* es.po: Update.
[official-gcc.git] / gcc / gimple-fold.c
blobf586c0933d5fb5351e6d3e3e3e206e23eaa8057b
1 /* Statement simplification on GIMPLE.
2 Copyright (C) 2010-2016 Free Software Foundation, Inc.
3 Split out from tree-ssa-ccp.c.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 3, or (at your option) any
10 later version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "target.h"
26 #include "rtl.h"
27 #include "tree.h"
28 #include "gimple.h"
29 #include "predict.h"
30 #include "ssa.h"
31 #include "cgraph.h"
32 #include "gimple-pretty-print.h"
33 #include "fold-const.h"
34 #include "stmt.h"
35 #include "expr.h"
36 #include "stor-layout.h"
37 #include "dumpfile.h"
38 #include "gimple-fold.h"
39 #include "gimplify.h"
40 #include "gimple-iterator.h"
41 #include "tree-into-ssa.h"
42 #include "tree-dfa.h"
43 #include "tree-ssa.h"
44 #include "tree-ssa-propagate.h"
45 #include "ipa-utils.h"
46 #include "tree-ssa-address.h"
47 #include "langhooks.h"
48 #include "gimplify-me.h"
49 #include "dbgcnt.h"
50 #include "builtins.h"
51 #include "tree-eh.h"
52 #include "gimple-match.h"
53 #include "gomp-constants.h"
54 #include "optabs-query.h"
55 #include "omp-low.h"
56 #include "ipa-chkp.h"
57 #include "tree-cfg.h"
58 #include "fold-const-call.h"
60 /* Return true when DECL can be referenced from current unit.
61 FROM_DECL (if non-null) specify constructor of variable DECL was taken from.
62 We can get declarations that are not possible to reference for various
63 reasons:
65 1) When analyzing C++ virtual tables.
66 C++ virtual tables do have known constructors even
67 when they are keyed to other compilation unit.
68 Those tables can contain pointers to methods and vars
69 in other units. Those methods have both STATIC and EXTERNAL
70 set.
71 2) In WHOPR mode devirtualization might lead to reference
72 to method that was partitioned elsehwere.
73 In this case we have static VAR_DECL or FUNCTION_DECL
74 that has no corresponding callgraph/varpool node
75 declaring the body.
76 3) COMDAT functions referred by external vtables that
77 we devirtualize only during final compilation stage.
78 At this time we already decided that we will not output
79 the function body and thus we can't reference the symbol
80 directly. */
82 static bool
83 can_refer_decl_in_current_unit_p (tree decl, tree from_decl)
85 varpool_node *vnode;
86 struct cgraph_node *node;
87 symtab_node *snode;
89 if (DECL_ABSTRACT_P (decl))
90 return false;
92 /* We are concerned only about static/external vars and functions. */
93 if ((!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
94 || !VAR_OR_FUNCTION_DECL_P (decl))
95 return true;
97 /* Static objects can be referred only if they was not optimized out yet. */
98 if (!TREE_PUBLIC (decl) && !DECL_EXTERNAL (decl))
100 /* Before we start optimizing unreachable code we can be sure all
101 static objects are defined. */
102 if (symtab->function_flags_ready)
103 return true;
104 snode = symtab_node::get (decl);
105 if (!snode || !snode->definition)
106 return false;
107 node = dyn_cast <cgraph_node *> (snode);
108 return !node || !node->global.inlined_to;
111 /* We will later output the initializer, so we can refer to it.
112 So we are concerned only when DECL comes from initializer of
113 external var or var that has been optimized out. */
114 if (!from_decl
115 || !VAR_P (from_decl)
116 || (!DECL_EXTERNAL (from_decl)
117 && (vnode = varpool_node::get (from_decl)) != NULL
118 && vnode->definition)
119 || (flag_ltrans
120 && (vnode = varpool_node::get (from_decl)) != NULL
121 && vnode->in_other_partition))
122 return true;
123 /* We are folding reference from external vtable. The vtable may reffer
124 to a symbol keyed to other compilation unit. The other compilation
125 unit may be in separate DSO and the symbol may be hidden. */
126 if (DECL_VISIBILITY_SPECIFIED (decl)
127 && DECL_EXTERNAL (decl)
128 && DECL_VISIBILITY (decl) != VISIBILITY_DEFAULT
129 && (!(snode = symtab_node::get (decl)) || !snode->in_other_partition))
130 return false;
131 /* When function is public, we always can introduce new reference.
132 Exception are the COMDAT functions where introducing a direct
133 reference imply need to include function body in the curren tunit. */
134 if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl))
135 return true;
136 /* We have COMDAT. We are going to check if we still have definition
137 or if the definition is going to be output in other partition.
138 Bypass this when gimplifying; all needed functions will be produced.
140 As observed in PR20991 for already optimized out comdat virtual functions
141 it may be tempting to not necessarily give up because the copy will be
142 output elsewhere when corresponding vtable is output.
143 This is however not possible - ABI specify that COMDATs are output in
144 units where they are used and when the other unit was compiled with LTO
145 it is possible that vtable was kept public while the function itself
146 was privatized. */
147 if (!symtab->function_flags_ready)
148 return true;
150 snode = symtab_node::get (decl);
151 if (!snode
152 || ((!snode->definition || DECL_EXTERNAL (decl))
153 && (!snode->in_other_partition
154 || (!snode->forced_by_abi && !snode->force_output))))
155 return false;
156 node = dyn_cast <cgraph_node *> (snode);
157 return !node || !node->global.inlined_to;
160 /* Create a temporary for TYPE for a statement STMT. If the current function
161 is in SSA form, a SSA name is created. Otherwise a temporary register
162 is made. */
164 static tree
165 create_tmp_reg_or_ssa_name (tree type, gimple *stmt = NULL)
167 if (gimple_in_ssa_p (cfun))
168 return make_ssa_name (type, stmt);
169 else
170 return create_tmp_reg (type);
173 /* CVAL is value taken from DECL_INITIAL of variable. Try to transform it into
174 acceptable form for is_gimple_min_invariant.
175 FROM_DECL (if non-NULL) specify variable whose constructor contains CVAL. */
177 tree
178 canonicalize_constructor_val (tree cval, tree from_decl)
180 tree orig_cval = cval;
181 STRIP_NOPS (cval);
182 if (TREE_CODE (cval) == POINTER_PLUS_EXPR
183 && TREE_CODE (TREE_OPERAND (cval, 1)) == INTEGER_CST)
185 tree ptr = TREE_OPERAND (cval, 0);
186 if (is_gimple_min_invariant (ptr))
187 cval = build1_loc (EXPR_LOCATION (cval),
188 ADDR_EXPR, TREE_TYPE (ptr),
189 fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (ptr)),
190 ptr,
191 fold_convert (ptr_type_node,
192 TREE_OPERAND (cval, 1))));
194 if (TREE_CODE (cval) == ADDR_EXPR)
196 tree base = NULL_TREE;
197 if (TREE_CODE (TREE_OPERAND (cval, 0)) == COMPOUND_LITERAL_EXPR)
199 base = COMPOUND_LITERAL_EXPR_DECL (TREE_OPERAND (cval, 0));
200 if (base)
201 TREE_OPERAND (cval, 0) = base;
203 else
204 base = get_base_address (TREE_OPERAND (cval, 0));
205 if (!base)
206 return NULL_TREE;
208 if (VAR_OR_FUNCTION_DECL_P (base)
209 && !can_refer_decl_in_current_unit_p (base, from_decl))
210 return NULL_TREE;
211 if (TREE_TYPE (base) == error_mark_node)
212 return NULL_TREE;
213 if (VAR_P (base))
214 TREE_ADDRESSABLE (base) = 1;
215 else if (TREE_CODE (base) == FUNCTION_DECL)
217 /* Make sure we create a cgraph node for functions we'll reference.
218 They can be non-existent if the reference comes from an entry
219 of an external vtable for example. */
220 cgraph_node::get_create (base);
222 /* Fixup types in global initializers. */
223 if (TREE_TYPE (TREE_TYPE (cval)) != TREE_TYPE (TREE_OPERAND (cval, 0)))
224 cval = build_fold_addr_expr (TREE_OPERAND (cval, 0));
226 if (!useless_type_conversion_p (TREE_TYPE (orig_cval), TREE_TYPE (cval)))
227 cval = fold_convert (TREE_TYPE (orig_cval), cval);
228 return cval;
230 if (TREE_OVERFLOW_P (cval))
231 return drop_tree_overflow (cval);
232 return orig_cval;
235 /* If SYM is a constant variable with known value, return the value.
236 NULL_TREE is returned otherwise. */
238 tree
239 get_symbol_constant_value (tree sym)
241 tree val = ctor_for_folding (sym);
242 if (val != error_mark_node)
244 if (val)
246 val = canonicalize_constructor_val (unshare_expr (val), sym);
247 if (val && is_gimple_min_invariant (val))
248 return val;
249 else
250 return NULL_TREE;
252 /* Variables declared 'const' without an initializer
253 have zero as the initializer if they may not be
254 overridden at link or run time. */
255 if (!val
256 && is_gimple_reg_type (TREE_TYPE (sym)))
257 return build_zero_cst (TREE_TYPE (sym));
260 return NULL_TREE;
265 /* Subroutine of fold_stmt. We perform several simplifications of the
266 memory reference tree EXPR and make sure to re-gimplify them properly
267 after propagation of constant addresses. IS_LHS is true if the
268 reference is supposed to be an lvalue. */
270 static tree
271 maybe_fold_reference (tree expr, bool is_lhs)
273 tree result;
275 if ((TREE_CODE (expr) == VIEW_CONVERT_EXPR
276 || TREE_CODE (expr) == REALPART_EXPR
277 || TREE_CODE (expr) == IMAGPART_EXPR)
278 && CONSTANT_CLASS_P (TREE_OPERAND (expr, 0)))
279 return fold_unary_loc (EXPR_LOCATION (expr),
280 TREE_CODE (expr),
281 TREE_TYPE (expr),
282 TREE_OPERAND (expr, 0));
283 else if (TREE_CODE (expr) == BIT_FIELD_REF
284 && CONSTANT_CLASS_P (TREE_OPERAND (expr, 0)))
285 return fold_ternary_loc (EXPR_LOCATION (expr),
286 TREE_CODE (expr),
287 TREE_TYPE (expr),
288 TREE_OPERAND (expr, 0),
289 TREE_OPERAND (expr, 1),
290 TREE_OPERAND (expr, 2));
292 if (!is_lhs
293 && (result = fold_const_aggregate_ref (expr))
294 && is_gimple_min_invariant (result))
295 return result;
297 return NULL_TREE;
301 /* Attempt to fold an assignment statement pointed-to by SI. Returns a
302 replacement rhs for the statement or NULL_TREE if no simplification
303 could be made. It is assumed that the operands have been previously
304 folded. */
306 static tree
307 fold_gimple_assign (gimple_stmt_iterator *si)
309 gimple *stmt = gsi_stmt (*si);
310 enum tree_code subcode = gimple_assign_rhs_code (stmt);
311 location_t loc = gimple_location (stmt);
313 tree result = NULL_TREE;
315 switch (get_gimple_rhs_class (subcode))
317 case GIMPLE_SINGLE_RHS:
319 tree rhs = gimple_assign_rhs1 (stmt);
321 if (TREE_CLOBBER_P (rhs))
322 return NULL_TREE;
324 if (REFERENCE_CLASS_P (rhs))
325 return maybe_fold_reference (rhs, false);
327 else if (TREE_CODE (rhs) == OBJ_TYPE_REF)
329 tree val = OBJ_TYPE_REF_EXPR (rhs);
330 if (is_gimple_min_invariant (val))
331 return val;
332 else if (flag_devirtualize && virtual_method_call_p (rhs))
334 bool final;
335 vec <cgraph_node *>targets
336 = possible_polymorphic_call_targets (rhs, stmt, &final);
337 if (final && targets.length () <= 1 && dbg_cnt (devirt))
339 if (dump_enabled_p ())
341 location_t loc = gimple_location_safe (stmt);
342 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, loc,
343 "resolving virtual function address "
344 "reference to function %s\n",
345 targets.length () == 1
346 ? targets[0]->name ()
347 : "NULL");
349 if (targets.length () == 1)
351 val = fold_convert (TREE_TYPE (val),
352 build_fold_addr_expr_loc
353 (loc, targets[0]->decl));
354 STRIP_USELESS_TYPE_CONVERSION (val);
356 else
357 /* We can not use __builtin_unreachable here because it
358 can not have address taken. */
359 val = build_int_cst (TREE_TYPE (val), 0);
360 return val;
365 else if (TREE_CODE (rhs) == ADDR_EXPR)
367 tree ref = TREE_OPERAND (rhs, 0);
368 tree tem = maybe_fold_reference (ref, true);
369 if (tem
370 && TREE_CODE (tem) == MEM_REF
371 && integer_zerop (TREE_OPERAND (tem, 1)))
372 result = fold_convert (TREE_TYPE (rhs), TREE_OPERAND (tem, 0));
373 else if (tem)
374 result = fold_convert (TREE_TYPE (rhs),
375 build_fold_addr_expr_loc (loc, tem));
376 else if (TREE_CODE (ref) == MEM_REF
377 && integer_zerop (TREE_OPERAND (ref, 1)))
378 result = fold_convert (TREE_TYPE (rhs), TREE_OPERAND (ref, 0));
380 if (result)
382 /* Strip away useless type conversions. Both the
383 NON_LVALUE_EXPR that may have been added by fold, and
384 "useless" type conversions that might now be apparent
385 due to propagation. */
386 STRIP_USELESS_TYPE_CONVERSION (result);
388 if (result != rhs && valid_gimple_rhs_p (result))
389 return result;
393 else if (TREE_CODE (rhs) == CONSTRUCTOR
394 && TREE_CODE (TREE_TYPE (rhs)) == VECTOR_TYPE)
396 /* Fold a constant vector CONSTRUCTOR to VECTOR_CST. */
397 unsigned i;
398 tree val;
400 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), i, val)
401 if (! CONSTANT_CLASS_P (val))
402 return NULL_TREE;
404 return build_vector_from_ctor (TREE_TYPE (rhs),
405 CONSTRUCTOR_ELTS (rhs));
408 else if (DECL_P (rhs))
409 return get_symbol_constant_value (rhs);
411 break;
413 case GIMPLE_UNARY_RHS:
414 break;
416 case GIMPLE_BINARY_RHS:
417 break;
419 case GIMPLE_TERNARY_RHS:
420 result = fold_ternary_loc (loc, subcode,
421 TREE_TYPE (gimple_assign_lhs (stmt)),
422 gimple_assign_rhs1 (stmt),
423 gimple_assign_rhs2 (stmt),
424 gimple_assign_rhs3 (stmt));
426 if (result)
428 STRIP_USELESS_TYPE_CONVERSION (result);
429 if (valid_gimple_rhs_p (result))
430 return result;
432 break;
434 case GIMPLE_INVALID_RHS:
435 gcc_unreachable ();
438 return NULL_TREE;
442 /* Replace a statement at *SI_P with a sequence of statements in STMTS,
443 adjusting the replacement stmts location and virtual operands.
444 If the statement has a lhs the last stmt in the sequence is expected
445 to assign to that lhs. */
447 static void
448 gsi_replace_with_seq_vops (gimple_stmt_iterator *si_p, gimple_seq stmts)
450 gimple *stmt = gsi_stmt (*si_p);
452 if (gimple_has_location (stmt))
453 annotate_all_with_location (stmts, gimple_location (stmt));
455 /* First iterate over the replacement statements backward, assigning
456 virtual operands to their defining statements. */
457 gimple *laststore = NULL;
458 for (gimple_stmt_iterator i = gsi_last (stmts);
459 !gsi_end_p (i); gsi_prev (&i))
461 gimple *new_stmt = gsi_stmt (i);
462 if ((gimple_assign_single_p (new_stmt)
463 && !is_gimple_reg (gimple_assign_lhs (new_stmt)))
464 || (is_gimple_call (new_stmt)
465 && (gimple_call_flags (new_stmt)
466 & (ECF_NOVOPS | ECF_PURE | ECF_CONST | ECF_NORETURN)) == 0))
468 tree vdef;
469 if (!laststore)
470 vdef = gimple_vdef (stmt);
471 else
472 vdef = make_ssa_name (gimple_vop (cfun), new_stmt);
473 gimple_set_vdef (new_stmt, vdef);
474 if (vdef && TREE_CODE (vdef) == SSA_NAME)
475 SSA_NAME_DEF_STMT (vdef) = new_stmt;
476 laststore = new_stmt;
480 /* Second iterate over the statements forward, assigning virtual
481 operands to their uses. */
482 tree reaching_vuse = gimple_vuse (stmt);
483 for (gimple_stmt_iterator i = gsi_start (stmts);
484 !gsi_end_p (i); gsi_next (&i))
486 gimple *new_stmt = gsi_stmt (i);
487 /* If the new statement possibly has a VUSE, update it with exact SSA
488 name we know will reach this one. */
489 if (gimple_has_mem_ops (new_stmt))
490 gimple_set_vuse (new_stmt, reaching_vuse);
491 gimple_set_modified (new_stmt, true);
492 if (gimple_vdef (new_stmt))
493 reaching_vuse = gimple_vdef (new_stmt);
496 /* If the new sequence does not do a store release the virtual
497 definition of the original statement. */
498 if (reaching_vuse
499 && reaching_vuse == gimple_vuse (stmt))
501 tree vdef = gimple_vdef (stmt);
502 if (vdef
503 && TREE_CODE (vdef) == SSA_NAME)
505 unlink_stmt_vdef (stmt);
506 release_ssa_name (vdef);
510 /* Finally replace the original statement with the sequence. */
511 gsi_replace_with_seq (si_p, stmts, false);
514 /* Convert EXPR into a GIMPLE value suitable for substitution on the
515 RHS of an assignment. Insert the necessary statements before
516 iterator *SI_P. The statement at *SI_P, which must be a GIMPLE_CALL
517 is replaced. If the call is expected to produces a result, then it
518 is replaced by an assignment of the new RHS to the result variable.
519 If the result is to be ignored, then the call is replaced by a
520 GIMPLE_NOP. A proper VDEF chain is retained by making the first
521 VUSE and the last VDEF of the whole sequence be the same as the replaced
522 statement and using new SSA names for stores in between. */
524 void
525 gimplify_and_update_call_from_tree (gimple_stmt_iterator *si_p, tree expr)
527 tree lhs;
528 gimple *stmt, *new_stmt;
529 gimple_stmt_iterator i;
530 gimple_seq stmts = NULL;
532 stmt = gsi_stmt (*si_p);
534 gcc_assert (is_gimple_call (stmt));
536 push_gimplify_context (gimple_in_ssa_p (cfun));
538 lhs = gimple_call_lhs (stmt);
539 if (lhs == NULL_TREE)
541 gimplify_and_add (expr, &stmts);
542 /* We can end up with folding a memcpy of an empty class assignment
543 which gets optimized away by C++ gimplification. */
544 if (gimple_seq_empty_p (stmts))
546 pop_gimplify_context (NULL);
547 if (gimple_in_ssa_p (cfun))
549 unlink_stmt_vdef (stmt);
550 release_defs (stmt);
552 gsi_replace (si_p, gimple_build_nop (), false);
553 return;
556 else
558 tree tmp = force_gimple_operand (expr, &stmts, false, NULL_TREE);
559 new_stmt = gimple_build_assign (lhs, tmp);
560 i = gsi_last (stmts);
561 gsi_insert_after_without_update (&i, new_stmt,
562 GSI_CONTINUE_LINKING);
565 pop_gimplify_context (NULL);
567 gsi_replace_with_seq_vops (si_p, stmts);
571 /* Replace the call at *GSI with the gimple value VAL. */
573 static void
574 replace_call_with_value (gimple_stmt_iterator *gsi, tree val)
576 gimple *stmt = gsi_stmt (*gsi);
577 tree lhs = gimple_call_lhs (stmt);
578 gimple *repl;
579 if (lhs)
581 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (val)))
582 val = fold_convert (TREE_TYPE (lhs), val);
583 repl = gimple_build_assign (lhs, val);
585 else
586 repl = gimple_build_nop ();
587 tree vdef = gimple_vdef (stmt);
588 if (vdef && TREE_CODE (vdef) == SSA_NAME)
590 unlink_stmt_vdef (stmt);
591 release_ssa_name (vdef);
593 gsi_replace (gsi, repl, false);
596 /* Replace the call at *GSI with the new call REPL and fold that
597 again. */
599 static void
600 replace_call_with_call_and_fold (gimple_stmt_iterator *gsi, gimple *repl)
602 gimple *stmt = gsi_stmt (*gsi);
603 gimple_call_set_lhs (repl, gimple_call_lhs (stmt));
604 gimple_set_location (repl, gimple_location (stmt));
605 if (gimple_vdef (stmt)
606 && TREE_CODE (gimple_vdef (stmt)) == SSA_NAME)
608 gimple_set_vdef (repl, gimple_vdef (stmt));
609 gimple_set_vuse (repl, gimple_vuse (stmt));
610 SSA_NAME_DEF_STMT (gimple_vdef (repl)) = repl;
612 gsi_replace (gsi, repl, false);
613 fold_stmt (gsi);
616 /* Return true if VAR is a VAR_DECL or a component thereof. */
618 static bool
619 var_decl_component_p (tree var)
621 tree inner = var;
622 while (handled_component_p (inner))
623 inner = TREE_OPERAND (inner, 0);
624 return SSA_VAR_P (inner);
627 /* Fold function call to builtin mem{{,p}cpy,move}. Return
628 false if no simplification can be made.
629 If ENDP is 0, return DEST (like memcpy).
630 If ENDP is 1, return DEST+LEN (like mempcpy).
631 If ENDP is 2, return DEST+LEN-1 (like stpcpy).
632 If ENDP is 3, return DEST, additionally *SRC and *DEST may overlap
633 (memmove). */
635 static bool
636 gimple_fold_builtin_memory_op (gimple_stmt_iterator *gsi,
637 tree dest, tree src, int endp)
639 gimple *stmt = gsi_stmt (*gsi);
640 tree lhs = gimple_call_lhs (stmt);
641 tree len = gimple_call_arg (stmt, 2);
642 tree destvar, srcvar;
643 location_t loc = gimple_location (stmt);
645 /* If the LEN parameter is zero, return DEST. */
646 if (integer_zerop (len))
648 gimple *repl;
649 if (gimple_call_lhs (stmt))
650 repl = gimple_build_assign (gimple_call_lhs (stmt), dest);
651 else
652 repl = gimple_build_nop ();
653 tree vdef = gimple_vdef (stmt);
654 if (vdef && TREE_CODE (vdef) == SSA_NAME)
656 unlink_stmt_vdef (stmt);
657 release_ssa_name (vdef);
659 gsi_replace (gsi, repl, false);
660 return true;
663 /* If SRC and DEST are the same (and not volatile), return
664 DEST{,+LEN,+LEN-1}. */
665 if (operand_equal_p (src, dest, 0))
667 unlink_stmt_vdef (stmt);
668 if (gimple_vdef (stmt) && TREE_CODE (gimple_vdef (stmt)) == SSA_NAME)
669 release_ssa_name (gimple_vdef (stmt));
670 if (!lhs)
672 gsi_replace (gsi, gimple_build_nop (), false);
673 return true;
675 goto done;
677 else
679 tree srctype, desttype;
680 unsigned int src_align, dest_align;
681 tree off0;
683 /* Inlining of memcpy/memmove may cause bounds lost (if we copy
684 pointers as wide integer) and also may result in huge function
685 size because of inlined bounds copy. Thus don't inline for
686 functions we want to instrument. */
687 if (flag_check_pointer_bounds
688 && chkp_instrumentable_p (cfun->decl)
689 /* Even if data may contain pointers we can inline if copy
690 less than a pointer size. */
691 && (!tree_fits_uhwi_p (len)
692 || compare_tree_int (len, POINTER_SIZE_UNITS) >= 0))
693 return false;
695 /* Build accesses at offset zero with a ref-all character type. */
696 off0 = build_int_cst (build_pointer_type_for_mode (char_type_node,
697 ptr_mode, true), 0);
699 /* If we can perform the copy efficiently with first doing all loads
700 and then all stores inline it that way. Currently efficiently
701 means that we can load all the memory into a single integer
702 register which is what MOVE_MAX gives us. */
703 src_align = get_pointer_alignment (src);
704 dest_align = get_pointer_alignment (dest);
705 if (tree_fits_uhwi_p (len)
706 && compare_tree_int (len, MOVE_MAX) <= 0
707 /* ??? Don't transform copies from strings with known length this
708 confuses the tree-ssa-strlen.c. This doesn't handle
709 the case in gcc.dg/strlenopt-8.c which is XFAILed for that
710 reason. */
711 && !c_strlen (src, 2))
713 unsigned ilen = tree_to_uhwi (len);
714 if (pow2p_hwi (ilen))
716 tree type = lang_hooks.types.type_for_size (ilen * 8, 1);
717 if (type
718 && TYPE_MODE (type) != BLKmode
719 && (GET_MODE_SIZE (TYPE_MODE (type)) * BITS_PER_UNIT
720 == ilen * 8)
721 /* If the destination pointer is not aligned we must be able
722 to emit an unaligned store. */
723 && (dest_align >= GET_MODE_ALIGNMENT (TYPE_MODE (type))
724 || !SLOW_UNALIGNED_ACCESS (TYPE_MODE (type), dest_align)
725 || (optab_handler (movmisalign_optab, TYPE_MODE (type))
726 != CODE_FOR_nothing)))
728 tree srctype = type;
729 tree desttype = type;
730 if (src_align < GET_MODE_ALIGNMENT (TYPE_MODE (type)))
731 srctype = build_aligned_type (type, src_align);
732 tree srcmem = fold_build2 (MEM_REF, srctype, src, off0);
733 tree tem = fold_const_aggregate_ref (srcmem);
734 if (tem)
735 srcmem = tem;
736 else if (src_align < GET_MODE_ALIGNMENT (TYPE_MODE (type))
737 && SLOW_UNALIGNED_ACCESS (TYPE_MODE (type),
738 src_align)
739 && (optab_handler (movmisalign_optab,
740 TYPE_MODE (type))
741 == CODE_FOR_nothing))
742 srcmem = NULL_TREE;
743 if (srcmem)
745 gimple *new_stmt;
746 if (is_gimple_reg_type (TREE_TYPE (srcmem)))
748 new_stmt = gimple_build_assign (NULL_TREE, srcmem);
749 srcmem
750 = create_tmp_reg_or_ssa_name (TREE_TYPE (srcmem),
751 new_stmt);
752 gimple_assign_set_lhs (new_stmt, srcmem);
753 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
754 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
756 if (dest_align < GET_MODE_ALIGNMENT (TYPE_MODE (type)))
757 desttype = build_aligned_type (type, dest_align);
758 new_stmt
759 = gimple_build_assign (fold_build2 (MEM_REF, desttype,
760 dest, off0),
761 srcmem);
762 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
763 gimple_set_vdef (new_stmt, gimple_vdef (stmt));
764 if (gimple_vdef (new_stmt)
765 && TREE_CODE (gimple_vdef (new_stmt)) == SSA_NAME)
766 SSA_NAME_DEF_STMT (gimple_vdef (new_stmt)) = new_stmt;
767 if (!lhs)
769 gsi_replace (gsi, new_stmt, false);
770 return true;
772 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
773 goto done;
779 if (endp == 3)
781 /* Both DEST and SRC must be pointer types.
782 ??? This is what old code did. Is the testing for pointer types
783 really mandatory?
785 If either SRC is readonly or length is 1, we can use memcpy. */
786 if (!dest_align || !src_align)
787 return false;
788 if (readonly_data_expr (src)
789 || (tree_fits_uhwi_p (len)
790 && (MIN (src_align, dest_align) / BITS_PER_UNIT
791 >= tree_to_uhwi (len))))
793 tree fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
794 if (!fn)
795 return false;
796 gimple_call_set_fndecl (stmt, fn);
797 gimple_call_set_arg (stmt, 0, dest);
798 gimple_call_set_arg (stmt, 1, src);
799 fold_stmt (gsi);
800 return true;
803 /* If *src and *dest can't overlap, optimize into memcpy as well. */
804 if (TREE_CODE (src) == ADDR_EXPR
805 && TREE_CODE (dest) == ADDR_EXPR)
807 tree src_base, dest_base, fn;
808 HOST_WIDE_INT src_offset = 0, dest_offset = 0;
809 HOST_WIDE_INT maxsize;
811 srcvar = TREE_OPERAND (src, 0);
812 src_base = get_addr_base_and_unit_offset (srcvar, &src_offset);
813 if (src_base == NULL)
814 src_base = srcvar;
815 destvar = TREE_OPERAND (dest, 0);
816 dest_base = get_addr_base_and_unit_offset (destvar,
817 &dest_offset);
818 if (dest_base == NULL)
819 dest_base = destvar;
820 if (tree_fits_uhwi_p (len))
821 maxsize = tree_to_uhwi (len);
822 else
823 maxsize = -1;
824 if (SSA_VAR_P (src_base)
825 && SSA_VAR_P (dest_base))
827 if (operand_equal_p (src_base, dest_base, 0)
828 && ranges_overlap_p (src_offset, maxsize,
829 dest_offset, maxsize))
830 return false;
832 else if (TREE_CODE (src_base) == MEM_REF
833 && TREE_CODE (dest_base) == MEM_REF)
835 if (! operand_equal_p (TREE_OPERAND (src_base, 0),
836 TREE_OPERAND (dest_base, 0), 0))
837 return false;
838 offset_int off = mem_ref_offset (src_base) + src_offset;
839 if (!wi::fits_shwi_p (off))
840 return false;
841 src_offset = off.to_shwi ();
843 off = mem_ref_offset (dest_base) + dest_offset;
844 if (!wi::fits_shwi_p (off))
845 return false;
846 dest_offset = off.to_shwi ();
847 if (ranges_overlap_p (src_offset, maxsize,
848 dest_offset, maxsize))
849 return false;
851 else
852 return false;
854 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
855 if (!fn)
856 return false;
857 gimple_call_set_fndecl (stmt, fn);
858 gimple_call_set_arg (stmt, 0, dest);
859 gimple_call_set_arg (stmt, 1, src);
860 fold_stmt (gsi);
861 return true;
864 /* If the destination and source do not alias optimize into
865 memcpy as well. */
866 if ((is_gimple_min_invariant (dest)
867 || TREE_CODE (dest) == SSA_NAME)
868 && (is_gimple_min_invariant (src)
869 || TREE_CODE (src) == SSA_NAME))
871 ao_ref destr, srcr;
872 ao_ref_init_from_ptr_and_size (&destr, dest, len);
873 ao_ref_init_from_ptr_and_size (&srcr, src, len);
874 if (!refs_may_alias_p_1 (&destr, &srcr, false))
876 tree fn;
877 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
878 if (!fn)
879 return false;
880 gimple_call_set_fndecl (stmt, fn);
881 gimple_call_set_arg (stmt, 0, dest);
882 gimple_call_set_arg (stmt, 1, src);
883 fold_stmt (gsi);
884 return true;
888 return false;
891 if (!tree_fits_shwi_p (len))
892 return false;
893 /* FIXME:
894 This logic lose for arguments like (type *)malloc (sizeof (type)),
895 since we strip the casts of up to VOID return value from malloc.
896 Perhaps we ought to inherit type from non-VOID argument here? */
897 STRIP_NOPS (src);
898 STRIP_NOPS (dest);
899 if (!POINTER_TYPE_P (TREE_TYPE (src))
900 || !POINTER_TYPE_P (TREE_TYPE (dest)))
901 return false;
902 /* In the following try to find a type that is most natural to be
903 used for the memcpy source and destination and that allows
904 the most optimization when memcpy is turned into a plain assignment
905 using that type. In theory we could always use a char[len] type
906 but that only gains us that the destination and source possibly
907 no longer will have their address taken. */
908 /* As we fold (void *)(p + CST) to (void *)p + CST undo this here. */
909 if (TREE_CODE (src) == POINTER_PLUS_EXPR)
911 tree tem = TREE_OPERAND (src, 0);
912 STRIP_NOPS (tem);
913 if (tem != TREE_OPERAND (src, 0))
914 src = build1 (NOP_EXPR, TREE_TYPE (tem), src);
916 if (TREE_CODE (dest) == POINTER_PLUS_EXPR)
918 tree tem = TREE_OPERAND (dest, 0);
919 STRIP_NOPS (tem);
920 if (tem != TREE_OPERAND (dest, 0))
921 dest = build1 (NOP_EXPR, TREE_TYPE (tem), dest);
923 srctype = TREE_TYPE (TREE_TYPE (src));
924 if (TREE_CODE (srctype) == ARRAY_TYPE
925 && !tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
927 srctype = TREE_TYPE (srctype);
928 STRIP_NOPS (src);
929 src = build1 (NOP_EXPR, build_pointer_type (srctype), src);
931 desttype = TREE_TYPE (TREE_TYPE (dest));
932 if (TREE_CODE (desttype) == ARRAY_TYPE
933 && !tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
935 desttype = TREE_TYPE (desttype);
936 STRIP_NOPS (dest);
937 dest = build1 (NOP_EXPR, build_pointer_type (desttype), dest);
939 if (TREE_ADDRESSABLE (srctype)
940 || TREE_ADDRESSABLE (desttype))
941 return false;
943 /* Make sure we are not copying using a floating-point mode or
944 a type whose size possibly does not match its precision. */
945 if (FLOAT_MODE_P (TYPE_MODE (desttype))
946 || TREE_CODE (desttype) == BOOLEAN_TYPE
947 || TREE_CODE (desttype) == ENUMERAL_TYPE)
948 desttype = bitwise_type_for_mode (TYPE_MODE (desttype));
949 if (FLOAT_MODE_P (TYPE_MODE (srctype))
950 || TREE_CODE (srctype) == BOOLEAN_TYPE
951 || TREE_CODE (srctype) == ENUMERAL_TYPE)
952 srctype = bitwise_type_for_mode (TYPE_MODE (srctype));
953 if (!srctype)
954 srctype = desttype;
955 if (!desttype)
956 desttype = srctype;
957 if (!srctype)
958 return false;
960 src_align = get_pointer_alignment (src);
961 dest_align = get_pointer_alignment (dest);
962 if (dest_align < TYPE_ALIGN (desttype)
963 || src_align < TYPE_ALIGN (srctype))
964 return false;
966 destvar = dest;
967 STRIP_NOPS (destvar);
968 if (TREE_CODE (destvar) == ADDR_EXPR
969 && var_decl_component_p (TREE_OPERAND (destvar, 0))
970 && tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
971 destvar = fold_build2 (MEM_REF, desttype, destvar, off0);
972 else
973 destvar = NULL_TREE;
975 srcvar = src;
976 STRIP_NOPS (srcvar);
977 if (TREE_CODE (srcvar) == ADDR_EXPR
978 && var_decl_component_p (TREE_OPERAND (srcvar, 0))
979 && tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
981 if (!destvar
982 || src_align >= TYPE_ALIGN (desttype))
983 srcvar = fold_build2 (MEM_REF, destvar ? desttype : srctype,
984 srcvar, off0);
985 else if (!STRICT_ALIGNMENT)
987 srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
988 src_align);
989 srcvar = fold_build2 (MEM_REF, srctype, srcvar, off0);
991 else
992 srcvar = NULL_TREE;
994 else
995 srcvar = NULL_TREE;
997 if (srcvar == NULL_TREE && destvar == NULL_TREE)
998 return false;
1000 if (srcvar == NULL_TREE)
1002 STRIP_NOPS (src);
1003 if (src_align >= TYPE_ALIGN (desttype))
1004 srcvar = fold_build2 (MEM_REF, desttype, src, off0);
1005 else
1007 if (STRICT_ALIGNMENT)
1008 return false;
1009 srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
1010 src_align);
1011 srcvar = fold_build2 (MEM_REF, srctype, src, off0);
1014 else if (destvar == NULL_TREE)
1016 STRIP_NOPS (dest);
1017 if (dest_align >= TYPE_ALIGN (srctype))
1018 destvar = fold_build2 (MEM_REF, srctype, dest, off0);
1019 else
1021 if (STRICT_ALIGNMENT)
1022 return false;
1023 desttype = build_aligned_type (TYPE_MAIN_VARIANT (srctype),
1024 dest_align);
1025 destvar = fold_build2 (MEM_REF, desttype, dest, off0);
1029 gimple *new_stmt;
1030 if (is_gimple_reg_type (TREE_TYPE (srcvar)))
1032 tree tem = fold_const_aggregate_ref (srcvar);
1033 if (tem)
1034 srcvar = tem;
1035 if (! is_gimple_min_invariant (srcvar))
1037 new_stmt = gimple_build_assign (NULL_TREE, srcvar);
1038 srcvar = create_tmp_reg_or_ssa_name (TREE_TYPE (srcvar),
1039 new_stmt);
1040 gimple_assign_set_lhs (new_stmt, srcvar);
1041 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
1042 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1045 new_stmt = gimple_build_assign (destvar, srcvar);
1046 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
1047 gimple_set_vdef (new_stmt, gimple_vdef (stmt));
1048 if (gimple_vdef (new_stmt)
1049 && TREE_CODE (gimple_vdef (new_stmt)) == SSA_NAME)
1050 SSA_NAME_DEF_STMT (gimple_vdef (new_stmt)) = new_stmt;
1051 if (!lhs)
1053 gsi_replace (gsi, new_stmt, false);
1054 return true;
1056 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1059 done:
1060 gimple_seq stmts = NULL;
1061 if (endp == 0 || endp == 3)
1062 len = NULL_TREE;
1063 else if (endp == 2)
1064 len = gimple_build (&stmts, loc, MINUS_EXPR, TREE_TYPE (len), len,
1065 ssize_int (1));
1066 if (endp == 2 || endp == 1)
1068 len = gimple_convert_to_ptrofftype (&stmts, loc, len);
1069 dest = gimple_build (&stmts, loc, POINTER_PLUS_EXPR,
1070 TREE_TYPE (dest), dest, len);
1073 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
1074 gimple *repl = gimple_build_assign (lhs, dest);
1075 gsi_replace (gsi, repl, false);
1076 return true;
1079 /* Fold function call to builtin memset or bzero at *GSI setting the
1080 memory of size LEN to VAL. Return whether a simplification was made. */
1082 static bool
1083 gimple_fold_builtin_memset (gimple_stmt_iterator *gsi, tree c, tree len)
1085 gimple *stmt = gsi_stmt (*gsi);
1086 tree etype;
1087 unsigned HOST_WIDE_INT length, cval;
1089 /* If the LEN parameter is zero, return DEST. */
1090 if (integer_zerop (len))
1092 replace_call_with_value (gsi, gimple_call_arg (stmt, 0));
1093 return true;
1096 if (! tree_fits_uhwi_p (len))
1097 return false;
1099 if (TREE_CODE (c) != INTEGER_CST)
1100 return false;
1102 tree dest = gimple_call_arg (stmt, 0);
1103 tree var = dest;
1104 if (TREE_CODE (var) != ADDR_EXPR)
1105 return false;
1107 var = TREE_OPERAND (var, 0);
1108 if (TREE_THIS_VOLATILE (var))
1109 return false;
1111 etype = TREE_TYPE (var);
1112 if (TREE_CODE (etype) == ARRAY_TYPE)
1113 etype = TREE_TYPE (etype);
1115 if (!INTEGRAL_TYPE_P (etype)
1116 && !POINTER_TYPE_P (etype))
1117 return NULL_TREE;
1119 if (! var_decl_component_p (var))
1120 return NULL_TREE;
1122 length = tree_to_uhwi (len);
1123 if (GET_MODE_SIZE (TYPE_MODE (etype)) != length
1124 || get_pointer_alignment (dest) / BITS_PER_UNIT < length)
1125 return NULL_TREE;
1127 if (length > HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT)
1128 return NULL_TREE;
1130 if (integer_zerop (c))
1131 cval = 0;
1132 else
1134 if (CHAR_BIT != 8 || BITS_PER_UNIT != 8 || HOST_BITS_PER_WIDE_INT > 64)
1135 return NULL_TREE;
1137 cval = TREE_INT_CST_LOW (c);
1138 cval &= 0xff;
1139 cval |= cval << 8;
1140 cval |= cval << 16;
1141 cval |= (cval << 31) << 1;
1144 var = fold_build2 (MEM_REF, etype, dest, build_int_cst (ptr_type_node, 0));
1145 gimple *store = gimple_build_assign (var, build_int_cst_type (etype, cval));
1146 gimple_set_vuse (store, gimple_vuse (stmt));
1147 tree vdef = gimple_vdef (stmt);
1148 if (vdef && TREE_CODE (vdef) == SSA_NAME)
1150 gimple_set_vdef (store, gimple_vdef (stmt));
1151 SSA_NAME_DEF_STMT (gimple_vdef (stmt)) = store;
1153 gsi_insert_before (gsi, store, GSI_SAME_STMT);
1154 if (gimple_call_lhs (stmt))
1156 gimple *asgn = gimple_build_assign (gimple_call_lhs (stmt), dest);
1157 gsi_replace (gsi, asgn, false);
1159 else
1161 gimple_stmt_iterator gsi2 = *gsi;
1162 gsi_prev (gsi);
1163 gsi_remove (&gsi2, true);
1166 return true;
1170 /* Obtain the minimum and maximum string length or minimum and maximum
1171 value of ARG in LENGTH[0] and LENGTH[1], respectively.
1172 If ARG is an SSA name variable, follow its use-def chains. When
1173 TYPE == 0, if LENGTH[1] is not equal to the length we determine or
1174 if we are unable to determine the length or value, return False.
1175 VISITED is a bitmap of visited variables.
1176 TYPE is 0 if string length should be obtained, 1 for maximum string
1177 length and 2 for maximum value ARG can have.
1178 When FUZZY is set and the length of a string cannot be determined,
1179 the function instead considers as the maximum possible length the
1180 size of a character array it may refer to. */
1182 static bool
1183 get_range_strlen (tree arg, tree length[2], bitmap *visited, int type,
1184 bool fuzzy)
1186 tree var, val;
1187 gimple *def_stmt;
1189 /* The minimum and maximum length. The MAXLEN pointer stays unchanged
1190 but MINLEN may be cleared during the execution of the function. */
1191 tree *minlen = length;
1192 tree *const maxlen = length + 1;
1194 if (TREE_CODE (arg) != SSA_NAME)
1196 /* We can end up with &(*iftmp_1)[0] here as well, so handle it. */
1197 if (TREE_CODE (arg) == ADDR_EXPR
1198 && TREE_CODE (TREE_OPERAND (arg, 0)) == ARRAY_REF
1199 && integer_zerop (TREE_OPERAND (TREE_OPERAND (arg, 0), 1)))
1201 tree aop0 = TREE_OPERAND (TREE_OPERAND (arg, 0), 0);
1202 if (TREE_CODE (aop0) == INDIRECT_REF
1203 && TREE_CODE (TREE_OPERAND (aop0, 0)) == SSA_NAME)
1204 return get_range_strlen (TREE_OPERAND (aop0, 0),
1205 length, visited, type, fuzzy);
1208 if (type == 2)
1210 val = arg;
1211 if (TREE_CODE (val) != INTEGER_CST
1212 || tree_int_cst_sgn (val) < 0)
1213 return false;
1215 else
1216 val = c_strlen (arg, 1);
1218 if (!val && fuzzy)
1220 if (TREE_CODE (arg) == ADDR_EXPR)
1221 return get_range_strlen (TREE_OPERAND (arg, 0), length,
1222 visited, type, fuzzy);
1224 if (TREE_CODE (arg) == COMPONENT_REF
1225 && TREE_CODE (TREE_TYPE (TREE_OPERAND (arg, 1))) == ARRAY_TYPE)
1227 /* Use the type of the member array to determine the upper
1228 bound on the length of the array. This may be overly
1229 optimistic if the array itself isn't NUL-terminated and
1230 the caller relies on the subsequent member to contain
1231 the NUL. */
1232 arg = TREE_OPERAND (arg, 1);
1233 val = TYPE_SIZE_UNIT (TREE_TYPE (arg));
1234 if (!val || integer_zerop (val))
1235 return false;
1236 val = fold_build2 (MINUS_EXPR, TREE_TYPE (val), val,
1237 integer_one_node);
1238 /* Avoid using the array size as the minimum. */
1239 minlen = NULL;
1243 if (!val)
1244 return false;
1246 if (minlen
1247 && (!*minlen
1248 || (type > 0
1249 && TREE_CODE (*minlen) == INTEGER_CST
1250 && TREE_CODE (val) == INTEGER_CST
1251 && tree_int_cst_lt (val, *minlen))))
1252 *minlen = val;
1254 if (*maxlen)
1256 if (type > 0)
1258 if (TREE_CODE (*maxlen) != INTEGER_CST
1259 || TREE_CODE (val) != INTEGER_CST)
1260 return false;
1262 if (tree_int_cst_lt (*maxlen, val))
1263 *maxlen = val;
1264 return true;
1266 else if (simple_cst_equal (val, *maxlen) != 1)
1267 return false;
1270 *maxlen = val;
1271 return true;
1274 /* If ARG is registered for SSA update we cannot look at its defining
1275 statement. */
1276 if (name_registered_for_update_p (arg))
1277 return false;
1279 /* If we were already here, break the infinite cycle. */
1280 if (!*visited)
1281 *visited = BITMAP_ALLOC (NULL);
1282 if (!bitmap_set_bit (*visited, SSA_NAME_VERSION (arg)))
1283 return true;
1285 var = arg;
1286 def_stmt = SSA_NAME_DEF_STMT (var);
1288 switch (gimple_code (def_stmt))
1290 case GIMPLE_ASSIGN:
1291 /* The RHS of the statement defining VAR must either have a
1292 constant length or come from another SSA_NAME with a constant
1293 length. */
1294 if (gimple_assign_single_p (def_stmt)
1295 || gimple_assign_unary_nop_p (def_stmt))
1297 tree rhs = gimple_assign_rhs1 (def_stmt);
1298 return get_range_strlen (rhs, length, visited, type, fuzzy);
1300 else if (gimple_assign_rhs_code (def_stmt) == COND_EXPR)
1302 tree op2 = gimple_assign_rhs2 (def_stmt);
1303 tree op3 = gimple_assign_rhs3 (def_stmt);
1304 return get_range_strlen (op2, length, visited, type, fuzzy)
1305 && get_range_strlen (op3, length, visited, type, fuzzy);
1307 return false;
1309 case GIMPLE_PHI:
1311 /* All the arguments of the PHI node must have the same constant
1312 length. */
1313 unsigned i;
1315 for (i = 0; i < gimple_phi_num_args (def_stmt); i++)
1317 tree arg = gimple_phi_arg (def_stmt, i)->def;
1319 /* If this PHI has itself as an argument, we cannot
1320 determine the string length of this argument. However,
1321 if we can find a constant string length for the other
1322 PHI args then we can still be sure that this is a
1323 constant string length. So be optimistic and just
1324 continue with the next argument. */
1325 if (arg == gimple_phi_result (def_stmt))
1326 continue;
1328 if (!get_range_strlen (arg, length, visited, type, fuzzy))
1330 if (fuzzy)
1331 *maxlen = build_all_ones_cst (size_type_node);
1332 else
1333 return false;
1337 return true;
1339 default:
1340 return false;
1344 /* Determine the minimum and maximum value or string length that ARG
1345 refers to and store each in the first two elements of MINMAXLEN.
1346 For expressions that point to strings of unknown lengths that are
1347 character arrays, use the upper bound of the array as the maximum
1348 length. For example, given an expression like 'x ? array : "xyz"'
1349 and array declared as 'char array[8]', MINMAXLEN[0] will be set
1350 to 3 and MINMAXLEN[1] to 7, the longest string that could be
1351 stored in array.
1354 void get_range_strlen (tree arg, tree minmaxlen[2])
1356 bitmap visited = NULL;
1358 minmaxlen[0] = NULL_TREE;
1359 minmaxlen[1] = NULL_TREE;
1361 get_range_strlen (arg, minmaxlen, &visited, 1, true);
1363 if (visited)
1364 BITMAP_FREE (visited);
1367 tree
1368 get_maxval_strlen (tree arg, int type)
1370 bitmap visited = NULL;
1371 tree len[2] = { NULL_TREE, NULL_TREE };
1372 if (!get_range_strlen (arg, len, &visited, type, false))
1373 len[1] = NULL_TREE;
1374 if (visited)
1375 BITMAP_FREE (visited);
1377 return len[1];
1381 /* Fold function call to builtin strcpy with arguments DEST and SRC.
1382 If LEN is not NULL, it represents the length of the string to be
1383 copied. Return NULL_TREE if no simplification can be made. */
1385 static bool
1386 gimple_fold_builtin_strcpy (gimple_stmt_iterator *gsi,
1387 tree dest, tree src)
1389 location_t loc = gimple_location (gsi_stmt (*gsi));
1390 tree fn;
1392 /* If SRC and DEST are the same (and not volatile), return DEST. */
1393 if (operand_equal_p (src, dest, 0))
1395 replace_call_with_value (gsi, dest);
1396 return true;
1399 if (optimize_function_for_size_p (cfun))
1400 return false;
1402 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1403 if (!fn)
1404 return false;
1406 tree len = get_maxval_strlen (src, 0);
1407 if (!len)
1408 return false;
1410 len = fold_convert_loc (loc, size_type_node, len);
1411 len = size_binop_loc (loc, PLUS_EXPR, len, build_int_cst (size_type_node, 1));
1412 len = force_gimple_operand_gsi (gsi, len, true,
1413 NULL_TREE, true, GSI_SAME_STMT);
1414 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
1415 replace_call_with_call_and_fold (gsi, repl);
1416 return true;
1419 /* Fold function call to builtin strncpy with arguments DEST, SRC, and LEN.
1420 If SLEN is not NULL, it represents the length of the source string.
1421 Return NULL_TREE if no simplification can be made. */
1423 static bool
1424 gimple_fold_builtin_strncpy (gimple_stmt_iterator *gsi,
1425 tree dest, tree src, tree len)
1427 location_t loc = gimple_location (gsi_stmt (*gsi));
1428 tree fn;
1430 /* If the LEN parameter is zero, return DEST. */
1431 if (integer_zerop (len))
1433 replace_call_with_value (gsi, dest);
1434 return true;
1437 /* We can't compare slen with len as constants below if len is not a
1438 constant. */
1439 if (TREE_CODE (len) != INTEGER_CST)
1440 return false;
1442 /* Now, we must be passed a constant src ptr parameter. */
1443 tree slen = get_maxval_strlen (src, 0);
1444 if (!slen || TREE_CODE (slen) != INTEGER_CST)
1445 return false;
1447 slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
1449 /* We do not support simplification of this case, though we do
1450 support it when expanding trees into RTL. */
1451 /* FIXME: generate a call to __builtin_memset. */
1452 if (tree_int_cst_lt (slen, len))
1453 return false;
1455 /* OK transform into builtin memcpy. */
1456 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1457 if (!fn)
1458 return false;
1460 len = fold_convert_loc (loc, size_type_node, len);
1461 len = force_gimple_operand_gsi (gsi, len, true,
1462 NULL_TREE, true, GSI_SAME_STMT);
1463 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
1464 replace_call_with_call_and_fold (gsi, repl);
1465 return true;
1468 /* Fold function call to builtin strchr or strrchr.
1469 If both arguments are constant, evaluate and fold the result,
1470 otherwise simplify str(r)chr (str, 0) into str + strlen (str).
1471 In general strlen is significantly faster than strchr
1472 due to being a simpler operation. */
1473 static bool
1474 gimple_fold_builtin_strchr (gimple_stmt_iterator *gsi, bool is_strrchr)
1476 gimple *stmt = gsi_stmt (*gsi);
1477 tree str = gimple_call_arg (stmt, 0);
1478 tree c = gimple_call_arg (stmt, 1);
1479 location_t loc = gimple_location (stmt);
1480 const char *p;
1481 char ch;
1483 if (!gimple_call_lhs (stmt))
1484 return false;
1486 if ((p = c_getstr (str)) && target_char_cst_p (c, &ch))
1488 const char *p1 = is_strrchr ? strrchr (p, ch) : strchr (p, ch);
1490 if (p1 == NULL)
1492 replace_call_with_value (gsi, integer_zero_node);
1493 return true;
1496 tree len = build_int_cst (size_type_node, p1 - p);
1497 gimple_seq stmts = NULL;
1498 gimple *new_stmt = gimple_build_assign (gimple_call_lhs (stmt),
1499 POINTER_PLUS_EXPR, str, len);
1500 gimple_seq_add_stmt_without_update (&stmts, new_stmt);
1501 gsi_replace_with_seq_vops (gsi, stmts);
1502 return true;
1505 if (!integer_zerop (c))
1506 return false;
1508 /* Transform strrchr (s, 0) to strchr (s, 0) when optimizing for size. */
1509 if (optimize_function_for_size_p (cfun))
1511 tree strchr_fn = builtin_decl_implicit (BUILT_IN_STRCHR);
1513 if (is_strrchr && strchr_fn)
1515 gimple *repl = gimple_build_call (strchr_fn, 2, str, c);
1516 replace_call_with_call_and_fold (gsi, repl);
1517 return true;
1520 return false;
1523 tree len;
1524 tree strlen_fn = builtin_decl_implicit (BUILT_IN_STRLEN);
1526 if (!strlen_fn)
1527 return false;
1529 /* Create newstr = strlen (str). */
1530 gimple_seq stmts = NULL;
1531 gimple *new_stmt = gimple_build_call (strlen_fn, 1, str);
1532 gimple_set_location (new_stmt, loc);
1533 len = create_tmp_reg_or_ssa_name (size_type_node);
1534 gimple_call_set_lhs (new_stmt, len);
1535 gimple_seq_add_stmt_without_update (&stmts, new_stmt);
1537 /* Create (str p+ strlen (str)). */
1538 new_stmt = gimple_build_assign (gimple_call_lhs (stmt),
1539 POINTER_PLUS_EXPR, str, len);
1540 gimple_seq_add_stmt_without_update (&stmts, new_stmt);
1541 gsi_replace_with_seq_vops (gsi, stmts);
1542 /* gsi now points at the assignment to the lhs, get a
1543 stmt iterator to the strlen.
1544 ??? We can't use gsi_for_stmt as that doesn't work when the
1545 CFG isn't built yet. */
1546 gimple_stmt_iterator gsi2 = *gsi;
1547 gsi_prev (&gsi2);
1548 fold_stmt (&gsi2);
1549 return true;
1552 /* Simplify a call to the strcat builtin. DST and SRC are the arguments
1553 to the call.
1555 Return NULL_TREE if no simplification was possible, otherwise return the
1556 simplified form of the call as a tree.
1558 The simplified form may be a constant or other expression which
1559 computes the same value, but in a more efficient manner (including
1560 calls to other builtin functions).
1562 The call may contain arguments which need to be evaluated, but
1563 which are not useful to determine the result of the call. In
1564 this case we return a chain of COMPOUND_EXPRs. The LHS of each
1565 COMPOUND_EXPR will be an argument which must be evaluated.
1566 COMPOUND_EXPRs are chained through their RHS. The RHS of the last
1567 COMPOUND_EXPR in the chain will contain the tree for the simplified
1568 form of the builtin function call. */
1570 static bool
1571 gimple_fold_builtin_strcat (gimple_stmt_iterator *gsi, tree dst, tree src)
1573 gimple *stmt = gsi_stmt (*gsi);
1574 location_t loc = gimple_location (stmt);
1576 const char *p = c_getstr (src);
1578 /* If the string length is zero, return the dst parameter. */
1579 if (p && *p == '\0')
1581 replace_call_with_value (gsi, dst);
1582 return true;
1585 if (!optimize_bb_for_speed_p (gimple_bb (stmt)))
1586 return false;
1588 /* See if we can store by pieces into (dst + strlen(dst)). */
1589 tree newdst;
1590 tree strlen_fn = builtin_decl_implicit (BUILT_IN_STRLEN);
1591 tree memcpy_fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1593 if (!strlen_fn || !memcpy_fn)
1594 return false;
1596 /* If the length of the source string isn't computable don't
1597 split strcat into strlen and memcpy. */
1598 tree len = get_maxval_strlen (src, 0);
1599 if (! len)
1600 return false;
1602 /* Create strlen (dst). */
1603 gimple_seq stmts = NULL, stmts2;
1604 gimple *repl = gimple_build_call (strlen_fn, 1, dst);
1605 gimple_set_location (repl, loc);
1606 newdst = create_tmp_reg_or_ssa_name (size_type_node);
1607 gimple_call_set_lhs (repl, newdst);
1608 gimple_seq_add_stmt_without_update (&stmts, repl);
1610 /* Create (dst p+ strlen (dst)). */
1611 newdst = fold_build_pointer_plus_loc (loc, dst, newdst);
1612 newdst = force_gimple_operand (newdst, &stmts2, true, NULL_TREE);
1613 gimple_seq_add_seq_without_update (&stmts, stmts2);
1615 len = fold_convert_loc (loc, size_type_node, len);
1616 len = size_binop_loc (loc, PLUS_EXPR, len,
1617 build_int_cst (size_type_node, 1));
1618 len = force_gimple_operand (len, &stmts2, true, NULL_TREE);
1619 gimple_seq_add_seq_without_update (&stmts, stmts2);
1621 repl = gimple_build_call (memcpy_fn, 3, newdst, src, len);
1622 gimple_seq_add_stmt_without_update (&stmts, repl);
1623 if (gimple_call_lhs (stmt))
1625 repl = gimple_build_assign (gimple_call_lhs (stmt), dst);
1626 gimple_seq_add_stmt_without_update (&stmts, repl);
1627 gsi_replace_with_seq_vops (gsi, stmts);
1628 /* gsi now points at the assignment to the lhs, get a
1629 stmt iterator to the memcpy call.
1630 ??? We can't use gsi_for_stmt as that doesn't work when the
1631 CFG isn't built yet. */
1632 gimple_stmt_iterator gsi2 = *gsi;
1633 gsi_prev (&gsi2);
1634 fold_stmt (&gsi2);
1636 else
1638 gsi_replace_with_seq_vops (gsi, stmts);
1639 fold_stmt (gsi);
1641 return true;
1644 /* Fold a call to the __strcat_chk builtin FNDECL. DEST, SRC, and SIZE
1645 are the arguments to the call. */
1647 static bool
1648 gimple_fold_builtin_strcat_chk (gimple_stmt_iterator *gsi)
1650 gimple *stmt = gsi_stmt (*gsi);
1651 tree dest = gimple_call_arg (stmt, 0);
1652 tree src = gimple_call_arg (stmt, 1);
1653 tree size = gimple_call_arg (stmt, 2);
1654 tree fn;
1655 const char *p;
1658 p = c_getstr (src);
1659 /* If the SRC parameter is "", return DEST. */
1660 if (p && *p == '\0')
1662 replace_call_with_value (gsi, dest);
1663 return true;
1666 if (! tree_fits_uhwi_p (size) || ! integer_all_onesp (size))
1667 return false;
1669 /* If __builtin_strcat_chk is used, assume strcat is available. */
1670 fn = builtin_decl_explicit (BUILT_IN_STRCAT);
1671 if (!fn)
1672 return false;
1674 gimple *repl = gimple_build_call (fn, 2, dest, src);
1675 replace_call_with_call_and_fold (gsi, repl);
1676 return true;
1679 /* Simplify a call to the strncat builtin. */
1681 static bool
1682 gimple_fold_builtin_strncat (gimple_stmt_iterator *gsi)
1684 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
1685 tree dst = gimple_call_arg (stmt, 0);
1686 tree src = gimple_call_arg (stmt, 1);
1687 tree len = gimple_call_arg (stmt, 2);
1689 const char *p = c_getstr (src);
1691 /* If the requested length is zero, or the src parameter string
1692 length is zero, return the dst parameter. */
1693 if (integer_zerop (len) || (p && *p == '\0'))
1695 replace_call_with_value (gsi, dst);
1696 return true;
1699 /* If the requested len is greater than or equal to the string
1700 length, call strcat. */
1701 if (TREE_CODE (len) == INTEGER_CST && p
1702 && compare_tree_int (len, strlen (p)) >= 0)
1704 tree fn = builtin_decl_implicit (BUILT_IN_STRCAT);
1706 /* If the replacement _DECL isn't initialized, don't do the
1707 transformation. */
1708 if (!fn)
1709 return false;
1711 gcall *repl = gimple_build_call (fn, 2, dst, src);
1712 replace_call_with_call_and_fold (gsi, repl);
1713 return true;
1716 return false;
1719 /* Fold a call to the __strncat_chk builtin with arguments DEST, SRC,
1720 LEN, and SIZE. */
1722 static bool
1723 gimple_fold_builtin_strncat_chk (gimple_stmt_iterator *gsi)
1725 gimple *stmt = gsi_stmt (*gsi);
1726 tree dest = gimple_call_arg (stmt, 0);
1727 tree src = gimple_call_arg (stmt, 1);
1728 tree len = gimple_call_arg (stmt, 2);
1729 tree size = gimple_call_arg (stmt, 3);
1730 tree fn;
1731 const char *p;
1733 p = c_getstr (src);
1734 /* If the SRC parameter is "" or if LEN is 0, return DEST. */
1735 if ((p && *p == '\0')
1736 || integer_zerop (len))
1738 replace_call_with_value (gsi, dest);
1739 return true;
1742 if (! tree_fits_uhwi_p (size))
1743 return false;
1745 if (! integer_all_onesp (size))
1747 tree src_len = c_strlen (src, 1);
1748 if (src_len
1749 && tree_fits_uhwi_p (src_len)
1750 && tree_fits_uhwi_p (len)
1751 && ! tree_int_cst_lt (len, src_len))
1753 /* If LEN >= strlen (SRC), optimize into __strcat_chk. */
1754 fn = builtin_decl_explicit (BUILT_IN_STRCAT_CHK);
1755 if (!fn)
1756 return false;
1758 gimple *repl = gimple_build_call (fn, 3, dest, src, size);
1759 replace_call_with_call_and_fold (gsi, repl);
1760 return true;
1762 return false;
1765 /* If __builtin_strncat_chk is used, assume strncat is available. */
1766 fn = builtin_decl_explicit (BUILT_IN_STRNCAT);
1767 if (!fn)
1768 return false;
1770 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
1771 replace_call_with_call_and_fold (gsi, repl);
1772 return true;
1775 /* Build and append gimple statements to STMTS that would load a first
1776 character of a memory location identified by STR. LOC is location
1777 of the statement. */
1779 static tree
1780 gimple_load_first_char (location_t loc, tree str, gimple_seq *stmts)
1782 tree var;
1784 tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
1785 tree cst_uchar_ptr_node
1786 = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
1787 tree off0 = build_int_cst (cst_uchar_ptr_node, 0);
1789 tree temp = fold_build2_loc (loc, MEM_REF, cst_uchar_node, str, off0);
1790 gassign *stmt = gimple_build_assign (NULL_TREE, temp);
1791 var = create_tmp_reg_or_ssa_name (cst_uchar_node, stmt);
1793 gimple_assign_set_lhs (stmt, var);
1794 gimple_seq_add_stmt_without_update (stmts, stmt);
1796 return var;
1799 /* Fold a call to the str{n}{case}cmp builtin pointed by GSI iterator.
1800 FCODE is the name of the builtin. */
1802 static bool
1803 gimple_fold_builtin_string_compare (gimple_stmt_iterator *gsi)
1805 gimple *stmt = gsi_stmt (*gsi);
1806 tree callee = gimple_call_fndecl (stmt);
1807 enum built_in_function fcode = DECL_FUNCTION_CODE (callee);
1809 tree type = integer_type_node;
1810 tree str1 = gimple_call_arg (stmt, 0);
1811 tree str2 = gimple_call_arg (stmt, 1);
1812 tree lhs = gimple_call_lhs (stmt);
1813 HOST_WIDE_INT length = -1;
1815 /* Handle strncmp and strncasecmp functions. */
1816 if (gimple_call_num_args (stmt) == 3)
1818 tree len = gimple_call_arg (stmt, 2);
1819 if (tree_fits_uhwi_p (len))
1820 length = tree_to_uhwi (len);
1823 /* If the LEN parameter is zero, return zero. */
1824 if (length == 0)
1826 replace_call_with_value (gsi, integer_zero_node);
1827 return true;
1830 /* If ARG1 and ARG2 are the same (and not volatile), return zero. */
1831 if (operand_equal_p (str1, str2, 0))
1833 replace_call_with_value (gsi, integer_zero_node);
1834 return true;
1837 const char *p1 = c_getstr (str1);
1838 const char *p2 = c_getstr (str2);
1840 /* For known strings, return an immediate value. */
1841 if (p1 && p2)
1843 int r = 0;
1844 bool known_result = false;
1846 switch (fcode)
1848 case BUILT_IN_STRCMP:
1850 r = strcmp (p1, p2);
1851 known_result = true;
1852 break;
1854 case BUILT_IN_STRNCMP:
1856 if (length == -1)
1857 break;
1858 r = strncmp (p1, p2, length);
1859 known_result = true;
1860 break;
1862 /* Only handleable situation is where the string are equal (result 0),
1863 which is already handled by operand_equal_p case. */
1864 case BUILT_IN_STRCASECMP:
1865 break;
1866 case BUILT_IN_STRNCASECMP:
1868 if (length == -1)
1869 break;
1870 r = strncmp (p1, p2, length);
1871 if (r == 0)
1872 known_result = true;
1873 break;;
1875 default:
1876 gcc_unreachable ();
1879 if (known_result)
1881 replace_call_with_value (gsi, build_cmp_result (type, r));
1882 return true;
1886 bool nonzero_length = length >= 1
1887 || fcode == BUILT_IN_STRCMP
1888 || fcode == BUILT_IN_STRCASECMP;
1890 location_t loc = gimple_location (stmt);
1892 /* If the second arg is "", return *(const unsigned char*)arg1. */
1893 if (p2 && *p2 == '\0' && nonzero_length)
1895 gimple_seq stmts = NULL;
1896 tree var = gimple_load_first_char (loc, str1, &stmts);
1897 if (lhs)
1899 stmt = gimple_build_assign (lhs, NOP_EXPR, var);
1900 gimple_seq_add_stmt_without_update (&stmts, stmt);
1903 gsi_replace_with_seq_vops (gsi, stmts);
1904 return true;
1907 /* If the first arg is "", return -*(const unsigned char*)arg2. */
1908 if (p1 && *p1 == '\0' && nonzero_length)
1910 gimple_seq stmts = NULL;
1911 tree var = gimple_load_first_char (loc, str2, &stmts);
1913 if (lhs)
1915 tree c = create_tmp_reg_or_ssa_name (integer_type_node);
1916 stmt = gimple_build_assign (c, NOP_EXPR, var);
1917 gimple_seq_add_stmt_without_update (&stmts, stmt);
1919 stmt = gimple_build_assign (lhs, NEGATE_EXPR, c);
1920 gimple_seq_add_stmt_without_update (&stmts, stmt);
1923 gsi_replace_with_seq_vops (gsi, stmts);
1924 return true;
1927 /* If len parameter is one, return an expression corresponding to
1928 (*(const unsigned char*)arg2 - *(const unsigned char*)arg1). */
1929 if (fcode == BUILT_IN_STRNCMP && length == 1)
1931 gimple_seq stmts = NULL;
1932 tree temp1 = gimple_load_first_char (loc, str1, &stmts);
1933 tree temp2 = gimple_load_first_char (loc, str2, &stmts);
1935 if (lhs)
1937 tree c1 = create_tmp_reg_or_ssa_name (integer_type_node);
1938 gassign *convert1 = gimple_build_assign (c1, NOP_EXPR, temp1);
1939 gimple_seq_add_stmt_without_update (&stmts, convert1);
1941 tree c2 = create_tmp_reg_or_ssa_name (integer_type_node);
1942 gassign *convert2 = gimple_build_assign (c2, NOP_EXPR, temp2);
1943 gimple_seq_add_stmt_without_update (&stmts, convert2);
1945 stmt = gimple_build_assign (lhs, MINUS_EXPR, c1, c2);
1946 gimple_seq_add_stmt_without_update (&stmts, stmt);
1949 gsi_replace_with_seq_vops (gsi, stmts);
1950 return true;
1953 return false;
1956 /* Fold a call to the memchr pointed by GSI iterator. */
1958 static bool
1959 gimple_fold_builtin_memchr (gimple_stmt_iterator *gsi)
1961 gimple *stmt = gsi_stmt (*gsi);
1962 tree lhs = gimple_call_lhs (stmt);
1963 tree arg1 = gimple_call_arg (stmt, 0);
1964 tree arg2 = gimple_call_arg (stmt, 1);
1965 tree len = gimple_call_arg (stmt, 2);
1967 /* If the LEN parameter is zero, return zero. */
1968 if (integer_zerop (len))
1970 replace_call_with_value (gsi, build_int_cst (ptr_type_node, 0));
1971 return true;
1974 char c;
1975 if (TREE_CODE (arg2) != INTEGER_CST
1976 || !tree_fits_uhwi_p (len)
1977 || !target_char_cst_p (arg2, &c))
1978 return false;
1980 unsigned HOST_WIDE_INT length = tree_to_uhwi (len);
1981 unsigned HOST_WIDE_INT string_length;
1982 const char *p1 = c_getstr (arg1, &string_length);
1984 if (p1)
1986 const char *r = (const char *)memchr (p1, c, MIN (length, string_length));
1987 if (r == NULL)
1989 if (length <= string_length)
1991 replace_call_with_value (gsi, build_int_cst (ptr_type_node, 0));
1992 return true;
1995 else
1997 unsigned HOST_WIDE_INT offset = r - p1;
1998 gimple_seq stmts = NULL;
1999 if (lhs != NULL_TREE)
2001 tree offset_cst = build_int_cst (TREE_TYPE (len), offset);
2002 gassign *stmt = gimple_build_assign (lhs, POINTER_PLUS_EXPR,
2003 arg1, offset_cst);
2004 gimple_seq_add_stmt_without_update (&stmts, stmt);
2006 else
2007 gimple_seq_add_stmt_without_update (&stmts,
2008 gimple_build_nop ());
2010 gsi_replace_with_seq_vops (gsi, stmts);
2011 return true;
2015 return false;
2018 /* Fold a call to the fputs builtin. ARG0 and ARG1 are the arguments
2019 to the call. IGNORE is true if the value returned
2020 by the builtin will be ignored. UNLOCKED is true is true if this
2021 actually a call to fputs_unlocked. If LEN in non-NULL, it represents
2022 the known length of the string. Return NULL_TREE if no simplification
2023 was possible. */
2025 static bool
2026 gimple_fold_builtin_fputs (gimple_stmt_iterator *gsi,
2027 tree arg0, tree arg1,
2028 bool unlocked)
2030 gimple *stmt = gsi_stmt (*gsi);
2032 /* If we're using an unlocked function, assume the other unlocked
2033 functions exist explicitly. */
2034 tree const fn_fputc = (unlocked
2035 ? builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED)
2036 : builtin_decl_implicit (BUILT_IN_FPUTC));
2037 tree const fn_fwrite = (unlocked
2038 ? builtin_decl_explicit (BUILT_IN_FWRITE_UNLOCKED)
2039 : builtin_decl_implicit (BUILT_IN_FWRITE));
2041 /* If the return value is used, don't do the transformation. */
2042 if (gimple_call_lhs (stmt))
2043 return false;
2045 /* Get the length of the string passed to fputs. If the length
2046 can't be determined, punt. */
2047 tree len = get_maxval_strlen (arg0, 0);
2048 if (!len
2049 || TREE_CODE (len) != INTEGER_CST)
2050 return false;
2052 switch (compare_tree_int (len, 1))
2054 case -1: /* length is 0, delete the call entirely . */
2055 replace_call_with_value (gsi, integer_zero_node);
2056 return true;
2058 case 0: /* length is 1, call fputc. */
2060 const char *p = c_getstr (arg0);
2061 if (p != NULL)
2063 if (!fn_fputc)
2064 return false;
2066 gimple *repl = gimple_build_call (fn_fputc, 2,
2067 build_int_cst
2068 (integer_type_node, p[0]), arg1);
2069 replace_call_with_call_and_fold (gsi, repl);
2070 return true;
2073 /* FALLTHROUGH */
2074 case 1: /* length is greater than 1, call fwrite. */
2076 /* If optimizing for size keep fputs. */
2077 if (optimize_function_for_size_p (cfun))
2078 return false;
2079 /* New argument list transforming fputs(string, stream) to
2080 fwrite(string, 1, len, stream). */
2081 if (!fn_fwrite)
2082 return false;
2084 gimple *repl = gimple_build_call (fn_fwrite, 4, arg0,
2085 size_one_node, len, arg1);
2086 replace_call_with_call_and_fold (gsi, repl);
2087 return true;
2089 default:
2090 gcc_unreachable ();
2092 return false;
2095 /* Fold a call to the __mem{cpy,pcpy,move,set}_chk builtin.
2096 DEST, SRC, LEN, and SIZE are the arguments to the call.
2097 IGNORE is true, if return value can be ignored. FCODE is the BUILT_IN_*
2098 code of the builtin. If MAXLEN is not NULL, it is maximum length
2099 passed as third argument. */
2101 static bool
2102 gimple_fold_builtin_memory_chk (gimple_stmt_iterator *gsi,
2103 tree dest, tree src, tree len, tree size,
2104 enum built_in_function fcode)
2106 gimple *stmt = gsi_stmt (*gsi);
2107 location_t loc = gimple_location (stmt);
2108 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
2109 tree fn;
2111 /* If SRC and DEST are the same (and not volatile), return DEST
2112 (resp. DEST+LEN for __mempcpy_chk). */
2113 if (fcode != BUILT_IN_MEMSET_CHK && operand_equal_p (src, dest, 0))
2115 if (fcode != BUILT_IN_MEMPCPY_CHK)
2117 replace_call_with_value (gsi, dest);
2118 return true;
2120 else
2122 gimple_seq stmts = NULL;
2123 len = gimple_convert_to_ptrofftype (&stmts, loc, len);
2124 tree temp = gimple_build (&stmts, loc, POINTER_PLUS_EXPR,
2125 TREE_TYPE (dest), dest, len);
2126 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
2127 replace_call_with_value (gsi, temp);
2128 return true;
2132 if (! tree_fits_uhwi_p (size))
2133 return false;
2135 tree maxlen = get_maxval_strlen (len, 2);
2136 if (! integer_all_onesp (size))
2138 if (! tree_fits_uhwi_p (len))
2140 /* If LEN is not constant, try MAXLEN too.
2141 For MAXLEN only allow optimizing into non-_ocs function
2142 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
2143 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
2145 if (fcode == BUILT_IN_MEMPCPY_CHK && ignore)
2147 /* (void) __mempcpy_chk () can be optimized into
2148 (void) __memcpy_chk (). */
2149 fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
2150 if (!fn)
2151 return false;
2153 gimple *repl = gimple_build_call (fn, 4, dest, src, len, size);
2154 replace_call_with_call_and_fold (gsi, repl);
2155 return true;
2157 return false;
2160 else
2161 maxlen = len;
2163 if (tree_int_cst_lt (size, maxlen))
2164 return false;
2167 fn = NULL_TREE;
2168 /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
2169 mem{cpy,pcpy,move,set} is available. */
2170 switch (fcode)
2172 case BUILT_IN_MEMCPY_CHK:
2173 fn = builtin_decl_explicit (BUILT_IN_MEMCPY);
2174 break;
2175 case BUILT_IN_MEMPCPY_CHK:
2176 fn = builtin_decl_explicit (BUILT_IN_MEMPCPY);
2177 break;
2178 case BUILT_IN_MEMMOVE_CHK:
2179 fn = builtin_decl_explicit (BUILT_IN_MEMMOVE);
2180 break;
2181 case BUILT_IN_MEMSET_CHK:
2182 fn = builtin_decl_explicit (BUILT_IN_MEMSET);
2183 break;
2184 default:
2185 break;
2188 if (!fn)
2189 return false;
2191 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
2192 replace_call_with_call_and_fold (gsi, repl);
2193 return true;
2196 /* Fold a call to the __st[rp]cpy_chk builtin.
2197 DEST, SRC, and SIZE are the arguments to the call.
2198 IGNORE is true if return value can be ignored. FCODE is the BUILT_IN_*
2199 code of the builtin. If MAXLEN is not NULL, it is maximum length of
2200 strings passed as second argument. */
2202 static bool
2203 gimple_fold_builtin_stxcpy_chk (gimple_stmt_iterator *gsi,
2204 tree dest,
2205 tree src, tree size,
2206 enum built_in_function fcode)
2208 gimple *stmt = gsi_stmt (*gsi);
2209 location_t loc = gimple_location (stmt);
2210 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
2211 tree len, fn;
2213 /* If SRC and DEST are the same (and not volatile), return DEST. */
2214 if (fcode == BUILT_IN_STRCPY_CHK && operand_equal_p (src, dest, 0))
2216 replace_call_with_value (gsi, dest);
2217 return true;
2220 if (! tree_fits_uhwi_p (size))
2221 return false;
2223 tree maxlen = get_maxval_strlen (src, 1);
2224 if (! integer_all_onesp (size))
2226 len = c_strlen (src, 1);
2227 if (! len || ! tree_fits_uhwi_p (len))
2229 /* If LEN is not constant, try MAXLEN too.
2230 For MAXLEN only allow optimizing into non-_ocs function
2231 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
2232 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
2234 if (fcode == BUILT_IN_STPCPY_CHK)
2236 if (! ignore)
2237 return false;
2239 /* If return value of __stpcpy_chk is ignored,
2240 optimize into __strcpy_chk. */
2241 fn = builtin_decl_explicit (BUILT_IN_STRCPY_CHK);
2242 if (!fn)
2243 return false;
2245 gimple *repl = gimple_build_call (fn, 3, dest, src, size);
2246 replace_call_with_call_and_fold (gsi, repl);
2247 return true;
2250 if (! len || TREE_SIDE_EFFECTS (len))
2251 return false;
2253 /* If c_strlen returned something, but not a constant,
2254 transform __strcpy_chk into __memcpy_chk. */
2255 fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
2256 if (!fn)
2257 return false;
2259 gimple_seq stmts = NULL;
2260 len = gimple_convert (&stmts, loc, size_type_node, len);
2261 len = gimple_build (&stmts, loc, PLUS_EXPR, size_type_node, len,
2262 build_int_cst (size_type_node, 1));
2263 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
2264 gimple *repl = gimple_build_call (fn, 4, dest, src, len, size);
2265 replace_call_with_call_and_fold (gsi, repl);
2266 return true;
2269 else
2270 maxlen = len;
2272 if (! tree_int_cst_lt (maxlen, size))
2273 return false;
2276 /* If __builtin_st{r,p}cpy_chk is used, assume st{r,p}cpy is available. */
2277 fn = builtin_decl_explicit (fcode == BUILT_IN_STPCPY_CHK
2278 ? BUILT_IN_STPCPY : BUILT_IN_STRCPY);
2279 if (!fn)
2280 return false;
2282 gimple *repl = gimple_build_call (fn, 2, dest, src);
2283 replace_call_with_call_and_fold (gsi, repl);
2284 return true;
2287 /* Fold a call to the __st{r,p}ncpy_chk builtin. DEST, SRC, LEN, and SIZE
2288 are the arguments to the call. If MAXLEN is not NULL, it is maximum
2289 length passed as third argument. IGNORE is true if return value can be
2290 ignored. FCODE is the BUILT_IN_* code of the builtin. */
2292 static bool
2293 gimple_fold_builtin_stxncpy_chk (gimple_stmt_iterator *gsi,
2294 tree dest, tree src,
2295 tree len, tree size,
2296 enum built_in_function fcode)
2298 gimple *stmt = gsi_stmt (*gsi);
2299 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
2300 tree fn;
2302 if (fcode == BUILT_IN_STPNCPY_CHK && ignore)
2304 /* If return value of __stpncpy_chk is ignored,
2305 optimize into __strncpy_chk. */
2306 fn = builtin_decl_explicit (BUILT_IN_STRNCPY_CHK);
2307 if (fn)
2309 gimple *repl = gimple_build_call (fn, 4, dest, src, len, size);
2310 replace_call_with_call_and_fold (gsi, repl);
2311 return true;
2315 if (! tree_fits_uhwi_p (size))
2316 return false;
2318 tree maxlen = get_maxval_strlen (len, 2);
2319 if (! integer_all_onesp (size))
2321 if (! tree_fits_uhwi_p (len))
2323 /* If LEN is not constant, try MAXLEN too.
2324 For MAXLEN only allow optimizing into non-_ocs function
2325 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
2326 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
2327 return false;
2329 else
2330 maxlen = len;
2332 if (tree_int_cst_lt (size, maxlen))
2333 return false;
2336 /* If __builtin_st{r,p}ncpy_chk is used, assume st{r,p}ncpy is available. */
2337 fn = builtin_decl_explicit (fcode == BUILT_IN_STPNCPY_CHK
2338 ? BUILT_IN_STPNCPY : BUILT_IN_STRNCPY);
2339 if (!fn)
2340 return false;
2342 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
2343 replace_call_with_call_and_fold (gsi, repl);
2344 return true;
2347 /* Fold function call to builtin stpcpy with arguments DEST and SRC.
2348 Return NULL_TREE if no simplification can be made. */
2350 static bool
2351 gimple_fold_builtin_stpcpy (gimple_stmt_iterator *gsi)
2353 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2354 location_t loc = gimple_location (stmt);
2355 tree dest = gimple_call_arg (stmt, 0);
2356 tree src = gimple_call_arg (stmt, 1);
2357 tree fn, len, lenp1;
2359 /* If the result is unused, replace stpcpy with strcpy. */
2360 if (gimple_call_lhs (stmt) == NULL_TREE)
2362 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2363 if (!fn)
2364 return false;
2365 gimple_call_set_fndecl (stmt, fn);
2366 fold_stmt (gsi);
2367 return true;
2370 len = c_strlen (src, 1);
2371 if (!len
2372 || TREE_CODE (len) != INTEGER_CST)
2373 return false;
2375 if (optimize_function_for_size_p (cfun)
2376 /* If length is zero it's small enough. */
2377 && !integer_zerop (len))
2378 return false;
2380 /* If the source has a known length replace stpcpy with memcpy. */
2381 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
2382 if (!fn)
2383 return false;
2385 gimple_seq stmts = NULL;
2386 tree tem = gimple_convert (&stmts, loc, size_type_node, len);
2387 lenp1 = gimple_build (&stmts, loc, PLUS_EXPR, size_type_node,
2388 tem, build_int_cst (size_type_node, 1));
2389 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
2390 gcall *repl = gimple_build_call (fn, 3, dest, src, lenp1);
2391 gimple_set_vuse (repl, gimple_vuse (stmt));
2392 gimple_set_vdef (repl, gimple_vdef (stmt));
2393 if (gimple_vdef (repl)
2394 && TREE_CODE (gimple_vdef (repl)) == SSA_NAME)
2395 SSA_NAME_DEF_STMT (gimple_vdef (repl)) = repl;
2396 gsi_insert_before (gsi, repl, GSI_SAME_STMT);
2397 /* Replace the result with dest + len. */
2398 stmts = NULL;
2399 tem = gimple_convert (&stmts, loc, sizetype, len);
2400 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
2401 gassign *ret = gimple_build_assign (gimple_call_lhs (stmt),
2402 POINTER_PLUS_EXPR, dest, tem);
2403 gsi_replace (gsi, ret, false);
2404 /* Finally fold the memcpy call. */
2405 gimple_stmt_iterator gsi2 = *gsi;
2406 gsi_prev (&gsi2);
2407 fold_stmt (&gsi2);
2408 return true;
2411 /* Fold a call EXP to {,v}snprintf having NARGS passed as ARGS. Return
2412 NULL_TREE if a normal call should be emitted rather than expanding
2413 the function inline. FCODE is either BUILT_IN_SNPRINTF_CHK or
2414 BUILT_IN_VSNPRINTF_CHK. If MAXLEN is not NULL, it is maximum length
2415 passed as second argument. */
2417 static bool
2418 gimple_fold_builtin_snprintf_chk (gimple_stmt_iterator *gsi,
2419 enum built_in_function fcode)
2421 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2422 tree dest, size, len, fn, fmt, flag;
2423 const char *fmt_str;
2425 /* Verify the required arguments in the original call. */
2426 if (gimple_call_num_args (stmt) < 5)
2427 return false;
2429 dest = gimple_call_arg (stmt, 0);
2430 len = gimple_call_arg (stmt, 1);
2431 flag = gimple_call_arg (stmt, 2);
2432 size = gimple_call_arg (stmt, 3);
2433 fmt = gimple_call_arg (stmt, 4);
2435 if (! tree_fits_uhwi_p (size))
2436 return false;
2438 if (! integer_all_onesp (size))
2440 tree maxlen = get_maxval_strlen (len, 2);
2441 if (! tree_fits_uhwi_p (len))
2443 /* If LEN is not constant, try MAXLEN too.
2444 For MAXLEN only allow optimizing into non-_ocs function
2445 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
2446 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
2447 return false;
2449 else
2450 maxlen = len;
2452 if (tree_int_cst_lt (size, maxlen))
2453 return false;
2456 if (!init_target_chars ())
2457 return false;
2459 /* Only convert __{,v}snprintf_chk to {,v}snprintf if flag is 0
2460 or if format doesn't contain % chars or is "%s". */
2461 if (! integer_zerop (flag))
2463 fmt_str = c_getstr (fmt);
2464 if (fmt_str == NULL)
2465 return false;
2466 if (strchr (fmt_str, target_percent) != NULL
2467 && strcmp (fmt_str, target_percent_s))
2468 return false;
2471 /* If __builtin_{,v}snprintf_chk is used, assume {,v}snprintf is
2472 available. */
2473 fn = builtin_decl_explicit (fcode == BUILT_IN_VSNPRINTF_CHK
2474 ? BUILT_IN_VSNPRINTF : BUILT_IN_SNPRINTF);
2475 if (!fn)
2476 return false;
2478 /* Replace the called function and the first 5 argument by 3 retaining
2479 trailing varargs. */
2480 gimple_call_set_fndecl (stmt, fn);
2481 gimple_call_set_fntype (stmt, TREE_TYPE (fn));
2482 gimple_call_set_arg (stmt, 0, dest);
2483 gimple_call_set_arg (stmt, 1, len);
2484 gimple_call_set_arg (stmt, 2, fmt);
2485 for (unsigned i = 3; i < gimple_call_num_args (stmt) - 2; ++i)
2486 gimple_call_set_arg (stmt, i, gimple_call_arg (stmt, i + 2));
2487 gimple_set_num_ops (stmt, gimple_num_ops (stmt) - 2);
2488 fold_stmt (gsi);
2489 return true;
2492 /* Fold a call EXP to __{,v}sprintf_chk having NARGS passed as ARGS.
2493 Return NULL_TREE if a normal call should be emitted rather than
2494 expanding the function inline. FCODE is either BUILT_IN_SPRINTF_CHK
2495 or BUILT_IN_VSPRINTF_CHK. */
2497 static bool
2498 gimple_fold_builtin_sprintf_chk (gimple_stmt_iterator *gsi,
2499 enum built_in_function fcode)
2501 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2502 tree dest, size, len, fn, fmt, flag;
2503 const char *fmt_str;
2504 unsigned nargs = gimple_call_num_args (stmt);
2506 /* Verify the required arguments in the original call. */
2507 if (nargs < 4)
2508 return false;
2509 dest = gimple_call_arg (stmt, 0);
2510 flag = gimple_call_arg (stmt, 1);
2511 size = gimple_call_arg (stmt, 2);
2512 fmt = gimple_call_arg (stmt, 3);
2514 if (! tree_fits_uhwi_p (size))
2515 return false;
2517 len = NULL_TREE;
2519 if (!init_target_chars ())
2520 return false;
2522 /* Check whether the format is a literal string constant. */
2523 fmt_str = c_getstr (fmt);
2524 if (fmt_str != NULL)
2526 /* If the format doesn't contain % args or %%, we know the size. */
2527 if (strchr (fmt_str, target_percent) == 0)
2529 if (fcode != BUILT_IN_SPRINTF_CHK || nargs == 4)
2530 len = build_int_cstu (size_type_node, strlen (fmt_str));
2532 /* If the format is "%s" and first ... argument is a string literal,
2533 we know the size too. */
2534 else if (fcode == BUILT_IN_SPRINTF_CHK
2535 && strcmp (fmt_str, target_percent_s) == 0)
2537 tree arg;
2539 if (nargs == 5)
2541 arg = gimple_call_arg (stmt, 4);
2542 if (POINTER_TYPE_P (TREE_TYPE (arg)))
2544 len = c_strlen (arg, 1);
2545 if (! len || ! tree_fits_uhwi_p (len))
2546 len = NULL_TREE;
2552 if (! integer_all_onesp (size))
2554 if (! len || ! tree_int_cst_lt (len, size))
2555 return false;
2558 /* Only convert __{,v}sprintf_chk to {,v}sprintf if flag is 0
2559 or if format doesn't contain % chars or is "%s". */
2560 if (! integer_zerop (flag))
2562 if (fmt_str == NULL)
2563 return false;
2564 if (strchr (fmt_str, target_percent) != NULL
2565 && strcmp (fmt_str, target_percent_s))
2566 return false;
2569 /* If __builtin_{,v}sprintf_chk is used, assume {,v}sprintf is available. */
2570 fn = builtin_decl_explicit (fcode == BUILT_IN_VSPRINTF_CHK
2571 ? BUILT_IN_VSPRINTF : BUILT_IN_SPRINTF);
2572 if (!fn)
2573 return false;
2575 /* Replace the called function and the first 4 argument by 2 retaining
2576 trailing varargs. */
2577 gimple_call_set_fndecl (stmt, fn);
2578 gimple_call_set_fntype (stmt, TREE_TYPE (fn));
2579 gimple_call_set_arg (stmt, 0, dest);
2580 gimple_call_set_arg (stmt, 1, fmt);
2581 for (unsigned i = 2; i < gimple_call_num_args (stmt) - 2; ++i)
2582 gimple_call_set_arg (stmt, i, gimple_call_arg (stmt, i + 2));
2583 gimple_set_num_ops (stmt, gimple_num_ops (stmt) - 2);
2584 fold_stmt (gsi);
2585 return true;
2588 /* Simplify a call to the sprintf builtin with arguments DEST, FMT, and ORIG.
2589 ORIG may be null if this is a 2-argument call. We don't attempt to
2590 simplify calls with more than 3 arguments.
2592 Return NULL_TREE if no simplification was possible, otherwise return the
2593 simplified form of the call as a tree. If IGNORED is true, it means that
2594 the caller does not use the returned value of the function. */
2596 static bool
2597 gimple_fold_builtin_sprintf (gimple_stmt_iterator *gsi)
2599 gimple *stmt = gsi_stmt (*gsi);
2600 tree dest = gimple_call_arg (stmt, 0);
2601 tree fmt = gimple_call_arg (stmt, 1);
2602 tree orig = NULL_TREE;
2603 const char *fmt_str = NULL;
2605 /* Verify the required arguments in the original call. We deal with two
2606 types of sprintf() calls: 'sprintf (str, fmt)' and
2607 'sprintf (dest, "%s", orig)'. */
2608 if (gimple_call_num_args (stmt) > 3)
2609 return false;
2611 if (gimple_call_num_args (stmt) == 3)
2612 orig = gimple_call_arg (stmt, 2);
2614 /* Check whether the format is a literal string constant. */
2615 fmt_str = c_getstr (fmt);
2616 if (fmt_str == NULL)
2617 return false;
2619 if (!init_target_chars ())
2620 return false;
2622 /* If the format doesn't contain % args or %%, use strcpy. */
2623 if (strchr (fmt_str, target_percent) == NULL)
2625 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2627 if (!fn)
2628 return false;
2630 /* Don't optimize sprintf (buf, "abc", ptr++). */
2631 if (orig)
2632 return false;
2634 /* Convert sprintf (str, fmt) into strcpy (str, fmt) when
2635 'format' is known to contain no % formats. */
2636 gimple_seq stmts = NULL;
2637 gimple *repl = gimple_build_call (fn, 2, dest, fmt);
2638 gimple_seq_add_stmt_without_update (&stmts, repl);
2639 if (gimple_call_lhs (stmt))
2641 repl = gimple_build_assign (gimple_call_lhs (stmt),
2642 build_int_cst (integer_type_node,
2643 strlen (fmt_str)));
2644 gimple_seq_add_stmt_without_update (&stmts, repl);
2645 gsi_replace_with_seq_vops (gsi, stmts);
2646 /* gsi now points at the assignment to the lhs, get a
2647 stmt iterator to the memcpy call.
2648 ??? We can't use gsi_for_stmt as that doesn't work when the
2649 CFG isn't built yet. */
2650 gimple_stmt_iterator gsi2 = *gsi;
2651 gsi_prev (&gsi2);
2652 fold_stmt (&gsi2);
2654 else
2656 gsi_replace_with_seq_vops (gsi, stmts);
2657 fold_stmt (gsi);
2659 return true;
2662 /* If the format is "%s", use strcpy if the result isn't used. */
2663 else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
2665 tree fn;
2666 fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2668 if (!fn)
2669 return false;
2671 /* Don't crash on sprintf (str1, "%s"). */
2672 if (!orig)
2673 return false;
2675 tree orig_len = NULL_TREE;
2676 if (gimple_call_lhs (stmt))
2678 orig_len = get_maxval_strlen (orig, 0);
2679 if (!orig_len)
2680 return false;
2683 /* Convert sprintf (str1, "%s", str2) into strcpy (str1, str2). */
2684 gimple_seq stmts = NULL;
2685 gimple *repl = gimple_build_call (fn, 2, dest, orig);
2686 gimple_seq_add_stmt_without_update (&stmts, repl);
2687 if (gimple_call_lhs (stmt))
2689 if (!useless_type_conversion_p (integer_type_node,
2690 TREE_TYPE (orig_len)))
2691 orig_len = fold_convert (integer_type_node, orig_len);
2692 repl = gimple_build_assign (gimple_call_lhs (stmt), orig_len);
2693 gimple_seq_add_stmt_without_update (&stmts, repl);
2694 gsi_replace_with_seq_vops (gsi, stmts);
2695 /* gsi now points at the assignment to the lhs, get a
2696 stmt iterator to the memcpy call.
2697 ??? We can't use gsi_for_stmt as that doesn't work when the
2698 CFG isn't built yet. */
2699 gimple_stmt_iterator gsi2 = *gsi;
2700 gsi_prev (&gsi2);
2701 fold_stmt (&gsi2);
2703 else
2705 gsi_replace_with_seq_vops (gsi, stmts);
2706 fold_stmt (gsi);
2708 return true;
2710 return false;
2713 /* Simplify a call to the snprintf builtin with arguments DEST, DESTSIZE,
2714 FMT, and ORIG. ORIG may be null if this is a 3-argument call. We don't
2715 attempt to simplify calls with more than 4 arguments.
2717 Return NULL_TREE if no simplification was possible, otherwise return the
2718 simplified form of the call as a tree. If IGNORED is true, it means that
2719 the caller does not use the returned value of the function. */
2721 static bool
2722 gimple_fold_builtin_snprintf (gimple_stmt_iterator *gsi)
2724 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2725 tree dest = gimple_call_arg (stmt, 0);
2726 tree destsize = gimple_call_arg (stmt, 1);
2727 tree fmt = gimple_call_arg (stmt, 2);
2728 tree orig = NULL_TREE;
2729 const char *fmt_str = NULL;
2731 if (gimple_call_num_args (stmt) > 4)
2732 return false;
2734 if (gimple_call_num_args (stmt) == 4)
2735 orig = gimple_call_arg (stmt, 3);
2737 if (!tree_fits_uhwi_p (destsize))
2738 return false;
2739 unsigned HOST_WIDE_INT destlen = tree_to_uhwi (destsize);
2741 /* Check whether the format is a literal string constant. */
2742 fmt_str = c_getstr (fmt);
2743 if (fmt_str == NULL)
2744 return false;
2746 if (!init_target_chars ())
2747 return false;
2749 /* If the format doesn't contain % args or %%, use strcpy. */
2750 if (strchr (fmt_str, target_percent) == NULL)
2752 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2753 if (!fn)
2754 return false;
2756 /* Don't optimize snprintf (buf, 4, "abc", ptr++). */
2757 if (orig)
2758 return false;
2760 /* We could expand this as
2761 memcpy (str, fmt, cst - 1); str[cst - 1] = '\0';
2762 or to
2763 memcpy (str, fmt_with_nul_at_cstm1, cst);
2764 but in the former case that might increase code size
2765 and in the latter case grow .rodata section too much.
2766 So punt for now. */
2767 size_t len = strlen (fmt_str);
2768 if (len >= destlen)
2769 return false;
2771 gimple_seq stmts = NULL;
2772 gimple *repl = gimple_build_call (fn, 2, dest, fmt);
2773 gimple_seq_add_stmt_without_update (&stmts, repl);
2774 if (gimple_call_lhs (stmt))
2776 repl = gimple_build_assign (gimple_call_lhs (stmt),
2777 build_int_cst (integer_type_node, len));
2778 gimple_seq_add_stmt_without_update (&stmts, repl);
2779 gsi_replace_with_seq_vops (gsi, stmts);
2780 /* gsi now points at the assignment to the lhs, get a
2781 stmt iterator to the memcpy call.
2782 ??? We can't use gsi_for_stmt as that doesn't work when the
2783 CFG isn't built yet. */
2784 gimple_stmt_iterator gsi2 = *gsi;
2785 gsi_prev (&gsi2);
2786 fold_stmt (&gsi2);
2788 else
2790 gsi_replace_with_seq_vops (gsi, stmts);
2791 fold_stmt (gsi);
2793 return true;
2796 /* If the format is "%s", use strcpy if the result isn't used. */
2797 else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
2799 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2800 if (!fn)
2801 return false;
2803 /* Don't crash on snprintf (str1, cst, "%s"). */
2804 if (!orig)
2805 return false;
2807 tree orig_len = get_maxval_strlen (orig, 0);
2808 if (!orig_len || TREE_CODE (orig_len) != INTEGER_CST)
2809 return false;
2811 /* We could expand this as
2812 memcpy (str1, str2, cst - 1); str1[cst - 1] = '\0';
2813 or to
2814 memcpy (str1, str2_with_nul_at_cstm1, cst);
2815 but in the former case that might increase code size
2816 and in the latter case grow .rodata section too much.
2817 So punt for now. */
2818 if (compare_tree_int (orig_len, destlen) >= 0)
2819 return false;
2821 /* Convert snprintf (str1, cst, "%s", str2) into
2822 strcpy (str1, str2) if strlen (str2) < cst. */
2823 gimple_seq stmts = NULL;
2824 gimple *repl = gimple_build_call (fn, 2, dest, orig);
2825 gimple_seq_add_stmt_without_update (&stmts, repl);
2826 if (gimple_call_lhs (stmt))
2828 if (!useless_type_conversion_p (integer_type_node,
2829 TREE_TYPE (orig_len)))
2830 orig_len = fold_convert (integer_type_node, orig_len);
2831 repl = gimple_build_assign (gimple_call_lhs (stmt), orig_len);
2832 gimple_seq_add_stmt_without_update (&stmts, repl);
2833 gsi_replace_with_seq_vops (gsi, stmts);
2834 /* gsi now points at the assignment to the lhs, get a
2835 stmt iterator to the memcpy call.
2836 ??? We can't use gsi_for_stmt as that doesn't work when the
2837 CFG isn't built yet. */
2838 gimple_stmt_iterator gsi2 = *gsi;
2839 gsi_prev (&gsi2);
2840 fold_stmt (&gsi2);
2842 else
2844 gsi_replace_with_seq_vops (gsi, stmts);
2845 fold_stmt (gsi);
2847 return true;
2849 return false;
2852 /* Fold a call to the {,v}fprintf{,_unlocked} and __{,v}printf_chk builtins.
2853 FP, FMT, and ARG are the arguments to the call. We don't fold calls with
2854 more than 3 arguments, and ARG may be null in the 2-argument case.
2856 Return NULL_TREE if no simplification was possible, otherwise return the
2857 simplified form of the call as a tree. FCODE is the BUILT_IN_*
2858 code of the function to be simplified. */
2860 static bool
2861 gimple_fold_builtin_fprintf (gimple_stmt_iterator *gsi,
2862 tree fp, tree fmt, tree arg,
2863 enum built_in_function fcode)
2865 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2866 tree fn_fputc, fn_fputs;
2867 const char *fmt_str = NULL;
2869 /* If the return value is used, don't do the transformation. */
2870 if (gimple_call_lhs (stmt) != NULL_TREE)
2871 return false;
2873 /* Check whether the format is a literal string constant. */
2874 fmt_str = c_getstr (fmt);
2875 if (fmt_str == NULL)
2876 return false;
2878 if (fcode == BUILT_IN_FPRINTF_UNLOCKED)
2880 /* If we're using an unlocked function, assume the other
2881 unlocked functions exist explicitly. */
2882 fn_fputc = builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED);
2883 fn_fputs = builtin_decl_explicit (BUILT_IN_FPUTS_UNLOCKED);
2885 else
2887 fn_fputc = builtin_decl_implicit (BUILT_IN_FPUTC);
2888 fn_fputs = builtin_decl_implicit (BUILT_IN_FPUTS);
2891 if (!init_target_chars ())
2892 return false;
2894 /* If the format doesn't contain % args or %%, use strcpy. */
2895 if (strchr (fmt_str, target_percent) == NULL)
2897 if (fcode != BUILT_IN_VFPRINTF && fcode != BUILT_IN_VFPRINTF_CHK
2898 && arg)
2899 return false;
2901 /* If the format specifier was "", fprintf does nothing. */
2902 if (fmt_str[0] == '\0')
2904 replace_call_with_value (gsi, NULL_TREE);
2905 return true;
2908 /* When "string" doesn't contain %, replace all cases of
2909 fprintf (fp, string) with fputs (string, fp). The fputs
2910 builtin will take care of special cases like length == 1. */
2911 if (fn_fputs)
2913 gcall *repl = gimple_build_call (fn_fputs, 2, fmt, fp);
2914 replace_call_with_call_and_fold (gsi, repl);
2915 return true;
2919 /* The other optimizations can be done only on the non-va_list variants. */
2920 else if (fcode == BUILT_IN_VFPRINTF || fcode == BUILT_IN_VFPRINTF_CHK)
2921 return false;
2923 /* If the format specifier was "%s", call __builtin_fputs (arg, fp). */
2924 else if (strcmp (fmt_str, target_percent_s) == 0)
2926 if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
2927 return false;
2928 if (fn_fputs)
2930 gcall *repl = gimple_build_call (fn_fputs, 2, arg, fp);
2931 replace_call_with_call_and_fold (gsi, repl);
2932 return true;
2936 /* If the format specifier was "%c", call __builtin_fputc (arg, fp). */
2937 else if (strcmp (fmt_str, target_percent_c) == 0)
2939 if (!arg
2940 || ! useless_type_conversion_p (integer_type_node, TREE_TYPE (arg)))
2941 return false;
2942 if (fn_fputc)
2944 gcall *repl = gimple_build_call (fn_fputc, 2, arg, fp);
2945 replace_call_with_call_and_fold (gsi, repl);
2946 return true;
2950 return false;
2953 /* Fold a call to the {,v}printf{,_unlocked} and __{,v}printf_chk builtins.
2954 FMT and ARG are the arguments to the call; we don't fold cases with
2955 more than 2 arguments, and ARG may be null if this is a 1-argument case.
2957 Return NULL_TREE if no simplification was possible, otherwise return the
2958 simplified form of the call as a tree. FCODE is the BUILT_IN_*
2959 code of the function to be simplified. */
2961 static bool
2962 gimple_fold_builtin_printf (gimple_stmt_iterator *gsi, tree fmt,
2963 tree arg, enum built_in_function fcode)
2965 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2966 tree fn_putchar, fn_puts, newarg;
2967 const char *fmt_str = NULL;
2969 /* If the return value is used, don't do the transformation. */
2970 if (gimple_call_lhs (stmt) != NULL_TREE)
2971 return false;
2973 /* Check whether the format is a literal string constant. */
2974 fmt_str = c_getstr (fmt);
2975 if (fmt_str == NULL)
2976 return false;
2978 if (fcode == BUILT_IN_PRINTF_UNLOCKED)
2980 /* If we're using an unlocked function, assume the other
2981 unlocked functions exist explicitly. */
2982 fn_putchar = builtin_decl_explicit (BUILT_IN_PUTCHAR_UNLOCKED);
2983 fn_puts = builtin_decl_explicit (BUILT_IN_PUTS_UNLOCKED);
2985 else
2987 fn_putchar = builtin_decl_implicit (BUILT_IN_PUTCHAR);
2988 fn_puts = builtin_decl_implicit (BUILT_IN_PUTS);
2991 if (!init_target_chars ())
2992 return false;
2994 if (strcmp (fmt_str, target_percent_s) == 0
2995 || strchr (fmt_str, target_percent) == NULL)
2997 const char *str;
2999 if (strcmp (fmt_str, target_percent_s) == 0)
3001 if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
3002 return false;
3004 if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
3005 return false;
3007 str = c_getstr (arg);
3008 if (str == NULL)
3009 return false;
3011 else
3013 /* The format specifier doesn't contain any '%' characters. */
3014 if (fcode != BUILT_IN_VPRINTF && fcode != BUILT_IN_VPRINTF_CHK
3015 && arg)
3016 return false;
3017 str = fmt_str;
3020 /* If the string was "", printf does nothing. */
3021 if (str[0] == '\0')
3023 replace_call_with_value (gsi, NULL_TREE);
3024 return true;
3027 /* If the string has length of 1, call putchar. */
3028 if (str[1] == '\0')
3030 /* Given printf("c"), (where c is any one character,)
3031 convert "c"[0] to an int and pass that to the replacement
3032 function. */
3033 newarg = build_int_cst (integer_type_node, str[0]);
3034 if (fn_putchar)
3036 gcall *repl = gimple_build_call (fn_putchar, 1, newarg);
3037 replace_call_with_call_and_fold (gsi, repl);
3038 return true;
3041 else
3043 /* If the string was "string\n", call puts("string"). */
3044 size_t len = strlen (str);
3045 if ((unsigned char)str[len - 1] == target_newline
3046 && (size_t) (int) len == len
3047 && (int) len > 0)
3049 char *newstr;
3050 tree offset_node, string_cst;
3052 /* Create a NUL-terminated string that's one char shorter
3053 than the original, stripping off the trailing '\n'. */
3054 newarg = build_string_literal (len, str);
3055 string_cst = string_constant (newarg, &offset_node);
3056 gcc_checking_assert (string_cst
3057 && (TREE_STRING_LENGTH (string_cst)
3058 == (int) len)
3059 && integer_zerop (offset_node)
3060 && (unsigned char)
3061 TREE_STRING_POINTER (string_cst)[len - 1]
3062 == target_newline);
3063 /* build_string_literal creates a new STRING_CST,
3064 modify it in place to avoid double copying. */
3065 newstr = CONST_CAST (char *, TREE_STRING_POINTER (string_cst));
3066 newstr[len - 1] = '\0';
3067 if (fn_puts)
3069 gcall *repl = gimple_build_call (fn_puts, 1, newarg);
3070 replace_call_with_call_and_fold (gsi, repl);
3071 return true;
3074 else
3075 /* We'd like to arrange to call fputs(string,stdout) here,
3076 but we need stdout and don't have a way to get it yet. */
3077 return false;
3081 /* The other optimizations can be done only on the non-va_list variants. */
3082 else if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
3083 return false;
3085 /* If the format specifier was "%s\n", call __builtin_puts(arg). */
3086 else if (strcmp (fmt_str, target_percent_s_newline) == 0)
3088 if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
3089 return false;
3090 if (fn_puts)
3092 gcall *repl = gimple_build_call (fn_puts, 1, arg);
3093 replace_call_with_call_and_fold (gsi, repl);
3094 return true;
3098 /* If the format specifier was "%c", call __builtin_putchar(arg). */
3099 else if (strcmp (fmt_str, target_percent_c) == 0)
3101 if (!arg || ! useless_type_conversion_p (integer_type_node,
3102 TREE_TYPE (arg)))
3103 return false;
3104 if (fn_putchar)
3106 gcall *repl = gimple_build_call (fn_putchar, 1, arg);
3107 replace_call_with_call_and_fold (gsi, repl);
3108 return true;
3112 return false;
3117 /* Fold a call to __builtin_strlen with known length LEN. */
3119 static bool
3120 gimple_fold_builtin_strlen (gimple_stmt_iterator *gsi)
3122 gimple *stmt = gsi_stmt (*gsi);
3123 tree len = get_maxval_strlen (gimple_call_arg (stmt, 0), 0);
3124 if (!len)
3125 return false;
3126 len = force_gimple_operand_gsi (gsi, len, true, NULL, true, GSI_SAME_STMT);
3127 replace_call_with_value (gsi, len);
3128 return true;
3131 /* Fold a call to __builtin_acc_on_device. */
3133 static bool
3134 gimple_fold_builtin_acc_on_device (gimple_stmt_iterator *gsi, tree arg0)
3136 /* Defer folding until we know which compiler we're in. */
3137 if (symtab->state != EXPANSION)
3138 return false;
3140 unsigned val_host = GOMP_DEVICE_HOST;
3141 unsigned val_dev = GOMP_DEVICE_NONE;
3143 #ifdef ACCEL_COMPILER
3144 val_host = GOMP_DEVICE_NOT_HOST;
3145 val_dev = ACCEL_COMPILER_acc_device;
3146 #endif
3148 location_t loc = gimple_location (gsi_stmt (*gsi));
3150 tree host_eq = make_ssa_name (boolean_type_node);
3151 gimple *host_ass = gimple_build_assign
3152 (host_eq, EQ_EXPR, arg0, build_int_cst (TREE_TYPE (arg0), val_host));
3153 gimple_set_location (host_ass, loc);
3154 gsi_insert_before (gsi, host_ass, GSI_SAME_STMT);
3156 tree dev_eq = make_ssa_name (boolean_type_node);
3157 gimple *dev_ass = gimple_build_assign
3158 (dev_eq, EQ_EXPR, arg0, build_int_cst (TREE_TYPE (arg0), val_dev));
3159 gimple_set_location (dev_ass, loc);
3160 gsi_insert_before (gsi, dev_ass, GSI_SAME_STMT);
3162 tree result = make_ssa_name (boolean_type_node);
3163 gimple *result_ass = gimple_build_assign
3164 (result, BIT_IOR_EXPR, host_eq, dev_eq);
3165 gimple_set_location (result_ass, loc);
3166 gsi_insert_before (gsi, result_ass, GSI_SAME_STMT);
3168 replace_call_with_value (gsi, result);
3170 return true;
3173 /* Fold the non-target builtin at *GSI and return whether any simplification
3174 was made. */
3176 static bool
3177 gimple_fold_builtin (gimple_stmt_iterator *gsi)
3179 gcall *stmt = as_a <gcall *>(gsi_stmt (*gsi));
3180 tree callee = gimple_call_fndecl (stmt);
3182 /* Give up for always_inline inline builtins until they are
3183 inlined. */
3184 if (avoid_folding_inline_builtin (callee))
3185 return false;
3187 unsigned n = gimple_call_num_args (stmt);
3188 enum built_in_function fcode = DECL_FUNCTION_CODE (callee);
3189 switch (fcode)
3191 case BUILT_IN_BZERO:
3192 return gimple_fold_builtin_memset (gsi, integer_zero_node,
3193 gimple_call_arg (stmt, 1));
3194 case BUILT_IN_MEMSET:
3195 return gimple_fold_builtin_memset (gsi,
3196 gimple_call_arg (stmt, 1),
3197 gimple_call_arg (stmt, 2));
3198 case BUILT_IN_BCOPY:
3199 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 1),
3200 gimple_call_arg (stmt, 0), 3);
3201 case BUILT_IN_MEMCPY:
3202 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
3203 gimple_call_arg (stmt, 1), 0);
3204 case BUILT_IN_MEMPCPY:
3205 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
3206 gimple_call_arg (stmt, 1), 1);
3207 case BUILT_IN_MEMMOVE:
3208 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
3209 gimple_call_arg (stmt, 1), 3);
3210 case BUILT_IN_SPRINTF_CHK:
3211 case BUILT_IN_VSPRINTF_CHK:
3212 return gimple_fold_builtin_sprintf_chk (gsi, fcode);
3213 case BUILT_IN_STRCAT_CHK:
3214 return gimple_fold_builtin_strcat_chk (gsi);
3215 case BUILT_IN_STRNCAT_CHK:
3216 return gimple_fold_builtin_strncat_chk (gsi);
3217 case BUILT_IN_STRLEN:
3218 return gimple_fold_builtin_strlen (gsi);
3219 case BUILT_IN_STRCPY:
3220 return gimple_fold_builtin_strcpy (gsi,
3221 gimple_call_arg (stmt, 0),
3222 gimple_call_arg (stmt, 1));
3223 case BUILT_IN_STRNCPY:
3224 return gimple_fold_builtin_strncpy (gsi,
3225 gimple_call_arg (stmt, 0),
3226 gimple_call_arg (stmt, 1),
3227 gimple_call_arg (stmt, 2));
3228 case BUILT_IN_STRCAT:
3229 return gimple_fold_builtin_strcat (gsi, gimple_call_arg (stmt, 0),
3230 gimple_call_arg (stmt, 1));
3231 case BUILT_IN_STRNCAT:
3232 return gimple_fold_builtin_strncat (gsi);
3233 case BUILT_IN_INDEX:
3234 case BUILT_IN_STRCHR:
3235 return gimple_fold_builtin_strchr (gsi, false);
3236 case BUILT_IN_RINDEX:
3237 case BUILT_IN_STRRCHR:
3238 return gimple_fold_builtin_strchr (gsi, true);
3239 case BUILT_IN_STRCMP:
3240 case BUILT_IN_STRCASECMP:
3241 case BUILT_IN_STRNCMP:
3242 case BUILT_IN_STRNCASECMP:
3243 return gimple_fold_builtin_string_compare (gsi);
3244 case BUILT_IN_MEMCHR:
3245 return gimple_fold_builtin_memchr (gsi);
3246 case BUILT_IN_FPUTS:
3247 return gimple_fold_builtin_fputs (gsi, gimple_call_arg (stmt, 0),
3248 gimple_call_arg (stmt, 1), false);
3249 case BUILT_IN_FPUTS_UNLOCKED:
3250 return gimple_fold_builtin_fputs (gsi, gimple_call_arg (stmt, 0),
3251 gimple_call_arg (stmt, 1), true);
3252 case BUILT_IN_MEMCPY_CHK:
3253 case BUILT_IN_MEMPCPY_CHK:
3254 case BUILT_IN_MEMMOVE_CHK:
3255 case BUILT_IN_MEMSET_CHK:
3256 return gimple_fold_builtin_memory_chk (gsi,
3257 gimple_call_arg (stmt, 0),
3258 gimple_call_arg (stmt, 1),
3259 gimple_call_arg (stmt, 2),
3260 gimple_call_arg (stmt, 3),
3261 fcode);
3262 case BUILT_IN_STPCPY:
3263 return gimple_fold_builtin_stpcpy (gsi);
3264 case BUILT_IN_STRCPY_CHK:
3265 case BUILT_IN_STPCPY_CHK:
3266 return gimple_fold_builtin_stxcpy_chk (gsi,
3267 gimple_call_arg (stmt, 0),
3268 gimple_call_arg (stmt, 1),
3269 gimple_call_arg (stmt, 2),
3270 fcode);
3271 case BUILT_IN_STRNCPY_CHK:
3272 case BUILT_IN_STPNCPY_CHK:
3273 return gimple_fold_builtin_stxncpy_chk (gsi,
3274 gimple_call_arg (stmt, 0),
3275 gimple_call_arg (stmt, 1),
3276 gimple_call_arg (stmt, 2),
3277 gimple_call_arg (stmt, 3),
3278 fcode);
3279 case BUILT_IN_SNPRINTF_CHK:
3280 case BUILT_IN_VSNPRINTF_CHK:
3281 return gimple_fold_builtin_snprintf_chk (gsi, fcode);
3282 case BUILT_IN_SNPRINTF:
3283 return gimple_fold_builtin_snprintf (gsi);
3284 case BUILT_IN_SPRINTF:
3285 return gimple_fold_builtin_sprintf (gsi);
3286 case BUILT_IN_FPRINTF:
3287 case BUILT_IN_FPRINTF_UNLOCKED:
3288 case BUILT_IN_VFPRINTF:
3289 if (n == 2 || n == 3)
3290 return gimple_fold_builtin_fprintf (gsi,
3291 gimple_call_arg (stmt, 0),
3292 gimple_call_arg (stmt, 1),
3293 n == 3
3294 ? gimple_call_arg (stmt, 2)
3295 : NULL_TREE,
3296 fcode);
3297 break;
3298 case BUILT_IN_FPRINTF_CHK:
3299 case BUILT_IN_VFPRINTF_CHK:
3300 if (n == 3 || n == 4)
3301 return gimple_fold_builtin_fprintf (gsi,
3302 gimple_call_arg (stmt, 0),
3303 gimple_call_arg (stmt, 2),
3304 n == 4
3305 ? gimple_call_arg (stmt, 3)
3306 : NULL_TREE,
3307 fcode);
3308 break;
3309 case BUILT_IN_PRINTF:
3310 case BUILT_IN_PRINTF_UNLOCKED:
3311 case BUILT_IN_VPRINTF:
3312 if (n == 1 || n == 2)
3313 return gimple_fold_builtin_printf (gsi, gimple_call_arg (stmt, 0),
3314 n == 2
3315 ? gimple_call_arg (stmt, 1)
3316 : NULL_TREE, fcode);
3317 break;
3318 case BUILT_IN_PRINTF_CHK:
3319 case BUILT_IN_VPRINTF_CHK:
3320 if (n == 2 || n == 3)
3321 return gimple_fold_builtin_printf (gsi, gimple_call_arg (stmt, 1),
3322 n == 3
3323 ? gimple_call_arg (stmt, 2)
3324 : NULL_TREE, fcode);
3325 break;
3326 case BUILT_IN_ACC_ON_DEVICE:
3327 return gimple_fold_builtin_acc_on_device (gsi,
3328 gimple_call_arg (stmt, 0));
3329 default:;
3332 /* Try the generic builtin folder. */
3333 bool ignore = (gimple_call_lhs (stmt) == NULL);
3334 tree result = fold_call_stmt (stmt, ignore);
3335 if (result)
3337 if (ignore)
3338 STRIP_NOPS (result);
3339 else
3340 result = fold_convert (gimple_call_return_type (stmt), result);
3341 if (!update_call_from_tree (gsi, result))
3342 gimplify_and_update_call_from_tree (gsi, result);
3343 return true;
3346 return false;
3349 /* Transform IFN_GOACC_DIM_SIZE and IFN_GOACC_DIM_POS internal
3350 function calls to constants, where possible. */
3352 static tree
3353 fold_internal_goacc_dim (const gimple *call)
3355 int axis = get_oacc_ifn_dim_arg (call);
3356 int size = get_oacc_fn_dim_size (current_function_decl, axis);
3357 bool is_pos = gimple_call_internal_fn (call) == IFN_GOACC_DIM_POS;
3358 tree result = NULL_TREE;
3360 /* If the size is 1, or we only want the size and it is not dynamic,
3361 we know the answer. */
3362 if (size == 1 || (!is_pos && size))
3364 tree type = TREE_TYPE (gimple_call_lhs (call));
3365 result = build_int_cst (type, size - is_pos);
3368 return result;
3371 /* Return true if stmt is __atomic_compare_exchange_N call which is suitable
3372 for conversion into ATOMIC_COMPARE_EXCHANGE if the second argument is
3373 &var where var is only addressable because of such calls. */
3375 bool
3376 optimize_atomic_compare_exchange_p (gimple *stmt)
3378 if (gimple_call_num_args (stmt) != 6
3379 || !flag_inline_atomics
3380 || !optimize
3381 || (flag_sanitize & (SANITIZE_THREAD | SANITIZE_ADDRESS)) != 0
3382 || !gimple_call_builtin_p (stmt, BUILT_IN_NORMAL)
3383 || !gimple_vdef (stmt)
3384 || !gimple_vuse (stmt))
3385 return false;
3387 tree fndecl = gimple_call_fndecl (stmt);
3388 switch (DECL_FUNCTION_CODE (fndecl))
3390 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1:
3391 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2:
3392 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4:
3393 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8:
3394 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16:
3395 break;
3396 default:
3397 return false;
3400 tree expected = gimple_call_arg (stmt, 1);
3401 if (TREE_CODE (expected) != ADDR_EXPR
3402 || !SSA_VAR_P (TREE_OPERAND (expected, 0)))
3403 return false;
3405 tree etype = TREE_TYPE (TREE_OPERAND (expected, 0));
3406 if (!is_gimple_reg_type (etype)
3407 || !auto_var_in_fn_p (TREE_OPERAND (expected, 0), current_function_decl)
3408 || TREE_THIS_VOLATILE (etype)
3409 || VECTOR_TYPE_P (etype)
3410 || TREE_CODE (etype) == COMPLEX_TYPE
3411 /* Don't optimize floating point expected vars, VIEW_CONVERT_EXPRs
3412 might not preserve all the bits. See PR71716. */
3413 || SCALAR_FLOAT_TYPE_P (etype)
3414 || TYPE_PRECISION (etype) != GET_MODE_BITSIZE (TYPE_MODE (etype)))
3415 return false;
3417 tree weak = gimple_call_arg (stmt, 3);
3418 if (!integer_zerop (weak) && !integer_onep (weak))
3419 return false;
3421 tree parmt = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
3422 tree itype = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (parmt)));
3423 machine_mode mode = TYPE_MODE (itype);
3425 if (direct_optab_handler (atomic_compare_and_swap_optab, mode)
3426 == CODE_FOR_nothing
3427 && optab_handler (sync_compare_and_swap_optab, mode) == CODE_FOR_nothing)
3428 return false;
3430 if (int_size_in_bytes (etype) != GET_MODE_SIZE (mode))
3431 return false;
3433 return true;
3436 /* Fold
3437 r = __atomic_compare_exchange_N (p, &e, d, w, s, f);
3438 into
3439 _Complex uintN_t t = ATOMIC_COMPARE_EXCHANGE (p, e, d, w * 256 + N, s, f);
3440 i = IMAGPART_EXPR <t>;
3441 r = (_Bool) i;
3442 e = REALPART_EXPR <t>; */
3444 void
3445 fold_builtin_atomic_compare_exchange (gimple_stmt_iterator *gsi)
3447 gimple *stmt = gsi_stmt (*gsi);
3448 tree fndecl = gimple_call_fndecl (stmt);
3449 tree parmt = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
3450 tree itype = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (parmt)));
3451 tree ctype = build_complex_type (itype);
3452 tree expected = TREE_OPERAND (gimple_call_arg (stmt, 1), 0);
3453 gimple *g = gimple_build_assign (make_ssa_name (TREE_TYPE (expected)),
3454 expected);
3455 gsi_insert_before (gsi, g, GSI_SAME_STMT);
3456 gimple_stmt_iterator gsiret = gsi_for_stmt (g);
3457 if (!useless_type_conversion_p (itype, TREE_TYPE (expected)))
3459 g = gimple_build_assign (make_ssa_name (itype), VIEW_CONVERT_EXPR,
3460 build1 (VIEW_CONVERT_EXPR, itype,
3461 gimple_assign_lhs (g)));
3462 gsi_insert_before (gsi, g, GSI_SAME_STMT);
3464 int flag = (integer_onep (gimple_call_arg (stmt, 3)) ? 256 : 0)
3465 + int_size_in_bytes (itype);
3466 g = gimple_build_call_internal (IFN_ATOMIC_COMPARE_EXCHANGE, 6,
3467 gimple_call_arg (stmt, 0),
3468 gimple_assign_lhs (g),
3469 gimple_call_arg (stmt, 2),
3470 build_int_cst (integer_type_node, flag),
3471 gimple_call_arg (stmt, 4),
3472 gimple_call_arg (stmt, 5));
3473 tree lhs = make_ssa_name (ctype);
3474 gimple_call_set_lhs (g, lhs);
3475 gimple_set_vdef (g, gimple_vdef (stmt));
3476 gimple_set_vuse (g, gimple_vuse (stmt));
3477 SSA_NAME_DEF_STMT (gimple_vdef (g)) = g;
3478 if (gimple_call_lhs (stmt))
3480 gsi_insert_before (gsi, g, GSI_SAME_STMT);
3481 g = gimple_build_assign (make_ssa_name (itype), IMAGPART_EXPR,
3482 build1 (IMAGPART_EXPR, itype, lhs));
3483 gsi_insert_before (gsi, g, GSI_SAME_STMT);
3484 g = gimple_build_assign (gimple_call_lhs (stmt), NOP_EXPR,
3485 gimple_assign_lhs (g));
3487 gsi_replace (gsi, g, true);
3488 g = gimple_build_assign (make_ssa_name (itype), REALPART_EXPR,
3489 build1 (REALPART_EXPR, itype, lhs));
3490 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3491 if (!useless_type_conversion_p (TREE_TYPE (expected), itype))
3493 g = gimple_build_assign (make_ssa_name (TREE_TYPE (expected)),
3494 VIEW_CONVERT_EXPR,
3495 build1 (VIEW_CONVERT_EXPR, TREE_TYPE (expected),
3496 gimple_assign_lhs (g)));
3497 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3499 g = gimple_build_assign (expected, SSA_NAME, gimple_assign_lhs (g));
3500 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3501 *gsi = gsiret;
3504 /* Return true if ARG0 CODE ARG1 in infinite signed precision operation
3505 doesn't fit into TYPE. The test for overflow should be regardless of
3506 -fwrapv, and even for unsigned types. */
3508 bool
3509 arith_overflowed_p (enum tree_code code, const_tree type,
3510 const_tree arg0, const_tree arg1)
3512 typedef FIXED_WIDE_INT (WIDE_INT_MAX_PRECISION * 2) widest2_int;
3513 typedef generic_wide_int <wi::extended_tree <WIDE_INT_MAX_PRECISION * 2> >
3514 widest2_int_cst;
3515 widest2_int warg0 = widest2_int_cst (arg0);
3516 widest2_int warg1 = widest2_int_cst (arg1);
3517 widest2_int wres;
3518 switch (code)
3520 case PLUS_EXPR: wres = wi::add (warg0, warg1); break;
3521 case MINUS_EXPR: wres = wi::sub (warg0, warg1); break;
3522 case MULT_EXPR: wres = wi::mul (warg0, warg1); break;
3523 default: gcc_unreachable ();
3525 signop sign = TYPE_SIGN (type);
3526 if (sign == UNSIGNED && wi::neg_p (wres))
3527 return true;
3528 return wi::min_precision (wres, sign) > TYPE_PRECISION (type);
3531 /* Attempt to fold a call statement referenced by the statement iterator GSI.
3532 The statement may be replaced by another statement, e.g., if the call
3533 simplifies to a constant value. Return true if any changes were made.
3534 It is assumed that the operands have been previously folded. */
3536 static bool
3537 gimple_fold_call (gimple_stmt_iterator *gsi, bool inplace)
3539 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3540 tree callee;
3541 bool changed = false;
3542 unsigned i;
3544 /* Fold *& in call arguments. */
3545 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3546 if (REFERENCE_CLASS_P (gimple_call_arg (stmt, i)))
3548 tree tmp = maybe_fold_reference (gimple_call_arg (stmt, i), false);
3549 if (tmp)
3551 gimple_call_set_arg (stmt, i, tmp);
3552 changed = true;
3556 /* Check for virtual calls that became direct calls. */
3557 callee = gimple_call_fn (stmt);
3558 if (callee && TREE_CODE (callee) == OBJ_TYPE_REF)
3560 if (gimple_call_addr_fndecl (OBJ_TYPE_REF_EXPR (callee)) != NULL_TREE)
3562 if (dump_file && virtual_method_call_p (callee)
3563 && !possible_polymorphic_call_target_p
3564 (callee, stmt, cgraph_node::get (gimple_call_addr_fndecl
3565 (OBJ_TYPE_REF_EXPR (callee)))))
3567 fprintf (dump_file,
3568 "Type inheritance inconsistent devirtualization of ");
3569 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
3570 fprintf (dump_file, " to ");
3571 print_generic_expr (dump_file, callee, TDF_SLIM);
3572 fprintf (dump_file, "\n");
3575 gimple_call_set_fn (stmt, OBJ_TYPE_REF_EXPR (callee));
3576 changed = true;
3578 else if (flag_devirtualize && !inplace && virtual_method_call_p (callee))
3580 bool final;
3581 vec <cgraph_node *>targets
3582 = possible_polymorphic_call_targets (callee, stmt, &final);
3583 if (final && targets.length () <= 1 && dbg_cnt (devirt))
3585 tree lhs = gimple_call_lhs (stmt);
3586 if (dump_enabled_p ())
3588 location_t loc = gimple_location_safe (stmt);
3589 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, loc,
3590 "folding virtual function call to %s\n",
3591 targets.length () == 1
3592 ? targets[0]->name ()
3593 : "__builtin_unreachable");
3595 if (targets.length () == 1)
3597 tree fndecl = targets[0]->decl;
3598 gimple_call_set_fndecl (stmt, fndecl);
3599 changed = true;
3600 /* If changing the call to __cxa_pure_virtual
3601 or similar noreturn function, adjust gimple_call_fntype
3602 too. */
3603 if (gimple_call_noreturn_p (stmt)
3604 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (fndecl)))
3605 && TYPE_ARG_TYPES (TREE_TYPE (fndecl))
3606 && (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (fndecl)))
3607 == void_type_node))
3608 gimple_call_set_fntype (stmt, TREE_TYPE (fndecl));
3609 /* If the call becomes noreturn, remove the lhs. */
3610 if (lhs
3611 && gimple_call_noreturn_p (stmt)
3612 && (VOID_TYPE_P (TREE_TYPE (gimple_call_fntype (stmt)))
3613 || should_remove_lhs_p (lhs)))
3615 if (TREE_CODE (lhs) == SSA_NAME)
3617 tree var = create_tmp_var (TREE_TYPE (lhs));
3618 tree def = get_or_create_ssa_default_def (cfun, var);
3619 gimple *new_stmt = gimple_build_assign (lhs, def);
3620 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
3622 gimple_call_set_lhs (stmt, NULL_TREE);
3624 maybe_remove_unused_call_args (cfun, stmt);
3626 else
3628 tree fndecl = builtin_decl_implicit (BUILT_IN_UNREACHABLE);
3629 gimple *new_stmt = gimple_build_call (fndecl, 0);
3630 gimple_set_location (new_stmt, gimple_location (stmt));
3631 if (lhs && TREE_CODE (lhs) == SSA_NAME)
3633 tree var = create_tmp_var (TREE_TYPE (lhs));
3634 tree def = get_or_create_ssa_default_def (cfun, var);
3636 /* To satisfy condition for
3637 cgraph_update_edges_for_call_stmt_node,
3638 we need to preserve GIMPLE_CALL statement
3639 at position of GSI iterator. */
3640 update_call_from_tree (gsi, def);
3641 gsi_insert_before (gsi, new_stmt, GSI_NEW_STMT);
3643 else
3645 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
3646 gimple_set_vdef (new_stmt, gimple_vdef (stmt));
3647 gsi_replace (gsi, new_stmt, false);
3649 return true;
3655 /* Check for indirect calls that became direct calls, and then
3656 no longer require a static chain. */
3657 if (gimple_call_chain (stmt))
3659 tree fn = gimple_call_fndecl (stmt);
3660 if (fn && !DECL_STATIC_CHAIN (fn))
3662 gimple_call_set_chain (stmt, NULL);
3663 changed = true;
3665 else
3667 tree tmp = maybe_fold_reference (gimple_call_chain (stmt), false);
3668 if (tmp)
3670 gimple_call_set_chain (stmt, tmp);
3671 changed = true;
3676 if (inplace)
3677 return changed;
3679 /* Check for builtins that CCP can handle using information not
3680 available in the generic fold routines. */
3681 if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
3683 if (gimple_fold_builtin (gsi))
3684 changed = true;
3686 else if (gimple_call_builtin_p (stmt, BUILT_IN_MD))
3688 changed |= targetm.gimple_fold_builtin (gsi);
3690 else if (gimple_call_internal_p (stmt))
3692 enum tree_code subcode = ERROR_MARK;
3693 tree result = NULL_TREE;
3694 bool cplx_result = false;
3695 tree overflow = NULL_TREE;
3696 switch (gimple_call_internal_fn (stmt))
3698 case IFN_BUILTIN_EXPECT:
3699 result = fold_builtin_expect (gimple_location (stmt),
3700 gimple_call_arg (stmt, 0),
3701 gimple_call_arg (stmt, 1),
3702 gimple_call_arg (stmt, 2));
3703 break;
3704 case IFN_UBSAN_OBJECT_SIZE:
3705 if (integer_all_onesp (gimple_call_arg (stmt, 2))
3706 || (TREE_CODE (gimple_call_arg (stmt, 1)) == INTEGER_CST
3707 && TREE_CODE (gimple_call_arg (stmt, 2)) == INTEGER_CST
3708 && tree_int_cst_le (gimple_call_arg (stmt, 1),
3709 gimple_call_arg (stmt, 2))))
3711 gsi_replace (gsi, gimple_build_nop (), false);
3712 unlink_stmt_vdef (stmt);
3713 release_defs (stmt);
3714 return true;
3716 break;
3717 case IFN_GOACC_DIM_SIZE:
3718 case IFN_GOACC_DIM_POS:
3719 result = fold_internal_goacc_dim (stmt);
3720 break;
3721 case IFN_UBSAN_CHECK_ADD:
3722 subcode = PLUS_EXPR;
3723 break;
3724 case IFN_UBSAN_CHECK_SUB:
3725 subcode = MINUS_EXPR;
3726 break;
3727 case IFN_UBSAN_CHECK_MUL:
3728 subcode = MULT_EXPR;
3729 break;
3730 case IFN_ADD_OVERFLOW:
3731 subcode = PLUS_EXPR;
3732 cplx_result = true;
3733 break;
3734 case IFN_SUB_OVERFLOW:
3735 subcode = MINUS_EXPR;
3736 cplx_result = true;
3737 break;
3738 case IFN_MUL_OVERFLOW:
3739 subcode = MULT_EXPR;
3740 cplx_result = true;
3741 break;
3742 default:
3743 break;
3745 if (subcode != ERROR_MARK)
3747 tree arg0 = gimple_call_arg (stmt, 0);
3748 tree arg1 = gimple_call_arg (stmt, 1);
3749 tree type = TREE_TYPE (arg0);
3750 if (cplx_result)
3752 tree lhs = gimple_call_lhs (stmt);
3753 if (lhs == NULL_TREE)
3754 type = NULL_TREE;
3755 else
3756 type = TREE_TYPE (TREE_TYPE (lhs));
3758 if (type == NULL_TREE)
3760 /* x = y + 0; x = y - 0; x = y * 0; */
3761 else if (integer_zerop (arg1))
3762 result = subcode == MULT_EXPR ? integer_zero_node : arg0;
3763 /* x = 0 + y; x = 0 * y; */
3764 else if (subcode != MINUS_EXPR && integer_zerop (arg0))
3765 result = subcode == MULT_EXPR ? integer_zero_node : arg1;
3766 /* x = y - y; */
3767 else if (subcode == MINUS_EXPR && operand_equal_p (arg0, arg1, 0))
3768 result = integer_zero_node;
3769 /* x = y * 1; x = 1 * y; */
3770 else if (subcode == MULT_EXPR && integer_onep (arg1))
3771 result = arg0;
3772 else if (subcode == MULT_EXPR && integer_onep (arg0))
3773 result = arg1;
3774 else if (TREE_CODE (arg0) == INTEGER_CST
3775 && TREE_CODE (arg1) == INTEGER_CST)
3777 if (cplx_result)
3778 result = int_const_binop (subcode, fold_convert (type, arg0),
3779 fold_convert (type, arg1));
3780 else
3781 result = int_const_binop (subcode, arg0, arg1);
3782 if (result && arith_overflowed_p (subcode, type, arg0, arg1))
3784 if (cplx_result)
3785 overflow = build_one_cst (type);
3786 else
3787 result = NULL_TREE;
3790 if (result)
3792 if (result == integer_zero_node)
3793 result = build_zero_cst (type);
3794 else if (cplx_result && TREE_TYPE (result) != type)
3796 if (TREE_CODE (result) == INTEGER_CST)
3798 if (arith_overflowed_p (PLUS_EXPR, type, result,
3799 integer_zero_node))
3800 overflow = build_one_cst (type);
3802 else if ((!TYPE_UNSIGNED (TREE_TYPE (result))
3803 && TYPE_UNSIGNED (type))
3804 || (TYPE_PRECISION (type)
3805 < (TYPE_PRECISION (TREE_TYPE (result))
3806 + (TYPE_UNSIGNED (TREE_TYPE (result))
3807 && !TYPE_UNSIGNED (type)))))
3808 result = NULL_TREE;
3809 if (result)
3810 result = fold_convert (type, result);
3815 if (result)
3817 if (TREE_CODE (result) == INTEGER_CST && TREE_OVERFLOW (result))
3818 result = drop_tree_overflow (result);
3819 if (cplx_result)
3821 if (overflow == NULL_TREE)
3822 overflow = build_zero_cst (TREE_TYPE (result));
3823 tree ctype = build_complex_type (TREE_TYPE (result));
3824 if (TREE_CODE (result) == INTEGER_CST
3825 && TREE_CODE (overflow) == INTEGER_CST)
3826 result = build_complex (ctype, result, overflow);
3827 else
3828 result = build2_loc (gimple_location (stmt), COMPLEX_EXPR,
3829 ctype, result, overflow);
3831 if (!update_call_from_tree (gsi, result))
3832 gimplify_and_update_call_from_tree (gsi, result);
3833 changed = true;
3837 return changed;
3841 /* Return true whether NAME has a use on STMT. */
3843 static bool
3844 has_use_on_stmt (tree name, gimple *stmt)
3846 imm_use_iterator iter;
3847 use_operand_p use_p;
3848 FOR_EACH_IMM_USE_FAST (use_p, iter, name)
3849 if (USE_STMT (use_p) == stmt)
3850 return true;
3851 return false;
3854 /* Worker for fold_stmt_1 dispatch to pattern based folding with
3855 gimple_simplify.
3857 Replaces *GSI with the simplification result in RCODE and OPS
3858 and the associated statements in *SEQ. Does the replacement
3859 according to INPLACE and returns true if the operation succeeded. */
3861 static bool
3862 replace_stmt_with_simplification (gimple_stmt_iterator *gsi,
3863 code_helper rcode, tree *ops,
3864 gimple_seq *seq, bool inplace)
3866 gimple *stmt = gsi_stmt (*gsi);
3868 /* Play safe and do not allow abnormals to be mentioned in
3869 newly created statements. See also maybe_push_res_to_seq.
3870 As an exception allow such uses if there was a use of the
3871 same SSA name on the old stmt. */
3872 if ((TREE_CODE (ops[0]) == SSA_NAME
3873 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ops[0])
3874 && !has_use_on_stmt (ops[0], stmt))
3875 || (ops[1]
3876 && TREE_CODE (ops[1]) == SSA_NAME
3877 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ops[1])
3878 && !has_use_on_stmt (ops[1], stmt))
3879 || (ops[2]
3880 && TREE_CODE (ops[2]) == SSA_NAME
3881 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ops[2])
3882 && !has_use_on_stmt (ops[2], stmt))
3883 || (COMPARISON_CLASS_P (ops[0])
3884 && ((TREE_CODE (TREE_OPERAND (ops[0], 0)) == SSA_NAME
3885 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (TREE_OPERAND (ops[0], 0))
3886 && !has_use_on_stmt (TREE_OPERAND (ops[0], 0), stmt))
3887 || (TREE_CODE (TREE_OPERAND (ops[0], 1)) == SSA_NAME
3888 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (TREE_OPERAND (ops[0], 1))
3889 && !has_use_on_stmt (TREE_OPERAND (ops[0], 1), stmt)))))
3890 return false;
3892 /* Don't insert new statements when INPLACE is true, even if we could
3893 reuse STMT for the final statement. */
3894 if (inplace && !gimple_seq_empty_p (*seq))
3895 return false;
3897 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
3899 gcc_assert (rcode.is_tree_code ());
3900 if (TREE_CODE_CLASS ((enum tree_code)rcode) == tcc_comparison
3901 /* GIMPLE_CONDs condition may not throw. */
3902 && (!flag_exceptions
3903 || !cfun->can_throw_non_call_exceptions
3904 || !operation_could_trap_p (rcode,
3905 FLOAT_TYPE_P (TREE_TYPE (ops[0])),
3906 false, NULL_TREE)))
3907 gimple_cond_set_condition (cond_stmt, rcode, ops[0], ops[1]);
3908 else if (rcode == SSA_NAME)
3909 gimple_cond_set_condition (cond_stmt, NE_EXPR, ops[0],
3910 build_zero_cst (TREE_TYPE (ops[0])));
3911 else if (rcode == INTEGER_CST)
3913 if (integer_zerop (ops[0]))
3914 gimple_cond_make_false (cond_stmt);
3915 else
3916 gimple_cond_make_true (cond_stmt);
3918 else if (!inplace)
3920 tree res = maybe_push_res_to_seq (rcode, boolean_type_node,
3921 ops, seq);
3922 if (!res)
3923 return false;
3924 gimple_cond_set_condition (cond_stmt, NE_EXPR, res,
3925 build_zero_cst (TREE_TYPE (res)));
3927 else
3928 return false;
3929 if (dump_file && (dump_flags & TDF_DETAILS))
3931 fprintf (dump_file, "gimple_simplified to ");
3932 if (!gimple_seq_empty_p (*seq))
3933 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
3934 print_gimple_stmt (dump_file, gsi_stmt (*gsi),
3935 0, TDF_SLIM);
3937 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
3938 return true;
3940 else if (is_gimple_assign (stmt)
3941 && rcode.is_tree_code ())
3943 if (!inplace
3944 || gimple_num_ops (stmt) > get_gimple_rhs_num_ops (rcode))
3946 maybe_build_generic_op (rcode,
3947 TREE_TYPE (gimple_assign_lhs (stmt)), ops);
3948 gimple_assign_set_rhs_with_ops (gsi, rcode, ops[0], ops[1], ops[2]);
3949 if (dump_file && (dump_flags & TDF_DETAILS))
3951 fprintf (dump_file, "gimple_simplified to ");
3952 if (!gimple_seq_empty_p (*seq))
3953 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
3954 print_gimple_stmt (dump_file, gsi_stmt (*gsi),
3955 0, TDF_SLIM);
3957 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
3958 return true;
3961 else if (rcode.is_fn_code ()
3962 && gimple_call_combined_fn (stmt) == rcode)
3964 unsigned i;
3965 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3967 gcc_assert (ops[i] != NULL_TREE);
3968 gimple_call_set_arg (stmt, i, ops[i]);
3970 if (i < 3)
3971 gcc_assert (ops[i] == NULL_TREE);
3972 if (dump_file && (dump_flags & TDF_DETAILS))
3974 fprintf (dump_file, "gimple_simplified to ");
3975 if (!gimple_seq_empty_p (*seq))
3976 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
3977 print_gimple_stmt (dump_file, gsi_stmt (*gsi), 0, TDF_SLIM);
3979 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
3980 return true;
3982 else if (!inplace)
3984 if (gimple_has_lhs (stmt))
3986 tree lhs = gimple_get_lhs (stmt);
3987 if (!maybe_push_res_to_seq (rcode, TREE_TYPE (lhs),
3988 ops, seq, lhs))
3989 return false;
3990 if (dump_file && (dump_flags & TDF_DETAILS))
3992 fprintf (dump_file, "gimple_simplified to ");
3993 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
3995 gsi_replace_with_seq_vops (gsi, *seq);
3996 return true;
3998 else
3999 gcc_unreachable ();
4002 return false;
4005 /* Canonicalize MEM_REFs invariant address operand after propagation. */
4007 static bool
4008 maybe_canonicalize_mem_ref_addr (tree *t)
4010 bool res = false;
4012 if (TREE_CODE (*t) == ADDR_EXPR)
4013 t = &TREE_OPERAND (*t, 0);
4015 /* The C and C++ frontends use an ARRAY_REF for indexing with their
4016 generic vector extension. The actual vector referenced is
4017 view-converted to an array type for this purpose. If the index
4018 is constant the canonical representation in the middle-end is a
4019 BIT_FIELD_REF so re-write the former to the latter here. */
4020 if (TREE_CODE (*t) == ARRAY_REF
4021 && TREE_CODE (TREE_OPERAND (*t, 0)) == VIEW_CONVERT_EXPR
4022 && TREE_CODE (TREE_OPERAND (*t, 1)) == INTEGER_CST
4023 && VECTOR_TYPE_P (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (*t, 0), 0))))
4025 tree vtype = TREE_TYPE (TREE_OPERAND (TREE_OPERAND (*t, 0), 0));
4026 if (VECTOR_TYPE_P (vtype))
4028 tree low = array_ref_low_bound (*t);
4029 if (TREE_CODE (low) == INTEGER_CST)
4031 if (tree_int_cst_le (low, TREE_OPERAND (*t, 1)))
4033 widest_int idx = wi::sub (wi::to_widest (TREE_OPERAND (*t, 1)),
4034 wi::to_widest (low));
4035 idx = wi::mul (idx, wi::to_widest
4036 (TYPE_SIZE (TREE_TYPE (*t))));
4037 widest_int ext
4038 = wi::add (idx, wi::to_widest (TYPE_SIZE (TREE_TYPE (*t))));
4039 if (wi::les_p (ext, wi::to_widest (TYPE_SIZE (vtype))))
4041 *t = build3_loc (EXPR_LOCATION (*t), BIT_FIELD_REF,
4042 TREE_TYPE (*t),
4043 TREE_OPERAND (TREE_OPERAND (*t, 0), 0),
4044 TYPE_SIZE (TREE_TYPE (*t)),
4045 wide_int_to_tree (sizetype, idx));
4046 res = true;
4053 while (handled_component_p (*t))
4054 t = &TREE_OPERAND (*t, 0);
4056 /* Canonicalize MEM [&foo.bar, 0] which appears after propagating
4057 of invariant addresses into a SSA name MEM_REF address. */
4058 if (TREE_CODE (*t) == MEM_REF
4059 || TREE_CODE (*t) == TARGET_MEM_REF)
4061 tree addr = TREE_OPERAND (*t, 0);
4062 if (TREE_CODE (addr) == ADDR_EXPR
4063 && (TREE_CODE (TREE_OPERAND (addr, 0)) == MEM_REF
4064 || handled_component_p (TREE_OPERAND (addr, 0))))
4066 tree base;
4067 HOST_WIDE_INT coffset;
4068 base = get_addr_base_and_unit_offset (TREE_OPERAND (addr, 0),
4069 &coffset);
4070 if (!base)
4071 gcc_unreachable ();
4073 TREE_OPERAND (*t, 0) = build_fold_addr_expr (base);
4074 TREE_OPERAND (*t, 1) = int_const_binop (PLUS_EXPR,
4075 TREE_OPERAND (*t, 1),
4076 size_int (coffset));
4077 res = true;
4079 gcc_checking_assert (TREE_CODE (TREE_OPERAND (*t, 0)) == DEBUG_EXPR_DECL
4080 || is_gimple_mem_ref_addr (TREE_OPERAND (*t, 0)));
4083 /* Canonicalize back MEM_REFs to plain reference trees if the object
4084 accessed is a decl that has the same access semantics as the MEM_REF. */
4085 if (TREE_CODE (*t) == MEM_REF
4086 && TREE_CODE (TREE_OPERAND (*t, 0)) == ADDR_EXPR
4087 && integer_zerop (TREE_OPERAND (*t, 1))
4088 && MR_DEPENDENCE_CLIQUE (*t) == 0)
4090 tree decl = TREE_OPERAND (TREE_OPERAND (*t, 0), 0);
4091 tree alias_type = TREE_TYPE (TREE_OPERAND (*t, 1));
4092 if (/* Same volatile qualification. */
4093 TREE_THIS_VOLATILE (*t) == TREE_THIS_VOLATILE (decl)
4094 /* Same TBAA behavior with -fstrict-aliasing. */
4095 && !TYPE_REF_CAN_ALIAS_ALL (alias_type)
4096 && (TYPE_MAIN_VARIANT (TREE_TYPE (decl))
4097 == TYPE_MAIN_VARIANT (TREE_TYPE (alias_type)))
4098 /* Same alignment. */
4099 && TYPE_ALIGN (TREE_TYPE (decl)) == TYPE_ALIGN (TREE_TYPE (*t))
4100 /* We have to look out here to not drop a required conversion
4101 from the rhs to the lhs if *t appears on the lhs or vice-versa
4102 if it appears on the rhs. Thus require strict type
4103 compatibility. */
4104 && types_compatible_p (TREE_TYPE (*t), TREE_TYPE (decl)))
4106 *t = TREE_OPERAND (TREE_OPERAND (*t, 0), 0);
4107 res = true;
4111 /* Canonicalize TARGET_MEM_REF in particular with respect to
4112 the indexes becoming constant. */
4113 else if (TREE_CODE (*t) == TARGET_MEM_REF)
4115 tree tem = maybe_fold_tmr (*t);
4116 if (tem)
4118 *t = tem;
4119 res = true;
4123 return res;
4126 /* Worker for both fold_stmt and fold_stmt_inplace. The INPLACE argument
4127 distinguishes both cases. */
4129 static bool
4130 fold_stmt_1 (gimple_stmt_iterator *gsi, bool inplace, tree (*valueize) (tree))
4132 bool changed = false;
4133 gimple *stmt = gsi_stmt (*gsi);
4134 bool nowarning = gimple_no_warning_p (stmt);
4135 unsigned i;
4136 fold_defer_overflow_warnings ();
4138 /* First do required canonicalization of [TARGET_]MEM_REF addresses
4139 after propagation.
4140 ??? This shouldn't be done in generic folding but in the
4141 propagation helpers which also know whether an address was
4142 propagated.
4143 Also canonicalize operand order. */
4144 switch (gimple_code (stmt))
4146 case GIMPLE_ASSIGN:
4147 if (gimple_assign_rhs_class (stmt) == GIMPLE_SINGLE_RHS)
4149 tree *rhs = gimple_assign_rhs1_ptr (stmt);
4150 if ((REFERENCE_CLASS_P (*rhs)
4151 || TREE_CODE (*rhs) == ADDR_EXPR)
4152 && maybe_canonicalize_mem_ref_addr (rhs))
4153 changed = true;
4154 tree *lhs = gimple_assign_lhs_ptr (stmt);
4155 if (REFERENCE_CLASS_P (*lhs)
4156 && maybe_canonicalize_mem_ref_addr (lhs))
4157 changed = true;
4159 else
4161 /* Canonicalize operand order. */
4162 enum tree_code code = gimple_assign_rhs_code (stmt);
4163 if (TREE_CODE_CLASS (code) == tcc_comparison
4164 || commutative_tree_code (code)
4165 || commutative_ternary_tree_code (code))
4167 tree rhs1 = gimple_assign_rhs1 (stmt);
4168 tree rhs2 = gimple_assign_rhs2 (stmt);
4169 if (tree_swap_operands_p (rhs1, rhs2))
4171 gimple_assign_set_rhs1 (stmt, rhs2);
4172 gimple_assign_set_rhs2 (stmt, rhs1);
4173 if (TREE_CODE_CLASS (code) == tcc_comparison)
4174 gimple_assign_set_rhs_code (stmt,
4175 swap_tree_comparison (code));
4176 changed = true;
4180 break;
4181 case GIMPLE_CALL:
4183 for (i = 0; i < gimple_call_num_args (stmt); ++i)
4185 tree *arg = gimple_call_arg_ptr (stmt, i);
4186 if (REFERENCE_CLASS_P (*arg)
4187 && maybe_canonicalize_mem_ref_addr (arg))
4188 changed = true;
4190 tree *lhs = gimple_call_lhs_ptr (stmt);
4191 if (*lhs
4192 && REFERENCE_CLASS_P (*lhs)
4193 && maybe_canonicalize_mem_ref_addr (lhs))
4194 changed = true;
4195 break;
4197 case GIMPLE_ASM:
4199 gasm *asm_stmt = as_a <gasm *> (stmt);
4200 for (i = 0; i < gimple_asm_noutputs (asm_stmt); ++i)
4202 tree link = gimple_asm_output_op (asm_stmt, i);
4203 tree op = TREE_VALUE (link);
4204 if (REFERENCE_CLASS_P (op)
4205 && maybe_canonicalize_mem_ref_addr (&TREE_VALUE (link)))
4206 changed = true;
4208 for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
4210 tree link = gimple_asm_input_op (asm_stmt, i);
4211 tree op = TREE_VALUE (link);
4212 if ((REFERENCE_CLASS_P (op)
4213 || TREE_CODE (op) == ADDR_EXPR)
4214 && maybe_canonicalize_mem_ref_addr (&TREE_VALUE (link)))
4215 changed = true;
4218 break;
4219 case GIMPLE_DEBUG:
4220 if (gimple_debug_bind_p (stmt))
4222 tree *val = gimple_debug_bind_get_value_ptr (stmt);
4223 if (*val
4224 && (REFERENCE_CLASS_P (*val)
4225 || TREE_CODE (*val) == ADDR_EXPR)
4226 && maybe_canonicalize_mem_ref_addr (val))
4227 changed = true;
4229 break;
4230 case GIMPLE_COND:
4232 /* Canonicalize operand order. */
4233 tree lhs = gimple_cond_lhs (stmt);
4234 tree rhs = gimple_cond_rhs (stmt);
4235 if (tree_swap_operands_p (lhs, rhs))
4237 gcond *gc = as_a <gcond *> (stmt);
4238 gimple_cond_set_lhs (gc, rhs);
4239 gimple_cond_set_rhs (gc, lhs);
4240 gimple_cond_set_code (gc,
4241 swap_tree_comparison (gimple_cond_code (gc)));
4242 changed = true;
4245 default:;
4248 /* Dispatch to pattern-based folding. */
4249 if (!inplace
4250 || is_gimple_assign (stmt)
4251 || gimple_code (stmt) == GIMPLE_COND)
4253 gimple_seq seq = NULL;
4254 code_helper rcode;
4255 tree ops[3] = {};
4256 if (gimple_simplify (stmt, &rcode, ops, inplace ? NULL : &seq,
4257 valueize, valueize))
4259 if (replace_stmt_with_simplification (gsi, rcode, ops, &seq, inplace))
4260 changed = true;
4261 else
4262 gimple_seq_discard (seq);
4266 stmt = gsi_stmt (*gsi);
4268 /* Fold the main computation performed by the statement. */
4269 switch (gimple_code (stmt))
4271 case GIMPLE_ASSIGN:
4273 /* Try to canonicalize for boolean-typed X the comparisons
4274 X == 0, X == 1, X != 0, and X != 1. */
4275 if (gimple_assign_rhs_code (stmt) == EQ_EXPR
4276 || gimple_assign_rhs_code (stmt) == NE_EXPR)
4278 tree lhs = gimple_assign_lhs (stmt);
4279 tree op1 = gimple_assign_rhs1 (stmt);
4280 tree op2 = gimple_assign_rhs2 (stmt);
4281 tree type = TREE_TYPE (op1);
4283 /* Check whether the comparison operands are of the same boolean
4284 type as the result type is.
4285 Check that second operand is an integer-constant with value
4286 one or zero. */
4287 if (TREE_CODE (op2) == INTEGER_CST
4288 && (integer_zerop (op2) || integer_onep (op2))
4289 && useless_type_conversion_p (TREE_TYPE (lhs), type))
4291 enum tree_code cmp_code = gimple_assign_rhs_code (stmt);
4292 bool is_logical_not = false;
4294 /* X == 0 and X != 1 is a logical-not.of X
4295 X == 1 and X != 0 is X */
4296 if ((cmp_code == EQ_EXPR && integer_zerop (op2))
4297 || (cmp_code == NE_EXPR && integer_onep (op2)))
4298 is_logical_not = true;
4300 if (is_logical_not == false)
4301 gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op1), op1);
4302 /* Only for one-bit precision typed X the transformation
4303 !X -> ~X is valied. */
4304 else if (TYPE_PRECISION (type) == 1)
4305 gimple_assign_set_rhs_with_ops (gsi, BIT_NOT_EXPR, op1);
4306 /* Otherwise we use !X -> X ^ 1. */
4307 else
4308 gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op1,
4309 build_int_cst (type, 1));
4310 changed = true;
4311 break;
4315 unsigned old_num_ops = gimple_num_ops (stmt);
4316 tree lhs = gimple_assign_lhs (stmt);
4317 tree new_rhs = fold_gimple_assign (gsi);
4318 if (new_rhs
4319 && !useless_type_conversion_p (TREE_TYPE (lhs),
4320 TREE_TYPE (new_rhs)))
4321 new_rhs = fold_convert (TREE_TYPE (lhs), new_rhs);
4322 if (new_rhs
4323 && (!inplace
4324 || get_gimple_rhs_num_ops (TREE_CODE (new_rhs)) < old_num_ops))
4326 gimple_assign_set_rhs_from_tree (gsi, new_rhs);
4327 changed = true;
4329 break;
4332 case GIMPLE_CALL:
4333 changed |= gimple_fold_call (gsi, inplace);
4334 break;
4336 case GIMPLE_ASM:
4337 /* Fold *& in asm operands. */
4339 gasm *asm_stmt = as_a <gasm *> (stmt);
4340 size_t noutputs;
4341 const char **oconstraints;
4342 const char *constraint;
4343 bool allows_mem, allows_reg;
4345 noutputs = gimple_asm_noutputs (asm_stmt);
4346 oconstraints = XALLOCAVEC (const char *, noutputs);
4348 for (i = 0; i < gimple_asm_noutputs (asm_stmt); ++i)
4350 tree link = gimple_asm_output_op (asm_stmt, i);
4351 tree op = TREE_VALUE (link);
4352 oconstraints[i]
4353 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
4354 if (REFERENCE_CLASS_P (op)
4355 && (op = maybe_fold_reference (op, true)) != NULL_TREE)
4357 TREE_VALUE (link) = op;
4358 changed = true;
4361 for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
4363 tree link = gimple_asm_input_op (asm_stmt, i);
4364 tree op = TREE_VALUE (link);
4365 constraint
4366 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
4367 parse_input_constraint (&constraint, 0, 0, noutputs, 0,
4368 oconstraints, &allows_mem, &allows_reg);
4369 if (REFERENCE_CLASS_P (op)
4370 && (op = maybe_fold_reference (op, !allows_reg && allows_mem))
4371 != NULL_TREE)
4373 TREE_VALUE (link) = op;
4374 changed = true;
4378 break;
4380 case GIMPLE_DEBUG:
4381 if (gimple_debug_bind_p (stmt))
4383 tree val = gimple_debug_bind_get_value (stmt);
4384 if (val
4385 && REFERENCE_CLASS_P (val))
4387 tree tem = maybe_fold_reference (val, false);
4388 if (tem)
4390 gimple_debug_bind_set_value (stmt, tem);
4391 changed = true;
4394 else if (val
4395 && TREE_CODE (val) == ADDR_EXPR)
4397 tree ref = TREE_OPERAND (val, 0);
4398 tree tem = maybe_fold_reference (ref, false);
4399 if (tem)
4401 tem = build_fold_addr_expr_with_type (tem, TREE_TYPE (val));
4402 gimple_debug_bind_set_value (stmt, tem);
4403 changed = true;
4407 break;
4409 case GIMPLE_RETURN:
4411 greturn *ret_stmt = as_a<greturn *> (stmt);
4412 tree ret = gimple_return_retval(ret_stmt);
4414 if (ret && TREE_CODE (ret) == SSA_NAME && valueize)
4416 tree val = valueize (ret);
4417 if (val && val != ret
4418 && may_propagate_copy (ret, val))
4420 gimple_return_set_retval (ret_stmt, val);
4421 changed = true;
4425 break;
4427 default:;
4430 stmt = gsi_stmt (*gsi);
4432 /* Fold *& on the lhs. */
4433 if (gimple_has_lhs (stmt))
4435 tree lhs = gimple_get_lhs (stmt);
4436 if (lhs && REFERENCE_CLASS_P (lhs))
4438 tree new_lhs = maybe_fold_reference (lhs, true);
4439 if (new_lhs)
4441 gimple_set_lhs (stmt, new_lhs);
4442 changed = true;
4447 fold_undefer_overflow_warnings (changed && !nowarning, stmt, 0);
4448 return changed;
4451 /* Valueziation callback that ends up not following SSA edges. */
4453 tree
4454 no_follow_ssa_edges (tree)
4456 return NULL_TREE;
4459 /* Valueization callback that ends up following single-use SSA edges only. */
4461 tree
4462 follow_single_use_edges (tree val)
4464 if (TREE_CODE (val) == SSA_NAME
4465 && !has_single_use (val))
4466 return NULL_TREE;
4467 return val;
4470 /* Fold the statement pointed to by GSI. In some cases, this function may
4471 replace the whole statement with a new one. Returns true iff folding
4472 makes any changes.
4473 The statement pointed to by GSI should be in valid gimple form but may
4474 be in unfolded state as resulting from for example constant propagation
4475 which can produce *&x = 0. */
4477 bool
4478 fold_stmt (gimple_stmt_iterator *gsi)
4480 return fold_stmt_1 (gsi, false, no_follow_ssa_edges);
4483 bool
4484 fold_stmt (gimple_stmt_iterator *gsi, tree (*valueize) (tree))
4486 return fold_stmt_1 (gsi, false, valueize);
4489 /* Perform the minimal folding on statement *GSI. Only operations like
4490 *&x created by constant propagation are handled. The statement cannot
4491 be replaced with a new one. Return true if the statement was
4492 changed, false otherwise.
4493 The statement *GSI should be in valid gimple form but may
4494 be in unfolded state as resulting from for example constant propagation
4495 which can produce *&x = 0. */
4497 bool
4498 fold_stmt_inplace (gimple_stmt_iterator *gsi)
4500 gimple *stmt = gsi_stmt (*gsi);
4501 bool changed = fold_stmt_1 (gsi, true, no_follow_ssa_edges);
4502 gcc_assert (gsi_stmt (*gsi) == stmt);
4503 return changed;
4506 /* Canonicalize and possibly invert the boolean EXPR; return NULL_TREE
4507 if EXPR is null or we don't know how.
4508 If non-null, the result always has boolean type. */
4510 static tree
4511 canonicalize_bool (tree expr, bool invert)
4513 if (!expr)
4514 return NULL_TREE;
4515 else if (invert)
4517 if (integer_nonzerop (expr))
4518 return boolean_false_node;
4519 else if (integer_zerop (expr))
4520 return boolean_true_node;
4521 else if (TREE_CODE (expr) == SSA_NAME)
4522 return fold_build2 (EQ_EXPR, boolean_type_node, expr,
4523 build_int_cst (TREE_TYPE (expr), 0));
4524 else if (COMPARISON_CLASS_P (expr))
4525 return fold_build2 (invert_tree_comparison (TREE_CODE (expr), false),
4526 boolean_type_node,
4527 TREE_OPERAND (expr, 0),
4528 TREE_OPERAND (expr, 1));
4529 else
4530 return NULL_TREE;
4532 else
4534 if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE)
4535 return expr;
4536 if (integer_nonzerop (expr))
4537 return boolean_true_node;
4538 else if (integer_zerop (expr))
4539 return boolean_false_node;
4540 else if (TREE_CODE (expr) == SSA_NAME)
4541 return fold_build2 (NE_EXPR, boolean_type_node, expr,
4542 build_int_cst (TREE_TYPE (expr), 0));
4543 else if (COMPARISON_CLASS_P (expr))
4544 return fold_build2 (TREE_CODE (expr),
4545 boolean_type_node,
4546 TREE_OPERAND (expr, 0),
4547 TREE_OPERAND (expr, 1));
4548 else
4549 return NULL_TREE;
4553 /* Check to see if a boolean expression EXPR is logically equivalent to the
4554 comparison (OP1 CODE OP2). Check for various identities involving
4555 SSA_NAMEs. */
4557 static bool
4558 same_bool_comparison_p (const_tree expr, enum tree_code code,
4559 const_tree op1, const_tree op2)
4561 gimple *s;
4563 /* The obvious case. */
4564 if (TREE_CODE (expr) == code
4565 && operand_equal_p (TREE_OPERAND (expr, 0), op1, 0)
4566 && operand_equal_p (TREE_OPERAND (expr, 1), op2, 0))
4567 return true;
4569 /* Check for comparing (name, name != 0) and the case where expr
4570 is an SSA_NAME with a definition matching the comparison. */
4571 if (TREE_CODE (expr) == SSA_NAME
4572 && TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE)
4574 if (operand_equal_p (expr, op1, 0))
4575 return ((code == NE_EXPR && integer_zerop (op2))
4576 || (code == EQ_EXPR && integer_nonzerop (op2)));
4577 s = SSA_NAME_DEF_STMT (expr);
4578 if (is_gimple_assign (s)
4579 && gimple_assign_rhs_code (s) == code
4580 && operand_equal_p (gimple_assign_rhs1 (s), op1, 0)
4581 && operand_equal_p (gimple_assign_rhs2 (s), op2, 0))
4582 return true;
4585 /* If op1 is of the form (name != 0) or (name == 0), and the definition
4586 of name is a comparison, recurse. */
4587 if (TREE_CODE (op1) == SSA_NAME
4588 && TREE_CODE (TREE_TYPE (op1)) == BOOLEAN_TYPE)
4590 s = SSA_NAME_DEF_STMT (op1);
4591 if (is_gimple_assign (s)
4592 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison)
4594 enum tree_code c = gimple_assign_rhs_code (s);
4595 if ((c == NE_EXPR && integer_zerop (op2))
4596 || (c == EQ_EXPR && integer_nonzerop (op2)))
4597 return same_bool_comparison_p (expr, c,
4598 gimple_assign_rhs1 (s),
4599 gimple_assign_rhs2 (s));
4600 if ((c == EQ_EXPR && integer_zerop (op2))
4601 || (c == NE_EXPR && integer_nonzerop (op2)))
4602 return same_bool_comparison_p (expr,
4603 invert_tree_comparison (c, false),
4604 gimple_assign_rhs1 (s),
4605 gimple_assign_rhs2 (s));
4608 return false;
4611 /* Check to see if two boolean expressions OP1 and OP2 are logically
4612 equivalent. */
4614 static bool
4615 same_bool_result_p (const_tree op1, const_tree op2)
4617 /* Simple cases first. */
4618 if (operand_equal_p (op1, op2, 0))
4619 return true;
4621 /* Check the cases where at least one of the operands is a comparison.
4622 These are a bit smarter than operand_equal_p in that they apply some
4623 identifies on SSA_NAMEs. */
4624 if (COMPARISON_CLASS_P (op2)
4625 && same_bool_comparison_p (op1, TREE_CODE (op2),
4626 TREE_OPERAND (op2, 0),
4627 TREE_OPERAND (op2, 1)))
4628 return true;
4629 if (COMPARISON_CLASS_P (op1)
4630 && same_bool_comparison_p (op2, TREE_CODE (op1),
4631 TREE_OPERAND (op1, 0),
4632 TREE_OPERAND (op1, 1)))
4633 return true;
4635 /* Default case. */
4636 return false;
4639 /* Forward declarations for some mutually recursive functions. */
4641 static tree
4642 and_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
4643 enum tree_code code2, tree op2a, tree op2b);
4644 static tree
4645 and_var_with_comparison (tree var, bool invert,
4646 enum tree_code code2, tree op2a, tree op2b);
4647 static tree
4648 and_var_with_comparison_1 (gimple *stmt,
4649 enum tree_code code2, tree op2a, tree op2b);
4650 static tree
4651 or_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
4652 enum tree_code code2, tree op2a, tree op2b);
4653 static tree
4654 or_var_with_comparison (tree var, bool invert,
4655 enum tree_code code2, tree op2a, tree op2b);
4656 static tree
4657 or_var_with_comparison_1 (gimple *stmt,
4658 enum tree_code code2, tree op2a, tree op2b);
4660 /* Helper function for and_comparisons_1: try to simplify the AND of the
4661 ssa variable VAR with the comparison specified by (OP2A CODE2 OP2B).
4662 If INVERT is true, invert the value of the VAR before doing the AND.
4663 Return NULL_EXPR if we can't simplify this to a single expression. */
4665 static tree
4666 and_var_with_comparison (tree var, bool invert,
4667 enum tree_code code2, tree op2a, tree op2b)
4669 tree t;
4670 gimple *stmt = SSA_NAME_DEF_STMT (var);
4672 /* We can only deal with variables whose definitions are assignments. */
4673 if (!is_gimple_assign (stmt))
4674 return NULL_TREE;
4676 /* If we have an inverted comparison, apply DeMorgan's law and rewrite
4677 !var AND (op2a code2 op2b) => !(var OR !(op2a code2 op2b))
4678 Then we only have to consider the simpler non-inverted cases. */
4679 if (invert)
4680 t = or_var_with_comparison_1 (stmt,
4681 invert_tree_comparison (code2, false),
4682 op2a, op2b);
4683 else
4684 t = and_var_with_comparison_1 (stmt, code2, op2a, op2b);
4685 return canonicalize_bool (t, invert);
4688 /* Try to simplify the AND of the ssa variable defined by the assignment
4689 STMT with the comparison specified by (OP2A CODE2 OP2B).
4690 Return NULL_EXPR if we can't simplify this to a single expression. */
4692 static tree
4693 and_var_with_comparison_1 (gimple *stmt,
4694 enum tree_code code2, tree op2a, tree op2b)
4696 tree var = gimple_assign_lhs (stmt);
4697 tree true_test_var = NULL_TREE;
4698 tree false_test_var = NULL_TREE;
4699 enum tree_code innercode = gimple_assign_rhs_code (stmt);
4701 /* Check for identities like (var AND (var == 0)) => false. */
4702 if (TREE_CODE (op2a) == SSA_NAME
4703 && TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE)
4705 if ((code2 == NE_EXPR && integer_zerop (op2b))
4706 || (code2 == EQ_EXPR && integer_nonzerop (op2b)))
4708 true_test_var = op2a;
4709 if (var == true_test_var)
4710 return var;
4712 else if ((code2 == EQ_EXPR && integer_zerop (op2b))
4713 || (code2 == NE_EXPR && integer_nonzerop (op2b)))
4715 false_test_var = op2a;
4716 if (var == false_test_var)
4717 return boolean_false_node;
4721 /* If the definition is a comparison, recurse on it. */
4722 if (TREE_CODE_CLASS (innercode) == tcc_comparison)
4724 tree t = and_comparisons_1 (innercode,
4725 gimple_assign_rhs1 (stmt),
4726 gimple_assign_rhs2 (stmt),
4727 code2,
4728 op2a,
4729 op2b);
4730 if (t)
4731 return t;
4734 /* If the definition is an AND or OR expression, we may be able to
4735 simplify by reassociating. */
4736 if (TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE
4737 && (innercode == BIT_AND_EXPR || innercode == BIT_IOR_EXPR))
4739 tree inner1 = gimple_assign_rhs1 (stmt);
4740 tree inner2 = gimple_assign_rhs2 (stmt);
4741 gimple *s;
4742 tree t;
4743 tree partial = NULL_TREE;
4744 bool is_and = (innercode == BIT_AND_EXPR);
4746 /* Check for boolean identities that don't require recursive examination
4747 of inner1/inner2:
4748 inner1 AND (inner1 AND inner2) => inner1 AND inner2 => var
4749 inner1 AND (inner1 OR inner2) => inner1
4750 !inner1 AND (inner1 AND inner2) => false
4751 !inner1 AND (inner1 OR inner2) => !inner1 AND inner2
4752 Likewise for similar cases involving inner2. */
4753 if (inner1 == true_test_var)
4754 return (is_and ? var : inner1);
4755 else if (inner2 == true_test_var)
4756 return (is_and ? var : inner2);
4757 else if (inner1 == false_test_var)
4758 return (is_and
4759 ? boolean_false_node
4760 : and_var_with_comparison (inner2, false, code2, op2a, op2b));
4761 else if (inner2 == false_test_var)
4762 return (is_and
4763 ? boolean_false_node
4764 : and_var_with_comparison (inner1, false, code2, op2a, op2b));
4766 /* Next, redistribute/reassociate the AND across the inner tests.
4767 Compute the first partial result, (inner1 AND (op2a code op2b)) */
4768 if (TREE_CODE (inner1) == SSA_NAME
4769 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner1))
4770 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
4771 && (t = maybe_fold_and_comparisons (gimple_assign_rhs_code (s),
4772 gimple_assign_rhs1 (s),
4773 gimple_assign_rhs2 (s),
4774 code2, op2a, op2b)))
4776 /* Handle the AND case, where we are reassociating:
4777 (inner1 AND inner2) AND (op2a code2 op2b)
4778 => (t AND inner2)
4779 If the partial result t is a constant, we win. Otherwise
4780 continue on to try reassociating with the other inner test. */
4781 if (is_and)
4783 if (integer_onep (t))
4784 return inner2;
4785 else if (integer_zerop (t))
4786 return boolean_false_node;
4789 /* Handle the OR case, where we are redistributing:
4790 (inner1 OR inner2) AND (op2a code2 op2b)
4791 => (t OR (inner2 AND (op2a code2 op2b))) */
4792 else if (integer_onep (t))
4793 return boolean_true_node;
4795 /* Save partial result for later. */
4796 partial = t;
4799 /* Compute the second partial result, (inner2 AND (op2a code op2b)) */
4800 if (TREE_CODE (inner2) == SSA_NAME
4801 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner2))
4802 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
4803 && (t = maybe_fold_and_comparisons (gimple_assign_rhs_code (s),
4804 gimple_assign_rhs1 (s),
4805 gimple_assign_rhs2 (s),
4806 code2, op2a, op2b)))
4808 /* Handle the AND case, where we are reassociating:
4809 (inner1 AND inner2) AND (op2a code2 op2b)
4810 => (inner1 AND t) */
4811 if (is_and)
4813 if (integer_onep (t))
4814 return inner1;
4815 else if (integer_zerop (t))
4816 return boolean_false_node;
4817 /* If both are the same, we can apply the identity
4818 (x AND x) == x. */
4819 else if (partial && same_bool_result_p (t, partial))
4820 return t;
4823 /* Handle the OR case. where we are redistributing:
4824 (inner1 OR inner2) AND (op2a code2 op2b)
4825 => (t OR (inner1 AND (op2a code2 op2b)))
4826 => (t OR partial) */
4827 else
4829 if (integer_onep (t))
4830 return boolean_true_node;
4831 else if (partial)
4833 /* We already got a simplification for the other
4834 operand to the redistributed OR expression. The
4835 interesting case is when at least one is false.
4836 Or, if both are the same, we can apply the identity
4837 (x OR x) == x. */
4838 if (integer_zerop (partial))
4839 return t;
4840 else if (integer_zerop (t))
4841 return partial;
4842 else if (same_bool_result_p (t, partial))
4843 return t;
4848 return NULL_TREE;
4851 /* Try to simplify the AND of two comparisons defined by
4852 (OP1A CODE1 OP1B) and (OP2A CODE2 OP2B), respectively.
4853 If this can be done without constructing an intermediate value,
4854 return the resulting tree; otherwise NULL_TREE is returned.
4855 This function is deliberately asymmetric as it recurses on SSA_DEFs
4856 in the first comparison but not the second. */
4858 static tree
4859 and_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
4860 enum tree_code code2, tree op2a, tree op2b)
4862 tree truth_type = truth_type_for (TREE_TYPE (op1a));
4864 /* First check for ((x CODE1 y) AND (x CODE2 y)). */
4865 if (operand_equal_p (op1a, op2a, 0)
4866 && operand_equal_p (op1b, op2b, 0))
4868 /* Result will be either NULL_TREE, or a combined comparison. */
4869 tree t = combine_comparisons (UNKNOWN_LOCATION,
4870 TRUTH_ANDIF_EXPR, code1, code2,
4871 truth_type, op1a, op1b);
4872 if (t)
4873 return t;
4876 /* Likewise the swapped case of the above. */
4877 if (operand_equal_p (op1a, op2b, 0)
4878 && operand_equal_p (op1b, op2a, 0))
4880 /* Result will be either NULL_TREE, or a combined comparison. */
4881 tree t = combine_comparisons (UNKNOWN_LOCATION,
4882 TRUTH_ANDIF_EXPR, code1,
4883 swap_tree_comparison (code2),
4884 truth_type, op1a, op1b);
4885 if (t)
4886 return t;
4889 /* If both comparisons are of the same value against constants, we might
4890 be able to merge them. */
4891 if (operand_equal_p (op1a, op2a, 0)
4892 && TREE_CODE (op1b) == INTEGER_CST
4893 && TREE_CODE (op2b) == INTEGER_CST)
4895 int cmp = tree_int_cst_compare (op1b, op2b);
4897 /* If we have (op1a == op1b), we should either be able to
4898 return that or FALSE, depending on whether the constant op1b
4899 also satisfies the other comparison against op2b. */
4900 if (code1 == EQ_EXPR)
4902 bool done = true;
4903 bool val;
4904 switch (code2)
4906 case EQ_EXPR: val = (cmp == 0); break;
4907 case NE_EXPR: val = (cmp != 0); break;
4908 case LT_EXPR: val = (cmp < 0); break;
4909 case GT_EXPR: val = (cmp > 0); break;
4910 case LE_EXPR: val = (cmp <= 0); break;
4911 case GE_EXPR: val = (cmp >= 0); break;
4912 default: done = false;
4914 if (done)
4916 if (val)
4917 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4918 else
4919 return boolean_false_node;
4922 /* Likewise if the second comparison is an == comparison. */
4923 else if (code2 == EQ_EXPR)
4925 bool done = true;
4926 bool val;
4927 switch (code1)
4929 case EQ_EXPR: val = (cmp == 0); break;
4930 case NE_EXPR: val = (cmp != 0); break;
4931 case LT_EXPR: val = (cmp > 0); break;
4932 case GT_EXPR: val = (cmp < 0); break;
4933 case LE_EXPR: val = (cmp >= 0); break;
4934 case GE_EXPR: val = (cmp <= 0); break;
4935 default: done = false;
4937 if (done)
4939 if (val)
4940 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4941 else
4942 return boolean_false_node;
4946 /* Same business with inequality tests. */
4947 else if (code1 == NE_EXPR)
4949 bool val;
4950 switch (code2)
4952 case EQ_EXPR: val = (cmp != 0); break;
4953 case NE_EXPR: val = (cmp == 0); break;
4954 case LT_EXPR: val = (cmp >= 0); break;
4955 case GT_EXPR: val = (cmp <= 0); break;
4956 case LE_EXPR: val = (cmp > 0); break;
4957 case GE_EXPR: val = (cmp < 0); break;
4958 default:
4959 val = false;
4961 if (val)
4962 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4964 else if (code2 == NE_EXPR)
4966 bool val;
4967 switch (code1)
4969 case EQ_EXPR: val = (cmp == 0); break;
4970 case NE_EXPR: val = (cmp != 0); break;
4971 case LT_EXPR: val = (cmp <= 0); break;
4972 case GT_EXPR: val = (cmp >= 0); break;
4973 case LE_EXPR: val = (cmp < 0); break;
4974 case GE_EXPR: val = (cmp > 0); break;
4975 default:
4976 val = false;
4978 if (val)
4979 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4982 /* Chose the more restrictive of two < or <= comparisons. */
4983 else if ((code1 == LT_EXPR || code1 == LE_EXPR)
4984 && (code2 == LT_EXPR || code2 == LE_EXPR))
4986 if ((cmp < 0) || (cmp == 0 && code1 == LT_EXPR))
4987 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4988 else
4989 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4992 /* Likewise chose the more restrictive of two > or >= comparisons. */
4993 else if ((code1 == GT_EXPR || code1 == GE_EXPR)
4994 && (code2 == GT_EXPR || code2 == GE_EXPR))
4996 if ((cmp > 0) || (cmp == 0 && code1 == GT_EXPR))
4997 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4998 else
4999 return fold_build2 (code2, boolean_type_node, op2a, op2b);
5002 /* Check for singleton ranges. */
5003 else if (cmp == 0
5004 && ((code1 == LE_EXPR && code2 == GE_EXPR)
5005 || (code1 == GE_EXPR && code2 == LE_EXPR)))
5006 return fold_build2 (EQ_EXPR, boolean_type_node, op1a, op2b);
5008 /* Check for disjoint ranges. */
5009 else if (cmp <= 0
5010 && (code1 == LT_EXPR || code1 == LE_EXPR)
5011 && (code2 == GT_EXPR || code2 == GE_EXPR))
5012 return boolean_false_node;
5013 else if (cmp >= 0
5014 && (code1 == GT_EXPR || code1 == GE_EXPR)
5015 && (code2 == LT_EXPR || code2 == LE_EXPR))
5016 return boolean_false_node;
5019 /* Perhaps the first comparison is (NAME != 0) or (NAME == 1) where
5020 NAME's definition is a truth value. See if there are any simplifications
5021 that can be done against the NAME's definition. */
5022 if (TREE_CODE (op1a) == SSA_NAME
5023 && (code1 == NE_EXPR || code1 == EQ_EXPR)
5024 && (integer_zerop (op1b) || integer_onep (op1b)))
5026 bool invert = ((code1 == EQ_EXPR && integer_zerop (op1b))
5027 || (code1 == NE_EXPR && integer_onep (op1b)));
5028 gimple *stmt = SSA_NAME_DEF_STMT (op1a);
5029 switch (gimple_code (stmt))
5031 case GIMPLE_ASSIGN:
5032 /* Try to simplify by copy-propagating the definition. */
5033 return and_var_with_comparison (op1a, invert, code2, op2a, op2b);
5035 case GIMPLE_PHI:
5036 /* If every argument to the PHI produces the same result when
5037 ANDed with the second comparison, we win.
5038 Do not do this unless the type is bool since we need a bool
5039 result here anyway. */
5040 if (TREE_CODE (TREE_TYPE (op1a)) == BOOLEAN_TYPE)
5042 tree result = NULL_TREE;
5043 unsigned i;
5044 for (i = 0; i < gimple_phi_num_args (stmt); i++)
5046 tree arg = gimple_phi_arg_def (stmt, i);
5048 /* If this PHI has itself as an argument, ignore it.
5049 If all the other args produce the same result,
5050 we're still OK. */
5051 if (arg == gimple_phi_result (stmt))
5052 continue;
5053 else if (TREE_CODE (arg) == INTEGER_CST)
5055 if (invert ? integer_nonzerop (arg) : integer_zerop (arg))
5057 if (!result)
5058 result = boolean_false_node;
5059 else if (!integer_zerop (result))
5060 return NULL_TREE;
5062 else if (!result)
5063 result = fold_build2 (code2, boolean_type_node,
5064 op2a, op2b);
5065 else if (!same_bool_comparison_p (result,
5066 code2, op2a, op2b))
5067 return NULL_TREE;
5069 else if (TREE_CODE (arg) == SSA_NAME
5070 && !SSA_NAME_IS_DEFAULT_DEF (arg))
5072 tree temp;
5073 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
5074 /* In simple cases we can look through PHI nodes,
5075 but we have to be careful with loops.
5076 See PR49073. */
5077 if (! dom_info_available_p (CDI_DOMINATORS)
5078 || gimple_bb (def_stmt) == gimple_bb (stmt)
5079 || dominated_by_p (CDI_DOMINATORS,
5080 gimple_bb (def_stmt),
5081 gimple_bb (stmt)))
5082 return NULL_TREE;
5083 temp = and_var_with_comparison (arg, invert, code2,
5084 op2a, op2b);
5085 if (!temp)
5086 return NULL_TREE;
5087 else if (!result)
5088 result = temp;
5089 else if (!same_bool_result_p (result, temp))
5090 return NULL_TREE;
5092 else
5093 return NULL_TREE;
5095 return result;
5098 default:
5099 break;
5102 return NULL_TREE;
5105 /* Try to simplify the AND of two comparisons, specified by
5106 (OP1A CODE1 OP1B) and (OP2B CODE2 OP2B), respectively.
5107 If this can be simplified to a single expression (without requiring
5108 introducing more SSA variables to hold intermediate values),
5109 return the resulting tree. Otherwise return NULL_TREE.
5110 If the result expression is non-null, it has boolean type. */
5112 tree
5113 maybe_fold_and_comparisons (enum tree_code code1, tree op1a, tree op1b,
5114 enum tree_code code2, tree op2a, tree op2b)
5116 tree t = and_comparisons_1 (code1, op1a, op1b, code2, op2a, op2b);
5117 if (t)
5118 return t;
5119 else
5120 return and_comparisons_1 (code2, op2a, op2b, code1, op1a, op1b);
5123 /* Helper function for or_comparisons_1: try to simplify the OR of the
5124 ssa variable VAR with the comparison specified by (OP2A CODE2 OP2B).
5125 If INVERT is true, invert the value of VAR before doing the OR.
5126 Return NULL_EXPR if we can't simplify this to a single expression. */
5128 static tree
5129 or_var_with_comparison (tree var, bool invert,
5130 enum tree_code code2, tree op2a, tree op2b)
5132 tree t;
5133 gimple *stmt = SSA_NAME_DEF_STMT (var);
5135 /* We can only deal with variables whose definitions are assignments. */
5136 if (!is_gimple_assign (stmt))
5137 return NULL_TREE;
5139 /* If we have an inverted comparison, apply DeMorgan's law and rewrite
5140 !var OR (op2a code2 op2b) => !(var AND !(op2a code2 op2b))
5141 Then we only have to consider the simpler non-inverted cases. */
5142 if (invert)
5143 t = and_var_with_comparison_1 (stmt,
5144 invert_tree_comparison (code2, false),
5145 op2a, op2b);
5146 else
5147 t = or_var_with_comparison_1 (stmt, code2, op2a, op2b);
5148 return canonicalize_bool (t, invert);
5151 /* Try to simplify the OR of the ssa variable defined by the assignment
5152 STMT with the comparison specified by (OP2A CODE2 OP2B).
5153 Return NULL_EXPR if we can't simplify this to a single expression. */
5155 static tree
5156 or_var_with_comparison_1 (gimple *stmt,
5157 enum tree_code code2, tree op2a, tree op2b)
5159 tree var = gimple_assign_lhs (stmt);
5160 tree true_test_var = NULL_TREE;
5161 tree false_test_var = NULL_TREE;
5162 enum tree_code innercode = gimple_assign_rhs_code (stmt);
5164 /* Check for identities like (var OR (var != 0)) => true . */
5165 if (TREE_CODE (op2a) == SSA_NAME
5166 && TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE)
5168 if ((code2 == NE_EXPR && integer_zerop (op2b))
5169 || (code2 == EQ_EXPR && integer_nonzerop (op2b)))
5171 true_test_var = op2a;
5172 if (var == true_test_var)
5173 return var;
5175 else if ((code2 == EQ_EXPR && integer_zerop (op2b))
5176 || (code2 == NE_EXPR && integer_nonzerop (op2b)))
5178 false_test_var = op2a;
5179 if (var == false_test_var)
5180 return boolean_true_node;
5184 /* If the definition is a comparison, recurse on it. */
5185 if (TREE_CODE_CLASS (innercode) == tcc_comparison)
5187 tree t = or_comparisons_1 (innercode,
5188 gimple_assign_rhs1 (stmt),
5189 gimple_assign_rhs2 (stmt),
5190 code2,
5191 op2a,
5192 op2b);
5193 if (t)
5194 return t;
5197 /* If the definition is an AND or OR expression, we may be able to
5198 simplify by reassociating. */
5199 if (TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE
5200 && (innercode == BIT_AND_EXPR || innercode == BIT_IOR_EXPR))
5202 tree inner1 = gimple_assign_rhs1 (stmt);
5203 tree inner2 = gimple_assign_rhs2 (stmt);
5204 gimple *s;
5205 tree t;
5206 tree partial = NULL_TREE;
5207 bool is_or = (innercode == BIT_IOR_EXPR);
5209 /* Check for boolean identities that don't require recursive examination
5210 of inner1/inner2:
5211 inner1 OR (inner1 OR inner2) => inner1 OR inner2 => var
5212 inner1 OR (inner1 AND inner2) => inner1
5213 !inner1 OR (inner1 OR inner2) => true
5214 !inner1 OR (inner1 AND inner2) => !inner1 OR inner2
5216 if (inner1 == true_test_var)
5217 return (is_or ? var : inner1);
5218 else if (inner2 == true_test_var)
5219 return (is_or ? var : inner2);
5220 else if (inner1 == false_test_var)
5221 return (is_or
5222 ? boolean_true_node
5223 : or_var_with_comparison (inner2, false, code2, op2a, op2b));
5224 else if (inner2 == false_test_var)
5225 return (is_or
5226 ? boolean_true_node
5227 : or_var_with_comparison (inner1, false, code2, op2a, op2b));
5229 /* Next, redistribute/reassociate the OR across the inner tests.
5230 Compute the first partial result, (inner1 OR (op2a code op2b)) */
5231 if (TREE_CODE (inner1) == SSA_NAME
5232 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner1))
5233 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
5234 && (t = maybe_fold_or_comparisons (gimple_assign_rhs_code (s),
5235 gimple_assign_rhs1 (s),
5236 gimple_assign_rhs2 (s),
5237 code2, op2a, op2b)))
5239 /* Handle the OR case, where we are reassociating:
5240 (inner1 OR inner2) OR (op2a code2 op2b)
5241 => (t OR inner2)
5242 If the partial result t is a constant, we win. Otherwise
5243 continue on to try reassociating with the other inner test. */
5244 if (is_or)
5246 if (integer_onep (t))
5247 return boolean_true_node;
5248 else if (integer_zerop (t))
5249 return inner2;
5252 /* Handle the AND case, where we are redistributing:
5253 (inner1 AND inner2) OR (op2a code2 op2b)
5254 => (t AND (inner2 OR (op2a code op2b))) */
5255 else if (integer_zerop (t))
5256 return boolean_false_node;
5258 /* Save partial result for later. */
5259 partial = t;
5262 /* Compute the second partial result, (inner2 OR (op2a code op2b)) */
5263 if (TREE_CODE (inner2) == SSA_NAME
5264 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner2))
5265 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
5266 && (t = maybe_fold_or_comparisons (gimple_assign_rhs_code (s),
5267 gimple_assign_rhs1 (s),
5268 gimple_assign_rhs2 (s),
5269 code2, op2a, op2b)))
5271 /* Handle the OR case, where we are reassociating:
5272 (inner1 OR inner2) OR (op2a code2 op2b)
5273 => (inner1 OR t)
5274 => (t OR partial) */
5275 if (is_or)
5277 if (integer_zerop (t))
5278 return inner1;
5279 else if (integer_onep (t))
5280 return boolean_true_node;
5281 /* If both are the same, we can apply the identity
5282 (x OR x) == x. */
5283 else if (partial && same_bool_result_p (t, partial))
5284 return t;
5287 /* Handle the AND case, where we are redistributing:
5288 (inner1 AND inner2) OR (op2a code2 op2b)
5289 => (t AND (inner1 OR (op2a code2 op2b)))
5290 => (t AND partial) */
5291 else
5293 if (integer_zerop (t))
5294 return boolean_false_node;
5295 else if (partial)
5297 /* We already got a simplification for the other
5298 operand to the redistributed AND expression. The
5299 interesting case is when at least one is true.
5300 Or, if both are the same, we can apply the identity
5301 (x AND x) == x. */
5302 if (integer_onep (partial))
5303 return t;
5304 else if (integer_onep (t))
5305 return partial;
5306 else if (same_bool_result_p (t, partial))
5307 return t;
5312 return NULL_TREE;
5315 /* Try to simplify the OR of two comparisons defined by
5316 (OP1A CODE1 OP1B) and (OP2A CODE2 OP2B), respectively.
5317 If this can be done without constructing an intermediate value,
5318 return the resulting tree; otherwise NULL_TREE is returned.
5319 This function is deliberately asymmetric as it recurses on SSA_DEFs
5320 in the first comparison but not the second. */
5322 static tree
5323 or_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
5324 enum tree_code code2, tree op2a, tree op2b)
5326 tree truth_type = truth_type_for (TREE_TYPE (op1a));
5328 /* First check for ((x CODE1 y) OR (x CODE2 y)). */
5329 if (operand_equal_p (op1a, op2a, 0)
5330 && operand_equal_p (op1b, op2b, 0))
5332 /* Result will be either NULL_TREE, or a combined comparison. */
5333 tree t = combine_comparisons (UNKNOWN_LOCATION,
5334 TRUTH_ORIF_EXPR, code1, code2,
5335 truth_type, op1a, op1b);
5336 if (t)
5337 return t;
5340 /* Likewise the swapped case of the above. */
5341 if (operand_equal_p (op1a, op2b, 0)
5342 && operand_equal_p (op1b, op2a, 0))
5344 /* Result will be either NULL_TREE, or a combined comparison. */
5345 tree t = combine_comparisons (UNKNOWN_LOCATION,
5346 TRUTH_ORIF_EXPR, code1,
5347 swap_tree_comparison (code2),
5348 truth_type, op1a, op1b);
5349 if (t)
5350 return t;
5353 /* If both comparisons are of the same value against constants, we might
5354 be able to merge them. */
5355 if (operand_equal_p (op1a, op2a, 0)
5356 && TREE_CODE (op1b) == INTEGER_CST
5357 && TREE_CODE (op2b) == INTEGER_CST)
5359 int cmp = tree_int_cst_compare (op1b, op2b);
5361 /* If we have (op1a != op1b), we should either be able to
5362 return that or TRUE, depending on whether the constant op1b
5363 also satisfies the other comparison against op2b. */
5364 if (code1 == NE_EXPR)
5366 bool done = true;
5367 bool val;
5368 switch (code2)
5370 case EQ_EXPR: val = (cmp == 0); break;
5371 case NE_EXPR: val = (cmp != 0); break;
5372 case LT_EXPR: val = (cmp < 0); break;
5373 case GT_EXPR: val = (cmp > 0); break;
5374 case LE_EXPR: val = (cmp <= 0); break;
5375 case GE_EXPR: val = (cmp >= 0); break;
5376 default: done = false;
5378 if (done)
5380 if (val)
5381 return boolean_true_node;
5382 else
5383 return fold_build2 (code1, boolean_type_node, op1a, op1b);
5386 /* Likewise if the second comparison is a != comparison. */
5387 else if (code2 == NE_EXPR)
5389 bool done = true;
5390 bool val;
5391 switch (code1)
5393 case EQ_EXPR: val = (cmp == 0); break;
5394 case NE_EXPR: val = (cmp != 0); break;
5395 case LT_EXPR: val = (cmp > 0); break;
5396 case GT_EXPR: val = (cmp < 0); break;
5397 case LE_EXPR: val = (cmp >= 0); break;
5398 case GE_EXPR: val = (cmp <= 0); break;
5399 default: done = false;
5401 if (done)
5403 if (val)
5404 return boolean_true_node;
5405 else
5406 return fold_build2 (code2, boolean_type_node, op2a, op2b);
5410 /* See if an equality test is redundant with the other comparison. */
5411 else if (code1 == EQ_EXPR)
5413 bool val;
5414 switch (code2)
5416 case EQ_EXPR: val = (cmp == 0); break;
5417 case NE_EXPR: val = (cmp != 0); break;
5418 case LT_EXPR: val = (cmp < 0); break;
5419 case GT_EXPR: val = (cmp > 0); break;
5420 case LE_EXPR: val = (cmp <= 0); break;
5421 case GE_EXPR: val = (cmp >= 0); break;
5422 default:
5423 val = false;
5425 if (val)
5426 return fold_build2 (code2, boolean_type_node, op2a, op2b);
5428 else if (code2 == EQ_EXPR)
5430 bool val;
5431 switch (code1)
5433 case EQ_EXPR: val = (cmp == 0); break;
5434 case NE_EXPR: val = (cmp != 0); break;
5435 case LT_EXPR: val = (cmp > 0); break;
5436 case GT_EXPR: val = (cmp < 0); break;
5437 case LE_EXPR: val = (cmp >= 0); break;
5438 case GE_EXPR: val = (cmp <= 0); break;
5439 default:
5440 val = false;
5442 if (val)
5443 return fold_build2 (code1, boolean_type_node, op1a, op1b);
5446 /* Chose the less restrictive of two < or <= comparisons. */
5447 else if ((code1 == LT_EXPR || code1 == LE_EXPR)
5448 && (code2 == LT_EXPR || code2 == LE_EXPR))
5450 if ((cmp < 0) || (cmp == 0 && code1 == LT_EXPR))
5451 return fold_build2 (code2, boolean_type_node, op2a, op2b);
5452 else
5453 return fold_build2 (code1, boolean_type_node, op1a, op1b);
5456 /* Likewise chose the less restrictive of two > or >= comparisons. */
5457 else if ((code1 == GT_EXPR || code1 == GE_EXPR)
5458 && (code2 == GT_EXPR || code2 == GE_EXPR))
5460 if ((cmp > 0) || (cmp == 0 && code1 == GT_EXPR))
5461 return fold_build2 (code2, boolean_type_node, op2a, op2b);
5462 else
5463 return fold_build2 (code1, boolean_type_node, op1a, op1b);
5466 /* Check for singleton ranges. */
5467 else if (cmp == 0
5468 && ((code1 == LT_EXPR && code2 == GT_EXPR)
5469 || (code1 == GT_EXPR && code2 == LT_EXPR)))
5470 return fold_build2 (NE_EXPR, boolean_type_node, op1a, op2b);
5472 /* Check for less/greater pairs that don't restrict the range at all. */
5473 else if (cmp >= 0
5474 && (code1 == LT_EXPR || code1 == LE_EXPR)
5475 && (code2 == GT_EXPR || code2 == GE_EXPR))
5476 return boolean_true_node;
5477 else if (cmp <= 0
5478 && (code1 == GT_EXPR || code1 == GE_EXPR)
5479 && (code2 == LT_EXPR || code2 == LE_EXPR))
5480 return boolean_true_node;
5483 /* Perhaps the first comparison is (NAME != 0) or (NAME == 1) where
5484 NAME's definition is a truth value. See if there are any simplifications
5485 that can be done against the NAME's definition. */
5486 if (TREE_CODE (op1a) == SSA_NAME
5487 && (code1 == NE_EXPR || code1 == EQ_EXPR)
5488 && (integer_zerop (op1b) || integer_onep (op1b)))
5490 bool invert = ((code1 == EQ_EXPR && integer_zerop (op1b))
5491 || (code1 == NE_EXPR && integer_onep (op1b)));
5492 gimple *stmt = SSA_NAME_DEF_STMT (op1a);
5493 switch (gimple_code (stmt))
5495 case GIMPLE_ASSIGN:
5496 /* Try to simplify by copy-propagating the definition. */
5497 return or_var_with_comparison (op1a, invert, code2, op2a, op2b);
5499 case GIMPLE_PHI:
5500 /* If every argument to the PHI produces the same result when
5501 ORed with the second comparison, we win.
5502 Do not do this unless the type is bool since we need a bool
5503 result here anyway. */
5504 if (TREE_CODE (TREE_TYPE (op1a)) == BOOLEAN_TYPE)
5506 tree result = NULL_TREE;
5507 unsigned i;
5508 for (i = 0; i < gimple_phi_num_args (stmt); i++)
5510 tree arg = gimple_phi_arg_def (stmt, i);
5512 /* If this PHI has itself as an argument, ignore it.
5513 If all the other args produce the same result,
5514 we're still OK. */
5515 if (arg == gimple_phi_result (stmt))
5516 continue;
5517 else if (TREE_CODE (arg) == INTEGER_CST)
5519 if (invert ? integer_zerop (arg) : integer_nonzerop (arg))
5521 if (!result)
5522 result = boolean_true_node;
5523 else if (!integer_onep (result))
5524 return NULL_TREE;
5526 else if (!result)
5527 result = fold_build2 (code2, boolean_type_node,
5528 op2a, op2b);
5529 else if (!same_bool_comparison_p (result,
5530 code2, op2a, op2b))
5531 return NULL_TREE;
5533 else if (TREE_CODE (arg) == SSA_NAME
5534 && !SSA_NAME_IS_DEFAULT_DEF (arg))
5536 tree temp;
5537 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
5538 /* In simple cases we can look through PHI nodes,
5539 but we have to be careful with loops.
5540 See PR49073. */
5541 if (! dom_info_available_p (CDI_DOMINATORS)
5542 || gimple_bb (def_stmt) == gimple_bb (stmt)
5543 || dominated_by_p (CDI_DOMINATORS,
5544 gimple_bb (def_stmt),
5545 gimple_bb (stmt)))
5546 return NULL_TREE;
5547 temp = or_var_with_comparison (arg, invert, code2,
5548 op2a, op2b);
5549 if (!temp)
5550 return NULL_TREE;
5551 else if (!result)
5552 result = temp;
5553 else if (!same_bool_result_p (result, temp))
5554 return NULL_TREE;
5556 else
5557 return NULL_TREE;
5559 return result;
5562 default:
5563 break;
5566 return NULL_TREE;
5569 /* Try to simplify the OR of two comparisons, specified by
5570 (OP1A CODE1 OP1B) and (OP2B CODE2 OP2B), respectively.
5571 If this can be simplified to a single expression (without requiring
5572 introducing more SSA variables to hold intermediate values),
5573 return the resulting tree. Otherwise return NULL_TREE.
5574 If the result expression is non-null, it has boolean type. */
5576 tree
5577 maybe_fold_or_comparisons (enum tree_code code1, tree op1a, tree op1b,
5578 enum tree_code code2, tree op2a, tree op2b)
5580 tree t = or_comparisons_1 (code1, op1a, op1b, code2, op2a, op2b);
5581 if (t)
5582 return t;
5583 else
5584 return or_comparisons_1 (code2, op2a, op2b, code1, op1a, op1b);
5588 /* Fold STMT to a constant using VALUEIZE to valueize SSA names.
5590 Either NULL_TREE, a simplified but non-constant or a constant
5591 is returned.
5593 ??? This should go into a gimple-fold-inline.h file to be eventually
5594 privatized with the single valueize function used in the various TUs
5595 to avoid the indirect function call overhead. */
5597 tree
5598 gimple_fold_stmt_to_constant_1 (gimple *stmt, tree (*valueize) (tree),
5599 tree (*gvalueize) (tree))
5601 code_helper rcode;
5602 tree ops[3] = {};
5603 /* ??? The SSA propagators do not correctly deal with following SSA use-def
5604 edges if there are intermediate VARYING defs. For this reason
5605 do not follow SSA edges here even though SCCVN can technically
5606 just deal fine with that. */
5607 if (gimple_simplify (stmt, &rcode, ops, NULL, gvalueize, valueize))
5609 tree res = NULL_TREE;
5610 if (gimple_simplified_result_is_gimple_val (rcode, ops))
5611 res = ops[0];
5612 else if (mprts_hook)
5613 res = mprts_hook (rcode, gimple_expr_type (stmt), ops);
5614 if (res)
5616 if (dump_file && dump_flags & TDF_DETAILS)
5618 fprintf (dump_file, "Match-and-simplified ");
5619 print_gimple_expr (dump_file, stmt, 0, TDF_SLIM);
5620 fprintf (dump_file, " to ");
5621 print_generic_expr (dump_file, res, 0);
5622 fprintf (dump_file, "\n");
5624 return res;
5628 location_t loc = gimple_location (stmt);
5629 switch (gimple_code (stmt))
5631 case GIMPLE_ASSIGN:
5633 enum tree_code subcode = gimple_assign_rhs_code (stmt);
5635 switch (get_gimple_rhs_class (subcode))
5637 case GIMPLE_SINGLE_RHS:
5639 tree rhs = gimple_assign_rhs1 (stmt);
5640 enum tree_code_class kind = TREE_CODE_CLASS (subcode);
5642 if (TREE_CODE (rhs) == SSA_NAME)
5644 /* If the RHS is an SSA_NAME, return its known constant value,
5645 if any. */
5646 return (*valueize) (rhs);
5648 /* Handle propagating invariant addresses into address
5649 operations. */
5650 else if (TREE_CODE (rhs) == ADDR_EXPR
5651 && !is_gimple_min_invariant (rhs))
5653 HOST_WIDE_INT offset = 0;
5654 tree base;
5655 base = get_addr_base_and_unit_offset_1 (TREE_OPERAND (rhs, 0),
5656 &offset,
5657 valueize);
5658 if (base
5659 && (CONSTANT_CLASS_P (base)
5660 || decl_address_invariant_p (base)))
5661 return build_invariant_address (TREE_TYPE (rhs),
5662 base, offset);
5664 else if (TREE_CODE (rhs) == CONSTRUCTOR
5665 && TREE_CODE (TREE_TYPE (rhs)) == VECTOR_TYPE
5666 && (CONSTRUCTOR_NELTS (rhs)
5667 == TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs))))
5669 unsigned i;
5670 tree val, *vec;
5672 vec = XALLOCAVEC (tree,
5673 TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs)));
5674 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), i, val)
5676 val = (*valueize) (val);
5677 if (TREE_CODE (val) == INTEGER_CST
5678 || TREE_CODE (val) == REAL_CST
5679 || TREE_CODE (val) == FIXED_CST)
5680 vec[i] = val;
5681 else
5682 return NULL_TREE;
5685 return build_vector (TREE_TYPE (rhs), vec);
5687 if (subcode == OBJ_TYPE_REF)
5689 tree val = (*valueize) (OBJ_TYPE_REF_EXPR (rhs));
5690 /* If callee is constant, we can fold away the wrapper. */
5691 if (is_gimple_min_invariant (val))
5692 return val;
5695 if (kind == tcc_reference)
5697 if ((TREE_CODE (rhs) == VIEW_CONVERT_EXPR
5698 || TREE_CODE (rhs) == REALPART_EXPR
5699 || TREE_CODE (rhs) == IMAGPART_EXPR)
5700 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
5702 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
5703 return fold_unary_loc (EXPR_LOCATION (rhs),
5704 TREE_CODE (rhs),
5705 TREE_TYPE (rhs), val);
5707 else if (TREE_CODE (rhs) == BIT_FIELD_REF
5708 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
5710 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
5711 return fold_ternary_loc (EXPR_LOCATION (rhs),
5712 TREE_CODE (rhs),
5713 TREE_TYPE (rhs), val,
5714 TREE_OPERAND (rhs, 1),
5715 TREE_OPERAND (rhs, 2));
5717 else if (TREE_CODE (rhs) == MEM_REF
5718 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
5720 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
5721 if (TREE_CODE (val) == ADDR_EXPR
5722 && is_gimple_min_invariant (val))
5724 tree tem = fold_build2 (MEM_REF, TREE_TYPE (rhs),
5725 unshare_expr (val),
5726 TREE_OPERAND (rhs, 1));
5727 if (tem)
5728 rhs = tem;
5731 return fold_const_aggregate_ref_1 (rhs, valueize);
5733 else if (kind == tcc_declaration)
5734 return get_symbol_constant_value (rhs);
5735 return rhs;
5738 case GIMPLE_UNARY_RHS:
5739 return NULL_TREE;
5741 case GIMPLE_BINARY_RHS:
5742 /* Translate &x + CST into an invariant form suitable for
5743 further propagation. */
5744 if (subcode == POINTER_PLUS_EXPR)
5746 tree op0 = (*valueize) (gimple_assign_rhs1 (stmt));
5747 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
5748 if (TREE_CODE (op0) == ADDR_EXPR
5749 && TREE_CODE (op1) == INTEGER_CST)
5751 tree off = fold_convert (ptr_type_node, op1);
5752 return build_fold_addr_expr_loc
5753 (loc,
5754 fold_build2 (MEM_REF,
5755 TREE_TYPE (TREE_TYPE (op0)),
5756 unshare_expr (op0), off));
5759 /* Canonicalize bool != 0 and bool == 0 appearing after
5760 valueization. While gimple_simplify handles this
5761 it can get confused by the ~X == 1 -> X == 0 transform
5762 which we cant reduce to a SSA name or a constant
5763 (and we have no way to tell gimple_simplify to not
5764 consider those transforms in the first place). */
5765 else if (subcode == EQ_EXPR
5766 || subcode == NE_EXPR)
5768 tree lhs = gimple_assign_lhs (stmt);
5769 tree op0 = gimple_assign_rhs1 (stmt);
5770 if (useless_type_conversion_p (TREE_TYPE (lhs),
5771 TREE_TYPE (op0)))
5773 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
5774 op0 = (*valueize) (op0);
5775 if (TREE_CODE (op0) == INTEGER_CST)
5776 std::swap (op0, op1);
5777 if (TREE_CODE (op1) == INTEGER_CST
5778 && ((subcode == NE_EXPR && integer_zerop (op1))
5779 || (subcode == EQ_EXPR && integer_onep (op1))))
5780 return op0;
5783 return NULL_TREE;
5785 case GIMPLE_TERNARY_RHS:
5787 /* Handle ternary operators that can appear in GIMPLE form. */
5788 tree op0 = (*valueize) (gimple_assign_rhs1 (stmt));
5789 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
5790 tree op2 = (*valueize) (gimple_assign_rhs3 (stmt));
5791 return fold_ternary_loc (loc, subcode,
5792 gimple_expr_type (stmt), op0, op1, op2);
5795 default:
5796 gcc_unreachable ();
5800 case GIMPLE_CALL:
5802 tree fn;
5803 gcall *call_stmt = as_a <gcall *> (stmt);
5805 if (gimple_call_internal_p (stmt))
5807 enum tree_code subcode = ERROR_MARK;
5808 switch (gimple_call_internal_fn (stmt))
5810 case IFN_UBSAN_CHECK_ADD:
5811 subcode = PLUS_EXPR;
5812 break;
5813 case IFN_UBSAN_CHECK_SUB:
5814 subcode = MINUS_EXPR;
5815 break;
5816 case IFN_UBSAN_CHECK_MUL:
5817 subcode = MULT_EXPR;
5818 break;
5819 case IFN_BUILTIN_EXPECT:
5821 tree arg0 = gimple_call_arg (stmt, 0);
5822 tree op0 = (*valueize) (arg0);
5823 if (TREE_CODE (op0) == INTEGER_CST)
5824 return op0;
5825 return NULL_TREE;
5827 default:
5828 return NULL_TREE;
5830 tree arg0 = gimple_call_arg (stmt, 0);
5831 tree arg1 = gimple_call_arg (stmt, 1);
5832 tree op0 = (*valueize) (arg0);
5833 tree op1 = (*valueize) (arg1);
5835 if (TREE_CODE (op0) != INTEGER_CST
5836 || TREE_CODE (op1) != INTEGER_CST)
5838 switch (subcode)
5840 case MULT_EXPR:
5841 /* x * 0 = 0 * x = 0 without overflow. */
5842 if (integer_zerop (op0) || integer_zerop (op1))
5843 return build_zero_cst (TREE_TYPE (arg0));
5844 break;
5845 case MINUS_EXPR:
5846 /* y - y = 0 without overflow. */
5847 if (operand_equal_p (op0, op1, 0))
5848 return build_zero_cst (TREE_TYPE (arg0));
5849 break;
5850 default:
5851 break;
5854 tree res
5855 = fold_binary_loc (loc, subcode, TREE_TYPE (arg0), op0, op1);
5856 if (res
5857 && TREE_CODE (res) == INTEGER_CST
5858 && !TREE_OVERFLOW (res))
5859 return res;
5860 return NULL_TREE;
5863 fn = (*valueize) (gimple_call_fn (stmt));
5864 if (TREE_CODE (fn) == ADDR_EXPR
5865 && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL
5866 && DECL_BUILT_IN (TREE_OPERAND (fn, 0))
5867 && gimple_builtin_call_types_compatible_p (stmt,
5868 TREE_OPERAND (fn, 0)))
5870 tree *args = XALLOCAVEC (tree, gimple_call_num_args (stmt));
5871 tree retval;
5872 unsigned i;
5873 for (i = 0; i < gimple_call_num_args (stmt); ++i)
5874 args[i] = (*valueize) (gimple_call_arg (stmt, i));
5875 retval = fold_builtin_call_array (loc,
5876 gimple_call_return_type (call_stmt),
5877 fn, gimple_call_num_args (stmt), args);
5878 if (retval)
5880 /* fold_call_expr wraps the result inside a NOP_EXPR. */
5881 STRIP_NOPS (retval);
5882 retval = fold_convert (gimple_call_return_type (call_stmt),
5883 retval);
5885 return retval;
5887 return NULL_TREE;
5890 default:
5891 return NULL_TREE;
5895 /* Fold STMT to a constant using VALUEIZE to valueize SSA names.
5896 Returns NULL_TREE if folding to a constant is not possible, otherwise
5897 returns a constant according to is_gimple_min_invariant. */
5899 tree
5900 gimple_fold_stmt_to_constant (gimple *stmt, tree (*valueize) (tree))
5902 tree res = gimple_fold_stmt_to_constant_1 (stmt, valueize);
5903 if (res && is_gimple_min_invariant (res))
5904 return res;
5905 return NULL_TREE;
5909 /* The following set of functions are supposed to fold references using
5910 their constant initializers. */
5912 /* See if we can find constructor defining value of BASE.
5913 When we know the consructor with constant offset (such as
5914 base is array[40] and we do know constructor of array), then
5915 BIT_OFFSET is adjusted accordingly.
5917 As a special case, return error_mark_node when constructor
5918 is not explicitly available, but it is known to be zero
5919 such as 'static const int a;'. */
5920 static tree
5921 get_base_constructor (tree base, HOST_WIDE_INT *bit_offset,
5922 tree (*valueize)(tree))
5924 HOST_WIDE_INT bit_offset2, size, max_size;
5925 bool reverse;
5927 if (TREE_CODE (base) == MEM_REF)
5929 if (!integer_zerop (TREE_OPERAND (base, 1)))
5931 if (!tree_fits_shwi_p (TREE_OPERAND (base, 1)))
5932 return NULL_TREE;
5933 *bit_offset += (mem_ref_offset (base).to_short_addr ()
5934 * BITS_PER_UNIT);
5937 if (valueize
5938 && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
5939 base = valueize (TREE_OPERAND (base, 0));
5940 if (!base || TREE_CODE (base) != ADDR_EXPR)
5941 return NULL_TREE;
5942 base = TREE_OPERAND (base, 0);
5944 else if (valueize
5945 && TREE_CODE (base) == SSA_NAME)
5946 base = valueize (base);
5948 /* Get a CONSTRUCTOR. If BASE is a VAR_DECL, get its
5949 DECL_INITIAL. If BASE is a nested reference into another
5950 ARRAY_REF or COMPONENT_REF, make a recursive call to resolve
5951 the inner reference. */
5952 switch (TREE_CODE (base))
5954 case VAR_DECL:
5955 case CONST_DECL:
5957 tree init = ctor_for_folding (base);
5959 /* Our semantic is exact opposite of ctor_for_folding;
5960 NULL means unknown, while error_mark_node is 0. */
5961 if (init == error_mark_node)
5962 return NULL_TREE;
5963 if (!init)
5964 return error_mark_node;
5965 return init;
5968 case VIEW_CONVERT_EXPR:
5969 return get_base_constructor (TREE_OPERAND (base, 0),
5970 bit_offset, valueize);
5972 case ARRAY_REF:
5973 case COMPONENT_REF:
5974 base = get_ref_base_and_extent (base, &bit_offset2, &size, &max_size,
5975 &reverse);
5976 if (max_size == -1 || size != max_size)
5977 return NULL_TREE;
5978 *bit_offset += bit_offset2;
5979 return get_base_constructor (base, bit_offset, valueize);
5981 case CONSTRUCTOR:
5982 return base;
5984 default:
5985 if (CONSTANT_CLASS_P (base))
5986 return base;
5988 return NULL_TREE;
5992 /* CTOR is CONSTRUCTOR of an array type. Fold reference of type TYPE and size
5993 SIZE to the memory at bit OFFSET. */
5995 static tree
5996 fold_array_ctor_reference (tree type, tree ctor,
5997 unsigned HOST_WIDE_INT offset,
5998 unsigned HOST_WIDE_INT size,
5999 tree from_decl)
6001 offset_int low_bound;
6002 offset_int elt_size;
6003 offset_int access_index;
6004 tree domain_type = NULL_TREE;
6005 HOST_WIDE_INT inner_offset;
6007 /* Compute low bound and elt size. */
6008 if (TREE_CODE (TREE_TYPE (ctor)) == ARRAY_TYPE)
6009 domain_type = TYPE_DOMAIN (TREE_TYPE (ctor));
6010 if (domain_type && TYPE_MIN_VALUE (domain_type))
6012 /* Static constructors for variably sized objects makes no sense. */
6013 if (TREE_CODE (TYPE_MIN_VALUE (domain_type)) != INTEGER_CST)
6014 return NULL_TREE;
6015 low_bound = wi::to_offset (TYPE_MIN_VALUE (domain_type));
6017 else
6018 low_bound = 0;
6019 /* Static constructors for variably sized objects makes no sense. */
6020 if (TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (ctor)))) != INTEGER_CST)
6021 return NULL_TREE;
6022 elt_size = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (ctor))));
6024 /* We can handle only constantly sized accesses that are known to not
6025 be larger than size of array element. */
6026 if (!TYPE_SIZE_UNIT (type)
6027 || TREE_CODE (TYPE_SIZE_UNIT (type)) != INTEGER_CST
6028 || elt_size < wi::to_offset (TYPE_SIZE_UNIT (type))
6029 || elt_size == 0)
6030 return NULL_TREE;
6032 /* Compute the array index we look for. */
6033 access_index = wi::udiv_trunc (offset_int (offset / BITS_PER_UNIT),
6034 elt_size);
6035 access_index += low_bound;
6037 /* And offset within the access. */
6038 inner_offset = offset % (elt_size.to_uhwi () * BITS_PER_UNIT);
6040 /* See if the array field is large enough to span whole access. We do not
6041 care to fold accesses spanning multiple array indexes. */
6042 if (inner_offset + size > elt_size.to_uhwi () * BITS_PER_UNIT)
6043 return NULL_TREE;
6044 if (tree val = get_array_ctor_element_at_index (ctor, access_index))
6045 return fold_ctor_reference (type, val, inner_offset, size, from_decl);
6047 /* When memory is not explicitely mentioned in constructor,
6048 it is 0 (or out of range). */
6049 return build_zero_cst (type);
6052 /* CTOR is CONSTRUCTOR of an aggregate or vector.
6053 Fold reference of type TYPE and size SIZE to the memory at bit OFFSET. */
6055 static tree
6056 fold_nonarray_ctor_reference (tree type, tree ctor,
6057 unsigned HOST_WIDE_INT offset,
6058 unsigned HOST_WIDE_INT size,
6059 tree from_decl)
6061 unsigned HOST_WIDE_INT cnt;
6062 tree cfield, cval;
6064 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), cnt, cfield,
6065 cval)
6067 tree byte_offset = DECL_FIELD_OFFSET (cfield);
6068 tree field_offset = DECL_FIELD_BIT_OFFSET (cfield);
6069 tree field_size = DECL_SIZE (cfield);
6070 offset_int bitoffset;
6071 offset_int bitoffset_end, access_end;
6073 /* Variable sized objects in static constructors makes no sense,
6074 but field_size can be NULL for flexible array members. */
6075 gcc_assert (TREE_CODE (field_offset) == INTEGER_CST
6076 && TREE_CODE (byte_offset) == INTEGER_CST
6077 && (field_size != NULL_TREE
6078 ? TREE_CODE (field_size) == INTEGER_CST
6079 : TREE_CODE (TREE_TYPE (cfield)) == ARRAY_TYPE));
6081 /* Compute bit offset of the field. */
6082 bitoffset = (wi::to_offset (field_offset)
6083 + (wi::to_offset (byte_offset) << LOG2_BITS_PER_UNIT));
6084 /* Compute bit offset where the field ends. */
6085 if (field_size != NULL_TREE)
6086 bitoffset_end = bitoffset + wi::to_offset (field_size);
6087 else
6088 bitoffset_end = 0;
6090 access_end = offset_int (offset) + size;
6092 /* Is there any overlap between [OFFSET, OFFSET+SIZE) and
6093 [BITOFFSET, BITOFFSET_END)? */
6094 if (wi::cmps (access_end, bitoffset) > 0
6095 && (field_size == NULL_TREE
6096 || wi::lts_p (offset, bitoffset_end)))
6098 offset_int inner_offset = offset_int (offset) - bitoffset;
6099 /* We do have overlap. Now see if field is large enough to
6100 cover the access. Give up for accesses spanning multiple
6101 fields. */
6102 if (wi::cmps (access_end, bitoffset_end) > 0)
6103 return NULL_TREE;
6104 if (offset < bitoffset)
6105 return NULL_TREE;
6106 return fold_ctor_reference (type, cval,
6107 inner_offset.to_uhwi (), size,
6108 from_decl);
6111 /* When memory is not explicitely mentioned in constructor, it is 0. */
6112 return build_zero_cst (type);
6115 /* CTOR is value initializing memory, fold reference of type TYPE and size SIZE
6116 to the memory at bit OFFSET. */
6118 tree
6119 fold_ctor_reference (tree type, tree ctor, unsigned HOST_WIDE_INT offset,
6120 unsigned HOST_WIDE_INT size, tree from_decl)
6122 tree ret;
6124 /* We found the field with exact match. */
6125 if (useless_type_conversion_p (type, TREE_TYPE (ctor))
6126 && !offset)
6127 return canonicalize_constructor_val (unshare_expr (ctor), from_decl);
6129 /* We are at the end of walk, see if we can view convert the
6130 result. */
6131 if (!AGGREGATE_TYPE_P (TREE_TYPE (ctor)) && !offset
6132 /* VIEW_CONVERT_EXPR is defined only for matching sizes. */
6133 && !compare_tree_int (TYPE_SIZE (type), size)
6134 && !compare_tree_int (TYPE_SIZE (TREE_TYPE (ctor)), size))
6136 ret = canonicalize_constructor_val (unshare_expr (ctor), from_decl);
6137 ret = fold_unary (VIEW_CONVERT_EXPR, type, ret);
6138 if (ret)
6139 STRIP_USELESS_TYPE_CONVERSION (ret);
6140 return ret;
6142 /* For constants and byte-aligned/sized reads try to go through
6143 native_encode/interpret. */
6144 if (CONSTANT_CLASS_P (ctor)
6145 && BITS_PER_UNIT == 8
6146 && offset % BITS_PER_UNIT == 0
6147 && size % BITS_PER_UNIT == 0
6148 && size <= MAX_BITSIZE_MODE_ANY_MODE)
6150 unsigned char buf[MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT];
6151 int len = native_encode_expr (ctor, buf, size / BITS_PER_UNIT,
6152 offset / BITS_PER_UNIT);
6153 if (len > 0)
6154 return native_interpret_expr (type, buf, len);
6156 if (TREE_CODE (ctor) == CONSTRUCTOR)
6159 if (TREE_CODE (TREE_TYPE (ctor)) == ARRAY_TYPE
6160 || TREE_CODE (TREE_TYPE (ctor)) == VECTOR_TYPE)
6161 return fold_array_ctor_reference (type, ctor, offset, size,
6162 from_decl);
6163 else
6164 return fold_nonarray_ctor_reference (type, ctor, offset, size,
6165 from_decl);
6168 return NULL_TREE;
6171 /* Return the tree representing the element referenced by T if T is an
6172 ARRAY_REF or COMPONENT_REF into constant aggregates valuezing SSA
6173 names using VALUEIZE. Return NULL_TREE otherwise. */
6175 tree
6176 fold_const_aggregate_ref_1 (tree t, tree (*valueize) (tree))
6178 tree ctor, idx, base;
6179 HOST_WIDE_INT offset, size, max_size;
6180 tree tem;
6181 bool reverse;
6183 if (TREE_THIS_VOLATILE (t))
6184 return NULL_TREE;
6186 if (DECL_P (t))
6187 return get_symbol_constant_value (t);
6189 tem = fold_read_from_constant_string (t);
6190 if (tem)
6191 return tem;
6193 switch (TREE_CODE (t))
6195 case ARRAY_REF:
6196 case ARRAY_RANGE_REF:
6197 /* Constant indexes are handled well by get_base_constructor.
6198 Only special case variable offsets.
6199 FIXME: This code can't handle nested references with variable indexes
6200 (they will be handled only by iteration of ccp). Perhaps we can bring
6201 get_ref_base_and_extent here and make it use a valueize callback. */
6202 if (TREE_CODE (TREE_OPERAND (t, 1)) == SSA_NAME
6203 && valueize
6204 && (idx = (*valueize) (TREE_OPERAND (t, 1)))
6205 && TREE_CODE (idx) == INTEGER_CST)
6207 tree low_bound, unit_size;
6209 /* If the resulting bit-offset is constant, track it. */
6210 if ((low_bound = array_ref_low_bound (t),
6211 TREE_CODE (low_bound) == INTEGER_CST)
6212 && (unit_size = array_ref_element_size (t),
6213 tree_fits_uhwi_p (unit_size)))
6215 offset_int woffset
6216 = wi::sext (wi::to_offset (idx) - wi::to_offset (low_bound),
6217 TYPE_PRECISION (TREE_TYPE (idx)));
6219 if (wi::fits_shwi_p (woffset))
6221 offset = woffset.to_shwi ();
6222 /* TODO: This code seems wrong, multiply then check
6223 to see if it fits. */
6224 offset *= tree_to_uhwi (unit_size);
6225 offset *= BITS_PER_UNIT;
6227 base = TREE_OPERAND (t, 0);
6228 ctor = get_base_constructor (base, &offset, valueize);
6229 /* Empty constructor. Always fold to 0. */
6230 if (ctor == error_mark_node)
6231 return build_zero_cst (TREE_TYPE (t));
6232 /* Out of bound array access. Value is undefined,
6233 but don't fold. */
6234 if (offset < 0)
6235 return NULL_TREE;
6236 /* We can not determine ctor. */
6237 if (!ctor)
6238 return NULL_TREE;
6239 return fold_ctor_reference (TREE_TYPE (t), ctor, offset,
6240 tree_to_uhwi (unit_size)
6241 * BITS_PER_UNIT,
6242 base);
6246 /* Fallthru. */
6248 case COMPONENT_REF:
6249 case BIT_FIELD_REF:
6250 case TARGET_MEM_REF:
6251 case MEM_REF:
6252 base = get_ref_base_and_extent (t, &offset, &size, &max_size, &reverse);
6253 ctor = get_base_constructor (base, &offset, valueize);
6255 /* Empty constructor. Always fold to 0. */
6256 if (ctor == error_mark_node)
6257 return build_zero_cst (TREE_TYPE (t));
6258 /* We do not know precise address. */
6259 if (max_size == -1 || max_size != size)
6260 return NULL_TREE;
6261 /* We can not determine ctor. */
6262 if (!ctor)
6263 return NULL_TREE;
6265 /* Out of bound array access. Value is undefined, but don't fold. */
6266 if (offset < 0)
6267 return NULL_TREE;
6269 return fold_ctor_reference (TREE_TYPE (t), ctor, offset, size,
6270 base);
6272 case REALPART_EXPR:
6273 case IMAGPART_EXPR:
6275 tree c = fold_const_aggregate_ref_1 (TREE_OPERAND (t, 0), valueize);
6276 if (c && TREE_CODE (c) == COMPLEX_CST)
6277 return fold_build1_loc (EXPR_LOCATION (t),
6278 TREE_CODE (t), TREE_TYPE (t), c);
6279 break;
6282 default:
6283 break;
6286 return NULL_TREE;
6289 tree
6290 fold_const_aggregate_ref (tree t)
6292 return fold_const_aggregate_ref_1 (t, NULL);
6295 /* Lookup virtual method with index TOKEN in a virtual table V
6296 at OFFSET.
6297 Set CAN_REFER if non-NULL to false if method
6298 is not referable or if the virtual table is ill-formed (such as rewriten
6299 by non-C++ produced symbol). Otherwise just return NULL in that calse. */
6301 tree
6302 gimple_get_virt_method_for_vtable (HOST_WIDE_INT token,
6303 tree v,
6304 unsigned HOST_WIDE_INT offset,
6305 bool *can_refer)
6307 tree vtable = v, init, fn;
6308 unsigned HOST_WIDE_INT size;
6309 unsigned HOST_WIDE_INT elt_size, access_index;
6310 tree domain_type;
6312 if (can_refer)
6313 *can_refer = true;
6315 /* First of all double check we have virtual table. */
6316 if (!VAR_P (v) || !DECL_VIRTUAL_P (v))
6318 /* Pass down that we lost track of the target. */
6319 if (can_refer)
6320 *can_refer = false;
6321 return NULL_TREE;
6324 init = ctor_for_folding (v);
6326 /* The virtual tables should always be born with constructors
6327 and we always should assume that they are avaialble for
6328 folding. At the moment we do not stream them in all cases,
6329 but it should never happen that ctor seem unreachable. */
6330 gcc_assert (init);
6331 if (init == error_mark_node)
6333 gcc_assert (in_lto_p);
6334 /* Pass down that we lost track of the target. */
6335 if (can_refer)
6336 *can_refer = false;
6337 return NULL_TREE;
6339 gcc_checking_assert (TREE_CODE (TREE_TYPE (v)) == ARRAY_TYPE);
6340 size = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (TREE_TYPE (v))));
6341 offset *= BITS_PER_UNIT;
6342 offset += token * size;
6344 /* Lookup the value in the constructor that is assumed to be array.
6345 This is equivalent to
6346 fn = fold_ctor_reference (TREE_TYPE (TREE_TYPE (v)), init,
6347 offset, size, NULL);
6348 but in a constant time. We expect that frontend produced a simple
6349 array without indexed initializers. */
6351 gcc_checking_assert (TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE);
6352 domain_type = TYPE_DOMAIN (TREE_TYPE (init));
6353 gcc_checking_assert (integer_zerop (TYPE_MIN_VALUE (domain_type)));
6354 elt_size = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (init))));
6356 access_index = offset / BITS_PER_UNIT / elt_size;
6357 gcc_checking_assert (offset % (elt_size * BITS_PER_UNIT) == 0);
6359 /* This code makes an assumption that there are no
6360 indexed fileds produced by C++ FE, so we can directly index the array. */
6361 if (access_index < CONSTRUCTOR_NELTS (init))
6363 fn = CONSTRUCTOR_ELT (init, access_index)->value;
6364 gcc_checking_assert (!CONSTRUCTOR_ELT (init, access_index)->index);
6365 STRIP_NOPS (fn);
6367 else
6368 fn = NULL;
6370 /* For type inconsistent program we may end up looking up virtual method
6371 in virtual table that does not contain TOKEN entries. We may overrun
6372 the virtual table and pick up a constant or RTTI info pointer.
6373 In any case the call is undefined. */
6374 if (!fn
6375 || (TREE_CODE (fn) != ADDR_EXPR && TREE_CODE (fn) != FDESC_EXPR)
6376 || TREE_CODE (TREE_OPERAND (fn, 0)) != FUNCTION_DECL)
6377 fn = builtin_decl_implicit (BUILT_IN_UNREACHABLE);
6378 else
6380 fn = TREE_OPERAND (fn, 0);
6382 /* When cgraph node is missing and function is not public, we cannot
6383 devirtualize. This can happen in WHOPR when the actual method
6384 ends up in other partition, because we found devirtualization
6385 possibility too late. */
6386 if (!can_refer_decl_in_current_unit_p (fn, vtable))
6388 if (can_refer)
6390 *can_refer = false;
6391 return fn;
6393 return NULL_TREE;
6397 /* Make sure we create a cgraph node for functions we'll reference.
6398 They can be non-existent if the reference comes from an entry
6399 of an external vtable for example. */
6400 cgraph_node::get_create (fn);
6402 return fn;
6405 /* Return a declaration of a function which an OBJ_TYPE_REF references. TOKEN
6406 is integer form of OBJ_TYPE_REF_TOKEN of the reference expression.
6407 KNOWN_BINFO carries the binfo describing the true type of
6408 OBJ_TYPE_REF_OBJECT(REF).
6409 Set CAN_REFER if non-NULL to false if method
6410 is not referable or if the virtual table is ill-formed (such as rewriten
6411 by non-C++ produced symbol). Otherwise just return NULL in that calse. */
6413 tree
6414 gimple_get_virt_method_for_binfo (HOST_WIDE_INT token, tree known_binfo,
6415 bool *can_refer)
6417 unsigned HOST_WIDE_INT offset;
6418 tree v;
6420 v = BINFO_VTABLE (known_binfo);
6421 /* If there is no virtual methods table, leave the OBJ_TYPE_REF alone. */
6422 if (!v)
6423 return NULL_TREE;
6425 if (!vtable_pointer_value_to_vtable (v, &v, &offset))
6427 if (can_refer)
6428 *can_refer = false;
6429 return NULL_TREE;
6431 return gimple_get_virt_method_for_vtable (token, v, offset, can_refer);
6434 /* Given a pointer value OP0, return a simplified version of an
6435 indirection through OP0, or NULL_TREE if no simplification is
6436 possible. Note that the resulting type may be different from
6437 the type pointed to in the sense that it is still compatible
6438 from the langhooks point of view. */
6440 tree
6441 gimple_fold_indirect_ref (tree t)
6443 tree ptype = TREE_TYPE (t), type = TREE_TYPE (ptype);
6444 tree sub = t;
6445 tree subtype;
6447 STRIP_NOPS (sub);
6448 subtype = TREE_TYPE (sub);
6449 if (!POINTER_TYPE_P (subtype))
6450 return NULL_TREE;
6452 if (TREE_CODE (sub) == ADDR_EXPR)
6454 tree op = TREE_OPERAND (sub, 0);
6455 tree optype = TREE_TYPE (op);
6456 /* *&p => p */
6457 if (useless_type_conversion_p (type, optype))
6458 return op;
6460 /* *(foo *)&fooarray => fooarray[0] */
6461 if (TREE_CODE (optype) == ARRAY_TYPE
6462 && TREE_CODE (TYPE_SIZE (TREE_TYPE (optype))) == INTEGER_CST
6463 && useless_type_conversion_p (type, TREE_TYPE (optype)))
6465 tree type_domain = TYPE_DOMAIN (optype);
6466 tree min_val = size_zero_node;
6467 if (type_domain && TYPE_MIN_VALUE (type_domain))
6468 min_val = TYPE_MIN_VALUE (type_domain);
6469 if (TREE_CODE (min_val) == INTEGER_CST)
6470 return build4 (ARRAY_REF, type, op, min_val, NULL_TREE, NULL_TREE);
6472 /* *(foo *)&complexfoo => __real__ complexfoo */
6473 else if (TREE_CODE (optype) == COMPLEX_TYPE
6474 && useless_type_conversion_p (type, TREE_TYPE (optype)))
6475 return fold_build1 (REALPART_EXPR, type, op);
6476 /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
6477 else if (TREE_CODE (optype) == VECTOR_TYPE
6478 && useless_type_conversion_p (type, TREE_TYPE (optype)))
6480 tree part_width = TYPE_SIZE (type);
6481 tree index = bitsize_int (0);
6482 return fold_build3 (BIT_FIELD_REF, type, op, part_width, index);
6486 /* *(p + CST) -> ... */
6487 if (TREE_CODE (sub) == POINTER_PLUS_EXPR
6488 && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST)
6490 tree addr = TREE_OPERAND (sub, 0);
6491 tree off = TREE_OPERAND (sub, 1);
6492 tree addrtype;
6494 STRIP_NOPS (addr);
6495 addrtype = TREE_TYPE (addr);
6497 /* ((foo*)&vectorfoo)[1] -> BIT_FIELD_REF<vectorfoo,...> */
6498 if (TREE_CODE (addr) == ADDR_EXPR
6499 && TREE_CODE (TREE_TYPE (addrtype)) == VECTOR_TYPE
6500 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (addrtype)))
6501 && tree_fits_uhwi_p (off))
6503 unsigned HOST_WIDE_INT offset = tree_to_uhwi (off);
6504 tree part_width = TYPE_SIZE (type);
6505 unsigned HOST_WIDE_INT part_widthi
6506 = tree_to_shwi (part_width) / BITS_PER_UNIT;
6507 unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT;
6508 tree index = bitsize_int (indexi);
6509 if (offset / part_widthi
6510 < TYPE_VECTOR_SUBPARTS (TREE_TYPE (addrtype)))
6511 return fold_build3 (BIT_FIELD_REF, type, TREE_OPERAND (addr, 0),
6512 part_width, index);
6515 /* ((foo*)&complexfoo)[1] -> __imag__ complexfoo */
6516 if (TREE_CODE (addr) == ADDR_EXPR
6517 && TREE_CODE (TREE_TYPE (addrtype)) == COMPLEX_TYPE
6518 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (addrtype))))
6520 tree size = TYPE_SIZE_UNIT (type);
6521 if (tree_int_cst_equal (size, off))
6522 return fold_build1 (IMAGPART_EXPR, type, TREE_OPERAND (addr, 0));
6525 /* *(p + CST) -> MEM_REF <p, CST>. */
6526 if (TREE_CODE (addr) != ADDR_EXPR
6527 || DECL_P (TREE_OPERAND (addr, 0)))
6528 return fold_build2 (MEM_REF, type,
6529 addr,
6530 wide_int_to_tree (ptype, off));
6533 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
6534 if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
6535 && TREE_CODE (TYPE_SIZE (TREE_TYPE (TREE_TYPE (subtype)))) == INTEGER_CST
6536 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (subtype))))
6538 tree type_domain;
6539 tree min_val = size_zero_node;
6540 tree osub = sub;
6541 sub = gimple_fold_indirect_ref (sub);
6542 if (! sub)
6543 sub = build1 (INDIRECT_REF, TREE_TYPE (subtype), osub);
6544 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
6545 if (type_domain && TYPE_MIN_VALUE (type_domain))
6546 min_val = TYPE_MIN_VALUE (type_domain);
6547 if (TREE_CODE (min_val) == INTEGER_CST)
6548 return build4 (ARRAY_REF, type, sub, min_val, NULL_TREE, NULL_TREE);
6551 return NULL_TREE;
6554 /* Return true if CODE is an operation that when operating on signed
6555 integer types involves undefined behavior on overflow and the
6556 operation can be expressed with unsigned arithmetic. */
6558 bool
6559 arith_code_with_undefined_signed_overflow (tree_code code)
6561 switch (code)
6563 case PLUS_EXPR:
6564 case MINUS_EXPR:
6565 case MULT_EXPR:
6566 case NEGATE_EXPR:
6567 case POINTER_PLUS_EXPR:
6568 return true;
6569 default:
6570 return false;
6574 /* Rewrite STMT, an assignment with a signed integer or pointer arithmetic
6575 operation that can be transformed to unsigned arithmetic by converting
6576 its operand, carrying out the operation in the corresponding unsigned
6577 type and converting the result back to the original type.
6579 Returns a sequence of statements that replace STMT and also contain
6580 a modified form of STMT itself. */
6582 gimple_seq
6583 rewrite_to_defined_overflow (gimple *stmt)
6585 if (dump_file && (dump_flags & TDF_DETAILS))
6587 fprintf (dump_file, "rewriting stmt with undefined signed "
6588 "overflow ");
6589 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
6592 tree lhs = gimple_assign_lhs (stmt);
6593 tree type = unsigned_type_for (TREE_TYPE (lhs));
6594 gimple_seq stmts = NULL;
6595 for (unsigned i = 1; i < gimple_num_ops (stmt); ++i)
6597 tree op = gimple_op (stmt, i);
6598 op = gimple_convert (&stmts, type, op);
6599 gimple_set_op (stmt, i, op);
6601 gimple_assign_set_lhs (stmt, make_ssa_name (type, stmt));
6602 if (gimple_assign_rhs_code (stmt) == POINTER_PLUS_EXPR)
6603 gimple_assign_set_rhs_code (stmt, PLUS_EXPR);
6604 gimple_seq_add_stmt (&stmts, stmt);
6605 gimple *cvt = gimple_build_assign (lhs, NOP_EXPR, gimple_assign_lhs (stmt));
6606 gimple_seq_add_stmt (&stmts, cvt);
6608 return stmts;
6612 /* The valueization hook we use for the gimple_build API simplification.
6613 This makes us match fold_buildN behavior by only combining with
6614 statements in the sequence(s) we are currently building. */
6616 static tree
6617 gimple_build_valueize (tree op)
6619 if (gimple_bb (SSA_NAME_DEF_STMT (op)) == NULL)
6620 return op;
6621 return NULL_TREE;
6624 /* Build the expression CODE OP0 of type TYPE with location LOC,
6625 simplifying it first if possible. Returns the built
6626 expression value and appends statements possibly defining it
6627 to SEQ. */
6629 tree
6630 gimple_build (gimple_seq *seq, location_t loc,
6631 enum tree_code code, tree type, tree op0)
6633 tree res = gimple_simplify (code, type, op0, seq, gimple_build_valueize);
6634 if (!res)
6636 res = create_tmp_reg_or_ssa_name (type);
6637 gimple *stmt;
6638 if (code == REALPART_EXPR
6639 || code == IMAGPART_EXPR
6640 || code == VIEW_CONVERT_EXPR)
6641 stmt = gimple_build_assign (res, code, build1 (code, type, op0));
6642 else
6643 stmt = gimple_build_assign (res, code, op0);
6644 gimple_set_location (stmt, loc);
6645 gimple_seq_add_stmt_without_update (seq, stmt);
6647 return res;
6650 /* Build the expression OP0 CODE OP1 of type TYPE with location LOC,
6651 simplifying it first if possible. Returns the built
6652 expression value and appends statements possibly defining it
6653 to SEQ. */
6655 tree
6656 gimple_build (gimple_seq *seq, location_t loc,
6657 enum tree_code code, tree type, tree op0, tree op1)
6659 tree res = gimple_simplify (code, type, op0, op1, seq, gimple_build_valueize);
6660 if (!res)
6662 res = create_tmp_reg_or_ssa_name (type);
6663 gimple *stmt = gimple_build_assign (res, code, op0, op1);
6664 gimple_set_location (stmt, loc);
6665 gimple_seq_add_stmt_without_update (seq, stmt);
6667 return res;
6670 /* Build the expression (CODE OP0 OP1 OP2) of type TYPE with location LOC,
6671 simplifying it first if possible. Returns the built
6672 expression value and appends statements possibly defining it
6673 to SEQ. */
6675 tree
6676 gimple_build (gimple_seq *seq, location_t loc,
6677 enum tree_code code, tree type, tree op0, tree op1, tree op2)
6679 tree res = gimple_simplify (code, type, op0, op1, op2,
6680 seq, gimple_build_valueize);
6681 if (!res)
6683 res = create_tmp_reg_or_ssa_name (type);
6684 gimple *stmt;
6685 if (code == BIT_FIELD_REF)
6686 stmt = gimple_build_assign (res, code,
6687 build3 (code, type, op0, op1, op2));
6688 else
6689 stmt = gimple_build_assign (res, code, op0, op1, op2);
6690 gimple_set_location (stmt, loc);
6691 gimple_seq_add_stmt_without_update (seq, stmt);
6693 return res;
6696 /* Build the call FN (ARG0) with a result of type TYPE
6697 (or no result if TYPE is void) with location LOC,
6698 simplifying it first if possible. Returns the built
6699 expression value (or NULL_TREE if TYPE is void) and appends
6700 statements possibly defining it to SEQ. */
6702 tree
6703 gimple_build (gimple_seq *seq, location_t loc,
6704 enum built_in_function fn, tree type, tree arg0)
6706 tree res = gimple_simplify (fn, type, arg0, seq, gimple_build_valueize);
6707 if (!res)
6709 tree decl = builtin_decl_implicit (fn);
6710 gimple *stmt = gimple_build_call (decl, 1, arg0);
6711 if (!VOID_TYPE_P (type))
6713 res = create_tmp_reg_or_ssa_name (type);
6714 gimple_call_set_lhs (stmt, res);
6716 gimple_set_location (stmt, loc);
6717 gimple_seq_add_stmt_without_update (seq, stmt);
6719 return res;
6722 /* Build the call FN (ARG0, ARG1) with a result of type TYPE
6723 (or no result if TYPE is void) with location LOC,
6724 simplifying it first if possible. Returns the built
6725 expression value (or NULL_TREE if TYPE is void) and appends
6726 statements possibly defining it to SEQ. */
6728 tree
6729 gimple_build (gimple_seq *seq, location_t loc,
6730 enum built_in_function fn, tree type, tree arg0, tree arg1)
6732 tree res = gimple_simplify (fn, type, arg0, arg1, seq, gimple_build_valueize);
6733 if (!res)
6735 tree decl = builtin_decl_implicit (fn);
6736 gimple *stmt = gimple_build_call (decl, 2, arg0, arg1);
6737 if (!VOID_TYPE_P (type))
6739 res = create_tmp_reg_or_ssa_name (type);
6740 gimple_call_set_lhs (stmt, res);
6742 gimple_set_location (stmt, loc);
6743 gimple_seq_add_stmt_without_update (seq, stmt);
6745 return res;
6748 /* Build the call FN (ARG0, ARG1, ARG2) with a result of type TYPE
6749 (or no result if TYPE is void) with location LOC,
6750 simplifying it first if possible. Returns the built
6751 expression value (or NULL_TREE if TYPE is void) and appends
6752 statements possibly defining it to SEQ. */
6754 tree
6755 gimple_build (gimple_seq *seq, location_t loc,
6756 enum built_in_function fn, tree type,
6757 tree arg0, tree arg1, tree arg2)
6759 tree res = gimple_simplify (fn, type, arg0, arg1, arg2,
6760 seq, gimple_build_valueize);
6761 if (!res)
6763 tree decl = builtin_decl_implicit (fn);
6764 gimple *stmt = gimple_build_call (decl, 3, arg0, arg1, arg2);
6765 if (!VOID_TYPE_P (type))
6767 res = create_tmp_reg_or_ssa_name (type);
6768 gimple_call_set_lhs (stmt, res);
6770 gimple_set_location (stmt, loc);
6771 gimple_seq_add_stmt_without_update (seq, stmt);
6773 return res;
6776 /* Build the conversion (TYPE) OP with a result of type TYPE
6777 with location LOC if such conversion is neccesary in GIMPLE,
6778 simplifying it first.
6779 Returns the built expression value and appends
6780 statements possibly defining it to SEQ. */
6782 tree
6783 gimple_convert (gimple_seq *seq, location_t loc, tree type, tree op)
6785 if (useless_type_conversion_p (type, TREE_TYPE (op)))
6786 return op;
6787 return gimple_build (seq, loc, NOP_EXPR, type, op);
6790 /* Build the conversion (ptrofftype) OP with a result of a type
6791 compatible with ptrofftype with location LOC if such conversion
6792 is neccesary in GIMPLE, simplifying it first.
6793 Returns the built expression value and appends
6794 statements possibly defining it to SEQ. */
6796 tree
6797 gimple_convert_to_ptrofftype (gimple_seq *seq, location_t loc, tree op)
6799 if (ptrofftype_p (TREE_TYPE (op)))
6800 return op;
6801 return gimple_convert (seq, loc, sizetype, op);
6804 /* Return true if the result of assignment STMT is known to be non-negative.
6805 If the return value is based on the assumption that signed overflow is
6806 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
6807 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
6809 static bool
6810 gimple_assign_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
6811 int depth)
6813 enum tree_code code = gimple_assign_rhs_code (stmt);
6814 switch (get_gimple_rhs_class (code))
6816 case GIMPLE_UNARY_RHS:
6817 return tree_unary_nonnegative_warnv_p (gimple_assign_rhs_code (stmt),
6818 gimple_expr_type (stmt),
6819 gimple_assign_rhs1 (stmt),
6820 strict_overflow_p, depth);
6821 case GIMPLE_BINARY_RHS:
6822 return tree_binary_nonnegative_warnv_p (gimple_assign_rhs_code (stmt),
6823 gimple_expr_type (stmt),
6824 gimple_assign_rhs1 (stmt),
6825 gimple_assign_rhs2 (stmt),
6826 strict_overflow_p, depth);
6827 case GIMPLE_TERNARY_RHS:
6828 return false;
6829 case GIMPLE_SINGLE_RHS:
6830 return tree_single_nonnegative_warnv_p (gimple_assign_rhs1 (stmt),
6831 strict_overflow_p, depth);
6832 case GIMPLE_INVALID_RHS:
6833 break;
6835 gcc_unreachable ();
6838 /* Return true if return value of call STMT is known to be non-negative.
6839 If the return value is based on the assumption that signed overflow is
6840 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
6841 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
6843 static bool
6844 gimple_call_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
6845 int depth)
6847 tree arg0 = gimple_call_num_args (stmt) > 0 ?
6848 gimple_call_arg (stmt, 0) : NULL_TREE;
6849 tree arg1 = gimple_call_num_args (stmt) > 1 ?
6850 gimple_call_arg (stmt, 1) : NULL_TREE;
6852 return tree_call_nonnegative_warnv_p (gimple_expr_type (stmt),
6853 gimple_call_combined_fn (stmt),
6854 arg0,
6855 arg1,
6856 strict_overflow_p, depth);
6859 /* Return true if return value of call STMT is known to be non-negative.
6860 If the return value is based on the assumption that signed overflow is
6861 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
6862 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
6864 static bool
6865 gimple_phi_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
6866 int depth)
6868 for (unsigned i = 0; i < gimple_phi_num_args (stmt); ++i)
6870 tree arg = gimple_phi_arg_def (stmt, i);
6871 if (!tree_single_nonnegative_warnv_p (arg, strict_overflow_p, depth + 1))
6872 return false;
6874 return true;
6877 /* Return true if STMT is known to compute a non-negative value.
6878 If the return value is based on the assumption that signed overflow is
6879 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
6880 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
6882 bool
6883 gimple_stmt_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
6884 int depth)
6886 switch (gimple_code (stmt))
6888 case GIMPLE_ASSIGN:
6889 return gimple_assign_nonnegative_warnv_p (stmt, strict_overflow_p,
6890 depth);
6891 case GIMPLE_CALL:
6892 return gimple_call_nonnegative_warnv_p (stmt, strict_overflow_p,
6893 depth);
6894 case GIMPLE_PHI:
6895 return gimple_phi_nonnegative_warnv_p (stmt, strict_overflow_p,
6896 depth);
6897 default:
6898 return false;
6902 /* Return true if the floating-point value computed by assignment STMT
6903 is known to have an integer value. We also allow +Inf, -Inf and NaN
6904 to be considered integer values. Return false for signaling NaN.
6906 DEPTH is the current nesting depth of the query. */
6908 static bool
6909 gimple_assign_integer_valued_real_p (gimple *stmt, int depth)
6911 enum tree_code code = gimple_assign_rhs_code (stmt);
6912 switch (get_gimple_rhs_class (code))
6914 case GIMPLE_UNARY_RHS:
6915 return integer_valued_real_unary_p (gimple_assign_rhs_code (stmt),
6916 gimple_assign_rhs1 (stmt), depth);
6917 case GIMPLE_BINARY_RHS:
6918 return integer_valued_real_binary_p (gimple_assign_rhs_code (stmt),
6919 gimple_assign_rhs1 (stmt),
6920 gimple_assign_rhs2 (stmt), depth);
6921 case GIMPLE_TERNARY_RHS:
6922 return false;
6923 case GIMPLE_SINGLE_RHS:
6924 return integer_valued_real_single_p (gimple_assign_rhs1 (stmt), depth);
6925 case GIMPLE_INVALID_RHS:
6926 break;
6928 gcc_unreachable ();
6931 /* Return true if the floating-point value computed by call STMT is known
6932 to have an integer value. We also allow +Inf, -Inf and NaN to be
6933 considered integer values. Return false for signaling NaN.
6935 DEPTH is the current nesting depth of the query. */
6937 static bool
6938 gimple_call_integer_valued_real_p (gimple *stmt, int depth)
6940 tree arg0 = (gimple_call_num_args (stmt) > 0
6941 ? gimple_call_arg (stmt, 0)
6942 : NULL_TREE);
6943 tree arg1 = (gimple_call_num_args (stmt) > 1
6944 ? gimple_call_arg (stmt, 1)
6945 : NULL_TREE);
6946 return integer_valued_real_call_p (gimple_call_combined_fn (stmt),
6947 arg0, arg1, depth);
6950 /* Return true if the floating-point result of phi STMT is known to have
6951 an integer value. We also allow +Inf, -Inf and NaN to be considered
6952 integer values. Return false for signaling NaN.
6954 DEPTH is the current nesting depth of the query. */
6956 static bool
6957 gimple_phi_integer_valued_real_p (gimple *stmt, int depth)
6959 for (unsigned i = 0; i < gimple_phi_num_args (stmt); ++i)
6961 tree arg = gimple_phi_arg_def (stmt, i);
6962 if (!integer_valued_real_single_p (arg, depth + 1))
6963 return false;
6965 return true;
6968 /* Return true if the floating-point value computed by STMT is known
6969 to have an integer value. We also allow +Inf, -Inf and NaN to be
6970 considered integer values. Return false for signaling NaN.
6972 DEPTH is the current nesting depth of the query. */
6974 bool
6975 gimple_stmt_integer_valued_real_p (gimple *stmt, int depth)
6977 switch (gimple_code (stmt))
6979 case GIMPLE_ASSIGN:
6980 return gimple_assign_integer_valued_real_p (stmt, depth);
6981 case GIMPLE_CALL:
6982 return gimple_call_integer_valued_real_p (stmt, depth);
6983 case GIMPLE_PHI:
6984 return gimple_phi_integer_valued_real_p (stmt, depth);
6985 default:
6986 return false;