Import pre-release gcc-5.0 to new vendor branch
[dragonfly.git] / contrib / gcc-5.0 / gcc / fold-const.c
1 /* Fold a constant sub-tree into a single node for C-compiler
2    Copyright (C) 1987-2015 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
10
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3.  If not see
18 <http://www.gnu.org/licenses/>.  */
19
20 /*@@ This file should be rewritten to use an arbitrary precision
21   @@ representation for "struct tree_int_cst" and "struct tree_real_cst".
22   @@ Perhaps the routines could also be used for bc/dc, and made a lib.
23   @@ The routines that translate from the ap rep should
24   @@ warn if precision et. al. is lost.
25   @@ This would also make life easier when this technology is used
26   @@ for cross-compilers.  */
27
28 /* The entry points in this file are fold, size_int_wide and size_binop.
29
30    fold takes a tree as argument and returns a simplified tree.
31
32    size_binop takes a tree code for an arithmetic operation
33    and two operands that are trees, and produces a tree for the
34    result, assuming the type comes from `sizetype'.
35
36    size_int takes an integer value, and creates a tree constant
37    with type from `sizetype'.
38
39    Note: Since the folders get called on non-gimple code as well as
40    gimple code, we need to handle GIMPLE tuples as well as their
41    corresponding tree equivalents.  */
42
43 #include "config.h"
44 #include "system.h"
45 #include "coretypes.h"
46 #include "tm.h"
47 #include "flags.h"
48 #include "hash-set.h"
49 #include "machmode.h"
50 #include "vec.h"
51 #include "double-int.h"
52 #include "input.h"
53 #include "alias.h"
54 #include "symtab.h"
55 #include "wide-int.h"
56 #include "inchash.h"
57 #include "tree.h"
58 #include "fold-const.h"
59 #include "stor-layout.h"
60 #include "calls.h"
61 #include "tree-iterator.h"
62 #include "realmpfr.h"
63 #include "rtl.h"
64 #include "hashtab.h"
65 #include "hard-reg-set.h"
66 #include "function.h"
67 #include "statistics.h"
68 #include "real.h"
69 #include "fixed-value.h"
70 #include "insn-config.h"
71 #include "expmed.h"
72 #include "dojump.h"
73 #include "explow.h"
74 #include "emit-rtl.h"
75 #include "varasm.h"
76 #include "stmt.h"
77 #include "expr.h"
78 #include "tm_p.h"
79 #include "target.h"
80 #include "diagnostic-core.h"
81 #include "intl.h"
82 #include "langhooks.h"
83 #include "md5.h"
84 #include "predict.h"
85 #include "basic-block.h"
86 #include "tree-ssa-alias.h"
87 #include "internal-fn.h"
88 #include "tree-eh.h"
89 #include "gimple-expr.h"
90 #include "is-a.h"
91 #include "gimple.h"
92 #include "gimplify.h"
93 #include "tree-dfa.h"
94 #include "hash-table.h"  /* Required for ENABLE_FOLD_CHECKING.  */
95 #include "builtins.h"
96 #include "hash-map.h"
97 #include "plugin-api.h"
98 #include "ipa-ref.h"
99 #include "cgraph.h"
100 #include "generic-match.h"
101 #include "optabs.h"
102
103 /* Nonzero if we are folding constants inside an initializer; zero
104    otherwise.  */
105 int folding_initializer = 0;
106
107 /* The following constants represent a bit based encoding of GCC's
108    comparison operators.  This encoding simplifies transformations
109    on relational comparison operators, such as AND and OR.  */
110 enum comparison_code {
111   COMPCODE_FALSE = 0,
112   COMPCODE_LT = 1,
113   COMPCODE_EQ = 2,
114   COMPCODE_LE = 3,
115   COMPCODE_GT = 4,
116   COMPCODE_LTGT = 5,
117   COMPCODE_GE = 6,
118   COMPCODE_ORD = 7,
119   COMPCODE_UNORD = 8,
120   COMPCODE_UNLT = 9,
121   COMPCODE_UNEQ = 10,
122   COMPCODE_UNLE = 11,
123   COMPCODE_UNGT = 12,
124   COMPCODE_NE = 13,
125   COMPCODE_UNGE = 14,
126   COMPCODE_TRUE = 15
127 };
128
129 static bool negate_mathfn_p (enum built_in_function);
130 static bool negate_expr_p (tree);
131 static tree negate_expr (tree);
132 static tree split_tree (tree, enum tree_code, tree *, tree *, tree *, int);
133 static tree associate_trees (location_t, tree, tree, enum tree_code, tree);
134 static enum comparison_code comparison_to_compcode (enum tree_code);
135 static enum tree_code compcode_to_comparison (enum comparison_code);
136 static int operand_equal_for_comparison_p (tree, tree, tree);
137 static int twoval_comparison_p (tree, tree *, tree *, int *);
138 static tree eval_subst (location_t, tree, tree, tree, tree, tree);
139 static tree distribute_bit_expr (location_t, enum tree_code, tree, tree, tree);
140 static tree make_bit_field_ref (location_t, tree, tree,
141                                 HOST_WIDE_INT, HOST_WIDE_INT, int);
142 static tree optimize_bit_field_compare (location_t, enum tree_code,
143                                         tree, tree, tree);
144 static tree decode_field_reference (location_t, tree, HOST_WIDE_INT *,
145                                     HOST_WIDE_INT *,
146                                     machine_mode *, int *, int *,
147                                     tree *, tree *);
148 static int simple_operand_p (const_tree);
149 static bool simple_operand_p_2 (tree);
150 static tree range_binop (enum tree_code, tree, tree, int, tree, int);
151 static tree range_predecessor (tree);
152 static tree range_successor (tree);
153 static tree fold_range_test (location_t, enum tree_code, tree, tree, tree);
154 static tree fold_cond_expr_with_comparison (location_t, tree, tree, tree, tree);
155 static tree unextend (tree, int, int, tree);
156 static tree optimize_minmax_comparison (location_t, enum tree_code,
157                                         tree, tree, tree);
158 static tree extract_muldiv (tree, tree, enum tree_code, tree, bool *);
159 static tree extract_muldiv_1 (tree, tree, enum tree_code, tree, bool *);
160 static tree fold_binary_op_with_conditional_arg (location_t,
161                                                  enum tree_code, tree,
162                                                  tree, tree,
163                                                  tree, tree, int);
164 static tree fold_mathfn_compare (location_t,
165                                  enum built_in_function, enum tree_code,
166                                  tree, tree, tree);
167 static tree fold_inf_compare (location_t, enum tree_code, tree, tree, tree);
168 static tree fold_div_compare (location_t, enum tree_code, tree, tree, tree);
169 static bool reorder_operands_p (const_tree, const_tree);
170 static tree fold_negate_const (tree, tree);
171 static tree fold_not_const (const_tree, tree);
172 static tree fold_relational_const (enum tree_code, tree, tree, tree);
173 static tree fold_convert_const (enum tree_code, tree, tree);
174 static tree fold_view_convert_expr (tree, tree);
175 static bool vec_cst_ctor_to_array (tree, tree *);
176
177
178 /* Return EXPR_LOCATION of T if it is not UNKNOWN_LOCATION.
179    Otherwise, return LOC.  */
180
181 static location_t
182 expr_location_or (tree t, location_t loc)
183 {
184   location_t tloc = EXPR_LOCATION (t);
185   return tloc == UNKNOWN_LOCATION ? loc : tloc;
186 }
187
188 /* Similar to protected_set_expr_location, but never modify x in place,
189    if location can and needs to be set, unshare it.  */
190
191 static inline tree
192 protected_set_expr_location_unshare (tree x, location_t loc)
193 {
194   if (CAN_HAVE_LOCATION_P (x)
195       && EXPR_LOCATION (x) != loc
196       && !(TREE_CODE (x) == SAVE_EXPR
197            || TREE_CODE (x) == TARGET_EXPR
198            || TREE_CODE (x) == BIND_EXPR))
199     {
200       x = copy_node (x);
201       SET_EXPR_LOCATION (x, loc);
202     }
203   return x;
204 }
205 \f
206 /* If ARG2 divides ARG1 with zero remainder, carries out the exact
207    division and returns the quotient.  Otherwise returns
208    NULL_TREE.  */
209
210 tree
211 div_if_zero_remainder (const_tree arg1, const_tree arg2)
212 {
213   widest_int quo;
214
215   if (wi::multiple_of_p (wi::to_widest (arg1), wi::to_widest (arg2),
216                          SIGNED, &quo))
217     return wide_int_to_tree (TREE_TYPE (arg1), quo);
218
219   return NULL_TREE; 
220 }
221 \f
222 /* This is nonzero if we should defer warnings about undefined
223    overflow.  This facility exists because these warnings are a
224    special case.  The code to estimate loop iterations does not want
225    to issue any warnings, since it works with expressions which do not
226    occur in user code.  Various bits of cleanup code call fold(), but
227    only use the result if it has certain characteristics (e.g., is a
228    constant); that code only wants to issue a warning if the result is
229    used.  */
230
231 static int fold_deferring_overflow_warnings;
232
233 /* If a warning about undefined overflow is deferred, this is the
234    warning.  Note that this may cause us to turn two warnings into
235    one, but that is fine since it is sufficient to only give one
236    warning per expression.  */
237
238 static const char* fold_deferred_overflow_warning;
239
240 /* If a warning about undefined overflow is deferred, this is the
241    level at which the warning should be emitted.  */
242
243 static enum warn_strict_overflow_code fold_deferred_overflow_code;
244
245 /* Start deferring overflow warnings.  We could use a stack here to
246    permit nested calls, but at present it is not necessary.  */
247
248 void
249 fold_defer_overflow_warnings (void)
250 {
251   ++fold_deferring_overflow_warnings;
252 }
253
254 /* Stop deferring overflow warnings.  If there is a pending warning,
255    and ISSUE is true, then issue the warning if appropriate.  STMT is
256    the statement with which the warning should be associated (used for
257    location information); STMT may be NULL.  CODE is the level of the
258    warning--a warn_strict_overflow_code value.  This function will use
259    the smaller of CODE and the deferred code when deciding whether to
260    issue the warning.  CODE may be zero to mean to always use the
261    deferred code.  */
262
263 void
264 fold_undefer_overflow_warnings (bool issue, const_gimple stmt, int code)
265 {
266   const char *warnmsg;
267   location_t locus;
268
269   gcc_assert (fold_deferring_overflow_warnings > 0);
270   --fold_deferring_overflow_warnings;
271   if (fold_deferring_overflow_warnings > 0)
272     {
273       if (fold_deferred_overflow_warning != NULL
274           && code != 0
275           && code < (int) fold_deferred_overflow_code)
276         fold_deferred_overflow_code = (enum warn_strict_overflow_code) code;
277       return;
278     }
279
280   warnmsg = fold_deferred_overflow_warning;
281   fold_deferred_overflow_warning = NULL;
282
283   if (!issue || warnmsg == NULL)
284     return;
285
286   if (gimple_no_warning_p (stmt))
287     return;
288
289   /* Use the smallest code level when deciding to issue the
290      warning.  */
291   if (code == 0 || code > (int) fold_deferred_overflow_code)
292     code = fold_deferred_overflow_code;
293
294   if (!issue_strict_overflow_warning (code))
295     return;
296
297   if (stmt == NULL)
298     locus = input_location;
299   else
300     locus = gimple_location (stmt);
301   warning_at (locus, OPT_Wstrict_overflow, "%s", warnmsg);
302 }
303
304 /* Stop deferring overflow warnings, ignoring any deferred
305    warnings.  */
306
307 void
308 fold_undefer_and_ignore_overflow_warnings (void)
309 {
310   fold_undefer_overflow_warnings (false, NULL, 0);
311 }
312
313 /* Whether we are deferring overflow warnings.  */
314
315 bool
316 fold_deferring_overflow_warnings_p (void)
317 {
318   return fold_deferring_overflow_warnings > 0;
319 }
320
321 /* This is called when we fold something based on the fact that signed
322    overflow is undefined.  */
323
324 static void
325 fold_overflow_warning (const char* gmsgid, enum warn_strict_overflow_code wc)
326 {
327   if (fold_deferring_overflow_warnings > 0)
328     {
329       if (fold_deferred_overflow_warning == NULL
330           || wc < fold_deferred_overflow_code)
331         {
332           fold_deferred_overflow_warning = gmsgid;
333           fold_deferred_overflow_code = wc;
334         }
335     }
336   else if (issue_strict_overflow_warning (wc))
337     warning (OPT_Wstrict_overflow, gmsgid);
338 }
339 \f
340 /* Return true if the built-in mathematical function specified by CODE
341    is odd, i.e. -f(x) == f(-x).  */
342
343 static bool
344 negate_mathfn_p (enum built_in_function code)
345 {
346   switch (code)
347     {
348     CASE_FLT_FN (BUILT_IN_ASIN):
349     CASE_FLT_FN (BUILT_IN_ASINH):
350     CASE_FLT_FN (BUILT_IN_ATAN):
351     CASE_FLT_FN (BUILT_IN_ATANH):
352     CASE_FLT_FN (BUILT_IN_CASIN):
353     CASE_FLT_FN (BUILT_IN_CASINH):
354     CASE_FLT_FN (BUILT_IN_CATAN):
355     CASE_FLT_FN (BUILT_IN_CATANH):
356     CASE_FLT_FN (BUILT_IN_CBRT):
357     CASE_FLT_FN (BUILT_IN_CPROJ):
358     CASE_FLT_FN (BUILT_IN_CSIN):
359     CASE_FLT_FN (BUILT_IN_CSINH):
360     CASE_FLT_FN (BUILT_IN_CTAN):
361     CASE_FLT_FN (BUILT_IN_CTANH):
362     CASE_FLT_FN (BUILT_IN_ERF):
363     CASE_FLT_FN (BUILT_IN_LLROUND):
364     CASE_FLT_FN (BUILT_IN_LROUND):
365     CASE_FLT_FN (BUILT_IN_ROUND):
366     CASE_FLT_FN (BUILT_IN_SIN):
367     CASE_FLT_FN (BUILT_IN_SINH):
368     CASE_FLT_FN (BUILT_IN_TAN):
369     CASE_FLT_FN (BUILT_IN_TANH):
370     CASE_FLT_FN (BUILT_IN_TRUNC):
371       return true;
372
373     CASE_FLT_FN (BUILT_IN_LLRINT):
374     CASE_FLT_FN (BUILT_IN_LRINT):
375     CASE_FLT_FN (BUILT_IN_NEARBYINT):
376     CASE_FLT_FN (BUILT_IN_RINT):
377       return !flag_rounding_math;
378
379     default:
380       break;
381     }
382   return false;
383 }
384
385 /* Check whether we may negate an integer constant T without causing
386    overflow.  */
387
388 bool
389 may_negate_without_overflow_p (const_tree t)
390 {
391   tree type;
392
393   gcc_assert (TREE_CODE (t) == INTEGER_CST);
394
395   type = TREE_TYPE (t);
396   if (TYPE_UNSIGNED (type))
397     return false;
398
399   return !wi::only_sign_bit_p (t);
400 }
401
402 /* Determine whether an expression T can be cheaply negated using
403    the function negate_expr without introducing undefined overflow.  */
404
405 static bool
406 negate_expr_p (tree t)
407 {
408   tree type;
409
410   if (t == 0)
411     return false;
412
413   type = TREE_TYPE (t);
414
415   STRIP_SIGN_NOPS (t);
416   switch (TREE_CODE (t))
417     {
418     case INTEGER_CST:
419       if (INTEGRAL_TYPE_P (type) && TYPE_OVERFLOW_WRAPS (type))
420         return true;
421
422       /* Check that -CST will not overflow type.  */
423       return may_negate_without_overflow_p (t);
424     case BIT_NOT_EXPR:
425       return (INTEGRAL_TYPE_P (type)
426               && TYPE_OVERFLOW_WRAPS (type));
427
428     case FIXED_CST:
429       return true;
430
431     case NEGATE_EXPR:
432       return !TYPE_OVERFLOW_SANITIZED (type);
433
434     case REAL_CST:
435       /* We want to canonicalize to positive real constants.  Pretend
436          that only negative ones can be easily negated.  */
437       return REAL_VALUE_NEGATIVE (TREE_REAL_CST (t));
438
439     case COMPLEX_CST:
440       return negate_expr_p (TREE_REALPART (t))
441              && negate_expr_p (TREE_IMAGPART (t));
442
443     case VECTOR_CST:
444       {
445         if (FLOAT_TYPE_P (TREE_TYPE (type)) || TYPE_OVERFLOW_WRAPS (type))
446           return true;
447
448         int count = TYPE_VECTOR_SUBPARTS (type), i;
449
450         for (i = 0; i < count; i++)
451           if (!negate_expr_p (VECTOR_CST_ELT (t, i)))
452             return false;
453
454         return true;
455       }
456
457     case COMPLEX_EXPR:
458       return negate_expr_p (TREE_OPERAND (t, 0))
459              && negate_expr_p (TREE_OPERAND (t, 1));
460
461     case CONJ_EXPR:
462       return negate_expr_p (TREE_OPERAND (t, 0));
463
464     case PLUS_EXPR:
465       if (HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (type))
466           || HONOR_SIGNED_ZEROS (element_mode (type)))
467         return false;
468       /* -(A + B) -> (-B) - A.  */
469       if (negate_expr_p (TREE_OPERAND (t, 1))
470           && reorder_operands_p (TREE_OPERAND (t, 0),
471                                  TREE_OPERAND (t, 1)))
472         return true;
473       /* -(A + B) -> (-A) - B.  */
474       return negate_expr_p (TREE_OPERAND (t, 0));
475
476     case MINUS_EXPR:
477       /* We can't turn -(A-B) into B-A when we honor signed zeros.  */
478       return !HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (type))
479              && !HONOR_SIGNED_ZEROS (element_mode (type))
480              && reorder_operands_p (TREE_OPERAND (t, 0),
481                                     TREE_OPERAND (t, 1));
482
483     case MULT_EXPR:
484       if (TYPE_UNSIGNED (TREE_TYPE (t)))
485         break;
486
487       /* Fall through.  */
488
489     case RDIV_EXPR:
490       if (! HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (TREE_TYPE (t))))
491         return negate_expr_p (TREE_OPERAND (t, 1))
492                || negate_expr_p (TREE_OPERAND (t, 0));
493       break;
494
495     case TRUNC_DIV_EXPR:
496     case ROUND_DIV_EXPR:
497     case EXACT_DIV_EXPR:
498       /* In general we can't negate A / B, because if A is INT_MIN and
499          B is 1, we may turn this into INT_MIN / -1 which is undefined
500          and actually traps on some architectures.  But if overflow is
501          undefined, we can negate, because - (INT_MIN / 1) is an
502          overflow.  */
503       if (INTEGRAL_TYPE_P (TREE_TYPE (t)))
504         {
505           if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (t)))
506             break;
507           /* If overflow is undefined then we have to be careful because
508              we ask whether it's ok to associate the negate with the
509              division which is not ok for example for
510              -((a - b) / c) where (-(a - b)) / c may invoke undefined
511              overflow because of negating INT_MIN.  So do not use
512              negate_expr_p here but open-code the two important cases.  */
513           if (TREE_CODE (TREE_OPERAND (t, 0)) == NEGATE_EXPR
514               || (TREE_CODE (TREE_OPERAND (t, 0)) == INTEGER_CST
515                   && may_negate_without_overflow_p (TREE_OPERAND (t, 0))))
516             return true;
517         }
518       else if (negate_expr_p (TREE_OPERAND (t, 0)))
519         return true;
520       return negate_expr_p (TREE_OPERAND (t, 1));
521
522     case NOP_EXPR:
523       /* Negate -((double)float) as (double)(-float).  */
524       if (TREE_CODE (type) == REAL_TYPE)
525         {
526           tree tem = strip_float_extensions (t);
527           if (tem != t)
528             return negate_expr_p (tem);
529         }
530       break;
531
532     case CALL_EXPR:
533       /* Negate -f(x) as f(-x).  */
534       if (negate_mathfn_p (builtin_mathfn_code (t)))
535         return negate_expr_p (CALL_EXPR_ARG (t, 0));
536       break;
537
538     case RSHIFT_EXPR:
539       /* Optimize -((int)x >> 31) into (unsigned)x >> 31 for int.  */
540       if (TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST)
541         {
542           tree op1 = TREE_OPERAND (t, 1);
543           if (wi::eq_p (op1, TYPE_PRECISION (type) - 1))
544             return true;
545         }
546       break;
547
548     default:
549       break;
550     }
551   return false;
552 }
553
554 /* Given T, an expression, return a folded tree for -T or NULL_TREE, if no
555    simplification is possible.
556    If negate_expr_p would return true for T, NULL_TREE will never be
557    returned.  */
558
559 static tree
560 fold_negate_expr (location_t loc, tree t)
561 {
562   tree type = TREE_TYPE (t);
563   tree tem;
564
565   switch (TREE_CODE (t))
566     {
567     /* Convert - (~A) to A + 1.  */
568     case BIT_NOT_EXPR:
569       if (INTEGRAL_TYPE_P (type))
570         return fold_build2_loc (loc, PLUS_EXPR, type, TREE_OPERAND (t, 0),
571                             build_one_cst (type));
572       break;
573
574     case INTEGER_CST:
575       tem = fold_negate_const (t, type);
576       if (TREE_OVERFLOW (tem) == TREE_OVERFLOW (t)
577           || (ANY_INTEGRAL_TYPE_P (type)
578               && !TYPE_OVERFLOW_TRAPS (type)
579               && TYPE_OVERFLOW_WRAPS (type))
580           || (flag_sanitize & SANITIZE_SI_OVERFLOW) == 0)
581         return tem;
582       break;
583
584     case REAL_CST:
585       tem = fold_negate_const (t, type);
586       return tem;
587
588     case FIXED_CST:
589       tem = fold_negate_const (t, type);
590       return tem;
591
592     case COMPLEX_CST:
593       {
594         tree rpart = fold_negate_expr (loc, TREE_REALPART (t));
595         tree ipart = fold_negate_expr (loc, TREE_IMAGPART (t));
596         if (rpart && ipart)
597           return build_complex (type, rpart, ipart);
598       }
599       break;
600
601     case VECTOR_CST:
602       {
603         int count = TYPE_VECTOR_SUBPARTS (type), i;
604         tree *elts = XALLOCAVEC (tree, count);
605
606         for (i = 0; i < count; i++)
607           {
608             elts[i] = fold_negate_expr (loc, VECTOR_CST_ELT (t, i));
609             if (elts[i] == NULL_TREE)
610               return NULL_TREE;
611           }
612
613         return build_vector (type, elts);
614       }
615
616     case COMPLEX_EXPR:
617       if (negate_expr_p (t))
618         return fold_build2_loc (loc, COMPLEX_EXPR, type,
619                             fold_negate_expr (loc, TREE_OPERAND (t, 0)),
620                             fold_negate_expr (loc, TREE_OPERAND (t, 1)));
621       break;
622
623     case CONJ_EXPR:
624       if (negate_expr_p (t))
625         return fold_build1_loc (loc, CONJ_EXPR, type,
626                             fold_negate_expr (loc, TREE_OPERAND (t, 0)));
627       break;
628
629     case NEGATE_EXPR:
630       if (!TYPE_OVERFLOW_SANITIZED (type))
631         return TREE_OPERAND (t, 0);
632       break;
633
634     case PLUS_EXPR:
635       if (!HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (type))
636           && !HONOR_SIGNED_ZEROS (element_mode (type)))
637         {
638           /* -(A + B) -> (-B) - A.  */
639           if (negate_expr_p (TREE_OPERAND (t, 1))
640               && reorder_operands_p (TREE_OPERAND (t, 0),
641                                      TREE_OPERAND (t, 1)))
642             {
643               tem = negate_expr (TREE_OPERAND (t, 1));
644               return fold_build2_loc (loc, MINUS_EXPR, type,
645                                   tem, TREE_OPERAND (t, 0));
646             }
647
648           /* -(A + B) -> (-A) - B.  */
649           if (negate_expr_p (TREE_OPERAND (t, 0)))
650             {
651               tem = negate_expr (TREE_OPERAND (t, 0));
652               return fold_build2_loc (loc, MINUS_EXPR, type,
653                                   tem, TREE_OPERAND (t, 1));
654             }
655         }
656       break;
657
658     case MINUS_EXPR:
659       /* - (A - B) -> B - A  */
660       if (!HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (type))
661           && !HONOR_SIGNED_ZEROS (element_mode (type))
662           && reorder_operands_p (TREE_OPERAND (t, 0), TREE_OPERAND (t, 1)))
663         return fold_build2_loc (loc, MINUS_EXPR, type,
664                             TREE_OPERAND (t, 1), TREE_OPERAND (t, 0));
665       break;
666
667     case MULT_EXPR:
668       if (TYPE_UNSIGNED (type))
669         break;
670
671       /* Fall through.  */
672
673     case RDIV_EXPR:
674       if (! HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (type)))
675         {
676           tem = TREE_OPERAND (t, 1);
677           if (negate_expr_p (tem))
678             return fold_build2_loc (loc, TREE_CODE (t), type,
679                                 TREE_OPERAND (t, 0), negate_expr (tem));
680           tem = TREE_OPERAND (t, 0);
681           if (negate_expr_p (tem))
682             return fold_build2_loc (loc, TREE_CODE (t), type,
683                                 negate_expr (tem), TREE_OPERAND (t, 1));
684         }
685       break;
686
687     case TRUNC_DIV_EXPR:
688     case ROUND_DIV_EXPR:
689     case EXACT_DIV_EXPR:
690       /* In general we can't negate A / B, because if A is INT_MIN and
691          B is 1, we may turn this into INT_MIN / -1 which is undefined
692          and actually traps on some architectures.  But if overflow is
693          undefined, we can negate, because - (INT_MIN / 1) is an
694          overflow.  */
695       if (!INTEGRAL_TYPE_P (type) || TYPE_OVERFLOW_UNDEFINED (type))
696         {
697           const char * const warnmsg = G_("assuming signed overflow does not "
698                                           "occur when negating a division");
699           tem = TREE_OPERAND (t, 1);
700           if (negate_expr_p (tem))
701             {
702               if (INTEGRAL_TYPE_P (type)
703                   && (TREE_CODE (tem) != INTEGER_CST
704                       || integer_onep (tem)))
705                 fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_MISC);
706               return fold_build2_loc (loc, TREE_CODE (t), type,
707                                   TREE_OPERAND (t, 0), negate_expr (tem));
708             }
709           /* If overflow is undefined then we have to be careful because
710              we ask whether it's ok to associate the negate with the
711              division which is not ok for example for
712              -((a - b) / c) where (-(a - b)) / c may invoke undefined
713              overflow because of negating INT_MIN.  So do not use
714              negate_expr_p here but open-code the two important cases.  */
715           tem = TREE_OPERAND (t, 0);
716           if ((INTEGRAL_TYPE_P (type)
717                && (TREE_CODE (tem) == NEGATE_EXPR
718                    || (TREE_CODE (tem) == INTEGER_CST
719                        && may_negate_without_overflow_p (tem))))
720               || !INTEGRAL_TYPE_P (type))
721             return fold_build2_loc (loc, TREE_CODE (t), type,
722                                     negate_expr (tem), TREE_OPERAND (t, 1));
723         }
724       break;
725
726     case NOP_EXPR:
727       /* Convert -((double)float) into (double)(-float).  */
728       if (TREE_CODE (type) == REAL_TYPE)
729         {
730           tem = strip_float_extensions (t);
731           if (tem != t && negate_expr_p (tem))
732             return fold_convert_loc (loc, type, negate_expr (tem));
733         }
734       break;
735
736     case CALL_EXPR:
737       /* Negate -f(x) as f(-x).  */
738       if (negate_mathfn_p (builtin_mathfn_code (t))
739           && negate_expr_p (CALL_EXPR_ARG (t, 0)))
740         {
741           tree fndecl, arg;
742
743           fndecl = get_callee_fndecl (t);
744           arg = negate_expr (CALL_EXPR_ARG (t, 0));
745           return build_call_expr_loc (loc, fndecl, 1, arg);
746         }
747       break;
748
749     case RSHIFT_EXPR:
750       /* Optimize -((int)x >> 31) into (unsigned)x >> 31 for int.  */
751       if (TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST)
752         {
753           tree op1 = TREE_OPERAND (t, 1);
754           if (wi::eq_p (op1, TYPE_PRECISION (type) - 1))
755             {
756               tree ntype = TYPE_UNSIGNED (type)
757                            ? signed_type_for (type)
758                            : unsigned_type_for (type);
759               tree temp = fold_convert_loc (loc, ntype, TREE_OPERAND (t, 0));
760               temp = fold_build2_loc (loc, RSHIFT_EXPR, ntype, temp, op1);
761               return fold_convert_loc (loc, type, temp);
762             }
763         }
764       break;
765
766     default:
767       break;
768     }
769
770   return NULL_TREE;
771 }
772
773 /* Like fold_negate_expr, but return a NEGATE_EXPR tree, if T can not be
774    negated in a simpler way.  Also allow for T to be NULL_TREE, in which case
775    return NULL_TREE. */
776
777 static tree
778 negate_expr (tree t)
779 {
780   tree type, tem;
781   location_t loc;
782
783   if (t == NULL_TREE)
784     return NULL_TREE;
785
786   loc = EXPR_LOCATION (t);
787   type = TREE_TYPE (t);
788   STRIP_SIGN_NOPS (t);
789
790   tem = fold_negate_expr (loc, t);
791   if (!tem)
792     tem = build1_loc (loc, NEGATE_EXPR, TREE_TYPE (t), t);
793   return fold_convert_loc (loc, type, tem);
794 }
795 \f
796 /* Split a tree IN into a constant, literal and variable parts that could be
797    combined with CODE to make IN.  "constant" means an expression with
798    TREE_CONSTANT but that isn't an actual constant.  CODE must be a
799    commutative arithmetic operation.  Store the constant part into *CONP,
800    the literal in *LITP and return the variable part.  If a part isn't
801    present, set it to null.  If the tree does not decompose in this way,
802    return the entire tree as the variable part and the other parts as null.
803
804    If CODE is PLUS_EXPR we also split trees that use MINUS_EXPR.  In that
805    case, we negate an operand that was subtracted.  Except if it is a
806    literal for which we use *MINUS_LITP instead.
807
808    If NEGATE_P is true, we are negating all of IN, again except a literal
809    for which we use *MINUS_LITP instead.
810
811    If IN is itself a literal or constant, return it as appropriate.
812
813    Note that we do not guarantee that any of the three values will be the
814    same type as IN, but they will have the same signedness and mode.  */
815
816 static tree
817 split_tree (tree in, enum tree_code code, tree *conp, tree *litp,
818             tree *minus_litp, int negate_p)
819 {
820   tree var = 0;
821
822   *conp = 0;
823   *litp = 0;
824   *minus_litp = 0;
825
826   /* Strip any conversions that don't change the machine mode or signedness.  */
827   STRIP_SIGN_NOPS (in);
828
829   if (TREE_CODE (in) == INTEGER_CST || TREE_CODE (in) == REAL_CST
830       || TREE_CODE (in) == FIXED_CST)
831     *litp = in;
832   else if (TREE_CODE (in) == code
833            || ((! FLOAT_TYPE_P (TREE_TYPE (in)) || flag_associative_math)
834                && ! SAT_FIXED_POINT_TYPE_P (TREE_TYPE (in))
835                /* We can associate addition and subtraction together (even
836                   though the C standard doesn't say so) for integers because
837                   the value is not affected.  For reals, the value might be
838                   affected, so we can't.  */
839                && ((code == PLUS_EXPR && TREE_CODE (in) == MINUS_EXPR)
840                    || (code == MINUS_EXPR && TREE_CODE (in) == PLUS_EXPR))))
841     {
842       tree op0 = TREE_OPERAND (in, 0);
843       tree op1 = TREE_OPERAND (in, 1);
844       int neg1_p = TREE_CODE (in) == MINUS_EXPR;
845       int neg_litp_p = 0, neg_conp_p = 0, neg_var_p = 0;
846
847       /* First see if either of the operands is a literal, then a constant.  */
848       if (TREE_CODE (op0) == INTEGER_CST || TREE_CODE (op0) == REAL_CST
849           || TREE_CODE (op0) == FIXED_CST)
850         *litp = op0, op0 = 0;
851       else if (TREE_CODE (op1) == INTEGER_CST || TREE_CODE (op1) == REAL_CST
852                || TREE_CODE (op1) == FIXED_CST)
853         *litp = op1, neg_litp_p = neg1_p, op1 = 0;
854
855       if (op0 != 0 && TREE_CONSTANT (op0))
856         *conp = op0, op0 = 0;
857       else if (op1 != 0 && TREE_CONSTANT (op1))
858         *conp = op1, neg_conp_p = neg1_p, op1 = 0;
859
860       /* If we haven't dealt with either operand, this is not a case we can
861          decompose.  Otherwise, VAR is either of the ones remaining, if any.  */
862       if (op0 != 0 && op1 != 0)
863         var = in;
864       else if (op0 != 0)
865         var = op0;
866       else
867         var = op1, neg_var_p = neg1_p;
868
869       /* Now do any needed negations.  */
870       if (neg_litp_p)
871         *minus_litp = *litp, *litp = 0;
872       if (neg_conp_p)
873         *conp = negate_expr (*conp);
874       if (neg_var_p)
875         var = negate_expr (var);
876     }
877   else if (TREE_CODE (in) == BIT_NOT_EXPR
878            && code == PLUS_EXPR)
879     {
880       /* -X - 1 is folded to ~X, undo that here.  */
881       *minus_litp = build_one_cst (TREE_TYPE (in));
882       var = negate_expr (TREE_OPERAND (in, 0));
883     }
884   else if (TREE_CONSTANT (in))
885     *conp = in;
886   else
887     var = in;
888
889   if (negate_p)
890     {
891       if (*litp)
892         *minus_litp = *litp, *litp = 0;
893       else if (*minus_litp)
894         *litp = *minus_litp, *minus_litp = 0;
895       *conp = negate_expr (*conp);
896       var = negate_expr (var);
897     }
898
899   return var;
900 }
901
902 /* Re-associate trees split by the above function.  T1 and T2 are
903    either expressions to associate or null.  Return the new
904    expression, if any.  LOC is the location of the new expression.  If
905    we build an operation, do it in TYPE and with CODE.  */
906
907 static tree
908 associate_trees (location_t loc, tree t1, tree t2, enum tree_code code, tree type)
909 {
910   if (t1 == 0)
911     return t2;
912   else if (t2 == 0)
913     return t1;
914
915   /* If either input is CODE, a PLUS_EXPR, or a MINUS_EXPR, don't
916      try to fold this since we will have infinite recursion.  But do
917      deal with any NEGATE_EXPRs.  */
918   if (TREE_CODE (t1) == code || TREE_CODE (t2) == code
919       || TREE_CODE (t1) == MINUS_EXPR || TREE_CODE (t2) == MINUS_EXPR)
920     {
921       if (code == PLUS_EXPR)
922         {
923           if (TREE_CODE (t1) == NEGATE_EXPR)
924             return build2_loc (loc, MINUS_EXPR, type,
925                                fold_convert_loc (loc, type, t2),
926                                fold_convert_loc (loc, type,
927                                                  TREE_OPERAND (t1, 0)));
928           else if (TREE_CODE (t2) == NEGATE_EXPR)
929             return build2_loc (loc, MINUS_EXPR, type,
930                                fold_convert_loc (loc, type, t1),
931                                fold_convert_loc (loc, type,
932                                                  TREE_OPERAND (t2, 0)));
933           else if (integer_zerop (t2))
934             return fold_convert_loc (loc, type, t1);
935         }
936       else if (code == MINUS_EXPR)
937         {
938           if (integer_zerop (t2))
939             return fold_convert_loc (loc, type, t1);
940         }
941
942       return build2_loc (loc, code, type, fold_convert_loc (loc, type, t1),
943                          fold_convert_loc (loc, type, t2));
944     }
945
946   return fold_build2_loc (loc, code, type, fold_convert_loc (loc, type, t1),
947                           fold_convert_loc (loc, type, t2));
948 }
949 \f
950 /* Check whether TYPE1 and TYPE2 are equivalent integer types, suitable
951    for use in int_const_binop, size_binop and size_diffop.  */
952
953 static bool
954 int_binop_types_match_p (enum tree_code code, const_tree type1, const_tree type2)
955 {
956   if (!INTEGRAL_TYPE_P (type1) && !POINTER_TYPE_P (type1))
957     return false;
958   if (!INTEGRAL_TYPE_P (type2) && !POINTER_TYPE_P (type2))
959     return false;
960
961   switch (code)
962     {
963     case LSHIFT_EXPR:
964     case RSHIFT_EXPR:
965     case LROTATE_EXPR:
966     case RROTATE_EXPR:
967       return true;
968
969     default:
970       break;
971     }
972
973   return TYPE_UNSIGNED (type1) == TYPE_UNSIGNED (type2)
974          && TYPE_PRECISION (type1) == TYPE_PRECISION (type2)
975          && TYPE_MODE (type1) == TYPE_MODE (type2);
976 }
977
978
979 /* Combine two integer constants ARG1 and ARG2 under operation CODE
980    to produce a new constant.  Return NULL_TREE if we don't know how
981    to evaluate CODE at compile-time.  */
982
983 static tree
984 int_const_binop_1 (enum tree_code code, const_tree arg1, const_tree parg2,
985                    int overflowable)
986 {
987   wide_int res;
988   tree t;
989   tree type = TREE_TYPE (arg1);
990   signop sign = TYPE_SIGN (type);
991   bool overflow = false;
992
993   wide_int arg2 = wide_int::from (parg2, TYPE_PRECISION (type),
994                                   TYPE_SIGN (TREE_TYPE (parg2)));
995
996   switch (code)
997     {
998     case BIT_IOR_EXPR:
999       res = wi::bit_or (arg1, arg2);
1000       break;
1001
1002     case BIT_XOR_EXPR:
1003       res = wi::bit_xor (arg1, arg2);
1004       break;
1005
1006     case BIT_AND_EXPR:
1007       res = wi::bit_and (arg1, arg2);
1008       break;
1009
1010     case RSHIFT_EXPR:
1011     case LSHIFT_EXPR:
1012       if (wi::neg_p (arg2))
1013         {
1014           arg2 = -arg2;
1015           if (code == RSHIFT_EXPR)
1016             code = LSHIFT_EXPR;
1017           else
1018             code = RSHIFT_EXPR;
1019         }
1020
1021       if (code == RSHIFT_EXPR)
1022         /* It's unclear from the C standard whether shifts can overflow.
1023            The following code ignores overflow; perhaps a C standard
1024            interpretation ruling is needed.  */
1025         res = wi::rshift (arg1, arg2, sign);
1026       else
1027         res = wi::lshift (arg1, arg2);
1028       break;
1029
1030     case RROTATE_EXPR:
1031     case LROTATE_EXPR:
1032       if (wi::neg_p (arg2))
1033         {
1034           arg2 = -arg2;
1035           if (code == RROTATE_EXPR)
1036             code = LROTATE_EXPR;
1037           else
1038             code = RROTATE_EXPR;
1039         }
1040
1041       if (code == RROTATE_EXPR)
1042         res = wi::rrotate (arg1, arg2);
1043       else
1044         res = wi::lrotate (arg1, arg2);
1045       break;
1046
1047     case PLUS_EXPR:
1048       res = wi::add (arg1, arg2, sign, &overflow);
1049       break;
1050
1051     case MINUS_EXPR:
1052       res = wi::sub (arg1, arg2, sign, &overflow);
1053       break;
1054
1055     case MULT_EXPR:
1056       res = wi::mul (arg1, arg2, sign, &overflow);
1057       break;
1058
1059     case MULT_HIGHPART_EXPR:
1060       res = wi::mul_high (arg1, arg2, sign);
1061       break;
1062
1063     case TRUNC_DIV_EXPR:
1064     case EXACT_DIV_EXPR:
1065       if (arg2 == 0)
1066         return NULL_TREE;
1067       res = wi::div_trunc (arg1, arg2, sign, &overflow);
1068       break;
1069
1070     case FLOOR_DIV_EXPR:
1071       if (arg2 == 0)
1072         return NULL_TREE;
1073       res = wi::div_floor (arg1, arg2, sign, &overflow);
1074       break;
1075
1076     case CEIL_DIV_EXPR:
1077       if (arg2 == 0)
1078         return NULL_TREE;
1079       res = wi::div_ceil (arg1, arg2, sign, &overflow);
1080       break;
1081
1082     case ROUND_DIV_EXPR:
1083       if (arg2 == 0)
1084         return NULL_TREE;
1085       res = wi::div_round (arg1, arg2, sign, &overflow);
1086       break;
1087
1088     case TRUNC_MOD_EXPR:
1089       if (arg2 == 0)
1090         return NULL_TREE;
1091       res = wi::mod_trunc (arg1, arg2, sign, &overflow);
1092       break;
1093
1094     case FLOOR_MOD_EXPR:
1095       if (arg2 == 0)
1096         return NULL_TREE;
1097       res = wi::mod_floor (arg1, arg2, sign, &overflow);
1098       break;
1099
1100     case CEIL_MOD_EXPR:
1101       if (arg2 == 0)
1102         return NULL_TREE;
1103       res = wi::mod_ceil (arg1, arg2, sign, &overflow);
1104       break;
1105
1106     case ROUND_MOD_EXPR:
1107       if (arg2 == 0)
1108         return NULL_TREE;
1109       res = wi::mod_round (arg1, arg2, sign, &overflow);
1110       break;
1111
1112     case MIN_EXPR:
1113       res = wi::min (arg1, arg2, sign);
1114       break;
1115
1116     case MAX_EXPR:
1117       res = wi::max (arg1, arg2, sign);
1118       break;
1119
1120     default:
1121       return NULL_TREE;
1122     }
1123
1124   t = force_fit_type (type, res, overflowable,
1125                       (((sign == SIGNED || overflowable == -1)
1126                         && overflow)
1127                        | TREE_OVERFLOW (arg1) | TREE_OVERFLOW (parg2)));
1128
1129   return t;
1130 }
1131
1132 tree
1133 int_const_binop (enum tree_code code, const_tree arg1, const_tree arg2)
1134 {
1135   return int_const_binop_1 (code, arg1, arg2, 1);
1136 }
1137
1138 /* Combine two constants ARG1 and ARG2 under operation CODE to produce a new
1139    constant.  We assume ARG1 and ARG2 have the same data type, or at least
1140    are the same kind of constant and the same machine mode.  Return zero if
1141    combining the constants is not allowed in the current operating mode.  */
1142
1143 static tree
1144 const_binop (enum tree_code code, tree arg1, tree arg2)
1145 {
1146   /* Sanity check for the recursive cases.  */
1147   if (!arg1 || !arg2)
1148     return NULL_TREE;
1149
1150   STRIP_NOPS (arg1);
1151   STRIP_NOPS (arg2);
1152
1153   if (TREE_CODE (arg1) == INTEGER_CST && TREE_CODE (arg2) == INTEGER_CST)
1154     {
1155       if (code == POINTER_PLUS_EXPR)
1156         return int_const_binop (PLUS_EXPR,
1157                                 arg1, fold_convert (TREE_TYPE (arg1), arg2));
1158
1159       return int_const_binop (code, arg1, arg2);
1160     }
1161
1162   if (TREE_CODE (arg1) == REAL_CST && TREE_CODE (arg2) == REAL_CST)
1163     {
1164       machine_mode mode;
1165       REAL_VALUE_TYPE d1;
1166       REAL_VALUE_TYPE d2;
1167       REAL_VALUE_TYPE value;
1168       REAL_VALUE_TYPE result;
1169       bool inexact;
1170       tree t, type;
1171
1172       /* The following codes are handled by real_arithmetic.  */
1173       switch (code)
1174         {
1175         case PLUS_EXPR:
1176         case MINUS_EXPR:
1177         case MULT_EXPR:
1178         case RDIV_EXPR:
1179         case MIN_EXPR:
1180         case MAX_EXPR:
1181           break;
1182
1183         default:
1184           return NULL_TREE;
1185         }
1186
1187       d1 = TREE_REAL_CST (arg1);
1188       d2 = TREE_REAL_CST (arg2);
1189
1190       type = TREE_TYPE (arg1);
1191       mode = TYPE_MODE (type);
1192
1193       /* Don't perform operation if we honor signaling NaNs and
1194          either operand is a NaN.  */
1195       if (HONOR_SNANS (mode)
1196           && (REAL_VALUE_ISNAN (d1) || REAL_VALUE_ISNAN (d2)))
1197         return NULL_TREE;
1198
1199       /* Don't perform operation if it would raise a division
1200          by zero exception.  */
1201       if (code == RDIV_EXPR
1202           && REAL_VALUES_EQUAL (d2, dconst0)
1203           && (flag_trapping_math || ! MODE_HAS_INFINITIES (mode)))
1204         return NULL_TREE;
1205
1206       /* If either operand is a NaN, just return it.  Otherwise, set up
1207          for floating-point trap; we return an overflow.  */
1208       if (REAL_VALUE_ISNAN (d1))
1209         return arg1;
1210       else if (REAL_VALUE_ISNAN (d2))
1211         return arg2;
1212
1213       inexact = real_arithmetic (&value, code, &d1, &d2);
1214       real_convert (&result, mode, &value);
1215
1216       /* Don't constant fold this floating point operation if
1217          the result has overflowed and flag_trapping_math.  */
1218       if (flag_trapping_math
1219           && MODE_HAS_INFINITIES (mode)
1220           && REAL_VALUE_ISINF (result)
1221           && !REAL_VALUE_ISINF (d1)
1222           && !REAL_VALUE_ISINF (d2))
1223         return NULL_TREE;
1224
1225       /* Don't constant fold this floating point operation if the
1226          result may dependent upon the run-time rounding mode and
1227          flag_rounding_math is set, or if GCC's software emulation
1228          is unable to accurately represent the result.  */
1229       if ((flag_rounding_math
1230            || (MODE_COMPOSITE_P (mode) && !flag_unsafe_math_optimizations))
1231           && (inexact || !real_identical (&result, &value)))
1232         return NULL_TREE;
1233
1234       t = build_real (type, result);
1235
1236       TREE_OVERFLOW (t) = TREE_OVERFLOW (arg1) | TREE_OVERFLOW (arg2);
1237       return t;
1238     }
1239
1240   if (TREE_CODE (arg1) == FIXED_CST)
1241     {
1242       FIXED_VALUE_TYPE f1;
1243       FIXED_VALUE_TYPE f2;
1244       FIXED_VALUE_TYPE result;
1245       tree t, type;
1246       int sat_p;
1247       bool overflow_p;
1248
1249       /* The following codes are handled by fixed_arithmetic.  */
1250       switch (code)
1251         {
1252         case PLUS_EXPR:
1253         case MINUS_EXPR:
1254         case MULT_EXPR:
1255         case TRUNC_DIV_EXPR:
1256           if (TREE_CODE (arg2) != FIXED_CST)
1257             return NULL_TREE;
1258           f2 = TREE_FIXED_CST (arg2);
1259           break;
1260
1261         case LSHIFT_EXPR:
1262         case RSHIFT_EXPR:
1263           {
1264             if (TREE_CODE (arg2) != INTEGER_CST)
1265               return NULL_TREE;
1266             wide_int w2 = arg2;
1267             f2.data.high = w2.elt (1);
1268             f2.data.low = w2.elt (0);
1269             f2.mode = SImode;
1270           }
1271           break;
1272
1273         default:
1274           return NULL_TREE;
1275         }
1276
1277       f1 = TREE_FIXED_CST (arg1);
1278       type = TREE_TYPE (arg1);
1279       sat_p = TYPE_SATURATING (type);
1280       overflow_p = fixed_arithmetic (&result, code, &f1, &f2, sat_p);
1281       t = build_fixed (type, result);
1282       /* Propagate overflow flags.  */
1283       if (overflow_p | TREE_OVERFLOW (arg1) | TREE_OVERFLOW (arg2))
1284         TREE_OVERFLOW (t) = 1;
1285       return t;
1286     }
1287
1288   if (TREE_CODE (arg1) == COMPLEX_CST && TREE_CODE (arg2) == COMPLEX_CST)
1289     {
1290       tree type = TREE_TYPE (arg1);
1291       tree r1 = TREE_REALPART (arg1);
1292       tree i1 = TREE_IMAGPART (arg1);
1293       tree r2 = TREE_REALPART (arg2);
1294       tree i2 = TREE_IMAGPART (arg2);
1295       tree real, imag;
1296
1297       switch (code)
1298         {
1299         case PLUS_EXPR:
1300         case MINUS_EXPR:
1301           real = const_binop (code, r1, r2);
1302           imag = const_binop (code, i1, i2);
1303           break;
1304
1305         case MULT_EXPR:
1306           if (COMPLEX_FLOAT_TYPE_P (type))
1307             return do_mpc_arg2 (arg1, arg2, type,
1308                                 /* do_nonfinite= */ folding_initializer,
1309                                 mpc_mul);
1310
1311           real = const_binop (MINUS_EXPR,
1312                               const_binop (MULT_EXPR, r1, r2),
1313                               const_binop (MULT_EXPR, i1, i2));
1314           imag = const_binop (PLUS_EXPR,
1315                               const_binop (MULT_EXPR, r1, i2),
1316                               const_binop (MULT_EXPR, i1, r2));
1317           break;
1318
1319         case RDIV_EXPR:
1320           if (COMPLEX_FLOAT_TYPE_P (type))
1321             return do_mpc_arg2 (arg1, arg2, type,
1322                                 /* do_nonfinite= */ folding_initializer,
1323                                 mpc_div);
1324           /* Fallthru ... */
1325         case TRUNC_DIV_EXPR:
1326         case CEIL_DIV_EXPR:
1327         case FLOOR_DIV_EXPR:
1328         case ROUND_DIV_EXPR:
1329           if (flag_complex_method == 0)
1330           {
1331             /* Keep this algorithm in sync with
1332                tree-complex.c:expand_complex_div_straight().
1333
1334                Expand complex division to scalars, straightforward algorithm.
1335                a / b = ((ar*br + ai*bi)/t) + i((ai*br - ar*bi)/t)
1336                t = br*br + bi*bi
1337             */
1338             tree magsquared
1339               = const_binop (PLUS_EXPR,
1340                              const_binop (MULT_EXPR, r2, r2),
1341                              const_binop (MULT_EXPR, i2, i2));
1342             tree t1
1343               = const_binop (PLUS_EXPR,
1344                              const_binop (MULT_EXPR, r1, r2),
1345                              const_binop (MULT_EXPR, i1, i2));
1346             tree t2
1347               = const_binop (MINUS_EXPR,
1348                              const_binop (MULT_EXPR, i1, r2),
1349                              const_binop (MULT_EXPR, r1, i2));
1350
1351             real = const_binop (code, t1, magsquared);
1352             imag = const_binop (code, t2, magsquared);
1353           }
1354           else
1355           {
1356             /* Keep this algorithm in sync with
1357                tree-complex.c:expand_complex_div_wide().
1358
1359                Expand complex division to scalars, modified algorithm to minimize
1360                overflow with wide input ranges.  */
1361             tree compare = fold_build2 (LT_EXPR, boolean_type_node,
1362                                         fold_abs_const (r2, TREE_TYPE (type)),
1363                                         fold_abs_const (i2, TREE_TYPE (type)));
1364
1365             if (integer_nonzerop (compare))
1366               {
1367                 /* In the TRUE branch, we compute
1368                    ratio = br/bi;
1369                    div = (br * ratio) + bi;
1370                    tr = (ar * ratio) + ai;
1371                    ti = (ai * ratio) - ar;
1372                    tr = tr / div;
1373                    ti = ti / div;  */
1374                 tree ratio = const_binop (code, r2, i2);
1375                 tree div = const_binop (PLUS_EXPR, i2,
1376                                         const_binop (MULT_EXPR, r2, ratio));
1377                 real = const_binop (MULT_EXPR, r1, ratio);
1378                 real = const_binop (PLUS_EXPR, real, i1);
1379                 real = const_binop (code, real, div);
1380
1381                 imag = const_binop (MULT_EXPR, i1, ratio);
1382                 imag = const_binop (MINUS_EXPR, imag, r1);
1383                 imag = const_binop (code, imag, div);
1384               }
1385             else
1386               {
1387                 /* In the FALSE branch, we compute
1388                    ratio = d/c;
1389                    divisor = (d * ratio) + c;
1390                    tr = (b * ratio) + a;
1391                    ti = b - (a * ratio);
1392                    tr = tr / div;
1393                    ti = ti / div;  */
1394                 tree ratio = const_binop (code, i2, r2);
1395                 tree div = const_binop (PLUS_EXPR, r2,
1396                                         const_binop (MULT_EXPR, i2, ratio));
1397
1398                 real = const_binop (MULT_EXPR, i1, ratio);
1399                 real = const_binop (PLUS_EXPR, real, r1);
1400                 real = const_binop (code, real, div);
1401
1402                 imag = const_binop (MULT_EXPR, r1, ratio);
1403                 imag = const_binop (MINUS_EXPR, i1, imag);
1404                 imag = const_binop (code, imag, div);
1405               }
1406           }
1407           break;
1408
1409         default:
1410           return NULL_TREE;
1411         }
1412
1413       if (real && imag)
1414         return build_complex (type, real, imag);
1415     }
1416
1417   if (TREE_CODE (arg1) == VECTOR_CST
1418       && TREE_CODE (arg2) == VECTOR_CST)
1419     {
1420       tree type = TREE_TYPE (arg1);
1421       int count = TYPE_VECTOR_SUBPARTS (type), i;
1422       tree *elts = XALLOCAVEC (tree, count);
1423
1424       for (i = 0; i < count; i++)
1425         {
1426           tree elem1 = VECTOR_CST_ELT (arg1, i);
1427           tree elem2 = VECTOR_CST_ELT (arg2, i);
1428
1429           elts[i] = const_binop (code, elem1, elem2);
1430
1431           /* It is possible that const_binop cannot handle the given
1432              code and return NULL_TREE */
1433           if (elts[i] == NULL_TREE)
1434             return NULL_TREE;
1435         }
1436
1437       return build_vector (type, elts);
1438     }
1439
1440   /* Shifts allow a scalar offset for a vector.  */
1441   if (TREE_CODE (arg1) == VECTOR_CST
1442       && TREE_CODE (arg2) == INTEGER_CST)
1443     {
1444       tree type = TREE_TYPE (arg1);
1445       int count = TYPE_VECTOR_SUBPARTS (type), i;
1446       tree *elts = XALLOCAVEC (tree, count);
1447
1448       for (i = 0; i < count; i++)
1449         {
1450           tree elem1 = VECTOR_CST_ELT (arg1, i);
1451
1452           elts[i] = const_binop (code, elem1, arg2);
1453
1454           /* It is possible that const_binop cannot handle the given
1455              code and return NULL_TREE.  */
1456           if (elts[i] == NULL_TREE)
1457             return NULL_TREE;
1458         }
1459
1460       return build_vector (type, elts);
1461     }
1462   return NULL_TREE;
1463 }
1464
1465 /* Overload that adds a TYPE parameter to be able to dispatch
1466    to fold_relational_const.  */
1467
1468 tree
1469 const_binop (enum tree_code code, tree type, tree arg1, tree arg2)
1470 {
1471   if (TREE_CODE_CLASS (code) == tcc_comparison)
1472     return fold_relational_const (code, type, arg1, arg2);
1473
1474   /* ???  Until we make the const_binop worker take the type of the
1475      result as argument put those cases that need it here.  */
1476   switch (code)
1477     {
1478     case COMPLEX_EXPR:
1479       if ((TREE_CODE (arg1) == REAL_CST
1480            && TREE_CODE (arg2) == REAL_CST)
1481           || (TREE_CODE (arg1) == INTEGER_CST
1482               && TREE_CODE (arg2) == INTEGER_CST))
1483         return build_complex (type, arg1, arg2);
1484       return NULL_TREE;
1485
1486     case VEC_PACK_TRUNC_EXPR:
1487     case VEC_PACK_FIX_TRUNC_EXPR:
1488       {
1489         unsigned int nelts = TYPE_VECTOR_SUBPARTS (type), i;
1490         tree *elts;
1491
1492         gcc_assert (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg1)) == nelts / 2
1493                     && TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg2)) == nelts / 2);
1494         if (TREE_CODE (arg1) != VECTOR_CST
1495             || TREE_CODE (arg2) != VECTOR_CST)
1496           return NULL_TREE;
1497
1498         elts = XALLOCAVEC (tree, nelts);
1499         if (!vec_cst_ctor_to_array (arg1, elts)
1500             || !vec_cst_ctor_to_array (arg2, elts + nelts / 2))
1501           return NULL_TREE;
1502
1503         for (i = 0; i < nelts; i++)
1504           {
1505             elts[i] = fold_convert_const (code == VEC_PACK_TRUNC_EXPR
1506                                           ? NOP_EXPR : FIX_TRUNC_EXPR,
1507                                           TREE_TYPE (type), elts[i]);
1508             if (elts[i] == NULL_TREE || !CONSTANT_CLASS_P (elts[i]))
1509               return NULL_TREE;
1510           }
1511
1512         return build_vector (type, elts);
1513       }
1514
1515     case VEC_WIDEN_MULT_LO_EXPR:
1516     case VEC_WIDEN_MULT_HI_EXPR:
1517     case VEC_WIDEN_MULT_EVEN_EXPR:
1518     case VEC_WIDEN_MULT_ODD_EXPR:
1519       {
1520         unsigned int nelts = TYPE_VECTOR_SUBPARTS (type);
1521         unsigned int out, ofs, scale;
1522         tree *elts;
1523
1524         gcc_assert (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg1)) == nelts * 2
1525                     && TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg2)) == nelts * 2);
1526         if (TREE_CODE (arg1) != VECTOR_CST || TREE_CODE (arg2) != VECTOR_CST)
1527           return NULL_TREE;
1528
1529         elts = XALLOCAVEC (tree, nelts * 4);
1530         if (!vec_cst_ctor_to_array (arg1, elts)
1531             || !vec_cst_ctor_to_array (arg2, elts + nelts * 2))
1532           return NULL_TREE;
1533
1534         if (code == VEC_WIDEN_MULT_LO_EXPR)
1535           scale = 0, ofs = BYTES_BIG_ENDIAN ? nelts : 0;
1536         else if (code == VEC_WIDEN_MULT_HI_EXPR)
1537           scale = 0, ofs = BYTES_BIG_ENDIAN ? 0 : nelts;
1538         else if (code == VEC_WIDEN_MULT_EVEN_EXPR)
1539           scale = 1, ofs = 0;
1540         else /* if (code == VEC_WIDEN_MULT_ODD_EXPR) */
1541           scale = 1, ofs = 1;
1542
1543         for (out = 0; out < nelts; out++)
1544           {
1545             unsigned int in1 = (out << scale) + ofs;
1546             unsigned int in2 = in1 + nelts * 2;
1547             tree t1, t2;
1548
1549             t1 = fold_convert_const (NOP_EXPR, TREE_TYPE (type), elts[in1]);
1550             t2 = fold_convert_const (NOP_EXPR, TREE_TYPE (type), elts[in2]);
1551
1552             if (t1 == NULL_TREE || t2 == NULL_TREE)
1553               return NULL_TREE;
1554             elts[out] = const_binop (MULT_EXPR, t1, t2);
1555             if (elts[out] == NULL_TREE || !CONSTANT_CLASS_P (elts[out]))
1556               return NULL_TREE;
1557           }
1558
1559         return build_vector (type, elts);
1560       }
1561
1562     default:;
1563     }
1564
1565   if (TREE_CODE_CLASS (code) != tcc_binary)
1566     return NULL_TREE;
1567
1568   /* Make sure type and arg0 have the same saturating flag.  */
1569   gcc_checking_assert (TYPE_SATURATING (type)
1570                        == TYPE_SATURATING (TREE_TYPE (arg1)));
1571
1572   return const_binop (code, arg1, arg2);
1573 }
1574
1575 /* Compute CODE ARG1 with resulting type TYPE with ARG1 being constant.
1576    Return zero if computing the constants is not possible.  */
1577
1578 tree
1579 const_unop (enum tree_code code, tree type, tree arg0)
1580 {
1581   switch (code)
1582     {
1583     CASE_CONVERT:
1584     case FLOAT_EXPR:
1585     case FIX_TRUNC_EXPR:
1586     case FIXED_CONVERT_EXPR:
1587       return fold_convert_const (code, type, arg0);
1588
1589     case ADDR_SPACE_CONVERT_EXPR:
1590       if (integer_zerop (arg0))
1591         return fold_convert_const (code, type, arg0);
1592       break;
1593
1594     case VIEW_CONVERT_EXPR:
1595       return fold_view_convert_expr (type, arg0);
1596
1597     case NEGATE_EXPR:
1598       {
1599         /* Can't call fold_negate_const directly here as that doesn't
1600            handle all cases and we might not be able to negate some
1601            constants.  */
1602         tree tem = fold_negate_expr (UNKNOWN_LOCATION, arg0);
1603         if (tem && CONSTANT_CLASS_P (tem))
1604           return tem;
1605         break;
1606       }
1607
1608     case ABS_EXPR:
1609       if (TREE_CODE (arg0) == INTEGER_CST || TREE_CODE (arg0) == REAL_CST)
1610         return fold_abs_const (arg0, type);
1611       break;
1612
1613     case CONJ_EXPR:
1614       if (TREE_CODE (arg0) == COMPLEX_CST)
1615         {
1616           tree ipart = fold_negate_const (TREE_IMAGPART (arg0),
1617                                           TREE_TYPE (type));
1618           return build_complex (type, TREE_REALPART (arg0), ipart);
1619         }
1620       break;
1621
1622     case BIT_NOT_EXPR:
1623       if (TREE_CODE (arg0) == INTEGER_CST)
1624         return fold_not_const (arg0, type);
1625       /* Perform BIT_NOT_EXPR on each element individually.  */
1626       else if (TREE_CODE (arg0) == VECTOR_CST)
1627         {
1628           tree *elements;
1629           tree elem;
1630           unsigned count = VECTOR_CST_NELTS (arg0), i;
1631
1632           elements = XALLOCAVEC (tree, count);
1633           for (i = 0; i < count; i++)
1634             {
1635               elem = VECTOR_CST_ELT (arg0, i);
1636               elem = const_unop (BIT_NOT_EXPR, TREE_TYPE (type), elem);
1637               if (elem == NULL_TREE)
1638                 break;
1639               elements[i] = elem;
1640             }
1641           if (i == count)
1642             return build_vector (type, elements);
1643         }
1644       break;
1645
1646     case TRUTH_NOT_EXPR:
1647       if (TREE_CODE (arg0) == INTEGER_CST)
1648         return constant_boolean_node (integer_zerop (arg0), type);
1649       break;
1650
1651     case REALPART_EXPR:
1652       if (TREE_CODE (arg0) == COMPLEX_CST)
1653         return fold_convert (type, TREE_REALPART (arg0));
1654       break;
1655
1656     case IMAGPART_EXPR:
1657       if (TREE_CODE (arg0) == COMPLEX_CST)
1658         return fold_convert (type, TREE_IMAGPART (arg0));
1659       break;
1660
1661     case VEC_UNPACK_LO_EXPR:
1662     case VEC_UNPACK_HI_EXPR:
1663     case VEC_UNPACK_FLOAT_LO_EXPR:
1664     case VEC_UNPACK_FLOAT_HI_EXPR:
1665       {
1666         unsigned int nelts = TYPE_VECTOR_SUBPARTS (type), i;
1667         tree *elts;
1668         enum tree_code subcode;
1669
1670         gcc_assert (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0)) == nelts * 2);
1671         if (TREE_CODE (arg0) != VECTOR_CST)
1672           return NULL_TREE;
1673
1674         elts = XALLOCAVEC (tree, nelts * 2);
1675         if (!vec_cst_ctor_to_array (arg0, elts))
1676           return NULL_TREE;
1677
1678         if ((!BYTES_BIG_ENDIAN) ^ (code == VEC_UNPACK_LO_EXPR
1679                                    || code == VEC_UNPACK_FLOAT_LO_EXPR))
1680           elts += nelts;
1681
1682         if (code == VEC_UNPACK_LO_EXPR || code == VEC_UNPACK_HI_EXPR)
1683           subcode = NOP_EXPR;
1684         else
1685           subcode = FLOAT_EXPR;
1686
1687         for (i = 0; i < nelts; i++)
1688           {
1689             elts[i] = fold_convert_const (subcode, TREE_TYPE (type), elts[i]);
1690             if (elts[i] == NULL_TREE || !CONSTANT_CLASS_P (elts[i]))
1691               return NULL_TREE;
1692           }
1693
1694         return build_vector (type, elts);
1695       }
1696
1697     case REDUC_MIN_EXPR:
1698     case REDUC_MAX_EXPR:
1699     case REDUC_PLUS_EXPR:
1700       {
1701         unsigned int nelts, i;
1702         tree *elts;
1703         enum tree_code subcode;
1704
1705         if (TREE_CODE (arg0) != VECTOR_CST)
1706           return NULL_TREE;
1707         nelts = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
1708
1709         elts = XALLOCAVEC (tree, nelts);
1710         if (!vec_cst_ctor_to_array (arg0, elts))
1711           return NULL_TREE;
1712
1713         switch (code)
1714           {
1715           case REDUC_MIN_EXPR: subcode = MIN_EXPR; break;
1716           case REDUC_MAX_EXPR: subcode = MAX_EXPR; break;
1717           case REDUC_PLUS_EXPR: subcode = PLUS_EXPR; break;
1718           default: gcc_unreachable ();
1719           }
1720
1721         for (i = 1; i < nelts; i++)
1722           {
1723             elts[0] = const_binop (subcode, elts[0], elts[i]);
1724             if (elts[0] == NULL_TREE || !CONSTANT_CLASS_P (elts[0]))
1725               return NULL_TREE;
1726           }
1727
1728         return elts[0];
1729       }
1730
1731     default:
1732       break;
1733     }
1734
1735   return NULL_TREE;
1736 }
1737
1738 /* Create a sizetype INT_CST node with NUMBER sign extended.  KIND
1739    indicates which particular sizetype to create.  */
1740
1741 tree
1742 size_int_kind (HOST_WIDE_INT number, enum size_type_kind kind)
1743 {
1744   return build_int_cst (sizetype_tab[(int) kind], number);
1745 }
1746 \f
1747 /* Combine operands OP1 and OP2 with arithmetic operation CODE.  CODE
1748    is a tree code.  The type of the result is taken from the operands.
1749    Both must be equivalent integer types, ala int_binop_types_match_p.
1750    If the operands are constant, so is the result.  */
1751
1752 tree
1753 size_binop_loc (location_t loc, enum tree_code code, tree arg0, tree arg1)
1754 {
1755   tree type = TREE_TYPE (arg0);
1756
1757   if (arg0 == error_mark_node || arg1 == error_mark_node)
1758     return error_mark_node;
1759
1760   gcc_assert (int_binop_types_match_p (code, TREE_TYPE (arg0),
1761                                        TREE_TYPE (arg1)));
1762
1763   /* Handle the special case of two integer constants faster.  */
1764   if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
1765     {
1766       /* And some specific cases even faster than that.  */
1767       if (code == PLUS_EXPR)
1768         {
1769           if (integer_zerop (arg0) && !TREE_OVERFLOW (arg0))
1770             return arg1;
1771           if (integer_zerop (arg1) && !TREE_OVERFLOW (arg1))
1772             return arg0;
1773         }
1774       else if (code == MINUS_EXPR)
1775         {
1776           if (integer_zerop (arg1) && !TREE_OVERFLOW (arg1))
1777             return arg0;
1778         }
1779       else if (code == MULT_EXPR)
1780         {
1781           if (integer_onep (arg0) && !TREE_OVERFLOW (arg0))
1782             return arg1;
1783         }
1784
1785       /* Handle general case of two integer constants.  For sizetype
1786          constant calculations we always want to know about overflow,
1787          even in the unsigned case.  */
1788       return int_const_binop_1 (code, arg0, arg1, -1);
1789     }
1790
1791   return fold_build2_loc (loc, code, type, arg0, arg1);
1792 }
1793
1794 /* Given two values, either both of sizetype or both of bitsizetype,
1795    compute the difference between the two values.  Return the value
1796    in signed type corresponding to the type of the operands.  */
1797
1798 tree
1799 size_diffop_loc (location_t loc, tree arg0, tree arg1)
1800 {
1801   tree type = TREE_TYPE (arg0);
1802   tree ctype;
1803
1804   gcc_assert (int_binop_types_match_p (MINUS_EXPR, TREE_TYPE (arg0),
1805                                        TREE_TYPE (arg1)));
1806
1807   /* If the type is already signed, just do the simple thing.  */
1808   if (!TYPE_UNSIGNED (type))
1809     return size_binop_loc (loc, MINUS_EXPR, arg0, arg1);
1810
1811   if (type == sizetype)
1812     ctype = ssizetype;
1813   else if (type == bitsizetype)
1814     ctype = sbitsizetype;
1815   else
1816     ctype = signed_type_for (type);
1817
1818   /* If either operand is not a constant, do the conversions to the signed
1819      type and subtract.  The hardware will do the right thing with any
1820      overflow in the subtraction.  */
1821   if (TREE_CODE (arg0) != INTEGER_CST || TREE_CODE (arg1) != INTEGER_CST)
1822     return size_binop_loc (loc, MINUS_EXPR,
1823                            fold_convert_loc (loc, ctype, arg0),
1824                            fold_convert_loc (loc, ctype, arg1));
1825
1826   /* If ARG0 is larger than ARG1, subtract and return the result in CTYPE.
1827      Otherwise, subtract the other way, convert to CTYPE (we know that can't
1828      overflow) and negate (which can't either).  Special-case a result
1829      of zero while we're here.  */
1830   if (tree_int_cst_equal (arg0, arg1))
1831     return build_int_cst (ctype, 0);
1832   else if (tree_int_cst_lt (arg1, arg0))
1833     return fold_convert_loc (loc, ctype,
1834                              size_binop_loc (loc, MINUS_EXPR, arg0, arg1));
1835   else
1836     return size_binop_loc (loc, MINUS_EXPR, build_int_cst (ctype, 0),
1837                            fold_convert_loc (loc, ctype,
1838                                              size_binop_loc (loc,
1839                                                              MINUS_EXPR,
1840                                                              arg1, arg0)));
1841 }
1842 \f
1843 /* A subroutine of fold_convert_const handling conversions of an
1844    INTEGER_CST to another integer type.  */
1845
1846 static tree
1847 fold_convert_const_int_from_int (tree type, const_tree arg1)
1848 {
1849   /* Given an integer constant, make new constant with new type,
1850      appropriately sign-extended or truncated.  Use widest_int
1851      so that any extension is done according ARG1's type.  */
1852   return force_fit_type (type, wi::to_widest (arg1),
1853                          !POINTER_TYPE_P (TREE_TYPE (arg1)),
1854                          TREE_OVERFLOW (arg1));
1855 }
1856
1857 /* A subroutine of fold_convert_const handling conversions a REAL_CST
1858    to an integer type.  */
1859
1860 static tree
1861 fold_convert_const_int_from_real (enum tree_code code, tree type, const_tree arg1)
1862 {
1863   bool overflow = false;
1864   tree t;
1865
1866   /* The following code implements the floating point to integer
1867      conversion rules required by the Java Language Specification,
1868      that IEEE NaNs are mapped to zero and values that overflow
1869      the target precision saturate, i.e. values greater than
1870      INT_MAX are mapped to INT_MAX, and values less than INT_MIN
1871      are mapped to INT_MIN.  These semantics are allowed by the
1872      C and C++ standards that simply state that the behavior of
1873      FP-to-integer conversion is unspecified upon overflow.  */
1874
1875   wide_int val;
1876   REAL_VALUE_TYPE r;
1877   REAL_VALUE_TYPE x = TREE_REAL_CST (arg1);
1878
1879   switch (code)
1880     {
1881     case FIX_TRUNC_EXPR:
1882       real_trunc (&r, VOIDmode, &x);
1883       break;
1884
1885     default:
1886       gcc_unreachable ();
1887     }
1888
1889   /* If R is NaN, return zero and show we have an overflow.  */
1890   if (REAL_VALUE_ISNAN (r))
1891     {
1892       overflow = true;
1893       val = wi::zero (TYPE_PRECISION (type));
1894     }
1895
1896   /* See if R is less than the lower bound or greater than the
1897      upper bound.  */
1898
1899   if (! overflow)
1900     {
1901       tree lt = TYPE_MIN_VALUE (type);
1902       REAL_VALUE_TYPE l = real_value_from_int_cst (NULL_TREE, lt);
1903       if (REAL_VALUES_LESS (r, l))
1904         {
1905           overflow = true;
1906           val = lt;
1907         }
1908     }
1909
1910   if (! overflow)
1911     {
1912       tree ut = TYPE_MAX_VALUE (type);
1913       if (ut)
1914         {
1915           REAL_VALUE_TYPE u = real_value_from_int_cst (NULL_TREE, ut);
1916           if (REAL_VALUES_LESS (u, r))
1917             {
1918               overflow = true;
1919               val = ut;
1920             }
1921         }
1922     }
1923
1924   if (! overflow)
1925     val = real_to_integer (&r, &overflow, TYPE_PRECISION (type));
1926
1927   t = force_fit_type (type, val, -1, overflow | TREE_OVERFLOW (arg1));
1928   return t;
1929 }
1930
1931 /* A subroutine of fold_convert_const handling conversions of a
1932    FIXED_CST to an integer type.  */
1933
1934 static tree
1935 fold_convert_const_int_from_fixed (tree type, const_tree arg1)
1936 {
1937   tree t;
1938   double_int temp, temp_trunc;
1939   unsigned int mode;
1940
1941   /* Right shift FIXED_CST to temp by fbit.  */
1942   temp = TREE_FIXED_CST (arg1).data;
1943   mode = TREE_FIXED_CST (arg1).mode;
1944   if (GET_MODE_FBIT (mode) < HOST_BITS_PER_DOUBLE_INT)
1945     {
1946       temp = temp.rshift (GET_MODE_FBIT (mode),
1947                           HOST_BITS_PER_DOUBLE_INT,
1948                           SIGNED_FIXED_POINT_MODE_P (mode));
1949
1950       /* Left shift temp to temp_trunc by fbit.  */
1951       temp_trunc = temp.lshift (GET_MODE_FBIT (mode),
1952                                 HOST_BITS_PER_DOUBLE_INT,
1953                                 SIGNED_FIXED_POINT_MODE_P (mode));
1954     }
1955   else
1956     {
1957       temp = double_int_zero;
1958       temp_trunc = double_int_zero;
1959     }
1960
1961   /* If FIXED_CST is negative, we need to round the value toward 0.
1962      By checking if the fractional bits are not zero to add 1 to temp.  */
1963   if (SIGNED_FIXED_POINT_MODE_P (mode)
1964       && temp_trunc.is_negative ()
1965       && TREE_FIXED_CST (arg1).data != temp_trunc)
1966     temp += double_int_one;
1967
1968   /* Given a fixed-point constant, make new constant with new type,
1969      appropriately sign-extended or truncated.  */
1970   t = force_fit_type (type, temp, -1,
1971                       (temp.is_negative ()
1972                        && (TYPE_UNSIGNED (type)
1973                            < TYPE_UNSIGNED (TREE_TYPE (arg1))))
1974                       | TREE_OVERFLOW (arg1));
1975
1976   return t;
1977 }
1978
1979 /* A subroutine of fold_convert_const handling conversions a REAL_CST
1980    to another floating point type.  */
1981
1982 static tree
1983 fold_convert_const_real_from_real (tree type, const_tree arg1)
1984 {
1985   REAL_VALUE_TYPE value;
1986   tree t;
1987
1988   real_convert (&value, TYPE_MODE (type), &TREE_REAL_CST (arg1));
1989   t = build_real (type, value);
1990
1991   /* If converting an infinity or NAN to a representation that doesn't
1992      have one, set the overflow bit so that we can produce some kind of
1993      error message at the appropriate point if necessary.  It's not the
1994      most user-friendly message, but it's better than nothing.  */
1995   if (REAL_VALUE_ISINF (TREE_REAL_CST (arg1))
1996       && !MODE_HAS_INFINITIES (TYPE_MODE (type)))
1997     TREE_OVERFLOW (t) = 1;
1998   else if (REAL_VALUE_ISNAN (TREE_REAL_CST (arg1))
1999            && !MODE_HAS_NANS (TYPE_MODE (type)))
2000     TREE_OVERFLOW (t) = 1;
2001   /* Regular overflow, conversion produced an infinity in a mode that
2002      can't represent them.  */
2003   else if (!MODE_HAS_INFINITIES (TYPE_MODE (type))
2004            && REAL_VALUE_ISINF (value)
2005            && !REAL_VALUE_ISINF (TREE_REAL_CST (arg1)))
2006     TREE_OVERFLOW (t) = 1;
2007   else
2008     TREE_OVERFLOW (t) = TREE_OVERFLOW (arg1);
2009   return t;
2010 }
2011
2012 /* A subroutine of fold_convert_const handling conversions a FIXED_CST
2013    to a floating point type.  */
2014
2015 static tree
2016 fold_convert_const_real_from_fixed (tree type, const_tree arg1)
2017 {
2018   REAL_VALUE_TYPE value;
2019   tree t;
2020
2021   real_convert_from_fixed (&value, TYPE_MODE (type), &TREE_FIXED_CST (arg1));
2022   t = build_real (type, value);
2023
2024   TREE_OVERFLOW (t) = TREE_OVERFLOW (arg1);
2025   return t;
2026 }
2027
2028 /* A subroutine of fold_convert_const handling conversions a FIXED_CST
2029    to another fixed-point type.  */
2030
2031 static tree
2032 fold_convert_const_fixed_from_fixed (tree type, const_tree arg1)
2033 {
2034   FIXED_VALUE_TYPE value;
2035   tree t;
2036   bool overflow_p;
2037
2038   overflow_p = fixed_convert (&value, TYPE_MODE (type), &TREE_FIXED_CST (arg1),
2039                               TYPE_SATURATING (type));
2040   t = build_fixed (type, value);
2041
2042   /* Propagate overflow flags.  */
2043   if (overflow_p | TREE_OVERFLOW (arg1))
2044     TREE_OVERFLOW (t) = 1;
2045   return t;
2046 }
2047
2048 /* A subroutine of fold_convert_const handling conversions an INTEGER_CST
2049    to a fixed-point type.  */
2050
2051 static tree
2052 fold_convert_const_fixed_from_int (tree type, const_tree arg1)
2053 {
2054   FIXED_VALUE_TYPE value;
2055   tree t;
2056   bool overflow_p;
2057   double_int di;
2058
2059   gcc_assert (TREE_INT_CST_NUNITS (arg1) <= 2);
2060
2061   di.low = TREE_INT_CST_ELT (arg1, 0);
2062   if (TREE_INT_CST_NUNITS (arg1) == 1)
2063     di.high = (HOST_WIDE_INT) di.low < 0 ? (HOST_WIDE_INT) -1 : 0;
2064   else
2065     di.high = TREE_INT_CST_ELT (arg1, 1);
2066
2067   overflow_p = fixed_convert_from_int (&value, TYPE_MODE (type), di,
2068                                        TYPE_UNSIGNED (TREE_TYPE (arg1)),
2069                                        TYPE_SATURATING (type));
2070   t = build_fixed (type, value);
2071
2072   /* Propagate overflow flags.  */
2073   if (overflow_p | TREE_OVERFLOW (arg1))
2074     TREE_OVERFLOW (t) = 1;
2075   return t;
2076 }
2077
2078 /* A subroutine of fold_convert_const handling conversions a REAL_CST
2079    to a fixed-point type.  */
2080
2081 static tree
2082 fold_convert_const_fixed_from_real (tree type, const_tree arg1)
2083 {
2084   FIXED_VALUE_TYPE value;
2085   tree t;
2086   bool overflow_p;
2087
2088   overflow_p = fixed_convert_from_real (&value, TYPE_MODE (type),
2089                                         &TREE_REAL_CST (arg1),
2090                                         TYPE_SATURATING (type));
2091   t = build_fixed (type, value);
2092
2093   /* Propagate overflow flags.  */
2094   if (overflow_p | TREE_OVERFLOW (arg1))
2095     TREE_OVERFLOW (t) = 1;
2096   return t;
2097 }
2098
2099 /* Attempt to fold type conversion operation CODE of expression ARG1 to
2100    type TYPE.  If no simplification can be done return NULL_TREE.  */
2101
2102 static tree
2103 fold_convert_const (enum tree_code code, tree type, tree arg1)
2104 {
2105   if (TREE_TYPE (arg1) == type)
2106     return arg1;
2107
2108   if (POINTER_TYPE_P (type) || INTEGRAL_TYPE_P (type)
2109       || TREE_CODE (type) == OFFSET_TYPE)
2110     {
2111       if (TREE_CODE (arg1) == INTEGER_CST)
2112         return fold_convert_const_int_from_int (type, arg1);
2113       else if (TREE_CODE (arg1) == REAL_CST)
2114         return fold_convert_const_int_from_real (code, type, arg1);
2115       else if (TREE_CODE (arg1) == FIXED_CST)
2116         return fold_convert_const_int_from_fixed (type, arg1);
2117     }
2118   else if (TREE_CODE (type) == REAL_TYPE)
2119     {
2120       if (TREE_CODE (arg1) == INTEGER_CST)
2121         return build_real_from_int_cst (type, arg1);
2122       else if (TREE_CODE (arg1) == REAL_CST)
2123         return fold_convert_const_real_from_real (type, arg1);
2124       else if (TREE_CODE (arg1) == FIXED_CST)
2125         return fold_convert_const_real_from_fixed (type, arg1);
2126     }
2127   else if (TREE_CODE (type) == FIXED_POINT_TYPE)
2128     {
2129       if (TREE_CODE (arg1) == FIXED_CST)
2130         return fold_convert_const_fixed_from_fixed (type, arg1);
2131       else if (TREE_CODE (arg1) == INTEGER_CST)
2132         return fold_convert_const_fixed_from_int (type, arg1);
2133       else if (TREE_CODE (arg1) == REAL_CST)
2134         return fold_convert_const_fixed_from_real (type, arg1);
2135     }
2136   return NULL_TREE;
2137 }
2138
2139 /* Construct a vector of zero elements of vector type TYPE.  */
2140
2141 static tree
2142 build_zero_vector (tree type)
2143 {
2144   tree t;
2145
2146   t = fold_convert_const (NOP_EXPR, TREE_TYPE (type), integer_zero_node);
2147   return build_vector_from_val (type, t);
2148 }
2149
2150 /* Returns true, if ARG is convertible to TYPE using a NOP_EXPR.  */
2151
2152 bool
2153 fold_convertible_p (const_tree type, const_tree arg)
2154 {
2155   tree orig = TREE_TYPE (arg);
2156
2157   if (type == orig)
2158     return true;
2159
2160   if (TREE_CODE (arg) == ERROR_MARK
2161       || TREE_CODE (type) == ERROR_MARK
2162       || TREE_CODE (orig) == ERROR_MARK)
2163     return false;
2164
2165   if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (orig))
2166     return true;
2167
2168   switch (TREE_CODE (type))
2169     {
2170     case INTEGER_TYPE: case ENUMERAL_TYPE: case BOOLEAN_TYPE:
2171     case POINTER_TYPE: case REFERENCE_TYPE:
2172     case OFFSET_TYPE:
2173       if (INTEGRAL_TYPE_P (orig) || POINTER_TYPE_P (orig)
2174           || TREE_CODE (orig) == OFFSET_TYPE)
2175         return true;
2176       return (TREE_CODE (orig) == VECTOR_TYPE
2177               && tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (orig)));
2178
2179     case REAL_TYPE:
2180     case FIXED_POINT_TYPE:
2181     case COMPLEX_TYPE:
2182     case VECTOR_TYPE:
2183     case VOID_TYPE:
2184       return TREE_CODE (type) == TREE_CODE (orig);
2185
2186     default:
2187       return false;
2188     }
2189 }
2190
2191 /* Convert expression ARG to type TYPE.  Used by the middle-end for
2192    simple conversions in preference to calling the front-end's convert.  */
2193
2194 tree
2195 fold_convert_loc (location_t loc, tree type, tree arg)
2196 {
2197   tree orig = TREE_TYPE (arg);
2198   tree tem;
2199
2200   if (type == orig)
2201     return arg;
2202
2203   if (TREE_CODE (arg) == ERROR_MARK
2204       || TREE_CODE (type) == ERROR_MARK
2205       || TREE_CODE (orig) == ERROR_MARK)
2206     return error_mark_node;
2207
2208   switch (TREE_CODE (type))
2209     {
2210     case POINTER_TYPE:
2211     case REFERENCE_TYPE:
2212       /* Handle conversions between pointers to different address spaces.  */
2213       if (POINTER_TYPE_P (orig)
2214           && (TYPE_ADDR_SPACE (TREE_TYPE (type))
2215               != TYPE_ADDR_SPACE (TREE_TYPE (orig))))
2216         return fold_build1_loc (loc, ADDR_SPACE_CONVERT_EXPR, type, arg);
2217       /* fall through */
2218
2219     case INTEGER_TYPE: case ENUMERAL_TYPE: case BOOLEAN_TYPE:
2220     case OFFSET_TYPE:
2221       if (TREE_CODE (arg) == INTEGER_CST)
2222         {
2223           tem = fold_convert_const (NOP_EXPR, type, arg);
2224           if (tem != NULL_TREE)
2225             return tem;
2226         }
2227       if (INTEGRAL_TYPE_P (orig) || POINTER_TYPE_P (orig)
2228           || TREE_CODE (orig) == OFFSET_TYPE)
2229         return fold_build1_loc (loc, NOP_EXPR, type, arg);
2230       if (TREE_CODE (orig) == COMPLEX_TYPE)
2231         return fold_convert_loc (loc, type,
2232                              fold_build1_loc (loc, REALPART_EXPR,
2233                                           TREE_TYPE (orig), arg));
2234       gcc_assert (TREE_CODE (orig) == VECTOR_TYPE
2235                   && tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (orig)));
2236       return fold_build1_loc (loc, NOP_EXPR, type, arg);
2237
2238     case REAL_TYPE:
2239       if (TREE_CODE (arg) == INTEGER_CST)
2240         {
2241           tem = fold_convert_const (FLOAT_EXPR, type, arg);
2242           if (tem != NULL_TREE)
2243             return tem;
2244         }
2245       else if (TREE_CODE (arg) == REAL_CST)
2246         {
2247           tem = fold_convert_const (NOP_EXPR, type, arg);
2248           if (tem != NULL_TREE)
2249             return tem;
2250         }
2251       else if (TREE_CODE (arg) == FIXED_CST)
2252         {
2253           tem = fold_convert_const (FIXED_CONVERT_EXPR, type, arg);
2254           if (tem != NULL_TREE)
2255             return tem;
2256         }
2257
2258       switch (TREE_CODE (orig))
2259         {
2260         case INTEGER_TYPE:
2261         case BOOLEAN_TYPE: case ENUMERAL_TYPE:
2262         case POINTER_TYPE: case REFERENCE_TYPE:
2263           return fold_build1_loc (loc, FLOAT_EXPR, type, arg);
2264
2265         case REAL_TYPE:
2266           return fold_build1_loc (loc, NOP_EXPR, type, arg);
2267
2268         case FIXED_POINT_TYPE:
2269           return fold_build1_loc (loc, FIXED_CONVERT_EXPR, type, arg);
2270
2271         case COMPLEX_TYPE:
2272           tem = fold_build1_loc (loc, REALPART_EXPR, TREE_TYPE (orig), arg);
2273           return fold_convert_loc (loc, type, tem);
2274
2275         default:
2276           gcc_unreachable ();
2277         }
2278
2279     case FIXED_POINT_TYPE:
2280       if (TREE_CODE (arg) == FIXED_CST || TREE_CODE (arg) == INTEGER_CST
2281           || TREE_CODE (arg) == REAL_CST)
2282         {
2283           tem = fold_convert_const (FIXED_CONVERT_EXPR, type, arg);
2284           if (tem != NULL_TREE)
2285             goto fold_convert_exit;
2286         }
2287
2288       switch (TREE_CODE (orig))
2289         {
2290         case FIXED_POINT_TYPE:
2291         case INTEGER_TYPE:
2292         case ENUMERAL_TYPE:
2293         case BOOLEAN_TYPE:
2294         case REAL_TYPE:
2295           return fold_build1_loc (loc, FIXED_CONVERT_EXPR, type, arg);
2296
2297         case COMPLEX_TYPE:
2298           tem = fold_build1_loc (loc, REALPART_EXPR, TREE_TYPE (orig), arg);
2299           return fold_convert_loc (loc, type, tem);
2300
2301         default:
2302           gcc_unreachable ();
2303         }
2304
2305     case COMPLEX_TYPE:
2306       switch (TREE_CODE (orig))
2307         {
2308         case INTEGER_TYPE:
2309         case BOOLEAN_TYPE: case ENUMERAL_TYPE:
2310         case POINTER_TYPE: case REFERENCE_TYPE:
2311         case REAL_TYPE:
2312         case FIXED_POINT_TYPE:
2313           return fold_build2_loc (loc, COMPLEX_EXPR, type,
2314                               fold_convert_loc (loc, TREE_TYPE (type), arg),
2315                               fold_convert_loc (loc, TREE_TYPE (type),
2316                                             integer_zero_node));
2317         case COMPLEX_TYPE:
2318           {
2319             tree rpart, ipart;
2320
2321             if (TREE_CODE (arg) == COMPLEX_EXPR)
2322               {
2323                 rpart = fold_convert_loc (loc, TREE_TYPE (type),
2324                                       TREE_OPERAND (arg, 0));
2325                 ipart = fold_convert_loc (loc, TREE_TYPE (type),
2326                                       TREE_OPERAND (arg, 1));
2327                 return fold_build2_loc (loc, COMPLEX_EXPR, type, rpart, ipart);
2328               }
2329
2330             arg = save_expr (arg);
2331             rpart = fold_build1_loc (loc, REALPART_EXPR, TREE_TYPE (orig), arg);
2332             ipart = fold_build1_loc (loc, IMAGPART_EXPR, TREE_TYPE (orig), arg);
2333             rpart = fold_convert_loc (loc, TREE_TYPE (type), rpart);
2334             ipart = fold_convert_loc (loc, TREE_TYPE (type), ipart);
2335             return fold_build2_loc (loc, COMPLEX_EXPR, type, rpart, ipart);
2336           }
2337
2338         default:
2339           gcc_unreachable ();
2340         }
2341
2342     case VECTOR_TYPE:
2343       if (integer_zerop (arg))
2344         return build_zero_vector (type);
2345       gcc_assert (tree_int_cst_equal (TYPE_SIZE (type), TYPE_SIZE (orig)));
2346       gcc_assert (INTEGRAL_TYPE_P (orig) || POINTER_TYPE_P (orig)
2347                   || TREE_CODE (orig) == VECTOR_TYPE);
2348       return fold_build1_loc (loc, VIEW_CONVERT_EXPR, type, arg);
2349
2350     case VOID_TYPE:
2351       tem = fold_ignored_result (arg);
2352       return fold_build1_loc (loc, NOP_EXPR, type, tem);
2353
2354     default:
2355       if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (orig))
2356         return fold_build1_loc (loc, NOP_EXPR, type, arg);
2357       gcc_unreachable ();
2358     }
2359  fold_convert_exit:
2360   protected_set_expr_location_unshare (tem, loc);
2361   return tem;
2362 }
2363 \f
2364 /* Return false if expr can be assumed not to be an lvalue, true
2365    otherwise.  */
2366
2367 static bool
2368 maybe_lvalue_p (const_tree x)
2369 {
2370   /* We only need to wrap lvalue tree codes.  */
2371   switch (TREE_CODE (x))
2372   {
2373   case VAR_DECL:
2374   case PARM_DECL:
2375   case RESULT_DECL:
2376   case LABEL_DECL:
2377   case FUNCTION_DECL:
2378   case SSA_NAME:
2379
2380   case COMPONENT_REF:
2381   case MEM_REF:
2382   case INDIRECT_REF:
2383   case ARRAY_REF:
2384   case ARRAY_RANGE_REF:
2385   case BIT_FIELD_REF:
2386   case OBJ_TYPE_REF:
2387
2388   case REALPART_EXPR:
2389   case IMAGPART_EXPR:
2390   case PREINCREMENT_EXPR:
2391   case PREDECREMENT_EXPR:
2392   case SAVE_EXPR:
2393   case TRY_CATCH_EXPR:
2394   case WITH_CLEANUP_EXPR:
2395   case COMPOUND_EXPR:
2396   case MODIFY_EXPR:
2397   case TARGET_EXPR:
2398   case COND_EXPR:
2399   case BIND_EXPR:
2400     break;
2401
2402   default:
2403     /* Assume the worst for front-end tree codes.  */
2404     if ((int)TREE_CODE (x) >= NUM_TREE_CODES)
2405       break;
2406     return false;
2407   }
2408
2409   return true;
2410 }
2411
2412 /* Return an expr equal to X but certainly not valid as an lvalue.  */
2413
2414 tree
2415 non_lvalue_loc (location_t loc, tree x)
2416 {
2417   /* While we are in GIMPLE, NON_LVALUE_EXPR doesn't mean anything to
2418      us.  */
2419   if (in_gimple_form)
2420     return x;
2421
2422   if (! maybe_lvalue_p (x))
2423     return x;
2424   return build1_loc (loc, NON_LVALUE_EXPR, TREE_TYPE (x), x);
2425 }
2426
2427 /* When pedantic, return an expr equal to X but certainly not valid as a
2428    pedantic lvalue.  Otherwise, return X.  */
2429
2430 static tree
2431 pedantic_non_lvalue_loc (location_t loc, tree x)
2432 {
2433   return protected_set_expr_location_unshare (x, loc);
2434 }
2435 \f
2436 /* Given a tree comparison code, return the code that is the logical inverse.
2437    It is generally not safe to do this for floating-point comparisons, except
2438    for EQ_EXPR, NE_EXPR, ORDERED_EXPR and UNORDERED_EXPR, so we return
2439    ERROR_MARK in this case.  */
2440
2441 enum tree_code
2442 invert_tree_comparison (enum tree_code code, bool honor_nans)
2443 {
2444   if (honor_nans && flag_trapping_math && code != EQ_EXPR && code != NE_EXPR
2445       && code != ORDERED_EXPR && code != UNORDERED_EXPR)
2446     return ERROR_MARK;
2447
2448   switch (code)
2449     {
2450     case EQ_EXPR:
2451       return NE_EXPR;
2452     case NE_EXPR:
2453       return EQ_EXPR;
2454     case GT_EXPR:
2455       return honor_nans ? UNLE_EXPR : LE_EXPR;
2456     case GE_EXPR:
2457       return honor_nans ? UNLT_EXPR : LT_EXPR;
2458     case LT_EXPR:
2459       return honor_nans ? UNGE_EXPR : GE_EXPR;
2460     case LE_EXPR:
2461       return honor_nans ? UNGT_EXPR : GT_EXPR;
2462     case LTGT_EXPR:
2463       return UNEQ_EXPR;
2464     case UNEQ_EXPR:
2465       return LTGT_EXPR;
2466     case UNGT_EXPR:
2467       return LE_EXPR;
2468     case UNGE_EXPR:
2469       return LT_EXPR;
2470     case UNLT_EXPR:
2471       return GE_EXPR;
2472     case UNLE_EXPR:
2473       return GT_EXPR;
2474     case ORDERED_EXPR:
2475       return UNORDERED_EXPR;
2476     case UNORDERED_EXPR:
2477       return ORDERED_EXPR;
2478     default:
2479       gcc_unreachable ();
2480     }
2481 }
2482
2483 /* Similar, but return the comparison that results if the operands are
2484    swapped.  This is safe for floating-point.  */
2485
2486 enum tree_code
2487 swap_tree_comparison (enum tree_code code)
2488 {
2489   switch (code)
2490     {
2491     case EQ_EXPR:
2492     case NE_EXPR:
2493     case ORDERED_EXPR:
2494     case UNORDERED_EXPR:
2495     case LTGT_EXPR:
2496     case UNEQ_EXPR:
2497       return code;
2498     case GT_EXPR:
2499       return LT_EXPR;
2500     case GE_EXPR:
2501       return LE_EXPR;
2502     case LT_EXPR:
2503       return GT_EXPR;
2504     case LE_EXPR:
2505       return GE_EXPR;
2506     case UNGT_EXPR:
2507       return UNLT_EXPR;
2508     case UNGE_EXPR:
2509       return UNLE_EXPR;
2510     case UNLT_EXPR:
2511       return UNGT_EXPR;
2512     case UNLE_EXPR:
2513       return UNGE_EXPR;
2514     default:
2515       gcc_unreachable ();
2516     }
2517 }
2518
2519
2520 /* Convert a comparison tree code from an enum tree_code representation
2521    into a compcode bit-based encoding.  This function is the inverse of
2522    compcode_to_comparison.  */
2523
2524 static enum comparison_code
2525 comparison_to_compcode (enum tree_code code)
2526 {
2527   switch (code)
2528     {
2529     case LT_EXPR:
2530       return COMPCODE_LT;
2531     case EQ_EXPR:
2532       return COMPCODE_EQ;
2533     case LE_EXPR:
2534       return COMPCODE_LE;
2535     case GT_EXPR:
2536       return COMPCODE_GT;
2537     case NE_EXPR:
2538       return COMPCODE_NE;
2539     case GE_EXPR:
2540       return COMPCODE_GE;
2541     case ORDERED_EXPR:
2542       return COMPCODE_ORD;
2543     case UNORDERED_EXPR:
2544       return COMPCODE_UNORD;
2545     case UNLT_EXPR:
2546       return COMPCODE_UNLT;
2547     case UNEQ_EXPR:
2548       return COMPCODE_UNEQ;
2549     case UNLE_EXPR:
2550       return COMPCODE_UNLE;
2551     case UNGT_EXPR:
2552       return COMPCODE_UNGT;
2553     case LTGT_EXPR:
2554       return COMPCODE_LTGT;
2555     case UNGE_EXPR:
2556       return COMPCODE_UNGE;
2557     default:
2558       gcc_unreachable ();
2559     }
2560 }
2561
2562 /* Convert a compcode bit-based encoding of a comparison operator back
2563    to GCC's enum tree_code representation.  This function is the
2564    inverse of comparison_to_compcode.  */
2565
2566 static enum tree_code
2567 compcode_to_comparison (enum comparison_code code)
2568 {
2569   switch (code)
2570     {
2571     case COMPCODE_LT:
2572       return LT_EXPR;
2573     case COMPCODE_EQ:
2574       return EQ_EXPR;
2575     case COMPCODE_LE:
2576       return LE_EXPR;
2577     case COMPCODE_GT:
2578       return GT_EXPR;
2579     case COMPCODE_NE:
2580       return NE_EXPR;
2581     case COMPCODE_GE:
2582       return GE_EXPR;
2583     case COMPCODE_ORD:
2584       return ORDERED_EXPR;
2585     case COMPCODE_UNORD:
2586       return UNORDERED_EXPR;
2587     case COMPCODE_UNLT:
2588       return UNLT_EXPR;
2589     case COMPCODE_UNEQ:
2590       return UNEQ_EXPR;
2591     case COMPCODE_UNLE:
2592       return UNLE_EXPR;
2593     case COMPCODE_UNGT:
2594       return UNGT_EXPR;
2595     case COMPCODE_LTGT:
2596       return LTGT_EXPR;
2597     case COMPCODE_UNGE:
2598       return UNGE_EXPR;
2599     default:
2600       gcc_unreachable ();
2601     }
2602 }
2603
2604 /* Return a tree for the comparison which is the combination of
2605    doing the AND or OR (depending on CODE) of the two operations LCODE
2606    and RCODE on the identical operands LL_ARG and LR_ARG.  Take into account
2607    the possibility of trapping if the mode has NaNs, and return NULL_TREE
2608    if this makes the transformation invalid.  */
2609
2610 tree
2611 combine_comparisons (location_t loc,
2612                      enum tree_code code, enum tree_code lcode,
2613                      enum tree_code rcode, tree truth_type,
2614                      tree ll_arg, tree lr_arg)
2615 {
2616   bool honor_nans = HONOR_NANS (ll_arg);
2617   enum comparison_code lcompcode = comparison_to_compcode (lcode);
2618   enum comparison_code rcompcode = comparison_to_compcode (rcode);
2619   int compcode;
2620
2621   switch (code)
2622     {
2623     case TRUTH_AND_EXPR: case TRUTH_ANDIF_EXPR:
2624       compcode = lcompcode & rcompcode;
2625       break;
2626
2627     case TRUTH_OR_EXPR: case TRUTH_ORIF_EXPR:
2628       compcode = lcompcode | rcompcode;
2629       break;
2630
2631     default:
2632       return NULL_TREE;
2633     }
2634
2635   if (!honor_nans)
2636     {
2637       /* Eliminate unordered comparisons, as well as LTGT and ORD
2638          which are not used unless the mode has NaNs.  */
2639       compcode &= ~COMPCODE_UNORD;
2640       if (compcode == COMPCODE_LTGT)
2641         compcode = COMPCODE_NE;
2642       else if (compcode == COMPCODE_ORD)
2643         compcode = COMPCODE_TRUE;
2644     }
2645    else if (flag_trapping_math)
2646      {
2647         /* Check that the original operation and the optimized ones will trap
2648            under the same condition.  */
2649         bool ltrap = (lcompcode & COMPCODE_UNORD) == 0
2650                      && (lcompcode != COMPCODE_EQ)
2651                      && (lcompcode != COMPCODE_ORD);
2652         bool rtrap = (rcompcode & COMPCODE_UNORD) == 0
2653                      && (rcompcode != COMPCODE_EQ)
2654                      && (rcompcode != COMPCODE_ORD);
2655         bool trap = (compcode & COMPCODE_UNORD) == 0
2656                     && (compcode != COMPCODE_EQ)
2657                     && (compcode != COMPCODE_ORD);
2658
2659         /* In a short-circuited boolean expression the LHS might be
2660            such that the RHS, if evaluated, will never trap.  For
2661            example, in ORD (x, y) && (x < y), we evaluate the RHS only
2662            if neither x nor y is NaN.  (This is a mixed blessing: for
2663            example, the expression above will never trap, hence
2664            optimizing it to x < y would be invalid).  */
2665         if ((code == TRUTH_ORIF_EXPR && (lcompcode & COMPCODE_UNORD))
2666             || (code == TRUTH_ANDIF_EXPR && !(lcompcode & COMPCODE_UNORD)))
2667           rtrap = false;
2668
2669         /* If the comparison was short-circuited, and only the RHS
2670            trapped, we may now generate a spurious trap.  */
2671         if (rtrap && !ltrap
2672             && (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR))
2673           return NULL_TREE;
2674
2675         /* If we changed the conditions that cause a trap, we lose.  */
2676         if ((ltrap || rtrap) != trap)
2677           return NULL_TREE;
2678       }
2679
2680   if (compcode == COMPCODE_TRUE)
2681     return constant_boolean_node (true, truth_type);
2682   else if (compcode == COMPCODE_FALSE)
2683     return constant_boolean_node (false, truth_type);
2684   else
2685     {
2686       enum tree_code tcode;
2687
2688       tcode = compcode_to_comparison ((enum comparison_code) compcode);
2689       return fold_build2_loc (loc, tcode, truth_type, ll_arg, lr_arg);
2690     }
2691 }
2692 \f
2693 /* Return nonzero if two operands (typically of the same tree node)
2694    are necessarily equal.  If either argument has side-effects this
2695    function returns zero.  FLAGS modifies behavior as follows:
2696
2697    If OEP_ONLY_CONST is set, only return nonzero for constants.
2698    This function tests whether the operands are indistinguishable;
2699    it does not test whether they are equal using C's == operation.
2700    The distinction is important for IEEE floating point, because
2701    (1) -0.0 and 0.0 are distinguishable, but -0.0==0.0, and
2702    (2) two NaNs may be indistinguishable, but NaN!=NaN.
2703
2704    If OEP_ONLY_CONST is unset, a VAR_DECL is considered equal to itself
2705    even though it may hold multiple values during a function.
2706    This is because a GCC tree node guarantees that nothing else is
2707    executed between the evaluation of its "operands" (which may often
2708    be evaluated in arbitrary order).  Hence if the operands themselves
2709    don't side-effect, the VAR_DECLs, PARM_DECLs etc... must hold the
2710    same value in each operand/subexpression.  Hence leaving OEP_ONLY_CONST
2711    unset means assuming isochronic (or instantaneous) tree equivalence.
2712    Unless comparing arbitrary expression trees, such as from different
2713    statements, this flag can usually be left unset.
2714
2715    If OEP_PURE_SAME is set, then pure functions with identical arguments
2716    are considered the same.  It is used when the caller has other ways
2717    to ensure that global memory is unchanged in between.  */
2718
2719 int
2720 operand_equal_p (const_tree arg0, const_tree arg1, unsigned int flags)
2721 {
2722   /* If either is ERROR_MARK, they aren't equal.  */
2723   if (TREE_CODE (arg0) == ERROR_MARK || TREE_CODE (arg1) == ERROR_MARK
2724       || TREE_TYPE (arg0) == error_mark_node
2725       || TREE_TYPE (arg1) == error_mark_node)
2726     return 0;
2727
2728   /* Similar, if either does not have a type (like a released SSA name), 
2729      they aren't equal.  */
2730   if (!TREE_TYPE (arg0) || !TREE_TYPE (arg1))
2731     return 0;
2732
2733   /* Check equality of integer constants before bailing out due to
2734      precision differences.  */
2735   if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
2736     return tree_int_cst_equal (arg0, arg1);
2737
2738   /* If both types don't have the same signedness, then we can't consider
2739      them equal.  We must check this before the STRIP_NOPS calls
2740      because they may change the signedness of the arguments.  As pointers
2741      strictly don't have a signedness, require either two pointers or
2742      two non-pointers as well.  */
2743   if (TYPE_UNSIGNED (TREE_TYPE (arg0)) != TYPE_UNSIGNED (TREE_TYPE (arg1))
2744       || POINTER_TYPE_P (TREE_TYPE (arg0)) != POINTER_TYPE_P (TREE_TYPE (arg1)))
2745     return 0;
2746
2747   /* We cannot consider pointers to different address space equal.  */
2748   if (POINTER_TYPE_P (TREE_TYPE (arg0)) && POINTER_TYPE_P (TREE_TYPE (arg1))
2749       && (TYPE_ADDR_SPACE (TREE_TYPE (TREE_TYPE (arg0)))
2750           != TYPE_ADDR_SPACE (TREE_TYPE (TREE_TYPE (arg1)))))
2751     return 0;
2752
2753   /* If both types don't have the same precision, then it is not safe
2754      to strip NOPs.  */
2755   if (element_precision (TREE_TYPE (arg0))
2756       != element_precision (TREE_TYPE (arg1)))
2757     return 0;
2758
2759   STRIP_NOPS (arg0);
2760   STRIP_NOPS (arg1);
2761
2762   /* In case both args are comparisons but with different comparison
2763      code, try to swap the comparison operands of one arg to produce
2764      a match and compare that variant.  */
2765   if (TREE_CODE (arg0) != TREE_CODE (arg1)
2766       && COMPARISON_CLASS_P (arg0)
2767       && COMPARISON_CLASS_P (arg1))
2768     {
2769       enum tree_code swap_code = swap_tree_comparison (TREE_CODE (arg1));
2770
2771       if (TREE_CODE (arg0) == swap_code)
2772         return operand_equal_p (TREE_OPERAND (arg0, 0),
2773                                 TREE_OPERAND (arg1, 1), flags)
2774                && operand_equal_p (TREE_OPERAND (arg0, 1),
2775                                    TREE_OPERAND (arg1, 0), flags);
2776     }
2777
2778   if (TREE_CODE (arg0) != TREE_CODE (arg1)
2779       /* NOP_EXPR and CONVERT_EXPR are considered equal.  */
2780       && !(CONVERT_EXPR_P (arg0) && CONVERT_EXPR_P (arg1)))
2781     return 0;
2782
2783   /* This is needed for conversions and for COMPONENT_REF.
2784      Might as well play it safe and always test this.  */
2785   if (TREE_CODE (TREE_TYPE (arg0)) == ERROR_MARK
2786       || TREE_CODE (TREE_TYPE (arg1)) == ERROR_MARK
2787       || TYPE_MODE (TREE_TYPE (arg0)) != TYPE_MODE (TREE_TYPE (arg1)))
2788     return 0;
2789
2790   /* If ARG0 and ARG1 are the same SAVE_EXPR, they are necessarily equal.
2791      We don't care about side effects in that case because the SAVE_EXPR
2792      takes care of that for us. In all other cases, two expressions are
2793      equal if they have no side effects.  If we have two identical
2794      expressions with side effects that should be treated the same due
2795      to the only side effects being identical SAVE_EXPR's, that will
2796      be detected in the recursive calls below.
2797      If we are taking an invariant address of two identical objects
2798      they are necessarily equal as well.  */
2799   if (arg0 == arg1 && ! (flags & OEP_ONLY_CONST)
2800       && (TREE_CODE (arg0) == SAVE_EXPR
2801           || (flags & OEP_CONSTANT_ADDRESS_OF)
2802           || (! TREE_SIDE_EFFECTS (arg0) && ! TREE_SIDE_EFFECTS (arg1))))
2803     return 1;
2804
2805   /* Next handle constant cases, those for which we can return 1 even
2806      if ONLY_CONST is set.  */
2807   if (TREE_CONSTANT (arg0) && TREE_CONSTANT (arg1))
2808     switch (TREE_CODE (arg0))
2809       {
2810       case INTEGER_CST:
2811         return tree_int_cst_equal (arg0, arg1);
2812
2813       case FIXED_CST:
2814         return FIXED_VALUES_IDENTICAL (TREE_FIXED_CST (arg0),
2815                                        TREE_FIXED_CST (arg1));
2816
2817       case REAL_CST:
2818         if (REAL_VALUES_IDENTICAL (TREE_REAL_CST (arg0),
2819                                    TREE_REAL_CST (arg1)))
2820           return 1;
2821
2822
2823         if (!HONOR_SIGNED_ZEROS (arg0))
2824           {
2825             /* If we do not distinguish between signed and unsigned zero,
2826                consider them equal.  */
2827             if (real_zerop (arg0) && real_zerop (arg1))
2828               return 1;
2829           }
2830         return 0;
2831
2832       case VECTOR_CST:
2833         {
2834           unsigned i;
2835
2836           if (VECTOR_CST_NELTS (arg0) != VECTOR_CST_NELTS (arg1))
2837             return 0;
2838
2839           for (i = 0; i < VECTOR_CST_NELTS (arg0); ++i)
2840             {
2841               if (!operand_equal_p (VECTOR_CST_ELT (arg0, i),
2842                                     VECTOR_CST_ELT (arg1, i), flags))
2843                 return 0;
2844             }
2845           return 1;
2846         }
2847
2848       case COMPLEX_CST:
2849         return (operand_equal_p (TREE_REALPART (arg0), TREE_REALPART (arg1),
2850                                  flags)
2851                 && operand_equal_p (TREE_IMAGPART (arg0), TREE_IMAGPART (arg1),
2852                                     flags));
2853
2854       case STRING_CST:
2855         return (TREE_STRING_LENGTH (arg0) == TREE_STRING_LENGTH (arg1)
2856                 && ! memcmp (TREE_STRING_POINTER (arg0),
2857                               TREE_STRING_POINTER (arg1),
2858                               TREE_STRING_LENGTH (arg0)));
2859
2860       case ADDR_EXPR:
2861         return operand_equal_p (TREE_OPERAND (arg0, 0), TREE_OPERAND (arg1, 0),
2862                                 TREE_CONSTANT (arg0) && TREE_CONSTANT (arg1)
2863                                 ? OEP_CONSTANT_ADDRESS_OF : 0);
2864       default:
2865         break;
2866       }
2867
2868   if (flags & OEP_ONLY_CONST)
2869     return 0;
2870
2871 /* Define macros to test an operand from arg0 and arg1 for equality and a
2872    variant that allows null and views null as being different from any
2873    non-null value.  In the latter case, if either is null, the both
2874    must be; otherwise, do the normal comparison.  */
2875 #define OP_SAME(N) operand_equal_p (TREE_OPERAND (arg0, N),     \
2876                                     TREE_OPERAND (arg1, N), flags)
2877
2878 #define OP_SAME_WITH_NULL(N)                            \
2879   ((!TREE_OPERAND (arg0, N) || !TREE_OPERAND (arg1, N)) \
2880    ? TREE_OPERAND (arg0, N) == TREE_OPERAND (arg1, N) : OP_SAME (N))
2881
2882   switch (TREE_CODE_CLASS (TREE_CODE (arg0)))
2883     {
2884     case tcc_unary:
2885       /* Two conversions are equal only if signedness and modes match.  */
2886       switch (TREE_CODE (arg0))
2887         {
2888         CASE_CONVERT:
2889         case FIX_TRUNC_EXPR:
2890           if (TYPE_UNSIGNED (TREE_TYPE (arg0))
2891               != TYPE_UNSIGNED (TREE_TYPE (arg1)))
2892             return 0;
2893           break;
2894         default:
2895           break;
2896         }
2897
2898       return OP_SAME (0);
2899
2900
2901     case tcc_comparison:
2902     case tcc_binary:
2903       if (OP_SAME (0) && OP_SAME (1))
2904         return 1;
2905
2906       /* For commutative ops, allow the other order.  */
2907       return (commutative_tree_code (TREE_CODE (arg0))
2908               && operand_equal_p (TREE_OPERAND (arg0, 0),
2909                                   TREE_OPERAND (arg1, 1), flags)
2910               && operand_equal_p (TREE_OPERAND (arg0, 1),
2911                                   TREE_OPERAND (arg1, 0), flags));
2912
2913     case tcc_reference:
2914       /* If either of the pointer (or reference) expressions we are
2915          dereferencing contain a side effect, these cannot be equal,
2916          but their addresses can be.  */
2917       if ((flags & OEP_CONSTANT_ADDRESS_OF) == 0
2918           && (TREE_SIDE_EFFECTS (arg0)
2919               || TREE_SIDE_EFFECTS (arg1)))
2920         return 0;
2921
2922       switch (TREE_CODE (arg0))
2923         {
2924         case INDIRECT_REF:
2925           flags &= ~OEP_CONSTANT_ADDRESS_OF;
2926           return OP_SAME (0);
2927
2928         case REALPART_EXPR:
2929         case IMAGPART_EXPR:
2930           return OP_SAME (0);
2931
2932         case TARGET_MEM_REF:
2933           flags &= ~OEP_CONSTANT_ADDRESS_OF;
2934           /* Require equal extra operands and then fall through to MEM_REF
2935              handling of the two common operands.  */
2936           if (!OP_SAME_WITH_NULL (2)
2937               || !OP_SAME_WITH_NULL (3)
2938               || !OP_SAME_WITH_NULL (4))
2939             return 0;
2940           /* Fallthru.  */
2941         case MEM_REF:
2942           flags &= ~OEP_CONSTANT_ADDRESS_OF;
2943           /* Require equal access sizes, and similar pointer types.
2944              We can have incomplete types for array references of
2945              variable-sized arrays from the Fortran frontend
2946              though.  Also verify the types are compatible.  */
2947           return ((TYPE_SIZE (TREE_TYPE (arg0)) == TYPE_SIZE (TREE_TYPE (arg1))
2948                    || (TYPE_SIZE (TREE_TYPE (arg0))
2949                        && TYPE_SIZE (TREE_TYPE (arg1))
2950                        && operand_equal_p (TYPE_SIZE (TREE_TYPE (arg0)),
2951                                            TYPE_SIZE (TREE_TYPE (arg1)), flags)))
2952                   && types_compatible_p (TREE_TYPE (arg0), TREE_TYPE (arg1))
2953                   && alias_ptr_types_compatible_p
2954                        (TREE_TYPE (TREE_OPERAND (arg0, 1)),
2955                         TREE_TYPE (TREE_OPERAND (arg1, 1)))
2956                   && OP_SAME (0) && OP_SAME (1));
2957
2958         case ARRAY_REF:
2959         case ARRAY_RANGE_REF:
2960           /* Operands 2 and 3 may be null.
2961              Compare the array index by value if it is constant first as we
2962              may have different types but same value here.  */
2963           if (!OP_SAME (0))
2964             return 0;
2965           flags &= ~OEP_CONSTANT_ADDRESS_OF;
2966           return ((tree_int_cst_equal (TREE_OPERAND (arg0, 1),
2967                                        TREE_OPERAND (arg1, 1))
2968                    || OP_SAME (1))
2969                   && OP_SAME_WITH_NULL (2)
2970                   && OP_SAME_WITH_NULL (3));
2971
2972         case COMPONENT_REF:
2973           /* Handle operand 2 the same as for ARRAY_REF.  Operand 0
2974              may be NULL when we're called to compare MEM_EXPRs.  */
2975           if (!OP_SAME_WITH_NULL (0)
2976               || !OP_SAME (1))
2977             return 0;
2978           flags &= ~OEP_CONSTANT_ADDRESS_OF;
2979           return OP_SAME_WITH_NULL (2);
2980
2981         case BIT_FIELD_REF:
2982           if (!OP_SAME (0))
2983             return 0;
2984           flags &= ~OEP_CONSTANT_ADDRESS_OF;
2985           return OP_SAME (1) && OP_SAME (2);
2986
2987         default:
2988           return 0;
2989         }
2990
2991     case tcc_expression:
2992       switch (TREE_CODE (arg0))
2993         {
2994         case ADDR_EXPR:
2995         case TRUTH_NOT_EXPR:
2996           return OP_SAME (0);
2997
2998         case TRUTH_ANDIF_EXPR:
2999         case TRUTH_ORIF_EXPR:
3000           return OP_SAME (0) && OP_SAME (1);
3001
3002         case FMA_EXPR:
3003         case WIDEN_MULT_PLUS_EXPR:
3004         case WIDEN_MULT_MINUS_EXPR:
3005           if (!OP_SAME (2))
3006             return 0;
3007           /* The multiplcation operands are commutative.  */
3008           /* FALLTHRU */
3009
3010         case TRUTH_AND_EXPR:
3011         case TRUTH_OR_EXPR:
3012         case TRUTH_XOR_EXPR:
3013           if (OP_SAME (0) && OP_SAME (1))
3014             return 1;
3015
3016           /* Otherwise take into account this is a commutative operation.  */
3017           return (operand_equal_p (TREE_OPERAND (arg0, 0),
3018                                    TREE_OPERAND (arg1, 1), flags)
3019                   && operand_equal_p (TREE_OPERAND (arg0, 1),
3020                                       TREE_OPERAND (arg1, 0), flags));
3021
3022         case COND_EXPR:
3023         case VEC_COND_EXPR:
3024         case DOT_PROD_EXPR:
3025           return OP_SAME (0) && OP_SAME (1) && OP_SAME (2);
3026
3027         default:
3028           return 0;
3029         }
3030
3031     case tcc_vl_exp:
3032       switch (TREE_CODE (arg0))
3033         {
3034         case CALL_EXPR:
3035           /* If the CALL_EXPRs call different functions, then they
3036              clearly can not be equal.  */
3037           if (! operand_equal_p (CALL_EXPR_FN (arg0), CALL_EXPR_FN (arg1),
3038                                  flags))
3039             return 0;
3040
3041           {
3042             unsigned int cef = call_expr_flags (arg0);
3043             if (flags & OEP_PURE_SAME)
3044               cef &= ECF_CONST | ECF_PURE;
3045             else
3046               cef &= ECF_CONST;
3047             if (!cef)
3048               return 0;
3049           }
3050
3051           /* Now see if all the arguments are the same.  */
3052           {
3053             const_call_expr_arg_iterator iter0, iter1;
3054             const_tree a0, a1;
3055             for (a0 = first_const_call_expr_arg (arg0, &iter0),
3056                    a1 = first_const_call_expr_arg (arg1, &iter1);
3057                  a0 && a1;
3058                  a0 = next_const_call_expr_arg (&iter0),
3059                    a1 = next_const_call_expr_arg (&iter1))
3060               if (! operand_equal_p (a0, a1, flags))
3061                 return 0;
3062
3063             /* If we get here and both argument lists are exhausted
3064                then the CALL_EXPRs are equal.  */
3065             return ! (a0 || a1);
3066           }
3067         default:
3068           return 0;
3069         }
3070
3071     case tcc_declaration:
3072       /* Consider __builtin_sqrt equal to sqrt.  */
3073       return (TREE_CODE (arg0) == FUNCTION_DECL
3074               && DECL_BUILT_IN (arg0) && DECL_BUILT_IN (arg1)
3075               && DECL_BUILT_IN_CLASS (arg0) == DECL_BUILT_IN_CLASS (arg1)
3076               && DECL_FUNCTION_CODE (arg0) == DECL_FUNCTION_CODE (arg1));
3077
3078     default:
3079       return 0;
3080     }
3081
3082 #undef OP_SAME
3083 #undef OP_SAME_WITH_NULL
3084 }
3085 \f
3086 /* Similar to operand_equal_p, but see if ARG0 might have been made by
3087    shorten_compare from ARG1 when ARG1 was being compared with OTHER.
3088
3089    When in doubt, return 0.  */
3090
3091 static int
3092 operand_equal_for_comparison_p (tree arg0, tree arg1, tree other)
3093 {
3094   int unsignedp1, unsignedpo;
3095   tree primarg0, primarg1, primother;
3096   unsigned int correct_width;
3097
3098   if (operand_equal_p (arg0, arg1, 0))
3099     return 1;
3100
3101   if (! INTEGRAL_TYPE_P (TREE_TYPE (arg0))
3102       || ! INTEGRAL_TYPE_P (TREE_TYPE (arg1)))
3103     return 0;
3104
3105   /* Discard any conversions that don't change the modes of ARG0 and ARG1
3106      and see if the inner values are the same.  This removes any
3107      signedness comparison, which doesn't matter here.  */
3108   primarg0 = arg0, primarg1 = arg1;
3109   STRIP_NOPS (primarg0);
3110   STRIP_NOPS (primarg1);
3111   if (operand_equal_p (primarg0, primarg1, 0))
3112     return 1;
3113
3114   /* Duplicate what shorten_compare does to ARG1 and see if that gives the
3115      actual comparison operand, ARG0.
3116
3117      First throw away any conversions to wider types
3118      already present in the operands.  */
3119
3120   primarg1 = get_narrower (arg1, &unsignedp1);
3121   primother = get_narrower (other, &unsignedpo);
3122
3123   correct_width = TYPE_PRECISION (TREE_TYPE (arg1));
3124   if (unsignedp1 == unsignedpo
3125       && TYPE_PRECISION (TREE_TYPE (primarg1)) < correct_width
3126       && TYPE_PRECISION (TREE_TYPE (primother)) < correct_width)
3127     {
3128       tree type = TREE_TYPE (arg0);
3129
3130       /* Make sure shorter operand is extended the right way
3131          to match the longer operand.  */
3132       primarg1 = fold_convert (signed_or_unsigned_type_for
3133                                (unsignedp1, TREE_TYPE (primarg1)), primarg1);
3134
3135       if (operand_equal_p (arg0, fold_convert (type, primarg1), 0))
3136         return 1;
3137     }
3138
3139   return 0;
3140 }
3141 \f
3142 /* See if ARG is an expression that is either a comparison or is performing
3143    arithmetic on comparisons.  The comparisons must only be comparing
3144    two different values, which will be stored in *CVAL1 and *CVAL2; if
3145    they are nonzero it means that some operands have already been found.
3146    No variables may be used anywhere else in the expression except in the
3147    comparisons.  If SAVE_P is true it means we removed a SAVE_EXPR around
3148    the expression and save_expr needs to be called with CVAL1 and CVAL2.
3149
3150    If this is true, return 1.  Otherwise, return zero.  */
3151
3152 static int
3153 twoval_comparison_p (tree arg, tree *cval1, tree *cval2, int *save_p)
3154 {
3155   enum tree_code code = TREE_CODE (arg);
3156   enum tree_code_class tclass = TREE_CODE_CLASS (code);
3157
3158   /* We can handle some of the tcc_expression cases here.  */
3159   if (tclass == tcc_expression && code == TRUTH_NOT_EXPR)
3160     tclass = tcc_unary;
3161   else if (tclass == tcc_expression
3162            && (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR
3163                || code == COMPOUND_EXPR))
3164     tclass = tcc_binary;
3165
3166   else if (tclass == tcc_expression && code == SAVE_EXPR
3167            && ! TREE_SIDE_EFFECTS (TREE_OPERAND (arg, 0)))
3168     {
3169       /* If we've already found a CVAL1 or CVAL2, this expression is
3170          two complex to handle.  */
3171       if (*cval1 || *cval2)
3172         return 0;
3173
3174       tclass = tcc_unary;
3175       *save_p = 1;
3176     }
3177
3178   switch (tclass)
3179     {
3180     case tcc_unary:
3181       return twoval_comparison_p (TREE_OPERAND (arg, 0), cval1, cval2, save_p);
3182
3183     case tcc_binary:
3184       return (twoval_comparison_p (TREE_OPERAND (arg, 0), cval1, cval2, save_p)
3185               && twoval_comparison_p (TREE_OPERAND (arg, 1),
3186                                       cval1, cval2, save_p));
3187
3188     case tcc_constant:
3189       return 1;
3190
3191     case tcc_expression:
3192       if (code == COND_EXPR)
3193         return (twoval_comparison_p (TREE_OPERAND (arg, 0),
3194                                      cval1, cval2, save_p)
3195                 && twoval_comparison_p (TREE_OPERAND (arg, 1),
3196                                         cval1, cval2, save_p)
3197                 && twoval_comparison_p (TREE_OPERAND (arg, 2),
3198                                         cval1, cval2, save_p));
3199       return 0;
3200
3201     case tcc_comparison:
3202       /* First see if we can handle the first operand, then the second.  For
3203          the second operand, we know *CVAL1 can't be zero.  It must be that
3204          one side of the comparison is each of the values; test for the
3205          case where this isn't true by failing if the two operands
3206          are the same.  */
3207
3208       if (operand_equal_p (TREE_OPERAND (arg, 0),
3209                            TREE_OPERAND (arg, 1), 0))
3210         return 0;
3211
3212       if (*cval1 == 0)
3213         *cval1 = TREE_OPERAND (arg, 0);
3214       else if (operand_equal_p (*cval1, TREE_OPERAND (arg, 0), 0))
3215         ;
3216       else if (*cval2 == 0)
3217         *cval2 = TREE_OPERAND (arg, 0);
3218       else if (operand_equal_p (*cval2, TREE_OPERAND (arg, 0), 0))
3219         ;
3220       else
3221         return 0;
3222
3223       if (operand_equal_p (*cval1, TREE_OPERAND (arg, 1), 0))
3224         ;
3225       else if (*cval2 == 0)
3226         *cval2 = TREE_OPERAND (arg, 1);
3227       else if (operand_equal_p (*cval2, TREE_OPERAND (arg, 1), 0))
3228         ;
3229       else
3230         return 0;
3231
3232       return 1;
3233
3234     default:
3235       return 0;
3236     }
3237 }
3238 \f
3239 /* ARG is a tree that is known to contain just arithmetic operations and
3240    comparisons.  Evaluate the operations in the tree substituting NEW0 for
3241    any occurrence of OLD0 as an operand of a comparison and likewise for
3242    NEW1 and OLD1.  */
3243
3244 static tree
3245 eval_subst (location_t loc, tree arg, tree old0, tree new0,
3246             tree old1, tree new1)
3247 {
3248   tree type = TREE_TYPE (arg);
3249   enum tree_code code = TREE_CODE (arg);
3250   enum tree_code_class tclass = TREE_CODE_CLASS (code);
3251
3252   /* We can handle some of the tcc_expression cases here.  */
3253   if (tclass == tcc_expression && code == TRUTH_NOT_EXPR)
3254     tclass = tcc_unary;
3255   else if (tclass == tcc_expression
3256            && (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR))
3257     tclass = tcc_binary;
3258
3259   switch (tclass)
3260     {
3261     case tcc_unary:
3262       return fold_build1_loc (loc, code, type,
3263                           eval_subst (loc, TREE_OPERAND (arg, 0),
3264                                       old0, new0, old1, new1));
3265
3266     case tcc_binary:
3267       return fold_build2_loc (loc, code, type,
3268                           eval_subst (loc, TREE_OPERAND (arg, 0),
3269                                       old0, new0, old1, new1),
3270                           eval_subst (loc, TREE_OPERAND (arg, 1),
3271                                       old0, new0, old1, new1));
3272
3273     case tcc_expression:
3274       switch (code)
3275         {
3276         case SAVE_EXPR:
3277           return eval_subst (loc, TREE_OPERAND (arg, 0), old0, new0,
3278                              old1, new1);
3279
3280         case COMPOUND_EXPR:
3281           return eval_subst (loc, TREE_OPERAND (arg, 1), old0, new0,
3282                              old1, new1);
3283
3284         case COND_EXPR:
3285           return fold_build3_loc (loc, code, type,
3286                               eval_subst (loc, TREE_OPERAND (arg, 0),
3287                                           old0, new0, old1, new1),
3288                               eval_subst (loc, TREE_OPERAND (arg, 1),
3289                                           old0, new0, old1, new1),
3290                               eval_subst (loc, TREE_OPERAND (arg, 2),
3291                                           old0, new0, old1, new1));
3292         default:
3293           break;
3294         }
3295       /* Fall through - ???  */
3296
3297     case tcc_comparison:
3298       {
3299         tree arg0 = TREE_OPERAND (arg, 0);
3300         tree arg1 = TREE_OPERAND (arg, 1);
3301
3302         /* We need to check both for exact equality and tree equality.  The
3303            former will be true if the operand has a side-effect.  In that
3304            case, we know the operand occurred exactly once.  */
3305
3306         if (arg0 == old0 || operand_equal_p (arg0, old0, 0))
3307           arg0 = new0;
3308         else if (arg0 == old1 || operand_equal_p (arg0, old1, 0))
3309           arg0 = new1;
3310
3311         if (arg1 == old0 || operand_equal_p (arg1, old0, 0))
3312           arg1 = new0;
3313         else if (arg1 == old1 || operand_equal_p (arg1, old1, 0))
3314           arg1 = new1;
3315
3316         return fold_build2_loc (loc, code, type, arg0, arg1);
3317       }
3318
3319     default:
3320       return arg;
3321     }
3322 }
3323 \f
3324 /* Return a tree for the case when the result of an expression is RESULT
3325    converted to TYPE and OMITTED was previously an operand of the expression
3326    but is now not needed (e.g., we folded OMITTED * 0).
3327
3328    If OMITTED has side effects, we must evaluate it.  Otherwise, just do
3329    the conversion of RESULT to TYPE.  */
3330
3331 tree
3332 omit_one_operand_loc (location_t loc, tree type, tree result, tree omitted)
3333 {
3334   tree t = fold_convert_loc (loc, type, result);
3335
3336   /* If the resulting operand is an empty statement, just return the omitted
3337      statement casted to void. */
3338   if (IS_EMPTY_STMT (t) && TREE_SIDE_EFFECTS (omitted))
3339     return build1_loc (loc, NOP_EXPR, void_type_node,
3340                        fold_ignored_result (omitted));
3341
3342   if (TREE_SIDE_EFFECTS (omitted))
3343     return build2_loc (loc, COMPOUND_EXPR, type,
3344                        fold_ignored_result (omitted), t);
3345
3346   return non_lvalue_loc (loc, t);
3347 }
3348
3349 /* Return a tree for the case when the result of an expression is RESULT
3350    converted to TYPE and OMITTED1 and OMITTED2 were previously operands
3351    of the expression but are now not needed.
3352
3353    If OMITTED1 or OMITTED2 has side effects, they must be evaluated.
3354    If both OMITTED1 and OMITTED2 have side effects, OMITTED1 is
3355    evaluated before OMITTED2.  Otherwise, if neither has side effects,
3356    just do the conversion of RESULT to TYPE.  */
3357
3358 tree
3359 omit_two_operands_loc (location_t loc, tree type, tree result,
3360                        tree omitted1, tree omitted2)
3361 {
3362   tree t = fold_convert_loc (loc, type, result);
3363
3364   if (TREE_SIDE_EFFECTS (omitted2))
3365     t = build2_loc (loc, COMPOUND_EXPR, type, omitted2, t);
3366   if (TREE_SIDE_EFFECTS (omitted1))
3367     t = build2_loc (loc, COMPOUND_EXPR, type, omitted1, t);
3368
3369   return TREE_CODE (t) != COMPOUND_EXPR ? non_lvalue_loc (loc, t) : t;
3370 }
3371
3372 \f
3373 /* Return a simplified tree node for the truth-negation of ARG.  This
3374    never alters ARG itself.  We assume that ARG is an operation that
3375    returns a truth value (0 or 1).
3376
3377    FIXME: one would think we would fold the result, but it causes
3378    problems with the dominator optimizer.  */
3379
3380 static tree
3381 fold_truth_not_expr (location_t loc, tree arg)
3382 {
3383   tree type = TREE_TYPE (arg);
3384   enum tree_code code = TREE_CODE (arg);
3385   location_t loc1, loc2;
3386
3387   /* If this is a comparison, we can simply invert it, except for
3388      floating-point non-equality comparisons, in which case we just
3389      enclose a TRUTH_NOT_EXPR around what we have.  */
3390
3391   if (TREE_CODE_CLASS (code) == tcc_comparison)
3392     {
3393       tree op_type = TREE_TYPE (TREE_OPERAND (arg, 0));
3394       if (FLOAT_TYPE_P (op_type)
3395           && flag_trapping_math
3396           && code != ORDERED_EXPR && code != UNORDERED_EXPR
3397           && code != NE_EXPR && code != EQ_EXPR)
3398         return NULL_TREE;
3399
3400       code = invert_tree_comparison (code, HONOR_NANS (op_type));
3401       if (code == ERROR_MARK)
3402         return NULL_TREE;
3403
3404       return build2_loc (loc, code, type, TREE_OPERAND (arg, 0),
3405                          TREE_OPERAND (arg, 1));
3406     }
3407
3408   switch (code)
3409     {
3410     case INTEGER_CST:
3411       return constant_boolean_node (integer_zerop (arg), type);
3412
3413     case TRUTH_AND_EXPR:
3414       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3415       loc2 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3416       return build2_loc (loc, TRUTH_OR_EXPR, type,
3417                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)),
3418                          invert_truthvalue_loc (loc2, TREE_OPERAND (arg, 1)));
3419
3420     case TRUTH_OR_EXPR:
3421       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3422       loc2 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3423       return build2_loc (loc, TRUTH_AND_EXPR, type,
3424                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)),
3425                          invert_truthvalue_loc (loc2, TREE_OPERAND (arg, 1)));
3426
3427     case TRUTH_XOR_EXPR:
3428       /* Here we can invert either operand.  We invert the first operand
3429          unless the second operand is a TRUTH_NOT_EXPR in which case our
3430          result is the XOR of the first operand with the inside of the
3431          negation of the second operand.  */
3432
3433       if (TREE_CODE (TREE_OPERAND (arg, 1)) == TRUTH_NOT_EXPR)
3434         return build2_loc (loc, TRUTH_XOR_EXPR, type, TREE_OPERAND (arg, 0),
3435                            TREE_OPERAND (TREE_OPERAND (arg, 1), 0));
3436       else
3437         return build2_loc (loc, TRUTH_XOR_EXPR, type,
3438                            invert_truthvalue_loc (loc, TREE_OPERAND (arg, 0)),
3439                            TREE_OPERAND (arg, 1));
3440
3441     case TRUTH_ANDIF_EXPR:
3442       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3443       loc2 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3444       return build2_loc (loc, TRUTH_ORIF_EXPR, type,
3445                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)),
3446                          invert_truthvalue_loc (loc2, TREE_OPERAND (arg, 1)));
3447
3448     case TRUTH_ORIF_EXPR:
3449       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3450       loc2 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3451       return build2_loc (loc, TRUTH_ANDIF_EXPR, type,
3452                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)),
3453                          invert_truthvalue_loc (loc2, TREE_OPERAND (arg, 1)));
3454
3455     case TRUTH_NOT_EXPR:
3456       return TREE_OPERAND (arg, 0);
3457
3458     case COND_EXPR:
3459       {
3460         tree arg1 = TREE_OPERAND (arg, 1);
3461         tree arg2 = TREE_OPERAND (arg, 2);
3462
3463         loc1 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3464         loc2 = expr_location_or (TREE_OPERAND (arg, 2), loc);
3465
3466         /* A COND_EXPR may have a throw as one operand, which
3467            then has void type.  Just leave void operands
3468            as they are.  */
3469         return build3_loc (loc, COND_EXPR, type, TREE_OPERAND (arg, 0),
3470                            VOID_TYPE_P (TREE_TYPE (arg1))
3471                            ? arg1 : invert_truthvalue_loc (loc1, arg1),
3472                            VOID_TYPE_P (TREE_TYPE (arg2))
3473                            ? arg2 : invert_truthvalue_loc (loc2, arg2));
3474       }
3475
3476     case COMPOUND_EXPR:
3477       loc1 = expr_location_or (TREE_OPERAND (arg, 1), loc);
3478       return build2_loc (loc, COMPOUND_EXPR, type,
3479                          TREE_OPERAND (arg, 0),
3480                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 1)));
3481
3482     case NON_LVALUE_EXPR:
3483       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3484       return invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0));
3485
3486     CASE_CONVERT:
3487       if (TREE_CODE (TREE_TYPE (arg)) == BOOLEAN_TYPE)
3488         return build1_loc (loc, TRUTH_NOT_EXPR, type, arg);
3489
3490       /* ... fall through ...  */
3491
3492     case FLOAT_EXPR:
3493       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3494       return build1_loc (loc, TREE_CODE (arg), type,
3495                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)));
3496
3497     case BIT_AND_EXPR:
3498       if (!integer_onep (TREE_OPERAND (arg, 1)))
3499         return NULL_TREE;
3500       return build2_loc (loc, EQ_EXPR, type, arg, build_int_cst (type, 0));
3501
3502     case SAVE_EXPR:
3503       return build1_loc (loc, TRUTH_NOT_EXPR, type, arg);
3504
3505     case CLEANUP_POINT_EXPR:
3506       loc1 = expr_location_or (TREE_OPERAND (arg, 0), loc);
3507       return build1_loc (loc, CLEANUP_POINT_EXPR, type,
3508                          invert_truthvalue_loc (loc1, TREE_OPERAND (arg, 0)));
3509
3510     default:
3511       return NULL_TREE;
3512     }
3513 }
3514
3515 /* Fold the truth-negation of ARG.  This never alters ARG itself.  We
3516    assume that ARG is an operation that returns a truth value (0 or 1
3517    for scalars, 0 or -1 for vectors).  Return the folded expression if
3518    folding is successful.  Otherwise, return NULL_TREE.  */
3519
3520 static tree
3521 fold_invert_truthvalue (location_t loc, tree arg)
3522 {
3523   tree type = TREE_TYPE (arg);
3524   return fold_unary_loc (loc, VECTOR_TYPE_P (type)
3525                               ? BIT_NOT_EXPR
3526                               : TRUTH_NOT_EXPR,
3527                          type, arg);
3528 }
3529
3530 /* Return a simplified tree node for the truth-negation of ARG.  This
3531    never alters ARG itself.  We assume that ARG is an operation that
3532    returns a truth value (0 or 1 for scalars, 0 or -1 for vectors).  */
3533
3534 tree
3535 invert_truthvalue_loc (location_t loc, tree arg)
3536 {
3537   if (TREE_CODE (arg) == ERROR_MARK)
3538     return arg;
3539
3540   tree type = TREE_TYPE (arg);
3541   return fold_build1_loc (loc, VECTOR_TYPE_P (type)
3542                                ? BIT_NOT_EXPR
3543                                : TRUTH_NOT_EXPR,
3544                           type, arg);
3545 }
3546
3547 /* Given a bit-wise operation CODE applied to ARG0 and ARG1, see if both
3548    operands are another bit-wise operation with a common input.  If so,
3549    distribute the bit operations to save an operation and possibly two if
3550    constants are involved.  For example, convert
3551         (A | B) & (A | C) into A | (B & C)
3552    Further simplification will occur if B and C are constants.
3553
3554    If this optimization cannot be done, 0 will be returned.  */
3555
3556 static tree
3557 distribute_bit_expr (location_t loc, enum tree_code code, tree type,
3558                      tree arg0, tree arg1)
3559 {
3560   tree common;
3561   tree left, right;
3562
3563   if (TREE_CODE (arg0) != TREE_CODE (arg1)
3564       || TREE_CODE (arg0) == code
3565       || (TREE_CODE (arg0) != BIT_AND_EXPR
3566           && TREE_CODE (arg0) != BIT_IOR_EXPR))
3567     return 0;
3568
3569   if (operand_equal_p (TREE_OPERAND (arg0, 0), TREE_OPERAND (arg1, 0), 0))
3570     {
3571       common = TREE_OPERAND (arg0, 0);
3572       left = TREE_OPERAND (arg0, 1);
3573       right = TREE_OPERAND (arg1, 1);
3574     }
3575   else if (operand_equal_p (TREE_OPERAND (arg0, 0), TREE_OPERAND (arg1, 1), 0))
3576     {
3577       common = TREE_OPERAND (arg0, 0);
3578       left = TREE_OPERAND (arg0, 1);
3579       right = TREE_OPERAND (arg1, 0);
3580     }
3581   else if (operand_equal_p (TREE_OPERAND (arg0, 1), TREE_OPERAND (arg1, 0), 0))
3582     {
3583       common = TREE_OPERAND (arg0, 1);
3584       left = TREE_OPERAND (arg0, 0);
3585       right = TREE_OPERAND (arg1, 1);
3586     }
3587   else if (operand_equal_p (TREE_OPERAND (arg0, 1), TREE_OPERAND (arg1, 1), 0))
3588     {
3589       common = TREE_OPERAND (arg0, 1);
3590       left = TREE_OPERAND (arg0, 0);
3591       right = TREE_OPERAND (arg1, 0);
3592     }
3593   else
3594     return 0;
3595
3596   common = fold_convert_loc (loc, type, common);
3597   left = fold_convert_loc (loc, type, left);
3598   right = fold_convert_loc (loc, type, right);
3599   return fold_build2_loc (loc, TREE_CODE (arg0), type, common,
3600                       fold_build2_loc (loc, code, type, left, right));
3601 }
3602
3603 /* Knowing that ARG0 and ARG1 are both RDIV_EXPRs, simplify a binary operation
3604    with code CODE.  This optimization is unsafe.  */
3605 static tree
3606 distribute_real_division (location_t loc, enum tree_code code, tree type,
3607                           tree arg0, tree arg1)
3608 {
3609   bool mul0 = TREE_CODE (arg0) == MULT_EXPR;
3610   bool mul1 = TREE_CODE (arg1) == MULT_EXPR;
3611
3612   /* (A / C) +- (B / C) -> (A +- B) / C.  */
3613   if (mul0 == mul1
3614       && operand_equal_p (TREE_OPERAND (arg0, 1),
3615                        TREE_OPERAND (arg1, 1), 0))
3616     return fold_build2_loc (loc, mul0 ? MULT_EXPR : RDIV_EXPR, type,
3617                         fold_build2_loc (loc, code, type,
3618                                      TREE_OPERAND (arg0, 0),
3619                                      TREE_OPERAND (arg1, 0)),
3620                         TREE_OPERAND (arg0, 1));
3621
3622   /* (A / C1) +- (A / C2) -> A * (1 / C1 +- 1 / C2).  */
3623   if (operand_equal_p (TREE_OPERAND (arg0, 0),
3624                        TREE_OPERAND (arg1, 0), 0)
3625       && TREE_CODE (TREE_OPERAND (arg0, 1)) == REAL_CST
3626       && TREE_CODE (TREE_OPERAND (arg1, 1)) == REAL_CST)
3627     {
3628       REAL_VALUE_TYPE r0, r1;
3629       r0 = TREE_REAL_CST (TREE_OPERAND (arg0, 1));
3630       r1 = TREE_REAL_CST (TREE_OPERAND (arg1, 1));
3631       if (!mul0)
3632         real_arithmetic (&r0, RDIV_EXPR, &dconst1, &r0);
3633       if (!mul1)
3634         real_arithmetic (&r1, RDIV_EXPR, &dconst1, &r1);
3635       real_arithmetic (&r0, code, &r0, &r1);
3636       return fold_build2_loc (loc, MULT_EXPR, type,
3637                           TREE_OPERAND (arg0, 0),
3638                           build_real (type, r0));
3639     }
3640
3641   return NULL_TREE;
3642 }
3643 \f
3644 /* Return a BIT_FIELD_REF of type TYPE to refer to BITSIZE bits of INNER
3645    starting at BITPOS.  The field is unsigned if UNSIGNEDP is nonzero.  */
3646
3647 static tree
3648 make_bit_field_ref (location_t loc, tree inner, tree type,
3649                     HOST_WIDE_INT bitsize, HOST_WIDE_INT bitpos, int unsignedp)
3650 {
3651   tree result, bftype;
3652
3653   if (bitpos == 0)
3654     {
3655       tree size = TYPE_SIZE (TREE_TYPE (inner));
3656       if ((INTEGRAL_TYPE_P (TREE_TYPE (inner))
3657            || POINTER_TYPE_P (TREE_TYPE (inner)))
3658           && tree_fits_shwi_p (size)
3659           && tree_to_shwi (size) == bitsize)
3660         return fold_convert_loc (loc, type, inner);
3661     }
3662
3663   bftype = type;
3664   if (TYPE_PRECISION (bftype) != bitsize
3665       || TYPE_UNSIGNED (bftype) == !unsignedp)
3666     bftype = build_nonstandard_integer_type (bitsize, 0);
3667
3668   result = build3_loc (loc, BIT_FIELD_REF, bftype, inner,
3669                        size_int (bitsize), bitsize_int (bitpos));
3670
3671   if (bftype != type)
3672     result = fold_convert_loc (loc, type, result);
3673
3674   return result;
3675 }
3676
3677 /* Optimize a bit-field compare.
3678
3679    There are two cases:  First is a compare against a constant and the
3680    second is a comparison of two items where the fields are at the same
3681    bit position relative to the start of a chunk (byte, halfword, word)
3682    large enough to contain it.  In these cases we can avoid the shift
3683    implicit in bitfield extractions.
3684
3685    For constants, we emit a compare of the shifted constant with the
3686    BIT_AND_EXPR of a mask and a byte, halfword, or word of the operand being
3687    compared.  For two fields at the same position, we do the ANDs with the
3688    similar mask and compare the result of the ANDs.
3689
3690    CODE is the comparison code, known to be either NE_EXPR or EQ_EXPR.
3691    COMPARE_TYPE is the type of the comparison, and LHS and RHS
3692    are the left and right operands of the comparison, respectively.
3693
3694    If the optimization described above can be done, we return the resulting
3695    tree.  Otherwise we return zero.  */
3696
3697 static tree
3698 optimize_bit_field_compare (location_t loc, enum tree_code code,
3699                             tree compare_type, tree lhs, tree rhs)
3700 {
3701   HOST_WIDE_INT lbitpos, lbitsize, rbitpos, rbitsize, nbitpos, nbitsize;
3702   tree type = TREE_TYPE (lhs);
3703   tree unsigned_type;
3704   int const_p = TREE_CODE (rhs) == INTEGER_CST;
3705   machine_mode lmode, rmode, nmode;
3706   int lunsignedp, runsignedp;
3707   int lvolatilep = 0, rvolatilep = 0;
3708   tree linner, rinner = NULL_TREE;
3709   tree mask;
3710   tree offset;
3711
3712   /* Get all the information about the extractions being done.  If the bit size
3713      if the same as the size of the underlying object, we aren't doing an
3714      extraction at all and so can do nothing.  We also don't want to
3715      do anything if the inner expression is a PLACEHOLDER_EXPR since we
3716      then will no longer be able to replace it.  */
3717   linner = get_inner_reference (lhs, &lbitsize, &lbitpos, &offset, &lmode,
3718                                 &lunsignedp, &lvolatilep, false);
3719   if (linner == lhs || lbitsize == GET_MODE_BITSIZE (lmode) || lbitsize < 0
3720       || offset != 0 || TREE_CODE (linner) == PLACEHOLDER_EXPR || lvolatilep)
3721     return 0;
3722
3723  if (!const_p)
3724    {
3725      /* If this is not a constant, we can only do something if bit positions,
3726         sizes, and signedness are the same.  */
3727      rinner = get_inner_reference (rhs, &rbitsize, &rbitpos, &offset, &rmode,
3728                                    &runsignedp, &rvolatilep, false);
3729
3730      if (rinner == rhs || lbitpos != rbitpos || lbitsize != rbitsize
3731          || lunsignedp != runsignedp || offset != 0
3732          || TREE_CODE (rinner) == PLACEHOLDER_EXPR || rvolatilep)
3733        return 0;
3734    }
3735
3736   /* See if we can find a mode to refer to this field.  We should be able to,
3737      but fail if we can't.  */
3738   nmode = get_best_mode (lbitsize, lbitpos, 0, 0,
3739                          const_p ? TYPE_ALIGN (TREE_TYPE (linner))
3740                          : MIN (TYPE_ALIGN (TREE_TYPE (linner)),
3741                                 TYPE_ALIGN (TREE_TYPE (rinner))),
3742                          word_mode, false);
3743   if (nmode == VOIDmode)
3744     return 0;
3745
3746   /* Set signed and unsigned types of the precision of this mode for the
3747      shifts below.  */
3748   unsigned_type = lang_hooks.types.type_for_mode (nmode, 1);
3749
3750   /* Compute the bit position and size for the new reference and our offset
3751      within it. If the new reference is the same size as the original, we
3752      won't optimize anything, so return zero.  */
3753   nbitsize = GET_MODE_BITSIZE (nmode);
3754   nbitpos = lbitpos & ~ (nbitsize - 1);
3755   lbitpos -= nbitpos;
3756   if (nbitsize == lbitsize)
3757     return 0;
3758
3759   if (BYTES_BIG_ENDIAN)
3760     lbitpos = nbitsize - lbitsize - lbitpos;
3761
3762   /* Make the mask to be used against the extracted field.  */
3763   mask = build_int_cst_type (unsigned_type, -1);
3764   mask = const_binop (LSHIFT_EXPR, mask, size_int (nbitsize - lbitsize));
3765   mask = const_binop (RSHIFT_EXPR, mask,
3766                       size_int (nbitsize - lbitsize - lbitpos));
3767
3768   if (! const_p)
3769     /* If not comparing with constant, just rework the comparison
3770        and return.  */
3771     return fold_build2_loc (loc, code, compare_type,
3772                         fold_build2_loc (loc, BIT_AND_EXPR, unsigned_type,
3773                                      make_bit_field_ref (loc, linner,
3774                                                          unsigned_type,
3775                                                          nbitsize, nbitpos,
3776                                                          1),
3777                                      mask),
3778                         fold_build2_loc (loc, BIT_AND_EXPR, unsigned_type,
3779                                      make_bit_field_ref (loc, rinner,
3780                                                          unsigned_type,
3781                                                          nbitsize, nbitpos,
3782                                                          1),
3783                                      mask));
3784
3785   /* Otherwise, we are handling the constant case. See if the constant is too
3786      big for the field.  Warn and return a tree of for 0 (false) if so.  We do
3787      this not only for its own sake, but to avoid having to test for this
3788      error case below.  If we didn't, we might generate wrong code.
3789
3790      For unsigned fields, the constant shifted right by the field length should
3791      be all zero.  For signed fields, the high-order bits should agree with
3792      the sign bit.  */
3793
3794   if (lunsignedp)
3795     {
3796       if (wi::lrshift (rhs, lbitsize) != 0)
3797         {
3798           warning (0, "comparison is always %d due to width of bit-field",
3799                    code == NE_EXPR);
3800           return constant_boolean_node (code == NE_EXPR, compare_type);
3801         }
3802     }
3803   else
3804     {
3805       wide_int tem = wi::arshift (rhs, lbitsize - 1);
3806       if (tem != 0 && tem != -1)
3807         {
3808           warning (0, "comparison is always %d due to width of bit-field",
3809                    code == NE_EXPR);
3810           return constant_boolean_node (code == NE_EXPR, compare_type);
3811         }
3812     }
3813
3814   /* Single-bit compares should always be against zero.  */
3815   if (lbitsize == 1 && ! integer_zerop (rhs))
3816     {
3817       code = code == EQ_EXPR ? NE_EXPR : EQ_EXPR;
3818       rhs = build_int_cst (type, 0);
3819     }
3820
3821   /* Make a new bitfield reference, shift the constant over the
3822      appropriate number of bits and mask it with the computed mask
3823      (in case this was a signed field).  If we changed it, make a new one.  */
3824   lhs = make_bit_field_ref (loc, linner, unsigned_type, nbitsize, nbitpos, 1);
3825
3826   rhs = const_binop (BIT_AND_EXPR,
3827                      const_binop (LSHIFT_EXPR,
3828                                   fold_convert_loc (loc, unsigned_type, rhs),
3829                                   size_int (lbitpos)),
3830                      mask);
3831
3832   lhs = build2_loc (loc, code, compare_type,
3833                     build2 (BIT_AND_EXPR, unsigned_type, lhs, mask), rhs);
3834   return lhs;
3835 }
3836 \f
3837 /* Subroutine for fold_truth_andor_1: decode a field reference.
3838
3839    If EXP is a comparison reference, we return the innermost reference.
3840
3841    *PBITSIZE is set to the number of bits in the reference, *PBITPOS is
3842    set to the starting bit number.
3843
3844    If the innermost field can be completely contained in a mode-sized
3845    unit, *PMODE is set to that mode.  Otherwise, it is set to VOIDmode.
3846
3847    *PVOLATILEP is set to 1 if the any expression encountered is volatile;
3848    otherwise it is not changed.
3849
3850    *PUNSIGNEDP is set to the signedness of the field.
3851
3852    *PMASK is set to the mask used.  This is either contained in a
3853    BIT_AND_EXPR or derived from the width of the field.
3854
3855    *PAND_MASK is set to the mask found in a BIT_AND_EXPR, if any.
3856
3857    Return 0 if this is not a component reference or is one that we can't
3858    do anything with.  */
3859
3860 static tree
3861 decode_field_reference (location_t loc, tree exp, HOST_WIDE_INT *pbitsize,
3862                         HOST_WIDE_INT *pbitpos, machine_mode *pmode,
3863                         int *punsignedp, int *pvolatilep,
3864                         tree *pmask, tree *pand_mask)
3865 {
3866   tree outer_type = 0;
3867   tree and_mask = 0;
3868   tree mask, inner, offset;
3869   tree unsigned_type;
3870   unsigned int precision;
3871
3872   /* All the optimizations using this function assume integer fields.
3873      There are problems with FP fields since the type_for_size call
3874      below can fail for, e.g., XFmode.  */
3875   if (! INTEGRAL_TYPE_P (TREE_TYPE (exp)))
3876     return 0;
3877
3878   /* We are interested in the bare arrangement of bits, so strip everything
3879      that doesn't affect the machine mode.  However, record the type of the
3880      outermost expression if it may matter below.  */
3881   if (CONVERT_EXPR_P (exp)
3882       || TREE_CODE (exp) == NON_LVALUE_EXPR)
3883     outer_type = TREE_TYPE (exp);
3884   STRIP_NOPS (exp);
3885
3886   if (TREE_CODE (exp) == BIT_AND_EXPR)
3887     {
3888       and_mask = TREE_OPERAND (exp, 1);
3889       exp = TREE_OPERAND (exp, 0);
3890       STRIP_NOPS (exp); STRIP_NOPS (and_mask);
3891       if (TREE_CODE (and_mask) != INTEGER_CST)
3892         return 0;
3893     }
3894
3895   inner = get_inner_reference (exp, pbitsize, pbitpos, &offset, pmode,
3896                                punsignedp, pvolatilep, false);
3897   if ((inner == exp && and_mask == 0)
3898       || *pbitsize < 0 || offset != 0
3899       || TREE_CODE (inner) == PLACEHOLDER_EXPR)
3900     return 0;
3901
3902   /* If the number of bits in the reference is the same as the bitsize of
3903      the outer type, then the outer type gives the signedness. Otherwise
3904      (in case of a small bitfield) the signedness is unchanged.  */
3905   if (outer_type && *pbitsize == TYPE_PRECISION (outer_type))
3906     *punsignedp = TYPE_UNSIGNED (outer_type);
3907
3908   /* Compute the mask to access the bitfield.  */
3909   unsigned_type = lang_hooks.types.type_for_size (*pbitsize, 1);
3910   precision = TYPE_PRECISION (unsigned_type);
3911
3912   mask = build_int_cst_type (unsigned_type, -1);
3913
3914   mask = const_binop (LSHIFT_EXPR, mask, size_int (precision - *pbitsize));
3915   mask = const_binop (RSHIFT_EXPR, mask, size_int (precision - *pbitsize));
3916
3917   /* Merge it with the mask we found in the BIT_AND_EXPR, if any.  */
3918   if (and_mask != 0)
3919     mask = fold_build2_loc (loc, BIT_AND_EXPR, unsigned_type,
3920                         fold_convert_loc (loc, unsigned_type, and_mask), mask);
3921
3922   *pmask = mask;
3923   *pand_mask = and_mask;
3924   return inner;
3925 }
3926
3927 /* Return nonzero if MASK represents a mask of SIZE ones in the low-order
3928    bit positions and MASK is SIGNED.  */
3929
3930 static int
3931 all_ones_mask_p (const_tree mask, unsigned int size)
3932 {
3933   tree type = TREE_TYPE (mask);
3934   unsigned int precision = TYPE_PRECISION (type);
3935
3936   /* If this function returns true when the type of the mask is
3937      UNSIGNED, then there will be errors.  In particular see
3938      gcc.c-torture/execute/990326-1.c.  There does not appear to be
3939      any documentation paper trail as to why this is so.  But the pre
3940      wide-int worked with that restriction and it has been preserved
3941      here.  */
3942   if (size > precision || TYPE_SIGN (type) == UNSIGNED)
3943     return false;
3944
3945   return wi::mask (size, false, precision) == mask;
3946 }
3947
3948 /* Subroutine for fold: determine if VAL is the INTEGER_CONST that
3949    represents the sign bit of EXP's type.  If EXP represents a sign
3950    or zero extension, also test VAL against the unextended type.
3951    The return value is the (sub)expression whose sign bit is VAL,
3952    or NULL_TREE otherwise.  */
3953
3954 tree
3955 sign_bit_p (tree exp, const_tree val)
3956 {
3957   int width;
3958   tree t;
3959
3960   /* Tree EXP must have an integral type.  */
3961   t = TREE_TYPE (exp);
3962   if (! INTEGRAL_TYPE_P (t))
3963     return NULL_TREE;
3964
3965   /* Tree VAL must be an integer constant.  */
3966   if (TREE_CODE (val) != INTEGER_CST
3967       || TREE_OVERFLOW (val))
3968     return NULL_TREE;
3969
3970   width = TYPE_PRECISION (t);
3971   if (wi::only_sign_bit_p (val, width))
3972     return exp;
3973
3974   /* Handle extension from a narrower type.  */
3975   if (TREE_CODE (exp) == NOP_EXPR
3976       && TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (exp, 0))) < width)
3977     return sign_bit_p (TREE_OPERAND (exp, 0), val);
3978
3979   return NULL_TREE;
3980 }
3981
3982 /* Subroutine for fold_truth_andor_1: determine if an operand is simple enough
3983    to be evaluated unconditionally.  */
3984
3985 static int
3986 simple_operand_p (const_tree exp)
3987 {
3988   /* Strip any conversions that don't change the machine mode.  */
3989   STRIP_NOPS (exp);
3990
3991   return (CONSTANT_CLASS_P (exp)
3992           || TREE_CODE (exp) == SSA_NAME
3993           || (DECL_P (exp)
3994               && ! TREE_ADDRESSABLE (exp)
3995               && ! TREE_THIS_VOLATILE (exp)
3996               && ! DECL_NONLOCAL (exp)
3997               /* Don't regard global variables as simple.  They may be
3998                  allocated in ways unknown to the compiler (shared memory,
3999                  #pragma weak, etc).  */
4000               && ! TREE_PUBLIC (exp)
4001               && ! DECL_EXTERNAL (exp)
4002               /* Weakrefs are not safe to be read, since they can be NULL.
4003                  They are !TREE_PUBLIC && !DECL_EXTERNAL but still
4004                  have DECL_WEAK flag set.  */
4005               && (! VAR_OR_FUNCTION_DECL_P (exp) || ! DECL_WEAK (exp))
4006               /* Loading a static variable is unduly expensive, but global
4007                  registers aren't expensive.  */
4008               && (! TREE_STATIC (exp) || DECL_REGISTER (exp))));
4009 }
4010
4011 /* Subroutine for fold_truth_andor: determine if an operand is simple enough
4012    to be evaluated unconditionally.
4013    I addition to simple_operand_p, we assume that comparisons, conversions,
4014    and logic-not operations are simple, if their operands are simple, too.  */
4015
4016 static bool
4017 simple_operand_p_2 (tree exp)
4018 {
4019   enum tree_code code;
4020
4021   if (TREE_SIDE_EFFECTS (exp)
4022       || tree_could_trap_p (exp))
4023     return false;
4024
4025   while (CONVERT_EXPR_P (exp))
4026     exp = TREE_OPERAND (exp, 0);
4027
4028   code = TREE_CODE (exp);
4029
4030   if (TREE_CODE_CLASS (code) == tcc_comparison)
4031     return (simple_operand_p (TREE_OPERAND (exp, 0))
4032             && simple_operand_p (TREE_OPERAND (exp, 1)));
4033
4034   if (code == TRUTH_NOT_EXPR)
4035       return simple_operand_p_2 (TREE_OPERAND (exp, 0));
4036
4037   return simple_operand_p (exp);
4038 }
4039
4040 \f
4041 /* The following functions are subroutines to fold_range_test and allow it to
4042    try to change a logical combination of comparisons into a range test.
4043
4044    For example, both
4045         X == 2 || X == 3 || X == 4 || X == 5
4046    and
4047         X >= 2 && X <= 5
4048    are converted to
4049         (unsigned) (X - 2) <= 3
4050
4051    We describe each set of comparisons as being either inside or outside
4052    a range, using a variable named like IN_P, and then describe the
4053    range with a lower and upper bound.  If one of the bounds is omitted,
4054    it represents either the highest or lowest value of the type.
4055
4056    In the comments below, we represent a range by two numbers in brackets
4057    preceded by a "+" to designate being inside that range, or a "-" to
4058    designate being outside that range, so the condition can be inverted by
4059    flipping the prefix.  An omitted bound is represented by a "-".  For
4060    example, "- [-, 10]" means being outside the range starting at the lowest
4061    possible value and ending at 10, in other words, being greater than 10.
4062    The range "+ [-, -]" is always true and hence the range "- [-, -]" is
4063    always false.
4064
4065    We set up things so that the missing bounds are handled in a consistent
4066    manner so neither a missing bound nor "true" and "false" need to be
4067    handled using a special case.  */
4068
4069 /* Return the result of applying CODE to ARG0 and ARG1, but handle the case
4070    of ARG0 and/or ARG1 being omitted, meaning an unlimited range. UPPER0_P
4071    and UPPER1_P are nonzero if the respective argument is an upper bound
4072    and zero for a lower.  TYPE, if nonzero, is the type of the result; it
4073    must be specified for a comparison.  ARG1 will be converted to ARG0's
4074    type if both are specified.  */
4075
4076 static tree
4077 range_binop (enum tree_code code, tree type, tree arg0, int upper0_p,
4078              tree arg1, int upper1_p)
4079 {
4080   tree tem;
4081   int result;
4082   int sgn0, sgn1;
4083
4084   /* If neither arg represents infinity, do the normal operation.
4085      Else, if not a comparison, return infinity.  Else handle the special
4086      comparison rules. Note that most of the cases below won't occur, but
4087      are handled for consistency.  */
4088
4089   if (arg0 != 0 && arg1 != 0)
4090     {
4091       tem = fold_build2 (code, type != 0 ? type : TREE_TYPE (arg0),
4092                          arg0, fold_convert (TREE_TYPE (arg0), arg1));
4093       STRIP_NOPS (tem);
4094       return TREE_CODE (tem) == INTEGER_CST ? tem : 0;
4095     }
4096
4097   if (TREE_CODE_CLASS (code) != tcc_comparison)
4098     return 0;
4099
4100   /* Set SGN[01] to -1 if ARG[01] is a lower bound, 1 for upper, and 0
4101      for neither.  In real maths, we cannot assume open ended ranges are
4102      the same. But, this is computer arithmetic, where numbers are finite.
4103      We can therefore make the transformation of any unbounded range with
4104      the value Z, Z being greater than any representable number. This permits
4105      us to treat unbounded ranges as equal.  */
4106   sgn0 = arg0 != 0 ? 0 : (upper0_p ? 1 : -1);
4107   sgn1 = arg1 != 0 ? 0 : (upper1_p ? 1 : -1);
4108   switch (code)
4109     {
4110     case EQ_EXPR:
4111       result = sgn0 == sgn1;
4112       break;
4113     case NE_EXPR:
4114       result = sgn0 != sgn1;
4115       break;
4116     case LT_EXPR:
4117       result = sgn0 < sgn1;
4118       break;
4119     case LE_EXPR:
4120       result = sgn0 <= sgn1;
4121       break;
4122     case GT_EXPR:
4123       result = sgn0 > sgn1;
4124       break;
4125     case GE_EXPR:
4126       result = sgn0 >= sgn1;
4127       break;
4128     default:
4129       gcc_unreachable ();
4130     }
4131
4132   return constant_boolean_node (result, type);
4133 }
4134 \f
4135 /* Helper routine for make_range.  Perform one step for it, return
4136    new expression if the loop should continue or NULL_TREE if it should
4137    stop.  */
4138
4139 tree
4140 make_range_step (location_t loc, enum tree_code code, tree arg0, tree arg1,
4141                  tree exp_type, tree *p_low, tree *p_high, int *p_in_p,
4142                  bool *strict_overflow_p)
4143 {
4144   tree arg0_type = TREE_TYPE (arg0);
4145   tree n_low, n_high, low = *p_low, high = *p_high;
4146   int in_p = *p_in_p, n_in_p;
4147
4148   switch (code)
4149     {
4150     case TRUTH_NOT_EXPR:
4151       /* We can only do something if the range is testing for zero.  */
4152       if (low == NULL_TREE || high == NULL_TREE
4153           || ! integer_zerop (low) || ! integer_zerop (high))
4154         return NULL_TREE;
4155       *p_in_p = ! in_p;
4156       return arg0;
4157
4158     case EQ_EXPR: case NE_EXPR:
4159     case LT_EXPR: case LE_EXPR: case GE_EXPR: case GT_EXPR:
4160       /* We can only do something if the range is testing for zero
4161          and if the second operand is an integer constant.  Note that
4162          saying something is "in" the range we make is done by
4163          complementing IN_P since it will set in the initial case of
4164          being not equal to zero; "out" is leaving it alone.  */
4165       if (low == NULL_TREE || high == NULL_TREE
4166           || ! integer_zerop (low) || ! integer_zerop (high)
4167           || TREE_CODE (arg1) != INTEGER_CST)
4168         return NULL_TREE;
4169
4170       switch (code)
4171         {
4172         case NE_EXPR:  /* - [c, c]  */
4173           low = high = arg1;
4174           break;
4175         case EQ_EXPR:  /* + [c, c]  */
4176           in_p = ! in_p, low = high = arg1;
4177           break;
4178         case GT_EXPR:  /* - [-, c] */
4179           low = 0, high = arg1;
4180           break;
4181         case GE_EXPR:  /* + [c, -] */
4182           in_p = ! in_p, low = arg1, high = 0;
4183           break;
4184         case LT_EXPR:  /* - [c, -] */
4185           low = arg1, high = 0;
4186           break;
4187         case LE_EXPR:  /* + [-, c] */
4188           in_p = ! in_p, low = 0, high = arg1;
4189           break;
4190         default:
4191           gcc_unreachable ();
4192         }
4193
4194       /* If this is an unsigned comparison, we also know that EXP is
4195          greater than or equal to zero.  We base the range tests we make
4196          on that fact, so we record it here so we can parse existing
4197          range tests.  We test arg0_type since often the return type
4198          of, e.g. EQ_EXPR, is boolean.  */
4199       if (TYPE_UNSIGNED (arg0_type) && (low == 0 || high == 0))
4200         {
4201           if (! merge_ranges (&n_in_p, &n_low, &n_high,
4202                               in_p, low, high, 1,
4203                               build_int_cst (arg0_type, 0),
4204                               NULL_TREE))
4205             return NULL_TREE;
4206
4207           in_p = n_in_p, low = n_low, high = n_high;
4208
4209           /* If the high bound is missing, but we have a nonzero low
4210              bound, reverse the range so it goes from zero to the low bound
4211              minus 1.  */
4212           if (high == 0 && low && ! integer_zerop (low))
4213             {
4214               in_p = ! in_p;
4215               high = range_binop (MINUS_EXPR, NULL_TREE, low, 0,
4216                                   build_int_cst (TREE_TYPE (low), 1), 0);
4217               low = build_int_cst (arg0_type, 0);
4218             }
4219         }
4220
4221       *p_low = low;
4222       *p_high = high;
4223       *p_in_p = in_p;
4224       return arg0;
4225
4226     case NEGATE_EXPR:
4227       /* If flag_wrapv and ARG0_TYPE is signed, make sure
4228          low and high are non-NULL, then normalize will DTRT.  */
4229       if (!TYPE_UNSIGNED (arg0_type)
4230           && !TYPE_OVERFLOW_UNDEFINED (arg0_type))
4231         {
4232           if (low == NULL_TREE)
4233             low = TYPE_MIN_VALUE (arg0_type);
4234           if (high == NULL_TREE)
4235             high = TYPE_MAX_VALUE (arg0_type);
4236         }
4237
4238       /* (-x) IN [a,b] -> x in [-b, -a]  */
4239       n_low = range_binop (MINUS_EXPR, exp_type,
4240                            build_int_cst (exp_type, 0),
4241                            0, high, 1);
4242       n_high = range_binop (MINUS_EXPR, exp_type,
4243                             build_int_cst (exp_type, 0),
4244                             0, low, 0);
4245       if (n_high != 0 && TREE_OVERFLOW (n_high))
4246         return NULL_TREE;
4247       goto normalize;
4248
4249     case BIT_NOT_EXPR:
4250       /* ~ X -> -X - 1  */
4251       return build2_loc (loc, MINUS_EXPR, exp_type, negate_expr (arg0),
4252                          build_int_cst (exp_type, 1));
4253
4254     case PLUS_EXPR:
4255     case MINUS_EXPR:
4256       if (TREE_CODE (arg1) != INTEGER_CST)
4257         return NULL_TREE;
4258
4259       /* If flag_wrapv and ARG0_TYPE is signed, then we cannot
4260          move a constant to the other side.  */
4261       if (!TYPE_UNSIGNED (arg0_type)
4262           && !TYPE_OVERFLOW_UNDEFINED (arg0_type))
4263         return NULL_TREE;
4264
4265       /* If EXP is signed, any overflow in the computation is undefined,
4266          so we don't worry about it so long as our computations on
4267          the bounds don't overflow.  For unsigned, overflow is defined
4268          and this is exactly the right thing.  */
4269       n_low = range_binop (code == MINUS_EXPR ? PLUS_EXPR : MINUS_EXPR,
4270                            arg0_type, low, 0, arg1, 0);
4271       n_high = range_binop (code == MINUS_EXPR ? PLUS_EXPR : MINUS_EXPR,
4272                             arg0_type, high, 1, arg1, 0);
4273       if ((n_low != 0 && TREE_OVERFLOW (n_low))
4274           || (n_high != 0 && TREE_OVERFLOW (n_high)))
4275         return NULL_TREE;
4276
4277       if (TYPE_OVERFLOW_UNDEFINED (arg0_type))
4278         *strict_overflow_p = true;
4279
4280       normalize:
4281         /* Check for an unsigned range which has wrapped around the maximum
4282            value thus making n_high < n_low, and normalize it.  */
4283         if (n_low && n_high && tree_int_cst_lt (n_high, n_low))
4284           {
4285             low = range_binop (PLUS_EXPR, arg0_type, n_high, 0,
4286                                build_int_cst (TREE_TYPE (n_high), 1), 0);
4287             high = range_binop (MINUS_EXPR, arg0_type, n_low, 0,
4288                                 build_int_cst (TREE_TYPE (n_low), 1), 0);
4289
4290             /* If the range is of the form +/- [ x+1, x ], we won't
4291                be able to normalize it.  But then, it represents the
4292                whole range or the empty set, so make it
4293                +/- [ -, - ].  */
4294             if (tree_int_cst_equal (n_low, low)
4295                 && tree_int_cst_equal (n_high, high))
4296               low = high = 0;
4297             else
4298               in_p = ! in_p;
4299           }
4300         else
4301           low = n_low, high = n_high;
4302
4303         *p_low = low;
4304         *p_high = high;
4305         *p_in_p = in_p;
4306         return arg0;
4307
4308     CASE_CONVERT:
4309     case NON_LVALUE_EXPR:
4310       if (TYPE_PRECISION (arg0_type) > TYPE_PRECISION (exp_type))
4311         return NULL_TREE;
4312
4313       if (! INTEGRAL_TYPE_P (arg0_type)
4314           || (low != 0 && ! int_fits_type_p (low, arg0_type))
4315           || (high != 0 && ! int_fits_type_p (high, arg0_type)))
4316         return NULL_TREE;
4317
4318       n_low = low, n_high = high;
4319
4320       if (n_low != 0)
4321         n_low = fold_convert_loc (loc, arg0_type, n_low);
4322
4323       if (n_high != 0)
4324         n_high = fold_convert_loc (loc, arg0_type, n_high);
4325
4326       /* If we're converting arg0 from an unsigned type, to exp,
4327          a signed type,  we will be doing the comparison as unsigned.
4328          The tests above have already verified that LOW and HIGH
4329          are both positive.
4330
4331          So we have to ensure that we will handle large unsigned
4332          values the same way that the current signed bounds treat
4333          negative values.  */
4334
4335       if (!TYPE_UNSIGNED (exp_type) && TYPE_UNSIGNED (arg0_type))
4336         {
4337           tree high_positive;
4338           tree equiv_type;
4339           /* For fixed-point modes, we need to pass the saturating flag
4340              as the 2nd parameter.  */
4341           if (ALL_FIXED_POINT_MODE_P (TYPE_MODE (arg0_type)))
4342             equiv_type
4343               = lang_hooks.types.type_for_mode (TYPE_MODE (arg0_type),
4344                                                 TYPE_SATURATING (arg0_type));
4345           else
4346             equiv_type
4347               = lang_hooks.types.type_for_mode (TYPE_MODE (arg0_type), 1);
4348
4349           /* A range without an upper bound is, naturally, unbounded.
4350              Since convert would have cropped a very large value, use
4351              the max value for the destination type.  */
4352           high_positive
4353             = TYPE_MAX_VALUE (equiv_type) ? TYPE_MAX_VALUE (equiv_type)
4354               : TYPE_MAX_VALUE (arg0_type);
4355
4356           if (TYPE_PRECISION (exp_type) == TYPE_PRECISION (arg0_type))
4357             high_positive = fold_build2_loc (loc, RSHIFT_EXPR, arg0_type,
4358                                              fold_convert_loc (loc, arg0_type,
4359                                                                high_positive),
4360                                              build_int_cst (arg0_type, 1));
4361
4362           /* If the low bound is specified, "and" the range with the
4363              range for which the original unsigned value will be
4364              positive.  */
4365           if (low != 0)
4366             {
4367               if (! merge_ranges (&n_in_p, &n_low, &n_high, 1, n_low, n_high,
4368                                   1, fold_convert_loc (loc, arg0_type,
4369                                                        integer_zero_node),
4370                                   high_positive))
4371                 return NULL_TREE;
4372
4373               in_p = (n_in_p == in_p);
4374             }
4375           else
4376             {
4377               /* Otherwise, "or" the range with the range of the input
4378                  that will be interpreted as negative.  */
4379               if (! merge_ranges (&n_in_p, &n_low, &n_high, 0, n_low, n_high,
4380                                   1, fold_convert_loc (loc, arg0_type,
4381                                                        integer_zero_node),
4382                                   high_positive))
4383                 return NULL_TREE;
4384
4385               in_p = (in_p != n_in_p);
4386             }
4387         }
4388
4389       *p_low = n_low;
4390       *p_high = n_high;
4391       *p_in_p = in_p;
4392       return arg0;
4393
4394     default:
4395       return NULL_TREE;
4396     }
4397 }
4398
4399 /* Given EXP, a logical expression, set the range it is testing into
4400    variables denoted by PIN_P, PLOW, and PHIGH.  Return the expression
4401    actually being tested.  *PLOW and *PHIGH will be made of the same
4402    type as the returned expression.  If EXP is not a comparison, we
4403    will most likely not be returning a useful value and range.  Set
4404    *STRICT_OVERFLOW_P to true if the return value is only valid
4405    because signed overflow is undefined; otherwise, do not change
4406    *STRICT_OVERFLOW_P.  */
4407
4408 tree
4409 make_range (tree exp, int *pin_p, tree *plow, tree *phigh,
4410             bool *strict_overflow_p)
4411 {
4412   enum tree_code code;
4413   tree arg0, arg1 = NULL_TREE;
4414   tree exp_type, nexp;
4415   int in_p;
4416   tree low, high;
4417   location_t loc = EXPR_LOCATION (exp);
4418
4419   /* Start with simply saying "EXP != 0" and then look at the code of EXP
4420      and see if we can refine the range.  Some of the cases below may not
4421      happen, but it doesn't seem worth worrying about this.  We "continue"
4422      the outer loop when we've changed something; otherwise we "break"
4423      the switch, which will "break" the while.  */
4424
4425   in_p = 0;
4426   low = high = build_int_cst (TREE_TYPE (exp), 0);
4427
4428   while (1)
4429     {
4430       code = TREE_CODE (exp);
4431       exp_type = TREE_TYPE (exp);
4432       arg0 = NULL_TREE;
4433
4434       if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code)))
4435         {
4436           if (TREE_OPERAND_LENGTH (exp) > 0)
4437             arg0 = TREE_OPERAND (exp, 0);
4438           if (TREE_CODE_CLASS (code) == tcc_binary
4439               || TREE_CODE_CLASS (code) == tcc_comparison
4440               || (TREE_CODE_CLASS (code) == tcc_expression
4441                   && TREE_OPERAND_LENGTH (exp) > 1))
4442             arg1 = TREE_OPERAND (exp, 1);
4443         }
4444       if (arg0 == NULL_TREE)
4445         break;
4446
4447       nexp = make_range_step (loc, code, arg0, arg1, exp_type, &low,
4448                               &high, &in_p, strict_overflow_p);
4449       if (nexp == NULL_TREE)
4450         break;
4451       exp = nexp;
4452     }
4453
4454   /* If EXP is a constant, we can evaluate whether this is true or false.  */
4455   if (TREE_CODE (exp) == INTEGER_CST)
4456     {
4457       in_p = in_p == (integer_onep (range_binop (GE_EXPR, integer_type_node,
4458                                                  exp, 0, low, 0))
4459                       && integer_onep (range_binop (LE_EXPR, integer_type_node,
4460                                                     exp, 1, high, 1)));
4461       low = high = 0;
4462       exp = 0;
4463     }
4464
4465   *pin_p = in_p, *plow = low, *phigh = high;
4466   return exp;
4467 }
4468 \f
4469 /* Given a range, LOW, HIGH, and IN_P, an expression, EXP, and a result
4470    type, TYPE, return an expression to test if EXP is in (or out of, depending
4471    on IN_P) the range.  Return 0 if the test couldn't be created.  */
4472
4473 tree
4474 build_range_check (location_t loc, tree type, tree exp, int in_p,
4475                    tree low, tree high)
4476 {
4477   tree etype = TREE_TYPE (exp), value;
4478
4479 #ifdef HAVE_canonicalize_funcptr_for_compare
4480   /* Disable this optimization for function pointer expressions
4481      on targets that require function pointer canonicalization.  */
4482   if (HAVE_canonicalize_funcptr_for_compare
4483       && TREE_CODE (etype) == POINTER_TYPE
4484       && TREE_CODE (TREE_TYPE (etype)) == FUNCTION_TYPE)
4485     return NULL_TREE;
4486 #endif
4487
4488   if (! in_p)
4489     {
4490       value = build_range_check (loc, type, exp, 1, low, high);
4491       if (value != 0)
4492         return invert_truthvalue_loc (loc, value);
4493
4494       return 0;
4495     }
4496
4497   if (low == 0 && high == 0)
4498     return omit_one_operand_loc (loc, type, build_int_cst (type, 1), exp);
4499
4500   if (low == 0)
4501     return fold_build2_loc (loc, LE_EXPR, type, exp,
4502                         fold_convert_loc (loc, etype, high));
4503
4504   if (high == 0)
4505     return fold_build2_loc (loc, GE_EXPR, type, exp,
4506                         fold_convert_loc (loc, etype, low));
4507
4508   if (operand_equal_p (low, high, 0))
4509     return fold_build2_loc (loc, EQ_EXPR, type, exp,
4510                         fold_convert_loc (loc, etype, low));
4511
4512   if (integer_zerop (low))
4513     {
4514       if (! TYPE_UNSIGNED (etype))
4515         {
4516           etype = unsigned_type_for (etype);
4517           high = fold_convert_loc (loc, etype, high);
4518           exp = fold_convert_loc (loc, etype, exp);
4519         }
4520       return build_range_check (loc, type, exp, 1, 0, high);
4521     }
4522
4523   /* Optimize (c>=1) && (c<=127) into (signed char)c > 0.  */
4524   if (integer_onep (low) && TREE_CODE (high) == INTEGER_CST)
4525     {
4526       int prec = TYPE_PRECISION (etype);
4527
4528       if (wi::mask (prec - 1, false, prec) == high)
4529         {
4530           if (TYPE_UNSIGNED (etype))
4531             {
4532               tree signed_etype = signed_type_for (etype);
4533               if (TYPE_PRECISION (signed_etype) != TYPE_PRECISION (etype))
4534                 etype
4535                   = build_nonstandard_integer_type (TYPE_PRECISION (etype), 0);
4536               else
4537                 etype = signed_etype;
4538               exp = fold_convert_loc (loc, etype, exp);
4539             }
4540           return fold_build2_loc (loc, GT_EXPR, type, exp,
4541                               build_int_cst (etype, 0));
4542         }
4543     }
4544
4545   /* Optimize (c>=low) && (c<=high) into (c-low>=0) && (c-low<=high-low).
4546      This requires wrap-around arithmetics for the type of the expression.
4547      First make sure that arithmetics in this type is valid, then make sure
4548      that it wraps around.  */
4549   if (TREE_CODE (etype) == ENUMERAL_TYPE || TREE_CODE (etype) == BOOLEAN_TYPE)
4550     etype = lang_hooks.types.type_for_size (TYPE_PRECISION (etype),
4551                                             TYPE_UNSIGNED (etype));
4552
4553   if (TREE_CODE (etype) == INTEGER_TYPE && !TYPE_OVERFLOW_WRAPS (etype))
4554     {
4555       tree utype, minv, maxv;
4556
4557       /* Check if (unsigned) INT_MAX + 1 == (unsigned) INT_MIN
4558          for the type in question, as we rely on this here.  */
4559       utype = unsigned_type_for (etype);
4560       maxv = fold_convert_loc (loc, utype, TYPE_MAX_VALUE (etype));
4561       maxv = range_binop (PLUS_EXPR, NULL_TREE, maxv, 1,
4562                           build_int_cst (TREE_TYPE (maxv), 1), 1);
4563       minv = fold_convert_loc (loc, utype, TYPE_MIN_VALUE (etype));
4564
4565       if (integer_zerop (range_binop (NE_EXPR, integer_type_node,
4566                                       minv, 1, maxv, 1)))
4567         etype = utype;
4568       else
4569         return 0;
4570     }
4571
4572   high = fold_convert_loc (loc, etype, high);
4573   low = fold_convert_loc (loc, etype, low);
4574   exp = fold_convert_loc (loc, etype, exp);
4575
4576   value = const_binop (MINUS_EXPR, high, low);
4577
4578
4579   if (POINTER_TYPE_P (etype))
4580     {
4581       if (value != 0 && !TREE_OVERFLOW (value))
4582         {
4583           low = fold_build1_loc (loc, NEGATE_EXPR, TREE_TYPE (low), low);
4584           return build_range_check (loc, type,
4585                                     fold_build_pointer_plus_loc (loc, exp, low),
4586                                     1, build_int_cst (etype, 0), value);
4587         }
4588       return 0;
4589     }
4590
4591   if (value != 0 && !TREE_OVERFLOW (value))
4592     return build_range_check (loc, type,
4593                               fold_build2_loc (loc, MINUS_EXPR, etype, exp, low),
4594                               1, build_int_cst (etype, 0), value);
4595
4596   return 0;
4597 }
4598 \f
4599 /* Return the predecessor of VAL in its type, handling the infinite case.  */
4600
4601 static tree
4602 range_predecessor (tree val)
4603 {
4604   tree type = TREE_TYPE (val);
4605
4606   if (INTEGRAL_TYPE_P (type)
4607       && operand_equal_p (val, TYPE_MIN_VALUE (type), 0))
4608     return 0;
4609   else
4610     return range_binop (MINUS_EXPR, NULL_TREE, val, 0,
4611                         build_int_cst (TREE_TYPE (val), 1), 0);
4612 }
4613
4614 /* Return the successor of VAL in its type, handling the infinite case.  */
4615
4616 static tree
4617 range_successor (tree val)
4618 {
4619   tree type = TREE_TYPE (val);
4620
4621   if (INTEGRAL_TYPE_P (type)
4622       && operand_equal_p (val, TYPE_MAX_VALUE (type), 0))
4623     return 0;
4624   else
4625     return range_binop (PLUS_EXPR, NULL_TREE, val, 0,
4626                         build_int_cst (TREE_TYPE (val), 1), 0);
4627 }
4628
4629 /* Given two ranges, see if we can merge them into one.  Return 1 if we
4630    can, 0 if we can't.  Set the output range into the specified parameters.  */
4631
4632 bool
4633 merge_ranges (int *pin_p, tree *plow, tree *phigh, int in0_p, tree low0,
4634               tree high0, int in1_p, tree low1, tree high1)
4635 {
4636   int no_overlap;
4637   int subset;
4638   int temp;
4639   tree tem;
4640   int in_p;
4641   tree low, high;
4642   int lowequal = ((low0 == 0 && low1 == 0)
4643                   || integer_onep (range_binop (EQ_EXPR, integer_type_node,
4644                                                 low0, 0, low1, 0)));
4645   int highequal = ((high0 == 0 && high1 == 0)
4646                    || integer_onep (range_binop (EQ_EXPR, integer_type_node,
4647                                                  high0, 1, high1, 1)));
4648
4649   /* Make range 0 be the range that starts first, or ends last if they
4650      start at the same value.  Swap them if it isn't.  */
4651   if (integer_onep (range_binop (GT_EXPR, integer_type_node,
4652                                  low0, 0, low1, 0))
4653       || (lowequal
4654           && integer_onep (range_binop (GT_EXPR, integer_type_node,
4655                                         high1, 1, high0, 1))))
4656     {
4657       temp = in0_p, in0_p = in1_p, in1_p = temp;
4658       tem = low0, low0 = low1, low1 = tem;
4659       tem = high0, high0 = high1, high1 = tem;
4660     }
4661
4662   /* Now flag two cases, whether the ranges are disjoint or whether the
4663      second range is totally subsumed in the first.  Note that the tests
4664      below are simplified by the ones above.  */
4665   no_overlap = integer_onep (range_binop (LT_EXPR, integer_type_node,
4666                                           high0, 1, low1, 0));
4667   subset = integer_onep (range_binop (LE_EXPR, integer_type_node,
4668                                       high1, 1, high0, 1));
4669
4670   /* We now have four cases, depending on whether we are including or
4671      excluding the two ranges.  */
4672   if (in0_p && in1_p)
4673     {
4674       /* If they don't overlap, the result is false.  If the second range
4675          is a subset it is the result.  Otherwise, the range is from the start
4676          of the second to the end of the first.  */
4677       if (no_overlap)
4678         in_p = 0, low = high = 0;
4679       else if (subset)
4680         in_p = 1, low = low1, high = high1;
4681       else
4682         in_p = 1, low = low1, high = high0;
4683     }
4684
4685   else if (in0_p && ! in1_p)
4686     {
4687       /* If they don't overlap, the result is the first range.  If they are
4688          equal, the result is false.  If the second range is a subset of the
4689          first, and the ranges begin at the same place, we go from just after
4690          the end of the second range to the end of the first.  If the second
4691          range is not a subset of the first, or if it is a subset and both
4692          ranges end at the same place, the range starts at the start of the
4693          first range and ends just before the second range.
4694          Otherwise, we can't describe this as a single range.  */
4695       if (no_overlap)
4696         in_p = 1, low = low0, high = high0;
4697       else if (lowequal && highequal)
4698         in_p = 0, low = high = 0;
4699       else if (subset && lowequal)
4700         {
4701           low = range_successor (high1);
4702           high = high0;
4703           in_p = 1;
4704           if (low == 0)
4705             {
4706               /* We are in the weird situation where high0 > high1 but
4707                  high1 has no successor.  Punt.  */
4708               return 0;
4709             }
4710         }
4711       else if (! subset || highequal)
4712         {
4713           low = low0;
4714           high = range_predecessor (low1);
4715           in_p = 1;
4716           if (high == 0)
4717             {
4718               /* low0 < low1 but low1 has no predecessor.  Punt.  */
4719               return 0;
4720             }
4721         }
4722       else
4723         return 0;
4724     }
4725
4726   else if (! in0_p && in1_p)
4727     {
4728       /* If they don't overlap, the result is the second range.  If the second
4729          is a subset of the first, the result is false.  Otherwise,
4730          the range starts just after the first range and ends at the
4731          end of the second.  */
4732       if (no_overlap)
4733         in_p = 1, low = low1, high = high1;
4734       else if (subset || highequal)
4735         in_p = 0, low = high = 0;
4736       else
4737         {
4738           low = range_successor (high0);
4739           high = high1;
4740           in_p = 1;
4741           if (low == 0)
4742             {
4743               /* high1 > high0 but high0 has no successor.  Punt.  */
4744               return 0;
4745             }
4746         }
4747     }
4748
4749   else
4750     {
4751       /* The case where we are excluding both ranges.  Here the complex case
4752          is if they don't overlap.  In that case, the only time we have a
4753          range is if they are adjacent.  If the second is a subset of the
4754          first, the result is the first.  Otherwise, the range to exclude
4755          starts at the beginning of the first range and ends at the end of the
4756          second.  */
4757       if (no_overlap)
4758         {
4759           if (integer_onep (range_binop (EQ_EXPR, integer_type_node,
4760                                          range_successor (high0),
4761                                          1, low1, 0)))
4762             in_p = 0, low = low0, high = high1;
4763           else
4764             {
4765               /* Canonicalize - [min, x] into - [-, x].  */
4766               if (low0 && TREE_CODE (low0) == INTEGER_CST)
4767                 switch (TREE_CODE (TREE_TYPE (low0)))
4768                   {
4769                   case ENUMERAL_TYPE:
4770                     if (TYPE_PRECISION (TREE_TYPE (low0))
4771                         != GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (low0))))
4772                       break;
4773                     /* FALLTHROUGH */
4774                   case INTEGER_TYPE:
4775                     if (tree_int_cst_equal (low0,
4776                                             TYPE_MIN_VALUE (TREE_TYPE (low0))))
4777                       low0 = 0;
4778                     break;
4779                   case POINTER_TYPE:
4780                     if (TYPE_UNSIGNED (TREE_TYPE (low0))
4781                         && integer_zerop (low0))
4782                       low0 = 0;
4783                     break;
4784                   default:
4785                     break;
4786                   }
4787
4788               /* Canonicalize - [x, max] into - [x, -].  */
4789               if (high1 && TREE_CODE (high1) == INTEGER_CST)
4790                 switch (TREE_CODE (TREE_TYPE (high1)))
4791                   {
4792                   case ENUMERAL_TYPE:
4793                     if (TYPE_PRECISION (TREE_TYPE (high1))
4794                         != GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (high1))))
4795                       break;
4796                     /* FALLTHROUGH */
4797                   case INTEGER_TYPE:
4798                     if (tree_int_cst_equal (high1,
4799                                             TYPE_MAX_VALUE (TREE_TYPE (high1))))
4800                       high1 = 0;
4801                     break;
4802                   case POINTER_TYPE:
4803                     if (TYPE_UNSIGNED (TREE_TYPE (high1))
4804                         && integer_zerop (range_binop (PLUS_EXPR, NULL_TREE,
4805                                                        high1, 1,
4806                                                        build_int_cst (TREE_TYPE (high1), 1),
4807                                                        1)))
4808                       high1 = 0;
4809                     break;
4810                   default:
4811                     break;
4812                   }
4813
4814               /* The ranges might be also adjacent between the maximum and
4815                  minimum values of the given type.  For
4816                  - [{min,-}, x] and - [y, {max,-}] ranges where x + 1 < y
4817                  return + [x + 1, y - 1].  */
4818               if (low0 == 0 && high1 == 0)
4819                 {
4820                   low = range_successor (high0);
4821                   high = range_predecessor (low1);
4822                   if (low == 0 || high == 0)
4823                     return 0;
4824
4825                   in_p = 1;
4826                 }
4827               else
4828                 return 0;
4829             }
4830         }
4831       else if (subset)
4832         in_p = 0, low = low0, high = high0;
4833       else
4834         in_p = 0, low = low0, high = high1;
4835     }
4836
4837   *pin_p = in_p, *plow = low, *phigh = high;
4838   return 1;
4839 }
4840 \f
4841
4842 /* Subroutine of fold, looking inside expressions of the form
4843    A op B ? A : C, where ARG0, ARG1 and ARG2 are the three operands
4844    of the COND_EXPR.  This function is being used also to optimize
4845    A op B ? C : A, by reversing the comparison first.
4846
4847    Return a folded expression whose code is not a COND_EXPR
4848    anymore, or NULL_TREE if no folding opportunity is found.  */
4849
4850 static tree
4851 fold_cond_expr_with_comparison (location_t loc, tree type,
4852                                 tree arg0, tree arg1, tree arg2)
4853 {
4854   enum tree_code comp_code = TREE_CODE (arg0);
4855   tree arg00 = TREE_OPERAND (arg0, 0);
4856   tree arg01 = TREE_OPERAND (arg0, 1);
4857   tree arg1_type = TREE_TYPE (arg1);
4858   tree tem;
4859
4860   STRIP_NOPS (arg1);
4861   STRIP_NOPS (arg2);
4862
4863   /* If we have A op 0 ? A : -A, consider applying the following
4864      transformations:
4865
4866      A == 0? A : -A    same as -A
4867      A != 0? A : -A    same as A
4868      A >= 0? A : -A    same as abs (A)
4869      A > 0?  A : -A    same as abs (A)
4870      A <= 0? A : -A    same as -abs (A)
4871      A < 0?  A : -A    same as -abs (A)
4872
4873      None of these transformations work for modes with signed
4874      zeros.  If A is +/-0, the first two transformations will
4875      change the sign of the result (from +0 to -0, or vice
4876      versa).  The last four will fix the sign of the result,
4877      even though the original expressions could be positive or
4878      negative, depending on the sign of A.
4879
4880      Note that all these transformations are correct if A is
4881      NaN, since the two alternatives (A and -A) are also NaNs.  */
4882   if (!HONOR_SIGNED_ZEROS (element_mode (type))
4883       && (FLOAT_TYPE_P (TREE_TYPE (arg01))
4884           ? real_zerop (arg01)
4885           : integer_zerop (arg01))
4886       && ((TREE_CODE (arg2) == NEGATE_EXPR
4887            && operand_equal_p (TREE_OPERAND (arg2, 0), arg1, 0))
4888              /* In the case that A is of the form X-Y, '-A' (arg2) may
4889                 have already been folded to Y-X, check for that. */
4890           || (TREE_CODE (arg1) == MINUS_EXPR
4891               && TREE_CODE (arg2) == MINUS_EXPR
4892               && operand_equal_p (TREE_OPERAND (arg1, 0),
4893                                   TREE_OPERAND (arg2, 1), 0)
4894               && operand_equal_p (TREE_OPERAND (arg1, 1),
4895                                   TREE_OPERAND (arg2, 0), 0))))
4896     switch (comp_code)
4897       {
4898       case EQ_EXPR:
4899       case UNEQ_EXPR:
4900         tem = fold_convert_loc (loc, arg1_type, arg1);
4901         return pedantic_non_lvalue_loc (loc,
4902                                     fold_convert_loc (loc, type,
4903                                                   negate_expr (tem)));
4904       case NE_EXPR:
4905       case LTGT_EXPR:
4906         return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
4907       case UNGE_EXPR:
4908       case UNGT_EXPR:
4909         if (flag_trapping_math)
4910           break;
4911         /* Fall through.  */
4912       case GE_EXPR:
4913       case GT_EXPR:
4914         if (TYPE_UNSIGNED (TREE_TYPE (arg1)))
4915           arg1 = fold_convert_loc (loc, signed_type_for
4916                                (TREE_TYPE (arg1)), arg1);
4917         tem = fold_build1_loc (loc, ABS_EXPR, TREE_TYPE (arg1), arg1);
4918         return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, tem));
4919       case UNLE_EXPR:
4920       case UNLT_EXPR:
4921         if (flag_trapping_math)
4922           break;
4923       case LE_EXPR:
4924       case LT_EXPR:
4925         if (TYPE_UNSIGNED (TREE_TYPE (arg1)))
4926           arg1 = fold_convert_loc (loc, signed_type_for
4927                                (TREE_TYPE (arg1)), arg1);
4928         tem = fold_build1_loc (loc, ABS_EXPR, TREE_TYPE (arg1), arg1);
4929         return negate_expr (fold_convert_loc (loc, type, tem));
4930       default:
4931         gcc_assert (TREE_CODE_CLASS (comp_code) == tcc_comparison);
4932         break;
4933       }
4934
4935   /* A != 0 ? A : 0 is simply A, unless A is -0.  Likewise
4936      A == 0 ? A : 0 is always 0 unless A is -0.  Note that
4937      both transformations are correct when A is NaN: A != 0
4938      is then true, and A == 0 is false.  */
4939
4940   if (!HONOR_SIGNED_ZEROS (element_mode (type))
4941       && integer_zerop (arg01) && integer_zerop (arg2))
4942     {
4943       if (comp_code == NE_EXPR)
4944         return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
4945       else if (comp_code == EQ_EXPR)
4946         return build_zero_cst (type);
4947     }
4948
4949   /* Try some transformations of A op B ? A : B.
4950
4951      A == B? A : B    same as B
4952      A != B? A : B    same as A
4953      A >= B? A : B    same as max (A, B)
4954      A > B?  A : B    same as max (B, A)
4955      A <= B? A : B    same as min (A, B)
4956      A < B?  A : B    same as min (B, A)
4957
4958      As above, these transformations don't work in the presence
4959      of signed zeros.  For example, if A and B are zeros of
4960      opposite sign, the first two transformations will change
4961      the sign of the result.  In the last four, the original
4962      expressions give different results for (A=+0, B=-0) and
4963      (A=-0, B=+0), but the transformed expressions do not.
4964
4965      The first two transformations are correct if either A or B
4966      is a NaN.  In the first transformation, the condition will
4967      be false, and B will indeed be chosen.  In the case of the
4968      second transformation, the condition A != B will be true,
4969      and A will be chosen.
4970
4971      The conversions to max() and min() are not correct if B is
4972      a number and A is not.  The conditions in the original
4973      expressions will be false, so all four give B.  The min()
4974      and max() versions would give a NaN instead.  */
4975   if (!HONOR_SIGNED_ZEROS (element_mode (type))
4976       && operand_equal_for_comparison_p (arg01, arg2, arg00)
4977       /* Avoid these transformations if the COND_EXPR may be used
4978          as an lvalue in the C++ front-end.  PR c++/19199.  */
4979       && (in_gimple_form
4980           || VECTOR_TYPE_P (type)
4981           || (! lang_GNU_CXX ()
4982               && strcmp (lang_hooks.name, "GNU Objective-C++") != 0)
4983           || ! maybe_lvalue_p (arg1)
4984           || ! maybe_lvalue_p (arg2)))
4985     {
4986       tree comp_op0 = arg00;
4987       tree comp_op1 = arg01;
4988       tree comp_type = TREE_TYPE (comp_op0);
4989
4990       /* Avoid adding NOP_EXPRs in case this is an lvalue.  */
4991       if (TYPE_MAIN_VARIANT (comp_type) == TYPE_MAIN_VARIANT (type))
4992         {
4993           comp_type = type;
4994           comp_op0 = arg1;
4995           comp_op1 = arg2;
4996         }
4997
4998       switch (comp_code)
4999         {
5000         case EQ_EXPR:
5001           return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, arg2));
5002         case NE_EXPR:
5003           return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
5004         case LE_EXPR:
5005         case LT_EXPR:
5006         case UNLE_EXPR:
5007         case UNLT_EXPR:
5008           /* In C++ a ?: expression can be an lvalue, so put the
5009              operand which will be used if they are equal first
5010              so that we can convert this back to the
5011              corresponding COND_EXPR.  */
5012           if (!HONOR_NANS (arg1))
5013             {
5014               comp_op0 = fold_convert_loc (loc, comp_type, comp_op0);
5015               comp_op1 = fold_convert_loc (loc, comp_type, comp_op1);
5016               tem = (comp_code == LE_EXPR || comp_code == UNLE_EXPR)
5017                     ? fold_build2_loc (loc, MIN_EXPR, comp_type, comp_op0, comp_op1)
5018                     : fold_build2_loc (loc, MIN_EXPR, comp_type,
5019                                    comp_op1, comp_op0);
5020               return pedantic_non_lvalue_loc (loc,
5021                                           fold_convert_loc (loc, type, tem));
5022             }
5023           break;
5024         case GE_EXPR:
5025         case GT_EXPR:
5026         case UNGE_EXPR:
5027         case UNGT_EXPR:
5028           if (!HONOR_NANS (arg1))
5029             {
5030               comp_op0 = fold_convert_loc (loc, comp_type, comp_op0);
5031               comp_op1 = fold_convert_loc (loc, comp_type, comp_op1);
5032               tem = (comp_code == GE_EXPR || comp_code == UNGE_EXPR)
5033                     ? fold_build2_loc (loc, MAX_EXPR, comp_type, comp_op0, comp_op1)
5034                     : fold_build2_loc (loc, MAX_EXPR, comp_type,
5035                                    comp_op1, comp_op0);
5036               return pedantic_non_lvalue_loc (loc,
5037                                           fold_convert_loc (loc, type, tem));
5038             }
5039           break;
5040         case UNEQ_EXPR:
5041           if (!HONOR_NANS (arg1))
5042             return pedantic_non_lvalue_loc (loc,
5043                                         fold_convert_loc (loc, type, arg2));
5044           break;
5045         case LTGT_EXPR:
5046           if (!HONOR_NANS (arg1))
5047             return pedantic_non_lvalue_loc (loc,
5048                                         fold_convert_loc (loc, type, arg1));
5049           break;
5050         default:
5051           gcc_assert (TREE_CODE_CLASS (comp_code) == tcc_comparison);
5052           break;
5053         }
5054     }
5055
5056   /* If this is A op C1 ? A : C2 with C1 and C2 constant integers,
5057      we might still be able to simplify this.  For example,
5058      if C1 is one less or one more than C2, this might have started
5059      out as a MIN or MAX and been transformed by this function.
5060      Only good for INTEGER_TYPEs, because we need TYPE_MAX_VALUE.  */
5061
5062   if (INTEGRAL_TYPE_P (type)
5063       && TREE_CODE (arg01) == INTEGER_CST
5064       && TREE_CODE (arg2) == INTEGER_CST)
5065     switch (comp_code)
5066       {
5067       case EQ_EXPR:
5068         if (TREE_CODE (arg1) == INTEGER_CST)
5069           break;
5070         /* We can replace A with C1 in this case.  */
5071         arg1 = fold_convert_loc (loc, type, arg01);
5072         return fold_build3_loc (loc, COND_EXPR, type, arg0, arg1, arg2);
5073
5074       case LT_EXPR:
5075         /* If C1 is C2 + 1, this is min(A, C2), but use ARG00's type for
5076            MIN_EXPR, to preserve the signedness of the comparison.  */
5077         if (! operand_equal_p (arg2, TYPE_MAX_VALUE (type),
5078                                OEP_ONLY_CONST)
5079             && operand_equal_p (arg01,
5080                                 const_binop (PLUS_EXPR, arg2,
5081                                              build_int_cst (type, 1)),
5082                                 OEP_ONLY_CONST))
5083           {
5084             tem = fold_build2_loc (loc, MIN_EXPR, TREE_TYPE (arg00), arg00,
5085                                    fold_convert_loc (loc, TREE_TYPE (arg00),
5086                                                      arg2));
5087             return pedantic_non_lvalue_loc (loc,
5088                                             fold_convert_loc (loc, type, tem));
5089           }
5090         break;
5091
5092       case LE_EXPR:
5093         /* If C1 is C2 - 1, this is min(A, C2), with the same care
5094            as above.  */
5095         if (! operand_equal_p (arg2, TYPE_MIN_VALUE (type),
5096                                OEP_ONLY_CONST)
5097             && operand_equal_p (arg01,
5098                                 const_binop (MINUS_EXPR, arg2,
5099                                              build_int_cst (type, 1)),
5100                                 OEP_ONLY_CONST))
5101           {
5102             tem = fold_build2_loc (loc, MIN_EXPR, TREE_TYPE (arg00), arg00,
5103                                    fold_convert_loc (loc, TREE_TYPE (arg00),
5104                                                      arg2));
5105             return pedantic_non_lvalue_loc (loc,
5106                                             fold_convert_loc (loc, type, tem));
5107           }
5108         break;
5109
5110       case GT_EXPR:
5111         /* If C1 is C2 - 1, this is max(A, C2), but use ARG00's type for
5112            MAX_EXPR, to preserve the signedness of the comparison.  */
5113         if (! operand_equal_p (arg2, TYPE_MIN_VALUE (type),
5114                                OEP_ONLY_CONST)
5115             && operand_equal_p (arg01,
5116                                 const_binop (MINUS_EXPR, arg2,
5117                                              build_int_cst (type, 1)),
5118                                 OEP_ONLY_CONST))
5119           {
5120             tem = fold_build2_loc (loc, MAX_EXPR, TREE_TYPE (arg00), arg00,
5121                                    fold_convert_loc (loc, TREE_TYPE (arg00),
5122                                                      arg2));
5123             return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, tem));
5124           }
5125         break;
5126
5127       case GE_EXPR:
5128         /* If C1 is C2 + 1, this is max(A, C2), with the same care as above.  */
5129         if (! operand_equal_p (arg2, TYPE_MAX_VALUE (type),
5130                                OEP_ONLY_CONST)
5131             && operand_equal_p (arg01,
5132                                 const_binop (PLUS_EXPR, arg2,
5133                                              build_int_cst (type, 1)),
5134                                 OEP_ONLY_CONST))
5135           {
5136             tem = fold_build2_loc (loc, MAX_EXPR, TREE_TYPE (arg00), arg00,
5137                                    fold_convert_loc (loc, TREE_TYPE (arg00),
5138                                                      arg2));
5139             return pedantic_non_lvalue_loc (loc, fold_convert_loc (loc, type, tem));
5140           }
5141         break;
5142       case NE_EXPR:
5143         break;
5144       default:
5145         gcc_unreachable ();
5146       }
5147
5148   return NULL_TREE;
5149 }
5150
5151
5152 \f
5153 #ifndef LOGICAL_OP_NON_SHORT_CIRCUIT
5154 #define LOGICAL_OP_NON_SHORT_CIRCUIT \
5155   (BRANCH_COST (optimize_function_for_speed_p (cfun), \
5156                 false) >= 2)
5157 #endif
5158
5159 /* EXP is some logical combination of boolean tests.  See if we can
5160    merge it into some range test.  Return the new tree if so.  */
5161
5162 static tree
5163 fold_range_test (location_t loc, enum tree_code code, tree type,
5164                  tree op0, tree op1)
5165 {
5166   int or_op = (code == TRUTH_ORIF_EXPR
5167                || code == TRUTH_OR_EXPR);
5168   int in0_p, in1_p, in_p;
5169   tree low0, low1, low, high0, high1, high;
5170   bool strict_overflow_p = false;
5171   tree tem, lhs, rhs;
5172   const char * const warnmsg = G_("assuming signed overflow does not occur "
5173                                   "when simplifying range test");
5174
5175   if (!INTEGRAL_TYPE_P (type))
5176     return 0;
5177
5178   lhs = make_range (op0, &in0_p, &low0, &high0, &strict_overflow_p);
5179   rhs = make_range (op1, &in1_p, &low1, &high1, &strict_overflow_p);
5180
5181   /* If this is an OR operation, invert both sides; we will invert
5182      again at the end.  */
5183   if (or_op)
5184     in0_p = ! in0_p, in1_p = ! in1_p;
5185
5186   /* If both expressions are the same, if we can merge the ranges, and we
5187      can build the range test, return it or it inverted.  If one of the
5188      ranges is always true or always false, consider it to be the same
5189      expression as the other.  */
5190   if ((lhs == 0 || rhs == 0 || operand_equal_p (lhs, rhs, 0))
5191       && merge_ranges (&in_p, &low, &high, in0_p, low0, high0,
5192                        in1_p, low1, high1)
5193       && 0 != (tem = (build_range_check (loc, type,
5194                                          lhs != 0 ? lhs
5195                                          : rhs != 0 ? rhs : integer_zero_node,
5196                                          in_p, low, high))))
5197     {
5198       if (strict_overflow_p)
5199         fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_COMPARISON);
5200       return or_op ? invert_truthvalue_loc (loc, tem) : tem;
5201     }
5202
5203   /* On machines where the branch cost is expensive, if this is a
5204      short-circuited branch and the underlying object on both sides
5205      is the same, make a non-short-circuit operation.  */
5206   else if (LOGICAL_OP_NON_SHORT_CIRCUIT
5207            && lhs != 0 && rhs != 0
5208            && (code == TRUTH_ANDIF_EXPR
5209                || code == TRUTH_ORIF_EXPR)
5210            && operand_equal_p (lhs, rhs, 0))
5211     {
5212       /* If simple enough, just rewrite.  Otherwise, make a SAVE_EXPR
5213          unless we are at top level or LHS contains a PLACEHOLDER_EXPR, in
5214          which cases we can't do this.  */
5215       if (simple_operand_p (lhs))
5216         return build2_loc (loc, code == TRUTH_ANDIF_EXPR
5217                            ? TRUTH_AND_EXPR : TRUTH_OR_EXPR,
5218                            type, op0, op1);
5219
5220       else if (!lang_hooks.decls.global_bindings_p ()
5221                && !CONTAINS_PLACEHOLDER_P (lhs))
5222         {
5223           tree common = save_expr (lhs);
5224
5225           if (0 != (lhs = build_range_check (loc, type, common,
5226                                              or_op ? ! in0_p : in0_p,
5227                                              low0, high0))
5228               && (0 != (rhs = build_range_check (loc, type, common,
5229                                                  or_op ? ! in1_p : in1_p,
5230                                                  low1, high1))))
5231             {
5232               if (strict_overflow_p)
5233                 fold_overflow_warning (warnmsg,
5234                                        WARN_STRICT_OVERFLOW_COMPARISON);
5235               return build2_loc (loc, code == TRUTH_ANDIF_EXPR
5236                                  ? TRUTH_AND_EXPR : TRUTH_OR_EXPR,
5237                                  type, lhs, rhs);
5238             }
5239         }
5240     }
5241
5242   return 0;
5243 }
5244 \f
5245 /* Subroutine for fold_truth_andor_1: C is an INTEGER_CST interpreted as a P
5246    bit value.  Arrange things so the extra bits will be set to zero if and
5247    only if C is signed-extended to its full width.  If MASK is nonzero,
5248    it is an INTEGER_CST that should be AND'ed with the extra bits.  */
5249
5250 static tree
5251 unextend (tree c, int p, int unsignedp, tree mask)
5252 {
5253   tree type = TREE_TYPE (c);
5254   int modesize = GET_MODE_BITSIZE (TYPE_MODE (type));
5255   tree temp;
5256
5257   if (p == modesize || unsignedp)
5258     return c;
5259
5260   /* We work by getting just the sign bit into the low-order bit, then
5261      into the high-order bit, then sign-extend.  We then XOR that value
5262      with C.  */
5263   temp = build_int_cst (TREE_TYPE (c), wi::extract_uhwi (c, p - 1, 1));
5264
5265   /* We must use a signed type in order to get an arithmetic right shift.
5266      However, we must also avoid introducing accidental overflows, so that
5267      a subsequent call to integer_zerop will work.  Hence we must
5268      do the type conversion here.  At this point, the constant is either
5269      zero or one, and the conversion to a signed type can never overflow.
5270      We could get an overflow if this conversion is done anywhere else.  */
5271   if (TYPE_UNSIGNED (type))
5272     temp = fold_convert (signed_type_for (type), temp);
5273
5274   temp = const_binop (LSHIFT_EXPR, temp, size_int (modesize - 1));
5275   temp = const_binop (RSHIFT_EXPR, temp, size_int (modesize - p - 1));
5276   if (mask != 0)
5277     temp = const_binop (BIT_AND_EXPR, temp,
5278                         fold_convert (TREE_TYPE (c), mask));
5279   /* If necessary, convert the type back to match the type of C.  */
5280   if (TYPE_UNSIGNED (type))
5281     temp = fold_convert (type, temp);
5282
5283   return fold_convert (type, const_binop (BIT_XOR_EXPR, c, temp));
5284 }
5285 \f
5286 /* For an expression that has the form
5287      (A && B) || ~B
5288    or
5289      (A || B) && ~B,
5290    we can drop one of the inner expressions and simplify to
5291      A || ~B
5292    or
5293      A && ~B
5294    LOC is the location of the resulting expression.  OP is the inner 
5295    logical operation; the left-hand side in the examples above, while CMPOP
5296    is the right-hand side.  RHS_ONLY is used to prevent us from accidentally
5297    removing a condition that guards another, as in
5298      (A != NULL && A->...) || A == NULL
5299    which we must not transform.  If RHS_ONLY is true, only eliminate the
5300    right-most operand of the inner logical operation.  */
5301
5302 static tree
5303 merge_truthop_with_opposite_arm (location_t loc, tree op, tree cmpop,
5304                                  bool rhs_only)
5305 {
5306   tree type = TREE_TYPE (cmpop);
5307   enum tree_code code = TREE_CODE (cmpop);
5308   enum tree_code truthop_code = TREE_CODE (op);
5309   tree lhs = TREE_OPERAND (op, 0);
5310   tree rhs = TREE_OPERAND (op, 1);
5311   tree orig_lhs = lhs, orig_rhs = rhs;
5312   enum tree_code rhs_code = TREE_CODE (rhs);
5313   enum tree_code lhs_code = TREE_CODE (lhs);
5314   enum tree_code inv_code;
5315
5316   if (TREE_SIDE_EFFECTS (op) || TREE_SIDE_EFFECTS (cmpop))
5317     return NULL_TREE;
5318
5319   if (TREE_CODE_CLASS (code) != tcc_comparison)
5320     return NULL_TREE;
5321
5322   if (rhs_code == truthop_code)
5323     {
5324       tree newrhs = merge_truthop_with_opposite_arm (loc, rhs, cmpop, rhs_only);
5325       if (newrhs != NULL_TREE)
5326         {
5327           rhs = newrhs;
5328           rhs_code = TREE_CODE (rhs);
5329         }
5330     }
5331   if (lhs_code == truthop_code && !rhs_only)
5332     {
5333       tree newlhs = merge_truthop_with_opposite_arm (loc, lhs, cmpop, false);
5334       if (newlhs != NULL_TREE)
5335         {
5336           lhs = newlhs;
5337           lhs_code = TREE_CODE (lhs);
5338         }
5339     }
5340
5341   inv_code = invert_tree_comparison (code, HONOR_NANS (type));
5342   if (inv_code == rhs_code
5343       && operand_equal_p (TREE_OPERAND (rhs, 0), TREE_OPERAND (cmpop, 0), 0)
5344       && operand_equal_p (TREE_OPERAND (rhs, 1), TREE_OPERAND (cmpop, 1), 0))
5345     return lhs;
5346   if (!rhs_only && inv_code == lhs_code
5347       && operand_equal_p (TREE_OPERAND (lhs, 0), TREE_OPERAND (cmpop, 0), 0)
5348       && operand_equal_p (TREE_OPERAND (lhs, 1), TREE_OPERAND (cmpop, 1), 0))
5349     return rhs;
5350   if (rhs != orig_rhs || lhs != orig_lhs)
5351     return fold_build2_loc (loc, truthop_code, TREE_TYPE (cmpop),
5352                             lhs, rhs);
5353   return NULL_TREE;
5354 }
5355
5356 /* Find ways of folding logical expressions of LHS and RHS:
5357    Try to merge two comparisons to the same innermost item.
5358    Look for range tests like "ch >= '0' && ch <= '9'".
5359    Look for combinations of simple terms on machines with expensive branches
5360    and evaluate the RHS unconditionally.
5361
5362    For example, if we have p->a == 2 && p->b == 4 and we can make an
5363    object large enough to span both A and B, we can do this with a comparison
5364    against the object ANDed with the a mask.
5365
5366    If we have p->a == q->a && p->b == q->b, we may be able to use bit masking
5367    operations to do this with one comparison.
5368
5369    We check for both normal comparisons and the BIT_AND_EXPRs made this by
5370    function and the one above.
5371
5372    CODE is the logical operation being done.  It can be TRUTH_ANDIF_EXPR,
5373    TRUTH_AND_EXPR, TRUTH_ORIF_EXPR, or TRUTH_OR_EXPR.
5374
5375    TRUTH_TYPE is the type of the logical operand and LHS and RHS are its
5376    two operands.
5377
5378    We return the simplified tree or 0 if no optimization is possible.  */
5379
5380 static tree
5381 fold_truth_andor_1 (location_t loc, enum tree_code code, tree truth_type,
5382                     tree lhs, tree rhs)
5383 {
5384   /* If this is the "or" of two comparisons, we can do something if
5385      the comparisons are NE_EXPR.  If this is the "and", we can do something
5386      if the comparisons are EQ_EXPR.  I.e.,
5387         (a->b == 2 && a->c == 4) can become (a->new == NEW).
5388
5389      WANTED_CODE is this operation code.  For single bit fields, we can
5390      convert EQ_EXPR to NE_EXPR so we need not reject the "wrong"
5391      comparison for one-bit fields.  */
5392
5393   enum tree_code wanted_code;
5394   enum tree_code lcode, rcode;
5395   tree ll_arg, lr_arg, rl_arg, rr_arg;
5396   tree ll_inner, lr_inner, rl_inner, rr_inner;
5397   HOST_WIDE_INT ll_bitsize, ll_bitpos, lr_bitsize, lr_bitpos;
5398   HOST_WIDE_INT rl_bitsize, rl_bitpos, rr_bitsize, rr_bitpos;
5399   HOST_WIDE_INT xll_bitpos, xlr_bitpos, xrl_bitpos, xrr_bitpos;
5400   HOST_WIDE_INT lnbitsize, lnbitpos, rnbitsize, rnbitpos;
5401   int ll_unsignedp, lr_unsignedp, rl_unsignedp, rr_unsignedp;
5402   machine_mode ll_mode, lr_mode, rl_mode, rr_mode;
5403   machine_mode lnmode, rnmode;
5404   tree ll_mask, lr_mask, rl_mask, rr_mask;
5405   tree ll_and_mask, lr_and_mask, rl_and_mask, rr_and_mask;
5406   tree l_const, r_const;
5407   tree lntype, rntype, result;
5408   HOST_WIDE_INT first_bit, end_bit;
5409   int volatilep;
5410
5411   /* Start by getting the comparison codes.  Fail if anything is volatile.
5412      If one operand is a BIT_AND_EXPR with the constant one, treat it as if
5413      it were surrounded with a NE_EXPR.  */
5414
5415   if (TREE_SIDE_EFFECTS (lhs) || TREE_SIDE_EFFECTS (rhs))
5416     return 0;
5417
5418   lcode = TREE_CODE (lhs);
5419   rcode = TREE_CODE (rhs);
5420
5421   if (lcode == BIT_AND_EXPR && integer_onep (TREE_OPERAND (lhs, 1)))
5422     {
5423       lhs = build2 (NE_EXPR, truth_type, lhs,
5424                     build_int_cst (TREE_TYPE (lhs), 0));
5425       lcode = NE_EXPR;
5426     }
5427
5428   if (rcode == BIT_AND_EXPR && integer_onep (TREE_OPERAND (rhs, 1)))
5429     {
5430       rhs = build2 (NE_EXPR, truth_type, rhs,
5431                     build_int_cst (TREE_TYPE (rhs), 0));
5432       rcode = NE_EXPR;
5433     }
5434
5435   if (TREE_CODE_CLASS (lcode) != tcc_comparison
5436       || TREE_CODE_CLASS (rcode) != tcc_comparison)
5437     return 0;
5438
5439   ll_arg = TREE_OPERAND (lhs, 0);
5440   lr_arg = TREE_OPERAND (lhs, 1);
5441   rl_arg = TREE_OPERAND (rhs, 0);
5442   rr_arg = TREE_OPERAND (rhs, 1);
5443
5444   /* Simplify (x<y) && (x==y) into (x<=y) and related optimizations.  */
5445   if (simple_operand_p (ll_arg)
5446       && simple_operand_p (lr_arg))
5447     {
5448       if (operand_equal_p (ll_arg, rl_arg, 0)
5449           && operand_equal_p (lr_arg, rr_arg, 0))
5450         {
5451           result = combine_comparisons (loc, code, lcode, rcode,
5452                                         truth_type, ll_arg, lr_arg);
5453           if (result)
5454             return result;
5455         }
5456       else if (operand_equal_p (ll_arg, rr_arg, 0)
5457                && operand_equal_p (lr_arg, rl_arg, 0))
5458         {
5459           result = combine_comparisons (loc, code, lcode,
5460                                         swap_tree_comparison (rcode),
5461                                         truth_type, ll_arg, lr_arg);
5462           if (result)
5463             return result;
5464         }
5465     }
5466
5467   code = ((code == TRUTH_AND_EXPR || code == TRUTH_ANDIF_EXPR)
5468           ? TRUTH_AND_EXPR : TRUTH_OR_EXPR);
5469
5470   /* If the RHS can be evaluated unconditionally and its operands are
5471      simple, it wins to evaluate the RHS unconditionally on machines
5472      with expensive branches.  In this case, this isn't a comparison
5473      that can be merged.  */
5474
5475   if (BRANCH_COST (optimize_function_for_speed_p (cfun),
5476                    false) >= 2
5477       && ! FLOAT_TYPE_P (TREE_TYPE (rl_arg))
5478       && simple_operand_p (rl_arg)
5479       && simple_operand_p (rr_arg))
5480     {
5481       /* Convert (a != 0) || (b != 0) into (a | b) != 0.  */
5482       if (code == TRUTH_OR_EXPR
5483           && lcode == NE_EXPR && integer_zerop (lr_arg)
5484           && rcode == NE_EXPR && integer_zerop (rr_arg)
5485           && TREE_TYPE (ll_arg) == TREE_TYPE (rl_arg)
5486           && INTEGRAL_TYPE_P (TREE_TYPE (ll_arg)))
5487         return build2_loc (loc, NE_EXPR, truth_type,
5488                            build2 (BIT_IOR_EXPR, TREE_TYPE (ll_arg),
5489                                    ll_arg, rl_arg),
5490                            build_int_cst (TREE_TYPE (ll_arg), 0));
5491
5492       /* Convert (a == 0) && (b == 0) into (a | b) == 0.  */
5493       if (code == TRUTH_AND_EXPR
5494           && lcode == EQ_EXPR && integer_zerop (lr_arg)
5495           && rcode == EQ_EXPR && integer_zerop (rr_arg)
5496           && TREE_TYPE (ll_arg) == TREE_TYPE (rl_arg)
5497           && INTEGRAL_TYPE_P (TREE_TYPE (ll_arg)))
5498         return build2_loc (loc, EQ_EXPR, truth_type,
5499                            build2 (BIT_IOR_EXPR, TREE_TYPE (ll_arg),
5500                                    ll_arg, rl_arg),
5501                            build_int_cst (TREE_TYPE (ll_arg), 0));
5502     }
5503
5504   /* See if the comparisons can be merged.  Then get all the parameters for
5505      each side.  */
5506
5507   if ((lcode != EQ_EXPR && lcode != NE_EXPR)
5508       || (rcode != EQ_EXPR && rcode != NE_EXPR))
5509     return 0;
5510
5511   volatilep = 0;
5512   ll_inner = decode_field_reference (loc, ll_arg,
5513                                      &ll_bitsize, &ll_bitpos, &ll_mode,
5514                                      &ll_unsignedp, &volatilep, &ll_mask,
5515                                      &ll_and_mask);
5516   lr_inner = decode_field_reference (loc, lr_arg,
5517                                      &lr_bitsize, &lr_bitpos, &lr_mode,
5518                                      &lr_unsignedp, &volatilep, &lr_mask,
5519                                      &lr_and_mask);
5520   rl_inner = decode_field_reference (loc, rl_arg,
5521                                      &rl_bitsize, &rl_bitpos, &rl_mode,
5522                                      &rl_unsignedp, &volatilep, &rl_mask,
5523                                      &rl_and_mask);
5524   rr_inner = decode_field_reference (loc, rr_arg,
5525                                      &rr_bitsize, &rr_bitpos, &rr_mode,
5526                                      &rr_unsignedp, &volatilep, &rr_mask,
5527                                      &rr_and_mask);
5528
5529   /* It must be true that the inner operation on the lhs of each
5530      comparison must be the same if we are to be able to do anything.
5531      Then see if we have constants.  If not, the same must be true for
5532      the rhs's.  */
5533   if (volatilep || ll_inner == 0 || rl_inner == 0
5534       || ! operand_equal_p (ll_inner, rl_inner, 0))
5535     return 0;
5536
5537   if (TREE_CODE (lr_arg) == INTEGER_CST
5538       && TREE_CODE (rr_arg) == INTEGER_CST)
5539     l_const = lr_arg, r_const = rr_arg;
5540   else if (lr_inner == 0 || rr_inner == 0
5541            || ! operand_equal_p (lr_inner, rr_inner, 0))
5542     return 0;
5543   else
5544     l_const = r_const = 0;
5545
5546   /* If either comparison code is not correct for our logical operation,
5547      fail.  However, we can convert a one-bit comparison against zero into
5548      the opposite comparison against that bit being set in the field.  */
5549
5550   wanted_code = (code == TRUTH_AND_EXPR ? EQ_EXPR : NE_EXPR);
5551   if (lcode != wanted_code)
5552     {
5553       if (l_const && integer_zerop (l_const) && integer_pow2p (ll_mask))
5554         {
5555           /* Make the left operand unsigned, since we are only interested
5556              in the value of one bit.  Otherwise we are doing the wrong
5557              thing below.  */
5558           ll_unsignedp = 1;
5559           l_const = ll_mask;
5560         }
5561       else
5562         return 0;
5563     }
5564
5565   /* This is analogous to the code for l_const above.  */
5566   if (rcode != wanted_code)
5567     {
5568       if (r_const && integer_zerop (r_const) && integer_pow2p (rl_mask))
5569         {
5570           rl_unsignedp = 1;
5571           r_const = rl_mask;
5572         }
5573       else
5574         return 0;
5575     }
5576
5577   /* See if we can find a mode that contains both fields being compared on
5578      the left.  If we can't, fail.  Otherwise, update all constants and masks
5579      to be relative to a field of that size.  */
5580   first_bit = MIN (ll_bitpos, rl_bitpos);
5581   end_bit = MAX (ll_bitpos + ll_bitsize, rl_bitpos + rl_bitsize);
5582   lnmode = get_best_mode (end_bit - first_bit, first_bit, 0, 0,
5583                           TYPE_ALIGN (TREE_TYPE (ll_inner)), word_mode,
5584                           volatilep);
5585   if (lnmode == VOIDmode)
5586     return 0;
5587
5588   lnbitsize = GET_MODE_BITSIZE (lnmode);
5589   lnbitpos = first_bit & ~ (lnbitsize - 1);
5590   lntype = lang_hooks.types.type_for_size (lnbitsize, 1);
5591   xll_bitpos = ll_bitpos - lnbitpos, xrl_bitpos = rl_bitpos - lnbitpos;
5592
5593   if (BYTES_BIG_ENDIAN)
5594     {
5595       xll_bitpos = lnbitsize - xll_bitpos - ll_bitsize;
5596       xrl_bitpos = lnbitsize - xrl_bitpos - rl_bitsize;
5597     }
5598
5599   ll_mask = const_binop (LSHIFT_EXPR, fold_convert_loc (loc, lntype, ll_mask),
5600                          size_int (xll_bitpos));
5601   rl_mask = const_binop (LSHIFT_EXPR, fold_convert_loc (loc, lntype, rl_mask),
5602                          size_int (xrl_bitpos));
5603
5604   if (l_const)
5605     {
5606       l_const = fold_convert_loc (loc, lntype, l_const);
5607       l_const = unextend (l_const, ll_bitsize, ll_unsignedp, ll_and_mask);
5608       l_const = const_binop (LSHIFT_EXPR, l_const, size_int (xll_bitpos));
5609       if (! integer_zerop (const_binop (BIT_AND_EXPR, l_const,
5610                                         fold_build1_loc (loc, BIT_NOT_EXPR,
5611                                                      lntype, ll_mask))))
5612         {
5613           warning (0, "comparison is always %d", wanted_code == NE_EXPR);
5614
5615           return constant_boolean_node (wanted_code == NE_EXPR, truth_type);
5616         }
5617     }
5618   if (r_const)
5619     {
5620       r_const = fold_convert_loc (loc, lntype, r_const);
5621       r_const = unextend (r_const, rl_bitsize, rl_unsignedp, rl_and_mask);
5622       r_const = const_binop (LSHIFT_EXPR, r_const, size_int (xrl_bitpos));
5623       if (! integer_zerop (const_binop (BIT_AND_EXPR, r_const,
5624                                         fold_build1_loc (loc, BIT_NOT_EXPR,
5625                                                      lntype, rl_mask))))
5626         {
5627           warning (0, "comparison is always %d", wanted_code == NE_EXPR);
5628
5629           return constant_boolean_node (wanted_code == NE_EXPR, truth_type);
5630         }
5631     }
5632
5633   /* If the right sides are not constant, do the same for it.  Also,
5634      disallow this optimization if a size or signedness mismatch occurs
5635      between the left and right sides.  */
5636   if (l_const == 0)
5637     {
5638       if (ll_bitsize != lr_bitsize || rl_bitsize != rr_bitsize
5639           || ll_unsignedp != lr_unsignedp || rl_unsignedp != rr_unsignedp
5640           /* Make sure the two fields on the right
5641              correspond to the left without being swapped.  */
5642           || ll_bitpos - rl_bitpos != lr_bitpos - rr_bitpos)
5643         return 0;
5644
5645       first_bit = MIN (lr_bitpos, rr_bitpos);
5646       end_bit = MAX (lr_bitpos + lr_bitsize, rr_bitpos + rr_bitsize);
5647       rnmode = get_best_mode (end_bit - first_bit, first_bit, 0, 0,
5648                               TYPE_ALIGN (TREE_TYPE (lr_inner)), word_mode,
5649                               volatilep);
5650       if (rnmode == VOIDmode)
5651         return 0;
5652
5653       rnbitsize = GET_MODE_BITSIZE (rnmode);
5654       rnbitpos = first_bit & ~ (rnbitsize - 1);
5655       rntype = lang_hooks.types.type_for_size (rnbitsize, 1);
5656       xlr_bitpos = lr_bitpos - rnbitpos, xrr_bitpos = rr_bitpos - rnbitpos;
5657
5658       if (BYTES_BIG_ENDIAN)
5659         {
5660           xlr_bitpos = rnbitsize - xlr_bitpos - lr_bitsize;
5661           xrr_bitpos = rnbitsize - xrr_bitpos - rr_bitsize;
5662         }
5663
5664       lr_mask = const_binop (LSHIFT_EXPR, fold_convert_loc (loc,
5665                                                             rntype, lr_mask),
5666                              size_int (xlr_bitpos));
5667       rr_mask = const_binop (LSHIFT_EXPR, fold_convert_loc (loc,
5668                                                             rntype, rr_mask),
5669                              size_int (xrr_bitpos));
5670
5671       /* Make a mask that corresponds to both fields being compared.
5672          Do this for both items being compared.  If the operands are the
5673          same size and the bits being compared are in the same position
5674          then we can do this by masking both and comparing the masked
5675          results.  */
5676       ll_mask = const_binop (BIT_IOR_EXPR, ll_mask, rl_mask);
5677       lr_mask = const_binop (BIT_IOR_EXPR, lr_mask, rr_mask);
5678       if (lnbitsize == rnbitsize && xll_bitpos == xlr_bitpos)
5679         {
5680           lhs = make_bit_field_ref (loc, ll_inner, lntype, lnbitsize, lnbitpos,
5681                                     ll_unsignedp || rl_unsignedp);
5682           if (! all_ones_mask_p (ll_mask, lnbitsize))
5683             lhs = build2 (BIT_AND_EXPR, lntype, lhs, ll_mask);
5684
5685           rhs = make_bit_field_ref (loc, lr_inner, rntype, rnbitsize, rnbitpos,
5686                                     lr_unsignedp || rr_unsignedp);
5687           if (! all_ones_mask_p (lr_mask, rnbitsize))
5688             rhs = build2 (BIT_AND_EXPR, rntype, rhs, lr_mask);
5689
5690           return build2_loc (loc, wanted_code, truth_type, lhs, rhs);
5691         }
5692
5693       /* There is still another way we can do something:  If both pairs of
5694          fields being compared are adjacent, we may be able to make a wider
5695          field containing them both.
5696
5697          Note that we still must mask the lhs/rhs expressions.  Furthermore,
5698          the mask must be shifted to account for the shift done by
5699          make_bit_field_ref.  */
5700       if ((ll_bitsize + ll_bitpos == rl_bitpos
5701            && lr_bitsize + lr_bitpos == rr_bitpos)
5702           || (ll_bitpos == rl_bitpos + rl_bitsize
5703               && lr_bitpos == rr_bitpos + rr_bitsize))
5704         {
5705           tree type;
5706
5707           lhs = make_bit_field_ref (loc, ll_inner, lntype,
5708                                     ll_bitsize + rl_bitsize,
5709                                     MIN (ll_bitpos, rl_bitpos), ll_unsignedp);
5710           rhs = make_bit_field_ref (loc, lr_inner, rntype,
5711                                     lr_bitsize + rr_bitsize,
5712                                     MIN (lr_bitpos, rr_bitpos), lr_unsignedp);
5713
5714           ll_mask = const_binop (RSHIFT_EXPR, ll_mask,
5715                                  size_int (MIN (xll_bitpos, xrl_bitpos)));
5716           lr_mask = const_binop (RSHIFT_EXPR, lr_mask,
5717                                  size_int (MIN (xlr_bitpos, xrr_bitpos)));
5718
5719           /* Convert to the smaller type before masking out unwanted bits.  */
5720           type = lntype;
5721           if (lntype != rntype)
5722             {
5723               if (lnbitsize > rnbitsize)
5724                 {
5725                   lhs = fold_convert_loc (loc, rntype, lhs);
5726                   ll_mask = fold_convert_loc (loc, rntype, ll_mask);
5727                   type = rntype;
5728                 }
5729               else if (lnbitsize < rnbitsize)
5730                 {
5731                   rhs = fold_convert_loc (loc, lntype, rhs);
5732                   lr_mask = fold_convert_loc (loc, lntype, lr_mask);
5733                   type = lntype;
5734                 }
5735             }
5736
5737           if (! all_ones_mask_p (ll_mask, ll_bitsize + rl_bitsize))
5738             lhs = build2 (BIT_AND_EXPR, type, lhs, ll_mask);
5739
5740           if (! all_ones_mask_p (lr_mask, lr_bitsize + rr_bitsize))
5741             rhs = build2 (BIT_AND_EXPR, type, rhs, lr_mask);
5742
5743           return build2_loc (loc, wanted_code, truth_type, lhs, rhs);
5744         }
5745
5746       return 0;
5747     }
5748
5749   /* Handle the case of comparisons with constants.  If there is something in
5750      common between the masks, those bits of the constants must be the same.
5751      If not, the condition is always false.  Test for this to avoid generating
5752      incorrect code below.  */
5753   result = const_binop (BIT_AND_EXPR, ll_mask, rl_mask);
5754   if (! integer_zerop (result)
5755       && simple_cst_equal (const_binop (BIT_AND_EXPR, result, l_const),
5756                            const_binop (BIT_AND_EXPR, result, r_const)) != 1)
5757     {
5758       if (wanted_code == NE_EXPR)
5759         {
5760           warning (0, "%<or%> of unmatched not-equal tests is always 1");
5761           return constant_boolean_node (true, truth_type);
5762         }
5763       else
5764         {
5765           warning (0, "%<and%> of mutually exclusive equal-tests is always 0");
5766           return constant_boolean_node (false, truth_type);
5767         }
5768     }
5769
5770   /* Construct the expression we will return.  First get the component
5771      reference we will make.  Unless the mask is all ones the width of
5772      that field, perform the mask operation.  Then compare with the
5773      merged constant.  */
5774   result = make_bit_field_ref (loc, ll_inner, lntype, lnbitsize, lnbitpos,
5775                                ll_unsignedp || rl_unsignedp);
5776
5777   ll_mask = const_binop (BIT_IOR_EXPR, ll_mask, rl_mask);
5778   if (! all_ones_mask_p (ll_mask, lnbitsize))
5779     result = build2_loc (loc, BIT_AND_EXPR, lntype, result, ll_mask);
5780
5781   return build2_loc (loc, wanted_code, truth_type, result,
5782                      const_binop (BIT_IOR_EXPR, l_const, r_const));
5783 }
5784 \f
5785 /* Optimize T, which is a comparison of a MIN_EXPR or MAX_EXPR with a
5786    constant.  */
5787
5788 static tree
5789 optimize_minmax_comparison (location_t loc, enum tree_code code, tree type,
5790                             tree op0, tree op1)
5791 {
5792   tree arg0 = op0;
5793   enum tree_code op_code;
5794   tree comp_const;
5795   tree minmax_const;
5796   int consts_equal, consts_lt;
5797   tree inner;
5798
5799   STRIP_SIGN_NOPS (arg0);
5800
5801   op_code = TREE_CODE (arg0);
5802   minmax_const = TREE_OPERAND (arg0, 1);
5803   comp_const = fold_convert_loc (loc, TREE_TYPE (arg0), op1);
5804   consts_equal = tree_int_cst_equal (minmax_const, comp_const);
5805   consts_lt = tree_int_cst_lt (minmax_const, comp_const);
5806   inner = TREE_OPERAND (arg0, 0);
5807
5808   /* If something does not permit us to optimize, return the original tree.  */
5809   if ((op_code != MIN_EXPR && op_code != MAX_EXPR)
5810       || TREE_CODE (comp_const) != INTEGER_CST
5811       || TREE_OVERFLOW (comp_const)
5812       || TREE_CODE (minmax_const) != INTEGER_CST
5813       || TREE_OVERFLOW (minmax_const))
5814     return NULL_TREE;
5815
5816   /* Now handle all the various comparison codes.  We only handle EQ_EXPR
5817      and GT_EXPR, doing the rest with recursive calls using logical
5818      simplifications.  */
5819   switch (code)
5820     {
5821     case NE_EXPR:  case LT_EXPR:  case LE_EXPR:
5822       {
5823         tree tem
5824           = optimize_minmax_comparison (loc,
5825                                         invert_tree_comparison (code, false),
5826                                         type, op0, op1);
5827         if (tem)
5828           return invert_truthvalue_loc (loc, tem);
5829         return NULL_TREE;
5830       }
5831
5832     case GE_EXPR:
5833       return
5834         fold_build2_loc (loc, TRUTH_ORIF_EXPR, type,
5835                      optimize_minmax_comparison
5836                      (loc, EQ_EXPR, type, arg0, comp_const),
5837                      optimize_minmax_comparison
5838                      (loc, GT_EXPR, type, arg0, comp_const));
5839
5840     case EQ_EXPR:
5841       if (op_code == MAX_EXPR && consts_equal)
5842         /* MAX (X, 0) == 0  ->  X <= 0  */
5843         return fold_build2_loc (loc, LE_EXPR, type, inner, comp_const);
5844
5845       else if (op_code == MAX_EXPR && consts_lt)
5846         /* MAX (X, 0) == 5  ->  X == 5   */
5847         return fold_build2_loc (loc, EQ_EXPR, type, inner, comp_const);
5848
5849       else if (op_code == MAX_EXPR)
5850         /* MAX (X, 0) == -1  ->  false  */
5851         return omit_one_operand_loc (loc, type, integer_zero_node, inner);
5852
5853       else if (consts_equal)
5854         /* MIN (X, 0) == 0  ->  X >= 0  */
5855         return fold_build2_loc (loc, GE_EXPR, type, inner, comp_const);
5856
5857       else if (consts_lt)
5858         /* MIN (X, 0) == 5  ->  false  */
5859         return omit_one_operand_loc (loc, type, integer_zero_node, inner);
5860
5861       else
5862         /* MIN (X, 0) == -1  ->  X == -1  */
5863         return fold_build2_loc (loc, EQ_EXPR, type, inner, comp_const);
5864
5865     case GT_EXPR:
5866       if (op_code == MAX_EXPR && (consts_equal || consts_lt))
5867         /* MAX (X, 0) > 0  ->  X > 0
5868            MAX (X, 0) > 5  ->  X > 5  */
5869         return fold_build2_loc (loc, GT_EXPR, type, inner, comp_const);
5870
5871       else if (op_code == MAX_EXPR)
5872         /* MAX (X, 0) > -1  ->  true  */
5873         return omit_one_operand_loc (loc, type, integer_one_node, inner);
5874
5875       else if (op_code == MIN_EXPR && (consts_equal || consts_lt))
5876         /* MIN (X, 0) > 0  ->  false
5877            MIN (X, 0) > 5  ->  false  */
5878         return omit_one_operand_loc (loc, type, integer_zero_node, inner);
5879
5880       else
5881         /* MIN (X, 0) > -1  ->  X > -1  */
5882         return fold_build2_loc (loc, GT_EXPR, type, inner, comp_const);
5883
5884     default:
5885       return NULL_TREE;
5886     }
5887 }
5888 \f
5889 /* T is an integer expression that is being multiplied, divided, or taken a
5890    modulus (CODE says which and what kind of divide or modulus) by a
5891    constant C.  See if we can eliminate that operation by folding it with
5892    other operations already in T.  WIDE_TYPE, if non-null, is a type that
5893    should be used for the computation if wider than our type.
5894
5895    For example, if we are dividing (X * 8) + (Y * 16) by 4, we can return
5896    (X * 2) + (Y * 4).  We must, however, be assured that either the original
5897    expression would not overflow or that overflow is undefined for the type
5898    in the language in question.
5899
5900    If we return a non-null expression, it is an equivalent form of the
5901    original computation, but need not be in the original type.
5902
5903    We set *STRICT_OVERFLOW_P to true if the return values depends on
5904    signed overflow being undefined.  Otherwise we do not change
5905    *STRICT_OVERFLOW_P.  */
5906
5907 static tree
5908 extract_muldiv (tree t, tree c, enum tree_code code, tree wide_type,
5909                 bool *strict_overflow_p)
5910 {
5911   /* To avoid exponential search depth, refuse to allow recursion past
5912      three levels.  Beyond that (1) it's highly unlikely that we'll find
5913      something interesting and (2) we've probably processed it before
5914      when we built the inner expression.  */
5915
5916   static int depth;
5917   tree ret;
5918
5919   if (depth > 3)
5920     return NULL;
5921
5922   depth++;
5923   ret = extract_muldiv_1 (t, c, code, wide_type, strict_overflow_p);
5924   depth--;
5925
5926   return ret;
5927 }
5928
5929 static tree
5930 extract_muldiv_1 (tree t, tree c, enum tree_code code, tree wide_type,
5931                   bool *strict_overflow_p)
5932 {
5933   tree type = TREE_TYPE (t);
5934   enum tree_code tcode = TREE_CODE (t);
5935   tree ctype = (wide_type != 0 && (GET_MODE_SIZE (TYPE_MODE (wide_type))
5936                                    > GET_MODE_SIZE (TYPE_MODE (type)))
5937                 ? wide_type : type);
5938   tree t1, t2;
5939   int same_p = tcode == code;
5940   tree op0 = NULL_TREE, op1 = NULL_TREE;
5941   bool sub_strict_overflow_p;
5942
5943   /* Don't deal with constants of zero here; they confuse the code below.  */
5944   if (integer_zerop (c))
5945     return NULL_TREE;
5946
5947   if (TREE_CODE_CLASS (tcode) == tcc_unary)
5948     op0 = TREE_OPERAND (t, 0);
5949
5950   if (TREE_CODE_CLASS (tcode) == tcc_binary)
5951     op0 = TREE_OPERAND (t, 0), op1 = TREE_OPERAND (t, 1);
5952
5953   /* Note that we need not handle conditional operations here since fold
5954      already handles those cases.  So just do arithmetic here.  */
5955   switch (tcode)
5956     {
5957     case INTEGER_CST:
5958       /* For a constant, we can always simplify if we are a multiply
5959          or (for divide and modulus) if it is a multiple of our constant.  */
5960       if (code == MULT_EXPR
5961           || wi::multiple_of_p (t, c, TYPE_SIGN (type)))
5962         return const_binop (code, fold_convert (ctype, t),
5963                             fold_convert (ctype, c));
5964       break;
5965
5966     CASE_CONVERT: case NON_LVALUE_EXPR:
5967       /* If op0 is an expression ...  */
5968       if ((COMPARISON_CLASS_P (op0)
5969            || UNARY_CLASS_P (op0)
5970            || BINARY_CLASS_P (op0)
5971            || VL_EXP_CLASS_P (op0)
5972            || EXPRESSION_CLASS_P (op0))
5973           /* ... and has wrapping overflow, and its type is smaller
5974              than ctype, then we cannot pass through as widening.  */
5975           && (((ANY_INTEGRAL_TYPE_P (TREE_TYPE (op0))
5976                 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
5977                && (TYPE_PRECISION (ctype)
5978                    > TYPE_PRECISION (TREE_TYPE (op0))))
5979               /* ... or this is a truncation (t is narrower than op0),
5980                  then we cannot pass through this narrowing.  */
5981               || (TYPE_PRECISION (type)
5982                   < TYPE_PRECISION (TREE_TYPE (op0)))
5983               /* ... or signedness changes for division or modulus,
5984                  then we cannot pass through this conversion.  */
5985               || (code != MULT_EXPR
5986                   && (TYPE_UNSIGNED (ctype)
5987                       != TYPE_UNSIGNED (TREE_TYPE (op0))))
5988               /* ... or has undefined overflow while the converted to
5989                  type has not, we cannot do the operation in the inner type
5990                  as that would introduce undefined overflow.  */
5991               || ((ANY_INTEGRAL_TYPE_P (TREE_TYPE (op0))
5992                    && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (op0)))
5993                   && !TYPE_OVERFLOW_UNDEFINED (type))))
5994         break;
5995
5996       /* Pass the constant down and see if we can make a simplification.  If
5997          we can, replace this expression with the inner simplification for
5998          possible later conversion to our or some other type.  */
5999       if ((t2 = fold_convert (TREE_TYPE (op0), c)) != 0
6000           && TREE_CODE (t2) == INTEGER_CST
6001           && !TREE_OVERFLOW (t2)
6002           && (0 != (t1 = extract_muldiv (op0, t2, code,
6003                                          code == MULT_EXPR
6004                                          ? ctype : NULL_TREE,
6005                                          strict_overflow_p))))
6006         return t1;
6007       break;
6008
6009     case ABS_EXPR:
6010       /* If widening the type changes it from signed to unsigned, then we
6011          must avoid building ABS_EXPR itself as unsigned.  */
6012       if (TYPE_UNSIGNED (ctype) && !TYPE_UNSIGNED (type))
6013         {
6014           tree cstype = (*signed_type_for) (ctype);
6015           if ((t1 = extract_muldiv (op0, c, code, cstype, strict_overflow_p))
6016               != 0)
6017             {
6018               t1 = fold_build1 (tcode, cstype, fold_convert (cstype, t1));
6019               return fold_convert (ctype, t1);
6020             }
6021           break;
6022         }
6023       /* If the constant is negative, we cannot simplify this.  */
6024       if (tree_int_cst_sgn (c) == -1)
6025         break;
6026       /* FALLTHROUGH */
6027     case NEGATE_EXPR:
6028       /* For division and modulus, type can't be unsigned, as e.g.
6029          (-(x / 2U)) / 2U isn't equal to -((x / 2U) / 2U) for x >= 2.
6030          For signed types, even with wrapping overflow, this is fine.  */
6031       if (code != MULT_EXPR && TYPE_UNSIGNED (type))
6032         break;
6033       if ((t1 = extract_muldiv (op0, c, code, wide_type, strict_overflow_p))
6034           != 0)
6035         return fold_build1 (tcode, ctype, fold_convert (ctype, t1));
6036       break;
6037
6038     case MIN_EXPR:  case MAX_EXPR:
6039       /* If widening the type changes the signedness, then we can't perform
6040          this optimization as that changes the result.  */
6041       if (TYPE_UNSIGNED (ctype) != TYPE_UNSIGNED (type))
6042         break;
6043
6044       /* MIN (a, b) / 5 -> MIN (a / 5, b / 5)  */
6045       sub_strict_overflow_p = false;
6046       if ((t1 = extract_muldiv (op0, c, code, wide_type,
6047                                 &sub_strict_overflow_p)) != 0
6048           && (t2 = extract_muldiv (op1, c, code, wide_type,
6049                                    &sub_strict_overflow_p)) != 0)
6050         {
6051           if (tree_int_cst_sgn (c) < 0)
6052             tcode = (tcode == MIN_EXPR ? MAX_EXPR : MIN_EXPR);
6053           if (sub_strict_overflow_p)
6054             *strict_overflow_p = true;
6055           return fold_build2 (tcode, ctype, fold_convert (ctype, t1),
6056                               fold_convert (ctype, t2));
6057         }
6058       break;
6059
6060     case LSHIFT_EXPR:  case RSHIFT_EXPR:
6061       /* If the second operand is constant, this is a multiplication
6062          or floor division, by a power of two, so we can treat it that
6063          way unless the multiplier or divisor overflows.  Signed
6064          left-shift overflow is implementation-defined rather than
6065          undefined in C90, so do not convert signed left shift into
6066          multiplication.  */
6067       if (TREE_CODE (op1) == INTEGER_CST
6068           && (tcode == RSHIFT_EXPR || TYPE_UNSIGNED (TREE_TYPE (op0)))
6069           /* const_binop may not detect overflow correctly,
6070              so check for it explicitly here.  */
6071           && wi::gtu_p (TYPE_PRECISION (TREE_TYPE (size_one_node)), op1)
6072           && 0 != (t1 = fold_convert (ctype,
6073                                       const_binop (LSHIFT_EXPR,
6074                                                    size_one_node,
6075                                                    op1)))
6076           && !TREE_OVERFLOW (t1))
6077         return extract_muldiv (build2 (tcode == LSHIFT_EXPR
6078                                        ? MULT_EXPR : FLOOR_DIV_EXPR,
6079                                        ctype,
6080                                        fold_convert (ctype, op0),
6081                                        t1),
6082                                c, code, wide_type, strict_overflow_p);
6083       break;
6084
6085     case PLUS_EXPR:  case MINUS_EXPR:
6086       /* See if we can eliminate the operation on both sides.  If we can, we
6087          can return a new PLUS or MINUS.  If we can't, the only remaining
6088          cases where we can do anything are if the second operand is a
6089          constant.  */
6090       sub_strict_overflow_p = false;
6091       t1 = extract_muldiv (op0, c, code, wide_type, &sub_strict_overflow_p);
6092       t2 = extract_muldiv (op1, c, code, wide_type, &sub_strict_overflow_p);
6093       if (t1 != 0 && t2 != 0
6094           && (code == MULT_EXPR
6095               /* If not multiplication, we can only do this if both operands
6096                  are divisible by c.  */
6097               || (multiple_of_p (ctype, op0, c)
6098                   && multiple_of_p (ctype, op1, c))))
6099         {
6100           if (sub_strict_overflow_p)
6101             *strict_overflow_p = true;
6102           return fold_build2 (tcode, ctype, fold_convert (ctype, t1),
6103                               fold_convert (ctype, t2));
6104         }
6105
6106       /* If this was a subtraction, negate OP1 and set it to be an addition.
6107          This simplifies the logic below.  */
6108       if (tcode == MINUS_EXPR)
6109         {
6110           tcode = PLUS_EXPR, op1 = negate_expr (op1);
6111           /* If OP1 was not easily negatable, the constant may be OP0.  */
6112           if (TREE_CODE (op0) == INTEGER_CST)
6113             {
6114               tree tem = op0;
6115               op0 = op1;
6116               op1 = tem;
6117               tem = t1;
6118               t1 = t2;
6119               t2 = tem;
6120             }
6121         }
6122
6123       if (TREE_CODE (op1) != INTEGER_CST)
6124         break;
6125
6126       /* If either OP1 or C are negative, this optimization is not safe for
6127          some of the division and remainder types while for others we need
6128          to change the code.  */
6129       if (tree_int_cst_sgn (op1) < 0 || tree_int_cst_sgn (c) < 0)
6130         {
6131           if (code == CEIL_DIV_EXPR)
6132             code = FLOOR_DIV_EXPR;
6133           else if (code == FLOOR_DIV_EXPR)
6134             code = CEIL_DIV_EXPR;
6135           else if (code != MULT_EXPR
6136                    && code != CEIL_MOD_EXPR && code != FLOOR_MOD_EXPR)
6137             break;
6138         }
6139
6140       /* If it's a multiply or a division/modulus operation of a multiple
6141          of our constant, do the operation and verify it doesn't overflow.  */
6142       if (code == MULT_EXPR
6143           || wi::multiple_of_p (op1, c, TYPE_SIGN (type)))
6144         {
6145           op1 = const_binop (code, fold_convert (ctype, op1),
6146                              fold_convert (ctype, c));
6147           /* We allow the constant to overflow with wrapping semantics.  */
6148           if (op1 == 0
6149               || (TREE_OVERFLOW (op1) && !TYPE_OVERFLOW_WRAPS (ctype)))
6150             break;
6151         }
6152       else
6153         break;
6154
6155       /* If we have an unsigned type, we cannot widen the operation since it
6156          will change the result if the original computation overflowed.  */
6157       if (TYPE_UNSIGNED (ctype) && ctype != type)
6158         break;
6159
6160       /* If we were able to eliminate our operation from the first side,
6161          apply our operation to the second side and reform the PLUS.  */
6162       if (t1 != 0 && (TREE_CODE (t1) != code || code == MULT_EXPR))
6163         return fold_build2 (tcode, ctype, fold_convert (ctype, t1), op1);
6164
6165       /* The last case is if we are a multiply.  In that case, we can
6166          apply the distributive law to commute the multiply and addition
6167          if the multiplication of the constants doesn't overflow
6168          and overflow is defined.  With undefined overflow
6169          op0 * c might overflow, while (op0 + orig_op1) * c doesn't.  */
6170       if (code == MULT_EXPR && TYPE_OVERFLOW_WRAPS (ctype))
6171         return fold_build2 (tcode, ctype,
6172                             fold_build2 (code, ctype,
6173                                          fold_convert (ctype, op0),
6174                                          fold_convert (ctype, c)),
6175                             op1);
6176
6177       break;
6178
6179     case MULT_EXPR:
6180       /* We have a special case here if we are doing something like
6181          (C * 8) % 4 since we know that's zero.  */
6182       if ((code == TRUNC_MOD_EXPR || code == CEIL_MOD_EXPR
6183            || code == FLOOR_MOD_EXPR || code == ROUND_MOD_EXPR)
6184           /* If the multiplication can overflow we cannot optimize this.  */
6185           && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (t))
6186           && TREE_CODE (TREE_OPERAND (t, 1)) == INTEGER_CST
6187           && wi::multiple_of_p (op1, c, TYPE_SIGN (type)))
6188         {
6189           *strict_overflow_p = true;
6190           return omit_one_operand (type, integer_zero_node, op0);
6191         }
6192
6193       /* ... fall through ...  */
6194
6195     case TRUNC_DIV_EXPR:  case CEIL_DIV_EXPR:  case FLOOR_DIV_EXPR:
6196     case ROUND_DIV_EXPR:  case EXACT_DIV_EXPR:
6197       /* If we can extract our operation from the LHS, do so and return a
6198          new operation.  Likewise for the RHS from a MULT_EXPR.  Otherwise,
6199          do something only if the second operand is a constant.  */
6200       if (same_p
6201           && (t1 = extract_muldiv (op0, c, code, wide_type,
6202                                    strict_overflow_p)) != 0)
6203         return fold_build2 (tcode, ctype, fold_convert (ctype, t1),
6204                             fold_convert (ctype, op1));
6205       else if (tcode == MULT_EXPR && code == MULT_EXPR
6206                && (t1 = extract_muldiv (op1, c, code, wide_type,
6207                                         strict_overflow_p)) != 0)
6208         return fold_build2 (tcode, ctype, fold_convert (ctype, op0),
6209                             fold_convert (ctype, t1));
6210       else if (TREE_CODE (op1) != INTEGER_CST)
6211         return 0;
6212
6213       /* If these are the same operation types, we can associate them
6214          assuming no overflow.  */
6215       if (tcode == code)
6216         {
6217           bool overflow_p = false;
6218           bool overflow_mul_p;
6219           signop sign = TYPE_SIGN (ctype);
6220           wide_int mul = wi::mul (op1, c, sign, &overflow_mul_p);
6221           overflow_p = TREE_OVERFLOW (c) | TREE_OVERFLOW (op1);
6222           if (overflow_mul_p
6223               && ((sign == UNSIGNED && tcode != MULT_EXPR) || sign == SIGNED))
6224             overflow_p = true;
6225           if (!overflow_p)
6226             return fold_build2 (tcode, ctype, fold_convert (ctype, op0),
6227                                 wide_int_to_tree (ctype, mul));
6228         }
6229
6230       /* If these operations "cancel" each other, we have the main
6231          optimizations of this pass, which occur when either constant is a
6232          multiple of the other, in which case we replace this with either an
6233          operation or CODE or TCODE.
6234
6235          If we have an unsigned type, we cannot do this since it will change
6236          the result if the original computation overflowed.  */
6237       if (TYPE_OVERFLOW_UNDEFINED (ctype)
6238           && ((code == MULT_EXPR && tcode == EXACT_DIV_EXPR)
6239               || (tcode == MULT_EXPR
6240                   && code != TRUNC_MOD_EXPR && code != CEIL_MOD_EXPR
6241                   && code != FLOOR_MOD_EXPR && code != ROUND_MOD_EXPR
6242                   && code != MULT_EXPR)))
6243         {
6244           if (wi::multiple_of_p (op1, c, TYPE_SIGN (type)))
6245             {
6246               if (TYPE_OVERFLOW_UNDEFINED (ctype))
6247                 *strict_overflow_p = true;
6248               return fold_build2 (tcode, ctype, fold_convert (ctype, op0),
6249                                   fold_convert (ctype,
6250                                                 const_binop (TRUNC_DIV_EXPR,
6251                                                              op1, c)));
6252             }
6253           else if (wi::multiple_of_p (c, op1, TYPE_SIGN (type)))
6254             {
6255               if (TYPE_OVERFLOW_UNDEFINED (ctype))
6256                 *strict_overflow_p = true;
6257               return fold_build2 (code, ctype, fold_convert (ctype, op0),
6258                                   fold_convert (ctype,
6259                                                 const_binop (TRUNC_DIV_EXPR,
6260                                                              c, op1)));
6261             }
6262         }
6263       break;
6264
6265     default:
6266       break;
6267     }
6268
6269   return 0;
6270 }
6271 \f
6272 /* Return a node which has the indicated constant VALUE (either 0 or
6273    1 for scalars or {-1,-1,..} or {0,0,...} for vectors),
6274    and is of the indicated TYPE.  */
6275
6276 tree
6277 constant_boolean_node (bool value, tree type)
6278 {
6279   if (type == integer_type_node)
6280     return value ? integer_one_node : integer_zero_node;
6281   else if (type == boolean_type_node)
6282     return value ? boolean_true_node : boolean_false_node;
6283   else if (TREE_CODE (type) == VECTOR_TYPE)
6284     return build_vector_from_val (type,
6285                                   build_int_cst (TREE_TYPE (type),
6286                                                  value ? -1 : 0));
6287   else
6288     return fold_convert (type, value ? integer_one_node : integer_zero_node);
6289 }
6290
6291
6292 /* Transform `a + (b ? x : y)' into `b ? (a + x) : (a + y)'.
6293    Transform, `a + (x < y)' into `(x < y) ? (a + 1) : (a + 0)'.  Here
6294    CODE corresponds to the `+', COND to the `(b ? x : y)' or `(x < y)'
6295    expression, and ARG to `a'.  If COND_FIRST_P is nonzero, then the
6296    COND is the first argument to CODE; otherwise (as in the example
6297    given here), it is the second argument.  TYPE is the type of the
6298    original expression.  Return NULL_TREE if no simplification is
6299    possible.  */
6300
6301 static tree
6302 fold_binary_op_with_conditional_arg (location_t loc,
6303                                      enum tree_code code,
6304                                      tree type, tree op0, tree op1,
6305                                      tree cond, tree arg, int cond_first_p)
6306 {
6307   tree cond_type = cond_first_p ? TREE_TYPE (op0) : TREE_TYPE (op1);
6308   tree arg_type = cond_first_p ? TREE_TYPE (op1) : TREE_TYPE (op0);
6309   tree test, true_value, false_value;
6310   tree lhs = NULL_TREE;
6311   tree rhs = NULL_TREE;
6312   enum tree_code cond_code = COND_EXPR;
6313
6314   if (TREE_CODE (cond) == COND_EXPR
6315       || TREE_CODE (cond) == VEC_COND_EXPR)
6316     {
6317       test = TREE_OPERAND (cond, 0);
6318       true_value = TREE_OPERAND (cond, 1);
6319       false_value = TREE_OPERAND (cond, 2);
6320       /* If this operand throws an expression, then it does not make
6321          sense to try to perform a logical or arithmetic operation
6322          involving it.  */
6323       if (VOID_TYPE_P (TREE_TYPE (true_value)))
6324         lhs = true_value;
6325       if (VOID_TYPE_P (TREE_TYPE (false_value)))
6326         rhs = false_value;
6327     }
6328   else
6329     {
6330       tree testtype = TREE_TYPE (cond);
6331       test = cond;
6332       true_value = constant_boolean_node (true, testtype);
6333       false_value = constant_boolean_node (false, testtype);
6334     }
6335
6336   if (TREE_CODE (TREE_TYPE (test)) == VECTOR_TYPE)
6337     cond_code = VEC_COND_EXPR;
6338
6339   /* This transformation is only worthwhile if we don't have to wrap ARG
6340      in a SAVE_EXPR and the operation can be simplified without recursing
6341      on at least one of the branches once its pushed inside the COND_EXPR.  */
6342   if (!TREE_CONSTANT (arg)
6343       && (TREE_SIDE_EFFECTS (arg)
6344           || TREE_CODE (arg) == COND_EXPR || TREE_CODE (arg) == VEC_COND_EXPR
6345           || TREE_CONSTANT (true_value) || TREE_CONSTANT (false_value)))
6346     return NULL_TREE;
6347
6348   arg = fold_convert_loc (loc, arg_type, arg);
6349   if (lhs == 0)
6350     {
6351       true_value = fold_convert_loc (loc, cond_type, true_value);
6352       if (cond_first_p)
6353         lhs = fold_build2_loc (loc, code, type, true_value, arg);
6354       else
6355         lhs = fold_build2_loc (loc, code, type, arg, true_value);
6356     }
6357   if (rhs == 0)
6358     {
6359       false_value = fold_convert_loc (loc, cond_type, false_value);
6360       if (cond_first_p)
6361         rhs = fold_build2_loc (loc, code, type, false_value, arg);
6362       else
6363         rhs = fold_build2_loc (loc, code, type, arg, false_value);
6364     }
6365
6366   /* Check that we have simplified at least one of the branches.  */
6367   if (!TREE_CONSTANT (arg) && !TREE_CONSTANT (lhs) && !TREE_CONSTANT (rhs))
6368     return NULL_TREE;
6369
6370   return fold_build3_loc (loc, cond_code, type, test, lhs, rhs);
6371 }
6372
6373 \f
6374 /* Subroutine of fold() that checks for the addition of +/- 0.0.
6375
6376    If !NEGATE, return true if ADDEND is +/-0.0 and, for all X of type
6377    TYPE, X + ADDEND is the same as X.  If NEGATE, return true if X -
6378    ADDEND is the same as X.
6379
6380    X + 0 and X - 0 both give X when X is NaN, infinite, or nonzero
6381    and finite.  The problematic cases are when X is zero, and its mode
6382    has signed zeros.  In the case of rounding towards -infinity,
6383    X - 0 is not the same as X because 0 - 0 is -0.  In other rounding
6384    modes, X + 0 is not the same as X because -0 + 0 is 0.  */
6385
6386 bool
6387 fold_real_zero_addition_p (const_tree type, const_tree addend, int negate)
6388 {
6389   if (!real_zerop (addend))
6390     return false;
6391
6392   /* Don't allow the fold with -fsignaling-nans.  */
6393   if (HONOR_SNANS (element_mode (type)))
6394     return false;
6395
6396   /* Allow the fold if zeros aren't signed, or their sign isn't important.  */
6397   if (!HONOR_SIGNED_ZEROS (element_mode (type)))
6398     return true;
6399
6400   /* In a vector or complex, we would need to check the sign of all zeros.  */
6401   if (TREE_CODE (addend) != REAL_CST)
6402     return false;
6403
6404   /* Treat x + -0 as x - 0 and x - -0 as x + 0.  */
6405   if (REAL_VALUE_MINUS_ZERO (TREE_REAL_CST (addend)))
6406     negate = !negate;
6407
6408   /* The mode has signed zeros, and we have to honor their sign.
6409      In this situation, there is only one case we can return true for.
6410      X - 0 is the same as X unless rounding towards -infinity is
6411      supported.  */
6412   return negate && !HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (type));
6413 }
6414
6415 /* Subroutine of fold() that checks comparisons of built-in math
6416    functions against real constants.
6417
6418    FCODE is the DECL_FUNCTION_CODE of the built-in, CODE is the comparison
6419    operator: EQ_EXPR, NE_EXPR, GT_EXPR, LT_EXPR, GE_EXPR or LE_EXPR.  TYPE
6420    is the type of the result and ARG0 and ARG1 are the operands of the
6421    comparison.  ARG1 must be a TREE_REAL_CST.
6422
6423    The function returns the constant folded tree if a simplification
6424    can be made, and NULL_TREE otherwise.  */
6425
6426 static tree
6427 fold_mathfn_compare (location_t loc,
6428                      enum built_in_function fcode, enum tree_code code,
6429                      tree type, tree arg0, tree arg1)
6430 {
6431   REAL_VALUE_TYPE c;
6432
6433   if (BUILTIN_SQRT_P (fcode))
6434     {
6435       tree arg = CALL_EXPR_ARG (arg0, 0);
6436       machine_mode mode = TYPE_MODE (TREE_TYPE (arg0));
6437
6438       c = TREE_REAL_CST (arg1);
6439       if (REAL_VALUE_NEGATIVE (c))
6440         {
6441           /* sqrt(x) < y is always false, if y is negative.  */
6442           if (code == EQ_EXPR || code == LT_EXPR || code == LE_EXPR)
6443             return omit_one_operand_loc (loc, type, integer_zero_node, arg);
6444
6445           /* sqrt(x) > y is always true, if y is negative and we
6446              don't care about NaNs, i.e. negative values of x.  */
6447           if (code == NE_EXPR || !HONOR_NANS (mode))
6448             return omit_one_operand_loc (loc, type, integer_one_node, arg);
6449
6450           /* sqrt(x) > y is the same as x >= 0, if y is negative.  */
6451           return fold_build2_loc (loc, GE_EXPR, type, arg,
6452                               build_real (TREE_TYPE (arg), dconst0));
6453         }
6454       else if (code == GT_EXPR || code == GE_EXPR)
6455         {
6456           REAL_VALUE_TYPE c2;
6457
6458           REAL_ARITHMETIC (c2, MULT_EXPR, c, c);
6459           real_convert (&c2, mode, &c2);
6460
6461           if (REAL_VALUE_ISINF (c2))
6462             {
6463               /* sqrt(x) > y is x == +Inf, when y is very large.  */
6464               if (HONOR_INFINITIES (mode))
6465                 return fold_build2_loc (loc, EQ_EXPR, type, arg,
6466                                     build_real (TREE_TYPE (arg), c2));
6467
6468               /* sqrt(x) > y is always false, when y is very large
6469                  and we don't care about infinities.  */
6470               return omit_one_operand_loc (loc, type, integer_zero_node, arg);
6471             }
6472
6473           /* sqrt(x) > c is the same as x > c*c.  */
6474           return fold_build2_loc (loc, code, type, arg,
6475                               build_real (TREE_TYPE (arg), c2));
6476         }
6477       else if (code == LT_EXPR || code == LE_EXPR)
6478         {
6479           REAL_VALUE_TYPE c2;
6480
6481           REAL_ARITHMETIC (c2, MULT_EXPR, c, c);
6482           real_convert (&c2, mode, &c2);
6483
6484           if (REAL_VALUE_ISINF (c2))
6485             {
6486               /* sqrt(x) < y is always true, when y is a very large
6487                  value and we don't care about NaNs or Infinities.  */
6488               if (! HONOR_NANS (mode) && ! HONOR_INFINITIES (mode))
6489                 return omit_one_operand_loc (loc, type, integer_one_node, arg);
6490
6491               /* sqrt(x) < y is x != +Inf when y is very large and we
6492                  don't care about NaNs.  */
6493               if (! HONOR_NANS (mode))
6494                 return fold_build2_loc (loc, NE_EXPR, type, arg,
6495                                     build_real (TREE_TYPE (arg), c2));
6496
6497               /* sqrt(x) < y is x >= 0 when y is very large and we
6498                  don't care about Infinities.  */
6499               if (! HONOR_INFINITIES (mode))
6500                 return fold_build2_loc (loc, GE_EXPR, type, arg,
6501                                     build_real (TREE_TYPE (arg), dconst0));
6502
6503               /* sqrt(x) < y is x >= 0 && x != +Inf, when y is large.  */
6504               arg = save_expr (arg);
6505               return fold_build2_loc (loc, TRUTH_ANDIF_EXPR, type,
6506                                   fold_build2_loc (loc, GE_EXPR, type, arg,
6507                                                build_real (TREE_TYPE (arg),
6508                                                            dconst0)),
6509                                   fold_build2_loc (loc, NE_EXPR, type, arg,
6510                                                build_real (TREE_TYPE (arg),
6511                                                            c2)));
6512             }
6513
6514           /* sqrt(x) < c is the same as x < c*c, if we ignore NaNs.  */
6515           if (! HONOR_NANS (mode))
6516             return fold_build2_loc (loc, code, type, arg,
6517                                 build_real (TREE_TYPE (arg), c2));
6518
6519           /* sqrt(x) < c is the same as x >= 0 && x < c*c.  */
6520           arg = save_expr (arg);
6521           return fold_build2_loc (loc, TRUTH_ANDIF_EXPR, type,
6522                                   fold_build2_loc (loc, GE_EXPR, type, arg,
6523                                                build_real (TREE_TYPE (arg),
6524                                                            dconst0)),
6525                                   fold_build2_loc (loc, code, type, arg,
6526                                                build_real (TREE_TYPE (arg),
6527                                                            c2)));
6528         }
6529     }
6530
6531   return NULL_TREE;
6532 }
6533
6534 /* Subroutine of fold() that optimizes comparisons against Infinities,
6535    either +Inf or -Inf.
6536
6537    CODE is the comparison operator: EQ_EXPR, NE_EXPR, GT_EXPR, LT_EXPR,
6538    GE_EXPR or LE_EXPR.  TYPE is the type of the result and ARG0 and ARG1
6539    are the operands of the comparison.  ARG1 must be a TREE_REAL_CST.
6540
6541    The function returns the constant folded tree if a simplification
6542    can be made, and NULL_TREE otherwise.  */
6543
6544 static tree
6545 fold_inf_compare (location_t loc, enum tree_code code, tree type,
6546                   tree arg0, tree arg1)
6547 {
6548   machine_mode mode;
6549   REAL_VALUE_TYPE max;
6550   tree temp;
6551   bool neg;
6552
6553   mode = TYPE_MODE (TREE_TYPE (arg0));
6554
6555   /* For negative infinity swap the sense of the comparison.  */
6556   neg = REAL_VALUE_NEGATIVE (TREE_REAL_CST (arg1));
6557   if (neg)
6558     code = swap_tree_comparison (code);
6559
6560   switch (code)
6561     {
6562     case GT_EXPR:
6563       /* x > +Inf is always false, if with ignore sNANs.  */
6564       if (HONOR_SNANS (mode))
6565         return NULL_TREE;
6566       return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
6567
6568     case LE_EXPR:
6569       /* x <= +Inf is always true, if we don't case about NaNs.  */
6570       if (! HONOR_NANS (mode))
6571         return omit_one_operand_loc (loc, type, integer_one_node, arg0);
6572
6573       /* x <= +Inf is the same as x == x, i.e. isfinite(x).  */
6574       arg0 = save_expr (arg0);
6575       return fold_build2_loc (loc, EQ_EXPR, type, arg0, arg0);
6576
6577     case EQ_EXPR:
6578     case GE_EXPR:
6579       /* x == +Inf and x >= +Inf are always equal to x > DBL_MAX.  */
6580       real_maxval (&max, neg, mode);
6581       return fold_build2_loc (loc, neg ? LT_EXPR : GT_EXPR, type,
6582                           arg0, build_real (TREE_TYPE (arg0), max));
6583
6584     case LT_EXPR:
6585       /* x < +Inf is always equal to x <= DBL_MAX.  */
6586       real_maxval (&max, neg, mode);
6587       return fold_build2_loc (loc, neg ? GE_EXPR : LE_EXPR, type,
6588                           arg0, build_real (TREE_TYPE (arg0), max));
6589
6590     case NE_EXPR:
6591       /* x != +Inf is always equal to !(x > DBL_MAX).  */
6592       real_maxval (&max, neg, mode);
6593       if (! HONOR_NANS (mode))
6594         return fold_build2_loc (loc, neg ? GE_EXPR : LE_EXPR, type,
6595                             arg0, build_real (TREE_TYPE (arg0), max));
6596
6597       temp = fold_build2_loc (loc, neg ? LT_EXPR : GT_EXPR, type,
6598                           arg0, build_real (TREE_TYPE (arg0), max));
6599       return fold_build1_loc (loc, TRUTH_NOT_EXPR, type, temp);
6600
6601     default:
6602       break;
6603     }
6604
6605   return NULL_TREE;
6606 }
6607
6608 /* Subroutine of fold() that optimizes comparisons of a division by
6609    a nonzero integer constant against an integer constant, i.e.
6610    X/C1 op C2.
6611
6612    CODE is the comparison operator: EQ_EXPR, NE_EXPR, GT_EXPR, LT_EXPR,
6613    GE_EXPR or LE_EXPR.  TYPE is the type of the result and ARG0 and ARG1
6614    are the operands of the comparison.  ARG1 must be a TREE_REAL_CST.
6615
6616    The function returns the constant folded tree if a simplification
6617    can be made, and NULL_TREE otherwise.  */
6618
6619 static tree
6620 fold_div_compare (location_t loc,
6621                   enum tree_code code, tree type, tree arg0, tree arg1)
6622 {
6623   tree prod, tmp, hi, lo;
6624   tree arg00 = TREE_OPERAND (arg0, 0);
6625   tree arg01 = TREE_OPERAND (arg0, 1);
6626   signop sign = TYPE_SIGN (TREE_TYPE (arg0));
6627   bool neg_overflow = false;
6628   bool overflow;
6629
6630   /* We have to do this the hard way to detect unsigned overflow.
6631      prod = int_const_binop (MULT_EXPR, arg01, arg1);  */
6632   wide_int val = wi::mul (arg01, arg1, sign, &overflow);
6633   prod = force_fit_type (TREE_TYPE (arg00), val, -1, overflow);
6634   neg_overflow = false;
6635
6636   if (sign == UNSIGNED)
6637     {
6638       tmp = int_const_binop (MINUS_EXPR, arg01,
6639                              build_int_cst (TREE_TYPE (arg01), 1));
6640       lo = prod;
6641
6642       /* Likewise hi = int_const_binop (PLUS_EXPR, prod, tmp).  */
6643       val = wi::add (prod, tmp, sign, &overflow);
6644       hi = force_fit_type (TREE_TYPE (arg00), val,
6645                            -1, overflow | TREE_OVERFLOW (prod));
6646     }
6647   else if (tree_int_cst_sgn (arg01) >= 0)
6648     {
6649       tmp = int_const_binop (MINUS_EXPR, arg01,
6650                              build_int_cst (TREE_TYPE (arg01), 1));
6651       switch (tree_int_cst_sgn (arg1))
6652         {
6653         case -1:
6654           neg_overflow = true;
6655           lo = int_const_binop (MINUS_EXPR, prod, tmp);
6656           hi = prod;
6657           break;
6658
6659         case  0:
6660           lo = fold_negate_const (tmp, TREE_TYPE (arg0));
6661           hi = tmp;
6662           break;
6663
6664         case  1:
6665           hi = int_const_binop (PLUS_EXPR, prod, tmp);
6666           lo = prod;
6667           break;
6668
6669         default:
6670           gcc_unreachable ();
6671         }
6672     }
6673   else
6674     {
6675       /* A negative divisor reverses the relational operators.  */
6676       code = swap_tree_comparison (code);
6677
6678       tmp = int_const_binop (PLUS_EXPR, arg01,
6679                              build_int_cst (TREE_TYPE (arg01), 1));
6680       switch (tree_int_cst_sgn (arg1))
6681         {
6682         case -1:
6683           hi = int_const_binop (MINUS_EXPR, prod, tmp);
6684           lo = prod;
6685           break;
6686
6687         case  0:
6688           hi = fold_negate_const (tmp, TREE_TYPE (arg0));
6689           lo = tmp;
6690           break;
6691
6692         case  1:
6693           neg_overflow = true;
6694           lo = int_const_binop (PLUS_EXPR, prod, tmp);
6695           hi = prod;
6696           break;
6697
6698         default:
6699           gcc_unreachable ();
6700         }
6701     }
6702
6703   switch (code)
6704     {
6705     case EQ_EXPR:
6706       if (TREE_OVERFLOW (lo) && TREE_OVERFLOW (hi))
6707         return omit_one_operand_loc (loc, type, integer_zero_node, arg00);
6708       if (TREE_OVERFLOW (hi))
6709         return fold_build2_loc (loc, GE_EXPR, type, arg00, lo);
6710       if (TREE_OVERFLOW (lo))
6711         return fold_build2_loc (loc, LE_EXPR, type, arg00, hi);
6712       return build_range_check (loc, type, arg00, 1, lo, hi);
6713
6714     case NE_EXPR:
6715       if (TREE_OVERFLOW (lo) && TREE_OVERFLOW (hi))
6716         return omit_one_operand_loc (loc, type, integer_one_node, arg00);
6717       if (TREE_OVERFLOW (hi))
6718         return fold_build2_loc (loc, LT_EXPR, type, arg00, lo);
6719       if (TREE_OVERFLOW (lo))
6720         return fold_build2_loc (loc, GT_EXPR, type, arg00, hi);
6721       return build_range_check (loc, type, arg00, 0, lo, hi);
6722
6723     case LT_EXPR:
6724       if (TREE_OVERFLOW (lo))
6725         {
6726           tmp = neg_overflow ? integer_zero_node : integer_one_node;
6727           return omit_one_operand_loc (loc, type, tmp, arg00);
6728         }
6729       return fold_build2_loc (loc, LT_EXPR, type, arg00, lo);
6730
6731     case LE_EXPR:
6732       if (TREE_OVERFLOW (hi))
6733         {
6734           tmp = neg_overflow ? integer_zero_node : integer_one_node;
6735           return omit_one_operand_loc (loc, type, tmp, arg00);
6736         }
6737       return fold_build2_loc (loc, LE_EXPR, type, arg00, hi);
6738
6739     case GT_EXPR:
6740       if (TREE_OVERFLOW (hi))
6741         {
6742           tmp = neg_overflow ? integer_one_node : integer_zero_node;
6743           return omit_one_operand_loc (loc, type, tmp, arg00);
6744         }
6745       return fold_build2_loc (loc, GT_EXPR, type, arg00, hi);
6746
6747     case GE_EXPR:
6748       if (TREE_OVERFLOW (lo))
6749         {
6750           tmp = neg_overflow ? integer_one_node : integer_zero_node;
6751           return omit_one_operand_loc (loc, type, tmp, arg00);
6752         }
6753       return fold_build2_loc (loc, GE_EXPR, type, arg00, lo);
6754
6755     default:
6756       break;
6757     }
6758
6759   return NULL_TREE;
6760 }
6761
6762
6763 /* If CODE with arguments ARG0 and ARG1 represents a single bit
6764    equality/inequality test, then return a simplified form of the test
6765    using a sign testing.  Otherwise return NULL.  TYPE is the desired
6766    result type.  */
6767
6768 static tree
6769 fold_single_bit_test_into_sign_test (location_t loc,
6770                                      enum tree_code code, tree arg0, tree arg1,
6771                                      tree result_type)
6772 {
6773   /* If this is testing a single bit, we can optimize the test.  */
6774   if ((code == NE_EXPR || code == EQ_EXPR)
6775       && TREE_CODE (arg0) == BIT_AND_EXPR && integer_zerop (arg1)
6776       && integer_pow2p (TREE_OPERAND (arg0, 1)))
6777     {
6778       /* If we have (A & C) != 0 where C is the sign bit of A, convert
6779          this into A < 0.  Similarly for (A & C) == 0 into A >= 0.  */
6780       tree arg00 = sign_bit_p (TREE_OPERAND (arg0, 0), TREE_OPERAND (arg0, 1));
6781
6782       if (arg00 != NULL_TREE
6783           /* This is only a win if casting to a signed type is cheap,
6784              i.e. when arg00's type is not a partial mode.  */
6785           && TYPE_PRECISION (TREE_TYPE (arg00))
6786              == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (arg00))))
6787         {
6788           tree stype = signed_type_for (TREE_TYPE (arg00));
6789           return fold_build2_loc (loc, code == EQ_EXPR ? GE_EXPR : LT_EXPR,
6790                               result_type,
6791                               fold_convert_loc (loc, stype, arg00),
6792                               build_int_cst (stype, 0));
6793         }
6794     }
6795
6796   return NULL_TREE;
6797 }
6798
6799 /* If CODE with arguments ARG0 and ARG1 represents a single bit
6800    equality/inequality test, then return a simplified form of
6801    the test using shifts and logical operations.  Otherwise return
6802    NULL.  TYPE is the desired result type.  */
6803
6804 tree
6805 fold_single_bit_test (location_t loc, enum tree_code code,
6806                       tree arg0, tree arg1, tree result_type)
6807 {
6808   /* If this is testing a single bit, we can optimize the test.  */
6809   if ((code == NE_EXPR || code == EQ_EXPR)
6810       && TREE_CODE (arg0) == BIT_AND_EXPR && integer_zerop (arg1)
6811       && integer_pow2p (TREE_OPERAND (arg0, 1)))
6812     {
6813       tree inner = TREE_OPERAND (arg0, 0);
6814       tree type = TREE_TYPE (arg0);
6815       int bitnum = tree_log2 (TREE_OPERAND (arg0, 1));
6816       machine_mode operand_mode = TYPE_MODE (type);
6817       int ops_unsigned;
6818       tree signed_type, unsigned_type, intermediate_type;
6819       tree tem, one;
6820
6821       /* First, see if we can fold the single bit test into a sign-bit
6822          test.  */
6823       tem = fold_single_bit_test_into_sign_test (loc, code, arg0, arg1,
6824                                                  result_type);
6825       if (tem)
6826         return tem;
6827
6828       /* Otherwise we have (A & C) != 0 where C is a single bit,
6829          convert that into ((A >> C2) & 1).  Where C2 = log2(C).
6830          Similarly for (A & C) == 0.  */
6831
6832       /* If INNER is a right shift of a constant and it plus BITNUM does
6833          not overflow, adjust BITNUM and INNER.  */
6834       if (TREE_CODE (inner) == RSHIFT_EXPR
6835           && TREE_CODE (TREE_OPERAND (inner, 1)) == INTEGER_CST
6836           && bitnum < TYPE_PRECISION (type)
6837           && wi::ltu_p (TREE_OPERAND (inner, 1),
6838                         TYPE_PRECISION (type) - bitnum))
6839         {
6840           bitnum += tree_to_uhwi (TREE_OPERAND (inner, 1));
6841           inner = TREE_OPERAND (inner, 0);
6842         }
6843
6844       /* If we are going to be able to omit the AND below, we must do our
6845          operations as unsigned.  If we must use the AND, we have a choice.
6846          Normally unsigned is faster, but for some machines signed is.  */
6847 #ifdef LOAD_EXTEND_OP
6848       ops_unsigned = (LOAD_EXTEND_OP (operand_mode) == SIGN_EXTEND
6849                       && !flag_syntax_only) ? 0 : 1;
6850 #else
6851       ops_unsigned = 1;
6852 #endif
6853
6854       signed_type = lang_hooks.types.type_for_mode (operand_mode, 0);
6855       unsigned_type = lang_hooks.types.type_for_mode (operand_mode, 1);
6856       intermediate_type = ops_unsigned ? unsigned_type : signed_type;
6857       inner = fold_convert_loc (loc, intermediate_type, inner);
6858
6859       if (bitnum != 0)
6860         inner = build2 (RSHIFT_EXPR, intermediate_type,
6861                         inner, size_int (bitnum));
6862
6863       one = build_int_cst (intermediate_type, 1);
6864
6865       if (code == EQ_EXPR)
6866         inner = fold_build2_loc (loc, BIT_XOR_EXPR, intermediate_type, inner, one);
6867
6868       /* Put the AND last so it can combine with more things.  */
6869       inner = build2 (BIT_AND_EXPR, intermediate_type, inner, one);
6870
6871       /* Make sure to return the proper type.  */
6872       inner = fold_convert_loc (loc, result_type, inner);
6873
6874       return inner;
6875     }
6876   return NULL_TREE;
6877 }
6878
6879 /* Check whether we are allowed to reorder operands arg0 and arg1,
6880    such that the evaluation of arg1 occurs before arg0.  */
6881
6882 static bool
6883 reorder_operands_p (const_tree arg0, const_tree arg1)
6884 {
6885   if (! flag_evaluation_order)
6886       return true;
6887   if (TREE_CONSTANT (arg0) || TREE_CONSTANT (arg1))
6888     return true;
6889   return ! TREE_SIDE_EFFECTS (arg0)
6890          && ! TREE_SIDE_EFFECTS (arg1);
6891 }
6892
6893 /* Test whether it is preferable two swap two operands, ARG0 and
6894    ARG1, for example because ARG0 is an integer constant and ARG1
6895    isn't.  If REORDER is true, only recommend swapping if we can
6896    evaluate the operands in reverse order.  */
6897
6898 bool
6899 tree_swap_operands_p (const_tree arg0, const_tree arg1, bool reorder)
6900 {
6901   if (CONSTANT_CLASS_P (arg1))
6902     return 0;
6903   if (CONSTANT_CLASS_P (arg0))
6904     return 1;
6905
6906   STRIP_NOPS (arg0);
6907   STRIP_NOPS (arg1);
6908
6909   if (TREE_CONSTANT (arg1))
6910     return 0;
6911   if (TREE_CONSTANT (arg0))
6912     return 1;
6913
6914   if (reorder && flag_evaluation_order
6915       && (TREE_SIDE_EFFECTS (arg0) || TREE_SIDE_EFFECTS (arg1)))
6916     return 0;
6917
6918   /* It is preferable to swap two SSA_NAME to ensure a canonical form
6919      for commutative and comparison operators.  Ensuring a canonical
6920      form allows the optimizers to find additional redundancies without
6921      having to explicitly check for both orderings.  */
6922   if (TREE_CODE (arg0) == SSA_NAME
6923       && TREE_CODE (arg1) == SSA_NAME
6924       && SSA_NAME_VERSION (arg0) > SSA_NAME_VERSION (arg1))
6925     return 1;
6926
6927   /* Put SSA_NAMEs last.  */
6928   if (TREE_CODE (arg1) == SSA_NAME)
6929     return 0;
6930   if (TREE_CODE (arg0) == SSA_NAME)
6931     return 1;
6932
6933   /* Put variables last.  */
6934   if (DECL_P (arg1))
6935     return 0;
6936   if (DECL_P (arg0))
6937     return 1;
6938
6939   return 0;
6940 }
6941
6942 /* Fold comparison ARG0 CODE ARG1 (with result in TYPE), where
6943    ARG0 is extended to a wider type.  */
6944
6945 static tree
6946 fold_widened_comparison (location_t loc, enum tree_code code,
6947                          tree type, tree arg0, tree arg1)
6948 {
6949   tree arg0_unw = get_unwidened (arg0, NULL_TREE);
6950   tree arg1_unw;
6951   tree shorter_type, outer_type;
6952   tree min, max;
6953   bool above, below;
6954
6955   if (arg0_unw == arg0)
6956     return NULL_TREE;
6957   shorter_type = TREE_TYPE (arg0_unw);
6958
6959 #ifdef HAVE_canonicalize_funcptr_for_compare
6960   /* Disable this optimization if we're casting a function pointer
6961      type on targets that require function pointer canonicalization.  */
6962   if (HAVE_canonicalize_funcptr_for_compare
6963       && TREE_CODE (shorter_type) == POINTER_TYPE
6964       && TREE_CODE (TREE_TYPE (shorter_type)) == FUNCTION_TYPE)
6965     return NULL_TREE;
6966 #endif
6967
6968   if (TYPE_PRECISION (TREE_TYPE (arg0)) <= TYPE_PRECISION (shorter_type))
6969     return NULL_TREE;
6970
6971   arg1_unw = get_unwidened (arg1, NULL_TREE);
6972
6973   /* If possible, express the comparison in the shorter mode.  */
6974   if ((code == EQ_EXPR || code == NE_EXPR
6975        || TYPE_UNSIGNED (TREE_TYPE (arg0)) == TYPE_UNSIGNED (shorter_type))
6976       && (TREE_TYPE (arg1_unw) == shorter_type
6977           || ((TYPE_PRECISION (shorter_type)
6978                >= TYPE_PRECISION (TREE_TYPE (arg1_unw)))
6979               && (TYPE_UNSIGNED (shorter_type)
6980                   == TYPE_UNSIGNED (TREE_TYPE (arg1_unw))))
6981           || (TREE_CODE (arg1_unw) == INTEGER_CST
6982               && (TREE_CODE (shorter_type) == INTEGER_TYPE
6983                   || TREE_CODE (shorter_type) == BOOLEAN_TYPE)
6984               && int_fits_type_p (arg1_unw, shorter_type))))
6985     return fold_build2_loc (loc, code, type, arg0_unw,
6986                         fold_convert_loc (loc, shorter_type, arg1_unw));
6987
6988   if (TREE_CODE (arg1_unw) != INTEGER_CST
6989       || TREE_CODE (shorter_type) != INTEGER_TYPE
6990       || !int_fits_type_p (arg1_unw, shorter_type))
6991     return NULL_TREE;
6992
6993   /* If we are comparing with the integer that does not fit into the range
6994      of the shorter type, the result is known.  */
6995   outer_type = TREE_TYPE (arg1_unw);
6996   min = lower_bound_in_type (outer_type, shorter_type);
6997   max = upper_bound_in_type (outer_type, shorter_type);
6998
6999   above = integer_nonzerop (fold_relational_const (LT_EXPR, type,
7000                                                    max, arg1_unw));
7001   below = integer_nonzerop (fold_relational_const (LT_EXPR, type,
7002                                                    arg1_unw, min));
7003
7004   switch (code)
7005     {
7006     case EQ_EXPR:
7007       if (above || below)
7008         return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
7009       break;
7010
7011     case NE_EXPR:
7012       if (above || below)
7013         return omit_one_operand_loc (loc, type, integer_one_node, arg0);
7014       break;
7015
7016     case LT_EXPR:
7017     case LE_EXPR:
7018       if (above)
7019         return omit_one_operand_loc (loc, type, integer_one_node, arg0);
7020       else if (below)
7021         return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
7022
7023     case GT_EXPR:
7024     case GE_EXPR:
7025       if (above)
7026         return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
7027       else if (below)
7028         return omit_one_operand_loc (loc, type, integer_one_node, arg0);
7029
7030     default:
7031       break;
7032     }
7033
7034   return NULL_TREE;
7035 }
7036
7037 /* Fold comparison ARG0 CODE ARG1 (with result in TYPE), where for
7038    ARG0 just the signedness is changed.  */
7039
7040 static tree
7041 fold_sign_changed_comparison (location_t loc, enum tree_code code, tree type,
7042                               tree arg0, tree arg1)
7043 {
7044   tree arg0_inner;
7045   tree inner_type, outer_type;
7046
7047   if (!CONVERT_EXPR_P (arg0))
7048     return NULL_TREE;
7049
7050   outer_type = TREE_TYPE (arg0);
7051   arg0_inner = TREE_OPERAND (arg0, 0);
7052   inner_type = TREE_TYPE (arg0_inner);
7053
7054 #ifdef HAVE_canonicalize_funcptr_for_compare
7055   /* Disable this optimization if we're casting a function pointer
7056      type on targets that require function pointer canonicalization.  */
7057   if (HAVE_canonicalize_funcptr_for_compare
7058       && TREE_CODE (inner_type) == POINTER_TYPE
7059       && TREE_CODE (TREE_TYPE (inner_type)) == FUNCTION_TYPE)
7060     return NULL_TREE;
7061 #endif
7062
7063   if (TYPE_PRECISION (inner_type) != TYPE_PRECISION (outer_type))
7064     return NULL_TREE;
7065
7066   if (TREE_CODE (arg1) != INTEGER_CST
7067       && !(CONVERT_EXPR_P (arg1)
7068            && TREE_TYPE (TREE_OPERAND (arg1, 0)) == inner_type))
7069     return NULL_TREE;
7070
7071   if (TYPE_UNSIGNED (inner_type) != TYPE_UNSIGNED (outer_type)
7072       && code != NE_EXPR
7073       && code != EQ_EXPR)
7074     return NULL_TREE;
7075
7076   if (POINTER_TYPE_P (inner_type) != POINTER_TYPE_P (outer_type))
7077     return NULL_TREE;
7078
7079   if (TREE_CODE (arg1) == INTEGER_CST)
7080     arg1 = force_fit_type (inner_type, wi::to_widest (arg1), 0,
7081                            TREE_OVERFLOW (arg1));
7082   else
7083     arg1 = fold_convert_loc (loc, inner_type, arg1);
7084
7085   return fold_build2_loc (loc, code, type, arg0_inner, arg1);
7086 }
7087
7088
7089 /* Fold A < X && A + 1 > Y to A < X && A >= Y.  Normally A + 1 > Y
7090    means A >= Y && A != MAX, but in this case we know that
7091    A < X <= MAX.  INEQ is A + 1 > Y, BOUND is A < X.  */
7092
7093 static tree
7094 fold_to_nonsharp_ineq_using_bound (location_t loc, tree ineq, tree bound)
7095 {
7096   tree a, typea, type = TREE_TYPE (ineq), a1, diff, y;
7097
7098   if (TREE_CODE (bound) == LT_EXPR)
7099     a = TREE_OPERAND (bound, 0);
7100   else if (TREE_CODE (bound) == GT_EXPR)
7101     a = TREE_OPERAND (bound, 1);
7102   else
7103     return NULL_TREE;
7104
7105   typea = TREE_TYPE (a);
7106   if (!INTEGRAL_TYPE_P (typea)
7107       && !POINTER_TYPE_P (typea))
7108     return NULL_TREE;
7109
7110   if (TREE_CODE (ineq) == LT_EXPR)
7111     {
7112       a1 = TREE_OPERAND (ineq, 1);
7113       y = TREE_OPERAND (ineq, 0);
7114     }
7115   else if (TREE_CODE (ineq) == GT_EXPR)
7116     {
7117       a1 = TREE_OPERAND (ineq, 0);
7118       y = TREE_OPERAND (ineq, 1);
7119     }
7120   else
7121     return NULL_TREE;
7122
7123   if (TREE_TYPE (a1) != typea)
7124     return NULL_TREE;
7125
7126   if (POINTER_TYPE_P (typea))
7127     {
7128       /* Convert the pointer types into integer before taking the difference.  */
7129       tree ta = fold_convert_loc (loc, ssizetype, a);
7130       tree ta1 = fold_convert_loc (loc, ssizetype, a1);
7131       diff = fold_binary_loc (loc, MINUS_EXPR, ssizetype, ta1, ta);
7132     }
7133   else
7134     diff = fold_binary_loc (loc, MINUS_EXPR, typea, a1, a);
7135
7136   if (!diff || !integer_onep (diff))
7137    return NULL_TREE;
7138
7139   return fold_build2_loc (loc, GE_EXPR, type, a, y);
7140 }
7141
7142 /* Fold a sum or difference of at least one multiplication.
7143    Returns the folded tree or NULL if no simplification could be made.  */
7144
7145 static tree
7146 fold_plusminus_mult_expr (location_t loc, enum tree_code code, tree type,
7147                           tree arg0, tree arg1)
7148 {
7149   tree arg00, arg01, arg10, arg11;
7150   tree alt0 = NULL_TREE, alt1 = NULL_TREE, same;
7151
7152   /* (A * C) +- (B * C) -> (A+-B) * C.
7153      (A * C) +- A -> A * (C+-1).
7154      We are most concerned about the case where C is a constant,
7155      but other combinations show up during loop reduction.  Since
7156      it is not difficult, try all four possibilities.  */
7157
7158   if (TREE_CODE (arg0) == MULT_EXPR)
7159     {
7160       arg00 = TREE_OPERAND (arg0, 0);
7161       arg01 = TREE_OPERAND (arg0, 1);
7162     }
7163   else if (TREE_CODE (arg0) == INTEGER_CST)
7164     {
7165       arg00 = build_one_cst (type);
7166       arg01 = arg0;
7167     }
7168   else
7169     {
7170       /* We cannot generate constant 1 for fract.  */
7171       if (ALL_FRACT_MODE_P (TYPE_MODE (type)))
7172         return NULL_TREE;
7173       arg00 = arg0;
7174       arg01 = build_one_cst (type);
7175     }
7176   if (TREE_CODE (arg1) == MULT_EXPR)
7177     {
7178       arg10 = TREE_OPERAND (arg1, 0);
7179       arg11 = TREE_OPERAND (arg1, 1);
7180     }
7181   else if (TREE_CODE (arg1) == INTEGER_CST)
7182     {
7183       arg10 = build_one_cst (type);
7184       /* As we canonicalize A - 2 to A + -2 get rid of that sign for
7185          the purpose of this canonicalization.  */
7186       if (wi::neg_p (arg1, TYPE_SIGN (TREE_TYPE (arg1)))
7187           && negate_expr_p (arg1)
7188           && code == PLUS_EXPR)
7189         {
7190           arg11 = negate_expr (arg1);
7191           code = MINUS_EXPR;
7192         }
7193       else
7194         arg11 = arg1;
7195     }
7196   else
7197     {
7198       /* We cannot generate constant 1 for fract.  */
7199       if (ALL_FRACT_MODE_P (TYPE_MODE (type)))
7200         return NULL_TREE;
7201       arg10 = arg1;
7202       arg11 = build_one_cst (type);
7203     }
7204   same = NULL_TREE;
7205
7206   if (operand_equal_p (arg01, arg11, 0))
7207     same = arg01, alt0 = arg00, alt1 = arg10;
7208   else if (operand_equal_p (arg00, arg10, 0))
7209     same = arg00, alt0 = arg01, alt1 = arg11;
7210   else if (operand_equal_p (arg00, arg11, 0))
7211     same = arg00, alt0 = arg01, alt1 = arg10;
7212   else if (operand_equal_p (arg01, arg10, 0))
7213     same = arg01, alt0 = arg00, alt1 = arg11;
7214
7215   /* No identical multiplicands; see if we can find a common
7216      power-of-two factor in non-power-of-two multiplies.  This
7217      can help in multi-dimensional array access.  */
7218   else if (tree_fits_shwi_p (arg01)
7219            && tree_fits_shwi_p (arg11))
7220     {
7221       HOST_WIDE_INT int01, int11, tmp;
7222       bool swap = false;
7223       tree maybe_same;
7224       int01 = tree_to_shwi (arg01);
7225       int11 = tree_to_shwi (arg11);
7226
7227       /* Move min of absolute values to int11.  */
7228       if (absu_hwi (int01) < absu_hwi (int11))
7229         {
7230           tmp = int01, int01 = int11, int11 = tmp;
7231           alt0 = arg00, arg00 = arg10, arg10 = alt0;
7232           maybe_same = arg01;
7233           swap = true;
7234         }
7235       else
7236         maybe_same = arg11;
7237
7238       if (exact_log2 (absu_hwi (int11)) > 0 && int01 % int11 == 0
7239           /* The remainder should not be a constant, otherwise we
7240              end up folding i * 4 + 2 to (i * 2 + 1) * 2 which has
7241              increased the number of multiplications necessary.  */
7242           && TREE_CODE (arg10) != INTEGER_CST)
7243         {
7244           alt0 = fold_build2_loc (loc, MULT_EXPR, TREE_TYPE (arg00), arg00,
7245                               build_int_cst (TREE_TYPE (arg00),
7246                                              int01 / int11));
7247           alt1 = arg10;
7248           same = maybe_same;
7249           if (swap)
7250             maybe_same = alt0, alt0 = alt1, alt1 = maybe_same;
7251         }
7252     }
7253
7254   if (same)
7255     return fold_build2_loc (loc, MULT_EXPR, type,
7256                         fold_build2_loc (loc, code, type,
7257                                      fold_convert_loc (loc, type, alt0),
7258                                      fold_convert_loc (loc, type, alt1)),
7259                         fold_convert_loc (loc, type, same));
7260
7261   return NULL_TREE;
7262 }
7263
7264 /* Subroutine of native_encode_expr.  Encode the INTEGER_CST
7265    specified by EXPR into the buffer PTR of length LEN bytes.
7266    Return the number of bytes placed in the buffer, or zero
7267    upon failure.  */
7268
7269 static int
7270 native_encode_int (const_tree expr, unsigned char *ptr, int len, int off)
7271 {
7272   tree type = TREE_TYPE (expr);
7273   int total_bytes = GET_MODE_SIZE (TYPE_MODE (type));
7274   int byte, offset, word, words;
7275   unsigned char value;
7276
7277   if ((off == -1 && total_bytes > len)
7278       || off >= total_bytes)
7279     return 0;
7280   if (off == -1)
7281     off = 0;
7282   words = total_bytes / UNITS_PER_WORD;
7283
7284   for (byte = 0; byte < total_bytes; byte++)
7285     {
7286       int bitpos = byte * BITS_PER_UNIT;
7287       /* Extend EXPR according to TYPE_SIGN if the precision isn't a whole
7288          number of bytes.  */
7289       value = wi::extract_uhwi (wi::to_widest (expr), bitpos, BITS_PER_UNIT);
7290
7291       if (total_bytes > UNITS_PER_WORD)
7292         {
7293           word = byte / UNITS_PER_WORD;
7294           if (WORDS_BIG_ENDIAN)
7295             word = (words - 1) - word;
7296           offset = word * UNITS_PER_WORD;
7297           if (BYTES_BIG_ENDIAN)
7298             offset += (UNITS_PER_WORD - 1) - (byte % UNITS_PER_WORD);
7299           else
7300             offset += byte % UNITS_PER_WORD;
7301         }
7302       else
7303         offset = BYTES_BIG_ENDIAN ? (total_bytes - 1) - byte : byte;
7304       if (offset >= off
7305           && offset - off < len)
7306         ptr[offset - off] = value;
7307     }
7308   return MIN (len, total_bytes - off);
7309 }
7310
7311
7312 /* Subroutine of native_encode_expr.  Encode the FIXED_CST
7313    specified by EXPR into the buffer PTR of length LEN bytes.
7314    Return the number of bytes placed in the buffer, or zero
7315    upon failure.  */
7316
7317 static int
7318 native_encode_fixed (const_tree expr, unsigned char *ptr, int len, int off)
7319 {
7320   tree type = TREE_TYPE (expr);
7321   machine_mode mode = TYPE_MODE (type);
7322   int total_bytes = GET_MODE_SIZE (mode);
7323   FIXED_VALUE_TYPE value;
7324   tree i_value, i_type;
7325
7326   if (total_bytes * BITS_PER_UNIT > HOST_BITS_PER_DOUBLE_INT)
7327     return 0;
7328
7329   i_type = lang_hooks.types.type_for_size (GET_MODE_BITSIZE (mode), 1);
7330
7331   if (NULL_TREE == i_type
7332       || TYPE_PRECISION (i_type) != total_bytes)
7333     return 0;
7334   
7335   value = TREE_FIXED_CST (expr);
7336   i_value = double_int_to_tree (i_type, value.data);
7337
7338   return native_encode_int (i_value, ptr, len, off);
7339 }
7340
7341
7342 /* Subroutine of native_encode_expr.  Encode the REAL_CST
7343    specified by EXPR into the buffer PTR of length LEN bytes.
7344    Return the number of bytes placed in the buffer, or zero
7345    upon failure.  */
7346
7347 static int
7348 native_encode_real (const_tree expr, unsigned char *ptr, int len, int off)
7349 {
7350   tree type = TREE_TYPE (expr);
7351   int total_bytes = GET_MODE_SIZE (TYPE_MODE (type));
7352   int byte, offset, word, words, bitpos;
7353   unsigned char value;
7354
7355   /* There are always 32 bits in each long, no matter the size of
7356      the hosts long.  We handle floating point representations with
7357      up to 192 bits.  */
7358   long tmp[6];
7359
7360   if ((off == -1 && total_bytes > len)
7361       || off >= total_bytes)
7362     return 0;
7363   if (off == -1)
7364     off = 0;
7365   words = (32 / BITS_PER_UNIT) / UNITS_PER_WORD;
7366
7367   real_to_target (tmp, TREE_REAL_CST_PTR (expr), TYPE_MODE (type));
7368
7369   for (bitpos = 0; bitpos < total_bytes * BITS_PER_UNIT;
7370        bitpos += BITS_PER_UNIT)
7371     {
7372       byte = (bitpos / BITS_PER_UNIT) & 3;
7373       value = (unsigned char) (tmp[bitpos / 32] >> (bitpos & 31));
7374
7375       if (UNITS_PER_WORD < 4)
7376         {
7377           word = byte / UNITS_PER_WORD;
7378           if (WORDS_BIG_ENDIAN)
7379             word = (words - 1) - word;
7380           offset = word * UNITS_PER_WORD;
7381           if (BYTES_BIG_ENDIAN)
7382             offset += (UNITS_PER_WORD - 1) - (byte % UNITS_PER_WORD);
7383           else
7384             offset += byte % UNITS_PER_WORD;
7385         }
7386       else
7387         offset = BYTES_BIG_ENDIAN ? 3 - byte : byte;
7388       offset = offset + ((bitpos / BITS_PER_UNIT) & ~3);
7389       if (offset >= off
7390           && offset - off < len)
7391         ptr[offset - off] = value;
7392     }
7393   return MIN (len, total_bytes - off);
7394 }
7395
7396 /* Subroutine of native_encode_expr.  Encode the COMPLEX_CST
7397    specified by EXPR into the buffer PTR of length LEN bytes.
7398    Return the number of bytes placed in the buffer, or zero
7399    upon failure.  */
7400
7401 static int
7402 native_encode_complex (const_tree expr, unsigned char *ptr, int len, int off)
7403 {
7404   int rsize, isize;
7405   tree part;
7406
7407   part = TREE_REALPART (expr);
7408   rsize = native_encode_expr (part, ptr, len, off);
7409   if (off == -1
7410       && rsize == 0)
7411     return 0;
7412   part = TREE_IMAGPART (expr);
7413   if (off != -1)
7414     off = MAX (0, off - GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (part))));
7415   isize = native_encode_expr (part, ptr+rsize, len-rsize, off);
7416   if (off == -1
7417       && isize != rsize)
7418     return 0;
7419   return rsize + isize;
7420 }
7421
7422
7423 /* Subroutine of native_encode_expr.  Encode the VECTOR_CST
7424    specified by EXPR into the buffer PTR of length LEN bytes.
7425    Return the number of bytes placed in the buffer, or zero
7426    upon failure.  */
7427
7428 static int
7429 native_encode_vector (const_tree expr, unsigned char *ptr, int len, int off)
7430 {
7431   unsigned i, count;
7432   int size, offset;
7433   tree itype, elem;
7434
7435   offset = 0;
7436   count = VECTOR_CST_NELTS (expr);
7437   itype = TREE_TYPE (TREE_TYPE (expr));
7438   size = GET_MODE_SIZE (TYPE_MODE (itype));
7439   for (i = 0; i < count; i++)
7440     {
7441       if (off >= size)
7442         {
7443           off -= size;
7444           continue;
7445         }
7446       elem = VECTOR_CST_ELT (expr, i);
7447       int res = native_encode_expr (elem, ptr+offset, len-offset, off);
7448       if ((off == -1 && res != size)
7449           || res == 0)
7450         return 0;
7451       offset += res;
7452       if (offset >= len)
7453         return offset;
7454       if (off != -1)
7455         off = 0;
7456     }
7457   return offset;
7458 }
7459
7460
7461 /* Subroutine of native_encode_expr.  Encode the STRING_CST
7462    specified by EXPR into the buffer PTR of length LEN bytes.
7463    Return the number of bytes placed in the buffer, or zero
7464    upon failure.  */
7465
7466 static int
7467 native_encode_string (const_tree expr, unsigned char *ptr, int len, int off)
7468 {
7469   tree type = TREE_TYPE (expr);
7470   HOST_WIDE_INT total_bytes;
7471
7472   if (TREE_CODE (type) != ARRAY_TYPE
7473       || TREE_CODE (TREE_TYPE (type)) != INTEGER_TYPE
7474       || GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (type))) != BITS_PER_UNIT
7475       || !tree_fits_shwi_p (TYPE_SIZE_UNIT (type)))
7476     return 0;
7477   total_bytes = tree_to_shwi (TYPE_SIZE_UNIT (type));
7478   if ((off == -1 && total_bytes > len)
7479       || off >= total_bytes)
7480     return 0;
7481   if (off == -1)
7482     off = 0;
7483   if (TREE_STRING_LENGTH (expr) - off < MIN (total_bytes, len))
7484     {
7485       int written = 0;
7486       if (off < TREE_STRING_LENGTH (expr))
7487         {
7488           written = MIN (len, TREE_STRING_LENGTH (expr) - off);
7489           memcpy (ptr, TREE_STRING_POINTER (expr) + off, written);
7490         }
7491       memset (ptr + written, 0,
7492               MIN (total_bytes - written, len - written));
7493     }
7494   else
7495     memcpy (ptr, TREE_STRING_POINTER (expr) + off, MIN (total_bytes, len));
7496   return MIN (total_bytes - off, len);
7497 }
7498
7499
7500 /* Subroutine of fold_view_convert_expr.  Encode the INTEGER_CST,
7501    REAL_CST, COMPLEX_CST or VECTOR_CST specified by EXPR into the
7502    buffer PTR of length LEN bytes.  If OFF is not -1 then start
7503    the encoding at byte offset OFF and encode at most LEN bytes.
7504    Return the number of bytes placed in the buffer, or zero upon failure.  */
7505
7506 int
7507 native_encode_expr (const_tree expr, unsigned char *ptr, int len, int off)
7508 {
7509   switch (TREE_CODE (expr))
7510     {
7511     case INTEGER_CST:
7512       return native_encode_int (expr, ptr, len, off);
7513
7514     case REAL_CST:
7515       return native_encode_real (expr, ptr, len, off);
7516
7517     case FIXED_CST:
7518       return native_encode_fixed (expr, ptr, len, off);
7519
7520     case COMPLEX_CST:
7521       return native_encode_complex (expr, ptr, len, off);
7522
7523     case VECTOR_CST:
7524       return native_encode_vector (expr, ptr, len, off);
7525
7526     case STRING_CST:
7527       return native_encode_string (expr, ptr, len, off);
7528
7529     default:
7530       return 0;
7531     }
7532 }
7533
7534
7535 /* Subroutine of native_interpret_expr.  Interpret the contents of
7536    the buffer PTR of length LEN as an INTEGER_CST of type TYPE.
7537    If the buffer cannot be interpreted, return NULL_TREE.  */
7538
7539 static tree
7540 native_interpret_int (tree type, const unsigned char *ptr, int len)
7541 {
7542   int total_bytes = GET_MODE_SIZE (TYPE_MODE (type));
7543
7544   if (total_bytes > len
7545       || total_bytes * BITS_PER_UNIT > HOST_BITS_PER_DOUBLE_INT)
7546     return NULL_TREE;
7547
7548   wide_int result = wi::from_buffer (ptr, total_bytes);
7549
7550   return wide_int_to_tree (type, result);
7551 }
7552
7553
7554 /* Subroutine of native_interpret_expr.  Interpret the contents of
7555    the buffer PTR of length LEN as a FIXED_CST of type TYPE.
7556    If the buffer cannot be interpreted, return NULL_TREE.  */
7557
7558 static tree
7559 native_interpret_fixed (tree type, const unsigned char *ptr, int len)
7560 {
7561   int total_bytes = GET_MODE_SIZE (TYPE_MODE (type));
7562   double_int result;
7563   FIXED_VALUE_TYPE fixed_value;
7564
7565   if (total_bytes > len
7566       || total_bytes * BITS_PER_UNIT > HOST_BITS_PER_DOUBLE_INT)
7567     return NULL_TREE;
7568
7569   result = double_int::from_buffer (ptr, total_bytes);
7570   fixed_value = fixed_from_double_int (result, TYPE_MODE (type));
7571
7572   return build_fixed (type, fixed_value);
7573 }
7574
7575
7576 /* Subroutine of native_interpret_expr.  Interpret the contents of
7577    the buffer PTR of length LEN as a REAL_CST of type TYPE.
7578    If the buffer cannot be interpreted, return NULL_TREE.  */
7579
7580 static tree
7581 native_interpret_real (tree type, const unsigned char *ptr, int len)
7582 {
7583   machine_mode mode = TYPE_MODE (type);
7584   int total_bytes = GET_MODE_SIZE (mode);
7585   int byte, offset, word, words, bitpos;
7586   unsigned char value;
7587   /* There are always 32 bits in each long, no matter the size of
7588      the hosts long.  We handle floating point representations with
7589      up to 192 bits.  */
7590   REAL_VALUE_TYPE r;
7591   long tmp[6];
7592
7593   total_bytes = GET_MODE_SIZE (TYPE_MODE (type));
7594   if (total_bytes > len || total_bytes > 24)
7595     return NULL_TREE;
7596   words = (32 / BITS_PER_UNIT) / UNITS_PER_WORD;
7597
7598   memset (tmp, 0, sizeof (tmp));
7599   for (bitpos = 0; bitpos < total_bytes * BITS_PER_UNIT;
7600        bitpos += BITS_PER_UNIT)
7601     {
7602       byte = (bitpos / BITS_PER_UNIT) & 3;
7603       if (UNITS_PER_WORD < 4)
7604         {
7605           word = byte / UNITS_PER_WORD;
7606           if (WORDS_BIG_ENDIAN)
7607             word = (words - 1) - word;
7608           offset = word * UNITS_PER_WORD;
7609           if (BYTES_BIG_ENDIAN)
7610             offset += (UNITS_PER_WORD - 1) - (byte % UNITS_PER_WORD);
7611           else
7612             offset += byte % UNITS_PER_WORD;
7613         }
7614       else
7615         offset = BYTES_BIG_ENDIAN ? 3 - byte : byte;
7616       value = ptr[offset + ((bitpos / BITS_PER_UNIT) & ~3)];
7617
7618       tmp[bitpos / 32] |= (unsigned long)value << (bitpos & 31);
7619     }
7620
7621   real_from_target (&r, tmp, mode);
7622   return build_real (type, r);
7623 }
7624
7625
7626 /* Subroutine of native_interpret_expr.  Interpret the contents of
7627    the buffer PTR of length LEN as a COMPLEX_CST of type TYPE.
7628    If the buffer cannot be interpreted, return NULL_TREE.  */
7629
7630 static tree
7631 native_interpret_complex (tree type, const unsigned char *ptr, int len)
7632 {
7633   tree etype, rpart, ipart;
7634   int size;
7635
7636   etype = TREE_TYPE (type);
7637   size = GET_MODE_SIZE (TYPE_MODE (etype));
7638   if (size * 2 > len)
7639     return NULL_TREE;
7640   rpart = native_interpret_expr (etype, ptr, size);
7641   if (!rpart)
7642     return NULL_TREE;
7643   ipart = native_interpret_expr (etype, ptr+size, size);
7644   if (!ipart)
7645     return NULL_TREE;
7646   return build_complex (type, rpart, ipart);
7647 }
7648
7649
7650 /* Subroutine of native_interpret_expr.  Interpret the contents of
7651    the buffer PTR of length LEN as a VECTOR_CST of type TYPE.
7652    If the buffer cannot be interpreted, return NULL_TREE.  */
7653
7654 static tree
7655 native_interpret_vector (tree type, const unsigned char *ptr, int len)
7656 {
7657   tree etype, elem;
7658   int i, size, count;
7659   tree *elements;
7660
7661   etype = TREE_TYPE (type);
7662   size = GET_MODE_SIZE (TYPE_MODE (etype));
7663   count = TYPE_VECTOR_SUBPARTS (type);
7664   if (size * count > len)
7665     return NULL_TREE;
7666
7667   elements = XALLOCAVEC (tree, count);
7668   for (i = count - 1; i >= 0; i--)
7669     {
7670       elem = native_interpret_expr (etype, ptr+(i*size), size);
7671       if (!elem)
7672         return NULL_TREE;
7673       elements[i] = elem;
7674     }
7675   return build_vector (type, elements);
7676 }
7677
7678
7679 /* Subroutine of fold_view_convert_expr.  Interpret the contents of
7680    the buffer PTR of length LEN as a constant of type TYPE.  For
7681    INTEGRAL_TYPE_P we return an INTEGER_CST, for SCALAR_FLOAT_TYPE_P
7682    we return a REAL_CST, etc...  If the buffer cannot be interpreted,
7683    return NULL_TREE.  */
7684
7685 tree
7686 native_interpret_expr (tree type, const unsigned char *ptr, int len)
7687 {
7688   switch (TREE_CODE (type))
7689     {
7690     case INTEGER_TYPE:
7691     case ENUMERAL_TYPE:
7692     case BOOLEAN_TYPE:
7693     case POINTER_TYPE:
7694     case REFERENCE_TYPE:
7695       return native_interpret_int (type, ptr, len);
7696
7697     case REAL_TYPE:
7698       return native_interpret_real (type, ptr, len);
7699
7700     case FIXED_POINT_TYPE:
7701       return native_interpret_fixed (type, ptr, len);
7702
7703     case COMPLEX_TYPE:
7704       return native_interpret_complex (type, ptr, len);
7705
7706     case VECTOR_TYPE:
7707       return native_interpret_vector (type, ptr, len);
7708
7709     default:
7710       return NULL_TREE;
7711     }
7712 }
7713
7714 /* Returns true if we can interpret the contents of a native encoding
7715    as TYPE.  */
7716
7717 static bool
7718 can_native_interpret_type_p (tree type)
7719 {
7720   switch (TREE_CODE (type))
7721     {
7722     case INTEGER_TYPE:
7723     case ENUMERAL_TYPE:
7724     case BOOLEAN_TYPE:
7725     case POINTER_TYPE:
7726     case REFERENCE_TYPE:
7727     case FIXED_POINT_TYPE:
7728     case REAL_TYPE:
7729     case COMPLEX_TYPE:
7730     case VECTOR_TYPE:
7731       return true;
7732     default:
7733       return false;
7734     }
7735 }
7736
7737 /* Fold a VIEW_CONVERT_EXPR of a constant expression EXPR to type
7738    TYPE at compile-time.  If we're unable to perform the conversion
7739    return NULL_TREE.  */
7740
7741 static tree
7742 fold_view_convert_expr (tree type, tree expr)
7743 {
7744   /* We support up to 512-bit values (for V8DFmode).  */
7745   unsigned char buffer[64];
7746   int len;
7747
7748   /* Check that the host and target are sane.  */
7749   if (CHAR_BIT != 8 || BITS_PER_UNIT != 8)
7750     return NULL_TREE;
7751
7752   len = native_encode_expr (expr, buffer, sizeof (buffer));
7753   if (len == 0)
7754     return NULL_TREE;
7755
7756   return native_interpret_expr (type, buffer, len);
7757 }
7758
7759 /* Build an expression for the address of T.  Folds away INDIRECT_REF
7760    to avoid confusing the gimplify process.  */
7761
7762 tree
7763 build_fold_addr_expr_with_type_loc (location_t loc, tree t, tree ptrtype)
7764 {
7765   /* The size of the object is not relevant when talking about its address.  */
7766   if (TREE_CODE (t) == WITH_SIZE_EXPR)
7767     t = TREE_OPERAND (t, 0);
7768
7769   if (TREE_CODE (t) == INDIRECT_REF)
7770     {
7771       t = TREE_OPERAND (t, 0);
7772
7773       if (TREE_TYPE (t) != ptrtype)
7774         t = build1_loc (loc, NOP_EXPR, ptrtype, t);
7775     }
7776   else if (TREE_CODE (t) == MEM_REF
7777            && integer_zerop (TREE_OPERAND (t, 1)))
7778     return TREE_OPERAND (t, 0);
7779   else if (TREE_CODE (t) == MEM_REF
7780            && TREE_CODE (TREE_OPERAND (t, 0)) == INTEGER_CST)
7781     return fold_binary (POINTER_PLUS_EXPR, ptrtype,
7782                         TREE_OPERAND (t, 0),
7783                         convert_to_ptrofftype (TREE_OPERAND (t, 1)));
7784   else if (TREE_CODE (t) == VIEW_CONVERT_EXPR)
7785     {
7786       t = build_fold_addr_expr_loc (loc, TREE_OPERAND (t, 0));
7787
7788       if (TREE_TYPE (t) != ptrtype)
7789         t = fold_convert_loc (loc, ptrtype, t);
7790     }
7791   else
7792     t = build1_loc (loc, ADDR_EXPR, ptrtype, t);
7793
7794   return t;
7795 }
7796
7797 /* Build an expression for the address of T.  */
7798
7799 tree
7800 build_fold_addr_expr_loc (location_t loc, tree t)
7801 {
7802   tree ptrtype = build_pointer_type (TREE_TYPE (t));
7803
7804   return build_fold_addr_expr_with_type_loc (loc, t, ptrtype);
7805 }
7806
7807 /* Fold a unary expression of code CODE and type TYPE with operand
7808    OP0.  Return the folded expression if folding is successful.
7809    Otherwise, return NULL_TREE.  */
7810
7811 tree
7812 fold_unary_loc (location_t loc, enum tree_code code, tree type, tree op0)
7813 {
7814   tree tem;
7815   tree arg0;
7816   enum tree_code_class kind = TREE_CODE_CLASS (code);
7817
7818   gcc_assert (IS_EXPR_CODE_CLASS (kind)
7819               && TREE_CODE_LENGTH (code) == 1);
7820
7821   arg0 = op0;
7822   if (arg0)
7823     {
7824       if (CONVERT_EXPR_CODE_P (code)
7825           || code == FLOAT_EXPR || code == ABS_EXPR || code == NEGATE_EXPR)
7826         {
7827           /* Don't use STRIP_NOPS, because signedness of argument type
7828              matters.  */
7829           STRIP_SIGN_NOPS (arg0);
7830         }
7831       else
7832         {
7833           /* Strip any conversions that don't change the mode.  This
7834              is safe for every expression, except for a comparison
7835              expression because its signedness is derived from its
7836              operands.
7837
7838              Note that this is done as an internal manipulation within
7839              the constant folder, in order to find the simplest
7840              representation of the arguments so that their form can be
7841              studied.  In any cases, the appropriate type conversions
7842              should be put back in the tree that will get out of the
7843              constant folder.  */
7844           STRIP_NOPS (arg0);
7845         }
7846
7847       if (CONSTANT_CLASS_P (arg0))
7848         {
7849           tree tem = const_unop (code, type, arg0);
7850           if (tem)
7851             {
7852               if (TREE_TYPE (tem) != type)
7853                 tem = fold_convert_loc (loc, type, tem);
7854               return tem;
7855             }
7856         }
7857     }
7858
7859   tem = generic_simplify (loc, code, type, op0);
7860   if (tem)
7861     return tem;
7862
7863   if (TREE_CODE_CLASS (code) == tcc_unary)
7864     {
7865       if (TREE_CODE (arg0) == COMPOUND_EXPR)
7866         return build2 (COMPOUND_EXPR, type, TREE_OPERAND (arg0, 0),
7867                        fold_build1_loc (loc, code, type,
7868                                     fold_convert_loc (loc, TREE_TYPE (op0),
7869                                                       TREE_OPERAND (arg0, 1))));
7870       else if (TREE_CODE (arg0) == COND_EXPR)
7871         {
7872           tree arg01 = TREE_OPERAND (arg0, 1);
7873           tree arg02 = TREE_OPERAND (arg0, 2);
7874           if (! VOID_TYPE_P (TREE_TYPE (arg01)))
7875             arg01 = fold_build1_loc (loc, code, type,
7876                                  fold_convert_loc (loc,
7877                                                    TREE_TYPE (op0), arg01));
7878           if (! VOID_TYPE_P (TREE_TYPE (arg02)))
7879             arg02 = fold_build1_loc (loc, code, type,
7880                                  fold_convert_loc (loc,
7881                                                    TREE_TYPE (op0), arg02));
7882           tem = fold_build3_loc (loc, COND_EXPR, type, TREE_OPERAND (arg0, 0),
7883                              arg01, arg02);
7884
7885           /* If this was a conversion, and all we did was to move into
7886              inside the COND_EXPR, bring it back out.  But leave it if
7887              it is a conversion from integer to integer and the
7888              result precision is no wider than a word since such a
7889              conversion is cheap and may be optimized away by combine,
7890              while it couldn't if it were outside the COND_EXPR.  Then return
7891              so we don't get into an infinite recursion loop taking the
7892              conversion out and then back in.  */
7893
7894           if ((CONVERT_EXPR_CODE_P (code)
7895                || code == NON_LVALUE_EXPR)
7896               && TREE_CODE (tem) == COND_EXPR
7897               && TREE_CODE (TREE_OPERAND (tem, 1)) == code
7898               && TREE_CODE (TREE_OPERAND (tem, 2)) == code
7899               && ! VOID_TYPE_P (TREE_OPERAND (tem, 1))
7900               && ! VOID_TYPE_P (TREE_OPERAND (tem, 2))
7901               && (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (tem, 1), 0))
7902                   == TREE_TYPE (TREE_OPERAND (TREE_OPERAND (tem, 2), 0)))
7903               && (! (INTEGRAL_TYPE_P (TREE_TYPE (tem))
7904                      && (INTEGRAL_TYPE_P
7905                          (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (tem, 1), 0))))
7906                      && TYPE_PRECISION (TREE_TYPE (tem)) <= BITS_PER_WORD)
7907                   || flag_syntax_only))
7908             tem = build1_loc (loc, code, type,
7909                               build3 (COND_EXPR,
7910                                       TREE_TYPE (TREE_OPERAND
7911                                                  (TREE_OPERAND (tem, 1), 0)),
7912                                       TREE_OPERAND (tem, 0),
7913                                       TREE_OPERAND (TREE_OPERAND (tem, 1), 0),
7914                                       TREE_OPERAND (TREE_OPERAND (tem, 2),
7915                                                     0)));
7916           return tem;
7917         }
7918    }
7919
7920   switch (code)
7921     {
7922     case NON_LVALUE_EXPR:
7923       if (!maybe_lvalue_p (op0))
7924         return fold_convert_loc (loc, type, op0);
7925       return NULL_TREE;
7926
7927     CASE_CONVERT:
7928     case FLOAT_EXPR:
7929     case FIX_TRUNC_EXPR:
7930       if (COMPARISON_CLASS_P (op0))
7931         {
7932           /* If we have (type) (a CMP b) and type is an integral type, return
7933              new expression involving the new type.  Canonicalize
7934              (type) (a CMP b) to (a CMP b) ? (type) true : (type) false for
7935              non-integral type.
7936              Do not fold the result as that would not simplify further, also
7937              folding again results in recursions.  */
7938           if (TREE_CODE (type) == BOOLEAN_TYPE)
7939             return build2_loc (loc, TREE_CODE (op0), type,
7940                                TREE_OPERAND (op0, 0),
7941                                TREE_OPERAND (op0, 1));
7942           else if (!INTEGRAL_TYPE_P (type) && !VOID_TYPE_P (type)
7943                    && TREE_CODE (type) != VECTOR_TYPE)
7944             return build3_loc (loc, COND_EXPR, type, op0,
7945                                constant_boolean_node (true, type),
7946                                constant_boolean_node (false, type));
7947         }
7948
7949       /* Handle (T *)&A.B.C for A being of type T and B and C
7950          living at offset zero.  This occurs frequently in
7951          C++ upcasting and then accessing the base.  */
7952       if (TREE_CODE (op0) == ADDR_EXPR
7953           && POINTER_TYPE_P (type)
7954           && handled_component_p (TREE_OPERAND (op0, 0)))
7955         {
7956           HOST_WIDE_INT bitsize, bitpos;
7957           tree offset;
7958           machine_mode mode;
7959           int unsignedp, volatilep;
7960           tree base = TREE_OPERAND (op0, 0);
7961           base = get_inner_reference (base, &bitsize, &bitpos, &offset,
7962                                       &mode, &unsignedp, &volatilep, false);
7963           /* If the reference was to a (constant) zero offset, we can use
7964              the address of the base if it has the same base type
7965              as the result type and the pointer type is unqualified.  */
7966           if (! offset && bitpos == 0
7967               && (TYPE_MAIN_VARIANT (TREE_TYPE (type))
7968                   == TYPE_MAIN_VARIANT (TREE_TYPE (base)))
7969               && TYPE_QUALS (type) == TYPE_UNQUALIFIED)
7970             return fold_convert_loc (loc, type,
7971                                      build_fold_addr_expr_loc (loc, base));
7972         }
7973
7974       if (TREE_CODE (op0) == MODIFY_EXPR
7975           && TREE_CONSTANT (TREE_OPERAND (op0, 1))
7976           /* Detect assigning a bitfield.  */
7977           && !(TREE_CODE (TREE_OPERAND (op0, 0)) == COMPONENT_REF
7978                && DECL_BIT_FIELD
7979                (TREE_OPERAND (TREE_OPERAND (op0, 0), 1))))
7980         {
7981           /* Don't leave an assignment inside a conversion
7982              unless assigning a bitfield.  */
7983           tem = fold_build1_loc (loc, code, type, TREE_OPERAND (op0, 1));
7984           /* First do the assignment, then return converted constant.  */
7985           tem = build2_loc (loc, COMPOUND_EXPR, TREE_TYPE (tem), op0, tem);
7986           TREE_NO_WARNING (tem) = 1;
7987           TREE_USED (tem) = 1;
7988           return tem;
7989         }
7990
7991       /* Convert (T)(x & c) into (T)x & (T)c, if c is an integer
7992          constants (if x has signed type, the sign bit cannot be set
7993          in c).  This folds extension into the BIT_AND_EXPR.
7994          ??? We don't do it for BOOLEAN_TYPE or ENUMERAL_TYPE because they
7995          very likely don't have maximal range for their precision and this
7996          transformation effectively doesn't preserve non-maximal ranges.  */
7997       if (TREE_CODE (type) == INTEGER_TYPE
7998           && TREE_CODE (op0) == BIT_AND_EXPR
7999           && TREE_CODE (TREE_OPERAND (op0, 1)) == INTEGER_CST)
8000         {
8001           tree and_expr = op0;
8002           tree and0 = TREE_OPERAND (and_expr, 0);
8003           tree and1 = TREE_OPERAND (and_expr, 1);
8004           int change = 0;
8005
8006           if (TYPE_UNSIGNED (TREE_TYPE (and_expr))
8007               || (TYPE_PRECISION (type)
8008                   <= TYPE_PRECISION (TREE_TYPE (and_expr))))
8009             change = 1;
8010           else if (TYPE_PRECISION (TREE_TYPE (and1))
8011                    <= HOST_BITS_PER_WIDE_INT
8012                    && tree_fits_uhwi_p (and1))
8013             {
8014               unsigned HOST_WIDE_INT cst;
8015
8016               cst = tree_to_uhwi (and1);
8017               cst &= HOST_WIDE_INT_M1U
8018                      << (TYPE_PRECISION (TREE_TYPE (and1)) - 1);
8019               change = (cst == 0);
8020 #ifdef LOAD_EXTEND_OP
8021               if (change
8022                   && !flag_syntax_only
8023                   && (LOAD_EXTEND_OP (TYPE_MODE (TREE_TYPE (and0)))
8024                       == ZERO_EXTEND))
8025                 {
8026                   tree uns = unsigned_type_for (TREE_TYPE (and0));
8027                   and0 = fold_convert_loc (loc, uns, and0);
8028                   and1 = fold_convert_loc (loc, uns, and1);
8029                 }
8030 #endif
8031             }
8032           if (change)
8033             {
8034               tem = force_fit_type (type, wi::to_widest (and1), 0,
8035                                     TREE_OVERFLOW (and1));
8036               return fold_build2_loc (loc, BIT_AND_EXPR, type,
8037                                       fold_convert_loc (loc, type, and0), tem);
8038             }
8039         }
8040
8041       /* Convert (T1)(X p+ Y) into ((T1)X p+ Y), for pointer type,
8042          when one of the new casts will fold away. Conservatively we assume
8043          that this happens when X or Y is NOP_EXPR or Y is INTEGER_CST. */
8044       if (POINTER_TYPE_P (type)
8045           && TREE_CODE (arg0) == POINTER_PLUS_EXPR
8046           && (!TYPE_RESTRICT (type) || TYPE_RESTRICT (TREE_TYPE (arg0)))
8047           && (TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
8048               || TREE_CODE (TREE_OPERAND (arg0, 0)) == NOP_EXPR
8049               || TREE_CODE (TREE_OPERAND (arg0, 1)) == NOP_EXPR))
8050         {
8051           tree arg00 = TREE_OPERAND (arg0, 0);
8052           tree arg01 = TREE_OPERAND (arg0, 1);
8053
8054           return fold_build_pointer_plus_loc
8055                    (loc, fold_convert_loc (loc, type, arg00), arg01);
8056         }
8057
8058       /* Convert (T1)(~(T2)X) into ~(T1)X if T1 and T2 are integral types
8059          of the same precision, and X is an integer type not narrower than
8060          types T1 or T2, i.e. the cast (T2)X isn't an extension.  */
8061       if (INTEGRAL_TYPE_P (type)
8062           && TREE_CODE (op0) == BIT_NOT_EXPR
8063           && INTEGRAL_TYPE_P (TREE_TYPE (op0))
8064           && CONVERT_EXPR_P (TREE_OPERAND (op0, 0))
8065           && TYPE_PRECISION (type) == TYPE_PRECISION (TREE_TYPE (op0)))
8066         {
8067           tem = TREE_OPERAND (TREE_OPERAND (op0, 0), 0);
8068           if (INTEGRAL_TYPE_P (TREE_TYPE (tem))
8069               && TYPE_PRECISION (type) <= TYPE_PRECISION (TREE_TYPE (tem)))
8070             return fold_build1_loc (loc, BIT_NOT_EXPR, type,
8071                                 fold_convert_loc (loc, type, tem));
8072         }
8073
8074       /* Convert (T1)(X * Y) into (T1)X * (T1)Y if T1 is narrower than the
8075          type of X and Y (integer types only).  */
8076       if (INTEGRAL_TYPE_P (type)
8077           && TREE_CODE (op0) == MULT_EXPR
8078           && INTEGRAL_TYPE_P (TREE_TYPE (op0))
8079           && TYPE_PRECISION (type) < TYPE_PRECISION (TREE_TYPE (op0)))
8080         {
8081           /* Be careful not to introduce new overflows.  */
8082           tree mult_type;
8083           if (TYPE_OVERFLOW_WRAPS (type))
8084             mult_type = type;
8085           else
8086             mult_type = unsigned_type_for (type);
8087
8088           if (TYPE_PRECISION (mult_type) < TYPE_PRECISION (TREE_TYPE (op0)))
8089             {
8090               tem = fold_build2_loc (loc, MULT_EXPR, mult_type,
8091                                  fold_convert_loc (loc, mult_type,
8092                                                    TREE_OPERAND (op0, 0)),
8093                                  fold_convert_loc (loc, mult_type,
8094                                                    TREE_OPERAND (op0, 1)));
8095               return fold_convert_loc (loc, type, tem);
8096             }
8097         }
8098
8099       return NULL_TREE;
8100
8101     case VIEW_CONVERT_EXPR:
8102       if (TREE_CODE (op0) == MEM_REF)
8103         return fold_build2_loc (loc, MEM_REF, type,
8104                                 TREE_OPERAND (op0, 0), TREE_OPERAND (op0, 1));
8105
8106       return NULL_TREE;
8107
8108     case NEGATE_EXPR:
8109       tem = fold_negate_expr (loc, arg0);
8110       if (tem)
8111         return fold_convert_loc (loc, type, tem);
8112       return NULL_TREE;
8113
8114     case ABS_EXPR:
8115       /* Convert fabs((double)float) into (double)fabsf(float).  */
8116       if (TREE_CODE (arg0) == NOP_EXPR
8117           && TREE_CODE (type) == REAL_TYPE)
8118         {
8119           tree targ0 = strip_float_extensions (arg0);
8120           if (targ0 != arg0)
8121             return fold_convert_loc (loc, type,
8122                                      fold_build1_loc (loc, ABS_EXPR,
8123                                                   TREE_TYPE (targ0),
8124                                                   targ0));
8125         }
8126       /* ABS_EXPR<ABS_EXPR<x>> = ABS_EXPR<x> even if flag_wrapv is on.  */
8127       else if (TREE_CODE (arg0) == ABS_EXPR)
8128         return arg0;
8129
8130       /* Strip sign ops from argument.  */
8131       if (TREE_CODE (type) == REAL_TYPE)
8132         {
8133           tem = fold_strip_sign_ops (arg0);
8134           if (tem)
8135             return fold_build1_loc (loc, ABS_EXPR, type,
8136                                 fold_convert_loc (loc, type, tem));
8137         }
8138       return NULL_TREE;
8139
8140     case CONJ_EXPR:
8141       if (TREE_CODE (TREE_TYPE (arg0)) != COMPLEX_TYPE)
8142         return fold_convert_loc (loc, type, arg0);
8143       if (TREE_CODE (arg0) == COMPLEX_EXPR)
8144         {
8145           tree itype = TREE_TYPE (type);
8146           tree rpart = fold_convert_loc (loc, itype, TREE_OPERAND (arg0, 0));
8147           tree ipart = fold_convert_loc (loc, itype, TREE_OPERAND (arg0, 1));
8148           return fold_build2_loc (loc, COMPLEX_EXPR, type, rpart,
8149                               negate_expr (ipart));
8150         }
8151       if (TREE_CODE (arg0) == CONJ_EXPR)
8152         return fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
8153       return NULL_TREE;
8154
8155     case BIT_NOT_EXPR:
8156       /* Convert ~ (-A) to A - 1.  */
8157       if (INTEGRAL_TYPE_P (type) && TREE_CODE (arg0) == NEGATE_EXPR)
8158         return fold_build2_loc (loc, MINUS_EXPR, type,
8159                             fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0)),
8160                             build_int_cst (type, 1));
8161       /* Convert ~ (A - 1) or ~ (A + -1) to -A.  */
8162       else if (INTEGRAL_TYPE_P (type)
8163                && ((TREE_CODE (arg0) == MINUS_EXPR
8164                     && integer_onep (TREE_OPERAND (arg0, 1)))
8165                    || (TREE_CODE (arg0) == PLUS_EXPR
8166                        && integer_all_onesp (TREE_OPERAND (arg0, 1)))))
8167         {
8168           /* Perform the negation in ARG0's type and only then convert
8169              to TYPE as to avoid introducing undefined behavior.  */
8170           tree t = fold_build1_loc (loc, NEGATE_EXPR,
8171                                     TREE_TYPE (TREE_OPERAND (arg0, 0)),
8172                                     TREE_OPERAND (arg0, 0));
8173           return fold_convert_loc (loc, type, t);
8174         }
8175       /* Convert ~(X ^ Y) to ~X ^ Y or X ^ ~Y if ~X or ~Y simplify.  */
8176       else if (TREE_CODE (arg0) == BIT_XOR_EXPR
8177                && (tem = fold_unary_loc (loc, BIT_NOT_EXPR, type,
8178                                      fold_convert_loc (loc, type,
8179                                                        TREE_OPERAND (arg0, 0)))))
8180         return fold_build2_loc (loc, BIT_XOR_EXPR, type, tem,
8181                             fold_convert_loc (loc, type,
8182                                               TREE_OPERAND (arg0, 1)));
8183       else if (TREE_CODE (arg0) == BIT_XOR_EXPR
8184                && (tem = fold_unary_loc (loc, BIT_NOT_EXPR, type,
8185                                      fold_convert_loc (loc, type,
8186                                                        TREE_OPERAND (arg0, 1)))))
8187         return fold_build2_loc (loc, BIT_XOR_EXPR, type,
8188                             fold_convert_loc (loc, type,
8189                                               TREE_OPERAND (arg0, 0)), tem);
8190
8191       return NULL_TREE;
8192
8193     case TRUTH_NOT_EXPR:
8194       /* Note that the operand of this must be an int
8195          and its values must be 0 or 1.
8196          ("true" is a fixed value perhaps depending on the language,
8197          but we don't handle values other than 1 correctly yet.)  */
8198       tem = fold_truth_not_expr (loc, arg0);
8199       if (!tem)
8200         return NULL_TREE;
8201       return fold_convert_loc (loc, type, tem);
8202
8203     case REALPART_EXPR:
8204       if (TREE_CODE (TREE_TYPE (arg0)) != COMPLEX_TYPE)
8205         return fold_convert_loc (loc, type, arg0);
8206       if (TREE_CODE (arg0) == PLUS_EXPR || TREE_CODE (arg0) == MINUS_EXPR)
8207         {
8208           tree itype = TREE_TYPE (TREE_TYPE (arg0));
8209           tem = fold_build2_loc (loc, TREE_CODE (arg0), itype,
8210                              fold_build1_loc (loc, REALPART_EXPR, itype,
8211                                           TREE_OPERAND (arg0, 0)),
8212                              fold_build1_loc (loc, REALPART_EXPR, itype,
8213                                           TREE_OPERAND (arg0, 1)));
8214           return fold_convert_loc (loc, type, tem);
8215         }
8216       if (TREE_CODE (arg0) == CONJ_EXPR)
8217         {
8218           tree itype = TREE_TYPE (TREE_TYPE (arg0));
8219           tem = fold_build1_loc (loc, REALPART_EXPR, itype,
8220                              TREE_OPERAND (arg0, 0));
8221           return fold_convert_loc (loc, type, tem);
8222         }
8223       if (TREE_CODE (arg0) == CALL_EXPR)
8224         {
8225           tree fn = get_callee_fndecl (arg0);
8226           if (fn && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
8227             switch (DECL_FUNCTION_CODE (fn))
8228               {
8229               CASE_FLT_FN (BUILT_IN_CEXPI):
8230                 fn = mathfn_built_in (type, BUILT_IN_COS);
8231                 if (fn)
8232                   return build_call_expr_loc (loc, fn, 1, CALL_EXPR_ARG (arg0, 0));
8233                 break;
8234
8235               default:
8236                 break;
8237               }
8238         }
8239       return NULL_TREE;
8240
8241     case IMAGPART_EXPR:
8242       if (TREE_CODE (TREE_TYPE (arg0)) != COMPLEX_TYPE)
8243         return build_zero_cst (type);
8244       if (TREE_CODE (arg0) == PLUS_EXPR || TREE_CODE (arg0) == MINUS_EXPR)
8245         {
8246           tree itype = TREE_TYPE (TREE_TYPE (arg0));
8247           tem = fold_build2_loc (loc, TREE_CODE (arg0), itype,
8248                              fold_build1_loc (loc, IMAGPART_EXPR, itype,
8249                                           TREE_OPERAND (arg0, 0)),
8250                              fold_build1_loc (loc, IMAGPART_EXPR, itype,
8251                                           TREE_OPERAND (arg0, 1)));
8252           return fold_convert_loc (loc, type, tem);
8253         }
8254       if (TREE_CODE (arg0) == CONJ_EXPR)
8255         {
8256           tree itype = TREE_TYPE (TREE_TYPE (arg0));
8257           tem = fold_build1_loc (loc, IMAGPART_EXPR, itype, TREE_OPERAND (arg0, 0));
8258           return fold_convert_loc (loc, type, negate_expr (tem));
8259         }
8260       if (TREE_CODE (arg0) == CALL_EXPR)
8261         {
8262           tree fn = get_callee_fndecl (arg0);
8263           if (fn && DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL)
8264             switch (DECL_FUNCTION_CODE (fn))
8265               {
8266               CASE_FLT_FN (BUILT_IN_CEXPI):
8267                 fn = mathfn_built_in (type, BUILT_IN_SIN);
8268                 if (fn)
8269                   return build_call_expr_loc (loc, fn, 1, CALL_EXPR_ARG (arg0, 0));
8270                 break;
8271
8272               default:
8273                 break;
8274               }
8275         }
8276       return NULL_TREE;
8277
8278     case INDIRECT_REF:
8279       /* Fold *&X to X if X is an lvalue.  */
8280       if (TREE_CODE (op0) == ADDR_EXPR)
8281         {
8282           tree op00 = TREE_OPERAND (op0, 0);
8283           if ((TREE_CODE (op00) == VAR_DECL
8284                || TREE_CODE (op00) == PARM_DECL
8285                || TREE_CODE (op00) == RESULT_DECL)
8286               && !TREE_READONLY (op00))
8287             return op00;
8288         }
8289       return NULL_TREE;
8290
8291     default:
8292       return NULL_TREE;
8293     } /* switch (code) */
8294 }
8295
8296
8297 /* If the operation was a conversion do _not_ mark a resulting constant
8298    with TREE_OVERFLOW if the original constant was not.  These conversions
8299    have implementation defined behavior and retaining the TREE_OVERFLOW
8300    flag here would confuse later passes such as VRP.  */
8301 tree
8302 fold_unary_ignore_overflow_loc (location_t loc, enum tree_code code,
8303                                 tree type, tree op0)
8304 {
8305   tree res = fold_unary_loc (loc, code, type, op0);
8306   if (res
8307       && TREE_CODE (res) == INTEGER_CST
8308       && TREE_CODE (op0) == INTEGER_CST
8309       && CONVERT_EXPR_CODE_P (code))
8310     TREE_OVERFLOW (res) = TREE_OVERFLOW (op0);
8311
8312   return res;
8313 }
8314
8315 /* Fold a binary bitwise/truth expression of code CODE and type TYPE with
8316    operands OP0 and OP1.  LOC is the location of the resulting expression.
8317    ARG0 and ARG1 are the NOP_STRIPed results of OP0 and OP1.
8318    Return the folded expression if folding is successful.  Otherwise,
8319    return NULL_TREE.  */
8320 static tree
8321 fold_truth_andor (location_t loc, enum tree_code code, tree type,
8322                   tree arg0, tree arg1, tree op0, tree op1)
8323 {
8324   tree tem;
8325
8326   /* We only do these simplifications if we are optimizing.  */
8327   if (!optimize)
8328     return NULL_TREE;
8329
8330   /* Check for things like (A || B) && (A || C).  We can convert this
8331      to A || (B && C).  Note that either operator can be any of the four
8332      truth and/or operations and the transformation will still be
8333      valid.   Also note that we only care about order for the
8334      ANDIF and ORIF operators.  If B contains side effects, this
8335      might change the truth-value of A.  */
8336   if (TREE_CODE (arg0) == TREE_CODE (arg1)
8337       && (TREE_CODE (arg0) == TRUTH_ANDIF_EXPR
8338           || TREE_CODE (arg0) == TRUTH_ORIF_EXPR
8339           || TREE_CODE (arg0) == TRUTH_AND_EXPR
8340           || TREE_CODE (arg0) == TRUTH_OR_EXPR)
8341       && ! TREE_SIDE_EFFECTS (TREE_OPERAND (arg0, 1)))
8342     {
8343       tree a00 = TREE_OPERAND (arg0, 0);
8344       tree a01 = TREE_OPERAND (arg0, 1);
8345       tree a10 = TREE_OPERAND (arg1, 0);
8346       tree a11 = TREE_OPERAND (arg1, 1);
8347       int commutative = ((TREE_CODE (arg0) == TRUTH_OR_EXPR
8348                           || TREE_CODE (arg0) == TRUTH_AND_EXPR)
8349                          && (code == TRUTH_AND_EXPR
8350                              || code == TRUTH_OR_EXPR));
8351
8352       if (operand_equal_p (a00, a10, 0))
8353         return fold_build2_loc (loc, TREE_CODE (arg0), type, a00,
8354                             fold_build2_loc (loc, code, type, a01, a11));
8355       else if (commutative && operand_equal_p (a00, a11, 0))
8356         return fold_build2_loc (loc, TREE_CODE (arg0), type, a00,
8357                             fold_build2_loc (loc, code, type, a01, a10));
8358       else if (commutative && operand_equal_p (a01, a10, 0))
8359         return fold_build2_loc (loc, TREE_CODE (arg0), type, a01,
8360                             fold_build2_loc (loc, code, type, a00, a11));
8361
8362       /* This case if tricky because we must either have commutative
8363          operators or else A10 must not have side-effects.  */
8364
8365       else if ((commutative || ! TREE_SIDE_EFFECTS (a10))
8366                && operand_equal_p (a01, a11, 0))
8367         return fold_build2_loc (loc, TREE_CODE (arg0), type,
8368                             fold_build2_loc (loc, code, type, a00, a10),
8369                             a01);
8370     }
8371
8372   /* See if we can build a range comparison.  */
8373   if (0 != (tem = fold_range_test (loc, code, type, op0, op1)))
8374     return tem;
8375
8376   if ((code == TRUTH_ANDIF_EXPR && TREE_CODE (arg0) == TRUTH_ORIF_EXPR)
8377       || (code == TRUTH_ORIF_EXPR && TREE_CODE (arg0) == TRUTH_ANDIF_EXPR))
8378     {
8379       tem = merge_truthop_with_opposite_arm (loc, arg0, arg1, true);
8380       if (tem)
8381         return fold_build2_loc (loc, code, type, tem, arg1);
8382     }
8383
8384   if ((code == TRUTH_ANDIF_EXPR && TREE_CODE (arg1) == TRUTH_ORIF_EXPR)
8385       || (code == TRUTH_ORIF_EXPR && TREE_CODE (arg1) == TRUTH_ANDIF_EXPR))
8386     {
8387       tem = merge_truthop_with_opposite_arm (loc, arg1, arg0, false);
8388       if (tem)
8389         return fold_build2_loc (loc, code, type, arg0, tem);
8390     }
8391
8392   /* Check for the possibility of merging component references.  If our
8393      lhs is another similar operation, try to merge its rhs with our
8394      rhs.  Then try to merge our lhs and rhs.  */
8395   if (TREE_CODE (arg0) == code
8396       && 0 != (tem = fold_truth_andor_1 (loc, code, type,
8397                                          TREE_OPERAND (arg0, 1), arg1)))
8398     return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0), tem);
8399
8400   if ((tem = fold_truth_andor_1 (loc, code, type, arg0, arg1)) != 0)
8401     return tem;
8402
8403   if (LOGICAL_OP_NON_SHORT_CIRCUIT
8404       && (code == TRUTH_AND_EXPR
8405           || code == TRUTH_ANDIF_EXPR
8406           || code == TRUTH_OR_EXPR
8407           || code == TRUTH_ORIF_EXPR))
8408     {
8409       enum tree_code ncode, icode;
8410
8411       ncode = (code == TRUTH_ANDIF_EXPR || code == TRUTH_AND_EXPR)
8412               ? TRUTH_AND_EXPR : TRUTH_OR_EXPR;
8413       icode = ncode == TRUTH_AND_EXPR ? TRUTH_ANDIF_EXPR : TRUTH_ORIF_EXPR;
8414
8415       /* Transform ((A AND-IF B) AND[-IF] C) into (A AND-IF (B AND C)),
8416          or ((A OR-IF B) OR[-IF] C) into (A OR-IF (B OR C))
8417          We don't want to pack more than two leafs to a non-IF AND/OR
8418          expression.
8419          If tree-code of left-hand operand isn't an AND/OR-IF code and not
8420          equal to IF-CODE, then we don't want to add right-hand operand.
8421          If the inner right-hand side of left-hand operand has
8422          side-effects, or isn't simple, then we can't add to it,
8423          as otherwise we might destroy if-sequence.  */
8424       if (TREE_CODE (arg0) == icode
8425           && simple_operand_p_2 (arg1)
8426           /* Needed for sequence points to handle trappings, and
8427              side-effects.  */
8428           && simple_operand_p_2 (TREE_OPERAND (arg0, 1)))
8429         {
8430           tem = fold_build2_loc (loc, ncode, type, TREE_OPERAND (arg0, 1),
8431                                  arg1);
8432           return fold_build2_loc (loc, icode, type, TREE_OPERAND (arg0, 0),
8433                                   tem);
8434         }
8435         /* Same as abouve but for (A AND[-IF] (B AND-IF C)) -> ((A AND B) AND-IF C),
8436            or (A OR[-IF] (B OR-IF C) -> ((A OR B) OR-IF C).  */
8437       else if (TREE_CODE (arg1) == icode
8438           && simple_operand_p_2 (arg0)
8439           /* Needed for sequence points to handle trappings, and
8440              side-effects.  */
8441           && simple_operand_p_2 (TREE_OPERAND (arg1, 0)))
8442         {
8443           tem = fold_build2_loc (loc, ncode, type, 
8444                                  arg0, TREE_OPERAND (arg1, 0));
8445           return fold_build2_loc (loc, icode, type, tem,
8446                                   TREE_OPERAND (arg1, 1));
8447         }
8448       /* Transform (A AND-IF B) into (A AND B), or (A OR-IF B)
8449          into (A OR B).
8450          For sequence point consistancy, we need to check for trapping,
8451          and side-effects.  */
8452       else if (code == icode && simple_operand_p_2 (arg0)
8453                && simple_operand_p_2 (arg1))
8454         return fold_build2_loc (loc, ncode, type, arg0, arg1);
8455     }
8456
8457   return NULL_TREE;
8458 }
8459
8460 /* Fold a binary expression of code CODE and type TYPE with operands
8461    OP0 and OP1, containing either a MIN-MAX or a MAX-MIN combination.
8462    Return the folded expression if folding is successful.  Otherwise,
8463    return NULL_TREE.  */
8464
8465 static tree
8466 fold_minmax (location_t loc, enum tree_code code, tree type, tree op0, tree op1)
8467 {
8468   enum tree_code compl_code;
8469
8470   if (code == MIN_EXPR)
8471     compl_code = MAX_EXPR;
8472   else if (code == MAX_EXPR)
8473     compl_code = MIN_EXPR;
8474   else
8475     gcc_unreachable ();
8476
8477   /* MIN (MAX (a, b), b) == b.  */
8478   if (TREE_CODE (op0) == compl_code
8479       && operand_equal_p (TREE_OPERAND (op0, 1), op1, 0))
8480     return omit_one_operand_loc (loc, type, op1, TREE_OPERAND (op0, 0));
8481
8482   /* MIN (MAX (b, a), b) == b.  */
8483   if (TREE_CODE (op0) == compl_code
8484       && operand_equal_p (TREE_OPERAND (op0, 0), op1, 0)
8485       && reorder_operands_p (TREE_OPERAND (op0, 1), op1))
8486     return omit_one_operand_loc (loc, type, op1, TREE_OPERAND (op0, 1));
8487
8488   /* MIN (a, MAX (a, b)) == a.  */
8489   if (TREE_CODE (op1) == compl_code
8490       && operand_equal_p (op0, TREE_OPERAND (op1, 0), 0)
8491       && reorder_operands_p (op0, TREE_OPERAND (op1, 1)))
8492     return omit_one_operand_loc (loc, type, op0, TREE_OPERAND (op1, 1));
8493
8494   /* MIN (a, MAX (b, a)) == a.  */
8495   if (TREE_CODE (op1) == compl_code
8496       && operand_equal_p (op0, TREE_OPERAND (op1, 1), 0)
8497       && reorder_operands_p (op0, TREE_OPERAND (op1, 0)))
8498     return omit_one_operand_loc (loc, type, op0, TREE_OPERAND (op1, 0));
8499
8500   return NULL_TREE;
8501 }
8502
8503 /* Helper that tries to canonicalize the comparison ARG0 CODE ARG1
8504    by changing CODE to reduce the magnitude of constants involved in
8505    ARG0 of the comparison.
8506    Returns a canonicalized comparison tree if a simplification was
8507    possible, otherwise returns NULL_TREE.
8508    Set *STRICT_OVERFLOW_P to true if the canonicalization is only
8509    valid if signed overflow is undefined.  */
8510
8511 static tree
8512 maybe_canonicalize_comparison_1 (location_t loc, enum tree_code code, tree type,
8513                                  tree arg0, tree arg1,
8514                                  bool *strict_overflow_p)
8515 {
8516   enum tree_code code0 = TREE_CODE (arg0);
8517   tree t, cst0 = NULL_TREE;
8518   int sgn0;
8519   bool swap = false;
8520
8521   /* Match A +- CST code arg1 and CST code arg1.  We can change the
8522      first form only if overflow is undefined.  */
8523   if (!(((ANY_INTEGRAL_TYPE_P (TREE_TYPE (arg0))
8524           && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0)))
8525          /* In principle pointers also have undefined overflow behavior,
8526             but that causes problems elsewhere.  */
8527          && !POINTER_TYPE_P (TREE_TYPE (arg0))
8528          && (code0 == MINUS_EXPR
8529              || code0 == PLUS_EXPR)
8530          && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
8531         || code0 == INTEGER_CST))
8532     return NULL_TREE;
8533
8534   /* Identify the constant in arg0 and its sign.  */
8535   if (code0 == INTEGER_CST)
8536     cst0 = arg0;
8537   else
8538     cst0 = TREE_OPERAND (arg0, 1);
8539   sgn0 = tree_int_cst_sgn (cst0);
8540
8541   /* Overflowed constants and zero will cause problems.  */
8542   if (integer_zerop (cst0)
8543       || TREE_OVERFLOW (cst0))
8544     return NULL_TREE;
8545
8546   /* See if we can reduce the magnitude of the constant in
8547      arg0 by changing the comparison code.  */
8548   if (code0 == INTEGER_CST)
8549     {
8550       /* CST <= arg1  ->  CST-1 < arg1.  */
8551       if (code == LE_EXPR && sgn0 == 1)
8552         code = LT_EXPR;
8553       /* -CST < arg1  ->  -CST-1 <= arg1.  */
8554       else if (code == LT_EXPR && sgn0 == -1)
8555         code = LE_EXPR;
8556       /* CST > arg1  ->  CST-1 >= arg1.  */
8557       else if (code == GT_EXPR && sgn0 == 1)
8558         code = GE_EXPR;
8559       /* -CST >= arg1  ->  -CST-1 > arg1.  */
8560       else if (code == GE_EXPR && sgn0 == -1)
8561         code = GT_EXPR;
8562       else
8563         return NULL_TREE;
8564       /* arg1 code' CST' might be more canonical.  */
8565       swap = true;
8566     }
8567   else
8568     {
8569       /* A - CST < arg1  ->  A - CST-1 <= arg1.  */
8570       if (code == LT_EXPR
8571           && code0 == ((sgn0 == -1) ? PLUS_EXPR : MINUS_EXPR))
8572         code = LE_EXPR;
8573       /* A + CST > arg1  ->  A + CST-1 >= arg1.  */
8574       else if (code == GT_EXPR
8575                && code0 == ((sgn0 == -1) ? MINUS_EXPR : PLUS_EXPR))
8576         code = GE_EXPR;
8577       /* A + CST <= arg1  ->  A + CST-1 < arg1.  */
8578       else if (code == LE_EXPR
8579                && code0 == ((sgn0 == -1) ? MINUS_EXPR : PLUS_EXPR))
8580         code = LT_EXPR;
8581       /* A - CST >= arg1  ->  A - CST-1 > arg1.  */
8582       else if (code == GE_EXPR
8583                && code0 == ((sgn0 == -1) ? PLUS_EXPR : MINUS_EXPR))
8584         code = GT_EXPR;
8585       else
8586         return NULL_TREE;
8587       *strict_overflow_p = true;
8588     }
8589
8590   /* Now build the constant reduced in magnitude.  But not if that
8591      would produce one outside of its types range.  */
8592   if (INTEGRAL_TYPE_P (TREE_TYPE (cst0))
8593       && ((sgn0 == 1
8594            && TYPE_MIN_VALUE (TREE_TYPE (cst0))
8595            && tree_int_cst_equal (cst0, TYPE_MIN_VALUE (TREE_TYPE (cst0))))
8596           || (sgn0 == -1
8597               && TYPE_MAX_VALUE (TREE_TYPE (cst0))
8598               && tree_int_cst_equal (cst0, TYPE_MAX_VALUE (TREE_TYPE (cst0))))))
8599     /* We cannot swap the comparison here as that would cause us to
8600        endlessly recurse.  */
8601     return NULL_TREE;
8602
8603   t = int_const_binop (sgn0 == -1 ? PLUS_EXPR : MINUS_EXPR,
8604                        cst0, build_int_cst (TREE_TYPE (cst0), 1));
8605   if (code0 != INTEGER_CST)
8606     t = fold_build2_loc (loc, code0, TREE_TYPE (arg0), TREE_OPERAND (arg0, 0), t);
8607   t = fold_convert (TREE_TYPE (arg1), t);
8608
8609   /* If swapping might yield to a more canonical form, do so.  */
8610   if (swap)
8611     return fold_build2_loc (loc, swap_tree_comparison (code), type, arg1, t);
8612   else
8613     return fold_build2_loc (loc, code, type, t, arg1);
8614 }
8615
8616 /* Canonicalize the comparison ARG0 CODE ARG1 with type TYPE with undefined
8617    overflow further.  Try to decrease the magnitude of constants involved
8618    by changing LE_EXPR and GE_EXPR to LT_EXPR and GT_EXPR or vice versa
8619    and put sole constants at the second argument position.
8620    Returns the canonicalized tree if changed, otherwise NULL_TREE.  */
8621
8622 static tree
8623 maybe_canonicalize_comparison (location_t loc, enum tree_code code, tree type,
8624                                tree arg0, tree arg1)
8625 {
8626   tree t;
8627   bool strict_overflow_p;
8628   const char * const warnmsg = G_("assuming signed overflow does not occur "
8629                                   "when reducing constant in comparison");
8630
8631   /* Try canonicalization by simplifying arg0.  */
8632   strict_overflow_p = false;
8633   t = maybe_canonicalize_comparison_1 (loc, code, type, arg0, arg1,
8634                                        &strict_overflow_p);
8635   if (t)
8636     {
8637       if (strict_overflow_p)
8638         fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_MAGNITUDE);
8639       return t;
8640     }
8641
8642   /* Try canonicalization by simplifying arg1 using the swapped
8643      comparison.  */
8644   code = swap_tree_comparison (code);
8645   strict_overflow_p = false;
8646   t = maybe_canonicalize_comparison_1 (loc, code, type, arg1, arg0,
8647                                        &strict_overflow_p);
8648   if (t && strict_overflow_p)
8649     fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_MAGNITUDE);
8650   return t;
8651 }
8652
8653 /* Return whether BASE + OFFSET + BITPOS may wrap around the address
8654    space.  This is used to avoid issuing overflow warnings for
8655    expressions like &p->x which can not wrap.  */
8656
8657 static bool
8658 pointer_may_wrap_p (tree base, tree offset, HOST_WIDE_INT bitpos)
8659 {
8660   if (!POINTER_TYPE_P (TREE_TYPE (base)))
8661     return true;
8662
8663   if (bitpos < 0)
8664     return true;
8665
8666   wide_int wi_offset;
8667   int precision = TYPE_PRECISION (TREE_TYPE (base));
8668   if (offset == NULL_TREE)
8669     wi_offset = wi::zero (precision);
8670   else if (TREE_CODE (offset) != INTEGER_CST || TREE_OVERFLOW (offset))
8671     return true;
8672   else
8673     wi_offset = offset;
8674
8675   bool overflow;
8676   wide_int units = wi::shwi (bitpos / BITS_PER_UNIT, precision);
8677   wide_int total = wi::add (wi_offset, units, UNSIGNED, &overflow);
8678   if (overflow)
8679     return true;
8680
8681   if (!wi::fits_uhwi_p (total))
8682     return true;
8683
8684   HOST_WIDE_INT size = int_size_in_bytes (TREE_TYPE (TREE_TYPE (base)));
8685   if (size <= 0)
8686     return true;
8687
8688   /* We can do slightly better for SIZE if we have an ADDR_EXPR of an
8689      array.  */
8690   if (TREE_CODE (base) == ADDR_EXPR)
8691     {
8692       HOST_WIDE_INT base_size;
8693
8694       base_size = int_size_in_bytes (TREE_TYPE (TREE_OPERAND (base, 0)));
8695       if (base_size > 0 && size < base_size)
8696         size = base_size;
8697     }
8698
8699   return total.to_uhwi () > (unsigned HOST_WIDE_INT) size;
8700 }
8701
8702 /* Return the HOST_WIDE_INT least significant bits of T, a sizetype
8703    kind INTEGER_CST.  This makes sure to properly sign-extend the
8704    constant.  */
8705
8706 static HOST_WIDE_INT
8707 size_low_cst (const_tree t)
8708 {
8709   HOST_WIDE_INT w = TREE_INT_CST_ELT (t, 0);
8710   int prec = TYPE_PRECISION (TREE_TYPE (t));
8711   if (prec < HOST_BITS_PER_WIDE_INT)
8712     return sext_hwi (w, prec);
8713   return w;
8714 }
8715
8716 /* Subroutine of fold_binary.  This routine performs all of the
8717    transformations that are common to the equality/inequality
8718    operators (EQ_EXPR and NE_EXPR) and the ordering operators
8719    (LT_EXPR, LE_EXPR, GE_EXPR and GT_EXPR).  Callers other than
8720    fold_binary should call fold_binary.  Fold a comparison with
8721    tree code CODE and type TYPE with operands OP0 and OP1.  Return
8722    the folded comparison or NULL_TREE.  */
8723
8724 static tree
8725 fold_comparison (location_t loc, enum tree_code code, tree type,
8726                  tree op0, tree op1)
8727 {
8728   const bool equality_code = (code == EQ_EXPR || code == NE_EXPR);
8729   tree arg0, arg1, tem;
8730
8731   arg0 = op0;
8732   arg1 = op1;
8733
8734   STRIP_SIGN_NOPS (arg0);
8735   STRIP_SIGN_NOPS (arg1);
8736
8737   /* Transform comparisons of the form X +- C1 CMP C2 to X CMP C2 -+ C1.  */
8738   if ((TREE_CODE (arg0) == PLUS_EXPR || TREE_CODE (arg0) == MINUS_EXPR)
8739       && (equality_code
8740           || (ANY_INTEGRAL_TYPE_P (TREE_TYPE (arg0))
8741               && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0))))
8742       && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
8743       && !TREE_OVERFLOW (TREE_OPERAND (arg0, 1))
8744       && TREE_CODE (arg1) == INTEGER_CST
8745       && !TREE_OVERFLOW (arg1))
8746     {
8747       const enum tree_code
8748         reverse_op = TREE_CODE (arg0) == PLUS_EXPR ? MINUS_EXPR : PLUS_EXPR;
8749       tree const1 = TREE_OPERAND (arg0, 1);
8750       tree const2 = fold_convert_loc (loc, TREE_TYPE (const1), arg1);
8751       tree variable = TREE_OPERAND (arg0, 0);
8752       tree new_const = int_const_binop (reverse_op, const2, const1);
8753
8754       /* If the constant operation overflowed this can be
8755          simplified as a comparison against INT_MAX/INT_MIN.  */
8756       if (TREE_OVERFLOW (new_const)
8757           && !TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg0)))
8758         {
8759           int const1_sgn = tree_int_cst_sgn (const1);
8760           enum tree_code code2 = code;
8761
8762           /* Get the sign of the constant on the lhs if the
8763              operation were VARIABLE + CONST1.  */
8764           if (TREE_CODE (arg0) == MINUS_EXPR)
8765             const1_sgn = -const1_sgn;
8766
8767           /* The sign of the constant determines if we overflowed
8768              INT_MAX (const1_sgn == -1) or INT_MIN (const1_sgn == 1).
8769              Canonicalize to the INT_MIN overflow by swapping the comparison
8770              if necessary.  */
8771           if (const1_sgn == -1)
8772             code2 = swap_tree_comparison (code);
8773
8774           /* We now can look at the canonicalized case
8775                VARIABLE + 1  CODE2  INT_MIN
8776              and decide on the result.  */
8777           switch (code2)
8778             {
8779             case EQ_EXPR:
8780             case LT_EXPR:
8781             case LE_EXPR:
8782               return
8783                 omit_one_operand_loc (loc, type, boolean_false_node, variable);
8784
8785             case NE_EXPR:
8786             case GE_EXPR:
8787             case GT_EXPR:
8788               return
8789                 omit_one_operand_loc (loc, type, boolean_true_node, variable);
8790
8791             default:
8792               gcc_unreachable ();
8793             }
8794         }
8795       else
8796         {
8797           if (!equality_code)
8798             fold_overflow_warning ("assuming signed overflow does not occur "
8799                                    "when changing X +- C1 cmp C2 to "
8800                                    "X cmp C2 -+ C1",
8801                                    WARN_STRICT_OVERFLOW_COMPARISON);
8802           return fold_build2_loc (loc, code, type, variable, new_const);
8803         }
8804     }
8805
8806   /* Transform comparisons of the form X - Y CMP 0 to X CMP Y.  */
8807   if (TREE_CODE (arg0) == MINUS_EXPR
8808       && equality_code
8809       && integer_zerop (arg1))
8810     {
8811       /* ??? The transformation is valid for the other operators if overflow
8812          is undefined for the type, but performing it here badly interacts
8813          with the transformation in fold_cond_expr_with_comparison which
8814          attempts to synthetize ABS_EXPR.  */
8815       if (!equality_code)
8816         fold_overflow_warning ("assuming signed overflow does not occur "
8817                                "when changing X - Y cmp 0 to X cmp Y",
8818                                WARN_STRICT_OVERFLOW_COMPARISON);
8819       return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0),
8820                               TREE_OPERAND (arg0, 1));
8821     }
8822
8823   /* For comparisons of pointers we can decompose it to a compile time
8824      comparison of the base objects and the offsets into the object.
8825      This requires at least one operand being an ADDR_EXPR or a
8826      POINTER_PLUS_EXPR to do more than the operand_equal_p test below.  */
8827   if (POINTER_TYPE_P (TREE_TYPE (arg0))
8828       && (TREE_CODE (arg0) == ADDR_EXPR
8829           || TREE_CODE (arg1) == ADDR_EXPR
8830           || TREE_CODE (arg0) == POINTER_PLUS_EXPR
8831           || TREE_CODE (arg1) == POINTER_PLUS_EXPR))
8832     {
8833       tree base0, base1, offset0 = NULL_TREE, offset1 = NULL_TREE;
8834       HOST_WIDE_INT bitsize, bitpos0 = 0, bitpos1 = 0;
8835       machine_mode mode;
8836       int volatilep, unsignedp;
8837       bool indirect_base0 = false, indirect_base1 = false;
8838
8839       /* Get base and offset for the access.  Strip ADDR_EXPR for
8840          get_inner_reference, but put it back by stripping INDIRECT_REF
8841          off the base object if possible.  indirect_baseN will be true
8842          if baseN is not an address but refers to the object itself.  */
8843       base0 = arg0;
8844       if (TREE_CODE (arg0) == ADDR_EXPR)
8845         {
8846           base0 = get_inner_reference (TREE_OPERAND (arg0, 0),
8847                                        &bitsize, &bitpos0, &offset0, &mode,
8848                                        &unsignedp, &volatilep, false);
8849           if (TREE_CODE (base0) == INDIRECT_REF)
8850             base0 = TREE_OPERAND (base0, 0);
8851           else
8852             indirect_base0 = true;
8853         }
8854       else if (TREE_CODE (arg0) == POINTER_PLUS_EXPR)
8855         {
8856           base0 = TREE_OPERAND (arg0, 0);
8857           STRIP_SIGN_NOPS (base0);
8858           if (TREE_CODE (base0) == ADDR_EXPR)
8859             {
8860               base0 = TREE_OPERAND (base0, 0);
8861               indirect_base0 = true;
8862             }
8863           offset0 = TREE_OPERAND (arg0, 1);
8864           if (tree_fits_shwi_p (offset0))
8865             {
8866               HOST_WIDE_INT off = size_low_cst (offset0);
8867               if ((HOST_WIDE_INT) (((unsigned HOST_WIDE_INT) off)
8868                                    * BITS_PER_UNIT)
8869                   / BITS_PER_UNIT == (HOST_WIDE_INT) off)
8870                 {
8871                   bitpos0 = off * BITS_PER_UNIT;
8872                   offset0 = NULL_TREE;
8873                 }
8874             }
8875         }
8876
8877       base1 = arg1;
8878       if (TREE_CODE (arg1) == ADDR_EXPR)
8879         {
8880           base1 = get_inner_reference (TREE_OPERAND (arg1, 0),
8881                                        &bitsize, &bitpos1, &offset1, &mode,
8882                                        &unsignedp, &volatilep, false);
8883           if (TREE_CODE (base1) == INDIRECT_REF)
8884             base1 = TREE_OPERAND (base1, 0);
8885           else
8886             indirect_base1 = true;
8887         }
8888       else if (TREE_CODE (arg1) == POINTER_PLUS_EXPR)
8889         {
8890           base1 = TREE_OPERAND (arg1, 0);
8891           STRIP_SIGN_NOPS (base1);
8892           if (TREE_CODE (base1) == ADDR_EXPR)
8893             {
8894               base1 = TREE_OPERAND (base1, 0);
8895               indirect_base1 = true;
8896             }
8897           offset1 = TREE_OPERAND (arg1, 1);
8898           if (tree_fits_shwi_p (offset1))
8899             {
8900               HOST_WIDE_INT off = size_low_cst (offset1);
8901               if ((HOST_WIDE_INT) (((unsigned HOST_WIDE_INT) off)
8902                                    * BITS_PER_UNIT)
8903                   / BITS_PER_UNIT == (HOST_WIDE_INT) off)
8904                 {
8905                   bitpos1 = off * BITS_PER_UNIT;
8906                   offset1 = NULL_TREE;
8907                 }
8908             }
8909         }
8910
8911       /* A local variable can never be pointed to by
8912          the default SSA name of an incoming parameter.  */
8913       if ((TREE_CODE (arg0) == ADDR_EXPR
8914            && indirect_base0
8915            && TREE_CODE (base0) == VAR_DECL
8916            && auto_var_in_fn_p (base0, current_function_decl)
8917            && !indirect_base1
8918            && TREE_CODE (base1) == SSA_NAME
8919            && SSA_NAME_IS_DEFAULT_DEF (base1)
8920            && TREE_CODE (SSA_NAME_VAR (base1)) == PARM_DECL)
8921           || (TREE_CODE (arg1) == ADDR_EXPR
8922               && indirect_base1
8923               && TREE_CODE (base1) == VAR_DECL
8924               && auto_var_in_fn_p (base1, current_function_decl)
8925               && !indirect_base0
8926               && TREE_CODE (base0) == SSA_NAME
8927               && SSA_NAME_IS_DEFAULT_DEF (base0)
8928               && TREE_CODE (SSA_NAME_VAR (base0)) == PARM_DECL))
8929         {
8930           if (code == NE_EXPR)
8931             return constant_boolean_node (1, type);
8932           else if (code == EQ_EXPR)
8933             return constant_boolean_node (0, type);
8934         }
8935       /* If we have equivalent bases we might be able to simplify.  */
8936       else if (indirect_base0 == indirect_base1
8937                && operand_equal_p (base0, base1, 0))
8938         {
8939           /* We can fold this expression to a constant if the non-constant
8940              offset parts are equal.  */
8941           if ((offset0 == offset1
8942                || (offset0 && offset1
8943                    && operand_equal_p (offset0, offset1, 0)))
8944               && (code == EQ_EXPR
8945                   || code == NE_EXPR
8946                   || (indirect_base0 && DECL_P (base0))
8947                   || POINTER_TYPE_OVERFLOW_UNDEFINED))
8948
8949             {
8950               if (!equality_code
8951                   && bitpos0 != bitpos1
8952                   && (pointer_may_wrap_p (base0, offset0, bitpos0)
8953                       || pointer_may_wrap_p (base1, offset1, bitpos1)))
8954                 fold_overflow_warning (("assuming pointer wraparound does not "
8955                                         "occur when comparing P +- C1 with "
8956                                         "P +- C2"),
8957                                        WARN_STRICT_OVERFLOW_CONDITIONAL);
8958
8959               switch (code)
8960                 {
8961                 case EQ_EXPR:
8962                   return constant_boolean_node (bitpos0 == bitpos1, type);
8963                 case NE_EXPR:
8964                   return constant_boolean_node (bitpos0 != bitpos1, type);
8965                 case LT_EXPR:
8966                   return constant_boolean_node (bitpos0 < bitpos1, type);
8967                 case LE_EXPR:
8968                   return constant_boolean_node (bitpos0 <= bitpos1, type);
8969                 case GE_EXPR:
8970                   return constant_boolean_node (bitpos0 >= bitpos1, type);
8971                 case GT_EXPR:
8972                   return constant_boolean_node (bitpos0 > bitpos1, type);
8973                 default:;
8974                 }
8975             }
8976           /* We can simplify the comparison to a comparison of the variable
8977              offset parts if the constant offset parts are equal.
8978              Be careful to use signed sizetype here because otherwise we
8979              mess with array offsets in the wrong way.  This is possible
8980              because pointer arithmetic is restricted to retain within an
8981              object and overflow on pointer differences is undefined as of
8982              6.5.6/8 and /9 with respect to the signed ptrdiff_t.  */
8983           else if (bitpos0 == bitpos1
8984                    && (equality_code
8985                        || (indirect_base0 && DECL_P (base0))
8986                        || POINTER_TYPE_OVERFLOW_UNDEFINED))
8987             {
8988               /* By converting to signed sizetype we cover middle-end pointer
8989                  arithmetic which operates on unsigned pointer types of size
8990                  type size and ARRAY_REF offsets which are properly sign or
8991                  zero extended from their type in case it is narrower than
8992                  sizetype.  */
8993               if (offset0 == NULL_TREE)
8994                 offset0 = build_int_cst (ssizetype, 0);
8995               else
8996                 offset0 = fold_convert_loc (loc, ssizetype, offset0);
8997               if (offset1 == NULL_TREE)
8998                 offset1 = build_int_cst (ssizetype, 0);
8999               else
9000                 offset1 = fold_convert_loc (loc, ssizetype, offset1);
9001
9002               if (!equality_code
9003                   && (pointer_may_wrap_p (base0, offset0, bitpos0)
9004                       || pointer_may_wrap_p (base1, offset1, bitpos1)))
9005                 fold_overflow_warning (("assuming pointer wraparound does not "
9006                                         "occur when comparing P +- C1 with "
9007                                         "P +- C2"),
9008                                        WARN_STRICT_OVERFLOW_COMPARISON);
9009
9010               return fold_build2_loc (loc, code, type, offset0, offset1);
9011             }
9012         }
9013       /* For non-equal bases we can simplify if they are addresses
9014          declarations with different addresses.  */
9015       else if (indirect_base0 && indirect_base1
9016                /* We know that !operand_equal_p (base0, base1, 0)
9017                   because the if condition was false.  But make
9018                   sure two decls are not the same.  */
9019                && base0 != base1
9020                && TREE_CODE (arg0) == ADDR_EXPR
9021                && TREE_CODE (arg1) == ADDR_EXPR
9022                && DECL_P (base0)
9023                && DECL_P (base1)
9024                /* Watch for aliases.  */
9025                && (!decl_in_symtab_p (base0)
9026                    || !decl_in_symtab_p (base1)
9027                    || !symtab_node::get_create (base0)->equal_address_to
9028                          (symtab_node::get_create (base1))))
9029         {
9030           if (code == EQ_EXPR)
9031             return omit_two_operands_loc (loc, type, boolean_false_node,
9032                                       arg0, arg1);
9033           else if (code == NE_EXPR)
9034             return omit_two_operands_loc (loc, type, boolean_true_node,
9035                                       arg0, arg1);
9036         }
9037       /* For equal offsets we can simplify to a comparison of the
9038          base addresses.  */
9039       else if (bitpos0 == bitpos1
9040                && (indirect_base0
9041                    ? base0 != TREE_OPERAND (arg0, 0) : base0 != arg0)
9042                && (indirect_base1
9043                    ? base1 != TREE_OPERAND (arg1, 0) : base1 != arg1)
9044                && ((offset0 == offset1)
9045                    || (offset0 && offset1
9046                        && operand_equal_p (offset0, offset1, 0))))
9047         {
9048           if (indirect_base0)
9049             base0 = build_fold_addr_expr_loc (loc, base0);
9050           if (indirect_base1)
9051             base1 = build_fold_addr_expr_loc (loc, base1);
9052           return fold_build2_loc (loc, code, type, base0, base1);
9053         }
9054     }
9055
9056   /* Transform comparisons of the form X +- C1 CMP Y +- C2 to
9057      X CMP Y +- C2 +- C1 for signed X, Y.  This is valid if
9058      the resulting offset is smaller in absolute value than the
9059      original one and has the same sign.  */
9060   if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (arg0))
9061       && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0))
9062       && (TREE_CODE (arg0) == PLUS_EXPR || TREE_CODE (arg0) == MINUS_EXPR)
9063       && (TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
9064           && !TREE_OVERFLOW (TREE_OPERAND (arg0, 1)))
9065       && (TREE_CODE (arg1) == PLUS_EXPR || TREE_CODE (arg1) == MINUS_EXPR)
9066       && (TREE_CODE (TREE_OPERAND (arg1, 1)) == INTEGER_CST
9067           && !TREE_OVERFLOW (TREE_OPERAND (arg1, 1))))
9068     {
9069       tree const1 = TREE_OPERAND (arg0, 1);
9070       tree const2 = TREE_OPERAND (arg1, 1);
9071       tree variable1 = TREE_OPERAND (arg0, 0);
9072       tree variable2 = TREE_OPERAND (arg1, 0);
9073       tree cst;
9074       const char * const warnmsg = G_("assuming signed overflow does not "
9075                                       "occur when combining constants around "
9076                                       "a comparison");
9077
9078       /* Put the constant on the side where it doesn't overflow and is
9079          of lower absolute value and of same sign than before.  */
9080       cst = int_const_binop (TREE_CODE (arg0) == TREE_CODE (arg1)
9081                              ? MINUS_EXPR : PLUS_EXPR,
9082                              const2, const1);
9083       if (!TREE_OVERFLOW (cst)
9084           && tree_int_cst_compare (const2, cst) == tree_int_cst_sgn (const2)
9085           && tree_int_cst_sgn (cst) == tree_int_cst_sgn (const2))
9086         {
9087           fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_COMPARISON);
9088           return fold_build2_loc (loc, code, type,
9089                                   variable1,
9090                                   fold_build2_loc (loc, TREE_CODE (arg1),
9091                                                    TREE_TYPE (arg1),
9092                                                    variable2, cst));
9093         }
9094
9095       cst = int_const_binop (TREE_CODE (arg0) == TREE_CODE (arg1)
9096                              ? MINUS_EXPR : PLUS_EXPR,
9097                              const1, const2);
9098       if (!TREE_OVERFLOW (cst)
9099           && tree_int_cst_compare (const1, cst) == tree_int_cst_sgn (const1)
9100           && tree_int_cst_sgn (cst) == tree_int_cst_sgn (const1))
9101         {
9102           fold_overflow_warning (warnmsg, WARN_STRICT_OVERFLOW_COMPARISON);
9103           return fold_build2_loc (loc, code, type,
9104                                   fold_build2_loc (loc, TREE_CODE (arg0),
9105                                                    TREE_TYPE (arg0),
9106                                                    variable1, cst),
9107                                   variable2);
9108         }
9109     }
9110
9111   /* Transform comparisons of the form X * C1 CMP 0 to X CMP 0 in the
9112      signed arithmetic case.  That form is created by the compiler
9113      often enough for folding it to be of value.  One example is in
9114      computing loop trip counts after Operator Strength Reduction.  */
9115   if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (arg0))
9116       && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg0))
9117       && TREE_CODE (arg0) == MULT_EXPR
9118       && (TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
9119           && !TREE_OVERFLOW (TREE_OPERAND (arg0, 1)))
9120       && integer_zerop (arg1))
9121     {
9122       tree const1 = TREE_OPERAND (arg0, 1);
9123       tree const2 = arg1;                       /* zero */
9124       tree variable1 = TREE_OPERAND (arg0, 0);
9125       enum tree_code cmp_code = code;
9126
9127       /* Handle unfolded multiplication by zero.  */
9128       if (integer_zerop (const1))
9129         return fold_build2_loc (loc, cmp_code, type, const1, const2);
9130
9131       fold_overflow_warning (("assuming signed overflow does not occur when "
9132                               "eliminating multiplication in comparison "
9133                               "with zero"),
9134                              WARN_STRICT_OVERFLOW_COMPARISON);
9135
9136       /* If const1 is negative we swap the sense of the comparison.  */
9137       if (tree_int_cst_sgn (const1) < 0)
9138         cmp_code = swap_tree_comparison (cmp_code);
9139
9140       return fold_build2_loc (loc, cmp_code, type, variable1, const2);
9141     }
9142
9143   tem = maybe_canonicalize_comparison (loc, code, type, arg0, arg1);
9144   if (tem)
9145     return tem;
9146
9147   if (FLOAT_TYPE_P (TREE_TYPE (arg0)))
9148     {
9149       tree targ0 = strip_float_extensions (arg0);
9150       tree targ1 = strip_float_extensions (arg1);
9151       tree newtype = TREE_TYPE (targ0);
9152
9153       if (TYPE_PRECISION (TREE_TYPE (targ1)) > TYPE_PRECISION (newtype))
9154         newtype = TREE_TYPE (targ1);
9155
9156       /* Fold (double)float1 CMP (double)float2 into float1 CMP float2.  */
9157       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (TREE_TYPE (arg0)))
9158         return fold_build2_loc (loc, code, type,
9159                             fold_convert_loc (loc, newtype, targ0),
9160                             fold_convert_loc (loc, newtype, targ1));
9161
9162       /* (-a) CMP (-b) -> b CMP a  */
9163       if (TREE_CODE (arg0) == NEGATE_EXPR
9164           && TREE_CODE (arg1) == NEGATE_EXPR)
9165         return fold_build2_loc (loc, code, type, TREE_OPERAND (arg1, 0),
9166                             TREE_OPERAND (arg0, 0));
9167
9168       if (TREE_CODE (arg1) == REAL_CST)
9169         {
9170           REAL_VALUE_TYPE cst;
9171           cst = TREE_REAL_CST (arg1);
9172
9173           /* (-a) CMP CST -> a swap(CMP) (-CST)  */
9174           if (TREE_CODE (arg0) == NEGATE_EXPR)
9175             return fold_build2_loc (loc, swap_tree_comparison (code), type,
9176                                 TREE_OPERAND (arg0, 0),
9177                                 build_real (TREE_TYPE (arg1),
9178                                             real_value_negate (&cst)));
9179
9180           /* IEEE doesn't distinguish +0 and -0 in comparisons.  */
9181           /* a CMP (-0) -> a CMP 0  */
9182           if (REAL_VALUE_MINUS_ZERO (cst))
9183             return fold_build2_loc (loc, code, type, arg0,
9184                                 build_real (TREE_TYPE (arg1), dconst0));
9185
9186           /* x != NaN is always true, other ops are always false.  */
9187           if (REAL_VALUE_ISNAN (cst)
9188               && ! HONOR_SNANS (arg1))
9189             {
9190               tem = (code == NE_EXPR) ? integer_one_node : integer_zero_node;
9191               return omit_one_operand_loc (loc, type, tem, arg0);
9192             }
9193
9194           /* Fold comparisons against infinity.  */
9195           if (REAL_VALUE_ISINF (cst)
9196               && MODE_HAS_INFINITIES (TYPE_MODE (TREE_TYPE (arg1))))
9197             {
9198               tem = fold_inf_compare (loc, code, type, arg0, arg1);
9199               if (tem != NULL_TREE)
9200                 return tem;
9201             }
9202         }
9203
9204       /* If this is a comparison of a real constant with a PLUS_EXPR
9205          or a MINUS_EXPR of a real constant, we can convert it into a
9206          comparison with a revised real constant as long as no overflow
9207          occurs when unsafe_math_optimizations are enabled.  */
9208       if (flag_unsafe_math_optimizations
9209           && TREE_CODE (arg1) == REAL_CST
9210           && (TREE_CODE (arg0) == PLUS_EXPR
9211               || TREE_CODE (arg0) == MINUS_EXPR)
9212           && TREE_CODE (TREE_OPERAND (arg0, 1)) == REAL_CST
9213           && 0 != (tem = const_binop (TREE_CODE (arg0) == PLUS_EXPR
9214                                       ? MINUS_EXPR : PLUS_EXPR,
9215                                       arg1, TREE_OPERAND (arg0, 1)))
9216           && !TREE_OVERFLOW (tem))
9217         return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0), tem);
9218
9219       /* Likewise, we can simplify a comparison of a real constant with
9220          a MINUS_EXPR whose first operand is also a real constant, i.e.
9221          (c1 - x) < c2 becomes x > c1-c2.  Reordering is allowed on
9222          floating-point types only if -fassociative-math is set.  */
9223       if (flag_associative_math
9224           && TREE_CODE (arg1) == REAL_CST
9225           && TREE_CODE (arg0) == MINUS_EXPR
9226           && TREE_CODE (TREE_OPERAND (arg0, 0)) == REAL_CST
9227           && 0 != (tem = const_binop (MINUS_EXPR, TREE_OPERAND (arg0, 0),
9228                                       arg1))
9229           && !TREE_OVERFLOW (tem))
9230         return fold_build2_loc (loc, swap_tree_comparison (code), type,
9231                             TREE_OPERAND (arg0, 1), tem);
9232
9233       /* Fold comparisons against built-in math functions.  */
9234       if (TREE_CODE (arg1) == REAL_CST
9235           && flag_unsafe_math_optimizations
9236           && ! flag_errno_math)
9237         {
9238           enum built_in_function fcode = builtin_mathfn_code (arg0);
9239
9240           if (fcode != END_BUILTINS)
9241             {
9242               tem = fold_mathfn_compare (loc, fcode, code, type, arg0, arg1);
9243               if (tem != NULL_TREE)
9244                 return tem;
9245             }
9246         }
9247     }
9248
9249   if (TREE_CODE (TREE_TYPE (arg0)) == INTEGER_TYPE
9250       && CONVERT_EXPR_P (arg0))
9251     {
9252       /* If we are widening one operand of an integer comparison,
9253          see if the other operand is similarly being widened.  Perhaps we
9254          can do the comparison in the narrower type.  */
9255       tem = fold_widened_comparison (loc, code, type, arg0, arg1);
9256       if (tem)
9257         return tem;
9258
9259       /* Or if we are changing signedness.  */
9260       tem = fold_sign_changed_comparison (loc, code, type, arg0, arg1);
9261       if (tem)
9262         return tem;
9263     }
9264
9265   /* If this is comparing a constant with a MIN_EXPR or a MAX_EXPR of a
9266      constant, we can simplify it.  */
9267   if (TREE_CODE (arg1) == INTEGER_CST
9268       && (TREE_CODE (arg0) == MIN_EXPR
9269           || TREE_CODE (arg0) == MAX_EXPR)
9270       && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
9271     {
9272       tem = optimize_minmax_comparison (loc, code, type, op0, op1);
9273       if (tem)
9274         return tem;
9275     }
9276
9277   /* Simplify comparison of something with itself.  (For IEEE
9278      floating-point, we can only do some of these simplifications.)  */
9279   if (operand_equal_p (arg0, arg1, 0))
9280     {
9281       switch (code)
9282         {
9283         case EQ_EXPR:
9284           if (! FLOAT_TYPE_P (TREE_TYPE (arg0))
9285               || ! HONOR_NANS (arg0))
9286             return constant_boolean_node (1, type);
9287           break;
9288
9289         case GE_EXPR:
9290         case LE_EXPR:
9291           if (! FLOAT_TYPE_P (TREE_TYPE (arg0))
9292               || ! HONOR_NANS (arg0))
9293             return constant_boolean_node (1, type);
9294           return fold_build2_loc (loc, EQ_EXPR, type, arg0, arg1);
9295
9296         case NE_EXPR:
9297           /* For NE, we can only do this simplification if integer
9298              or we don't honor IEEE floating point NaNs.  */
9299           if (FLOAT_TYPE_P (TREE_TYPE (arg0))
9300               && HONOR_NANS (arg0))
9301             break;
9302           /* ... fall through ...  */
9303         case GT_EXPR:
9304         case LT_EXPR:
9305           return constant_boolean_node (0, type);
9306         default:
9307           gcc_unreachable ();
9308         }
9309     }
9310
9311   /* If we are comparing an expression that just has comparisons
9312      of two integer values, arithmetic expressions of those comparisons,
9313      and constants, we can simplify it.  There are only three cases
9314      to check: the two values can either be equal, the first can be
9315      greater, or the second can be greater.  Fold the expression for
9316      those three values.  Since each value must be 0 or 1, we have
9317      eight possibilities, each of which corresponds to the constant 0
9318      or 1 or one of the six possible comparisons.
9319
9320      This handles common cases like (a > b) == 0 but also handles
9321      expressions like  ((x > y) - (y > x)) > 0, which supposedly
9322      occur in macroized code.  */
9323
9324   if (TREE_CODE (arg1) == INTEGER_CST && TREE_CODE (arg0) != INTEGER_CST)
9325     {
9326       tree cval1 = 0, cval2 = 0;
9327       int save_p = 0;
9328
9329       if (twoval_comparison_p (arg0, &cval1, &cval2, &save_p)
9330           /* Don't handle degenerate cases here; they should already
9331              have been handled anyway.  */
9332           && cval1 != 0 && cval2 != 0
9333           && ! (TREE_CONSTANT (cval1) && TREE_CONSTANT (cval2))
9334           && TREE_TYPE (cval1) == TREE_TYPE (cval2)
9335           && INTEGRAL_TYPE_P (TREE_TYPE (cval1))
9336           && TYPE_MAX_VALUE (TREE_TYPE (cval1))
9337           && TYPE_MAX_VALUE (TREE_TYPE (cval2))
9338           && ! operand_equal_p (TYPE_MIN_VALUE (TREE_TYPE (cval1)),
9339                                 TYPE_MAX_VALUE (TREE_TYPE (cval2)), 0))
9340         {
9341           tree maxval = TYPE_MAX_VALUE (TREE_TYPE (cval1));
9342           tree minval = TYPE_MIN_VALUE (TREE_TYPE (cval1));
9343
9344           /* We can't just pass T to eval_subst in case cval1 or cval2
9345              was the same as ARG1.  */
9346
9347           tree high_result
9348                 = fold_build2_loc (loc, code, type,
9349                                eval_subst (loc, arg0, cval1, maxval,
9350                                            cval2, minval),
9351                                arg1);
9352           tree equal_result
9353                 = fold_build2_loc (loc, code, type,
9354                                eval_subst (loc, arg0, cval1, maxval,
9355                                            cval2, maxval),
9356                                arg1);
9357           tree low_result
9358                 = fold_build2_loc (loc, code, type,
9359                                eval_subst (loc, arg0, cval1, minval,
9360                                            cval2, maxval),
9361                                arg1);
9362
9363           /* All three of these results should be 0 or 1.  Confirm they are.
9364              Then use those values to select the proper code to use.  */
9365
9366           if (TREE_CODE (high_result) == INTEGER_CST
9367               && TREE_CODE (equal_result) == INTEGER_CST
9368               && TREE_CODE (low_result) == INTEGER_CST)
9369             {
9370               /* Make a 3-bit mask with the high-order bit being the
9371                  value for `>', the next for '=', and the low for '<'.  */
9372               switch ((integer_onep (high_result) * 4)
9373                       + (integer_onep (equal_result) * 2)
9374                       + integer_onep (low_result))
9375                 {
9376                 case 0:
9377                   /* Always false.  */
9378                   return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
9379                 case 1:
9380                   code = LT_EXPR;
9381                   break;
9382                 case 2:
9383                   code = EQ_EXPR;
9384                   break;
9385                 case 3:
9386                   code = LE_EXPR;
9387                   break;
9388                 case 4:
9389                   code = GT_EXPR;
9390                   break;
9391                 case 5:
9392                   code = NE_EXPR;
9393                   break;
9394                 case 6:
9395                   code = GE_EXPR;
9396                   break;
9397                 case 7:
9398                   /* Always true.  */
9399                   return omit_one_operand_loc (loc, type, integer_one_node, arg0);
9400                 }
9401
9402               if (save_p)
9403                 {
9404                   tem = save_expr (build2 (code, type, cval1, cval2));
9405                   SET_EXPR_LOCATION (tem, loc);
9406                   return tem;
9407                 }
9408               return fold_build2_loc (loc, code, type, cval1, cval2);
9409             }
9410         }
9411     }
9412
9413   /* We can fold X/C1 op C2 where C1 and C2 are integer constants
9414      into a single range test.  */
9415   if ((TREE_CODE (arg0) == TRUNC_DIV_EXPR
9416        || TREE_CODE (arg0) == EXACT_DIV_EXPR)
9417       && TREE_CODE (arg1) == INTEGER_CST
9418       && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
9419       && !integer_zerop (TREE_OPERAND (arg0, 1))
9420       && !TREE_OVERFLOW (TREE_OPERAND (arg0, 1))
9421       && !TREE_OVERFLOW (arg1))
9422     {
9423       tem = fold_div_compare (loc, code, type, arg0, arg1);
9424       if (tem != NULL_TREE)
9425         return tem;
9426     }
9427
9428   /* Fold ~X op ~Y as Y op X.  */
9429   if (TREE_CODE (arg0) == BIT_NOT_EXPR
9430       && TREE_CODE (arg1) == BIT_NOT_EXPR)
9431     {
9432       tree cmp_type = TREE_TYPE (TREE_OPERAND (arg0, 0));
9433       return fold_build2_loc (loc, code, type,
9434                           fold_convert_loc (loc, cmp_type,
9435                                             TREE_OPERAND (arg1, 0)),
9436                           TREE_OPERAND (arg0, 0));
9437     }
9438
9439   /* Fold ~X op C as X op' ~C, where op' is the swapped comparison.  */
9440   if (TREE_CODE (arg0) == BIT_NOT_EXPR
9441       && (TREE_CODE (arg1) == INTEGER_CST || TREE_CODE (arg1) == VECTOR_CST))
9442     {
9443       tree cmp_type = TREE_TYPE (TREE_OPERAND (arg0, 0));
9444       return fold_build2_loc (loc, swap_tree_comparison (code), type,
9445                           TREE_OPERAND (arg0, 0),
9446                           fold_build1_loc (loc, BIT_NOT_EXPR, cmp_type,
9447                                        fold_convert_loc (loc, cmp_type, arg1)));
9448     }
9449
9450   return NULL_TREE;
9451 }
9452
9453
9454 /* Subroutine of fold_binary.  Optimize complex multiplications of the
9455    form z * conj(z), as pow(realpart(z),2) + pow(imagpart(z),2).  The
9456    argument EXPR represents the expression "z" of type TYPE.  */
9457
9458 static tree
9459 fold_mult_zconjz (location_t loc, tree type, tree expr)
9460 {
9461   tree itype = TREE_TYPE (type);
9462   tree rpart, ipart, tem;
9463
9464   if (TREE_CODE (expr) == COMPLEX_EXPR)
9465     {
9466       rpart = TREE_OPERAND (expr, 0);
9467       ipart = TREE_OPERAND (expr, 1);
9468     }
9469   else if (TREE_CODE (expr) == COMPLEX_CST)
9470     {
9471       rpart = TREE_REALPART (expr);
9472       ipart = TREE_IMAGPART (expr);
9473     }
9474   else
9475     {
9476       expr = save_expr (expr);
9477       rpart = fold_build1_loc (loc, REALPART_EXPR, itype, expr);
9478       ipart = fold_build1_loc (loc, IMAGPART_EXPR, itype, expr);
9479     }
9480
9481   rpart = save_expr (rpart);
9482   ipart = save_expr (ipart);
9483   tem = fold_build2_loc (loc, PLUS_EXPR, itype,
9484                      fold_build2_loc (loc, MULT_EXPR, itype, rpart, rpart),
9485                      fold_build2_loc (loc, MULT_EXPR, itype, ipart, ipart));
9486   return fold_build2_loc (loc, COMPLEX_EXPR, type, tem,
9487                           build_zero_cst (itype));
9488 }
9489
9490
9491 /* Subroutine of fold_binary.  If P is the value of EXPR, computes
9492    power-of-two M and (arbitrary) N such that M divides (P-N).  This condition
9493    guarantees that P and N have the same least significant log2(M) bits.
9494    N is not otherwise constrained.  In particular, N is not normalized to
9495    0 <= N < M as is common.  In general, the precise value of P is unknown.
9496    M is chosen as large as possible such that constant N can be determined.
9497
9498    Returns M and sets *RESIDUE to N.
9499
9500    If ALLOW_FUNC_ALIGN is true, do take functions' DECL_ALIGN_UNIT into
9501    account.  This is not always possible due to PR 35705.
9502  */
9503
9504 static unsigned HOST_WIDE_INT
9505 get_pointer_modulus_and_residue (tree expr, unsigned HOST_WIDE_INT *residue,
9506                                  bool allow_func_align)
9507 {
9508   enum tree_code code;
9509
9510   *residue = 0;
9511
9512   code = TREE_CODE (expr);
9513   if (code == ADDR_EXPR)
9514     {
9515       unsigned int bitalign;
9516       get_object_alignment_1 (TREE_OPERAND (expr, 0), &bitalign, residue);
9517       *residue /= BITS_PER_UNIT;
9518       return bitalign / BITS_PER_UNIT;
9519     }
9520   else if (code == POINTER_PLUS_EXPR)
9521     {
9522       tree op0, op1;
9523       unsigned HOST_WIDE_INT modulus;
9524       enum tree_code inner_code;
9525
9526       op0 = TREE_OPERAND (expr, 0);
9527       STRIP_NOPS (op0);
9528       modulus = get_pointer_modulus_and_residue (op0, residue,
9529                                                  allow_func_align);
9530
9531       op1 = TREE_OPERAND (expr, 1);
9532       STRIP_NOPS (op1);
9533       inner_code = TREE_CODE (op1);
9534       if (inner_code == INTEGER_CST)
9535         {
9536           *residue += TREE_INT_CST_LOW (op1);
9537           return modulus;
9538         }
9539       else if (inner_code == MULT_EXPR)
9540         {
9541           op1 = TREE_OPERAND (op1, 1);
9542           if (TREE_CODE (op1) == INTEGER_CST)
9543             {
9544               unsigned HOST_WIDE_INT align;
9545
9546               /* Compute the greatest power-of-2 divisor of op1.  */
9547               align = TREE_INT_CST_LOW (op1);
9548               align &= -align;
9549
9550               /* If align is non-zero and less than *modulus, replace
9551                  *modulus with align., If align is 0, then either op1 is 0
9552                  or the greatest power-of-2 divisor of op1 doesn't fit in an
9553                  unsigned HOST_WIDE_INT.  In either case, no additional
9554                  constraint is imposed.  */
9555               if (align)
9556                 modulus = MIN (modulus, align);
9557
9558               return modulus;
9559             }
9560         }
9561     }
9562
9563   /* If we get here, we were unable to determine anything useful about the
9564      expression.  */
9565   return 1;
9566 }
9567
9568 /* Helper function for fold_vec_perm.  Store elements of VECTOR_CST or
9569    CONSTRUCTOR ARG into array ELTS and return true if successful.  */
9570
9571 static bool
9572 vec_cst_ctor_to_array (tree arg, tree *elts)
9573 {
9574   unsigned int nelts = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg)), i;
9575
9576   if (TREE_CODE (arg) == VECTOR_CST)
9577     {
9578       for (i = 0; i < VECTOR_CST_NELTS (arg); ++i)
9579         elts[i] = VECTOR_CST_ELT (arg, i);
9580     }
9581   else if (TREE_CODE (arg) == CONSTRUCTOR)
9582     {
9583       constructor_elt *elt;
9584
9585       FOR_EACH_VEC_SAFE_ELT (CONSTRUCTOR_ELTS (arg), i, elt)
9586         if (i >= nelts || TREE_CODE (TREE_TYPE (elt->value)) == VECTOR_TYPE)
9587           return false;
9588         else
9589           elts[i] = elt->value;
9590     }
9591   else
9592     return false;
9593   for (; i < nelts; i++)
9594     elts[i]
9595       = fold_convert (TREE_TYPE (TREE_TYPE (arg)), integer_zero_node);
9596   return true;
9597 }
9598
9599 /* Attempt to fold vector permutation of ARG0 and ARG1 vectors using SEL
9600    selector.  Return the folded VECTOR_CST or CONSTRUCTOR if successful,
9601    NULL_TREE otherwise.  */
9602
9603 static tree
9604 fold_vec_perm (tree type, tree arg0, tree arg1, const unsigned char *sel)
9605 {
9606   unsigned int nelts = TYPE_VECTOR_SUBPARTS (type), i;
9607   tree *elts;
9608   bool need_ctor = false;
9609
9610   gcc_assert (TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0)) == nelts
9611               && TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg1)) == nelts);
9612   if (TREE_TYPE (TREE_TYPE (arg0)) != TREE_TYPE (type)
9613       || TREE_TYPE (TREE_TYPE (arg1)) != TREE_TYPE (type))
9614     return NULL_TREE;
9615
9616   elts = XALLOCAVEC (tree, nelts * 3);
9617   if (!vec_cst_ctor_to_array (arg0, elts)
9618       || !vec_cst_ctor_to_array (arg1, elts + nelts))
9619     return NULL_TREE;
9620
9621   for (i = 0; i < nelts; i++)
9622     {
9623       if (!CONSTANT_CLASS_P (elts[sel[i]]))
9624         need_ctor = true;
9625       elts[i + 2 * nelts] = unshare_expr (elts[sel[i]]);
9626     }
9627
9628   if (need_ctor)
9629     {
9630       vec<constructor_elt, va_gc> *v;
9631       vec_alloc (v, nelts);
9632       for (i = 0; i < nelts; i++)
9633         CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, elts[2 * nelts + i]);
9634       return build_constructor (type, v);
9635     }
9636   else
9637     return build_vector (type, &elts[2 * nelts]);
9638 }
9639
9640 /* Try to fold a pointer difference of type TYPE two address expressions of
9641    array references AREF0 and AREF1 using location LOC.  Return a
9642    simplified expression for the difference or NULL_TREE.  */
9643
9644 static tree
9645 fold_addr_of_array_ref_difference (location_t loc, tree type,
9646                                    tree aref0, tree aref1)
9647 {
9648   tree base0 = TREE_OPERAND (aref0, 0);
9649   tree base1 = TREE_OPERAND (aref1, 0);
9650   tree base_offset = build_int_cst (type, 0);
9651
9652   /* If the bases are array references as well, recurse.  If the bases
9653      are pointer indirections compute the difference of the pointers.
9654      If the bases are equal, we are set.  */
9655   if ((TREE_CODE (base0) == ARRAY_REF
9656        && TREE_CODE (base1) == ARRAY_REF
9657        && (base_offset
9658            = fold_addr_of_array_ref_difference (loc, type, base0, base1)))
9659       || (INDIRECT_REF_P (base0)
9660           && INDIRECT_REF_P (base1)
9661           && (base_offset = fold_binary_loc (loc, MINUS_EXPR, type,
9662                                              TREE_OPERAND (base0, 0),
9663                                              TREE_OPERAND (base1, 0))))
9664       || operand_equal_p (base0, base1, 0))
9665     {
9666       tree op0 = fold_convert_loc (loc, type, TREE_OPERAND (aref0, 1));
9667       tree op1 = fold_convert_loc (loc, type, TREE_OPERAND (aref1, 1));
9668       tree esz = fold_convert_loc (loc, type, array_ref_element_size (aref0));
9669       tree diff = build2 (MINUS_EXPR, type, op0, op1);
9670       return fold_build2_loc (loc, PLUS_EXPR, type,
9671                               base_offset,
9672                               fold_build2_loc (loc, MULT_EXPR, type,
9673                                                diff, esz));
9674     }
9675   return NULL_TREE;
9676 }
9677
9678 /* If the real or vector real constant CST of type TYPE has an exact
9679    inverse, return it, else return NULL.  */
9680
9681 tree
9682 exact_inverse (tree type, tree cst)
9683 {
9684   REAL_VALUE_TYPE r;
9685   tree unit_type, *elts;
9686   machine_mode mode;
9687   unsigned vec_nelts, i;
9688
9689   switch (TREE_CODE (cst))
9690     {
9691     case REAL_CST:
9692       r = TREE_REAL_CST (cst);
9693
9694       if (exact_real_inverse (TYPE_MODE (type), &r))
9695         return build_real (type, r);
9696
9697       return NULL_TREE;
9698
9699     case VECTOR_CST:
9700       vec_nelts = VECTOR_CST_NELTS (cst);
9701       elts = XALLOCAVEC (tree, vec_nelts);
9702       unit_type = TREE_TYPE (type);
9703       mode = TYPE_MODE (unit_type);
9704
9705       for (i = 0; i < vec_nelts; i++)
9706         {
9707           r = TREE_REAL_CST (VECTOR_CST_ELT (cst, i));
9708           if (!exact_real_inverse (mode, &r))
9709             return NULL_TREE;
9710           elts[i] = build_real (unit_type, r);
9711         }
9712
9713       return build_vector (type, elts);
9714
9715     default:
9716       return NULL_TREE;
9717     }
9718 }
9719
9720 /*  Mask out the tz least significant bits of X of type TYPE where
9721     tz is the number of trailing zeroes in Y.  */
9722 static wide_int
9723 mask_with_tz (tree type, const wide_int &x, const wide_int &y)
9724 {
9725   int tz = wi::ctz (y);
9726   if (tz > 0)
9727     return wi::mask (tz, true, TYPE_PRECISION (type)) & x;
9728   return x;
9729 }
9730
9731 /* Return true when T is an address and is known to be nonzero.
9732    For floating point we further ensure that T is not denormal.
9733    Similar logic is present in nonzero_address in rtlanal.h.
9734
9735    If the return value is based on the assumption that signed overflow
9736    is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
9737    change *STRICT_OVERFLOW_P.  */
9738
9739 static bool
9740 tree_expr_nonzero_warnv_p (tree t, bool *strict_overflow_p)
9741 {
9742   tree type = TREE_TYPE (t);
9743   enum tree_code code;
9744
9745   /* Doing something useful for floating point would need more work.  */
9746   if (!INTEGRAL_TYPE_P (type) && !POINTER_TYPE_P (type))
9747     return false;
9748
9749   code = TREE_CODE (t);
9750   switch (TREE_CODE_CLASS (code))
9751     {
9752     case tcc_unary:
9753       return tree_unary_nonzero_warnv_p (code, type, TREE_OPERAND (t, 0),
9754                                               strict_overflow_p);
9755     case tcc_binary:
9756     case tcc_comparison:
9757       return tree_binary_nonzero_warnv_p (code, type,
9758                                                TREE_OPERAND (t, 0),
9759                                                TREE_OPERAND (t, 1),
9760                                                strict_overflow_p);
9761     case tcc_constant:
9762     case tcc_declaration:
9763     case tcc_reference:
9764       return tree_single_nonzero_warnv_p (t, strict_overflow_p);
9765
9766     default:
9767       break;
9768     }
9769
9770   switch (code)
9771     {
9772     case TRUTH_NOT_EXPR:
9773       return tree_unary_nonzero_warnv_p (code, type, TREE_OPERAND (t, 0),
9774                                               strict_overflow_p);
9775
9776     case TRUTH_AND_EXPR:
9777     case TRUTH_OR_EXPR:
9778     case TRUTH_XOR_EXPR:
9779       return tree_binary_nonzero_warnv_p (code, type,
9780                                                TREE_OPERAND (t, 0),
9781                                                TREE_OPERAND (t, 1),
9782                                                strict_overflow_p);
9783
9784     case COND_EXPR:
9785     case CONSTRUCTOR:
9786     case OBJ_TYPE_REF:
9787     case ASSERT_EXPR:
9788     case ADDR_EXPR:
9789     case WITH_SIZE_EXPR:
9790     case SSA_NAME:
9791       return tree_single_nonzero_warnv_p (t, strict_overflow_p);
9792
9793     case COMPOUND_EXPR:
9794     case MODIFY_EXPR:
9795     case BIND_EXPR:
9796       return tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 1),
9797                                         strict_overflow_p);
9798
9799     case SAVE_EXPR:
9800       return tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 0),
9801                                         strict_overflow_p);
9802
9803     case CALL_EXPR:
9804       {
9805         tree fndecl = get_callee_fndecl (t);
9806         if (!fndecl) return false;
9807         if (flag_delete_null_pointer_checks && !flag_check_new
9808             && DECL_IS_OPERATOR_NEW (fndecl)
9809             && !TREE_NOTHROW (fndecl))
9810           return true;
9811         if (flag_delete_null_pointer_checks
9812             && lookup_attribute ("returns_nonnull",
9813                  TYPE_ATTRIBUTES (TREE_TYPE (fndecl))))
9814           return true;
9815         return alloca_call_p (t);
9816       }
9817
9818     default:
9819       break;
9820     }
9821   return false;
9822 }
9823
9824 /* Return true when T is an address and is known to be nonzero.
9825    Handle warnings about undefined signed overflow.  */
9826
9827 static bool
9828 tree_expr_nonzero_p (tree t)
9829 {
9830   bool ret, strict_overflow_p;
9831
9832   strict_overflow_p = false;
9833   ret = tree_expr_nonzero_warnv_p (t, &strict_overflow_p);
9834   if (strict_overflow_p)
9835     fold_overflow_warning (("assuming signed overflow does not occur when "
9836                             "determining that expression is always "
9837                             "non-zero"),
9838                            WARN_STRICT_OVERFLOW_MISC);
9839   return ret;
9840 }
9841
9842 /* Fold a binary expression of code CODE and type TYPE with operands
9843    OP0 and OP1.  LOC is the location of the resulting expression.
9844    Return the folded expression if folding is successful.  Otherwise,
9845    return NULL_TREE.  */
9846
9847 tree
9848 fold_binary_loc (location_t loc,
9849              enum tree_code code, tree type, tree op0, tree op1)
9850 {
9851   enum tree_code_class kind = TREE_CODE_CLASS (code);
9852   tree arg0, arg1, tem;
9853   tree t1 = NULL_TREE;
9854   bool strict_overflow_p;
9855   unsigned int prec;
9856
9857   gcc_assert (IS_EXPR_CODE_CLASS (kind)
9858               && TREE_CODE_LENGTH (code) == 2
9859               && op0 != NULL_TREE
9860               && op1 != NULL_TREE);
9861
9862   arg0 = op0;
9863   arg1 = op1;
9864
9865   /* Strip any conversions that don't change the mode.  This is
9866      safe for every expression, except for a comparison expression
9867      because its signedness is derived from its operands.  So, in
9868      the latter case, only strip conversions that don't change the
9869      signedness.  MIN_EXPR/MAX_EXPR also need signedness of arguments
9870      preserved.
9871
9872      Note that this is done as an internal manipulation within the
9873      constant folder, in order to find the simplest representation
9874      of the arguments so that their form can be studied.  In any
9875      cases, the appropriate type conversions should be put back in
9876      the tree that will get out of the constant folder.  */
9877
9878   if (kind == tcc_comparison || code == MIN_EXPR || code == MAX_EXPR)
9879     {
9880       STRIP_SIGN_NOPS (arg0);
9881       STRIP_SIGN_NOPS (arg1);
9882     }
9883   else
9884     {
9885       STRIP_NOPS (arg0);
9886       STRIP_NOPS (arg1);
9887     }
9888
9889   /* Note that TREE_CONSTANT isn't enough: static var addresses are
9890      constant but we can't do arithmetic on them.  */
9891   if (CONSTANT_CLASS_P (arg0) && CONSTANT_CLASS_P (arg1))
9892     {
9893       tem = const_binop (code, type, arg0, arg1);
9894       if (tem != NULL_TREE)
9895         {
9896           if (TREE_TYPE (tem) != type)
9897             tem = fold_convert_loc (loc, type, tem);
9898           return tem;
9899         }
9900     }
9901
9902   /* If this is a commutative operation, and ARG0 is a constant, move it
9903      to ARG1 to reduce the number of tests below.  */
9904   if (commutative_tree_code (code)
9905       && tree_swap_operands_p (arg0, arg1, true))
9906     return fold_build2_loc (loc, code, type, op1, op0);
9907
9908   /* Likewise if this is a comparison, and ARG0 is a constant, move it
9909      to ARG1 to reduce the number of tests below.  */
9910   if (kind == tcc_comparison
9911       && tree_swap_operands_p (arg0, arg1, true))
9912     return fold_build2_loc (loc, swap_tree_comparison (code), type, op1, op0);
9913
9914   tem = generic_simplify (loc, code, type, op0, op1);
9915   if (tem)
9916     return tem;
9917
9918   /* ARG0 is the first operand of EXPR, and ARG1 is the second operand.
9919
9920      First check for cases where an arithmetic operation is applied to a
9921      compound, conditional, or comparison operation.  Push the arithmetic
9922      operation inside the compound or conditional to see if any folding
9923      can then be done.  Convert comparison to conditional for this purpose.
9924      The also optimizes non-constant cases that used to be done in
9925      expand_expr.
9926
9927      Before we do that, see if this is a BIT_AND_EXPR or a BIT_IOR_EXPR,
9928      one of the operands is a comparison and the other is a comparison, a
9929      BIT_AND_EXPR with the constant 1, or a truth value.  In that case, the
9930      code below would make the expression more complex.  Change it to a
9931      TRUTH_{AND,OR}_EXPR.  Likewise, convert a similar NE_EXPR to
9932      TRUTH_XOR_EXPR and an EQ_EXPR to the inversion of a TRUTH_XOR_EXPR.  */
9933
9934   if ((code == BIT_AND_EXPR || code == BIT_IOR_EXPR
9935        || code == EQ_EXPR || code == NE_EXPR)
9936       && TREE_CODE (type) != VECTOR_TYPE
9937       && ((truth_value_p (TREE_CODE (arg0))
9938            && (truth_value_p (TREE_CODE (arg1))
9939                || (TREE_CODE (arg1) == BIT_AND_EXPR
9940                    && integer_onep (TREE_OPERAND (arg1, 1)))))
9941           || (truth_value_p (TREE_CODE (arg1))
9942               && (truth_value_p (TREE_CODE (arg0))
9943                   || (TREE_CODE (arg0) == BIT_AND_EXPR
9944                       && integer_onep (TREE_OPERAND (arg0, 1)))))))
9945     {
9946       tem = fold_build2_loc (loc, code == BIT_AND_EXPR ? TRUTH_AND_EXPR
9947                          : code == BIT_IOR_EXPR ? TRUTH_OR_EXPR
9948                          : TRUTH_XOR_EXPR,
9949                          boolean_type_node,
9950                          fold_convert_loc (loc, boolean_type_node, arg0),
9951                          fold_convert_loc (loc, boolean_type_node, arg1));
9952
9953       if (code == EQ_EXPR)
9954         tem = invert_truthvalue_loc (loc, tem);
9955
9956       return fold_convert_loc (loc, type, tem);
9957     }
9958
9959   if (TREE_CODE_CLASS (code) == tcc_binary
9960       || TREE_CODE_CLASS (code) == tcc_comparison)
9961     {
9962       if (TREE_CODE (arg0) == COMPOUND_EXPR)
9963         {
9964           tem = fold_build2_loc (loc, code, type,
9965                              fold_convert_loc (loc, TREE_TYPE (op0),
9966                                                TREE_OPERAND (arg0, 1)), op1);
9967           return build2_loc (loc, COMPOUND_EXPR, type, TREE_OPERAND (arg0, 0),
9968                              tem);
9969         }
9970       if (TREE_CODE (arg1) == COMPOUND_EXPR
9971           && reorder_operands_p (arg0, TREE_OPERAND (arg1, 0)))
9972         {
9973           tem = fold_build2_loc (loc, code, type, op0,
9974                              fold_convert_loc (loc, TREE_TYPE (op1),
9975                                                TREE_OPERAND (arg1, 1)));
9976           return build2_loc (loc, COMPOUND_EXPR, type, TREE_OPERAND (arg1, 0),
9977                              tem);
9978         }
9979
9980       if (TREE_CODE (arg0) == COND_EXPR
9981           || TREE_CODE (arg0) == VEC_COND_EXPR
9982           || COMPARISON_CLASS_P (arg0))
9983         {
9984           tem = fold_binary_op_with_conditional_arg (loc, code, type, op0, op1,
9985                                                      arg0, arg1,
9986                                                      /*cond_first_p=*/1);
9987           if (tem != NULL_TREE)
9988             return tem;
9989         }
9990
9991       if (TREE_CODE (arg1) == COND_EXPR
9992           || TREE_CODE (arg1) == VEC_COND_EXPR
9993           || COMPARISON_CLASS_P (arg1))
9994         {
9995           tem = fold_binary_op_with_conditional_arg (loc, code, type, op0, op1,
9996                                                      arg1, arg0,
9997                                                      /*cond_first_p=*/0);
9998           if (tem != NULL_TREE)
9999             return tem;
10000         }
10001     }
10002
10003   switch (code)
10004     {
10005     case MEM_REF:
10006       /* MEM[&MEM[p, CST1], CST2] -> MEM[p, CST1 + CST2].  */
10007       if (TREE_CODE (arg0) == ADDR_EXPR
10008           && TREE_CODE (TREE_OPERAND (arg0, 0)) == MEM_REF)
10009         {
10010           tree iref = TREE_OPERAND (arg0, 0);
10011           return fold_build2 (MEM_REF, type,
10012                               TREE_OPERAND (iref, 0),
10013                               int_const_binop (PLUS_EXPR, arg1,
10014                                                TREE_OPERAND (iref, 1)));
10015         }
10016
10017       /* MEM[&a.b, CST2] -> MEM[&a, offsetof (a, b) + CST2].  */
10018       if (TREE_CODE (arg0) == ADDR_EXPR
10019           && handled_component_p (TREE_OPERAND (arg0, 0)))
10020         {
10021           tree base;
10022           HOST_WIDE_INT coffset;
10023           base = get_addr_base_and_unit_offset (TREE_OPERAND (arg0, 0),
10024                                                 &coffset);
10025           if (!base)
10026             return NULL_TREE;
10027           return fold_build2 (MEM_REF, type,
10028                               build_fold_addr_expr (base),
10029                               int_const_binop (PLUS_EXPR, arg1,
10030                                                size_int (coffset)));
10031         }
10032
10033       return NULL_TREE;
10034
10035     case POINTER_PLUS_EXPR:
10036       /* INT +p INT -> (PTR)(INT + INT).  Stripping types allows for this. */
10037       if (INTEGRAL_TYPE_P (TREE_TYPE (arg1))
10038            && INTEGRAL_TYPE_P (TREE_TYPE (arg0)))
10039         return fold_convert_loc (loc, type,
10040                                  fold_build2_loc (loc, PLUS_EXPR, sizetype,
10041                                               fold_convert_loc (loc, sizetype,
10042                                                                 arg1),
10043                                               fold_convert_loc (loc, sizetype,
10044                                                                 arg0)));
10045
10046       return NULL_TREE;
10047
10048     case PLUS_EXPR:
10049       if (INTEGRAL_TYPE_P (type) || VECTOR_INTEGER_TYPE_P (type))
10050         {
10051           /* X + (X / CST) * -CST is X % CST.  */
10052           if (TREE_CODE (arg1) == MULT_EXPR
10053               && TREE_CODE (TREE_OPERAND (arg1, 0)) == TRUNC_DIV_EXPR
10054               && operand_equal_p (arg0,
10055                                   TREE_OPERAND (TREE_OPERAND (arg1, 0), 0), 0))
10056             {
10057               tree cst0 = TREE_OPERAND (TREE_OPERAND (arg1, 0), 1);
10058               tree cst1 = TREE_OPERAND (arg1, 1);
10059               tree sum = fold_binary_loc (loc, PLUS_EXPR, TREE_TYPE (cst1),
10060                                       cst1, cst0);
10061               if (sum && integer_zerop (sum))
10062                 return fold_convert_loc (loc, type,
10063                                          fold_build2_loc (loc, TRUNC_MOD_EXPR,
10064                                                       TREE_TYPE (arg0), arg0,
10065                                                       cst0));
10066             }
10067         }
10068
10069       /* Handle (A1 * C1) + (A2 * C2) with A1, A2 or C1, C2 being the same or
10070          one.  Make sure the type is not saturating and has the signedness of
10071          the stripped operands, as fold_plusminus_mult_expr will re-associate.
10072          ??? The latter condition should use TYPE_OVERFLOW_* flags instead.  */
10073       if ((TREE_CODE (arg0) == MULT_EXPR
10074            || TREE_CODE (arg1) == MULT_EXPR)
10075           && !TYPE_SATURATING (type)
10076           && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg0))
10077           && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg1))
10078           && (!FLOAT_TYPE_P (type) || flag_associative_math))
10079         {
10080           tree tem = fold_plusminus_mult_expr (loc, code, type, arg0, arg1);
10081           if (tem)
10082             return tem;
10083         }
10084
10085       if (! FLOAT_TYPE_P (type))
10086         {
10087           /* If we are adding two BIT_AND_EXPR's, both of which are and'ing
10088              with a constant, and the two constants have no bits in common,
10089              we should treat this as a BIT_IOR_EXPR since this may produce more
10090              simplifications.  */
10091           if (TREE_CODE (arg0) == BIT_AND_EXPR
10092               && TREE_CODE (arg1) == BIT_AND_EXPR
10093               && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
10094               && TREE_CODE (TREE_OPERAND (arg1, 1)) == INTEGER_CST
10095               && wi::bit_and (TREE_OPERAND (arg0, 1),
10096                               TREE_OPERAND (arg1, 1)) == 0)
10097             {
10098               code = BIT_IOR_EXPR;
10099               goto bit_ior;
10100             }
10101
10102           /* Reassociate (plus (plus (mult) (foo)) (mult)) as
10103              (plus (plus (mult) (mult)) (foo)) so that we can
10104              take advantage of the factoring cases below.  */
10105           if (ANY_INTEGRAL_TYPE_P (type)
10106               && TYPE_OVERFLOW_WRAPS (type)
10107               && (((TREE_CODE (arg0) == PLUS_EXPR
10108                     || TREE_CODE (arg0) == MINUS_EXPR)
10109                    && TREE_CODE (arg1) == MULT_EXPR)
10110                   || ((TREE_CODE (arg1) == PLUS_EXPR
10111                        || TREE_CODE (arg1) == MINUS_EXPR)
10112                       && TREE_CODE (arg0) == MULT_EXPR)))
10113             {
10114               tree parg0, parg1, parg, marg;
10115               enum tree_code pcode;
10116
10117               if (TREE_CODE (arg1) == MULT_EXPR)
10118                 parg = arg0, marg = arg1;
10119               else
10120                 parg = arg1, marg = arg0;
10121               pcode = TREE_CODE (parg);
10122               parg0 = TREE_OPERAND (parg, 0);
10123               parg1 = TREE_OPERAND (parg, 1);
10124               STRIP_NOPS (parg0);
10125               STRIP_NOPS (parg1);
10126
10127               if (TREE_CODE (parg0) == MULT_EXPR
10128                   && TREE_CODE (parg1) != MULT_EXPR)
10129                 return fold_build2_loc (loc, pcode, type,
10130                                     fold_build2_loc (loc, PLUS_EXPR, type,
10131                                                  fold_convert_loc (loc, type,
10132                                                                    parg0),
10133                                                  fold_convert_loc (loc, type,
10134                                                                    marg)),
10135                                     fold_convert_loc (loc, type, parg1));
10136               if (TREE_CODE (parg0) != MULT_EXPR
10137                   && TREE_CODE (parg1) == MULT_EXPR)
10138                 return
10139                   fold_build2_loc (loc, PLUS_EXPR, type,
10140                                fold_convert_loc (loc, type, parg0),
10141                                fold_build2_loc (loc, pcode, type,
10142                                             fold_convert_loc (loc, type, marg),
10143                                             fold_convert_loc (loc, type,
10144                                                               parg1)));
10145             }
10146         }
10147       else
10148         {
10149           /* Fold __complex__ ( x, 0 ) + __complex__ ( 0, y )
10150              to __complex__ ( x, y ).  This is not the same for SNaNs or
10151              if signed zeros are involved.  */
10152           if (!HONOR_SNANS (element_mode (arg0))
10153               && !HONOR_SIGNED_ZEROS (element_mode (arg0))
10154               && COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg0)))
10155             {
10156               tree rtype = TREE_TYPE (TREE_TYPE (arg0));
10157               tree arg0r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0);
10158               tree arg0i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
10159               bool arg0rz = false, arg0iz = false;
10160               if ((arg0r && (arg0rz = real_zerop (arg0r)))
10161                   || (arg0i && (arg0iz = real_zerop (arg0i))))
10162                 {
10163                   tree arg1r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg1);
10164                   tree arg1i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg1);
10165                   if (arg0rz && arg1i && real_zerop (arg1i))
10166                     {
10167                       tree rp = arg1r ? arg1r
10168                                   : build1 (REALPART_EXPR, rtype, arg1);
10169                       tree ip = arg0i ? arg0i
10170                                   : build1 (IMAGPART_EXPR, rtype, arg0);
10171                       return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
10172                     }
10173                   else if (arg0iz && arg1r && real_zerop (arg1r))
10174                     {
10175                       tree rp = arg0r ? arg0r
10176                                   : build1 (REALPART_EXPR, rtype, arg0);
10177                       tree ip = arg1i ? arg1i
10178                                   : build1 (IMAGPART_EXPR, rtype, arg1);
10179                       return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
10180                     }
10181                 }
10182             }
10183
10184           if (flag_unsafe_math_optimizations
10185               && (TREE_CODE (arg0) == RDIV_EXPR || TREE_CODE (arg0) == MULT_EXPR)
10186               && (TREE_CODE (arg1) == RDIV_EXPR || TREE_CODE (arg1) == MULT_EXPR)
10187               && (tem = distribute_real_division (loc, code, type, arg0, arg1)))
10188             return tem;
10189
10190           /* Convert a + (b*c + d*e) into (a + b*c) + d*e.
10191              We associate floats only if the user has specified
10192              -fassociative-math.  */
10193           if (flag_associative_math
10194               && TREE_CODE (arg1) == PLUS_EXPR
10195               && TREE_CODE (arg0) != MULT_EXPR)
10196             {
10197               tree tree10 = TREE_OPERAND (arg1, 0);
10198               tree tree11 = TREE_OPERAND (arg1, 1);
10199               if (TREE_CODE (tree11) == MULT_EXPR
10200                   && TREE_CODE (tree10) == MULT_EXPR)
10201                 {
10202                   tree tree0;
10203                   tree0 = fold_build2_loc (loc, PLUS_EXPR, type, arg0, tree10);
10204                   return fold_build2_loc (loc, PLUS_EXPR, type, tree0, tree11);
10205                 }
10206             }
10207           /* Convert (b*c + d*e) + a into b*c + (d*e +a).
10208              We associate floats only if the user has specified
10209              -fassociative-math.  */
10210           if (flag_associative_math
10211               && TREE_CODE (arg0) == PLUS_EXPR
10212               && TREE_CODE (arg1) != MULT_EXPR)
10213             {
10214               tree tree00 = TREE_OPERAND (arg0, 0);
10215               tree tree01 = TREE_OPERAND (arg0, 1);
10216               if (TREE_CODE (tree01) == MULT_EXPR
10217                   && TREE_CODE (tree00) == MULT_EXPR)
10218                 {
10219                   tree tree0;
10220                   tree0 = fold_build2_loc (loc, PLUS_EXPR, type, tree01, arg1);
10221                   return fold_build2_loc (loc, PLUS_EXPR, type, tree00, tree0);
10222                 }
10223             }
10224         }
10225
10226      bit_rotate:
10227       /* (A << C1) + (A >> C2) if A is unsigned and C1+C2 is the size of A
10228          is a rotate of A by C1 bits.  */
10229       /* (A << B) + (A >> (Z - B)) if A is unsigned and Z is the size of A
10230          is a rotate of A by B bits.  */
10231       {
10232         enum tree_code code0, code1;
10233         tree rtype;
10234         code0 = TREE_CODE (arg0);
10235         code1 = TREE_CODE (arg1);
10236         if (((code0 == RSHIFT_EXPR && code1 == LSHIFT_EXPR)
10237              || (code1 == RSHIFT_EXPR && code0 == LSHIFT_EXPR))
10238             && operand_equal_p (TREE_OPERAND (arg0, 0),
10239                                 TREE_OPERAND (arg1, 0), 0)
10240             && (rtype = TREE_TYPE (TREE_OPERAND (arg0, 0)),
10241                 TYPE_UNSIGNED (rtype))
10242             /* Only create rotates in complete modes.  Other cases are not
10243                expanded properly.  */
10244             && (element_precision (rtype)
10245                 == element_precision (TYPE_MODE (rtype))))
10246           {
10247             tree tree01, tree11;
10248             enum tree_code code01, code11;
10249
10250             tree01 = TREE_OPERAND (arg0, 1);
10251             tree11 = TREE_OPERAND (arg1, 1);
10252             STRIP_NOPS (tree01);
10253             STRIP_NOPS (tree11);
10254             code01 = TREE_CODE (tree01);
10255             code11 = TREE_CODE (tree11);
10256             if (code01 == INTEGER_CST
10257                 && code11 == INTEGER_CST
10258                 && (wi::to_widest (tree01) + wi::to_widest (tree11)
10259                     == element_precision (TREE_TYPE (TREE_OPERAND (arg0, 0)))))
10260               {
10261                 tem = build2_loc (loc, LROTATE_EXPR,
10262                                   TREE_TYPE (TREE_OPERAND (arg0, 0)),
10263                                   TREE_OPERAND (arg0, 0),
10264                                   code0 == LSHIFT_EXPR ? tree01 : tree11);
10265                 return fold_convert_loc (loc, type, tem);
10266               }
10267             else if (code11 == MINUS_EXPR)
10268               {
10269                 tree tree110, tree111;
10270                 tree110 = TREE_OPERAND (tree11, 0);
10271                 tree111 = TREE_OPERAND (tree11, 1);
10272                 STRIP_NOPS (tree110);
10273                 STRIP_NOPS (tree111);
10274                 if (TREE_CODE (tree110) == INTEGER_CST
10275                     && 0 == compare_tree_int (tree110,
10276                                               element_precision
10277                                               (TREE_TYPE (TREE_OPERAND
10278                                                           (arg0, 0))))
10279                     && operand_equal_p (tree01, tree111, 0))
10280                   return
10281                     fold_convert_loc (loc, type,
10282                                       build2 ((code0 == LSHIFT_EXPR
10283                                                ? LROTATE_EXPR
10284                                                : RROTATE_EXPR),
10285                                               TREE_TYPE (TREE_OPERAND (arg0, 0)),
10286                                               TREE_OPERAND (arg0, 0), tree01));
10287               }
10288             else if (code01 == MINUS_EXPR)
10289               {
10290                 tree tree010, tree011;
10291                 tree010 = TREE_OPERAND (tree01, 0);
10292                 tree011 = TREE_OPERAND (tree01, 1);
10293                 STRIP_NOPS (tree010);
10294                 STRIP_NOPS (tree011);
10295                 if (TREE_CODE (tree010) == INTEGER_CST
10296                     && 0 == compare_tree_int (tree010,
10297                                               element_precision
10298                                               (TREE_TYPE (TREE_OPERAND
10299                                                           (arg0, 0))))
10300                     && operand_equal_p (tree11, tree011, 0))
10301                     return fold_convert_loc
10302                       (loc, type,
10303                        build2 ((code0 != LSHIFT_EXPR
10304                                 ? LROTATE_EXPR
10305                                 : RROTATE_EXPR),
10306                                TREE_TYPE (TREE_OPERAND (arg0, 0)),
10307                                TREE_OPERAND (arg0, 0), tree11));
10308               }
10309           }
10310       }
10311
10312     associate:
10313       /* In most languages, can't associate operations on floats through
10314          parentheses.  Rather than remember where the parentheses were, we
10315          don't associate floats at all, unless the user has specified
10316          -fassociative-math.
10317          And, we need to make sure type is not saturating.  */
10318
10319       if ((! FLOAT_TYPE_P (type) || flag_associative_math)
10320           && !TYPE_SATURATING (type))
10321         {
10322           tree var0, con0, lit0, minus_lit0;
10323           tree var1, con1, lit1, minus_lit1;
10324           tree atype = type;
10325           bool ok = true;
10326
10327           /* Split both trees into variables, constants, and literals.  Then
10328              associate each group together, the constants with literals,
10329              then the result with variables.  This increases the chances of
10330              literals being recombined later and of generating relocatable
10331              expressions for the sum of a constant and literal.  */
10332           var0 = split_tree (arg0, code, &con0, &lit0, &minus_lit0, 0);
10333           var1 = split_tree (arg1, code, &con1, &lit1, &minus_lit1,
10334                              code == MINUS_EXPR);
10335
10336           /* Recombine MINUS_EXPR operands by using PLUS_EXPR.  */
10337           if (code == MINUS_EXPR)
10338             code = PLUS_EXPR;
10339
10340           /* With undefined overflow prefer doing association in a type
10341              which wraps on overflow, if that is one of the operand types.  */
10342           if ((POINTER_TYPE_P (type) && POINTER_TYPE_OVERFLOW_UNDEFINED)
10343               || (INTEGRAL_TYPE_P (type) && !TYPE_OVERFLOW_WRAPS (type)))
10344             {
10345               if (INTEGRAL_TYPE_P (TREE_TYPE (arg0))
10346                   && TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg0)))
10347                 atype = TREE_TYPE (arg0);
10348               else if (INTEGRAL_TYPE_P (TREE_TYPE (arg1))
10349                        && TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg1)))
10350                 atype = TREE_TYPE (arg1);
10351               gcc_assert (TYPE_PRECISION (atype) == TYPE_PRECISION (type));
10352             }
10353
10354           /* With undefined overflow we can only associate constants with one
10355              variable, and constants whose association doesn't overflow.  */
10356           if ((POINTER_TYPE_P (atype) && POINTER_TYPE_OVERFLOW_UNDEFINED)
10357               || (INTEGRAL_TYPE_P (atype) && !TYPE_OVERFLOW_WRAPS (atype)))
10358             {
10359               if (var0 && var1)
10360                 {
10361                   tree tmp0 = var0;
10362                   tree tmp1 = var1;
10363
10364                   if (TREE_CODE (tmp0) == NEGATE_EXPR)
10365                     tmp0 = TREE_OPERAND (tmp0, 0);
10366                   if (CONVERT_EXPR_P (tmp0)
10367                       && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (tmp0, 0)))
10368                       && (TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (tmp0, 0)))
10369                           <= TYPE_PRECISION (atype)))
10370                     tmp0 = TREE_OPERAND (tmp0, 0);
10371                   if (TREE_CODE (tmp1) == NEGATE_EXPR)
10372                     tmp1 = TREE_OPERAND (tmp1, 0);
10373                   if (CONVERT_EXPR_P (tmp1)
10374                       && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (tmp1, 0)))
10375                       && (TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (tmp1, 0)))
10376                           <= TYPE_PRECISION (atype)))
10377                     tmp1 = TREE_OPERAND (tmp1, 0);
10378                   /* The only case we can still associate with two variables
10379                      is if they are the same, modulo negation and bit-pattern
10380                      preserving conversions.  */
10381                   if (!operand_equal_p (tmp0, tmp1, 0))
10382                     ok = false;
10383                 }
10384             }
10385
10386           /* Only do something if we found more than two objects.  Otherwise,
10387              nothing has changed and we risk infinite recursion.  */
10388           if (ok
10389               && (2 < ((var0 != 0) + (var1 != 0)
10390                        + (con0 != 0) + (con1 != 0)
10391                        + (lit0 != 0) + (lit1 != 0)
10392                        + (minus_lit0 != 0) + (minus_lit1 != 0))))
10393             {
10394               bool any_overflows = false;
10395               if (lit0) any_overflows |= TREE_OVERFLOW (lit0);
10396               if (lit1) any_overflows |= TREE_OVERFLOW (lit1);
10397               if (minus_lit0) any_overflows |= TREE_OVERFLOW (minus_lit0);
10398               if (minus_lit1) any_overflows |= TREE_OVERFLOW (minus_lit1);
10399               var0 = associate_trees (loc, var0, var1, code, atype);
10400               con0 = associate_trees (loc, con0, con1, code, atype);
10401               lit0 = associate_trees (loc, lit0, lit1, code, atype);
10402               minus_lit0 = associate_trees (loc, minus_lit0, minus_lit1,
10403                                             code, atype);
10404
10405               /* Preserve the MINUS_EXPR if the negative part of the literal is
10406                  greater than the positive part.  Otherwise, the multiplicative
10407                  folding code (i.e extract_muldiv) may be fooled in case
10408                  unsigned constants are subtracted, like in the following
10409                  example: ((X*2 + 4) - 8U)/2.  */
10410               if (minus_lit0 && lit0)
10411                 {
10412                   if (TREE_CODE (lit0) == INTEGER_CST
10413                       && TREE_CODE (minus_lit0) == INTEGER_CST
10414                       && tree_int_cst_lt (lit0, minus_lit0))
10415                     {
10416                       minus_lit0 = associate_trees (loc, minus_lit0, lit0,
10417                                                     MINUS_EXPR, atype);
10418                       lit0 = 0;
10419                     }
10420                   else
10421                     {
10422                       lit0 = associate_trees (loc, lit0, minus_lit0,
10423                                               MINUS_EXPR, atype);
10424                       minus_lit0 = 0;
10425                     }
10426                 }
10427
10428               /* Don't introduce overflows through reassociation.  */
10429               if (!any_overflows
10430                   && ((lit0 && TREE_OVERFLOW_P (lit0))
10431                       || (minus_lit0 && TREE_OVERFLOW_P (minus_lit0))))
10432                 return NULL_TREE;
10433
10434               if (minus_lit0)
10435                 {
10436                   if (con0 == 0)
10437                     return
10438                       fold_convert_loc (loc, type,
10439                                         associate_trees (loc, var0, minus_lit0,
10440                                                          MINUS_EXPR, atype));
10441                   else
10442                     {
10443                       con0 = associate_trees (loc, con0, minus_lit0,
10444                                               MINUS_EXPR, atype);
10445                       return
10446                         fold_convert_loc (loc, type,
10447                                           associate_trees (loc, var0, con0,
10448                                                            PLUS_EXPR, atype));
10449                     }
10450                 }
10451
10452               con0 = associate_trees (loc, con0, lit0, code, atype);
10453               return
10454                 fold_convert_loc (loc, type, associate_trees (loc, var0, con0,
10455                                                               code, atype));
10456             }
10457         }
10458
10459       return NULL_TREE;
10460
10461     case MINUS_EXPR:
10462       /* Pointer simplifications for subtraction, simple reassociations. */
10463       if (POINTER_TYPE_P (TREE_TYPE (arg1)) && POINTER_TYPE_P (TREE_TYPE (arg0)))
10464         {
10465           /* (PTR0 p+ A) - (PTR1 p+ B) -> (PTR0 - PTR1) + (A - B) */
10466           if (TREE_CODE (arg0) == POINTER_PLUS_EXPR
10467               && TREE_CODE (arg1) == POINTER_PLUS_EXPR)
10468             {
10469               tree arg00 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
10470               tree arg01 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 1));
10471               tree arg10 = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 0));
10472               tree arg11 = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 1));
10473               return fold_build2_loc (loc, PLUS_EXPR, type,
10474                                   fold_build2_loc (loc, MINUS_EXPR, type,
10475                                                arg00, arg10),
10476                                   fold_build2_loc (loc, MINUS_EXPR, type,
10477                                                arg01, arg11));
10478             }
10479           /* (PTR0 p+ A) - PTR1 -> (PTR0 - PTR1) + A, assuming PTR0 - PTR1 simplifies. */
10480           else if (TREE_CODE (arg0) == POINTER_PLUS_EXPR)
10481             {
10482               tree arg00 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
10483               tree arg01 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 1));
10484               tree tmp = fold_binary_loc (loc, MINUS_EXPR, type, arg00,
10485                                       fold_convert_loc (loc, type, arg1));
10486               if (tmp)
10487                 return fold_build2_loc (loc, PLUS_EXPR, type, tmp, arg01);
10488             }
10489           /* PTR0 - (PTR1 p+ A) -> (PTR0 - PTR1) - A, assuming PTR0 - PTR1
10490              simplifies. */
10491           else if (TREE_CODE (arg1) == POINTER_PLUS_EXPR)
10492             {
10493               tree arg10 = fold_convert_loc (loc, type,
10494                                              TREE_OPERAND (arg1, 0));
10495               tree arg11 = fold_convert_loc (loc, type,
10496                                              TREE_OPERAND (arg1, 1));
10497               tree tmp = fold_binary_loc (loc, MINUS_EXPR, type,
10498                                           fold_convert_loc (loc, type, arg0),
10499                                           arg10);
10500               if (tmp)
10501                 return fold_build2_loc (loc, MINUS_EXPR, type, tmp, arg11);
10502             }
10503         }
10504       /* (-A) - B -> (-B) - A  where B is easily negated and we can swap.  */
10505       if (TREE_CODE (arg0) == NEGATE_EXPR
10506           && negate_expr_p (arg1)
10507           && reorder_operands_p (arg0, arg1))
10508         return fold_build2_loc (loc, MINUS_EXPR, type,
10509                             fold_convert_loc (loc, type,
10510                                               negate_expr (arg1)),
10511                             fold_convert_loc (loc, type,
10512                                               TREE_OPERAND (arg0, 0)));
10513
10514       /* X - (X / Y) * Y is X % Y.  */
10515       if ((INTEGRAL_TYPE_P (type) || VECTOR_INTEGER_TYPE_P (type))
10516           && TREE_CODE (arg1) == MULT_EXPR
10517           && TREE_CODE (TREE_OPERAND (arg1, 0)) == TRUNC_DIV_EXPR
10518           && operand_equal_p (arg0,
10519                               TREE_OPERAND (TREE_OPERAND (arg1, 0), 0), 0)
10520           && operand_equal_p (TREE_OPERAND (TREE_OPERAND (arg1, 0), 1),
10521                               TREE_OPERAND (arg1, 1), 0))
10522         return
10523           fold_convert_loc (loc, type,
10524                             fold_build2_loc (loc, TRUNC_MOD_EXPR, TREE_TYPE (arg0),
10525                                          arg0, TREE_OPERAND (arg1, 1)));
10526
10527       if (! FLOAT_TYPE_P (type))
10528         {
10529           /* Fold A - (A & B) into ~B & A.  */
10530           if (!TREE_SIDE_EFFECTS (arg0)
10531               && TREE_CODE (arg1) == BIT_AND_EXPR)
10532             {
10533               if (operand_equal_p (arg0, TREE_OPERAND (arg1, 1), 0))
10534                 {
10535                   tree arg10 = fold_convert_loc (loc, type,
10536                                                  TREE_OPERAND (arg1, 0));
10537                   return fold_build2_loc (loc, BIT_AND_EXPR, type,
10538                                       fold_build1_loc (loc, BIT_NOT_EXPR,
10539                                                    type, arg10),
10540                                       fold_convert_loc (loc, type, arg0));
10541                 }
10542               if (operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
10543                 {
10544                   tree arg11 = fold_convert_loc (loc,
10545                                                  type, TREE_OPERAND (arg1, 1));
10546                   return fold_build2_loc (loc, BIT_AND_EXPR, type,
10547                                       fold_build1_loc (loc, BIT_NOT_EXPR,
10548                                                    type, arg11),
10549                                       fold_convert_loc (loc, type, arg0));
10550                 }
10551             }
10552
10553           /* Fold (A & ~B) - (A & B) into (A ^ B) - B, where B is
10554              any power of 2 minus 1.  */
10555           if (TREE_CODE (arg0) == BIT_AND_EXPR
10556               && TREE_CODE (arg1) == BIT_AND_EXPR
10557               && operand_equal_p (TREE_OPERAND (arg0, 0),
10558                                   TREE_OPERAND (arg1, 0), 0))
10559             {
10560               tree mask0 = TREE_OPERAND (arg0, 1);
10561               tree mask1 = TREE_OPERAND (arg1, 1);
10562               tree tem = fold_build1_loc (loc, BIT_NOT_EXPR, type, mask0);
10563
10564               if (operand_equal_p (tem, mask1, 0))
10565                 {
10566                   tem = fold_build2_loc (loc, BIT_XOR_EXPR, type,
10567                                      TREE_OPERAND (arg0, 0), mask1);
10568                   return fold_build2_loc (loc, MINUS_EXPR, type, tem, mask1);
10569                 }
10570             }
10571         }
10572
10573       /* Fold __complex__ ( x, 0 ) - __complex__ ( 0, y ) to
10574          __complex__ ( x, -y ).  This is not the same for SNaNs or if
10575          signed zeros are involved.  */
10576       if (!HONOR_SNANS (element_mode (arg0))
10577           && !HONOR_SIGNED_ZEROS (element_mode (arg0))
10578           && COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg0)))
10579         {
10580           tree rtype = TREE_TYPE (TREE_TYPE (arg0));
10581           tree arg0r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0);
10582           tree arg0i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
10583           bool arg0rz = false, arg0iz = false;
10584           if ((arg0r && (arg0rz = real_zerop (arg0r)))
10585               || (arg0i && (arg0iz = real_zerop (arg0i))))
10586             {
10587               tree arg1r = fold_unary_loc (loc, REALPART_EXPR, rtype, arg1);
10588               tree arg1i = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg1);
10589               if (arg0rz && arg1i && real_zerop (arg1i))
10590                 {
10591                   tree rp = fold_build1_loc (loc, NEGATE_EXPR, rtype,
10592                                          arg1r ? arg1r
10593                                          : build1 (REALPART_EXPR, rtype, arg1));
10594                   tree ip = arg0i ? arg0i
10595                     : build1 (IMAGPART_EXPR, rtype, arg0);
10596                   return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
10597                 }
10598               else if (arg0iz && arg1r && real_zerop (arg1r))
10599                 {
10600                   tree rp = arg0r ? arg0r
10601                     : build1 (REALPART_EXPR, rtype, arg0);
10602                   tree ip = fold_build1_loc (loc, NEGATE_EXPR, rtype,
10603                                          arg1i ? arg1i
10604                                          : build1 (IMAGPART_EXPR, rtype, arg1));
10605                   return fold_build2_loc (loc, COMPLEX_EXPR, type, rp, ip);
10606                 }
10607             }
10608         }
10609
10610       /* A - B -> A + (-B) if B is easily negatable.  */
10611       if (negate_expr_p (arg1)
10612           && !TYPE_OVERFLOW_SANITIZED (type)
10613           && ((FLOAT_TYPE_P (type)
10614                /* Avoid this transformation if B is a positive REAL_CST.  */
10615                && (TREE_CODE (arg1) != REAL_CST
10616                    ||  REAL_VALUE_NEGATIVE (TREE_REAL_CST (arg1))))
10617               || INTEGRAL_TYPE_P (type)))
10618         return fold_build2_loc (loc, PLUS_EXPR, type,
10619                             fold_convert_loc (loc, type, arg0),
10620                             fold_convert_loc (loc, type,
10621                                               negate_expr (arg1)));
10622
10623       /* Try folding difference of addresses.  */
10624       {
10625         HOST_WIDE_INT diff;
10626
10627         if ((TREE_CODE (arg0) == ADDR_EXPR
10628              || TREE_CODE (arg1) == ADDR_EXPR)
10629             && ptr_difference_const (arg0, arg1, &diff))
10630           return build_int_cst_type (type, diff);
10631       }
10632
10633       /* Fold &a[i] - &a[j] to i-j.  */
10634       if (TREE_CODE (arg0) == ADDR_EXPR
10635           && TREE_CODE (TREE_OPERAND (arg0, 0)) == ARRAY_REF
10636           && TREE_CODE (arg1) == ADDR_EXPR
10637           && TREE_CODE (TREE_OPERAND (arg1, 0)) == ARRAY_REF)
10638         {
10639           tree tem = fold_addr_of_array_ref_difference (loc, type,
10640                                                         TREE_OPERAND (arg0, 0),
10641                                                         TREE_OPERAND (arg1, 0));
10642           if (tem)
10643             return tem;
10644         }
10645
10646       if (FLOAT_TYPE_P (type)
10647           && flag_unsafe_math_optimizations
10648           && (TREE_CODE (arg0) == RDIV_EXPR || TREE_CODE (arg0) == MULT_EXPR)
10649           && (TREE_CODE (arg1) == RDIV_EXPR || TREE_CODE (arg1) == MULT_EXPR)
10650           && (tem = distribute_real_division (loc, code, type, arg0, arg1)))
10651         return tem;
10652
10653       /* Handle (A1 * C1) - (A2 * C2) with A1, A2 or C1, C2 being the same or
10654          one.  Make sure the type is not saturating and has the signedness of
10655          the stripped operands, as fold_plusminus_mult_expr will re-associate.
10656          ??? The latter condition should use TYPE_OVERFLOW_* flags instead.  */
10657       if ((TREE_CODE (arg0) == MULT_EXPR
10658            || TREE_CODE (arg1) == MULT_EXPR)
10659           && !TYPE_SATURATING (type)
10660           && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg0))
10661           && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (TREE_TYPE (arg1))
10662           && (!FLOAT_TYPE_P (type) || flag_associative_math))
10663         {
10664           tree tem = fold_plusminus_mult_expr (loc, code, type, arg0, arg1);
10665           if (tem)
10666             return tem;
10667         }
10668
10669       goto associate;
10670
10671     case MULT_EXPR:
10672       /* (-A) * (-B) -> A * B  */
10673       if (TREE_CODE (arg0) == NEGATE_EXPR && negate_expr_p (arg1))
10674         return fold_build2_loc (loc, MULT_EXPR, type,
10675                             fold_convert_loc (loc, type,
10676                                               TREE_OPERAND (arg0, 0)),
10677                             fold_convert_loc (loc, type,
10678                                               negate_expr (arg1)));
10679       if (TREE_CODE (arg1) == NEGATE_EXPR && negate_expr_p (arg0))
10680         return fold_build2_loc (loc, MULT_EXPR, type,
10681                             fold_convert_loc (loc, type,
10682                                               negate_expr (arg0)),
10683                             fold_convert_loc (loc, type,
10684                                               TREE_OPERAND (arg1, 0)));
10685
10686       if (! FLOAT_TYPE_P (type))
10687         {
10688           /* Transform x * -C into -x * C if x is easily negatable.  */
10689           if (TREE_CODE (arg1) == INTEGER_CST
10690               && tree_int_cst_sgn (arg1) == -1
10691               && negate_expr_p (arg0)
10692               && (tem = negate_expr (arg1)) != arg1
10693               && !TREE_OVERFLOW (tem))
10694             return fold_build2_loc (loc, MULT_EXPR, type,
10695                                 fold_convert_loc (loc, type,
10696                                                   negate_expr (arg0)),
10697                                 tem);
10698
10699           /* (a * (1 << b)) is (a << b)  */
10700           if (TREE_CODE (arg1) == LSHIFT_EXPR
10701               && integer_onep (TREE_OPERAND (arg1, 0)))
10702             return fold_build2_loc (loc, LSHIFT_EXPR, type, op0,
10703                                 TREE_OPERAND (arg1, 1));
10704           if (TREE_CODE (arg0) == LSHIFT_EXPR
10705               && integer_onep (TREE_OPERAND (arg0, 0)))
10706             return fold_build2_loc (loc, LSHIFT_EXPR, type, op1,
10707                                 TREE_OPERAND (arg0, 1));
10708
10709           /* (A + A) * C -> A * 2 * C  */
10710           if (TREE_CODE (arg0) == PLUS_EXPR
10711               && TREE_CODE (arg1) == INTEGER_CST
10712               && operand_equal_p (TREE_OPERAND (arg0, 0),
10713                                   TREE_OPERAND (arg0, 1), 0))
10714             return fold_build2_loc (loc, MULT_EXPR, type,
10715                                 omit_one_operand_loc (loc, type,
10716                                                   TREE_OPERAND (arg0, 0),
10717                                                   TREE_OPERAND (arg0, 1)),
10718                                 fold_build2_loc (loc, MULT_EXPR, type,
10719                                              build_int_cst (type, 2) , arg1));
10720
10721           /* ((T) (X /[ex] C)) * C cancels out if the conversion is
10722              sign-changing only.  */
10723           if (TREE_CODE (arg1) == INTEGER_CST
10724               && TREE_CODE (arg0) == EXACT_DIV_EXPR
10725               && operand_equal_p (arg1, TREE_OPERAND (arg0, 1), 0))
10726             return fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
10727
10728           strict_overflow_p = false;
10729           if (TREE_CODE (arg1) == INTEGER_CST
10730               && 0 != (tem = extract_muldiv (op0, arg1, code, NULL_TREE,
10731                                              &strict_overflow_p)))
10732             {
10733               if (strict_overflow_p)
10734                 fold_overflow_warning (("assuming signed overflow does not "
10735                                         "occur when simplifying "
10736                                         "multiplication"),
10737                                        WARN_STRICT_OVERFLOW_MISC);
10738               return fold_convert_loc (loc, type, tem);
10739             }
10740
10741           /* Optimize z * conj(z) for integer complex numbers.  */
10742           if (TREE_CODE (arg0) == CONJ_EXPR
10743               && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
10744             return fold_mult_zconjz (loc, type, arg1);
10745           if (TREE_CODE (arg1) == CONJ_EXPR
10746               && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
10747             return fold_mult_zconjz (loc, type, arg0);
10748         }
10749       else
10750         {
10751           /* Convert (C1/X)*C2 into (C1*C2)/X.  This transformation may change
10752              the result for floating point types due to rounding so it is applied
10753              only if -fassociative-math was specify.  */
10754           if (flag_associative_math
10755               && TREE_CODE (arg0) == RDIV_EXPR
10756               && TREE_CODE (arg1) == REAL_CST
10757               && TREE_CODE (TREE_OPERAND (arg0, 0)) == REAL_CST)
10758             {
10759               tree tem = const_binop (MULT_EXPR, TREE_OPERAND (arg0, 0),
10760                                       arg1);
10761               if (tem)
10762                 return fold_build2_loc (loc, RDIV_EXPR, type, tem,
10763                                     TREE_OPERAND (arg0, 1));
10764             }
10765
10766           /* Strip sign operations from X in X*X, i.e. -Y*-Y -> Y*Y.  */
10767           if (operand_equal_p (arg0, arg1, 0))
10768             {
10769               tree tem = fold_strip_sign_ops (arg0);
10770               if (tem != NULL_TREE)
10771                 {
10772                   tem = fold_convert_loc (loc, type, tem);
10773                   return fold_build2_loc (loc, MULT_EXPR, type, tem, tem);
10774                 }
10775             }
10776
10777           /* Fold z * +-I to __complex__ (-+__imag z, +-__real z).
10778              This is not the same for NaNs or if signed zeros are
10779              involved.  */
10780           if (!HONOR_NANS (arg0)
10781               && !HONOR_SIGNED_ZEROS (element_mode (arg0))
10782               && COMPLEX_FLOAT_TYPE_P (TREE_TYPE (arg0))
10783               && TREE_CODE (arg1) == COMPLEX_CST
10784               && real_zerop (TREE_REALPART (arg1)))
10785             {
10786               tree rtype = TREE_TYPE (TREE_TYPE (arg0));
10787               if (real_onep (TREE_IMAGPART (arg1)))
10788                 return
10789                   fold_build2_loc (loc, COMPLEX_EXPR, type,
10790                                negate_expr (fold_build1_loc (loc, IMAGPART_EXPR,
10791                                                              rtype, arg0)),
10792                                fold_build1_loc (loc, REALPART_EXPR, rtype, arg0));
10793               else if (real_minus_onep (TREE_IMAGPART (arg1)))
10794                 return
10795                   fold_build2_loc (loc, COMPLEX_EXPR, type,
10796                                fold_build1_loc (loc, IMAGPART_EXPR, rtype, arg0),
10797                                negate_expr (fold_build1_loc (loc, REALPART_EXPR,
10798                                                              rtype, arg0)));
10799             }
10800
10801           /* Optimize z * conj(z) for floating point complex numbers.
10802              Guarded by flag_unsafe_math_optimizations as non-finite
10803              imaginary components don't produce scalar results.  */
10804           if (flag_unsafe_math_optimizations
10805               && TREE_CODE (arg0) == CONJ_EXPR
10806               && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
10807             return fold_mult_zconjz (loc, type, arg1);
10808           if (flag_unsafe_math_optimizations
10809               && TREE_CODE (arg1) == CONJ_EXPR
10810               && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
10811             return fold_mult_zconjz (loc, type, arg0);
10812
10813           if (flag_unsafe_math_optimizations)
10814             {
10815               enum built_in_function fcode0 = builtin_mathfn_code (arg0);
10816               enum built_in_function fcode1 = builtin_mathfn_code (arg1);
10817
10818               /* Optimizations of root(...)*root(...).  */
10819               if (fcode0 == fcode1 && BUILTIN_ROOT_P (fcode0))
10820                 {
10821                   tree rootfn, arg;
10822                   tree arg00 = CALL_EXPR_ARG (arg0, 0);
10823                   tree arg10 = CALL_EXPR_ARG (arg1, 0);
10824
10825                   /* Optimize sqrt(x)*sqrt(x) as x.  */
10826                   if (BUILTIN_SQRT_P (fcode0)
10827                       && operand_equal_p (arg00, arg10, 0)
10828                       && ! HONOR_SNANS (element_mode (type)))
10829                     return arg00;
10830
10831                   /* Optimize root(x)*root(y) as root(x*y).  */
10832                   rootfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
10833                   arg = fold_build2_loc (loc, MULT_EXPR, type, arg00, arg10);
10834                   return build_call_expr_loc (loc, rootfn, 1, arg);
10835                 }
10836
10837               /* Optimize expN(x)*expN(y) as expN(x+y).  */
10838               if (fcode0 == fcode1 && BUILTIN_EXPONENT_P (fcode0))
10839                 {
10840                   tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
10841                   tree arg = fold_build2_loc (loc, PLUS_EXPR, type,
10842                                           CALL_EXPR_ARG (arg0, 0),
10843                                           CALL_EXPR_ARG (arg1, 0));
10844                   return build_call_expr_loc (loc, expfn, 1, arg);
10845                 }
10846
10847               /* Optimizations of pow(...)*pow(...).  */
10848               if ((fcode0 == BUILT_IN_POW && fcode1 == BUILT_IN_POW)
10849                   || (fcode0 == BUILT_IN_POWF && fcode1 == BUILT_IN_POWF)
10850                   || (fcode0 == BUILT_IN_POWL && fcode1 == BUILT_IN_POWL))
10851                 {
10852                   tree arg00 = CALL_EXPR_ARG (arg0, 0);
10853                   tree arg01 = CALL_EXPR_ARG (arg0, 1);
10854                   tree arg10 = CALL_EXPR_ARG (arg1, 0);
10855                   tree arg11 = CALL_EXPR_ARG (arg1, 1);
10856
10857                   /* Optimize pow(x,y)*pow(z,y) as pow(x*z,y).  */
10858                   if (operand_equal_p (arg01, arg11, 0))
10859                     {
10860                       tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
10861                       tree arg = fold_build2_loc (loc, MULT_EXPR, type,
10862                                               arg00, arg10);
10863                       return build_call_expr_loc (loc, powfn, 2, arg, arg01);
10864                     }
10865
10866                   /* Optimize pow(x,y)*pow(x,z) as pow(x,y+z).  */
10867                   if (operand_equal_p (arg00, arg10, 0))
10868                     {
10869                       tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
10870                       tree arg = fold_build2_loc (loc, PLUS_EXPR, type,
10871                                               arg01, arg11);
10872                       return build_call_expr_loc (loc, powfn, 2, arg00, arg);
10873                     }
10874                 }
10875
10876               /* Optimize tan(x)*cos(x) as sin(x).  */
10877               if (((fcode0 == BUILT_IN_TAN && fcode1 == BUILT_IN_COS)
10878                    || (fcode0 == BUILT_IN_TANF && fcode1 == BUILT_IN_COSF)
10879                    || (fcode0 == BUILT_IN_TANL && fcode1 == BUILT_IN_COSL)
10880                    || (fcode0 == BUILT_IN_COS && fcode1 == BUILT_IN_TAN)
10881                    || (fcode0 == BUILT_IN_COSF && fcode1 == BUILT_IN_TANF)
10882                    || (fcode0 == BUILT_IN_COSL && fcode1 == BUILT_IN_TANL))
10883                   && operand_equal_p (CALL_EXPR_ARG (arg0, 0),
10884                                       CALL_EXPR_ARG (arg1, 0), 0))
10885                 {
10886                   tree sinfn = mathfn_built_in (type, BUILT_IN_SIN);
10887
10888                   if (sinfn != NULL_TREE)
10889                     return build_call_expr_loc (loc, sinfn, 1,
10890                                             CALL_EXPR_ARG (arg0, 0));
10891                 }
10892
10893               /* Optimize x*pow(x,c) as pow(x,c+1).  */
10894               if (fcode1 == BUILT_IN_POW
10895                   || fcode1 == BUILT_IN_POWF
10896                   || fcode1 == BUILT_IN_POWL)
10897                 {
10898                   tree arg10 = CALL_EXPR_ARG (arg1, 0);
10899                   tree arg11 = CALL_EXPR_ARG (arg1, 1);
10900                   if (TREE_CODE (arg11) == REAL_CST
10901                       && !TREE_OVERFLOW (arg11)
10902                       && operand_equal_p (arg0, arg10, 0))
10903                     {
10904                       tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg1), 0);
10905                       REAL_VALUE_TYPE c;
10906                       tree arg;
10907
10908                       c = TREE_REAL_CST (arg11);
10909                       real_arithmetic (&c, PLUS_EXPR, &c, &dconst1);
10910                       arg = build_real (type, c);
10911                       return build_call_expr_loc (loc, powfn, 2, arg0, arg);
10912                     }
10913                 }
10914
10915               /* Optimize pow(x,c)*x as pow(x,c+1).  */
10916               if (fcode0 == BUILT_IN_POW
10917                   || fcode0 == BUILT_IN_POWF
10918                   || fcode0 == BUILT_IN_POWL)
10919                 {
10920                   tree arg00 = CALL_EXPR_ARG (arg0, 0);
10921                   tree arg01 = CALL_EXPR_ARG (arg0, 1);
10922                   if (TREE_CODE (arg01) == REAL_CST
10923                       && !TREE_OVERFLOW (arg01)
10924                       && operand_equal_p (arg1, arg00, 0))
10925                     {
10926                       tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
10927                       REAL_VALUE_TYPE c;
10928                       tree arg;
10929
10930                       c = TREE_REAL_CST (arg01);
10931                       real_arithmetic (&c, PLUS_EXPR, &c, &dconst1);
10932                       arg = build_real (type, c);
10933                       return build_call_expr_loc (loc, powfn, 2, arg1, arg);
10934                     }
10935                 }
10936
10937               /* Canonicalize x*x as pow(x,2.0), which is expanded as x*x.  */
10938               if (!in_gimple_form
10939                   && optimize
10940                   && operand_equal_p (arg0, arg1, 0))
10941                 {
10942                   tree powfn = mathfn_built_in (type, BUILT_IN_POW);
10943
10944                   if (powfn)
10945                     {
10946                       tree arg = build_real (type, dconst2);
10947                       return build_call_expr_loc (loc, powfn, 2, arg0, arg);
10948                     }
10949                 }
10950             }
10951         }
10952       goto associate;
10953
10954     case BIT_IOR_EXPR:
10955     bit_ior:
10956       /* ~X | X is -1.  */
10957       if (TREE_CODE (arg0) == BIT_NOT_EXPR
10958           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
10959         {
10960           t1 = build_zero_cst (type);
10961           t1 = fold_unary_loc (loc, BIT_NOT_EXPR, type, t1);
10962           return omit_one_operand_loc (loc, type, t1, arg1);
10963         }
10964
10965       /* X | ~X is -1.  */
10966       if (TREE_CODE (arg1) == BIT_NOT_EXPR
10967           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
10968         {
10969           t1 = build_zero_cst (type);
10970           t1 = fold_unary_loc (loc, BIT_NOT_EXPR, type, t1);
10971           return omit_one_operand_loc (loc, type, t1, arg0);
10972         }
10973
10974       /* Canonicalize (X & C1) | C2.  */
10975       if (TREE_CODE (arg0) == BIT_AND_EXPR
10976           && TREE_CODE (arg1) == INTEGER_CST
10977           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
10978         {
10979           int width = TYPE_PRECISION (type), w;
10980           wide_int c1 = TREE_OPERAND (arg0, 1);
10981           wide_int c2 = arg1;
10982
10983           /* If (C1&C2) == C1, then (X&C1)|C2 becomes (X,C2).  */
10984           if ((c1 & c2) == c1)
10985             return omit_one_operand_loc (loc, type, arg1,
10986                                          TREE_OPERAND (arg0, 0));
10987
10988           wide_int msk = wi::mask (width, false,
10989                                    TYPE_PRECISION (TREE_TYPE (arg1)));
10990
10991           /* If (C1|C2) == ~0 then (X&C1)|C2 becomes X|C2.  */
10992           if (msk.and_not (c1 | c2) == 0)
10993             return fold_build2_loc (loc, BIT_IOR_EXPR, type,
10994                                     TREE_OPERAND (arg0, 0), arg1);
10995
10996           /* Minimize the number of bits set in C1, i.e. C1 := C1 & ~C2,
10997              unless (C1 & ~C2) | (C2 & C3) for some C3 is a mask of some
10998              mode which allows further optimizations.  */
10999           c1 &= msk;
11000           c2 &= msk;
11001           wide_int c3 = c1.and_not (c2);
11002           for (w = BITS_PER_UNIT; w <= width; w <<= 1)
11003             {
11004               wide_int mask = wi::mask (w, false,
11005                                         TYPE_PRECISION (type));
11006               if (((c1 | c2) & mask) == mask && c1.and_not (mask) == 0)
11007                 {
11008                   c3 = mask;
11009                   break;
11010                 }
11011             }
11012
11013           if (c3 != c1)
11014             return fold_build2_loc (loc, BIT_IOR_EXPR, type,
11015                                     fold_build2_loc (loc, BIT_AND_EXPR, type,
11016                                                      TREE_OPERAND (arg0, 0),
11017                                                      wide_int_to_tree (type,
11018                                                                        c3)),
11019                                     arg1);
11020         }
11021
11022       /* (X & ~Y) | (~X & Y) is X ^ Y */
11023       if (TREE_CODE (arg0) == BIT_AND_EXPR
11024           && TREE_CODE (arg1) == BIT_AND_EXPR)
11025         {
11026           tree a0, a1, l0, l1, n0, n1;
11027
11028           a0 = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 0));
11029           a1 = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 1));
11030
11031           l0 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
11032           l1 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 1));
11033           
11034           n0 = fold_build1_loc (loc, BIT_NOT_EXPR, type, l0);
11035           n1 = fold_build1_loc (loc, BIT_NOT_EXPR, type, l1);
11036           
11037           if ((operand_equal_p (n0, a0, 0)
11038                && operand_equal_p (n1, a1, 0))
11039               || (operand_equal_p (n0, a1, 0)
11040                   && operand_equal_p (n1, a0, 0)))
11041             return fold_build2_loc (loc, BIT_XOR_EXPR, type, l0, n1);
11042         }
11043
11044       t1 = distribute_bit_expr (loc, code, type, arg0, arg1);
11045       if (t1 != NULL_TREE)
11046         return t1;
11047
11048       /* Convert (or (not arg0) (not arg1)) to (not (and (arg0) (arg1))).
11049
11050          This results in more efficient code for machines without a NAND
11051          instruction.  Combine will canonicalize to the first form
11052          which will allow use of NAND instructions provided by the
11053          backend if they exist.  */
11054       if (TREE_CODE (arg0) == BIT_NOT_EXPR
11055           && TREE_CODE (arg1) == BIT_NOT_EXPR)
11056         {
11057           return
11058             fold_build1_loc (loc, BIT_NOT_EXPR, type,
11059                          build2 (BIT_AND_EXPR, type,
11060                                  fold_convert_loc (loc, type,
11061                                                    TREE_OPERAND (arg0, 0)),
11062                                  fold_convert_loc (loc, type,
11063                                                    TREE_OPERAND (arg1, 0))));
11064         }
11065
11066       /* See if this can be simplified into a rotate first.  If that
11067          is unsuccessful continue in the association code.  */
11068       goto bit_rotate;
11069
11070     case BIT_XOR_EXPR:
11071       /* ~X ^ X is -1.  */
11072       if (TREE_CODE (arg0) == BIT_NOT_EXPR
11073           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
11074         {
11075           t1 = build_zero_cst (type);
11076           t1 = fold_unary_loc (loc, BIT_NOT_EXPR, type, t1);
11077           return omit_one_operand_loc (loc, type, t1, arg1);
11078         }
11079
11080       /* X ^ ~X is -1.  */
11081       if (TREE_CODE (arg1) == BIT_NOT_EXPR
11082           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
11083         {
11084           t1 = build_zero_cst (type);
11085           t1 = fold_unary_loc (loc, BIT_NOT_EXPR, type, t1);
11086           return omit_one_operand_loc (loc, type, t1, arg0);
11087         }
11088
11089       /* If we are XORing two BIT_AND_EXPR's, both of which are and'ing
11090          with a constant, and the two constants have no bits in common,
11091          we should treat this as a BIT_IOR_EXPR since this may produce more
11092          simplifications.  */
11093       if (TREE_CODE (arg0) == BIT_AND_EXPR
11094           && TREE_CODE (arg1) == BIT_AND_EXPR
11095           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
11096           && TREE_CODE (TREE_OPERAND (arg1, 1)) == INTEGER_CST
11097           && wi::bit_and (TREE_OPERAND (arg0, 1),
11098                           TREE_OPERAND (arg1, 1)) == 0)
11099         {
11100           code = BIT_IOR_EXPR;
11101           goto bit_ior;
11102         }
11103
11104       /* (X | Y) ^ X -> Y & ~ X*/
11105       if (TREE_CODE (arg0) == BIT_IOR_EXPR
11106           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
11107         {
11108           tree t2 = TREE_OPERAND (arg0, 1);
11109           t1 = fold_build1_loc (loc, BIT_NOT_EXPR, TREE_TYPE (arg1),
11110                             arg1);
11111           t1 = fold_build2_loc (loc, BIT_AND_EXPR, type,
11112                             fold_convert_loc (loc, type, t2),
11113                             fold_convert_loc (loc, type, t1));
11114           return t1;
11115         }
11116
11117       /* (Y | X) ^ X -> Y & ~ X*/
11118       if (TREE_CODE (arg0) == BIT_IOR_EXPR
11119           && operand_equal_p (TREE_OPERAND (arg0, 1), arg1, 0))
11120         {
11121           tree t2 = TREE_OPERAND (arg0, 0);
11122           t1 = fold_build1_loc (loc, BIT_NOT_EXPR, TREE_TYPE (arg1),
11123                             arg1);
11124           t1 = fold_build2_loc (loc, BIT_AND_EXPR, type,
11125                             fold_convert_loc (loc, type, t2),
11126                             fold_convert_loc (loc, type, t1));
11127           return t1;
11128         }
11129
11130       /* X ^ (X | Y) -> Y & ~ X*/
11131       if (TREE_CODE (arg1) == BIT_IOR_EXPR
11132           && operand_equal_p (TREE_OPERAND (arg1, 0), arg0, 0))
11133         {
11134           tree t2 = TREE_OPERAND (arg1, 1);
11135           t1 = fold_build1_loc (loc, BIT_NOT_EXPR, TREE_TYPE (arg0),
11136                             arg0);
11137           t1 = fold_build2_loc (loc, BIT_AND_EXPR, type,
11138                             fold_convert_loc (loc, type, t2),
11139                             fold_convert_loc (loc, type, t1));
11140           return t1;
11141         }
11142
11143       /* X ^ (Y | X) -> Y & ~ X*/
11144       if (TREE_CODE (arg1) == BIT_IOR_EXPR
11145           && operand_equal_p (TREE_OPERAND (arg1, 1), arg0, 0))
11146         {
11147           tree t2 = TREE_OPERAND (arg1, 0);
11148           t1 = fold_build1_loc (loc, BIT_NOT_EXPR, TREE_TYPE (arg0),
11149                             arg0);
11150           t1 = fold_build2_loc (loc, BIT_AND_EXPR, type,
11151                             fold_convert_loc (loc, type, t2),
11152                             fold_convert_loc (loc, type, t1));
11153           return t1;
11154         }
11155
11156       /* Convert ~X ^ ~Y to X ^ Y.  */
11157       if (TREE_CODE (arg0) == BIT_NOT_EXPR
11158           && TREE_CODE (arg1) == BIT_NOT_EXPR)
11159         return fold_build2_loc (loc, code, type,
11160                             fold_convert_loc (loc, type,
11161                                               TREE_OPERAND (arg0, 0)),
11162                             fold_convert_loc (loc, type,
11163                                               TREE_OPERAND (arg1, 0)));
11164
11165       /* Convert ~X ^ C to X ^ ~C.  */
11166       if (TREE_CODE (arg0) == BIT_NOT_EXPR
11167           && TREE_CODE (arg1) == INTEGER_CST)
11168         return fold_build2_loc (loc, code, type,
11169                             fold_convert_loc (loc, type,
11170                                               TREE_OPERAND (arg0, 0)),
11171                             fold_build1_loc (loc, BIT_NOT_EXPR, type, arg1));
11172
11173       /* Fold (X & 1) ^ 1 as (X & 1) == 0.  */
11174       if (TREE_CODE (arg0) == BIT_AND_EXPR
11175           && INTEGRAL_TYPE_P (type)
11176           && integer_onep (TREE_OPERAND (arg0, 1))
11177           && integer_onep (arg1))
11178         return fold_build2_loc (loc, EQ_EXPR, type, arg0,
11179                                 build_zero_cst (TREE_TYPE (arg0)));
11180
11181       /* Fold (X & Y) ^ Y as ~X & Y.  */
11182       if (TREE_CODE (arg0) == BIT_AND_EXPR
11183           && operand_equal_p (TREE_OPERAND (arg0, 1), arg1, 0))
11184         {
11185           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
11186           return fold_build2_loc (loc, BIT_AND_EXPR, type,
11187                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem),
11188                               fold_convert_loc (loc, type, arg1));
11189         }
11190       /* Fold (X & Y) ^ X as ~Y & X.  */
11191       if (TREE_CODE (arg0) == BIT_AND_EXPR
11192           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0)
11193           && reorder_operands_p (TREE_OPERAND (arg0, 1), arg1))
11194         {
11195           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 1));
11196           return fold_build2_loc (loc, BIT_AND_EXPR, type,
11197                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem),
11198                               fold_convert_loc (loc, type, arg1));
11199         }
11200       /* Fold X ^ (X & Y) as X & ~Y.  */
11201       if (TREE_CODE (arg1) == BIT_AND_EXPR
11202           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
11203         {
11204           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 1));
11205           return fold_build2_loc (loc, BIT_AND_EXPR, type,
11206                               fold_convert_loc (loc, type, arg0),
11207                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem));
11208         }
11209       /* Fold X ^ (Y & X) as ~Y & X.  */
11210       if (TREE_CODE (arg1) == BIT_AND_EXPR
11211           && operand_equal_p (arg0, TREE_OPERAND (arg1, 1), 0)
11212           && reorder_operands_p (arg0, TREE_OPERAND (arg1, 0)))
11213         {
11214           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 0));
11215           return fold_build2_loc (loc, BIT_AND_EXPR, type,
11216                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem),
11217                               fold_convert_loc (loc, type, arg0));
11218         }
11219
11220       /* See if this can be simplified into a rotate first.  If that
11221          is unsuccessful continue in the association code.  */
11222       goto bit_rotate;
11223
11224     case BIT_AND_EXPR:
11225       /* ~X & X, (X == 0) & X, and !X & X are always zero.  */
11226       if ((TREE_CODE (arg0) == BIT_NOT_EXPR
11227            || TREE_CODE (arg0) == TRUTH_NOT_EXPR
11228            || (TREE_CODE (arg0) == EQ_EXPR
11229                && integer_zerop (TREE_OPERAND (arg0, 1))))
11230           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
11231         return omit_one_operand_loc (loc, type, integer_zero_node, arg1);
11232
11233       /* X & ~X , X & (X == 0), and X & !X are always zero.  */
11234       if ((TREE_CODE (arg1) == BIT_NOT_EXPR
11235            || TREE_CODE (arg1) == TRUTH_NOT_EXPR
11236            || (TREE_CODE (arg1) == EQ_EXPR
11237                && integer_zerop (TREE_OPERAND (arg1, 1))))
11238           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
11239         return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
11240
11241       /* Fold (X ^ 1) & 1 as (X & 1) == 0.  */
11242       if (TREE_CODE (arg0) == BIT_XOR_EXPR
11243           && INTEGRAL_TYPE_P (type)
11244           && integer_onep (TREE_OPERAND (arg0, 1))
11245           && integer_onep (arg1))
11246         {
11247           tree tem2;
11248           tem = TREE_OPERAND (arg0, 0);
11249           tem2 = fold_convert_loc (loc, TREE_TYPE (tem), arg1);
11250           tem2 = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (tem),
11251                                   tem, tem2);
11252           return fold_build2_loc (loc, EQ_EXPR, type, tem2,
11253                                   build_zero_cst (TREE_TYPE (tem)));
11254         }
11255       /* Fold ~X & 1 as (X & 1) == 0.  */
11256       if (TREE_CODE (arg0) == BIT_NOT_EXPR
11257           && INTEGRAL_TYPE_P (type)
11258           && integer_onep (arg1))
11259         {
11260           tree tem2;
11261           tem = TREE_OPERAND (arg0, 0);
11262           tem2 = fold_convert_loc (loc, TREE_TYPE (tem), arg1);
11263           tem2 = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (tem),
11264                                   tem, tem2);
11265           return fold_build2_loc (loc, EQ_EXPR, type, tem2,
11266                                   build_zero_cst (TREE_TYPE (tem)));
11267         }
11268       /* Fold !X & 1 as X == 0.  */
11269       if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
11270           && integer_onep (arg1))
11271         {
11272           tem = TREE_OPERAND (arg0, 0);
11273           return fold_build2_loc (loc, EQ_EXPR, type, tem,
11274                                   build_zero_cst (TREE_TYPE (tem)));
11275         }
11276
11277       /* Fold (X ^ Y) & Y as ~X & Y.  */
11278       if (TREE_CODE (arg0) == BIT_XOR_EXPR
11279           && operand_equal_p (TREE_OPERAND (arg0, 1), arg1, 0))
11280         {
11281           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
11282           return fold_build2_loc (loc, BIT_AND_EXPR, type,
11283                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem),
11284                               fold_convert_loc (loc, type, arg1));
11285         }
11286       /* Fold (X ^ Y) & X as ~Y & X.  */
11287       if (TREE_CODE (arg0) == BIT_XOR_EXPR
11288           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0)
11289           && reorder_operands_p (TREE_OPERAND (arg0, 1), arg1))
11290         {
11291           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 1));
11292           return fold_build2_loc (loc, BIT_AND_EXPR, type,
11293                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem),
11294                               fold_convert_loc (loc, type, arg1));
11295         }
11296       /* Fold X & (X ^ Y) as X & ~Y.  */
11297       if (TREE_CODE (arg1) == BIT_XOR_EXPR
11298           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
11299         {
11300           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 1));
11301           return fold_build2_loc (loc, BIT_AND_EXPR, type,
11302                               fold_convert_loc (loc, type, arg0),
11303                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem));
11304         }
11305       /* Fold X & (Y ^ X) as ~Y & X.  */
11306       if (TREE_CODE (arg1) == BIT_XOR_EXPR
11307           && operand_equal_p (arg0, TREE_OPERAND (arg1, 1), 0)
11308           && reorder_operands_p (arg0, TREE_OPERAND (arg1, 0)))
11309         {
11310           tem = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 0));
11311           return fold_build2_loc (loc, BIT_AND_EXPR, type,
11312                               fold_build1_loc (loc, BIT_NOT_EXPR, type, tem),
11313                               fold_convert_loc (loc, type, arg0));
11314         }
11315
11316       /* Fold (X * Y) & -(1 << CST) to X * Y if Y is a constant
11317          multiple of 1 << CST.  */
11318       if (TREE_CODE (arg1) == INTEGER_CST)
11319         {
11320           wide_int cst1 = arg1;
11321           wide_int ncst1 = -cst1;
11322           if ((cst1 & ncst1) == ncst1
11323               && multiple_of_p (type, arg0,
11324                                 wide_int_to_tree (TREE_TYPE (arg1), ncst1)))
11325             return fold_convert_loc (loc, type, arg0);
11326         }
11327
11328       /* Fold (X * CST1) & CST2 to zero if we can, or drop known zero
11329          bits from CST2.  */
11330       if (TREE_CODE (arg1) == INTEGER_CST
11331           && TREE_CODE (arg0) == MULT_EXPR
11332           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
11333         {
11334           wide_int warg1 = arg1;
11335           wide_int masked = mask_with_tz (type, warg1, TREE_OPERAND (arg0, 1));
11336
11337           if (masked == 0)
11338             return omit_two_operands_loc (loc, type, build_zero_cst (type),
11339                                           arg0, arg1);
11340           else if (masked != warg1)
11341             {
11342               /* Avoid the transform if arg1 is a mask of some
11343                  mode which allows further optimizations.  */
11344               int pop = wi::popcount (warg1);
11345               if (!(pop >= BITS_PER_UNIT
11346                     && exact_log2 (pop) != -1
11347                     && wi::mask (pop, false, warg1.get_precision ()) == warg1))
11348                 return fold_build2_loc (loc, code, type, op0,
11349                                         wide_int_to_tree (type, masked));
11350             }
11351         }
11352
11353       /* For constants M and N, if M == (1LL << cst) - 1 && (N & M) == M,
11354          ((A & N) + B) & M -> (A + B) & M
11355          Similarly if (N & M) == 0,
11356          ((A | N) + B) & M -> (A + B) & M
11357          and for - instead of + (or unary - instead of +)
11358          and/or ^ instead of |.
11359          If B is constant and (B & M) == 0, fold into A & M.  */
11360       if (TREE_CODE (arg1) == INTEGER_CST)
11361         {
11362           wide_int cst1 = arg1;
11363           if ((~cst1 != 0) && (cst1 & (cst1 + 1)) == 0
11364               && INTEGRAL_TYPE_P (TREE_TYPE (arg0))
11365               && (TREE_CODE (arg0) == PLUS_EXPR
11366                   || TREE_CODE (arg0) == MINUS_EXPR
11367                   || TREE_CODE (arg0) == NEGATE_EXPR)
11368               && (TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg0))
11369                   || TREE_CODE (TREE_TYPE (arg0)) == INTEGER_TYPE))
11370             {
11371               tree pmop[2];
11372               int which = 0;
11373               wide_int cst0;
11374
11375               /* Now we know that arg0 is (C + D) or (C - D) or
11376                  -C and arg1 (M) is == (1LL << cst) - 1.
11377                  Store C into PMOP[0] and D into PMOP[1].  */
11378               pmop[0] = TREE_OPERAND (arg0, 0);
11379               pmop[1] = NULL;
11380               if (TREE_CODE (arg0) != NEGATE_EXPR)
11381                 {
11382                   pmop[1] = TREE_OPERAND (arg0, 1);
11383                   which = 1;
11384                 }
11385
11386               if ((wi::max_value (TREE_TYPE (arg0)) & cst1) != cst1)
11387                 which = -1;
11388
11389               for (; which >= 0; which--)
11390                 switch (TREE_CODE (pmop[which]))
11391                   {
11392                   case BIT_AND_EXPR:
11393                   case BIT_IOR_EXPR:
11394                   case BIT_XOR_EXPR:
11395                     if (TREE_CODE (TREE_OPERAND (pmop[which], 1))
11396                         != INTEGER_CST)
11397                       break;
11398                     cst0 = TREE_OPERAND (pmop[which], 1);
11399                     cst0 &= cst1;
11400                     if (TREE_CODE (pmop[which]) == BIT_AND_EXPR)
11401                       {
11402                         if (cst0 != cst1)
11403                           break;
11404                       }
11405                     else if (cst0 != 0)
11406                       break;
11407                     /* If C or D is of the form (A & N) where
11408                        (N & M) == M, or of the form (A | N) or
11409                        (A ^ N) where (N & M) == 0, replace it with A.  */
11410                     pmop[which] = TREE_OPERAND (pmop[which], 0);
11411                     break;
11412                   case INTEGER_CST:
11413                     /* If C or D is a N where (N & M) == 0, it can be
11414                        omitted (assumed 0).  */
11415                     if ((TREE_CODE (arg0) == PLUS_EXPR
11416                          || (TREE_CODE (arg0) == MINUS_EXPR && which == 0))
11417                         && (cst1 & pmop[which]) == 0)
11418                       pmop[which] = NULL;
11419                     break;
11420                   default:
11421                     break;
11422                   }
11423
11424               /* Only build anything new if we optimized one or both arguments
11425                  above.  */
11426               if (pmop[0] != TREE_OPERAND (arg0, 0)
11427                   || (TREE_CODE (arg0) != NEGATE_EXPR
11428                       && pmop[1] != TREE_OPERAND (arg0, 1)))
11429                 {
11430                   tree utype = TREE_TYPE (arg0);
11431                   if (! TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg0)))
11432                     {
11433                       /* Perform the operations in a type that has defined
11434                          overflow behavior.  */
11435                       utype = unsigned_type_for (TREE_TYPE (arg0));
11436                       if (pmop[0] != NULL)
11437                         pmop[0] = fold_convert_loc (loc, utype, pmop[0]);
11438                       if (pmop[1] != NULL)
11439                         pmop[1] = fold_convert_loc (loc, utype, pmop[1]);
11440                     }
11441
11442                   if (TREE_CODE (arg0) == NEGATE_EXPR)
11443                     tem = fold_build1_loc (loc, NEGATE_EXPR, utype, pmop[0]);
11444                   else if (TREE_CODE (arg0) == PLUS_EXPR)
11445                     {
11446                       if (pmop[0] != NULL && pmop[1] != NULL)
11447                         tem = fold_build2_loc (loc, PLUS_EXPR, utype,
11448                                                pmop[0], pmop[1]);
11449                       else if (pmop[0] != NULL)
11450                         tem = pmop[0];
11451                       else if (pmop[1] != NULL)
11452                         tem = pmop[1];
11453                       else
11454                         return build_int_cst (type, 0);
11455                     }
11456                   else if (pmop[0] == NULL)
11457                     tem = fold_build1_loc (loc, NEGATE_EXPR, utype, pmop[1]);
11458                   else
11459                     tem = fold_build2_loc (loc, MINUS_EXPR, utype,
11460                                            pmop[0], pmop[1]);
11461                   /* TEM is now the new binary +, - or unary - replacement.  */
11462                   tem = fold_build2_loc (loc, BIT_AND_EXPR, utype, tem,
11463                                          fold_convert_loc (loc, utype, arg1));
11464                   return fold_convert_loc (loc, type, tem);
11465                 }
11466             }
11467         }
11468
11469       t1 = distribute_bit_expr (loc, code, type, arg0, arg1);
11470       if (t1 != NULL_TREE)
11471         return t1;
11472       /* Simplify ((int)c & 0377) into (int)c, if c is unsigned char.  */
11473       if (TREE_CODE (arg1) == INTEGER_CST && TREE_CODE (arg0) == NOP_EXPR
11474           && TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (arg0, 0))))
11475         {
11476           prec = element_precision (TREE_TYPE (TREE_OPERAND (arg0, 0)));
11477
11478           wide_int mask = wide_int::from (arg1, prec, UNSIGNED);
11479           if (mask == -1)
11480             return
11481               fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
11482         }
11483
11484       /* Convert (and (not arg0) (not arg1)) to (not (or (arg0) (arg1))).
11485
11486          This results in more efficient code for machines without a NOR
11487          instruction.  Combine will canonicalize to the first form
11488          which will allow use of NOR instructions provided by the
11489          backend if they exist.  */
11490       if (TREE_CODE (arg0) == BIT_NOT_EXPR
11491           && TREE_CODE (arg1) == BIT_NOT_EXPR)
11492         {
11493           return fold_build1_loc (loc, BIT_NOT_EXPR, type,
11494                               build2 (BIT_IOR_EXPR, type,
11495                                       fold_convert_loc (loc, type,
11496                                                         TREE_OPERAND (arg0, 0)),
11497                                       fold_convert_loc (loc, type,
11498                                                         TREE_OPERAND (arg1, 0))));
11499         }
11500
11501       /* If arg0 is derived from the address of an object or function, we may
11502          be able to fold this expression using the object or function's
11503          alignment.  */
11504       if (POINTER_TYPE_P (TREE_TYPE (arg0)) && tree_fits_uhwi_p (arg1))
11505         {
11506           unsigned HOST_WIDE_INT modulus, residue;
11507           unsigned HOST_WIDE_INT low = tree_to_uhwi (arg1);
11508
11509           modulus = get_pointer_modulus_and_residue (arg0, &residue,
11510                                                      integer_onep (arg1));
11511
11512           /* This works because modulus is a power of 2.  If this weren't the
11513              case, we'd have to replace it by its greatest power-of-2
11514              divisor: modulus & -modulus.  */
11515           if (low < modulus)
11516             return build_int_cst (type, residue & low);
11517         }
11518
11519       /* Fold (X << C1) & C2 into (X << C1) & (C2 | ((1 << C1) - 1))
11520               (X >> C1) & C2 into (X >> C1) & (C2 | ~((type) -1 >> C1))
11521          if the new mask might be further optimized.  */
11522       if ((TREE_CODE (arg0) == LSHIFT_EXPR
11523            || TREE_CODE (arg0) == RSHIFT_EXPR)
11524           && TYPE_PRECISION (TREE_TYPE (arg0)) <= HOST_BITS_PER_WIDE_INT
11525           && TREE_CODE (arg1) == INTEGER_CST
11526           && tree_fits_uhwi_p (TREE_OPERAND (arg0, 1))
11527           && tree_to_uhwi (TREE_OPERAND (arg0, 1)) > 0
11528           && (tree_to_uhwi (TREE_OPERAND (arg0, 1))
11529               < TYPE_PRECISION (TREE_TYPE (arg0))))
11530         {
11531           unsigned int shiftc = tree_to_uhwi (TREE_OPERAND (arg0, 1));
11532           unsigned HOST_WIDE_INT mask = TREE_INT_CST_LOW (arg1);
11533           unsigned HOST_WIDE_INT newmask, zerobits = 0;
11534           tree shift_type = TREE_TYPE (arg0);
11535
11536           if (TREE_CODE (arg0) == LSHIFT_EXPR)
11537             zerobits = ((((unsigned HOST_WIDE_INT) 1) << shiftc) - 1);
11538           else if (TREE_CODE (arg0) == RSHIFT_EXPR
11539                    && TYPE_PRECISION (TREE_TYPE (arg0))
11540                       == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (arg0))))
11541             {
11542               prec = TYPE_PRECISION (TREE_TYPE (arg0));
11543               tree arg00 = TREE_OPERAND (arg0, 0);
11544               /* See if more bits can be proven as zero because of
11545                  zero extension.  */
11546               if (TREE_CODE (arg00) == NOP_EXPR
11547                   && TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (arg00, 0))))
11548                 {
11549                   tree inner_type = TREE_TYPE (TREE_OPERAND (arg00, 0));
11550                   if (TYPE_PRECISION (inner_type)
11551                       == GET_MODE_PRECISION (TYPE_MODE (inner_type))
11552                       && TYPE_PRECISION (inner_type) < prec)
11553                     {
11554                       prec = TYPE_PRECISION (inner_type);
11555                       /* See if we can shorten the right shift.  */
11556                       if (shiftc < prec)
11557                         shift_type = inner_type;
11558                       /* Otherwise X >> C1 is all zeros, so we'll optimize
11559                          it into (X, 0) later on by making sure zerobits
11560                          is all ones.  */
11561                     }
11562                 }
11563               zerobits = ~(unsigned HOST_WIDE_INT) 0;
11564               if (shiftc < prec)
11565                 {
11566                   zerobits >>= HOST_BITS_PER_WIDE_INT - shiftc;
11567                   zerobits <<= prec - shiftc;
11568                 }
11569               /* For arithmetic shift if sign bit could be set, zerobits
11570                  can contain actually sign bits, so no transformation is
11571                  possible, unless MASK masks them all away.  In that
11572                  case the shift needs to be converted into logical shift.  */
11573               if (!TYPE_UNSIGNED (TREE_TYPE (arg0))
11574                   && prec == TYPE_PRECISION (TREE_TYPE (arg0)))
11575                 {
11576                   if ((mask & zerobits) == 0)
11577                     shift_type = unsigned_type_for (TREE_TYPE (arg0));
11578                   else
11579                     zerobits = 0;
11580                 }
11581             }
11582
11583           /* ((X << 16) & 0xff00) is (X, 0).  */
11584           if ((mask & zerobits) == mask)
11585             return omit_one_operand_loc (loc, type,
11586                                          build_int_cst (type, 0), arg0);
11587
11588           newmask = mask | zerobits;
11589           if (newmask != mask && (newmask & (newmask + 1)) == 0)
11590             {
11591               /* Only do the transformation if NEWMASK is some integer
11592                  mode's mask.  */
11593               for (prec = BITS_PER_UNIT;
11594                    prec < HOST_BITS_PER_WIDE_INT; prec <<= 1)
11595                 if (newmask == (((unsigned HOST_WIDE_INT) 1) << prec) - 1)
11596                   break;
11597               if (prec < HOST_BITS_PER_WIDE_INT
11598                   || newmask == ~(unsigned HOST_WIDE_INT) 0)
11599                 {
11600                   tree newmaskt;
11601
11602                   if (shift_type != TREE_TYPE (arg0))
11603                     {
11604                       tem = fold_build2_loc (loc, TREE_CODE (arg0), shift_type,
11605                                          fold_convert_loc (loc, shift_type,
11606                                                            TREE_OPERAND (arg0, 0)),
11607                                          TREE_OPERAND (arg0, 1));
11608                       tem = fold_convert_loc (loc, type, tem);
11609                     }
11610                   else
11611                     tem = op0;
11612                   newmaskt = build_int_cst_type (TREE_TYPE (op1), newmask);
11613                   if (!tree_int_cst_equal (newmaskt, arg1))
11614                     return fold_build2_loc (loc, BIT_AND_EXPR, type, tem, newmaskt);
11615                 }
11616             }
11617         }
11618
11619       goto associate;
11620
11621     case RDIV_EXPR:
11622       /* Don't touch a floating-point divide by zero unless the mode
11623          of the constant can represent infinity.  */
11624       if (TREE_CODE (arg1) == REAL_CST
11625           && !MODE_HAS_INFINITIES (TYPE_MODE (TREE_TYPE (arg1)))
11626           && real_zerop (arg1))
11627         return NULL_TREE;
11628
11629       /* (-A) / (-B) -> A / B  */
11630       if (TREE_CODE (arg0) == NEGATE_EXPR && negate_expr_p (arg1))
11631         return fold_build2_loc (loc, RDIV_EXPR, type,
11632                             TREE_OPERAND (arg0, 0),
11633                             negate_expr (arg1));
11634       if (TREE_CODE (arg1) == NEGATE_EXPR && negate_expr_p (arg0))
11635         return fold_build2_loc (loc, RDIV_EXPR, type,
11636                             negate_expr (arg0),
11637                             TREE_OPERAND (arg1, 0));
11638
11639       /* Convert A/B/C to A/(B*C).  */
11640       if (flag_reciprocal_math
11641           && TREE_CODE (arg0) == RDIV_EXPR)
11642         return fold_build2_loc (loc, RDIV_EXPR, type, TREE_OPERAND (arg0, 0),
11643                             fold_build2_loc (loc, MULT_EXPR, type,
11644                                          TREE_OPERAND (arg0, 1), arg1));
11645
11646       /* Convert A/(B/C) to (A/B)*C.  */
11647       if (flag_reciprocal_math
11648           && TREE_CODE (arg1) == RDIV_EXPR)
11649         return fold_build2_loc (loc, MULT_EXPR, type,
11650                             fold_build2_loc (loc, RDIV_EXPR, type, arg0,
11651                                          TREE_OPERAND (arg1, 0)),
11652                             TREE_OPERAND (arg1, 1));
11653
11654       /* Convert C1/(X*C2) into (C1/C2)/X.  */
11655       if (flag_reciprocal_math
11656           && TREE_CODE (arg1) == MULT_EXPR
11657           && TREE_CODE (arg0) == REAL_CST
11658           && TREE_CODE (TREE_OPERAND (arg1, 1)) == REAL_CST)
11659         {
11660           tree tem = const_binop (RDIV_EXPR, arg0,
11661                                   TREE_OPERAND (arg1, 1));
11662           if (tem)
11663             return fold_build2_loc (loc, RDIV_EXPR, type, tem,
11664                                 TREE_OPERAND (arg1, 0));
11665         }
11666
11667       if (flag_unsafe_math_optimizations)
11668         {
11669           enum built_in_function fcode0 = builtin_mathfn_code (arg0);
11670           enum built_in_function fcode1 = builtin_mathfn_code (arg1);
11671
11672           /* Optimize sin(x)/cos(x) as tan(x).  */
11673           if (((fcode0 == BUILT_IN_SIN && fcode1 == BUILT_IN_COS)
11674                || (fcode0 == BUILT_IN_SINF && fcode1 == BUILT_IN_COSF)
11675                || (fcode0 == BUILT_IN_SINL && fcode1 == BUILT_IN_COSL))
11676               && operand_equal_p (CALL_EXPR_ARG (arg0, 0),
11677                                   CALL_EXPR_ARG (arg1, 0), 0))
11678             {
11679               tree tanfn = mathfn_built_in (type, BUILT_IN_TAN);
11680
11681               if (tanfn != NULL_TREE)
11682                 return build_call_expr_loc (loc, tanfn, 1, CALL_EXPR_ARG (arg0, 0));
11683             }
11684
11685           /* Optimize cos(x)/sin(x) as 1.0/tan(x).  */
11686           if (((fcode0 == BUILT_IN_COS && fcode1 == BUILT_IN_SIN)
11687                || (fcode0 == BUILT_IN_COSF && fcode1 == BUILT_IN_SINF)
11688                || (fcode0 == BUILT_IN_COSL && fcode1 == BUILT_IN_SINL))
11689               && operand_equal_p (CALL_EXPR_ARG (arg0, 0),
11690                                   CALL_EXPR_ARG (arg1, 0), 0))
11691             {
11692               tree tanfn = mathfn_built_in (type, BUILT_IN_TAN);
11693
11694               if (tanfn != NULL_TREE)
11695                 {
11696                   tree tmp = build_call_expr_loc (loc, tanfn, 1,
11697                                               CALL_EXPR_ARG (arg0, 0));
11698                   return fold_build2_loc (loc, RDIV_EXPR, type,
11699                                       build_real (type, dconst1), tmp);
11700                 }
11701             }
11702
11703           /* Optimize sin(x)/tan(x) as cos(x) if we don't care about
11704              NaNs or Infinities.  */
11705           if (((fcode0 == BUILT_IN_SIN && fcode1 == BUILT_IN_TAN)
11706                || (fcode0 == BUILT_IN_SINF && fcode1 == BUILT_IN_TANF)
11707                || (fcode0 == BUILT_IN_SINL && fcode1 == BUILT_IN_TANL)))
11708             {
11709               tree arg00 = CALL_EXPR_ARG (arg0, 0);
11710               tree arg01 = CALL_EXPR_ARG (arg1, 0);
11711
11712               if (! HONOR_NANS (arg00)
11713                   && ! HONOR_INFINITIES (element_mode (arg00))
11714                   && operand_equal_p (arg00, arg01, 0))
11715                 {
11716                   tree cosfn = mathfn_built_in (type, BUILT_IN_COS);
11717
11718                   if (cosfn != NULL_TREE)
11719                     return build_call_expr_loc (loc, cosfn, 1, arg00);
11720                 }
11721             }
11722
11723           /* Optimize tan(x)/sin(x) as 1.0/cos(x) if we don't care about
11724              NaNs or Infinities.  */
11725           if (((fcode0 == BUILT_IN_TAN && fcode1 == BUILT_IN_SIN)
11726                || (fcode0 == BUILT_IN_TANF && fcode1 == BUILT_IN_SINF)
11727                || (fcode0 == BUILT_IN_TANL && fcode1 == BUILT_IN_SINL)))
11728             {
11729               tree arg00 = CALL_EXPR_ARG (arg0, 0);
11730               tree arg01 = CALL_EXPR_ARG (arg1, 0);
11731
11732               if (! HONOR_NANS (arg00)
11733                   && ! HONOR_INFINITIES (element_mode (arg00))
11734                   && operand_equal_p (arg00, arg01, 0))
11735                 {
11736                   tree cosfn = mathfn_built_in (type, BUILT_IN_COS);
11737
11738                   if (cosfn != NULL_TREE)
11739                     {
11740                       tree tmp = build_call_expr_loc (loc, cosfn, 1, arg00);
11741                       return fold_build2_loc (loc, RDIV_EXPR, type,
11742                                           build_real (type, dconst1),
11743                                           tmp);
11744                     }
11745                 }
11746             }
11747
11748           /* Optimize pow(x,c)/x as pow(x,c-1).  */
11749           if (fcode0 == BUILT_IN_POW
11750               || fcode0 == BUILT_IN_POWF
11751               || fcode0 == BUILT_IN_POWL)
11752             {
11753               tree arg00 = CALL_EXPR_ARG (arg0, 0);
11754               tree arg01 = CALL_EXPR_ARG (arg0, 1);
11755               if (TREE_CODE (arg01) == REAL_CST
11756                   && !TREE_OVERFLOW (arg01)
11757                   && operand_equal_p (arg1, arg00, 0))
11758                 {
11759                   tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
11760                   REAL_VALUE_TYPE c;
11761                   tree arg;
11762
11763                   c = TREE_REAL_CST (arg01);
11764                   real_arithmetic (&c, MINUS_EXPR, &c, &dconst1);
11765                   arg = build_real (type, c);
11766                   return build_call_expr_loc (loc, powfn, 2, arg1, arg);
11767                 }
11768             }
11769
11770           /* Optimize a/root(b/c) into a*root(c/b).  */
11771           if (BUILTIN_ROOT_P (fcode1))
11772             {
11773               tree rootarg = CALL_EXPR_ARG (arg1, 0);
11774
11775               if (TREE_CODE (rootarg) == RDIV_EXPR)
11776                 {
11777                   tree rootfn = TREE_OPERAND (CALL_EXPR_FN (arg1), 0);
11778                   tree b = TREE_OPERAND (rootarg, 0);
11779                   tree c = TREE_OPERAND (rootarg, 1);
11780
11781                   tree tmp = fold_build2_loc (loc, RDIV_EXPR, type, c, b);
11782
11783                   tmp = build_call_expr_loc (loc, rootfn, 1, tmp);
11784                   return fold_build2_loc (loc, MULT_EXPR, type, arg0, tmp);
11785                 }
11786             }
11787
11788           /* Optimize x/expN(y) into x*expN(-y).  */
11789           if (BUILTIN_EXPONENT_P (fcode1))
11790             {
11791               tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg1), 0);
11792               tree arg = negate_expr (CALL_EXPR_ARG (arg1, 0));
11793               arg1 = build_call_expr_loc (loc,
11794                                       expfn, 1,
11795                                       fold_convert_loc (loc, type, arg));
11796               return fold_build2_loc (loc, MULT_EXPR, type, arg0, arg1);
11797             }
11798
11799           /* Optimize x/pow(y,z) into x*pow(y,-z).  */
11800           if (fcode1 == BUILT_IN_POW
11801               || fcode1 == BUILT_IN_POWF
11802               || fcode1 == BUILT_IN_POWL)
11803             {
11804               tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg1), 0);
11805               tree arg10 = CALL_EXPR_ARG (arg1, 0);
11806               tree arg11 = CALL_EXPR_ARG (arg1, 1);
11807               tree neg11 = fold_convert_loc (loc, type,
11808                                              negate_expr (arg11));
11809               arg1 = build_call_expr_loc (loc, powfn, 2, arg10, neg11);
11810               return fold_build2_loc (loc, MULT_EXPR, type, arg0, arg1);
11811             }
11812         }
11813       return NULL_TREE;
11814
11815     case TRUNC_DIV_EXPR:
11816       /* Optimize (X & (-A)) / A where A is a power of 2,
11817          to X >> log2(A) */
11818       if (TREE_CODE (arg0) == BIT_AND_EXPR
11819           && !TYPE_UNSIGNED (type) && TREE_CODE (arg1) == INTEGER_CST
11820           && integer_pow2p (arg1) && tree_int_cst_sgn (arg1) > 0)
11821         {
11822           tree sum = fold_binary_loc (loc, PLUS_EXPR, TREE_TYPE (arg1),
11823                                       arg1, TREE_OPERAND (arg0, 1));
11824           if (sum && integer_zerop (sum)) {
11825             tree pow2 = build_int_cst (integer_type_node,
11826                                        wi::exact_log2 (arg1));
11827             return fold_build2_loc (loc, RSHIFT_EXPR, type,
11828                                     TREE_OPERAND (arg0, 0), pow2);
11829           }
11830         }
11831
11832       /* Fall through */
11833       
11834     case FLOOR_DIV_EXPR:
11835       /* Simplify A / (B << N) where A and B are positive and B is
11836          a power of 2, to A >> (N + log2(B)).  */
11837       strict_overflow_p = false;
11838       if (TREE_CODE (arg1) == LSHIFT_EXPR
11839           && (TYPE_UNSIGNED (type)
11840               || tree_expr_nonnegative_warnv_p (op0, &strict_overflow_p)))
11841         {
11842           tree sval = TREE_OPERAND (arg1, 0);
11843           if (integer_pow2p (sval) && tree_int_cst_sgn (sval) > 0)
11844             {
11845               tree sh_cnt = TREE_OPERAND (arg1, 1);
11846               tree pow2 = build_int_cst (TREE_TYPE (sh_cnt),
11847                                          wi::exact_log2 (sval));
11848
11849               if (strict_overflow_p)
11850                 fold_overflow_warning (("assuming signed overflow does not "
11851                                         "occur when simplifying A / (B << N)"),
11852                                        WARN_STRICT_OVERFLOW_MISC);
11853
11854               sh_cnt = fold_build2_loc (loc, PLUS_EXPR, TREE_TYPE (sh_cnt),
11855                                         sh_cnt, pow2);
11856               return fold_build2_loc (loc, RSHIFT_EXPR, type,
11857                                       fold_convert_loc (loc, type, arg0), sh_cnt);
11858             }
11859         }
11860
11861       /* Fall through */
11862
11863     case ROUND_DIV_EXPR:
11864     case CEIL_DIV_EXPR:
11865     case EXACT_DIV_EXPR:
11866       if (integer_zerop (arg1))
11867         return NULL_TREE;
11868
11869       /* Convert -A / -B to A / B when the type is signed and overflow is
11870          undefined.  */
11871       if ((!INTEGRAL_TYPE_P (type) || TYPE_OVERFLOW_UNDEFINED (type))
11872           && TREE_CODE (arg0) == NEGATE_EXPR
11873           && negate_expr_p (arg1))
11874         {
11875           if (INTEGRAL_TYPE_P (type))
11876             fold_overflow_warning (("assuming signed overflow does not occur "
11877                                     "when distributing negation across "
11878                                     "division"),
11879                                    WARN_STRICT_OVERFLOW_MISC);
11880           return fold_build2_loc (loc, code, type,
11881                               fold_convert_loc (loc, type,
11882                                                 TREE_OPERAND (arg0, 0)),
11883                               fold_convert_loc (loc, type,
11884                                                 negate_expr (arg1)));
11885         }
11886       if ((!INTEGRAL_TYPE_P (type) || TYPE_OVERFLOW_UNDEFINED (type))
11887           && TREE_CODE (arg1) == NEGATE_EXPR
11888           && negate_expr_p (arg0))
11889         {
11890           if (INTEGRAL_TYPE_P (type))
11891             fold_overflow_warning (("assuming signed overflow does not occur "
11892                                     "when distributing negation across "
11893                                     "division"),
11894                                    WARN_STRICT_OVERFLOW_MISC);
11895           return fold_build2_loc (loc, code, type,
11896                               fold_convert_loc (loc, type,
11897                                                 negate_expr (arg0)),
11898                               fold_convert_loc (loc, type,
11899                                                 TREE_OPERAND (arg1, 0)));
11900         }
11901
11902       /* If arg0 is a multiple of arg1, then rewrite to the fastest div
11903          operation, EXACT_DIV_EXPR.
11904
11905          Note that only CEIL_DIV_EXPR and FLOOR_DIV_EXPR are rewritten now.
11906          At one time others generated faster code, it's not clear if they do
11907          after the last round to changes to the DIV code in expmed.c.  */
11908       if ((code == CEIL_DIV_EXPR || code == FLOOR_DIV_EXPR)
11909           && multiple_of_p (type, arg0, arg1))
11910         return fold_build2_loc (loc, EXACT_DIV_EXPR, type, arg0, arg1);
11911
11912       strict_overflow_p = false;
11913       if (TREE_CODE (arg1) == INTEGER_CST
11914           && 0 != (tem = extract_muldiv (op0, arg1, code, NULL_TREE,
11915                                          &strict_overflow_p)))
11916         {
11917           if (strict_overflow_p)
11918             fold_overflow_warning (("assuming signed overflow does not occur "
11919                                     "when simplifying division"),
11920                                    WARN_STRICT_OVERFLOW_MISC);
11921           return fold_convert_loc (loc, type, tem);
11922         }
11923
11924       return NULL_TREE;
11925
11926     case CEIL_MOD_EXPR:
11927     case FLOOR_MOD_EXPR:
11928     case ROUND_MOD_EXPR:
11929     case TRUNC_MOD_EXPR:
11930       /* X % -Y is the same as X % Y.  */
11931       if (code == TRUNC_MOD_EXPR
11932           && !TYPE_UNSIGNED (type)
11933           && TREE_CODE (arg1) == NEGATE_EXPR
11934           && !TYPE_OVERFLOW_TRAPS (type))
11935         return fold_build2_loc (loc, code, type, fold_convert_loc (loc, type, arg0),
11936                             fold_convert_loc (loc, type,
11937                                               TREE_OPERAND (arg1, 0)));
11938
11939       strict_overflow_p = false;
11940       if (TREE_CODE (arg1) == INTEGER_CST
11941           && 0 != (tem = extract_muldiv (op0, arg1, code, NULL_TREE,
11942                                          &strict_overflow_p)))
11943         {
11944           if (strict_overflow_p)
11945             fold_overflow_warning (("assuming signed overflow does not occur "
11946                                     "when simplifying modulus"),
11947                                    WARN_STRICT_OVERFLOW_MISC);
11948           return fold_convert_loc (loc, type, tem);
11949         }
11950
11951       /* Optimize TRUNC_MOD_EXPR by a power of two into a BIT_AND_EXPR,
11952          i.e. "X % C" into "X & (C - 1)", if X and C are positive.  */
11953       if ((code == TRUNC_MOD_EXPR || code == FLOOR_MOD_EXPR)
11954           && (TYPE_UNSIGNED (type)
11955               || tree_expr_nonnegative_warnv_p (op0, &strict_overflow_p)))
11956         {
11957           tree c = arg1;
11958           /* Also optimize A % (C << N)  where C is a power of 2,
11959              to A & ((C << N) - 1).  */
11960           if (TREE_CODE (arg1) == LSHIFT_EXPR)
11961             c = TREE_OPERAND (arg1, 0);
11962
11963           if (integer_pow2p (c) && tree_int_cst_sgn (c) > 0)
11964             {
11965               tree mask
11966                 = fold_build2_loc (loc, MINUS_EXPR, TREE_TYPE (arg1), arg1,
11967                                    build_int_cst (TREE_TYPE (arg1), 1));
11968               if (strict_overflow_p)
11969                 fold_overflow_warning (("assuming signed overflow does not "
11970                                         "occur when simplifying "
11971                                         "X % (power of two)"),
11972                                        WARN_STRICT_OVERFLOW_MISC);
11973               return fold_build2_loc (loc, BIT_AND_EXPR, type,
11974                                       fold_convert_loc (loc, type, arg0),
11975                                       fold_convert_loc (loc, type, mask));
11976             }
11977         }
11978
11979       return NULL_TREE;
11980
11981     case LROTATE_EXPR:
11982     case RROTATE_EXPR:
11983     case RSHIFT_EXPR:
11984     case LSHIFT_EXPR:
11985       /* Since negative shift count is not well-defined,
11986          don't try to compute it in the compiler.  */
11987       if (TREE_CODE (arg1) == INTEGER_CST && tree_int_cst_sgn (arg1) < 0)
11988         return NULL_TREE;
11989
11990       prec = element_precision (type);
11991
11992       /* Turn (a OP c1) OP c2 into a OP (c1+c2).  */
11993       if (TREE_CODE (op0) == code && tree_fits_uhwi_p (arg1)
11994           && tree_to_uhwi (arg1) < prec
11995           && tree_fits_uhwi_p (TREE_OPERAND (arg0, 1))
11996           && tree_to_uhwi (TREE_OPERAND (arg0, 1)) < prec)
11997         {
11998           unsigned int low = (tree_to_uhwi (TREE_OPERAND (arg0, 1))
11999                               + tree_to_uhwi (arg1));
12000
12001           /* Deal with a OP (c1 + c2) being undefined but (a OP c1) OP c2
12002              being well defined.  */
12003           if (low >= prec)
12004             {
12005               if (code == LROTATE_EXPR || code == RROTATE_EXPR)
12006                 low = low % prec;
12007               else if (TYPE_UNSIGNED (type) || code == LSHIFT_EXPR)
12008                 return omit_one_operand_loc (loc, type, build_zero_cst (type),
12009                                          TREE_OPERAND (arg0, 0));
12010               else
12011                 low = prec - 1;
12012             }
12013
12014           return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0),
12015                                   build_int_cst (TREE_TYPE (arg1), low));
12016         }
12017
12018       /* Transform (x >> c) << c into x & (-1<<c), or transform (x << c) >> c
12019          into x & ((unsigned)-1 >> c) for unsigned types.  */
12020       if (((code == LSHIFT_EXPR && TREE_CODE (arg0) == RSHIFT_EXPR)
12021            || (TYPE_UNSIGNED (type)
12022                && code == RSHIFT_EXPR && TREE_CODE (arg0) == LSHIFT_EXPR))
12023           && tree_fits_uhwi_p (arg1)
12024           && tree_to_uhwi (arg1) < prec
12025           && tree_fits_uhwi_p (TREE_OPERAND (arg0, 1))
12026           && tree_to_uhwi (TREE_OPERAND (arg0, 1)) < prec)
12027         {
12028           HOST_WIDE_INT low0 = tree_to_uhwi (TREE_OPERAND (arg0, 1));
12029           HOST_WIDE_INT low1 = tree_to_uhwi (arg1);
12030           tree lshift;
12031           tree arg00;
12032
12033           if (low0 == low1)
12034             {
12035               arg00 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
12036
12037               lshift = build_minus_one_cst (type);
12038               lshift = const_binop (code, lshift, arg1);
12039
12040               return fold_build2_loc (loc, BIT_AND_EXPR, type, arg00, lshift);
12041             }
12042         }
12043
12044       /* If we have a rotate of a bit operation with the rotate count and
12045          the second operand of the bit operation both constant,
12046          permute the two operations.  */
12047       if (code == RROTATE_EXPR && TREE_CODE (arg1) == INTEGER_CST
12048           && (TREE_CODE (arg0) == BIT_AND_EXPR
12049               || TREE_CODE (arg0) == BIT_IOR_EXPR
12050               || TREE_CODE (arg0) == BIT_XOR_EXPR)
12051           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12052         return fold_build2_loc (loc, TREE_CODE (arg0), type,
12053                             fold_build2_loc (loc, code, type,
12054                                          TREE_OPERAND (arg0, 0), arg1),
12055                             fold_build2_loc (loc, code, type,
12056                                          TREE_OPERAND (arg0, 1), arg1));
12057
12058       /* Two consecutive rotates adding up to the some integer
12059          multiple of the precision of the type can be ignored.  */
12060       if (code == RROTATE_EXPR && TREE_CODE (arg1) == INTEGER_CST
12061           && TREE_CODE (arg0) == RROTATE_EXPR
12062           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
12063           && wi::umod_trunc (wi::add (arg1, TREE_OPERAND (arg0, 1)),
12064                              prec) == 0)
12065         return TREE_OPERAND (arg0, 0);
12066
12067       /* Fold (X & C2) << C1 into (X << C1) & (C2 << C1)
12068               (X & C2) >> C1 into (X >> C1) & (C2 >> C1)
12069          if the latter can be further optimized.  */
12070       if ((code == LSHIFT_EXPR || code == RSHIFT_EXPR)
12071           && TREE_CODE (arg0) == BIT_AND_EXPR
12072           && TREE_CODE (arg1) == INTEGER_CST
12073           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12074         {
12075           tree mask = fold_build2_loc (loc, code, type,
12076                                    fold_convert_loc (loc, type,
12077                                                      TREE_OPERAND (arg0, 1)),
12078                                    arg1);
12079           tree shift = fold_build2_loc (loc, code, type,
12080                                     fold_convert_loc (loc, type,
12081                                                       TREE_OPERAND (arg0, 0)),
12082                                     arg1);
12083           tem = fold_binary_loc (loc, BIT_AND_EXPR, type, shift, mask);
12084           if (tem)
12085             return tem;
12086         }
12087
12088       return NULL_TREE;
12089
12090     case MIN_EXPR:
12091       tem = fold_minmax (loc, MIN_EXPR, type, arg0, arg1);
12092       if (tem)
12093         return tem;
12094       goto associate;
12095
12096     case MAX_EXPR:
12097       tem = fold_minmax (loc, MAX_EXPR, type, arg0, arg1);
12098       if (tem)
12099         return tem;
12100       goto associate;
12101
12102     case TRUTH_ANDIF_EXPR:
12103       /* Note that the operands of this must be ints
12104          and their values must be 0 or 1.
12105          ("true" is a fixed value perhaps depending on the language.)  */
12106       /* If first arg is constant zero, return it.  */
12107       if (integer_zerop (arg0))
12108         return fold_convert_loc (loc, type, arg0);
12109     case TRUTH_AND_EXPR:
12110       /* If either arg is constant true, drop it.  */
12111       if (TREE_CODE (arg0) == INTEGER_CST && ! integer_zerop (arg0))
12112         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
12113       if (TREE_CODE (arg1) == INTEGER_CST && ! integer_zerop (arg1)
12114           /* Preserve sequence points.  */
12115           && (code != TRUTH_ANDIF_EXPR || ! TREE_SIDE_EFFECTS (arg0)))
12116         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
12117       /* If second arg is constant zero, result is zero, but first arg
12118          must be evaluated.  */
12119       if (integer_zerop (arg1))
12120         return omit_one_operand_loc (loc, type, arg1, arg0);
12121       /* Likewise for first arg, but note that only the TRUTH_AND_EXPR
12122          case will be handled here.  */
12123       if (integer_zerop (arg0))
12124         return omit_one_operand_loc (loc, type, arg0, arg1);
12125
12126       /* !X && X is always false.  */
12127       if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
12128           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
12129         return omit_one_operand_loc (loc, type, integer_zero_node, arg1);
12130       /* X && !X is always false.  */
12131       if (TREE_CODE (arg1) == TRUTH_NOT_EXPR
12132           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
12133         return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
12134
12135       /* A < X && A + 1 > Y ==> A < X && A >= Y.  Normally A + 1 > Y
12136          means A >= Y && A != MAX, but in this case we know that
12137          A < X <= MAX.  */
12138
12139       if (!TREE_SIDE_EFFECTS (arg0)
12140           && !TREE_SIDE_EFFECTS (arg1))
12141         {
12142           tem = fold_to_nonsharp_ineq_using_bound (loc, arg0, arg1);
12143           if (tem && !operand_equal_p (tem, arg0, 0))
12144             return fold_build2_loc (loc, code, type, tem, arg1);
12145
12146           tem = fold_to_nonsharp_ineq_using_bound (loc, arg1, arg0);
12147           if (tem && !operand_equal_p (tem, arg1, 0))
12148             return fold_build2_loc (loc, code, type, arg0, tem);
12149         }
12150
12151       if ((tem = fold_truth_andor (loc, code, type, arg0, arg1, op0, op1))
12152           != NULL_TREE)
12153         return tem;
12154
12155       return NULL_TREE;
12156
12157     case TRUTH_ORIF_EXPR:
12158       /* Note that the operands of this must be ints
12159          and their values must be 0 or true.
12160          ("true" is a fixed value perhaps depending on the language.)  */
12161       /* If first arg is constant true, return it.  */
12162       if (TREE_CODE (arg0) == INTEGER_CST && ! integer_zerop (arg0))
12163         return fold_convert_loc (loc, type, arg0);
12164     case TRUTH_OR_EXPR:
12165       /* If either arg is constant zero, drop it.  */
12166       if (TREE_CODE (arg0) == INTEGER_CST && integer_zerop (arg0))
12167         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg1));
12168       if (TREE_CODE (arg1) == INTEGER_CST && integer_zerop (arg1)
12169           /* Preserve sequence points.  */
12170           && (code != TRUTH_ORIF_EXPR || ! TREE_SIDE_EFFECTS (arg0)))
12171         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
12172       /* If second arg is constant true, result is true, but we must
12173          evaluate first arg.  */
12174       if (TREE_CODE (arg1) == INTEGER_CST && ! integer_zerop (arg1))
12175         return omit_one_operand_loc (loc, type, arg1, arg0);
12176       /* Likewise for first arg, but note this only occurs here for
12177          TRUTH_OR_EXPR.  */
12178       if (TREE_CODE (arg0) == INTEGER_CST && ! integer_zerop (arg0))
12179         return omit_one_operand_loc (loc, type, arg0, arg1);
12180
12181       /* !X || X is always true.  */
12182       if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
12183           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
12184         return omit_one_operand_loc (loc, type, integer_one_node, arg1);
12185       /* X || !X is always true.  */
12186       if (TREE_CODE (arg1) == TRUTH_NOT_EXPR
12187           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
12188         return omit_one_operand_loc (loc, type, integer_one_node, arg0);
12189
12190       /* (X && !Y) || (!X && Y) is X ^ Y */
12191       if (TREE_CODE (arg0) == TRUTH_AND_EXPR
12192           && TREE_CODE (arg1) == TRUTH_AND_EXPR)
12193         {
12194           tree a0, a1, l0, l1, n0, n1;
12195
12196           a0 = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 0));
12197           a1 = fold_convert_loc (loc, type, TREE_OPERAND (arg1, 1));
12198
12199           l0 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0));
12200           l1 = fold_convert_loc (loc, type, TREE_OPERAND (arg0, 1));
12201           
12202           n0 = fold_build1_loc (loc, TRUTH_NOT_EXPR, type, l0);
12203           n1 = fold_build1_loc (loc, TRUTH_NOT_EXPR, type, l1);
12204           
12205           if ((operand_equal_p (n0, a0, 0)
12206                && operand_equal_p (n1, a1, 0))
12207               || (operand_equal_p (n0, a1, 0)
12208                   && operand_equal_p (n1, a0, 0)))
12209             return fold_build2_loc (loc, TRUTH_XOR_EXPR, type, l0, n1);
12210         }
12211
12212       if ((tem = fold_truth_andor (loc, code, type, arg0, arg1, op0, op1))
12213           != NULL_TREE)
12214         return tem;
12215
12216       return NULL_TREE;
12217
12218     case TRUTH_XOR_EXPR:
12219       /* If the second arg is constant zero, drop it.  */
12220       if (integer_zerop (arg1))
12221         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
12222       /* If the second arg is constant true, this is a logical inversion.  */
12223       if (integer_onep (arg1))
12224         {
12225           tem = invert_truthvalue_loc (loc, arg0);
12226           return non_lvalue_loc (loc, fold_convert_loc (loc, type, tem));
12227         }
12228       /* Identical arguments cancel to zero.  */
12229       if (operand_equal_p (arg0, arg1, 0))
12230         return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
12231
12232       /* !X ^ X is always true.  */
12233       if (TREE_CODE (arg0) == TRUTH_NOT_EXPR
12234           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0))
12235         return omit_one_operand_loc (loc, type, integer_one_node, arg1);
12236
12237       /* X ^ !X is always true.  */
12238       if (TREE_CODE (arg1) == TRUTH_NOT_EXPR
12239           && operand_equal_p (arg0, TREE_OPERAND (arg1, 0), 0))
12240         return omit_one_operand_loc (loc, type, integer_one_node, arg0);
12241
12242       return NULL_TREE;
12243
12244     case EQ_EXPR:
12245     case NE_EXPR:
12246       STRIP_NOPS (arg0);
12247       STRIP_NOPS (arg1);
12248
12249       tem = fold_comparison (loc, code, type, op0, op1);
12250       if (tem != NULL_TREE)
12251         return tem;
12252
12253       /* bool_var != 0 becomes bool_var. */
12254       if (TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE && integer_zerop (arg1)
12255           && code == NE_EXPR)
12256         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
12257
12258       /* bool_var == 1 becomes bool_var. */
12259       if (TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE && integer_onep (arg1)
12260           && code == EQ_EXPR)
12261         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
12262
12263       /* bool_var != 1 becomes !bool_var. */
12264       if (TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE && integer_onep (arg1)
12265           && code == NE_EXPR)
12266         return fold_convert_loc (loc, type,
12267                                  fold_build1_loc (loc, TRUTH_NOT_EXPR,
12268                                                   TREE_TYPE (arg0), arg0));
12269
12270       /* bool_var == 0 becomes !bool_var. */
12271       if (TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE && integer_zerop (arg1)
12272           && code == EQ_EXPR)
12273         return fold_convert_loc (loc, type,
12274                                  fold_build1_loc (loc, TRUTH_NOT_EXPR,
12275                                                   TREE_TYPE (arg0), arg0));
12276
12277       /* !exp != 0 becomes !exp */
12278       if (TREE_CODE (arg0) == TRUTH_NOT_EXPR && integer_zerop (arg1)
12279           && code == NE_EXPR)
12280         return non_lvalue_loc (loc, fold_convert_loc (loc, type, arg0));
12281
12282       /* If this is an equality comparison of the address of two non-weak,
12283          unaliased symbols neither of which are extern (since we do not
12284          have access to attributes for externs), then we know the result.  */
12285       if (TREE_CODE (arg0) == ADDR_EXPR
12286           && DECL_P (TREE_OPERAND (arg0, 0))
12287           && TREE_CODE (arg1) == ADDR_EXPR
12288           && DECL_P (TREE_OPERAND (arg1, 0)))
12289         {
12290           int equal;
12291
12292           if (decl_in_symtab_p (TREE_OPERAND (arg0, 0))
12293               && decl_in_symtab_p (TREE_OPERAND (arg1, 0)))
12294             equal = symtab_node::get_create (TREE_OPERAND (arg0, 0))
12295                     ->equal_address_to (symtab_node::get_create
12296                                           (TREE_OPERAND (arg1, 0)));
12297           else
12298             equal = TREE_OPERAND (arg0, 0) == TREE_OPERAND (arg1, 0);
12299           if (equal != 2)
12300             return constant_boolean_node (equal
12301                                           ? code == EQ_EXPR : code != EQ_EXPR,
12302                                           type);
12303         }
12304
12305       /* Similarly for a NEGATE_EXPR.  */
12306       if (TREE_CODE (arg0) == NEGATE_EXPR
12307           && TREE_CODE (arg1) == INTEGER_CST
12308           && 0 != (tem = negate_expr (fold_convert_loc (loc, TREE_TYPE (arg0),
12309                                                         arg1)))
12310           && TREE_CODE (tem) == INTEGER_CST
12311           && !TREE_OVERFLOW (tem))
12312         return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0), tem);
12313
12314       /* Similarly for a BIT_XOR_EXPR;  X ^ C1 == C2 is X == (C1 ^ C2).  */
12315       if (TREE_CODE (arg0) == BIT_XOR_EXPR
12316           && TREE_CODE (arg1) == INTEGER_CST
12317           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12318         return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0),
12319                             fold_build2_loc (loc, BIT_XOR_EXPR, TREE_TYPE (arg0),
12320                                          fold_convert_loc (loc,
12321                                                            TREE_TYPE (arg0),
12322                                                            arg1),
12323                                          TREE_OPERAND (arg0, 1)));
12324
12325       /* Transform comparisons of the form X +- Y CMP X to Y CMP 0.  */
12326       if ((TREE_CODE (arg0) == PLUS_EXPR
12327            || TREE_CODE (arg0) == POINTER_PLUS_EXPR
12328            || TREE_CODE (arg0) == MINUS_EXPR)
12329           && operand_equal_p (tree_strip_nop_conversions (TREE_OPERAND (arg0,
12330                                                                         0)),
12331                               arg1, 0)
12332           && (INTEGRAL_TYPE_P (TREE_TYPE (arg0))
12333               || POINTER_TYPE_P (TREE_TYPE (arg0))))
12334         {
12335           tree val = TREE_OPERAND (arg0, 1);
12336           return omit_two_operands_loc (loc, type,
12337                                     fold_build2_loc (loc, code, type,
12338                                                  val,
12339                                                  build_int_cst (TREE_TYPE (val),
12340                                                                 0)),
12341                                     TREE_OPERAND (arg0, 0), arg1);
12342         }
12343
12344       /* Transform comparisons of the form C - X CMP X if C % 2 == 1.  */
12345       if (TREE_CODE (arg0) == MINUS_EXPR
12346           && TREE_CODE (TREE_OPERAND (arg0, 0)) == INTEGER_CST
12347           && operand_equal_p (tree_strip_nop_conversions (TREE_OPERAND (arg0,
12348                                                                         1)),
12349                               arg1, 0)
12350           && wi::extract_uhwi (TREE_OPERAND (arg0, 0), 0, 1) == 1)
12351         {
12352           return omit_two_operands_loc (loc, type,
12353                                     code == NE_EXPR
12354                                     ? boolean_true_node : boolean_false_node,
12355                                     TREE_OPERAND (arg0, 1), arg1);
12356         }
12357
12358       /* Convert ABS_EXPR<x> == 0 or ABS_EXPR<x> != 0 to x == 0 or x != 0.  */
12359       if (TREE_CODE (arg0) == ABS_EXPR
12360           && (integer_zerop (arg1) || real_zerop (arg1)))
12361         return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0), arg1);
12362
12363       /* If this is an EQ or NE comparison with zero and ARG0 is
12364          (1 << foo) & bar, convert it to (bar >> foo) & 1.  Both require
12365          two operations, but the latter can be done in one less insn
12366          on machines that have only two-operand insns or on which a
12367          constant cannot be the first operand.  */
12368       if (TREE_CODE (arg0) == BIT_AND_EXPR
12369           && integer_zerop (arg1))
12370         {
12371           tree arg00 = TREE_OPERAND (arg0, 0);
12372           tree arg01 = TREE_OPERAND (arg0, 1);
12373           if (TREE_CODE (arg00) == LSHIFT_EXPR
12374               && integer_onep (TREE_OPERAND (arg00, 0)))
12375             {
12376               tree tem = fold_build2_loc (loc, RSHIFT_EXPR, TREE_TYPE (arg00),
12377                                       arg01, TREE_OPERAND (arg00, 1));
12378               tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0), tem,
12379                                  build_int_cst (TREE_TYPE (arg0), 1));
12380               return fold_build2_loc (loc, code, type,
12381                                   fold_convert_loc (loc, TREE_TYPE (arg1), tem),
12382                                   arg1);
12383             }
12384           else if (TREE_CODE (arg01) == LSHIFT_EXPR
12385                    && integer_onep (TREE_OPERAND (arg01, 0)))
12386             {
12387               tree tem = fold_build2_loc (loc, RSHIFT_EXPR, TREE_TYPE (arg01),
12388                                       arg00, TREE_OPERAND (arg01, 1));
12389               tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0), tem,
12390                                  build_int_cst (TREE_TYPE (arg0), 1));
12391               return fold_build2_loc (loc, code, type,
12392                                   fold_convert_loc (loc, TREE_TYPE (arg1), tem),
12393                                   arg1);
12394             }
12395         }
12396
12397       /* If this is an NE or EQ comparison of zero against the result of a
12398          signed MOD operation whose second operand is a power of 2, make
12399          the MOD operation unsigned since it is simpler and equivalent.  */
12400       if (integer_zerop (arg1)
12401           && !TYPE_UNSIGNED (TREE_TYPE (arg0))
12402           && (TREE_CODE (arg0) == TRUNC_MOD_EXPR
12403               || TREE_CODE (arg0) == CEIL_MOD_EXPR
12404               || TREE_CODE (arg0) == FLOOR_MOD_EXPR
12405               || TREE_CODE (arg0) == ROUND_MOD_EXPR)
12406           && integer_pow2p (TREE_OPERAND (arg0, 1)))
12407         {
12408           tree newtype = unsigned_type_for (TREE_TYPE (arg0));
12409           tree newmod = fold_build2_loc (loc, TREE_CODE (arg0), newtype,
12410                                      fold_convert_loc (loc, newtype,
12411                                                        TREE_OPERAND (arg0, 0)),
12412                                      fold_convert_loc (loc, newtype,
12413                                                        TREE_OPERAND (arg0, 1)));
12414
12415           return fold_build2_loc (loc, code, type, newmod,
12416                               fold_convert_loc (loc, newtype, arg1));
12417         }
12418
12419       /* Fold ((X >> C1) & C2) == 0 and ((X >> C1) & C2) != 0 where
12420          C1 is a valid shift constant, and C2 is a power of two, i.e.
12421          a single bit.  */
12422       if (TREE_CODE (arg0) == BIT_AND_EXPR
12423           && TREE_CODE (TREE_OPERAND (arg0, 0)) == RSHIFT_EXPR
12424           && TREE_CODE (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1))
12425              == INTEGER_CST
12426           && integer_pow2p (TREE_OPERAND (arg0, 1))
12427           && integer_zerop (arg1))
12428         {
12429           tree itype = TREE_TYPE (arg0);
12430           tree arg001 = TREE_OPERAND (TREE_OPERAND (arg0, 0), 1);
12431           prec = TYPE_PRECISION (itype);
12432
12433           /* Check for a valid shift count.  */
12434           if (wi::ltu_p (arg001, prec))
12435             {
12436               tree arg01 = TREE_OPERAND (arg0, 1);
12437               tree arg000 = TREE_OPERAND (TREE_OPERAND (arg0, 0), 0);
12438               unsigned HOST_WIDE_INT log2 = tree_log2 (arg01);
12439               /* If (C2 << C1) doesn't overflow, then ((X >> C1) & C2) != 0
12440                  can be rewritten as (X & (C2 << C1)) != 0.  */
12441               if ((log2 + TREE_INT_CST_LOW (arg001)) < prec)
12442                 {
12443                   tem = fold_build2_loc (loc, LSHIFT_EXPR, itype, arg01, arg001);
12444                   tem = fold_build2_loc (loc, BIT_AND_EXPR, itype, arg000, tem);
12445                   return fold_build2_loc (loc, code, type, tem,
12446                                           fold_convert_loc (loc, itype, arg1));
12447                 }
12448               /* Otherwise, for signed (arithmetic) shifts,
12449                  ((X >> C1) & C2) != 0 is rewritten as X < 0, and
12450                  ((X >> C1) & C2) == 0 is rewritten as X >= 0.  */
12451               else if (!TYPE_UNSIGNED (itype))
12452                 return fold_build2_loc (loc, code == EQ_EXPR ? GE_EXPR : LT_EXPR, type,
12453                                     arg000, build_int_cst (itype, 0));
12454               /* Otherwise, of unsigned (logical) shifts,
12455                  ((X >> C1) & C2) != 0 is rewritten as (X,false), and
12456                  ((X >> C1) & C2) == 0 is rewritten as (X,true).  */
12457               else
12458                 return omit_one_operand_loc (loc, type,
12459                                          code == EQ_EXPR ? integer_one_node
12460                                                          : integer_zero_node,
12461                                          arg000);
12462             }
12463         }
12464
12465       /* If we have (A & C) == C where C is a power of 2, convert this into
12466          (A & C) != 0.  Similarly for NE_EXPR.  */
12467       if (TREE_CODE (arg0) == BIT_AND_EXPR
12468           && integer_pow2p (TREE_OPERAND (arg0, 1))
12469           && operand_equal_p (TREE_OPERAND (arg0, 1), arg1, 0))
12470         return fold_build2_loc (loc, code == EQ_EXPR ? NE_EXPR : EQ_EXPR, type,
12471                             arg0, fold_convert_loc (loc, TREE_TYPE (arg0),
12472                                                     integer_zero_node));
12473
12474       /* If we have (A & C) != 0 or (A & C) == 0 and C is the sign
12475          bit, then fold the expression into A < 0 or A >= 0.  */
12476       tem = fold_single_bit_test_into_sign_test (loc, code, arg0, arg1, type);
12477       if (tem)
12478         return tem;
12479
12480       /* If we have (A & C) == D where D & ~C != 0, convert this into 0.
12481          Similarly for NE_EXPR.  */
12482       if (TREE_CODE (arg0) == BIT_AND_EXPR
12483           && TREE_CODE (arg1) == INTEGER_CST
12484           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12485         {
12486           tree notc = fold_build1_loc (loc, BIT_NOT_EXPR,
12487                                    TREE_TYPE (TREE_OPERAND (arg0, 1)),
12488                                    TREE_OPERAND (arg0, 1));
12489           tree dandnotc
12490             = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0),
12491                                fold_convert_loc (loc, TREE_TYPE (arg0), arg1),
12492                                notc);
12493           tree rslt = code == EQ_EXPR ? integer_zero_node : integer_one_node;
12494           if (integer_nonzerop (dandnotc))
12495             return omit_one_operand_loc (loc, type, rslt, arg0);
12496         }
12497
12498       /* If we have (A | C) == D where C & ~D != 0, convert this into 0.
12499          Similarly for NE_EXPR.  */
12500       if (TREE_CODE (arg0) == BIT_IOR_EXPR
12501           && TREE_CODE (arg1) == INTEGER_CST
12502           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12503         {
12504           tree notd = fold_build1_loc (loc, BIT_NOT_EXPR, TREE_TYPE (arg1), arg1);
12505           tree candnotd
12506             = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0),
12507                                TREE_OPERAND (arg0, 1),
12508                                fold_convert_loc (loc, TREE_TYPE (arg0), notd));
12509           tree rslt = code == EQ_EXPR ? integer_zero_node : integer_one_node;
12510           if (integer_nonzerop (candnotd))
12511             return omit_one_operand_loc (loc, type, rslt, arg0);
12512         }
12513
12514       /* If this is a comparison of a field, we may be able to simplify it.  */
12515       if ((TREE_CODE (arg0) == COMPONENT_REF
12516            || TREE_CODE (arg0) == BIT_FIELD_REF)
12517           /* Handle the constant case even without -O
12518              to make sure the warnings are given.  */
12519           && (optimize || TREE_CODE (arg1) == INTEGER_CST))
12520         {
12521           t1 = optimize_bit_field_compare (loc, code, type, arg0, arg1);
12522           if (t1)
12523             return t1;
12524         }
12525
12526       /* Optimize comparisons of strlen vs zero to a compare of the
12527          first character of the string vs zero.  To wit,
12528                 strlen(ptr) == 0   =>  *ptr == 0
12529                 strlen(ptr) != 0   =>  *ptr != 0
12530          Other cases should reduce to one of these two (or a constant)
12531          due to the return value of strlen being unsigned.  */
12532       if (TREE_CODE (arg0) == CALL_EXPR
12533           && integer_zerop (arg1))
12534         {
12535           tree fndecl = get_callee_fndecl (arg0);
12536
12537           if (fndecl
12538               && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
12539               && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STRLEN
12540               && call_expr_nargs (arg0) == 1
12541               && TREE_CODE (TREE_TYPE (CALL_EXPR_ARG (arg0, 0))) == POINTER_TYPE)
12542             {
12543               tree iref = build_fold_indirect_ref_loc (loc,
12544                                                    CALL_EXPR_ARG (arg0, 0));
12545               return fold_build2_loc (loc, code, type, iref,
12546                                   build_int_cst (TREE_TYPE (iref), 0));
12547             }
12548         }
12549
12550       /* Fold (X >> C) != 0 into X < 0 if C is one less than the width
12551          of X.  Similarly fold (X >> C) == 0 into X >= 0.  */
12552       if (TREE_CODE (arg0) == RSHIFT_EXPR
12553           && integer_zerop (arg1)
12554           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12555         {
12556           tree arg00 = TREE_OPERAND (arg0, 0);
12557           tree arg01 = TREE_OPERAND (arg0, 1);
12558           tree itype = TREE_TYPE (arg00);
12559           if (wi::eq_p (arg01, element_precision (itype) - 1))
12560             {
12561               if (TYPE_UNSIGNED (itype))
12562                 {
12563                   itype = signed_type_for (itype);
12564                   arg00 = fold_convert_loc (loc, itype, arg00);
12565                 }
12566               return fold_build2_loc (loc, code == EQ_EXPR ? GE_EXPR : LT_EXPR,
12567                                   type, arg00, build_zero_cst (itype));
12568             }
12569         }
12570
12571       /* (X ^ Y) == 0 becomes X == Y, and (X ^ Y) != 0 becomes X != Y.  */
12572       if (integer_zerop (arg1)
12573           && TREE_CODE (arg0) == BIT_XOR_EXPR)
12574         return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0),
12575                             TREE_OPERAND (arg0, 1));
12576
12577       /* (X ^ Y) == Y becomes X == 0.  We know that Y has no side-effects.  */
12578       if (TREE_CODE (arg0) == BIT_XOR_EXPR
12579           && operand_equal_p (TREE_OPERAND (arg0, 1), arg1, 0))
12580         return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0),
12581                                 build_zero_cst (TREE_TYPE (arg0)));
12582       /* Likewise (X ^ Y) == X becomes Y == 0.  X has no side-effects.  */
12583       if (TREE_CODE (arg0) == BIT_XOR_EXPR
12584           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0)
12585           && reorder_operands_p (TREE_OPERAND (arg0, 1), arg1))
12586         return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 1),
12587                                 build_zero_cst (TREE_TYPE (arg0)));
12588
12589       /* (X ^ C1) op C2 can be rewritten as X op (C1 ^ C2).  */
12590       if (TREE_CODE (arg0) == BIT_XOR_EXPR
12591           && TREE_CODE (arg1) == INTEGER_CST
12592           && TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST)
12593         return fold_build2_loc (loc, code, type, TREE_OPERAND (arg0, 0),
12594                             fold_build2_loc (loc, BIT_XOR_EXPR, TREE_TYPE (arg1),
12595                                          TREE_OPERAND (arg0, 1), arg1));
12596
12597       /* Fold (~X & C) == 0 into (X & C) != 0 and (~X & C) != 0 into
12598          (X & C) == 0 when C is a single bit.  */
12599       if (TREE_CODE (arg0) == BIT_AND_EXPR
12600           && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_NOT_EXPR
12601           && integer_zerop (arg1)
12602           && integer_pow2p (TREE_OPERAND (arg0, 1)))
12603         {
12604           tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg0),
12605                                  TREE_OPERAND (TREE_OPERAND (arg0, 0), 0),
12606                                  TREE_OPERAND (arg0, 1));
12607           return fold_build2_loc (loc, code == EQ_EXPR ? NE_EXPR : EQ_EXPR,
12608                                   type, tem,
12609                                   fold_convert_loc (loc, TREE_TYPE (arg0),
12610                                                     arg1));
12611         }
12612
12613       /* Fold ((X & C) ^ C) eq/ne 0 into (X & C) ne/eq 0, when the
12614          constant C is a power of two, i.e. a single bit.  */
12615       if (TREE_CODE (arg0) == BIT_XOR_EXPR
12616           && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_AND_EXPR
12617           && integer_zerop (arg1)
12618           && integer_pow2p (TREE_OPERAND (arg0, 1))
12619           && operand_equal_p (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1),
12620                               TREE_OPERAND (arg0, 1), OEP_ONLY_CONST))
12621         {
12622           tree arg00 = TREE_OPERAND (arg0, 0);
12623           return fold_build2_loc (loc, code == EQ_EXPR ? NE_EXPR : EQ_EXPR, type,
12624                               arg00, build_int_cst (TREE_TYPE (arg00), 0));
12625         }
12626
12627       /* Likewise, fold ((X ^ C) & C) eq/ne 0 into (X & C) ne/eq 0,
12628          when is C is a power of two, i.e. a single bit.  */
12629       if (TREE_CODE (arg0) == BIT_AND_EXPR
12630           && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_XOR_EXPR
12631           && integer_zerop (arg1)
12632           && integer_pow2p (TREE_OPERAND (arg0, 1))
12633           && operand_equal_p (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1),
12634                               TREE_OPERAND (arg0, 1), OEP_ONLY_CONST))
12635         {
12636           tree arg000 = TREE_OPERAND (TREE_OPERAND (arg0, 0), 0);
12637           tem = fold_build2_loc (loc, BIT_AND_EXPR, TREE_TYPE (arg000),
12638                              arg000, TREE_OPERAND (arg0, 1));
12639           return fold_build2_loc (loc, code == EQ_EXPR ? NE_EXPR : EQ_EXPR, type,
12640                               tem, build_int_cst (TREE_TYPE (tem), 0));
12641         }
12642
12643       if (integer_zerop (arg1)
12644           && tree_expr_nonzero_p (arg0))
12645         {
12646           tree res = constant_boolean_node (code==NE_EXPR, type);
12647           return omit_one_operand_loc (loc, type, res, arg0);
12648         }
12649
12650       /* Fold -X op -Y as X op Y, where op is eq/ne.  */
12651       if (TREE_CODE (arg0) == NEGATE_EXPR
12652           && TREE_CODE (arg1) == NEGATE_EXPR)
12653         return fold_build2_loc (loc, code, type,
12654                                 TREE_OPERAND (arg0, 0),
12655                                 fold_convert_loc (loc, TREE_TYPE (arg0),
12656                                                   TREE_OPERAND (arg1, 0)));
12657
12658       /* Fold (X & C) op (Y & C) as (X ^ Y) & C op 0", and symmetries.  */
12659       if (TREE_CODE (arg0) == BIT_AND_EXPR
12660           && TREE_CODE (arg1) == BIT_AND_EXPR)
12661         {
12662           tree arg00 = TREE_OPERAND (arg0, 0);
12663           tree arg01 = TREE_OPERAND (arg0, 1);
12664           tree arg10 = TREE_OPERAND (arg1, 0);
12665           tree arg11 = TREE_OPERAND (arg1, 1);
12666           tree itype = TREE_TYPE (arg0);
12667
12668           if (operand_equal_p (arg01, arg11, 0))
12669             return fold_build2_loc (loc, code, type,
12670                                 fold_build2_loc (loc, BIT_AND_EXPR, itype,
12671                                              fold_build2_loc (loc,
12672                                                           BIT_XOR_EXPR, itype,
12673                                                           arg00, arg10),
12674                                              arg01),
12675                                 build_zero_cst (itype));
12676
12677           if (operand_equal_p (arg01, arg10, 0))
12678             return fold_build2_loc (loc, code, type,
12679                                 fold_build2_loc (loc, BIT_AND_EXPR, itype,
12680                                              fold_build2_loc (loc,
12681                                                           BIT_XOR_EXPR, itype,
12682                                                           arg00, arg11),
12683                                              arg01),
12684                                 build_zero_cst (itype));
12685
12686           if (operand_equal_p (arg00, arg11, 0))
12687             return fold_build2_loc (loc, code, type,
12688                                 fold_build2_loc (loc, BIT_AND_EXPR, itype,
12689                                              fold_build2_loc (loc,
12690                                                           BIT_XOR_EXPR, itype,
12691                                                           arg01, arg10),
12692                                              arg00),
12693                                 build_zero_cst (itype));
12694
12695           if (operand_equal_p (arg00, arg10, 0))
12696             return fold_build2_loc (loc, code, type,
12697                                 fold_build2_loc (loc, BIT_AND_EXPR, itype,
12698                                              fold_build2_loc (loc,
12699                                                           BIT_XOR_EXPR, itype,
12700                                                           arg01, arg11),
12701                                              arg00),
12702                                 build_zero_cst (itype));
12703         }
12704
12705       if (TREE_CODE (arg0) == BIT_XOR_EXPR
12706           && TREE_CODE (arg1) == BIT_XOR_EXPR)
12707         {
12708           tree arg00 = TREE_OPERAND (arg0, 0);
12709           tree arg01 = TREE_OPERAND (arg0, 1);
12710           tree arg10 = TREE_OPERAND (arg1, 0);
12711           tree arg11 = TREE_OPERAND (arg1, 1);
12712           tree itype = TREE_TYPE (arg0);
12713
12714           /* Optimize (X ^ Z) op (Y ^ Z) as X op Y, and symmetries.
12715              operand_equal_p guarantees no side-effects so we don't need
12716              to use omit_one_operand on Z.  */
12717           if (operand_equal_p (arg01, arg11, 0))
12718             return fold_build2_loc (loc, code, type, arg00,
12719                                     fold_convert_loc (loc, TREE_TYPE (arg00),
12720                                                       arg10));
12721           if (operand_equal_p (arg01, arg10, 0))
12722             return fold_build2_loc (loc, code, type, arg00,
12723                                     fold_convert_loc (loc, TREE_TYPE (arg00),
12724                                                       arg11));
12725           if (operand_equal_p (arg00, arg11, 0))
12726             return fold_build2_loc (loc, code, type, arg01,
12727                                     fold_convert_loc (loc, TREE_TYPE (arg01),
12728                                                       arg10));
12729           if (operand_equal_p (arg00, arg10, 0))
12730             return fold_build2_loc (loc, code, type, arg01,
12731                                     fold_convert_loc (loc, TREE_TYPE (arg01),
12732                                                       arg11));
12733
12734           /* Optimize (X ^ C1) op (Y ^ C2) as (X ^ (C1 ^ C2)) op Y.  */
12735           if (TREE_CODE (arg01) == INTEGER_CST
12736               && TREE_CODE (arg11) == INTEGER_CST)
12737             {
12738               tem = fold_build2_loc (loc, BIT_XOR_EXPR, itype, arg01,
12739                                      fold_convert_loc (loc, itype, arg11));
12740               tem = fold_build2_loc (loc, BIT_XOR_EXPR, itype, arg00, tem);
12741               return fold_build2_loc (loc, code, type, tem,
12742                                       fold_convert_loc (loc, itype, arg10));
12743             }
12744         }
12745
12746       /* Attempt to simplify equality/inequality comparisons of complex
12747          values.  Only lower the comparison if the result is known or
12748          can be simplified to a single scalar comparison.  */
12749       if ((TREE_CODE (arg0) == COMPLEX_EXPR
12750            || TREE_CODE (arg0) == COMPLEX_CST)
12751           && (TREE_CODE (arg1) == COMPLEX_EXPR
12752               || TREE_CODE (arg1) == COMPLEX_CST))
12753         {
12754           tree real0, imag0, real1, imag1;
12755           tree rcond, icond;
12756
12757           if (TREE_CODE (arg0) == COMPLEX_EXPR)
12758             {
12759               real0 = TREE_OPERAND (arg0, 0);
12760               imag0 = TREE_OPERAND (arg0, 1);
12761             }
12762           else
12763             {
12764               real0 = TREE_REALPART (arg0);
12765               imag0 = TREE_IMAGPART (arg0);
12766             }
12767
12768           if (TREE_CODE (arg1) == COMPLEX_EXPR)
12769             {
12770               real1 = TREE_OPERAND (arg1, 0);
12771               imag1 = TREE_OPERAND (arg1, 1);
12772             }
12773           else
12774             {
12775               real1 = TREE_REALPART (arg1);
12776               imag1 = TREE_IMAGPART (arg1);
12777             }
12778
12779           rcond = fold_binary_loc (loc, code, type, real0, real1);
12780           if (rcond && TREE_CODE (rcond) == INTEGER_CST)
12781             {
12782               if (integer_zerop (rcond))
12783                 {
12784                   if (code == EQ_EXPR)
12785                     return omit_two_operands_loc (loc, type, boolean_false_node,
12786                                               imag0, imag1);
12787                   return fold_build2_loc (loc, NE_EXPR, type, imag0, imag1);
12788                 }
12789               else
12790                 {
12791                   if (code == NE_EXPR)
12792                     return omit_two_operands_loc (loc, type, boolean_true_node,
12793                                               imag0, imag1);
12794                   return fold_build2_loc (loc, EQ_EXPR, type, imag0, imag1);
12795                 }
12796             }
12797
12798           icond = fold_binary_loc (loc, code, type, imag0, imag1);
12799           if (icond && TREE_CODE (icond) == INTEGER_CST)
12800             {
12801               if (integer_zerop (icond))
12802                 {
12803                   if (code == EQ_EXPR)
12804                     return omit_two_operands_loc (loc, type, boolean_false_node,
12805                                               real0, real1);
12806                   return fold_build2_loc (loc, NE_EXPR, type, real0, real1);
12807                 }
12808               else
12809                 {
12810                   if (code == NE_EXPR)
12811                     return omit_two_operands_loc (loc, type, boolean_true_node,
12812                                               real0, real1);
12813                   return fold_build2_loc (loc, EQ_EXPR, type, real0, real1);
12814                 }
12815             }
12816         }
12817
12818       return NULL_TREE;
12819
12820     case LT_EXPR:
12821     case GT_EXPR:
12822     case LE_EXPR:
12823     case GE_EXPR:
12824       tem = fold_comparison (loc, code, type, op0, op1);
12825       if (tem != NULL_TREE)
12826         return tem;
12827
12828       /* Transform comparisons of the form X +- C CMP X.  */
12829       if ((TREE_CODE (arg0) == PLUS_EXPR || TREE_CODE (arg0) == MINUS_EXPR)
12830           && operand_equal_p (TREE_OPERAND (arg0, 0), arg1, 0)
12831           && ((TREE_CODE (TREE_OPERAND (arg0, 1)) == REAL_CST
12832                && !HONOR_SNANS (arg0))
12833               || (TREE_CODE (TREE_OPERAND (arg0, 1)) == INTEGER_CST
12834                   && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))))
12835         {
12836           tree arg01 = TREE_OPERAND (arg0, 1);
12837           enum tree_code code0 = TREE_CODE (arg0);
12838           int is_positive;
12839
12840           if (TREE_CODE (arg01) == REAL_CST)
12841             is_positive = REAL_VALUE_NEGATIVE (TREE_REAL_CST (arg01)) ? -1 : 1;
12842           else
12843             is_positive = tree_int_cst_sgn (arg01);
12844
12845           /* (X - c) > X becomes false.  */
12846           if (code == GT_EXPR
12847               && ((code0 == MINUS_EXPR && is_positive >= 0)
12848                   || (code0 == PLUS_EXPR && is_positive <= 0)))
12849             {
12850               if (TREE_CODE (arg01) == INTEGER_CST
12851                   && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
12852                 fold_overflow_warning (("assuming signed overflow does not "
12853                                         "occur when assuming that (X - c) > X "
12854                                         "is always false"),
12855                                        WARN_STRICT_OVERFLOW_ALL);
12856               return constant_boolean_node (0, type);
12857             }
12858
12859           /* Likewise (X + c) < X becomes false.  */
12860           if (code == LT_EXPR
12861               && ((code0 == PLUS_EXPR && is_positive >= 0)
12862                   || (code0 == MINUS_EXPR && is_positive <= 0)))
12863             {
12864               if (TREE_CODE (arg01) == INTEGER_CST
12865                   && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
12866                 fold_overflow_warning (("assuming signed overflow does not "
12867                                         "occur when assuming that "
12868                                         "(X + c) < X is always false"),
12869                                        WARN_STRICT_OVERFLOW_ALL);
12870               return constant_boolean_node (0, type);
12871             }
12872
12873           /* Convert (X - c) <= X to true.  */
12874           if (!HONOR_NANS (arg1)
12875               && code == LE_EXPR
12876               && ((code0 == MINUS_EXPR && is_positive >= 0)
12877                   || (code0 == PLUS_EXPR && is_positive <= 0)))
12878             {
12879               if (TREE_CODE (arg01) == INTEGER_CST
12880                   && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
12881                 fold_overflow_warning (("assuming signed overflow does not "
12882                                         "occur when assuming that "
12883                                         "(X - c) <= X is always true"),
12884                                        WARN_STRICT_OVERFLOW_ALL);
12885               return constant_boolean_node (1, type);
12886             }
12887
12888           /* Convert (X + c) >= X to true.  */
12889           if (!HONOR_NANS (arg1)
12890               && code == GE_EXPR
12891               && ((code0 == PLUS_EXPR && is_positive >= 0)
12892                   || (code0 == MINUS_EXPR && is_positive <= 0)))
12893             {
12894               if (TREE_CODE (arg01) == INTEGER_CST
12895                   && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
12896                 fold_overflow_warning (("assuming signed overflow does not "
12897                                         "occur when assuming that "
12898                                         "(X + c) >= X is always true"),
12899                                        WARN_STRICT_OVERFLOW_ALL);
12900               return constant_boolean_node (1, type);
12901             }
12902
12903           if (TREE_CODE (arg01) == INTEGER_CST)
12904             {
12905               /* Convert X + c > X and X - c < X to true for integers.  */
12906               if (code == GT_EXPR
12907                   && ((code0 == PLUS_EXPR && is_positive > 0)
12908                       || (code0 == MINUS_EXPR && is_positive < 0)))
12909                 {
12910                   if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
12911                     fold_overflow_warning (("assuming signed overflow does "
12912                                             "not occur when assuming that "
12913                                             "(X + c) > X is always true"),
12914                                            WARN_STRICT_OVERFLOW_ALL);
12915                   return constant_boolean_node (1, type);
12916                 }
12917
12918               if (code == LT_EXPR
12919                   && ((code0 == MINUS_EXPR && is_positive > 0)
12920                       || (code0 == PLUS_EXPR && is_positive < 0)))
12921                 {
12922                   if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
12923                     fold_overflow_warning (("assuming signed overflow does "
12924                                             "not occur when assuming that "
12925                                             "(X - c) < X is always true"),
12926                                            WARN_STRICT_OVERFLOW_ALL);
12927                   return constant_boolean_node (1, type);
12928                 }
12929
12930               /* Convert X + c <= X and X - c >= X to false for integers.  */
12931               if (code == LE_EXPR
12932                   && ((code0 == PLUS_EXPR && is_positive > 0)
12933                       || (code0 == MINUS_EXPR && is_positive < 0)))
12934                 {
12935                   if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
12936                     fold_overflow_warning (("assuming signed overflow does "
12937                                             "not occur when assuming that "
12938                                             "(X + c) <= X is always false"),
12939                                            WARN_STRICT_OVERFLOW_ALL);
12940                   return constant_boolean_node (0, type);
12941                 }
12942
12943               if (code == GE_EXPR
12944                   && ((code0 == MINUS_EXPR && is_positive > 0)
12945                       || (code0 == PLUS_EXPR && is_positive < 0)))
12946                 {
12947                   if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (arg1)))
12948                     fold_overflow_warning (("assuming signed overflow does "
12949                                             "not occur when assuming that "
12950                                             "(X - c) >= X is always false"),
12951                                            WARN_STRICT_OVERFLOW_ALL);
12952                   return constant_boolean_node (0, type);
12953                 }
12954             }
12955         }
12956
12957       /* Comparisons with the highest or lowest possible integer of
12958          the specified precision will have known values.  */
12959       {
12960         tree arg1_type = TREE_TYPE (arg1);
12961         unsigned int prec = TYPE_PRECISION (arg1_type);
12962
12963         if (TREE_CODE (arg1) == INTEGER_CST
12964             && (INTEGRAL_TYPE_P (arg1_type) || POINTER_TYPE_P (arg1_type)))
12965           {
12966             wide_int max = wi::max_value (arg1_type);
12967             wide_int signed_max = wi::max_value (prec, SIGNED);
12968             wide_int min = wi::min_value (arg1_type);
12969
12970             if (wi::eq_p (arg1, max))
12971               switch (code)
12972                 {
12973                 case GT_EXPR:
12974                   return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
12975
12976                 case GE_EXPR:
12977                   return fold_build2_loc (loc, EQ_EXPR, type, op0, op1);
12978
12979                 case LE_EXPR:
12980                   return omit_one_operand_loc (loc, type, integer_one_node, arg0);
12981
12982                 case LT_EXPR:
12983                   return fold_build2_loc (loc, NE_EXPR, type, op0, op1);
12984
12985                 /* The GE_EXPR and LT_EXPR cases above are not normally
12986                    reached because of previous transformations.  */
12987
12988                 default:
12989                   break;
12990                 }
12991             else if (wi::eq_p (arg1, max - 1))
12992               switch (code)
12993                 {
12994                 case GT_EXPR:
12995                   arg1 = const_binop (PLUS_EXPR, arg1,
12996                                       build_int_cst (TREE_TYPE (arg1), 1));
12997                   return fold_build2_loc (loc, EQ_EXPR, type,
12998                                       fold_convert_loc (loc,
12999                                                         TREE_TYPE (arg1), arg0),
13000                                       arg1);
13001                 case LE_EXPR:
13002                   arg1 = const_binop (PLUS_EXPR, arg1,
13003                                       build_int_cst (TREE_TYPE (arg1), 1));
13004                   return fold_build2_loc (loc, NE_EXPR, type,
13005                                       fold_convert_loc (loc, TREE_TYPE (arg1),
13006                                                         arg0),
13007                                       arg1);
13008                 default:
13009                   break;
13010                 }
13011             else if (wi::eq_p (arg1, min))
13012               switch (code)
13013                 {
13014                 case LT_EXPR:
13015                   return omit_one_operand_loc (loc, type, integer_zero_node, arg0);
13016
13017                 case LE_EXPR:
13018                   return fold_build2_loc (loc, EQ_EXPR, type, op0, op1);
13019
13020                 case GE_EXPR:
13021                   return omit_one_operand_loc (loc, type, integer_one_node, arg0);
13022
13023                 case GT_EXPR:
13024                   return fold_build2_loc (loc, NE_EXPR, type, op0, op1);
13025
13026                 default:
13027                   break;
13028                 }
13029             else if (wi::eq_p (arg1, min + 1))
13030               switch (code)
13031                 {
13032                 case GE_EXPR:
13033                   arg1 = const_binop (MINUS_EXPR, arg1,
13034                                       build_int_cst (TREE_TYPE (arg1), 1));
13035                   return fold_build2_loc (loc, NE_EXPR, type,
13036                                       fold_convert_loc (loc,
13037                                                         TREE_TYPE (arg1), arg0),
13038                                       arg1);
13039                 case LT_EXPR:
13040                   arg1 = const_binop (MINUS_EXPR, arg1,
13041                                       build_int_cst (TREE_TYPE (arg1), 1));
13042                   return fold_build2_loc (loc, EQ_EXPR, type,
13043                                       fold_convert_loc (loc, TREE_TYPE (arg1),
13044                                                         arg0),
13045                                       arg1);
13046                 default:
13047                   break;
13048                 }
13049
13050             else if (wi::eq_p (arg1, signed_max)
13051                      && TYPE_UNSIGNED (arg1_type)
13052                      /* We will flip the signedness of the comparison operator
13053                         associated with the mode of arg1, so the sign bit is
13054                         specified by this mode.  Check that arg1 is the signed
13055                         max associated with this sign bit.  */
13056                      && prec == GET_MODE_PRECISION (TYPE_MODE (arg1_type))
13057                      /* signed_type does not work on pointer types.  */
13058                      && INTEGRAL_TYPE_P (arg1_type))
13059               {
13060                 /* The following case also applies to X < signed_max+1
13061                    and X >= signed_max+1 because previous transformations.  */
13062                 if (code == LE_EXPR || code == GT_EXPR)
13063                   {
13064                     tree st = signed_type_for (arg1_type);
13065                     return fold_build2_loc (loc,
13066                                         code == LE_EXPR ? GE_EXPR : LT_EXPR,
13067                                         type, fold_convert_loc (loc, st, arg0),
13068                                         build_int_cst (st, 0));
13069                   }
13070               }
13071           }
13072       }
13073
13074       /* If we are comparing an ABS_EXPR with a constant, we can
13075          convert all the cases into explicit comparisons, but they may
13076          well not be faster than doing the ABS and one comparison.
13077          But ABS (X) <= C is a range comparison, which becomes a subtraction
13078          and a comparison, and is probably faster.  */
13079       if (code == LE_EXPR
13080           && TREE_CODE (arg1) == INTEGER_CST
13081           && TREE_CODE (arg0) == ABS_EXPR
13082           && ! TREE_SIDE_EFFECTS (arg0)
13083           && (0 != (tem = negate_expr (arg1)))
13084           && TREE_CODE (tem) == INTEGER_CST
13085           && !TREE_OVERFLOW (tem))
13086         return fold_build2_loc (loc, TRUTH_ANDIF_EXPR, type,
13087                             build2 (GE_EXPR, type,
13088                                     TREE_OPERAND (arg0, 0), tem),
13089                             build2 (LE_EXPR, type,
13090                                     TREE_OPERAND (arg0, 0), arg1));
13091
13092       /* Convert ABS_EXPR<x> >= 0 to true.  */
13093       strict_overflow_p = false;
13094       if (code == GE_EXPR
13095           && (integer_zerop (arg1)
13096               || (! HONOR_NANS (arg0)
13097                   && real_zerop (arg1)))
13098           && tree_expr_nonnegative_warnv_p (arg0, &strict_overflow_p))
13099         {
13100           if (strict_overflow_p)
13101             fold_overflow_warning (("assuming signed overflow does not occur "
13102                                     "when simplifying comparison of "
13103                                     "absolute value and zero"),
13104                                    WARN_STRICT_OVERFLOW_CONDITIONAL);
13105           return omit_one_operand_loc (loc, type,
13106                                        constant_boolean_node (true, type),
13107                                        arg0);
13108         }
13109
13110       /* Convert ABS_EXPR<x> < 0 to false.  */
13111       strict_overflow_p = false;
13112       if (code == LT_EXPR
13113           && (integer_zerop (arg1) || real_zerop (arg1))
13114           && tree_expr_nonnegative_warnv_p (arg0, &strict_overflow_p))
13115         {
13116           if (strict_overflow_p)
13117             fold_overflow_warning (("assuming signed overflow does not occur "
13118                                     "when simplifying comparison of "
13119                                     "absolute value and zero"),
13120                                    WARN_STRICT_OVERFLOW_CONDITIONAL);
13121           return omit_one_operand_loc (loc, type,
13122                                        constant_boolean_node (false, type),
13123                                        arg0);
13124         }
13125
13126       /* If X is unsigned, convert X < (1 << Y) into X >> Y == 0
13127          and similarly for >= into !=.  */
13128       if ((code == LT_EXPR || code == GE_EXPR)
13129           && TYPE_UNSIGNED (TREE_TYPE (arg0))
13130           && TREE_CODE (arg1) == LSHIFT_EXPR
13131           && integer_onep (TREE_OPERAND (arg1, 0)))
13132         return build2_loc (loc, code == LT_EXPR ? EQ_EXPR : NE_EXPR, type,
13133                            build2 (RSHIFT_EXPR, TREE_TYPE (arg0), arg0,
13134                                    TREE_OPERAND (arg1, 1)),
13135                            build_zero_cst (TREE_TYPE (arg0)));
13136
13137       /* Similarly for X < (cast) (1 << Y).  But cast can't be narrowing,
13138          otherwise Y might be >= # of bits in X's type and thus e.g.
13139          (unsigned char) (1 << Y) for Y 15 might be 0.
13140          If the cast is widening, then 1 << Y should have unsigned type,
13141          otherwise if Y is number of bits in the signed shift type minus 1,
13142          we can't optimize this.  E.g. (unsigned long long) (1 << Y) for Y
13143          31 might be 0xffffffff80000000.  */
13144       if ((code == LT_EXPR || code == GE_EXPR)
13145           && TYPE_UNSIGNED (TREE_TYPE (arg0))
13146           && CONVERT_EXPR_P (arg1)
13147           && TREE_CODE (TREE_OPERAND (arg1, 0)) == LSHIFT_EXPR
13148           && (element_precision (TREE_TYPE (arg1))
13149               >= element_precision (TREE_TYPE (TREE_OPERAND (arg1, 0))))
13150           && (TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (arg1, 0)))
13151               || (element_precision (TREE_TYPE (arg1))
13152                   == element_precision (TREE_TYPE (TREE_OPERAND (arg1, 0)))))
13153           && integer_onep (TREE_OPERAND (TREE_OPERAND (arg1, 0), 0)))
13154         {
13155           tem = build2 (RSHIFT_EXPR, TREE_TYPE (arg0), arg0,
13156                         TREE_OPERAND (TREE_OPERAND (arg1, 0), 1));
13157           return build2_loc (loc, code == LT_EXPR ? EQ_EXPR : NE_EXPR, type,
13158                              fold_convert_loc (loc, TREE_TYPE (arg0), tem),
13159                              build_zero_cst (TREE_TYPE (arg0)));
13160         }
13161
13162       return NULL_TREE;
13163
13164     case UNORDERED_EXPR:
13165     case ORDERED_EXPR:
13166     case UNLT_EXPR:
13167     case UNLE_EXPR:
13168     case UNGT_EXPR:
13169     case UNGE_EXPR:
13170     case UNEQ_EXPR:
13171     case LTGT_EXPR:
13172       if (TREE_CODE (arg0) == REAL_CST && TREE_CODE (arg1) == REAL_CST)
13173         {
13174           t1 = fold_relational_const (code, type, arg0, arg1);
13175           if (t1 != NULL_TREE)
13176             return t1;
13177         }
13178
13179       /* If the first operand is NaN, the result is constant.  */
13180       if (TREE_CODE (arg0) == REAL_CST
13181           && REAL_VALUE_ISNAN (TREE_REAL_CST (arg0))
13182           && (code != LTGT_EXPR || ! flag_trapping_math))
13183         {
13184           t1 = (code == ORDERED_EXPR || code == LTGT_EXPR)
13185                ? integer_zero_node
13186                : integer_one_node;
13187           return omit_one_operand_loc (loc, type, t1, arg1);
13188         }
13189
13190       /* If the second operand is NaN, the result is constant.  */
13191       if (TREE_CODE (arg1) == REAL_CST
13192           && REAL_VALUE_ISNAN (TREE_REAL_CST (arg1))
13193           && (code != LTGT_EXPR || ! flag_trapping_math))
13194         {
13195           t1 = (code == ORDERED_EXPR || code == LTGT_EXPR)
13196                ? integer_zero_node
13197                : integer_one_node;
13198           return omit_one_operand_loc (loc, type, t1, arg0);
13199         }
13200
13201       /* Simplify unordered comparison of something with itself.  */
13202       if ((code == UNLE_EXPR || code == UNGE_EXPR || code == UNEQ_EXPR)
13203           && operand_equal_p (arg0, arg1, 0))
13204         return constant_boolean_node (1, type);
13205
13206       if (code == LTGT_EXPR
13207           && !flag_trapping_math
13208           && operand_equal_p (arg0, arg1, 0))
13209         return constant_boolean_node (0, type);
13210
13211       /* Fold (double)float1 CMP (double)float2 into float1 CMP float2.  */
13212       {
13213         tree targ0 = strip_float_extensions (arg0);
13214         tree targ1 = strip_float_extensions (arg1);
13215         tree newtype = TREE_TYPE (targ0);
13216
13217         if (TYPE_PRECISION (TREE_TYPE (targ1)) > TYPE_PRECISION (newtype))
13218           newtype = TREE_TYPE (targ1);
13219
13220         if (TYPE_PRECISION (newtype) < TYPE_PRECISION (TREE_TYPE (arg0)))
13221           return fold_build2_loc (loc, code, type,
13222                               fold_convert_loc (loc, newtype, targ0),
13223                               fold_convert_loc (loc, newtype, targ1));
13224       }
13225
13226       return NULL_TREE;
13227
13228     case COMPOUND_EXPR:
13229       /* When pedantic, a compound expression can be neither an lvalue
13230          nor an integer constant expression.  */
13231       if (TREE_SIDE_EFFECTS (arg0) || TREE_CONSTANT (arg1))
13232         return NULL_TREE;
13233       /* Don't let (0, 0) be null pointer constant.  */
13234       tem = integer_zerop (arg1) ? build1 (NOP_EXPR, type, arg1)
13235                                  : fold_convert_loc (loc, type, arg1);
13236       return pedantic_non_lvalue_loc (loc, tem);
13237
13238     case ASSERT_EXPR:
13239       /* An ASSERT_EXPR should never be passed to fold_binary.  */
13240       gcc_unreachable ();
13241
13242     default:
13243       return NULL_TREE;
13244     } /* switch (code) */
13245 }
13246
13247 /* Callback for walk_tree, looking for LABEL_EXPR.  Return *TP if it is
13248    a LABEL_EXPR; otherwise return NULL_TREE.  Do not check the subtrees
13249    of GOTO_EXPR.  */
13250
13251 static tree
13252 contains_label_1 (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
13253 {
13254   switch (TREE_CODE (*tp))
13255     {
13256     case LABEL_EXPR:
13257       return *tp;
13258
13259     case GOTO_EXPR:
13260       *walk_subtrees = 0;
13261
13262       /* ... fall through ...  */
13263
13264     default:
13265       return NULL_TREE;
13266     }
13267 }
13268
13269 /* Return whether the sub-tree ST contains a label which is accessible from
13270    outside the sub-tree.  */
13271
13272 static bool
13273 contains_label_p (tree st)
13274 {
13275   return
13276    (walk_tree_without_duplicates (&st, contains_label_1 , NULL) != NULL_TREE);
13277 }
13278
13279 /* Fold a ternary expression of code CODE and type TYPE with operands
13280    OP0, OP1, and OP2.  Return the folded expression if folding is
13281    successful.  Otherwise, return NULL_TREE.  */
13282
13283 tree
13284 fold_ternary_loc (location_t loc, enum tree_code code, tree type,
13285                   tree op0, tree op1, tree op2)
13286 {
13287   tree tem;
13288   tree arg0 = NULL_TREE, arg1 = NULL_TREE, arg2 = NULL_TREE;
13289   enum tree_code_class kind = TREE_CODE_CLASS (code);
13290
13291   gcc_assert (IS_EXPR_CODE_CLASS (kind)
13292               && TREE_CODE_LENGTH (code) == 3);
13293
13294   /* If this is a commutative operation, and OP0 is a constant, move it
13295      to OP1 to reduce the number of tests below.  */
13296   if (commutative_ternary_tree_code (code)
13297       && tree_swap_operands_p (op0, op1, true))
13298     return fold_build3_loc (loc, code, type, op1, op0, op2);
13299
13300   tem = generic_simplify (loc, code, type, op0, op1, op2);
13301   if (tem)
13302     return tem;
13303
13304   /* Strip any conversions that don't change the mode.  This is safe
13305      for every expression, except for a comparison expression because
13306      its signedness is derived from its operands.  So, in the latter
13307      case, only strip conversions that don't change the signedness.
13308
13309      Note that this is done as an internal manipulation within the
13310      constant folder, in order to find the simplest representation of
13311      the arguments so that their form can be studied.  In any cases,
13312      the appropriate type conversions should be put back in the tree
13313      that will get out of the constant folder.  */
13314   if (op0)
13315     {
13316       arg0 = op0;
13317       STRIP_NOPS (arg0);
13318     }
13319
13320   if (op1)
13321     {
13322       arg1 = op1;
13323       STRIP_NOPS (arg1);
13324     }
13325
13326   if (op2)
13327     {
13328       arg2 = op2;
13329       STRIP_NOPS (arg2);
13330     }
13331
13332   switch (code)
13333     {
13334     case COMPONENT_REF:
13335       if (TREE_CODE (arg0) == CONSTRUCTOR
13336           && ! type_contains_placeholder_p (TREE_TYPE (arg0)))
13337         {
13338           unsigned HOST_WIDE_INT idx;
13339           tree field, value;
13340           FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg0), idx, field, value)
13341             if (field == arg1)
13342               return value;
13343         }
13344       return NULL_TREE;
13345
13346     case COND_EXPR:
13347     case VEC_COND_EXPR:
13348       /* Pedantic ANSI C says that a conditional expression is never an lvalue,
13349          so all simple results must be passed through pedantic_non_lvalue.  */
13350       if (TREE_CODE (arg0) == INTEGER_CST)
13351         {
13352           tree unused_op = integer_zerop (arg0) ? op1 : op2;
13353           tem = integer_zerop (arg0) ? op2 : op1;
13354           /* Only optimize constant conditions when the selected branch
13355              has the same type as the COND_EXPR.  This avoids optimizing
13356              away "c ? x : throw", where the throw has a void type.
13357              Avoid throwing away that operand which contains label.  */
13358           if ((!TREE_SIDE_EFFECTS (unused_op)
13359                || !contains_label_p (unused_op))
13360               && (! VOID_TYPE_P (TREE_TYPE (tem))
13361                   || VOID_TYPE_P (type)))
13362             return pedantic_non_lvalue_loc (loc, tem);
13363           return NULL_TREE;
13364         }
13365       else if (TREE_CODE (arg0) == VECTOR_CST)
13366         {
13367           if ((TREE_CODE (arg1) == VECTOR_CST
13368                || TREE_CODE (arg1) == CONSTRUCTOR)
13369               && (TREE_CODE (arg2) == VECTOR_CST
13370                   || TREE_CODE (arg2) == CONSTRUCTOR))
13371             {
13372               unsigned int nelts = TYPE_VECTOR_SUBPARTS (type), i;
13373               unsigned char *sel = XALLOCAVEC (unsigned char, nelts);
13374               gcc_assert (nelts == VECTOR_CST_NELTS (arg0));
13375               for (i = 0; i < nelts; i++)
13376                 {
13377                   tree val = VECTOR_CST_ELT (arg0, i);
13378                   if (integer_all_onesp (val))
13379                     sel[i] = i;
13380                   else if (integer_zerop (val))
13381                     sel[i] = nelts + i;
13382                   else /* Currently unreachable.  */
13383                     return NULL_TREE;
13384                 }
13385               tree t = fold_vec_perm (type, arg1, arg2, sel);
13386               if (t != NULL_TREE)
13387                 return t;
13388             }
13389         }
13390
13391       /* If we have A op B ? A : C, we may be able to convert this to a
13392          simpler expression, depending on the operation and the values
13393          of B and C.  Signed zeros prevent all of these transformations,
13394          for reasons given above each one.
13395
13396          Also try swapping the arguments and inverting the conditional.  */
13397       if (COMPARISON_CLASS_P (arg0)
13398           && operand_equal_for_comparison_p (TREE_OPERAND (arg0, 0),
13399                                              arg1, TREE_OPERAND (arg0, 1))
13400           && !HONOR_SIGNED_ZEROS (element_mode (arg1)))
13401         {
13402           tem = fold_cond_expr_with_comparison (loc, type, arg0, op1, op2);
13403           if (tem)
13404             return tem;
13405         }
13406
13407       if (COMPARISON_CLASS_P (arg0)
13408           && operand_equal_for_comparison_p (TREE_OPERAND (arg0, 0),
13409                                              op2,
13410                                              TREE_OPERAND (arg0, 1))
13411           && !HONOR_SIGNED_ZEROS (element_mode (op2)))
13412         {
13413           location_t loc0 = expr_location_or (arg0, loc);
13414           tem = fold_invert_truthvalue (loc0, arg0);
13415           if (tem && COMPARISON_CLASS_P (tem))
13416             {
13417               tem = fold_cond_expr_with_comparison (loc, type, tem, op2, op1);
13418               if (tem)
13419                 return tem;
13420             }
13421         }
13422
13423       /* If the second operand is simpler than the third, swap them
13424          since that produces better jump optimization results.  */
13425       if (truth_value_p (TREE_CODE (arg0))
13426           && tree_swap_operands_p (op1, op2, false))
13427         {
13428           location_t loc0 = expr_location_or (arg0, loc);
13429           /* See if this can be inverted.  If it can't, possibly because
13430              it was a floating-point inequality comparison, don't do
13431              anything.  */
13432           tem = fold_invert_truthvalue (loc0, arg0);
13433           if (tem)
13434             return fold_build3_loc (loc, code, type, tem, op2, op1);
13435         }
13436
13437       /* Convert A ? 1 : 0 to simply A.  */
13438       if ((code == VEC_COND_EXPR ? integer_all_onesp (op1)
13439                                  : (integer_onep (op1)
13440                                     && !VECTOR_TYPE_P (type)))
13441           && integer_zerop (op2)
13442           /* If we try to convert OP0 to our type, the
13443              call to fold will try to move the conversion inside
13444              a COND, which will recurse.  In that case, the COND_EXPR
13445              is probably the best choice, so leave it alone.  */
13446           && type == TREE_TYPE (arg0))
13447         return pedantic_non_lvalue_loc (loc, arg0);
13448
13449       /* Convert A ? 0 : 1 to !A.  This prefers the use of NOT_EXPR
13450          over COND_EXPR in cases such as floating point comparisons.  */
13451       if (integer_zerop (op1)
13452           && (code == VEC_COND_EXPR ? integer_all_onesp (op2)
13453                                     : (integer_onep (op2)
13454                                        && !VECTOR_TYPE_P (type)))
13455           && truth_value_p (TREE_CODE (arg0)))
13456         return pedantic_non_lvalue_loc (loc,
13457                                     fold_convert_loc (loc, type,
13458                                               invert_truthvalue_loc (loc,
13459                                                                      arg0)));
13460
13461       /* A < 0 ? <sign bit of A> : 0 is simply (A & <sign bit of A>).  */
13462       if (TREE_CODE (arg0) == LT_EXPR
13463           && integer_zerop (TREE_OPERAND (arg0, 1))
13464           && integer_zerop (op2)
13465           && (tem = sign_bit_p (TREE_OPERAND (arg0, 0), arg1)))
13466         {
13467           /* sign_bit_p looks through both zero and sign extensions,
13468              but for this optimization only sign extensions are
13469              usable.  */
13470           tree tem2 = TREE_OPERAND (arg0, 0);
13471           while (tem != tem2)
13472             {
13473               if (TREE_CODE (tem2) != NOP_EXPR
13474                   || TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (tem2, 0))))
13475                 {
13476                   tem = NULL_TREE;
13477                   break;
13478                 }
13479               tem2 = TREE_OPERAND (tem2, 0);
13480             }
13481           /* sign_bit_p only checks ARG1 bits within A's precision.
13482              If <sign bit of A> has wider type than A, bits outside
13483              of A's precision in <sign bit of A> need to be checked.
13484              If they are all 0, this optimization needs to be done
13485              in unsigned A's type, if they are all 1 in signed A's type,
13486              otherwise this can't be done.  */
13487           if (tem
13488               && TYPE_PRECISION (TREE_TYPE (tem))
13489                  < TYPE_PRECISION (TREE_TYPE (arg1))
13490               && TYPE_PRECISION (TREE_TYPE (tem))
13491                  < TYPE_PRECISION (type))
13492             {
13493               int inner_width, outer_width;
13494               tree tem_type;
13495
13496               inner_width = TYPE_PRECISION (TREE_TYPE (tem));
13497               outer_width = TYPE_PRECISION (TREE_TYPE (arg1));
13498               if (outer_width > TYPE_PRECISION (type))
13499                 outer_width = TYPE_PRECISION (type);
13500
13501               wide_int mask = wi::shifted_mask
13502                 (inner_width, outer_width - inner_width, false,
13503                  TYPE_PRECISION (TREE_TYPE (arg1)));
13504
13505               wide_int common = mask & arg1;
13506               if (common == mask)
13507                 {
13508                   tem_type = signed_type_for (TREE_TYPE (tem));
13509                   tem = fold_convert_loc (loc, tem_type, tem);
13510                 }
13511               else if (common == 0)
13512                 {
13513                   tem_type = unsigned_type_for (TREE_TYPE (tem));
13514                   tem = fold_convert_loc (loc, tem_type, tem);
13515                 }
13516               else
13517                 tem = NULL;
13518             }
13519
13520           if (tem)
13521             return
13522               fold_convert_loc (loc, type,
13523                                 fold_build2_loc (loc, BIT_AND_EXPR,
13524                                              TREE_TYPE (tem), tem,
13525                                              fold_convert_loc (loc,
13526                                                                TREE_TYPE (tem),
13527                                                                arg1)));
13528         }
13529
13530       /* (A >> N) & 1 ? (1 << N) : 0 is simply A & (1 << N).  A & 1 was
13531          already handled above.  */
13532       if (TREE_CODE (arg0) == BIT_AND_EXPR
13533           && integer_onep (TREE_OPERAND (arg0, 1))
13534           && integer_zerop (op2)
13535           && integer_pow2p (arg1))
13536         {
13537           tree tem = TREE_OPERAND (arg0, 0);
13538           STRIP_NOPS (tem);
13539           if (TREE_CODE (tem) == RSHIFT_EXPR
13540               && tree_fits_uhwi_p (TREE_OPERAND (tem, 1))
13541               && (unsigned HOST_WIDE_INT) tree_log2 (arg1) ==
13542                  tree_to_uhwi (TREE_OPERAND (tem, 1)))
13543             return fold_build2_loc (loc, BIT_AND_EXPR, type,
13544                                 TREE_OPERAND (tem, 0), arg1);
13545         }
13546
13547       /* A & N ? N : 0 is simply A & N if N is a power of two.  This
13548          is probably obsolete because the first operand should be a
13549          truth value (that's why we have the two cases above), but let's
13550          leave it in until we can confirm this for all front-ends.  */
13551       if (integer_zerop (op2)
13552           && TREE_CODE (arg0) == NE_EXPR
13553           && integer_zerop (TREE_OPERAND (arg0, 1))
13554           && integer_pow2p (arg1)
13555           && TREE_CODE (TREE_OPERAND (arg0, 0)) == BIT_AND_EXPR
13556           && operand_equal_p (TREE_OPERAND (TREE_OPERAND (arg0, 0), 1),
13557                               arg1, OEP_ONLY_CONST))
13558         return pedantic_non_lvalue_loc (loc,
13559                                     fold_convert_loc (loc, type,
13560                                                       TREE_OPERAND (arg0, 0)));
13561
13562       /* Disable the transformations below for vectors, since
13563          fold_binary_op_with_conditional_arg may undo them immediately,
13564          yielding an infinite loop.  */
13565       if (code == VEC_COND_EXPR)
13566         return NULL_TREE;
13567
13568       /* Convert A ? B : 0 into A && B if A and B are truth values.  */
13569       if (integer_zerop (op2)
13570           && truth_value_p (TREE_CODE (arg0))
13571           && truth_value_p (TREE_CODE (arg1))
13572           && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
13573         return fold_build2_loc (loc, code == VEC_COND_EXPR ? BIT_AND_EXPR
13574                                                            : TRUTH_ANDIF_EXPR,
13575                                 type, fold_convert_loc (loc, type, arg0), arg1);
13576
13577       /* Convert A ? B : 1 into !A || B if A and B are truth values.  */
13578       if (code == VEC_COND_EXPR ? integer_all_onesp (op2) : integer_onep (op2)
13579           && truth_value_p (TREE_CODE (arg0))
13580           && truth_value_p (TREE_CODE (arg1))
13581           && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
13582         {
13583           location_t loc0 = expr_location_or (arg0, loc);
13584           /* Only perform transformation if ARG0 is easily inverted.  */
13585           tem = fold_invert_truthvalue (loc0, arg0);
13586           if (tem)
13587             return fold_build2_loc (loc, code == VEC_COND_EXPR
13588                                          ? BIT_IOR_EXPR
13589                                          : TRUTH_ORIF_EXPR,
13590                                     type, fold_convert_loc (loc, type, tem),
13591                                     arg1);
13592         }
13593
13594       /* Convert A ? 0 : B into !A && B if A and B are truth values.  */
13595       if (integer_zerop (arg1)
13596           && truth_value_p (TREE_CODE (arg0))
13597           && truth_value_p (TREE_CODE (op2))
13598           && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
13599         {
13600           location_t loc0 = expr_location_or (arg0, loc);
13601           /* Only perform transformation if ARG0 is easily inverted.  */
13602           tem = fold_invert_truthvalue (loc0, arg0);
13603           if (tem)
13604             return fold_build2_loc (loc, code == VEC_COND_EXPR
13605                                          ? BIT_AND_EXPR : TRUTH_ANDIF_EXPR,
13606                                     type, fold_convert_loc (loc, type, tem),
13607                                     op2);
13608         }
13609
13610       /* Convert A ? 1 : B into A || B if A and B are truth values.  */
13611       if (code == VEC_COND_EXPR ? integer_all_onesp (arg1) : integer_onep (arg1)
13612           && truth_value_p (TREE_CODE (arg0))
13613           && truth_value_p (TREE_CODE (op2))
13614           && (code == VEC_COND_EXPR || !VECTOR_TYPE_P (type)))
13615         return fold_build2_loc (loc, code == VEC_COND_EXPR
13616                                      ? BIT_IOR_EXPR : TRUTH_ORIF_EXPR,
13617                                 type, fold_convert_loc (loc, type, arg0), op2);
13618
13619       return NULL_TREE;
13620
13621     case CALL_EXPR:
13622       /* CALL_EXPRs used to be ternary exprs.  Catch any mistaken uses
13623          of fold_ternary on them.  */
13624       gcc_unreachable ();
13625
13626     case BIT_FIELD_REF:
13627       if ((TREE_CODE (arg0) == VECTOR_CST
13628            || (TREE_CODE (arg0) == CONSTRUCTOR
13629                && TREE_CODE (TREE_TYPE (arg0)) == VECTOR_TYPE))
13630           && (type == TREE_TYPE (TREE_TYPE (arg0))
13631               || (TREE_CODE (type) == VECTOR_TYPE
13632                   && TREE_TYPE (type) == TREE_TYPE (TREE_TYPE (arg0)))))
13633         {
13634           tree eltype = TREE_TYPE (TREE_TYPE (arg0));
13635           unsigned HOST_WIDE_INT width = tree_to_uhwi (TYPE_SIZE (eltype));
13636           unsigned HOST_WIDE_INT n = tree_to_uhwi (arg1);
13637           unsigned HOST_WIDE_INT idx = tree_to_uhwi (op2);
13638
13639           if (n != 0
13640               && (idx % width) == 0
13641               && (n % width) == 0
13642               && ((idx + n) / width) <= TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0)))
13643             {
13644               idx = idx / width;
13645               n = n / width;
13646
13647               if (TREE_CODE (arg0) == VECTOR_CST)
13648                 {
13649                   if (n == 1)
13650                     return VECTOR_CST_ELT (arg0, idx);
13651
13652                   tree *vals = XALLOCAVEC (tree, n);
13653                   for (unsigned i = 0; i < n; ++i)
13654                     vals[i] = VECTOR_CST_ELT (arg0, idx + i);
13655                   return build_vector (type, vals);
13656                 }
13657
13658               /* Constructor elements can be subvectors.  */
13659               unsigned HOST_WIDE_INT k = 1;
13660               if (CONSTRUCTOR_NELTS (arg0) != 0)
13661                 {
13662                   tree cons_elem = TREE_TYPE (CONSTRUCTOR_ELT (arg0, 0)->value);
13663                   if (TREE_CODE (cons_elem) == VECTOR_TYPE)
13664                     k = TYPE_VECTOR_SUBPARTS (cons_elem);
13665                 }
13666
13667               /* We keep an exact subset of the constructor elements.  */
13668               if ((idx % k) == 0 && (n % k) == 0)
13669                 {
13670                   if (CONSTRUCTOR_NELTS (arg0) == 0)
13671                     return build_constructor (type, NULL);
13672                   idx /= k;
13673                   n /= k;
13674                   if (n == 1)
13675                     {
13676                       if (idx < CONSTRUCTOR_NELTS (arg0))
13677                         return CONSTRUCTOR_ELT (arg0, idx)->value;
13678                       return build_zero_cst (type);
13679                     }
13680
13681                   vec<constructor_elt, va_gc> *vals;
13682                   vec_alloc (vals, n);
13683                   for (unsigned i = 0;
13684                        i < n && idx + i < CONSTRUCTOR_NELTS (arg0);
13685                        ++i)
13686                     CONSTRUCTOR_APPEND_ELT (vals, NULL_TREE,
13687                                             CONSTRUCTOR_ELT
13688                                               (arg0, idx + i)->value);
13689                   return build_constructor (type, vals);
13690                 }
13691               /* The bitfield references a single constructor element.  */
13692               else if (idx + n <= (idx / k + 1) * k)
13693                 {
13694                   if (CONSTRUCTOR_NELTS (arg0) <= idx / k)
13695                     return build_zero_cst (type);
13696                   else if (n == k)
13697                     return CONSTRUCTOR_ELT (arg0, idx / k)->value;
13698                   else
13699                     return fold_build3_loc (loc, code, type,
13700                       CONSTRUCTOR_ELT (arg0, idx / k)->value, op1,
13701                       build_int_cst (TREE_TYPE (op2), (idx % k) * width));
13702                 }
13703             }
13704         }
13705
13706       /* A bit-field-ref that referenced the full argument can be stripped.  */
13707       if (INTEGRAL_TYPE_P (TREE_TYPE (arg0))
13708           && TYPE_PRECISION (TREE_TYPE (arg0)) == tree_to_uhwi (arg1)
13709           && integer_zerop (op2))
13710         return fold_convert_loc (loc, type, arg0);
13711
13712       /* On constants we can use native encode/interpret to constant
13713          fold (nearly) all BIT_FIELD_REFs.  */
13714       if (CONSTANT_CLASS_P (arg0)
13715           && can_native_interpret_type_p (type)
13716           && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (arg0)))
13717           /* This limitation should not be necessary, we just need to
13718              round this up to mode size.  */
13719           && tree_to_uhwi (op1) % BITS_PER_UNIT == 0
13720           /* Need bit-shifting of the buffer to relax the following.  */
13721           && tree_to_uhwi (op2) % BITS_PER_UNIT == 0)
13722         {
13723           unsigned HOST_WIDE_INT bitpos = tree_to_uhwi (op2);
13724           unsigned HOST_WIDE_INT bitsize = tree_to_uhwi (op1);
13725           unsigned HOST_WIDE_INT clen;
13726           clen = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (arg0)));
13727           /* ???  We cannot tell native_encode_expr to start at
13728              some random byte only.  So limit us to a reasonable amount
13729              of work.  */
13730           if (clen <= 4096)
13731             {
13732               unsigned char *b = XALLOCAVEC (unsigned char, clen);
13733               unsigned HOST_WIDE_INT len = native_encode_expr (arg0, b, clen);
13734               if (len > 0
13735                   && len * BITS_PER_UNIT >= bitpos + bitsize)
13736                 {
13737                   tree v = native_interpret_expr (type,
13738                                                   b + bitpos / BITS_PER_UNIT,
13739                                                   bitsize / BITS_PER_UNIT);
13740                   if (v)
13741                     return v;
13742                 }
13743             }
13744         }
13745
13746       return NULL_TREE;
13747
13748     case FMA_EXPR:
13749       /* For integers we can decompose the FMA if possible.  */
13750       if (TREE_CODE (arg0) == INTEGER_CST
13751           && TREE_CODE (arg1) == INTEGER_CST)
13752         return fold_build2_loc (loc, PLUS_EXPR, type,
13753                                 const_binop (MULT_EXPR, arg0, arg1), arg2);
13754       if (integer_zerop (arg2))
13755         return fold_build2_loc (loc, MULT_EXPR, type, arg0, arg1);
13756
13757       return fold_fma (loc, type, arg0, arg1, arg2);
13758
13759     case VEC_PERM_EXPR:
13760       if (TREE_CODE (arg2) == VECTOR_CST)
13761         {
13762           unsigned int nelts = TYPE_VECTOR_SUBPARTS (type), i, mask, mask2;
13763           unsigned char *sel = XALLOCAVEC (unsigned char, 2 * nelts);
13764           unsigned char *sel2 = sel + nelts;
13765           bool need_mask_canon = false;
13766           bool need_mask_canon2 = false;
13767           bool all_in_vec0 = true;
13768           bool all_in_vec1 = true;
13769           bool maybe_identity = true;
13770           bool single_arg = (op0 == op1);
13771           bool changed = false;
13772
13773           mask2 = 2 * nelts - 1;
13774           mask = single_arg ? (nelts - 1) : mask2;
13775           gcc_assert (nelts == VECTOR_CST_NELTS (arg2));
13776           for (i = 0; i < nelts; i++)
13777             {
13778               tree val = VECTOR_CST_ELT (arg2, i);
13779               if (TREE_CODE (val) != INTEGER_CST)
13780                 return NULL_TREE;
13781
13782               /* Make sure that the perm value is in an acceptable
13783                  range.  */
13784               wide_int t = val;
13785               need_mask_canon |= wi::gtu_p (t, mask);
13786               need_mask_canon2 |= wi::gtu_p (t, mask2);
13787               sel[i] = t.to_uhwi () & mask;
13788               sel2[i] = t.to_uhwi () & mask2;
13789
13790               if (sel[i] < nelts)
13791                 all_in_vec1 = false;
13792               else
13793                 all_in_vec0 = false;
13794
13795               if ((sel[i] & (nelts-1)) != i)
13796                 maybe_identity = false;
13797             }
13798
13799           if (maybe_identity)
13800             {
13801               if (all_in_vec0)
13802                 return op0;
13803               if (all_in_vec1)
13804                 return op1;
13805             }
13806
13807           if (all_in_vec0)
13808             op1 = op0;
13809           else if (all_in_vec1)
13810             {
13811               op0 = op1;
13812               for (i = 0; i < nelts; i++)
13813                 sel[i] -= nelts;
13814               need_mask_canon = true;
13815             }
13816
13817           if ((TREE_CODE (op0) == VECTOR_CST
13818                || TREE_CODE (op0) == CONSTRUCTOR)
13819               && (TREE_CODE (op1) == VECTOR_CST
13820                   || TREE_CODE (op1) == CONSTRUCTOR))
13821             {
13822               tree t = fold_vec_perm (type, op0, op1, sel);
13823               if (t != NULL_TREE)
13824                 return t;
13825             }
13826
13827           if (op0 == op1 && !single_arg)
13828             changed = true;
13829
13830           /* Some targets are deficient and fail to expand a single
13831              argument permutation while still allowing an equivalent
13832              2-argument version.  */
13833           if (need_mask_canon && arg2 == op2
13834               && !can_vec_perm_p (TYPE_MODE (type), false, sel)
13835               && can_vec_perm_p (TYPE_MODE (type), false, sel2))
13836             {
13837               need_mask_canon = need_mask_canon2;
13838               sel = sel2;
13839             }
13840
13841           if (need_mask_canon && arg2 == op2)
13842             {
13843               tree *tsel = XALLOCAVEC (tree, nelts);
13844               tree eltype = TREE_TYPE (TREE_TYPE (arg2));
13845               for (i = 0; i < nelts; i++)
13846                 tsel[i] = build_int_cst (eltype, sel[i]);
13847               op2 = build_vector (TREE_TYPE (arg2), tsel);
13848               changed = true;
13849             }
13850
13851           if (changed)
13852             return build3_loc (loc, VEC_PERM_EXPR, type, op0, op1, op2);
13853         }
13854       return NULL_TREE;
13855
13856     default:
13857       return NULL_TREE;
13858     } /* switch (code) */
13859 }
13860
13861 /* Perform constant folding and related simplification of EXPR.
13862    The related simplifications include x*1 => x, x*0 => 0, etc.,
13863    and application of the associative law.
13864    NOP_EXPR conversions may be removed freely (as long as we
13865    are careful not to change the type of the overall expression).
13866    We cannot simplify through a CONVERT_EXPR, FIX_EXPR or FLOAT_EXPR,
13867    but we can constant-fold them if they have constant operands.  */
13868
13869 #ifdef ENABLE_FOLD_CHECKING
13870 # define fold(x) fold_1 (x)
13871 static tree fold_1 (tree);
13872 static
13873 #endif
13874 tree
13875 fold (tree expr)
13876 {
13877   const tree t = expr;
13878   enum tree_code code = TREE_CODE (t);
13879   enum tree_code_class kind = TREE_CODE_CLASS (code);
13880   tree tem;
13881   location_t loc = EXPR_LOCATION (expr);
13882
13883   /* Return right away if a constant.  */
13884   if (kind == tcc_constant)
13885     return t;
13886
13887   /* CALL_EXPR-like objects with variable numbers of operands are
13888      treated specially.  */
13889   if (kind == tcc_vl_exp)
13890     {
13891       if (code == CALL_EXPR)
13892         {
13893           tem = fold_call_expr (loc, expr, false);
13894           return tem ? tem : expr;
13895         }
13896       return expr;
13897     }
13898
13899   if (IS_EXPR_CODE_CLASS (kind))
13900     {
13901       tree type = TREE_TYPE (t);
13902       tree op0, op1, op2;
13903
13904       switch (TREE_CODE_LENGTH (code))
13905         {
13906         case 1:
13907           op0 = TREE_OPERAND (t, 0);
13908           tem = fold_unary_loc (loc, code, type, op0);
13909           return tem ? tem : expr;
13910         case 2:
13911           op0 = TREE_OPERAND (t, 0);
13912           op1 = TREE_OPERAND (t, 1);
13913           tem = fold_binary_loc (loc, code, type, op0, op1);
13914           return tem ? tem : expr;
13915         case 3:
13916           op0 = TREE_OPERAND (t, 0);
13917           op1 = TREE_OPERAND (t, 1);
13918           op2 = TREE_OPERAND (t, 2);
13919           tem = fold_ternary_loc (loc, code, type, op0, op1, op2);
13920           return tem ? tem : expr;
13921         default:
13922           break;
13923         }
13924     }
13925
13926   switch (code)
13927     {
13928     case ARRAY_REF:
13929       {
13930         tree op0 = TREE_OPERAND (t, 0);
13931         tree op1 = TREE_OPERAND (t, 1);
13932
13933         if (TREE_CODE (op1) == INTEGER_CST
13934             && TREE_CODE (op0) == CONSTRUCTOR
13935             && ! type_contains_placeholder_p (TREE_TYPE (op0)))
13936           {
13937             vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (op0);
13938             unsigned HOST_WIDE_INT end = vec_safe_length (elts);
13939             unsigned HOST_WIDE_INT begin = 0;
13940
13941             /* Find a matching index by means of a binary search.  */
13942             while (begin != end)
13943               {
13944                 unsigned HOST_WIDE_INT middle = (begin + end) / 2;
13945                 tree index = (*elts)[middle].index;
13946
13947                 if (TREE_CODE (index) == INTEGER_CST
13948                     && tree_int_cst_lt (index, op1))
13949                   begin = middle + 1;
13950                 else if (TREE_CODE (index) == INTEGER_CST
13951                          && tree_int_cst_lt (op1, index))
13952                   end = middle;
13953                 else if (TREE_CODE (index) == RANGE_EXPR
13954                          && tree_int_cst_lt (TREE_OPERAND (index, 1), op1))
13955                   begin = middle + 1;
13956                 else if (TREE_CODE (index) == RANGE_EXPR
13957                          && tree_int_cst_lt (op1, TREE_OPERAND (index, 0)))
13958                   end = middle;
13959                 else
13960                   return (*elts)[middle].value;
13961               }
13962           }
13963
13964         return t;
13965       }
13966
13967       /* Return a VECTOR_CST if possible.  */
13968     case CONSTRUCTOR:
13969       {
13970         tree type = TREE_TYPE (t);
13971         if (TREE_CODE (type) != VECTOR_TYPE)
13972           return t;
13973
13974         tree *vec = XALLOCAVEC (tree, TYPE_VECTOR_SUBPARTS (type));
13975         unsigned HOST_WIDE_INT idx, pos = 0;
13976         tree value;
13977
13978         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (t), idx, value)
13979           {
13980             if (!CONSTANT_CLASS_P (value))
13981               return t;
13982             if (TREE_CODE (value) == VECTOR_CST)
13983               {
13984                 for (unsigned i = 0; i < VECTOR_CST_NELTS (value); ++i)
13985                   vec[pos++] = VECTOR_CST_ELT (value, i);
13986               }
13987             else
13988               vec[pos++] = value;
13989           }
13990         for (; pos < TYPE_VECTOR_SUBPARTS (type); ++pos)
13991           vec[pos] = build_zero_cst (TREE_TYPE (type));
13992
13993         return build_vector (type, vec);
13994       }
13995
13996     case CONST_DECL:
13997       return fold (DECL_INITIAL (t));
13998
13999     default:
14000       return t;
14001     } /* switch (code) */
14002 }
14003
14004 #ifdef ENABLE_FOLD_CHECKING
14005 #undef fold
14006
14007 static void fold_checksum_tree (const_tree, struct md5_ctx *,
14008                                 hash_table<pointer_hash<const tree_node> > *);
14009 static void fold_check_failed (const_tree, const_tree);
14010 void print_fold_checksum (const_tree);
14011
14012 /* When --enable-checking=fold, compute a digest of expr before
14013    and after actual fold call to see if fold did not accidentally
14014    change original expr.  */
14015
14016 tree
14017 fold (tree expr)
14018 {
14019   tree ret;
14020   struct md5_ctx ctx;
14021   unsigned char checksum_before[16], checksum_after[16];
14022   hash_table<pointer_hash<const tree_node> > ht (32);
14023
14024   md5_init_ctx (&ctx);
14025   fold_checksum_tree (expr, &ctx, &ht);
14026   md5_finish_ctx (&ctx, checksum_before);
14027   ht.empty ();
14028
14029   ret = fold_1 (expr);
14030
14031   md5_init_ctx (&ctx);
14032   fold_checksum_tree (expr, &ctx, &ht);
14033   md5_finish_ctx (&ctx, checksum_after);
14034
14035   if (memcmp (checksum_before, checksum_after, 16))
14036     fold_check_failed (expr, ret);
14037
14038   return ret;
14039 }
14040
14041 void
14042 print_fold_checksum (const_tree expr)
14043 {
14044   struct md5_ctx ctx;
14045   unsigned char checksum[16], cnt;
14046   hash_table<pointer_hash<const tree_node> > ht (32);
14047
14048   md5_init_ctx (&ctx);
14049   fold_checksum_tree (expr, &ctx, &ht);
14050   md5_finish_ctx (&ctx, checksum);
14051   for (cnt = 0; cnt < 16; ++cnt)
14052     fprintf (stderr, "%02x", checksum[cnt]);
14053   putc ('\n', stderr);
14054 }
14055
14056 static void
14057 fold_check_failed (const_tree expr ATTRIBUTE_UNUSED, const_tree ret ATTRIBUTE_UNUSED)
14058 {
14059   internal_error ("fold check: original tree changed by fold");
14060 }
14061
14062 static void
14063 fold_checksum_tree (const_tree expr, struct md5_ctx *ctx,
14064                     hash_table<pointer_hash <const tree_node> > *ht)
14065 {
14066   const tree_node **slot;
14067   enum tree_code code;
14068   union tree_node buf;
14069   int i, len;
14070
14071  recursive_label:
14072   if (expr == NULL)
14073     return;
14074   slot = ht->find_slot (expr, INSERT);
14075   if (*slot != NULL)
14076     return;
14077   *slot = expr;
14078   code = TREE_CODE (expr);
14079   if (TREE_CODE_CLASS (code) == tcc_declaration
14080       && HAS_DECL_ASSEMBLER_NAME_P (expr))
14081     {
14082       /* Allow DECL_ASSEMBLER_NAME and symtab_node to be modified.  */
14083       memcpy ((char *) &buf, expr, tree_size (expr));
14084       SET_DECL_ASSEMBLER_NAME ((tree)&buf, NULL);
14085       buf.decl_with_vis.symtab_node = NULL;
14086       expr = (tree) &buf;
14087     }
14088   else if (TREE_CODE_CLASS (code) == tcc_type
14089            && (TYPE_POINTER_TO (expr)
14090                || TYPE_REFERENCE_TO (expr)
14091                || TYPE_CACHED_VALUES_P (expr)
14092                || TYPE_CONTAINS_PLACEHOLDER_INTERNAL (expr)
14093                || TYPE_NEXT_VARIANT (expr)))
14094     {
14095       /* Allow these fields to be modified.  */
14096       tree tmp;
14097       memcpy ((char *) &buf, expr, tree_size (expr));
14098       expr = tmp = (tree) &buf;
14099       TYPE_CONTAINS_PLACEHOLDER_INTERNAL (tmp) = 0;
14100       TYPE_POINTER_TO (tmp) = NULL;
14101       TYPE_REFERENCE_TO (tmp) = NULL;
14102       TYPE_NEXT_VARIANT (tmp) = NULL;
14103       if (TYPE_CACHED_VALUES_P (tmp))
14104         {
14105           TYPE_CACHED_VALUES_P (tmp) = 0;
14106           TYPE_CACHED_VALUES (tmp) = NULL;
14107         }
14108     }
14109   md5_process_bytes (expr, tree_size (expr), ctx);
14110   if (CODE_CONTAINS_STRUCT (code, TS_TYPED))
14111     fold_checksum_tree (TREE_TYPE (expr), ctx, ht);
14112   if (TREE_CODE_CLASS (code) != tcc_type
14113       && TREE_CODE_CLASS (code) != tcc_declaration
14114       && code != TREE_LIST
14115       && code != SSA_NAME
14116       && CODE_CONTAINS_STRUCT (code, TS_COMMON))
14117     fold_checksum_tree (TREE_CHAIN (expr), ctx, ht);
14118   switch (TREE_CODE_CLASS (code))
14119     {
14120     case tcc_constant:
14121       switch (code)
14122         {
14123         case STRING_CST:
14124           md5_process_bytes (TREE_STRING_POINTER (expr),
14125                              TREE_STRING_LENGTH (expr), ctx);
14126           break;
14127         case COMPLEX_CST:
14128           fold_checksum_tree (TREE_REALPART (expr), ctx, ht);
14129           fold_checksum_tree (TREE_IMAGPART (expr), ctx, ht);
14130           break;
14131         case VECTOR_CST:
14132           for (i = 0; i < (int) VECTOR_CST_NELTS (expr); ++i)
14133             fold_checksum_tree (VECTOR_CST_ELT (expr, i), ctx, ht);
14134           break;
14135         default:
14136           break;
14137         }
14138       break;
14139     case tcc_exceptional:
14140       switch (code)
14141         {
14142         case TREE_LIST:
14143           fold_checksum_tree (TREE_PURPOSE (expr), ctx, ht);
14144           fold_checksum_tree (TREE_VALUE (expr), ctx, ht);
14145           expr = TREE_CHAIN (expr);
14146           goto recursive_label;
14147           break;
14148         case TREE_VEC:
14149           for (i = 0; i < TREE_VEC_LENGTH (expr); ++i)
14150             fold_checksum_tree (TREE_VEC_ELT (expr, i), ctx, ht);
14151           break;
14152         default:
14153           break;
14154         }
14155       break;
14156     case tcc_expression:
14157     case tcc_reference:
14158     case tcc_comparison:
14159     case tcc_unary:
14160     case tcc_binary:
14161     case tcc_statement:
14162     case tcc_vl_exp:
14163       len = TREE_OPERAND_LENGTH (expr);
14164       for (i = 0; i < len; ++i)
14165         fold_checksum_tree (TREE_OPERAND (expr, i), ctx, ht);
14166       break;
14167     case tcc_declaration:
14168       fold_checksum_tree (DECL_NAME (expr), ctx, ht);
14169       fold_checksum_tree (DECL_CONTEXT (expr), ctx, ht);
14170       if (CODE_CONTAINS_STRUCT (TREE_CODE (expr), TS_DECL_COMMON))
14171         {
14172           fold_checksum_tree (DECL_SIZE (expr), ctx, ht);
14173           fold_checksum_tree (DECL_SIZE_UNIT (expr), ctx, ht);
14174           fold_checksum_tree (DECL_INITIAL (expr), ctx, ht);
14175           fold_checksum_tree (DECL_ABSTRACT_ORIGIN (expr), ctx, ht);
14176           fold_checksum_tree (DECL_ATTRIBUTES (expr), ctx, ht);
14177         }
14178
14179       if (CODE_CONTAINS_STRUCT (TREE_CODE (expr), TS_DECL_NON_COMMON))
14180         {
14181           if (TREE_CODE (expr) == FUNCTION_DECL)
14182             {
14183               fold_checksum_tree (DECL_VINDEX (expr), ctx, ht);
14184               fold_checksum_tree (DECL_ARGUMENTS (expr), ctx, ht);
14185             }
14186           fold_checksum_tree (DECL_RESULT_FLD (expr), ctx, ht);
14187         }
14188       break;
14189     case tcc_type:
14190       if (TREE_CODE (expr) == ENUMERAL_TYPE)
14191         fold_checksum_tree (TYPE_VALUES (expr), ctx, ht);
14192       fold_checksum_tree (TYPE_SIZE (expr), ctx, ht);
14193       fold_checksum_tree (TYPE_SIZE_UNIT (expr), ctx, ht);
14194       fold_checksum_tree (TYPE_ATTRIBUTES (expr), ctx, ht);
14195       fold_checksum_tree (TYPE_NAME (expr), ctx, ht);
14196       if (INTEGRAL_TYPE_P (expr)
14197           || SCALAR_FLOAT_TYPE_P (expr))
14198         {
14199           fold_checksum_tree (TYPE_MIN_VALUE (expr), ctx, ht);
14200           fold_checksum_tree (TYPE_MAX_VALUE (expr), ctx, ht);
14201         }
14202       fold_checksum_tree (TYPE_MAIN_VARIANT (expr), ctx, ht);
14203       if (TREE_CODE (expr) == RECORD_TYPE
14204           || TREE_CODE (expr) == UNION_TYPE
14205           || TREE_CODE (expr) == QUAL_UNION_TYPE)
14206         fold_checksum_tree (TYPE_BINFO (expr), ctx, ht);
14207       fold_checksum_tree (TYPE_CONTEXT (expr), ctx, ht);
14208       break;
14209     default:
14210       break;
14211     }
14212 }
14213
14214 /* Helper function for outputting the checksum of a tree T.  When
14215    debugging with gdb, you can "define mynext" to be "next" followed
14216    by "call debug_fold_checksum (op0)", then just trace down till the
14217    outputs differ.  */
14218
14219 DEBUG_FUNCTION void
14220 debug_fold_checksum (const_tree t)
14221 {
14222   int i;
14223   unsigned char checksum[16];
14224   struct md5_ctx ctx;
14225   hash_table<pointer_hash<const tree_node> > ht (32);
14226
14227   md5_init_ctx (&ctx);
14228   fold_checksum_tree (t, &ctx, &ht);
14229   md5_finish_ctx (&ctx, checksum);
14230   ht.empty ();
14231
14232   for (i = 0; i < 16; i++)
14233     fprintf (stderr, "%d ", checksum[i]);
14234
14235   fprintf (stderr, "\n");
14236 }
14237
14238 #endif
14239
14240 /* Fold a unary tree expression with code CODE of type TYPE with an
14241    operand OP0.  LOC is the location of the resulting expression.
14242    Return a folded expression if successful.  Otherwise, return a tree
14243    expression with code CODE of type TYPE with an operand OP0.  */
14244
14245 tree
14246 fold_build1_stat_loc (location_t loc,
14247                       enum tree_code code, tree type, tree op0 MEM_STAT_DECL)
14248 {
14249   tree tem;
14250 #ifdef ENABLE_FOLD_CHECKING
14251   unsigned char checksum_before[16], checksum_after[16];
14252   struct md5_ctx ctx;
14253   hash_table<pointer_hash<const tree_node> > ht (32);
14254
14255   md5_init_ctx (&ctx);
14256   fold_checksum_tree (op0, &ctx, &ht);
14257   md5_finish_ctx (&ctx, checksum_before);
14258   ht.empty ();
14259 #endif
14260
14261   tem = fold_unary_loc (loc, code, type, op0);
14262   if (!tem)
14263     tem = build1_stat_loc (loc, code, type, op0 PASS_MEM_STAT);
14264
14265 #ifdef ENABLE_FOLD_CHECKING
14266   md5_init_ctx (&ctx);
14267   fold_checksum_tree (op0, &ctx, &ht);
14268   md5_finish_ctx (&ctx, checksum_after);
14269
14270   if (memcmp (checksum_before, checksum_after, 16))
14271     fold_check_failed (op0, tem);
14272 #endif
14273   return tem;
14274 }
14275
14276 /* Fold a binary tree expression with code CODE of type TYPE with
14277    operands OP0 and OP1.  LOC is the location of the resulting
14278    expression.  Return a folded expression if successful.  Otherwise,
14279    return a tree expression with code CODE of type TYPE with operands
14280    OP0 and OP1.  */
14281
14282 tree
14283 fold_build2_stat_loc (location_t loc,
14284                       enum tree_code code, tree type, tree op0, tree op1
14285                       MEM_STAT_DECL)
14286 {
14287   tree tem;
14288 #ifdef ENABLE_FOLD_CHECKING
14289   unsigned char checksum_before_op0[16],
14290                 checksum_before_op1[16],
14291                 checksum_after_op0[16],
14292                 checksum_after_op1[16];
14293   struct md5_ctx ctx;
14294   hash_table<pointer_hash<const tree_node> > ht (32);
14295
14296   md5_init_ctx (&ctx);
14297   fold_checksum_tree (op0, &ctx, &ht);
14298   md5_finish_ctx (&ctx, checksum_before_op0);
14299   ht.empty ();
14300
14301   md5_init_ctx (&ctx);
14302   fold_checksum_tree (op1, &ctx, &ht);
14303   md5_finish_ctx (&ctx, checksum_before_op1);
14304   ht.empty ();
14305 #endif
14306
14307   tem = fold_binary_loc (loc, code, type, op0, op1);
14308   if (!tem)
14309     tem = build2_stat_loc (loc, code, type, op0, op1 PASS_MEM_STAT);
14310
14311 #ifdef ENABLE_FOLD_CHECKING
14312   md5_init_ctx (&ctx);
14313   fold_checksum_tree (op0, &ctx, &ht);
14314   md5_finish_ctx (&ctx, checksum_after_op0);
14315   ht.empty ();
14316
14317   if (memcmp (checksum_before_op0, checksum_after_op0, 16))
14318     fold_check_failed (op0, tem);
14319
14320   md5_init_ctx (&ctx);
14321   fold_checksum_tree (op1, &ctx, &ht);
14322   md5_finish_ctx (&ctx, checksum_after_op1);
14323
14324   if (memcmp (checksum_before_op1, checksum_after_op1, 16))
14325     fold_check_failed (op1, tem);
14326 #endif
14327   return tem;
14328 }
14329
14330 /* Fold a ternary tree expression with code CODE of type TYPE with
14331    operands OP0, OP1, and OP2.  Return a folded expression if
14332    successful.  Otherwise, return a tree expression with code CODE of
14333    type TYPE with operands OP0, OP1, and OP2.  */
14334
14335 tree
14336 fold_build3_stat_loc (location_t loc, enum tree_code code, tree type,
14337                       tree op0, tree op1, tree op2 MEM_STAT_DECL)
14338 {
14339   tree tem;
14340 #ifdef ENABLE_FOLD_CHECKING
14341   unsigned char checksum_before_op0[16],
14342                 checksum_before_op1[16],
14343                 checksum_before_op2[16],
14344                 checksum_after_op0[16],
14345                 checksum_after_op1[16],
14346                 checksum_after_op2[16];
14347   struct md5_ctx ctx;
14348   hash_table<pointer_hash<const tree_node> > ht (32);
14349
14350   md5_init_ctx (&ctx);
14351   fold_checksum_tree (op0, &ctx, &ht);
14352   md5_finish_ctx (&ctx, checksum_before_op0);
14353   ht.empty ();
14354
14355   md5_init_ctx (&ctx);
14356   fold_checksum_tree (op1, &ctx, &ht);
14357   md5_finish_ctx (&ctx, checksum_before_op1);
14358   ht.empty ();
14359
14360   md5_init_ctx (&ctx);
14361   fold_checksum_tree (op2, &ctx, &ht);
14362   md5_finish_ctx (&ctx, checksum_before_op2);
14363   ht.empty ();
14364 #endif
14365
14366   gcc_assert (TREE_CODE_CLASS (code) != tcc_vl_exp);
14367   tem = fold_ternary_loc (loc, code, type, op0, op1, op2);
14368   if (!tem)
14369     tem = build3_stat_loc (loc, code, type, op0, op1, op2 PASS_MEM_STAT);
14370
14371 #ifdef ENABLE_FOLD_CHECKING
14372   md5_init_ctx (&ctx);
14373   fold_checksum_tree (op0, &ctx, &ht);
14374   md5_finish_ctx (&ctx, checksum_after_op0);
14375   ht.empty ();
14376
14377   if (memcmp (checksum_before_op0, checksum_after_op0, 16))
14378     fold_check_failed (op0, tem);
14379
14380   md5_init_ctx (&ctx);
14381   fold_checksum_tree (op1, &ctx, &ht);
14382   md5_finish_ctx (&ctx, checksum_after_op1);
14383   ht.empty ();
14384
14385   if (memcmp (checksum_before_op1, checksum_after_op1, 16))
14386     fold_check_failed (op1, tem);
14387
14388   md5_init_ctx (&ctx);
14389   fold_checksum_tree (op2, &ctx, &ht);
14390   md5_finish_ctx (&ctx, checksum_after_op2);
14391
14392   if (memcmp (checksum_before_op2, checksum_after_op2, 16))
14393     fold_check_failed (op2, tem);
14394 #endif
14395   return tem;
14396 }
14397
14398 /* Fold a CALL_EXPR expression of type TYPE with operands FN and NARGS
14399    arguments in ARGARRAY, and a null static chain.
14400    Return a folded expression if successful.  Otherwise, return a CALL_EXPR
14401    of type TYPE from the given operands as constructed by build_call_array.  */
14402
14403 tree
14404 fold_build_call_array_loc (location_t loc, tree type, tree fn,
14405                            int nargs, tree *argarray)
14406 {
14407   tree tem;
14408 #ifdef ENABLE_FOLD_CHECKING
14409   unsigned char checksum_before_fn[16],
14410                 checksum_before_arglist[16],
14411                 checksum_after_fn[16],
14412                 checksum_after_arglist[16];
14413   struct md5_ctx ctx;
14414   hash_table<pointer_hash<const tree_node> > ht (32);
14415   int i;
14416
14417   md5_init_ctx (&ctx);
14418   fold_checksum_tree (fn, &ctx, &ht);
14419   md5_finish_ctx (&ctx, checksum_before_fn);
14420   ht.empty ();
14421
14422   md5_init_ctx (&ctx);
14423   for (i = 0; i < nargs; i++)
14424     fold_checksum_tree (argarray[i], &ctx, &ht);
14425   md5_finish_ctx (&ctx, checksum_before_arglist);
14426   ht.empty ();
14427 #endif
14428
14429   tem = fold_builtin_call_array (loc, type, fn, nargs, argarray);
14430   if (!tem)
14431     tem = build_call_array_loc (loc, type, fn, nargs, argarray);
14432
14433 #ifdef ENABLE_FOLD_CHECKING
14434   md5_init_ctx (&ctx);
14435   fold_checksum_tree (fn, &ctx, &ht);
14436   md5_finish_ctx (&ctx, checksum_after_fn);
14437   ht.empty ();
14438
14439   if (memcmp (checksum_before_fn, checksum_after_fn, 16))
14440     fold_check_failed (fn, tem);
14441
14442   md5_init_ctx (&ctx);
14443   for (i = 0; i < nargs; i++)
14444     fold_checksum_tree (argarray[i], &ctx, &ht);
14445   md5_finish_ctx (&ctx, checksum_after_arglist);
14446
14447   if (memcmp (checksum_before_arglist, checksum_after_arglist, 16))
14448     fold_check_failed (NULL_TREE, tem);
14449 #endif
14450   return tem;
14451 }
14452
14453 /* Perform constant folding and related simplification of initializer
14454    expression EXPR.  These behave identically to "fold_buildN" but ignore
14455    potential run-time traps and exceptions that fold must preserve.  */
14456
14457 #define START_FOLD_INIT \
14458   int saved_signaling_nans = flag_signaling_nans;\
14459   int saved_trapping_math = flag_trapping_math;\
14460   int saved_rounding_math = flag_rounding_math;\
14461   int saved_trapv = flag_trapv;\
14462   int saved_folding_initializer = folding_initializer;\
14463   flag_signaling_nans = 0;\
14464   flag_trapping_math = 0;\
14465   flag_rounding_math = 0;\
14466   flag_trapv = 0;\
14467   folding_initializer = 1;
14468
14469 #define END_FOLD_INIT \
14470   flag_signaling_nans = saved_signaling_nans;\
14471   flag_trapping_math = saved_trapping_math;\
14472   flag_rounding_math = saved_rounding_math;\
14473   flag_trapv = saved_trapv;\
14474   folding_initializer = saved_folding_initializer;
14475
14476 tree
14477 fold_build1_initializer_loc (location_t loc, enum tree_code code,
14478                              tree type, tree op)
14479 {
14480   tree result;
14481   START_FOLD_INIT;
14482
14483   result = fold_build1_loc (loc, code, type, op);
14484
14485   END_FOLD_INIT;
14486   return result;
14487 }
14488
14489 tree
14490 fold_build2_initializer_loc (location_t loc, enum tree_code code,
14491                              tree type, tree op0, tree op1)
14492 {
14493   tree result;
14494   START_FOLD_INIT;
14495
14496   result = fold_build2_loc (loc, code, type, op0, op1);
14497
14498   END_FOLD_INIT;
14499   return result;
14500 }
14501
14502 tree
14503 fold_build_call_array_initializer_loc (location_t loc, tree type, tree fn,
14504                                        int nargs, tree *argarray)
14505 {
14506   tree result;
14507   START_FOLD_INIT;
14508
14509   result = fold_build_call_array_loc (loc, type, fn, nargs, argarray);
14510
14511   END_FOLD_INIT;
14512   return result;
14513 }
14514
14515 #undef START_FOLD_INIT
14516 #undef END_FOLD_INIT
14517
14518 /* Determine if first argument is a multiple of second argument.  Return 0 if
14519    it is not, or we cannot easily determined it to be.
14520
14521    An example of the sort of thing we care about (at this point; this routine
14522    could surely be made more general, and expanded to do what the *_DIV_EXPR's
14523    fold cases do now) is discovering that
14524
14525      SAVE_EXPR (I) * SAVE_EXPR (J * 8)
14526
14527    is a multiple of
14528
14529      SAVE_EXPR (J * 8)
14530
14531    when we know that the two SAVE_EXPR (J * 8) nodes are the same node.
14532
14533    This code also handles discovering that
14534
14535      SAVE_EXPR (I) * SAVE_EXPR (J * 8)
14536
14537    is a multiple of 8 so we don't have to worry about dealing with a
14538    possible remainder.
14539
14540    Note that we *look* inside a SAVE_EXPR only to determine how it was
14541    calculated; it is not safe for fold to do much of anything else with the
14542    internals of a SAVE_EXPR, since it cannot know when it will be evaluated
14543    at run time.  For example, the latter example above *cannot* be implemented
14544    as SAVE_EXPR (I) * J or any variant thereof, since the value of J at
14545    evaluation time of the original SAVE_EXPR is not necessarily the same at
14546    the time the new expression is evaluated.  The only optimization of this
14547    sort that would be valid is changing
14548
14549      SAVE_EXPR (I) * SAVE_EXPR (SAVE_EXPR (J) * 8)
14550
14551    divided by 8 to
14552
14553      SAVE_EXPR (I) * SAVE_EXPR (J)
14554
14555    (where the same SAVE_EXPR (J) is used in the original and the
14556    transformed version).  */
14557
14558 int
14559 multiple_of_p (tree type, const_tree top, const_tree bottom)
14560 {
14561   if (operand_equal_p (top, bottom, 0))
14562     return 1;
14563
14564   if (TREE_CODE (type) != INTEGER_TYPE)
14565     return 0;
14566
14567   switch (TREE_CODE (top))
14568     {
14569     case BIT_AND_EXPR:
14570       /* Bitwise and provides a power of two multiple.  If the mask is
14571          a multiple of BOTTOM then TOP is a multiple of BOTTOM.  */
14572       if (!integer_pow2p (bottom))
14573         return 0;
14574       /* FALLTHRU */
14575
14576     case MULT_EXPR:
14577       return (multiple_of_p (type, TREE_OPERAND (top, 0), bottom)
14578               || multiple_of_p (type, TREE_OPERAND (top, 1), bottom));
14579
14580     case PLUS_EXPR:
14581     case MINUS_EXPR:
14582       return (multiple_of_p (type, TREE_OPERAND (top, 0), bottom)
14583               && multiple_of_p (type, TREE_OPERAND (top, 1), bottom));
14584
14585     case LSHIFT_EXPR:
14586       if (TREE_CODE (TREE_OPERAND (top, 1)) == INTEGER_CST)
14587         {
14588           tree op1, t1;
14589
14590           op1 = TREE_OPERAND (top, 1);
14591           /* const_binop may not detect overflow correctly,
14592              so check for it explicitly here.  */
14593           if (wi::gtu_p (TYPE_PRECISION (TREE_TYPE (size_one_node)), op1)
14594               && 0 != (t1 = fold_convert (type,
14595                                           const_binop (LSHIFT_EXPR,
14596                                                        size_one_node,
14597                                                        op1)))
14598               && !TREE_OVERFLOW (t1))
14599             return multiple_of_p (type, t1, bottom);
14600         }
14601       return 0;
14602
14603     case NOP_EXPR:
14604       /* Can't handle conversions from non-integral or wider integral type.  */
14605       if ((TREE_CODE (TREE_TYPE (TREE_OPERAND (top, 0))) != INTEGER_TYPE)
14606           || (TYPE_PRECISION (type)
14607               < TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (top, 0)))))
14608         return 0;
14609
14610       /* .. fall through ...  */
14611
14612     case SAVE_EXPR:
14613       return multiple_of_p (type, TREE_OPERAND (top, 0), bottom);
14614
14615     case COND_EXPR:
14616       return (multiple_of_p (type, TREE_OPERAND (top, 1), bottom)
14617               && multiple_of_p (type, TREE_OPERAND (top, 2), bottom));
14618
14619     case INTEGER_CST:
14620       if (TREE_CODE (bottom) != INTEGER_CST
14621           || integer_zerop (bottom)
14622           || (TYPE_UNSIGNED (type)
14623               && (tree_int_cst_sgn (top) < 0
14624                   || tree_int_cst_sgn (bottom) < 0)))
14625         return 0;
14626       return wi::multiple_of_p (wi::to_widest (top), wi::to_widest (bottom),
14627                                 SIGNED);
14628
14629     default:
14630       return 0;
14631     }
14632 }
14633
14634 /* Return true if CODE or TYPE is known to be non-negative. */
14635
14636 static bool
14637 tree_simple_nonnegative_warnv_p (enum tree_code code, tree type)
14638 {
14639   if ((TYPE_PRECISION (type) != 1 || TYPE_UNSIGNED (type))
14640       && truth_value_p (code))
14641     /* Truth values evaluate to 0 or 1, which is nonnegative unless we
14642        have a signed:1 type (where the value is -1 and 0).  */
14643     return true;
14644   return false;
14645 }
14646
14647 /* Return true if (CODE OP0) is known to be non-negative.  If the return
14648    value is based on the assumption that signed overflow is undefined,
14649    set *STRICT_OVERFLOW_P to true; otherwise, don't change
14650    *STRICT_OVERFLOW_P.  */
14651
14652 bool
14653 tree_unary_nonnegative_warnv_p (enum tree_code code, tree type, tree op0,
14654                                 bool *strict_overflow_p)
14655 {
14656   if (TYPE_UNSIGNED (type))
14657     return true;
14658
14659   switch (code)
14660     {
14661     case ABS_EXPR:
14662       /* We can't return 1 if flag_wrapv is set because
14663          ABS_EXPR<INT_MIN> = INT_MIN.  */
14664       if (!INTEGRAL_TYPE_P (type))
14665         return true;
14666       if (TYPE_OVERFLOW_UNDEFINED (type))
14667         {
14668           *strict_overflow_p = true;
14669           return true;
14670         }
14671       break;
14672
14673     case NON_LVALUE_EXPR:
14674     case FLOAT_EXPR:
14675     case FIX_TRUNC_EXPR:
14676       return tree_expr_nonnegative_warnv_p (op0,
14677                                             strict_overflow_p);
14678
14679     CASE_CONVERT:
14680       {
14681         tree inner_type = TREE_TYPE (op0);
14682         tree outer_type = type;
14683
14684         if (TREE_CODE (outer_type) == REAL_TYPE)
14685           {
14686             if (TREE_CODE (inner_type) == REAL_TYPE)
14687               return tree_expr_nonnegative_warnv_p (op0,
14688                                                     strict_overflow_p);
14689             if (INTEGRAL_TYPE_P (inner_type))
14690               {
14691                 if (TYPE_UNSIGNED (inner_type))
14692                   return true;
14693                 return tree_expr_nonnegative_warnv_p (op0,
14694                                                       strict_overflow_p);
14695               }
14696           }
14697         else if (INTEGRAL_TYPE_P (outer_type))
14698           {
14699             if (TREE_CODE (inner_type) == REAL_TYPE)
14700               return tree_expr_nonnegative_warnv_p (op0,
14701                                                     strict_overflow_p);
14702             if (INTEGRAL_TYPE_P (inner_type))
14703               return TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type)
14704                       && TYPE_UNSIGNED (inner_type);
14705           }
14706       }
14707       break;
14708
14709     default:
14710       return tree_simple_nonnegative_warnv_p (code, type);
14711     }
14712
14713   /* We don't know sign of `t', so be conservative and return false.  */
14714   return false;
14715 }
14716
14717 /* Return true if (CODE OP0 OP1) is known to be non-negative.  If the return
14718    value is based on the assumption that signed overflow is undefined,
14719    set *STRICT_OVERFLOW_P to true; otherwise, don't change
14720    *STRICT_OVERFLOW_P.  */
14721
14722 bool
14723 tree_binary_nonnegative_warnv_p (enum tree_code code, tree type, tree op0,
14724                                       tree op1, bool *strict_overflow_p)
14725 {
14726   if (TYPE_UNSIGNED (type))
14727     return true;
14728
14729   switch (code)
14730     {
14731     case POINTER_PLUS_EXPR:
14732     case PLUS_EXPR:
14733       if (FLOAT_TYPE_P (type))
14734         return (tree_expr_nonnegative_warnv_p (op0,
14735                                                strict_overflow_p)
14736                 && tree_expr_nonnegative_warnv_p (op1,
14737                                                   strict_overflow_p));
14738
14739       /* zero_extend(x) + zero_extend(y) is non-negative if x and y are
14740          both unsigned and at least 2 bits shorter than the result.  */
14741       if (TREE_CODE (type) == INTEGER_TYPE
14742           && TREE_CODE (op0) == NOP_EXPR
14743           && TREE_CODE (op1) == NOP_EXPR)
14744         {
14745           tree inner1 = TREE_TYPE (TREE_OPERAND (op0, 0));
14746           tree inner2 = TREE_TYPE (TREE_OPERAND (op1, 0));
14747           if (TREE_CODE (inner1) == INTEGER_TYPE && TYPE_UNSIGNED (inner1)
14748               && TREE_CODE (inner2) == INTEGER_TYPE && TYPE_UNSIGNED (inner2))
14749             {
14750               unsigned int prec = MAX (TYPE_PRECISION (inner1),
14751                                        TYPE_PRECISION (inner2)) + 1;
14752               return prec < TYPE_PRECISION (type);
14753             }
14754         }
14755       break;
14756
14757     case MULT_EXPR:
14758       if (FLOAT_TYPE_P (type) || TYPE_OVERFLOW_UNDEFINED (type))
14759         {
14760           /* x * x is always non-negative for floating point x
14761              or without overflow.  */
14762           if (operand_equal_p (op0, op1, 0)
14763               || (tree_expr_nonnegative_warnv_p (op0, strict_overflow_p)
14764                   && tree_expr_nonnegative_warnv_p (op1, strict_overflow_p)))
14765             {
14766               if (ANY_INTEGRAL_TYPE_P (type)
14767                   && TYPE_OVERFLOW_UNDEFINED (type))
14768                 *strict_overflow_p = true;
14769               return true;
14770             }
14771         }
14772
14773       /* zero_extend(x) * zero_extend(y) is non-negative if x and y are
14774          both unsigned and their total bits is shorter than the result.  */
14775       if (TREE_CODE (type) == INTEGER_TYPE
14776           && (TREE_CODE (op0) == NOP_EXPR || TREE_CODE (op0) == INTEGER_CST)
14777           && (TREE_CODE (op1) == NOP_EXPR || TREE_CODE (op1) == INTEGER_CST))
14778         {
14779           tree inner0 = (TREE_CODE (op0) == NOP_EXPR)
14780             ? TREE_TYPE (TREE_OPERAND (op0, 0))
14781             : TREE_TYPE (op0);
14782           tree inner1 = (TREE_CODE (op1) == NOP_EXPR)
14783             ? TREE_TYPE (TREE_OPERAND (op1, 0))
14784             : TREE_TYPE (op1);
14785
14786           bool unsigned0 = TYPE_UNSIGNED (inner0);
14787           bool unsigned1 = TYPE_UNSIGNED (inner1);
14788
14789           if (TREE_CODE (op0) == INTEGER_CST)
14790             unsigned0 = unsigned0 || tree_int_cst_sgn (op0) >= 0;
14791
14792           if (TREE_CODE (op1) == INTEGER_CST)
14793             unsigned1 = unsigned1 || tree_int_cst_sgn (op1) >= 0;
14794
14795           if (TREE_CODE (inner0) == INTEGER_TYPE && unsigned0
14796               && TREE_CODE (inner1) == INTEGER_TYPE && unsigned1)
14797             {
14798               unsigned int precision0 = (TREE_CODE (op0) == INTEGER_CST)
14799                 ? tree_int_cst_min_precision (op0, UNSIGNED)
14800                 : TYPE_PRECISION (inner0);
14801
14802               unsigned int precision1 = (TREE_CODE (op1) == INTEGER_CST)
14803                 ? tree_int_cst_min_precision (op1, UNSIGNED)
14804                 : TYPE_PRECISION (inner1);
14805
14806               return precision0 + precision1 < TYPE_PRECISION (type);
14807             }
14808         }
14809       return false;
14810
14811     case BIT_AND_EXPR:
14812     case MAX_EXPR:
14813       return (tree_expr_nonnegative_warnv_p (op0,
14814                                              strict_overflow_p)
14815               || tree_expr_nonnegative_warnv_p (op1,
14816                                                 strict_overflow_p));
14817
14818     case BIT_IOR_EXPR:
14819     case BIT_XOR_EXPR:
14820     case MIN_EXPR:
14821     case RDIV_EXPR:
14822     case TRUNC_DIV_EXPR:
14823     case CEIL_DIV_EXPR:
14824     case FLOOR_DIV_EXPR:
14825     case ROUND_DIV_EXPR:
14826       return (tree_expr_nonnegative_warnv_p (op0,
14827                                              strict_overflow_p)
14828               && tree_expr_nonnegative_warnv_p (op1,
14829                                                 strict_overflow_p));
14830
14831     case TRUNC_MOD_EXPR:
14832     case CEIL_MOD_EXPR:
14833     case FLOOR_MOD_EXPR:
14834     case ROUND_MOD_EXPR:
14835       return tree_expr_nonnegative_warnv_p (op0,
14836                                             strict_overflow_p);
14837     default:
14838       return tree_simple_nonnegative_warnv_p (code, type);
14839     }
14840
14841   /* We don't know sign of `t', so be conservative and return false.  */
14842   return false;
14843 }
14844
14845 /* Return true if T is known to be non-negative.  If the return
14846    value is based on the assumption that signed overflow is undefined,
14847    set *STRICT_OVERFLOW_P to true; otherwise, don't change
14848    *STRICT_OVERFLOW_P.  */
14849
14850 bool
14851 tree_single_nonnegative_warnv_p (tree t, bool *strict_overflow_p)
14852 {
14853   if (TYPE_UNSIGNED (TREE_TYPE (t)))
14854     return true;
14855
14856   switch (TREE_CODE (t))
14857     {
14858     case INTEGER_CST:
14859       return tree_int_cst_sgn (t) >= 0;
14860
14861     case REAL_CST:
14862       return ! REAL_VALUE_NEGATIVE (TREE_REAL_CST (t));
14863
14864     case FIXED_CST:
14865       return ! FIXED_VALUE_NEGATIVE (TREE_FIXED_CST (t));
14866
14867     case COND_EXPR:
14868       return (tree_expr_nonnegative_warnv_p (TREE_OPERAND (t, 1),
14869                                              strict_overflow_p)
14870               && tree_expr_nonnegative_warnv_p (TREE_OPERAND (t, 2),
14871                                                 strict_overflow_p));
14872     default:
14873       return tree_simple_nonnegative_warnv_p (TREE_CODE (t),
14874                                                    TREE_TYPE (t));
14875     }
14876   /* We don't know sign of `t', so be conservative and return false.  */
14877   return false;
14878 }
14879
14880 /* Return true if T is known to be non-negative.  If the return
14881    value is based on the assumption that signed overflow is undefined,
14882    set *STRICT_OVERFLOW_P to true; otherwise, don't change
14883    *STRICT_OVERFLOW_P.  */
14884
14885 bool
14886 tree_call_nonnegative_warnv_p (tree type, tree fndecl,
14887                                tree arg0, tree arg1, bool *strict_overflow_p)
14888 {
14889   if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
14890     switch (DECL_FUNCTION_CODE (fndecl))
14891       {
14892         CASE_FLT_FN (BUILT_IN_ACOS):
14893         CASE_FLT_FN (BUILT_IN_ACOSH):
14894         CASE_FLT_FN (BUILT_IN_CABS):
14895         CASE_FLT_FN (BUILT_IN_COSH):
14896         CASE_FLT_FN (BUILT_IN_ERFC):
14897         CASE_FLT_FN (BUILT_IN_EXP):
14898         CASE_FLT_FN (BUILT_IN_EXP10):
14899         CASE_FLT_FN (BUILT_IN_EXP2):
14900         CASE_FLT_FN (BUILT_IN_FABS):
14901         CASE_FLT_FN (BUILT_IN_FDIM):
14902         CASE_FLT_FN (BUILT_IN_HYPOT):
14903         CASE_FLT_FN (BUILT_IN_POW10):
14904         CASE_INT_FN (BUILT_IN_FFS):
14905         CASE_INT_FN (BUILT_IN_PARITY):
14906         CASE_INT_FN (BUILT_IN_POPCOUNT):
14907         CASE_INT_FN (BUILT_IN_CLZ):
14908         CASE_INT_FN (BUILT_IN_CLRSB):
14909       case BUILT_IN_BSWAP32:
14910       case BUILT_IN_BSWAP64:
14911         /* Always true.  */
14912         return true;
14913
14914         CASE_FLT_FN (BUILT_IN_SQRT):
14915         /* sqrt(-0.0) is -0.0.  */
14916         if (!HONOR_SIGNED_ZEROS (element_mode (type)))
14917           return true;
14918         return tree_expr_nonnegative_warnv_p (arg0,
14919                                               strict_overflow_p);
14920
14921         CASE_FLT_FN (BUILT_IN_ASINH):
14922         CASE_FLT_FN (BUILT_IN_ATAN):
14923         CASE_FLT_FN (BUILT_IN_ATANH):
14924         CASE_FLT_FN (BUILT_IN_CBRT):
14925         CASE_FLT_FN (BUILT_IN_CEIL):
14926         CASE_FLT_FN (BUILT_IN_ERF):
14927         CASE_FLT_FN (BUILT_IN_EXPM1):
14928         CASE_FLT_FN (BUILT_IN_FLOOR):
14929         CASE_FLT_FN (BUILT_IN_FMOD):
14930         CASE_FLT_FN (BUILT_IN_FREXP):
14931         CASE_FLT_FN (BUILT_IN_ICEIL):
14932         CASE_FLT_FN (BUILT_IN_IFLOOR):
14933         CASE_FLT_FN (BUILT_IN_IRINT):
14934         CASE_FLT_FN (BUILT_IN_IROUND):
14935         CASE_FLT_FN (BUILT_IN_LCEIL):
14936         CASE_FLT_FN (BUILT_IN_LDEXP):
14937         CASE_FLT_FN (BUILT_IN_LFLOOR):
14938         CASE_FLT_FN (BUILT_IN_LLCEIL):
14939         CASE_FLT_FN (BUILT_IN_LLFLOOR):
14940         CASE_FLT_FN (BUILT_IN_LLRINT):
14941         CASE_FLT_FN (BUILT_IN_LLROUND):
14942         CASE_FLT_FN (BUILT_IN_LRINT):
14943         CASE_FLT_FN (BUILT_IN_LROUND):
14944         CASE_FLT_FN (BUILT_IN_MODF):
14945         CASE_FLT_FN (BUILT_IN_NEARBYINT):
14946         CASE_FLT_FN (BUILT_IN_RINT):
14947         CASE_FLT_FN (BUILT_IN_ROUND):
14948         CASE_FLT_FN (BUILT_IN_SCALB):
14949         CASE_FLT_FN (BUILT_IN_SCALBLN):
14950         CASE_FLT_FN (BUILT_IN_SCALBN):
14951         CASE_FLT_FN (BUILT_IN_SIGNBIT):
14952         CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
14953         CASE_FLT_FN (BUILT_IN_SINH):
14954         CASE_FLT_FN (BUILT_IN_TANH):
14955         CASE_FLT_FN (BUILT_IN_TRUNC):
14956         /* True if the 1st argument is nonnegative.  */
14957         return tree_expr_nonnegative_warnv_p (arg0,
14958                                               strict_overflow_p);
14959
14960         CASE_FLT_FN (BUILT_IN_FMAX):
14961         /* True if the 1st OR 2nd arguments are nonnegative.  */
14962         return (tree_expr_nonnegative_warnv_p (arg0,
14963                                                strict_overflow_p)
14964                 || (tree_expr_nonnegative_warnv_p (arg1,
14965                                                    strict_overflow_p)));
14966
14967         CASE_FLT_FN (BUILT_IN_FMIN):
14968         /* True if the 1st AND 2nd arguments are nonnegative.  */
14969         return (tree_expr_nonnegative_warnv_p (arg0,
14970                                                strict_overflow_p)
14971                 && (tree_expr_nonnegative_warnv_p (arg1,
14972                                                    strict_overflow_p)));
14973
14974         CASE_FLT_FN (BUILT_IN_COPYSIGN):
14975         /* True if the 2nd argument is nonnegative.  */
14976         return tree_expr_nonnegative_warnv_p (arg1,
14977                                               strict_overflow_p);
14978
14979         CASE_FLT_FN (BUILT_IN_POWI):
14980         /* True if the 1st argument is nonnegative or the second
14981            argument is an even integer.  */
14982         if (TREE_CODE (arg1) == INTEGER_CST
14983             && (TREE_INT_CST_LOW (arg1) & 1) == 0)
14984           return true;
14985         return tree_expr_nonnegative_warnv_p (arg0,
14986                                               strict_overflow_p);
14987
14988         CASE_FLT_FN (BUILT_IN_POW):
14989         /* True if the 1st argument is nonnegative or the second
14990            argument is an even integer valued real.  */
14991         if (TREE_CODE (arg1) == REAL_CST)
14992           {
14993             REAL_VALUE_TYPE c;
14994             HOST_WIDE_INT n;
14995
14996             c = TREE_REAL_CST (arg1);
14997             n = real_to_integer (&c);
14998             if ((n & 1) == 0)
14999               {
15000                 REAL_VALUE_TYPE cint;
15001                 real_from_integer (&cint, VOIDmode, n, SIGNED);
15002                 if (real_identical (&c, &cint))
15003                   return true;
15004               }
15005           }
15006         return tree_expr_nonnegative_warnv_p (arg0,
15007                                               strict_overflow_p);
15008
15009       default:
15010         break;
15011       }
15012   return tree_simple_nonnegative_warnv_p (CALL_EXPR,
15013                                           type);
15014 }
15015
15016 /* Return true if T is known to be non-negative.  If the return
15017    value is based on the assumption that signed overflow is undefined,
15018    set *STRICT_OVERFLOW_P to true; otherwise, don't change
15019    *STRICT_OVERFLOW_P.  */
15020
15021 static bool
15022 tree_invalid_nonnegative_warnv_p (tree t, bool *strict_overflow_p)
15023 {
15024   enum tree_code code = TREE_CODE (t);
15025   if (TYPE_UNSIGNED (TREE_TYPE (t)))
15026     return true;
15027
15028   switch (code)
15029     {
15030     case TARGET_EXPR:
15031       {
15032         tree temp = TARGET_EXPR_SLOT (t);
15033         t = TARGET_EXPR_INITIAL (t);
15034
15035         /* If the initializer is non-void, then it's a normal expression
15036            that will be assigned to the slot.  */
15037         if (!VOID_TYPE_P (t))
15038           return tree_expr_nonnegative_warnv_p (t, strict_overflow_p);
15039
15040         /* Otherwise, the initializer sets the slot in some way.  One common
15041            way is an assignment statement at the end of the initializer.  */
15042         while (1)
15043           {
15044             if (TREE_CODE (t) == BIND_EXPR)
15045               t = expr_last (BIND_EXPR_BODY (t));
15046             else if (TREE_CODE (t) == TRY_FINALLY_EXPR
15047                      || TREE_CODE (t) == TRY_CATCH_EXPR)
15048               t = expr_last (TREE_OPERAND (t, 0));
15049             else if (TREE_CODE (t) == STATEMENT_LIST)
15050               t = expr_last (t);
15051             else
15052               break;
15053           }
15054         if (TREE_CODE (t) == MODIFY_EXPR
15055             && TREE_OPERAND (t, 0) == temp)
15056           return tree_expr_nonnegative_warnv_p (TREE_OPERAND (t, 1),
15057                                                 strict_overflow_p);
15058
15059         return false;
15060       }
15061
15062     case CALL_EXPR:
15063       {
15064         tree arg0 = call_expr_nargs (t) > 0 ?  CALL_EXPR_ARG (t, 0) : NULL_TREE;
15065         tree arg1 = call_expr_nargs (t) > 1 ?  CALL_EXPR_ARG (t, 1) : NULL_TREE;
15066
15067         return tree_call_nonnegative_warnv_p (TREE_TYPE (t),
15068                                               get_callee_fndecl (t),
15069                                               arg0,
15070                                               arg1,
15071                                               strict_overflow_p);
15072       }
15073     case COMPOUND_EXPR:
15074     case MODIFY_EXPR:
15075       return tree_expr_nonnegative_warnv_p (TREE_OPERAND (t, 1),
15076                                             strict_overflow_p);
15077     case BIND_EXPR:
15078       return tree_expr_nonnegative_warnv_p (expr_last (TREE_OPERAND (t, 1)),
15079                                             strict_overflow_p);
15080     case SAVE_EXPR:
15081       return tree_expr_nonnegative_warnv_p (TREE_OPERAND (t, 0),
15082                                             strict_overflow_p);
15083
15084     default:
15085       return tree_simple_nonnegative_warnv_p (TREE_CODE (t),
15086                                                    TREE_TYPE (t));
15087     }
15088
15089   /* We don't know sign of `t', so be conservative and return false.  */
15090   return false;
15091 }
15092
15093 /* Return true if T is known to be non-negative.  If the return
15094    value is based on the assumption that signed overflow is undefined,
15095    set *STRICT_OVERFLOW_P to true; otherwise, don't change
15096    *STRICT_OVERFLOW_P.  */
15097
15098 bool
15099 tree_expr_nonnegative_warnv_p (tree t, bool *strict_overflow_p)
15100 {
15101   enum tree_code code;
15102   if (t == error_mark_node)
15103     return false;
15104
15105   code = TREE_CODE (t);
15106   switch (TREE_CODE_CLASS (code))
15107     {
15108     case tcc_binary:
15109     case tcc_comparison:
15110       return tree_binary_nonnegative_warnv_p (TREE_CODE (t),
15111                                               TREE_TYPE (t),
15112                                               TREE_OPERAND (t, 0),
15113                                               TREE_OPERAND (t, 1),
15114                                               strict_overflow_p);
15115
15116     case tcc_unary:
15117       return tree_unary_nonnegative_warnv_p (TREE_CODE (t),
15118                                              TREE_TYPE (t),
15119                                              TREE_OPERAND (t, 0),
15120                                              strict_overflow_p);
15121
15122     case tcc_constant:
15123     case tcc_declaration:
15124     case tcc_reference:
15125       return tree_single_nonnegative_warnv_p (t, strict_overflow_p);
15126
15127     default:
15128       break;
15129     }
15130
15131   switch (code)
15132     {
15133     case TRUTH_AND_EXPR:
15134     case TRUTH_OR_EXPR:
15135     case TRUTH_XOR_EXPR:
15136       return tree_binary_nonnegative_warnv_p (TREE_CODE (t),
15137                                               TREE_TYPE (t),
15138                                               TREE_OPERAND (t, 0),
15139                                               TREE_OPERAND (t, 1),
15140                                               strict_overflow_p);
15141     case TRUTH_NOT_EXPR:
15142       return tree_unary_nonnegative_warnv_p (TREE_CODE (t),
15143                                              TREE_TYPE (t),
15144                                              TREE_OPERAND (t, 0),
15145                                              strict_overflow_p);
15146
15147     case COND_EXPR:
15148     case CONSTRUCTOR:
15149     case OBJ_TYPE_REF:
15150     case ASSERT_EXPR:
15151     case ADDR_EXPR:
15152     case WITH_SIZE_EXPR:
15153     case SSA_NAME:
15154       return tree_single_nonnegative_warnv_p (t, strict_overflow_p);
15155
15156     default:
15157       return tree_invalid_nonnegative_warnv_p (t, strict_overflow_p);
15158     }
15159 }
15160
15161 /* Return true if `t' is known to be non-negative.  Handle warnings
15162    about undefined signed overflow.  */
15163
15164 bool
15165 tree_expr_nonnegative_p (tree t)
15166 {
15167   bool ret, strict_overflow_p;
15168
15169   strict_overflow_p = false;
15170   ret = tree_expr_nonnegative_warnv_p (t, &strict_overflow_p);
15171   if (strict_overflow_p)
15172     fold_overflow_warning (("assuming signed overflow does not occur when "
15173                             "determining that expression is always "
15174                             "non-negative"),
15175                            WARN_STRICT_OVERFLOW_MISC);
15176   return ret;
15177 }
15178
15179
15180 /* Return true when (CODE OP0) is an address and is known to be nonzero.
15181    For floating point we further ensure that T is not denormal.
15182    Similar logic is present in nonzero_address in rtlanal.h.
15183
15184    If the return value is based on the assumption that signed overflow
15185    is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
15186    change *STRICT_OVERFLOW_P.  */
15187
15188 bool
15189 tree_unary_nonzero_warnv_p (enum tree_code code, tree type, tree op0,
15190                                  bool *strict_overflow_p)
15191 {
15192   switch (code)
15193     {
15194     case ABS_EXPR:
15195       return tree_expr_nonzero_warnv_p (op0,
15196                                         strict_overflow_p);
15197
15198     case NOP_EXPR:
15199       {
15200         tree inner_type = TREE_TYPE (op0);
15201         tree outer_type = type;
15202
15203         return (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
15204                 && tree_expr_nonzero_warnv_p (op0,
15205                                               strict_overflow_p));
15206       }
15207       break;
15208
15209     case NON_LVALUE_EXPR:
15210       return tree_expr_nonzero_warnv_p (op0,
15211                                         strict_overflow_p);
15212
15213     default:
15214       break;
15215   }
15216
15217   return false;
15218 }
15219
15220 /* Return true when (CODE OP0 OP1) is an address and is known to be nonzero.
15221    For floating point we further ensure that T is not denormal.
15222    Similar logic is present in nonzero_address in rtlanal.h.
15223
15224    If the return value is based on the assumption that signed overflow
15225    is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
15226    change *STRICT_OVERFLOW_P.  */
15227
15228 bool
15229 tree_binary_nonzero_warnv_p (enum tree_code code,
15230                              tree type,
15231                              tree op0,
15232                              tree op1, bool *strict_overflow_p)
15233 {
15234   bool sub_strict_overflow_p;
15235   switch (code)
15236     {
15237     case POINTER_PLUS_EXPR:
15238     case PLUS_EXPR:
15239       if (ANY_INTEGRAL_TYPE_P (type) && TYPE_OVERFLOW_UNDEFINED (type))
15240         {
15241           /* With the presence of negative values it is hard
15242              to say something.  */
15243           sub_strict_overflow_p = false;
15244           if (!tree_expr_nonnegative_warnv_p (op0,
15245                                               &sub_strict_overflow_p)
15246               || !tree_expr_nonnegative_warnv_p (op1,
15247                                                  &sub_strict_overflow_p))
15248             return false;
15249           /* One of operands must be positive and the other non-negative.  */
15250           /* We don't set *STRICT_OVERFLOW_P here: even if this value
15251              overflows, on a twos-complement machine the sum of two
15252              nonnegative numbers can never be zero.  */
15253           return (tree_expr_nonzero_warnv_p (op0,
15254                                              strict_overflow_p)
15255                   || tree_expr_nonzero_warnv_p (op1,
15256                                                 strict_overflow_p));
15257         }
15258       break;
15259
15260     case MULT_EXPR:
15261       if (TYPE_OVERFLOW_UNDEFINED (type))
15262         {
15263           if (tree_expr_nonzero_warnv_p (op0,
15264                                          strict_overflow_p)
15265               && tree_expr_nonzero_warnv_p (op1,
15266                                             strict_overflow_p))
15267             {
15268               *strict_overflow_p = true;
15269               return true;
15270             }
15271         }
15272       break;
15273
15274     case MIN_EXPR:
15275       sub_strict_overflow_p = false;
15276       if (tree_expr_nonzero_warnv_p (op0,
15277                                      &sub_strict_overflow_p)
15278           && tree_expr_nonzero_warnv_p (op1,
15279                                         &sub_strict_overflow_p))
15280         {
15281           if (sub_strict_overflow_p)
15282             *strict_overflow_p = true;
15283         }
15284       break;
15285
15286     case MAX_EXPR:
15287       sub_strict_overflow_p = false;
15288       if (tree_expr_nonzero_warnv_p (op0,
15289                                      &sub_strict_overflow_p))
15290         {
15291           if (sub_strict_overflow_p)
15292             *strict_overflow_p = true;
15293
15294           /* When both operands are nonzero, then MAX must be too.  */
15295           if (tree_expr_nonzero_warnv_p (op1,
15296                                          strict_overflow_p))
15297             return true;
15298
15299           /* MAX where operand 0 is positive is positive.  */
15300           return tree_expr_nonnegative_warnv_p (op0,
15301                                                strict_overflow_p);
15302         }
15303       /* MAX where operand 1 is positive is positive.  */
15304       else if (tree_expr_nonzero_warnv_p (op1,
15305                                           &sub_strict_overflow_p)
15306                && tree_expr_nonnegative_warnv_p (op1,
15307                                                  &sub_strict_overflow_p))
15308         {
15309           if (sub_strict_overflow_p)
15310             *strict_overflow_p = true;
15311           return true;
15312         }
15313       break;
15314
15315     case BIT_IOR_EXPR:
15316       return (tree_expr_nonzero_warnv_p (op1,
15317                                          strict_overflow_p)
15318               || tree_expr_nonzero_warnv_p (op0,
15319                                             strict_overflow_p));
15320
15321     default:
15322       break;
15323   }
15324
15325   return false;
15326 }
15327
15328 /* Return true when T is an address and is known to be nonzero.
15329    For floating point we further ensure that T is not denormal.
15330    Similar logic is present in nonzero_address in rtlanal.h.
15331
15332    If the return value is based on the assumption that signed overflow
15333    is undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't
15334    change *STRICT_OVERFLOW_P.  */
15335
15336 bool
15337 tree_single_nonzero_warnv_p (tree t, bool *strict_overflow_p)
15338 {
15339   bool sub_strict_overflow_p;
15340   switch (TREE_CODE (t))
15341     {
15342     case INTEGER_CST:
15343       return !integer_zerop (t);
15344
15345     case ADDR_EXPR:
15346       {
15347         tree base = TREE_OPERAND (t, 0);
15348
15349         if (!DECL_P (base))
15350           base = get_base_address (base);
15351
15352         if (!base)
15353           return false;
15354
15355         /* For objects in symbol table check if we know they are non-zero.
15356            Don't do anything for variables and functions before symtab is built;
15357            it is quite possible that they will be declared weak later.  */
15358         if (DECL_P (base) && decl_in_symtab_p (base))
15359           {
15360             struct symtab_node *symbol;
15361
15362             symbol = symtab_node::get_create (base);
15363             if (symbol)
15364               return symbol->nonzero_address ();
15365             else
15366               return false;
15367           }
15368
15369         /* Function local objects are never NULL.  */
15370         if (DECL_P (base)
15371             && (DECL_CONTEXT (base)
15372                 && TREE_CODE (DECL_CONTEXT (base)) == FUNCTION_DECL
15373                 && auto_var_in_fn_p (base, DECL_CONTEXT (base))))
15374           return true;
15375
15376         /* Constants are never weak.  */
15377         if (CONSTANT_CLASS_P (base))
15378           return true;
15379
15380         return false;
15381       }
15382
15383     case COND_EXPR:
15384       sub_strict_overflow_p = false;
15385       if (tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 1),
15386                                      &sub_strict_overflow_p)
15387           && tree_expr_nonzero_warnv_p (TREE_OPERAND (t, 2),
15388                                         &sub_strict_overflow_p))
15389         {
15390           if (sub_strict_overflow_p)
15391             *strict_overflow_p = true;
15392           return true;
15393         }
15394       break;
15395
15396     default:
15397       break;
15398     }
15399   return false;
15400 }
15401
15402 /* Given the components of a binary expression CODE, TYPE, OP0 and OP1,
15403    attempt to fold the expression to a constant without modifying TYPE,
15404    OP0 or OP1.
15405
15406    If the expression could be simplified to a constant, then return
15407    the constant.  If the expression would not be simplified to a
15408    constant, then return NULL_TREE.  */
15409
15410 tree
15411 fold_binary_to_constant (enum tree_code code, tree type, tree op0, tree op1)
15412 {
15413   tree tem = fold_binary (code, type, op0, op1);
15414   return (tem && TREE_CONSTANT (tem)) ? tem : NULL_TREE;
15415 }
15416
15417 /* Given the components of a unary expression CODE, TYPE and OP0,
15418    attempt to fold the expression to a constant without modifying
15419    TYPE or OP0.
15420
15421    If the expression could be simplified to a constant, then return
15422    the constant.  If the expression would not be simplified to a
15423    constant, then return NULL_TREE.  */
15424
15425 tree
15426 fold_unary_to_constant (enum tree_code code, tree type, tree op0)
15427 {
15428   tree tem = fold_unary (code, type, op0);
15429   return (tem && TREE_CONSTANT (tem)) ? tem : NULL_TREE;
15430 }
15431
15432 /* If EXP represents referencing an element in a constant string
15433    (either via pointer arithmetic or array indexing), return the
15434    tree representing the value accessed, otherwise return NULL.  */
15435
15436 tree
15437 fold_read_from_constant_string (tree exp)
15438 {
15439   if ((TREE_CODE (exp) == INDIRECT_REF
15440        || TREE_CODE (exp) == ARRAY_REF)
15441       && TREE_CODE (TREE_TYPE (exp)) == INTEGER_TYPE)
15442     {
15443       tree exp1 = TREE_OPERAND (exp, 0);
15444       tree index;
15445       tree string;
15446       location_t loc = EXPR_LOCATION (exp);
15447
15448       if (TREE_CODE (exp) == INDIRECT_REF)
15449         string = string_constant (exp1, &index);
15450       else
15451         {
15452           tree low_bound = array_ref_low_bound (exp);
15453           index = fold_convert_loc (loc, sizetype, TREE_OPERAND (exp, 1));
15454
15455           /* Optimize the special-case of a zero lower bound.
15456
15457              We convert the low_bound to sizetype to avoid some problems
15458              with constant folding.  (E.g. suppose the lower bound is 1,
15459              and its mode is QI.  Without the conversion,l (ARRAY
15460              +(INDEX-(unsigned char)1)) becomes ((ARRAY+(-(unsigned char)1))
15461              +INDEX), which becomes (ARRAY+255+INDEX).  Oops!)  */
15462           if (! integer_zerop (low_bound))
15463             index = size_diffop_loc (loc, index,
15464                                  fold_convert_loc (loc, sizetype, low_bound));
15465
15466           string = exp1;
15467         }
15468
15469       if (string
15470           && TYPE_MODE (TREE_TYPE (exp)) == TYPE_MODE (TREE_TYPE (TREE_TYPE (string)))
15471           && TREE_CODE (string) == STRING_CST
15472           && TREE_CODE (index) == INTEGER_CST
15473           && compare_tree_int (index, TREE_STRING_LENGTH (string)) < 0
15474           && (GET_MODE_CLASS (TYPE_MODE (TREE_TYPE (TREE_TYPE (string))))
15475               == MODE_INT)
15476           && (GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (TREE_TYPE (string)))) == 1))
15477         return build_int_cst_type (TREE_TYPE (exp),
15478                                    (TREE_STRING_POINTER (string)
15479                                     [TREE_INT_CST_LOW (index)]));
15480     }
15481   return NULL;
15482 }
15483
15484 /* Return the tree for neg (ARG0) when ARG0 is known to be either
15485    an integer constant, real, or fixed-point constant.
15486
15487    TYPE is the type of the result.  */
15488
15489 static tree
15490 fold_negate_const (tree arg0, tree type)
15491 {
15492   tree t = NULL_TREE;
15493
15494   switch (TREE_CODE (arg0))
15495     {
15496     case INTEGER_CST:
15497       {
15498         bool overflow;
15499         wide_int val = wi::neg (arg0, &overflow);
15500         t = force_fit_type (type, val, 1,
15501                             (overflow | TREE_OVERFLOW (arg0))
15502                             && !TYPE_UNSIGNED (type));
15503         break;
15504       }
15505
15506     case REAL_CST:
15507       t = build_real (type, real_value_negate (&TREE_REAL_CST (arg0)));
15508       break;
15509
15510     case FIXED_CST:
15511       {
15512         FIXED_VALUE_TYPE f;
15513         bool overflow_p = fixed_arithmetic (&f, NEGATE_EXPR,
15514                                             &(TREE_FIXED_CST (arg0)), NULL,
15515                                             TYPE_SATURATING (type));
15516         t = build_fixed (type, f);
15517         /* Propagate overflow flags.  */
15518         if (overflow_p | TREE_OVERFLOW (arg0))
15519           TREE_OVERFLOW (t) = 1;
15520         break;
15521       }
15522
15523     default:
15524       gcc_unreachable ();
15525     }
15526
15527   return t;
15528 }
15529
15530 /* Return the tree for abs (ARG0) when ARG0 is known to be either
15531    an integer constant or real constant.
15532
15533    TYPE is the type of the result.  */
15534
15535 tree
15536 fold_abs_const (tree arg0, tree type)
15537 {
15538   tree t = NULL_TREE;
15539
15540   switch (TREE_CODE (arg0))
15541     {
15542     case INTEGER_CST:
15543       {
15544         /* If the value is unsigned or non-negative, then the absolute value
15545            is the same as the ordinary value.  */
15546         if (!wi::neg_p (arg0, TYPE_SIGN (type)))
15547           t = arg0;
15548
15549         /* If the value is negative, then the absolute value is
15550            its negation.  */
15551         else
15552           {
15553             bool overflow;
15554             wide_int val = wi::neg (arg0, &overflow);
15555             t = force_fit_type (type, val, -1,
15556                                 overflow | TREE_OVERFLOW (arg0));
15557           }
15558       }
15559       break;
15560
15561     case REAL_CST:
15562       if (REAL_VALUE_NEGATIVE (TREE_REAL_CST (arg0)))
15563         t = build_real (type, real_value_negate (&TREE_REAL_CST (arg0)));
15564       else
15565         t =  arg0;
15566       break;
15567
15568     default:
15569       gcc_unreachable ();
15570     }
15571
15572   return t;
15573 }
15574
15575 /* Return the tree for not (ARG0) when ARG0 is known to be an integer
15576    constant.  TYPE is the type of the result.  */
15577
15578 static tree
15579 fold_not_const (const_tree arg0, tree type)
15580 {
15581   gcc_assert (TREE_CODE (arg0) == INTEGER_CST);
15582
15583   return force_fit_type (type, wi::bit_not (arg0), 0, TREE_OVERFLOW (arg0));
15584 }
15585
15586 /* Given CODE, a relational operator, the target type, TYPE and two
15587    constant operands OP0 and OP1, return the result of the
15588    relational operation.  If the result is not a compile time
15589    constant, then return NULL_TREE.  */
15590
15591 static tree
15592 fold_relational_const (enum tree_code code, tree type, tree op0, tree op1)
15593 {
15594   int result, invert;
15595
15596   /* From here on, the only cases we handle are when the result is
15597      known to be a constant.  */
15598
15599   if (TREE_CODE (op0) == REAL_CST && TREE_CODE (op1) == REAL_CST)
15600     {
15601       const REAL_VALUE_TYPE *c0 = TREE_REAL_CST_PTR (op0);
15602       const REAL_VALUE_TYPE *c1 = TREE_REAL_CST_PTR (op1);
15603
15604       /* Handle the cases where either operand is a NaN.  */
15605       if (real_isnan (c0) || real_isnan (c1))
15606         {
15607           switch (code)
15608             {
15609             case EQ_EXPR:
15610             case ORDERED_EXPR:
15611               result = 0;
15612               break;
15613
15614             case NE_EXPR:
15615             case UNORDERED_EXPR:
15616             case UNLT_EXPR:
15617             case UNLE_EXPR:
15618             case UNGT_EXPR:
15619             case UNGE_EXPR:
15620             case UNEQ_EXPR:
15621               result = 1;
15622               break;
15623
15624             case LT_EXPR:
15625             case LE_EXPR:
15626             case GT_EXPR:
15627             case GE_EXPR:
15628             case LTGT_EXPR:
15629               if (flag_trapping_math)
15630                 return NULL_TREE;
15631               result = 0;
15632               break;
15633
15634             default:
15635               gcc_unreachable ();
15636             }
15637
15638           return constant_boolean_node (result, type);
15639         }
15640
15641       return constant_boolean_node (real_compare (code, c0, c1), type);
15642     }
15643
15644   if (TREE_CODE (op0) == FIXED_CST && TREE_CODE (op1) == FIXED_CST)
15645     {
15646       const FIXED_VALUE_TYPE *c0 = TREE_FIXED_CST_PTR (op0);
15647       const FIXED_VALUE_TYPE *c1 = TREE_FIXED_CST_PTR (op1);
15648       return constant_boolean_node (fixed_compare (code, c0, c1), type);
15649     }
15650
15651   /* Handle equality/inequality of complex constants.  */
15652   if (TREE_CODE (op0) == COMPLEX_CST && TREE_CODE (op1) == COMPLEX_CST)
15653     {
15654       tree rcond = fold_relational_const (code, type,
15655                                           TREE_REALPART (op0),
15656                                           TREE_REALPART (op1));
15657       tree icond = fold_relational_const (code, type,
15658                                           TREE_IMAGPART (op0),
15659                                           TREE_IMAGPART (op1));
15660       if (code == EQ_EXPR)
15661         return fold_build2 (TRUTH_ANDIF_EXPR, type, rcond, icond);
15662       else if (code == NE_EXPR)
15663         return fold_build2 (TRUTH_ORIF_EXPR, type, rcond, icond);
15664       else
15665         return NULL_TREE;
15666     }
15667
15668   if (TREE_CODE (op0) == VECTOR_CST && TREE_CODE (op1) == VECTOR_CST)
15669     {
15670       unsigned count = VECTOR_CST_NELTS (op0);
15671       tree *elts =  XALLOCAVEC (tree, count);
15672       gcc_assert (VECTOR_CST_NELTS (op1) == count
15673                   && TYPE_VECTOR_SUBPARTS (type) == count);
15674
15675       for (unsigned i = 0; i < count; i++)
15676         {
15677           tree elem_type = TREE_TYPE (type);
15678           tree elem0 = VECTOR_CST_ELT (op0, i);
15679           tree elem1 = VECTOR_CST_ELT (op1, i);
15680
15681           tree tem = fold_relational_const (code, elem_type,
15682                                             elem0, elem1);
15683
15684           if (tem == NULL_TREE)
15685             return NULL_TREE;
15686
15687           elts[i] = build_int_cst (elem_type, integer_zerop (tem) ? 0 : -1);
15688         }
15689
15690       return build_vector (type, elts);
15691     }
15692
15693   /* From here on we only handle LT, LE, GT, GE, EQ and NE.
15694
15695      To compute GT, swap the arguments and do LT.
15696      To compute GE, do LT and invert the result.
15697      To compute LE, swap the arguments, do LT and invert the result.
15698      To compute NE, do EQ and invert the result.
15699
15700      Therefore, the code below must handle only EQ and LT.  */
15701
15702   if (code == LE_EXPR || code == GT_EXPR)
15703     {
15704       tree tem = op0;
15705       op0 = op1;
15706       op1 = tem;
15707       code = swap_tree_comparison (code);
15708     }
15709
15710   /* Note that it is safe to invert for real values here because we
15711      have already handled the one case that it matters.  */
15712
15713   invert = 0;
15714   if (code == NE_EXPR || code == GE_EXPR)
15715     {
15716       invert = 1;
15717       code = invert_tree_comparison (code, false);
15718     }
15719
15720   /* Compute a result for LT or EQ if args permit;
15721      Otherwise return T.  */
15722   if (TREE_CODE (op0) == INTEGER_CST && TREE_CODE (op1) == INTEGER_CST)
15723     {
15724       if (code == EQ_EXPR)
15725         result = tree_int_cst_equal (op0, op1);
15726       else
15727         result = tree_int_cst_lt (op0, op1);
15728     }
15729   else
15730     return NULL_TREE;
15731
15732   if (invert)
15733     result ^= 1;
15734   return constant_boolean_node (result, type);
15735 }
15736
15737 /* If necessary, return a CLEANUP_POINT_EXPR for EXPR with the
15738    indicated TYPE.  If no CLEANUP_POINT_EXPR is necessary, return EXPR
15739    itself.  */
15740
15741 tree
15742 fold_build_cleanup_point_expr (tree type, tree expr)
15743 {
15744   /* If the expression does not have side effects then we don't have to wrap
15745      it with a cleanup point expression.  */
15746   if (!TREE_SIDE_EFFECTS (expr))
15747     return expr;
15748
15749   /* If the expression is a return, check to see if the expression inside the
15750      return has no side effects or the right hand side of the modify expression
15751      inside the return. If either don't have side effects set we don't need to
15752      wrap the expression in a cleanup point expression.  Note we don't check the
15753      left hand side of the modify because it should always be a return decl.  */
15754   if (TREE_CODE (expr) == RETURN_EXPR)
15755     {
15756       tree op = TREE_OPERAND (expr, 0);
15757       if (!op || !TREE_SIDE_EFFECTS (op))
15758         return expr;
15759       op = TREE_OPERAND (op, 1);
15760       if (!TREE_SIDE_EFFECTS (op))
15761         return expr;
15762     }
15763
15764   return build1 (CLEANUP_POINT_EXPR, type, expr);
15765 }
15766
15767 /* Given a pointer value OP0 and a type TYPE, return a simplified version
15768    of an indirection through OP0, or NULL_TREE if no simplification is
15769    possible.  */
15770
15771 tree
15772 fold_indirect_ref_1 (location_t loc, tree type, tree op0)
15773 {
15774   tree sub = op0;
15775   tree subtype;
15776
15777   STRIP_NOPS (sub);
15778   subtype = TREE_TYPE (sub);
15779   if (!POINTER_TYPE_P (subtype))
15780     return NULL_TREE;
15781
15782   if (TREE_CODE (sub) == ADDR_EXPR)
15783     {
15784       tree op = TREE_OPERAND (sub, 0);
15785       tree optype = TREE_TYPE (op);
15786       /* *&CONST_DECL -> to the value of the const decl.  */
15787       if (TREE_CODE (op) == CONST_DECL)
15788         return DECL_INITIAL (op);
15789       /* *&p => p;  make sure to handle *&"str"[cst] here.  */
15790       if (type == optype)
15791         {
15792           tree fop = fold_read_from_constant_string (op);
15793           if (fop)
15794             return fop;
15795           else
15796             return op;
15797         }
15798       /* *(foo *)&fooarray => fooarray[0] */
15799       else if (TREE_CODE (optype) == ARRAY_TYPE
15800                && type == TREE_TYPE (optype)
15801                && (!in_gimple_form
15802                    || TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST))
15803         {
15804           tree type_domain = TYPE_DOMAIN (optype);
15805           tree min_val = size_zero_node;
15806           if (type_domain && TYPE_MIN_VALUE (type_domain))
15807             min_val = TYPE_MIN_VALUE (type_domain);
15808           if (in_gimple_form
15809               && TREE_CODE (min_val) != INTEGER_CST)
15810             return NULL_TREE;
15811           return build4_loc (loc, ARRAY_REF, type, op, min_val,
15812                              NULL_TREE, NULL_TREE);
15813         }
15814       /* *(foo *)&complexfoo => __real__ complexfoo */
15815       else if (TREE_CODE (optype) == COMPLEX_TYPE
15816                && type == TREE_TYPE (optype))
15817         return fold_build1_loc (loc, REALPART_EXPR, type, op);
15818       /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
15819       else if (TREE_CODE (optype) == VECTOR_TYPE
15820                && type == TREE_TYPE (optype))
15821         {
15822           tree part_width = TYPE_SIZE (type);
15823           tree index = bitsize_int (0);
15824           return fold_build3_loc (loc, BIT_FIELD_REF, type, op, part_width, index);
15825         }
15826     }
15827
15828   if (TREE_CODE (sub) == POINTER_PLUS_EXPR
15829       && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST)
15830     {
15831       tree op00 = TREE_OPERAND (sub, 0);
15832       tree op01 = TREE_OPERAND (sub, 1);
15833
15834       STRIP_NOPS (op00);
15835       if (TREE_CODE (op00) == ADDR_EXPR)
15836         {
15837           tree op00type;
15838           op00 = TREE_OPERAND (op00, 0);
15839           op00type = TREE_TYPE (op00);
15840
15841           /* ((foo*)&vectorfoo)[1] => BIT_FIELD_REF<vectorfoo,...> */
15842           if (TREE_CODE (op00type) == VECTOR_TYPE
15843               && type == TREE_TYPE (op00type))
15844             {
15845               HOST_WIDE_INT offset = tree_to_shwi (op01);
15846               tree part_width = TYPE_SIZE (type);
15847               unsigned HOST_WIDE_INT part_widthi = tree_to_shwi (part_width)/BITS_PER_UNIT;
15848               unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT;
15849               tree index = bitsize_int (indexi);
15850
15851               if (offset / part_widthi < TYPE_VECTOR_SUBPARTS (op00type))
15852                 return fold_build3_loc (loc,
15853                                         BIT_FIELD_REF, type, op00,
15854                                         part_width, index);
15855
15856             }
15857           /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
15858           else if (TREE_CODE (op00type) == COMPLEX_TYPE
15859                    && type == TREE_TYPE (op00type))
15860             {
15861               tree size = TYPE_SIZE_UNIT (type);
15862               if (tree_int_cst_equal (size, op01))
15863                 return fold_build1_loc (loc, IMAGPART_EXPR, type, op00);
15864             }
15865           /* ((foo *)&fooarray)[1] => fooarray[1] */
15866           else if (TREE_CODE (op00type) == ARRAY_TYPE
15867                    && type == TREE_TYPE (op00type))
15868             {
15869               tree type_domain = TYPE_DOMAIN (op00type);
15870               tree min_val = size_zero_node;
15871               if (type_domain && TYPE_MIN_VALUE (type_domain))
15872                 min_val = TYPE_MIN_VALUE (type_domain);
15873               op01 = size_binop_loc (loc, EXACT_DIV_EXPR, op01,
15874                                      TYPE_SIZE_UNIT (type));
15875               op01 = size_binop_loc (loc, PLUS_EXPR, op01, min_val);
15876               return build4_loc (loc, ARRAY_REF, type, op00, op01,
15877                                  NULL_TREE, NULL_TREE);
15878             }
15879         }
15880     }
15881
15882   /* *(foo *)fooarrptr => (*fooarrptr)[0] */
15883   if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
15884       && type == TREE_TYPE (TREE_TYPE (subtype))
15885       && (!in_gimple_form
15886           || TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST))
15887     {
15888       tree type_domain;
15889       tree min_val = size_zero_node;
15890       sub = build_fold_indirect_ref_loc (loc, sub);
15891       type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
15892       if (type_domain && TYPE_MIN_VALUE (type_domain))
15893         min_val = TYPE_MIN_VALUE (type_domain);
15894       if (in_gimple_form
15895           && TREE_CODE (min_val) != INTEGER_CST)
15896         return NULL_TREE;
15897       return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
15898                          NULL_TREE);
15899     }
15900
15901   return NULL_TREE;
15902 }
15903
15904 /* Builds an expression for an indirection through T, simplifying some
15905    cases.  */
15906
15907 tree
15908 build_fold_indirect_ref_loc (location_t loc, tree t)
15909 {
15910   tree type = TREE_TYPE (TREE_TYPE (t));
15911   tree sub = fold_indirect_ref_1 (loc, type, t);
15912
15913   if (sub)
15914     return sub;
15915
15916   return build1_loc (loc, INDIRECT_REF, type, t);
15917 }
15918
15919 /* Given an INDIRECT_REF T, return either T or a simplified version.  */
15920
15921 tree
15922 fold_indirect_ref_loc (location_t loc, tree t)
15923 {
15924   tree sub = fold_indirect_ref_1 (loc, TREE_TYPE (t), TREE_OPERAND (t, 0));
15925
15926   if (sub)
15927     return sub;
15928   else
15929     return t;
15930 }
15931
15932 /* Strip non-trapping, non-side-effecting tree nodes from an expression
15933    whose result is ignored.  The type of the returned tree need not be
15934    the same as the original expression.  */
15935
15936 tree
15937 fold_ignored_result (tree t)
15938 {
15939   if (!TREE_SIDE_EFFECTS (t))
15940     return integer_zero_node;
15941
15942   for (;;)
15943     switch (TREE_CODE_CLASS (TREE_CODE (t)))
15944       {
15945       case tcc_unary:
15946         t = TREE_OPERAND (t, 0);
15947         break;
15948
15949       case tcc_binary:
15950       case tcc_comparison:
15951         if (!TREE_SIDE_EFFECTS (TREE_OPERAND (t, 1)))
15952           t = TREE_OPERAND (t, 0);
15953         else if (!TREE_SIDE_EFFECTS (TREE_OPERAND (t, 0)))
15954           t = TREE_OPERAND (t, 1);
15955         else
15956           return t;
15957         break;
15958
15959       case tcc_expression:
15960         switch (TREE_CODE (t))
15961           {
15962           case COMPOUND_EXPR:
15963             if (TREE_SIDE_EFFECTS (TREE_OPERAND (t, 1)))
15964               return t;
15965             t = TREE_OPERAND (t, 0);
15966             break;
15967
15968           case COND_EXPR:
15969             if (TREE_SIDE_EFFECTS (TREE_OPERAND (t, 1))
15970                 || TREE_SIDE_EFFECTS (TREE_OPERAND (t, 2)))
15971               return t;
15972             t = TREE_OPERAND (t, 0);
15973             break;
15974
15975           default:
15976             return t;
15977           }
15978         break;
15979
15980       default:
15981         return t;
15982       }
15983 }
15984
15985 /* Return the value of VALUE, rounded up to a multiple of DIVISOR. */
15986
15987 tree
15988 round_up_loc (location_t loc, tree value, unsigned int divisor)
15989 {
15990   tree div = NULL_TREE;
15991
15992   if (divisor == 1)
15993     return value;
15994
15995   /* See if VALUE is already a multiple of DIVISOR.  If so, we don't
15996      have to do anything.  Only do this when we are not given a const,
15997      because in that case, this check is more expensive than just
15998      doing it.  */
15999   if (TREE_CODE (value) != INTEGER_CST)
16000     {
16001       div = build_int_cst (TREE_TYPE (value), divisor);
16002
16003       if (multiple_of_p (TREE_TYPE (value), value, div))
16004         return value;
16005     }
16006
16007   /* If divisor is a power of two, simplify this to bit manipulation.  */
16008   if (divisor == (divisor & -divisor))
16009     {
16010       if (TREE_CODE (value) == INTEGER_CST)
16011         {
16012           wide_int val = value;
16013           bool overflow_p;
16014
16015           if ((val & (divisor - 1)) == 0)
16016             return value;
16017
16018           overflow_p = TREE_OVERFLOW (value);
16019           val &= ~(divisor - 1);
16020           val += divisor;
16021           if (val == 0)
16022             overflow_p = true;
16023
16024           return force_fit_type (TREE_TYPE (value), val, -1, overflow_p);
16025         }
16026       else
16027         {
16028           tree t;
16029
16030           t = build_int_cst (TREE_TYPE (value), divisor - 1);
16031           value = size_binop_loc (loc, PLUS_EXPR, value, t);
16032           t = build_int_cst (TREE_TYPE (value), -divisor);
16033           value = size_binop_loc (loc, BIT_AND_EXPR, value, t);
16034         }
16035     }
16036   else
16037     {
16038       if (!div)
16039         div = build_int_cst (TREE_TYPE (value), divisor);
16040       value = size_binop_loc (loc, CEIL_DIV_EXPR, value, div);
16041       value = size_binop_loc (loc, MULT_EXPR, value, div);
16042     }
16043
16044   return value;
16045 }
16046
16047 /* Likewise, but round down.  */
16048
16049 tree
16050 round_down_loc (location_t loc, tree value, int divisor)
16051 {
16052   tree div = NULL_TREE;
16053
16054   gcc_assert (divisor > 0);
16055   if (divisor == 1)
16056     return value;
16057
16058   /* See if VALUE is already a multiple of DIVISOR.  If so, we don't
16059      have to do anything.  Only do this when we are not given a const,
16060      because in that case, this check is more expensive than just
16061      doing it.  */
16062   if (TREE_CODE (value) != INTEGER_CST)
16063     {
16064       div = build_int_cst (TREE_TYPE (value), divisor);
16065
16066       if (multiple_of_p (TREE_TYPE (value), value, div))
16067         return value;
16068     }
16069
16070   /* If divisor is a power of two, simplify this to bit manipulation.  */
16071   if (divisor == (divisor & -divisor))
16072     {
16073       tree t;
16074
16075       t = build_int_cst (TREE_TYPE (value), -divisor);
16076       value = size_binop_loc (loc, BIT_AND_EXPR, value, t);
16077     }
16078   else
16079     {
16080       if (!div)
16081         div = build_int_cst (TREE_TYPE (value), divisor);
16082       value = size_binop_loc (loc, FLOOR_DIV_EXPR, value, div);
16083       value = size_binop_loc (loc, MULT_EXPR, value, div);
16084     }
16085
16086   return value;
16087 }
16088
16089 /* Returns the pointer to the base of the object addressed by EXP and
16090    extracts the information about the offset of the access, storing it
16091    to PBITPOS and POFFSET.  */
16092
16093 static tree
16094 split_address_to_core_and_offset (tree exp,
16095                                   HOST_WIDE_INT *pbitpos, tree *poffset)
16096 {
16097   tree core;
16098   machine_mode mode;
16099   int unsignedp, volatilep;
16100   HOST_WIDE_INT bitsize;
16101   location_t loc = EXPR_LOCATION (exp);
16102
16103   if (TREE_CODE (exp) == ADDR_EXPR)
16104     {
16105       core = get_inner_reference (TREE_OPERAND (exp, 0), &bitsize, pbitpos,
16106                                   poffset, &mode, &unsignedp, &volatilep,
16107                                   false);
16108       core = build_fold_addr_expr_loc (loc, core);
16109     }
16110   else
16111     {
16112       core = exp;
16113       *pbitpos = 0;
16114       *poffset = NULL_TREE;
16115     }
16116
16117   return core;
16118 }
16119
16120 /* Returns true if addresses of E1 and E2 differ by a constant, false
16121    otherwise.  If they do, E1 - E2 is stored in *DIFF.  */
16122
16123 bool
16124 ptr_difference_const (tree e1, tree e2, HOST_WIDE_INT *diff)
16125 {
16126   tree core1, core2;
16127   HOST_WIDE_INT bitpos1, bitpos2;
16128   tree toffset1, toffset2, tdiff, type;
16129
16130   core1 = split_address_to_core_and_offset (e1, &bitpos1, &toffset1);
16131   core2 = split_address_to_core_and_offset (e2, &bitpos2, &toffset2);
16132
16133   if (bitpos1 % BITS_PER_UNIT != 0
16134       || bitpos2 % BITS_PER_UNIT != 0
16135       || !operand_equal_p (core1, core2, 0))
16136     return false;
16137
16138   if (toffset1 && toffset2)
16139     {
16140       type = TREE_TYPE (toffset1);
16141       if (type != TREE_TYPE (toffset2))
16142         toffset2 = fold_convert (type, toffset2);
16143
16144       tdiff = fold_build2 (MINUS_EXPR, type, toffset1, toffset2);
16145       if (!cst_and_fits_in_hwi (tdiff))
16146         return false;
16147
16148       *diff = int_cst_value (tdiff);
16149     }
16150   else if (toffset1 || toffset2)
16151     {
16152       /* If only one of the offsets is non-constant, the difference cannot
16153          be a constant.  */
16154       return false;
16155     }
16156   else
16157     *diff = 0;
16158
16159   *diff += (bitpos1 - bitpos2) / BITS_PER_UNIT;
16160   return true;
16161 }
16162
16163 /* Simplify the floating point expression EXP when the sign of the
16164    result is not significant.  Return NULL_TREE if no simplification
16165    is possible.  */
16166
16167 tree
16168 fold_strip_sign_ops (tree exp)
16169 {
16170   tree arg0, arg1;
16171   location_t loc = EXPR_LOCATION (exp);
16172
16173   switch (TREE_CODE (exp))
16174     {
16175     case ABS_EXPR:
16176     case NEGATE_EXPR:
16177       arg0 = fold_strip_sign_ops (TREE_OPERAND (exp, 0));
16178       return arg0 ? arg0 : TREE_OPERAND (exp, 0);
16179
16180     case MULT_EXPR:
16181     case RDIV_EXPR:
16182       if (HONOR_SIGN_DEPENDENT_ROUNDING (element_mode (exp)))
16183         return NULL_TREE;
16184       arg0 = fold_strip_sign_ops (TREE_OPERAND (exp, 0));
16185       arg1 = fold_strip_sign_ops (TREE_OPERAND (exp, 1));
16186       if (arg0 != NULL_TREE || arg1 != NULL_TREE)
16187         return fold_build2_loc (loc, TREE_CODE (exp), TREE_TYPE (exp),
16188                             arg0 ? arg0 : TREE_OPERAND (exp, 0),
16189                             arg1 ? arg1 : TREE_OPERAND (exp, 1));
16190       break;
16191
16192     case COMPOUND_EXPR:
16193       arg0 = TREE_OPERAND (exp, 0);
16194       arg1 = fold_strip_sign_ops (TREE_OPERAND (exp, 1));
16195       if (arg1)
16196         return fold_build2_loc (loc, COMPOUND_EXPR, TREE_TYPE (exp), arg0, arg1);
16197       break;
16198
16199     case COND_EXPR:
16200       arg0 = fold_strip_sign_ops (TREE_OPERAND (exp, 1));
16201       arg1 = fold_strip_sign_ops (TREE_OPERAND (exp, 2));
16202       if (arg0 || arg1)
16203         return fold_build3_loc (loc,
16204                             COND_EXPR, TREE_TYPE (exp), TREE_OPERAND (exp, 0),
16205                             arg0 ? arg0 : TREE_OPERAND (exp, 1),
16206                             arg1 ? arg1 : TREE_OPERAND (exp, 2));
16207       break;
16208
16209     case CALL_EXPR:
16210       {
16211         const enum built_in_function fcode = builtin_mathfn_code (exp);
16212         switch (fcode)
16213         {
16214         CASE_FLT_FN (BUILT_IN_COPYSIGN):
16215           /* Strip copysign function call, return the 1st argument. */
16216           arg0 = CALL_EXPR_ARG (exp, 0);
16217           arg1 = CALL_EXPR_ARG (exp, 1);
16218           return omit_one_operand_loc (loc, TREE_TYPE (exp), arg0, arg1);
16219
16220         default:
16221           /* Strip sign ops from the argument of "odd" math functions.  */
16222           if (negate_mathfn_p (fcode))
16223             {
16224               arg0 = fold_strip_sign_ops (CALL_EXPR_ARG (exp, 0));
16225               if (arg0)
16226                 return build_call_expr_loc (loc, get_callee_fndecl (exp), 1, arg0);
16227             }
16228           break;
16229         }
16230       }
16231       break;
16232
16233     default:
16234       break;
16235     }
16236   return NULL_TREE;
16237 }
16238
16239 /* Return OFF converted to a pointer offset type suitable as offset for
16240    POINTER_PLUS_EXPR.  Use location LOC for this conversion.  */
16241 tree
16242 convert_to_ptrofftype_loc (location_t loc, tree off)
16243 {
16244   return fold_convert_loc (loc, sizetype, off);
16245 }
16246
16247 /* Build and fold a POINTER_PLUS_EXPR at LOC offsetting PTR by OFF.  */
16248 tree
16249 fold_build_pointer_plus_loc (location_t loc, tree ptr, tree off)
16250 {
16251   return fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (ptr),
16252                           ptr, convert_to_ptrofftype_loc (loc, off));
16253 }
16254
16255 /* Build and fold a POINTER_PLUS_EXPR at LOC offsetting PTR by OFF.  */
16256 tree
16257 fold_build_pointer_plus_hwi_loc (location_t loc, tree ptr, HOST_WIDE_INT off)
16258 {
16259   return fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (ptr),
16260                           ptr, size_int (off));
16261 }