]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/gimple-fold.c
scanner.c (skip_free_comments, [...]): Use gfc_warning_now instead of ..._now_1.
[thirdparty/gcc.git] / gcc / gimple-fold.c
CommitLineData
cbdd87d4 1/* Statement simplification on GIMPLE.
23a5b65a 2 Copyright (C) 2010-2014 Free Software Foundation, Inc.
cbdd87d4
RG
3 Split out from tree-ssa-ccp.c.
4
5This file is part of GCC.
6
7GCC is free software; you can redistribute it and/or modify it
8under the terms of the GNU General Public License as published by the
9Free Software Foundation; either version 3, or (at your option) any
10later version.
11
12GCC is distributed in the hope that it will be useful, but WITHOUT
13ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15for more details.
16
17You should have received a copy of the GNU General Public License
18along with GCC; see the file COPYING3. If not see
19<http://www.gnu.org/licenses/>. */
20
21#include "config.h"
22#include "system.h"
23#include "coretypes.h"
24#include "tm.h"
25#include "tree.h"
d8a2d370
DN
26#include "stringpool.h"
27#include "expr.h"
28#include "stmt.h"
29#include "stor-layout.h"
cbdd87d4 30#include "flags.h"
83685514
AM
31#include "hashtab.h"
32#include "hash-set.h"
33#include "vec.h"
34#include "machmode.h"
35#include "hard-reg-set.h"
36#include "input.h"
cbdd87d4 37#include "function.h"
7ee2468b 38#include "dumpfile.h"
442b4905 39#include "bitmap.h"
60393bbc
AM
40#include "predict.h"
41#include "dominance.h"
2fb9a547
AM
42#include "basic-block.h"
43#include "tree-ssa-alias.h"
44#include "internal-fn.h"
45#include "gimple-fold.h"
46#include "gimple-expr.h"
47#include "is-a.h"
18f429e2 48#include "gimple.h"
45b0be94 49#include "gimplify.h"
5be5c238 50#include "gimple-iterator.h"
442b4905
AM
51#include "gimple-ssa.h"
52#include "tree-ssanames.h"
53#include "tree-into-ssa.h"
54#include "tree-dfa.h"
7a300452 55#include "tree-ssa.h"
cbdd87d4 56#include "tree-ssa-propagate.h"
cbdd87d4 57#include "target.h"
c582198b
AM
58#include "hash-map.h"
59#include "plugin-api.h"
60#include "ipa-ref.h"
61#include "cgraph.h"
450ad0cd
JH
62#include "ipa-utils.h"
63#include "gimple-pretty-print.h"
4484a35a 64#include "tree-ssa-address.h"
862d0b35 65#include "langhooks.h"
19e51b40 66#include "gimplify-me.h"
2b5f0895 67#include "dbgcnt.h"
9b2b7279 68#include "builtins.h"
fef5a0d9 69#include "output.h"
e0ee10ed
RB
70#include "tree-eh.h"
71#include "gimple-match.h"
45cc9f96
RB
72#include "tree-phinodes.h"
73#include "ssa-iterators.h"
cbdd87d4 74
b3b9f3d0 75/* Return true when DECL can be referenced from current unit.
c44c2088
JH
76 FROM_DECL (if non-null) specify constructor of variable DECL was taken from.
77 We can get declarations that are not possible to reference for various
78 reasons:
1389294c 79
1389294c
JH
80 1) When analyzing C++ virtual tables.
81 C++ virtual tables do have known constructors even
82 when they are keyed to other compilation unit.
83 Those tables can contain pointers to methods and vars
84 in other units. Those methods have both STATIC and EXTERNAL
85 set.
86 2) In WHOPR mode devirtualization might lead to reference
87 to method that was partitioned elsehwere.
88 In this case we have static VAR_DECL or FUNCTION_DECL
89 that has no corresponding callgraph/varpool node
b3b9f3d0
JH
90 declaring the body.
91 3) COMDAT functions referred by external vtables that
3e89949e 92 we devirtualize only during final compilation stage.
b3b9f3d0
JH
93 At this time we already decided that we will not output
94 the function body and thus we can't reference the symbol
95 directly. */
96
1389294c 97static bool
c44c2088 98can_refer_decl_in_current_unit_p (tree decl, tree from_decl)
1389294c 99{
2c8326a5 100 varpool_node *vnode;
1389294c 101 struct cgraph_node *node;
5e20cdc9 102 symtab_node *snode;
c44c2088 103
00de328a 104 if (DECL_ABSTRACT_P (decl))
1632a686
JH
105 return false;
106
107 /* We are concerned only about static/external vars and functions. */
108 if ((!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
109 || (TREE_CODE (decl) != VAR_DECL && TREE_CODE (decl) != FUNCTION_DECL))
110 return true;
111
112 /* Static objects can be referred only if they was not optimized out yet. */
113 if (!TREE_PUBLIC (decl) && !DECL_EXTERNAL (decl))
114 {
3aaf0529
JH
115 /* Before we start optimizing unreachable code we can be sure all
116 static objects are defined. */
3dafb85c 117 if (symtab->function_flags_ready)
3aaf0529 118 return true;
d52f5295 119 snode = symtab_node::get (decl);
3aaf0529 120 if (!snode || !snode->definition)
1632a686 121 return false;
7de90a6c 122 node = dyn_cast <cgraph_node *> (snode);
1632a686
JH
123 return !node || !node->global.inlined_to;
124 }
125
6da8be89 126 /* We will later output the initializer, so we can refer to it.
c44c2088 127 So we are concerned only when DECL comes from initializer of
3aaf0529 128 external var or var that has been optimized out. */
c44c2088
JH
129 if (!from_decl
130 || TREE_CODE (from_decl) != VAR_DECL
3aaf0529 131 || (!DECL_EXTERNAL (from_decl)
9041d2e6 132 && (vnode = varpool_node::get (from_decl)) != NULL
3aaf0529 133 && vnode->definition)
6da8be89 134 || (flag_ltrans
9041d2e6 135 && (vnode = varpool_node::get (from_decl)) != NULL
6adda80b 136 && vnode->in_other_partition))
c44c2088 137 return true;
c44c2088
JH
138 /* We are folding reference from external vtable. The vtable may reffer
139 to a symbol keyed to other compilation unit. The other compilation
140 unit may be in separate DSO and the symbol may be hidden. */
141 if (DECL_VISIBILITY_SPECIFIED (decl)
142 && DECL_EXTERNAL (decl)
a33a931b 143 && DECL_VISIBILITY (decl) != VISIBILITY_DEFAULT
d52f5295 144 && (!(snode = symtab_node::get (decl)) || !snode->in_other_partition))
c44c2088 145 return false;
b3b9f3d0
JH
146 /* When function is public, we always can introduce new reference.
147 Exception are the COMDAT functions where introducing a direct
148 reference imply need to include function body in the curren tunit. */
149 if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl))
150 return true;
3aaf0529
JH
151 /* We have COMDAT. We are going to check if we still have definition
152 or if the definition is going to be output in other partition.
153 Bypass this when gimplifying; all needed functions will be produced.
c44c2088
JH
154
155 As observed in PR20991 for already optimized out comdat virtual functions
073a8998 156 it may be tempting to not necessarily give up because the copy will be
c44c2088
JH
157 output elsewhere when corresponding vtable is output.
158 This is however not possible - ABI specify that COMDATs are output in
159 units where they are used and when the other unit was compiled with LTO
160 it is possible that vtable was kept public while the function itself
161 was privatized. */
3dafb85c 162 if (!symtab->function_flags_ready)
b3b9f3d0 163 return true;
c44c2088 164
d52f5295 165 snode = symtab_node::get (decl);
3aaf0529
JH
166 if (!snode
167 || ((!snode->definition || DECL_EXTERNAL (decl))
168 && (!snode->in_other_partition
169 || (!snode->forced_by_abi && !snode->force_output))))
170 return false;
171 node = dyn_cast <cgraph_node *> (snode);
172 return !node || !node->global.inlined_to;
1389294c
JH
173}
174
0038d4e0 175/* CVAL is value taken from DECL_INITIAL of variable. Try to transform it into
c44c2088
JH
176 acceptable form for is_gimple_min_invariant.
177 FROM_DECL (if non-NULL) specify variable whose constructor contains CVAL. */
17f39a39
JH
178
179tree
c44c2088 180canonicalize_constructor_val (tree cval, tree from_decl)
17f39a39 181{
50619002
EB
182 tree orig_cval = cval;
183 STRIP_NOPS (cval);
315f5f1b
RG
184 if (TREE_CODE (cval) == POINTER_PLUS_EXPR
185 && TREE_CODE (TREE_OPERAND (cval, 1)) == INTEGER_CST)
17f39a39 186 {
315f5f1b
RG
187 tree ptr = TREE_OPERAND (cval, 0);
188 if (is_gimple_min_invariant (ptr))
189 cval = build1_loc (EXPR_LOCATION (cval),
190 ADDR_EXPR, TREE_TYPE (ptr),
191 fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (ptr)),
192 ptr,
193 fold_convert (ptr_type_node,
194 TREE_OPERAND (cval, 1))));
17f39a39
JH
195 }
196 if (TREE_CODE (cval) == ADDR_EXPR)
197 {
5a27a197
RG
198 tree base = NULL_TREE;
199 if (TREE_CODE (TREE_OPERAND (cval, 0)) == COMPOUND_LITERAL_EXPR)
ca5f4331
MM
200 {
201 base = COMPOUND_LITERAL_EXPR_DECL (TREE_OPERAND (cval, 0));
202 if (base)
203 TREE_OPERAND (cval, 0) = base;
204 }
5a27a197
RG
205 else
206 base = get_base_address (TREE_OPERAND (cval, 0));
7501ca28
RG
207 if (!base)
208 return NULL_TREE;
b3b9f3d0 209
7501ca28
RG
210 if ((TREE_CODE (base) == VAR_DECL
211 || TREE_CODE (base) == FUNCTION_DECL)
c44c2088 212 && !can_refer_decl_in_current_unit_p (base, from_decl))
1389294c 213 return NULL_TREE;
7501ca28 214 if (TREE_CODE (base) == VAR_DECL)
46eb666a 215 TREE_ADDRESSABLE (base) = 1;
7501ca28
RG
216 else if (TREE_CODE (base) == FUNCTION_DECL)
217 {
218 /* Make sure we create a cgraph node for functions we'll reference.
219 They can be non-existent if the reference comes from an entry
220 of an external vtable for example. */
d52f5295 221 cgraph_node::get_create (base);
7501ca28 222 }
0038d4e0 223 /* Fixup types in global initializers. */
73aef89e
RG
224 if (TREE_TYPE (TREE_TYPE (cval)) != TREE_TYPE (TREE_OPERAND (cval, 0)))
225 cval = build_fold_addr_expr (TREE_OPERAND (cval, 0));
50619002
EB
226
227 if (!useless_type_conversion_p (TREE_TYPE (orig_cval), TREE_TYPE (cval)))
228 cval = fold_convert (TREE_TYPE (orig_cval), cval);
229 return cval;
17f39a39 230 }
846abd0d
RB
231 if (TREE_OVERFLOW_P (cval))
232 return drop_tree_overflow (cval);
50619002 233 return orig_cval;
17f39a39 234}
cbdd87d4
RG
235
236/* If SYM is a constant variable with known value, return the value.
237 NULL_TREE is returned otherwise. */
238
239tree
240get_symbol_constant_value (tree sym)
241{
6a6dac52
JH
242 tree val = ctor_for_folding (sym);
243 if (val != error_mark_node)
cbdd87d4 244 {
cbdd87d4
RG
245 if (val)
246 {
9d60be38 247 val = canonicalize_constructor_val (unshare_expr (val), sym);
1389294c 248 if (val && is_gimple_min_invariant (val))
17f39a39 249 return val;
1389294c
JH
250 else
251 return NULL_TREE;
cbdd87d4
RG
252 }
253 /* Variables declared 'const' without an initializer
254 have zero as the initializer if they may not be
255 overridden at link or run time. */
256 if (!val
b8a8c472 257 && is_gimple_reg_type (TREE_TYPE (sym)))
e8160c9a 258 return build_zero_cst (TREE_TYPE (sym));
cbdd87d4
RG
259 }
260
261 return NULL_TREE;
262}
263
264
cbdd87d4
RG
265
266/* Subroutine of fold_stmt. We perform several simplifications of the
267 memory reference tree EXPR and make sure to re-gimplify them properly
268 after propagation of constant addresses. IS_LHS is true if the
269 reference is supposed to be an lvalue. */
270
271static tree
272maybe_fold_reference (tree expr, bool is_lhs)
273{
17f39a39 274 tree result;
cbdd87d4 275
f0eddb90
RG
276 if ((TREE_CODE (expr) == VIEW_CONVERT_EXPR
277 || TREE_CODE (expr) == REALPART_EXPR
278 || TREE_CODE (expr) == IMAGPART_EXPR)
279 && CONSTANT_CLASS_P (TREE_OPERAND (expr, 0)))
280 return fold_unary_loc (EXPR_LOCATION (expr),
281 TREE_CODE (expr),
282 TREE_TYPE (expr),
283 TREE_OPERAND (expr, 0));
284 else if (TREE_CODE (expr) == BIT_FIELD_REF
285 && CONSTANT_CLASS_P (TREE_OPERAND (expr, 0)))
286 return fold_ternary_loc (EXPR_LOCATION (expr),
287 TREE_CODE (expr),
288 TREE_TYPE (expr),
289 TREE_OPERAND (expr, 0),
290 TREE_OPERAND (expr, 1),
291 TREE_OPERAND (expr, 2));
292
f0eddb90
RG
293 if (!is_lhs
294 && (result = fold_const_aggregate_ref (expr))
295 && is_gimple_min_invariant (result))
296 return result;
cbdd87d4 297
cbdd87d4
RG
298 return NULL_TREE;
299}
300
301
302/* Attempt to fold an assignment statement pointed-to by SI. Returns a
303 replacement rhs for the statement or NULL_TREE if no simplification
304 could be made. It is assumed that the operands have been previously
305 folded. */
306
307static tree
308fold_gimple_assign (gimple_stmt_iterator *si)
309{
310 gimple stmt = gsi_stmt (*si);
311 enum tree_code subcode = gimple_assign_rhs_code (stmt);
312 location_t loc = gimple_location (stmt);
313
314 tree result = NULL_TREE;
315
316 switch (get_gimple_rhs_class (subcode))
317 {
318 case GIMPLE_SINGLE_RHS:
319 {
320 tree rhs = gimple_assign_rhs1 (stmt);
321
8c00ba08
JW
322 if (TREE_CLOBBER_P (rhs))
323 return NULL_TREE;
324
4e71066d 325 if (REFERENCE_CLASS_P (rhs))
cbdd87d4
RG
326 return maybe_fold_reference (rhs, false);
327
bdf37f7a
JH
328 else if (TREE_CODE (rhs) == OBJ_TYPE_REF)
329 {
330 tree val = OBJ_TYPE_REF_EXPR (rhs);
331 if (is_gimple_min_invariant (val))
332 return val;
f8a39967 333 else if (flag_devirtualize && virtual_method_call_p (rhs))
bdf37f7a
JH
334 {
335 bool final;
336 vec <cgraph_node *>targets
f8a39967 337 = possible_polymorphic_call_targets (rhs, stmt, &final);
2b5f0895 338 if (final && targets.length () <= 1 && dbg_cnt (devirt))
bdf37f7a 339 {
2b5f0895
XDL
340 if (dump_enabled_p ())
341 {
807b7d62 342 location_t loc = gimple_location_safe (stmt);
2b5f0895
XDL
343 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, loc,
344 "resolving virtual function address "
345 "reference to function %s\n",
346 targets.length () == 1
347 ? targets[0]->name ()
3ef276e4 348 : "NULL");
2b5f0895 349 }
3ef276e4
RB
350 if (targets.length () == 1)
351 {
352 val = fold_convert (TREE_TYPE (val),
353 build_fold_addr_expr_loc
354 (loc, targets[0]->decl));
355 STRIP_USELESS_TYPE_CONVERSION (val);
356 }
357 else
358 /* We can not use __builtin_unreachable here because it
359 can not have address taken. */
360 val = build_int_cst (TREE_TYPE (val), 0);
bdf37f7a
JH
361 return val;
362 }
363 }
364
365 }
cbdd87d4
RG
366 else if (TREE_CODE (rhs) == ADDR_EXPR)
367 {
70f34814
RG
368 tree ref = TREE_OPERAND (rhs, 0);
369 tree tem = maybe_fold_reference (ref, true);
370 if (tem
371 && TREE_CODE (tem) == MEM_REF
372 && integer_zerop (TREE_OPERAND (tem, 1)))
373 result = fold_convert (TREE_TYPE (rhs), TREE_OPERAND (tem, 0));
374 else if (tem)
cbdd87d4
RG
375 result = fold_convert (TREE_TYPE (rhs),
376 build_fold_addr_expr_loc (loc, tem));
70f34814
RG
377 else if (TREE_CODE (ref) == MEM_REF
378 && integer_zerop (TREE_OPERAND (ref, 1)))
379 result = fold_convert (TREE_TYPE (rhs), TREE_OPERAND (ref, 0));
cbdd87d4
RG
380 }
381
382 else if (TREE_CODE (rhs) == CONSTRUCTOR
383 && TREE_CODE (TREE_TYPE (rhs)) == VECTOR_TYPE
384 && (CONSTRUCTOR_NELTS (rhs)
385 == TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs))))
386 {
387 /* Fold a constant vector CONSTRUCTOR to VECTOR_CST. */
388 unsigned i;
389 tree val;
390
391 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), i, val)
392 if (TREE_CODE (val) != INTEGER_CST
393 && TREE_CODE (val) != REAL_CST
394 && TREE_CODE (val) != FIXED_CST)
395 return NULL_TREE;
396
397 return build_vector_from_ctor (TREE_TYPE (rhs),
398 CONSTRUCTOR_ELTS (rhs));
399 }
400
401 else if (DECL_P (rhs))
9d60be38 402 return get_symbol_constant_value (rhs);
cbdd87d4
RG
403
404 /* If we couldn't fold the RHS, hand over to the generic
405 fold routines. */
406 if (result == NULL_TREE)
407 result = fold (rhs);
408
409 /* Strip away useless type conversions. Both the NON_LVALUE_EXPR
410 that may have been added by fold, and "useless" type
411 conversions that might now be apparent due to propagation. */
412 STRIP_USELESS_TYPE_CONVERSION (result);
413
414 if (result != rhs && valid_gimple_rhs_p (result))
415 return result;
416
417 return NULL_TREE;
418 }
419 break;
420
421 case GIMPLE_UNARY_RHS:
cbdd87d4
RG
422 break;
423
424 case GIMPLE_BINARY_RHS:
9b80d091
KT
425 /* Try to canonicalize for boolean-typed X the comparisons
426 X == 0, X == 1, X != 0, and X != 1. */
315f5f1b
RG
427 if (gimple_assign_rhs_code (stmt) == EQ_EXPR
428 || gimple_assign_rhs_code (stmt) == NE_EXPR)
9b80d091
KT
429 {
430 tree lhs = gimple_assign_lhs (stmt);
431 tree op1 = gimple_assign_rhs1 (stmt);
432 tree op2 = gimple_assign_rhs2 (stmt);
433 tree type = TREE_TYPE (op1);
434
435 /* Check whether the comparison operands are of the same boolean
436 type as the result type is.
437 Check that second operand is an integer-constant with value
438 one or zero. */
439 if (TREE_CODE (op2) == INTEGER_CST
440 && (integer_zerop (op2) || integer_onep (op2))
441 && useless_type_conversion_p (TREE_TYPE (lhs), type))
442 {
443 enum tree_code cmp_code = gimple_assign_rhs_code (stmt);
444 bool is_logical_not = false;
445
446 /* X == 0 and X != 1 is a logical-not.of X
447 X == 1 and X != 0 is X */
448 if ((cmp_code == EQ_EXPR && integer_zerop (op2))
449 || (cmp_code == NE_EXPR && integer_onep (op2)))
450 is_logical_not = true;
451
452 if (is_logical_not == false)
453 result = op1;
454 /* Only for one-bit precision typed X the transformation
455 !X -> ~X is valied. */
456 else if (TYPE_PRECISION (type) == 1)
457 result = build1_loc (gimple_location (stmt), BIT_NOT_EXPR,
458 type, op1);
459 /* Otherwise we use !X -> X ^ 1. */
460 else
461 result = build2_loc (gimple_location (stmt), BIT_XOR_EXPR,
462 type, op1, build_int_cst (type, 1));
463
464 }
465 }
cbdd87d4
RG
466
467 if (!result)
468 result = fold_binary_loc (loc, subcode,
5fbcc0ed
RG
469 TREE_TYPE (gimple_assign_lhs (stmt)),
470 gimple_assign_rhs1 (stmt),
471 gimple_assign_rhs2 (stmt));
cbdd87d4
RG
472
473 if (result)
474 {
475 STRIP_USELESS_TYPE_CONVERSION (result);
476 if (valid_gimple_rhs_p (result))
477 return result;
cbdd87d4
RG
478 }
479 break;
480
0354c0c7 481 case GIMPLE_TERNARY_RHS:
4e71066d
RG
482 /* Try to fold a conditional expression. */
483 if (gimple_assign_rhs_code (stmt) == COND_EXPR)
484 {
485 tree op0 = gimple_assign_rhs1 (stmt);
486 tree tem;
487 bool set = false;
488 location_t cond_loc = gimple_location (stmt);
489
490 if (COMPARISON_CLASS_P (op0))
491 {
492 fold_defer_overflow_warnings ();
493 tem = fold_binary_loc (cond_loc,
494 TREE_CODE (op0), TREE_TYPE (op0),
495 TREE_OPERAND (op0, 0),
496 TREE_OPERAND (op0, 1));
497 /* This is actually a conditional expression, not a GIMPLE
498 conditional statement, however, the valid_gimple_rhs_p
499 test still applies. */
500 set = (tem && is_gimple_condexpr (tem)
501 && valid_gimple_rhs_p (tem));
502 fold_undefer_overflow_warnings (set, stmt, 0);
503 }
504 else if (is_gimple_min_invariant (op0))
505 {
506 tem = op0;
507 set = true;
508 }
509 else
510 return NULL_TREE;
511
512 if (set)
513 result = fold_build3_loc (cond_loc, COND_EXPR,
514 TREE_TYPE (gimple_assign_lhs (stmt)), tem,
515 gimple_assign_rhs2 (stmt),
516 gimple_assign_rhs3 (stmt));
517 }
518
519 if (!result)
520 result = fold_ternary_loc (loc, subcode,
521 TREE_TYPE (gimple_assign_lhs (stmt)),
522 gimple_assign_rhs1 (stmt),
523 gimple_assign_rhs2 (stmt),
524 gimple_assign_rhs3 (stmt));
0354c0c7
BS
525
526 if (result)
527 {
528 STRIP_USELESS_TYPE_CONVERSION (result);
529 if (valid_gimple_rhs_p (result))
530 return result;
0354c0c7
BS
531 }
532 break;
533
cbdd87d4
RG
534 case GIMPLE_INVALID_RHS:
535 gcc_unreachable ();
536 }
537
538 return NULL_TREE;
539}
540
541/* Attempt to fold a conditional statement. Return true if any changes were
542 made. We only attempt to fold the condition expression, and do not perform
543 any transformation that would require alteration of the cfg. It is
544 assumed that the operands have been previously folded. */
545
546static bool
538dd0b7 547fold_gimple_cond (gcond *stmt)
cbdd87d4
RG
548{
549 tree result = fold_binary_loc (gimple_location (stmt),
550 gimple_cond_code (stmt),
551 boolean_type_node,
552 gimple_cond_lhs (stmt),
553 gimple_cond_rhs (stmt));
554
555 if (result)
556 {
557 STRIP_USELESS_TYPE_CONVERSION (result);
558 if (is_gimple_condexpr (result) && valid_gimple_rhs_p (result))
559 {
560 gimple_cond_set_condition_from_tree (stmt, result);
561 return true;
562 }
563 }
564
565 return false;
566}
567
fef5a0d9
RB
568
569/* Replace a statement at *SI_P with a sequence of statements in STMTS,
570 adjusting the replacement stmts location and virtual operands.
571 If the statement has a lhs the last stmt in the sequence is expected
572 to assign to that lhs. */
573
574static void
575gsi_replace_with_seq_vops (gimple_stmt_iterator *si_p, gimple_seq stmts)
576{
577 gimple stmt = gsi_stmt (*si_p);
578
579 if (gimple_has_location (stmt))
580 annotate_all_with_location (stmts, gimple_location (stmt));
581
582 /* First iterate over the replacement statements backward, assigning
583 virtual operands to their defining statements. */
584 gimple laststore = NULL;
585 for (gimple_stmt_iterator i = gsi_last (stmts);
586 !gsi_end_p (i); gsi_prev (&i))
587 {
588 gimple new_stmt = gsi_stmt (i);
589 if ((gimple_assign_single_p (new_stmt)
590 && !is_gimple_reg (gimple_assign_lhs (new_stmt)))
591 || (is_gimple_call (new_stmt)
592 && (gimple_call_flags (new_stmt)
593 & (ECF_NOVOPS | ECF_PURE | ECF_CONST | ECF_NORETURN)) == 0))
594 {
595 tree vdef;
596 if (!laststore)
597 vdef = gimple_vdef (stmt);
598 else
599 vdef = make_ssa_name (gimple_vop (cfun), new_stmt);
600 gimple_set_vdef (new_stmt, vdef);
601 if (vdef && TREE_CODE (vdef) == SSA_NAME)
602 SSA_NAME_DEF_STMT (vdef) = new_stmt;
603 laststore = new_stmt;
604 }
605 }
606
607 /* Second iterate over the statements forward, assigning virtual
608 operands to their uses. */
609 tree reaching_vuse = gimple_vuse (stmt);
610 for (gimple_stmt_iterator i = gsi_start (stmts);
611 !gsi_end_p (i); gsi_next (&i))
612 {
613 gimple new_stmt = gsi_stmt (i);
614 /* If the new statement possibly has a VUSE, update it with exact SSA
615 name we know will reach this one. */
616 if (gimple_has_mem_ops (new_stmt))
617 gimple_set_vuse (new_stmt, reaching_vuse);
618 gimple_set_modified (new_stmt, true);
619 if (gimple_vdef (new_stmt))
620 reaching_vuse = gimple_vdef (new_stmt);
621 }
622
623 /* If the new sequence does not do a store release the virtual
624 definition of the original statement. */
625 if (reaching_vuse
626 && reaching_vuse == gimple_vuse (stmt))
627 {
628 tree vdef = gimple_vdef (stmt);
629 if (vdef
630 && TREE_CODE (vdef) == SSA_NAME)
631 {
632 unlink_stmt_vdef (stmt);
633 release_ssa_name (vdef);
634 }
635 }
636
637 /* Finally replace the original statement with the sequence. */
638 gsi_replace_with_seq (si_p, stmts, false);
639}
640
cbdd87d4
RG
641/* Convert EXPR into a GIMPLE value suitable for substitution on the
642 RHS of an assignment. Insert the necessary statements before
643 iterator *SI_P. The statement at *SI_P, which must be a GIMPLE_CALL
644 is replaced. If the call is expected to produces a result, then it
645 is replaced by an assignment of the new RHS to the result variable.
646 If the result is to be ignored, then the call is replaced by a
fe2ef088
MM
647 GIMPLE_NOP. A proper VDEF chain is retained by making the first
648 VUSE and the last VDEF of the whole sequence be the same as the replaced
649 statement and using new SSA names for stores in between. */
cbdd87d4
RG
650
651void
652gimplify_and_update_call_from_tree (gimple_stmt_iterator *si_p, tree expr)
653{
654 tree lhs;
cbdd87d4
RG
655 gimple stmt, new_stmt;
656 gimple_stmt_iterator i;
355a7673 657 gimple_seq stmts = NULL;
cbdd87d4
RG
658
659 stmt = gsi_stmt (*si_p);
660
661 gcc_assert (is_gimple_call (stmt));
662
45852dcc 663 push_gimplify_context (gimple_in_ssa_p (cfun));
cbdd87d4 664
e256dfce 665 lhs = gimple_call_lhs (stmt);
cbdd87d4 666 if (lhs == NULL_TREE)
6e572326
RG
667 {
668 gimplify_and_add (expr, &stmts);
669 /* We can end up with folding a memcpy of an empty class assignment
670 which gets optimized away by C++ gimplification. */
671 if (gimple_seq_empty_p (stmts))
672 {
9fdc58de 673 pop_gimplify_context (NULL);
6e572326
RG
674 if (gimple_in_ssa_p (cfun))
675 {
676 unlink_stmt_vdef (stmt);
677 release_defs (stmt);
678 }
77d19c72 679 gsi_replace (si_p, gimple_build_nop (), true);
6e572326
RG
680 return;
681 }
682 }
cbdd87d4 683 else
e256dfce
RG
684 {
685 tree tmp = get_initialized_tmp_var (expr, &stmts, NULL);
686 new_stmt = gimple_build_assign (lhs, tmp);
687 i = gsi_last (stmts);
688 gsi_insert_after_without_update (&i, new_stmt,
689 GSI_CONTINUE_LINKING);
690 }
cbdd87d4
RG
691
692 pop_gimplify_context (NULL);
693
fef5a0d9
RB
694 gsi_replace_with_seq_vops (si_p, stmts);
695}
cbdd87d4 696
fef5a0d9
RB
697
698/* Replace the call at *GSI with the gimple value VAL. */
699
700static void
701replace_call_with_value (gimple_stmt_iterator *gsi, tree val)
702{
703 gimple stmt = gsi_stmt (*gsi);
704 tree lhs = gimple_call_lhs (stmt);
705 gimple repl;
706 if (lhs)
e256dfce 707 {
fef5a0d9
RB
708 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (val)))
709 val = fold_convert (TREE_TYPE (lhs), val);
710 repl = gimple_build_assign (lhs, val);
711 }
712 else
713 repl = gimple_build_nop ();
714 tree vdef = gimple_vdef (stmt);
715 if (vdef && TREE_CODE (vdef) == SSA_NAME)
716 {
717 unlink_stmt_vdef (stmt);
718 release_ssa_name (vdef);
719 }
720 gsi_replace (gsi, repl, true);
721}
722
723/* Replace the call at *GSI with the new call REPL and fold that
724 again. */
725
726static void
727replace_call_with_call_and_fold (gimple_stmt_iterator *gsi, gimple repl)
728{
729 gimple stmt = gsi_stmt (*gsi);
730 gimple_call_set_lhs (repl, gimple_call_lhs (stmt));
731 gimple_set_location (repl, gimple_location (stmt));
732 if (gimple_vdef (stmt)
733 && TREE_CODE (gimple_vdef (stmt)) == SSA_NAME)
734 {
735 gimple_set_vdef (repl, gimple_vdef (stmt));
736 gimple_set_vuse (repl, gimple_vuse (stmt));
737 SSA_NAME_DEF_STMT (gimple_vdef (repl)) = repl;
738 }
739 gsi_replace (gsi, repl, true);
740 fold_stmt (gsi);
741}
742
743/* Return true if VAR is a VAR_DECL or a component thereof. */
744
745static bool
746var_decl_component_p (tree var)
747{
748 tree inner = var;
749 while (handled_component_p (inner))
750 inner = TREE_OPERAND (inner, 0);
751 return SSA_VAR_P (inner);
752}
753
754/* Fold function call to builtin mem{{,p}cpy,move}. Return
755 NULL_TREE if no simplification can be made.
756 If ENDP is 0, return DEST (like memcpy).
757 If ENDP is 1, return DEST+LEN (like mempcpy).
758 If ENDP is 2, return DEST+LEN-1 (like stpcpy).
759 If ENDP is 3, return DEST, additionally *SRC and *DEST may overlap
760 (memmove). */
761
762static bool
763gimple_fold_builtin_memory_op (gimple_stmt_iterator *gsi,
764 tree dest, tree src, int endp)
765{
766 gimple stmt = gsi_stmt (*gsi);
767 tree lhs = gimple_call_lhs (stmt);
768 tree len = gimple_call_arg (stmt, 2);
769 tree destvar, srcvar;
770 location_t loc = gimple_location (stmt);
771
772 /* If the LEN parameter is zero, return DEST. */
773 if (integer_zerop (len))
774 {
775 gimple repl;
776 if (gimple_call_lhs (stmt))
777 repl = gimple_build_assign (gimple_call_lhs (stmt), dest);
778 else
779 repl = gimple_build_nop ();
780 tree vdef = gimple_vdef (stmt);
781 if (vdef && TREE_CODE (vdef) == SSA_NAME)
e256dfce 782 {
fef5a0d9
RB
783 unlink_stmt_vdef (stmt);
784 release_ssa_name (vdef);
785 }
786 gsi_replace (gsi, repl, true);
787 return true;
788 }
789
790 /* If SRC and DEST are the same (and not volatile), return
791 DEST{,+LEN,+LEN-1}. */
792 if (operand_equal_p (src, dest, 0))
793 {
794 unlink_stmt_vdef (stmt);
795 if (gimple_vdef (stmt) && TREE_CODE (gimple_vdef (stmt)) == SSA_NAME)
796 release_ssa_name (gimple_vdef (stmt));
797 if (!lhs)
798 {
799 gsi_replace (gsi, gimple_build_nop (), true);
800 return true;
801 }
802 goto done;
803 }
804 else
805 {
806 tree srctype, desttype;
807 unsigned int src_align, dest_align;
808 tree off0;
809
810 /* Build accesses at offset zero with a ref-all character type. */
811 off0 = build_int_cst (build_pointer_type_for_mode (char_type_node,
812 ptr_mode, true), 0);
813
814 /* If we can perform the copy efficiently with first doing all loads
815 and then all stores inline it that way. Currently efficiently
816 means that we can load all the memory into a single integer
817 register which is what MOVE_MAX gives us. */
818 src_align = get_pointer_alignment (src);
819 dest_align = get_pointer_alignment (dest);
820 if (tree_fits_uhwi_p (len)
821 && compare_tree_int (len, MOVE_MAX) <= 0
822 /* ??? Don't transform copies from strings with known length this
823 confuses the tree-ssa-strlen.c. This doesn't handle
824 the case in gcc.dg/strlenopt-8.c which is XFAILed for that
825 reason. */
826 && !c_strlen (src, 2))
827 {
828 unsigned ilen = tree_to_uhwi (len);
829 if (exact_log2 (ilen) != -1)
830 {
831 tree type = lang_hooks.types.type_for_size (ilen * 8, 1);
832 if (type
833 && TYPE_MODE (type) != BLKmode
834 && (GET_MODE_SIZE (TYPE_MODE (type)) * BITS_PER_UNIT
835 == ilen * 8)
836 /* If the destination pointer is not aligned we must be able
837 to emit an unaligned store. */
838 && (dest_align >= GET_MODE_ALIGNMENT (TYPE_MODE (type))
839 || !SLOW_UNALIGNED_ACCESS (TYPE_MODE (type), dest_align)))
840 {
841 tree srctype = type;
842 tree desttype = type;
843 if (src_align < GET_MODE_ALIGNMENT (TYPE_MODE (type)))
844 srctype = build_aligned_type (type, src_align);
845 tree srcmem = fold_build2 (MEM_REF, srctype, src, off0);
846 tree tem = fold_const_aggregate_ref (srcmem);
847 if (tem)
848 srcmem = tem;
849 else if (src_align < GET_MODE_ALIGNMENT (TYPE_MODE (type))
850 && SLOW_UNALIGNED_ACCESS (TYPE_MODE (type),
851 src_align))
852 srcmem = NULL_TREE;
853 if (srcmem)
854 {
855 gimple new_stmt;
856 if (is_gimple_reg_type (TREE_TYPE (srcmem)))
857 {
858 new_stmt = gimple_build_assign (NULL_TREE, srcmem);
859 if (gimple_in_ssa_p (cfun))
860 srcmem = make_ssa_name (TREE_TYPE (srcmem),
861 new_stmt);
862 else
863 srcmem = create_tmp_reg (TREE_TYPE (srcmem),
864 NULL);
865 gimple_assign_set_lhs (new_stmt, srcmem);
866 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
867 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
868 }
869 if (dest_align < GET_MODE_ALIGNMENT (TYPE_MODE (type)))
870 desttype = build_aligned_type (type, dest_align);
871 new_stmt
872 = gimple_build_assign (fold_build2 (MEM_REF, desttype,
873 dest, off0),
874 srcmem);
875 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
876 gimple_set_vdef (new_stmt, gimple_vdef (stmt));
877 if (gimple_vdef (new_stmt)
878 && TREE_CODE (gimple_vdef (new_stmt)) == SSA_NAME)
879 SSA_NAME_DEF_STMT (gimple_vdef (new_stmt)) = new_stmt;
880 if (!lhs)
881 {
882 gsi_replace (gsi, new_stmt, true);
883 return true;
884 }
885 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
886 goto done;
887 }
888 }
889 }
890 }
891
892 if (endp == 3)
893 {
894 /* Both DEST and SRC must be pointer types.
895 ??? This is what old code did. Is the testing for pointer types
896 really mandatory?
897
898 If either SRC is readonly or length is 1, we can use memcpy. */
899 if (!dest_align || !src_align)
900 return false;
901 if (readonly_data_expr (src)
902 || (tree_fits_uhwi_p (len)
903 && (MIN (src_align, dest_align) / BITS_PER_UNIT
904 >= tree_to_uhwi (len))))
905 {
906 tree fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
907 if (!fn)
908 return false;
909 gimple_call_set_fndecl (stmt, fn);
910 gimple_call_set_arg (stmt, 0, dest);
911 gimple_call_set_arg (stmt, 1, src);
912 fold_stmt (gsi);
913 return true;
914 }
915
916 /* If *src and *dest can't overlap, optimize into memcpy as well. */
917 if (TREE_CODE (src) == ADDR_EXPR
918 && TREE_CODE (dest) == ADDR_EXPR)
919 {
920 tree src_base, dest_base, fn;
921 HOST_WIDE_INT src_offset = 0, dest_offset = 0;
922 HOST_WIDE_INT size = -1;
923 HOST_WIDE_INT maxsize = -1;
924
925 srcvar = TREE_OPERAND (src, 0);
926 src_base = get_ref_base_and_extent (srcvar, &src_offset,
927 &size, &maxsize);
928 destvar = TREE_OPERAND (dest, 0);
929 dest_base = get_ref_base_and_extent (destvar, &dest_offset,
930 &size, &maxsize);
931 if (tree_fits_uhwi_p (len))
932 maxsize = tree_to_uhwi (len);
933 else
934 maxsize = -1;
935 src_offset /= BITS_PER_UNIT;
936 dest_offset /= BITS_PER_UNIT;
937 if (SSA_VAR_P (src_base)
938 && SSA_VAR_P (dest_base))
939 {
940 if (operand_equal_p (src_base, dest_base, 0)
941 && ranges_overlap_p (src_offset, maxsize,
942 dest_offset, maxsize))
943 return false;
944 }
945 else if (TREE_CODE (src_base) == MEM_REF
946 && TREE_CODE (dest_base) == MEM_REF)
947 {
948 if (! operand_equal_p (TREE_OPERAND (src_base, 0),
949 TREE_OPERAND (dest_base, 0), 0))
950 return false;
951 offset_int off = mem_ref_offset (src_base) + src_offset;
952 if (!wi::fits_shwi_p (off))
953 return false;
954 src_offset = off.to_shwi ();
955
956 off = mem_ref_offset (dest_base) + dest_offset;
957 if (!wi::fits_shwi_p (off))
958 return false;
959 dest_offset = off.to_shwi ();
960 if (ranges_overlap_p (src_offset, maxsize,
961 dest_offset, maxsize))
962 return false;
963 }
964 else
965 return false;
966
967 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
968 if (!fn)
969 return false;
970 gimple_call_set_fndecl (stmt, fn);
971 gimple_call_set_arg (stmt, 0, dest);
972 gimple_call_set_arg (stmt, 1, src);
973 fold_stmt (gsi);
974 return true;
975 }
976
977 /* If the destination and source do not alias optimize into
978 memcpy as well. */
979 if ((is_gimple_min_invariant (dest)
980 || TREE_CODE (dest) == SSA_NAME)
981 && (is_gimple_min_invariant (src)
982 || TREE_CODE (src) == SSA_NAME))
983 {
984 ao_ref destr, srcr;
985 ao_ref_init_from_ptr_and_size (&destr, dest, len);
986 ao_ref_init_from_ptr_and_size (&srcr, src, len);
987 if (!refs_may_alias_p_1 (&destr, &srcr, false))
988 {
989 tree fn;
990 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
991 if (!fn)
992 return false;
993 gimple_call_set_fndecl (stmt, fn);
994 gimple_call_set_arg (stmt, 0, dest);
995 gimple_call_set_arg (stmt, 1, src);
996 fold_stmt (gsi);
997 return true;
998 }
999 }
1000
1001 return false;
1002 }
1003
1004 if (!tree_fits_shwi_p (len))
1005 return false;
1006 /* FIXME:
1007 This logic lose for arguments like (type *)malloc (sizeof (type)),
1008 since we strip the casts of up to VOID return value from malloc.
1009 Perhaps we ought to inherit type from non-VOID argument here? */
1010 STRIP_NOPS (src);
1011 STRIP_NOPS (dest);
1012 if (!POINTER_TYPE_P (TREE_TYPE (src))
1013 || !POINTER_TYPE_P (TREE_TYPE (dest)))
1014 return false;
1015 /* In the following try to find a type that is most natural to be
1016 used for the memcpy source and destination and that allows
1017 the most optimization when memcpy is turned into a plain assignment
1018 using that type. In theory we could always use a char[len] type
1019 but that only gains us that the destination and source possibly
1020 no longer will have their address taken. */
1021 /* As we fold (void *)(p + CST) to (void *)p + CST undo this here. */
1022 if (TREE_CODE (src) == POINTER_PLUS_EXPR)
1023 {
1024 tree tem = TREE_OPERAND (src, 0);
1025 STRIP_NOPS (tem);
1026 if (tem != TREE_OPERAND (src, 0))
1027 src = build1 (NOP_EXPR, TREE_TYPE (tem), src);
1028 }
1029 if (TREE_CODE (dest) == POINTER_PLUS_EXPR)
1030 {
1031 tree tem = TREE_OPERAND (dest, 0);
1032 STRIP_NOPS (tem);
1033 if (tem != TREE_OPERAND (dest, 0))
1034 dest = build1 (NOP_EXPR, TREE_TYPE (tem), dest);
1035 }
1036 srctype = TREE_TYPE (TREE_TYPE (src));
1037 if (TREE_CODE (srctype) == ARRAY_TYPE
1038 && !tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
1039 {
1040 srctype = TREE_TYPE (srctype);
1041 STRIP_NOPS (src);
1042 src = build1 (NOP_EXPR, build_pointer_type (srctype), src);
1043 }
1044 desttype = TREE_TYPE (TREE_TYPE (dest));
1045 if (TREE_CODE (desttype) == ARRAY_TYPE
1046 && !tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
1047 {
1048 desttype = TREE_TYPE (desttype);
1049 STRIP_NOPS (dest);
1050 dest = build1 (NOP_EXPR, build_pointer_type (desttype), dest);
1051 }
1052 if (TREE_ADDRESSABLE (srctype)
1053 || TREE_ADDRESSABLE (desttype))
1054 return false;
1055
1056 /* Make sure we are not copying using a floating-point mode or
1057 a type whose size possibly does not match its precision. */
1058 if (FLOAT_MODE_P (TYPE_MODE (desttype))
1059 || TREE_CODE (desttype) == BOOLEAN_TYPE
1060 || TREE_CODE (desttype) == ENUMERAL_TYPE)
1061 desttype = bitwise_type_for_mode (TYPE_MODE (desttype));
1062 if (FLOAT_MODE_P (TYPE_MODE (srctype))
1063 || TREE_CODE (srctype) == BOOLEAN_TYPE
1064 || TREE_CODE (srctype) == ENUMERAL_TYPE)
1065 srctype = bitwise_type_for_mode (TYPE_MODE (srctype));
1066 if (!srctype)
1067 srctype = desttype;
1068 if (!desttype)
1069 desttype = srctype;
1070 if (!srctype)
1071 return false;
1072
1073 src_align = get_pointer_alignment (src);
1074 dest_align = get_pointer_alignment (dest);
1075 if (dest_align < TYPE_ALIGN (desttype)
1076 || src_align < TYPE_ALIGN (srctype))
1077 return false;
1078
1079 destvar = dest;
1080 STRIP_NOPS (destvar);
1081 if (TREE_CODE (destvar) == ADDR_EXPR
1082 && var_decl_component_p (TREE_OPERAND (destvar, 0))
1083 && tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
1084 destvar = fold_build2 (MEM_REF, desttype, destvar, off0);
1085 else
1086 destvar = NULL_TREE;
1087
1088 srcvar = src;
1089 STRIP_NOPS (srcvar);
1090 if (TREE_CODE (srcvar) == ADDR_EXPR
1091 && var_decl_component_p (TREE_OPERAND (srcvar, 0))
1092 && tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
1093 {
1094 if (!destvar
1095 || src_align >= TYPE_ALIGN (desttype))
1096 srcvar = fold_build2 (MEM_REF, destvar ? desttype : srctype,
1097 srcvar, off0);
1098 else if (!STRICT_ALIGNMENT)
1099 {
1100 srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
1101 src_align);
1102 srcvar = fold_build2 (MEM_REF, srctype, srcvar, off0);
1103 }
e256dfce 1104 else
fef5a0d9
RB
1105 srcvar = NULL_TREE;
1106 }
1107 else
1108 srcvar = NULL_TREE;
1109
1110 if (srcvar == NULL_TREE && destvar == NULL_TREE)
1111 return false;
1112
1113 if (srcvar == NULL_TREE)
1114 {
1115 STRIP_NOPS (src);
1116 if (src_align >= TYPE_ALIGN (desttype))
1117 srcvar = fold_build2 (MEM_REF, desttype, src, off0);
1118 else
1119 {
1120 if (STRICT_ALIGNMENT)
1121 return false;
1122 srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
1123 src_align);
1124 srcvar = fold_build2 (MEM_REF, srctype, src, off0);
1125 }
1126 }
1127 else if (destvar == NULL_TREE)
1128 {
1129 STRIP_NOPS (dest);
1130 if (dest_align >= TYPE_ALIGN (srctype))
1131 destvar = fold_build2 (MEM_REF, srctype, dest, off0);
1132 else
1133 {
1134 if (STRICT_ALIGNMENT)
1135 return false;
1136 desttype = build_aligned_type (TYPE_MAIN_VARIANT (srctype),
1137 dest_align);
1138 destvar = fold_build2 (MEM_REF, desttype, dest, off0);
1139 }
1140 }
1141
1142 gimple new_stmt;
1143 if (is_gimple_reg_type (TREE_TYPE (srcvar)))
1144 {
1145 new_stmt = gimple_build_assign (NULL_TREE, srcvar);
1146 if (gimple_in_ssa_p (cfun))
1147 srcvar = make_ssa_name (TREE_TYPE (srcvar), new_stmt);
1148 else
1149 srcvar = create_tmp_reg (TREE_TYPE (srcvar), NULL);
1150 gimple_assign_set_lhs (new_stmt, srcvar);
1151 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
1152 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1153 }
1154 new_stmt = gimple_build_assign (destvar, srcvar);
1155 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
1156 gimple_set_vdef (new_stmt, gimple_vdef (stmt));
1157 if (gimple_vdef (new_stmt)
1158 && TREE_CODE (gimple_vdef (new_stmt)) == SSA_NAME)
1159 SSA_NAME_DEF_STMT (gimple_vdef (new_stmt)) = new_stmt;
1160 if (!lhs)
1161 {
1162 gsi_replace (gsi, new_stmt, true);
1163 return true;
1164 }
1165 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1166 }
1167
1168done:
1169 if (endp == 0 || endp == 3)
1170 len = NULL_TREE;
1171 else if (endp == 2)
1172 len = fold_build2_loc (loc, MINUS_EXPR, TREE_TYPE (len), len,
1173 ssize_int (1));
1174 if (endp == 2 || endp == 1)
1175 dest = fold_build_pointer_plus_loc (loc, dest, len);
1176
1177 dest = force_gimple_operand_gsi (gsi, dest, false, NULL_TREE, true,
1178 GSI_SAME_STMT);
1179 gimple repl = gimple_build_assign (lhs, dest);
1180 gsi_replace (gsi, repl, true);
1181 return true;
1182}
1183
1184/* Fold function call to builtin memset or bzero at *GSI setting the
1185 memory of size LEN to VAL. Return whether a simplification was made. */
1186
1187static bool
1188gimple_fold_builtin_memset (gimple_stmt_iterator *gsi, tree c, tree len)
1189{
1190 gimple stmt = gsi_stmt (*gsi);
1191 tree etype;
1192 unsigned HOST_WIDE_INT length, cval;
1193
1194 /* If the LEN parameter is zero, return DEST. */
1195 if (integer_zerop (len))
1196 {
1197 replace_call_with_value (gsi, gimple_call_arg (stmt, 0));
1198 return true;
1199 }
1200
1201 if (! tree_fits_uhwi_p (len))
1202 return false;
1203
1204 if (TREE_CODE (c) != INTEGER_CST)
1205 return false;
1206
1207 tree dest = gimple_call_arg (stmt, 0);
1208 tree var = dest;
1209 if (TREE_CODE (var) != ADDR_EXPR)
1210 return false;
1211
1212 var = TREE_OPERAND (var, 0);
1213 if (TREE_THIS_VOLATILE (var))
1214 return false;
1215
1216 etype = TREE_TYPE (var);
1217 if (TREE_CODE (etype) == ARRAY_TYPE)
1218 etype = TREE_TYPE (etype);
1219
1220 if (!INTEGRAL_TYPE_P (etype)
1221 && !POINTER_TYPE_P (etype))
1222 return NULL_TREE;
1223
1224 if (! var_decl_component_p (var))
1225 return NULL_TREE;
1226
1227 length = tree_to_uhwi (len);
1228 if (GET_MODE_SIZE (TYPE_MODE (etype)) != length
1229 || get_pointer_alignment (dest) / BITS_PER_UNIT < length)
1230 return NULL_TREE;
1231
1232 if (length > HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT)
1233 return NULL_TREE;
1234
1235 if (integer_zerop (c))
1236 cval = 0;
1237 else
1238 {
1239 if (CHAR_BIT != 8 || BITS_PER_UNIT != 8 || HOST_BITS_PER_WIDE_INT > 64)
1240 return NULL_TREE;
1241
1242 cval = TREE_INT_CST_LOW (c);
1243 cval &= 0xff;
1244 cval |= cval << 8;
1245 cval |= cval << 16;
1246 cval |= (cval << 31) << 1;
1247 }
1248
1249 var = fold_build2 (MEM_REF, etype, dest, build_int_cst (ptr_type_node, 0));
1250 gimple store = gimple_build_assign (var, build_int_cst_type (etype, cval));
1251 gimple_set_vuse (store, gimple_vuse (stmt));
1252 tree vdef = gimple_vdef (stmt);
1253 if (vdef && TREE_CODE (vdef) == SSA_NAME)
1254 {
1255 gimple_set_vdef (store, gimple_vdef (stmt));
1256 SSA_NAME_DEF_STMT (gimple_vdef (stmt)) = store;
1257 }
1258 gsi_insert_before (gsi, store, GSI_SAME_STMT);
1259 if (gimple_call_lhs (stmt))
1260 {
1261 gimple asgn = gimple_build_assign (gimple_call_lhs (stmt), dest);
1262 gsi_replace (gsi, asgn, true);
1263 }
1264 else
1265 {
1266 gimple_stmt_iterator gsi2 = *gsi;
1267 gsi_prev (gsi);
1268 gsi_remove (&gsi2, true);
1269 }
1270
1271 return true;
1272}
1273
1274
1275/* Return the string length, maximum string length or maximum value of
1276 ARG in LENGTH.
1277 If ARG is an SSA name variable, follow its use-def chains. If LENGTH
1278 is not NULL and, for TYPE == 0, its value is not equal to the length
1279 we determine or if we are unable to determine the length or value,
1280 return false. VISITED is a bitmap of visited variables.
1281 TYPE is 0 if string length should be returned, 1 for maximum string
1282 length and 2 for maximum value ARG can have. */
1283
1284static bool
dcb7fae2 1285get_maxval_strlen (tree arg, tree *length, bitmap *visited, int type)
fef5a0d9
RB
1286{
1287 tree var, val;
1288 gimple def_stmt;
1289
1290 if (TREE_CODE (arg) != SSA_NAME)
1291 {
1292 /* We can end up with &(*iftmp_1)[0] here as well, so handle it. */
1293 if (TREE_CODE (arg) == ADDR_EXPR
1294 && TREE_CODE (TREE_OPERAND (arg, 0)) == ARRAY_REF
1295 && integer_zerop (TREE_OPERAND (TREE_OPERAND (arg, 0), 1)))
1296 {
1297 tree aop0 = TREE_OPERAND (TREE_OPERAND (arg, 0), 0);
1298 if (TREE_CODE (aop0) == INDIRECT_REF
1299 && TREE_CODE (TREE_OPERAND (aop0, 0)) == SSA_NAME)
1300 return get_maxval_strlen (TREE_OPERAND (aop0, 0),
1301 length, visited, type);
1302 }
1303
1304 if (type == 2)
1305 {
1306 val = arg;
1307 if (TREE_CODE (val) != INTEGER_CST
1308 || tree_int_cst_sgn (val) < 0)
1309 return false;
1310 }
1311 else
1312 val = c_strlen (arg, 1);
1313 if (!val)
1314 return false;
1315
1316 if (*length)
1317 {
1318 if (type > 0)
1319 {
1320 if (TREE_CODE (*length) != INTEGER_CST
1321 || TREE_CODE (val) != INTEGER_CST)
1322 return false;
1323
1324 if (tree_int_cst_lt (*length, val))
1325 *length = val;
1326 return true;
1327 }
1328 else if (simple_cst_equal (val, *length) != 1)
1329 return false;
1330 }
1331
1332 *length = val;
1333 return true;
1334 }
1335
1336 /* If ARG is registered for SSA update we cannot look at its defining
1337 statement. */
1338 if (name_registered_for_update_p (arg))
1339 return false;
1340
1341 /* If we were already here, break the infinite cycle. */
dcb7fae2
RB
1342 if (!*visited)
1343 *visited = BITMAP_ALLOC (NULL);
1344 if (!bitmap_set_bit (*visited, SSA_NAME_VERSION (arg)))
fef5a0d9
RB
1345 return true;
1346
1347 var = arg;
1348 def_stmt = SSA_NAME_DEF_STMT (var);
1349
1350 switch (gimple_code (def_stmt))
1351 {
1352 case GIMPLE_ASSIGN:
1353 /* The RHS of the statement defining VAR must either have a
1354 constant length or come from another SSA_NAME with a constant
1355 length. */
1356 if (gimple_assign_single_p (def_stmt)
1357 || gimple_assign_unary_nop_p (def_stmt))
1358 {
1359 tree rhs = gimple_assign_rhs1 (def_stmt);
1360 return get_maxval_strlen (rhs, length, visited, type);
1361 }
1362 else if (gimple_assign_rhs_code (def_stmt) == COND_EXPR)
1363 {
1364 tree op2 = gimple_assign_rhs2 (def_stmt);
1365 tree op3 = gimple_assign_rhs3 (def_stmt);
1366 return get_maxval_strlen (op2, length, visited, type)
1367 && get_maxval_strlen (op3, length, visited, type);
1368 }
1369 return false;
1370
1371 case GIMPLE_PHI:
1372 {
1373 /* All the arguments of the PHI node must have the same constant
1374 length. */
1375 unsigned i;
1376
1377 for (i = 0; i < gimple_phi_num_args (def_stmt); i++)
1378 {
1379 tree arg = gimple_phi_arg (def_stmt, i)->def;
1380
1381 /* If this PHI has itself as an argument, we cannot
1382 determine the string length of this argument. However,
1383 if we can find a constant string length for the other
1384 PHI args then we can still be sure that this is a
1385 constant string length. So be optimistic and just
1386 continue with the next argument. */
1387 if (arg == gimple_phi_result (def_stmt))
1388 continue;
1389
1390 if (!get_maxval_strlen (arg, length, visited, type))
1391 return false;
1392 }
1393 }
1394 return true;
1395
1396 default:
1397 return false;
1398 }
1399}
1400
dcb7fae2
RB
1401tree
1402get_maxval_strlen (tree arg, int type)
1403{
1404 bitmap visited = NULL;
1405 tree len = NULL_TREE;
1406 if (!get_maxval_strlen (arg, &len, &visited, type))
1407 len = NULL_TREE;
1408 if (visited)
1409 BITMAP_FREE (visited);
1410
1411 return len;
1412}
1413
fef5a0d9
RB
1414
1415/* Fold function call to builtin strcpy with arguments DEST and SRC.
1416 If LEN is not NULL, it represents the length of the string to be
1417 copied. Return NULL_TREE if no simplification can be made. */
1418
1419static bool
1420gimple_fold_builtin_strcpy (gimple_stmt_iterator *gsi,
dcb7fae2 1421 tree dest, tree src)
fef5a0d9 1422{
dcb7fae2 1423 location_t loc = gimple_location (gsi_stmt (*gsi));
fef5a0d9
RB
1424 tree fn;
1425
1426 /* If SRC and DEST are the same (and not volatile), return DEST. */
1427 if (operand_equal_p (src, dest, 0))
1428 {
1429 replace_call_with_value (gsi, dest);
1430 return true;
1431 }
1432
1433 if (optimize_function_for_size_p (cfun))
1434 return false;
1435
1436 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1437 if (!fn)
1438 return false;
1439
1579e1f8 1440 tree len = get_maxval_strlen (src, 0);
fef5a0d9 1441 if (!len)
dcb7fae2 1442 return false;
fef5a0d9
RB
1443
1444 len = fold_convert_loc (loc, size_type_node, len);
1445 len = size_binop_loc (loc, PLUS_EXPR, len, build_int_cst (size_type_node, 1));
1446 len = force_gimple_operand_gsi (gsi, len, true,
1447 NULL_TREE, true, GSI_SAME_STMT);
1448 gimple repl = gimple_build_call (fn, 3, dest, src, len);
1449 replace_call_with_call_and_fold (gsi, repl);
1450 return true;
1451}
1452
1453/* Fold function call to builtin strncpy with arguments DEST, SRC, and LEN.
1454 If SLEN is not NULL, it represents the length of the source string.
1455 Return NULL_TREE if no simplification can be made. */
1456
1457static bool
dcb7fae2
RB
1458gimple_fold_builtin_strncpy (gimple_stmt_iterator *gsi,
1459 tree dest, tree src, tree len)
fef5a0d9 1460{
dcb7fae2 1461 location_t loc = gimple_location (gsi_stmt (*gsi));
fef5a0d9
RB
1462 tree fn;
1463
1464 /* If the LEN parameter is zero, return DEST. */
1465 if (integer_zerop (len))
1466 {
1467 replace_call_with_value (gsi, dest);
1468 return true;
1469 }
1470
1471 /* We can't compare slen with len as constants below if len is not a
1472 constant. */
dcb7fae2 1473 if (TREE_CODE (len) != INTEGER_CST)
fef5a0d9
RB
1474 return false;
1475
fef5a0d9 1476 /* Now, we must be passed a constant src ptr parameter. */
1579e1f8 1477 tree slen = get_maxval_strlen (src, 0);
dcb7fae2 1478 if (!slen || TREE_CODE (slen) != INTEGER_CST)
fef5a0d9
RB
1479 return false;
1480
1481 slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
1482
1483 /* We do not support simplification of this case, though we do
1484 support it when expanding trees into RTL. */
1485 /* FIXME: generate a call to __builtin_memset. */
1486 if (tree_int_cst_lt (slen, len))
1487 return false;
1488
1489 /* OK transform into builtin memcpy. */
1490 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1491 if (!fn)
1492 return false;
1493
1494 len = fold_convert_loc (loc, size_type_node, len);
1495 len = force_gimple_operand_gsi (gsi, len, true,
1496 NULL_TREE, true, GSI_SAME_STMT);
1497 gimple repl = gimple_build_call (fn, 3, dest, src, len);
1498 replace_call_with_call_and_fold (gsi, repl);
1499 return true;
1500}
1501
1502/* Simplify a call to the strcat builtin. DST and SRC are the arguments
1503 to the call.
1504
1505 Return NULL_TREE if no simplification was possible, otherwise return the
1506 simplified form of the call as a tree.
1507
1508 The simplified form may be a constant or other expression which
1509 computes the same value, but in a more efficient manner (including
1510 calls to other builtin functions).
1511
1512 The call may contain arguments which need to be evaluated, but
1513 which are not useful to determine the result of the call. In
1514 this case we return a chain of COMPOUND_EXPRs. The LHS of each
1515 COMPOUND_EXPR will be an argument which must be evaluated.
1516 COMPOUND_EXPRs are chained through their RHS. The RHS of the last
1517 COMPOUND_EXPR in the chain will contain the tree for the simplified
1518 form of the builtin function call. */
1519
1520static bool
dcb7fae2 1521gimple_fold_builtin_strcat (gimple_stmt_iterator *gsi, tree dst, tree src)
fef5a0d9
RB
1522{
1523 gimple stmt = gsi_stmt (*gsi);
dcb7fae2 1524 location_t loc = gimple_location (stmt);
fef5a0d9
RB
1525
1526 const char *p = c_getstr (src);
1527
1528 /* If the string length is zero, return the dst parameter. */
1529 if (p && *p == '\0')
1530 {
1531 replace_call_with_value (gsi, dst);
1532 return true;
1533 }
1534
1535 if (!optimize_bb_for_speed_p (gimple_bb (stmt)))
1536 return false;
1537
1538 /* See if we can store by pieces into (dst + strlen(dst)). */
1539 tree newdst;
1540 tree strlen_fn = builtin_decl_implicit (BUILT_IN_STRLEN);
1541 tree memcpy_fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1542
1543 if (!strlen_fn || !memcpy_fn)
1544 return false;
1545
1546 /* If the length of the source string isn't computable don't
1547 split strcat into strlen and memcpy. */
dcb7fae2 1548 tree len = get_maxval_strlen (src, 0);
fef5a0d9 1549 if (! len)
fef5a0d9
RB
1550 return false;
1551
1552 /* Create strlen (dst). */
1553 gimple_seq stmts = NULL, stmts2;
1554 gimple repl = gimple_build_call (strlen_fn, 1, dst);
1555 gimple_set_location (repl, loc);
1556 if (gimple_in_ssa_p (cfun))
1557 newdst = make_ssa_name (size_type_node, NULL);
1558 else
1559 newdst = create_tmp_reg (size_type_node, NULL);
1560 gimple_call_set_lhs (repl, newdst);
1561 gimple_seq_add_stmt_without_update (&stmts, repl);
1562
1563 /* Create (dst p+ strlen (dst)). */
1564 newdst = fold_build_pointer_plus_loc (loc, dst, newdst);
1565 newdst = force_gimple_operand (newdst, &stmts2, true, NULL_TREE);
1566 gimple_seq_add_seq_without_update (&stmts, stmts2);
1567
1568 len = fold_convert_loc (loc, size_type_node, len);
1569 len = size_binop_loc (loc, PLUS_EXPR, len,
1570 build_int_cst (size_type_node, 1));
1571 len = force_gimple_operand (len, &stmts2, true, NULL_TREE);
1572 gimple_seq_add_seq_without_update (&stmts, stmts2);
1573
1574 repl = gimple_build_call (memcpy_fn, 3, newdst, src, len);
1575 gimple_seq_add_stmt_without_update (&stmts, repl);
1576 if (gimple_call_lhs (stmt))
1577 {
1578 repl = gimple_build_assign (gimple_call_lhs (stmt), dst);
1579 gimple_seq_add_stmt_without_update (&stmts, repl);
1580 gsi_replace_with_seq_vops (gsi, stmts);
1581 /* gsi now points at the assignment to the lhs, get a
1582 stmt iterator to the memcpy call.
1583 ??? We can't use gsi_for_stmt as that doesn't work when the
1584 CFG isn't built yet. */
1585 gimple_stmt_iterator gsi2 = *gsi;
1586 gsi_prev (&gsi2);
1587 fold_stmt (&gsi2);
1588 }
1589 else
1590 {
1591 gsi_replace_with_seq_vops (gsi, stmts);
1592 fold_stmt (gsi);
1593 }
1594 return true;
1595}
1596
07f1cf56
RB
1597/* Fold a call to the __strcat_chk builtin FNDECL. DEST, SRC, and SIZE
1598 are the arguments to the call. */
1599
1600static bool
1601gimple_fold_builtin_strcat_chk (gimple_stmt_iterator *gsi)
1602{
1603 gimple stmt = gsi_stmt (*gsi);
1604 tree dest = gimple_call_arg (stmt, 0);
1605 tree src = gimple_call_arg (stmt, 1);
1606 tree size = gimple_call_arg (stmt, 2);
1607 tree fn;
1608 const char *p;
1609
1610
1611 p = c_getstr (src);
1612 /* If the SRC parameter is "", return DEST. */
1613 if (p && *p == '\0')
1614 {
1615 replace_call_with_value (gsi, dest);
1616 return true;
1617 }
1618
1619 if (! tree_fits_uhwi_p (size) || ! integer_all_onesp (size))
1620 return false;
1621
1622 /* If __builtin_strcat_chk is used, assume strcat is available. */
1623 fn = builtin_decl_explicit (BUILT_IN_STRCAT);
1624 if (!fn)
1625 return false;
1626
1627 gimple repl = gimple_build_call (fn, 2, dest, src);
1628 replace_call_with_call_and_fold (gsi, repl);
1629 return true;
1630}
1631
745583f9
RB
1632/* Fold a call to the __strncat_chk builtin with arguments DEST, SRC,
1633 LEN, and SIZE. */
1634
1635static bool
1636gimple_fold_builtin_strncat_chk (gimple_stmt_iterator *gsi)
1637{
1638 gimple stmt = gsi_stmt (*gsi);
1639 tree dest = gimple_call_arg (stmt, 0);
1640 tree src = gimple_call_arg (stmt, 1);
1641 tree len = gimple_call_arg (stmt, 2);
1642 tree size = gimple_call_arg (stmt, 3);
1643 tree fn;
1644 const char *p;
1645
1646 p = c_getstr (src);
1647 /* If the SRC parameter is "" or if LEN is 0, return DEST. */
1648 if ((p && *p == '\0')
1649 || integer_zerop (len))
1650 {
1651 replace_call_with_value (gsi, dest);
1652 return true;
1653 }
1654
1655 if (! tree_fits_uhwi_p (size))
1656 return false;
1657
1658 if (! integer_all_onesp (size))
1659 {
1660 tree src_len = c_strlen (src, 1);
1661 if (src_len
1662 && tree_fits_uhwi_p (src_len)
1663 && tree_fits_uhwi_p (len)
1664 && ! tree_int_cst_lt (len, src_len))
1665 {
1666 /* If LEN >= strlen (SRC), optimize into __strcat_chk. */
1667 fn = builtin_decl_explicit (BUILT_IN_STRCAT_CHK);
1668 if (!fn)
1669 return false;
1670
1671 gimple repl = gimple_build_call (fn, 3, dest, src, size);
1672 replace_call_with_call_and_fold (gsi, repl);
1673 return true;
1674 }
1675 return false;
1676 }
1677
1678 /* If __builtin_strncat_chk is used, assume strncat is available. */
1679 fn = builtin_decl_explicit (BUILT_IN_STRNCAT);
1680 if (!fn)
1681 return false;
1682
1683 gimple repl = gimple_build_call (fn, 3, dest, src, len);
1684 replace_call_with_call_and_fold (gsi, repl);
1685 return true;
1686}
1687
fef5a0d9
RB
1688/* Fold a call to the fputs builtin. ARG0 and ARG1 are the arguments
1689 to the call. IGNORE is true if the value returned
1690 by the builtin will be ignored. UNLOCKED is true is true if this
1691 actually a call to fputs_unlocked. If LEN in non-NULL, it represents
1692 the known length of the string. Return NULL_TREE if no simplification
1693 was possible. */
1694
1695static bool
1696gimple_fold_builtin_fputs (gimple_stmt_iterator *gsi,
fef5a0d9 1697 tree arg0, tree arg1,
dcb7fae2 1698 bool unlocked)
fef5a0d9 1699{
dcb7fae2
RB
1700 gimple stmt = gsi_stmt (*gsi);
1701
fef5a0d9
RB
1702 /* If we're using an unlocked function, assume the other unlocked
1703 functions exist explicitly. */
1704 tree const fn_fputc = (unlocked
1705 ? builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED)
1706 : builtin_decl_implicit (BUILT_IN_FPUTC));
1707 tree const fn_fwrite = (unlocked
1708 ? builtin_decl_explicit (BUILT_IN_FWRITE_UNLOCKED)
1709 : builtin_decl_implicit (BUILT_IN_FWRITE));
1710
1711 /* If the return value is used, don't do the transformation. */
dcb7fae2 1712 if (gimple_call_lhs (stmt))
fef5a0d9
RB
1713 return false;
1714
fef5a0d9
RB
1715 /* Get the length of the string passed to fputs. If the length
1716 can't be determined, punt. */
dcb7fae2 1717 tree len = get_maxval_strlen (arg0, 0);
fef5a0d9
RB
1718 if (!len
1719 || TREE_CODE (len) != INTEGER_CST)
1720 return false;
1721
1722 switch (compare_tree_int (len, 1))
1723 {
1724 case -1: /* length is 0, delete the call entirely . */
1725 replace_call_with_value (gsi, integer_zero_node);
1726 return true;
1727
1728 case 0: /* length is 1, call fputc. */
1729 {
1730 const char *p = c_getstr (arg0);
1731 if (p != NULL)
1732 {
1733 if (!fn_fputc)
1734 return false;
1735
1736 gimple repl = gimple_build_call (fn_fputc, 2,
1737 build_int_cst
1738 (integer_type_node, p[0]), arg1);
1739 replace_call_with_call_and_fold (gsi, repl);
1740 return true;
1741 }
1742 }
1743 /* FALLTHROUGH */
1744 case 1: /* length is greater than 1, call fwrite. */
1745 {
1746 /* If optimizing for size keep fputs. */
1747 if (optimize_function_for_size_p (cfun))
1748 return false;
1749 /* New argument list transforming fputs(string, stream) to
1750 fwrite(string, 1, len, stream). */
1751 if (!fn_fwrite)
1752 return false;
1753
1754 gimple repl = gimple_build_call (fn_fwrite, 4, arg0,
1755 size_one_node, len, arg1);
1756 replace_call_with_call_and_fold (gsi, repl);
1757 return true;
1758 }
1759 default:
1760 gcc_unreachable ();
1761 }
1762 return false;
1763}
1764
1765/* Fold a call to the __mem{cpy,pcpy,move,set}_chk builtin.
1766 DEST, SRC, LEN, and SIZE are the arguments to the call.
1767 IGNORE is true, if return value can be ignored. FCODE is the BUILT_IN_*
1768 code of the builtin. If MAXLEN is not NULL, it is maximum length
1769 passed as third argument. */
1770
1771static bool
1772gimple_fold_builtin_memory_chk (gimple_stmt_iterator *gsi,
fef5a0d9 1773 tree dest, tree src, tree len, tree size,
fef5a0d9
RB
1774 enum built_in_function fcode)
1775{
dcb7fae2
RB
1776 gimple stmt = gsi_stmt (*gsi);
1777 location_t loc = gimple_location (stmt);
1778 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
fef5a0d9
RB
1779 tree fn;
1780
1781 /* If SRC and DEST are the same (and not volatile), return DEST
1782 (resp. DEST+LEN for __mempcpy_chk). */
1783 if (fcode != BUILT_IN_MEMSET_CHK && operand_equal_p (src, dest, 0))
1784 {
1785 if (fcode != BUILT_IN_MEMPCPY_CHK)
1786 {
1787 replace_call_with_value (gsi, dest);
1788 return true;
1789 }
1790 else
1791 {
1792 tree temp = fold_build_pointer_plus_loc (loc, dest, len);
1793 temp = force_gimple_operand_gsi (gsi, temp,
1794 false, NULL_TREE, true,
1795 GSI_SAME_STMT);
1796 replace_call_with_value (gsi, temp);
1797 return true;
1798 }
1799 }
1800
1801 if (! tree_fits_uhwi_p (size))
1802 return false;
1803
dcb7fae2 1804 tree maxlen = get_maxval_strlen (len, 2);
fef5a0d9
RB
1805 if (! integer_all_onesp (size))
1806 {
1807 if (! tree_fits_uhwi_p (len))
1808 {
1809 /* If LEN is not constant, try MAXLEN too.
1810 For MAXLEN only allow optimizing into non-_ocs function
1811 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
1812 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
1813 {
1814 if (fcode == BUILT_IN_MEMPCPY_CHK && ignore)
1815 {
1816 /* (void) __mempcpy_chk () can be optimized into
1817 (void) __memcpy_chk (). */
1818 fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
1819 if (!fn)
1820 return false;
1821
1822 gimple repl = gimple_build_call (fn, 4, dest, src, len, size);
1823 replace_call_with_call_and_fold (gsi, repl);
1824 return true;
1825 }
1826 return false;
1827 }
1828 }
1829 else
1830 maxlen = len;
1831
1832 if (tree_int_cst_lt (size, maxlen))
1833 return false;
1834 }
1835
1836 fn = NULL_TREE;
1837 /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
1838 mem{cpy,pcpy,move,set} is available. */
1839 switch (fcode)
1840 {
1841 case BUILT_IN_MEMCPY_CHK:
1842 fn = builtin_decl_explicit (BUILT_IN_MEMCPY);
1843 break;
1844 case BUILT_IN_MEMPCPY_CHK:
1845 fn = builtin_decl_explicit (BUILT_IN_MEMPCPY);
1846 break;
1847 case BUILT_IN_MEMMOVE_CHK:
1848 fn = builtin_decl_explicit (BUILT_IN_MEMMOVE);
1849 break;
1850 case BUILT_IN_MEMSET_CHK:
1851 fn = builtin_decl_explicit (BUILT_IN_MEMSET);
1852 break;
1853 default:
1854 break;
1855 }
1856
1857 if (!fn)
1858 return false;
1859
1860 gimple repl = gimple_build_call (fn, 3, dest, src, len);
1861 replace_call_with_call_and_fold (gsi, repl);
1862 return true;
1863}
1864
1865/* Fold a call to the __st[rp]cpy_chk builtin.
1866 DEST, SRC, and SIZE are the arguments to the call.
1867 IGNORE is true if return value can be ignored. FCODE is the BUILT_IN_*
1868 code of the builtin. If MAXLEN is not NULL, it is maximum length of
1869 strings passed as second argument. */
1870
1871static bool
1872gimple_fold_builtin_stxcpy_chk (gimple_stmt_iterator *gsi,
dcb7fae2 1873 tree dest,
fef5a0d9 1874 tree src, tree size,
fef5a0d9
RB
1875 enum built_in_function fcode)
1876{
dcb7fae2
RB
1877 gimple stmt = gsi_stmt (*gsi);
1878 location_t loc = gimple_location (stmt);
1879 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
fef5a0d9
RB
1880 tree len, fn;
1881
1882 /* If SRC and DEST are the same (and not volatile), return DEST. */
1883 if (fcode == BUILT_IN_STRCPY_CHK && operand_equal_p (src, dest, 0))
1884 {
1885 replace_call_with_value (gsi, dest);
1886 return true;
1887 }
1888
1889 if (! tree_fits_uhwi_p (size))
1890 return false;
1891
dcb7fae2 1892 tree maxlen = get_maxval_strlen (src, 1);
fef5a0d9
RB
1893 if (! integer_all_onesp (size))
1894 {
1895 len = c_strlen (src, 1);
1896 if (! len || ! tree_fits_uhwi_p (len))
1897 {
1898 /* If LEN is not constant, try MAXLEN too.
1899 For MAXLEN only allow optimizing into non-_ocs function
1900 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
1901 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
1902 {
1903 if (fcode == BUILT_IN_STPCPY_CHK)
1904 {
1905 if (! ignore)
1906 return false;
1907
1908 /* If return value of __stpcpy_chk is ignored,
1909 optimize into __strcpy_chk. */
1910 fn = builtin_decl_explicit (BUILT_IN_STRCPY_CHK);
1911 if (!fn)
1912 return false;
1913
1914 gimple repl = gimple_build_call (fn, 3, dest, src, size);
1915 replace_call_with_call_and_fold (gsi, repl);
1916 return true;
1917 }
1918
1919 if (! len || TREE_SIDE_EFFECTS (len))
1920 return false;
1921
1922 /* If c_strlen returned something, but not a constant,
1923 transform __strcpy_chk into __memcpy_chk. */
1924 fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
1925 if (!fn)
1926 return false;
1927
1928 len = fold_convert_loc (loc, size_type_node, len);
1929 len = size_binop_loc (loc, PLUS_EXPR, len,
1930 build_int_cst (size_type_node, 1));
1931 len = force_gimple_operand_gsi (gsi, len, true, NULL_TREE,
1932 true, GSI_SAME_STMT);
1933 gimple repl = gimple_build_call (fn, 4, dest, src, len, size);
1934 replace_call_with_call_and_fold (gsi, repl);
1935 return true;
1936 }
e256dfce 1937 }
fef5a0d9
RB
1938 else
1939 maxlen = len;
1940
1941 if (! tree_int_cst_lt (maxlen, size))
1942 return false;
e256dfce
RG
1943 }
1944
fef5a0d9
RB
1945 /* If __builtin_st{r,p}cpy_chk is used, assume st{r,p}cpy is available. */
1946 fn = builtin_decl_explicit (fcode == BUILT_IN_STPCPY_CHK
1947 ? BUILT_IN_STPCPY : BUILT_IN_STRCPY);
1948 if (!fn)
1949 return false;
1950
1951 gimple repl = gimple_build_call (fn, 2, dest, src);
1952 replace_call_with_call_and_fold (gsi, repl);
1953 return true;
1954}
1955
1956/* Fold a call to the __st{r,p}ncpy_chk builtin. DEST, SRC, LEN, and SIZE
1957 are the arguments to the call. If MAXLEN is not NULL, it is maximum
1958 length passed as third argument. IGNORE is true if return value can be
1959 ignored. FCODE is the BUILT_IN_* code of the builtin. */
1960
1961static bool
1962gimple_fold_builtin_stxncpy_chk (gimple_stmt_iterator *gsi,
1963 tree dest, tree src,
dcb7fae2 1964 tree len, tree size,
fef5a0d9
RB
1965 enum built_in_function fcode)
1966{
dcb7fae2
RB
1967 gimple stmt = gsi_stmt (*gsi);
1968 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
fef5a0d9
RB
1969 tree fn;
1970
1971 if (fcode == BUILT_IN_STPNCPY_CHK && ignore)
cbdd87d4 1972 {
fef5a0d9
RB
1973 /* If return value of __stpncpy_chk is ignored,
1974 optimize into __strncpy_chk. */
1975 fn = builtin_decl_explicit (BUILT_IN_STRNCPY_CHK);
1976 if (fn)
1977 {
1978 gimple repl = gimple_build_call (fn, 4, dest, src, len, size);
1979 replace_call_with_call_and_fold (gsi, repl);
1980 return true;
1981 }
cbdd87d4
RG
1982 }
1983
fef5a0d9
RB
1984 if (! tree_fits_uhwi_p (size))
1985 return false;
1986
dcb7fae2 1987 tree maxlen = get_maxval_strlen (len, 2);
fef5a0d9 1988 if (! integer_all_onesp (size))
cbdd87d4 1989 {
fef5a0d9 1990 if (! tree_fits_uhwi_p (len))
fe2ef088 1991 {
fef5a0d9
RB
1992 /* If LEN is not constant, try MAXLEN too.
1993 For MAXLEN only allow optimizing into non-_ocs function
1994 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
1995 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
1996 return false;
8a1561bc 1997 }
fef5a0d9
RB
1998 else
1999 maxlen = len;
2000
2001 if (tree_int_cst_lt (size, maxlen))
2002 return false;
cbdd87d4
RG
2003 }
2004
fef5a0d9
RB
2005 /* If __builtin_st{r,p}ncpy_chk is used, assume st{r,p}ncpy is available. */
2006 fn = builtin_decl_explicit (fcode == BUILT_IN_STPNCPY_CHK
2007 ? BUILT_IN_STPNCPY : BUILT_IN_STRNCPY);
2008 if (!fn)
2009 return false;
2010
2011 gimple repl = gimple_build_call (fn, 3, dest, src, len);
2012 replace_call_with_call_and_fold (gsi, repl);
2013 return true;
cbdd87d4
RG
2014}
2015
fef5a0d9
RB
2016/* Fold a call EXP to {,v}snprintf having NARGS passed as ARGS. Return
2017 NULL_TREE if a normal call should be emitted rather than expanding
2018 the function inline. FCODE is either BUILT_IN_SNPRINTF_CHK or
2019 BUILT_IN_VSNPRINTF_CHK. If MAXLEN is not NULL, it is maximum length
2020 passed as second argument. */
cbdd87d4
RG
2021
2022static bool
fef5a0d9 2023gimple_fold_builtin_snprintf_chk (gimple_stmt_iterator *gsi,
dcb7fae2 2024 enum built_in_function fcode)
cbdd87d4 2025{
538dd0b7 2026 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
fef5a0d9
RB
2027 tree dest, size, len, fn, fmt, flag;
2028 const char *fmt_str;
cbdd87d4 2029
fef5a0d9
RB
2030 /* Verify the required arguments in the original call. */
2031 if (gimple_call_num_args (stmt) < 5)
2032 return false;
cbdd87d4 2033
fef5a0d9
RB
2034 dest = gimple_call_arg (stmt, 0);
2035 len = gimple_call_arg (stmt, 1);
2036 flag = gimple_call_arg (stmt, 2);
2037 size = gimple_call_arg (stmt, 3);
2038 fmt = gimple_call_arg (stmt, 4);
2039
2040 if (! tree_fits_uhwi_p (size))
2041 return false;
2042
2043 if (! integer_all_onesp (size))
2044 {
dcb7fae2 2045 tree maxlen = get_maxval_strlen (len, 2);
fef5a0d9 2046 if (! tree_fits_uhwi_p (len))
cbdd87d4 2047 {
fef5a0d9
RB
2048 /* If LEN is not constant, try MAXLEN too.
2049 For MAXLEN only allow optimizing into non-_ocs function
2050 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
2051 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
cbdd87d4
RG
2052 return false;
2053 }
2054 else
fef5a0d9 2055 maxlen = len;
cbdd87d4 2056
fef5a0d9
RB
2057 if (tree_int_cst_lt (size, maxlen))
2058 return false;
2059 }
cbdd87d4 2060
fef5a0d9
RB
2061 if (!init_target_chars ())
2062 return false;
cbdd87d4 2063
fef5a0d9
RB
2064 /* Only convert __{,v}snprintf_chk to {,v}snprintf if flag is 0
2065 or if format doesn't contain % chars or is "%s". */
2066 if (! integer_zerop (flag))
2067 {
2068 fmt_str = c_getstr (fmt);
2069 if (fmt_str == NULL)
2070 return false;
2071 if (strchr (fmt_str, target_percent) != NULL
2072 && strcmp (fmt_str, target_percent_s))
2073 return false;
cbdd87d4
RG
2074 }
2075
fef5a0d9
RB
2076 /* If __builtin_{,v}snprintf_chk is used, assume {,v}snprintf is
2077 available. */
2078 fn = builtin_decl_explicit (fcode == BUILT_IN_VSNPRINTF_CHK
2079 ? BUILT_IN_VSNPRINTF : BUILT_IN_SNPRINTF);
2080 if (!fn)
491e0b9b
RG
2081 return false;
2082
fef5a0d9
RB
2083 /* Replace the called function and the first 5 argument by 3 retaining
2084 trailing varargs. */
2085 gimple_call_set_fndecl (stmt, fn);
2086 gimple_call_set_fntype (stmt, TREE_TYPE (fn));
2087 gimple_call_set_arg (stmt, 0, dest);
2088 gimple_call_set_arg (stmt, 1, len);
2089 gimple_call_set_arg (stmt, 2, fmt);
2090 for (unsigned i = 3; i < gimple_call_num_args (stmt) - 2; ++i)
2091 gimple_call_set_arg (stmt, i, gimple_call_arg (stmt, i + 2));
2092 gimple_set_num_ops (stmt, gimple_num_ops (stmt) - 2);
2093 fold_stmt (gsi);
2094 return true;
2095}
cbdd87d4 2096
fef5a0d9
RB
2097/* Fold a call EXP to __{,v}sprintf_chk having NARGS passed as ARGS.
2098 Return NULL_TREE if a normal call should be emitted rather than
2099 expanding the function inline. FCODE is either BUILT_IN_SPRINTF_CHK
2100 or BUILT_IN_VSPRINTF_CHK. */
cbdd87d4 2101
fef5a0d9
RB
2102static bool
2103gimple_fold_builtin_sprintf_chk (gimple_stmt_iterator *gsi,
2104 enum built_in_function fcode)
2105{
538dd0b7 2106 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
fef5a0d9
RB
2107 tree dest, size, len, fn, fmt, flag;
2108 const char *fmt_str;
2109 unsigned nargs = gimple_call_num_args (stmt);
cbdd87d4 2110
fef5a0d9
RB
2111 /* Verify the required arguments in the original call. */
2112 if (nargs < 4)
2113 return false;
2114 dest = gimple_call_arg (stmt, 0);
2115 flag = gimple_call_arg (stmt, 1);
2116 size = gimple_call_arg (stmt, 2);
2117 fmt = gimple_call_arg (stmt, 3);
2118
2119 if (! tree_fits_uhwi_p (size))
2120 return false;
2121
2122 len = NULL_TREE;
2123
2124 if (!init_target_chars ())
2125 return false;
2126
2127 /* Check whether the format is a literal string constant. */
2128 fmt_str = c_getstr (fmt);
2129 if (fmt_str != NULL)
2130 {
2131 /* If the format doesn't contain % args or %%, we know the size. */
2132 if (strchr (fmt_str, target_percent) == 0)
cbdd87d4 2133 {
fef5a0d9
RB
2134 if (fcode != BUILT_IN_SPRINTF_CHK || nargs == 4)
2135 len = build_int_cstu (size_type_node, strlen (fmt_str));
2136 }
2137 /* If the format is "%s" and first ... argument is a string literal,
2138 we know the size too. */
2139 else if (fcode == BUILT_IN_SPRINTF_CHK
2140 && strcmp (fmt_str, target_percent_s) == 0)
2141 {
2142 tree arg;
cbdd87d4 2143
fef5a0d9
RB
2144 if (nargs == 5)
2145 {
2146 arg = gimple_call_arg (stmt, 4);
2147 if (POINTER_TYPE_P (TREE_TYPE (arg)))
2148 {
2149 len = c_strlen (arg, 1);
2150 if (! len || ! tree_fits_uhwi_p (len))
2151 len = NULL_TREE;
2152 }
2153 }
2154 }
2155 }
cbdd87d4 2156
fef5a0d9
RB
2157 if (! integer_all_onesp (size))
2158 {
2159 if (! len || ! tree_int_cst_lt (len, size))
2160 return false;
2161 }
cbdd87d4 2162
fef5a0d9
RB
2163 /* Only convert __{,v}sprintf_chk to {,v}sprintf if flag is 0
2164 or if format doesn't contain % chars or is "%s". */
2165 if (! integer_zerop (flag))
2166 {
2167 if (fmt_str == NULL)
2168 return false;
2169 if (strchr (fmt_str, target_percent) != NULL
2170 && strcmp (fmt_str, target_percent_s))
2171 return false;
2172 }
cbdd87d4 2173
fef5a0d9
RB
2174 /* If __builtin_{,v}sprintf_chk is used, assume {,v}sprintf is available. */
2175 fn = builtin_decl_explicit (fcode == BUILT_IN_VSPRINTF_CHK
2176 ? BUILT_IN_VSPRINTF : BUILT_IN_SPRINTF);
2177 if (!fn)
2178 return false;
2179
2180 /* Replace the called function and the first 4 argument by 2 retaining
2181 trailing varargs. */
2182 gimple_call_set_fndecl (stmt, fn);
2183 gimple_call_set_fntype (stmt, TREE_TYPE (fn));
2184 gimple_call_set_arg (stmt, 0, dest);
2185 gimple_call_set_arg (stmt, 1, fmt);
2186 for (unsigned i = 2; i < gimple_call_num_args (stmt) - 2; ++i)
2187 gimple_call_set_arg (stmt, i, gimple_call_arg (stmt, i + 2));
2188 gimple_set_num_ops (stmt, gimple_num_ops (stmt) - 2);
2189 fold_stmt (gsi);
2190 return true;
2191}
2192
35770bb2
RB
2193/* Simplify a call to the sprintf builtin with arguments DEST, FMT, and ORIG.
2194 ORIG may be null if this is a 2-argument call. We don't attempt to
2195 simplify calls with more than 3 arguments.
2196
2197 Return NULL_TREE if no simplification was possible, otherwise return the
2198 simplified form of the call as a tree. If IGNORED is true, it means that
2199 the caller does not use the returned value of the function. */
2200
2201static bool
dcb7fae2 2202gimple_fold_builtin_sprintf (gimple_stmt_iterator *gsi)
35770bb2
RB
2203{
2204 gimple stmt = gsi_stmt (*gsi);
2205 tree dest = gimple_call_arg (stmt, 0);
2206 tree fmt = gimple_call_arg (stmt, 1);
2207 tree orig = NULL_TREE;
2208 const char *fmt_str = NULL;
2209
2210 /* Verify the required arguments in the original call. We deal with two
2211 types of sprintf() calls: 'sprintf (str, fmt)' and
2212 'sprintf (dest, "%s", orig)'. */
2213 if (gimple_call_num_args (stmt) > 3)
2214 return false;
2215
2216 if (gimple_call_num_args (stmt) == 3)
2217 orig = gimple_call_arg (stmt, 2);
2218
2219 /* Check whether the format is a literal string constant. */
2220 fmt_str = c_getstr (fmt);
2221 if (fmt_str == NULL)
2222 return false;
2223
2224 if (!init_target_chars ())
2225 return false;
2226
2227 /* If the format doesn't contain % args or %%, use strcpy. */
2228 if (strchr (fmt_str, target_percent) == NULL)
2229 {
2230 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2231
2232 if (!fn)
2233 return false;
2234
2235 /* Don't optimize sprintf (buf, "abc", ptr++). */
2236 if (orig)
2237 return false;
2238
2239 /* Convert sprintf (str, fmt) into strcpy (str, fmt) when
2240 'format' is known to contain no % formats. */
2241 gimple_seq stmts = NULL;
2242 gimple repl = gimple_build_call (fn, 2, dest, fmt);
2243 gimple_seq_add_stmt_without_update (&stmts, repl);
2244 if (gimple_call_lhs (stmt))
2245 {
2246 repl = gimple_build_assign (gimple_call_lhs (stmt),
2247 build_int_cst (integer_type_node,
2248 strlen (fmt_str)));
2249 gimple_seq_add_stmt_without_update (&stmts, repl);
2250 gsi_replace_with_seq_vops (gsi, stmts);
2251 /* gsi now points at the assignment to the lhs, get a
2252 stmt iterator to the memcpy call.
2253 ??? We can't use gsi_for_stmt as that doesn't work when the
2254 CFG isn't built yet. */
2255 gimple_stmt_iterator gsi2 = *gsi;
2256 gsi_prev (&gsi2);
2257 fold_stmt (&gsi2);
2258 }
2259 else
2260 {
2261 gsi_replace_with_seq_vops (gsi, stmts);
2262 fold_stmt (gsi);
2263 }
2264 return true;
2265 }
2266
2267 /* If the format is "%s", use strcpy if the result isn't used. */
2268 else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
2269 {
2270 tree fn;
2271 fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2272
2273 if (!fn)
2274 return false;
2275
2276 /* Don't crash on sprintf (str1, "%s"). */
2277 if (!orig)
2278 return false;
2279
dcb7fae2
RB
2280 tree orig_len = NULL_TREE;
2281 if (gimple_call_lhs (stmt))
35770bb2 2282 {
dcb7fae2 2283 orig_len = get_maxval_strlen (orig, 0);
d7e78447 2284 if (!orig_len)
35770bb2
RB
2285 return false;
2286 }
2287
2288 /* Convert sprintf (str1, "%s", str2) into strcpy (str1, str2). */
2289 gimple_seq stmts = NULL;
2290 gimple repl = gimple_build_call (fn, 2, dest, orig);
2291 gimple_seq_add_stmt_without_update (&stmts, repl);
2292 if (gimple_call_lhs (stmt))
2293 {
d7e78447
RB
2294 if (!useless_type_conversion_p (integer_type_node,
2295 TREE_TYPE (orig_len)))
2296 orig_len = fold_convert (integer_type_node, orig_len);
2297 repl = gimple_build_assign (gimple_call_lhs (stmt), orig_len);
35770bb2
RB
2298 gimple_seq_add_stmt_without_update (&stmts, repl);
2299 gsi_replace_with_seq_vops (gsi, stmts);
2300 /* gsi now points at the assignment to the lhs, get a
2301 stmt iterator to the memcpy call.
2302 ??? We can't use gsi_for_stmt as that doesn't work when the
2303 CFG isn't built yet. */
2304 gimple_stmt_iterator gsi2 = *gsi;
2305 gsi_prev (&gsi2);
2306 fold_stmt (&gsi2);
2307 }
2308 else
2309 {
2310 gsi_replace_with_seq_vops (gsi, stmts);
2311 fold_stmt (gsi);
2312 }
2313 return true;
2314 }
2315 return false;
2316}
2317
d7e78447
RB
2318/* Simplify a call to the snprintf builtin with arguments DEST, DESTSIZE,
2319 FMT, and ORIG. ORIG may be null if this is a 3-argument call. We don't
2320 attempt to simplify calls with more than 4 arguments.
35770bb2 2321
d7e78447
RB
2322 Return NULL_TREE if no simplification was possible, otherwise return the
2323 simplified form of the call as a tree. If IGNORED is true, it means that
2324 the caller does not use the returned value of the function. */
2325
2326static bool
dcb7fae2 2327gimple_fold_builtin_snprintf (gimple_stmt_iterator *gsi)
d7e78447 2328{
538dd0b7 2329 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
d7e78447
RB
2330 tree dest = gimple_call_arg (stmt, 0);
2331 tree destsize = gimple_call_arg (stmt, 1);
2332 tree fmt = gimple_call_arg (stmt, 2);
2333 tree orig = NULL_TREE;
2334 const char *fmt_str = NULL;
2335
2336 if (gimple_call_num_args (stmt) > 4)
2337 return false;
2338
2339 if (gimple_call_num_args (stmt) == 4)
2340 orig = gimple_call_arg (stmt, 3);
2341
2342 if (!tree_fits_uhwi_p (destsize))
2343 return false;
2344 unsigned HOST_WIDE_INT destlen = tree_to_uhwi (destsize);
2345
2346 /* Check whether the format is a literal string constant. */
2347 fmt_str = c_getstr (fmt);
2348 if (fmt_str == NULL)
2349 return false;
2350
2351 if (!init_target_chars ())
2352 return false;
2353
2354 /* If the format doesn't contain % args or %%, use strcpy. */
2355 if (strchr (fmt_str, target_percent) == NULL)
2356 {
2357 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2358 if (!fn)
2359 return false;
2360
2361 /* Don't optimize snprintf (buf, 4, "abc", ptr++). */
2362 if (orig)
2363 return false;
2364
2365 /* We could expand this as
2366 memcpy (str, fmt, cst - 1); str[cst - 1] = '\0';
2367 or to
2368 memcpy (str, fmt_with_nul_at_cstm1, cst);
2369 but in the former case that might increase code size
2370 and in the latter case grow .rodata section too much.
2371 So punt for now. */
2372 size_t len = strlen (fmt_str);
2373 if (len >= destlen)
2374 return false;
2375
2376 gimple_seq stmts = NULL;
2377 gimple repl = gimple_build_call (fn, 2, dest, fmt);
2378 gimple_seq_add_stmt_without_update (&stmts, repl);
2379 if (gimple_call_lhs (stmt))
2380 {
2381 repl = gimple_build_assign (gimple_call_lhs (stmt),
2382 build_int_cst (integer_type_node, len));
2383 gimple_seq_add_stmt_without_update (&stmts, repl);
2384 gsi_replace_with_seq_vops (gsi, stmts);
2385 /* gsi now points at the assignment to the lhs, get a
2386 stmt iterator to the memcpy call.
2387 ??? We can't use gsi_for_stmt as that doesn't work when the
2388 CFG isn't built yet. */
2389 gimple_stmt_iterator gsi2 = *gsi;
2390 gsi_prev (&gsi2);
2391 fold_stmt (&gsi2);
2392 }
2393 else
2394 {
2395 gsi_replace_with_seq_vops (gsi, stmts);
2396 fold_stmt (gsi);
2397 }
2398 return true;
2399 }
2400
2401 /* If the format is "%s", use strcpy if the result isn't used. */
2402 else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
2403 {
2404 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2405 if (!fn)
2406 return false;
2407
2408 /* Don't crash on snprintf (str1, cst, "%s"). */
2409 if (!orig)
2410 return false;
2411
dcb7fae2 2412 tree orig_len = get_maxval_strlen (orig, 0);
d7e78447 2413 if (!orig_len)
dcb7fae2 2414 return false;
d7e78447
RB
2415
2416 /* We could expand this as
2417 memcpy (str1, str2, cst - 1); str1[cst - 1] = '\0';
2418 or to
2419 memcpy (str1, str2_with_nul_at_cstm1, cst);
2420 but in the former case that might increase code size
2421 and in the latter case grow .rodata section too much.
2422 So punt for now. */
2423 if (compare_tree_int (orig_len, destlen) >= 0)
2424 return false;
2425
2426 /* Convert snprintf (str1, cst, "%s", str2) into
2427 strcpy (str1, str2) if strlen (str2) < cst. */
2428 gimple_seq stmts = NULL;
2429 gimple repl = gimple_build_call (fn, 2, dest, orig);
2430 gimple_seq_add_stmt_without_update (&stmts, repl);
2431 if (gimple_call_lhs (stmt))
2432 {
2433 if (!useless_type_conversion_p (integer_type_node,
2434 TREE_TYPE (orig_len)))
2435 orig_len = fold_convert (integer_type_node, orig_len);
2436 repl = gimple_build_assign (gimple_call_lhs (stmt), orig_len);
2437 gimple_seq_add_stmt_without_update (&stmts, repl);
2438 gsi_replace_with_seq_vops (gsi, stmts);
2439 /* gsi now points at the assignment to the lhs, get a
2440 stmt iterator to the memcpy call.
2441 ??? We can't use gsi_for_stmt as that doesn't work when the
2442 CFG isn't built yet. */
2443 gimple_stmt_iterator gsi2 = *gsi;
2444 gsi_prev (&gsi2);
2445 fold_stmt (&gsi2);
2446 }
2447 else
2448 {
2449 gsi_replace_with_seq_vops (gsi, stmts);
2450 fold_stmt (gsi);
2451 }
2452 return true;
2453 }
2454 return false;
2455}
35770bb2 2456
fef5a0d9
RB
2457
2458/* Fold a call to __builtin_strlen with known length LEN. */
2459
2460static bool
dcb7fae2 2461gimple_fold_builtin_strlen (gimple_stmt_iterator *gsi)
fef5a0d9 2462{
dcb7fae2
RB
2463 gimple stmt = gsi_stmt (*gsi);
2464 tree len = get_maxval_strlen (gimple_call_arg (stmt, 0), 0);
fef5a0d9
RB
2465 if (!len)
2466 return false;
2813904b 2467 len = force_gimple_operand_gsi (gsi, len, true, NULL, true, GSI_SAME_STMT);
fef5a0d9
RB
2468 replace_call_with_value (gsi, len);
2469 return true;
cbdd87d4
RG
2470}
2471
2472
dcb7fae2
RB
2473/* Fold the non-target builtin at *GSI and return whether any simplification
2474 was made. */
cbdd87d4 2475
fef5a0d9 2476static bool
dcb7fae2 2477gimple_fold_builtin (gimple_stmt_iterator *gsi)
cbdd87d4 2478{
538dd0b7 2479 gcall *stmt = as_a <gcall *>(gsi_stmt (*gsi));
fef5a0d9 2480 tree callee = gimple_call_fndecl (stmt);
cbdd87d4 2481
dcb7fae2
RB
2482 /* Give up for always_inline inline builtins until they are
2483 inlined. */
2484 if (avoid_folding_inline_builtin (callee))
2485 return false;
cbdd87d4 2486
cbdd87d4
RG
2487 switch (DECL_FUNCTION_CODE (callee))
2488 {
dcb7fae2
RB
2489 case BUILT_IN_BZERO:
2490 return gimple_fold_builtin_memset (gsi, integer_zero_node,
2491 gimple_call_arg (stmt, 1));
2492 case BUILT_IN_MEMSET:
2493 return gimple_fold_builtin_memset (gsi,
2494 gimple_call_arg (stmt, 1),
2495 gimple_call_arg (stmt, 2));
2496 case BUILT_IN_BCOPY:
2497 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 1),
2498 gimple_call_arg (stmt, 0), 3);
2499 case BUILT_IN_MEMCPY:
2500 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
2501 gimple_call_arg (stmt, 1), 0);
2502 case BUILT_IN_MEMPCPY:
2503 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
2504 gimple_call_arg (stmt, 1), 1);
2505 case BUILT_IN_MEMMOVE:
2506 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
2507 gimple_call_arg (stmt, 1), 3);
2508 case BUILT_IN_SPRINTF_CHK:
2509 case BUILT_IN_VSPRINTF_CHK:
2510 return gimple_fold_builtin_sprintf_chk (gsi, DECL_FUNCTION_CODE (callee));
2511 case BUILT_IN_STRCAT_CHK:
2512 return gimple_fold_builtin_strcat_chk (gsi);
745583f9
RB
2513 case BUILT_IN_STRNCAT_CHK:
2514 return gimple_fold_builtin_strncat_chk (gsi);
cbdd87d4 2515 case BUILT_IN_STRLEN:
dcb7fae2 2516 return gimple_fold_builtin_strlen (gsi);
cbdd87d4 2517 case BUILT_IN_STRCPY:
dcb7fae2 2518 return gimple_fold_builtin_strcpy (gsi,
fef5a0d9 2519 gimple_call_arg (stmt, 0),
dcb7fae2 2520 gimple_call_arg (stmt, 1));
cbdd87d4 2521 case BUILT_IN_STRNCPY:
dcb7fae2 2522 return gimple_fold_builtin_strncpy (gsi,
fef5a0d9
RB
2523 gimple_call_arg (stmt, 0),
2524 gimple_call_arg (stmt, 1),
dcb7fae2 2525 gimple_call_arg (stmt, 2));
9a7eefec 2526 case BUILT_IN_STRCAT:
dcb7fae2
RB
2527 return gimple_fold_builtin_strcat (gsi, gimple_call_arg (stmt, 0),
2528 gimple_call_arg (stmt, 1));
cbdd87d4 2529 case BUILT_IN_FPUTS:
dcb7fae2
RB
2530 return gimple_fold_builtin_fputs (gsi, gimple_call_arg (stmt, 0),
2531 gimple_call_arg (stmt, 1), false);
cbdd87d4 2532 case BUILT_IN_FPUTS_UNLOCKED:
dcb7fae2
RB
2533 return gimple_fold_builtin_fputs (gsi, gimple_call_arg (stmt, 0),
2534 gimple_call_arg (stmt, 1), true);
cbdd87d4
RG
2535 case BUILT_IN_MEMCPY_CHK:
2536 case BUILT_IN_MEMPCPY_CHK:
2537 case BUILT_IN_MEMMOVE_CHK:
2538 case BUILT_IN_MEMSET_CHK:
dcb7fae2 2539 return gimple_fold_builtin_memory_chk (gsi,
fef5a0d9
RB
2540 gimple_call_arg (stmt, 0),
2541 gimple_call_arg (stmt, 1),
2542 gimple_call_arg (stmt, 2),
2543 gimple_call_arg (stmt, 3),
fef5a0d9 2544 DECL_FUNCTION_CODE (callee));
cbdd87d4
RG
2545 case BUILT_IN_STRCPY_CHK:
2546 case BUILT_IN_STPCPY_CHK:
dcb7fae2 2547 return gimple_fold_builtin_stxcpy_chk (gsi,
fef5a0d9
RB
2548 gimple_call_arg (stmt, 0),
2549 gimple_call_arg (stmt, 1),
2550 gimple_call_arg (stmt, 2),
fef5a0d9 2551 DECL_FUNCTION_CODE (callee));
cbdd87d4 2552 case BUILT_IN_STRNCPY_CHK:
f3fc9b80 2553 case BUILT_IN_STPNCPY_CHK:
fef5a0d9
RB
2554 return gimple_fold_builtin_stxncpy_chk (gsi,
2555 gimple_call_arg (stmt, 0),
2556 gimple_call_arg (stmt, 1),
2557 gimple_call_arg (stmt, 2),
2558 gimple_call_arg (stmt, 3),
fef5a0d9 2559 DECL_FUNCTION_CODE (callee));
cbdd87d4
RG
2560 case BUILT_IN_SNPRINTF_CHK:
2561 case BUILT_IN_VSNPRINTF_CHK:
dcb7fae2 2562 return gimple_fold_builtin_snprintf_chk (gsi,
fef5a0d9 2563 DECL_FUNCTION_CODE (callee));
d7e78447 2564 case BUILT_IN_SNPRINTF:
dcb7fae2 2565 return gimple_fold_builtin_snprintf (gsi);
d7e78447 2566 case BUILT_IN_SPRINTF:
dcb7fae2 2567 return gimple_fold_builtin_sprintf (gsi);
fef5a0d9
RB
2568 default:;
2569 }
2570
2571 /* Try the generic builtin folder. */
2572 bool ignore = (gimple_call_lhs (stmt) == NULL);
2573 tree result = fold_call_stmt (stmt, ignore);
2574 if (result)
2575 {
2576 if (ignore)
2577 STRIP_NOPS (result);
2578 else
2579 result = fold_convert (gimple_call_return_type (stmt), result);
2580 if (!update_call_from_tree (gsi, result))
2581 gimplify_and_update_call_from_tree (gsi, result);
2582 return true;
2583 }
2584
2585 return false;
2586}
2587
1304953e
JJ
2588/* Return true if ARG0 CODE ARG1 in infinite signed precision operation
2589 doesn't fit into TYPE. The test for overflow should be regardless of
2590 -fwrapv, and even for unsigned types. */
2591
2592bool
2593arith_overflowed_p (enum tree_code code, const_tree type,
2594 const_tree arg0, const_tree arg1)
2595{
2596 typedef FIXED_WIDE_INT (WIDE_INT_MAX_PRECISION * 2) widest2_int;
2597 typedef generic_wide_int <wi::extended_tree <WIDE_INT_MAX_PRECISION * 2> >
2598 widest2_int_cst;
2599 widest2_int warg0 = widest2_int_cst (arg0);
2600 widest2_int warg1 = widest2_int_cst (arg1);
2601 widest2_int wres;
2602 switch (code)
2603 {
2604 case PLUS_EXPR: wres = wi::add (warg0, warg1); break;
2605 case MINUS_EXPR: wres = wi::sub (warg0, warg1); break;
2606 case MULT_EXPR: wres = wi::mul (warg0, warg1); break;
2607 default: gcc_unreachable ();
2608 }
2609 signop sign = TYPE_SIGN (type);
2610 if (sign == UNSIGNED && wi::neg_p (wres))
2611 return true;
2612 return wi::min_precision (wres, sign) > TYPE_PRECISION (type);
2613}
2614
cbdd87d4
RG
2615/* Attempt to fold a call statement referenced by the statement iterator GSI.
2616 The statement may be replaced by another statement, e.g., if the call
2617 simplifies to a constant value. Return true if any changes were made.
2618 It is assumed that the operands have been previously folded. */
2619
e021c122 2620static bool
ceeffab0 2621gimple_fold_call (gimple_stmt_iterator *gsi, bool inplace)
cbdd87d4 2622{
538dd0b7 2623 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3b45a007 2624 tree callee;
e021c122
RG
2625 bool changed = false;
2626 unsigned i;
cbdd87d4 2627
e021c122
RG
2628 /* Fold *& in call arguments. */
2629 for (i = 0; i < gimple_call_num_args (stmt); ++i)
2630 if (REFERENCE_CLASS_P (gimple_call_arg (stmt, i)))
2631 {
2632 tree tmp = maybe_fold_reference (gimple_call_arg (stmt, i), false);
2633 if (tmp)
2634 {
2635 gimple_call_set_arg (stmt, i, tmp);
2636 changed = true;
2637 }
2638 }
3b45a007
RG
2639
2640 /* Check for virtual calls that became direct calls. */
2641 callee = gimple_call_fn (stmt);
25583c4f 2642 if (callee && TREE_CODE (callee) == OBJ_TYPE_REF)
3b45a007 2643 {
49c471e3
MJ
2644 if (gimple_call_addr_fndecl (OBJ_TYPE_REF_EXPR (callee)) != NULL_TREE)
2645 {
450ad0cd
JH
2646 if (dump_file && virtual_method_call_p (callee)
2647 && !possible_polymorphic_call_target_p
6f8091fc
JH
2648 (callee, stmt, cgraph_node::get (gimple_call_addr_fndecl
2649 (OBJ_TYPE_REF_EXPR (callee)))))
450ad0cd
JH
2650 {
2651 fprintf (dump_file,
a70e9985 2652 "Type inheritance inconsistent devirtualization of ");
450ad0cd
JH
2653 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2654 fprintf (dump_file, " to ");
2655 print_generic_expr (dump_file, callee, TDF_SLIM);
2656 fprintf (dump_file, "\n");
2657 }
2658
49c471e3 2659 gimple_call_set_fn (stmt, OBJ_TYPE_REF_EXPR (callee));
e021c122
RG
2660 changed = true;
2661 }
a70e9985 2662 else if (flag_devirtualize && !inplace && virtual_method_call_p (callee))
e021c122 2663 {
61dd6a2e
JH
2664 bool final;
2665 vec <cgraph_node *>targets
058d0a90 2666 = possible_polymorphic_call_targets (callee, stmt, &final);
2b5f0895 2667 if (final && targets.length () <= 1 && dbg_cnt (devirt))
e021c122 2668 {
a70e9985 2669 tree lhs = gimple_call_lhs (stmt);
2b5f0895
XDL
2670 if (dump_enabled_p ())
2671 {
807b7d62 2672 location_t loc = gimple_location_safe (stmt);
2b5f0895
XDL
2673 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, loc,
2674 "folding virtual function call to %s\n",
2675 targets.length () == 1
2676 ? targets[0]->name ()
2677 : "__builtin_unreachable");
2678 }
61dd6a2e 2679 if (targets.length () == 1)
cf3e5a89
JJ
2680 {
2681 gimple_call_set_fndecl (stmt, targets[0]->decl);
2682 changed = true;
a70e9985
JJ
2683 /* If the call becomes noreturn, remove the lhs. */
2684 if (lhs && (gimple_call_flags (stmt) & ECF_NORETURN))
2685 {
2686 if (TREE_CODE (lhs) == SSA_NAME)
2687 {
2688 tree var = create_tmp_var (TREE_TYPE (lhs), NULL);
2689 tree def = get_or_create_ssa_default_def (cfun, var);
2690 gimple new_stmt = gimple_build_assign (lhs, def);
2691 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
2692 }
2693 gimple_call_set_lhs (stmt, NULL_TREE);
2694 }
cf3e5a89 2695 }
a70e9985 2696 else
cf3e5a89
JJ
2697 {
2698 tree fndecl = builtin_decl_implicit (BUILT_IN_UNREACHABLE);
2699 gimple new_stmt = gimple_build_call (fndecl, 0);
2700 gimple_set_location (new_stmt, gimple_location (stmt));
a70e9985
JJ
2701 if (lhs && TREE_CODE (lhs) == SSA_NAME)
2702 {
2703 tree var = create_tmp_var (TREE_TYPE (lhs), NULL);
2704 tree def = get_or_create_ssa_default_def (cfun, var);
eb14a79f
ML
2705
2706 /* To satisfy condition for
2707 cgraph_update_edges_for_call_stmt_node,
2708 we need to preserve GIMPLE_CALL statement
2709 at position of GSI iterator. */
a70e9985 2710 update_call_from_tree (gsi, def);
eb14a79f 2711 gsi_insert_before (gsi, new_stmt, GSI_NEW_STMT);
a70e9985
JJ
2712 }
2713 else
42e52a51
RB
2714 {
2715 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
2716 gimple_set_vdef (new_stmt, gimple_vdef (stmt));
2717 gsi_replace (gsi, new_stmt, false);
2718 }
cf3e5a89
JJ
2719 return true;
2720 }
e021c122 2721 }
49c471e3 2722 }
e021c122 2723 }
49c471e3 2724
f2d3d07e
RH
2725 /* Check for indirect calls that became direct calls, and then
2726 no longer require a static chain. */
2727 if (gimple_call_chain (stmt))
2728 {
2729 tree fn = gimple_call_fndecl (stmt);
2730 if (fn && !DECL_STATIC_CHAIN (fn))
2731 {
2732 gimple_call_set_chain (stmt, NULL);
2733 changed = true;
2734 }
2735 else
2736 {
2737 tree tmp = maybe_fold_reference (gimple_call_chain (stmt), false);
2738 if (tmp)
2739 {
2740 gimple_call_set_chain (stmt, tmp);
2741 changed = true;
2742 }
2743 }
2744 }
2745
e021c122
RG
2746 if (inplace)
2747 return changed;
2748
2749 /* Check for builtins that CCP can handle using information not
2750 available in the generic fold routines. */
fef5a0d9
RB
2751 if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
2752 {
2753 if (gimple_fold_builtin (gsi))
2754 changed = true;
2755 }
2756 else if (gimple_call_builtin_p (stmt, BUILT_IN_MD))
e021c122 2757 {
ea679d55 2758 changed |= targetm.gimple_fold_builtin (gsi);
3b45a007 2759 }
368b454d 2760 else if (gimple_call_internal_p (stmt))
ed9c79e1 2761 {
368b454d
JJ
2762 enum tree_code subcode = ERROR_MARK;
2763 tree result = NULL_TREE;
1304953e
JJ
2764 bool cplx_result = false;
2765 tree overflow = NULL_TREE;
368b454d
JJ
2766 switch (gimple_call_internal_fn (stmt))
2767 {
2768 case IFN_BUILTIN_EXPECT:
2769 result = fold_builtin_expect (gimple_location (stmt),
2770 gimple_call_arg (stmt, 0),
2771 gimple_call_arg (stmt, 1),
2772 gimple_call_arg (stmt, 2));
2773 break;
0e82f089
MP
2774 case IFN_UBSAN_OBJECT_SIZE:
2775 if (integer_all_onesp (gimple_call_arg (stmt, 2))
2776 || (TREE_CODE (gimple_call_arg (stmt, 1)) == INTEGER_CST
2777 && TREE_CODE (gimple_call_arg (stmt, 2)) == INTEGER_CST
2778 && tree_int_cst_le (gimple_call_arg (stmt, 1),
2779 gimple_call_arg (stmt, 2))))
2780 {
2781 gsi_replace (gsi, gimple_build_nop (), true);
2782 unlink_stmt_vdef (stmt);
2783 release_defs (stmt);
2784 return true;
2785 }
2786 break;
368b454d
JJ
2787 case IFN_UBSAN_CHECK_ADD:
2788 subcode = PLUS_EXPR;
2789 break;
2790 case IFN_UBSAN_CHECK_SUB:
2791 subcode = MINUS_EXPR;
2792 break;
2793 case IFN_UBSAN_CHECK_MUL:
2794 subcode = MULT_EXPR;
2795 break;
1304953e
JJ
2796 case IFN_ADD_OVERFLOW:
2797 subcode = PLUS_EXPR;
2798 cplx_result = true;
2799 break;
2800 case IFN_SUB_OVERFLOW:
2801 subcode = MINUS_EXPR;
2802 cplx_result = true;
2803 break;
2804 case IFN_MUL_OVERFLOW:
2805 subcode = MULT_EXPR;
2806 cplx_result = true;
2807 break;
368b454d
JJ
2808 default:
2809 break;
2810 }
2811 if (subcode != ERROR_MARK)
2812 {
2813 tree arg0 = gimple_call_arg (stmt, 0);
2814 tree arg1 = gimple_call_arg (stmt, 1);
1304953e
JJ
2815 tree type = TREE_TYPE (arg0);
2816 if (cplx_result)
2817 {
2818 tree lhs = gimple_call_lhs (stmt);
2819 if (lhs == NULL_TREE)
2820 type = NULL_TREE;
2821 else
2822 type = TREE_TYPE (TREE_TYPE (lhs));
2823 }
2824 if (type == NULL_TREE)
2825 ;
368b454d 2826 /* x = y + 0; x = y - 0; x = y * 0; */
1304953e
JJ
2827 else if (integer_zerop (arg1))
2828 result = subcode == MULT_EXPR ? integer_zero_node : arg0;
368b454d
JJ
2829 /* x = 0 + y; x = 0 * y; */
2830 else if (subcode != MINUS_EXPR && integer_zerop (arg0))
1304953e 2831 result = subcode == MULT_EXPR ? integer_zero_node : arg1;
368b454d
JJ
2832 /* x = y - y; */
2833 else if (subcode == MINUS_EXPR && operand_equal_p (arg0, arg1, 0))
1304953e 2834 result = integer_zero_node;
368b454d 2835 /* x = y * 1; x = 1 * y; */
1304953e
JJ
2836 else if (subcode == MULT_EXPR && integer_onep (arg1))
2837 result = arg0;
2838 else if (subcode == MULT_EXPR && integer_onep (arg0))
2839 result = arg1;
2840 else if (TREE_CODE (arg0) == INTEGER_CST
2841 && TREE_CODE (arg1) == INTEGER_CST)
368b454d 2842 {
1304953e
JJ
2843 if (cplx_result)
2844 result = int_const_binop (subcode, fold_convert (type, arg0),
2845 fold_convert (type, arg1));
2846 else
2847 result = int_const_binop (subcode, arg0, arg1);
2848 if (result && arith_overflowed_p (subcode, type, arg0, arg1))
2849 {
2850 if (cplx_result)
2851 overflow = build_one_cst (type);
2852 else
2853 result = NULL_TREE;
2854 }
2855 }
2856 if (result)
2857 {
2858 if (result == integer_zero_node)
2859 result = build_zero_cst (type);
2860 else if (cplx_result && TREE_TYPE (result) != type)
2861 {
2862 if (TREE_CODE (result) == INTEGER_CST)
2863 {
2864 if (arith_overflowed_p (PLUS_EXPR, type, result,
2865 integer_zero_node))
2866 overflow = build_one_cst (type);
2867 }
2868 else if ((!TYPE_UNSIGNED (TREE_TYPE (result))
2869 && TYPE_UNSIGNED (type))
2870 || (TYPE_PRECISION (type)
2871 < (TYPE_PRECISION (TREE_TYPE (result))
2872 + (TYPE_UNSIGNED (TREE_TYPE (result))
2873 && !TYPE_UNSIGNED (type)))))
2874 result = NULL_TREE;
2875 if (result)
2876 result = fold_convert (type, result);
2877 }
368b454d
JJ
2878 }
2879 }
1304953e 2880
ed9c79e1
JJ
2881 if (result)
2882 {
1304953e
JJ
2883 if (TREE_CODE (result) == INTEGER_CST && TREE_OVERFLOW (result))
2884 result = drop_tree_overflow (result);
2885 if (cplx_result)
2886 {
2887 if (overflow == NULL_TREE)
2888 overflow = build_zero_cst (TREE_TYPE (result));
2889 tree ctype = build_complex_type (TREE_TYPE (result));
2890 if (TREE_CODE (result) == INTEGER_CST
2891 && TREE_CODE (overflow) == INTEGER_CST)
2892 result = build_complex (ctype, result, overflow);
2893 else
2894 result = build2_loc (gimple_location (stmt), COMPLEX_EXPR,
2895 ctype, result, overflow);
2896 }
ed9c79e1
JJ
2897 if (!update_call_from_tree (gsi, result))
2898 gimplify_and_update_call_from_tree (gsi, result);
2899 changed = true;
2900 }
2901 }
3b45a007 2902
e021c122 2903 return changed;
cbdd87d4
RG
2904}
2905
e0ee10ed
RB
2906
2907/* Worker for fold_stmt_1 dispatch to pattern based folding with
2908 gimple_simplify.
2909
2910 Replaces *GSI with the simplification result in RCODE and OPS
2911 and the associated statements in *SEQ. Does the replacement
2912 according to INPLACE and returns true if the operation succeeded. */
2913
2914static bool
2915replace_stmt_with_simplification (gimple_stmt_iterator *gsi,
2916 code_helper rcode, tree *ops,
2917 gimple_seq *seq, bool inplace)
2918{
2919 gimple stmt = gsi_stmt (*gsi);
2920
2921 /* Play safe and do not allow abnormals to be mentioned in
2922 newly created statements. See also maybe_push_res_to_seq. */
2923 if ((TREE_CODE (ops[0]) == SSA_NAME
2924 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ops[0]))
2925 || (ops[1]
2926 && TREE_CODE (ops[1]) == SSA_NAME
2927 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ops[1]))
2928 || (ops[2]
2929 && TREE_CODE (ops[2]) == SSA_NAME
2930 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ops[2])))
2931 return false;
2932
538dd0b7 2933 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
e0ee10ed
RB
2934 {
2935 gcc_assert (rcode.is_tree_code ());
2936 if (TREE_CODE_CLASS ((enum tree_code)rcode) == tcc_comparison
2937 /* GIMPLE_CONDs condition may not throw. */
2938 && (!flag_exceptions
2939 || !cfun->can_throw_non_call_exceptions
2940 || !operation_could_trap_p (rcode,
2941 FLOAT_TYPE_P (TREE_TYPE (ops[0])),
2942 false, NULL_TREE)))
538dd0b7 2943 gimple_cond_set_condition (cond_stmt, rcode, ops[0], ops[1]);
e0ee10ed 2944 else if (rcode == SSA_NAME)
538dd0b7 2945 gimple_cond_set_condition (cond_stmt, NE_EXPR, ops[0],
e0ee10ed
RB
2946 build_zero_cst (TREE_TYPE (ops[0])));
2947 else if (rcode == INTEGER_CST)
2948 {
2949 if (integer_zerop (ops[0]))
538dd0b7 2950 gimple_cond_make_false (cond_stmt);
e0ee10ed 2951 else
538dd0b7 2952 gimple_cond_make_true (cond_stmt);
e0ee10ed
RB
2953 }
2954 else if (!inplace)
2955 {
2956 tree res = maybe_push_res_to_seq (rcode, boolean_type_node,
2957 ops, seq);
2958 if (!res)
2959 return false;
538dd0b7 2960 gimple_cond_set_condition (cond_stmt, NE_EXPR, res,
e0ee10ed
RB
2961 build_zero_cst (TREE_TYPE (res)));
2962 }
2963 else
2964 return false;
2965 if (dump_file && (dump_flags & TDF_DETAILS))
2966 {
2967 fprintf (dump_file, "gimple_simplified to ");
2968 if (!gimple_seq_empty_p (*seq))
2969 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
2970 print_gimple_stmt (dump_file, gsi_stmt (*gsi),
2971 0, TDF_SLIM);
2972 }
2973 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
2974 return true;
2975 }
2976 else if (is_gimple_assign (stmt)
2977 && rcode.is_tree_code ())
2978 {
2979 if (!inplace
f3582e54 2980 || gimple_num_ops (stmt) > get_gimple_rhs_num_ops (rcode))
e0ee10ed
RB
2981 {
2982 maybe_build_generic_op (rcode,
2983 TREE_TYPE (gimple_assign_lhs (stmt)),
2984 &ops[0], ops[1], ops[2]);
00d66391 2985 gimple_assign_set_rhs_with_ops (gsi, rcode, ops[0], ops[1], ops[2]);
e0ee10ed
RB
2986 if (dump_file && (dump_flags & TDF_DETAILS))
2987 {
2988 fprintf (dump_file, "gimple_simplified to ");
2989 if (!gimple_seq_empty_p (*seq))
2990 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
2991 print_gimple_stmt (dump_file, gsi_stmt (*gsi),
2992 0, TDF_SLIM);
2993 }
2994 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
2995 return true;
2996 }
2997 }
2998 else if (!inplace)
2999 {
3000 if (gimple_has_lhs (stmt))
3001 {
3002 tree lhs = gimple_get_lhs (stmt);
3003 maybe_push_res_to_seq (rcode, TREE_TYPE (lhs),
3004 ops, seq, lhs);
3005 if (dump_file && (dump_flags & TDF_DETAILS))
3006 {
3007 fprintf (dump_file, "gimple_simplified to ");
3008 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
3009 }
3010 gsi_replace_with_seq_vops (gsi, *seq);
3011 return true;
3012 }
3013 else
3014 gcc_unreachable ();
3015 }
3016
3017 return false;
3018}
3019
040292e7
RB
3020/* Canonicalize MEM_REFs invariant address operand after propagation. */
3021
3022static bool
3023maybe_canonicalize_mem_ref_addr (tree *t)
3024{
3025 bool res = false;
3026
3027 if (TREE_CODE (*t) == ADDR_EXPR)
3028 t = &TREE_OPERAND (*t, 0);
3029
3030 while (handled_component_p (*t))
3031 t = &TREE_OPERAND (*t, 0);
3032
3033 /* Canonicalize MEM [&foo.bar, 0] which appears after propagating
3034 of invariant addresses into a SSA name MEM_REF address. */
3035 if (TREE_CODE (*t) == MEM_REF
3036 || TREE_CODE (*t) == TARGET_MEM_REF)
3037 {
3038 tree addr = TREE_OPERAND (*t, 0);
3039 if (TREE_CODE (addr) == ADDR_EXPR
3040 && (TREE_CODE (TREE_OPERAND (addr, 0)) == MEM_REF
3041 || handled_component_p (TREE_OPERAND (addr, 0))))
3042 {
3043 tree base;
3044 HOST_WIDE_INT coffset;
3045 base = get_addr_base_and_unit_offset (TREE_OPERAND (addr, 0),
3046 &coffset);
3047 if (!base)
3048 gcc_unreachable ();
3049
3050 TREE_OPERAND (*t, 0) = build_fold_addr_expr (base);
3051 TREE_OPERAND (*t, 1) = int_const_binop (PLUS_EXPR,
3052 TREE_OPERAND (*t, 1),
3053 size_int (coffset));
3054 res = true;
3055 }
3056 gcc_checking_assert (TREE_CODE (TREE_OPERAND (*t, 0)) == DEBUG_EXPR_DECL
3057 || is_gimple_mem_ref_addr (TREE_OPERAND (*t, 0)));
3058 }
3059
3060 /* Canonicalize back MEM_REFs to plain reference trees if the object
3061 accessed is a decl that has the same access semantics as the MEM_REF. */
3062 if (TREE_CODE (*t) == MEM_REF
3063 && TREE_CODE (TREE_OPERAND (*t, 0)) == ADDR_EXPR
f3dccf50
RB
3064 && integer_zerop (TREE_OPERAND (*t, 1))
3065 && MR_DEPENDENCE_CLIQUE (*t) == 0)
040292e7
RB
3066 {
3067 tree decl = TREE_OPERAND (TREE_OPERAND (*t, 0), 0);
3068 tree alias_type = TREE_TYPE (TREE_OPERAND (*t, 1));
3069 if (/* Same volatile qualification. */
3070 TREE_THIS_VOLATILE (*t) == TREE_THIS_VOLATILE (decl)
3071 /* Same TBAA behavior with -fstrict-aliasing. */
3072 && !TYPE_REF_CAN_ALIAS_ALL (alias_type)
3073 && (TYPE_MAIN_VARIANT (TREE_TYPE (decl))
3074 == TYPE_MAIN_VARIANT (TREE_TYPE (alias_type)))
3075 /* Same alignment. */
3076 && TYPE_ALIGN (TREE_TYPE (decl)) == TYPE_ALIGN (TREE_TYPE (*t))
3077 /* We have to look out here to not drop a required conversion
3078 from the rhs to the lhs if *t appears on the lhs or vice-versa
3079 if it appears on the rhs. Thus require strict type
3080 compatibility. */
3081 && types_compatible_p (TREE_TYPE (*t), TREE_TYPE (decl)))
3082 {
3083 *t = TREE_OPERAND (TREE_OPERAND (*t, 0), 0);
3084 res = true;
3085 }
3086 }
3087
3088 /* Canonicalize TARGET_MEM_REF in particular with respect to
3089 the indexes becoming constant. */
3090 else if (TREE_CODE (*t) == TARGET_MEM_REF)
3091 {
3092 tree tem = maybe_fold_tmr (*t);
3093 if (tem)
3094 {
3095 *t = tem;
3096 res = true;
3097 }
3098 }
3099
3100 return res;
3101}
3102
cbdd87d4
RG
3103/* Worker for both fold_stmt and fold_stmt_inplace. The INPLACE argument
3104 distinguishes both cases. */
3105
3106static bool
e0ee10ed 3107fold_stmt_1 (gimple_stmt_iterator *gsi, bool inplace, tree (*valueize) (tree))
cbdd87d4
RG
3108{
3109 bool changed = false;
3110 gimple stmt = gsi_stmt (*gsi);
3111 unsigned i;
3112
040292e7
RB
3113 /* First do required canonicalization of [TARGET_]MEM_REF addresses
3114 after propagation.
3115 ??? This shouldn't be done in generic folding but in the
3116 propagation helpers which also know whether an address was
3117 propagated. */
3118 switch (gimple_code (stmt))
3119 {
3120 case GIMPLE_ASSIGN:
3121 if (gimple_assign_rhs_class (stmt) == GIMPLE_SINGLE_RHS)
3122 {
3123 tree *rhs = gimple_assign_rhs1_ptr (stmt);
3124 if ((REFERENCE_CLASS_P (*rhs)
3125 || TREE_CODE (*rhs) == ADDR_EXPR)
3126 && maybe_canonicalize_mem_ref_addr (rhs))
3127 changed = true;
3128 tree *lhs = gimple_assign_lhs_ptr (stmt);
3129 if (REFERENCE_CLASS_P (*lhs)
3130 && maybe_canonicalize_mem_ref_addr (lhs))
3131 changed = true;
3132 }
3133 break;
3134 case GIMPLE_CALL:
3135 {
3136 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3137 {
3138 tree *arg = gimple_call_arg_ptr (stmt, i);
3139 if (REFERENCE_CLASS_P (*arg)
3140 && maybe_canonicalize_mem_ref_addr (arg))
3141 changed = true;
3142 }
3143 tree *lhs = gimple_call_lhs_ptr (stmt);
3144 if (*lhs
3145 && REFERENCE_CLASS_P (*lhs)
3146 && maybe_canonicalize_mem_ref_addr (lhs))
3147 changed = true;
3148 break;
3149 }
3150 case GIMPLE_ASM:
3151 {
538dd0b7
DM
3152 gasm *asm_stmt = as_a <gasm *> (stmt);
3153 for (i = 0; i < gimple_asm_noutputs (asm_stmt); ++i)
040292e7 3154 {
538dd0b7 3155 tree link = gimple_asm_output_op (asm_stmt, i);
040292e7
RB
3156 tree op = TREE_VALUE (link);
3157 if (REFERENCE_CLASS_P (op)
3158 && maybe_canonicalize_mem_ref_addr (&TREE_VALUE (link)))
3159 changed = true;
3160 }
538dd0b7 3161 for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
040292e7 3162 {
538dd0b7 3163 tree link = gimple_asm_input_op (asm_stmt, i);
040292e7
RB
3164 tree op = TREE_VALUE (link);
3165 if ((REFERENCE_CLASS_P (op)
3166 || TREE_CODE (op) == ADDR_EXPR)
3167 && maybe_canonicalize_mem_ref_addr (&TREE_VALUE (link)))
3168 changed = true;
3169 }
3170 }
3171 break;
3172 case GIMPLE_DEBUG:
3173 if (gimple_debug_bind_p (stmt))
3174 {
3175 tree *val = gimple_debug_bind_get_value_ptr (stmt);
3176 if (*val
3177 && (REFERENCE_CLASS_P (*val)
3178 || TREE_CODE (*val) == ADDR_EXPR)
3179 && maybe_canonicalize_mem_ref_addr (val))
3180 changed = true;
3181 }
3182 break;
3183 default:;
3184 }
3185
e0ee10ed
RB
3186 /* Dispatch to pattern-based folding. */
3187 if (!inplace
3188 || is_gimple_assign (stmt)
3189 || gimple_code (stmt) == GIMPLE_COND)
3190 {
3191 gimple_seq seq = NULL;
3192 code_helper rcode;
3193 tree ops[3] = {};
3194 if (gimple_simplify (stmt, &rcode, ops, inplace ? NULL : &seq, valueize))
3195 {
3196 if (replace_stmt_with_simplification (gsi, rcode, ops, &seq, inplace))
3197 changed = true;
3198 else
3199 gimple_seq_discard (seq);
3200 }
3201 }
3202
3203 stmt = gsi_stmt (*gsi);
3204
cbdd87d4
RG
3205 /* Fold the main computation performed by the statement. */
3206 switch (gimple_code (stmt))
3207 {
3208 case GIMPLE_ASSIGN:
3209 {
3210 unsigned old_num_ops = gimple_num_ops (stmt);
5fbcc0ed 3211 enum tree_code subcode = gimple_assign_rhs_code (stmt);
cbdd87d4 3212 tree lhs = gimple_assign_lhs (stmt);
5fbcc0ed
RG
3213 tree new_rhs;
3214 /* First canonicalize operand order. This avoids building new
3215 trees if this is the only thing fold would later do. */
3216 if ((commutative_tree_code (subcode)
3217 || commutative_ternary_tree_code (subcode))
3218 && tree_swap_operands_p (gimple_assign_rhs1 (stmt),
3219 gimple_assign_rhs2 (stmt), false))
3220 {
3221 tree tem = gimple_assign_rhs1 (stmt);
3222 gimple_assign_set_rhs1 (stmt, gimple_assign_rhs2 (stmt));
3223 gimple_assign_set_rhs2 (stmt, tem);
3224 changed = true;
3225 }
3226 new_rhs = fold_gimple_assign (gsi);
cbdd87d4
RG
3227 if (new_rhs
3228 && !useless_type_conversion_p (TREE_TYPE (lhs),
3229 TREE_TYPE (new_rhs)))
3230 new_rhs = fold_convert (TREE_TYPE (lhs), new_rhs);
3231 if (new_rhs
3232 && (!inplace
3233 || get_gimple_rhs_num_ops (TREE_CODE (new_rhs)) < old_num_ops))
3234 {
3235 gimple_assign_set_rhs_from_tree (gsi, new_rhs);
3236 changed = true;
3237 }
3238 break;
3239 }
3240
3241 case GIMPLE_COND:
538dd0b7 3242 changed |= fold_gimple_cond (as_a <gcond *> (stmt));
cbdd87d4
RG
3243 break;
3244
3245 case GIMPLE_CALL:
ceeffab0 3246 changed |= gimple_fold_call (gsi, inplace);
cbdd87d4
RG
3247 break;
3248
3249 case GIMPLE_ASM:
3250 /* Fold *& in asm operands. */
38384150 3251 {
538dd0b7 3252 gasm *asm_stmt = as_a <gasm *> (stmt);
38384150
JJ
3253 size_t noutputs;
3254 const char **oconstraints;
3255 const char *constraint;
3256 bool allows_mem, allows_reg;
3257
538dd0b7 3258 noutputs = gimple_asm_noutputs (asm_stmt);
38384150
JJ
3259 oconstraints = XALLOCAVEC (const char *, noutputs);
3260
538dd0b7 3261 for (i = 0; i < gimple_asm_noutputs (asm_stmt); ++i)
38384150 3262 {
538dd0b7 3263 tree link = gimple_asm_output_op (asm_stmt, i);
38384150
JJ
3264 tree op = TREE_VALUE (link);
3265 oconstraints[i]
3266 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
3267 if (REFERENCE_CLASS_P (op)
3268 && (op = maybe_fold_reference (op, true)) != NULL_TREE)
3269 {
3270 TREE_VALUE (link) = op;
3271 changed = true;
3272 }
3273 }
538dd0b7 3274 for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
38384150 3275 {
538dd0b7 3276 tree link = gimple_asm_input_op (asm_stmt, i);
38384150
JJ
3277 tree op = TREE_VALUE (link);
3278 constraint
3279 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
3280 parse_input_constraint (&constraint, 0, 0, noutputs, 0,
3281 oconstraints, &allows_mem, &allows_reg);
3282 if (REFERENCE_CLASS_P (op)
3283 && (op = maybe_fold_reference (op, !allows_reg && allows_mem))
3284 != NULL_TREE)
3285 {
3286 TREE_VALUE (link) = op;
3287 changed = true;
3288 }
3289 }
3290 }
cbdd87d4
RG
3291 break;
3292
bd422c4a
RG
3293 case GIMPLE_DEBUG:
3294 if (gimple_debug_bind_p (stmt))
3295 {
3296 tree val = gimple_debug_bind_get_value (stmt);
3297 if (val
3298 && REFERENCE_CLASS_P (val))
3299 {
3300 tree tem = maybe_fold_reference (val, false);
3301 if (tem)
3302 {
3303 gimple_debug_bind_set_value (stmt, tem);
3304 changed = true;
3305 }
3306 }
3e888a5e
RG
3307 else if (val
3308 && TREE_CODE (val) == ADDR_EXPR)
3309 {
3310 tree ref = TREE_OPERAND (val, 0);
3311 tree tem = maybe_fold_reference (ref, false);
3312 if (tem)
3313 {
3314 tem = build_fold_addr_expr_with_type (tem, TREE_TYPE (val));
3315 gimple_debug_bind_set_value (stmt, tem);
3316 changed = true;
3317 }
3318 }
bd422c4a
RG
3319 }
3320 break;
3321
cbdd87d4
RG
3322 default:;
3323 }
3324
3325 stmt = gsi_stmt (*gsi);
3326
37376165
RB
3327 /* Fold *& on the lhs. */
3328 if (gimple_has_lhs (stmt))
cbdd87d4
RG
3329 {
3330 tree lhs = gimple_get_lhs (stmt);
3331 if (lhs && REFERENCE_CLASS_P (lhs))
3332 {
3333 tree new_lhs = maybe_fold_reference (lhs, true);
3334 if (new_lhs)
3335 {
3336 gimple_set_lhs (stmt, new_lhs);
3337 changed = true;
3338 }
3339 }
3340 }
3341
3342 return changed;
3343}
3344
e0ee10ed
RB
3345/* Valueziation callback that ends up not following SSA edges. */
3346
3347tree
3348no_follow_ssa_edges (tree)
3349{
3350 return NULL_TREE;
3351}
3352
45cc9f96
RB
3353/* Valueization callback that ends up following single-use SSA edges only. */
3354
3355tree
3356follow_single_use_edges (tree val)
3357{
3358 if (TREE_CODE (val) == SSA_NAME
3359 && !has_single_use (val))
3360 return NULL_TREE;
3361 return val;
3362}
3363
cbdd87d4
RG
3364/* Fold the statement pointed to by GSI. In some cases, this function may
3365 replace the whole statement with a new one. Returns true iff folding
3366 makes any changes.
3367 The statement pointed to by GSI should be in valid gimple form but may
3368 be in unfolded state as resulting from for example constant propagation
3369 which can produce *&x = 0. */
3370
3371bool
3372fold_stmt (gimple_stmt_iterator *gsi)
3373{
e0ee10ed
RB
3374 return fold_stmt_1 (gsi, false, no_follow_ssa_edges);
3375}
3376
3377bool
3378fold_stmt (gimple_stmt_iterator *gsi, tree (*valueize) (tree))
3379{
3380 return fold_stmt_1 (gsi, false, valueize);
cbdd87d4
RG
3381}
3382
59401b92 3383/* Perform the minimal folding on statement *GSI. Only operations like
cbdd87d4
RG
3384 *&x created by constant propagation are handled. The statement cannot
3385 be replaced with a new one. Return true if the statement was
3386 changed, false otherwise.
59401b92 3387 The statement *GSI should be in valid gimple form but may
cbdd87d4
RG
3388 be in unfolded state as resulting from for example constant propagation
3389 which can produce *&x = 0. */
3390
3391bool
59401b92 3392fold_stmt_inplace (gimple_stmt_iterator *gsi)
cbdd87d4 3393{
59401b92 3394 gimple stmt = gsi_stmt (*gsi);
e0ee10ed 3395 bool changed = fold_stmt_1 (gsi, true, no_follow_ssa_edges);
59401b92 3396 gcc_assert (gsi_stmt (*gsi) == stmt);
cbdd87d4
RG
3397 return changed;
3398}
3399
e89065a1
SL
3400/* Canonicalize and possibly invert the boolean EXPR; return NULL_TREE
3401 if EXPR is null or we don't know how.
3402 If non-null, the result always has boolean type. */
3403
3404static tree
3405canonicalize_bool (tree expr, bool invert)
3406{
3407 if (!expr)
3408 return NULL_TREE;
3409 else if (invert)
3410 {
3411 if (integer_nonzerop (expr))
3412 return boolean_false_node;
3413 else if (integer_zerop (expr))
3414 return boolean_true_node;
3415 else if (TREE_CODE (expr) == SSA_NAME)
3416 return fold_build2 (EQ_EXPR, boolean_type_node, expr,
3417 build_int_cst (TREE_TYPE (expr), 0));
3418 else if (TREE_CODE_CLASS (TREE_CODE (expr)) == tcc_comparison)
3419 return fold_build2 (invert_tree_comparison (TREE_CODE (expr), false),
3420 boolean_type_node,
3421 TREE_OPERAND (expr, 0),
3422 TREE_OPERAND (expr, 1));
3423 else
3424 return NULL_TREE;
3425 }
3426 else
3427 {
3428 if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE)
3429 return expr;
3430 if (integer_nonzerop (expr))
3431 return boolean_true_node;
3432 else if (integer_zerop (expr))
3433 return boolean_false_node;
3434 else if (TREE_CODE (expr) == SSA_NAME)
3435 return fold_build2 (NE_EXPR, boolean_type_node, expr,
3436 build_int_cst (TREE_TYPE (expr), 0));
3437 else if (TREE_CODE_CLASS (TREE_CODE (expr)) == tcc_comparison)
3438 return fold_build2 (TREE_CODE (expr),
3439 boolean_type_node,
3440 TREE_OPERAND (expr, 0),
3441 TREE_OPERAND (expr, 1));
3442 else
3443 return NULL_TREE;
3444 }
3445}
3446
3447/* Check to see if a boolean expression EXPR is logically equivalent to the
3448 comparison (OP1 CODE OP2). Check for various identities involving
3449 SSA_NAMEs. */
3450
3451static bool
3452same_bool_comparison_p (const_tree expr, enum tree_code code,
3453 const_tree op1, const_tree op2)
3454{
3455 gimple s;
3456
3457 /* The obvious case. */
3458 if (TREE_CODE (expr) == code
3459 && operand_equal_p (TREE_OPERAND (expr, 0), op1, 0)
3460 && operand_equal_p (TREE_OPERAND (expr, 1), op2, 0))
3461 return true;
3462
3463 /* Check for comparing (name, name != 0) and the case where expr
3464 is an SSA_NAME with a definition matching the comparison. */
3465 if (TREE_CODE (expr) == SSA_NAME
3466 && TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE)
3467 {
3468 if (operand_equal_p (expr, op1, 0))
3469 return ((code == NE_EXPR && integer_zerop (op2))
3470 || (code == EQ_EXPR && integer_nonzerop (op2)));
3471 s = SSA_NAME_DEF_STMT (expr);
3472 if (is_gimple_assign (s)
3473 && gimple_assign_rhs_code (s) == code
3474 && operand_equal_p (gimple_assign_rhs1 (s), op1, 0)
3475 && operand_equal_p (gimple_assign_rhs2 (s), op2, 0))
3476 return true;
3477 }
3478
3479 /* If op1 is of the form (name != 0) or (name == 0), and the definition
3480 of name is a comparison, recurse. */
3481 if (TREE_CODE (op1) == SSA_NAME
3482 && TREE_CODE (TREE_TYPE (op1)) == BOOLEAN_TYPE)
3483 {
3484 s = SSA_NAME_DEF_STMT (op1);
3485 if (is_gimple_assign (s)
3486 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison)
3487 {
3488 enum tree_code c = gimple_assign_rhs_code (s);
3489 if ((c == NE_EXPR && integer_zerop (op2))
3490 || (c == EQ_EXPR && integer_nonzerop (op2)))
3491 return same_bool_comparison_p (expr, c,
3492 gimple_assign_rhs1 (s),
3493 gimple_assign_rhs2 (s));
3494 if ((c == EQ_EXPR && integer_zerop (op2))
3495 || (c == NE_EXPR && integer_nonzerop (op2)))
3496 return same_bool_comparison_p (expr,
3497 invert_tree_comparison (c, false),
3498 gimple_assign_rhs1 (s),
3499 gimple_assign_rhs2 (s));
3500 }
3501 }
3502 return false;
3503}
3504
3505/* Check to see if two boolean expressions OP1 and OP2 are logically
3506 equivalent. */
3507
3508static bool
3509same_bool_result_p (const_tree op1, const_tree op2)
3510{
3511 /* Simple cases first. */
3512 if (operand_equal_p (op1, op2, 0))
3513 return true;
3514
3515 /* Check the cases where at least one of the operands is a comparison.
3516 These are a bit smarter than operand_equal_p in that they apply some
3517 identifies on SSA_NAMEs. */
3518 if (TREE_CODE_CLASS (TREE_CODE (op2)) == tcc_comparison
3519 && same_bool_comparison_p (op1, TREE_CODE (op2),
3520 TREE_OPERAND (op2, 0),
3521 TREE_OPERAND (op2, 1)))
3522 return true;
3523 if (TREE_CODE_CLASS (TREE_CODE (op1)) == tcc_comparison
3524 && same_bool_comparison_p (op2, TREE_CODE (op1),
3525 TREE_OPERAND (op1, 0),
3526 TREE_OPERAND (op1, 1)))
3527 return true;
3528
3529 /* Default case. */
3530 return false;
3531}
3532
3533/* Forward declarations for some mutually recursive functions. */
3534
3535static tree
3536and_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
3537 enum tree_code code2, tree op2a, tree op2b);
3538static tree
3539and_var_with_comparison (tree var, bool invert,
3540 enum tree_code code2, tree op2a, tree op2b);
3541static tree
3542and_var_with_comparison_1 (gimple stmt,
3543 enum tree_code code2, tree op2a, tree op2b);
3544static tree
3545or_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
3546 enum tree_code code2, tree op2a, tree op2b);
3547static tree
3548or_var_with_comparison (tree var, bool invert,
3549 enum tree_code code2, tree op2a, tree op2b);
3550static tree
3551or_var_with_comparison_1 (gimple stmt,
3552 enum tree_code code2, tree op2a, tree op2b);
3553
3554/* Helper function for and_comparisons_1: try to simplify the AND of the
3555 ssa variable VAR with the comparison specified by (OP2A CODE2 OP2B).
3556 If INVERT is true, invert the value of the VAR before doing the AND.
3557 Return NULL_EXPR if we can't simplify this to a single expression. */
3558
3559static tree
3560and_var_with_comparison (tree var, bool invert,
3561 enum tree_code code2, tree op2a, tree op2b)
3562{
3563 tree t;
3564 gimple stmt = SSA_NAME_DEF_STMT (var);
3565
3566 /* We can only deal with variables whose definitions are assignments. */
3567 if (!is_gimple_assign (stmt))
3568 return NULL_TREE;
3569
3570 /* If we have an inverted comparison, apply DeMorgan's law and rewrite
3571 !var AND (op2a code2 op2b) => !(var OR !(op2a code2 op2b))
3572 Then we only have to consider the simpler non-inverted cases. */
3573 if (invert)
3574 t = or_var_with_comparison_1 (stmt,
3575 invert_tree_comparison (code2, false),
3576 op2a, op2b);
3577 else
3578 t = and_var_with_comparison_1 (stmt, code2, op2a, op2b);
3579 return canonicalize_bool (t, invert);
3580}
3581
3582/* Try to simplify the AND of the ssa variable defined by the assignment
3583 STMT with the comparison specified by (OP2A CODE2 OP2B).
3584 Return NULL_EXPR if we can't simplify this to a single expression. */
3585
3586static tree
3587and_var_with_comparison_1 (gimple stmt,
3588 enum tree_code code2, tree op2a, tree op2b)
3589{
3590 tree var = gimple_assign_lhs (stmt);
3591 tree true_test_var = NULL_TREE;
3592 tree false_test_var = NULL_TREE;
3593 enum tree_code innercode = gimple_assign_rhs_code (stmt);
3594
3595 /* Check for identities like (var AND (var == 0)) => false. */
3596 if (TREE_CODE (op2a) == SSA_NAME
3597 && TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE)
3598 {
3599 if ((code2 == NE_EXPR && integer_zerop (op2b))
3600 || (code2 == EQ_EXPR && integer_nonzerop (op2b)))
3601 {
3602 true_test_var = op2a;
3603 if (var == true_test_var)
3604 return var;
3605 }
3606 else if ((code2 == EQ_EXPR && integer_zerop (op2b))
3607 || (code2 == NE_EXPR && integer_nonzerop (op2b)))
3608 {
3609 false_test_var = op2a;
3610 if (var == false_test_var)
3611 return boolean_false_node;
3612 }
3613 }
3614
3615 /* If the definition is a comparison, recurse on it. */
3616 if (TREE_CODE_CLASS (innercode) == tcc_comparison)
3617 {
3618 tree t = and_comparisons_1 (innercode,
3619 gimple_assign_rhs1 (stmt),
3620 gimple_assign_rhs2 (stmt),
3621 code2,
3622 op2a,
3623 op2b);
3624 if (t)
3625 return t;
3626 }
3627
3628 /* If the definition is an AND or OR expression, we may be able to
3629 simplify by reassociating. */
eb9820c0
KT
3630 if (TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE
3631 && (innercode == BIT_AND_EXPR || innercode == BIT_IOR_EXPR))
e89065a1
SL
3632 {
3633 tree inner1 = gimple_assign_rhs1 (stmt);
3634 tree inner2 = gimple_assign_rhs2 (stmt);
3635 gimple s;
3636 tree t;
3637 tree partial = NULL_TREE;
eb9820c0 3638 bool is_and = (innercode == BIT_AND_EXPR);
e89065a1
SL
3639
3640 /* Check for boolean identities that don't require recursive examination
3641 of inner1/inner2:
3642 inner1 AND (inner1 AND inner2) => inner1 AND inner2 => var
3643 inner1 AND (inner1 OR inner2) => inner1
3644 !inner1 AND (inner1 AND inner2) => false
3645 !inner1 AND (inner1 OR inner2) => !inner1 AND inner2
3646 Likewise for similar cases involving inner2. */
3647 if (inner1 == true_test_var)
3648 return (is_and ? var : inner1);
3649 else if (inner2 == true_test_var)
3650 return (is_and ? var : inner2);
3651 else if (inner1 == false_test_var)
3652 return (is_and
3653 ? boolean_false_node
3654 : and_var_with_comparison (inner2, false, code2, op2a, op2b));
3655 else if (inner2 == false_test_var)
3656 return (is_and
3657 ? boolean_false_node
3658 : and_var_with_comparison (inner1, false, code2, op2a, op2b));
3659
3660 /* Next, redistribute/reassociate the AND across the inner tests.
3661 Compute the first partial result, (inner1 AND (op2a code op2b)) */
3662 if (TREE_CODE (inner1) == SSA_NAME
3663 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner1))
3664 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
3665 && (t = maybe_fold_and_comparisons (gimple_assign_rhs_code (s),
3666 gimple_assign_rhs1 (s),
3667 gimple_assign_rhs2 (s),
3668 code2, op2a, op2b)))
3669 {
3670 /* Handle the AND case, where we are reassociating:
3671 (inner1 AND inner2) AND (op2a code2 op2b)
3672 => (t AND inner2)
3673 If the partial result t is a constant, we win. Otherwise
3674 continue on to try reassociating with the other inner test. */
3675 if (is_and)
3676 {
3677 if (integer_onep (t))
3678 return inner2;
3679 else if (integer_zerop (t))
3680 return boolean_false_node;
3681 }
3682
3683 /* Handle the OR case, where we are redistributing:
3684 (inner1 OR inner2) AND (op2a code2 op2b)
3685 => (t OR (inner2 AND (op2a code2 op2b))) */
8236c8eb
JJ
3686 else if (integer_onep (t))
3687 return boolean_true_node;
3688
3689 /* Save partial result for later. */
3690 partial = t;
e89065a1
SL
3691 }
3692
3693 /* Compute the second partial result, (inner2 AND (op2a code op2b)) */
3694 if (TREE_CODE (inner2) == SSA_NAME
3695 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner2))
3696 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
3697 && (t = maybe_fold_and_comparisons (gimple_assign_rhs_code (s),
3698 gimple_assign_rhs1 (s),
3699 gimple_assign_rhs2 (s),
3700 code2, op2a, op2b)))
3701 {
3702 /* Handle the AND case, where we are reassociating:
3703 (inner1 AND inner2) AND (op2a code2 op2b)
3704 => (inner1 AND t) */
3705 if (is_and)
3706 {
3707 if (integer_onep (t))
3708 return inner1;
3709 else if (integer_zerop (t))
3710 return boolean_false_node;
8236c8eb
JJ
3711 /* If both are the same, we can apply the identity
3712 (x AND x) == x. */
3713 else if (partial && same_bool_result_p (t, partial))
3714 return t;
e89065a1
SL
3715 }
3716
3717 /* Handle the OR case. where we are redistributing:
3718 (inner1 OR inner2) AND (op2a code2 op2b)
3719 => (t OR (inner1 AND (op2a code2 op2b)))
3720 => (t OR partial) */
3721 else
3722 {
3723 if (integer_onep (t))
3724 return boolean_true_node;
3725 else if (partial)
3726 {
3727 /* We already got a simplification for the other
3728 operand to the redistributed OR expression. The
3729 interesting case is when at least one is false.
3730 Or, if both are the same, we can apply the identity
3731 (x OR x) == x. */
3732 if (integer_zerop (partial))
3733 return t;
3734 else if (integer_zerop (t))
3735 return partial;
3736 else if (same_bool_result_p (t, partial))
3737 return t;
3738 }
3739 }
3740 }
3741 }
3742 return NULL_TREE;
3743}
3744
3745/* Try to simplify the AND of two comparisons defined by
3746 (OP1A CODE1 OP1B) and (OP2A CODE2 OP2B), respectively.
3747 If this can be done without constructing an intermediate value,
3748 return the resulting tree; otherwise NULL_TREE is returned.
3749 This function is deliberately asymmetric as it recurses on SSA_DEFs
3750 in the first comparison but not the second. */
3751
3752static tree
3753and_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
3754 enum tree_code code2, tree op2a, tree op2b)
3755{
ae22ac3c 3756 tree truth_type = truth_type_for (TREE_TYPE (op1a));
31ed6226 3757
e89065a1
SL
3758 /* First check for ((x CODE1 y) AND (x CODE2 y)). */
3759 if (operand_equal_p (op1a, op2a, 0)
3760 && operand_equal_p (op1b, op2b, 0))
3761 {
eb9820c0 3762 /* Result will be either NULL_TREE, or a combined comparison. */
e89065a1
SL
3763 tree t = combine_comparisons (UNKNOWN_LOCATION,
3764 TRUTH_ANDIF_EXPR, code1, code2,
31ed6226 3765 truth_type, op1a, op1b);
e89065a1
SL
3766 if (t)
3767 return t;
3768 }
3769
3770 /* Likewise the swapped case of the above. */
3771 if (operand_equal_p (op1a, op2b, 0)
3772 && operand_equal_p (op1b, op2a, 0))
3773 {
eb9820c0 3774 /* Result will be either NULL_TREE, or a combined comparison. */
e89065a1
SL
3775 tree t = combine_comparisons (UNKNOWN_LOCATION,
3776 TRUTH_ANDIF_EXPR, code1,
3777 swap_tree_comparison (code2),
31ed6226 3778 truth_type, op1a, op1b);
e89065a1
SL
3779 if (t)
3780 return t;
3781 }
3782
3783 /* If both comparisons are of the same value against constants, we might
3784 be able to merge them. */
3785 if (operand_equal_p (op1a, op2a, 0)
3786 && TREE_CODE (op1b) == INTEGER_CST
3787 && TREE_CODE (op2b) == INTEGER_CST)
3788 {
3789 int cmp = tree_int_cst_compare (op1b, op2b);
3790
3791 /* If we have (op1a == op1b), we should either be able to
3792 return that or FALSE, depending on whether the constant op1b
3793 also satisfies the other comparison against op2b. */
3794 if (code1 == EQ_EXPR)
3795 {
3796 bool done = true;
3797 bool val;
3798 switch (code2)
3799 {
3800 case EQ_EXPR: val = (cmp == 0); break;
3801 case NE_EXPR: val = (cmp != 0); break;
3802 case LT_EXPR: val = (cmp < 0); break;
3803 case GT_EXPR: val = (cmp > 0); break;
3804 case LE_EXPR: val = (cmp <= 0); break;
3805 case GE_EXPR: val = (cmp >= 0); break;
3806 default: done = false;
3807 }
3808 if (done)
3809 {
3810 if (val)
3811 return fold_build2 (code1, boolean_type_node, op1a, op1b);
3812 else
3813 return boolean_false_node;
3814 }
3815 }
3816 /* Likewise if the second comparison is an == comparison. */
3817 else if (code2 == EQ_EXPR)
3818 {
3819 bool done = true;
3820 bool val;
3821 switch (code1)
3822 {
3823 case EQ_EXPR: val = (cmp == 0); break;
3824 case NE_EXPR: val = (cmp != 0); break;
3825 case LT_EXPR: val = (cmp > 0); break;
3826 case GT_EXPR: val = (cmp < 0); break;
3827 case LE_EXPR: val = (cmp >= 0); break;
3828 case GE_EXPR: val = (cmp <= 0); break;
3829 default: done = false;
3830 }
3831 if (done)
3832 {
3833 if (val)
3834 return fold_build2 (code2, boolean_type_node, op2a, op2b);
3835 else
3836 return boolean_false_node;
3837 }
3838 }
3839
3840 /* Same business with inequality tests. */
3841 else if (code1 == NE_EXPR)
3842 {
3843 bool val;
3844 switch (code2)
3845 {
3846 case EQ_EXPR: val = (cmp != 0); break;
3847 case NE_EXPR: val = (cmp == 0); break;
3848 case LT_EXPR: val = (cmp >= 0); break;
3849 case GT_EXPR: val = (cmp <= 0); break;
3850 case LE_EXPR: val = (cmp > 0); break;
3851 case GE_EXPR: val = (cmp < 0); break;
3852 default:
3853 val = false;
3854 }
3855 if (val)
3856 return fold_build2 (code2, boolean_type_node, op2a, op2b);
3857 }
3858 else if (code2 == NE_EXPR)
3859 {
3860 bool val;
3861 switch (code1)
3862 {
3863 case EQ_EXPR: val = (cmp == 0); break;
3864 case NE_EXPR: val = (cmp != 0); break;
3865 case LT_EXPR: val = (cmp <= 0); break;
3866 case GT_EXPR: val = (cmp >= 0); break;
3867 case LE_EXPR: val = (cmp < 0); break;
3868 case GE_EXPR: val = (cmp > 0); break;
3869 default:
3870 val = false;
3871 }
3872 if (val)
3873 return fold_build2 (code1, boolean_type_node, op1a, op1b);
3874 }
3875
3876 /* Chose the more restrictive of two < or <= comparisons. */
3877 else if ((code1 == LT_EXPR || code1 == LE_EXPR)
3878 && (code2 == LT_EXPR || code2 == LE_EXPR))
3879 {
3880 if ((cmp < 0) || (cmp == 0 && code1 == LT_EXPR))
3881 return fold_build2 (code1, boolean_type_node, op1a, op1b);
3882 else
3883 return fold_build2 (code2, boolean_type_node, op2a, op2b);
3884 }
3885
3886 /* Likewise chose the more restrictive of two > or >= comparisons. */
3887 else if ((code1 == GT_EXPR || code1 == GE_EXPR)
3888 && (code2 == GT_EXPR || code2 == GE_EXPR))
3889 {
3890 if ((cmp > 0) || (cmp == 0 && code1 == GT_EXPR))
3891 return fold_build2 (code1, boolean_type_node, op1a, op1b);
3892 else
3893 return fold_build2 (code2, boolean_type_node, op2a, op2b);
3894 }
3895
3896 /* Check for singleton ranges. */
3897 else if (cmp == 0
3898 && ((code1 == LE_EXPR && code2 == GE_EXPR)
3899 || (code1 == GE_EXPR && code2 == LE_EXPR)))
3900 return fold_build2 (EQ_EXPR, boolean_type_node, op1a, op2b);
3901
3902 /* Check for disjoint ranges. */
3903 else if (cmp <= 0
3904 && (code1 == LT_EXPR || code1 == LE_EXPR)
3905 && (code2 == GT_EXPR || code2 == GE_EXPR))
3906 return boolean_false_node;
3907 else if (cmp >= 0
3908 && (code1 == GT_EXPR || code1 == GE_EXPR)
3909 && (code2 == LT_EXPR || code2 == LE_EXPR))
3910 return boolean_false_node;
3911 }
3912
3913 /* Perhaps the first comparison is (NAME != 0) or (NAME == 1) where
3914 NAME's definition is a truth value. See if there are any simplifications
3915 that can be done against the NAME's definition. */
3916 if (TREE_CODE (op1a) == SSA_NAME
3917 && (code1 == NE_EXPR || code1 == EQ_EXPR)
3918 && (integer_zerop (op1b) || integer_onep (op1b)))
3919 {
3920 bool invert = ((code1 == EQ_EXPR && integer_zerop (op1b))
3921 || (code1 == NE_EXPR && integer_onep (op1b)));
3922 gimple stmt = SSA_NAME_DEF_STMT (op1a);
3923 switch (gimple_code (stmt))
3924 {
3925 case GIMPLE_ASSIGN:
3926 /* Try to simplify by copy-propagating the definition. */
3927 return and_var_with_comparison (op1a, invert, code2, op2a, op2b);
3928
3929 case GIMPLE_PHI:
3930 /* If every argument to the PHI produces the same result when
3931 ANDed with the second comparison, we win.
3932 Do not do this unless the type is bool since we need a bool
3933 result here anyway. */
3934 if (TREE_CODE (TREE_TYPE (op1a)) == BOOLEAN_TYPE)
3935 {
3936 tree result = NULL_TREE;
3937 unsigned i;
3938 for (i = 0; i < gimple_phi_num_args (stmt); i++)
3939 {
3940 tree arg = gimple_phi_arg_def (stmt, i);
3941
3942 /* If this PHI has itself as an argument, ignore it.
3943 If all the other args produce the same result,
3944 we're still OK. */
3945 if (arg == gimple_phi_result (stmt))
3946 continue;
3947 else if (TREE_CODE (arg) == INTEGER_CST)
3948 {
3949 if (invert ? integer_nonzerop (arg) : integer_zerop (arg))
3950 {
3951 if (!result)
3952 result = boolean_false_node;
3953 else if (!integer_zerop (result))
3954 return NULL_TREE;
3955 }
3956 else if (!result)
3957 result = fold_build2 (code2, boolean_type_node,
3958 op2a, op2b);
3959 else if (!same_bool_comparison_p (result,
3960 code2, op2a, op2b))
3961 return NULL_TREE;
3962 }
0e8b84ec
JJ
3963 else if (TREE_CODE (arg) == SSA_NAME
3964 && !SSA_NAME_IS_DEFAULT_DEF (arg))
e89065a1 3965 {
6c66f733
JJ
3966 tree temp;
3967 gimple def_stmt = SSA_NAME_DEF_STMT (arg);
3968 /* In simple cases we can look through PHI nodes,
3969 but we have to be careful with loops.
3970 See PR49073. */
3971 if (! dom_info_available_p (CDI_DOMINATORS)
3972 || gimple_bb (def_stmt) == gimple_bb (stmt)
3973 || dominated_by_p (CDI_DOMINATORS,
3974 gimple_bb (def_stmt),
3975 gimple_bb (stmt)))
3976 return NULL_TREE;
3977 temp = and_var_with_comparison (arg, invert, code2,
3978 op2a, op2b);
e89065a1
SL
3979 if (!temp)
3980 return NULL_TREE;
3981 else if (!result)
3982 result = temp;
3983 else if (!same_bool_result_p (result, temp))
3984 return NULL_TREE;
3985 }
3986 else
3987 return NULL_TREE;
3988 }
3989 return result;
3990 }
3991
3992 default:
3993 break;
3994 }
3995 }
3996 return NULL_TREE;
3997}
3998
3999/* Try to simplify the AND of two comparisons, specified by
4000 (OP1A CODE1 OP1B) and (OP2B CODE2 OP2B), respectively.
4001 If this can be simplified to a single expression (without requiring
4002 introducing more SSA variables to hold intermediate values),
4003 return the resulting tree. Otherwise return NULL_TREE.
4004 If the result expression is non-null, it has boolean type. */
4005
4006tree
4007maybe_fold_and_comparisons (enum tree_code code1, tree op1a, tree op1b,
4008 enum tree_code code2, tree op2a, tree op2b)
4009{
4010 tree t = and_comparisons_1 (code1, op1a, op1b, code2, op2a, op2b);
4011 if (t)
4012 return t;
4013 else
4014 return and_comparisons_1 (code2, op2a, op2b, code1, op1a, op1b);
4015}
4016
4017/* Helper function for or_comparisons_1: try to simplify the OR of the
4018 ssa variable VAR with the comparison specified by (OP2A CODE2 OP2B).
4019 If INVERT is true, invert the value of VAR before doing the OR.
4020 Return NULL_EXPR if we can't simplify this to a single expression. */
4021
4022static tree
4023or_var_with_comparison (tree var, bool invert,
4024 enum tree_code code2, tree op2a, tree op2b)
4025{
4026 tree t;
4027 gimple stmt = SSA_NAME_DEF_STMT (var);
4028
4029 /* We can only deal with variables whose definitions are assignments. */
4030 if (!is_gimple_assign (stmt))
4031 return NULL_TREE;
4032
4033 /* If we have an inverted comparison, apply DeMorgan's law and rewrite
4034 !var OR (op2a code2 op2b) => !(var AND !(op2a code2 op2b))
4035 Then we only have to consider the simpler non-inverted cases. */
4036 if (invert)
4037 t = and_var_with_comparison_1 (stmt,
4038 invert_tree_comparison (code2, false),
4039 op2a, op2b);
4040 else
4041 t = or_var_with_comparison_1 (stmt, code2, op2a, op2b);
4042 return canonicalize_bool (t, invert);
4043}
4044
4045/* Try to simplify the OR of the ssa variable defined by the assignment
4046 STMT with the comparison specified by (OP2A CODE2 OP2B).
4047 Return NULL_EXPR if we can't simplify this to a single expression. */
4048
4049static tree
4050or_var_with_comparison_1 (gimple stmt,
4051 enum tree_code code2, tree op2a, tree op2b)
4052{
4053 tree var = gimple_assign_lhs (stmt);
4054 tree true_test_var = NULL_TREE;
4055 tree false_test_var = NULL_TREE;
4056 enum tree_code innercode = gimple_assign_rhs_code (stmt);
4057
4058 /* Check for identities like (var OR (var != 0)) => true . */
4059 if (TREE_CODE (op2a) == SSA_NAME
4060 && TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE)
4061 {
4062 if ((code2 == NE_EXPR && integer_zerop (op2b))
4063 || (code2 == EQ_EXPR && integer_nonzerop (op2b)))
4064 {
4065 true_test_var = op2a;
4066 if (var == true_test_var)
4067 return var;
4068 }
4069 else if ((code2 == EQ_EXPR && integer_zerop (op2b))
4070 || (code2 == NE_EXPR && integer_nonzerop (op2b)))
4071 {
4072 false_test_var = op2a;
4073 if (var == false_test_var)
4074 return boolean_true_node;
4075 }
4076 }
4077
4078 /* If the definition is a comparison, recurse on it. */
4079 if (TREE_CODE_CLASS (innercode) == tcc_comparison)
4080 {
4081 tree t = or_comparisons_1 (innercode,
4082 gimple_assign_rhs1 (stmt),
4083 gimple_assign_rhs2 (stmt),
4084 code2,
4085 op2a,
4086 op2b);
4087 if (t)
4088 return t;
4089 }
4090
4091 /* If the definition is an AND or OR expression, we may be able to
4092 simplify by reassociating. */
eb9820c0
KT
4093 if (TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE
4094 && (innercode == BIT_AND_EXPR || innercode == BIT_IOR_EXPR))
e89065a1
SL
4095 {
4096 tree inner1 = gimple_assign_rhs1 (stmt);
4097 tree inner2 = gimple_assign_rhs2 (stmt);
4098 gimple s;
4099 tree t;
4100 tree partial = NULL_TREE;
eb9820c0 4101 bool is_or = (innercode == BIT_IOR_EXPR);
e89065a1
SL
4102
4103 /* Check for boolean identities that don't require recursive examination
4104 of inner1/inner2:
4105 inner1 OR (inner1 OR inner2) => inner1 OR inner2 => var
4106 inner1 OR (inner1 AND inner2) => inner1
4107 !inner1 OR (inner1 OR inner2) => true
4108 !inner1 OR (inner1 AND inner2) => !inner1 OR inner2
4109 */
4110 if (inner1 == true_test_var)
4111 return (is_or ? var : inner1);
4112 else if (inner2 == true_test_var)
4113 return (is_or ? var : inner2);
4114 else if (inner1 == false_test_var)
4115 return (is_or
4116 ? boolean_true_node
4117 : or_var_with_comparison (inner2, false, code2, op2a, op2b));
4118 else if (inner2 == false_test_var)
4119 return (is_or
4120 ? boolean_true_node
4121 : or_var_with_comparison (inner1, false, code2, op2a, op2b));
4122
4123 /* Next, redistribute/reassociate the OR across the inner tests.
4124 Compute the first partial result, (inner1 OR (op2a code op2b)) */
4125 if (TREE_CODE (inner1) == SSA_NAME
4126 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner1))
4127 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
4128 && (t = maybe_fold_or_comparisons (gimple_assign_rhs_code (s),
4129 gimple_assign_rhs1 (s),
4130 gimple_assign_rhs2 (s),
4131 code2, op2a, op2b)))
4132 {
4133 /* Handle the OR case, where we are reassociating:
4134 (inner1 OR inner2) OR (op2a code2 op2b)
4135 => (t OR inner2)
4136 If the partial result t is a constant, we win. Otherwise
4137 continue on to try reassociating with the other inner test. */
8236c8eb 4138 if (is_or)
e89065a1
SL
4139 {
4140 if (integer_onep (t))
4141 return boolean_true_node;
4142 else if (integer_zerop (t))
4143 return inner2;
4144 }
4145
4146 /* Handle the AND case, where we are redistributing:
4147 (inner1 AND inner2) OR (op2a code2 op2b)
4148 => (t AND (inner2 OR (op2a code op2b))) */
8236c8eb
JJ
4149 else if (integer_zerop (t))
4150 return boolean_false_node;
4151
4152 /* Save partial result for later. */
4153 partial = t;
e89065a1
SL
4154 }
4155
4156 /* Compute the second partial result, (inner2 OR (op2a code op2b)) */
4157 if (TREE_CODE (inner2) == SSA_NAME
4158 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner2))
4159 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
4160 && (t = maybe_fold_or_comparisons (gimple_assign_rhs_code (s),
4161 gimple_assign_rhs1 (s),
4162 gimple_assign_rhs2 (s),
4163 code2, op2a, op2b)))
4164 {
4165 /* Handle the OR case, where we are reassociating:
4166 (inner1 OR inner2) OR (op2a code2 op2b)
8236c8eb
JJ
4167 => (inner1 OR t)
4168 => (t OR partial) */
4169 if (is_or)
e89065a1
SL
4170 {
4171 if (integer_zerop (t))
4172 return inner1;
4173 else if (integer_onep (t))
4174 return boolean_true_node;
8236c8eb
JJ
4175 /* If both are the same, we can apply the identity
4176 (x OR x) == x. */
4177 else if (partial && same_bool_result_p (t, partial))
4178 return t;
e89065a1
SL
4179 }
4180
4181 /* Handle the AND case, where we are redistributing:
4182 (inner1 AND inner2) OR (op2a code2 op2b)
4183 => (t AND (inner1 OR (op2a code2 op2b)))
4184 => (t AND partial) */
4185 else
4186 {
4187 if (integer_zerop (t))
4188 return boolean_false_node;
4189 else if (partial)
4190 {
4191 /* We already got a simplification for the other
4192 operand to the redistributed AND expression. The
4193 interesting case is when at least one is true.
4194 Or, if both are the same, we can apply the identity
8236c8eb 4195 (x AND x) == x. */
e89065a1
SL
4196 if (integer_onep (partial))
4197 return t;
4198 else if (integer_onep (t))
4199 return partial;
4200 else if (same_bool_result_p (t, partial))
8236c8eb 4201 return t;
e89065a1
SL
4202 }
4203 }
4204 }
4205 }
4206 return NULL_TREE;
4207}
4208
4209/* Try to simplify the OR of two comparisons defined by
4210 (OP1A CODE1 OP1B) and (OP2A CODE2 OP2B), respectively.
4211 If this can be done without constructing an intermediate value,
4212 return the resulting tree; otherwise NULL_TREE is returned.
4213 This function is deliberately asymmetric as it recurses on SSA_DEFs
4214 in the first comparison but not the second. */
4215
4216static tree
4217or_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
4218 enum tree_code code2, tree op2a, tree op2b)
4219{
ae22ac3c 4220 tree truth_type = truth_type_for (TREE_TYPE (op1a));
31ed6226 4221
e89065a1
SL
4222 /* First check for ((x CODE1 y) OR (x CODE2 y)). */
4223 if (operand_equal_p (op1a, op2a, 0)
4224 && operand_equal_p (op1b, op2b, 0))
4225 {
eb9820c0 4226 /* Result will be either NULL_TREE, or a combined comparison. */
e89065a1
SL
4227 tree t = combine_comparisons (UNKNOWN_LOCATION,
4228 TRUTH_ORIF_EXPR, code1, code2,
31ed6226 4229 truth_type, op1a, op1b);
e89065a1
SL
4230 if (t)
4231 return t;
4232 }
4233
4234 /* Likewise the swapped case of the above. */
4235 if (operand_equal_p (op1a, op2b, 0)
4236 && operand_equal_p (op1b, op2a, 0))
4237 {
eb9820c0 4238 /* Result will be either NULL_TREE, or a combined comparison. */
e89065a1
SL
4239 tree t = combine_comparisons (UNKNOWN_LOCATION,
4240 TRUTH_ORIF_EXPR, code1,
4241 swap_tree_comparison (code2),
31ed6226 4242 truth_type, op1a, op1b);
e89065a1
SL
4243 if (t)
4244 return t;
4245 }
4246
4247 /* If both comparisons are of the same value against constants, we might
4248 be able to merge them. */
4249 if (operand_equal_p (op1a, op2a, 0)
4250 && TREE_CODE (op1b) == INTEGER_CST
4251 && TREE_CODE (op2b) == INTEGER_CST)
4252 {
4253 int cmp = tree_int_cst_compare (op1b, op2b);
4254
4255 /* If we have (op1a != op1b), we should either be able to
4256 return that or TRUE, depending on whether the constant op1b
4257 also satisfies the other comparison against op2b. */
4258 if (code1 == NE_EXPR)
4259 {
4260 bool done = true;
4261 bool val;
4262 switch (code2)
4263 {
4264 case EQ_EXPR: val = (cmp == 0); break;
4265 case NE_EXPR: val = (cmp != 0); break;
4266 case LT_EXPR: val = (cmp < 0); break;
4267 case GT_EXPR: val = (cmp > 0); break;
4268 case LE_EXPR: val = (cmp <= 0); break;
4269 case GE_EXPR: val = (cmp >= 0); break;
4270 default: done = false;
4271 }
4272 if (done)
4273 {
4274 if (val)
4275 return boolean_true_node;
4276 else
4277 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4278 }
4279 }
4280 /* Likewise if the second comparison is a != comparison. */
4281 else if (code2 == NE_EXPR)
4282 {
4283 bool done = true;
4284 bool val;
4285 switch (code1)
4286 {
4287 case EQ_EXPR: val = (cmp == 0); break;
4288 case NE_EXPR: val = (cmp != 0); break;
4289 case LT_EXPR: val = (cmp > 0); break;
4290 case GT_EXPR: val = (cmp < 0); break;
4291 case LE_EXPR: val = (cmp >= 0); break;
4292 case GE_EXPR: val = (cmp <= 0); break;
4293 default: done = false;
4294 }
4295 if (done)
4296 {
4297 if (val)
4298 return boolean_true_node;
4299 else
4300 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4301 }
4302 }
4303
4304 /* See if an equality test is redundant with the other comparison. */
4305 else if (code1 == EQ_EXPR)
4306 {
4307 bool val;
4308 switch (code2)
4309 {
4310 case EQ_EXPR: val = (cmp == 0); break;
4311 case NE_EXPR: val = (cmp != 0); break;
4312 case LT_EXPR: val = (cmp < 0); break;
4313 case GT_EXPR: val = (cmp > 0); break;
4314 case LE_EXPR: val = (cmp <= 0); break;
4315 case GE_EXPR: val = (cmp >= 0); break;
4316 default:
4317 val = false;
4318 }
4319 if (val)
4320 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4321 }
4322 else if (code2 == EQ_EXPR)
4323 {
4324 bool val;
4325 switch (code1)
4326 {
4327 case EQ_EXPR: val = (cmp == 0); break;
4328 case NE_EXPR: val = (cmp != 0); break;
4329 case LT_EXPR: val = (cmp > 0); break;
4330 case GT_EXPR: val = (cmp < 0); break;
4331 case LE_EXPR: val = (cmp >= 0); break;
4332 case GE_EXPR: val = (cmp <= 0); break;
4333 default:
4334 val = false;
4335 }
4336 if (val)
4337 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4338 }
4339
4340 /* Chose the less restrictive of two < or <= comparisons. */
4341 else if ((code1 == LT_EXPR || code1 == LE_EXPR)
4342 && (code2 == LT_EXPR || code2 == LE_EXPR))
4343 {
4344 if ((cmp < 0) || (cmp == 0 && code1 == LT_EXPR))
4345 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4346 else
4347 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4348 }
4349
4350 /* Likewise chose the less restrictive of two > or >= comparisons. */
4351 else if ((code1 == GT_EXPR || code1 == GE_EXPR)
4352 && (code2 == GT_EXPR || code2 == GE_EXPR))
4353 {
4354 if ((cmp > 0) || (cmp == 0 && code1 == GT_EXPR))
4355 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4356 else
4357 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4358 }
4359
4360 /* Check for singleton ranges. */
4361 else if (cmp == 0
4362 && ((code1 == LT_EXPR && code2 == GT_EXPR)
4363 || (code1 == GT_EXPR && code2 == LT_EXPR)))
4364 return fold_build2 (NE_EXPR, boolean_type_node, op1a, op2b);
4365
4366 /* Check for less/greater pairs that don't restrict the range at all. */
4367 else if (cmp >= 0
4368 && (code1 == LT_EXPR || code1 == LE_EXPR)
4369 && (code2 == GT_EXPR || code2 == GE_EXPR))
4370 return boolean_true_node;
4371 else if (cmp <= 0
4372 && (code1 == GT_EXPR || code1 == GE_EXPR)
4373 && (code2 == LT_EXPR || code2 == LE_EXPR))
4374 return boolean_true_node;
4375 }
4376
4377 /* Perhaps the first comparison is (NAME != 0) or (NAME == 1) where
4378 NAME's definition is a truth value. See if there are any simplifications
4379 that can be done against the NAME's definition. */
4380 if (TREE_CODE (op1a) == SSA_NAME
4381 && (code1 == NE_EXPR || code1 == EQ_EXPR)
4382 && (integer_zerop (op1b) || integer_onep (op1b)))
4383 {
4384 bool invert = ((code1 == EQ_EXPR && integer_zerop (op1b))
4385 || (code1 == NE_EXPR && integer_onep (op1b)));
4386 gimple stmt = SSA_NAME_DEF_STMT (op1a);
4387 switch (gimple_code (stmt))
4388 {
4389 case GIMPLE_ASSIGN:
4390 /* Try to simplify by copy-propagating the definition. */
4391 return or_var_with_comparison (op1a, invert, code2, op2a, op2b);
4392
4393 case GIMPLE_PHI:
4394 /* If every argument to the PHI produces the same result when
4395 ORed with the second comparison, we win.
4396 Do not do this unless the type is bool since we need a bool
4397 result here anyway. */
4398 if (TREE_CODE (TREE_TYPE (op1a)) == BOOLEAN_TYPE)
4399 {
4400 tree result = NULL_TREE;
4401 unsigned i;
4402 for (i = 0; i < gimple_phi_num_args (stmt); i++)
4403 {
4404 tree arg = gimple_phi_arg_def (stmt, i);
4405
4406 /* If this PHI has itself as an argument, ignore it.
4407 If all the other args produce the same result,
4408 we're still OK. */
4409 if (arg == gimple_phi_result (stmt))
4410 continue;
4411 else if (TREE_CODE (arg) == INTEGER_CST)
4412 {
4413 if (invert ? integer_zerop (arg) : integer_nonzerop (arg))
4414 {
4415 if (!result)
4416 result = boolean_true_node;
4417 else if (!integer_onep (result))
4418 return NULL_TREE;
4419 }
4420 else if (!result)
4421 result = fold_build2 (code2, boolean_type_node,
4422 op2a, op2b);
4423 else if (!same_bool_comparison_p (result,
4424 code2, op2a, op2b))
4425 return NULL_TREE;
4426 }
0e8b84ec
JJ
4427 else if (TREE_CODE (arg) == SSA_NAME
4428 && !SSA_NAME_IS_DEFAULT_DEF (arg))
e89065a1 4429 {
6c66f733
JJ
4430 tree temp;
4431 gimple def_stmt = SSA_NAME_DEF_STMT (arg);
4432 /* In simple cases we can look through PHI nodes,
4433 but we have to be careful with loops.
4434 See PR49073. */
4435 if (! dom_info_available_p (CDI_DOMINATORS)
4436 || gimple_bb (def_stmt) == gimple_bb (stmt)
4437 || dominated_by_p (CDI_DOMINATORS,
4438 gimple_bb (def_stmt),
4439 gimple_bb (stmt)))
4440 return NULL_TREE;
4441 temp = or_var_with_comparison (arg, invert, code2,
4442 op2a, op2b);
e89065a1
SL
4443 if (!temp)
4444 return NULL_TREE;
4445 else if (!result)
4446 result = temp;
4447 else if (!same_bool_result_p (result, temp))
4448 return NULL_TREE;
4449 }
4450 else
4451 return NULL_TREE;
4452 }
4453 return result;
4454 }
4455
4456 default:
4457 break;
4458 }
4459 }
4460 return NULL_TREE;
4461}
4462
4463/* Try to simplify the OR of two comparisons, specified by
4464 (OP1A CODE1 OP1B) and (OP2B CODE2 OP2B), respectively.
4465 If this can be simplified to a single expression (without requiring
4466 introducing more SSA variables to hold intermediate values),
4467 return the resulting tree. Otherwise return NULL_TREE.
4468 If the result expression is non-null, it has boolean type. */
4469
4470tree
4471maybe_fold_or_comparisons (enum tree_code code1, tree op1a, tree op1b,
4472 enum tree_code code2, tree op2a, tree op2b)
4473{
4474 tree t = or_comparisons_1 (code1, op1a, op1b, code2, op2a, op2b);
4475 if (t)
4476 return t;
4477 else
4478 return or_comparisons_1 (code2, op2a, op2b, code1, op1a, op1b);
4479}
cfef45c8
RG
4480
4481
4482/* Fold STMT to a constant using VALUEIZE to valueize SSA names.
4483
4484 Either NULL_TREE, a simplified but non-constant or a constant
4485 is returned.
4486
4487 ??? This should go into a gimple-fold-inline.h file to be eventually
4488 privatized with the single valueize function used in the various TUs
4489 to avoid the indirect function call overhead. */
4490
4491tree
d2a85801
RB
4492gimple_fold_stmt_to_constant_1 (gimple stmt, tree (*valueize) (tree),
4493 tree (*gvalueize) (tree))
cfef45c8 4494{
45cc9f96
RB
4495 code_helper rcode;
4496 tree ops[3] = {};
4497 /* ??? The SSA propagators do not correctly deal with following SSA use-def
4498 edges if there are intermediate VARYING defs. For this reason
4499 do not follow SSA edges here even though SCCVN can technically
4500 just deal fine with that. */
d2a85801 4501 if (gimple_simplify (stmt, &rcode, ops, NULL, gvalueize)
45cc9f96
RB
4502 && rcode.is_tree_code ()
4503 && (TREE_CODE_LENGTH ((tree_code) rcode) == 0
4504 || ((tree_code) rcode) == ADDR_EXPR)
4505 && is_gimple_val (ops[0]))
4506 {
4507 tree res = ops[0];
4508 if (dump_file && dump_flags & TDF_DETAILS)
4509 {
4510 fprintf (dump_file, "Match-and-simplified ");
4511 print_gimple_expr (dump_file, stmt, 0, TDF_SLIM);
4512 fprintf (dump_file, " to ");
4513 print_generic_expr (dump_file, res, 0);
4514 fprintf (dump_file, "\n");
4515 }
4516 return res;
4517 }
4518
cfef45c8
RG
4519 location_t loc = gimple_location (stmt);
4520 switch (gimple_code (stmt))
4521 {
4522 case GIMPLE_ASSIGN:
4523 {
4524 enum tree_code subcode = gimple_assign_rhs_code (stmt);
4525
4526 switch (get_gimple_rhs_class (subcode))
4527 {
4528 case GIMPLE_SINGLE_RHS:
4529 {
4530 tree rhs = gimple_assign_rhs1 (stmt);
4531 enum tree_code_class kind = TREE_CODE_CLASS (subcode);
4532
4533 if (TREE_CODE (rhs) == SSA_NAME)
4534 {
4535 /* If the RHS is an SSA_NAME, return its known constant value,
4536 if any. */
4537 return (*valueize) (rhs);
4538 }
4539 /* Handle propagating invariant addresses into address
4540 operations. */
4541 else if (TREE_CODE (rhs) == ADDR_EXPR
4542 && !is_gimple_min_invariant (rhs))
4543 {
d25c4172 4544 HOST_WIDE_INT offset = 0;
cfef45c8
RG
4545 tree base;
4546 base = get_addr_base_and_unit_offset_1 (TREE_OPERAND (rhs, 0),
4547 &offset,
4548 valueize);
4549 if (base
4550 && (CONSTANT_CLASS_P (base)
4551 || decl_address_invariant_p (base)))
4552 return build_invariant_address (TREE_TYPE (rhs),
4553 base, offset);
4554 }
4555 else if (TREE_CODE (rhs) == CONSTRUCTOR
4556 && TREE_CODE (TREE_TYPE (rhs)) == VECTOR_TYPE
4557 && (CONSTRUCTOR_NELTS (rhs)
4558 == TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs))))
4559 {
4560 unsigned i;
d2a12ae7 4561 tree val, *vec;
cfef45c8 4562
d2a12ae7
RG
4563 vec = XALLOCAVEC (tree,
4564 TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs)));
cfef45c8
RG
4565 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), i, val)
4566 {
4567 val = (*valueize) (val);
4568 if (TREE_CODE (val) == INTEGER_CST
4569 || TREE_CODE (val) == REAL_CST
4570 || TREE_CODE (val) == FIXED_CST)
d2a12ae7 4571 vec[i] = val;
cfef45c8
RG
4572 else
4573 return NULL_TREE;
4574 }
4575
d2a12ae7 4576 return build_vector (TREE_TYPE (rhs), vec);
cfef45c8 4577 }
bdf37f7a
JH
4578 if (subcode == OBJ_TYPE_REF)
4579 {
4580 tree val = (*valueize) (OBJ_TYPE_REF_EXPR (rhs));
4581 /* If callee is constant, we can fold away the wrapper. */
4582 if (is_gimple_min_invariant (val))
4583 return val;
4584 }
cfef45c8
RG
4585
4586 if (kind == tcc_reference)
4587 {
4588 if ((TREE_CODE (rhs) == VIEW_CONVERT_EXPR
4589 || TREE_CODE (rhs) == REALPART_EXPR
4590 || TREE_CODE (rhs) == IMAGPART_EXPR)
4591 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
4592 {
4593 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
4594 return fold_unary_loc (EXPR_LOCATION (rhs),
4595 TREE_CODE (rhs),
4596 TREE_TYPE (rhs), val);
4597 }
4598 else if (TREE_CODE (rhs) == BIT_FIELD_REF
4599 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
4600 {
4601 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
4602 return fold_ternary_loc (EXPR_LOCATION (rhs),
4603 TREE_CODE (rhs),
4604 TREE_TYPE (rhs), val,
4605 TREE_OPERAND (rhs, 1),
4606 TREE_OPERAND (rhs, 2));
4607 }
4608 else if (TREE_CODE (rhs) == MEM_REF
4609 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
4610 {
4611 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
4612 if (TREE_CODE (val) == ADDR_EXPR
4613 && is_gimple_min_invariant (val))
4614 {
4615 tree tem = fold_build2 (MEM_REF, TREE_TYPE (rhs),
4616 unshare_expr (val),
4617 TREE_OPERAND (rhs, 1));
4618 if (tem)
4619 rhs = tem;
4620 }
4621 }
4622 return fold_const_aggregate_ref_1 (rhs, valueize);
4623 }
4624 else if (kind == tcc_declaration)
4625 return get_symbol_constant_value (rhs);
4626 return rhs;
4627 }
4628
4629 case GIMPLE_UNARY_RHS:
f3582e54 4630 return NULL_TREE;
cfef45c8
RG
4631
4632 case GIMPLE_BINARY_RHS:
4633 {
4634 /* Handle binary operators that can appear in GIMPLE form. */
4635 tree op0 = (*valueize) (gimple_assign_rhs1 (stmt));
4636 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
4637
4638 /* Translate &x + CST into an invariant form suitable for
4639 further propagation. */
4640 if (gimple_assign_rhs_code (stmt) == POINTER_PLUS_EXPR
4641 && TREE_CODE (op0) == ADDR_EXPR
4642 && TREE_CODE (op1) == INTEGER_CST)
4643 {
4644 tree off = fold_convert (ptr_type_node, op1);
4d59a001
RG
4645 return build_fold_addr_expr_loc
4646 (loc,
4647 fold_build2 (MEM_REF,
cfef45c8
RG
4648 TREE_TYPE (TREE_TYPE (op0)),
4649 unshare_expr (op0), off));
4650 }
4651
4652 return fold_binary_loc (loc, subcode,
4653 gimple_expr_type (stmt), op0, op1);
4654 }
4655
4656 case GIMPLE_TERNARY_RHS:
4657 {
4658 /* Handle ternary operators that can appear in GIMPLE form. */
4659 tree op0 = (*valueize) (gimple_assign_rhs1 (stmt));
4660 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
4661 tree op2 = (*valueize) (gimple_assign_rhs3 (stmt));
4662
d3878abf
RG
4663 /* Fold embedded expressions in ternary codes. */
4664 if ((subcode == COND_EXPR
4665 || subcode == VEC_COND_EXPR)
4666 && COMPARISON_CLASS_P (op0))
4667 {
4668 tree op00 = (*valueize) (TREE_OPERAND (op0, 0));
4669 tree op01 = (*valueize) (TREE_OPERAND (op0, 1));
4670 tree tem = fold_binary_loc (loc, TREE_CODE (op0),
4671 TREE_TYPE (op0), op00, op01);
4672 if (tem)
4673 op0 = tem;
4674 }
4675
cfef45c8
RG
4676 return fold_ternary_loc (loc, subcode,
4677 gimple_expr_type (stmt), op0, op1, op2);
4678 }
4679
4680 default:
4681 gcc_unreachable ();
4682 }
4683 }
4684
4685 case GIMPLE_CALL:
4686 {
25583c4f 4687 tree fn;
538dd0b7 4688 gcall *call_stmt = as_a <gcall *> (stmt);
25583c4f
RS
4689
4690 if (gimple_call_internal_p (stmt))
31e071ae
MP
4691 {
4692 enum tree_code subcode = ERROR_MARK;
4693 switch (gimple_call_internal_fn (stmt))
4694 {
4695 case IFN_UBSAN_CHECK_ADD:
4696 subcode = PLUS_EXPR;
4697 break;
4698 case IFN_UBSAN_CHECK_SUB:
4699 subcode = MINUS_EXPR;
4700 break;
4701 case IFN_UBSAN_CHECK_MUL:
4702 subcode = MULT_EXPR;
4703 break;
4704 default:
4705 return NULL_TREE;
4706 }
368b454d
JJ
4707 tree arg0 = gimple_call_arg (stmt, 0);
4708 tree arg1 = gimple_call_arg (stmt, 1);
4709 tree op0 = (*valueize) (arg0);
4710 tree op1 = (*valueize) (arg1);
31e071ae
MP
4711
4712 if (TREE_CODE (op0) != INTEGER_CST
4713 || TREE_CODE (op1) != INTEGER_CST)
368b454d
JJ
4714 {
4715 switch (subcode)
4716 {
4717 case MULT_EXPR:
4718 /* x * 0 = 0 * x = 0 without overflow. */
4719 if (integer_zerop (op0) || integer_zerop (op1))
4720 return build_zero_cst (TREE_TYPE (arg0));
4721 break;
4722 case MINUS_EXPR:
4723 /* y - y = 0 without overflow. */
4724 if (operand_equal_p (op0, op1, 0))
4725 return build_zero_cst (TREE_TYPE (arg0));
4726 break;
4727 default:
4728 break;
4729 }
4730 }
4731 tree res
4732 = fold_binary_loc (loc, subcode, TREE_TYPE (arg0), op0, op1);
31e071ae
MP
4733 if (res
4734 && TREE_CODE (res) == INTEGER_CST
4735 && !TREE_OVERFLOW (res))
4736 return res;
4737 return NULL_TREE;
4738 }
25583c4f
RS
4739
4740 fn = (*valueize) (gimple_call_fn (stmt));
cfef45c8
RG
4741 if (TREE_CODE (fn) == ADDR_EXPR
4742 && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL
5c944c6c
RB
4743 && DECL_BUILT_IN (TREE_OPERAND (fn, 0))
4744 && gimple_builtin_call_types_compatible_p (stmt,
4745 TREE_OPERAND (fn, 0)))
cfef45c8
RG
4746 {
4747 tree *args = XALLOCAVEC (tree, gimple_call_num_args (stmt));
4748 tree call, retval;
4749 unsigned i;
4750 for (i = 0; i < gimple_call_num_args (stmt); ++i)
4751 args[i] = (*valueize) (gimple_call_arg (stmt, i));
4752 call = build_call_array_loc (loc,
538dd0b7 4753 gimple_call_return_type (call_stmt),
cfef45c8
RG
4754 fn, gimple_call_num_args (stmt), args);
4755 retval = fold_call_expr (EXPR_LOCATION (call), call, false);
4756 if (retval)
5c944c6c
RB
4757 {
4758 /* fold_call_expr wraps the result inside a NOP_EXPR. */
4759 STRIP_NOPS (retval);
538dd0b7
DM
4760 retval = fold_convert (gimple_call_return_type (call_stmt),
4761 retval);
5c944c6c 4762 }
cfef45c8
RG
4763 return retval;
4764 }
4765 return NULL_TREE;
4766 }
4767
4768 default:
4769 return NULL_TREE;
4770 }
4771}
4772
4773/* Fold STMT to a constant using VALUEIZE to valueize SSA names.
4774 Returns NULL_TREE if folding to a constant is not possible, otherwise
4775 returns a constant according to is_gimple_min_invariant. */
4776
4777tree
4778gimple_fold_stmt_to_constant (gimple stmt, tree (*valueize) (tree))
4779{
4780 tree res = gimple_fold_stmt_to_constant_1 (stmt, valueize);
4781 if (res && is_gimple_min_invariant (res))
4782 return res;
4783 return NULL_TREE;
4784}
4785
4786
4787/* The following set of functions are supposed to fold references using
4788 their constant initializers. */
4789
cfef45c8
RG
4790/* See if we can find constructor defining value of BASE.
4791 When we know the consructor with constant offset (such as
4792 base is array[40] and we do know constructor of array), then
4793 BIT_OFFSET is adjusted accordingly.
4794
4795 As a special case, return error_mark_node when constructor
4796 is not explicitly available, but it is known to be zero
4797 such as 'static const int a;'. */
4798static tree
4799get_base_constructor (tree base, HOST_WIDE_INT *bit_offset,
4800 tree (*valueize)(tree))
4801{
4802 HOST_WIDE_INT bit_offset2, size, max_size;
4803 if (TREE_CODE (base) == MEM_REF)
4804 {
4805 if (!integer_zerop (TREE_OPERAND (base, 1)))
4806 {
9541ffee 4807 if (!tree_fits_shwi_p (TREE_OPERAND (base, 1)))
cfef45c8 4808 return NULL_TREE;
807e902e 4809 *bit_offset += (mem_ref_offset (base).to_short_addr ()
cfef45c8
RG
4810 * BITS_PER_UNIT);
4811 }
4812
4813 if (valueize
4814 && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
4815 base = valueize (TREE_OPERAND (base, 0));
4816 if (!base || TREE_CODE (base) != ADDR_EXPR)
4817 return NULL_TREE;
4818 base = TREE_OPERAND (base, 0);
4819 }
4820
4821 /* Get a CONSTRUCTOR. If BASE is a VAR_DECL, get its
4822 DECL_INITIAL. If BASE is a nested reference into another
4823 ARRAY_REF or COMPONENT_REF, make a recursive call to resolve
4824 the inner reference. */
4825 switch (TREE_CODE (base))
4826 {
4827 case VAR_DECL:
cfef45c8 4828 case CONST_DECL:
6a6dac52
JH
4829 {
4830 tree init = ctor_for_folding (base);
4831
688010ba 4832 /* Our semantic is exact opposite of ctor_for_folding;
6a6dac52
JH
4833 NULL means unknown, while error_mark_node is 0. */
4834 if (init == error_mark_node)
4835 return NULL_TREE;
4836 if (!init)
4837 return error_mark_node;
4838 return init;
4839 }
cfef45c8
RG
4840
4841 case ARRAY_REF:
4842 case COMPONENT_REF:
4843 base = get_ref_base_and_extent (base, &bit_offset2, &size, &max_size);
4844 if (max_size == -1 || size != max_size)
4845 return NULL_TREE;
4846 *bit_offset += bit_offset2;
4847 return get_base_constructor (base, bit_offset, valueize);
4848
4849 case STRING_CST:
4850 case CONSTRUCTOR:
4851 return base;
4852
4853 default:
4854 return NULL_TREE;
4855 }
4856}
4857
cfef45c8
RG
4858/* CTOR is CONSTRUCTOR of an array type. Fold reference of type TYPE and size
4859 SIZE to the memory at bit OFFSET. */
4860
4861static tree
4862fold_array_ctor_reference (tree type, tree ctor,
4863 unsigned HOST_WIDE_INT offset,
c44c2088
JH
4864 unsigned HOST_WIDE_INT size,
4865 tree from_decl)
cfef45c8
RG
4866{
4867 unsigned HOST_WIDE_INT cnt;
4868 tree cfield, cval;
807e902e
KZ
4869 offset_int low_bound;
4870 offset_int elt_size;
4871 offset_int index, max_index;
4872 offset_int access_index;
b48e22b2 4873 tree domain_type = NULL_TREE, index_type = NULL_TREE;
cfef45c8
RG
4874 HOST_WIDE_INT inner_offset;
4875
4876 /* Compute low bound and elt size. */
eb8f1123
RG
4877 if (TREE_CODE (TREE_TYPE (ctor)) == ARRAY_TYPE)
4878 domain_type = TYPE_DOMAIN (TREE_TYPE (ctor));
cfef45c8
RG
4879 if (domain_type && TYPE_MIN_VALUE (domain_type))
4880 {
4881 /* Static constructors for variably sized objects makes no sense. */
4882 gcc_assert (TREE_CODE (TYPE_MIN_VALUE (domain_type)) == INTEGER_CST);
b48e22b2 4883 index_type = TREE_TYPE (TYPE_MIN_VALUE (domain_type));
807e902e 4884 low_bound = wi::to_offset (TYPE_MIN_VALUE (domain_type));
cfef45c8
RG
4885 }
4886 else
807e902e 4887 low_bound = 0;
cfef45c8 4888 /* Static constructors for variably sized objects makes no sense. */
c3284718 4889 gcc_assert (TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (ctor))))
cfef45c8 4890 == INTEGER_CST);
807e902e 4891 elt_size = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (ctor))));
cfef45c8
RG
4892
4893 /* We can handle only constantly sized accesses that are known to not
4894 be larger than size of array element. */
4895 if (!TYPE_SIZE_UNIT (type)
4896 || TREE_CODE (TYPE_SIZE_UNIT (type)) != INTEGER_CST
807e902e
KZ
4897 || wi::lts_p (elt_size, wi::to_offset (TYPE_SIZE_UNIT (type)))
4898 || elt_size == 0)
cfef45c8
RG
4899 return NULL_TREE;
4900
4901 /* Compute the array index we look for. */
807e902e
KZ
4902 access_index = wi::udiv_trunc (offset_int (offset / BITS_PER_UNIT),
4903 elt_size);
27bcd47c 4904 access_index += low_bound;
b48e22b2 4905 if (index_type)
807e902e
KZ
4906 access_index = wi::ext (access_index, TYPE_PRECISION (index_type),
4907 TYPE_SIGN (index_type));
cfef45c8
RG
4908
4909 /* And offset within the access. */
27bcd47c 4910 inner_offset = offset % (elt_size.to_uhwi () * BITS_PER_UNIT);
cfef45c8
RG
4911
4912 /* See if the array field is large enough to span whole access. We do not
4913 care to fold accesses spanning multiple array indexes. */
27bcd47c 4914 if (inner_offset + size > elt_size.to_uhwi () * BITS_PER_UNIT)
cfef45c8
RG
4915 return NULL_TREE;
4916
807e902e 4917 index = low_bound - 1;
b48e22b2 4918 if (index_type)
807e902e
KZ
4919 index = wi::ext (index, TYPE_PRECISION (index_type),
4920 TYPE_SIGN (index_type));
b48e22b2 4921
cfef45c8
RG
4922 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), cnt, cfield, cval)
4923 {
4924 /* Array constructor might explicitely set index, or specify range
4925 or leave index NULL meaning that it is next index after previous
4926 one. */
4927 if (cfield)
4928 {
4929 if (TREE_CODE (cfield) == INTEGER_CST)
807e902e 4930 max_index = index = wi::to_offset (cfield);
cfef45c8
RG
4931 else
4932 {
4933 gcc_assert (TREE_CODE (cfield) == RANGE_EXPR);
807e902e
KZ
4934 index = wi::to_offset (TREE_OPERAND (cfield, 0));
4935 max_index = wi::to_offset (TREE_OPERAND (cfield, 1));
cfef45c8
RG
4936 }
4937 }
4938 else
b48e22b2 4939 {
807e902e 4940 index += 1;
b48e22b2 4941 if (index_type)
807e902e
KZ
4942 index = wi::ext (index, TYPE_PRECISION (index_type),
4943 TYPE_SIGN (index_type));
b48e22b2
EB
4944 max_index = index;
4945 }
cfef45c8
RG
4946
4947 /* Do we have match? */
807e902e
KZ
4948 if (wi::cmpu (access_index, index) >= 0
4949 && wi::cmpu (access_index, max_index) <= 0)
c44c2088
JH
4950 return fold_ctor_reference (type, cval, inner_offset, size,
4951 from_decl);
cfef45c8
RG
4952 }
4953 /* When memory is not explicitely mentioned in constructor,
4954 it is 0 (or out of range). */
4955 return build_zero_cst (type);
4956}
4957
4958/* CTOR is CONSTRUCTOR of an aggregate or vector.
4959 Fold reference of type TYPE and size SIZE to the memory at bit OFFSET. */
4960
4961static tree
4962fold_nonarray_ctor_reference (tree type, tree ctor,
4963 unsigned HOST_WIDE_INT offset,
c44c2088
JH
4964 unsigned HOST_WIDE_INT size,
4965 tree from_decl)
cfef45c8
RG
4966{
4967 unsigned HOST_WIDE_INT cnt;
4968 tree cfield, cval;
4969
4970 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), cnt, cfield,
4971 cval)
4972 {
4973 tree byte_offset = DECL_FIELD_OFFSET (cfield);
4974 tree field_offset = DECL_FIELD_BIT_OFFSET (cfield);
4975 tree field_size = DECL_SIZE (cfield);
807e902e
KZ
4976 offset_int bitoffset;
4977 offset_int bitoffset_end, access_end;
cfef45c8
RG
4978
4979 /* Variable sized objects in static constructors makes no sense,
4980 but field_size can be NULL for flexible array members. */
4981 gcc_assert (TREE_CODE (field_offset) == INTEGER_CST
4982 && TREE_CODE (byte_offset) == INTEGER_CST
4983 && (field_size != NULL_TREE
4984 ? TREE_CODE (field_size) == INTEGER_CST
4985 : TREE_CODE (TREE_TYPE (cfield)) == ARRAY_TYPE));
4986
4987 /* Compute bit offset of the field. */
807e902e
KZ
4988 bitoffset = (wi::to_offset (field_offset)
4989 + wi::lshift (wi::to_offset (byte_offset),
4990 LOG2_BITS_PER_UNIT));
cfef45c8
RG
4991 /* Compute bit offset where the field ends. */
4992 if (field_size != NULL_TREE)
807e902e 4993 bitoffset_end = bitoffset + wi::to_offset (field_size);
cfef45c8 4994 else
807e902e 4995 bitoffset_end = 0;
cfef45c8 4996
807e902e 4997 access_end = offset_int (offset) + size;
b8b2b009
JJ
4998
4999 /* Is there any overlap between [OFFSET, OFFSET+SIZE) and
5000 [BITOFFSET, BITOFFSET_END)? */
807e902e 5001 if (wi::cmps (access_end, bitoffset) > 0
cfef45c8 5002 && (field_size == NULL_TREE
807e902e 5003 || wi::lts_p (offset, bitoffset_end)))
cfef45c8 5004 {
807e902e 5005 offset_int inner_offset = offset_int (offset) - bitoffset;
cfef45c8
RG
5006 /* We do have overlap. Now see if field is large enough to
5007 cover the access. Give up for accesses spanning multiple
5008 fields. */
807e902e 5009 if (wi::cmps (access_end, bitoffset_end) > 0)
cfef45c8 5010 return NULL_TREE;
807e902e 5011 if (wi::lts_p (offset, bitoffset))
b8b2b009 5012 return NULL_TREE;
cfef45c8 5013 return fold_ctor_reference (type, cval,
27bcd47c 5014 inner_offset.to_uhwi (), size,
c44c2088 5015 from_decl);
cfef45c8
RG
5016 }
5017 }
5018 /* When memory is not explicitely mentioned in constructor, it is 0. */
5019 return build_zero_cst (type);
5020}
5021
5022/* CTOR is value initializing memory, fold reference of type TYPE and size SIZE
5023 to the memory at bit OFFSET. */
5024
8403c2cf 5025tree
cfef45c8 5026fold_ctor_reference (tree type, tree ctor, unsigned HOST_WIDE_INT offset,
c44c2088 5027 unsigned HOST_WIDE_INT size, tree from_decl)
cfef45c8
RG
5028{
5029 tree ret;
5030
5031 /* We found the field with exact match. */
5032 if (useless_type_conversion_p (type, TREE_TYPE (ctor))
5033 && !offset)
9d60be38 5034 return canonicalize_constructor_val (unshare_expr (ctor), from_decl);
cfef45c8
RG
5035
5036 /* We are at the end of walk, see if we can view convert the
5037 result. */
5038 if (!AGGREGATE_TYPE_P (TREE_TYPE (ctor)) && !offset
5039 /* VIEW_CONVERT_EXPR is defined only for matching sizes. */
3d8208ce
TP
5040 && !compare_tree_int (TYPE_SIZE (type), size)
5041 && !compare_tree_int (TYPE_SIZE (TREE_TYPE (ctor)), size))
cfef45c8 5042 {
9d60be38 5043 ret = canonicalize_constructor_val (unshare_expr (ctor), from_decl);
cfef45c8
RG
5044 ret = fold_unary (VIEW_CONVERT_EXPR, type, ret);
5045 if (ret)
5046 STRIP_NOPS (ret);
5047 return ret;
5048 }
b2505143
RB
5049 /* For constants and byte-aligned/sized reads try to go through
5050 native_encode/interpret. */
5051 if (CONSTANT_CLASS_P (ctor)
5052 && BITS_PER_UNIT == 8
5053 && offset % BITS_PER_UNIT == 0
5054 && size % BITS_PER_UNIT == 0
5055 && size <= MAX_BITSIZE_MODE_ANY_MODE)
5056 {
5057 unsigned char buf[MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT];
5058 if (native_encode_expr (ctor, buf, size / BITS_PER_UNIT,
5059 offset / BITS_PER_UNIT) > 0)
5060 return native_interpret_expr (type, buf, size / BITS_PER_UNIT);
5061 }
cfef45c8
RG
5062 if (TREE_CODE (ctor) == CONSTRUCTOR)
5063 {
5064
eb8f1123
RG
5065 if (TREE_CODE (TREE_TYPE (ctor)) == ARRAY_TYPE
5066 || TREE_CODE (TREE_TYPE (ctor)) == VECTOR_TYPE)
c44c2088
JH
5067 return fold_array_ctor_reference (type, ctor, offset, size,
5068 from_decl);
cfef45c8 5069 else
c44c2088
JH
5070 return fold_nonarray_ctor_reference (type, ctor, offset, size,
5071 from_decl);
cfef45c8
RG
5072 }
5073
5074 return NULL_TREE;
5075}
5076
5077/* Return the tree representing the element referenced by T if T is an
5078 ARRAY_REF or COMPONENT_REF into constant aggregates valuezing SSA
5079 names using VALUEIZE. Return NULL_TREE otherwise. */
5080
5081tree
5082fold_const_aggregate_ref_1 (tree t, tree (*valueize) (tree))
5083{
5084 tree ctor, idx, base;
5085 HOST_WIDE_INT offset, size, max_size;
5086 tree tem;
5087
f8a7df45
RG
5088 if (TREE_THIS_VOLATILE (t))
5089 return NULL_TREE;
5090
cfef45c8
RG
5091 if (TREE_CODE_CLASS (TREE_CODE (t)) == tcc_declaration)
5092 return get_symbol_constant_value (t);
5093
5094 tem = fold_read_from_constant_string (t);
5095 if (tem)
5096 return tem;
5097
5098 switch (TREE_CODE (t))
5099 {
5100 case ARRAY_REF:
5101 case ARRAY_RANGE_REF:
5102 /* Constant indexes are handled well by get_base_constructor.
5103 Only special case variable offsets.
5104 FIXME: This code can't handle nested references with variable indexes
5105 (they will be handled only by iteration of ccp). Perhaps we can bring
5106 get_ref_base_and_extent here and make it use a valueize callback. */
5107 if (TREE_CODE (TREE_OPERAND (t, 1)) == SSA_NAME
5108 && valueize
5109 && (idx = (*valueize) (TREE_OPERAND (t, 1)))
b48e22b2 5110 && TREE_CODE (idx) == INTEGER_CST)
cfef45c8
RG
5111 {
5112 tree low_bound, unit_size;
5113
5114 /* If the resulting bit-offset is constant, track it. */
5115 if ((low_bound = array_ref_low_bound (t),
b48e22b2 5116 TREE_CODE (low_bound) == INTEGER_CST)
cfef45c8 5117 && (unit_size = array_ref_element_size (t),
807e902e 5118 tree_fits_uhwi_p (unit_size)))
cfef45c8 5119 {
807e902e
KZ
5120 offset_int woffset
5121 = wi::sext (wi::to_offset (idx) - wi::to_offset (low_bound),
5122 TYPE_PRECISION (TREE_TYPE (idx)));
5123
5124 if (wi::fits_shwi_p (woffset))
5125 {
5126 offset = woffset.to_shwi ();
5127 /* TODO: This code seems wrong, multiply then check
5128 to see if it fits. */
5129 offset *= tree_to_uhwi (unit_size);
5130 offset *= BITS_PER_UNIT;
5131
5132 base = TREE_OPERAND (t, 0);
5133 ctor = get_base_constructor (base, &offset, valueize);
5134 /* Empty constructor. Always fold to 0. */
5135 if (ctor == error_mark_node)
5136 return build_zero_cst (TREE_TYPE (t));
5137 /* Out of bound array access. Value is undefined,
5138 but don't fold. */
5139 if (offset < 0)
5140 return NULL_TREE;
5141 /* We can not determine ctor. */
5142 if (!ctor)
5143 return NULL_TREE;
5144 return fold_ctor_reference (TREE_TYPE (t), ctor, offset,
5145 tree_to_uhwi (unit_size)
5146 * BITS_PER_UNIT,
5147 base);
5148 }
cfef45c8
RG
5149 }
5150 }
5151 /* Fallthru. */
5152
5153 case COMPONENT_REF:
5154 case BIT_FIELD_REF:
5155 case TARGET_MEM_REF:
5156 case MEM_REF:
5157 base = get_ref_base_and_extent (t, &offset, &size, &max_size);
5158 ctor = get_base_constructor (base, &offset, valueize);
5159
5160 /* Empty constructor. Always fold to 0. */
5161 if (ctor == error_mark_node)
5162 return build_zero_cst (TREE_TYPE (t));
5163 /* We do not know precise address. */
5164 if (max_size == -1 || max_size != size)
5165 return NULL_TREE;
5166 /* We can not determine ctor. */
5167 if (!ctor)
5168 return NULL_TREE;
5169
5170 /* Out of bound array access. Value is undefined, but don't fold. */
5171 if (offset < 0)
5172 return NULL_TREE;
5173
c44c2088
JH
5174 return fold_ctor_reference (TREE_TYPE (t), ctor, offset, size,
5175 base);
cfef45c8
RG
5176
5177 case REALPART_EXPR:
5178 case IMAGPART_EXPR:
5179 {
5180 tree c = fold_const_aggregate_ref_1 (TREE_OPERAND (t, 0), valueize);
5181 if (c && TREE_CODE (c) == COMPLEX_CST)
5182 return fold_build1_loc (EXPR_LOCATION (t),
5183 TREE_CODE (t), TREE_TYPE (t), c);
5184 break;
5185 }
5186
5187 default:
5188 break;
5189 }
5190
5191 return NULL_TREE;
5192}
5193
5194tree
5195fold_const_aggregate_ref (tree t)
5196{
5197 return fold_const_aggregate_ref_1 (t, NULL);
5198}
06bc3ec7 5199
85942f45 5200/* Lookup virtual method with index TOKEN in a virtual table V
ec77d61f
JH
5201 at OFFSET.
5202 Set CAN_REFER if non-NULL to false if method
5203 is not referable or if the virtual table is ill-formed (such as rewriten
5204 by non-C++ produced symbol). Otherwise just return NULL in that calse. */
81fa35bd
MJ
5205
5206tree
85942f45
JH
5207gimple_get_virt_method_for_vtable (HOST_WIDE_INT token,
5208 tree v,
ec77d61f
JH
5209 unsigned HOST_WIDE_INT offset,
5210 bool *can_refer)
81fa35bd 5211{
85942f45
JH
5212 tree vtable = v, init, fn;
5213 unsigned HOST_WIDE_INT size;
8c311b50
JH
5214 unsigned HOST_WIDE_INT elt_size, access_index;
5215 tree domain_type;
81fa35bd 5216
ec77d61f
JH
5217 if (can_refer)
5218 *can_refer = true;
5219
9de2f554 5220 /* First of all double check we have virtual table. */
81fa35bd 5221 if (TREE_CODE (v) != VAR_DECL
2aa3da06 5222 || !DECL_VIRTUAL_P (v))
ec77d61f
JH
5223 {
5224 gcc_assert (in_lto_p);
5225 /* Pass down that we lost track of the target. */
5226 if (can_refer)
5227 *can_refer = false;
5228 return NULL_TREE;
5229 }
9de2f554 5230
2aa3da06
JH
5231 init = ctor_for_folding (v);
5232
9de2f554 5233 /* The virtual tables should always be born with constructors
2aa3da06
JH
5234 and we always should assume that they are avaialble for
5235 folding. At the moment we do not stream them in all cases,
5236 but it should never happen that ctor seem unreachable. */
5237 gcc_assert (init);
5238 if (init == error_mark_node)
5239 {
5240 gcc_assert (in_lto_p);
ec77d61f
JH
5241 /* Pass down that we lost track of the target. */
5242 if (can_refer)
5243 *can_refer = false;
2aa3da06
JH
5244 return NULL_TREE;
5245 }
81fa35bd 5246 gcc_checking_assert (TREE_CODE (TREE_TYPE (v)) == ARRAY_TYPE);
ae7e9ddd 5247 size = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (TREE_TYPE (v))));
85942f45 5248 offset *= BITS_PER_UNIT;
81fa35bd 5249 offset += token * size;
9de2f554 5250
8c311b50
JH
5251 /* Lookup the value in the constructor that is assumed to be array.
5252 This is equivalent to
5253 fn = fold_ctor_reference (TREE_TYPE (TREE_TYPE (v)), init,
5254 offset, size, NULL);
5255 but in a constant time. We expect that frontend produced a simple
5256 array without indexed initializers. */
5257
5258 gcc_checking_assert (TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE);
5259 domain_type = TYPE_DOMAIN (TREE_TYPE (init));
5260 gcc_checking_assert (integer_zerop (TYPE_MIN_VALUE (domain_type)));
5261 elt_size = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (init))));
5262
5263 access_index = offset / BITS_PER_UNIT / elt_size;
5264 gcc_checking_assert (offset % (elt_size * BITS_PER_UNIT) == 0);
5265
5266 /* This code makes an assumption that there are no
5267 indexed fileds produced by C++ FE, so we can directly index the array. */
5268 if (access_index < CONSTRUCTOR_NELTS (init))
5269 {
5270 fn = CONSTRUCTOR_ELT (init, access_index)->value;
5271 gcc_checking_assert (!CONSTRUCTOR_ELT (init, access_index)->index);
5272 STRIP_NOPS (fn);
5273 }
5274 else
5275 fn = NULL;
9de2f554
JH
5276
5277 /* For type inconsistent program we may end up looking up virtual method
5278 in virtual table that does not contain TOKEN entries. We may overrun
5279 the virtual table and pick up a constant or RTTI info pointer.
5280 In any case the call is undefined. */
5281 if (!fn
5282 || (TREE_CODE (fn) != ADDR_EXPR && TREE_CODE (fn) != FDESC_EXPR)
5283 || TREE_CODE (TREE_OPERAND (fn, 0)) != FUNCTION_DECL)
5284 fn = builtin_decl_implicit (BUILT_IN_UNREACHABLE);
5285 else
5286 {
5287 fn = TREE_OPERAND (fn, 0);
5288
5289 /* When cgraph node is missing and function is not public, we cannot
5290 devirtualize. This can happen in WHOPR when the actual method
5291 ends up in other partition, because we found devirtualization
5292 possibility too late. */
5293 if (!can_refer_decl_in_current_unit_p (fn, vtable))
ec77d61f
JH
5294 {
5295 if (can_refer)
5296 {
5297 *can_refer = false;
5298 return fn;
5299 }
5300 return NULL_TREE;
5301 }
9de2f554 5302 }
81fa35bd 5303
7501ca28
RG
5304 /* Make sure we create a cgraph node for functions we'll reference.
5305 They can be non-existent if the reference comes from an entry
5306 of an external vtable for example. */
d52f5295 5307 cgraph_node::get_create (fn);
7501ca28 5308
81fa35bd
MJ
5309 return fn;
5310}
5311
85942f45
JH
5312/* Return a declaration of a function which an OBJ_TYPE_REF references. TOKEN
5313 is integer form of OBJ_TYPE_REF_TOKEN of the reference expression.
5314 KNOWN_BINFO carries the binfo describing the true type of
ec77d61f
JH
5315 OBJ_TYPE_REF_OBJECT(REF).
5316 Set CAN_REFER if non-NULL to false if method
5317 is not referable or if the virtual table is ill-formed (such as rewriten
5318 by non-C++ produced symbol). Otherwise just return NULL in that calse. */
85942f45
JH
5319
5320tree
ec77d61f
JH
5321gimple_get_virt_method_for_binfo (HOST_WIDE_INT token, tree known_binfo,
5322 bool *can_refer)
85942f45
JH
5323{
5324 unsigned HOST_WIDE_INT offset;
5325 tree v;
5326
5327 v = BINFO_VTABLE (known_binfo);
5328 /* If there is no virtual methods table, leave the OBJ_TYPE_REF alone. */
5329 if (!v)
5330 return NULL_TREE;
5331
5332 if (!vtable_pointer_value_to_vtable (v, &v, &offset))
ec77d61f
JH
5333 {
5334 if (can_refer)
5335 *can_refer = false;
5336 return NULL_TREE;
5337 }
5338 return gimple_get_virt_method_for_vtable (token, v, offset, can_refer);
85942f45
JH
5339}
5340
06bc3ec7
BS
5341/* Return true iff VAL is a gimple expression that is known to be
5342 non-negative. Restricted to floating-point inputs. */
5343
5344bool
5345gimple_val_nonnegative_real_p (tree val)
5346{
5347 gimple def_stmt;
5348
5349 gcc_assert (val && SCALAR_FLOAT_TYPE_P (TREE_TYPE (val)));
5350
5351 /* Use existing logic for non-gimple trees. */
5352 if (tree_expr_nonnegative_p (val))
5353 return true;
5354
5355 if (TREE_CODE (val) != SSA_NAME)
5356 return false;
5357
5358 /* Currently we look only at the immediately defining statement
5359 to make this determination, since recursion on defining
5360 statements of operands can lead to quadratic behavior in the
5361 worst case. This is expected to catch almost all occurrences
5362 in practice. It would be possible to implement limited-depth
5363 recursion if important cases are lost. Alternatively, passes
5364 that need this information (such as the pow/powi lowering code
5365 in the cse_sincos pass) could be revised to provide it through
5366 dataflow propagation. */
5367
5368 def_stmt = SSA_NAME_DEF_STMT (val);
5369
5370 if (is_gimple_assign (def_stmt))
5371 {
5372 tree op0, op1;
5373
5374 /* See fold-const.c:tree_expr_nonnegative_p for additional
5375 cases that could be handled with recursion. */
5376
5377 switch (gimple_assign_rhs_code (def_stmt))
5378 {
5379 case ABS_EXPR:
5380 /* Always true for floating-point operands. */
5381 return true;
5382
5383 case MULT_EXPR:
5384 /* True if the two operands are identical (since we are
5385 restricted to floating-point inputs). */
5386 op0 = gimple_assign_rhs1 (def_stmt);
5387 op1 = gimple_assign_rhs2 (def_stmt);
5388
5389 if (op0 == op1
5390 || operand_equal_p (op0, op1, 0))
5391 return true;
5392
5393 default:
5394 return false;
5395 }
5396 }
5397 else if (is_gimple_call (def_stmt))
5398 {
5399 tree fndecl = gimple_call_fndecl (def_stmt);
5400 if (fndecl
5401 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
5402 {
5403 tree arg1;
5404
5405 switch (DECL_FUNCTION_CODE (fndecl))
5406 {
5407 CASE_FLT_FN (BUILT_IN_ACOS):
5408 CASE_FLT_FN (BUILT_IN_ACOSH):
5409 CASE_FLT_FN (BUILT_IN_CABS):
5410 CASE_FLT_FN (BUILT_IN_COSH):
5411 CASE_FLT_FN (BUILT_IN_ERFC):
5412 CASE_FLT_FN (BUILT_IN_EXP):
5413 CASE_FLT_FN (BUILT_IN_EXP10):
5414 CASE_FLT_FN (BUILT_IN_EXP2):
5415 CASE_FLT_FN (BUILT_IN_FABS):
5416 CASE_FLT_FN (BUILT_IN_FDIM):
5417 CASE_FLT_FN (BUILT_IN_HYPOT):
5418 CASE_FLT_FN (BUILT_IN_POW10):
5419 return true;
5420
5421 CASE_FLT_FN (BUILT_IN_SQRT):
5422 /* sqrt(-0.0) is -0.0, and sqrt is not defined over other
5423 nonnegative inputs. */
5424 if (!HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (val))))
5425 return true;
5426
5427 break;
5428
5429 CASE_FLT_FN (BUILT_IN_POWI):
5430 /* True if the second argument is an even integer. */
5431 arg1 = gimple_call_arg (def_stmt, 1);
5432
5433 if (TREE_CODE (arg1) == INTEGER_CST
5434 && (TREE_INT_CST_LOW (arg1) & 1) == 0)
5435 return true;
5436
5437 break;
5438
5439 CASE_FLT_FN (BUILT_IN_POW):
5440 /* True if the second argument is an even integer-valued
5441 real. */
5442 arg1 = gimple_call_arg (def_stmt, 1);
5443
5444 if (TREE_CODE (arg1) == REAL_CST)
5445 {
5446 REAL_VALUE_TYPE c;
5447 HOST_WIDE_INT n;
5448
5449 c = TREE_REAL_CST (arg1);
5450 n = real_to_integer (&c);
5451
5452 if ((n & 1) == 0)
5453 {
5454 REAL_VALUE_TYPE cint;
807e902e 5455 real_from_integer (&cint, VOIDmode, n, SIGNED);
06bc3ec7
BS
5456 if (real_identical (&c, &cint))
5457 return true;
5458 }
5459 }
5460
5461 break;
5462
5463 default:
5464 return false;
5465 }
5466 }
5467 }
5468
5469 return false;
5470}
b184c8f1
AM
5471
5472/* Given a pointer value OP0, return a simplified version of an
5473 indirection through OP0, or NULL_TREE if no simplification is
5474 possible. Note that the resulting type may be different from
5475 the type pointed to in the sense that it is still compatible
5476 from the langhooks point of view. */
5477
5478tree
5479gimple_fold_indirect_ref (tree t)
5480{
5481 tree ptype = TREE_TYPE (t), type = TREE_TYPE (ptype);
5482 tree sub = t;
5483 tree subtype;
5484
5485 STRIP_NOPS (sub);
5486 subtype = TREE_TYPE (sub);
5487 if (!POINTER_TYPE_P (subtype))
5488 return NULL_TREE;
5489
5490 if (TREE_CODE (sub) == ADDR_EXPR)
5491 {
5492 tree op = TREE_OPERAND (sub, 0);
5493 tree optype = TREE_TYPE (op);
5494 /* *&p => p */
5495 if (useless_type_conversion_p (type, optype))
5496 return op;
5497
5498 /* *(foo *)&fooarray => fooarray[0] */
5499 if (TREE_CODE (optype) == ARRAY_TYPE
5500 && TREE_CODE (TYPE_SIZE (TREE_TYPE (optype))) == INTEGER_CST
5501 && useless_type_conversion_p (type, TREE_TYPE (optype)))
5502 {
5503 tree type_domain = TYPE_DOMAIN (optype);
5504 tree min_val = size_zero_node;
5505 if (type_domain && TYPE_MIN_VALUE (type_domain))
5506 min_val = TYPE_MIN_VALUE (type_domain);
5507 if (TREE_CODE (min_val) == INTEGER_CST)
5508 return build4 (ARRAY_REF, type, op, min_val, NULL_TREE, NULL_TREE);
5509 }
5510 /* *(foo *)&complexfoo => __real__ complexfoo */
5511 else if (TREE_CODE (optype) == COMPLEX_TYPE
5512 && useless_type_conversion_p (type, TREE_TYPE (optype)))
5513 return fold_build1 (REALPART_EXPR, type, op);
5514 /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
5515 else if (TREE_CODE (optype) == VECTOR_TYPE
5516 && useless_type_conversion_p (type, TREE_TYPE (optype)))
5517 {
5518 tree part_width = TYPE_SIZE (type);
5519 tree index = bitsize_int (0);
5520 return fold_build3 (BIT_FIELD_REF, type, op, part_width, index);
5521 }
5522 }
5523
5524 /* *(p + CST) -> ... */
5525 if (TREE_CODE (sub) == POINTER_PLUS_EXPR
5526 && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST)
5527 {
5528 tree addr = TREE_OPERAND (sub, 0);
5529 tree off = TREE_OPERAND (sub, 1);
5530 tree addrtype;
5531
5532 STRIP_NOPS (addr);
5533 addrtype = TREE_TYPE (addr);
5534
5535 /* ((foo*)&vectorfoo)[1] -> BIT_FIELD_REF<vectorfoo,...> */
5536 if (TREE_CODE (addr) == ADDR_EXPR
5537 && TREE_CODE (TREE_TYPE (addrtype)) == VECTOR_TYPE
5538 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (addrtype)))
cc269bb6 5539 && tree_fits_uhwi_p (off))
b184c8f1 5540 {
ae7e9ddd 5541 unsigned HOST_WIDE_INT offset = tree_to_uhwi (off);
b184c8f1
AM
5542 tree part_width = TYPE_SIZE (type);
5543 unsigned HOST_WIDE_INT part_widthi
9439e9a1 5544 = tree_to_shwi (part_width) / BITS_PER_UNIT;
b184c8f1
AM
5545 unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT;
5546 tree index = bitsize_int (indexi);
5547 if (offset / part_widthi
e934916c 5548 < TYPE_VECTOR_SUBPARTS (TREE_TYPE (addrtype)))
b184c8f1
AM
5549 return fold_build3 (BIT_FIELD_REF, type, TREE_OPERAND (addr, 0),
5550 part_width, index);
5551 }
5552
5553 /* ((foo*)&complexfoo)[1] -> __imag__ complexfoo */
5554 if (TREE_CODE (addr) == ADDR_EXPR
5555 && TREE_CODE (TREE_TYPE (addrtype)) == COMPLEX_TYPE
5556 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (addrtype))))
5557 {
5558 tree size = TYPE_SIZE_UNIT (type);
5559 if (tree_int_cst_equal (size, off))
5560 return fold_build1 (IMAGPART_EXPR, type, TREE_OPERAND (addr, 0));
5561 }
5562
5563 /* *(p + CST) -> MEM_REF <p, CST>. */
5564 if (TREE_CODE (addr) != ADDR_EXPR
5565 || DECL_P (TREE_OPERAND (addr, 0)))
5566 return fold_build2 (MEM_REF, type,
5567 addr,
807e902e 5568 wide_int_to_tree (ptype, off));
b184c8f1
AM
5569 }
5570
5571 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
5572 if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
5573 && TREE_CODE (TYPE_SIZE (TREE_TYPE (TREE_TYPE (subtype)))) == INTEGER_CST
5574 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (subtype))))
5575 {
5576 tree type_domain;
5577 tree min_val = size_zero_node;
5578 tree osub = sub;
5579 sub = gimple_fold_indirect_ref (sub);
5580 if (! sub)
5581 sub = build1 (INDIRECT_REF, TREE_TYPE (subtype), osub);
5582 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
5583 if (type_domain && TYPE_MIN_VALUE (type_domain))
5584 min_val = TYPE_MIN_VALUE (type_domain);
5585 if (TREE_CODE (min_val) == INTEGER_CST)
5586 return build4 (ARRAY_REF, type, sub, min_val, NULL_TREE, NULL_TREE);
5587 }
5588
5589 return NULL_TREE;
5590}
19e51b40
JJ
5591
5592/* Return true if CODE is an operation that when operating on signed
5593 integer types involves undefined behavior on overflow and the
5594 operation can be expressed with unsigned arithmetic. */
5595
5596bool
5597arith_code_with_undefined_signed_overflow (tree_code code)
5598{
5599 switch (code)
5600 {
5601 case PLUS_EXPR:
5602 case MINUS_EXPR:
5603 case MULT_EXPR:
5604 case NEGATE_EXPR:
5605 case POINTER_PLUS_EXPR:
5606 return true;
5607 default:
5608 return false;
5609 }
5610}
5611
5612/* Rewrite STMT, an assignment with a signed integer or pointer arithmetic
5613 operation that can be transformed to unsigned arithmetic by converting
5614 its operand, carrying out the operation in the corresponding unsigned
5615 type and converting the result back to the original type.
5616
5617 Returns a sequence of statements that replace STMT and also contain
5618 a modified form of STMT itself. */
5619
5620gimple_seq
5621rewrite_to_defined_overflow (gimple stmt)
5622{
5623 if (dump_file && (dump_flags & TDF_DETAILS))
5624 {
5625 fprintf (dump_file, "rewriting stmt with undefined signed "
5626 "overflow ");
5627 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
5628 }
5629
5630 tree lhs = gimple_assign_lhs (stmt);
5631 tree type = unsigned_type_for (TREE_TYPE (lhs));
5632 gimple_seq stmts = NULL;
5633 for (unsigned i = 1; i < gimple_num_ops (stmt); ++i)
5634 {
5635 gimple_seq stmts2 = NULL;
5636 gimple_set_op (stmt, i,
5637 force_gimple_operand (fold_convert (type,
5638 gimple_op (stmt, i)),
5639 &stmts2, true, NULL_TREE));
5640 gimple_seq_add_seq (&stmts, stmts2);
5641 }
5642 gimple_assign_set_lhs (stmt, make_ssa_name (type, stmt));
5643 if (gimple_assign_rhs_code (stmt) == POINTER_PLUS_EXPR)
5644 gimple_assign_set_rhs_code (stmt, PLUS_EXPR);
5645 gimple_seq_add_stmt (&stmts, stmt);
00d66391
JJ
5646 gimple cvt = gimple_build_assign_with_ops (NOP_EXPR, lhs,
5647 gimple_assign_lhs (stmt));
19e51b40
JJ
5648 gimple_seq_add_stmt (&stmts, cvt);
5649
5650 return stmts;
5651}
d4f5cd5e 5652
3d2cf79f
RB
5653
5654/* Build the expression CODE OP0 of type TYPE with location LOC,
5655 simplifying it first if possible using VALUEIZE if not NULL.
5656 OP0 is expected to be valueized already. Returns the built
5657 expression value and appends statements possibly defining it
5658 to SEQ. */
5659
5660tree
5661gimple_build (gimple_seq *seq, location_t loc,
5662 enum tree_code code, tree type, tree op0,
5663 tree (*valueize)(tree))
5664{
5665 tree res = gimple_simplify (code, type, op0, seq, valueize);
5666 if (!res)
5667 {
5668 if (gimple_in_ssa_p (cfun))
5669 res = make_ssa_name (type, NULL);
5670 else
5671 res = create_tmp_reg (type, NULL);
5672 gimple stmt;
5673 if (code == REALPART_EXPR
5674 || code == IMAGPART_EXPR
5675 || code == VIEW_CONVERT_EXPR)
5676 stmt = gimple_build_assign_with_ops (code, res,
00d66391 5677 build1 (code, type, op0));
3d2cf79f 5678 else
00d66391 5679 stmt = gimple_build_assign_with_ops (code, res, op0);
3d2cf79f
RB
5680 gimple_set_location (stmt, loc);
5681 gimple_seq_add_stmt_without_update (seq, stmt);
5682 }
5683 return res;
5684}
5685
5686/* Build the expression OP0 CODE OP1 of type TYPE with location LOC,
5687 simplifying it first if possible using VALUEIZE if not NULL.
5688 OP0 and OP1 are expected to be valueized already. Returns the built
5689 expression value and appends statements possibly defining it
5690 to SEQ. */
5691
5692tree
5693gimple_build (gimple_seq *seq, location_t loc,
5694 enum tree_code code, tree type, tree op0, tree op1,
5695 tree (*valueize)(tree))
5696{
5697 tree res = gimple_simplify (code, type, op0, op1, seq, valueize);
5698 if (!res)
5699 {
5700 if (gimple_in_ssa_p (cfun))
5701 res = make_ssa_name (type, NULL);
5702 else
5703 res = create_tmp_reg (type, NULL);
5704 gimple stmt = gimple_build_assign_with_ops (code, res, op0, op1);
5705 gimple_set_location (stmt, loc);
5706 gimple_seq_add_stmt_without_update (seq, stmt);
5707 }
5708 return res;
5709}
5710
5711/* Build the expression (CODE OP0 OP1 OP2) of type TYPE with location LOC,
5712 simplifying it first if possible using VALUEIZE if not NULL.
5713 OP0, OP1 and OP2 are expected to be valueized already. Returns the built
5714 expression value and appends statements possibly defining it
5715 to SEQ. */
5716
5717tree
5718gimple_build (gimple_seq *seq, location_t loc,
5719 enum tree_code code, tree type, tree op0, tree op1, tree op2,
5720 tree (*valueize)(tree))
5721{
5722 tree res = gimple_simplify (code, type, op0, op1, op2,
5723 seq, valueize);
5724 if (!res)
5725 {
5726 if (gimple_in_ssa_p (cfun))
5727 res = make_ssa_name (type, NULL);
5728 else
5729 res = create_tmp_reg (type, NULL);
5730 gimple stmt;
5731 if (code == BIT_FIELD_REF)
5732 stmt = gimple_build_assign_with_ops (code, res,
5733 build3 (BIT_FIELD_REF, type,
00d66391 5734 op0, op1, op2));
3d2cf79f
RB
5735 else
5736 stmt = gimple_build_assign_with_ops (code, res, op0, op1, op2);
5737 gimple_set_location (stmt, loc);
5738 gimple_seq_add_stmt_without_update (seq, stmt);
5739 }
5740 return res;
5741}
5742
5743/* Build the call FN (ARG0) with a result of type TYPE
5744 (or no result if TYPE is void) with location LOC,
5745 simplifying it first if possible using VALUEIZE if not NULL.
5746 ARG0 is expected to be valueized already. Returns the built
5747 expression value (or NULL_TREE if TYPE is void) and appends
5748 statements possibly defining it to SEQ. */
5749
5750tree
5751gimple_build (gimple_seq *seq, location_t loc,
5752 enum built_in_function fn, tree type, tree arg0,
5753 tree (*valueize)(tree))
5754{
5755 tree res = gimple_simplify (fn, type, arg0, seq, valueize);
5756 if (!res)
5757 {
5758 tree decl = builtin_decl_implicit (fn);
5759 gimple stmt = gimple_build_call (decl, 1, arg0);
5760 if (!VOID_TYPE_P (type))
5761 {
5762 if (gimple_in_ssa_p (cfun))
5763 res = make_ssa_name (type, NULL);
5764 else
5765 res = create_tmp_reg (type, NULL);
5766 gimple_call_set_lhs (stmt, res);
5767 }
5768 gimple_set_location (stmt, loc);
5769 gimple_seq_add_stmt_without_update (seq, stmt);
5770 }
5771 return res;
5772}
5773
5774/* Build the call FN (ARG0, ARG1) with a result of type TYPE
5775 (or no result if TYPE is void) with location LOC,
5776 simplifying it first if possible using VALUEIZE if not NULL.
5777 ARG0 is expected to be valueized already. Returns the built
5778 expression value (or NULL_TREE if TYPE is void) and appends
5779 statements possibly defining it to SEQ. */
5780
5781tree
5782gimple_build (gimple_seq *seq, location_t loc,
5783 enum built_in_function fn, tree type, tree arg0, tree arg1,
5784 tree (*valueize)(tree))
5785{
5786 tree res = gimple_simplify (fn, type, arg0, arg1, seq, valueize);
5787 if (!res)
5788 {
5789 tree decl = builtin_decl_implicit (fn);
5790 gimple stmt = gimple_build_call (decl, 2, arg0, arg1);
5791 if (!VOID_TYPE_P (type))
5792 {
5793 if (gimple_in_ssa_p (cfun))
5794 res = make_ssa_name (type, NULL);
5795 else
5796 res = create_tmp_reg (type, NULL);
5797 gimple_call_set_lhs (stmt, res);
5798 }
5799 gimple_set_location (stmt, loc);
5800 gimple_seq_add_stmt_without_update (seq, stmt);
5801 }
5802 return res;
5803}
5804
5805/* Build the call FN (ARG0, ARG1, ARG2) with a result of type TYPE
5806 (or no result if TYPE is void) with location LOC,
5807 simplifying it first if possible using VALUEIZE if not NULL.
5808 ARG0 is expected to be valueized already. Returns the built
5809 expression value (or NULL_TREE if TYPE is void) and appends
5810 statements possibly defining it to SEQ. */
5811
5812tree
5813gimple_build (gimple_seq *seq, location_t loc,
5814 enum built_in_function fn, tree type,
5815 tree arg0, tree arg1, tree arg2,
5816 tree (*valueize)(tree))
5817{
5818 tree res = gimple_simplify (fn, type, arg0, arg1, arg2, seq, valueize);
5819 if (!res)
5820 {
5821 tree decl = builtin_decl_implicit (fn);
5822 gimple stmt = gimple_build_call (decl, 3, arg0, arg1, arg2);
5823 if (!VOID_TYPE_P (type))
5824 {
5825 if (gimple_in_ssa_p (cfun))
5826 res = make_ssa_name (type, NULL);
5827 else
5828 res = create_tmp_reg (type, NULL);
5829 gimple_call_set_lhs (stmt, res);
5830 }
5831 gimple_set_location (stmt, loc);
5832 gimple_seq_add_stmt_without_update (seq, stmt);
5833 }
5834 return res;
5835}
5836
5837/* Build the conversion (TYPE) OP with a result of type TYPE
5838 with location LOC if such conversion is neccesary in GIMPLE,
5839 simplifying it first.
5840 Returns the built expression value and appends
5841 statements possibly defining it to SEQ. */
d4f5cd5e
RB
5842
5843tree
5844gimple_convert (gimple_seq *seq, location_t loc, tree type, tree op)
5845{
5846 if (useless_type_conversion_p (type, TREE_TYPE (op)))
5847 return op;
3d2cf79f 5848 return gimple_build (seq, loc, NOP_EXPR, type, op);
d4f5cd5e 5849}