target-supports.exp (check_effective_target_weak_undefined): Return 0 on hppa*-*...
[official-gcc.git] / gcc / gimple-fold.c
blob62d2e0abc2648b16c1e9a011aa23b5f9cea93ff2
1 /* Statement simplification on GIMPLE.
2 Copyright (C) 2010-2019 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 "target.h"
26 #include "rtl.h"
27 #include "tree.h"
28 #include "gimple.h"
29 #include "predict.h"
30 #include "ssa.h"
31 #include "cgraph.h"
32 #include "gimple-pretty-print.h"
33 #include "gimple-ssa-warn-restrict.h"
34 #include "fold-const.h"
35 #include "stmt.h"
36 #include "expr.h"
37 #include "stor-layout.h"
38 #include "dumpfile.h"
39 #include "gimple-fold.h"
40 #include "gimplify.h"
41 #include "gimple-iterator.h"
42 #include "tree-into-ssa.h"
43 #include "tree-dfa.h"
44 #include "tree-object-size.h"
45 #include "tree-ssa.h"
46 #include "tree-ssa-propagate.h"
47 #include "ipa-utils.h"
48 #include "tree-ssa-address.h"
49 #include "langhooks.h"
50 #include "gimplify-me.h"
51 #include "dbgcnt.h"
52 #include "builtins.h"
53 #include "tree-eh.h"
54 #include "gimple-match.h"
55 #include "gomp-constants.h"
56 #include "optabs-query.h"
57 #include "omp-general.h"
58 #include "tree-cfg.h"
59 #include "fold-const-call.h"
60 #include "stringpool.h"
61 #include "attribs.h"
62 #include "asan.h"
63 #include "diagnostic-core.h"
64 #include "intl.h"
65 #include "calls.h"
66 #include "tree-vector-builder.h"
67 #include "tree-ssa-strlen.h"
69 enum strlen_range_kind {
70 /* Compute the exact constant string length. */
71 SRK_STRLEN,
72 /* Compute the maximum constant string length. */
73 SRK_STRLENMAX,
74 /* Compute a range of string lengths bounded by object sizes. When
75 the length of a string cannot be determined, consider as the upper
76 bound the size of the enclosing object the string may be a member
77 or element of. Also determine the size of the largest character
78 array the string may refer to. */
79 SRK_LENRANGE,
80 /* Determine the integer value of the argument (not string length). */
81 SRK_INT_VALUE
84 static bool
85 get_range_strlen (tree, bitmap *, strlen_range_kind, c_strlen_data *, unsigned);
87 /* Return true when DECL can be referenced from current unit.
88 FROM_DECL (if non-null) specify constructor of variable DECL was taken from.
89 We can get declarations that are not possible to reference for various
90 reasons:
92 1) When analyzing C++ virtual tables.
93 C++ virtual tables do have known constructors even
94 when they are keyed to other compilation unit.
95 Those tables can contain pointers to methods and vars
96 in other units. Those methods have both STATIC and EXTERNAL
97 set.
98 2) In WHOPR mode devirtualization might lead to reference
99 to method that was partitioned elsehwere.
100 In this case we have static VAR_DECL or FUNCTION_DECL
101 that has no corresponding callgraph/varpool node
102 declaring the body.
103 3) COMDAT functions referred by external vtables that
104 we devirtualize only during final compilation stage.
105 At this time we already decided that we will not output
106 the function body and thus we can't reference the symbol
107 directly. */
109 static bool
110 can_refer_decl_in_current_unit_p (tree decl, tree from_decl)
112 varpool_node *vnode;
113 struct cgraph_node *node;
114 symtab_node *snode;
116 if (DECL_ABSTRACT_P (decl))
117 return false;
119 /* We are concerned only about static/external vars and functions. */
120 if ((!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
121 || !VAR_OR_FUNCTION_DECL_P (decl))
122 return true;
124 /* Static objects can be referred only if they are defined and not optimized
125 out yet. */
126 if (!TREE_PUBLIC (decl))
128 if (DECL_EXTERNAL (decl))
129 return false;
130 /* Before we start optimizing unreachable code we can be sure all
131 static objects are defined. */
132 if (symtab->function_flags_ready)
133 return true;
134 snode = symtab_node::get (decl);
135 if (!snode || !snode->definition)
136 return false;
137 node = dyn_cast <cgraph_node *> (snode);
138 return !node || !node->global.inlined_to;
141 /* We will later output the initializer, so we can refer to it.
142 So we are concerned only when DECL comes from initializer of
143 external var or var that has been optimized out. */
144 if (!from_decl
145 || !VAR_P (from_decl)
146 || (!DECL_EXTERNAL (from_decl)
147 && (vnode = varpool_node::get (from_decl)) != NULL
148 && vnode->definition)
149 || (flag_ltrans
150 && (vnode = varpool_node::get (from_decl)) != NULL
151 && vnode->in_other_partition))
152 return true;
153 /* We are folding reference from external vtable. The vtable may reffer
154 to a symbol keyed to other compilation unit. The other compilation
155 unit may be in separate DSO and the symbol may be hidden. */
156 if (DECL_VISIBILITY_SPECIFIED (decl)
157 && DECL_EXTERNAL (decl)
158 && DECL_VISIBILITY (decl) != VISIBILITY_DEFAULT
159 && (!(snode = symtab_node::get (decl)) || !snode->in_other_partition))
160 return false;
161 /* When function is public, we always can introduce new reference.
162 Exception are the COMDAT functions where introducing a direct
163 reference imply need to include function body in the curren tunit. */
164 if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl))
165 return true;
166 /* We have COMDAT. We are going to check if we still have definition
167 or if the definition is going to be output in other partition.
168 Bypass this when gimplifying; all needed functions will be produced.
170 As observed in PR20991 for already optimized out comdat virtual functions
171 it may be tempting to not necessarily give up because the copy will be
172 output elsewhere when corresponding vtable is output.
173 This is however not possible - ABI specify that COMDATs are output in
174 units where they are used and when the other unit was compiled with LTO
175 it is possible that vtable was kept public while the function itself
176 was privatized. */
177 if (!symtab->function_flags_ready)
178 return true;
180 snode = symtab_node::get (decl);
181 if (!snode
182 || ((!snode->definition || DECL_EXTERNAL (decl))
183 && (!snode->in_other_partition
184 || (!snode->forced_by_abi && !snode->force_output))))
185 return false;
186 node = dyn_cast <cgraph_node *> (snode);
187 return !node || !node->global.inlined_to;
190 /* Create a temporary for TYPE for a statement STMT. If the current function
191 is in SSA form, a SSA name is created. Otherwise a temporary register
192 is made. */
194 tree
195 create_tmp_reg_or_ssa_name (tree type, gimple *stmt)
197 if (gimple_in_ssa_p (cfun))
198 return make_ssa_name (type, stmt);
199 else
200 return create_tmp_reg (type);
203 /* CVAL is value taken from DECL_INITIAL of variable. Try to transform it into
204 acceptable form for is_gimple_min_invariant.
205 FROM_DECL (if non-NULL) specify variable whose constructor contains CVAL. */
207 tree
208 canonicalize_constructor_val (tree cval, tree from_decl)
210 tree orig_cval = cval;
211 STRIP_NOPS (cval);
212 if (TREE_CODE (cval) == POINTER_PLUS_EXPR
213 && TREE_CODE (TREE_OPERAND (cval, 1)) == INTEGER_CST)
215 tree ptr = TREE_OPERAND (cval, 0);
216 if (is_gimple_min_invariant (ptr))
217 cval = build1_loc (EXPR_LOCATION (cval),
218 ADDR_EXPR, TREE_TYPE (ptr),
219 fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (ptr)),
220 ptr,
221 fold_convert (ptr_type_node,
222 TREE_OPERAND (cval, 1))));
224 if (TREE_CODE (cval) == ADDR_EXPR)
226 tree base = NULL_TREE;
227 if (TREE_CODE (TREE_OPERAND (cval, 0)) == COMPOUND_LITERAL_EXPR)
229 base = COMPOUND_LITERAL_EXPR_DECL (TREE_OPERAND (cval, 0));
230 if (base)
231 TREE_OPERAND (cval, 0) = base;
233 else
234 base = get_base_address (TREE_OPERAND (cval, 0));
235 if (!base)
236 return NULL_TREE;
238 if (VAR_OR_FUNCTION_DECL_P (base)
239 && !can_refer_decl_in_current_unit_p (base, from_decl))
240 return NULL_TREE;
241 if (TREE_TYPE (base) == error_mark_node)
242 return NULL_TREE;
243 if (VAR_P (base))
244 TREE_ADDRESSABLE (base) = 1;
245 else if (TREE_CODE (base) == FUNCTION_DECL)
247 /* Make sure we create a cgraph node for functions we'll reference.
248 They can be non-existent if the reference comes from an entry
249 of an external vtable for example. */
250 cgraph_node::get_create (base);
252 /* Fixup types in global initializers. */
253 if (TREE_TYPE (TREE_TYPE (cval)) != TREE_TYPE (TREE_OPERAND (cval, 0)))
254 cval = build_fold_addr_expr (TREE_OPERAND (cval, 0));
256 if (!useless_type_conversion_p (TREE_TYPE (orig_cval), TREE_TYPE (cval)))
257 cval = fold_convert (TREE_TYPE (orig_cval), cval);
258 return cval;
260 if (TREE_OVERFLOW_P (cval))
261 return drop_tree_overflow (cval);
262 return orig_cval;
265 /* If SYM is a constant variable with known value, return the value.
266 NULL_TREE is returned otherwise. */
268 tree
269 get_symbol_constant_value (tree sym)
271 tree val = ctor_for_folding (sym);
272 if (val != error_mark_node)
274 if (val)
276 val = canonicalize_constructor_val (unshare_expr (val), sym);
277 if (val && is_gimple_min_invariant (val))
278 return val;
279 else
280 return NULL_TREE;
282 /* Variables declared 'const' without an initializer
283 have zero as the initializer if they may not be
284 overridden at link or run time. */
285 if (!val
286 && is_gimple_reg_type (TREE_TYPE (sym)))
287 return build_zero_cst (TREE_TYPE (sym));
290 return NULL_TREE;
295 /* Subroutine of fold_stmt. We perform several simplifications of the
296 memory reference tree EXPR and make sure to re-gimplify them properly
297 after propagation of constant addresses. IS_LHS is true if the
298 reference is supposed to be an lvalue. */
300 static tree
301 maybe_fold_reference (tree expr, bool is_lhs)
303 tree result;
305 if ((TREE_CODE (expr) == VIEW_CONVERT_EXPR
306 || TREE_CODE (expr) == REALPART_EXPR
307 || TREE_CODE (expr) == IMAGPART_EXPR)
308 && CONSTANT_CLASS_P (TREE_OPERAND (expr, 0)))
309 return fold_unary_loc (EXPR_LOCATION (expr),
310 TREE_CODE (expr),
311 TREE_TYPE (expr),
312 TREE_OPERAND (expr, 0));
313 else if (TREE_CODE (expr) == BIT_FIELD_REF
314 && CONSTANT_CLASS_P (TREE_OPERAND (expr, 0)))
315 return fold_ternary_loc (EXPR_LOCATION (expr),
316 TREE_CODE (expr),
317 TREE_TYPE (expr),
318 TREE_OPERAND (expr, 0),
319 TREE_OPERAND (expr, 1),
320 TREE_OPERAND (expr, 2));
322 if (!is_lhs
323 && (result = fold_const_aggregate_ref (expr))
324 && is_gimple_min_invariant (result))
325 return result;
327 return NULL_TREE;
331 /* Attempt to fold an assignment statement pointed-to by SI. Returns a
332 replacement rhs for the statement or NULL_TREE if no simplification
333 could be made. It is assumed that the operands have been previously
334 folded. */
336 static tree
337 fold_gimple_assign (gimple_stmt_iterator *si)
339 gimple *stmt = gsi_stmt (*si);
340 enum tree_code subcode = gimple_assign_rhs_code (stmt);
341 location_t loc = gimple_location (stmt);
343 tree result = NULL_TREE;
345 switch (get_gimple_rhs_class (subcode))
347 case GIMPLE_SINGLE_RHS:
349 tree rhs = gimple_assign_rhs1 (stmt);
351 if (TREE_CLOBBER_P (rhs))
352 return NULL_TREE;
354 if (REFERENCE_CLASS_P (rhs))
355 return maybe_fold_reference (rhs, false);
357 else if (TREE_CODE (rhs) == OBJ_TYPE_REF)
359 tree val = OBJ_TYPE_REF_EXPR (rhs);
360 if (is_gimple_min_invariant (val))
361 return val;
362 else if (flag_devirtualize && virtual_method_call_p (rhs))
364 bool final;
365 vec <cgraph_node *>targets
366 = possible_polymorphic_call_targets (rhs, stmt, &final);
367 if (final && targets.length () <= 1 && dbg_cnt (devirt))
369 if (dump_enabled_p ())
371 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, stmt,
372 "resolving virtual function address "
373 "reference to function %s\n",
374 targets.length () == 1
375 ? targets[0]->name ()
376 : "NULL");
378 if (targets.length () == 1)
380 val = fold_convert (TREE_TYPE (val),
381 build_fold_addr_expr_loc
382 (loc, targets[0]->decl));
383 STRIP_USELESS_TYPE_CONVERSION (val);
385 else
386 /* We cannot use __builtin_unreachable here because it
387 cannot have address taken. */
388 val = build_int_cst (TREE_TYPE (val), 0);
389 return val;
394 else if (TREE_CODE (rhs) == ADDR_EXPR)
396 tree ref = TREE_OPERAND (rhs, 0);
397 tree tem = maybe_fold_reference (ref, true);
398 if (tem
399 && TREE_CODE (tem) == MEM_REF
400 && integer_zerop (TREE_OPERAND (tem, 1)))
401 result = fold_convert (TREE_TYPE (rhs), TREE_OPERAND (tem, 0));
402 else if (tem)
403 result = fold_convert (TREE_TYPE (rhs),
404 build_fold_addr_expr_loc (loc, tem));
405 else if (TREE_CODE (ref) == MEM_REF
406 && integer_zerop (TREE_OPERAND (ref, 1)))
407 result = fold_convert (TREE_TYPE (rhs), TREE_OPERAND (ref, 0));
409 if (result)
411 /* Strip away useless type conversions. Both the
412 NON_LVALUE_EXPR that may have been added by fold, and
413 "useless" type conversions that might now be apparent
414 due to propagation. */
415 STRIP_USELESS_TYPE_CONVERSION (result);
417 if (result != rhs && valid_gimple_rhs_p (result))
418 return result;
422 else if (TREE_CODE (rhs) == CONSTRUCTOR
423 && TREE_CODE (TREE_TYPE (rhs)) == VECTOR_TYPE)
425 /* Fold a constant vector CONSTRUCTOR to VECTOR_CST. */
426 unsigned i;
427 tree val;
429 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), i, val)
430 if (! CONSTANT_CLASS_P (val))
431 return NULL_TREE;
433 return build_vector_from_ctor (TREE_TYPE (rhs),
434 CONSTRUCTOR_ELTS (rhs));
437 else if (DECL_P (rhs))
438 return get_symbol_constant_value (rhs);
440 break;
442 case GIMPLE_UNARY_RHS:
443 break;
445 case GIMPLE_BINARY_RHS:
446 break;
448 case GIMPLE_TERNARY_RHS:
449 result = fold_ternary_loc (loc, subcode,
450 TREE_TYPE (gimple_assign_lhs (stmt)),
451 gimple_assign_rhs1 (stmt),
452 gimple_assign_rhs2 (stmt),
453 gimple_assign_rhs3 (stmt));
455 if (result)
457 STRIP_USELESS_TYPE_CONVERSION (result);
458 if (valid_gimple_rhs_p (result))
459 return result;
461 break;
463 case GIMPLE_INVALID_RHS:
464 gcc_unreachable ();
467 return NULL_TREE;
471 /* Replace a statement at *SI_P with a sequence of statements in STMTS,
472 adjusting the replacement stmts location and virtual operands.
473 If the statement has a lhs the last stmt in the sequence is expected
474 to assign to that lhs. */
476 static void
477 gsi_replace_with_seq_vops (gimple_stmt_iterator *si_p, gimple_seq stmts)
479 gimple *stmt = gsi_stmt (*si_p);
481 if (gimple_has_location (stmt))
482 annotate_all_with_location (stmts, gimple_location (stmt));
484 /* First iterate over the replacement statements backward, assigning
485 virtual operands to their defining statements. */
486 gimple *laststore = NULL;
487 for (gimple_stmt_iterator i = gsi_last (stmts);
488 !gsi_end_p (i); gsi_prev (&i))
490 gimple *new_stmt = gsi_stmt (i);
491 if ((gimple_assign_single_p (new_stmt)
492 && !is_gimple_reg (gimple_assign_lhs (new_stmt)))
493 || (is_gimple_call (new_stmt)
494 && (gimple_call_flags (new_stmt)
495 & (ECF_NOVOPS | ECF_PURE | ECF_CONST | ECF_NORETURN)) == 0))
497 tree vdef;
498 if (!laststore)
499 vdef = gimple_vdef (stmt);
500 else
501 vdef = make_ssa_name (gimple_vop (cfun), new_stmt);
502 gimple_set_vdef (new_stmt, vdef);
503 if (vdef && TREE_CODE (vdef) == SSA_NAME)
504 SSA_NAME_DEF_STMT (vdef) = new_stmt;
505 laststore = new_stmt;
509 /* Second iterate over the statements forward, assigning virtual
510 operands to their uses. */
511 tree reaching_vuse = gimple_vuse (stmt);
512 for (gimple_stmt_iterator i = gsi_start (stmts);
513 !gsi_end_p (i); gsi_next (&i))
515 gimple *new_stmt = gsi_stmt (i);
516 /* If the new statement possibly has a VUSE, update it with exact SSA
517 name we know will reach this one. */
518 if (gimple_has_mem_ops (new_stmt))
519 gimple_set_vuse (new_stmt, reaching_vuse);
520 gimple_set_modified (new_stmt, true);
521 if (gimple_vdef (new_stmt))
522 reaching_vuse = gimple_vdef (new_stmt);
525 /* If the new sequence does not do a store release the virtual
526 definition of the original statement. */
527 if (reaching_vuse
528 && reaching_vuse == gimple_vuse (stmt))
530 tree vdef = gimple_vdef (stmt);
531 if (vdef
532 && TREE_CODE (vdef) == SSA_NAME)
534 unlink_stmt_vdef (stmt);
535 release_ssa_name (vdef);
539 /* Finally replace the original statement with the sequence. */
540 gsi_replace_with_seq (si_p, stmts, false);
543 /* Convert EXPR into a GIMPLE value suitable for substitution on the
544 RHS of an assignment. Insert the necessary statements before
545 iterator *SI_P. The statement at *SI_P, which must be a GIMPLE_CALL
546 is replaced. If the call is expected to produces a result, then it
547 is replaced by an assignment of the new RHS to the result variable.
548 If the result is to be ignored, then the call is replaced by a
549 GIMPLE_NOP. A proper VDEF chain is retained by making the first
550 VUSE and the last VDEF of the whole sequence be the same as the replaced
551 statement and using new SSA names for stores in between. */
553 void
554 gimplify_and_update_call_from_tree (gimple_stmt_iterator *si_p, tree expr)
556 tree lhs;
557 gimple *stmt, *new_stmt;
558 gimple_stmt_iterator i;
559 gimple_seq stmts = NULL;
561 stmt = gsi_stmt (*si_p);
563 gcc_assert (is_gimple_call (stmt));
565 push_gimplify_context (gimple_in_ssa_p (cfun));
567 lhs = gimple_call_lhs (stmt);
568 if (lhs == NULL_TREE)
570 gimplify_and_add (expr, &stmts);
571 /* We can end up with folding a memcpy of an empty class assignment
572 which gets optimized away by C++ gimplification. */
573 if (gimple_seq_empty_p (stmts))
575 pop_gimplify_context (NULL);
576 if (gimple_in_ssa_p (cfun))
578 unlink_stmt_vdef (stmt);
579 release_defs (stmt);
581 gsi_replace (si_p, gimple_build_nop (), false);
582 return;
585 else
587 tree tmp = force_gimple_operand (expr, &stmts, false, NULL_TREE);
588 new_stmt = gimple_build_assign (lhs, tmp);
589 i = gsi_last (stmts);
590 gsi_insert_after_without_update (&i, new_stmt,
591 GSI_CONTINUE_LINKING);
594 pop_gimplify_context (NULL);
596 gsi_replace_with_seq_vops (si_p, stmts);
600 /* Replace the call at *GSI with the gimple value VAL. */
602 void
603 replace_call_with_value (gimple_stmt_iterator *gsi, tree val)
605 gimple *stmt = gsi_stmt (*gsi);
606 tree lhs = gimple_call_lhs (stmt);
607 gimple *repl;
608 if (lhs)
610 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (val)))
611 val = fold_convert (TREE_TYPE (lhs), val);
612 repl = gimple_build_assign (lhs, val);
614 else
615 repl = gimple_build_nop ();
616 tree vdef = gimple_vdef (stmt);
617 if (vdef && TREE_CODE (vdef) == SSA_NAME)
619 unlink_stmt_vdef (stmt);
620 release_ssa_name (vdef);
622 gsi_replace (gsi, repl, false);
625 /* Replace the call at *GSI with the new call REPL and fold that
626 again. */
628 static void
629 replace_call_with_call_and_fold (gimple_stmt_iterator *gsi, gimple *repl)
631 gimple *stmt = gsi_stmt (*gsi);
632 gimple_call_set_lhs (repl, gimple_call_lhs (stmt));
633 gimple_set_location (repl, gimple_location (stmt));
634 if (gimple_vdef (stmt)
635 && TREE_CODE (gimple_vdef (stmt)) == SSA_NAME)
637 gimple_set_vdef (repl, gimple_vdef (stmt));
638 SSA_NAME_DEF_STMT (gimple_vdef (repl)) = repl;
640 if (gimple_vuse (stmt))
641 gimple_set_vuse (repl, gimple_vuse (stmt));
642 gsi_replace (gsi, repl, false);
643 fold_stmt (gsi);
646 /* Return true if VAR is a VAR_DECL or a component thereof. */
648 static bool
649 var_decl_component_p (tree var)
651 tree inner = var;
652 while (handled_component_p (inner))
653 inner = TREE_OPERAND (inner, 0);
654 return (DECL_P (inner)
655 || (TREE_CODE (inner) == MEM_REF
656 && TREE_CODE (TREE_OPERAND (inner, 0)) == ADDR_EXPR));
659 /* Return TRUE if the SIZE argument, representing the size of an
660 object, is in a range of values of which exactly zero is valid. */
662 static bool
663 size_must_be_zero_p (tree size)
665 if (integer_zerop (size))
666 return true;
668 if (TREE_CODE (size) != SSA_NAME || !INTEGRAL_TYPE_P (TREE_TYPE (size)))
669 return false;
671 tree type = TREE_TYPE (size);
672 int prec = TYPE_PRECISION (type);
674 /* Compute the value of SSIZE_MAX, the largest positive value that
675 can be stored in ssize_t, the signed counterpart of size_t. */
676 wide_int ssize_max = wi::lshift (wi::one (prec), prec - 1) - 1;
677 value_range valid_range (VR_RANGE,
678 build_int_cst (type, 0),
679 wide_int_to_tree (type, ssize_max));
680 value_range vr;
681 get_range_info (size, vr);
682 vr.intersect (&valid_range);
683 return vr.zero_p ();
686 /* Fold function call to builtin mem{{,p}cpy,move}. Try to detect and
687 diagnose (otherwise undefined) overlapping copies without preventing
688 folding. When folded, GCC guarantees that overlapping memcpy has
689 the same semantics as memmove. Call to the library memcpy need not
690 provide the same guarantee. Return false if no simplification can
691 be made. */
693 static bool
694 gimple_fold_builtin_memory_op (gimple_stmt_iterator *gsi,
695 tree dest, tree src, int endp)
697 gimple *stmt = gsi_stmt (*gsi);
698 tree lhs = gimple_call_lhs (stmt);
699 tree len = gimple_call_arg (stmt, 2);
700 tree destvar, srcvar;
701 location_t loc = gimple_location (stmt);
703 /* If the LEN parameter is a constant zero or in range where
704 the only valid value is zero, return DEST. */
705 if (size_must_be_zero_p (len))
707 gimple *repl;
708 if (gimple_call_lhs (stmt))
709 repl = gimple_build_assign (gimple_call_lhs (stmt), dest);
710 else
711 repl = gimple_build_nop ();
712 tree vdef = gimple_vdef (stmt);
713 if (vdef && TREE_CODE (vdef) == SSA_NAME)
715 unlink_stmt_vdef (stmt);
716 release_ssa_name (vdef);
718 gsi_replace (gsi, repl, false);
719 return true;
722 /* If SRC and DEST are the same (and not volatile), return
723 DEST{,+LEN,+LEN-1}. */
724 if (operand_equal_p (src, dest, 0))
726 /* Avoid diagnosing exact overlap in calls to __builtin_memcpy.
727 It's safe and may even be emitted by GCC itself (see bug
728 32667). */
729 unlink_stmt_vdef (stmt);
730 if (gimple_vdef (stmt) && TREE_CODE (gimple_vdef (stmt)) == SSA_NAME)
731 release_ssa_name (gimple_vdef (stmt));
732 if (!lhs)
734 gsi_replace (gsi, gimple_build_nop (), false);
735 return true;
737 goto done;
739 else
741 tree srctype, desttype;
742 unsigned int src_align, dest_align;
743 tree off0;
744 const char *tmp_str;
745 unsigned HOST_WIDE_INT tmp_len;
747 /* Build accesses at offset zero with a ref-all character type. */
748 off0 = build_int_cst (build_pointer_type_for_mode (char_type_node,
749 ptr_mode, true), 0);
751 /* If we can perform the copy efficiently with first doing all loads
752 and then all stores inline it that way. Currently efficiently
753 means that we can load all the memory into a single integer
754 register which is what MOVE_MAX gives us. */
755 src_align = get_pointer_alignment (src);
756 dest_align = get_pointer_alignment (dest);
757 if (tree_fits_uhwi_p (len)
758 && compare_tree_int (len, MOVE_MAX) <= 0
759 /* ??? Don't transform copies from strings with known length this
760 confuses the tree-ssa-strlen.c. This doesn't handle
761 the case in gcc.dg/strlenopt-8.c which is XFAILed for that
762 reason. */
763 && !c_strlen (src, 2)
764 && !((tmp_str = c_getstr (src, &tmp_len)) != NULL
765 && memchr (tmp_str, 0, tmp_len) == NULL))
767 unsigned ilen = tree_to_uhwi (len);
768 if (pow2p_hwi (ilen))
770 /* Detect out-of-bounds accesses without issuing warnings.
771 Avoid folding out-of-bounds copies but to avoid false
772 positives for unreachable code defer warning until after
773 DCE has worked its magic.
774 -Wrestrict is still diagnosed. */
775 if (int warning = check_bounds_or_overlap (as_a <gcall *>(stmt),
776 dest, src, len, len,
777 false, false))
778 if (warning != OPT_Wrestrict)
779 return false;
781 scalar_int_mode mode;
782 tree type = lang_hooks.types.type_for_size (ilen * 8, 1);
783 if (type
784 && is_a <scalar_int_mode> (TYPE_MODE (type), &mode)
785 && GET_MODE_SIZE (mode) * BITS_PER_UNIT == ilen * 8
786 /* If the destination pointer is not aligned we must be able
787 to emit an unaligned store. */
788 && (dest_align >= GET_MODE_ALIGNMENT (mode)
789 || !targetm.slow_unaligned_access (mode, dest_align)
790 || (optab_handler (movmisalign_optab, mode)
791 != CODE_FOR_nothing)))
793 tree srctype = type;
794 tree desttype = type;
795 if (src_align < GET_MODE_ALIGNMENT (mode))
796 srctype = build_aligned_type (type, src_align);
797 tree srcmem = fold_build2 (MEM_REF, srctype, src, off0);
798 tree tem = fold_const_aggregate_ref (srcmem);
799 if (tem)
800 srcmem = tem;
801 else if (src_align < GET_MODE_ALIGNMENT (mode)
802 && targetm.slow_unaligned_access (mode, src_align)
803 && (optab_handler (movmisalign_optab, mode)
804 == CODE_FOR_nothing))
805 srcmem = NULL_TREE;
806 if (srcmem)
808 gimple *new_stmt;
809 if (is_gimple_reg_type (TREE_TYPE (srcmem)))
811 new_stmt = gimple_build_assign (NULL_TREE, srcmem);
812 srcmem
813 = create_tmp_reg_or_ssa_name (TREE_TYPE (srcmem),
814 new_stmt);
815 gimple_assign_set_lhs (new_stmt, srcmem);
816 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
817 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
819 if (dest_align < GET_MODE_ALIGNMENT (mode))
820 desttype = build_aligned_type (type, dest_align);
821 new_stmt
822 = gimple_build_assign (fold_build2 (MEM_REF, desttype,
823 dest, off0),
824 srcmem);
825 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
826 gimple_set_vdef (new_stmt, gimple_vdef (stmt));
827 if (gimple_vdef (new_stmt)
828 && TREE_CODE (gimple_vdef (new_stmt)) == SSA_NAME)
829 SSA_NAME_DEF_STMT (gimple_vdef (new_stmt)) = new_stmt;
830 if (!lhs)
832 gsi_replace (gsi, new_stmt, false);
833 return true;
835 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
836 goto done;
842 if (endp == 3)
844 /* Both DEST and SRC must be pointer types.
845 ??? This is what old code did. Is the testing for pointer types
846 really mandatory?
848 If either SRC is readonly or length is 1, we can use memcpy. */
849 if (!dest_align || !src_align)
850 return false;
851 if (readonly_data_expr (src)
852 || (tree_fits_uhwi_p (len)
853 && (MIN (src_align, dest_align) / BITS_PER_UNIT
854 >= tree_to_uhwi (len))))
856 tree fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
857 if (!fn)
858 return false;
859 gimple_call_set_fndecl (stmt, fn);
860 gimple_call_set_arg (stmt, 0, dest);
861 gimple_call_set_arg (stmt, 1, src);
862 fold_stmt (gsi);
863 return true;
866 /* If *src and *dest can't overlap, optimize into memcpy as well. */
867 if (TREE_CODE (src) == ADDR_EXPR
868 && TREE_CODE (dest) == ADDR_EXPR)
870 tree src_base, dest_base, fn;
871 poly_int64 src_offset = 0, dest_offset = 0;
872 poly_uint64 maxsize;
874 srcvar = TREE_OPERAND (src, 0);
875 src_base = get_addr_base_and_unit_offset (srcvar, &src_offset);
876 if (src_base == NULL)
877 src_base = srcvar;
878 destvar = TREE_OPERAND (dest, 0);
879 dest_base = get_addr_base_and_unit_offset (destvar,
880 &dest_offset);
881 if (dest_base == NULL)
882 dest_base = destvar;
883 if (!poly_int_tree_p (len, &maxsize))
884 maxsize = -1;
885 if (SSA_VAR_P (src_base)
886 && SSA_VAR_P (dest_base))
888 if (operand_equal_p (src_base, dest_base, 0)
889 && ranges_maybe_overlap_p (src_offset, maxsize,
890 dest_offset, maxsize))
891 return false;
893 else if (TREE_CODE (src_base) == MEM_REF
894 && TREE_CODE (dest_base) == MEM_REF)
896 if (! operand_equal_p (TREE_OPERAND (src_base, 0),
897 TREE_OPERAND (dest_base, 0), 0))
898 return false;
899 poly_offset_int full_src_offset
900 = mem_ref_offset (src_base) + src_offset;
901 poly_offset_int full_dest_offset
902 = mem_ref_offset (dest_base) + dest_offset;
903 if (ranges_maybe_overlap_p (full_src_offset, maxsize,
904 full_dest_offset, maxsize))
905 return false;
907 else
908 return false;
910 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
911 if (!fn)
912 return false;
913 gimple_call_set_fndecl (stmt, fn);
914 gimple_call_set_arg (stmt, 0, dest);
915 gimple_call_set_arg (stmt, 1, src);
916 fold_stmt (gsi);
917 return true;
920 /* If the destination and source do not alias optimize into
921 memcpy as well. */
922 if ((is_gimple_min_invariant (dest)
923 || TREE_CODE (dest) == SSA_NAME)
924 && (is_gimple_min_invariant (src)
925 || TREE_CODE (src) == SSA_NAME))
927 ao_ref destr, srcr;
928 ao_ref_init_from_ptr_and_size (&destr, dest, len);
929 ao_ref_init_from_ptr_and_size (&srcr, src, len);
930 if (!refs_may_alias_p_1 (&destr, &srcr, false))
932 tree fn;
933 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
934 if (!fn)
935 return false;
936 gimple_call_set_fndecl (stmt, fn);
937 gimple_call_set_arg (stmt, 0, dest);
938 gimple_call_set_arg (stmt, 1, src);
939 fold_stmt (gsi);
940 return true;
944 return false;
947 if (!tree_fits_shwi_p (len))
948 return false;
949 if (!POINTER_TYPE_P (TREE_TYPE (src))
950 || !POINTER_TYPE_P (TREE_TYPE (dest)))
951 return false;
952 /* In the following try to find a type that is most natural to be
953 used for the memcpy source and destination and that allows
954 the most optimization when memcpy is turned into a plain assignment
955 using that type. In theory we could always use a char[len] type
956 but that only gains us that the destination and source possibly
957 no longer will have their address taken. */
958 srctype = TREE_TYPE (TREE_TYPE (src));
959 if (TREE_CODE (srctype) == ARRAY_TYPE
960 && !tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
961 srctype = TREE_TYPE (srctype);
962 desttype = TREE_TYPE (TREE_TYPE (dest));
963 if (TREE_CODE (desttype) == ARRAY_TYPE
964 && !tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
965 desttype = TREE_TYPE (desttype);
966 if (TREE_ADDRESSABLE (srctype)
967 || TREE_ADDRESSABLE (desttype))
968 return false;
970 /* Make sure we are not copying using a floating-point mode or
971 a type whose size possibly does not match its precision. */
972 if (FLOAT_MODE_P (TYPE_MODE (desttype))
973 || TREE_CODE (desttype) == BOOLEAN_TYPE
974 || TREE_CODE (desttype) == ENUMERAL_TYPE)
975 desttype = bitwise_type_for_mode (TYPE_MODE (desttype));
976 if (FLOAT_MODE_P (TYPE_MODE (srctype))
977 || TREE_CODE (srctype) == BOOLEAN_TYPE
978 || TREE_CODE (srctype) == ENUMERAL_TYPE)
979 srctype = bitwise_type_for_mode (TYPE_MODE (srctype));
980 if (!srctype)
981 srctype = desttype;
982 if (!desttype)
983 desttype = srctype;
984 if (!srctype)
985 return false;
987 src_align = get_pointer_alignment (src);
988 dest_align = get_pointer_alignment (dest);
989 if (dest_align < TYPE_ALIGN (desttype)
990 || src_align < TYPE_ALIGN (srctype))
991 return false;
993 destvar = NULL_TREE;
994 if (TREE_CODE (dest) == ADDR_EXPR
995 && var_decl_component_p (TREE_OPERAND (dest, 0))
996 && tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
997 destvar = fold_build2 (MEM_REF, desttype, dest, off0);
999 srcvar = NULL_TREE;
1000 if (TREE_CODE (src) == ADDR_EXPR
1001 && var_decl_component_p (TREE_OPERAND (src, 0))
1002 && tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
1004 if (!destvar
1005 || src_align >= TYPE_ALIGN (desttype))
1006 srcvar = fold_build2 (MEM_REF, destvar ? desttype : srctype,
1007 src, off0);
1008 else if (!STRICT_ALIGNMENT)
1010 srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
1011 src_align);
1012 srcvar = fold_build2 (MEM_REF, srctype, src, off0);
1016 if (srcvar == NULL_TREE && destvar == NULL_TREE)
1017 return false;
1019 if (srcvar == NULL_TREE)
1021 if (src_align >= TYPE_ALIGN (desttype))
1022 srcvar = fold_build2 (MEM_REF, desttype, src, off0);
1023 else
1025 if (STRICT_ALIGNMENT)
1026 return false;
1027 srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
1028 src_align);
1029 srcvar = fold_build2 (MEM_REF, srctype, src, off0);
1032 else if (destvar == NULL_TREE)
1034 if (dest_align >= TYPE_ALIGN (srctype))
1035 destvar = fold_build2 (MEM_REF, srctype, dest, off0);
1036 else
1038 if (STRICT_ALIGNMENT)
1039 return false;
1040 desttype = build_aligned_type (TYPE_MAIN_VARIANT (srctype),
1041 dest_align);
1042 destvar = fold_build2 (MEM_REF, desttype, dest, off0);
1046 /* Same as above, detect out-of-bounds accesses without issuing
1047 warnings. Avoid folding out-of-bounds copies but to avoid
1048 false positives for unreachable code defer warning until
1049 after DCE has worked its magic.
1050 -Wrestrict is still diagnosed. */
1051 if (int warning = check_bounds_or_overlap (as_a <gcall *>(stmt),
1052 dest, src, len, len,
1053 false, false))
1054 if (warning != OPT_Wrestrict)
1055 return false;
1057 gimple *new_stmt;
1058 if (is_gimple_reg_type (TREE_TYPE (srcvar)))
1060 tree tem = fold_const_aggregate_ref (srcvar);
1061 if (tem)
1062 srcvar = tem;
1063 if (! is_gimple_min_invariant (srcvar))
1065 new_stmt = gimple_build_assign (NULL_TREE, srcvar);
1066 srcvar = create_tmp_reg_or_ssa_name (TREE_TYPE (srcvar),
1067 new_stmt);
1068 gimple_assign_set_lhs (new_stmt, srcvar);
1069 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
1070 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1072 new_stmt = gimple_build_assign (destvar, srcvar);
1073 goto set_vop_and_replace;
1076 /* We get an aggregate copy. Use an unsigned char[] type to
1077 perform the copying to preserve padding and to avoid any issues
1078 with TREE_ADDRESSABLE types or float modes behavior on copying. */
1079 desttype = build_array_type_nelts (unsigned_char_type_node,
1080 tree_to_uhwi (len));
1081 srctype = desttype;
1082 if (src_align > TYPE_ALIGN (srctype))
1083 srctype = build_aligned_type (srctype, src_align);
1084 if (dest_align > TYPE_ALIGN (desttype))
1085 desttype = build_aligned_type (desttype, dest_align);
1086 new_stmt
1087 = gimple_build_assign (fold_build2 (MEM_REF, desttype, dest, off0),
1088 fold_build2 (MEM_REF, srctype, src, off0));
1089 set_vop_and_replace:
1090 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
1091 gimple_set_vdef (new_stmt, gimple_vdef (stmt));
1092 if (gimple_vdef (new_stmt)
1093 && TREE_CODE (gimple_vdef (new_stmt)) == SSA_NAME)
1094 SSA_NAME_DEF_STMT (gimple_vdef (new_stmt)) = new_stmt;
1095 if (!lhs)
1097 gsi_replace (gsi, new_stmt, false);
1098 return true;
1100 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1103 done:
1104 gimple_seq stmts = NULL;
1105 if (endp == 0 || endp == 3)
1106 len = NULL_TREE;
1107 else if (endp == 2)
1108 len = gimple_build (&stmts, loc, MINUS_EXPR, TREE_TYPE (len), len,
1109 ssize_int (1));
1110 if (endp == 2 || endp == 1)
1112 len = gimple_convert_to_ptrofftype (&stmts, loc, len);
1113 dest = gimple_build (&stmts, loc, POINTER_PLUS_EXPR,
1114 TREE_TYPE (dest), dest, len);
1117 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
1118 gimple *repl = gimple_build_assign (lhs, dest);
1119 gsi_replace (gsi, repl, false);
1120 return true;
1123 /* Transform a call to built-in bcmp(a, b, len) at *GSI into one
1124 to built-in memcmp (a, b, len). */
1126 static bool
1127 gimple_fold_builtin_bcmp (gimple_stmt_iterator *gsi)
1129 tree fn = builtin_decl_implicit (BUILT_IN_MEMCMP);
1131 if (!fn)
1132 return false;
1134 /* Transform bcmp (a, b, len) into memcmp (a, b, len). */
1136 gimple *stmt = gsi_stmt (*gsi);
1137 tree a = gimple_call_arg (stmt, 0);
1138 tree b = gimple_call_arg (stmt, 1);
1139 tree len = gimple_call_arg (stmt, 2);
1141 gimple *repl = gimple_build_call (fn, 3, a, b, len);
1142 replace_call_with_call_and_fold (gsi, repl);
1144 return true;
1147 /* Transform a call to built-in bcopy (src, dest, len) at *GSI into one
1148 to built-in memmove (dest, src, len). */
1150 static bool
1151 gimple_fold_builtin_bcopy (gimple_stmt_iterator *gsi)
1153 tree fn = builtin_decl_implicit (BUILT_IN_MEMMOVE);
1155 if (!fn)
1156 return false;
1158 /* bcopy has been removed from POSIX in Issue 7 but Issue 6 specifies
1159 it's quivalent to memmove (not memcpy). Transform bcopy (src, dest,
1160 len) into memmove (dest, src, len). */
1162 gimple *stmt = gsi_stmt (*gsi);
1163 tree src = gimple_call_arg (stmt, 0);
1164 tree dest = gimple_call_arg (stmt, 1);
1165 tree len = gimple_call_arg (stmt, 2);
1167 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
1168 gimple_call_set_fntype (as_a <gcall *> (stmt), TREE_TYPE (fn));
1169 replace_call_with_call_and_fold (gsi, repl);
1171 return true;
1174 /* Transform a call to built-in bzero (dest, len) at *GSI into one
1175 to built-in memset (dest, 0, len). */
1177 static bool
1178 gimple_fold_builtin_bzero (gimple_stmt_iterator *gsi)
1180 tree fn = builtin_decl_implicit (BUILT_IN_MEMSET);
1182 if (!fn)
1183 return false;
1185 /* Transform bzero (dest, len) into memset (dest, 0, len). */
1187 gimple *stmt = gsi_stmt (*gsi);
1188 tree dest = gimple_call_arg (stmt, 0);
1189 tree len = gimple_call_arg (stmt, 1);
1191 gimple_seq seq = NULL;
1192 gimple *repl = gimple_build_call (fn, 3, dest, integer_zero_node, len);
1193 gimple_seq_add_stmt_without_update (&seq, repl);
1194 gsi_replace_with_seq_vops (gsi, seq);
1195 fold_stmt (gsi);
1197 return true;
1200 /* Fold function call to builtin memset or bzero at *GSI setting the
1201 memory of size LEN to VAL. Return whether a simplification was made. */
1203 static bool
1204 gimple_fold_builtin_memset (gimple_stmt_iterator *gsi, tree c, tree len)
1206 gimple *stmt = gsi_stmt (*gsi);
1207 tree etype;
1208 unsigned HOST_WIDE_INT length, cval;
1210 /* If the LEN parameter is zero, return DEST. */
1211 if (integer_zerop (len))
1213 replace_call_with_value (gsi, gimple_call_arg (stmt, 0));
1214 return true;
1217 if (! tree_fits_uhwi_p (len))
1218 return false;
1220 if (TREE_CODE (c) != INTEGER_CST)
1221 return false;
1223 tree dest = gimple_call_arg (stmt, 0);
1224 tree var = dest;
1225 if (TREE_CODE (var) != ADDR_EXPR)
1226 return false;
1228 var = TREE_OPERAND (var, 0);
1229 if (TREE_THIS_VOLATILE (var))
1230 return false;
1232 etype = TREE_TYPE (var);
1233 if (TREE_CODE (etype) == ARRAY_TYPE)
1234 etype = TREE_TYPE (etype);
1236 if (!INTEGRAL_TYPE_P (etype)
1237 && !POINTER_TYPE_P (etype))
1238 return NULL_TREE;
1240 if (! var_decl_component_p (var))
1241 return NULL_TREE;
1243 length = tree_to_uhwi (len);
1244 if (GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (etype)) != length
1245 || get_pointer_alignment (dest) / BITS_PER_UNIT < length)
1246 return NULL_TREE;
1248 if (length > HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT)
1249 return NULL_TREE;
1251 if (integer_zerop (c))
1252 cval = 0;
1253 else
1255 if (CHAR_BIT != 8 || BITS_PER_UNIT != 8 || HOST_BITS_PER_WIDE_INT > 64)
1256 return NULL_TREE;
1258 cval = TREE_INT_CST_LOW (c);
1259 cval &= 0xff;
1260 cval |= cval << 8;
1261 cval |= cval << 16;
1262 cval |= (cval << 31) << 1;
1265 var = fold_build2 (MEM_REF, etype, dest, build_int_cst (ptr_type_node, 0));
1266 gimple *store = gimple_build_assign (var, build_int_cst_type (etype, cval));
1267 gimple_set_vuse (store, gimple_vuse (stmt));
1268 tree vdef = gimple_vdef (stmt);
1269 if (vdef && TREE_CODE (vdef) == SSA_NAME)
1271 gimple_set_vdef (store, gimple_vdef (stmt));
1272 SSA_NAME_DEF_STMT (gimple_vdef (stmt)) = store;
1274 gsi_insert_before (gsi, store, GSI_SAME_STMT);
1275 if (gimple_call_lhs (stmt))
1277 gimple *asgn = gimple_build_assign (gimple_call_lhs (stmt), dest);
1278 gsi_replace (gsi, asgn, false);
1280 else
1282 gimple_stmt_iterator gsi2 = *gsi;
1283 gsi_prev (gsi);
1284 gsi_remove (&gsi2, true);
1287 return true;
1290 /* Helper of get_range_strlen for ARG that is not an SSA_NAME. */
1292 static bool
1293 get_range_strlen_tree (tree arg, bitmap *visited, strlen_range_kind rkind,
1294 c_strlen_data *pdata, unsigned eltsize)
1296 gcc_assert (TREE_CODE (arg) != SSA_NAME);
1298 /* The length computed by this invocation of the function. */
1299 tree val = NULL_TREE;
1301 /* True if VAL is an optimistic (tight) bound determined from
1302 the size of the character array in which the string may be
1303 stored. In that case, the computed VAL is used to set
1304 PDATA->MAXBOUND. */
1305 bool tight_bound = false;
1307 /* We can end up with &(*iftmp_1)[0] here as well, so handle it. */
1308 if (TREE_CODE (arg) == ADDR_EXPR
1309 && TREE_CODE (TREE_OPERAND (arg, 0)) == ARRAY_REF)
1311 tree op = TREE_OPERAND (arg, 0);
1312 if (integer_zerop (TREE_OPERAND (op, 1)))
1314 tree aop0 = TREE_OPERAND (op, 0);
1315 if (TREE_CODE (aop0) == INDIRECT_REF
1316 && TREE_CODE (TREE_OPERAND (aop0, 0)) == SSA_NAME)
1317 return get_range_strlen (TREE_OPERAND (aop0, 0), visited, rkind,
1318 pdata, eltsize);
1320 else if (TREE_CODE (TREE_OPERAND (op, 0)) == COMPONENT_REF
1321 && rkind == SRK_LENRANGE)
1323 /* Fail if an array is the last member of a struct object
1324 since it could be treated as a (fake) flexible array
1325 member. */
1326 tree idx = TREE_OPERAND (op, 1);
1328 arg = TREE_OPERAND (op, 0);
1329 tree optype = TREE_TYPE (arg);
1330 if (tree dom = TYPE_DOMAIN (optype))
1331 if (tree bound = TYPE_MAX_VALUE (dom))
1332 if (TREE_CODE (bound) == INTEGER_CST
1333 && TREE_CODE (idx) == INTEGER_CST
1334 && tree_int_cst_lt (bound, idx))
1335 return false;
1339 if (rkind == SRK_INT_VALUE)
1341 /* We are computing the maximum value (not string length). */
1342 val = arg;
1343 if (TREE_CODE (val) != INTEGER_CST
1344 || tree_int_cst_sgn (val) < 0)
1345 return false;
1347 else
1349 c_strlen_data lendata = { };
1350 val = c_strlen (arg, 1, &lendata, eltsize);
1352 if (!val && lendata.decl)
1354 /* ARG refers to an unterminated const character array.
1355 DATA.DECL with size DATA.LEN. */
1356 val = lendata.minlen;
1357 pdata->decl = lendata.decl;
1361 if (!val && rkind == SRK_LENRANGE)
1363 if (TREE_CODE (arg) == ADDR_EXPR)
1364 return get_range_strlen (TREE_OPERAND (arg, 0), visited, rkind,
1365 pdata, eltsize);
1367 if (TREE_CODE (arg) == ARRAY_REF)
1369 tree optype = TREE_TYPE (TREE_OPERAND (arg, 0));
1371 /* Determine the "innermost" array type. */
1372 while (TREE_CODE (optype) == ARRAY_TYPE
1373 && TREE_CODE (TREE_TYPE (optype)) == ARRAY_TYPE)
1374 optype = TREE_TYPE (optype);
1376 /* Avoid arrays of pointers. */
1377 tree eltype = TREE_TYPE (optype);
1378 if (TREE_CODE (optype) != ARRAY_TYPE
1379 || !INTEGRAL_TYPE_P (eltype))
1380 return false;
1382 /* Fail when the array bound is unknown or zero. */
1383 val = TYPE_SIZE_UNIT (optype);
1384 if (!val || integer_zerop (val))
1385 return false;
1387 val = fold_build2 (MINUS_EXPR, TREE_TYPE (val), val,
1388 integer_one_node);
1390 /* Set the minimum size to zero since the string in
1391 the array could have zero length. */
1392 pdata->minlen = ssize_int (0);
1394 tight_bound = true;
1396 else if (TREE_CODE (arg) == COMPONENT_REF
1397 && (TREE_CODE (TREE_TYPE (TREE_OPERAND (arg, 1)))
1398 == ARRAY_TYPE))
1400 /* Use the type of the member array to determine the upper
1401 bound on the length of the array. This may be overly
1402 optimistic if the array itself isn't NUL-terminated and
1403 the caller relies on the subsequent member to contain
1404 the NUL but that would only be considered valid if
1405 the array were the last member of a struct. */
1407 tree fld = TREE_OPERAND (arg, 1);
1409 tree optype = TREE_TYPE (fld);
1411 /* Determine the "innermost" array type. */
1412 while (TREE_CODE (optype) == ARRAY_TYPE
1413 && TREE_CODE (TREE_TYPE (optype)) == ARRAY_TYPE)
1414 optype = TREE_TYPE (optype);
1416 /* Fail when the array bound is unknown or zero. */
1417 val = TYPE_SIZE_UNIT (optype);
1418 if (!val || integer_zerop (val))
1419 return false;
1420 val = fold_build2 (MINUS_EXPR, TREE_TYPE (val), val,
1421 integer_one_node);
1423 /* Set the minimum size to zero since the string in
1424 the array could have zero length. */
1425 pdata->minlen = ssize_int (0);
1427 /* The array size determined above is an optimistic bound
1428 on the length. If the array isn't nul-terminated the
1429 length computed by the library function would be greater.
1430 Even though using strlen to cross the subobject boundary
1431 is undefined, avoid drawing conclusions from the member
1432 type about the length here. */
1433 tight_bound = true;
1435 else if (VAR_P (arg))
1437 /* Avoid handling pointers to arrays. GCC might misuse
1438 a pointer to an array of one bound to point to an array
1439 object of a greater bound. */
1440 tree argtype = TREE_TYPE (arg);
1441 if (TREE_CODE (argtype) == ARRAY_TYPE)
1443 val = TYPE_SIZE_UNIT (argtype);
1444 if (!val
1445 || TREE_CODE (val) != INTEGER_CST
1446 || integer_zerop (val))
1447 return false;
1448 val = wide_int_to_tree (TREE_TYPE (val),
1449 wi::sub (wi::to_wide (val), 1));
1451 /* Set the minimum size to zero since the string in
1452 the array could have zero length. */
1453 pdata->minlen = ssize_int (0);
1458 if (!val)
1459 return false;
1461 /* Adjust the lower bound on the string length as necessary. */
1462 if (!pdata->minlen
1463 || (rkind != SRK_STRLEN
1464 && TREE_CODE (pdata->minlen) == INTEGER_CST
1465 && TREE_CODE (val) == INTEGER_CST
1466 && tree_int_cst_lt (val, pdata->minlen)))
1467 pdata->minlen = val;
1469 if (pdata->maxbound)
1471 /* Adjust the tighter (more optimistic) string length bound
1472 if necessary and proceed to adjust the more conservative
1473 bound. */
1474 if (TREE_CODE (val) == INTEGER_CST)
1476 if (TREE_CODE (pdata->maxbound) == INTEGER_CST)
1478 if (tree_int_cst_lt (pdata->maxbound, val))
1479 pdata->maxbound = val;
1481 else
1482 pdata->maxbound = build_all_ones_cst (size_type_node);
1484 else
1485 pdata->maxbound = val;
1487 else
1488 pdata->maxbound = val;
1490 if (tight_bound)
1492 /* VAL computed above represents an optimistically tight bound
1493 on the length of the string based on the referenced object's
1494 or subobject's type. Determine the conservative upper bound
1495 based on the enclosing object's size if possible. */
1496 if (rkind == SRK_LENRANGE)
1498 poly_int64 offset;
1499 tree base = get_addr_base_and_unit_offset (arg, &offset);
1500 if (!base)
1502 /* When the call above fails due to a non-constant offset
1503 assume the offset is zero and use the size of the whole
1504 enclosing object instead. */
1505 base = get_base_address (arg);
1506 offset = 0;
1508 /* If the base object is a pointer no upper bound on the length
1509 can be determined. Otherwise the maximum length is equal to
1510 the size of the enclosing object minus the offset of
1511 the referenced subobject minus 1 (for the terminating nul). */
1512 tree type = TREE_TYPE (base);
1513 if (TREE_CODE (type) == POINTER_TYPE
1514 || !VAR_P (base) || !(val = DECL_SIZE_UNIT (base)))
1515 val = build_all_ones_cst (size_type_node);
1516 else
1518 val = DECL_SIZE_UNIT (base);
1519 val = fold_build2 (MINUS_EXPR, TREE_TYPE (val), val,
1520 size_int (offset + 1));
1523 else
1524 return false;
1527 if (pdata->maxlen)
1529 /* Adjust the more conservative bound if possible/necessary
1530 and fail otherwise. */
1531 if (rkind != SRK_STRLEN)
1533 if (TREE_CODE (pdata->maxlen) != INTEGER_CST
1534 || TREE_CODE (val) != INTEGER_CST)
1535 return false;
1537 if (tree_int_cst_lt (pdata->maxlen, val))
1538 pdata->maxlen = val;
1539 return true;
1541 else if (simple_cst_equal (val, pdata->maxlen) != 1)
1543 /* Fail if the length of this ARG is different from that
1544 previously determined from another ARG. */
1545 return false;
1549 pdata->maxlen = val;
1550 return rkind == SRK_LENRANGE || !integer_all_onesp (val);
1553 /* For an ARG referencing one or more strings, try to obtain the range
1554 of their lengths, or the size of the largest array ARG referes to if
1555 the range of lengths cannot be determined, and store all in *PDATA.
1556 For an integer ARG (when RKIND == SRK_INT_VALUE), try to determine
1557 the maximum constant value.
1558 If ARG is an SSA_NAME, follow its use-def chains. When RKIND ==
1559 SRK_STRLEN, then if PDATA->MAXLEN is not equal to the determined
1560 length or if we are unable to determine the length, return false.
1561 VISITED is a bitmap of visited variables.
1562 RKIND determines the kind of value or range to obtain (see
1563 strlen_range_kind).
1564 Set PDATA->DECL if ARG refers to an unterminated constant array.
1565 On input, set ELTSIZE to 1 for normal single byte character strings,
1566 and either 2 or 4 for wide characer strings (the size of wchar_t).
1567 Return true if *PDATA was successfully populated and false otherwise. */
1569 static bool
1570 get_range_strlen (tree arg, bitmap *visited,
1571 strlen_range_kind rkind,
1572 c_strlen_data *pdata, unsigned eltsize)
1575 if (TREE_CODE (arg) != SSA_NAME)
1576 return get_range_strlen_tree (arg, visited, rkind, pdata, eltsize);
1578 /* If ARG is registered for SSA update we cannot look at its defining
1579 statement. */
1580 if (name_registered_for_update_p (arg))
1581 return false;
1583 /* If we were already here, break the infinite cycle. */
1584 if (!*visited)
1585 *visited = BITMAP_ALLOC (NULL);
1586 if (!bitmap_set_bit (*visited, SSA_NAME_VERSION (arg)))
1587 return true;
1589 tree var = arg;
1590 gimple *def_stmt = SSA_NAME_DEF_STMT (var);
1592 switch (gimple_code (def_stmt))
1594 case GIMPLE_ASSIGN:
1595 /* The RHS of the statement defining VAR must either have a
1596 constant length or come from another SSA_NAME with a constant
1597 length. */
1598 if (gimple_assign_single_p (def_stmt)
1599 || gimple_assign_unary_nop_p (def_stmt))
1601 tree rhs = gimple_assign_rhs1 (def_stmt);
1602 return get_range_strlen (rhs, visited, rkind, pdata, eltsize);
1604 else if (gimple_assign_rhs_code (def_stmt) == COND_EXPR)
1606 tree ops[2] = { gimple_assign_rhs2 (def_stmt),
1607 gimple_assign_rhs3 (def_stmt) };
1609 for (unsigned int i = 0; i < 2; i++)
1610 if (!get_range_strlen (ops[i], visited, rkind, pdata, eltsize))
1612 if (rkind != SRK_LENRANGE)
1613 return false;
1614 /* Set the upper bound to the maximum to prevent
1615 it from being adjusted in the next iteration but
1616 leave MINLEN and the more conservative MAXBOUND
1617 determined so far alone (or leave them null if
1618 they haven't been set yet). That the MINLEN is
1619 in fact zero can be determined from MAXLEN being
1620 unbounded but the discovered minimum is used for
1621 diagnostics. */
1622 pdata->maxlen = build_all_ones_cst (size_type_node);
1624 return true;
1626 return false;
1628 case GIMPLE_PHI:
1629 /* Unless RKIND == SRK_LENRANGE, all arguments of the PHI node
1630 must have a constant length. */
1631 for (unsigned i = 0; i < gimple_phi_num_args (def_stmt); i++)
1633 tree arg = gimple_phi_arg (def_stmt, i)->def;
1635 /* If this PHI has itself as an argument, we cannot
1636 determine the string length of this argument. However,
1637 if we can find a constant string length for the other
1638 PHI args then we can still be sure that this is a
1639 constant string length. So be optimistic and just
1640 continue with the next argument. */
1641 if (arg == gimple_phi_result (def_stmt))
1642 continue;
1644 if (!get_range_strlen (arg, visited, rkind, pdata, eltsize))
1646 if (rkind != SRK_LENRANGE)
1647 return false;
1648 /* Set the upper bound to the maximum to prevent
1649 it from being adjusted in the next iteration but
1650 leave MINLEN and the more conservative MAXBOUND
1651 determined so far alone (or leave them null if
1652 they haven't been set yet). That the MINLEN is
1653 in fact zero can be determined from MAXLEN being
1654 unbounded but the discovered minimum is used for
1655 diagnostics. */
1656 pdata->maxlen = build_all_ones_cst (size_type_node);
1659 return true;
1661 default:
1662 return false;
1666 /* Determine the minimum and maximum value or string length that ARG
1667 refers to and store each in the first two elements of MINMAXLEN.
1668 For expressions that point to strings of unknown lengths that are
1669 character arrays, use the upper bound of the array as the maximum
1670 length. For example, given an expression like 'x ? array : "xyz"'
1671 and array declared as 'char array[8]', MINMAXLEN[0] will be set
1672 to 0 and MINMAXLEN[1] to 7, the longest string that could be
1673 stored in array.
1674 Return true if the range of the string lengths has been obtained
1675 from the upper bound of an array at the end of a struct. Such
1676 an array may hold a string that's longer than its upper bound
1677 due to it being used as a poor-man's flexible array member.
1679 STRICT is true if it will handle PHIs and COND_EXPRs conservatively
1680 and false if PHIs and COND_EXPRs are to be handled optimistically,
1681 if we can determine string length minimum and maximum; it will use
1682 the minimum from the ones where it can be determined.
1683 STRICT false should be only used for warning code.
1684 When non-null, clear *NONSTR if ARG refers to a constant array
1685 that is known not be nul-terminated. Otherwise set it to
1686 the declaration of the constant non-terminated array.
1688 ELTSIZE is 1 for normal single byte character strings, and 2 or
1689 4 for wide characer strings. ELTSIZE is by default 1. */
1691 bool
1692 get_range_strlen (tree arg, c_strlen_data *pdata, unsigned eltsize)
1694 bitmap visited = NULL;
1696 if (!get_range_strlen (arg, &visited, SRK_LENRANGE, pdata, eltsize))
1698 /* On failure extend the length range to an impossible maximum
1699 (a valid MAXLEN must be less than PTRDIFF_MAX - 1). Other
1700 members can stay unchanged regardless. */
1701 pdata->minlen = ssize_int (0);
1702 pdata->maxlen = build_all_ones_cst (size_type_node);
1704 else if (!pdata->minlen)
1705 pdata->minlen = ssize_int (0);
1707 /* Unless its null, leave the more conservative MAXBOUND unchanged. */
1708 if (!pdata->maxbound)
1709 pdata->maxbound = pdata->maxlen;
1711 if (visited)
1712 BITMAP_FREE (visited);
1714 return !integer_all_onesp (pdata->maxlen);
1717 /* Return the maximum value for ARG given RKIND (see strlen_range_kind).
1718 For ARG of pointer types, NONSTR indicates if the caller is prepared
1719 to handle unterminated strings. For integer ARG and when RKIND ==
1720 SRK_INT_VALUE, NONSTR must be null.
1722 If an unterminated array is discovered and our caller handles
1723 unterminated arrays, then bubble up the offending DECL and
1724 return the maximum size. Otherwise return NULL. */
1726 static tree
1727 get_maxval_strlen (tree arg, strlen_range_kind rkind, tree *nonstr = NULL)
1729 /* A non-null NONSTR is meaningless when determining the maximum
1730 value of an integer ARG. */
1731 gcc_assert (rkind != SRK_INT_VALUE || nonstr == NULL);
1732 /* ARG must have an integral type when RKIND says so. */
1733 gcc_assert (rkind != SRK_INT_VALUE || INTEGRAL_TYPE_P (TREE_TYPE (arg)));
1735 bitmap visited = NULL;
1737 /* Reset DATA.MAXLEN if the call fails or when DATA.MAXLEN
1738 is unbounded. */
1739 c_strlen_data lendata = { };
1740 if (!get_range_strlen (arg, &visited, rkind, &lendata, /* eltsize = */1))
1741 lendata.maxlen = NULL_TREE;
1742 else if (lendata.maxlen && integer_all_onesp (lendata.maxlen))
1743 lendata.maxlen = NULL_TREE;
1745 if (visited)
1746 BITMAP_FREE (visited);
1748 if (nonstr)
1750 /* For callers prepared to handle unterminated arrays set
1751 *NONSTR to point to the declaration of the array and return
1752 the maximum length/size. */
1753 *nonstr = lendata.decl;
1754 return lendata.maxlen;
1757 /* Fail if the constant array isn't nul-terminated. */
1758 return lendata.decl ? NULL_TREE : lendata.maxlen;
1762 /* Fold function call to builtin strcpy with arguments DEST and SRC.
1763 If LEN is not NULL, it represents the length of the string to be
1764 copied. Return NULL_TREE if no simplification can be made. */
1766 static bool
1767 gimple_fold_builtin_strcpy (gimple_stmt_iterator *gsi,
1768 tree dest, tree src)
1770 gimple *stmt = gsi_stmt (*gsi);
1771 location_t loc = gimple_location (stmt);
1772 tree fn;
1774 /* If SRC and DEST are the same (and not volatile), return DEST. */
1775 if (operand_equal_p (src, dest, 0))
1777 /* Issue -Wrestrict unless the pointers are null (those do
1778 not point to objects and so do not indicate an overlap;
1779 such calls could be the result of sanitization and jump
1780 threading). */
1781 if (!integer_zerop (dest) && !gimple_no_warning_p (stmt))
1783 tree func = gimple_call_fndecl (stmt);
1785 warning_at (loc, OPT_Wrestrict,
1786 "%qD source argument is the same as destination",
1787 func);
1790 replace_call_with_value (gsi, dest);
1791 return true;
1794 if (optimize_function_for_size_p (cfun))
1795 return false;
1797 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1798 if (!fn)
1799 return false;
1801 /* Set to non-null if ARG refers to an unterminated array. */
1802 tree nonstr = NULL;
1803 tree len = get_maxval_strlen (src, SRK_STRLEN, &nonstr);
1805 if (nonstr)
1807 /* Avoid folding calls with unterminated arrays. */
1808 if (!gimple_no_warning_p (stmt))
1809 warn_string_no_nul (loc, "strcpy", src, nonstr);
1810 gimple_set_no_warning (stmt, true);
1811 return false;
1814 if (!len)
1815 return false;
1817 len = fold_convert_loc (loc, size_type_node, len);
1818 len = size_binop_loc (loc, PLUS_EXPR, len, build_int_cst (size_type_node, 1));
1819 len = force_gimple_operand_gsi (gsi, len, true,
1820 NULL_TREE, true, GSI_SAME_STMT);
1821 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
1822 replace_call_with_call_and_fold (gsi, repl);
1823 return true;
1826 /* Fold function call to builtin strncpy with arguments DEST, SRC, and LEN.
1827 If SLEN is not NULL, it represents the length of the source string.
1828 Return NULL_TREE if no simplification can be made. */
1830 static bool
1831 gimple_fold_builtin_strncpy (gimple_stmt_iterator *gsi,
1832 tree dest, tree src, tree len)
1834 gimple *stmt = gsi_stmt (*gsi);
1835 location_t loc = gimple_location (stmt);
1836 bool nonstring = get_attr_nonstring_decl (dest) != NULL_TREE;
1838 /* If the LEN parameter is zero, return DEST. */
1839 if (integer_zerop (len))
1841 /* Avoid warning if the destination refers to a an array/pointer
1842 decorate with attribute nonstring. */
1843 if (!nonstring)
1845 tree fndecl = gimple_call_fndecl (stmt);
1847 /* Warn about the lack of nul termination: the result is not
1848 a (nul-terminated) string. */
1849 tree slen = get_maxval_strlen (src, SRK_STRLEN);
1850 if (slen && !integer_zerop (slen))
1851 warning_at (loc, OPT_Wstringop_truncation,
1852 "%G%qD destination unchanged after copying no bytes "
1853 "from a string of length %E",
1854 stmt, fndecl, slen);
1855 else
1856 warning_at (loc, OPT_Wstringop_truncation,
1857 "%G%qD destination unchanged after copying no bytes",
1858 stmt, fndecl);
1861 replace_call_with_value (gsi, dest);
1862 return true;
1865 /* We can't compare slen with len as constants below if len is not a
1866 constant. */
1867 if (TREE_CODE (len) != INTEGER_CST)
1868 return false;
1870 /* Now, we must be passed a constant src ptr parameter. */
1871 tree slen = get_maxval_strlen (src, SRK_STRLEN);
1872 if (!slen || TREE_CODE (slen) != INTEGER_CST)
1873 return false;
1875 /* The size of the source string including the terminating nul. */
1876 tree ssize = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
1878 /* We do not support simplification of this case, though we do
1879 support it when expanding trees into RTL. */
1880 /* FIXME: generate a call to __builtin_memset. */
1881 if (tree_int_cst_lt (ssize, len))
1882 return false;
1884 /* Diagnose truncation that leaves the copy unterminated. */
1885 maybe_diag_stxncpy_trunc (*gsi, src, len);
1887 /* OK transform into builtin memcpy. */
1888 tree fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1889 if (!fn)
1890 return false;
1892 len = fold_convert_loc (loc, size_type_node, len);
1893 len = force_gimple_operand_gsi (gsi, len, true,
1894 NULL_TREE, true, GSI_SAME_STMT);
1895 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
1896 replace_call_with_call_and_fold (gsi, repl);
1898 return true;
1901 /* Fold function call to builtin strchr or strrchr.
1902 If both arguments are constant, evaluate and fold the result,
1903 otherwise simplify str(r)chr (str, 0) into str + strlen (str).
1904 In general strlen is significantly faster than strchr
1905 due to being a simpler operation. */
1906 static bool
1907 gimple_fold_builtin_strchr (gimple_stmt_iterator *gsi, bool is_strrchr)
1909 gimple *stmt = gsi_stmt (*gsi);
1910 tree str = gimple_call_arg (stmt, 0);
1911 tree c = gimple_call_arg (stmt, 1);
1912 location_t loc = gimple_location (stmt);
1913 const char *p;
1914 char ch;
1916 if (!gimple_call_lhs (stmt))
1917 return false;
1919 if ((p = c_getstr (str)) && target_char_cst_p (c, &ch))
1921 const char *p1 = is_strrchr ? strrchr (p, ch) : strchr (p, ch);
1923 if (p1 == NULL)
1925 replace_call_with_value (gsi, integer_zero_node);
1926 return true;
1929 tree len = build_int_cst (size_type_node, p1 - p);
1930 gimple_seq stmts = NULL;
1931 gimple *new_stmt = gimple_build_assign (gimple_call_lhs (stmt),
1932 POINTER_PLUS_EXPR, str, len);
1933 gimple_seq_add_stmt_without_update (&stmts, new_stmt);
1934 gsi_replace_with_seq_vops (gsi, stmts);
1935 return true;
1938 if (!integer_zerop (c))
1939 return false;
1941 /* Transform strrchr (s, 0) to strchr (s, 0) when optimizing for size. */
1942 if (is_strrchr && optimize_function_for_size_p (cfun))
1944 tree strchr_fn = builtin_decl_implicit (BUILT_IN_STRCHR);
1946 if (strchr_fn)
1948 gimple *repl = gimple_build_call (strchr_fn, 2, str, c);
1949 replace_call_with_call_and_fold (gsi, repl);
1950 return true;
1953 return false;
1956 tree len;
1957 tree strlen_fn = builtin_decl_implicit (BUILT_IN_STRLEN);
1959 if (!strlen_fn)
1960 return false;
1962 /* Create newstr = strlen (str). */
1963 gimple_seq stmts = NULL;
1964 gimple *new_stmt = gimple_build_call (strlen_fn, 1, str);
1965 gimple_set_location (new_stmt, loc);
1966 len = create_tmp_reg_or_ssa_name (size_type_node);
1967 gimple_call_set_lhs (new_stmt, len);
1968 gimple_seq_add_stmt_without_update (&stmts, new_stmt);
1970 /* Create (str p+ strlen (str)). */
1971 new_stmt = gimple_build_assign (gimple_call_lhs (stmt),
1972 POINTER_PLUS_EXPR, str, len);
1973 gimple_seq_add_stmt_without_update (&stmts, new_stmt);
1974 gsi_replace_with_seq_vops (gsi, stmts);
1975 /* gsi now points at the assignment to the lhs, get a
1976 stmt iterator to the strlen.
1977 ??? We can't use gsi_for_stmt as that doesn't work when the
1978 CFG isn't built yet. */
1979 gimple_stmt_iterator gsi2 = *gsi;
1980 gsi_prev (&gsi2);
1981 fold_stmt (&gsi2);
1982 return true;
1985 /* Fold function call to builtin strstr.
1986 If both arguments are constant, evaluate and fold the result,
1987 additionally fold strstr (x, "") into x and strstr (x, "c")
1988 into strchr (x, 'c'). */
1989 static bool
1990 gimple_fold_builtin_strstr (gimple_stmt_iterator *gsi)
1992 gimple *stmt = gsi_stmt (*gsi);
1993 tree haystack = gimple_call_arg (stmt, 0);
1994 tree needle = gimple_call_arg (stmt, 1);
1995 const char *p, *q;
1997 if (!gimple_call_lhs (stmt))
1998 return false;
2000 q = c_getstr (needle);
2001 if (q == NULL)
2002 return false;
2004 if ((p = c_getstr (haystack)))
2006 const char *r = strstr (p, q);
2008 if (r == NULL)
2010 replace_call_with_value (gsi, integer_zero_node);
2011 return true;
2014 tree len = build_int_cst (size_type_node, r - p);
2015 gimple_seq stmts = NULL;
2016 gimple *new_stmt
2017 = gimple_build_assign (gimple_call_lhs (stmt), POINTER_PLUS_EXPR,
2018 haystack, len);
2019 gimple_seq_add_stmt_without_update (&stmts, new_stmt);
2020 gsi_replace_with_seq_vops (gsi, stmts);
2021 return true;
2024 /* For strstr (x, "") return x. */
2025 if (q[0] == '\0')
2027 replace_call_with_value (gsi, haystack);
2028 return true;
2031 /* Transform strstr (x, "c") into strchr (x, 'c'). */
2032 if (q[1] == '\0')
2034 tree strchr_fn = builtin_decl_implicit (BUILT_IN_STRCHR);
2035 if (strchr_fn)
2037 tree c = build_int_cst (integer_type_node, q[0]);
2038 gimple *repl = gimple_build_call (strchr_fn, 2, haystack, c);
2039 replace_call_with_call_and_fold (gsi, repl);
2040 return true;
2044 return false;
2047 /* Simplify a call to the strcat builtin. DST and SRC are the arguments
2048 to the call.
2050 Return NULL_TREE if no simplification was possible, otherwise return the
2051 simplified form of the call as a tree.
2053 The simplified form may be a constant or other expression which
2054 computes the same value, but in a more efficient manner (including
2055 calls to other builtin functions).
2057 The call may contain arguments which need to be evaluated, but
2058 which are not useful to determine the result of the call. In
2059 this case we return a chain of COMPOUND_EXPRs. The LHS of each
2060 COMPOUND_EXPR will be an argument which must be evaluated.
2061 COMPOUND_EXPRs are chained through their RHS. The RHS of the last
2062 COMPOUND_EXPR in the chain will contain the tree for the simplified
2063 form of the builtin function call. */
2065 static bool
2066 gimple_fold_builtin_strcat (gimple_stmt_iterator *gsi, tree dst, tree src)
2068 gimple *stmt = gsi_stmt (*gsi);
2069 location_t loc = gimple_location (stmt);
2071 const char *p = c_getstr (src);
2073 /* If the string length is zero, return the dst parameter. */
2074 if (p && *p == '\0')
2076 replace_call_with_value (gsi, dst);
2077 return true;
2080 if (!optimize_bb_for_speed_p (gimple_bb (stmt)))
2081 return false;
2083 /* See if we can store by pieces into (dst + strlen(dst)). */
2084 tree newdst;
2085 tree strlen_fn = builtin_decl_implicit (BUILT_IN_STRLEN);
2086 tree memcpy_fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
2088 if (!strlen_fn || !memcpy_fn)
2089 return false;
2091 /* If the length of the source string isn't computable don't
2092 split strcat into strlen and memcpy. */
2093 tree len = get_maxval_strlen (src, SRK_STRLEN);
2094 if (! len)
2095 return false;
2097 /* Create strlen (dst). */
2098 gimple_seq stmts = NULL, stmts2;
2099 gimple *repl = gimple_build_call (strlen_fn, 1, dst);
2100 gimple_set_location (repl, loc);
2101 newdst = create_tmp_reg_or_ssa_name (size_type_node);
2102 gimple_call_set_lhs (repl, newdst);
2103 gimple_seq_add_stmt_without_update (&stmts, repl);
2105 /* Create (dst p+ strlen (dst)). */
2106 newdst = fold_build_pointer_plus_loc (loc, dst, newdst);
2107 newdst = force_gimple_operand (newdst, &stmts2, true, NULL_TREE);
2108 gimple_seq_add_seq_without_update (&stmts, stmts2);
2110 len = fold_convert_loc (loc, size_type_node, len);
2111 len = size_binop_loc (loc, PLUS_EXPR, len,
2112 build_int_cst (size_type_node, 1));
2113 len = force_gimple_operand (len, &stmts2, true, NULL_TREE);
2114 gimple_seq_add_seq_without_update (&stmts, stmts2);
2116 repl = gimple_build_call (memcpy_fn, 3, newdst, src, len);
2117 gimple_seq_add_stmt_without_update (&stmts, repl);
2118 if (gimple_call_lhs (stmt))
2120 repl = gimple_build_assign (gimple_call_lhs (stmt), dst);
2121 gimple_seq_add_stmt_without_update (&stmts, repl);
2122 gsi_replace_with_seq_vops (gsi, stmts);
2123 /* gsi now points at the assignment to the lhs, get a
2124 stmt iterator to the memcpy call.
2125 ??? We can't use gsi_for_stmt as that doesn't work when the
2126 CFG isn't built yet. */
2127 gimple_stmt_iterator gsi2 = *gsi;
2128 gsi_prev (&gsi2);
2129 fold_stmt (&gsi2);
2131 else
2133 gsi_replace_with_seq_vops (gsi, stmts);
2134 fold_stmt (gsi);
2136 return true;
2139 /* Fold a call to the __strcat_chk builtin FNDECL. DEST, SRC, and SIZE
2140 are the arguments to the call. */
2142 static bool
2143 gimple_fold_builtin_strcat_chk (gimple_stmt_iterator *gsi)
2145 gimple *stmt = gsi_stmt (*gsi);
2146 tree dest = gimple_call_arg (stmt, 0);
2147 tree src = gimple_call_arg (stmt, 1);
2148 tree size = gimple_call_arg (stmt, 2);
2149 tree fn;
2150 const char *p;
2153 p = c_getstr (src);
2154 /* If the SRC parameter is "", return DEST. */
2155 if (p && *p == '\0')
2157 replace_call_with_value (gsi, dest);
2158 return true;
2161 if (! tree_fits_uhwi_p (size) || ! integer_all_onesp (size))
2162 return false;
2164 /* If __builtin_strcat_chk is used, assume strcat is available. */
2165 fn = builtin_decl_explicit (BUILT_IN_STRCAT);
2166 if (!fn)
2167 return false;
2169 gimple *repl = gimple_build_call (fn, 2, dest, src);
2170 replace_call_with_call_and_fold (gsi, repl);
2171 return true;
2174 /* Simplify a call to the strncat builtin. */
2176 static bool
2177 gimple_fold_builtin_strncat (gimple_stmt_iterator *gsi)
2179 gimple *stmt = gsi_stmt (*gsi);
2180 tree dst = gimple_call_arg (stmt, 0);
2181 tree src = gimple_call_arg (stmt, 1);
2182 tree len = gimple_call_arg (stmt, 2);
2184 const char *p = c_getstr (src);
2186 /* If the requested length is zero, or the src parameter string
2187 length is zero, return the dst parameter. */
2188 if (integer_zerop (len) || (p && *p == '\0'))
2190 replace_call_with_value (gsi, dst);
2191 return true;
2194 if (TREE_CODE (len) != INTEGER_CST || !p)
2195 return false;
2197 unsigned srclen = strlen (p);
2199 int cmpsrc = compare_tree_int (len, srclen);
2201 /* Return early if the requested len is less than the string length.
2202 Warnings will be issued elsewhere later. */
2203 if (cmpsrc < 0)
2204 return false;
2206 unsigned HOST_WIDE_INT dstsize;
2208 bool nowarn = gimple_no_warning_p (stmt);
2210 if (!nowarn && compute_builtin_object_size (dst, 1, &dstsize))
2212 int cmpdst = compare_tree_int (len, dstsize);
2214 if (cmpdst >= 0)
2216 tree fndecl = gimple_call_fndecl (stmt);
2218 /* Strncat copies (at most) LEN bytes and always appends
2219 the terminating NUL so the specified bound should never
2220 be equal to (or greater than) the size of the destination.
2221 If it is, the copy could overflow. */
2222 location_t loc = gimple_location (stmt);
2223 nowarn = warning_at (loc, OPT_Wstringop_overflow_,
2224 cmpdst == 0
2225 ? G_("%G%qD specified bound %E equals "
2226 "destination size")
2227 : G_("%G%qD specified bound %E exceeds "
2228 "destination size %wu"),
2229 stmt, fndecl, len, dstsize);
2230 if (nowarn)
2231 gimple_set_no_warning (stmt, true);
2235 if (!nowarn && cmpsrc == 0)
2237 tree fndecl = gimple_call_fndecl (stmt);
2238 location_t loc = gimple_location (stmt);
2240 /* To avoid possible overflow the specified bound should also
2241 not be equal to the length of the source, even when the size
2242 of the destination is unknown (it's not an uncommon mistake
2243 to specify as the bound to strncpy the length of the source). */
2244 if (warning_at (loc, OPT_Wstringop_overflow_,
2245 "%G%qD specified bound %E equals source length",
2246 stmt, fndecl, len))
2247 gimple_set_no_warning (stmt, true);
2250 tree fn = builtin_decl_implicit (BUILT_IN_STRCAT);
2252 /* If the replacement _DECL isn't initialized, don't do the
2253 transformation. */
2254 if (!fn)
2255 return false;
2257 /* Otherwise, emit a call to strcat. */
2258 gcall *repl = gimple_build_call (fn, 2, dst, src);
2259 replace_call_with_call_and_fold (gsi, repl);
2260 return true;
2263 /* Fold a call to the __strncat_chk builtin with arguments DEST, SRC,
2264 LEN, and SIZE. */
2266 static bool
2267 gimple_fold_builtin_strncat_chk (gimple_stmt_iterator *gsi)
2269 gimple *stmt = gsi_stmt (*gsi);
2270 tree dest = gimple_call_arg (stmt, 0);
2271 tree src = gimple_call_arg (stmt, 1);
2272 tree len = gimple_call_arg (stmt, 2);
2273 tree size = gimple_call_arg (stmt, 3);
2274 tree fn;
2275 const char *p;
2277 p = c_getstr (src);
2278 /* If the SRC parameter is "" or if LEN is 0, return DEST. */
2279 if ((p && *p == '\0')
2280 || integer_zerop (len))
2282 replace_call_with_value (gsi, dest);
2283 return true;
2286 if (! tree_fits_uhwi_p (size))
2287 return false;
2289 if (! integer_all_onesp (size))
2291 tree src_len = c_strlen (src, 1);
2292 if (src_len
2293 && tree_fits_uhwi_p (src_len)
2294 && tree_fits_uhwi_p (len)
2295 && ! tree_int_cst_lt (len, src_len))
2297 /* If LEN >= strlen (SRC), optimize into __strcat_chk. */
2298 fn = builtin_decl_explicit (BUILT_IN_STRCAT_CHK);
2299 if (!fn)
2300 return false;
2302 gimple *repl = gimple_build_call (fn, 3, dest, src, size);
2303 replace_call_with_call_and_fold (gsi, repl);
2304 return true;
2306 return false;
2309 /* If __builtin_strncat_chk is used, assume strncat is available. */
2310 fn = builtin_decl_explicit (BUILT_IN_STRNCAT);
2311 if (!fn)
2312 return false;
2314 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
2315 replace_call_with_call_and_fold (gsi, repl);
2316 return true;
2319 /* Build and append gimple statements to STMTS that would load a first
2320 character of a memory location identified by STR. LOC is location
2321 of the statement. */
2323 static tree
2324 gimple_load_first_char (location_t loc, tree str, gimple_seq *stmts)
2326 tree var;
2328 tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
2329 tree cst_uchar_ptr_node
2330 = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
2331 tree off0 = build_int_cst (cst_uchar_ptr_node, 0);
2333 tree temp = fold_build2_loc (loc, MEM_REF, cst_uchar_node, str, off0);
2334 gassign *stmt = gimple_build_assign (NULL_TREE, temp);
2335 var = create_tmp_reg_or_ssa_name (cst_uchar_node, stmt);
2337 gimple_assign_set_lhs (stmt, var);
2338 gimple_seq_add_stmt_without_update (stmts, stmt);
2340 return var;
2343 /* Fold a call to the str{n}{case}cmp builtin pointed by GSI iterator.
2344 FCODE is the name of the builtin. */
2346 static bool
2347 gimple_fold_builtin_string_compare (gimple_stmt_iterator *gsi)
2349 gimple *stmt = gsi_stmt (*gsi);
2350 tree callee = gimple_call_fndecl (stmt);
2351 enum built_in_function fcode = DECL_FUNCTION_CODE (callee);
2353 tree type = integer_type_node;
2354 tree str1 = gimple_call_arg (stmt, 0);
2355 tree str2 = gimple_call_arg (stmt, 1);
2356 tree lhs = gimple_call_lhs (stmt);
2357 HOST_WIDE_INT length = -1;
2359 /* Handle strncmp and strncasecmp functions. */
2360 if (gimple_call_num_args (stmt) == 3)
2362 tree len = gimple_call_arg (stmt, 2);
2363 if (tree_fits_uhwi_p (len))
2364 length = tree_to_uhwi (len);
2367 /* If the LEN parameter is zero, return zero. */
2368 if (length == 0)
2370 replace_call_with_value (gsi, integer_zero_node);
2371 return true;
2374 /* If ARG1 and ARG2 are the same (and not volatile), return zero. */
2375 if (operand_equal_p (str1, str2, 0))
2377 replace_call_with_value (gsi, integer_zero_node);
2378 return true;
2381 const char *p1 = c_getstr (str1);
2382 const char *p2 = c_getstr (str2);
2384 /* For known strings, return an immediate value. */
2385 if (p1 && p2)
2387 int r = 0;
2388 bool known_result = false;
2390 switch (fcode)
2392 case BUILT_IN_STRCMP:
2393 case BUILT_IN_STRCMP_EQ:
2395 r = strcmp (p1, p2);
2396 known_result = true;
2397 break;
2399 case BUILT_IN_STRNCMP:
2400 case BUILT_IN_STRNCMP_EQ:
2402 if (length == -1)
2403 break;
2404 r = strncmp (p1, p2, length);
2405 known_result = true;
2406 break;
2408 /* Only handleable situation is where the string are equal (result 0),
2409 which is already handled by operand_equal_p case. */
2410 case BUILT_IN_STRCASECMP:
2411 break;
2412 case BUILT_IN_STRNCASECMP:
2414 if (length == -1)
2415 break;
2416 r = strncmp (p1, p2, length);
2417 if (r == 0)
2418 known_result = true;
2419 break;
2421 default:
2422 gcc_unreachable ();
2425 if (known_result)
2427 replace_call_with_value (gsi, build_cmp_result (type, r));
2428 return true;
2432 bool nonzero_length = length >= 1
2433 || fcode == BUILT_IN_STRCMP
2434 || fcode == BUILT_IN_STRCMP_EQ
2435 || fcode == BUILT_IN_STRCASECMP;
2437 location_t loc = gimple_location (stmt);
2439 /* If the second arg is "", return *(const unsigned char*)arg1. */
2440 if (p2 && *p2 == '\0' && nonzero_length)
2442 gimple_seq stmts = NULL;
2443 tree var = gimple_load_first_char (loc, str1, &stmts);
2444 if (lhs)
2446 stmt = gimple_build_assign (lhs, NOP_EXPR, var);
2447 gimple_seq_add_stmt_without_update (&stmts, stmt);
2450 gsi_replace_with_seq_vops (gsi, stmts);
2451 return true;
2454 /* If the first arg is "", return -*(const unsigned char*)arg2. */
2455 if (p1 && *p1 == '\0' && nonzero_length)
2457 gimple_seq stmts = NULL;
2458 tree var = gimple_load_first_char (loc, str2, &stmts);
2460 if (lhs)
2462 tree c = create_tmp_reg_or_ssa_name (integer_type_node);
2463 stmt = gimple_build_assign (c, NOP_EXPR, var);
2464 gimple_seq_add_stmt_without_update (&stmts, stmt);
2466 stmt = gimple_build_assign (lhs, NEGATE_EXPR, c);
2467 gimple_seq_add_stmt_without_update (&stmts, stmt);
2470 gsi_replace_with_seq_vops (gsi, stmts);
2471 return true;
2474 /* If len parameter is one, return an expression corresponding to
2475 (*(const unsigned char*)arg2 - *(const unsigned char*)arg1). */
2476 if (fcode == BUILT_IN_STRNCMP && length == 1)
2478 gimple_seq stmts = NULL;
2479 tree temp1 = gimple_load_first_char (loc, str1, &stmts);
2480 tree temp2 = gimple_load_first_char (loc, str2, &stmts);
2482 if (lhs)
2484 tree c1 = create_tmp_reg_or_ssa_name (integer_type_node);
2485 gassign *convert1 = gimple_build_assign (c1, NOP_EXPR, temp1);
2486 gimple_seq_add_stmt_without_update (&stmts, convert1);
2488 tree c2 = create_tmp_reg_or_ssa_name (integer_type_node);
2489 gassign *convert2 = gimple_build_assign (c2, NOP_EXPR, temp2);
2490 gimple_seq_add_stmt_without_update (&stmts, convert2);
2492 stmt = gimple_build_assign (lhs, MINUS_EXPR, c1, c2);
2493 gimple_seq_add_stmt_without_update (&stmts, stmt);
2496 gsi_replace_with_seq_vops (gsi, stmts);
2497 return true;
2500 /* If length is larger than the length of one constant string,
2501 replace strncmp with corresponding strcmp */
2502 if (fcode == BUILT_IN_STRNCMP
2503 && length > 0
2504 && ((p2 && (size_t) length > strlen (p2))
2505 || (p1 && (size_t) length > strlen (p1))))
2507 tree fn = builtin_decl_implicit (BUILT_IN_STRCMP);
2508 if (!fn)
2509 return false;
2510 gimple *repl = gimple_build_call (fn, 2, str1, str2);
2511 replace_call_with_call_and_fold (gsi, repl);
2512 return true;
2515 return false;
2518 /* Fold a call to the memchr pointed by GSI iterator. */
2520 static bool
2521 gimple_fold_builtin_memchr (gimple_stmt_iterator *gsi)
2523 gimple *stmt = gsi_stmt (*gsi);
2524 tree lhs = gimple_call_lhs (stmt);
2525 tree arg1 = gimple_call_arg (stmt, 0);
2526 tree arg2 = gimple_call_arg (stmt, 1);
2527 tree len = gimple_call_arg (stmt, 2);
2529 /* If the LEN parameter is zero, return zero. */
2530 if (integer_zerop (len))
2532 replace_call_with_value (gsi, build_int_cst (ptr_type_node, 0));
2533 return true;
2536 char c;
2537 if (TREE_CODE (arg2) != INTEGER_CST
2538 || !tree_fits_uhwi_p (len)
2539 || !target_char_cst_p (arg2, &c))
2540 return false;
2542 unsigned HOST_WIDE_INT length = tree_to_uhwi (len);
2543 unsigned HOST_WIDE_INT string_length;
2544 const char *p1 = c_getstr (arg1, &string_length);
2546 if (p1)
2548 const char *r = (const char *)memchr (p1, c, MIN (length, string_length));
2549 if (r == NULL)
2551 if (length <= string_length)
2553 replace_call_with_value (gsi, build_int_cst (ptr_type_node, 0));
2554 return true;
2557 else
2559 unsigned HOST_WIDE_INT offset = r - p1;
2560 gimple_seq stmts = NULL;
2561 if (lhs != NULL_TREE)
2563 tree offset_cst = build_int_cst (TREE_TYPE (len), offset);
2564 gassign *stmt = gimple_build_assign (lhs, POINTER_PLUS_EXPR,
2565 arg1, offset_cst);
2566 gimple_seq_add_stmt_without_update (&stmts, stmt);
2568 else
2569 gimple_seq_add_stmt_without_update (&stmts,
2570 gimple_build_nop ());
2572 gsi_replace_with_seq_vops (gsi, stmts);
2573 return true;
2577 return false;
2580 /* Fold a call to the fputs builtin. ARG0 and ARG1 are the arguments
2581 to the call. IGNORE is true if the value returned
2582 by the builtin will be ignored. UNLOCKED is true is true if this
2583 actually a call to fputs_unlocked. If LEN in non-NULL, it represents
2584 the known length of the string. Return NULL_TREE if no simplification
2585 was possible. */
2587 static bool
2588 gimple_fold_builtin_fputs (gimple_stmt_iterator *gsi,
2589 tree arg0, tree arg1,
2590 bool unlocked)
2592 gimple *stmt = gsi_stmt (*gsi);
2594 /* If we're using an unlocked function, assume the other unlocked
2595 functions exist explicitly. */
2596 tree const fn_fputc = (unlocked
2597 ? builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED)
2598 : builtin_decl_implicit (BUILT_IN_FPUTC));
2599 tree const fn_fwrite = (unlocked
2600 ? builtin_decl_explicit (BUILT_IN_FWRITE_UNLOCKED)
2601 : builtin_decl_implicit (BUILT_IN_FWRITE));
2603 /* If the return value is used, don't do the transformation. */
2604 if (gimple_call_lhs (stmt))
2605 return false;
2607 /* Get the length of the string passed to fputs. If the length
2608 can't be determined, punt. */
2609 tree len = get_maxval_strlen (arg0, SRK_STRLEN);
2610 if (!len
2611 || TREE_CODE (len) != INTEGER_CST)
2612 return false;
2614 switch (compare_tree_int (len, 1))
2616 case -1: /* length is 0, delete the call entirely . */
2617 replace_call_with_value (gsi, integer_zero_node);
2618 return true;
2620 case 0: /* length is 1, call fputc. */
2622 const char *p = c_getstr (arg0);
2623 if (p != NULL)
2625 if (!fn_fputc)
2626 return false;
2628 gimple *repl = gimple_build_call (fn_fputc, 2,
2629 build_int_cst
2630 (integer_type_node, p[0]), arg1);
2631 replace_call_with_call_and_fold (gsi, repl);
2632 return true;
2635 /* FALLTHROUGH */
2636 case 1: /* length is greater than 1, call fwrite. */
2638 /* If optimizing for size keep fputs. */
2639 if (optimize_function_for_size_p (cfun))
2640 return false;
2641 /* New argument list transforming fputs(string, stream) to
2642 fwrite(string, 1, len, stream). */
2643 if (!fn_fwrite)
2644 return false;
2646 gimple *repl = gimple_build_call (fn_fwrite, 4, arg0,
2647 size_one_node, len, arg1);
2648 replace_call_with_call_and_fold (gsi, repl);
2649 return true;
2651 default:
2652 gcc_unreachable ();
2654 return false;
2657 /* Fold a call to the __mem{cpy,pcpy,move,set}_chk builtin.
2658 DEST, SRC, LEN, and SIZE are the arguments to the call.
2659 IGNORE is true, if return value can be ignored. FCODE is the BUILT_IN_*
2660 code of the builtin. If MAXLEN is not NULL, it is maximum length
2661 passed as third argument. */
2663 static bool
2664 gimple_fold_builtin_memory_chk (gimple_stmt_iterator *gsi,
2665 tree dest, tree src, tree len, tree size,
2666 enum built_in_function fcode)
2668 gimple *stmt = gsi_stmt (*gsi);
2669 location_t loc = gimple_location (stmt);
2670 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
2671 tree fn;
2673 /* If SRC and DEST are the same (and not volatile), return DEST
2674 (resp. DEST+LEN for __mempcpy_chk). */
2675 if (fcode != BUILT_IN_MEMSET_CHK && operand_equal_p (src, dest, 0))
2677 if (fcode != BUILT_IN_MEMPCPY_CHK)
2679 replace_call_with_value (gsi, dest);
2680 return true;
2682 else
2684 gimple_seq stmts = NULL;
2685 len = gimple_convert_to_ptrofftype (&stmts, loc, len);
2686 tree temp = gimple_build (&stmts, loc, POINTER_PLUS_EXPR,
2687 TREE_TYPE (dest), dest, len);
2688 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
2689 replace_call_with_value (gsi, temp);
2690 return true;
2694 if (! tree_fits_uhwi_p (size))
2695 return false;
2697 tree maxlen = get_maxval_strlen (len, SRK_INT_VALUE);
2698 if (! integer_all_onesp (size))
2700 if (! tree_fits_uhwi_p (len))
2702 /* If LEN is not constant, try MAXLEN too.
2703 For MAXLEN only allow optimizing into non-_ocs function
2704 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
2705 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
2707 if (fcode == BUILT_IN_MEMPCPY_CHK && ignore)
2709 /* (void) __mempcpy_chk () can be optimized into
2710 (void) __memcpy_chk (). */
2711 fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
2712 if (!fn)
2713 return false;
2715 gimple *repl = gimple_build_call (fn, 4, dest, src, len, size);
2716 replace_call_with_call_and_fold (gsi, repl);
2717 return true;
2719 return false;
2722 else
2723 maxlen = len;
2725 if (tree_int_cst_lt (size, maxlen))
2726 return false;
2729 fn = NULL_TREE;
2730 /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
2731 mem{cpy,pcpy,move,set} is available. */
2732 switch (fcode)
2734 case BUILT_IN_MEMCPY_CHK:
2735 fn = builtin_decl_explicit (BUILT_IN_MEMCPY);
2736 break;
2737 case BUILT_IN_MEMPCPY_CHK:
2738 fn = builtin_decl_explicit (BUILT_IN_MEMPCPY);
2739 break;
2740 case BUILT_IN_MEMMOVE_CHK:
2741 fn = builtin_decl_explicit (BUILT_IN_MEMMOVE);
2742 break;
2743 case BUILT_IN_MEMSET_CHK:
2744 fn = builtin_decl_explicit (BUILT_IN_MEMSET);
2745 break;
2746 default:
2747 break;
2750 if (!fn)
2751 return false;
2753 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
2754 replace_call_with_call_and_fold (gsi, repl);
2755 return true;
2758 /* Fold a call to the __st[rp]cpy_chk builtin.
2759 DEST, SRC, and SIZE are the arguments to the call.
2760 IGNORE is true if return value can be ignored. FCODE is the BUILT_IN_*
2761 code of the builtin. If MAXLEN is not NULL, it is maximum length of
2762 strings passed as second argument. */
2764 static bool
2765 gimple_fold_builtin_stxcpy_chk (gimple_stmt_iterator *gsi,
2766 tree dest,
2767 tree src, tree size,
2768 enum built_in_function fcode)
2770 gimple *stmt = gsi_stmt (*gsi);
2771 location_t loc = gimple_location (stmt);
2772 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
2773 tree len, fn;
2775 /* If SRC and DEST are the same (and not volatile), return DEST. */
2776 if (fcode == BUILT_IN_STRCPY_CHK && operand_equal_p (src, dest, 0))
2778 /* Issue -Wrestrict unless the pointers are null (those do
2779 not point to objects and so do not indicate an overlap;
2780 such calls could be the result of sanitization and jump
2781 threading). */
2782 if (!integer_zerop (dest) && !gimple_no_warning_p (stmt))
2784 tree func = gimple_call_fndecl (stmt);
2786 warning_at (loc, OPT_Wrestrict,
2787 "%qD source argument is the same as destination",
2788 func);
2791 replace_call_with_value (gsi, dest);
2792 return true;
2795 if (! tree_fits_uhwi_p (size))
2796 return false;
2798 tree maxlen = get_maxval_strlen (src, SRK_STRLENMAX);
2799 if (! integer_all_onesp (size))
2801 len = c_strlen (src, 1);
2802 if (! len || ! tree_fits_uhwi_p (len))
2804 /* If LEN is not constant, try MAXLEN too.
2805 For MAXLEN only allow optimizing into non-_ocs function
2806 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
2807 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
2809 if (fcode == BUILT_IN_STPCPY_CHK)
2811 if (! ignore)
2812 return false;
2814 /* If return value of __stpcpy_chk is ignored,
2815 optimize into __strcpy_chk. */
2816 fn = builtin_decl_explicit (BUILT_IN_STRCPY_CHK);
2817 if (!fn)
2818 return false;
2820 gimple *repl = gimple_build_call (fn, 3, dest, src, size);
2821 replace_call_with_call_and_fold (gsi, repl);
2822 return true;
2825 if (! len || TREE_SIDE_EFFECTS (len))
2826 return false;
2828 /* If c_strlen returned something, but not a constant,
2829 transform __strcpy_chk into __memcpy_chk. */
2830 fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
2831 if (!fn)
2832 return false;
2834 gimple_seq stmts = NULL;
2835 len = force_gimple_operand (len, &stmts, true, NULL_TREE);
2836 len = gimple_convert (&stmts, loc, size_type_node, len);
2837 len = gimple_build (&stmts, loc, PLUS_EXPR, size_type_node, len,
2838 build_int_cst (size_type_node, 1));
2839 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
2840 gimple *repl = gimple_build_call (fn, 4, dest, src, len, size);
2841 replace_call_with_call_and_fold (gsi, repl);
2842 return true;
2845 else
2846 maxlen = len;
2848 if (! tree_int_cst_lt (maxlen, size))
2849 return false;
2852 /* If __builtin_st{r,p}cpy_chk is used, assume st{r,p}cpy is available. */
2853 fn = builtin_decl_explicit (fcode == BUILT_IN_STPCPY_CHK
2854 ? BUILT_IN_STPCPY : BUILT_IN_STRCPY);
2855 if (!fn)
2856 return false;
2858 gimple *repl = gimple_build_call (fn, 2, dest, src);
2859 replace_call_with_call_and_fold (gsi, repl);
2860 return true;
2863 /* Fold a call to the __st{r,p}ncpy_chk builtin. DEST, SRC, LEN, and SIZE
2864 are the arguments to the call. If MAXLEN is not NULL, it is maximum
2865 length passed as third argument. IGNORE is true if return value can be
2866 ignored. FCODE is the BUILT_IN_* code of the builtin. */
2868 static bool
2869 gimple_fold_builtin_stxncpy_chk (gimple_stmt_iterator *gsi,
2870 tree dest, tree src,
2871 tree len, tree size,
2872 enum built_in_function fcode)
2874 gimple *stmt = gsi_stmt (*gsi);
2875 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
2876 tree fn;
2878 if (fcode == BUILT_IN_STPNCPY_CHK && ignore)
2880 /* If return value of __stpncpy_chk is ignored,
2881 optimize into __strncpy_chk. */
2882 fn = builtin_decl_explicit (BUILT_IN_STRNCPY_CHK);
2883 if (fn)
2885 gimple *repl = gimple_build_call (fn, 4, dest, src, len, size);
2886 replace_call_with_call_and_fold (gsi, repl);
2887 return true;
2891 if (! tree_fits_uhwi_p (size))
2892 return false;
2894 tree maxlen = get_maxval_strlen (len, SRK_INT_VALUE);
2895 if (! integer_all_onesp (size))
2897 if (! tree_fits_uhwi_p (len))
2899 /* If LEN is not constant, try MAXLEN too.
2900 For MAXLEN only allow optimizing into non-_ocs function
2901 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
2902 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
2903 return false;
2905 else
2906 maxlen = len;
2908 if (tree_int_cst_lt (size, maxlen))
2909 return false;
2912 /* If __builtin_st{r,p}ncpy_chk is used, assume st{r,p}ncpy is available. */
2913 fn = builtin_decl_explicit (fcode == BUILT_IN_STPNCPY_CHK
2914 ? BUILT_IN_STPNCPY : BUILT_IN_STRNCPY);
2915 if (!fn)
2916 return false;
2918 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
2919 replace_call_with_call_and_fold (gsi, repl);
2920 return true;
2923 /* Fold function call to builtin stpcpy with arguments DEST and SRC.
2924 Return NULL_TREE if no simplification can be made. */
2926 static bool
2927 gimple_fold_builtin_stpcpy (gimple_stmt_iterator *gsi)
2929 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2930 location_t loc = gimple_location (stmt);
2931 tree dest = gimple_call_arg (stmt, 0);
2932 tree src = gimple_call_arg (stmt, 1);
2933 tree fn, lenp1;
2935 /* If the result is unused, replace stpcpy with strcpy. */
2936 if (gimple_call_lhs (stmt) == NULL_TREE)
2938 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2939 if (!fn)
2940 return false;
2941 gimple_call_set_fndecl (stmt, fn);
2942 fold_stmt (gsi);
2943 return true;
2946 /* Set to non-null if ARG refers to an unterminated array. */
2947 c_strlen_data data = { };
2948 tree len = c_strlen (src, 1, &data, 1);
2949 if (!len
2950 || TREE_CODE (len) != INTEGER_CST)
2952 data.decl = unterminated_array (src);
2953 if (!data.decl)
2954 return false;
2957 if (data.decl)
2959 /* Avoid folding calls with unterminated arrays. */
2960 if (!gimple_no_warning_p (stmt))
2961 warn_string_no_nul (loc, "stpcpy", src, data.decl);
2962 gimple_set_no_warning (stmt, true);
2963 return false;
2966 if (optimize_function_for_size_p (cfun)
2967 /* If length is zero it's small enough. */
2968 && !integer_zerop (len))
2969 return false;
2971 /* If the source has a known length replace stpcpy with memcpy. */
2972 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
2973 if (!fn)
2974 return false;
2976 gimple_seq stmts = NULL;
2977 tree tem = gimple_convert (&stmts, loc, size_type_node, len);
2978 lenp1 = gimple_build (&stmts, loc, PLUS_EXPR, size_type_node,
2979 tem, build_int_cst (size_type_node, 1));
2980 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
2981 gcall *repl = gimple_build_call (fn, 3, dest, src, lenp1);
2982 gimple_set_vuse (repl, gimple_vuse (stmt));
2983 gimple_set_vdef (repl, gimple_vdef (stmt));
2984 if (gimple_vdef (repl)
2985 && TREE_CODE (gimple_vdef (repl)) == SSA_NAME)
2986 SSA_NAME_DEF_STMT (gimple_vdef (repl)) = repl;
2987 gsi_insert_before (gsi, repl, GSI_SAME_STMT);
2988 /* Replace the result with dest + len. */
2989 stmts = NULL;
2990 tem = gimple_convert (&stmts, loc, sizetype, len);
2991 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
2992 gassign *ret = gimple_build_assign (gimple_call_lhs (stmt),
2993 POINTER_PLUS_EXPR, dest, tem);
2994 gsi_replace (gsi, ret, false);
2995 /* Finally fold the memcpy call. */
2996 gimple_stmt_iterator gsi2 = *gsi;
2997 gsi_prev (&gsi2);
2998 fold_stmt (&gsi2);
2999 return true;
3002 /* Fold a call EXP to {,v}snprintf having NARGS passed as ARGS. Return
3003 NULL_TREE if a normal call should be emitted rather than expanding
3004 the function inline. FCODE is either BUILT_IN_SNPRINTF_CHK or
3005 BUILT_IN_VSNPRINTF_CHK. If MAXLEN is not NULL, it is maximum length
3006 passed as second argument. */
3008 static bool
3009 gimple_fold_builtin_snprintf_chk (gimple_stmt_iterator *gsi,
3010 enum built_in_function fcode)
3012 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3013 tree dest, size, len, fn, fmt, flag;
3014 const char *fmt_str;
3016 /* Verify the required arguments in the original call. */
3017 if (gimple_call_num_args (stmt) < 5)
3018 return false;
3020 dest = gimple_call_arg (stmt, 0);
3021 len = gimple_call_arg (stmt, 1);
3022 flag = gimple_call_arg (stmt, 2);
3023 size = gimple_call_arg (stmt, 3);
3024 fmt = gimple_call_arg (stmt, 4);
3026 if (! tree_fits_uhwi_p (size))
3027 return false;
3029 if (! integer_all_onesp (size))
3031 tree maxlen = get_maxval_strlen (len, SRK_INT_VALUE);
3032 if (! tree_fits_uhwi_p (len))
3034 /* If LEN is not constant, try MAXLEN too.
3035 For MAXLEN only allow optimizing into non-_ocs function
3036 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
3037 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
3038 return false;
3040 else
3041 maxlen = len;
3043 if (tree_int_cst_lt (size, maxlen))
3044 return false;
3047 if (!init_target_chars ())
3048 return false;
3050 /* Only convert __{,v}snprintf_chk to {,v}snprintf if flag is 0
3051 or if format doesn't contain % chars or is "%s". */
3052 if (! integer_zerop (flag))
3054 fmt_str = c_getstr (fmt);
3055 if (fmt_str == NULL)
3056 return false;
3057 if (strchr (fmt_str, target_percent) != NULL
3058 && strcmp (fmt_str, target_percent_s))
3059 return false;
3062 /* If __builtin_{,v}snprintf_chk is used, assume {,v}snprintf is
3063 available. */
3064 fn = builtin_decl_explicit (fcode == BUILT_IN_VSNPRINTF_CHK
3065 ? BUILT_IN_VSNPRINTF : BUILT_IN_SNPRINTF);
3066 if (!fn)
3067 return false;
3069 /* Replace the called function and the first 5 argument by 3 retaining
3070 trailing varargs. */
3071 gimple_call_set_fndecl (stmt, fn);
3072 gimple_call_set_fntype (stmt, TREE_TYPE (fn));
3073 gimple_call_set_arg (stmt, 0, dest);
3074 gimple_call_set_arg (stmt, 1, len);
3075 gimple_call_set_arg (stmt, 2, fmt);
3076 for (unsigned i = 3; i < gimple_call_num_args (stmt) - 2; ++i)
3077 gimple_call_set_arg (stmt, i, gimple_call_arg (stmt, i + 2));
3078 gimple_set_num_ops (stmt, gimple_num_ops (stmt) - 2);
3079 fold_stmt (gsi);
3080 return true;
3083 /* Fold a call EXP to __{,v}sprintf_chk having NARGS passed as ARGS.
3084 Return NULL_TREE if a normal call should be emitted rather than
3085 expanding the function inline. FCODE is either BUILT_IN_SPRINTF_CHK
3086 or BUILT_IN_VSPRINTF_CHK. */
3088 static bool
3089 gimple_fold_builtin_sprintf_chk (gimple_stmt_iterator *gsi,
3090 enum built_in_function fcode)
3092 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3093 tree dest, size, len, fn, fmt, flag;
3094 const char *fmt_str;
3095 unsigned nargs = gimple_call_num_args (stmt);
3097 /* Verify the required arguments in the original call. */
3098 if (nargs < 4)
3099 return false;
3100 dest = gimple_call_arg (stmt, 0);
3101 flag = gimple_call_arg (stmt, 1);
3102 size = gimple_call_arg (stmt, 2);
3103 fmt = gimple_call_arg (stmt, 3);
3105 if (! tree_fits_uhwi_p (size))
3106 return false;
3108 len = NULL_TREE;
3110 if (!init_target_chars ())
3111 return false;
3113 /* Check whether the format is a literal string constant. */
3114 fmt_str = c_getstr (fmt);
3115 if (fmt_str != NULL)
3117 /* If the format doesn't contain % args or %%, we know the size. */
3118 if (strchr (fmt_str, target_percent) == 0)
3120 if (fcode != BUILT_IN_SPRINTF_CHK || nargs == 4)
3121 len = build_int_cstu (size_type_node, strlen (fmt_str));
3123 /* If the format is "%s" and first ... argument is a string literal,
3124 we know the size too. */
3125 else if (fcode == BUILT_IN_SPRINTF_CHK
3126 && strcmp (fmt_str, target_percent_s) == 0)
3128 tree arg;
3130 if (nargs == 5)
3132 arg = gimple_call_arg (stmt, 4);
3133 if (POINTER_TYPE_P (TREE_TYPE (arg)))
3135 len = c_strlen (arg, 1);
3136 if (! len || ! tree_fits_uhwi_p (len))
3137 len = NULL_TREE;
3143 if (! integer_all_onesp (size))
3145 if (! len || ! tree_int_cst_lt (len, size))
3146 return false;
3149 /* Only convert __{,v}sprintf_chk to {,v}sprintf if flag is 0
3150 or if format doesn't contain % chars or is "%s". */
3151 if (! integer_zerop (flag))
3153 if (fmt_str == NULL)
3154 return false;
3155 if (strchr (fmt_str, target_percent) != NULL
3156 && strcmp (fmt_str, target_percent_s))
3157 return false;
3160 /* If __builtin_{,v}sprintf_chk is used, assume {,v}sprintf is available. */
3161 fn = builtin_decl_explicit (fcode == BUILT_IN_VSPRINTF_CHK
3162 ? BUILT_IN_VSPRINTF : BUILT_IN_SPRINTF);
3163 if (!fn)
3164 return false;
3166 /* Replace the called function and the first 4 argument by 2 retaining
3167 trailing varargs. */
3168 gimple_call_set_fndecl (stmt, fn);
3169 gimple_call_set_fntype (stmt, TREE_TYPE (fn));
3170 gimple_call_set_arg (stmt, 0, dest);
3171 gimple_call_set_arg (stmt, 1, fmt);
3172 for (unsigned i = 2; i < gimple_call_num_args (stmt) - 2; ++i)
3173 gimple_call_set_arg (stmt, i, gimple_call_arg (stmt, i + 2));
3174 gimple_set_num_ops (stmt, gimple_num_ops (stmt) - 2);
3175 fold_stmt (gsi);
3176 return true;
3179 /* Simplify a call to the sprintf builtin with arguments DEST, FMT, and ORIG.
3180 ORIG may be null if this is a 2-argument call. We don't attempt to
3181 simplify calls with more than 3 arguments.
3183 Return true if simplification was possible, otherwise false. */
3185 bool
3186 gimple_fold_builtin_sprintf (gimple_stmt_iterator *gsi)
3188 gimple *stmt = gsi_stmt (*gsi);
3189 tree dest = gimple_call_arg (stmt, 0);
3190 tree fmt = gimple_call_arg (stmt, 1);
3191 tree orig = NULL_TREE;
3192 const char *fmt_str = NULL;
3194 /* Verify the required arguments in the original call. We deal with two
3195 types of sprintf() calls: 'sprintf (str, fmt)' and
3196 'sprintf (dest, "%s", orig)'. */
3197 if (gimple_call_num_args (stmt) > 3)
3198 return false;
3200 if (gimple_call_num_args (stmt) == 3)
3201 orig = gimple_call_arg (stmt, 2);
3203 /* Check whether the format is a literal string constant. */
3204 fmt_str = c_getstr (fmt);
3205 if (fmt_str == NULL)
3206 return false;
3208 if (!init_target_chars ())
3209 return false;
3211 /* If the format doesn't contain % args or %%, use strcpy. */
3212 if (strchr (fmt_str, target_percent) == NULL)
3214 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
3216 if (!fn)
3217 return false;
3219 /* Don't optimize sprintf (buf, "abc", ptr++). */
3220 if (orig)
3221 return false;
3223 /* Convert sprintf (str, fmt) into strcpy (str, fmt) when
3224 'format' is known to contain no % formats. */
3225 gimple_seq stmts = NULL;
3226 gimple *repl = gimple_build_call (fn, 2, dest, fmt);
3228 /* Propagate the NO_WARNING bit to avoid issuing the same
3229 warning more than once. */
3230 if (gimple_no_warning_p (stmt))
3231 gimple_set_no_warning (repl, true);
3233 gimple_seq_add_stmt_without_update (&stmts, repl);
3234 if (gimple_call_lhs (stmt))
3236 repl = gimple_build_assign (gimple_call_lhs (stmt),
3237 build_int_cst (integer_type_node,
3238 strlen (fmt_str)));
3239 gimple_seq_add_stmt_without_update (&stmts, repl);
3240 gsi_replace_with_seq_vops (gsi, stmts);
3241 /* gsi now points at the assignment to the lhs, get a
3242 stmt iterator to the memcpy call.
3243 ??? We can't use gsi_for_stmt as that doesn't work when the
3244 CFG isn't built yet. */
3245 gimple_stmt_iterator gsi2 = *gsi;
3246 gsi_prev (&gsi2);
3247 fold_stmt (&gsi2);
3249 else
3251 gsi_replace_with_seq_vops (gsi, stmts);
3252 fold_stmt (gsi);
3254 return true;
3257 /* If the format is "%s", use strcpy if the result isn't used. */
3258 else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
3260 tree fn;
3261 fn = builtin_decl_implicit (BUILT_IN_STRCPY);
3263 if (!fn)
3264 return false;
3266 /* Don't crash on sprintf (str1, "%s"). */
3267 if (!orig)
3268 return false;
3270 tree orig_len = NULL_TREE;
3271 if (gimple_call_lhs (stmt))
3273 orig_len = get_maxval_strlen (orig, SRK_STRLEN);
3274 if (!orig_len)
3275 return false;
3278 /* Convert sprintf (str1, "%s", str2) into strcpy (str1, str2). */
3279 gimple_seq stmts = NULL;
3280 gimple *repl = gimple_build_call (fn, 2, dest, orig);
3282 /* Propagate the NO_WARNING bit to avoid issuing the same
3283 warning more than once. */
3284 if (gimple_no_warning_p (stmt))
3285 gimple_set_no_warning (repl, true);
3287 gimple_seq_add_stmt_without_update (&stmts, repl);
3288 if (gimple_call_lhs (stmt))
3290 if (!useless_type_conversion_p (integer_type_node,
3291 TREE_TYPE (orig_len)))
3292 orig_len = fold_convert (integer_type_node, orig_len);
3293 repl = gimple_build_assign (gimple_call_lhs (stmt), orig_len);
3294 gimple_seq_add_stmt_without_update (&stmts, repl);
3295 gsi_replace_with_seq_vops (gsi, stmts);
3296 /* gsi now points at the assignment to the lhs, get a
3297 stmt iterator to the memcpy call.
3298 ??? We can't use gsi_for_stmt as that doesn't work when the
3299 CFG isn't built yet. */
3300 gimple_stmt_iterator gsi2 = *gsi;
3301 gsi_prev (&gsi2);
3302 fold_stmt (&gsi2);
3304 else
3306 gsi_replace_with_seq_vops (gsi, stmts);
3307 fold_stmt (gsi);
3309 return true;
3311 return false;
3314 /* Simplify a call to the snprintf builtin with arguments DEST, DESTSIZE,
3315 FMT, and ORIG. ORIG may be null if this is a 3-argument call. We don't
3316 attempt to simplify calls with more than 4 arguments.
3318 Return true if simplification was possible, otherwise false. */
3320 bool
3321 gimple_fold_builtin_snprintf (gimple_stmt_iterator *gsi)
3323 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3324 tree dest = gimple_call_arg (stmt, 0);
3325 tree destsize = gimple_call_arg (stmt, 1);
3326 tree fmt = gimple_call_arg (stmt, 2);
3327 tree orig = NULL_TREE;
3328 const char *fmt_str = NULL;
3330 if (gimple_call_num_args (stmt) > 4)
3331 return false;
3333 if (gimple_call_num_args (stmt) == 4)
3334 orig = gimple_call_arg (stmt, 3);
3336 if (!tree_fits_uhwi_p (destsize))
3337 return false;
3338 unsigned HOST_WIDE_INT destlen = tree_to_uhwi (destsize);
3340 /* Check whether the format is a literal string constant. */
3341 fmt_str = c_getstr (fmt);
3342 if (fmt_str == NULL)
3343 return false;
3345 if (!init_target_chars ())
3346 return false;
3348 /* If the format doesn't contain % args or %%, use strcpy. */
3349 if (strchr (fmt_str, target_percent) == NULL)
3351 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
3352 if (!fn)
3353 return false;
3355 /* Don't optimize snprintf (buf, 4, "abc", ptr++). */
3356 if (orig)
3357 return false;
3359 /* We could expand this as
3360 memcpy (str, fmt, cst - 1); str[cst - 1] = '\0';
3361 or to
3362 memcpy (str, fmt_with_nul_at_cstm1, cst);
3363 but in the former case that might increase code size
3364 and in the latter case grow .rodata section too much.
3365 So punt for now. */
3366 size_t len = strlen (fmt_str);
3367 if (len >= destlen)
3368 return false;
3370 gimple_seq stmts = NULL;
3371 gimple *repl = gimple_build_call (fn, 2, dest, fmt);
3372 gimple_seq_add_stmt_without_update (&stmts, repl);
3373 if (gimple_call_lhs (stmt))
3375 repl = gimple_build_assign (gimple_call_lhs (stmt),
3376 build_int_cst (integer_type_node, len));
3377 gimple_seq_add_stmt_without_update (&stmts, repl);
3378 gsi_replace_with_seq_vops (gsi, stmts);
3379 /* gsi now points at the assignment to the lhs, get a
3380 stmt iterator to the memcpy call.
3381 ??? We can't use gsi_for_stmt as that doesn't work when the
3382 CFG isn't built yet. */
3383 gimple_stmt_iterator gsi2 = *gsi;
3384 gsi_prev (&gsi2);
3385 fold_stmt (&gsi2);
3387 else
3389 gsi_replace_with_seq_vops (gsi, stmts);
3390 fold_stmt (gsi);
3392 return true;
3395 /* If the format is "%s", use strcpy if the result isn't used. */
3396 else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
3398 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
3399 if (!fn)
3400 return false;
3402 /* Don't crash on snprintf (str1, cst, "%s"). */
3403 if (!orig)
3404 return false;
3406 tree orig_len = get_maxval_strlen (orig, SRK_STRLEN);
3407 if (!orig_len || TREE_CODE (orig_len) != INTEGER_CST)
3408 return false;
3410 /* We could expand this as
3411 memcpy (str1, str2, cst - 1); str1[cst - 1] = '\0';
3412 or to
3413 memcpy (str1, str2_with_nul_at_cstm1, cst);
3414 but in the former case that might increase code size
3415 and in the latter case grow .rodata section too much.
3416 So punt for now. */
3417 if (compare_tree_int (orig_len, destlen) >= 0)
3418 return false;
3420 /* Convert snprintf (str1, cst, "%s", str2) into
3421 strcpy (str1, str2) if strlen (str2) < cst. */
3422 gimple_seq stmts = NULL;
3423 gimple *repl = gimple_build_call (fn, 2, dest, orig);
3424 gimple_seq_add_stmt_without_update (&stmts, repl);
3425 if (gimple_call_lhs (stmt))
3427 if (!useless_type_conversion_p (integer_type_node,
3428 TREE_TYPE (orig_len)))
3429 orig_len = fold_convert (integer_type_node, orig_len);
3430 repl = gimple_build_assign (gimple_call_lhs (stmt), orig_len);
3431 gimple_seq_add_stmt_without_update (&stmts, repl);
3432 gsi_replace_with_seq_vops (gsi, stmts);
3433 /* gsi now points at the assignment to the lhs, get a
3434 stmt iterator to the memcpy call.
3435 ??? We can't use gsi_for_stmt as that doesn't work when the
3436 CFG isn't built yet. */
3437 gimple_stmt_iterator gsi2 = *gsi;
3438 gsi_prev (&gsi2);
3439 fold_stmt (&gsi2);
3441 else
3443 gsi_replace_with_seq_vops (gsi, stmts);
3444 fold_stmt (gsi);
3446 return true;
3448 return false;
3451 /* Fold a call to the {,v}fprintf{,_unlocked} and __{,v}printf_chk builtins.
3452 FP, FMT, and ARG are the arguments to the call. We don't fold calls with
3453 more than 3 arguments, and ARG may be null in the 2-argument case.
3455 Return NULL_TREE if no simplification was possible, otherwise return the
3456 simplified form of the call as a tree. FCODE is the BUILT_IN_*
3457 code of the function to be simplified. */
3459 static bool
3460 gimple_fold_builtin_fprintf (gimple_stmt_iterator *gsi,
3461 tree fp, tree fmt, tree arg,
3462 enum built_in_function fcode)
3464 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3465 tree fn_fputc, fn_fputs;
3466 const char *fmt_str = NULL;
3468 /* If the return value is used, don't do the transformation. */
3469 if (gimple_call_lhs (stmt) != NULL_TREE)
3470 return false;
3472 /* Check whether the format is a literal string constant. */
3473 fmt_str = c_getstr (fmt);
3474 if (fmt_str == NULL)
3475 return false;
3477 if (fcode == BUILT_IN_FPRINTF_UNLOCKED)
3479 /* If we're using an unlocked function, assume the other
3480 unlocked functions exist explicitly. */
3481 fn_fputc = builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED);
3482 fn_fputs = builtin_decl_explicit (BUILT_IN_FPUTS_UNLOCKED);
3484 else
3486 fn_fputc = builtin_decl_implicit (BUILT_IN_FPUTC);
3487 fn_fputs = builtin_decl_implicit (BUILT_IN_FPUTS);
3490 if (!init_target_chars ())
3491 return false;
3493 /* If the format doesn't contain % args or %%, use strcpy. */
3494 if (strchr (fmt_str, target_percent) == NULL)
3496 if (fcode != BUILT_IN_VFPRINTF && fcode != BUILT_IN_VFPRINTF_CHK
3497 && arg)
3498 return false;
3500 /* If the format specifier was "", fprintf does nothing. */
3501 if (fmt_str[0] == '\0')
3503 replace_call_with_value (gsi, NULL_TREE);
3504 return true;
3507 /* When "string" doesn't contain %, replace all cases of
3508 fprintf (fp, string) with fputs (string, fp). The fputs
3509 builtin will take care of special cases like length == 1. */
3510 if (fn_fputs)
3512 gcall *repl = gimple_build_call (fn_fputs, 2, fmt, fp);
3513 replace_call_with_call_and_fold (gsi, repl);
3514 return true;
3518 /* The other optimizations can be done only on the non-va_list variants. */
3519 else if (fcode == BUILT_IN_VFPRINTF || fcode == BUILT_IN_VFPRINTF_CHK)
3520 return false;
3522 /* If the format specifier was "%s", call __builtin_fputs (arg, fp). */
3523 else if (strcmp (fmt_str, target_percent_s) == 0)
3525 if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
3526 return false;
3527 if (fn_fputs)
3529 gcall *repl = gimple_build_call (fn_fputs, 2, arg, fp);
3530 replace_call_with_call_and_fold (gsi, repl);
3531 return true;
3535 /* If the format specifier was "%c", call __builtin_fputc (arg, fp). */
3536 else if (strcmp (fmt_str, target_percent_c) == 0)
3538 if (!arg
3539 || ! useless_type_conversion_p (integer_type_node, TREE_TYPE (arg)))
3540 return false;
3541 if (fn_fputc)
3543 gcall *repl = gimple_build_call (fn_fputc, 2, arg, fp);
3544 replace_call_with_call_and_fold (gsi, repl);
3545 return true;
3549 return false;
3552 /* Fold a call to the {,v}printf{,_unlocked} and __{,v}printf_chk builtins.
3553 FMT and ARG are the arguments to the call; we don't fold cases with
3554 more than 2 arguments, and ARG may be null if this is a 1-argument case.
3556 Return NULL_TREE if no simplification was possible, otherwise return the
3557 simplified form of the call as a tree. FCODE is the BUILT_IN_*
3558 code of the function to be simplified. */
3560 static bool
3561 gimple_fold_builtin_printf (gimple_stmt_iterator *gsi, tree fmt,
3562 tree arg, enum built_in_function fcode)
3564 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3565 tree fn_putchar, fn_puts, newarg;
3566 const char *fmt_str = NULL;
3568 /* If the return value is used, don't do the transformation. */
3569 if (gimple_call_lhs (stmt) != NULL_TREE)
3570 return false;
3572 /* Check whether the format is a literal string constant. */
3573 fmt_str = c_getstr (fmt);
3574 if (fmt_str == NULL)
3575 return false;
3577 if (fcode == BUILT_IN_PRINTF_UNLOCKED)
3579 /* If we're using an unlocked function, assume the other
3580 unlocked functions exist explicitly. */
3581 fn_putchar = builtin_decl_explicit (BUILT_IN_PUTCHAR_UNLOCKED);
3582 fn_puts = builtin_decl_explicit (BUILT_IN_PUTS_UNLOCKED);
3584 else
3586 fn_putchar = builtin_decl_implicit (BUILT_IN_PUTCHAR);
3587 fn_puts = builtin_decl_implicit (BUILT_IN_PUTS);
3590 if (!init_target_chars ())
3591 return false;
3593 if (strcmp (fmt_str, target_percent_s) == 0
3594 || strchr (fmt_str, target_percent) == NULL)
3596 const char *str;
3598 if (strcmp (fmt_str, target_percent_s) == 0)
3600 if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
3601 return false;
3603 if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
3604 return false;
3606 str = c_getstr (arg);
3607 if (str == NULL)
3608 return false;
3610 else
3612 /* The format specifier doesn't contain any '%' characters. */
3613 if (fcode != BUILT_IN_VPRINTF && fcode != BUILT_IN_VPRINTF_CHK
3614 && arg)
3615 return false;
3616 str = fmt_str;
3619 /* If the string was "", printf does nothing. */
3620 if (str[0] == '\0')
3622 replace_call_with_value (gsi, NULL_TREE);
3623 return true;
3626 /* If the string has length of 1, call putchar. */
3627 if (str[1] == '\0')
3629 /* Given printf("c"), (where c is any one character,)
3630 convert "c"[0] to an int and pass that to the replacement
3631 function. */
3632 newarg = build_int_cst (integer_type_node, str[0]);
3633 if (fn_putchar)
3635 gcall *repl = gimple_build_call (fn_putchar, 1, newarg);
3636 replace_call_with_call_and_fold (gsi, repl);
3637 return true;
3640 else
3642 /* If the string was "string\n", call puts("string"). */
3643 size_t len = strlen (str);
3644 if ((unsigned char)str[len - 1] == target_newline
3645 && (size_t) (int) len == len
3646 && (int) len > 0)
3648 char *newstr;
3650 /* Create a NUL-terminated string that's one char shorter
3651 than the original, stripping off the trailing '\n'. */
3652 newstr = xstrdup (str);
3653 newstr[len - 1] = '\0';
3654 newarg = build_string_literal (len, newstr);
3655 free (newstr);
3656 if (fn_puts)
3658 gcall *repl = gimple_build_call (fn_puts, 1, newarg);
3659 replace_call_with_call_and_fold (gsi, repl);
3660 return true;
3663 else
3664 /* We'd like to arrange to call fputs(string,stdout) here,
3665 but we need stdout and don't have a way to get it yet. */
3666 return false;
3670 /* The other optimizations can be done only on the non-va_list variants. */
3671 else if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
3672 return false;
3674 /* If the format specifier was "%s\n", call __builtin_puts(arg). */
3675 else if (strcmp (fmt_str, target_percent_s_newline) == 0)
3677 if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
3678 return false;
3679 if (fn_puts)
3681 gcall *repl = gimple_build_call (fn_puts, 1, arg);
3682 replace_call_with_call_and_fold (gsi, repl);
3683 return true;
3687 /* If the format specifier was "%c", call __builtin_putchar(arg). */
3688 else if (strcmp (fmt_str, target_percent_c) == 0)
3690 if (!arg || ! useless_type_conversion_p (integer_type_node,
3691 TREE_TYPE (arg)))
3692 return false;
3693 if (fn_putchar)
3695 gcall *repl = gimple_build_call (fn_putchar, 1, arg);
3696 replace_call_with_call_and_fold (gsi, repl);
3697 return true;
3701 return false;
3706 /* Fold a call to __builtin_strlen with known length LEN. */
3708 static bool
3709 gimple_fold_builtin_strlen (gimple_stmt_iterator *gsi)
3711 gimple *stmt = gsi_stmt (*gsi);
3712 tree arg = gimple_call_arg (stmt, 0);
3714 wide_int minlen;
3715 wide_int maxlen;
3717 c_strlen_data lendata = { };
3718 if (get_range_strlen (arg, &lendata, /* eltsize = */ 1)
3719 && !lendata.decl
3720 && lendata.minlen && TREE_CODE (lendata.minlen) == INTEGER_CST
3721 && lendata.maxlen && TREE_CODE (lendata.maxlen) == INTEGER_CST)
3723 /* The range of lengths refers to either a single constant
3724 string or to the longest and shortest constant string
3725 referenced by the argument of the strlen() call, or to
3726 the strings that can possibly be stored in the arrays
3727 the argument refers to. */
3728 minlen = wi::to_wide (lendata.minlen);
3729 maxlen = wi::to_wide (lendata.maxlen);
3731 else
3733 unsigned prec = TYPE_PRECISION (sizetype);
3735 minlen = wi::shwi (0, prec);
3736 maxlen = wi::to_wide (max_object_size (), prec) - 2;
3739 if (minlen == maxlen)
3741 /* Fold the strlen call to a constant. */
3742 tree type = TREE_TYPE (lendata.minlen);
3743 tree len = force_gimple_operand_gsi (gsi,
3744 wide_int_to_tree (type, minlen),
3745 true, NULL, true, GSI_SAME_STMT);
3746 replace_call_with_value (gsi, len);
3747 return true;
3750 /* Set the strlen() range to [0, MAXLEN]. */
3751 if (tree lhs = gimple_call_lhs (stmt))
3752 set_strlen_range (lhs, maxlen);
3754 return false;
3757 /* Fold a call to __builtin_acc_on_device. */
3759 static bool
3760 gimple_fold_builtin_acc_on_device (gimple_stmt_iterator *gsi, tree arg0)
3762 /* Defer folding until we know which compiler we're in. */
3763 if (symtab->state != EXPANSION)
3764 return false;
3766 unsigned val_host = GOMP_DEVICE_HOST;
3767 unsigned val_dev = GOMP_DEVICE_NONE;
3769 #ifdef ACCEL_COMPILER
3770 val_host = GOMP_DEVICE_NOT_HOST;
3771 val_dev = ACCEL_COMPILER_acc_device;
3772 #endif
3774 location_t loc = gimple_location (gsi_stmt (*gsi));
3776 tree host_eq = make_ssa_name (boolean_type_node);
3777 gimple *host_ass = gimple_build_assign
3778 (host_eq, EQ_EXPR, arg0, build_int_cst (TREE_TYPE (arg0), val_host));
3779 gimple_set_location (host_ass, loc);
3780 gsi_insert_before (gsi, host_ass, GSI_SAME_STMT);
3782 tree dev_eq = make_ssa_name (boolean_type_node);
3783 gimple *dev_ass = gimple_build_assign
3784 (dev_eq, EQ_EXPR, arg0, build_int_cst (TREE_TYPE (arg0), val_dev));
3785 gimple_set_location (dev_ass, loc);
3786 gsi_insert_before (gsi, dev_ass, GSI_SAME_STMT);
3788 tree result = make_ssa_name (boolean_type_node);
3789 gimple *result_ass = gimple_build_assign
3790 (result, BIT_IOR_EXPR, host_eq, dev_eq);
3791 gimple_set_location (result_ass, loc);
3792 gsi_insert_before (gsi, result_ass, GSI_SAME_STMT);
3794 replace_call_with_value (gsi, result);
3796 return true;
3799 /* Fold realloc (0, n) -> malloc (n). */
3801 static bool
3802 gimple_fold_builtin_realloc (gimple_stmt_iterator *gsi)
3804 gimple *stmt = gsi_stmt (*gsi);
3805 tree arg = gimple_call_arg (stmt, 0);
3806 tree size = gimple_call_arg (stmt, 1);
3808 if (operand_equal_p (arg, null_pointer_node, 0))
3810 tree fn_malloc = builtin_decl_implicit (BUILT_IN_MALLOC);
3811 if (fn_malloc)
3813 gcall *repl = gimple_build_call (fn_malloc, 1, size);
3814 replace_call_with_call_and_fold (gsi, repl);
3815 return true;
3818 return false;
3821 /* Fold the non-target builtin at *GSI and return whether any simplification
3822 was made. */
3824 static bool
3825 gimple_fold_builtin (gimple_stmt_iterator *gsi)
3827 gcall *stmt = as_a <gcall *>(gsi_stmt (*gsi));
3828 tree callee = gimple_call_fndecl (stmt);
3830 /* Give up for always_inline inline builtins until they are
3831 inlined. */
3832 if (avoid_folding_inline_builtin (callee))
3833 return false;
3835 unsigned n = gimple_call_num_args (stmt);
3836 enum built_in_function fcode = DECL_FUNCTION_CODE (callee);
3837 switch (fcode)
3839 case BUILT_IN_BCMP:
3840 return gimple_fold_builtin_bcmp (gsi);
3841 case BUILT_IN_BCOPY:
3842 return gimple_fold_builtin_bcopy (gsi);
3843 case BUILT_IN_BZERO:
3844 return gimple_fold_builtin_bzero (gsi);
3846 case BUILT_IN_MEMSET:
3847 return gimple_fold_builtin_memset (gsi,
3848 gimple_call_arg (stmt, 1),
3849 gimple_call_arg (stmt, 2));
3850 case BUILT_IN_MEMCPY:
3851 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
3852 gimple_call_arg (stmt, 1), 0);
3853 case BUILT_IN_MEMPCPY:
3854 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
3855 gimple_call_arg (stmt, 1), 1);
3856 case BUILT_IN_MEMMOVE:
3857 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
3858 gimple_call_arg (stmt, 1), 3);
3859 case BUILT_IN_SPRINTF_CHK:
3860 case BUILT_IN_VSPRINTF_CHK:
3861 return gimple_fold_builtin_sprintf_chk (gsi, fcode);
3862 case BUILT_IN_STRCAT_CHK:
3863 return gimple_fold_builtin_strcat_chk (gsi);
3864 case BUILT_IN_STRNCAT_CHK:
3865 return gimple_fold_builtin_strncat_chk (gsi);
3866 case BUILT_IN_STRLEN:
3867 return gimple_fold_builtin_strlen (gsi);
3868 case BUILT_IN_STRCPY:
3869 return gimple_fold_builtin_strcpy (gsi,
3870 gimple_call_arg (stmt, 0),
3871 gimple_call_arg (stmt, 1));
3872 case BUILT_IN_STRNCPY:
3873 return gimple_fold_builtin_strncpy (gsi,
3874 gimple_call_arg (stmt, 0),
3875 gimple_call_arg (stmt, 1),
3876 gimple_call_arg (stmt, 2));
3877 case BUILT_IN_STRCAT:
3878 return gimple_fold_builtin_strcat (gsi, gimple_call_arg (stmt, 0),
3879 gimple_call_arg (stmt, 1));
3880 case BUILT_IN_STRNCAT:
3881 return gimple_fold_builtin_strncat (gsi);
3882 case BUILT_IN_INDEX:
3883 case BUILT_IN_STRCHR:
3884 return gimple_fold_builtin_strchr (gsi, false);
3885 case BUILT_IN_RINDEX:
3886 case BUILT_IN_STRRCHR:
3887 return gimple_fold_builtin_strchr (gsi, true);
3888 case BUILT_IN_STRSTR:
3889 return gimple_fold_builtin_strstr (gsi);
3890 case BUILT_IN_STRCMP:
3891 case BUILT_IN_STRCMP_EQ:
3892 case BUILT_IN_STRCASECMP:
3893 case BUILT_IN_STRNCMP:
3894 case BUILT_IN_STRNCMP_EQ:
3895 case BUILT_IN_STRNCASECMP:
3896 return gimple_fold_builtin_string_compare (gsi);
3897 case BUILT_IN_MEMCHR:
3898 return gimple_fold_builtin_memchr (gsi);
3899 case BUILT_IN_FPUTS:
3900 return gimple_fold_builtin_fputs (gsi, gimple_call_arg (stmt, 0),
3901 gimple_call_arg (stmt, 1), false);
3902 case BUILT_IN_FPUTS_UNLOCKED:
3903 return gimple_fold_builtin_fputs (gsi, gimple_call_arg (stmt, 0),
3904 gimple_call_arg (stmt, 1), true);
3905 case BUILT_IN_MEMCPY_CHK:
3906 case BUILT_IN_MEMPCPY_CHK:
3907 case BUILT_IN_MEMMOVE_CHK:
3908 case BUILT_IN_MEMSET_CHK:
3909 return gimple_fold_builtin_memory_chk (gsi,
3910 gimple_call_arg (stmt, 0),
3911 gimple_call_arg (stmt, 1),
3912 gimple_call_arg (stmt, 2),
3913 gimple_call_arg (stmt, 3),
3914 fcode);
3915 case BUILT_IN_STPCPY:
3916 return gimple_fold_builtin_stpcpy (gsi);
3917 case BUILT_IN_STRCPY_CHK:
3918 case BUILT_IN_STPCPY_CHK:
3919 return gimple_fold_builtin_stxcpy_chk (gsi,
3920 gimple_call_arg (stmt, 0),
3921 gimple_call_arg (stmt, 1),
3922 gimple_call_arg (stmt, 2),
3923 fcode);
3924 case BUILT_IN_STRNCPY_CHK:
3925 case BUILT_IN_STPNCPY_CHK:
3926 return gimple_fold_builtin_stxncpy_chk (gsi,
3927 gimple_call_arg (stmt, 0),
3928 gimple_call_arg (stmt, 1),
3929 gimple_call_arg (stmt, 2),
3930 gimple_call_arg (stmt, 3),
3931 fcode);
3932 case BUILT_IN_SNPRINTF_CHK:
3933 case BUILT_IN_VSNPRINTF_CHK:
3934 return gimple_fold_builtin_snprintf_chk (gsi, fcode);
3936 case BUILT_IN_FPRINTF:
3937 case BUILT_IN_FPRINTF_UNLOCKED:
3938 case BUILT_IN_VFPRINTF:
3939 if (n == 2 || n == 3)
3940 return gimple_fold_builtin_fprintf (gsi,
3941 gimple_call_arg (stmt, 0),
3942 gimple_call_arg (stmt, 1),
3943 n == 3
3944 ? gimple_call_arg (stmt, 2)
3945 : NULL_TREE,
3946 fcode);
3947 break;
3948 case BUILT_IN_FPRINTF_CHK:
3949 case BUILT_IN_VFPRINTF_CHK:
3950 if (n == 3 || n == 4)
3951 return gimple_fold_builtin_fprintf (gsi,
3952 gimple_call_arg (stmt, 0),
3953 gimple_call_arg (stmt, 2),
3954 n == 4
3955 ? gimple_call_arg (stmt, 3)
3956 : NULL_TREE,
3957 fcode);
3958 break;
3959 case BUILT_IN_PRINTF:
3960 case BUILT_IN_PRINTF_UNLOCKED:
3961 case BUILT_IN_VPRINTF:
3962 if (n == 1 || n == 2)
3963 return gimple_fold_builtin_printf (gsi, gimple_call_arg (stmt, 0),
3964 n == 2
3965 ? gimple_call_arg (stmt, 1)
3966 : NULL_TREE, fcode);
3967 break;
3968 case BUILT_IN_PRINTF_CHK:
3969 case BUILT_IN_VPRINTF_CHK:
3970 if (n == 2 || n == 3)
3971 return gimple_fold_builtin_printf (gsi, gimple_call_arg (stmt, 1),
3972 n == 3
3973 ? gimple_call_arg (stmt, 2)
3974 : NULL_TREE, fcode);
3975 break;
3976 case BUILT_IN_ACC_ON_DEVICE:
3977 return gimple_fold_builtin_acc_on_device (gsi,
3978 gimple_call_arg (stmt, 0));
3979 case BUILT_IN_REALLOC:
3980 return gimple_fold_builtin_realloc (gsi);
3982 default:;
3985 /* Try the generic builtin folder. */
3986 bool ignore = (gimple_call_lhs (stmt) == NULL);
3987 tree result = fold_call_stmt (stmt, ignore);
3988 if (result)
3990 if (ignore)
3991 STRIP_NOPS (result);
3992 else
3993 result = fold_convert (gimple_call_return_type (stmt), result);
3994 if (!update_call_from_tree (gsi, result))
3995 gimplify_and_update_call_from_tree (gsi, result);
3996 return true;
3999 return false;
4002 /* Transform IFN_GOACC_DIM_SIZE and IFN_GOACC_DIM_POS internal
4003 function calls to constants, where possible. */
4005 static tree
4006 fold_internal_goacc_dim (const gimple *call)
4008 int axis = oacc_get_ifn_dim_arg (call);
4009 int size = oacc_get_fn_dim_size (current_function_decl, axis);
4010 tree result = NULL_TREE;
4011 tree type = TREE_TYPE (gimple_call_lhs (call));
4013 switch (gimple_call_internal_fn (call))
4015 case IFN_GOACC_DIM_POS:
4016 /* If the size is 1, we know the answer. */
4017 if (size == 1)
4018 result = build_int_cst (type, 0);
4019 break;
4020 case IFN_GOACC_DIM_SIZE:
4021 /* If the size is not dynamic, we know the answer. */
4022 if (size)
4023 result = build_int_cst (type, size);
4024 break;
4025 default:
4026 break;
4029 return result;
4032 /* Return true if stmt is __atomic_compare_exchange_N call which is suitable
4033 for conversion into ATOMIC_COMPARE_EXCHANGE if the second argument is
4034 &var where var is only addressable because of such calls. */
4036 bool
4037 optimize_atomic_compare_exchange_p (gimple *stmt)
4039 if (gimple_call_num_args (stmt) != 6
4040 || !flag_inline_atomics
4041 || !optimize
4042 || sanitize_flags_p (SANITIZE_THREAD | SANITIZE_ADDRESS)
4043 || !gimple_call_builtin_p (stmt, BUILT_IN_NORMAL)
4044 || !gimple_vdef (stmt)
4045 || !gimple_vuse (stmt))
4046 return false;
4048 tree fndecl = gimple_call_fndecl (stmt);
4049 switch (DECL_FUNCTION_CODE (fndecl))
4051 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1:
4052 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2:
4053 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4:
4054 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8:
4055 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16:
4056 break;
4057 default:
4058 return false;
4061 tree expected = gimple_call_arg (stmt, 1);
4062 if (TREE_CODE (expected) != ADDR_EXPR
4063 || !SSA_VAR_P (TREE_OPERAND (expected, 0)))
4064 return false;
4066 tree etype = TREE_TYPE (TREE_OPERAND (expected, 0));
4067 if (!is_gimple_reg_type (etype)
4068 || !auto_var_in_fn_p (TREE_OPERAND (expected, 0), current_function_decl)
4069 || TREE_THIS_VOLATILE (etype)
4070 || VECTOR_TYPE_P (etype)
4071 || TREE_CODE (etype) == COMPLEX_TYPE
4072 /* Don't optimize floating point expected vars, VIEW_CONVERT_EXPRs
4073 might not preserve all the bits. See PR71716. */
4074 || SCALAR_FLOAT_TYPE_P (etype)
4075 || maybe_ne (TYPE_PRECISION (etype),
4076 GET_MODE_BITSIZE (TYPE_MODE (etype))))
4077 return false;
4079 tree weak = gimple_call_arg (stmt, 3);
4080 if (!integer_zerop (weak) && !integer_onep (weak))
4081 return false;
4083 tree parmt = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
4084 tree itype = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (parmt)));
4085 machine_mode mode = TYPE_MODE (itype);
4087 if (direct_optab_handler (atomic_compare_and_swap_optab, mode)
4088 == CODE_FOR_nothing
4089 && optab_handler (sync_compare_and_swap_optab, mode) == CODE_FOR_nothing)
4090 return false;
4092 if (maybe_ne (int_size_in_bytes (etype), GET_MODE_SIZE (mode)))
4093 return false;
4095 return true;
4098 /* Fold
4099 r = __atomic_compare_exchange_N (p, &e, d, w, s, f);
4100 into
4101 _Complex uintN_t t = ATOMIC_COMPARE_EXCHANGE (p, e, d, w * 256 + N, s, f);
4102 i = IMAGPART_EXPR <t>;
4103 r = (_Bool) i;
4104 e = REALPART_EXPR <t>; */
4106 void
4107 fold_builtin_atomic_compare_exchange (gimple_stmt_iterator *gsi)
4109 gimple *stmt = gsi_stmt (*gsi);
4110 tree fndecl = gimple_call_fndecl (stmt);
4111 tree parmt = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
4112 tree itype = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (parmt)));
4113 tree ctype = build_complex_type (itype);
4114 tree expected = TREE_OPERAND (gimple_call_arg (stmt, 1), 0);
4115 bool throws = false;
4116 edge e = NULL;
4117 gimple *g = gimple_build_assign (make_ssa_name (TREE_TYPE (expected)),
4118 expected);
4119 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4120 gimple_stmt_iterator gsiret = gsi_for_stmt (g);
4121 if (!useless_type_conversion_p (itype, TREE_TYPE (expected)))
4123 g = gimple_build_assign (make_ssa_name (itype), VIEW_CONVERT_EXPR,
4124 build1 (VIEW_CONVERT_EXPR, itype,
4125 gimple_assign_lhs (g)));
4126 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4128 int flag = (integer_onep (gimple_call_arg (stmt, 3)) ? 256 : 0)
4129 + int_size_in_bytes (itype);
4130 g = gimple_build_call_internal (IFN_ATOMIC_COMPARE_EXCHANGE, 6,
4131 gimple_call_arg (stmt, 0),
4132 gimple_assign_lhs (g),
4133 gimple_call_arg (stmt, 2),
4134 build_int_cst (integer_type_node, flag),
4135 gimple_call_arg (stmt, 4),
4136 gimple_call_arg (stmt, 5));
4137 tree lhs = make_ssa_name (ctype);
4138 gimple_call_set_lhs (g, lhs);
4139 gimple_set_vdef (g, gimple_vdef (stmt));
4140 gimple_set_vuse (g, gimple_vuse (stmt));
4141 SSA_NAME_DEF_STMT (gimple_vdef (g)) = g;
4142 tree oldlhs = gimple_call_lhs (stmt);
4143 if (stmt_can_throw_internal (cfun, stmt))
4145 throws = true;
4146 e = find_fallthru_edge (gsi_bb (*gsi)->succs);
4148 gimple_call_set_nothrow (as_a <gcall *> (g),
4149 gimple_call_nothrow_p (as_a <gcall *> (stmt)));
4150 gimple_call_set_lhs (stmt, NULL_TREE);
4151 gsi_replace (gsi, g, true);
4152 if (oldlhs)
4154 g = gimple_build_assign (make_ssa_name (itype), IMAGPART_EXPR,
4155 build1 (IMAGPART_EXPR, itype, lhs));
4156 if (throws)
4158 gsi_insert_on_edge_immediate (e, g);
4159 *gsi = gsi_for_stmt (g);
4161 else
4162 gsi_insert_after (gsi, g, GSI_NEW_STMT);
4163 g = gimple_build_assign (oldlhs, NOP_EXPR, gimple_assign_lhs (g));
4164 gsi_insert_after (gsi, g, GSI_NEW_STMT);
4166 g = gimple_build_assign (make_ssa_name (itype), REALPART_EXPR,
4167 build1 (REALPART_EXPR, itype, lhs));
4168 if (throws && oldlhs == NULL_TREE)
4170 gsi_insert_on_edge_immediate (e, g);
4171 *gsi = gsi_for_stmt (g);
4173 else
4174 gsi_insert_after (gsi, g, GSI_NEW_STMT);
4175 if (!useless_type_conversion_p (TREE_TYPE (expected), itype))
4177 g = gimple_build_assign (make_ssa_name (TREE_TYPE (expected)),
4178 VIEW_CONVERT_EXPR,
4179 build1 (VIEW_CONVERT_EXPR, TREE_TYPE (expected),
4180 gimple_assign_lhs (g)));
4181 gsi_insert_after (gsi, g, GSI_NEW_STMT);
4183 g = gimple_build_assign (expected, SSA_NAME, gimple_assign_lhs (g));
4184 gsi_insert_after (gsi, g, GSI_NEW_STMT);
4185 *gsi = gsiret;
4188 /* Return true if ARG0 CODE ARG1 in infinite signed precision operation
4189 doesn't fit into TYPE. The test for overflow should be regardless of
4190 -fwrapv, and even for unsigned types. */
4192 bool
4193 arith_overflowed_p (enum tree_code code, const_tree type,
4194 const_tree arg0, const_tree arg1)
4196 widest2_int warg0 = widest2_int_cst (arg0);
4197 widest2_int warg1 = widest2_int_cst (arg1);
4198 widest2_int wres;
4199 switch (code)
4201 case PLUS_EXPR: wres = wi::add (warg0, warg1); break;
4202 case MINUS_EXPR: wres = wi::sub (warg0, warg1); break;
4203 case MULT_EXPR: wres = wi::mul (warg0, warg1); break;
4204 default: gcc_unreachable ();
4206 signop sign = TYPE_SIGN (type);
4207 if (sign == UNSIGNED && wi::neg_p (wres))
4208 return true;
4209 return wi::min_precision (wres, sign) > TYPE_PRECISION (type);
4212 /* Attempt to fold a call statement referenced by the statement iterator GSI.
4213 The statement may be replaced by another statement, e.g., if the call
4214 simplifies to a constant value. Return true if any changes were made.
4215 It is assumed that the operands have been previously folded. */
4217 static bool
4218 gimple_fold_call (gimple_stmt_iterator *gsi, bool inplace)
4220 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
4221 tree callee;
4222 bool changed = false;
4223 unsigned i;
4225 /* Fold *& in call arguments. */
4226 for (i = 0; i < gimple_call_num_args (stmt); ++i)
4227 if (REFERENCE_CLASS_P (gimple_call_arg (stmt, i)))
4229 tree tmp = maybe_fold_reference (gimple_call_arg (stmt, i), false);
4230 if (tmp)
4232 gimple_call_set_arg (stmt, i, tmp);
4233 changed = true;
4237 /* Check for virtual calls that became direct calls. */
4238 callee = gimple_call_fn (stmt);
4239 if (callee && TREE_CODE (callee) == OBJ_TYPE_REF)
4241 if (gimple_call_addr_fndecl (OBJ_TYPE_REF_EXPR (callee)) != NULL_TREE)
4243 if (dump_file && virtual_method_call_p (callee)
4244 && !possible_polymorphic_call_target_p
4245 (callee, stmt, cgraph_node::get (gimple_call_addr_fndecl
4246 (OBJ_TYPE_REF_EXPR (callee)))))
4248 fprintf (dump_file,
4249 "Type inheritance inconsistent devirtualization of ");
4250 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
4251 fprintf (dump_file, " to ");
4252 print_generic_expr (dump_file, callee, TDF_SLIM);
4253 fprintf (dump_file, "\n");
4256 gimple_call_set_fn (stmt, OBJ_TYPE_REF_EXPR (callee));
4257 changed = true;
4259 else if (flag_devirtualize && !inplace && virtual_method_call_p (callee))
4261 bool final;
4262 vec <cgraph_node *>targets
4263 = possible_polymorphic_call_targets (callee, stmt, &final);
4264 if (final && targets.length () <= 1 && dbg_cnt (devirt))
4266 tree lhs = gimple_call_lhs (stmt);
4267 if (dump_enabled_p ())
4269 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, stmt,
4270 "folding virtual function call to %s\n",
4271 targets.length () == 1
4272 ? targets[0]->name ()
4273 : "__builtin_unreachable");
4275 if (targets.length () == 1)
4277 tree fndecl = targets[0]->decl;
4278 gimple_call_set_fndecl (stmt, fndecl);
4279 changed = true;
4280 /* If changing the call to __cxa_pure_virtual
4281 or similar noreturn function, adjust gimple_call_fntype
4282 too. */
4283 if (gimple_call_noreturn_p (stmt)
4284 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (fndecl)))
4285 && TYPE_ARG_TYPES (TREE_TYPE (fndecl))
4286 && (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (fndecl)))
4287 == void_type_node))
4288 gimple_call_set_fntype (stmt, TREE_TYPE (fndecl));
4289 /* If the call becomes noreturn, remove the lhs. */
4290 if (lhs
4291 && gimple_call_noreturn_p (stmt)
4292 && (VOID_TYPE_P (TREE_TYPE (gimple_call_fntype (stmt)))
4293 || should_remove_lhs_p (lhs)))
4295 if (TREE_CODE (lhs) == SSA_NAME)
4297 tree var = create_tmp_var (TREE_TYPE (lhs));
4298 tree def = get_or_create_ssa_default_def (cfun, var);
4299 gimple *new_stmt = gimple_build_assign (lhs, def);
4300 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
4302 gimple_call_set_lhs (stmt, NULL_TREE);
4304 maybe_remove_unused_call_args (cfun, stmt);
4306 else
4308 tree fndecl = builtin_decl_implicit (BUILT_IN_UNREACHABLE);
4309 gimple *new_stmt = gimple_build_call (fndecl, 0);
4310 gimple_set_location (new_stmt, gimple_location (stmt));
4311 /* If the call had a SSA name as lhs morph that into
4312 an uninitialized value. */
4313 if (lhs && TREE_CODE (lhs) == SSA_NAME)
4315 tree var = create_tmp_var (TREE_TYPE (lhs));
4316 SET_SSA_NAME_VAR_OR_IDENTIFIER (lhs, var);
4317 SSA_NAME_DEF_STMT (lhs) = gimple_build_nop ();
4318 set_ssa_default_def (cfun, var, lhs);
4320 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
4321 gimple_set_vdef (new_stmt, gimple_vdef (stmt));
4322 gsi_replace (gsi, new_stmt, false);
4323 return true;
4329 /* Check for indirect calls that became direct calls, and then
4330 no longer require a static chain. */
4331 if (gimple_call_chain (stmt))
4333 tree fn = gimple_call_fndecl (stmt);
4334 if (fn && !DECL_STATIC_CHAIN (fn))
4336 gimple_call_set_chain (stmt, NULL);
4337 changed = true;
4339 else
4341 tree tmp = maybe_fold_reference (gimple_call_chain (stmt), false);
4342 if (tmp)
4344 gimple_call_set_chain (stmt, tmp);
4345 changed = true;
4350 if (inplace)
4351 return changed;
4353 /* Check for builtins that CCP can handle using information not
4354 available in the generic fold routines. */
4355 if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
4357 if (gimple_fold_builtin (gsi))
4358 changed = true;
4360 else if (gimple_call_builtin_p (stmt, BUILT_IN_MD))
4362 changed |= targetm.gimple_fold_builtin (gsi);
4364 else if (gimple_call_internal_p (stmt))
4366 enum tree_code subcode = ERROR_MARK;
4367 tree result = NULL_TREE;
4368 bool cplx_result = false;
4369 tree overflow = NULL_TREE;
4370 switch (gimple_call_internal_fn (stmt))
4372 case IFN_BUILTIN_EXPECT:
4373 result = fold_builtin_expect (gimple_location (stmt),
4374 gimple_call_arg (stmt, 0),
4375 gimple_call_arg (stmt, 1),
4376 gimple_call_arg (stmt, 2),
4377 NULL_TREE);
4378 break;
4379 case IFN_UBSAN_OBJECT_SIZE:
4381 tree offset = gimple_call_arg (stmt, 1);
4382 tree objsize = gimple_call_arg (stmt, 2);
4383 if (integer_all_onesp (objsize)
4384 || (TREE_CODE (offset) == INTEGER_CST
4385 && TREE_CODE (objsize) == INTEGER_CST
4386 && tree_int_cst_le (offset, objsize)))
4388 replace_call_with_value (gsi, NULL_TREE);
4389 return true;
4392 break;
4393 case IFN_UBSAN_PTR:
4394 if (integer_zerop (gimple_call_arg (stmt, 1)))
4396 replace_call_with_value (gsi, NULL_TREE);
4397 return true;
4399 break;
4400 case IFN_UBSAN_BOUNDS:
4402 tree index = gimple_call_arg (stmt, 1);
4403 tree bound = gimple_call_arg (stmt, 2);
4404 if (TREE_CODE (index) == INTEGER_CST
4405 && TREE_CODE (bound) == INTEGER_CST)
4407 index = fold_convert (TREE_TYPE (bound), index);
4408 if (TREE_CODE (index) == INTEGER_CST
4409 && tree_int_cst_le (index, bound))
4411 replace_call_with_value (gsi, NULL_TREE);
4412 return true;
4416 break;
4417 case IFN_GOACC_DIM_SIZE:
4418 case IFN_GOACC_DIM_POS:
4419 result = fold_internal_goacc_dim (stmt);
4420 break;
4421 case IFN_UBSAN_CHECK_ADD:
4422 subcode = PLUS_EXPR;
4423 break;
4424 case IFN_UBSAN_CHECK_SUB:
4425 subcode = MINUS_EXPR;
4426 break;
4427 case IFN_UBSAN_CHECK_MUL:
4428 subcode = MULT_EXPR;
4429 break;
4430 case IFN_ADD_OVERFLOW:
4431 subcode = PLUS_EXPR;
4432 cplx_result = true;
4433 break;
4434 case IFN_SUB_OVERFLOW:
4435 subcode = MINUS_EXPR;
4436 cplx_result = true;
4437 break;
4438 case IFN_MUL_OVERFLOW:
4439 subcode = MULT_EXPR;
4440 cplx_result = true;
4441 break;
4442 default:
4443 break;
4445 if (subcode != ERROR_MARK)
4447 tree arg0 = gimple_call_arg (stmt, 0);
4448 tree arg1 = gimple_call_arg (stmt, 1);
4449 tree type = TREE_TYPE (arg0);
4450 if (cplx_result)
4452 tree lhs = gimple_call_lhs (stmt);
4453 if (lhs == NULL_TREE)
4454 type = NULL_TREE;
4455 else
4456 type = TREE_TYPE (TREE_TYPE (lhs));
4458 if (type == NULL_TREE)
4460 /* x = y + 0; x = y - 0; x = y * 0; */
4461 else if (integer_zerop (arg1))
4462 result = subcode == MULT_EXPR ? integer_zero_node : arg0;
4463 /* x = 0 + y; x = 0 * y; */
4464 else if (subcode != MINUS_EXPR && integer_zerop (arg0))
4465 result = subcode == MULT_EXPR ? integer_zero_node : arg1;
4466 /* x = y - y; */
4467 else if (subcode == MINUS_EXPR && operand_equal_p (arg0, arg1, 0))
4468 result = integer_zero_node;
4469 /* x = y * 1; x = 1 * y; */
4470 else if (subcode == MULT_EXPR && integer_onep (arg1))
4471 result = arg0;
4472 else if (subcode == MULT_EXPR && integer_onep (arg0))
4473 result = arg1;
4474 else if (TREE_CODE (arg0) == INTEGER_CST
4475 && TREE_CODE (arg1) == INTEGER_CST)
4477 if (cplx_result)
4478 result = int_const_binop (subcode, fold_convert (type, arg0),
4479 fold_convert (type, arg1));
4480 else
4481 result = int_const_binop (subcode, arg0, arg1);
4482 if (result && arith_overflowed_p (subcode, type, arg0, arg1))
4484 if (cplx_result)
4485 overflow = build_one_cst (type);
4486 else
4487 result = NULL_TREE;
4490 if (result)
4492 if (result == integer_zero_node)
4493 result = build_zero_cst (type);
4494 else if (cplx_result && TREE_TYPE (result) != type)
4496 if (TREE_CODE (result) == INTEGER_CST)
4498 if (arith_overflowed_p (PLUS_EXPR, type, result,
4499 integer_zero_node))
4500 overflow = build_one_cst (type);
4502 else if ((!TYPE_UNSIGNED (TREE_TYPE (result))
4503 && TYPE_UNSIGNED (type))
4504 || (TYPE_PRECISION (type)
4505 < (TYPE_PRECISION (TREE_TYPE (result))
4506 + (TYPE_UNSIGNED (TREE_TYPE (result))
4507 && !TYPE_UNSIGNED (type)))))
4508 result = NULL_TREE;
4509 if (result)
4510 result = fold_convert (type, result);
4515 if (result)
4517 if (TREE_CODE (result) == INTEGER_CST && TREE_OVERFLOW (result))
4518 result = drop_tree_overflow (result);
4519 if (cplx_result)
4521 if (overflow == NULL_TREE)
4522 overflow = build_zero_cst (TREE_TYPE (result));
4523 tree ctype = build_complex_type (TREE_TYPE (result));
4524 if (TREE_CODE (result) == INTEGER_CST
4525 && TREE_CODE (overflow) == INTEGER_CST)
4526 result = build_complex (ctype, result, overflow);
4527 else
4528 result = build2_loc (gimple_location (stmt), COMPLEX_EXPR,
4529 ctype, result, overflow);
4531 if (!update_call_from_tree (gsi, result))
4532 gimplify_and_update_call_from_tree (gsi, result);
4533 changed = true;
4537 return changed;
4541 /* Return true whether NAME has a use on STMT. */
4543 static bool
4544 has_use_on_stmt (tree name, gimple *stmt)
4546 imm_use_iterator iter;
4547 use_operand_p use_p;
4548 FOR_EACH_IMM_USE_FAST (use_p, iter, name)
4549 if (USE_STMT (use_p) == stmt)
4550 return true;
4551 return false;
4554 /* Worker for fold_stmt_1 dispatch to pattern based folding with
4555 gimple_simplify.
4557 Replaces *GSI with the simplification result in RCODE and OPS
4558 and the associated statements in *SEQ. Does the replacement
4559 according to INPLACE and returns true if the operation succeeded. */
4561 static bool
4562 replace_stmt_with_simplification (gimple_stmt_iterator *gsi,
4563 gimple_match_op *res_op,
4564 gimple_seq *seq, bool inplace)
4566 gimple *stmt = gsi_stmt (*gsi);
4567 tree *ops = res_op->ops;
4568 unsigned int num_ops = res_op->num_ops;
4570 /* Play safe and do not allow abnormals to be mentioned in
4571 newly created statements. See also maybe_push_res_to_seq.
4572 As an exception allow such uses if there was a use of the
4573 same SSA name on the old stmt. */
4574 for (unsigned int i = 0; i < num_ops; ++i)
4575 if (TREE_CODE (ops[i]) == SSA_NAME
4576 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ops[i])
4577 && !has_use_on_stmt (ops[i], stmt))
4578 return false;
4580 if (num_ops > 0 && COMPARISON_CLASS_P (ops[0]))
4581 for (unsigned int i = 0; i < 2; ++i)
4582 if (TREE_CODE (TREE_OPERAND (ops[0], i)) == SSA_NAME
4583 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (TREE_OPERAND (ops[0], i))
4584 && !has_use_on_stmt (TREE_OPERAND (ops[0], i), stmt))
4585 return false;
4587 /* Don't insert new statements when INPLACE is true, even if we could
4588 reuse STMT for the final statement. */
4589 if (inplace && !gimple_seq_empty_p (*seq))
4590 return false;
4592 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
4594 gcc_assert (res_op->code.is_tree_code ());
4595 if (TREE_CODE_CLASS ((enum tree_code) res_op->code) == tcc_comparison
4596 /* GIMPLE_CONDs condition may not throw. */
4597 && (!flag_exceptions
4598 || !cfun->can_throw_non_call_exceptions
4599 || !operation_could_trap_p (res_op->code,
4600 FLOAT_TYPE_P (TREE_TYPE (ops[0])),
4601 false, NULL_TREE)))
4602 gimple_cond_set_condition (cond_stmt, res_op->code, ops[0], ops[1]);
4603 else if (res_op->code == SSA_NAME)
4604 gimple_cond_set_condition (cond_stmt, NE_EXPR, ops[0],
4605 build_zero_cst (TREE_TYPE (ops[0])));
4606 else if (res_op->code == INTEGER_CST)
4608 if (integer_zerop (ops[0]))
4609 gimple_cond_make_false (cond_stmt);
4610 else
4611 gimple_cond_make_true (cond_stmt);
4613 else if (!inplace)
4615 tree res = maybe_push_res_to_seq (res_op, seq);
4616 if (!res)
4617 return false;
4618 gimple_cond_set_condition (cond_stmt, NE_EXPR, res,
4619 build_zero_cst (TREE_TYPE (res)));
4621 else
4622 return false;
4623 if (dump_file && (dump_flags & TDF_DETAILS))
4625 fprintf (dump_file, "gimple_simplified to ");
4626 if (!gimple_seq_empty_p (*seq))
4627 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
4628 print_gimple_stmt (dump_file, gsi_stmt (*gsi),
4629 0, TDF_SLIM);
4631 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
4632 return true;
4634 else if (is_gimple_assign (stmt)
4635 && res_op->code.is_tree_code ())
4637 if (!inplace
4638 || gimple_num_ops (stmt) > get_gimple_rhs_num_ops (res_op->code))
4640 maybe_build_generic_op (res_op);
4641 gimple_assign_set_rhs_with_ops (gsi, res_op->code,
4642 res_op->op_or_null (0),
4643 res_op->op_or_null (1),
4644 res_op->op_or_null (2));
4645 if (dump_file && (dump_flags & TDF_DETAILS))
4647 fprintf (dump_file, "gimple_simplified to ");
4648 if (!gimple_seq_empty_p (*seq))
4649 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
4650 print_gimple_stmt (dump_file, gsi_stmt (*gsi),
4651 0, TDF_SLIM);
4653 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
4654 return true;
4657 else if (res_op->code.is_fn_code ()
4658 && gimple_call_combined_fn (stmt) == res_op->code)
4660 gcc_assert (num_ops == gimple_call_num_args (stmt));
4661 for (unsigned int i = 0; i < num_ops; ++i)
4662 gimple_call_set_arg (stmt, i, ops[i]);
4663 if (dump_file && (dump_flags & TDF_DETAILS))
4665 fprintf (dump_file, "gimple_simplified to ");
4666 if (!gimple_seq_empty_p (*seq))
4667 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
4668 print_gimple_stmt (dump_file, gsi_stmt (*gsi), 0, TDF_SLIM);
4670 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
4671 return true;
4673 else if (!inplace)
4675 if (gimple_has_lhs (stmt))
4677 tree lhs = gimple_get_lhs (stmt);
4678 if (!maybe_push_res_to_seq (res_op, seq, lhs))
4679 return false;
4680 if (dump_file && (dump_flags & TDF_DETAILS))
4682 fprintf (dump_file, "gimple_simplified to ");
4683 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
4685 gsi_replace_with_seq_vops (gsi, *seq);
4686 return true;
4688 else
4689 gcc_unreachable ();
4692 return false;
4695 /* Canonicalize MEM_REFs invariant address operand after propagation. */
4697 static bool
4698 maybe_canonicalize_mem_ref_addr (tree *t)
4700 bool res = false;
4702 if (TREE_CODE (*t) == ADDR_EXPR)
4703 t = &TREE_OPERAND (*t, 0);
4705 /* The C and C++ frontends use an ARRAY_REF for indexing with their
4706 generic vector extension. The actual vector referenced is
4707 view-converted to an array type for this purpose. If the index
4708 is constant the canonical representation in the middle-end is a
4709 BIT_FIELD_REF so re-write the former to the latter here. */
4710 if (TREE_CODE (*t) == ARRAY_REF
4711 && TREE_CODE (TREE_OPERAND (*t, 0)) == VIEW_CONVERT_EXPR
4712 && TREE_CODE (TREE_OPERAND (*t, 1)) == INTEGER_CST
4713 && VECTOR_TYPE_P (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (*t, 0), 0))))
4715 tree vtype = TREE_TYPE (TREE_OPERAND (TREE_OPERAND (*t, 0), 0));
4716 if (VECTOR_TYPE_P (vtype))
4718 tree low = array_ref_low_bound (*t);
4719 if (TREE_CODE (low) == INTEGER_CST)
4721 if (tree_int_cst_le (low, TREE_OPERAND (*t, 1)))
4723 widest_int idx = wi::sub (wi::to_widest (TREE_OPERAND (*t, 1)),
4724 wi::to_widest (low));
4725 idx = wi::mul (idx, wi::to_widest
4726 (TYPE_SIZE (TREE_TYPE (*t))));
4727 widest_int ext
4728 = wi::add (idx, wi::to_widest (TYPE_SIZE (TREE_TYPE (*t))));
4729 if (wi::les_p (ext, wi::to_widest (TYPE_SIZE (vtype))))
4731 *t = build3_loc (EXPR_LOCATION (*t), BIT_FIELD_REF,
4732 TREE_TYPE (*t),
4733 TREE_OPERAND (TREE_OPERAND (*t, 0), 0),
4734 TYPE_SIZE (TREE_TYPE (*t)),
4735 wide_int_to_tree (bitsizetype, idx));
4736 res = true;
4743 while (handled_component_p (*t))
4744 t = &TREE_OPERAND (*t, 0);
4746 /* Canonicalize MEM [&foo.bar, 0] which appears after propagating
4747 of invariant addresses into a SSA name MEM_REF address. */
4748 if (TREE_CODE (*t) == MEM_REF
4749 || TREE_CODE (*t) == TARGET_MEM_REF)
4751 tree addr = TREE_OPERAND (*t, 0);
4752 if (TREE_CODE (addr) == ADDR_EXPR
4753 && (TREE_CODE (TREE_OPERAND (addr, 0)) == MEM_REF
4754 || handled_component_p (TREE_OPERAND (addr, 0))))
4756 tree base;
4757 poly_int64 coffset;
4758 base = get_addr_base_and_unit_offset (TREE_OPERAND (addr, 0),
4759 &coffset);
4760 if (!base)
4761 gcc_unreachable ();
4763 TREE_OPERAND (*t, 0) = build_fold_addr_expr (base);
4764 TREE_OPERAND (*t, 1) = int_const_binop (PLUS_EXPR,
4765 TREE_OPERAND (*t, 1),
4766 size_int (coffset));
4767 res = true;
4769 gcc_checking_assert (TREE_CODE (TREE_OPERAND (*t, 0)) == DEBUG_EXPR_DECL
4770 || is_gimple_mem_ref_addr (TREE_OPERAND (*t, 0)));
4773 /* Canonicalize back MEM_REFs to plain reference trees if the object
4774 accessed is a decl that has the same access semantics as the MEM_REF. */
4775 if (TREE_CODE (*t) == MEM_REF
4776 && TREE_CODE (TREE_OPERAND (*t, 0)) == ADDR_EXPR
4777 && integer_zerop (TREE_OPERAND (*t, 1))
4778 && MR_DEPENDENCE_CLIQUE (*t) == 0)
4780 tree decl = TREE_OPERAND (TREE_OPERAND (*t, 0), 0);
4781 tree alias_type = TREE_TYPE (TREE_OPERAND (*t, 1));
4782 if (/* Same volatile qualification. */
4783 TREE_THIS_VOLATILE (*t) == TREE_THIS_VOLATILE (decl)
4784 /* Same TBAA behavior with -fstrict-aliasing. */
4785 && !TYPE_REF_CAN_ALIAS_ALL (alias_type)
4786 && (TYPE_MAIN_VARIANT (TREE_TYPE (decl))
4787 == TYPE_MAIN_VARIANT (TREE_TYPE (alias_type)))
4788 /* Same alignment. */
4789 && TYPE_ALIGN (TREE_TYPE (decl)) == TYPE_ALIGN (TREE_TYPE (*t))
4790 /* We have to look out here to not drop a required conversion
4791 from the rhs to the lhs if *t appears on the lhs or vice-versa
4792 if it appears on the rhs. Thus require strict type
4793 compatibility. */
4794 && types_compatible_p (TREE_TYPE (*t), TREE_TYPE (decl)))
4796 *t = TREE_OPERAND (TREE_OPERAND (*t, 0), 0);
4797 res = true;
4801 /* Canonicalize TARGET_MEM_REF in particular with respect to
4802 the indexes becoming constant. */
4803 else if (TREE_CODE (*t) == TARGET_MEM_REF)
4805 tree tem = maybe_fold_tmr (*t);
4806 if (tem)
4808 *t = tem;
4809 res = true;
4813 return res;
4816 /* Worker for both fold_stmt and fold_stmt_inplace. The INPLACE argument
4817 distinguishes both cases. */
4819 static bool
4820 fold_stmt_1 (gimple_stmt_iterator *gsi, bool inplace, tree (*valueize) (tree))
4822 bool changed = false;
4823 gimple *stmt = gsi_stmt (*gsi);
4824 bool nowarning = gimple_no_warning_p (stmt);
4825 unsigned i;
4826 fold_defer_overflow_warnings ();
4828 /* First do required canonicalization of [TARGET_]MEM_REF addresses
4829 after propagation.
4830 ??? This shouldn't be done in generic folding but in the
4831 propagation helpers which also know whether an address was
4832 propagated.
4833 Also canonicalize operand order. */
4834 switch (gimple_code (stmt))
4836 case GIMPLE_ASSIGN:
4837 if (gimple_assign_rhs_class (stmt) == GIMPLE_SINGLE_RHS)
4839 tree *rhs = gimple_assign_rhs1_ptr (stmt);
4840 if ((REFERENCE_CLASS_P (*rhs)
4841 || TREE_CODE (*rhs) == ADDR_EXPR)
4842 && maybe_canonicalize_mem_ref_addr (rhs))
4843 changed = true;
4844 tree *lhs = gimple_assign_lhs_ptr (stmt);
4845 if (REFERENCE_CLASS_P (*lhs)
4846 && maybe_canonicalize_mem_ref_addr (lhs))
4847 changed = true;
4849 else
4851 /* Canonicalize operand order. */
4852 enum tree_code code = gimple_assign_rhs_code (stmt);
4853 if (TREE_CODE_CLASS (code) == tcc_comparison
4854 || commutative_tree_code (code)
4855 || commutative_ternary_tree_code (code))
4857 tree rhs1 = gimple_assign_rhs1 (stmt);
4858 tree rhs2 = gimple_assign_rhs2 (stmt);
4859 if (tree_swap_operands_p (rhs1, rhs2))
4861 gimple_assign_set_rhs1 (stmt, rhs2);
4862 gimple_assign_set_rhs2 (stmt, rhs1);
4863 if (TREE_CODE_CLASS (code) == tcc_comparison)
4864 gimple_assign_set_rhs_code (stmt,
4865 swap_tree_comparison (code));
4866 changed = true;
4870 break;
4871 case GIMPLE_CALL:
4873 for (i = 0; i < gimple_call_num_args (stmt); ++i)
4875 tree *arg = gimple_call_arg_ptr (stmt, i);
4876 if (REFERENCE_CLASS_P (*arg)
4877 && maybe_canonicalize_mem_ref_addr (arg))
4878 changed = true;
4880 tree *lhs = gimple_call_lhs_ptr (stmt);
4881 if (*lhs
4882 && REFERENCE_CLASS_P (*lhs)
4883 && maybe_canonicalize_mem_ref_addr (lhs))
4884 changed = true;
4885 break;
4887 case GIMPLE_ASM:
4889 gasm *asm_stmt = as_a <gasm *> (stmt);
4890 for (i = 0; i < gimple_asm_noutputs (asm_stmt); ++i)
4892 tree link = gimple_asm_output_op (asm_stmt, i);
4893 tree op = TREE_VALUE (link);
4894 if (REFERENCE_CLASS_P (op)
4895 && maybe_canonicalize_mem_ref_addr (&TREE_VALUE (link)))
4896 changed = true;
4898 for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
4900 tree link = gimple_asm_input_op (asm_stmt, i);
4901 tree op = TREE_VALUE (link);
4902 if ((REFERENCE_CLASS_P (op)
4903 || TREE_CODE (op) == ADDR_EXPR)
4904 && maybe_canonicalize_mem_ref_addr (&TREE_VALUE (link)))
4905 changed = true;
4908 break;
4909 case GIMPLE_DEBUG:
4910 if (gimple_debug_bind_p (stmt))
4912 tree *val = gimple_debug_bind_get_value_ptr (stmt);
4913 if (*val
4914 && (REFERENCE_CLASS_P (*val)
4915 || TREE_CODE (*val) == ADDR_EXPR)
4916 && maybe_canonicalize_mem_ref_addr (val))
4917 changed = true;
4919 break;
4920 case GIMPLE_COND:
4922 /* Canonicalize operand order. */
4923 tree lhs = gimple_cond_lhs (stmt);
4924 tree rhs = gimple_cond_rhs (stmt);
4925 if (tree_swap_operands_p (lhs, rhs))
4927 gcond *gc = as_a <gcond *> (stmt);
4928 gimple_cond_set_lhs (gc, rhs);
4929 gimple_cond_set_rhs (gc, lhs);
4930 gimple_cond_set_code (gc,
4931 swap_tree_comparison (gimple_cond_code (gc)));
4932 changed = true;
4935 default:;
4938 /* Dispatch to pattern-based folding. */
4939 if (!inplace
4940 || is_gimple_assign (stmt)
4941 || gimple_code (stmt) == GIMPLE_COND)
4943 gimple_seq seq = NULL;
4944 gimple_match_op res_op;
4945 if (gimple_simplify (stmt, &res_op, inplace ? NULL : &seq,
4946 valueize, valueize))
4948 if (replace_stmt_with_simplification (gsi, &res_op, &seq, inplace))
4949 changed = true;
4950 else
4951 gimple_seq_discard (seq);
4955 stmt = gsi_stmt (*gsi);
4957 /* Fold the main computation performed by the statement. */
4958 switch (gimple_code (stmt))
4960 case GIMPLE_ASSIGN:
4962 /* Try to canonicalize for boolean-typed X the comparisons
4963 X == 0, X == 1, X != 0, and X != 1. */
4964 if (gimple_assign_rhs_code (stmt) == EQ_EXPR
4965 || gimple_assign_rhs_code (stmt) == NE_EXPR)
4967 tree lhs = gimple_assign_lhs (stmt);
4968 tree op1 = gimple_assign_rhs1 (stmt);
4969 tree op2 = gimple_assign_rhs2 (stmt);
4970 tree type = TREE_TYPE (op1);
4972 /* Check whether the comparison operands are of the same boolean
4973 type as the result type is.
4974 Check that second operand is an integer-constant with value
4975 one or zero. */
4976 if (TREE_CODE (op2) == INTEGER_CST
4977 && (integer_zerop (op2) || integer_onep (op2))
4978 && useless_type_conversion_p (TREE_TYPE (lhs), type))
4980 enum tree_code cmp_code = gimple_assign_rhs_code (stmt);
4981 bool is_logical_not = false;
4983 /* X == 0 and X != 1 is a logical-not.of X
4984 X == 1 and X != 0 is X */
4985 if ((cmp_code == EQ_EXPR && integer_zerop (op2))
4986 || (cmp_code == NE_EXPR && integer_onep (op2)))
4987 is_logical_not = true;
4989 if (is_logical_not == false)
4990 gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op1), op1);
4991 /* Only for one-bit precision typed X the transformation
4992 !X -> ~X is valied. */
4993 else if (TYPE_PRECISION (type) == 1)
4994 gimple_assign_set_rhs_with_ops (gsi, BIT_NOT_EXPR, op1);
4995 /* Otherwise we use !X -> X ^ 1. */
4996 else
4997 gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op1,
4998 build_int_cst (type, 1));
4999 changed = true;
5000 break;
5004 unsigned old_num_ops = gimple_num_ops (stmt);
5005 tree lhs = gimple_assign_lhs (stmt);
5006 tree new_rhs = fold_gimple_assign (gsi);
5007 if (new_rhs
5008 && !useless_type_conversion_p (TREE_TYPE (lhs),
5009 TREE_TYPE (new_rhs)))
5010 new_rhs = fold_convert (TREE_TYPE (lhs), new_rhs);
5011 if (new_rhs
5012 && (!inplace
5013 || get_gimple_rhs_num_ops (TREE_CODE (new_rhs)) < old_num_ops))
5015 gimple_assign_set_rhs_from_tree (gsi, new_rhs);
5016 changed = true;
5018 break;
5021 case GIMPLE_CALL:
5022 changed |= gimple_fold_call (gsi, inplace);
5023 break;
5025 case GIMPLE_ASM:
5026 /* Fold *& in asm operands. */
5028 gasm *asm_stmt = as_a <gasm *> (stmt);
5029 size_t noutputs;
5030 const char **oconstraints;
5031 const char *constraint;
5032 bool allows_mem, allows_reg;
5034 noutputs = gimple_asm_noutputs (asm_stmt);
5035 oconstraints = XALLOCAVEC (const char *, noutputs);
5037 for (i = 0; i < gimple_asm_noutputs (asm_stmt); ++i)
5039 tree link = gimple_asm_output_op (asm_stmt, i);
5040 tree op = TREE_VALUE (link);
5041 oconstraints[i]
5042 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
5043 if (REFERENCE_CLASS_P (op)
5044 && (op = maybe_fold_reference (op, true)) != NULL_TREE)
5046 TREE_VALUE (link) = op;
5047 changed = true;
5050 for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
5052 tree link = gimple_asm_input_op (asm_stmt, i);
5053 tree op = TREE_VALUE (link);
5054 constraint
5055 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
5056 parse_input_constraint (&constraint, 0, 0, noutputs, 0,
5057 oconstraints, &allows_mem, &allows_reg);
5058 if (REFERENCE_CLASS_P (op)
5059 && (op = maybe_fold_reference (op, !allows_reg && allows_mem))
5060 != NULL_TREE)
5062 TREE_VALUE (link) = op;
5063 changed = true;
5067 break;
5069 case GIMPLE_DEBUG:
5070 if (gimple_debug_bind_p (stmt))
5072 tree val = gimple_debug_bind_get_value (stmt);
5073 if (val
5074 && REFERENCE_CLASS_P (val))
5076 tree tem = maybe_fold_reference (val, false);
5077 if (tem)
5079 gimple_debug_bind_set_value (stmt, tem);
5080 changed = true;
5083 else if (val
5084 && TREE_CODE (val) == ADDR_EXPR)
5086 tree ref = TREE_OPERAND (val, 0);
5087 tree tem = maybe_fold_reference (ref, false);
5088 if (tem)
5090 tem = build_fold_addr_expr_with_type (tem, TREE_TYPE (val));
5091 gimple_debug_bind_set_value (stmt, tem);
5092 changed = true;
5096 break;
5098 case GIMPLE_RETURN:
5100 greturn *ret_stmt = as_a<greturn *> (stmt);
5101 tree ret = gimple_return_retval(ret_stmt);
5103 if (ret && TREE_CODE (ret) == SSA_NAME && valueize)
5105 tree val = valueize (ret);
5106 if (val && val != ret
5107 && may_propagate_copy (ret, val))
5109 gimple_return_set_retval (ret_stmt, val);
5110 changed = true;
5114 break;
5116 default:;
5119 stmt = gsi_stmt (*gsi);
5121 /* Fold *& on the lhs. */
5122 if (gimple_has_lhs (stmt))
5124 tree lhs = gimple_get_lhs (stmt);
5125 if (lhs && REFERENCE_CLASS_P (lhs))
5127 tree new_lhs = maybe_fold_reference (lhs, true);
5128 if (new_lhs)
5130 gimple_set_lhs (stmt, new_lhs);
5131 changed = true;
5136 fold_undefer_overflow_warnings (changed && !nowarning, stmt, 0);
5137 return changed;
5140 /* Valueziation callback that ends up not following SSA edges. */
5142 tree
5143 no_follow_ssa_edges (tree)
5145 return NULL_TREE;
5148 /* Valueization callback that ends up following single-use SSA edges only. */
5150 tree
5151 follow_single_use_edges (tree val)
5153 if (TREE_CODE (val) == SSA_NAME
5154 && !has_single_use (val))
5155 return NULL_TREE;
5156 return val;
5159 /* Valueization callback that follows all SSA edges. */
5161 tree
5162 follow_all_ssa_edges (tree val)
5164 return val;
5167 /* Fold the statement pointed to by GSI. In some cases, this function may
5168 replace the whole statement with a new one. Returns true iff folding
5169 makes any changes.
5170 The statement pointed to by GSI should be in valid gimple form but may
5171 be in unfolded state as resulting from for example constant propagation
5172 which can produce *&x = 0. */
5174 bool
5175 fold_stmt (gimple_stmt_iterator *gsi)
5177 return fold_stmt_1 (gsi, false, no_follow_ssa_edges);
5180 bool
5181 fold_stmt (gimple_stmt_iterator *gsi, tree (*valueize) (tree))
5183 return fold_stmt_1 (gsi, false, valueize);
5186 /* Perform the minimal folding on statement *GSI. Only operations like
5187 *&x created by constant propagation are handled. The statement cannot
5188 be replaced with a new one. Return true if the statement was
5189 changed, false otherwise.
5190 The statement *GSI should be in valid gimple form but may
5191 be in unfolded state as resulting from for example constant propagation
5192 which can produce *&x = 0. */
5194 bool
5195 fold_stmt_inplace (gimple_stmt_iterator *gsi)
5197 gimple *stmt = gsi_stmt (*gsi);
5198 bool changed = fold_stmt_1 (gsi, true, no_follow_ssa_edges);
5199 gcc_assert (gsi_stmt (*gsi) == stmt);
5200 return changed;
5203 /* Canonicalize and possibly invert the boolean EXPR; return NULL_TREE
5204 if EXPR is null or we don't know how.
5205 If non-null, the result always has boolean type. */
5207 static tree
5208 canonicalize_bool (tree expr, bool invert)
5210 if (!expr)
5211 return NULL_TREE;
5212 else if (invert)
5214 if (integer_nonzerop (expr))
5215 return boolean_false_node;
5216 else if (integer_zerop (expr))
5217 return boolean_true_node;
5218 else if (TREE_CODE (expr) == SSA_NAME)
5219 return fold_build2 (EQ_EXPR, boolean_type_node, expr,
5220 build_int_cst (TREE_TYPE (expr), 0));
5221 else if (COMPARISON_CLASS_P (expr))
5222 return fold_build2 (invert_tree_comparison (TREE_CODE (expr), false),
5223 boolean_type_node,
5224 TREE_OPERAND (expr, 0),
5225 TREE_OPERAND (expr, 1));
5226 else
5227 return NULL_TREE;
5229 else
5231 if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE)
5232 return expr;
5233 if (integer_nonzerop (expr))
5234 return boolean_true_node;
5235 else if (integer_zerop (expr))
5236 return boolean_false_node;
5237 else if (TREE_CODE (expr) == SSA_NAME)
5238 return fold_build2 (NE_EXPR, boolean_type_node, expr,
5239 build_int_cst (TREE_TYPE (expr), 0));
5240 else if (COMPARISON_CLASS_P (expr))
5241 return fold_build2 (TREE_CODE (expr),
5242 boolean_type_node,
5243 TREE_OPERAND (expr, 0),
5244 TREE_OPERAND (expr, 1));
5245 else
5246 return NULL_TREE;
5250 /* Check to see if a boolean expression EXPR is logically equivalent to the
5251 comparison (OP1 CODE OP2). Check for various identities involving
5252 SSA_NAMEs. */
5254 static bool
5255 same_bool_comparison_p (const_tree expr, enum tree_code code,
5256 const_tree op1, const_tree op2)
5258 gimple *s;
5260 /* The obvious case. */
5261 if (TREE_CODE (expr) == code
5262 && operand_equal_p (TREE_OPERAND (expr, 0), op1, 0)
5263 && operand_equal_p (TREE_OPERAND (expr, 1), op2, 0))
5264 return true;
5266 /* Check for comparing (name, name != 0) and the case where expr
5267 is an SSA_NAME with a definition matching the comparison. */
5268 if (TREE_CODE (expr) == SSA_NAME
5269 && TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE)
5271 if (operand_equal_p (expr, op1, 0))
5272 return ((code == NE_EXPR && integer_zerop (op2))
5273 || (code == EQ_EXPR && integer_nonzerop (op2)));
5274 s = SSA_NAME_DEF_STMT (expr);
5275 if (is_gimple_assign (s)
5276 && gimple_assign_rhs_code (s) == code
5277 && operand_equal_p (gimple_assign_rhs1 (s), op1, 0)
5278 && operand_equal_p (gimple_assign_rhs2 (s), op2, 0))
5279 return true;
5282 /* If op1 is of the form (name != 0) or (name == 0), and the definition
5283 of name is a comparison, recurse. */
5284 if (TREE_CODE (op1) == SSA_NAME
5285 && TREE_CODE (TREE_TYPE (op1)) == BOOLEAN_TYPE)
5287 s = SSA_NAME_DEF_STMT (op1);
5288 if (is_gimple_assign (s)
5289 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison)
5291 enum tree_code c = gimple_assign_rhs_code (s);
5292 if ((c == NE_EXPR && integer_zerop (op2))
5293 || (c == EQ_EXPR && integer_nonzerop (op2)))
5294 return same_bool_comparison_p (expr, c,
5295 gimple_assign_rhs1 (s),
5296 gimple_assign_rhs2 (s));
5297 if ((c == EQ_EXPR && integer_zerop (op2))
5298 || (c == NE_EXPR && integer_nonzerop (op2)))
5299 return same_bool_comparison_p (expr,
5300 invert_tree_comparison (c, false),
5301 gimple_assign_rhs1 (s),
5302 gimple_assign_rhs2 (s));
5305 return false;
5308 /* Check to see if two boolean expressions OP1 and OP2 are logically
5309 equivalent. */
5311 static bool
5312 same_bool_result_p (const_tree op1, const_tree op2)
5314 /* Simple cases first. */
5315 if (operand_equal_p (op1, op2, 0))
5316 return true;
5318 /* Check the cases where at least one of the operands is a comparison.
5319 These are a bit smarter than operand_equal_p in that they apply some
5320 identifies on SSA_NAMEs. */
5321 if (COMPARISON_CLASS_P (op2)
5322 && same_bool_comparison_p (op1, TREE_CODE (op2),
5323 TREE_OPERAND (op2, 0),
5324 TREE_OPERAND (op2, 1)))
5325 return true;
5326 if (COMPARISON_CLASS_P (op1)
5327 && same_bool_comparison_p (op2, TREE_CODE (op1),
5328 TREE_OPERAND (op1, 0),
5329 TREE_OPERAND (op1, 1)))
5330 return true;
5332 /* Default case. */
5333 return false;
5336 /* Forward declarations for some mutually recursive functions. */
5338 static tree
5339 and_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
5340 enum tree_code code2, tree op2a, tree op2b);
5341 static tree
5342 and_var_with_comparison (tree var, bool invert,
5343 enum tree_code code2, tree op2a, tree op2b);
5344 static tree
5345 and_var_with_comparison_1 (gimple *stmt,
5346 enum tree_code code2, tree op2a, tree op2b);
5347 static tree
5348 or_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
5349 enum tree_code code2, tree op2a, tree op2b);
5350 static tree
5351 or_var_with_comparison (tree var, bool invert,
5352 enum tree_code code2, tree op2a, tree op2b);
5353 static tree
5354 or_var_with_comparison_1 (gimple *stmt,
5355 enum tree_code code2, tree op2a, tree op2b);
5357 /* Helper function for and_comparisons_1: try to simplify the AND of the
5358 ssa variable VAR with the comparison specified by (OP2A CODE2 OP2B).
5359 If INVERT is true, invert the value of the VAR before doing the AND.
5360 Return NULL_EXPR if we can't simplify this to a single expression. */
5362 static tree
5363 and_var_with_comparison (tree var, bool invert,
5364 enum tree_code code2, tree op2a, tree op2b)
5366 tree t;
5367 gimple *stmt = SSA_NAME_DEF_STMT (var);
5369 /* We can only deal with variables whose definitions are assignments. */
5370 if (!is_gimple_assign (stmt))
5371 return NULL_TREE;
5373 /* If we have an inverted comparison, apply DeMorgan's law and rewrite
5374 !var AND (op2a code2 op2b) => !(var OR !(op2a code2 op2b))
5375 Then we only have to consider the simpler non-inverted cases. */
5376 if (invert)
5377 t = or_var_with_comparison_1 (stmt,
5378 invert_tree_comparison (code2, false),
5379 op2a, op2b);
5380 else
5381 t = and_var_with_comparison_1 (stmt, code2, op2a, op2b);
5382 return canonicalize_bool (t, invert);
5385 /* Try to simplify the AND of the ssa variable defined by the assignment
5386 STMT with the comparison specified by (OP2A CODE2 OP2B).
5387 Return NULL_EXPR if we can't simplify this to a single expression. */
5389 static tree
5390 and_var_with_comparison_1 (gimple *stmt,
5391 enum tree_code code2, tree op2a, tree op2b)
5393 tree var = gimple_assign_lhs (stmt);
5394 tree true_test_var = NULL_TREE;
5395 tree false_test_var = NULL_TREE;
5396 enum tree_code innercode = gimple_assign_rhs_code (stmt);
5398 /* Check for identities like (var AND (var == 0)) => false. */
5399 if (TREE_CODE (op2a) == SSA_NAME
5400 && TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE)
5402 if ((code2 == NE_EXPR && integer_zerop (op2b))
5403 || (code2 == EQ_EXPR && integer_nonzerop (op2b)))
5405 true_test_var = op2a;
5406 if (var == true_test_var)
5407 return var;
5409 else if ((code2 == EQ_EXPR && integer_zerop (op2b))
5410 || (code2 == NE_EXPR && integer_nonzerop (op2b)))
5412 false_test_var = op2a;
5413 if (var == false_test_var)
5414 return boolean_false_node;
5418 /* If the definition is a comparison, recurse on it. */
5419 if (TREE_CODE_CLASS (innercode) == tcc_comparison)
5421 tree t = and_comparisons_1 (innercode,
5422 gimple_assign_rhs1 (stmt),
5423 gimple_assign_rhs2 (stmt),
5424 code2,
5425 op2a,
5426 op2b);
5427 if (t)
5428 return t;
5431 /* If the definition is an AND or OR expression, we may be able to
5432 simplify by reassociating. */
5433 if (TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE
5434 && (innercode == BIT_AND_EXPR || innercode == BIT_IOR_EXPR))
5436 tree inner1 = gimple_assign_rhs1 (stmt);
5437 tree inner2 = gimple_assign_rhs2 (stmt);
5438 gimple *s;
5439 tree t;
5440 tree partial = NULL_TREE;
5441 bool is_and = (innercode == BIT_AND_EXPR);
5443 /* Check for boolean identities that don't require recursive examination
5444 of inner1/inner2:
5445 inner1 AND (inner1 AND inner2) => inner1 AND inner2 => var
5446 inner1 AND (inner1 OR inner2) => inner1
5447 !inner1 AND (inner1 AND inner2) => false
5448 !inner1 AND (inner1 OR inner2) => !inner1 AND inner2
5449 Likewise for similar cases involving inner2. */
5450 if (inner1 == true_test_var)
5451 return (is_and ? var : inner1);
5452 else if (inner2 == true_test_var)
5453 return (is_and ? var : inner2);
5454 else if (inner1 == false_test_var)
5455 return (is_and
5456 ? boolean_false_node
5457 : and_var_with_comparison (inner2, false, code2, op2a, op2b));
5458 else if (inner2 == false_test_var)
5459 return (is_and
5460 ? boolean_false_node
5461 : and_var_with_comparison (inner1, false, code2, op2a, op2b));
5463 /* Next, redistribute/reassociate the AND across the inner tests.
5464 Compute the first partial result, (inner1 AND (op2a code op2b)) */
5465 if (TREE_CODE (inner1) == SSA_NAME
5466 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner1))
5467 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
5468 && (t = maybe_fold_and_comparisons (gimple_assign_rhs_code (s),
5469 gimple_assign_rhs1 (s),
5470 gimple_assign_rhs2 (s),
5471 code2, op2a, op2b)))
5473 /* Handle the AND case, where we are reassociating:
5474 (inner1 AND inner2) AND (op2a code2 op2b)
5475 => (t AND inner2)
5476 If the partial result t is a constant, we win. Otherwise
5477 continue on to try reassociating with the other inner test. */
5478 if (is_and)
5480 if (integer_onep (t))
5481 return inner2;
5482 else if (integer_zerop (t))
5483 return boolean_false_node;
5486 /* Handle the OR case, where we are redistributing:
5487 (inner1 OR inner2) AND (op2a code2 op2b)
5488 => (t OR (inner2 AND (op2a code2 op2b))) */
5489 else if (integer_onep (t))
5490 return boolean_true_node;
5492 /* Save partial result for later. */
5493 partial = t;
5496 /* Compute the second partial result, (inner2 AND (op2a code op2b)) */
5497 if (TREE_CODE (inner2) == SSA_NAME
5498 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner2))
5499 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
5500 && (t = maybe_fold_and_comparisons (gimple_assign_rhs_code (s),
5501 gimple_assign_rhs1 (s),
5502 gimple_assign_rhs2 (s),
5503 code2, op2a, op2b)))
5505 /* Handle the AND case, where we are reassociating:
5506 (inner1 AND inner2) AND (op2a code2 op2b)
5507 => (inner1 AND t) */
5508 if (is_and)
5510 if (integer_onep (t))
5511 return inner1;
5512 else if (integer_zerop (t))
5513 return boolean_false_node;
5514 /* If both are the same, we can apply the identity
5515 (x AND x) == x. */
5516 else if (partial && same_bool_result_p (t, partial))
5517 return t;
5520 /* Handle the OR case. where we are redistributing:
5521 (inner1 OR inner2) AND (op2a code2 op2b)
5522 => (t OR (inner1 AND (op2a code2 op2b)))
5523 => (t OR partial) */
5524 else
5526 if (integer_onep (t))
5527 return boolean_true_node;
5528 else if (partial)
5530 /* We already got a simplification for the other
5531 operand to the redistributed OR expression. The
5532 interesting case is when at least one is false.
5533 Or, if both are the same, we can apply the identity
5534 (x OR x) == x. */
5535 if (integer_zerop (partial))
5536 return t;
5537 else if (integer_zerop (t))
5538 return partial;
5539 else if (same_bool_result_p (t, partial))
5540 return t;
5545 return NULL_TREE;
5548 /* Try to simplify the AND of two comparisons defined by
5549 (OP1A CODE1 OP1B) and (OP2A CODE2 OP2B), respectively.
5550 If this can be done without constructing an intermediate value,
5551 return the resulting tree; otherwise NULL_TREE is returned.
5552 This function is deliberately asymmetric as it recurses on SSA_DEFs
5553 in the first comparison but not the second. */
5555 static tree
5556 and_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
5557 enum tree_code code2, tree op2a, tree op2b)
5559 tree truth_type = truth_type_for (TREE_TYPE (op1a));
5561 /* First check for ((x CODE1 y) AND (x CODE2 y)). */
5562 if (operand_equal_p (op1a, op2a, 0)
5563 && operand_equal_p (op1b, op2b, 0))
5565 /* Result will be either NULL_TREE, or a combined comparison. */
5566 tree t = combine_comparisons (UNKNOWN_LOCATION,
5567 TRUTH_ANDIF_EXPR, code1, code2,
5568 truth_type, op1a, op1b);
5569 if (t)
5570 return t;
5573 /* Likewise the swapped case of the above. */
5574 if (operand_equal_p (op1a, op2b, 0)
5575 && operand_equal_p (op1b, op2a, 0))
5577 /* Result will be either NULL_TREE, or a combined comparison. */
5578 tree t = combine_comparisons (UNKNOWN_LOCATION,
5579 TRUTH_ANDIF_EXPR, code1,
5580 swap_tree_comparison (code2),
5581 truth_type, op1a, op1b);
5582 if (t)
5583 return t;
5586 /* If both comparisons are of the same value against constants, we might
5587 be able to merge them. */
5588 if (operand_equal_p (op1a, op2a, 0)
5589 && TREE_CODE (op1b) == INTEGER_CST
5590 && TREE_CODE (op2b) == INTEGER_CST)
5592 int cmp = tree_int_cst_compare (op1b, op2b);
5594 /* If we have (op1a == op1b), we should either be able to
5595 return that or FALSE, depending on whether the constant op1b
5596 also satisfies the other comparison against op2b. */
5597 if (code1 == EQ_EXPR)
5599 bool done = true;
5600 bool val;
5601 switch (code2)
5603 case EQ_EXPR: val = (cmp == 0); break;
5604 case NE_EXPR: val = (cmp != 0); break;
5605 case LT_EXPR: val = (cmp < 0); break;
5606 case GT_EXPR: val = (cmp > 0); break;
5607 case LE_EXPR: val = (cmp <= 0); break;
5608 case GE_EXPR: val = (cmp >= 0); break;
5609 default: done = false;
5611 if (done)
5613 if (val)
5614 return fold_build2 (code1, boolean_type_node, op1a, op1b);
5615 else
5616 return boolean_false_node;
5619 /* Likewise if the second comparison is an == comparison. */
5620 else if (code2 == EQ_EXPR)
5622 bool done = true;
5623 bool val;
5624 switch (code1)
5626 case EQ_EXPR: val = (cmp == 0); break;
5627 case NE_EXPR: val = (cmp != 0); break;
5628 case LT_EXPR: val = (cmp > 0); break;
5629 case GT_EXPR: val = (cmp < 0); break;
5630 case LE_EXPR: val = (cmp >= 0); break;
5631 case GE_EXPR: val = (cmp <= 0); break;
5632 default: done = false;
5634 if (done)
5636 if (val)
5637 return fold_build2 (code2, boolean_type_node, op2a, op2b);
5638 else
5639 return boolean_false_node;
5643 /* Same business with inequality tests. */
5644 else if (code1 == NE_EXPR)
5646 bool val;
5647 switch (code2)
5649 case EQ_EXPR: val = (cmp != 0); break;
5650 case NE_EXPR: val = (cmp == 0); break;
5651 case LT_EXPR: val = (cmp >= 0); break;
5652 case GT_EXPR: val = (cmp <= 0); break;
5653 case LE_EXPR: val = (cmp > 0); break;
5654 case GE_EXPR: val = (cmp < 0); break;
5655 default:
5656 val = false;
5658 if (val)
5659 return fold_build2 (code2, boolean_type_node, op2a, op2b);
5661 else if (code2 == NE_EXPR)
5663 bool val;
5664 switch (code1)
5666 case EQ_EXPR: val = (cmp == 0); break;
5667 case NE_EXPR: val = (cmp != 0); break;
5668 case LT_EXPR: val = (cmp <= 0); break;
5669 case GT_EXPR: val = (cmp >= 0); break;
5670 case LE_EXPR: val = (cmp < 0); break;
5671 case GE_EXPR: val = (cmp > 0); break;
5672 default:
5673 val = false;
5675 if (val)
5676 return fold_build2 (code1, boolean_type_node, op1a, op1b);
5679 /* Chose the more restrictive of two < or <= comparisons. */
5680 else if ((code1 == LT_EXPR || code1 == LE_EXPR)
5681 && (code2 == LT_EXPR || code2 == LE_EXPR))
5683 if ((cmp < 0) || (cmp == 0 && code1 == LT_EXPR))
5684 return fold_build2 (code1, boolean_type_node, op1a, op1b);
5685 else
5686 return fold_build2 (code2, boolean_type_node, op2a, op2b);
5689 /* Likewise chose the more restrictive of two > or >= comparisons. */
5690 else if ((code1 == GT_EXPR || code1 == GE_EXPR)
5691 && (code2 == GT_EXPR || code2 == GE_EXPR))
5693 if ((cmp > 0) || (cmp == 0 && code1 == GT_EXPR))
5694 return fold_build2 (code1, boolean_type_node, op1a, op1b);
5695 else
5696 return fold_build2 (code2, boolean_type_node, op2a, op2b);
5699 /* Check for singleton ranges. */
5700 else if (cmp == 0
5701 && ((code1 == LE_EXPR && code2 == GE_EXPR)
5702 || (code1 == GE_EXPR && code2 == LE_EXPR)))
5703 return fold_build2 (EQ_EXPR, boolean_type_node, op1a, op2b);
5705 /* Check for disjoint ranges. */
5706 else if (cmp <= 0
5707 && (code1 == LT_EXPR || code1 == LE_EXPR)
5708 && (code2 == GT_EXPR || code2 == GE_EXPR))
5709 return boolean_false_node;
5710 else if (cmp >= 0
5711 && (code1 == GT_EXPR || code1 == GE_EXPR)
5712 && (code2 == LT_EXPR || code2 == LE_EXPR))
5713 return boolean_false_node;
5716 /* Perhaps the first comparison is (NAME != 0) or (NAME == 1) where
5717 NAME's definition is a truth value. See if there are any simplifications
5718 that can be done against the NAME's definition. */
5719 if (TREE_CODE (op1a) == SSA_NAME
5720 && (code1 == NE_EXPR || code1 == EQ_EXPR)
5721 && (integer_zerop (op1b) || integer_onep (op1b)))
5723 bool invert = ((code1 == EQ_EXPR && integer_zerop (op1b))
5724 || (code1 == NE_EXPR && integer_onep (op1b)));
5725 gimple *stmt = SSA_NAME_DEF_STMT (op1a);
5726 switch (gimple_code (stmt))
5728 case GIMPLE_ASSIGN:
5729 /* Try to simplify by copy-propagating the definition. */
5730 return and_var_with_comparison (op1a, invert, code2, op2a, op2b);
5732 case GIMPLE_PHI:
5733 /* If every argument to the PHI produces the same result when
5734 ANDed with the second comparison, we win.
5735 Do not do this unless the type is bool since we need a bool
5736 result here anyway. */
5737 if (TREE_CODE (TREE_TYPE (op1a)) == BOOLEAN_TYPE)
5739 tree result = NULL_TREE;
5740 unsigned i;
5741 for (i = 0; i < gimple_phi_num_args (stmt); i++)
5743 tree arg = gimple_phi_arg_def (stmt, i);
5745 /* If this PHI has itself as an argument, ignore it.
5746 If all the other args produce the same result,
5747 we're still OK. */
5748 if (arg == gimple_phi_result (stmt))
5749 continue;
5750 else if (TREE_CODE (arg) == INTEGER_CST)
5752 if (invert ? integer_nonzerop (arg) : integer_zerop (arg))
5754 if (!result)
5755 result = boolean_false_node;
5756 else if (!integer_zerop (result))
5757 return NULL_TREE;
5759 else if (!result)
5760 result = fold_build2 (code2, boolean_type_node,
5761 op2a, op2b);
5762 else if (!same_bool_comparison_p (result,
5763 code2, op2a, op2b))
5764 return NULL_TREE;
5766 else if (TREE_CODE (arg) == SSA_NAME
5767 && !SSA_NAME_IS_DEFAULT_DEF (arg))
5769 tree temp;
5770 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
5771 /* In simple cases we can look through PHI nodes,
5772 but we have to be careful with loops.
5773 See PR49073. */
5774 if (! dom_info_available_p (CDI_DOMINATORS)
5775 || gimple_bb (def_stmt) == gimple_bb (stmt)
5776 || dominated_by_p (CDI_DOMINATORS,
5777 gimple_bb (def_stmt),
5778 gimple_bb (stmt)))
5779 return NULL_TREE;
5780 temp = and_var_with_comparison (arg, invert, code2,
5781 op2a, op2b);
5782 if (!temp)
5783 return NULL_TREE;
5784 else if (!result)
5785 result = temp;
5786 else if (!same_bool_result_p (result, temp))
5787 return NULL_TREE;
5789 else
5790 return NULL_TREE;
5792 return result;
5795 default:
5796 break;
5799 return NULL_TREE;
5802 /* Try to simplify the AND of two comparisons, specified by
5803 (OP1A CODE1 OP1B) and (OP2B CODE2 OP2B), respectively.
5804 If this can be simplified to a single expression (without requiring
5805 introducing more SSA variables to hold intermediate values),
5806 return the resulting tree. Otherwise return NULL_TREE.
5807 If the result expression is non-null, it has boolean type. */
5809 tree
5810 maybe_fold_and_comparisons (enum tree_code code1, tree op1a, tree op1b,
5811 enum tree_code code2, tree op2a, tree op2b)
5813 tree t = and_comparisons_1 (code1, op1a, op1b, code2, op2a, op2b);
5814 if (t)
5815 return t;
5816 else
5817 return and_comparisons_1 (code2, op2a, op2b, code1, op1a, op1b);
5820 /* Helper function for or_comparisons_1: try to simplify the OR of the
5821 ssa variable VAR with the comparison specified by (OP2A CODE2 OP2B).
5822 If INVERT is true, invert the value of VAR before doing the OR.
5823 Return NULL_EXPR if we can't simplify this to a single expression. */
5825 static tree
5826 or_var_with_comparison (tree var, bool invert,
5827 enum tree_code code2, tree op2a, tree op2b)
5829 tree t;
5830 gimple *stmt = SSA_NAME_DEF_STMT (var);
5832 /* We can only deal with variables whose definitions are assignments. */
5833 if (!is_gimple_assign (stmt))
5834 return NULL_TREE;
5836 /* If we have an inverted comparison, apply DeMorgan's law and rewrite
5837 !var OR (op2a code2 op2b) => !(var AND !(op2a code2 op2b))
5838 Then we only have to consider the simpler non-inverted cases. */
5839 if (invert)
5840 t = and_var_with_comparison_1 (stmt,
5841 invert_tree_comparison (code2, false),
5842 op2a, op2b);
5843 else
5844 t = or_var_with_comparison_1 (stmt, code2, op2a, op2b);
5845 return canonicalize_bool (t, invert);
5848 /* Try to simplify the OR of the ssa variable defined by the assignment
5849 STMT with the comparison specified by (OP2A CODE2 OP2B).
5850 Return NULL_EXPR if we can't simplify this to a single expression. */
5852 static tree
5853 or_var_with_comparison_1 (gimple *stmt,
5854 enum tree_code code2, tree op2a, tree op2b)
5856 tree var = gimple_assign_lhs (stmt);
5857 tree true_test_var = NULL_TREE;
5858 tree false_test_var = NULL_TREE;
5859 enum tree_code innercode = gimple_assign_rhs_code (stmt);
5861 /* Check for identities like (var OR (var != 0)) => true . */
5862 if (TREE_CODE (op2a) == SSA_NAME
5863 && TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE)
5865 if ((code2 == NE_EXPR && integer_zerop (op2b))
5866 || (code2 == EQ_EXPR && integer_nonzerop (op2b)))
5868 true_test_var = op2a;
5869 if (var == true_test_var)
5870 return var;
5872 else if ((code2 == EQ_EXPR && integer_zerop (op2b))
5873 || (code2 == NE_EXPR && integer_nonzerop (op2b)))
5875 false_test_var = op2a;
5876 if (var == false_test_var)
5877 return boolean_true_node;
5881 /* If the definition is a comparison, recurse on it. */
5882 if (TREE_CODE_CLASS (innercode) == tcc_comparison)
5884 tree t = or_comparisons_1 (innercode,
5885 gimple_assign_rhs1 (stmt),
5886 gimple_assign_rhs2 (stmt),
5887 code2,
5888 op2a,
5889 op2b);
5890 if (t)
5891 return t;
5894 /* If the definition is an AND or OR expression, we may be able to
5895 simplify by reassociating. */
5896 if (TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE
5897 && (innercode == BIT_AND_EXPR || innercode == BIT_IOR_EXPR))
5899 tree inner1 = gimple_assign_rhs1 (stmt);
5900 tree inner2 = gimple_assign_rhs2 (stmt);
5901 gimple *s;
5902 tree t;
5903 tree partial = NULL_TREE;
5904 bool is_or = (innercode == BIT_IOR_EXPR);
5906 /* Check for boolean identities that don't require recursive examination
5907 of inner1/inner2:
5908 inner1 OR (inner1 OR inner2) => inner1 OR inner2 => var
5909 inner1 OR (inner1 AND inner2) => inner1
5910 !inner1 OR (inner1 OR inner2) => true
5911 !inner1 OR (inner1 AND inner2) => !inner1 OR inner2
5913 if (inner1 == true_test_var)
5914 return (is_or ? var : inner1);
5915 else if (inner2 == true_test_var)
5916 return (is_or ? var : inner2);
5917 else if (inner1 == false_test_var)
5918 return (is_or
5919 ? boolean_true_node
5920 : or_var_with_comparison (inner2, false, code2, op2a, op2b));
5921 else if (inner2 == false_test_var)
5922 return (is_or
5923 ? boolean_true_node
5924 : or_var_with_comparison (inner1, false, code2, op2a, op2b));
5926 /* Next, redistribute/reassociate the OR across the inner tests.
5927 Compute the first partial result, (inner1 OR (op2a code op2b)) */
5928 if (TREE_CODE (inner1) == SSA_NAME
5929 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner1))
5930 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
5931 && (t = maybe_fold_or_comparisons (gimple_assign_rhs_code (s),
5932 gimple_assign_rhs1 (s),
5933 gimple_assign_rhs2 (s),
5934 code2, op2a, op2b)))
5936 /* Handle the OR case, where we are reassociating:
5937 (inner1 OR inner2) OR (op2a code2 op2b)
5938 => (t OR inner2)
5939 If the partial result t is a constant, we win. Otherwise
5940 continue on to try reassociating with the other inner test. */
5941 if (is_or)
5943 if (integer_onep (t))
5944 return boolean_true_node;
5945 else if (integer_zerop (t))
5946 return inner2;
5949 /* Handle the AND case, where we are redistributing:
5950 (inner1 AND inner2) OR (op2a code2 op2b)
5951 => (t AND (inner2 OR (op2a code op2b))) */
5952 else if (integer_zerop (t))
5953 return boolean_false_node;
5955 /* Save partial result for later. */
5956 partial = t;
5959 /* Compute the second partial result, (inner2 OR (op2a code op2b)) */
5960 if (TREE_CODE (inner2) == SSA_NAME
5961 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner2))
5962 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
5963 && (t = maybe_fold_or_comparisons (gimple_assign_rhs_code (s),
5964 gimple_assign_rhs1 (s),
5965 gimple_assign_rhs2 (s),
5966 code2, op2a, op2b)))
5968 /* Handle the OR case, where we are reassociating:
5969 (inner1 OR inner2) OR (op2a code2 op2b)
5970 => (inner1 OR t)
5971 => (t OR partial) */
5972 if (is_or)
5974 if (integer_zerop (t))
5975 return inner1;
5976 else if (integer_onep (t))
5977 return boolean_true_node;
5978 /* If both are the same, we can apply the identity
5979 (x OR x) == x. */
5980 else if (partial && same_bool_result_p (t, partial))
5981 return t;
5984 /* Handle the AND case, where we are redistributing:
5985 (inner1 AND inner2) OR (op2a code2 op2b)
5986 => (t AND (inner1 OR (op2a code2 op2b)))
5987 => (t AND partial) */
5988 else
5990 if (integer_zerop (t))
5991 return boolean_false_node;
5992 else if (partial)
5994 /* We already got a simplification for the other
5995 operand to the redistributed AND expression. The
5996 interesting case is when at least one is true.
5997 Or, if both are the same, we can apply the identity
5998 (x AND x) == x. */
5999 if (integer_onep (partial))
6000 return t;
6001 else if (integer_onep (t))
6002 return partial;
6003 else if (same_bool_result_p (t, partial))
6004 return t;
6009 return NULL_TREE;
6012 /* Try to simplify the OR of two comparisons defined by
6013 (OP1A CODE1 OP1B) and (OP2A CODE2 OP2B), respectively.
6014 If this can be done without constructing an intermediate value,
6015 return the resulting tree; otherwise NULL_TREE is returned.
6016 This function is deliberately asymmetric as it recurses on SSA_DEFs
6017 in the first comparison but not the second. */
6019 static tree
6020 or_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
6021 enum tree_code code2, tree op2a, tree op2b)
6023 tree truth_type = truth_type_for (TREE_TYPE (op1a));
6025 /* First check for ((x CODE1 y) OR (x CODE2 y)). */
6026 if (operand_equal_p (op1a, op2a, 0)
6027 && operand_equal_p (op1b, op2b, 0))
6029 /* Result will be either NULL_TREE, or a combined comparison. */
6030 tree t = combine_comparisons (UNKNOWN_LOCATION,
6031 TRUTH_ORIF_EXPR, code1, code2,
6032 truth_type, op1a, op1b);
6033 if (t)
6034 return t;
6037 /* Likewise the swapped case of the above. */
6038 if (operand_equal_p (op1a, op2b, 0)
6039 && operand_equal_p (op1b, op2a, 0))
6041 /* Result will be either NULL_TREE, or a combined comparison. */
6042 tree t = combine_comparisons (UNKNOWN_LOCATION,
6043 TRUTH_ORIF_EXPR, code1,
6044 swap_tree_comparison (code2),
6045 truth_type, op1a, op1b);
6046 if (t)
6047 return t;
6050 /* If both comparisons are of the same value against constants, we might
6051 be able to merge them. */
6052 if (operand_equal_p (op1a, op2a, 0)
6053 && TREE_CODE (op1b) == INTEGER_CST
6054 && TREE_CODE (op2b) == INTEGER_CST)
6056 int cmp = tree_int_cst_compare (op1b, op2b);
6058 /* If we have (op1a != op1b), we should either be able to
6059 return that or TRUE, depending on whether the constant op1b
6060 also satisfies the other comparison against op2b. */
6061 if (code1 == NE_EXPR)
6063 bool done = true;
6064 bool val;
6065 switch (code2)
6067 case EQ_EXPR: val = (cmp == 0); break;
6068 case NE_EXPR: val = (cmp != 0); break;
6069 case LT_EXPR: val = (cmp < 0); break;
6070 case GT_EXPR: val = (cmp > 0); break;
6071 case LE_EXPR: val = (cmp <= 0); break;
6072 case GE_EXPR: val = (cmp >= 0); break;
6073 default: done = false;
6075 if (done)
6077 if (val)
6078 return boolean_true_node;
6079 else
6080 return fold_build2 (code1, boolean_type_node, op1a, op1b);
6083 /* Likewise if the second comparison is a != comparison. */
6084 else if (code2 == NE_EXPR)
6086 bool done = true;
6087 bool val;
6088 switch (code1)
6090 case EQ_EXPR: val = (cmp == 0); break;
6091 case NE_EXPR: val = (cmp != 0); break;
6092 case LT_EXPR: val = (cmp > 0); break;
6093 case GT_EXPR: val = (cmp < 0); break;
6094 case LE_EXPR: val = (cmp >= 0); break;
6095 case GE_EXPR: val = (cmp <= 0); break;
6096 default: done = false;
6098 if (done)
6100 if (val)
6101 return boolean_true_node;
6102 else
6103 return fold_build2 (code2, boolean_type_node, op2a, op2b);
6107 /* See if an equality test is redundant with the other comparison. */
6108 else if (code1 == EQ_EXPR)
6110 bool val;
6111 switch (code2)
6113 case EQ_EXPR: val = (cmp == 0); break;
6114 case NE_EXPR: val = (cmp != 0); break;
6115 case LT_EXPR: val = (cmp < 0); break;
6116 case GT_EXPR: val = (cmp > 0); break;
6117 case LE_EXPR: val = (cmp <= 0); break;
6118 case GE_EXPR: val = (cmp >= 0); break;
6119 default:
6120 val = false;
6122 if (val)
6123 return fold_build2 (code2, boolean_type_node, op2a, op2b);
6125 else if (code2 == EQ_EXPR)
6127 bool val;
6128 switch (code1)
6130 case EQ_EXPR: val = (cmp == 0); break;
6131 case NE_EXPR: val = (cmp != 0); break;
6132 case LT_EXPR: val = (cmp > 0); break;
6133 case GT_EXPR: val = (cmp < 0); break;
6134 case LE_EXPR: val = (cmp >= 0); break;
6135 case GE_EXPR: val = (cmp <= 0); break;
6136 default:
6137 val = false;
6139 if (val)
6140 return fold_build2 (code1, boolean_type_node, op1a, op1b);
6143 /* Chose the less restrictive of two < or <= comparisons. */
6144 else if ((code1 == LT_EXPR || code1 == LE_EXPR)
6145 && (code2 == LT_EXPR || code2 == LE_EXPR))
6147 if ((cmp < 0) || (cmp == 0 && code1 == LT_EXPR))
6148 return fold_build2 (code2, boolean_type_node, op2a, op2b);
6149 else
6150 return fold_build2 (code1, boolean_type_node, op1a, op1b);
6153 /* Likewise chose the less restrictive of two > or >= comparisons. */
6154 else if ((code1 == GT_EXPR || code1 == GE_EXPR)
6155 && (code2 == GT_EXPR || code2 == GE_EXPR))
6157 if ((cmp > 0) || (cmp == 0 && code1 == GT_EXPR))
6158 return fold_build2 (code2, boolean_type_node, op2a, op2b);
6159 else
6160 return fold_build2 (code1, boolean_type_node, op1a, op1b);
6163 /* Check for singleton ranges. */
6164 else if (cmp == 0
6165 && ((code1 == LT_EXPR && code2 == GT_EXPR)
6166 || (code1 == GT_EXPR && code2 == LT_EXPR)))
6167 return fold_build2 (NE_EXPR, boolean_type_node, op1a, op2b);
6169 /* Check for less/greater pairs that don't restrict the range at all. */
6170 else if (cmp >= 0
6171 && (code1 == LT_EXPR || code1 == LE_EXPR)
6172 && (code2 == GT_EXPR || code2 == GE_EXPR))
6173 return boolean_true_node;
6174 else if (cmp <= 0
6175 && (code1 == GT_EXPR || code1 == GE_EXPR)
6176 && (code2 == LT_EXPR || code2 == LE_EXPR))
6177 return boolean_true_node;
6180 /* Perhaps the first comparison is (NAME != 0) or (NAME == 1) where
6181 NAME's definition is a truth value. See if there are any simplifications
6182 that can be done against the NAME's definition. */
6183 if (TREE_CODE (op1a) == SSA_NAME
6184 && (code1 == NE_EXPR || code1 == EQ_EXPR)
6185 && (integer_zerop (op1b) || integer_onep (op1b)))
6187 bool invert = ((code1 == EQ_EXPR && integer_zerop (op1b))
6188 || (code1 == NE_EXPR && integer_onep (op1b)));
6189 gimple *stmt = SSA_NAME_DEF_STMT (op1a);
6190 switch (gimple_code (stmt))
6192 case GIMPLE_ASSIGN:
6193 /* Try to simplify by copy-propagating the definition. */
6194 return or_var_with_comparison (op1a, invert, code2, op2a, op2b);
6196 case GIMPLE_PHI:
6197 /* If every argument to the PHI produces the same result when
6198 ORed with the second comparison, we win.
6199 Do not do this unless the type is bool since we need a bool
6200 result here anyway. */
6201 if (TREE_CODE (TREE_TYPE (op1a)) == BOOLEAN_TYPE)
6203 tree result = NULL_TREE;
6204 unsigned i;
6205 for (i = 0; i < gimple_phi_num_args (stmt); i++)
6207 tree arg = gimple_phi_arg_def (stmt, i);
6209 /* If this PHI has itself as an argument, ignore it.
6210 If all the other args produce the same result,
6211 we're still OK. */
6212 if (arg == gimple_phi_result (stmt))
6213 continue;
6214 else if (TREE_CODE (arg) == INTEGER_CST)
6216 if (invert ? integer_zerop (arg) : integer_nonzerop (arg))
6218 if (!result)
6219 result = boolean_true_node;
6220 else if (!integer_onep (result))
6221 return NULL_TREE;
6223 else if (!result)
6224 result = fold_build2 (code2, boolean_type_node,
6225 op2a, op2b);
6226 else if (!same_bool_comparison_p (result,
6227 code2, op2a, op2b))
6228 return NULL_TREE;
6230 else if (TREE_CODE (arg) == SSA_NAME
6231 && !SSA_NAME_IS_DEFAULT_DEF (arg))
6233 tree temp;
6234 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
6235 /* In simple cases we can look through PHI nodes,
6236 but we have to be careful with loops.
6237 See PR49073. */
6238 if (! dom_info_available_p (CDI_DOMINATORS)
6239 || gimple_bb (def_stmt) == gimple_bb (stmt)
6240 || dominated_by_p (CDI_DOMINATORS,
6241 gimple_bb (def_stmt),
6242 gimple_bb (stmt)))
6243 return NULL_TREE;
6244 temp = or_var_with_comparison (arg, invert, code2,
6245 op2a, op2b);
6246 if (!temp)
6247 return NULL_TREE;
6248 else if (!result)
6249 result = temp;
6250 else if (!same_bool_result_p (result, temp))
6251 return NULL_TREE;
6253 else
6254 return NULL_TREE;
6256 return result;
6259 default:
6260 break;
6263 return NULL_TREE;
6266 /* Try to simplify the OR of two comparisons, specified by
6267 (OP1A CODE1 OP1B) and (OP2B CODE2 OP2B), respectively.
6268 If this can be simplified to a single expression (without requiring
6269 introducing more SSA variables to hold intermediate values),
6270 return the resulting tree. Otherwise return NULL_TREE.
6271 If the result expression is non-null, it has boolean type. */
6273 tree
6274 maybe_fold_or_comparisons (enum tree_code code1, tree op1a, tree op1b,
6275 enum tree_code code2, tree op2a, tree op2b)
6277 tree t = or_comparisons_1 (code1, op1a, op1b, code2, op2a, op2b);
6278 if (t)
6279 return t;
6280 else
6281 return or_comparisons_1 (code2, op2a, op2b, code1, op1a, op1b);
6285 /* Fold STMT to a constant using VALUEIZE to valueize SSA names.
6287 Either NULL_TREE, a simplified but non-constant or a constant
6288 is returned.
6290 ??? This should go into a gimple-fold-inline.h file to be eventually
6291 privatized with the single valueize function used in the various TUs
6292 to avoid the indirect function call overhead. */
6294 tree
6295 gimple_fold_stmt_to_constant_1 (gimple *stmt, tree (*valueize) (tree),
6296 tree (*gvalueize) (tree))
6298 gimple_match_op res_op;
6299 /* ??? The SSA propagators do not correctly deal with following SSA use-def
6300 edges if there are intermediate VARYING defs. For this reason
6301 do not follow SSA edges here even though SCCVN can technically
6302 just deal fine with that. */
6303 if (gimple_simplify (stmt, &res_op, NULL, gvalueize, valueize))
6305 tree res = NULL_TREE;
6306 if (gimple_simplified_result_is_gimple_val (&res_op))
6307 res = res_op.ops[0];
6308 else if (mprts_hook)
6309 res = mprts_hook (&res_op);
6310 if (res)
6312 if (dump_file && dump_flags & TDF_DETAILS)
6314 fprintf (dump_file, "Match-and-simplified ");
6315 print_gimple_expr (dump_file, stmt, 0, TDF_SLIM);
6316 fprintf (dump_file, " to ");
6317 print_generic_expr (dump_file, res);
6318 fprintf (dump_file, "\n");
6320 return res;
6324 location_t loc = gimple_location (stmt);
6325 switch (gimple_code (stmt))
6327 case GIMPLE_ASSIGN:
6329 enum tree_code subcode = gimple_assign_rhs_code (stmt);
6331 switch (get_gimple_rhs_class (subcode))
6333 case GIMPLE_SINGLE_RHS:
6335 tree rhs = gimple_assign_rhs1 (stmt);
6336 enum tree_code_class kind = TREE_CODE_CLASS (subcode);
6338 if (TREE_CODE (rhs) == SSA_NAME)
6340 /* If the RHS is an SSA_NAME, return its known constant value,
6341 if any. */
6342 return (*valueize) (rhs);
6344 /* Handle propagating invariant addresses into address
6345 operations. */
6346 else if (TREE_CODE (rhs) == ADDR_EXPR
6347 && !is_gimple_min_invariant (rhs))
6349 poly_int64 offset = 0;
6350 tree base;
6351 base = get_addr_base_and_unit_offset_1 (TREE_OPERAND (rhs, 0),
6352 &offset,
6353 valueize);
6354 if (base
6355 && (CONSTANT_CLASS_P (base)
6356 || decl_address_invariant_p (base)))
6357 return build_invariant_address (TREE_TYPE (rhs),
6358 base, offset);
6360 else if (TREE_CODE (rhs) == CONSTRUCTOR
6361 && TREE_CODE (TREE_TYPE (rhs)) == VECTOR_TYPE
6362 && known_eq (CONSTRUCTOR_NELTS (rhs),
6363 TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs))))
6365 unsigned i, nelts;
6366 tree val;
6368 nelts = CONSTRUCTOR_NELTS (rhs);
6369 tree_vector_builder vec (TREE_TYPE (rhs), nelts, 1);
6370 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), i, val)
6372 val = (*valueize) (val);
6373 if (TREE_CODE (val) == INTEGER_CST
6374 || TREE_CODE (val) == REAL_CST
6375 || TREE_CODE (val) == FIXED_CST)
6376 vec.quick_push (val);
6377 else
6378 return NULL_TREE;
6381 return vec.build ();
6383 if (subcode == OBJ_TYPE_REF)
6385 tree val = (*valueize) (OBJ_TYPE_REF_EXPR (rhs));
6386 /* If callee is constant, we can fold away the wrapper. */
6387 if (is_gimple_min_invariant (val))
6388 return val;
6391 if (kind == tcc_reference)
6393 if ((TREE_CODE (rhs) == VIEW_CONVERT_EXPR
6394 || TREE_CODE (rhs) == REALPART_EXPR
6395 || TREE_CODE (rhs) == IMAGPART_EXPR)
6396 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
6398 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
6399 return fold_unary_loc (EXPR_LOCATION (rhs),
6400 TREE_CODE (rhs),
6401 TREE_TYPE (rhs), val);
6403 else if (TREE_CODE (rhs) == BIT_FIELD_REF
6404 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
6406 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
6407 return fold_ternary_loc (EXPR_LOCATION (rhs),
6408 TREE_CODE (rhs),
6409 TREE_TYPE (rhs), val,
6410 TREE_OPERAND (rhs, 1),
6411 TREE_OPERAND (rhs, 2));
6413 else if (TREE_CODE (rhs) == MEM_REF
6414 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
6416 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
6417 if (TREE_CODE (val) == ADDR_EXPR
6418 && is_gimple_min_invariant (val))
6420 tree tem = fold_build2 (MEM_REF, TREE_TYPE (rhs),
6421 unshare_expr (val),
6422 TREE_OPERAND (rhs, 1));
6423 if (tem)
6424 rhs = tem;
6427 return fold_const_aggregate_ref_1 (rhs, valueize);
6429 else if (kind == tcc_declaration)
6430 return get_symbol_constant_value (rhs);
6431 return rhs;
6434 case GIMPLE_UNARY_RHS:
6435 return NULL_TREE;
6437 case GIMPLE_BINARY_RHS:
6438 /* Translate &x + CST into an invariant form suitable for
6439 further propagation. */
6440 if (subcode == POINTER_PLUS_EXPR)
6442 tree op0 = (*valueize) (gimple_assign_rhs1 (stmt));
6443 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
6444 if (TREE_CODE (op0) == ADDR_EXPR
6445 && TREE_CODE (op1) == INTEGER_CST)
6447 tree off = fold_convert (ptr_type_node, op1);
6448 return build_fold_addr_expr_loc
6449 (loc,
6450 fold_build2 (MEM_REF,
6451 TREE_TYPE (TREE_TYPE (op0)),
6452 unshare_expr (op0), off));
6455 /* Canonicalize bool != 0 and bool == 0 appearing after
6456 valueization. While gimple_simplify handles this
6457 it can get confused by the ~X == 1 -> X == 0 transform
6458 which we cant reduce to a SSA name or a constant
6459 (and we have no way to tell gimple_simplify to not
6460 consider those transforms in the first place). */
6461 else if (subcode == EQ_EXPR
6462 || subcode == NE_EXPR)
6464 tree lhs = gimple_assign_lhs (stmt);
6465 tree op0 = gimple_assign_rhs1 (stmt);
6466 if (useless_type_conversion_p (TREE_TYPE (lhs),
6467 TREE_TYPE (op0)))
6469 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
6470 op0 = (*valueize) (op0);
6471 if (TREE_CODE (op0) == INTEGER_CST)
6472 std::swap (op0, op1);
6473 if (TREE_CODE (op1) == INTEGER_CST
6474 && ((subcode == NE_EXPR && integer_zerop (op1))
6475 || (subcode == EQ_EXPR && integer_onep (op1))))
6476 return op0;
6479 return NULL_TREE;
6481 case GIMPLE_TERNARY_RHS:
6483 /* Handle ternary operators that can appear in GIMPLE form. */
6484 tree op0 = (*valueize) (gimple_assign_rhs1 (stmt));
6485 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
6486 tree op2 = (*valueize) (gimple_assign_rhs3 (stmt));
6487 return fold_ternary_loc (loc, subcode,
6488 gimple_expr_type (stmt), op0, op1, op2);
6491 default:
6492 gcc_unreachable ();
6496 case GIMPLE_CALL:
6498 tree fn;
6499 gcall *call_stmt = as_a <gcall *> (stmt);
6501 if (gimple_call_internal_p (stmt))
6503 enum tree_code subcode = ERROR_MARK;
6504 switch (gimple_call_internal_fn (stmt))
6506 case IFN_UBSAN_CHECK_ADD:
6507 subcode = PLUS_EXPR;
6508 break;
6509 case IFN_UBSAN_CHECK_SUB:
6510 subcode = MINUS_EXPR;
6511 break;
6512 case IFN_UBSAN_CHECK_MUL:
6513 subcode = MULT_EXPR;
6514 break;
6515 case IFN_BUILTIN_EXPECT:
6517 tree arg0 = gimple_call_arg (stmt, 0);
6518 tree op0 = (*valueize) (arg0);
6519 if (TREE_CODE (op0) == INTEGER_CST)
6520 return op0;
6521 return NULL_TREE;
6523 default:
6524 return NULL_TREE;
6526 tree arg0 = gimple_call_arg (stmt, 0);
6527 tree arg1 = gimple_call_arg (stmt, 1);
6528 tree op0 = (*valueize) (arg0);
6529 tree op1 = (*valueize) (arg1);
6531 if (TREE_CODE (op0) != INTEGER_CST
6532 || TREE_CODE (op1) != INTEGER_CST)
6534 switch (subcode)
6536 case MULT_EXPR:
6537 /* x * 0 = 0 * x = 0 without overflow. */
6538 if (integer_zerop (op0) || integer_zerop (op1))
6539 return build_zero_cst (TREE_TYPE (arg0));
6540 break;
6541 case MINUS_EXPR:
6542 /* y - y = 0 without overflow. */
6543 if (operand_equal_p (op0, op1, 0))
6544 return build_zero_cst (TREE_TYPE (arg0));
6545 break;
6546 default:
6547 break;
6550 tree res
6551 = fold_binary_loc (loc, subcode, TREE_TYPE (arg0), op0, op1);
6552 if (res
6553 && TREE_CODE (res) == INTEGER_CST
6554 && !TREE_OVERFLOW (res))
6555 return res;
6556 return NULL_TREE;
6559 fn = (*valueize) (gimple_call_fn (stmt));
6560 if (TREE_CODE (fn) == ADDR_EXPR
6561 && fndecl_built_in_p (TREE_OPERAND (fn, 0))
6562 && gimple_builtin_call_types_compatible_p (stmt,
6563 TREE_OPERAND (fn, 0)))
6565 tree *args = XALLOCAVEC (tree, gimple_call_num_args (stmt));
6566 tree retval;
6567 unsigned i;
6568 for (i = 0; i < gimple_call_num_args (stmt); ++i)
6569 args[i] = (*valueize) (gimple_call_arg (stmt, i));
6570 retval = fold_builtin_call_array (loc,
6571 gimple_call_return_type (call_stmt),
6572 fn, gimple_call_num_args (stmt), args);
6573 if (retval)
6575 /* fold_call_expr wraps the result inside a NOP_EXPR. */
6576 STRIP_NOPS (retval);
6577 retval = fold_convert (gimple_call_return_type (call_stmt),
6578 retval);
6580 return retval;
6582 return NULL_TREE;
6585 default:
6586 return NULL_TREE;
6590 /* Fold STMT to a constant using VALUEIZE to valueize SSA names.
6591 Returns NULL_TREE if folding to a constant is not possible, otherwise
6592 returns a constant according to is_gimple_min_invariant. */
6594 tree
6595 gimple_fold_stmt_to_constant (gimple *stmt, tree (*valueize) (tree))
6597 tree res = gimple_fold_stmt_to_constant_1 (stmt, valueize);
6598 if (res && is_gimple_min_invariant (res))
6599 return res;
6600 return NULL_TREE;
6604 /* The following set of functions are supposed to fold references using
6605 their constant initializers. */
6607 /* See if we can find constructor defining value of BASE.
6608 When we know the consructor with constant offset (such as
6609 base is array[40] and we do know constructor of array), then
6610 BIT_OFFSET is adjusted accordingly.
6612 As a special case, return error_mark_node when constructor
6613 is not explicitly available, but it is known to be zero
6614 such as 'static const int a;'. */
6615 static tree
6616 get_base_constructor (tree base, poly_int64_pod *bit_offset,
6617 tree (*valueize)(tree))
6619 poly_int64 bit_offset2, size, max_size;
6620 bool reverse;
6622 if (TREE_CODE (base) == MEM_REF)
6624 poly_offset_int boff = *bit_offset + mem_ref_offset (base) * BITS_PER_UNIT;
6625 if (!boff.to_shwi (bit_offset))
6626 return NULL_TREE;
6628 if (valueize
6629 && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
6630 base = valueize (TREE_OPERAND (base, 0));
6631 if (!base || TREE_CODE (base) != ADDR_EXPR)
6632 return NULL_TREE;
6633 base = TREE_OPERAND (base, 0);
6635 else if (valueize
6636 && TREE_CODE (base) == SSA_NAME)
6637 base = valueize (base);
6639 /* Get a CONSTRUCTOR. If BASE is a VAR_DECL, get its
6640 DECL_INITIAL. If BASE is a nested reference into another
6641 ARRAY_REF or COMPONENT_REF, make a recursive call to resolve
6642 the inner reference. */
6643 switch (TREE_CODE (base))
6645 case VAR_DECL:
6646 case CONST_DECL:
6648 tree init = ctor_for_folding (base);
6650 /* Our semantic is exact opposite of ctor_for_folding;
6651 NULL means unknown, while error_mark_node is 0. */
6652 if (init == error_mark_node)
6653 return NULL_TREE;
6654 if (!init)
6655 return error_mark_node;
6656 return init;
6659 case VIEW_CONVERT_EXPR:
6660 return get_base_constructor (TREE_OPERAND (base, 0),
6661 bit_offset, valueize);
6663 case ARRAY_REF:
6664 case COMPONENT_REF:
6665 base = get_ref_base_and_extent (base, &bit_offset2, &size, &max_size,
6666 &reverse);
6667 if (!known_size_p (max_size) || maybe_ne (size, max_size))
6668 return NULL_TREE;
6669 *bit_offset += bit_offset2;
6670 return get_base_constructor (base, bit_offset, valueize);
6672 case CONSTRUCTOR:
6673 return base;
6675 default:
6676 if (CONSTANT_CLASS_P (base))
6677 return base;
6679 return NULL_TREE;
6683 /* CTOR is CONSTRUCTOR of an array type. Fold a reference of SIZE bits
6684 to the memory at bit OFFSET. When non-null, TYPE is the expected
6685 type of the reference; otherwise the type of the referenced element
6686 is used instead. When SIZE is zero, attempt to fold a reference to
6687 the entire element which OFFSET refers to. Increment *SUBOFF by
6688 the bit offset of the accessed element. */
6690 static tree
6691 fold_array_ctor_reference (tree type, tree ctor,
6692 unsigned HOST_WIDE_INT offset,
6693 unsigned HOST_WIDE_INT size,
6694 tree from_decl,
6695 unsigned HOST_WIDE_INT *suboff)
6697 offset_int low_bound;
6698 offset_int elt_size;
6699 offset_int access_index;
6700 tree domain_type = NULL_TREE;
6701 HOST_WIDE_INT inner_offset;
6703 /* Compute low bound and elt size. */
6704 if (TREE_CODE (TREE_TYPE (ctor)) == ARRAY_TYPE)
6705 domain_type = TYPE_DOMAIN (TREE_TYPE (ctor));
6706 if (domain_type && TYPE_MIN_VALUE (domain_type))
6708 /* Static constructors for variably sized objects make no sense. */
6709 if (TREE_CODE (TYPE_MIN_VALUE (domain_type)) != INTEGER_CST)
6710 return NULL_TREE;
6711 low_bound = wi::to_offset (TYPE_MIN_VALUE (domain_type));
6713 else
6714 low_bound = 0;
6715 /* Static constructors for variably sized objects make no sense. */
6716 if (TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (ctor)))) != INTEGER_CST)
6717 return NULL_TREE;
6718 elt_size = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (ctor))));
6720 /* When TYPE is non-null, verify that it specifies a constant-sized
6721 accessed not larger than size of array element. Avoid division
6722 by zero below when ELT_SIZE is zero, such as with the result of
6723 an initializer for a zero-length array or an empty struct. */
6724 if (elt_size == 0
6725 || (type
6726 && (!TYPE_SIZE_UNIT (type)
6727 || TREE_CODE (TYPE_SIZE_UNIT (type)) != INTEGER_CST
6728 || elt_size < wi::to_offset (TYPE_SIZE_UNIT (type)))))
6729 return NULL_TREE;
6731 /* Compute the array index we look for. */
6732 access_index = wi::udiv_trunc (offset_int (offset / BITS_PER_UNIT),
6733 elt_size);
6734 access_index += low_bound;
6736 /* And offset within the access. */
6737 inner_offset = offset % (elt_size.to_uhwi () * BITS_PER_UNIT);
6739 /* See if the array field is large enough to span whole access. We do not
6740 care to fold accesses spanning multiple array indexes. */
6741 if (inner_offset + size > elt_size.to_uhwi () * BITS_PER_UNIT)
6742 return NULL_TREE;
6743 if (tree val = get_array_ctor_element_at_index (ctor, access_index))
6745 if (!size && TREE_CODE (val) != CONSTRUCTOR)
6747 /* For the final reference to the entire accessed element
6748 (SIZE is zero), reset INNER_OFFSET, disegard TYPE (which
6749 may be null) in favor of the type of the element, and set
6750 SIZE to the size of the accessed element. */
6751 inner_offset = 0;
6752 type = TREE_TYPE (val);
6753 size = elt_size.to_uhwi () * BITS_PER_UNIT;
6756 *suboff += (access_index * elt_size * BITS_PER_UNIT).to_uhwi ();
6757 return fold_ctor_reference (type, val, inner_offset, size, from_decl,
6758 suboff);
6761 /* Memory not explicitly mentioned in constructor is 0 (or
6762 the reference is out of range). */
6763 return type ? build_zero_cst (type) : NULL_TREE;
6766 /* CTOR is CONSTRUCTOR of an aggregate or vector. Fold a reference
6767 of SIZE bits to the memory at bit OFFSET. When non-null, TYPE
6768 is the expected type of the reference; otherwise the type of
6769 the referenced member is used instead. When SIZE is zero,
6770 attempt to fold a reference to the entire member which OFFSET
6771 refers to; in this case. Increment *SUBOFF by the bit offset
6772 of the accessed member. */
6774 static tree
6775 fold_nonarray_ctor_reference (tree type, tree ctor,
6776 unsigned HOST_WIDE_INT offset,
6777 unsigned HOST_WIDE_INT size,
6778 tree from_decl,
6779 unsigned HOST_WIDE_INT *suboff)
6781 unsigned HOST_WIDE_INT cnt;
6782 tree cfield, cval;
6784 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), cnt, cfield,
6785 cval)
6787 tree byte_offset = DECL_FIELD_OFFSET (cfield);
6788 tree field_offset = DECL_FIELD_BIT_OFFSET (cfield);
6789 tree field_size = DECL_SIZE (cfield);
6791 if (!field_size)
6793 /* Determine the size of the flexible array member from
6794 the size of the initializer provided for it. */
6795 field_size = TYPE_SIZE (TREE_TYPE (cval));
6798 /* Variable sized objects in static constructors makes no sense,
6799 but field_size can be NULL for flexible array members. */
6800 gcc_assert (TREE_CODE (field_offset) == INTEGER_CST
6801 && TREE_CODE (byte_offset) == INTEGER_CST
6802 && (field_size != NULL_TREE
6803 ? TREE_CODE (field_size) == INTEGER_CST
6804 : TREE_CODE (TREE_TYPE (cfield)) == ARRAY_TYPE));
6806 /* Compute bit offset of the field. */
6807 offset_int bitoffset
6808 = (wi::to_offset (field_offset)
6809 + (wi::to_offset (byte_offset) << LOG2_BITS_PER_UNIT));
6810 /* Compute bit offset where the field ends. */
6811 offset_int bitoffset_end;
6812 if (field_size != NULL_TREE)
6813 bitoffset_end = bitoffset + wi::to_offset (field_size);
6814 else
6815 bitoffset_end = 0;
6817 /* Compute the bit offset of the end of the desired access.
6818 As a special case, if the size of the desired access is
6819 zero, assume the access is to the entire field (and let
6820 the caller make any necessary adjustments by storing
6821 the actual bounds of the field in FIELDBOUNDS). */
6822 offset_int access_end = offset_int (offset);
6823 if (size)
6824 access_end += size;
6825 else
6826 access_end = bitoffset_end;
6828 /* Is there any overlap between the desired access at
6829 [OFFSET, OFFSET+SIZE) and the offset of the field within
6830 the object at [BITOFFSET, BITOFFSET_END)? */
6831 if (wi::cmps (access_end, bitoffset) > 0
6832 && (field_size == NULL_TREE
6833 || wi::lts_p (offset, bitoffset_end)))
6835 *suboff += bitoffset.to_uhwi ();
6837 if (!size && TREE_CODE (cval) != CONSTRUCTOR)
6839 /* For the final reference to the entire accessed member
6840 (SIZE is zero), reset OFFSET, disegard TYPE (which may
6841 be null) in favor of the type of the member, and set
6842 SIZE to the size of the accessed member. */
6843 offset = bitoffset.to_uhwi ();
6844 type = TREE_TYPE (cval);
6845 size = (bitoffset_end - bitoffset).to_uhwi ();
6848 /* We do have overlap. Now see if the field is large enough
6849 to cover the access. Give up for accesses that extend
6850 beyond the end of the object or that span multiple fields. */
6851 if (wi::cmps (access_end, bitoffset_end) > 0)
6852 return NULL_TREE;
6853 if (offset < bitoffset)
6854 return NULL_TREE;
6856 offset_int inner_offset = offset_int (offset) - bitoffset;
6857 return fold_ctor_reference (type, cval,
6858 inner_offset.to_uhwi (), size,
6859 from_decl, suboff);
6862 /* Memory not explicitly mentioned in constructor is 0. */
6863 return type ? build_zero_cst (type) : NULL_TREE;
6866 /* CTOR is value initializing memory. Fold a reference of TYPE and
6867 bit size POLY_SIZE to the memory at bit POLY_OFFSET. When SIZE
6868 is zero, attempt to fold a reference to the entire subobject
6869 which OFFSET refers to. This is used when folding accesses to
6870 string members of aggregates. When non-null, set *SUBOFF to
6871 the bit offset of the accessed subobject. */
6873 tree
6874 fold_ctor_reference (tree type, tree ctor, const poly_uint64 &poly_offset,
6875 const poly_uint64 &poly_size, tree from_decl,
6876 unsigned HOST_WIDE_INT *suboff /* = NULL */)
6878 tree ret;
6880 /* We found the field with exact match. */
6881 if (type
6882 && useless_type_conversion_p (type, TREE_TYPE (ctor))
6883 && known_eq (poly_offset, 0U))
6884 return canonicalize_constructor_val (unshare_expr (ctor), from_decl);
6886 /* The remaining optimizations need a constant size and offset. */
6887 unsigned HOST_WIDE_INT size, offset;
6888 if (!poly_size.is_constant (&size) || !poly_offset.is_constant (&offset))
6889 return NULL_TREE;
6891 /* We are at the end of walk, see if we can view convert the
6892 result. */
6893 if (!AGGREGATE_TYPE_P (TREE_TYPE (ctor)) && !offset
6894 /* VIEW_CONVERT_EXPR is defined only for matching sizes. */
6895 && !compare_tree_int (TYPE_SIZE (type), size)
6896 && !compare_tree_int (TYPE_SIZE (TREE_TYPE (ctor)), size))
6898 ret = canonicalize_constructor_val (unshare_expr (ctor), from_decl);
6899 if (ret)
6901 ret = fold_unary (VIEW_CONVERT_EXPR, type, ret);
6902 if (ret)
6903 STRIP_USELESS_TYPE_CONVERSION (ret);
6905 return ret;
6907 /* For constants and byte-aligned/sized reads try to go through
6908 native_encode/interpret. */
6909 if (CONSTANT_CLASS_P (ctor)
6910 && BITS_PER_UNIT == 8
6911 && offset % BITS_PER_UNIT == 0
6912 && size % BITS_PER_UNIT == 0
6913 && size <= MAX_BITSIZE_MODE_ANY_MODE)
6915 unsigned char buf[MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT];
6916 int len = native_encode_expr (ctor, buf, size / BITS_PER_UNIT,
6917 offset / BITS_PER_UNIT);
6918 if (len > 0)
6919 return native_interpret_expr (type, buf, len);
6921 if (TREE_CODE (ctor) == CONSTRUCTOR)
6923 unsigned HOST_WIDE_INT dummy = 0;
6924 if (!suboff)
6925 suboff = &dummy;
6927 if (TREE_CODE (TREE_TYPE (ctor)) == ARRAY_TYPE
6928 || TREE_CODE (TREE_TYPE (ctor)) == VECTOR_TYPE)
6929 return fold_array_ctor_reference (type, ctor, offset, size,
6930 from_decl, suboff);
6932 return fold_nonarray_ctor_reference (type, ctor, offset, size,
6933 from_decl, suboff);
6936 return NULL_TREE;
6939 /* Return the tree representing the element referenced by T if T is an
6940 ARRAY_REF or COMPONENT_REF into constant aggregates valuezing SSA
6941 names using VALUEIZE. Return NULL_TREE otherwise. */
6943 tree
6944 fold_const_aggregate_ref_1 (tree t, tree (*valueize) (tree))
6946 tree ctor, idx, base;
6947 poly_int64 offset, size, max_size;
6948 tree tem;
6949 bool reverse;
6951 if (TREE_THIS_VOLATILE (t))
6952 return NULL_TREE;
6954 if (DECL_P (t))
6955 return get_symbol_constant_value (t);
6957 tem = fold_read_from_constant_string (t);
6958 if (tem)
6959 return tem;
6961 switch (TREE_CODE (t))
6963 case ARRAY_REF:
6964 case ARRAY_RANGE_REF:
6965 /* Constant indexes are handled well by get_base_constructor.
6966 Only special case variable offsets.
6967 FIXME: This code can't handle nested references with variable indexes
6968 (they will be handled only by iteration of ccp). Perhaps we can bring
6969 get_ref_base_and_extent here and make it use a valueize callback. */
6970 if (TREE_CODE (TREE_OPERAND (t, 1)) == SSA_NAME
6971 && valueize
6972 && (idx = (*valueize) (TREE_OPERAND (t, 1)))
6973 && poly_int_tree_p (idx))
6975 tree low_bound, unit_size;
6977 /* If the resulting bit-offset is constant, track it. */
6978 if ((low_bound = array_ref_low_bound (t),
6979 poly_int_tree_p (low_bound))
6980 && (unit_size = array_ref_element_size (t),
6981 tree_fits_uhwi_p (unit_size)))
6983 poly_offset_int woffset
6984 = wi::sext (wi::to_poly_offset (idx)
6985 - wi::to_poly_offset (low_bound),
6986 TYPE_PRECISION (TREE_TYPE (idx)));
6988 if (woffset.to_shwi (&offset))
6990 /* TODO: This code seems wrong, multiply then check
6991 to see if it fits. */
6992 offset *= tree_to_uhwi (unit_size);
6993 offset *= BITS_PER_UNIT;
6995 base = TREE_OPERAND (t, 0);
6996 ctor = get_base_constructor (base, &offset, valueize);
6997 /* Empty constructor. Always fold to 0. */
6998 if (ctor == error_mark_node)
6999 return build_zero_cst (TREE_TYPE (t));
7000 /* Out of bound array access. Value is undefined,
7001 but don't fold. */
7002 if (maybe_lt (offset, 0))
7003 return NULL_TREE;
7004 /* We cannot determine ctor. */
7005 if (!ctor)
7006 return NULL_TREE;
7007 return fold_ctor_reference (TREE_TYPE (t), ctor, offset,
7008 tree_to_uhwi (unit_size)
7009 * BITS_PER_UNIT,
7010 base);
7014 /* Fallthru. */
7016 case COMPONENT_REF:
7017 case BIT_FIELD_REF:
7018 case TARGET_MEM_REF:
7019 case MEM_REF:
7020 base = get_ref_base_and_extent (t, &offset, &size, &max_size, &reverse);
7021 ctor = get_base_constructor (base, &offset, valueize);
7023 /* Empty constructor. Always fold to 0. */
7024 if (ctor == error_mark_node)
7025 return build_zero_cst (TREE_TYPE (t));
7026 /* We do not know precise address. */
7027 if (!known_size_p (max_size) || maybe_ne (max_size, size))
7028 return NULL_TREE;
7029 /* We cannot determine ctor. */
7030 if (!ctor)
7031 return NULL_TREE;
7033 /* Out of bound array access. Value is undefined, but don't fold. */
7034 if (maybe_lt (offset, 0))
7035 return NULL_TREE;
7037 return fold_ctor_reference (TREE_TYPE (t), ctor, offset, size,
7038 base);
7040 case REALPART_EXPR:
7041 case IMAGPART_EXPR:
7043 tree c = fold_const_aggregate_ref_1 (TREE_OPERAND (t, 0), valueize);
7044 if (c && TREE_CODE (c) == COMPLEX_CST)
7045 return fold_build1_loc (EXPR_LOCATION (t),
7046 TREE_CODE (t), TREE_TYPE (t), c);
7047 break;
7050 default:
7051 break;
7054 return NULL_TREE;
7057 tree
7058 fold_const_aggregate_ref (tree t)
7060 return fold_const_aggregate_ref_1 (t, NULL);
7063 /* Lookup virtual method with index TOKEN in a virtual table V
7064 at OFFSET.
7065 Set CAN_REFER if non-NULL to false if method
7066 is not referable or if the virtual table is ill-formed (such as rewriten
7067 by non-C++ produced symbol). Otherwise just return NULL in that calse. */
7069 tree
7070 gimple_get_virt_method_for_vtable (HOST_WIDE_INT token,
7071 tree v,
7072 unsigned HOST_WIDE_INT offset,
7073 bool *can_refer)
7075 tree vtable = v, init, fn;
7076 unsigned HOST_WIDE_INT size;
7077 unsigned HOST_WIDE_INT elt_size, access_index;
7078 tree domain_type;
7080 if (can_refer)
7081 *can_refer = true;
7083 /* First of all double check we have virtual table. */
7084 if (!VAR_P (v) || !DECL_VIRTUAL_P (v))
7086 /* Pass down that we lost track of the target. */
7087 if (can_refer)
7088 *can_refer = false;
7089 return NULL_TREE;
7092 init = ctor_for_folding (v);
7094 /* The virtual tables should always be born with constructors
7095 and we always should assume that they are avaialble for
7096 folding. At the moment we do not stream them in all cases,
7097 but it should never happen that ctor seem unreachable. */
7098 gcc_assert (init);
7099 if (init == error_mark_node)
7101 /* Pass down that we lost track of the target. */
7102 if (can_refer)
7103 *can_refer = false;
7104 return NULL_TREE;
7106 gcc_checking_assert (TREE_CODE (TREE_TYPE (v)) == ARRAY_TYPE);
7107 size = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (TREE_TYPE (v))));
7108 offset *= BITS_PER_UNIT;
7109 offset += token * size;
7111 /* Lookup the value in the constructor that is assumed to be array.
7112 This is equivalent to
7113 fn = fold_ctor_reference (TREE_TYPE (TREE_TYPE (v)), init,
7114 offset, size, NULL);
7115 but in a constant time. We expect that frontend produced a simple
7116 array without indexed initializers. */
7118 gcc_checking_assert (TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE);
7119 domain_type = TYPE_DOMAIN (TREE_TYPE (init));
7120 gcc_checking_assert (integer_zerop (TYPE_MIN_VALUE (domain_type)));
7121 elt_size = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (init))));
7123 access_index = offset / BITS_PER_UNIT / elt_size;
7124 gcc_checking_assert (offset % (elt_size * BITS_PER_UNIT) == 0);
7126 /* The C++ FE can now produce indexed fields, and we check if the indexes
7127 match. */
7128 if (access_index < CONSTRUCTOR_NELTS (init))
7130 fn = CONSTRUCTOR_ELT (init, access_index)->value;
7131 tree idx = CONSTRUCTOR_ELT (init, access_index)->index;
7132 gcc_checking_assert (!idx || tree_to_uhwi (idx) == access_index);
7133 STRIP_NOPS (fn);
7135 else
7136 fn = NULL;
7138 /* For type inconsistent program we may end up looking up virtual method
7139 in virtual table that does not contain TOKEN entries. We may overrun
7140 the virtual table and pick up a constant or RTTI info pointer.
7141 In any case the call is undefined. */
7142 if (!fn
7143 || (TREE_CODE (fn) != ADDR_EXPR && TREE_CODE (fn) != FDESC_EXPR)
7144 || TREE_CODE (TREE_OPERAND (fn, 0)) != FUNCTION_DECL)
7145 fn = builtin_decl_implicit (BUILT_IN_UNREACHABLE);
7146 else
7148 fn = TREE_OPERAND (fn, 0);
7150 /* When cgraph node is missing and function is not public, we cannot
7151 devirtualize. This can happen in WHOPR when the actual method
7152 ends up in other partition, because we found devirtualization
7153 possibility too late. */
7154 if (!can_refer_decl_in_current_unit_p (fn, vtable))
7156 if (can_refer)
7158 *can_refer = false;
7159 return fn;
7161 return NULL_TREE;
7165 /* Make sure we create a cgraph node for functions we'll reference.
7166 They can be non-existent if the reference comes from an entry
7167 of an external vtable for example. */
7168 cgraph_node::get_create (fn);
7170 return fn;
7173 /* Return a declaration of a function which an OBJ_TYPE_REF references. TOKEN
7174 is integer form of OBJ_TYPE_REF_TOKEN of the reference expression.
7175 KNOWN_BINFO carries the binfo describing the true type of
7176 OBJ_TYPE_REF_OBJECT(REF).
7177 Set CAN_REFER if non-NULL to false if method
7178 is not referable or if the virtual table is ill-formed (such as rewriten
7179 by non-C++ produced symbol). Otherwise just return NULL in that calse. */
7181 tree
7182 gimple_get_virt_method_for_binfo (HOST_WIDE_INT token, tree known_binfo,
7183 bool *can_refer)
7185 unsigned HOST_WIDE_INT offset;
7186 tree v;
7188 v = BINFO_VTABLE (known_binfo);
7189 /* If there is no virtual methods table, leave the OBJ_TYPE_REF alone. */
7190 if (!v)
7191 return NULL_TREE;
7193 if (!vtable_pointer_value_to_vtable (v, &v, &offset))
7195 if (can_refer)
7196 *can_refer = false;
7197 return NULL_TREE;
7199 return gimple_get_virt_method_for_vtable (token, v, offset, can_refer);
7202 /* Given a pointer value T, return a simplified version of an
7203 indirection through T, or NULL_TREE if no simplification is
7204 possible. Note that the resulting type may be different from
7205 the type pointed to in the sense that it is still compatible
7206 from the langhooks point of view. */
7208 tree
7209 gimple_fold_indirect_ref (tree t)
7211 tree ptype = TREE_TYPE (t), type = TREE_TYPE (ptype);
7212 tree sub = t;
7213 tree subtype;
7215 STRIP_NOPS (sub);
7216 subtype = TREE_TYPE (sub);
7217 if (!POINTER_TYPE_P (subtype)
7218 || TYPE_REF_CAN_ALIAS_ALL (ptype))
7219 return NULL_TREE;
7221 if (TREE_CODE (sub) == ADDR_EXPR)
7223 tree op = TREE_OPERAND (sub, 0);
7224 tree optype = TREE_TYPE (op);
7225 /* *&p => p */
7226 if (useless_type_conversion_p (type, optype))
7227 return op;
7229 /* *(foo *)&fooarray => fooarray[0] */
7230 if (TREE_CODE (optype) == ARRAY_TYPE
7231 && TREE_CODE (TYPE_SIZE (TREE_TYPE (optype))) == INTEGER_CST
7232 && useless_type_conversion_p (type, TREE_TYPE (optype)))
7234 tree type_domain = TYPE_DOMAIN (optype);
7235 tree min_val = size_zero_node;
7236 if (type_domain && TYPE_MIN_VALUE (type_domain))
7237 min_val = TYPE_MIN_VALUE (type_domain);
7238 if (TREE_CODE (min_val) == INTEGER_CST)
7239 return build4 (ARRAY_REF, type, op, min_val, NULL_TREE, NULL_TREE);
7241 /* *(foo *)&complexfoo => __real__ complexfoo */
7242 else if (TREE_CODE (optype) == COMPLEX_TYPE
7243 && useless_type_conversion_p (type, TREE_TYPE (optype)))
7244 return fold_build1 (REALPART_EXPR, type, op);
7245 /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
7246 else if (TREE_CODE (optype) == VECTOR_TYPE
7247 && useless_type_conversion_p (type, TREE_TYPE (optype)))
7249 tree part_width = TYPE_SIZE (type);
7250 tree index = bitsize_int (0);
7251 return fold_build3 (BIT_FIELD_REF, type, op, part_width, index);
7255 /* *(p + CST) -> ... */
7256 if (TREE_CODE (sub) == POINTER_PLUS_EXPR
7257 && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST)
7259 tree addr = TREE_OPERAND (sub, 0);
7260 tree off = TREE_OPERAND (sub, 1);
7261 tree addrtype;
7263 STRIP_NOPS (addr);
7264 addrtype = TREE_TYPE (addr);
7266 /* ((foo*)&vectorfoo)[1] -> BIT_FIELD_REF<vectorfoo,...> */
7267 if (TREE_CODE (addr) == ADDR_EXPR
7268 && TREE_CODE (TREE_TYPE (addrtype)) == VECTOR_TYPE
7269 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (addrtype)))
7270 && tree_fits_uhwi_p (off))
7272 unsigned HOST_WIDE_INT offset = tree_to_uhwi (off);
7273 tree part_width = TYPE_SIZE (type);
7274 unsigned HOST_WIDE_INT part_widthi
7275 = tree_to_shwi (part_width) / BITS_PER_UNIT;
7276 unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT;
7277 tree index = bitsize_int (indexi);
7278 if (known_lt (offset / part_widthi,
7279 TYPE_VECTOR_SUBPARTS (TREE_TYPE (addrtype))))
7280 return fold_build3 (BIT_FIELD_REF, type, TREE_OPERAND (addr, 0),
7281 part_width, index);
7284 /* ((foo*)&complexfoo)[1] -> __imag__ complexfoo */
7285 if (TREE_CODE (addr) == ADDR_EXPR
7286 && TREE_CODE (TREE_TYPE (addrtype)) == COMPLEX_TYPE
7287 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (addrtype))))
7289 tree size = TYPE_SIZE_UNIT (type);
7290 if (tree_int_cst_equal (size, off))
7291 return fold_build1 (IMAGPART_EXPR, type, TREE_OPERAND (addr, 0));
7294 /* *(p + CST) -> MEM_REF <p, CST>. */
7295 if (TREE_CODE (addr) != ADDR_EXPR
7296 || DECL_P (TREE_OPERAND (addr, 0)))
7297 return fold_build2 (MEM_REF, type,
7298 addr,
7299 wide_int_to_tree (ptype, wi::to_wide (off)));
7302 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
7303 if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
7304 && TREE_CODE (TYPE_SIZE (TREE_TYPE (TREE_TYPE (subtype)))) == INTEGER_CST
7305 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (subtype))))
7307 tree type_domain;
7308 tree min_val = size_zero_node;
7309 tree osub = sub;
7310 sub = gimple_fold_indirect_ref (sub);
7311 if (! sub)
7312 sub = build1 (INDIRECT_REF, TREE_TYPE (subtype), osub);
7313 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
7314 if (type_domain && TYPE_MIN_VALUE (type_domain))
7315 min_val = TYPE_MIN_VALUE (type_domain);
7316 if (TREE_CODE (min_val) == INTEGER_CST)
7317 return build4 (ARRAY_REF, type, sub, min_val, NULL_TREE, NULL_TREE);
7320 return NULL_TREE;
7323 /* Return true if CODE is an operation that when operating on signed
7324 integer types involves undefined behavior on overflow and the
7325 operation can be expressed with unsigned arithmetic. */
7327 bool
7328 arith_code_with_undefined_signed_overflow (tree_code code)
7330 switch (code)
7332 case PLUS_EXPR:
7333 case MINUS_EXPR:
7334 case MULT_EXPR:
7335 case NEGATE_EXPR:
7336 case POINTER_PLUS_EXPR:
7337 return true;
7338 default:
7339 return false;
7343 /* Rewrite STMT, an assignment with a signed integer or pointer arithmetic
7344 operation that can be transformed to unsigned arithmetic by converting
7345 its operand, carrying out the operation in the corresponding unsigned
7346 type and converting the result back to the original type.
7348 Returns a sequence of statements that replace STMT and also contain
7349 a modified form of STMT itself. */
7351 gimple_seq
7352 rewrite_to_defined_overflow (gimple *stmt)
7354 if (dump_file && (dump_flags & TDF_DETAILS))
7356 fprintf (dump_file, "rewriting stmt with undefined signed "
7357 "overflow ");
7358 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
7361 tree lhs = gimple_assign_lhs (stmt);
7362 tree type = unsigned_type_for (TREE_TYPE (lhs));
7363 gimple_seq stmts = NULL;
7364 for (unsigned i = 1; i < gimple_num_ops (stmt); ++i)
7366 tree op = gimple_op (stmt, i);
7367 op = gimple_convert (&stmts, type, op);
7368 gimple_set_op (stmt, i, op);
7370 gimple_assign_set_lhs (stmt, make_ssa_name (type, stmt));
7371 if (gimple_assign_rhs_code (stmt) == POINTER_PLUS_EXPR)
7372 gimple_assign_set_rhs_code (stmt, PLUS_EXPR);
7373 gimple_seq_add_stmt (&stmts, stmt);
7374 gimple *cvt = gimple_build_assign (lhs, NOP_EXPR, gimple_assign_lhs (stmt));
7375 gimple_seq_add_stmt (&stmts, cvt);
7377 return stmts;
7381 /* The valueization hook we use for the gimple_build API simplification.
7382 This makes us match fold_buildN behavior by only combining with
7383 statements in the sequence(s) we are currently building. */
7385 static tree
7386 gimple_build_valueize (tree op)
7388 if (gimple_bb (SSA_NAME_DEF_STMT (op)) == NULL)
7389 return op;
7390 return NULL_TREE;
7393 /* Build the expression CODE OP0 of type TYPE with location LOC,
7394 simplifying it first if possible. Returns the built
7395 expression value and appends statements possibly defining it
7396 to SEQ. */
7398 tree
7399 gimple_build (gimple_seq *seq, location_t loc,
7400 enum tree_code code, tree type, tree op0)
7402 tree res = gimple_simplify (code, type, op0, seq, gimple_build_valueize);
7403 if (!res)
7405 res = create_tmp_reg_or_ssa_name (type);
7406 gimple *stmt;
7407 if (code == REALPART_EXPR
7408 || code == IMAGPART_EXPR
7409 || code == VIEW_CONVERT_EXPR)
7410 stmt = gimple_build_assign (res, code, build1 (code, type, op0));
7411 else
7412 stmt = gimple_build_assign (res, code, op0);
7413 gimple_set_location (stmt, loc);
7414 gimple_seq_add_stmt_without_update (seq, stmt);
7416 return res;
7419 /* Build the expression OP0 CODE OP1 of type TYPE with location LOC,
7420 simplifying it first if possible. Returns the built
7421 expression value and appends statements possibly defining it
7422 to SEQ. */
7424 tree
7425 gimple_build (gimple_seq *seq, location_t loc,
7426 enum tree_code code, tree type, tree op0, tree op1)
7428 tree res = gimple_simplify (code, type, op0, op1, seq, gimple_build_valueize);
7429 if (!res)
7431 res = create_tmp_reg_or_ssa_name (type);
7432 gimple *stmt = gimple_build_assign (res, code, op0, op1);
7433 gimple_set_location (stmt, loc);
7434 gimple_seq_add_stmt_without_update (seq, stmt);
7436 return res;
7439 /* Build the expression (CODE OP0 OP1 OP2) of type TYPE with location LOC,
7440 simplifying it first if possible. Returns the built
7441 expression value and appends statements possibly defining it
7442 to SEQ. */
7444 tree
7445 gimple_build (gimple_seq *seq, location_t loc,
7446 enum tree_code code, tree type, tree op0, tree op1, tree op2)
7448 tree res = gimple_simplify (code, type, op0, op1, op2,
7449 seq, gimple_build_valueize);
7450 if (!res)
7452 res = create_tmp_reg_or_ssa_name (type);
7453 gimple *stmt;
7454 if (code == BIT_FIELD_REF)
7455 stmt = gimple_build_assign (res, code,
7456 build3 (code, type, op0, op1, op2));
7457 else
7458 stmt = gimple_build_assign (res, code, op0, op1, op2);
7459 gimple_set_location (stmt, loc);
7460 gimple_seq_add_stmt_without_update (seq, stmt);
7462 return res;
7465 /* Build the call FN (ARG0) with a result of type TYPE
7466 (or no result if TYPE is void) with location LOC,
7467 simplifying it first if possible. Returns the built
7468 expression value (or NULL_TREE if TYPE is void) and appends
7469 statements possibly defining it to SEQ. */
7471 tree
7472 gimple_build (gimple_seq *seq, location_t loc, combined_fn fn,
7473 tree type, tree arg0)
7475 tree res = gimple_simplify (fn, type, arg0, seq, gimple_build_valueize);
7476 if (!res)
7478 gcall *stmt;
7479 if (internal_fn_p (fn))
7480 stmt = gimple_build_call_internal (as_internal_fn (fn), 1, arg0);
7481 else
7483 tree decl = builtin_decl_implicit (as_builtin_fn (fn));
7484 stmt = gimple_build_call (decl, 1, arg0);
7486 if (!VOID_TYPE_P (type))
7488 res = create_tmp_reg_or_ssa_name (type);
7489 gimple_call_set_lhs (stmt, res);
7491 gimple_set_location (stmt, loc);
7492 gimple_seq_add_stmt_without_update (seq, stmt);
7494 return res;
7497 /* Build the call FN (ARG0, ARG1) with a result of type TYPE
7498 (or no result if TYPE is void) with location LOC,
7499 simplifying it first if possible. Returns the built
7500 expression value (or NULL_TREE if TYPE is void) and appends
7501 statements possibly defining it to SEQ. */
7503 tree
7504 gimple_build (gimple_seq *seq, location_t loc, combined_fn fn,
7505 tree type, tree arg0, tree arg1)
7507 tree res = gimple_simplify (fn, type, arg0, arg1, seq, gimple_build_valueize);
7508 if (!res)
7510 gcall *stmt;
7511 if (internal_fn_p (fn))
7512 stmt = gimple_build_call_internal (as_internal_fn (fn), 2, arg0, arg1);
7513 else
7515 tree decl = builtin_decl_implicit (as_builtin_fn (fn));
7516 stmt = gimple_build_call (decl, 2, arg0, arg1);
7518 if (!VOID_TYPE_P (type))
7520 res = create_tmp_reg_or_ssa_name (type);
7521 gimple_call_set_lhs (stmt, res);
7523 gimple_set_location (stmt, loc);
7524 gimple_seq_add_stmt_without_update (seq, stmt);
7526 return res;
7529 /* Build the call FN (ARG0, ARG1, ARG2) with a result of type TYPE
7530 (or no result if TYPE is void) with location LOC,
7531 simplifying it first if possible. Returns the built
7532 expression value (or NULL_TREE if TYPE is void) and appends
7533 statements possibly defining it to SEQ. */
7535 tree
7536 gimple_build (gimple_seq *seq, location_t loc, combined_fn fn,
7537 tree type, tree arg0, tree arg1, tree arg2)
7539 tree res = gimple_simplify (fn, type, arg0, arg1, arg2,
7540 seq, gimple_build_valueize);
7541 if (!res)
7543 gcall *stmt;
7544 if (internal_fn_p (fn))
7545 stmt = gimple_build_call_internal (as_internal_fn (fn),
7546 3, arg0, arg1, arg2);
7547 else
7549 tree decl = builtin_decl_implicit (as_builtin_fn (fn));
7550 stmt = gimple_build_call (decl, 3, arg0, arg1, arg2);
7552 if (!VOID_TYPE_P (type))
7554 res = create_tmp_reg_or_ssa_name (type);
7555 gimple_call_set_lhs (stmt, res);
7557 gimple_set_location (stmt, loc);
7558 gimple_seq_add_stmt_without_update (seq, stmt);
7560 return res;
7563 /* Build the conversion (TYPE) OP with a result of type TYPE
7564 with location LOC if such conversion is neccesary in GIMPLE,
7565 simplifying it first.
7566 Returns the built expression value and appends
7567 statements possibly defining it to SEQ. */
7569 tree
7570 gimple_convert (gimple_seq *seq, location_t loc, tree type, tree op)
7572 if (useless_type_conversion_p (type, TREE_TYPE (op)))
7573 return op;
7574 return gimple_build (seq, loc, NOP_EXPR, type, op);
7577 /* Build the conversion (ptrofftype) OP with a result of a type
7578 compatible with ptrofftype with location LOC if such conversion
7579 is neccesary in GIMPLE, simplifying it first.
7580 Returns the built expression value and appends
7581 statements possibly defining it to SEQ. */
7583 tree
7584 gimple_convert_to_ptrofftype (gimple_seq *seq, location_t loc, tree op)
7586 if (ptrofftype_p (TREE_TYPE (op)))
7587 return op;
7588 return gimple_convert (seq, loc, sizetype, op);
7591 /* Build a vector of type TYPE in which each element has the value OP.
7592 Return a gimple value for the result, appending any new statements
7593 to SEQ. */
7595 tree
7596 gimple_build_vector_from_val (gimple_seq *seq, location_t loc, tree type,
7597 tree op)
7599 if (!TYPE_VECTOR_SUBPARTS (type).is_constant ()
7600 && !CONSTANT_CLASS_P (op))
7601 return gimple_build (seq, loc, VEC_DUPLICATE_EXPR, type, op);
7603 tree res, vec = build_vector_from_val (type, op);
7604 if (is_gimple_val (vec))
7605 return vec;
7606 if (gimple_in_ssa_p (cfun))
7607 res = make_ssa_name (type);
7608 else
7609 res = create_tmp_reg (type);
7610 gimple *stmt = gimple_build_assign (res, vec);
7611 gimple_set_location (stmt, loc);
7612 gimple_seq_add_stmt_without_update (seq, stmt);
7613 return res;
7616 /* Build a vector from BUILDER, handling the case in which some elements
7617 are non-constant. Return a gimple value for the result, appending any
7618 new instructions to SEQ.
7620 BUILDER must not have a stepped encoding on entry. This is because
7621 the function is not geared up to handle the arithmetic that would
7622 be needed in the variable case, and any code building a vector that
7623 is known to be constant should use BUILDER->build () directly. */
7625 tree
7626 gimple_build_vector (gimple_seq *seq, location_t loc,
7627 tree_vector_builder *builder)
7629 gcc_assert (builder->nelts_per_pattern () <= 2);
7630 unsigned int encoded_nelts = builder->encoded_nelts ();
7631 for (unsigned int i = 0; i < encoded_nelts; ++i)
7632 if (!TREE_CONSTANT ((*builder)[i]))
7634 tree type = builder->type ();
7635 unsigned int nelts = TYPE_VECTOR_SUBPARTS (type).to_constant ();
7636 vec<constructor_elt, va_gc> *v;
7637 vec_alloc (v, nelts);
7638 for (i = 0; i < nelts; ++i)
7639 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, builder->elt (i));
7641 tree res;
7642 if (gimple_in_ssa_p (cfun))
7643 res = make_ssa_name (type);
7644 else
7645 res = create_tmp_reg (type);
7646 gimple *stmt = gimple_build_assign (res, build_constructor (type, v));
7647 gimple_set_location (stmt, loc);
7648 gimple_seq_add_stmt_without_update (seq, stmt);
7649 return res;
7651 return builder->build ();
7654 /* Return true if the result of assignment STMT is known to be non-negative.
7655 If the return value is based on the assumption that signed overflow is
7656 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
7657 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
7659 static bool
7660 gimple_assign_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
7661 int depth)
7663 enum tree_code code = gimple_assign_rhs_code (stmt);
7664 switch (get_gimple_rhs_class (code))
7666 case GIMPLE_UNARY_RHS:
7667 return tree_unary_nonnegative_warnv_p (gimple_assign_rhs_code (stmt),
7668 gimple_expr_type (stmt),
7669 gimple_assign_rhs1 (stmt),
7670 strict_overflow_p, depth);
7671 case GIMPLE_BINARY_RHS:
7672 return tree_binary_nonnegative_warnv_p (gimple_assign_rhs_code (stmt),
7673 gimple_expr_type (stmt),
7674 gimple_assign_rhs1 (stmt),
7675 gimple_assign_rhs2 (stmt),
7676 strict_overflow_p, depth);
7677 case GIMPLE_TERNARY_RHS:
7678 return false;
7679 case GIMPLE_SINGLE_RHS:
7680 return tree_single_nonnegative_warnv_p (gimple_assign_rhs1 (stmt),
7681 strict_overflow_p, depth);
7682 case GIMPLE_INVALID_RHS:
7683 break;
7685 gcc_unreachable ();
7688 /* Return true if return value of call STMT is known to be non-negative.
7689 If the return value is based on the assumption that signed overflow is
7690 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
7691 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
7693 static bool
7694 gimple_call_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
7695 int depth)
7697 tree arg0 = gimple_call_num_args (stmt) > 0 ?
7698 gimple_call_arg (stmt, 0) : NULL_TREE;
7699 tree arg1 = gimple_call_num_args (stmt) > 1 ?
7700 gimple_call_arg (stmt, 1) : NULL_TREE;
7702 return tree_call_nonnegative_warnv_p (gimple_expr_type (stmt),
7703 gimple_call_combined_fn (stmt),
7704 arg0,
7705 arg1,
7706 strict_overflow_p, depth);
7709 /* Return true if return value of call STMT is known to be non-negative.
7710 If the return value is based on the assumption that signed overflow is
7711 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
7712 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
7714 static bool
7715 gimple_phi_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
7716 int depth)
7718 for (unsigned i = 0; i < gimple_phi_num_args (stmt); ++i)
7720 tree arg = gimple_phi_arg_def (stmt, i);
7721 if (!tree_single_nonnegative_warnv_p (arg, strict_overflow_p, depth + 1))
7722 return false;
7724 return true;
7727 /* Return true if STMT is known to compute a non-negative value.
7728 If the return value is based on the assumption that signed overflow is
7729 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
7730 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
7732 bool
7733 gimple_stmt_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
7734 int depth)
7736 switch (gimple_code (stmt))
7738 case GIMPLE_ASSIGN:
7739 return gimple_assign_nonnegative_warnv_p (stmt, strict_overflow_p,
7740 depth);
7741 case GIMPLE_CALL:
7742 return gimple_call_nonnegative_warnv_p (stmt, strict_overflow_p,
7743 depth);
7744 case GIMPLE_PHI:
7745 return gimple_phi_nonnegative_warnv_p (stmt, strict_overflow_p,
7746 depth);
7747 default:
7748 return false;
7752 /* Return true if the floating-point value computed by assignment STMT
7753 is known to have an integer value. We also allow +Inf, -Inf and NaN
7754 to be considered integer values. Return false for signaling NaN.
7756 DEPTH is the current nesting depth of the query. */
7758 static bool
7759 gimple_assign_integer_valued_real_p (gimple *stmt, int depth)
7761 enum tree_code code = gimple_assign_rhs_code (stmt);
7762 switch (get_gimple_rhs_class (code))
7764 case GIMPLE_UNARY_RHS:
7765 return integer_valued_real_unary_p (gimple_assign_rhs_code (stmt),
7766 gimple_assign_rhs1 (stmt), depth);
7767 case GIMPLE_BINARY_RHS:
7768 return integer_valued_real_binary_p (gimple_assign_rhs_code (stmt),
7769 gimple_assign_rhs1 (stmt),
7770 gimple_assign_rhs2 (stmt), depth);
7771 case GIMPLE_TERNARY_RHS:
7772 return false;
7773 case GIMPLE_SINGLE_RHS:
7774 return integer_valued_real_single_p (gimple_assign_rhs1 (stmt), depth);
7775 case GIMPLE_INVALID_RHS:
7776 break;
7778 gcc_unreachable ();
7781 /* Return true if the floating-point value computed by call STMT is known
7782 to have an integer value. We also allow +Inf, -Inf and NaN to be
7783 considered integer values. Return false for signaling NaN.
7785 DEPTH is the current nesting depth of the query. */
7787 static bool
7788 gimple_call_integer_valued_real_p (gimple *stmt, int depth)
7790 tree arg0 = (gimple_call_num_args (stmt) > 0
7791 ? gimple_call_arg (stmt, 0)
7792 : NULL_TREE);
7793 tree arg1 = (gimple_call_num_args (stmt) > 1
7794 ? gimple_call_arg (stmt, 1)
7795 : NULL_TREE);
7796 return integer_valued_real_call_p (gimple_call_combined_fn (stmt),
7797 arg0, arg1, depth);
7800 /* Return true if the floating-point result of phi STMT is known to have
7801 an integer value. We also allow +Inf, -Inf and NaN to be considered
7802 integer values. Return false for signaling NaN.
7804 DEPTH is the current nesting depth of the query. */
7806 static bool
7807 gimple_phi_integer_valued_real_p (gimple *stmt, int depth)
7809 for (unsigned i = 0; i < gimple_phi_num_args (stmt); ++i)
7811 tree arg = gimple_phi_arg_def (stmt, i);
7812 if (!integer_valued_real_single_p (arg, depth + 1))
7813 return false;
7815 return true;
7818 /* Return true if the floating-point value computed by STMT is known
7819 to have an integer value. We also allow +Inf, -Inf and NaN to be
7820 considered integer values. Return false for signaling NaN.
7822 DEPTH is the current nesting depth of the query. */
7824 bool
7825 gimple_stmt_integer_valued_real_p (gimple *stmt, int depth)
7827 switch (gimple_code (stmt))
7829 case GIMPLE_ASSIGN:
7830 return gimple_assign_integer_valued_real_p (stmt, depth);
7831 case GIMPLE_CALL:
7832 return gimple_call_integer_valued_real_p (stmt, depth);
7833 case GIMPLE_PHI:
7834 return gimple_phi_integer_valued_real_p (stmt, depth);
7835 default:
7836 return false;