gccrs: dump: Fix module dumping
[official-gcc.git] / gcc / gimple-fold.cc
blob935e800641300110b70f1e7d861bbe11ed2936be
1 /* Statement simplification on GIMPLE.
2 Copyright (C) 2010-2023 Free Software Foundation, Inc.
3 Split out from tree-ssa-ccp.cc.
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-access.h"
34 #include "gimple-ssa-warn-restrict.h"
35 #include "fold-const.h"
36 #include "stmt.h"
37 #include "expr.h"
38 #include "stor-layout.h"
39 #include "dumpfile.h"
40 #include "gimple-iterator.h"
41 #include "gimple-fold.h"
42 #include "gimplify.h"
43 #include "tree-into-ssa.h"
44 #include "tree-dfa.h"
45 #include "tree-object-size.h"
46 #include "tree-ssa.h"
47 #include "tree-ssa-propagate.h"
48 #include "ipa-utils.h"
49 #include "tree-ssa-address.h"
50 #include "langhooks.h"
51 #include "gimplify-me.h"
52 #include "dbgcnt.h"
53 #include "builtins.h"
54 #include "tree-eh.h"
55 #include "gimple-match.h"
56 #include "gomp-constants.h"
57 #include "optabs-query.h"
58 #include "omp-general.h"
59 #include "tree-cfg.h"
60 #include "fold-const-call.h"
61 #include "stringpool.h"
62 #include "attribs.h"
63 #include "asan.h"
64 #include "diagnostic-core.h"
65 #include "intl.h"
66 #include "calls.h"
67 #include "tree-vector-builder.h"
68 #include "tree-ssa-strlen.h"
69 #include "varasm.h"
70 #include "internal-fn.h"
71 #include "gimple-range.h"
73 enum strlen_range_kind {
74 /* Compute the exact constant string length. */
75 SRK_STRLEN,
76 /* Compute the maximum constant string length. */
77 SRK_STRLENMAX,
78 /* Compute a range of string lengths bounded by object sizes. When
79 the length of a string cannot be determined, consider as the upper
80 bound the size of the enclosing object the string may be a member
81 or element of. Also determine the size of the largest character
82 array the string may refer to. */
83 SRK_LENRANGE,
84 /* Determine the integer value of the argument (not string length). */
85 SRK_INT_VALUE
88 static bool
89 get_range_strlen (tree, bitmap, strlen_range_kind, c_strlen_data *, unsigned);
91 /* Return true when DECL can be referenced from current unit.
92 FROM_DECL (if non-null) specify constructor of variable DECL was taken from.
93 We can get declarations that are not possible to reference for various
94 reasons:
96 1) When analyzing C++ virtual tables.
97 C++ virtual tables do have known constructors even
98 when they are keyed to other compilation unit.
99 Those tables can contain pointers to methods and vars
100 in other units. Those methods have both STATIC and EXTERNAL
101 set.
102 2) In WHOPR mode devirtualization might lead to reference
103 to method that was partitioned elsehwere.
104 In this case we have static VAR_DECL or FUNCTION_DECL
105 that has no corresponding callgraph/varpool node
106 declaring the body.
107 3) COMDAT functions referred by external vtables that
108 we devirtualize only during final compilation stage.
109 At this time we already decided that we will not output
110 the function body and thus we can't reference the symbol
111 directly. */
113 static bool
114 can_refer_decl_in_current_unit_p (tree decl, tree from_decl)
116 varpool_node *vnode;
117 struct cgraph_node *node;
118 symtab_node *snode;
120 if (DECL_ABSTRACT_P (decl))
121 return false;
123 /* We are concerned only about static/external vars and functions. */
124 if ((!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
125 || !VAR_OR_FUNCTION_DECL_P (decl))
126 return true;
128 /* Static objects can be referred only if they are defined and not optimized
129 out yet. */
130 if (!TREE_PUBLIC (decl))
132 if (DECL_EXTERNAL (decl))
133 return false;
134 /* Before we start optimizing unreachable code we can be sure all
135 static objects are defined. */
136 if (symtab->function_flags_ready)
137 return true;
138 snode = symtab_node::get (decl);
139 if (!snode || !snode->definition)
140 return false;
141 node = dyn_cast <cgraph_node *> (snode);
142 return !node || !node->inlined_to;
145 /* We will later output the initializer, so we can refer to it.
146 So we are concerned only when DECL comes from initializer of
147 external var or var that has been optimized out. */
148 if (!from_decl
149 || !VAR_P (from_decl)
150 || (!DECL_EXTERNAL (from_decl)
151 && (vnode = varpool_node::get (from_decl)) != NULL
152 && vnode->definition)
153 || (flag_ltrans
154 && (vnode = varpool_node::get (from_decl)) != NULL
155 && vnode->in_other_partition))
156 return true;
157 /* We are folding reference from external vtable. The vtable may reffer
158 to a symbol keyed to other compilation unit. The other compilation
159 unit may be in separate DSO and the symbol may be hidden. */
160 if (DECL_VISIBILITY_SPECIFIED (decl)
161 && DECL_EXTERNAL (decl)
162 && DECL_VISIBILITY (decl) != VISIBILITY_DEFAULT
163 && (!(snode = symtab_node::get (decl)) || !snode->in_other_partition))
164 return false;
165 /* When function is public, we always can introduce new reference.
166 Exception are the COMDAT functions where introducing a direct
167 reference imply need to include function body in the curren tunit. */
168 if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl))
169 return true;
170 /* We have COMDAT. We are going to check if we still have definition
171 or if the definition is going to be output in other partition.
172 Bypass this when gimplifying; all needed functions will be produced.
174 As observed in PR20991 for already optimized out comdat virtual functions
175 it may be tempting to not necessarily give up because the copy will be
176 output elsewhere when corresponding vtable is output.
177 This is however not possible - ABI specify that COMDATs are output in
178 units where they are used and when the other unit was compiled with LTO
179 it is possible that vtable was kept public while the function itself
180 was privatized. */
181 if (!symtab->function_flags_ready)
182 return true;
184 snode = symtab_node::get (decl);
185 if (!snode
186 || ((!snode->definition || DECL_EXTERNAL (decl))
187 && (!snode->in_other_partition
188 || (!snode->forced_by_abi && !snode->force_output))))
189 return false;
190 node = dyn_cast <cgraph_node *> (snode);
191 return !node || !node->inlined_to;
194 /* Create a temporary for TYPE for a statement STMT. If the current function
195 is in SSA form, a SSA name is created. Otherwise a temporary register
196 is made. */
198 tree
199 create_tmp_reg_or_ssa_name (tree type, gimple *stmt)
201 if (gimple_in_ssa_p (cfun))
202 return make_ssa_name (type, stmt);
203 else
204 return create_tmp_reg (type);
207 /* CVAL is value taken from DECL_INITIAL of variable. Try to transform it into
208 acceptable form for is_gimple_min_invariant.
209 FROM_DECL (if non-NULL) specify variable whose constructor contains CVAL. */
211 tree
212 canonicalize_constructor_val (tree cval, tree from_decl)
214 if (CONSTANT_CLASS_P (cval))
215 return cval;
217 tree orig_cval = cval;
218 STRIP_NOPS (cval);
219 if (TREE_CODE (cval) == POINTER_PLUS_EXPR
220 && TREE_CODE (TREE_OPERAND (cval, 1)) == INTEGER_CST)
222 tree ptr = TREE_OPERAND (cval, 0);
223 if (is_gimple_min_invariant (ptr))
224 cval = build1_loc (EXPR_LOCATION (cval),
225 ADDR_EXPR, TREE_TYPE (ptr),
226 fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (ptr)),
227 ptr,
228 fold_convert (ptr_type_node,
229 TREE_OPERAND (cval, 1))));
231 if (TREE_CODE (cval) == ADDR_EXPR)
233 tree base = NULL_TREE;
234 if (TREE_CODE (TREE_OPERAND (cval, 0)) == COMPOUND_LITERAL_EXPR)
236 base = COMPOUND_LITERAL_EXPR_DECL (TREE_OPERAND (cval, 0));
237 if (base)
238 TREE_OPERAND (cval, 0) = base;
240 else
241 base = get_base_address (TREE_OPERAND (cval, 0));
242 if (!base)
243 return NULL_TREE;
245 if (VAR_OR_FUNCTION_DECL_P (base)
246 && !can_refer_decl_in_current_unit_p (base, from_decl))
247 return NULL_TREE;
248 if (TREE_TYPE (base) == error_mark_node)
249 return NULL_TREE;
250 if (VAR_P (base))
251 /* ??? We should be able to assert that TREE_ADDRESSABLE is set,
252 but since the use can be in a debug stmt we can't. */
254 else if (TREE_CODE (base) == FUNCTION_DECL)
256 /* Make sure we create a cgraph node for functions we'll reference.
257 They can be non-existent if the reference comes from an entry
258 of an external vtable for example. */
259 cgraph_node::get_create (base);
261 /* Fixup types in global initializers. */
262 if (TREE_TYPE (TREE_TYPE (cval)) != TREE_TYPE (TREE_OPERAND (cval, 0)))
263 cval = build_fold_addr_expr (TREE_OPERAND (cval, 0));
265 if (!useless_type_conversion_p (TREE_TYPE (orig_cval), TREE_TYPE (cval)))
266 cval = fold_convert (TREE_TYPE (orig_cval), cval);
267 return cval;
269 /* In CONSTRUCTORs we may see unfolded constants like (int (*) ()) 0. */
270 if (TREE_CODE (cval) == INTEGER_CST)
272 if (TREE_OVERFLOW_P (cval))
273 cval = drop_tree_overflow (cval);
274 if (!useless_type_conversion_p (TREE_TYPE (orig_cval), TREE_TYPE (cval)))
275 cval = fold_convert (TREE_TYPE (orig_cval), cval);
276 return cval;
278 return orig_cval;
281 /* If SYM is a constant variable with known value, return the value.
282 NULL_TREE is returned otherwise. */
284 tree
285 get_symbol_constant_value (tree sym)
287 tree val = ctor_for_folding (sym);
288 if (val != error_mark_node)
290 if (val)
292 val = canonicalize_constructor_val (unshare_expr (val), sym);
293 if (val
294 && is_gimple_min_invariant (val)
295 && useless_type_conversion_p (TREE_TYPE (sym), TREE_TYPE (val)))
296 return val;
297 else
298 return NULL_TREE;
300 /* Variables declared 'const' without an initializer
301 have zero as the initializer if they may not be
302 overridden at link or run time. */
303 if (!val
304 && is_gimple_reg_type (TREE_TYPE (sym)))
305 return build_zero_cst (TREE_TYPE (sym));
308 return NULL_TREE;
313 /* Subroutine of fold_stmt. We perform constant folding of the
314 memory reference tree EXPR. */
316 static tree
317 maybe_fold_reference (tree expr)
319 tree result = NULL_TREE;
321 if ((TREE_CODE (expr) == VIEW_CONVERT_EXPR
322 || TREE_CODE (expr) == REALPART_EXPR
323 || TREE_CODE (expr) == IMAGPART_EXPR)
324 && CONSTANT_CLASS_P (TREE_OPERAND (expr, 0)))
325 result = fold_unary_loc (EXPR_LOCATION (expr),
326 TREE_CODE (expr),
327 TREE_TYPE (expr),
328 TREE_OPERAND (expr, 0));
329 else if (TREE_CODE (expr) == BIT_FIELD_REF
330 && CONSTANT_CLASS_P (TREE_OPERAND (expr, 0)))
331 result = fold_ternary_loc (EXPR_LOCATION (expr),
332 TREE_CODE (expr),
333 TREE_TYPE (expr),
334 TREE_OPERAND (expr, 0),
335 TREE_OPERAND (expr, 1),
336 TREE_OPERAND (expr, 2));
337 else
338 result = fold_const_aggregate_ref (expr);
340 if (result && is_gimple_min_invariant (result))
341 return result;
343 return NULL_TREE;
346 /* Return true if EXPR is an acceptable right-hand-side for a
347 GIMPLE assignment. We validate the entire tree, not just
348 the root node, thus catching expressions that embed complex
349 operands that are not permitted in GIMPLE. This function
350 is needed because the folding routines in fold-const.cc
351 may return such expressions in some cases, e.g., an array
352 access with an embedded index addition. It may make more
353 sense to have folding routines that are sensitive to the
354 constraints on GIMPLE operands, rather than abandoning any
355 any attempt to fold if the usual folding turns out to be too
356 aggressive. */
358 bool
359 valid_gimple_rhs_p (tree expr)
361 enum tree_code code = TREE_CODE (expr);
363 switch (TREE_CODE_CLASS (code))
365 case tcc_declaration:
366 if (!is_gimple_variable (expr))
367 return false;
368 break;
370 case tcc_constant:
371 /* All constants are ok. */
372 break;
374 case tcc_comparison:
375 /* GENERIC allows comparisons with non-boolean types, reject
376 those for GIMPLE. Let vector-typed comparisons pass - rules
377 for GENERIC and GIMPLE are the same here. */
378 if (!(INTEGRAL_TYPE_P (TREE_TYPE (expr))
379 && (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE
380 || TYPE_PRECISION (TREE_TYPE (expr)) == 1))
381 && ! VECTOR_TYPE_P (TREE_TYPE (expr)))
382 return false;
384 /* Fallthru. */
385 case tcc_binary:
386 if (!is_gimple_val (TREE_OPERAND (expr, 0))
387 || !is_gimple_val (TREE_OPERAND (expr, 1)))
388 return false;
389 break;
391 case tcc_unary:
392 if (!is_gimple_val (TREE_OPERAND (expr, 0)))
393 return false;
394 break;
396 case tcc_expression:
397 switch (code)
399 case ADDR_EXPR:
401 tree t;
402 if (is_gimple_min_invariant (expr))
403 return true;
404 t = TREE_OPERAND (expr, 0);
405 while (handled_component_p (t))
407 /* ??? More checks needed, see the GIMPLE verifier. */
408 if ((TREE_CODE (t) == ARRAY_REF
409 || TREE_CODE (t) == ARRAY_RANGE_REF)
410 && !is_gimple_val (TREE_OPERAND (t, 1)))
411 return false;
412 t = TREE_OPERAND (t, 0);
414 if (!is_gimple_id (t))
415 return false;
417 break;
419 default:
420 if (get_gimple_rhs_class (code) == GIMPLE_TERNARY_RHS)
422 if (!is_gimple_val (TREE_OPERAND (expr, 0))
423 || !is_gimple_val (TREE_OPERAND (expr, 1))
424 || !is_gimple_val (TREE_OPERAND (expr, 2)))
425 return false;
426 break;
428 return false;
430 break;
432 case tcc_vl_exp:
433 return false;
435 case tcc_exceptional:
436 if (code == CONSTRUCTOR)
438 unsigned i;
439 tree elt;
440 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), i, elt)
441 if (!is_gimple_val (elt))
442 return false;
443 return true;
445 if (code != SSA_NAME)
446 return false;
447 break;
449 case tcc_reference:
450 if (code == BIT_FIELD_REF)
451 return is_gimple_val (TREE_OPERAND (expr, 0));
452 return false;
454 default:
455 return false;
458 return true;
462 /* Attempt to fold an assignment statement pointed-to by SI. Returns a
463 replacement rhs for the statement or NULL_TREE if no simplification
464 could be made. It is assumed that the operands have been previously
465 folded. */
467 static tree
468 fold_gimple_assign (gimple_stmt_iterator *si)
470 gimple *stmt = gsi_stmt (*si);
471 enum tree_code subcode = gimple_assign_rhs_code (stmt);
472 location_t loc = gimple_location (stmt);
474 tree result = NULL_TREE;
476 switch (get_gimple_rhs_class (subcode))
478 case GIMPLE_SINGLE_RHS:
480 tree rhs = gimple_assign_rhs1 (stmt);
482 if (TREE_CLOBBER_P (rhs))
483 return NULL_TREE;
485 if (REFERENCE_CLASS_P (rhs))
486 return maybe_fold_reference (rhs);
488 else if (TREE_CODE (rhs) == OBJ_TYPE_REF)
490 tree val = OBJ_TYPE_REF_EXPR (rhs);
491 if (is_gimple_min_invariant (val))
492 return val;
493 else if (flag_devirtualize && virtual_method_call_p (rhs))
495 bool final;
496 vec <cgraph_node *>targets
497 = possible_polymorphic_call_targets (rhs, stmt, &final);
498 if (final && targets.length () <= 1 && dbg_cnt (devirt))
500 if (dump_enabled_p ())
502 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, stmt,
503 "resolving virtual function address "
504 "reference to function %s\n",
505 targets.length () == 1
506 ? targets[0]->name ()
507 : "NULL");
509 if (targets.length () == 1)
511 val = fold_convert (TREE_TYPE (val),
512 build_fold_addr_expr_loc
513 (loc, targets[0]->decl));
514 STRIP_USELESS_TYPE_CONVERSION (val);
516 else
517 /* We cannot use __builtin_unreachable here because it
518 cannot have address taken. */
519 val = build_int_cst (TREE_TYPE (val), 0);
520 return val;
525 else if (TREE_CODE (rhs) == ADDR_EXPR)
527 tree ref = TREE_OPERAND (rhs, 0);
528 if (TREE_CODE (ref) == MEM_REF
529 && integer_zerop (TREE_OPERAND (ref, 1)))
531 result = TREE_OPERAND (ref, 0);
532 if (!useless_type_conversion_p (TREE_TYPE (rhs),
533 TREE_TYPE (result)))
534 result = build1 (NOP_EXPR, TREE_TYPE (rhs), result);
535 return result;
539 else if (TREE_CODE (rhs) == CONSTRUCTOR
540 && TREE_CODE (TREE_TYPE (rhs)) == VECTOR_TYPE)
542 /* Fold a constant vector CONSTRUCTOR to VECTOR_CST. */
543 unsigned i;
544 tree val;
546 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), i, val)
547 if (! CONSTANT_CLASS_P (val))
548 return NULL_TREE;
550 return build_vector_from_ctor (TREE_TYPE (rhs),
551 CONSTRUCTOR_ELTS (rhs));
554 else if (DECL_P (rhs)
555 && is_gimple_reg_type (TREE_TYPE (rhs)))
556 return get_symbol_constant_value (rhs);
558 break;
560 case GIMPLE_UNARY_RHS:
561 break;
563 case GIMPLE_BINARY_RHS:
564 break;
566 case GIMPLE_TERNARY_RHS:
567 result = fold_ternary_loc (loc, subcode,
568 TREE_TYPE (gimple_assign_lhs (stmt)),
569 gimple_assign_rhs1 (stmt),
570 gimple_assign_rhs2 (stmt),
571 gimple_assign_rhs3 (stmt));
573 if (result)
575 STRIP_USELESS_TYPE_CONVERSION (result);
576 if (valid_gimple_rhs_p (result))
577 return result;
579 break;
581 case GIMPLE_INVALID_RHS:
582 gcc_unreachable ();
585 return NULL_TREE;
589 /* Replace a statement at *SI_P with a sequence of statements in STMTS,
590 adjusting the replacement stmts location and virtual operands.
591 If the statement has a lhs the last stmt in the sequence is expected
592 to assign to that lhs. */
594 void
595 gsi_replace_with_seq_vops (gimple_stmt_iterator *si_p, gimple_seq stmts)
597 gimple *stmt = gsi_stmt (*si_p);
599 if (gimple_has_location (stmt))
600 annotate_all_with_location (stmts, gimple_location (stmt));
602 /* First iterate over the replacement statements backward, assigning
603 virtual operands to their defining statements. */
604 gimple *laststore = NULL;
605 for (gimple_stmt_iterator i = gsi_last (stmts);
606 !gsi_end_p (i); gsi_prev (&i))
608 gimple *new_stmt = gsi_stmt (i);
609 if ((gimple_assign_single_p (new_stmt)
610 && !is_gimple_reg (gimple_assign_lhs (new_stmt)))
611 || (is_gimple_call (new_stmt)
612 && (gimple_call_flags (new_stmt)
613 & (ECF_NOVOPS | ECF_PURE | ECF_CONST | ECF_NORETURN)) == 0))
615 tree vdef;
616 if (!laststore)
617 vdef = gimple_vdef (stmt);
618 else
619 vdef = make_ssa_name (gimple_vop (cfun), new_stmt);
620 gimple_set_vdef (new_stmt, vdef);
621 if (vdef && TREE_CODE (vdef) == SSA_NAME)
622 SSA_NAME_DEF_STMT (vdef) = new_stmt;
623 laststore = new_stmt;
627 /* Second iterate over the statements forward, assigning virtual
628 operands to their uses. */
629 tree reaching_vuse = gimple_vuse (stmt);
630 for (gimple_stmt_iterator i = gsi_start (stmts);
631 !gsi_end_p (i); gsi_next (&i))
633 gimple *new_stmt = gsi_stmt (i);
634 /* If the new statement possibly has a VUSE, update it with exact SSA
635 name we know will reach this one. */
636 if (gimple_has_mem_ops (new_stmt))
637 gimple_set_vuse (new_stmt, reaching_vuse);
638 gimple_set_modified (new_stmt, true);
639 if (gimple_vdef (new_stmt))
640 reaching_vuse = gimple_vdef (new_stmt);
643 /* If the new sequence does not do a store release the virtual
644 definition of the original statement. */
645 if (reaching_vuse
646 && reaching_vuse == gimple_vuse (stmt))
648 tree vdef = gimple_vdef (stmt);
649 if (vdef
650 && TREE_CODE (vdef) == SSA_NAME)
652 unlink_stmt_vdef (stmt);
653 release_ssa_name (vdef);
657 /* Finally replace the original statement with the sequence. */
658 gsi_replace_with_seq (si_p, stmts, false);
661 /* Helper function for update_gimple_call and
662 gimplify_and_update_call_from_tree. A GIMPLE_CALL STMT is being replaced
663 with GIMPLE_CALL NEW_STMT. */
665 static void
666 finish_update_gimple_call (gimple_stmt_iterator *si_p, gimple *new_stmt,
667 gimple *stmt)
669 tree lhs = gimple_call_lhs (stmt);
670 gimple_call_set_lhs (new_stmt, lhs);
671 if (lhs && TREE_CODE (lhs) == SSA_NAME)
672 SSA_NAME_DEF_STMT (lhs) = new_stmt;
673 gimple_move_vops (new_stmt, stmt);
674 gimple_set_location (new_stmt, gimple_location (stmt));
675 if (gimple_block (new_stmt) == NULL_TREE)
676 gimple_set_block (new_stmt, gimple_block (stmt));
677 gsi_replace (si_p, new_stmt, false);
680 /* Update a GIMPLE_CALL statement at iterator *SI_P to call to FN
681 with number of arguments NARGS, where the arguments in GIMPLE form
682 follow NARGS argument. */
684 bool
685 update_gimple_call (gimple_stmt_iterator *si_p, tree fn, int nargs, ...)
687 va_list ap;
688 gcall *new_stmt, *stmt = as_a <gcall *> (gsi_stmt (*si_p));
690 gcc_assert (is_gimple_call (stmt));
691 va_start (ap, nargs);
692 new_stmt = gimple_build_call_valist (fn, nargs, ap);
693 finish_update_gimple_call (si_p, new_stmt, stmt);
694 va_end (ap);
695 return true;
698 /* Return true if EXPR is a CALL_EXPR suitable for representation
699 as a single GIMPLE_CALL statement. If the arguments require
700 further gimplification, return false. */
702 static bool
703 valid_gimple_call_p (tree expr)
705 unsigned i, nargs;
707 if (TREE_CODE (expr) != CALL_EXPR)
708 return false;
710 nargs = call_expr_nargs (expr);
711 for (i = 0; i < nargs; i++)
713 tree arg = CALL_EXPR_ARG (expr, i);
714 if (is_gimple_reg_type (TREE_TYPE (arg)))
716 if (!is_gimple_val (arg))
717 return false;
719 else
720 if (!is_gimple_lvalue (arg))
721 return false;
724 return true;
727 /* Convert EXPR into a GIMPLE value suitable for substitution on the
728 RHS of an assignment. Insert the necessary statements before
729 iterator *SI_P. The statement at *SI_P, which must be a GIMPLE_CALL
730 is replaced. If the call is expected to produces a result, then it
731 is replaced by an assignment of the new RHS to the result variable.
732 If the result is to be ignored, then the call is replaced by a
733 GIMPLE_NOP. A proper VDEF chain is retained by making the first
734 VUSE and the last VDEF of the whole sequence be the same as the replaced
735 statement and using new SSA names for stores in between. */
737 void
738 gimplify_and_update_call_from_tree (gimple_stmt_iterator *si_p, tree expr)
740 tree lhs;
741 gimple *stmt, *new_stmt;
742 gimple_stmt_iterator i;
743 gimple_seq stmts = NULL;
745 stmt = gsi_stmt (*si_p);
747 gcc_assert (is_gimple_call (stmt));
749 if (valid_gimple_call_p (expr))
751 /* The call has simplified to another call. */
752 tree fn = CALL_EXPR_FN (expr);
753 unsigned i;
754 unsigned nargs = call_expr_nargs (expr);
755 vec<tree> args = vNULL;
756 gcall *new_stmt;
758 if (nargs > 0)
760 args.create (nargs);
761 args.safe_grow_cleared (nargs, true);
763 for (i = 0; i < nargs; i++)
764 args[i] = CALL_EXPR_ARG (expr, i);
767 new_stmt = gimple_build_call_vec (fn, args);
768 finish_update_gimple_call (si_p, new_stmt, stmt);
769 args.release ();
770 return;
773 lhs = gimple_call_lhs (stmt);
774 if (lhs == NULL_TREE)
776 push_gimplify_context (gimple_in_ssa_p (cfun));
777 gimplify_and_add (expr, &stmts);
778 pop_gimplify_context (NULL);
780 /* We can end up with folding a memcpy of an empty class assignment
781 which gets optimized away by C++ gimplification. */
782 if (gimple_seq_empty_p (stmts))
784 if (gimple_in_ssa_p (cfun))
786 unlink_stmt_vdef (stmt);
787 release_defs (stmt);
789 gsi_replace (si_p, gimple_build_nop (), false);
790 return;
793 else
795 tree tmp = force_gimple_operand (expr, &stmts, false, NULL_TREE);
796 new_stmt = gimple_build_assign (lhs, tmp);
797 i = gsi_last (stmts);
798 gsi_insert_after_without_update (&i, new_stmt,
799 GSI_CONTINUE_LINKING);
802 gsi_replace_with_seq_vops (si_p, stmts);
806 /* Replace the call at *GSI with the gimple value VAL. */
808 void
809 replace_call_with_value (gimple_stmt_iterator *gsi, tree val)
811 gimple *stmt = gsi_stmt (*gsi);
812 tree lhs = gimple_call_lhs (stmt);
813 gimple *repl;
814 if (lhs)
816 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (val)))
817 val = fold_convert (TREE_TYPE (lhs), val);
818 repl = gimple_build_assign (lhs, val);
820 else
821 repl = gimple_build_nop ();
822 tree vdef = gimple_vdef (stmt);
823 if (vdef && TREE_CODE (vdef) == SSA_NAME)
825 unlink_stmt_vdef (stmt);
826 release_ssa_name (vdef);
828 gsi_replace (gsi, repl, false);
831 /* Replace the call at *GSI with the new call REPL and fold that
832 again. */
834 static void
835 replace_call_with_call_and_fold (gimple_stmt_iterator *gsi, gimple *repl)
837 gimple *stmt = gsi_stmt (*gsi);
838 gimple_call_set_lhs (repl, gimple_call_lhs (stmt));
839 gimple_set_location (repl, gimple_location (stmt));
840 gimple_move_vops (repl, stmt);
841 gsi_replace (gsi, repl, false);
842 fold_stmt (gsi);
845 /* Return true if VAR is a VAR_DECL or a component thereof. */
847 static bool
848 var_decl_component_p (tree var)
850 tree inner = var;
851 while (handled_component_p (inner))
852 inner = TREE_OPERAND (inner, 0);
853 return (DECL_P (inner)
854 || (TREE_CODE (inner) == MEM_REF
855 && TREE_CODE (TREE_OPERAND (inner, 0)) == ADDR_EXPR));
858 /* Return TRUE if the SIZE argument, representing the size of an
859 object, is in a range of values of which exactly zero is valid. */
861 static bool
862 size_must_be_zero_p (tree size)
864 if (integer_zerop (size))
865 return true;
867 if (TREE_CODE (size) != SSA_NAME || !INTEGRAL_TYPE_P (TREE_TYPE (size)))
868 return false;
870 tree type = TREE_TYPE (size);
871 int prec = TYPE_PRECISION (type);
873 /* Compute the value of SSIZE_MAX, the largest positive value that
874 can be stored in ssize_t, the signed counterpart of size_t. */
875 wide_int ssize_max = wi::lshift (wi::one (prec), prec - 1) - 1;
876 value_range valid_range (build_int_cst (type, 0),
877 wide_int_to_tree (type, ssize_max));
878 value_range vr;
879 if (cfun)
880 get_range_query (cfun)->range_of_expr (vr, size);
881 else
882 get_global_range_query ()->range_of_expr (vr, size);
883 if (vr.undefined_p ())
884 vr.set_varying (TREE_TYPE (size));
885 vr.intersect (valid_range);
886 return vr.zero_p ();
889 /* Fold function call to builtin mem{{,p}cpy,move}. Try to detect and
890 diagnose (otherwise undefined) overlapping copies without preventing
891 folding. When folded, GCC guarantees that overlapping memcpy has
892 the same semantics as memmove. Call to the library memcpy need not
893 provide the same guarantee. Return false if no simplification can
894 be made. */
896 static bool
897 gimple_fold_builtin_memory_op (gimple_stmt_iterator *gsi,
898 tree dest, tree src, enum built_in_function code)
900 gimple *stmt = gsi_stmt (*gsi);
901 tree lhs = gimple_call_lhs (stmt);
902 tree len = gimple_call_arg (stmt, 2);
903 location_t loc = gimple_location (stmt);
905 /* If the LEN parameter is a constant zero or in range where
906 the only valid value is zero, return DEST. */
907 if (size_must_be_zero_p (len))
909 gimple *repl;
910 if (gimple_call_lhs (stmt))
911 repl = gimple_build_assign (gimple_call_lhs (stmt), dest);
912 else
913 repl = gimple_build_nop ();
914 tree vdef = gimple_vdef (stmt);
915 if (vdef && TREE_CODE (vdef) == SSA_NAME)
917 unlink_stmt_vdef (stmt);
918 release_ssa_name (vdef);
920 gsi_replace (gsi, repl, false);
921 return true;
924 /* If SRC and DEST are the same (and not volatile), return
925 DEST{,+LEN,+LEN-1}. */
926 if (operand_equal_p (src, dest, 0))
928 /* Avoid diagnosing exact overlap in calls to __builtin_memcpy.
929 It's safe and may even be emitted by GCC itself (see bug
930 32667). */
931 unlink_stmt_vdef (stmt);
932 if (gimple_vdef (stmt) && TREE_CODE (gimple_vdef (stmt)) == SSA_NAME)
933 release_ssa_name (gimple_vdef (stmt));
934 if (!lhs)
936 gsi_replace (gsi, gimple_build_nop (), false);
937 return true;
939 goto done;
941 else
943 /* We cannot (easily) change the type of the copy if it is a storage
944 order barrier, i.e. is equivalent to a VIEW_CONVERT_EXPR that can
945 modify the storage order of objects (see storage_order_barrier_p). */
946 tree srctype
947 = POINTER_TYPE_P (TREE_TYPE (src))
948 ? TREE_TYPE (TREE_TYPE (src)) : NULL_TREE;
949 tree desttype
950 = POINTER_TYPE_P (TREE_TYPE (dest))
951 ? TREE_TYPE (TREE_TYPE (dest)) : NULL_TREE;
952 tree destvar, srcvar, srcoff;
953 unsigned int src_align, dest_align;
954 unsigned HOST_WIDE_INT tmp_len;
955 const char *tmp_str;
957 /* Build accesses at offset zero with a ref-all character type. */
958 tree off0
959 = build_int_cst (build_pointer_type_for_mode (char_type_node,
960 ptr_mode, true), 0);
962 /* If we can perform the copy efficiently with first doing all loads
963 and then all stores inline it that way. Currently efficiently
964 means that we can load all the memory into a single integer
965 register which is what MOVE_MAX gives us. */
966 src_align = get_pointer_alignment (src);
967 dest_align = get_pointer_alignment (dest);
968 if (tree_fits_uhwi_p (len)
969 && compare_tree_int (len, MOVE_MAX) <= 0
970 /* FIXME: Don't transform copies from strings with known length.
971 Until GCC 9 this prevented a case in gcc.dg/strlenopt-8.c
972 from being handled, and the case was XFAILed for that reason.
973 Now that it is handled and the XFAIL removed, as soon as other
974 strlenopt tests that rely on it for passing are adjusted, this
975 hack can be removed. */
976 && !c_strlen (src, 1)
977 && !((tmp_str = getbyterep (src, &tmp_len)) != NULL
978 && memchr (tmp_str, 0, tmp_len) == NULL)
979 && !(srctype
980 && AGGREGATE_TYPE_P (srctype)
981 && TYPE_REVERSE_STORAGE_ORDER (srctype))
982 && !(desttype
983 && AGGREGATE_TYPE_P (desttype)
984 && TYPE_REVERSE_STORAGE_ORDER (desttype)))
986 unsigned ilen = tree_to_uhwi (len);
987 if (pow2p_hwi (ilen))
989 /* Detect out-of-bounds accesses without issuing warnings.
990 Avoid folding out-of-bounds copies but to avoid false
991 positives for unreachable code defer warning until after
992 DCE has worked its magic.
993 -Wrestrict is still diagnosed. */
994 if (int warning = check_bounds_or_overlap (as_a <gcall *>(stmt),
995 dest, src, len, len,
996 false, false))
997 if (warning != OPT_Wrestrict)
998 return false;
1000 scalar_int_mode mode;
1001 if (int_mode_for_size (ilen * 8, 0).exists (&mode)
1002 && GET_MODE_SIZE (mode) * BITS_PER_UNIT == ilen * 8
1003 /* If the destination pointer is not aligned we must be able
1004 to emit an unaligned store. */
1005 && (dest_align >= GET_MODE_ALIGNMENT (mode)
1006 || !targetm.slow_unaligned_access (mode, dest_align)
1007 || (optab_handler (movmisalign_optab, mode)
1008 != CODE_FOR_nothing)))
1010 tree type = build_nonstandard_integer_type (ilen * 8, 1);
1011 tree srctype = type;
1012 tree desttype = type;
1013 if (src_align < GET_MODE_ALIGNMENT (mode))
1014 srctype = build_aligned_type (type, src_align);
1015 tree srcmem = fold_build2 (MEM_REF, srctype, src, off0);
1016 tree tem = fold_const_aggregate_ref (srcmem);
1017 if (tem)
1018 srcmem = tem;
1019 else if (src_align < GET_MODE_ALIGNMENT (mode)
1020 && targetm.slow_unaligned_access (mode, src_align)
1021 && (optab_handler (movmisalign_optab, mode)
1022 == CODE_FOR_nothing))
1023 srcmem = NULL_TREE;
1024 if (srcmem)
1026 gimple *new_stmt;
1027 if (is_gimple_reg_type (TREE_TYPE (srcmem)))
1029 new_stmt = gimple_build_assign (NULL_TREE, srcmem);
1030 srcmem
1031 = create_tmp_reg_or_ssa_name (TREE_TYPE (srcmem),
1032 new_stmt);
1033 gimple_assign_set_lhs (new_stmt, srcmem);
1034 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
1035 gimple_set_location (new_stmt, loc);
1036 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1038 if (dest_align < GET_MODE_ALIGNMENT (mode))
1039 desttype = build_aligned_type (type, dest_align);
1040 new_stmt
1041 = gimple_build_assign (fold_build2 (MEM_REF, desttype,
1042 dest, off0),
1043 srcmem);
1044 gimple_move_vops (new_stmt, stmt);
1045 if (!lhs)
1047 gsi_replace (gsi, new_stmt, false);
1048 return true;
1050 gimple_set_location (new_stmt, loc);
1051 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1052 goto done;
1058 if (code == BUILT_IN_MEMMOVE)
1060 /* Both DEST and SRC must be pointer types.
1061 ??? This is what old code did. Is the testing for pointer types
1062 really mandatory?
1064 If either SRC is readonly or length is 1, we can use memcpy. */
1065 if (!dest_align || !src_align)
1066 return false;
1067 if (readonly_data_expr (src)
1068 || (tree_fits_uhwi_p (len)
1069 && (MIN (src_align, dest_align) / BITS_PER_UNIT
1070 >= tree_to_uhwi (len))))
1072 tree fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1073 if (!fn)
1074 return false;
1075 gimple_call_set_fndecl (stmt, fn);
1076 gimple_call_set_arg (stmt, 0, dest);
1077 gimple_call_set_arg (stmt, 1, src);
1078 fold_stmt (gsi);
1079 return true;
1082 /* If *src and *dest can't overlap, optimize into memcpy as well. */
1083 if (TREE_CODE (src) == ADDR_EXPR
1084 && TREE_CODE (dest) == ADDR_EXPR)
1086 tree src_base, dest_base, fn;
1087 poly_int64 src_offset = 0, dest_offset = 0;
1088 poly_uint64 maxsize;
1090 srcvar = TREE_OPERAND (src, 0);
1091 src_base = get_addr_base_and_unit_offset (srcvar, &src_offset);
1092 if (src_base == NULL)
1093 src_base = srcvar;
1094 destvar = TREE_OPERAND (dest, 0);
1095 dest_base = get_addr_base_and_unit_offset (destvar,
1096 &dest_offset);
1097 if (dest_base == NULL)
1098 dest_base = destvar;
1099 if (!poly_int_tree_p (len, &maxsize))
1100 maxsize = -1;
1101 if (SSA_VAR_P (src_base)
1102 && SSA_VAR_P (dest_base))
1104 if (operand_equal_p (src_base, dest_base, 0)
1105 && ranges_maybe_overlap_p (src_offset, maxsize,
1106 dest_offset, maxsize))
1107 return false;
1109 else if (TREE_CODE (src_base) == MEM_REF
1110 && TREE_CODE (dest_base) == MEM_REF)
1112 if (! operand_equal_p (TREE_OPERAND (src_base, 0),
1113 TREE_OPERAND (dest_base, 0), 0))
1114 return false;
1115 poly_offset_int full_src_offset
1116 = mem_ref_offset (src_base) + src_offset;
1117 poly_offset_int full_dest_offset
1118 = mem_ref_offset (dest_base) + dest_offset;
1119 if (ranges_maybe_overlap_p (full_src_offset, maxsize,
1120 full_dest_offset, maxsize))
1121 return false;
1123 else
1124 return false;
1126 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1127 if (!fn)
1128 return false;
1129 gimple_call_set_fndecl (stmt, fn);
1130 gimple_call_set_arg (stmt, 0, dest);
1131 gimple_call_set_arg (stmt, 1, src);
1132 fold_stmt (gsi);
1133 return true;
1136 /* If the destination and source do not alias optimize into
1137 memcpy as well. */
1138 if ((is_gimple_min_invariant (dest)
1139 || TREE_CODE (dest) == SSA_NAME)
1140 && (is_gimple_min_invariant (src)
1141 || TREE_CODE (src) == SSA_NAME))
1143 ao_ref destr, srcr;
1144 ao_ref_init_from_ptr_and_size (&destr, dest, len);
1145 ao_ref_init_from_ptr_and_size (&srcr, src, len);
1146 if (!refs_may_alias_p_1 (&destr, &srcr, false))
1148 tree fn;
1149 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1150 if (!fn)
1151 return false;
1152 gimple_call_set_fndecl (stmt, fn);
1153 gimple_call_set_arg (stmt, 0, dest);
1154 gimple_call_set_arg (stmt, 1, src);
1155 fold_stmt (gsi);
1156 return true;
1160 return false;
1163 if (!tree_fits_shwi_p (len))
1164 return false;
1165 if (!srctype
1166 || (AGGREGATE_TYPE_P (srctype)
1167 && TYPE_REVERSE_STORAGE_ORDER (srctype)))
1168 return false;
1169 if (!desttype
1170 || (AGGREGATE_TYPE_P (desttype)
1171 && TYPE_REVERSE_STORAGE_ORDER (desttype)))
1172 return false;
1173 /* In the following try to find a type that is most natural to be
1174 used for the memcpy source and destination and that allows
1175 the most optimization when memcpy is turned into a plain assignment
1176 using that type. In theory we could always use a char[len] type
1177 but that only gains us that the destination and source possibly
1178 no longer will have their address taken. */
1179 if (TREE_CODE (srctype) == ARRAY_TYPE
1180 && !tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
1181 srctype = TREE_TYPE (srctype);
1182 if (TREE_CODE (desttype) == ARRAY_TYPE
1183 && !tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
1184 desttype = TREE_TYPE (desttype);
1185 if (TREE_ADDRESSABLE (srctype)
1186 || TREE_ADDRESSABLE (desttype))
1187 return false;
1189 /* Make sure we are not copying using a floating-point mode or
1190 a type whose size possibly does not match its precision. */
1191 if (FLOAT_MODE_P (TYPE_MODE (desttype))
1192 || TREE_CODE (desttype) == BOOLEAN_TYPE
1193 || TREE_CODE (desttype) == ENUMERAL_TYPE)
1194 desttype = bitwise_type_for_mode (TYPE_MODE (desttype));
1195 if (FLOAT_MODE_P (TYPE_MODE (srctype))
1196 || TREE_CODE (srctype) == BOOLEAN_TYPE
1197 || TREE_CODE (srctype) == ENUMERAL_TYPE)
1198 srctype = bitwise_type_for_mode (TYPE_MODE (srctype));
1199 if (!srctype)
1200 srctype = desttype;
1201 if (!desttype)
1202 desttype = srctype;
1203 if (!srctype)
1204 return false;
1206 src_align = get_pointer_alignment (src);
1207 dest_align = get_pointer_alignment (dest);
1209 /* Choose between src and destination type for the access based
1210 on alignment, whether the access constitutes a register access
1211 and whether it may actually expose a declaration for SSA rewrite
1212 or SRA decomposition. Also try to expose a string constant, we
1213 might be able to concatenate several of them later into a single
1214 string store. */
1215 destvar = NULL_TREE;
1216 srcvar = NULL_TREE;
1217 if (TREE_CODE (dest) == ADDR_EXPR
1218 && var_decl_component_p (TREE_OPERAND (dest, 0))
1219 && tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len)
1220 && dest_align >= TYPE_ALIGN (desttype)
1221 && (is_gimple_reg_type (desttype)
1222 || src_align >= TYPE_ALIGN (desttype)))
1223 destvar = fold_build2 (MEM_REF, desttype, dest, off0);
1224 else if (TREE_CODE (src) == ADDR_EXPR
1225 && var_decl_component_p (TREE_OPERAND (src, 0))
1226 && tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len)
1227 && src_align >= TYPE_ALIGN (srctype)
1228 && (is_gimple_reg_type (srctype)
1229 || dest_align >= TYPE_ALIGN (srctype)))
1230 srcvar = fold_build2 (MEM_REF, srctype, src, off0);
1231 /* FIXME: Don't transform copies from strings with known original length.
1232 As soon as strlenopt tests that rely on it for passing are adjusted,
1233 this hack can be removed. */
1234 else if (gimple_call_alloca_for_var_p (stmt)
1235 && (srcvar = string_constant (src, &srcoff, NULL, NULL))
1236 && integer_zerop (srcoff)
1237 && tree_int_cst_equal (TYPE_SIZE_UNIT (TREE_TYPE (srcvar)), len)
1238 && dest_align >= TYPE_ALIGN (TREE_TYPE (srcvar)))
1239 srctype = TREE_TYPE (srcvar);
1240 else
1241 return false;
1243 /* Now that we chose an access type express the other side in
1244 terms of it if the target allows that with respect to alignment
1245 constraints. */
1246 if (srcvar == NULL_TREE)
1248 if (src_align >= TYPE_ALIGN (desttype))
1249 srcvar = fold_build2 (MEM_REF, desttype, src, off0);
1250 else
1252 enum machine_mode mode = TYPE_MODE (desttype);
1253 if ((mode == BLKmode && STRICT_ALIGNMENT)
1254 || (targetm.slow_unaligned_access (mode, src_align)
1255 && (optab_handler (movmisalign_optab, mode)
1256 == CODE_FOR_nothing)))
1257 return false;
1258 srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
1259 src_align);
1260 srcvar = fold_build2 (MEM_REF, srctype, src, off0);
1263 else if (destvar == NULL_TREE)
1265 if (dest_align >= TYPE_ALIGN (srctype))
1266 destvar = fold_build2 (MEM_REF, srctype, dest, off0);
1267 else
1269 enum machine_mode mode = TYPE_MODE (srctype);
1270 if ((mode == BLKmode && STRICT_ALIGNMENT)
1271 || (targetm.slow_unaligned_access (mode, dest_align)
1272 && (optab_handler (movmisalign_optab, mode)
1273 == CODE_FOR_nothing)))
1274 return false;
1275 desttype = build_aligned_type (TYPE_MAIN_VARIANT (srctype),
1276 dest_align);
1277 destvar = fold_build2 (MEM_REF, desttype, dest, off0);
1281 /* Same as above, detect out-of-bounds accesses without issuing
1282 warnings. Avoid folding out-of-bounds copies but to avoid
1283 false positives for unreachable code defer warning until
1284 after DCE has worked its magic.
1285 -Wrestrict is still diagnosed. */
1286 if (int warning = check_bounds_or_overlap (as_a <gcall *>(stmt),
1287 dest, src, len, len,
1288 false, false))
1289 if (warning != OPT_Wrestrict)
1290 return false;
1292 gimple *new_stmt;
1293 if (is_gimple_reg_type (TREE_TYPE (srcvar)))
1295 tree tem = fold_const_aggregate_ref (srcvar);
1296 if (tem)
1297 srcvar = tem;
1298 if (! is_gimple_min_invariant (srcvar))
1300 new_stmt = gimple_build_assign (NULL_TREE, srcvar);
1301 srcvar = create_tmp_reg_or_ssa_name (TREE_TYPE (srcvar),
1302 new_stmt);
1303 gimple_assign_set_lhs (new_stmt, srcvar);
1304 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
1305 gimple_set_location (new_stmt, loc);
1306 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1308 new_stmt = gimple_build_assign (destvar, srcvar);
1309 goto set_vop_and_replace;
1312 /* We get an aggregate copy. If the source is a STRING_CST, then
1313 directly use its type to perform the copy. */
1314 if (TREE_CODE (srcvar) == STRING_CST)
1315 desttype = srctype;
1317 /* Or else, use an unsigned char[] type to perform the copy in order
1318 to preserve padding and to avoid any issues with TREE_ADDRESSABLE
1319 types or float modes behavior on copying. */
1320 else
1322 desttype = build_array_type_nelts (unsigned_char_type_node,
1323 tree_to_uhwi (len));
1324 srctype = desttype;
1325 if (src_align > TYPE_ALIGN (srctype))
1326 srctype = build_aligned_type (srctype, src_align);
1327 srcvar = fold_build2 (MEM_REF, srctype, src, off0);
1330 if (dest_align > TYPE_ALIGN (desttype))
1331 desttype = build_aligned_type (desttype, dest_align);
1332 destvar = fold_build2 (MEM_REF, desttype, dest, off0);
1333 new_stmt = gimple_build_assign (destvar, srcvar);
1335 set_vop_and_replace:
1336 gimple_move_vops (new_stmt, stmt);
1337 if (!lhs)
1339 gsi_replace (gsi, new_stmt, false);
1340 return true;
1342 gimple_set_location (new_stmt, loc);
1343 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1346 done:
1347 gimple_seq stmts = NULL;
1348 if (code == BUILT_IN_MEMCPY || code == BUILT_IN_MEMMOVE)
1349 len = NULL_TREE;
1350 else if (code == BUILT_IN_MEMPCPY)
1352 len = gimple_convert_to_ptrofftype (&stmts, loc, len);
1353 dest = gimple_build (&stmts, loc, POINTER_PLUS_EXPR,
1354 TREE_TYPE (dest), dest, len);
1356 else
1357 gcc_unreachable ();
1359 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
1360 gimple *repl = gimple_build_assign (lhs, dest);
1361 gsi_replace (gsi, repl, false);
1362 return true;
1365 /* Transform a call to built-in bcmp(a, b, len) at *GSI into one
1366 to built-in memcmp (a, b, len). */
1368 static bool
1369 gimple_fold_builtin_bcmp (gimple_stmt_iterator *gsi)
1371 tree fn = builtin_decl_implicit (BUILT_IN_MEMCMP);
1373 if (!fn)
1374 return false;
1376 /* Transform bcmp (a, b, len) into memcmp (a, b, len). */
1378 gimple *stmt = gsi_stmt (*gsi);
1379 tree a = gimple_call_arg (stmt, 0);
1380 tree b = gimple_call_arg (stmt, 1);
1381 tree len = gimple_call_arg (stmt, 2);
1383 gimple *repl = gimple_build_call (fn, 3, a, b, len);
1384 replace_call_with_call_and_fold (gsi, repl);
1386 return true;
1389 /* Transform a call to built-in bcopy (src, dest, len) at *GSI into one
1390 to built-in memmove (dest, src, len). */
1392 static bool
1393 gimple_fold_builtin_bcopy (gimple_stmt_iterator *gsi)
1395 tree fn = builtin_decl_implicit (BUILT_IN_MEMMOVE);
1397 if (!fn)
1398 return false;
1400 /* bcopy has been removed from POSIX in Issue 7 but Issue 6 specifies
1401 it's quivalent to memmove (not memcpy). Transform bcopy (src, dest,
1402 len) into memmove (dest, src, len). */
1404 gimple *stmt = gsi_stmt (*gsi);
1405 tree src = gimple_call_arg (stmt, 0);
1406 tree dest = gimple_call_arg (stmt, 1);
1407 tree len = gimple_call_arg (stmt, 2);
1409 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
1410 gimple_call_set_fntype (as_a <gcall *> (stmt), TREE_TYPE (fn));
1411 replace_call_with_call_and_fold (gsi, repl);
1413 return true;
1416 /* Transform a call to built-in bzero (dest, len) at *GSI into one
1417 to built-in memset (dest, 0, len). */
1419 static bool
1420 gimple_fold_builtin_bzero (gimple_stmt_iterator *gsi)
1422 tree fn = builtin_decl_implicit (BUILT_IN_MEMSET);
1424 if (!fn)
1425 return false;
1427 /* Transform bzero (dest, len) into memset (dest, 0, len). */
1429 gimple *stmt = gsi_stmt (*gsi);
1430 tree dest = gimple_call_arg (stmt, 0);
1431 tree len = gimple_call_arg (stmt, 1);
1433 gimple_seq seq = NULL;
1434 gimple *repl = gimple_build_call (fn, 3, dest, integer_zero_node, len);
1435 gimple_seq_add_stmt_without_update (&seq, repl);
1436 gsi_replace_with_seq_vops (gsi, seq);
1437 fold_stmt (gsi);
1439 return true;
1442 /* Fold function call to builtin memset or bzero at *GSI setting the
1443 memory of size LEN to VAL. Return whether a simplification was made. */
1445 static bool
1446 gimple_fold_builtin_memset (gimple_stmt_iterator *gsi, tree c, tree len)
1448 gimple *stmt = gsi_stmt (*gsi);
1449 tree etype;
1450 unsigned HOST_WIDE_INT length, cval;
1452 /* If the LEN parameter is zero, return DEST. */
1453 if (integer_zerop (len))
1455 replace_call_with_value (gsi, gimple_call_arg (stmt, 0));
1456 return true;
1459 if (! tree_fits_uhwi_p (len))
1460 return false;
1462 if (TREE_CODE (c) != INTEGER_CST)
1463 return false;
1465 tree dest = gimple_call_arg (stmt, 0);
1466 tree var = dest;
1467 if (TREE_CODE (var) != ADDR_EXPR)
1468 return false;
1470 var = TREE_OPERAND (var, 0);
1471 if (TREE_THIS_VOLATILE (var))
1472 return false;
1474 etype = TREE_TYPE (var);
1475 if (TREE_CODE (etype) == ARRAY_TYPE)
1476 etype = TREE_TYPE (etype);
1478 if (!INTEGRAL_TYPE_P (etype)
1479 && !POINTER_TYPE_P (etype))
1480 return NULL_TREE;
1482 if (! var_decl_component_p (var))
1483 return NULL_TREE;
1485 length = tree_to_uhwi (len);
1486 if (GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (etype)) != length
1487 || (GET_MODE_PRECISION (SCALAR_INT_TYPE_MODE (etype))
1488 != GET_MODE_BITSIZE (SCALAR_INT_TYPE_MODE (etype)))
1489 || get_pointer_alignment (dest) / BITS_PER_UNIT < length)
1490 return NULL_TREE;
1492 if (length > HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT)
1493 return NULL_TREE;
1495 if (!type_has_mode_precision_p (etype))
1496 etype = lang_hooks.types.type_for_mode (SCALAR_INT_TYPE_MODE (etype),
1497 TYPE_UNSIGNED (etype));
1499 if (integer_zerop (c))
1500 cval = 0;
1501 else
1503 if (CHAR_BIT != 8 || BITS_PER_UNIT != 8 || HOST_BITS_PER_WIDE_INT > 64)
1504 return NULL_TREE;
1506 cval = TREE_INT_CST_LOW (c);
1507 cval &= 0xff;
1508 cval |= cval << 8;
1509 cval |= cval << 16;
1510 cval |= (cval << 31) << 1;
1513 var = fold_build2 (MEM_REF, etype, dest, build_int_cst (ptr_type_node, 0));
1514 gimple *store = gimple_build_assign (var, build_int_cst_type (etype, cval));
1515 gimple_move_vops (store, stmt);
1516 gimple_set_location (store, gimple_location (stmt));
1517 gsi_insert_before (gsi, store, GSI_SAME_STMT);
1518 if (gimple_call_lhs (stmt))
1520 gimple *asgn = gimple_build_assign (gimple_call_lhs (stmt), dest);
1521 gsi_replace (gsi, asgn, false);
1523 else
1525 gimple_stmt_iterator gsi2 = *gsi;
1526 gsi_prev (gsi);
1527 gsi_remove (&gsi2, true);
1530 return true;
1533 /* Helper of get_range_strlen for ARG that is not an SSA_NAME. */
1535 static bool
1536 get_range_strlen_tree (tree arg, bitmap visited, strlen_range_kind rkind,
1537 c_strlen_data *pdata, unsigned eltsize)
1539 gcc_assert (TREE_CODE (arg) != SSA_NAME);
1541 /* The length computed by this invocation of the function. */
1542 tree val = NULL_TREE;
1544 /* True if VAL is an optimistic (tight) bound determined from
1545 the size of the character array in which the string may be
1546 stored. In that case, the computed VAL is used to set
1547 PDATA->MAXBOUND. */
1548 bool tight_bound = false;
1550 /* We can end up with &(*iftmp_1)[0] here as well, so handle it. */
1551 if (TREE_CODE (arg) == ADDR_EXPR
1552 && TREE_CODE (TREE_OPERAND (arg, 0)) == ARRAY_REF)
1554 tree op = TREE_OPERAND (arg, 0);
1555 if (integer_zerop (TREE_OPERAND (op, 1)))
1557 tree aop0 = TREE_OPERAND (op, 0);
1558 if (TREE_CODE (aop0) == INDIRECT_REF
1559 && TREE_CODE (TREE_OPERAND (aop0, 0)) == SSA_NAME)
1560 return get_range_strlen (TREE_OPERAND (aop0, 0), visited, rkind,
1561 pdata, eltsize);
1563 else if (TREE_CODE (TREE_OPERAND (op, 0)) == COMPONENT_REF
1564 && rkind == SRK_LENRANGE)
1566 /* Fail if an array is the last member of a struct object
1567 since it could be treated as a (fake) flexible array
1568 member. */
1569 tree idx = TREE_OPERAND (op, 1);
1571 arg = TREE_OPERAND (op, 0);
1572 tree optype = TREE_TYPE (arg);
1573 if (tree dom = TYPE_DOMAIN (optype))
1574 if (tree bound = TYPE_MAX_VALUE (dom))
1575 if (TREE_CODE (bound) == INTEGER_CST
1576 && TREE_CODE (idx) == INTEGER_CST
1577 && tree_int_cst_lt (bound, idx))
1578 return false;
1582 if (rkind == SRK_INT_VALUE)
1584 /* We are computing the maximum value (not string length). */
1585 val = arg;
1586 if (TREE_CODE (val) != INTEGER_CST
1587 || tree_int_cst_sgn (val) < 0)
1588 return false;
1590 else
1592 c_strlen_data lendata = { };
1593 val = c_strlen (arg, 1, &lendata, eltsize);
1595 if (!val && lendata.decl)
1597 /* ARG refers to an unterminated const character array.
1598 DATA.DECL with size DATA.LEN. */
1599 val = lendata.minlen;
1600 pdata->decl = lendata.decl;
1604 /* Set if VAL represents the maximum length based on array size (set
1605 when exact length cannot be determined). */
1606 bool maxbound = false;
1608 if (!val && rkind == SRK_LENRANGE)
1610 if (TREE_CODE (arg) == ADDR_EXPR)
1611 return get_range_strlen (TREE_OPERAND (arg, 0), visited, rkind,
1612 pdata, eltsize);
1614 if (TREE_CODE (arg) == ARRAY_REF)
1616 tree optype = TREE_TYPE (TREE_OPERAND (arg, 0));
1618 /* Determine the "innermost" array type. */
1619 while (TREE_CODE (optype) == ARRAY_TYPE
1620 && TREE_CODE (TREE_TYPE (optype)) == ARRAY_TYPE)
1621 optype = TREE_TYPE (optype);
1623 /* Avoid arrays of pointers. */
1624 tree eltype = TREE_TYPE (optype);
1625 if (TREE_CODE (optype) != ARRAY_TYPE
1626 || !INTEGRAL_TYPE_P (eltype))
1627 return false;
1629 /* Fail when the array bound is unknown or zero. */
1630 val = TYPE_SIZE_UNIT (optype);
1631 if (!val
1632 || TREE_CODE (val) != INTEGER_CST
1633 || integer_zerop (val))
1634 return false;
1636 val = fold_build2 (MINUS_EXPR, TREE_TYPE (val), val,
1637 integer_one_node);
1639 /* Set the minimum size to zero since the string in
1640 the array could have zero length. */
1641 pdata->minlen = ssize_int (0);
1643 tight_bound = true;
1645 else if (TREE_CODE (arg) == COMPONENT_REF
1646 && (TREE_CODE (TREE_TYPE (TREE_OPERAND (arg, 1)))
1647 == ARRAY_TYPE))
1649 /* Use the type of the member array to determine the upper
1650 bound on the length of the array. This may be overly
1651 optimistic if the array itself isn't NUL-terminated and
1652 the caller relies on the subsequent member to contain
1653 the NUL but that would only be considered valid if
1654 the array were the last member of a struct. */
1656 tree fld = TREE_OPERAND (arg, 1);
1658 tree optype = TREE_TYPE (fld);
1660 /* Determine the "innermost" array type. */
1661 while (TREE_CODE (optype) == ARRAY_TYPE
1662 && TREE_CODE (TREE_TYPE (optype)) == ARRAY_TYPE)
1663 optype = TREE_TYPE (optype);
1665 /* Fail when the array bound is unknown or zero. */
1666 val = TYPE_SIZE_UNIT (optype);
1667 if (!val
1668 || TREE_CODE (val) != INTEGER_CST
1669 || integer_zerop (val))
1670 return false;
1671 val = fold_build2 (MINUS_EXPR, TREE_TYPE (val), val,
1672 integer_one_node);
1674 /* Set the minimum size to zero since the string in
1675 the array could have zero length. */
1676 pdata->minlen = ssize_int (0);
1678 /* The array size determined above is an optimistic bound
1679 on the length. If the array isn't nul-terminated the
1680 length computed by the library function would be greater.
1681 Even though using strlen to cross the subobject boundary
1682 is undefined, avoid drawing conclusions from the member
1683 type about the length here. */
1684 tight_bound = true;
1686 else if (TREE_CODE (arg) == MEM_REF
1687 && TREE_CODE (TREE_TYPE (arg)) == ARRAY_TYPE
1688 && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == INTEGER_TYPE
1689 && TREE_CODE (TREE_OPERAND (arg, 0)) == ADDR_EXPR)
1691 /* Handle a MEM_REF into a DECL accessing an array of integers,
1692 being conservative about references to extern structures with
1693 flexible array members that can be initialized to arbitrary
1694 numbers of elements as an extension (static structs are okay). */
1695 tree ref = TREE_OPERAND (TREE_OPERAND (arg, 0), 0);
1696 if ((TREE_CODE (ref) == PARM_DECL || VAR_P (ref))
1697 && (decl_binds_to_current_def_p (ref)
1698 || !array_ref_flexible_size_p (arg)))
1700 /* Fail if the offset is out of bounds. Such accesses
1701 should be diagnosed at some point. */
1702 val = DECL_SIZE_UNIT (ref);
1703 if (!val
1704 || TREE_CODE (val) != INTEGER_CST
1705 || integer_zerop (val))
1706 return false;
1708 poly_offset_int psiz = wi::to_offset (val);
1709 poly_offset_int poff = mem_ref_offset (arg);
1710 if (known_le (psiz, poff))
1711 return false;
1713 pdata->minlen = ssize_int (0);
1715 /* Subtract the offset and one for the terminating nul. */
1716 psiz -= poff;
1717 psiz -= 1;
1718 val = wide_int_to_tree (TREE_TYPE (val), psiz);
1719 /* Since VAL reflects the size of a declared object
1720 rather the type of the access it is not a tight bound. */
1723 else if (TREE_CODE (arg) == PARM_DECL || VAR_P (arg))
1725 /* Avoid handling pointers to arrays. GCC might misuse
1726 a pointer to an array of one bound to point to an array
1727 object of a greater bound. */
1728 tree argtype = TREE_TYPE (arg);
1729 if (TREE_CODE (argtype) == ARRAY_TYPE)
1731 val = TYPE_SIZE_UNIT (argtype);
1732 if (!val
1733 || TREE_CODE (val) != INTEGER_CST
1734 || integer_zerop (val))
1735 return false;
1736 val = wide_int_to_tree (TREE_TYPE (val),
1737 wi::sub (wi::to_wide (val), 1));
1739 /* Set the minimum size to zero since the string in
1740 the array could have zero length. */
1741 pdata->minlen = ssize_int (0);
1744 maxbound = true;
1747 if (!val)
1748 return false;
1750 /* Adjust the lower bound on the string length as necessary. */
1751 if (!pdata->minlen
1752 || (rkind != SRK_STRLEN
1753 && TREE_CODE (pdata->minlen) == INTEGER_CST
1754 && TREE_CODE (val) == INTEGER_CST
1755 && tree_int_cst_lt (val, pdata->minlen)))
1756 pdata->minlen = val;
1758 if (pdata->maxbound && TREE_CODE (pdata->maxbound) == INTEGER_CST)
1760 /* Adjust the tighter (more optimistic) string length bound
1761 if necessary and proceed to adjust the more conservative
1762 bound. */
1763 if (TREE_CODE (val) == INTEGER_CST)
1765 if (tree_int_cst_lt (pdata->maxbound, val))
1766 pdata->maxbound = val;
1768 else
1769 pdata->maxbound = val;
1771 else if (pdata->maxbound || maxbound)
1772 /* Set PDATA->MAXBOUND only if it either isn't INTEGER_CST or
1773 if VAL corresponds to the maximum length determined based
1774 on the type of the object. */
1775 pdata->maxbound = val;
1777 if (tight_bound)
1779 /* VAL computed above represents an optimistically tight bound
1780 on the length of the string based on the referenced object's
1781 or subobject's type. Determine the conservative upper bound
1782 based on the enclosing object's size if possible. */
1783 if (rkind == SRK_LENRANGE)
1785 poly_int64 offset;
1786 tree base = get_addr_base_and_unit_offset (arg, &offset);
1787 if (!base)
1789 /* When the call above fails due to a non-constant offset
1790 assume the offset is zero and use the size of the whole
1791 enclosing object instead. */
1792 base = get_base_address (arg);
1793 offset = 0;
1795 /* If the base object is a pointer no upper bound on the length
1796 can be determined. Otherwise the maximum length is equal to
1797 the size of the enclosing object minus the offset of
1798 the referenced subobject minus 1 (for the terminating nul). */
1799 tree type = TREE_TYPE (base);
1800 if (TREE_CODE (type) == POINTER_TYPE
1801 || (TREE_CODE (base) != PARM_DECL && !VAR_P (base))
1802 || !(val = DECL_SIZE_UNIT (base)))
1803 val = build_all_ones_cst (size_type_node);
1804 else
1806 val = DECL_SIZE_UNIT (base);
1807 val = fold_build2 (MINUS_EXPR, TREE_TYPE (val), val,
1808 size_int (offset + 1));
1811 else
1812 return false;
1815 if (pdata->maxlen)
1817 /* Adjust the more conservative bound if possible/necessary
1818 and fail otherwise. */
1819 if (rkind != SRK_STRLEN)
1821 if (TREE_CODE (pdata->maxlen) != INTEGER_CST
1822 || TREE_CODE (val) != INTEGER_CST)
1823 return false;
1825 if (tree_int_cst_lt (pdata->maxlen, val))
1826 pdata->maxlen = val;
1827 return true;
1829 else if (simple_cst_equal (val, pdata->maxlen) != 1)
1831 /* Fail if the length of this ARG is different from that
1832 previously determined from another ARG. */
1833 return false;
1837 pdata->maxlen = val;
1838 return rkind == SRK_LENRANGE || !integer_all_onesp (val);
1841 /* For an ARG referencing one or more strings, try to obtain the range
1842 of their lengths, or the size of the largest array ARG referes to if
1843 the range of lengths cannot be determined, and store all in *PDATA.
1844 For an integer ARG (when RKIND == SRK_INT_VALUE), try to determine
1845 the maximum constant value.
1846 If ARG is an SSA_NAME, follow its use-def chains. When RKIND ==
1847 SRK_STRLEN, then if PDATA->MAXLEN is not equal to the determined
1848 length or if we are unable to determine the length, return false.
1849 VISITED is a bitmap of visited variables.
1850 RKIND determines the kind of value or range to obtain (see
1851 strlen_range_kind).
1852 Set PDATA->DECL if ARG refers to an unterminated constant array.
1853 On input, set ELTSIZE to 1 for normal single byte character strings,
1854 and either 2 or 4 for wide characer strings (the size of wchar_t).
1855 Return true if *PDATA was successfully populated and false otherwise. */
1857 static bool
1858 get_range_strlen (tree arg, bitmap visited,
1859 strlen_range_kind rkind,
1860 c_strlen_data *pdata, unsigned eltsize)
1863 if (TREE_CODE (arg) != SSA_NAME)
1864 return get_range_strlen_tree (arg, visited, rkind, pdata, eltsize);
1866 /* If ARG is registered for SSA update we cannot look at its defining
1867 statement. */
1868 if (name_registered_for_update_p (arg))
1869 return false;
1871 /* If we were already here, break the infinite cycle. */
1872 if (!bitmap_set_bit (visited, SSA_NAME_VERSION (arg)))
1873 return true;
1875 tree var = arg;
1876 gimple *def_stmt = SSA_NAME_DEF_STMT (var);
1878 switch (gimple_code (def_stmt))
1880 case GIMPLE_ASSIGN:
1881 /* The RHS of the statement defining VAR must either have a
1882 constant length or come from another SSA_NAME with a constant
1883 length. */
1884 if (gimple_assign_single_p (def_stmt)
1885 || gimple_assign_unary_nop_p (def_stmt))
1887 tree rhs = gimple_assign_rhs1 (def_stmt);
1888 return get_range_strlen (rhs, visited, rkind, pdata, eltsize);
1890 else if (gimple_assign_rhs_code (def_stmt) == COND_EXPR)
1892 tree ops[2] = { gimple_assign_rhs2 (def_stmt),
1893 gimple_assign_rhs3 (def_stmt) };
1895 for (unsigned int i = 0; i < 2; i++)
1896 if (!get_range_strlen (ops[i], visited, rkind, pdata, eltsize))
1898 if (rkind != SRK_LENRANGE)
1899 return false;
1900 /* Set the upper bound to the maximum to prevent
1901 it from being adjusted in the next iteration but
1902 leave MINLEN and the more conservative MAXBOUND
1903 determined so far alone (or leave them null if
1904 they haven't been set yet). That the MINLEN is
1905 in fact zero can be determined from MAXLEN being
1906 unbounded but the discovered minimum is used for
1907 diagnostics. */
1908 pdata->maxlen = build_all_ones_cst (size_type_node);
1910 return true;
1912 return false;
1914 case GIMPLE_PHI:
1915 /* Unless RKIND == SRK_LENRANGE, all arguments of the PHI node
1916 must have a constant length. */
1917 for (unsigned i = 0; i < gimple_phi_num_args (def_stmt); i++)
1919 tree arg = gimple_phi_arg (def_stmt, i)->def;
1921 /* If this PHI has itself as an argument, we cannot
1922 determine the string length of this argument. However,
1923 if we can find a constant string length for the other
1924 PHI args then we can still be sure that this is a
1925 constant string length. So be optimistic and just
1926 continue with the next argument. */
1927 if (arg == gimple_phi_result (def_stmt))
1928 continue;
1930 if (!get_range_strlen (arg, visited, rkind, pdata, eltsize))
1932 if (rkind != SRK_LENRANGE)
1933 return false;
1934 /* Set the upper bound to the maximum to prevent
1935 it from being adjusted in the next iteration but
1936 leave MINLEN and the more conservative MAXBOUND
1937 determined so far alone (or leave them null if
1938 they haven't been set yet). That the MINLEN is
1939 in fact zero can be determined from MAXLEN being
1940 unbounded but the discovered minimum is used for
1941 diagnostics. */
1942 pdata->maxlen = build_all_ones_cst (size_type_node);
1945 return true;
1947 default:
1948 return false;
1952 /* Try to obtain the range of the lengths of the string(s) referenced
1953 by ARG, or the size of the largest array ARG refers to if the range
1954 of lengths cannot be determined, and store all in *PDATA which must
1955 be zero-initialized on input except PDATA->MAXBOUND may be set to
1956 a non-null tree node other than INTEGER_CST to request to have it
1957 set to the length of the longest string in a PHI. ELTSIZE is
1958 the expected size of the string element in bytes: 1 for char and
1959 some power of 2 for wide characters.
1960 Return true if the range [PDATA->MINLEN, PDATA->MAXLEN] is suitable
1961 for optimization. Returning false means that a nonzero PDATA->MINLEN
1962 doesn't reflect the true lower bound of the range when PDATA->MAXLEN
1963 is -1 (in that case, the actual range is indeterminate, i.e.,
1964 [0, PTRDIFF_MAX - 2]. */
1966 bool
1967 get_range_strlen (tree arg, c_strlen_data *pdata, unsigned eltsize)
1969 auto_bitmap visited;
1970 tree maxbound = pdata->maxbound;
1972 if (!get_range_strlen (arg, visited, SRK_LENRANGE, pdata, eltsize))
1974 /* On failure extend the length range to an impossible maximum
1975 (a valid MAXLEN must be less than PTRDIFF_MAX - 1). Other
1976 members can stay unchanged regardless. */
1977 pdata->minlen = ssize_int (0);
1978 pdata->maxlen = build_all_ones_cst (size_type_node);
1980 else if (!pdata->minlen)
1981 pdata->minlen = ssize_int (0);
1983 /* If it's unchanged from it initial non-null value, set the conservative
1984 MAXBOUND to SIZE_MAX. Otherwise leave it null (if it is null). */
1985 if (maxbound && pdata->maxbound == maxbound)
1986 pdata->maxbound = build_all_ones_cst (size_type_node);
1988 return !integer_all_onesp (pdata->maxlen);
1991 /* Return the maximum value for ARG given RKIND (see strlen_range_kind).
1992 For ARG of pointer types, NONSTR indicates if the caller is prepared
1993 to handle unterminated strings. For integer ARG and when RKIND ==
1994 SRK_INT_VALUE, NONSTR must be null.
1996 If an unterminated array is discovered and our caller handles
1997 unterminated arrays, then bubble up the offending DECL and
1998 return the maximum size. Otherwise return NULL. */
2000 static tree
2001 get_maxval_strlen (tree arg, strlen_range_kind rkind, tree *nonstr = NULL)
2003 /* A non-null NONSTR is meaningless when determining the maximum
2004 value of an integer ARG. */
2005 gcc_assert (rkind != SRK_INT_VALUE || nonstr == NULL);
2006 /* ARG must have an integral type when RKIND says so. */
2007 gcc_assert (rkind != SRK_INT_VALUE || INTEGRAL_TYPE_P (TREE_TYPE (arg)));
2009 auto_bitmap visited;
2011 /* Reset DATA.MAXLEN if the call fails or when DATA.MAXLEN
2012 is unbounded. */
2013 c_strlen_data lendata = { };
2014 if (!get_range_strlen (arg, visited, rkind, &lendata, /* eltsize = */1))
2015 lendata.maxlen = NULL_TREE;
2016 else if (lendata.maxlen && integer_all_onesp (lendata.maxlen))
2017 lendata.maxlen = NULL_TREE;
2019 if (nonstr)
2021 /* For callers prepared to handle unterminated arrays set
2022 *NONSTR to point to the declaration of the array and return
2023 the maximum length/size. */
2024 *nonstr = lendata.decl;
2025 return lendata.maxlen;
2028 /* Fail if the constant array isn't nul-terminated. */
2029 return lendata.decl ? NULL_TREE : lendata.maxlen;
2032 /* Return true if LEN is known to be less than or equal to (or if STRICT is
2033 true, strictly less than) the lower bound of SIZE at compile time and false
2034 otherwise. */
2036 static bool
2037 known_lower (gimple *stmt, tree len, tree size, bool strict = false)
2039 if (len == NULL_TREE)
2040 return false;
2042 wide_int size_range[2];
2043 wide_int len_range[2];
2044 if (get_range (len, stmt, len_range) && get_range (size, stmt, size_range))
2046 if (strict)
2047 return wi::ltu_p (len_range[1], size_range[0]);
2048 else
2049 return wi::leu_p (len_range[1], size_range[0]);
2052 return false;
2055 /* Fold function call to builtin strcpy with arguments DEST and SRC.
2056 If LEN is not NULL, it represents the length of the string to be
2057 copied. Return NULL_TREE if no simplification can be made. */
2059 static bool
2060 gimple_fold_builtin_strcpy (gimple_stmt_iterator *gsi,
2061 tree dest, tree src)
2063 gimple *stmt = gsi_stmt (*gsi);
2064 location_t loc = gimple_location (stmt);
2065 tree fn;
2067 /* If SRC and DEST are the same (and not volatile), return DEST. */
2068 if (operand_equal_p (src, dest, 0))
2070 /* Issue -Wrestrict unless the pointers are null (those do
2071 not point to objects and so do not indicate an overlap;
2072 such calls could be the result of sanitization and jump
2073 threading). */
2074 if (!integer_zerop (dest) && !warning_suppressed_p (stmt, OPT_Wrestrict))
2076 tree func = gimple_call_fndecl (stmt);
2078 warning_at (loc, OPT_Wrestrict,
2079 "%qD source argument is the same as destination",
2080 func);
2083 replace_call_with_value (gsi, dest);
2084 return true;
2087 if (optimize_function_for_size_p (cfun))
2088 return false;
2090 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
2091 if (!fn)
2092 return false;
2094 /* Set to non-null if ARG refers to an unterminated array. */
2095 tree nonstr = NULL;
2096 tree len = get_maxval_strlen (src, SRK_STRLEN, &nonstr);
2098 if (nonstr)
2100 /* Avoid folding calls with unterminated arrays. */
2101 if (!warning_suppressed_p (stmt, OPT_Wstringop_overread))
2102 warn_string_no_nul (loc, stmt, "strcpy", src, nonstr);
2103 suppress_warning (stmt, OPT_Wstringop_overread);
2104 return false;
2107 if (!len)
2108 return false;
2110 len = fold_convert_loc (loc, size_type_node, len);
2111 len = size_binop_loc (loc, PLUS_EXPR, len, build_int_cst (size_type_node, 1));
2112 len = force_gimple_operand_gsi (gsi, len, true,
2113 NULL_TREE, true, GSI_SAME_STMT);
2114 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
2115 replace_call_with_call_and_fold (gsi, repl);
2116 return true;
2119 /* Fold function call to builtin strncpy with arguments DEST, SRC, and LEN.
2120 If SLEN is not NULL, it represents the length of the source string.
2121 Return NULL_TREE if no simplification can be made. */
2123 static bool
2124 gimple_fold_builtin_strncpy (gimple_stmt_iterator *gsi,
2125 tree dest, tree src, tree len)
2127 gimple *stmt = gsi_stmt (*gsi);
2128 location_t loc = gimple_location (stmt);
2129 bool nonstring = get_attr_nonstring_decl (dest) != NULL_TREE;
2131 /* If the LEN parameter is zero, return DEST. */
2132 if (integer_zerop (len))
2134 /* Avoid warning if the destination refers to an array/pointer
2135 decorate with attribute nonstring. */
2136 if (!nonstring)
2138 tree fndecl = gimple_call_fndecl (stmt);
2140 /* Warn about the lack of nul termination: the result is not
2141 a (nul-terminated) string. */
2142 tree slen = get_maxval_strlen (src, SRK_STRLEN);
2143 if (slen && !integer_zerop (slen))
2144 warning_at (loc, OPT_Wstringop_truncation,
2145 "%qD destination unchanged after copying no bytes "
2146 "from a string of length %E",
2147 fndecl, slen);
2148 else
2149 warning_at (loc, OPT_Wstringop_truncation,
2150 "%qD destination unchanged after copying no bytes",
2151 fndecl);
2154 replace_call_with_value (gsi, dest);
2155 return true;
2158 /* We can't compare slen with len as constants below if len is not a
2159 constant. */
2160 if (TREE_CODE (len) != INTEGER_CST)
2161 return false;
2163 /* Now, we must be passed a constant src ptr parameter. */
2164 tree slen = get_maxval_strlen (src, SRK_STRLEN);
2165 if (!slen || TREE_CODE (slen) != INTEGER_CST)
2166 return false;
2168 /* The size of the source string including the terminating nul. */
2169 tree ssize = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
2171 /* We do not support simplification of this case, though we do
2172 support it when expanding trees into RTL. */
2173 /* FIXME: generate a call to __builtin_memset. */
2174 if (tree_int_cst_lt (ssize, len))
2175 return false;
2177 /* Diagnose truncation that leaves the copy unterminated. */
2178 maybe_diag_stxncpy_trunc (*gsi, src, len);
2180 /* OK transform into builtin memcpy. */
2181 tree fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
2182 if (!fn)
2183 return false;
2185 len = fold_convert_loc (loc, size_type_node, len);
2186 len = force_gimple_operand_gsi (gsi, len, true,
2187 NULL_TREE, true, GSI_SAME_STMT);
2188 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
2189 replace_call_with_call_and_fold (gsi, repl);
2191 return true;
2194 /* Fold function call to builtin strchr or strrchr.
2195 If both arguments are constant, evaluate and fold the result,
2196 otherwise simplify str(r)chr (str, 0) into str + strlen (str).
2197 In general strlen is significantly faster than strchr
2198 due to being a simpler operation. */
2199 static bool
2200 gimple_fold_builtin_strchr (gimple_stmt_iterator *gsi, bool is_strrchr)
2202 gimple *stmt = gsi_stmt (*gsi);
2203 tree str = gimple_call_arg (stmt, 0);
2204 tree c = gimple_call_arg (stmt, 1);
2205 location_t loc = gimple_location (stmt);
2206 const char *p;
2207 char ch;
2209 if (!gimple_call_lhs (stmt))
2210 return false;
2212 /* Avoid folding if the first argument is not a nul-terminated array.
2213 Defer warning until later. */
2214 if (!check_nul_terminated_array (NULL_TREE, str))
2215 return false;
2217 if ((p = c_getstr (str)) && target_char_cst_p (c, &ch))
2219 const char *p1 = is_strrchr ? strrchr (p, ch) : strchr (p, ch);
2221 if (p1 == NULL)
2223 replace_call_with_value (gsi, integer_zero_node);
2224 return true;
2227 tree len = build_int_cst (size_type_node, p1 - p);
2228 gimple_seq stmts = NULL;
2229 gimple *new_stmt = gimple_build_assign (gimple_call_lhs (stmt),
2230 POINTER_PLUS_EXPR, str, len);
2231 gimple_seq_add_stmt_without_update (&stmts, new_stmt);
2232 gsi_replace_with_seq_vops (gsi, stmts);
2233 return true;
2236 if (!integer_zerop (c))
2237 return false;
2239 /* Transform strrchr (s, 0) to strchr (s, 0) when optimizing for size. */
2240 if (is_strrchr && optimize_function_for_size_p (cfun))
2242 tree strchr_fn = builtin_decl_implicit (BUILT_IN_STRCHR);
2244 if (strchr_fn)
2246 gimple *repl = gimple_build_call (strchr_fn, 2, str, c);
2247 replace_call_with_call_and_fold (gsi, repl);
2248 return true;
2251 return false;
2254 tree len;
2255 tree strlen_fn = builtin_decl_implicit (BUILT_IN_STRLEN);
2257 if (!strlen_fn)
2258 return false;
2260 /* Create newstr = strlen (str). */
2261 gimple_seq stmts = NULL;
2262 gimple *new_stmt = gimple_build_call (strlen_fn, 1, str);
2263 gimple_set_location (new_stmt, loc);
2264 len = create_tmp_reg_or_ssa_name (size_type_node);
2265 gimple_call_set_lhs (new_stmt, len);
2266 gimple_seq_add_stmt_without_update (&stmts, new_stmt);
2268 /* Create (str p+ strlen (str)). */
2269 new_stmt = gimple_build_assign (gimple_call_lhs (stmt),
2270 POINTER_PLUS_EXPR, str, len);
2271 gimple_seq_add_stmt_without_update (&stmts, new_stmt);
2272 gsi_replace_with_seq_vops (gsi, stmts);
2273 /* gsi now points at the assignment to the lhs, get a
2274 stmt iterator to the strlen.
2275 ??? We can't use gsi_for_stmt as that doesn't work when the
2276 CFG isn't built yet. */
2277 gimple_stmt_iterator gsi2 = *gsi;
2278 gsi_prev (&gsi2);
2279 fold_stmt (&gsi2);
2280 return true;
2283 /* Fold function call to builtin strstr.
2284 If both arguments are constant, evaluate and fold the result,
2285 additionally fold strstr (x, "") into x and strstr (x, "c")
2286 into strchr (x, 'c'). */
2287 static bool
2288 gimple_fold_builtin_strstr (gimple_stmt_iterator *gsi)
2290 gimple *stmt = gsi_stmt (*gsi);
2291 if (!gimple_call_lhs (stmt))
2292 return false;
2294 tree haystack = gimple_call_arg (stmt, 0);
2295 tree needle = gimple_call_arg (stmt, 1);
2297 /* Avoid folding if either argument is not a nul-terminated array.
2298 Defer warning until later. */
2299 if (!check_nul_terminated_array (NULL_TREE, haystack)
2300 || !check_nul_terminated_array (NULL_TREE, needle))
2301 return false;
2303 const char *q = c_getstr (needle);
2304 if (q == NULL)
2305 return false;
2307 if (const char *p = c_getstr (haystack))
2309 const char *r = strstr (p, q);
2311 if (r == NULL)
2313 replace_call_with_value (gsi, integer_zero_node);
2314 return true;
2317 tree len = build_int_cst (size_type_node, r - p);
2318 gimple_seq stmts = NULL;
2319 gimple *new_stmt
2320 = gimple_build_assign (gimple_call_lhs (stmt), POINTER_PLUS_EXPR,
2321 haystack, len);
2322 gimple_seq_add_stmt_without_update (&stmts, new_stmt);
2323 gsi_replace_with_seq_vops (gsi, stmts);
2324 return true;
2327 /* For strstr (x, "") return x. */
2328 if (q[0] == '\0')
2330 replace_call_with_value (gsi, haystack);
2331 return true;
2334 /* Transform strstr (x, "c") into strchr (x, 'c'). */
2335 if (q[1] == '\0')
2337 tree strchr_fn = builtin_decl_implicit (BUILT_IN_STRCHR);
2338 if (strchr_fn)
2340 tree c = build_int_cst (integer_type_node, q[0]);
2341 gimple *repl = gimple_build_call (strchr_fn, 2, haystack, c);
2342 replace_call_with_call_and_fold (gsi, repl);
2343 return true;
2347 return false;
2350 /* Simplify a call to the strcat builtin. DST and SRC are the arguments
2351 to the call.
2353 Return NULL_TREE if no simplification was possible, otherwise return the
2354 simplified form of the call as a tree.
2356 The simplified form may be a constant or other expression which
2357 computes the same value, but in a more efficient manner (including
2358 calls to other builtin functions).
2360 The call may contain arguments which need to be evaluated, but
2361 which are not useful to determine the result of the call. In
2362 this case we return a chain of COMPOUND_EXPRs. The LHS of each
2363 COMPOUND_EXPR will be an argument which must be evaluated.
2364 COMPOUND_EXPRs are chained through their RHS. The RHS of the last
2365 COMPOUND_EXPR in the chain will contain the tree for the simplified
2366 form of the builtin function call. */
2368 static bool
2369 gimple_fold_builtin_strcat (gimple_stmt_iterator *gsi, tree dst, tree src)
2371 gimple *stmt = gsi_stmt (*gsi);
2372 location_t loc = gimple_location (stmt);
2374 const char *p = c_getstr (src);
2376 /* If the string length is zero, return the dst parameter. */
2377 if (p && *p == '\0')
2379 replace_call_with_value (gsi, dst);
2380 return true;
2383 if (!optimize_bb_for_speed_p (gimple_bb (stmt)))
2384 return false;
2386 /* See if we can store by pieces into (dst + strlen(dst)). */
2387 tree newdst;
2388 tree strlen_fn = builtin_decl_implicit (BUILT_IN_STRLEN);
2389 tree memcpy_fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
2391 if (!strlen_fn || !memcpy_fn)
2392 return false;
2394 /* If the length of the source string isn't computable don't
2395 split strcat into strlen and memcpy. */
2396 tree len = get_maxval_strlen (src, SRK_STRLEN);
2397 if (! len)
2398 return false;
2400 /* Create strlen (dst). */
2401 gimple_seq stmts = NULL, stmts2;
2402 gimple *repl = gimple_build_call (strlen_fn, 1, dst);
2403 gimple_set_location (repl, loc);
2404 newdst = create_tmp_reg_or_ssa_name (size_type_node);
2405 gimple_call_set_lhs (repl, newdst);
2406 gimple_seq_add_stmt_without_update (&stmts, repl);
2408 /* Create (dst p+ strlen (dst)). */
2409 newdst = fold_build_pointer_plus_loc (loc, dst, newdst);
2410 newdst = force_gimple_operand (newdst, &stmts2, true, NULL_TREE);
2411 gimple_seq_add_seq_without_update (&stmts, stmts2);
2413 len = fold_convert_loc (loc, size_type_node, len);
2414 len = size_binop_loc (loc, PLUS_EXPR, len,
2415 build_int_cst (size_type_node, 1));
2416 len = force_gimple_operand (len, &stmts2, true, NULL_TREE);
2417 gimple_seq_add_seq_without_update (&stmts, stmts2);
2419 repl = gimple_build_call (memcpy_fn, 3, newdst, src, len);
2420 gimple_seq_add_stmt_without_update (&stmts, repl);
2421 if (gimple_call_lhs (stmt))
2423 repl = gimple_build_assign (gimple_call_lhs (stmt), dst);
2424 gimple_seq_add_stmt_without_update (&stmts, repl);
2425 gsi_replace_with_seq_vops (gsi, stmts);
2426 /* gsi now points at the assignment to the lhs, get a
2427 stmt iterator to the memcpy call.
2428 ??? We can't use gsi_for_stmt as that doesn't work when the
2429 CFG isn't built yet. */
2430 gimple_stmt_iterator gsi2 = *gsi;
2431 gsi_prev (&gsi2);
2432 fold_stmt (&gsi2);
2434 else
2436 gsi_replace_with_seq_vops (gsi, stmts);
2437 fold_stmt (gsi);
2439 return true;
2442 /* Fold a call to the __strcat_chk builtin FNDECL. DEST, SRC, and SIZE
2443 are the arguments to the call. */
2445 static bool
2446 gimple_fold_builtin_strcat_chk (gimple_stmt_iterator *gsi)
2448 gimple *stmt = gsi_stmt (*gsi);
2449 tree dest = gimple_call_arg (stmt, 0);
2450 tree src = gimple_call_arg (stmt, 1);
2451 tree size = gimple_call_arg (stmt, 2);
2452 tree fn;
2453 const char *p;
2456 p = c_getstr (src);
2457 /* If the SRC parameter is "", return DEST. */
2458 if (p && *p == '\0')
2460 replace_call_with_value (gsi, dest);
2461 return true;
2464 if (! tree_fits_uhwi_p (size) || ! integer_all_onesp (size))
2465 return false;
2467 /* If __builtin_strcat_chk is used, assume strcat is available. */
2468 fn = builtin_decl_explicit (BUILT_IN_STRCAT);
2469 if (!fn)
2470 return false;
2472 gimple *repl = gimple_build_call (fn, 2, dest, src);
2473 replace_call_with_call_and_fold (gsi, repl);
2474 return true;
2477 /* Simplify a call to the strncat builtin. */
2479 static bool
2480 gimple_fold_builtin_strncat (gimple_stmt_iterator *gsi)
2482 gimple *stmt = gsi_stmt (*gsi);
2483 tree dst = gimple_call_arg (stmt, 0);
2484 tree src = gimple_call_arg (stmt, 1);
2485 tree len = gimple_call_arg (stmt, 2);
2486 tree src_len = c_strlen (src, 1);
2488 /* If the requested length is zero, or the src parameter string
2489 length is zero, return the dst parameter. */
2490 if (integer_zerop (len) || (src_len && integer_zerop (src_len)))
2492 replace_call_with_value (gsi, dst);
2493 return true;
2496 /* Return early if the requested len is less than the string length.
2497 Warnings will be issued elsewhere later. */
2498 if (!src_len || known_lower (stmt, len, src_len, true))
2499 return false;
2501 /* Warn on constant LEN. */
2502 if (TREE_CODE (len) == INTEGER_CST)
2504 bool nowarn = warning_suppressed_p (stmt, OPT_Wstringop_overflow_);
2505 tree dstsize;
2507 if (!nowarn && compute_builtin_object_size (dst, 1, &dstsize)
2508 && TREE_CODE (dstsize) == INTEGER_CST)
2510 int cmpdst = tree_int_cst_compare (len, dstsize);
2512 if (cmpdst >= 0)
2514 tree fndecl = gimple_call_fndecl (stmt);
2516 /* Strncat copies (at most) LEN bytes and always appends
2517 the terminating NUL so the specified bound should never
2518 be equal to (or greater than) the size of the destination.
2519 If it is, the copy could overflow. */
2520 location_t loc = gimple_location (stmt);
2521 nowarn = warning_at (loc, OPT_Wstringop_overflow_,
2522 cmpdst == 0
2523 ? G_("%qD specified bound %E equals "
2524 "destination size")
2525 : G_("%qD specified bound %E exceeds "
2526 "destination size %E"),
2527 fndecl, len, dstsize);
2528 if (nowarn)
2529 suppress_warning (stmt, OPT_Wstringop_overflow_);
2533 if (!nowarn && TREE_CODE (src_len) == INTEGER_CST
2534 && tree_int_cst_compare (src_len, len) == 0)
2536 tree fndecl = gimple_call_fndecl (stmt);
2537 location_t loc = gimple_location (stmt);
2539 /* To avoid possible overflow the specified bound should also
2540 not be equal to the length of the source, even when the size
2541 of the destination is unknown (it's not an uncommon mistake
2542 to specify as the bound to strncpy the length of the source). */
2543 if (warning_at (loc, OPT_Wstringop_overflow_,
2544 "%qD specified bound %E equals source length",
2545 fndecl, len))
2546 suppress_warning (stmt, OPT_Wstringop_overflow_);
2550 if (!known_lower (stmt, src_len, len))
2551 return false;
2553 tree fn = builtin_decl_implicit (BUILT_IN_STRCAT);
2555 /* If the replacement _DECL isn't initialized, don't do the
2556 transformation. */
2557 if (!fn)
2558 return false;
2560 /* Otherwise, emit a call to strcat. */
2561 gcall *repl = gimple_build_call (fn, 2, dst, src);
2562 replace_call_with_call_and_fold (gsi, repl);
2563 return true;
2566 /* Fold a call to the __strncat_chk builtin with arguments DEST, SRC,
2567 LEN, and SIZE. */
2569 static bool
2570 gimple_fold_builtin_strncat_chk (gimple_stmt_iterator *gsi)
2572 gimple *stmt = gsi_stmt (*gsi);
2573 tree dest = gimple_call_arg (stmt, 0);
2574 tree src = gimple_call_arg (stmt, 1);
2575 tree len = gimple_call_arg (stmt, 2);
2576 tree size = gimple_call_arg (stmt, 3);
2577 tree fn;
2578 const char *p;
2580 p = c_getstr (src);
2581 /* If the SRC parameter is "" or if LEN is 0, return DEST. */
2582 if ((p && *p == '\0')
2583 || integer_zerop (len))
2585 replace_call_with_value (gsi, dest);
2586 return true;
2589 if (! integer_all_onesp (size))
2591 tree src_len = c_strlen (src, 1);
2592 if (known_lower (stmt, src_len, len))
2594 /* If LEN >= strlen (SRC), optimize into __strcat_chk. */
2595 fn = builtin_decl_explicit (BUILT_IN_STRCAT_CHK);
2596 if (!fn)
2597 return false;
2599 gimple *repl = gimple_build_call (fn, 3, dest, src, size);
2600 replace_call_with_call_and_fold (gsi, repl);
2601 return true;
2603 return false;
2606 /* If __builtin_strncat_chk is used, assume strncat is available. */
2607 fn = builtin_decl_explicit (BUILT_IN_STRNCAT);
2608 if (!fn)
2609 return false;
2611 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
2612 replace_call_with_call_and_fold (gsi, repl);
2613 return true;
2616 /* Build and append gimple statements to STMTS that would load a first
2617 character of a memory location identified by STR. LOC is location
2618 of the statement. */
2620 static tree
2621 gimple_load_first_char (location_t loc, tree str, gimple_seq *stmts)
2623 tree var;
2625 tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
2626 tree cst_uchar_ptr_node
2627 = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
2628 tree off0 = build_int_cst (cst_uchar_ptr_node, 0);
2630 tree temp = fold_build2_loc (loc, MEM_REF, cst_uchar_node, str, off0);
2631 gassign *stmt = gimple_build_assign (NULL_TREE, temp);
2632 var = create_tmp_reg_or_ssa_name (cst_uchar_node, stmt);
2634 gimple_assign_set_lhs (stmt, var);
2635 gimple_seq_add_stmt_without_update (stmts, stmt);
2637 return var;
2640 /* Fold a call to the str{n}{case}cmp builtin pointed by GSI iterator. */
2642 static bool
2643 gimple_fold_builtin_string_compare (gimple_stmt_iterator *gsi)
2645 gimple *stmt = gsi_stmt (*gsi);
2646 tree callee = gimple_call_fndecl (stmt);
2647 enum built_in_function fcode = DECL_FUNCTION_CODE (callee);
2649 tree type = integer_type_node;
2650 tree str1 = gimple_call_arg (stmt, 0);
2651 tree str2 = gimple_call_arg (stmt, 1);
2652 tree lhs = gimple_call_lhs (stmt);
2654 tree bound_node = NULL_TREE;
2655 unsigned HOST_WIDE_INT bound = HOST_WIDE_INT_M1U;
2657 /* Handle strncmp and strncasecmp functions. */
2658 if (gimple_call_num_args (stmt) == 3)
2660 bound_node = gimple_call_arg (stmt, 2);
2661 if (tree_fits_uhwi_p (bound_node))
2662 bound = tree_to_uhwi (bound_node);
2665 /* If the BOUND parameter is zero, return zero. */
2666 if (bound == 0)
2668 replace_call_with_value (gsi, integer_zero_node);
2669 return true;
2672 /* If ARG1 and ARG2 are the same (and not volatile), return zero. */
2673 if (operand_equal_p (str1, str2, 0))
2675 replace_call_with_value (gsi, integer_zero_node);
2676 return true;
2679 /* Initially set to the number of characters, including the terminating
2680 nul if each array has one. LENx == strnlen (Sx, LENx) implies that
2681 the array Sx is not terminated by a nul.
2682 For nul-terminated strings then adjusted to their length so that
2683 LENx == NULPOSx holds. */
2684 unsigned HOST_WIDE_INT len1 = HOST_WIDE_INT_MAX, len2 = len1;
2685 const char *p1 = getbyterep (str1, &len1);
2686 const char *p2 = getbyterep (str2, &len2);
2688 /* The position of the terminating nul character if one exists, otherwise
2689 a value greater than LENx. */
2690 unsigned HOST_WIDE_INT nulpos1 = HOST_WIDE_INT_MAX, nulpos2 = nulpos1;
2692 if (p1)
2694 size_t n = strnlen (p1, len1);
2695 if (n < len1)
2696 len1 = nulpos1 = n;
2699 if (p2)
2701 size_t n = strnlen (p2, len2);
2702 if (n < len2)
2703 len2 = nulpos2 = n;
2706 /* For known strings, return an immediate value. */
2707 if (p1 && p2)
2709 int r = 0;
2710 bool known_result = false;
2712 switch (fcode)
2714 case BUILT_IN_STRCMP:
2715 case BUILT_IN_STRCMP_EQ:
2716 if (len1 != nulpos1 || len2 != nulpos2)
2717 break;
2719 r = strcmp (p1, p2);
2720 known_result = true;
2721 break;
2723 case BUILT_IN_STRNCMP:
2724 case BUILT_IN_STRNCMP_EQ:
2726 if (bound == HOST_WIDE_INT_M1U)
2727 break;
2729 /* Reduce the bound to be no more than the length
2730 of the shorter of the two strings, or the sizes
2731 of the unterminated arrays. */
2732 unsigned HOST_WIDE_INT n = bound;
2734 if (len1 == nulpos1 && len1 < n)
2735 n = len1 + 1;
2736 if (len2 == nulpos2 && len2 < n)
2737 n = len2 + 1;
2739 if (MIN (nulpos1, nulpos2) + 1 < n)
2740 break;
2742 r = strncmp (p1, p2, n);
2743 known_result = true;
2744 break;
2746 /* Only handleable situation is where the string are equal (result 0),
2747 which is already handled by operand_equal_p case. */
2748 case BUILT_IN_STRCASECMP:
2749 break;
2750 case BUILT_IN_STRNCASECMP:
2752 if (bound == HOST_WIDE_INT_M1U)
2753 break;
2754 r = strncmp (p1, p2, bound);
2755 if (r == 0)
2756 known_result = true;
2757 break;
2759 default:
2760 gcc_unreachable ();
2763 if (known_result)
2765 replace_call_with_value (gsi, build_cmp_result (type, r));
2766 return true;
2770 bool nonzero_bound = (bound >= 1 && bound < HOST_WIDE_INT_M1U)
2771 || fcode == BUILT_IN_STRCMP
2772 || fcode == BUILT_IN_STRCMP_EQ
2773 || fcode == BUILT_IN_STRCASECMP;
2775 location_t loc = gimple_location (stmt);
2777 /* If the second arg is "", return *(const unsigned char*)arg1. */
2778 if (p2 && *p2 == '\0' && nonzero_bound)
2780 gimple_seq stmts = NULL;
2781 tree var = gimple_load_first_char (loc, str1, &stmts);
2782 if (lhs)
2784 stmt = gimple_build_assign (lhs, NOP_EXPR, var);
2785 gimple_seq_add_stmt_without_update (&stmts, stmt);
2788 gsi_replace_with_seq_vops (gsi, stmts);
2789 return true;
2792 /* If the first arg is "", return -*(const unsigned char*)arg2. */
2793 if (p1 && *p1 == '\0' && nonzero_bound)
2795 gimple_seq stmts = NULL;
2796 tree var = gimple_load_first_char (loc, str2, &stmts);
2798 if (lhs)
2800 tree c = create_tmp_reg_or_ssa_name (integer_type_node);
2801 stmt = gimple_build_assign (c, NOP_EXPR, var);
2802 gimple_seq_add_stmt_without_update (&stmts, stmt);
2804 stmt = gimple_build_assign (lhs, NEGATE_EXPR, c);
2805 gimple_seq_add_stmt_without_update (&stmts, stmt);
2808 gsi_replace_with_seq_vops (gsi, stmts);
2809 return true;
2812 /* If BOUND is one, return an expression corresponding to
2813 (*(const unsigned char*)arg2 - *(const unsigned char*)arg1). */
2814 if (fcode == BUILT_IN_STRNCMP && bound == 1)
2816 gimple_seq stmts = NULL;
2817 tree temp1 = gimple_load_first_char (loc, str1, &stmts);
2818 tree temp2 = gimple_load_first_char (loc, str2, &stmts);
2820 if (lhs)
2822 tree c1 = create_tmp_reg_or_ssa_name (integer_type_node);
2823 gassign *convert1 = gimple_build_assign (c1, NOP_EXPR, temp1);
2824 gimple_seq_add_stmt_without_update (&stmts, convert1);
2826 tree c2 = create_tmp_reg_or_ssa_name (integer_type_node);
2827 gassign *convert2 = gimple_build_assign (c2, NOP_EXPR, temp2);
2828 gimple_seq_add_stmt_without_update (&stmts, convert2);
2830 stmt = gimple_build_assign (lhs, MINUS_EXPR, c1, c2);
2831 gimple_seq_add_stmt_without_update (&stmts, stmt);
2834 gsi_replace_with_seq_vops (gsi, stmts);
2835 return true;
2838 /* If BOUND is greater than the length of one constant string,
2839 and the other argument is also a nul-terminated string, replace
2840 strncmp with strcmp. */
2841 if (fcode == BUILT_IN_STRNCMP
2842 && bound > 0 && bound < HOST_WIDE_INT_M1U
2843 && ((p2 && len2 < bound && len2 == nulpos2)
2844 || (p1 && len1 < bound && len1 == nulpos1)))
2846 tree fn = builtin_decl_implicit (BUILT_IN_STRCMP);
2847 if (!fn)
2848 return false;
2849 gimple *repl = gimple_build_call (fn, 2, str1, str2);
2850 replace_call_with_call_and_fold (gsi, repl);
2851 return true;
2854 return false;
2857 /* Fold a call to the memchr pointed by GSI iterator. */
2859 static bool
2860 gimple_fold_builtin_memchr (gimple_stmt_iterator *gsi)
2862 gimple *stmt = gsi_stmt (*gsi);
2863 tree lhs = gimple_call_lhs (stmt);
2864 tree arg1 = gimple_call_arg (stmt, 0);
2865 tree arg2 = gimple_call_arg (stmt, 1);
2866 tree len = gimple_call_arg (stmt, 2);
2868 /* If the LEN parameter is zero, return zero. */
2869 if (integer_zerop (len))
2871 replace_call_with_value (gsi, build_int_cst (ptr_type_node, 0));
2872 return true;
2875 char c;
2876 if (TREE_CODE (arg2) != INTEGER_CST
2877 || !tree_fits_uhwi_p (len)
2878 || !target_char_cst_p (arg2, &c))
2879 return false;
2881 unsigned HOST_WIDE_INT length = tree_to_uhwi (len);
2882 unsigned HOST_WIDE_INT string_length;
2883 const char *p1 = getbyterep (arg1, &string_length);
2885 if (p1)
2887 const char *r = (const char *)memchr (p1, c, MIN (length, string_length));
2888 if (r == NULL)
2890 tree mem_size, offset_node;
2891 byte_representation (arg1, &offset_node, &mem_size, NULL);
2892 unsigned HOST_WIDE_INT offset = (offset_node == NULL_TREE)
2893 ? 0 : tree_to_uhwi (offset_node);
2894 /* MEM_SIZE is the size of the array the string literal
2895 is stored in. */
2896 unsigned HOST_WIDE_INT string_size = tree_to_uhwi (mem_size) - offset;
2897 gcc_checking_assert (string_length <= string_size);
2898 if (length <= string_size)
2900 replace_call_with_value (gsi, build_int_cst (ptr_type_node, 0));
2901 return true;
2904 else
2906 unsigned HOST_WIDE_INT offset = r - p1;
2907 gimple_seq stmts = NULL;
2908 if (lhs != NULL_TREE)
2910 tree offset_cst = build_int_cst (sizetype, offset);
2911 gassign *stmt = gimple_build_assign (lhs, POINTER_PLUS_EXPR,
2912 arg1, offset_cst);
2913 gimple_seq_add_stmt_without_update (&stmts, stmt);
2915 else
2916 gimple_seq_add_stmt_without_update (&stmts,
2917 gimple_build_nop ());
2919 gsi_replace_with_seq_vops (gsi, stmts);
2920 return true;
2924 return false;
2927 /* Fold a call to the fputs builtin. ARG0 and ARG1 are the arguments
2928 to the call. IGNORE is true if the value returned
2929 by the builtin will be ignored. UNLOCKED is true is true if this
2930 actually a call to fputs_unlocked. If LEN in non-NULL, it represents
2931 the known length of the string. Return NULL_TREE if no simplification
2932 was possible. */
2934 static bool
2935 gimple_fold_builtin_fputs (gimple_stmt_iterator *gsi,
2936 tree arg0, tree arg1,
2937 bool unlocked)
2939 gimple *stmt = gsi_stmt (*gsi);
2941 /* If we're using an unlocked function, assume the other unlocked
2942 functions exist explicitly. */
2943 tree const fn_fputc = (unlocked
2944 ? builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED)
2945 : builtin_decl_implicit (BUILT_IN_FPUTC));
2946 tree const fn_fwrite = (unlocked
2947 ? builtin_decl_explicit (BUILT_IN_FWRITE_UNLOCKED)
2948 : builtin_decl_implicit (BUILT_IN_FWRITE));
2950 /* If the return value is used, don't do the transformation. */
2951 if (gimple_call_lhs (stmt))
2952 return false;
2954 /* Get the length of the string passed to fputs. If the length
2955 can't be determined, punt. */
2956 tree len = get_maxval_strlen (arg0, SRK_STRLEN);
2957 if (!len
2958 || TREE_CODE (len) != INTEGER_CST)
2959 return false;
2961 switch (compare_tree_int (len, 1))
2963 case -1: /* length is 0, delete the call entirely . */
2964 replace_call_with_value (gsi, integer_zero_node);
2965 return true;
2967 case 0: /* length is 1, call fputc. */
2969 const char *p = c_getstr (arg0);
2970 if (p != NULL)
2972 if (!fn_fputc)
2973 return false;
2975 gimple *repl = gimple_build_call (fn_fputc, 2,
2976 build_int_cst
2977 (integer_type_node, p[0]), arg1);
2978 replace_call_with_call_and_fold (gsi, repl);
2979 return true;
2982 /* FALLTHROUGH */
2983 case 1: /* length is greater than 1, call fwrite. */
2985 /* If optimizing for size keep fputs. */
2986 if (optimize_function_for_size_p (cfun))
2987 return false;
2988 /* New argument list transforming fputs(string, stream) to
2989 fwrite(string, 1, len, stream). */
2990 if (!fn_fwrite)
2991 return false;
2993 gimple *repl = gimple_build_call (fn_fwrite, 4, arg0,
2994 size_one_node, len, arg1);
2995 replace_call_with_call_and_fold (gsi, repl);
2996 return true;
2998 default:
2999 gcc_unreachable ();
3003 /* Fold a call to the __mem{cpy,pcpy,move,set}_chk builtin.
3004 DEST, SRC, LEN, and SIZE are the arguments to the call.
3005 IGNORE is true, if return value can be ignored. FCODE is the BUILT_IN_*
3006 code of the builtin. If MAXLEN is not NULL, it is maximum length
3007 passed as third argument. */
3009 static bool
3010 gimple_fold_builtin_memory_chk (gimple_stmt_iterator *gsi,
3011 tree dest, tree src, tree len, tree size,
3012 enum built_in_function fcode)
3014 gimple *stmt = gsi_stmt (*gsi);
3015 location_t loc = gimple_location (stmt);
3016 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
3017 tree fn;
3019 /* If SRC and DEST are the same (and not volatile), return DEST
3020 (resp. DEST+LEN for __mempcpy_chk). */
3021 if (fcode != BUILT_IN_MEMSET_CHK && operand_equal_p (src, dest, 0))
3023 if (fcode != BUILT_IN_MEMPCPY_CHK)
3025 replace_call_with_value (gsi, dest);
3026 return true;
3028 else
3030 gimple_seq stmts = NULL;
3031 len = gimple_convert_to_ptrofftype (&stmts, loc, len);
3032 tree temp = gimple_build (&stmts, loc, POINTER_PLUS_EXPR,
3033 TREE_TYPE (dest), dest, len);
3034 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
3035 replace_call_with_value (gsi, temp);
3036 return true;
3040 tree maxlen = get_maxval_strlen (len, SRK_INT_VALUE);
3041 if (! integer_all_onesp (size)
3042 && !known_lower (stmt, len, size)
3043 && !known_lower (stmt, maxlen, size))
3045 /* MAXLEN and LEN both cannot be proved to be less than SIZE, at
3046 least try to optimize (void) __mempcpy_chk () into
3047 (void) __memcpy_chk () */
3048 if (fcode == BUILT_IN_MEMPCPY_CHK && ignore)
3050 fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
3051 if (!fn)
3052 return false;
3054 gimple *repl = gimple_build_call (fn, 4, dest, src, len, size);
3055 replace_call_with_call_and_fold (gsi, repl);
3056 return true;
3058 return false;
3061 fn = NULL_TREE;
3062 /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
3063 mem{cpy,pcpy,move,set} is available. */
3064 switch (fcode)
3066 case BUILT_IN_MEMCPY_CHK:
3067 fn = builtin_decl_explicit (BUILT_IN_MEMCPY);
3068 break;
3069 case BUILT_IN_MEMPCPY_CHK:
3070 fn = builtin_decl_explicit (BUILT_IN_MEMPCPY);
3071 break;
3072 case BUILT_IN_MEMMOVE_CHK:
3073 fn = builtin_decl_explicit (BUILT_IN_MEMMOVE);
3074 break;
3075 case BUILT_IN_MEMSET_CHK:
3076 fn = builtin_decl_explicit (BUILT_IN_MEMSET);
3077 break;
3078 default:
3079 break;
3082 if (!fn)
3083 return false;
3085 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
3086 replace_call_with_call_and_fold (gsi, repl);
3087 return true;
3090 /* Print a message in the dump file recording transformation of FROM to TO. */
3092 static void
3093 dump_transformation (gcall *from, gcall *to)
3095 if (dump_enabled_p ())
3096 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, from, "simplified %T to %T\n",
3097 gimple_call_fn (from), gimple_call_fn (to));
3100 /* Fold a call to the __st[rp]cpy_chk builtin.
3101 DEST, SRC, and SIZE are the arguments to the call.
3102 IGNORE is true if return value can be ignored. FCODE is the BUILT_IN_*
3103 code of the builtin. If MAXLEN is not NULL, it is maximum length of
3104 strings passed as second argument. */
3106 static bool
3107 gimple_fold_builtin_stxcpy_chk (gimple_stmt_iterator *gsi,
3108 tree dest,
3109 tree src, tree size,
3110 enum built_in_function fcode)
3112 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3113 location_t loc = gimple_location (stmt);
3114 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
3115 tree len, fn;
3117 /* If SRC and DEST are the same (and not volatile), return DEST. */
3118 if (fcode == BUILT_IN_STRCPY_CHK && operand_equal_p (src, dest, 0))
3120 /* Issue -Wrestrict unless the pointers are null (those do
3121 not point to objects and so do not indicate an overlap;
3122 such calls could be the result of sanitization and jump
3123 threading). */
3124 if (!integer_zerop (dest)
3125 && !warning_suppressed_p (stmt, OPT_Wrestrict))
3127 tree func = gimple_call_fndecl (stmt);
3129 warning_at (loc, OPT_Wrestrict,
3130 "%qD source argument is the same as destination",
3131 func);
3134 replace_call_with_value (gsi, dest);
3135 return true;
3138 tree maxlen = get_maxval_strlen (src, SRK_STRLENMAX);
3139 if (! integer_all_onesp (size))
3141 len = c_strlen (src, 1);
3142 if (!known_lower (stmt, len, size, true)
3143 && !known_lower (stmt, maxlen, size, true))
3145 if (fcode == BUILT_IN_STPCPY_CHK)
3147 if (! ignore)
3148 return false;
3150 /* If return value of __stpcpy_chk is ignored,
3151 optimize into __strcpy_chk. */
3152 fn = builtin_decl_explicit (BUILT_IN_STRCPY_CHK);
3153 if (!fn)
3154 return false;
3156 gimple *repl = gimple_build_call (fn, 3, dest, src, size);
3157 replace_call_with_call_and_fold (gsi, repl);
3158 return true;
3161 if (! len || TREE_SIDE_EFFECTS (len))
3162 return false;
3164 /* If c_strlen returned something, but not provably less than size,
3165 transform __strcpy_chk into __memcpy_chk. */
3166 fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
3167 if (!fn)
3168 return false;
3170 gimple_seq stmts = NULL;
3171 len = force_gimple_operand (len, &stmts, true, NULL_TREE);
3172 len = gimple_convert (&stmts, loc, size_type_node, len);
3173 len = gimple_build (&stmts, loc, PLUS_EXPR, size_type_node, len,
3174 build_int_cst (size_type_node, 1));
3175 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
3176 gimple *repl = gimple_build_call (fn, 4, dest, src, len, size);
3177 replace_call_with_call_and_fold (gsi, repl);
3178 return true;
3182 /* If __builtin_st{r,p}cpy_chk is used, assume st{r,p}cpy is available. */
3183 fn = builtin_decl_explicit (fcode == BUILT_IN_STPCPY_CHK && !ignore
3184 ? BUILT_IN_STPCPY : BUILT_IN_STRCPY);
3185 if (!fn)
3186 return false;
3188 gcall *repl = gimple_build_call (fn, 2, dest, src);
3189 dump_transformation (stmt, repl);
3190 replace_call_with_call_and_fold (gsi, repl);
3191 return true;
3194 /* Fold a call to the __st{r,p}ncpy_chk builtin. DEST, SRC, LEN, and SIZE
3195 are the arguments to the call. If MAXLEN is not NULL, it is maximum
3196 length passed as third argument. IGNORE is true if return value can be
3197 ignored. FCODE is the BUILT_IN_* code of the builtin. */
3199 static bool
3200 gimple_fold_builtin_stxncpy_chk (gimple_stmt_iterator *gsi,
3201 tree dest, tree src,
3202 tree len, tree size,
3203 enum built_in_function fcode)
3205 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3206 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
3207 tree fn;
3209 tree maxlen = get_maxval_strlen (len, SRK_INT_VALUE);
3210 if (! integer_all_onesp (size)
3211 && !known_lower (stmt, len, size) && !known_lower (stmt, maxlen, size))
3213 if (fcode == BUILT_IN_STPNCPY_CHK && ignore)
3215 /* If return value of __stpncpy_chk is ignored,
3216 optimize into __strncpy_chk. */
3217 fn = builtin_decl_explicit (BUILT_IN_STRNCPY_CHK);
3218 if (fn)
3220 gimple *repl = gimple_build_call (fn, 4, dest, src, len, size);
3221 replace_call_with_call_and_fold (gsi, repl);
3222 return true;
3225 return false;
3228 /* If __builtin_st{r,p}ncpy_chk is used, assume st{r,p}ncpy is available. */
3229 fn = builtin_decl_explicit (fcode == BUILT_IN_STPNCPY_CHK && !ignore
3230 ? BUILT_IN_STPNCPY : BUILT_IN_STRNCPY);
3231 if (!fn)
3232 return false;
3234 gcall *repl = gimple_build_call (fn, 3, dest, src, len);
3235 dump_transformation (stmt, repl);
3236 replace_call_with_call_and_fold (gsi, repl);
3237 return true;
3240 /* Fold function call to builtin stpcpy with arguments DEST and SRC.
3241 Return NULL_TREE if no simplification can be made. */
3243 static bool
3244 gimple_fold_builtin_stpcpy (gimple_stmt_iterator *gsi)
3246 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3247 location_t loc = gimple_location (stmt);
3248 tree dest = gimple_call_arg (stmt, 0);
3249 tree src = gimple_call_arg (stmt, 1);
3250 tree fn, lenp1;
3252 /* If the result is unused, replace stpcpy with strcpy. */
3253 if (gimple_call_lhs (stmt) == NULL_TREE)
3255 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
3256 if (!fn)
3257 return false;
3258 gimple_call_set_fndecl (stmt, fn);
3259 fold_stmt (gsi);
3260 return true;
3263 /* Set to non-null if ARG refers to an unterminated array. */
3264 c_strlen_data data = { };
3265 /* The size of the unterminated array if SRC referes to one. */
3266 tree size;
3267 /* True if the size is exact/constant, false if it's the lower bound
3268 of a range. */
3269 bool exact;
3270 tree len = c_strlen (src, 1, &data, 1);
3271 if (!len
3272 || TREE_CODE (len) != INTEGER_CST)
3274 data.decl = unterminated_array (src, &size, &exact);
3275 if (!data.decl)
3276 return false;
3279 if (data.decl)
3281 /* Avoid folding calls with unterminated arrays. */
3282 if (!warning_suppressed_p (stmt, OPT_Wstringop_overread))
3283 warn_string_no_nul (loc, stmt, "stpcpy", src, data.decl, size,
3284 exact);
3285 suppress_warning (stmt, OPT_Wstringop_overread);
3286 return false;
3289 if (optimize_function_for_size_p (cfun)
3290 /* If length is zero it's small enough. */
3291 && !integer_zerop (len))
3292 return false;
3294 /* If the source has a known length replace stpcpy with memcpy. */
3295 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
3296 if (!fn)
3297 return false;
3299 gimple_seq stmts = NULL;
3300 tree tem = gimple_convert (&stmts, loc, size_type_node, len);
3301 lenp1 = gimple_build (&stmts, loc, PLUS_EXPR, size_type_node,
3302 tem, build_int_cst (size_type_node, 1));
3303 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
3304 gcall *repl = gimple_build_call (fn, 3, dest, src, lenp1);
3305 gimple_move_vops (repl, stmt);
3306 gsi_insert_before (gsi, repl, GSI_SAME_STMT);
3307 /* Replace the result with dest + len. */
3308 stmts = NULL;
3309 tem = gimple_convert (&stmts, loc, sizetype, len);
3310 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
3311 gassign *ret = gimple_build_assign (gimple_call_lhs (stmt),
3312 POINTER_PLUS_EXPR, dest, tem);
3313 gsi_replace (gsi, ret, false);
3314 /* Finally fold the memcpy call. */
3315 gimple_stmt_iterator gsi2 = *gsi;
3316 gsi_prev (&gsi2);
3317 fold_stmt (&gsi2);
3318 return true;
3321 /* Fold a call EXP to {,v}snprintf having NARGS passed as ARGS. Return
3322 NULL_TREE if a normal call should be emitted rather than expanding
3323 the function inline. FCODE is either BUILT_IN_SNPRINTF_CHK or
3324 BUILT_IN_VSNPRINTF_CHK. If MAXLEN is not NULL, it is maximum length
3325 passed as second argument. */
3327 static bool
3328 gimple_fold_builtin_snprintf_chk (gimple_stmt_iterator *gsi,
3329 enum built_in_function fcode)
3331 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3332 tree dest, size, len, fn, fmt, flag;
3333 const char *fmt_str;
3335 /* Verify the required arguments in the original call. */
3336 if (gimple_call_num_args (stmt) < 5)
3337 return false;
3339 dest = gimple_call_arg (stmt, 0);
3340 len = gimple_call_arg (stmt, 1);
3341 flag = gimple_call_arg (stmt, 2);
3342 size = gimple_call_arg (stmt, 3);
3343 fmt = gimple_call_arg (stmt, 4);
3345 tree maxlen = get_maxval_strlen (len, SRK_INT_VALUE);
3346 if (! integer_all_onesp (size)
3347 && !known_lower (stmt, len, size) && !known_lower (stmt, maxlen, size))
3348 return false;
3350 if (!init_target_chars ())
3351 return false;
3353 /* Only convert __{,v}snprintf_chk to {,v}snprintf if flag is 0
3354 or if format doesn't contain % chars or is "%s". */
3355 if (! integer_zerop (flag))
3357 fmt_str = c_getstr (fmt);
3358 if (fmt_str == NULL)
3359 return false;
3360 if (strchr (fmt_str, target_percent) != NULL
3361 && strcmp (fmt_str, target_percent_s))
3362 return false;
3365 /* If __builtin_{,v}snprintf_chk is used, assume {,v}snprintf is
3366 available. */
3367 fn = builtin_decl_explicit (fcode == BUILT_IN_VSNPRINTF_CHK
3368 ? BUILT_IN_VSNPRINTF : BUILT_IN_SNPRINTF);
3369 if (!fn)
3370 return false;
3372 /* Replace the called function and the first 5 argument by 3 retaining
3373 trailing varargs. */
3374 gimple_call_set_fndecl (stmt, fn);
3375 gimple_call_set_fntype (stmt, TREE_TYPE (fn));
3376 gimple_call_set_arg (stmt, 0, dest);
3377 gimple_call_set_arg (stmt, 1, len);
3378 gimple_call_set_arg (stmt, 2, fmt);
3379 for (unsigned i = 3; i < gimple_call_num_args (stmt) - 2; ++i)
3380 gimple_call_set_arg (stmt, i, gimple_call_arg (stmt, i + 2));
3381 gimple_set_num_ops (stmt, gimple_num_ops (stmt) - 2);
3382 fold_stmt (gsi);
3383 return true;
3386 /* Fold a call EXP to __{,v}sprintf_chk having NARGS passed as ARGS.
3387 Return NULL_TREE if a normal call should be emitted rather than
3388 expanding the function inline. FCODE is either BUILT_IN_SPRINTF_CHK
3389 or BUILT_IN_VSPRINTF_CHK. */
3391 static bool
3392 gimple_fold_builtin_sprintf_chk (gimple_stmt_iterator *gsi,
3393 enum built_in_function fcode)
3395 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3396 tree dest, size, len, fn, fmt, flag;
3397 const char *fmt_str;
3398 unsigned nargs = gimple_call_num_args (stmt);
3400 /* Verify the required arguments in the original call. */
3401 if (nargs < 4)
3402 return false;
3403 dest = gimple_call_arg (stmt, 0);
3404 flag = gimple_call_arg (stmt, 1);
3405 size = gimple_call_arg (stmt, 2);
3406 fmt = gimple_call_arg (stmt, 3);
3408 len = NULL_TREE;
3410 if (!init_target_chars ())
3411 return false;
3413 /* Check whether the format is a literal string constant. */
3414 fmt_str = c_getstr (fmt);
3415 if (fmt_str != NULL)
3417 /* If the format doesn't contain % args or %%, we know the size. */
3418 if (strchr (fmt_str, target_percent) == 0)
3420 if (fcode != BUILT_IN_SPRINTF_CHK || nargs == 4)
3421 len = build_int_cstu (size_type_node, strlen (fmt_str));
3423 /* If the format is "%s" and first ... argument is a string literal,
3424 we know the size too. */
3425 else if (fcode == BUILT_IN_SPRINTF_CHK
3426 && strcmp (fmt_str, target_percent_s) == 0)
3428 tree arg;
3430 if (nargs == 5)
3432 arg = gimple_call_arg (stmt, 4);
3433 if (POINTER_TYPE_P (TREE_TYPE (arg)))
3434 len = c_strlen (arg, 1);
3439 if (! integer_all_onesp (size) && !known_lower (stmt, len, size, true))
3440 return false;
3442 /* Only convert __{,v}sprintf_chk to {,v}sprintf if flag is 0
3443 or if format doesn't contain % chars or is "%s". */
3444 if (! integer_zerop (flag))
3446 if (fmt_str == NULL)
3447 return false;
3448 if (strchr (fmt_str, target_percent) != NULL
3449 && strcmp (fmt_str, target_percent_s))
3450 return false;
3453 /* If __builtin_{,v}sprintf_chk is used, assume {,v}sprintf is available. */
3454 fn = builtin_decl_explicit (fcode == BUILT_IN_VSPRINTF_CHK
3455 ? BUILT_IN_VSPRINTF : BUILT_IN_SPRINTF);
3456 if (!fn)
3457 return false;
3459 /* Replace the called function and the first 4 argument by 2 retaining
3460 trailing varargs. */
3461 gimple_call_set_fndecl (stmt, fn);
3462 gimple_call_set_fntype (stmt, TREE_TYPE (fn));
3463 gimple_call_set_arg (stmt, 0, dest);
3464 gimple_call_set_arg (stmt, 1, fmt);
3465 for (unsigned i = 2; i < gimple_call_num_args (stmt) - 2; ++i)
3466 gimple_call_set_arg (stmt, i, gimple_call_arg (stmt, i + 2));
3467 gimple_set_num_ops (stmt, gimple_num_ops (stmt) - 2);
3468 fold_stmt (gsi);
3469 return true;
3472 /* Simplify a call to the sprintf builtin with arguments DEST, FMT, and ORIG.
3473 ORIG may be null if this is a 2-argument call. We don't attempt to
3474 simplify calls with more than 3 arguments.
3476 Return true if simplification was possible, otherwise false. */
3478 bool
3479 gimple_fold_builtin_sprintf (gimple_stmt_iterator *gsi)
3481 gimple *stmt = gsi_stmt (*gsi);
3483 /* Verify the required arguments in the original call. We deal with two
3484 types of sprintf() calls: 'sprintf (str, fmt)' and
3485 'sprintf (dest, "%s", orig)'. */
3486 if (gimple_call_num_args (stmt) > 3)
3487 return false;
3489 tree orig = NULL_TREE;
3490 if (gimple_call_num_args (stmt) == 3)
3491 orig = gimple_call_arg (stmt, 2);
3493 /* Check whether the format is a literal string constant. */
3494 tree fmt = gimple_call_arg (stmt, 1);
3495 const char *fmt_str = c_getstr (fmt);
3496 if (fmt_str == NULL)
3497 return false;
3499 tree dest = gimple_call_arg (stmt, 0);
3501 if (!init_target_chars ())
3502 return false;
3504 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
3505 if (!fn)
3506 return false;
3508 /* If the format doesn't contain % args or %%, use strcpy. */
3509 if (strchr (fmt_str, target_percent) == NULL)
3511 /* Don't optimize sprintf (buf, "abc", ptr++). */
3512 if (orig)
3513 return false;
3515 /* Convert sprintf (str, fmt) into strcpy (str, fmt) when
3516 'format' is known to contain no % formats. */
3517 gimple_seq stmts = NULL;
3518 gimple *repl = gimple_build_call (fn, 2, dest, fmt);
3520 /* Propagate the NO_WARNING bit to avoid issuing the same
3521 warning more than once. */
3522 copy_warning (repl, stmt);
3524 gimple_seq_add_stmt_without_update (&stmts, repl);
3525 if (tree lhs = gimple_call_lhs (stmt))
3527 repl = gimple_build_assign (lhs, build_int_cst (TREE_TYPE (lhs),
3528 strlen (fmt_str)));
3529 gimple_seq_add_stmt_without_update (&stmts, repl);
3530 gsi_replace_with_seq_vops (gsi, stmts);
3531 /* gsi now points at the assignment to the lhs, get a
3532 stmt iterator to the memcpy call.
3533 ??? We can't use gsi_for_stmt as that doesn't work when the
3534 CFG isn't built yet. */
3535 gimple_stmt_iterator gsi2 = *gsi;
3536 gsi_prev (&gsi2);
3537 fold_stmt (&gsi2);
3539 else
3541 gsi_replace_with_seq_vops (gsi, stmts);
3542 fold_stmt (gsi);
3544 return true;
3547 /* If the format is "%s", use strcpy if the result isn't used. */
3548 else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
3550 /* Don't crash on sprintf (str1, "%s"). */
3551 if (!orig)
3552 return false;
3554 /* Don't fold calls with source arguments of invalid (nonpointer)
3555 types. */
3556 if (!POINTER_TYPE_P (TREE_TYPE (orig)))
3557 return false;
3559 tree orig_len = NULL_TREE;
3560 if (gimple_call_lhs (stmt))
3562 orig_len = get_maxval_strlen (orig, SRK_STRLEN);
3563 if (!orig_len)
3564 return false;
3567 /* Convert sprintf (str1, "%s", str2) into strcpy (str1, str2). */
3568 gimple_seq stmts = NULL;
3569 gimple *repl = gimple_build_call (fn, 2, dest, orig);
3571 /* Propagate the NO_WARNING bit to avoid issuing the same
3572 warning more than once. */
3573 copy_warning (repl, stmt);
3575 gimple_seq_add_stmt_without_update (&stmts, repl);
3576 if (tree lhs = gimple_call_lhs (stmt))
3578 if (!useless_type_conversion_p (TREE_TYPE (lhs),
3579 TREE_TYPE (orig_len)))
3580 orig_len = fold_convert (TREE_TYPE (lhs), orig_len);
3581 repl = gimple_build_assign (lhs, orig_len);
3582 gimple_seq_add_stmt_without_update (&stmts, repl);
3583 gsi_replace_with_seq_vops (gsi, stmts);
3584 /* gsi now points at the assignment to the lhs, get a
3585 stmt iterator to the memcpy call.
3586 ??? We can't use gsi_for_stmt as that doesn't work when the
3587 CFG isn't built yet. */
3588 gimple_stmt_iterator gsi2 = *gsi;
3589 gsi_prev (&gsi2);
3590 fold_stmt (&gsi2);
3592 else
3594 gsi_replace_with_seq_vops (gsi, stmts);
3595 fold_stmt (gsi);
3597 return true;
3599 return false;
3602 /* Simplify a call to the snprintf builtin with arguments DEST, DESTSIZE,
3603 FMT, and ORIG. ORIG may be null if this is a 3-argument call. We don't
3604 attempt to simplify calls with more than 4 arguments.
3606 Return true if simplification was possible, otherwise false. */
3608 bool
3609 gimple_fold_builtin_snprintf (gimple_stmt_iterator *gsi)
3611 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3612 tree dest = gimple_call_arg (stmt, 0);
3613 tree destsize = gimple_call_arg (stmt, 1);
3614 tree fmt = gimple_call_arg (stmt, 2);
3615 tree orig = NULL_TREE;
3616 const char *fmt_str = NULL;
3618 if (gimple_call_num_args (stmt) > 4)
3619 return false;
3621 if (gimple_call_num_args (stmt) == 4)
3622 orig = gimple_call_arg (stmt, 3);
3624 /* Check whether the format is a literal string constant. */
3625 fmt_str = c_getstr (fmt);
3626 if (fmt_str == NULL)
3627 return false;
3629 if (!init_target_chars ())
3630 return false;
3632 /* If the format doesn't contain % args or %%, use strcpy. */
3633 if (strchr (fmt_str, target_percent) == NULL)
3635 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
3636 if (!fn)
3637 return false;
3639 /* Don't optimize snprintf (buf, 4, "abc", ptr++). */
3640 if (orig)
3641 return false;
3643 tree len = build_int_cstu (TREE_TYPE (destsize), strlen (fmt_str));
3645 /* We could expand this as
3646 memcpy (str, fmt, cst - 1); str[cst - 1] = '\0';
3647 or to
3648 memcpy (str, fmt_with_nul_at_cstm1, cst);
3649 but in the former case that might increase code size
3650 and in the latter case grow .rodata section too much.
3651 So punt for now. */
3652 if (!known_lower (stmt, len, destsize, true))
3653 return false;
3655 gimple_seq stmts = NULL;
3656 gimple *repl = gimple_build_call (fn, 2, dest, fmt);
3657 gimple_seq_add_stmt_without_update (&stmts, repl);
3658 if (tree lhs = gimple_call_lhs (stmt))
3660 repl = gimple_build_assign (lhs,
3661 fold_convert (TREE_TYPE (lhs), len));
3662 gimple_seq_add_stmt_without_update (&stmts, repl);
3663 gsi_replace_with_seq_vops (gsi, stmts);
3664 /* gsi now points at the assignment to the lhs, get a
3665 stmt iterator to the memcpy call.
3666 ??? We can't use gsi_for_stmt as that doesn't work when the
3667 CFG isn't built yet. */
3668 gimple_stmt_iterator gsi2 = *gsi;
3669 gsi_prev (&gsi2);
3670 fold_stmt (&gsi2);
3672 else
3674 gsi_replace_with_seq_vops (gsi, stmts);
3675 fold_stmt (gsi);
3677 return true;
3680 /* If the format is "%s", use strcpy if the result isn't used. */
3681 else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
3683 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
3684 if (!fn)
3685 return false;
3687 /* Don't crash on snprintf (str1, cst, "%s"). */
3688 if (!orig)
3689 return false;
3691 tree orig_len = get_maxval_strlen (orig, SRK_STRLEN);
3693 /* We could expand this as
3694 memcpy (str1, str2, cst - 1); str1[cst - 1] = '\0';
3695 or to
3696 memcpy (str1, str2_with_nul_at_cstm1, cst);
3697 but in the former case that might increase code size
3698 and in the latter case grow .rodata section too much.
3699 So punt for now. */
3700 if (!known_lower (stmt, orig_len, destsize, true))
3701 return false;
3703 /* Convert snprintf (str1, cst, "%s", str2) into
3704 strcpy (str1, str2) if strlen (str2) < cst. */
3705 gimple_seq stmts = NULL;
3706 gimple *repl = gimple_build_call (fn, 2, dest, orig);
3707 gimple_seq_add_stmt_without_update (&stmts, repl);
3708 if (tree lhs = gimple_call_lhs (stmt))
3710 if (!useless_type_conversion_p (TREE_TYPE (lhs),
3711 TREE_TYPE (orig_len)))
3712 orig_len = fold_convert (TREE_TYPE (lhs), orig_len);
3713 repl = gimple_build_assign (lhs, orig_len);
3714 gimple_seq_add_stmt_without_update (&stmts, repl);
3715 gsi_replace_with_seq_vops (gsi, stmts);
3716 /* gsi now points at the assignment to the lhs, get a
3717 stmt iterator to the memcpy call.
3718 ??? We can't use gsi_for_stmt as that doesn't work when the
3719 CFG isn't built yet. */
3720 gimple_stmt_iterator gsi2 = *gsi;
3721 gsi_prev (&gsi2);
3722 fold_stmt (&gsi2);
3724 else
3726 gsi_replace_with_seq_vops (gsi, stmts);
3727 fold_stmt (gsi);
3729 return true;
3731 return false;
3734 /* Fold a call to the {,v}fprintf{,_unlocked} and __{,v}printf_chk builtins.
3735 FP, FMT, and ARG are the arguments to the call. We don't fold calls with
3736 more than 3 arguments, and ARG may be null in the 2-argument case.
3738 Return NULL_TREE if no simplification was possible, otherwise return the
3739 simplified form of the call as a tree. FCODE is the BUILT_IN_*
3740 code of the function to be simplified. */
3742 static bool
3743 gimple_fold_builtin_fprintf (gimple_stmt_iterator *gsi,
3744 tree fp, tree fmt, tree arg,
3745 enum built_in_function fcode)
3747 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3748 tree fn_fputc, fn_fputs;
3749 const char *fmt_str = NULL;
3751 /* If the return value is used, don't do the transformation. */
3752 if (gimple_call_lhs (stmt) != NULL_TREE)
3753 return false;
3755 /* Check whether the format is a literal string constant. */
3756 fmt_str = c_getstr (fmt);
3757 if (fmt_str == NULL)
3758 return false;
3760 if (fcode == BUILT_IN_FPRINTF_UNLOCKED)
3762 /* If we're using an unlocked function, assume the other
3763 unlocked functions exist explicitly. */
3764 fn_fputc = builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED);
3765 fn_fputs = builtin_decl_explicit (BUILT_IN_FPUTS_UNLOCKED);
3767 else
3769 fn_fputc = builtin_decl_implicit (BUILT_IN_FPUTC);
3770 fn_fputs = builtin_decl_implicit (BUILT_IN_FPUTS);
3773 if (!init_target_chars ())
3774 return false;
3776 /* If the format doesn't contain % args or %%, use strcpy. */
3777 if (strchr (fmt_str, target_percent) == NULL)
3779 if (fcode != BUILT_IN_VFPRINTF && fcode != BUILT_IN_VFPRINTF_CHK
3780 && arg)
3781 return false;
3783 /* If the format specifier was "", fprintf does nothing. */
3784 if (fmt_str[0] == '\0')
3786 replace_call_with_value (gsi, NULL_TREE);
3787 return true;
3790 /* When "string" doesn't contain %, replace all cases of
3791 fprintf (fp, string) with fputs (string, fp). The fputs
3792 builtin will take care of special cases like length == 1. */
3793 if (fn_fputs)
3795 gcall *repl = gimple_build_call (fn_fputs, 2, fmt, fp);
3796 replace_call_with_call_and_fold (gsi, repl);
3797 return true;
3801 /* The other optimizations can be done only on the non-va_list variants. */
3802 else if (fcode == BUILT_IN_VFPRINTF || fcode == BUILT_IN_VFPRINTF_CHK)
3803 return false;
3805 /* If the format specifier was "%s", call __builtin_fputs (arg, fp). */
3806 else if (strcmp (fmt_str, target_percent_s) == 0)
3808 if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
3809 return false;
3810 if (fn_fputs)
3812 gcall *repl = gimple_build_call (fn_fputs, 2, arg, fp);
3813 replace_call_with_call_and_fold (gsi, repl);
3814 return true;
3818 /* If the format specifier was "%c", call __builtin_fputc (arg, fp). */
3819 else if (strcmp (fmt_str, target_percent_c) == 0)
3821 if (!arg
3822 || ! useless_type_conversion_p (integer_type_node, TREE_TYPE (arg)))
3823 return false;
3824 if (fn_fputc)
3826 gcall *repl = gimple_build_call (fn_fputc, 2, arg, fp);
3827 replace_call_with_call_and_fold (gsi, repl);
3828 return true;
3832 return false;
3835 /* Fold a call to the {,v}printf{,_unlocked} and __{,v}printf_chk builtins.
3836 FMT and ARG are the arguments to the call; we don't fold cases with
3837 more than 2 arguments, and ARG may be null if this is a 1-argument case.
3839 Return NULL_TREE if no simplification was possible, otherwise return the
3840 simplified form of the call as a tree. FCODE is the BUILT_IN_*
3841 code of the function to be simplified. */
3843 static bool
3844 gimple_fold_builtin_printf (gimple_stmt_iterator *gsi, tree fmt,
3845 tree arg, enum built_in_function fcode)
3847 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3848 tree fn_putchar, fn_puts, newarg;
3849 const char *fmt_str = NULL;
3851 /* If the return value is used, don't do the transformation. */
3852 if (gimple_call_lhs (stmt) != NULL_TREE)
3853 return false;
3855 /* Check whether the format is a literal string constant. */
3856 fmt_str = c_getstr (fmt);
3857 if (fmt_str == NULL)
3858 return false;
3860 if (fcode == BUILT_IN_PRINTF_UNLOCKED)
3862 /* If we're using an unlocked function, assume the other
3863 unlocked functions exist explicitly. */
3864 fn_putchar = builtin_decl_explicit (BUILT_IN_PUTCHAR_UNLOCKED);
3865 fn_puts = builtin_decl_explicit (BUILT_IN_PUTS_UNLOCKED);
3867 else
3869 fn_putchar = builtin_decl_implicit (BUILT_IN_PUTCHAR);
3870 fn_puts = builtin_decl_implicit (BUILT_IN_PUTS);
3873 if (!init_target_chars ())
3874 return false;
3876 if (strcmp (fmt_str, target_percent_s) == 0
3877 || strchr (fmt_str, target_percent) == NULL)
3879 const char *str;
3881 if (strcmp (fmt_str, target_percent_s) == 0)
3883 if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
3884 return false;
3886 if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
3887 return false;
3889 str = c_getstr (arg);
3890 if (str == NULL)
3891 return false;
3893 else
3895 /* The format specifier doesn't contain any '%' characters. */
3896 if (fcode != BUILT_IN_VPRINTF && fcode != BUILT_IN_VPRINTF_CHK
3897 && arg)
3898 return false;
3899 str = fmt_str;
3902 /* If the string was "", printf does nothing. */
3903 if (str[0] == '\0')
3905 replace_call_with_value (gsi, NULL_TREE);
3906 return true;
3909 /* If the string has length of 1, call putchar. */
3910 if (str[1] == '\0')
3912 /* Given printf("c"), (where c is any one character,)
3913 convert "c"[0] to an int and pass that to the replacement
3914 function. */
3915 newarg = build_int_cst (integer_type_node, str[0]);
3916 if (fn_putchar)
3918 gcall *repl = gimple_build_call (fn_putchar, 1, newarg);
3919 replace_call_with_call_and_fold (gsi, repl);
3920 return true;
3923 else
3925 /* If the string was "string\n", call puts("string"). */
3926 size_t len = strlen (str);
3927 if ((unsigned char)str[len - 1] == target_newline
3928 && (size_t) (int) len == len
3929 && (int) len > 0)
3931 char *newstr;
3933 /* Create a NUL-terminated string that's one char shorter
3934 than the original, stripping off the trailing '\n'. */
3935 newstr = xstrdup (str);
3936 newstr[len - 1] = '\0';
3937 newarg = build_string_literal (len, newstr);
3938 free (newstr);
3939 if (fn_puts)
3941 gcall *repl = gimple_build_call (fn_puts, 1, newarg);
3942 replace_call_with_call_and_fold (gsi, repl);
3943 return true;
3946 else
3947 /* We'd like to arrange to call fputs(string,stdout) here,
3948 but we need stdout and don't have a way to get it yet. */
3949 return false;
3953 /* The other optimizations can be done only on the non-va_list variants. */
3954 else if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
3955 return false;
3957 /* If the format specifier was "%s\n", call __builtin_puts(arg). */
3958 else if (strcmp (fmt_str, target_percent_s_newline) == 0)
3960 if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
3961 return false;
3962 if (fn_puts)
3964 gcall *repl = gimple_build_call (fn_puts, 1, arg);
3965 replace_call_with_call_and_fold (gsi, repl);
3966 return true;
3970 /* If the format specifier was "%c", call __builtin_putchar(arg). */
3971 else if (strcmp (fmt_str, target_percent_c) == 0)
3973 if (!arg || ! useless_type_conversion_p (integer_type_node,
3974 TREE_TYPE (arg)))
3975 return false;
3976 if (fn_putchar)
3978 gcall *repl = gimple_build_call (fn_putchar, 1, arg);
3979 replace_call_with_call_and_fold (gsi, repl);
3980 return true;
3984 return false;
3989 /* Fold a call to __builtin_strlen with known length LEN. */
3991 static bool
3992 gimple_fold_builtin_strlen (gimple_stmt_iterator *gsi)
3994 gimple *stmt = gsi_stmt (*gsi);
3995 tree arg = gimple_call_arg (stmt, 0);
3997 wide_int minlen;
3998 wide_int maxlen;
4000 c_strlen_data lendata = { };
4001 if (get_range_strlen (arg, &lendata, /* eltsize = */ 1)
4002 && !lendata.decl
4003 && lendata.minlen && TREE_CODE (lendata.minlen) == INTEGER_CST
4004 && lendata.maxlen && TREE_CODE (lendata.maxlen) == INTEGER_CST)
4006 /* The range of lengths refers to either a single constant
4007 string or to the longest and shortest constant string
4008 referenced by the argument of the strlen() call, or to
4009 the strings that can possibly be stored in the arrays
4010 the argument refers to. */
4011 minlen = wi::to_wide (lendata.minlen);
4012 maxlen = wi::to_wide (lendata.maxlen);
4014 else
4016 unsigned prec = TYPE_PRECISION (sizetype);
4018 minlen = wi::shwi (0, prec);
4019 maxlen = wi::to_wide (max_object_size (), prec) - 2;
4022 if (minlen == maxlen)
4024 /* Fold the strlen call to a constant. */
4025 tree type = TREE_TYPE (lendata.minlen);
4026 tree len = force_gimple_operand_gsi (gsi,
4027 wide_int_to_tree (type, minlen),
4028 true, NULL, true, GSI_SAME_STMT);
4029 replace_call_with_value (gsi, len);
4030 return true;
4033 /* Set the strlen() range to [0, MAXLEN]. */
4034 if (tree lhs = gimple_call_lhs (stmt))
4035 set_strlen_range (lhs, minlen, maxlen);
4037 return false;
4040 /* Fold a call to __builtin_acc_on_device. */
4042 static bool
4043 gimple_fold_builtin_acc_on_device (gimple_stmt_iterator *gsi, tree arg0)
4045 /* Defer folding until we know which compiler we're in. */
4046 if (symtab->state != EXPANSION)
4047 return false;
4049 unsigned val_host = GOMP_DEVICE_HOST;
4050 unsigned val_dev = GOMP_DEVICE_NONE;
4052 #ifdef ACCEL_COMPILER
4053 val_host = GOMP_DEVICE_NOT_HOST;
4054 val_dev = ACCEL_COMPILER_acc_device;
4055 #endif
4057 location_t loc = gimple_location (gsi_stmt (*gsi));
4059 tree host_eq = make_ssa_name (boolean_type_node);
4060 gimple *host_ass = gimple_build_assign
4061 (host_eq, EQ_EXPR, arg0, build_int_cst (TREE_TYPE (arg0), val_host));
4062 gimple_set_location (host_ass, loc);
4063 gsi_insert_before (gsi, host_ass, GSI_SAME_STMT);
4065 tree dev_eq = make_ssa_name (boolean_type_node);
4066 gimple *dev_ass = gimple_build_assign
4067 (dev_eq, EQ_EXPR, arg0, build_int_cst (TREE_TYPE (arg0), val_dev));
4068 gimple_set_location (dev_ass, loc);
4069 gsi_insert_before (gsi, dev_ass, GSI_SAME_STMT);
4071 tree result = make_ssa_name (boolean_type_node);
4072 gimple *result_ass = gimple_build_assign
4073 (result, BIT_IOR_EXPR, host_eq, dev_eq);
4074 gimple_set_location (result_ass, loc);
4075 gsi_insert_before (gsi, result_ass, GSI_SAME_STMT);
4077 replace_call_with_value (gsi, result);
4079 return true;
4082 /* Fold realloc (0, n) -> malloc (n). */
4084 static bool
4085 gimple_fold_builtin_realloc (gimple_stmt_iterator *gsi)
4087 gimple *stmt = gsi_stmt (*gsi);
4088 tree arg = gimple_call_arg (stmt, 0);
4089 tree size = gimple_call_arg (stmt, 1);
4091 if (operand_equal_p (arg, null_pointer_node, 0))
4093 tree fn_malloc = builtin_decl_implicit (BUILT_IN_MALLOC);
4094 if (fn_malloc)
4096 gcall *repl = gimple_build_call (fn_malloc, 1, size);
4097 replace_call_with_call_and_fold (gsi, repl);
4098 return true;
4101 return false;
4104 /* Number of bytes into which any type but aggregate or vector types
4105 should fit. */
4106 static constexpr size_t clear_padding_unit
4107 = MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT;
4108 /* Buffer size on which __builtin_clear_padding folding code works. */
4109 static const size_t clear_padding_buf_size = 32 * clear_padding_unit;
4111 /* Data passed through __builtin_clear_padding folding. */
4112 struct clear_padding_struct {
4113 location_t loc;
4114 /* 0 during __builtin_clear_padding folding, nonzero during
4115 clear_type_padding_in_mask. In that case, instead of clearing the
4116 non-padding bits in union_ptr array clear the padding bits in there. */
4117 bool clear_in_mask;
4118 tree base;
4119 tree alias_type;
4120 gimple_stmt_iterator *gsi;
4121 /* Alignment of buf->base + 0. */
4122 unsigned align;
4123 /* Offset from buf->base. Should be always a multiple of UNITS_PER_WORD. */
4124 HOST_WIDE_INT off;
4125 /* Number of padding bytes before buf->off that don't have padding clear
4126 code emitted yet. */
4127 HOST_WIDE_INT padding_bytes;
4128 /* The size of the whole object. Never emit code to touch
4129 buf->base + buf->sz or following bytes. */
4130 HOST_WIDE_INT sz;
4131 /* Number of bytes recorded in buf->buf. */
4132 size_t size;
4133 /* When inside union, instead of emitting code we and bits inside of
4134 the union_ptr array. */
4135 unsigned char *union_ptr;
4136 /* Set bits mean padding bits that need to be cleared by the builtin. */
4137 unsigned char buf[clear_padding_buf_size + clear_padding_unit];
4140 /* Emit code to clear padding requested in BUF->buf - set bits
4141 in there stand for padding that should be cleared. FULL is true
4142 if everything from the buffer should be flushed, otherwise
4143 it can leave up to 2 * clear_padding_unit bytes for further
4144 processing. */
4146 static void
4147 clear_padding_flush (clear_padding_struct *buf, bool full)
4149 gcc_assert ((clear_padding_unit % UNITS_PER_WORD) == 0);
4150 if (!full && buf->size < 2 * clear_padding_unit)
4151 return;
4152 gcc_assert ((buf->off % UNITS_PER_WORD) == 0);
4153 size_t end = buf->size;
4154 if (!full)
4155 end = ((end - clear_padding_unit - 1) / clear_padding_unit
4156 * clear_padding_unit);
4157 size_t padding_bytes = buf->padding_bytes;
4158 if (buf->union_ptr)
4160 if (buf->clear_in_mask)
4162 /* During clear_type_padding_in_mask, clear the padding
4163 bits set in buf->buf in the buf->union_ptr mask. */
4164 for (size_t i = 0; i < end; i++)
4166 if (buf->buf[i] == (unsigned char) ~0)
4167 padding_bytes++;
4168 else
4170 memset (&buf->union_ptr[buf->off + i - padding_bytes],
4171 0, padding_bytes);
4172 padding_bytes = 0;
4173 buf->union_ptr[buf->off + i] &= ~buf->buf[i];
4176 if (full)
4178 memset (&buf->union_ptr[buf->off + end - padding_bytes],
4179 0, padding_bytes);
4180 buf->off = 0;
4181 buf->size = 0;
4182 buf->padding_bytes = 0;
4184 else
4186 memmove (buf->buf, buf->buf + end, buf->size - end);
4187 buf->off += end;
4188 buf->size -= end;
4189 buf->padding_bytes = padding_bytes;
4191 return;
4193 /* Inside of a union, instead of emitting any code, instead
4194 clear all bits in the union_ptr buffer that are clear
4195 in buf. Whole padding bytes don't clear anything. */
4196 for (size_t i = 0; i < end; i++)
4198 if (buf->buf[i] == (unsigned char) ~0)
4199 padding_bytes++;
4200 else
4202 padding_bytes = 0;
4203 buf->union_ptr[buf->off + i] &= buf->buf[i];
4206 if (full)
4208 buf->off = 0;
4209 buf->size = 0;
4210 buf->padding_bytes = 0;
4212 else
4214 memmove (buf->buf, buf->buf + end, buf->size - end);
4215 buf->off += end;
4216 buf->size -= end;
4217 buf->padding_bytes = padding_bytes;
4219 return;
4221 size_t wordsize = UNITS_PER_WORD;
4222 for (size_t i = 0; i < end; i += wordsize)
4224 size_t nonzero_first = wordsize;
4225 size_t nonzero_last = 0;
4226 size_t zero_first = wordsize;
4227 size_t zero_last = 0;
4228 bool all_ones = true, bytes_only = true;
4229 if ((unsigned HOST_WIDE_INT) (buf->off + i + wordsize)
4230 > (unsigned HOST_WIDE_INT) buf->sz)
4232 gcc_assert (wordsize > 1);
4233 wordsize /= 2;
4234 i -= wordsize;
4235 continue;
4237 for (size_t j = i; j < i + wordsize && j < end; j++)
4239 if (buf->buf[j])
4241 if (nonzero_first == wordsize)
4243 nonzero_first = j - i;
4244 nonzero_last = j - i;
4246 if (nonzero_last != j - i)
4247 all_ones = false;
4248 nonzero_last = j + 1 - i;
4250 else
4252 if (zero_first == wordsize)
4253 zero_first = j - i;
4254 zero_last = j + 1 - i;
4256 if (buf->buf[j] != 0 && buf->buf[j] != (unsigned char) ~0)
4258 all_ones = false;
4259 bytes_only = false;
4262 size_t padding_end = i;
4263 if (padding_bytes)
4265 if (nonzero_first == 0
4266 && nonzero_last == wordsize
4267 && all_ones)
4269 /* All bits are padding and we had some padding
4270 before too. Just extend it. */
4271 padding_bytes += wordsize;
4272 continue;
4274 if (all_ones && nonzero_first == 0)
4276 padding_bytes += nonzero_last;
4277 padding_end += nonzero_last;
4278 nonzero_first = wordsize;
4279 nonzero_last = 0;
4281 else if (bytes_only && nonzero_first == 0)
4283 gcc_assert (zero_first && zero_first != wordsize);
4284 padding_bytes += zero_first;
4285 padding_end += zero_first;
4287 tree atype, src;
4288 if (padding_bytes == 1)
4290 atype = char_type_node;
4291 src = build_zero_cst (char_type_node);
4293 else
4295 atype = build_array_type_nelts (char_type_node, padding_bytes);
4296 src = build_constructor (atype, NULL);
4298 tree dst = build2_loc (buf->loc, MEM_REF, atype, buf->base,
4299 build_int_cst (buf->alias_type,
4300 buf->off + padding_end
4301 - padding_bytes));
4302 gimple *g = gimple_build_assign (dst, src);
4303 gimple_set_location (g, buf->loc);
4304 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4305 padding_bytes = 0;
4306 buf->padding_bytes = 0;
4308 if (nonzero_first == wordsize)
4309 /* All bits in a word are 0, there are no padding bits. */
4310 continue;
4311 if (all_ones && nonzero_last == wordsize)
4313 /* All bits between nonzero_first and end of word are padding
4314 bits, start counting padding_bytes. */
4315 padding_bytes = nonzero_last - nonzero_first;
4316 continue;
4318 if (bytes_only)
4320 /* If bitfields aren't involved in this word, prefer storing
4321 individual bytes or groups of them over performing a RMW
4322 operation on the whole word. */
4323 gcc_assert (i + zero_last <= end);
4324 for (size_t j = padding_end; j < i + zero_last; j++)
4326 if (buf->buf[j])
4328 size_t k;
4329 for (k = j; k < i + zero_last; k++)
4330 if (buf->buf[k] == 0)
4331 break;
4332 HOST_WIDE_INT off = buf->off + j;
4333 tree atype, src;
4334 if (k - j == 1)
4336 atype = char_type_node;
4337 src = build_zero_cst (char_type_node);
4339 else
4341 atype = build_array_type_nelts (char_type_node, k - j);
4342 src = build_constructor (atype, NULL);
4344 tree dst = build2_loc (buf->loc, MEM_REF, atype,
4345 buf->base,
4346 build_int_cst (buf->alias_type, off));
4347 gimple *g = gimple_build_assign (dst, src);
4348 gimple_set_location (g, buf->loc);
4349 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4350 j = k;
4353 if (nonzero_last == wordsize)
4354 padding_bytes = nonzero_last - zero_last;
4355 continue;
4357 for (size_t eltsz = 1; eltsz <= wordsize; eltsz <<= 1)
4359 if (nonzero_last - nonzero_first <= eltsz
4360 && ((nonzero_first & ~(eltsz - 1))
4361 == ((nonzero_last - 1) & ~(eltsz - 1))))
4363 tree type;
4364 if (eltsz == 1)
4365 type = char_type_node;
4366 else
4367 type = lang_hooks.types.type_for_size (eltsz * BITS_PER_UNIT,
4369 size_t start = nonzero_first & ~(eltsz - 1);
4370 HOST_WIDE_INT off = buf->off + i + start;
4371 tree atype = type;
4372 if (eltsz > 1 && buf->align < TYPE_ALIGN (type))
4373 atype = build_aligned_type (type, buf->align);
4374 tree dst = build2_loc (buf->loc, MEM_REF, atype, buf->base,
4375 build_int_cst (buf->alias_type, off));
4376 tree src;
4377 gimple *g;
4378 if (all_ones
4379 && nonzero_first == start
4380 && nonzero_last == start + eltsz)
4381 src = build_zero_cst (type);
4382 else
4384 src = make_ssa_name (type);
4385 tree tmp_dst = unshare_expr (dst);
4386 /* The folding introduces a read from the tmp_dst, we should
4387 prevent uninitialized warning analysis from issuing warning
4388 for such fake read. In order to suppress warning only for
4389 this expr, we should set the location of tmp_dst to
4390 UNKNOWN_LOCATION first, then suppress_warning will call
4391 set_no_warning_bit to set the no_warning flag only for
4392 tmp_dst. */
4393 SET_EXPR_LOCATION (tmp_dst, UNKNOWN_LOCATION);
4394 suppress_warning (tmp_dst, OPT_Wuninitialized);
4395 g = gimple_build_assign (src, tmp_dst);
4396 gimple_set_location (g, buf->loc);
4397 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4398 tree mask = native_interpret_expr (type,
4399 buf->buf + i + start,
4400 eltsz);
4401 gcc_assert (mask && TREE_CODE (mask) == INTEGER_CST);
4402 mask = fold_build1 (BIT_NOT_EXPR, type, mask);
4403 tree src_masked = make_ssa_name (type);
4404 g = gimple_build_assign (src_masked, BIT_AND_EXPR,
4405 src, mask);
4406 gimple_set_location (g, buf->loc);
4407 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4408 src = src_masked;
4410 g = gimple_build_assign (dst, src);
4411 gimple_set_location (g, buf->loc);
4412 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4413 break;
4417 if (full)
4419 if (padding_bytes)
4421 tree atype, src;
4422 if (padding_bytes == 1)
4424 atype = char_type_node;
4425 src = build_zero_cst (char_type_node);
4427 else
4429 atype = build_array_type_nelts (char_type_node, padding_bytes);
4430 src = build_constructor (atype, NULL);
4432 tree dst = build2_loc (buf->loc, MEM_REF, atype, buf->base,
4433 build_int_cst (buf->alias_type,
4434 buf->off + end
4435 - padding_bytes));
4436 gimple *g = gimple_build_assign (dst, src);
4437 gimple_set_location (g, buf->loc);
4438 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4440 size_t end_rem = end % UNITS_PER_WORD;
4441 buf->off += end - end_rem;
4442 buf->size = end_rem;
4443 memset (buf->buf, 0, buf->size);
4444 buf->padding_bytes = 0;
4446 else
4448 memmove (buf->buf, buf->buf + end, buf->size - end);
4449 buf->off += end;
4450 buf->size -= end;
4451 buf->padding_bytes = padding_bytes;
4455 /* Append PADDING_BYTES padding bytes. */
4457 static void
4458 clear_padding_add_padding (clear_padding_struct *buf,
4459 HOST_WIDE_INT padding_bytes)
4461 if (padding_bytes == 0)
4462 return;
4463 if ((unsigned HOST_WIDE_INT) padding_bytes + buf->size
4464 > (unsigned HOST_WIDE_INT) clear_padding_buf_size)
4465 clear_padding_flush (buf, false);
4466 if ((unsigned HOST_WIDE_INT) padding_bytes + buf->size
4467 > (unsigned HOST_WIDE_INT) clear_padding_buf_size)
4469 memset (buf->buf + buf->size, ~0, clear_padding_buf_size - buf->size);
4470 padding_bytes -= clear_padding_buf_size - buf->size;
4471 buf->size = clear_padding_buf_size;
4472 clear_padding_flush (buf, false);
4473 gcc_assert (buf->padding_bytes);
4474 /* At this point buf->buf[0] through buf->buf[buf->size - 1]
4475 is guaranteed to be all ones. */
4476 padding_bytes += buf->size;
4477 buf->size = padding_bytes % UNITS_PER_WORD;
4478 memset (buf->buf, ~0, buf->size);
4479 buf->off += padding_bytes - buf->size;
4480 buf->padding_bytes += padding_bytes - buf->size;
4482 else
4484 memset (buf->buf + buf->size, ~0, padding_bytes);
4485 buf->size += padding_bytes;
4489 static void clear_padding_type (clear_padding_struct *, tree,
4490 HOST_WIDE_INT, bool);
4492 /* Clear padding bits of union type TYPE. */
4494 static void
4495 clear_padding_union (clear_padding_struct *buf, tree type,
4496 HOST_WIDE_INT sz, bool for_auto_init)
4498 clear_padding_struct *union_buf;
4499 HOST_WIDE_INT start_off = 0, next_off = 0;
4500 size_t start_size = 0;
4501 if (buf->union_ptr)
4503 start_off = buf->off + buf->size;
4504 next_off = start_off + sz;
4505 start_size = start_off % UNITS_PER_WORD;
4506 start_off -= start_size;
4507 clear_padding_flush (buf, true);
4508 union_buf = buf;
4510 else
4512 if (sz + buf->size > clear_padding_buf_size)
4513 clear_padding_flush (buf, false);
4514 union_buf = XALLOCA (clear_padding_struct);
4515 union_buf->loc = buf->loc;
4516 union_buf->clear_in_mask = buf->clear_in_mask;
4517 union_buf->base = NULL_TREE;
4518 union_buf->alias_type = NULL_TREE;
4519 union_buf->gsi = NULL;
4520 union_buf->align = 0;
4521 union_buf->off = 0;
4522 union_buf->padding_bytes = 0;
4523 union_buf->sz = sz;
4524 union_buf->size = 0;
4525 if (sz + buf->size <= clear_padding_buf_size)
4526 union_buf->union_ptr = buf->buf + buf->size;
4527 else
4528 union_buf->union_ptr = XNEWVEC (unsigned char, sz);
4529 memset (union_buf->union_ptr, ~0, sz);
4532 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
4533 if (TREE_CODE (field) == FIELD_DECL && !DECL_PADDING_P (field))
4535 if (DECL_SIZE_UNIT (field) == NULL_TREE)
4537 if (TREE_TYPE (field) == error_mark_node)
4538 continue;
4539 gcc_assert (TREE_CODE (TREE_TYPE (field)) == ARRAY_TYPE
4540 && !COMPLETE_TYPE_P (TREE_TYPE (field)));
4541 if (!buf->clear_in_mask && !for_auto_init)
4542 error_at (buf->loc, "flexible array member %qD does not have "
4543 "well defined padding bits for %qs",
4544 field, "__builtin_clear_padding");
4545 continue;
4547 HOST_WIDE_INT fldsz = tree_to_shwi (DECL_SIZE_UNIT (field));
4548 gcc_assert (union_buf->size == 0);
4549 union_buf->off = start_off;
4550 union_buf->size = start_size;
4551 memset (union_buf->buf, ~0, start_size);
4552 clear_padding_type (union_buf, TREE_TYPE (field), fldsz, for_auto_init);
4553 clear_padding_add_padding (union_buf, sz - fldsz);
4554 clear_padding_flush (union_buf, true);
4557 if (buf == union_buf)
4559 buf->off = next_off;
4560 buf->size = next_off % UNITS_PER_WORD;
4561 buf->off -= buf->size;
4562 memset (buf->buf, ~0, buf->size);
4564 else if (sz + buf->size <= clear_padding_buf_size)
4565 buf->size += sz;
4566 else
4568 unsigned char *union_ptr = union_buf->union_ptr;
4569 while (sz)
4571 clear_padding_flush (buf, false);
4572 HOST_WIDE_INT this_sz
4573 = MIN ((unsigned HOST_WIDE_INT) sz,
4574 clear_padding_buf_size - buf->size);
4575 memcpy (buf->buf + buf->size, union_ptr, this_sz);
4576 buf->size += this_sz;
4577 union_ptr += this_sz;
4578 sz -= this_sz;
4580 XDELETE (union_buf->union_ptr);
4584 /* The only known floating point formats with padding bits are the
4585 IEEE extended ones. */
4587 static bool
4588 clear_padding_real_needs_padding_p (tree type)
4590 const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
4591 return (fmt->b == 2
4592 && fmt->signbit_ro == fmt->signbit_rw
4593 && (fmt->signbit_ro == 79 || fmt->signbit_ro == 95));
4596 /* Return true if TYPE might contain any padding bits. */
4598 bool
4599 clear_padding_type_may_have_padding_p (tree type)
4601 switch (TREE_CODE (type))
4603 case RECORD_TYPE:
4604 case UNION_TYPE:
4605 return true;
4606 case ARRAY_TYPE:
4607 case COMPLEX_TYPE:
4608 case VECTOR_TYPE:
4609 return clear_padding_type_may_have_padding_p (TREE_TYPE (type));
4610 case REAL_TYPE:
4611 return clear_padding_real_needs_padding_p (type);
4612 default:
4613 return false;
4617 /* Emit a runtime loop:
4618 for (; buf.base != end; buf.base += sz)
4619 __builtin_clear_padding (buf.base); */
4621 static void
4622 clear_padding_emit_loop (clear_padding_struct *buf, tree type,
4623 tree end, bool for_auto_init)
4625 tree l1 = create_artificial_label (buf->loc);
4626 tree l2 = create_artificial_label (buf->loc);
4627 tree l3 = create_artificial_label (buf->loc);
4628 gimple *g = gimple_build_goto (l2);
4629 gimple_set_location (g, buf->loc);
4630 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4631 g = gimple_build_label (l1);
4632 gimple_set_location (g, buf->loc);
4633 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4634 clear_padding_type (buf, type, buf->sz, for_auto_init);
4635 clear_padding_flush (buf, true);
4636 g = gimple_build_assign (buf->base, POINTER_PLUS_EXPR, buf->base,
4637 size_int (buf->sz));
4638 gimple_set_location (g, buf->loc);
4639 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4640 g = gimple_build_label (l2);
4641 gimple_set_location (g, buf->loc);
4642 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4643 g = gimple_build_cond (NE_EXPR, buf->base, end, l1, l3);
4644 gimple_set_location (g, buf->loc);
4645 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4646 g = gimple_build_label (l3);
4647 gimple_set_location (g, buf->loc);
4648 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4651 /* Clear padding bits for TYPE. Called recursively from
4652 gimple_fold_builtin_clear_padding. If FOR_AUTO_INIT is true,
4653 the __builtin_clear_padding is not called by the end user,
4654 instead, it's inserted by the compiler to initialize the
4655 paddings of automatic variable. Therefore, we should not
4656 emit the error messages for flexible array members to confuse
4657 the end user. */
4659 static void
4660 clear_padding_type (clear_padding_struct *buf, tree type,
4661 HOST_WIDE_INT sz, bool for_auto_init)
4663 switch (TREE_CODE (type))
4665 case RECORD_TYPE:
4666 HOST_WIDE_INT cur_pos;
4667 cur_pos = 0;
4668 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
4669 if (TREE_CODE (field) == FIELD_DECL && !DECL_PADDING_P (field))
4671 tree ftype = TREE_TYPE (field);
4672 if (DECL_BIT_FIELD (field))
4674 HOST_WIDE_INT fldsz = TYPE_PRECISION (ftype);
4675 if (fldsz == 0)
4676 continue;
4677 HOST_WIDE_INT pos = int_byte_position (field);
4678 if (pos >= sz)
4679 continue;
4680 HOST_WIDE_INT bpos
4681 = tree_to_uhwi (DECL_FIELD_BIT_OFFSET (field));
4682 bpos %= BITS_PER_UNIT;
4683 HOST_WIDE_INT end
4684 = ROUND_UP (bpos + fldsz, BITS_PER_UNIT) / BITS_PER_UNIT;
4685 if (pos + end > cur_pos)
4687 clear_padding_add_padding (buf, pos + end - cur_pos);
4688 cur_pos = pos + end;
4690 gcc_assert (cur_pos > pos
4691 && ((unsigned HOST_WIDE_INT) buf->size
4692 >= (unsigned HOST_WIDE_INT) cur_pos - pos));
4693 unsigned char *p = buf->buf + buf->size - (cur_pos - pos);
4694 if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN)
4695 sorry_at (buf->loc, "PDP11 bit-field handling unsupported"
4696 " in %qs", "__builtin_clear_padding");
4697 else if (BYTES_BIG_ENDIAN)
4699 /* Big endian. */
4700 if (bpos + fldsz <= BITS_PER_UNIT)
4701 *p &= ~(((1 << fldsz) - 1)
4702 << (BITS_PER_UNIT - bpos - fldsz));
4703 else
4705 if (bpos)
4707 *p &= ~(((1U << BITS_PER_UNIT) - 1) >> bpos);
4708 p++;
4709 fldsz -= BITS_PER_UNIT - bpos;
4711 memset (p, 0, fldsz / BITS_PER_UNIT);
4712 p += fldsz / BITS_PER_UNIT;
4713 fldsz %= BITS_PER_UNIT;
4714 if (fldsz)
4715 *p &= ((1U << BITS_PER_UNIT) - 1) >> fldsz;
4718 else
4720 /* Little endian. */
4721 if (bpos + fldsz <= BITS_PER_UNIT)
4722 *p &= ~(((1 << fldsz) - 1) << bpos);
4723 else
4725 if (bpos)
4727 *p &= ~(((1 << BITS_PER_UNIT) - 1) << bpos);
4728 p++;
4729 fldsz -= BITS_PER_UNIT - bpos;
4731 memset (p, 0, fldsz / BITS_PER_UNIT);
4732 p += fldsz / BITS_PER_UNIT;
4733 fldsz %= BITS_PER_UNIT;
4734 if (fldsz)
4735 *p &= ~((1 << fldsz) - 1);
4739 else if (DECL_SIZE_UNIT (field) == NULL_TREE)
4741 if (ftype == error_mark_node)
4742 continue;
4743 gcc_assert (TREE_CODE (ftype) == ARRAY_TYPE
4744 && !COMPLETE_TYPE_P (ftype));
4745 if (!buf->clear_in_mask && !for_auto_init)
4746 error_at (buf->loc, "flexible array member %qD does not "
4747 "have well defined padding bits for %qs",
4748 field, "__builtin_clear_padding");
4750 else if (is_empty_type (ftype))
4751 continue;
4752 else
4754 HOST_WIDE_INT pos = int_byte_position (field);
4755 if (pos >= sz)
4756 continue;
4757 HOST_WIDE_INT fldsz = tree_to_shwi (DECL_SIZE_UNIT (field));
4758 gcc_assert (pos >= 0 && fldsz >= 0 && pos >= cur_pos);
4759 clear_padding_add_padding (buf, pos - cur_pos);
4760 cur_pos = pos;
4761 if (tree asbase = lang_hooks.types.classtype_as_base (field))
4762 ftype = asbase;
4763 clear_padding_type (buf, ftype, fldsz, for_auto_init);
4764 cur_pos += fldsz;
4767 gcc_assert (sz >= cur_pos);
4768 clear_padding_add_padding (buf, sz - cur_pos);
4769 break;
4770 case ARRAY_TYPE:
4771 HOST_WIDE_INT nelts, fldsz;
4772 fldsz = int_size_in_bytes (TREE_TYPE (type));
4773 if (fldsz == 0)
4774 break;
4775 nelts = sz / fldsz;
4776 if (nelts > 1
4777 && sz > 8 * UNITS_PER_WORD
4778 && buf->union_ptr == NULL
4779 && clear_padding_type_may_have_padding_p (TREE_TYPE (type)))
4781 /* For sufficiently large array of more than one elements,
4782 emit a runtime loop to keep code size manageable. */
4783 tree base = buf->base;
4784 unsigned int prev_align = buf->align;
4785 HOST_WIDE_INT off = buf->off + buf->size;
4786 HOST_WIDE_INT prev_sz = buf->sz;
4787 clear_padding_flush (buf, true);
4788 tree elttype = TREE_TYPE (type);
4789 buf->base = create_tmp_var (build_pointer_type (elttype));
4790 tree end = make_ssa_name (TREE_TYPE (buf->base));
4791 gimple *g = gimple_build_assign (buf->base, POINTER_PLUS_EXPR,
4792 base, size_int (off));
4793 gimple_set_location (g, buf->loc);
4794 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4795 g = gimple_build_assign (end, POINTER_PLUS_EXPR, buf->base,
4796 size_int (sz));
4797 gimple_set_location (g, buf->loc);
4798 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4799 buf->sz = fldsz;
4800 buf->align = TYPE_ALIGN (elttype);
4801 buf->off = 0;
4802 buf->size = 0;
4803 clear_padding_emit_loop (buf, elttype, end, for_auto_init);
4804 buf->base = base;
4805 buf->sz = prev_sz;
4806 buf->align = prev_align;
4807 buf->size = off % UNITS_PER_WORD;
4808 buf->off = off - buf->size;
4809 memset (buf->buf, 0, buf->size);
4810 break;
4812 for (HOST_WIDE_INT i = 0; i < nelts; i++)
4813 clear_padding_type (buf, TREE_TYPE (type), fldsz, for_auto_init);
4814 break;
4815 case UNION_TYPE:
4816 clear_padding_union (buf, type, sz, for_auto_init);
4817 break;
4818 case REAL_TYPE:
4819 gcc_assert ((size_t) sz <= clear_padding_unit);
4820 if ((unsigned HOST_WIDE_INT) sz + buf->size > clear_padding_buf_size)
4821 clear_padding_flush (buf, false);
4822 if (clear_padding_real_needs_padding_p (type))
4824 /* Use native_interpret_real + native_encode_expr to figure out
4825 which bits are padding. */
4826 memset (buf->buf + buf->size, ~0, sz);
4827 tree cst = native_interpret_real (type, buf->buf + buf->size, sz);
4828 gcc_assert (cst && TREE_CODE (cst) == REAL_CST);
4829 int len = native_encode_expr (cst, buf->buf + buf->size, sz);
4830 gcc_assert (len > 0 && (size_t) len == (size_t) sz);
4831 for (size_t i = 0; i < (size_t) sz; i++)
4832 buf->buf[buf->size + i] ^= ~0;
4834 else
4835 memset (buf->buf + buf->size, 0, sz);
4836 buf->size += sz;
4837 break;
4838 case COMPLEX_TYPE:
4839 fldsz = int_size_in_bytes (TREE_TYPE (type));
4840 clear_padding_type (buf, TREE_TYPE (type), fldsz, for_auto_init);
4841 clear_padding_type (buf, TREE_TYPE (type), fldsz, for_auto_init);
4842 break;
4843 case VECTOR_TYPE:
4844 nelts = TYPE_VECTOR_SUBPARTS (type).to_constant ();
4845 fldsz = int_size_in_bytes (TREE_TYPE (type));
4846 for (HOST_WIDE_INT i = 0; i < nelts; i++)
4847 clear_padding_type (buf, TREE_TYPE (type), fldsz, for_auto_init);
4848 break;
4849 case NULLPTR_TYPE:
4850 gcc_assert ((size_t) sz <= clear_padding_unit);
4851 if ((unsigned HOST_WIDE_INT) sz + buf->size > clear_padding_buf_size)
4852 clear_padding_flush (buf, false);
4853 memset (buf->buf + buf->size, ~0, sz);
4854 buf->size += sz;
4855 break;
4856 default:
4857 gcc_assert ((size_t) sz <= clear_padding_unit);
4858 if ((unsigned HOST_WIDE_INT) sz + buf->size > clear_padding_buf_size)
4859 clear_padding_flush (buf, false);
4860 memset (buf->buf + buf->size, 0, sz);
4861 buf->size += sz;
4862 break;
4866 /* Clear padding bits of TYPE in MASK. */
4868 void
4869 clear_type_padding_in_mask (tree type, unsigned char *mask)
4871 clear_padding_struct buf;
4872 buf.loc = UNKNOWN_LOCATION;
4873 buf.clear_in_mask = true;
4874 buf.base = NULL_TREE;
4875 buf.alias_type = NULL_TREE;
4876 buf.gsi = NULL;
4877 buf.align = 0;
4878 buf.off = 0;
4879 buf.padding_bytes = 0;
4880 buf.sz = int_size_in_bytes (type);
4881 buf.size = 0;
4882 buf.union_ptr = mask;
4883 clear_padding_type (&buf, type, buf.sz, false);
4884 clear_padding_flush (&buf, true);
4887 /* Fold __builtin_clear_padding builtin. */
4889 static bool
4890 gimple_fold_builtin_clear_padding (gimple_stmt_iterator *gsi)
4892 gimple *stmt = gsi_stmt (*gsi);
4893 gcc_assert (gimple_call_num_args (stmt) == 2);
4894 tree ptr = gimple_call_arg (stmt, 0);
4895 tree typearg = gimple_call_arg (stmt, 1);
4896 /* The 2nd argument of __builtin_clear_padding's value is used to
4897 distinguish whether this call is made by the user or by the compiler
4898 for automatic variable initialization. */
4899 bool for_auto_init = (bool) TREE_INT_CST_LOW (typearg);
4900 tree type = TREE_TYPE (TREE_TYPE (typearg));
4901 location_t loc = gimple_location (stmt);
4902 clear_padding_struct buf;
4903 gimple_stmt_iterator gsiprev = *gsi;
4904 /* This should be folded during the lower pass. */
4905 gcc_assert (!gimple_in_ssa_p (cfun) && cfun->cfg == NULL);
4906 gcc_assert (COMPLETE_TYPE_P (type));
4907 gsi_prev (&gsiprev);
4909 buf.loc = loc;
4910 buf.clear_in_mask = false;
4911 buf.base = ptr;
4912 buf.alias_type = NULL_TREE;
4913 buf.gsi = gsi;
4914 buf.align = get_pointer_alignment (ptr);
4915 unsigned int talign = min_align_of_type (type) * BITS_PER_UNIT;
4916 buf.align = MAX (buf.align, talign);
4917 buf.off = 0;
4918 buf.padding_bytes = 0;
4919 buf.size = 0;
4920 buf.sz = int_size_in_bytes (type);
4921 buf.union_ptr = NULL;
4922 if (buf.sz < 0 && int_size_in_bytes (strip_array_types (type)) < 0)
4923 sorry_at (loc, "%s not supported for variable length aggregates",
4924 "__builtin_clear_padding");
4925 /* The implementation currently assumes 8-bit host and target
4926 chars which is the case for all currently supported targets
4927 and hosts and is required e.g. for native_{encode,interpret}* APIs. */
4928 else if (CHAR_BIT != 8 || BITS_PER_UNIT != 8)
4929 sorry_at (loc, "%s not supported on this target",
4930 "__builtin_clear_padding");
4931 else if (!clear_padding_type_may_have_padding_p (type))
4933 else if (TREE_CODE (type) == ARRAY_TYPE && buf.sz < 0)
4935 tree sz = TYPE_SIZE_UNIT (type);
4936 tree elttype = type;
4937 /* Only supports C/C++ VLAs and flattens all the VLA levels. */
4938 while (TREE_CODE (elttype) == ARRAY_TYPE
4939 && int_size_in_bytes (elttype) < 0)
4940 elttype = TREE_TYPE (elttype);
4941 HOST_WIDE_INT eltsz = int_size_in_bytes (elttype);
4942 gcc_assert (eltsz >= 0);
4943 if (eltsz)
4945 buf.base = create_tmp_var (build_pointer_type (elttype));
4946 tree end = make_ssa_name (TREE_TYPE (buf.base));
4947 gimple *g = gimple_build_assign (buf.base, ptr);
4948 gimple_set_location (g, loc);
4949 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4950 g = gimple_build_assign (end, POINTER_PLUS_EXPR, buf.base, sz);
4951 gimple_set_location (g, loc);
4952 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4953 buf.sz = eltsz;
4954 buf.align = TYPE_ALIGN (elttype);
4955 buf.alias_type = build_pointer_type (elttype);
4956 clear_padding_emit_loop (&buf, elttype, end, for_auto_init);
4959 else
4961 if (!is_gimple_mem_ref_addr (buf.base))
4963 buf.base = make_ssa_name (TREE_TYPE (ptr));
4964 gimple *g = gimple_build_assign (buf.base, ptr);
4965 gimple_set_location (g, loc);
4966 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4968 buf.alias_type = build_pointer_type (type);
4969 clear_padding_type (&buf, type, buf.sz, for_auto_init);
4970 clear_padding_flush (&buf, true);
4973 gimple_stmt_iterator gsiprev2 = *gsi;
4974 gsi_prev (&gsiprev2);
4975 if (gsi_stmt (gsiprev) == gsi_stmt (gsiprev2))
4976 gsi_replace (gsi, gimple_build_nop (), true);
4977 else
4979 gsi_remove (gsi, true);
4980 *gsi = gsiprev2;
4982 return true;
4985 /* Fold the non-target builtin at *GSI and return whether any simplification
4986 was made. */
4988 static bool
4989 gimple_fold_builtin (gimple_stmt_iterator *gsi)
4991 gcall *stmt = as_a <gcall *>(gsi_stmt (*gsi));
4992 tree callee = gimple_call_fndecl (stmt);
4994 /* Give up for always_inline inline builtins until they are
4995 inlined. */
4996 if (avoid_folding_inline_builtin (callee))
4997 return false;
4999 unsigned n = gimple_call_num_args (stmt);
5000 enum built_in_function fcode = DECL_FUNCTION_CODE (callee);
5001 switch (fcode)
5003 case BUILT_IN_BCMP:
5004 return gimple_fold_builtin_bcmp (gsi);
5005 case BUILT_IN_BCOPY:
5006 return gimple_fold_builtin_bcopy (gsi);
5007 case BUILT_IN_BZERO:
5008 return gimple_fold_builtin_bzero (gsi);
5010 case BUILT_IN_MEMSET:
5011 return gimple_fold_builtin_memset (gsi,
5012 gimple_call_arg (stmt, 1),
5013 gimple_call_arg (stmt, 2));
5014 case BUILT_IN_MEMCPY:
5015 case BUILT_IN_MEMPCPY:
5016 case BUILT_IN_MEMMOVE:
5017 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
5018 gimple_call_arg (stmt, 1), fcode);
5019 case BUILT_IN_SPRINTF_CHK:
5020 case BUILT_IN_VSPRINTF_CHK:
5021 return gimple_fold_builtin_sprintf_chk (gsi, fcode);
5022 case BUILT_IN_STRCAT_CHK:
5023 return gimple_fold_builtin_strcat_chk (gsi);
5024 case BUILT_IN_STRNCAT_CHK:
5025 return gimple_fold_builtin_strncat_chk (gsi);
5026 case BUILT_IN_STRLEN:
5027 return gimple_fold_builtin_strlen (gsi);
5028 case BUILT_IN_STRCPY:
5029 return gimple_fold_builtin_strcpy (gsi,
5030 gimple_call_arg (stmt, 0),
5031 gimple_call_arg (stmt, 1));
5032 case BUILT_IN_STRNCPY:
5033 return gimple_fold_builtin_strncpy (gsi,
5034 gimple_call_arg (stmt, 0),
5035 gimple_call_arg (stmt, 1),
5036 gimple_call_arg (stmt, 2));
5037 case BUILT_IN_STRCAT:
5038 return gimple_fold_builtin_strcat (gsi, gimple_call_arg (stmt, 0),
5039 gimple_call_arg (stmt, 1));
5040 case BUILT_IN_STRNCAT:
5041 return gimple_fold_builtin_strncat (gsi);
5042 case BUILT_IN_INDEX:
5043 case BUILT_IN_STRCHR:
5044 return gimple_fold_builtin_strchr (gsi, false);
5045 case BUILT_IN_RINDEX:
5046 case BUILT_IN_STRRCHR:
5047 return gimple_fold_builtin_strchr (gsi, true);
5048 case BUILT_IN_STRSTR:
5049 return gimple_fold_builtin_strstr (gsi);
5050 case BUILT_IN_STRCMP:
5051 case BUILT_IN_STRCMP_EQ:
5052 case BUILT_IN_STRCASECMP:
5053 case BUILT_IN_STRNCMP:
5054 case BUILT_IN_STRNCMP_EQ:
5055 case BUILT_IN_STRNCASECMP:
5056 return gimple_fold_builtin_string_compare (gsi);
5057 case BUILT_IN_MEMCHR:
5058 return gimple_fold_builtin_memchr (gsi);
5059 case BUILT_IN_FPUTS:
5060 return gimple_fold_builtin_fputs (gsi, gimple_call_arg (stmt, 0),
5061 gimple_call_arg (stmt, 1), false);
5062 case BUILT_IN_FPUTS_UNLOCKED:
5063 return gimple_fold_builtin_fputs (gsi, gimple_call_arg (stmt, 0),
5064 gimple_call_arg (stmt, 1), true);
5065 case BUILT_IN_MEMCPY_CHK:
5066 case BUILT_IN_MEMPCPY_CHK:
5067 case BUILT_IN_MEMMOVE_CHK:
5068 case BUILT_IN_MEMSET_CHK:
5069 return gimple_fold_builtin_memory_chk (gsi,
5070 gimple_call_arg (stmt, 0),
5071 gimple_call_arg (stmt, 1),
5072 gimple_call_arg (stmt, 2),
5073 gimple_call_arg (stmt, 3),
5074 fcode);
5075 case BUILT_IN_STPCPY:
5076 return gimple_fold_builtin_stpcpy (gsi);
5077 case BUILT_IN_STRCPY_CHK:
5078 case BUILT_IN_STPCPY_CHK:
5079 return gimple_fold_builtin_stxcpy_chk (gsi,
5080 gimple_call_arg (stmt, 0),
5081 gimple_call_arg (stmt, 1),
5082 gimple_call_arg (stmt, 2),
5083 fcode);
5084 case BUILT_IN_STRNCPY_CHK:
5085 case BUILT_IN_STPNCPY_CHK:
5086 return gimple_fold_builtin_stxncpy_chk (gsi,
5087 gimple_call_arg (stmt, 0),
5088 gimple_call_arg (stmt, 1),
5089 gimple_call_arg (stmt, 2),
5090 gimple_call_arg (stmt, 3),
5091 fcode);
5092 case BUILT_IN_SNPRINTF_CHK:
5093 case BUILT_IN_VSNPRINTF_CHK:
5094 return gimple_fold_builtin_snprintf_chk (gsi, fcode);
5096 case BUILT_IN_FPRINTF:
5097 case BUILT_IN_FPRINTF_UNLOCKED:
5098 case BUILT_IN_VFPRINTF:
5099 if (n == 2 || n == 3)
5100 return gimple_fold_builtin_fprintf (gsi,
5101 gimple_call_arg (stmt, 0),
5102 gimple_call_arg (stmt, 1),
5103 n == 3
5104 ? gimple_call_arg (stmt, 2)
5105 : NULL_TREE,
5106 fcode);
5107 break;
5108 case BUILT_IN_FPRINTF_CHK:
5109 case BUILT_IN_VFPRINTF_CHK:
5110 if (n == 3 || n == 4)
5111 return gimple_fold_builtin_fprintf (gsi,
5112 gimple_call_arg (stmt, 0),
5113 gimple_call_arg (stmt, 2),
5114 n == 4
5115 ? gimple_call_arg (stmt, 3)
5116 : NULL_TREE,
5117 fcode);
5118 break;
5119 case BUILT_IN_PRINTF:
5120 case BUILT_IN_PRINTF_UNLOCKED:
5121 case BUILT_IN_VPRINTF:
5122 if (n == 1 || n == 2)
5123 return gimple_fold_builtin_printf (gsi, gimple_call_arg (stmt, 0),
5124 n == 2
5125 ? gimple_call_arg (stmt, 1)
5126 : NULL_TREE, fcode);
5127 break;
5128 case BUILT_IN_PRINTF_CHK:
5129 case BUILT_IN_VPRINTF_CHK:
5130 if (n == 2 || n == 3)
5131 return gimple_fold_builtin_printf (gsi, gimple_call_arg (stmt, 1),
5132 n == 3
5133 ? gimple_call_arg (stmt, 2)
5134 : NULL_TREE, fcode);
5135 break;
5136 case BUILT_IN_ACC_ON_DEVICE:
5137 return gimple_fold_builtin_acc_on_device (gsi,
5138 gimple_call_arg (stmt, 0));
5139 case BUILT_IN_REALLOC:
5140 return gimple_fold_builtin_realloc (gsi);
5142 case BUILT_IN_CLEAR_PADDING:
5143 return gimple_fold_builtin_clear_padding (gsi);
5145 default:;
5148 /* Try the generic builtin folder. */
5149 bool ignore = (gimple_call_lhs (stmt) == NULL);
5150 tree result = fold_call_stmt (stmt, ignore);
5151 if (result)
5153 if (ignore)
5154 STRIP_NOPS (result);
5155 else
5156 result = fold_convert (gimple_call_return_type (stmt), result);
5157 gimplify_and_update_call_from_tree (gsi, result);
5158 return true;
5161 return false;
5164 /* Transform IFN_GOACC_DIM_SIZE and IFN_GOACC_DIM_POS internal
5165 function calls to constants, where possible. */
5167 static tree
5168 fold_internal_goacc_dim (const gimple *call)
5170 int axis = oacc_get_ifn_dim_arg (call);
5171 int size = oacc_get_fn_dim_size (current_function_decl, axis);
5172 tree result = NULL_TREE;
5173 tree type = TREE_TYPE (gimple_call_lhs (call));
5175 switch (gimple_call_internal_fn (call))
5177 case IFN_GOACC_DIM_POS:
5178 /* If the size is 1, we know the answer. */
5179 if (size == 1)
5180 result = build_int_cst (type, 0);
5181 break;
5182 case IFN_GOACC_DIM_SIZE:
5183 /* If the size is not dynamic, we know the answer. */
5184 if (size)
5185 result = build_int_cst (type, size);
5186 break;
5187 default:
5188 break;
5191 return result;
5194 /* Return true if stmt is __atomic_compare_exchange_N call which is suitable
5195 for conversion into ATOMIC_COMPARE_EXCHANGE if the second argument is
5196 &var where var is only addressable because of such calls. */
5198 bool
5199 optimize_atomic_compare_exchange_p (gimple *stmt)
5201 if (gimple_call_num_args (stmt) != 6
5202 || !flag_inline_atomics
5203 || !optimize
5204 || sanitize_flags_p (SANITIZE_THREAD | SANITIZE_ADDRESS)
5205 || !gimple_call_builtin_p (stmt, BUILT_IN_NORMAL)
5206 || !gimple_vdef (stmt)
5207 || !gimple_vuse (stmt))
5208 return false;
5210 tree fndecl = gimple_call_fndecl (stmt);
5211 switch (DECL_FUNCTION_CODE (fndecl))
5213 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1:
5214 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2:
5215 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4:
5216 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8:
5217 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16:
5218 break;
5219 default:
5220 return false;
5223 tree expected = gimple_call_arg (stmt, 1);
5224 if (TREE_CODE (expected) != ADDR_EXPR
5225 || !SSA_VAR_P (TREE_OPERAND (expected, 0)))
5226 return false;
5228 tree etype = TREE_TYPE (TREE_OPERAND (expected, 0));
5229 if (!is_gimple_reg_type (etype)
5230 || !auto_var_in_fn_p (TREE_OPERAND (expected, 0), current_function_decl)
5231 || TREE_THIS_VOLATILE (etype)
5232 || VECTOR_TYPE_P (etype)
5233 || TREE_CODE (etype) == COMPLEX_TYPE
5234 /* Don't optimize floating point expected vars, VIEW_CONVERT_EXPRs
5235 might not preserve all the bits. See PR71716. */
5236 || SCALAR_FLOAT_TYPE_P (etype)
5237 || maybe_ne (TYPE_PRECISION (etype),
5238 GET_MODE_BITSIZE (TYPE_MODE (etype))))
5239 return false;
5241 tree weak = gimple_call_arg (stmt, 3);
5242 if (!integer_zerop (weak) && !integer_onep (weak))
5243 return false;
5245 tree parmt = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
5246 tree itype = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (parmt)));
5247 machine_mode mode = TYPE_MODE (itype);
5249 if (direct_optab_handler (atomic_compare_and_swap_optab, mode)
5250 == CODE_FOR_nothing
5251 && optab_handler (sync_compare_and_swap_optab, mode) == CODE_FOR_nothing)
5252 return false;
5254 if (maybe_ne (int_size_in_bytes (etype), GET_MODE_SIZE (mode)))
5255 return false;
5257 return true;
5260 /* Fold
5261 r = __atomic_compare_exchange_N (p, &e, d, w, s, f);
5262 into
5263 _Complex uintN_t t = ATOMIC_COMPARE_EXCHANGE (p, e, d, w * 256 + N, s, f);
5264 i = IMAGPART_EXPR <t>;
5265 r = (_Bool) i;
5266 e = REALPART_EXPR <t>; */
5268 void
5269 fold_builtin_atomic_compare_exchange (gimple_stmt_iterator *gsi)
5271 gimple *stmt = gsi_stmt (*gsi);
5272 tree fndecl = gimple_call_fndecl (stmt);
5273 tree parmt = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
5274 tree itype = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (parmt)));
5275 tree ctype = build_complex_type (itype);
5276 tree expected = TREE_OPERAND (gimple_call_arg (stmt, 1), 0);
5277 bool throws = false;
5278 edge e = NULL;
5279 gimple *g = gimple_build_assign (make_ssa_name (TREE_TYPE (expected)),
5280 expected);
5281 gsi_insert_before (gsi, g, GSI_SAME_STMT);
5282 gimple_stmt_iterator gsiret = gsi_for_stmt (g);
5283 if (!useless_type_conversion_p (itype, TREE_TYPE (expected)))
5285 g = gimple_build_assign (make_ssa_name (itype), VIEW_CONVERT_EXPR,
5286 build1 (VIEW_CONVERT_EXPR, itype,
5287 gimple_assign_lhs (g)));
5288 gsi_insert_before (gsi, g, GSI_SAME_STMT);
5290 int flag = (integer_onep (gimple_call_arg (stmt, 3)) ? 256 : 0)
5291 + int_size_in_bytes (itype);
5292 g = gimple_build_call_internal (IFN_ATOMIC_COMPARE_EXCHANGE, 6,
5293 gimple_call_arg (stmt, 0),
5294 gimple_assign_lhs (g),
5295 gimple_call_arg (stmt, 2),
5296 build_int_cst (integer_type_node, flag),
5297 gimple_call_arg (stmt, 4),
5298 gimple_call_arg (stmt, 5));
5299 tree lhs = make_ssa_name (ctype);
5300 gimple_call_set_lhs (g, lhs);
5301 gimple_move_vops (g, stmt);
5302 tree oldlhs = gimple_call_lhs (stmt);
5303 if (stmt_can_throw_internal (cfun, stmt))
5305 throws = true;
5306 e = find_fallthru_edge (gsi_bb (*gsi)->succs);
5308 gimple_call_set_nothrow (as_a <gcall *> (g),
5309 gimple_call_nothrow_p (as_a <gcall *> (stmt)));
5310 gimple_call_set_lhs (stmt, NULL_TREE);
5311 gsi_replace (gsi, g, true);
5312 if (oldlhs)
5314 g = gimple_build_assign (make_ssa_name (itype), IMAGPART_EXPR,
5315 build1 (IMAGPART_EXPR, itype, lhs));
5316 if (throws)
5318 gsi_insert_on_edge_immediate (e, g);
5319 *gsi = gsi_for_stmt (g);
5321 else
5322 gsi_insert_after (gsi, g, GSI_NEW_STMT);
5323 g = gimple_build_assign (oldlhs, NOP_EXPR, gimple_assign_lhs (g));
5324 gsi_insert_after (gsi, g, GSI_NEW_STMT);
5326 g = gimple_build_assign (make_ssa_name (itype), REALPART_EXPR,
5327 build1 (REALPART_EXPR, itype, lhs));
5328 if (throws && oldlhs == NULL_TREE)
5330 gsi_insert_on_edge_immediate (e, g);
5331 *gsi = gsi_for_stmt (g);
5333 else
5334 gsi_insert_after (gsi, g, GSI_NEW_STMT);
5335 if (!useless_type_conversion_p (TREE_TYPE (expected), itype))
5337 g = gimple_build_assign (make_ssa_name (TREE_TYPE (expected)),
5338 VIEW_CONVERT_EXPR,
5339 build1 (VIEW_CONVERT_EXPR, TREE_TYPE (expected),
5340 gimple_assign_lhs (g)));
5341 gsi_insert_after (gsi, g, GSI_NEW_STMT);
5343 g = gimple_build_assign (expected, SSA_NAME, gimple_assign_lhs (g));
5344 gsi_insert_after (gsi, g, GSI_NEW_STMT);
5345 *gsi = gsiret;
5348 /* Return true if ARG0 CODE ARG1 in infinite signed precision operation
5349 doesn't fit into TYPE. The test for overflow should be regardless of
5350 -fwrapv, and even for unsigned types. */
5352 bool
5353 arith_overflowed_p (enum tree_code code, const_tree type,
5354 const_tree arg0, const_tree arg1)
5356 widest2_int warg0 = widest2_int_cst (arg0);
5357 widest2_int warg1 = widest2_int_cst (arg1);
5358 widest2_int wres;
5359 switch (code)
5361 case PLUS_EXPR: wres = wi::add (warg0, warg1); break;
5362 case MINUS_EXPR: wres = wi::sub (warg0, warg1); break;
5363 case MULT_EXPR: wres = wi::mul (warg0, warg1); break;
5364 default: gcc_unreachable ();
5366 signop sign = TYPE_SIGN (type);
5367 if (sign == UNSIGNED && wi::neg_p (wres))
5368 return true;
5369 return wi::min_precision (wres, sign) > TYPE_PRECISION (type);
5372 /* If IFN_{MASK,LEN}_LOAD/STORE call CALL is unconditional, return a MEM_REF
5373 for the memory it references, otherwise return null. VECTYPE is the
5374 type of the memory vector. MASK_P indicates it's for MASK if true,
5375 otherwise it's for LEN. */
5377 static tree
5378 gimple_fold_partial_load_store_mem_ref (gcall *call, tree vectype, bool mask_p)
5380 tree ptr = gimple_call_arg (call, 0);
5381 tree alias_align = gimple_call_arg (call, 1);
5382 if (!tree_fits_uhwi_p (alias_align))
5383 return NULL_TREE;
5385 if (mask_p)
5387 tree mask = gimple_call_arg (call, 2);
5388 if (!integer_all_onesp (mask))
5389 return NULL_TREE;
5391 else
5393 tree basic_len = gimple_call_arg (call, 2);
5394 if (!poly_int_tree_p (basic_len))
5395 return NULL_TREE;
5396 unsigned int nargs = gimple_call_num_args (call);
5397 tree bias = gimple_call_arg (call, nargs - 1);
5398 gcc_assert (TREE_CODE (bias) == INTEGER_CST);
5399 if (maybe_ne (wi::to_poly_widest (basic_len) - wi::to_widest (bias),
5400 GET_MODE_SIZE (TYPE_MODE (vectype))))
5401 return NULL_TREE;
5404 unsigned HOST_WIDE_INT align = tree_to_uhwi (alias_align);
5405 if (TYPE_ALIGN (vectype) != align)
5406 vectype = build_aligned_type (vectype, align);
5407 tree offset = build_zero_cst (TREE_TYPE (alias_align));
5408 return fold_build2 (MEM_REF, vectype, ptr, offset);
5411 /* Try to fold IFN_{MASK,LEN}_LOAD call CALL. Return true on success.
5412 MASK_P indicates it's for MASK if true, otherwise it's for LEN. */
5414 static bool
5415 gimple_fold_partial_load (gimple_stmt_iterator *gsi, gcall *call, bool mask_p)
5417 tree lhs = gimple_call_lhs (call);
5418 if (!lhs)
5419 return false;
5421 if (tree rhs
5422 = gimple_fold_partial_load_store_mem_ref (call, TREE_TYPE (lhs), mask_p))
5424 gassign *new_stmt = gimple_build_assign (lhs, rhs);
5425 gimple_set_location (new_stmt, gimple_location (call));
5426 gimple_move_vops (new_stmt, call);
5427 gsi_replace (gsi, new_stmt, false);
5428 return true;
5430 return false;
5433 /* Try to fold IFN_{MASK,LEN}_STORE call CALL. Return true on success.
5434 MASK_P indicates it's for MASK if true, otherwise it's for LEN. */
5436 static bool
5437 gimple_fold_partial_store (gimple_stmt_iterator *gsi, gcall *call,
5438 bool mask_p)
5440 tree rhs = gimple_call_arg (call, 3);
5441 if (tree lhs
5442 = gimple_fold_partial_load_store_mem_ref (call, TREE_TYPE (rhs), mask_p))
5444 gassign *new_stmt = gimple_build_assign (lhs, rhs);
5445 gimple_set_location (new_stmt, gimple_location (call));
5446 gimple_move_vops (new_stmt, call);
5447 gsi_replace (gsi, new_stmt, false);
5448 return true;
5450 return false;
5453 /* Attempt to fold a call statement referenced by the statement iterator GSI.
5454 The statement may be replaced by another statement, e.g., if the call
5455 simplifies to a constant value. Return true if any changes were made.
5456 It is assumed that the operands have been previously folded. */
5458 static bool
5459 gimple_fold_call (gimple_stmt_iterator *gsi, bool inplace)
5461 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
5462 tree callee;
5463 bool changed = false;
5465 /* Check for virtual calls that became direct calls. */
5466 callee = gimple_call_fn (stmt);
5467 if (callee && TREE_CODE (callee) == OBJ_TYPE_REF)
5469 if (gimple_call_addr_fndecl (OBJ_TYPE_REF_EXPR (callee)) != NULL_TREE)
5471 if (dump_file && virtual_method_call_p (callee)
5472 && !possible_polymorphic_call_target_p
5473 (callee, stmt, cgraph_node::get (gimple_call_addr_fndecl
5474 (OBJ_TYPE_REF_EXPR (callee)))))
5476 fprintf (dump_file,
5477 "Type inheritance inconsistent devirtualization of ");
5478 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
5479 fprintf (dump_file, " to ");
5480 print_generic_expr (dump_file, callee, TDF_SLIM);
5481 fprintf (dump_file, "\n");
5484 gimple_call_set_fn (stmt, OBJ_TYPE_REF_EXPR (callee));
5485 changed = true;
5487 else if (flag_devirtualize && !inplace && virtual_method_call_p (callee))
5489 bool final;
5490 vec <cgraph_node *>targets
5491 = possible_polymorphic_call_targets (callee, stmt, &final);
5492 if (final && targets.length () <= 1 && dbg_cnt (devirt))
5494 tree lhs = gimple_call_lhs (stmt);
5495 if (dump_enabled_p ())
5497 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, stmt,
5498 "folding virtual function call to %s\n",
5499 targets.length () == 1
5500 ? targets[0]->name ()
5501 : "__builtin_unreachable");
5503 if (targets.length () == 1)
5505 tree fndecl = targets[0]->decl;
5506 gimple_call_set_fndecl (stmt, fndecl);
5507 changed = true;
5508 /* If changing the call to __cxa_pure_virtual
5509 or similar noreturn function, adjust gimple_call_fntype
5510 too. */
5511 if (gimple_call_noreturn_p (stmt)
5512 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (fndecl)))
5513 && TYPE_ARG_TYPES (TREE_TYPE (fndecl))
5514 && (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (fndecl)))
5515 == void_type_node))
5516 gimple_call_set_fntype (stmt, TREE_TYPE (fndecl));
5517 /* If the call becomes noreturn, remove the lhs. */
5518 if (lhs
5519 && gimple_call_noreturn_p (stmt)
5520 && (VOID_TYPE_P (TREE_TYPE (gimple_call_fntype (stmt)))
5521 || should_remove_lhs_p (lhs)))
5523 if (TREE_CODE (lhs) == SSA_NAME)
5525 tree var = create_tmp_var (TREE_TYPE (lhs));
5526 tree def = get_or_create_ssa_default_def (cfun, var);
5527 gimple *new_stmt = gimple_build_assign (lhs, def);
5528 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
5530 gimple_call_set_lhs (stmt, NULL_TREE);
5532 maybe_remove_unused_call_args (cfun, stmt);
5534 else
5536 location_t loc = gimple_location (stmt);
5537 gimple *new_stmt = gimple_build_builtin_unreachable (loc);
5538 gimple_call_set_ctrl_altering (new_stmt, false);
5539 /* If the call had a SSA name as lhs morph that into
5540 an uninitialized value. */
5541 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5543 tree var = create_tmp_var (TREE_TYPE (lhs));
5544 SET_SSA_NAME_VAR_OR_IDENTIFIER (lhs, var);
5545 SSA_NAME_DEF_STMT (lhs) = gimple_build_nop ();
5546 set_ssa_default_def (cfun, var, lhs);
5548 gimple_move_vops (new_stmt, stmt);
5549 gsi_replace (gsi, new_stmt, false);
5550 return true;
5556 /* Check for indirect calls that became direct calls, and then
5557 no longer require a static chain. */
5558 if (gimple_call_chain (stmt))
5560 tree fn = gimple_call_fndecl (stmt);
5561 if (fn && !DECL_STATIC_CHAIN (fn))
5563 gimple_call_set_chain (stmt, NULL);
5564 changed = true;
5568 if (inplace)
5569 return changed;
5571 /* Check for builtins that CCP can handle using information not
5572 available in the generic fold routines. */
5573 if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
5575 if (gimple_fold_builtin (gsi))
5576 changed = true;
5578 else if (gimple_call_builtin_p (stmt, BUILT_IN_MD))
5580 changed |= targetm.gimple_fold_builtin (gsi);
5582 else if (gimple_call_internal_p (stmt))
5584 enum tree_code subcode = ERROR_MARK;
5585 tree result = NULL_TREE;
5586 bool cplx_result = false;
5587 tree overflow = NULL_TREE;
5588 switch (gimple_call_internal_fn (stmt))
5590 case IFN_BUILTIN_EXPECT:
5591 result = fold_builtin_expect (gimple_location (stmt),
5592 gimple_call_arg (stmt, 0),
5593 gimple_call_arg (stmt, 1),
5594 gimple_call_arg (stmt, 2),
5595 NULL_TREE);
5596 break;
5597 case IFN_UBSAN_OBJECT_SIZE:
5599 tree offset = gimple_call_arg (stmt, 1);
5600 tree objsize = gimple_call_arg (stmt, 2);
5601 if (integer_all_onesp (objsize)
5602 || (TREE_CODE (offset) == INTEGER_CST
5603 && TREE_CODE (objsize) == INTEGER_CST
5604 && tree_int_cst_le (offset, objsize)))
5606 replace_call_with_value (gsi, NULL_TREE);
5607 return true;
5610 break;
5611 case IFN_UBSAN_PTR:
5612 if (integer_zerop (gimple_call_arg (stmt, 1)))
5614 replace_call_with_value (gsi, NULL_TREE);
5615 return true;
5617 break;
5618 case IFN_UBSAN_BOUNDS:
5620 tree index = gimple_call_arg (stmt, 1);
5621 tree bound = gimple_call_arg (stmt, 2);
5622 if (TREE_CODE (index) == INTEGER_CST
5623 && TREE_CODE (bound) == INTEGER_CST)
5625 index = fold_convert (TREE_TYPE (bound), index);
5626 if (TREE_CODE (index) == INTEGER_CST
5627 && tree_int_cst_le (index, bound))
5629 replace_call_with_value (gsi, NULL_TREE);
5630 return true;
5634 break;
5635 case IFN_GOACC_DIM_SIZE:
5636 case IFN_GOACC_DIM_POS:
5637 result = fold_internal_goacc_dim (stmt);
5638 break;
5639 case IFN_UBSAN_CHECK_ADD:
5640 subcode = PLUS_EXPR;
5641 break;
5642 case IFN_UBSAN_CHECK_SUB:
5643 subcode = MINUS_EXPR;
5644 break;
5645 case IFN_UBSAN_CHECK_MUL:
5646 subcode = MULT_EXPR;
5647 break;
5648 case IFN_ADD_OVERFLOW:
5649 subcode = PLUS_EXPR;
5650 cplx_result = true;
5651 break;
5652 case IFN_SUB_OVERFLOW:
5653 subcode = MINUS_EXPR;
5654 cplx_result = true;
5655 break;
5656 case IFN_MUL_OVERFLOW:
5657 subcode = MULT_EXPR;
5658 cplx_result = true;
5659 break;
5660 case IFN_MASK_LOAD:
5661 changed |= gimple_fold_partial_load (gsi, stmt, true);
5662 break;
5663 case IFN_MASK_STORE:
5664 changed |= gimple_fold_partial_store (gsi, stmt, true);
5665 break;
5666 case IFN_LEN_LOAD:
5667 changed |= gimple_fold_partial_load (gsi, stmt, false);
5668 break;
5669 case IFN_LEN_STORE:
5670 changed |= gimple_fold_partial_store (gsi, stmt, false);
5671 break;
5672 default:
5673 break;
5675 if (subcode != ERROR_MARK)
5677 tree arg0 = gimple_call_arg (stmt, 0);
5678 tree arg1 = gimple_call_arg (stmt, 1);
5679 tree type = TREE_TYPE (arg0);
5680 if (cplx_result)
5682 tree lhs = gimple_call_lhs (stmt);
5683 if (lhs == NULL_TREE)
5684 type = NULL_TREE;
5685 else
5686 type = TREE_TYPE (TREE_TYPE (lhs));
5688 if (type == NULL_TREE)
5690 /* x = y + 0; x = y - 0; x = y * 0; */
5691 else if (integer_zerop (arg1))
5692 result = subcode == MULT_EXPR ? integer_zero_node : arg0;
5693 /* x = 0 + y; x = 0 * y; */
5694 else if (subcode != MINUS_EXPR && integer_zerop (arg0))
5695 result = subcode == MULT_EXPR ? integer_zero_node : arg1;
5696 /* x = y - y; */
5697 else if (subcode == MINUS_EXPR && operand_equal_p (arg0, arg1, 0))
5698 result = integer_zero_node;
5699 /* x = y * 1; x = 1 * y; */
5700 else if (subcode == MULT_EXPR && integer_onep (arg1))
5701 result = arg0;
5702 else if (subcode == MULT_EXPR && integer_onep (arg0))
5703 result = arg1;
5704 else if (TREE_CODE (arg0) == INTEGER_CST
5705 && TREE_CODE (arg1) == INTEGER_CST)
5707 if (cplx_result)
5708 result = int_const_binop (subcode, fold_convert (type, arg0),
5709 fold_convert (type, arg1));
5710 else
5711 result = int_const_binop (subcode, arg0, arg1);
5712 if (result && arith_overflowed_p (subcode, type, arg0, arg1))
5714 if (cplx_result)
5715 overflow = build_one_cst (type);
5716 else
5717 result = NULL_TREE;
5720 if (result)
5722 if (result == integer_zero_node)
5723 result = build_zero_cst (type);
5724 else if (cplx_result && TREE_TYPE (result) != type)
5726 if (TREE_CODE (result) == INTEGER_CST)
5728 if (arith_overflowed_p (PLUS_EXPR, type, result,
5729 integer_zero_node))
5730 overflow = build_one_cst (type);
5732 else if ((!TYPE_UNSIGNED (TREE_TYPE (result))
5733 && TYPE_UNSIGNED (type))
5734 || (TYPE_PRECISION (type)
5735 < (TYPE_PRECISION (TREE_TYPE (result))
5736 + (TYPE_UNSIGNED (TREE_TYPE (result))
5737 && !TYPE_UNSIGNED (type)))))
5738 result = NULL_TREE;
5739 if (result)
5740 result = fold_convert (type, result);
5745 if (result)
5747 if (TREE_CODE (result) == INTEGER_CST && TREE_OVERFLOW (result))
5748 result = drop_tree_overflow (result);
5749 if (cplx_result)
5751 if (overflow == NULL_TREE)
5752 overflow = build_zero_cst (TREE_TYPE (result));
5753 tree ctype = build_complex_type (TREE_TYPE (result));
5754 if (TREE_CODE (result) == INTEGER_CST
5755 && TREE_CODE (overflow) == INTEGER_CST)
5756 result = build_complex (ctype, result, overflow);
5757 else
5758 result = build2_loc (gimple_location (stmt), COMPLEX_EXPR,
5759 ctype, result, overflow);
5761 gimplify_and_update_call_from_tree (gsi, result);
5762 changed = true;
5766 return changed;
5770 /* Return true whether NAME has a use on STMT. Note this can return
5771 false even though there's a use on STMT if SSA operands are not
5772 up-to-date. */
5774 static bool
5775 has_use_on_stmt (tree name, gimple *stmt)
5777 ssa_op_iter iter;
5778 tree op;
5779 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
5780 if (op == name)
5781 return true;
5782 return false;
5785 /* Worker for fold_stmt_1 dispatch to pattern based folding with
5786 gimple_simplify.
5788 Replaces *GSI with the simplification result in RCODE and OPS
5789 and the associated statements in *SEQ. Does the replacement
5790 according to INPLACE and returns true if the operation succeeded. */
5792 static bool
5793 replace_stmt_with_simplification (gimple_stmt_iterator *gsi,
5794 gimple_match_op *res_op,
5795 gimple_seq *seq, bool inplace)
5797 gimple *stmt = gsi_stmt (*gsi);
5798 tree *ops = res_op->ops;
5799 unsigned int num_ops = res_op->num_ops;
5801 /* Play safe and do not allow abnormals to be mentioned in
5802 newly created statements. See also maybe_push_res_to_seq.
5803 As an exception allow such uses if there was a use of the
5804 same SSA name on the old stmt. */
5805 for (unsigned int i = 0; i < num_ops; ++i)
5806 if (TREE_CODE (ops[i]) == SSA_NAME
5807 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ops[i])
5808 && !has_use_on_stmt (ops[i], stmt))
5809 return false;
5811 if (num_ops > 0 && COMPARISON_CLASS_P (ops[0]))
5812 for (unsigned int i = 0; i < 2; ++i)
5813 if (TREE_CODE (TREE_OPERAND (ops[0], i)) == SSA_NAME
5814 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (TREE_OPERAND (ops[0], i))
5815 && !has_use_on_stmt (TREE_OPERAND (ops[0], i), stmt))
5816 return false;
5818 /* Don't insert new statements when INPLACE is true, even if we could
5819 reuse STMT for the final statement. */
5820 if (inplace && !gimple_seq_empty_p (*seq))
5821 return false;
5823 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
5825 gcc_assert (res_op->code.is_tree_code ());
5826 auto code = tree_code (res_op->code);
5827 if (TREE_CODE_CLASS (code) == tcc_comparison
5828 /* GIMPLE_CONDs condition may not throw. */
5829 && (!flag_exceptions
5830 || !cfun->can_throw_non_call_exceptions
5831 || !operation_could_trap_p (code,
5832 FLOAT_TYPE_P (TREE_TYPE (ops[0])),
5833 false, NULL_TREE)))
5834 gimple_cond_set_condition (cond_stmt, code, ops[0], ops[1]);
5835 else if (code == SSA_NAME)
5836 gimple_cond_set_condition (cond_stmt, NE_EXPR, ops[0],
5837 build_zero_cst (TREE_TYPE (ops[0])));
5838 else if (code == INTEGER_CST)
5840 if (integer_zerop (ops[0]))
5841 gimple_cond_make_false (cond_stmt);
5842 else
5843 gimple_cond_make_true (cond_stmt);
5845 else if (!inplace)
5847 tree res = maybe_push_res_to_seq (res_op, seq);
5848 if (!res)
5849 return false;
5850 gimple_cond_set_condition (cond_stmt, NE_EXPR, res,
5851 build_zero_cst (TREE_TYPE (res)));
5853 else
5854 return false;
5855 if (dump_file && (dump_flags & TDF_DETAILS))
5857 fprintf (dump_file, "gimple_simplified to ");
5858 if (!gimple_seq_empty_p (*seq))
5859 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
5860 print_gimple_stmt (dump_file, gsi_stmt (*gsi),
5861 0, TDF_SLIM);
5863 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
5864 return true;
5866 else if (is_gimple_assign (stmt)
5867 && res_op->code.is_tree_code ())
5869 auto code = tree_code (res_op->code);
5870 if (!inplace
5871 || gimple_num_ops (stmt) > get_gimple_rhs_num_ops (code))
5873 maybe_build_generic_op (res_op);
5874 gimple_assign_set_rhs_with_ops (gsi, code,
5875 res_op->op_or_null (0),
5876 res_op->op_or_null (1),
5877 res_op->op_or_null (2));
5878 if (dump_file && (dump_flags & TDF_DETAILS))
5880 fprintf (dump_file, "gimple_simplified to ");
5881 if (!gimple_seq_empty_p (*seq))
5882 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
5883 print_gimple_stmt (dump_file, gsi_stmt (*gsi),
5884 0, TDF_SLIM);
5886 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
5887 return true;
5890 else if (res_op->code.is_fn_code ()
5891 && gimple_call_combined_fn (stmt) == combined_fn (res_op->code))
5893 gcc_assert (num_ops == gimple_call_num_args (stmt));
5894 for (unsigned int i = 0; i < num_ops; ++i)
5895 gimple_call_set_arg (stmt, i, ops[i]);
5896 if (dump_file && (dump_flags & TDF_DETAILS))
5898 fprintf (dump_file, "gimple_simplified to ");
5899 if (!gimple_seq_empty_p (*seq))
5900 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
5901 print_gimple_stmt (dump_file, gsi_stmt (*gsi), 0, TDF_SLIM);
5903 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
5904 return true;
5906 else if (!inplace)
5908 if (gimple_has_lhs (stmt))
5910 tree lhs = gimple_get_lhs (stmt);
5911 if (!maybe_push_res_to_seq (res_op, seq, lhs))
5912 return false;
5913 if (dump_file && (dump_flags & TDF_DETAILS))
5915 fprintf (dump_file, "gimple_simplified to ");
5916 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
5918 gsi_replace_with_seq_vops (gsi, *seq);
5919 return true;
5921 else
5922 gcc_unreachable ();
5925 return false;
5928 /* Canonicalize MEM_REFs invariant address operand after propagation. */
5930 static bool
5931 maybe_canonicalize_mem_ref_addr (tree *t, bool is_debug = false)
5933 bool res = false;
5934 tree *orig_t = t;
5936 if (TREE_CODE (*t) == ADDR_EXPR)
5937 t = &TREE_OPERAND (*t, 0);
5939 /* The C and C++ frontends use an ARRAY_REF for indexing with their
5940 generic vector extension. The actual vector referenced is
5941 view-converted to an array type for this purpose. If the index
5942 is constant the canonical representation in the middle-end is a
5943 BIT_FIELD_REF so re-write the former to the latter here. */
5944 if (TREE_CODE (*t) == ARRAY_REF
5945 && TREE_CODE (TREE_OPERAND (*t, 0)) == VIEW_CONVERT_EXPR
5946 && TREE_CODE (TREE_OPERAND (*t, 1)) == INTEGER_CST
5947 && VECTOR_TYPE_P (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (*t, 0), 0))))
5949 tree vtype = TREE_TYPE (TREE_OPERAND (TREE_OPERAND (*t, 0), 0));
5950 if (VECTOR_TYPE_P (vtype))
5952 tree low = array_ref_low_bound (*t);
5953 if (TREE_CODE (low) == INTEGER_CST)
5955 if (tree_int_cst_le (low, TREE_OPERAND (*t, 1)))
5957 widest_int idx = wi::sub (wi::to_widest (TREE_OPERAND (*t, 1)),
5958 wi::to_widest (low));
5959 idx = wi::mul (idx, wi::to_widest
5960 (TYPE_SIZE (TREE_TYPE (*t))));
5961 widest_int ext
5962 = wi::add (idx, wi::to_widest (TYPE_SIZE (TREE_TYPE (*t))));
5963 if (wi::les_p (ext, wi::to_widest (TYPE_SIZE (vtype))))
5965 *t = build3_loc (EXPR_LOCATION (*t), BIT_FIELD_REF,
5966 TREE_TYPE (*t),
5967 TREE_OPERAND (TREE_OPERAND (*t, 0), 0),
5968 TYPE_SIZE (TREE_TYPE (*t)),
5969 wide_int_to_tree (bitsizetype, idx));
5970 res = true;
5977 while (handled_component_p (*t))
5978 t = &TREE_OPERAND (*t, 0);
5980 /* Canonicalize MEM [&foo.bar, 0] which appears after propagating
5981 of invariant addresses into a SSA name MEM_REF address. */
5982 if (TREE_CODE (*t) == MEM_REF
5983 || TREE_CODE (*t) == TARGET_MEM_REF)
5985 tree addr = TREE_OPERAND (*t, 0);
5986 if (TREE_CODE (addr) == ADDR_EXPR
5987 && (TREE_CODE (TREE_OPERAND (addr, 0)) == MEM_REF
5988 || handled_component_p (TREE_OPERAND (addr, 0))))
5990 tree base;
5991 poly_int64 coffset;
5992 base = get_addr_base_and_unit_offset (TREE_OPERAND (addr, 0),
5993 &coffset);
5994 if (!base)
5996 if (is_debug)
5997 return false;
5998 gcc_unreachable ();
6001 TREE_OPERAND (*t, 0) = build_fold_addr_expr (base);
6002 TREE_OPERAND (*t, 1) = int_const_binop (PLUS_EXPR,
6003 TREE_OPERAND (*t, 1),
6004 size_int (coffset));
6005 res = true;
6007 gcc_checking_assert (TREE_CODE (TREE_OPERAND (*t, 0)) == DEBUG_EXPR_DECL
6008 || is_gimple_mem_ref_addr (TREE_OPERAND (*t, 0)));
6011 /* Canonicalize back MEM_REFs to plain reference trees if the object
6012 accessed is a decl that has the same access semantics as the MEM_REF. */
6013 if (TREE_CODE (*t) == MEM_REF
6014 && TREE_CODE (TREE_OPERAND (*t, 0)) == ADDR_EXPR
6015 && integer_zerop (TREE_OPERAND (*t, 1))
6016 && MR_DEPENDENCE_CLIQUE (*t) == 0)
6018 tree decl = TREE_OPERAND (TREE_OPERAND (*t, 0), 0);
6019 tree alias_type = TREE_TYPE (TREE_OPERAND (*t, 1));
6020 if (/* Same volatile qualification. */
6021 TREE_THIS_VOLATILE (*t) == TREE_THIS_VOLATILE (decl)
6022 /* Same TBAA behavior with -fstrict-aliasing. */
6023 && !TYPE_REF_CAN_ALIAS_ALL (alias_type)
6024 && (TYPE_MAIN_VARIANT (TREE_TYPE (decl))
6025 == TYPE_MAIN_VARIANT (TREE_TYPE (alias_type)))
6026 /* Same alignment. */
6027 && TYPE_ALIGN (TREE_TYPE (decl)) == TYPE_ALIGN (TREE_TYPE (*t))
6028 /* We have to look out here to not drop a required conversion
6029 from the rhs to the lhs if *t appears on the lhs or vice-versa
6030 if it appears on the rhs. Thus require strict type
6031 compatibility. */
6032 && types_compatible_p (TREE_TYPE (*t), TREE_TYPE (decl)))
6034 *t = TREE_OPERAND (TREE_OPERAND (*t, 0), 0);
6035 res = true;
6039 else if (TREE_CODE (*orig_t) == ADDR_EXPR
6040 && TREE_CODE (*t) == MEM_REF
6041 && TREE_CODE (TREE_OPERAND (*t, 0)) == INTEGER_CST)
6043 tree base;
6044 poly_int64 coffset;
6045 base = get_addr_base_and_unit_offset (TREE_OPERAND (*orig_t, 0),
6046 &coffset);
6047 if (base)
6049 gcc_assert (TREE_CODE (base) == MEM_REF);
6050 poly_int64 moffset;
6051 if (mem_ref_offset (base).to_shwi (&moffset))
6053 coffset += moffset;
6054 if (wi::to_poly_wide (TREE_OPERAND (base, 0)).to_shwi (&moffset))
6056 coffset += moffset;
6057 *orig_t = build_int_cst (TREE_TYPE (*orig_t), coffset);
6058 return true;
6064 /* Canonicalize TARGET_MEM_REF in particular with respect to
6065 the indexes becoming constant. */
6066 else if (TREE_CODE (*t) == TARGET_MEM_REF)
6068 tree tem = maybe_fold_tmr (*t);
6069 if (tem)
6071 *t = tem;
6072 if (TREE_CODE (*orig_t) == ADDR_EXPR)
6073 recompute_tree_invariant_for_addr_expr (*orig_t);
6074 res = true;
6078 return res;
6081 /* Worker for both fold_stmt and fold_stmt_inplace. The INPLACE argument
6082 distinguishes both cases. */
6084 static bool
6085 fold_stmt_1 (gimple_stmt_iterator *gsi, bool inplace, tree (*valueize) (tree))
6087 bool changed = false;
6088 gimple *stmt = gsi_stmt (*gsi);
6089 bool nowarning = warning_suppressed_p (stmt, OPT_Wstrict_overflow);
6090 unsigned i;
6091 fold_defer_overflow_warnings ();
6093 /* First do required canonicalization of [TARGET_]MEM_REF addresses
6094 after propagation.
6095 ??? This shouldn't be done in generic folding but in the
6096 propagation helpers which also know whether an address was
6097 propagated.
6098 Also canonicalize operand order. */
6099 switch (gimple_code (stmt))
6101 case GIMPLE_ASSIGN:
6102 if (gimple_assign_rhs_class (stmt) == GIMPLE_SINGLE_RHS)
6104 tree *rhs = gimple_assign_rhs1_ptr (stmt);
6105 if ((REFERENCE_CLASS_P (*rhs)
6106 || TREE_CODE (*rhs) == ADDR_EXPR)
6107 && maybe_canonicalize_mem_ref_addr (rhs))
6108 changed = true;
6109 tree *lhs = gimple_assign_lhs_ptr (stmt);
6110 if (REFERENCE_CLASS_P (*lhs)
6111 && maybe_canonicalize_mem_ref_addr (lhs))
6112 changed = true;
6113 /* Canonicalize &MEM[ssa_n, CST] to ssa_n p+ CST.
6114 This cannot be done in maybe_canonicalize_mem_ref_addr
6115 as the gimple now has two operands rather than one.
6116 The same reason why this can't be done in
6117 maybe_canonicalize_mem_ref_addr is the same reason why
6118 this can't be done inplace. */
6119 if (!inplace && TREE_CODE (*rhs) == ADDR_EXPR)
6121 tree inner = TREE_OPERAND (*rhs, 0);
6122 if (TREE_CODE (inner) == MEM_REF
6123 && TREE_CODE (TREE_OPERAND (inner, 0)) == SSA_NAME
6124 && TREE_CODE (TREE_OPERAND (inner, 1)) == INTEGER_CST)
6126 tree ptr = TREE_OPERAND (inner, 0);
6127 tree addon = TREE_OPERAND (inner, 1);
6128 addon = fold_convert (sizetype, addon);
6129 gimple_assign_set_rhs_with_ops (gsi, POINTER_PLUS_EXPR,
6130 ptr, addon);
6131 changed = true;
6132 stmt = gsi_stmt (*gsi);
6136 else
6138 /* Canonicalize operand order. */
6139 enum tree_code code = gimple_assign_rhs_code (stmt);
6140 if (TREE_CODE_CLASS (code) == tcc_comparison
6141 || commutative_tree_code (code)
6142 || commutative_ternary_tree_code (code))
6144 tree rhs1 = gimple_assign_rhs1 (stmt);
6145 tree rhs2 = gimple_assign_rhs2 (stmt);
6146 if (tree_swap_operands_p (rhs1, rhs2))
6148 gimple_assign_set_rhs1 (stmt, rhs2);
6149 gimple_assign_set_rhs2 (stmt, rhs1);
6150 if (TREE_CODE_CLASS (code) == tcc_comparison)
6151 gimple_assign_set_rhs_code (stmt,
6152 swap_tree_comparison (code));
6153 changed = true;
6157 break;
6158 case GIMPLE_CALL:
6160 gcall *call = as_a<gcall *> (stmt);
6161 for (i = 0; i < gimple_call_num_args (call); ++i)
6163 tree *arg = gimple_call_arg_ptr (call, i);
6164 if (REFERENCE_CLASS_P (*arg)
6165 && maybe_canonicalize_mem_ref_addr (arg))
6166 changed = true;
6168 tree *lhs = gimple_call_lhs_ptr (call);
6169 if (*lhs
6170 && REFERENCE_CLASS_P (*lhs)
6171 && maybe_canonicalize_mem_ref_addr (lhs))
6172 changed = true;
6173 if (*lhs)
6175 combined_fn cfn = gimple_call_combined_fn (call);
6176 internal_fn ifn = associated_internal_fn (cfn, TREE_TYPE (*lhs));
6177 int opno = first_commutative_argument (ifn);
6178 if (opno >= 0)
6180 tree arg1 = gimple_call_arg (call, opno);
6181 tree arg2 = gimple_call_arg (call, opno + 1);
6182 if (tree_swap_operands_p (arg1, arg2))
6184 gimple_call_set_arg (call, opno, arg2);
6185 gimple_call_set_arg (call, opno + 1, arg1);
6186 changed = true;
6190 break;
6192 case GIMPLE_ASM:
6194 gasm *asm_stmt = as_a <gasm *> (stmt);
6195 for (i = 0; i < gimple_asm_noutputs (asm_stmt); ++i)
6197 tree link = gimple_asm_output_op (asm_stmt, i);
6198 tree op = TREE_VALUE (link);
6199 if (REFERENCE_CLASS_P (op)
6200 && maybe_canonicalize_mem_ref_addr (&TREE_VALUE (link)))
6201 changed = true;
6203 for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
6205 tree link = gimple_asm_input_op (asm_stmt, i);
6206 tree op = TREE_VALUE (link);
6207 if ((REFERENCE_CLASS_P (op)
6208 || TREE_CODE (op) == ADDR_EXPR)
6209 && maybe_canonicalize_mem_ref_addr (&TREE_VALUE (link)))
6210 changed = true;
6213 break;
6214 case GIMPLE_DEBUG:
6215 if (gimple_debug_bind_p (stmt))
6217 tree *val = gimple_debug_bind_get_value_ptr (stmt);
6218 if (*val
6219 && (REFERENCE_CLASS_P (*val)
6220 || TREE_CODE (*val) == ADDR_EXPR)
6221 && maybe_canonicalize_mem_ref_addr (val, true))
6222 changed = true;
6224 break;
6225 case GIMPLE_COND:
6227 /* Canonicalize operand order. */
6228 tree lhs = gimple_cond_lhs (stmt);
6229 tree rhs = gimple_cond_rhs (stmt);
6230 if (tree_swap_operands_p (lhs, rhs))
6232 gcond *gc = as_a <gcond *> (stmt);
6233 gimple_cond_set_lhs (gc, rhs);
6234 gimple_cond_set_rhs (gc, lhs);
6235 gimple_cond_set_code (gc,
6236 swap_tree_comparison (gimple_cond_code (gc)));
6237 changed = true;
6240 default:;
6243 /* Dispatch to pattern-based folding. */
6244 if (!inplace
6245 || is_gimple_assign (stmt)
6246 || gimple_code (stmt) == GIMPLE_COND)
6248 gimple_seq seq = NULL;
6249 gimple_match_op res_op;
6250 if (gimple_simplify (stmt, &res_op, inplace ? NULL : &seq,
6251 valueize, valueize))
6253 if (replace_stmt_with_simplification (gsi, &res_op, &seq, inplace))
6254 changed = true;
6255 else
6256 gimple_seq_discard (seq);
6260 stmt = gsi_stmt (*gsi);
6262 /* Fold the main computation performed by the statement. */
6263 switch (gimple_code (stmt))
6265 case GIMPLE_ASSIGN:
6267 /* Try to canonicalize for boolean-typed X the comparisons
6268 X == 0, X == 1, X != 0, and X != 1. */
6269 if (gimple_assign_rhs_code (stmt) == EQ_EXPR
6270 || gimple_assign_rhs_code (stmt) == NE_EXPR)
6272 tree lhs = gimple_assign_lhs (stmt);
6273 tree op1 = gimple_assign_rhs1 (stmt);
6274 tree op2 = gimple_assign_rhs2 (stmt);
6275 tree type = TREE_TYPE (op1);
6277 /* Check whether the comparison operands are of the same boolean
6278 type as the result type is.
6279 Check that second operand is an integer-constant with value
6280 one or zero. */
6281 if (TREE_CODE (op2) == INTEGER_CST
6282 && (integer_zerop (op2) || integer_onep (op2))
6283 && useless_type_conversion_p (TREE_TYPE (lhs), type))
6285 enum tree_code cmp_code = gimple_assign_rhs_code (stmt);
6286 bool is_logical_not = false;
6288 /* X == 0 and X != 1 is a logical-not.of X
6289 X == 1 and X != 0 is X */
6290 if ((cmp_code == EQ_EXPR && integer_zerop (op2))
6291 || (cmp_code == NE_EXPR && integer_onep (op2)))
6292 is_logical_not = true;
6294 if (is_logical_not == false)
6295 gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op1), op1);
6296 /* Only for one-bit precision typed X the transformation
6297 !X -> ~X is valied. */
6298 else if (TYPE_PRECISION (type) == 1)
6299 gimple_assign_set_rhs_with_ops (gsi, BIT_NOT_EXPR, op1);
6300 /* Otherwise we use !X -> X ^ 1. */
6301 else
6302 gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op1,
6303 build_int_cst (type, 1));
6304 changed = true;
6305 break;
6309 unsigned old_num_ops = gimple_num_ops (stmt);
6310 tree lhs = gimple_assign_lhs (stmt);
6311 tree new_rhs = fold_gimple_assign (gsi);
6312 if (new_rhs
6313 && !useless_type_conversion_p (TREE_TYPE (lhs),
6314 TREE_TYPE (new_rhs)))
6315 new_rhs = fold_convert (TREE_TYPE (lhs), new_rhs);
6316 if (new_rhs
6317 && (!inplace
6318 || get_gimple_rhs_num_ops (TREE_CODE (new_rhs)) < old_num_ops))
6320 gimple_assign_set_rhs_from_tree (gsi, new_rhs);
6321 changed = true;
6323 break;
6326 case GIMPLE_CALL:
6327 changed |= gimple_fold_call (gsi, inplace);
6328 break;
6330 case GIMPLE_DEBUG:
6331 if (gimple_debug_bind_p (stmt))
6333 tree val = gimple_debug_bind_get_value (stmt);
6334 if (val && REFERENCE_CLASS_P (val))
6336 tree tem = maybe_fold_reference (val);
6337 if (tem)
6339 gimple_debug_bind_set_value (stmt, tem);
6340 changed = true;
6344 break;
6346 case GIMPLE_RETURN:
6348 greturn *ret_stmt = as_a<greturn *> (stmt);
6349 tree ret = gimple_return_retval(ret_stmt);
6351 if (ret && TREE_CODE (ret) == SSA_NAME && valueize)
6353 tree val = valueize (ret);
6354 if (val && val != ret
6355 && may_propagate_copy (ret, val))
6357 gimple_return_set_retval (ret_stmt, val);
6358 changed = true;
6362 break;
6364 default:;
6367 stmt = gsi_stmt (*gsi);
6369 fold_undefer_overflow_warnings (changed && !nowarning, stmt, 0);
6370 return changed;
6373 /* Valueziation callback that ends up not following SSA edges. */
6375 tree
6376 no_follow_ssa_edges (tree)
6378 return NULL_TREE;
6381 /* Valueization callback that ends up following single-use SSA edges only. */
6383 tree
6384 follow_single_use_edges (tree val)
6386 if (TREE_CODE (val) == SSA_NAME
6387 && !has_single_use (val))
6388 return NULL_TREE;
6389 return val;
6392 /* Valueization callback that follows all SSA edges. */
6394 tree
6395 follow_all_ssa_edges (tree val)
6397 return val;
6400 /* Fold the statement pointed to by GSI. In some cases, this function may
6401 replace the whole statement with a new one. Returns true iff folding
6402 makes any changes.
6403 The statement pointed to by GSI should be in valid gimple form but may
6404 be in unfolded state as resulting from for example constant propagation
6405 which can produce *&x = 0. */
6407 bool
6408 fold_stmt (gimple_stmt_iterator *gsi)
6410 return fold_stmt_1 (gsi, false, no_follow_ssa_edges);
6413 bool
6414 fold_stmt (gimple_stmt_iterator *gsi, tree (*valueize) (tree))
6416 return fold_stmt_1 (gsi, false, valueize);
6419 /* Perform the minimal folding on statement *GSI. Only operations like
6420 *&x created by constant propagation are handled. The statement cannot
6421 be replaced with a new one. Return true if the statement was
6422 changed, false otherwise.
6423 The statement *GSI should be in valid gimple form but may
6424 be in unfolded state as resulting from for example constant propagation
6425 which can produce *&x = 0. */
6427 bool
6428 fold_stmt_inplace (gimple_stmt_iterator *gsi)
6430 gimple *stmt = gsi_stmt (*gsi);
6431 bool changed = fold_stmt_1 (gsi, true, no_follow_ssa_edges);
6432 gcc_assert (gsi_stmt (*gsi) == stmt);
6433 return changed;
6436 /* Canonicalize and possibly invert the boolean EXPR; return NULL_TREE
6437 if EXPR is null or we don't know how.
6438 If non-null, the result always has boolean type. */
6440 static tree
6441 canonicalize_bool (tree expr, bool invert)
6443 if (!expr)
6444 return NULL_TREE;
6445 else if (invert)
6447 if (integer_nonzerop (expr))
6448 return boolean_false_node;
6449 else if (integer_zerop (expr))
6450 return boolean_true_node;
6451 else if (TREE_CODE (expr) == SSA_NAME)
6452 return fold_build2 (EQ_EXPR, boolean_type_node, expr,
6453 build_int_cst (TREE_TYPE (expr), 0));
6454 else if (COMPARISON_CLASS_P (expr))
6455 return fold_build2 (invert_tree_comparison (TREE_CODE (expr), false),
6456 boolean_type_node,
6457 TREE_OPERAND (expr, 0),
6458 TREE_OPERAND (expr, 1));
6459 else
6460 return NULL_TREE;
6462 else
6464 if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE)
6465 return expr;
6466 if (integer_nonzerop (expr))
6467 return boolean_true_node;
6468 else if (integer_zerop (expr))
6469 return boolean_false_node;
6470 else if (TREE_CODE (expr) == SSA_NAME)
6471 return fold_build2 (NE_EXPR, boolean_type_node, expr,
6472 build_int_cst (TREE_TYPE (expr), 0));
6473 else if (COMPARISON_CLASS_P (expr))
6474 return fold_build2 (TREE_CODE (expr),
6475 boolean_type_node,
6476 TREE_OPERAND (expr, 0),
6477 TREE_OPERAND (expr, 1));
6478 else
6479 return NULL_TREE;
6483 /* Check to see if a boolean expression EXPR is logically equivalent to the
6484 comparison (OP1 CODE OP2). Check for various identities involving
6485 SSA_NAMEs. */
6487 static bool
6488 same_bool_comparison_p (const_tree expr, enum tree_code code,
6489 const_tree op1, const_tree op2)
6491 gimple *s;
6493 /* The obvious case. */
6494 if (TREE_CODE (expr) == code
6495 && operand_equal_p (TREE_OPERAND (expr, 0), op1, 0)
6496 && operand_equal_p (TREE_OPERAND (expr, 1), op2, 0))
6497 return true;
6499 /* Check for comparing (name, name != 0) and the case where expr
6500 is an SSA_NAME with a definition matching the comparison. */
6501 if (TREE_CODE (expr) == SSA_NAME
6502 && TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE)
6504 if (operand_equal_p (expr, op1, 0))
6505 return ((code == NE_EXPR && integer_zerop (op2))
6506 || (code == EQ_EXPR && integer_nonzerop (op2)));
6507 s = SSA_NAME_DEF_STMT (expr);
6508 if (is_gimple_assign (s)
6509 && gimple_assign_rhs_code (s) == code
6510 && operand_equal_p (gimple_assign_rhs1 (s), op1, 0)
6511 && operand_equal_p (gimple_assign_rhs2 (s), op2, 0))
6512 return true;
6515 /* If op1 is of the form (name != 0) or (name == 0), and the definition
6516 of name is a comparison, recurse. */
6517 if (TREE_CODE (op1) == SSA_NAME
6518 && TREE_CODE (TREE_TYPE (op1)) == BOOLEAN_TYPE)
6520 s = SSA_NAME_DEF_STMT (op1);
6521 if (is_gimple_assign (s)
6522 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison)
6524 enum tree_code c = gimple_assign_rhs_code (s);
6525 if ((c == NE_EXPR && integer_zerop (op2))
6526 || (c == EQ_EXPR && integer_nonzerop (op2)))
6527 return same_bool_comparison_p (expr, c,
6528 gimple_assign_rhs1 (s),
6529 gimple_assign_rhs2 (s));
6530 if ((c == EQ_EXPR && integer_zerop (op2))
6531 || (c == NE_EXPR && integer_nonzerop (op2)))
6532 return same_bool_comparison_p (expr,
6533 invert_tree_comparison (c, false),
6534 gimple_assign_rhs1 (s),
6535 gimple_assign_rhs2 (s));
6538 return false;
6541 /* Check to see if two boolean expressions OP1 and OP2 are logically
6542 equivalent. */
6544 static bool
6545 same_bool_result_p (const_tree op1, const_tree op2)
6547 /* Simple cases first. */
6548 if (operand_equal_p (op1, op2, 0))
6549 return true;
6551 /* Check the cases where at least one of the operands is a comparison.
6552 These are a bit smarter than operand_equal_p in that they apply some
6553 identifies on SSA_NAMEs. */
6554 if (COMPARISON_CLASS_P (op2)
6555 && same_bool_comparison_p (op1, TREE_CODE (op2),
6556 TREE_OPERAND (op2, 0),
6557 TREE_OPERAND (op2, 1)))
6558 return true;
6559 if (COMPARISON_CLASS_P (op1)
6560 && same_bool_comparison_p (op2, TREE_CODE (op1),
6561 TREE_OPERAND (op1, 0),
6562 TREE_OPERAND (op1, 1)))
6563 return true;
6565 /* Default case. */
6566 return false;
6569 /* Forward declarations for some mutually recursive functions. */
6571 static tree
6572 and_comparisons_1 (tree type, enum tree_code code1, tree op1a, tree op1b,
6573 enum tree_code code2, tree op2a, tree op2b, basic_block);
6574 static tree
6575 and_var_with_comparison (tree type, tree var, bool invert,
6576 enum tree_code code2, tree op2a, tree op2b,
6577 basic_block);
6578 static tree
6579 and_var_with_comparison_1 (tree type, gimple *stmt,
6580 enum tree_code code2, tree op2a, tree op2b,
6581 basic_block);
6582 static tree
6583 or_comparisons_1 (tree, enum tree_code code1, tree op1a, tree op1b,
6584 enum tree_code code2, tree op2a, tree op2b,
6585 basic_block);
6586 static tree
6587 or_var_with_comparison (tree, tree var, bool invert,
6588 enum tree_code code2, tree op2a, tree op2b,
6589 basic_block);
6590 static tree
6591 or_var_with_comparison_1 (tree, gimple *stmt,
6592 enum tree_code code2, tree op2a, tree op2b,
6593 basic_block);
6595 /* Helper function for and_comparisons_1: try to simplify the AND of the
6596 ssa variable VAR with the comparison specified by (OP2A CODE2 OP2B).
6597 If INVERT is true, invert the value of the VAR before doing the AND.
6598 Return NULL_EXPR if we can't simplify this to a single expression. */
6600 static tree
6601 and_var_with_comparison (tree type, tree var, bool invert,
6602 enum tree_code code2, tree op2a, tree op2b,
6603 basic_block outer_cond_bb)
6605 tree t;
6606 gimple *stmt = SSA_NAME_DEF_STMT (var);
6608 /* We can only deal with variables whose definitions are assignments. */
6609 if (!is_gimple_assign (stmt))
6610 return NULL_TREE;
6612 /* If we have an inverted comparison, apply DeMorgan's law and rewrite
6613 !var AND (op2a code2 op2b) => !(var OR !(op2a code2 op2b))
6614 Then we only have to consider the simpler non-inverted cases. */
6615 if (invert)
6616 t = or_var_with_comparison_1 (type, stmt,
6617 invert_tree_comparison (code2, false),
6618 op2a, op2b, outer_cond_bb);
6619 else
6620 t = and_var_with_comparison_1 (type, stmt, code2, op2a, op2b,
6621 outer_cond_bb);
6622 return canonicalize_bool (t, invert);
6625 /* Try to simplify the AND of the ssa variable defined by the assignment
6626 STMT with the comparison specified by (OP2A CODE2 OP2B).
6627 Return NULL_EXPR if we can't simplify this to a single expression. */
6629 static tree
6630 and_var_with_comparison_1 (tree type, gimple *stmt,
6631 enum tree_code code2, tree op2a, tree op2b,
6632 basic_block outer_cond_bb)
6634 tree var = gimple_assign_lhs (stmt);
6635 tree true_test_var = NULL_TREE;
6636 tree false_test_var = NULL_TREE;
6637 enum tree_code innercode = gimple_assign_rhs_code (stmt);
6639 /* Check for identities like (var AND (var == 0)) => false. */
6640 if (TREE_CODE (op2a) == SSA_NAME
6641 && TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE)
6643 if ((code2 == NE_EXPR && integer_zerop (op2b))
6644 || (code2 == EQ_EXPR && integer_nonzerop (op2b)))
6646 true_test_var = op2a;
6647 if (var == true_test_var)
6648 return var;
6650 else if ((code2 == EQ_EXPR && integer_zerop (op2b))
6651 || (code2 == NE_EXPR && integer_nonzerop (op2b)))
6653 false_test_var = op2a;
6654 if (var == false_test_var)
6655 return boolean_false_node;
6659 /* If the definition is a comparison, recurse on it. */
6660 if (TREE_CODE_CLASS (innercode) == tcc_comparison)
6662 tree t = and_comparisons_1 (type, innercode,
6663 gimple_assign_rhs1 (stmt),
6664 gimple_assign_rhs2 (stmt),
6665 code2,
6666 op2a,
6667 op2b, outer_cond_bb);
6668 if (t)
6669 return t;
6672 /* If the definition is an AND or OR expression, we may be able to
6673 simplify by reassociating. */
6674 if (TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE
6675 && (innercode == BIT_AND_EXPR || innercode == BIT_IOR_EXPR))
6677 tree inner1 = gimple_assign_rhs1 (stmt);
6678 tree inner2 = gimple_assign_rhs2 (stmt);
6679 gimple *s;
6680 tree t;
6681 tree partial = NULL_TREE;
6682 bool is_and = (innercode == BIT_AND_EXPR);
6684 /* Check for boolean identities that don't require recursive examination
6685 of inner1/inner2:
6686 inner1 AND (inner1 AND inner2) => inner1 AND inner2 => var
6687 inner1 AND (inner1 OR inner2) => inner1
6688 !inner1 AND (inner1 AND inner2) => false
6689 !inner1 AND (inner1 OR inner2) => !inner1 AND inner2
6690 Likewise for similar cases involving inner2. */
6691 if (inner1 == true_test_var)
6692 return (is_and ? var : inner1);
6693 else if (inner2 == true_test_var)
6694 return (is_and ? var : inner2);
6695 else if (inner1 == false_test_var)
6696 return (is_and
6697 ? boolean_false_node
6698 : and_var_with_comparison (type, inner2, false, code2, op2a,
6699 op2b, outer_cond_bb));
6700 else if (inner2 == false_test_var)
6701 return (is_and
6702 ? boolean_false_node
6703 : and_var_with_comparison (type, inner1, false, code2, op2a,
6704 op2b, outer_cond_bb));
6706 /* Next, redistribute/reassociate the AND across the inner tests.
6707 Compute the first partial result, (inner1 AND (op2a code op2b)) */
6708 if (TREE_CODE (inner1) == SSA_NAME
6709 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner1))
6710 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
6711 && (t = maybe_fold_and_comparisons (type, gimple_assign_rhs_code (s),
6712 gimple_assign_rhs1 (s),
6713 gimple_assign_rhs2 (s),
6714 code2, op2a, op2b,
6715 outer_cond_bb)))
6717 /* Handle the AND case, where we are reassociating:
6718 (inner1 AND inner2) AND (op2a code2 op2b)
6719 => (t AND inner2)
6720 If the partial result t is a constant, we win. Otherwise
6721 continue on to try reassociating with the other inner test. */
6722 if (is_and)
6724 if (integer_onep (t))
6725 return inner2;
6726 else if (integer_zerop (t))
6727 return boolean_false_node;
6730 /* Handle the OR case, where we are redistributing:
6731 (inner1 OR inner2) AND (op2a code2 op2b)
6732 => (t OR (inner2 AND (op2a code2 op2b))) */
6733 else if (integer_onep (t))
6734 return boolean_true_node;
6736 /* Save partial result for later. */
6737 partial = t;
6740 /* Compute the second partial result, (inner2 AND (op2a code op2b)) */
6741 if (TREE_CODE (inner2) == SSA_NAME
6742 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner2))
6743 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
6744 && (t = maybe_fold_and_comparisons (type, gimple_assign_rhs_code (s),
6745 gimple_assign_rhs1 (s),
6746 gimple_assign_rhs2 (s),
6747 code2, op2a, op2b,
6748 outer_cond_bb)))
6750 /* Handle the AND case, where we are reassociating:
6751 (inner1 AND inner2) AND (op2a code2 op2b)
6752 => (inner1 AND t) */
6753 if (is_and)
6755 if (integer_onep (t))
6756 return inner1;
6757 else if (integer_zerop (t))
6758 return boolean_false_node;
6759 /* If both are the same, we can apply the identity
6760 (x AND x) == x. */
6761 else if (partial && same_bool_result_p (t, partial))
6762 return t;
6765 /* Handle the OR case. where we are redistributing:
6766 (inner1 OR inner2) AND (op2a code2 op2b)
6767 => (t OR (inner1 AND (op2a code2 op2b)))
6768 => (t OR partial) */
6769 else
6771 if (integer_onep (t))
6772 return boolean_true_node;
6773 else if (partial)
6775 /* We already got a simplification for the other
6776 operand to the redistributed OR expression. The
6777 interesting case is when at least one is false.
6778 Or, if both are the same, we can apply the identity
6779 (x OR x) == x. */
6780 if (integer_zerop (partial))
6781 return t;
6782 else if (integer_zerop (t))
6783 return partial;
6784 else if (same_bool_result_p (t, partial))
6785 return t;
6790 return NULL_TREE;
6793 /* Try to simplify the AND of two comparisons defined by
6794 (OP1A CODE1 OP1B) and (OP2A CODE2 OP2B), respectively.
6795 If this can be done without constructing an intermediate value,
6796 return the resulting tree; otherwise NULL_TREE is returned.
6797 This function is deliberately asymmetric as it recurses on SSA_DEFs
6798 in the first comparison but not the second. */
6800 static tree
6801 and_comparisons_1 (tree type, enum tree_code code1, tree op1a, tree op1b,
6802 enum tree_code code2, tree op2a, tree op2b,
6803 basic_block outer_cond_bb)
6805 tree truth_type = truth_type_for (TREE_TYPE (op1a));
6807 /* First check for ((x CODE1 y) AND (x CODE2 y)). */
6808 if (operand_equal_p (op1a, op2a, 0)
6809 && operand_equal_p (op1b, op2b, 0))
6811 /* Result will be either NULL_TREE, or a combined comparison. */
6812 tree t = combine_comparisons (UNKNOWN_LOCATION,
6813 TRUTH_ANDIF_EXPR, code1, code2,
6814 truth_type, op1a, op1b);
6815 if (t)
6816 return t;
6819 /* Likewise the swapped case of the above. */
6820 if (operand_equal_p (op1a, op2b, 0)
6821 && operand_equal_p (op1b, op2a, 0))
6823 /* Result will be either NULL_TREE, or a combined comparison. */
6824 tree t = combine_comparisons (UNKNOWN_LOCATION,
6825 TRUTH_ANDIF_EXPR, code1,
6826 swap_tree_comparison (code2),
6827 truth_type, op1a, op1b);
6828 if (t)
6829 return t;
6832 /* Perhaps the first comparison is (NAME != 0) or (NAME == 1) where
6833 NAME's definition is a truth value. See if there are any simplifications
6834 that can be done against the NAME's definition. */
6835 if (TREE_CODE (op1a) == SSA_NAME
6836 && (code1 == NE_EXPR || code1 == EQ_EXPR)
6837 && (integer_zerop (op1b) || integer_onep (op1b)))
6839 bool invert = ((code1 == EQ_EXPR && integer_zerop (op1b))
6840 || (code1 == NE_EXPR && integer_onep (op1b)));
6841 gimple *stmt = SSA_NAME_DEF_STMT (op1a);
6842 switch (gimple_code (stmt))
6844 case GIMPLE_ASSIGN:
6845 /* Try to simplify by copy-propagating the definition. */
6846 return and_var_with_comparison (type, op1a, invert, code2, op2a,
6847 op2b, outer_cond_bb);
6849 case GIMPLE_PHI:
6850 /* If every argument to the PHI produces the same result when
6851 ANDed with the second comparison, we win.
6852 Do not do this unless the type is bool since we need a bool
6853 result here anyway. */
6854 if (TREE_CODE (TREE_TYPE (op1a)) == BOOLEAN_TYPE)
6856 tree result = NULL_TREE;
6857 unsigned i;
6858 for (i = 0; i < gimple_phi_num_args (stmt); i++)
6860 tree arg = gimple_phi_arg_def (stmt, i);
6862 /* If this PHI has itself as an argument, ignore it.
6863 If all the other args produce the same result,
6864 we're still OK. */
6865 if (arg == gimple_phi_result (stmt))
6866 continue;
6867 else if (TREE_CODE (arg) == INTEGER_CST)
6869 if (invert ? integer_nonzerop (arg) : integer_zerop (arg))
6871 if (!result)
6872 result = boolean_false_node;
6873 else if (!integer_zerop (result))
6874 return NULL_TREE;
6876 else if (!result)
6877 result = fold_build2 (code2, boolean_type_node,
6878 op2a, op2b);
6879 else if (!same_bool_comparison_p (result,
6880 code2, op2a, op2b))
6881 return NULL_TREE;
6883 else if (TREE_CODE (arg) == SSA_NAME
6884 && !SSA_NAME_IS_DEFAULT_DEF (arg))
6886 tree temp;
6887 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
6888 /* In simple cases we can look through PHI nodes,
6889 but we have to be careful with loops.
6890 See PR49073. */
6891 if (! dom_info_available_p (CDI_DOMINATORS)
6892 || gimple_bb (def_stmt) == gimple_bb (stmt)
6893 || dominated_by_p (CDI_DOMINATORS,
6894 gimple_bb (def_stmt),
6895 gimple_bb (stmt)))
6896 return NULL_TREE;
6897 temp = and_var_with_comparison (type, arg, invert, code2,
6898 op2a, op2b,
6899 outer_cond_bb);
6900 if (!temp)
6901 return NULL_TREE;
6902 else if (!result)
6903 result = temp;
6904 else if (!same_bool_result_p (result, temp))
6905 return NULL_TREE;
6907 else
6908 return NULL_TREE;
6910 return result;
6913 default:
6914 break;
6917 return NULL_TREE;
6920 static basic_block fosa_bb;
6921 static vec<std::pair<tree, void *> > *fosa_unwind;
6922 static tree
6923 follow_outer_ssa_edges (tree val)
6925 if (TREE_CODE (val) == SSA_NAME
6926 && !SSA_NAME_IS_DEFAULT_DEF (val))
6928 basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (val));
6929 if (!def_bb
6930 || def_bb == fosa_bb
6931 || (dom_info_available_p (CDI_DOMINATORS)
6932 && (def_bb == fosa_bb
6933 || dominated_by_p (CDI_DOMINATORS, fosa_bb, def_bb))))
6934 return val;
6935 /* We cannot temporarily rewrite stmts with undefined overflow
6936 behavior, so avoid expanding them. */
6937 if ((ANY_INTEGRAL_TYPE_P (TREE_TYPE (val))
6938 || POINTER_TYPE_P (TREE_TYPE (val)))
6939 && !TYPE_OVERFLOW_WRAPS (TREE_TYPE (val)))
6940 return NULL_TREE;
6941 /* If the definition does not dominate fosa_bb temporarily reset
6942 flow-sensitive info. */
6943 if (val->ssa_name.info.range_info)
6945 fosa_unwind->safe_push (std::make_pair
6946 (val, val->ssa_name.info.range_info));
6947 val->ssa_name.info.range_info = NULL;
6949 return val;
6951 return val;
6954 /* Helper function for maybe_fold_and_comparisons and maybe_fold_or_comparisons
6955 : try to simplify the AND/OR of the ssa variable VAR with the comparison
6956 specified by (OP2A CODE2 OP2B) from match.pd. Return NULL_EXPR if we can't
6957 simplify this to a single expression. As we are going to lower the cost
6958 of building SSA names / gimple stmts significantly, we need to allocate
6959 them ont the stack. This will cause the code to be a bit ugly. */
6961 static tree
6962 maybe_fold_comparisons_from_match_pd (tree type, enum tree_code code,
6963 enum tree_code code1,
6964 tree op1a, tree op1b,
6965 enum tree_code code2, tree op2a,
6966 tree op2b,
6967 basic_block outer_cond_bb)
6969 /* Allocate gimple stmt1 on the stack. */
6970 gassign *stmt1
6971 = (gassign *) XALLOCAVEC (char, gimple_size (GIMPLE_ASSIGN, 3));
6972 gimple_init (stmt1, GIMPLE_ASSIGN, 3);
6973 gimple_assign_set_rhs_code (stmt1, code1);
6974 gimple_assign_set_rhs1 (stmt1, op1a);
6975 gimple_assign_set_rhs2 (stmt1, op1b);
6976 gimple_set_bb (stmt1, NULL);
6978 /* Allocate gimple stmt2 on the stack. */
6979 gassign *stmt2
6980 = (gassign *) XALLOCAVEC (char, gimple_size (GIMPLE_ASSIGN, 3));
6981 gimple_init (stmt2, GIMPLE_ASSIGN, 3);
6982 gimple_assign_set_rhs_code (stmt2, code2);
6983 gimple_assign_set_rhs1 (stmt2, op2a);
6984 gimple_assign_set_rhs2 (stmt2, op2b);
6985 gimple_set_bb (stmt2, NULL);
6987 /* Allocate SSA names(lhs1) on the stack. */
6988 tree lhs1 = (tree)XALLOCA (tree_ssa_name);
6989 memset (lhs1, 0, sizeof (tree_ssa_name));
6990 TREE_SET_CODE (lhs1, SSA_NAME);
6991 TREE_TYPE (lhs1) = type;
6992 init_ssa_name_imm_use (lhs1);
6994 /* Allocate SSA names(lhs2) on the stack. */
6995 tree lhs2 = (tree)XALLOCA (tree_ssa_name);
6996 memset (lhs2, 0, sizeof (tree_ssa_name));
6997 TREE_SET_CODE (lhs2, SSA_NAME);
6998 TREE_TYPE (lhs2) = type;
6999 init_ssa_name_imm_use (lhs2);
7001 gimple_assign_set_lhs (stmt1, lhs1);
7002 gimple_assign_set_lhs (stmt2, lhs2);
7004 gimple_match_op op (gimple_match_cond::UNCOND, code,
7005 type, gimple_assign_lhs (stmt1),
7006 gimple_assign_lhs (stmt2));
7007 fosa_bb = outer_cond_bb;
7008 auto_vec<std::pair<tree, void *>, 8> unwind_stack;
7009 fosa_unwind = &unwind_stack;
7010 if (op.resimplify (NULL, (!outer_cond_bb
7011 ? follow_all_ssa_edges : follow_outer_ssa_edges)))
7013 fosa_unwind = NULL;
7014 for (auto p : unwind_stack)
7015 p.first->ssa_name.info.range_info = p.second;
7016 if (gimple_simplified_result_is_gimple_val (&op))
7018 tree res = op.ops[0];
7019 if (res == lhs1)
7020 return build2 (code1, type, op1a, op1b);
7021 else if (res == lhs2)
7022 return build2 (code2, type, op2a, op2b);
7023 else
7024 return res;
7026 else if (op.code.is_tree_code ()
7027 && TREE_CODE_CLASS ((tree_code)op.code) == tcc_comparison)
7029 tree op0 = op.ops[0];
7030 tree op1 = op.ops[1];
7031 if (op0 == lhs1 || op0 == lhs2 || op1 == lhs1 || op1 == lhs2)
7032 return NULL_TREE; /* not simple */
7034 return build2 ((enum tree_code)op.code, op.type, op0, op1);
7037 fosa_unwind = NULL;
7038 for (auto p : unwind_stack)
7039 p.first->ssa_name.info.range_info = p.second;
7041 return NULL_TREE;
7044 /* Try to simplify the AND of two comparisons, specified by
7045 (OP1A CODE1 OP1B) and (OP2B CODE2 OP2B), respectively.
7046 If this can be simplified to a single expression (without requiring
7047 introducing more SSA variables to hold intermediate values),
7048 return the resulting tree. Otherwise return NULL_TREE.
7049 If the result expression is non-null, it has boolean type. */
7051 tree
7052 maybe_fold_and_comparisons (tree type,
7053 enum tree_code code1, tree op1a, tree op1b,
7054 enum tree_code code2, tree op2a, tree op2b,
7055 basic_block outer_cond_bb)
7057 if (tree t = and_comparisons_1 (type, code1, op1a, op1b, code2, op2a, op2b,
7058 outer_cond_bb))
7059 return t;
7061 if (tree t = and_comparisons_1 (type, code2, op2a, op2b, code1, op1a, op1b,
7062 outer_cond_bb))
7063 return t;
7065 if (tree t = maybe_fold_comparisons_from_match_pd (type, BIT_AND_EXPR, code1,
7066 op1a, op1b, code2, op2a,
7067 op2b, outer_cond_bb))
7068 return t;
7070 return NULL_TREE;
7073 /* Helper function for or_comparisons_1: try to simplify the OR of the
7074 ssa variable VAR with the comparison specified by (OP2A CODE2 OP2B).
7075 If INVERT is true, invert the value of VAR before doing the OR.
7076 Return NULL_EXPR if we can't simplify this to a single expression. */
7078 static tree
7079 or_var_with_comparison (tree type, tree var, bool invert,
7080 enum tree_code code2, tree op2a, tree op2b,
7081 basic_block outer_cond_bb)
7083 tree t;
7084 gimple *stmt = SSA_NAME_DEF_STMT (var);
7086 /* We can only deal with variables whose definitions are assignments. */
7087 if (!is_gimple_assign (stmt))
7088 return NULL_TREE;
7090 /* If we have an inverted comparison, apply DeMorgan's law and rewrite
7091 !var OR (op2a code2 op2b) => !(var AND !(op2a code2 op2b))
7092 Then we only have to consider the simpler non-inverted cases. */
7093 if (invert)
7094 t = and_var_with_comparison_1 (type, stmt,
7095 invert_tree_comparison (code2, false),
7096 op2a, op2b, outer_cond_bb);
7097 else
7098 t = or_var_with_comparison_1 (type, stmt, code2, op2a, op2b,
7099 outer_cond_bb);
7100 return canonicalize_bool (t, invert);
7103 /* Try to simplify the OR of the ssa variable defined by the assignment
7104 STMT with the comparison specified by (OP2A CODE2 OP2B).
7105 Return NULL_EXPR if we can't simplify this to a single expression. */
7107 static tree
7108 or_var_with_comparison_1 (tree type, gimple *stmt,
7109 enum tree_code code2, tree op2a, tree op2b,
7110 basic_block outer_cond_bb)
7112 tree var = gimple_assign_lhs (stmt);
7113 tree true_test_var = NULL_TREE;
7114 tree false_test_var = NULL_TREE;
7115 enum tree_code innercode = gimple_assign_rhs_code (stmt);
7117 /* Check for identities like (var OR (var != 0)) => true . */
7118 if (TREE_CODE (op2a) == SSA_NAME
7119 && TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE)
7121 if ((code2 == NE_EXPR && integer_zerop (op2b))
7122 || (code2 == EQ_EXPR && integer_nonzerop (op2b)))
7124 true_test_var = op2a;
7125 if (var == true_test_var)
7126 return var;
7128 else if ((code2 == EQ_EXPR && integer_zerop (op2b))
7129 || (code2 == NE_EXPR && integer_nonzerop (op2b)))
7131 false_test_var = op2a;
7132 if (var == false_test_var)
7133 return boolean_true_node;
7137 /* If the definition is a comparison, recurse on it. */
7138 if (TREE_CODE_CLASS (innercode) == tcc_comparison)
7140 tree t = or_comparisons_1 (type, innercode,
7141 gimple_assign_rhs1 (stmt),
7142 gimple_assign_rhs2 (stmt),
7143 code2, op2a, op2b, outer_cond_bb);
7144 if (t)
7145 return t;
7148 /* If the definition is an AND or OR expression, we may be able to
7149 simplify by reassociating. */
7150 if (TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE
7151 && (innercode == BIT_AND_EXPR || innercode == BIT_IOR_EXPR))
7153 tree inner1 = gimple_assign_rhs1 (stmt);
7154 tree inner2 = gimple_assign_rhs2 (stmt);
7155 gimple *s;
7156 tree t;
7157 tree partial = NULL_TREE;
7158 bool is_or = (innercode == BIT_IOR_EXPR);
7160 /* Check for boolean identities that don't require recursive examination
7161 of inner1/inner2:
7162 inner1 OR (inner1 OR inner2) => inner1 OR inner2 => var
7163 inner1 OR (inner1 AND inner2) => inner1
7164 !inner1 OR (inner1 OR inner2) => true
7165 !inner1 OR (inner1 AND inner2) => !inner1 OR inner2
7167 if (inner1 == true_test_var)
7168 return (is_or ? var : inner1);
7169 else if (inner2 == true_test_var)
7170 return (is_or ? var : inner2);
7171 else if (inner1 == false_test_var)
7172 return (is_or
7173 ? boolean_true_node
7174 : or_var_with_comparison (type, inner2, false, code2, op2a,
7175 op2b, outer_cond_bb));
7176 else if (inner2 == false_test_var)
7177 return (is_or
7178 ? boolean_true_node
7179 : or_var_with_comparison (type, inner1, false, code2, op2a,
7180 op2b, outer_cond_bb));
7182 /* Next, redistribute/reassociate the OR across the inner tests.
7183 Compute the first partial result, (inner1 OR (op2a code op2b)) */
7184 if (TREE_CODE (inner1) == SSA_NAME
7185 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner1))
7186 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
7187 && (t = maybe_fold_or_comparisons (type, gimple_assign_rhs_code (s),
7188 gimple_assign_rhs1 (s),
7189 gimple_assign_rhs2 (s),
7190 code2, op2a, op2b,
7191 outer_cond_bb)))
7193 /* Handle the OR case, where we are reassociating:
7194 (inner1 OR inner2) OR (op2a code2 op2b)
7195 => (t OR inner2)
7196 If the partial result t is a constant, we win. Otherwise
7197 continue on to try reassociating with the other inner test. */
7198 if (is_or)
7200 if (integer_onep (t))
7201 return boolean_true_node;
7202 else if (integer_zerop (t))
7203 return inner2;
7206 /* Handle the AND case, where we are redistributing:
7207 (inner1 AND inner2) OR (op2a code2 op2b)
7208 => (t AND (inner2 OR (op2a code op2b))) */
7209 else if (integer_zerop (t))
7210 return boolean_false_node;
7212 /* Save partial result for later. */
7213 partial = t;
7216 /* Compute the second partial result, (inner2 OR (op2a code op2b)) */
7217 if (TREE_CODE (inner2) == SSA_NAME
7218 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner2))
7219 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
7220 && (t = maybe_fold_or_comparisons (type, gimple_assign_rhs_code (s),
7221 gimple_assign_rhs1 (s),
7222 gimple_assign_rhs2 (s),
7223 code2, op2a, op2b,
7224 outer_cond_bb)))
7226 /* Handle the OR case, where we are reassociating:
7227 (inner1 OR inner2) OR (op2a code2 op2b)
7228 => (inner1 OR t)
7229 => (t OR partial) */
7230 if (is_or)
7232 if (integer_zerop (t))
7233 return inner1;
7234 else if (integer_onep (t))
7235 return boolean_true_node;
7236 /* If both are the same, we can apply the identity
7237 (x OR x) == x. */
7238 else if (partial && same_bool_result_p (t, partial))
7239 return t;
7242 /* Handle the AND case, where we are redistributing:
7243 (inner1 AND inner2) OR (op2a code2 op2b)
7244 => (t AND (inner1 OR (op2a code2 op2b)))
7245 => (t AND partial) */
7246 else
7248 if (integer_zerop (t))
7249 return boolean_false_node;
7250 else if (partial)
7252 /* We already got a simplification for the other
7253 operand to the redistributed AND expression. The
7254 interesting case is when at least one is true.
7255 Or, if both are the same, we can apply the identity
7256 (x AND x) == x. */
7257 if (integer_onep (partial))
7258 return t;
7259 else if (integer_onep (t))
7260 return partial;
7261 else if (same_bool_result_p (t, partial))
7262 return t;
7267 return NULL_TREE;
7270 /* Try to simplify the OR of two comparisons defined by
7271 (OP1A CODE1 OP1B) and (OP2A CODE2 OP2B), respectively.
7272 If this can be done without constructing an intermediate value,
7273 return the resulting tree; otherwise NULL_TREE is returned.
7274 This function is deliberately asymmetric as it recurses on SSA_DEFs
7275 in the first comparison but not the second. */
7277 static tree
7278 or_comparisons_1 (tree type, enum tree_code code1, tree op1a, tree op1b,
7279 enum tree_code code2, tree op2a, tree op2b,
7280 basic_block outer_cond_bb)
7282 tree truth_type = truth_type_for (TREE_TYPE (op1a));
7284 /* First check for ((x CODE1 y) OR (x CODE2 y)). */
7285 if (operand_equal_p (op1a, op2a, 0)
7286 && operand_equal_p (op1b, op2b, 0))
7288 /* Result will be either NULL_TREE, or a combined comparison. */
7289 tree t = combine_comparisons (UNKNOWN_LOCATION,
7290 TRUTH_ORIF_EXPR, code1, code2,
7291 truth_type, op1a, op1b);
7292 if (t)
7293 return t;
7296 /* Likewise the swapped case of the above. */
7297 if (operand_equal_p (op1a, op2b, 0)
7298 && operand_equal_p (op1b, op2a, 0))
7300 /* Result will be either NULL_TREE, or a combined comparison. */
7301 tree t = combine_comparisons (UNKNOWN_LOCATION,
7302 TRUTH_ORIF_EXPR, code1,
7303 swap_tree_comparison (code2),
7304 truth_type, op1a, op1b);
7305 if (t)
7306 return t;
7309 /* Perhaps the first comparison is (NAME != 0) or (NAME == 1) where
7310 NAME's definition is a truth value. See if there are any simplifications
7311 that can be done against the NAME's definition. */
7312 if (TREE_CODE (op1a) == SSA_NAME
7313 && (code1 == NE_EXPR || code1 == EQ_EXPR)
7314 && (integer_zerop (op1b) || integer_onep (op1b)))
7316 bool invert = ((code1 == EQ_EXPR && integer_zerop (op1b))
7317 || (code1 == NE_EXPR && integer_onep (op1b)));
7318 gimple *stmt = SSA_NAME_DEF_STMT (op1a);
7319 switch (gimple_code (stmt))
7321 case GIMPLE_ASSIGN:
7322 /* Try to simplify by copy-propagating the definition. */
7323 return or_var_with_comparison (type, op1a, invert, code2, op2a,
7324 op2b, outer_cond_bb);
7326 case GIMPLE_PHI:
7327 /* If every argument to the PHI produces the same result when
7328 ORed with the second comparison, we win.
7329 Do not do this unless the type is bool since we need a bool
7330 result here anyway. */
7331 if (TREE_CODE (TREE_TYPE (op1a)) == BOOLEAN_TYPE)
7333 tree result = NULL_TREE;
7334 unsigned i;
7335 for (i = 0; i < gimple_phi_num_args (stmt); i++)
7337 tree arg = gimple_phi_arg_def (stmt, i);
7339 /* If this PHI has itself as an argument, ignore it.
7340 If all the other args produce the same result,
7341 we're still OK. */
7342 if (arg == gimple_phi_result (stmt))
7343 continue;
7344 else if (TREE_CODE (arg) == INTEGER_CST)
7346 if (invert ? integer_zerop (arg) : integer_nonzerop (arg))
7348 if (!result)
7349 result = boolean_true_node;
7350 else if (!integer_onep (result))
7351 return NULL_TREE;
7353 else if (!result)
7354 result = fold_build2 (code2, boolean_type_node,
7355 op2a, op2b);
7356 else if (!same_bool_comparison_p (result,
7357 code2, op2a, op2b))
7358 return NULL_TREE;
7360 else if (TREE_CODE (arg) == SSA_NAME
7361 && !SSA_NAME_IS_DEFAULT_DEF (arg))
7363 tree temp;
7364 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
7365 /* In simple cases we can look through PHI nodes,
7366 but we have to be careful with loops.
7367 See PR49073. */
7368 if (! dom_info_available_p (CDI_DOMINATORS)
7369 || gimple_bb (def_stmt) == gimple_bb (stmt)
7370 || dominated_by_p (CDI_DOMINATORS,
7371 gimple_bb (def_stmt),
7372 gimple_bb (stmt)))
7373 return NULL_TREE;
7374 temp = or_var_with_comparison (type, arg, invert, code2,
7375 op2a, op2b, outer_cond_bb);
7376 if (!temp)
7377 return NULL_TREE;
7378 else if (!result)
7379 result = temp;
7380 else if (!same_bool_result_p (result, temp))
7381 return NULL_TREE;
7383 else
7384 return NULL_TREE;
7386 return result;
7389 default:
7390 break;
7393 return NULL_TREE;
7396 /* Try to simplify the OR of two comparisons, specified by
7397 (OP1A CODE1 OP1B) and (OP2B CODE2 OP2B), respectively.
7398 If this can be simplified to a single expression (without requiring
7399 introducing more SSA variables to hold intermediate values),
7400 return the resulting tree. Otherwise return NULL_TREE.
7401 If the result expression is non-null, it has boolean type. */
7403 tree
7404 maybe_fold_or_comparisons (tree type,
7405 enum tree_code code1, tree op1a, tree op1b,
7406 enum tree_code code2, tree op2a, tree op2b,
7407 basic_block outer_cond_bb)
7409 if (tree t = or_comparisons_1 (type, code1, op1a, op1b, code2, op2a, op2b,
7410 outer_cond_bb))
7411 return t;
7413 if (tree t = or_comparisons_1 (type, code2, op2a, op2b, code1, op1a, op1b,
7414 outer_cond_bb))
7415 return t;
7417 if (tree t = maybe_fold_comparisons_from_match_pd (type, BIT_IOR_EXPR, code1,
7418 op1a, op1b, code2, op2a,
7419 op2b, outer_cond_bb))
7420 return t;
7422 return NULL_TREE;
7425 /* Fold STMT to a constant using VALUEIZE to valueize SSA names.
7427 Either NULL_TREE, a simplified but non-constant or a constant
7428 is returned.
7430 ??? This should go into a gimple-fold-inline.h file to be eventually
7431 privatized with the single valueize function used in the various TUs
7432 to avoid the indirect function call overhead. */
7434 tree
7435 gimple_fold_stmt_to_constant_1 (gimple *stmt, tree (*valueize) (tree),
7436 tree (*gvalueize) (tree))
7438 gimple_match_op res_op;
7439 /* ??? The SSA propagators do not correctly deal with following SSA use-def
7440 edges if there are intermediate VARYING defs. For this reason
7441 do not follow SSA edges here even though SCCVN can technically
7442 just deal fine with that. */
7443 if (gimple_simplify (stmt, &res_op, NULL, gvalueize, valueize))
7445 tree res = NULL_TREE;
7446 if (gimple_simplified_result_is_gimple_val (&res_op))
7447 res = res_op.ops[0];
7448 else if (mprts_hook)
7449 res = mprts_hook (&res_op);
7450 if (res)
7452 if (dump_file && dump_flags & TDF_DETAILS)
7454 fprintf (dump_file, "Match-and-simplified ");
7455 print_gimple_expr (dump_file, stmt, 0, TDF_SLIM);
7456 fprintf (dump_file, " to ");
7457 print_generic_expr (dump_file, res);
7458 fprintf (dump_file, "\n");
7460 return res;
7464 location_t loc = gimple_location (stmt);
7465 switch (gimple_code (stmt))
7467 case GIMPLE_ASSIGN:
7469 enum tree_code subcode = gimple_assign_rhs_code (stmt);
7471 switch (get_gimple_rhs_class (subcode))
7473 case GIMPLE_SINGLE_RHS:
7475 tree rhs = gimple_assign_rhs1 (stmt);
7476 enum tree_code_class kind = TREE_CODE_CLASS (subcode);
7478 if (TREE_CODE (rhs) == SSA_NAME)
7480 /* If the RHS is an SSA_NAME, return its known constant value,
7481 if any. */
7482 return (*valueize) (rhs);
7484 /* Handle propagating invariant addresses into address
7485 operations. */
7486 else if (TREE_CODE (rhs) == ADDR_EXPR
7487 && !is_gimple_min_invariant (rhs))
7489 poly_int64 offset = 0;
7490 tree base;
7491 base = get_addr_base_and_unit_offset_1 (TREE_OPERAND (rhs, 0),
7492 &offset,
7493 valueize);
7494 if (base
7495 && (CONSTANT_CLASS_P (base)
7496 || decl_address_invariant_p (base)))
7497 return build_invariant_address (TREE_TYPE (rhs),
7498 base, offset);
7500 else if (TREE_CODE (rhs) == CONSTRUCTOR
7501 && TREE_CODE (TREE_TYPE (rhs)) == VECTOR_TYPE
7502 && known_eq (CONSTRUCTOR_NELTS (rhs),
7503 TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs))))
7505 unsigned i, nelts;
7506 tree val;
7508 nelts = CONSTRUCTOR_NELTS (rhs);
7509 tree_vector_builder vec (TREE_TYPE (rhs), nelts, 1);
7510 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), i, val)
7512 val = (*valueize) (val);
7513 if (TREE_CODE (val) == INTEGER_CST
7514 || TREE_CODE (val) == REAL_CST
7515 || TREE_CODE (val) == FIXED_CST)
7516 vec.quick_push (val);
7517 else
7518 return NULL_TREE;
7521 return vec.build ();
7523 if (subcode == OBJ_TYPE_REF)
7525 tree val = (*valueize) (OBJ_TYPE_REF_EXPR (rhs));
7526 /* If callee is constant, we can fold away the wrapper. */
7527 if (is_gimple_min_invariant (val))
7528 return val;
7531 if (kind == tcc_reference)
7533 if ((TREE_CODE (rhs) == VIEW_CONVERT_EXPR
7534 || TREE_CODE (rhs) == REALPART_EXPR
7535 || TREE_CODE (rhs) == IMAGPART_EXPR)
7536 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
7538 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
7539 return fold_unary_loc (EXPR_LOCATION (rhs),
7540 TREE_CODE (rhs),
7541 TREE_TYPE (rhs), val);
7543 else if (TREE_CODE (rhs) == BIT_FIELD_REF
7544 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
7546 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
7547 return fold_ternary_loc (EXPR_LOCATION (rhs),
7548 TREE_CODE (rhs),
7549 TREE_TYPE (rhs), val,
7550 TREE_OPERAND (rhs, 1),
7551 TREE_OPERAND (rhs, 2));
7553 else if (TREE_CODE (rhs) == MEM_REF
7554 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
7556 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
7557 if (TREE_CODE (val) == ADDR_EXPR
7558 && is_gimple_min_invariant (val))
7560 tree tem = fold_build2 (MEM_REF, TREE_TYPE (rhs),
7561 unshare_expr (val),
7562 TREE_OPERAND (rhs, 1));
7563 if (tem)
7564 rhs = tem;
7567 return fold_const_aggregate_ref_1 (rhs, valueize);
7569 else if (kind == tcc_declaration)
7570 return get_symbol_constant_value (rhs);
7571 return rhs;
7574 case GIMPLE_UNARY_RHS:
7575 return NULL_TREE;
7577 case GIMPLE_BINARY_RHS:
7578 /* Translate &x + CST into an invariant form suitable for
7579 further propagation. */
7580 if (subcode == POINTER_PLUS_EXPR)
7582 tree op0 = (*valueize) (gimple_assign_rhs1 (stmt));
7583 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
7584 if (TREE_CODE (op0) == ADDR_EXPR
7585 && TREE_CODE (op1) == INTEGER_CST)
7587 tree off = fold_convert (ptr_type_node, op1);
7588 return build1_loc
7589 (loc, ADDR_EXPR, TREE_TYPE (op0),
7590 fold_build2 (MEM_REF,
7591 TREE_TYPE (TREE_TYPE (op0)),
7592 unshare_expr (op0), off));
7595 /* Canonicalize bool != 0 and bool == 0 appearing after
7596 valueization. While gimple_simplify handles this
7597 it can get confused by the ~X == 1 -> X == 0 transform
7598 which we cant reduce to a SSA name or a constant
7599 (and we have no way to tell gimple_simplify to not
7600 consider those transforms in the first place). */
7601 else if (subcode == EQ_EXPR
7602 || subcode == NE_EXPR)
7604 tree lhs = gimple_assign_lhs (stmt);
7605 tree op0 = gimple_assign_rhs1 (stmt);
7606 if (useless_type_conversion_p (TREE_TYPE (lhs),
7607 TREE_TYPE (op0)))
7609 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
7610 op0 = (*valueize) (op0);
7611 if (TREE_CODE (op0) == INTEGER_CST)
7612 std::swap (op0, op1);
7613 if (TREE_CODE (op1) == INTEGER_CST
7614 && ((subcode == NE_EXPR && integer_zerop (op1))
7615 || (subcode == EQ_EXPR && integer_onep (op1))))
7616 return op0;
7619 return NULL_TREE;
7621 case GIMPLE_TERNARY_RHS:
7623 /* Handle ternary operators that can appear in GIMPLE form. */
7624 tree op0 = (*valueize) (gimple_assign_rhs1 (stmt));
7625 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
7626 tree op2 = (*valueize) (gimple_assign_rhs3 (stmt));
7627 return fold_ternary_loc (loc, subcode,
7628 TREE_TYPE (gimple_assign_lhs (stmt)),
7629 op0, op1, op2);
7632 default:
7633 gcc_unreachable ();
7637 case GIMPLE_CALL:
7639 tree fn;
7640 gcall *call_stmt = as_a <gcall *> (stmt);
7642 if (gimple_call_internal_p (stmt))
7644 enum tree_code subcode = ERROR_MARK;
7645 switch (gimple_call_internal_fn (stmt))
7647 case IFN_UBSAN_CHECK_ADD:
7648 subcode = PLUS_EXPR;
7649 break;
7650 case IFN_UBSAN_CHECK_SUB:
7651 subcode = MINUS_EXPR;
7652 break;
7653 case IFN_UBSAN_CHECK_MUL:
7654 subcode = MULT_EXPR;
7655 break;
7656 case IFN_BUILTIN_EXPECT:
7658 tree arg0 = gimple_call_arg (stmt, 0);
7659 tree op0 = (*valueize) (arg0);
7660 if (TREE_CODE (op0) == INTEGER_CST)
7661 return op0;
7662 return NULL_TREE;
7664 default:
7665 return NULL_TREE;
7667 tree arg0 = gimple_call_arg (stmt, 0);
7668 tree arg1 = gimple_call_arg (stmt, 1);
7669 tree op0 = (*valueize) (arg0);
7670 tree op1 = (*valueize) (arg1);
7672 if (TREE_CODE (op0) != INTEGER_CST
7673 || TREE_CODE (op1) != INTEGER_CST)
7675 switch (subcode)
7677 case MULT_EXPR:
7678 /* x * 0 = 0 * x = 0 without overflow. */
7679 if (integer_zerop (op0) || integer_zerop (op1))
7680 return build_zero_cst (TREE_TYPE (arg0));
7681 break;
7682 case MINUS_EXPR:
7683 /* y - y = 0 without overflow. */
7684 if (operand_equal_p (op0, op1, 0))
7685 return build_zero_cst (TREE_TYPE (arg0));
7686 break;
7687 default:
7688 break;
7691 tree res
7692 = fold_binary_loc (loc, subcode, TREE_TYPE (arg0), op0, op1);
7693 if (res
7694 && TREE_CODE (res) == INTEGER_CST
7695 && !TREE_OVERFLOW (res))
7696 return res;
7697 return NULL_TREE;
7700 fn = (*valueize) (gimple_call_fn (stmt));
7701 if (TREE_CODE (fn) == ADDR_EXPR
7702 && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL
7703 && fndecl_built_in_p (TREE_OPERAND (fn, 0))
7704 && gimple_builtin_call_types_compatible_p (stmt,
7705 TREE_OPERAND (fn, 0)))
7707 tree *args = XALLOCAVEC (tree, gimple_call_num_args (stmt));
7708 tree retval;
7709 unsigned i;
7710 for (i = 0; i < gimple_call_num_args (stmt); ++i)
7711 args[i] = (*valueize) (gimple_call_arg (stmt, i));
7712 retval = fold_builtin_call_array (loc,
7713 gimple_call_return_type (call_stmt),
7714 fn, gimple_call_num_args (stmt), args);
7715 if (retval)
7717 /* fold_call_expr wraps the result inside a NOP_EXPR. */
7718 STRIP_NOPS (retval);
7719 retval = fold_convert (gimple_call_return_type (call_stmt),
7720 retval);
7722 return retval;
7724 return NULL_TREE;
7727 default:
7728 return NULL_TREE;
7732 /* Fold STMT to a constant using VALUEIZE to valueize SSA names.
7733 Returns NULL_TREE if folding to a constant is not possible, otherwise
7734 returns a constant according to is_gimple_min_invariant. */
7736 tree
7737 gimple_fold_stmt_to_constant (gimple *stmt, tree (*valueize) (tree))
7739 tree res = gimple_fold_stmt_to_constant_1 (stmt, valueize);
7740 if (res && is_gimple_min_invariant (res))
7741 return res;
7742 return NULL_TREE;
7746 /* The following set of functions are supposed to fold references using
7747 their constant initializers. */
7749 /* See if we can find constructor defining value of BASE.
7750 When we know the consructor with constant offset (such as
7751 base is array[40] and we do know constructor of array), then
7752 BIT_OFFSET is adjusted accordingly.
7754 As a special case, return error_mark_node when constructor
7755 is not explicitly available, but it is known to be zero
7756 such as 'static const int a;'. */
7757 static tree
7758 get_base_constructor (tree base, poly_int64_pod *bit_offset,
7759 tree (*valueize)(tree))
7761 poly_int64 bit_offset2, size, max_size;
7762 bool reverse;
7764 if (TREE_CODE (base) == MEM_REF)
7766 poly_offset_int boff = *bit_offset + mem_ref_offset (base) * BITS_PER_UNIT;
7767 if (!boff.to_shwi (bit_offset))
7768 return NULL_TREE;
7770 if (valueize
7771 && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
7772 base = valueize (TREE_OPERAND (base, 0));
7773 if (!base || TREE_CODE (base) != ADDR_EXPR)
7774 return NULL_TREE;
7775 base = TREE_OPERAND (base, 0);
7777 else if (valueize
7778 && TREE_CODE (base) == SSA_NAME)
7779 base = valueize (base);
7781 /* Get a CONSTRUCTOR. If BASE is a VAR_DECL, get its
7782 DECL_INITIAL. If BASE is a nested reference into another
7783 ARRAY_REF or COMPONENT_REF, make a recursive call to resolve
7784 the inner reference. */
7785 switch (TREE_CODE (base))
7787 case VAR_DECL:
7788 case CONST_DECL:
7790 tree init = ctor_for_folding (base);
7792 /* Our semantic is exact opposite of ctor_for_folding;
7793 NULL means unknown, while error_mark_node is 0. */
7794 if (init == error_mark_node)
7795 return NULL_TREE;
7796 if (!init)
7797 return error_mark_node;
7798 return init;
7801 case VIEW_CONVERT_EXPR:
7802 return get_base_constructor (TREE_OPERAND (base, 0),
7803 bit_offset, valueize);
7805 case ARRAY_REF:
7806 case COMPONENT_REF:
7807 base = get_ref_base_and_extent (base, &bit_offset2, &size, &max_size,
7808 &reverse);
7809 if (!known_size_p (max_size) || maybe_ne (size, max_size))
7810 return NULL_TREE;
7811 *bit_offset += bit_offset2;
7812 return get_base_constructor (base, bit_offset, valueize);
7814 case CONSTRUCTOR:
7815 return base;
7817 default:
7818 if (CONSTANT_CLASS_P (base))
7819 return base;
7821 return NULL_TREE;
7825 /* CTOR is CONSTRUCTOR of an array type. Fold a reference of SIZE bits
7826 to the memory at bit OFFSET. When non-null, TYPE is the expected
7827 type of the reference; otherwise the type of the referenced element
7828 is used instead. When SIZE is zero, attempt to fold a reference to
7829 the entire element which OFFSET refers to. Increment *SUBOFF by
7830 the bit offset of the accessed element. */
7832 static tree
7833 fold_array_ctor_reference (tree type, tree ctor,
7834 unsigned HOST_WIDE_INT offset,
7835 unsigned HOST_WIDE_INT size,
7836 tree from_decl,
7837 unsigned HOST_WIDE_INT *suboff)
7839 offset_int low_bound;
7840 offset_int elt_size;
7841 offset_int access_index;
7842 tree domain_type = NULL_TREE;
7843 HOST_WIDE_INT inner_offset;
7845 /* Compute low bound and elt size. */
7846 if (TREE_CODE (TREE_TYPE (ctor)) == ARRAY_TYPE)
7847 domain_type = TYPE_DOMAIN (TREE_TYPE (ctor));
7848 if (domain_type && TYPE_MIN_VALUE (domain_type))
7850 /* Static constructors for variably sized objects make no sense. */
7851 if (TREE_CODE (TYPE_MIN_VALUE (domain_type)) != INTEGER_CST)
7852 return NULL_TREE;
7853 low_bound = wi::to_offset (TYPE_MIN_VALUE (domain_type));
7855 else
7856 low_bound = 0;
7857 /* Static constructors for variably sized objects make no sense. */
7858 if (TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (ctor)))) != INTEGER_CST)
7859 return NULL_TREE;
7860 elt_size = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (ctor))));
7862 /* When TYPE is non-null, verify that it specifies a constant-sized
7863 access of a multiple of the array element size. Avoid division
7864 by zero below when ELT_SIZE is zero, such as with the result of
7865 an initializer for a zero-length array or an empty struct. */
7866 if (elt_size == 0
7867 || (type
7868 && (!TYPE_SIZE_UNIT (type)
7869 || TREE_CODE (TYPE_SIZE_UNIT (type)) != INTEGER_CST)))
7870 return NULL_TREE;
7872 /* Compute the array index we look for. */
7873 access_index = wi::udiv_trunc (offset_int (offset / BITS_PER_UNIT),
7874 elt_size);
7875 access_index += low_bound;
7877 /* And offset within the access. */
7878 inner_offset = offset % (elt_size.to_uhwi () * BITS_PER_UNIT);
7880 unsigned HOST_WIDE_INT elt_sz = elt_size.to_uhwi ();
7881 if (size > elt_sz * BITS_PER_UNIT)
7883 /* native_encode_expr constraints. */
7884 if (size > MAX_BITSIZE_MODE_ANY_MODE
7885 || size % BITS_PER_UNIT != 0
7886 || inner_offset % BITS_PER_UNIT != 0
7887 || elt_sz > MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT)
7888 return NULL_TREE;
7890 unsigned ctor_idx;
7891 tree val = get_array_ctor_element_at_index (ctor, access_index,
7892 &ctor_idx);
7893 if (!val && ctor_idx >= CONSTRUCTOR_NELTS (ctor))
7894 return build_zero_cst (type);
7896 /* native-encode adjacent ctor elements. */
7897 unsigned char buf[MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT];
7898 unsigned bufoff = 0;
7899 offset_int index = 0;
7900 offset_int max_index = access_index;
7901 constructor_elt *elt = CONSTRUCTOR_ELT (ctor, ctor_idx);
7902 if (!val)
7903 val = build_zero_cst (TREE_TYPE (TREE_TYPE (ctor)));
7904 else if (!CONSTANT_CLASS_P (val))
7905 return NULL_TREE;
7906 if (!elt->index)
7908 else if (TREE_CODE (elt->index) == RANGE_EXPR)
7910 index = wi::to_offset (TREE_OPERAND (elt->index, 0));
7911 max_index = wi::to_offset (TREE_OPERAND (elt->index, 1));
7913 else
7914 index = max_index = wi::to_offset (elt->index);
7915 index = wi::umax (index, access_index);
7918 if (bufoff + elt_sz > sizeof (buf))
7919 elt_sz = sizeof (buf) - bufoff;
7920 int len = native_encode_expr (val, buf + bufoff, elt_sz,
7921 inner_offset / BITS_PER_UNIT);
7922 if (len != (int) elt_sz - inner_offset / BITS_PER_UNIT)
7923 return NULL_TREE;
7924 inner_offset = 0;
7925 bufoff += len;
7927 access_index += 1;
7928 if (wi::cmpu (access_index, index) == 0)
7929 val = elt->value;
7930 else if (wi::cmpu (access_index, max_index) > 0)
7932 ctor_idx++;
7933 if (ctor_idx >= CONSTRUCTOR_NELTS (ctor))
7935 val = build_zero_cst (TREE_TYPE (TREE_TYPE (ctor)));
7936 ++max_index;
7938 else
7940 elt = CONSTRUCTOR_ELT (ctor, ctor_idx);
7941 index = 0;
7942 max_index = access_index;
7943 if (!elt->index)
7945 else if (TREE_CODE (elt->index) == RANGE_EXPR)
7947 index = wi::to_offset (TREE_OPERAND (elt->index, 0));
7948 max_index = wi::to_offset (TREE_OPERAND (elt->index, 1));
7950 else
7951 index = max_index = wi::to_offset (elt->index);
7952 index = wi::umax (index, access_index);
7953 if (wi::cmpu (access_index, index) == 0)
7954 val = elt->value;
7955 else
7956 val = build_zero_cst (TREE_TYPE (TREE_TYPE (ctor)));
7960 while (bufoff < size / BITS_PER_UNIT);
7961 *suboff += size;
7962 return native_interpret_expr (type, buf, size / BITS_PER_UNIT);
7965 if (tree val = get_array_ctor_element_at_index (ctor, access_index))
7967 if (!size && TREE_CODE (val) != CONSTRUCTOR)
7969 /* For the final reference to the entire accessed element
7970 (SIZE is zero), reset INNER_OFFSET, disegard TYPE (which
7971 may be null) in favor of the type of the element, and set
7972 SIZE to the size of the accessed element. */
7973 inner_offset = 0;
7974 type = TREE_TYPE (val);
7975 size = elt_sz * BITS_PER_UNIT;
7977 else if (size && access_index < CONSTRUCTOR_NELTS (ctor) - 1
7978 && TREE_CODE (val) == CONSTRUCTOR
7979 && (elt_sz * BITS_PER_UNIT - inner_offset) < size)
7980 /* If this isn't the last element in the CTOR and a CTOR itself
7981 and it does not cover the whole object we are requesting give up
7982 since we're not set up for combining from multiple CTORs. */
7983 return NULL_TREE;
7985 *suboff += access_index.to_uhwi () * elt_sz * BITS_PER_UNIT;
7986 return fold_ctor_reference (type, val, inner_offset, size, from_decl,
7987 suboff);
7990 /* Memory not explicitly mentioned in constructor is 0 (or
7991 the reference is out of range). */
7992 return type ? build_zero_cst (type) : NULL_TREE;
7995 /* CTOR is CONSTRUCTOR of an aggregate or vector. Fold a reference
7996 of SIZE bits to the memory at bit OFFSET. When non-null, TYPE
7997 is the expected type of the reference; otherwise the type of
7998 the referenced member is used instead. When SIZE is zero,
7999 attempt to fold a reference to the entire member which OFFSET
8000 refers to; in this case. Increment *SUBOFF by the bit offset
8001 of the accessed member. */
8003 static tree
8004 fold_nonarray_ctor_reference (tree type, tree ctor,
8005 unsigned HOST_WIDE_INT offset,
8006 unsigned HOST_WIDE_INT size,
8007 tree from_decl,
8008 unsigned HOST_WIDE_INT *suboff)
8010 unsigned HOST_WIDE_INT cnt;
8011 tree cfield, cval;
8013 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), cnt, cfield,
8014 cval)
8016 tree byte_offset = DECL_FIELD_OFFSET (cfield);
8017 tree field_offset = DECL_FIELD_BIT_OFFSET (cfield);
8018 tree field_size = DECL_SIZE (cfield);
8020 if (!field_size)
8022 /* Determine the size of the flexible array member from
8023 the size of the initializer provided for it. */
8024 field_size = TYPE_SIZE (TREE_TYPE (cval));
8027 /* Variable sized objects in static constructors makes no sense,
8028 but field_size can be NULL for flexible array members. */
8029 gcc_assert (TREE_CODE (field_offset) == INTEGER_CST
8030 && TREE_CODE (byte_offset) == INTEGER_CST
8031 && (field_size != NULL_TREE
8032 ? TREE_CODE (field_size) == INTEGER_CST
8033 : TREE_CODE (TREE_TYPE (cfield)) == ARRAY_TYPE));
8035 /* Compute bit offset of the field. */
8036 offset_int bitoffset
8037 = (wi::to_offset (field_offset)
8038 + (wi::to_offset (byte_offset) << LOG2_BITS_PER_UNIT));
8039 /* Compute bit offset where the field ends. */
8040 offset_int bitoffset_end;
8041 if (field_size != NULL_TREE)
8042 bitoffset_end = bitoffset + wi::to_offset (field_size);
8043 else
8044 bitoffset_end = 0;
8046 /* Compute the bit offset of the end of the desired access.
8047 As a special case, if the size of the desired access is
8048 zero, assume the access is to the entire field (and let
8049 the caller make any necessary adjustments by storing
8050 the actual bounds of the field in FIELDBOUNDS). */
8051 offset_int access_end = offset_int (offset);
8052 if (size)
8053 access_end += size;
8054 else
8055 access_end = bitoffset_end;
8057 /* Is there any overlap between the desired access at
8058 [OFFSET, OFFSET+SIZE) and the offset of the field within
8059 the object at [BITOFFSET, BITOFFSET_END)? */
8060 if (wi::cmps (access_end, bitoffset) > 0
8061 && (field_size == NULL_TREE
8062 || wi::lts_p (offset, bitoffset_end)))
8064 *suboff += bitoffset.to_uhwi ();
8066 if (!size && TREE_CODE (cval) != CONSTRUCTOR)
8068 /* For the final reference to the entire accessed member
8069 (SIZE is zero), reset OFFSET, disegard TYPE (which may
8070 be null) in favor of the type of the member, and set
8071 SIZE to the size of the accessed member. */
8072 offset = bitoffset.to_uhwi ();
8073 type = TREE_TYPE (cval);
8074 size = (bitoffset_end - bitoffset).to_uhwi ();
8077 /* We do have overlap. Now see if the field is large enough
8078 to cover the access. Give up for accesses that extend
8079 beyond the end of the object or that span multiple fields. */
8080 if (wi::cmps (access_end, bitoffset_end) > 0)
8081 return NULL_TREE;
8082 if (offset < bitoffset)
8083 return NULL_TREE;
8085 offset_int inner_offset = offset_int (offset) - bitoffset;
8086 return fold_ctor_reference (type, cval,
8087 inner_offset.to_uhwi (), size,
8088 from_decl, suboff);
8092 if (!type)
8093 return NULL_TREE;
8095 return build_zero_cst (type);
8098 /* CTOR is value initializing memory. Fold a reference of TYPE and
8099 bit size POLY_SIZE to the memory at bit POLY_OFFSET. When POLY_SIZE
8100 is zero, attempt to fold a reference to the entire subobject
8101 which OFFSET refers to. This is used when folding accesses to
8102 string members of aggregates. When non-null, set *SUBOFF to
8103 the bit offset of the accessed subobject. */
8105 tree
8106 fold_ctor_reference (tree type, tree ctor, const poly_uint64 &poly_offset,
8107 const poly_uint64 &poly_size, tree from_decl,
8108 unsigned HOST_WIDE_INT *suboff /* = NULL */)
8110 tree ret;
8112 /* We found the field with exact match. */
8113 if (type
8114 && useless_type_conversion_p (type, TREE_TYPE (ctor))
8115 && known_eq (poly_offset, 0U))
8116 return canonicalize_constructor_val (unshare_expr (ctor), from_decl);
8118 /* The remaining optimizations need a constant size and offset. */
8119 unsigned HOST_WIDE_INT size, offset;
8120 if (!poly_size.is_constant (&size) || !poly_offset.is_constant (&offset))
8121 return NULL_TREE;
8123 /* We are at the end of walk, see if we can view convert the
8124 result. */
8125 if (!AGGREGATE_TYPE_P (TREE_TYPE (ctor)) && !offset
8126 /* VIEW_CONVERT_EXPR is defined only for matching sizes. */
8127 && !compare_tree_int (TYPE_SIZE (type), size)
8128 && !compare_tree_int (TYPE_SIZE (TREE_TYPE (ctor)), size))
8130 ret = canonicalize_constructor_val (unshare_expr (ctor), from_decl);
8131 if (ret)
8133 ret = fold_unary (VIEW_CONVERT_EXPR, type, ret);
8134 if (ret)
8135 STRIP_USELESS_TYPE_CONVERSION (ret);
8137 return ret;
8139 /* For constants and byte-aligned/sized reads try to go through
8140 native_encode/interpret. */
8141 if (CONSTANT_CLASS_P (ctor)
8142 && BITS_PER_UNIT == 8
8143 && offset % BITS_PER_UNIT == 0
8144 && offset / BITS_PER_UNIT <= INT_MAX
8145 && size % BITS_PER_UNIT == 0
8146 && size <= MAX_BITSIZE_MODE_ANY_MODE
8147 && can_native_interpret_type_p (type))
8149 unsigned char buf[MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT];
8150 int len = native_encode_expr (ctor, buf, size / BITS_PER_UNIT,
8151 offset / BITS_PER_UNIT);
8152 if (len > 0)
8153 return native_interpret_expr (type, buf, len);
8155 if (TREE_CODE (ctor) == CONSTRUCTOR)
8157 unsigned HOST_WIDE_INT dummy = 0;
8158 if (!suboff)
8159 suboff = &dummy;
8161 tree ret;
8162 if (TREE_CODE (TREE_TYPE (ctor)) == ARRAY_TYPE
8163 || TREE_CODE (TREE_TYPE (ctor)) == VECTOR_TYPE)
8164 ret = fold_array_ctor_reference (type, ctor, offset, size,
8165 from_decl, suboff);
8166 else
8167 ret = fold_nonarray_ctor_reference (type, ctor, offset, size,
8168 from_decl, suboff);
8170 /* Fall back to native_encode_initializer. Needs to be done
8171 only in the outermost fold_ctor_reference call (because it itself
8172 recurses into CONSTRUCTORs) and doesn't update suboff. */
8173 if (ret == NULL_TREE
8174 && suboff == &dummy
8175 && BITS_PER_UNIT == 8
8176 && offset % BITS_PER_UNIT == 0
8177 && offset / BITS_PER_UNIT <= INT_MAX
8178 && size % BITS_PER_UNIT == 0
8179 && size <= MAX_BITSIZE_MODE_ANY_MODE
8180 && can_native_interpret_type_p (type))
8182 unsigned char buf[MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT];
8183 int len = native_encode_initializer (ctor, buf, size / BITS_PER_UNIT,
8184 offset / BITS_PER_UNIT);
8185 if (len > 0)
8186 return native_interpret_expr (type, buf, len);
8189 return ret;
8192 return NULL_TREE;
8195 /* Return the tree representing the element referenced by T if T is an
8196 ARRAY_REF or COMPONENT_REF into constant aggregates valuezing SSA
8197 names using VALUEIZE. Return NULL_TREE otherwise. */
8199 tree
8200 fold_const_aggregate_ref_1 (tree t, tree (*valueize) (tree))
8202 tree ctor, idx, base;
8203 poly_int64 offset, size, max_size;
8204 tree tem;
8205 bool reverse;
8207 if (TREE_THIS_VOLATILE (t))
8208 return NULL_TREE;
8210 if (DECL_P (t))
8211 return get_symbol_constant_value (t);
8213 tem = fold_read_from_constant_string (t);
8214 if (tem)
8215 return tem;
8217 switch (TREE_CODE (t))
8219 case ARRAY_REF:
8220 case ARRAY_RANGE_REF:
8221 /* Constant indexes are handled well by get_base_constructor.
8222 Only special case variable offsets.
8223 FIXME: This code can't handle nested references with variable indexes
8224 (they will be handled only by iteration of ccp). Perhaps we can bring
8225 get_ref_base_and_extent here and make it use a valueize callback. */
8226 if (TREE_CODE (TREE_OPERAND (t, 1)) == SSA_NAME
8227 && valueize
8228 && (idx = (*valueize) (TREE_OPERAND (t, 1)))
8229 && poly_int_tree_p (idx))
8231 tree low_bound, unit_size;
8233 /* If the resulting bit-offset is constant, track it. */
8234 if ((low_bound = array_ref_low_bound (t),
8235 poly_int_tree_p (low_bound))
8236 && (unit_size = array_ref_element_size (t),
8237 tree_fits_uhwi_p (unit_size)))
8239 poly_offset_int woffset
8240 = wi::sext (wi::to_poly_offset (idx)
8241 - wi::to_poly_offset (low_bound),
8242 TYPE_PRECISION (sizetype));
8243 woffset *= tree_to_uhwi (unit_size);
8244 woffset *= BITS_PER_UNIT;
8245 if (woffset.to_shwi (&offset))
8247 base = TREE_OPERAND (t, 0);
8248 ctor = get_base_constructor (base, &offset, valueize);
8249 /* Empty constructor. Always fold to 0. */
8250 if (ctor == error_mark_node)
8251 return build_zero_cst (TREE_TYPE (t));
8252 /* Out of bound array access. Value is undefined,
8253 but don't fold. */
8254 if (maybe_lt (offset, 0))
8255 return NULL_TREE;
8256 /* We cannot determine ctor. */
8257 if (!ctor)
8258 return NULL_TREE;
8259 return fold_ctor_reference (TREE_TYPE (t), ctor, offset,
8260 tree_to_uhwi (unit_size)
8261 * BITS_PER_UNIT,
8262 base);
8266 /* Fallthru. */
8268 case COMPONENT_REF:
8269 case BIT_FIELD_REF:
8270 case TARGET_MEM_REF:
8271 case MEM_REF:
8272 base = get_ref_base_and_extent (t, &offset, &size, &max_size, &reverse);
8273 ctor = get_base_constructor (base, &offset, valueize);
8275 /* Empty constructor. Always fold to 0. */
8276 if (ctor == error_mark_node)
8277 return build_zero_cst (TREE_TYPE (t));
8278 /* We do not know precise address. */
8279 if (!known_size_p (max_size) || maybe_ne (max_size, size))
8280 return NULL_TREE;
8281 /* We cannot determine ctor. */
8282 if (!ctor)
8283 return NULL_TREE;
8285 /* Out of bound array access. Value is undefined, but don't fold. */
8286 if (maybe_lt (offset, 0))
8287 return NULL_TREE;
8289 tem = fold_ctor_reference (TREE_TYPE (t), ctor, offset, size, base);
8290 if (tem)
8291 return tem;
8293 /* For bit field reads try to read the representative and
8294 adjust. */
8295 if (TREE_CODE (t) == COMPONENT_REF
8296 && DECL_BIT_FIELD (TREE_OPERAND (t, 1))
8297 && DECL_BIT_FIELD_REPRESENTATIVE (TREE_OPERAND (t, 1)))
8299 HOST_WIDE_INT csize, coffset;
8300 tree field = TREE_OPERAND (t, 1);
8301 tree repr = DECL_BIT_FIELD_REPRESENTATIVE (field);
8302 if (INTEGRAL_TYPE_P (TREE_TYPE (repr))
8303 && size.is_constant (&csize)
8304 && offset.is_constant (&coffset)
8305 && (coffset % BITS_PER_UNIT != 0
8306 || csize % BITS_PER_UNIT != 0)
8307 && !reverse
8308 && BYTES_BIG_ENDIAN == WORDS_BIG_ENDIAN)
8310 poly_int64 bitoffset;
8311 poly_uint64 field_offset, repr_offset;
8312 if (poly_int_tree_p (DECL_FIELD_OFFSET (field), &field_offset)
8313 && poly_int_tree_p (DECL_FIELD_OFFSET (repr), &repr_offset))
8314 bitoffset = (field_offset - repr_offset) * BITS_PER_UNIT;
8315 else
8316 bitoffset = 0;
8317 bitoffset += (tree_to_uhwi (DECL_FIELD_BIT_OFFSET (field))
8318 - tree_to_uhwi (DECL_FIELD_BIT_OFFSET (repr)));
8319 HOST_WIDE_INT bitoff;
8320 int diff = (TYPE_PRECISION (TREE_TYPE (repr))
8321 - TYPE_PRECISION (TREE_TYPE (field)));
8322 if (bitoffset.is_constant (&bitoff)
8323 && bitoff >= 0
8324 && bitoff <= diff)
8326 offset -= bitoff;
8327 size = tree_to_uhwi (DECL_SIZE (repr));
8329 tem = fold_ctor_reference (TREE_TYPE (repr), ctor, offset,
8330 size, base);
8331 if (tem && TREE_CODE (tem) == INTEGER_CST)
8333 if (!BYTES_BIG_ENDIAN)
8334 tem = wide_int_to_tree (TREE_TYPE (field),
8335 wi::lrshift (wi::to_wide (tem),
8336 bitoff));
8337 else
8338 tem = wide_int_to_tree (TREE_TYPE (field),
8339 wi::lrshift (wi::to_wide (tem),
8340 diff - bitoff));
8341 return tem;
8346 break;
8348 case REALPART_EXPR:
8349 case IMAGPART_EXPR:
8351 tree c = fold_const_aggregate_ref_1 (TREE_OPERAND (t, 0), valueize);
8352 if (c && TREE_CODE (c) == COMPLEX_CST)
8353 return fold_build1_loc (EXPR_LOCATION (t),
8354 TREE_CODE (t), TREE_TYPE (t), c);
8355 break;
8358 default:
8359 break;
8362 return NULL_TREE;
8365 tree
8366 fold_const_aggregate_ref (tree t)
8368 return fold_const_aggregate_ref_1 (t, NULL);
8371 /* Lookup virtual method with index TOKEN in a virtual table V
8372 at OFFSET.
8373 Set CAN_REFER if non-NULL to false if method
8374 is not referable or if the virtual table is ill-formed (such as rewriten
8375 by non-C++ produced symbol). Otherwise just return NULL in that calse. */
8377 tree
8378 gimple_get_virt_method_for_vtable (HOST_WIDE_INT token,
8379 tree v,
8380 unsigned HOST_WIDE_INT offset,
8381 bool *can_refer)
8383 tree vtable = v, init, fn;
8384 unsigned HOST_WIDE_INT size;
8385 unsigned HOST_WIDE_INT elt_size, access_index;
8386 tree domain_type;
8388 if (can_refer)
8389 *can_refer = true;
8391 /* First of all double check we have virtual table. */
8392 if (!VAR_P (v) || !DECL_VIRTUAL_P (v))
8394 /* Pass down that we lost track of the target. */
8395 if (can_refer)
8396 *can_refer = false;
8397 return NULL_TREE;
8400 init = ctor_for_folding (v);
8402 /* The virtual tables should always be born with constructors
8403 and we always should assume that they are avaialble for
8404 folding. At the moment we do not stream them in all cases,
8405 but it should never happen that ctor seem unreachable. */
8406 gcc_assert (init);
8407 if (init == error_mark_node)
8409 /* Pass down that we lost track of the target. */
8410 if (can_refer)
8411 *can_refer = false;
8412 return NULL_TREE;
8414 gcc_checking_assert (TREE_CODE (TREE_TYPE (v)) == ARRAY_TYPE);
8415 size = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (TREE_TYPE (v))));
8416 offset *= BITS_PER_UNIT;
8417 offset += token * size;
8419 /* Lookup the value in the constructor that is assumed to be array.
8420 This is equivalent to
8421 fn = fold_ctor_reference (TREE_TYPE (TREE_TYPE (v)), init,
8422 offset, size, NULL);
8423 but in a constant time. We expect that frontend produced a simple
8424 array without indexed initializers. */
8426 gcc_checking_assert (TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE);
8427 domain_type = TYPE_DOMAIN (TREE_TYPE (init));
8428 gcc_checking_assert (integer_zerop (TYPE_MIN_VALUE (domain_type)));
8429 elt_size = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (init))));
8431 access_index = offset / BITS_PER_UNIT / elt_size;
8432 gcc_checking_assert (offset % (elt_size * BITS_PER_UNIT) == 0);
8434 /* The C++ FE can now produce indexed fields, and we check if the indexes
8435 match. */
8436 if (access_index < CONSTRUCTOR_NELTS (init))
8438 fn = CONSTRUCTOR_ELT (init, access_index)->value;
8439 tree idx = CONSTRUCTOR_ELT (init, access_index)->index;
8440 gcc_checking_assert (!idx || tree_to_uhwi (idx) == access_index);
8441 STRIP_NOPS (fn);
8443 else
8444 fn = NULL;
8446 /* For type inconsistent program we may end up looking up virtual method
8447 in virtual table that does not contain TOKEN entries. We may overrun
8448 the virtual table and pick up a constant or RTTI info pointer.
8449 In any case the call is undefined. */
8450 if (!fn
8451 || (TREE_CODE (fn) != ADDR_EXPR && TREE_CODE (fn) != FDESC_EXPR)
8452 || TREE_CODE (TREE_OPERAND (fn, 0)) != FUNCTION_DECL)
8453 fn = builtin_decl_unreachable ();
8454 else
8456 fn = TREE_OPERAND (fn, 0);
8458 /* When cgraph node is missing and function is not public, we cannot
8459 devirtualize. This can happen in WHOPR when the actual method
8460 ends up in other partition, because we found devirtualization
8461 possibility too late. */
8462 if (!can_refer_decl_in_current_unit_p (fn, vtable))
8464 if (can_refer)
8466 *can_refer = false;
8467 return fn;
8469 return NULL_TREE;
8473 /* Make sure we create a cgraph node for functions we'll reference.
8474 They can be non-existent if the reference comes from an entry
8475 of an external vtable for example. */
8476 cgraph_node::get_create (fn);
8478 return fn;
8481 /* Return a declaration of a function which an OBJ_TYPE_REF references. TOKEN
8482 is integer form of OBJ_TYPE_REF_TOKEN of the reference expression.
8483 KNOWN_BINFO carries the binfo describing the true type of
8484 OBJ_TYPE_REF_OBJECT(REF).
8485 Set CAN_REFER if non-NULL to false if method
8486 is not referable or if the virtual table is ill-formed (such as rewriten
8487 by non-C++ produced symbol). Otherwise just return NULL in that calse. */
8489 tree
8490 gimple_get_virt_method_for_binfo (HOST_WIDE_INT token, tree known_binfo,
8491 bool *can_refer)
8493 unsigned HOST_WIDE_INT offset;
8494 tree v;
8496 v = BINFO_VTABLE (known_binfo);
8497 /* If there is no virtual methods table, leave the OBJ_TYPE_REF alone. */
8498 if (!v)
8499 return NULL_TREE;
8501 if (!vtable_pointer_value_to_vtable (v, &v, &offset))
8503 if (can_refer)
8504 *can_refer = false;
8505 return NULL_TREE;
8507 return gimple_get_virt_method_for_vtable (token, v, offset, can_refer);
8510 /* Given a pointer value T, return a simplified version of an
8511 indirection through T, or NULL_TREE if no simplification is
8512 possible. Note that the resulting type may be different from
8513 the type pointed to in the sense that it is still compatible
8514 from the langhooks point of view. */
8516 tree
8517 gimple_fold_indirect_ref (tree t)
8519 tree ptype = TREE_TYPE (t), type = TREE_TYPE (ptype);
8520 tree sub = t;
8521 tree subtype;
8523 STRIP_NOPS (sub);
8524 subtype = TREE_TYPE (sub);
8525 if (!POINTER_TYPE_P (subtype)
8526 || TYPE_REF_CAN_ALIAS_ALL (ptype))
8527 return NULL_TREE;
8529 if (TREE_CODE (sub) == ADDR_EXPR)
8531 tree op = TREE_OPERAND (sub, 0);
8532 tree optype = TREE_TYPE (op);
8533 /* *&p => p */
8534 if (useless_type_conversion_p (type, optype))
8535 return op;
8537 /* *(foo *)&fooarray => fooarray[0] */
8538 if (TREE_CODE (optype) == ARRAY_TYPE
8539 && TREE_CODE (TYPE_SIZE (TREE_TYPE (optype))) == INTEGER_CST
8540 && useless_type_conversion_p (type, TREE_TYPE (optype)))
8542 tree type_domain = TYPE_DOMAIN (optype);
8543 tree min_val = size_zero_node;
8544 if (type_domain && TYPE_MIN_VALUE (type_domain))
8545 min_val = TYPE_MIN_VALUE (type_domain);
8546 if (TREE_CODE (min_val) == INTEGER_CST)
8547 return build4 (ARRAY_REF, type, op, min_val, NULL_TREE, NULL_TREE);
8549 /* *(foo *)&complexfoo => __real__ complexfoo */
8550 else if (TREE_CODE (optype) == COMPLEX_TYPE
8551 && useless_type_conversion_p (type, TREE_TYPE (optype)))
8552 return fold_build1 (REALPART_EXPR, type, op);
8553 /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
8554 else if (TREE_CODE (optype) == VECTOR_TYPE
8555 && useless_type_conversion_p (type, TREE_TYPE (optype)))
8557 tree part_width = TYPE_SIZE (type);
8558 tree index = bitsize_int (0);
8559 return fold_build3 (BIT_FIELD_REF, type, op, part_width, index);
8563 /* *(p + CST) -> ... */
8564 if (TREE_CODE (sub) == POINTER_PLUS_EXPR
8565 && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST)
8567 tree addr = TREE_OPERAND (sub, 0);
8568 tree off = TREE_OPERAND (sub, 1);
8569 tree addrtype;
8571 STRIP_NOPS (addr);
8572 addrtype = TREE_TYPE (addr);
8574 /* ((foo*)&vectorfoo)[1] -> BIT_FIELD_REF<vectorfoo,...> */
8575 if (TREE_CODE (addr) == ADDR_EXPR
8576 && TREE_CODE (TREE_TYPE (addrtype)) == VECTOR_TYPE
8577 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (addrtype)))
8578 && tree_fits_uhwi_p (off))
8580 unsigned HOST_WIDE_INT offset = tree_to_uhwi (off);
8581 tree part_width = TYPE_SIZE (type);
8582 unsigned HOST_WIDE_INT part_widthi
8583 = tree_to_shwi (part_width) / BITS_PER_UNIT;
8584 unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT;
8585 tree index = bitsize_int (indexi);
8586 if (known_lt (offset / part_widthi,
8587 TYPE_VECTOR_SUBPARTS (TREE_TYPE (addrtype))))
8588 return fold_build3 (BIT_FIELD_REF, type, TREE_OPERAND (addr, 0),
8589 part_width, index);
8592 /* ((foo*)&complexfoo)[1] -> __imag__ complexfoo */
8593 if (TREE_CODE (addr) == ADDR_EXPR
8594 && TREE_CODE (TREE_TYPE (addrtype)) == COMPLEX_TYPE
8595 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (addrtype))))
8597 tree size = TYPE_SIZE_UNIT (type);
8598 if (tree_int_cst_equal (size, off))
8599 return fold_build1 (IMAGPART_EXPR, type, TREE_OPERAND (addr, 0));
8602 /* *(p + CST) -> MEM_REF <p, CST>. */
8603 if (TREE_CODE (addr) != ADDR_EXPR
8604 || DECL_P (TREE_OPERAND (addr, 0)))
8605 return fold_build2 (MEM_REF, type,
8606 addr,
8607 wide_int_to_tree (ptype, wi::to_wide (off)));
8610 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
8611 if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
8612 && TREE_CODE (TYPE_SIZE (TREE_TYPE (TREE_TYPE (subtype)))) == INTEGER_CST
8613 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (subtype))))
8615 tree type_domain;
8616 tree min_val = size_zero_node;
8617 tree osub = sub;
8618 sub = gimple_fold_indirect_ref (sub);
8619 if (! sub)
8620 sub = build1 (INDIRECT_REF, TREE_TYPE (subtype), osub);
8621 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
8622 if (type_domain && TYPE_MIN_VALUE (type_domain))
8623 min_val = TYPE_MIN_VALUE (type_domain);
8624 if (TREE_CODE (min_val) == INTEGER_CST)
8625 return build4 (ARRAY_REF, type, sub, min_val, NULL_TREE, NULL_TREE);
8628 return NULL_TREE;
8631 /* Return true if CODE is an operation that when operating on signed
8632 integer types involves undefined behavior on overflow and the
8633 operation can be expressed with unsigned arithmetic. */
8635 bool
8636 arith_code_with_undefined_signed_overflow (tree_code code)
8638 switch (code)
8640 case ABS_EXPR:
8641 case PLUS_EXPR:
8642 case MINUS_EXPR:
8643 case MULT_EXPR:
8644 case NEGATE_EXPR:
8645 case POINTER_PLUS_EXPR:
8646 return true;
8647 default:
8648 return false;
8652 /* Rewrite STMT, an assignment with a signed integer or pointer arithmetic
8653 operation that can be transformed to unsigned arithmetic by converting
8654 its operand, carrying out the operation in the corresponding unsigned
8655 type and converting the result back to the original type.
8657 If IN_PLACE is true, adjust the stmt in place and return NULL.
8658 Otherwise returns a sequence of statements that replace STMT and also
8659 contain a modified form of STMT itself. */
8661 gimple_seq
8662 rewrite_to_defined_overflow (gimple *stmt, bool in_place /* = false */)
8664 if (dump_file && (dump_flags & TDF_DETAILS))
8666 fprintf (dump_file, "rewriting stmt with undefined signed "
8667 "overflow ");
8668 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
8671 tree lhs = gimple_assign_lhs (stmt);
8672 tree type = unsigned_type_for (TREE_TYPE (lhs));
8673 gimple_seq stmts = NULL;
8674 if (gimple_assign_rhs_code (stmt) == ABS_EXPR)
8675 gimple_assign_set_rhs_code (stmt, ABSU_EXPR);
8676 else
8677 for (unsigned i = 1; i < gimple_num_ops (stmt); ++i)
8679 tree op = gimple_op (stmt, i);
8680 op = gimple_convert (&stmts, type, op);
8681 gimple_set_op (stmt, i, op);
8683 gimple_assign_set_lhs (stmt, make_ssa_name (type, stmt));
8684 if (gimple_assign_rhs_code (stmt) == POINTER_PLUS_EXPR)
8685 gimple_assign_set_rhs_code (stmt, PLUS_EXPR);
8686 gimple_set_modified (stmt, true);
8687 if (in_place)
8689 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
8690 if (stmts)
8691 gsi_insert_seq_before (&gsi, stmts, GSI_SAME_STMT);
8692 stmts = NULL;
8694 else
8695 gimple_seq_add_stmt (&stmts, stmt);
8696 gimple *cvt = gimple_build_assign (lhs, NOP_EXPR, gimple_assign_lhs (stmt));
8697 if (in_place)
8699 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
8700 gsi_insert_after (&gsi, cvt, GSI_SAME_STMT);
8701 update_stmt (stmt);
8703 else
8704 gimple_seq_add_stmt (&stmts, cvt);
8706 return stmts;
8710 /* The valueization hook we use for the gimple_build API simplification.
8711 This makes us match fold_buildN behavior by only combining with
8712 statements in the sequence(s) we are currently building. */
8714 static tree
8715 gimple_build_valueize (tree op)
8717 if (gimple_bb (SSA_NAME_DEF_STMT (op)) == NULL)
8718 return op;
8719 return NULL_TREE;
8722 /* Helper for gimple_build to perform the final insertion of stmts on SEQ. */
8724 static inline void
8725 gimple_build_insert_seq (gimple_stmt_iterator *gsi,
8726 bool before, gsi_iterator_update update,
8727 gimple_seq seq)
8729 if (before)
8731 if (gsi->bb)
8732 gsi_insert_seq_before (gsi, seq, update);
8733 else
8734 gsi_insert_seq_before_without_update (gsi, seq, update);
8736 else
8738 if (gsi->bb)
8739 gsi_insert_seq_after (gsi, seq, update);
8740 else
8741 gsi_insert_seq_after_without_update (gsi, seq, update);
8745 /* Build the expression CODE OP0 of type TYPE with location LOC,
8746 simplifying it first if possible. Returns the built
8747 expression value and inserts statements possibly defining it
8748 before GSI if BEFORE is true or after GSI if false and advance
8749 the iterator accordingly.
8750 If gsi refers to a basic block simplifying is allowed to look
8751 at all SSA defs while when it does not it is restricted to
8752 SSA defs that are not associated with a basic block yet,
8753 indicating they belong to the currently building sequence. */
8755 tree
8756 gimple_build (gimple_stmt_iterator *gsi,
8757 bool before, gsi_iterator_update update,
8758 location_t loc, enum tree_code code, tree type, tree op0)
8760 gimple_seq seq = NULL;
8761 tree res
8762 = gimple_simplify (code, type, op0, &seq,
8763 gsi->bb ? follow_all_ssa_edges : gimple_build_valueize);
8764 if (!res)
8766 res = create_tmp_reg_or_ssa_name (type);
8767 gimple *stmt;
8768 if (code == REALPART_EXPR
8769 || code == IMAGPART_EXPR
8770 || code == VIEW_CONVERT_EXPR)
8771 stmt = gimple_build_assign (res, code, build1 (code, type, op0));
8772 else
8773 stmt = gimple_build_assign (res, code, op0);
8774 gimple_set_location (stmt, loc);
8775 gimple_seq_add_stmt_without_update (&seq, stmt);
8777 gimple_build_insert_seq (gsi, before, update, seq);
8778 return res;
8781 /* Build the expression OP0 CODE OP1 of type TYPE with location LOC,
8782 simplifying it first if possible. Returns the built
8783 expression value inserting any new statements at GSI honoring BEFORE
8784 and UPDATE. */
8786 tree
8787 gimple_build (gimple_stmt_iterator *gsi,
8788 bool before, gsi_iterator_update update,
8789 location_t loc, enum tree_code code, tree type,
8790 tree op0, tree op1)
8792 gimple_seq seq = NULL;
8793 tree res
8794 = gimple_simplify (code, type, op0, op1, &seq,
8795 gsi->bb ? follow_all_ssa_edges : gimple_build_valueize);
8796 if (!res)
8798 res = create_tmp_reg_or_ssa_name (type);
8799 gimple *stmt = gimple_build_assign (res, code, op0, op1);
8800 gimple_set_location (stmt, loc);
8801 gimple_seq_add_stmt_without_update (&seq, stmt);
8803 gimple_build_insert_seq (gsi, before, update, seq);
8804 return res;
8807 /* Build the expression (CODE OP0 OP1 OP2) of type TYPE with location LOC,
8808 simplifying it first if possible. Returns the built
8809 expression value inserting any new statements at GSI honoring BEFORE
8810 and UPDATE. */
8812 tree
8813 gimple_build (gimple_stmt_iterator *gsi,
8814 bool before, gsi_iterator_update update,
8815 location_t loc, enum tree_code code, tree type,
8816 tree op0, tree op1, tree op2)
8819 gimple_seq seq = NULL;
8820 tree res
8821 = gimple_simplify (code, type, op0, op1, op2, &seq,
8822 gsi->bb ? follow_all_ssa_edges : gimple_build_valueize);
8823 if (!res)
8825 res = create_tmp_reg_or_ssa_name (type);
8826 gimple *stmt;
8827 if (code == BIT_FIELD_REF)
8828 stmt = gimple_build_assign (res, code,
8829 build3 (code, type, op0, op1, op2));
8830 else
8831 stmt = gimple_build_assign (res, code, op0, op1, op2);
8832 gimple_set_location (stmt, loc);
8833 gimple_seq_add_stmt_without_update (&seq, stmt);
8835 gimple_build_insert_seq (gsi, before, update, seq);
8836 return res;
8839 /* Build the call FN () with a result of type TYPE (or no result if TYPE is
8840 void) with a location LOC. Returns the built expression value (or NULL_TREE
8841 if TYPE is void) inserting any new statements at GSI honoring BEFORE
8842 and UPDATE. */
8844 tree
8845 gimple_build (gimple_stmt_iterator *gsi,
8846 bool before, gsi_iterator_update update,
8847 location_t loc, combined_fn fn, tree type)
8849 tree res = NULL_TREE;
8850 gimple_seq seq = NULL;
8851 gcall *stmt;
8852 if (internal_fn_p (fn))
8853 stmt = gimple_build_call_internal (as_internal_fn (fn), 0);
8854 else
8856 tree decl = builtin_decl_implicit (as_builtin_fn (fn));
8857 stmt = gimple_build_call (decl, 0);
8859 if (!VOID_TYPE_P (type))
8861 res = create_tmp_reg_or_ssa_name (type);
8862 gimple_call_set_lhs (stmt, res);
8864 gimple_set_location (stmt, loc);
8865 gimple_seq_add_stmt_without_update (&seq, stmt);
8866 gimple_build_insert_seq (gsi, before, update, seq);
8867 return res;
8870 /* Build the call FN (ARG0) with a result of type TYPE
8871 (or no result if TYPE is void) with location LOC,
8872 simplifying it first if possible. Returns the built
8873 expression value (or NULL_TREE if TYPE is void) inserting any new
8874 statements at GSI honoring BEFORE and UPDATE. */
8876 tree
8877 gimple_build (gimple_stmt_iterator *gsi,
8878 bool before, gsi_iterator_update update,
8879 location_t loc, combined_fn fn,
8880 tree type, tree arg0)
8882 gimple_seq seq = NULL;
8883 tree res = gimple_simplify (fn, type, arg0, &seq, gimple_build_valueize);
8884 if (!res)
8886 gcall *stmt;
8887 if (internal_fn_p (fn))
8888 stmt = gimple_build_call_internal (as_internal_fn (fn), 1, arg0);
8889 else
8891 tree decl = builtin_decl_implicit (as_builtin_fn (fn));
8892 stmt = gimple_build_call (decl, 1, arg0);
8894 if (!VOID_TYPE_P (type))
8896 res = create_tmp_reg_or_ssa_name (type);
8897 gimple_call_set_lhs (stmt, res);
8899 gimple_set_location (stmt, loc);
8900 gimple_seq_add_stmt_without_update (&seq, stmt);
8902 gimple_build_insert_seq (gsi, before, update, seq);
8903 return res;
8906 /* Build the call FN (ARG0, ARG1) with a result of type TYPE
8907 (or no result if TYPE is void) with location LOC,
8908 simplifying it first if possible. Returns the built
8909 expression value (or NULL_TREE if TYPE is void) inserting any new
8910 statements at GSI honoring BEFORE and UPDATE. */
8912 tree
8913 gimple_build (gimple_stmt_iterator *gsi,
8914 bool before, gsi_iterator_update update,
8915 location_t loc, combined_fn fn,
8916 tree type, tree arg0, tree arg1)
8918 gimple_seq seq = NULL;
8919 tree res = gimple_simplify (fn, type, arg0, arg1, &seq,
8920 gimple_build_valueize);
8921 if (!res)
8923 gcall *stmt;
8924 if (internal_fn_p (fn))
8925 stmt = gimple_build_call_internal (as_internal_fn (fn), 2, arg0, arg1);
8926 else
8928 tree decl = builtin_decl_implicit (as_builtin_fn (fn));
8929 stmt = gimple_build_call (decl, 2, arg0, arg1);
8931 if (!VOID_TYPE_P (type))
8933 res = create_tmp_reg_or_ssa_name (type);
8934 gimple_call_set_lhs (stmt, res);
8936 gimple_set_location (stmt, loc);
8937 gimple_seq_add_stmt_without_update (&seq, stmt);
8939 gimple_build_insert_seq (gsi, before, update, seq);
8940 return res;
8943 /* Build the call FN (ARG0, ARG1, ARG2) with a result of type TYPE
8944 (or no result if TYPE is void) with location LOC,
8945 simplifying it first if possible. Returns the built
8946 expression value (or NULL_TREE if TYPE is void) inserting any new
8947 statements at GSI honoring BEFORE and UPDATE. */
8949 tree
8950 gimple_build (gimple_stmt_iterator *gsi,
8951 bool before, gsi_iterator_update update,
8952 location_t loc, combined_fn fn,
8953 tree type, tree arg0, tree arg1, tree arg2)
8955 gimple_seq seq = NULL;
8956 tree res = gimple_simplify (fn, type, arg0, arg1, arg2,
8957 &seq, gimple_build_valueize);
8958 if (!res)
8960 gcall *stmt;
8961 if (internal_fn_p (fn))
8962 stmt = gimple_build_call_internal (as_internal_fn (fn),
8963 3, arg0, arg1, arg2);
8964 else
8966 tree decl = builtin_decl_implicit (as_builtin_fn (fn));
8967 stmt = gimple_build_call (decl, 3, arg0, arg1, arg2);
8969 if (!VOID_TYPE_P (type))
8971 res = create_tmp_reg_or_ssa_name (type);
8972 gimple_call_set_lhs (stmt, res);
8974 gimple_set_location (stmt, loc);
8975 gimple_seq_add_stmt_without_update (&seq, stmt);
8977 gimple_build_insert_seq (gsi, before, update, seq);
8978 return res;
8981 /* Build CODE (OP0) with a result of type TYPE (or no result if TYPE is
8982 void) with location LOC, simplifying it first if possible. Returns the
8983 built expression value (or NULL_TREE if TYPE is void) inserting any new
8984 statements at GSI honoring BEFORE and UPDATE. */
8986 tree
8987 gimple_build (gimple_stmt_iterator *gsi,
8988 bool before, gsi_iterator_update update,
8989 location_t loc, code_helper code, tree type, tree op0)
8991 if (code.is_tree_code ())
8992 return gimple_build (gsi, before, update, loc, tree_code (code), type, op0);
8993 return gimple_build (gsi, before, update, loc, combined_fn (code), type, op0);
8996 /* Build CODE (OP0, OP1) with a result of type TYPE (or no result if TYPE is
8997 void) with location LOC, simplifying it first if possible. Returns the
8998 built expression value (or NULL_TREE if TYPE is void) inserting any new
8999 statements at GSI honoring BEFORE and UPDATE. */
9001 tree
9002 gimple_build (gimple_stmt_iterator *gsi,
9003 bool before, gsi_iterator_update update,
9004 location_t loc, code_helper code, tree type, tree op0, tree op1)
9006 if (code.is_tree_code ())
9007 return gimple_build (gsi, before, update,
9008 loc, tree_code (code), type, op0, op1);
9009 return gimple_build (gsi, before, update,
9010 loc, combined_fn (code), type, op0, op1);
9013 /* Build CODE (OP0, OP1, OP2) with a result of type TYPE (or no result if TYPE
9014 is void) with location LOC, simplifying it first if possible. Returns the
9015 built expression value (or NULL_TREE if TYPE is void) inserting any new
9016 statements at GSI honoring BEFORE and UPDATE. */
9018 tree
9019 gimple_build (gimple_stmt_iterator *gsi,
9020 bool before, gsi_iterator_update update,
9021 location_t loc, code_helper code,
9022 tree type, tree op0, tree op1, tree op2)
9024 if (code.is_tree_code ())
9025 return gimple_build (gsi, before, update,
9026 loc, tree_code (code), type, op0, op1, op2);
9027 return gimple_build (gsi, before, update,
9028 loc, combined_fn (code), type, op0, op1, op2);
9031 /* Build the conversion (TYPE) OP with a result of type TYPE
9032 with location LOC if such conversion is neccesary in GIMPLE,
9033 simplifying it first.
9034 Returns the built expression inserting any new statements
9035 at GSI honoring BEFORE and UPDATE. */
9037 tree
9038 gimple_convert (gimple_stmt_iterator *gsi,
9039 bool before, gsi_iterator_update update,
9040 location_t loc, tree type, tree op)
9042 if (useless_type_conversion_p (type, TREE_TYPE (op)))
9043 return op;
9044 return gimple_build (gsi, before, update, loc, NOP_EXPR, type, op);
9047 /* Build the conversion (ptrofftype) OP with a result of a type
9048 compatible with ptrofftype with location LOC if such conversion
9049 is neccesary in GIMPLE, simplifying it first.
9050 Returns the built expression value inserting any new statements
9051 at GSI honoring BEFORE and UPDATE. */
9053 tree
9054 gimple_convert_to_ptrofftype (gimple_stmt_iterator *gsi,
9055 bool before, gsi_iterator_update update,
9056 location_t loc, tree op)
9058 if (ptrofftype_p (TREE_TYPE (op)))
9059 return op;
9060 return gimple_convert (gsi, before, update, loc, sizetype, op);
9063 /* Build a vector of type TYPE in which each element has the value OP.
9064 Return a gimple value for the result, inserting any new statements
9065 at GSI honoring BEFORE and UPDATE. */
9067 tree
9068 gimple_build_vector_from_val (gimple_stmt_iterator *gsi,
9069 bool before, gsi_iterator_update update,
9070 location_t loc, tree type, tree op)
9072 if (!TYPE_VECTOR_SUBPARTS (type).is_constant ()
9073 && !CONSTANT_CLASS_P (op))
9074 return gimple_build (gsi, before, update,
9075 loc, VEC_DUPLICATE_EXPR, type, op);
9077 tree res, vec = build_vector_from_val (type, op);
9078 if (is_gimple_val (vec))
9079 return vec;
9080 if (gimple_in_ssa_p (cfun))
9081 res = make_ssa_name (type);
9082 else
9083 res = create_tmp_reg (type);
9084 gimple_seq seq = NULL;
9085 gimple *stmt = gimple_build_assign (res, vec);
9086 gimple_set_location (stmt, loc);
9087 gimple_seq_add_stmt_without_update (&seq, stmt);
9088 gimple_build_insert_seq (gsi, before, update, seq);
9089 return res;
9092 /* Build a vector from BUILDER, handling the case in which some elements
9093 are non-constant. Return a gimple value for the result, inserting
9094 any new instructions to GSI honoring BEFORE and UPDATE.
9096 BUILDER must not have a stepped encoding on entry. This is because
9097 the function is not geared up to handle the arithmetic that would
9098 be needed in the variable case, and any code building a vector that
9099 is known to be constant should use BUILDER->build () directly. */
9101 tree
9102 gimple_build_vector (gimple_stmt_iterator *gsi,
9103 bool before, gsi_iterator_update update,
9104 location_t loc, tree_vector_builder *builder)
9106 gcc_assert (builder->nelts_per_pattern () <= 2);
9107 unsigned int encoded_nelts = builder->encoded_nelts ();
9108 for (unsigned int i = 0; i < encoded_nelts; ++i)
9109 if (!CONSTANT_CLASS_P ((*builder)[i]))
9111 gimple_seq seq = NULL;
9112 tree type = builder->type ();
9113 unsigned int nelts = TYPE_VECTOR_SUBPARTS (type).to_constant ();
9114 vec<constructor_elt, va_gc> *v;
9115 vec_alloc (v, nelts);
9116 for (i = 0; i < nelts; ++i)
9117 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, builder->elt (i));
9119 tree res;
9120 if (gimple_in_ssa_p (cfun))
9121 res = make_ssa_name (type);
9122 else
9123 res = create_tmp_reg (type);
9124 gimple *stmt = gimple_build_assign (res, build_constructor (type, v));
9125 gimple_set_location (stmt, loc);
9126 gimple_seq_add_stmt_without_update (&seq, stmt);
9127 gimple_build_insert_seq (gsi, before, update, seq);
9128 return res;
9130 return builder->build ();
9133 /* Emit gimple statements into &stmts that take a value given in OLD_SIZE
9134 and generate a value guaranteed to be rounded upwards to ALIGN.
9136 Return the tree node representing this size, it is of TREE_TYPE TYPE. */
9138 tree
9139 gimple_build_round_up (gimple_stmt_iterator *gsi,
9140 bool before, gsi_iterator_update update,
9141 location_t loc, tree type,
9142 tree old_size, unsigned HOST_WIDE_INT align)
9144 unsigned HOST_WIDE_INT tg_mask = align - 1;
9145 /* tree new_size = (old_size + tg_mask) & ~tg_mask; */
9146 gcc_assert (INTEGRAL_TYPE_P (type));
9147 tree tree_mask = build_int_cst (type, tg_mask);
9148 tree oversize = gimple_build (gsi, before, update,
9149 loc, PLUS_EXPR, type, old_size, tree_mask);
9151 tree mask = build_int_cst (type, -align);
9152 return gimple_build (gsi, before, update,
9153 loc, BIT_AND_EXPR, type, oversize, mask);
9156 /* Return true if the result of assignment STMT is known to be non-negative.
9157 If the return value is based on the assumption that signed overflow is
9158 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
9159 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
9161 static bool
9162 gimple_assign_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
9163 int depth)
9165 enum tree_code code = gimple_assign_rhs_code (stmt);
9166 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
9167 switch (get_gimple_rhs_class (code))
9169 case GIMPLE_UNARY_RHS:
9170 return tree_unary_nonnegative_warnv_p (gimple_assign_rhs_code (stmt),
9171 type,
9172 gimple_assign_rhs1 (stmt),
9173 strict_overflow_p, depth);
9174 case GIMPLE_BINARY_RHS:
9175 return tree_binary_nonnegative_warnv_p (gimple_assign_rhs_code (stmt),
9176 type,
9177 gimple_assign_rhs1 (stmt),
9178 gimple_assign_rhs2 (stmt),
9179 strict_overflow_p, depth);
9180 case GIMPLE_TERNARY_RHS:
9181 return false;
9182 case GIMPLE_SINGLE_RHS:
9183 return tree_single_nonnegative_warnv_p (gimple_assign_rhs1 (stmt),
9184 strict_overflow_p, depth);
9185 case GIMPLE_INVALID_RHS:
9186 break;
9188 gcc_unreachable ();
9191 /* Return true if return value of call STMT is known to be non-negative.
9192 If the return value is based on the assumption that signed overflow is
9193 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
9194 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
9196 static bool
9197 gimple_call_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
9198 int depth)
9200 tree arg0 = gimple_call_num_args (stmt) > 0 ?
9201 gimple_call_arg (stmt, 0) : NULL_TREE;
9202 tree arg1 = gimple_call_num_args (stmt) > 1 ?
9203 gimple_call_arg (stmt, 1) : NULL_TREE;
9204 tree lhs = gimple_call_lhs (stmt);
9205 return (lhs
9206 && tree_call_nonnegative_warnv_p (TREE_TYPE (lhs),
9207 gimple_call_combined_fn (stmt),
9208 arg0, arg1,
9209 strict_overflow_p, depth));
9212 /* Return true if return value of call STMT is known to be non-negative.
9213 If the return value is based on the assumption that signed overflow is
9214 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
9215 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
9217 static bool
9218 gimple_phi_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
9219 int depth)
9221 for (unsigned i = 0; i < gimple_phi_num_args (stmt); ++i)
9223 tree arg = gimple_phi_arg_def (stmt, i);
9224 if (!tree_single_nonnegative_warnv_p (arg, strict_overflow_p, depth + 1))
9225 return false;
9227 return true;
9230 /* Return true if STMT is known to compute a non-negative value.
9231 If the return value is based on the assumption that signed overflow is
9232 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
9233 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
9235 bool
9236 gimple_stmt_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
9237 int depth)
9239 tree type = gimple_range_type (stmt);
9240 if (type && frange::supports_p (type))
9242 frange r;
9243 bool sign;
9244 if (get_global_range_query ()->range_of_stmt (r, stmt)
9245 && r.signbit_p (sign))
9246 return !sign;
9248 switch (gimple_code (stmt))
9250 case GIMPLE_ASSIGN:
9251 return gimple_assign_nonnegative_warnv_p (stmt, strict_overflow_p,
9252 depth);
9253 case GIMPLE_CALL:
9254 return gimple_call_nonnegative_warnv_p (stmt, strict_overflow_p,
9255 depth);
9256 case GIMPLE_PHI:
9257 return gimple_phi_nonnegative_warnv_p (stmt, strict_overflow_p,
9258 depth);
9259 default:
9260 return false;
9264 /* Return true if the floating-point value computed by assignment STMT
9265 is known to have an integer value. We also allow +Inf, -Inf and NaN
9266 to be considered integer values. Return false for signaling NaN.
9268 DEPTH is the current nesting depth of the query. */
9270 static bool
9271 gimple_assign_integer_valued_real_p (gimple *stmt, int depth)
9273 enum tree_code code = gimple_assign_rhs_code (stmt);
9274 switch (get_gimple_rhs_class (code))
9276 case GIMPLE_UNARY_RHS:
9277 return integer_valued_real_unary_p (gimple_assign_rhs_code (stmt),
9278 gimple_assign_rhs1 (stmt), depth);
9279 case GIMPLE_BINARY_RHS:
9280 return integer_valued_real_binary_p (gimple_assign_rhs_code (stmt),
9281 gimple_assign_rhs1 (stmt),
9282 gimple_assign_rhs2 (stmt), depth);
9283 case GIMPLE_TERNARY_RHS:
9284 return false;
9285 case GIMPLE_SINGLE_RHS:
9286 return integer_valued_real_single_p (gimple_assign_rhs1 (stmt), depth);
9287 case GIMPLE_INVALID_RHS:
9288 break;
9290 gcc_unreachable ();
9293 /* Return true if the floating-point value computed by call STMT is known
9294 to have an integer value. We also allow +Inf, -Inf and NaN to be
9295 considered integer values. Return false for signaling NaN.
9297 DEPTH is the current nesting depth of the query. */
9299 static bool
9300 gimple_call_integer_valued_real_p (gimple *stmt, int depth)
9302 tree arg0 = (gimple_call_num_args (stmt) > 0
9303 ? gimple_call_arg (stmt, 0)
9304 : NULL_TREE);
9305 tree arg1 = (gimple_call_num_args (stmt) > 1
9306 ? gimple_call_arg (stmt, 1)
9307 : NULL_TREE);
9308 return integer_valued_real_call_p (gimple_call_combined_fn (stmt),
9309 arg0, arg1, depth);
9312 /* Return true if the floating-point result of phi STMT is known to have
9313 an integer value. We also allow +Inf, -Inf and NaN to be considered
9314 integer values. Return false for signaling NaN.
9316 DEPTH is the current nesting depth of the query. */
9318 static bool
9319 gimple_phi_integer_valued_real_p (gimple *stmt, int depth)
9321 for (unsigned i = 0; i < gimple_phi_num_args (stmt); ++i)
9323 tree arg = gimple_phi_arg_def (stmt, i);
9324 if (!integer_valued_real_single_p (arg, depth + 1))
9325 return false;
9327 return true;
9330 /* Return true if the floating-point value computed by STMT is known
9331 to have an integer value. We also allow +Inf, -Inf and NaN to be
9332 considered integer values. Return false for signaling NaN.
9334 DEPTH is the current nesting depth of the query. */
9336 bool
9337 gimple_stmt_integer_valued_real_p (gimple *stmt, int depth)
9339 switch (gimple_code (stmt))
9341 case GIMPLE_ASSIGN:
9342 return gimple_assign_integer_valued_real_p (stmt, depth);
9343 case GIMPLE_CALL:
9344 return gimple_call_integer_valued_real_p (stmt, depth);
9345 case GIMPLE_PHI:
9346 return gimple_phi_integer_valued_real_p (stmt, depth);
9347 default:
9348 return false;