OSDN Git Service

205d586fc3328cd4d045cb3f6e2405286cbabeb6
[pf3gnuchains/gcc-fork.git] / gcc / builtins.c
1 /* Expand builtin functions.
2    Copyright (C) 1988, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
3    2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
4    Free Software Foundation, Inc.
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "machmode.h"
27 #include "rtl.h"
28 #include "tree.h"
29 #include "realmpfr.h"
30 #include "gimple.h"
31 #include "flags.h"
32 #include "regs.h"
33 #include "hard-reg-set.h"
34 #include "except.h"
35 #include "function.h"
36 #include "insn-config.h"
37 #include "expr.h"
38 #include "optabs.h"
39 #include "libfuncs.h"
40 #include "recog.h"
41 #include "output.h"
42 #include "typeclass.h"
43 #include "predict.h"
44 #include "tm_p.h"
45 #include "target.h"
46 #include "langhooks.h"
47 #include "basic-block.h"
48 #include "tree-mudflap.h"
49 #include "tree-flow.h"
50 #include "value-prof.h"
51 #include "diagnostic-core.h"
52 #include "builtins.h"
53
54
55 #ifndef PAD_VARARGS_DOWN
56 #define PAD_VARARGS_DOWN BYTES_BIG_ENDIAN
57 #endif
58 static tree do_mpc_arg1 (tree, tree, int (*)(mpc_ptr, mpc_srcptr, mpc_rnd_t));
59
60 struct target_builtins default_target_builtins;
61 #if SWITCHABLE_TARGET
62 struct target_builtins *this_target_builtins = &default_target_builtins;
63 #endif
64
65 /* Define the names of the builtin function types and codes.  */
66 const char *const built_in_class_names[4]
67   = {"NOT_BUILT_IN", "BUILT_IN_FRONTEND", "BUILT_IN_MD", "BUILT_IN_NORMAL"};
68
69 #define DEF_BUILTIN(X, N, C, T, LT, B, F, NA, AT, IM, COND) #X,
70 const char * built_in_names[(int) END_BUILTINS] =
71 {
72 #include "builtins.def"
73 };
74 #undef DEF_BUILTIN
75
76 /* Setup an array of _DECL trees, make sure each element is
77    initialized to NULL_TREE.  */
78 builtin_info_type builtin_info;
79
80 static const char *c_getstr (tree);
81 static rtx c_readstr (const char *, enum machine_mode);
82 static int target_char_cast (tree, char *);
83 static rtx get_memory_rtx (tree, tree);
84 static int apply_args_size (void);
85 static int apply_result_size (void);
86 #if defined (HAVE_untyped_call) || defined (HAVE_untyped_return)
87 static rtx result_vector (int, rtx);
88 #endif
89 static void expand_builtin_update_setjmp_buf (rtx);
90 static void expand_builtin_prefetch (tree);
91 static rtx expand_builtin_apply_args (void);
92 static rtx expand_builtin_apply_args_1 (void);
93 static rtx expand_builtin_apply (rtx, rtx, rtx);
94 static void expand_builtin_return (rtx);
95 static enum type_class type_to_class (tree);
96 static rtx expand_builtin_classify_type (tree);
97 static void expand_errno_check (tree, rtx);
98 static rtx expand_builtin_mathfn (tree, rtx, rtx);
99 static rtx expand_builtin_mathfn_2 (tree, rtx, rtx);
100 static rtx expand_builtin_mathfn_3 (tree, rtx, rtx);
101 static rtx expand_builtin_mathfn_ternary (tree, rtx, rtx);
102 static rtx expand_builtin_interclass_mathfn (tree, rtx);
103 static rtx expand_builtin_sincos (tree);
104 static rtx expand_builtin_cexpi (tree, rtx);
105 static rtx expand_builtin_int_roundingfn (tree, rtx);
106 static rtx expand_builtin_int_roundingfn_2 (tree, rtx);
107 static rtx expand_builtin_next_arg (void);
108 static rtx expand_builtin_va_start (tree);
109 static rtx expand_builtin_va_end (tree);
110 static rtx expand_builtin_va_copy (tree);
111 static rtx expand_builtin_memcmp (tree, rtx, enum machine_mode);
112 static rtx expand_builtin_strcmp (tree, rtx);
113 static rtx expand_builtin_strncmp (tree, rtx, enum machine_mode);
114 static rtx builtin_memcpy_read_str (void *, HOST_WIDE_INT, enum machine_mode);
115 static rtx expand_builtin_memcpy (tree, rtx);
116 static rtx expand_builtin_mempcpy (tree, rtx, enum machine_mode);
117 static rtx expand_builtin_mempcpy_args (tree, tree, tree, rtx,
118                                         enum machine_mode, int);
119 static rtx expand_builtin_strcpy (tree, rtx);
120 static rtx expand_builtin_strcpy_args (tree, tree, rtx);
121 static rtx expand_builtin_stpcpy (tree, rtx, enum machine_mode);
122 static rtx expand_builtin_strncpy (tree, rtx);
123 static rtx builtin_memset_gen_str (void *, HOST_WIDE_INT, enum machine_mode);
124 static rtx expand_builtin_memset (tree, rtx, enum machine_mode);
125 static rtx expand_builtin_memset_args (tree, tree, tree, rtx, enum machine_mode, tree);
126 static rtx expand_builtin_bzero (tree);
127 static rtx expand_builtin_strlen (tree, rtx, enum machine_mode);
128 static rtx expand_builtin_alloca (tree, bool);
129 static rtx expand_builtin_unop (enum machine_mode, tree, rtx, rtx, optab);
130 static rtx expand_builtin_frame_address (tree, tree);
131 static tree stabilize_va_list_loc (location_t, tree, int);
132 static rtx expand_builtin_expect (tree, rtx);
133 static tree fold_builtin_constant_p (tree);
134 static tree fold_builtin_expect (location_t, tree, tree);
135 static tree fold_builtin_classify_type (tree);
136 static tree fold_builtin_strlen (location_t, tree, tree);
137 static tree fold_builtin_inf (location_t, tree, int);
138 static tree fold_builtin_nan (tree, tree, int);
139 static tree rewrite_call_expr (location_t, tree, int, tree, int, ...);
140 static bool validate_arg (const_tree, enum tree_code code);
141 static bool integer_valued_real_p (tree);
142 static tree fold_trunc_transparent_mathfn (location_t, tree, tree);
143 static bool readonly_data_expr (tree);
144 static rtx expand_builtin_fabs (tree, rtx, rtx);
145 static rtx expand_builtin_signbit (tree, rtx);
146 static tree fold_builtin_sqrt (location_t, tree, tree);
147 static tree fold_builtin_cbrt (location_t, tree, tree);
148 static tree fold_builtin_pow (location_t, tree, tree, tree, tree);
149 static tree fold_builtin_powi (location_t, tree, tree, tree, tree);
150 static tree fold_builtin_cos (location_t, tree, tree, tree);
151 static tree fold_builtin_cosh (location_t, tree, tree, tree);
152 static tree fold_builtin_tan (tree, tree);
153 static tree fold_builtin_trunc (location_t, tree, tree);
154 static tree fold_builtin_floor (location_t, tree, tree);
155 static tree fold_builtin_ceil (location_t, tree, tree);
156 static tree fold_builtin_round (location_t, tree, tree);
157 static tree fold_builtin_int_roundingfn (location_t, tree, tree);
158 static tree fold_builtin_bitop (tree, tree);
159 static tree fold_builtin_memory_op (location_t, tree, tree, tree, tree, bool, int);
160 static tree fold_builtin_strchr (location_t, tree, tree, tree);
161 static tree fold_builtin_memchr (location_t, tree, tree, tree, tree);
162 static tree fold_builtin_memcmp (location_t, tree, tree, tree);
163 static tree fold_builtin_strcmp (location_t, tree, tree);
164 static tree fold_builtin_strncmp (location_t, tree, tree, tree);
165 static tree fold_builtin_signbit (location_t, tree, tree);
166 static tree fold_builtin_copysign (location_t, tree, tree, tree, tree);
167 static tree fold_builtin_isascii (location_t, tree);
168 static tree fold_builtin_toascii (location_t, tree);
169 static tree fold_builtin_isdigit (location_t, tree);
170 static tree fold_builtin_fabs (location_t, tree, tree);
171 static tree fold_builtin_abs (location_t, tree, tree);
172 static tree fold_builtin_unordered_cmp (location_t, tree, tree, tree, enum tree_code,
173                                         enum tree_code);
174 static tree fold_builtin_n (location_t, tree, tree *, int, bool);
175 static tree fold_builtin_0 (location_t, tree, bool);
176 static tree fold_builtin_1 (location_t, tree, tree, bool);
177 static tree fold_builtin_2 (location_t, tree, tree, tree, bool);
178 static tree fold_builtin_3 (location_t, tree, tree, tree, tree, bool);
179 static tree fold_builtin_4 (location_t, tree, tree, tree, tree, tree, bool);
180 static tree fold_builtin_varargs (location_t, tree, tree, bool);
181
182 static tree fold_builtin_strpbrk (location_t, tree, tree, tree);
183 static tree fold_builtin_strstr (location_t, tree, tree, tree);
184 static tree fold_builtin_strrchr (location_t, tree, tree, tree);
185 static tree fold_builtin_strcat (location_t, tree, tree);
186 static tree fold_builtin_strncat (location_t, tree, tree, tree);
187 static tree fold_builtin_strspn (location_t, tree, tree);
188 static tree fold_builtin_strcspn (location_t, tree, tree);
189 static tree fold_builtin_sprintf (location_t, tree, tree, tree, int);
190 static tree fold_builtin_snprintf (location_t, tree, tree, tree, tree, int);
191
192 static rtx expand_builtin_object_size (tree);
193 static rtx expand_builtin_memory_chk (tree, rtx, enum machine_mode,
194                                       enum built_in_function);
195 static void maybe_emit_chk_warning (tree, enum built_in_function);
196 static void maybe_emit_sprintf_chk_warning (tree, enum built_in_function);
197 static void maybe_emit_free_warning (tree);
198 static tree fold_builtin_object_size (tree, tree);
199 static tree fold_builtin_strcat_chk (location_t, tree, tree, tree, tree);
200 static tree fold_builtin_strncat_chk (location_t, tree, tree, tree, tree, tree);
201 static tree fold_builtin_sprintf_chk (location_t, tree, enum built_in_function);
202 static tree fold_builtin_printf (location_t, tree, tree, tree, bool, enum built_in_function);
203 static tree fold_builtin_fprintf (location_t, tree, tree, tree, tree, bool,
204                                   enum built_in_function);
205 static bool init_target_chars (void);
206
207 static unsigned HOST_WIDE_INT target_newline;
208 static unsigned HOST_WIDE_INT target_percent;
209 static unsigned HOST_WIDE_INT target_c;
210 static unsigned HOST_WIDE_INT target_s;
211 static char target_percent_c[3];
212 static char target_percent_s[3];
213 static char target_percent_s_newline[4];
214 static tree do_mpfr_arg1 (tree, tree, int (*)(mpfr_ptr, mpfr_srcptr, mp_rnd_t),
215                           const REAL_VALUE_TYPE *, const REAL_VALUE_TYPE *, bool);
216 static tree do_mpfr_arg2 (tree, tree, tree,
217                           int (*)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t));
218 static tree do_mpfr_arg3 (tree, tree, tree, tree,
219                           int (*)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t));
220 static tree do_mpfr_sincos (tree, tree, tree);
221 static tree do_mpfr_bessel_n (tree, tree, tree,
222                               int (*)(mpfr_ptr, long, mpfr_srcptr, mp_rnd_t),
223                               const REAL_VALUE_TYPE *, bool);
224 static tree do_mpfr_remquo (tree, tree, tree);
225 static tree do_mpfr_lgamma_r (tree, tree, tree);
226 static void expand_builtin_sync_synchronize (void);
227
228 /* Return true if NAME starts with __builtin_ or __sync_.  */
229
230 bool
231 is_builtin_name (const char *name)
232 {
233   if (strncmp (name, "__builtin_", 10) == 0)
234     return true;
235   if (strncmp (name, "__sync_", 7) == 0)
236     return true;
237   if (strncmp (name, "__atomic_", 9) == 0)
238     return true;
239   return false;
240 }
241
242
243 /* Return true if DECL is a function symbol representing a built-in.  */
244
245 bool
246 is_builtin_fn (tree decl)
247 {
248   return TREE_CODE (decl) == FUNCTION_DECL && DECL_BUILT_IN (decl);
249 }
250
251
252 /* Return true if NODE should be considered for inline expansion regardless
253    of the optimization level.  This means whenever a function is invoked with
254    its "internal" name, which normally contains the prefix "__builtin".  */
255
256 static bool
257 called_as_built_in (tree node)
258 {
259   /* Note that we must use DECL_NAME, not DECL_ASSEMBLER_NAME_SET_P since
260      we want the name used to call the function, not the name it
261      will have. */
262   const char *name = IDENTIFIER_POINTER (DECL_NAME (node));
263   return is_builtin_name (name);
264 }
265
266 /* Compute values M and N such that M divides (address of EXP - N) and
267    such that N < M.  Store N in *BITPOSP and return M.
268
269    Note that the address (and thus the alignment) computed here is based
270    on the address to which a symbol resolves, whereas DECL_ALIGN is based
271    on the address at which an object is actually located.  These two
272    addresses are not always the same.  For example, on ARM targets,
273    the address &foo of a Thumb function foo() has the lowest bit set,
274    whereas foo() itself starts on an even address.  */
275
276 unsigned int
277 get_object_alignment_1 (tree exp, unsigned HOST_WIDE_INT *bitposp)
278 {
279   HOST_WIDE_INT bitsize, bitpos;
280   tree offset;
281   enum machine_mode mode;
282   int unsignedp, volatilep;
283   unsigned int align, inner;
284
285   /* Get the innermost object and the constant (bitpos) and possibly
286      variable (offset) offset of the access.  */
287   exp = get_inner_reference (exp, &bitsize, &bitpos, &offset,
288                              &mode, &unsignedp, &volatilep, true);
289
290   /* Extract alignment information from the innermost object and
291      possibly adjust bitpos and offset.  */
292   if (TREE_CODE (exp) == CONST_DECL)
293     exp = DECL_INITIAL (exp);
294   if (DECL_P (exp)
295       && TREE_CODE (exp) != LABEL_DECL)
296     {
297       if (TREE_CODE (exp) == FUNCTION_DECL)
298         {
299           /* Function addresses can encode extra information besides their
300              alignment.  However, if TARGET_PTRMEMFUNC_VBIT_LOCATION
301              allows the low bit to be used as a virtual bit, we know
302              that the address itself must be 2-byte aligned.  */
303           if (TARGET_PTRMEMFUNC_VBIT_LOCATION == ptrmemfunc_vbit_in_pfn)
304             align = 2 * BITS_PER_UNIT;
305           else
306             align = BITS_PER_UNIT;
307         }
308       else
309         align = DECL_ALIGN (exp);
310     }
311   else if (CONSTANT_CLASS_P (exp))
312     {
313       align = TYPE_ALIGN (TREE_TYPE (exp));
314 #ifdef CONSTANT_ALIGNMENT
315       align = (unsigned)CONSTANT_ALIGNMENT (exp, align);
316 #endif
317     }
318   else if (TREE_CODE (exp) == VIEW_CONVERT_EXPR)
319     align = TYPE_ALIGN (TREE_TYPE (exp));
320   else if (TREE_CODE (exp) == INDIRECT_REF)
321     align = TYPE_ALIGN (TREE_TYPE (exp));
322   else if (TREE_CODE (exp) == MEM_REF)
323     {
324       tree addr = TREE_OPERAND (exp, 0);
325       struct ptr_info_def *pi;
326       if (TREE_CODE (addr) == BIT_AND_EXPR
327           && TREE_CODE (TREE_OPERAND (addr, 1)) == INTEGER_CST)
328         {
329           align = (TREE_INT_CST_LOW (TREE_OPERAND (addr, 1))
330                     & -TREE_INT_CST_LOW (TREE_OPERAND (addr, 1)));
331           align *= BITS_PER_UNIT;
332           addr = TREE_OPERAND (addr, 0);
333         }
334       else
335         align = BITS_PER_UNIT;
336       if (TREE_CODE (addr) == SSA_NAME
337           && (pi = SSA_NAME_PTR_INFO (addr)))
338         {
339           bitpos += (pi->misalign * BITS_PER_UNIT) & ~(align - 1);
340           align = MAX (pi->align * BITS_PER_UNIT, align);
341         }
342       else if (TREE_CODE (addr) == ADDR_EXPR)
343         align = MAX (align, get_object_alignment (TREE_OPERAND (addr, 0)));
344       bitpos += mem_ref_offset (exp).low * BITS_PER_UNIT;
345     }
346   else if (TREE_CODE (exp) == TARGET_MEM_REF)
347     {
348       struct ptr_info_def *pi;
349       tree addr = TMR_BASE (exp);
350       if (TREE_CODE (addr) == BIT_AND_EXPR
351           && TREE_CODE (TREE_OPERAND (addr, 1)) == INTEGER_CST)
352         {
353           align = (TREE_INT_CST_LOW (TREE_OPERAND (addr, 1))
354                    & -TREE_INT_CST_LOW (TREE_OPERAND (addr, 1)));
355           align *= BITS_PER_UNIT;
356           addr = TREE_OPERAND (addr, 0);
357         }
358       else
359         align = BITS_PER_UNIT;
360       if (TREE_CODE (addr) == SSA_NAME
361           && (pi = SSA_NAME_PTR_INFO (addr)))
362         {
363           bitpos += (pi->misalign * BITS_PER_UNIT) & ~(align - 1);
364           align = MAX (pi->align * BITS_PER_UNIT, align);
365         }
366       else if (TREE_CODE (addr) == ADDR_EXPR)
367         align = MAX (align, get_object_alignment (TREE_OPERAND (addr, 0)));
368       if (TMR_OFFSET (exp))
369         bitpos += TREE_INT_CST_LOW (TMR_OFFSET (exp)) * BITS_PER_UNIT;
370       if (TMR_INDEX (exp) && TMR_STEP (exp))
371         {
372           unsigned HOST_WIDE_INT step = TREE_INT_CST_LOW (TMR_STEP (exp));
373           align = MIN (align, (step & -step) * BITS_PER_UNIT);
374         }
375       else if (TMR_INDEX (exp))
376         align = BITS_PER_UNIT;
377       if (TMR_INDEX2 (exp))
378         align = BITS_PER_UNIT;
379     }
380   else
381     align = BITS_PER_UNIT;
382
383   /* If there is a non-constant offset part extract the maximum
384      alignment that can prevail.  */
385   inner = ~0U;
386   while (offset)
387     {
388       tree next_offset;
389
390       if (TREE_CODE (offset) == PLUS_EXPR)
391         {
392           next_offset = TREE_OPERAND (offset, 0);
393           offset = TREE_OPERAND (offset, 1);
394         }
395       else
396         next_offset = NULL;
397       if (host_integerp (offset, 1))
398         {
399           /* Any overflow in calculating offset_bits won't change
400              the alignment.  */
401           unsigned offset_bits
402             = ((unsigned) tree_low_cst (offset, 1) * BITS_PER_UNIT);
403
404           if (offset_bits)
405             inner = MIN (inner, (offset_bits & -offset_bits));
406         }
407       else if (TREE_CODE (offset) == MULT_EXPR
408                && host_integerp (TREE_OPERAND (offset, 1), 1))
409         {
410           /* Any overflow in calculating offset_factor won't change
411              the alignment.  */
412           unsigned offset_factor
413             = ((unsigned) tree_low_cst (TREE_OPERAND (offset, 1), 1)
414                * BITS_PER_UNIT);
415
416           if (offset_factor)
417             inner = MIN (inner, (offset_factor & -offset_factor));
418         }
419       else
420         {
421           inner = MIN (inner, BITS_PER_UNIT);
422           break;
423         }
424       offset = next_offset;
425     }
426
427   /* Alignment is innermost object alignment adjusted by the constant
428      and non-constant offset parts.  */
429   align = MIN (align, inner);
430   bitpos = bitpos & (align - 1);
431
432   *bitposp = bitpos;
433   return align;
434 }
435
436 /* Return the alignment in bits of EXP, an object.  */
437
438 unsigned int
439 get_object_alignment (tree exp)
440 {
441   unsigned HOST_WIDE_INT bitpos = 0;
442   unsigned int align;
443
444   align = get_object_alignment_1 (exp, &bitpos);
445
446   /* align and bitpos now specify known low bits of the pointer.
447      ptr & (align - 1) == bitpos.  */
448
449   if (bitpos != 0)
450     align = (bitpos & -bitpos);
451
452   return align;
453 }
454
455 /* Return the alignment in bits of EXP, a pointer valued expression.
456    The alignment returned is, by default, the alignment of the thing that
457    EXP points to.  If it is not a POINTER_TYPE, 0 is returned.
458
459    Otherwise, look at the expression to see if we can do better, i.e., if the
460    expression is actually pointing at an object whose alignment is tighter.  */
461
462 unsigned int
463 get_pointer_alignment (tree exp)
464 {
465   STRIP_NOPS (exp);
466
467   if (TREE_CODE (exp) == ADDR_EXPR)
468     return get_object_alignment (TREE_OPERAND (exp, 0));
469   else if (TREE_CODE (exp) == SSA_NAME
470            && POINTER_TYPE_P (TREE_TYPE (exp)))
471     {
472       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (exp);
473       unsigned align;
474       if (!pi)
475         return BITS_PER_UNIT;
476       if (pi->misalign != 0)
477         align = (pi->misalign & -pi->misalign);
478       else
479         align = pi->align;
480       return align * BITS_PER_UNIT;
481     }
482
483   return POINTER_TYPE_P (TREE_TYPE (exp)) ? BITS_PER_UNIT : 0;
484 }
485
486 /* Compute the length of a C string.  TREE_STRING_LENGTH is not the right
487    way, because it could contain a zero byte in the middle.
488    TREE_STRING_LENGTH is the size of the character array, not the string.
489
490    ONLY_VALUE should be nonzero if the result is not going to be emitted
491    into the instruction stream and zero if it is going to be expanded.
492    E.g. with i++ ? "foo" : "bar", if ONLY_VALUE is nonzero, constant 3
493    is returned, otherwise NULL, since
494    len = c_strlen (src, 1); if (len) expand_expr (len, ...); would not
495    evaluate the side-effects.
496
497    The value returned is of type `ssizetype'.
498
499    Unfortunately, string_constant can't access the values of const char
500    arrays with initializers, so neither can we do so here.  */
501
502 tree
503 c_strlen (tree src, int only_value)
504 {
505   tree offset_node;
506   HOST_WIDE_INT offset;
507   int max;
508   const char *ptr;
509   location_t loc;
510
511   STRIP_NOPS (src);
512   if (TREE_CODE (src) == COND_EXPR
513       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
514     {
515       tree len1, len2;
516
517       len1 = c_strlen (TREE_OPERAND (src, 1), only_value);
518       len2 = c_strlen (TREE_OPERAND (src, 2), only_value);
519       if (tree_int_cst_equal (len1, len2))
520         return len1;
521     }
522
523   if (TREE_CODE (src) == COMPOUND_EXPR
524       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
525     return c_strlen (TREE_OPERAND (src, 1), only_value);
526
527   loc = EXPR_LOC_OR_HERE (src);
528
529   src = string_constant (src, &offset_node);
530   if (src == 0)
531     return NULL_TREE;
532
533   max = TREE_STRING_LENGTH (src) - 1;
534   ptr = TREE_STRING_POINTER (src);
535
536   if (offset_node && TREE_CODE (offset_node) != INTEGER_CST)
537     {
538       /* If the string has an internal zero byte (e.g., "foo\0bar"), we can't
539          compute the offset to the following null if we don't know where to
540          start searching for it.  */
541       int i;
542
543       for (i = 0; i < max; i++)
544         if (ptr[i] == 0)
545           return NULL_TREE;
546
547       /* We don't know the starting offset, but we do know that the string
548          has no internal zero bytes.  We can assume that the offset falls
549          within the bounds of the string; otherwise, the programmer deserves
550          what he gets.  Subtract the offset from the length of the string,
551          and return that.  This would perhaps not be valid if we were dealing
552          with named arrays in addition to literal string constants.  */
553
554       return size_diffop_loc (loc, size_int (max), offset_node);
555     }
556
557   /* We have a known offset into the string.  Start searching there for
558      a null character if we can represent it as a single HOST_WIDE_INT.  */
559   if (offset_node == 0)
560     offset = 0;
561   else if (! host_integerp (offset_node, 0))
562     offset = -1;
563   else
564     offset = tree_low_cst (offset_node, 0);
565
566   /* If the offset is known to be out of bounds, warn, and call strlen at
567      runtime.  */
568   if (offset < 0 || offset > max)
569     {
570      /* Suppress multiple warnings for propagated constant strings.  */
571       if (! TREE_NO_WARNING (src))
572         {
573           warning_at (loc, 0, "offset outside bounds of constant string");
574           TREE_NO_WARNING (src) = 1;
575         }
576       return NULL_TREE;
577     }
578
579   /* Use strlen to search for the first zero byte.  Since any strings
580      constructed with build_string will have nulls appended, we win even
581      if we get handed something like (char[4])"abcd".
582
583      Since OFFSET is our starting index into the string, no further
584      calculation is needed.  */
585   return ssize_int (strlen (ptr + offset));
586 }
587
588 /* Return a char pointer for a C string if it is a string constant
589    or sum of string constant and integer constant.  */
590
591 static const char *
592 c_getstr (tree src)
593 {
594   tree offset_node;
595
596   src = string_constant (src, &offset_node);
597   if (src == 0)
598     return 0;
599
600   if (offset_node == 0)
601     return TREE_STRING_POINTER (src);
602   else if (!host_integerp (offset_node, 1)
603            || compare_tree_int (offset_node, TREE_STRING_LENGTH (src) - 1) > 0)
604     return 0;
605
606   return TREE_STRING_POINTER (src) + tree_low_cst (offset_node, 1);
607 }
608
609 /* Return a CONST_INT or CONST_DOUBLE corresponding to target reading
610    GET_MODE_BITSIZE (MODE) bits from string constant STR.  */
611
612 static rtx
613 c_readstr (const char *str, enum machine_mode mode)
614 {
615   HOST_WIDE_INT c[2];
616   HOST_WIDE_INT ch;
617   unsigned int i, j;
618
619   gcc_assert (GET_MODE_CLASS (mode) == MODE_INT);
620
621   c[0] = 0;
622   c[1] = 0;
623   ch = 1;
624   for (i = 0; i < GET_MODE_SIZE (mode); i++)
625     {
626       j = i;
627       if (WORDS_BIG_ENDIAN)
628         j = GET_MODE_SIZE (mode) - i - 1;
629       if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN
630           && GET_MODE_SIZE (mode) >= UNITS_PER_WORD)
631         j = j + UNITS_PER_WORD - 2 * (j % UNITS_PER_WORD) - 1;
632       j *= BITS_PER_UNIT;
633       gcc_assert (j < 2 * HOST_BITS_PER_WIDE_INT);
634
635       if (ch)
636         ch = (unsigned char) str[i];
637       c[j / HOST_BITS_PER_WIDE_INT] |= ch << (j % HOST_BITS_PER_WIDE_INT);
638     }
639   return immed_double_const (c[0], c[1], mode);
640 }
641
642 /* Cast a target constant CST to target CHAR and if that value fits into
643    host char type, return zero and put that value into variable pointed to by
644    P.  */
645
646 static int
647 target_char_cast (tree cst, char *p)
648 {
649   unsigned HOST_WIDE_INT val, hostval;
650
651   if (TREE_CODE (cst) != INTEGER_CST
652       || CHAR_TYPE_SIZE > HOST_BITS_PER_WIDE_INT)
653     return 1;
654
655   val = TREE_INT_CST_LOW (cst);
656   if (CHAR_TYPE_SIZE < HOST_BITS_PER_WIDE_INT)
657     val &= (((unsigned HOST_WIDE_INT) 1) << CHAR_TYPE_SIZE) - 1;
658
659   hostval = val;
660   if (HOST_BITS_PER_CHAR < HOST_BITS_PER_WIDE_INT)
661     hostval &= (((unsigned HOST_WIDE_INT) 1) << HOST_BITS_PER_CHAR) - 1;
662
663   if (val != hostval)
664     return 1;
665
666   *p = hostval;
667   return 0;
668 }
669
670 /* Similar to save_expr, but assumes that arbitrary code is not executed
671    in between the multiple evaluations.  In particular, we assume that a
672    non-addressable local variable will not be modified.  */
673
674 static tree
675 builtin_save_expr (tree exp)
676 {
677   if (TREE_CODE (exp) == SSA_NAME
678       || (TREE_ADDRESSABLE (exp) == 0
679           && (TREE_CODE (exp) == PARM_DECL
680               || (TREE_CODE (exp) == VAR_DECL && !TREE_STATIC (exp)))))
681     return exp;
682
683   return save_expr (exp);
684 }
685
686 /* Given TEM, a pointer to a stack frame, follow the dynamic chain COUNT
687    times to get the address of either a higher stack frame, or a return
688    address located within it (depending on FNDECL_CODE).  */
689
690 static rtx
691 expand_builtin_return_addr (enum built_in_function fndecl_code, int count)
692 {
693   int i;
694
695 #ifdef INITIAL_FRAME_ADDRESS_RTX
696   rtx tem = INITIAL_FRAME_ADDRESS_RTX;
697 #else
698   rtx tem;
699
700   /* For a zero count with __builtin_return_address, we don't care what
701      frame address we return, because target-specific definitions will
702      override us.  Therefore frame pointer elimination is OK, and using
703      the soft frame pointer is OK.
704
705      For a nonzero count, or a zero count with __builtin_frame_address,
706      we require a stable offset from the current frame pointer to the
707      previous one, so we must use the hard frame pointer, and
708      we must disable frame pointer elimination.  */
709   if (count == 0 && fndecl_code == BUILT_IN_RETURN_ADDRESS)
710     tem = frame_pointer_rtx;
711   else
712     {
713       tem = hard_frame_pointer_rtx;
714
715       /* Tell reload not to eliminate the frame pointer.  */
716       crtl->accesses_prior_frames = 1;
717     }
718 #endif
719
720   /* Some machines need special handling before we can access
721      arbitrary frames.  For example, on the SPARC, we must first flush
722      all register windows to the stack.  */
723 #ifdef SETUP_FRAME_ADDRESSES
724   if (count > 0)
725     SETUP_FRAME_ADDRESSES ();
726 #endif
727
728   /* On the SPARC, the return address is not in the frame, it is in a
729      register.  There is no way to access it off of the current frame
730      pointer, but it can be accessed off the previous frame pointer by
731      reading the value from the register window save area.  */
732 #ifdef RETURN_ADDR_IN_PREVIOUS_FRAME
733   if (fndecl_code == BUILT_IN_RETURN_ADDRESS)
734     count--;
735 #endif
736
737   /* Scan back COUNT frames to the specified frame.  */
738   for (i = 0; i < count; i++)
739     {
740       /* Assume the dynamic chain pointer is in the word that the
741          frame address points to, unless otherwise specified.  */
742 #ifdef DYNAMIC_CHAIN_ADDRESS
743       tem = DYNAMIC_CHAIN_ADDRESS (tem);
744 #endif
745       tem = memory_address (Pmode, tem);
746       tem = gen_frame_mem (Pmode, tem);
747       tem = copy_to_reg (tem);
748     }
749
750   /* For __builtin_frame_address, return what we've got.  But, on
751      the SPARC for example, we may have to add a bias.  */
752   if (fndecl_code == BUILT_IN_FRAME_ADDRESS)
753 #ifdef FRAME_ADDR_RTX
754     return FRAME_ADDR_RTX (tem);
755 #else
756     return tem;
757 #endif
758
759   /* For __builtin_return_address, get the return address from that frame.  */
760 #ifdef RETURN_ADDR_RTX
761   tem = RETURN_ADDR_RTX (count, tem);
762 #else
763   tem = memory_address (Pmode,
764                         plus_constant (tem, GET_MODE_SIZE (Pmode)));
765   tem = gen_frame_mem (Pmode, tem);
766 #endif
767   return tem;
768 }
769
770 /* Alias set used for setjmp buffer.  */
771 static alias_set_type setjmp_alias_set = -1;
772
773 /* Construct the leading half of a __builtin_setjmp call.  Control will
774    return to RECEIVER_LABEL.  This is also called directly by the SJLJ
775    exception handling code.  */
776
777 void
778 expand_builtin_setjmp_setup (rtx buf_addr, rtx receiver_label)
779 {
780   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
781   rtx stack_save;
782   rtx mem;
783
784   if (setjmp_alias_set == -1)
785     setjmp_alias_set = new_alias_set ();
786
787   buf_addr = convert_memory_address (Pmode, buf_addr);
788
789   buf_addr = force_reg (Pmode, force_operand (buf_addr, NULL_RTX));
790
791   /* We store the frame pointer and the address of receiver_label in
792      the buffer and use the rest of it for the stack save area, which
793      is machine-dependent.  */
794
795   mem = gen_rtx_MEM (Pmode, buf_addr);
796   set_mem_alias_set (mem, setjmp_alias_set);
797   emit_move_insn (mem, targetm.builtin_setjmp_frame_value ());
798
799   mem = gen_rtx_MEM (Pmode, plus_constant (buf_addr, GET_MODE_SIZE (Pmode))),
800   set_mem_alias_set (mem, setjmp_alias_set);
801
802   emit_move_insn (validize_mem (mem),
803                   force_reg (Pmode, gen_rtx_LABEL_REF (Pmode, receiver_label)));
804
805   stack_save = gen_rtx_MEM (sa_mode,
806                             plus_constant (buf_addr,
807                                            2 * GET_MODE_SIZE (Pmode)));
808   set_mem_alias_set (stack_save, setjmp_alias_set);
809   emit_stack_save (SAVE_NONLOCAL, &stack_save);
810
811   /* If there is further processing to do, do it.  */
812 #ifdef HAVE_builtin_setjmp_setup
813   if (HAVE_builtin_setjmp_setup)
814     emit_insn (gen_builtin_setjmp_setup (buf_addr));
815 #endif
816
817   /* We have a nonlocal label.   */
818   cfun->has_nonlocal_label = 1;
819 }
820
821 /* Construct the trailing part of a __builtin_setjmp call.  This is
822    also called directly by the SJLJ exception handling code.  */
823
824 void
825 expand_builtin_setjmp_receiver (rtx receiver_label ATTRIBUTE_UNUSED)
826 {
827   rtx chain;
828
829   /* Clobber the FP when we get here, so we have to make sure it's
830      marked as used by this function.  */
831   emit_use (hard_frame_pointer_rtx);
832
833   /* Mark the static chain as clobbered here so life information
834      doesn't get messed up for it.  */
835   chain = targetm.calls.static_chain (current_function_decl, true);
836   if (chain && REG_P (chain))
837     emit_clobber (chain);
838
839   /* Now put in the code to restore the frame pointer, and argument
840      pointer, if needed.  */
841 #ifdef HAVE_nonlocal_goto
842   if (! HAVE_nonlocal_goto)
843 #endif
844     {
845       emit_move_insn (virtual_stack_vars_rtx, hard_frame_pointer_rtx);
846       /* This might change the hard frame pointer in ways that aren't
847          apparent to early optimization passes, so force a clobber.  */
848       emit_clobber (hard_frame_pointer_rtx);
849     }
850
851 #if !HARD_FRAME_POINTER_IS_ARG_POINTER
852   if (fixed_regs[ARG_POINTER_REGNUM])
853     {
854 #ifdef ELIMINABLE_REGS
855       size_t i;
856       static const struct elims {const int from, to;} elim_regs[] = ELIMINABLE_REGS;
857
858       for (i = 0; i < ARRAY_SIZE (elim_regs); i++)
859         if (elim_regs[i].from == ARG_POINTER_REGNUM
860             && elim_regs[i].to == HARD_FRAME_POINTER_REGNUM)
861           break;
862
863       if (i == ARRAY_SIZE (elim_regs))
864 #endif
865         {
866           /* Now restore our arg pointer from the address at which it
867              was saved in our stack frame.  */
868           emit_move_insn (crtl->args.internal_arg_pointer,
869                           copy_to_reg (get_arg_pointer_save_area ()));
870         }
871     }
872 #endif
873
874 #ifdef HAVE_builtin_setjmp_receiver
875   if (HAVE_builtin_setjmp_receiver)
876     emit_insn (gen_builtin_setjmp_receiver (receiver_label));
877   else
878 #endif
879 #ifdef HAVE_nonlocal_goto_receiver
880     if (HAVE_nonlocal_goto_receiver)
881       emit_insn (gen_nonlocal_goto_receiver ());
882     else
883 #endif
884       { /* Nothing */ }
885
886   /* We must not allow the code we just generated to be reordered by
887      scheduling.  Specifically, the update of the frame pointer must
888      happen immediately, not later.  */
889   emit_insn (gen_blockage ());
890 }
891
892 /* __builtin_longjmp is passed a pointer to an array of five words (not
893    all will be used on all machines).  It operates similarly to the C
894    library function of the same name, but is more efficient.  Much of
895    the code below is copied from the handling of non-local gotos.  */
896
897 static void
898 expand_builtin_longjmp (rtx buf_addr, rtx value)
899 {
900   rtx fp, lab, stack, insn, last;
901   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
902
903   /* DRAP is needed for stack realign if longjmp is expanded to current
904      function  */
905   if (SUPPORTS_STACK_ALIGNMENT)
906     crtl->need_drap = true;
907
908   if (setjmp_alias_set == -1)
909     setjmp_alias_set = new_alias_set ();
910
911   buf_addr = convert_memory_address (Pmode, buf_addr);
912
913   buf_addr = force_reg (Pmode, buf_addr);
914
915   /* We require that the user must pass a second argument of 1, because
916      that is what builtin_setjmp will return.  */
917   gcc_assert (value == const1_rtx);
918
919   last = get_last_insn ();
920 #ifdef HAVE_builtin_longjmp
921   if (HAVE_builtin_longjmp)
922     emit_insn (gen_builtin_longjmp (buf_addr));
923   else
924 #endif
925     {
926       fp = gen_rtx_MEM (Pmode, buf_addr);
927       lab = gen_rtx_MEM (Pmode, plus_constant (buf_addr,
928                                                GET_MODE_SIZE (Pmode)));
929
930       stack = gen_rtx_MEM (sa_mode, plus_constant (buf_addr,
931                                                    2 * GET_MODE_SIZE (Pmode)));
932       set_mem_alias_set (fp, setjmp_alias_set);
933       set_mem_alias_set (lab, setjmp_alias_set);
934       set_mem_alias_set (stack, setjmp_alias_set);
935
936       /* Pick up FP, label, and SP from the block and jump.  This code is
937          from expand_goto in stmt.c; see there for detailed comments.  */
938 #ifdef HAVE_nonlocal_goto
939       if (HAVE_nonlocal_goto)
940         /* We have to pass a value to the nonlocal_goto pattern that will
941            get copied into the static_chain pointer, but it does not matter
942            what that value is, because builtin_setjmp does not use it.  */
943         emit_insn (gen_nonlocal_goto (value, lab, stack, fp));
944       else
945 #endif
946         {
947           lab = copy_to_reg (lab);
948
949           emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
950           emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
951
952           emit_move_insn (hard_frame_pointer_rtx, fp);
953           emit_stack_restore (SAVE_NONLOCAL, stack);
954
955           emit_use (hard_frame_pointer_rtx);
956           emit_use (stack_pointer_rtx);
957           emit_indirect_jump (lab);
958         }
959     }
960
961   /* Search backwards and mark the jump insn as a non-local goto.
962      Note that this precludes the use of __builtin_longjmp to a
963      __builtin_setjmp target in the same function.  However, we've
964      already cautioned the user that these functions are for
965      internal exception handling use only.  */
966   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
967     {
968       gcc_assert (insn != last);
969
970       if (JUMP_P (insn))
971         {
972           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
973           break;
974         }
975       else if (CALL_P (insn))
976         break;
977     }
978 }
979
980 /* Expand a call to __builtin_nonlocal_goto.  We're passed the target label
981    and the address of the save area.  */
982
983 static rtx
984 expand_builtin_nonlocal_goto (tree exp)
985 {
986   tree t_label, t_save_area;
987   rtx r_label, r_save_area, r_fp, r_sp, insn;
988
989   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
990     return NULL_RTX;
991
992   t_label = CALL_EXPR_ARG (exp, 0);
993   t_save_area = CALL_EXPR_ARG (exp, 1);
994
995   r_label = expand_normal (t_label);
996   r_label = convert_memory_address (Pmode, r_label);
997   r_save_area = expand_normal (t_save_area);
998   r_save_area = convert_memory_address (Pmode, r_save_area);
999   /* Copy the address of the save location to a register just in case it was
1000      based on the frame pointer.   */
1001   r_save_area = copy_to_reg (r_save_area);
1002   r_fp = gen_rtx_MEM (Pmode, r_save_area);
1003   r_sp = gen_rtx_MEM (STACK_SAVEAREA_MODE (SAVE_NONLOCAL),
1004                       plus_constant (r_save_area, GET_MODE_SIZE (Pmode)));
1005
1006   crtl->has_nonlocal_goto = 1;
1007
1008 #ifdef HAVE_nonlocal_goto
1009   /* ??? We no longer need to pass the static chain value, afaik.  */
1010   if (HAVE_nonlocal_goto)
1011     emit_insn (gen_nonlocal_goto (const0_rtx, r_label, r_sp, r_fp));
1012   else
1013 #endif
1014     {
1015       r_label = copy_to_reg (r_label);
1016
1017       emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
1018       emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
1019
1020       /* Restore frame pointer for containing function.  */
1021       emit_move_insn (hard_frame_pointer_rtx, r_fp);
1022       emit_stack_restore (SAVE_NONLOCAL, r_sp);
1023
1024       /* USE of hard_frame_pointer_rtx added for consistency;
1025          not clear if really needed.  */
1026       emit_use (hard_frame_pointer_rtx);
1027       emit_use (stack_pointer_rtx);
1028
1029       /* If the architecture is using a GP register, we must
1030          conservatively assume that the target function makes use of it.
1031          The prologue of functions with nonlocal gotos must therefore
1032          initialize the GP register to the appropriate value, and we
1033          must then make sure that this value is live at the point
1034          of the jump.  (Note that this doesn't necessarily apply
1035          to targets with a nonlocal_goto pattern; they are free
1036          to implement it in their own way.  Note also that this is
1037          a no-op if the GP register is a global invariant.)  */
1038       if ((unsigned) PIC_OFFSET_TABLE_REGNUM != INVALID_REGNUM
1039           && fixed_regs[PIC_OFFSET_TABLE_REGNUM])
1040         emit_use (pic_offset_table_rtx);
1041
1042       emit_indirect_jump (r_label);
1043     }
1044
1045   /* Search backwards to the jump insn and mark it as a
1046      non-local goto.  */
1047   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
1048     {
1049       if (JUMP_P (insn))
1050         {
1051           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
1052           break;
1053         }
1054       else if (CALL_P (insn))
1055         break;
1056     }
1057
1058   return const0_rtx;
1059 }
1060
1061 /* __builtin_update_setjmp_buf is passed a pointer to an array of five words
1062    (not all will be used on all machines) that was passed to __builtin_setjmp.
1063    It updates the stack pointer in that block to correspond to the current
1064    stack pointer.  */
1065
1066 static void
1067 expand_builtin_update_setjmp_buf (rtx buf_addr)
1068 {
1069   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
1070   rtx stack_save
1071     = gen_rtx_MEM (sa_mode,
1072                    memory_address
1073                    (sa_mode,
1074                     plus_constant (buf_addr, 2 * GET_MODE_SIZE (Pmode))));
1075
1076   emit_stack_save (SAVE_NONLOCAL, &stack_save);
1077 }
1078
1079 /* Expand a call to __builtin_prefetch.  For a target that does not support
1080    data prefetch, evaluate the memory address argument in case it has side
1081    effects.  */
1082
1083 static void
1084 expand_builtin_prefetch (tree exp)
1085 {
1086   tree arg0, arg1, arg2;
1087   int nargs;
1088   rtx op0, op1, op2;
1089
1090   if (!validate_arglist (exp, POINTER_TYPE, 0))
1091     return;
1092
1093   arg0 = CALL_EXPR_ARG (exp, 0);
1094
1095   /* Arguments 1 and 2 are optional; argument 1 (read/write) defaults to
1096      zero (read) and argument 2 (locality) defaults to 3 (high degree of
1097      locality).  */
1098   nargs = call_expr_nargs (exp);
1099   if (nargs > 1)
1100     arg1 = CALL_EXPR_ARG (exp, 1);
1101   else
1102     arg1 = integer_zero_node;
1103   if (nargs > 2)
1104     arg2 = CALL_EXPR_ARG (exp, 2);
1105   else
1106     arg2 = integer_three_node;
1107
1108   /* Argument 0 is an address.  */
1109   op0 = expand_expr (arg0, NULL_RTX, Pmode, EXPAND_NORMAL);
1110
1111   /* Argument 1 (read/write flag) must be a compile-time constant int.  */
1112   if (TREE_CODE (arg1) != INTEGER_CST)
1113     {
1114       error ("second argument to %<__builtin_prefetch%> must be a constant");
1115       arg1 = integer_zero_node;
1116     }
1117   op1 = expand_normal (arg1);
1118   /* Argument 1 must be either zero or one.  */
1119   if (INTVAL (op1) != 0 && INTVAL (op1) != 1)
1120     {
1121       warning (0, "invalid second argument to %<__builtin_prefetch%>;"
1122                " using zero");
1123       op1 = const0_rtx;
1124     }
1125
1126   /* Argument 2 (locality) must be a compile-time constant int.  */
1127   if (TREE_CODE (arg2) != INTEGER_CST)
1128     {
1129       error ("third argument to %<__builtin_prefetch%> must be a constant");
1130       arg2 = integer_zero_node;
1131     }
1132   op2 = expand_normal (arg2);
1133   /* Argument 2 must be 0, 1, 2, or 3.  */
1134   if (INTVAL (op2) < 0 || INTVAL (op2) > 3)
1135     {
1136       warning (0, "invalid third argument to %<__builtin_prefetch%>; using zero");
1137       op2 = const0_rtx;
1138     }
1139
1140 #ifdef HAVE_prefetch
1141   if (HAVE_prefetch)
1142     {
1143       struct expand_operand ops[3];
1144
1145       create_address_operand (&ops[0], op0);
1146       create_integer_operand (&ops[1], INTVAL (op1));
1147       create_integer_operand (&ops[2], INTVAL (op2));
1148       if (maybe_expand_insn (CODE_FOR_prefetch, 3, ops))
1149         return;
1150     }
1151 #endif
1152
1153   /* Don't do anything with direct references to volatile memory, but
1154      generate code to handle other side effects.  */
1155   if (!MEM_P (op0) && side_effects_p (op0))
1156     emit_insn (op0);
1157 }
1158
1159 /* Get a MEM rtx for expression EXP which is the address of an operand
1160    to be used in a string instruction (cmpstrsi, movmemsi, ..).  LEN is
1161    the maximum length of the block of memory that might be accessed or
1162    NULL if unknown.  */
1163
1164 static rtx
1165 get_memory_rtx (tree exp, tree len)
1166 {
1167   tree orig_exp = exp;
1168   rtx addr, mem;
1169   HOST_WIDE_INT off;
1170
1171   /* When EXP is not resolved SAVE_EXPR, MEM_ATTRS can be still derived
1172      from its expression, for expr->a.b only <variable>.a.b is recorded.  */
1173   if (TREE_CODE (exp) == SAVE_EXPR && !SAVE_EXPR_RESOLVED_P (exp))
1174     exp = TREE_OPERAND (exp, 0);
1175
1176   addr = expand_expr (orig_exp, NULL_RTX, ptr_mode, EXPAND_NORMAL);
1177   mem = gen_rtx_MEM (BLKmode, memory_address (BLKmode, addr));
1178
1179   /* Get an expression we can use to find the attributes to assign to MEM.
1180      If it is an ADDR_EXPR, use the operand.  Otherwise, dereference it if
1181      we can.  First remove any nops.  */
1182   while (CONVERT_EXPR_P (exp)
1183          && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (exp, 0))))
1184     exp = TREE_OPERAND (exp, 0);
1185
1186   off = 0;
1187   if (TREE_CODE (exp) == POINTER_PLUS_EXPR
1188       && TREE_CODE (TREE_OPERAND (exp, 0)) == ADDR_EXPR
1189       && host_integerp (TREE_OPERAND (exp, 1), 0)
1190       && (off = tree_low_cst (TREE_OPERAND (exp, 1), 0)) > 0)
1191     exp = TREE_OPERAND (TREE_OPERAND (exp, 0), 0);
1192   else if (TREE_CODE (exp) == ADDR_EXPR)
1193     exp = TREE_OPERAND (exp, 0);
1194   else if (POINTER_TYPE_P (TREE_TYPE (exp)))
1195     exp = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (exp)), exp);
1196   else
1197     exp = NULL;
1198
1199   /* Honor attributes derived from exp, except for the alias set
1200      (as builtin stringops may alias with anything) and the size
1201      (as stringops may access multiple array elements).  */
1202   if (exp)
1203     {
1204       set_mem_attributes (mem, exp, 0);
1205
1206       if (off)
1207         mem = adjust_automodify_address_nv (mem, BLKmode, NULL, off);
1208
1209       /* Allow the string and memory builtins to overflow from one
1210          field into another, see http://gcc.gnu.org/PR23561.
1211          Thus avoid COMPONENT_REFs in MEM_EXPR unless we know the whole
1212          memory accessed by the string or memory builtin will fit
1213          within the field.  */
1214       if (MEM_EXPR (mem) && TREE_CODE (MEM_EXPR (mem)) == COMPONENT_REF)
1215         {
1216           tree mem_expr = MEM_EXPR (mem);
1217           HOST_WIDE_INT offset = -1, length = -1;
1218           tree inner = exp;
1219
1220           while (TREE_CODE (inner) == ARRAY_REF
1221                  || CONVERT_EXPR_P (inner)
1222                  || TREE_CODE (inner) == VIEW_CONVERT_EXPR
1223                  || TREE_CODE (inner) == SAVE_EXPR)
1224             inner = TREE_OPERAND (inner, 0);
1225
1226           gcc_assert (TREE_CODE (inner) == COMPONENT_REF);
1227
1228           if (MEM_OFFSET_KNOWN_P (mem))
1229             offset = MEM_OFFSET (mem);
1230
1231           if (offset >= 0 && len && host_integerp (len, 0))
1232             length = tree_low_cst (len, 0);
1233
1234           while (TREE_CODE (inner) == COMPONENT_REF)
1235             {
1236               tree field = TREE_OPERAND (inner, 1);
1237               gcc_assert (TREE_CODE (mem_expr) == COMPONENT_REF);
1238               gcc_assert (field == TREE_OPERAND (mem_expr, 1));
1239
1240               /* Bitfields are generally not byte-addressable.  */
1241               gcc_assert (!DECL_BIT_FIELD (field)
1242                           || ((tree_low_cst (DECL_FIELD_BIT_OFFSET (field), 1)
1243                                % BITS_PER_UNIT) == 0
1244                               && host_integerp (DECL_SIZE (field), 0)
1245                               && (TREE_INT_CST_LOW (DECL_SIZE (field))
1246                                   % BITS_PER_UNIT) == 0));
1247
1248               /* If we can prove that the memory starting at XEXP (mem, 0) and
1249                  ending at XEXP (mem, 0) + LENGTH will fit into this field, we
1250                  can keep the COMPONENT_REF in MEM_EXPR.  But be careful with
1251                  fields without DECL_SIZE_UNIT like flexible array members.  */
1252               if (length >= 0
1253                   && DECL_SIZE_UNIT (field)
1254                   && host_integerp (DECL_SIZE_UNIT (field), 0))
1255                 {
1256                   HOST_WIDE_INT size
1257                     = TREE_INT_CST_LOW (DECL_SIZE_UNIT (field));
1258                   if (offset <= size
1259                       && length <= size
1260                       && offset + length <= size)
1261                     break;
1262                 }
1263
1264               if (offset >= 0
1265                   && host_integerp (DECL_FIELD_OFFSET (field), 0))
1266                 offset += TREE_INT_CST_LOW (DECL_FIELD_OFFSET (field))
1267                           + tree_low_cst (DECL_FIELD_BIT_OFFSET (field), 1)
1268                             / BITS_PER_UNIT;
1269               else
1270                 {
1271                   offset = -1;
1272                   length = -1;
1273                 }
1274
1275               mem_expr = TREE_OPERAND (mem_expr, 0);
1276               inner = TREE_OPERAND (inner, 0);
1277             }
1278
1279           if (mem_expr == NULL)
1280             offset = -1;
1281           if (mem_expr != MEM_EXPR (mem))
1282             {
1283               set_mem_expr (mem, mem_expr);
1284               if (offset >= 0)
1285                 set_mem_offset (mem, offset);
1286               else
1287                 clear_mem_offset (mem);
1288             }
1289         }
1290       set_mem_alias_set (mem, 0);
1291       clear_mem_size (mem);
1292     }
1293
1294   return mem;
1295 }
1296 \f
1297 /* Built-in functions to perform an untyped call and return.  */
1298
1299 #define apply_args_mode \
1300   (this_target_builtins->x_apply_args_mode)
1301 #define apply_result_mode \
1302   (this_target_builtins->x_apply_result_mode)
1303
1304 /* Return the size required for the block returned by __builtin_apply_args,
1305    and initialize apply_args_mode.  */
1306
1307 static int
1308 apply_args_size (void)
1309 {
1310   static int size = -1;
1311   int align;
1312   unsigned int regno;
1313   enum machine_mode mode;
1314
1315   /* The values computed by this function never change.  */
1316   if (size < 0)
1317     {
1318       /* The first value is the incoming arg-pointer.  */
1319       size = GET_MODE_SIZE (Pmode);
1320
1321       /* The second value is the structure value address unless this is
1322          passed as an "invisible" first argument.  */
1323       if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1324         size += GET_MODE_SIZE (Pmode);
1325
1326       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1327         if (FUNCTION_ARG_REGNO_P (regno))
1328           {
1329             mode = targetm.calls.get_raw_arg_mode (regno);
1330
1331             gcc_assert (mode != VOIDmode);
1332
1333             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1334             if (size % align != 0)
1335               size = CEIL (size, align) * align;
1336             size += GET_MODE_SIZE (mode);
1337             apply_args_mode[regno] = mode;
1338           }
1339         else
1340           {
1341             apply_args_mode[regno] = VOIDmode;
1342           }
1343     }
1344   return size;
1345 }
1346
1347 /* Return the size required for the block returned by __builtin_apply,
1348    and initialize apply_result_mode.  */
1349
1350 static int
1351 apply_result_size (void)
1352 {
1353   static int size = -1;
1354   int align, regno;
1355   enum machine_mode mode;
1356
1357   /* The values computed by this function never change.  */
1358   if (size < 0)
1359     {
1360       size = 0;
1361
1362       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1363         if (targetm.calls.function_value_regno_p (regno))
1364           {
1365             mode = targetm.calls.get_raw_result_mode (regno);
1366
1367             gcc_assert (mode != VOIDmode);
1368
1369             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1370             if (size % align != 0)
1371               size = CEIL (size, align) * align;
1372             size += GET_MODE_SIZE (mode);
1373             apply_result_mode[regno] = mode;
1374           }
1375         else
1376           apply_result_mode[regno] = VOIDmode;
1377
1378       /* Allow targets that use untyped_call and untyped_return to override
1379          the size so that machine-specific information can be stored here.  */
1380 #ifdef APPLY_RESULT_SIZE
1381       size = APPLY_RESULT_SIZE;
1382 #endif
1383     }
1384   return size;
1385 }
1386
1387 #if defined (HAVE_untyped_call) || defined (HAVE_untyped_return)
1388 /* Create a vector describing the result block RESULT.  If SAVEP is true,
1389    the result block is used to save the values; otherwise it is used to
1390    restore the values.  */
1391
1392 static rtx
1393 result_vector (int savep, rtx result)
1394 {
1395   int regno, size, align, nelts;
1396   enum machine_mode mode;
1397   rtx reg, mem;
1398   rtx *savevec = XALLOCAVEC (rtx, FIRST_PSEUDO_REGISTER);
1399
1400   size = nelts = 0;
1401   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1402     if ((mode = apply_result_mode[regno]) != VOIDmode)
1403       {
1404         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1405         if (size % align != 0)
1406           size = CEIL (size, align) * align;
1407         reg = gen_rtx_REG (mode, savep ? regno : INCOMING_REGNO (regno));
1408         mem = adjust_address (result, mode, size);
1409         savevec[nelts++] = (savep
1410                             ? gen_rtx_SET (VOIDmode, mem, reg)
1411                             : gen_rtx_SET (VOIDmode, reg, mem));
1412         size += GET_MODE_SIZE (mode);
1413       }
1414   return gen_rtx_PARALLEL (VOIDmode, gen_rtvec_v (nelts, savevec));
1415 }
1416 #endif /* HAVE_untyped_call or HAVE_untyped_return */
1417
1418 /* Save the state required to perform an untyped call with the same
1419    arguments as were passed to the current function.  */
1420
1421 static rtx
1422 expand_builtin_apply_args_1 (void)
1423 {
1424   rtx registers, tem;
1425   int size, align, regno;
1426   enum machine_mode mode;
1427   rtx struct_incoming_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 1);
1428
1429   /* Create a block where the arg-pointer, structure value address,
1430      and argument registers can be saved.  */
1431   registers = assign_stack_local (BLKmode, apply_args_size (), -1);
1432
1433   /* Walk past the arg-pointer and structure value address.  */
1434   size = GET_MODE_SIZE (Pmode);
1435   if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1436     size += GET_MODE_SIZE (Pmode);
1437
1438   /* Save each register used in calling a function to the block.  */
1439   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1440     if ((mode = apply_args_mode[regno]) != VOIDmode)
1441       {
1442         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1443         if (size % align != 0)
1444           size = CEIL (size, align) * align;
1445
1446         tem = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1447
1448         emit_move_insn (adjust_address (registers, mode, size), tem);
1449         size += GET_MODE_SIZE (mode);
1450       }
1451
1452   /* Save the arg pointer to the block.  */
1453   tem = copy_to_reg (crtl->args.internal_arg_pointer);
1454 #ifdef STACK_GROWS_DOWNWARD
1455   /* We need the pointer as the caller actually passed them to us, not
1456      as we might have pretended they were passed.  Make sure it's a valid
1457      operand, as emit_move_insn isn't expected to handle a PLUS.  */
1458   tem
1459     = force_operand (plus_constant (tem, crtl->args.pretend_args_size),
1460                      NULL_RTX);
1461 #endif
1462   emit_move_insn (adjust_address (registers, Pmode, 0), tem);
1463
1464   size = GET_MODE_SIZE (Pmode);
1465
1466   /* Save the structure value address unless this is passed as an
1467      "invisible" first argument.  */
1468   if (struct_incoming_value)
1469     {
1470       emit_move_insn (adjust_address (registers, Pmode, size),
1471                       copy_to_reg (struct_incoming_value));
1472       size += GET_MODE_SIZE (Pmode);
1473     }
1474
1475   /* Return the address of the block.  */
1476   return copy_addr_to_reg (XEXP (registers, 0));
1477 }
1478
1479 /* __builtin_apply_args returns block of memory allocated on
1480    the stack into which is stored the arg pointer, structure
1481    value address, static chain, and all the registers that might
1482    possibly be used in performing a function call.  The code is
1483    moved to the start of the function so the incoming values are
1484    saved.  */
1485
1486 static rtx
1487 expand_builtin_apply_args (void)
1488 {
1489   /* Don't do __builtin_apply_args more than once in a function.
1490      Save the result of the first call and reuse it.  */
1491   if (apply_args_value != 0)
1492     return apply_args_value;
1493   {
1494     /* When this function is called, it means that registers must be
1495        saved on entry to this function.  So we migrate the
1496        call to the first insn of this function.  */
1497     rtx temp;
1498     rtx seq;
1499
1500     start_sequence ();
1501     temp = expand_builtin_apply_args_1 ();
1502     seq = get_insns ();
1503     end_sequence ();
1504
1505     apply_args_value = temp;
1506
1507     /* Put the insns after the NOTE that starts the function.
1508        If this is inside a start_sequence, make the outer-level insn
1509        chain current, so the code is placed at the start of the
1510        function.  If internal_arg_pointer is a non-virtual pseudo,
1511        it needs to be placed after the function that initializes
1512        that pseudo.  */
1513     push_topmost_sequence ();
1514     if (REG_P (crtl->args.internal_arg_pointer)
1515         && REGNO (crtl->args.internal_arg_pointer) > LAST_VIRTUAL_REGISTER)
1516       emit_insn_before (seq, parm_birth_insn);
1517     else
1518       emit_insn_before (seq, NEXT_INSN (entry_of_function ()));
1519     pop_topmost_sequence ();
1520     return temp;
1521   }
1522 }
1523
1524 /* Perform an untyped call and save the state required to perform an
1525    untyped return of whatever value was returned by the given function.  */
1526
1527 static rtx
1528 expand_builtin_apply (rtx function, rtx arguments, rtx argsize)
1529 {
1530   int size, align, regno;
1531   enum machine_mode mode;
1532   rtx incoming_args, result, reg, dest, src, call_insn;
1533   rtx old_stack_level = 0;
1534   rtx call_fusage = 0;
1535   rtx struct_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0);
1536
1537   arguments = convert_memory_address (Pmode, arguments);
1538
1539   /* Create a block where the return registers can be saved.  */
1540   result = assign_stack_local (BLKmode, apply_result_size (), -1);
1541
1542   /* Fetch the arg pointer from the ARGUMENTS block.  */
1543   incoming_args = gen_reg_rtx (Pmode);
1544   emit_move_insn (incoming_args, gen_rtx_MEM (Pmode, arguments));
1545 #ifndef STACK_GROWS_DOWNWARD
1546   incoming_args = expand_simple_binop (Pmode, MINUS, incoming_args, argsize,
1547                                        incoming_args, 0, OPTAB_LIB_WIDEN);
1548 #endif
1549
1550   /* Push a new argument block and copy the arguments.  Do not allow
1551      the (potential) memcpy call below to interfere with our stack
1552      manipulations.  */
1553   do_pending_stack_adjust ();
1554   NO_DEFER_POP;
1555
1556   /* Save the stack with nonlocal if available.  */
1557 #ifdef HAVE_save_stack_nonlocal
1558   if (HAVE_save_stack_nonlocal)
1559     emit_stack_save (SAVE_NONLOCAL, &old_stack_level);
1560   else
1561 #endif
1562     emit_stack_save (SAVE_BLOCK, &old_stack_level);
1563
1564   /* Allocate a block of memory onto the stack and copy the memory
1565      arguments to the outgoing arguments address.  We can pass TRUE
1566      as the 4th argument because we just saved the stack pointer
1567      and will restore it right after the call.  */
1568   allocate_dynamic_stack_space (argsize, 0, BIGGEST_ALIGNMENT, true);
1569
1570   /* Set DRAP flag to true, even though allocate_dynamic_stack_space
1571      may have already set current_function_calls_alloca to true.
1572      current_function_calls_alloca won't be set if argsize is zero,
1573      so we have to guarantee need_drap is true here.  */
1574   if (SUPPORTS_STACK_ALIGNMENT)
1575     crtl->need_drap = true;
1576
1577   dest = virtual_outgoing_args_rtx;
1578 #ifndef STACK_GROWS_DOWNWARD
1579   if (CONST_INT_P (argsize))
1580     dest = plus_constant (dest, -INTVAL (argsize));
1581   else
1582     dest = gen_rtx_PLUS (Pmode, dest, negate_rtx (Pmode, argsize));
1583 #endif
1584   dest = gen_rtx_MEM (BLKmode, dest);
1585   set_mem_align (dest, PARM_BOUNDARY);
1586   src = gen_rtx_MEM (BLKmode, incoming_args);
1587   set_mem_align (src, PARM_BOUNDARY);
1588   emit_block_move (dest, src, argsize, BLOCK_OP_NORMAL);
1589
1590   /* Refer to the argument block.  */
1591   apply_args_size ();
1592   arguments = gen_rtx_MEM (BLKmode, arguments);
1593   set_mem_align (arguments, PARM_BOUNDARY);
1594
1595   /* Walk past the arg-pointer and structure value address.  */
1596   size = GET_MODE_SIZE (Pmode);
1597   if (struct_value)
1598     size += GET_MODE_SIZE (Pmode);
1599
1600   /* Restore each of the registers previously saved.  Make USE insns
1601      for each of these registers for use in making the call.  */
1602   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1603     if ((mode = apply_args_mode[regno]) != VOIDmode)
1604       {
1605         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1606         if (size % align != 0)
1607           size = CEIL (size, align) * align;
1608         reg = gen_rtx_REG (mode, regno);
1609         emit_move_insn (reg, adjust_address (arguments, mode, size));
1610         use_reg (&call_fusage, reg);
1611         size += GET_MODE_SIZE (mode);
1612       }
1613
1614   /* Restore the structure value address unless this is passed as an
1615      "invisible" first argument.  */
1616   size = GET_MODE_SIZE (Pmode);
1617   if (struct_value)
1618     {
1619       rtx value = gen_reg_rtx (Pmode);
1620       emit_move_insn (value, adjust_address (arguments, Pmode, size));
1621       emit_move_insn (struct_value, value);
1622       if (REG_P (struct_value))
1623         use_reg (&call_fusage, struct_value);
1624       size += GET_MODE_SIZE (Pmode);
1625     }
1626
1627   /* All arguments and registers used for the call are set up by now!  */
1628   function = prepare_call_address (NULL, function, NULL, &call_fusage, 0, 0);
1629
1630   /* Ensure address is valid.  SYMBOL_REF is already valid, so no need,
1631      and we don't want to load it into a register as an optimization,
1632      because prepare_call_address already did it if it should be done.  */
1633   if (GET_CODE (function) != SYMBOL_REF)
1634     function = memory_address (FUNCTION_MODE, function);
1635
1636   /* Generate the actual call instruction and save the return value.  */
1637 #ifdef HAVE_untyped_call
1638   if (HAVE_untyped_call)
1639     emit_call_insn (gen_untyped_call (gen_rtx_MEM (FUNCTION_MODE, function),
1640                                       result, result_vector (1, result)));
1641   else
1642 #endif
1643 #ifdef HAVE_call_value
1644   if (HAVE_call_value)
1645     {
1646       rtx valreg = 0;
1647
1648       /* Locate the unique return register.  It is not possible to
1649          express a call that sets more than one return register using
1650          call_value; use untyped_call for that.  In fact, untyped_call
1651          only needs to save the return registers in the given block.  */
1652       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1653         if ((mode = apply_result_mode[regno]) != VOIDmode)
1654           {
1655             gcc_assert (!valreg); /* HAVE_untyped_call required.  */
1656
1657             valreg = gen_rtx_REG (mode, regno);
1658           }
1659
1660       emit_call_insn (GEN_CALL_VALUE (valreg,
1661                                       gen_rtx_MEM (FUNCTION_MODE, function),
1662                                       const0_rtx, NULL_RTX, const0_rtx));
1663
1664       emit_move_insn (adjust_address (result, GET_MODE (valreg), 0), valreg);
1665     }
1666   else
1667 #endif
1668     gcc_unreachable ();
1669
1670   /* Find the CALL insn we just emitted, and attach the register usage
1671      information.  */
1672   call_insn = last_call_insn ();
1673   add_function_usage_to (call_insn, call_fusage);
1674
1675   /* Restore the stack.  */
1676 #ifdef HAVE_save_stack_nonlocal
1677   if (HAVE_save_stack_nonlocal)
1678     emit_stack_restore (SAVE_NONLOCAL, old_stack_level);
1679   else
1680 #endif
1681     emit_stack_restore (SAVE_BLOCK, old_stack_level);
1682   fixup_args_size_notes (call_insn, get_last_insn(), 0);
1683
1684   OK_DEFER_POP;
1685
1686   /* Return the address of the result block.  */
1687   result = copy_addr_to_reg (XEXP (result, 0));
1688   return convert_memory_address (ptr_mode, result);
1689 }
1690
1691 /* Perform an untyped return.  */
1692
1693 static void
1694 expand_builtin_return (rtx result)
1695 {
1696   int size, align, regno;
1697   enum machine_mode mode;
1698   rtx reg;
1699   rtx call_fusage = 0;
1700
1701   result = convert_memory_address (Pmode, result);
1702
1703   apply_result_size ();
1704   result = gen_rtx_MEM (BLKmode, result);
1705
1706 #ifdef HAVE_untyped_return
1707   if (HAVE_untyped_return)
1708     {
1709       emit_jump_insn (gen_untyped_return (result, result_vector (0, result)));
1710       emit_barrier ();
1711       return;
1712     }
1713 #endif
1714
1715   /* Restore the return value and note that each value is used.  */
1716   size = 0;
1717   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1718     if ((mode = apply_result_mode[regno]) != VOIDmode)
1719       {
1720         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1721         if (size % align != 0)
1722           size = CEIL (size, align) * align;
1723         reg = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1724         emit_move_insn (reg, adjust_address (result, mode, size));
1725
1726         push_to_sequence (call_fusage);
1727         emit_use (reg);
1728         call_fusage = get_insns ();
1729         end_sequence ();
1730         size += GET_MODE_SIZE (mode);
1731       }
1732
1733   /* Put the USE insns before the return.  */
1734   emit_insn (call_fusage);
1735
1736   /* Return whatever values was restored by jumping directly to the end
1737      of the function.  */
1738   expand_naked_return ();
1739 }
1740
1741 /* Used by expand_builtin_classify_type and fold_builtin_classify_type.  */
1742
1743 static enum type_class
1744 type_to_class (tree type)
1745 {
1746   switch (TREE_CODE (type))
1747     {
1748     case VOID_TYPE:        return void_type_class;
1749     case INTEGER_TYPE:     return integer_type_class;
1750     case ENUMERAL_TYPE:    return enumeral_type_class;
1751     case BOOLEAN_TYPE:     return boolean_type_class;
1752     case POINTER_TYPE:     return pointer_type_class;
1753     case REFERENCE_TYPE:   return reference_type_class;
1754     case OFFSET_TYPE:      return offset_type_class;
1755     case REAL_TYPE:        return real_type_class;
1756     case COMPLEX_TYPE:     return complex_type_class;
1757     case FUNCTION_TYPE:    return function_type_class;
1758     case METHOD_TYPE:      return method_type_class;
1759     case RECORD_TYPE:      return record_type_class;
1760     case UNION_TYPE:
1761     case QUAL_UNION_TYPE:  return union_type_class;
1762     case ARRAY_TYPE:       return (TYPE_STRING_FLAG (type)
1763                                    ? string_type_class : array_type_class);
1764     case LANG_TYPE:        return lang_type_class;
1765     default:               return no_type_class;
1766     }
1767 }
1768
1769 /* Expand a call EXP to __builtin_classify_type.  */
1770
1771 static rtx
1772 expand_builtin_classify_type (tree exp)
1773 {
1774   if (call_expr_nargs (exp))
1775     return GEN_INT (type_to_class (TREE_TYPE (CALL_EXPR_ARG (exp, 0))));
1776   return GEN_INT (no_type_class);
1777 }
1778
1779 /* This helper macro, meant to be used in mathfn_built_in below,
1780    determines which among a set of three builtin math functions is
1781    appropriate for a given type mode.  The `F' and `L' cases are
1782    automatically generated from the `double' case.  */
1783 #define CASE_MATHFN(BUILT_IN_MATHFN) \
1784   case BUILT_IN_MATHFN: case BUILT_IN_MATHFN##F: case BUILT_IN_MATHFN##L: \
1785   fcode = BUILT_IN_MATHFN; fcodef = BUILT_IN_MATHFN##F ; \
1786   fcodel = BUILT_IN_MATHFN##L ; break;
1787 /* Similar to above, but appends _R after any F/L suffix.  */
1788 #define CASE_MATHFN_REENT(BUILT_IN_MATHFN) \
1789   case BUILT_IN_MATHFN##_R: case BUILT_IN_MATHFN##F_R: case BUILT_IN_MATHFN##L_R: \
1790   fcode = BUILT_IN_MATHFN##_R; fcodef = BUILT_IN_MATHFN##F_R ; \
1791   fcodel = BUILT_IN_MATHFN##L_R ; break;
1792
1793 /* Return mathematic function equivalent to FN but operating directly on TYPE,
1794    if available.  If IMPLICIT is true use the implicit builtin declaration,
1795    otherwise use the explicit declaration.  If we can't do the conversion,
1796    return zero.  */
1797
1798 static tree
1799 mathfn_built_in_1 (tree type, enum built_in_function fn, bool implicit_p)
1800 {
1801   enum built_in_function fcode, fcodef, fcodel, fcode2;
1802
1803   switch (fn)
1804     {
1805       CASE_MATHFN (BUILT_IN_ACOS)
1806       CASE_MATHFN (BUILT_IN_ACOSH)
1807       CASE_MATHFN (BUILT_IN_ASIN)
1808       CASE_MATHFN (BUILT_IN_ASINH)
1809       CASE_MATHFN (BUILT_IN_ATAN)
1810       CASE_MATHFN (BUILT_IN_ATAN2)
1811       CASE_MATHFN (BUILT_IN_ATANH)
1812       CASE_MATHFN (BUILT_IN_CBRT)
1813       CASE_MATHFN (BUILT_IN_CEIL)
1814       CASE_MATHFN (BUILT_IN_CEXPI)
1815       CASE_MATHFN (BUILT_IN_COPYSIGN)
1816       CASE_MATHFN (BUILT_IN_COS)
1817       CASE_MATHFN (BUILT_IN_COSH)
1818       CASE_MATHFN (BUILT_IN_DREM)
1819       CASE_MATHFN (BUILT_IN_ERF)
1820       CASE_MATHFN (BUILT_IN_ERFC)
1821       CASE_MATHFN (BUILT_IN_EXP)
1822       CASE_MATHFN (BUILT_IN_EXP10)
1823       CASE_MATHFN (BUILT_IN_EXP2)
1824       CASE_MATHFN (BUILT_IN_EXPM1)
1825       CASE_MATHFN (BUILT_IN_FABS)
1826       CASE_MATHFN (BUILT_IN_FDIM)
1827       CASE_MATHFN (BUILT_IN_FLOOR)
1828       CASE_MATHFN (BUILT_IN_FMA)
1829       CASE_MATHFN (BUILT_IN_FMAX)
1830       CASE_MATHFN (BUILT_IN_FMIN)
1831       CASE_MATHFN (BUILT_IN_FMOD)
1832       CASE_MATHFN (BUILT_IN_FREXP)
1833       CASE_MATHFN (BUILT_IN_GAMMA)
1834       CASE_MATHFN_REENT (BUILT_IN_GAMMA) /* GAMMA_R */
1835       CASE_MATHFN (BUILT_IN_HUGE_VAL)
1836       CASE_MATHFN (BUILT_IN_HYPOT)
1837       CASE_MATHFN (BUILT_IN_ILOGB)
1838       CASE_MATHFN (BUILT_IN_ICEIL)
1839       CASE_MATHFN (BUILT_IN_IFLOOR)
1840       CASE_MATHFN (BUILT_IN_INF)
1841       CASE_MATHFN (BUILT_IN_IRINT)
1842       CASE_MATHFN (BUILT_IN_IROUND)
1843       CASE_MATHFN (BUILT_IN_ISINF)
1844       CASE_MATHFN (BUILT_IN_J0)
1845       CASE_MATHFN (BUILT_IN_J1)
1846       CASE_MATHFN (BUILT_IN_JN)
1847       CASE_MATHFN (BUILT_IN_LCEIL)
1848       CASE_MATHFN (BUILT_IN_LDEXP)
1849       CASE_MATHFN (BUILT_IN_LFLOOR)
1850       CASE_MATHFN (BUILT_IN_LGAMMA)
1851       CASE_MATHFN_REENT (BUILT_IN_LGAMMA) /* LGAMMA_R */
1852       CASE_MATHFN (BUILT_IN_LLCEIL)
1853       CASE_MATHFN (BUILT_IN_LLFLOOR)
1854       CASE_MATHFN (BUILT_IN_LLRINT)
1855       CASE_MATHFN (BUILT_IN_LLROUND)
1856       CASE_MATHFN (BUILT_IN_LOG)
1857       CASE_MATHFN (BUILT_IN_LOG10)
1858       CASE_MATHFN (BUILT_IN_LOG1P)
1859       CASE_MATHFN (BUILT_IN_LOG2)
1860       CASE_MATHFN (BUILT_IN_LOGB)
1861       CASE_MATHFN (BUILT_IN_LRINT)
1862       CASE_MATHFN (BUILT_IN_LROUND)
1863       CASE_MATHFN (BUILT_IN_MODF)
1864       CASE_MATHFN (BUILT_IN_NAN)
1865       CASE_MATHFN (BUILT_IN_NANS)
1866       CASE_MATHFN (BUILT_IN_NEARBYINT)
1867       CASE_MATHFN (BUILT_IN_NEXTAFTER)
1868       CASE_MATHFN (BUILT_IN_NEXTTOWARD)
1869       CASE_MATHFN (BUILT_IN_POW)
1870       CASE_MATHFN (BUILT_IN_POWI)
1871       CASE_MATHFN (BUILT_IN_POW10)
1872       CASE_MATHFN (BUILT_IN_REMAINDER)
1873       CASE_MATHFN (BUILT_IN_REMQUO)
1874       CASE_MATHFN (BUILT_IN_RINT)
1875       CASE_MATHFN (BUILT_IN_ROUND)
1876       CASE_MATHFN (BUILT_IN_SCALB)
1877       CASE_MATHFN (BUILT_IN_SCALBLN)
1878       CASE_MATHFN (BUILT_IN_SCALBN)
1879       CASE_MATHFN (BUILT_IN_SIGNBIT)
1880       CASE_MATHFN (BUILT_IN_SIGNIFICAND)
1881       CASE_MATHFN (BUILT_IN_SIN)
1882       CASE_MATHFN (BUILT_IN_SINCOS)
1883       CASE_MATHFN (BUILT_IN_SINH)
1884       CASE_MATHFN (BUILT_IN_SQRT)
1885       CASE_MATHFN (BUILT_IN_TAN)
1886       CASE_MATHFN (BUILT_IN_TANH)
1887       CASE_MATHFN (BUILT_IN_TGAMMA)
1888       CASE_MATHFN (BUILT_IN_TRUNC)
1889       CASE_MATHFN (BUILT_IN_Y0)
1890       CASE_MATHFN (BUILT_IN_Y1)
1891       CASE_MATHFN (BUILT_IN_YN)
1892
1893       default:
1894         return NULL_TREE;
1895       }
1896
1897   if (TYPE_MAIN_VARIANT (type) == double_type_node)
1898     fcode2 = fcode;
1899   else if (TYPE_MAIN_VARIANT (type) == float_type_node)
1900     fcode2 = fcodef;
1901   else if (TYPE_MAIN_VARIANT (type) == long_double_type_node)
1902     fcode2 = fcodel;
1903   else
1904     return NULL_TREE;
1905
1906   if (implicit_p && !builtin_decl_implicit_p (fcode2))
1907     return NULL_TREE;
1908
1909   return builtin_decl_explicit (fcode2);
1910 }
1911
1912 /* Like mathfn_built_in_1(), but always use the implicit array.  */
1913
1914 tree
1915 mathfn_built_in (tree type, enum built_in_function fn)
1916 {
1917   return mathfn_built_in_1 (type, fn, /*implicit=*/ 1);
1918 }
1919
1920 /* If errno must be maintained, expand the RTL to check if the result,
1921    TARGET, of a built-in function call, EXP, is NaN, and if so set
1922    errno to EDOM.  */
1923
1924 static void
1925 expand_errno_check (tree exp, rtx target)
1926 {
1927   rtx lab = gen_label_rtx ();
1928
1929   /* Test the result; if it is NaN, set errno=EDOM because
1930      the argument was not in the domain.  */
1931   do_compare_rtx_and_jump (target, target, EQ, 0, GET_MODE (target),
1932                            NULL_RTX, NULL_RTX, lab,
1933                            /* The jump is very likely.  */
1934                            REG_BR_PROB_BASE - (REG_BR_PROB_BASE / 2000 - 1));
1935
1936 #ifdef TARGET_EDOM
1937   /* If this built-in doesn't throw an exception, set errno directly.  */
1938   if (TREE_NOTHROW (TREE_OPERAND (CALL_EXPR_FN (exp), 0)))
1939     {
1940 #ifdef GEN_ERRNO_RTX
1941       rtx errno_rtx = GEN_ERRNO_RTX;
1942 #else
1943       rtx errno_rtx
1944           = gen_rtx_MEM (word_mode, gen_rtx_SYMBOL_REF (Pmode, "errno"));
1945 #endif
1946       emit_move_insn (errno_rtx, GEN_INT (TARGET_EDOM));
1947       emit_label (lab);
1948       return;
1949     }
1950 #endif
1951
1952   /* Make sure the library call isn't expanded as a tail call.  */
1953   CALL_EXPR_TAILCALL (exp) = 0;
1954
1955   /* We can't set errno=EDOM directly; let the library call do it.
1956      Pop the arguments right away in case the call gets deleted.  */
1957   NO_DEFER_POP;
1958   expand_call (exp, target, 0);
1959   OK_DEFER_POP;
1960   emit_label (lab);
1961 }
1962
1963 /* Expand a call to one of the builtin math functions (sqrt, exp, or log).
1964    Return NULL_RTX if a normal call should be emitted rather than expanding
1965    the function in-line.  EXP is the expression that is a call to the builtin
1966    function; if convenient, the result should be placed in TARGET.
1967    SUBTARGET may be used as the target for computing one of EXP's operands.  */
1968
1969 static rtx
1970 expand_builtin_mathfn (tree exp, rtx target, rtx subtarget)
1971 {
1972   optab builtin_optab;
1973   rtx op0, insns;
1974   tree fndecl = get_callee_fndecl (exp);
1975   enum machine_mode mode;
1976   bool errno_set = false;
1977   tree arg;
1978
1979   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
1980     return NULL_RTX;
1981
1982   arg = CALL_EXPR_ARG (exp, 0);
1983
1984   switch (DECL_FUNCTION_CODE (fndecl))
1985     {
1986     CASE_FLT_FN (BUILT_IN_SQRT):
1987       errno_set = ! tree_expr_nonnegative_p (arg);
1988       builtin_optab = sqrt_optab;
1989       break;
1990     CASE_FLT_FN (BUILT_IN_EXP):
1991       errno_set = true; builtin_optab = exp_optab; break;
1992     CASE_FLT_FN (BUILT_IN_EXP10):
1993     CASE_FLT_FN (BUILT_IN_POW10):
1994       errno_set = true; builtin_optab = exp10_optab; break;
1995     CASE_FLT_FN (BUILT_IN_EXP2):
1996       errno_set = true; builtin_optab = exp2_optab; break;
1997     CASE_FLT_FN (BUILT_IN_EXPM1):
1998       errno_set = true; builtin_optab = expm1_optab; break;
1999     CASE_FLT_FN (BUILT_IN_LOGB):
2000       errno_set = true; builtin_optab = logb_optab; break;
2001     CASE_FLT_FN (BUILT_IN_LOG):
2002       errno_set = true; builtin_optab = log_optab; break;
2003     CASE_FLT_FN (BUILT_IN_LOG10):
2004       errno_set = true; builtin_optab = log10_optab; break;
2005     CASE_FLT_FN (BUILT_IN_LOG2):
2006       errno_set = true; builtin_optab = log2_optab; break;
2007     CASE_FLT_FN (BUILT_IN_LOG1P):
2008       errno_set = true; builtin_optab = log1p_optab; break;
2009     CASE_FLT_FN (BUILT_IN_ASIN):
2010       builtin_optab = asin_optab; break;
2011     CASE_FLT_FN (BUILT_IN_ACOS):
2012       builtin_optab = acos_optab; break;
2013     CASE_FLT_FN (BUILT_IN_TAN):
2014       builtin_optab = tan_optab; break;
2015     CASE_FLT_FN (BUILT_IN_ATAN):
2016       builtin_optab = atan_optab; break;
2017     CASE_FLT_FN (BUILT_IN_FLOOR):
2018       builtin_optab = floor_optab; break;
2019     CASE_FLT_FN (BUILT_IN_CEIL):
2020       builtin_optab = ceil_optab; break;
2021     CASE_FLT_FN (BUILT_IN_TRUNC):
2022       builtin_optab = btrunc_optab; break;
2023     CASE_FLT_FN (BUILT_IN_ROUND):
2024       builtin_optab = round_optab; break;
2025     CASE_FLT_FN (BUILT_IN_NEARBYINT):
2026       builtin_optab = nearbyint_optab;
2027       if (flag_trapping_math)
2028         break;
2029       /* Else fallthrough and expand as rint.  */
2030     CASE_FLT_FN (BUILT_IN_RINT):
2031       builtin_optab = rint_optab; break;
2032     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
2033       builtin_optab = significand_optab; break;
2034     default:
2035       gcc_unreachable ();
2036     }
2037
2038   /* Make a suitable register to place result in.  */
2039   mode = TYPE_MODE (TREE_TYPE (exp));
2040
2041   if (! flag_errno_math || ! HONOR_NANS (mode))
2042     errno_set = false;
2043
2044   /* Before working hard, check whether the instruction is available.  */
2045   if (optab_handler (builtin_optab, mode) != CODE_FOR_nothing
2046       && (!errno_set || !optimize_insn_for_size_p ()))
2047     {
2048       target = gen_reg_rtx (mode);
2049
2050       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2051          need to expand the argument again.  This way, we will not perform
2052          side-effects more the once.  */
2053       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2054
2055       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2056
2057       start_sequence ();
2058
2059       /* Compute into TARGET.
2060          Set TARGET to wherever the result comes back.  */
2061       target = expand_unop (mode, builtin_optab, op0, target, 0);
2062
2063       if (target != 0)
2064         {
2065           if (errno_set)
2066             expand_errno_check (exp, target);
2067
2068           /* Output the entire sequence.  */
2069           insns = get_insns ();
2070           end_sequence ();
2071           emit_insn (insns);
2072           return target;
2073         }
2074
2075       /* If we were unable to expand via the builtin, stop the sequence
2076          (without outputting the insns) and call to the library function
2077          with the stabilized argument list.  */
2078       end_sequence ();
2079     }
2080
2081   return expand_call (exp, target, target == const0_rtx);
2082 }
2083
2084 /* Expand a call to the builtin binary math functions (pow and atan2).
2085    Return NULL_RTX if a normal call should be emitted rather than expanding the
2086    function in-line.  EXP is the expression that is a call to the builtin
2087    function; if convenient, the result should be placed in TARGET.
2088    SUBTARGET may be used as the target for computing one of EXP's
2089    operands.  */
2090
2091 static rtx
2092 expand_builtin_mathfn_2 (tree exp, rtx target, rtx subtarget)
2093 {
2094   optab builtin_optab;
2095   rtx op0, op1, insns;
2096   int op1_type = REAL_TYPE;
2097   tree fndecl = get_callee_fndecl (exp);
2098   tree arg0, arg1;
2099   enum machine_mode mode;
2100   bool errno_set = true;
2101
2102   switch (DECL_FUNCTION_CODE (fndecl))
2103     {
2104     CASE_FLT_FN (BUILT_IN_SCALBN):
2105     CASE_FLT_FN (BUILT_IN_SCALBLN):
2106     CASE_FLT_FN (BUILT_IN_LDEXP):
2107       op1_type = INTEGER_TYPE;
2108     default:
2109       break;
2110     }
2111
2112   if (!validate_arglist (exp, REAL_TYPE, op1_type, VOID_TYPE))
2113     return NULL_RTX;
2114
2115   arg0 = CALL_EXPR_ARG (exp, 0);
2116   arg1 = CALL_EXPR_ARG (exp, 1);
2117
2118   switch (DECL_FUNCTION_CODE (fndecl))
2119     {
2120     CASE_FLT_FN (BUILT_IN_POW):
2121       builtin_optab = pow_optab; break;
2122     CASE_FLT_FN (BUILT_IN_ATAN2):
2123       builtin_optab = atan2_optab; break;
2124     CASE_FLT_FN (BUILT_IN_SCALB):
2125       if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (exp)))->b != 2)
2126         return 0;
2127       builtin_optab = scalb_optab; break;
2128     CASE_FLT_FN (BUILT_IN_SCALBN):
2129     CASE_FLT_FN (BUILT_IN_SCALBLN):
2130       if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (exp)))->b != 2)
2131         return 0;
2132     /* Fall through... */
2133     CASE_FLT_FN (BUILT_IN_LDEXP):
2134       builtin_optab = ldexp_optab; break;
2135     CASE_FLT_FN (BUILT_IN_FMOD):
2136       builtin_optab = fmod_optab; break;
2137     CASE_FLT_FN (BUILT_IN_REMAINDER):
2138     CASE_FLT_FN (BUILT_IN_DREM):
2139       builtin_optab = remainder_optab; break;
2140     default:
2141       gcc_unreachable ();
2142     }
2143
2144   /* Make a suitable register to place result in.  */
2145   mode = TYPE_MODE (TREE_TYPE (exp));
2146
2147   /* Before working hard, check whether the instruction is available.  */
2148   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2149     return NULL_RTX;
2150
2151   target = gen_reg_rtx (mode);
2152
2153   if (! flag_errno_math || ! HONOR_NANS (mode))
2154     errno_set = false;
2155
2156   if (errno_set && optimize_insn_for_size_p ())
2157     return 0;
2158
2159   /* Always stabilize the argument list.  */
2160   CALL_EXPR_ARG (exp, 0) = arg0 = builtin_save_expr (arg0);
2161   CALL_EXPR_ARG (exp, 1) = arg1 = builtin_save_expr (arg1);
2162
2163   op0 = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
2164   op1 = expand_normal (arg1);
2165
2166   start_sequence ();
2167
2168   /* Compute into TARGET.
2169      Set TARGET to wherever the result comes back.  */
2170   target = expand_binop (mode, builtin_optab, op0, op1,
2171                          target, 0, OPTAB_DIRECT);
2172
2173   /* If we were unable to expand via the builtin, stop the sequence
2174      (without outputting the insns) and call to the library function
2175      with the stabilized argument list.  */
2176   if (target == 0)
2177     {
2178       end_sequence ();
2179       return expand_call (exp, target, target == const0_rtx);
2180     }
2181
2182   if (errno_set)
2183     expand_errno_check (exp, target);
2184
2185   /* Output the entire sequence.  */
2186   insns = get_insns ();
2187   end_sequence ();
2188   emit_insn (insns);
2189
2190   return target;
2191 }
2192
2193 /* Expand a call to the builtin trinary math functions (fma).
2194    Return NULL_RTX if a normal call should be emitted rather than expanding the
2195    function in-line.  EXP is the expression that is a call to the builtin
2196    function; if convenient, the result should be placed in TARGET.
2197    SUBTARGET may be used as the target for computing one of EXP's
2198    operands.  */
2199
2200 static rtx
2201 expand_builtin_mathfn_ternary (tree exp, rtx target, rtx subtarget)
2202 {
2203   optab builtin_optab;
2204   rtx op0, op1, op2, insns;
2205   tree fndecl = get_callee_fndecl (exp);
2206   tree arg0, arg1, arg2;
2207   enum machine_mode mode;
2208
2209   if (!validate_arglist (exp, REAL_TYPE, REAL_TYPE, REAL_TYPE, VOID_TYPE))
2210     return NULL_RTX;
2211
2212   arg0 = CALL_EXPR_ARG (exp, 0);
2213   arg1 = CALL_EXPR_ARG (exp, 1);
2214   arg2 = CALL_EXPR_ARG (exp, 2);
2215
2216   switch (DECL_FUNCTION_CODE (fndecl))
2217     {
2218     CASE_FLT_FN (BUILT_IN_FMA):
2219       builtin_optab = fma_optab; break;
2220     default:
2221       gcc_unreachable ();
2222     }
2223
2224   /* Make a suitable register to place result in.  */
2225   mode = TYPE_MODE (TREE_TYPE (exp));
2226
2227   /* Before working hard, check whether the instruction is available.  */
2228   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2229     return NULL_RTX;
2230
2231   target = gen_reg_rtx (mode);
2232
2233   /* Always stabilize the argument list.  */
2234   CALL_EXPR_ARG (exp, 0) = arg0 = builtin_save_expr (arg0);
2235   CALL_EXPR_ARG (exp, 1) = arg1 = builtin_save_expr (arg1);
2236   CALL_EXPR_ARG (exp, 2) = arg2 = builtin_save_expr (arg2);
2237
2238   op0 = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
2239   op1 = expand_normal (arg1);
2240   op2 = expand_normal (arg2);
2241
2242   start_sequence ();
2243
2244   /* Compute into TARGET.
2245      Set TARGET to wherever the result comes back.  */
2246   target = expand_ternary_op (mode, builtin_optab, op0, op1, op2,
2247                               target, 0);
2248
2249   /* If we were unable to expand via the builtin, stop the sequence
2250      (without outputting the insns) and call to the library function
2251      with the stabilized argument list.  */
2252   if (target == 0)
2253     {
2254       end_sequence ();
2255       return expand_call (exp, target, target == const0_rtx);
2256     }
2257
2258   /* Output the entire sequence.  */
2259   insns = get_insns ();
2260   end_sequence ();
2261   emit_insn (insns);
2262
2263   return target;
2264 }
2265
2266 /* Expand a call to the builtin sin and cos math functions.
2267    Return NULL_RTX if a normal call should be emitted rather than expanding the
2268    function in-line.  EXP is the expression that is a call to the builtin
2269    function; if convenient, the result should be placed in TARGET.
2270    SUBTARGET may be used as the target for computing one of EXP's
2271    operands.  */
2272
2273 static rtx
2274 expand_builtin_mathfn_3 (tree exp, rtx target, rtx subtarget)
2275 {
2276   optab builtin_optab;
2277   rtx op0, insns;
2278   tree fndecl = get_callee_fndecl (exp);
2279   enum machine_mode mode;
2280   tree arg;
2281
2282   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2283     return NULL_RTX;
2284
2285   arg = CALL_EXPR_ARG (exp, 0);
2286
2287   switch (DECL_FUNCTION_CODE (fndecl))
2288     {
2289     CASE_FLT_FN (BUILT_IN_SIN):
2290     CASE_FLT_FN (BUILT_IN_COS):
2291       builtin_optab = sincos_optab; break;
2292     default:
2293       gcc_unreachable ();
2294     }
2295
2296   /* Make a suitable register to place result in.  */
2297   mode = TYPE_MODE (TREE_TYPE (exp));
2298
2299   /* Check if sincos insn is available, otherwise fallback
2300      to sin or cos insn.  */
2301   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2302     switch (DECL_FUNCTION_CODE (fndecl))
2303       {
2304       CASE_FLT_FN (BUILT_IN_SIN):
2305         builtin_optab = sin_optab; break;
2306       CASE_FLT_FN (BUILT_IN_COS):
2307         builtin_optab = cos_optab; break;
2308       default:
2309         gcc_unreachable ();
2310       }
2311
2312   /* Before working hard, check whether the instruction is available.  */
2313   if (optab_handler (builtin_optab, mode) != CODE_FOR_nothing)
2314     {
2315       target = gen_reg_rtx (mode);
2316
2317       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2318          need to expand the argument again.  This way, we will not perform
2319          side-effects more the once.  */
2320       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2321
2322       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2323
2324       start_sequence ();
2325
2326       /* Compute into TARGET.
2327          Set TARGET to wherever the result comes back.  */
2328       if (builtin_optab == sincos_optab)
2329         {
2330           int result;
2331
2332           switch (DECL_FUNCTION_CODE (fndecl))
2333             {
2334             CASE_FLT_FN (BUILT_IN_SIN):
2335               result = expand_twoval_unop (builtin_optab, op0, 0, target, 0);
2336               break;
2337             CASE_FLT_FN (BUILT_IN_COS):
2338               result = expand_twoval_unop (builtin_optab, op0, target, 0, 0);
2339               break;
2340             default:
2341               gcc_unreachable ();
2342             }
2343           gcc_assert (result);
2344         }
2345       else
2346         {
2347           target = expand_unop (mode, builtin_optab, op0, target, 0);
2348         }
2349
2350       if (target != 0)
2351         {
2352           /* Output the entire sequence.  */
2353           insns = get_insns ();
2354           end_sequence ();
2355           emit_insn (insns);
2356           return target;
2357         }
2358
2359       /* If we were unable to expand via the builtin, stop the sequence
2360          (without outputting the insns) and call to the library function
2361          with the stabilized argument list.  */
2362       end_sequence ();
2363     }
2364
2365   target = expand_call (exp, target, target == const0_rtx);
2366
2367   return target;
2368 }
2369
2370 /* Given an interclass math builtin decl FNDECL and it's argument ARG
2371    return an RTL instruction code that implements the functionality.
2372    If that isn't possible or available return CODE_FOR_nothing.  */
2373
2374 static enum insn_code
2375 interclass_mathfn_icode (tree arg, tree fndecl)
2376 {
2377   bool errno_set = false;
2378   optab builtin_optab = 0;
2379   enum machine_mode mode;
2380
2381   switch (DECL_FUNCTION_CODE (fndecl))
2382     {
2383     CASE_FLT_FN (BUILT_IN_ILOGB):
2384       errno_set = true; builtin_optab = ilogb_optab; break;
2385     CASE_FLT_FN (BUILT_IN_ISINF):
2386       builtin_optab = isinf_optab; break;
2387     case BUILT_IN_ISNORMAL:
2388     case BUILT_IN_ISFINITE:
2389     CASE_FLT_FN (BUILT_IN_FINITE):
2390     case BUILT_IN_FINITED32:
2391     case BUILT_IN_FINITED64:
2392     case BUILT_IN_FINITED128:
2393     case BUILT_IN_ISINFD32:
2394     case BUILT_IN_ISINFD64:
2395     case BUILT_IN_ISINFD128:
2396       /* These builtins have no optabs (yet).  */
2397       break;
2398     default:
2399       gcc_unreachable ();
2400     }
2401
2402   /* There's no easy way to detect the case we need to set EDOM.  */
2403   if (flag_errno_math && errno_set)
2404     return CODE_FOR_nothing;
2405
2406   /* Optab mode depends on the mode of the input argument.  */
2407   mode = TYPE_MODE (TREE_TYPE (arg));
2408
2409   if (builtin_optab)
2410     return optab_handler (builtin_optab, mode);
2411   return CODE_FOR_nothing;
2412 }
2413
2414 /* Expand a call to one of the builtin math functions that operate on
2415    floating point argument and output an integer result (ilogb, isinf,
2416    isnan, etc).
2417    Return 0 if a normal call should be emitted rather than expanding the
2418    function in-line.  EXP is the expression that is a call to the builtin
2419    function; if convenient, the result should be placed in TARGET.  */
2420
2421 static rtx
2422 expand_builtin_interclass_mathfn (tree exp, rtx target)
2423 {
2424   enum insn_code icode = CODE_FOR_nothing;
2425   rtx op0;
2426   tree fndecl = get_callee_fndecl (exp);
2427   enum machine_mode mode;
2428   tree arg;
2429
2430   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2431     return NULL_RTX;
2432
2433   arg = CALL_EXPR_ARG (exp, 0);
2434   icode = interclass_mathfn_icode (arg, fndecl);
2435   mode = TYPE_MODE (TREE_TYPE (arg));
2436
2437   if (icode != CODE_FOR_nothing)
2438     {
2439       struct expand_operand ops[1];
2440       rtx last = get_last_insn ();
2441       tree orig_arg = arg;
2442
2443       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2444          need to expand the argument again.  This way, we will not perform
2445          side-effects more the once.  */
2446       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2447
2448       op0 = expand_expr (arg, NULL_RTX, VOIDmode, EXPAND_NORMAL);
2449
2450       if (mode != GET_MODE (op0))
2451         op0 = convert_to_mode (mode, op0, 0);
2452
2453       create_output_operand (&ops[0], target, TYPE_MODE (TREE_TYPE (exp)));
2454       if (maybe_legitimize_operands (icode, 0, 1, ops)
2455           && maybe_emit_unop_insn (icode, ops[0].value, op0, UNKNOWN))
2456         return ops[0].value;
2457
2458       delete_insns_since (last);
2459       CALL_EXPR_ARG (exp, 0) = orig_arg;
2460     }
2461
2462   return NULL_RTX;
2463 }
2464
2465 /* Expand a call to the builtin sincos math function.
2466    Return NULL_RTX if a normal call should be emitted rather than expanding the
2467    function in-line.  EXP is the expression that is a call to the builtin
2468    function.  */
2469
2470 static rtx
2471 expand_builtin_sincos (tree exp)
2472 {
2473   rtx op0, op1, op2, target1, target2;
2474   enum machine_mode mode;
2475   tree arg, sinp, cosp;
2476   int result;
2477   location_t loc = EXPR_LOCATION (exp);
2478   tree alias_type, alias_off;
2479
2480   if (!validate_arglist (exp, REAL_TYPE,
2481                          POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
2482     return NULL_RTX;
2483
2484   arg = CALL_EXPR_ARG (exp, 0);
2485   sinp = CALL_EXPR_ARG (exp, 1);
2486   cosp = CALL_EXPR_ARG (exp, 2);
2487
2488   /* Make a suitable register to place result in.  */
2489   mode = TYPE_MODE (TREE_TYPE (arg));
2490
2491   /* Check if sincos insn is available, otherwise emit the call.  */
2492   if (optab_handler (sincos_optab, mode) == CODE_FOR_nothing)
2493     return NULL_RTX;
2494
2495   target1 = gen_reg_rtx (mode);
2496   target2 = gen_reg_rtx (mode);
2497
2498   op0 = expand_normal (arg);
2499   alias_type = build_pointer_type_for_mode (TREE_TYPE (arg), ptr_mode, true);
2500   alias_off = build_int_cst (alias_type, 0);
2501   op1 = expand_normal (fold_build2_loc (loc, MEM_REF, TREE_TYPE (arg),
2502                                         sinp, alias_off));
2503   op2 = expand_normal (fold_build2_loc (loc, MEM_REF, TREE_TYPE (arg),
2504                                         cosp, alias_off));
2505
2506   /* Compute into target1 and target2.
2507      Set TARGET to wherever the result comes back.  */
2508   result = expand_twoval_unop (sincos_optab, op0, target2, target1, 0);
2509   gcc_assert (result);
2510
2511   /* Move target1 and target2 to the memory locations indicated
2512      by op1 and op2.  */
2513   emit_move_insn (op1, target1);
2514   emit_move_insn (op2, target2);
2515
2516   return const0_rtx;
2517 }
2518
2519 /* Expand a call to the internal cexpi builtin to the sincos math function.
2520    EXP is the expression that is a call to the builtin function; if convenient,
2521    the result should be placed in TARGET.  */
2522
2523 static rtx
2524 expand_builtin_cexpi (tree exp, rtx target)
2525 {
2526   tree fndecl = get_callee_fndecl (exp);
2527   tree arg, type;
2528   enum machine_mode mode;
2529   rtx op0, op1, op2;
2530   location_t loc = EXPR_LOCATION (exp);
2531
2532   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2533     return NULL_RTX;
2534
2535   arg = CALL_EXPR_ARG (exp, 0);
2536   type = TREE_TYPE (arg);
2537   mode = TYPE_MODE (TREE_TYPE (arg));
2538
2539   /* Try expanding via a sincos optab, fall back to emitting a libcall
2540      to sincos or cexp.  We are sure we have sincos or cexp because cexpi
2541      is only generated from sincos, cexp or if we have either of them.  */
2542   if (optab_handler (sincos_optab, mode) != CODE_FOR_nothing)
2543     {
2544       op1 = gen_reg_rtx (mode);
2545       op2 = gen_reg_rtx (mode);
2546
2547       op0 = expand_expr (arg, NULL_RTX, VOIDmode, EXPAND_NORMAL);
2548
2549       /* Compute into op1 and op2.  */
2550       expand_twoval_unop (sincos_optab, op0, op2, op1, 0);
2551     }
2552   else if (TARGET_HAS_SINCOS)
2553     {
2554       tree call, fn = NULL_TREE;
2555       tree top1, top2;
2556       rtx op1a, op2a;
2557
2558       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2559         fn = builtin_decl_explicit (BUILT_IN_SINCOSF);
2560       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2561         fn = builtin_decl_explicit (BUILT_IN_SINCOS);
2562       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2563         fn = builtin_decl_explicit (BUILT_IN_SINCOSL);
2564       else
2565         gcc_unreachable ();
2566
2567       op1 = assign_temp (TREE_TYPE (arg), 0, 1, 1);
2568       op2 = assign_temp (TREE_TYPE (arg), 0, 1, 1);
2569       op1a = copy_to_mode_reg (Pmode, XEXP (op1, 0));
2570       op2a = copy_to_mode_reg (Pmode, XEXP (op2, 0));
2571       top1 = make_tree (build_pointer_type (TREE_TYPE (arg)), op1a);
2572       top2 = make_tree (build_pointer_type (TREE_TYPE (arg)), op2a);
2573
2574       /* Make sure not to fold the sincos call again.  */
2575       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2576       expand_normal (build_call_nary (TREE_TYPE (TREE_TYPE (fn)),
2577                                       call, 3, arg, top1, top2));
2578     }
2579   else
2580     {
2581       tree call, fn = NULL_TREE, narg;
2582       tree ctype = build_complex_type (type);
2583
2584       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2585         fn = builtin_decl_explicit (BUILT_IN_CEXPF);
2586       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2587         fn = builtin_decl_explicit (BUILT_IN_CEXP);
2588       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2589         fn = builtin_decl_explicit (BUILT_IN_CEXPL);
2590       else
2591         gcc_unreachable ();
2592
2593       /* If we don't have a decl for cexp create one.  This is the
2594          friendliest fallback if the user calls __builtin_cexpi
2595          without full target C99 function support.  */
2596       if (fn == NULL_TREE)
2597         {
2598           tree fntype;
2599           const char *name = NULL;
2600
2601           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2602             name = "cexpf";
2603           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2604             name = "cexp";
2605           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2606             name = "cexpl";
2607
2608           fntype = build_function_type_list (ctype, ctype, NULL_TREE);
2609           fn = build_fn_decl (name, fntype);
2610         }
2611
2612       narg = fold_build2_loc (loc, COMPLEX_EXPR, ctype,
2613                           build_real (type, dconst0), arg);
2614
2615       /* Make sure not to fold the cexp call again.  */
2616       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2617       return expand_expr (build_call_nary (ctype, call, 1, narg),
2618                           target, VOIDmode, EXPAND_NORMAL);
2619     }
2620
2621   /* Now build the proper return type.  */
2622   return expand_expr (build2 (COMPLEX_EXPR, build_complex_type (type),
2623                               make_tree (TREE_TYPE (arg), op2),
2624                               make_tree (TREE_TYPE (arg), op1)),
2625                       target, VOIDmode, EXPAND_NORMAL);
2626 }
2627
2628 /* Conveniently construct a function call expression.  FNDECL names the
2629    function to be called, N is the number of arguments, and the "..."
2630    parameters are the argument expressions.  Unlike build_call_exr
2631    this doesn't fold the call, hence it will always return a CALL_EXPR.  */
2632
2633 static tree
2634 build_call_nofold_loc (location_t loc, tree fndecl, int n, ...)
2635 {
2636   va_list ap;
2637   tree fntype = TREE_TYPE (fndecl);
2638   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
2639
2640   va_start (ap, n);
2641   fn = build_call_valist (TREE_TYPE (fntype), fn, n, ap);
2642   va_end (ap);
2643   SET_EXPR_LOCATION (fn, loc);
2644   return fn;
2645 }
2646
2647 /* Expand a call to one of the builtin rounding functions gcc defines
2648    as an extension (lfloor and lceil).  As these are gcc extensions we
2649    do not need to worry about setting errno to EDOM.
2650    If expanding via optab fails, lower expression to (int)(floor(x)).
2651    EXP is the expression that is a call to the builtin function;
2652    if convenient, the result should be placed in TARGET.  */
2653
2654 static rtx
2655 expand_builtin_int_roundingfn (tree exp, rtx target)
2656 {
2657   convert_optab builtin_optab;
2658   rtx op0, insns, tmp;
2659   tree fndecl = get_callee_fndecl (exp);
2660   enum built_in_function fallback_fn;
2661   tree fallback_fndecl;
2662   enum machine_mode mode;
2663   tree arg;
2664
2665   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2666     gcc_unreachable ();
2667
2668   arg = CALL_EXPR_ARG (exp, 0);
2669
2670   switch (DECL_FUNCTION_CODE (fndecl))
2671     {
2672     CASE_FLT_FN (BUILT_IN_ICEIL):
2673     CASE_FLT_FN (BUILT_IN_LCEIL):
2674     CASE_FLT_FN (BUILT_IN_LLCEIL):
2675       builtin_optab = lceil_optab;
2676       fallback_fn = BUILT_IN_CEIL;
2677       break;
2678
2679     CASE_FLT_FN (BUILT_IN_IFLOOR):
2680     CASE_FLT_FN (BUILT_IN_LFLOOR):
2681     CASE_FLT_FN (BUILT_IN_LLFLOOR):
2682       builtin_optab = lfloor_optab;
2683       fallback_fn = BUILT_IN_FLOOR;
2684       break;
2685
2686     default:
2687       gcc_unreachable ();
2688     }
2689
2690   /* Make a suitable register to place result in.  */
2691   mode = TYPE_MODE (TREE_TYPE (exp));
2692
2693   target = gen_reg_rtx (mode);
2694
2695   /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2696      need to expand the argument again.  This way, we will not perform
2697      side-effects more the once.  */
2698   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2699
2700   op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2701
2702   start_sequence ();
2703
2704   /* Compute into TARGET.  */
2705   if (expand_sfix_optab (target, op0, builtin_optab))
2706     {
2707       /* Output the entire sequence.  */
2708       insns = get_insns ();
2709       end_sequence ();
2710       emit_insn (insns);
2711       return target;
2712     }
2713
2714   /* If we were unable to expand via the builtin, stop the sequence
2715      (without outputting the insns).  */
2716   end_sequence ();
2717
2718   /* Fall back to floating point rounding optab.  */
2719   fallback_fndecl = mathfn_built_in (TREE_TYPE (arg), fallback_fn);
2720
2721   /* For non-C99 targets we may end up without a fallback fndecl here
2722      if the user called __builtin_lfloor directly.  In this case emit
2723      a call to the floor/ceil variants nevertheless.  This should result
2724      in the best user experience for not full C99 targets.  */
2725   if (fallback_fndecl == NULL_TREE)
2726     {
2727       tree fntype;
2728       const char *name = NULL;
2729
2730       switch (DECL_FUNCTION_CODE (fndecl))
2731         {
2732         case BUILT_IN_ICEIL:
2733         case BUILT_IN_LCEIL:
2734         case BUILT_IN_LLCEIL:
2735           name = "ceil";
2736           break;
2737         case BUILT_IN_ICEILF:
2738         case BUILT_IN_LCEILF:
2739         case BUILT_IN_LLCEILF:
2740           name = "ceilf";
2741           break;
2742         case BUILT_IN_ICEILL:
2743         case BUILT_IN_LCEILL:
2744         case BUILT_IN_LLCEILL:
2745           name = "ceill";
2746           break;
2747         case BUILT_IN_IFLOOR:
2748         case BUILT_IN_LFLOOR:
2749         case BUILT_IN_LLFLOOR:
2750           name = "floor";
2751           break;
2752         case BUILT_IN_IFLOORF:
2753         case BUILT_IN_LFLOORF:
2754         case BUILT_IN_LLFLOORF:
2755           name = "floorf";
2756           break;
2757         case BUILT_IN_IFLOORL:
2758         case BUILT_IN_LFLOORL:
2759         case BUILT_IN_LLFLOORL:
2760           name = "floorl";
2761           break;
2762         default:
2763           gcc_unreachable ();
2764         }
2765
2766       fntype = build_function_type_list (TREE_TYPE (arg),
2767                                          TREE_TYPE (arg), NULL_TREE);
2768       fallback_fndecl = build_fn_decl (name, fntype);
2769     }
2770
2771   exp = build_call_nofold_loc (EXPR_LOCATION (exp), fallback_fndecl, 1, arg);
2772
2773   tmp = expand_normal (exp);
2774
2775   /* Truncate the result of floating point optab to integer
2776      via expand_fix ().  */
2777   target = gen_reg_rtx (mode);
2778   expand_fix (target, tmp, 0);
2779
2780   return target;
2781 }
2782
2783 /* Expand a call to one of the builtin math functions doing integer
2784    conversion (lrint).
2785    Return 0 if a normal call should be emitted rather than expanding the
2786    function in-line.  EXP is the expression that is a call to the builtin
2787    function; if convenient, the result should be placed in TARGET.  */
2788
2789 static rtx
2790 expand_builtin_int_roundingfn_2 (tree exp, rtx target)
2791 {
2792   convert_optab builtin_optab;
2793   rtx op0, insns;
2794   tree fndecl = get_callee_fndecl (exp);
2795   tree arg;
2796   enum machine_mode mode;
2797
2798   /* There's no easy way to detect the case we need to set EDOM.  */
2799   if (flag_errno_math)
2800     return NULL_RTX;
2801
2802   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2803      gcc_unreachable ();
2804
2805   arg = CALL_EXPR_ARG (exp, 0);
2806
2807   switch (DECL_FUNCTION_CODE (fndecl))
2808     {
2809     CASE_FLT_FN (BUILT_IN_IRINT):
2810     CASE_FLT_FN (BUILT_IN_LRINT):
2811     CASE_FLT_FN (BUILT_IN_LLRINT):
2812       builtin_optab = lrint_optab; break;
2813
2814     CASE_FLT_FN (BUILT_IN_IROUND):
2815     CASE_FLT_FN (BUILT_IN_LROUND):
2816     CASE_FLT_FN (BUILT_IN_LLROUND):
2817       builtin_optab = lround_optab; break;
2818
2819     default:
2820       gcc_unreachable ();
2821     }
2822
2823   /* Make a suitable register to place result in.  */
2824   mode = TYPE_MODE (TREE_TYPE (exp));
2825
2826   target = gen_reg_rtx (mode);
2827
2828   /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2829      need to expand the argument again.  This way, we will not perform
2830      side-effects more the once.  */
2831   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2832
2833   op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2834
2835   start_sequence ();
2836
2837   if (expand_sfix_optab (target, op0, builtin_optab))
2838     {
2839       /* Output the entire sequence.  */
2840       insns = get_insns ();
2841       end_sequence ();
2842       emit_insn (insns);
2843       return target;
2844     }
2845
2846   /* If we were unable to expand via the builtin, stop the sequence
2847      (without outputting the insns) and call to the library function
2848      with the stabilized argument list.  */
2849   end_sequence ();
2850
2851   target = expand_call (exp, target, target == const0_rtx);
2852
2853   return target;
2854 }
2855
2856 /* Expand a call to the powi built-in mathematical function.  Return NULL_RTX if
2857    a normal call should be emitted rather than expanding the function
2858    in-line.  EXP is the expression that is a call to the builtin
2859    function; if convenient, the result should be placed in TARGET.  */
2860
2861 static rtx
2862 expand_builtin_powi (tree exp, rtx target)
2863 {
2864   tree arg0, arg1;
2865   rtx op0, op1;
2866   enum machine_mode mode;
2867   enum machine_mode mode2;
2868
2869   if (! validate_arglist (exp, REAL_TYPE, INTEGER_TYPE, VOID_TYPE))
2870     return NULL_RTX;
2871
2872   arg0 = CALL_EXPR_ARG (exp, 0);
2873   arg1 = CALL_EXPR_ARG (exp, 1);
2874   mode = TYPE_MODE (TREE_TYPE (exp));
2875
2876   /* Emit a libcall to libgcc.  */
2877
2878   /* Mode of the 2nd argument must match that of an int.  */
2879   mode2 = mode_for_size (INT_TYPE_SIZE, MODE_INT, 0);
2880
2881   if (target == NULL_RTX)
2882     target = gen_reg_rtx (mode);
2883
2884   op0 = expand_expr (arg0, NULL_RTX, mode, EXPAND_NORMAL);
2885   if (GET_MODE (op0) != mode)
2886     op0 = convert_to_mode (mode, op0, 0);
2887   op1 = expand_expr (arg1, NULL_RTX, mode2, EXPAND_NORMAL);
2888   if (GET_MODE (op1) != mode2)
2889     op1 = convert_to_mode (mode2, op1, 0);
2890
2891   target = emit_library_call_value (optab_libfunc (powi_optab, mode),
2892                                     target, LCT_CONST, mode, 2,
2893                                     op0, mode, op1, mode2);
2894
2895   return target;
2896 }
2897
2898 /* Expand expression EXP which is a call to the strlen builtin.  Return
2899    NULL_RTX if we failed the caller should emit a normal call, otherwise
2900    try to get the result in TARGET, if convenient.  */
2901
2902 static rtx
2903 expand_builtin_strlen (tree exp, rtx target,
2904                        enum machine_mode target_mode)
2905 {
2906   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
2907     return NULL_RTX;
2908   else
2909     {
2910       struct expand_operand ops[4];
2911       rtx pat;
2912       tree len;
2913       tree src = CALL_EXPR_ARG (exp, 0);
2914       rtx src_reg, before_strlen;
2915       enum machine_mode insn_mode = target_mode;
2916       enum insn_code icode = CODE_FOR_nothing;
2917       unsigned int align;
2918
2919       /* If the length can be computed at compile-time, return it.  */
2920       len = c_strlen (src, 0);
2921       if (len)
2922         return expand_expr (len, target, target_mode, EXPAND_NORMAL);
2923
2924       /* If the length can be computed at compile-time and is constant
2925          integer, but there are side-effects in src, evaluate
2926          src for side-effects, then return len.
2927          E.g. x = strlen (i++ ? "xfoo" + 1 : "bar");
2928          can be optimized into: i++; x = 3;  */
2929       len = c_strlen (src, 1);
2930       if (len && TREE_CODE (len) == INTEGER_CST)
2931         {
2932           expand_expr (src, const0_rtx, VOIDmode, EXPAND_NORMAL);
2933           return expand_expr (len, target, target_mode, EXPAND_NORMAL);
2934         }
2935
2936       align = get_pointer_alignment (src) / BITS_PER_UNIT;
2937
2938       /* If SRC is not a pointer type, don't do this operation inline.  */
2939       if (align == 0)
2940         return NULL_RTX;
2941
2942       /* Bail out if we can't compute strlen in the right mode.  */
2943       while (insn_mode != VOIDmode)
2944         {
2945           icode = optab_handler (strlen_optab, insn_mode);
2946           if (icode != CODE_FOR_nothing)
2947             break;
2948
2949           insn_mode = GET_MODE_WIDER_MODE (insn_mode);
2950         }
2951       if (insn_mode == VOIDmode)
2952         return NULL_RTX;
2953
2954       /* Make a place to hold the source address.  We will not expand
2955          the actual source until we are sure that the expansion will
2956          not fail -- there are trees that cannot be expanded twice.  */
2957       src_reg = gen_reg_rtx (Pmode);
2958
2959       /* Mark the beginning of the strlen sequence so we can emit the
2960          source operand later.  */
2961       before_strlen = get_last_insn ();
2962
2963       create_output_operand (&ops[0], target, insn_mode);
2964       create_fixed_operand (&ops[1], gen_rtx_MEM (BLKmode, src_reg));
2965       create_integer_operand (&ops[2], 0);
2966       create_integer_operand (&ops[3], align);
2967       if (!maybe_expand_insn (icode, 4, ops))
2968         return NULL_RTX;
2969
2970       /* Now that we are assured of success, expand the source.  */
2971       start_sequence ();
2972       pat = expand_expr (src, src_reg, Pmode, EXPAND_NORMAL);
2973       if (pat != src_reg)
2974         {
2975 #ifdef POINTERS_EXTEND_UNSIGNED
2976           if (GET_MODE (pat) != Pmode)
2977             pat = convert_to_mode (Pmode, pat,
2978                                    POINTERS_EXTEND_UNSIGNED);
2979 #endif
2980           emit_move_insn (src_reg, pat);
2981         }
2982       pat = get_insns ();
2983       end_sequence ();
2984
2985       if (before_strlen)
2986         emit_insn_after (pat, before_strlen);
2987       else
2988         emit_insn_before (pat, get_insns ());
2989
2990       /* Return the value in the proper mode for this function.  */
2991       if (GET_MODE (ops[0].value) == target_mode)
2992         target = ops[0].value;
2993       else if (target != 0)
2994         convert_move (target, ops[0].value, 0);
2995       else
2996         target = convert_to_mode (target_mode, ops[0].value, 0);
2997
2998       return target;
2999     }
3000 }
3001
3002 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3003    bytes from constant string DATA + OFFSET and return it as target
3004    constant.  */
3005
3006 static rtx
3007 builtin_memcpy_read_str (void *data, HOST_WIDE_INT offset,
3008                          enum machine_mode mode)
3009 {
3010   const char *str = (const char *) data;
3011
3012   gcc_assert (offset >= 0
3013               && ((unsigned HOST_WIDE_INT) offset + GET_MODE_SIZE (mode)
3014                   <= strlen (str) + 1));
3015
3016   return c_readstr (str + offset, mode);
3017 }
3018
3019 /* Expand a call EXP to the memcpy builtin.
3020    Return NULL_RTX if we failed, the caller should emit a normal call,
3021    otherwise try to get the result in TARGET, if convenient (and in
3022    mode MODE if that's convenient).  */
3023
3024 static rtx
3025 expand_builtin_memcpy (tree exp, rtx target)
3026 {
3027   if (!validate_arglist (exp,
3028                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3029     return NULL_RTX;
3030   else
3031     {
3032       tree dest = CALL_EXPR_ARG (exp, 0);
3033       tree src = CALL_EXPR_ARG (exp, 1);
3034       tree len = CALL_EXPR_ARG (exp, 2);
3035       const char *src_str;
3036       unsigned int src_align = get_pointer_alignment (src);
3037       unsigned int dest_align = get_pointer_alignment (dest);
3038       rtx dest_mem, src_mem, dest_addr, len_rtx;
3039       HOST_WIDE_INT expected_size = -1;
3040       unsigned int expected_align = 0;
3041
3042       /* If DEST is not a pointer type, call the normal function.  */
3043       if (dest_align == 0)
3044         return NULL_RTX;
3045
3046       /* If either SRC is not a pointer type, don't do this
3047          operation in-line.  */
3048       if (src_align == 0)
3049         return NULL_RTX;
3050
3051       if (currently_expanding_gimple_stmt)
3052         stringop_block_profile (currently_expanding_gimple_stmt,
3053                                 &expected_align, &expected_size);
3054
3055       if (expected_align < dest_align)
3056         expected_align = dest_align;
3057       dest_mem = get_memory_rtx (dest, len);
3058       set_mem_align (dest_mem, dest_align);
3059       len_rtx = expand_normal (len);
3060       src_str = c_getstr (src);
3061
3062       /* If SRC is a string constant and block move would be done
3063          by pieces, we can avoid loading the string from memory
3064          and only stored the computed constants.  */
3065       if (src_str
3066           && CONST_INT_P (len_rtx)
3067           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
3068           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
3069                                   CONST_CAST (char *, src_str),
3070                                   dest_align, false))
3071         {
3072           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
3073                                       builtin_memcpy_read_str,
3074                                       CONST_CAST (char *, src_str),
3075                                       dest_align, false, 0);
3076           dest_mem = force_operand (XEXP (dest_mem, 0), target);
3077           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3078           return dest_mem;
3079         }
3080
3081       src_mem = get_memory_rtx (src, len);
3082       set_mem_align (src_mem, src_align);
3083
3084       /* Copy word part most expediently.  */
3085       dest_addr = emit_block_move_hints (dest_mem, src_mem, len_rtx,
3086                                          CALL_EXPR_TAILCALL (exp)
3087                                          ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
3088                                          expected_align, expected_size);
3089
3090       if (dest_addr == 0)
3091         {
3092           dest_addr = force_operand (XEXP (dest_mem, 0), target);
3093           dest_addr = convert_memory_address (ptr_mode, dest_addr);
3094         }
3095       return dest_addr;
3096     }
3097 }
3098
3099 /* Expand a call EXP to the mempcpy builtin.
3100    Return NULL_RTX if we failed; the caller should emit a normal call,
3101    otherwise try to get the result in TARGET, if convenient (and in
3102    mode MODE if that's convenient).  If ENDP is 0 return the
3103    destination pointer, if ENDP is 1 return the end pointer ala
3104    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3105    stpcpy.  */
3106
3107 static rtx
3108 expand_builtin_mempcpy (tree exp, rtx target, enum machine_mode mode)
3109 {
3110   if (!validate_arglist (exp,
3111                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3112     return NULL_RTX;
3113   else
3114     {
3115       tree dest = CALL_EXPR_ARG (exp, 0);
3116       tree src = CALL_EXPR_ARG (exp, 1);
3117       tree len = CALL_EXPR_ARG (exp, 2);
3118       return expand_builtin_mempcpy_args (dest, src, len,
3119                                           target, mode, /*endp=*/ 1);
3120     }
3121 }
3122
3123 /* Helper function to do the actual work for expand_builtin_mempcpy.  The
3124    arguments to the builtin_mempcpy call DEST, SRC, and LEN are broken out
3125    so that this can also be called without constructing an actual CALL_EXPR.
3126    The other arguments and return value are the same as for
3127    expand_builtin_mempcpy.  */
3128
3129 static rtx
3130 expand_builtin_mempcpy_args (tree dest, tree src, tree len,
3131                              rtx target, enum machine_mode mode, int endp)
3132 {
3133     /* If return value is ignored, transform mempcpy into memcpy.  */
3134   if (target == const0_rtx && builtin_decl_implicit_p (BUILT_IN_MEMCPY))
3135     {
3136       tree fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
3137       tree result = build_call_nofold_loc (UNKNOWN_LOCATION, fn, 3,
3138                                            dest, src, len);
3139       return expand_expr (result, target, mode, EXPAND_NORMAL);
3140     }
3141   else
3142     {
3143       const char *src_str;
3144       unsigned int src_align = get_pointer_alignment (src);
3145       unsigned int dest_align = get_pointer_alignment (dest);
3146       rtx dest_mem, src_mem, len_rtx;
3147
3148       /* If either SRC or DEST is not a pointer type, don't do this
3149          operation in-line.  */
3150       if (dest_align == 0 || src_align == 0)
3151         return NULL_RTX;
3152
3153       /* If LEN is not constant, call the normal function.  */
3154       if (! host_integerp (len, 1))
3155         return NULL_RTX;
3156
3157       len_rtx = expand_normal (len);
3158       src_str = c_getstr (src);
3159
3160       /* If SRC is a string constant and block move would be done
3161          by pieces, we can avoid loading the string from memory
3162          and only stored the computed constants.  */
3163       if (src_str
3164           && CONST_INT_P (len_rtx)
3165           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
3166           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
3167                                   CONST_CAST (char *, src_str),
3168                                   dest_align, false))
3169         {
3170           dest_mem = get_memory_rtx (dest, len);
3171           set_mem_align (dest_mem, dest_align);
3172           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
3173                                       builtin_memcpy_read_str,
3174                                       CONST_CAST (char *, src_str),
3175                                       dest_align, false, endp);
3176           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3177           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3178           return dest_mem;
3179         }
3180
3181       if (CONST_INT_P (len_rtx)
3182           && can_move_by_pieces (INTVAL (len_rtx),
3183                                  MIN (dest_align, src_align)))
3184         {
3185           dest_mem = get_memory_rtx (dest, len);
3186           set_mem_align (dest_mem, dest_align);
3187           src_mem = get_memory_rtx (src, len);
3188           set_mem_align (src_mem, src_align);
3189           dest_mem = move_by_pieces (dest_mem, src_mem, INTVAL (len_rtx),
3190                                      MIN (dest_align, src_align), endp);
3191           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3192           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3193           return dest_mem;
3194         }
3195
3196       return NULL_RTX;
3197     }
3198 }
3199
3200 #ifndef HAVE_movstr
3201 # define HAVE_movstr 0
3202 # define CODE_FOR_movstr CODE_FOR_nothing
3203 #endif
3204
3205 /* Expand into a movstr instruction, if one is available.  Return NULL_RTX if
3206    we failed, the caller should emit a normal call, otherwise try to
3207    get the result in TARGET, if convenient.  If ENDP is 0 return the
3208    destination pointer, if ENDP is 1 return the end pointer ala
3209    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3210    stpcpy.  */
3211
3212 static rtx
3213 expand_movstr (tree dest, tree src, rtx target, int endp)
3214 {
3215   struct expand_operand ops[3];
3216   rtx dest_mem;
3217   rtx src_mem;
3218
3219   if (!HAVE_movstr)
3220     return NULL_RTX;
3221
3222   dest_mem = get_memory_rtx (dest, NULL);
3223   src_mem = get_memory_rtx (src, NULL);
3224   if (!endp)
3225     {
3226       target = force_reg (Pmode, XEXP (dest_mem, 0));
3227       dest_mem = replace_equiv_address (dest_mem, target);
3228     }
3229
3230   create_output_operand (&ops[0], endp ? target : NULL_RTX, Pmode);
3231   create_fixed_operand (&ops[1], dest_mem);
3232   create_fixed_operand (&ops[2], src_mem);
3233   expand_insn (CODE_FOR_movstr, 3, ops);
3234
3235   if (endp && target != const0_rtx)
3236     {
3237       target = ops[0].value;
3238       /* movstr is supposed to set end to the address of the NUL
3239          terminator.  If the caller requested a mempcpy-like return value,
3240          adjust it.  */
3241       if (endp == 1)
3242         {
3243           rtx tem = plus_constant (gen_lowpart (GET_MODE (target), target), 1);
3244           emit_move_insn (target, force_operand (tem, NULL_RTX));
3245         }
3246     }
3247   return target;
3248 }
3249
3250 /* Expand expression EXP, which is a call to the strcpy builtin.  Return
3251    NULL_RTX if we failed the caller should emit a normal call, otherwise
3252    try to get the result in TARGET, if convenient (and in mode MODE if that's
3253    convenient).  */
3254
3255 static rtx
3256 expand_builtin_strcpy (tree exp, rtx target)
3257 {
3258   if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3259    {
3260      tree dest = CALL_EXPR_ARG (exp, 0);
3261      tree src = CALL_EXPR_ARG (exp, 1);
3262      return expand_builtin_strcpy_args (dest, src, target);
3263    }
3264    return NULL_RTX;
3265 }
3266
3267 /* Helper function to do the actual work for expand_builtin_strcpy.  The
3268    arguments to the builtin_strcpy call DEST and SRC are broken out
3269    so that this can also be called without constructing an actual CALL_EXPR.
3270    The other arguments and return value are the same as for
3271    expand_builtin_strcpy.  */
3272
3273 static rtx
3274 expand_builtin_strcpy_args (tree dest, tree src, rtx target)
3275 {
3276   return expand_movstr (dest, src, target, /*endp=*/0);
3277 }
3278
3279 /* Expand a call EXP to the stpcpy builtin.
3280    Return NULL_RTX if we failed the caller should emit a normal call,
3281    otherwise try to get the result in TARGET, if convenient (and in
3282    mode MODE if that's convenient).  */
3283
3284 static rtx
3285 expand_builtin_stpcpy (tree exp, rtx target, enum machine_mode mode)
3286 {
3287   tree dst, src;
3288   location_t loc = EXPR_LOCATION (exp);
3289
3290   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3291     return NULL_RTX;
3292
3293   dst = CALL_EXPR_ARG (exp, 0);
3294   src = CALL_EXPR_ARG (exp, 1);
3295
3296   /* If return value is ignored, transform stpcpy into strcpy.  */
3297   if (target == const0_rtx && builtin_decl_implicit (BUILT_IN_STRCPY))
3298     {
3299       tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
3300       tree result = build_call_nofold_loc (loc, fn, 2, dst, src);
3301       return expand_expr (result, target, mode, EXPAND_NORMAL);
3302     }
3303   else
3304     {
3305       tree len, lenp1;
3306       rtx ret;
3307
3308       /* Ensure we get an actual string whose length can be evaluated at
3309          compile-time, not an expression containing a string.  This is
3310          because the latter will potentially produce pessimized code
3311          when used to produce the return value.  */
3312       if (! c_getstr (src) || ! (len = c_strlen (src, 0)))
3313         return expand_movstr (dst, src, target, /*endp=*/2);
3314
3315       lenp1 = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
3316       ret = expand_builtin_mempcpy_args (dst, src, lenp1,
3317                                          target, mode, /*endp=*/2);
3318
3319       if (ret)
3320         return ret;
3321
3322       if (TREE_CODE (len) == INTEGER_CST)
3323         {
3324           rtx len_rtx = expand_normal (len);
3325
3326           if (CONST_INT_P (len_rtx))
3327             {
3328               ret = expand_builtin_strcpy_args (dst, src, target);
3329
3330               if (ret)
3331                 {
3332                   if (! target)
3333                     {
3334                       if (mode != VOIDmode)
3335                         target = gen_reg_rtx (mode);
3336                       else
3337                         target = gen_reg_rtx (GET_MODE (ret));
3338                     }
3339                   if (GET_MODE (target) != GET_MODE (ret))
3340                     ret = gen_lowpart (GET_MODE (target), ret);
3341
3342                   ret = plus_constant (ret, INTVAL (len_rtx));
3343                   ret = emit_move_insn (target, force_operand (ret, NULL_RTX));
3344                   gcc_assert (ret);
3345
3346                   return target;
3347                 }
3348             }
3349         }
3350
3351       return expand_movstr (dst, src, target, /*endp=*/2);
3352     }
3353 }
3354
3355 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3356    bytes from constant string DATA + OFFSET and return it as target
3357    constant.  */
3358
3359 rtx
3360 builtin_strncpy_read_str (void *data, HOST_WIDE_INT offset,
3361                           enum machine_mode mode)
3362 {
3363   const char *str = (const char *) data;
3364
3365   if ((unsigned HOST_WIDE_INT) offset > strlen (str))
3366     return const0_rtx;
3367
3368   return c_readstr (str + offset, mode);
3369 }
3370
3371 /* Expand expression EXP, which is a call to the strncpy builtin.  Return
3372    NULL_RTX if we failed the caller should emit a normal call.  */
3373
3374 static rtx
3375 expand_builtin_strncpy (tree exp, rtx target)
3376 {
3377   location_t loc = EXPR_LOCATION (exp);
3378
3379   if (validate_arglist (exp,
3380                         POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3381     {
3382       tree dest = CALL_EXPR_ARG (exp, 0);
3383       tree src = CALL_EXPR_ARG (exp, 1);
3384       tree len = CALL_EXPR_ARG (exp, 2);
3385       tree slen = c_strlen (src, 1);
3386
3387       /* We must be passed a constant len and src parameter.  */
3388       if (!host_integerp (len, 1) || !slen || !host_integerp (slen, 1))
3389         return NULL_RTX;
3390
3391       slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
3392
3393       /* We're required to pad with trailing zeros if the requested
3394          len is greater than strlen(s2)+1.  In that case try to
3395          use store_by_pieces, if it fails, punt.  */
3396       if (tree_int_cst_lt (slen, len))
3397         {
3398           unsigned int dest_align = get_pointer_alignment (dest);
3399           const char *p = c_getstr (src);
3400           rtx dest_mem;
3401
3402           if (!p || dest_align == 0 || !host_integerp (len, 1)
3403               || !can_store_by_pieces (tree_low_cst (len, 1),
3404                                        builtin_strncpy_read_str,
3405                                        CONST_CAST (char *, p),
3406                                        dest_align, false))
3407             return NULL_RTX;
3408
3409           dest_mem = get_memory_rtx (dest, len);
3410           store_by_pieces (dest_mem, tree_low_cst (len, 1),
3411                            builtin_strncpy_read_str,
3412                            CONST_CAST (char *, p), dest_align, false, 0);
3413           dest_mem = force_operand (XEXP (dest_mem, 0), target);
3414           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3415           return dest_mem;
3416         }
3417     }
3418   return NULL_RTX;
3419 }
3420
3421 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3422    bytes from constant string DATA + OFFSET and return it as target
3423    constant.  */
3424
3425 rtx
3426 builtin_memset_read_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3427                          enum machine_mode mode)
3428 {
3429   const char *c = (const char *) data;
3430   char *p = XALLOCAVEC (char, GET_MODE_SIZE (mode));
3431
3432   memset (p, *c, GET_MODE_SIZE (mode));
3433
3434   return c_readstr (p, mode);
3435 }
3436
3437 /* Callback routine for store_by_pieces.  Return the RTL of a register
3438    containing GET_MODE_SIZE (MODE) consecutive copies of the unsigned
3439    char value given in the RTL register data.  For example, if mode is
3440    4 bytes wide, return the RTL for 0x01010101*data.  */
3441
3442 static rtx
3443 builtin_memset_gen_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3444                         enum machine_mode mode)
3445 {
3446   rtx target, coeff;
3447   size_t size;
3448   char *p;
3449
3450   size = GET_MODE_SIZE (mode);
3451   if (size == 1)
3452     return (rtx) data;
3453
3454   p = XALLOCAVEC (char, size);
3455   memset (p, 1, size);
3456   coeff = c_readstr (p, mode);
3457
3458   target = convert_to_mode (mode, (rtx) data, 1);
3459   target = expand_mult (mode, target, coeff, NULL_RTX, 1);
3460   return force_reg (mode, target);
3461 }
3462
3463 /* Expand expression EXP, which is a call to the memset builtin.  Return
3464    NULL_RTX if we failed the caller should emit a normal call, otherwise
3465    try to get the result in TARGET, if convenient (and in mode MODE if that's
3466    convenient).  */
3467
3468 static rtx
3469 expand_builtin_memset (tree exp, rtx target, enum machine_mode mode)
3470 {
3471   if (!validate_arglist (exp,
3472                          POINTER_TYPE, INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
3473     return NULL_RTX;
3474   else
3475     {
3476       tree dest = CALL_EXPR_ARG (exp, 0);
3477       tree val = CALL_EXPR_ARG (exp, 1);
3478       tree len = CALL_EXPR_ARG (exp, 2);
3479       return expand_builtin_memset_args (dest, val, len, target, mode, exp);
3480     }
3481 }
3482
3483 /* Helper function to do the actual work for expand_builtin_memset.  The
3484    arguments to the builtin_memset call DEST, VAL, and LEN are broken out
3485    so that this can also be called without constructing an actual CALL_EXPR.
3486    The other arguments and return value are the same as for
3487    expand_builtin_memset.  */
3488
3489 static rtx
3490 expand_builtin_memset_args (tree dest, tree val, tree len,
3491                             rtx target, enum machine_mode mode, tree orig_exp)
3492 {
3493   tree fndecl, fn;
3494   enum built_in_function fcode;
3495   enum machine_mode val_mode;
3496   char c;
3497   unsigned int dest_align;
3498   rtx dest_mem, dest_addr, len_rtx;
3499   HOST_WIDE_INT expected_size = -1;
3500   unsigned int expected_align = 0;
3501
3502   dest_align = get_pointer_alignment (dest);
3503
3504   /* If DEST is not a pointer type, don't do this operation in-line.  */
3505   if (dest_align == 0)
3506     return NULL_RTX;
3507
3508   if (currently_expanding_gimple_stmt)
3509     stringop_block_profile (currently_expanding_gimple_stmt,
3510                             &expected_align, &expected_size);
3511
3512   if (expected_align < dest_align)
3513     expected_align = dest_align;
3514
3515   /* If the LEN parameter is zero, return DEST.  */
3516   if (integer_zerop (len))
3517     {
3518       /* Evaluate and ignore VAL in case it has side-effects.  */
3519       expand_expr (val, const0_rtx, VOIDmode, EXPAND_NORMAL);
3520       return expand_expr (dest, target, mode, EXPAND_NORMAL);
3521     }
3522
3523   /* Stabilize the arguments in case we fail.  */
3524   dest = builtin_save_expr (dest);
3525   val = builtin_save_expr (val);
3526   len = builtin_save_expr (len);
3527
3528   len_rtx = expand_normal (len);
3529   dest_mem = get_memory_rtx (dest, len);
3530   val_mode = TYPE_MODE (unsigned_char_type_node);
3531
3532   if (TREE_CODE (val) != INTEGER_CST)
3533     {
3534       rtx val_rtx;
3535
3536       val_rtx = expand_normal (val);
3537       val_rtx = convert_to_mode (val_mode, val_rtx, 0);
3538
3539       /* Assume that we can memset by pieces if we can store
3540        * the coefficients by pieces (in the required modes).
3541        * We can't pass builtin_memset_gen_str as that emits RTL.  */
3542       c = 1;
3543       if (host_integerp (len, 1)
3544           && can_store_by_pieces (tree_low_cst (len, 1),
3545                                   builtin_memset_read_str, &c, dest_align,
3546                                   true))
3547         {
3548           val_rtx = force_reg (val_mode, val_rtx);
3549           store_by_pieces (dest_mem, tree_low_cst (len, 1),
3550                            builtin_memset_gen_str, val_rtx, dest_align,
3551                            true, 0);
3552         }
3553       else if (!set_storage_via_setmem (dest_mem, len_rtx, val_rtx,
3554                                         dest_align, expected_align,
3555                                         expected_size))
3556         goto do_libcall;
3557
3558       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3559       dest_mem = convert_memory_address (ptr_mode, dest_mem);
3560       return dest_mem;
3561     }
3562
3563   if (target_char_cast (val, &c))
3564     goto do_libcall;
3565
3566   if (c)
3567     {
3568       if (host_integerp (len, 1)
3569           && can_store_by_pieces (tree_low_cst (len, 1),
3570                                   builtin_memset_read_str, &c, dest_align,
3571                                   true))
3572         store_by_pieces (dest_mem, tree_low_cst (len, 1),
3573                          builtin_memset_read_str, &c, dest_align, true, 0);
3574       else if (!set_storage_via_setmem (dest_mem, len_rtx,
3575                                         gen_int_mode (c, val_mode),
3576                                         dest_align, expected_align,
3577                                         expected_size))
3578         goto do_libcall;
3579
3580       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3581       dest_mem = convert_memory_address (ptr_mode, dest_mem);
3582       return dest_mem;
3583     }
3584
3585   set_mem_align (dest_mem, dest_align);
3586   dest_addr = clear_storage_hints (dest_mem, len_rtx,
3587                                    CALL_EXPR_TAILCALL (orig_exp)
3588                                    ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
3589                                    expected_align, expected_size);
3590
3591   if (dest_addr == 0)
3592     {
3593       dest_addr = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3594       dest_addr = convert_memory_address (ptr_mode, dest_addr);
3595     }
3596
3597   return dest_addr;
3598
3599  do_libcall:
3600   fndecl = get_callee_fndecl (orig_exp);
3601   fcode = DECL_FUNCTION_CODE (fndecl);
3602   if (fcode == BUILT_IN_MEMSET)
3603     fn = build_call_nofold_loc (EXPR_LOCATION (orig_exp), fndecl, 3,
3604                                 dest, val, len);
3605   else if (fcode == BUILT_IN_BZERO)
3606     fn = build_call_nofold_loc (EXPR_LOCATION (orig_exp), fndecl, 2,
3607                                 dest, len);
3608   else
3609     gcc_unreachable ();
3610   gcc_assert (TREE_CODE (fn) == CALL_EXPR);
3611   CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (orig_exp);
3612   return expand_call (fn, target, target == const0_rtx);
3613 }
3614
3615 /* Expand expression EXP, which is a call to the bzero builtin.  Return
3616    NULL_RTX if we failed the caller should emit a normal call.  */
3617
3618 static rtx
3619 expand_builtin_bzero (tree exp)
3620 {
3621   tree dest, size;
3622   location_t loc = EXPR_LOCATION (exp);
3623
3624   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3625     return NULL_RTX;
3626
3627   dest = CALL_EXPR_ARG (exp, 0);
3628   size = CALL_EXPR_ARG (exp, 1);
3629
3630   /* New argument list transforming bzero(ptr x, int y) to
3631      memset(ptr x, int 0, size_t y).   This is done this way
3632      so that if it isn't expanded inline, we fallback to
3633      calling bzero instead of memset.  */
3634
3635   return expand_builtin_memset_args (dest, integer_zero_node,
3636                                      fold_convert_loc (loc,
3637                                                        size_type_node, size),
3638                                      const0_rtx, VOIDmode, exp);
3639 }
3640
3641 /* Expand expression EXP, which is a call to the memcmp built-in function.
3642    Return NULL_RTX if we failed and the caller should emit a normal call,
3643    otherwise try to get the result in TARGET, if convenient (and in mode
3644    MODE, if that's convenient).  */
3645
3646 static rtx
3647 expand_builtin_memcmp (tree exp, ATTRIBUTE_UNUSED rtx target,
3648                        ATTRIBUTE_UNUSED enum machine_mode mode)
3649 {
3650   location_t loc ATTRIBUTE_UNUSED = EXPR_LOCATION (exp);
3651
3652   if (!validate_arglist (exp,
3653                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3654     return NULL_RTX;
3655
3656   /* Note: The cmpstrnsi pattern, if it exists, is not suitable for
3657      implementing memcmp because it will stop if it encounters two
3658      zero bytes.  */
3659 #if defined HAVE_cmpmemsi
3660   {
3661     rtx arg1_rtx, arg2_rtx, arg3_rtx;
3662     rtx result;
3663     rtx insn;
3664     tree arg1 = CALL_EXPR_ARG (exp, 0);
3665     tree arg2 = CALL_EXPR_ARG (exp, 1);
3666     tree len = CALL_EXPR_ARG (exp, 2);
3667
3668     unsigned int arg1_align = get_pointer_alignment (arg1) / BITS_PER_UNIT;
3669     unsigned int arg2_align = get_pointer_alignment (arg2) / BITS_PER_UNIT;
3670     enum machine_mode insn_mode;
3671
3672     if (HAVE_cmpmemsi)
3673       insn_mode = insn_data[(int) CODE_FOR_cmpmemsi].operand[0].mode;
3674     else
3675       return NULL_RTX;
3676
3677     /* If we don't have POINTER_TYPE, call the function.  */
3678     if (arg1_align == 0 || arg2_align == 0)
3679       return NULL_RTX;
3680
3681     /* Make a place to write the result of the instruction.  */
3682     result = target;
3683     if (! (result != 0
3684            && REG_P (result) && GET_MODE (result) == insn_mode
3685            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3686       result = gen_reg_rtx (insn_mode);
3687
3688     arg1_rtx = get_memory_rtx (arg1, len);
3689     arg2_rtx = get_memory_rtx (arg2, len);
3690     arg3_rtx = expand_normal (fold_convert_loc (loc, sizetype, len));
3691
3692     /* Set MEM_SIZE as appropriate.  */
3693     if (CONST_INT_P (arg3_rtx))
3694       {
3695         set_mem_size (arg1_rtx, INTVAL (arg3_rtx));
3696         set_mem_size (arg2_rtx, INTVAL (arg3_rtx));
3697       }
3698
3699     if (HAVE_cmpmemsi)
3700       insn = gen_cmpmemsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3701                            GEN_INT (MIN (arg1_align, arg2_align)));
3702     else
3703       gcc_unreachable ();
3704
3705     if (insn)
3706       emit_insn (insn);
3707     else
3708       emit_library_call_value (memcmp_libfunc, result, LCT_PURE,
3709                                TYPE_MODE (integer_type_node), 3,
3710                                XEXP (arg1_rtx, 0), Pmode,
3711                                XEXP (arg2_rtx, 0), Pmode,
3712                                convert_to_mode (TYPE_MODE (sizetype), arg3_rtx,
3713                                                 TYPE_UNSIGNED (sizetype)),
3714                                TYPE_MODE (sizetype));
3715
3716     /* Return the value in the proper mode for this function.  */
3717     mode = TYPE_MODE (TREE_TYPE (exp));
3718     if (GET_MODE (result) == mode)
3719       return result;
3720     else if (target != 0)
3721       {
3722         convert_move (target, result, 0);
3723         return target;
3724       }
3725     else
3726       return convert_to_mode (mode, result, 0);
3727   }
3728 #endif /* HAVE_cmpmemsi.  */
3729
3730   return NULL_RTX;
3731 }
3732
3733 /* Expand expression EXP, which is a call to the strcmp builtin.  Return NULL_RTX
3734    if we failed the caller should emit a normal call, otherwise try to get
3735    the result in TARGET, if convenient.  */
3736
3737 static rtx
3738 expand_builtin_strcmp (tree exp, ATTRIBUTE_UNUSED rtx target)
3739 {
3740   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3741     return NULL_RTX;
3742
3743 #if defined HAVE_cmpstrsi || defined HAVE_cmpstrnsi
3744   if (direct_optab_handler (cmpstr_optab, SImode) != CODE_FOR_nothing
3745       || direct_optab_handler (cmpstrn_optab, SImode) != CODE_FOR_nothing)
3746     {
3747       rtx arg1_rtx, arg2_rtx;
3748       rtx result, insn = NULL_RTX;
3749       tree fndecl, fn;
3750       tree arg1 = CALL_EXPR_ARG (exp, 0);
3751       tree arg2 = CALL_EXPR_ARG (exp, 1);
3752
3753       unsigned int arg1_align = get_pointer_alignment (arg1) / BITS_PER_UNIT;
3754       unsigned int arg2_align = get_pointer_alignment (arg2) / BITS_PER_UNIT;
3755
3756       /* If we don't have POINTER_TYPE, call the function.  */
3757       if (arg1_align == 0 || arg2_align == 0)
3758         return NULL_RTX;
3759
3760       /* Stabilize the arguments in case gen_cmpstr(n)si fail.  */
3761       arg1 = builtin_save_expr (arg1);
3762       arg2 = builtin_save_expr (arg2);
3763
3764       arg1_rtx = get_memory_rtx (arg1, NULL);
3765       arg2_rtx = get_memory_rtx (arg2, NULL);
3766
3767 #ifdef HAVE_cmpstrsi
3768       /* Try to call cmpstrsi.  */
3769       if (HAVE_cmpstrsi)
3770         {
3771           enum machine_mode insn_mode
3772             = insn_data[(int) CODE_FOR_cmpstrsi].operand[0].mode;
3773
3774           /* Make a place to write the result of the instruction.  */
3775           result = target;
3776           if (! (result != 0
3777                  && REG_P (result) && GET_MODE (result) == insn_mode
3778                  && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3779             result = gen_reg_rtx (insn_mode);
3780
3781           insn = gen_cmpstrsi (result, arg1_rtx, arg2_rtx,
3782                                GEN_INT (MIN (arg1_align, arg2_align)));
3783         }
3784 #endif
3785 #ifdef HAVE_cmpstrnsi
3786       /* Try to determine at least one length and call cmpstrnsi.  */
3787       if (!insn && HAVE_cmpstrnsi)
3788         {
3789           tree len;
3790           rtx arg3_rtx;
3791
3792           enum machine_mode insn_mode
3793             = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
3794           tree len1 = c_strlen (arg1, 1);
3795           tree len2 = c_strlen (arg2, 1);
3796
3797           if (len1)
3798             len1 = size_binop (PLUS_EXPR, ssize_int (1), len1);
3799           if (len2)
3800             len2 = size_binop (PLUS_EXPR, ssize_int (1), len2);
3801
3802           /* If we don't have a constant length for the first, use the length
3803              of the second, if we know it.  We don't require a constant for
3804              this case; some cost analysis could be done if both are available
3805              but neither is constant.  For now, assume they're equally cheap,
3806              unless one has side effects.  If both strings have constant lengths,
3807              use the smaller.  */
3808
3809           if (!len1)
3810             len = len2;
3811           else if (!len2)
3812             len = len1;
3813           else if (TREE_SIDE_EFFECTS (len1))
3814             len = len2;
3815           else if (TREE_SIDE_EFFECTS (len2))
3816             len = len1;
3817           else if (TREE_CODE (len1) != INTEGER_CST)
3818             len = len2;
3819           else if (TREE_CODE (len2) != INTEGER_CST)
3820             len = len1;
3821           else if (tree_int_cst_lt (len1, len2))
3822             len = len1;
3823           else
3824             len = len2;
3825
3826           /* If both arguments have side effects, we cannot optimize.  */
3827           if (!len || TREE_SIDE_EFFECTS (len))
3828             goto do_libcall;
3829
3830           arg3_rtx = expand_normal (len);
3831
3832           /* Make a place to write the result of the instruction.  */
3833           result = target;
3834           if (! (result != 0
3835                  && REG_P (result) && GET_MODE (result) == insn_mode
3836                  && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3837             result = gen_reg_rtx (insn_mode);
3838
3839           insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3840                                 GEN_INT (MIN (arg1_align, arg2_align)));
3841         }
3842 #endif
3843
3844       if (insn)
3845         {
3846           enum machine_mode mode;
3847           emit_insn (insn);
3848
3849           /* Return the value in the proper mode for this function.  */
3850           mode = TYPE_MODE (TREE_TYPE (exp));
3851           if (GET_MODE (result) == mode)
3852             return result;
3853           if (target == 0)
3854             return convert_to_mode (mode, result, 0);
3855           convert_move (target, result, 0);
3856           return target;
3857         }
3858
3859       /* Expand the library call ourselves using a stabilized argument
3860          list to avoid re-evaluating the function's arguments twice.  */
3861 #ifdef HAVE_cmpstrnsi
3862     do_libcall:
3863 #endif
3864       fndecl = get_callee_fndecl (exp);
3865       fn = build_call_nofold_loc (EXPR_LOCATION (exp), fndecl, 2, arg1, arg2);
3866       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
3867       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
3868       return expand_call (fn, target, target == const0_rtx);
3869     }
3870 #endif
3871   return NULL_RTX;
3872 }
3873
3874 /* Expand expression EXP, which is a call to the strncmp builtin. Return
3875    NULL_RTX if we failed the caller should emit a normal call, otherwise try to get
3876    the result in TARGET, if convenient.  */
3877
3878 static rtx
3879 expand_builtin_strncmp (tree exp, ATTRIBUTE_UNUSED rtx target,
3880                         ATTRIBUTE_UNUSED enum machine_mode mode)
3881 {
3882   location_t loc ATTRIBUTE_UNUSED = EXPR_LOCATION (exp);
3883
3884   if (!validate_arglist (exp,
3885                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3886     return NULL_RTX;
3887
3888   /* If c_strlen can determine an expression for one of the string
3889      lengths, and it doesn't have side effects, then emit cmpstrnsi
3890      using length MIN(strlen(string)+1, arg3).  */
3891 #ifdef HAVE_cmpstrnsi
3892   if (HAVE_cmpstrnsi)
3893   {
3894     tree len, len1, len2;
3895     rtx arg1_rtx, arg2_rtx, arg3_rtx;
3896     rtx result, insn;
3897     tree fndecl, fn;
3898     tree arg1 = CALL_EXPR_ARG (exp, 0);
3899     tree arg2 = CALL_EXPR_ARG (exp, 1);
3900     tree arg3 = CALL_EXPR_ARG (exp, 2);
3901
3902     unsigned int arg1_align = get_pointer_alignment (arg1) / BITS_PER_UNIT;
3903     unsigned int arg2_align = get_pointer_alignment (arg2) / BITS_PER_UNIT;
3904     enum machine_mode insn_mode
3905       = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
3906
3907     len1 = c_strlen (arg1, 1);
3908     len2 = c_strlen (arg2, 1);
3909
3910     if (len1)
3911       len1 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len1);
3912     if (len2)
3913       len2 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len2);
3914
3915     /* If we don't have a constant length for the first, use the length
3916        of the second, if we know it.  We don't require a constant for
3917        this case; some cost analysis could be done if both are available
3918        but neither is constant.  For now, assume they're equally cheap,
3919        unless one has side effects.  If both strings have constant lengths,
3920        use the smaller.  */
3921
3922     if (!len1)
3923       len = len2;
3924     else if (!len2)
3925       len = len1;
3926     else if (TREE_SIDE_EFFECTS (len1))
3927       len = len2;
3928     else if (TREE_SIDE_EFFECTS (len2))
3929       len = len1;
3930     else if (TREE_CODE (len1) != INTEGER_CST)
3931       len = len2;
3932     else if (TREE_CODE (len2) != INTEGER_CST)
3933       len = len1;
3934     else if (tree_int_cst_lt (len1, len2))
3935       len = len1;
3936     else
3937       len = len2;
3938
3939     /* If both arguments have side effects, we cannot optimize.  */
3940     if (!len || TREE_SIDE_EFFECTS (len))
3941       return NULL_RTX;
3942
3943     /* The actual new length parameter is MIN(len,arg3).  */
3944     len = fold_build2_loc (loc, MIN_EXPR, TREE_TYPE (len), len,
3945                        fold_convert_loc (loc, TREE_TYPE (len), arg3));
3946
3947     /* If we don't have POINTER_TYPE, call the function.  */
3948     if (arg1_align == 0 || arg2_align == 0)
3949       return NULL_RTX;
3950
3951     /* Make a place to write the result of the instruction.  */
3952     result = target;
3953     if (! (result != 0
3954            && REG_P (result) && GET_MODE (result) == insn_mode
3955            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3956       result = gen_reg_rtx (insn_mode);
3957
3958     /* Stabilize the arguments in case gen_cmpstrnsi fails.  */
3959     arg1 = builtin_save_expr (arg1);
3960     arg2 = builtin_save_expr (arg2);
3961     len = builtin_save_expr (len);
3962
3963     arg1_rtx = get_memory_rtx (arg1, len);
3964     arg2_rtx = get_memory_rtx (arg2, len);
3965     arg3_rtx = expand_normal (len);
3966     insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3967                           GEN_INT (MIN (arg1_align, arg2_align)));
3968     if (insn)
3969       {
3970         emit_insn (insn);
3971
3972         /* Return the value in the proper mode for this function.  */
3973         mode = TYPE_MODE (TREE_TYPE (exp));
3974         if (GET_MODE (result) == mode)
3975           return result;
3976         if (target == 0)
3977           return convert_to_mode (mode, result, 0);
3978         convert_move (target, result, 0);
3979         return target;
3980       }
3981
3982     /* Expand the library call ourselves using a stabilized argument
3983        list to avoid re-evaluating the function's arguments twice.  */
3984     fndecl = get_callee_fndecl (exp);
3985     fn = build_call_nofold_loc (EXPR_LOCATION (exp), fndecl, 3,
3986                                 arg1, arg2, len);
3987     gcc_assert (TREE_CODE (fn) == CALL_EXPR);
3988     CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
3989     return expand_call (fn, target, target == const0_rtx);
3990   }
3991 #endif
3992   return NULL_RTX;
3993 }
3994
3995 /* Expand a call to __builtin_saveregs, generating the result in TARGET,
3996    if that's convenient.  */
3997
3998 rtx
3999 expand_builtin_saveregs (void)
4000 {
4001   rtx val, seq;
4002
4003   /* Don't do __builtin_saveregs more than once in a function.
4004      Save the result of the first call and reuse it.  */
4005   if (saveregs_value != 0)
4006     return saveregs_value;
4007
4008   /* When this function is called, it means that registers must be
4009      saved on entry to this function.  So we migrate the call to the
4010      first insn of this function.  */
4011
4012   start_sequence ();
4013
4014   /* Do whatever the machine needs done in this case.  */
4015   val = targetm.calls.expand_builtin_saveregs ();
4016
4017   seq = get_insns ();
4018   end_sequence ();
4019
4020   saveregs_value = val;
4021
4022   /* Put the insns after the NOTE that starts the function.  If this
4023      is inside a start_sequence, make the outer-level insn chain current, so
4024      the code is placed at the start of the function.  */
4025   push_topmost_sequence ();
4026   emit_insn_after (seq, entry_of_function ());
4027   pop_topmost_sequence ();
4028
4029   return val;
4030 }
4031
4032 /* Expand a call to __builtin_next_arg.  */
4033
4034 static rtx
4035 expand_builtin_next_arg (void)
4036 {
4037   /* Checking arguments is already done in fold_builtin_next_arg
4038      that must be called before this function.  */
4039   return expand_binop (ptr_mode, add_optab,
4040                        crtl->args.internal_arg_pointer,
4041                        crtl->args.arg_offset_rtx,
4042                        NULL_RTX, 0, OPTAB_LIB_WIDEN);
4043 }
4044
4045 /* Make it easier for the backends by protecting the valist argument
4046    from multiple evaluations.  */
4047
4048 static tree
4049 stabilize_va_list_loc (location_t loc, tree valist, int needs_lvalue)
4050 {
4051   tree vatype = targetm.canonical_va_list_type (TREE_TYPE (valist));
4052
4053   /* The current way of determining the type of valist is completely
4054      bogus.  We should have the information on the va builtin instead.  */
4055   if (!vatype)
4056     vatype = targetm.fn_abi_va_list (cfun->decl);
4057
4058   if (TREE_CODE (vatype) == ARRAY_TYPE)
4059     {
4060       if (TREE_SIDE_EFFECTS (valist))
4061         valist = save_expr (valist);
4062
4063       /* For this case, the backends will be expecting a pointer to
4064          vatype, but it's possible we've actually been given an array
4065          (an actual TARGET_CANONICAL_VA_LIST_TYPE (valist)).
4066          So fix it.  */
4067       if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
4068         {
4069           tree p1 = build_pointer_type (TREE_TYPE (vatype));
4070           valist = build_fold_addr_expr_with_type_loc (loc, valist, p1);
4071         }
4072     }
4073   else
4074     {
4075       tree pt = build_pointer_type (vatype);
4076
4077       if (! needs_lvalue)
4078         {
4079           if (! TREE_SIDE_EFFECTS (valist))
4080             return valist;
4081
4082           valist = fold_build1_loc (loc, ADDR_EXPR, pt, valist);
4083           TREE_SIDE_EFFECTS (valist) = 1;
4084         }
4085
4086       if (TREE_SIDE_EFFECTS (valist))
4087         valist = save_expr (valist);
4088       valist = fold_build2_loc (loc, MEM_REF,
4089                                 vatype, valist, build_int_cst (pt, 0));
4090     }
4091
4092   return valist;
4093 }
4094
4095 /* The "standard" definition of va_list is void*.  */
4096
4097 tree
4098 std_build_builtin_va_list (void)
4099 {
4100   return ptr_type_node;
4101 }
4102
4103 /* The "standard" abi va_list is va_list_type_node.  */
4104
4105 tree
4106 std_fn_abi_va_list (tree fndecl ATTRIBUTE_UNUSED)
4107 {
4108   return va_list_type_node;
4109 }
4110
4111 /* The "standard" type of va_list is va_list_type_node.  */
4112
4113 tree
4114 std_canonical_va_list_type (tree type)
4115 {
4116   tree wtype, htype;
4117
4118   if (INDIRECT_REF_P (type))
4119     type = TREE_TYPE (type);
4120   else if (POINTER_TYPE_P (type) && POINTER_TYPE_P (TREE_TYPE(type)))
4121     type = TREE_TYPE (type);
4122   wtype = va_list_type_node;
4123   htype = type;
4124   /* Treat structure va_list types.  */
4125   if (TREE_CODE (wtype) == RECORD_TYPE && POINTER_TYPE_P (htype))
4126     htype = TREE_TYPE (htype);
4127   else if (TREE_CODE (wtype) == ARRAY_TYPE)
4128     {
4129       /* If va_list is an array type, the argument may have decayed
4130          to a pointer type, e.g. by being passed to another function.
4131          In that case, unwrap both types so that we can compare the
4132          underlying records.  */
4133       if (TREE_CODE (htype) == ARRAY_TYPE
4134           || POINTER_TYPE_P (htype))
4135         {
4136           wtype = TREE_TYPE (wtype);
4137           htype = TREE_TYPE (htype);
4138         }
4139     }
4140   if (TYPE_MAIN_VARIANT (wtype) == TYPE_MAIN_VARIANT (htype))
4141     return va_list_type_node;
4142
4143   return NULL_TREE;
4144 }
4145
4146 /* The "standard" implementation of va_start: just assign `nextarg' to
4147    the variable.  */
4148
4149 void
4150 std_expand_builtin_va_start (tree valist, rtx nextarg)
4151 {
4152   rtx va_r = expand_expr (valist, NULL_RTX, VOIDmode, EXPAND_WRITE);
4153   convert_move (va_r, nextarg, 0);
4154 }
4155
4156 /* Expand EXP, a call to __builtin_va_start.  */
4157
4158 static rtx
4159 expand_builtin_va_start (tree exp)
4160 {
4161   rtx nextarg;
4162   tree valist;
4163   location_t loc = EXPR_LOCATION (exp);
4164
4165   if (call_expr_nargs (exp) < 2)
4166     {
4167       error_at (loc, "too few arguments to function %<va_start%>");
4168       return const0_rtx;
4169     }
4170
4171   if (fold_builtin_next_arg (exp, true))
4172     return const0_rtx;
4173
4174   nextarg = expand_builtin_next_arg ();
4175   valist = stabilize_va_list_loc (loc, CALL_EXPR_ARG (exp, 0), 1);
4176
4177   if (targetm.expand_builtin_va_start)
4178     targetm.expand_builtin_va_start (valist, nextarg);
4179   else
4180     std_expand_builtin_va_start (valist, nextarg);
4181
4182   return const0_rtx;
4183 }
4184
4185 /* The "standard" implementation of va_arg: read the value from the
4186    current (padded) address and increment by the (padded) size.  */
4187
4188 tree
4189 std_gimplify_va_arg_expr (tree valist, tree type, gimple_seq *pre_p,
4190                           gimple_seq *post_p)
4191 {
4192   tree addr, t, type_size, rounded_size, valist_tmp;
4193   unsigned HOST_WIDE_INT align, boundary;
4194   bool indirect;
4195
4196 #ifdef ARGS_GROW_DOWNWARD
4197   /* All of the alignment and movement below is for args-grow-up machines.
4198      As of 2004, there are only 3 ARGS_GROW_DOWNWARD targets, and they all
4199      implement their own specialized gimplify_va_arg_expr routines.  */
4200   gcc_unreachable ();
4201 #endif
4202
4203   indirect = pass_by_reference (NULL, TYPE_MODE (type), type, false);
4204   if (indirect)
4205     type = build_pointer_type (type);
4206
4207   align = PARM_BOUNDARY / BITS_PER_UNIT;
4208   boundary = targetm.calls.function_arg_boundary (TYPE_MODE (type), type);
4209
4210   /* When we align parameter on stack for caller, if the parameter
4211      alignment is beyond MAX_SUPPORTED_STACK_ALIGNMENT, it will be
4212      aligned at MAX_SUPPORTED_STACK_ALIGNMENT.  We will match callee
4213      here with caller.  */
4214   if (boundary > MAX_SUPPORTED_STACK_ALIGNMENT)
4215     boundary = MAX_SUPPORTED_STACK_ALIGNMENT;
4216
4217   boundary /= BITS_PER_UNIT;
4218
4219   /* Hoist the valist value into a temporary for the moment.  */
4220   valist_tmp = get_initialized_tmp_var (valist, pre_p, NULL);
4221
4222   /* va_list pointer is aligned to PARM_BOUNDARY.  If argument actually
4223      requires greater alignment, we must perform dynamic alignment.  */
4224   if (boundary > align
4225       && !integer_zerop (TYPE_SIZE (type)))
4226     {
4227       t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
4228                   fold_build_pointer_plus_hwi (valist_tmp, boundary - 1));
4229       gimplify_and_add (t, pre_p);
4230
4231       t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
4232                   fold_build2 (BIT_AND_EXPR, TREE_TYPE (valist),
4233                                valist_tmp,
4234                                build_int_cst (TREE_TYPE (valist), -boundary)));
4235       gimplify_and_add (t, pre_p);
4236     }
4237   else
4238     boundary = align;
4239
4240   /* If the actual alignment is less than the alignment of the type,
4241      adjust the type accordingly so that we don't assume strict alignment
4242      when dereferencing the pointer.  */
4243   boundary *= BITS_PER_UNIT;
4244   if (boundary < TYPE_ALIGN (type))
4245     {
4246       type = build_variant_type_copy (type);
4247       TYPE_ALIGN (type) = boundary;
4248     }
4249
4250   /* Compute the rounded size of the type.  */
4251   type_size = size_in_bytes (type);
4252   rounded_size = round_up (type_size, align);
4253
4254   /* Reduce rounded_size so it's sharable with the postqueue.  */
4255   gimplify_expr (&rounded_size, pre_p, post_p, is_gimple_val, fb_rvalue);
4256
4257   /* Get AP.  */
4258   addr = valist_tmp;
4259   if (PAD_VARARGS_DOWN && !integer_zerop (rounded_size))
4260     {
4261       /* Small args are padded downward.  */
4262       t = fold_build2_loc (input_location, GT_EXPR, sizetype,
4263                        rounded_size, size_int (align));
4264       t = fold_build3 (COND_EXPR, sizetype, t, size_zero_node,
4265                        size_binop (MINUS_EXPR, rounded_size, type_size));
4266       addr = fold_build_pointer_plus (addr, t);
4267     }
4268
4269   /* Compute new value for AP.  */
4270   t = fold_build_pointer_plus (valist_tmp, rounded_size);
4271   t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist, t);
4272   gimplify_and_add (t, pre_p);
4273
4274   addr = fold_convert (build_pointer_type (type), addr);
4275
4276   if (indirect)
4277     addr = build_va_arg_indirect_ref (addr);
4278
4279   return build_va_arg_indirect_ref (addr);
4280 }
4281
4282 /* Build an indirect-ref expression over the given TREE, which represents a
4283    piece of a va_arg() expansion.  */
4284 tree
4285 build_va_arg_indirect_ref (tree addr)
4286 {
4287   addr = build_simple_mem_ref_loc (EXPR_LOCATION (addr), addr);
4288
4289   if (flag_mudflap) /* Don't instrument va_arg INDIRECT_REF.  */
4290     mf_mark (addr);
4291
4292   return addr;
4293 }
4294
4295 /* Return a dummy expression of type TYPE in order to keep going after an
4296    error.  */
4297
4298 static tree
4299 dummy_object (tree type)
4300 {
4301   tree t = build_int_cst (build_pointer_type (type), 0);
4302   return build2 (MEM_REF, type, t, t);
4303 }
4304
4305 /* Gimplify __builtin_va_arg, aka VA_ARG_EXPR, which is not really a
4306    builtin function, but a very special sort of operator.  */
4307
4308 enum gimplify_status
4309 gimplify_va_arg_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p)
4310 {
4311   tree promoted_type, have_va_type;
4312   tree valist = TREE_OPERAND (*expr_p, 0);
4313   tree type = TREE_TYPE (*expr_p);
4314   tree t;
4315   location_t loc = EXPR_LOCATION (*expr_p);
4316
4317   /* Verify that valist is of the proper type.  */
4318   have_va_type = TREE_TYPE (valist);
4319   if (have_va_type == error_mark_node)
4320     return GS_ERROR;
4321   have_va_type = targetm.canonical_va_list_type (have_va_type);
4322
4323   if (have_va_type == NULL_TREE)
4324     {
4325       error_at (loc, "first argument to %<va_arg%> not of type %<va_list%>");
4326       return GS_ERROR;
4327     }
4328
4329   /* Generate a diagnostic for requesting data of a type that cannot
4330      be passed through `...' due to type promotion at the call site.  */
4331   if ((promoted_type = lang_hooks.types.type_promotes_to (type))
4332            != type)
4333     {
4334       static bool gave_help;
4335       bool warned;
4336
4337       /* Unfortunately, this is merely undefined, rather than a constraint
4338          violation, so we cannot make this an error.  If this call is never
4339          executed, the program is still strictly conforming.  */
4340       warned = warning_at (loc, 0,
4341                            "%qT is promoted to %qT when passed through %<...%>",
4342                            type, promoted_type);
4343       if (!gave_help && warned)
4344         {
4345           gave_help = true;
4346           inform (loc, "(so you should pass %qT not %qT to %<va_arg%>)",
4347                   promoted_type, type);
4348         }
4349
4350       /* We can, however, treat "undefined" any way we please.
4351          Call abort to encourage the user to fix the program.  */
4352       if (warned)
4353         inform (loc, "if this code is reached, the program will abort");
4354       /* Before the abort, allow the evaluation of the va_list
4355          expression to exit or longjmp.  */
4356       gimplify_and_add (valist, pre_p);
4357       t = build_call_expr_loc (loc,
4358                                builtin_decl_implicit (BUILT_IN_TRAP), 0);
4359       gimplify_and_add (t, pre_p);
4360
4361       /* This is dead code, but go ahead and finish so that the
4362          mode of the result comes out right.  */
4363       *expr_p = dummy_object (type);
4364       return GS_ALL_DONE;
4365     }
4366   else
4367     {
4368       /* Make it easier for the backends by protecting the valist argument
4369          from multiple evaluations.  */
4370       if (TREE_CODE (have_va_type) == ARRAY_TYPE)
4371         {
4372           /* For this case, the backends will be expecting a pointer to
4373              TREE_TYPE (abi), but it's possible we've
4374              actually been given an array (an actual TARGET_FN_ABI_VA_LIST).
4375              So fix it.  */
4376           if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
4377             {
4378               tree p1 = build_pointer_type (TREE_TYPE (have_va_type));
4379               valist = fold_convert_loc (loc, p1,
4380                                          build_fold_addr_expr_loc (loc, valist));
4381             }
4382
4383           gimplify_expr (&valist, pre_p, post_p, is_gimple_val, fb_rvalue);
4384         }
4385       else
4386         gimplify_expr (&valist, pre_p, post_p, is_gimple_min_lval, fb_lvalue);
4387
4388       if (!targetm.gimplify_va_arg_expr)
4389         /* FIXME: Once most targets are converted we should merely
4390            assert this is non-null.  */
4391         return GS_ALL_DONE;
4392
4393       *expr_p = targetm.gimplify_va_arg_expr (valist, type, pre_p, post_p);
4394       return GS_OK;
4395     }
4396 }
4397
4398 /* Expand EXP, a call to __builtin_va_end.  */
4399
4400 static rtx
4401 expand_builtin_va_end (tree exp)
4402 {
4403   tree valist = CALL_EXPR_ARG (exp, 0);
4404
4405   /* Evaluate for side effects, if needed.  I hate macros that don't
4406      do that.  */
4407   if (TREE_SIDE_EFFECTS (valist))
4408     expand_expr (valist, const0_rtx, VOIDmode, EXPAND_NORMAL);
4409
4410   return const0_rtx;
4411 }
4412
4413 /* Expand EXP, a call to __builtin_va_copy.  We do this as a
4414    builtin rather than just as an assignment in stdarg.h because of the
4415    nastiness of array-type va_list types.  */
4416
4417 static rtx
4418 expand_builtin_va_copy (tree exp)
4419 {
4420   tree dst, src, t;
4421   location_t loc = EXPR_LOCATION (exp);
4422
4423   dst = CALL_EXPR_ARG (exp, 0);
4424   src = CALL_EXPR_ARG (exp, 1);
4425
4426   dst = stabilize_va_list_loc (loc, dst, 1);
4427   src = stabilize_va_list_loc (loc, src, 0);
4428
4429   gcc_assert (cfun != NULL && cfun->decl != NULL_TREE);
4430
4431   if (TREE_CODE (targetm.fn_abi_va_list (cfun->decl)) != ARRAY_TYPE)
4432     {
4433       t = build2 (MODIFY_EXPR, targetm.fn_abi_va_list (cfun->decl), dst, src);
4434       TREE_SIDE_EFFECTS (t) = 1;
4435       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4436     }
4437   else
4438     {
4439       rtx dstb, srcb, size;
4440
4441       /* Evaluate to pointers.  */
4442       dstb = expand_expr (dst, NULL_RTX, Pmode, EXPAND_NORMAL);
4443       srcb = expand_expr (src, NULL_RTX, Pmode, EXPAND_NORMAL);
4444       size = expand_expr (TYPE_SIZE_UNIT (targetm.fn_abi_va_list (cfun->decl)),
4445                   NULL_RTX, VOIDmode, EXPAND_NORMAL);
4446
4447       dstb = convert_memory_address (Pmode, dstb);
4448       srcb = convert_memory_address (Pmode, srcb);
4449
4450       /* "Dereference" to BLKmode memories.  */
4451       dstb = gen_rtx_MEM (BLKmode, dstb);
4452       set_mem_alias_set (dstb, get_alias_set (TREE_TYPE (TREE_TYPE (dst))));
4453       set_mem_align (dstb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4454       srcb = gen_rtx_MEM (BLKmode, srcb);
4455       set_mem_alias_set (srcb, get_alias_set (TREE_TYPE (TREE_TYPE (src))));
4456       set_mem_align (srcb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4457
4458       /* Copy.  */
4459       emit_block_move (dstb, srcb, size, BLOCK_OP_NORMAL);
4460     }
4461
4462   return const0_rtx;
4463 }
4464
4465 /* Expand a call to one of the builtin functions __builtin_frame_address or
4466    __builtin_return_address.  */
4467
4468 static rtx
4469 expand_builtin_frame_address (tree fndecl, tree exp)
4470 {
4471   /* The argument must be a nonnegative integer constant.
4472      It counts the number of frames to scan up the stack.
4473      The value is the return address saved in that frame.  */
4474   if (call_expr_nargs (exp) == 0)
4475     /* Warning about missing arg was already issued.  */
4476     return const0_rtx;
4477   else if (! host_integerp (CALL_EXPR_ARG (exp, 0), 1))
4478     {
4479       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4480         error ("invalid argument to %<__builtin_frame_address%>");
4481       else
4482         error ("invalid argument to %<__builtin_return_address%>");
4483       return const0_rtx;
4484     }
4485   else
4486     {
4487       rtx tem
4488         = expand_builtin_return_addr (DECL_FUNCTION_CODE (fndecl),
4489                                       tree_low_cst (CALL_EXPR_ARG (exp, 0), 1));
4490
4491       /* Some ports cannot access arbitrary stack frames.  */
4492       if (tem == NULL)
4493         {
4494           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4495             warning (0, "unsupported argument to %<__builtin_frame_address%>");
4496           else
4497             warning (0, "unsupported argument to %<__builtin_return_address%>");
4498           return const0_rtx;
4499         }
4500
4501       /* For __builtin_frame_address, return what we've got.  */
4502       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4503         return tem;
4504
4505       if (!REG_P (tem)
4506           && ! CONSTANT_P (tem))
4507         tem = copy_to_mode_reg (Pmode, tem);
4508       return tem;
4509     }
4510 }
4511
4512 /* Expand EXP, a call to the alloca builtin.  Return NULL_RTX if we
4513    failed and the caller should emit a normal call.  CANNOT_ACCUMULATE
4514    is the same as for allocate_dynamic_stack_space.  */
4515
4516 static rtx
4517 expand_builtin_alloca (tree exp, bool cannot_accumulate)
4518 {
4519   rtx op0;
4520   rtx result;
4521   bool valid_arglist;
4522   unsigned int align;
4523   bool alloca_with_align = (DECL_FUNCTION_CODE (get_callee_fndecl (exp))
4524                             == BUILT_IN_ALLOCA_WITH_ALIGN);
4525
4526   /* Emit normal call if marked not-inlineable.  */
4527   if (CALL_CANNOT_INLINE_P (exp))
4528     return NULL_RTX;
4529
4530   valid_arglist
4531     = (alloca_with_align
4532        ? validate_arglist (exp, INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE)
4533        : validate_arglist (exp, INTEGER_TYPE, VOID_TYPE));
4534
4535   if (!valid_arglist)
4536     return NULL_RTX;
4537
4538   /* Compute the argument.  */
4539   op0 = expand_normal (CALL_EXPR_ARG (exp, 0));
4540
4541   /* Compute the alignment.  */
4542   align = (alloca_with_align
4543            ? TREE_INT_CST_LOW (CALL_EXPR_ARG (exp, 1))
4544            : BIGGEST_ALIGNMENT);
4545
4546   /* Allocate the desired space.  */
4547   result = allocate_dynamic_stack_space (op0, 0, align, cannot_accumulate);
4548   result = convert_memory_address (ptr_mode, result);
4549
4550   return result;
4551 }
4552
4553 /* Expand a call to a bswap builtin with argument ARG0.  MODE
4554    is the mode to expand with.  */
4555
4556 static rtx
4557 expand_builtin_bswap (tree exp, rtx target, rtx subtarget)
4558 {
4559   enum machine_mode mode;
4560   tree arg;
4561   rtx op0;
4562
4563   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4564     return NULL_RTX;
4565
4566   arg = CALL_EXPR_ARG (exp, 0);
4567   mode = TYPE_MODE (TREE_TYPE (arg));
4568   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
4569
4570   target = expand_unop (mode, bswap_optab, op0, target, 1);
4571
4572   gcc_assert (target);
4573
4574   return convert_to_mode (mode, target, 0);
4575 }
4576
4577 /* Expand a call to a unary builtin in EXP.
4578    Return NULL_RTX if a normal call should be emitted rather than expanding the
4579    function in-line.  If convenient, the result should be placed in TARGET.
4580    SUBTARGET may be used as the target for computing one of EXP's operands.  */
4581
4582 static rtx
4583 expand_builtin_unop (enum machine_mode target_mode, tree exp, rtx target,
4584                      rtx subtarget, optab op_optab)
4585 {
4586   rtx op0;
4587
4588   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4589     return NULL_RTX;
4590
4591   /* Compute the argument.  */
4592   op0 = expand_expr (CALL_EXPR_ARG (exp, 0),
4593                      (subtarget
4594                       && (TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 0)))
4595                           == GET_MODE (subtarget))) ? subtarget : NULL_RTX,
4596                      VOIDmode, EXPAND_NORMAL);
4597   /* Compute op, into TARGET if possible.
4598      Set TARGET to wherever the result comes back.  */
4599   target = expand_unop (TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 0))),
4600                         op_optab, op0, target, op_optab != clrsb_optab);
4601   gcc_assert (target);
4602
4603   return convert_to_mode (target_mode, target, 0);
4604 }
4605
4606 /* Expand a call to __builtin_expect.  We just return our argument
4607    as the builtin_expect semantic should've been already executed by
4608    tree branch prediction pass. */
4609
4610 static rtx
4611 expand_builtin_expect (tree exp, rtx target)
4612 {
4613   tree arg;
4614
4615   if (call_expr_nargs (exp) < 2)
4616     return const0_rtx;
4617   arg = CALL_EXPR_ARG (exp, 0);
4618
4619   target = expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
4620   /* When guessing was done, the hints should be already stripped away.  */
4621   gcc_assert (!flag_guess_branch_prob
4622               || optimize == 0 || seen_error ());
4623   return target;
4624 }
4625
4626 /* Expand a call to __builtin_assume_aligned.  We just return our first
4627    argument as the builtin_assume_aligned semantic should've been already
4628    executed by CCP.  */
4629
4630 static rtx
4631 expand_builtin_assume_aligned (tree exp, rtx target)
4632 {
4633   if (call_expr_nargs (exp) < 2)
4634     return const0_rtx;
4635   target = expand_expr (CALL_EXPR_ARG (exp, 0), target, VOIDmode,
4636                         EXPAND_NORMAL);
4637   gcc_assert (!TREE_SIDE_EFFECTS (CALL_EXPR_ARG (exp, 1))
4638               && (call_expr_nargs (exp) < 3
4639                   || !TREE_SIDE_EFFECTS (CALL_EXPR_ARG (exp, 2))));
4640   return target;
4641 }
4642
4643 void
4644 expand_builtin_trap (void)
4645 {
4646 #ifdef HAVE_trap
4647   if (HAVE_trap)
4648     emit_insn (gen_trap ());
4649   else
4650 #endif
4651     emit_library_call (abort_libfunc, LCT_NORETURN, VOIDmode, 0);
4652   emit_barrier ();
4653 }
4654
4655 /* Expand a call to __builtin_unreachable.  We do nothing except emit
4656    a barrier saying that control flow will not pass here.
4657
4658    It is the responsibility of the program being compiled to ensure
4659    that control flow does never reach __builtin_unreachable.  */
4660 static void
4661 expand_builtin_unreachable (void)
4662 {
4663   emit_barrier ();
4664 }
4665
4666 /* Expand EXP, a call to fabs, fabsf or fabsl.
4667    Return NULL_RTX if a normal call should be emitted rather than expanding
4668    the function inline.  If convenient, the result should be placed
4669    in TARGET.  SUBTARGET may be used as the target for computing
4670    the operand.  */
4671
4672 static rtx
4673 expand_builtin_fabs (tree exp, rtx target, rtx subtarget)
4674 {
4675   enum machine_mode mode;
4676   tree arg;
4677   rtx op0;
4678
4679   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
4680     return NULL_RTX;
4681
4682   arg = CALL_EXPR_ARG (exp, 0);
4683   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
4684   mode = TYPE_MODE (TREE_TYPE (arg));
4685   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
4686   return expand_abs (mode, op0, target, 0, safe_from_p (target, arg, 1));
4687 }
4688
4689 /* Expand EXP, a call to copysign, copysignf, or copysignl.
4690    Return NULL is a normal call should be emitted rather than expanding the
4691    function inline.  If convenient, the result should be placed in TARGET.
4692    SUBTARGET may be used as the target for computing the operand.  */
4693
4694 static rtx
4695 expand_builtin_copysign (tree exp, rtx target, rtx subtarget)
4696 {
4697   rtx op0, op1;
4698   tree arg;
4699
4700   if (!validate_arglist (exp, REAL_TYPE, REAL_TYPE, VOID_TYPE))
4701     return NULL_RTX;
4702
4703   arg = CALL_EXPR_ARG (exp, 0);
4704   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
4705
4706   arg = CALL_EXPR_ARG (exp, 1);
4707   op1 = expand_normal (arg);
4708
4709   return expand_copysign (op0, op1, target);
4710 }
4711
4712 /* Create a new constant string literal and return a char* pointer to it.
4713    The STRING_CST value is the LEN characters at STR.  */
4714 tree
4715 build_string_literal (int len, const char *str)
4716 {
4717   tree t, elem, index, type;
4718
4719   t = build_string (len, str);
4720   elem = build_type_variant (char_type_node, 1, 0);
4721   index = build_index_type (size_int (len - 1));
4722   type = build_array_type (elem, index);
4723   TREE_TYPE (t) = type;
4724   TREE_CONSTANT (t) = 1;
4725   TREE_READONLY (t) = 1;
4726   TREE_STATIC (t) = 1;
4727
4728   type = build_pointer_type (elem);
4729   t = build1 (ADDR_EXPR, type,
4730               build4 (ARRAY_REF, elem,
4731                       t, integer_zero_node, NULL_TREE, NULL_TREE));
4732   return t;
4733 }
4734
4735 /* Expand a call to __builtin___clear_cache.  */
4736
4737 static rtx
4738 expand_builtin___clear_cache (tree exp ATTRIBUTE_UNUSED)
4739 {
4740 #ifndef HAVE_clear_cache
4741 #ifdef CLEAR_INSN_CACHE
4742   /* There is no "clear_cache" insn, and __clear_cache() in libgcc
4743      does something.  Just do the default expansion to a call to
4744      __clear_cache().  */
4745   return NULL_RTX;
4746 #else
4747   /* There is no "clear_cache" insn, and __clear_cache() in libgcc
4748      does nothing.  There is no need to call it.  Do nothing.  */
4749   return const0_rtx;
4750 #endif /* CLEAR_INSN_CACHE */
4751 #else
4752   /* We have a "clear_cache" insn, and it will handle everything.  */
4753   tree begin, end;
4754   rtx begin_rtx, end_rtx;
4755
4756   /* We must not expand to a library call.  If we did, any
4757      fallback library function in libgcc that might contain a call to
4758      __builtin___clear_cache() would recurse infinitely.  */
4759   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
4760     {
4761       error ("both arguments to %<__builtin___clear_cache%> must be pointers");
4762       return const0_rtx;
4763     }
4764
4765   if (HAVE_clear_cache)
4766     {
4767       struct expand_operand ops[2];
4768
4769       begin = CALL_EXPR_ARG (exp, 0);
4770       begin_rtx = expand_expr (begin, NULL_RTX, Pmode, EXPAND_NORMAL);
4771
4772       end = CALL_EXPR_ARG (exp, 1);
4773       end_rtx = expand_expr (end, NULL_RTX, Pmode, EXPAND_NORMAL);
4774
4775       create_address_operand (&ops[0], begin_rtx);
4776       create_address_operand (&ops[1], end_rtx);
4777       if (maybe_expand_insn (CODE_FOR_clear_cache, 2, ops))
4778         return const0_rtx;
4779     }
4780   return const0_rtx;
4781 #endif /* HAVE_clear_cache */
4782 }
4783
4784 /* Given a trampoline address, make sure it satisfies TRAMPOLINE_ALIGNMENT.  */
4785
4786 static rtx
4787 round_trampoline_addr (rtx tramp)
4788 {
4789   rtx temp, addend, mask;
4790
4791   /* If we don't need too much alignment, we'll have been guaranteed
4792      proper alignment by get_trampoline_type.  */
4793   if (TRAMPOLINE_ALIGNMENT <= STACK_BOUNDARY)
4794     return tramp;
4795
4796   /* Round address up to desired boundary.  */
4797   temp = gen_reg_rtx (Pmode);
4798   addend = GEN_INT (TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT - 1);
4799   mask = GEN_INT (-TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT);
4800
4801   temp  = expand_simple_binop (Pmode, PLUS, tramp, addend,
4802                                temp, 0, OPTAB_LIB_WIDEN);
4803   tramp = expand_simple_binop (Pmode, AND, temp, mask,
4804                                temp, 0, OPTAB_LIB_WIDEN);
4805
4806   return tramp;
4807 }
4808
4809 static rtx
4810 expand_builtin_init_trampoline (tree exp)
4811 {
4812   tree t_tramp, t_func, t_chain;
4813   rtx m_tramp, r_tramp, r_chain, tmp;
4814
4815   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE,
4816                          POINTER_TYPE, VOID_TYPE))
4817     return NULL_RTX;
4818
4819   t_tramp = CALL_EXPR_ARG (exp, 0);
4820   t_func = CALL_EXPR_ARG (exp, 1);
4821   t_chain = CALL_EXPR_ARG (exp, 2);
4822
4823   r_tramp = expand_normal (t_tramp);
4824   m_tramp = gen_rtx_MEM (BLKmode, r_tramp);
4825   MEM_NOTRAP_P (m_tramp) = 1;
4826
4827   /* The TRAMP argument should be the address of a field within the
4828      local function's FRAME decl.  Let's see if we can fill in the
4829      to fill in the MEM_ATTRs for this memory.  */
4830   if (TREE_CODE (t_tramp) == ADDR_EXPR)
4831     set_mem_attributes_minus_bitpos (m_tramp, TREE_OPERAND (t_tramp, 0),
4832                                      true, 0);
4833
4834   tmp = round_trampoline_addr (r_tramp);
4835   if (tmp != r_tramp)
4836     {
4837       m_tramp = change_address (m_tramp, BLKmode, tmp);
4838       set_mem_align (m_tramp, TRAMPOLINE_ALIGNMENT);
4839       set_mem_size (m_tramp, TRAMPOLINE_SIZE);
4840     }
4841
4842   /* The FUNC argument should be the address of the nested function.
4843      Extract the actual function decl to pass to the hook.  */
4844   gcc_assert (TREE_CODE (t_func) == ADDR_EXPR);
4845   t_func = TREE_OPERAND (t_func, 0);
4846   gcc_assert (TREE_CODE (t_func) == FUNCTION_DECL);
4847
4848   r_chain = expand_normal (t_chain);
4849
4850   /* Generate insns to initialize the trampoline.  */
4851   targetm.calls.trampoline_init (m_tramp, t_func, r_chain);
4852
4853   trampolines_created = 1;
4854
4855   warning_at (DECL_SOURCE_LOCATION (t_func), OPT_Wtrampolines,
4856               "trampoline generated for nested function %qD", t_func);
4857
4858   return const0_rtx;
4859 }
4860
4861 static rtx
4862 expand_builtin_adjust_trampoline (tree exp)
4863 {
4864   rtx tramp;
4865
4866   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
4867     return NULL_RTX;
4868
4869   tramp = expand_normal (CALL_EXPR_ARG (exp, 0));
4870   tramp = round_trampoline_addr (tramp);
4871   if (targetm.calls.trampoline_adjust_address)
4872     tramp = targetm.calls.trampoline_adjust_address (tramp);
4873
4874   return tramp;
4875 }
4876
4877 /* Expand the call EXP to the built-in signbit, signbitf or signbitl
4878    function.  The function first checks whether the back end provides
4879    an insn to implement signbit for the respective mode.  If not, it
4880    checks whether the floating point format of the value is such that
4881    the sign bit can be extracted.  If that is not the case, the
4882    function returns NULL_RTX to indicate that a normal call should be
4883    emitted rather than expanding the function in-line.  EXP is the
4884    expression that is a call to the builtin function; if convenient,
4885    the result should be placed in TARGET.  */
4886 static rtx
4887 expand_builtin_signbit (tree exp, rtx target)
4888 {
4889   const struct real_format *fmt;
4890   enum machine_mode fmode, imode, rmode;
4891   tree arg;
4892   int word, bitpos;
4893   enum insn_code icode;
4894   rtx temp;
4895   location_t loc = EXPR_LOCATION (exp);
4896
4897   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
4898     return NULL_RTX;
4899
4900   arg = CALL_EXPR_ARG (exp, 0);
4901   fmode = TYPE_MODE (TREE_TYPE (arg));
4902   rmode = TYPE_MODE (TREE_TYPE (exp));
4903   fmt = REAL_MODE_FORMAT (fmode);
4904
4905   arg = builtin_save_expr (arg);
4906
4907   /* Expand the argument yielding a RTX expression. */
4908   temp = expand_normal (arg);
4909
4910   /* Check if the back end provides an insn that handles signbit for the
4911      argument's mode. */
4912   icode = optab_handler (signbit_optab, fmode);
4913   if (icode != CODE_FOR_nothing)
4914     {
4915       rtx last = get_last_insn ();
4916       target = gen_reg_rtx (TYPE_MODE (TREE_TYPE (exp)));
4917       if (maybe_emit_unop_insn (icode, target, temp, UNKNOWN))
4918         return target;
4919       delete_insns_since (last);
4920     }
4921
4922   /* For floating point formats without a sign bit, implement signbit
4923      as "ARG < 0.0".  */
4924   bitpos = fmt->signbit_ro;
4925   if (bitpos < 0)
4926   {
4927     /* But we can't do this if the format supports signed zero.  */
4928     if (fmt->has_signed_zero && HONOR_SIGNED_ZEROS (fmode))
4929       return NULL_RTX;
4930
4931     arg = fold_build2_loc (loc, LT_EXPR, TREE_TYPE (exp), arg,
4932                        build_real (TREE_TYPE (arg), dconst0));
4933     return expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
4934   }
4935
4936   if (GET_MODE_SIZE (fmode) <= UNITS_PER_WORD)
4937     {
4938       imode = int_mode_for_mode (fmode);
4939       if (imode == BLKmode)
4940         return NULL_RTX;
4941       temp = gen_lowpart (imode, temp);
4942     }
4943   else
4944     {
4945       imode = word_mode;
4946       /* Handle targets with different FP word orders.  */
4947       if (FLOAT_WORDS_BIG_ENDIAN)
4948         word = (GET_MODE_BITSIZE (fmode) - bitpos) / BITS_PER_WORD;
4949       else
4950         word = bitpos / BITS_PER_WORD;
4951       temp = operand_subword_force (temp, word, fmode);
4952       bitpos = bitpos % BITS_PER_WORD;
4953     }
4954
4955   /* Force the intermediate word_mode (or narrower) result into a
4956      register.  This avoids attempting to create paradoxical SUBREGs
4957      of floating point modes below.  */
4958   temp = force_reg (imode, temp);
4959
4960   /* If the bitpos is within the "result mode" lowpart, the operation
4961      can be implement with a single bitwise AND.  Otherwise, we need
4962      a right shift and an AND.  */
4963
4964   if (bitpos < GET_MODE_BITSIZE (rmode))
4965     {
4966       double_int mask = double_int_setbit (double_int_zero, bitpos);
4967
4968       if (GET_MODE_SIZE (imode) > GET_MODE_SIZE (rmode))
4969         temp = gen_lowpart (rmode, temp);
4970       temp = expand_binop (rmode, and_optab, temp,
4971                            immed_double_int_const (mask, rmode),
4972                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
4973     }
4974   else
4975     {
4976       /* Perform a logical right shift to place the signbit in the least
4977          significant bit, then truncate the result to the desired mode
4978          and mask just this bit.  */
4979       temp = expand_shift (RSHIFT_EXPR, imode, temp, bitpos, NULL_RTX, 1);
4980       temp = gen_lowpart (rmode, temp);
4981       temp = expand_binop (rmode, and_optab, temp, const1_rtx,
4982                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
4983     }
4984
4985   return temp;
4986 }
4987
4988 /* Expand fork or exec calls.  TARGET is the desired target of the
4989    call.  EXP is the call. FN is the
4990    identificator of the actual function.  IGNORE is nonzero if the
4991    value is to be ignored.  */
4992
4993 static rtx
4994 expand_builtin_fork_or_exec (tree fn, tree exp, rtx target, int ignore)
4995 {
4996   tree id, decl;
4997   tree call;
4998
4999   /* If we are not profiling, just call the function.  */
5000   if (!profile_arc_flag)
5001     return NULL_RTX;
5002
5003   /* Otherwise call the wrapper.  This should be equivalent for the rest of
5004      compiler, so the code does not diverge, and the wrapper may run the
5005      code necessary for keeping the profiling sane.  */
5006
5007   switch (DECL_FUNCTION_CODE (fn))
5008     {
5009     case BUILT_IN_FORK:
5010       id = get_identifier ("__gcov_fork");
5011       break;
5012
5013     case BUILT_IN_EXECL:
5014       id = get_identifier ("__gcov_execl");
5015       break;
5016
5017     case BUILT_IN_EXECV:
5018       id = get_identifier ("__gcov_execv");
5019       break;
5020
5021     case BUILT_IN_EXECLP:
5022       id = get_identifier ("__gcov_execlp");
5023       break;
5024
5025     case BUILT_IN_EXECLE:
5026       id = get_identifier ("__gcov_execle");
5027       break;
5028
5029     case BUILT_IN_EXECVP:
5030       id = get_identifier ("__gcov_execvp");
5031       break;
5032
5033     case BUILT_IN_EXECVE:
5034       id = get_identifier ("__gcov_execve");
5035       break;
5036
5037     default:
5038       gcc_unreachable ();
5039     }
5040
5041   decl = build_decl (DECL_SOURCE_LOCATION (fn),
5042                      FUNCTION_DECL, id, TREE_TYPE (fn));
5043   DECL_EXTERNAL (decl) = 1;
5044   TREE_PUBLIC (decl) = 1;
5045   DECL_ARTIFICIAL (decl) = 1;
5046   TREE_NOTHROW (decl) = 1;
5047   DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
5048   DECL_VISIBILITY_SPECIFIED (decl) = 1;
5049   call = rewrite_call_expr (EXPR_LOCATION (exp), exp, 0, decl, 0);
5050   return expand_call (call, target, ignore);
5051  }
5052
5053
5054 \f
5055 /* Reconstitute a mode for a __sync intrinsic operation.  Since the type of
5056    the pointer in these functions is void*, the tree optimizers may remove
5057    casts.  The mode computed in expand_builtin isn't reliable either, due
5058    to __sync_bool_compare_and_swap.
5059
5060    FCODE_DIFF should be fcode - base, where base is the FOO_1 code for the
5061    group of builtins.  This gives us log2 of the mode size.  */
5062
5063 static inline enum machine_mode
5064 get_builtin_sync_mode (int fcode_diff)
5065 {
5066   /* The size is not negotiable, so ask not to get BLKmode in return
5067      if the target indicates that a smaller size would be better.  */
5068   return mode_for_size (BITS_PER_UNIT << fcode_diff, MODE_INT, 0);
5069 }
5070
5071 /* Expand the memory expression LOC and return the appropriate memory operand
5072    for the builtin_sync operations.  */
5073
5074 static rtx
5075 get_builtin_sync_mem (tree loc, enum machine_mode mode)
5076 {
5077   rtx addr, mem;
5078
5079   addr = expand_expr (loc, NULL_RTX, ptr_mode, EXPAND_SUM);
5080   addr = convert_memory_address (Pmode, addr);
5081
5082   /* Note that we explicitly do not want any alias information for this
5083      memory, so that we kill all other live memories.  Otherwise we don't
5084      satisfy the full barrier semantics of the intrinsic.  */
5085   mem = validize_mem (gen_rtx_MEM (mode, addr));
5086
5087   /* The alignment needs to be at least according to that of the mode.  */
5088   set_mem_align (mem, MAX (GET_MODE_ALIGNMENT (mode),
5089                            get_pointer_alignment (loc)));
5090   set_mem_alias_set (mem, ALIAS_SET_MEMORY_BARRIER);
5091   MEM_VOLATILE_P (mem) = 1;
5092
5093   return mem;
5094 }
5095
5096 /* Make sure an argument is in the right mode.
5097    EXP is the tree argument. 
5098    MODE is the mode it should be in.  */
5099
5100 static rtx
5101 expand_expr_force_mode (tree exp, enum machine_mode mode)
5102 {
5103   rtx val;
5104   enum machine_mode old_mode;
5105
5106   val = expand_expr (exp, NULL_RTX, mode, EXPAND_NORMAL);
5107   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5108      of CONST_INTs, where we know the old_mode only from the call argument.  */
5109
5110   old_mode = GET_MODE (val);
5111   if (old_mode == VOIDmode)
5112     old_mode = TYPE_MODE (TREE_TYPE (exp));
5113   val = convert_modes (mode, old_mode, val, 1);
5114   return val;
5115 }
5116
5117
5118 /* Expand the __sync_xxx_and_fetch and __sync_fetch_and_xxx intrinsics.
5119    EXP is the CALL_EXPR.  CODE is the rtx code
5120    that corresponds to the arithmetic or logical operation from the name;
5121    an exception here is that NOT actually means NAND.  TARGET is an optional
5122    place for us to store the results; AFTER is true if this is the
5123    fetch_and_xxx form.  */
5124
5125 static rtx
5126 expand_builtin_sync_operation (enum machine_mode mode, tree exp,
5127                                enum rtx_code code, bool after,
5128                                rtx target)
5129 {
5130   rtx val, mem;
5131   location_t loc = EXPR_LOCATION (exp);
5132
5133   if (code == NOT && warn_sync_nand)
5134     {
5135       tree fndecl = get_callee_fndecl (exp);
5136       enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5137
5138       static bool warned_f_a_n, warned_n_a_f;
5139
5140       switch (fcode)
5141         {
5142         case BUILT_IN_SYNC_FETCH_AND_NAND_1:
5143         case BUILT_IN_SYNC_FETCH_AND_NAND_2:
5144         case BUILT_IN_SYNC_FETCH_AND_NAND_4:
5145         case BUILT_IN_SYNC_FETCH_AND_NAND_8:
5146         case BUILT_IN_SYNC_FETCH_AND_NAND_16:
5147
5148           if (warned_f_a_n)
5149             break;
5150
5151           fndecl = builtin_decl_implicit (BUILT_IN_SYNC_FETCH_AND_NAND_N);
5152           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
5153           warned_f_a_n = true;
5154           break;
5155
5156         case BUILT_IN_SYNC_NAND_AND_FETCH_1:
5157         case BUILT_IN_SYNC_NAND_AND_FETCH_2:
5158         case BUILT_IN_SYNC_NAND_AND_FETCH_4:
5159         case BUILT_IN_SYNC_NAND_AND_FETCH_8:
5160         case BUILT_IN_SYNC_NAND_AND_FETCH_16:
5161
5162           if (warned_n_a_f)
5163             break;
5164
5165          fndecl = builtin_decl_implicit (BUILT_IN_SYNC_NAND_AND_FETCH_N);
5166           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
5167           warned_n_a_f = true;
5168           break;
5169
5170         default:
5171           gcc_unreachable ();
5172         }
5173     }
5174
5175   /* Expand the operands.  */
5176   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5177   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5178
5179   return expand_atomic_fetch_op (target, mem, val, code, MEMMODEL_SEQ_CST,
5180                                  after);
5181 }
5182
5183 /* Expand the __sync_val_compare_and_swap and __sync_bool_compare_and_swap
5184    intrinsics. EXP is the CALL_EXPR.  IS_BOOL is
5185    true if this is the boolean form.  TARGET is a place for us to store the
5186    results; this is NOT optional if IS_BOOL is true.  */
5187
5188 static rtx
5189 expand_builtin_compare_and_swap (enum machine_mode mode, tree exp,
5190                                  bool is_bool, rtx target)
5191 {
5192   rtx old_val, new_val, mem;
5193
5194   /* Expand the operands.  */
5195   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5196   old_val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5197   new_val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 2), mode);
5198
5199   if (!expand_atomic_compare_and_swap ((is_bool ? &target : NULL),
5200                                        (is_bool ? NULL : &target),
5201                                        mem, old_val, new_val, false,
5202                                        MEMMODEL_SEQ_CST, MEMMODEL_SEQ_CST))
5203     return NULL_RTX;
5204
5205   return target;
5206 }
5207
5208 /* Expand the __sync_lock_test_and_set intrinsic.  Note that the most
5209    general form is actually an atomic exchange, and some targets only
5210    support a reduced form with the second argument being a constant 1.
5211    EXP is the CALL_EXPR; TARGET is an optional place for us to store
5212    the results.  */
5213
5214 static rtx
5215 expand_builtin_sync_lock_test_and_set (enum machine_mode mode, tree exp,
5216                                        rtx target)
5217 {
5218   rtx val, mem;
5219
5220   /* Expand the operands.  */
5221   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5222   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5223
5224   return expand_atomic_exchange (target, mem, val, MEMMODEL_ACQUIRE, true);
5225 }
5226
5227 /* Expand the __sync_lock_release intrinsic.  EXP is the CALL_EXPR.  */
5228
5229 static void
5230 expand_builtin_sync_lock_release (enum machine_mode mode, tree exp)
5231 {
5232   rtx mem;
5233
5234   /* Expand the operands.  */
5235   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5236
5237   expand_atomic_store (mem, const0_rtx, MEMMODEL_RELEASE, true);
5238 }
5239
5240 /* Given an integer representing an ``enum memmodel'', verify its
5241    correctness and return the memory model enum.  */
5242
5243 static enum memmodel
5244 get_memmodel (tree exp)
5245 {
5246   rtx op;
5247
5248   /* If the parameter is not a constant, it's a run time value so we'll just
5249      convert it to MEMMODEL_SEQ_CST to avoid annoying runtime checking.  */
5250   if (TREE_CODE (exp) != INTEGER_CST)
5251     return MEMMODEL_SEQ_CST;
5252
5253   op = expand_normal (exp);
5254   if (INTVAL (op) < 0 || INTVAL (op) >= MEMMODEL_LAST)
5255     {
5256       warning (OPT_Winvalid_memory_model,
5257                "invalid memory model argument to builtin");
5258       return MEMMODEL_SEQ_CST;
5259     }
5260   return (enum memmodel) INTVAL (op);
5261 }
5262
5263 /* Expand the __atomic_exchange intrinsic:
5264         TYPE __atomic_exchange (TYPE *object, TYPE desired, enum memmodel)
5265    EXP is the CALL_EXPR.
5266    TARGET is an optional place for us to store the results.  */
5267
5268 static rtx
5269 expand_builtin_atomic_exchange (enum machine_mode mode, tree exp, rtx target)
5270 {
5271   rtx val, mem;
5272   enum memmodel model;
5273
5274   model = get_memmodel (CALL_EXPR_ARG (exp, 2));
5275   if (model == MEMMODEL_CONSUME)
5276     {
5277       error ("invalid memory model for %<__atomic_exchange%>");
5278       return NULL_RTX;
5279     }
5280
5281   if (!flag_inline_atomics)
5282     return NULL_RTX;
5283
5284   /* Expand the operands.  */
5285   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5286   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5287
5288   return expand_atomic_exchange (target, mem, val, model, false);
5289 }
5290
5291 /* Expand the __atomic_compare_exchange intrinsic:
5292         bool __atomic_compare_exchange (TYPE *object, TYPE *expect, 
5293                                         TYPE desired, BOOL weak, 
5294                                         enum memmodel success,
5295                                         enum memmodel failure)
5296    EXP is the CALL_EXPR.
5297    TARGET is an optional place for us to store the results.  */
5298
5299 static rtx
5300 expand_builtin_atomic_compare_exchange (enum machine_mode mode, tree exp, 
5301                                         rtx target)
5302 {
5303   rtx expect, desired, mem, oldval;
5304   enum memmodel success, failure;
5305   tree weak;
5306   bool is_weak;
5307
5308   success = get_memmodel (CALL_EXPR_ARG (exp, 4));
5309   failure = get_memmodel (CALL_EXPR_ARG (exp, 5));
5310
5311   if (failure == MEMMODEL_RELEASE || failure == MEMMODEL_ACQ_REL)
5312     {
5313       error ("invalid failure memory model for %<__atomic_compare_exchange%>");
5314       return NULL_RTX;
5315     }
5316
5317   if (failure > success)
5318     {
5319       error ("failure memory model cannot be stronger than success "
5320              "memory model for %<__atomic_compare_exchange%>");
5321       return NULL_RTX;
5322     }
5323   
5324   if (!flag_inline_atomics)
5325     return NULL_RTX;
5326
5327   /* Expand the operands.  */
5328   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5329
5330   expect = expand_normal (CALL_EXPR_ARG (exp, 1));
5331   expect = convert_memory_address (Pmode, expect);
5332   desired = expand_expr_force_mode (CALL_EXPR_ARG (exp, 2), mode);
5333
5334   weak = CALL_EXPR_ARG (exp, 3);
5335   is_weak = false;
5336   if (host_integerp (weak, 0) && tree_low_cst (weak, 0) != 0)
5337     is_weak = true;
5338
5339   oldval = copy_to_reg (gen_rtx_MEM (mode, expect));
5340
5341   if (!expand_atomic_compare_and_swap (&target, &oldval, mem, oldval,
5342                                        desired, is_weak, success, failure))
5343     return NULL_RTX;
5344
5345   emit_move_insn (gen_rtx_MEM (mode, expect), oldval);
5346   return target;
5347 }
5348
5349 /* Expand the __atomic_load intrinsic:
5350         TYPE __atomic_load (TYPE *object, enum memmodel)
5351    EXP is the CALL_EXPR.
5352    TARGET is an optional place for us to store the results.  */
5353
5354 static rtx
5355 expand_builtin_atomic_load (enum machine_mode mode, tree exp, rtx target)
5356 {
5357   rtx mem;
5358   enum memmodel model;
5359
5360   model = get_memmodel (CALL_EXPR_ARG (exp, 1));
5361   if (model == MEMMODEL_RELEASE
5362       || model == MEMMODEL_ACQ_REL)
5363     {
5364       error ("invalid memory model for %<__atomic_load%>");
5365       return NULL_RTX;
5366     }
5367
5368   if (!flag_inline_atomics)
5369     return NULL_RTX;
5370
5371   /* Expand the operand.  */
5372   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5373
5374   return expand_atomic_load (target, mem, model);
5375 }
5376
5377
5378 /* Expand the __atomic_store intrinsic:
5379         void __atomic_store (TYPE *object, TYPE desired, enum memmodel)
5380    EXP is the CALL_EXPR.
5381    TARGET is an optional place for us to store the results.  */
5382
5383 static rtx
5384 expand_builtin_atomic_store (enum machine_mode mode, tree exp)
5385 {
5386   rtx mem, val;
5387   enum memmodel model;
5388
5389   model = get_memmodel (CALL_EXPR_ARG (exp, 2));
5390   if (model != MEMMODEL_RELAXED
5391       && model != MEMMODEL_SEQ_CST
5392       && model != MEMMODEL_RELEASE)
5393     {
5394       error ("invalid memory model for %<__atomic_store%>");
5395       return NULL_RTX;
5396     }
5397
5398   if (!flag_inline_atomics)
5399     return NULL_RTX;
5400
5401   /* Expand the operands.  */
5402   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5403   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5404
5405   return expand_atomic_store (mem, val, model, false);
5406 }
5407
5408 /* Expand the __atomic_fetch_XXX intrinsic:
5409         TYPE __atomic_fetch_XXX (TYPE *object, TYPE val, enum memmodel)
5410    EXP is the CALL_EXPR.
5411    TARGET is an optional place for us to store the results.
5412    CODE is the operation, PLUS, MINUS, ADD, XOR, or IOR.
5413    FETCH_AFTER is true if returning the result of the operation.
5414    FETCH_AFTER is false if returning the value before the operation.
5415    IGNORE is true if the result is not used.
5416    EXT_CALL is the correct builtin for an external call if this cannot be
5417    resolved to an instruction sequence.  */
5418
5419 static rtx
5420 expand_builtin_atomic_fetch_op (enum machine_mode mode, tree exp, rtx target,
5421                                 enum rtx_code code, bool fetch_after,
5422                                 bool ignore, enum built_in_function ext_call)
5423 {
5424   rtx val, mem, ret;
5425   enum memmodel model;
5426   tree fndecl;
5427   tree addr;
5428
5429   model = get_memmodel (CALL_EXPR_ARG (exp, 2));
5430
5431   /* Expand the operands.  */
5432   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5433   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5434
5435   /* Only try generating instructions if inlining is turned on.  */
5436   if (flag_inline_atomics)
5437     {
5438       ret = expand_atomic_fetch_op (target, mem, val, code, model, fetch_after);
5439       if (ret)
5440         return ret;
5441     }
5442
5443   /* Return if a different routine isn't needed for the library call.  */
5444   if (ext_call == BUILT_IN_NONE)
5445     return NULL_RTX;
5446
5447   /* Change the call to the specified function.  */
5448   fndecl = get_callee_fndecl (exp);
5449   addr = CALL_EXPR_FN (exp);
5450   STRIP_NOPS (addr);
5451
5452   gcc_assert (TREE_OPERAND (addr, 0) == fndecl);
5453   TREE_OPERAND (addr, 0) = builtin_decl_explicit(ext_call);
5454
5455   /* Expand the call here so we can emit trailing code.  */
5456   ret = expand_call (exp, target, ignore);
5457
5458   /* Replace the original function just in case it matters.  */
5459   TREE_OPERAND (addr, 0) = fndecl;
5460
5461   /* Then issue the arithmetic correction to return the right result.  */
5462   if (!ignore)
5463     ret = expand_simple_binop (mode, code, ret, val, NULL_RTX, true,
5464                                OPTAB_LIB_WIDEN);
5465   return ret;
5466 }
5467
5468 /* Return true if (optional) argument ARG1 of size ARG0 is always lock free on
5469    this architecture.  If ARG1 is NULL, use typical alignment for size ARG0.  */
5470
5471 static tree
5472 fold_builtin_atomic_always_lock_free (tree arg0, tree arg1)
5473 {
5474   int size;
5475   enum machine_mode mode;
5476   unsigned int mode_align, type_align;
5477
5478   if (TREE_CODE (arg0) != INTEGER_CST)
5479     return NULL_TREE;
5480
5481   size = INTVAL (expand_normal (arg0)) * BITS_PER_UNIT;
5482   mode = mode_for_size (size, MODE_INT, 0);
5483   mode_align = GET_MODE_ALIGNMENT (mode);
5484
5485   if (TREE_CODE (arg1) == INTEGER_CST && INTVAL (expand_normal (arg1)) == 0)
5486     type_align = mode_align;
5487   else
5488     {
5489       tree ttype = TREE_TYPE (arg1);
5490
5491       /* This function is usually invoked and folded immediately by the front
5492          end before anything else has a chance to look at it.  The pointer
5493          parameter at this point is usually cast to a void *, so check for that
5494          and look past the cast.  */
5495       if (TREE_CODE (arg1) == NOP_EXPR && POINTER_TYPE_P (ttype)
5496           && VOID_TYPE_P (TREE_TYPE (ttype)))
5497         arg1 = TREE_OPERAND (arg1, 0);
5498
5499       ttype = TREE_TYPE (arg1);
5500       gcc_assert (POINTER_TYPE_P (ttype));
5501
5502       /* Get the underlying type of the object.  */
5503       ttype = TREE_TYPE (ttype);
5504       type_align = TYPE_ALIGN (ttype);
5505     }
5506
5507   /* If the object has smaller alignment, the the lock free routines cannot
5508      be used.  */
5509   if (type_align < mode_align)
5510     return integer_zero_node;
5511
5512   /* Check if a compare_and_swap pattern exists for the mode which represents
5513      the required size.  The pattern is not allowed to fail, so the existence
5514      of the pattern indicates support is present.  */
5515   if (can_compare_and_swap_p (mode))
5516     return integer_one_node;
5517   else
5518     return integer_zero_node;
5519 }
5520
5521 /* Return true if the parameters to call EXP represent an object which will
5522    always generate lock free instructions.  The first argument represents the
5523    size of the object, and the second parameter is a pointer to the object 
5524    itself.  If NULL is passed for the object, then the result is based on 
5525    typical alignment for an object of the specified size.  Otherwise return 
5526    false.  */
5527
5528 static rtx
5529 expand_builtin_atomic_always_lock_free (tree exp)
5530 {
5531   tree size;
5532   tree arg0 = CALL_EXPR_ARG (exp, 0);
5533   tree arg1 = CALL_EXPR_ARG (exp, 1);
5534
5535   if (TREE_CODE (arg0) != INTEGER_CST)
5536     {
5537       error ("non-constant argument 1 to __atomic_always_lock_free");
5538       return const0_rtx;
5539     }
5540
5541   size = fold_builtin_atomic_always_lock_free (arg0, arg1);
5542   if (size == integer_one_node)
5543     return const1_rtx;
5544   return const0_rtx;
5545 }
5546
5547 /* Return a one or zero if it can be determined that object ARG1 of size ARG 
5548    is lock free on this architecture.  */
5549
5550 static tree
5551 fold_builtin_atomic_is_lock_free (tree arg0, tree arg1)
5552 {
5553   if (!flag_inline_atomics)
5554     return NULL_TREE;
5555   
5556   /* If it isn't always lock free, don't generate a result.  */
5557   if (fold_builtin_atomic_always_lock_free (arg0, arg1) == integer_one_node)
5558     return integer_one_node;
5559
5560   return NULL_TREE;
5561 }
5562
5563 /* Return true if the parameters to call EXP represent an object which will
5564    always generate lock free instructions.  The first argument represents the
5565    size of the object, and the second parameter is a pointer to the object 
5566    itself.  If NULL is passed for the object, then the result is based on 
5567    typical alignment for an object of the specified size.  Otherwise return 
5568    NULL*/
5569
5570 static rtx
5571 expand_builtin_atomic_is_lock_free (tree exp)
5572 {
5573   tree size;
5574   tree arg0 = CALL_EXPR_ARG (exp, 0);
5575   tree arg1 = CALL_EXPR_ARG (exp, 1);
5576
5577   if (!INTEGRAL_TYPE_P (TREE_TYPE (arg0)))
5578     {
5579       error ("non-integer argument 1 to __atomic_is_lock_free");
5580       return NULL_RTX;
5581     }
5582
5583   if (!flag_inline_atomics)
5584     return NULL_RTX; 
5585
5586   /* If the value is known at compile time, return the RTX for it.  */
5587   size = fold_builtin_atomic_is_lock_free (arg0, arg1);
5588   if (size == integer_one_node)
5589     return const1_rtx;
5590
5591   return NULL_RTX;
5592 }
5593
5594 /* This routine will either emit the mem_thread_fence pattern or issue a 
5595    sync_synchronize to generate a fence for memory model MEMMODEL.  */
5596
5597 #ifndef HAVE_mem_thread_fence
5598 # define HAVE_mem_thread_fence 0
5599 # define gen_mem_thread_fence(x) (gcc_unreachable (), NULL_RTX)
5600 #endif
5601
5602 void
5603 expand_builtin_mem_thread_fence (enum memmodel model)
5604 {
5605   if (HAVE_mem_thread_fence)
5606     emit_insn (gen_mem_thread_fence (GEN_INT (model)));
5607   else if (model != MEMMODEL_RELAXED)
5608     expand_builtin_sync_synchronize ();
5609 }
5610
5611 /* Expand the __atomic_thread_fence intrinsic:
5612         void __atomic_thread_fence (enum memmodel)
5613    EXP is the CALL_EXPR.  */
5614
5615 static void
5616 expand_builtin_atomic_thread_fence (tree exp)
5617 {
5618   enum memmodel model;
5619   
5620   model = get_memmodel (CALL_EXPR_ARG (exp, 0));
5621   expand_builtin_mem_thread_fence (model);
5622 }
5623
5624 /* This routine will either emit the mem_signal_fence pattern or issue a 
5625    sync_synchronize to generate a fence for memory model MEMMODEL.  */
5626
5627 #ifndef HAVE_mem_signal_fence
5628 # define HAVE_mem_signal_fence 0
5629 # define gen_mem_signal_fence(x) (gcc_unreachable (), NULL_RTX)
5630 #endif
5631
5632 static void
5633 expand_builtin_mem_signal_fence (enum memmodel model)
5634 {
5635   if (HAVE_mem_signal_fence)
5636     emit_insn (gen_mem_signal_fence (GEN_INT (model)));
5637   else if (model != MEMMODEL_RELAXED)
5638     {
5639       rtx asm_op, clob;
5640
5641       /* By default targets are coherent between a thread and the signal
5642          handler running on the same thread.  Thus this really becomes a
5643          compiler barrier, in that stores must not be sunk past
5644          (or raised above) a given point.  */
5645
5646       /* Generate asm volatile("" : : : "memory") as the memory barrier.  */
5647       asm_op = gen_rtx_ASM_OPERANDS (VOIDmode, empty_string, empty_string, 0,
5648                                      rtvec_alloc (0), rtvec_alloc (0),
5649                                      rtvec_alloc (0), UNKNOWN_LOCATION);
5650       MEM_VOLATILE_P (asm_op) = 1;
5651
5652       clob = gen_rtx_SCRATCH (VOIDmode);
5653       clob = gen_rtx_MEM (BLKmode, clob);
5654       clob = gen_rtx_CLOBBER (VOIDmode, clob);
5655
5656       emit_insn (gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, asm_op, clob)));
5657     }
5658 }
5659
5660 /* Expand the __atomic_signal_fence intrinsic:
5661         void __atomic_signal_fence (enum memmodel)
5662    EXP is the CALL_EXPR.  */
5663
5664 static void
5665 expand_builtin_atomic_signal_fence (tree exp)
5666 {
5667   enum memmodel model;
5668
5669   model = get_memmodel (CALL_EXPR_ARG (exp, 0));
5670   expand_builtin_mem_signal_fence (model);
5671 }
5672
5673 /* Expand the __sync_synchronize intrinsic.  */
5674
5675 static void
5676 expand_builtin_sync_synchronize (void)
5677 {
5678   gimple x;
5679   VEC (tree, gc) *v_clobbers;
5680
5681 #ifdef HAVE_memory_barrier
5682   if (HAVE_memory_barrier)
5683     {
5684       emit_insn (gen_memory_barrier ());
5685       return;
5686     }
5687 #endif
5688
5689   if (synchronize_libfunc != NULL_RTX)
5690     {
5691       emit_library_call (synchronize_libfunc, LCT_NORMAL, VOIDmode, 0);
5692       return;
5693     }
5694
5695   /* If no explicit memory barrier instruction is available, create an
5696      empty asm stmt with a memory clobber.  */
5697   v_clobbers = VEC_alloc (tree, gc, 1);
5698   VEC_quick_push (tree, v_clobbers,
5699                   tree_cons (NULL, build_string (6, "memory"), NULL));
5700   x = gimple_build_asm_vec ("", NULL, NULL, v_clobbers, NULL);
5701   gimple_asm_set_volatile (x, true);
5702   expand_asm_stmt (x);
5703 }
5704
5705 \f
5706 /* Expand an expression EXP that calls a built-in function,
5707    with result going to TARGET if that's convenient
5708    (and in mode MODE if that's convenient).
5709    SUBTARGET may be used as the target for computing one of EXP's operands.
5710    IGNORE is nonzero if the value is to be ignored.  */
5711
5712 rtx
5713 expand_builtin (tree exp, rtx target, rtx subtarget, enum machine_mode mode,
5714                 int ignore)
5715 {
5716   tree fndecl = get_callee_fndecl (exp);
5717   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5718   enum machine_mode target_mode = TYPE_MODE (TREE_TYPE (exp));
5719   int flags;
5720
5721   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
5722     return targetm.expand_builtin (exp, target, subtarget, mode, ignore);
5723
5724   /* When not optimizing, generate calls to library functions for a certain
5725      set of builtins.  */
5726   if (!optimize
5727       && !called_as_built_in (fndecl)
5728       && DECL_ASSEMBLER_NAME_SET_P (fndecl)
5729       && fcode != BUILT_IN_ALLOCA
5730       && fcode != BUILT_IN_ALLOCA_WITH_ALIGN
5731       && fcode != BUILT_IN_FREE)
5732     return expand_call (exp, target, ignore);
5733
5734   /* The built-in function expanders test for target == const0_rtx
5735      to determine whether the function's result will be ignored.  */
5736   if (ignore)
5737     target = const0_rtx;
5738
5739   /* If the result of a pure or const built-in function is ignored, and
5740      none of its arguments are volatile, we can avoid expanding the
5741      built-in call and just evaluate the arguments for side-effects.  */
5742   if (target == const0_rtx
5743       && ((flags = flags_from_decl_or_type (fndecl)) & (ECF_CONST | ECF_PURE))
5744       && !(flags & ECF_LOOPING_CONST_OR_PURE))
5745     {
5746       bool volatilep = false;
5747       tree arg;
5748       call_expr_arg_iterator iter;
5749
5750       FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5751         if (TREE_THIS_VOLATILE (arg))
5752           {
5753             volatilep = true;
5754             break;
5755           }
5756
5757       if (! volatilep)
5758         {
5759           FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5760             expand_expr (arg, const0_rtx, VOIDmode, EXPAND_NORMAL);
5761           return const0_rtx;
5762         }
5763     }
5764
5765   switch (fcode)
5766     {
5767     CASE_FLT_FN (BUILT_IN_FABS):
5768       target = expand_builtin_fabs (exp, target, subtarget);
5769       if (target)
5770         return target;
5771       break;
5772
5773     CASE_FLT_FN (BUILT_IN_COPYSIGN):
5774       target = expand_builtin_copysign (exp, target, subtarget);
5775       if (target)
5776         return target;
5777       break;
5778
5779       /* Just do a normal library call if we were unable to fold
5780          the values.  */
5781     CASE_FLT_FN (BUILT_IN_CABS):
5782       break;
5783
5784     CASE_FLT_FN (BUILT_IN_EXP):
5785     CASE_FLT_FN (BUILT_IN_EXP10):
5786     CASE_FLT_FN (BUILT_IN_POW10):
5787     CASE_FLT_FN (BUILT_IN_EXP2):
5788     CASE_FLT_FN (BUILT_IN_EXPM1):
5789     CASE_FLT_FN (BUILT_IN_LOGB):
5790     CASE_FLT_FN (BUILT_IN_LOG):
5791     CASE_FLT_FN (BUILT_IN_LOG10):
5792     CASE_FLT_FN (BUILT_IN_LOG2):
5793     CASE_FLT_FN (BUILT_IN_LOG1P):
5794     CASE_FLT_FN (BUILT_IN_TAN):
5795     CASE_FLT_FN (BUILT_IN_ASIN):
5796     CASE_FLT_FN (BUILT_IN_ACOS):
5797     CASE_FLT_FN (BUILT_IN_ATAN):
5798     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
5799       /* Treat these like sqrt only if unsafe math optimizations are allowed,
5800          because of possible accuracy problems.  */
5801       if (! flag_unsafe_math_optimizations)
5802         break;
5803     CASE_FLT_FN (BUILT_IN_SQRT):
5804     CASE_FLT_FN (BUILT_IN_FLOOR):
5805     CASE_FLT_FN (BUILT_IN_CEIL):
5806     CASE_FLT_FN (BUILT_IN_TRUNC):
5807     CASE_FLT_FN (BUILT_IN_ROUND):
5808     CASE_FLT_FN (BUILT_IN_NEARBYINT):
5809     CASE_FLT_FN (BUILT_IN_RINT):
5810       target = expand_builtin_mathfn (exp, target, subtarget);
5811       if (target)
5812         return target;
5813       break;
5814
5815     CASE_FLT_FN (BUILT_IN_FMA):
5816       target = expand_builtin_mathfn_ternary (exp, target, subtarget);
5817       if (target)
5818         return target;
5819       break;
5820
5821     CASE_FLT_FN (BUILT_IN_ILOGB):
5822       if (! flag_unsafe_math_optimizations)
5823         break;
5824     CASE_FLT_FN (BUILT_IN_ISINF):
5825     CASE_FLT_FN (BUILT_IN_FINITE):
5826     case BUILT_IN_ISFINITE:
5827     case BUILT_IN_ISNORMAL:
5828       target = expand_builtin_interclass_mathfn (exp, target);
5829       if (target)
5830         return target;
5831       break;
5832
5833     CASE_FLT_FN (BUILT_IN_ICEIL):
5834     CASE_FLT_FN (BUILT_IN_LCEIL):
5835     CASE_FLT_FN (BUILT_IN_LLCEIL):
5836     CASE_FLT_FN (BUILT_IN_LFLOOR):
5837     CASE_FLT_FN (BUILT_IN_IFLOOR):
5838     CASE_FLT_FN (BUILT_IN_LLFLOOR):
5839       target = expand_builtin_int_roundingfn (exp, target);
5840       if (target)
5841         return target;
5842       break;
5843
5844     CASE_FLT_FN (BUILT_IN_IRINT):
5845     CASE_FLT_FN (BUILT_IN_LRINT):
5846     CASE_FLT_FN (BUILT_IN_LLRINT):
5847     CASE_FLT_FN (BUILT_IN_IROUND):
5848     CASE_FLT_FN (BUILT_IN_LROUND):
5849     CASE_FLT_FN (BUILT_IN_LLROUND):
5850       target = expand_builtin_int_roundingfn_2 (exp, target);
5851       if (target)
5852         return target;
5853       break;
5854
5855     CASE_FLT_FN (BUILT_IN_POWI):
5856       target = expand_builtin_powi (exp, target);
5857       if (target)
5858         return target;
5859       break;
5860
5861     CASE_FLT_FN (BUILT_IN_ATAN2):
5862     CASE_FLT_FN (BUILT_IN_LDEXP):
5863     CASE_FLT_FN (BUILT_IN_SCALB):
5864     CASE_FLT_FN (BUILT_IN_SCALBN):
5865     CASE_FLT_FN (BUILT_IN_SCALBLN):
5866       if (! flag_unsafe_math_optimizations)
5867         break;
5868
5869     CASE_FLT_FN (BUILT_IN_FMOD):
5870     CASE_FLT_FN (BUILT_IN_REMAINDER):
5871     CASE_FLT_FN (BUILT_IN_DREM):
5872     CASE_FLT_FN (BUILT_IN_POW):
5873       target = expand_builtin_mathfn_2 (exp, target, subtarget);
5874       if (target)
5875         return target;
5876       break;
5877
5878     CASE_FLT_FN (BUILT_IN_CEXPI):
5879       target = expand_builtin_cexpi (exp, target);
5880       gcc_assert (target);
5881       return target;
5882
5883     CASE_FLT_FN (BUILT_IN_SIN):
5884     CASE_FLT_FN (BUILT_IN_COS):
5885       if (! flag_unsafe_math_optimizations)
5886         break;
5887       target = expand_builtin_mathfn_3 (exp, target, subtarget);
5888       if (target)
5889         return target;
5890       break;
5891
5892     CASE_FLT_FN (BUILT_IN_SINCOS):
5893       if (! flag_unsafe_math_optimizations)
5894         break;
5895       target = expand_builtin_sincos (exp);
5896       if (target)
5897         return target;
5898       break;
5899
5900     case BUILT_IN_APPLY_ARGS:
5901       return expand_builtin_apply_args ();
5902
5903       /* __builtin_apply (FUNCTION, ARGUMENTS, ARGSIZE) invokes
5904          FUNCTION with a copy of the parameters described by
5905          ARGUMENTS, and ARGSIZE.  It returns a block of memory
5906          allocated on the stack into which is stored all the registers
5907          that might possibly be used for returning the result of a
5908          function.  ARGUMENTS is the value returned by
5909          __builtin_apply_args.  ARGSIZE is the number of bytes of
5910          arguments that must be copied.  ??? How should this value be
5911          computed?  We'll also need a safe worst case value for varargs
5912          functions.  */
5913     case BUILT_IN_APPLY:
5914       if (!validate_arglist (exp, POINTER_TYPE,
5915                              POINTER_TYPE, INTEGER_TYPE, VOID_TYPE)
5916           && !validate_arglist (exp, REFERENCE_TYPE,
5917                                 POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
5918         return const0_rtx;
5919       else
5920         {
5921           rtx ops[3];
5922
5923           ops[0] = expand_normal (CALL_EXPR_ARG (exp, 0));
5924           ops[1] = expand_normal (CALL_EXPR_ARG (exp, 1));
5925           ops[2] = expand_normal (CALL_EXPR_ARG (exp, 2));
5926
5927           return expand_builtin_apply (ops[0], ops[1], ops[2]);
5928         }
5929
5930       /* __builtin_return (RESULT) causes the function to return the
5931          value described by RESULT.  RESULT is address of the block of
5932          memory returned by __builtin_apply.  */
5933     case BUILT_IN_RETURN:
5934       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
5935         expand_builtin_return (expand_normal (CALL_EXPR_ARG (exp, 0)));
5936       return const0_rtx;
5937
5938     case BUILT_IN_SAVEREGS:
5939       return expand_builtin_saveregs ();
5940
5941     case BUILT_IN_VA_ARG_PACK:
5942       /* All valid uses of __builtin_va_arg_pack () are removed during
5943          inlining.  */
5944       error ("%Kinvalid use of %<__builtin_va_arg_pack ()%>", exp);
5945       return const0_rtx;
5946
5947     case BUILT_IN_VA_ARG_PACK_LEN:
5948       /* All valid uses of __builtin_va_arg_pack_len () are removed during
5949          inlining.  */
5950       error ("%Kinvalid use of %<__builtin_va_arg_pack_len ()%>", exp);
5951       return const0_rtx;
5952
5953       /* Return the address of the first anonymous stack arg.  */
5954     case BUILT_IN_NEXT_ARG:
5955       if (fold_builtin_next_arg (exp, false))
5956         return const0_rtx;
5957       return expand_builtin_next_arg ();
5958
5959     case BUILT_IN_CLEAR_CACHE:
5960       target = expand_builtin___clear_cache (exp);
5961       if (target)
5962         return target;
5963       break;
5964
5965     case BUILT_IN_CLASSIFY_TYPE:
5966       return expand_builtin_classify_type (exp);
5967
5968     case BUILT_IN_CONSTANT_P:
5969       return const0_rtx;
5970
5971     case BUILT_IN_FRAME_ADDRESS:
5972     case BUILT_IN_RETURN_ADDRESS:
5973       return expand_builtin_frame_address (fndecl, exp);
5974
5975     /* Returns the address of the area where the structure is returned.
5976        0 otherwise.  */
5977     case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
5978       if (call_expr_nargs (exp) != 0
5979           || ! AGGREGATE_TYPE_P (TREE_TYPE (TREE_TYPE (current_function_decl)))
5980           || !MEM_P (DECL_RTL (DECL_RESULT (current_function_decl))))
5981         return const0_rtx;
5982       else
5983         return XEXP (DECL_RTL (DECL_RESULT (current_function_decl)), 0);
5984
5985     case BUILT_IN_ALLOCA:
5986     case BUILT_IN_ALLOCA_WITH_ALIGN:
5987       /* If the allocation stems from the declaration of a variable-sized
5988          object, it cannot accumulate.  */
5989       target = expand_builtin_alloca (exp, CALL_ALLOCA_FOR_VAR_P (exp));
5990       if (target)
5991         return target;
5992       break;
5993
5994     case BUILT_IN_STACK_SAVE:
5995       return expand_stack_save ();
5996
5997     case BUILT_IN_STACK_RESTORE:
5998       expand_stack_restore (CALL_EXPR_ARG (exp, 0));
5999       return const0_rtx;
6000
6001     case BUILT_IN_BSWAP32:
6002     case BUILT_IN_BSWAP64:
6003       target = expand_builtin_bswap (exp, target, subtarget);
6004
6005       if (target)
6006         return target;
6007       break;
6008
6009     CASE_INT_FN (BUILT_IN_FFS):
6010     case BUILT_IN_FFSIMAX:
6011       target = expand_builtin_unop (target_mode, exp, target,
6012                                     subtarget, ffs_optab);
6013       if (target)
6014         return target;
6015       break;
6016
6017     CASE_INT_FN (BUILT_IN_CLZ):
6018     case BUILT_IN_CLZIMAX:
6019       target = expand_builtin_unop (target_mode, exp, target,
6020                                     subtarget, clz_optab);
6021       if (target)
6022         return target;
6023       break;
6024
6025     CASE_INT_FN (BUILT_IN_CTZ):
6026     case BUILT_IN_CTZIMAX:
6027       target = expand_builtin_unop (target_mode, exp, target,
6028                                     subtarget, ctz_optab);
6029       if (target)
6030         return target;
6031       break;
6032
6033     CASE_INT_FN (BUILT_IN_CLRSB):
6034     case BUILT_IN_CLRSBIMAX:
6035       target = expand_builtin_unop (target_mode, exp, target,
6036                                     subtarget, clrsb_optab);
6037       if (target)
6038         return target;
6039       break;
6040
6041     CASE_INT_FN (BUILT_IN_POPCOUNT):
6042     case BUILT_IN_POPCOUNTIMAX:
6043       target = expand_builtin_unop (target_mode, exp, target,
6044                                     subtarget, popcount_optab);
6045       if (target)
6046         return target;
6047       break;
6048
6049     CASE_INT_FN (BUILT_IN_PARITY):
6050     case BUILT_IN_PARITYIMAX:
6051       target = expand_builtin_unop (target_mode, exp, target,
6052                                     subtarget, parity_optab);
6053       if (target)
6054         return target;
6055       break;
6056
6057     case BUILT_IN_STRLEN:
6058       target = expand_builtin_strlen (exp, target, target_mode);
6059       if (target)
6060         return target;
6061       break;
6062
6063     case BUILT_IN_STRCPY:
6064       target = expand_builtin_strcpy (exp, target);
6065       if (target)
6066         return target;
6067       break;
6068
6069     case BUILT_IN_STRNCPY:
6070       target = expand_builtin_strncpy (exp, target);
6071       if (target)
6072         return target;
6073       break;
6074
6075     case BUILT_IN_STPCPY:
6076       target = expand_builtin_stpcpy (exp, target, mode);
6077       if (target)
6078         return target;
6079       break;
6080
6081     case BUILT_IN_MEMCPY:
6082       target = expand_builtin_memcpy (exp, target);
6083       if (target)
6084         return target;
6085       break;
6086
6087     case BUILT_IN_MEMPCPY:
6088       target = expand_builtin_mempcpy (exp, target, mode);
6089       if (target)
6090         return target;
6091       break;
6092
6093     case BUILT_IN_MEMSET:
6094       target = expand_builtin_memset (exp, target, mode);
6095       if (target)
6096         return target;
6097       break;
6098
6099     case BUILT_IN_BZERO:
6100       target = expand_builtin_bzero (exp);
6101       if (target)
6102         return target;
6103       break;
6104
6105     case BUILT_IN_STRCMP:
6106       target = expand_builtin_strcmp (exp, target);
6107       if (target)
6108         return target;
6109       break;
6110
6111     case BUILT_IN_STRNCMP:
6112       target = expand_builtin_strncmp (exp, target, mode);
6113       if (target)
6114         return target;
6115       break;
6116
6117     case BUILT_IN_BCMP:
6118     case BUILT_IN_MEMCMP:
6119       target = expand_builtin_memcmp (exp, target, mode);
6120       if (target)
6121         return target;
6122       break;
6123
6124     case BUILT_IN_SETJMP:
6125       /* This should have been lowered to the builtins below.  */
6126       gcc_unreachable ();
6127
6128     case BUILT_IN_SETJMP_SETUP:
6129       /* __builtin_setjmp_setup is passed a pointer to an array of five words
6130           and the receiver label.  */
6131       if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
6132         {
6133           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
6134                                       VOIDmode, EXPAND_NORMAL);
6135           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 1), 0);
6136           rtx label_r = label_rtx (label);
6137
6138           /* This is copied from the handling of non-local gotos.  */
6139           expand_builtin_setjmp_setup (buf_addr, label_r);
6140           nonlocal_goto_handler_labels
6141             = gen_rtx_EXPR_LIST (VOIDmode, label_r,
6142                                  nonlocal_goto_handler_labels);
6143           /* ??? Do not let expand_label treat us as such since we would
6144              not want to be both on the list of non-local labels and on
6145              the list of forced labels.  */
6146           FORCED_LABEL (label) = 0;
6147           return const0_rtx;
6148         }
6149       break;
6150
6151     case BUILT_IN_SETJMP_DISPATCHER:
6152        /* __builtin_setjmp_dispatcher is passed the dispatcher label.  */
6153       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6154         {
6155           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
6156           rtx label_r = label_rtx (label);
6157
6158           /* Remove the dispatcher label from the list of non-local labels
6159              since the receiver labels have been added to it above.  */
6160           remove_node_from_expr_list (label_r, &nonlocal_goto_handler_labels);
6161           return const0_rtx;
6162         }
6163       break;
6164
6165     case BUILT_IN_SETJMP_RECEIVER:
6166        /* __builtin_setjmp_receiver is passed the receiver label.  */
6167       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6168         {
6169           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
6170           rtx label_r = label_rtx (label);
6171
6172           expand_builtin_setjmp_receiver (label_r);
6173           return const0_rtx;
6174         }
6175       break;
6176
6177       /* __builtin_longjmp is passed a pointer to an array of five words.
6178          It's similar to the C library longjmp function but works with
6179          __builtin_setjmp above.  */
6180     case BUILT_IN_LONGJMP:
6181       if (validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
6182         {
6183           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
6184                                       VOIDmode, EXPAND_NORMAL);
6185           rtx value = expand_normal (CALL_EXPR_ARG (exp, 1));
6186
6187           if (value != const1_rtx)
6188             {
6189               error ("%<__builtin_longjmp%> second argument must be 1");
6190               return const0_rtx;
6191             }
6192
6193           expand_builtin_longjmp (buf_addr, value);
6194           return const0_rtx;
6195         }
6196       break;
6197
6198     case BUILT_IN_NONLOCAL_GOTO:
6199       target = expand_builtin_nonlocal_goto (exp);
6200       if (target)
6201         return target;
6202       break;
6203
6204       /* This updates the setjmp buffer that is its argument with the value
6205          of the current stack pointer.  */
6206     case BUILT_IN_UPDATE_SETJMP_BUF:
6207       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6208         {
6209           rtx buf_addr
6210             = expand_normal (CALL_EXPR_ARG (exp, 0));
6211
6212           expand_builtin_update_setjmp_buf (buf_addr);
6213           return const0_rtx;
6214         }
6215       break;
6216
6217     case BUILT_IN_TRAP:
6218       expand_builtin_trap ();
6219       return const0_rtx;
6220
6221     case BUILT_IN_UNREACHABLE:
6222       expand_builtin_unreachable ();
6223       return const0_rtx;
6224
6225     CASE_FLT_FN (BUILT_IN_SIGNBIT):
6226     case BUILT_IN_SIGNBITD32:
6227     case BUILT_IN_SIGNBITD64:
6228     case BUILT_IN_SIGNBITD128:
6229       target = expand_builtin_signbit (exp, target);
6230       if (target)
6231         return target;
6232       break;
6233
6234       /* Various hooks for the DWARF 2 __throw routine.  */
6235     case BUILT_IN_UNWIND_INIT:
6236       expand_builtin_unwind_init ();
6237       return const0_rtx;
6238     case BUILT_IN_DWARF_CFA:
6239       return virtual_cfa_rtx;
6240 #ifdef DWARF2_UNWIND_INFO
6241     case BUILT_IN_DWARF_SP_COLUMN:
6242       return expand_builtin_dwarf_sp_column ();
6243     case BUILT_IN_INIT_DWARF_REG_SIZES:
6244       expand_builtin_init_dwarf_reg_sizes (CALL_EXPR_ARG (exp, 0));
6245       return const0_rtx;
6246 #endif
6247     case BUILT_IN_FROB_RETURN_ADDR:
6248       return expand_builtin_frob_return_addr (CALL_EXPR_ARG (exp, 0));
6249     case BUILT_IN_EXTRACT_RETURN_ADDR:
6250       return expand_builtin_extract_return_addr (CALL_EXPR_ARG (exp, 0));
6251     case BUILT_IN_EH_RETURN:
6252       expand_builtin_eh_return (CALL_EXPR_ARG (exp, 0),
6253                                 CALL_EXPR_ARG (exp, 1));
6254       return const0_rtx;
6255 #ifdef EH_RETURN_DATA_REGNO
6256     case BUILT_IN_EH_RETURN_DATA_REGNO:
6257       return expand_builtin_eh_return_data_regno (exp);
6258 #endif
6259     case BUILT_IN_EXTEND_POINTER:
6260       return expand_builtin_extend_pointer (CALL_EXPR_ARG (exp, 0));
6261     case BUILT_IN_EH_POINTER:
6262       return expand_builtin_eh_pointer (exp);
6263     case BUILT_IN_EH_FILTER:
6264       return expand_builtin_eh_filter (exp);
6265     case BUILT_IN_EH_COPY_VALUES:
6266       return expand_builtin_eh_copy_values (exp);
6267
6268     case BUILT_IN_VA_START:
6269       return expand_builtin_va_start (exp);
6270     case BUILT_IN_VA_END:
6271       return expand_builtin_va_end (exp);
6272     case BUILT_IN_VA_COPY:
6273       return expand_builtin_va_copy (exp);
6274     case BUILT_IN_EXPECT:
6275       return expand_builtin_expect (exp, target);
6276     case BUILT_IN_ASSUME_ALIGNED:
6277       return expand_builtin_assume_aligned (exp, target);
6278     case BUILT_IN_PREFETCH:
6279       expand_builtin_prefetch (exp);
6280       return const0_rtx;
6281
6282     case BUILT_IN_INIT_TRAMPOLINE:
6283       return expand_builtin_init_trampoline (exp);
6284     case BUILT_IN_ADJUST_TRAMPOLINE:
6285       return expand_builtin_adjust_trampoline (exp);
6286
6287     case BUILT_IN_FORK:
6288     case BUILT_IN_EXECL:
6289     case BUILT_IN_EXECV:
6290     case BUILT_IN_EXECLP:
6291     case BUILT_IN_EXECLE:
6292     case BUILT_IN_EXECVP:
6293     case BUILT_IN_EXECVE:
6294       target = expand_builtin_fork_or_exec (fndecl, exp, target, ignore);
6295       if (target)
6296         return target;
6297       break;
6298
6299     case BUILT_IN_SYNC_FETCH_AND_ADD_1:
6300     case BUILT_IN_SYNC_FETCH_AND_ADD_2:
6301     case BUILT_IN_SYNC_FETCH_AND_ADD_4:
6302     case BUILT_IN_SYNC_FETCH_AND_ADD_8:
6303     case BUILT_IN_SYNC_FETCH_AND_ADD_16:
6304       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_ADD_1);
6305       target = expand_builtin_sync_operation (mode, exp, PLUS, false, target);
6306       if (target)
6307         return target;
6308       break;
6309
6310     case BUILT_IN_SYNC_FETCH_AND_SUB_1:
6311     case BUILT_IN_SYNC_FETCH_AND_SUB_2:
6312     case BUILT_IN_SYNC_FETCH_AND_SUB_4:
6313     case BUILT_IN_SYNC_FETCH_AND_SUB_8:
6314     case BUILT_IN_SYNC_FETCH_AND_SUB_16:
6315       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_SUB_1);
6316       target = expand_builtin_sync_operation (mode, exp, MINUS, false, target);
6317       if (target)
6318         return target;
6319       break;
6320
6321     case BUILT_IN_SYNC_FETCH_AND_OR_1:
6322     case BUILT_IN_SYNC_FETCH_AND_OR_2:
6323     case BUILT_IN_SYNC_FETCH_AND_OR_4:
6324     case BUILT_IN_SYNC_FETCH_AND_OR_8:
6325     case BUILT_IN_SYNC_FETCH_AND_OR_16:
6326       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_OR_1);
6327       target = expand_builtin_sync_operation (mode, exp, IOR, false, target);
6328       if (target)
6329         return target;
6330       break;
6331
6332     case BUILT_IN_SYNC_FETCH_AND_AND_1:
6333     case BUILT_IN_SYNC_FETCH_AND_AND_2:
6334     case BUILT_IN_SYNC_FETCH_AND_AND_4:
6335     case BUILT_IN_SYNC_FETCH_AND_AND_8:
6336     case BUILT_IN_SYNC_FETCH_AND_AND_16:
6337       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_AND_1);
6338       target = expand_builtin_sync_operation (mode, exp, AND, false, target);
6339       if (target)
6340         return target;
6341       break;
6342
6343     case BUILT_IN_SYNC_FETCH_AND_XOR_1:
6344     case BUILT_IN_SYNC_FETCH_AND_XOR_2:
6345     case BUILT_IN_SYNC_FETCH_AND_XOR_4:
6346     case BUILT_IN_SYNC_FETCH_AND_XOR_8:
6347     case BUILT_IN_SYNC_FETCH_AND_XOR_16:
6348       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_XOR_1);
6349       target = expand_builtin_sync_operation (mode, exp, XOR, false, target);
6350       if (target)
6351         return target;
6352       break;
6353
6354     case BUILT_IN_SYNC_FETCH_AND_NAND_1:
6355     case BUILT_IN_SYNC_FETCH_AND_NAND_2:
6356     case BUILT_IN_SYNC_FETCH_AND_NAND_4:
6357     case BUILT_IN_SYNC_FETCH_AND_NAND_8:
6358     case BUILT_IN_SYNC_FETCH_AND_NAND_16:
6359       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_NAND_1);
6360       target = expand_builtin_sync_operation (mode, exp, NOT, false, target);
6361       if (target)
6362         return target;
6363       break;
6364
6365     case BUILT_IN_SYNC_ADD_AND_FETCH_1:
6366     case BUILT_IN_SYNC_ADD_AND_FETCH_2:
6367     case BUILT_IN_SYNC_ADD_AND_FETCH_4:
6368     case BUILT_IN_SYNC_ADD_AND_FETCH_8:
6369     case BUILT_IN_SYNC_ADD_AND_FETCH_16:
6370       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_ADD_AND_FETCH_1);
6371       target = expand_builtin_sync_operation (mode, exp, PLUS, true, target);
6372       if (target)
6373         return target;
6374       break;
6375
6376     case BUILT_IN_SYNC_SUB_AND_FETCH_1:
6377     case BUILT_IN_SYNC_SUB_AND_FETCH_2:
6378     case BUILT_IN_SYNC_SUB_AND_FETCH_4:
6379     case BUILT_IN_SYNC_SUB_AND_FETCH_8:
6380     case BUILT_IN_SYNC_SUB_AND_FETCH_16:
6381       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_SUB_AND_FETCH_1);
6382       target = expand_builtin_sync_operation (mode, exp, MINUS, true, target);
6383       if (target)
6384         return target;
6385       break;
6386
6387     case BUILT_IN_SYNC_OR_AND_FETCH_1:
6388     case BUILT_IN_SYNC_OR_AND_FETCH_2:
6389     case BUILT_IN_SYNC_OR_AND_FETCH_4:
6390     case BUILT_IN_SYNC_OR_AND_FETCH_8:
6391     case BUILT_IN_SYNC_OR_AND_FETCH_16:
6392       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_OR_AND_FETCH_1);
6393       target = expand_builtin_sync_operation (mode, exp, IOR, true, target);
6394       if (target)
6395         return target;
6396       break;
6397
6398     case BUILT_IN_SYNC_AND_AND_FETCH_1:
6399     case BUILT_IN_SYNC_AND_AND_FETCH_2:
6400     case BUILT_IN_SYNC_AND_AND_FETCH_4:
6401     case BUILT_IN_SYNC_AND_AND_FETCH_8:
6402     case BUILT_IN_SYNC_AND_AND_FETCH_16:
6403       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_AND_AND_FETCH_1);
6404       target = expand_builtin_sync_operation (mode, exp, AND, true, target);
6405       if (target)
6406         return target;
6407       break;
6408
6409     case BUILT_IN_SYNC_XOR_AND_FETCH_1:
6410     case BUILT_IN_SYNC_XOR_AND_FETCH_2:
6411     case BUILT_IN_SYNC_XOR_AND_FETCH_4:
6412     case BUILT_IN_SYNC_XOR_AND_FETCH_8:
6413     case BUILT_IN_SYNC_XOR_AND_FETCH_16:
6414       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_XOR_AND_FETCH_1);
6415       target = expand_builtin_sync_operation (mode, exp, XOR, true, target);
6416       if (target)
6417         return target;
6418       break;
6419
6420     case BUILT_IN_SYNC_NAND_AND_FETCH_1:
6421     case BUILT_IN_SYNC_NAND_AND_FETCH_2:
6422     case BUILT_IN_SYNC_NAND_AND_FETCH_4:
6423     case BUILT_IN_SYNC_NAND_AND_FETCH_8:
6424     case BUILT_IN_SYNC_NAND_AND_FETCH_16:
6425       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_NAND_AND_FETCH_1);
6426       target = expand_builtin_sync_operation (mode, exp, NOT, true, target);
6427       if (target)
6428         return target;
6429       break;
6430
6431     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1:
6432     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_2:
6433     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_4:
6434     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_8:
6435     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_16:
6436       if (mode == VOIDmode)
6437         mode = TYPE_MODE (boolean_type_node);
6438       if (!target || !register_operand (target, mode))
6439         target = gen_reg_rtx (mode);
6440
6441       mode = get_builtin_sync_mode 
6442                                 (fcode - BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1);
6443       target = expand_builtin_compare_and_swap (mode, exp, true, target);
6444       if (target)
6445         return target;
6446       break;
6447
6448     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_1:
6449     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_2:
6450     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_4:
6451     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_8:
6452     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_16:
6453       mode = get_builtin_sync_mode 
6454                                 (fcode - BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_1);
6455       target = expand_builtin_compare_and_swap (mode, exp, false, target);
6456       if (target)
6457         return target;
6458       break;
6459
6460     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_1:
6461     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_2:
6462     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_4:
6463     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_8:
6464     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_16:
6465       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_LOCK_TEST_AND_SET_1);
6466       target = expand_builtin_sync_lock_test_and_set (mode, exp, target);
6467       if (target)
6468         return target;
6469       break;
6470
6471     case BUILT_IN_SYNC_LOCK_RELEASE_1:
6472     case BUILT_IN_SYNC_LOCK_RELEASE_2:
6473     case BUILT_IN_SYNC_LOCK_RELEASE_4:
6474     case BUILT_IN_SYNC_LOCK_RELEASE_8:
6475     case BUILT_IN_SYNC_LOCK_RELEASE_16:
6476       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_LOCK_RELEASE_1);
6477       expand_builtin_sync_lock_release (mode, exp);
6478       return const0_rtx;
6479
6480     case BUILT_IN_SYNC_SYNCHRONIZE:
6481       expand_builtin_sync_synchronize ();
6482       return const0_rtx;
6483
6484     case BUILT_IN_ATOMIC_EXCHANGE_1:
6485     case BUILT_IN_ATOMIC_EXCHANGE_2:
6486     case BUILT_IN_ATOMIC_EXCHANGE_4:
6487     case BUILT_IN_ATOMIC_EXCHANGE_8:
6488     case BUILT_IN_ATOMIC_EXCHANGE_16:
6489       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_EXCHANGE_1);
6490       target = expand_builtin_atomic_exchange (mode, exp, target);
6491       if (target)
6492         return target;
6493       break;
6494
6495     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1:
6496     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2:
6497     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4:
6498     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8:
6499     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16:
6500       mode = 
6501           get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1);
6502       target = expand_builtin_atomic_compare_exchange (mode, exp, target);
6503       if (target)
6504         return target;
6505       break;
6506
6507     case BUILT_IN_ATOMIC_LOAD_1:
6508     case BUILT_IN_ATOMIC_LOAD_2:
6509     case BUILT_IN_ATOMIC_LOAD_4:
6510     case BUILT_IN_ATOMIC_LOAD_8:
6511     case BUILT_IN_ATOMIC_LOAD_16:
6512       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_LOAD_1);
6513       target = expand_builtin_atomic_load (mode, exp, target);
6514       if (target)
6515         return target;
6516       break;
6517
6518     case BUILT_IN_ATOMIC_STORE_1:
6519     case BUILT_IN_ATOMIC_STORE_2:
6520     case BUILT_IN_ATOMIC_STORE_4:
6521     case BUILT_IN_ATOMIC_STORE_8:
6522     case BUILT_IN_ATOMIC_STORE_16:
6523       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_STORE_1);
6524       target = expand_builtin_atomic_store (mode, exp);
6525       if (target)
6526         return const0_rtx;
6527       break;
6528
6529     case BUILT_IN_ATOMIC_ADD_FETCH_1:
6530     case BUILT_IN_ATOMIC_ADD_FETCH_2:
6531     case BUILT_IN_ATOMIC_ADD_FETCH_4:
6532     case BUILT_IN_ATOMIC_ADD_FETCH_8:
6533     case BUILT_IN_ATOMIC_ADD_FETCH_16:
6534       {
6535         enum built_in_function lib;
6536         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_ADD_FETCH_1);
6537         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_ADD_1 + 
6538                                        (fcode - BUILT_IN_ATOMIC_ADD_FETCH_1));
6539         target = expand_builtin_atomic_fetch_op (mode, exp, target, PLUS, true,
6540                                                  ignore, lib);
6541         if (target)
6542           return target;
6543         break;
6544       }
6545     case BUILT_IN_ATOMIC_SUB_FETCH_1:
6546     case BUILT_IN_ATOMIC_SUB_FETCH_2:
6547     case BUILT_IN_ATOMIC_SUB_FETCH_4:
6548     case BUILT_IN_ATOMIC_SUB_FETCH_8:
6549     case BUILT_IN_ATOMIC_SUB_FETCH_16:
6550       {
6551         enum built_in_function lib;
6552         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_SUB_FETCH_1);
6553         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_SUB_1 + 
6554                                        (fcode - BUILT_IN_ATOMIC_SUB_FETCH_1));
6555         target = expand_builtin_atomic_fetch_op (mode, exp, target, MINUS, true,
6556                                                  ignore, lib);
6557         if (target)
6558           return target;
6559         break;
6560       }
6561     case BUILT_IN_ATOMIC_AND_FETCH_1:
6562     case BUILT_IN_ATOMIC_AND_FETCH_2:
6563     case BUILT_IN_ATOMIC_AND_FETCH_4:
6564     case BUILT_IN_ATOMIC_AND_FETCH_8:
6565     case BUILT_IN_ATOMIC_AND_FETCH_16:
6566       {
6567         enum built_in_function lib;
6568         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_AND_FETCH_1);
6569         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_AND_1 + 
6570                                        (fcode - BUILT_IN_ATOMIC_AND_FETCH_1));
6571         target = expand_builtin_atomic_fetch_op (mode, exp, target, AND, true,
6572                                                  ignore, lib);
6573         if (target)
6574           return target;
6575         break;
6576       }
6577     case BUILT_IN_ATOMIC_NAND_FETCH_1:
6578     case BUILT_IN_ATOMIC_NAND_FETCH_2:
6579     case BUILT_IN_ATOMIC_NAND_FETCH_4:
6580     case BUILT_IN_ATOMIC_NAND_FETCH_8:
6581     case BUILT_IN_ATOMIC_NAND_FETCH_16:
6582       {
6583         enum built_in_function lib;
6584         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_NAND_FETCH_1);
6585         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_NAND_1 + 
6586                                        (fcode - BUILT_IN_ATOMIC_NAND_FETCH_1));
6587         target = expand_builtin_atomic_fetch_op (mode, exp, target, NOT, true,
6588                                                  ignore, lib);
6589         if (target)
6590           return target;
6591         break;
6592       }
6593     case BUILT_IN_ATOMIC_XOR_FETCH_1:
6594     case BUILT_IN_ATOMIC_XOR_FETCH_2:
6595     case BUILT_IN_ATOMIC_XOR_FETCH_4:
6596     case BUILT_IN_ATOMIC_XOR_FETCH_8:
6597     case BUILT_IN_ATOMIC_XOR_FETCH_16:
6598       {
6599         enum built_in_function lib;
6600         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_XOR_FETCH_1);
6601         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_XOR_1 + 
6602                                        (fcode - BUILT_IN_ATOMIC_XOR_FETCH_1));
6603         target = expand_builtin_atomic_fetch_op (mode, exp, target, XOR, true,
6604                                                  ignore, lib);
6605         if (target)
6606           return target;
6607         break;
6608       }
6609     case BUILT_IN_ATOMIC_OR_FETCH_1:
6610     case BUILT_IN_ATOMIC_OR_FETCH_2:
6611     case BUILT_IN_ATOMIC_OR_FETCH_4:
6612     case BUILT_IN_ATOMIC_OR_FETCH_8:
6613     case BUILT_IN_ATOMIC_OR_FETCH_16:
6614       {
6615         enum built_in_function lib;
6616         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_OR_FETCH_1);
6617         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_OR_1 + 
6618                                        (fcode - BUILT_IN_ATOMIC_OR_FETCH_1));
6619         target = expand_builtin_atomic_fetch_op (mode, exp, target, IOR, true,
6620                                                  ignore, lib);
6621         if (target)
6622           return target;
6623         break;
6624       }
6625     case BUILT_IN_ATOMIC_FETCH_ADD_1:
6626     case BUILT_IN_ATOMIC_FETCH_ADD_2:
6627     case BUILT_IN_ATOMIC_FETCH_ADD_4:
6628     case BUILT_IN_ATOMIC_FETCH_ADD_8:
6629     case BUILT_IN_ATOMIC_FETCH_ADD_16:
6630       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_ADD_1);
6631       target = expand_builtin_atomic_fetch_op (mode, exp, target, PLUS, false,
6632                                                ignore, BUILT_IN_NONE);
6633       if (target)
6634         return target;
6635       break;
6636  
6637     case BUILT_IN_ATOMIC_FETCH_SUB_1:
6638     case BUILT_IN_ATOMIC_FETCH_SUB_2:
6639     case BUILT_IN_ATOMIC_FETCH_SUB_4:
6640     case BUILT_IN_ATOMIC_FETCH_SUB_8:
6641     case BUILT_IN_ATOMIC_FETCH_SUB_16:
6642       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_SUB_1);
6643       target = expand_builtin_atomic_fetch_op (mode, exp, target, MINUS, false,
6644                                                ignore, BUILT_IN_NONE);
6645       if (target)
6646         return target;
6647       break;
6648
6649     case BUILT_IN_ATOMIC_FETCH_AND_1:
6650     case BUILT_IN_ATOMIC_FETCH_AND_2:
6651     case BUILT_IN_ATOMIC_FETCH_AND_4:
6652     case BUILT_IN_ATOMIC_FETCH_AND_8:
6653     case BUILT_IN_ATOMIC_FETCH_AND_16:
6654       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_AND_1);
6655       target = expand_builtin_atomic_fetch_op (mode, exp, target, AND, false,
6656                                                ignore, BUILT_IN_NONE);
6657       if (target)
6658         return target;
6659       break;
6660   
6661     case BUILT_IN_ATOMIC_FETCH_NAND_1:
6662     case BUILT_IN_ATOMIC_FETCH_NAND_2:
6663     case BUILT_IN_ATOMIC_FETCH_NAND_4:
6664     case BUILT_IN_ATOMIC_FETCH_NAND_8:
6665     case BUILT_IN_ATOMIC_FETCH_NAND_16:
6666       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_NAND_1);
6667       target = expand_builtin_atomic_fetch_op (mode, exp, target, NOT, false,
6668                                                ignore, BUILT_IN_NONE);
6669       if (target)
6670         return target;
6671       break;
6672  
6673     case BUILT_IN_ATOMIC_FETCH_XOR_1:
6674     case BUILT_IN_ATOMIC_FETCH_XOR_2:
6675     case BUILT_IN_ATOMIC_FETCH_XOR_4:
6676     case BUILT_IN_ATOMIC_FETCH_XOR_8:
6677     case BUILT_IN_ATOMIC_FETCH_XOR_16:
6678       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_XOR_1);
6679       target = expand_builtin_atomic_fetch_op (mode, exp, target, XOR, false,
6680                                                ignore, BUILT_IN_NONE);
6681       if (target)
6682         return target;
6683       break;
6684  
6685     case BUILT_IN_ATOMIC_FETCH_OR_1:
6686     case BUILT_IN_ATOMIC_FETCH_OR_2:
6687     case BUILT_IN_ATOMIC_FETCH_OR_4:
6688     case BUILT_IN_ATOMIC_FETCH_OR_8:
6689     case BUILT_IN_ATOMIC_FETCH_OR_16:
6690       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_OR_1);
6691       target = expand_builtin_atomic_fetch_op (mode, exp, target, IOR, false,
6692                                                ignore, BUILT_IN_NONE);
6693       if (target)
6694         return target;
6695       break;
6696  
6697     case BUILT_IN_ATOMIC_ALWAYS_LOCK_FREE:
6698       return expand_builtin_atomic_always_lock_free (exp);
6699
6700     case BUILT_IN_ATOMIC_IS_LOCK_FREE:
6701       target = expand_builtin_atomic_is_lock_free (exp);
6702       if (target)
6703         return target;
6704       break;
6705
6706     case BUILT_IN_ATOMIC_THREAD_FENCE:
6707       expand_builtin_atomic_thread_fence (exp);
6708       return const0_rtx;
6709
6710     case BUILT_IN_ATOMIC_SIGNAL_FENCE:
6711       expand_builtin_atomic_signal_fence (exp);
6712       return const0_rtx;
6713
6714     case BUILT_IN_OBJECT_SIZE:
6715       return expand_builtin_object_size (exp);
6716
6717     case BUILT_IN_MEMCPY_CHK:
6718     case BUILT_IN_MEMPCPY_CHK:
6719     case BUILT_IN_MEMMOVE_CHK:
6720     case BUILT_IN_MEMSET_CHK:
6721       target = expand_builtin_memory_chk (exp, target, mode, fcode);
6722       if (target)
6723         return target;
6724       break;
6725
6726     case BUILT_IN_STRCPY_CHK:
6727     case BUILT_IN_STPCPY_CHK:
6728     case BUILT_IN_STRNCPY_CHK:
6729     case BUILT_IN_STRCAT_CHK:
6730     case BUILT_IN_STRNCAT_CHK:
6731     case BUILT_IN_SNPRINTF_CHK:
6732     case BUILT_IN_VSNPRINTF_CHK:
6733       maybe_emit_chk_warning (exp, fcode);
6734       break;
6735
6736     case BUILT_IN_SPRINTF_CHK:
6737     case BUILT_IN_VSPRINTF_CHK:
6738       maybe_emit_sprintf_chk_warning (exp, fcode);
6739       break;
6740
6741     case BUILT_IN_FREE:
6742       if (warn_free_nonheap_object)
6743         maybe_emit_free_warning (exp);
6744       break;
6745
6746     default:    /* just do library call, if unknown builtin */
6747       break;
6748     }
6749
6750   /* The switch statement above can drop through to cause the function
6751      to be called normally.  */
6752   return expand_call (exp, target, ignore);
6753 }
6754
6755 /* Determine whether a tree node represents a call to a built-in
6756    function.  If the tree T is a call to a built-in function with
6757    the right number of arguments of the appropriate types, return
6758    the DECL_FUNCTION_CODE of the call, e.g. BUILT_IN_SQRT.
6759    Otherwise the return value is END_BUILTINS.  */
6760
6761 enum built_in_function
6762 builtin_mathfn_code (const_tree t)
6763 {
6764   const_tree fndecl, arg, parmlist;
6765   const_tree argtype, parmtype;
6766   const_call_expr_arg_iterator iter;
6767
6768   if (TREE_CODE (t) != CALL_EXPR
6769       || TREE_CODE (CALL_EXPR_FN (t)) != ADDR_EXPR)
6770     return END_BUILTINS;
6771
6772   fndecl = get_callee_fndecl (t);
6773   if (fndecl == NULL_TREE
6774       || TREE_CODE (fndecl) != FUNCTION_DECL
6775       || ! DECL_BUILT_IN (fndecl)
6776       || DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
6777     return END_BUILTINS;
6778
6779   parmlist = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
6780   init_const_call_expr_arg_iterator (t, &iter);
6781   for (; parmlist; parmlist = TREE_CHAIN (parmlist))
6782     {
6783       /* If a function doesn't take a variable number of arguments,
6784          the last element in the list will have type `void'.  */
6785       parmtype = TREE_VALUE (parmlist);
6786       if (VOID_TYPE_P (parmtype))
6787         {
6788           if (more_const_call_expr_args_p (&iter))
6789             return END_BUILTINS;
6790           return DECL_FUNCTION_CODE (fndecl);
6791         }
6792
6793       if (! more_const_call_expr_args_p (&iter))
6794         return END_BUILTINS;
6795
6796       arg = next_const_call_expr_arg (&iter);
6797       argtype = TREE_TYPE (arg);
6798
6799       if (SCALAR_FLOAT_TYPE_P (parmtype))
6800         {
6801           if (! SCALAR_FLOAT_TYPE_P (argtype))
6802             return END_BUILTINS;
6803         }
6804       else if (COMPLEX_FLOAT_TYPE_P (parmtype))
6805         {
6806           if (! COMPLEX_FLOAT_TYPE_P (argtype))
6807             return END_BUILTINS;
6808         }
6809       else if (POINTER_TYPE_P (parmtype))
6810         {
6811           if (! POINTER_TYPE_P (argtype))
6812             return END_BUILTINS;
6813         }
6814       else if (INTEGRAL_TYPE_P (parmtype))
6815         {
6816           if (! INTEGRAL_TYPE_P (argtype))
6817             return END_BUILTINS;
6818         }
6819       else
6820         return END_BUILTINS;
6821     }
6822
6823   /* Variable-length argument list.  */
6824   return DECL_FUNCTION_CODE (fndecl);
6825 }
6826
6827 /* Fold a call to __builtin_constant_p, if we know its argument ARG will
6828    evaluate to a constant.  */
6829
6830 static tree
6831 fold_builtin_constant_p (tree arg)
6832 {
6833   /* We return 1 for a numeric type that's known to be a constant
6834      value at compile-time or for an aggregate type that's a
6835      literal constant.  */
6836   STRIP_NOPS (arg);
6837
6838   /* If we know this is a constant, emit the constant of one.  */
6839   if (CONSTANT_CLASS_P (arg)
6840       || (TREE_CODE (arg) == CONSTRUCTOR
6841           && TREE_CONSTANT (arg)))
6842     return integer_one_node;
6843   if (TREE_CODE (arg) == ADDR_EXPR)
6844     {
6845        tree op = TREE_OPERAND (arg, 0);
6846        if (TREE_CODE (op) == STRING_CST
6847            || (TREE_CODE (op) == ARRAY_REF
6848                && integer_zerop (TREE_OPERAND (op, 1))
6849                && TREE_CODE (TREE_OPERAND (op, 0)) == STRING_CST))
6850          return integer_one_node;
6851     }
6852
6853   /* If this expression has side effects, show we don't know it to be a
6854      constant.  Likewise if it's a pointer or aggregate type since in
6855      those case we only want literals, since those are only optimized
6856      when generating RTL, not later.
6857      And finally, if we are compiling an initializer, not code, we
6858      need to return a definite result now; there's not going to be any
6859      more optimization done.  */
6860   if (TREE_SIDE_EFFECTS (arg)
6861       || AGGREGATE_TYPE_P (TREE_TYPE (arg))
6862       || POINTER_TYPE_P (TREE_TYPE (arg))
6863       || cfun == 0
6864       || folding_initializer)
6865     return integer_zero_node;
6866
6867   return NULL_TREE;
6868 }
6869
6870 /* Create builtin_expect with PRED and EXPECTED as its arguments and
6871    return it as a truthvalue.  */
6872
6873 static tree
6874 build_builtin_expect_predicate (location_t loc, tree pred, tree expected)
6875 {
6876   tree fn, arg_types, pred_type, expected_type, call_expr, ret_type;
6877
6878   fn = builtin_decl_explicit (BUILT_IN_EXPECT);
6879   arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
6880   ret_type = TREE_TYPE (TREE_TYPE (fn));
6881   pred_type = TREE_VALUE (arg_types);
6882   expected_type = TREE_VALUE (TREE_CHAIN (arg_types));
6883
6884   pred = fold_convert_loc (loc, pred_type, pred);
6885   expected = fold_convert_loc (loc, expected_type, expected);
6886   call_expr = build_call_expr_loc (loc, fn, 2, pred, expected);
6887
6888   return build2 (NE_EXPR, TREE_TYPE (pred), call_expr,
6889                  build_int_cst (ret_type, 0));
6890 }
6891
6892 /* Fold a call to builtin_expect with arguments ARG0 and ARG1.  Return
6893    NULL_TREE if no simplification is possible.  */
6894
6895 static tree
6896 fold_builtin_expect (location_t loc, tree arg0, tree arg1)
6897 {
6898   tree inner, fndecl, inner_arg0;
6899   enum tree_code code;
6900
6901   /* Distribute the expected value over short-circuiting operators.
6902      See through the cast from truthvalue_type_node to long.  */
6903   inner_arg0 = arg0;
6904   while (TREE_CODE (inner_arg0) == NOP_EXPR
6905          && INTEGRAL_TYPE_P (TREE_TYPE (inner_arg0))
6906          && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (inner_arg0, 0))))
6907     inner_arg0 = TREE_OPERAND (inner_arg0, 0);
6908
6909   /* If this is a builtin_expect within a builtin_expect keep the
6910      inner one.  See through a comparison against a constant.  It
6911      might have been added to create a thruthvalue.  */
6912   inner = inner_arg0;
6913
6914   if (COMPARISON_CLASS_P (inner)
6915       && TREE_CODE (TREE_OPERAND (inner, 1)) == INTEGER_CST)
6916     inner = TREE_OPERAND (inner, 0);
6917
6918   if (TREE_CODE (inner) == CALL_EXPR
6919       && (fndecl = get_callee_fndecl (inner))
6920       && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
6921       && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT)
6922     return arg0;
6923
6924   inner = inner_arg0;
6925   code = TREE_CODE (inner);
6926   if (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR)
6927     {
6928       tree op0 = TREE_OPERAND (inner, 0);
6929       tree op1 = TREE_OPERAND (inner, 1);
6930
6931       op0 = build_builtin_expect_predicate (loc, op0, arg1);
6932       op1 = build_builtin_expect_predicate (loc, op1, arg1);
6933       inner = build2 (code, TREE_TYPE (inner), op0, op1);
6934
6935       return fold_convert_loc (loc, TREE_TYPE (arg0), inner);
6936     }
6937
6938   /* If the argument isn't invariant then there's nothing else we can do.  */
6939   if (!TREE_CONSTANT (inner_arg0))
6940     return NULL_TREE;
6941
6942   /* If we expect that a comparison against the argument will fold to
6943      a constant return the constant.  In practice, this means a true
6944      constant or the address of a non-weak symbol.  */
6945   inner = inner_arg0;
6946   STRIP_NOPS (inner);
6947   if (TREE_CODE (inner) == ADDR_EXPR)
6948     {
6949       do
6950         {
6951           inner = TREE_OPERAND (inner, 0);
6952         }
6953       while (TREE_CODE (inner) == COMPONENT_REF
6954              || TREE_CODE (inner) == ARRAY_REF);
6955       if ((TREE_CODE (inner) == VAR_DECL
6956            || TREE_CODE (inner) == FUNCTION_DECL)
6957           && DECL_WEAK (inner))
6958         return NULL_TREE;
6959     }
6960
6961   /* Otherwise, ARG0 already has the proper type for the return value.  */
6962   return arg0;
6963 }
6964
6965 /* Fold a call to __builtin_classify_type with argument ARG.  */
6966
6967 static tree
6968 fold_builtin_classify_type (tree arg)
6969 {
6970   if (arg == 0)
6971     return build_int_cst (integer_type_node, no_type_class);
6972
6973   return build_int_cst (integer_type_node, type_to_class (TREE_TYPE (arg)));
6974 }
6975
6976 /* Fold a call to __builtin_strlen with argument ARG.  */
6977
6978 static tree
6979 fold_builtin_strlen (location_t loc, tree type, tree arg)
6980 {
6981   if (!validate_arg (arg, POINTER_TYPE))
6982     return NULL_TREE;
6983   else
6984     {
6985       tree len = c_strlen (arg, 0);
6986
6987       if (len)
6988         return fold_convert_loc (loc, type, len);
6989
6990       return NULL_TREE;
6991     }
6992 }
6993
6994 /* Fold a call to __builtin_inf or __builtin_huge_val.  */
6995
6996 static tree
6997 fold_builtin_inf (location_t loc, tree type, int warn)
6998 {
6999   REAL_VALUE_TYPE real;
7000
7001   /* __builtin_inff is intended to be usable to define INFINITY on all
7002      targets.  If an infinity is not available, INFINITY expands "to a
7003      positive constant of type float that overflows at translation
7004      time", footnote "In this case, using INFINITY will violate the
7005      constraint in 6.4.4 and thus require a diagnostic." (C99 7.12#4).
7006      Thus we pedwarn to ensure this constraint violation is
7007      diagnosed.  */
7008   if (!MODE_HAS_INFINITIES (TYPE_MODE (type)) && warn)
7009     pedwarn (loc, 0, "target format does not support infinity");
7010
7011   real_inf (&real);
7012   return build_real (type, real);
7013 }
7014
7015 /* Fold a call to __builtin_nan or __builtin_nans with argument ARG.  */
7016
7017 static tree
7018 fold_builtin_nan (tree arg, tree type, int quiet)
7019 {
7020   REAL_VALUE_TYPE real;
7021   const char *str;
7022
7023   if (!validate_arg (arg, POINTER_TYPE))
7024     return NULL_TREE;
7025   str = c_getstr (arg);
7026   if (!str)
7027     return NULL_TREE;
7028
7029   if (!real_nan (&real, str, quiet, TYPE_MODE (type)))
7030     return NULL_TREE;
7031
7032   return build_real (type, real);
7033 }
7034
7035 /* Return true if the floating point expression T has an integer value.
7036    We also allow +Inf, -Inf and NaN to be considered integer values.  */
7037
7038 static bool
7039 integer_valued_real_p (tree t)
7040 {
7041   switch (TREE_CODE (t))
7042     {
7043     case FLOAT_EXPR:
7044       return true;
7045
7046     case ABS_EXPR:
7047     case SAVE_EXPR:
7048       return integer_valued_real_p (TREE_OPERAND (t, 0));
7049
7050     case COMPOUND_EXPR:
7051     case MODIFY_EXPR:
7052     case BIND_EXPR:
7053       return integer_valued_real_p (TREE_OPERAND (t, 1));
7054
7055     case PLUS_EXPR:
7056     case MINUS_EXPR:
7057     case MULT_EXPR:
7058     case MIN_EXPR:
7059     case MAX_EXPR:
7060       return integer_valued_real_p (TREE_OPERAND (t, 0))
7061              && integer_valued_real_p (TREE_OPERAND (t, 1));
7062
7063     case COND_EXPR:
7064       return integer_valued_real_p (TREE_OPERAND (t, 1))
7065              && integer_valued_real_p (TREE_OPERAND (t, 2));
7066
7067     case REAL_CST:
7068       return real_isinteger (TREE_REAL_CST_PTR (t), TYPE_MODE (TREE_TYPE (t)));
7069
7070     case NOP_EXPR:
7071       {
7072         tree type = TREE_TYPE (TREE_OPERAND (t, 0));
7073         if (TREE_CODE (type) == INTEGER_TYPE)
7074           return true;
7075         if (TREE_CODE (type) == REAL_TYPE)
7076           return integer_valued_real_p (TREE_OPERAND (t, 0));
7077         break;
7078       }
7079
7080     case CALL_EXPR:
7081       switch (builtin_mathfn_code (t))
7082         {
7083         CASE_FLT_FN (BUILT_IN_CEIL):
7084         CASE_FLT_FN (BUILT_IN_FLOOR):
7085         CASE_FLT_FN (BUILT_IN_NEARBYINT):
7086         CASE_FLT_FN (BUILT_IN_RINT):
7087         CASE_FLT_FN (BUILT_IN_ROUND):
7088         CASE_FLT_FN (BUILT_IN_TRUNC):
7089           return true;
7090
7091         CASE_FLT_FN (BUILT_IN_FMIN):
7092         CASE_FLT_FN (BUILT_IN_FMAX):
7093           return integer_valued_real_p (CALL_EXPR_ARG (t, 0))
7094             && integer_valued_real_p (CALL_EXPR_ARG (t, 1));
7095
7096         default:
7097           break;
7098         }
7099       break;
7100
7101     default:
7102       break;
7103     }
7104   return false;
7105 }
7106
7107 /* FNDECL is assumed to be a builtin where truncation can be propagated
7108    across (for instance floor((double)f) == (double)floorf (f).
7109    Do the transformation for a call with argument ARG.  */
7110
7111 static tree
7112 fold_trunc_transparent_mathfn (location_t loc, tree fndecl, tree arg)
7113 {
7114   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
7115
7116   if (!validate_arg (arg, REAL_TYPE))
7117     return NULL_TREE;
7118
7119   /* Integer rounding functions are idempotent.  */
7120   if (fcode == builtin_mathfn_code (arg))
7121     return arg;
7122
7123   /* If argument is already integer valued, and we don't need to worry
7124      about setting errno, there's no need to perform rounding.  */
7125   if (! flag_errno_math && integer_valued_real_p (arg))
7126     return arg;
7127
7128   if (optimize)
7129     {
7130       tree arg0 = strip_float_extensions (arg);
7131       tree ftype = TREE_TYPE (TREE_TYPE (fndecl));
7132       tree newtype = TREE_TYPE (arg0);
7133       tree decl;
7134
7135       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
7136           && (decl = mathfn_built_in (newtype, fcode)))
7137         return fold_convert_loc (loc, ftype,
7138                                  build_call_expr_loc (loc, decl, 1,
7139                                                   fold_convert_loc (loc,
7140                                                                     newtype,
7141                                                                     arg0)));
7142     }
7143   return NULL_TREE;
7144 }
7145
7146 /* FNDECL is assumed to be builtin which can narrow the FP type of
7147    the argument, for instance lround((double)f) -> lroundf (f).
7148    Do the transformation for a call with argument ARG.  */
7149
7150 static tree
7151 fold_fixed_mathfn (location_t loc, tree fndecl, tree arg)
7152 {
7153   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
7154
7155   if (!validate_arg (arg, REAL_TYPE))
7156     return NULL_TREE;
7157
7158   /* If argument is already integer valued, and we don't need to worry
7159      about setting errno, there's no need to perform rounding.  */
7160   if (! flag_errno_math && integer_valued_real_p (arg))
7161     return fold_build1_loc (loc, FIX_TRUNC_EXPR,
7162                         TREE_TYPE (TREE_TYPE (fndecl)), arg);
7163
7164   if (optimize)
7165     {
7166       tree ftype = TREE_TYPE (arg);
7167       tree arg0 = strip_float_extensions (arg);
7168       tree newtype = TREE_TYPE (arg0);
7169       tree decl;
7170
7171       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
7172           && (decl = mathfn_built_in (newtype, fcode)))
7173         return build_call_expr_loc (loc, decl, 1,
7174                                 fold_convert_loc (loc, newtype, arg0));
7175     }
7176
7177   /* Canonicalize iround (x) to lround (x) on ILP32 targets where
7178      sizeof (int) == sizeof (long).  */
7179   if (TYPE_PRECISION (integer_type_node)
7180       == TYPE_PRECISION (long_integer_type_node))
7181     {
7182       tree newfn = NULL_TREE;
7183       switch (fcode)
7184         {
7185         CASE_FLT_FN (BUILT_IN_ICEIL):
7186           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LCEIL);
7187           break;
7188
7189         CASE_FLT_FN (BUILT_IN_IFLOOR):
7190           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LFLOOR);
7191           break;
7192
7193         CASE_FLT_FN (BUILT_IN_IROUND):
7194           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LROUND);
7195           break;
7196
7197         CASE_FLT_FN (BUILT_IN_IRINT):
7198           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LRINT);
7199           break;
7200
7201         default:
7202           break;
7203         }
7204
7205       if (newfn)
7206         {
7207           tree newcall = build_call_expr_loc (loc, newfn, 1, arg);
7208           return fold_convert_loc (loc,
7209                                    TREE_TYPE (TREE_TYPE (fndecl)), newcall);
7210         }
7211     }
7212
7213   /* Canonicalize llround (x) to lround (x) on LP64 targets where
7214      sizeof (long long) == sizeof (long).  */
7215   if (TYPE_PRECISION (long_long_integer_type_node)
7216       == TYPE_PRECISION (long_integer_type_node))
7217     {
7218       tree newfn = NULL_TREE;
7219       switch (fcode)
7220         {
7221         CASE_FLT_FN (BUILT_IN_LLCEIL):
7222           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LCEIL);
7223           break;
7224
7225         CASE_FLT_FN (BUILT_IN_LLFLOOR):
7226           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LFLOOR);
7227           break;
7228
7229         CASE_FLT_FN (BUILT_IN_LLROUND):
7230           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LROUND);
7231           break;
7232
7233         CASE_FLT_FN (BUILT_IN_LLRINT):
7234           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LRINT);
7235           break;
7236
7237         default:
7238           break;
7239         }
7240
7241       if (newfn)
7242         {
7243           tree newcall = build_call_expr_loc (loc, newfn, 1, arg);
7244           return fold_convert_loc (loc,
7245                                    TREE_TYPE (TREE_TYPE (fndecl)), newcall);
7246         }
7247     }
7248
7249   return NULL_TREE;
7250 }
7251
7252 /* Fold call to builtin cabs, cabsf or cabsl with argument ARG.  TYPE is the
7253    return type.  Return NULL_TREE if no simplification can be made.  */
7254
7255 static tree
7256 fold_builtin_cabs (location_t loc, tree arg, tree type, tree fndecl)
7257 {
7258   tree res;
7259
7260   if (!validate_arg (arg, COMPLEX_TYPE)
7261       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) != REAL_TYPE)
7262     return NULL_TREE;
7263
7264   /* Calculate the result when the argument is a constant.  */
7265   if (TREE_CODE (arg) == COMPLEX_CST
7266       && (res = do_mpfr_arg2 (TREE_REALPART (arg), TREE_IMAGPART (arg),
7267                               type, mpfr_hypot)))
7268     return res;
7269
7270   if (TREE_CODE (arg) == COMPLEX_EXPR)
7271     {
7272       tree real = TREE_OPERAND (arg, 0);
7273       tree imag = TREE_OPERAND (arg, 1);
7274
7275       /* If either part is zero, cabs is fabs of the other.  */
7276       if (real_zerop (real))
7277         return fold_build1_loc (loc, ABS_EXPR, type, imag);
7278       if (real_zerop (imag))
7279         return fold_build1_loc (loc, ABS_EXPR, type, real);
7280
7281       /* cabs(x+xi) -> fabs(x)*sqrt(2).  */
7282       if (flag_unsafe_math_optimizations
7283           && operand_equal_p (real, imag, OEP_PURE_SAME))
7284         {
7285           const REAL_VALUE_TYPE sqrt2_trunc
7286             = real_value_truncate (TYPE_MODE (type), dconst_sqrt2 ());
7287           STRIP_NOPS (real);
7288           return fold_build2_loc (loc, MULT_EXPR, type,
7289                               fold_build1_loc (loc, ABS_EXPR, type, real),
7290                               build_real (type, sqrt2_trunc));
7291         }
7292     }
7293
7294   /* Optimize cabs(-z) and cabs(conj(z)) as cabs(z).  */
7295   if (TREE_CODE (arg) == NEGATE_EXPR
7296       || TREE_CODE (arg) == CONJ_EXPR)
7297     return build_call_expr_loc (loc, fndecl, 1, TREE_OPERAND (arg, 0));
7298
7299   /* Don't do this when optimizing for size.  */
7300   if (flag_unsafe_math_optimizations
7301       && optimize && optimize_function_for_speed_p (cfun))
7302     {
7303       tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
7304
7305       if (sqrtfn != NULL_TREE)
7306         {
7307           tree rpart, ipart, result;
7308
7309           arg = builtin_save_expr (arg);
7310
7311           rpart = fold_build1_loc (loc, REALPART_EXPR, type, arg);
7312           ipart = fold_build1_loc (loc, IMAGPART_EXPR, type, arg);
7313
7314           rpart = builtin_save_expr (rpart);
7315           ipart = builtin_save_expr (ipart);
7316
7317           result = fold_build2_loc (loc, PLUS_EXPR, type,
7318                                 fold_build2_loc (loc, MULT_EXPR, type,
7319                                              rpart, rpart),
7320                                 fold_build2_loc (loc, MULT_EXPR, type,
7321                                              ipart, ipart));
7322
7323           return build_call_expr_loc (loc, sqrtfn, 1, result);
7324         }
7325     }
7326
7327   return NULL_TREE;
7328 }
7329
7330 /* Build a complex (inf +- 0i) for the result of cproj.  TYPE is the
7331    complex tree type of the result.  If NEG is true, the imaginary
7332    zero is negative.  */
7333
7334 static tree
7335 build_complex_cproj (tree type, bool neg)
7336 {
7337   REAL_VALUE_TYPE rinf, rzero = dconst0;
7338   
7339   real_inf (&rinf);
7340   rzero.sign = neg;
7341   return build_complex (type, build_real (TREE_TYPE (type), rinf),
7342                         build_real (TREE_TYPE (type), rzero));
7343 }
7344
7345 /* Fold call to builtin cproj, cprojf or cprojl with argument ARG.  TYPE is the
7346    return type.  Return NULL_TREE if no simplification can be made.  */
7347
7348 static tree
7349 fold_builtin_cproj (location_t loc, tree arg, tree type)
7350 {
7351   if (!validate_arg (arg, COMPLEX_TYPE)
7352       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) != REAL_TYPE)
7353     return NULL_TREE;
7354
7355   /* If there are no infinities, return arg.  */
7356   if (! HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (type))))
7357     return non_lvalue_loc (loc, arg);
7358
7359   /* Calculate the result when the argument is a constant.  */
7360   if (TREE_CODE (arg) == COMPLEX_CST)
7361     {
7362       const REAL_VALUE_TYPE *real = TREE_REAL_CST_PTR (TREE_REALPART (arg));
7363       const REAL_VALUE_TYPE *imag = TREE_REAL_CST_PTR (TREE_IMAGPART (arg));
7364       
7365       if (real_isinf (real) || real_isinf (imag))
7366         return build_complex_cproj (type, imag->sign);
7367       else
7368         return arg;
7369     }
7370   else if (TREE_CODE (arg) == COMPLEX_EXPR)
7371     {
7372       tree real = TREE_OPERAND (arg, 0);
7373       tree imag = TREE_OPERAND (arg, 1);
7374
7375       STRIP_NOPS (real);
7376       STRIP_NOPS (imag);
7377       
7378       /* If the real part is inf and the imag part is known to be
7379          nonnegative, return (inf + 0i).  Remember side-effects are
7380          possible in the imag part.  */
7381       if (TREE_CODE (real) == REAL_CST
7382           && real_isinf (TREE_REAL_CST_PTR (real))
7383           && tree_expr_nonnegative_p (imag))
7384         return omit_one_operand_loc (loc, type,
7385                                      build_complex_cproj (type, false),
7386                                      arg);
7387       
7388       /* If the imag part is inf, return (inf+I*copysign(0,imag)).
7389          Remember side-effects are possible in the real part.  */
7390       if (TREE_CODE (imag) == REAL_CST
7391           && real_isinf (TREE_REAL_CST_PTR (imag)))
7392         return
7393           omit_one_operand_loc (loc, type,
7394                                 build_complex_cproj (type, TREE_REAL_CST_PTR
7395                                                      (imag)->sign), arg);
7396     }
7397
7398   return NULL_TREE;
7399 }
7400
7401 /* Fold a builtin function call to sqrt, sqrtf, or sqrtl with argument ARG.
7402    Return NULL_TREE if no simplification can be made.  */
7403
7404 static tree
7405 fold_builtin_sqrt (location_t loc, tree arg, tree type)
7406 {
7407
7408   enum built_in_function fcode;
7409   tree res;
7410
7411   if (!validate_arg (arg, REAL_TYPE))
7412     return NULL_TREE;
7413
7414   /* Calculate the result when the argument is a constant.  */
7415   if ((res = do_mpfr_arg1 (arg, type, mpfr_sqrt, &dconst0, NULL, true)))
7416     return res;
7417
7418   /* Optimize sqrt(expN(x)) = expN(x*0.5).  */
7419   fcode = builtin_mathfn_code (arg);
7420   if (flag_unsafe_math_optimizations && BUILTIN_EXPONENT_P (fcode))
7421     {
7422       tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7423       arg = fold_build2_loc (loc, MULT_EXPR, type,
7424                          CALL_EXPR_ARG (arg, 0),
7425                          build_real (type, dconsthalf));
7426       return build_call_expr_loc (loc, expfn, 1, arg);
7427     }
7428
7429   /* Optimize sqrt(Nroot(x)) -> pow(x,1/(2*N)).  */
7430   if (flag_unsafe_math_optimizations && BUILTIN_ROOT_P (fcode))
7431     {
7432       tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7433
7434       if (powfn)
7435         {
7436           tree arg0 = CALL_EXPR_ARG (arg, 0);
7437           tree tree_root;
7438           /* The inner root was either sqrt or cbrt.  */
7439           /* This was a conditional expression but it triggered a bug
7440              in Sun C 5.5.  */
7441           REAL_VALUE_TYPE dconstroot;
7442           if (BUILTIN_SQRT_P (fcode))
7443             dconstroot = dconsthalf;
7444           else
7445             dconstroot = dconst_third ();
7446
7447           /* Adjust for the outer root.  */
7448           SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
7449           dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7450           tree_root = build_real (type, dconstroot);
7451           return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7452         }
7453     }
7454
7455   /* Optimize sqrt(pow(x,y)) = pow(|x|,y*0.5).  */
7456   if (flag_unsafe_math_optimizations
7457       && (fcode == BUILT_IN_POW
7458           || fcode == BUILT_IN_POWF
7459           || fcode == BUILT_IN_POWL))
7460     {
7461       tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7462       tree arg0 = CALL_EXPR_ARG (arg, 0);
7463       tree arg1 = CALL_EXPR_ARG (arg, 1);
7464       tree narg1;
7465       if (!tree_expr_nonnegative_p (arg0))
7466         arg0 = build1 (ABS_EXPR, type, arg0);
7467       narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
7468                            build_real (type, dconsthalf));
7469       return build_call_expr_loc (loc, powfn, 2, arg0, narg1);
7470     }
7471
7472   return NULL_TREE;
7473 }
7474
7475 /* Fold a builtin function call to cbrt, cbrtf, or cbrtl with argument ARG.
7476    Return NULL_TREE if no simplification can be made.  */
7477
7478 static tree
7479 fold_builtin_cbrt (location_t loc, tree arg, tree type)
7480 {
7481   const enum built_in_function fcode = builtin_mathfn_code (arg);
7482   tree res;
7483
7484   if (!validate_arg (arg, REAL_TYPE))
7485     return NULL_TREE;
7486
7487   /* Calculate the result when the argument is a constant.  */
7488   if ((res = do_mpfr_arg1 (arg, type, mpfr_cbrt, NULL, NULL, 0)))
7489     return res;
7490
7491   if (flag_unsafe_math_optimizations)
7492     {
7493       /* Optimize cbrt(expN(x)) -> expN(x/3).  */
7494       if (BUILTIN_EXPONENT_P (fcode))
7495         {
7496           tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7497           const REAL_VALUE_TYPE third_trunc =
7498             real_value_truncate (TYPE_MODE (type), dconst_third ());
7499           arg = fold_build2_loc (loc, MULT_EXPR, type,
7500                              CALL_EXPR_ARG (arg, 0),
7501                              build_real (type, third_trunc));
7502           return build_call_expr_loc (loc, expfn, 1, arg);
7503         }
7504
7505       /* Optimize cbrt(sqrt(x)) -> pow(x,1/6).  */
7506       if (BUILTIN_SQRT_P (fcode))
7507         {
7508           tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7509
7510           if (powfn)
7511             {
7512               tree arg0 = CALL_EXPR_ARG (arg, 0);
7513               tree tree_root;
7514               REAL_VALUE_TYPE dconstroot = dconst_third ();
7515
7516               SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
7517               dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7518               tree_root = build_real (type, dconstroot);
7519               return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7520             }
7521         }
7522
7523       /* Optimize cbrt(cbrt(x)) -> pow(x,1/9) iff x is nonnegative.  */
7524       if (BUILTIN_CBRT_P (fcode))
7525         {
7526           tree arg0 = CALL_EXPR_ARG (arg, 0);
7527           if (tree_expr_nonnegative_p (arg0))
7528             {
7529               tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7530
7531               if (powfn)
7532                 {
7533                   tree tree_root;
7534                   REAL_VALUE_TYPE dconstroot;
7535
7536                   real_arithmetic (&dconstroot, MULT_EXPR,
7537                                    dconst_third_ptr (), dconst_third_ptr ());
7538                   dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7539                   tree_root = build_real (type, dconstroot);
7540                   return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7541                 }
7542             }
7543         }
7544
7545       /* Optimize cbrt(pow(x,y)) -> pow(x,y/3) iff x is nonnegative.  */
7546       if (fcode == BUILT_IN_POW
7547           || fcode == BUILT_IN_POWF
7548           || fcode == BUILT_IN_POWL)
7549         {
7550           tree arg00 = CALL_EXPR_ARG (arg, 0);
7551           tree arg01 = CALL_EXPR_ARG (arg, 1);
7552           if (tree_expr_nonnegative_p (arg00))
7553             {
7554               tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7555               const REAL_VALUE_TYPE dconstroot
7556                 = real_value_truncate (TYPE_MODE (type), dconst_third ());
7557               tree narg01 = fold_build2_loc (loc, MULT_EXPR, type, arg01,
7558                                          build_real (type, dconstroot));
7559               return build_call_expr_loc (loc, powfn, 2, arg00, narg01);
7560             }
7561         }
7562     }
7563   return NULL_TREE;
7564 }
7565
7566 /* Fold function call to builtin cos, cosf, or cosl with argument ARG.
7567    TYPE is the type of the return value.  Return NULL_TREE if no
7568    simplification can be made.  */
7569
7570 static tree
7571 fold_builtin_cos (location_t loc,
7572                   tree arg, tree type, tree fndecl)
7573 {
7574   tree res, narg;
7575
7576   if (!validate_arg (arg, REAL_TYPE))
7577     return NULL_TREE;
7578
7579   /* Calculate the result when the argument is a constant.  */
7580   if ((res = do_mpfr_arg1 (arg, type, mpfr_cos, NULL, NULL, 0)))
7581     return res;
7582
7583   /* Optimize cos(-x) into cos (x).  */
7584   if ((narg = fold_strip_sign_ops (arg)))
7585     return build_call_expr_loc (loc, fndecl, 1, narg);
7586
7587   return NULL_TREE;
7588 }
7589
7590 /* Fold function call to builtin cosh, coshf, or coshl with argument ARG.
7591    Return NULL_TREE if no simplification can be made.  */
7592
7593 static tree
7594 fold_builtin_cosh (location_t loc, tree arg, tree type, tree fndecl)
7595 {
7596   if (validate_arg (arg, REAL_TYPE))
7597     {
7598       tree res, narg;
7599
7600       /* Calculate the result when the argument is a constant.  */
7601       if ((res = do_mpfr_arg1 (arg, type, mpfr_cosh, NULL, NULL, 0)))
7602         return res;
7603
7604       /* Optimize cosh(-x) into cosh (x).  */
7605       if ((narg = fold_strip_sign_ops (arg)))
7606         return build_call_expr_loc (loc, fndecl, 1, narg);
7607     }
7608
7609   return NULL_TREE;
7610 }
7611
7612 /* Fold function call to builtin ccos (or ccosh if HYPER is TRUE) with
7613    argument ARG.  TYPE is the type of the return value.  Return
7614    NULL_TREE if no simplification can be made.  */
7615
7616 static tree
7617 fold_builtin_ccos (location_t loc, tree arg, tree type, tree fndecl,
7618                    bool hyper)
7619 {
7620   if (validate_arg (arg, COMPLEX_TYPE)
7621       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE)
7622     {
7623       tree tmp;
7624
7625       /* Calculate the result when the argument is a constant.  */
7626       if ((tmp = do_mpc_arg1 (arg, type, (hyper ? mpc_cosh : mpc_cos))))
7627         return tmp;
7628
7629       /* Optimize fn(-x) into fn(x).  */
7630       if ((tmp = fold_strip_sign_ops (arg)))
7631         return build_call_expr_loc (loc, fndecl, 1, tmp);
7632     }
7633
7634   return NULL_TREE;
7635 }
7636
7637 /* Fold function call to builtin tan, tanf, or tanl with argument ARG.
7638    Return NULL_TREE if no simplification can be made.  */
7639
7640 static tree
7641 fold_builtin_tan (tree arg, tree type)
7642 {
7643   enum built_in_function fcode;
7644   tree res;
7645
7646   if (!validate_arg (arg, REAL_TYPE))
7647     return NULL_TREE;
7648
7649   /* Calculate the result when the argument is a constant.  */
7650   if ((res = do_mpfr_arg1 (arg, type, mpfr_tan, NULL, NULL, 0)))
7651     return res;
7652
7653   /* Optimize tan(atan(x)) = x.  */
7654   fcode = builtin_mathfn_code (arg);
7655   if (flag_unsafe_math_optimizations
7656       && (fcode == BUILT_IN_ATAN
7657           || fcode == BUILT_IN_ATANF
7658           || fcode == BUILT_IN_ATANL))
7659     return CALL_EXPR_ARG (arg, 0);
7660
7661   return NULL_TREE;
7662 }
7663
7664 /* Fold function call to builtin sincos, sincosf, or sincosl.  Return
7665    NULL_TREE if no simplification can be made.  */
7666
7667 static tree
7668 fold_builtin_sincos (location_t loc,
7669                      tree arg0, tree arg1, tree arg2)
7670 {
7671   tree type;
7672   tree res, fn, call;
7673
7674   if (!validate_arg (arg0, REAL_TYPE)
7675       || !validate_arg (arg1, POINTER_TYPE)
7676       || !validate_arg (arg2, POINTER_TYPE))
7677     return NULL_TREE;
7678
7679   type = TREE_TYPE (arg0);
7680
7681   /* Calculate the result when the argument is a constant.  */
7682   if ((res = do_mpfr_sincos (arg0, arg1, arg2)))
7683     return res;
7684
7685   /* Canonicalize sincos to cexpi.  */
7686   if (!TARGET_C99_FUNCTIONS)
7687     return NULL_TREE;
7688   fn = mathfn_built_in (type, BUILT_IN_CEXPI);
7689   if (!fn)
7690     return NULL_TREE;
7691
7692   call = build_call_expr_loc (loc, fn, 1, arg0);
7693   call = builtin_save_expr (call);
7694
7695   return build2 (COMPOUND_EXPR, void_type_node,
7696                  build2 (MODIFY_EXPR, void_type_node,
7697                          build_fold_indirect_ref_loc (loc, arg1),
7698                          build1 (IMAGPART_EXPR, type, call)),
7699                  build2 (MODIFY_EXPR, void_type_node,
7700                          build_fold_indirect_ref_loc (loc, arg2),
7701                          build1 (REALPART_EXPR, type, call)));
7702 }
7703
7704 /* Fold function call to builtin cexp, cexpf, or cexpl.  Return
7705    NULL_TREE if no simplification can be made.  */
7706
7707 static tree
7708 fold_builtin_cexp (location_t loc, tree arg0, tree type)
7709 {
7710   tree rtype;
7711   tree realp, imagp, ifn;
7712   tree res;
7713
7714   if (!validate_arg (arg0, COMPLEX_TYPE)
7715       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) != REAL_TYPE)
7716     return NULL_TREE;
7717
7718   /* Calculate the result when the argument is a constant.  */
7719   if ((res = do_mpc_arg1 (arg0, type, mpc_exp)))
7720     return res;
7721
7722   rtype = TREE_TYPE (TREE_TYPE (arg0));
7723
7724   /* In case we can figure out the real part of arg0 and it is constant zero
7725      fold to cexpi.  */
7726   if (!TARGET_C99_FUNCTIONS)
7727     return NULL_TREE;
7728   ifn = mathfn_built_in (rtype, BUILT_IN_CEXPI);
7729   if (!ifn)
7730     return NULL_TREE;
7731
7732   if ((realp = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0))
7733       && real_zerop (realp))
7734     {
7735       tree narg = fold_build1_loc (loc, IMAGPART_EXPR, rtype, arg0);
7736       return build_call_expr_loc (loc, ifn, 1, narg);
7737     }
7738
7739   /* In case we can easily decompose real and imaginary parts split cexp
7740      to exp (r) * cexpi (i).  */
7741   if (flag_unsafe_math_optimizations
7742       && realp)
7743     {
7744       tree rfn, rcall, icall;
7745
7746       rfn = mathfn_built_in (rtype, BUILT_IN_EXP);
7747       if (!rfn)
7748         return NULL_TREE;
7749
7750       imagp = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
7751       if (!imagp)
7752         return NULL_TREE;
7753
7754       icall = build_call_expr_loc (loc, ifn, 1, imagp);
7755       icall = builtin_save_expr (icall);
7756       rcall = build_call_expr_loc (loc, rfn, 1, realp);
7757       rcall = builtin_save_expr (rcall);
7758       return fold_build2_loc (loc, COMPLEX_EXPR, type,
7759                           fold_build2_loc (loc, MULT_EXPR, rtype,
7760                                        rcall,
7761                                        fold_build1_loc (loc, REALPART_EXPR,
7762                                                     rtype, icall)),
7763                           fold_build2_loc (loc, MULT_EXPR, rtype,
7764                                        rcall,
7765                                        fold_build1_loc (loc, IMAGPART_EXPR,
7766                                                     rtype, icall)));
7767     }
7768
7769   return NULL_TREE;
7770 }
7771
7772 /* Fold function call to builtin trunc, truncf or truncl with argument ARG.
7773    Return NULL_TREE if no simplification can be made.  */
7774
7775 static tree
7776 fold_builtin_trunc (location_t loc, tree fndecl, tree arg)
7777 {
7778   if (!validate_arg (arg, REAL_TYPE))
7779     return NULL_TREE;
7780
7781   /* Optimize trunc of constant value.  */
7782   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7783     {
7784       REAL_VALUE_TYPE r, x;
7785       tree type = TREE_TYPE (TREE_TYPE (fndecl));
7786
7787       x = TREE_REAL_CST (arg);
7788       real_trunc (&r, TYPE_MODE (type), &x);
7789       return build_real (type, r);
7790     }
7791
7792   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7793 }
7794
7795 /* Fold function call to builtin floor, floorf or floorl with argument ARG.
7796    Return NULL_TREE if no simplification can be made.  */
7797
7798 static tree
7799 fold_builtin_floor (location_t loc, tree fndecl, tree arg)
7800 {
7801   if (!validate_arg (arg, REAL_TYPE))
7802     return NULL_TREE;
7803
7804   /* Optimize floor of constant value.  */
7805   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7806     {
7807       REAL_VALUE_TYPE x;
7808
7809       x = TREE_REAL_CST (arg);
7810       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7811         {
7812           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7813           REAL_VALUE_TYPE r;
7814
7815           real_floor (&r, TYPE_MODE (type), &x);
7816           return build_real (type, r);
7817         }
7818     }
7819
7820   /* Fold floor (x) where x is nonnegative to trunc (x).  */
7821   if (tree_expr_nonnegative_p (arg))
7822     {
7823       tree truncfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_TRUNC);
7824       if (truncfn)
7825         return build_call_expr_loc (loc, truncfn, 1, arg);
7826     }
7827
7828   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7829 }
7830
7831 /* Fold function call to builtin ceil, ceilf or ceill with argument ARG.
7832    Return NULL_TREE if no simplification can be made.  */
7833
7834 static tree
7835 fold_builtin_ceil (location_t loc, tree fndecl, tree arg)
7836 {
7837   if (!validate_arg (arg, REAL_TYPE))
7838     return NULL_TREE;
7839
7840   /* Optimize ceil of constant value.  */
7841   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7842     {
7843       REAL_VALUE_TYPE x;
7844
7845       x = TREE_REAL_CST (arg);
7846       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7847         {
7848           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7849           REAL_VALUE_TYPE r;
7850
7851           real_ceil (&r, TYPE_MODE (type), &x);
7852           return build_real (type, r);
7853         }
7854     }
7855
7856   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7857 }
7858
7859 /* Fold function call to builtin round, roundf or roundl with argument ARG.
7860    Return NULL_TREE if no simplification can be made.  */
7861
7862 static tree
7863 fold_builtin_round (location_t loc, tree fndecl, tree arg)
7864 {
7865   if (!validate_arg (arg, REAL_TYPE))
7866     return NULL_TREE;
7867
7868   /* Optimize round of constant value.  */
7869   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7870     {
7871       REAL_VALUE_TYPE x;
7872
7873       x = TREE_REAL_CST (arg);
7874       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7875         {
7876           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7877           REAL_VALUE_TYPE r;
7878
7879           real_round (&r, TYPE_MODE (type), &x);
7880           return build_real (type, r);
7881         }
7882     }
7883
7884   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7885 }
7886
7887 /* Fold function call to builtin lround, lroundf or lroundl (or the
7888    corresponding long long versions) and other rounding functions.  ARG
7889    is the argument to the call.  Return NULL_TREE if no simplification
7890    can be made.  */
7891
7892 static tree
7893 fold_builtin_int_roundingfn (location_t loc, tree fndecl, tree arg)
7894 {
7895   if (!validate_arg (arg, REAL_TYPE))
7896     return NULL_TREE;
7897
7898   /* Optimize lround of constant value.  */
7899   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7900     {
7901       const REAL_VALUE_TYPE x = TREE_REAL_CST (arg);
7902
7903       if (real_isfinite (&x))
7904         {
7905           tree itype = TREE_TYPE (TREE_TYPE (fndecl));
7906           tree ftype = TREE_TYPE (arg);
7907           double_int val;
7908           REAL_VALUE_TYPE r;
7909
7910           switch (DECL_FUNCTION_CODE (fndecl))
7911             {
7912             CASE_FLT_FN (BUILT_IN_IFLOOR):
7913             CASE_FLT_FN (BUILT_IN_LFLOOR):
7914             CASE_FLT_FN (BUILT_IN_LLFLOOR):
7915               real_floor (&r, TYPE_MODE (ftype), &x);
7916               break;
7917
7918             CASE_FLT_FN (BUILT_IN_ICEIL):
7919             CASE_FLT_FN (BUILT_IN_LCEIL):
7920             CASE_FLT_FN (BUILT_IN_LLCEIL):
7921               real_ceil (&r, TYPE_MODE (ftype), &x);
7922               break;
7923
7924             CASE_FLT_FN (BUILT_IN_IROUND):
7925             CASE_FLT_FN (BUILT_IN_LROUND):
7926             CASE_FLT_FN (BUILT_IN_LLROUND):
7927               real_round (&r, TYPE_MODE (ftype), &x);
7928               break;
7929
7930             default:
7931               gcc_unreachable ();
7932             }
7933
7934           real_to_integer2 ((HOST_WIDE_INT *)&val.low, &val.high, &r);
7935           if (double_int_fits_to_tree_p (itype, val))
7936             return double_int_to_tree (itype, val);
7937         }
7938     }
7939
7940   switch (DECL_FUNCTION_CODE (fndecl))
7941     {
7942     CASE_FLT_FN (BUILT_IN_LFLOOR):
7943     CASE_FLT_FN (BUILT_IN_LLFLOOR):
7944       /* Fold lfloor (x) where x is nonnegative to FIX_TRUNC (x).  */
7945       if (tree_expr_nonnegative_p (arg))
7946         return fold_build1_loc (loc, FIX_TRUNC_EXPR,
7947                             TREE_TYPE (TREE_TYPE (fndecl)), arg);
7948       break;
7949     default:;
7950     }
7951
7952   return fold_fixed_mathfn (loc, fndecl, arg);
7953 }
7954
7955 /* Fold function call to builtin ffs, clz, ctz, popcount and parity
7956    and their long and long long variants (i.e. ffsl and ffsll).  ARG is
7957    the argument to the call.  Return NULL_TREE if no simplification can
7958    be made.  */
7959
7960 static tree
7961 fold_builtin_bitop (tree fndecl, tree arg)
7962 {
7963   if (!validate_arg (arg, INTEGER_TYPE))
7964     return NULL_TREE;
7965
7966   /* Optimize for constant argument.  */
7967   if (TREE_CODE (arg) == INTEGER_CST && !TREE_OVERFLOW (arg))
7968     {
7969       HOST_WIDE_INT hi, width, result;
7970       unsigned HOST_WIDE_INT lo;
7971       tree type;
7972
7973       type = TREE_TYPE (arg);
7974       width = TYPE_PRECISION (type);
7975       lo = TREE_INT_CST_LOW (arg);
7976
7977       /* Clear all the bits that are beyond the type's precision.  */
7978       if (width > HOST_BITS_PER_WIDE_INT)
7979         {
7980           hi = TREE_INT_CST_HIGH (arg);
7981           if (width < 2 * HOST_BITS_PER_WIDE_INT)
7982             hi &= ~((unsigned HOST_WIDE_INT) (-1)
7983                     << (width - HOST_BITS_PER_WIDE_INT));
7984         }
7985       else
7986         {
7987           hi = 0;
7988           if (width < HOST_BITS_PER_WIDE_INT)
7989             lo &= ~((unsigned HOST_WIDE_INT) (-1) << width);
7990         }
7991
7992       switch (DECL_FUNCTION_CODE (fndecl))
7993         {
7994         CASE_INT_FN (BUILT_IN_FFS):
7995           if (lo != 0)
7996             result = ffs_hwi (lo);
7997           else if (hi != 0)
7998             result = HOST_BITS_PER_WIDE_INT + ffs_hwi (hi);
7999           else
8000             result = 0;
8001           break;
8002
8003         CASE_INT_FN (BUILT_IN_CLZ):
8004           if (hi != 0)
8005             result = width - floor_log2 (hi) - 1 - HOST_BITS_PER_WIDE_INT;
8006           else if (lo != 0)
8007             result = width - floor_log2 (lo) - 1;
8008           else if (! CLZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
8009             result = width;
8010           break;
8011
8012         CASE_INT_FN (BUILT_IN_CTZ):
8013           if (lo != 0)
8014             result = ctz_hwi (lo);
8015           else if (hi != 0)
8016             result = HOST_BITS_PER_WIDE_INT + ctz_hwi (hi);
8017           else if (! CTZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
8018             result = width;
8019           break;
8020
8021         CASE_INT_FN (BUILT_IN_CLRSB):
8022           if (width > HOST_BITS_PER_WIDE_INT
8023               && (hi & ((unsigned HOST_WIDE_INT) 1
8024                         << (width - HOST_BITS_PER_WIDE_INT - 1))) != 0)
8025             {
8026               hi = ~hi & ~((unsigned HOST_WIDE_INT) (-1)
8027                            << (width - HOST_BITS_PER_WIDE_INT - 1));
8028               lo = ~lo;
8029             }
8030           else if (width <= HOST_BITS_PER_WIDE_INT
8031                    && (lo & ((unsigned HOST_WIDE_INT) 1 << (width - 1))) != 0)
8032             lo = ~lo & ~((unsigned HOST_WIDE_INT) (-1) << (width - 1));
8033           if (hi != 0)
8034             result = width - floor_log2 (hi) - 2 - HOST_BITS_PER_WIDE_INT;
8035           else if (lo != 0)
8036             result = width - floor_log2 (lo) - 2;
8037           else
8038             result = width - 1;
8039           break;
8040
8041         CASE_INT_FN (BUILT_IN_POPCOUNT):
8042           result = 0;
8043           while (lo)
8044             result++, lo &= lo - 1;
8045           while (hi)
8046             result++, hi &= (unsigned HOST_WIDE_INT) hi - 1;
8047           break;
8048
8049         CASE_INT_FN (BUILT_IN_PARITY):
8050           result = 0;
8051           while (lo)
8052             result++, lo &= lo - 1;
8053           while (hi)
8054             result++, hi &= (unsigned HOST_WIDE_INT) hi - 1;
8055           result &= 1;
8056           break;
8057
8058         default:
8059           gcc_unreachable ();
8060         }
8061
8062       return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), result);
8063     }
8064
8065   return NULL_TREE;
8066 }
8067
8068 /* Fold function call to builtin_bswap and the long and long long
8069    variants.  Return NULL_TREE if no simplification can be made.  */
8070 static tree
8071 fold_builtin_bswap (tree fndecl, tree arg)
8072 {
8073   if (! validate_arg (arg, INTEGER_TYPE))
8074     return NULL_TREE;
8075
8076   /* Optimize constant value.  */
8077   if (TREE_CODE (arg) == INTEGER_CST && !TREE_OVERFLOW (arg))
8078     {
8079       HOST_WIDE_INT hi, width, r_hi = 0;
8080       unsigned HOST_WIDE_INT lo, r_lo = 0;
8081       tree type;
8082
8083       type = TREE_TYPE (arg);
8084       width = TYPE_PRECISION (type);
8085       lo = TREE_INT_CST_LOW (arg);
8086       hi = TREE_INT_CST_HIGH (arg);
8087
8088       switch (DECL_FUNCTION_CODE (fndecl))
8089         {
8090           case BUILT_IN_BSWAP32:
8091           case BUILT_IN_BSWAP64:
8092             {
8093               int s;
8094
8095               for (s = 0; s < width; s += 8)
8096                 {
8097                   int d = width - s - 8;
8098                   unsigned HOST_WIDE_INT byte;
8099
8100                   if (s < HOST_BITS_PER_WIDE_INT)
8101                     byte = (lo >> s) & 0xff;
8102                   else
8103                     byte = (hi >> (s - HOST_BITS_PER_WIDE_INT)) & 0xff;
8104
8105                   if (d < HOST_BITS_PER_WIDE_INT)
8106                     r_lo |= byte << d;
8107                   else
8108                     r_hi |= byte << (d - HOST_BITS_PER_WIDE_INT);
8109                 }
8110             }
8111
8112             break;
8113
8114         default:
8115           gcc_unreachable ();
8116         }
8117
8118       if (width < HOST_BITS_PER_WIDE_INT)
8119         return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), r_lo);
8120       else
8121         return build_int_cst_wide (TREE_TYPE (TREE_TYPE (fndecl)), r_lo, r_hi);
8122     }
8123
8124   return NULL_TREE;
8125 }
8126
8127 /* A subroutine of fold_builtin to fold the various logarithmic
8128    functions.  Return NULL_TREE if no simplification can me made.
8129    FUNC is the corresponding MPFR logarithm function.  */
8130
8131 static tree
8132 fold_builtin_logarithm (location_t loc, tree fndecl, tree arg,
8133                         int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t))
8134 {
8135   if (validate_arg (arg, REAL_TYPE))
8136     {
8137       tree type = TREE_TYPE (TREE_TYPE (fndecl));
8138       tree res;
8139       const enum built_in_function fcode = builtin_mathfn_code (arg);
8140
8141       /* Calculate the result when the argument is a constant.  */
8142       if ((res = do_mpfr_arg1 (arg, type, func, &dconst0, NULL, false)))
8143         return res;
8144
8145       /* Special case, optimize logN(expN(x)) = x.  */
8146       if (flag_unsafe_math_optimizations
8147           && ((func == mpfr_log
8148                && (fcode == BUILT_IN_EXP
8149                    || fcode == BUILT_IN_EXPF
8150                    || fcode == BUILT_IN_EXPL))
8151               || (func == mpfr_log2
8152                   && (fcode == BUILT_IN_EXP2
8153                       || fcode == BUILT_IN_EXP2F
8154                       || fcode == BUILT_IN_EXP2L))
8155               || (func == mpfr_log10 && (BUILTIN_EXP10_P (fcode)))))
8156         return fold_convert_loc (loc, type, CALL_EXPR_ARG (arg, 0));
8157
8158       /* Optimize logN(func()) for various exponential functions.  We
8159          want to determine the value "x" and the power "exponent" in
8160          order to transform logN(x**exponent) into exponent*logN(x).  */
8161       if (flag_unsafe_math_optimizations)
8162         {
8163           tree exponent = 0, x = 0;
8164
8165           switch (fcode)
8166           {
8167           CASE_FLT_FN (BUILT_IN_EXP):
8168             /* Prepare to do logN(exp(exponent) -> exponent*logN(e).  */
8169             x = build_real (type, real_value_truncate (TYPE_MODE (type),
8170                                                        dconst_e ()));
8171             exponent = CALL_EXPR_ARG (arg, 0);
8172             break;
8173           CASE_FLT_FN (BUILT_IN_EXP2):
8174             /* Prepare to do logN(exp2(exponent) -> exponent*logN(2).  */
8175             x = build_real (type, dconst2);
8176             exponent = CALL_EXPR_ARG (arg, 0);
8177             break;
8178           CASE_FLT_FN (BUILT_IN_EXP10):
8179           CASE_FLT_FN (BUILT_IN_POW10):
8180             /* Prepare to do logN(exp10(exponent) -> exponent*logN(10).  */
8181             {
8182               REAL_VALUE_TYPE dconst10;
8183               real_from_integer (&dconst10, VOIDmode, 10, 0, 0);
8184               x = build_real (type, dconst10);
8185             }
8186             exponent = CALL_EXPR_ARG (arg, 0);
8187             break;
8188           CASE_FLT_FN (BUILT_IN_SQRT):
8189             /* Prepare to do logN(sqrt(x) -> 0.5*logN(x).  */
8190             x = CALL_EXPR_ARG (arg, 0);
8191             exponent = build_real (type, dconsthalf);
8192             break;
8193           CASE_FLT_FN (BUILT_IN_CBRT):
8194             /* Prepare to do logN(cbrt(x) -> (1/3)*logN(x).  */
8195             x = CALL_EXPR_ARG (arg, 0);
8196             exponent = build_real (type, real_value_truncate (TYPE_MODE (type),
8197                                                               dconst_third ()));
8198             break;
8199           CASE_FLT_FN (BUILT_IN_POW):
8200             /* Prepare to do logN(pow(x,exponent) -> exponent*logN(x).  */
8201             x = CALL_EXPR_ARG (arg, 0);
8202             exponent = CALL_EXPR_ARG (arg, 1);
8203             break;
8204           default:
8205             break;
8206           }
8207
8208           /* Now perform the optimization.  */
8209           if (x && exponent)
8210             {
8211               tree logfn = build_call_expr_loc (loc, fndecl, 1, x);
8212               return fold_build2_loc (loc, MULT_EXPR, type, exponent, logfn);
8213             }
8214         }
8215     }
8216
8217   return NULL_TREE;
8218 }
8219
8220 /* Fold a builtin function call to hypot, hypotf, or hypotl.  Return
8221    NULL_TREE if no simplification can be made.  */
8222
8223 static tree
8224 fold_builtin_hypot (location_t loc, tree fndecl,
8225                     tree arg0, tree arg1, tree type)
8226 {
8227   tree res, narg0, narg1;
8228
8229   if (!validate_arg (arg0, REAL_TYPE)
8230       || !validate_arg (arg1, REAL_TYPE))
8231     return NULL_TREE;
8232
8233   /* Calculate the result when the argument is a constant.  */
8234   if ((res = do_mpfr_arg2 (arg0, arg1, type, mpfr_hypot)))
8235     return res;
8236
8237   /* If either argument to hypot has a negate or abs, strip that off.
8238      E.g. hypot(-x,fabs(y)) -> hypot(x,y).  */
8239   narg0 = fold_strip_sign_ops (arg0);
8240   narg1 = fold_strip_sign_ops (arg1);
8241   if (narg0 || narg1)
8242     {
8243       return build_call_expr_loc (loc, fndecl, 2, narg0 ? narg0 : arg0,
8244                               narg1 ? narg1 : arg1);
8245     }
8246
8247   /* If either argument is zero, hypot is fabs of the other.  */
8248   if (real_zerop (arg0))
8249     return fold_build1_loc (loc, ABS_EXPR, type, arg1);
8250   else if (real_zerop (arg1))
8251     return fold_build1_loc (loc, ABS_EXPR, type, arg0);
8252
8253   /* hypot(x,x) -> fabs(x)*sqrt(2).  */
8254   if (flag_unsafe_math_optimizations
8255       && operand_equal_p (arg0, arg1, OEP_PURE_SAME))
8256     {
8257       const REAL_VALUE_TYPE sqrt2_trunc
8258         = real_value_truncate (TYPE_MODE (type), dconst_sqrt2 ());
8259       return fold_build2_loc (loc, MULT_EXPR, type,
8260                           fold_build1_loc (loc, ABS_EXPR, type, arg0),
8261                           build_real (type, sqrt2_trunc));
8262     }
8263
8264   return NULL_TREE;
8265 }
8266
8267
8268 /* Fold a builtin function call to pow, powf, or powl.  Return
8269    NULL_TREE if no simplification can be made.  */
8270 static tree
8271 fold_builtin_pow (location_t loc, tree fndecl, tree arg0, tree arg1, tree type)
8272 {
8273   tree res;
8274
8275   if (!validate_arg (arg0, REAL_TYPE)
8276        || !validate_arg (arg1, REAL_TYPE))
8277     return NULL_TREE;
8278
8279   /* Calculate the result when the argument is a constant.  */
8280   if ((res = do_mpfr_arg2 (arg0, arg1, type, mpfr_pow)))
8281     return res;
8282
8283   /* Optimize pow(1.0,y) = 1.0.  */
8284   if (real_onep (arg0))
8285     return omit_one_operand_loc (loc, type, build_real (type, dconst1), arg1);
8286
8287   if (TREE_CODE (arg1) == REAL_CST
8288       && !TREE_OVERFLOW (arg1))
8289     {
8290       REAL_VALUE_TYPE cint;
8291       REAL_VALUE_TYPE c;
8292       HOST_WIDE_INT n;
8293
8294       c = TREE_REAL_CST (arg1);
8295
8296       /* Optimize pow(x,0.0) = 1.0.  */
8297       if (REAL_VALUES_EQUAL (c, dconst0))
8298         return omit_one_operand_loc (loc, type, build_real (type, dconst1),
8299                                  arg0);
8300
8301       /* Optimize pow(x,1.0) = x.  */
8302       if (REAL_VALUES_EQUAL (c, dconst1))
8303         return arg0;
8304
8305       /* Optimize pow(x,-1.0) = 1.0/x.  */
8306       if (REAL_VALUES_EQUAL (c, dconstm1))
8307         return fold_build2_loc (loc, RDIV_EXPR, type,
8308                             build_real (type, dconst1), arg0);
8309
8310       /* Optimize pow(x,0.5) = sqrt(x).  */
8311       if (flag_unsafe_math_optimizations
8312           && REAL_VALUES_EQUAL (c, dconsthalf))
8313         {
8314           tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
8315
8316           if (sqrtfn != NULL_TREE)
8317             return build_call_expr_loc (loc, sqrtfn, 1, arg0);
8318         }
8319
8320       /* Optimize pow(x,1.0/3.0) = cbrt(x).  */
8321       if (flag_unsafe_math_optimizations)
8322         {
8323           const REAL_VALUE_TYPE dconstroot
8324             = real_value_truncate (TYPE_MODE (type), dconst_third ());
8325
8326           if (REAL_VALUES_EQUAL (c, dconstroot))
8327             {
8328               tree cbrtfn = mathfn_built_in (type, BUILT_IN_CBRT);
8329               if (cbrtfn != NULL_TREE)
8330                 return build_call_expr_loc (loc, cbrtfn, 1, arg0);
8331             }
8332         }
8333
8334       /* Check for an integer exponent.  */
8335       n = real_to_integer (&c);
8336       real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
8337       if (real_identical (&c, &cint))
8338         {
8339           /* Attempt to evaluate pow at compile-time, unless this should
8340              raise an exception.  */
8341           if (TREE_CODE (arg0) == REAL_CST
8342               && !TREE_OVERFLOW (arg0)
8343               && (n > 0
8344                   || (!flag_trapping_math && !flag_errno_math)
8345                   || !REAL_VALUES_EQUAL (TREE_REAL_CST (arg0), dconst0)))
8346             {
8347               REAL_VALUE_TYPE x;
8348               bool inexact;
8349
8350               x = TREE_REAL_CST (arg0);
8351               inexact = real_powi (&x, TYPE_MODE (type), &x, n);
8352               if (flag_unsafe_math_optimizations || !inexact)
8353                 return build_real (type, x);
8354             }
8355
8356           /* Strip sign ops from even integer powers.  */
8357           if ((n & 1) == 0 && flag_unsafe_math_optimizations)
8358             {
8359               tree narg0 = fold_strip_sign_ops (arg0);
8360               if (narg0)
8361                 return build_call_expr_loc (loc, fndecl, 2, narg0, arg1);
8362             }
8363         }
8364     }
8365
8366   if (flag_unsafe_math_optimizations)
8367     {
8368       const enum built_in_function fcode = builtin_mathfn_code (arg0);
8369
8370       /* Optimize pow(expN(x),y) = expN(x*y).  */
8371       if (BUILTIN_EXPONENT_P (fcode))
8372         {
8373           tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
8374           tree arg = CALL_EXPR_ARG (arg0, 0);
8375           arg = fold_build2_loc (loc, MULT_EXPR, type, arg, arg1);
8376           return build_call_expr_loc (loc, expfn, 1, arg);
8377         }
8378
8379       /* Optimize pow(sqrt(x),y) = pow(x,y*0.5).  */
8380       if (BUILTIN_SQRT_P (fcode))
8381         {
8382           tree narg0 = CALL_EXPR_ARG (arg0, 0);
8383           tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
8384                                     build_real (type, dconsthalf));
8385           return build_call_expr_loc (loc, fndecl, 2, narg0, narg1);
8386         }
8387
8388       /* Optimize pow(cbrt(x),y) = pow(x,y/3) iff x is nonnegative.  */
8389       if (BUILTIN_CBRT_P (fcode))
8390         {
8391           tree arg = CALL_EXPR_ARG (arg0, 0);
8392           if (tree_expr_nonnegative_p (arg))
8393             {
8394               const REAL_VALUE_TYPE dconstroot
8395                 = real_value_truncate (TYPE_MODE (type), dconst_third ());
8396               tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
8397                                         build_real (type, dconstroot));
8398               return build_call_expr_loc (loc, fndecl, 2, arg, narg1);
8399             }
8400         }
8401
8402       /* Optimize pow(pow(x,y),z) = pow(x,y*z) iff x is nonnegative.  */
8403       if (fcode == BUILT_IN_POW
8404           || fcode == BUILT_IN_POWF
8405           || fcode == BUILT_IN_POWL)
8406         {
8407           tree arg00 = CALL_EXPR_ARG (arg0, 0);
8408           if (tree_expr_nonnegative_p (arg00))
8409             {
8410               tree arg01 = CALL_EXPR_ARG (arg0, 1);
8411               tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg01, arg1);
8412               return build_call_expr_loc (loc, fndecl, 2, arg00, narg1);
8413             }
8414         }
8415     }
8416
8417   return NULL_TREE;
8418 }
8419
8420 /* Fold a builtin function call to powi, powif, or powil with argument ARG.
8421    Return NULL_TREE if no simplification can be made.  */
8422 static tree
8423 fold_builtin_powi (location_t loc, tree fndecl ATTRIBUTE_UNUSED,
8424                    tree arg0, tree arg1, tree type)
8425 {
8426   if (!validate_arg (arg0, REAL_TYPE)
8427       || !validate_arg (arg1, INTEGER_TYPE))
8428     return NULL_TREE;
8429
8430   /* Optimize pow(1.0,y) = 1.0.  */
8431   if (real_onep (arg0))
8432     return omit_one_operand_loc (loc, type, build_real (type, dconst1), arg1);
8433
8434   if (host_integerp (arg1, 0))
8435     {
8436       HOST_WIDE_INT c = TREE_INT_CST_LOW (arg1);
8437
8438       /* Evaluate powi at compile-time.  */
8439       if (TREE_CODE (arg0) == REAL_CST
8440           && !TREE_OVERFLOW (arg0))
8441         {
8442           REAL_VALUE_TYPE x;
8443           x = TREE_REAL_CST (arg0);
8444           real_powi (&x, TYPE_MODE (type), &x, c);
8445           return build_real (type, x);
8446         }
8447
8448       /* Optimize pow(x,0) = 1.0.  */
8449       if (c == 0)
8450         return omit_one_operand_loc (loc, type, build_real (type, dconst1),
8451                                  arg0);
8452
8453       /* Optimize pow(x,1) = x.  */
8454       if (c == 1)
8455         return arg0;
8456
8457       /* Optimize pow(x,-1) = 1.0/x.  */
8458       if (c == -1)
8459         return fold_build2_loc (loc, RDIV_EXPR, type,
8460                            build_real (type, dconst1), arg0);
8461     }
8462
8463   return NULL_TREE;
8464 }
8465
8466 /* A subroutine of fold_builtin to fold the various exponent
8467    functions.  Return NULL_TREE if no simplification can be made.
8468    FUNC is the corresponding MPFR exponent function.  */
8469
8470 static tree
8471 fold_builtin_exponent (location_t loc, tree fndecl, tree arg,
8472                        int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t))
8473 {
8474   if (validate_arg (arg, REAL_TYPE))
8475     {
8476       tree type = TREE_TYPE (TREE_TYPE (fndecl));
8477       tree res;
8478
8479       /* Calculate the result when the argument is a constant.  */
8480       if ((res = do_mpfr_arg1 (arg, type, func, NULL, NULL, 0)))
8481         return res;
8482
8483       /* Optimize expN(logN(x)) = x.  */
8484       if (flag_unsafe_math_optimizations)
8485         {
8486           const enum built_in_function fcode = builtin_mathfn_code (arg);
8487
8488           if ((func == mpfr_exp
8489                && (fcode == BUILT_IN_LOG
8490                    || fcode == BUILT_IN_LOGF
8491                    || fcode == BUILT_IN_LOGL))
8492               || (func == mpfr_exp2
8493                   && (fcode == BUILT_IN_LOG2
8494                       || fcode == BUILT_IN_LOG2F
8495                       || fcode == BUILT_IN_LOG2L))
8496               || (func == mpfr_exp10
8497                   && (fcode == BUILT_IN_LOG10
8498                       || fcode == BUILT_IN_LOG10F
8499                       || fcode == BUILT_IN_LOG10L)))
8500             return fold_convert_loc (loc, type, CALL_EXPR_ARG (arg, 0));
8501         }
8502     }
8503
8504   return NULL_TREE;
8505 }
8506
8507 /* Return true if VAR is a VAR_DECL or a component thereof.  */
8508
8509 static bool
8510 var_decl_component_p (tree var)
8511 {
8512   tree inner = var;
8513   while (handled_component_p (inner))
8514     inner = TREE_OPERAND (inner, 0);
8515   return SSA_VAR_P (inner);
8516 }
8517
8518 /* Fold function call to builtin memset.  Return
8519    NULL_TREE if no simplification can be made.  */
8520
8521 static tree
8522 fold_builtin_memset (location_t loc, tree dest, tree c, tree len,
8523                      tree type, bool ignore)
8524 {
8525   tree var, ret, etype;
8526   unsigned HOST_WIDE_INT length, cval;
8527
8528   if (! validate_arg (dest, POINTER_TYPE)
8529       || ! validate_arg (c, INTEGER_TYPE)
8530       || ! validate_arg (len, INTEGER_TYPE))
8531     return NULL_TREE;
8532
8533   if (! host_integerp (len, 1))
8534     return NULL_TREE;
8535
8536   /* If the LEN parameter is zero, return DEST.  */
8537   if (integer_zerop (len))
8538     return omit_one_operand_loc (loc, type, dest, c);
8539
8540   if (TREE_CODE (c) != INTEGER_CST || TREE_SIDE_EFFECTS (dest))
8541     return NULL_TREE;
8542
8543   var = dest;
8544   STRIP_NOPS (var);
8545   if (TREE_CODE (var) != ADDR_EXPR)
8546     return NULL_TREE;
8547
8548   var = TREE_OPERAND (var, 0);
8549   if (TREE_THIS_VOLATILE (var))
8550     return NULL_TREE;
8551
8552   etype = TREE_TYPE (var);
8553   if (TREE_CODE (etype) == ARRAY_TYPE)
8554     etype = TREE_TYPE (etype);
8555
8556   if (!INTEGRAL_TYPE_P (etype)
8557       && !POINTER_TYPE_P (etype))
8558     return NULL_TREE;
8559
8560   if (! var_decl_component_p (var))
8561     return NULL_TREE;
8562
8563   length = tree_low_cst (len, 1);
8564   if (GET_MODE_SIZE (TYPE_MODE (etype)) != length
8565       || get_pointer_alignment (dest) / BITS_PER_UNIT < length)
8566     return NULL_TREE;
8567
8568   if (length > HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT)
8569     return NULL_TREE;
8570
8571   if (integer_zerop (c))
8572     cval = 0;
8573   else
8574     {
8575       if (CHAR_BIT != 8 || BITS_PER_UNIT != 8 || HOST_BITS_PER_WIDE_INT > 64)
8576         return NULL_TREE;
8577
8578       cval = TREE_INT_CST_LOW (c);
8579       cval &= 0xff;
8580       cval |= cval << 8;
8581       cval |= cval << 16;
8582       cval |= (cval << 31) << 1;
8583     }
8584
8585   ret = build_int_cst_type (etype, cval);
8586   var = build_fold_indirect_ref_loc (loc,
8587                                  fold_convert_loc (loc,
8588                                                    build_pointer_type (etype),
8589                                                    dest));
8590   ret = build2 (MODIFY_EXPR, etype, var, ret);
8591   if (ignore)
8592     return ret;
8593
8594   return omit_one_operand_loc (loc, type, dest, ret);
8595 }
8596
8597 /* Fold function call to builtin memset.  Return
8598    NULL_TREE if no simplification can be made.  */
8599
8600 static tree
8601 fold_builtin_bzero (location_t loc, tree dest, tree size, bool ignore)
8602 {
8603   if (! validate_arg (dest, POINTER_TYPE)
8604       || ! validate_arg (size, INTEGER_TYPE))
8605     return NULL_TREE;
8606
8607   if (!ignore)
8608     return NULL_TREE;
8609
8610   /* New argument list transforming bzero(ptr x, int y) to
8611      memset(ptr x, int 0, size_t y).   This is done this way
8612      so that if it isn't expanded inline, we fallback to
8613      calling bzero instead of memset.  */
8614
8615   return fold_builtin_memset (loc, dest, integer_zero_node,
8616                               fold_convert_loc (loc, size_type_node, size),
8617                               void_type_node, ignore);
8618 }
8619
8620 /* Fold function call to builtin mem{{,p}cpy,move}.  Return
8621    NULL_TREE if no simplification can be made.
8622    If ENDP is 0, return DEST (like memcpy).
8623    If ENDP is 1, return DEST+LEN (like mempcpy).
8624    If ENDP is 2, return DEST+LEN-1 (like stpcpy).
8625    If ENDP is 3, return DEST, additionally *SRC and *DEST may overlap
8626    (memmove).   */
8627
8628 static tree
8629 fold_builtin_memory_op (location_t loc, tree dest, tree src,
8630                         tree len, tree type, bool ignore, int endp)
8631 {
8632   tree destvar, srcvar, expr;
8633
8634   if (! validate_arg (dest, POINTER_TYPE)
8635       || ! validate_arg (src, POINTER_TYPE)
8636       || ! validate_arg (len, INTEGER_TYPE))
8637     return NULL_TREE;
8638
8639   /* If the LEN parameter is zero, return DEST.  */
8640   if (integer_zerop (len))
8641     return omit_one_operand_loc (loc, type, dest, src);
8642
8643   /* If SRC and DEST are the same (and not volatile), return
8644      DEST{,+LEN,+LEN-1}.  */
8645   if (operand_equal_p (src, dest, 0))
8646     expr = len;
8647   else
8648     {
8649       tree srctype, desttype;
8650       unsigned int src_align, dest_align;
8651       tree off0;
8652
8653       if (endp == 3)
8654         {
8655           src_align = get_pointer_alignment (src);
8656           dest_align = get_pointer_alignment (dest);
8657
8658           /* Both DEST and SRC must be pointer types.
8659              ??? This is what old code did.  Is the testing for pointer types
8660              really mandatory?
8661
8662              If either SRC is readonly or length is 1, we can use memcpy.  */
8663           if (!dest_align || !src_align)
8664             return NULL_TREE;
8665           if (readonly_data_expr (src)
8666               || (host_integerp (len, 1)
8667                   && (MIN (src_align, dest_align) / BITS_PER_UNIT
8668                       >= (unsigned HOST_WIDE_INT) tree_low_cst (len, 1))))
8669             {
8670               tree fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
8671               if (!fn)
8672                 return NULL_TREE;
8673               return build_call_expr_loc (loc, fn, 3, dest, src, len);
8674             }
8675
8676           /* If *src and *dest can't overlap, optimize into memcpy as well.  */
8677           if (TREE_CODE (src) == ADDR_EXPR
8678               && TREE_CODE (dest) == ADDR_EXPR)
8679             {
8680               tree src_base, dest_base, fn;
8681               HOST_WIDE_INT src_offset = 0, dest_offset = 0;
8682               HOST_WIDE_INT size = -1;
8683               HOST_WIDE_INT maxsize = -1;
8684
8685               srcvar = TREE_OPERAND (src, 0);
8686               src_base = get_ref_base_and_extent (srcvar, &src_offset,
8687                                                   &size, &maxsize);
8688               destvar = TREE_OPERAND (dest, 0);
8689               dest_base = get_ref_base_and_extent (destvar, &dest_offset,
8690                                                    &size, &maxsize);
8691               if (host_integerp (len, 1))
8692                 maxsize = tree_low_cst (len, 1);
8693               else
8694                 maxsize = -1;
8695               src_offset /= BITS_PER_UNIT;
8696               dest_offset /= BITS_PER_UNIT;
8697               if (SSA_VAR_P (src_base)
8698                   && SSA_VAR_P (dest_base))
8699                 {
8700                   if (operand_equal_p (src_base, dest_base, 0)
8701                       && ranges_overlap_p (src_offset, maxsize,
8702                                            dest_offset, maxsize))
8703                     return NULL_TREE;
8704                 }
8705               else if (TREE_CODE (src_base) == MEM_REF
8706                        && TREE_CODE (dest_base) == MEM_REF)
8707                 {
8708                   double_int off;
8709                   if (! operand_equal_p (TREE_OPERAND (src_base, 0),
8710                                          TREE_OPERAND (dest_base, 0), 0))
8711                     return NULL_TREE;
8712                   off = double_int_add (mem_ref_offset (src_base),
8713                                         shwi_to_double_int (src_offset));
8714                   if (!double_int_fits_in_shwi_p (off))
8715                     return NULL_TREE;
8716                   src_offset = off.low;
8717                   off = double_int_add (mem_ref_offset (dest_base),
8718                                         shwi_to_double_int (dest_offset));
8719                   if (!double_int_fits_in_shwi_p (off))
8720                     return NULL_TREE;
8721                   dest_offset = off.low;
8722                   if (ranges_overlap_p (src_offset, maxsize,
8723                                         dest_offset, maxsize))
8724                     return NULL_TREE;
8725                 }
8726               else
8727                 return NULL_TREE;
8728
8729               fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
8730               if (!fn)
8731                 return NULL_TREE;
8732               return build_call_expr_loc (loc, fn, 3, dest, src, len);
8733             }
8734
8735           /* If the destination and source do not alias optimize into
8736              memcpy as well.  */
8737           if ((is_gimple_min_invariant (dest)
8738                || TREE_CODE (dest) == SSA_NAME)
8739               && (is_gimple_min_invariant (src)
8740                   || TREE_CODE (src) == SSA_NAME))
8741             {
8742               ao_ref destr, srcr;
8743               ao_ref_init_from_ptr_and_size (&destr, dest, len);
8744               ao_ref_init_from_ptr_and_size (&srcr, src, len);
8745               if (!refs_may_alias_p_1 (&destr, &srcr, false))
8746                 {
8747                   tree fn;
8748                   fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
8749                   if (!fn)
8750                     return NULL_TREE;
8751                   return build_call_expr_loc (loc, fn, 3, dest, src, len);
8752                 }
8753             }
8754
8755           return NULL_TREE;
8756         }
8757
8758       if (!host_integerp (len, 0))
8759         return NULL_TREE;
8760       /* FIXME:
8761          This logic lose for arguments like (type *)malloc (sizeof (type)),
8762          since we strip the casts of up to VOID return value from malloc.
8763          Perhaps we ought to inherit type from non-VOID argument here?  */
8764       STRIP_NOPS (src);
8765       STRIP_NOPS (dest);
8766       if (!POINTER_TYPE_P (TREE_TYPE (src))
8767           || !POINTER_TYPE_P (TREE_TYPE (dest)))
8768         return NULL_TREE;
8769       /* As we fold (void *)(p + CST) to (void *)p + CST undo this here.  */
8770       if (TREE_CODE (src) == POINTER_PLUS_EXPR)
8771         {
8772           tree tem = TREE_OPERAND (src, 0);
8773           STRIP_NOPS (tem);
8774           if (tem != TREE_OPERAND (src, 0))
8775             src = build1 (NOP_EXPR, TREE_TYPE (tem), src);
8776         }
8777       if (TREE_CODE (dest) == POINTER_PLUS_EXPR)
8778         {
8779           tree tem = TREE_OPERAND (dest, 0);
8780           STRIP_NOPS (tem);
8781           if (tem != TREE_OPERAND (dest, 0))
8782             dest = build1 (NOP_EXPR, TREE_TYPE (tem), dest);
8783         }
8784       srctype = TREE_TYPE (TREE_TYPE (src));
8785       if (TREE_CODE (srctype) == ARRAY_TYPE
8786           && !tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
8787         {
8788           srctype = TREE_TYPE (srctype);
8789           STRIP_NOPS (src);
8790           src = build1 (NOP_EXPR, build_pointer_type (srctype), src);
8791         }
8792       desttype = TREE_TYPE (TREE_TYPE (dest));
8793       if (TREE_CODE (desttype) == ARRAY_TYPE
8794           && !tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
8795         {
8796           desttype = TREE_TYPE (desttype);
8797           STRIP_NOPS (dest);
8798           dest = build1 (NOP_EXPR, build_pointer_type (desttype), dest);
8799         }
8800       if (TREE_ADDRESSABLE (srctype)
8801           || TREE_ADDRESSABLE (desttype))
8802         return NULL_TREE;
8803
8804       src_align = get_pointer_alignment (src);
8805       dest_align = get_pointer_alignment (dest);
8806       if (dest_align < TYPE_ALIGN (desttype)
8807           || src_align < TYPE_ALIGN (srctype))
8808         return NULL_TREE;
8809
8810       if (!ignore)
8811         dest = builtin_save_expr (dest);
8812
8813       /* Build accesses at offset zero with a ref-all character type.  */
8814       off0 = build_int_cst (build_pointer_type_for_mode (char_type_node,
8815                                                          ptr_mode, true), 0);
8816
8817       destvar = dest;
8818       STRIP_NOPS (destvar);
8819       if (TREE_CODE (destvar) == ADDR_EXPR
8820           && var_decl_component_p (TREE_OPERAND (destvar, 0))
8821           && tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
8822         destvar = fold_build2 (MEM_REF, desttype, destvar, off0);
8823       else
8824         destvar = NULL_TREE;
8825
8826       srcvar = src;
8827       STRIP_NOPS (srcvar);
8828       if (TREE_CODE (srcvar) == ADDR_EXPR
8829           && var_decl_component_p (TREE_OPERAND (srcvar, 0))
8830           && tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
8831         {
8832           if (!destvar
8833               || src_align >= TYPE_ALIGN (desttype))
8834             srcvar = fold_build2 (MEM_REF, destvar ? desttype : srctype,
8835                                   srcvar, off0);
8836           else if (!STRICT_ALIGNMENT)
8837             {
8838               srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
8839                                             src_align);
8840               srcvar = fold_build2 (MEM_REF, srctype, srcvar, off0);
8841             }
8842           else
8843             srcvar = NULL_TREE;
8844         }
8845       else
8846         srcvar = NULL_TREE;
8847
8848       if (srcvar == NULL_TREE && destvar == NULL_TREE)
8849         return NULL_TREE;
8850
8851       if (srcvar == NULL_TREE)
8852         {
8853           STRIP_NOPS (src);
8854           if (src_align >= TYPE_ALIGN (desttype))
8855             srcvar = fold_build2 (MEM_REF, desttype, src, off0);
8856           else
8857             {
8858               if (STRICT_ALIGNMENT)
8859                 return NULL_TREE;
8860               srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
8861                                             src_align);
8862               srcvar = fold_build2 (MEM_REF, srctype, src, off0);
8863             }
8864         }
8865       else if (destvar == NULL_TREE)
8866         {
8867           STRIP_NOPS (dest);
8868           if (dest_align >= TYPE_ALIGN (srctype))
8869             destvar = fold_build2 (MEM_REF, srctype, dest, off0);
8870           else
8871             {
8872               if (STRICT_ALIGNMENT)
8873                 return NULL_TREE;
8874               desttype = build_aligned_type (TYPE_MAIN_VARIANT (srctype),
8875                                              dest_align);
8876               destvar = fold_build2 (MEM_REF, desttype, dest, off0);
8877             }
8878         }
8879
8880       expr = build2 (MODIFY_EXPR, TREE_TYPE (destvar), destvar, srcvar);
8881     }
8882
8883   if (ignore)
8884     return expr;
8885
8886   if (endp == 0 || endp == 3)
8887     return omit_one_operand_loc (loc, type, dest, expr);
8888
8889   if (expr == len)
8890     expr = NULL_TREE;
8891
8892   if (endp == 2)
8893     len = fold_build2_loc (loc, MINUS_EXPR, TREE_TYPE (len), len,
8894                        ssize_int (1));
8895
8896   dest = fold_build_pointer_plus_loc (loc, dest, len);
8897   dest = fold_convert_loc (loc, type, dest);
8898   if (expr)
8899     dest = omit_one_operand_loc (loc, type, dest, expr);
8900   return dest;
8901 }
8902
8903 /* Fold function call to builtin strcpy with arguments DEST and SRC.
8904    If LEN is not NULL, it represents the length of the string to be
8905    copied.  Return NULL_TREE if no simplification can be made.  */
8906
8907 tree
8908 fold_builtin_strcpy (location_t loc, tree fndecl, tree dest, tree src, tree len)
8909 {
8910   tree fn;
8911
8912   if (!validate_arg (dest, POINTER_TYPE)
8913       || !validate_arg (src, POINTER_TYPE))
8914     return NULL_TREE;
8915
8916   /* If SRC and DEST are the same (and not volatile), return DEST.  */
8917   if (operand_equal_p (src, dest, 0))
8918     return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest);
8919
8920   if (optimize_function_for_size_p (cfun))
8921     return NULL_TREE;
8922
8923   fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
8924   if (!fn)
8925     return NULL_TREE;
8926
8927   if (!len)
8928     {
8929       len = c_strlen (src, 1);
8930       if (! len || TREE_SIDE_EFFECTS (len))
8931         return NULL_TREE;
8932     }
8933
8934   len = fold_convert_loc (loc, size_type_node, len);
8935   len = size_binop_loc (loc, PLUS_EXPR, len, build_int_cst (size_type_node, 1));
8936   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
8937                            build_call_expr_loc (loc, fn, 3, dest, src, len));
8938 }
8939
8940 /* Fold function call to builtin stpcpy with arguments DEST and SRC.
8941    Return NULL_TREE if no simplification can be made.  */
8942
8943 static tree
8944 fold_builtin_stpcpy (location_t loc, tree fndecl, tree dest, tree src)
8945 {
8946   tree fn, len, lenp1, call, type;
8947
8948   if (!validate_arg (dest, POINTER_TYPE)
8949       || !validate_arg (src, POINTER_TYPE))
8950     return NULL_TREE;
8951
8952   len = c_strlen (src, 1);
8953   if (!len
8954       || TREE_CODE (len) != INTEGER_CST)
8955     return NULL_TREE;
8956
8957   if (optimize_function_for_size_p (cfun)
8958       /* If length is zero it's small enough.  */
8959       && !integer_zerop (len))
8960     return NULL_TREE;
8961
8962   fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
8963   if (!fn)
8964     return NULL_TREE;
8965
8966   lenp1 = size_binop_loc (loc, PLUS_EXPR,
8967                           fold_convert_loc (loc, size_type_node, len),
8968                           build_int_cst (size_type_node, 1));
8969   /* We use dest twice in building our expression.  Save it from
8970      multiple expansions.  */
8971   dest = builtin_save_expr (dest);
8972   call = build_call_expr_loc (loc, fn, 3, dest, src, lenp1);
8973
8974   type = TREE_TYPE (TREE_TYPE (fndecl));
8975   dest = fold_build_pointer_plus_loc (loc, dest, len);
8976   dest = fold_convert_loc (loc, type, dest);
8977   dest = omit_one_operand_loc (loc, type, dest, call);
8978   return dest;
8979 }
8980
8981 /* Fold function call to builtin strncpy with arguments DEST, SRC, and LEN.
8982    If SLEN is not NULL, it represents the length of the source string.
8983    Return NULL_TREE if no simplification can be made.  */
8984
8985 tree
8986 fold_builtin_strncpy (location_t loc, tree fndecl, tree dest,
8987                       tree src, tree len, tree slen)
8988 {
8989   tree fn;
8990
8991   if (!validate_arg (dest, POINTER_TYPE)
8992       || !validate_arg (src, POINTER_TYPE)
8993       || !validate_arg (len, INTEGER_TYPE))
8994     return NULL_TREE;
8995
8996   /* If the LEN parameter is zero, return DEST.  */
8997   if (integer_zerop (len))
8998     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
8999
9000   /* We can't compare slen with len as constants below if len is not a
9001      constant.  */
9002   if (len == 0 || TREE_CODE (len) != INTEGER_CST)
9003     return NULL_TREE;
9004
9005   if (!slen)
9006     slen = c_strlen (src, 1);
9007
9008   /* Now, we must be passed a constant src ptr parameter.  */
9009   if (slen == 0 || TREE_CODE (slen) != INTEGER_CST)
9010     return NULL_TREE;
9011
9012   slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
9013
9014   /* We do not support simplification of this case, though we do
9015      support it when expanding trees into RTL.  */
9016   /* FIXME: generate a call to __builtin_memset.  */
9017   if (tree_int_cst_lt (slen, len))
9018     return NULL_TREE;
9019
9020   /* OK transform into builtin memcpy.  */
9021   fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
9022   if (!fn)
9023     return NULL_TREE;
9024
9025   len = fold_convert_loc (loc, size_type_node, len);
9026   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
9027                            build_call_expr_loc (loc, fn, 3, dest, src, len));
9028 }
9029
9030 /* Fold function call to builtin memchr.  ARG1, ARG2 and LEN are the
9031    arguments to the call, and TYPE is its return type.
9032    Return NULL_TREE if no simplification can be made.  */
9033
9034 static tree
9035 fold_builtin_memchr (location_t loc, tree arg1, tree arg2, tree len, tree type)
9036 {
9037   if (!validate_arg (arg1, POINTER_TYPE)
9038       || !validate_arg (arg2, INTEGER_TYPE)
9039       || !validate_arg (len, INTEGER_TYPE))
9040     return NULL_TREE;
9041   else
9042     {
9043       const char *p1;
9044
9045       if (TREE_CODE (arg2) != INTEGER_CST
9046           || !host_integerp (len, 1))
9047         return NULL_TREE;
9048
9049       p1 = c_getstr (arg1);
9050       if (p1 && compare_tree_int (len, strlen (p1) + 1) <= 0)
9051         {
9052           char c;
9053           const char *r;
9054           tree tem;
9055
9056           if (target_char_cast (arg2, &c))
9057             return NULL_TREE;
9058
9059           r = (const char *) memchr (p1, c, tree_low_cst (len, 1));
9060
9061           if (r == NULL)
9062             return build_int_cst (TREE_TYPE (arg1), 0);
9063
9064           tem = fold_build_pointer_plus_hwi_loc (loc, arg1, r - p1);
9065           return fold_convert_loc (loc, type, tem);
9066         }
9067       return NULL_TREE;
9068     }
9069 }
9070
9071 /* Fold function call to builtin memcmp with arguments ARG1 and ARG2.
9072    Return NULL_TREE if no simplification can be made.  */
9073
9074 static tree
9075 fold_builtin_memcmp (location_t loc, tree arg1, tree arg2, tree len)
9076 {
9077   const char *p1, *p2;
9078
9079   if (!validate_arg (arg1, POINTER_TYPE)
9080       || !validate_arg (arg2, POINTER_TYPE)
9081       || !validate_arg (len, INTEGER_TYPE))
9082     return NULL_TREE;
9083
9084   /* If the LEN parameter is zero, return zero.  */
9085   if (integer_zerop (len))
9086     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
9087                               arg1, arg2);
9088
9089   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
9090   if (operand_equal_p (arg1, arg2, 0))
9091     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
9092
9093   p1 = c_getstr (arg1);
9094   p2 = c_getstr (arg2);
9095
9096   /* If all arguments are constant, and the value of len is not greater
9097      than the lengths of arg1 and arg2, evaluate at compile-time.  */
9098   if (host_integerp (len, 1) && p1 && p2
9099       && compare_tree_int (len, strlen (p1) + 1) <= 0
9100       && compare_tree_int (len, strlen (p2) + 1) <= 0)
9101     {
9102       const int r = memcmp (p1, p2, tree_low_cst (len, 1));
9103
9104       if (r > 0)
9105         return integer_one_node;
9106       else if (r < 0)
9107         return integer_minus_one_node;
9108       else
9109         return integer_zero_node;
9110     }
9111
9112   /* If len parameter is one, return an expression corresponding to
9113      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
9114   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
9115     {
9116       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9117       tree cst_uchar_ptr_node
9118         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9119
9120       tree ind1
9121         = fold_convert_loc (loc, integer_type_node,
9122                             build1 (INDIRECT_REF, cst_uchar_node,
9123                                     fold_convert_loc (loc,
9124                                                       cst_uchar_ptr_node,
9125                                                       arg1)));
9126       tree ind2
9127         = fold_convert_loc (loc, integer_type_node,
9128                             build1 (INDIRECT_REF, cst_uchar_node,
9129                                     fold_convert_loc (loc,
9130                                                       cst_uchar_ptr_node,
9131                                                       arg2)));
9132       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
9133     }
9134
9135   return NULL_TREE;
9136 }
9137
9138 /* Fold function call to builtin strcmp with arguments ARG1 and ARG2.
9139    Return NULL_TREE if no simplification can be made.  */
9140
9141 static tree
9142 fold_builtin_strcmp (location_t loc, tree arg1, tree arg2)
9143 {
9144   const char *p1, *p2;
9145
9146   if (!validate_arg (arg1, POINTER_TYPE)
9147       || !validate_arg (arg2, POINTER_TYPE))
9148     return NULL_TREE;
9149
9150   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
9151   if (operand_equal_p (arg1, arg2, 0))
9152     return integer_zero_node;
9153
9154   p1 = c_getstr (arg1);
9155   p2 = c_getstr (arg2);
9156
9157   if (p1 && p2)
9158     {
9159       const int i = strcmp (p1, p2);
9160       if (i < 0)
9161         return integer_minus_one_node;
9162       else if (i > 0)
9163         return integer_one_node;
9164       else
9165         return integer_zero_node;
9166     }
9167
9168   /* If the second arg is "", return *(const unsigned char*)arg1.  */
9169   if (p2 && *p2 == '\0')
9170     {
9171       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9172       tree cst_uchar_ptr_node
9173         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9174
9175       return fold_convert_loc (loc, integer_type_node,
9176                                build1 (INDIRECT_REF, cst_uchar_node,
9177                                        fold_convert_loc (loc,
9178                                                          cst_uchar_ptr_node,
9179                                                          arg1)));
9180     }
9181
9182   /* If the first arg is "", return -*(const unsigned char*)arg2.  */
9183   if (p1 && *p1 == '\0')
9184     {
9185       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9186       tree cst_uchar_ptr_node
9187         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9188
9189       tree temp
9190         = fold_convert_loc (loc, integer_type_node,
9191                             build1 (INDIRECT_REF, cst_uchar_node,
9192                                     fold_convert_loc (loc,
9193                                                       cst_uchar_ptr_node,
9194                                                       arg2)));
9195       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
9196     }
9197
9198   return NULL_TREE;
9199 }
9200
9201 /* Fold function call to builtin strncmp with arguments ARG1, ARG2, and LEN.
9202    Return NULL_TREE if no simplification can be made.  */
9203
9204 static tree
9205 fold_builtin_strncmp (location_t loc, tree arg1, tree arg2, tree len)
9206 {
9207   const char *p1, *p2;
9208
9209   if (!validate_arg (arg1, POINTER_TYPE)
9210       || !validate_arg (arg2, POINTER_TYPE)
9211       || !validate_arg (len, INTEGER_TYPE))
9212     return NULL_TREE;
9213
9214   /* If the LEN parameter is zero, return zero.  */
9215   if (integer_zerop (len))
9216     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
9217                               arg1, arg2);
9218
9219   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
9220   if (operand_equal_p (arg1, arg2, 0))
9221     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
9222
9223   p1 = c_getstr (arg1);
9224   p2 = c_getstr (arg2);
9225
9226   if (host_integerp (len, 1) && p1 && p2)
9227     {
9228       const int i = strncmp (p1, p2, tree_low_cst (len, 1));
9229       if (i > 0)
9230         return integer_one_node;
9231       else if (i < 0)
9232         return integer_minus_one_node;
9233       else
9234         return integer_zero_node;
9235     }
9236
9237   /* If the second arg is "", and the length is greater than zero,
9238      return *(const unsigned char*)arg1.  */
9239   if (p2 && *p2 == '\0'
9240       && TREE_CODE (len) == INTEGER_CST
9241       && tree_int_cst_sgn (len) == 1)
9242     {
9243       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9244       tree cst_uchar_ptr_node
9245         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9246
9247       return fold_convert_loc (loc, integer_type_node,
9248                                build1 (INDIRECT_REF, cst_uchar_node,
9249                                        fold_convert_loc (loc,
9250                                                          cst_uchar_ptr_node,
9251                                                          arg1)));
9252     }
9253
9254   /* If the first arg is "", and the length is greater than zero,
9255      return -*(const unsigned char*)arg2.  */
9256   if (p1 && *p1 == '\0'
9257       && TREE_CODE (len) == INTEGER_CST
9258       && tree_int_cst_sgn (len) == 1)
9259     {
9260       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9261       tree cst_uchar_ptr_node
9262         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9263
9264       tree temp = fold_convert_loc (loc, integer_type_node,
9265                                     build1 (INDIRECT_REF, cst_uchar_node,
9266                                             fold_convert_loc (loc,
9267                                                               cst_uchar_ptr_node,
9268                                                               arg2)));
9269       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
9270     }
9271
9272   /* If len parameter is one, return an expression corresponding to
9273      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
9274   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
9275     {
9276       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9277       tree cst_uchar_ptr_node
9278         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9279
9280       tree ind1 = fold_convert_loc (loc, integer_type_node,
9281                                     build1 (INDIRECT_REF, cst_uchar_node,
9282                                             fold_convert_loc (loc,
9283                                                               cst_uchar_ptr_node,
9284                                                               arg1)));
9285       tree ind2 = fold_convert_loc (loc, integer_type_node,
9286                                     build1 (INDIRECT_REF, cst_uchar_node,
9287                                             fold_convert_loc (loc,
9288                                                               cst_uchar_ptr_node,
9289                                                               arg2)));
9290       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
9291     }
9292
9293   return NULL_TREE;
9294 }
9295
9296 /* Fold function call to builtin signbit, signbitf or signbitl with argument
9297    ARG.  Return NULL_TREE if no simplification can be made.  */
9298
9299 static tree
9300 fold_builtin_signbit (location_t loc, tree arg, tree type)
9301 {
9302   if (!validate_arg (arg, REAL_TYPE))
9303     return NULL_TREE;
9304
9305   /* If ARG is a compile-time constant, determine the result.  */
9306   if (TREE_CODE (arg) == REAL_CST
9307       && !TREE_OVERFLOW (arg))
9308     {
9309       REAL_VALUE_TYPE c;
9310
9311       c = TREE_REAL_CST (arg);
9312       return (REAL_VALUE_NEGATIVE (c)
9313               ? build_one_cst (type)
9314               : build_zero_cst (type));
9315     }
9316
9317   /* If ARG is non-negative, the result is always zero.  */
9318   if (tree_expr_nonnegative_p (arg))
9319     return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9320
9321   /* If ARG's format doesn't have signed zeros, return "arg < 0.0".  */
9322   if (!HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (arg))))
9323     return fold_convert (type,
9324                          fold_build2_loc (loc, LT_EXPR, boolean_type_node, arg,
9325                         build_real (TREE_TYPE (arg), dconst0)));
9326
9327   return NULL_TREE;
9328 }
9329
9330 /* Fold function call to builtin copysign, copysignf or copysignl with
9331    arguments ARG1 and ARG2.  Return NULL_TREE if no simplification can
9332    be made.  */
9333
9334 static tree
9335 fold_builtin_copysign (location_t loc, tree fndecl,
9336                        tree arg1, tree arg2, tree type)
9337 {
9338   tree tem;
9339
9340   if (!validate_arg (arg1, REAL_TYPE)
9341       || !validate_arg (arg2, REAL_TYPE))
9342     return NULL_TREE;
9343
9344   /* copysign(X,X) is X.  */
9345   if (operand_equal_p (arg1, arg2, 0))
9346     return fold_convert_loc (loc, type, arg1);
9347
9348   /* If ARG1 and ARG2 are compile-time constants, determine the result.  */
9349   if (TREE_CODE (arg1) == REAL_CST
9350       && TREE_CODE (arg2) == REAL_CST
9351       && !TREE_OVERFLOW (arg1)
9352       && !TREE_OVERFLOW (arg2))
9353     {
9354       REAL_VALUE_TYPE c1, c2;
9355
9356       c1 = TREE_REAL_CST (arg1);
9357       c2 = TREE_REAL_CST (arg2);
9358       /* c1.sign := c2.sign.  */
9359       real_copysign (&c1, &c2);
9360       return build_real (type, c1);
9361     }
9362
9363   /* copysign(X, Y) is fabs(X) when Y is always non-negative.
9364      Remember to evaluate Y for side-effects.  */
9365   if (tree_expr_nonnegative_p (arg2))
9366     return omit_one_operand_loc (loc, type,
9367                              fold_build1_loc (loc, ABS_EXPR, type, arg1),
9368                              arg2);
9369
9370   /* Strip sign changing operations for the first argument.  */
9371   tem = fold_strip_sign_ops (arg1);
9372   if (tem)
9373     return build_call_expr_loc (loc, fndecl, 2, tem, arg2);
9374
9375   return NULL_TREE;
9376 }
9377
9378 /* Fold a call to builtin isascii with argument ARG.  */
9379
9380 static tree
9381 fold_builtin_isascii (location_t loc, tree arg)
9382 {
9383   if (!validate_arg (arg, INTEGER_TYPE))
9384     return NULL_TREE;
9385   else
9386     {
9387       /* Transform isascii(c) -> ((c & ~0x7f) == 0).  */
9388       arg = fold_build2 (BIT_AND_EXPR, integer_type_node, arg,
9389                          build_int_cst (integer_type_node,
9390                                         ~ (unsigned HOST_WIDE_INT) 0x7f));
9391       return fold_build2_loc (loc, EQ_EXPR, integer_type_node,
9392                               arg, integer_zero_node);
9393     }
9394 }
9395
9396 /* Fold a call to builtin toascii with argument ARG.  */
9397
9398 static tree
9399 fold_builtin_toascii (location_t loc, tree arg)
9400 {
9401   if (!validate_arg (arg, INTEGER_TYPE))
9402     return NULL_TREE;
9403
9404   /* Transform toascii(c) -> (c & 0x7f).  */
9405   return fold_build2_loc (loc, BIT_AND_EXPR, integer_type_node, arg,
9406                           build_int_cst (integer_type_node, 0x7f));
9407 }
9408
9409 /* Fold a call to builtin isdigit with argument ARG.  */
9410
9411 static tree
9412 fold_builtin_isdigit (location_t loc, tree arg)
9413 {
9414   if (!validate_arg (arg, INTEGER_TYPE))
9415     return NULL_TREE;
9416   else
9417     {
9418       /* Transform isdigit(c) -> (unsigned)(c) - '0' <= 9.  */
9419       /* According to the C standard, isdigit is unaffected by locale.
9420          However, it definitely is affected by the target character set.  */
9421       unsigned HOST_WIDE_INT target_digit0
9422         = lang_hooks.to_target_charset ('0');
9423
9424       if (target_digit0 == 0)
9425         return NULL_TREE;
9426
9427       arg = fold_convert_loc (loc, unsigned_type_node, arg);
9428       arg = fold_build2 (MINUS_EXPR, unsigned_type_node, arg,
9429                          build_int_cst (unsigned_type_node, target_digit0));
9430       return fold_build2_loc (loc, LE_EXPR, integer_type_node, arg,
9431                           build_int_cst (unsigned_type_node, 9));
9432     }
9433 }
9434
9435 /* Fold a call to fabs, fabsf or fabsl with argument ARG.  */
9436
9437 static tree
9438 fold_builtin_fabs (location_t loc, tree arg, tree type)
9439 {
9440   if (!validate_arg (arg, REAL_TYPE))
9441     return NULL_TREE;
9442
9443   arg = fold_convert_loc (loc, type, arg);
9444   if (TREE_CODE (arg) == REAL_CST)
9445     return fold_abs_const (arg, type);
9446   return fold_build1_loc (loc, ABS_EXPR, type, arg);
9447 }
9448
9449 /* Fold a call to abs, labs, llabs or imaxabs with argument ARG.  */
9450
9451 static tree
9452 fold_builtin_abs (location_t loc, tree arg, tree type)
9453 {
9454   if (!validate_arg (arg, INTEGER_TYPE))
9455     return NULL_TREE;
9456
9457   arg = fold_convert_loc (loc, type, arg);
9458   if (TREE_CODE (arg) == INTEGER_CST)
9459     return fold_abs_const (arg, type);
9460   return fold_build1_loc (loc, ABS_EXPR, type, arg);
9461 }
9462
9463 /* Fold a fma operation with arguments ARG[012].  */
9464
9465 tree
9466 fold_fma (location_t loc ATTRIBUTE_UNUSED,
9467           tree type, tree arg0, tree arg1, tree arg2)
9468 {
9469   if (TREE_CODE (arg0) == REAL_CST
9470       && TREE_CODE (arg1) == REAL_CST
9471       && TREE_CODE (arg2) == REAL_CST)
9472     return do_mpfr_arg3 (arg0, arg1, arg2, type, mpfr_fma);
9473
9474   return NULL_TREE;
9475 }
9476
9477 /* Fold a call to fma, fmaf, or fmal with arguments ARG[012].  */
9478
9479 static tree
9480 fold_builtin_fma (location_t loc, tree arg0, tree arg1, tree arg2, tree type)
9481 {
9482   if (validate_arg (arg0, REAL_TYPE)
9483       && validate_arg(arg1, REAL_TYPE)
9484       && validate_arg(arg2, REAL_TYPE))
9485     {
9486       tree tem = fold_fma (loc, type, arg0, arg1, arg2);
9487       if (tem)
9488         return tem;
9489
9490       /* ??? Only expand to FMA_EXPR if it's directly supported.  */
9491       if (optab_handler (fma_optab, TYPE_MODE (type)) != CODE_FOR_nothing)
9492         return fold_build3_loc (loc, FMA_EXPR, type, arg0, arg1, arg2);
9493     }
9494   return NULL_TREE;
9495 }
9496
9497 /* Fold a call to builtin fmin or fmax.  */
9498
9499 static tree
9500 fold_builtin_fmin_fmax (location_t loc, tree arg0, tree arg1,
9501                         tree type, bool max)
9502 {
9503   if (validate_arg (arg0, REAL_TYPE) && validate_arg (arg1, REAL_TYPE))
9504     {
9505       /* Calculate the result when the argument is a constant.  */
9506       tree res = do_mpfr_arg2 (arg0, arg1, type, (max ? mpfr_max : mpfr_min));
9507
9508       if (res)
9509         return res;
9510
9511       /* If either argument is NaN, return the other one.  Avoid the
9512          transformation if we get (and honor) a signalling NaN.  Using
9513          omit_one_operand() ensures we create a non-lvalue.  */
9514       if (TREE_CODE (arg0) == REAL_CST
9515           && real_isnan (&TREE_REAL_CST (arg0))
9516           && (! HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg0)))
9517               || ! TREE_REAL_CST (arg0).signalling))
9518         return omit_one_operand_loc (loc, type, arg1, arg0);
9519       if (TREE_CODE (arg1) == REAL_CST
9520           && real_isnan (&TREE_REAL_CST (arg1))
9521           && (! HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg1)))
9522               || ! TREE_REAL_CST (arg1).signalling))
9523         return omit_one_operand_loc (loc, type, arg0, arg1);
9524
9525       /* Transform fmin/fmax(x,x) -> x.  */
9526       if (operand_equal_p (arg0, arg1, OEP_PURE_SAME))
9527         return omit_one_operand_loc (loc, type, arg0, arg1);
9528
9529       /* Convert fmin/fmax to MIN_EXPR/MAX_EXPR.  C99 requires these
9530          functions to return the numeric arg if the other one is NaN.
9531          These tree codes don't honor that, so only transform if
9532          -ffinite-math-only is set.  C99 doesn't require -0.0 to be
9533          handled, so we don't have to worry about it either.  */
9534       if (flag_finite_math_only)
9535         return fold_build2_loc (loc, (max ? MAX_EXPR : MIN_EXPR), type,
9536                             fold_convert_loc (loc, type, arg0),
9537                             fold_convert_loc (loc, type, arg1));
9538     }
9539   return NULL_TREE;
9540 }
9541
9542 /* Fold a call to builtin carg(a+bi) -> atan2(b,a).  */
9543
9544 static tree
9545 fold_builtin_carg (location_t loc, tree arg, tree type)
9546 {
9547   if (validate_arg (arg, COMPLEX_TYPE)
9548       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE)
9549     {
9550       tree atan2_fn = mathfn_built_in (type, BUILT_IN_ATAN2);
9551
9552       if (atan2_fn)
9553         {
9554           tree new_arg = builtin_save_expr (arg);
9555           tree r_arg = fold_build1_loc (loc, REALPART_EXPR, type, new_arg);
9556           tree i_arg = fold_build1_loc (loc, IMAGPART_EXPR, type, new_arg);
9557           return build_call_expr_loc (loc, atan2_fn, 2, i_arg, r_arg);
9558         }
9559     }
9560
9561   return NULL_TREE;
9562 }
9563
9564 /* Fold a call to builtin logb/ilogb.  */
9565
9566 static tree
9567 fold_builtin_logb (location_t loc, tree arg, tree rettype)
9568 {
9569   if (! validate_arg (arg, REAL_TYPE))
9570     return NULL_TREE;
9571
9572   STRIP_NOPS (arg);
9573
9574   if (TREE_CODE (arg) == REAL_CST && ! TREE_OVERFLOW (arg))
9575     {
9576       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg);
9577
9578       switch (value->cl)
9579       {
9580       case rvc_nan:
9581       case rvc_inf:
9582         /* If arg is Inf or NaN and we're logb, return it.  */
9583         if (TREE_CODE (rettype) == REAL_TYPE)
9584           return fold_convert_loc (loc, rettype, arg);
9585         /* Fall through... */
9586       case rvc_zero:
9587         /* Zero may set errno and/or raise an exception for logb, also
9588            for ilogb we don't know FP_ILOGB0.  */
9589         return NULL_TREE;
9590       case rvc_normal:
9591         /* For normal numbers, proceed iff radix == 2.  In GCC,
9592            normalized significands are in the range [0.5, 1.0).  We
9593            want the exponent as if they were [1.0, 2.0) so get the
9594            exponent and subtract 1.  */
9595         if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->b == 2)
9596           return fold_convert_loc (loc, rettype,
9597                                    build_int_cst (integer_type_node,
9598                                                   REAL_EXP (value)-1));
9599         break;
9600       }
9601     }
9602
9603   return NULL_TREE;
9604 }
9605
9606 /* Fold a call to builtin significand, if radix == 2.  */
9607
9608 static tree
9609 fold_builtin_significand (location_t loc, tree arg, tree rettype)
9610 {
9611   if (! validate_arg (arg, REAL_TYPE))
9612     return NULL_TREE;
9613
9614   STRIP_NOPS (arg);
9615
9616   if (TREE_CODE (arg) == REAL_CST && ! TREE_OVERFLOW (arg))
9617     {
9618       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg);
9619
9620       switch (value->cl)
9621       {
9622       case rvc_zero:
9623       case rvc_nan:
9624       case rvc_inf:
9625         /* If arg is +-0, +-Inf or +-NaN, then return it.  */
9626         return fold_convert_loc (loc, rettype, arg);
9627       case rvc_normal:
9628         /* For normal numbers, proceed iff radix == 2.  */
9629         if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->b == 2)
9630           {
9631             REAL_VALUE_TYPE result = *value;
9632             /* In GCC, normalized significands are in the range [0.5,
9633                1.0).  We want them to be [1.0, 2.0) so set the
9634                exponent to 1.  */
9635             SET_REAL_EXP (&result, 1);
9636             return build_real (rettype, result);
9637           }
9638         break;
9639       }
9640     }
9641
9642   return NULL_TREE;
9643 }
9644
9645 /* Fold a call to builtin frexp, we can assume the base is 2.  */
9646
9647 static tree
9648 fold_builtin_frexp (location_t loc, tree arg0, tree arg1, tree rettype)
9649 {
9650   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
9651     return NULL_TREE;
9652
9653   STRIP_NOPS (arg0);
9654
9655   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
9656     return NULL_TREE;
9657
9658   arg1 = build_fold_indirect_ref_loc (loc, arg1);
9659
9660   /* Proceed if a valid pointer type was passed in.  */
9661   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == integer_type_node)
9662     {
9663       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
9664       tree frac, exp;
9665
9666       switch (value->cl)
9667       {
9668       case rvc_zero:
9669         /* For +-0, return (*exp = 0, +-0).  */
9670         exp = integer_zero_node;
9671         frac = arg0;
9672         break;
9673       case rvc_nan:
9674       case rvc_inf:
9675         /* For +-NaN or +-Inf, *exp is unspecified, return arg0.  */
9676         return omit_one_operand_loc (loc, rettype, arg0, arg1);
9677       case rvc_normal:
9678         {
9679           /* Since the frexp function always expects base 2, and in
9680              GCC normalized significands are already in the range
9681              [0.5, 1.0), we have exactly what frexp wants.  */
9682           REAL_VALUE_TYPE frac_rvt = *value;
9683           SET_REAL_EXP (&frac_rvt, 0);
9684           frac = build_real (rettype, frac_rvt);
9685           exp = build_int_cst (integer_type_node, REAL_EXP (value));
9686         }
9687         break;
9688       default:
9689         gcc_unreachable ();
9690       }
9691
9692       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
9693       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1, exp);
9694       TREE_SIDE_EFFECTS (arg1) = 1;
9695       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1, frac);
9696     }
9697
9698   return NULL_TREE;
9699 }
9700
9701 /* Fold a call to builtin ldexp or scalbn/scalbln.  If LDEXP is true
9702    then we can assume the base is two.  If it's false, then we have to
9703    check the mode of the TYPE parameter in certain cases.  */
9704
9705 static tree
9706 fold_builtin_load_exponent (location_t loc, tree arg0, tree arg1,
9707                             tree type, bool ldexp)
9708 {
9709   if (validate_arg (arg0, REAL_TYPE) && validate_arg (arg1, INTEGER_TYPE))
9710     {
9711       STRIP_NOPS (arg0);
9712       STRIP_NOPS (arg1);
9713
9714       /* If arg0 is 0, Inf or NaN, or if arg1 is 0, then return arg0.  */
9715       if (real_zerop (arg0) || integer_zerop (arg1)
9716           || (TREE_CODE (arg0) == REAL_CST
9717               && !real_isfinite (&TREE_REAL_CST (arg0))))
9718         return omit_one_operand_loc (loc, type, arg0, arg1);
9719
9720       /* If both arguments are constant, then try to evaluate it.  */
9721       if ((ldexp || REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2)
9722           && TREE_CODE (arg0) == REAL_CST && !TREE_OVERFLOW (arg0)
9723           && host_integerp (arg1, 0))
9724         {
9725           /* Bound the maximum adjustment to twice the range of the
9726              mode's valid exponents.  Use abs to ensure the range is
9727              positive as a sanity check.  */
9728           const long max_exp_adj = 2 *
9729             labs (REAL_MODE_FORMAT (TYPE_MODE (type))->emax
9730                  - REAL_MODE_FORMAT (TYPE_MODE (type))->emin);
9731
9732           /* Get the user-requested adjustment.  */
9733           const HOST_WIDE_INT req_exp_adj = tree_low_cst (arg1, 0);
9734
9735           /* The requested adjustment must be inside this range.  This
9736              is a preliminary cap to avoid things like overflow, we
9737              may still fail to compute the result for other reasons.  */
9738           if (-max_exp_adj < req_exp_adj && req_exp_adj < max_exp_adj)
9739             {
9740               REAL_VALUE_TYPE initial_result;
9741
9742               real_ldexp (&initial_result, &TREE_REAL_CST (arg0), req_exp_adj);
9743
9744               /* Ensure we didn't overflow.  */
9745               if (! real_isinf (&initial_result))
9746                 {
9747                   const REAL_VALUE_TYPE trunc_result
9748                     = real_value_truncate (TYPE_MODE (type), initial_result);
9749
9750                   /* Only proceed if the target mode can hold the
9751                      resulting value.  */
9752                   if (REAL_VALUES_EQUAL (initial_result, trunc_result))
9753                     return build_real (type, trunc_result);
9754                 }
9755             }
9756         }
9757     }
9758
9759   return NULL_TREE;
9760 }
9761
9762 /* Fold a call to builtin modf.  */
9763
9764 static tree
9765 fold_builtin_modf (location_t loc, tree arg0, tree arg1, tree rettype)
9766 {
9767   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
9768     return NULL_TREE;
9769
9770   STRIP_NOPS (arg0);
9771
9772   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
9773     return NULL_TREE;
9774
9775   arg1 = build_fold_indirect_ref_loc (loc, arg1);
9776
9777   /* Proceed if a valid pointer type was passed in.  */
9778   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == TYPE_MAIN_VARIANT (rettype))
9779     {
9780       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
9781       REAL_VALUE_TYPE trunc, frac;
9782
9783       switch (value->cl)
9784       {
9785       case rvc_nan:
9786       case rvc_zero:
9787         /* For +-NaN or +-0, return (*arg1 = arg0, arg0).  */
9788         trunc = frac = *value;
9789         break;
9790       case rvc_inf:
9791         /* For +-Inf, return (*arg1 = arg0, +-0).  */
9792         frac = dconst0;
9793         frac.sign = value->sign;
9794         trunc = *value;
9795         break;
9796       case rvc_normal:
9797         /* Return (*arg1 = trunc(arg0), arg0-trunc(arg0)).  */
9798         real_trunc (&trunc, VOIDmode, value);
9799         real_arithmetic (&frac, MINUS_EXPR, value, &trunc);
9800         /* If the original number was negative and already
9801            integral, then the fractional part is -0.0.  */
9802         if (value->sign && frac.cl == rvc_zero)
9803           frac.sign = value->sign;
9804         break;
9805       }
9806
9807       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
9808       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1,
9809                           build_real (rettype, trunc));
9810       TREE_SIDE_EFFECTS (arg1) = 1;
9811       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1,
9812                           build_real (rettype, frac));
9813     }
9814
9815   return NULL_TREE;
9816 }
9817
9818 /* Given a location LOC, an interclass builtin function decl FNDECL
9819    and its single argument ARG, return an folded expression computing
9820    the same, or NULL_TREE if we either couldn't or didn't want to fold
9821    (the latter happen if there's an RTL instruction available).  */
9822
9823 static tree
9824 fold_builtin_interclass_mathfn (location_t loc, tree fndecl, tree arg)
9825 {
9826   enum machine_mode mode;
9827
9828   if (!validate_arg (arg, REAL_TYPE))
9829     return NULL_TREE;
9830
9831   if (interclass_mathfn_icode (arg, fndecl) != CODE_FOR_nothing)
9832     return NULL_TREE;
9833
9834   mode = TYPE_MODE (TREE_TYPE (arg));
9835
9836   /* If there is no optab, try generic code.  */
9837   switch (DECL_FUNCTION_CODE (fndecl))
9838     {
9839       tree result;
9840
9841     CASE_FLT_FN (BUILT_IN_ISINF):
9842       {
9843         /* isinf(x) -> isgreater(fabs(x),DBL_MAX).  */
9844         tree const isgr_fn = builtin_decl_explicit (BUILT_IN_ISGREATER);
9845         tree const type = TREE_TYPE (arg);
9846         REAL_VALUE_TYPE r;
9847         char buf[128];
9848
9849         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9850         real_from_string (&r, buf);
9851         result = build_call_expr (isgr_fn, 2,
9852                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9853                                   build_real (type, r));
9854         return result;
9855       }
9856     CASE_FLT_FN (BUILT_IN_FINITE):
9857     case BUILT_IN_ISFINITE:
9858       {
9859         /* isfinite(x) -> islessequal(fabs(x),DBL_MAX).  */
9860         tree const isle_fn = builtin_decl_explicit (BUILT_IN_ISLESSEQUAL);
9861         tree const type = TREE_TYPE (arg);
9862         REAL_VALUE_TYPE r;
9863         char buf[128];
9864
9865         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9866         real_from_string (&r, buf);
9867         result = build_call_expr (isle_fn, 2,
9868                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9869                                   build_real (type, r));
9870         /*result = fold_build2_loc (loc, UNGT_EXPR,
9871                                   TREE_TYPE (TREE_TYPE (fndecl)),
9872                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9873                                   build_real (type, r));
9874         result = fold_build1_loc (loc, TRUTH_NOT_EXPR,
9875                                   TREE_TYPE (TREE_TYPE (fndecl)),
9876                                   result);*/
9877         return result;
9878       }
9879     case BUILT_IN_ISNORMAL:
9880       {
9881         /* isnormal(x) -> isgreaterequal(fabs(x),DBL_MIN) &
9882            islessequal(fabs(x),DBL_MAX).  */
9883         tree const isle_fn = builtin_decl_explicit (BUILT_IN_ISLESSEQUAL);
9884         tree const isge_fn = builtin_decl_explicit (BUILT_IN_ISGREATEREQUAL);
9885         tree const type = TREE_TYPE (arg);
9886         REAL_VALUE_TYPE rmax, rmin;
9887         char buf[128];
9888
9889         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9890         real_from_string (&rmax, buf);
9891         sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (mode)->emin - 1);
9892         real_from_string (&rmin, buf);
9893         arg = builtin_save_expr (fold_build1_loc (loc, ABS_EXPR, type, arg));
9894         result = build_call_expr (isle_fn, 2, arg,
9895                                   build_real (type, rmax));
9896         result = fold_build2 (BIT_AND_EXPR, integer_type_node, result,
9897                               build_call_expr (isge_fn, 2, arg,
9898                                                build_real (type, rmin)));
9899         return result;
9900       }
9901     default:
9902       break;
9903     }
9904
9905   return NULL_TREE;
9906 }
9907
9908 /* Fold a call to __builtin_isnan(), __builtin_isinf, __builtin_finite.
9909    ARG is the argument for the call.  */
9910
9911 static tree
9912 fold_builtin_classify (location_t loc, tree fndecl, tree arg, int builtin_index)
9913 {
9914   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9915   REAL_VALUE_TYPE r;
9916
9917   if (!validate_arg (arg, REAL_TYPE))
9918     return NULL_TREE;
9919
9920   switch (builtin_index)
9921     {
9922     case BUILT_IN_ISINF:
9923       if (!HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
9924         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9925
9926       if (TREE_CODE (arg) == REAL_CST)
9927         {
9928           r = TREE_REAL_CST (arg);
9929           if (real_isinf (&r))
9930             return real_compare (GT_EXPR, &r, &dconst0)
9931                    ? integer_one_node : integer_minus_one_node;
9932           else
9933             return integer_zero_node;
9934         }
9935
9936       return NULL_TREE;
9937
9938     case BUILT_IN_ISINF_SIGN:
9939       {
9940         /* isinf_sign(x) -> isinf(x) ? (signbit(x) ? -1 : 1) : 0 */
9941         /* In a boolean context, GCC will fold the inner COND_EXPR to
9942            1.  So e.g. "if (isinf_sign(x))" would be folded to just
9943            "if (isinf(x) ? 1 : 0)" which becomes "if (isinf(x))". */
9944         tree signbit_fn = mathfn_built_in_1 (TREE_TYPE (arg), BUILT_IN_SIGNBIT, 0);
9945         tree isinf_fn = builtin_decl_explicit (BUILT_IN_ISINF);
9946         tree tmp = NULL_TREE;
9947
9948         arg = builtin_save_expr (arg);
9949
9950         if (signbit_fn && isinf_fn)
9951           {
9952             tree signbit_call = build_call_expr_loc (loc, signbit_fn, 1, arg);
9953             tree isinf_call = build_call_expr_loc (loc, isinf_fn, 1, arg);
9954
9955             signbit_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
9956                                         signbit_call, integer_zero_node);
9957             isinf_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
9958                                       isinf_call, integer_zero_node);
9959
9960             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node, signbit_call,
9961                                integer_minus_one_node, integer_one_node);
9962             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node,
9963                                isinf_call, tmp,
9964                                integer_zero_node);
9965           }
9966
9967         return tmp;
9968       }
9969
9970     case BUILT_IN_ISFINITE:
9971       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg)))
9972           && !HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
9973         return omit_one_operand_loc (loc, type, integer_one_node, arg);
9974
9975       if (TREE_CODE (arg) == REAL_CST)
9976         {
9977           r = TREE_REAL_CST (arg);
9978           return real_isfinite (&r) ? integer_one_node : integer_zero_node;
9979         }
9980
9981       return NULL_TREE;
9982
9983     case BUILT_IN_ISNAN:
9984       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg))))
9985         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9986
9987       if (TREE_CODE (arg) == REAL_CST)
9988         {
9989           r = TREE_REAL_CST (arg);
9990           return real_isnan (&r) ? integer_one_node : integer_zero_node;
9991         }
9992
9993       arg = builtin_save_expr (arg);
9994       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg, arg);
9995
9996     default:
9997       gcc_unreachable ();
9998     }
9999 }
10000
10001 /* Fold a call to __builtin_fpclassify(int, int, int, int, int, ...).
10002    This builtin will generate code to return the appropriate floating
10003    point classification depending on the value of the floating point
10004    number passed in.  The possible return values must be supplied as
10005    int arguments to the call in the following order: FP_NAN, FP_INFINITE,
10006    FP_NORMAL, FP_SUBNORMAL and FP_ZERO.  The ellipses is for exactly
10007    one floating point argument which is "type generic".  */
10008
10009 static tree
10010 fold_builtin_fpclassify (location_t loc, tree exp)
10011 {
10012   tree fp_nan, fp_infinite, fp_normal, fp_subnormal, fp_zero,
10013     arg, type, res, tmp;
10014   enum machine_mode mode;
10015   REAL_VALUE_TYPE r;
10016   char buf[128];
10017
10018   /* Verify the required arguments in the original call.  */
10019   if (!validate_arglist (exp, INTEGER_TYPE, INTEGER_TYPE,
10020                          INTEGER_TYPE, INTEGER_TYPE,
10021                          INTEGER_TYPE, REAL_TYPE, VOID_TYPE))
10022     return NULL_TREE;
10023
10024   fp_nan = CALL_EXPR_ARG (exp, 0);
10025   fp_infinite = CALL_EXPR_ARG (exp, 1);
10026   fp_normal = CALL_EXPR_ARG (exp, 2);
10027   fp_subnormal = CALL_EXPR_ARG (exp, 3);
10028   fp_zero = CALL_EXPR_ARG (exp, 4);
10029   arg = CALL_EXPR_ARG (exp, 5);
10030   type = TREE_TYPE (arg);
10031   mode = TYPE_MODE (type);
10032   arg = builtin_save_expr (fold_build1_loc (loc, ABS_EXPR, type, arg));
10033
10034   /* fpclassify(x) ->
10035        isnan(x) ? FP_NAN :
10036          (fabs(x) == Inf ? FP_INFINITE :
10037            (fabs(x) >= DBL_MIN ? FP_NORMAL :
10038              (x == 0 ? FP_ZERO : FP_SUBNORMAL))).  */
10039
10040   tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
10041                      build_real (type, dconst0));
10042   res = fold_build3_loc (loc, COND_EXPR, integer_type_node,
10043                      tmp, fp_zero, fp_subnormal);
10044
10045   sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (mode)->emin - 1);
10046   real_from_string (&r, buf);
10047   tmp = fold_build2_loc (loc, GE_EXPR, integer_type_node,
10048                      arg, build_real (type, r));
10049   res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, fp_normal, res);
10050
10051   if (HONOR_INFINITIES (mode))
10052     {
10053       real_inf (&r);
10054       tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
10055                          build_real (type, r));
10056       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp,
10057                          fp_infinite, res);
10058     }
10059
10060   if (HONOR_NANS (mode))
10061     {
10062       tmp = fold_build2_loc (loc, ORDERED_EXPR, integer_type_node, arg, arg);
10063       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, res, fp_nan);
10064     }
10065
10066   return res;
10067 }
10068
10069 /* Fold a call to an unordered comparison function such as
10070    __builtin_isgreater().  FNDECL is the FUNCTION_DECL for the function
10071    being called and ARG0 and ARG1 are the arguments for the call.
10072    UNORDERED_CODE and ORDERED_CODE are comparison codes that give
10073    the opposite of the desired result.  UNORDERED_CODE is used
10074    for modes that can hold NaNs and ORDERED_CODE is used for
10075    the rest.  */
10076
10077 static tree
10078 fold_builtin_unordered_cmp (location_t loc, tree fndecl, tree arg0, tree arg1,
10079                             enum tree_code unordered_code,
10080                             enum tree_code ordered_code)
10081 {
10082   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10083   enum tree_code code;
10084   tree type0, type1;
10085   enum tree_code code0, code1;
10086   tree cmp_type = NULL_TREE;
10087
10088   type0 = TREE_TYPE (arg0);
10089   type1 = TREE_TYPE (arg1);
10090
10091   code0 = TREE_CODE (type0);
10092   code1 = TREE_CODE (type1);
10093
10094   if (code0 == REAL_TYPE && code1 == REAL_TYPE)
10095     /* Choose the wider of two real types.  */
10096     cmp_type = TYPE_PRECISION (type0) >= TYPE_PRECISION (type1)
10097       ? type0 : type1;
10098   else if (code0 == REAL_TYPE && code1 == INTEGER_TYPE)
10099     cmp_type = type0;
10100   else if (code0 == INTEGER_TYPE && code1 == REAL_TYPE)
10101     cmp_type = type1;
10102
10103   arg0 = fold_convert_loc (loc, cmp_type, arg0);
10104   arg1 = fold_convert_loc (loc, cmp_type, arg1);
10105
10106   if (unordered_code == UNORDERED_EXPR)
10107     {
10108       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))))
10109         return omit_two_operands_loc (loc, type, integer_zero_node, arg0, arg1);
10110       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg0, arg1);
10111     }
10112
10113   code = HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))) ? unordered_code
10114                                                    : ordered_code;
10115   return fold_build1_loc (loc, TRUTH_NOT_EXPR, type,
10116                       fold_build2_loc (loc, code, type, arg0, arg1));
10117 }
10118
10119 /* Fold a call to built-in function FNDECL with 0 arguments.
10120    IGNORE is true if the result of the function call is ignored.  This
10121    function returns NULL_TREE if no simplification was possible.  */
10122
10123 static tree
10124 fold_builtin_0 (location_t loc, tree fndecl, bool ignore ATTRIBUTE_UNUSED)
10125 {
10126   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10127   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10128   switch (fcode)
10129     {
10130     CASE_FLT_FN (BUILT_IN_INF):
10131     case BUILT_IN_INFD32:
10132     case BUILT_IN_INFD64:
10133     case BUILT_IN_INFD128:
10134       return fold_builtin_inf (loc, type, true);
10135
10136     CASE_FLT_FN (BUILT_IN_HUGE_VAL):
10137       return fold_builtin_inf (loc, type, false);
10138
10139     case BUILT_IN_CLASSIFY_TYPE:
10140       return fold_builtin_classify_type (NULL_TREE);
10141
10142     default:
10143       break;
10144     }
10145   return NULL_TREE;
10146 }
10147
10148 /* Fold a call to built-in function FNDECL with 1 argument, ARG0.
10149    IGNORE is true if the result of the function call is ignored.  This
10150    function returns NULL_TREE if no simplification was possible.  */
10151
10152 static tree
10153 fold_builtin_1 (location_t loc, tree fndecl, tree arg0, bool ignore)
10154 {
10155   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10156   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10157   switch (fcode)
10158     {
10159     case BUILT_IN_CONSTANT_P:
10160       {
10161         tree val = fold_builtin_constant_p (arg0);
10162
10163         /* Gimplification will pull the CALL_EXPR for the builtin out of
10164            an if condition.  When not optimizing, we'll not CSE it back.
10165            To avoid link error types of regressions, return false now.  */
10166         if (!val && !optimize)
10167           val = integer_zero_node;
10168
10169         return val;
10170       }
10171
10172     case BUILT_IN_CLASSIFY_TYPE:
10173       return fold_builtin_classify_type (arg0);
10174
10175     case BUILT_IN_STRLEN:
10176       return fold_builtin_strlen (loc, type, arg0);
10177
10178     CASE_FLT_FN (BUILT_IN_FABS):
10179       return fold_builtin_fabs (loc, arg0, type);
10180
10181     case BUILT_IN_ABS:
10182     case BUILT_IN_LABS:
10183     case BUILT_IN_LLABS:
10184     case BUILT_IN_IMAXABS:
10185       return fold_builtin_abs (loc, arg0, type);
10186
10187     CASE_FLT_FN (BUILT_IN_CONJ):
10188       if (validate_arg (arg0, COMPLEX_TYPE)
10189         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10190         return fold_build1_loc (loc, CONJ_EXPR, type, arg0);
10191     break;
10192
10193     CASE_FLT_FN (BUILT_IN_CREAL):
10194       if (validate_arg (arg0, COMPLEX_TYPE)
10195         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10196         return non_lvalue_loc (loc, fold_build1_loc (loc, REALPART_EXPR, type, arg0));;
10197     break;
10198
10199     CASE_FLT_FN (BUILT_IN_CIMAG):
10200       if (validate_arg (arg0, COMPLEX_TYPE)
10201           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10202         return non_lvalue_loc (loc, fold_build1_loc (loc, IMAGPART_EXPR, type, arg0));
10203     break;
10204
10205     CASE_FLT_FN (BUILT_IN_CCOS):
10206       return fold_builtin_ccos(loc, arg0, type, fndecl, /*hyper=*/ false);
10207
10208     CASE_FLT_FN (BUILT_IN_CCOSH):
10209       return fold_builtin_ccos(loc, arg0, type, fndecl, /*hyper=*/ true);
10210
10211     CASE_FLT_FN (BUILT_IN_CPROJ):
10212       return fold_builtin_cproj(loc, arg0, type);
10213
10214     CASE_FLT_FN (BUILT_IN_CSIN):
10215       if (validate_arg (arg0, COMPLEX_TYPE)
10216           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10217         return do_mpc_arg1 (arg0, type, mpc_sin);
10218     break;
10219
10220     CASE_FLT_FN (BUILT_IN_CSINH):
10221       if (validate_arg (arg0, COMPLEX_TYPE)
10222           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10223         return do_mpc_arg1 (arg0, type, mpc_sinh);
10224     break;
10225
10226     CASE_FLT_FN (BUILT_IN_CTAN):
10227       if (validate_arg (arg0, COMPLEX_TYPE)
10228           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10229         return do_mpc_arg1 (arg0, type, mpc_tan);
10230     break;
10231
10232     CASE_FLT_FN (BUILT_IN_CTANH):
10233       if (validate_arg (arg0, COMPLEX_TYPE)
10234           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10235         return do_mpc_arg1 (arg0, type, mpc_tanh);
10236     break;
10237
10238     CASE_FLT_FN (BUILT_IN_CLOG):
10239       if (validate_arg (arg0, COMPLEX_TYPE)
10240           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10241         return do_mpc_arg1 (arg0, type, mpc_log);
10242     break;
10243
10244     CASE_FLT_FN (BUILT_IN_CSQRT):
10245       if (validate_arg (arg0, COMPLEX_TYPE)
10246           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10247         return do_mpc_arg1 (arg0, type, mpc_sqrt);
10248     break;
10249
10250     CASE_FLT_FN (BUILT_IN_CASIN):
10251       if (validate_arg (arg0, COMPLEX_TYPE)
10252           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10253         return do_mpc_arg1 (arg0, type, mpc_asin);
10254     break;
10255
10256     CASE_FLT_FN (BUILT_IN_CACOS):
10257       if (validate_arg (arg0, COMPLEX_TYPE)
10258           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10259         return do_mpc_arg1 (arg0, type, mpc_acos);
10260     break;
10261
10262     CASE_FLT_FN (BUILT_IN_CATAN):
10263       if (validate_arg (arg0, COMPLEX_TYPE)
10264           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10265         return do_mpc_arg1 (arg0, type, mpc_atan);
10266     break;
10267
10268     CASE_FLT_FN (BUILT_IN_CASINH):
10269       if (validate_arg (arg0, COMPLEX_TYPE)
10270           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10271         return do_mpc_arg1 (arg0, type, mpc_asinh);
10272     break;
10273
10274     CASE_FLT_FN (BUILT_IN_CACOSH):
10275       if (validate_arg (arg0, COMPLEX_TYPE)
10276           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10277         return do_mpc_arg1 (arg0, type, mpc_acosh);
10278     break;
10279
10280     CASE_FLT_FN (BUILT_IN_CATANH):
10281       if (validate_arg (arg0, COMPLEX_TYPE)
10282           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10283         return do_mpc_arg1 (arg0, type, mpc_atanh);
10284     break;
10285
10286     CASE_FLT_FN (BUILT_IN_CABS):
10287       return fold_builtin_cabs (loc, arg0, type, fndecl);
10288
10289     CASE_FLT_FN (BUILT_IN_CARG):
10290       return fold_builtin_carg (loc, arg0, type);
10291
10292     CASE_FLT_FN (BUILT_IN_SQRT):
10293       return fold_builtin_sqrt (loc, arg0, type);
10294
10295     CASE_FLT_FN (BUILT_IN_CBRT):
10296       return fold_builtin_cbrt (loc, arg0, type);
10297
10298     CASE_FLT_FN (BUILT_IN_ASIN):
10299       if (validate_arg (arg0, REAL_TYPE))
10300         return do_mpfr_arg1 (arg0, type, mpfr_asin,
10301                              &dconstm1, &dconst1, true);
10302     break;
10303
10304     CASE_FLT_FN (BUILT_IN_ACOS):
10305       if (validate_arg (arg0, REAL_TYPE))
10306         return do_mpfr_arg1 (arg0, type, mpfr_acos,
10307                              &dconstm1, &dconst1, true);
10308     break;
10309
10310     CASE_FLT_FN (BUILT_IN_ATAN):
10311       if (validate_arg (arg0, REAL_TYPE))
10312         return do_mpfr_arg1 (arg0, type, mpfr_atan, NULL, NULL, 0);
10313     break;
10314
10315     CASE_FLT_FN (BUILT_IN_ASINH):
10316       if (validate_arg (arg0, REAL_TYPE))
10317         return do_mpfr_arg1 (arg0, type, mpfr_asinh, NULL, NULL, 0);
10318     break;
10319
10320     CASE_FLT_FN (BUILT_IN_ACOSH):
10321       if (validate_arg (arg0, REAL_TYPE))
10322         return do_mpfr_arg1 (arg0, type, mpfr_acosh,
10323                              &dconst1, NULL, true);
10324     break;
10325
10326     CASE_FLT_FN (BUILT_IN_ATANH):
10327       if (validate_arg (arg0, REAL_TYPE))
10328         return do_mpfr_arg1 (arg0, type, mpfr_atanh,
10329                              &dconstm1, &dconst1, false);
10330     break;
10331
10332     CASE_FLT_FN (BUILT_IN_SIN):
10333       if (validate_arg (arg0, REAL_TYPE))
10334         return do_mpfr_arg1 (arg0, type, mpfr_sin, NULL, NULL, 0);
10335     break;
10336
10337     CASE_FLT_FN (BUILT_IN_COS):
10338       return fold_builtin_cos (loc, arg0, type, fndecl);
10339
10340     CASE_FLT_FN (BUILT_IN_TAN):
10341       return fold_builtin_tan (arg0, type);
10342
10343     CASE_FLT_FN (BUILT_IN_CEXP):
10344       return fold_builtin_cexp (loc, arg0, type);
10345
10346     CASE_FLT_FN (BUILT_IN_CEXPI):
10347       if (validate_arg (arg0, REAL_TYPE))
10348         return do_mpfr_sincos (arg0, NULL_TREE, NULL_TREE);
10349     break;
10350
10351     CASE_FLT_FN (BUILT_IN_SINH):
10352       if (validate_arg (arg0, REAL_TYPE))
10353         return do_mpfr_arg1 (arg0, type, mpfr_sinh, NULL, NULL, 0);
10354     break;
10355
10356     CASE_FLT_FN (BUILT_IN_COSH):
10357       return fold_builtin_cosh (loc, arg0, type, fndecl);
10358
10359     CASE_FLT_FN (BUILT_IN_TANH):
10360       if (validate_arg (arg0, REAL_TYPE))
10361         return do_mpfr_arg1 (arg0, type, mpfr_tanh, NULL, NULL, 0);
10362     break;
10363
10364     CASE_FLT_FN (BUILT_IN_ERF):
10365       if (validate_arg (arg0, REAL_TYPE))
10366         return do_mpfr_arg1 (arg0, type, mpfr_erf, NULL, NULL, 0);
10367     break;
10368
10369     CASE_FLT_FN (BUILT_IN_ERFC):
10370       if (validate_arg (arg0, REAL_TYPE))
10371         return do_mpfr_arg1 (arg0, type, mpfr_erfc, NULL, NULL, 0);
10372     break;
10373
10374     CASE_FLT_FN (BUILT_IN_TGAMMA):
10375       if (validate_arg (arg0, REAL_TYPE))
10376         return do_mpfr_arg1 (arg0, type, mpfr_gamma, NULL, NULL, 0);
10377     break;
10378
10379     CASE_FLT_FN (BUILT_IN_EXP):
10380       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp);
10381
10382     CASE_FLT_FN (BUILT_IN_EXP2):
10383       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp2);
10384
10385     CASE_FLT_FN (BUILT_IN_EXP10):
10386     CASE_FLT_FN (BUILT_IN_POW10):
10387       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp10);
10388
10389     CASE_FLT_FN (BUILT_IN_EXPM1):
10390       if (validate_arg (arg0, REAL_TYPE))
10391         return do_mpfr_arg1 (arg0, type, mpfr_expm1, NULL, NULL, 0);
10392     break;
10393
10394     CASE_FLT_FN (BUILT_IN_LOG):
10395     return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log);
10396
10397     CASE_FLT_FN (BUILT_IN_LOG2):
10398       return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log2);
10399
10400     CASE_FLT_FN (BUILT_IN_LOG10):
10401       return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log10);
10402
10403     CASE_FLT_FN (BUILT_IN_LOG1P):
10404       if (validate_arg (arg0, REAL_TYPE))
10405         return do_mpfr_arg1 (arg0, type, mpfr_log1p,
10406                              &dconstm1, NULL, false);
10407     break;
10408
10409     CASE_FLT_FN (BUILT_IN_J0):
10410       if (validate_arg (arg0, REAL_TYPE))
10411         return do_mpfr_arg1 (arg0, type, mpfr_j0,
10412                              NULL, NULL, 0);
10413     break;
10414
10415     CASE_FLT_FN (BUILT_IN_J1):
10416       if (validate_arg (arg0, REAL_TYPE))
10417         return do_mpfr_arg1 (arg0, type, mpfr_j1,
10418                              NULL, NULL, 0);
10419     break;
10420
10421     CASE_FLT_FN (BUILT_IN_Y0):
10422       if (validate_arg (arg0, REAL_TYPE))
10423         return do_mpfr_arg1 (arg0, type, mpfr_y0,
10424                              &dconst0, NULL, false);
10425     break;
10426
10427     CASE_FLT_FN (BUILT_IN_Y1):
10428       if (validate_arg (arg0, REAL_TYPE))
10429         return do_mpfr_arg1 (arg0, type, mpfr_y1,
10430                              &dconst0, NULL, false);
10431     break;
10432
10433     CASE_FLT_FN (BUILT_IN_NAN):
10434     case BUILT_IN_NAND32:
10435     case BUILT_IN_NAND64:
10436     case BUILT_IN_NAND128:
10437       return fold_builtin_nan (arg0, type, true);
10438
10439     CASE_FLT_FN (BUILT_IN_NANS):
10440       return fold_builtin_nan (arg0, type, false);
10441
10442     CASE_FLT_FN (BUILT_IN_FLOOR):
10443       return fold_builtin_floor (loc, fndecl, arg0);
10444
10445     CASE_FLT_FN (BUILT_IN_CEIL):
10446       return fold_builtin_ceil (loc, fndecl, arg0);
10447
10448     CASE_FLT_FN (BUILT_IN_TRUNC):
10449       return fold_builtin_trunc (loc, fndecl, arg0);
10450
10451     CASE_FLT_FN (BUILT_IN_ROUND):
10452       return fold_builtin_round (loc, fndecl, arg0);
10453
10454     CASE_FLT_FN (BUILT_IN_NEARBYINT):
10455     CASE_FLT_FN (BUILT_IN_RINT):
10456       return fold_trunc_transparent_mathfn (loc, fndecl, arg0);
10457
10458     CASE_FLT_FN (BUILT_IN_ICEIL):
10459     CASE_FLT_FN (BUILT_IN_LCEIL):
10460     CASE_FLT_FN (BUILT_IN_LLCEIL):
10461     CASE_FLT_FN (BUILT_IN_LFLOOR):
10462     CASE_FLT_FN (BUILT_IN_IFLOOR):
10463     CASE_FLT_FN (BUILT_IN_LLFLOOR):
10464     CASE_FLT_FN (BUILT_IN_IROUND):
10465     CASE_FLT_FN (BUILT_IN_LROUND):
10466     CASE_FLT_FN (BUILT_IN_LLROUND):
10467       return fold_builtin_int_roundingfn (loc, fndecl, arg0);
10468
10469     CASE_FLT_FN (BUILT_IN_IRINT):
10470     CASE_FLT_FN (BUILT_IN_LRINT):
10471     CASE_FLT_FN (BUILT_IN_LLRINT):
10472       return fold_fixed_mathfn (loc, fndecl, arg0);
10473
10474     case BUILT_IN_BSWAP32:
10475     case BUILT_IN_BSWAP64:
10476       return fold_builtin_bswap (fndecl, arg0);
10477
10478     CASE_INT_FN (BUILT_IN_FFS):
10479     CASE_INT_FN (BUILT_IN_CLZ):
10480     CASE_INT_FN (BUILT_IN_CTZ):
10481     CASE_INT_FN (BUILT_IN_CLRSB):
10482     CASE_INT_FN (BUILT_IN_POPCOUNT):
10483     CASE_INT_FN (BUILT_IN_PARITY):
10484       return fold_builtin_bitop (fndecl, arg0);
10485
10486     CASE_FLT_FN (BUILT_IN_SIGNBIT):
10487       return fold_builtin_signbit (loc, arg0, type);
10488
10489     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
10490       return fold_builtin_significand (loc, arg0, type);
10491
10492     CASE_FLT_FN (BUILT_IN_ILOGB):
10493     CASE_FLT_FN (BUILT_IN_LOGB):
10494       return fold_builtin_logb (loc, arg0, type);
10495
10496     case BUILT_IN_ISASCII:
10497       return fold_builtin_isascii (loc, arg0);
10498
10499     case BUILT_IN_TOASCII:
10500       return fold_builtin_toascii (loc, arg0);
10501
10502     case BUILT_IN_ISDIGIT:
10503       return fold_builtin_isdigit (loc, arg0);
10504
10505     CASE_FLT_FN (BUILT_IN_FINITE):
10506     case BUILT_IN_FINITED32:
10507     case BUILT_IN_FINITED64:
10508     case BUILT_IN_FINITED128:
10509     case BUILT_IN_ISFINITE:
10510       {
10511         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISFINITE);
10512         if (ret)
10513           return ret;
10514         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10515       }
10516
10517     CASE_FLT_FN (BUILT_IN_ISINF):
10518     case BUILT_IN_ISINFD32:
10519     case BUILT_IN_ISINFD64:
10520     case BUILT_IN_ISINFD128:
10521       {
10522         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF);
10523         if (ret)
10524           return ret;
10525         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10526       }
10527
10528     case BUILT_IN_ISNORMAL:
10529       return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10530
10531     case BUILT_IN_ISINF_SIGN:
10532       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF_SIGN);
10533
10534     CASE_FLT_FN (BUILT_IN_ISNAN):
10535     case BUILT_IN_ISNAND32:
10536     case BUILT_IN_ISNAND64:
10537     case BUILT_IN_ISNAND128:
10538       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISNAN);
10539
10540     case BUILT_IN_PRINTF:
10541     case BUILT_IN_PRINTF_UNLOCKED:
10542     case BUILT_IN_VPRINTF:
10543       return fold_builtin_printf (loc, fndecl, arg0, NULL_TREE, ignore, fcode);
10544
10545     case BUILT_IN_FREE:
10546       if (integer_zerop (arg0))
10547         return build_empty_stmt (loc);
10548       break;
10549
10550     default:
10551       break;
10552     }
10553
10554   return NULL_TREE;
10555
10556 }
10557
10558 /* Fold a call to built-in function FNDECL with 2 arguments, ARG0 and ARG1.
10559    IGNORE is true if the result of the function call is ignored.  This
10560    function returns NULL_TREE if no simplification was possible.  */
10561
10562 static tree
10563 fold_builtin_2 (location_t loc, tree fndecl, tree arg0, tree arg1, bool ignore)
10564 {
10565   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10566   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10567
10568   switch (fcode)
10569     {
10570     CASE_FLT_FN (BUILT_IN_JN):
10571       if (validate_arg (arg0, INTEGER_TYPE)
10572           && validate_arg (arg1, REAL_TYPE))
10573         return do_mpfr_bessel_n (arg0, arg1, type, mpfr_jn, NULL, 0);
10574     break;
10575
10576     CASE_FLT_FN (BUILT_IN_YN):
10577       if (validate_arg (arg0, INTEGER_TYPE)
10578           && validate_arg (arg1, REAL_TYPE))
10579         return do_mpfr_bessel_n (arg0, arg1, type, mpfr_yn,
10580                                  &dconst0, false);
10581     break;
10582
10583     CASE_FLT_FN (BUILT_IN_DREM):
10584     CASE_FLT_FN (BUILT_IN_REMAINDER):
10585       if (validate_arg (arg0, REAL_TYPE)
10586           && validate_arg(arg1, REAL_TYPE))
10587         return do_mpfr_arg2 (arg0, arg1, type, mpfr_remainder);
10588     break;
10589
10590     CASE_FLT_FN_REENT (BUILT_IN_GAMMA): /* GAMMA_R */
10591     CASE_FLT_FN_REENT (BUILT_IN_LGAMMA): /* LGAMMA_R */
10592       if (validate_arg (arg0, REAL_TYPE)
10593           && validate_arg(arg1, POINTER_TYPE))
10594         return do_mpfr_lgamma_r (arg0, arg1, type);
10595     break;
10596
10597     CASE_FLT_FN (BUILT_IN_ATAN2):
10598       if (validate_arg (arg0, REAL_TYPE)
10599           && validate_arg(arg1, REAL_TYPE))
10600         return do_mpfr_arg2 (arg0, arg1, type, mpfr_atan2);
10601     break;
10602
10603     CASE_FLT_FN (BUILT_IN_FDIM):
10604       if (validate_arg (arg0, REAL_TYPE)
10605           && validate_arg(arg1, REAL_TYPE))
10606         return do_mpfr_arg2 (arg0, arg1, type, mpfr_dim);
10607     break;
10608
10609     CASE_FLT_FN (BUILT_IN_HYPOT):
10610       return fold_builtin_hypot (loc, fndecl, arg0, arg1, type);
10611
10612     CASE_FLT_FN (BUILT_IN_CPOW):
10613       if (validate_arg (arg0, COMPLEX_TYPE)
10614           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE
10615           && validate_arg (arg1, COMPLEX_TYPE)
10616           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg1))) == REAL_TYPE)
10617         return do_mpc_arg2 (arg0, arg1, type, /*do_nonfinite=*/ 0, mpc_pow);
10618     break;
10619
10620     CASE_FLT_FN (BUILT_IN_LDEXP):
10621       return fold_builtin_load_exponent (loc, arg0, arg1, type, /*ldexp=*/true);
10622     CASE_FLT_FN (BUILT_IN_SCALBN):
10623     CASE_FLT_FN (BUILT_IN_SCALBLN):
10624       return fold_builtin_load_exponent (loc, arg0, arg1,
10625                                          type, /*ldexp=*/false);
10626
10627     CASE_FLT_FN (BUILT_IN_FREXP):
10628       return fold_builtin_frexp (loc, arg0, arg1, type);
10629
10630     CASE_FLT_FN (BUILT_IN_MODF):
10631       return fold_builtin_modf (loc, arg0, arg1, type);
10632
10633     case BUILT_IN_BZERO:
10634       return fold_builtin_bzero (loc, arg0, arg1, ignore);
10635
10636     case BUILT_IN_FPUTS:
10637       return fold_builtin_fputs (loc, arg0, arg1, ignore, false, NULL_TREE);
10638
10639     case BUILT_IN_FPUTS_UNLOCKED:
10640       return fold_builtin_fputs (loc, arg0, arg1, ignore, true, NULL_TREE);
10641
10642     case BUILT_IN_STRSTR:
10643       return fold_builtin_strstr (loc, arg0, arg1, type);
10644
10645     case BUILT_IN_STRCAT:
10646       return fold_builtin_strcat (loc, arg0, arg1);
10647
10648     case BUILT_IN_STRSPN:
10649       return fold_builtin_strspn (loc, arg0, arg1);
10650
10651     case BUILT_IN_STRCSPN:
10652       return fold_builtin_strcspn (loc, arg0, arg1);
10653
10654     case BUILT_IN_STRCHR:
10655     case BUILT_IN_INDEX:
10656       return fold_builtin_strchr (loc, arg0, arg1, type);
10657
10658     case BUILT_IN_STRRCHR:
10659     case BUILT_IN_RINDEX:
10660       return fold_builtin_strrchr (loc, arg0, arg1, type);
10661
10662     case BUILT_IN_STRCPY:
10663       return fold_builtin_strcpy (loc, fndecl, arg0, arg1, NULL_TREE);
10664
10665     case BUILT_IN_STPCPY:
10666       if (ignore)
10667         {
10668           tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
10669           if (!fn)
10670             break;
10671
10672           return build_call_expr_loc (loc, fn, 2, arg0, arg1);
10673         }
10674       else
10675         return fold_builtin_stpcpy (loc, fndecl, arg0, arg1);
10676       break;
10677
10678     case BUILT_IN_STRCMP:
10679       return fold_builtin_strcmp (loc, arg0, arg1);
10680
10681     case BUILT_IN_STRPBRK:
10682       return fold_builtin_strpbrk (loc, arg0, arg1, type);
10683
10684     case BUILT_IN_EXPECT:
10685       return fold_builtin_expect (loc, arg0, arg1);
10686
10687     CASE_FLT_FN (BUILT_IN_POW):
10688       return fold_builtin_pow (loc, fndecl, arg0, arg1, type);
10689
10690     CASE_FLT_FN (BUILT_IN_POWI):
10691       return fold_builtin_powi (loc, fndecl, arg0, arg1, type);
10692
10693     CASE_FLT_FN (BUILT_IN_COPYSIGN):
10694       return fold_builtin_copysign (loc, fndecl, arg0, arg1, type);
10695
10696     CASE_FLT_FN (BUILT_IN_FMIN):
10697       return fold_builtin_fmin_fmax (loc, arg0, arg1, type, /*max=*/false);
10698
10699     CASE_FLT_FN (BUILT_IN_FMAX):
10700       return fold_builtin_fmin_fmax (loc, arg0, arg1, type, /*max=*/true);
10701
10702     case BUILT_IN_ISGREATER:
10703       return fold_builtin_unordered_cmp (loc, fndecl,
10704                                          arg0, arg1, UNLE_EXPR, LE_EXPR);
10705     case BUILT_IN_ISGREATEREQUAL:
10706       return fold_builtin_unordered_cmp (loc, fndecl,
10707                                          arg0, arg1, UNLT_EXPR, LT_EXPR);
10708     case BUILT_IN_ISLESS:
10709       return fold_builtin_unordered_cmp (loc, fndecl,
10710                                          arg0, arg1, UNGE_EXPR, GE_EXPR);
10711     case BUILT_IN_ISLESSEQUAL:
10712       return fold_builtin_unordered_cmp (loc, fndecl,
10713                                          arg0, arg1, UNGT_EXPR, GT_EXPR);
10714     case BUILT_IN_ISLESSGREATER:
10715       return fold_builtin_unordered_cmp (loc, fndecl,
10716                                          arg0, arg1, UNEQ_EXPR, EQ_EXPR);
10717     case BUILT_IN_ISUNORDERED:
10718       return fold_builtin_unordered_cmp (loc, fndecl,
10719                                          arg0, arg1, UNORDERED_EXPR,
10720                                          NOP_EXPR);
10721
10722       /* We do the folding for va_start in the expander.  */
10723     case BUILT_IN_VA_START:
10724       break;
10725
10726     case BUILT_IN_SPRINTF:
10727       return fold_builtin_sprintf (loc, arg0, arg1, NULL_TREE, ignore);
10728
10729     case BUILT_IN_OBJECT_SIZE:
10730       return fold_builtin_object_size (arg0, arg1);
10731
10732     case BUILT_IN_PRINTF:
10733     case BUILT_IN_PRINTF_UNLOCKED:
10734     case BUILT_IN_VPRINTF:
10735       return fold_builtin_printf (loc, fndecl, arg0, arg1, ignore, fcode);
10736
10737     case BUILT_IN_PRINTF_CHK:
10738     case BUILT_IN_VPRINTF_CHK:
10739       if (!validate_arg (arg0, INTEGER_TYPE)
10740           || TREE_SIDE_EFFECTS (arg0))
10741         return NULL_TREE;
10742       else
10743         return fold_builtin_printf (loc, fndecl,
10744                                     arg1, NULL_TREE, ignore, fcode);
10745     break;
10746
10747     case BUILT_IN_FPRINTF:
10748     case BUILT_IN_FPRINTF_UNLOCKED:
10749     case BUILT_IN_VFPRINTF:
10750       return fold_builtin_fprintf (loc, fndecl, arg0, arg1, NULL_TREE,
10751                                    ignore, fcode);
10752
10753     case BUILT_IN_ATOMIC_ALWAYS_LOCK_FREE:
10754       return fold_builtin_atomic_always_lock_free (arg0, arg1);
10755
10756     case BUILT_IN_ATOMIC_IS_LOCK_FREE:
10757       return fold_builtin_atomic_is_lock_free (arg0, arg1);
10758
10759     default:
10760       break;
10761     }
10762   return NULL_TREE;
10763 }
10764
10765 /* Fold a call to built-in function FNDECL with 3 arguments, ARG0, ARG1,
10766    and ARG2.  IGNORE is true if the result of the function call is ignored.
10767    This function returns NULL_TREE if no simplification was possible.  */
10768
10769 static tree
10770 fold_builtin_3 (location_t loc, tree fndecl,
10771                 tree arg0, tree arg1, tree arg2, bool ignore)
10772 {
10773   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10774   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10775   switch (fcode)
10776     {
10777
10778     CASE_FLT_FN (BUILT_IN_SINCOS):
10779       return fold_builtin_sincos (loc, arg0, arg1, arg2);
10780
10781     CASE_FLT_FN (BUILT_IN_FMA):
10782       return fold_builtin_fma (loc, arg0, arg1, arg2, type);
10783     break;
10784
10785     CASE_FLT_FN (BUILT_IN_REMQUO):
10786       if (validate_arg (arg0, REAL_TYPE)
10787           && validate_arg(arg1, REAL_TYPE)
10788           && validate_arg(arg2, POINTER_TYPE))
10789         return do_mpfr_remquo (arg0, arg1, arg2);
10790     break;
10791
10792     case BUILT_IN_MEMSET:
10793       return fold_builtin_memset (loc, arg0, arg1, arg2, type, ignore);
10794
10795     case BUILT_IN_BCOPY:
10796       return fold_builtin_memory_op (loc, arg1, arg0, arg2,
10797                                      void_type_node, true, /*endp=*/3);
10798
10799     case BUILT_IN_MEMCPY:
10800       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10801                                      type, ignore, /*endp=*/0);
10802
10803     case BUILT_IN_MEMPCPY:
10804       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10805                                      type, ignore, /*endp=*/1);
10806
10807     case BUILT_IN_MEMMOVE:
10808       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10809                                      type, ignore, /*endp=*/3);
10810
10811     case BUILT_IN_STRNCAT:
10812       return fold_builtin_strncat (loc, arg0, arg1, arg2);
10813
10814     case BUILT_IN_STRNCPY:
10815       return fold_builtin_strncpy (loc, fndecl, arg0, arg1, arg2, NULL_TREE);
10816
10817     case BUILT_IN_STRNCMP:
10818       return fold_builtin_strncmp (loc, arg0, arg1, arg2);
10819
10820     case BUILT_IN_MEMCHR:
10821       return fold_builtin_memchr (loc, arg0, arg1, arg2, type);
10822
10823     case BUILT_IN_BCMP:
10824     case BUILT_IN_MEMCMP:
10825       return fold_builtin_memcmp (loc, arg0, arg1, arg2);;
10826
10827     case BUILT_IN_SPRINTF:
10828       return fold_builtin_sprintf (loc, arg0, arg1, arg2, ignore);
10829
10830     case BUILT_IN_SNPRINTF:
10831       return fold_builtin_snprintf (loc, arg0, arg1, arg2, NULL_TREE, ignore);
10832
10833     case BUILT_IN_STRCPY_CHK:
10834     case BUILT_IN_STPCPY_CHK:
10835       return fold_builtin_stxcpy_chk (loc, fndecl, arg0, arg1, arg2, NULL_TREE,
10836                                       ignore, fcode);
10837
10838     case BUILT_IN_STRCAT_CHK:
10839       return fold_builtin_strcat_chk (loc, fndecl, arg0, arg1, arg2);
10840
10841     case BUILT_IN_PRINTF_CHK:
10842     case BUILT_IN_VPRINTF_CHK:
10843       if (!validate_arg (arg0, INTEGER_TYPE)
10844           || TREE_SIDE_EFFECTS (arg0))
10845         return NULL_TREE;
10846       else
10847         return fold_builtin_printf (loc, fndecl, arg1, arg2, ignore, fcode);
10848     break;
10849
10850     case BUILT_IN_FPRINTF:
10851     case BUILT_IN_FPRINTF_UNLOCKED:
10852     case BUILT_IN_VFPRINTF:
10853       return fold_builtin_fprintf (loc, fndecl, arg0, arg1, arg2,
10854                                    ignore, fcode);
10855
10856     case BUILT_IN_FPRINTF_CHK:
10857     case BUILT_IN_VFPRINTF_CHK:
10858       if (!validate_arg (arg1, INTEGER_TYPE)
10859           || TREE_SIDE_EFFECTS (arg1))
10860         return NULL_TREE;
10861       else
10862         return fold_builtin_fprintf (loc, fndecl, arg0, arg2, NULL_TREE,
10863                                      ignore, fcode);
10864
10865     default:
10866       break;
10867     }
10868   return NULL_TREE;
10869 }
10870
10871 /* Fold a call to built-in function FNDECL with 4 arguments, ARG0, ARG1,
10872    ARG2, and ARG3.  IGNORE is true if the result of the function call is
10873    ignored.  This function returns NULL_TREE if no simplification was
10874    possible.  */
10875
10876 static tree
10877 fold_builtin_4 (location_t loc, tree fndecl,
10878                 tree arg0, tree arg1, tree arg2, tree arg3, bool ignore)
10879 {
10880   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10881
10882   switch (fcode)
10883     {
10884     case BUILT_IN_MEMCPY_CHK:
10885     case BUILT_IN_MEMPCPY_CHK:
10886     case BUILT_IN_MEMMOVE_CHK:
10887     case BUILT_IN_MEMSET_CHK:
10888       return fold_builtin_memory_chk (loc, fndecl, arg0, arg1, arg2, arg3,
10889                                       NULL_TREE, ignore,
10890                                       DECL_FUNCTION_CODE (fndecl));
10891
10892     case BUILT_IN_STRNCPY_CHK:
10893       return fold_builtin_strncpy_chk (loc, arg0, arg1, arg2, arg3, NULL_TREE);
10894
10895     case BUILT_IN_STRNCAT_CHK:
10896       return fold_builtin_strncat_chk (loc, fndecl, arg0, arg1, arg2, arg3);
10897
10898     case BUILT_IN_SNPRINTF:
10899       return fold_builtin_snprintf (loc, arg0, arg1, arg2, arg3, ignore);
10900
10901     case BUILT_IN_FPRINTF_CHK:
10902     case BUILT_IN_VFPRINTF_CHK:
10903       if (!validate_arg (arg1, INTEGER_TYPE)
10904           || TREE_SIDE_EFFECTS (arg1))
10905         return NULL_TREE;
10906       else
10907         return fold_builtin_fprintf (loc, fndecl, arg0, arg2, arg3,
10908                                      ignore, fcode);
10909     break;
10910
10911     default:
10912       break;
10913     }
10914   return NULL_TREE;
10915 }
10916
10917 /* Fold a call to built-in function FNDECL.  ARGS is an array of NARGS
10918     arguments, where NARGS <= 4.  IGNORE is true if the result of the
10919     function call is ignored.  This function returns NULL_TREE if no
10920     simplification was possible.  Note that this only folds builtins with
10921     fixed argument patterns.  Foldings that do varargs-to-varargs
10922     transformations, or that match calls with more than 4 arguments,
10923     need to be handled with fold_builtin_varargs instead.  */
10924
10925 #define MAX_ARGS_TO_FOLD_BUILTIN 4
10926
10927 static tree
10928 fold_builtin_n (location_t loc, tree fndecl, tree *args, int nargs, bool ignore)
10929 {
10930   tree ret = NULL_TREE;
10931
10932   switch (nargs)
10933     {
10934     case 0:
10935       ret = fold_builtin_0 (loc, fndecl, ignore);
10936       break;
10937     case 1:
10938       ret = fold_builtin_1 (loc, fndecl, args[0], ignore);
10939       break;
10940     case 2:
10941       ret = fold_builtin_2 (loc, fndecl, args[0], args[1], ignore);
10942       break;
10943     case 3:
10944       ret = fold_builtin_3 (loc, fndecl, args[0], args[1], args[2], ignore);
10945       break;
10946     case 4:
10947       ret = fold_builtin_4 (loc, fndecl, args[0], args[1], args[2], args[3],
10948                             ignore);
10949       break;
10950     default:
10951       break;
10952     }
10953   if (ret)
10954     {
10955       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
10956       SET_EXPR_LOCATION (ret, loc);
10957       TREE_NO_WARNING (ret) = 1;
10958       return ret;
10959     }
10960   return NULL_TREE;
10961 }
10962
10963 /* Builtins with folding operations that operate on "..." arguments
10964    need special handling; we need to store the arguments in a convenient
10965    data structure before attempting any folding.  Fortunately there are
10966    only a few builtins that fall into this category.  FNDECL is the
10967    function, EXP is the CALL_EXPR for the call, and IGNORE is true if the
10968    result of the function call is ignored.  */
10969
10970 static tree
10971 fold_builtin_varargs (location_t loc, tree fndecl, tree exp,
10972                       bool ignore ATTRIBUTE_UNUSED)
10973 {
10974   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10975   tree ret = NULL_TREE;
10976
10977   switch (fcode)
10978     {
10979     case BUILT_IN_SPRINTF_CHK:
10980     case BUILT_IN_VSPRINTF_CHK:
10981       ret = fold_builtin_sprintf_chk (loc, exp, fcode);
10982       break;
10983
10984     case BUILT_IN_SNPRINTF_CHK:
10985     case BUILT_IN_VSNPRINTF_CHK:
10986       ret = fold_builtin_snprintf_chk (loc, exp, NULL_TREE, fcode);
10987       break;
10988
10989     case BUILT_IN_FPCLASSIFY:
10990       ret = fold_builtin_fpclassify (loc, exp);
10991       break;
10992
10993     default:
10994       break;
10995     }
10996   if (ret)
10997     {
10998       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
10999       SET_EXPR_LOCATION (ret, loc);
11000       TREE_NO_WARNING (ret) = 1;
11001       return ret;
11002     }
11003   return NULL_TREE;
11004 }
11005
11006 /* Return true if FNDECL shouldn't be folded right now.
11007    If a built-in function has an inline attribute always_inline
11008    wrapper, defer folding it after always_inline functions have
11009    been inlined, otherwise e.g. -D_FORTIFY_SOURCE checking
11010    might not be performed.  */
11011
11012 bool
11013 avoid_folding_inline_builtin (tree fndecl)
11014 {
11015   return (DECL_DECLARED_INLINE_P (fndecl)
11016           && DECL_DISREGARD_INLINE_LIMITS (fndecl)
11017           && cfun
11018           && !cfun->always_inline_functions_inlined
11019           && lookup_attribute ("always_inline", DECL_ATTRIBUTES (fndecl)));
11020 }
11021
11022 /* A wrapper function for builtin folding that prevents warnings for
11023    "statement without effect" and the like, caused by removing the
11024    call node earlier than the warning is generated.  */
11025
11026 tree
11027 fold_call_expr (location_t loc, tree exp, bool ignore)
11028 {
11029   tree ret = NULL_TREE;
11030   tree fndecl = get_callee_fndecl (exp);
11031   if (fndecl
11032       && TREE_CODE (fndecl) == FUNCTION_DECL
11033       && DECL_BUILT_IN (fndecl)
11034       /* If CALL_EXPR_VA_ARG_PACK is set, the arguments aren't finalized
11035          yet.  Defer folding until we see all the arguments
11036          (after inlining).  */
11037       && !CALL_EXPR_VA_ARG_PACK (exp))
11038     {
11039       int nargs = call_expr_nargs (exp);
11040
11041       /* Before gimplification CALL_EXPR_VA_ARG_PACK is not set, but
11042          instead last argument is __builtin_va_arg_pack ().  Defer folding
11043          even in that case, until arguments are finalized.  */
11044       if (nargs && TREE_CODE (CALL_EXPR_ARG (exp, nargs - 1)) == CALL_EXPR)
11045         {
11046           tree fndecl2 = get_callee_fndecl (CALL_EXPR_ARG (exp, nargs - 1));
11047           if (fndecl2
11048               && TREE_CODE (fndecl2) == FUNCTION_DECL
11049               && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
11050               && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
11051             return NULL_TREE;
11052         }
11053
11054       if (avoid_folding_inline_builtin (fndecl))
11055         return NULL_TREE;
11056
11057       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
11058         return targetm.fold_builtin (fndecl, call_expr_nargs (exp),
11059                                      CALL_EXPR_ARGP (exp), ignore);
11060       else
11061         {
11062           if (nargs <= MAX_ARGS_TO_FOLD_BUILTIN)
11063             {
11064               tree *args = CALL_EXPR_ARGP (exp);
11065               ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
11066             }
11067           if (!ret)
11068             ret = fold_builtin_varargs (loc, fndecl, exp, ignore);
11069           if (ret)
11070             return ret;
11071         }
11072     }
11073   return NULL_TREE;
11074 }
11075
11076 /* Conveniently construct a function call expression.  FNDECL names the
11077    function to be called and N arguments are passed in the array
11078    ARGARRAY.  */
11079
11080 tree
11081 build_call_expr_loc_array (location_t loc, tree fndecl, int n, tree *argarray)
11082 {
11083   tree fntype = TREE_TYPE (fndecl);
11084   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
11085  
11086   return fold_builtin_call_array (loc, TREE_TYPE (fntype), fn, n, argarray);
11087 }
11088
11089 /* Conveniently construct a function call expression.  FNDECL names the
11090    function to be called and the arguments are passed in the vector
11091    VEC.  */
11092
11093 tree
11094 build_call_expr_loc_vec (location_t loc, tree fndecl, VEC(tree,gc) *vec)
11095 {
11096   return build_call_expr_loc_array (loc, fndecl, VEC_length (tree, vec),
11097                                     VEC_address (tree, vec));
11098 }
11099
11100
11101 /* Conveniently construct a function call expression.  FNDECL names the
11102    function to be called, N is the number of arguments, and the "..."
11103    parameters are the argument expressions.  */
11104
11105 tree
11106 build_call_expr_loc (location_t loc, tree fndecl, int n, ...)
11107 {
11108   va_list ap;
11109   tree *argarray = XALLOCAVEC (tree, n);
11110   int i;
11111
11112   va_start (ap, n);
11113   for (i = 0; i < n; i++)
11114     argarray[i] = va_arg (ap, tree);
11115   va_end (ap);
11116   return build_call_expr_loc_array (loc, fndecl, n, argarray);
11117 }
11118
11119 /* Like build_call_expr_loc (UNKNOWN_LOCATION, ...).  Duplicated because
11120    varargs macros aren't supported by all bootstrap compilers.  */
11121
11122 tree
11123 build_call_expr (tree fndecl, int n, ...)
11124 {
11125   va_list ap;
11126   tree *argarray = XALLOCAVEC (tree, n);
11127   int i;
11128
11129   va_start (ap, n);
11130   for (i = 0; i < n; i++)
11131     argarray[i] = va_arg (ap, tree);
11132   va_end (ap);
11133   return build_call_expr_loc_array (UNKNOWN_LOCATION, fndecl, n, argarray);
11134 }
11135
11136 /* Construct a CALL_EXPR with type TYPE with FN as the function expression.
11137    N arguments are passed in the array ARGARRAY.  */
11138
11139 tree
11140 fold_builtin_call_array (location_t loc, tree type,
11141                          tree fn,
11142                          int n,
11143                          tree *argarray)
11144 {
11145   tree ret = NULL_TREE;
11146    tree exp;
11147
11148   if (TREE_CODE (fn) == ADDR_EXPR)
11149   {
11150     tree fndecl = TREE_OPERAND (fn, 0);
11151     if (TREE_CODE (fndecl) == FUNCTION_DECL
11152         && DECL_BUILT_IN (fndecl))
11153       {
11154         /* If last argument is __builtin_va_arg_pack (), arguments to this
11155            function are not finalized yet.  Defer folding until they are.  */
11156         if (n && TREE_CODE (argarray[n - 1]) == CALL_EXPR)
11157           {
11158             tree fndecl2 = get_callee_fndecl (argarray[n - 1]);
11159             if (fndecl2
11160                 && TREE_CODE (fndecl2) == FUNCTION_DECL
11161                 && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
11162                 && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
11163               return build_call_array_loc (loc, type, fn, n, argarray);
11164           }
11165         if (avoid_folding_inline_builtin (fndecl))
11166           return build_call_array_loc (loc, type, fn, n, argarray);
11167         if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
11168           {
11169             ret = targetm.fold_builtin (fndecl, n, argarray, false);
11170             if (ret)
11171               return ret;
11172
11173             return build_call_array_loc (loc, type, fn, n, argarray);
11174           }
11175         else if (n <= MAX_ARGS_TO_FOLD_BUILTIN)
11176           {
11177             /* First try the transformations that don't require consing up
11178                an exp.  */
11179             ret = fold_builtin_n (loc, fndecl, argarray, n, false);
11180             if (ret)
11181               return ret;
11182           }
11183
11184         /* If we got this far, we need to build an exp.  */
11185         exp = build_call_array_loc (loc, type, fn, n, argarray);
11186         ret = fold_builtin_varargs (loc, fndecl, exp, false);
11187         return ret ? ret : exp;
11188       }
11189   }
11190
11191   return build_call_array_loc (loc, type, fn, n, argarray);
11192 }
11193
11194 /* Construct a new CALL_EXPR to FNDECL using the tail of the argument
11195    list ARGS along with N new arguments in NEWARGS.  SKIP is the number
11196    of arguments in ARGS to be omitted.  OLDNARGS is the number of
11197    elements in ARGS.  */
11198
11199 static tree
11200 rewrite_call_expr_valist (location_t loc, int oldnargs, tree *args,
11201                           int skip, tree fndecl, int n, va_list newargs)
11202 {
11203   int nargs = oldnargs - skip + n;
11204   tree *buffer;
11205
11206   if (n > 0)
11207     {
11208       int i, j;
11209
11210       buffer = XALLOCAVEC (tree, nargs);
11211       for (i = 0; i < n; i++)
11212         buffer[i] = va_arg (newargs, tree);
11213       for (j = skip; j < oldnargs; j++, i++)
11214         buffer[i] = args[j];
11215     }
11216   else
11217     buffer = args + skip;
11218
11219   return build_call_expr_loc_array (loc, fndecl, nargs, buffer);
11220 }
11221
11222 /* Construct a new CALL_EXPR to FNDECL using the tail of the argument
11223    list ARGS along with N new arguments specified as the "..."
11224    parameters.  SKIP is the number of arguments in ARGS to be omitted.
11225    OLDNARGS is the number of elements in ARGS.  */
11226
11227 static tree
11228 rewrite_call_expr_array (location_t loc, int oldnargs, tree *args,
11229                          int skip, tree fndecl, int n, ...)
11230 {
11231   va_list ap;
11232   tree t;
11233
11234   va_start (ap, n);
11235   t = rewrite_call_expr_valist (loc, oldnargs, args, skip, fndecl, n, ap);
11236   va_end (ap);
11237
11238   return t;
11239 }
11240
11241 /* Construct a new CALL_EXPR using the tail of the argument list of EXP
11242    along with N new arguments specified as the "..." parameters.  SKIP
11243    is the number of arguments in EXP to be omitted.  This function is used
11244    to do varargs-to-varargs transformations.  */
11245
11246 static tree
11247 rewrite_call_expr (location_t loc, tree exp, int skip, tree fndecl, int n, ...)
11248 {
11249   va_list ap;
11250   tree t;
11251
11252   va_start (ap, n);
11253   t = rewrite_call_expr_valist (loc, call_expr_nargs (exp),
11254                                 CALL_EXPR_ARGP (exp), skip, fndecl, n, ap);
11255   va_end (ap);
11256
11257   return t;
11258 }
11259
11260 /* Validate a single argument ARG against a tree code CODE representing
11261    a type.  */
11262
11263 static bool
11264 validate_arg (const_tree arg, enum tree_code code)
11265 {
11266   if (!arg)
11267     return false;
11268   else if (code == POINTER_TYPE)
11269     return POINTER_TYPE_P (TREE_TYPE (arg));
11270   else if (code == INTEGER_TYPE)
11271     return INTEGRAL_TYPE_P (TREE_TYPE (arg));
11272   return code == TREE_CODE (TREE_TYPE (arg));
11273 }
11274
11275 /* This function validates the types of a function call argument list
11276    against a specified list of tree_codes.  If the last specifier is a 0,
11277    that represents an ellipses, otherwise the last specifier must be a
11278    VOID_TYPE.
11279
11280    This is the GIMPLE version of validate_arglist.  Eventually we want to
11281    completely convert builtins.c to work from GIMPLEs and the tree based
11282    validate_arglist will then be removed.  */
11283
11284 bool
11285 validate_gimple_arglist (const_gimple call, ...)
11286 {
11287   enum tree_code code;
11288   bool res = 0;
11289   va_list ap;
11290   const_tree arg;
11291   size_t i;
11292
11293   va_start (ap, call);
11294   i = 0;
11295
11296   do
11297     {
11298       code = (enum tree_code) va_arg (ap, int);
11299       switch (code)
11300         {
11301         case 0:
11302           /* This signifies an ellipses, any further arguments are all ok.  */
11303           res = true;
11304           goto end;
11305         case VOID_TYPE:
11306           /* This signifies an endlink, if no arguments remain, return
11307              true, otherwise return false.  */
11308           res = (i == gimple_call_num_args (call));
11309           goto end;
11310         default:
11311           /* If no parameters remain or the parameter's code does not
11312              match the specified code, return false.  Otherwise continue
11313              checking any remaining arguments.  */
11314           arg = gimple_call_arg (call, i++);
11315           if (!validate_arg (arg, code))
11316             goto end;
11317           break;
11318         }
11319     }
11320   while (1);
11321
11322   /* We need gotos here since we can only have one VA_CLOSE in a
11323      function.  */
11324  end: ;
11325   va_end (ap);
11326
11327   return res;
11328 }
11329
11330 /* This function validates the types of a function call argument list
11331    against a specified list of tree_codes.  If the last specifier is a 0,
11332    that represents an ellipses, otherwise the last specifier must be a
11333    VOID_TYPE.  */
11334
11335 bool
11336 validate_arglist (const_tree callexpr, ...)
11337 {
11338   enum tree_code code;
11339   bool res = 0;
11340   va_list ap;
11341   const_call_expr_arg_iterator iter;
11342   const_tree arg;
11343
11344   va_start (ap, callexpr);
11345   init_const_call_expr_arg_iterator (callexpr, &iter);
11346
11347   do
11348     {
11349       code = (enum tree_code) va_arg (ap, int);
11350       switch (code)
11351         {
11352         case 0:
11353           /* This signifies an ellipses, any further arguments are all ok.  */
11354           res = true;
11355           goto end;
11356         case VOID_TYPE:
11357           /* This signifies an endlink, if no arguments remain, return
11358              true, otherwise return false.  */
11359           res = !more_const_call_expr_args_p (&iter);
11360           goto end;
11361         default:
11362           /* If no parameters remain or the parameter's code does not
11363              match the specified code, return false.  Otherwise continue
11364              checking any remaining arguments.  */
11365           arg = next_const_call_expr_arg (&iter);
11366           if (!validate_arg (arg, code))
11367             goto end;
11368           break;
11369         }
11370     }
11371   while (1);
11372
11373   /* We need gotos here since we can only have one VA_CLOSE in a
11374      function.  */
11375  end: ;
11376   va_end (ap);
11377
11378   return res;
11379 }
11380
11381 /* Default target-specific builtin expander that does nothing.  */
11382
11383 rtx
11384 default_expand_builtin (tree exp ATTRIBUTE_UNUSED,
11385                         rtx target ATTRIBUTE_UNUSED,
11386                         rtx subtarget ATTRIBUTE_UNUSED,
11387                         enum machine_mode mode ATTRIBUTE_UNUSED,
11388                         int ignore ATTRIBUTE_UNUSED)
11389 {
11390   return NULL_RTX;
11391 }
11392
11393 /* Returns true is EXP represents data that would potentially reside
11394    in a readonly section.  */
11395
11396 static bool
11397 readonly_data_expr (tree exp)
11398 {
11399   STRIP_NOPS (exp);
11400
11401   if (TREE_CODE (exp) != ADDR_EXPR)
11402     return false;
11403
11404   exp = get_base_address (TREE_OPERAND (exp, 0));
11405   if (!exp)
11406     return false;
11407
11408   /* Make sure we call decl_readonly_section only for trees it
11409      can handle (since it returns true for everything it doesn't
11410      understand).  */
11411   if (TREE_CODE (exp) == STRING_CST
11412       || TREE_CODE (exp) == CONSTRUCTOR
11413       || (TREE_CODE (exp) == VAR_DECL && TREE_STATIC (exp)))
11414     return decl_readonly_section (exp, 0);
11415   else
11416     return false;
11417 }
11418
11419 /* Simplify a call to the strstr builtin.  S1 and S2 are the arguments
11420    to the call, and TYPE is its return type.
11421
11422    Return NULL_TREE if no simplification was possible, otherwise return the
11423    simplified form of the call as a tree.
11424
11425    The simplified form may be a constant or other expression which
11426    computes the same value, but in a more efficient manner (including
11427    calls to other builtin functions).
11428
11429    The call may contain arguments which need to be evaluated, but
11430    which are not useful to determine the result of the call.  In
11431    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11432    COMPOUND_EXPR will be an argument which must be evaluated.
11433    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11434    COMPOUND_EXPR in the chain will contain the tree for the simplified
11435    form of the builtin function call.  */
11436
11437 static tree
11438 fold_builtin_strstr (location_t loc, tree s1, tree s2, tree type)
11439 {
11440   if (!validate_arg (s1, POINTER_TYPE)
11441       || !validate_arg (s2, POINTER_TYPE))
11442     return NULL_TREE;
11443   else
11444     {
11445       tree fn;
11446       const char *p1, *p2;
11447
11448       p2 = c_getstr (s2);
11449       if (p2 == NULL)
11450         return NULL_TREE;
11451
11452       p1 = c_getstr (s1);
11453       if (p1 != NULL)
11454         {
11455           const char *r = strstr (p1, p2);
11456           tree tem;
11457
11458           if (r == NULL)
11459             return build_int_cst (TREE_TYPE (s1), 0);
11460
11461           /* Return an offset into the constant string argument.  */
11462           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
11463           return fold_convert_loc (loc, type, tem);
11464         }
11465
11466       /* The argument is const char *, and the result is char *, so we need
11467          a type conversion here to avoid a warning.  */
11468       if (p2[0] == '\0')
11469         return fold_convert_loc (loc, type, s1);
11470
11471       if (p2[1] != '\0')
11472         return NULL_TREE;
11473
11474       fn = builtin_decl_implicit (BUILT_IN_STRCHR);
11475       if (!fn)
11476         return NULL_TREE;
11477
11478       /* New argument list transforming strstr(s1, s2) to
11479          strchr(s1, s2[0]).  */
11480       return build_call_expr_loc (loc, fn, 2, s1,
11481                                   build_int_cst (integer_type_node, p2[0]));
11482     }
11483 }
11484
11485 /* Simplify a call to the strchr builtin.  S1 and S2 are the arguments to
11486    the call, and TYPE is its return type.
11487
11488    Return NULL_TREE if no simplification was possible, otherwise return the
11489    simplified form of the call as a tree.
11490
11491    The simplified form may be a constant or other expression which
11492    computes the same value, but in a more efficient manner (including
11493    calls to other builtin functions).
11494
11495    The call may contain arguments which need to be evaluated, but
11496    which are not useful to determine the result of the call.  In
11497    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11498    COMPOUND_EXPR will be an argument which must be evaluated.
11499    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11500    COMPOUND_EXPR in the chain will contain the tree for the simplified
11501    form of the builtin function call.  */
11502
11503 static tree
11504 fold_builtin_strchr (location_t loc, tree s1, tree s2, tree type)
11505 {
11506   if (!validate_arg (s1, POINTER_TYPE)
11507       || !validate_arg (s2, INTEGER_TYPE))
11508     return NULL_TREE;
11509   else
11510     {
11511       const char *p1;
11512
11513       if (TREE_CODE (s2) != INTEGER_CST)
11514         return NULL_TREE;
11515
11516       p1 = c_getstr (s1);
11517       if (p1 != NULL)
11518         {
11519           char c;
11520           const char *r;
11521           tree tem;
11522
11523           if (target_char_cast (s2, &c))
11524             return NULL_TREE;
11525
11526           r = strchr (p1, c);
11527
11528           if (r == NULL)
11529             return build_int_cst (TREE_TYPE (s1), 0);
11530
11531           /* Return an offset into the constant string argument.  */
11532           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
11533           return fold_convert_loc (loc, type, tem);
11534         }
11535       return NULL_TREE;
11536     }
11537 }
11538
11539 /* Simplify a call to the strrchr builtin.  S1 and S2 are the arguments to
11540    the call, and TYPE is its return type.
11541
11542    Return NULL_TREE if no simplification was possible, otherwise return the
11543    simplified form of the call as a tree.
11544
11545    The simplified form may be a constant or other expression which
11546    computes the same value, but in a more efficient manner (including
11547    calls to other builtin functions).
11548
11549    The call may contain arguments which need to be evaluated, but
11550    which are not useful to determine the result of the call.  In
11551    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11552    COMPOUND_EXPR will be an argument which must be evaluated.
11553    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11554    COMPOUND_EXPR in the chain will contain the tree for the simplified
11555    form of the builtin function call.  */
11556
11557 static tree
11558 fold_builtin_strrchr (location_t loc, tree s1, tree s2, tree type)
11559 {
11560   if (!validate_arg (s1, POINTER_TYPE)
11561       || !validate_arg (s2, INTEGER_TYPE))
11562     return NULL_TREE;
11563   else
11564     {
11565       tree fn;
11566       const char *p1;
11567
11568       if (TREE_CODE (s2) != INTEGER_CST)
11569         return NULL_TREE;
11570
11571       p1 = c_getstr (s1);
11572       if (p1 != NULL)
11573         {
11574           char c;
11575           const char *r;
11576           tree tem;
11577
11578           if (target_char_cast (s2, &c))
11579             return NULL_TREE;
11580
11581           r = strrchr (p1, c);
11582
11583           if (r == NULL)
11584             return build_int_cst (TREE_TYPE (s1), 0);
11585
11586           /* Return an offset into the constant string argument.  */
11587           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
11588           return fold_convert_loc (loc, type, tem);
11589         }
11590
11591       if (! integer_zerop (s2))
11592         return NULL_TREE;
11593
11594       fn = builtin_decl_implicit (BUILT_IN_STRCHR);
11595       if (!fn)
11596         return NULL_TREE;
11597
11598       /* Transform strrchr(s1, '\0') to strchr(s1, '\0').  */
11599       return build_call_expr_loc (loc, fn, 2, s1, s2);
11600     }
11601 }
11602
11603 /* Simplify a call to the strpbrk builtin.  S1 and S2 are the arguments
11604    to the call, and TYPE is its return type.
11605
11606    Return NULL_TREE if no simplification was possible, otherwise return the
11607    simplified form of the call as a tree.
11608
11609    The simplified form may be a constant or other expression which
11610    computes the same value, but in a more efficient manner (including
11611    calls to other builtin functions).
11612
11613    The call may contain arguments which need to be evaluated, but
11614    which are not useful to determine the result of the call.  In
11615    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11616    COMPOUND_EXPR will be an argument which must be evaluated.
11617    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11618    COMPOUND_EXPR in the chain will contain the tree for the simplified
11619    form of the builtin function call.  */
11620
11621 static tree
11622 fold_builtin_strpbrk (location_t loc, tree s1, tree s2, tree type)
11623 {
11624   if (!validate_arg (s1, POINTER_TYPE)
11625       || !validate_arg (s2, POINTER_TYPE))
11626     return NULL_TREE;
11627   else
11628     {
11629       tree fn;
11630       const char *p1, *p2;
11631
11632       p2 = c_getstr (s2);
11633       if (p2 == NULL)
11634         return NULL_TREE;
11635
11636       p1 = c_getstr (s1);
11637       if (p1 != NULL)
11638         {
11639           const char *r = strpbrk (p1, p2);
11640           tree tem;
11641
11642           if (r == NULL)
11643             return build_int_cst (TREE_TYPE (s1), 0);
11644
11645           /* Return an offset into the constant string argument.  */
11646           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
11647           return fold_convert_loc (loc, type, tem);
11648         }
11649
11650       if (p2[0] == '\0')
11651         /* strpbrk(x, "") == NULL.
11652            Evaluate and ignore s1 in case it had side-effects.  */
11653         return omit_one_operand_loc (loc, TREE_TYPE (s1), integer_zero_node, s1);
11654
11655       if (p2[1] != '\0')
11656         return NULL_TREE;  /* Really call strpbrk.  */
11657
11658       fn = builtin_decl_implicit (BUILT_IN_STRCHR);
11659       if (!fn)
11660         return NULL_TREE;
11661
11662       /* New argument list transforming strpbrk(s1, s2) to
11663          strchr(s1, s2[0]).  */
11664       return build_call_expr_loc (loc, fn, 2, s1,
11665                                   build_int_cst (integer_type_node, p2[0]));
11666     }
11667 }
11668
11669 /* Simplify a call to the strcat builtin.  DST and SRC are the arguments
11670    to the call.
11671
11672    Return NULL_TREE if no simplification was possible, otherwise return the
11673    simplified form of the call as a tree.
11674
11675    The simplified form may be a constant or other expression which
11676    computes the same value, but in a more efficient manner (including
11677    calls to other builtin functions).
11678
11679    The call may contain arguments which need to be evaluated, but
11680    which are not useful to determine the result of the call.  In
11681    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11682    COMPOUND_EXPR will be an argument which must be evaluated.
11683    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11684    COMPOUND_EXPR in the chain will contain the tree for the simplified
11685    form of the builtin function call.  */
11686
11687 static tree
11688 fold_builtin_strcat (location_t loc ATTRIBUTE_UNUSED, tree dst, tree src)
11689 {
11690   if (!validate_arg (dst, POINTER_TYPE)
11691       || !validate_arg (src, POINTER_TYPE))
11692     return NULL_TREE;
11693   else
11694     {
11695       const char *p = c_getstr (src);
11696
11697       /* If the string length is zero, return the dst parameter.  */
11698       if (p && *p == '\0')
11699         return dst;
11700
11701       if (optimize_insn_for_speed_p ())
11702         {
11703           /* See if we can store by pieces into (dst + strlen(dst)).  */
11704           tree newdst, call;
11705           tree strlen_fn = builtin_decl_implicit (BUILT_IN_STRLEN);
11706           tree strcpy_fn = builtin_decl_implicit (BUILT_IN_STRCPY);
11707
11708           if (!strlen_fn || !strcpy_fn)
11709             return NULL_TREE;
11710
11711           /* If we don't have a movstr we don't want to emit an strcpy
11712              call.  We have to do that if the length of the source string
11713              isn't computable (in that case we can use memcpy probably
11714              later expanding to a sequence of mov instructions).  If we
11715              have movstr instructions we can emit strcpy calls.  */
11716           if (!HAVE_movstr)
11717             {
11718               tree len = c_strlen (src, 1);
11719               if (! len || TREE_SIDE_EFFECTS (len))
11720                 return NULL_TREE;
11721             }
11722
11723           /* Stabilize the argument list.  */
11724           dst = builtin_save_expr (dst);
11725
11726           /* Create strlen (dst).  */
11727           newdst = build_call_expr_loc (loc, strlen_fn, 1, dst);
11728           /* Create (dst p+ strlen (dst)).  */
11729
11730           newdst = fold_build_pointer_plus_loc (loc, dst, newdst);
11731           newdst = builtin_save_expr (newdst);
11732
11733           call = build_call_expr_loc (loc, strcpy_fn, 2, newdst, src);
11734           return build2 (COMPOUND_EXPR, TREE_TYPE (dst), call, dst);
11735         }
11736       return NULL_TREE;
11737     }
11738 }
11739
11740 /* Simplify a call to the strncat builtin.  DST, SRC, and LEN are the
11741    arguments to the call.
11742
11743    Return NULL_TREE if no simplification was possible, otherwise return the
11744    simplified form of the call as a tree.
11745
11746    The simplified form may be a constant or other expression which
11747    computes the same value, but in a more efficient manner (including
11748    calls to other builtin functions).
11749
11750    The call may contain arguments which need to be evaluated, but
11751    which are not useful to determine the result of the call.  In
11752    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11753    COMPOUND_EXPR will be an argument which must be evaluated.
11754    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11755    COMPOUND_EXPR in the chain will contain the tree for the simplified
11756    form of the builtin function call.  */
11757
11758 static tree
11759 fold_builtin_strncat (location_t loc, tree dst, tree src, tree len)
11760 {
11761   if (!validate_arg (dst, POINTER_TYPE)
11762       || !validate_arg (src, POINTER_TYPE)
11763       || !validate_arg (len, INTEGER_TYPE))
11764     return NULL_TREE;
11765   else
11766     {
11767       const char *p = c_getstr (src);
11768
11769       /* If the requested length is zero, or the src parameter string
11770          length is zero, return the dst parameter.  */
11771       if (integer_zerop (len) || (p && *p == '\0'))
11772         return omit_two_operands_loc (loc, TREE_TYPE (dst), dst, src, len);
11773
11774       /* If the requested len is greater than or equal to the string
11775          length, call strcat.  */
11776       if (TREE_CODE (len) == INTEGER_CST && p
11777           && compare_tree_int (len, strlen (p)) >= 0)
11778         {
11779           tree fn = builtin_decl_implicit (BUILT_IN_STRCAT);
11780
11781           /* If the replacement _DECL isn't initialized, don't do the
11782              transformation.  */
11783           if (!fn)
11784             return NULL_TREE;
11785
11786           return build_call_expr_loc (loc, fn, 2, dst, src);
11787         }
11788       return NULL_TREE;
11789     }
11790 }
11791
11792 /* Simplify a call to the strspn builtin.  S1 and S2 are the arguments
11793    to the call.
11794
11795    Return NULL_TREE if no simplification was possible, otherwise return the
11796    simplified form of the call as a tree.
11797
11798    The simplified form may be a constant or other expression which
11799    computes the same value, but in a more efficient manner (including
11800    calls to other builtin functions).
11801
11802    The call may contain arguments which need to be evaluated, but
11803    which are not useful to determine the result of the call.  In
11804    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11805    COMPOUND_EXPR will be an argument which must be evaluated.
11806    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11807    COMPOUND_EXPR in the chain will contain the tree for the simplified
11808    form of the builtin function call.  */
11809
11810 static tree
11811 fold_builtin_strspn (location_t loc, tree s1, tree s2)
11812 {
11813   if (!validate_arg (s1, POINTER_TYPE)
11814       || !validate_arg (s2, POINTER_TYPE))
11815     return NULL_TREE;
11816   else
11817     {
11818       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
11819
11820       /* If both arguments are constants, evaluate at compile-time.  */
11821       if (p1 && p2)
11822         {
11823           const size_t r = strspn (p1, p2);
11824           return size_int (r);
11825         }
11826
11827       /* If either argument is "", return NULL_TREE.  */
11828       if ((p1 && *p1 == '\0') || (p2 && *p2 == '\0'))
11829         /* Evaluate and ignore both arguments in case either one has
11830            side-effects.  */
11831         return omit_two_operands_loc (loc, size_type_node, size_zero_node,
11832                                   s1, s2);
11833       return NULL_TREE;
11834     }
11835 }
11836
11837 /* Simplify a call to the strcspn builtin.  S1 and S2 are the arguments
11838    to the call.
11839
11840    Return NULL_TREE if no simplification was possible, otherwise return the
11841    simplified form of the call as a tree.
11842
11843    The simplified form may be a constant or other expression which
11844    computes the same value, but in a more efficient manner (including
11845    calls to other builtin functions).
11846
11847    The call may contain arguments which need to be evaluated, but
11848    which are not useful to determine the result of the call.  In
11849    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11850    COMPOUND_EXPR will be an argument which must be evaluated.
11851    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11852    COMPOUND_EXPR in the chain will contain the tree for the simplified
11853    form of the builtin function call.  */
11854
11855 static tree
11856 fold_builtin_strcspn (location_t loc, tree s1, tree s2)
11857 {
11858   if (!validate_arg (s1, POINTER_TYPE)
11859       || !validate_arg (s2, POINTER_TYPE))
11860     return NULL_TREE;
11861   else
11862     {
11863       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
11864
11865       /* If both arguments are constants, evaluate at compile-time.  */
11866       if (p1 && p2)
11867         {
11868           const size_t r = strcspn (p1, p2);
11869           return size_int (r);
11870         }
11871
11872       /* If the first argument is "", return NULL_TREE.  */
11873       if (p1 && *p1 == '\0')
11874         {
11875           /* Evaluate and ignore argument s2 in case it has
11876              side-effects.  */
11877           return omit_one_operand_loc (loc, size_type_node,
11878                                    size_zero_node, s2);
11879         }
11880
11881       /* If the second argument is "", return __builtin_strlen(s1).  */
11882       if (p2 && *p2 == '\0')
11883         {
11884           tree fn = builtin_decl_implicit (BUILT_IN_STRLEN);
11885
11886           /* If the replacement _DECL isn't initialized, don't do the
11887              transformation.  */
11888           if (!fn)
11889             return NULL_TREE;
11890
11891           return build_call_expr_loc (loc, fn, 1, s1);
11892         }
11893       return NULL_TREE;
11894     }
11895 }
11896
11897 /* Fold a call to the fputs builtin.  ARG0 and ARG1 are the arguments
11898    to the call.  IGNORE is true if the value returned
11899    by the builtin will be ignored.  UNLOCKED is true is true if this
11900    actually a call to fputs_unlocked.  If LEN in non-NULL, it represents
11901    the known length of the string.  Return NULL_TREE if no simplification
11902    was possible.  */
11903
11904 tree
11905 fold_builtin_fputs (location_t loc, tree arg0, tree arg1,
11906                     bool ignore, bool unlocked, tree len)
11907 {
11908   /* If we're using an unlocked function, assume the other unlocked
11909      functions exist explicitly.  */
11910   tree const fn_fputc = (unlocked
11911                          ? builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED)
11912                          : builtin_decl_implicit (BUILT_IN_FPUTC));
11913   tree const fn_fwrite = (unlocked
11914                           ? builtin_decl_explicit (BUILT_IN_FWRITE_UNLOCKED)
11915                           : builtin_decl_implicit (BUILT_IN_FWRITE));
11916
11917   /* If the return value is used, don't do the transformation.  */
11918   if (!ignore)
11919     return NULL_TREE;
11920
11921   /* Verify the arguments in the original call.  */
11922   if (!validate_arg (arg0, POINTER_TYPE)
11923       || !validate_arg (arg1, POINTER_TYPE))
11924     return NULL_TREE;
11925
11926   if (! len)
11927     len = c_strlen (arg0, 0);
11928
11929   /* Get the length of the string passed to fputs.  If the length
11930      can't be determined, punt.  */
11931   if (!len
11932       || TREE_CODE (len) != INTEGER_CST)
11933     return NULL_TREE;
11934
11935   switch (compare_tree_int (len, 1))
11936     {
11937     case -1: /* length is 0, delete the call entirely .  */
11938       return omit_one_operand_loc (loc, integer_type_node,
11939                                integer_zero_node, arg1);;
11940
11941     case 0: /* length is 1, call fputc.  */
11942       {
11943         const char *p = c_getstr (arg0);
11944
11945         if (p != NULL)
11946           {
11947             if (fn_fputc)
11948               return build_call_expr_loc (loc, fn_fputc, 2,
11949                                           build_int_cst
11950                                             (integer_type_node, p[0]), arg1);
11951             else
11952               return NULL_TREE;
11953           }
11954       }
11955       /* FALLTHROUGH */
11956     case 1: /* length is greater than 1, call fwrite.  */
11957       {
11958         /* If optimizing for size keep fputs.  */
11959         if (optimize_function_for_size_p (cfun))
11960           return NULL_TREE;
11961         /* New argument list transforming fputs(string, stream) to
11962            fwrite(string, 1, len, stream).  */
11963         if (fn_fwrite)
11964           return build_call_expr_loc (loc, fn_fwrite, 4, arg0,
11965                                   size_one_node, len, arg1);
11966         else
11967           return NULL_TREE;
11968       }
11969     default:
11970       gcc_unreachable ();
11971     }
11972   return NULL_TREE;
11973 }
11974
11975 /* Fold the next_arg or va_start call EXP. Returns true if there was an error
11976    produced.  False otherwise.  This is done so that we don't output the error
11977    or warning twice or three times.  */
11978
11979 bool
11980 fold_builtin_next_arg (tree exp, bool va_start_p)
11981 {
11982   tree fntype = TREE_TYPE (current_function_decl);
11983   int nargs = call_expr_nargs (exp);
11984   tree arg;
11985
11986   if (!stdarg_p (fntype))
11987     {
11988       error ("%<va_start%> used in function with fixed args");
11989       return true;
11990     }
11991
11992   if (va_start_p)
11993     {
11994       if (va_start_p && (nargs != 2))
11995         {
11996           error ("wrong number of arguments to function %<va_start%>");
11997           return true;
11998         }
11999       arg = CALL_EXPR_ARG (exp, 1);
12000     }
12001   /* We use __builtin_va_start (ap, 0, 0) or __builtin_next_arg (0, 0)
12002      when we checked the arguments and if needed issued a warning.  */
12003   else
12004     {
12005       if (nargs == 0)
12006         {
12007           /* Evidently an out of date version of <stdarg.h>; can't validate
12008              va_start's second argument, but can still work as intended.  */
12009           warning (0, "%<__builtin_next_arg%> called without an argument");
12010           return true;
12011         }
12012       else if (nargs > 1)
12013         {
12014           error ("wrong number of arguments to function %<__builtin_next_arg%>");
12015           return true;
12016         }
12017       arg = CALL_EXPR_ARG (exp, 0);
12018     }
12019
12020   if (TREE_CODE (arg) == SSA_NAME)
12021     arg = SSA_NAME_VAR (arg);
12022
12023   /* We destructively modify the call to be __builtin_va_start (ap, 0)
12024      or __builtin_next_arg (0) the first time we see it, after checking
12025      the arguments and if needed issuing a warning.  */
12026   if (!integer_zerop (arg))
12027     {
12028       tree last_parm = tree_last (DECL_ARGUMENTS (current_function_decl));
12029
12030       /* Strip off all nops for the sake of the comparison.  This
12031          is not quite the same as STRIP_NOPS.  It does more.
12032          We must also strip off INDIRECT_EXPR for C++ reference
12033          parameters.  */
12034       while (CONVERT_EXPR_P (arg)
12035              || TREE_CODE (arg) == INDIRECT_REF)
12036         arg = TREE_OPERAND (arg, 0);
12037       if (arg != last_parm)
12038         {
12039           /* FIXME: Sometimes with the tree optimizers we can get the
12040              not the last argument even though the user used the last
12041              argument.  We just warn and set the arg to be the last
12042              argument so that we will get wrong-code because of
12043              it.  */
12044           warning (0, "second parameter of %<va_start%> not last named argument");
12045         }
12046
12047       /* Undefined by C99 7.15.1.4p4 (va_start):
12048          "If the parameter parmN is declared with the register storage
12049          class, with a function or array type, or with a type that is
12050          not compatible with the type that results after application of
12051          the default argument promotions, the behavior is undefined."
12052       */
12053       else if (DECL_REGISTER (arg))
12054         warning (0, "undefined behaviour when second parameter of "
12055                  "%<va_start%> is declared with %<register%> storage");
12056
12057       /* We want to verify the second parameter just once before the tree
12058          optimizers are run and then avoid keeping it in the tree,
12059          as otherwise we could warn even for correct code like:
12060          void foo (int i, ...)
12061          { va_list ap; i++; va_start (ap, i); va_end (ap); }  */
12062       if (va_start_p)
12063         CALL_EXPR_ARG (exp, 1) = integer_zero_node;
12064       else
12065         CALL_EXPR_ARG (exp, 0) = integer_zero_node;
12066     }
12067   return false;
12068 }
12069
12070
12071 /* Simplify a call to the sprintf builtin with arguments DEST, FMT, and ORIG.
12072    ORIG may be null if this is a 2-argument call.  We don't attempt to
12073    simplify calls with more than 3 arguments.
12074
12075    Return NULL_TREE if no simplification was possible, otherwise return the
12076    simplified form of the call as a tree.  If IGNORED is true, it means that
12077    the caller does not use the returned value of the function.  */
12078
12079 static tree
12080 fold_builtin_sprintf (location_t loc, tree dest, tree fmt,
12081                       tree orig, int ignored)
12082 {
12083   tree call, retval;
12084   const char *fmt_str = NULL;
12085
12086   /* Verify the required arguments in the original call.  We deal with two
12087      types of sprintf() calls: 'sprintf (str, fmt)' and
12088      'sprintf (dest, "%s", orig)'.  */
12089   if (!validate_arg (dest, POINTER_TYPE)
12090       || !validate_arg (fmt, POINTER_TYPE))
12091     return NULL_TREE;
12092   if (orig && !validate_arg (orig, POINTER_TYPE))
12093     return NULL_TREE;
12094
12095   /* Check whether the format is a literal string constant.  */
12096   fmt_str = c_getstr (fmt);
12097   if (fmt_str == NULL)
12098     return NULL_TREE;
12099
12100   call = NULL_TREE;
12101   retval = NULL_TREE;
12102
12103   if (!init_target_chars ())
12104     return NULL_TREE;
12105
12106   /* If the format doesn't contain % args or %%, use strcpy.  */
12107   if (strchr (fmt_str, target_percent) == NULL)
12108     {
12109       tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
12110
12111       if (!fn)
12112         return NULL_TREE;
12113
12114       /* Don't optimize sprintf (buf, "abc", ptr++).  */
12115       if (orig)
12116         return NULL_TREE;
12117
12118       /* Convert sprintf (str, fmt) into strcpy (str, fmt) when
12119          'format' is known to contain no % formats.  */
12120       call = build_call_expr_loc (loc, fn, 2, dest, fmt);
12121       if (!ignored)
12122         retval = build_int_cst (integer_type_node, strlen (fmt_str));
12123     }
12124
12125   /* If the format is "%s", use strcpy if the result isn't used.  */
12126   else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
12127     {
12128       tree fn;
12129       fn = builtin_decl_implicit (BUILT_IN_STRCPY);
12130
12131       if (!fn)
12132         return NULL_TREE;
12133
12134       /* Don't crash on sprintf (str1, "%s").  */
12135       if (!orig)
12136         return NULL_TREE;
12137
12138       /* Convert sprintf (str1, "%s", str2) into strcpy (str1, str2).  */
12139       if (!ignored)
12140         {
12141           retval = c_strlen (orig, 1);
12142           if (!retval || TREE_CODE (retval) != INTEGER_CST)
12143             return NULL_TREE;
12144         }
12145       call = build_call_expr_loc (loc, fn, 2, dest, orig);
12146     }
12147
12148   if (call && retval)
12149     {
12150       retval = fold_convert_loc
12151         (loc, TREE_TYPE (TREE_TYPE (builtin_decl_implicit (BUILT_IN_SPRINTF))),
12152          retval);
12153       return build2 (COMPOUND_EXPR, TREE_TYPE (retval), call, retval);
12154     }
12155   else
12156     return call;
12157 }
12158
12159 /* Simplify a call to the snprintf builtin with arguments DEST, DESTSIZE,
12160    FMT, and ORIG.  ORIG may be null if this is a 3-argument call.  We don't
12161    attempt to simplify calls with more than 4 arguments.
12162
12163    Return NULL_TREE if no simplification was possible, otherwise return the
12164    simplified form of the call as a tree.  If IGNORED is true, it means that
12165    the caller does not use the returned value of the function.  */
12166
12167 static tree
12168 fold_builtin_snprintf (location_t loc, tree dest, tree destsize, tree fmt,
12169                        tree orig, int ignored)
12170 {
12171   tree call, retval;
12172   const char *fmt_str = NULL;
12173   unsigned HOST_WIDE_INT destlen;
12174
12175   /* Verify the required arguments in the original call.  We deal with two
12176      types of snprintf() calls: 'snprintf (str, cst, fmt)' and
12177      'snprintf (dest, cst, "%s", orig)'.  */
12178   if (!validate_arg (dest, POINTER_TYPE)
12179       || !validate_arg (destsize, INTEGER_TYPE)
12180       || !validate_arg (fmt, POINTER_TYPE))
12181     return NULL_TREE;
12182   if (orig && !validate_arg (orig, POINTER_TYPE))
12183     return NULL_TREE;
12184
12185   if (!host_integerp (destsize, 1))
12186     return NULL_TREE;
12187
12188   /* Check whether the format is a literal string constant.  */
12189   fmt_str = c_getstr (fmt);
12190   if (fmt_str == NULL)
12191     return NULL_TREE;
12192
12193   call = NULL_TREE;
12194   retval = NULL_TREE;
12195
12196   if (!init_target_chars ())
12197     return NULL_TREE;
12198
12199   destlen = tree_low_cst (destsize, 1);
12200
12201   /* If the format doesn't contain % args or %%, use strcpy.  */
12202   if (strchr (fmt_str, target_percent) == NULL)
12203     {
12204       tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
12205       size_t len = strlen (fmt_str);
12206
12207       /* Don't optimize snprintf (buf, 4, "abc", ptr++).  */
12208       if (orig)
12209         return NULL_TREE;
12210
12211       /* We could expand this as
12212          memcpy (str, fmt, cst - 1); str[cst - 1] = '\0';
12213          or to
12214          memcpy (str, fmt_with_nul_at_cstm1, cst);
12215          but in the former case that might increase code size
12216          and in the latter case grow .rodata section too much.
12217          So punt for now.  */
12218       if (len >= destlen)
12219         return NULL_TREE;
12220
12221       if (!fn)
12222         return NULL_TREE;
12223
12224       /* Convert snprintf (str, cst, fmt) into strcpy (str, fmt) when
12225          'format' is known to contain no % formats and
12226          strlen (fmt) < cst.  */
12227       call = build_call_expr_loc (loc, fn, 2, dest, fmt);
12228
12229       if (!ignored)
12230         retval = build_int_cst (integer_type_node, strlen (fmt_str));
12231     }
12232
12233   /* If the format is "%s", use strcpy if the result isn't used.  */
12234   else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
12235     {
12236       tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
12237       unsigned HOST_WIDE_INT origlen;
12238
12239       /* Don't crash on snprintf (str1, cst, "%s").  */
12240       if (!orig)
12241         return NULL_TREE;
12242
12243       retval = c_strlen (orig, 1);
12244       if (!retval || !host_integerp (retval, 1))  
12245         return NULL_TREE;
12246
12247       origlen = tree_low_cst (retval, 1);
12248       /* We could expand this as
12249          memcpy (str1, str2, cst - 1); str1[cst - 1] = '\0';
12250          or to
12251          memcpy (str1, str2_with_nul_at_cstm1, cst);
12252          but in the former case that might increase code size
12253          and in the latter case grow .rodata section too much.
12254          So punt for now.  */
12255       if (origlen >= destlen)
12256         return NULL_TREE;
12257
12258       /* Convert snprintf (str1, cst, "%s", str2) into
12259          strcpy (str1, str2) if strlen (str2) < cst.  */
12260       if (!fn)
12261         return NULL_TREE;
12262
12263       call = build_call_expr_loc (loc, fn, 2, dest, orig);
12264
12265       if (ignored)
12266         retval = NULL_TREE;
12267     }
12268
12269   if (call && retval)
12270     {
12271       tree fn = builtin_decl_explicit (BUILT_IN_SNPRINTF);
12272       retval = fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fn)), retval);
12273       return build2 (COMPOUND_EXPR, TREE_TYPE (retval), call, retval);
12274     }
12275   else
12276     return call;
12277 }
12278
12279 /* Expand a call EXP to __builtin_object_size.  */
12280
12281 rtx
12282 expand_builtin_object_size (tree exp)
12283 {
12284   tree ost;
12285   int object_size_type;
12286   tree fndecl = get_callee_fndecl (exp);
12287
12288   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
12289     {
12290       error ("%Kfirst argument of %D must be a pointer, second integer constant",
12291              exp, fndecl);
12292       expand_builtin_trap ();
12293       return const0_rtx;
12294     }
12295
12296   ost = CALL_EXPR_ARG (exp, 1);
12297   STRIP_NOPS (ost);
12298
12299   if (TREE_CODE (ost) != INTEGER_CST
12300       || tree_int_cst_sgn (ost) < 0
12301       || compare_tree_int (ost, 3) > 0)
12302     {
12303       error ("%Klast argument of %D is not integer constant between 0 and 3",
12304              exp, fndecl);
12305       expand_builtin_trap ();
12306       return const0_rtx;
12307     }
12308
12309   object_size_type = tree_low_cst (ost, 0);
12310
12311   return object_size_type < 2 ? constm1_rtx : const0_rtx;
12312 }
12313
12314 /* Expand EXP, a call to the __mem{cpy,pcpy,move,set}_chk builtin.
12315    FCODE is the BUILT_IN_* to use.
12316    Return NULL_RTX if we failed; the caller should emit a normal call,
12317    otherwise try to get the result in TARGET, if convenient (and in
12318    mode MODE if that's convenient).  */
12319
12320 static rtx
12321 expand_builtin_memory_chk (tree exp, rtx target, enum machine_mode mode,
12322                            enum built_in_function fcode)
12323 {
12324   tree dest, src, len, size;
12325
12326   if (!validate_arglist (exp,
12327                          POINTER_TYPE,
12328                          fcode == BUILT_IN_MEMSET_CHK
12329                          ? INTEGER_TYPE : POINTER_TYPE,
12330                          INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
12331     return NULL_RTX;
12332
12333   dest = CALL_EXPR_ARG (exp, 0);
12334   src = CALL_EXPR_ARG (exp, 1);
12335   len = CALL_EXPR_ARG (exp, 2);
12336   size = CALL_EXPR_ARG (exp, 3);
12337
12338   if (! host_integerp (size, 1))
12339     return NULL_RTX;
12340
12341   if (host_integerp (len, 1) || integer_all_onesp (size))
12342     {
12343       tree fn;
12344
12345       if (! integer_all_onesp (size) && tree_int_cst_lt (size, len))
12346         {
12347           warning_at (tree_nonartificial_location (exp),
12348                       0, "%Kcall to %D will always overflow destination buffer",
12349                       exp, get_callee_fndecl (exp));
12350           return NULL_RTX;
12351         }
12352
12353       fn = NULL_TREE;
12354       /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
12355          mem{cpy,pcpy,move,set} is available.  */
12356       switch (fcode)
12357         {
12358         case BUILT_IN_MEMCPY_CHK:
12359           fn = builtin_decl_explicit (BUILT_IN_MEMCPY);
12360           break;
12361         case BUILT_IN_MEMPCPY_CHK:
12362           fn = builtin_decl_explicit (BUILT_IN_MEMPCPY);
12363           break;
12364         case BUILT_IN_MEMMOVE_CHK:
12365           fn = builtin_decl_explicit (BUILT_IN_MEMMOVE);
12366           break;
12367         case BUILT_IN_MEMSET_CHK:
12368           fn = builtin_decl_explicit (BUILT_IN_MEMSET);
12369           break;
12370         default:
12371           break;
12372         }
12373
12374       if (! fn)
12375         return NULL_RTX;
12376
12377       fn = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 3, dest, src, len);
12378       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
12379       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
12380       return expand_expr (fn, target, mode, EXPAND_NORMAL);
12381     }
12382   else if (fcode == BUILT_IN_MEMSET_CHK)
12383     return NULL_RTX;
12384   else
12385     {
12386       unsigned int dest_align = get_pointer_alignment (dest);
12387
12388       /* If DEST is not a pointer type, call the normal function.  */
12389       if (dest_align == 0)
12390         return NULL_RTX;
12391
12392       /* If SRC and DEST are the same (and not volatile), do nothing.  */
12393       if (operand_equal_p (src, dest, 0))
12394         {
12395           tree expr;
12396
12397           if (fcode != BUILT_IN_MEMPCPY_CHK)
12398             {
12399               /* Evaluate and ignore LEN in case it has side-effects.  */
12400               expand_expr (len, const0_rtx, VOIDmode, EXPAND_NORMAL);
12401               return expand_expr (dest, target, mode, EXPAND_NORMAL);
12402             }
12403
12404           expr = fold_build_pointer_plus (dest, len);
12405           return expand_expr (expr, target, mode, EXPAND_NORMAL);
12406         }
12407
12408       /* __memmove_chk special case.  */
12409       if (fcode == BUILT_IN_MEMMOVE_CHK)
12410         {
12411           unsigned int src_align = get_pointer_alignment (src);
12412
12413           if (src_align == 0)
12414             return NULL_RTX;
12415
12416           /* If src is categorized for a readonly section we can use
12417              normal __memcpy_chk.  */
12418           if (readonly_data_expr (src))
12419             {
12420               tree fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
12421               if (!fn)
12422                 return NULL_RTX;
12423               fn = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 4,
12424                                           dest, src, len, size);
12425               gcc_assert (TREE_CODE (fn) == CALL_EXPR);
12426               CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
12427               return expand_expr (fn, target, mode, EXPAND_NORMAL);
12428             }
12429         }
12430       return NULL_RTX;
12431     }
12432 }
12433
12434 /* Emit warning if a buffer overflow is detected at compile time.  */
12435
12436 static void
12437 maybe_emit_chk_warning (tree exp, enum built_in_function fcode)
12438 {
12439   int is_strlen = 0;
12440   tree len, size;
12441   location_t loc = tree_nonartificial_location (exp);
12442
12443   switch (fcode)
12444     {
12445     case BUILT_IN_STRCPY_CHK:
12446     case BUILT_IN_STPCPY_CHK:
12447     /* For __strcat_chk the warning will be emitted only if overflowing
12448        by at least strlen (dest) + 1 bytes.  */
12449     case BUILT_IN_STRCAT_CHK:
12450       len = CALL_EXPR_ARG (exp, 1);
12451       size = CALL_EXPR_ARG (exp, 2);
12452       is_strlen = 1;
12453       break;
12454     case BUILT_IN_STRNCAT_CHK:
12455     case BUILT_IN_STRNCPY_CHK:
12456       len = CALL_EXPR_ARG (exp, 2);
12457       size = CALL_EXPR_ARG (exp, 3);
12458       break;
12459     case BUILT_IN_SNPRINTF_CHK:
12460     case BUILT_IN_VSNPRINTF_CHK:
12461       len = CALL_EXPR_ARG (exp, 1);
12462       size = CALL_EXPR_ARG (exp, 3);
12463       break;
12464     default:
12465       gcc_unreachable ();
12466     }
12467
12468   if (!len || !size)
12469     return;
12470
12471   if (! host_integerp (size, 1) || integer_all_onesp (size))
12472     return;
12473
12474   if (is_strlen)
12475     {
12476       len = c_strlen (len, 1);
12477       if (! len || ! host_integerp (len, 1) || tree_int_cst_lt (len, size))
12478         return;
12479     }
12480   else if (fcode == BUILT_IN_STRNCAT_CHK)
12481     {
12482       tree src = CALL_EXPR_ARG (exp, 1);
12483       if (! src || ! host_integerp (len, 1) || tree_int_cst_lt (len, size))
12484         return;
12485       src = c_strlen (src, 1);
12486       if (! src || ! host_integerp (src, 1))
12487         {
12488           warning_at (loc, 0, "%Kcall to %D might overflow destination buffer",
12489                       exp, get_callee_fndecl (exp));
12490           return;
12491         }
12492       else if (tree_int_cst_lt (src, size))
12493         return;
12494     }
12495   else if (! host_integerp (len, 1) || ! tree_int_cst_lt (size, len))
12496     return;
12497
12498   warning_at (loc, 0, "%Kcall to %D will always overflow destination buffer",
12499               exp, get_callee_fndecl (exp));
12500 }
12501
12502 /* Emit warning if a buffer overflow is detected at compile time
12503    in __sprintf_chk/__vsprintf_chk calls.  */
12504
12505 static void
12506 maybe_emit_sprintf_chk_warning (tree exp, enum built_in_function fcode)
12507 {
12508   tree size, len, fmt;
12509   const char *fmt_str;
12510   int nargs = call_expr_nargs (exp);
12511
12512   /* Verify the required arguments in the original call.  */
12513
12514   if (nargs < 4)
12515     return;
12516   size = CALL_EXPR_ARG (exp, 2);
12517   fmt = CALL_EXPR_ARG (exp, 3);
12518
12519   if (! host_integerp (size, 1) || integer_all_onesp (size))
12520     return;
12521
12522   /* Check whether the format is a literal string constant.  */
12523   fmt_str = c_getstr (fmt);
12524   if (fmt_str == NULL)
12525     return;
12526
12527   if (!init_target_chars ())
12528     return;
12529
12530   /* If the format doesn't contain % args or %%, we know its size.  */
12531   if (strchr (fmt_str, target_percent) == 0)
12532     len = build_int_cstu (size_type_node, strlen (fmt_str));
12533   /* If the format is "%s" and first ... argument is a string literal,
12534      we know it too.  */
12535   else if (fcode == BUILT_IN_SPRINTF_CHK
12536            && strcmp (fmt_str, target_percent_s) == 0)
12537     {
12538       tree arg;
12539
12540       if (nargs < 5)
12541         return;
12542       arg = CALL_EXPR_ARG (exp, 4);
12543       if (! POINTER_TYPE_P (TREE_TYPE (arg)))
12544         return;
12545
12546       len = c_strlen (arg, 1);
12547       if (!len || ! host_integerp (len, 1))
12548         return;
12549     }
12550   else
12551     return;
12552
12553   if (! tree_int_cst_lt (len, size))
12554     warning_at (tree_nonartificial_location (exp),
12555                 0, "%Kcall to %D will always overflow destination buffer",
12556                 exp, get_callee_fndecl (exp));
12557 }
12558
12559 /* Emit warning if a free is called with address of a variable.  */
12560
12561 static void
12562 maybe_emit_free_warning (tree exp)
12563 {
12564   tree arg = CALL_EXPR_ARG (exp, 0);
12565
12566   STRIP_NOPS (arg);
12567   if (TREE_CODE (arg) != ADDR_EXPR)
12568     return;
12569
12570   arg = get_base_address (TREE_OPERAND (arg, 0));
12571   if (arg == NULL || INDIRECT_REF_P (arg) || TREE_CODE (arg) == MEM_REF)
12572     return;
12573
12574   if (SSA_VAR_P (arg))
12575     warning_at (tree_nonartificial_location (exp), OPT_Wfree_nonheap_object,
12576                 "%Kattempt to free a non-heap object %qD", exp, arg);
12577   else
12578     warning_at (tree_nonartificial_location (exp), OPT_Wfree_nonheap_object,
12579                 "%Kattempt to free a non-heap object", exp);
12580 }
12581
12582 /* Fold a call to __builtin_object_size with arguments PTR and OST,
12583    if possible.  */
12584
12585 tree
12586 fold_builtin_object_size (tree ptr, tree ost)
12587 {
12588   unsigned HOST_WIDE_INT bytes;
12589   int object_size_type;
12590
12591   if (!validate_arg (ptr, POINTER_TYPE)
12592       || !validate_arg (ost, INTEGER_TYPE))
12593     return NULL_TREE;
12594
12595   STRIP_NOPS (ost);
12596
12597   if (TREE_CODE (ost) != INTEGER_CST
12598       || tree_int_cst_sgn (ost) < 0
12599       || compare_tree_int (ost, 3) > 0)
12600     return NULL_TREE;
12601
12602   object_size_type = tree_low_cst (ost, 0);
12603
12604   /* __builtin_object_size doesn't evaluate side-effects in its arguments;
12605      if there are any side-effects, it returns (size_t) -1 for types 0 and 1
12606      and (size_t) 0 for types 2 and 3.  */
12607   if (TREE_SIDE_EFFECTS (ptr))
12608     return build_int_cst_type (size_type_node, object_size_type < 2 ? -1 : 0);
12609
12610   if (TREE_CODE (ptr) == ADDR_EXPR)
12611     {
12612       bytes = compute_builtin_object_size (ptr, object_size_type);
12613       if (double_int_fits_to_tree_p (size_type_node,
12614                                      uhwi_to_double_int (bytes)))
12615         return build_int_cstu (size_type_node, bytes);
12616     }
12617   else if (TREE_CODE (ptr) == SSA_NAME)
12618     {
12619       /* If object size is not known yet, delay folding until
12620        later.  Maybe subsequent passes will help determining
12621        it.  */
12622       bytes = compute_builtin_object_size (ptr, object_size_type);
12623       if (bytes != (unsigned HOST_WIDE_INT) (object_size_type < 2 ? -1 : 0)
12624           && double_int_fits_to_tree_p (size_type_node,
12625                                         uhwi_to_double_int (bytes)))
12626         return build_int_cstu (size_type_node, bytes);
12627     }
12628
12629   return NULL_TREE;
12630 }
12631
12632 /* Fold a call to the __mem{cpy,pcpy,move,set}_chk builtin.
12633    DEST, SRC, LEN, and SIZE are the arguments to the call.
12634    IGNORE is true, if return value can be ignored.  FCODE is the BUILT_IN_*
12635    code of the builtin.  If MAXLEN is not NULL, it is maximum length
12636    passed as third argument.  */
12637
12638 tree
12639 fold_builtin_memory_chk (location_t loc, tree fndecl,
12640                          tree dest, tree src, tree len, tree size,
12641                          tree maxlen, bool ignore,
12642                          enum built_in_function fcode)
12643 {
12644   tree fn;
12645
12646   if (!validate_arg (dest, POINTER_TYPE)
12647       || !validate_arg (src,
12648                         (fcode == BUILT_IN_MEMSET_CHK
12649                          ? INTEGER_TYPE : POINTER_TYPE))
12650       || !validate_arg (len, INTEGER_TYPE)
12651       || !validate_arg (size, INTEGER_TYPE))
12652     return NULL_TREE;
12653
12654   /* If SRC and DEST are the same (and not volatile), return DEST
12655      (resp. DEST+LEN for __mempcpy_chk).  */
12656   if (fcode != BUILT_IN_MEMSET_CHK && operand_equal_p (src, dest, 0))
12657     {
12658       if (fcode != BUILT_IN_MEMPCPY_CHK)
12659         return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
12660                                  dest, len);
12661       else
12662         {
12663           tree temp = fold_build_pointer_plus_loc (loc, dest, len);
12664           return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), temp);
12665         }
12666     }
12667
12668   if (! host_integerp (size, 1))
12669     return NULL_TREE;
12670
12671   if (! integer_all_onesp (size))
12672     {
12673       if (! host_integerp (len, 1))
12674         {
12675           /* If LEN is not constant, try MAXLEN too.
12676              For MAXLEN only allow optimizing into non-_ocs function
12677              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12678           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12679             {
12680               if (fcode == BUILT_IN_MEMPCPY_CHK && ignore)
12681                 {
12682                   /* (void) __mempcpy_chk () can be optimized into
12683                      (void) __memcpy_chk ().  */
12684                   fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
12685                   if (!fn)
12686                     return NULL_TREE;
12687
12688                   return build_call_expr_loc (loc, fn, 4, dest, src, len, size);
12689                 }
12690               return NULL_TREE;
12691             }
12692         }
12693       else
12694         maxlen = len;
12695
12696       if (tree_int_cst_lt (size, maxlen))
12697         return NULL_TREE;
12698     }
12699
12700   fn = NULL_TREE;
12701   /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
12702      mem{cpy,pcpy,move,set} is available.  */
12703   switch (fcode)
12704     {
12705     case BUILT_IN_MEMCPY_CHK:
12706       fn = builtin_decl_explicit (BUILT_IN_MEMCPY);
12707       break;
12708     case BUILT_IN_MEMPCPY_CHK:
12709       fn = builtin_decl_explicit (BUILT_IN_MEMPCPY);
12710       break;
12711     case BUILT_IN_MEMMOVE_CHK:
12712       fn = builtin_decl_explicit (BUILT_IN_MEMMOVE);
12713       break;
12714     case BUILT_IN_MEMSET_CHK:
12715       fn = builtin_decl_explicit (BUILT_IN_MEMSET);
12716       break;
12717     default:
12718       break;
12719     }
12720
12721   if (!fn)
12722     return NULL_TREE;
12723
12724   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12725 }
12726
12727 /* Fold a call to the __st[rp]cpy_chk builtin.
12728    DEST, SRC, and SIZE are the arguments to the call.
12729    IGNORE is true if return value can be ignored.  FCODE is the BUILT_IN_*
12730    code of the builtin.  If MAXLEN is not NULL, it is maximum length of
12731    strings passed as second argument.  */
12732
12733 tree
12734 fold_builtin_stxcpy_chk (location_t loc, tree fndecl, tree dest,
12735                          tree src, tree size,
12736                          tree maxlen, bool ignore,
12737                          enum built_in_function fcode)
12738 {
12739   tree len, fn;
12740
12741   if (!validate_arg (dest, POINTER_TYPE)
12742       || !validate_arg (src, POINTER_TYPE)
12743       || !validate_arg (size, INTEGER_TYPE))
12744     return NULL_TREE;
12745
12746   /* If SRC and DEST are the same (and not volatile), return DEST.  */
12747   if (fcode == BUILT_IN_STRCPY_CHK && operand_equal_p (src, dest, 0))
12748     return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest);
12749
12750   if (! host_integerp (size, 1))
12751     return NULL_TREE;
12752
12753   if (! integer_all_onesp (size))
12754     {
12755       len = c_strlen (src, 1);
12756       if (! len || ! host_integerp (len, 1))
12757         {
12758           /* If LEN is not constant, try MAXLEN too.
12759              For MAXLEN only allow optimizing into non-_ocs function
12760              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12761           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12762             {
12763               if (fcode == BUILT_IN_STPCPY_CHK)
12764                 {
12765                   if (! ignore)
12766                     return NULL_TREE;
12767
12768                   /* If return value of __stpcpy_chk is ignored,
12769                      optimize into __strcpy_chk.  */
12770                   fn = builtin_decl_explicit (BUILT_IN_STRCPY_CHK);
12771                   if (!fn)
12772                     return NULL_TREE;
12773
12774                   return build_call_expr_loc (loc, fn, 3, dest, src, size);
12775                 }
12776
12777               if (! len || TREE_SIDE_EFFECTS (len))
12778                 return NULL_TREE;
12779
12780               /* If c_strlen returned something, but not a constant,
12781                  transform __strcpy_chk into __memcpy_chk.  */
12782               fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
12783               if (!fn)
12784                 return NULL_TREE;
12785
12786               len = fold_convert_loc (loc, size_type_node, len);
12787               len = size_binop_loc (loc, PLUS_EXPR, len,
12788                                     build_int_cst (size_type_node, 1));
12789               return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
12790                                        build_call_expr_loc (loc, fn, 4,
12791                                                         dest, src, len, size));
12792             }
12793         }
12794       else
12795         maxlen = len;
12796
12797       if (! tree_int_cst_lt (maxlen, size))
12798         return NULL_TREE;
12799     }
12800
12801   /* If __builtin_st{r,p}cpy_chk is used, assume st{r,p}cpy is available.  */
12802   fn = builtin_decl_explicit (fcode == BUILT_IN_STPCPY_CHK
12803                               ? BUILT_IN_STPCPY : BUILT_IN_STRCPY);
12804   if (!fn)
12805     return NULL_TREE;
12806
12807   return build_call_expr_loc (loc, fn, 2, dest, src);
12808 }
12809
12810 /* Fold a call to the __strncpy_chk builtin.  DEST, SRC, LEN, and SIZE
12811    are the arguments to the call.  If MAXLEN is not NULL, it is maximum
12812    length passed as third argument.  */
12813
12814 tree
12815 fold_builtin_strncpy_chk (location_t loc, tree dest, tree src,
12816                           tree len, tree size, tree maxlen)
12817 {
12818   tree fn;
12819
12820   if (!validate_arg (dest, POINTER_TYPE)
12821       || !validate_arg (src, POINTER_TYPE)
12822       || !validate_arg (len, INTEGER_TYPE)
12823       || !validate_arg (size, INTEGER_TYPE))
12824     return NULL_TREE;
12825
12826   if (! host_integerp (size, 1))
12827     return NULL_TREE;
12828
12829   if (! integer_all_onesp (size))
12830     {
12831       if (! host_integerp (len, 1))
12832         {
12833           /* If LEN is not constant, try MAXLEN too.
12834              For MAXLEN only allow optimizing into non-_ocs function
12835              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12836           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12837             return NULL_TREE;
12838         }
12839       else
12840         maxlen = len;
12841
12842       if (tree_int_cst_lt (size, maxlen))
12843         return NULL_TREE;
12844     }
12845
12846   /* If __builtin_strncpy_chk is used, assume strncpy is available.  */
12847   fn = builtin_decl_explicit (BUILT_IN_STRNCPY);
12848   if (!fn)
12849     return NULL_TREE;
12850
12851   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12852 }
12853
12854 /* Fold a call to the __strcat_chk builtin FNDECL.  DEST, SRC, and SIZE
12855    are the arguments to the call.  */
12856
12857 static tree
12858 fold_builtin_strcat_chk (location_t loc, tree fndecl, tree dest,
12859                          tree src, tree size)
12860 {
12861   tree fn;
12862   const char *p;
12863
12864   if (!validate_arg (dest, POINTER_TYPE)
12865       || !validate_arg (src, POINTER_TYPE)
12866       || !validate_arg (size, INTEGER_TYPE))
12867     return NULL_TREE;
12868
12869   p = c_getstr (src);
12870   /* If the SRC parameter is "", return DEST.  */
12871   if (p && *p == '\0')
12872     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
12873
12874   if (! host_integerp (size, 1) || ! integer_all_onesp (size))
12875     return NULL_TREE;
12876
12877   /* If __builtin_strcat_chk is used, assume strcat is available.  */
12878   fn = builtin_decl_explicit (BUILT_IN_STRCAT);
12879   if (!fn)
12880     return NULL_TREE;
12881
12882   return build_call_expr_loc (loc, fn, 2, dest, src);
12883 }
12884
12885 /* Fold a call to the __strncat_chk builtin with arguments DEST, SRC,
12886    LEN, and SIZE.  */
12887
12888 static tree
12889 fold_builtin_strncat_chk (location_t loc, tree fndecl,
12890                           tree dest, tree src, tree len, tree size)
12891 {
12892   tree fn;
12893   const char *p;
12894
12895   if (!validate_arg (dest, POINTER_TYPE)
12896       || !validate_arg (src, POINTER_TYPE)
12897       || !validate_arg (size, INTEGER_TYPE)
12898       || !validate_arg (size, INTEGER_TYPE))
12899     return NULL_TREE;
12900
12901   p = c_getstr (src);
12902   /* If the SRC parameter is "" or if LEN is 0, return DEST.  */
12903   if (p && *p == '\0')
12904     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, len);
12905   else if (integer_zerop (len))
12906     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
12907
12908   if (! host_integerp (size, 1))
12909     return NULL_TREE;
12910
12911   if (! integer_all_onesp (size))
12912     {
12913       tree src_len = c_strlen (src, 1);
12914       if (src_len
12915           && host_integerp (src_len, 1)
12916           && host_integerp (len, 1)
12917           && ! tree_int_cst_lt (len, src_len))
12918         {
12919           /* If LEN >= strlen (SRC), optimize into __strcat_chk.  */
12920           fn = builtin_decl_explicit (BUILT_IN_STRCAT_CHK);
12921           if (!fn)
12922             return NULL_TREE;
12923
12924           return build_call_expr_loc (loc, fn, 3, dest, src, size);
12925         }
12926       return NULL_TREE;
12927     }
12928
12929   /* If __builtin_strncat_chk is used, assume strncat is available.  */
12930   fn = builtin_decl_explicit (BUILT_IN_STRNCAT);
12931   if (!fn)
12932     return NULL_TREE;
12933
12934   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12935 }
12936
12937 /* Fold a call EXP to __{,v}sprintf_chk having NARGS passed as ARGS.
12938    Return NULL_TREE if a normal call should be emitted rather than
12939    expanding the function inline.  FCODE is either BUILT_IN_SPRINTF_CHK
12940    or BUILT_IN_VSPRINTF_CHK.  */
12941
12942 static tree
12943 fold_builtin_sprintf_chk_1 (location_t loc, int nargs, tree *args,
12944                             enum built_in_function fcode)
12945 {
12946   tree dest, size, len, fn, fmt, flag;
12947   const char *fmt_str;
12948
12949   /* Verify the required arguments in the original call.  */
12950   if (nargs < 4)
12951     return NULL_TREE;
12952   dest = args[0];
12953   if (!validate_arg (dest, POINTER_TYPE))
12954     return NULL_TREE;
12955   flag = args[1];
12956   if (!validate_arg (flag, INTEGER_TYPE))
12957     return NULL_TREE;
12958   size = args[2];
12959   if (!validate_arg (size, INTEGER_TYPE))
12960     return NULL_TREE;
12961   fmt = args[3];
12962   if (!validate_arg (fmt, POINTER_TYPE))
12963     return NULL_TREE;
12964
12965   if (! host_integerp (size, 1))
12966     return NULL_TREE;
12967
12968   len = NULL_TREE;
12969
12970   if (!init_target_chars ())
12971     return NULL_TREE;
12972
12973   /* Check whether the format is a literal string constant.  */
12974   fmt_str = c_getstr (fmt);
12975   if (fmt_str != NULL)
12976     {
12977       /* If the format doesn't contain % args or %%, we know the size.  */
12978       if (strchr (fmt_str, target_percent) == 0)
12979         {
12980           if (fcode != BUILT_IN_SPRINTF_CHK || nargs == 4)
12981             len = build_int_cstu (size_type_node, strlen (fmt_str));
12982         }
12983       /* If the format is "%s" and first ... argument is a string literal,
12984          we know the size too.  */
12985       else if (fcode == BUILT_IN_SPRINTF_CHK
12986                && strcmp (fmt_str, target_percent_s) == 0)
12987         {
12988           tree arg;
12989
12990           if (nargs == 5)
12991             {
12992               arg = args[4];
12993               if (validate_arg (arg, POINTER_TYPE))
12994                 {
12995                   len = c_strlen (arg, 1);
12996                   if (! len || ! host_integerp (len, 1))
12997                     len = NULL_TREE;
12998                 }
12999             }
13000         }
13001     }
13002
13003   if (! integer_all_onesp (size))
13004     {
13005       if (! len || ! tree_int_cst_lt (len, size))
13006         return NULL_TREE;
13007     }
13008
13009   /* Only convert __{,v}sprintf_chk to {,v}sprintf if flag is 0
13010      or if format doesn't contain % chars or is "%s".  */
13011   if (! integer_zerop (flag))
13012     {
13013       if (fmt_str == NULL)
13014         return NULL_TREE;
13015       if (strchr (fmt_str, target_percent) != NULL
13016           && strcmp (fmt_str, target_percent_s))
13017         return NULL_TREE;
13018     }
13019
13020   /* If __builtin_{,v}sprintf_chk is used, assume {,v}sprintf is available.  */
13021   fn = builtin_decl_explicit (fcode == BUILT_IN_VSPRINTF_CHK
13022                               ? BUILT_IN_VSPRINTF : BUILT_IN_SPRINTF);
13023   if (!fn)
13024     return NULL_TREE;
13025
13026   return rewrite_call_expr_array (loc, nargs, args, 4, fn, 2, dest, fmt);
13027 }
13028
13029 /* Fold a call EXP to __{,v}sprintf_chk.  Return NULL_TREE if
13030    a normal call should be emitted rather than expanding the function
13031    inline.  FCODE is either BUILT_IN_SPRINTF_CHK or BUILT_IN_VSPRINTF_CHK.  */
13032
13033 static tree
13034 fold_builtin_sprintf_chk (location_t loc, tree exp,
13035                           enum built_in_function fcode)
13036 {
13037   return fold_builtin_sprintf_chk_1 (loc, call_expr_nargs (exp),
13038                                      CALL_EXPR_ARGP (exp), fcode);
13039 }
13040
13041 /* Fold a call EXP to {,v}snprintf having NARGS passed as ARGS.  Return
13042    NULL_TREE if a normal call should be emitted rather than expanding
13043    the function inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
13044    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
13045    passed as second argument.  */
13046
13047 static tree
13048 fold_builtin_snprintf_chk_1 (location_t loc, int nargs, tree *args,
13049                              tree maxlen, enum built_in_function fcode)
13050 {
13051   tree dest, size, len, fn, fmt, flag;
13052   const char *fmt_str;
13053
13054   /* Verify the required arguments in the original call.  */
13055   if (nargs < 5)
13056     return NULL_TREE;
13057   dest = args[0];
13058   if (!validate_arg (dest, POINTER_TYPE))
13059     return NULL_TREE;
13060   len = args[1];
13061   if (!validate_arg (len, INTEGER_TYPE))
13062     return NULL_TREE;
13063   flag = args[2];
13064   if (!validate_arg (flag, INTEGER_TYPE))
13065     return NULL_TREE;
13066   size = args[3];
13067   if (!validate_arg (size, INTEGER_TYPE))
13068     return NULL_TREE;
13069   fmt = args[4];
13070   if (!validate_arg (fmt, POINTER_TYPE))
13071     return NULL_TREE;
13072
13073   if (! host_integerp (size, 1))
13074     return NULL_TREE;
13075
13076   if (! integer_all_onesp (size))
13077     {
13078       if (! host_integerp (len, 1))
13079         {
13080           /* If LEN is not constant, try MAXLEN too.
13081              For MAXLEN only allow optimizing into non-_ocs function
13082              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
13083           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
13084             return NULL_TREE;
13085         }
13086       else
13087         maxlen = len;
13088
13089       if (tree_int_cst_lt (size, maxlen))
13090         return NULL_TREE;
13091     }
13092
13093   if (!init_target_chars ())
13094     return NULL_TREE;
13095
13096   /* Only convert __{,v}snprintf_chk to {,v}snprintf if flag is 0
13097      or if format doesn't contain % chars or is "%s".  */
13098   if (! integer_zerop (flag))
13099     {
13100       fmt_str = c_getstr (fmt);
13101       if (fmt_str == NULL)
13102         return NULL_TREE;
13103       if (strchr (fmt_str, target_percent) != NULL
13104           && strcmp (fmt_str, target_percent_s))
13105         return NULL_TREE;
13106     }
13107
13108   /* If __builtin_{,v}snprintf_chk is used, assume {,v}snprintf is
13109      available.  */
13110   fn = builtin_decl_explicit (fcode == BUILT_IN_VSNPRINTF_CHK
13111                               ? BUILT_IN_VSNPRINTF : BUILT_IN_SNPRINTF);
13112   if (!fn)
13113     return NULL_TREE;
13114
13115   return rewrite_call_expr_array (loc, nargs, args, 5, fn, 3, dest, len, fmt);
13116 }
13117
13118 /* Fold a call EXP to {,v}snprintf.  Return NULL_TREE if
13119    a normal call should be emitted rather than expanding the function
13120    inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
13121    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
13122    passed as second argument.  */
13123
13124 tree
13125 fold_builtin_snprintf_chk (location_t loc, tree exp, tree maxlen,
13126                            enum built_in_function fcode)
13127 {
13128   return fold_builtin_snprintf_chk_1 (loc, call_expr_nargs (exp),
13129                                       CALL_EXPR_ARGP (exp), maxlen, fcode);
13130 }
13131
13132 /* Fold a call to the {,v}printf{,_unlocked} and __{,v}printf_chk builtins.
13133    FMT and ARG are the arguments to the call; we don't fold cases with
13134    more than 2 arguments, and ARG may be null if this is a 1-argument case.
13135
13136    Return NULL_TREE if no simplification was possible, otherwise return the
13137    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
13138    code of the function to be simplified.  */
13139
13140 static tree
13141 fold_builtin_printf (location_t loc, tree fndecl, tree fmt,
13142                      tree arg, bool ignore,
13143                      enum built_in_function fcode)
13144 {
13145   tree fn_putchar, fn_puts, newarg, call = NULL_TREE;
13146   const char *fmt_str = NULL;
13147
13148   /* If the return value is used, don't do the transformation.  */
13149   if (! ignore)
13150     return NULL_TREE;
13151
13152   /* Verify the required arguments in the original call.  */
13153   if (!validate_arg (fmt, POINTER_TYPE))
13154     return NULL_TREE;
13155
13156   /* Check whether the format is a literal string constant.  */
13157   fmt_str = c_getstr (fmt);
13158   if (fmt_str == NULL)
13159     return NULL_TREE;
13160
13161   if (fcode == BUILT_IN_PRINTF_UNLOCKED)
13162     {
13163       /* If we're using an unlocked function, assume the other
13164          unlocked functions exist explicitly.  */
13165       fn_putchar = builtin_decl_explicit (BUILT_IN_PUTCHAR_UNLOCKED);
13166       fn_puts = builtin_decl_explicit (BUILT_IN_PUTS_UNLOCKED);
13167     }
13168   else
13169     {
13170       fn_putchar = builtin_decl_implicit (BUILT_IN_PUTCHAR);
13171       fn_puts = builtin_decl_implicit (BUILT_IN_PUTS);
13172     }
13173
13174   if (!init_target_chars ())
13175     return NULL_TREE;
13176
13177   if (strcmp (fmt_str, target_percent_s) == 0
13178       || strchr (fmt_str, target_percent) == NULL)
13179     {
13180       const char *str;
13181
13182       if (strcmp (fmt_str, target_percent_s) == 0)
13183         {
13184           if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
13185             return NULL_TREE;
13186
13187           if (!arg || !validate_arg (arg, POINTER_TYPE))
13188             return NULL_TREE;
13189
13190           str = c_getstr (arg);
13191           if (str == NULL)
13192             return NULL_TREE;
13193         }
13194       else
13195         {
13196           /* The format specifier doesn't contain any '%' characters.  */
13197           if (fcode != BUILT_IN_VPRINTF && fcode != BUILT_IN_VPRINTF_CHK
13198               && arg)
13199             return NULL_TREE;
13200           str = fmt_str;
13201         }
13202
13203       /* If the string was "", printf does nothing.  */
13204       if (str[0] == '\0')
13205         return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
13206
13207       /* If the string has length of 1, call putchar.  */
13208       if (str[1] == '\0')
13209         {
13210           /* Given printf("c"), (where c is any one character,)
13211              convert "c"[0] to an int and pass that to the replacement
13212              function.  */
13213           newarg = build_int_cst (integer_type_node, str[0]);
13214           if (fn_putchar)
13215             call = build_call_expr_loc (loc, fn_putchar, 1, newarg);
13216         }
13217       else
13218         {
13219           /* If the string was "string\n", call puts("string").  */
13220           size_t len = strlen (str);
13221           if ((unsigned char)str[len - 1] == target_newline
13222               && (size_t) (int) len == len
13223               && (int) len > 0)
13224             {
13225               char *newstr;
13226               tree offset_node, string_cst;
13227
13228               /* Create a NUL-terminated string that's one char shorter
13229                  than the original, stripping off the trailing '\n'.  */
13230               newarg = build_string_literal (len, str);
13231               string_cst = string_constant (newarg, &offset_node);
13232               gcc_checking_assert (string_cst
13233                                    && (TREE_STRING_LENGTH (string_cst)
13234                                        == (int) len)
13235                                    && integer_zerop (offset_node)
13236                                    && (unsigned char)
13237                                       TREE_STRING_POINTER (string_cst)[len - 1]
13238                                       == target_newline);
13239               /* build_string_literal creates a new STRING_CST,
13240                  modify it in place to avoid double copying.  */
13241               newstr = CONST_CAST (char *, TREE_STRING_POINTER (string_cst));
13242               newstr[len - 1] = '\0';
13243               if (fn_puts)
13244                 call = build_call_expr_loc (loc, fn_puts, 1, newarg);
13245             }
13246           else
13247             /* We'd like to arrange to call fputs(string,stdout) here,
13248                but we need stdout and don't have a way to get it yet.  */
13249             return NULL_TREE;
13250         }
13251     }
13252
13253   /* The other optimizations can be done only on the non-va_list variants.  */
13254   else if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
13255     return NULL_TREE;
13256
13257   /* If the format specifier was "%s\n", call __builtin_puts(arg).  */
13258   else if (strcmp (fmt_str, target_percent_s_newline) == 0)
13259     {
13260       if (!arg || !validate_arg (arg, POINTER_TYPE))
13261         return NULL_TREE;
13262       if (fn_puts)
13263         call = build_call_expr_loc (loc, fn_puts, 1, arg);
13264     }
13265
13266   /* If the format specifier was "%c", call __builtin_putchar(arg).  */
13267   else if (strcmp (fmt_str, target_percent_c) == 0)
13268     {
13269       if (!arg || !validate_arg (arg, INTEGER_TYPE))
13270         return NULL_TREE;
13271       if (fn_putchar)
13272         call = build_call_expr_loc (loc, fn_putchar, 1, arg);
13273     }
13274
13275   if (!call)
13276     return NULL_TREE;
13277
13278   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), call);
13279 }
13280
13281 /* Fold a call to the {,v}fprintf{,_unlocked} and __{,v}printf_chk builtins.
13282    FP, FMT, and ARG are the arguments to the call.  We don't fold calls with
13283    more than 3 arguments, and ARG may be null in the 2-argument case.
13284
13285    Return NULL_TREE if no simplification was possible, otherwise return the
13286    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
13287    code of the function to be simplified.  */
13288
13289 static tree
13290 fold_builtin_fprintf (location_t loc, tree fndecl, tree fp,
13291                       tree fmt, tree arg, bool ignore,
13292                       enum built_in_function fcode)
13293 {
13294   tree fn_fputc, fn_fputs, call = NULL_TREE;
13295   const char *fmt_str = NULL;
13296
13297   /* If the return value is used, don't do the transformation.  */
13298   if (! ignore)
13299     return NULL_TREE;
13300
13301   /* Verify the required arguments in the original call.  */
13302   if (!validate_arg (fp, POINTER_TYPE))
13303     return NULL_TREE;
13304   if (!validate_arg (fmt, POINTER_TYPE))
13305     return NULL_TREE;
13306
13307   /* Check whether the format is a literal string constant.  */
13308   fmt_str = c_getstr (fmt);
13309   if (fmt_str == NULL)
13310     return NULL_TREE;
13311
13312   if (fcode == BUILT_IN_FPRINTF_UNLOCKED)
13313     {
13314       /* If we're using an unlocked function, assume the other
13315          unlocked functions exist explicitly.  */
13316       fn_fputc = builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED);
13317       fn_fputs = builtin_decl_explicit (BUILT_IN_FPUTS_UNLOCKED);
13318     }
13319   else
13320     {
13321       fn_fputc = builtin_decl_implicit (BUILT_IN_FPUTC);
13322       fn_fputs = builtin_decl_implicit (BUILT_IN_FPUTS);
13323     }
13324
13325   if (!init_target_chars ())
13326     return NULL_TREE;
13327
13328   /* If the format doesn't contain % args or %%, use strcpy.  */
13329   if (strchr (fmt_str, target_percent) == NULL)
13330     {
13331       if (fcode != BUILT_IN_VFPRINTF && fcode != BUILT_IN_VFPRINTF_CHK
13332           && arg)
13333         return NULL_TREE;
13334
13335       /* If the format specifier was "", fprintf does nothing.  */
13336       if (fmt_str[0] == '\0')
13337         {
13338           /* If FP has side-effects, just wait until gimplification is
13339              done.  */
13340           if (TREE_SIDE_EFFECTS (fp))
13341             return NULL_TREE;
13342
13343           return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
13344         }
13345
13346       /* When "string" doesn't contain %, replace all cases of
13347          fprintf (fp, string) with fputs (string, fp).  The fputs
13348          builtin will take care of special cases like length == 1.  */
13349       if (fn_fputs)
13350         call = build_call_expr_loc (loc, fn_fputs, 2, fmt, fp);
13351     }
13352
13353   /* The other optimizations can be done only on the non-va_list variants.  */
13354   else if (fcode == BUILT_IN_VFPRINTF || fcode == BUILT_IN_VFPRINTF_CHK)
13355     return NULL_TREE;
13356
13357   /* If the format specifier was "%s", call __builtin_fputs (arg, fp).  */
13358   else if (strcmp (fmt_str, target_percent_s) == 0)
13359     {
13360       if (!arg || !validate_arg (arg, POINTER_TYPE))
13361         return NULL_TREE;
13362       if (fn_fputs)
13363         call = build_call_expr_loc (loc, fn_fputs, 2, arg, fp);
13364     }
13365
13366   /* If the format specifier was "%c", call __builtin_fputc (arg, fp).  */
13367   else if (strcmp (fmt_str, target_percent_c) == 0)
13368     {
13369       if (!arg || !validate_arg (arg, INTEGER_TYPE))
13370         return NULL_TREE;
13371       if (fn_fputc)
13372         call = build_call_expr_loc (loc, fn_fputc, 2, arg, fp);
13373     }
13374
13375   if (!call)
13376     return NULL_TREE;
13377   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), call);
13378 }
13379
13380 /* Initialize format string characters in the target charset.  */
13381
13382 static bool
13383 init_target_chars (void)
13384 {
13385   static bool init;
13386   if (!init)
13387     {
13388       target_newline = lang_hooks.to_target_charset ('\n');
13389       target_percent = lang_hooks.to_target_charset ('%');
13390       target_c = lang_hooks.to_target_charset ('c');
13391       target_s = lang_hooks.to_target_charset ('s');
13392       if (target_newline == 0 || target_percent == 0 || target_c == 0
13393           || target_s == 0)
13394         return false;
13395
13396       target_percent_c[0] = target_percent;
13397       target_percent_c[1] = target_c;
13398       target_percent_c[2] = '\0';
13399
13400       target_percent_s[0] = target_percent;
13401       target_percent_s[1] = target_s;
13402       target_percent_s[2] = '\0';
13403
13404       target_percent_s_newline[0] = target_percent;
13405       target_percent_s_newline[1] = target_s;
13406       target_percent_s_newline[2] = target_newline;
13407       target_percent_s_newline[3] = '\0';
13408
13409       init = true;
13410     }
13411   return true;
13412 }
13413
13414 /* Helper function for do_mpfr_arg*().  Ensure M is a normal number
13415    and no overflow/underflow occurred.  INEXACT is true if M was not
13416    exactly calculated.  TYPE is the tree type for the result.  This
13417    function assumes that you cleared the MPFR flags and then
13418    calculated M to see if anything subsequently set a flag prior to
13419    entering this function.  Return NULL_TREE if any checks fail.  */
13420
13421 static tree
13422 do_mpfr_ckconv (mpfr_srcptr m, tree type, int inexact)
13423 {
13424   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
13425      overflow/underflow occurred.  If -frounding-math, proceed iff the
13426      result of calling FUNC was exact.  */
13427   if (mpfr_number_p (m) && !mpfr_overflow_p () && !mpfr_underflow_p ()
13428       && (!flag_rounding_math || !inexact))
13429     {
13430       REAL_VALUE_TYPE rr;
13431
13432       real_from_mpfr (&rr, m, type, GMP_RNDN);
13433       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR value,
13434          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
13435          but the mpft_t is not, then we underflowed in the
13436          conversion.  */
13437       if (real_isfinite (&rr)
13438           && (rr.cl == rvc_zero) == (mpfr_zero_p (m) != 0))
13439         {
13440           REAL_VALUE_TYPE rmode;
13441
13442           real_convert (&rmode, TYPE_MODE (type), &rr);
13443           /* Proceed iff the specified mode can hold the value.  */
13444           if (real_identical (&rmode, &rr))
13445             return build_real (type, rmode);
13446         }
13447     }
13448   return NULL_TREE;
13449 }
13450
13451 /* Helper function for do_mpc_arg*().  Ensure M is a normal complex
13452    number and no overflow/underflow occurred.  INEXACT is true if M
13453    was not exactly calculated.  TYPE is the tree type for the result.
13454    This function assumes that you cleared the MPFR flags and then
13455    calculated M to see if anything subsequently set a flag prior to
13456    entering this function.  Return NULL_TREE if any checks fail, if
13457    FORCE_CONVERT is true, then bypass the checks.  */
13458
13459 static tree
13460 do_mpc_ckconv (mpc_srcptr m, tree type, int inexact, int force_convert)
13461 {
13462   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
13463      overflow/underflow occurred.  If -frounding-math, proceed iff the
13464      result of calling FUNC was exact.  */
13465   if (force_convert
13466       || (mpfr_number_p (mpc_realref (m)) && mpfr_number_p (mpc_imagref (m))
13467           && !mpfr_overflow_p () && !mpfr_underflow_p ()
13468           && (!flag_rounding_math || !inexact)))
13469     {
13470       REAL_VALUE_TYPE re, im;
13471
13472       real_from_mpfr (&re, mpc_realref (m), TREE_TYPE (type), GMP_RNDN);
13473       real_from_mpfr (&im, mpc_imagref (m), TREE_TYPE (type), GMP_RNDN);
13474       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR values,
13475          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
13476          but the mpft_t is not, then we underflowed in the
13477          conversion.  */
13478       if (force_convert
13479           || (real_isfinite (&re) && real_isfinite (&im)
13480               && (re.cl == rvc_zero) == (mpfr_zero_p (mpc_realref (m)) != 0)
13481               && (im.cl == rvc_zero) == (mpfr_zero_p (mpc_imagref (m)) != 0)))
13482         {
13483           REAL_VALUE_TYPE re_mode, im_mode;
13484
13485           real_convert (&re_mode, TYPE_MODE (TREE_TYPE (type)), &re);
13486           real_convert (&im_mode, TYPE_MODE (TREE_TYPE (type)), &im);
13487           /* Proceed iff the specified mode can hold the value.  */
13488           if (force_convert
13489               || (real_identical (&re_mode, &re)
13490                   && real_identical (&im_mode, &im)))
13491             return build_complex (type, build_real (TREE_TYPE (type), re_mode),
13492                                   build_real (TREE_TYPE (type), im_mode));
13493         }
13494     }
13495   return NULL_TREE;
13496 }
13497
13498 /* If argument ARG is a REAL_CST, call the one-argument mpfr function
13499    FUNC on it and return the resulting value as a tree with type TYPE.
13500    If MIN and/or MAX are not NULL, then the supplied ARG must be
13501    within those bounds.  If INCLUSIVE is true, then MIN/MAX are
13502    acceptable values, otherwise they are not.  The mpfr precision is
13503    set to the precision of TYPE.  We assume that function FUNC returns
13504    zero if the result could be calculated exactly within the requested
13505    precision.  */
13506
13507 static tree
13508 do_mpfr_arg1 (tree arg, tree type, int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t),
13509               const REAL_VALUE_TYPE *min, const REAL_VALUE_TYPE *max,
13510               bool inclusive)
13511 {
13512   tree result = NULL_TREE;
13513
13514   STRIP_NOPS (arg);
13515
13516   /* To proceed, MPFR must exactly represent the target floating point
13517      format, which only happens when the target base equals two.  */
13518   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13519       && TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
13520     {
13521       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg);
13522
13523       if (real_isfinite (ra)
13524           && (!min || real_compare (inclusive ? GE_EXPR: GT_EXPR , ra, min))
13525           && (!max || real_compare (inclusive ? LE_EXPR: LT_EXPR , ra, max)))
13526         {
13527           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13528           const int prec = fmt->p;
13529           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13530           int inexact;
13531           mpfr_t m;
13532
13533           mpfr_init2 (m, prec);
13534           mpfr_from_real (m, ra, GMP_RNDN);
13535           mpfr_clear_flags ();
13536           inexact = func (m, m, rnd);
13537           result = do_mpfr_ckconv (m, type, inexact);
13538           mpfr_clear (m);
13539         }
13540     }
13541
13542   return result;
13543 }
13544
13545 /* If argument ARG is a REAL_CST, call the two-argument mpfr function
13546    FUNC on it and return the resulting value as a tree with type TYPE.
13547    The mpfr precision is set to the precision of TYPE.  We assume that
13548    function FUNC returns zero if the result could be calculated
13549    exactly within the requested precision.  */
13550
13551 static tree
13552 do_mpfr_arg2 (tree arg1, tree arg2, tree type,
13553               int (*func)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t))
13554 {
13555   tree result = NULL_TREE;
13556
13557   STRIP_NOPS (arg1);
13558   STRIP_NOPS (arg2);
13559
13560   /* To proceed, MPFR must exactly represent the target floating point
13561      format, which only happens when the target base equals two.  */
13562   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13563       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1)
13564       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2))
13565     {
13566       const REAL_VALUE_TYPE *const ra1 = &TREE_REAL_CST (arg1);
13567       const REAL_VALUE_TYPE *const ra2 = &TREE_REAL_CST (arg2);
13568
13569       if (real_isfinite (ra1) && real_isfinite (ra2))
13570         {
13571           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13572           const int prec = fmt->p;
13573           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13574           int inexact;
13575           mpfr_t m1, m2;
13576
13577           mpfr_inits2 (prec, m1, m2, NULL);
13578           mpfr_from_real (m1, ra1, GMP_RNDN);
13579           mpfr_from_real (m2, ra2, GMP_RNDN);
13580           mpfr_clear_flags ();
13581           inexact = func (m1, m1, m2, rnd);
13582           result = do_mpfr_ckconv (m1, type, inexact);
13583           mpfr_clears (m1, m2, NULL);
13584         }
13585     }
13586
13587   return result;
13588 }
13589
13590 /* If argument ARG is a REAL_CST, call the three-argument mpfr function
13591    FUNC on it and return the resulting value as a tree with type TYPE.
13592    The mpfr precision is set to the precision of TYPE.  We assume that
13593    function FUNC returns zero if the result could be calculated
13594    exactly within the requested precision.  */
13595
13596 static tree
13597 do_mpfr_arg3 (tree arg1, tree arg2, tree arg3, tree type,
13598               int (*func)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t))
13599 {
13600   tree result = NULL_TREE;
13601
13602   STRIP_NOPS (arg1);
13603   STRIP_NOPS (arg2);
13604   STRIP_NOPS (arg3);
13605
13606   /* To proceed, MPFR must exactly represent the target floating point
13607      format, which only happens when the target base equals two.  */
13608   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13609       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1)
13610       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2)
13611       && TREE_CODE (arg3) == REAL_CST && !TREE_OVERFLOW (arg3))
13612     {
13613       const REAL_VALUE_TYPE *const ra1 = &TREE_REAL_CST (arg1);
13614       const REAL_VALUE_TYPE *const ra2 = &TREE_REAL_CST (arg2);
13615       const REAL_VALUE_TYPE *const ra3 = &TREE_REAL_CST (arg3);
13616
13617       if (real_isfinite (ra1) && real_isfinite (ra2) && real_isfinite (ra3))
13618         {
13619           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13620           const int prec = fmt->p;
13621           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13622           int inexact;
13623           mpfr_t m1, m2, m3;
13624
13625           mpfr_inits2 (prec, m1, m2, m3, NULL);
13626           mpfr_from_real (m1, ra1, GMP_RNDN);
13627           mpfr_from_real (m2, ra2, GMP_RNDN);
13628           mpfr_from_real (m3, ra3, GMP_RNDN);
13629           mpfr_clear_flags ();
13630           inexact = func (m1, m1, m2, m3, rnd);
13631           result = do_mpfr_ckconv (m1, type, inexact);
13632           mpfr_clears (m1, m2, m3, NULL);
13633         }
13634     }
13635
13636   return result;
13637 }
13638
13639 /* If argument ARG is a REAL_CST, call mpfr_sin_cos() on it and set
13640    the pointers *(ARG_SINP) and *(ARG_COSP) to the resulting values.
13641    If ARG_SINP and ARG_COSP are NULL then the result is returned
13642    as a complex value.
13643    The type is taken from the type of ARG and is used for setting the
13644    precision of the calculation and results.  */
13645
13646 static tree
13647 do_mpfr_sincos (tree arg, tree arg_sinp, tree arg_cosp)
13648 {
13649   tree const type = TREE_TYPE (arg);
13650   tree result = NULL_TREE;
13651
13652   STRIP_NOPS (arg);
13653
13654   /* To proceed, MPFR must exactly represent the target floating point
13655      format, which only happens when the target base equals two.  */
13656   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13657       && TREE_CODE (arg) == REAL_CST
13658       && !TREE_OVERFLOW (arg))
13659     {
13660       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg);
13661
13662       if (real_isfinite (ra))
13663         {
13664           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13665           const int prec = fmt->p;
13666           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13667           tree result_s, result_c;
13668           int inexact;
13669           mpfr_t m, ms, mc;
13670
13671           mpfr_inits2 (prec, m, ms, mc, NULL);
13672           mpfr_from_real (m, ra, GMP_RNDN);
13673           mpfr_clear_flags ();
13674           inexact = mpfr_sin_cos (ms, mc, m, rnd);
13675           result_s = do_mpfr_ckconv (ms, type, inexact);
13676           result_c = do_mpfr_ckconv (mc, type, inexact);
13677           mpfr_clears (m, ms, mc, NULL);
13678           if (result_s && result_c)
13679             {
13680               /* If we are to return in a complex value do so.  */
13681               if (!arg_sinp && !arg_cosp)
13682                 return build_complex (build_complex_type (type),
13683                                       result_c, result_s);
13684
13685               /* Dereference the sin/cos pointer arguments.  */
13686               arg_sinp = build_fold_indirect_ref (arg_sinp);
13687               arg_cosp = build_fold_indirect_ref (arg_cosp);
13688               /* Proceed if valid pointer type were passed in.  */
13689               if (TYPE_MAIN_VARIANT (TREE_TYPE (arg_sinp)) == TYPE_MAIN_VARIANT (type)
13690                   && TYPE_MAIN_VARIANT (TREE_TYPE (arg_cosp)) == TYPE_MAIN_VARIANT (type))
13691                 {
13692                   /* Set the values. */
13693                   result_s = fold_build2 (MODIFY_EXPR, type, arg_sinp,
13694                                           result_s);
13695                   TREE_SIDE_EFFECTS (result_s) = 1;
13696                   result_c = fold_build2 (MODIFY_EXPR, type, arg_cosp,
13697                                           result_c);
13698                   TREE_SIDE_EFFECTS (result_c) = 1;
13699                   /* Combine the assignments into a compound expr.  */
13700                   result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13701                                                     result_s, result_c));
13702                 }
13703             }
13704         }
13705     }
13706   return result;
13707 }
13708
13709 /* If argument ARG1 is an INTEGER_CST and ARG2 is a REAL_CST, call the
13710    two-argument mpfr order N Bessel function FUNC on them and return
13711    the resulting value as a tree with type TYPE.  The mpfr precision
13712    is set to the precision of TYPE.  We assume that function FUNC
13713    returns zero if the result could be calculated exactly within the
13714    requested precision.  */
13715 static tree
13716 do_mpfr_bessel_n (tree arg1, tree arg2, tree type,
13717                   int (*func)(mpfr_ptr, long, mpfr_srcptr, mp_rnd_t),
13718                   const REAL_VALUE_TYPE *min, bool inclusive)
13719 {
13720   tree result = NULL_TREE;
13721
13722   STRIP_NOPS (arg1);
13723   STRIP_NOPS (arg2);
13724
13725   /* To proceed, MPFR must exactly represent the target floating point
13726      format, which only happens when the target base equals two.  */
13727   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13728       && host_integerp (arg1, 0)
13729       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2))
13730     {
13731       const HOST_WIDE_INT n = tree_low_cst(arg1, 0);
13732       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg2);
13733
13734       if (n == (long)n
13735           && real_isfinite (ra)
13736           && (!min || real_compare (inclusive ? GE_EXPR: GT_EXPR , ra, min)))
13737         {
13738           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13739           const int prec = fmt->p;
13740           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13741           int inexact;
13742           mpfr_t m;
13743
13744           mpfr_init2 (m, prec);
13745           mpfr_from_real (m, ra, GMP_RNDN);
13746           mpfr_clear_flags ();
13747           inexact = func (m, n, m, rnd);
13748           result = do_mpfr_ckconv (m, type, inexact);
13749           mpfr_clear (m);
13750         }
13751     }
13752
13753   return result;
13754 }
13755
13756 /* If arguments ARG0 and ARG1 are REAL_CSTs, call mpfr_remquo() to set
13757    the pointer *(ARG_QUO) and return the result.  The type is taken
13758    from the type of ARG0 and is used for setting the precision of the
13759    calculation and results.  */
13760
13761 static tree
13762 do_mpfr_remquo (tree arg0, tree arg1, tree arg_quo)
13763 {
13764   tree const type = TREE_TYPE (arg0);
13765   tree result = NULL_TREE;
13766
13767   STRIP_NOPS (arg0);
13768   STRIP_NOPS (arg1);
13769
13770   /* To proceed, MPFR must exactly represent the target floating point
13771      format, which only happens when the target base equals two.  */
13772   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13773       && TREE_CODE (arg0) == REAL_CST && !TREE_OVERFLOW (arg0)
13774       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1))
13775     {
13776       const REAL_VALUE_TYPE *const ra0 = TREE_REAL_CST_PTR (arg0);
13777       const REAL_VALUE_TYPE *const ra1 = TREE_REAL_CST_PTR (arg1);
13778
13779       if (real_isfinite (ra0) && real_isfinite (ra1))
13780         {
13781           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13782           const int prec = fmt->p;
13783           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13784           tree result_rem;
13785           long integer_quo;
13786           mpfr_t m0, m1;
13787
13788           mpfr_inits2 (prec, m0, m1, NULL);
13789           mpfr_from_real (m0, ra0, GMP_RNDN);
13790           mpfr_from_real (m1, ra1, GMP_RNDN);
13791           mpfr_clear_flags ();
13792           mpfr_remquo (m0, &integer_quo, m0, m1, rnd);
13793           /* Remquo is independent of the rounding mode, so pass
13794              inexact=0 to do_mpfr_ckconv().  */
13795           result_rem = do_mpfr_ckconv (m0, type, /*inexact=*/ 0);
13796           mpfr_clears (m0, m1, NULL);
13797           if (result_rem)
13798             {
13799               /* MPFR calculates quo in the host's long so it may
13800                  return more bits in quo than the target int can hold
13801                  if sizeof(host long) > sizeof(target int).  This can
13802                  happen even for native compilers in LP64 mode.  In
13803                  these cases, modulo the quo value with the largest
13804                  number that the target int can hold while leaving one
13805                  bit for the sign.  */
13806               if (sizeof (integer_quo) * CHAR_BIT > INT_TYPE_SIZE)
13807                 integer_quo %= (long)(1UL << (INT_TYPE_SIZE - 1));
13808
13809               /* Dereference the quo pointer argument.  */
13810               arg_quo = build_fold_indirect_ref (arg_quo);
13811               /* Proceed iff a valid pointer type was passed in.  */
13812               if (TYPE_MAIN_VARIANT (TREE_TYPE (arg_quo)) == integer_type_node)
13813                 {
13814                   /* Set the value. */
13815                   tree result_quo
13816                     = fold_build2 (MODIFY_EXPR, TREE_TYPE (arg_quo), arg_quo,
13817                                    build_int_cst (TREE_TYPE (arg_quo),
13818                                                   integer_quo));
13819                   TREE_SIDE_EFFECTS (result_quo) = 1;
13820                   /* Combine the quo assignment with the rem.  */
13821                   result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13822                                                     result_quo, result_rem));
13823                 }
13824             }
13825         }
13826     }
13827   return result;
13828 }
13829
13830 /* If ARG is a REAL_CST, call mpfr_lgamma() on it and return the
13831    resulting value as a tree with type TYPE.  The mpfr precision is
13832    set to the precision of TYPE.  We assume that this mpfr function
13833    returns zero if the result could be calculated exactly within the
13834    requested precision.  In addition, the integer pointer represented
13835    by ARG_SG will be dereferenced and set to the appropriate signgam
13836    (-1,1) value.  */
13837
13838 static tree
13839 do_mpfr_lgamma_r (tree arg, tree arg_sg, tree type)
13840 {
13841   tree result = NULL_TREE;
13842
13843   STRIP_NOPS (arg);
13844
13845   /* To proceed, MPFR must exactly represent the target floating point
13846      format, which only happens when the target base equals two.  Also
13847      verify ARG is a constant and that ARG_SG is an int pointer.  */
13848   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13849       && TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg)
13850       && TREE_CODE (TREE_TYPE (arg_sg)) == POINTER_TYPE
13851       && TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (arg_sg))) == integer_type_node)
13852     {
13853       const REAL_VALUE_TYPE *const ra = TREE_REAL_CST_PTR (arg);
13854
13855       /* In addition to NaN and Inf, the argument cannot be zero or a
13856          negative integer.  */
13857       if (real_isfinite (ra)
13858           && ra->cl != rvc_zero
13859           && !(real_isneg(ra) && real_isinteger(ra, TYPE_MODE (type))))
13860         {
13861           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13862           const int prec = fmt->p;
13863           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13864           int inexact, sg;
13865           mpfr_t m;
13866           tree result_lg;
13867
13868           mpfr_init2 (m, prec);
13869           mpfr_from_real (m, ra, GMP_RNDN);
13870           mpfr_clear_flags ();
13871           inexact = mpfr_lgamma (m, &sg, m, rnd);
13872           result_lg = do_mpfr_ckconv (m, type, inexact);
13873           mpfr_clear (m);
13874           if (result_lg)
13875             {
13876               tree result_sg;
13877
13878               /* Dereference the arg_sg pointer argument.  */
13879               arg_sg = build_fold_indirect_ref (arg_sg);
13880               /* Assign the signgam value into *arg_sg. */
13881               result_sg = fold_build2 (MODIFY_EXPR,
13882                                        TREE_TYPE (arg_sg), arg_sg,
13883                                        build_int_cst (TREE_TYPE (arg_sg), sg));
13884               TREE_SIDE_EFFECTS (result_sg) = 1;
13885               /* Combine the signgam assignment with the lgamma result.  */
13886               result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13887                                                 result_sg, result_lg));
13888             }
13889         }
13890     }
13891
13892   return result;
13893 }
13894
13895 /* If argument ARG is a COMPLEX_CST, call the one-argument mpc
13896    function FUNC on it and return the resulting value as a tree with
13897    type TYPE.  The mpfr precision is set to the precision of TYPE.  We
13898    assume that function FUNC returns zero if the result could be
13899    calculated exactly within the requested precision.  */
13900
13901 static tree
13902 do_mpc_arg1 (tree arg, tree type, int (*func)(mpc_ptr, mpc_srcptr, mpc_rnd_t))
13903 {
13904   tree result = NULL_TREE;
13905
13906   STRIP_NOPS (arg);
13907
13908   /* To proceed, MPFR must exactly represent the target floating point
13909      format, which only happens when the target base equals two.  */
13910   if (TREE_CODE (arg) == COMPLEX_CST && !TREE_OVERFLOW (arg)
13911       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE
13912       && REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (TREE_TYPE (arg))))->b == 2)
13913     {
13914       const REAL_VALUE_TYPE *const re = TREE_REAL_CST_PTR (TREE_REALPART (arg));
13915       const REAL_VALUE_TYPE *const im = TREE_REAL_CST_PTR (TREE_IMAGPART (arg));
13916
13917       if (real_isfinite (re) && real_isfinite (im))
13918         {
13919           const struct real_format *const fmt =
13920             REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (type)));
13921           const int prec = fmt->p;
13922           const mp_rnd_t rnd = fmt->round_towards_zero ? GMP_RNDZ : GMP_RNDN;
13923           const mpc_rnd_t crnd = fmt->round_towards_zero ? MPC_RNDZZ : MPC_RNDNN;
13924           int inexact;
13925           mpc_t m;
13926
13927           mpc_init2 (m, prec);
13928           mpfr_from_real (mpc_realref(m), re, rnd);
13929           mpfr_from_real (mpc_imagref(m), im, rnd);
13930           mpfr_clear_flags ();
13931           inexact = func (m, m, crnd);
13932           result = do_mpc_ckconv (m, type, inexact, /*force_convert=*/ 0);
13933           mpc_clear (m);
13934         }
13935     }
13936
13937   return result;
13938 }
13939
13940 /* If arguments ARG0 and ARG1 are a COMPLEX_CST, call the two-argument
13941    mpc function FUNC on it and return the resulting value as a tree
13942    with type TYPE.  The mpfr precision is set to the precision of
13943    TYPE.  We assume that function FUNC returns zero if the result
13944    could be calculated exactly within the requested precision.  If
13945    DO_NONFINITE is true, then fold expressions containing Inf or NaN
13946    in the arguments and/or results.  */
13947
13948 tree
13949 do_mpc_arg2 (tree arg0, tree arg1, tree type, int do_nonfinite,
13950              int (*func)(mpc_ptr, mpc_srcptr, mpc_srcptr, mpc_rnd_t))
13951 {
13952   tree result = NULL_TREE;
13953
13954   STRIP_NOPS (arg0);
13955   STRIP_NOPS (arg1);
13956
13957   /* To proceed, MPFR must exactly represent the target floating point
13958      format, which only happens when the target base equals two.  */
13959   if (TREE_CODE (arg0) == COMPLEX_CST && !TREE_OVERFLOW (arg0)
13960       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE
13961       && TREE_CODE (arg1) == COMPLEX_CST && !TREE_OVERFLOW (arg1)
13962       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg1))) == REAL_TYPE
13963       && REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (TREE_TYPE (arg0))))->b == 2)
13964     {
13965       const REAL_VALUE_TYPE *const re0 = TREE_REAL_CST_PTR (TREE_REALPART (arg0));
13966       const REAL_VALUE_TYPE *const im0 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg0));
13967       const REAL_VALUE_TYPE *const re1 = TREE_REAL_CST_PTR (TREE_REALPART (arg1));
13968       const REAL_VALUE_TYPE *const im1 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg1));
13969
13970       if (do_nonfinite
13971           || (real_isfinite (re0) && real_isfinite (im0)
13972               && real_isfinite (re1) && real_isfinite (im1)))
13973         {
13974           const struct real_format *const fmt =
13975             REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (type)));
13976           const int prec = fmt->p;
13977           const mp_rnd_t rnd = fmt->round_towards_zero ? GMP_RNDZ : GMP_RNDN;
13978           const mpc_rnd_t crnd = fmt->round_towards_zero ? MPC_RNDZZ : MPC_RNDNN;
13979           int inexact;
13980           mpc_t m0, m1;
13981
13982           mpc_init2 (m0, prec);
13983           mpc_init2 (m1, prec);
13984           mpfr_from_real (mpc_realref(m0), re0, rnd);
13985           mpfr_from_real (mpc_imagref(m0), im0, rnd);
13986           mpfr_from_real (mpc_realref(m1), re1, rnd);
13987           mpfr_from_real (mpc_imagref(m1), im1, rnd);
13988           mpfr_clear_flags ();
13989           inexact = func (m0, m0, m1, crnd);
13990           result = do_mpc_ckconv (m0, type, inexact, do_nonfinite);
13991           mpc_clear (m0);
13992           mpc_clear (m1);
13993         }
13994     }
13995
13996   return result;
13997 }
13998
13999 /* Fold a call STMT to __{,v}sprintf_chk.  Return NULL_TREE if
14000    a normal call should be emitted rather than expanding the function
14001    inline.  FCODE is either BUILT_IN_SPRINTF_CHK or BUILT_IN_VSPRINTF_CHK.  */
14002
14003 static tree
14004 gimple_fold_builtin_sprintf_chk (gimple stmt, enum built_in_function fcode)
14005 {
14006   int nargs = gimple_call_num_args (stmt);
14007
14008   return fold_builtin_sprintf_chk_1 (gimple_location (stmt), nargs,
14009                                      (nargs > 0
14010                                       ? gimple_call_arg_ptr (stmt, 0)
14011                                       : &error_mark_node), fcode);
14012 }
14013
14014 /* Fold a call STMT to {,v}snprintf.  Return NULL_TREE if
14015    a normal call should be emitted rather than expanding the function
14016    inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
14017    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
14018    passed as second argument.  */
14019
14020 tree
14021 gimple_fold_builtin_snprintf_chk (gimple stmt, tree maxlen,
14022                                   enum built_in_function fcode)
14023 {
14024   int nargs = gimple_call_num_args (stmt);
14025
14026   return fold_builtin_snprintf_chk_1 (gimple_location (stmt), nargs,
14027                                       (nargs > 0
14028                                        ? gimple_call_arg_ptr (stmt, 0)
14029                                        : &error_mark_node), maxlen, fcode);
14030 }
14031
14032 /* Builtins with folding operations that operate on "..." arguments
14033    need special handling; we need to store the arguments in a convenient
14034    data structure before attempting any folding.  Fortunately there are
14035    only a few builtins that fall into this category.  FNDECL is the
14036    function, EXP is the CALL_EXPR for the call, and IGNORE is true if the
14037    result of the function call is ignored.  */
14038
14039 static tree
14040 gimple_fold_builtin_varargs (tree fndecl, gimple stmt,
14041                              bool ignore ATTRIBUTE_UNUSED)
14042 {
14043   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
14044   tree ret = NULL_TREE;
14045
14046   switch (fcode)
14047     {
14048     case BUILT_IN_SPRINTF_CHK:
14049     case BUILT_IN_VSPRINTF_CHK:
14050       ret = gimple_fold_builtin_sprintf_chk (stmt, fcode);
14051       break;
14052
14053     case BUILT_IN_SNPRINTF_CHK:
14054     case BUILT_IN_VSNPRINTF_CHK:
14055       ret = gimple_fold_builtin_snprintf_chk (stmt, NULL_TREE, fcode);
14056
14057     default:
14058       break;
14059     }
14060   if (ret)
14061     {
14062       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
14063       TREE_NO_WARNING (ret) = 1;
14064       return ret;
14065     }
14066   return NULL_TREE;
14067 }
14068
14069 /* A wrapper function for builtin folding that prevents warnings for
14070    "statement without effect" and the like, caused by removing the
14071    call node earlier than the warning is generated.  */
14072
14073 tree
14074 fold_call_stmt (gimple stmt, bool ignore)
14075 {
14076   tree ret = NULL_TREE;
14077   tree fndecl = gimple_call_fndecl (stmt);
14078   location_t loc = gimple_location (stmt);
14079   if (fndecl
14080       && TREE_CODE (fndecl) == FUNCTION_DECL
14081       && DECL_BUILT_IN (fndecl)
14082       && !gimple_call_va_arg_pack_p (stmt))
14083     {
14084       int nargs = gimple_call_num_args (stmt);
14085       tree *args = (nargs > 0
14086                     ? gimple_call_arg_ptr (stmt, 0)
14087                     : &error_mark_node);
14088
14089       if (avoid_folding_inline_builtin (fndecl))
14090         return NULL_TREE;
14091       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
14092         {
14093           return targetm.fold_builtin (fndecl, nargs, args, ignore);
14094         }
14095       else
14096         {
14097           if (nargs <= MAX_ARGS_TO_FOLD_BUILTIN)
14098             ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
14099           if (!ret)
14100             ret = gimple_fold_builtin_varargs (fndecl, stmt, ignore);
14101           if (ret)
14102             {
14103               /* Propagate location information from original call to
14104                  expansion of builtin.  Otherwise things like
14105                  maybe_emit_chk_warning, that operate on the expansion
14106                  of a builtin, will use the wrong location information.  */
14107               if (gimple_has_location (stmt))
14108                 {
14109                   tree realret = ret;
14110                   if (TREE_CODE (ret) == NOP_EXPR)
14111                     realret = TREE_OPERAND (ret, 0);
14112                   if (CAN_HAVE_LOCATION_P (realret)
14113                       && !EXPR_HAS_LOCATION (realret))
14114                     SET_EXPR_LOCATION (realret, loc);
14115                   return realret;
14116                 }
14117               return ret;
14118             }
14119         }
14120     }
14121   return NULL_TREE;
14122 }
14123
14124 /* Look up the function in builtin_decl that corresponds to DECL
14125    and set ASMSPEC as its user assembler name.  DECL must be a
14126    function decl that declares a builtin.  */
14127
14128 void
14129 set_builtin_user_assembler_name (tree decl, const char *asmspec)
14130 {
14131   tree builtin;
14132   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
14133               && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
14134               && asmspec != 0);
14135
14136   builtin = builtin_decl_explicit (DECL_FUNCTION_CODE (decl));
14137   set_user_assembler_name (builtin, asmspec);
14138   switch (DECL_FUNCTION_CODE (decl))
14139     {
14140     case BUILT_IN_MEMCPY:
14141       init_block_move_fn (asmspec);
14142       memcpy_libfunc = set_user_assembler_libfunc ("memcpy", asmspec);
14143       break;
14144     case BUILT_IN_MEMSET:
14145       init_block_clear_fn (asmspec);
14146       memset_libfunc = set_user_assembler_libfunc ("memset", asmspec);
14147       break;
14148     case BUILT_IN_MEMMOVE:
14149       memmove_libfunc = set_user_assembler_libfunc ("memmove", asmspec);
14150       break;
14151     case BUILT_IN_MEMCMP:
14152       memcmp_libfunc = set_user_assembler_libfunc ("memcmp", asmspec);
14153       break;
14154     case BUILT_IN_ABORT:
14155       abort_libfunc = set_user_assembler_libfunc ("abort", asmspec);
14156       break;
14157     case BUILT_IN_FFS:
14158       if (INT_TYPE_SIZE < BITS_PER_WORD)
14159         {
14160           set_user_assembler_libfunc ("ffs", asmspec);
14161           set_optab_libfunc (ffs_optab, mode_for_size (INT_TYPE_SIZE,
14162                                                        MODE_INT, 0), "ffs");
14163         }
14164       break;
14165     default:
14166       break;
14167     }
14168 }
14169
14170 /* Return true if DECL is a builtin that expands to a constant or similarly
14171    simple code.  */
14172 bool
14173 is_simple_builtin (tree decl)
14174 {
14175   if (decl && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
14176     switch (DECL_FUNCTION_CODE (decl))
14177       {
14178         /* Builtins that expand to constants.  */
14179       case BUILT_IN_CONSTANT_P:
14180       case BUILT_IN_EXPECT:
14181       case BUILT_IN_OBJECT_SIZE:
14182       case BUILT_IN_UNREACHABLE:
14183         /* Simple register moves or loads from stack.  */
14184       case BUILT_IN_ASSUME_ALIGNED:
14185       case BUILT_IN_RETURN_ADDRESS:
14186       case BUILT_IN_EXTRACT_RETURN_ADDR:
14187       case BUILT_IN_FROB_RETURN_ADDR:
14188       case BUILT_IN_RETURN:
14189       case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
14190       case BUILT_IN_FRAME_ADDRESS:
14191       case BUILT_IN_VA_END:
14192       case BUILT_IN_STACK_SAVE:
14193       case BUILT_IN_STACK_RESTORE:
14194         /* Exception state returns or moves registers around.  */
14195       case BUILT_IN_EH_FILTER:
14196       case BUILT_IN_EH_POINTER:
14197       case BUILT_IN_EH_COPY_VALUES:
14198         return true;
14199
14200       default:
14201         return false;
14202       }
14203
14204   return false;
14205 }
14206
14207 /* Return true if DECL is a builtin that is not expensive, i.e., they are
14208    most probably expanded inline into reasonably simple code.  This is a
14209    superset of is_simple_builtin.  */
14210 bool
14211 is_inexpensive_builtin (tree decl)
14212 {
14213   if (!decl)
14214     return false;
14215   else if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_MD)
14216     return true;
14217   else if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
14218     switch (DECL_FUNCTION_CODE (decl))
14219       {
14220       case BUILT_IN_ABS:
14221       case BUILT_IN_ALLOCA:
14222       case BUILT_IN_ALLOCA_WITH_ALIGN:
14223       case BUILT_IN_BSWAP32:
14224       case BUILT_IN_BSWAP64:
14225       case BUILT_IN_CLZ:
14226       case BUILT_IN_CLZIMAX:
14227       case BUILT_IN_CLZL:
14228       case BUILT_IN_CLZLL:
14229       case BUILT_IN_CTZ:
14230       case BUILT_IN_CTZIMAX:
14231       case BUILT_IN_CTZL:
14232       case BUILT_IN_CTZLL:
14233       case BUILT_IN_FFS:
14234       case BUILT_IN_FFSIMAX:
14235       case BUILT_IN_FFSL:
14236       case BUILT_IN_FFSLL:
14237       case BUILT_IN_IMAXABS:
14238       case BUILT_IN_FINITE:
14239       case BUILT_IN_FINITEF:
14240       case BUILT_IN_FINITEL:
14241       case BUILT_IN_FINITED32:
14242       case BUILT_IN_FINITED64:
14243       case BUILT_IN_FINITED128:
14244       case BUILT_IN_FPCLASSIFY:
14245       case BUILT_IN_ISFINITE:
14246       case BUILT_IN_ISINF_SIGN:
14247       case BUILT_IN_ISINF:
14248       case BUILT_IN_ISINFF:
14249       case BUILT_IN_ISINFL:
14250       case BUILT_IN_ISINFD32:
14251       case BUILT_IN_ISINFD64:
14252       case BUILT_IN_ISINFD128:
14253       case BUILT_IN_ISNAN:
14254       case BUILT_IN_ISNANF:
14255       case BUILT_IN_ISNANL:
14256       case BUILT_IN_ISNAND32:
14257       case BUILT_IN_ISNAND64:
14258       case BUILT_IN_ISNAND128:
14259       case BUILT_IN_ISNORMAL:
14260       case BUILT_IN_ISGREATER:
14261       case BUILT_IN_ISGREATEREQUAL:
14262       case BUILT_IN_ISLESS:
14263       case BUILT_IN_ISLESSEQUAL:
14264       case BUILT_IN_ISLESSGREATER:
14265       case BUILT_IN_ISUNORDERED:
14266       case BUILT_IN_VA_ARG_PACK:
14267       case BUILT_IN_VA_ARG_PACK_LEN:
14268       case BUILT_IN_VA_COPY:
14269       case BUILT_IN_TRAP:
14270       case BUILT_IN_SAVEREGS:
14271       case BUILT_IN_POPCOUNTL:
14272       case BUILT_IN_POPCOUNTLL:
14273       case BUILT_IN_POPCOUNTIMAX:
14274       case BUILT_IN_POPCOUNT:
14275       case BUILT_IN_PARITYL:
14276       case BUILT_IN_PARITYLL:
14277       case BUILT_IN_PARITYIMAX:
14278       case BUILT_IN_PARITY:
14279       case BUILT_IN_LABS:
14280       case BUILT_IN_LLABS:
14281       case BUILT_IN_PREFETCH:
14282         return true;
14283
14284       default:
14285         return is_simple_builtin (decl);
14286       }
14287
14288   return false;
14289 }