LTO: display file name if LTO version check fails
[official-gcc.git] / gcc / gimple-fold.c
blobd3968e98620c121c42d32f06548ba73ac622214d
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"
59 /* Return true when DECL can be referenced from current unit.
60 FROM_DECL (if non-null) specify constructor of variable DECL was taken from.
61 We can get declarations that are not possible to reference for various
62 reasons:
64 1) When analyzing C++ virtual tables.
65 C++ virtual tables do have known constructors even
66 when they are keyed to other compilation unit.
67 Those tables can contain pointers to methods and vars
68 in other units. Those methods have both STATIC and EXTERNAL
69 set.
70 2) In WHOPR mode devirtualization might lead to reference
71 to method that was partitioned elsehwere.
72 In this case we have static VAR_DECL or FUNCTION_DECL
73 that has no corresponding callgraph/varpool node
74 declaring the body.
75 3) COMDAT functions referred by external vtables that
76 we devirtualize only during final compilation stage.
77 At this time we already decided that we will not output
78 the function body and thus we can't reference the symbol
79 directly. */
81 static bool
82 can_refer_decl_in_current_unit_p (tree decl, tree from_decl)
84 varpool_node *vnode;
85 struct cgraph_node *node;
86 symtab_node *snode;
88 if (DECL_ABSTRACT_P (decl))
89 return false;
91 /* We are concerned only about static/external vars and functions. */
92 if ((!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
93 || (TREE_CODE (decl) != VAR_DECL && TREE_CODE (decl) != FUNCTION_DECL))
94 return true;
96 /* Static objects can be referred only if they was not optimized out yet. */
97 if (!TREE_PUBLIC (decl) && !DECL_EXTERNAL (decl))
99 /* Before we start optimizing unreachable code we can be sure all
100 static objects are defined. */
101 if (symtab->function_flags_ready)
102 return true;
103 snode = symtab_node::get (decl);
104 if (!snode || !snode->definition)
105 return false;
106 node = dyn_cast <cgraph_node *> (snode);
107 return !node || !node->global.inlined_to;
110 /* We will later output the initializer, so we can refer to it.
111 So we are concerned only when DECL comes from initializer of
112 external var or var that has been optimized out. */
113 if (!from_decl
114 || TREE_CODE (from_decl) != VAR_DECL
115 || (!DECL_EXTERNAL (from_decl)
116 && (vnode = varpool_node::get (from_decl)) != NULL
117 && vnode->definition)
118 || (flag_ltrans
119 && (vnode = varpool_node::get (from_decl)) != NULL
120 && vnode->in_other_partition))
121 return true;
122 /* We are folding reference from external vtable. The vtable may reffer
123 to a symbol keyed to other compilation unit. The other compilation
124 unit may be in separate DSO and the symbol may be hidden. */
125 if (DECL_VISIBILITY_SPECIFIED (decl)
126 && DECL_EXTERNAL (decl)
127 && DECL_VISIBILITY (decl) != VISIBILITY_DEFAULT
128 && (!(snode = symtab_node::get (decl)) || !snode->in_other_partition))
129 return false;
130 /* When function is public, we always can introduce new reference.
131 Exception are the COMDAT functions where introducing a direct
132 reference imply need to include function body in the curren tunit. */
133 if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl))
134 return true;
135 /* We have COMDAT. We are going to check if we still have definition
136 or if the definition is going to be output in other partition.
137 Bypass this when gimplifying; all needed functions will be produced.
139 As observed in PR20991 for already optimized out comdat virtual functions
140 it may be tempting to not necessarily give up because the copy will be
141 output elsewhere when corresponding vtable is output.
142 This is however not possible - ABI specify that COMDATs are output in
143 units where they are used and when the other unit was compiled with LTO
144 it is possible that vtable was kept public while the function itself
145 was privatized. */
146 if (!symtab->function_flags_ready)
147 return true;
149 snode = symtab_node::get (decl);
150 if (!snode
151 || ((!snode->definition || DECL_EXTERNAL (decl))
152 && (!snode->in_other_partition
153 || (!snode->forced_by_abi && !snode->force_output))))
154 return false;
155 node = dyn_cast <cgraph_node *> (snode);
156 return !node || !node->global.inlined_to;
159 /* CVAL is value taken from DECL_INITIAL of variable. Try to transform it into
160 acceptable form for is_gimple_min_invariant.
161 FROM_DECL (if non-NULL) specify variable whose constructor contains CVAL. */
163 tree
164 canonicalize_constructor_val (tree cval, tree from_decl)
166 tree orig_cval = cval;
167 STRIP_NOPS (cval);
168 if (TREE_CODE (cval) == POINTER_PLUS_EXPR
169 && TREE_CODE (TREE_OPERAND (cval, 1)) == INTEGER_CST)
171 tree ptr = TREE_OPERAND (cval, 0);
172 if (is_gimple_min_invariant (ptr))
173 cval = build1_loc (EXPR_LOCATION (cval),
174 ADDR_EXPR, TREE_TYPE (ptr),
175 fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (ptr)),
176 ptr,
177 fold_convert (ptr_type_node,
178 TREE_OPERAND (cval, 1))));
180 if (TREE_CODE (cval) == ADDR_EXPR)
182 tree base = NULL_TREE;
183 if (TREE_CODE (TREE_OPERAND (cval, 0)) == COMPOUND_LITERAL_EXPR)
185 base = COMPOUND_LITERAL_EXPR_DECL (TREE_OPERAND (cval, 0));
186 if (base)
187 TREE_OPERAND (cval, 0) = base;
189 else
190 base = get_base_address (TREE_OPERAND (cval, 0));
191 if (!base)
192 return NULL_TREE;
194 if ((TREE_CODE (base) == VAR_DECL
195 || TREE_CODE (base) == FUNCTION_DECL)
196 && !can_refer_decl_in_current_unit_p (base, from_decl))
197 return NULL_TREE;
198 if (TREE_TYPE (base) == error_mark_node)
199 return NULL_TREE;
200 if (TREE_CODE (base) == VAR_DECL)
201 TREE_ADDRESSABLE (base) = 1;
202 else if (TREE_CODE (base) == FUNCTION_DECL)
204 /* Make sure we create a cgraph node for functions we'll reference.
205 They can be non-existent if the reference comes from an entry
206 of an external vtable for example. */
207 cgraph_node::get_create (base);
209 /* Fixup types in global initializers. */
210 if (TREE_TYPE (TREE_TYPE (cval)) != TREE_TYPE (TREE_OPERAND (cval, 0)))
211 cval = build_fold_addr_expr (TREE_OPERAND (cval, 0));
213 if (!useless_type_conversion_p (TREE_TYPE (orig_cval), TREE_TYPE (cval)))
214 cval = fold_convert (TREE_TYPE (orig_cval), cval);
215 return cval;
217 if (TREE_OVERFLOW_P (cval))
218 return drop_tree_overflow (cval);
219 return orig_cval;
222 /* If SYM is a constant variable with known value, return the value.
223 NULL_TREE is returned otherwise. */
225 tree
226 get_symbol_constant_value (tree sym)
228 tree val = ctor_for_folding (sym);
229 if (val != error_mark_node)
231 if (val)
233 val = canonicalize_constructor_val (unshare_expr (val), sym);
234 if (val && is_gimple_min_invariant (val))
235 return val;
236 else
237 return NULL_TREE;
239 /* Variables declared 'const' without an initializer
240 have zero as the initializer if they may not be
241 overridden at link or run time. */
242 if (!val
243 && is_gimple_reg_type (TREE_TYPE (sym)))
244 return build_zero_cst (TREE_TYPE (sym));
247 return NULL_TREE;
252 /* Subroutine of fold_stmt. We perform several simplifications of the
253 memory reference tree EXPR and make sure to re-gimplify them properly
254 after propagation of constant addresses. IS_LHS is true if the
255 reference is supposed to be an lvalue. */
257 static tree
258 maybe_fold_reference (tree expr, bool is_lhs)
260 tree result;
262 if ((TREE_CODE (expr) == VIEW_CONVERT_EXPR
263 || TREE_CODE (expr) == REALPART_EXPR
264 || TREE_CODE (expr) == IMAGPART_EXPR)
265 && CONSTANT_CLASS_P (TREE_OPERAND (expr, 0)))
266 return fold_unary_loc (EXPR_LOCATION (expr),
267 TREE_CODE (expr),
268 TREE_TYPE (expr),
269 TREE_OPERAND (expr, 0));
270 else if (TREE_CODE (expr) == BIT_FIELD_REF
271 && CONSTANT_CLASS_P (TREE_OPERAND (expr, 0)))
272 return fold_ternary_loc (EXPR_LOCATION (expr),
273 TREE_CODE (expr),
274 TREE_TYPE (expr),
275 TREE_OPERAND (expr, 0),
276 TREE_OPERAND (expr, 1),
277 TREE_OPERAND (expr, 2));
279 if (!is_lhs
280 && (result = fold_const_aggregate_ref (expr))
281 && is_gimple_min_invariant (result))
282 return result;
284 return NULL_TREE;
288 /* Attempt to fold an assignment statement pointed-to by SI. Returns a
289 replacement rhs for the statement or NULL_TREE if no simplification
290 could be made. It is assumed that the operands have been previously
291 folded. */
293 static tree
294 fold_gimple_assign (gimple_stmt_iterator *si)
296 gimple *stmt = gsi_stmt (*si);
297 enum tree_code subcode = gimple_assign_rhs_code (stmt);
298 location_t loc = gimple_location (stmt);
300 tree result = NULL_TREE;
302 switch (get_gimple_rhs_class (subcode))
304 case GIMPLE_SINGLE_RHS:
306 tree rhs = gimple_assign_rhs1 (stmt);
308 if (TREE_CLOBBER_P (rhs))
309 return NULL_TREE;
311 if (REFERENCE_CLASS_P (rhs))
312 return maybe_fold_reference (rhs, false);
314 else if (TREE_CODE (rhs) == OBJ_TYPE_REF)
316 tree val = OBJ_TYPE_REF_EXPR (rhs);
317 if (is_gimple_min_invariant (val))
318 return val;
319 else if (flag_devirtualize && virtual_method_call_p (rhs))
321 bool final;
322 vec <cgraph_node *>targets
323 = possible_polymorphic_call_targets (rhs, stmt, &final);
324 if (final && targets.length () <= 1 && dbg_cnt (devirt))
326 if (dump_enabled_p ())
328 location_t loc = gimple_location_safe (stmt);
329 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, loc,
330 "resolving virtual function address "
331 "reference to function %s\n",
332 targets.length () == 1
333 ? targets[0]->name ()
334 : "NULL");
336 if (targets.length () == 1)
338 val = fold_convert (TREE_TYPE (val),
339 build_fold_addr_expr_loc
340 (loc, targets[0]->decl));
341 STRIP_USELESS_TYPE_CONVERSION (val);
343 else
344 /* We can not use __builtin_unreachable here because it
345 can not have address taken. */
346 val = build_int_cst (TREE_TYPE (val), 0);
347 return val;
352 else if (TREE_CODE (rhs) == ADDR_EXPR)
354 tree ref = TREE_OPERAND (rhs, 0);
355 tree tem = maybe_fold_reference (ref, true);
356 if (tem
357 && TREE_CODE (tem) == MEM_REF
358 && integer_zerop (TREE_OPERAND (tem, 1)))
359 result = fold_convert (TREE_TYPE (rhs), TREE_OPERAND (tem, 0));
360 else if (tem)
361 result = fold_convert (TREE_TYPE (rhs),
362 build_fold_addr_expr_loc (loc, tem));
363 else if (TREE_CODE (ref) == MEM_REF
364 && integer_zerop (TREE_OPERAND (ref, 1)))
365 result = fold_convert (TREE_TYPE (rhs), TREE_OPERAND (ref, 0));
367 if (result)
369 /* Strip away useless type conversions. Both the
370 NON_LVALUE_EXPR that may have been added by fold, and
371 "useless" type conversions that might now be apparent
372 due to propagation. */
373 STRIP_USELESS_TYPE_CONVERSION (result);
375 if (result != rhs && valid_gimple_rhs_p (result))
376 return result;
380 else if (TREE_CODE (rhs) == CONSTRUCTOR
381 && TREE_CODE (TREE_TYPE (rhs)) == VECTOR_TYPE)
383 /* Fold a constant vector CONSTRUCTOR to VECTOR_CST. */
384 unsigned i;
385 tree val;
387 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), i, val)
388 if (! CONSTANT_CLASS_P (val))
389 return NULL_TREE;
391 return build_vector_from_ctor (TREE_TYPE (rhs),
392 CONSTRUCTOR_ELTS (rhs));
395 else if (DECL_P (rhs))
396 return get_symbol_constant_value (rhs);
398 break;
400 case GIMPLE_UNARY_RHS:
401 break;
403 case GIMPLE_BINARY_RHS:
404 break;
406 case GIMPLE_TERNARY_RHS:
407 result = fold_ternary_loc (loc, subcode,
408 TREE_TYPE (gimple_assign_lhs (stmt)),
409 gimple_assign_rhs1 (stmt),
410 gimple_assign_rhs2 (stmt),
411 gimple_assign_rhs3 (stmt));
413 if (result)
415 STRIP_USELESS_TYPE_CONVERSION (result);
416 if (valid_gimple_rhs_p (result))
417 return result;
419 break;
421 case GIMPLE_INVALID_RHS:
422 gcc_unreachable ();
425 return NULL_TREE;
429 /* Replace a statement at *SI_P with a sequence of statements in STMTS,
430 adjusting the replacement stmts location and virtual operands.
431 If the statement has a lhs the last stmt in the sequence is expected
432 to assign to that lhs. */
434 static void
435 gsi_replace_with_seq_vops (gimple_stmt_iterator *si_p, gimple_seq stmts)
437 gimple *stmt = gsi_stmt (*si_p);
439 if (gimple_has_location (stmt))
440 annotate_all_with_location (stmts, gimple_location (stmt));
442 /* First iterate over the replacement statements backward, assigning
443 virtual operands to their defining statements. */
444 gimple *laststore = NULL;
445 for (gimple_stmt_iterator i = gsi_last (stmts);
446 !gsi_end_p (i); gsi_prev (&i))
448 gimple *new_stmt = gsi_stmt (i);
449 if ((gimple_assign_single_p (new_stmt)
450 && !is_gimple_reg (gimple_assign_lhs (new_stmt)))
451 || (is_gimple_call (new_stmt)
452 && (gimple_call_flags (new_stmt)
453 & (ECF_NOVOPS | ECF_PURE | ECF_CONST | ECF_NORETURN)) == 0))
455 tree vdef;
456 if (!laststore)
457 vdef = gimple_vdef (stmt);
458 else
459 vdef = make_ssa_name (gimple_vop (cfun), new_stmt);
460 gimple_set_vdef (new_stmt, vdef);
461 if (vdef && TREE_CODE (vdef) == SSA_NAME)
462 SSA_NAME_DEF_STMT (vdef) = new_stmt;
463 laststore = new_stmt;
467 /* Second iterate over the statements forward, assigning virtual
468 operands to their uses. */
469 tree reaching_vuse = gimple_vuse (stmt);
470 for (gimple_stmt_iterator i = gsi_start (stmts);
471 !gsi_end_p (i); gsi_next (&i))
473 gimple *new_stmt = gsi_stmt (i);
474 /* If the new statement possibly has a VUSE, update it with exact SSA
475 name we know will reach this one. */
476 if (gimple_has_mem_ops (new_stmt))
477 gimple_set_vuse (new_stmt, reaching_vuse);
478 gimple_set_modified (new_stmt, true);
479 if (gimple_vdef (new_stmt))
480 reaching_vuse = gimple_vdef (new_stmt);
483 /* If the new sequence does not do a store release the virtual
484 definition of the original statement. */
485 if (reaching_vuse
486 && reaching_vuse == gimple_vuse (stmt))
488 tree vdef = gimple_vdef (stmt);
489 if (vdef
490 && TREE_CODE (vdef) == SSA_NAME)
492 unlink_stmt_vdef (stmt);
493 release_ssa_name (vdef);
497 /* Finally replace the original statement with the sequence. */
498 gsi_replace_with_seq (si_p, stmts, false);
501 /* Convert EXPR into a GIMPLE value suitable for substitution on the
502 RHS of an assignment. Insert the necessary statements before
503 iterator *SI_P. The statement at *SI_P, which must be a GIMPLE_CALL
504 is replaced. If the call is expected to produces a result, then it
505 is replaced by an assignment of the new RHS to the result variable.
506 If the result is to be ignored, then the call is replaced by a
507 GIMPLE_NOP. A proper VDEF chain is retained by making the first
508 VUSE and the last VDEF of the whole sequence be the same as the replaced
509 statement and using new SSA names for stores in between. */
511 void
512 gimplify_and_update_call_from_tree (gimple_stmt_iterator *si_p, tree expr)
514 tree lhs;
515 gimple *stmt, *new_stmt;
516 gimple_stmt_iterator i;
517 gimple_seq stmts = NULL;
519 stmt = gsi_stmt (*si_p);
521 gcc_assert (is_gimple_call (stmt));
523 push_gimplify_context (gimple_in_ssa_p (cfun));
525 lhs = gimple_call_lhs (stmt);
526 if (lhs == NULL_TREE)
528 gimplify_and_add (expr, &stmts);
529 /* We can end up with folding a memcpy of an empty class assignment
530 which gets optimized away by C++ gimplification. */
531 if (gimple_seq_empty_p (stmts))
533 pop_gimplify_context (NULL);
534 if (gimple_in_ssa_p (cfun))
536 unlink_stmt_vdef (stmt);
537 release_defs (stmt);
539 gsi_replace (si_p, gimple_build_nop (), false);
540 return;
543 else
545 tree tmp = force_gimple_operand (expr, &stmts, false, NULL_TREE);
546 new_stmt = gimple_build_assign (lhs, tmp);
547 i = gsi_last (stmts);
548 gsi_insert_after_without_update (&i, new_stmt,
549 GSI_CONTINUE_LINKING);
552 pop_gimplify_context (NULL);
554 gsi_replace_with_seq_vops (si_p, stmts);
558 /* Replace the call at *GSI with the gimple value VAL. */
560 static void
561 replace_call_with_value (gimple_stmt_iterator *gsi, tree val)
563 gimple *stmt = gsi_stmt (*gsi);
564 tree lhs = gimple_call_lhs (stmt);
565 gimple *repl;
566 if (lhs)
568 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (val)))
569 val = fold_convert (TREE_TYPE (lhs), val);
570 repl = gimple_build_assign (lhs, val);
572 else
573 repl = gimple_build_nop ();
574 tree vdef = gimple_vdef (stmt);
575 if (vdef && TREE_CODE (vdef) == SSA_NAME)
577 unlink_stmt_vdef (stmt);
578 release_ssa_name (vdef);
580 gsi_replace (gsi, repl, false);
583 /* Replace the call at *GSI with the new call REPL and fold that
584 again. */
586 static void
587 replace_call_with_call_and_fold (gimple_stmt_iterator *gsi, gimple *repl)
589 gimple *stmt = gsi_stmt (*gsi);
590 gimple_call_set_lhs (repl, gimple_call_lhs (stmt));
591 gimple_set_location (repl, gimple_location (stmt));
592 if (gimple_vdef (stmt)
593 && TREE_CODE (gimple_vdef (stmt)) == SSA_NAME)
595 gimple_set_vdef (repl, gimple_vdef (stmt));
596 gimple_set_vuse (repl, gimple_vuse (stmt));
597 SSA_NAME_DEF_STMT (gimple_vdef (repl)) = repl;
599 gsi_replace (gsi, repl, false);
600 fold_stmt (gsi);
603 /* Return true if VAR is a VAR_DECL or a component thereof. */
605 static bool
606 var_decl_component_p (tree var)
608 tree inner = var;
609 while (handled_component_p (inner))
610 inner = TREE_OPERAND (inner, 0);
611 return SSA_VAR_P (inner);
614 /* Fold function call to builtin mem{{,p}cpy,move}. Return
615 false if no simplification can be made.
616 If ENDP is 0, return DEST (like memcpy).
617 If ENDP is 1, return DEST+LEN (like mempcpy).
618 If ENDP is 2, return DEST+LEN-1 (like stpcpy).
619 If ENDP is 3, return DEST, additionally *SRC and *DEST may overlap
620 (memmove). */
622 static bool
623 gimple_fold_builtin_memory_op (gimple_stmt_iterator *gsi,
624 tree dest, tree src, int endp)
626 gimple *stmt = gsi_stmt (*gsi);
627 tree lhs = gimple_call_lhs (stmt);
628 tree len = gimple_call_arg (stmt, 2);
629 tree destvar, srcvar;
630 location_t loc = gimple_location (stmt);
632 /* If the LEN parameter is zero, return DEST. */
633 if (integer_zerop (len))
635 gimple *repl;
636 if (gimple_call_lhs (stmt))
637 repl = gimple_build_assign (gimple_call_lhs (stmt), dest);
638 else
639 repl = gimple_build_nop ();
640 tree vdef = gimple_vdef (stmt);
641 if (vdef && TREE_CODE (vdef) == SSA_NAME)
643 unlink_stmt_vdef (stmt);
644 release_ssa_name (vdef);
646 gsi_replace (gsi, repl, false);
647 return true;
650 /* If SRC and DEST are the same (and not volatile), return
651 DEST{,+LEN,+LEN-1}. */
652 if (operand_equal_p (src, dest, 0))
654 unlink_stmt_vdef (stmt);
655 if (gimple_vdef (stmt) && TREE_CODE (gimple_vdef (stmt)) == SSA_NAME)
656 release_ssa_name (gimple_vdef (stmt));
657 if (!lhs)
659 gsi_replace (gsi, gimple_build_nop (), false);
660 return true;
662 goto done;
664 else
666 tree srctype, desttype;
667 unsigned int src_align, dest_align;
668 tree off0;
670 /* Inlining of memcpy/memmove may cause bounds lost (if we copy
671 pointers as wide integer) and also may result in huge function
672 size because of inlined bounds copy. Thus don't inline for
673 functions we want to instrument. */
674 if (flag_check_pointer_bounds
675 && chkp_instrumentable_p (cfun->decl)
676 /* Even if data may contain pointers we can inline if copy
677 less than a pointer size. */
678 && (!tree_fits_uhwi_p (len)
679 || compare_tree_int (len, POINTER_SIZE_UNITS) >= 0))
680 return false;
682 /* Build accesses at offset zero with a ref-all character type. */
683 off0 = build_int_cst (build_pointer_type_for_mode (char_type_node,
684 ptr_mode, true), 0);
686 /* If we can perform the copy efficiently with first doing all loads
687 and then all stores inline it that way. Currently efficiently
688 means that we can load all the memory into a single integer
689 register which is what MOVE_MAX gives us. */
690 src_align = get_pointer_alignment (src);
691 dest_align = get_pointer_alignment (dest);
692 if (tree_fits_uhwi_p (len)
693 && compare_tree_int (len, MOVE_MAX) <= 0
694 /* ??? Don't transform copies from strings with known length this
695 confuses the tree-ssa-strlen.c. This doesn't handle
696 the case in gcc.dg/strlenopt-8.c which is XFAILed for that
697 reason. */
698 && !c_strlen (src, 2))
700 unsigned ilen = tree_to_uhwi (len);
701 if (exact_log2 (ilen) != -1)
703 tree type = lang_hooks.types.type_for_size (ilen * 8, 1);
704 if (type
705 && TYPE_MODE (type) != BLKmode
706 && (GET_MODE_SIZE (TYPE_MODE (type)) * BITS_PER_UNIT
707 == ilen * 8)
708 /* If the destination pointer is not aligned we must be able
709 to emit an unaligned store. */
710 && (dest_align >= GET_MODE_ALIGNMENT (TYPE_MODE (type))
711 || !SLOW_UNALIGNED_ACCESS (TYPE_MODE (type), dest_align)
712 || (optab_handler (movmisalign_optab, TYPE_MODE (type))
713 != CODE_FOR_nothing)))
715 tree srctype = type;
716 tree desttype = type;
717 if (src_align < GET_MODE_ALIGNMENT (TYPE_MODE (type)))
718 srctype = build_aligned_type (type, src_align);
719 tree srcmem = fold_build2 (MEM_REF, srctype, src, off0);
720 tree tem = fold_const_aggregate_ref (srcmem);
721 if (tem)
722 srcmem = tem;
723 else if (src_align < GET_MODE_ALIGNMENT (TYPE_MODE (type))
724 && SLOW_UNALIGNED_ACCESS (TYPE_MODE (type),
725 src_align)
726 && (optab_handler (movmisalign_optab,
727 TYPE_MODE (type))
728 == CODE_FOR_nothing))
729 srcmem = NULL_TREE;
730 if (srcmem)
732 gimple *new_stmt;
733 if (is_gimple_reg_type (TREE_TYPE (srcmem)))
735 new_stmt = gimple_build_assign (NULL_TREE, srcmem);
736 if (gimple_in_ssa_p (cfun))
737 srcmem = make_ssa_name (TREE_TYPE (srcmem),
738 new_stmt);
739 else
740 srcmem = create_tmp_reg (TREE_TYPE (srcmem));
741 gimple_assign_set_lhs (new_stmt, srcmem);
742 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
743 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
745 if (dest_align < GET_MODE_ALIGNMENT (TYPE_MODE (type)))
746 desttype = build_aligned_type (type, dest_align);
747 new_stmt
748 = gimple_build_assign (fold_build2 (MEM_REF, desttype,
749 dest, off0),
750 srcmem);
751 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
752 gimple_set_vdef (new_stmt, gimple_vdef (stmt));
753 if (gimple_vdef (new_stmt)
754 && TREE_CODE (gimple_vdef (new_stmt)) == SSA_NAME)
755 SSA_NAME_DEF_STMT (gimple_vdef (new_stmt)) = new_stmt;
756 if (!lhs)
758 gsi_replace (gsi, new_stmt, false);
759 return true;
761 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
762 goto done;
768 if (endp == 3)
770 /* Both DEST and SRC must be pointer types.
771 ??? This is what old code did. Is the testing for pointer types
772 really mandatory?
774 If either SRC is readonly or length is 1, we can use memcpy. */
775 if (!dest_align || !src_align)
776 return false;
777 if (readonly_data_expr (src)
778 || (tree_fits_uhwi_p (len)
779 && (MIN (src_align, dest_align) / BITS_PER_UNIT
780 >= tree_to_uhwi (len))))
782 tree fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
783 if (!fn)
784 return false;
785 gimple_call_set_fndecl (stmt, fn);
786 gimple_call_set_arg (stmt, 0, dest);
787 gimple_call_set_arg (stmt, 1, src);
788 fold_stmt (gsi);
789 return true;
792 /* If *src and *dest can't overlap, optimize into memcpy as well. */
793 if (TREE_CODE (src) == ADDR_EXPR
794 && TREE_CODE (dest) == ADDR_EXPR)
796 tree src_base, dest_base, fn;
797 HOST_WIDE_INT src_offset = 0, dest_offset = 0;
798 HOST_WIDE_INT size = -1;
799 HOST_WIDE_INT maxsize = -1;
800 bool reverse;
802 srcvar = TREE_OPERAND (src, 0);
803 src_base = get_ref_base_and_extent (srcvar, &src_offset,
804 &size, &maxsize, &reverse);
805 destvar = TREE_OPERAND (dest, 0);
806 dest_base = get_ref_base_and_extent (destvar, &dest_offset,
807 &size, &maxsize, &reverse);
808 if (tree_fits_uhwi_p (len))
809 maxsize = tree_to_uhwi (len);
810 else
811 maxsize = -1;
812 src_offset /= BITS_PER_UNIT;
813 dest_offset /= BITS_PER_UNIT;
814 if (SSA_VAR_P (src_base)
815 && SSA_VAR_P (dest_base))
817 if (operand_equal_p (src_base, dest_base, 0)
818 && ranges_overlap_p (src_offset, maxsize,
819 dest_offset, maxsize))
820 return false;
822 else if (TREE_CODE (src_base) == MEM_REF
823 && TREE_CODE (dest_base) == MEM_REF)
825 if (! operand_equal_p (TREE_OPERAND (src_base, 0),
826 TREE_OPERAND (dest_base, 0), 0))
827 return false;
828 offset_int off = mem_ref_offset (src_base) + src_offset;
829 if (!wi::fits_shwi_p (off))
830 return false;
831 src_offset = off.to_shwi ();
833 off = mem_ref_offset (dest_base) + dest_offset;
834 if (!wi::fits_shwi_p (off))
835 return false;
836 dest_offset = off.to_shwi ();
837 if (ranges_overlap_p (src_offset, maxsize,
838 dest_offset, maxsize))
839 return false;
841 else
842 return false;
844 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
845 if (!fn)
846 return false;
847 gimple_call_set_fndecl (stmt, fn);
848 gimple_call_set_arg (stmt, 0, dest);
849 gimple_call_set_arg (stmt, 1, src);
850 fold_stmt (gsi);
851 return true;
854 /* If the destination and source do not alias optimize into
855 memcpy as well. */
856 if ((is_gimple_min_invariant (dest)
857 || TREE_CODE (dest) == SSA_NAME)
858 && (is_gimple_min_invariant (src)
859 || TREE_CODE (src) == SSA_NAME))
861 ao_ref destr, srcr;
862 ao_ref_init_from_ptr_and_size (&destr, dest, len);
863 ao_ref_init_from_ptr_and_size (&srcr, src, len);
864 if (!refs_may_alias_p_1 (&destr, &srcr, false))
866 tree fn;
867 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
868 if (!fn)
869 return false;
870 gimple_call_set_fndecl (stmt, fn);
871 gimple_call_set_arg (stmt, 0, dest);
872 gimple_call_set_arg (stmt, 1, src);
873 fold_stmt (gsi);
874 return true;
878 return false;
881 if (!tree_fits_shwi_p (len))
882 return false;
883 /* FIXME:
884 This logic lose for arguments like (type *)malloc (sizeof (type)),
885 since we strip the casts of up to VOID return value from malloc.
886 Perhaps we ought to inherit type from non-VOID argument here? */
887 STRIP_NOPS (src);
888 STRIP_NOPS (dest);
889 if (!POINTER_TYPE_P (TREE_TYPE (src))
890 || !POINTER_TYPE_P (TREE_TYPE (dest)))
891 return false;
892 /* In the following try to find a type that is most natural to be
893 used for the memcpy source and destination and that allows
894 the most optimization when memcpy is turned into a plain assignment
895 using that type. In theory we could always use a char[len] type
896 but that only gains us that the destination and source possibly
897 no longer will have their address taken. */
898 /* As we fold (void *)(p + CST) to (void *)p + CST undo this here. */
899 if (TREE_CODE (src) == POINTER_PLUS_EXPR)
901 tree tem = TREE_OPERAND (src, 0);
902 STRIP_NOPS (tem);
903 if (tem != TREE_OPERAND (src, 0))
904 src = build1 (NOP_EXPR, TREE_TYPE (tem), src);
906 if (TREE_CODE (dest) == POINTER_PLUS_EXPR)
908 tree tem = TREE_OPERAND (dest, 0);
909 STRIP_NOPS (tem);
910 if (tem != TREE_OPERAND (dest, 0))
911 dest = build1 (NOP_EXPR, TREE_TYPE (tem), dest);
913 srctype = TREE_TYPE (TREE_TYPE (src));
914 if (TREE_CODE (srctype) == ARRAY_TYPE
915 && !tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
917 srctype = TREE_TYPE (srctype);
918 STRIP_NOPS (src);
919 src = build1 (NOP_EXPR, build_pointer_type (srctype), src);
921 desttype = TREE_TYPE (TREE_TYPE (dest));
922 if (TREE_CODE (desttype) == ARRAY_TYPE
923 && !tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
925 desttype = TREE_TYPE (desttype);
926 STRIP_NOPS (dest);
927 dest = build1 (NOP_EXPR, build_pointer_type (desttype), dest);
929 if (TREE_ADDRESSABLE (srctype)
930 || TREE_ADDRESSABLE (desttype))
931 return false;
933 /* Make sure we are not copying using a floating-point mode or
934 a type whose size possibly does not match its precision. */
935 if (FLOAT_MODE_P (TYPE_MODE (desttype))
936 || TREE_CODE (desttype) == BOOLEAN_TYPE
937 || TREE_CODE (desttype) == ENUMERAL_TYPE)
938 desttype = bitwise_type_for_mode (TYPE_MODE (desttype));
939 if (FLOAT_MODE_P (TYPE_MODE (srctype))
940 || TREE_CODE (srctype) == BOOLEAN_TYPE
941 || TREE_CODE (srctype) == ENUMERAL_TYPE)
942 srctype = bitwise_type_for_mode (TYPE_MODE (srctype));
943 if (!srctype)
944 srctype = desttype;
945 if (!desttype)
946 desttype = srctype;
947 if (!srctype)
948 return false;
950 src_align = get_pointer_alignment (src);
951 dest_align = get_pointer_alignment (dest);
952 if (dest_align < TYPE_ALIGN (desttype)
953 || src_align < TYPE_ALIGN (srctype))
954 return false;
956 destvar = dest;
957 STRIP_NOPS (destvar);
958 if (TREE_CODE (destvar) == ADDR_EXPR
959 && var_decl_component_p (TREE_OPERAND (destvar, 0))
960 && tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
961 destvar = fold_build2 (MEM_REF, desttype, destvar, off0);
962 else
963 destvar = NULL_TREE;
965 srcvar = src;
966 STRIP_NOPS (srcvar);
967 if (TREE_CODE (srcvar) == ADDR_EXPR
968 && var_decl_component_p (TREE_OPERAND (srcvar, 0))
969 && tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
971 if (!destvar
972 || src_align >= TYPE_ALIGN (desttype))
973 srcvar = fold_build2 (MEM_REF, destvar ? desttype : srctype,
974 srcvar, off0);
975 else if (!STRICT_ALIGNMENT)
977 srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
978 src_align);
979 srcvar = fold_build2 (MEM_REF, srctype, srcvar, off0);
981 else
982 srcvar = NULL_TREE;
984 else
985 srcvar = NULL_TREE;
987 if (srcvar == NULL_TREE && destvar == NULL_TREE)
988 return false;
990 if (srcvar == NULL_TREE)
992 STRIP_NOPS (src);
993 if (src_align >= TYPE_ALIGN (desttype))
994 srcvar = fold_build2 (MEM_REF, desttype, src, off0);
995 else
997 if (STRICT_ALIGNMENT)
998 return false;
999 srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
1000 src_align);
1001 srcvar = fold_build2 (MEM_REF, srctype, src, off0);
1004 else if (destvar == NULL_TREE)
1006 STRIP_NOPS (dest);
1007 if (dest_align >= TYPE_ALIGN (srctype))
1008 destvar = fold_build2 (MEM_REF, srctype, dest, off0);
1009 else
1011 if (STRICT_ALIGNMENT)
1012 return false;
1013 desttype = build_aligned_type (TYPE_MAIN_VARIANT (srctype),
1014 dest_align);
1015 destvar = fold_build2 (MEM_REF, desttype, dest, off0);
1019 gimple *new_stmt;
1020 if (is_gimple_reg_type (TREE_TYPE (srcvar)))
1022 new_stmt = gimple_build_assign (NULL_TREE, srcvar);
1023 if (gimple_in_ssa_p (cfun))
1024 srcvar = make_ssa_name (TREE_TYPE (srcvar), new_stmt);
1025 else
1026 srcvar = create_tmp_reg (TREE_TYPE (srcvar));
1027 gimple_assign_set_lhs (new_stmt, srcvar);
1028 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
1029 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1031 new_stmt = gimple_build_assign (destvar, srcvar);
1032 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
1033 gimple_set_vdef (new_stmt, gimple_vdef (stmt));
1034 if (gimple_vdef (new_stmt)
1035 && TREE_CODE (gimple_vdef (new_stmt)) == SSA_NAME)
1036 SSA_NAME_DEF_STMT (gimple_vdef (new_stmt)) = new_stmt;
1037 if (!lhs)
1039 gsi_replace (gsi, new_stmt, false);
1040 return true;
1042 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1045 done:
1046 gimple_seq stmts = NULL;
1047 if (endp == 0 || endp == 3)
1048 len = NULL_TREE;
1049 else if (endp == 2)
1050 len = gimple_build (&stmts, loc, MINUS_EXPR, TREE_TYPE (len), len,
1051 ssize_int (1));
1052 if (endp == 2 || endp == 1)
1054 len = gimple_convert_to_ptrofftype (&stmts, loc, len);
1055 dest = gimple_build (&stmts, loc, POINTER_PLUS_EXPR,
1056 TREE_TYPE (dest), dest, len);
1059 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
1060 gimple *repl = gimple_build_assign (lhs, dest);
1061 gsi_replace (gsi, repl, false);
1062 return true;
1065 /* Fold function call to builtin memset or bzero at *GSI setting the
1066 memory of size LEN to VAL. Return whether a simplification was made. */
1068 static bool
1069 gimple_fold_builtin_memset (gimple_stmt_iterator *gsi, tree c, tree len)
1071 gimple *stmt = gsi_stmt (*gsi);
1072 tree etype;
1073 unsigned HOST_WIDE_INT length, cval;
1075 /* If the LEN parameter is zero, return DEST. */
1076 if (integer_zerop (len))
1078 replace_call_with_value (gsi, gimple_call_arg (stmt, 0));
1079 return true;
1082 if (! tree_fits_uhwi_p (len))
1083 return false;
1085 if (TREE_CODE (c) != INTEGER_CST)
1086 return false;
1088 tree dest = gimple_call_arg (stmt, 0);
1089 tree var = dest;
1090 if (TREE_CODE (var) != ADDR_EXPR)
1091 return false;
1093 var = TREE_OPERAND (var, 0);
1094 if (TREE_THIS_VOLATILE (var))
1095 return false;
1097 etype = TREE_TYPE (var);
1098 if (TREE_CODE (etype) == ARRAY_TYPE)
1099 etype = TREE_TYPE (etype);
1101 if (!INTEGRAL_TYPE_P (etype)
1102 && !POINTER_TYPE_P (etype))
1103 return NULL_TREE;
1105 if (! var_decl_component_p (var))
1106 return NULL_TREE;
1108 length = tree_to_uhwi (len);
1109 if (GET_MODE_SIZE (TYPE_MODE (etype)) != length
1110 || get_pointer_alignment (dest) / BITS_PER_UNIT < length)
1111 return NULL_TREE;
1113 if (length > HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT)
1114 return NULL_TREE;
1116 if (integer_zerop (c))
1117 cval = 0;
1118 else
1120 if (CHAR_BIT != 8 || BITS_PER_UNIT != 8 || HOST_BITS_PER_WIDE_INT > 64)
1121 return NULL_TREE;
1123 cval = TREE_INT_CST_LOW (c);
1124 cval &= 0xff;
1125 cval |= cval << 8;
1126 cval |= cval << 16;
1127 cval |= (cval << 31) << 1;
1130 var = fold_build2 (MEM_REF, etype, dest, build_int_cst (ptr_type_node, 0));
1131 gimple *store = gimple_build_assign (var, build_int_cst_type (etype, cval));
1132 gimple_set_vuse (store, gimple_vuse (stmt));
1133 tree vdef = gimple_vdef (stmt);
1134 if (vdef && TREE_CODE (vdef) == SSA_NAME)
1136 gimple_set_vdef (store, gimple_vdef (stmt));
1137 SSA_NAME_DEF_STMT (gimple_vdef (stmt)) = store;
1139 gsi_insert_before (gsi, store, GSI_SAME_STMT);
1140 if (gimple_call_lhs (stmt))
1142 gimple *asgn = gimple_build_assign (gimple_call_lhs (stmt), dest);
1143 gsi_replace (gsi, asgn, false);
1145 else
1147 gimple_stmt_iterator gsi2 = *gsi;
1148 gsi_prev (gsi);
1149 gsi_remove (&gsi2, true);
1152 return true;
1156 /* Return the string length, maximum string length or maximum value of
1157 ARG in LENGTH.
1158 If ARG is an SSA name variable, follow its use-def chains. If LENGTH
1159 is not NULL and, for TYPE == 0, its value is not equal to the length
1160 we determine or if we are unable to determine the length or value,
1161 return false. VISITED is a bitmap of visited variables.
1162 TYPE is 0 if string length should be returned, 1 for maximum string
1163 length and 2 for maximum value ARG can have. */
1165 static bool
1166 get_maxval_strlen (tree arg, tree *length, bitmap *visited, int type)
1168 tree var, val;
1169 gimple *def_stmt;
1171 if (TREE_CODE (arg) != SSA_NAME)
1173 /* We can end up with &(*iftmp_1)[0] here as well, so handle it. */
1174 if (TREE_CODE (arg) == ADDR_EXPR
1175 && TREE_CODE (TREE_OPERAND (arg, 0)) == ARRAY_REF
1176 && integer_zerop (TREE_OPERAND (TREE_OPERAND (arg, 0), 1)))
1178 tree aop0 = TREE_OPERAND (TREE_OPERAND (arg, 0), 0);
1179 if (TREE_CODE (aop0) == INDIRECT_REF
1180 && TREE_CODE (TREE_OPERAND (aop0, 0)) == SSA_NAME)
1181 return get_maxval_strlen (TREE_OPERAND (aop0, 0),
1182 length, visited, type);
1185 if (type == 2)
1187 val = arg;
1188 if (TREE_CODE (val) != INTEGER_CST
1189 || tree_int_cst_sgn (val) < 0)
1190 return false;
1192 else
1193 val = c_strlen (arg, 1);
1194 if (!val)
1195 return false;
1197 if (*length)
1199 if (type > 0)
1201 if (TREE_CODE (*length) != INTEGER_CST
1202 || TREE_CODE (val) != INTEGER_CST)
1203 return false;
1205 if (tree_int_cst_lt (*length, val))
1206 *length = val;
1207 return true;
1209 else if (simple_cst_equal (val, *length) != 1)
1210 return false;
1213 *length = val;
1214 return true;
1217 /* If ARG is registered for SSA update we cannot look at its defining
1218 statement. */
1219 if (name_registered_for_update_p (arg))
1220 return false;
1222 /* If we were already here, break the infinite cycle. */
1223 if (!*visited)
1224 *visited = BITMAP_ALLOC (NULL);
1225 if (!bitmap_set_bit (*visited, SSA_NAME_VERSION (arg)))
1226 return true;
1228 var = arg;
1229 def_stmt = SSA_NAME_DEF_STMT (var);
1231 switch (gimple_code (def_stmt))
1233 case GIMPLE_ASSIGN:
1234 /* The RHS of the statement defining VAR must either have a
1235 constant length or come from another SSA_NAME with a constant
1236 length. */
1237 if (gimple_assign_single_p (def_stmt)
1238 || gimple_assign_unary_nop_p (def_stmt))
1240 tree rhs = gimple_assign_rhs1 (def_stmt);
1241 return get_maxval_strlen (rhs, length, visited, type);
1243 else if (gimple_assign_rhs_code (def_stmt) == COND_EXPR)
1245 tree op2 = gimple_assign_rhs2 (def_stmt);
1246 tree op3 = gimple_assign_rhs3 (def_stmt);
1247 return get_maxval_strlen (op2, length, visited, type)
1248 && get_maxval_strlen (op3, length, visited, type);
1250 return false;
1252 case GIMPLE_PHI:
1254 /* All the arguments of the PHI node must have the same constant
1255 length. */
1256 unsigned i;
1258 for (i = 0; i < gimple_phi_num_args (def_stmt); i++)
1260 tree arg = gimple_phi_arg (def_stmt, i)->def;
1262 /* If this PHI has itself as an argument, we cannot
1263 determine the string length of this argument. However,
1264 if we can find a constant string length for the other
1265 PHI args then we can still be sure that this is a
1266 constant string length. So be optimistic and just
1267 continue with the next argument. */
1268 if (arg == gimple_phi_result (def_stmt))
1269 continue;
1271 if (!get_maxval_strlen (arg, length, visited, type))
1272 return false;
1275 return true;
1277 default:
1278 return false;
1282 tree
1283 get_maxval_strlen (tree arg, int type)
1285 bitmap visited = NULL;
1286 tree len = NULL_TREE;
1287 if (!get_maxval_strlen (arg, &len, &visited, type))
1288 len = NULL_TREE;
1289 if (visited)
1290 BITMAP_FREE (visited);
1292 return len;
1296 /* Fold function call to builtin strcpy with arguments DEST and SRC.
1297 If LEN is not NULL, it represents the length of the string to be
1298 copied. Return NULL_TREE if no simplification can be made. */
1300 static bool
1301 gimple_fold_builtin_strcpy (gimple_stmt_iterator *gsi,
1302 tree dest, tree src)
1304 location_t loc = gimple_location (gsi_stmt (*gsi));
1305 tree fn;
1307 /* If SRC and DEST are the same (and not volatile), return DEST. */
1308 if (operand_equal_p (src, dest, 0))
1310 replace_call_with_value (gsi, dest);
1311 return true;
1314 if (optimize_function_for_size_p (cfun))
1315 return false;
1317 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1318 if (!fn)
1319 return false;
1321 tree len = get_maxval_strlen (src, 0);
1322 if (!len)
1323 return false;
1325 len = fold_convert_loc (loc, size_type_node, len);
1326 len = size_binop_loc (loc, PLUS_EXPR, len, build_int_cst (size_type_node, 1));
1327 len = force_gimple_operand_gsi (gsi, len, true,
1328 NULL_TREE, true, GSI_SAME_STMT);
1329 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
1330 replace_call_with_call_and_fold (gsi, repl);
1331 return true;
1334 /* Fold function call to builtin strncpy with arguments DEST, SRC, and LEN.
1335 If SLEN is not NULL, it represents the length of the source string.
1336 Return NULL_TREE if no simplification can be made. */
1338 static bool
1339 gimple_fold_builtin_strncpy (gimple_stmt_iterator *gsi,
1340 tree dest, tree src, tree len)
1342 location_t loc = gimple_location (gsi_stmt (*gsi));
1343 tree fn;
1345 /* If the LEN parameter is zero, return DEST. */
1346 if (integer_zerop (len))
1348 replace_call_with_value (gsi, dest);
1349 return true;
1352 /* We can't compare slen with len as constants below if len is not a
1353 constant. */
1354 if (TREE_CODE (len) != INTEGER_CST)
1355 return false;
1357 /* Now, we must be passed a constant src ptr parameter. */
1358 tree slen = get_maxval_strlen (src, 0);
1359 if (!slen || TREE_CODE (slen) != INTEGER_CST)
1360 return false;
1362 slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
1364 /* We do not support simplification of this case, though we do
1365 support it when expanding trees into RTL. */
1366 /* FIXME: generate a call to __builtin_memset. */
1367 if (tree_int_cst_lt (slen, len))
1368 return false;
1370 /* OK transform into builtin memcpy. */
1371 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1372 if (!fn)
1373 return false;
1375 len = fold_convert_loc (loc, size_type_node, len);
1376 len = force_gimple_operand_gsi (gsi, len, true,
1377 NULL_TREE, true, GSI_SAME_STMT);
1378 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
1379 replace_call_with_call_and_fold (gsi, repl);
1380 return true;
1383 /* Simplify a call to the strcat builtin. DST and SRC are the arguments
1384 to the call.
1386 Return NULL_TREE if no simplification was possible, otherwise return the
1387 simplified form of the call as a tree.
1389 The simplified form may be a constant or other expression which
1390 computes the same value, but in a more efficient manner (including
1391 calls to other builtin functions).
1393 The call may contain arguments which need to be evaluated, but
1394 which are not useful to determine the result of the call. In
1395 this case we return a chain of COMPOUND_EXPRs. The LHS of each
1396 COMPOUND_EXPR will be an argument which must be evaluated.
1397 COMPOUND_EXPRs are chained through their RHS. The RHS of the last
1398 COMPOUND_EXPR in the chain will contain the tree for the simplified
1399 form of the builtin function call. */
1401 static bool
1402 gimple_fold_builtin_strcat (gimple_stmt_iterator *gsi, tree dst, tree src)
1404 gimple *stmt = gsi_stmt (*gsi);
1405 location_t loc = gimple_location (stmt);
1407 const char *p = c_getstr (src);
1409 /* If the string length is zero, return the dst parameter. */
1410 if (p && *p == '\0')
1412 replace_call_with_value (gsi, dst);
1413 return true;
1416 if (!optimize_bb_for_speed_p (gimple_bb (stmt)))
1417 return false;
1419 /* See if we can store by pieces into (dst + strlen(dst)). */
1420 tree newdst;
1421 tree strlen_fn = builtin_decl_implicit (BUILT_IN_STRLEN);
1422 tree memcpy_fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1424 if (!strlen_fn || !memcpy_fn)
1425 return false;
1427 /* If the length of the source string isn't computable don't
1428 split strcat into strlen and memcpy. */
1429 tree len = get_maxval_strlen (src, 0);
1430 if (! len)
1431 return false;
1433 /* Create strlen (dst). */
1434 gimple_seq stmts = NULL, stmts2;
1435 gimple *repl = gimple_build_call (strlen_fn, 1, dst);
1436 gimple_set_location (repl, loc);
1437 if (gimple_in_ssa_p (cfun))
1438 newdst = make_ssa_name (size_type_node);
1439 else
1440 newdst = create_tmp_reg (size_type_node);
1441 gimple_call_set_lhs (repl, newdst);
1442 gimple_seq_add_stmt_without_update (&stmts, repl);
1444 /* Create (dst p+ strlen (dst)). */
1445 newdst = fold_build_pointer_plus_loc (loc, dst, newdst);
1446 newdst = force_gimple_operand (newdst, &stmts2, true, NULL_TREE);
1447 gimple_seq_add_seq_without_update (&stmts, stmts2);
1449 len = fold_convert_loc (loc, size_type_node, len);
1450 len = size_binop_loc (loc, PLUS_EXPR, len,
1451 build_int_cst (size_type_node, 1));
1452 len = force_gimple_operand (len, &stmts2, true, NULL_TREE);
1453 gimple_seq_add_seq_without_update (&stmts, stmts2);
1455 repl = gimple_build_call (memcpy_fn, 3, newdst, src, len);
1456 gimple_seq_add_stmt_without_update (&stmts, repl);
1457 if (gimple_call_lhs (stmt))
1459 repl = gimple_build_assign (gimple_call_lhs (stmt), dst);
1460 gimple_seq_add_stmt_without_update (&stmts, repl);
1461 gsi_replace_with_seq_vops (gsi, stmts);
1462 /* gsi now points at the assignment to the lhs, get a
1463 stmt iterator to the memcpy call.
1464 ??? We can't use gsi_for_stmt as that doesn't work when the
1465 CFG isn't built yet. */
1466 gimple_stmt_iterator gsi2 = *gsi;
1467 gsi_prev (&gsi2);
1468 fold_stmt (&gsi2);
1470 else
1472 gsi_replace_with_seq_vops (gsi, stmts);
1473 fold_stmt (gsi);
1475 return true;
1478 /* Fold a call to the __strcat_chk builtin FNDECL. DEST, SRC, and SIZE
1479 are the arguments to the call. */
1481 static bool
1482 gimple_fold_builtin_strcat_chk (gimple_stmt_iterator *gsi)
1484 gimple *stmt = gsi_stmt (*gsi);
1485 tree dest = gimple_call_arg (stmt, 0);
1486 tree src = gimple_call_arg (stmt, 1);
1487 tree size = gimple_call_arg (stmt, 2);
1488 tree fn;
1489 const char *p;
1492 p = c_getstr (src);
1493 /* If the SRC parameter is "", return DEST. */
1494 if (p && *p == '\0')
1496 replace_call_with_value (gsi, dest);
1497 return true;
1500 if (! tree_fits_uhwi_p (size) || ! integer_all_onesp (size))
1501 return false;
1503 /* If __builtin_strcat_chk is used, assume strcat is available. */
1504 fn = builtin_decl_explicit (BUILT_IN_STRCAT);
1505 if (!fn)
1506 return false;
1508 gimple *repl = gimple_build_call (fn, 2, dest, src);
1509 replace_call_with_call_and_fold (gsi, repl);
1510 return true;
1513 /* Simplify a call to the strncat builtin. */
1515 static bool
1516 gimple_fold_builtin_strncat (gimple_stmt_iterator *gsi)
1518 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
1519 tree dst = gimple_call_arg (stmt, 0);
1520 tree src = gimple_call_arg (stmt, 1);
1521 tree len = gimple_call_arg (stmt, 2);
1523 const char *p = c_getstr (src);
1525 /* If the requested length is zero, or the src parameter string
1526 length is zero, return the dst parameter. */
1527 if (integer_zerop (len) || (p && *p == '\0'))
1529 replace_call_with_value (gsi, dst);
1530 return true;
1533 /* If the requested len is greater than or equal to the string
1534 length, call strcat. */
1535 if (TREE_CODE (len) == INTEGER_CST && p
1536 && compare_tree_int (len, strlen (p)) >= 0)
1538 tree fn = builtin_decl_implicit (BUILT_IN_STRCAT);
1540 /* If the replacement _DECL isn't initialized, don't do the
1541 transformation. */
1542 if (!fn)
1543 return false;
1545 gcall *repl = gimple_build_call (fn, 2, dst, src);
1546 replace_call_with_call_and_fold (gsi, repl);
1547 return true;
1550 return false;
1553 /* Fold a call to the __strncat_chk builtin with arguments DEST, SRC,
1554 LEN, and SIZE. */
1556 static bool
1557 gimple_fold_builtin_strncat_chk (gimple_stmt_iterator *gsi)
1559 gimple *stmt = gsi_stmt (*gsi);
1560 tree dest = gimple_call_arg (stmt, 0);
1561 tree src = gimple_call_arg (stmt, 1);
1562 tree len = gimple_call_arg (stmt, 2);
1563 tree size = gimple_call_arg (stmt, 3);
1564 tree fn;
1565 const char *p;
1567 p = c_getstr (src);
1568 /* If the SRC parameter is "" or if LEN is 0, return DEST. */
1569 if ((p && *p == '\0')
1570 || integer_zerop (len))
1572 replace_call_with_value (gsi, dest);
1573 return true;
1576 if (! tree_fits_uhwi_p (size))
1577 return false;
1579 if (! integer_all_onesp (size))
1581 tree src_len = c_strlen (src, 1);
1582 if (src_len
1583 && tree_fits_uhwi_p (src_len)
1584 && tree_fits_uhwi_p (len)
1585 && ! tree_int_cst_lt (len, src_len))
1587 /* If LEN >= strlen (SRC), optimize into __strcat_chk. */
1588 fn = builtin_decl_explicit (BUILT_IN_STRCAT_CHK);
1589 if (!fn)
1590 return false;
1592 gimple *repl = gimple_build_call (fn, 3, dest, src, size);
1593 replace_call_with_call_and_fold (gsi, repl);
1594 return true;
1596 return false;
1599 /* If __builtin_strncat_chk is used, assume strncat is available. */
1600 fn = builtin_decl_explicit (BUILT_IN_STRNCAT);
1601 if (!fn)
1602 return false;
1604 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
1605 replace_call_with_call_and_fold (gsi, repl);
1606 return true;
1609 /* Fold a call to the fputs builtin. ARG0 and ARG1 are the arguments
1610 to the call. IGNORE is true if the value returned
1611 by the builtin will be ignored. UNLOCKED is true is true if this
1612 actually a call to fputs_unlocked. If LEN in non-NULL, it represents
1613 the known length of the string. Return NULL_TREE if no simplification
1614 was possible. */
1616 static bool
1617 gimple_fold_builtin_fputs (gimple_stmt_iterator *gsi,
1618 tree arg0, tree arg1,
1619 bool unlocked)
1621 gimple *stmt = gsi_stmt (*gsi);
1623 /* If we're using an unlocked function, assume the other unlocked
1624 functions exist explicitly. */
1625 tree const fn_fputc = (unlocked
1626 ? builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED)
1627 : builtin_decl_implicit (BUILT_IN_FPUTC));
1628 tree const fn_fwrite = (unlocked
1629 ? builtin_decl_explicit (BUILT_IN_FWRITE_UNLOCKED)
1630 : builtin_decl_implicit (BUILT_IN_FWRITE));
1632 /* If the return value is used, don't do the transformation. */
1633 if (gimple_call_lhs (stmt))
1634 return false;
1636 /* Get the length of the string passed to fputs. If the length
1637 can't be determined, punt. */
1638 tree len = get_maxval_strlen (arg0, 0);
1639 if (!len
1640 || TREE_CODE (len) != INTEGER_CST)
1641 return false;
1643 switch (compare_tree_int (len, 1))
1645 case -1: /* length is 0, delete the call entirely . */
1646 replace_call_with_value (gsi, integer_zero_node);
1647 return true;
1649 case 0: /* length is 1, call fputc. */
1651 const char *p = c_getstr (arg0);
1652 if (p != NULL)
1654 if (!fn_fputc)
1655 return false;
1657 gimple *repl = gimple_build_call (fn_fputc, 2,
1658 build_int_cst
1659 (integer_type_node, p[0]), arg1);
1660 replace_call_with_call_and_fold (gsi, repl);
1661 return true;
1664 /* FALLTHROUGH */
1665 case 1: /* length is greater than 1, call fwrite. */
1667 /* If optimizing for size keep fputs. */
1668 if (optimize_function_for_size_p (cfun))
1669 return false;
1670 /* New argument list transforming fputs(string, stream) to
1671 fwrite(string, 1, len, stream). */
1672 if (!fn_fwrite)
1673 return false;
1675 gimple *repl = gimple_build_call (fn_fwrite, 4, arg0,
1676 size_one_node, len, arg1);
1677 replace_call_with_call_and_fold (gsi, repl);
1678 return true;
1680 default:
1681 gcc_unreachable ();
1683 return false;
1686 /* Fold a call to the __mem{cpy,pcpy,move,set}_chk builtin.
1687 DEST, SRC, LEN, and SIZE are the arguments to the call.
1688 IGNORE is true, if return value can be ignored. FCODE is the BUILT_IN_*
1689 code of the builtin. If MAXLEN is not NULL, it is maximum length
1690 passed as third argument. */
1692 static bool
1693 gimple_fold_builtin_memory_chk (gimple_stmt_iterator *gsi,
1694 tree dest, tree src, tree len, tree size,
1695 enum built_in_function fcode)
1697 gimple *stmt = gsi_stmt (*gsi);
1698 location_t loc = gimple_location (stmt);
1699 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
1700 tree fn;
1702 /* If SRC and DEST are the same (and not volatile), return DEST
1703 (resp. DEST+LEN for __mempcpy_chk). */
1704 if (fcode != BUILT_IN_MEMSET_CHK && operand_equal_p (src, dest, 0))
1706 if (fcode != BUILT_IN_MEMPCPY_CHK)
1708 replace_call_with_value (gsi, dest);
1709 return true;
1711 else
1713 gimple_seq stmts = NULL;
1714 len = gimple_convert_to_ptrofftype (&stmts, loc, len);
1715 tree temp = gimple_build (&stmts, loc, POINTER_PLUS_EXPR,
1716 TREE_TYPE (dest), dest, len);
1717 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
1718 replace_call_with_value (gsi, temp);
1719 return true;
1723 if (! tree_fits_uhwi_p (size))
1724 return false;
1726 tree maxlen = get_maxval_strlen (len, 2);
1727 if (! integer_all_onesp (size))
1729 if (! tree_fits_uhwi_p (len))
1731 /* If LEN is not constant, try MAXLEN too.
1732 For MAXLEN only allow optimizing into non-_ocs function
1733 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
1734 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
1736 if (fcode == BUILT_IN_MEMPCPY_CHK && ignore)
1738 /* (void) __mempcpy_chk () can be optimized into
1739 (void) __memcpy_chk (). */
1740 fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
1741 if (!fn)
1742 return false;
1744 gimple *repl = gimple_build_call (fn, 4, dest, src, len, size);
1745 replace_call_with_call_and_fold (gsi, repl);
1746 return true;
1748 return false;
1751 else
1752 maxlen = len;
1754 if (tree_int_cst_lt (size, maxlen))
1755 return false;
1758 fn = NULL_TREE;
1759 /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
1760 mem{cpy,pcpy,move,set} is available. */
1761 switch (fcode)
1763 case BUILT_IN_MEMCPY_CHK:
1764 fn = builtin_decl_explicit (BUILT_IN_MEMCPY);
1765 break;
1766 case BUILT_IN_MEMPCPY_CHK:
1767 fn = builtin_decl_explicit (BUILT_IN_MEMPCPY);
1768 break;
1769 case BUILT_IN_MEMMOVE_CHK:
1770 fn = builtin_decl_explicit (BUILT_IN_MEMMOVE);
1771 break;
1772 case BUILT_IN_MEMSET_CHK:
1773 fn = builtin_decl_explicit (BUILT_IN_MEMSET);
1774 break;
1775 default:
1776 break;
1779 if (!fn)
1780 return false;
1782 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
1783 replace_call_with_call_and_fold (gsi, repl);
1784 return true;
1787 /* Fold a call to the __st[rp]cpy_chk builtin.
1788 DEST, SRC, and SIZE are the arguments to the call.
1789 IGNORE is true if return value can be ignored. FCODE is the BUILT_IN_*
1790 code of the builtin. If MAXLEN is not NULL, it is maximum length of
1791 strings passed as second argument. */
1793 static bool
1794 gimple_fold_builtin_stxcpy_chk (gimple_stmt_iterator *gsi,
1795 tree dest,
1796 tree src, tree size,
1797 enum built_in_function fcode)
1799 gimple *stmt = gsi_stmt (*gsi);
1800 location_t loc = gimple_location (stmt);
1801 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
1802 tree len, fn;
1804 /* If SRC and DEST are the same (and not volatile), return DEST. */
1805 if (fcode == BUILT_IN_STRCPY_CHK && operand_equal_p (src, dest, 0))
1807 replace_call_with_value (gsi, dest);
1808 return true;
1811 if (! tree_fits_uhwi_p (size))
1812 return false;
1814 tree maxlen = get_maxval_strlen (src, 1);
1815 if (! integer_all_onesp (size))
1817 len = c_strlen (src, 1);
1818 if (! len || ! tree_fits_uhwi_p (len))
1820 /* If LEN is not constant, try MAXLEN too.
1821 For MAXLEN only allow optimizing into non-_ocs function
1822 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
1823 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
1825 if (fcode == BUILT_IN_STPCPY_CHK)
1827 if (! ignore)
1828 return false;
1830 /* If return value of __stpcpy_chk is ignored,
1831 optimize into __strcpy_chk. */
1832 fn = builtin_decl_explicit (BUILT_IN_STRCPY_CHK);
1833 if (!fn)
1834 return false;
1836 gimple *repl = gimple_build_call (fn, 3, dest, src, size);
1837 replace_call_with_call_and_fold (gsi, repl);
1838 return true;
1841 if (! len || TREE_SIDE_EFFECTS (len))
1842 return false;
1844 /* If c_strlen returned something, but not a constant,
1845 transform __strcpy_chk into __memcpy_chk. */
1846 fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
1847 if (!fn)
1848 return false;
1850 gimple_seq stmts = NULL;
1851 len = gimple_convert (&stmts, loc, size_type_node, len);
1852 len = gimple_build (&stmts, loc, PLUS_EXPR, size_type_node, len,
1853 build_int_cst (size_type_node, 1));
1854 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
1855 gimple *repl = gimple_build_call (fn, 4, dest, src, len, size);
1856 replace_call_with_call_and_fold (gsi, repl);
1857 return true;
1860 else
1861 maxlen = len;
1863 if (! tree_int_cst_lt (maxlen, size))
1864 return false;
1867 /* If __builtin_st{r,p}cpy_chk is used, assume st{r,p}cpy is available. */
1868 fn = builtin_decl_explicit (fcode == BUILT_IN_STPCPY_CHK
1869 ? BUILT_IN_STPCPY : BUILT_IN_STRCPY);
1870 if (!fn)
1871 return false;
1873 gimple *repl = gimple_build_call (fn, 2, dest, src);
1874 replace_call_with_call_and_fold (gsi, repl);
1875 return true;
1878 /* Fold a call to the __st{r,p}ncpy_chk builtin. DEST, SRC, LEN, and SIZE
1879 are the arguments to the call. If MAXLEN is not NULL, it is maximum
1880 length passed as third argument. IGNORE is true if return value can be
1881 ignored. FCODE is the BUILT_IN_* code of the builtin. */
1883 static bool
1884 gimple_fold_builtin_stxncpy_chk (gimple_stmt_iterator *gsi,
1885 tree dest, tree src,
1886 tree len, tree size,
1887 enum built_in_function fcode)
1889 gimple *stmt = gsi_stmt (*gsi);
1890 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
1891 tree fn;
1893 if (fcode == BUILT_IN_STPNCPY_CHK && ignore)
1895 /* If return value of __stpncpy_chk is ignored,
1896 optimize into __strncpy_chk. */
1897 fn = builtin_decl_explicit (BUILT_IN_STRNCPY_CHK);
1898 if (fn)
1900 gimple *repl = gimple_build_call (fn, 4, dest, src, len, size);
1901 replace_call_with_call_and_fold (gsi, repl);
1902 return true;
1906 if (! tree_fits_uhwi_p (size))
1907 return false;
1909 tree maxlen = get_maxval_strlen (len, 2);
1910 if (! integer_all_onesp (size))
1912 if (! tree_fits_uhwi_p (len))
1914 /* If LEN is not constant, try MAXLEN too.
1915 For MAXLEN only allow optimizing into non-_ocs function
1916 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
1917 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
1918 return false;
1920 else
1921 maxlen = len;
1923 if (tree_int_cst_lt (size, maxlen))
1924 return false;
1927 /* If __builtin_st{r,p}ncpy_chk is used, assume st{r,p}ncpy is available. */
1928 fn = builtin_decl_explicit (fcode == BUILT_IN_STPNCPY_CHK
1929 ? BUILT_IN_STPNCPY : BUILT_IN_STRNCPY);
1930 if (!fn)
1931 return false;
1933 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
1934 replace_call_with_call_and_fold (gsi, repl);
1935 return true;
1938 /* Fold function call to builtin stpcpy with arguments DEST and SRC.
1939 Return NULL_TREE if no simplification can be made. */
1941 static bool
1942 gimple_fold_builtin_stpcpy (gimple_stmt_iterator *gsi)
1944 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
1945 location_t loc = gimple_location (stmt);
1946 tree dest = gimple_call_arg (stmt, 0);
1947 tree src = gimple_call_arg (stmt, 1);
1948 tree fn, len, lenp1;
1950 /* If the result is unused, replace stpcpy with strcpy. */
1951 if (gimple_call_lhs (stmt) == NULL_TREE)
1953 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
1954 if (!fn)
1955 return false;
1956 gimple_call_set_fndecl (stmt, fn);
1957 fold_stmt (gsi);
1958 return true;
1961 len = c_strlen (src, 1);
1962 if (!len
1963 || TREE_CODE (len) != INTEGER_CST)
1964 return false;
1966 if (optimize_function_for_size_p (cfun)
1967 /* If length is zero it's small enough. */
1968 && !integer_zerop (len))
1969 return false;
1971 /* If the source has a known length replace stpcpy with memcpy. */
1972 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1973 if (!fn)
1974 return false;
1976 gimple_seq stmts = NULL;
1977 tree tem = gimple_convert (&stmts, loc, size_type_node, len);
1978 lenp1 = gimple_build (&stmts, loc, PLUS_EXPR, size_type_node,
1979 tem, build_int_cst (size_type_node, 1));
1980 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
1981 gcall *repl = gimple_build_call (fn, 3, dest, src, lenp1);
1982 gimple_set_vuse (repl, gimple_vuse (stmt));
1983 gimple_set_vdef (repl, gimple_vdef (stmt));
1984 if (gimple_vdef (repl)
1985 && TREE_CODE (gimple_vdef (repl)) == SSA_NAME)
1986 SSA_NAME_DEF_STMT (gimple_vdef (repl)) = repl;
1987 gsi_insert_before (gsi, repl, GSI_SAME_STMT);
1988 /* Replace the result with dest + len. */
1989 stmts = NULL;
1990 tem = gimple_convert (&stmts, loc, sizetype, len);
1991 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
1992 gassign *ret = gimple_build_assign (gimple_call_lhs (stmt),
1993 POINTER_PLUS_EXPR, dest, tem);
1994 gsi_replace (gsi, ret, false);
1995 /* Finally fold the memcpy call. */
1996 gimple_stmt_iterator gsi2 = *gsi;
1997 gsi_prev (&gsi2);
1998 fold_stmt (&gsi2);
1999 return true;
2002 /* Fold a call EXP to {,v}snprintf having NARGS passed as ARGS. Return
2003 NULL_TREE if a normal call should be emitted rather than expanding
2004 the function inline. FCODE is either BUILT_IN_SNPRINTF_CHK or
2005 BUILT_IN_VSNPRINTF_CHK. If MAXLEN is not NULL, it is maximum length
2006 passed as second argument. */
2008 static bool
2009 gimple_fold_builtin_snprintf_chk (gimple_stmt_iterator *gsi,
2010 enum built_in_function fcode)
2012 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2013 tree dest, size, len, fn, fmt, flag;
2014 const char *fmt_str;
2016 /* Verify the required arguments in the original call. */
2017 if (gimple_call_num_args (stmt) < 5)
2018 return false;
2020 dest = gimple_call_arg (stmt, 0);
2021 len = gimple_call_arg (stmt, 1);
2022 flag = gimple_call_arg (stmt, 2);
2023 size = gimple_call_arg (stmt, 3);
2024 fmt = gimple_call_arg (stmt, 4);
2026 if (! tree_fits_uhwi_p (size))
2027 return false;
2029 if (! integer_all_onesp (size))
2031 tree maxlen = get_maxval_strlen (len, 2);
2032 if (! tree_fits_uhwi_p (len))
2034 /* If LEN is not constant, try MAXLEN too.
2035 For MAXLEN only allow optimizing into non-_ocs function
2036 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
2037 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
2038 return false;
2040 else
2041 maxlen = len;
2043 if (tree_int_cst_lt (size, maxlen))
2044 return false;
2047 if (!init_target_chars ())
2048 return false;
2050 /* Only convert __{,v}snprintf_chk to {,v}snprintf if flag is 0
2051 or if format doesn't contain % chars or is "%s". */
2052 if (! integer_zerop (flag))
2054 fmt_str = c_getstr (fmt);
2055 if (fmt_str == NULL)
2056 return false;
2057 if (strchr (fmt_str, target_percent) != NULL
2058 && strcmp (fmt_str, target_percent_s))
2059 return false;
2062 /* If __builtin_{,v}snprintf_chk is used, assume {,v}snprintf is
2063 available. */
2064 fn = builtin_decl_explicit (fcode == BUILT_IN_VSNPRINTF_CHK
2065 ? BUILT_IN_VSNPRINTF : BUILT_IN_SNPRINTF);
2066 if (!fn)
2067 return false;
2069 /* Replace the called function and the first 5 argument by 3 retaining
2070 trailing varargs. */
2071 gimple_call_set_fndecl (stmt, fn);
2072 gimple_call_set_fntype (stmt, TREE_TYPE (fn));
2073 gimple_call_set_arg (stmt, 0, dest);
2074 gimple_call_set_arg (stmt, 1, len);
2075 gimple_call_set_arg (stmt, 2, fmt);
2076 for (unsigned i = 3; i < gimple_call_num_args (stmt) - 2; ++i)
2077 gimple_call_set_arg (stmt, i, gimple_call_arg (stmt, i + 2));
2078 gimple_set_num_ops (stmt, gimple_num_ops (stmt) - 2);
2079 fold_stmt (gsi);
2080 return true;
2083 /* Fold a call EXP to __{,v}sprintf_chk having NARGS passed as ARGS.
2084 Return NULL_TREE if a normal call should be emitted rather than
2085 expanding the function inline. FCODE is either BUILT_IN_SPRINTF_CHK
2086 or BUILT_IN_VSPRINTF_CHK. */
2088 static bool
2089 gimple_fold_builtin_sprintf_chk (gimple_stmt_iterator *gsi,
2090 enum built_in_function fcode)
2092 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2093 tree dest, size, len, fn, fmt, flag;
2094 const char *fmt_str;
2095 unsigned nargs = gimple_call_num_args (stmt);
2097 /* Verify the required arguments in the original call. */
2098 if (nargs < 4)
2099 return false;
2100 dest = gimple_call_arg (stmt, 0);
2101 flag = gimple_call_arg (stmt, 1);
2102 size = gimple_call_arg (stmt, 2);
2103 fmt = gimple_call_arg (stmt, 3);
2105 if (! tree_fits_uhwi_p (size))
2106 return false;
2108 len = NULL_TREE;
2110 if (!init_target_chars ())
2111 return false;
2113 /* Check whether the format is a literal string constant. */
2114 fmt_str = c_getstr (fmt);
2115 if (fmt_str != NULL)
2117 /* If the format doesn't contain % args or %%, we know the size. */
2118 if (strchr (fmt_str, target_percent) == 0)
2120 if (fcode != BUILT_IN_SPRINTF_CHK || nargs == 4)
2121 len = build_int_cstu (size_type_node, strlen (fmt_str));
2123 /* If the format is "%s" and first ... argument is a string literal,
2124 we know the size too. */
2125 else if (fcode == BUILT_IN_SPRINTF_CHK
2126 && strcmp (fmt_str, target_percent_s) == 0)
2128 tree arg;
2130 if (nargs == 5)
2132 arg = gimple_call_arg (stmt, 4);
2133 if (POINTER_TYPE_P (TREE_TYPE (arg)))
2135 len = c_strlen (arg, 1);
2136 if (! len || ! tree_fits_uhwi_p (len))
2137 len = NULL_TREE;
2143 if (! integer_all_onesp (size))
2145 if (! len || ! tree_int_cst_lt (len, size))
2146 return false;
2149 /* Only convert __{,v}sprintf_chk to {,v}sprintf if flag is 0
2150 or if format doesn't contain % chars or is "%s". */
2151 if (! integer_zerop (flag))
2153 if (fmt_str == NULL)
2154 return false;
2155 if (strchr (fmt_str, target_percent) != NULL
2156 && strcmp (fmt_str, target_percent_s))
2157 return false;
2160 /* If __builtin_{,v}sprintf_chk is used, assume {,v}sprintf is available. */
2161 fn = builtin_decl_explicit (fcode == BUILT_IN_VSPRINTF_CHK
2162 ? BUILT_IN_VSPRINTF : BUILT_IN_SPRINTF);
2163 if (!fn)
2164 return false;
2166 /* Replace the called function and the first 4 argument by 2 retaining
2167 trailing varargs. */
2168 gimple_call_set_fndecl (stmt, fn);
2169 gimple_call_set_fntype (stmt, TREE_TYPE (fn));
2170 gimple_call_set_arg (stmt, 0, dest);
2171 gimple_call_set_arg (stmt, 1, fmt);
2172 for (unsigned i = 2; i < gimple_call_num_args (stmt) - 2; ++i)
2173 gimple_call_set_arg (stmt, i, gimple_call_arg (stmt, i + 2));
2174 gimple_set_num_ops (stmt, gimple_num_ops (stmt) - 2);
2175 fold_stmt (gsi);
2176 return true;
2179 /* Simplify a call to the sprintf builtin with arguments DEST, FMT, and ORIG.
2180 ORIG may be null if this is a 2-argument call. We don't attempt to
2181 simplify calls with more than 3 arguments.
2183 Return NULL_TREE if no simplification was possible, otherwise return the
2184 simplified form of the call as a tree. If IGNORED is true, it means that
2185 the caller does not use the returned value of the function. */
2187 static bool
2188 gimple_fold_builtin_sprintf (gimple_stmt_iterator *gsi)
2190 gimple *stmt = gsi_stmt (*gsi);
2191 tree dest = gimple_call_arg (stmt, 0);
2192 tree fmt = gimple_call_arg (stmt, 1);
2193 tree orig = NULL_TREE;
2194 const char *fmt_str = NULL;
2196 /* Verify the required arguments in the original call. We deal with two
2197 types of sprintf() calls: 'sprintf (str, fmt)' and
2198 'sprintf (dest, "%s", orig)'. */
2199 if (gimple_call_num_args (stmt) > 3)
2200 return false;
2202 if (gimple_call_num_args (stmt) == 3)
2203 orig = gimple_call_arg (stmt, 2);
2205 /* Check whether the format is a literal string constant. */
2206 fmt_str = c_getstr (fmt);
2207 if (fmt_str == NULL)
2208 return false;
2210 if (!init_target_chars ())
2211 return false;
2213 /* If the format doesn't contain % args or %%, use strcpy. */
2214 if (strchr (fmt_str, target_percent) == NULL)
2216 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2218 if (!fn)
2219 return false;
2221 /* Don't optimize sprintf (buf, "abc", ptr++). */
2222 if (orig)
2223 return false;
2225 /* Convert sprintf (str, fmt) into strcpy (str, fmt) when
2226 'format' is known to contain no % formats. */
2227 gimple_seq stmts = NULL;
2228 gimple *repl = gimple_build_call (fn, 2, dest, fmt);
2229 gimple_seq_add_stmt_without_update (&stmts, repl);
2230 if (gimple_call_lhs (stmt))
2232 repl = gimple_build_assign (gimple_call_lhs (stmt),
2233 build_int_cst (integer_type_node,
2234 strlen (fmt_str)));
2235 gimple_seq_add_stmt_without_update (&stmts, repl);
2236 gsi_replace_with_seq_vops (gsi, stmts);
2237 /* gsi now points at the assignment to the lhs, get a
2238 stmt iterator to the memcpy call.
2239 ??? We can't use gsi_for_stmt as that doesn't work when the
2240 CFG isn't built yet. */
2241 gimple_stmt_iterator gsi2 = *gsi;
2242 gsi_prev (&gsi2);
2243 fold_stmt (&gsi2);
2245 else
2247 gsi_replace_with_seq_vops (gsi, stmts);
2248 fold_stmt (gsi);
2250 return true;
2253 /* If the format is "%s", use strcpy if the result isn't used. */
2254 else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
2256 tree fn;
2257 fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2259 if (!fn)
2260 return false;
2262 /* Don't crash on sprintf (str1, "%s"). */
2263 if (!orig)
2264 return false;
2266 tree orig_len = NULL_TREE;
2267 if (gimple_call_lhs (stmt))
2269 orig_len = get_maxval_strlen (orig, 0);
2270 if (!orig_len)
2271 return false;
2274 /* Convert sprintf (str1, "%s", str2) into strcpy (str1, str2). */
2275 gimple_seq stmts = NULL;
2276 gimple *repl = gimple_build_call (fn, 2, dest, orig);
2277 gimple_seq_add_stmt_without_update (&stmts, repl);
2278 if (gimple_call_lhs (stmt))
2280 if (!useless_type_conversion_p (integer_type_node,
2281 TREE_TYPE (orig_len)))
2282 orig_len = fold_convert (integer_type_node, orig_len);
2283 repl = gimple_build_assign (gimple_call_lhs (stmt), orig_len);
2284 gimple_seq_add_stmt_without_update (&stmts, repl);
2285 gsi_replace_with_seq_vops (gsi, stmts);
2286 /* gsi now points at the assignment to the lhs, get a
2287 stmt iterator to the memcpy call.
2288 ??? We can't use gsi_for_stmt as that doesn't work when the
2289 CFG isn't built yet. */
2290 gimple_stmt_iterator gsi2 = *gsi;
2291 gsi_prev (&gsi2);
2292 fold_stmt (&gsi2);
2294 else
2296 gsi_replace_with_seq_vops (gsi, stmts);
2297 fold_stmt (gsi);
2299 return true;
2301 return false;
2304 /* Simplify a call to the snprintf builtin with arguments DEST, DESTSIZE,
2305 FMT, and ORIG. ORIG may be null if this is a 3-argument call. We don't
2306 attempt to simplify calls with more than 4 arguments.
2308 Return NULL_TREE if no simplification was possible, otherwise return the
2309 simplified form of the call as a tree. If IGNORED is true, it means that
2310 the caller does not use the returned value of the function. */
2312 static bool
2313 gimple_fold_builtin_snprintf (gimple_stmt_iterator *gsi)
2315 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2316 tree dest = gimple_call_arg (stmt, 0);
2317 tree destsize = gimple_call_arg (stmt, 1);
2318 tree fmt = gimple_call_arg (stmt, 2);
2319 tree orig = NULL_TREE;
2320 const char *fmt_str = NULL;
2322 if (gimple_call_num_args (stmt) > 4)
2323 return false;
2325 if (gimple_call_num_args (stmt) == 4)
2326 orig = gimple_call_arg (stmt, 3);
2328 if (!tree_fits_uhwi_p (destsize))
2329 return false;
2330 unsigned HOST_WIDE_INT destlen = tree_to_uhwi (destsize);
2332 /* Check whether the format is a literal string constant. */
2333 fmt_str = c_getstr (fmt);
2334 if (fmt_str == NULL)
2335 return false;
2337 if (!init_target_chars ())
2338 return false;
2340 /* If the format doesn't contain % args or %%, use strcpy. */
2341 if (strchr (fmt_str, target_percent) == NULL)
2343 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2344 if (!fn)
2345 return false;
2347 /* Don't optimize snprintf (buf, 4, "abc", ptr++). */
2348 if (orig)
2349 return false;
2351 /* We could expand this as
2352 memcpy (str, fmt, cst - 1); str[cst - 1] = '\0';
2353 or to
2354 memcpy (str, fmt_with_nul_at_cstm1, cst);
2355 but in the former case that might increase code size
2356 and in the latter case grow .rodata section too much.
2357 So punt for now. */
2358 size_t len = strlen (fmt_str);
2359 if (len >= destlen)
2360 return false;
2362 gimple_seq stmts = NULL;
2363 gimple *repl = gimple_build_call (fn, 2, dest, fmt);
2364 gimple_seq_add_stmt_without_update (&stmts, repl);
2365 if (gimple_call_lhs (stmt))
2367 repl = gimple_build_assign (gimple_call_lhs (stmt),
2368 build_int_cst (integer_type_node, len));
2369 gimple_seq_add_stmt_without_update (&stmts, repl);
2370 gsi_replace_with_seq_vops (gsi, stmts);
2371 /* gsi now points at the assignment to the lhs, get a
2372 stmt iterator to the memcpy call.
2373 ??? We can't use gsi_for_stmt as that doesn't work when the
2374 CFG isn't built yet. */
2375 gimple_stmt_iterator gsi2 = *gsi;
2376 gsi_prev (&gsi2);
2377 fold_stmt (&gsi2);
2379 else
2381 gsi_replace_with_seq_vops (gsi, stmts);
2382 fold_stmt (gsi);
2384 return true;
2387 /* If the format is "%s", use strcpy if the result isn't used. */
2388 else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
2390 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2391 if (!fn)
2392 return false;
2394 /* Don't crash on snprintf (str1, cst, "%s"). */
2395 if (!orig)
2396 return false;
2398 tree orig_len = get_maxval_strlen (orig, 0);
2399 if (!orig_len || TREE_CODE (orig_len) != INTEGER_CST)
2400 return false;
2402 /* We could expand this as
2403 memcpy (str1, str2, cst - 1); str1[cst - 1] = '\0';
2404 or to
2405 memcpy (str1, str2_with_nul_at_cstm1, cst);
2406 but in the former case that might increase code size
2407 and in the latter case grow .rodata section too much.
2408 So punt for now. */
2409 if (compare_tree_int (orig_len, destlen) >= 0)
2410 return false;
2412 /* Convert snprintf (str1, cst, "%s", str2) into
2413 strcpy (str1, str2) if strlen (str2) < cst. */
2414 gimple_seq stmts = NULL;
2415 gimple *repl = gimple_build_call (fn, 2, dest, orig);
2416 gimple_seq_add_stmt_without_update (&stmts, repl);
2417 if (gimple_call_lhs (stmt))
2419 if (!useless_type_conversion_p (integer_type_node,
2420 TREE_TYPE (orig_len)))
2421 orig_len = fold_convert (integer_type_node, orig_len);
2422 repl = gimple_build_assign (gimple_call_lhs (stmt), orig_len);
2423 gimple_seq_add_stmt_without_update (&stmts, repl);
2424 gsi_replace_with_seq_vops (gsi, stmts);
2425 /* gsi now points at the assignment to the lhs, get a
2426 stmt iterator to the memcpy call.
2427 ??? We can't use gsi_for_stmt as that doesn't work when the
2428 CFG isn't built yet. */
2429 gimple_stmt_iterator gsi2 = *gsi;
2430 gsi_prev (&gsi2);
2431 fold_stmt (&gsi2);
2433 else
2435 gsi_replace_with_seq_vops (gsi, stmts);
2436 fold_stmt (gsi);
2438 return true;
2440 return false;
2443 /* Fold a call to the {,v}fprintf{,_unlocked} and __{,v}printf_chk builtins.
2444 FP, FMT, and ARG are the arguments to the call. We don't fold calls with
2445 more than 3 arguments, and ARG may be null in the 2-argument case.
2447 Return NULL_TREE if no simplification was possible, otherwise return the
2448 simplified form of the call as a tree. FCODE is the BUILT_IN_*
2449 code of the function to be simplified. */
2451 static bool
2452 gimple_fold_builtin_fprintf (gimple_stmt_iterator *gsi,
2453 tree fp, tree fmt, tree arg,
2454 enum built_in_function fcode)
2456 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2457 tree fn_fputc, fn_fputs;
2458 const char *fmt_str = NULL;
2460 /* If the return value is used, don't do the transformation. */
2461 if (gimple_call_lhs (stmt) != NULL_TREE)
2462 return false;
2464 /* Check whether the format is a literal string constant. */
2465 fmt_str = c_getstr (fmt);
2466 if (fmt_str == NULL)
2467 return false;
2469 if (fcode == BUILT_IN_FPRINTF_UNLOCKED)
2471 /* If we're using an unlocked function, assume the other
2472 unlocked functions exist explicitly. */
2473 fn_fputc = builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED);
2474 fn_fputs = builtin_decl_explicit (BUILT_IN_FPUTS_UNLOCKED);
2476 else
2478 fn_fputc = builtin_decl_implicit (BUILT_IN_FPUTC);
2479 fn_fputs = builtin_decl_implicit (BUILT_IN_FPUTS);
2482 if (!init_target_chars ())
2483 return false;
2485 /* If the format doesn't contain % args or %%, use strcpy. */
2486 if (strchr (fmt_str, target_percent) == NULL)
2488 if (fcode != BUILT_IN_VFPRINTF && fcode != BUILT_IN_VFPRINTF_CHK
2489 && arg)
2490 return false;
2492 /* If the format specifier was "", fprintf does nothing. */
2493 if (fmt_str[0] == '\0')
2495 replace_call_with_value (gsi, NULL_TREE);
2496 return true;
2499 /* When "string" doesn't contain %, replace all cases of
2500 fprintf (fp, string) with fputs (string, fp). The fputs
2501 builtin will take care of special cases like length == 1. */
2502 if (fn_fputs)
2504 gcall *repl = gimple_build_call (fn_fputs, 2, fmt, fp);
2505 replace_call_with_call_and_fold (gsi, repl);
2506 return true;
2510 /* The other optimizations can be done only on the non-va_list variants. */
2511 else if (fcode == BUILT_IN_VFPRINTF || fcode == BUILT_IN_VFPRINTF_CHK)
2512 return false;
2514 /* If the format specifier was "%s", call __builtin_fputs (arg, fp). */
2515 else if (strcmp (fmt_str, target_percent_s) == 0)
2517 if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
2518 return false;
2519 if (fn_fputs)
2521 gcall *repl = gimple_build_call (fn_fputs, 2, arg, fp);
2522 replace_call_with_call_and_fold (gsi, repl);
2523 return true;
2527 /* If the format specifier was "%c", call __builtin_fputc (arg, fp). */
2528 else if (strcmp (fmt_str, target_percent_c) == 0)
2530 if (!arg
2531 || ! useless_type_conversion_p (integer_type_node, TREE_TYPE (arg)))
2532 return false;
2533 if (fn_fputc)
2535 gcall *repl = gimple_build_call (fn_fputc, 2, arg, fp);
2536 replace_call_with_call_and_fold (gsi, repl);
2537 return true;
2541 return false;
2544 /* Fold a call to the {,v}printf{,_unlocked} and __{,v}printf_chk builtins.
2545 FMT and ARG are the arguments to the call; we don't fold cases with
2546 more than 2 arguments, and ARG may be null if this is a 1-argument case.
2548 Return NULL_TREE if no simplification was possible, otherwise return the
2549 simplified form of the call as a tree. FCODE is the BUILT_IN_*
2550 code of the function to be simplified. */
2552 static bool
2553 gimple_fold_builtin_printf (gimple_stmt_iterator *gsi, tree fmt,
2554 tree arg, enum built_in_function fcode)
2556 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2557 tree fn_putchar, fn_puts, newarg;
2558 const char *fmt_str = NULL;
2560 /* If the return value is used, don't do the transformation. */
2561 if (gimple_call_lhs (stmt) != NULL_TREE)
2562 return false;
2564 /* Check whether the format is a literal string constant. */
2565 fmt_str = c_getstr (fmt);
2566 if (fmt_str == NULL)
2567 return false;
2569 if (fcode == BUILT_IN_PRINTF_UNLOCKED)
2571 /* If we're using an unlocked function, assume the other
2572 unlocked functions exist explicitly. */
2573 fn_putchar = builtin_decl_explicit (BUILT_IN_PUTCHAR_UNLOCKED);
2574 fn_puts = builtin_decl_explicit (BUILT_IN_PUTS_UNLOCKED);
2576 else
2578 fn_putchar = builtin_decl_implicit (BUILT_IN_PUTCHAR);
2579 fn_puts = builtin_decl_implicit (BUILT_IN_PUTS);
2582 if (!init_target_chars ())
2583 return false;
2585 if (strcmp (fmt_str, target_percent_s) == 0
2586 || strchr (fmt_str, target_percent) == NULL)
2588 const char *str;
2590 if (strcmp (fmt_str, target_percent_s) == 0)
2592 if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
2593 return false;
2595 if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
2596 return false;
2598 str = c_getstr (arg);
2599 if (str == NULL)
2600 return false;
2602 else
2604 /* The format specifier doesn't contain any '%' characters. */
2605 if (fcode != BUILT_IN_VPRINTF && fcode != BUILT_IN_VPRINTF_CHK
2606 && arg)
2607 return false;
2608 str = fmt_str;
2611 /* If the string was "", printf does nothing. */
2612 if (str[0] == '\0')
2614 replace_call_with_value (gsi, NULL_TREE);
2615 return true;
2618 /* If the string has length of 1, call putchar. */
2619 if (str[1] == '\0')
2621 /* Given printf("c"), (where c is any one character,)
2622 convert "c"[0] to an int and pass that to the replacement
2623 function. */
2624 newarg = build_int_cst (integer_type_node, str[0]);
2625 if (fn_putchar)
2627 gcall *repl = gimple_build_call (fn_putchar, 1, newarg);
2628 replace_call_with_call_and_fold (gsi, repl);
2629 return true;
2632 else
2634 /* If the string was "string\n", call puts("string"). */
2635 size_t len = strlen (str);
2636 if ((unsigned char)str[len - 1] == target_newline
2637 && (size_t) (int) len == len
2638 && (int) len > 0)
2640 char *newstr;
2641 tree offset_node, string_cst;
2643 /* Create a NUL-terminated string that's one char shorter
2644 than the original, stripping off the trailing '\n'. */
2645 newarg = build_string_literal (len, str);
2646 string_cst = string_constant (newarg, &offset_node);
2647 gcc_checking_assert (string_cst
2648 && (TREE_STRING_LENGTH (string_cst)
2649 == (int) len)
2650 && integer_zerop (offset_node)
2651 && (unsigned char)
2652 TREE_STRING_POINTER (string_cst)[len - 1]
2653 == target_newline);
2654 /* build_string_literal creates a new STRING_CST,
2655 modify it in place to avoid double copying. */
2656 newstr = CONST_CAST (char *, TREE_STRING_POINTER (string_cst));
2657 newstr[len - 1] = '\0';
2658 if (fn_puts)
2660 gcall *repl = gimple_build_call (fn_puts, 1, newarg);
2661 replace_call_with_call_and_fold (gsi, repl);
2662 return true;
2665 else
2666 /* We'd like to arrange to call fputs(string,stdout) here,
2667 but we need stdout and don't have a way to get it yet. */
2668 return false;
2672 /* The other optimizations can be done only on the non-va_list variants. */
2673 else if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
2674 return false;
2676 /* If the format specifier was "%s\n", call __builtin_puts(arg). */
2677 else if (strcmp (fmt_str, target_percent_s_newline) == 0)
2679 if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
2680 return false;
2681 if (fn_puts)
2683 gcall *repl = gimple_build_call (fn_puts, 1, arg);
2684 replace_call_with_call_and_fold (gsi, repl);
2685 return true;
2689 /* If the format specifier was "%c", call __builtin_putchar(arg). */
2690 else if (strcmp (fmt_str, target_percent_c) == 0)
2692 if (!arg || ! useless_type_conversion_p (integer_type_node,
2693 TREE_TYPE (arg)))
2694 return false;
2695 if (fn_putchar)
2697 gcall *repl = gimple_build_call (fn_putchar, 1, arg);
2698 replace_call_with_call_and_fold (gsi, repl);
2699 return true;
2703 return false;
2708 /* Fold a call to __builtin_strlen with known length LEN. */
2710 static bool
2711 gimple_fold_builtin_strlen (gimple_stmt_iterator *gsi)
2713 gimple *stmt = gsi_stmt (*gsi);
2714 tree len = get_maxval_strlen (gimple_call_arg (stmt, 0), 0);
2715 if (!len)
2716 return false;
2717 len = force_gimple_operand_gsi (gsi, len, true, NULL, true, GSI_SAME_STMT);
2718 replace_call_with_value (gsi, len);
2719 return true;
2722 /* Fold a call to __builtin_acc_on_device. */
2724 static bool
2725 gimple_fold_builtin_acc_on_device (gimple_stmt_iterator *gsi, tree arg0)
2727 /* Defer folding until we know which compiler we're in. */
2728 if (symtab->state != EXPANSION)
2729 return false;
2731 unsigned val_host = GOMP_DEVICE_HOST;
2732 unsigned val_dev = GOMP_DEVICE_NONE;
2734 #ifdef ACCEL_COMPILER
2735 val_host = GOMP_DEVICE_NOT_HOST;
2736 val_dev = ACCEL_COMPILER_acc_device;
2737 #endif
2739 location_t loc = gimple_location (gsi_stmt (*gsi));
2741 tree host_eq = make_ssa_name (boolean_type_node);
2742 gimple *host_ass = gimple_build_assign
2743 (host_eq, EQ_EXPR, arg0, build_int_cst (TREE_TYPE (arg0), val_host));
2744 gimple_set_location (host_ass, loc);
2745 gsi_insert_before (gsi, host_ass, GSI_SAME_STMT);
2747 tree dev_eq = make_ssa_name (boolean_type_node);
2748 gimple *dev_ass = gimple_build_assign
2749 (dev_eq, EQ_EXPR, arg0, build_int_cst (TREE_TYPE (arg0), val_dev));
2750 gimple_set_location (dev_ass, loc);
2751 gsi_insert_before (gsi, dev_ass, GSI_SAME_STMT);
2753 tree result = make_ssa_name (boolean_type_node);
2754 gimple *result_ass = gimple_build_assign
2755 (result, BIT_IOR_EXPR, host_eq, dev_eq);
2756 gimple_set_location (result_ass, loc);
2757 gsi_insert_before (gsi, result_ass, GSI_SAME_STMT);
2759 replace_call_with_value (gsi, result);
2761 return true;
2764 /* Fold the non-target builtin at *GSI and return whether any simplification
2765 was made. */
2767 static bool
2768 gimple_fold_builtin (gimple_stmt_iterator *gsi)
2770 gcall *stmt = as_a <gcall *>(gsi_stmt (*gsi));
2771 tree callee = gimple_call_fndecl (stmt);
2773 /* Give up for always_inline inline builtins until they are
2774 inlined. */
2775 if (avoid_folding_inline_builtin (callee))
2776 return false;
2778 unsigned n = gimple_call_num_args (stmt);
2779 enum built_in_function fcode = DECL_FUNCTION_CODE (callee);
2780 switch (fcode)
2782 case BUILT_IN_BZERO:
2783 return gimple_fold_builtin_memset (gsi, integer_zero_node,
2784 gimple_call_arg (stmt, 1));
2785 case BUILT_IN_MEMSET:
2786 return gimple_fold_builtin_memset (gsi,
2787 gimple_call_arg (stmt, 1),
2788 gimple_call_arg (stmt, 2));
2789 case BUILT_IN_BCOPY:
2790 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 1),
2791 gimple_call_arg (stmt, 0), 3);
2792 case BUILT_IN_MEMCPY:
2793 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
2794 gimple_call_arg (stmt, 1), 0);
2795 case BUILT_IN_MEMPCPY:
2796 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
2797 gimple_call_arg (stmt, 1), 1);
2798 case BUILT_IN_MEMMOVE:
2799 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
2800 gimple_call_arg (stmt, 1), 3);
2801 case BUILT_IN_SPRINTF_CHK:
2802 case BUILT_IN_VSPRINTF_CHK:
2803 return gimple_fold_builtin_sprintf_chk (gsi, fcode);
2804 case BUILT_IN_STRCAT_CHK:
2805 return gimple_fold_builtin_strcat_chk (gsi);
2806 case BUILT_IN_STRNCAT_CHK:
2807 return gimple_fold_builtin_strncat_chk (gsi);
2808 case BUILT_IN_STRLEN:
2809 return gimple_fold_builtin_strlen (gsi);
2810 case BUILT_IN_STRCPY:
2811 return gimple_fold_builtin_strcpy (gsi,
2812 gimple_call_arg (stmt, 0),
2813 gimple_call_arg (stmt, 1));
2814 case BUILT_IN_STRNCPY:
2815 return gimple_fold_builtin_strncpy (gsi,
2816 gimple_call_arg (stmt, 0),
2817 gimple_call_arg (stmt, 1),
2818 gimple_call_arg (stmt, 2));
2819 case BUILT_IN_STRCAT:
2820 return gimple_fold_builtin_strcat (gsi, gimple_call_arg (stmt, 0),
2821 gimple_call_arg (stmt, 1));
2822 case BUILT_IN_STRNCAT:
2823 return gimple_fold_builtin_strncat (gsi);
2824 case BUILT_IN_FPUTS:
2825 return gimple_fold_builtin_fputs (gsi, gimple_call_arg (stmt, 0),
2826 gimple_call_arg (stmt, 1), false);
2827 case BUILT_IN_FPUTS_UNLOCKED:
2828 return gimple_fold_builtin_fputs (gsi, gimple_call_arg (stmt, 0),
2829 gimple_call_arg (stmt, 1), true);
2830 case BUILT_IN_MEMCPY_CHK:
2831 case BUILT_IN_MEMPCPY_CHK:
2832 case BUILT_IN_MEMMOVE_CHK:
2833 case BUILT_IN_MEMSET_CHK:
2834 return gimple_fold_builtin_memory_chk (gsi,
2835 gimple_call_arg (stmt, 0),
2836 gimple_call_arg (stmt, 1),
2837 gimple_call_arg (stmt, 2),
2838 gimple_call_arg (stmt, 3),
2839 fcode);
2840 case BUILT_IN_STPCPY:
2841 return gimple_fold_builtin_stpcpy (gsi);
2842 case BUILT_IN_STRCPY_CHK:
2843 case BUILT_IN_STPCPY_CHK:
2844 return gimple_fold_builtin_stxcpy_chk (gsi,
2845 gimple_call_arg (stmt, 0),
2846 gimple_call_arg (stmt, 1),
2847 gimple_call_arg (stmt, 2),
2848 fcode);
2849 case BUILT_IN_STRNCPY_CHK:
2850 case BUILT_IN_STPNCPY_CHK:
2851 return gimple_fold_builtin_stxncpy_chk (gsi,
2852 gimple_call_arg (stmt, 0),
2853 gimple_call_arg (stmt, 1),
2854 gimple_call_arg (stmt, 2),
2855 gimple_call_arg (stmt, 3),
2856 fcode);
2857 case BUILT_IN_SNPRINTF_CHK:
2858 case BUILT_IN_VSNPRINTF_CHK:
2859 return gimple_fold_builtin_snprintf_chk (gsi, fcode);
2860 case BUILT_IN_SNPRINTF:
2861 return gimple_fold_builtin_snprintf (gsi);
2862 case BUILT_IN_SPRINTF:
2863 return gimple_fold_builtin_sprintf (gsi);
2864 case BUILT_IN_FPRINTF:
2865 case BUILT_IN_FPRINTF_UNLOCKED:
2866 case BUILT_IN_VFPRINTF:
2867 if (n == 2 || n == 3)
2868 return gimple_fold_builtin_fprintf (gsi,
2869 gimple_call_arg (stmt, 0),
2870 gimple_call_arg (stmt, 1),
2871 n == 3
2872 ? gimple_call_arg (stmt, 2)
2873 : NULL_TREE,
2874 fcode);
2875 break;
2876 case BUILT_IN_FPRINTF_CHK:
2877 case BUILT_IN_VFPRINTF_CHK:
2878 if (n == 3 || n == 4)
2879 return gimple_fold_builtin_fprintf (gsi,
2880 gimple_call_arg (stmt, 0),
2881 gimple_call_arg (stmt, 2),
2882 n == 4
2883 ? gimple_call_arg (stmt, 3)
2884 : NULL_TREE,
2885 fcode);
2886 break;
2887 case BUILT_IN_PRINTF:
2888 case BUILT_IN_PRINTF_UNLOCKED:
2889 case BUILT_IN_VPRINTF:
2890 if (n == 1 || n == 2)
2891 return gimple_fold_builtin_printf (gsi, gimple_call_arg (stmt, 0),
2892 n == 2
2893 ? gimple_call_arg (stmt, 1)
2894 : NULL_TREE, fcode);
2895 break;
2896 case BUILT_IN_PRINTF_CHK:
2897 case BUILT_IN_VPRINTF_CHK:
2898 if (n == 2 || n == 3)
2899 return gimple_fold_builtin_printf (gsi, gimple_call_arg (stmt, 1),
2900 n == 3
2901 ? gimple_call_arg (stmt, 2)
2902 : NULL_TREE, fcode);
2903 break;
2904 case BUILT_IN_ACC_ON_DEVICE:
2905 return gimple_fold_builtin_acc_on_device (gsi,
2906 gimple_call_arg (stmt, 0));
2907 default:;
2910 /* Try the generic builtin folder. */
2911 bool ignore = (gimple_call_lhs (stmt) == NULL);
2912 tree result = fold_call_stmt (stmt, ignore);
2913 if (result)
2915 if (ignore)
2916 STRIP_NOPS (result);
2917 else
2918 result = fold_convert (gimple_call_return_type (stmt), result);
2919 if (!update_call_from_tree (gsi, result))
2920 gimplify_and_update_call_from_tree (gsi, result);
2921 return true;
2924 return false;
2927 /* Transform IFN_GOACC_DIM_SIZE and IFN_GOACC_DIM_POS internal
2928 function calls to constants, where possible. */
2930 static tree
2931 fold_internal_goacc_dim (const gimple *call)
2933 int axis = get_oacc_ifn_dim_arg (call);
2934 int size = get_oacc_fn_dim_size (current_function_decl, axis);
2935 bool is_pos = gimple_call_internal_fn (call) == IFN_GOACC_DIM_POS;
2936 tree result = NULL_TREE;
2938 /* If the size is 1, or we only want the size and it is not dynamic,
2939 we know the answer. */
2940 if (size == 1 || (!is_pos && size))
2942 tree type = TREE_TYPE (gimple_call_lhs (call));
2943 result = build_int_cst (type, size - is_pos);
2946 return result;
2949 /* Return true if ARG0 CODE ARG1 in infinite signed precision operation
2950 doesn't fit into TYPE. The test for overflow should be regardless of
2951 -fwrapv, and even for unsigned types. */
2953 bool
2954 arith_overflowed_p (enum tree_code code, const_tree type,
2955 const_tree arg0, const_tree arg1)
2957 typedef FIXED_WIDE_INT (WIDE_INT_MAX_PRECISION * 2) widest2_int;
2958 typedef generic_wide_int <wi::extended_tree <WIDE_INT_MAX_PRECISION * 2> >
2959 widest2_int_cst;
2960 widest2_int warg0 = widest2_int_cst (arg0);
2961 widest2_int warg1 = widest2_int_cst (arg1);
2962 widest2_int wres;
2963 switch (code)
2965 case PLUS_EXPR: wres = wi::add (warg0, warg1); break;
2966 case MINUS_EXPR: wres = wi::sub (warg0, warg1); break;
2967 case MULT_EXPR: wres = wi::mul (warg0, warg1); break;
2968 default: gcc_unreachable ();
2970 signop sign = TYPE_SIGN (type);
2971 if (sign == UNSIGNED && wi::neg_p (wres))
2972 return true;
2973 return wi::min_precision (wres, sign) > TYPE_PRECISION (type);
2976 /* Attempt to fold a call statement referenced by the statement iterator GSI.
2977 The statement may be replaced by another statement, e.g., if the call
2978 simplifies to a constant value. Return true if any changes were made.
2979 It is assumed that the operands have been previously folded. */
2981 static bool
2982 gimple_fold_call (gimple_stmt_iterator *gsi, bool inplace)
2984 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2985 tree callee;
2986 bool changed = false;
2987 unsigned i;
2989 /* Fold *& in call arguments. */
2990 for (i = 0; i < gimple_call_num_args (stmt); ++i)
2991 if (REFERENCE_CLASS_P (gimple_call_arg (stmt, i)))
2993 tree tmp = maybe_fold_reference (gimple_call_arg (stmt, i), false);
2994 if (tmp)
2996 gimple_call_set_arg (stmt, i, tmp);
2997 changed = true;
3001 /* Check for virtual calls that became direct calls. */
3002 callee = gimple_call_fn (stmt);
3003 if (callee && TREE_CODE (callee) == OBJ_TYPE_REF)
3005 if (gimple_call_addr_fndecl (OBJ_TYPE_REF_EXPR (callee)) != NULL_TREE)
3007 if (dump_file && virtual_method_call_p (callee)
3008 && !possible_polymorphic_call_target_p
3009 (callee, stmt, cgraph_node::get (gimple_call_addr_fndecl
3010 (OBJ_TYPE_REF_EXPR (callee)))))
3012 fprintf (dump_file,
3013 "Type inheritance inconsistent devirtualization of ");
3014 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
3015 fprintf (dump_file, " to ");
3016 print_generic_expr (dump_file, callee, TDF_SLIM);
3017 fprintf (dump_file, "\n");
3020 gimple_call_set_fn (stmt, OBJ_TYPE_REF_EXPR (callee));
3021 changed = true;
3023 else if (flag_devirtualize && !inplace && virtual_method_call_p (callee))
3025 bool final;
3026 vec <cgraph_node *>targets
3027 = possible_polymorphic_call_targets (callee, stmt, &final);
3028 if (final && targets.length () <= 1 && dbg_cnt (devirt))
3030 tree lhs = gimple_call_lhs (stmt);
3031 if (dump_enabled_p ())
3033 location_t loc = gimple_location_safe (stmt);
3034 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, loc,
3035 "folding virtual function call to %s\n",
3036 targets.length () == 1
3037 ? targets[0]->name ()
3038 : "__builtin_unreachable");
3040 if (targets.length () == 1)
3042 gimple_call_set_fndecl (stmt, targets[0]->decl);
3043 changed = true;
3044 /* If the call becomes noreturn, remove the lhs. */
3045 if (lhs && (gimple_call_flags (stmt) & ECF_NORETURN))
3047 if (TREE_CODE (lhs) == SSA_NAME)
3049 tree var = create_tmp_var (TREE_TYPE (lhs));
3050 tree def = get_or_create_ssa_default_def (cfun, var);
3051 gimple *new_stmt = gimple_build_assign (lhs, def);
3052 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
3054 gimple_call_set_lhs (stmt, NULL_TREE);
3056 maybe_remove_unused_call_args (cfun, stmt);
3058 else
3060 tree fndecl = builtin_decl_implicit (BUILT_IN_UNREACHABLE);
3061 gimple *new_stmt = gimple_build_call (fndecl, 0);
3062 gimple_set_location (new_stmt, gimple_location (stmt));
3063 if (lhs && TREE_CODE (lhs) == SSA_NAME)
3065 tree var = create_tmp_var (TREE_TYPE (lhs));
3066 tree def = get_or_create_ssa_default_def (cfun, var);
3068 /* To satisfy condition for
3069 cgraph_update_edges_for_call_stmt_node,
3070 we need to preserve GIMPLE_CALL statement
3071 at position of GSI iterator. */
3072 update_call_from_tree (gsi, def);
3073 gsi_insert_before (gsi, new_stmt, GSI_NEW_STMT);
3075 else
3077 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
3078 gimple_set_vdef (new_stmt, gimple_vdef (stmt));
3079 gsi_replace (gsi, new_stmt, false);
3081 return true;
3087 /* Check for indirect calls that became direct calls, and then
3088 no longer require a static chain. */
3089 if (gimple_call_chain (stmt))
3091 tree fn = gimple_call_fndecl (stmt);
3092 if (fn && !DECL_STATIC_CHAIN (fn))
3094 gimple_call_set_chain (stmt, NULL);
3095 changed = true;
3097 else
3099 tree tmp = maybe_fold_reference (gimple_call_chain (stmt), false);
3100 if (tmp)
3102 gimple_call_set_chain (stmt, tmp);
3103 changed = true;
3108 if (inplace)
3109 return changed;
3111 /* Check for builtins that CCP can handle using information not
3112 available in the generic fold routines. */
3113 if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
3115 if (gimple_fold_builtin (gsi))
3116 changed = true;
3118 else if (gimple_call_builtin_p (stmt, BUILT_IN_MD))
3120 changed |= targetm.gimple_fold_builtin (gsi);
3122 else if (gimple_call_internal_p (stmt))
3124 enum tree_code subcode = ERROR_MARK;
3125 tree result = NULL_TREE;
3126 bool cplx_result = false;
3127 tree overflow = NULL_TREE;
3128 switch (gimple_call_internal_fn (stmt))
3130 case IFN_BUILTIN_EXPECT:
3131 result = fold_builtin_expect (gimple_location (stmt),
3132 gimple_call_arg (stmt, 0),
3133 gimple_call_arg (stmt, 1),
3134 gimple_call_arg (stmt, 2));
3135 break;
3136 case IFN_UBSAN_OBJECT_SIZE:
3137 if (integer_all_onesp (gimple_call_arg (stmt, 2))
3138 || (TREE_CODE (gimple_call_arg (stmt, 1)) == INTEGER_CST
3139 && TREE_CODE (gimple_call_arg (stmt, 2)) == INTEGER_CST
3140 && tree_int_cst_le (gimple_call_arg (stmt, 1),
3141 gimple_call_arg (stmt, 2))))
3143 gsi_replace (gsi, gimple_build_nop (), false);
3144 unlink_stmt_vdef (stmt);
3145 release_defs (stmt);
3146 return true;
3148 break;
3149 case IFN_GOACC_DIM_SIZE:
3150 case IFN_GOACC_DIM_POS:
3151 result = fold_internal_goacc_dim (stmt);
3152 break;
3153 case IFN_UBSAN_CHECK_ADD:
3154 subcode = PLUS_EXPR;
3155 break;
3156 case IFN_UBSAN_CHECK_SUB:
3157 subcode = MINUS_EXPR;
3158 break;
3159 case IFN_UBSAN_CHECK_MUL:
3160 subcode = MULT_EXPR;
3161 break;
3162 case IFN_ADD_OVERFLOW:
3163 subcode = PLUS_EXPR;
3164 cplx_result = true;
3165 break;
3166 case IFN_SUB_OVERFLOW:
3167 subcode = MINUS_EXPR;
3168 cplx_result = true;
3169 break;
3170 case IFN_MUL_OVERFLOW:
3171 subcode = MULT_EXPR;
3172 cplx_result = true;
3173 break;
3174 default:
3175 break;
3177 if (subcode != ERROR_MARK)
3179 tree arg0 = gimple_call_arg (stmt, 0);
3180 tree arg1 = gimple_call_arg (stmt, 1);
3181 tree type = TREE_TYPE (arg0);
3182 if (cplx_result)
3184 tree lhs = gimple_call_lhs (stmt);
3185 if (lhs == NULL_TREE)
3186 type = NULL_TREE;
3187 else
3188 type = TREE_TYPE (TREE_TYPE (lhs));
3190 if (type == NULL_TREE)
3192 /* x = y + 0; x = y - 0; x = y * 0; */
3193 else if (integer_zerop (arg1))
3194 result = subcode == MULT_EXPR ? integer_zero_node : arg0;
3195 /* x = 0 + y; x = 0 * y; */
3196 else if (subcode != MINUS_EXPR && integer_zerop (arg0))
3197 result = subcode == MULT_EXPR ? integer_zero_node : arg1;
3198 /* x = y - y; */
3199 else if (subcode == MINUS_EXPR && operand_equal_p (arg0, arg1, 0))
3200 result = integer_zero_node;
3201 /* x = y * 1; x = 1 * y; */
3202 else if (subcode == MULT_EXPR && integer_onep (arg1))
3203 result = arg0;
3204 else if (subcode == MULT_EXPR && integer_onep (arg0))
3205 result = arg1;
3206 else if (TREE_CODE (arg0) == INTEGER_CST
3207 && TREE_CODE (arg1) == INTEGER_CST)
3209 if (cplx_result)
3210 result = int_const_binop (subcode, fold_convert (type, arg0),
3211 fold_convert (type, arg1));
3212 else
3213 result = int_const_binop (subcode, arg0, arg1);
3214 if (result && arith_overflowed_p (subcode, type, arg0, arg1))
3216 if (cplx_result)
3217 overflow = build_one_cst (type);
3218 else
3219 result = NULL_TREE;
3222 if (result)
3224 if (result == integer_zero_node)
3225 result = build_zero_cst (type);
3226 else if (cplx_result && TREE_TYPE (result) != type)
3228 if (TREE_CODE (result) == INTEGER_CST)
3230 if (arith_overflowed_p (PLUS_EXPR, type, result,
3231 integer_zero_node))
3232 overflow = build_one_cst (type);
3234 else if ((!TYPE_UNSIGNED (TREE_TYPE (result))
3235 && TYPE_UNSIGNED (type))
3236 || (TYPE_PRECISION (type)
3237 < (TYPE_PRECISION (TREE_TYPE (result))
3238 + (TYPE_UNSIGNED (TREE_TYPE (result))
3239 && !TYPE_UNSIGNED (type)))))
3240 result = NULL_TREE;
3241 if (result)
3242 result = fold_convert (type, result);
3247 if (result)
3249 if (TREE_CODE (result) == INTEGER_CST && TREE_OVERFLOW (result))
3250 result = drop_tree_overflow (result);
3251 if (cplx_result)
3253 if (overflow == NULL_TREE)
3254 overflow = build_zero_cst (TREE_TYPE (result));
3255 tree ctype = build_complex_type (TREE_TYPE (result));
3256 if (TREE_CODE (result) == INTEGER_CST
3257 && TREE_CODE (overflow) == INTEGER_CST)
3258 result = build_complex (ctype, result, overflow);
3259 else
3260 result = build2_loc (gimple_location (stmt), COMPLEX_EXPR,
3261 ctype, result, overflow);
3263 if (!update_call_from_tree (gsi, result))
3264 gimplify_and_update_call_from_tree (gsi, result);
3265 changed = true;
3269 return changed;
3273 /* Return true whether NAME has a use on STMT. */
3275 static bool
3276 has_use_on_stmt (tree name, gimple *stmt)
3278 imm_use_iterator iter;
3279 use_operand_p use_p;
3280 FOR_EACH_IMM_USE_FAST (use_p, iter, name)
3281 if (USE_STMT (use_p) == stmt)
3282 return true;
3283 return false;
3286 /* Worker for fold_stmt_1 dispatch to pattern based folding with
3287 gimple_simplify.
3289 Replaces *GSI with the simplification result in RCODE and OPS
3290 and the associated statements in *SEQ. Does the replacement
3291 according to INPLACE and returns true if the operation succeeded. */
3293 static bool
3294 replace_stmt_with_simplification (gimple_stmt_iterator *gsi,
3295 code_helper rcode, tree *ops,
3296 gimple_seq *seq, bool inplace)
3298 gimple *stmt = gsi_stmt (*gsi);
3300 /* Play safe and do not allow abnormals to be mentioned in
3301 newly created statements. See also maybe_push_res_to_seq.
3302 As an exception allow such uses if there was a use of the
3303 same SSA name on the old stmt. */
3304 if ((TREE_CODE (ops[0]) == SSA_NAME
3305 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ops[0])
3306 && !has_use_on_stmt (ops[0], stmt))
3307 || (ops[1]
3308 && TREE_CODE (ops[1]) == SSA_NAME
3309 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ops[1])
3310 && !has_use_on_stmt (ops[1], stmt))
3311 || (ops[2]
3312 && TREE_CODE (ops[2]) == SSA_NAME
3313 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ops[2])
3314 && !has_use_on_stmt (ops[2], stmt))
3315 || (COMPARISON_CLASS_P (ops[0])
3316 && ((TREE_CODE (TREE_OPERAND (ops[0], 0)) == SSA_NAME
3317 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (TREE_OPERAND (ops[0], 0))
3318 && !has_use_on_stmt (TREE_OPERAND (ops[0], 0), stmt))
3319 || (TREE_CODE (TREE_OPERAND (ops[0], 1)) == SSA_NAME
3320 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (TREE_OPERAND (ops[0], 1))
3321 && !has_use_on_stmt (TREE_OPERAND (ops[0], 1), stmt)))))
3322 return false;
3324 /* Don't insert new statements when INPLACE is true, even if we could
3325 reuse STMT for the final statement. */
3326 if (inplace && !gimple_seq_empty_p (*seq))
3327 return false;
3329 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
3331 gcc_assert (rcode.is_tree_code ());
3332 if (TREE_CODE_CLASS ((enum tree_code)rcode) == tcc_comparison
3333 /* GIMPLE_CONDs condition may not throw. */
3334 && (!flag_exceptions
3335 || !cfun->can_throw_non_call_exceptions
3336 || !operation_could_trap_p (rcode,
3337 FLOAT_TYPE_P (TREE_TYPE (ops[0])),
3338 false, NULL_TREE)))
3339 gimple_cond_set_condition (cond_stmt, rcode, ops[0], ops[1]);
3340 else if (rcode == SSA_NAME)
3341 gimple_cond_set_condition (cond_stmt, NE_EXPR, ops[0],
3342 build_zero_cst (TREE_TYPE (ops[0])));
3343 else if (rcode == INTEGER_CST)
3345 if (integer_zerop (ops[0]))
3346 gimple_cond_make_false (cond_stmt);
3347 else
3348 gimple_cond_make_true (cond_stmt);
3350 else if (!inplace)
3352 tree res = maybe_push_res_to_seq (rcode, boolean_type_node,
3353 ops, seq);
3354 if (!res)
3355 return false;
3356 gimple_cond_set_condition (cond_stmt, NE_EXPR, res,
3357 build_zero_cst (TREE_TYPE (res)));
3359 else
3360 return false;
3361 if (dump_file && (dump_flags & TDF_DETAILS))
3363 fprintf (dump_file, "gimple_simplified to ");
3364 if (!gimple_seq_empty_p (*seq))
3365 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
3366 print_gimple_stmt (dump_file, gsi_stmt (*gsi),
3367 0, TDF_SLIM);
3369 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
3370 return true;
3372 else if (is_gimple_assign (stmt)
3373 && rcode.is_tree_code ())
3375 if (!inplace
3376 || gimple_num_ops (stmt) > get_gimple_rhs_num_ops (rcode))
3378 maybe_build_generic_op (rcode,
3379 TREE_TYPE (gimple_assign_lhs (stmt)), ops);
3380 gimple_assign_set_rhs_with_ops (gsi, rcode, ops[0], ops[1], ops[2]);
3381 if (dump_file && (dump_flags & TDF_DETAILS))
3383 fprintf (dump_file, "gimple_simplified to ");
3384 if (!gimple_seq_empty_p (*seq))
3385 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
3386 print_gimple_stmt (dump_file, gsi_stmt (*gsi),
3387 0, TDF_SLIM);
3389 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
3390 return true;
3393 else if (rcode.is_fn_code ()
3394 && gimple_call_combined_fn (stmt) == rcode)
3396 unsigned i;
3397 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3399 gcc_assert (ops[i] != NULL_TREE);
3400 gimple_call_set_arg (stmt, i, ops[i]);
3402 if (i < 3)
3403 gcc_assert (ops[i] == NULL_TREE);
3404 if (dump_file && (dump_flags & TDF_DETAILS))
3406 fprintf (dump_file, "gimple_simplified to ");
3407 if (!gimple_seq_empty_p (*seq))
3408 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
3409 print_gimple_stmt (dump_file, gsi_stmt (*gsi), 0, TDF_SLIM);
3411 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
3412 return true;
3414 else if (!inplace)
3416 if (gimple_has_lhs (stmt))
3418 tree lhs = gimple_get_lhs (stmt);
3419 if (!maybe_push_res_to_seq (rcode, TREE_TYPE (lhs),
3420 ops, seq, lhs))
3421 return false;
3422 if (dump_file && (dump_flags & TDF_DETAILS))
3424 fprintf (dump_file, "gimple_simplified to ");
3425 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
3427 gsi_replace_with_seq_vops (gsi, *seq);
3428 return true;
3430 else
3431 gcc_unreachable ();
3434 return false;
3437 /* Canonicalize MEM_REFs invariant address operand after propagation. */
3439 static bool
3440 maybe_canonicalize_mem_ref_addr (tree *t)
3442 bool res = false;
3444 if (TREE_CODE (*t) == ADDR_EXPR)
3445 t = &TREE_OPERAND (*t, 0);
3447 while (handled_component_p (*t))
3448 t = &TREE_OPERAND (*t, 0);
3450 /* Canonicalize MEM [&foo.bar, 0] which appears after propagating
3451 of invariant addresses into a SSA name MEM_REF address. */
3452 if (TREE_CODE (*t) == MEM_REF
3453 || TREE_CODE (*t) == TARGET_MEM_REF)
3455 tree addr = TREE_OPERAND (*t, 0);
3456 if (TREE_CODE (addr) == ADDR_EXPR
3457 && (TREE_CODE (TREE_OPERAND (addr, 0)) == MEM_REF
3458 || handled_component_p (TREE_OPERAND (addr, 0))))
3460 tree base;
3461 HOST_WIDE_INT coffset;
3462 base = get_addr_base_and_unit_offset (TREE_OPERAND (addr, 0),
3463 &coffset);
3464 if (!base)
3465 gcc_unreachable ();
3467 TREE_OPERAND (*t, 0) = build_fold_addr_expr (base);
3468 TREE_OPERAND (*t, 1) = int_const_binop (PLUS_EXPR,
3469 TREE_OPERAND (*t, 1),
3470 size_int (coffset));
3471 res = true;
3473 gcc_checking_assert (TREE_CODE (TREE_OPERAND (*t, 0)) == DEBUG_EXPR_DECL
3474 || is_gimple_mem_ref_addr (TREE_OPERAND (*t, 0)));
3477 /* Canonicalize back MEM_REFs to plain reference trees if the object
3478 accessed is a decl that has the same access semantics as the MEM_REF. */
3479 if (TREE_CODE (*t) == MEM_REF
3480 && TREE_CODE (TREE_OPERAND (*t, 0)) == ADDR_EXPR
3481 && integer_zerop (TREE_OPERAND (*t, 1))
3482 && MR_DEPENDENCE_CLIQUE (*t) == 0)
3484 tree decl = TREE_OPERAND (TREE_OPERAND (*t, 0), 0);
3485 tree alias_type = TREE_TYPE (TREE_OPERAND (*t, 1));
3486 if (/* Same volatile qualification. */
3487 TREE_THIS_VOLATILE (*t) == TREE_THIS_VOLATILE (decl)
3488 /* Same TBAA behavior with -fstrict-aliasing. */
3489 && !TYPE_REF_CAN_ALIAS_ALL (alias_type)
3490 && (TYPE_MAIN_VARIANT (TREE_TYPE (decl))
3491 == TYPE_MAIN_VARIANT (TREE_TYPE (alias_type)))
3492 /* Same alignment. */
3493 && TYPE_ALIGN (TREE_TYPE (decl)) == TYPE_ALIGN (TREE_TYPE (*t))
3494 /* We have to look out here to not drop a required conversion
3495 from the rhs to the lhs if *t appears on the lhs or vice-versa
3496 if it appears on the rhs. Thus require strict type
3497 compatibility. */
3498 && types_compatible_p (TREE_TYPE (*t), TREE_TYPE (decl)))
3500 *t = TREE_OPERAND (TREE_OPERAND (*t, 0), 0);
3501 res = true;
3505 /* Canonicalize TARGET_MEM_REF in particular with respect to
3506 the indexes becoming constant. */
3507 else if (TREE_CODE (*t) == TARGET_MEM_REF)
3509 tree tem = maybe_fold_tmr (*t);
3510 if (tem)
3512 *t = tem;
3513 res = true;
3517 return res;
3520 /* Worker for both fold_stmt and fold_stmt_inplace. The INPLACE argument
3521 distinguishes both cases. */
3523 static bool
3524 fold_stmt_1 (gimple_stmt_iterator *gsi, bool inplace, tree (*valueize) (tree))
3526 bool changed = false;
3527 gimple *stmt = gsi_stmt (*gsi);
3528 bool nowarning = gimple_no_warning_p (stmt);
3529 unsigned i;
3530 fold_defer_overflow_warnings ();
3532 /* First do required canonicalization of [TARGET_]MEM_REF addresses
3533 after propagation.
3534 ??? This shouldn't be done in generic folding but in the
3535 propagation helpers which also know whether an address was
3536 propagated.
3537 Also canonicalize operand order. */
3538 switch (gimple_code (stmt))
3540 case GIMPLE_ASSIGN:
3541 if (gimple_assign_rhs_class (stmt) == GIMPLE_SINGLE_RHS)
3543 tree *rhs = gimple_assign_rhs1_ptr (stmt);
3544 if ((REFERENCE_CLASS_P (*rhs)
3545 || TREE_CODE (*rhs) == ADDR_EXPR)
3546 && maybe_canonicalize_mem_ref_addr (rhs))
3547 changed = true;
3548 tree *lhs = gimple_assign_lhs_ptr (stmt);
3549 if (REFERENCE_CLASS_P (*lhs)
3550 && maybe_canonicalize_mem_ref_addr (lhs))
3551 changed = true;
3553 else
3555 /* Canonicalize operand order. */
3556 enum tree_code code = gimple_assign_rhs_code (stmt);
3557 if (TREE_CODE_CLASS (code) == tcc_comparison
3558 || commutative_tree_code (code)
3559 || commutative_ternary_tree_code (code))
3561 tree rhs1 = gimple_assign_rhs1 (stmt);
3562 tree rhs2 = gimple_assign_rhs2 (stmt);
3563 if (tree_swap_operands_p (rhs1, rhs2, false))
3565 gimple_assign_set_rhs1 (stmt, rhs2);
3566 gimple_assign_set_rhs2 (stmt, rhs1);
3567 if (TREE_CODE_CLASS (code) == tcc_comparison)
3568 gimple_assign_set_rhs_code (stmt,
3569 swap_tree_comparison (code));
3570 changed = true;
3574 break;
3575 case GIMPLE_CALL:
3577 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3579 tree *arg = gimple_call_arg_ptr (stmt, i);
3580 if (REFERENCE_CLASS_P (*arg)
3581 && maybe_canonicalize_mem_ref_addr (arg))
3582 changed = true;
3584 tree *lhs = gimple_call_lhs_ptr (stmt);
3585 if (*lhs
3586 && REFERENCE_CLASS_P (*lhs)
3587 && maybe_canonicalize_mem_ref_addr (lhs))
3588 changed = true;
3589 break;
3591 case GIMPLE_ASM:
3593 gasm *asm_stmt = as_a <gasm *> (stmt);
3594 for (i = 0; i < gimple_asm_noutputs (asm_stmt); ++i)
3596 tree link = gimple_asm_output_op (asm_stmt, i);
3597 tree op = TREE_VALUE (link);
3598 if (REFERENCE_CLASS_P (op)
3599 && maybe_canonicalize_mem_ref_addr (&TREE_VALUE (link)))
3600 changed = true;
3602 for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
3604 tree link = gimple_asm_input_op (asm_stmt, i);
3605 tree op = TREE_VALUE (link);
3606 if ((REFERENCE_CLASS_P (op)
3607 || TREE_CODE (op) == ADDR_EXPR)
3608 && maybe_canonicalize_mem_ref_addr (&TREE_VALUE (link)))
3609 changed = true;
3612 break;
3613 case GIMPLE_DEBUG:
3614 if (gimple_debug_bind_p (stmt))
3616 tree *val = gimple_debug_bind_get_value_ptr (stmt);
3617 if (*val
3618 && (REFERENCE_CLASS_P (*val)
3619 || TREE_CODE (*val) == ADDR_EXPR)
3620 && maybe_canonicalize_mem_ref_addr (val))
3621 changed = true;
3623 break;
3624 case GIMPLE_COND:
3626 /* Canonicalize operand order. */
3627 tree lhs = gimple_cond_lhs (stmt);
3628 tree rhs = gimple_cond_rhs (stmt);
3629 if (tree_swap_operands_p (lhs, rhs, false))
3631 gcond *gc = as_a <gcond *> (stmt);
3632 gimple_cond_set_lhs (gc, rhs);
3633 gimple_cond_set_rhs (gc, lhs);
3634 gimple_cond_set_code (gc,
3635 swap_tree_comparison (gimple_cond_code (gc)));
3636 changed = true;
3639 default:;
3642 /* Dispatch to pattern-based folding. */
3643 if (!inplace
3644 || is_gimple_assign (stmt)
3645 || gimple_code (stmt) == GIMPLE_COND)
3647 gimple_seq seq = NULL;
3648 code_helper rcode;
3649 tree ops[3] = {};
3650 if (gimple_simplify (stmt, &rcode, ops, inplace ? NULL : &seq,
3651 valueize, valueize))
3653 if (replace_stmt_with_simplification (gsi, rcode, ops, &seq, inplace))
3654 changed = true;
3655 else
3656 gimple_seq_discard (seq);
3660 stmt = gsi_stmt (*gsi);
3662 /* Fold the main computation performed by the statement. */
3663 switch (gimple_code (stmt))
3665 case GIMPLE_ASSIGN:
3667 /* Try to canonicalize for boolean-typed X the comparisons
3668 X == 0, X == 1, X != 0, and X != 1. */
3669 if (gimple_assign_rhs_code (stmt) == EQ_EXPR
3670 || gimple_assign_rhs_code (stmt) == NE_EXPR)
3672 tree lhs = gimple_assign_lhs (stmt);
3673 tree op1 = gimple_assign_rhs1 (stmt);
3674 tree op2 = gimple_assign_rhs2 (stmt);
3675 tree type = TREE_TYPE (op1);
3677 /* Check whether the comparison operands are of the same boolean
3678 type as the result type is.
3679 Check that second operand is an integer-constant with value
3680 one or zero. */
3681 if (TREE_CODE (op2) == INTEGER_CST
3682 && (integer_zerop (op2) || integer_onep (op2))
3683 && useless_type_conversion_p (TREE_TYPE (lhs), type))
3685 enum tree_code cmp_code = gimple_assign_rhs_code (stmt);
3686 bool is_logical_not = false;
3688 /* X == 0 and X != 1 is a logical-not.of X
3689 X == 1 and X != 0 is X */
3690 if ((cmp_code == EQ_EXPR && integer_zerop (op2))
3691 || (cmp_code == NE_EXPR && integer_onep (op2)))
3692 is_logical_not = true;
3694 if (is_logical_not == false)
3695 gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op1), op1);
3696 /* Only for one-bit precision typed X the transformation
3697 !X -> ~X is valied. */
3698 else if (TYPE_PRECISION (type) == 1)
3699 gimple_assign_set_rhs_with_ops (gsi, BIT_NOT_EXPR, op1);
3700 /* Otherwise we use !X -> X ^ 1. */
3701 else
3702 gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op1,
3703 build_int_cst (type, 1));
3704 changed = true;
3705 break;
3709 unsigned old_num_ops = gimple_num_ops (stmt);
3710 tree lhs = gimple_assign_lhs (stmt);
3711 tree new_rhs = fold_gimple_assign (gsi);
3712 if (new_rhs
3713 && !useless_type_conversion_p (TREE_TYPE (lhs),
3714 TREE_TYPE (new_rhs)))
3715 new_rhs = fold_convert (TREE_TYPE (lhs), new_rhs);
3716 if (new_rhs
3717 && (!inplace
3718 || get_gimple_rhs_num_ops (TREE_CODE (new_rhs)) < old_num_ops))
3720 gimple_assign_set_rhs_from_tree (gsi, new_rhs);
3721 changed = true;
3723 break;
3726 case GIMPLE_CALL:
3727 changed |= gimple_fold_call (gsi, inplace);
3728 break;
3730 case GIMPLE_ASM:
3731 /* Fold *& in asm operands. */
3733 gasm *asm_stmt = as_a <gasm *> (stmt);
3734 size_t noutputs;
3735 const char **oconstraints;
3736 const char *constraint;
3737 bool allows_mem, allows_reg;
3739 noutputs = gimple_asm_noutputs (asm_stmt);
3740 oconstraints = XALLOCAVEC (const char *, noutputs);
3742 for (i = 0; i < gimple_asm_noutputs (asm_stmt); ++i)
3744 tree link = gimple_asm_output_op (asm_stmt, i);
3745 tree op = TREE_VALUE (link);
3746 oconstraints[i]
3747 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
3748 if (REFERENCE_CLASS_P (op)
3749 && (op = maybe_fold_reference (op, true)) != NULL_TREE)
3751 TREE_VALUE (link) = op;
3752 changed = true;
3755 for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
3757 tree link = gimple_asm_input_op (asm_stmt, i);
3758 tree op = TREE_VALUE (link);
3759 constraint
3760 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
3761 parse_input_constraint (&constraint, 0, 0, noutputs, 0,
3762 oconstraints, &allows_mem, &allows_reg);
3763 if (REFERENCE_CLASS_P (op)
3764 && (op = maybe_fold_reference (op, !allows_reg && allows_mem))
3765 != NULL_TREE)
3767 TREE_VALUE (link) = op;
3768 changed = true;
3772 break;
3774 case GIMPLE_DEBUG:
3775 if (gimple_debug_bind_p (stmt))
3777 tree val = gimple_debug_bind_get_value (stmt);
3778 if (val
3779 && REFERENCE_CLASS_P (val))
3781 tree tem = maybe_fold_reference (val, false);
3782 if (tem)
3784 gimple_debug_bind_set_value (stmt, tem);
3785 changed = true;
3788 else if (val
3789 && TREE_CODE (val) == ADDR_EXPR)
3791 tree ref = TREE_OPERAND (val, 0);
3792 tree tem = maybe_fold_reference (ref, false);
3793 if (tem)
3795 tem = build_fold_addr_expr_with_type (tem, TREE_TYPE (val));
3796 gimple_debug_bind_set_value (stmt, tem);
3797 changed = true;
3801 break;
3803 default:;
3806 stmt = gsi_stmt (*gsi);
3808 /* Fold *& on the lhs. */
3809 if (gimple_has_lhs (stmt))
3811 tree lhs = gimple_get_lhs (stmt);
3812 if (lhs && REFERENCE_CLASS_P (lhs))
3814 tree new_lhs = maybe_fold_reference (lhs, true);
3815 if (new_lhs)
3817 gimple_set_lhs (stmt, new_lhs);
3818 changed = true;
3823 fold_undefer_overflow_warnings (changed && !nowarning, stmt, 0);
3824 return changed;
3827 /* Valueziation callback that ends up not following SSA edges. */
3829 tree
3830 no_follow_ssa_edges (tree)
3832 return NULL_TREE;
3835 /* Valueization callback that ends up following single-use SSA edges only. */
3837 tree
3838 follow_single_use_edges (tree val)
3840 if (TREE_CODE (val) == SSA_NAME
3841 && !has_single_use (val))
3842 return NULL_TREE;
3843 return val;
3846 /* Fold the statement pointed to by GSI. In some cases, this function may
3847 replace the whole statement with a new one. Returns true iff folding
3848 makes any changes.
3849 The statement pointed to by GSI should be in valid gimple form but may
3850 be in unfolded state as resulting from for example constant propagation
3851 which can produce *&x = 0. */
3853 bool
3854 fold_stmt (gimple_stmt_iterator *gsi)
3856 return fold_stmt_1 (gsi, false, no_follow_ssa_edges);
3859 bool
3860 fold_stmt (gimple_stmt_iterator *gsi, tree (*valueize) (tree))
3862 return fold_stmt_1 (gsi, false, valueize);
3865 /* Perform the minimal folding on statement *GSI. Only operations like
3866 *&x created by constant propagation are handled. The statement cannot
3867 be replaced with a new one. Return true if the statement was
3868 changed, false otherwise.
3869 The statement *GSI should be in valid gimple form but may
3870 be in unfolded state as resulting from for example constant propagation
3871 which can produce *&x = 0. */
3873 bool
3874 fold_stmt_inplace (gimple_stmt_iterator *gsi)
3876 gimple *stmt = gsi_stmt (*gsi);
3877 bool changed = fold_stmt_1 (gsi, true, no_follow_ssa_edges);
3878 gcc_assert (gsi_stmt (*gsi) == stmt);
3879 return changed;
3882 /* Canonicalize and possibly invert the boolean EXPR; return NULL_TREE
3883 if EXPR is null or we don't know how.
3884 If non-null, the result always has boolean type. */
3886 static tree
3887 canonicalize_bool (tree expr, bool invert)
3889 if (!expr)
3890 return NULL_TREE;
3891 else if (invert)
3893 if (integer_nonzerop (expr))
3894 return boolean_false_node;
3895 else if (integer_zerop (expr))
3896 return boolean_true_node;
3897 else if (TREE_CODE (expr) == SSA_NAME)
3898 return fold_build2 (EQ_EXPR, boolean_type_node, expr,
3899 build_int_cst (TREE_TYPE (expr), 0));
3900 else if (COMPARISON_CLASS_P (expr))
3901 return fold_build2 (invert_tree_comparison (TREE_CODE (expr), false),
3902 boolean_type_node,
3903 TREE_OPERAND (expr, 0),
3904 TREE_OPERAND (expr, 1));
3905 else
3906 return NULL_TREE;
3908 else
3910 if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE)
3911 return expr;
3912 if (integer_nonzerop (expr))
3913 return boolean_true_node;
3914 else if (integer_zerop (expr))
3915 return boolean_false_node;
3916 else if (TREE_CODE (expr) == SSA_NAME)
3917 return fold_build2 (NE_EXPR, boolean_type_node, expr,
3918 build_int_cst (TREE_TYPE (expr), 0));
3919 else if (COMPARISON_CLASS_P (expr))
3920 return fold_build2 (TREE_CODE (expr),
3921 boolean_type_node,
3922 TREE_OPERAND (expr, 0),
3923 TREE_OPERAND (expr, 1));
3924 else
3925 return NULL_TREE;
3929 /* Check to see if a boolean expression EXPR is logically equivalent to the
3930 comparison (OP1 CODE OP2). Check for various identities involving
3931 SSA_NAMEs. */
3933 static bool
3934 same_bool_comparison_p (const_tree expr, enum tree_code code,
3935 const_tree op1, const_tree op2)
3937 gimple *s;
3939 /* The obvious case. */
3940 if (TREE_CODE (expr) == code
3941 && operand_equal_p (TREE_OPERAND (expr, 0), op1, 0)
3942 && operand_equal_p (TREE_OPERAND (expr, 1), op2, 0))
3943 return true;
3945 /* Check for comparing (name, name != 0) and the case where expr
3946 is an SSA_NAME with a definition matching the comparison. */
3947 if (TREE_CODE (expr) == SSA_NAME
3948 && TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE)
3950 if (operand_equal_p (expr, op1, 0))
3951 return ((code == NE_EXPR && integer_zerop (op2))
3952 || (code == EQ_EXPR && integer_nonzerop (op2)));
3953 s = SSA_NAME_DEF_STMT (expr);
3954 if (is_gimple_assign (s)
3955 && gimple_assign_rhs_code (s) == code
3956 && operand_equal_p (gimple_assign_rhs1 (s), op1, 0)
3957 && operand_equal_p (gimple_assign_rhs2 (s), op2, 0))
3958 return true;
3961 /* If op1 is of the form (name != 0) or (name == 0), and the definition
3962 of name is a comparison, recurse. */
3963 if (TREE_CODE (op1) == SSA_NAME
3964 && TREE_CODE (TREE_TYPE (op1)) == BOOLEAN_TYPE)
3966 s = SSA_NAME_DEF_STMT (op1);
3967 if (is_gimple_assign (s)
3968 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison)
3970 enum tree_code c = gimple_assign_rhs_code (s);
3971 if ((c == NE_EXPR && integer_zerop (op2))
3972 || (c == EQ_EXPR && integer_nonzerop (op2)))
3973 return same_bool_comparison_p (expr, c,
3974 gimple_assign_rhs1 (s),
3975 gimple_assign_rhs2 (s));
3976 if ((c == EQ_EXPR && integer_zerop (op2))
3977 || (c == NE_EXPR && integer_nonzerop (op2)))
3978 return same_bool_comparison_p (expr,
3979 invert_tree_comparison (c, false),
3980 gimple_assign_rhs1 (s),
3981 gimple_assign_rhs2 (s));
3984 return false;
3987 /* Check to see if two boolean expressions OP1 and OP2 are logically
3988 equivalent. */
3990 static bool
3991 same_bool_result_p (const_tree op1, const_tree op2)
3993 /* Simple cases first. */
3994 if (operand_equal_p (op1, op2, 0))
3995 return true;
3997 /* Check the cases where at least one of the operands is a comparison.
3998 These are a bit smarter than operand_equal_p in that they apply some
3999 identifies on SSA_NAMEs. */
4000 if (COMPARISON_CLASS_P (op2)
4001 && same_bool_comparison_p (op1, TREE_CODE (op2),
4002 TREE_OPERAND (op2, 0),
4003 TREE_OPERAND (op2, 1)))
4004 return true;
4005 if (COMPARISON_CLASS_P (op1)
4006 && same_bool_comparison_p (op2, TREE_CODE (op1),
4007 TREE_OPERAND (op1, 0),
4008 TREE_OPERAND (op1, 1)))
4009 return true;
4011 /* Default case. */
4012 return false;
4015 /* Forward declarations for some mutually recursive functions. */
4017 static tree
4018 and_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
4019 enum tree_code code2, tree op2a, tree op2b);
4020 static tree
4021 and_var_with_comparison (tree var, bool invert,
4022 enum tree_code code2, tree op2a, tree op2b);
4023 static tree
4024 and_var_with_comparison_1 (gimple *stmt,
4025 enum tree_code code2, tree op2a, tree op2b);
4026 static tree
4027 or_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
4028 enum tree_code code2, tree op2a, tree op2b);
4029 static tree
4030 or_var_with_comparison (tree var, bool invert,
4031 enum tree_code code2, tree op2a, tree op2b);
4032 static tree
4033 or_var_with_comparison_1 (gimple *stmt,
4034 enum tree_code code2, tree op2a, tree op2b);
4036 /* Helper function for and_comparisons_1: try to simplify the AND of the
4037 ssa variable VAR with the comparison specified by (OP2A CODE2 OP2B).
4038 If INVERT is true, invert the value of the VAR before doing the AND.
4039 Return NULL_EXPR if we can't simplify this to a single expression. */
4041 static tree
4042 and_var_with_comparison (tree var, bool invert,
4043 enum tree_code code2, tree op2a, tree op2b)
4045 tree t;
4046 gimple *stmt = SSA_NAME_DEF_STMT (var);
4048 /* We can only deal with variables whose definitions are assignments. */
4049 if (!is_gimple_assign (stmt))
4050 return NULL_TREE;
4052 /* If we have an inverted comparison, apply DeMorgan's law and rewrite
4053 !var AND (op2a code2 op2b) => !(var OR !(op2a code2 op2b))
4054 Then we only have to consider the simpler non-inverted cases. */
4055 if (invert)
4056 t = or_var_with_comparison_1 (stmt,
4057 invert_tree_comparison (code2, false),
4058 op2a, op2b);
4059 else
4060 t = and_var_with_comparison_1 (stmt, code2, op2a, op2b);
4061 return canonicalize_bool (t, invert);
4064 /* Try to simplify the AND of the ssa variable defined by the assignment
4065 STMT with the comparison specified by (OP2A CODE2 OP2B).
4066 Return NULL_EXPR if we can't simplify this to a single expression. */
4068 static tree
4069 and_var_with_comparison_1 (gimple *stmt,
4070 enum tree_code code2, tree op2a, tree op2b)
4072 tree var = gimple_assign_lhs (stmt);
4073 tree true_test_var = NULL_TREE;
4074 tree false_test_var = NULL_TREE;
4075 enum tree_code innercode = gimple_assign_rhs_code (stmt);
4077 /* Check for identities like (var AND (var == 0)) => false. */
4078 if (TREE_CODE (op2a) == SSA_NAME
4079 && TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE)
4081 if ((code2 == NE_EXPR && integer_zerop (op2b))
4082 || (code2 == EQ_EXPR && integer_nonzerop (op2b)))
4084 true_test_var = op2a;
4085 if (var == true_test_var)
4086 return var;
4088 else if ((code2 == EQ_EXPR && integer_zerop (op2b))
4089 || (code2 == NE_EXPR && integer_nonzerop (op2b)))
4091 false_test_var = op2a;
4092 if (var == false_test_var)
4093 return boolean_false_node;
4097 /* If the definition is a comparison, recurse on it. */
4098 if (TREE_CODE_CLASS (innercode) == tcc_comparison)
4100 tree t = and_comparisons_1 (innercode,
4101 gimple_assign_rhs1 (stmt),
4102 gimple_assign_rhs2 (stmt),
4103 code2,
4104 op2a,
4105 op2b);
4106 if (t)
4107 return t;
4110 /* If the definition is an AND or OR expression, we may be able to
4111 simplify by reassociating. */
4112 if (TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE
4113 && (innercode == BIT_AND_EXPR || innercode == BIT_IOR_EXPR))
4115 tree inner1 = gimple_assign_rhs1 (stmt);
4116 tree inner2 = gimple_assign_rhs2 (stmt);
4117 gimple *s;
4118 tree t;
4119 tree partial = NULL_TREE;
4120 bool is_and = (innercode == BIT_AND_EXPR);
4122 /* Check for boolean identities that don't require recursive examination
4123 of inner1/inner2:
4124 inner1 AND (inner1 AND inner2) => inner1 AND inner2 => var
4125 inner1 AND (inner1 OR inner2) => inner1
4126 !inner1 AND (inner1 AND inner2) => false
4127 !inner1 AND (inner1 OR inner2) => !inner1 AND inner2
4128 Likewise for similar cases involving inner2. */
4129 if (inner1 == true_test_var)
4130 return (is_and ? var : inner1);
4131 else if (inner2 == true_test_var)
4132 return (is_and ? var : inner2);
4133 else if (inner1 == false_test_var)
4134 return (is_and
4135 ? boolean_false_node
4136 : and_var_with_comparison (inner2, false, code2, op2a, op2b));
4137 else if (inner2 == false_test_var)
4138 return (is_and
4139 ? boolean_false_node
4140 : and_var_with_comparison (inner1, false, code2, op2a, op2b));
4142 /* Next, redistribute/reassociate the AND across the inner tests.
4143 Compute the first partial result, (inner1 AND (op2a code op2b)) */
4144 if (TREE_CODE (inner1) == SSA_NAME
4145 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner1))
4146 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
4147 && (t = maybe_fold_and_comparisons (gimple_assign_rhs_code (s),
4148 gimple_assign_rhs1 (s),
4149 gimple_assign_rhs2 (s),
4150 code2, op2a, op2b)))
4152 /* Handle the AND case, where we are reassociating:
4153 (inner1 AND inner2) AND (op2a code2 op2b)
4154 => (t AND inner2)
4155 If the partial result t is a constant, we win. Otherwise
4156 continue on to try reassociating with the other inner test. */
4157 if (is_and)
4159 if (integer_onep (t))
4160 return inner2;
4161 else if (integer_zerop (t))
4162 return boolean_false_node;
4165 /* Handle the OR case, where we are redistributing:
4166 (inner1 OR inner2) AND (op2a code2 op2b)
4167 => (t OR (inner2 AND (op2a code2 op2b))) */
4168 else if (integer_onep (t))
4169 return boolean_true_node;
4171 /* Save partial result for later. */
4172 partial = t;
4175 /* Compute the second partial result, (inner2 AND (op2a code op2b)) */
4176 if (TREE_CODE (inner2) == SSA_NAME
4177 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner2))
4178 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
4179 && (t = maybe_fold_and_comparisons (gimple_assign_rhs_code (s),
4180 gimple_assign_rhs1 (s),
4181 gimple_assign_rhs2 (s),
4182 code2, op2a, op2b)))
4184 /* Handle the AND case, where we are reassociating:
4185 (inner1 AND inner2) AND (op2a code2 op2b)
4186 => (inner1 AND t) */
4187 if (is_and)
4189 if (integer_onep (t))
4190 return inner1;
4191 else if (integer_zerop (t))
4192 return boolean_false_node;
4193 /* If both are the same, we can apply the identity
4194 (x AND x) == x. */
4195 else if (partial && same_bool_result_p (t, partial))
4196 return t;
4199 /* Handle the OR case. where we are redistributing:
4200 (inner1 OR inner2) AND (op2a code2 op2b)
4201 => (t OR (inner1 AND (op2a code2 op2b)))
4202 => (t OR partial) */
4203 else
4205 if (integer_onep (t))
4206 return boolean_true_node;
4207 else if (partial)
4209 /* We already got a simplification for the other
4210 operand to the redistributed OR expression. The
4211 interesting case is when at least one is false.
4212 Or, if both are the same, we can apply the identity
4213 (x OR x) == x. */
4214 if (integer_zerop (partial))
4215 return t;
4216 else if (integer_zerop (t))
4217 return partial;
4218 else if (same_bool_result_p (t, partial))
4219 return t;
4224 return NULL_TREE;
4227 /* Try to simplify the AND of two comparisons defined by
4228 (OP1A CODE1 OP1B) and (OP2A CODE2 OP2B), respectively.
4229 If this can be done without constructing an intermediate value,
4230 return the resulting tree; otherwise NULL_TREE is returned.
4231 This function is deliberately asymmetric as it recurses on SSA_DEFs
4232 in the first comparison but not the second. */
4234 static tree
4235 and_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
4236 enum tree_code code2, tree op2a, tree op2b)
4238 tree truth_type = truth_type_for (TREE_TYPE (op1a));
4240 /* First check for ((x CODE1 y) AND (x CODE2 y)). */
4241 if (operand_equal_p (op1a, op2a, 0)
4242 && operand_equal_p (op1b, op2b, 0))
4244 /* Result will be either NULL_TREE, or a combined comparison. */
4245 tree t = combine_comparisons (UNKNOWN_LOCATION,
4246 TRUTH_ANDIF_EXPR, code1, code2,
4247 truth_type, op1a, op1b);
4248 if (t)
4249 return t;
4252 /* Likewise the swapped case of the above. */
4253 if (operand_equal_p (op1a, op2b, 0)
4254 && operand_equal_p (op1b, op2a, 0))
4256 /* Result will be either NULL_TREE, or a combined comparison. */
4257 tree t = combine_comparisons (UNKNOWN_LOCATION,
4258 TRUTH_ANDIF_EXPR, code1,
4259 swap_tree_comparison (code2),
4260 truth_type, op1a, op1b);
4261 if (t)
4262 return t;
4265 /* If both comparisons are of the same value against constants, we might
4266 be able to merge them. */
4267 if (operand_equal_p (op1a, op2a, 0)
4268 && TREE_CODE (op1b) == INTEGER_CST
4269 && TREE_CODE (op2b) == INTEGER_CST)
4271 int cmp = tree_int_cst_compare (op1b, op2b);
4273 /* If we have (op1a == op1b), we should either be able to
4274 return that or FALSE, depending on whether the constant op1b
4275 also satisfies the other comparison against op2b. */
4276 if (code1 == EQ_EXPR)
4278 bool done = true;
4279 bool val;
4280 switch (code2)
4282 case EQ_EXPR: val = (cmp == 0); break;
4283 case NE_EXPR: val = (cmp != 0); break;
4284 case LT_EXPR: val = (cmp < 0); break;
4285 case GT_EXPR: val = (cmp > 0); break;
4286 case LE_EXPR: val = (cmp <= 0); break;
4287 case GE_EXPR: val = (cmp >= 0); break;
4288 default: done = false;
4290 if (done)
4292 if (val)
4293 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4294 else
4295 return boolean_false_node;
4298 /* Likewise if the second comparison is an == comparison. */
4299 else if (code2 == EQ_EXPR)
4301 bool done = true;
4302 bool val;
4303 switch (code1)
4305 case EQ_EXPR: val = (cmp == 0); break;
4306 case NE_EXPR: val = (cmp != 0); break;
4307 case LT_EXPR: val = (cmp > 0); break;
4308 case GT_EXPR: val = (cmp < 0); break;
4309 case LE_EXPR: val = (cmp >= 0); break;
4310 case GE_EXPR: val = (cmp <= 0); break;
4311 default: done = false;
4313 if (done)
4315 if (val)
4316 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4317 else
4318 return boolean_false_node;
4322 /* Same business with inequality tests. */
4323 else if (code1 == NE_EXPR)
4325 bool val;
4326 switch (code2)
4328 case EQ_EXPR: val = (cmp != 0); break;
4329 case NE_EXPR: val = (cmp == 0); break;
4330 case LT_EXPR: val = (cmp >= 0); break;
4331 case GT_EXPR: val = (cmp <= 0); break;
4332 case LE_EXPR: val = (cmp > 0); break;
4333 case GE_EXPR: val = (cmp < 0); break;
4334 default:
4335 val = false;
4337 if (val)
4338 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4340 else if (code2 == NE_EXPR)
4342 bool val;
4343 switch (code1)
4345 case EQ_EXPR: val = (cmp == 0); break;
4346 case NE_EXPR: val = (cmp != 0); break;
4347 case LT_EXPR: val = (cmp <= 0); break;
4348 case GT_EXPR: val = (cmp >= 0); break;
4349 case LE_EXPR: val = (cmp < 0); break;
4350 case GE_EXPR: val = (cmp > 0); break;
4351 default:
4352 val = false;
4354 if (val)
4355 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4358 /* Chose the more restrictive of two < or <= comparisons. */
4359 else if ((code1 == LT_EXPR || code1 == LE_EXPR)
4360 && (code2 == LT_EXPR || code2 == LE_EXPR))
4362 if ((cmp < 0) || (cmp == 0 && code1 == LT_EXPR))
4363 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4364 else
4365 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4368 /* Likewise chose the more restrictive of two > or >= comparisons. */
4369 else if ((code1 == GT_EXPR || code1 == GE_EXPR)
4370 && (code2 == GT_EXPR || code2 == GE_EXPR))
4372 if ((cmp > 0) || (cmp == 0 && code1 == GT_EXPR))
4373 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4374 else
4375 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4378 /* Check for singleton ranges. */
4379 else if (cmp == 0
4380 && ((code1 == LE_EXPR && code2 == GE_EXPR)
4381 || (code1 == GE_EXPR && code2 == LE_EXPR)))
4382 return fold_build2 (EQ_EXPR, boolean_type_node, op1a, op2b);
4384 /* Check for disjoint ranges. */
4385 else if (cmp <= 0
4386 && (code1 == LT_EXPR || code1 == LE_EXPR)
4387 && (code2 == GT_EXPR || code2 == GE_EXPR))
4388 return boolean_false_node;
4389 else if (cmp >= 0
4390 && (code1 == GT_EXPR || code1 == GE_EXPR)
4391 && (code2 == LT_EXPR || code2 == LE_EXPR))
4392 return boolean_false_node;
4395 /* Perhaps the first comparison is (NAME != 0) or (NAME == 1) where
4396 NAME's definition is a truth value. See if there are any simplifications
4397 that can be done against the NAME's definition. */
4398 if (TREE_CODE (op1a) == SSA_NAME
4399 && (code1 == NE_EXPR || code1 == EQ_EXPR)
4400 && (integer_zerop (op1b) || integer_onep (op1b)))
4402 bool invert = ((code1 == EQ_EXPR && integer_zerop (op1b))
4403 || (code1 == NE_EXPR && integer_onep (op1b)));
4404 gimple *stmt = SSA_NAME_DEF_STMT (op1a);
4405 switch (gimple_code (stmt))
4407 case GIMPLE_ASSIGN:
4408 /* Try to simplify by copy-propagating the definition. */
4409 return and_var_with_comparison (op1a, invert, code2, op2a, op2b);
4411 case GIMPLE_PHI:
4412 /* If every argument to the PHI produces the same result when
4413 ANDed with the second comparison, we win.
4414 Do not do this unless the type is bool since we need a bool
4415 result here anyway. */
4416 if (TREE_CODE (TREE_TYPE (op1a)) == BOOLEAN_TYPE)
4418 tree result = NULL_TREE;
4419 unsigned i;
4420 for (i = 0; i < gimple_phi_num_args (stmt); i++)
4422 tree arg = gimple_phi_arg_def (stmt, i);
4424 /* If this PHI has itself as an argument, ignore it.
4425 If all the other args produce the same result,
4426 we're still OK. */
4427 if (arg == gimple_phi_result (stmt))
4428 continue;
4429 else if (TREE_CODE (arg) == INTEGER_CST)
4431 if (invert ? integer_nonzerop (arg) : integer_zerop (arg))
4433 if (!result)
4434 result = boolean_false_node;
4435 else if (!integer_zerop (result))
4436 return NULL_TREE;
4438 else if (!result)
4439 result = fold_build2 (code2, boolean_type_node,
4440 op2a, op2b);
4441 else if (!same_bool_comparison_p (result,
4442 code2, op2a, op2b))
4443 return NULL_TREE;
4445 else if (TREE_CODE (arg) == SSA_NAME
4446 && !SSA_NAME_IS_DEFAULT_DEF (arg))
4448 tree temp;
4449 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
4450 /* In simple cases we can look through PHI nodes,
4451 but we have to be careful with loops.
4452 See PR49073. */
4453 if (! dom_info_available_p (CDI_DOMINATORS)
4454 || gimple_bb (def_stmt) == gimple_bb (stmt)
4455 || dominated_by_p (CDI_DOMINATORS,
4456 gimple_bb (def_stmt),
4457 gimple_bb (stmt)))
4458 return NULL_TREE;
4459 temp = and_var_with_comparison (arg, invert, code2,
4460 op2a, op2b);
4461 if (!temp)
4462 return NULL_TREE;
4463 else if (!result)
4464 result = temp;
4465 else if (!same_bool_result_p (result, temp))
4466 return NULL_TREE;
4468 else
4469 return NULL_TREE;
4471 return result;
4474 default:
4475 break;
4478 return NULL_TREE;
4481 /* Try to simplify the AND of two comparisons, specified by
4482 (OP1A CODE1 OP1B) and (OP2B CODE2 OP2B), respectively.
4483 If this can be simplified to a single expression (without requiring
4484 introducing more SSA variables to hold intermediate values),
4485 return the resulting tree. Otherwise return NULL_TREE.
4486 If the result expression is non-null, it has boolean type. */
4488 tree
4489 maybe_fold_and_comparisons (enum tree_code code1, tree op1a, tree op1b,
4490 enum tree_code code2, tree op2a, tree op2b)
4492 tree t = and_comparisons_1 (code1, op1a, op1b, code2, op2a, op2b);
4493 if (t)
4494 return t;
4495 else
4496 return and_comparisons_1 (code2, op2a, op2b, code1, op1a, op1b);
4499 /* Helper function for or_comparisons_1: try to simplify the OR of the
4500 ssa variable VAR with the comparison specified by (OP2A CODE2 OP2B).
4501 If INVERT is true, invert the value of VAR before doing the OR.
4502 Return NULL_EXPR if we can't simplify this to a single expression. */
4504 static tree
4505 or_var_with_comparison (tree var, bool invert,
4506 enum tree_code code2, tree op2a, tree op2b)
4508 tree t;
4509 gimple *stmt = SSA_NAME_DEF_STMT (var);
4511 /* We can only deal with variables whose definitions are assignments. */
4512 if (!is_gimple_assign (stmt))
4513 return NULL_TREE;
4515 /* If we have an inverted comparison, apply DeMorgan's law and rewrite
4516 !var OR (op2a code2 op2b) => !(var AND !(op2a code2 op2b))
4517 Then we only have to consider the simpler non-inverted cases. */
4518 if (invert)
4519 t = and_var_with_comparison_1 (stmt,
4520 invert_tree_comparison (code2, false),
4521 op2a, op2b);
4522 else
4523 t = or_var_with_comparison_1 (stmt, code2, op2a, op2b);
4524 return canonicalize_bool (t, invert);
4527 /* Try to simplify the OR of the ssa variable defined by the assignment
4528 STMT with the comparison specified by (OP2A CODE2 OP2B).
4529 Return NULL_EXPR if we can't simplify this to a single expression. */
4531 static tree
4532 or_var_with_comparison_1 (gimple *stmt,
4533 enum tree_code code2, tree op2a, tree op2b)
4535 tree var = gimple_assign_lhs (stmt);
4536 tree true_test_var = NULL_TREE;
4537 tree false_test_var = NULL_TREE;
4538 enum tree_code innercode = gimple_assign_rhs_code (stmt);
4540 /* Check for identities like (var OR (var != 0)) => true . */
4541 if (TREE_CODE (op2a) == SSA_NAME
4542 && TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE)
4544 if ((code2 == NE_EXPR && integer_zerop (op2b))
4545 || (code2 == EQ_EXPR && integer_nonzerop (op2b)))
4547 true_test_var = op2a;
4548 if (var == true_test_var)
4549 return var;
4551 else if ((code2 == EQ_EXPR && integer_zerop (op2b))
4552 || (code2 == NE_EXPR && integer_nonzerop (op2b)))
4554 false_test_var = op2a;
4555 if (var == false_test_var)
4556 return boolean_true_node;
4560 /* If the definition is a comparison, recurse on it. */
4561 if (TREE_CODE_CLASS (innercode) == tcc_comparison)
4563 tree t = or_comparisons_1 (innercode,
4564 gimple_assign_rhs1 (stmt),
4565 gimple_assign_rhs2 (stmt),
4566 code2,
4567 op2a,
4568 op2b);
4569 if (t)
4570 return t;
4573 /* If the definition is an AND or OR expression, we may be able to
4574 simplify by reassociating. */
4575 if (TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE
4576 && (innercode == BIT_AND_EXPR || innercode == BIT_IOR_EXPR))
4578 tree inner1 = gimple_assign_rhs1 (stmt);
4579 tree inner2 = gimple_assign_rhs2 (stmt);
4580 gimple *s;
4581 tree t;
4582 tree partial = NULL_TREE;
4583 bool is_or = (innercode == BIT_IOR_EXPR);
4585 /* Check for boolean identities that don't require recursive examination
4586 of inner1/inner2:
4587 inner1 OR (inner1 OR inner2) => inner1 OR inner2 => var
4588 inner1 OR (inner1 AND inner2) => inner1
4589 !inner1 OR (inner1 OR inner2) => true
4590 !inner1 OR (inner1 AND inner2) => !inner1 OR inner2
4592 if (inner1 == true_test_var)
4593 return (is_or ? var : inner1);
4594 else if (inner2 == true_test_var)
4595 return (is_or ? var : inner2);
4596 else if (inner1 == false_test_var)
4597 return (is_or
4598 ? boolean_true_node
4599 : or_var_with_comparison (inner2, false, code2, op2a, op2b));
4600 else if (inner2 == false_test_var)
4601 return (is_or
4602 ? boolean_true_node
4603 : or_var_with_comparison (inner1, false, code2, op2a, op2b));
4605 /* Next, redistribute/reassociate the OR across the inner tests.
4606 Compute the first partial result, (inner1 OR (op2a code op2b)) */
4607 if (TREE_CODE (inner1) == SSA_NAME
4608 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner1))
4609 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
4610 && (t = maybe_fold_or_comparisons (gimple_assign_rhs_code (s),
4611 gimple_assign_rhs1 (s),
4612 gimple_assign_rhs2 (s),
4613 code2, op2a, op2b)))
4615 /* Handle the OR case, where we are reassociating:
4616 (inner1 OR inner2) OR (op2a code2 op2b)
4617 => (t OR inner2)
4618 If the partial result t is a constant, we win. Otherwise
4619 continue on to try reassociating with the other inner test. */
4620 if (is_or)
4622 if (integer_onep (t))
4623 return boolean_true_node;
4624 else if (integer_zerop (t))
4625 return inner2;
4628 /* Handle the AND case, where we are redistributing:
4629 (inner1 AND inner2) OR (op2a code2 op2b)
4630 => (t AND (inner2 OR (op2a code op2b))) */
4631 else if (integer_zerop (t))
4632 return boolean_false_node;
4634 /* Save partial result for later. */
4635 partial = t;
4638 /* Compute the second partial result, (inner2 OR (op2a code op2b)) */
4639 if (TREE_CODE (inner2) == SSA_NAME
4640 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner2))
4641 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
4642 && (t = maybe_fold_or_comparisons (gimple_assign_rhs_code (s),
4643 gimple_assign_rhs1 (s),
4644 gimple_assign_rhs2 (s),
4645 code2, op2a, op2b)))
4647 /* Handle the OR case, where we are reassociating:
4648 (inner1 OR inner2) OR (op2a code2 op2b)
4649 => (inner1 OR t)
4650 => (t OR partial) */
4651 if (is_or)
4653 if (integer_zerop (t))
4654 return inner1;
4655 else if (integer_onep (t))
4656 return boolean_true_node;
4657 /* If both are the same, we can apply the identity
4658 (x OR x) == x. */
4659 else if (partial && same_bool_result_p (t, partial))
4660 return t;
4663 /* Handle the AND case, where we are redistributing:
4664 (inner1 AND inner2) OR (op2a code2 op2b)
4665 => (t AND (inner1 OR (op2a code2 op2b)))
4666 => (t AND partial) */
4667 else
4669 if (integer_zerop (t))
4670 return boolean_false_node;
4671 else if (partial)
4673 /* We already got a simplification for the other
4674 operand to the redistributed AND expression. The
4675 interesting case is when at least one is true.
4676 Or, if both are the same, we can apply the identity
4677 (x AND x) == x. */
4678 if (integer_onep (partial))
4679 return t;
4680 else if (integer_onep (t))
4681 return partial;
4682 else if (same_bool_result_p (t, partial))
4683 return t;
4688 return NULL_TREE;
4691 /* Try to simplify the OR of two comparisons defined by
4692 (OP1A CODE1 OP1B) and (OP2A CODE2 OP2B), respectively.
4693 If this can be done without constructing an intermediate value,
4694 return the resulting tree; otherwise NULL_TREE is returned.
4695 This function is deliberately asymmetric as it recurses on SSA_DEFs
4696 in the first comparison but not the second. */
4698 static tree
4699 or_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
4700 enum tree_code code2, tree op2a, tree op2b)
4702 tree truth_type = truth_type_for (TREE_TYPE (op1a));
4704 /* First check for ((x CODE1 y) OR (x CODE2 y)). */
4705 if (operand_equal_p (op1a, op2a, 0)
4706 && operand_equal_p (op1b, op2b, 0))
4708 /* Result will be either NULL_TREE, or a combined comparison. */
4709 tree t = combine_comparisons (UNKNOWN_LOCATION,
4710 TRUTH_ORIF_EXPR, code1, code2,
4711 truth_type, op1a, op1b);
4712 if (t)
4713 return t;
4716 /* Likewise the swapped case of the above. */
4717 if (operand_equal_p (op1a, op2b, 0)
4718 && operand_equal_p (op1b, op2a, 0))
4720 /* Result will be either NULL_TREE, or a combined comparison. */
4721 tree t = combine_comparisons (UNKNOWN_LOCATION,
4722 TRUTH_ORIF_EXPR, code1,
4723 swap_tree_comparison (code2),
4724 truth_type, op1a, op1b);
4725 if (t)
4726 return t;
4729 /* If both comparisons are of the same value against constants, we might
4730 be able to merge them. */
4731 if (operand_equal_p (op1a, op2a, 0)
4732 && TREE_CODE (op1b) == INTEGER_CST
4733 && TREE_CODE (op2b) == INTEGER_CST)
4735 int cmp = tree_int_cst_compare (op1b, op2b);
4737 /* If we have (op1a != op1b), we should either be able to
4738 return that or TRUE, depending on whether the constant op1b
4739 also satisfies the other comparison against op2b. */
4740 if (code1 == NE_EXPR)
4742 bool done = true;
4743 bool val;
4744 switch (code2)
4746 case EQ_EXPR: val = (cmp == 0); break;
4747 case NE_EXPR: val = (cmp != 0); break;
4748 case LT_EXPR: val = (cmp < 0); break;
4749 case GT_EXPR: val = (cmp > 0); break;
4750 case LE_EXPR: val = (cmp <= 0); break;
4751 case GE_EXPR: val = (cmp >= 0); break;
4752 default: done = false;
4754 if (done)
4756 if (val)
4757 return boolean_true_node;
4758 else
4759 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4762 /* Likewise if the second comparison is a != comparison. */
4763 else if (code2 == NE_EXPR)
4765 bool done = true;
4766 bool val;
4767 switch (code1)
4769 case EQ_EXPR: val = (cmp == 0); break;
4770 case NE_EXPR: val = (cmp != 0); break;
4771 case LT_EXPR: val = (cmp > 0); break;
4772 case GT_EXPR: val = (cmp < 0); break;
4773 case LE_EXPR: val = (cmp >= 0); break;
4774 case GE_EXPR: val = (cmp <= 0); break;
4775 default: done = false;
4777 if (done)
4779 if (val)
4780 return boolean_true_node;
4781 else
4782 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4786 /* See if an equality test is redundant with the other comparison. */
4787 else if (code1 == EQ_EXPR)
4789 bool val;
4790 switch (code2)
4792 case EQ_EXPR: val = (cmp == 0); break;
4793 case NE_EXPR: val = (cmp != 0); break;
4794 case LT_EXPR: val = (cmp < 0); break;
4795 case GT_EXPR: val = (cmp > 0); break;
4796 case LE_EXPR: val = (cmp <= 0); break;
4797 case GE_EXPR: val = (cmp >= 0); break;
4798 default:
4799 val = false;
4801 if (val)
4802 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4804 else if (code2 == EQ_EXPR)
4806 bool val;
4807 switch (code1)
4809 case EQ_EXPR: val = (cmp == 0); break;
4810 case NE_EXPR: val = (cmp != 0); break;
4811 case LT_EXPR: val = (cmp > 0); break;
4812 case GT_EXPR: val = (cmp < 0); break;
4813 case LE_EXPR: val = (cmp >= 0); break;
4814 case GE_EXPR: val = (cmp <= 0); break;
4815 default:
4816 val = false;
4818 if (val)
4819 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4822 /* Chose the less restrictive of two < or <= comparisons. */
4823 else if ((code1 == LT_EXPR || code1 == LE_EXPR)
4824 && (code2 == LT_EXPR || code2 == LE_EXPR))
4826 if ((cmp < 0) || (cmp == 0 && code1 == LT_EXPR))
4827 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4828 else
4829 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4832 /* Likewise chose the less restrictive of two > or >= comparisons. */
4833 else if ((code1 == GT_EXPR || code1 == GE_EXPR)
4834 && (code2 == GT_EXPR || code2 == GE_EXPR))
4836 if ((cmp > 0) || (cmp == 0 && code1 == GT_EXPR))
4837 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4838 else
4839 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4842 /* Check for singleton ranges. */
4843 else if (cmp == 0
4844 && ((code1 == LT_EXPR && code2 == GT_EXPR)
4845 || (code1 == GT_EXPR && code2 == LT_EXPR)))
4846 return fold_build2 (NE_EXPR, boolean_type_node, op1a, op2b);
4848 /* Check for less/greater pairs that don't restrict the range at all. */
4849 else if (cmp >= 0
4850 && (code1 == LT_EXPR || code1 == LE_EXPR)
4851 && (code2 == GT_EXPR || code2 == GE_EXPR))
4852 return boolean_true_node;
4853 else if (cmp <= 0
4854 && (code1 == GT_EXPR || code1 == GE_EXPR)
4855 && (code2 == LT_EXPR || code2 == LE_EXPR))
4856 return boolean_true_node;
4859 /* Perhaps the first comparison is (NAME != 0) or (NAME == 1) where
4860 NAME's definition is a truth value. See if there are any simplifications
4861 that can be done against the NAME's definition. */
4862 if (TREE_CODE (op1a) == SSA_NAME
4863 && (code1 == NE_EXPR || code1 == EQ_EXPR)
4864 && (integer_zerop (op1b) || integer_onep (op1b)))
4866 bool invert = ((code1 == EQ_EXPR && integer_zerop (op1b))
4867 || (code1 == NE_EXPR && integer_onep (op1b)));
4868 gimple *stmt = SSA_NAME_DEF_STMT (op1a);
4869 switch (gimple_code (stmt))
4871 case GIMPLE_ASSIGN:
4872 /* Try to simplify by copy-propagating the definition. */
4873 return or_var_with_comparison (op1a, invert, code2, op2a, op2b);
4875 case GIMPLE_PHI:
4876 /* If every argument to the PHI produces the same result when
4877 ORed with the second comparison, we win.
4878 Do not do this unless the type is bool since we need a bool
4879 result here anyway. */
4880 if (TREE_CODE (TREE_TYPE (op1a)) == BOOLEAN_TYPE)
4882 tree result = NULL_TREE;
4883 unsigned i;
4884 for (i = 0; i < gimple_phi_num_args (stmt); i++)
4886 tree arg = gimple_phi_arg_def (stmt, i);
4888 /* If this PHI has itself as an argument, ignore it.
4889 If all the other args produce the same result,
4890 we're still OK. */
4891 if (arg == gimple_phi_result (stmt))
4892 continue;
4893 else if (TREE_CODE (arg) == INTEGER_CST)
4895 if (invert ? integer_zerop (arg) : integer_nonzerop (arg))
4897 if (!result)
4898 result = boolean_true_node;
4899 else if (!integer_onep (result))
4900 return NULL_TREE;
4902 else if (!result)
4903 result = fold_build2 (code2, boolean_type_node,
4904 op2a, op2b);
4905 else if (!same_bool_comparison_p (result,
4906 code2, op2a, op2b))
4907 return NULL_TREE;
4909 else if (TREE_CODE (arg) == SSA_NAME
4910 && !SSA_NAME_IS_DEFAULT_DEF (arg))
4912 tree temp;
4913 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
4914 /* In simple cases we can look through PHI nodes,
4915 but we have to be careful with loops.
4916 See PR49073. */
4917 if (! dom_info_available_p (CDI_DOMINATORS)
4918 || gimple_bb (def_stmt) == gimple_bb (stmt)
4919 || dominated_by_p (CDI_DOMINATORS,
4920 gimple_bb (def_stmt),
4921 gimple_bb (stmt)))
4922 return NULL_TREE;
4923 temp = or_var_with_comparison (arg, invert, code2,
4924 op2a, op2b);
4925 if (!temp)
4926 return NULL_TREE;
4927 else if (!result)
4928 result = temp;
4929 else if (!same_bool_result_p (result, temp))
4930 return NULL_TREE;
4932 else
4933 return NULL_TREE;
4935 return result;
4938 default:
4939 break;
4942 return NULL_TREE;
4945 /* Try to simplify the OR of two comparisons, specified by
4946 (OP1A CODE1 OP1B) and (OP2B CODE2 OP2B), respectively.
4947 If this can be simplified to a single expression (without requiring
4948 introducing more SSA variables to hold intermediate values),
4949 return the resulting tree. Otherwise return NULL_TREE.
4950 If the result expression is non-null, it has boolean type. */
4952 tree
4953 maybe_fold_or_comparisons (enum tree_code code1, tree op1a, tree op1b,
4954 enum tree_code code2, tree op2a, tree op2b)
4956 tree t = or_comparisons_1 (code1, op1a, op1b, code2, op2a, op2b);
4957 if (t)
4958 return t;
4959 else
4960 return or_comparisons_1 (code2, op2a, op2b, code1, op1a, op1b);
4964 /* Fold STMT to a constant using VALUEIZE to valueize SSA names.
4966 Either NULL_TREE, a simplified but non-constant or a constant
4967 is returned.
4969 ??? This should go into a gimple-fold-inline.h file to be eventually
4970 privatized with the single valueize function used in the various TUs
4971 to avoid the indirect function call overhead. */
4973 tree
4974 gimple_fold_stmt_to_constant_1 (gimple *stmt, tree (*valueize) (tree),
4975 tree (*gvalueize) (tree))
4977 code_helper rcode;
4978 tree ops[3] = {};
4979 /* ??? The SSA propagators do not correctly deal with following SSA use-def
4980 edges if there are intermediate VARYING defs. For this reason
4981 do not follow SSA edges here even though SCCVN can technically
4982 just deal fine with that. */
4983 if (gimple_simplify (stmt, &rcode, ops, NULL, gvalueize, valueize))
4985 tree res = NULL_TREE;
4986 if (gimple_simplified_result_is_gimple_val (rcode, ops))
4987 res = ops[0];
4988 else if (mprts_hook)
4989 res = mprts_hook (rcode, gimple_expr_type (stmt), ops);
4990 if (res)
4992 if (dump_file && dump_flags & TDF_DETAILS)
4994 fprintf (dump_file, "Match-and-simplified ");
4995 print_gimple_expr (dump_file, stmt, 0, TDF_SLIM);
4996 fprintf (dump_file, " to ");
4997 print_generic_expr (dump_file, res, 0);
4998 fprintf (dump_file, "\n");
5000 return res;
5004 location_t loc = gimple_location (stmt);
5005 switch (gimple_code (stmt))
5007 case GIMPLE_ASSIGN:
5009 enum tree_code subcode = gimple_assign_rhs_code (stmt);
5011 switch (get_gimple_rhs_class (subcode))
5013 case GIMPLE_SINGLE_RHS:
5015 tree rhs = gimple_assign_rhs1 (stmt);
5016 enum tree_code_class kind = TREE_CODE_CLASS (subcode);
5018 if (TREE_CODE (rhs) == SSA_NAME)
5020 /* If the RHS is an SSA_NAME, return its known constant value,
5021 if any. */
5022 return (*valueize) (rhs);
5024 /* Handle propagating invariant addresses into address
5025 operations. */
5026 else if (TREE_CODE (rhs) == ADDR_EXPR
5027 && !is_gimple_min_invariant (rhs))
5029 HOST_WIDE_INT offset = 0;
5030 tree base;
5031 base = get_addr_base_and_unit_offset_1 (TREE_OPERAND (rhs, 0),
5032 &offset,
5033 valueize);
5034 if (base
5035 && (CONSTANT_CLASS_P (base)
5036 || decl_address_invariant_p (base)))
5037 return build_invariant_address (TREE_TYPE (rhs),
5038 base, offset);
5040 else if (TREE_CODE (rhs) == CONSTRUCTOR
5041 && TREE_CODE (TREE_TYPE (rhs)) == VECTOR_TYPE
5042 && (CONSTRUCTOR_NELTS (rhs)
5043 == TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs))))
5045 unsigned i;
5046 tree val, *vec;
5048 vec = XALLOCAVEC (tree,
5049 TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs)));
5050 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), i, val)
5052 val = (*valueize) (val);
5053 if (TREE_CODE (val) == INTEGER_CST
5054 || TREE_CODE (val) == REAL_CST
5055 || TREE_CODE (val) == FIXED_CST)
5056 vec[i] = val;
5057 else
5058 return NULL_TREE;
5061 return build_vector (TREE_TYPE (rhs), vec);
5063 if (subcode == OBJ_TYPE_REF)
5065 tree val = (*valueize) (OBJ_TYPE_REF_EXPR (rhs));
5066 /* If callee is constant, we can fold away the wrapper. */
5067 if (is_gimple_min_invariant (val))
5068 return val;
5071 if (kind == tcc_reference)
5073 if ((TREE_CODE (rhs) == VIEW_CONVERT_EXPR
5074 || TREE_CODE (rhs) == REALPART_EXPR
5075 || TREE_CODE (rhs) == IMAGPART_EXPR)
5076 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
5078 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
5079 return fold_unary_loc (EXPR_LOCATION (rhs),
5080 TREE_CODE (rhs),
5081 TREE_TYPE (rhs), val);
5083 else if (TREE_CODE (rhs) == BIT_FIELD_REF
5084 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
5086 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
5087 return fold_ternary_loc (EXPR_LOCATION (rhs),
5088 TREE_CODE (rhs),
5089 TREE_TYPE (rhs), val,
5090 TREE_OPERAND (rhs, 1),
5091 TREE_OPERAND (rhs, 2));
5093 else if (TREE_CODE (rhs) == MEM_REF
5094 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
5096 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
5097 if (TREE_CODE (val) == ADDR_EXPR
5098 && is_gimple_min_invariant (val))
5100 tree tem = fold_build2 (MEM_REF, TREE_TYPE (rhs),
5101 unshare_expr (val),
5102 TREE_OPERAND (rhs, 1));
5103 if (tem)
5104 rhs = tem;
5107 return fold_const_aggregate_ref_1 (rhs, valueize);
5109 else if (kind == tcc_declaration)
5110 return get_symbol_constant_value (rhs);
5111 return rhs;
5114 case GIMPLE_UNARY_RHS:
5115 return NULL_TREE;
5117 case GIMPLE_BINARY_RHS:
5118 /* Translate &x + CST into an invariant form suitable for
5119 further propagation. */
5120 if (subcode == POINTER_PLUS_EXPR)
5122 tree op0 = (*valueize) (gimple_assign_rhs1 (stmt));
5123 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
5124 if (TREE_CODE (op0) == ADDR_EXPR
5125 && TREE_CODE (op1) == INTEGER_CST)
5127 tree off = fold_convert (ptr_type_node, op1);
5128 return build_fold_addr_expr_loc
5129 (loc,
5130 fold_build2 (MEM_REF,
5131 TREE_TYPE (TREE_TYPE (op0)),
5132 unshare_expr (op0), off));
5135 /* Canonicalize bool != 0 and bool == 0 appearing after
5136 valueization. While gimple_simplify handles this
5137 it can get confused by the ~X == 1 -> X == 0 transform
5138 which we cant reduce to a SSA name or a constant
5139 (and we have no way to tell gimple_simplify to not
5140 consider those transforms in the first place). */
5141 else if (subcode == EQ_EXPR
5142 || subcode == NE_EXPR)
5144 tree lhs = gimple_assign_lhs (stmt);
5145 tree op0 = gimple_assign_rhs1 (stmt);
5146 if (useless_type_conversion_p (TREE_TYPE (lhs),
5147 TREE_TYPE (op0)))
5149 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
5150 op0 = (*valueize) (op0);
5151 if (TREE_CODE (op0) == INTEGER_CST)
5152 std::swap (op0, op1);
5153 if (TREE_CODE (op1) == INTEGER_CST
5154 && ((subcode == NE_EXPR && integer_zerop (op1))
5155 || (subcode == EQ_EXPR && integer_onep (op1))))
5156 return op0;
5159 return NULL_TREE;
5161 case GIMPLE_TERNARY_RHS:
5163 /* Handle ternary operators that can appear in GIMPLE form. */
5164 tree op0 = (*valueize) (gimple_assign_rhs1 (stmt));
5165 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
5166 tree op2 = (*valueize) (gimple_assign_rhs3 (stmt));
5167 return fold_ternary_loc (loc, subcode,
5168 gimple_expr_type (stmt), op0, op1, op2);
5171 default:
5172 gcc_unreachable ();
5176 case GIMPLE_CALL:
5178 tree fn;
5179 gcall *call_stmt = as_a <gcall *> (stmt);
5181 if (gimple_call_internal_p (stmt))
5183 enum tree_code subcode = ERROR_MARK;
5184 switch (gimple_call_internal_fn (stmt))
5186 case IFN_UBSAN_CHECK_ADD:
5187 subcode = PLUS_EXPR;
5188 break;
5189 case IFN_UBSAN_CHECK_SUB:
5190 subcode = MINUS_EXPR;
5191 break;
5192 case IFN_UBSAN_CHECK_MUL:
5193 subcode = MULT_EXPR;
5194 break;
5195 default:
5196 return NULL_TREE;
5198 tree arg0 = gimple_call_arg (stmt, 0);
5199 tree arg1 = gimple_call_arg (stmt, 1);
5200 tree op0 = (*valueize) (arg0);
5201 tree op1 = (*valueize) (arg1);
5203 if (TREE_CODE (op0) != INTEGER_CST
5204 || TREE_CODE (op1) != INTEGER_CST)
5206 switch (subcode)
5208 case MULT_EXPR:
5209 /* x * 0 = 0 * x = 0 without overflow. */
5210 if (integer_zerop (op0) || integer_zerop (op1))
5211 return build_zero_cst (TREE_TYPE (arg0));
5212 break;
5213 case MINUS_EXPR:
5214 /* y - y = 0 without overflow. */
5215 if (operand_equal_p (op0, op1, 0))
5216 return build_zero_cst (TREE_TYPE (arg0));
5217 break;
5218 default:
5219 break;
5222 tree res
5223 = fold_binary_loc (loc, subcode, TREE_TYPE (arg0), op0, op1);
5224 if (res
5225 && TREE_CODE (res) == INTEGER_CST
5226 && !TREE_OVERFLOW (res))
5227 return res;
5228 return NULL_TREE;
5231 fn = (*valueize) (gimple_call_fn (stmt));
5232 if (TREE_CODE (fn) == ADDR_EXPR
5233 && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL
5234 && DECL_BUILT_IN (TREE_OPERAND (fn, 0))
5235 && gimple_builtin_call_types_compatible_p (stmt,
5236 TREE_OPERAND (fn, 0)))
5238 tree *args = XALLOCAVEC (tree, gimple_call_num_args (stmt));
5239 tree retval;
5240 unsigned i;
5241 for (i = 0; i < gimple_call_num_args (stmt); ++i)
5242 args[i] = (*valueize) (gimple_call_arg (stmt, i));
5243 retval = fold_builtin_call_array (loc,
5244 gimple_call_return_type (call_stmt),
5245 fn, gimple_call_num_args (stmt), args);
5246 if (retval)
5248 /* fold_call_expr wraps the result inside a NOP_EXPR. */
5249 STRIP_NOPS (retval);
5250 retval = fold_convert (gimple_call_return_type (call_stmt),
5251 retval);
5253 return retval;
5255 return NULL_TREE;
5258 default:
5259 return NULL_TREE;
5263 /* Fold STMT to a constant using VALUEIZE to valueize SSA names.
5264 Returns NULL_TREE if folding to a constant is not possible, otherwise
5265 returns a constant according to is_gimple_min_invariant. */
5267 tree
5268 gimple_fold_stmt_to_constant (gimple *stmt, tree (*valueize) (tree))
5270 tree res = gimple_fold_stmt_to_constant_1 (stmt, valueize);
5271 if (res && is_gimple_min_invariant (res))
5272 return res;
5273 return NULL_TREE;
5277 /* The following set of functions are supposed to fold references using
5278 their constant initializers. */
5280 /* See if we can find constructor defining value of BASE.
5281 When we know the consructor with constant offset (such as
5282 base is array[40] and we do know constructor of array), then
5283 BIT_OFFSET is adjusted accordingly.
5285 As a special case, return error_mark_node when constructor
5286 is not explicitly available, but it is known to be zero
5287 such as 'static const int a;'. */
5288 static tree
5289 get_base_constructor (tree base, HOST_WIDE_INT *bit_offset,
5290 tree (*valueize)(tree))
5292 HOST_WIDE_INT bit_offset2, size, max_size;
5293 bool reverse;
5295 if (TREE_CODE (base) == MEM_REF)
5297 if (!integer_zerop (TREE_OPERAND (base, 1)))
5299 if (!tree_fits_shwi_p (TREE_OPERAND (base, 1)))
5300 return NULL_TREE;
5301 *bit_offset += (mem_ref_offset (base).to_short_addr ()
5302 * BITS_PER_UNIT);
5305 if (valueize
5306 && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
5307 base = valueize (TREE_OPERAND (base, 0));
5308 if (!base || TREE_CODE (base) != ADDR_EXPR)
5309 return NULL_TREE;
5310 base = TREE_OPERAND (base, 0);
5313 /* Get a CONSTRUCTOR. If BASE is a VAR_DECL, get its
5314 DECL_INITIAL. If BASE is a nested reference into another
5315 ARRAY_REF or COMPONENT_REF, make a recursive call to resolve
5316 the inner reference. */
5317 switch (TREE_CODE (base))
5319 case VAR_DECL:
5320 case CONST_DECL:
5322 tree init = ctor_for_folding (base);
5324 /* Our semantic is exact opposite of ctor_for_folding;
5325 NULL means unknown, while error_mark_node is 0. */
5326 if (init == error_mark_node)
5327 return NULL_TREE;
5328 if (!init)
5329 return error_mark_node;
5330 return init;
5333 case ARRAY_REF:
5334 case COMPONENT_REF:
5335 base = get_ref_base_and_extent (base, &bit_offset2, &size, &max_size,
5336 &reverse);
5337 if (max_size == -1 || size != max_size)
5338 return NULL_TREE;
5339 *bit_offset += bit_offset2;
5340 return get_base_constructor (base, bit_offset, valueize);
5342 case STRING_CST:
5343 case CONSTRUCTOR:
5344 return base;
5346 default:
5347 return NULL_TREE;
5351 /* CTOR is CONSTRUCTOR of an array type. Fold reference of type TYPE and size
5352 SIZE to the memory at bit OFFSET. */
5354 static tree
5355 fold_array_ctor_reference (tree type, tree ctor,
5356 unsigned HOST_WIDE_INT offset,
5357 unsigned HOST_WIDE_INT size,
5358 tree from_decl)
5360 offset_int low_bound;
5361 offset_int elt_size;
5362 offset_int access_index;
5363 tree domain_type = NULL_TREE;
5364 HOST_WIDE_INT inner_offset;
5366 /* Compute low bound and elt size. */
5367 if (TREE_CODE (TREE_TYPE (ctor)) == ARRAY_TYPE)
5368 domain_type = TYPE_DOMAIN (TREE_TYPE (ctor));
5369 if (domain_type && TYPE_MIN_VALUE (domain_type))
5371 /* Static constructors for variably sized objects makes no sense. */
5372 gcc_assert (TREE_CODE (TYPE_MIN_VALUE (domain_type)) == INTEGER_CST);
5373 low_bound = wi::to_offset (TYPE_MIN_VALUE (domain_type));
5375 else
5376 low_bound = 0;
5377 /* Static constructors for variably sized objects makes no sense. */
5378 gcc_assert (TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (ctor))))
5379 == INTEGER_CST);
5380 elt_size = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (ctor))));
5382 /* We can handle only constantly sized accesses that are known to not
5383 be larger than size of array element. */
5384 if (!TYPE_SIZE_UNIT (type)
5385 || TREE_CODE (TYPE_SIZE_UNIT (type)) != INTEGER_CST
5386 || elt_size < wi::to_offset (TYPE_SIZE_UNIT (type))
5387 || elt_size == 0)
5388 return NULL_TREE;
5390 /* Compute the array index we look for. */
5391 access_index = wi::udiv_trunc (offset_int (offset / BITS_PER_UNIT),
5392 elt_size);
5393 access_index += low_bound;
5395 /* And offset within the access. */
5396 inner_offset = offset % (elt_size.to_uhwi () * BITS_PER_UNIT);
5398 /* See if the array field is large enough to span whole access. We do not
5399 care to fold accesses spanning multiple array indexes. */
5400 if (inner_offset + size > elt_size.to_uhwi () * BITS_PER_UNIT)
5401 return NULL_TREE;
5402 if (tree val = get_array_ctor_element_at_index (ctor, access_index))
5403 return fold_ctor_reference (type, val, inner_offset, size, from_decl);
5405 /* When memory is not explicitely mentioned in constructor,
5406 it is 0 (or out of range). */
5407 return build_zero_cst (type);
5410 /* CTOR is CONSTRUCTOR of an aggregate or vector.
5411 Fold reference of type TYPE and size SIZE to the memory at bit OFFSET. */
5413 static tree
5414 fold_nonarray_ctor_reference (tree type, tree ctor,
5415 unsigned HOST_WIDE_INT offset,
5416 unsigned HOST_WIDE_INT size,
5417 tree from_decl)
5419 unsigned HOST_WIDE_INT cnt;
5420 tree cfield, cval;
5422 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), cnt, cfield,
5423 cval)
5425 tree byte_offset = DECL_FIELD_OFFSET (cfield);
5426 tree field_offset = DECL_FIELD_BIT_OFFSET (cfield);
5427 tree field_size = DECL_SIZE (cfield);
5428 offset_int bitoffset;
5429 offset_int bitoffset_end, access_end;
5431 /* Variable sized objects in static constructors makes no sense,
5432 but field_size can be NULL for flexible array members. */
5433 gcc_assert (TREE_CODE (field_offset) == INTEGER_CST
5434 && TREE_CODE (byte_offset) == INTEGER_CST
5435 && (field_size != NULL_TREE
5436 ? TREE_CODE (field_size) == INTEGER_CST
5437 : TREE_CODE (TREE_TYPE (cfield)) == ARRAY_TYPE));
5439 /* Compute bit offset of the field. */
5440 bitoffset = (wi::to_offset (field_offset)
5441 + (wi::to_offset (byte_offset) << LOG2_BITS_PER_UNIT));
5442 /* Compute bit offset where the field ends. */
5443 if (field_size != NULL_TREE)
5444 bitoffset_end = bitoffset + wi::to_offset (field_size);
5445 else
5446 bitoffset_end = 0;
5448 access_end = offset_int (offset) + size;
5450 /* Is there any overlap between [OFFSET, OFFSET+SIZE) and
5451 [BITOFFSET, BITOFFSET_END)? */
5452 if (wi::cmps (access_end, bitoffset) > 0
5453 && (field_size == NULL_TREE
5454 || wi::lts_p (offset, bitoffset_end)))
5456 offset_int inner_offset = offset_int (offset) - bitoffset;
5457 /* We do have overlap. Now see if field is large enough to
5458 cover the access. Give up for accesses spanning multiple
5459 fields. */
5460 if (wi::cmps (access_end, bitoffset_end) > 0)
5461 return NULL_TREE;
5462 if (offset < bitoffset)
5463 return NULL_TREE;
5464 return fold_ctor_reference (type, cval,
5465 inner_offset.to_uhwi (), size,
5466 from_decl);
5469 /* When memory is not explicitely mentioned in constructor, it is 0. */
5470 return build_zero_cst (type);
5473 /* CTOR is value initializing memory, fold reference of type TYPE and size SIZE
5474 to the memory at bit OFFSET. */
5476 tree
5477 fold_ctor_reference (tree type, tree ctor, unsigned HOST_WIDE_INT offset,
5478 unsigned HOST_WIDE_INT size, tree from_decl)
5480 tree ret;
5482 /* We found the field with exact match. */
5483 if (useless_type_conversion_p (type, TREE_TYPE (ctor))
5484 && !offset)
5485 return canonicalize_constructor_val (unshare_expr (ctor), from_decl);
5487 /* We are at the end of walk, see if we can view convert the
5488 result. */
5489 if (!AGGREGATE_TYPE_P (TREE_TYPE (ctor)) && !offset
5490 /* VIEW_CONVERT_EXPR is defined only for matching sizes. */
5491 && !compare_tree_int (TYPE_SIZE (type), size)
5492 && !compare_tree_int (TYPE_SIZE (TREE_TYPE (ctor)), size))
5494 ret = canonicalize_constructor_val (unshare_expr (ctor), from_decl);
5495 ret = fold_unary (VIEW_CONVERT_EXPR, type, ret);
5496 if (ret)
5497 STRIP_USELESS_TYPE_CONVERSION (ret);
5498 return ret;
5500 /* For constants and byte-aligned/sized reads try to go through
5501 native_encode/interpret. */
5502 if (CONSTANT_CLASS_P (ctor)
5503 && BITS_PER_UNIT == 8
5504 && offset % BITS_PER_UNIT == 0
5505 && size % BITS_PER_UNIT == 0
5506 && size <= MAX_BITSIZE_MODE_ANY_MODE)
5508 unsigned char buf[MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT];
5509 int len = native_encode_expr (ctor, buf, size / BITS_PER_UNIT,
5510 offset / BITS_PER_UNIT);
5511 if (len > 0)
5512 return native_interpret_expr (type, buf, len);
5514 if (TREE_CODE (ctor) == CONSTRUCTOR)
5517 if (TREE_CODE (TREE_TYPE (ctor)) == ARRAY_TYPE
5518 || TREE_CODE (TREE_TYPE (ctor)) == VECTOR_TYPE)
5519 return fold_array_ctor_reference (type, ctor, offset, size,
5520 from_decl);
5521 else
5522 return fold_nonarray_ctor_reference (type, ctor, offset, size,
5523 from_decl);
5526 return NULL_TREE;
5529 /* Return the tree representing the element referenced by T if T is an
5530 ARRAY_REF or COMPONENT_REF into constant aggregates valuezing SSA
5531 names using VALUEIZE. Return NULL_TREE otherwise. */
5533 tree
5534 fold_const_aggregate_ref_1 (tree t, tree (*valueize) (tree))
5536 tree ctor, idx, base;
5537 HOST_WIDE_INT offset, size, max_size;
5538 tree tem;
5539 bool reverse;
5541 if (TREE_THIS_VOLATILE (t))
5542 return NULL_TREE;
5544 if (DECL_P (t))
5545 return get_symbol_constant_value (t);
5547 tem = fold_read_from_constant_string (t);
5548 if (tem)
5549 return tem;
5551 switch (TREE_CODE (t))
5553 case ARRAY_REF:
5554 case ARRAY_RANGE_REF:
5555 /* Constant indexes are handled well by get_base_constructor.
5556 Only special case variable offsets.
5557 FIXME: This code can't handle nested references with variable indexes
5558 (they will be handled only by iteration of ccp). Perhaps we can bring
5559 get_ref_base_and_extent here and make it use a valueize callback. */
5560 if (TREE_CODE (TREE_OPERAND (t, 1)) == SSA_NAME
5561 && valueize
5562 && (idx = (*valueize) (TREE_OPERAND (t, 1)))
5563 && TREE_CODE (idx) == INTEGER_CST)
5565 tree low_bound, unit_size;
5567 /* If the resulting bit-offset is constant, track it. */
5568 if ((low_bound = array_ref_low_bound (t),
5569 TREE_CODE (low_bound) == INTEGER_CST)
5570 && (unit_size = array_ref_element_size (t),
5571 tree_fits_uhwi_p (unit_size)))
5573 offset_int woffset
5574 = wi::sext (wi::to_offset (idx) - wi::to_offset (low_bound),
5575 TYPE_PRECISION (TREE_TYPE (idx)));
5577 if (wi::fits_shwi_p (woffset))
5579 offset = woffset.to_shwi ();
5580 /* TODO: This code seems wrong, multiply then check
5581 to see if it fits. */
5582 offset *= tree_to_uhwi (unit_size);
5583 offset *= BITS_PER_UNIT;
5585 base = TREE_OPERAND (t, 0);
5586 ctor = get_base_constructor (base, &offset, valueize);
5587 /* Empty constructor. Always fold to 0. */
5588 if (ctor == error_mark_node)
5589 return build_zero_cst (TREE_TYPE (t));
5590 /* Out of bound array access. Value is undefined,
5591 but don't fold. */
5592 if (offset < 0)
5593 return NULL_TREE;
5594 /* We can not determine ctor. */
5595 if (!ctor)
5596 return NULL_TREE;
5597 return fold_ctor_reference (TREE_TYPE (t), ctor, offset,
5598 tree_to_uhwi (unit_size)
5599 * BITS_PER_UNIT,
5600 base);
5604 /* Fallthru. */
5606 case COMPONENT_REF:
5607 case BIT_FIELD_REF:
5608 case TARGET_MEM_REF:
5609 case MEM_REF:
5610 base = get_ref_base_and_extent (t, &offset, &size, &max_size, &reverse);
5611 ctor = get_base_constructor (base, &offset, valueize);
5613 /* Empty constructor. Always fold to 0. */
5614 if (ctor == error_mark_node)
5615 return build_zero_cst (TREE_TYPE (t));
5616 /* We do not know precise address. */
5617 if (max_size == -1 || max_size != size)
5618 return NULL_TREE;
5619 /* We can not determine ctor. */
5620 if (!ctor)
5621 return NULL_TREE;
5623 /* Out of bound array access. Value is undefined, but don't fold. */
5624 if (offset < 0)
5625 return NULL_TREE;
5627 return fold_ctor_reference (TREE_TYPE (t), ctor, offset, size,
5628 base);
5630 case REALPART_EXPR:
5631 case IMAGPART_EXPR:
5633 tree c = fold_const_aggregate_ref_1 (TREE_OPERAND (t, 0), valueize);
5634 if (c && TREE_CODE (c) == COMPLEX_CST)
5635 return fold_build1_loc (EXPR_LOCATION (t),
5636 TREE_CODE (t), TREE_TYPE (t), c);
5637 break;
5640 default:
5641 break;
5644 return NULL_TREE;
5647 tree
5648 fold_const_aggregate_ref (tree t)
5650 return fold_const_aggregate_ref_1 (t, NULL);
5653 /* Lookup virtual method with index TOKEN in a virtual table V
5654 at OFFSET.
5655 Set CAN_REFER if non-NULL to false if method
5656 is not referable or if the virtual table is ill-formed (such as rewriten
5657 by non-C++ produced symbol). Otherwise just return NULL in that calse. */
5659 tree
5660 gimple_get_virt_method_for_vtable (HOST_WIDE_INT token,
5661 tree v,
5662 unsigned HOST_WIDE_INT offset,
5663 bool *can_refer)
5665 tree vtable = v, init, fn;
5666 unsigned HOST_WIDE_INT size;
5667 unsigned HOST_WIDE_INT elt_size, access_index;
5668 tree domain_type;
5670 if (can_refer)
5671 *can_refer = true;
5673 /* First of all double check we have virtual table. */
5674 if (TREE_CODE (v) != VAR_DECL
5675 || !DECL_VIRTUAL_P (v))
5677 /* Pass down that we lost track of the target. */
5678 if (can_refer)
5679 *can_refer = false;
5680 return NULL_TREE;
5683 init = ctor_for_folding (v);
5685 /* The virtual tables should always be born with constructors
5686 and we always should assume that they are avaialble for
5687 folding. At the moment we do not stream them in all cases,
5688 but it should never happen that ctor seem unreachable. */
5689 gcc_assert (init);
5690 if (init == error_mark_node)
5692 gcc_assert (in_lto_p);
5693 /* Pass down that we lost track of the target. */
5694 if (can_refer)
5695 *can_refer = false;
5696 return NULL_TREE;
5698 gcc_checking_assert (TREE_CODE (TREE_TYPE (v)) == ARRAY_TYPE);
5699 size = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (TREE_TYPE (v))));
5700 offset *= BITS_PER_UNIT;
5701 offset += token * size;
5703 /* Lookup the value in the constructor that is assumed to be array.
5704 This is equivalent to
5705 fn = fold_ctor_reference (TREE_TYPE (TREE_TYPE (v)), init,
5706 offset, size, NULL);
5707 but in a constant time. We expect that frontend produced a simple
5708 array without indexed initializers. */
5710 gcc_checking_assert (TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE);
5711 domain_type = TYPE_DOMAIN (TREE_TYPE (init));
5712 gcc_checking_assert (integer_zerop (TYPE_MIN_VALUE (domain_type)));
5713 elt_size = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (init))));
5715 access_index = offset / BITS_PER_UNIT / elt_size;
5716 gcc_checking_assert (offset % (elt_size * BITS_PER_UNIT) == 0);
5718 /* This code makes an assumption that there are no
5719 indexed fileds produced by C++ FE, so we can directly index the array. */
5720 if (access_index < CONSTRUCTOR_NELTS (init))
5722 fn = CONSTRUCTOR_ELT (init, access_index)->value;
5723 gcc_checking_assert (!CONSTRUCTOR_ELT (init, access_index)->index);
5724 STRIP_NOPS (fn);
5726 else
5727 fn = NULL;
5729 /* For type inconsistent program we may end up looking up virtual method
5730 in virtual table that does not contain TOKEN entries. We may overrun
5731 the virtual table and pick up a constant or RTTI info pointer.
5732 In any case the call is undefined. */
5733 if (!fn
5734 || (TREE_CODE (fn) != ADDR_EXPR && TREE_CODE (fn) != FDESC_EXPR)
5735 || TREE_CODE (TREE_OPERAND (fn, 0)) != FUNCTION_DECL)
5736 fn = builtin_decl_implicit (BUILT_IN_UNREACHABLE);
5737 else
5739 fn = TREE_OPERAND (fn, 0);
5741 /* When cgraph node is missing and function is not public, we cannot
5742 devirtualize. This can happen in WHOPR when the actual method
5743 ends up in other partition, because we found devirtualization
5744 possibility too late. */
5745 if (!can_refer_decl_in_current_unit_p (fn, vtable))
5747 if (can_refer)
5749 *can_refer = false;
5750 return fn;
5752 return NULL_TREE;
5756 /* Make sure we create a cgraph node for functions we'll reference.
5757 They can be non-existent if the reference comes from an entry
5758 of an external vtable for example. */
5759 cgraph_node::get_create (fn);
5761 return fn;
5764 /* Return a declaration of a function which an OBJ_TYPE_REF references. TOKEN
5765 is integer form of OBJ_TYPE_REF_TOKEN of the reference expression.
5766 KNOWN_BINFO carries the binfo describing the true type of
5767 OBJ_TYPE_REF_OBJECT(REF).
5768 Set CAN_REFER if non-NULL to false if method
5769 is not referable or if the virtual table is ill-formed (such as rewriten
5770 by non-C++ produced symbol). Otherwise just return NULL in that calse. */
5772 tree
5773 gimple_get_virt_method_for_binfo (HOST_WIDE_INT token, tree known_binfo,
5774 bool *can_refer)
5776 unsigned HOST_WIDE_INT offset;
5777 tree v;
5779 v = BINFO_VTABLE (known_binfo);
5780 /* If there is no virtual methods table, leave the OBJ_TYPE_REF alone. */
5781 if (!v)
5782 return NULL_TREE;
5784 if (!vtable_pointer_value_to_vtable (v, &v, &offset))
5786 if (can_refer)
5787 *can_refer = false;
5788 return NULL_TREE;
5790 return gimple_get_virt_method_for_vtable (token, v, offset, can_refer);
5793 /* Given a pointer value OP0, return a simplified version of an
5794 indirection through OP0, or NULL_TREE if no simplification is
5795 possible. Note that the resulting type may be different from
5796 the type pointed to in the sense that it is still compatible
5797 from the langhooks point of view. */
5799 tree
5800 gimple_fold_indirect_ref (tree t)
5802 tree ptype = TREE_TYPE (t), type = TREE_TYPE (ptype);
5803 tree sub = t;
5804 tree subtype;
5806 STRIP_NOPS (sub);
5807 subtype = TREE_TYPE (sub);
5808 if (!POINTER_TYPE_P (subtype))
5809 return NULL_TREE;
5811 if (TREE_CODE (sub) == ADDR_EXPR)
5813 tree op = TREE_OPERAND (sub, 0);
5814 tree optype = TREE_TYPE (op);
5815 /* *&p => p */
5816 if (useless_type_conversion_p (type, optype))
5817 return op;
5819 /* *(foo *)&fooarray => fooarray[0] */
5820 if (TREE_CODE (optype) == ARRAY_TYPE
5821 && TREE_CODE (TYPE_SIZE (TREE_TYPE (optype))) == INTEGER_CST
5822 && useless_type_conversion_p (type, TREE_TYPE (optype)))
5824 tree type_domain = TYPE_DOMAIN (optype);
5825 tree min_val = size_zero_node;
5826 if (type_domain && TYPE_MIN_VALUE (type_domain))
5827 min_val = TYPE_MIN_VALUE (type_domain);
5828 if (TREE_CODE (min_val) == INTEGER_CST)
5829 return build4 (ARRAY_REF, type, op, min_val, NULL_TREE, NULL_TREE);
5831 /* *(foo *)&complexfoo => __real__ complexfoo */
5832 else if (TREE_CODE (optype) == COMPLEX_TYPE
5833 && useless_type_conversion_p (type, TREE_TYPE (optype)))
5834 return fold_build1 (REALPART_EXPR, type, op);
5835 /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
5836 else if (TREE_CODE (optype) == VECTOR_TYPE
5837 && useless_type_conversion_p (type, TREE_TYPE (optype)))
5839 tree part_width = TYPE_SIZE (type);
5840 tree index = bitsize_int (0);
5841 return fold_build3 (BIT_FIELD_REF, type, op, part_width, index);
5845 /* *(p + CST) -> ... */
5846 if (TREE_CODE (sub) == POINTER_PLUS_EXPR
5847 && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST)
5849 tree addr = TREE_OPERAND (sub, 0);
5850 tree off = TREE_OPERAND (sub, 1);
5851 tree addrtype;
5853 STRIP_NOPS (addr);
5854 addrtype = TREE_TYPE (addr);
5856 /* ((foo*)&vectorfoo)[1] -> BIT_FIELD_REF<vectorfoo,...> */
5857 if (TREE_CODE (addr) == ADDR_EXPR
5858 && TREE_CODE (TREE_TYPE (addrtype)) == VECTOR_TYPE
5859 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (addrtype)))
5860 && tree_fits_uhwi_p (off))
5862 unsigned HOST_WIDE_INT offset = tree_to_uhwi (off);
5863 tree part_width = TYPE_SIZE (type);
5864 unsigned HOST_WIDE_INT part_widthi
5865 = tree_to_shwi (part_width) / BITS_PER_UNIT;
5866 unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT;
5867 tree index = bitsize_int (indexi);
5868 if (offset / part_widthi
5869 < TYPE_VECTOR_SUBPARTS (TREE_TYPE (addrtype)))
5870 return fold_build3 (BIT_FIELD_REF, type, TREE_OPERAND (addr, 0),
5871 part_width, index);
5874 /* ((foo*)&complexfoo)[1] -> __imag__ complexfoo */
5875 if (TREE_CODE (addr) == ADDR_EXPR
5876 && TREE_CODE (TREE_TYPE (addrtype)) == COMPLEX_TYPE
5877 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (addrtype))))
5879 tree size = TYPE_SIZE_UNIT (type);
5880 if (tree_int_cst_equal (size, off))
5881 return fold_build1 (IMAGPART_EXPR, type, TREE_OPERAND (addr, 0));
5884 /* *(p + CST) -> MEM_REF <p, CST>. */
5885 if (TREE_CODE (addr) != ADDR_EXPR
5886 || DECL_P (TREE_OPERAND (addr, 0)))
5887 return fold_build2 (MEM_REF, type,
5888 addr,
5889 wide_int_to_tree (ptype, off));
5892 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
5893 if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
5894 && TREE_CODE (TYPE_SIZE (TREE_TYPE (TREE_TYPE (subtype)))) == INTEGER_CST
5895 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (subtype))))
5897 tree type_domain;
5898 tree min_val = size_zero_node;
5899 tree osub = sub;
5900 sub = gimple_fold_indirect_ref (sub);
5901 if (! sub)
5902 sub = build1 (INDIRECT_REF, TREE_TYPE (subtype), osub);
5903 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
5904 if (type_domain && TYPE_MIN_VALUE (type_domain))
5905 min_val = TYPE_MIN_VALUE (type_domain);
5906 if (TREE_CODE (min_val) == INTEGER_CST)
5907 return build4 (ARRAY_REF, type, sub, min_val, NULL_TREE, NULL_TREE);
5910 return NULL_TREE;
5913 /* Return true if CODE is an operation that when operating on signed
5914 integer types involves undefined behavior on overflow and the
5915 operation can be expressed with unsigned arithmetic. */
5917 bool
5918 arith_code_with_undefined_signed_overflow (tree_code code)
5920 switch (code)
5922 case PLUS_EXPR:
5923 case MINUS_EXPR:
5924 case MULT_EXPR:
5925 case NEGATE_EXPR:
5926 case POINTER_PLUS_EXPR:
5927 return true;
5928 default:
5929 return false;
5933 /* Rewrite STMT, an assignment with a signed integer or pointer arithmetic
5934 operation that can be transformed to unsigned arithmetic by converting
5935 its operand, carrying out the operation in the corresponding unsigned
5936 type and converting the result back to the original type.
5938 Returns a sequence of statements that replace STMT and also contain
5939 a modified form of STMT itself. */
5941 gimple_seq
5942 rewrite_to_defined_overflow (gimple *stmt)
5944 if (dump_file && (dump_flags & TDF_DETAILS))
5946 fprintf (dump_file, "rewriting stmt with undefined signed "
5947 "overflow ");
5948 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
5951 tree lhs = gimple_assign_lhs (stmt);
5952 tree type = unsigned_type_for (TREE_TYPE (lhs));
5953 gimple_seq stmts = NULL;
5954 for (unsigned i = 1; i < gimple_num_ops (stmt); ++i)
5956 tree op = gimple_op (stmt, i);
5957 op = gimple_convert (&stmts, type, op);
5958 gimple_set_op (stmt, i, op);
5960 gimple_assign_set_lhs (stmt, make_ssa_name (type, stmt));
5961 if (gimple_assign_rhs_code (stmt) == POINTER_PLUS_EXPR)
5962 gimple_assign_set_rhs_code (stmt, PLUS_EXPR);
5963 gimple_seq_add_stmt (&stmts, stmt);
5964 gimple *cvt = gimple_build_assign (lhs, NOP_EXPR, gimple_assign_lhs (stmt));
5965 gimple_seq_add_stmt (&stmts, cvt);
5967 return stmts;
5971 /* The valueization hook we use for the gimple_build API simplification.
5972 This makes us match fold_buildN behavior by only combining with
5973 statements in the sequence(s) we are currently building. */
5975 static tree
5976 gimple_build_valueize (tree op)
5978 if (gimple_bb (SSA_NAME_DEF_STMT (op)) == NULL)
5979 return op;
5980 return NULL_TREE;
5983 /* Build the expression CODE OP0 of type TYPE with location LOC,
5984 simplifying it first if possible. Returns the built
5985 expression value and appends statements possibly defining it
5986 to SEQ. */
5988 tree
5989 gimple_build (gimple_seq *seq, location_t loc,
5990 enum tree_code code, tree type, tree op0)
5992 tree res = gimple_simplify (code, type, op0, seq, gimple_build_valueize);
5993 if (!res)
5995 if (gimple_in_ssa_p (cfun))
5996 res = make_ssa_name (type);
5997 else
5998 res = create_tmp_reg (type);
5999 gimple *stmt;
6000 if (code == REALPART_EXPR
6001 || code == IMAGPART_EXPR
6002 || code == VIEW_CONVERT_EXPR)
6003 stmt = gimple_build_assign (res, code, build1 (code, type, op0));
6004 else
6005 stmt = gimple_build_assign (res, code, op0);
6006 gimple_set_location (stmt, loc);
6007 gimple_seq_add_stmt_without_update (seq, stmt);
6009 return res;
6012 /* Build the expression OP0 CODE OP1 of type TYPE with location LOC,
6013 simplifying it first if possible. Returns the built
6014 expression value and appends statements possibly defining it
6015 to SEQ. */
6017 tree
6018 gimple_build (gimple_seq *seq, location_t loc,
6019 enum tree_code code, tree type, tree op0, tree op1)
6021 tree res = gimple_simplify (code, type, op0, op1, seq, gimple_build_valueize);
6022 if (!res)
6024 if (gimple_in_ssa_p (cfun))
6025 res = make_ssa_name (type);
6026 else
6027 res = create_tmp_reg (type);
6028 gimple *stmt = gimple_build_assign (res, code, op0, op1);
6029 gimple_set_location (stmt, loc);
6030 gimple_seq_add_stmt_without_update (seq, stmt);
6032 return res;
6035 /* Build the expression (CODE OP0 OP1 OP2) of type TYPE with location LOC,
6036 simplifying it first if possible. Returns the built
6037 expression value and appends statements possibly defining it
6038 to SEQ. */
6040 tree
6041 gimple_build (gimple_seq *seq, location_t loc,
6042 enum tree_code code, tree type, tree op0, tree op1, tree op2)
6044 tree res = gimple_simplify (code, type, op0, op1, op2,
6045 seq, gimple_build_valueize);
6046 if (!res)
6048 if (gimple_in_ssa_p (cfun))
6049 res = make_ssa_name (type);
6050 else
6051 res = create_tmp_reg (type);
6052 gimple *stmt;
6053 if (code == BIT_FIELD_REF)
6054 stmt = gimple_build_assign (res, code,
6055 build3 (code, type, op0, op1, op2));
6056 else
6057 stmt = gimple_build_assign (res, code, op0, op1, op2);
6058 gimple_set_location (stmt, loc);
6059 gimple_seq_add_stmt_without_update (seq, stmt);
6061 return res;
6064 /* Build the call FN (ARG0) with a result of type TYPE
6065 (or no result if TYPE is void) with location LOC,
6066 simplifying it first if possible. Returns the built
6067 expression value (or NULL_TREE if TYPE is void) and appends
6068 statements possibly defining it to SEQ. */
6070 tree
6071 gimple_build (gimple_seq *seq, location_t loc,
6072 enum built_in_function fn, tree type, tree arg0)
6074 tree res = gimple_simplify (fn, type, arg0, seq, gimple_build_valueize);
6075 if (!res)
6077 tree decl = builtin_decl_implicit (fn);
6078 gimple *stmt = gimple_build_call (decl, 1, arg0);
6079 if (!VOID_TYPE_P (type))
6081 if (gimple_in_ssa_p (cfun))
6082 res = make_ssa_name (type);
6083 else
6084 res = create_tmp_reg (type);
6085 gimple_call_set_lhs (stmt, res);
6087 gimple_set_location (stmt, loc);
6088 gimple_seq_add_stmt_without_update (seq, stmt);
6090 return res;
6093 /* Build the call FN (ARG0, ARG1) with a result of type TYPE
6094 (or no result if TYPE is void) with location LOC,
6095 simplifying it first if possible. Returns the built
6096 expression value (or NULL_TREE if TYPE is void) and appends
6097 statements possibly defining it to SEQ. */
6099 tree
6100 gimple_build (gimple_seq *seq, location_t loc,
6101 enum built_in_function fn, tree type, tree arg0, tree arg1)
6103 tree res = gimple_simplify (fn, type, arg0, arg1, seq, gimple_build_valueize);
6104 if (!res)
6106 tree decl = builtin_decl_implicit (fn);
6107 gimple *stmt = gimple_build_call (decl, 2, arg0, arg1);
6108 if (!VOID_TYPE_P (type))
6110 if (gimple_in_ssa_p (cfun))
6111 res = make_ssa_name (type);
6112 else
6113 res = create_tmp_reg (type);
6114 gimple_call_set_lhs (stmt, res);
6116 gimple_set_location (stmt, loc);
6117 gimple_seq_add_stmt_without_update (seq, stmt);
6119 return res;
6122 /* Build the call FN (ARG0, ARG1, ARG2) with a result of type TYPE
6123 (or no result if TYPE is void) with location LOC,
6124 simplifying it first if possible. Returns the built
6125 expression value (or NULL_TREE if TYPE is void) and appends
6126 statements possibly defining it to SEQ. */
6128 tree
6129 gimple_build (gimple_seq *seq, location_t loc,
6130 enum built_in_function fn, tree type,
6131 tree arg0, tree arg1, tree arg2)
6133 tree res = gimple_simplify (fn, type, arg0, arg1, arg2,
6134 seq, gimple_build_valueize);
6135 if (!res)
6137 tree decl = builtin_decl_implicit (fn);
6138 gimple *stmt = gimple_build_call (decl, 3, arg0, arg1, arg2);
6139 if (!VOID_TYPE_P (type))
6141 if (gimple_in_ssa_p (cfun))
6142 res = make_ssa_name (type);
6143 else
6144 res = create_tmp_reg (type);
6145 gimple_call_set_lhs (stmt, res);
6147 gimple_set_location (stmt, loc);
6148 gimple_seq_add_stmt_without_update (seq, stmt);
6150 return res;
6153 /* Build the conversion (TYPE) OP with a result of type TYPE
6154 with location LOC if such conversion is neccesary in GIMPLE,
6155 simplifying it first.
6156 Returns the built expression value and appends
6157 statements possibly defining it to SEQ. */
6159 tree
6160 gimple_convert (gimple_seq *seq, location_t loc, tree type, tree op)
6162 if (useless_type_conversion_p (type, TREE_TYPE (op)))
6163 return op;
6164 return gimple_build (seq, loc, NOP_EXPR, type, op);
6167 /* Build the conversion (ptrofftype) OP with a result of a type
6168 compatible with ptrofftype with location LOC if such conversion
6169 is neccesary in GIMPLE, simplifying it first.
6170 Returns the built expression value and appends
6171 statements possibly defining it to SEQ. */
6173 tree
6174 gimple_convert_to_ptrofftype (gimple_seq *seq, location_t loc, tree op)
6176 if (ptrofftype_p (TREE_TYPE (op)))
6177 return op;
6178 return gimple_convert (seq, loc, sizetype, op);
6181 /* Return true if the result of assignment STMT is known to be non-negative.
6182 If the return value is based on the assumption that signed overflow is
6183 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
6184 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
6186 static bool
6187 gimple_assign_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
6188 int depth)
6190 enum tree_code code = gimple_assign_rhs_code (stmt);
6191 switch (get_gimple_rhs_class (code))
6193 case GIMPLE_UNARY_RHS:
6194 return tree_unary_nonnegative_warnv_p (gimple_assign_rhs_code (stmt),
6195 gimple_expr_type (stmt),
6196 gimple_assign_rhs1 (stmt),
6197 strict_overflow_p, depth);
6198 case GIMPLE_BINARY_RHS:
6199 return tree_binary_nonnegative_warnv_p (gimple_assign_rhs_code (stmt),
6200 gimple_expr_type (stmt),
6201 gimple_assign_rhs1 (stmt),
6202 gimple_assign_rhs2 (stmt),
6203 strict_overflow_p, depth);
6204 case GIMPLE_TERNARY_RHS:
6205 return false;
6206 case GIMPLE_SINGLE_RHS:
6207 return tree_single_nonnegative_warnv_p (gimple_assign_rhs1 (stmt),
6208 strict_overflow_p, depth);
6209 case GIMPLE_INVALID_RHS:
6210 break;
6212 gcc_unreachable ();
6215 /* Return true if return value of call STMT is known to be non-negative.
6216 If the return value is based on the assumption that signed overflow is
6217 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
6218 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
6220 static bool
6221 gimple_call_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
6222 int depth)
6224 tree arg0 = gimple_call_num_args (stmt) > 0 ?
6225 gimple_call_arg (stmt, 0) : NULL_TREE;
6226 tree arg1 = gimple_call_num_args (stmt) > 1 ?
6227 gimple_call_arg (stmt, 1) : NULL_TREE;
6229 return tree_call_nonnegative_warnv_p (gimple_expr_type (stmt),
6230 gimple_call_combined_fn (stmt),
6231 arg0,
6232 arg1,
6233 strict_overflow_p, depth);
6236 /* Return true if return value of call STMT is known to be non-negative.
6237 If the return value is based on the assumption that signed overflow is
6238 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
6239 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
6241 static bool
6242 gimple_phi_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
6243 int depth)
6245 for (unsigned i = 0; i < gimple_phi_num_args (stmt); ++i)
6247 tree arg = gimple_phi_arg_def (stmt, i);
6248 if (!tree_single_nonnegative_warnv_p (arg, strict_overflow_p, depth + 1))
6249 return false;
6251 return true;
6254 /* Return true if STMT is known to compute a non-negative value.
6255 If the return value is based on the assumption that signed overflow is
6256 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
6257 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
6259 bool
6260 gimple_stmt_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
6261 int depth)
6263 switch (gimple_code (stmt))
6265 case GIMPLE_ASSIGN:
6266 return gimple_assign_nonnegative_warnv_p (stmt, strict_overflow_p,
6267 depth);
6268 case GIMPLE_CALL:
6269 return gimple_call_nonnegative_warnv_p (stmt, strict_overflow_p,
6270 depth);
6271 case GIMPLE_PHI:
6272 return gimple_phi_nonnegative_warnv_p (stmt, strict_overflow_p,
6273 depth);
6274 default:
6275 return false;
6279 /* Return true if the floating-point value computed by assignment STMT
6280 is known to have an integer value. We also allow +Inf, -Inf and NaN
6281 to be considered integer values. Return false for signaling NaN.
6283 DEPTH is the current nesting depth of the query. */
6285 static bool
6286 gimple_assign_integer_valued_real_p (gimple *stmt, int depth)
6288 enum tree_code code = gimple_assign_rhs_code (stmt);
6289 switch (get_gimple_rhs_class (code))
6291 case GIMPLE_UNARY_RHS:
6292 return integer_valued_real_unary_p (gimple_assign_rhs_code (stmt),
6293 gimple_assign_rhs1 (stmt), depth);
6294 case GIMPLE_BINARY_RHS:
6295 return integer_valued_real_binary_p (gimple_assign_rhs_code (stmt),
6296 gimple_assign_rhs1 (stmt),
6297 gimple_assign_rhs2 (stmt), depth);
6298 case GIMPLE_TERNARY_RHS:
6299 return false;
6300 case GIMPLE_SINGLE_RHS:
6301 return integer_valued_real_single_p (gimple_assign_rhs1 (stmt), depth);
6302 case GIMPLE_INVALID_RHS:
6303 break;
6305 gcc_unreachable ();
6308 /* Return true if the floating-point value computed by call STMT is known
6309 to have an integer value. We also allow +Inf, -Inf and NaN to be
6310 considered integer values. Return false for signaling NaN.
6312 DEPTH is the current nesting depth of the query. */
6314 static bool
6315 gimple_call_integer_valued_real_p (gimple *stmt, int depth)
6317 tree arg0 = (gimple_call_num_args (stmt) > 0
6318 ? gimple_call_arg (stmt, 0)
6319 : NULL_TREE);
6320 tree arg1 = (gimple_call_num_args (stmt) > 1
6321 ? gimple_call_arg (stmt, 1)
6322 : NULL_TREE);
6323 return integer_valued_real_call_p (gimple_call_combined_fn (stmt),
6324 arg0, arg1, depth);
6327 /* Return true if the floating-point result of phi STMT is known to have
6328 an integer value. We also allow +Inf, -Inf and NaN to be considered
6329 integer values. Return false for signaling NaN.
6331 DEPTH is the current nesting depth of the query. */
6333 static bool
6334 gimple_phi_integer_valued_real_p (gimple *stmt, int depth)
6336 for (unsigned i = 0; i < gimple_phi_num_args (stmt); ++i)
6338 tree arg = gimple_phi_arg_def (stmt, i);
6339 if (!integer_valued_real_single_p (arg, depth + 1))
6340 return false;
6342 return true;
6345 /* Return true if the floating-point value computed by STMT is known
6346 to have an integer value. We also allow +Inf, -Inf and NaN to be
6347 considered integer values. Return false for signaling NaN.
6349 DEPTH is the current nesting depth of the query. */
6351 bool
6352 gimple_stmt_integer_valued_real_p (gimple *stmt, int depth)
6354 switch (gimple_code (stmt))
6356 case GIMPLE_ASSIGN:
6357 return gimple_assign_integer_valued_real_p (stmt, depth);
6358 case GIMPLE_CALL:
6359 return gimple_call_integer_valued_real_p (stmt, depth);
6360 case GIMPLE_PHI:
6361 return gimple_phi_integer_valued_real_p (stmt, depth);
6362 default:
6363 return false;