Daily bump.
[official-gcc.git] / gcc / gimple-fold.c
blobc79f9b3f436ef448e0b0f2c738347155e811d6a9
1 /* Statement simplification on GIMPLE.
2 Copyright (C) 2010-2015 Free Software Foundation, Inc.
3 Split out from tree-ssa-ccp.c.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 3, or (at your option) any
10 later version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "predict.h"
26 #include "tree.h"
27 #include "gimple.h"
28 #include "rtl.h"
29 #include "ssa.h"
30 #include "alias.h"
31 #include "fold-const.h"
32 #include "flags.h"
33 #include "insn-config.h"
34 #include "expmed.h"
35 #include "dojump.h"
36 #include "explow.h"
37 #include "calls.h"
38 #include "emit-rtl.h"
39 #include "varasm.h"
40 #include "stmt.h"
41 #include "expr.h"
42 #include "stor-layout.h"
43 #include "dumpfile.h"
44 #include "dominance.h"
45 #include "internal-fn.h"
46 #include "gimple-fold.h"
47 #include "gimplify.h"
48 #include "gimple-iterator.h"
49 #include "tree-into-ssa.h"
50 #include "tree-dfa.h"
51 #include "tree-ssa.h"
52 #include "tree-ssa-propagate.h"
53 #include "target.h"
54 #include "cgraph.h"
55 #include "ipa-utils.h"
56 #include "gimple-pretty-print.h"
57 #include "tree-ssa-address.h"
58 #include "langhooks.h"
59 #include "gimplify-me.h"
60 #include "dbgcnt.h"
61 #include "builtins.h"
62 #include "output.h"
63 #include "tree-eh.h"
64 #include "gimple-match.h"
66 /* Return true when DECL can be referenced from current unit.
67 FROM_DECL (if non-null) specify constructor of variable DECL was taken from.
68 We can get declarations that are not possible to reference for various
69 reasons:
71 1) When analyzing C++ virtual tables.
72 C++ virtual tables do have known constructors even
73 when they are keyed to other compilation unit.
74 Those tables can contain pointers to methods and vars
75 in other units. Those methods have both STATIC and EXTERNAL
76 set.
77 2) In WHOPR mode devirtualization might lead to reference
78 to method that was partitioned elsehwere.
79 In this case we have static VAR_DECL or FUNCTION_DECL
80 that has no corresponding callgraph/varpool node
81 declaring the body.
82 3) COMDAT functions referred by external vtables that
83 we devirtualize only during final compilation stage.
84 At this time we already decided that we will not output
85 the function body and thus we can't reference the symbol
86 directly. */
88 static bool
89 can_refer_decl_in_current_unit_p (tree decl, tree from_decl)
91 varpool_node *vnode;
92 struct cgraph_node *node;
93 symtab_node *snode;
95 if (DECL_ABSTRACT_P (decl))
96 return false;
98 /* We are concerned only about static/external vars and functions. */
99 if ((!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
100 || (TREE_CODE (decl) != VAR_DECL && TREE_CODE (decl) != FUNCTION_DECL))
101 return true;
103 /* Static objects can be referred only if they was not optimized out yet. */
104 if (!TREE_PUBLIC (decl) && !DECL_EXTERNAL (decl))
106 /* Before we start optimizing unreachable code we can be sure all
107 static objects are defined. */
108 if (symtab->function_flags_ready)
109 return true;
110 snode = symtab_node::get (decl);
111 if (!snode || !snode->definition)
112 return false;
113 node = dyn_cast <cgraph_node *> (snode);
114 return !node || !node->global.inlined_to;
117 /* We will later output the initializer, so we can refer to it.
118 So we are concerned only when DECL comes from initializer of
119 external var or var that has been optimized out. */
120 if (!from_decl
121 || TREE_CODE (from_decl) != VAR_DECL
122 || (!DECL_EXTERNAL (from_decl)
123 && (vnode = varpool_node::get (from_decl)) != NULL
124 && vnode->definition)
125 || (flag_ltrans
126 && (vnode = varpool_node::get (from_decl)) != NULL
127 && vnode->in_other_partition))
128 return true;
129 /* We are folding reference from external vtable. The vtable may reffer
130 to a symbol keyed to other compilation unit. The other compilation
131 unit may be in separate DSO and the symbol may be hidden. */
132 if (DECL_VISIBILITY_SPECIFIED (decl)
133 && DECL_EXTERNAL (decl)
134 && DECL_VISIBILITY (decl) != VISIBILITY_DEFAULT
135 && (!(snode = symtab_node::get (decl)) || !snode->in_other_partition))
136 return false;
137 /* When function is public, we always can introduce new reference.
138 Exception are the COMDAT functions where introducing a direct
139 reference imply need to include function body in the curren tunit. */
140 if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl))
141 return true;
142 /* We have COMDAT. We are going to check if we still have definition
143 or if the definition is going to be output in other partition.
144 Bypass this when gimplifying; all needed functions will be produced.
146 As observed in PR20991 for already optimized out comdat virtual functions
147 it may be tempting to not necessarily give up because the copy will be
148 output elsewhere when corresponding vtable is output.
149 This is however not possible - ABI specify that COMDATs are output in
150 units where they are used and when the other unit was compiled with LTO
151 it is possible that vtable was kept public while the function itself
152 was privatized. */
153 if (!symtab->function_flags_ready)
154 return true;
156 snode = symtab_node::get (decl);
157 if (!snode
158 || ((!snode->definition || DECL_EXTERNAL (decl))
159 && (!snode->in_other_partition
160 || (!snode->forced_by_abi && !snode->force_output))))
161 return false;
162 node = dyn_cast <cgraph_node *> (snode);
163 return !node || !node->global.inlined_to;
166 /* CVAL is value taken from DECL_INITIAL of variable. Try to transform it into
167 acceptable form for is_gimple_min_invariant.
168 FROM_DECL (if non-NULL) specify variable whose constructor contains CVAL. */
170 tree
171 canonicalize_constructor_val (tree cval, tree from_decl)
173 tree orig_cval = cval;
174 STRIP_NOPS (cval);
175 if (TREE_CODE (cval) == POINTER_PLUS_EXPR
176 && TREE_CODE (TREE_OPERAND (cval, 1)) == INTEGER_CST)
178 tree ptr = TREE_OPERAND (cval, 0);
179 if (is_gimple_min_invariant (ptr))
180 cval = build1_loc (EXPR_LOCATION (cval),
181 ADDR_EXPR, TREE_TYPE (ptr),
182 fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (ptr)),
183 ptr,
184 fold_convert (ptr_type_node,
185 TREE_OPERAND (cval, 1))));
187 if (TREE_CODE (cval) == ADDR_EXPR)
189 tree base = NULL_TREE;
190 if (TREE_CODE (TREE_OPERAND (cval, 0)) == COMPOUND_LITERAL_EXPR)
192 base = COMPOUND_LITERAL_EXPR_DECL (TREE_OPERAND (cval, 0));
193 if (base)
194 TREE_OPERAND (cval, 0) = base;
196 else
197 base = get_base_address (TREE_OPERAND (cval, 0));
198 if (!base)
199 return NULL_TREE;
201 if ((TREE_CODE (base) == VAR_DECL
202 || TREE_CODE (base) == FUNCTION_DECL)
203 && !can_refer_decl_in_current_unit_p (base, from_decl))
204 return NULL_TREE;
205 if (TREE_CODE (base) == VAR_DECL)
206 TREE_ADDRESSABLE (base) = 1;
207 else if (TREE_CODE (base) == FUNCTION_DECL)
209 /* Make sure we create a cgraph node for functions we'll reference.
210 They can be non-existent if the reference comes from an entry
211 of an external vtable for example. */
212 cgraph_node::get_create (base);
214 /* Fixup types in global initializers. */
215 if (TREE_TYPE (TREE_TYPE (cval)) != TREE_TYPE (TREE_OPERAND (cval, 0)))
216 cval = build_fold_addr_expr (TREE_OPERAND (cval, 0));
218 if (!useless_type_conversion_p (TREE_TYPE (orig_cval), TREE_TYPE (cval)))
219 cval = fold_convert (TREE_TYPE (orig_cval), cval);
220 return cval;
222 if (TREE_OVERFLOW_P (cval))
223 return drop_tree_overflow (cval);
224 return orig_cval;
227 /* If SYM is a constant variable with known value, return the value.
228 NULL_TREE is returned otherwise. */
230 tree
231 get_symbol_constant_value (tree sym)
233 tree val = ctor_for_folding (sym);
234 if (val != error_mark_node)
236 if (val)
238 val = canonicalize_constructor_val (unshare_expr (val), sym);
239 if (val && is_gimple_min_invariant (val))
240 return val;
241 else
242 return NULL_TREE;
244 /* Variables declared 'const' without an initializer
245 have zero as the initializer if they may not be
246 overridden at link or run time. */
247 if (!val
248 && is_gimple_reg_type (TREE_TYPE (sym)))
249 return build_zero_cst (TREE_TYPE (sym));
252 return NULL_TREE;
257 /* Subroutine of fold_stmt. We perform several simplifications of the
258 memory reference tree EXPR and make sure to re-gimplify them properly
259 after propagation of constant addresses. IS_LHS is true if the
260 reference is supposed to be an lvalue. */
262 static tree
263 maybe_fold_reference (tree expr, bool is_lhs)
265 tree result;
267 if ((TREE_CODE (expr) == VIEW_CONVERT_EXPR
268 || TREE_CODE (expr) == REALPART_EXPR
269 || TREE_CODE (expr) == IMAGPART_EXPR)
270 && CONSTANT_CLASS_P (TREE_OPERAND (expr, 0)))
271 return fold_unary_loc (EXPR_LOCATION (expr),
272 TREE_CODE (expr),
273 TREE_TYPE (expr),
274 TREE_OPERAND (expr, 0));
275 else if (TREE_CODE (expr) == BIT_FIELD_REF
276 && CONSTANT_CLASS_P (TREE_OPERAND (expr, 0)))
277 return fold_ternary_loc (EXPR_LOCATION (expr),
278 TREE_CODE (expr),
279 TREE_TYPE (expr),
280 TREE_OPERAND (expr, 0),
281 TREE_OPERAND (expr, 1),
282 TREE_OPERAND (expr, 2));
284 if (!is_lhs
285 && (result = fold_const_aggregate_ref (expr))
286 && is_gimple_min_invariant (result))
287 return result;
289 return NULL_TREE;
293 /* Attempt to fold an assignment statement pointed-to by SI. Returns a
294 replacement rhs for the statement or NULL_TREE if no simplification
295 could be made. It is assumed that the operands have been previously
296 folded. */
298 static tree
299 fold_gimple_assign (gimple_stmt_iterator *si)
301 gimple stmt = gsi_stmt (*si);
302 enum tree_code subcode = gimple_assign_rhs_code (stmt);
303 location_t loc = gimple_location (stmt);
305 tree result = NULL_TREE;
307 switch (get_gimple_rhs_class (subcode))
309 case GIMPLE_SINGLE_RHS:
311 tree rhs = gimple_assign_rhs1 (stmt);
313 if (TREE_CLOBBER_P (rhs))
314 return NULL_TREE;
316 if (REFERENCE_CLASS_P (rhs))
317 return maybe_fold_reference (rhs, false);
319 else if (TREE_CODE (rhs) == OBJ_TYPE_REF)
321 tree val = OBJ_TYPE_REF_EXPR (rhs);
322 if (is_gimple_min_invariant (val))
323 return val;
324 else if (flag_devirtualize && virtual_method_call_p (rhs))
326 bool final;
327 vec <cgraph_node *>targets
328 = possible_polymorphic_call_targets (rhs, stmt, &final);
329 if (final && targets.length () <= 1 && dbg_cnt (devirt))
331 if (dump_enabled_p ())
333 location_t loc = gimple_location_safe (stmt);
334 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, loc,
335 "resolving virtual function address "
336 "reference to function %s\n",
337 targets.length () == 1
338 ? targets[0]->name ()
339 : "NULL");
341 if (targets.length () == 1)
343 val = fold_convert (TREE_TYPE (val),
344 build_fold_addr_expr_loc
345 (loc, targets[0]->decl));
346 STRIP_USELESS_TYPE_CONVERSION (val);
348 else
349 /* We can not use __builtin_unreachable here because it
350 can not have address taken. */
351 val = build_int_cst (TREE_TYPE (val), 0);
352 return val;
357 else if (TREE_CODE (rhs) == ADDR_EXPR)
359 tree ref = TREE_OPERAND (rhs, 0);
360 tree tem = maybe_fold_reference (ref, true);
361 if (tem
362 && TREE_CODE (tem) == MEM_REF
363 && integer_zerop (TREE_OPERAND (tem, 1)))
364 result = fold_convert (TREE_TYPE (rhs), TREE_OPERAND (tem, 0));
365 else if (tem)
366 result = fold_convert (TREE_TYPE (rhs),
367 build_fold_addr_expr_loc (loc, tem));
368 else if (TREE_CODE (ref) == MEM_REF
369 && integer_zerop (TREE_OPERAND (ref, 1)))
370 result = fold_convert (TREE_TYPE (rhs), TREE_OPERAND (ref, 0));
373 else if (TREE_CODE (rhs) == CONSTRUCTOR
374 && TREE_CODE (TREE_TYPE (rhs)) == VECTOR_TYPE
375 && (CONSTRUCTOR_NELTS (rhs)
376 == TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs))))
378 /* Fold a constant vector CONSTRUCTOR to VECTOR_CST. */
379 unsigned i;
380 tree val;
382 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), i, val)
383 if (TREE_CODE (val) != INTEGER_CST
384 && TREE_CODE (val) != REAL_CST
385 && TREE_CODE (val) != FIXED_CST)
386 return NULL_TREE;
388 return build_vector_from_ctor (TREE_TYPE (rhs),
389 CONSTRUCTOR_ELTS (rhs));
392 else if (DECL_P (rhs))
393 return get_symbol_constant_value (rhs);
395 /* If we couldn't fold the RHS, hand over to the generic
396 fold routines. */
397 if (result == NULL_TREE)
398 result = fold (rhs);
400 /* Strip away useless type conversions. Both the NON_LVALUE_EXPR
401 that may have been added by fold, and "useless" type
402 conversions that might now be apparent due to propagation. */
403 STRIP_USELESS_TYPE_CONVERSION (result);
405 if (result != rhs && valid_gimple_rhs_p (result))
406 return result;
408 return NULL_TREE;
410 break;
412 case GIMPLE_UNARY_RHS:
413 break;
415 case GIMPLE_BINARY_RHS:
416 break;
418 case GIMPLE_TERNARY_RHS:
419 result = fold_ternary_loc (loc, subcode,
420 TREE_TYPE (gimple_assign_lhs (stmt)),
421 gimple_assign_rhs1 (stmt),
422 gimple_assign_rhs2 (stmt),
423 gimple_assign_rhs3 (stmt));
425 if (result)
427 STRIP_USELESS_TYPE_CONVERSION (result);
428 if (valid_gimple_rhs_p (result))
429 return result;
431 break;
433 case GIMPLE_INVALID_RHS:
434 gcc_unreachable ();
437 return NULL_TREE;
441 /* Replace a statement at *SI_P with a sequence of statements in STMTS,
442 adjusting the replacement stmts location and virtual operands.
443 If the statement has a lhs the last stmt in the sequence is expected
444 to assign to that lhs. */
446 static void
447 gsi_replace_with_seq_vops (gimple_stmt_iterator *si_p, gimple_seq stmts)
449 gimple stmt = gsi_stmt (*si_p);
451 if (gimple_has_location (stmt))
452 annotate_all_with_location (stmts, gimple_location (stmt));
454 /* First iterate over the replacement statements backward, assigning
455 virtual operands to their defining statements. */
456 gimple laststore = NULL;
457 for (gimple_stmt_iterator i = gsi_last (stmts);
458 !gsi_end_p (i); gsi_prev (&i))
460 gimple new_stmt = gsi_stmt (i);
461 if ((gimple_assign_single_p (new_stmt)
462 && !is_gimple_reg (gimple_assign_lhs (new_stmt)))
463 || (is_gimple_call (new_stmt)
464 && (gimple_call_flags (new_stmt)
465 & (ECF_NOVOPS | ECF_PURE | ECF_CONST | ECF_NORETURN)) == 0))
467 tree vdef;
468 if (!laststore)
469 vdef = gimple_vdef (stmt);
470 else
471 vdef = make_ssa_name (gimple_vop (cfun), new_stmt);
472 gimple_set_vdef (new_stmt, vdef);
473 if (vdef && TREE_CODE (vdef) == SSA_NAME)
474 SSA_NAME_DEF_STMT (vdef) = new_stmt;
475 laststore = new_stmt;
479 /* Second iterate over the statements forward, assigning virtual
480 operands to their uses. */
481 tree reaching_vuse = gimple_vuse (stmt);
482 for (gimple_stmt_iterator i = gsi_start (stmts);
483 !gsi_end_p (i); gsi_next (&i))
485 gimple new_stmt = gsi_stmt (i);
486 /* If the new statement possibly has a VUSE, update it with exact SSA
487 name we know will reach this one. */
488 if (gimple_has_mem_ops (new_stmt))
489 gimple_set_vuse (new_stmt, reaching_vuse);
490 gimple_set_modified (new_stmt, true);
491 if (gimple_vdef (new_stmt))
492 reaching_vuse = gimple_vdef (new_stmt);
495 /* If the new sequence does not do a store release the virtual
496 definition of the original statement. */
497 if (reaching_vuse
498 && reaching_vuse == gimple_vuse (stmt))
500 tree vdef = gimple_vdef (stmt);
501 if (vdef
502 && TREE_CODE (vdef) == SSA_NAME)
504 unlink_stmt_vdef (stmt);
505 release_ssa_name (vdef);
509 /* Finally replace the original statement with the sequence. */
510 gsi_replace_with_seq (si_p, stmts, false);
513 /* Convert EXPR into a GIMPLE value suitable for substitution on the
514 RHS of an assignment. Insert the necessary statements before
515 iterator *SI_P. The statement at *SI_P, which must be a GIMPLE_CALL
516 is replaced. If the call is expected to produces a result, then it
517 is replaced by an assignment of the new RHS to the result variable.
518 If the result is to be ignored, then the call is replaced by a
519 GIMPLE_NOP. A proper VDEF chain is retained by making the first
520 VUSE and the last VDEF of the whole sequence be the same as the replaced
521 statement and using new SSA names for stores in between. */
523 void
524 gimplify_and_update_call_from_tree (gimple_stmt_iterator *si_p, tree expr)
526 tree lhs;
527 gimple stmt, new_stmt;
528 gimple_stmt_iterator i;
529 gimple_seq stmts = NULL;
531 stmt = gsi_stmt (*si_p);
533 gcc_assert (is_gimple_call (stmt));
535 push_gimplify_context (gimple_in_ssa_p (cfun));
537 lhs = gimple_call_lhs (stmt);
538 if (lhs == NULL_TREE)
540 gimplify_and_add (expr, &stmts);
541 /* We can end up with folding a memcpy of an empty class assignment
542 which gets optimized away by C++ gimplification. */
543 if (gimple_seq_empty_p (stmts))
545 pop_gimplify_context (NULL);
546 if (gimple_in_ssa_p (cfun))
548 unlink_stmt_vdef (stmt);
549 release_defs (stmt);
551 gsi_replace (si_p, gimple_build_nop (), true);
552 return;
555 else
557 tree tmp = get_initialized_tmp_var (expr, &stmts, NULL);
558 new_stmt = gimple_build_assign (lhs, tmp);
559 i = gsi_last (stmts);
560 gsi_insert_after_without_update (&i, new_stmt,
561 GSI_CONTINUE_LINKING);
564 pop_gimplify_context (NULL);
566 gsi_replace_with_seq_vops (si_p, stmts);
570 /* Replace the call at *GSI with the gimple value VAL. */
572 static void
573 replace_call_with_value (gimple_stmt_iterator *gsi, tree val)
575 gimple stmt = gsi_stmt (*gsi);
576 tree lhs = gimple_call_lhs (stmt);
577 gimple repl;
578 if (lhs)
580 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (val)))
581 val = fold_convert (TREE_TYPE (lhs), val);
582 repl = gimple_build_assign (lhs, val);
584 else
585 repl = gimple_build_nop ();
586 tree vdef = gimple_vdef (stmt);
587 if (vdef && TREE_CODE (vdef) == SSA_NAME)
589 unlink_stmt_vdef (stmt);
590 release_ssa_name (vdef);
592 gsi_replace (gsi, repl, true);
595 /* Replace the call at *GSI with the new call REPL and fold that
596 again. */
598 static void
599 replace_call_with_call_and_fold (gimple_stmt_iterator *gsi, gimple repl)
601 gimple stmt = gsi_stmt (*gsi);
602 gimple_call_set_lhs (repl, gimple_call_lhs (stmt));
603 gimple_set_location (repl, gimple_location (stmt));
604 if (gimple_vdef (stmt)
605 && TREE_CODE (gimple_vdef (stmt)) == SSA_NAME)
607 gimple_set_vdef (repl, gimple_vdef (stmt));
608 gimple_set_vuse (repl, gimple_vuse (stmt));
609 SSA_NAME_DEF_STMT (gimple_vdef (repl)) = repl;
611 gsi_replace (gsi, repl, true);
612 fold_stmt (gsi);
615 /* Return true if VAR is a VAR_DECL or a component thereof. */
617 static bool
618 var_decl_component_p (tree var)
620 tree inner = var;
621 while (handled_component_p (inner))
622 inner = TREE_OPERAND (inner, 0);
623 return SSA_VAR_P (inner);
626 /* Fold function call to builtin mem{{,p}cpy,move}. Return
627 false if no simplification can be made.
628 If ENDP is 0, return DEST (like memcpy).
629 If ENDP is 1, return DEST+LEN (like mempcpy).
630 If ENDP is 2, return DEST+LEN-1 (like stpcpy).
631 If ENDP is 3, return DEST, additionally *SRC and *DEST may overlap
632 (memmove). */
634 static bool
635 gimple_fold_builtin_memory_op (gimple_stmt_iterator *gsi,
636 tree dest, tree src, int endp)
638 gimple stmt = gsi_stmt (*gsi);
639 tree lhs = gimple_call_lhs (stmt);
640 tree len = gimple_call_arg (stmt, 2);
641 tree destvar, srcvar;
642 location_t loc = gimple_location (stmt);
644 /* If the LEN parameter is zero, return DEST. */
645 if (integer_zerop (len))
647 gimple repl;
648 if (gimple_call_lhs (stmt))
649 repl = gimple_build_assign (gimple_call_lhs (stmt), dest);
650 else
651 repl = gimple_build_nop ();
652 tree vdef = gimple_vdef (stmt);
653 if (vdef && TREE_CODE (vdef) == SSA_NAME)
655 unlink_stmt_vdef (stmt);
656 release_ssa_name (vdef);
658 gsi_replace (gsi, repl, true);
659 return true;
662 /* If SRC and DEST are the same (and not volatile), return
663 DEST{,+LEN,+LEN-1}. */
664 if (operand_equal_p (src, dest, 0))
666 unlink_stmt_vdef (stmt);
667 if (gimple_vdef (stmt) && TREE_CODE (gimple_vdef (stmt)) == SSA_NAME)
668 release_ssa_name (gimple_vdef (stmt));
669 if (!lhs)
671 gsi_replace (gsi, gimple_build_nop (), true);
672 return true;
674 goto done;
676 else
678 tree srctype, desttype;
679 unsigned int src_align, dest_align;
680 tree off0;
682 /* Build accesses at offset zero with a ref-all character type. */
683 off0 = build_int_cst (build_pointer_type_for_mode (char_type_node,
684 ptr_mode, true), 0);
686 /* If we can perform the copy efficiently with first doing all loads
687 and then all stores inline it that way. Currently efficiently
688 means that we can load all the memory into a single integer
689 register which is what MOVE_MAX gives us. */
690 src_align = get_pointer_alignment (src);
691 dest_align = get_pointer_alignment (dest);
692 if (tree_fits_uhwi_p (len)
693 && compare_tree_int (len, MOVE_MAX) <= 0
694 /* ??? Don't transform copies from strings with known length this
695 confuses the tree-ssa-strlen.c. This doesn't handle
696 the case in gcc.dg/strlenopt-8.c which is XFAILed for that
697 reason. */
698 && !c_strlen (src, 2))
700 unsigned ilen = tree_to_uhwi (len);
701 if (exact_log2 (ilen) != -1)
703 tree type = lang_hooks.types.type_for_size (ilen * 8, 1);
704 if (type
705 && TYPE_MODE (type) != BLKmode
706 && (GET_MODE_SIZE (TYPE_MODE (type)) * BITS_PER_UNIT
707 == ilen * 8)
708 /* If the destination pointer is not aligned we must be able
709 to emit an unaligned store. */
710 && (dest_align >= GET_MODE_ALIGNMENT (TYPE_MODE (type))
711 || !SLOW_UNALIGNED_ACCESS (TYPE_MODE (type), dest_align)))
713 tree srctype = type;
714 tree desttype = type;
715 if (src_align < GET_MODE_ALIGNMENT (TYPE_MODE (type)))
716 srctype = build_aligned_type (type, src_align);
717 tree srcmem = fold_build2 (MEM_REF, srctype, src, off0);
718 tree tem = fold_const_aggregate_ref (srcmem);
719 if (tem)
720 srcmem = tem;
721 else if (src_align < GET_MODE_ALIGNMENT (TYPE_MODE (type))
722 && SLOW_UNALIGNED_ACCESS (TYPE_MODE (type),
723 src_align))
724 srcmem = NULL_TREE;
725 if (srcmem)
727 gimple new_stmt;
728 if (is_gimple_reg_type (TREE_TYPE (srcmem)))
730 new_stmt = gimple_build_assign (NULL_TREE, srcmem);
731 if (gimple_in_ssa_p (cfun))
732 srcmem = make_ssa_name (TREE_TYPE (srcmem),
733 new_stmt);
734 else
735 srcmem = create_tmp_reg (TREE_TYPE (srcmem));
736 gimple_assign_set_lhs (new_stmt, srcmem);
737 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
738 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
740 if (dest_align < GET_MODE_ALIGNMENT (TYPE_MODE (type)))
741 desttype = build_aligned_type (type, dest_align);
742 new_stmt
743 = gimple_build_assign (fold_build2 (MEM_REF, desttype,
744 dest, off0),
745 srcmem);
746 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
747 gimple_set_vdef (new_stmt, gimple_vdef (stmt));
748 if (gimple_vdef (new_stmt)
749 && TREE_CODE (gimple_vdef (new_stmt)) == SSA_NAME)
750 SSA_NAME_DEF_STMT (gimple_vdef (new_stmt)) = new_stmt;
751 if (!lhs)
753 gsi_replace (gsi, new_stmt, true);
754 return true;
756 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
757 goto done;
763 if (endp == 3)
765 /* Both DEST and SRC must be pointer types.
766 ??? This is what old code did. Is the testing for pointer types
767 really mandatory?
769 If either SRC is readonly or length is 1, we can use memcpy. */
770 if (!dest_align || !src_align)
771 return false;
772 if (readonly_data_expr (src)
773 || (tree_fits_uhwi_p (len)
774 && (MIN (src_align, dest_align) / BITS_PER_UNIT
775 >= tree_to_uhwi (len))))
777 tree fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
778 if (!fn)
779 return false;
780 gimple_call_set_fndecl (stmt, fn);
781 gimple_call_set_arg (stmt, 0, dest);
782 gimple_call_set_arg (stmt, 1, src);
783 fold_stmt (gsi);
784 return true;
787 /* If *src and *dest can't overlap, optimize into memcpy as well. */
788 if (TREE_CODE (src) == ADDR_EXPR
789 && TREE_CODE (dest) == ADDR_EXPR)
791 tree src_base, dest_base, fn;
792 HOST_WIDE_INT src_offset = 0, dest_offset = 0;
793 HOST_WIDE_INT size = -1;
794 HOST_WIDE_INT maxsize = -1;
796 srcvar = TREE_OPERAND (src, 0);
797 src_base = get_ref_base_and_extent (srcvar, &src_offset,
798 &size, &maxsize);
799 destvar = TREE_OPERAND (dest, 0);
800 dest_base = get_ref_base_and_extent (destvar, &dest_offset,
801 &size, &maxsize);
802 if (tree_fits_uhwi_p (len))
803 maxsize = tree_to_uhwi (len);
804 else
805 maxsize = -1;
806 src_offset /= BITS_PER_UNIT;
807 dest_offset /= BITS_PER_UNIT;
808 if (SSA_VAR_P (src_base)
809 && SSA_VAR_P (dest_base))
811 if (operand_equal_p (src_base, dest_base, 0)
812 && ranges_overlap_p (src_offset, maxsize,
813 dest_offset, maxsize))
814 return false;
816 else if (TREE_CODE (src_base) == MEM_REF
817 && TREE_CODE (dest_base) == MEM_REF)
819 if (! operand_equal_p (TREE_OPERAND (src_base, 0),
820 TREE_OPERAND (dest_base, 0), 0))
821 return false;
822 offset_int off = mem_ref_offset (src_base) + src_offset;
823 if (!wi::fits_shwi_p (off))
824 return false;
825 src_offset = off.to_shwi ();
827 off = mem_ref_offset (dest_base) + dest_offset;
828 if (!wi::fits_shwi_p (off))
829 return false;
830 dest_offset = off.to_shwi ();
831 if (ranges_overlap_p (src_offset, maxsize,
832 dest_offset, maxsize))
833 return false;
835 else
836 return false;
838 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
839 if (!fn)
840 return false;
841 gimple_call_set_fndecl (stmt, fn);
842 gimple_call_set_arg (stmt, 0, dest);
843 gimple_call_set_arg (stmt, 1, src);
844 fold_stmt (gsi);
845 return true;
848 /* If the destination and source do not alias optimize into
849 memcpy as well. */
850 if ((is_gimple_min_invariant (dest)
851 || TREE_CODE (dest) == SSA_NAME)
852 && (is_gimple_min_invariant (src)
853 || TREE_CODE (src) == SSA_NAME))
855 ao_ref destr, srcr;
856 ao_ref_init_from_ptr_and_size (&destr, dest, len);
857 ao_ref_init_from_ptr_and_size (&srcr, src, len);
858 if (!refs_may_alias_p_1 (&destr, &srcr, false))
860 tree fn;
861 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
862 if (!fn)
863 return false;
864 gimple_call_set_fndecl (stmt, fn);
865 gimple_call_set_arg (stmt, 0, dest);
866 gimple_call_set_arg (stmt, 1, src);
867 fold_stmt (gsi);
868 return true;
872 return false;
875 if (!tree_fits_shwi_p (len))
876 return false;
877 /* FIXME:
878 This logic lose for arguments like (type *)malloc (sizeof (type)),
879 since we strip the casts of up to VOID return value from malloc.
880 Perhaps we ought to inherit type from non-VOID argument here? */
881 STRIP_NOPS (src);
882 STRIP_NOPS (dest);
883 if (!POINTER_TYPE_P (TREE_TYPE (src))
884 || !POINTER_TYPE_P (TREE_TYPE (dest)))
885 return false;
886 /* In the following try to find a type that is most natural to be
887 used for the memcpy source and destination and that allows
888 the most optimization when memcpy is turned into a plain assignment
889 using that type. In theory we could always use a char[len] type
890 but that only gains us that the destination and source possibly
891 no longer will have their address taken. */
892 /* As we fold (void *)(p + CST) to (void *)p + CST undo this here. */
893 if (TREE_CODE (src) == POINTER_PLUS_EXPR)
895 tree tem = TREE_OPERAND (src, 0);
896 STRIP_NOPS (tem);
897 if (tem != TREE_OPERAND (src, 0))
898 src = build1 (NOP_EXPR, TREE_TYPE (tem), src);
900 if (TREE_CODE (dest) == POINTER_PLUS_EXPR)
902 tree tem = TREE_OPERAND (dest, 0);
903 STRIP_NOPS (tem);
904 if (tem != TREE_OPERAND (dest, 0))
905 dest = build1 (NOP_EXPR, TREE_TYPE (tem), dest);
907 srctype = TREE_TYPE (TREE_TYPE (src));
908 if (TREE_CODE (srctype) == ARRAY_TYPE
909 && !tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
911 srctype = TREE_TYPE (srctype);
912 STRIP_NOPS (src);
913 src = build1 (NOP_EXPR, build_pointer_type (srctype), src);
915 desttype = TREE_TYPE (TREE_TYPE (dest));
916 if (TREE_CODE (desttype) == ARRAY_TYPE
917 && !tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
919 desttype = TREE_TYPE (desttype);
920 STRIP_NOPS (dest);
921 dest = build1 (NOP_EXPR, build_pointer_type (desttype), dest);
923 if (TREE_ADDRESSABLE (srctype)
924 || TREE_ADDRESSABLE (desttype))
925 return false;
927 /* Make sure we are not copying using a floating-point mode or
928 a type whose size possibly does not match its precision. */
929 if (FLOAT_MODE_P (TYPE_MODE (desttype))
930 || TREE_CODE (desttype) == BOOLEAN_TYPE
931 || TREE_CODE (desttype) == ENUMERAL_TYPE)
932 desttype = bitwise_type_for_mode (TYPE_MODE (desttype));
933 if (FLOAT_MODE_P (TYPE_MODE (srctype))
934 || TREE_CODE (srctype) == BOOLEAN_TYPE
935 || TREE_CODE (srctype) == ENUMERAL_TYPE)
936 srctype = bitwise_type_for_mode (TYPE_MODE (srctype));
937 if (!srctype)
938 srctype = desttype;
939 if (!desttype)
940 desttype = srctype;
941 if (!srctype)
942 return false;
944 src_align = get_pointer_alignment (src);
945 dest_align = get_pointer_alignment (dest);
946 if (dest_align < TYPE_ALIGN (desttype)
947 || src_align < TYPE_ALIGN (srctype))
948 return false;
950 destvar = dest;
951 STRIP_NOPS (destvar);
952 if (TREE_CODE (destvar) == ADDR_EXPR
953 && var_decl_component_p (TREE_OPERAND (destvar, 0))
954 && tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
955 destvar = fold_build2 (MEM_REF, desttype, destvar, off0);
956 else
957 destvar = NULL_TREE;
959 srcvar = src;
960 STRIP_NOPS (srcvar);
961 if (TREE_CODE (srcvar) == ADDR_EXPR
962 && var_decl_component_p (TREE_OPERAND (srcvar, 0))
963 && tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
965 if (!destvar
966 || src_align >= TYPE_ALIGN (desttype))
967 srcvar = fold_build2 (MEM_REF, destvar ? desttype : srctype,
968 srcvar, off0);
969 else if (!STRICT_ALIGNMENT)
971 srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
972 src_align);
973 srcvar = fold_build2 (MEM_REF, srctype, srcvar, off0);
975 else
976 srcvar = NULL_TREE;
978 else
979 srcvar = NULL_TREE;
981 if (srcvar == NULL_TREE && destvar == NULL_TREE)
982 return false;
984 if (srcvar == NULL_TREE)
986 STRIP_NOPS (src);
987 if (src_align >= TYPE_ALIGN (desttype))
988 srcvar = fold_build2 (MEM_REF, desttype, src, off0);
989 else
991 if (STRICT_ALIGNMENT)
992 return false;
993 srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
994 src_align);
995 srcvar = fold_build2 (MEM_REF, srctype, src, off0);
998 else if (destvar == NULL_TREE)
1000 STRIP_NOPS (dest);
1001 if (dest_align >= TYPE_ALIGN (srctype))
1002 destvar = fold_build2 (MEM_REF, srctype, dest, off0);
1003 else
1005 if (STRICT_ALIGNMENT)
1006 return false;
1007 desttype = build_aligned_type (TYPE_MAIN_VARIANT (srctype),
1008 dest_align);
1009 destvar = fold_build2 (MEM_REF, desttype, dest, off0);
1013 gimple new_stmt;
1014 if (is_gimple_reg_type (TREE_TYPE (srcvar)))
1016 new_stmt = gimple_build_assign (NULL_TREE, srcvar);
1017 if (gimple_in_ssa_p (cfun))
1018 srcvar = make_ssa_name (TREE_TYPE (srcvar), new_stmt);
1019 else
1020 srcvar = create_tmp_reg (TREE_TYPE (srcvar));
1021 gimple_assign_set_lhs (new_stmt, srcvar);
1022 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
1023 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1025 new_stmt = gimple_build_assign (destvar, srcvar);
1026 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
1027 gimple_set_vdef (new_stmt, gimple_vdef (stmt));
1028 if (gimple_vdef (new_stmt)
1029 && TREE_CODE (gimple_vdef (new_stmt)) == SSA_NAME)
1030 SSA_NAME_DEF_STMT (gimple_vdef (new_stmt)) = new_stmt;
1031 if (!lhs)
1033 gsi_replace (gsi, new_stmt, true);
1034 return true;
1036 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1039 done:
1040 if (endp == 0 || endp == 3)
1041 len = NULL_TREE;
1042 else if (endp == 2)
1043 len = fold_build2_loc (loc, MINUS_EXPR, TREE_TYPE (len), len,
1044 ssize_int (1));
1045 if (endp == 2 || endp == 1)
1046 dest = fold_build_pointer_plus_loc (loc, dest, len);
1048 dest = force_gimple_operand_gsi (gsi, dest, false, NULL_TREE, true,
1049 GSI_SAME_STMT);
1050 gimple repl = gimple_build_assign (lhs, dest);
1051 gsi_replace (gsi, repl, true);
1052 return true;
1055 /* Fold function call to builtin memset or bzero at *GSI setting the
1056 memory of size LEN to VAL. Return whether a simplification was made. */
1058 static bool
1059 gimple_fold_builtin_memset (gimple_stmt_iterator *gsi, tree c, tree len)
1061 gimple stmt = gsi_stmt (*gsi);
1062 tree etype;
1063 unsigned HOST_WIDE_INT length, cval;
1065 /* If the LEN parameter is zero, return DEST. */
1066 if (integer_zerop (len))
1068 replace_call_with_value (gsi, gimple_call_arg (stmt, 0));
1069 return true;
1072 if (! tree_fits_uhwi_p (len))
1073 return false;
1075 if (TREE_CODE (c) != INTEGER_CST)
1076 return false;
1078 tree dest = gimple_call_arg (stmt, 0);
1079 tree var = dest;
1080 if (TREE_CODE (var) != ADDR_EXPR)
1081 return false;
1083 var = TREE_OPERAND (var, 0);
1084 if (TREE_THIS_VOLATILE (var))
1085 return false;
1087 etype = TREE_TYPE (var);
1088 if (TREE_CODE (etype) == ARRAY_TYPE)
1089 etype = TREE_TYPE (etype);
1091 if (!INTEGRAL_TYPE_P (etype)
1092 && !POINTER_TYPE_P (etype))
1093 return NULL_TREE;
1095 if (! var_decl_component_p (var))
1096 return NULL_TREE;
1098 length = tree_to_uhwi (len);
1099 if (GET_MODE_SIZE (TYPE_MODE (etype)) != length
1100 || get_pointer_alignment (dest) / BITS_PER_UNIT < length)
1101 return NULL_TREE;
1103 if (length > HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT)
1104 return NULL_TREE;
1106 if (integer_zerop (c))
1107 cval = 0;
1108 else
1110 if (CHAR_BIT != 8 || BITS_PER_UNIT != 8 || HOST_BITS_PER_WIDE_INT > 64)
1111 return NULL_TREE;
1113 cval = TREE_INT_CST_LOW (c);
1114 cval &= 0xff;
1115 cval |= cval << 8;
1116 cval |= cval << 16;
1117 cval |= (cval << 31) << 1;
1120 var = fold_build2 (MEM_REF, etype, dest, build_int_cst (ptr_type_node, 0));
1121 gimple store = gimple_build_assign (var, build_int_cst_type (etype, cval));
1122 gimple_set_vuse (store, gimple_vuse (stmt));
1123 tree vdef = gimple_vdef (stmt);
1124 if (vdef && TREE_CODE (vdef) == SSA_NAME)
1126 gimple_set_vdef (store, gimple_vdef (stmt));
1127 SSA_NAME_DEF_STMT (gimple_vdef (stmt)) = store;
1129 gsi_insert_before (gsi, store, GSI_SAME_STMT);
1130 if (gimple_call_lhs (stmt))
1132 gimple asgn = gimple_build_assign (gimple_call_lhs (stmt), dest);
1133 gsi_replace (gsi, asgn, true);
1135 else
1137 gimple_stmt_iterator gsi2 = *gsi;
1138 gsi_prev (gsi);
1139 gsi_remove (&gsi2, true);
1142 return true;
1146 /* Return the string length, maximum string length or maximum value of
1147 ARG in LENGTH.
1148 If ARG is an SSA name variable, follow its use-def chains. If LENGTH
1149 is not NULL and, for TYPE == 0, its value is not equal to the length
1150 we determine or if we are unable to determine the length or value,
1151 return false. VISITED is a bitmap of visited variables.
1152 TYPE is 0 if string length should be returned, 1 for maximum string
1153 length and 2 for maximum value ARG can have. */
1155 static bool
1156 get_maxval_strlen (tree arg, tree *length, bitmap *visited, int type)
1158 tree var, val;
1159 gimple def_stmt;
1161 if (TREE_CODE (arg) != SSA_NAME)
1163 /* We can end up with &(*iftmp_1)[0] here as well, so handle it. */
1164 if (TREE_CODE (arg) == ADDR_EXPR
1165 && TREE_CODE (TREE_OPERAND (arg, 0)) == ARRAY_REF
1166 && integer_zerop (TREE_OPERAND (TREE_OPERAND (arg, 0), 1)))
1168 tree aop0 = TREE_OPERAND (TREE_OPERAND (arg, 0), 0);
1169 if (TREE_CODE (aop0) == INDIRECT_REF
1170 && TREE_CODE (TREE_OPERAND (aop0, 0)) == SSA_NAME)
1171 return get_maxval_strlen (TREE_OPERAND (aop0, 0),
1172 length, visited, type);
1175 if (type == 2)
1177 val = arg;
1178 if (TREE_CODE (val) != INTEGER_CST
1179 || tree_int_cst_sgn (val) < 0)
1180 return false;
1182 else
1183 val = c_strlen (arg, 1);
1184 if (!val)
1185 return false;
1187 if (*length)
1189 if (type > 0)
1191 if (TREE_CODE (*length) != INTEGER_CST
1192 || TREE_CODE (val) != INTEGER_CST)
1193 return false;
1195 if (tree_int_cst_lt (*length, val))
1196 *length = val;
1197 return true;
1199 else if (simple_cst_equal (val, *length) != 1)
1200 return false;
1203 *length = val;
1204 return true;
1207 /* If ARG is registered for SSA update we cannot look at its defining
1208 statement. */
1209 if (name_registered_for_update_p (arg))
1210 return false;
1212 /* If we were already here, break the infinite cycle. */
1213 if (!*visited)
1214 *visited = BITMAP_ALLOC (NULL);
1215 if (!bitmap_set_bit (*visited, SSA_NAME_VERSION (arg)))
1216 return true;
1218 var = arg;
1219 def_stmt = SSA_NAME_DEF_STMT (var);
1221 switch (gimple_code (def_stmt))
1223 case GIMPLE_ASSIGN:
1224 /* The RHS of the statement defining VAR must either have a
1225 constant length or come from another SSA_NAME with a constant
1226 length. */
1227 if (gimple_assign_single_p (def_stmt)
1228 || gimple_assign_unary_nop_p (def_stmt))
1230 tree rhs = gimple_assign_rhs1 (def_stmt);
1231 return get_maxval_strlen (rhs, length, visited, type);
1233 else if (gimple_assign_rhs_code (def_stmt) == COND_EXPR)
1235 tree op2 = gimple_assign_rhs2 (def_stmt);
1236 tree op3 = gimple_assign_rhs3 (def_stmt);
1237 return get_maxval_strlen (op2, length, visited, type)
1238 && get_maxval_strlen (op3, length, visited, type);
1240 return false;
1242 case GIMPLE_PHI:
1244 /* All the arguments of the PHI node must have the same constant
1245 length. */
1246 unsigned i;
1248 for (i = 0; i < gimple_phi_num_args (def_stmt); i++)
1250 tree arg = gimple_phi_arg (def_stmt, i)->def;
1252 /* If this PHI has itself as an argument, we cannot
1253 determine the string length of this argument. However,
1254 if we can find a constant string length for the other
1255 PHI args then we can still be sure that this is a
1256 constant string length. So be optimistic and just
1257 continue with the next argument. */
1258 if (arg == gimple_phi_result (def_stmt))
1259 continue;
1261 if (!get_maxval_strlen (arg, length, visited, type))
1262 return false;
1265 return true;
1267 default:
1268 return false;
1272 tree
1273 get_maxval_strlen (tree arg, int type)
1275 bitmap visited = NULL;
1276 tree len = NULL_TREE;
1277 if (!get_maxval_strlen (arg, &len, &visited, type))
1278 len = NULL_TREE;
1279 if (visited)
1280 BITMAP_FREE (visited);
1282 return len;
1286 /* Fold function call to builtin strcpy with arguments DEST and SRC.
1287 If LEN is not NULL, it represents the length of the string to be
1288 copied. Return NULL_TREE if no simplification can be made. */
1290 static bool
1291 gimple_fold_builtin_strcpy (gimple_stmt_iterator *gsi,
1292 tree dest, tree src)
1294 location_t loc = gimple_location (gsi_stmt (*gsi));
1295 tree fn;
1297 /* If SRC and DEST are the same (and not volatile), return DEST. */
1298 if (operand_equal_p (src, dest, 0))
1300 replace_call_with_value (gsi, dest);
1301 return true;
1304 if (optimize_function_for_size_p (cfun))
1305 return false;
1307 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1308 if (!fn)
1309 return false;
1311 tree len = get_maxval_strlen (src, 0);
1312 if (!len)
1313 return false;
1315 len = fold_convert_loc (loc, size_type_node, len);
1316 len = size_binop_loc (loc, PLUS_EXPR, len, build_int_cst (size_type_node, 1));
1317 len = force_gimple_operand_gsi (gsi, len, true,
1318 NULL_TREE, true, GSI_SAME_STMT);
1319 gimple repl = gimple_build_call (fn, 3, dest, src, len);
1320 replace_call_with_call_and_fold (gsi, repl);
1321 return true;
1324 /* Fold function call to builtin strncpy with arguments DEST, SRC, and LEN.
1325 If SLEN is not NULL, it represents the length of the source string.
1326 Return NULL_TREE if no simplification can be made. */
1328 static bool
1329 gimple_fold_builtin_strncpy (gimple_stmt_iterator *gsi,
1330 tree dest, tree src, tree len)
1332 location_t loc = gimple_location (gsi_stmt (*gsi));
1333 tree fn;
1335 /* If the LEN parameter is zero, return DEST. */
1336 if (integer_zerop (len))
1338 replace_call_with_value (gsi, dest);
1339 return true;
1342 /* We can't compare slen with len as constants below if len is not a
1343 constant. */
1344 if (TREE_CODE (len) != INTEGER_CST)
1345 return false;
1347 /* Now, we must be passed a constant src ptr parameter. */
1348 tree slen = get_maxval_strlen (src, 0);
1349 if (!slen || TREE_CODE (slen) != INTEGER_CST)
1350 return false;
1352 slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
1354 /* We do not support simplification of this case, though we do
1355 support it when expanding trees into RTL. */
1356 /* FIXME: generate a call to __builtin_memset. */
1357 if (tree_int_cst_lt (slen, len))
1358 return false;
1360 /* OK transform into builtin memcpy. */
1361 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1362 if (!fn)
1363 return false;
1365 len = fold_convert_loc (loc, size_type_node, len);
1366 len = force_gimple_operand_gsi (gsi, len, true,
1367 NULL_TREE, true, GSI_SAME_STMT);
1368 gimple repl = gimple_build_call (fn, 3, dest, src, len);
1369 replace_call_with_call_and_fold (gsi, repl);
1370 return true;
1373 /* Simplify a call to the strcat builtin. DST and SRC are the arguments
1374 to the call.
1376 Return NULL_TREE if no simplification was possible, otherwise return the
1377 simplified form of the call as a tree.
1379 The simplified form may be a constant or other expression which
1380 computes the same value, but in a more efficient manner (including
1381 calls to other builtin functions).
1383 The call may contain arguments which need to be evaluated, but
1384 which are not useful to determine the result of the call. In
1385 this case we return a chain of COMPOUND_EXPRs. The LHS of each
1386 COMPOUND_EXPR will be an argument which must be evaluated.
1387 COMPOUND_EXPRs are chained through their RHS. The RHS of the last
1388 COMPOUND_EXPR in the chain will contain the tree for the simplified
1389 form of the builtin function call. */
1391 static bool
1392 gimple_fold_builtin_strcat (gimple_stmt_iterator *gsi, tree dst, tree src)
1394 gimple stmt = gsi_stmt (*gsi);
1395 location_t loc = gimple_location (stmt);
1397 const char *p = c_getstr (src);
1399 /* If the string length is zero, return the dst parameter. */
1400 if (p && *p == '\0')
1402 replace_call_with_value (gsi, dst);
1403 return true;
1406 if (!optimize_bb_for_speed_p (gimple_bb (stmt)))
1407 return false;
1409 /* See if we can store by pieces into (dst + strlen(dst)). */
1410 tree newdst;
1411 tree strlen_fn = builtin_decl_implicit (BUILT_IN_STRLEN);
1412 tree memcpy_fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1414 if (!strlen_fn || !memcpy_fn)
1415 return false;
1417 /* If the length of the source string isn't computable don't
1418 split strcat into strlen and memcpy. */
1419 tree len = get_maxval_strlen (src, 0);
1420 if (! len)
1421 return false;
1423 /* Create strlen (dst). */
1424 gimple_seq stmts = NULL, stmts2;
1425 gimple repl = gimple_build_call (strlen_fn, 1, dst);
1426 gimple_set_location (repl, loc);
1427 if (gimple_in_ssa_p (cfun))
1428 newdst = make_ssa_name (size_type_node);
1429 else
1430 newdst = create_tmp_reg (size_type_node);
1431 gimple_call_set_lhs (repl, newdst);
1432 gimple_seq_add_stmt_without_update (&stmts, repl);
1434 /* Create (dst p+ strlen (dst)). */
1435 newdst = fold_build_pointer_plus_loc (loc, dst, newdst);
1436 newdst = force_gimple_operand (newdst, &stmts2, true, NULL_TREE);
1437 gimple_seq_add_seq_without_update (&stmts, stmts2);
1439 len = fold_convert_loc (loc, size_type_node, len);
1440 len = size_binop_loc (loc, PLUS_EXPR, len,
1441 build_int_cst (size_type_node, 1));
1442 len = force_gimple_operand (len, &stmts2, true, NULL_TREE);
1443 gimple_seq_add_seq_without_update (&stmts, stmts2);
1445 repl = gimple_build_call (memcpy_fn, 3, newdst, src, len);
1446 gimple_seq_add_stmt_without_update (&stmts, repl);
1447 if (gimple_call_lhs (stmt))
1449 repl = gimple_build_assign (gimple_call_lhs (stmt), dst);
1450 gimple_seq_add_stmt_without_update (&stmts, repl);
1451 gsi_replace_with_seq_vops (gsi, stmts);
1452 /* gsi now points at the assignment to the lhs, get a
1453 stmt iterator to the memcpy call.
1454 ??? We can't use gsi_for_stmt as that doesn't work when the
1455 CFG isn't built yet. */
1456 gimple_stmt_iterator gsi2 = *gsi;
1457 gsi_prev (&gsi2);
1458 fold_stmt (&gsi2);
1460 else
1462 gsi_replace_with_seq_vops (gsi, stmts);
1463 fold_stmt (gsi);
1465 return true;
1468 /* Fold a call to the __strcat_chk builtin FNDECL. DEST, SRC, and SIZE
1469 are the arguments to the call. */
1471 static bool
1472 gimple_fold_builtin_strcat_chk (gimple_stmt_iterator *gsi)
1474 gimple stmt = gsi_stmt (*gsi);
1475 tree dest = gimple_call_arg (stmt, 0);
1476 tree src = gimple_call_arg (stmt, 1);
1477 tree size = gimple_call_arg (stmt, 2);
1478 tree fn;
1479 const char *p;
1482 p = c_getstr (src);
1483 /* If the SRC parameter is "", return DEST. */
1484 if (p && *p == '\0')
1486 replace_call_with_value (gsi, dest);
1487 return true;
1490 if (! tree_fits_uhwi_p (size) || ! integer_all_onesp (size))
1491 return false;
1493 /* If __builtin_strcat_chk is used, assume strcat is available. */
1494 fn = builtin_decl_explicit (BUILT_IN_STRCAT);
1495 if (!fn)
1496 return false;
1498 gimple repl = gimple_build_call (fn, 2, dest, src);
1499 replace_call_with_call_and_fold (gsi, repl);
1500 return true;
1503 /* Simplify a call to the strncat builtin. */
1505 static bool
1506 gimple_fold_builtin_strncat (gimple_stmt_iterator *gsi)
1508 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
1509 tree dst = gimple_call_arg (stmt, 0);
1510 tree src = gimple_call_arg (stmt, 1);
1511 tree len = gimple_call_arg (stmt, 2);
1513 const char *p = c_getstr (src);
1515 /* If the requested length is zero, or the src parameter string
1516 length is zero, return the dst parameter. */
1517 if (integer_zerop (len) || (p && *p == '\0'))
1519 replace_call_with_value (gsi, dst);
1520 return true;
1523 /* If the requested len is greater than or equal to the string
1524 length, call strcat. */
1525 if (TREE_CODE (len) == INTEGER_CST && p
1526 && compare_tree_int (len, strlen (p)) >= 0)
1528 tree fn = builtin_decl_implicit (BUILT_IN_STRCAT);
1530 /* If the replacement _DECL isn't initialized, don't do the
1531 transformation. */
1532 if (!fn)
1533 return false;
1535 gcall *repl = gimple_build_call (fn, 2, dst, src);
1536 replace_call_with_call_and_fold (gsi, repl);
1537 return true;
1540 return false;
1543 /* Fold a call to the __strncat_chk builtin with arguments DEST, SRC,
1544 LEN, and SIZE. */
1546 static bool
1547 gimple_fold_builtin_strncat_chk (gimple_stmt_iterator *gsi)
1549 gimple stmt = gsi_stmt (*gsi);
1550 tree dest = gimple_call_arg (stmt, 0);
1551 tree src = gimple_call_arg (stmt, 1);
1552 tree len = gimple_call_arg (stmt, 2);
1553 tree size = gimple_call_arg (stmt, 3);
1554 tree fn;
1555 const char *p;
1557 p = c_getstr (src);
1558 /* If the SRC parameter is "" or if LEN is 0, return DEST. */
1559 if ((p && *p == '\0')
1560 || integer_zerop (len))
1562 replace_call_with_value (gsi, dest);
1563 return true;
1566 if (! tree_fits_uhwi_p (size))
1567 return false;
1569 if (! integer_all_onesp (size))
1571 tree src_len = c_strlen (src, 1);
1572 if (src_len
1573 && tree_fits_uhwi_p (src_len)
1574 && tree_fits_uhwi_p (len)
1575 && ! tree_int_cst_lt (len, src_len))
1577 /* If LEN >= strlen (SRC), optimize into __strcat_chk. */
1578 fn = builtin_decl_explicit (BUILT_IN_STRCAT_CHK);
1579 if (!fn)
1580 return false;
1582 gimple repl = gimple_build_call (fn, 3, dest, src, size);
1583 replace_call_with_call_and_fold (gsi, repl);
1584 return true;
1586 return false;
1589 /* If __builtin_strncat_chk is used, assume strncat is available. */
1590 fn = builtin_decl_explicit (BUILT_IN_STRNCAT);
1591 if (!fn)
1592 return false;
1594 gimple repl = gimple_build_call (fn, 3, dest, src, len);
1595 replace_call_with_call_and_fold (gsi, repl);
1596 return true;
1599 /* Fold a call to the fputs builtin. ARG0 and ARG1 are the arguments
1600 to the call. IGNORE is true if the value returned
1601 by the builtin will be ignored. UNLOCKED is true is true if this
1602 actually a call to fputs_unlocked. If LEN in non-NULL, it represents
1603 the known length of the string. Return NULL_TREE if no simplification
1604 was possible. */
1606 static bool
1607 gimple_fold_builtin_fputs (gimple_stmt_iterator *gsi,
1608 tree arg0, tree arg1,
1609 bool unlocked)
1611 gimple stmt = gsi_stmt (*gsi);
1613 /* If we're using an unlocked function, assume the other unlocked
1614 functions exist explicitly. */
1615 tree const fn_fputc = (unlocked
1616 ? builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED)
1617 : builtin_decl_implicit (BUILT_IN_FPUTC));
1618 tree const fn_fwrite = (unlocked
1619 ? builtin_decl_explicit (BUILT_IN_FWRITE_UNLOCKED)
1620 : builtin_decl_implicit (BUILT_IN_FWRITE));
1622 /* If the return value is used, don't do the transformation. */
1623 if (gimple_call_lhs (stmt))
1624 return false;
1626 /* Get the length of the string passed to fputs. If the length
1627 can't be determined, punt. */
1628 tree len = get_maxval_strlen (arg0, 0);
1629 if (!len
1630 || TREE_CODE (len) != INTEGER_CST)
1631 return false;
1633 switch (compare_tree_int (len, 1))
1635 case -1: /* length is 0, delete the call entirely . */
1636 replace_call_with_value (gsi, integer_zero_node);
1637 return true;
1639 case 0: /* length is 1, call fputc. */
1641 const char *p = c_getstr (arg0);
1642 if (p != NULL)
1644 if (!fn_fputc)
1645 return false;
1647 gimple repl = gimple_build_call (fn_fputc, 2,
1648 build_int_cst
1649 (integer_type_node, p[0]), arg1);
1650 replace_call_with_call_and_fold (gsi, repl);
1651 return true;
1654 /* FALLTHROUGH */
1655 case 1: /* length is greater than 1, call fwrite. */
1657 /* If optimizing for size keep fputs. */
1658 if (optimize_function_for_size_p (cfun))
1659 return false;
1660 /* New argument list transforming fputs(string, stream) to
1661 fwrite(string, 1, len, stream). */
1662 if (!fn_fwrite)
1663 return false;
1665 gimple repl = gimple_build_call (fn_fwrite, 4, arg0,
1666 size_one_node, len, arg1);
1667 replace_call_with_call_and_fold (gsi, repl);
1668 return true;
1670 default:
1671 gcc_unreachable ();
1673 return false;
1676 /* Fold a call to the __mem{cpy,pcpy,move,set}_chk builtin.
1677 DEST, SRC, LEN, and SIZE are the arguments to the call.
1678 IGNORE is true, if return value can be ignored. FCODE is the BUILT_IN_*
1679 code of the builtin. If MAXLEN is not NULL, it is maximum length
1680 passed as third argument. */
1682 static bool
1683 gimple_fold_builtin_memory_chk (gimple_stmt_iterator *gsi,
1684 tree dest, tree src, tree len, tree size,
1685 enum built_in_function fcode)
1687 gimple stmt = gsi_stmt (*gsi);
1688 location_t loc = gimple_location (stmt);
1689 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
1690 tree fn;
1692 /* If SRC and DEST are the same (and not volatile), return DEST
1693 (resp. DEST+LEN for __mempcpy_chk). */
1694 if (fcode != BUILT_IN_MEMSET_CHK && operand_equal_p (src, dest, 0))
1696 if (fcode != BUILT_IN_MEMPCPY_CHK)
1698 replace_call_with_value (gsi, dest);
1699 return true;
1701 else
1703 tree temp = fold_build_pointer_plus_loc (loc, dest, len);
1704 temp = force_gimple_operand_gsi (gsi, temp,
1705 false, NULL_TREE, true,
1706 GSI_SAME_STMT);
1707 replace_call_with_value (gsi, temp);
1708 return true;
1712 if (! tree_fits_uhwi_p (size))
1713 return false;
1715 tree maxlen = get_maxval_strlen (len, 2);
1716 if (! integer_all_onesp (size))
1718 if (! tree_fits_uhwi_p (len))
1720 /* If LEN is not constant, try MAXLEN too.
1721 For MAXLEN only allow optimizing into non-_ocs function
1722 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
1723 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
1725 if (fcode == BUILT_IN_MEMPCPY_CHK && ignore)
1727 /* (void) __mempcpy_chk () can be optimized into
1728 (void) __memcpy_chk (). */
1729 fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
1730 if (!fn)
1731 return false;
1733 gimple repl = gimple_build_call (fn, 4, dest, src, len, size);
1734 replace_call_with_call_and_fold (gsi, repl);
1735 return true;
1737 return false;
1740 else
1741 maxlen = len;
1743 if (tree_int_cst_lt (size, maxlen))
1744 return false;
1747 fn = NULL_TREE;
1748 /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
1749 mem{cpy,pcpy,move,set} is available. */
1750 switch (fcode)
1752 case BUILT_IN_MEMCPY_CHK:
1753 fn = builtin_decl_explicit (BUILT_IN_MEMCPY);
1754 break;
1755 case BUILT_IN_MEMPCPY_CHK:
1756 fn = builtin_decl_explicit (BUILT_IN_MEMPCPY);
1757 break;
1758 case BUILT_IN_MEMMOVE_CHK:
1759 fn = builtin_decl_explicit (BUILT_IN_MEMMOVE);
1760 break;
1761 case BUILT_IN_MEMSET_CHK:
1762 fn = builtin_decl_explicit (BUILT_IN_MEMSET);
1763 break;
1764 default:
1765 break;
1768 if (!fn)
1769 return false;
1771 gimple repl = gimple_build_call (fn, 3, dest, src, len);
1772 replace_call_with_call_and_fold (gsi, repl);
1773 return true;
1776 /* Fold a call to the __st[rp]cpy_chk builtin.
1777 DEST, SRC, and SIZE are the arguments to the call.
1778 IGNORE is true if return value can be ignored. FCODE is the BUILT_IN_*
1779 code of the builtin. If MAXLEN is not NULL, it is maximum length of
1780 strings passed as second argument. */
1782 static bool
1783 gimple_fold_builtin_stxcpy_chk (gimple_stmt_iterator *gsi,
1784 tree dest,
1785 tree src, tree size,
1786 enum built_in_function fcode)
1788 gimple stmt = gsi_stmt (*gsi);
1789 location_t loc = gimple_location (stmt);
1790 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
1791 tree len, fn;
1793 /* If SRC and DEST are the same (and not volatile), return DEST. */
1794 if (fcode == BUILT_IN_STRCPY_CHK && operand_equal_p (src, dest, 0))
1796 replace_call_with_value (gsi, dest);
1797 return true;
1800 if (! tree_fits_uhwi_p (size))
1801 return false;
1803 tree maxlen = get_maxval_strlen (src, 1);
1804 if (! integer_all_onesp (size))
1806 len = c_strlen (src, 1);
1807 if (! len || ! tree_fits_uhwi_p (len))
1809 /* If LEN is not constant, try MAXLEN too.
1810 For MAXLEN only allow optimizing into non-_ocs function
1811 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
1812 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
1814 if (fcode == BUILT_IN_STPCPY_CHK)
1816 if (! ignore)
1817 return false;
1819 /* If return value of __stpcpy_chk is ignored,
1820 optimize into __strcpy_chk. */
1821 fn = builtin_decl_explicit (BUILT_IN_STRCPY_CHK);
1822 if (!fn)
1823 return false;
1825 gimple repl = gimple_build_call (fn, 3, dest, src, size);
1826 replace_call_with_call_and_fold (gsi, repl);
1827 return true;
1830 if (! len || TREE_SIDE_EFFECTS (len))
1831 return false;
1833 /* If c_strlen returned something, but not a constant,
1834 transform __strcpy_chk into __memcpy_chk. */
1835 fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
1836 if (!fn)
1837 return false;
1839 len = fold_convert_loc (loc, size_type_node, len);
1840 len = size_binop_loc (loc, PLUS_EXPR, len,
1841 build_int_cst (size_type_node, 1));
1842 len = force_gimple_operand_gsi (gsi, len, true, NULL_TREE,
1843 true, GSI_SAME_STMT);
1844 gimple repl = gimple_build_call (fn, 4, dest, src, len, size);
1845 replace_call_with_call_and_fold (gsi, repl);
1846 return true;
1849 else
1850 maxlen = len;
1852 if (! tree_int_cst_lt (maxlen, size))
1853 return false;
1856 /* If __builtin_st{r,p}cpy_chk is used, assume st{r,p}cpy is available. */
1857 fn = builtin_decl_explicit (fcode == BUILT_IN_STPCPY_CHK
1858 ? BUILT_IN_STPCPY : BUILT_IN_STRCPY);
1859 if (!fn)
1860 return false;
1862 gimple repl = gimple_build_call (fn, 2, dest, src);
1863 replace_call_with_call_and_fold (gsi, repl);
1864 return true;
1867 /* Fold a call to the __st{r,p}ncpy_chk builtin. DEST, SRC, LEN, and SIZE
1868 are the arguments to the call. If MAXLEN is not NULL, it is maximum
1869 length passed as third argument. IGNORE is true if return value can be
1870 ignored. FCODE is the BUILT_IN_* code of the builtin. */
1872 static bool
1873 gimple_fold_builtin_stxncpy_chk (gimple_stmt_iterator *gsi,
1874 tree dest, tree src,
1875 tree len, tree size,
1876 enum built_in_function fcode)
1878 gimple stmt = gsi_stmt (*gsi);
1879 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
1880 tree fn;
1882 if (fcode == BUILT_IN_STPNCPY_CHK && ignore)
1884 /* If return value of __stpncpy_chk is ignored,
1885 optimize into __strncpy_chk. */
1886 fn = builtin_decl_explicit (BUILT_IN_STRNCPY_CHK);
1887 if (fn)
1889 gimple repl = gimple_build_call (fn, 4, dest, src, len, size);
1890 replace_call_with_call_and_fold (gsi, repl);
1891 return true;
1895 if (! tree_fits_uhwi_p (size))
1896 return false;
1898 tree maxlen = get_maxval_strlen (len, 2);
1899 if (! integer_all_onesp (size))
1901 if (! tree_fits_uhwi_p (len))
1903 /* If LEN is not constant, try MAXLEN too.
1904 For MAXLEN only allow optimizing into non-_ocs function
1905 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
1906 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
1907 return false;
1909 else
1910 maxlen = len;
1912 if (tree_int_cst_lt (size, maxlen))
1913 return false;
1916 /* If __builtin_st{r,p}ncpy_chk is used, assume st{r,p}ncpy is available. */
1917 fn = builtin_decl_explicit (fcode == BUILT_IN_STPNCPY_CHK
1918 ? BUILT_IN_STPNCPY : BUILT_IN_STRNCPY);
1919 if (!fn)
1920 return false;
1922 gimple repl = gimple_build_call (fn, 3, dest, src, len);
1923 replace_call_with_call_and_fold (gsi, repl);
1924 return true;
1927 /* Fold function call to builtin stpcpy with arguments DEST and SRC.
1928 Return NULL_TREE if no simplification can be made. */
1930 static bool
1931 gimple_fold_builtin_stpcpy (gimple_stmt_iterator *gsi)
1933 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
1934 location_t loc = gimple_location (stmt);
1935 tree dest = gimple_call_arg (stmt, 0);
1936 tree src = gimple_call_arg (stmt, 1);
1937 tree fn, len, lenp1;
1939 /* If the result is unused, replace stpcpy with strcpy. */
1940 if (gimple_call_lhs (stmt) == NULL_TREE)
1942 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
1943 if (!fn)
1944 return false;
1945 gimple_call_set_fndecl (stmt, fn);
1946 fold_stmt (gsi);
1947 return true;
1950 len = c_strlen (src, 1);
1951 if (!len
1952 || TREE_CODE (len) != INTEGER_CST)
1953 return false;
1955 if (optimize_function_for_size_p (cfun)
1956 /* If length is zero it's small enough. */
1957 && !integer_zerop (len))
1958 return false;
1960 /* If the source has a known length replace stpcpy with memcpy. */
1961 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1962 if (!fn)
1963 return false;
1965 gimple_seq stmts = NULL;
1966 tree tem = gimple_convert (&stmts, loc, size_type_node, len);
1967 lenp1 = gimple_build (&stmts, loc, PLUS_EXPR, size_type_node,
1968 tem, build_int_cst (size_type_node, 1));
1969 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
1970 gcall *repl = gimple_build_call (fn, 3, dest, src, lenp1);
1971 gimple_set_vuse (repl, gimple_vuse (stmt));
1972 gimple_set_vdef (repl, gimple_vdef (stmt));
1973 if (gimple_vdef (repl)
1974 && TREE_CODE (gimple_vdef (repl)) == SSA_NAME)
1975 SSA_NAME_DEF_STMT (gimple_vdef (repl)) = repl;
1976 gsi_insert_before (gsi, repl, GSI_SAME_STMT);
1977 /* Replace the result with dest + len. */
1978 stmts = NULL;
1979 tem = gimple_convert (&stmts, loc, sizetype, len);
1980 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
1981 gassign *ret = gimple_build_assign (gimple_call_lhs (stmt),
1982 POINTER_PLUS_EXPR, dest, tem);
1983 gsi_replace (gsi, ret, true);
1984 /* Finally fold the memcpy call. */
1985 gimple_stmt_iterator gsi2 = *gsi;
1986 gsi_prev (&gsi2);
1987 fold_stmt (&gsi2);
1988 return true;
1991 /* Fold a call EXP to {,v}snprintf having NARGS passed as ARGS. Return
1992 NULL_TREE if a normal call should be emitted rather than expanding
1993 the function inline. FCODE is either BUILT_IN_SNPRINTF_CHK or
1994 BUILT_IN_VSNPRINTF_CHK. If MAXLEN is not NULL, it is maximum length
1995 passed as second argument. */
1997 static bool
1998 gimple_fold_builtin_snprintf_chk (gimple_stmt_iterator *gsi,
1999 enum built_in_function fcode)
2001 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2002 tree dest, size, len, fn, fmt, flag;
2003 const char *fmt_str;
2005 /* Verify the required arguments in the original call. */
2006 if (gimple_call_num_args (stmt) < 5)
2007 return false;
2009 dest = gimple_call_arg (stmt, 0);
2010 len = gimple_call_arg (stmt, 1);
2011 flag = gimple_call_arg (stmt, 2);
2012 size = gimple_call_arg (stmt, 3);
2013 fmt = gimple_call_arg (stmt, 4);
2015 if (! tree_fits_uhwi_p (size))
2016 return false;
2018 if (! integer_all_onesp (size))
2020 tree maxlen = get_maxval_strlen (len, 2);
2021 if (! tree_fits_uhwi_p (len))
2023 /* If LEN is not constant, try MAXLEN too.
2024 For MAXLEN only allow optimizing into non-_ocs function
2025 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
2026 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
2027 return false;
2029 else
2030 maxlen = len;
2032 if (tree_int_cst_lt (size, maxlen))
2033 return false;
2036 if (!init_target_chars ())
2037 return false;
2039 /* Only convert __{,v}snprintf_chk to {,v}snprintf if flag is 0
2040 or if format doesn't contain % chars or is "%s". */
2041 if (! integer_zerop (flag))
2043 fmt_str = c_getstr (fmt);
2044 if (fmt_str == NULL)
2045 return false;
2046 if (strchr (fmt_str, target_percent) != NULL
2047 && strcmp (fmt_str, target_percent_s))
2048 return false;
2051 /* If __builtin_{,v}snprintf_chk is used, assume {,v}snprintf is
2052 available. */
2053 fn = builtin_decl_explicit (fcode == BUILT_IN_VSNPRINTF_CHK
2054 ? BUILT_IN_VSNPRINTF : BUILT_IN_SNPRINTF);
2055 if (!fn)
2056 return false;
2058 /* Replace the called function and the first 5 argument by 3 retaining
2059 trailing varargs. */
2060 gimple_call_set_fndecl (stmt, fn);
2061 gimple_call_set_fntype (stmt, TREE_TYPE (fn));
2062 gimple_call_set_arg (stmt, 0, dest);
2063 gimple_call_set_arg (stmt, 1, len);
2064 gimple_call_set_arg (stmt, 2, fmt);
2065 for (unsigned i = 3; i < gimple_call_num_args (stmt) - 2; ++i)
2066 gimple_call_set_arg (stmt, i, gimple_call_arg (stmt, i + 2));
2067 gimple_set_num_ops (stmt, gimple_num_ops (stmt) - 2);
2068 fold_stmt (gsi);
2069 return true;
2072 /* Fold a call EXP to __{,v}sprintf_chk having NARGS passed as ARGS.
2073 Return NULL_TREE if a normal call should be emitted rather than
2074 expanding the function inline. FCODE is either BUILT_IN_SPRINTF_CHK
2075 or BUILT_IN_VSPRINTF_CHK. */
2077 static bool
2078 gimple_fold_builtin_sprintf_chk (gimple_stmt_iterator *gsi,
2079 enum built_in_function fcode)
2081 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2082 tree dest, size, len, fn, fmt, flag;
2083 const char *fmt_str;
2084 unsigned nargs = gimple_call_num_args (stmt);
2086 /* Verify the required arguments in the original call. */
2087 if (nargs < 4)
2088 return false;
2089 dest = gimple_call_arg (stmt, 0);
2090 flag = gimple_call_arg (stmt, 1);
2091 size = gimple_call_arg (stmt, 2);
2092 fmt = gimple_call_arg (stmt, 3);
2094 if (! tree_fits_uhwi_p (size))
2095 return false;
2097 len = NULL_TREE;
2099 if (!init_target_chars ())
2100 return false;
2102 /* Check whether the format is a literal string constant. */
2103 fmt_str = c_getstr (fmt);
2104 if (fmt_str != NULL)
2106 /* If the format doesn't contain % args or %%, we know the size. */
2107 if (strchr (fmt_str, target_percent) == 0)
2109 if (fcode != BUILT_IN_SPRINTF_CHK || nargs == 4)
2110 len = build_int_cstu (size_type_node, strlen (fmt_str));
2112 /* If the format is "%s" and first ... argument is a string literal,
2113 we know the size too. */
2114 else if (fcode == BUILT_IN_SPRINTF_CHK
2115 && strcmp (fmt_str, target_percent_s) == 0)
2117 tree arg;
2119 if (nargs == 5)
2121 arg = gimple_call_arg (stmt, 4);
2122 if (POINTER_TYPE_P (TREE_TYPE (arg)))
2124 len = c_strlen (arg, 1);
2125 if (! len || ! tree_fits_uhwi_p (len))
2126 len = NULL_TREE;
2132 if (! integer_all_onesp (size))
2134 if (! len || ! tree_int_cst_lt (len, size))
2135 return false;
2138 /* Only convert __{,v}sprintf_chk to {,v}sprintf if flag is 0
2139 or if format doesn't contain % chars or is "%s". */
2140 if (! integer_zerop (flag))
2142 if (fmt_str == NULL)
2143 return false;
2144 if (strchr (fmt_str, target_percent) != NULL
2145 && strcmp (fmt_str, target_percent_s))
2146 return false;
2149 /* If __builtin_{,v}sprintf_chk is used, assume {,v}sprintf is available. */
2150 fn = builtin_decl_explicit (fcode == BUILT_IN_VSPRINTF_CHK
2151 ? BUILT_IN_VSPRINTF : BUILT_IN_SPRINTF);
2152 if (!fn)
2153 return false;
2155 /* Replace the called function and the first 4 argument by 2 retaining
2156 trailing varargs. */
2157 gimple_call_set_fndecl (stmt, fn);
2158 gimple_call_set_fntype (stmt, TREE_TYPE (fn));
2159 gimple_call_set_arg (stmt, 0, dest);
2160 gimple_call_set_arg (stmt, 1, fmt);
2161 for (unsigned i = 2; i < gimple_call_num_args (stmt) - 2; ++i)
2162 gimple_call_set_arg (stmt, i, gimple_call_arg (stmt, i + 2));
2163 gimple_set_num_ops (stmt, gimple_num_ops (stmt) - 2);
2164 fold_stmt (gsi);
2165 return true;
2168 /* Simplify a call to the sprintf builtin with arguments DEST, FMT, and ORIG.
2169 ORIG may be null if this is a 2-argument call. We don't attempt to
2170 simplify calls with more than 3 arguments.
2172 Return NULL_TREE if no simplification was possible, otherwise return the
2173 simplified form of the call as a tree. If IGNORED is true, it means that
2174 the caller does not use the returned value of the function. */
2176 static bool
2177 gimple_fold_builtin_sprintf (gimple_stmt_iterator *gsi)
2179 gimple stmt = gsi_stmt (*gsi);
2180 tree dest = gimple_call_arg (stmt, 0);
2181 tree fmt = gimple_call_arg (stmt, 1);
2182 tree orig = NULL_TREE;
2183 const char *fmt_str = NULL;
2185 /* Verify the required arguments in the original call. We deal with two
2186 types of sprintf() calls: 'sprintf (str, fmt)' and
2187 'sprintf (dest, "%s", orig)'. */
2188 if (gimple_call_num_args (stmt) > 3)
2189 return false;
2191 if (gimple_call_num_args (stmt) == 3)
2192 orig = gimple_call_arg (stmt, 2);
2194 /* Check whether the format is a literal string constant. */
2195 fmt_str = c_getstr (fmt);
2196 if (fmt_str == NULL)
2197 return false;
2199 if (!init_target_chars ())
2200 return false;
2202 /* If the format doesn't contain % args or %%, use strcpy. */
2203 if (strchr (fmt_str, target_percent) == NULL)
2205 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2207 if (!fn)
2208 return false;
2210 /* Don't optimize sprintf (buf, "abc", ptr++). */
2211 if (orig)
2212 return false;
2214 /* Convert sprintf (str, fmt) into strcpy (str, fmt) when
2215 'format' is known to contain no % formats. */
2216 gimple_seq stmts = NULL;
2217 gimple repl = gimple_build_call (fn, 2, dest, fmt);
2218 gimple_seq_add_stmt_without_update (&stmts, repl);
2219 if (gimple_call_lhs (stmt))
2221 repl = gimple_build_assign (gimple_call_lhs (stmt),
2222 build_int_cst (integer_type_node,
2223 strlen (fmt_str)));
2224 gimple_seq_add_stmt_without_update (&stmts, repl);
2225 gsi_replace_with_seq_vops (gsi, stmts);
2226 /* gsi now points at the assignment to the lhs, get a
2227 stmt iterator to the memcpy call.
2228 ??? We can't use gsi_for_stmt as that doesn't work when the
2229 CFG isn't built yet. */
2230 gimple_stmt_iterator gsi2 = *gsi;
2231 gsi_prev (&gsi2);
2232 fold_stmt (&gsi2);
2234 else
2236 gsi_replace_with_seq_vops (gsi, stmts);
2237 fold_stmt (gsi);
2239 return true;
2242 /* If the format is "%s", use strcpy if the result isn't used. */
2243 else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
2245 tree fn;
2246 fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2248 if (!fn)
2249 return false;
2251 /* Don't crash on sprintf (str1, "%s"). */
2252 if (!orig)
2253 return false;
2255 tree orig_len = NULL_TREE;
2256 if (gimple_call_lhs (stmt))
2258 orig_len = get_maxval_strlen (orig, 0);
2259 if (!orig_len)
2260 return false;
2263 /* Convert sprintf (str1, "%s", str2) into strcpy (str1, str2). */
2264 gimple_seq stmts = NULL;
2265 gimple repl = gimple_build_call (fn, 2, dest, orig);
2266 gimple_seq_add_stmt_without_update (&stmts, repl);
2267 if (gimple_call_lhs (stmt))
2269 if (!useless_type_conversion_p (integer_type_node,
2270 TREE_TYPE (orig_len)))
2271 orig_len = fold_convert (integer_type_node, orig_len);
2272 repl = gimple_build_assign (gimple_call_lhs (stmt), orig_len);
2273 gimple_seq_add_stmt_without_update (&stmts, repl);
2274 gsi_replace_with_seq_vops (gsi, stmts);
2275 /* gsi now points at the assignment to the lhs, get a
2276 stmt iterator to the memcpy call.
2277 ??? We can't use gsi_for_stmt as that doesn't work when the
2278 CFG isn't built yet. */
2279 gimple_stmt_iterator gsi2 = *gsi;
2280 gsi_prev (&gsi2);
2281 fold_stmt (&gsi2);
2283 else
2285 gsi_replace_with_seq_vops (gsi, stmts);
2286 fold_stmt (gsi);
2288 return true;
2290 return false;
2293 /* Simplify a call to the snprintf builtin with arguments DEST, DESTSIZE,
2294 FMT, and ORIG. ORIG may be null if this is a 3-argument call. We don't
2295 attempt to simplify calls with more than 4 arguments.
2297 Return NULL_TREE if no simplification was possible, otherwise return the
2298 simplified form of the call as a tree. If IGNORED is true, it means that
2299 the caller does not use the returned value of the function. */
2301 static bool
2302 gimple_fold_builtin_snprintf (gimple_stmt_iterator *gsi)
2304 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2305 tree dest = gimple_call_arg (stmt, 0);
2306 tree destsize = gimple_call_arg (stmt, 1);
2307 tree fmt = gimple_call_arg (stmt, 2);
2308 tree orig = NULL_TREE;
2309 const char *fmt_str = NULL;
2311 if (gimple_call_num_args (stmt) > 4)
2312 return false;
2314 if (gimple_call_num_args (stmt) == 4)
2315 orig = gimple_call_arg (stmt, 3);
2317 if (!tree_fits_uhwi_p (destsize))
2318 return false;
2319 unsigned HOST_WIDE_INT destlen = tree_to_uhwi (destsize);
2321 /* Check whether the format is a literal string constant. */
2322 fmt_str = c_getstr (fmt);
2323 if (fmt_str == NULL)
2324 return false;
2326 if (!init_target_chars ())
2327 return false;
2329 /* If the format doesn't contain % args or %%, use strcpy. */
2330 if (strchr (fmt_str, target_percent) == NULL)
2332 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2333 if (!fn)
2334 return false;
2336 /* Don't optimize snprintf (buf, 4, "abc", ptr++). */
2337 if (orig)
2338 return false;
2340 /* We could expand this as
2341 memcpy (str, fmt, cst - 1); str[cst - 1] = '\0';
2342 or to
2343 memcpy (str, fmt_with_nul_at_cstm1, cst);
2344 but in the former case that might increase code size
2345 and in the latter case grow .rodata section too much.
2346 So punt for now. */
2347 size_t len = strlen (fmt_str);
2348 if (len >= destlen)
2349 return false;
2351 gimple_seq stmts = NULL;
2352 gimple repl = gimple_build_call (fn, 2, dest, fmt);
2353 gimple_seq_add_stmt_without_update (&stmts, repl);
2354 if (gimple_call_lhs (stmt))
2356 repl = gimple_build_assign (gimple_call_lhs (stmt),
2357 build_int_cst (integer_type_node, len));
2358 gimple_seq_add_stmt_without_update (&stmts, repl);
2359 gsi_replace_with_seq_vops (gsi, stmts);
2360 /* gsi now points at the assignment to the lhs, get a
2361 stmt iterator to the memcpy call.
2362 ??? We can't use gsi_for_stmt as that doesn't work when the
2363 CFG isn't built yet. */
2364 gimple_stmt_iterator gsi2 = *gsi;
2365 gsi_prev (&gsi2);
2366 fold_stmt (&gsi2);
2368 else
2370 gsi_replace_with_seq_vops (gsi, stmts);
2371 fold_stmt (gsi);
2373 return true;
2376 /* If the format is "%s", use strcpy if the result isn't used. */
2377 else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
2379 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2380 if (!fn)
2381 return false;
2383 /* Don't crash on snprintf (str1, cst, "%s"). */
2384 if (!orig)
2385 return false;
2387 tree orig_len = get_maxval_strlen (orig, 0);
2388 if (!orig_len || TREE_CODE (orig_len) != INTEGER_CST)
2389 return false;
2391 /* We could expand this as
2392 memcpy (str1, str2, cst - 1); str1[cst - 1] = '\0';
2393 or to
2394 memcpy (str1, str2_with_nul_at_cstm1, cst);
2395 but in the former case that might increase code size
2396 and in the latter case grow .rodata section too much.
2397 So punt for now. */
2398 if (compare_tree_int (orig_len, destlen) >= 0)
2399 return false;
2401 /* Convert snprintf (str1, cst, "%s", str2) into
2402 strcpy (str1, str2) if strlen (str2) < cst. */
2403 gimple_seq stmts = NULL;
2404 gimple repl = gimple_build_call (fn, 2, dest, orig);
2405 gimple_seq_add_stmt_without_update (&stmts, repl);
2406 if (gimple_call_lhs (stmt))
2408 if (!useless_type_conversion_p (integer_type_node,
2409 TREE_TYPE (orig_len)))
2410 orig_len = fold_convert (integer_type_node, orig_len);
2411 repl = gimple_build_assign (gimple_call_lhs (stmt), orig_len);
2412 gimple_seq_add_stmt_without_update (&stmts, repl);
2413 gsi_replace_with_seq_vops (gsi, stmts);
2414 /* gsi now points at the assignment to the lhs, get a
2415 stmt iterator to the memcpy call.
2416 ??? We can't use gsi_for_stmt as that doesn't work when the
2417 CFG isn't built yet. */
2418 gimple_stmt_iterator gsi2 = *gsi;
2419 gsi_prev (&gsi2);
2420 fold_stmt (&gsi2);
2422 else
2424 gsi_replace_with_seq_vops (gsi, stmts);
2425 fold_stmt (gsi);
2427 return true;
2429 return false;
2432 /* Fold a call to the {,v}fprintf{,_unlocked} and __{,v}printf_chk builtins.
2433 FP, FMT, and ARG are the arguments to the call. We don't fold calls with
2434 more than 3 arguments, and ARG may be null in the 2-argument case.
2436 Return NULL_TREE if no simplification was possible, otherwise return the
2437 simplified form of the call as a tree. FCODE is the BUILT_IN_*
2438 code of the function to be simplified. */
2440 static bool
2441 gimple_fold_builtin_fprintf (gimple_stmt_iterator *gsi,
2442 tree fp, tree fmt, tree arg,
2443 enum built_in_function fcode)
2445 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2446 tree fn_fputc, fn_fputs;
2447 const char *fmt_str = NULL;
2449 /* If the return value is used, don't do the transformation. */
2450 if (gimple_call_lhs (stmt) != NULL_TREE)
2451 return false;
2453 /* Check whether the format is a literal string constant. */
2454 fmt_str = c_getstr (fmt);
2455 if (fmt_str == NULL)
2456 return false;
2458 if (fcode == BUILT_IN_FPRINTF_UNLOCKED)
2460 /* If we're using an unlocked function, assume the other
2461 unlocked functions exist explicitly. */
2462 fn_fputc = builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED);
2463 fn_fputs = builtin_decl_explicit (BUILT_IN_FPUTS_UNLOCKED);
2465 else
2467 fn_fputc = builtin_decl_implicit (BUILT_IN_FPUTC);
2468 fn_fputs = builtin_decl_implicit (BUILT_IN_FPUTS);
2471 if (!init_target_chars ())
2472 return false;
2474 /* If the format doesn't contain % args or %%, use strcpy. */
2475 if (strchr (fmt_str, target_percent) == NULL)
2477 if (fcode != BUILT_IN_VFPRINTF && fcode != BUILT_IN_VFPRINTF_CHK
2478 && arg)
2479 return false;
2481 /* If the format specifier was "", fprintf does nothing. */
2482 if (fmt_str[0] == '\0')
2484 replace_call_with_value (gsi, NULL_TREE);
2485 return true;
2488 /* When "string" doesn't contain %, replace all cases of
2489 fprintf (fp, string) with fputs (string, fp). The fputs
2490 builtin will take care of special cases like length == 1. */
2491 if (fn_fputs)
2493 gcall *repl = gimple_build_call (fn_fputs, 2, fmt, fp);
2494 replace_call_with_call_and_fold (gsi, repl);
2495 return true;
2499 /* The other optimizations can be done only on the non-va_list variants. */
2500 else if (fcode == BUILT_IN_VFPRINTF || fcode == BUILT_IN_VFPRINTF_CHK)
2501 return false;
2503 /* If the format specifier was "%s", call __builtin_fputs (arg, fp). */
2504 else if (strcmp (fmt_str, target_percent_s) == 0)
2506 if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
2507 return false;
2508 if (fn_fputs)
2510 gcall *repl = gimple_build_call (fn_fputs, 2, arg, fp);
2511 replace_call_with_call_and_fold (gsi, repl);
2512 return true;
2516 /* If the format specifier was "%c", call __builtin_fputc (arg, fp). */
2517 else if (strcmp (fmt_str, target_percent_c) == 0)
2519 if (!arg
2520 || ! useless_type_conversion_p (integer_type_node, TREE_TYPE (arg)))
2521 return false;
2522 if (fn_fputc)
2524 gcall *repl = gimple_build_call (fn_fputc, 2, arg, fp);
2525 replace_call_with_call_and_fold (gsi, repl);
2526 return true;
2530 return false;
2533 /* Fold a call to the {,v}printf{,_unlocked} and __{,v}printf_chk builtins.
2534 FMT and ARG are the arguments to the call; we don't fold cases with
2535 more than 2 arguments, and ARG may be null if this is a 1-argument case.
2537 Return NULL_TREE if no simplification was possible, otherwise return the
2538 simplified form of the call as a tree. FCODE is the BUILT_IN_*
2539 code of the function to be simplified. */
2541 static bool
2542 gimple_fold_builtin_printf (gimple_stmt_iterator *gsi, tree fmt,
2543 tree arg, enum built_in_function fcode)
2545 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2546 tree fn_putchar, fn_puts, newarg;
2547 const char *fmt_str = NULL;
2549 /* If the return value is used, don't do the transformation. */
2550 if (gimple_call_lhs (stmt) != NULL_TREE)
2551 return false;
2553 /* Check whether the format is a literal string constant. */
2554 fmt_str = c_getstr (fmt);
2555 if (fmt_str == NULL)
2556 return false;
2558 if (fcode == BUILT_IN_PRINTF_UNLOCKED)
2560 /* If we're using an unlocked function, assume the other
2561 unlocked functions exist explicitly. */
2562 fn_putchar = builtin_decl_explicit (BUILT_IN_PUTCHAR_UNLOCKED);
2563 fn_puts = builtin_decl_explicit (BUILT_IN_PUTS_UNLOCKED);
2565 else
2567 fn_putchar = builtin_decl_implicit (BUILT_IN_PUTCHAR);
2568 fn_puts = builtin_decl_implicit (BUILT_IN_PUTS);
2571 if (!init_target_chars ())
2572 return false;
2574 if (strcmp (fmt_str, target_percent_s) == 0
2575 || strchr (fmt_str, target_percent) == NULL)
2577 const char *str;
2579 if (strcmp (fmt_str, target_percent_s) == 0)
2581 if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
2582 return false;
2584 if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
2585 return false;
2587 str = c_getstr (arg);
2588 if (str == NULL)
2589 return false;
2591 else
2593 /* The format specifier doesn't contain any '%' characters. */
2594 if (fcode != BUILT_IN_VPRINTF && fcode != BUILT_IN_VPRINTF_CHK
2595 && arg)
2596 return false;
2597 str = fmt_str;
2600 /* If the string was "", printf does nothing. */
2601 if (str[0] == '\0')
2603 replace_call_with_value (gsi, NULL_TREE);
2604 return true;
2607 /* If the string has length of 1, call putchar. */
2608 if (str[1] == '\0')
2610 /* Given printf("c"), (where c is any one character,)
2611 convert "c"[0] to an int and pass that to the replacement
2612 function. */
2613 newarg = build_int_cst (integer_type_node, str[0]);
2614 if (fn_putchar)
2616 gcall *repl = gimple_build_call (fn_putchar, 1, newarg);
2617 replace_call_with_call_and_fold (gsi, repl);
2618 return true;
2621 else
2623 /* If the string was "string\n", call puts("string"). */
2624 size_t len = strlen (str);
2625 if ((unsigned char)str[len - 1] == target_newline
2626 && (size_t) (int) len == len
2627 && (int) len > 0)
2629 char *newstr;
2630 tree offset_node, string_cst;
2632 /* Create a NUL-terminated string that's one char shorter
2633 than the original, stripping off the trailing '\n'. */
2634 newarg = build_string_literal (len, str);
2635 string_cst = string_constant (newarg, &offset_node);
2636 gcc_checking_assert (string_cst
2637 && (TREE_STRING_LENGTH (string_cst)
2638 == (int) len)
2639 && integer_zerop (offset_node)
2640 && (unsigned char)
2641 TREE_STRING_POINTER (string_cst)[len - 1]
2642 == target_newline);
2643 /* build_string_literal creates a new STRING_CST,
2644 modify it in place to avoid double copying. */
2645 newstr = CONST_CAST (char *, TREE_STRING_POINTER (string_cst));
2646 newstr[len - 1] = '\0';
2647 if (fn_puts)
2649 gcall *repl = gimple_build_call (fn_puts, 1, newarg);
2650 replace_call_with_call_and_fold (gsi, repl);
2651 return true;
2654 else
2655 /* We'd like to arrange to call fputs(string,stdout) here,
2656 but we need stdout and don't have a way to get it yet. */
2657 return false;
2661 /* The other optimizations can be done only on the non-va_list variants. */
2662 else if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
2663 return false;
2665 /* If the format specifier was "%s\n", call __builtin_puts(arg). */
2666 else if (strcmp (fmt_str, target_percent_s_newline) == 0)
2668 if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
2669 return false;
2670 if (fn_puts)
2672 gcall *repl = gimple_build_call (fn_puts, 1, arg);
2673 replace_call_with_call_and_fold (gsi, repl);
2674 return true;
2678 /* If the format specifier was "%c", call __builtin_putchar(arg). */
2679 else if (strcmp (fmt_str, target_percent_c) == 0)
2681 if (!arg || ! useless_type_conversion_p (integer_type_node,
2682 TREE_TYPE (arg)))
2683 return false;
2684 if (fn_putchar)
2686 gcall *repl = gimple_build_call (fn_putchar, 1, arg);
2687 replace_call_with_call_and_fold (gsi, repl);
2688 return true;
2692 return false;
2697 /* Fold a call to __builtin_strlen with known length LEN. */
2699 static bool
2700 gimple_fold_builtin_strlen (gimple_stmt_iterator *gsi)
2702 gimple stmt = gsi_stmt (*gsi);
2703 tree len = get_maxval_strlen (gimple_call_arg (stmt, 0), 0);
2704 if (!len)
2705 return false;
2706 len = force_gimple_operand_gsi (gsi, len, true, NULL, true, GSI_SAME_STMT);
2707 replace_call_with_value (gsi, len);
2708 return true;
2712 /* Fold the non-target builtin at *GSI and return whether any simplification
2713 was made. */
2715 static bool
2716 gimple_fold_builtin (gimple_stmt_iterator *gsi)
2718 gcall *stmt = as_a <gcall *>(gsi_stmt (*gsi));
2719 tree callee = gimple_call_fndecl (stmt);
2721 /* Give up for always_inline inline builtins until they are
2722 inlined. */
2723 if (avoid_folding_inline_builtin (callee))
2724 return false;
2726 unsigned n = gimple_call_num_args (stmt);
2727 enum built_in_function fcode = DECL_FUNCTION_CODE (callee);
2728 switch (fcode)
2730 case BUILT_IN_BZERO:
2731 return gimple_fold_builtin_memset (gsi, integer_zero_node,
2732 gimple_call_arg (stmt, 1));
2733 case BUILT_IN_MEMSET:
2734 return gimple_fold_builtin_memset (gsi,
2735 gimple_call_arg (stmt, 1),
2736 gimple_call_arg (stmt, 2));
2737 case BUILT_IN_BCOPY:
2738 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 1),
2739 gimple_call_arg (stmt, 0), 3);
2740 case BUILT_IN_MEMCPY:
2741 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
2742 gimple_call_arg (stmt, 1), 0);
2743 case BUILT_IN_MEMPCPY:
2744 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
2745 gimple_call_arg (stmt, 1), 1);
2746 case BUILT_IN_MEMMOVE:
2747 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
2748 gimple_call_arg (stmt, 1), 3);
2749 case BUILT_IN_SPRINTF_CHK:
2750 case BUILT_IN_VSPRINTF_CHK:
2751 return gimple_fold_builtin_sprintf_chk (gsi, fcode);
2752 case BUILT_IN_STRCAT_CHK:
2753 return gimple_fold_builtin_strcat_chk (gsi);
2754 case BUILT_IN_STRNCAT_CHK:
2755 return gimple_fold_builtin_strncat_chk (gsi);
2756 case BUILT_IN_STRLEN:
2757 return gimple_fold_builtin_strlen (gsi);
2758 case BUILT_IN_STRCPY:
2759 return gimple_fold_builtin_strcpy (gsi,
2760 gimple_call_arg (stmt, 0),
2761 gimple_call_arg (stmt, 1));
2762 case BUILT_IN_STRNCPY:
2763 return gimple_fold_builtin_strncpy (gsi,
2764 gimple_call_arg (stmt, 0),
2765 gimple_call_arg (stmt, 1),
2766 gimple_call_arg (stmt, 2));
2767 case BUILT_IN_STRCAT:
2768 return gimple_fold_builtin_strcat (gsi, gimple_call_arg (stmt, 0),
2769 gimple_call_arg (stmt, 1));
2770 case BUILT_IN_STRNCAT:
2771 return gimple_fold_builtin_strncat (gsi);
2772 case BUILT_IN_FPUTS:
2773 return gimple_fold_builtin_fputs (gsi, gimple_call_arg (stmt, 0),
2774 gimple_call_arg (stmt, 1), false);
2775 case BUILT_IN_FPUTS_UNLOCKED:
2776 return gimple_fold_builtin_fputs (gsi, gimple_call_arg (stmt, 0),
2777 gimple_call_arg (stmt, 1), true);
2778 case BUILT_IN_MEMCPY_CHK:
2779 case BUILT_IN_MEMPCPY_CHK:
2780 case BUILT_IN_MEMMOVE_CHK:
2781 case BUILT_IN_MEMSET_CHK:
2782 return gimple_fold_builtin_memory_chk (gsi,
2783 gimple_call_arg (stmt, 0),
2784 gimple_call_arg (stmt, 1),
2785 gimple_call_arg (stmt, 2),
2786 gimple_call_arg (stmt, 3),
2787 fcode);
2788 case BUILT_IN_STPCPY:
2789 return gimple_fold_builtin_stpcpy (gsi);
2790 case BUILT_IN_STRCPY_CHK:
2791 case BUILT_IN_STPCPY_CHK:
2792 return gimple_fold_builtin_stxcpy_chk (gsi,
2793 gimple_call_arg (stmt, 0),
2794 gimple_call_arg (stmt, 1),
2795 gimple_call_arg (stmt, 2),
2796 fcode);
2797 case BUILT_IN_STRNCPY_CHK:
2798 case BUILT_IN_STPNCPY_CHK:
2799 return gimple_fold_builtin_stxncpy_chk (gsi,
2800 gimple_call_arg (stmt, 0),
2801 gimple_call_arg (stmt, 1),
2802 gimple_call_arg (stmt, 2),
2803 gimple_call_arg (stmt, 3),
2804 fcode);
2805 case BUILT_IN_SNPRINTF_CHK:
2806 case BUILT_IN_VSNPRINTF_CHK:
2807 return gimple_fold_builtin_snprintf_chk (gsi, fcode);
2808 case BUILT_IN_SNPRINTF:
2809 return gimple_fold_builtin_snprintf (gsi);
2810 case BUILT_IN_SPRINTF:
2811 return gimple_fold_builtin_sprintf (gsi);
2812 case BUILT_IN_FPRINTF:
2813 case BUILT_IN_FPRINTF_UNLOCKED:
2814 case BUILT_IN_VFPRINTF:
2815 if (n == 2 || n == 3)
2816 return gimple_fold_builtin_fprintf (gsi,
2817 gimple_call_arg (stmt, 0),
2818 gimple_call_arg (stmt, 1),
2819 n == 3
2820 ? gimple_call_arg (stmt, 2)
2821 : NULL_TREE,
2822 fcode);
2823 break;
2824 case BUILT_IN_FPRINTF_CHK:
2825 case BUILT_IN_VFPRINTF_CHK:
2826 if (n == 3 || n == 4)
2827 return gimple_fold_builtin_fprintf (gsi,
2828 gimple_call_arg (stmt, 0),
2829 gimple_call_arg (stmt, 2),
2830 n == 4
2831 ? gimple_call_arg (stmt, 3)
2832 : NULL_TREE,
2833 fcode);
2834 break;
2835 case BUILT_IN_PRINTF:
2836 case BUILT_IN_PRINTF_UNLOCKED:
2837 case BUILT_IN_VPRINTF:
2838 if (n == 1 || n == 2)
2839 return gimple_fold_builtin_printf (gsi, gimple_call_arg (stmt, 0),
2840 n == 2
2841 ? gimple_call_arg (stmt, 1)
2842 : NULL_TREE, fcode);
2843 break;
2844 case BUILT_IN_PRINTF_CHK:
2845 case BUILT_IN_VPRINTF_CHK:
2846 if (n == 2 || n == 3)
2847 return gimple_fold_builtin_printf (gsi, gimple_call_arg (stmt, 1),
2848 n == 3
2849 ? gimple_call_arg (stmt, 2)
2850 : NULL_TREE, fcode);
2851 default:;
2854 /* Try the generic builtin folder. */
2855 bool ignore = (gimple_call_lhs (stmt) == NULL);
2856 tree result = fold_call_stmt (stmt, ignore);
2857 if (result)
2859 if (ignore)
2860 STRIP_NOPS (result);
2861 else
2862 result = fold_convert (gimple_call_return_type (stmt), result);
2863 if (!update_call_from_tree (gsi, result))
2864 gimplify_and_update_call_from_tree (gsi, result);
2865 return true;
2868 return false;
2871 /* Return true if ARG0 CODE ARG1 in infinite signed precision operation
2872 doesn't fit into TYPE. The test for overflow should be regardless of
2873 -fwrapv, and even for unsigned types. */
2875 bool
2876 arith_overflowed_p (enum tree_code code, const_tree type,
2877 const_tree arg0, const_tree arg1)
2879 typedef FIXED_WIDE_INT (WIDE_INT_MAX_PRECISION * 2) widest2_int;
2880 typedef generic_wide_int <wi::extended_tree <WIDE_INT_MAX_PRECISION * 2> >
2881 widest2_int_cst;
2882 widest2_int warg0 = widest2_int_cst (arg0);
2883 widest2_int warg1 = widest2_int_cst (arg1);
2884 widest2_int wres;
2885 switch (code)
2887 case PLUS_EXPR: wres = wi::add (warg0, warg1); break;
2888 case MINUS_EXPR: wres = wi::sub (warg0, warg1); break;
2889 case MULT_EXPR: wres = wi::mul (warg0, warg1); break;
2890 default: gcc_unreachable ();
2892 signop sign = TYPE_SIGN (type);
2893 if (sign == UNSIGNED && wi::neg_p (wres))
2894 return true;
2895 return wi::min_precision (wres, sign) > TYPE_PRECISION (type);
2898 /* Attempt to fold a call statement referenced by the statement iterator GSI.
2899 The statement may be replaced by another statement, e.g., if the call
2900 simplifies to a constant value. Return true if any changes were made.
2901 It is assumed that the operands have been previously folded. */
2903 static bool
2904 gimple_fold_call (gimple_stmt_iterator *gsi, bool inplace)
2906 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2907 tree callee;
2908 bool changed = false;
2909 unsigned i;
2911 /* Fold *& in call arguments. */
2912 for (i = 0; i < gimple_call_num_args (stmt); ++i)
2913 if (REFERENCE_CLASS_P (gimple_call_arg (stmt, i)))
2915 tree tmp = maybe_fold_reference (gimple_call_arg (stmt, i), false);
2916 if (tmp)
2918 gimple_call_set_arg (stmt, i, tmp);
2919 changed = true;
2923 /* Check for virtual calls that became direct calls. */
2924 callee = gimple_call_fn (stmt);
2925 if (callee && TREE_CODE (callee) == OBJ_TYPE_REF)
2927 if (gimple_call_addr_fndecl (OBJ_TYPE_REF_EXPR (callee)) != NULL_TREE)
2929 if (dump_file && virtual_method_call_p (callee)
2930 && !possible_polymorphic_call_target_p
2931 (callee, stmt, cgraph_node::get (gimple_call_addr_fndecl
2932 (OBJ_TYPE_REF_EXPR (callee)))))
2934 fprintf (dump_file,
2935 "Type inheritance inconsistent devirtualization of ");
2936 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2937 fprintf (dump_file, " to ");
2938 print_generic_expr (dump_file, callee, TDF_SLIM);
2939 fprintf (dump_file, "\n");
2942 gimple_call_set_fn (stmt, OBJ_TYPE_REF_EXPR (callee));
2943 changed = true;
2945 else if (flag_devirtualize && !inplace && virtual_method_call_p (callee))
2947 bool final;
2948 vec <cgraph_node *>targets
2949 = possible_polymorphic_call_targets (callee, stmt, &final);
2950 if (final && targets.length () <= 1 && dbg_cnt (devirt))
2952 tree lhs = gimple_call_lhs (stmt);
2953 if (dump_enabled_p ())
2955 location_t loc = gimple_location_safe (stmt);
2956 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, loc,
2957 "folding virtual function call to %s\n",
2958 targets.length () == 1
2959 ? targets[0]->name ()
2960 : "__builtin_unreachable");
2962 if (targets.length () == 1)
2964 gimple_call_set_fndecl (stmt, targets[0]->decl);
2965 changed = true;
2966 /* If the call becomes noreturn, remove the lhs. */
2967 if (lhs && (gimple_call_flags (stmt) & ECF_NORETURN))
2969 if (TREE_CODE (lhs) == SSA_NAME)
2971 tree var = create_tmp_var (TREE_TYPE (lhs));
2972 tree def = get_or_create_ssa_default_def (cfun, var);
2973 gimple new_stmt = gimple_build_assign (lhs, def);
2974 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
2976 gimple_call_set_lhs (stmt, NULL_TREE);
2978 maybe_remove_unused_call_args (cfun, stmt);
2980 else
2982 tree fndecl = builtin_decl_implicit (BUILT_IN_UNREACHABLE);
2983 gimple new_stmt = gimple_build_call (fndecl, 0);
2984 gimple_set_location (new_stmt, gimple_location (stmt));
2985 if (lhs && TREE_CODE (lhs) == SSA_NAME)
2987 tree var = create_tmp_var (TREE_TYPE (lhs));
2988 tree def = get_or_create_ssa_default_def (cfun, var);
2990 /* To satisfy condition for
2991 cgraph_update_edges_for_call_stmt_node,
2992 we need to preserve GIMPLE_CALL statement
2993 at position of GSI iterator. */
2994 update_call_from_tree (gsi, def);
2995 gsi_insert_before (gsi, new_stmt, GSI_NEW_STMT);
2997 else
2999 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
3000 gimple_set_vdef (new_stmt, gimple_vdef (stmt));
3001 gsi_replace (gsi, new_stmt, false);
3003 return true;
3009 /* Check for indirect calls that became direct calls, and then
3010 no longer require a static chain. */
3011 if (gimple_call_chain (stmt))
3013 tree fn = gimple_call_fndecl (stmt);
3014 if (fn && !DECL_STATIC_CHAIN (fn))
3016 gimple_call_set_chain (stmt, NULL);
3017 changed = true;
3019 else
3021 tree tmp = maybe_fold_reference (gimple_call_chain (stmt), false);
3022 if (tmp)
3024 gimple_call_set_chain (stmt, tmp);
3025 changed = true;
3030 if (inplace)
3031 return changed;
3033 /* Check for builtins that CCP can handle using information not
3034 available in the generic fold routines. */
3035 if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
3037 if (gimple_fold_builtin (gsi))
3038 changed = true;
3040 else if (gimple_call_builtin_p (stmt, BUILT_IN_MD))
3042 changed |= targetm.gimple_fold_builtin (gsi);
3044 else if (gimple_call_internal_p (stmt))
3046 enum tree_code subcode = ERROR_MARK;
3047 tree result = NULL_TREE;
3048 bool cplx_result = false;
3049 tree overflow = NULL_TREE;
3050 switch (gimple_call_internal_fn (stmt))
3052 case IFN_BUILTIN_EXPECT:
3053 result = fold_builtin_expect (gimple_location (stmt),
3054 gimple_call_arg (stmt, 0),
3055 gimple_call_arg (stmt, 1),
3056 gimple_call_arg (stmt, 2));
3057 break;
3058 case IFN_UBSAN_OBJECT_SIZE:
3059 if (integer_all_onesp (gimple_call_arg (stmt, 2))
3060 || (TREE_CODE (gimple_call_arg (stmt, 1)) == INTEGER_CST
3061 && TREE_CODE (gimple_call_arg (stmt, 2)) == INTEGER_CST
3062 && tree_int_cst_le (gimple_call_arg (stmt, 1),
3063 gimple_call_arg (stmt, 2))))
3065 gsi_replace (gsi, gimple_build_nop (), true);
3066 unlink_stmt_vdef (stmt);
3067 release_defs (stmt);
3068 return true;
3070 break;
3071 case IFN_UBSAN_CHECK_ADD:
3072 subcode = PLUS_EXPR;
3073 break;
3074 case IFN_UBSAN_CHECK_SUB:
3075 subcode = MINUS_EXPR;
3076 break;
3077 case IFN_UBSAN_CHECK_MUL:
3078 subcode = MULT_EXPR;
3079 break;
3080 case IFN_ADD_OVERFLOW:
3081 subcode = PLUS_EXPR;
3082 cplx_result = true;
3083 break;
3084 case IFN_SUB_OVERFLOW:
3085 subcode = MINUS_EXPR;
3086 cplx_result = true;
3087 break;
3088 case IFN_MUL_OVERFLOW:
3089 subcode = MULT_EXPR;
3090 cplx_result = true;
3091 break;
3092 default:
3093 break;
3095 if (subcode != ERROR_MARK)
3097 tree arg0 = gimple_call_arg (stmt, 0);
3098 tree arg1 = gimple_call_arg (stmt, 1);
3099 tree type = TREE_TYPE (arg0);
3100 if (cplx_result)
3102 tree lhs = gimple_call_lhs (stmt);
3103 if (lhs == NULL_TREE)
3104 type = NULL_TREE;
3105 else
3106 type = TREE_TYPE (TREE_TYPE (lhs));
3108 if (type == NULL_TREE)
3110 /* x = y + 0; x = y - 0; x = y * 0; */
3111 else if (integer_zerop (arg1))
3112 result = subcode == MULT_EXPR ? integer_zero_node : arg0;
3113 /* x = 0 + y; x = 0 * y; */
3114 else if (subcode != MINUS_EXPR && integer_zerop (arg0))
3115 result = subcode == MULT_EXPR ? integer_zero_node : arg1;
3116 /* x = y - y; */
3117 else if (subcode == MINUS_EXPR && operand_equal_p (arg0, arg1, 0))
3118 result = integer_zero_node;
3119 /* x = y * 1; x = 1 * y; */
3120 else if (subcode == MULT_EXPR && integer_onep (arg1))
3121 result = arg0;
3122 else if (subcode == MULT_EXPR && integer_onep (arg0))
3123 result = arg1;
3124 else if (TREE_CODE (arg0) == INTEGER_CST
3125 && TREE_CODE (arg1) == INTEGER_CST)
3127 if (cplx_result)
3128 result = int_const_binop (subcode, fold_convert (type, arg0),
3129 fold_convert (type, arg1));
3130 else
3131 result = int_const_binop (subcode, arg0, arg1);
3132 if (result && arith_overflowed_p (subcode, type, arg0, arg1))
3134 if (cplx_result)
3135 overflow = build_one_cst (type);
3136 else
3137 result = NULL_TREE;
3140 if (result)
3142 if (result == integer_zero_node)
3143 result = build_zero_cst (type);
3144 else if (cplx_result && TREE_TYPE (result) != type)
3146 if (TREE_CODE (result) == INTEGER_CST)
3148 if (arith_overflowed_p (PLUS_EXPR, type, result,
3149 integer_zero_node))
3150 overflow = build_one_cst (type);
3152 else if ((!TYPE_UNSIGNED (TREE_TYPE (result))
3153 && TYPE_UNSIGNED (type))
3154 || (TYPE_PRECISION (type)
3155 < (TYPE_PRECISION (TREE_TYPE (result))
3156 + (TYPE_UNSIGNED (TREE_TYPE (result))
3157 && !TYPE_UNSIGNED (type)))))
3158 result = NULL_TREE;
3159 if (result)
3160 result = fold_convert (type, result);
3165 if (result)
3167 if (TREE_CODE (result) == INTEGER_CST && TREE_OVERFLOW (result))
3168 result = drop_tree_overflow (result);
3169 if (cplx_result)
3171 if (overflow == NULL_TREE)
3172 overflow = build_zero_cst (TREE_TYPE (result));
3173 tree ctype = build_complex_type (TREE_TYPE (result));
3174 if (TREE_CODE (result) == INTEGER_CST
3175 && TREE_CODE (overflow) == INTEGER_CST)
3176 result = build_complex (ctype, result, overflow);
3177 else
3178 result = build2_loc (gimple_location (stmt), COMPLEX_EXPR,
3179 ctype, result, overflow);
3181 if (!update_call_from_tree (gsi, result))
3182 gimplify_and_update_call_from_tree (gsi, result);
3183 changed = true;
3187 return changed;
3191 /* Return true whether NAME has a use on STMT. */
3193 static bool
3194 has_use_on_stmt (tree name, gimple stmt)
3196 imm_use_iterator iter;
3197 use_operand_p use_p;
3198 FOR_EACH_IMM_USE_FAST (use_p, iter, name)
3199 if (USE_STMT (use_p) == stmt)
3200 return true;
3201 return false;
3204 /* Worker for fold_stmt_1 dispatch to pattern based folding with
3205 gimple_simplify.
3207 Replaces *GSI with the simplification result in RCODE and OPS
3208 and the associated statements in *SEQ. Does the replacement
3209 according to INPLACE and returns true if the operation succeeded. */
3211 static bool
3212 replace_stmt_with_simplification (gimple_stmt_iterator *gsi,
3213 code_helper rcode, tree *ops,
3214 gimple_seq *seq, bool inplace)
3216 gimple stmt = gsi_stmt (*gsi);
3218 /* Play safe and do not allow abnormals to be mentioned in
3219 newly created statements. See also maybe_push_res_to_seq.
3220 As an exception allow such uses if there was a use of the
3221 same SSA name on the old stmt. */
3222 if ((TREE_CODE (ops[0]) == SSA_NAME
3223 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ops[0])
3224 && !has_use_on_stmt (ops[0], stmt))
3225 || (ops[1]
3226 && TREE_CODE (ops[1]) == SSA_NAME
3227 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ops[1])
3228 && !has_use_on_stmt (ops[1], stmt))
3229 || (ops[2]
3230 && TREE_CODE (ops[2]) == SSA_NAME
3231 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ops[2])
3232 && !has_use_on_stmt (ops[2], stmt)))
3233 return false;
3235 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
3237 gcc_assert (rcode.is_tree_code ());
3238 if (TREE_CODE_CLASS ((enum tree_code)rcode) == tcc_comparison
3239 /* GIMPLE_CONDs condition may not throw. */
3240 && (!flag_exceptions
3241 || !cfun->can_throw_non_call_exceptions
3242 || !operation_could_trap_p (rcode,
3243 FLOAT_TYPE_P (TREE_TYPE (ops[0])),
3244 false, NULL_TREE)))
3245 gimple_cond_set_condition (cond_stmt, rcode, ops[0], ops[1]);
3246 else if (rcode == SSA_NAME)
3247 gimple_cond_set_condition (cond_stmt, NE_EXPR, ops[0],
3248 build_zero_cst (TREE_TYPE (ops[0])));
3249 else if (rcode == INTEGER_CST)
3251 if (integer_zerop (ops[0]))
3252 gimple_cond_make_false (cond_stmt);
3253 else
3254 gimple_cond_make_true (cond_stmt);
3256 else if (!inplace)
3258 tree res = maybe_push_res_to_seq (rcode, boolean_type_node,
3259 ops, seq);
3260 if (!res)
3261 return false;
3262 gimple_cond_set_condition (cond_stmt, NE_EXPR, res,
3263 build_zero_cst (TREE_TYPE (res)));
3265 else
3266 return false;
3267 if (dump_file && (dump_flags & TDF_DETAILS))
3269 fprintf (dump_file, "gimple_simplified to ");
3270 if (!gimple_seq_empty_p (*seq))
3271 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
3272 print_gimple_stmt (dump_file, gsi_stmt (*gsi),
3273 0, TDF_SLIM);
3275 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
3276 return true;
3278 else if (is_gimple_assign (stmt)
3279 && rcode.is_tree_code ())
3281 if (!inplace
3282 || gimple_num_ops (stmt) > get_gimple_rhs_num_ops (rcode))
3284 maybe_build_generic_op (rcode,
3285 TREE_TYPE (gimple_assign_lhs (stmt)),
3286 &ops[0], ops[1], ops[2]);
3287 gimple_assign_set_rhs_with_ops (gsi, rcode, ops[0], ops[1], ops[2]);
3288 if (dump_file && (dump_flags & TDF_DETAILS))
3290 fprintf (dump_file, "gimple_simplified to ");
3291 if (!gimple_seq_empty_p (*seq))
3292 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
3293 print_gimple_stmt (dump_file, gsi_stmt (*gsi),
3294 0, TDF_SLIM);
3296 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
3297 return true;
3300 else if (rcode.is_fn_code ()
3301 && gimple_call_builtin_p (stmt, rcode))
3303 unsigned i;
3304 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3306 gcc_assert (ops[i] != NULL_TREE);
3307 gimple_call_set_arg (stmt, i, ops[i]);
3309 if (i < 3)
3310 gcc_assert (ops[i] == NULL_TREE);
3311 gcc_assert (gimple_seq_empty_p (*seq));
3312 return true;
3314 else if (!inplace)
3316 if (gimple_has_lhs (stmt))
3318 tree lhs = gimple_get_lhs (stmt);
3319 if (!maybe_push_res_to_seq (rcode, TREE_TYPE (lhs),
3320 ops, seq, lhs))
3321 return false;
3322 if (dump_file && (dump_flags & TDF_DETAILS))
3324 fprintf (dump_file, "gimple_simplified to ");
3325 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
3327 gsi_replace_with_seq_vops (gsi, *seq);
3328 return true;
3330 else
3331 gcc_unreachable ();
3334 return false;
3337 /* Canonicalize MEM_REFs invariant address operand after propagation. */
3339 static bool
3340 maybe_canonicalize_mem_ref_addr (tree *t)
3342 bool res = false;
3344 if (TREE_CODE (*t) == ADDR_EXPR)
3345 t = &TREE_OPERAND (*t, 0);
3347 while (handled_component_p (*t))
3348 t = &TREE_OPERAND (*t, 0);
3350 /* Canonicalize MEM [&foo.bar, 0] which appears after propagating
3351 of invariant addresses into a SSA name MEM_REF address. */
3352 if (TREE_CODE (*t) == MEM_REF
3353 || TREE_CODE (*t) == TARGET_MEM_REF)
3355 tree addr = TREE_OPERAND (*t, 0);
3356 if (TREE_CODE (addr) == ADDR_EXPR
3357 && (TREE_CODE (TREE_OPERAND (addr, 0)) == MEM_REF
3358 || handled_component_p (TREE_OPERAND (addr, 0))))
3360 tree base;
3361 HOST_WIDE_INT coffset;
3362 base = get_addr_base_and_unit_offset (TREE_OPERAND (addr, 0),
3363 &coffset);
3364 if (!base)
3365 gcc_unreachable ();
3367 TREE_OPERAND (*t, 0) = build_fold_addr_expr (base);
3368 TREE_OPERAND (*t, 1) = int_const_binop (PLUS_EXPR,
3369 TREE_OPERAND (*t, 1),
3370 size_int (coffset));
3371 res = true;
3373 gcc_checking_assert (TREE_CODE (TREE_OPERAND (*t, 0)) == DEBUG_EXPR_DECL
3374 || is_gimple_mem_ref_addr (TREE_OPERAND (*t, 0)));
3377 /* Canonicalize back MEM_REFs to plain reference trees if the object
3378 accessed is a decl that has the same access semantics as the MEM_REF. */
3379 if (TREE_CODE (*t) == MEM_REF
3380 && TREE_CODE (TREE_OPERAND (*t, 0)) == ADDR_EXPR
3381 && integer_zerop (TREE_OPERAND (*t, 1))
3382 && MR_DEPENDENCE_CLIQUE (*t) == 0)
3384 tree decl = TREE_OPERAND (TREE_OPERAND (*t, 0), 0);
3385 tree alias_type = TREE_TYPE (TREE_OPERAND (*t, 1));
3386 if (/* Same volatile qualification. */
3387 TREE_THIS_VOLATILE (*t) == TREE_THIS_VOLATILE (decl)
3388 /* Same TBAA behavior with -fstrict-aliasing. */
3389 && !TYPE_REF_CAN_ALIAS_ALL (alias_type)
3390 && (TYPE_MAIN_VARIANT (TREE_TYPE (decl))
3391 == TYPE_MAIN_VARIANT (TREE_TYPE (alias_type)))
3392 /* Same alignment. */
3393 && TYPE_ALIGN (TREE_TYPE (decl)) == TYPE_ALIGN (TREE_TYPE (*t))
3394 /* We have to look out here to not drop a required conversion
3395 from the rhs to the lhs if *t appears on the lhs or vice-versa
3396 if it appears on the rhs. Thus require strict type
3397 compatibility. */
3398 && types_compatible_p (TREE_TYPE (*t), TREE_TYPE (decl)))
3400 *t = TREE_OPERAND (TREE_OPERAND (*t, 0), 0);
3401 res = true;
3405 /* Canonicalize TARGET_MEM_REF in particular with respect to
3406 the indexes becoming constant. */
3407 else if (TREE_CODE (*t) == TARGET_MEM_REF)
3409 tree tem = maybe_fold_tmr (*t);
3410 if (tem)
3412 *t = tem;
3413 res = true;
3417 return res;
3420 /* Worker for both fold_stmt and fold_stmt_inplace. The INPLACE argument
3421 distinguishes both cases. */
3423 static bool
3424 fold_stmt_1 (gimple_stmt_iterator *gsi, bool inplace, tree (*valueize) (tree))
3426 bool changed = false;
3427 gimple stmt = gsi_stmt (*gsi);
3428 unsigned i;
3430 /* First do required canonicalization of [TARGET_]MEM_REF addresses
3431 after propagation.
3432 ??? This shouldn't be done in generic folding but in the
3433 propagation helpers which also know whether an address was
3434 propagated.
3435 Also canonicalize operand order. */
3436 switch (gimple_code (stmt))
3438 case GIMPLE_ASSIGN:
3439 if (gimple_assign_rhs_class (stmt) == GIMPLE_SINGLE_RHS)
3441 tree *rhs = gimple_assign_rhs1_ptr (stmt);
3442 if ((REFERENCE_CLASS_P (*rhs)
3443 || TREE_CODE (*rhs) == ADDR_EXPR)
3444 && maybe_canonicalize_mem_ref_addr (rhs))
3445 changed = true;
3446 tree *lhs = gimple_assign_lhs_ptr (stmt);
3447 if (REFERENCE_CLASS_P (*lhs)
3448 && maybe_canonicalize_mem_ref_addr (lhs))
3449 changed = true;
3451 else
3453 /* Canonicalize operand order. */
3454 enum tree_code code = gimple_assign_rhs_code (stmt);
3455 if (TREE_CODE_CLASS (code) == tcc_comparison
3456 || commutative_tree_code (code)
3457 || commutative_ternary_tree_code (code))
3459 tree rhs1 = gimple_assign_rhs1 (stmt);
3460 tree rhs2 = gimple_assign_rhs2 (stmt);
3461 if (tree_swap_operands_p (rhs1, rhs2, false))
3463 gimple_assign_set_rhs1 (stmt, rhs2);
3464 gimple_assign_set_rhs2 (stmt, rhs1);
3465 if (TREE_CODE_CLASS (code) == tcc_comparison)
3466 gimple_assign_set_rhs_code (stmt,
3467 swap_tree_comparison (code));
3468 changed = true;
3472 break;
3473 case GIMPLE_CALL:
3475 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3477 tree *arg = gimple_call_arg_ptr (stmt, i);
3478 if (REFERENCE_CLASS_P (*arg)
3479 && maybe_canonicalize_mem_ref_addr (arg))
3480 changed = true;
3482 tree *lhs = gimple_call_lhs_ptr (stmt);
3483 if (*lhs
3484 && REFERENCE_CLASS_P (*lhs)
3485 && maybe_canonicalize_mem_ref_addr (lhs))
3486 changed = true;
3487 break;
3489 case GIMPLE_ASM:
3491 gasm *asm_stmt = as_a <gasm *> (stmt);
3492 for (i = 0; i < gimple_asm_noutputs (asm_stmt); ++i)
3494 tree link = gimple_asm_output_op (asm_stmt, i);
3495 tree op = TREE_VALUE (link);
3496 if (REFERENCE_CLASS_P (op)
3497 && maybe_canonicalize_mem_ref_addr (&TREE_VALUE (link)))
3498 changed = true;
3500 for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
3502 tree link = gimple_asm_input_op (asm_stmt, i);
3503 tree op = TREE_VALUE (link);
3504 if ((REFERENCE_CLASS_P (op)
3505 || TREE_CODE (op) == ADDR_EXPR)
3506 && maybe_canonicalize_mem_ref_addr (&TREE_VALUE (link)))
3507 changed = true;
3510 break;
3511 case GIMPLE_DEBUG:
3512 if (gimple_debug_bind_p (stmt))
3514 tree *val = gimple_debug_bind_get_value_ptr (stmt);
3515 if (*val
3516 && (REFERENCE_CLASS_P (*val)
3517 || TREE_CODE (*val) == ADDR_EXPR)
3518 && maybe_canonicalize_mem_ref_addr (val))
3519 changed = true;
3521 break;
3522 case GIMPLE_COND:
3524 /* Canonicalize operand order. */
3525 tree lhs = gimple_cond_lhs (stmt);
3526 tree rhs = gimple_cond_rhs (stmt);
3527 if (tree_swap_operands_p (lhs, rhs, false))
3529 gcond *gc = as_a <gcond *> (stmt);
3530 gimple_cond_set_lhs (gc, rhs);
3531 gimple_cond_set_rhs (gc, lhs);
3532 gimple_cond_set_code (gc,
3533 swap_tree_comparison (gimple_cond_code (gc)));
3534 changed = true;
3537 default:;
3540 /* Dispatch to pattern-based folding. */
3541 if (!inplace
3542 || is_gimple_assign (stmt)
3543 || gimple_code (stmt) == GIMPLE_COND)
3545 gimple_seq seq = NULL;
3546 code_helper rcode;
3547 tree ops[3] = {};
3548 if (gimple_simplify (stmt, &rcode, ops, inplace ? NULL : &seq,
3549 valueize, valueize))
3551 if (replace_stmt_with_simplification (gsi, rcode, ops, &seq, inplace))
3552 changed = true;
3553 else
3554 gimple_seq_discard (seq);
3558 stmt = gsi_stmt (*gsi);
3560 /* Fold the main computation performed by the statement. */
3561 switch (gimple_code (stmt))
3563 case GIMPLE_ASSIGN:
3565 /* Try to canonicalize for boolean-typed X the comparisons
3566 X == 0, X == 1, X != 0, and X != 1. */
3567 if (gimple_assign_rhs_code (stmt) == EQ_EXPR
3568 || gimple_assign_rhs_code (stmt) == NE_EXPR)
3570 tree lhs = gimple_assign_lhs (stmt);
3571 tree op1 = gimple_assign_rhs1 (stmt);
3572 tree op2 = gimple_assign_rhs2 (stmt);
3573 tree type = TREE_TYPE (op1);
3575 /* Check whether the comparison operands are of the same boolean
3576 type as the result type is.
3577 Check that second operand is an integer-constant with value
3578 one or zero. */
3579 if (TREE_CODE (op2) == INTEGER_CST
3580 && (integer_zerop (op2) || integer_onep (op2))
3581 && useless_type_conversion_p (TREE_TYPE (lhs), type))
3583 enum tree_code cmp_code = gimple_assign_rhs_code (stmt);
3584 bool is_logical_not = false;
3586 /* X == 0 and X != 1 is a logical-not.of X
3587 X == 1 and X != 0 is X */
3588 if ((cmp_code == EQ_EXPR && integer_zerop (op2))
3589 || (cmp_code == NE_EXPR && integer_onep (op2)))
3590 is_logical_not = true;
3592 if (is_logical_not == false)
3593 gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op1), op1);
3594 /* Only for one-bit precision typed X the transformation
3595 !X -> ~X is valied. */
3596 else if (TYPE_PRECISION (type) == 1)
3597 gimple_assign_set_rhs_with_ops (gsi, BIT_NOT_EXPR, op1);
3598 /* Otherwise we use !X -> X ^ 1. */
3599 else
3600 gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op1,
3601 build_int_cst (type, 1));
3602 changed = true;
3603 break;
3607 unsigned old_num_ops = gimple_num_ops (stmt);
3608 tree lhs = gimple_assign_lhs (stmt);
3609 tree new_rhs = fold_gimple_assign (gsi);
3610 if (new_rhs
3611 && !useless_type_conversion_p (TREE_TYPE (lhs),
3612 TREE_TYPE (new_rhs)))
3613 new_rhs = fold_convert (TREE_TYPE (lhs), new_rhs);
3614 if (new_rhs
3615 && (!inplace
3616 || get_gimple_rhs_num_ops (TREE_CODE (new_rhs)) < old_num_ops))
3618 gimple_assign_set_rhs_from_tree (gsi, new_rhs);
3619 changed = true;
3621 break;
3624 case GIMPLE_CALL:
3625 changed |= gimple_fold_call (gsi, inplace);
3626 break;
3628 case GIMPLE_ASM:
3629 /* Fold *& in asm operands. */
3631 gasm *asm_stmt = as_a <gasm *> (stmt);
3632 size_t noutputs;
3633 const char **oconstraints;
3634 const char *constraint;
3635 bool allows_mem, allows_reg;
3637 noutputs = gimple_asm_noutputs (asm_stmt);
3638 oconstraints = XALLOCAVEC (const char *, noutputs);
3640 for (i = 0; i < gimple_asm_noutputs (asm_stmt); ++i)
3642 tree link = gimple_asm_output_op (asm_stmt, i);
3643 tree op = TREE_VALUE (link);
3644 oconstraints[i]
3645 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
3646 if (REFERENCE_CLASS_P (op)
3647 && (op = maybe_fold_reference (op, true)) != NULL_TREE)
3649 TREE_VALUE (link) = op;
3650 changed = true;
3653 for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
3655 tree link = gimple_asm_input_op (asm_stmt, i);
3656 tree op = TREE_VALUE (link);
3657 constraint
3658 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
3659 parse_input_constraint (&constraint, 0, 0, noutputs, 0,
3660 oconstraints, &allows_mem, &allows_reg);
3661 if (REFERENCE_CLASS_P (op)
3662 && (op = maybe_fold_reference (op, !allows_reg && allows_mem))
3663 != NULL_TREE)
3665 TREE_VALUE (link) = op;
3666 changed = true;
3670 break;
3672 case GIMPLE_DEBUG:
3673 if (gimple_debug_bind_p (stmt))
3675 tree val = gimple_debug_bind_get_value (stmt);
3676 if (val
3677 && REFERENCE_CLASS_P (val))
3679 tree tem = maybe_fold_reference (val, false);
3680 if (tem)
3682 gimple_debug_bind_set_value (stmt, tem);
3683 changed = true;
3686 else if (val
3687 && TREE_CODE (val) == ADDR_EXPR)
3689 tree ref = TREE_OPERAND (val, 0);
3690 tree tem = maybe_fold_reference (ref, false);
3691 if (tem)
3693 tem = build_fold_addr_expr_with_type (tem, TREE_TYPE (val));
3694 gimple_debug_bind_set_value (stmt, tem);
3695 changed = true;
3699 break;
3701 default:;
3704 stmt = gsi_stmt (*gsi);
3706 /* Fold *& on the lhs. */
3707 if (gimple_has_lhs (stmt))
3709 tree lhs = gimple_get_lhs (stmt);
3710 if (lhs && REFERENCE_CLASS_P (lhs))
3712 tree new_lhs = maybe_fold_reference (lhs, true);
3713 if (new_lhs)
3715 gimple_set_lhs (stmt, new_lhs);
3716 changed = true;
3721 return changed;
3724 /* Valueziation callback that ends up not following SSA edges. */
3726 tree
3727 no_follow_ssa_edges (tree)
3729 return NULL_TREE;
3732 /* Valueization callback that ends up following single-use SSA edges only. */
3734 tree
3735 follow_single_use_edges (tree val)
3737 if (TREE_CODE (val) == SSA_NAME
3738 && !has_single_use (val))
3739 return NULL_TREE;
3740 return val;
3743 /* Fold the statement pointed to by GSI. In some cases, this function may
3744 replace the whole statement with a new one. Returns true iff folding
3745 makes any changes.
3746 The statement pointed to by GSI should be in valid gimple form but may
3747 be in unfolded state as resulting from for example constant propagation
3748 which can produce *&x = 0. */
3750 bool
3751 fold_stmt (gimple_stmt_iterator *gsi)
3753 return fold_stmt_1 (gsi, false, no_follow_ssa_edges);
3756 bool
3757 fold_stmt (gimple_stmt_iterator *gsi, tree (*valueize) (tree))
3759 return fold_stmt_1 (gsi, false, valueize);
3762 /* Perform the minimal folding on statement *GSI. Only operations like
3763 *&x created by constant propagation are handled. The statement cannot
3764 be replaced with a new one. Return true if the statement was
3765 changed, false otherwise.
3766 The statement *GSI should be in valid gimple form but may
3767 be in unfolded state as resulting from for example constant propagation
3768 which can produce *&x = 0. */
3770 bool
3771 fold_stmt_inplace (gimple_stmt_iterator *gsi)
3773 gimple stmt = gsi_stmt (*gsi);
3774 bool changed = fold_stmt_1 (gsi, true, no_follow_ssa_edges);
3775 gcc_assert (gsi_stmt (*gsi) == stmt);
3776 return changed;
3779 /* Canonicalize and possibly invert the boolean EXPR; return NULL_TREE
3780 if EXPR is null or we don't know how.
3781 If non-null, the result always has boolean type. */
3783 static tree
3784 canonicalize_bool (tree expr, bool invert)
3786 if (!expr)
3787 return NULL_TREE;
3788 else if (invert)
3790 if (integer_nonzerop (expr))
3791 return boolean_false_node;
3792 else if (integer_zerop (expr))
3793 return boolean_true_node;
3794 else if (TREE_CODE (expr) == SSA_NAME)
3795 return fold_build2 (EQ_EXPR, boolean_type_node, expr,
3796 build_int_cst (TREE_TYPE (expr), 0));
3797 else if (COMPARISON_CLASS_P (expr))
3798 return fold_build2 (invert_tree_comparison (TREE_CODE (expr), false),
3799 boolean_type_node,
3800 TREE_OPERAND (expr, 0),
3801 TREE_OPERAND (expr, 1));
3802 else
3803 return NULL_TREE;
3805 else
3807 if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE)
3808 return expr;
3809 if (integer_nonzerop (expr))
3810 return boolean_true_node;
3811 else if (integer_zerop (expr))
3812 return boolean_false_node;
3813 else if (TREE_CODE (expr) == SSA_NAME)
3814 return fold_build2 (NE_EXPR, boolean_type_node, expr,
3815 build_int_cst (TREE_TYPE (expr), 0));
3816 else if (COMPARISON_CLASS_P (expr))
3817 return fold_build2 (TREE_CODE (expr),
3818 boolean_type_node,
3819 TREE_OPERAND (expr, 0),
3820 TREE_OPERAND (expr, 1));
3821 else
3822 return NULL_TREE;
3826 /* Check to see if a boolean expression EXPR is logically equivalent to the
3827 comparison (OP1 CODE OP2). Check for various identities involving
3828 SSA_NAMEs. */
3830 static bool
3831 same_bool_comparison_p (const_tree expr, enum tree_code code,
3832 const_tree op1, const_tree op2)
3834 gimple s;
3836 /* The obvious case. */
3837 if (TREE_CODE (expr) == code
3838 && operand_equal_p (TREE_OPERAND (expr, 0), op1, 0)
3839 && operand_equal_p (TREE_OPERAND (expr, 1), op2, 0))
3840 return true;
3842 /* Check for comparing (name, name != 0) and the case where expr
3843 is an SSA_NAME with a definition matching the comparison. */
3844 if (TREE_CODE (expr) == SSA_NAME
3845 && TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE)
3847 if (operand_equal_p (expr, op1, 0))
3848 return ((code == NE_EXPR && integer_zerop (op2))
3849 || (code == EQ_EXPR && integer_nonzerop (op2)));
3850 s = SSA_NAME_DEF_STMT (expr);
3851 if (is_gimple_assign (s)
3852 && gimple_assign_rhs_code (s) == code
3853 && operand_equal_p (gimple_assign_rhs1 (s), op1, 0)
3854 && operand_equal_p (gimple_assign_rhs2 (s), op2, 0))
3855 return true;
3858 /* If op1 is of the form (name != 0) or (name == 0), and the definition
3859 of name is a comparison, recurse. */
3860 if (TREE_CODE (op1) == SSA_NAME
3861 && TREE_CODE (TREE_TYPE (op1)) == BOOLEAN_TYPE)
3863 s = SSA_NAME_DEF_STMT (op1);
3864 if (is_gimple_assign (s)
3865 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison)
3867 enum tree_code c = gimple_assign_rhs_code (s);
3868 if ((c == NE_EXPR && integer_zerop (op2))
3869 || (c == EQ_EXPR && integer_nonzerop (op2)))
3870 return same_bool_comparison_p (expr, c,
3871 gimple_assign_rhs1 (s),
3872 gimple_assign_rhs2 (s));
3873 if ((c == EQ_EXPR && integer_zerop (op2))
3874 || (c == NE_EXPR && integer_nonzerop (op2)))
3875 return same_bool_comparison_p (expr,
3876 invert_tree_comparison (c, false),
3877 gimple_assign_rhs1 (s),
3878 gimple_assign_rhs2 (s));
3881 return false;
3884 /* Check to see if two boolean expressions OP1 and OP2 are logically
3885 equivalent. */
3887 static bool
3888 same_bool_result_p (const_tree op1, const_tree op2)
3890 /* Simple cases first. */
3891 if (operand_equal_p (op1, op2, 0))
3892 return true;
3894 /* Check the cases where at least one of the operands is a comparison.
3895 These are a bit smarter than operand_equal_p in that they apply some
3896 identifies on SSA_NAMEs. */
3897 if (COMPARISON_CLASS_P (op2)
3898 && same_bool_comparison_p (op1, TREE_CODE (op2),
3899 TREE_OPERAND (op2, 0),
3900 TREE_OPERAND (op2, 1)))
3901 return true;
3902 if (COMPARISON_CLASS_P (op1)
3903 && same_bool_comparison_p (op2, TREE_CODE (op1),
3904 TREE_OPERAND (op1, 0),
3905 TREE_OPERAND (op1, 1)))
3906 return true;
3908 /* Default case. */
3909 return false;
3912 /* Forward declarations for some mutually recursive functions. */
3914 static tree
3915 and_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
3916 enum tree_code code2, tree op2a, tree op2b);
3917 static tree
3918 and_var_with_comparison (tree var, bool invert,
3919 enum tree_code code2, tree op2a, tree op2b);
3920 static tree
3921 and_var_with_comparison_1 (gimple stmt,
3922 enum tree_code code2, tree op2a, tree op2b);
3923 static tree
3924 or_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
3925 enum tree_code code2, tree op2a, tree op2b);
3926 static tree
3927 or_var_with_comparison (tree var, bool invert,
3928 enum tree_code code2, tree op2a, tree op2b);
3929 static tree
3930 or_var_with_comparison_1 (gimple stmt,
3931 enum tree_code code2, tree op2a, tree op2b);
3933 /* Helper function for and_comparisons_1: try to simplify the AND of the
3934 ssa variable VAR with the comparison specified by (OP2A CODE2 OP2B).
3935 If INVERT is true, invert the value of the VAR before doing the AND.
3936 Return NULL_EXPR if we can't simplify this to a single expression. */
3938 static tree
3939 and_var_with_comparison (tree var, bool invert,
3940 enum tree_code code2, tree op2a, tree op2b)
3942 tree t;
3943 gimple stmt = SSA_NAME_DEF_STMT (var);
3945 /* We can only deal with variables whose definitions are assignments. */
3946 if (!is_gimple_assign (stmt))
3947 return NULL_TREE;
3949 /* If we have an inverted comparison, apply DeMorgan's law and rewrite
3950 !var AND (op2a code2 op2b) => !(var OR !(op2a code2 op2b))
3951 Then we only have to consider the simpler non-inverted cases. */
3952 if (invert)
3953 t = or_var_with_comparison_1 (stmt,
3954 invert_tree_comparison (code2, false),
3955 op2a, op2b);
3956 else
3957 t = and_var_with_comparison_1 (stmt, code2, op2a, op2b);
3958 return canonicalize_bool (t, invert);
3961 /* Try to simplify the AND of the ssa variable defined by the assignment
3962 STMT with the comparison specified by (OP2A CODE2 OP2B).
3963 Return NULL_EXPR if we can't simplify this to a single expression. */
3965 static tree
3966 and_var_with_comparison_1 (gimple stmt,
3967 enum tree_code code2, tree op2a, tree op2b)
3969 tree var = gimple_assign_lhs (stmt);
3970 tree true_test_var = NULL_TREE;
3971 tree false_test_var = NULL_TREE;
3972 enum tree_code innercode = gimple_assign_rhs_code (stmt);
3974 /* Check for identities like (var AND (var == 0)) => false. */
3975 if (TREE_CODE (op2a) == SSA_NAME
3976 && TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE)
3978 if ((code2 == NE_EXPR && integer_zerop (op2b))
3979 || (code2 == EQ_EXPR && integer_nonzerop (op2b)))
3981 true_test_var = op2a;
3982 if (var == true_test_var)
3983 return var;
3985 else if ((code2 == EQ_EXPR && integer_zerop (op2b))
3986 || (code2 == NE_EXPR && integer_nonzerop (op2b)))
3988 false_test_var = op2a;
3989 if (var == false_test_var)
3990 return boolean_false_node;
3994 /* If the definition is a comparison, recurse on it. */
3995 if (TREE_CODE_CLASS (innercode) == tcc_comparison)
3997 tree t = and_comparisons_1 (innercode,
3998 gimple_assign_rhs1 (stmt),
3999 gimple_assign_rhs2 (stmt),
4000 code2,
4001 op2a,
4002 op2b);
4003 if (t)
4004 return t;
4007 /* If the definition is an AND or OR expression, we may be able to
4008 simplify by reassociating. */
4009 if (TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE
4010 && (innercode == BIT_AND_EXPR || innercode == BIT_IOR_EXPR))
4012 tree inner1 = gimple_assign_rhs1 (stmt);
4013 tree inner2 = gimple_assign_rhs2 (stmt);
4014 gimple s;
4015 tree t;
4016 tree partial = NULL_TREE;
4017 bool is_and = (innercode == BIT_AND_EXPR);
4019 /* Check for boolean identities that don't require recursive examination
4020 of inner1/inner2:
4021 inner1 AND (inner1 AND inner2) => inner1 AND inner2 => var
4022 inner1 AND (inner1 OR inner2) => inner1
4023 !inner1 AND (inner1 AND inner2) => false
4024 !inner1 AND (inner1 OR inner2) => !inner1 AND inner2
4025 Likewise for similar cases involving inner2. */
4026 if (inner1 == true_test_var)
4027 return (is_and ? var : inner1);
4028 else if (inner2 == true_test_var)
4029 return (is_and ? var : inner2);
4030 else if (inner1 == false_test_var)
4031 return (is_and
4032 ? boolean_false_node
4033 : and_var_with_comparison (inner2, false, code2, op2a, op2b));
4034 else if (inner2 == false_test_var)
4035 return (is_and
4036 ? boolean_false_node
4037 : and_var_with_comparison (inner1, false, code2, op2a, op2b));
4039 /* Next, redistribute/reassociate the AND across the inner tests.
4040 Compute the first partial result, (inner1 AND (op2a code op2b)) */
4041 if (TREE_CODE (inner1) == SSA_NAME
4042 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner1))
4043 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
4044 && (t = maybe_fold_and_comparisons (gimple_assign_rhs_code (s),
4045 gimple_assign_rhs1 (s),
4046 gimple_assign_rhs2 (s),
4047 code2, op2a, op2b)))
4049 /* Handle the AND case, where we are reassociating:
4050 (inner1 AND inner2) AND (op2a code2 op2b)
4051 => (t AND inner2)
4052 If the partial result t is a constant, we win. Otherwise
4053 continue on to try reassociating with the other inner test. */
4054 if (is_and)
4056 if (integer_onep (t))
4057 return inner2;
4058 else if (integer_zerop (t))
4059 return boolean_false_node;
4062 /* Handle the OR case, where we are redistributing:
4063 (inner1 OR inner2) AND (op2a code2 op2b)
4064 => (t OR (inner2 AND (op2a code2 op2b))) */
4065 else if (integer_onep (t))
4066 return boolean_true_node;
4068 /* Save partial result for later. */
4069 partial = t;
4072 /* Compute the second partial result, (inner2 AND (op2a code op2b)) */
4073 if (TREE_CODE (inner2) == SSA_NAME
4074 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner2))
4075 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
4076 && (t = maybe_fold_and_comparisons (gimple_assign_rhs_code (s),
4077 gimple_assign_rhs1 (s),
4078 gimple_assign_rhs2 (s),
4079 code2, op2a, op2b)))
4081 /* Handle the AND case, where we are reassociating:
4082 (inner1 AND inner2) AND (op2a code2 op2b)
4083 => (inner1 AND t) */
4084 if (is_and)
4086 if (integer_onep (t))
4087 return inner1;
4088 else if (integer_zerop (t))
4089 return boolean_false_node;
4090 /* If both are the same, we can apply the identity
4091 (x AND x) == x. */
4092 else if (partial && same_bool_result_p (t, partial))
4093 return t;
4096 /* Handle the OR case. where we are redistributing:
4097 (inner1 OR inner2) AND (op2a code2 op2b)
4098 => (t OR (inner1 AND (op2a code2 op2b)))
4099 => (t OR partial) */
4100 else
4102 if (integer_onep (t))
4103 return boolean_true_node;
4104 else if (partial)
4106 /* We already got a simplification for the other
4107 operand to the redistributed OR expression. The
4108 interesting case is when at least one is false.
4109 Or, if both are the same, we can apply the identity
4110 (x OR x) == x. */
4111 if (integer_zerop (partial))
4112 return t;
4113 else if (integer_zerop (t))
4114 return partial;
4115 else if (same_bool_result_p (t, partial))
4116 return t;
4121 return NULL_TREE;
4124 /* Try to simplify the AND of two comparisons defined by
4125 (OP1A CODE1 OP1B) and (OP2A CODE2 OP2B), respectively.
4126 If this can be done without constructing an intermediate value,
4127 return the resulting tree; otherwise NULL_TREE is returned.
4128 This function is deliberately asymmetric as it recurses on SSA_DEFs
4129 in the first comparison but not the second. */
4131 static tree
4132 and_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
4133 enum tree_code code2, tree op2a, tree op2b)
4135 tree truth_type = truth_type_for (TREE_TYPE (op1a));
4137 /* First check for ((x CODE1 y) AND (x CODE2 y)). */
4138 if (operand_equal_p (op1a, op2a, 0)
4139 && operand_equal_p (op1b, op2b, 0))
4141 /* Result will be either NULL_TREE, or a combined comparison. */
4142 tree t = combine_comparisons (UNKNOWN_LOCATION,
4143 TRUTH_ANDIF_EXPR, code1, code2,
4144 truth_type, op1a, op1b);
4145 if (t)
4146 return t;
4149 /* Likewise the swapped case of the above. */
4150 if (operand_equal_p (op1a, op2b, 0)
4151 && operand_equal_p (op1b, op2a, 0))
4153 /* Result will be either NULL_TREE, or a combined comparison. */
4154 tree t = combine_comparisons (UNKNOWN_LOCATION,
4155 TRUTH_ANDIF_EXPR, code1,
4156 swap_tree_comparison (code2),
4157 truth_type, op1a, op1b);
4158 if (t)
4159 return t;
4162 /* If both comparisons are of the same value against constants, we might
4163 be able to merge them. */
4164 if (operand_equal_p (op1a, op2a, 0)
4165 && TREE_CODE (op1b) == INTEGER_CST
4166 && TREE_CODE (op2b) == INTEGER_CST)
4168 int cmp = tree_int_cst_compare (op1b, op2b);
4170 /* If we have (op1a == op1b), we should either be able to
4171 return that or FALSE, depending on whether the constant op1b
4172 also satisfies the other comparison against op2b. */
4173 if (code1 == EQ_EXPR)
4175 bool done = true;
4176 bool val;
4177 switch (code2)
4179 case EQ_EXPR: val = (cmp == 0); break;
4180 case NE_EXPR: val = (cmp != 0); break;
4181 case LT_EXPR: val = (cmp < 0); break;
4182 case GT_EXPR: val = (cmp > 0); break;
4183 case LE_EXPR: val = (cmp <= 0); break;
4184 case GE_EXPR: val = (cmp >= 0); break;
4185 default: done = false;
4187 if (done)
4189 if (val)
4190 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4191 else
4192 return boolean_false_node;
4195 /* Likewise if the second comparison is an == comparison. */
4196 else if (code2 == EQ_EXPR)
4198 bool done = true;
4199 bool val;
4200 switch (code1)
4202 case EQ_EXPR: val = (cmp == 0); break;
4203 case NE_EXPR: val = (cmp != 0); break;
4204 case LT_EXPR: val = (cmp > 0); break;
4205 case GT_EXPR: val = (cmp < 0); break;
4206 case LE_EXPR: val = (cmp >= 0); break;
4207 case GE_EXPR: val = (cmp <= 0); break;
4208 default: done = false;
4210 if (done)
4212 if (val)
4213 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4214 else
4215 return boolean_false_node;
4219 /* Same business with inequality tests. */
4220 else if (code1 == NE_EXPR)
4222 bool val;
4223 switch (code2)
4225 case EQ_EXPR: val = (cmp != 0); break;
4226 case NE_EXPR: val = (cmp == 0); break;
4227 case LT_EXPR: val = (cmp >= 0); break;
4228 case GT_EXPR: val = (cmp <= 0); break;
4229 case LE_EXPR: val = (cmp > 0); break;
4230 case GE_EXPR: val = (cmp < 0); break;
4231 default:
4232 val = false;
4234 if (val)
4235 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4237 else if (code2 == NE_EXPR)
4239 bool val;
4240 switch (code1)
4242 case EQ_EXPR: val = (cmp == 0); break;
4243 case NE_EXPR: val = (cmp != 0); break;
4244 case LT_EXPR: val = (cmp <= 0); break;
4245 case GT_EXPR: val = (cmp >= 0); break;
4246 case LE_EXPR: val = (cmp < 0); break;
4247 case GE_EXPR: val = (cmp > 0); break;
4248 default:
4249 val = false;
4251 if (val)
4252 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4255 /* Chose the more restrictive of two < or <= comparisons. */
4256 else if ((code1 == LT_EXPR || code1 == LE_EXPR)
4257 && (code2 == LT_EXPR || code2 == LE_EXPR))
4259 if ((cmp < 0) || (cmp == 0 && code1 == LT_EXPR))
4260 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4261 else
4262 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4265 /* Likewise chose the more restrictive of two > or >= comparisons. */
4266 else if ((code1 == GT_EXPR || code1 == GE_EXPR)
4267 && (code2 == GT_EXPR || code2 == GE_EXPR))
4269 if ((cmp > 0) || (cmp == 0 && code1 == GT_EXPR))
4270 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4271 else
4272 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4275 /* Check for singleton ranges. */
4276 else if (cmp == 0
4277 && ((code1 == LE_EXPR && code2 == GE_EXPR)
4278 || (code1 == GE_EXPR && code2 == LE_EXPR)))
4279 return fold_build2 (EQ_EXPR, boolean_type_node, op1a, op2b);
4281 /* Check for disjoint ranges. */
4282 else if (cmp <= 0
4283 && (code1 == LT_EXPR || code1 == LE_EXPR)
4284 && (code2 == GT_EXPR || code2 == GE_EXPR))
4285 return boolean_false_node;
4286 else if (cmp >= 0
4287 && (code1 == GT_EXPR || code1 == GE_EXPR)
4288 && (code2 == LT_EXPR || code2 == LE_EXPR))
4289 return boolean_false_node;
4292 /* Perhaps the first comparison is (NAME != 0) or (NAME == 1) where
4293 NAME's definition is a truth value. See if there are any simplifications
4294 that can be done against the NAME's definition. */
4295 if (TREE_CODE (op1a) == SSA_NAME
4296 && (code1 == NE_EXPR || code1 == EQ_EXPR)
4297 && (integer_zerop (op1b) || integer_onep (op1b)))
4299 bool invert = ((code1 == EQ_EXPR && integer_zerop (op1b))
4300 || (code1 == NE_EXPR && integer_onep (op1b)));
4301 gimple stmt = SSA_NAME_DEF_STMT (op1a);
4302 switch (gimple_code (stmt))
4304 case GIMPLE_ASSIGN:
4305 /* Try to simplify by copy-propagating the definition. */
4306 return and_var_with_comparison (op1a, invert, code2, op2a, op2b);
4308 case GIMPLE_PHI:
4309 /* If every argument to the PHI produces the same result when
4310 ANDed with the second comparison, we win.
4311 Do not do this unless the type is bool since we need a bool
4312 result here anyway. */
4313 if (TREE_CODE (TREE_TYPE (op1a)) == BOOLEAN_TYPE)
4315 tree result = NULL_TREE;
4316 unsigned i;
4317 for (i = 0; i < gimple_phi_num_args (stmt); i++)
4319 tree arg = gimple_phi_arg_def (stmt, i);
4321 /* If this PHI has itself as an argument, ignore it.
4322 If all the other args produce the same result,
4323 we're still OK. */
4324 if (arg == gimple_phi_result (stmt))
4325 continue;
4326 else if (TREE_CODE (arg) == INTEGER_CST)
4328 if (invert ? integer_nonzerop (arg) : integer_zerop (arg))
4330 if (!result)
4331 result = boolean_false_node;
4332 else if (!integer_zerop (result))
4333 return NULL_TREE;
4335 else if (!result)
4336 result = fold_build2 (code2, boolean_type_node,
4337 op2a, op2b);
4338 else if (!same_bool_comparison_p (result,
4339 code2, op2a, op2b))
4340 return NULL_TREE;
4342 else if (TREE_CODE (arg) == SSA_NAME
4343 && !SSA_NAME_IS_DEFAULT_DEF (arg))
4345 tree temp;
4346 gimple def_stmt = SSA_NAME_DEF_STMT (arg);
4347 /* In simple cases we can look through PHI nodes,
4348 but we have to be careful with loops.
4349 See PR49073. */
4350 if (! dom_info_available_p (CDI_DOMINATORS)
4351 || gimple_bb (def_stmt) == gimple_bb (stmt)
4352 || dominated_by_p (CDI_DOMINATORS,
4353 gimple_bb (def_stmt),
4354 gimple_bb (stmt)))
4355 return NULL_TREE;
4356 temp = and_var_with_comparison (arg, invert, code2,
4357 op2a, op2b);
4358 if (!temp)
4359 return NULL_TREE;
4360 else if (!result)
4361 result = temp;
4362 else if (!same_bool_result_p (result, temp))
4363 return NULL_TREE;
4365 else
4366 return NULL_TREE;
4368 return result;
4371 default:
4372 break;
4375 return NULL_TREE;
4378 /* Try to simplify the AND of two comparisons, specified by
4379 (OP1A CODE1 OP1B) and (OP2B CODE2 OP2B), respectively.
4380 If this can be simplified to a single expression (without requiring
4381 introducing more SSA variables to hold intermediate values),
4382 return the resulting tree. Otherwise return NULL_TREE.
4383 If the result expression is non-null, it has boolean type. */
4385 tree
4386 maybe_fold_and_comparisons (enum tree_code code1, tree op1a, tree op1b,
4387 enum tree_code code2, tree op2a, tree op2b)
4389 tree t = and_comparisons_1 (code1, op1a, op1b, code2, op2a, op2b);
4390 if (t)
4391 return t;
4392 else
4393 return and_comparisons_1 (code2, op2a, op2b, code1, op1a, op1b);
4396 /* Helper function for or_comparisons_1: try to simplify the OR of the
4397 ssa variable VAR with the comparison specified by (OP2A CODE2 OP2B).
4398 If INVERT is true, invert the value of VAR before doing the OR.
4399 Return NULL_EXPR if we can't simplify this to a single expression. */
4401 static tree
4402 or_var_with_comparison (tree var, bool invert,
4403 enum tree_code code2, tree op2a, tree op2b)
4405 tree t;
4406 gimple stmt = SSA_NAME_DEF_STMT (var);
4408 /* We can only deal with variables whose definitions are assignments. */
4409 if (!is_gimple_assign (stmt))
4410 return NULL_TREE;
4412 /* If we have an inverted comparison, apply DeMorgan's law and rewrite
4413 !var OR (op2a code2 op2b) => !(var AND !(op2a code2 op2b))
4414 Then we only have to consider the simpler non-inverted cases. */
4415 if (invert)
4416 t = and_var_with_comparison_1 (stmt,
4417 invert_tree_comparison (code2, false),
4418 op2a, op2b);
4419 else
4420 t = or_var_with_comparison_1 (stmt, code2, op2a, op2b);
4421 return canonicalize_bool (t, invert);
4424 /* Try to simplify the OR of the ssa variable defined by the assignment
4425 STMT with the comparison specified by (OP2A CODE2 OP2B).
4426 Return NULL_EXPR if we can't simplify this to a single expression. */
4428 static tree
4429 or_var_with_comparison_1 (gimple stmt,
4430 enum tree_code code2, tree op2a, tree op2b)
4432 tree var = gimple_assign_lhs (stmt);
4433 tree true_test_var = NULL_TREE;
4434 tree false_test_var = NULL_TREE;
4435 enum tree_code innercode = gimple_assign_rhs_code (stmt);
4437 /* Check for identities like (var OR (var != 0)) => true . */
4438 if (TREE_CODE (op2a) == SSA_NAME
4439 && TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE)
4441 if ((code2 == NE_EXPR && integer_zerop (op2b))
4442 || (code2 == EQ_EXPR && integer_nonzerop (op2b)))
4444 true_test_var = op2a;
4445 if (var == true_test_var)
4446 return var;
4448 else if ((code2 == EQ_EXPR && integer_zerop (op2b))
4449 || (code2 == NE_EXPR && integer_nonzerop (op2b)))
4451 false_test_var = op2a;
4452 if (var == false_test_var)
4453 return boolean_true_node;
4457 /* If the definition is a comparison, recurse on it. */
4458 if (TREE_CODE_CLASS (innercode) == tcc_comparison)
4460 tree t = or_comparisons_1 (innercode,
4461 gimple_assign_rhs1 (stmt),
4462 gimple_assign_rhs2 (stmt),
4463 code2,
4464 op2a,
4465 op2b);
4466 if (t)
4467 return t;
4470 /* If the definition is an AND or OR expression, we may be able to
4471 simplify by reassociating. */
4472 if (TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE
4473 && (innercode == BIT_AND_EXPR || innercode == BIT_IOR_EXPR))
4475 tree inner1 = gimple_assign_rhs1 (stmt);
4476 tree inner2 = gimple_assign_rhs2 (stmt);
4477 gimple s;
4478 tree t;
4479 tree partial = NULL_TREE;
4480 bool is_or = (innercode == BIT_IOR_EXPR);
4482 /* Check for boolean identities that don't require recursive examination
4483 of inner1/inner2:
4484 inner1 OR (inner1 OR inner2) => inner1 OR inner2 => var
4485 inner1 OR (inner1 AND inner2) => inner1
4486 !inner1 OR (inner1 OR inner2) => true
4487 !inner1 OR (inner1 AND inner2) => !inner1 OR inner2
4489 if (inner1 == true_test_var)
4490 return (is_or ? var : inner1);
4491 else if (inner2 == true_test_var)
4492 return (is_or ? var : inner2);
4493 else if (inner1 == false_test_var)
4494 return (is_or
4495 ? boolean_true_node
4496 : or_var_with_comparison (inner2, false, code2, op2a, op2b));
4497 else if (inner2 == false_test_var)
4498 return (is_or
4499 ? boolean_true_node
4500 : or_var_with_comparison (inner1, false, code2, op2a, op2b));
4502 /* Next, redistribute/reassociate the OR across the inner tests.
4503 Compute the first partial result, (inner1 OR (op2a code op2b)) */
4504 if (TREE_CODE (inner1) == SSA_NAME
4505 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner1))
4506 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
4507 && (t = maybe_fold_or_comparisons (gimple_assign_rhs_code (s),
4508 gimple_assign_rhs1 (s),
4509 gimple_assign_rhs2 (s),
4510 code2, op2a, op2b)))
4512 /* Handle the OR case, where we are reassociating:
4513 (inner1 OR inner2) OR (op2a code2 op2b)
4514 => (t OR inner2)
4515 If the partial result t is a constant, we win. Otherwise
4516 continue on to try reassociating with the other inner test. */
4517 if (is_or)
4519 if (integer_onep (t))
4520 return boolean_true_node;
4521 else if (integer_zerop (t))
4522 return inner2;
4525 /* Handle the AND case, where we are redistributing:
4526 (inner1 AND inner2) OR (op2a code2 op2b)
4527 => (t AND (inner2 OR (op2a code op2b))) */
4528 else if (integer_zerop (t))
4529 return boolean_false_node;
4531 /* Save partial result for later. */
4532 partial = t;
4535 /* Compute the second partial result, (inner2 OR (op2a code op2b)) */
4536 if (TREE_CODE (inner2) == SSA_NAME
4537 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner2))
4538 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
4539 && (t = maybe_fold_or_comparisons (gimple_assign_rhs_code (s),
4540 gimple_assign_rhs1 (s),
4541 gimple_assign_rhs2 (s),
4542 code2, op2a, op2b)))
4544 /* Handle the OR case, where we are reassociating:
4545 (inner1 OR inner2) OR (op2a code2 op2b)
4546 => (inner1 OR t)
4547 => (t OR partial) */
4548 if (is_or)
4550 if (integer_zerop (t))
4551 return inner1;
4552 else if (integer_onep (t))
4553 return boolean_true_node;
4554 /* If both are the same, we can apply the identity
4555 (x OR x) == x. */
4556 else if (partial && same_bool_result_p (t, partial))
4557 return t;
4560 /* Handle the AND case, where we are redistributing:
4561 (inner1 AND inner2) OR (op2a code2 op2b)
4562 => (t AND (inner1 OR (op2a code2 op2b)))
4563 => (t AND partial) */
4564 else
4566 if (integer_zerop (t))
4567 return boolean_false_node;
4568 else if (partial)
4570 /* We already got a simplification for the other
4571 operand to the redistributed AND expression. The
4572 interesting case is when at least one is true.
4573 Or, if both are the same, we can apply the identity
4574 (x AND x) == x. */
4575 if (integer_onep (partial))
4576 return t;
4577 else if (integer_onep (t))
4578 return partial;
4579 else if (same_bool_result_p (t, partial))
4580 return t;
4585 return NULL_TREE;
4588 /* Try to simplify the OR of two comparisons defined by
4589 (OP1A CODE1 OP1B) and (OP2A CODE2 OP2B), respectively.
4590 If this can be done without constructing an intermediate value,
4591 return the resulting tree; otherwise NULL_TREE is returned.
4592 This function is deliberately asymmetric as it recurses on SSA_DEFs
4593 in the first comparison but not the second. */
4595 static tree
4596 or_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
4597 enum tree_code code2, tree op2a, tree op2b)
4599 tree truth_type = truth_type_for (TREE_TYPE (op1a));
4601 /* First check for ((x CODE1 y) OR (x CODE2 y)). */
4602 if (operand_equal_p (op1a, op2a, 0)
4603 && operand_equal_p (op1b, op2b, 0))
4605 /* Result will be either NULL_TREE, or a combined comparison. */
4606 tree t = combine_comparisons (UNKNOWN_LOCATION,
4607 TRUTH_ORIF_EXPR, code1, code2,
4608 truth_type, op1a, op1b);
4609 if (t)
4610 return t;
4613 /* Likewise the swapped case of the above. */
4614 if (operand_equal_p (op1a, op2b, 0)
4615 && operand_equal_p (op1b, op2a, 0))
4617 /* Result will be either NULL_TREE, or a combined comparison. */
4618 tree t = combine_comparisons (UNKNOWN_LOCATION,
4619 TRUTH_ORIF_EXPR, code1,
4620 swap_tree_comparison (code2),
4621 truth_type, op1a, op1b);
4622 if (t)
4623 return t;
4626 /* If both comparisons are of the same value against constants, we might
4627 be able to merge them. */
4628 if (operand_equal_p (op1a, op2a, 0)
4629 && TREE_CODE (op1b) == INTEGER_CST
4630 && TREE_CODE (op2b) == INTEGER_CST)
4632 int cmp = tree_int_cst_compare (op1b, op2b);
4634 /* If we have (op1a != op1b), we should either be able to
4635 return that or TRUE, depending on whether the constant op1b
4636 also satisfies the other comparison against op2b. */
4637 if (code1 == NE_EXPR)
4639 bool done = true;
4640 bool val;
4641 switch (code2)
4643 case EQ_EXPR: val = (cmp == 0); break;
4644 case NE_EXPR: val = (cmp != 0); break;
4645 case LT_EXPR: val = (cmp < 0); break;
4646 case GT_EXPR: val = (cmp > 0); break;
4647 case LE_EXPR: val = (cmp <= 0); break;
4648 case GE_EXPR: val = (cmp >= 0); break;
4649 default: done = false;
4651 if (done)
4653 if (val)
4654 return boolean_true_node;
4655 else
4656 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4659 /* Likewise if the second comparison is a != comparison. */
4660 else if (code2 == NE_EXPR)
4662 bool done = true;
4663 bool val;
4664 switch (code1)
4666 case EQ_EXPR: val = (cmp == 0); break;
4667 case NE_EXPR: val = (cmp != 0); break;
4668 case LT_EXPR: val = (cmp > 0); break;
4669 case GT_EXPR: val = (cmp < 0); break;
4670 case LE_EXPR: val = (cmp >= 0); break;
4671 case GE_EXPR: val = (cmp <= 0); break;
4672 default: done = false;
4674 if (done)
4676 if (val)
4677 return boolean_true_node;
4678 else
4679 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4683 /* See if an equality test is redundant with the other comparison. */
4684 else if (code1 == EQ_EXPR)
4686 bool val;
4687 switch (code2)
4689 case EQ_EXPR: val = (cmp == 0); break;
4690 case NE_EXPR: val = (cmp != 0); break;
4691 case LT_EXPR: val = (cmp < 0); break;
4692 case GT_EXPR: val = (cmp > 0); break;
4693 case LE_EXPR: val = (cmp <= 0); break;
4694 case GE_EXPR: val = (cmp >= 0); break;
4695 default:
4696 val = false;
4698 if (val)
4699 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4701 else if (code2 == EQ_EXPR)
4703 bool val;
4704 switch (code1)
4706 case EQ_EXPR: val = (cmp == 0); break;
4707 case NE_EXPR: val = (cmp != 0); break;
4708 case LT_EXPR: val = (cmp > 0); break;
4709 case GT_EXPR: val = (cmp < 0); break;
4710 case LE_EXPR: val = (cmp >= 0); break;
4711 case GE_EXPR: val = (cmp <= 0); break;
4712 default:
4713 val = false;
4715 if (val)
4716 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4719 /* Chose the less restrictive of two < or <= comparisons. */
4720 else if ((code1 == LT_EXPR || code1 == LE_EXPR)
4721 && (code2 == LT_EXPR || code2 == LE_EXPR))
4723 if ((cmp < 0) || (cmp == 0 && code1 == LT_EXPR))
4724 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4725 else
4726 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4729 /* Likewise chose the less restrictive of two > or >= comparisons. */
4730 else if ((code1 == GT_EXPR || code1 == GE_EXPR)
4731 && (code2 == GT_EXPR || code2 == GE_EXPR))
4733 if ((cmp > 0) || (cmp == 0 && code1 == GT_EXPR))
4734 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4735 else
4736 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4739 /* Check for singleton ranges. */
4740 else if (cmp == 0
4741 && ((code1 == LT_EXPR && code2 == GT_EXPR)
4742 || (code1 == GT_EXPR && code2 == LT_EXPR)))
4743 return fold_build2 (NE_EXPR, boolean_type_node, op1a, op2b);
4745 /* Check for less/greater pairs that don't restrict the range at all. */
4746 else if (cmp >= 0
4747 && (code1 == LT_EXPR || code1 == LE_EXPR)
4748 && (code2 == GT_EXPR || code2 == GE_EXPR))
4749 return boolean_true_node;
4750 else if (cmp <= 0
4751 && (code1 == GT_EXPR || code1 == GE_EXPR)
4752 && (code2 == LT_EXPR || code2 == LE_EXPR))
4753 return boolean_true_node;
4756 /* Perhaps the first comparison is (NAME != 0) or (NAME == 1) where
4757 NAME's definition is a truth value. See if there are any simplifications
4758 that can be done against the NAME's definition. */
4759 if (TREE_CODE (op1a) == SSA_NAME
4760 && (code1 == NE_EXPR || code1 == EQ_EXPR)
4761 && (integer_zerop (op1b) || integer_onep (op1b)))
4763 bool invert = ((code1 == EQ_EXPR && integer_zerop (op1b))
4764 || (code1 == NE_EXPR && integer_onep (op1b)));
4765 gimple stmt = SSA_NAME_DEF_STMT (op1a);
4766 switch (gimple_code (stmt))
4768 case GIMPLE_ASSIGN:
4769 /* Try to simplify by copy-propagating the definition. */
4770 return or_var_with_comparison (op1a, invert, code2, op2a, op2b);
4772 case GIMPLE_PHI:
4773 /* If every argument to the PHI produces the same result when
4774 ORed with the second comparison, we win.
4775 Do not do this unless the type is bool since we need a bool
4776 result here anyway. */
4777 if (TREE_CODE (TREE_TYPE (op1a)) == BOOLEAN_TYPE)
4779 tree result = NULL_TREE;
4780 unsigned i;
4781 for (i = 0; i < gimple_phi_num_args (stmt); i++)
4783 tree arg = gimple_phi_arg_def (stmt, i);
4785 /* If this PHI has itself as an argument, ignore it.
4786 If all the other args produce the same result,
4787 we're still OK. */
4788 if (arg == gimple_phi_result (stmt))
4789 continue;
4790 else if (TREE_CODE (arg) == INTEGER_CST)
4792 if (invert ? integer_zerop (arg) : integer_nonzerop (arg))
4794 if (!result)
4795 result = boolean_true_node;
4796 else if (!integer_onep (result))
4797 return NULL_TREE;
4799 else if (!result)
4800 result = fold_build2 (code2, boolean_type_node,
4801 op2a, op2b);
4802 else if (!same_bool_comparison_p (result,
4803 code2, op2a, op2b))
4804 return NULL_TREE;
4806 else if (TREE_CODE (arg) == SSA_NAME
4807 && !SSA_NAME_IS_DEFAULT_DEF (arg))
4809 tree temp;
4810 gimple def_stmt = SSA_NAME_DEF_STMT (arg);
4811 /* In simple cases we can look through PHI nodes,
4812 but we have to be careful with loops.
4813 See PR49073. */
4814 if (! dom_info_available_p (CDI_DOMINATORS)
4815 || gimple_bb (def_stmt) == gimple_bb (stmt)
4816 || dominated_by_p (CDI_DOMINATORS,
4817 gimple_bb (def_stmt),
4818 gimple_bb (stmt)))
4819 return NULL_TREE;
4820 temp = or_var_with_comparison (arg, invert, code2,
4821 op2a, op2b);
4822 if (!temp)
4823 return NULL_TREE;
4824 else if (!result)
4825 result = temp;
4826 else if (!same_bool_result_p (result, temp))
4827 return NULL_TREE;
4829 else
4830 return NULL_TREE;
4832 return result;
4835 default:
4836 break;
4839 return NULL_TREE;
4842 /* Try to simplify the OR of two comparisons, specified by
4843 (OP1A CODE1 OP1B) and (OP2B CODE2 OP2B), respectively.
4844 If this can be simplified to a single expression (without requiring
4845 introducing more SSA variables to hold intermediate values),
4846 return the resulting tree. Otherwise return NULL_TREE.
4847 If the result expression is non-null, it has boolean type. */
4849 tree
4850 maybe_fold_or_comparisons (enum tree_code code1, tree op1a, tree op1b,
4851 enum tree_code code2, tree op2a, tree op2b)
4853 tree t = or_comparisons_1 (code1, op1a, op1b, code2, op2a, op2b);
4854 if (t)
4855 return t;
4856 else
4857 return or_comparisons_1 (code2, op2a, op2b, code1, op1a, op1b);
4861 /* Fold STMT to a constant using VALUEIZE to valueize SSA names.
4863 Either NULL_TREE, a simplified but non-constant or a constant
4864 is returned.
4866 ??? This should go into a gimple-fold-inline.h file to be eventually
4867 privatized with the single valueize function used in the various TUs
4868 to avoid the indirect function call overhead. */
4870 tree
4871 gimple_fold_stmt_to_constant_1 (gimple stmt, tree (*valueize) (tree),
4872 tree (*gvalueize) (tree))
4874 code_helper rcode;
4875 tree ops[3] = {};
4876 /* ??? The SSA propagators do not correctly deal with following SSA use-def
4877 edges if there are intermediate VARYING defs. For this reason
4878 do not follow SSA edges here even though SCCVN can technically
4879 just deal fine with that. */
4880 if (gimple_simplify (stmt, &rcode, ops, NULL, gvalueize, valueize)
4881 && rcode.is_tree_code ()
4882 && (TREE_CODE_LENGTH ((tree_code) rcode) == 0
4883 || ((tree_code) rcode) == ADDR_EXPR)
4884 && is_gimple_val (ops[0]))
4886 tree res = ops[0];
4887 if (dump_file && dump_flags & TDF_DETAILS)
4889 fprintf (dump_file, "Match-and-simplified ");
4890 print_gimple_expr (dump_file, stmt, 0, TDF_SLIM);
4891 fprintf (dump_file, " to ");
4892 print_generic_expr (dump_file, res, 0);
4893 fprintf (dump_file, "\n");
4895 return res;
4898 location_t loc = gimple_location (stmt);
4899 switch (gimple_code (stmt))
4901 case GIMPLE_ASSIGN:
4903 enum tree_code subcode = gimple_assign_rhs_code (stmt);
4905 switch (get_gimple_rhs_class (subcode))
4907 case GIMPLE_SINGLE_RHS:
4909 tree rhs = gimple_assign_rhs1 (stmt);
4910 enum tree_code_class kind = TREE_CODE_CLASS (subcode);
4912 if (TREE_CODE (rhs) == SSA_NAME)
4914 /* If the RHS is an SSA_NAME, return its known constant value,
4915 if any. */
4916 return (*valueize) (rhs);
4918 /* Handle propagating invariant addresses into address
4919 operations. */
4920 else if (TREE_CODE (rhs) == ADDR_EXPR
4921 && !is_gimple_min_invariant (rhs))
4923 HOST_WIDE_INT offset = 0;
4924 tree base;
4925 base = get_addr_base_and_unit_offset_1 (TREE_OPERAND (rhs, 0),
4926 &offset,
4927 valueize);
4928 if (base
4929 && (CONSTANT_CLASS_P (base)
4930 || decl_address_invariant_p (base)))
4931 return build_invariant_address (TREE_TYPE (rhs),
4932 base, offset);
4934 else if (TREE_CODE (rhs) == CONSTRUCTOR
4935 && TREE_CODE (TREE_TYPE (rhs)) == VECTOR_TYPE
4936 && (CONSTRUCTOR_NELTS (rhs)
4937 == TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs))))
4939 unsigned i;
4940 tree val, *vec;
4942 vec = XALLOCAVEC (tree,
4943 TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs)));
4944 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), i, val)
4946 val = (*valueize) (val);
4947 if (TREE_CODE (val) == INTEGER_CST
4948 || TREE_CODE (val) == REAL_CST
4949 || TREE_CODE (val) == FIXED_CST)
4950 vec[i] = val;
4951 else
4952 return NULL_TREE;
4955 return build_vector (TREE_TYPE (rhs), vec);
4957 if (subcode == OBJ_TYPE_REF)
4959 tree val = (*valueize) (OBJ_TYPE_REF_EXPR (rhs));
4960 /* If callee is constant, we can fold away the wrapper. */
4961 if (is_gimple_min_invariant (val))
4962 return val;
4965 if (kind == tcc_reference)
4967 if ((TREE_CODE (rhs) == VIEW_CONVERT_EXPR
4968 || TREE_CODE (rhs) == REALPART_EXPR
4969 || TREE_CODE (rhs) == IMAGPART_EXPR)
4970 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
4972 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
4973 return fold_unary_loc (EXPR_LOCATION (rhs),
4974 TREE_CODE (rhs),
4975 TREE_TYPE (rhs), val);
4977 else if (TREE_CODE (rhs) == BIT_FIELD_REF
4978 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
4980 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
4981 return fold_ternary_loc (EXPR_LOCATION (rhs),
4982 TREE_CODE (rhs),
4983 TREE_TYPE (rhs), val,
4984 TREE_OPERAND (rhs, 1),
4985 TREE_OPERAND (rhs, 2));
4987 else if (TREE_CODE (rhs) == MEM_REF
4988 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
4990 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
4991 if (TREE_CODE (val) == ADDR_EXPR
4992 && is_gimple_min_invariant (val))
4994 tree tem = fold_build2 (MEM_REF, TREE_TYPE (rhs),
4995 unshare_expr (val),
4996 TREE_OPERAND (rhs, 1));
4997 if (tem)
4998 rhs = tem;
5001 return fold_const_aggregate_ref_1 (rhs, valueize);
5003 else if (kind == tcc_declaration)
5004 return get_symbol_constant_value (rhs);
5005 return rhs;
5008 case GIMPLE_UNARY_RHS:
5009 return NULL_TREE;
5011 case GIMPLE_BINARY_RHS:
5012 /* Translate &x + CST into an invariant form suitable for
5013 further propagation. */
5014 if (subcode == POINTER_PLUS_EXPR)
5016 tree op0 = (*valueize) (gimple_assign_rhs1 (stmt));
5017 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
5018 if (TREE_CODE (op0) == ADDR_EXPR
5019 && TREE_CODE (op1) == INTEGER_CST)
5021 tree off = fold_convert (ptr_type_node, op1);
5022 return build_fold_addr_expr_loc
5023 (loc,
5024 fold_build2 (MEM_REF,
5025 TREE_TYPE (TREE_TYPE (op0)),
5026 unshare_expr (op0), off));
5029 /* Canonicalize bool != 0 and bool == 0 appearing after
5030 valueization. While gimple_simplify handles this
5031 it can get confused by the ~X == 1 -> X == 0 transform
5032 which we cant reduce to a SSA name or a constant
5033 (and we have no way to tell gimple_simplify to not
5034 consider those transforms in the first place). */
5035 else if (subcode == EQ_EXPR
5036 || subcode == NE_EXPR)
5038 tree lhs = gimple_assign_lhs (stmt);
5039 tree op0 = gimple_assign_rhs1 (stmt);
5040 if (useless_type_conversion_p (TREE_TYPE (lhs),
5041 TREE_TYPE (op0)))
5043 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
5044 op0 = (*valueize) (op0);
5045 if (TREE_CODE (op0) == INTEGER_CST)
5046 std::swap (op0, op1);
5047 if (TREE_CODE (op1) == INTEGER_CST
5048 && ((subcode == NE_EXPR && integer_zerop (op1))
5049 || (subcode == EQ_EXPR && integer_onep (op1))))
5050 return op0;
5053 return NULL_TREE;
5055 case GIMPLE_TERNARY_RHS:
5057 /* Handle ternary operators that can appear in GIMPLE form. */
5058 tree op0 = (*valueize) (gimple_assign_rhs1 (stmt));
5059 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
5060 tree op2 = (*valueize) (gimple_assign_rhs3 (stmt));
5061 return fold_ternary_loc (loc, subcode,
5062 gimple_expr_type (stmt), op0, op1, op2);
5065 default:
5066 gcc_unreachable ();
5070 case GIMPLE_CALL:
5072 tree fn;
5073 gcall *call_stmt = as_a <gcall *> (stmt);
5075 if (gimple_call_internal_p (stmt))
5077 enum tree_code subcode = ERROR_MARK;
5078 switch (gimple_call_internal_fn (stmt))
5080 case IFN_UBSAN_CHECK_ADD:
5081 subcode = PLUS_EXPR;
5082 break;
5083 case IFN_UBSAN_CHECK_SUB:
5084 subcode = MINUS_EXPR;
5085 break;
5086 case IFN_UBSAN_CHECK_MUL:
5087 subcode = MULT_EXPR;
5088 break;
5089 default:
5090 return NULL_TREE;
5092 tree arg0 = gimple_call_arg (stmt, 0);
5093 tree arg1 = gimple_call_arg (stmt, 1);
5094 tree op0 = (*valueize) (arg0);
5095 tree op1 = (*valueize) (arg1);
5097 if (TREE_CODE (op0) != INTEGER_CST
5098 || TREE_CODE (op1) != INTEGER_CST)
5100 switch (subcode)
5102 case MULT_EXPR:
5103 /* x * 0 = 0 * x = 0 without overflow. */
5104 if (integer_zerop (op0) || integer_zerop (op1))
5105 return build_zero_cst (TREE_TYPE (arg0));
5106 break;
5107 case MINUS_EXPR:
5108 /* y - y = 0 without overflow. */
5109 if (operand_equal_p (op0, op1, 0))
5110 return build_zero_cst (TREE_TYPE (arg0));
5111 break;
5112 default:
5113 break;
5116 tree res
5117 = fold_binary_loc (loc, subcode, TREE_TYPE (arg0), op0, op1);
5118 if (res
5119 && TREE_CODE (res) == INTEGER_CST
5120 && !TREE_OVERFLOW (res))
5121 return res;
5122 return NULL_TREE;
5125 fn = (*valueize) (gimple_call_fn (stmt));
5126 if (TREE_CODE (fn) == ADDR_EXPR
5127 && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL
5128 && DECL_BUILT_IN (TREE_OPERAND (fn, 0))
5129 && gimple_builtin_call_types_compatible_p (stmt,
5130 TREE_OPERAND (fn, 0)))
5132 tree *args = XALLOCAVEC (tree, gimple_call_num_args (stmt));
5133 tree retval;
5134 unsigned i;
5135 for (i = 0; i < gimple_call_num_args (stmt); ++i)
5136 args[i] = (*valueize) (gimple_call_arg (stmt, i));
5137 retval = fold_builtin_call_array (loc,
5138 gimple_call_return_type (call_stmt),
5139 fn, gimple_call_num_args (stmt), args);
5140 if (retval)
5142 /* fold_call_expr wraps the result inside a NOP_EXPR. */
5143 STRIP_NOPS (retval);
5144 retval = fold_convert (gimple_call_return_type (call_stmt),
5145 retval);
5147 return retval;
5149 return NULL_TREE;
5152 default:
5153 return NULL_TREE;
5157 /* Fold STMT to a constant using VALUEIZE to valueize SSA names.
5158 Returns NULL_TREE if folding to a constant is not possible, otherwise
5159 returns a constant according to is_gimple_min_invariant. */
5161 tree
5162 gimple_fold_stmt_to_constant (gimple stmt, tree (*valueize) (tree))
5164 tree res = gimple_fold_stmt_to_constant_1 (stmt, valueize);
5165 if (res && is_gimple_min_invariant (res))
5166 return res;
5167 return NULL_TREE;
5171 /* The following set of functions are supposed to fold references using
5172 their constant initializers. */
5174 /* See if we can find constructor defining value of BASE.
5175 When we know the consructor with constant offset (such as
5176 base is array[40] and we do know constructor of array), then
5177 BIT_OFFSET is adjusted accordingly.
5179 As a special case, return error_mark_node when constructor
5180 is not explicitly available, but it is known to be zero
5181 such as 'static const int a;'. */
5182 static tree
5183 get_base_constructor (tree base, HOST_WIDE_INT *bit_offset,
5184 tree (*valueize)(tree))
5186 HOST_WIDE_INT bit_offset2, size, max_size;
5187 if (TREE_CODE (base) == MEM_REF)
5189 if (!integer_zerop (TREE_OPERAND (base, 1)))
5191 if (!tree_fits_shwi_p (TREE_OPERAND (base, 1)))
5192 return NULL_TREE;
5193 *bit_offset += (mem_ref_offset (base).to_short_addr ()
5194 * BITS_PER_UNIT);
5197 if (valueize
5198 && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
5199 base = valueize (TREE_OPERAND (base, 0));
5200 if (!base || TREE_CODE (base) != ADDR_EXPR)
5201 return NULL_TREE;
5202 base = TREE_OPERAND (base, 0);
5205 /* Get a CONSTRUCTOR. If BASE is a VAR_DECL, get its
5206 DECL_INITIAL. If BASE is a nested reference into another
5207 ARRAY_REF or COMPONENT_REF, make a recursive call to resolve
5208 the inner reference. */
5209 switch (TREE_CODE (base))
5211 case VAR_DECL:
5212 case CONST_DECL:
5214 tree init = ctor_for_folding (base);
5216 /* Our semantic is exact opposite of ctor_for_folding;
5217 NULL means unknown, while error_mark_node is 0. */
5218 if (init == error_mark_node)
5219 return NULL_TREE;
5220 if (!init)
5221 return error_mark_node;
5222 return init;
5225 case ARRAY_REF:
5226 case COMPONENT_REF:
5227 base = get_ref_base_and_extent (base, &bit_offset2, &size, &max_size);
5228 if (max_size == -1 || size != max_size)
5229 return NULL_TREE;
5230 *bit_offset += bit_offset2;
5231 return get_base_constructor (base, bit_offset, valueize);
5233 case STRING_CST:
5234 case CONSTRUCTOR:
5235 return base;
5237 default:
5238 return NULL_TREE;
5242 /* CTOR is CONSTRUCTOR of an array type. Fold reference of type TYPE and size
5243 SIZE to the memory at bit OFFSET. */
5245 static tree
5246 fold_array_ctor_reference (tree type, tree ctor,
5247 unsigned HOST_WIDE_INT offset,
5248 unsigned HOST_WIDE_INT size,
5249 tree from_decl)
5251 unsigned HOST_WIDE_INT cnt;
5252 tree cfield, cval;
5253 offset_int low_bound;
5254 offset_int elt_size;
5255 offset_int index, max_index;
5256 offset_int access_index;
5257 tree domain_type = NULL_TREE, index_type = NULL_TREE;
5258 HOST_WIDE_INT inner_offset;
5260 /* Compute low bound and elt size. */
5261 if (TREE_CODE (TREE_TYPE (ctor)) == ARRAY_TYPE)
5262 domain_type = TYPE_DOMAIN (TREE_TYPE (ctor));
5263 if (domain_type && TYPE_MIN_VALUE (domain_type))
5265 /* Static constructors for variably sized objects makes no sense. */
5266 gcc_assert (TREE_CODE (TYPE_MIN_VALUE (domain_type)) == INTEGER_CST);
5267 index_type = TREE_TYPE (TYPE_MIN_VALUE (domain_type));
5268 low_bound = wi::to_offset (TYPE_MIN_VALUE (domain_type));
5270 else
5271 low_bound = 0;
5272 /* Static constructors for variably sized objects makes no sense. */
5273 gcc_assert (TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (ctor))))
5274 == INTEGER_CST);
5275 elt_size = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (ctor))));
5277 /* We can handle only constantly sized accesses that are known to not
5278 be larger than size of array element. */
5279 if (!TYPE_SIZE_UNIT (type)
5280 || TREE_CODE (TYPE_SIZE_UNIT (type)) != INTEGER_CST
5281 || wi::lts_p (elt_size, wi::to_offset (TYPE_SIZE_UNIT (type)))
5282 || elt_size == 0)
5283 return NULL_TREE;
5285 /* Compute the array index we look for. */
5286 access_index = wi::udiv_trunc (offset_int (offset / BITS_PER_UNIT),
5287 elt_size);
5288 access_index += low_bound;
5289 if (index_type)
5290 access_index = wi::ext (access_index, TYPE_PRECISION (index_type),
5291 TYPE_SIGN (index_type));
5293 /* And offset within the access. */
5294 inner_offset = offset % (elt_size.to_uhwi () * BITS_PER_UNIT);
5296 /* See if the array field is large enough to span whole access. We do not
5297 care to fold accesses spanning multiple array indexes. */
5298 if (inner_offset + size > elt_size.to_uhwi () * BITS_PER_UNIT)
5299 return NULL_TREE;
5301 index = low_bound - 1;
5302 if (index_type)
5303 index = wi::ext (index, TYPE_PRECISION (index_type),
5304 TYPE_SIGN (index_type));
5306 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), cnt, cfield, cval)
5308 /* Array constructor might explicitely set index, or specify range
5309 or leave index NULL meaning that it is next index after previous
5310 one. */
5311 if (cfield)
5313 if (TREE_CODE (cfield) == INTEGER_CST)
5314 max_index = index = wi::to_offset (cfield);
5315 else
5317 gcc_assert (TREE_CODE (cfield) == RANGE_EXPR);
5318 index = wi::to_offset (TREE_OPERAND (cfield, 0));
5319 max_index = wi::to_offset (TREE_OPERAND (cfield, 1));
5322 else
5324 index += 1;
5325 if (index_type)
5326 index = wi::ext (index, TYPE_PRECISION (index_type),
5327 TYPE_SIGN (index_type));
5328 max_index = index;
5331 /* Do we have match? */
5332 if (wi::cmpu (access_index, index) >= 0
5333 && wi::cmpu (access_index, max_index) <= 0)
5334 return fold_ctor_reference (type, cval, inner_offset, size,
5335 from_decl);
5337 /* When memory is not explicitely mentioned in constructor,
5338 it is 0 (or out of range). */
5339 return build_zero_cst (type);
5342 /* CTOR is CONSTRUCTOR of an aggregate or vector.
5343 Fold reference of type TYPE and size SIZE to the memory at bit OFFSET. */
5345 static tree
5346 fold_nonarray_ctor_reference (tree type, tree ctor,
5347 unsigned HOST_WIDE_INT offset,
5348 unsigned HOST_WIDE_INT size,
5349 tree from_decl)
5351 unsigned HOST_WIDE_INT cnt;
5352 tree cfield, cval;
5354 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), cnt, cfield,
5355 cval)
5357 tree byte_offset = DECL_FIELD_OFFSET (cfield);
5358 tree field_offset = DECL_FIELD_BIT_OFFSET (cfield);
5359 tree field_size = DECL_SIZE (cfield);
5360 offset_int bitoffset;
5361 offset_int bitoffset_end, access_end;
5363 /* Variable sized objects in static constructors makes no sense,
5364 but field_size can be NULL for flexible array members. */
5365 gcc_assert (TREE_CODE (field_offset) == INTEGER_CST
5366 && TREE_CODE (byte_offset) == INTEGER_CST
5367 && (field_size != NULL_TREE
5368 ? TREE_CODE (field_size) == INTEGER_CST
5369 : TREE_CODE (TREE_TYPE (cfield)) == ARRAY_TYPE));
5371 /* Compute bit offset of the field. */
5372 bitoffset = (wi::to_offset (field_offset)
5373 + wi::lshift (wi::to_offset (byte_offset),
5374 LOG2_BITS_PER_UNIT));
5375 /* Compute bit offset where the field ends. */
5376 if (field_size != NULL_TREE)
5377 bitoffset_end = bitoffset + wi::to_offset (field_size);
5378 else
5379 bitoffset_end = 0;
5381 access_end = offset_int (offset) + size;
5383 /* Is there any overlap between [OFFSET, OFFSET+SIZE) and
5384 [BITOFFSET, BITOFFSET_END)? */
5385 if (wi::cmps (access_end, bitoffset) > 0
5386 && (field_size == NULL_TREE
5387 || wi::lts_p (offset, bitoffset_end)))
5389 offset_int inner_offset = offset_int (offset) - bitoffset;
5390 /* We do have overlap. Now see if field is large enough to
5391 cover the access. Give up for accesses spanning multiple
5392 fields. */
5393 if (wi::cmps (access_end, bitoffset_end) > 0)
5394 return NULL_TREE;
5395 if (wi::lts_p (offset, bitoffset))
5396 return NULL_TREE;
5397 return fold_ctor_reference (type, cval,
5398 inner_offset.to_uhwi (), size,
5399 from_decl);
5402 /* When memory is not explicitely mentioned in constructor, it is 0. */
5403 return build_zero_cst (type);
5406 /* CTOR is value initializing memory, fold reference of type TYPE and size SIZE
5407 to the memory at bit OFFSET. */
5409 tree
5410 fold_ctor_reference (tree type, tree ctor, unsigned HOST_WIDE_INT offset,
5411 unsigned HOST_WIDE_INT size, tree from_decl)
5413 tree ret;
5415 /* We found the field with exact match. */
5416 if (useless_type_conversion_p (type, TREE_TYPE (ctor))
5417 && !offset)
5418 return canonicalize_constructor_val (unshare_expr (ctor), from_decl);
5420 /* We are at the end of walk, see if we can view convert the
5421 result. */
5422 if (!AGGREGATE_TYPE_P (TREE_TYPE (ctor)) && !offset
5423 /* VIEW_CONVERT_EXPR is defined only for matching sizes. */
5424 && !compare_tree_int (TYPE_SIZE (type), size)
5425 && !compare_tree_int (TYPE_SIZE (TREE_TYPE (ctor)), size))
5427 ret = canonicalize_constructor_val (unshare_expr (ctor), from_decl);
5428 ret = fold_unary (VIEW_CONVERT_EXPR, type, ret);
5429 if (ret)
5430 STRIP_USELESS_TYPE_CONVERSION (ret);
5431 return ret;
5433 /* For constants and byte-aligned/sized reads try to go through
5434 native_encode/interpret. */
5435 if (CONSTANT_CLASS_P (ctor)
5436 && BITS_PER_UNIT == 8
5437 && offset % BITS_PER_UNIT == 0
5438 && size % BITS_PER_UNIT == 0
5439 && size <= MAX_BITSIZE_MODE_ANY_MODE)
5441 unsigned char buf[MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT];
5442 if (native_encode_expr (ctor, buf, size / BITS_PER_UNIT,
5443 offset / BITS_PER_UNIT) > 0)
5444 return native_interpret_expr (type, buf, size / BITS_PER_UNIT);
5446 if (TREE_CODE (ctor) == CONSTRUCTOR)
5449 if (TREE_CODE (TREE_TYPE (ctor)) == ARRAY_TYPE
5450 || TREE_CODE (TREE_TYPE (ctor)) == VECTOR_TYPE)
5451 return fold_array_ctor_reference (type, ctor, offset, size,
5452 from_decl);
5453 else
5454 return fold_nonarray_ctor_reference (type, ctor, offset, size,
5455 from_decl);
5458 return NULL_TREE;
5461 /* Return the tree representing the element referenced by T if T is an
5462 ARRAY_REF or COMPONENT_REF into constant aggregates valuezing SSA
5463 names using VALUEIZE. Return NULL_TREE otherwise. */
5465 tree
5466 fold_const_aggregate_ref_1 (tree t, tree (*valueize) (tree))
5468 tree ctor, idx, base;
5469 HOST_WIDE_INT offset, size, max_size;
5470 tree tem;
5472 if (TREE_THIS_VOLATILE (t))
5473 return NULL_TREE;
5475 if (DECL_P (t))
5476 return get_symbol_constant_value (t);
5478 tem = fold_read_from_constant_string (t);
5479 if (tem)
5480 return tem;
5482 switch (TREE_CODE (t))
5484 case ARRAY_REF:
5485 case ARRAY_RANGE_REF:
5486 /* Constant indexes are handled well by get_base_constructor.
5487 Only special case variable offsets.
5488 FIXME: This code can't handle nested references with variable indexes
5489 (they will be handled only by iteration of ccp). Perhaps we can bring
5490 get_ref_base_and_extent here and make it use a valueize callback. */
5491 if (TREE_CODE (TREE_OPERAND (t, 1)) == SSA_NAME
5492 && valueize
5493 && (idx = (*valueize) (TREE_OPERAND (t, 1)))
5494 && TREE_CODE (idx) == INTEGER_CST)
5496 tree low_bound, unit_size;
5498 /* If the resulting bit-offset is constant, track it. */
5499 if ((low_bound = array_ref_low_bound (t),
5500 TREE_CODE (low_bound) == INTEGER_CST)
5501 && (unit_size = array_ref_element_size (t),
5502 tree_fits_uhwi_p (unit_size)))
5504 offset_int woffset
5505 = wi::sext (wi::to_offset (idx) - wi::to_offset (low_bound),
5506 TYPE_PRECISION (TREE_TYPE (idx)));
5508 if (wi::fits_shwi_p (woffset))
5510 offset = woffset.to_shwi ();
5511 /* TODO: This code seems wrong, multiply then check
5512 to see if it fits. */
5513 offset *= tree_to_uhwi (unit_size);
5514 offset *= BITS_PER_UNIT;
5516 base = TREE_OPERAND (t, 0);
5517 ctor = get_base_constructor (base, &offset, valueize);
5518 /* Empty constructor. Always fold to 0. */
5519 if (ctor == error_mark_node)
5520 return build_zero_cst (TREE_TYPE (t));
5521 /* Out of bound array access. Value is undefined,
5522 but don't fold. */
5523 if (offset < 0)
5524 return NULL_TREE;
5525 /* We can not determine ctor. */
5526 if (!ctor)
5527 return NULL_TREE;
5528 return fold_ctor_reference (TREE_TYPE (t), ctor, offset,
5529 tree_to_uhwi (unit_size)
5530 * BITS_PER_UNIT,
5531 base);
5535 /* Fallthru. */
5537 case COMPONENT_REF:
5538 case BIT_FIELD_REF:
5539 case TARGET_MEM_REF:
5540 case MEM_REF:
5541 base = get_ref_base_and_extent (t, &offset, &size, &max_size);
5542 ctor = get_base_constructor (base, &offset, valueize);
5544 /* Empty constructor. Always fold to 0. */
5545 if (ctor == error_mark_node)
5546 return build_zero_cst (TREE_TYPE (t));
5547 /* We do not know precise address. */
5548 if (max_size == -1 || max_size != size)
5549 return NULL_TREE;
5550 /* We can not determine ctor. */
5551 if (!ctor)
5552 return NULL_TREE;
5554 /* Out of bound array access. Value is undefined, but don't fold. */
5555 if (offset < 0)
5556 return NULL_TREE;
5558 return fold_ctor_reference (TREE_TYPE (t), ctor, offset, size,
5559 base);
5561 case REALPART_EXPR:
5562 case IMAGPART_EXPR:
5564 tree c = fold_const_aggregate_ref_1 (TREE_OPERAND (t, 0), valueize);
5565 if (c && TREE_CODE (c) == COMPLEX_CST)
5566 return fold_build1_loc (EXPR_LOCATION (t),
5567 TREE_CODE (t), TREE_TYPE (t), c);
5568 break;
5571 default:
5572 break;
5575 return NULL_TREE;
5578 tree
5579 fold_const_aggregate_ref (tree t)
5581 return fold_const_aggregate_ref_1 (t, NULL);
5584 /* Lookup virtual method with index TOKEN in a virtual table V
5585 at OFFSET.
5586 Set CAN_REFER if non-NULL to false if method
5587 is not referable or if the virtual table is ill-formed (such as rewriten
5588 by non-C++ produced symbol). Otherwise just return NULL in that calse. */
5590 tree
5591 gimple_get_virt_method_for_vtable (HOST_WIDE_INT token,
5592 tree v,
5593 unsigned HOST_WIDE_INT offset,
5594 bool *can_refer)
5596 tree vtable = v, init, fn;
5597 unsigned HOST_WIDE_INT size;
5598 unsigned HOST_WIDE_INT elt_size, access_index;
5599 tree domain_type;
5601 if (can_refer)
5602 *can_refer = true;
5604 /* First of all double check we have virtual table. */
5605 if (TREE_CODE (v) != VAR_DECL
5606 || !DECL_VIRTUAL_P (v))
5608 /* Pass down that we lost track of the target. */
5609 if (can_refer)
5610 *can_refer = false;
5611 return NULL_TREE;
5614 init = ctor_for_folding (v);
5616 /* The virtual tables should always be born with constructors
5617 and we always should assume that they are avaialble for
5618 folding. At the moment we do not stream them in all cases,
5619 but it should never happen that ctor seem unreachable. */
5620 gcc_assert (init);
5621 if (init == error_mark_node)
5623 gcc_assert (in_lto_p);
5624 /* Pass down that we lost track of the target. */
5625 if (can_refer)
5626 *can_refer = false;
5627 return NULL_TREE;
5629 gcc_checking_assert (TREE_CODE (TREE_TYPE (v)) == ARRAY_TYPE);
5630 size = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (TREE_TYPE (v))));
5631 offset *= BITS_PER_UNIT;
5632 offset += token * size;
5634 /* Lookup the value in the constructor that is assumed to be array.
5635 This is equivalent to
5636 fn = fold_ctor_reference (TREE_TYPE (TREE_TYPE (v)), init,
5637 offset, size, NULL);
5638 but in a constant time. We expect that frontend produced a simple
5639 array without indexed initializers. */
5641 gcc_checking_assert (TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE);
5642 domain_type = TYPE_DOMAIN (TREE_TYPE (init));
5643 gcc_checking_assert (integer_zerop (TYPE_MIN_VALUE (domain_type)));
5644 elt_size = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (init))));
5646 access_index = offset / BITS_PER_UNIT / elt_size;
5647 gcc_checking_assert (offset % (elt_size * BITS_PER_UNIT) == 0);
5649 /* This code makes an assumption that there are no
5650 indexed fileds produced by C++ FE, so we can directly index the array. */
5651 if (access_index < CONSTRUCTOR_NELTS (init))
5653 fn = CONSTRUCTOR_ELT (init, access_index)->value;
5654 gcc_checking_assert (!CONSTRUCTOR_ELT (init, access_index)->index);
5655 STRIP_NOPS (fn);
5657 else
5658 fn = NULL;
5660 /* For type inconsistent program we may end up looking up virtual method
5661 in virtual table that does not contain TOKEN entries. We may overrun
5662 the virtual table and pick up a constant or RTTI info pointer.
5663 In any case the call is undefined. */
5664 if (!fn
5665 || (TREE_CODE (fn) != ADDR_EXPR && TREE_CODE (fn) != FDESC_EXPR)
5666 || TREE_CODE (TREE_OPERAND (fn, 0)) != FUNCTION_DECL)
5667 fn = builtin_decl_implicit (BUILT_IN_UNREACHABLE);
5668 else
5670 fn = TREE_OPERAND (fn, 0);
5672 /* When cgraph node is missing and function is not public, we cannot
5673 devirtualize. This can happen in WHOPR when the actual method
5674 ends up in other partition, because we found devirtualization
5675 possibility too late. */
5676 if (!can_refer_decl_in_current_unit_p (fn, vtable))
5678 if (can_refer)
5680 *can_refer = false;
5681 return fn;
5683 return NULL_TREE;
5687 /* Make sure we create a cgraph node for functions we'll reference.
5688 They can be non-existent if the reference comes from an entry
5689 of an external vtable for example. */
5690 cgraph_node::get_create (fn);
5692 return fn;
5695 /* Return a declaration of a function which an OBJ_TYPE_REF references. TOKEN
5696 is integer form of OBJ_TYPE_REF_TOKEN of the reference expression.
5697 KNOWN_BINFO carries the binfo describing the true type of
5698 OBJ_TYPE_REF_OBJECT(REF).
5699 Set CAN_REFER if non-NULL to false if method
5700 is not referable or if the virtual table is ill-formed (such as rewriten
5701 by non-C++ produced symbol). Otherwise just return NULL in that calse. */
5703 tree
5704 gimple_get_virt_method_for_binfo (HOST_WIDE_INT token, tree known_binfo,
5705 bool *can_refer)
5707 unsigned HOST_WIDE_INT offset;
5708 tree v;
5710 v = BINFO_VTABLE (known_binfo);
5711 /* If there is no virtual methods table, leave the OBJ_TYPE_REF alone. */
5712 if (!v)
5713 return NULL_TREE;
5715 if (!vtable_pointer_value_to_vtable (v, &v, &offset))
5717 if (can_refer)
5718 *can_refer = false;
5719 return NULL_TREE;
5721 return gimple_get_virt_method_for_vtable (token, v, offset, can_refer);
5724 /* Return true iff VAL is a gimple expression that is known to be
5725 non-negative. Restricted to floating-point inputs. */
5727 bool
5728 gimple_val_nonnegative_real_p (tree val)
5730 gimple def_stmt;
5732 gcc_assert (val && SCALAR_FLOAT_TYPE_P (TREE_TYPE (val)));
5734 /* Use existing logic for non-gimple trees. */
5735 if (tree_expr_nonnegative_p (val))
5736 return true;
5738 if (TREE_CODE (val) != SSA_NAME)
5739 return false;
5741 /* Currently we look only at the immediately defining statement
5742 to make this determination, since recursion on defining
5743 statements of operands can lead to quadratic behavior in the
5744 worst case. This is expected to catch almost all occurrences
5745 in practice. It would be possible to implement limited-depth
5746 recursion if important cases are lost. Alternatively, passes
5747 that need this information (such as the pow/powi lowering code
5748 in the cse_sincos pass) could be revised to provide it through
5749 dataflow propagation. */
5751 def_stmt = SSA_NAME_DEF_STMT (val);
5753 if (is_gimple_assign (def_stmt))
5755 tree op0, op1;
5757 /* See fold-const.c:tree_expr_nonnegative_p for additional
5758 cases that could be handled with recursion. */
5760 switch (gimple_assign_rhs_code (def_stmt))
5762 case ABS_EXPR:
5763 /* Always true for floating-point operands. */
5764 return true;
5766 case MULT_EXPR:
5767 /* True if the two operands are identical (since we are
5768 restricted to floating-point inputs). */
5769 op0 = gimple_assign_rhs1 (def_stmt);
5770 op1 = gimple_assign_rhs2 (def_stmt);
5772 if (op0 == op1
5773 || operand_equal_p (op0, op1, 0))
5774 return true;
5776 default:
5777 return false;
5780 else if (is_gimple_call (def_stmt))
5782 tree fndecl = gimple_call_fndecl (def_stmt);
5783 if (fndecl
5784 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
5786 tree arg1;
5788 switch (DECL_FUNCTION_CODE (fndecl))
5790 CASE_FLT_FN (BUILT_IN_ACOS):
5791 CASE_FLT_FN (BUILT_IN_ACOSH):
5792 CASE_FLT_FN (BUILT_IN_CABS):
5793 CASE_FLT_FN (BUILT_IN_COSH):
5794 CASE_FLT_FN (BUILT_IN_ERFC):
5795 CASE_FLT_FN (BUILT_IN_EXP):
5796 CASE_FLT_FN (BUILT_IN_EXP10):
5797 CASE_FLT_FN (BUILT_IN_EXP2):
5798 CASE_FLT_FN (BUILT_IN_FABS):
5799 CASE_FLT_FN (BUILT_IN_FDIM):
5800 CASE_FLT_FN (BUILT_IN_HYPOT):
5801 CASE_FLT_FN (BUILT_IN_POW10):
5802 return true;
5804 CASE_FLT_FN (BUILT_IN_SQRT):
5805 /* sqrt(-0.0) is -0.0, and sqrt is not defined over other
5806 nonnegative inputs. */
5807 if (!HONOR_SIGNED_ZEROS (val))
5808 return true;
5810 break;
5812 CASE_FLT_FN (BUILT_IN_POWI):
5813 /* True if the second argument is an even integer. */
5814 arg1 = gimple_call_arg (def_stmt, 1);
5816 if (TREE_CODE (arg1) == INTEGER_CST
5817 && (TREE_INT_CST_LOW (arg1) & 1) == 0)
5818 return true;
5820 break;
5822 CASE_FLT_FN (BUILT_IN_POW):
5823 /* True if the second argument is an even integer-valued
5824 real. */
5825 arg1 = gimple_call_arg (def_stmt, 1);
5827 if (TREE_CODE (arg1) == REAL_CST)
5829 REAL_VALUE_TYPE c;
5830 HOST_WIDE_INT n;
5832 c = TREE_REAL_CST (arg1);
5833 n = real_to_integer (&c);
5835 if ((n & 1) == 0)
5837 REAL_VALUE_TYPE cint;
5838 real_from_integer (&cint, VOIDmode, n, SIGNED);
5839 if (real_identical (&c, &cint))
5840 return true;
5844 break;
5846 default:
5847 return false;
5852 return false;
5855 /* Given a pointer value OP0, return a simplified version of an
5856 indirection through OP0, or NULL_TREE if no simplification is
5857 possible. Note that the resulting type may be different from
5858 the type pointed to in the sense that it is still compatible
5859 from the langhooks point of view. */
5861 tree
5862 gimple_fold_indirect_ref (tree t)
5864 tree ptype = TREE_TYPE (t), type = TREE_TYPE (ptype);
5865 tree sub = t;
5866 tree subtype;
5868 STRIP_NOPS (sub);
5869 subtype = TREE_TYPE (sub);
5870 if (!POINTER_TYPE_P (subtype))
5871 return NULL_TREE;
5873 if (TREE_CODE (sub) == ADDR_EXPR)
5875 tree op = TREE_OPERAND (sub, 0);
5876 tree optype = TREE_TYPE (op);
5877 /* *&p => p */
5878 if (useless_type_conversion_p (type, optype))
5879 return op;
5881 /* *(foo *)&fooarray => fooarray[0] */
5882 if (TREE_CODE (optype) == ARRAY_TYPE
5883 && TREE_CODE (TYPE_SIZE (TREE_TYPE (optype))) == INTEGER_CST
5884 && useless_type_conversion_p (type, TREE_TYPE (optype)))
5886 tree type_domain = TYPE_DOMAIN (optype);
5887 tree min_val = size_zero_node;
5888 if (type_domain && TYPE_MIN_VALUE (type_domain))
5889 min_val = TYPE_MIN_VALUE (type_domain);
5890 if (TREE_CODE (min_val) == INTEGER_CST)
5891 return build4 (ARRAY_REF, type, op, min_val, NULL_TREE, NULL_TREE);
5893 /* *(foo *)&complexfoo => __real__ complexfoo */
5894 else if (TREE_CODE (optype) == COMPLEX_TYPE
5895 && useless_type_conversion_p (type, TREE_TYPE (optype)))
5896 return fold_build1 (REALPART_EXPR, type, op);
5897 /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
5898 else if (TREE_CODE (optype) == VECTOR_TYPE
5899 && useless_type_conversion_p (type, TREE_TYPE (optype)))
5901 tree part_width = TYPE_SIZE (type);
5902 tree index = bitsize_int (0);
5903 return fold_build3 (BIT_FIELD_REF, type, op, part_width, index);
5907 /* *(p + CST) -> ... */
5908 if (TREE_CODE (sub) == POINTER_PLUS_EXPR
5909 && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST)
5911 tree addr = TREE_OPERAND (sub, 0);
5912 tree off = TREE_OPERAND (sub, 1);
5913 tree addrtype;
5915 STRIP_NOPS (addr);
5916 addrtype = TREE_TYPE (addr);
5918 /* ((foo*)&vectorfoo)[1] -> BIT_FIELD_REF<vectorfoo,...> */
5919 if (TREE_CODE (addr) == ADDR_EXPR
5920 && TREE_CODE (TREE_TYPE (addrtype)) == VECTOR_TYPE
5921 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (addrtype)))
5922 && tree_fits_uhwi_p (off))
5924 unsigned HOST_WIDE_INT offset = tree_to_uhwi (off);
5925 tree part_width = TYPE_SIZE (type);
5926 unsigned HOST_WIDE_INT part_widthi
5927 = tree_to_shwi (part_width) / BITS_PER_UNIT;
5928 unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT;
5929 tree index = bitsize_int (indexi);
5930 if (offset / part_widthi
5931 < TYPE_VECTOR_SUBPARTS (TREE_TYPE (addrtype)))
5932 return fold_build3 (BIT_FIELD_REF, type, TREE_OPERAND (addr, 0),
5933 part_width, index);
5936 /* ((foo*)&complexfoo)[1] -> __imag__ complexfoo */
5937 if (TREE_CODE (addr) == ADDR_EXPR
5938 && TREE_CODE (TREE_TYPE (addrtype)) == COMPLEX_TYPE
5939 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (addrtype))))
5941 tree size = TYPE_SIZE_UNIT (type);
5942 if (tree_int_cst_equal (size, off))
5943 return fold_build1 (IMAGPART_EXPR, type, TREE_OPERAND (addr, 0));
5946 /* *(p + CST) -> MEM_REF <p, CST>. */
5947 if (TREE_CODE (addr) != ADDR_EXPR
5948 || DECL_P (TREE_OPERAND (addr, 0)))
5949 return fold_build2 (MEM_REF, type,
5950 addr,
5951 wide_int_to_tree (ptype, off));
5954 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
5955 if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
5956 && TREE_CODE (TYPE_SIZE (TREE_TYPE (TREE_TYPE (subtype)))) == INTEGER_CST
5957 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (subtype))))
5959 tree type_domain;
5960 tree min_val = size_zero_node;
5961 tree osub = sub;
5962 sub = gimple_fold_indirect_ref (sub);
5963 if (! sub)
5964 sub = build1 (INDIRECT_REF, TREE_TYPE (subtype), osub);
5965 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
5966 if (type_domain && TYPE_MIN_VALUE (type_domain))
5967 min_val = TYPE_MIN_VALUE (type_domain);
5968 if (TREE_CODE (min_val) == INTEGER_CST)
5969 return build4 (ARRAY_REF, type, sub, min_val, NULL_TREE, NULL_TREE);
5972 return NULL_TREE;
5975 /* Return true if CODE is an operation that when operating on signed
5976 integer types involves undefined behavior on overflow and the
5977 operation can be expressed with unsigned arithmetic. */
5979 bool
5980 arith_code_with_undefined_signed_overflow (tree_code code)
5982 switch (code)
5984 case PLUS_EXPR:
5985 case MINUS_EXPR:
5986 case MULT_EXPR:
5987 case NEGATE_EXPR:
5988 case POINTER_PLUS_EXPR:
5989 return true;
5990 default:
5991 return false;
5995 /* Rewrite STMT, an assignment with a signed integer or pointer arithmetic
5996 operation that can be transformed to unsigned arithmetic by converting
5997 its operand, carrying out the operation in the corresponding unsigned
5998 type and converting the result back to the original type.
6000 Returns a sequence of statements that replace STMT and also contain
6001 a modified form of STMT itself. */
6003 gimple_seq
6004 rewrite_to_defined_overflow (gimple stmt)
6006 if (dump_file && (dump_flags & TDF_DETAILS))
6008 fprintf (dump_file, "rewriting stmt with undefined signed "
6009 "overflow ");
6010 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
6013 tree lhs = gimple_assign_lhs (stmt);
6014 tree type = unsigned_type_for (TREE_TYPE (lhs));
6015 gimple_seq stmts = NULL;
6016 for (unsigned i = 1; i < gimple_num_ops (stmt); ++i)
6018 gimple_seq stmts2 = NULL;
6019 gimple_set_op (stmt, i,
6020 force_gimple_operand (fold_convert (type,
6021 gimple_op (stmt, i)),
6022 &stmts2, true, NULL_TREE));
6023 gimple_seq_add_seq (&stmts, stmts2);
6025 gimple_assign_set_lhs (stmt, make_ssa_name (type, stmt));
6026 if (gimple_assign_rhs_code (stmt) == POINTER_PLUS_EXPR)
6027 gimple_assign_set_rhs_code (stmt, PLUS_EXPR);
6028 gimple_seq_add_stmt (&stmts, stmt);
6029 gimple cvt = gimple_build_assign (lhs, NOP_EXPR, gimple_assign_lhs (stmt));
6030 gimple_seq_add_stmt (&stmts, cvt);
6032 return stmts;
6036 /* The valueization hook we use for the gimple_build API simplification.
6037 This makes us match fold_buildN behavior by only combining with
6038 statements in the sequence(s) we are currently building. */
6040 static tree
6041 gimple_build_valueize (tree op)
6043 if (gimple_bb (SSA_NAME_DEF_STMT (op)) == NULL)
6044 return op;
6045 return NULL_TREE;
6048 /* Build the expression CODE OP0 of type TYPE with location LOC,
6049 simplifying it first if possible. Returns the built
6050 expression value and appends statements possibly defining it
6051 to SEQ. */
6053 tree
6054 gimple_build (gimple_seq *seq, location_t loc,
6055 enum tree_code code, tree type, tree op0)
6057 tree res = gimple_simplify (code, type, op0, seq, gimple_build_valueize);
6058 if (!res)
6060 if (gimple_in_ssa_p (cfun))
6061 res = make_ssa_name (type);
6062 else
6063 res = create_tmp_reg (type);
6064 gimple stmt;
6065 if (code == REALPART_EXPR
6066 || code == IMAGPART_EXPR
6067 || code == VIEW_CONVERT_EXPR)
6068 stmt = gimple_build_assign (res, code, build1 (code, type, op0));
6069 else
6070 stmt = gimple_build_assign (res, code, op0);
6071 gimple_set_location (stmt, loc);
6072 gimple_seq_add_stmt_without_update (seq, stmt);
6074 return res;
6077 /* Build the expression OP0 CODE OP1 of type TYPE with location LOC,
6078 simplifying it first if possible. Returns the built
6079 expression value and appends statements possibly defining it
6080 to SEQ. */
6082 tree
6083 gimple_build (gimple_seq *seq, location_t loc,
6084 enum tree_code code, tree type, tree op0, tree op1)
6086 tree res = gimple_simplify (code, type, op0, op1, seq, gimple_build_valueize);
6087 if (!res)
6089 if (gimple_in_ssa_p (cfun))
6090 res = make_ssa_name (type);
6091 else
6092 res = create_tmp_reg (type);
6093 gimple stmt = gimple_build_assign (res, code, op0, op1);
6094 gimple_set_location (stmt, loc);
6095 gimple_seq_add_stmt_without_update (seq, stmt);
6097 return res;
6100 /* Build the expression (CODE OP0 OP1 OP2) of type TYPE with location LOC,
6101 simplifying it first if possible. Returns the built
6102 expression value and appends statements possibly defining it
6103 to SEQ. */
6105 tree
6106 gimple_build (gimple_seq *seq, location_t loc,
6107 enum tree_code code, tree type, tree op0, tree op1, tree op2)
6109 tree res = gimple_simplify (code, type, op0, op1, op2,
6110 seq, gimple_build_valueize);
6111 if (!res)
6113 if (gimple_in_ssa_p (cfun))
6114 res = make_ssa_name (type);
6115 else
6116 res = create_tmp_reg (type);
6117 gimple stmt;
6118 if (code == BIT_FIELD_REF)
6119 stmt = gimple_build_assign (res, code,
6120 build3 (code, type, op0, op1, op2));
6121 else
6122 stmt = gimple_build_assign (res, code, op0, op1, op2);
6123 gimple_set_location (stmt, loc);
6124 gimple_seq_add_stmt_without_update (seq, stmt);
6126 return res;
6129 /* Build the call FN (ARG0) with a result of type TYPE
6130 (or no result if TYPE is void) with location LOC,
6131 simplifying it first if possible. Returns the built
6132 expression value (or NULL_TREE if TYPE is void) and appends
6133 statements possibly defining it to SEQ. */
6135 tree
6136 gimple_build (gimple_seq *seq, location_t loc,
6137 enum built_in_function fn, tree type, tree arg0)
6139 tree res = gimple_simplify (fn, type, arg0, seq, gimple_build_valueize);
6140 if (!res)
6142 tree decl = builtin_decl_implicit (fn);
6143 gimple stmt = gimple_build_call (decl, 1, arg0);
6144 if (!VOID_TYPE_P (type))
6146 if (gimple_in_ssa_p (cfun))
6147 res = make_ssa_name (type);
6148 else
6149 res = create_tmp_reg (type);
6150 gimple_call_set_lhs (stmt, res);
6152 gimple_set_location (stmt, loc);
6153 gimple_seq_add_stmt_without_update (seq, stmt);
6155 return res;
6158 /* Build the call FN (ARG0, ARG1) with a result of type TYPE
6159 (or no result if TYPE is void) with location LOC,
6160 simplifying it first if possible. Returns the built
6161 expression value (or NULL_TREE if TYPE is void) and appends
6162 statements possibly defining it to SEQ. */
6164 tree
6165 gimple_build (gimple_seq *seq, location_t loc,
6166 enum built_in_function fn, tree type, tree arg0, tree arg1)
6168 tree res = gimple_simplify (fn, type, arg0, arg1, seq, gimple_build_valueize);
6169 if (!res)
6171 tree decl = builtin_decl_implicit (fn);
6172 gimple stmt = gimple_build_call (decl, 2, arg0, arg1);
6173 if (!VOID_TYPE_P (type))
6175 if (gimple_in_ssa_p (cfun))
6176 res = make_ssa_name (type);
6177 else
6178 res = create_tmp_reg (type);
6179 gimple_call_set_lhs (stmt, res);
6181 gimple_set_location (stmt, loc);
6182 gimple_seq_add_stmt_without_update (seq, stmt);
6184 return res;
6187 /* Build the call FN (ARG0, ARG1, ARG2) with a result of type TYPE
6188 (or no result if TYPE is void) with location LOC,
6189 simplifying it first if possible. Returns the built
6190 expression value (or NULL_TREE if TYPE is void) and appends
6191 statements possibly defining it to SEQ. */
6193 tree
6194 gimple_build (gimple_seq *seq, location_t loc,
6195 enum built_in_function fn, tree type,
6196 tree arg0, tree arg1, tree arg2)
6198 tree res = gimple_simplify (fn, type, arg0, arg1, arg2,
6199 seq, gimple_build_valueize);
6200 if (!res)
6202 tree decl = builtin_decl_implicit (fn);
6203 gimple stmt = gimple_build_call (decl, 3, arg0, arg1, arg2);
6204 if (!VOID_TYPE_P (type))
6206 if (gimple_in_ssa_p (cfun))
6207 res = make_ssa_name (type);
6208 else
6209 res = create_tmp_reg (type);
6210 gimple_call_set_lhs (stmt, res);
6212 gimple_set_location (stmt, loc);
6213 gimple_seq_add_stmt_without_update (seq, stmt);
6215 return res;
6218 /* Build the conversion (TYPE) OP with a result of type TYPE
6219 with location LOC if such conversion is neccesary in GIMPLE,
6220 simplifying it first.
6221 Returns the built expression value and appends
6222 statements possibly defining it to SEQ. */
6224 tree
6225 gimple_convert (gimple_seq *seq, location_t loc, tree type, tree op)
6227 if (useless_type_conversion_p (type, TREE_TYPE (op)))
6228 return op;
6229 return gimple_build (seq, loc, NOP_EXPR, type, op);