OSDN Git Service

2011-08-10 Richard Guenther <rguenther@suse.de>
[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 tree built_in_decls[(int) END_BUILTINS];
79 /* Declarations used when constructing the builtin implicitly in the compiler.
80    It may be NULL_TREE when this is invalid (for instance runtime is not
81    required to implement the function call in all cases).  */
82 tree implicit_built_in_decls[(int) END_BUILTINS];
83
84 static const char *c_getstr (tree);
85 static rtx c_readstr (const char *, enum machine_mode);
86 static int target_char_cast (tree, char *);
87 static rtx get_memory_rtx (tree, tree);
88 static int apply_args_size (void);
89 static int apply_result_size (void);
90 #if defined (HAVE_untyped_call) || defined (HAVE_untyped_return)
91 static rtx result_vector (int, rtx);
92 #endif
93 static void expand_builtin_update_setjmp_buf (rtx);
94 static void expand_builtin_prefetch (tree);
95 static rtx expand_builtin_apply_args (void);
96 static rtx expand_builtin_apply_args_1 (void);
97 static rtx expand_builtin_apply (rtx, rtx, rtx);
98 static void expand_builtin_return (rtx);
99 static enum type_class type_to_class (tree);
100 static rtx expand_builtin_classify_type (tree);
101 static void expand_errno_check (tree, rtx);
102 static rtx expand_builtin_mathfn (tree, rtx, rtx);
103 static rtx expand_builtin_mathfn_2 (tree, rtx, rtx);
104 static rtx expand_builtin_mathfn_3 (tree, rtx, rtx);
105 static rtx expand_builtin_mathfn_ternary (tree, rtx, rtx);
106 static rtx expand_builtin_interclass_mathfn (tree, rtx);
107 static rtx expand_builtin_sincos (tree);
108 static rtx expand_builtin_cexpi (tree, rtx);
109 static rtx expand_builtin_int_roundingfn (tree, rtx);
110 static rtx expand_builtin_int_roundingfn_2 (tree, rtx);
111 static rtx expand_builtin_next_arg (void);
112 static rtx expand_builtin_va_start (tree);
113 static rtx expand_builtin_va_end (tree);
114 static rtx expand_builtin_va_copy (tree);
115 static rtx expand_builtin_memcmp (tree, rtx, enum machine_mode);
116 static rtx expand_builtin_strcmp (tree, rtx);
117 static rtx expand_builtin_strncmp (tree, rtx, enum machine_mode);
118 static rtx builtin_memcpy_read_str (void *, HOST_WIDE_INT, enum machine_mode);
119 static rtx expand_builtin_memcpy (tree, rtx);
120 static rtx expand_builtin_mempcpy (tree, rtx, enum machine_mode);
121 static rtx expand_builtin_mempcpy_args (tree, tree, tree, rtx,
122                                         enum machine_mode, int);
123 static rtx expand_builtin_strcpy (tree, rtx);
124 static rtx expand_builtin_strcpy_args (tree, tree, rtx);
125 static rtx expand_builtin_stpcpy (tree, rtx, enum machine_mode);
126 static rtx expand_builtin_strncpy (tree, rtx);
127 static rtx builtin_memset_gen_str (void *, HOST_WIDE_INT, enum machine_mode);
128 static rtx expand_builtin_memset (tree, rtx, enum machine_mode);
129 static rtx expand_builtin_memset_args (tree, tree, tree, rtx, enum machine_mode, tree);
130 static rtx expand_builtin_bzero (tree);
131 static rtx expand_builtin_strlen (tree, rtx, enum machine_mode);
132 static rtx expand_builtin_alloca (tree, bool);
133 static rtx expand_builtin_unop (enum machine_mode, tree, rtx, rtx, optab);
134 static rtx expand_builtin_frame_address (tree, tree);
135 static tree stabilize_va_list_loc (location_t, tree, int);
136 static rtx expand_builtin_expect (tree, rtx);
137 static tree fold_builtin_constant_p (tree);
138 static tree fold_builtin_expect (location_t, tree, tree);
139 static tree fold_builtin_classify_type (tree);
140 static tree fold_builtin_strlen (location_t, tree, tree);
141 static tree fold_builtin_inf (location_t, tree, int);
142 static tree fold_builtin_nan (tree, tree, int);
143 static tree rewrite_call_expr (location_t, tree, int, tree, int, ...);
144 static bool validate_arg (const_tree, enum tree_code code);
145 static bool integer_valued_real_p (tree);
146 static tree fold_trunc_transparent_mathfn (location_t, tree, tree);
147 static bool readonly_data_expr (tree);
148 static rtx expand_builtin_fabs (tree, rtx, rtx);
149 static rtx expand_builtin_signbit (tree, rtx);
150 static tree fold_builtin_sqrt (location_t, tree, tree);
151 static tree fold_builtin_cbrt (location_t, tree, tree);
152 static tree fold_builtin_pow (location_t, tree, tree, tree, tree);
153 static tree fold_builtin_powi (location_t, tree, tree, tree, tree);
154 static tree fold_builtin_cos (location_t, tree, tree, tree);
155 static tree fold_builtin_cosh (location_t, tree, tree, tree);
156 static tree fold_builtin_tan (tree, tree);
157 static tree fold_builtin_trunc (location_t, tree, tree);
158 static tree fold_builtin_floor (location_t, tree, tree);
159 static tree fold_builtin_ceil (location_t, tree, tree);
160 static tree fold_builtin_round (location_t, tree, tree);
161 static tree fold_builtin_int_roundingfn (location_t, tree, tree);
162 static tree fold_builtin_bitop (tree, tree);
163 static tree fold_builtin_memory_op (location_t, tree, tree, tree, tree, bool, int);
164 static tree fold_builtin_strchr (location_t, tree, tree, tree);
165 static tree fold_builtin_memchr (location_t, tree, tree, tree, tree);
166 static tree fold_builtin_memcmp (location_t, tree, tree, tree);
167 static tree fold_builtin_strcmp (location_t, tree, tree);
168 static tree fold_builtin_strncmp (location_t, tree, tree, tree);
169 static tree fold_builtin_signbit (location_t, tree, tree);
170 static tree fold_builtin_copysign (location_t, tree, tree, tree, tree);
171 static tree fold_builtin_isascii (location_t, tree);
172 static tree fold_builtin_toascii (location_t, tree);
173 static tree fold_builtin_isdigit (location_t, tree);
174 static tree fold_builtin_fabs (location_t, tree, tree);
175 static tree fold_builtin_abs (location_t, tree, tree);
176 static tree fold_builtin_unordered_cmp (location_t, tree, tree, tree, enum tree_code,
177                                         enum tree_code);
178 static tree fold_builtin_n (location_t, tree, tree *, int, bool);
179 static tree fold_builtin_0 (location_t, tree, bool);
180 static tree fold_builtin_1 (location_t, tree, tree, bool);
181 static tree fold_builtin_2 (location_t, tree, tree, tree, bool);
182 static tree fold_builtin_3 (location_t, tree, tree, tree, tree, bool);
183 static tree fold_builtin_4 (location_t, tree, tree, tree, tree, tree, bool);
184 static tree fold_builtin_varargs (location_t, tree, tree, bool);
185
186 static tree fold_builtin_strpbrk (location_t, tree, tree, tree);
187 static tree fold_builtin_strstr (location_t, tree, tree, tree);
188 static tree fold_builtin_strrchr (location_t, tree, tree, tree);
189 static tree fold_builtin_strcat (location_t, tree, tree);
190 static tree fold_builtin_strncat (location_t, tree, tree, tree);
191 static tree fold_builtin_strspn (location_t, tree, tree);
192 static tree fold_builtin_strcspn (location_t, tree, tree);
193 static tree fold_builtin_sprintf (location_t, tree, tree, tree, int);
194 static tree fold_builtin_snprintf (location_t, tree, tree, tree, tree, int);
195
196 static rtx expand_builtin_object_size (tree);
197 static rtx expand_builtin_memory_chk (tree, rtx, enum machine_mode,
198                                       enum built_in_function);
199 static void maybe_emit_chk_warning (tree, enum built_in_function);
200 static void maybe_emit_sprintf_chk_warning (tree, enum built_in_function);
201 static void maybe_emit_free_warning (tree);
202 static tree fold_builtin_object_size (tree, tree);
203 static tree fold_builtin_strcat_chk (location_t, tree, tree, tree, tree);
204 static tree fold_builtin_strncat_chk (location_t, tree, tree, tree, tree, tree);
205 static tree fold_builtin_sprintf_chk (location_t, tree, enum built_in_function);
206 static tree fold_builtin_printf (location_t, tree, tree, tree, bool, enum built_in_function);
207 static tree fold_builtin_fprintf (location_t, tree, tree, tree, tree, bool,
208                                   enum built_in_function);
209 static bool init_target_chars (void);
210
211 static unsigned HOST_WIDE_INT target_newline;
212 static unsigned HOST_WIDE_INT target_percent;
213 static unsigned HOST_WIDE_INT target_c;
214 static unsigned HOST_WIDE_INT target_s;
215 static char target_percent_c[3];
216 static char target_percent_s[3];
217 static char target_percent_s_newline[4];
218 static tree do_mpfr_arg1 (tree, tree, int (*)(mpfr_ptr, mpfr_srcptr, mp_rnd_t),
219                           const REAL_VALUE_TYPE *, const REAL_VALUE_TYPE *, bool);
220 static tree do_mpfr_arg2 (tree, tree, tree,
221                           int (*)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t));
222 static tree do_mpfr_arg3 (tree, tree, tree, tree,
223                           int (*)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t));
224 static tree do_mpfr_sincos (tree, tree, tree);
225 static tree do_mpfr_bessel_n (tree, tree, tree,
226                               int (*)(mpfr_ptr, long, mpfr_srcptr, mp_rnd_t),
227                               const REAL_VALUE_TYPE *, bool);
228 static tree do_mpfr_remquo (tree, tree, tree);
229 static tree do_mpfr_lgamma_r (tree, tree, tree);
230
231 /* Return true if NAME starts with __builtin_ or __sync_.  */
232
233 bool
234 is_builtin_name (const char *name)
235 {
236   if (strncmp (name, "__builtin_", 10) == 0)
237     return true;
238   if (strncmp (name, "__sync_", 7) == 0)
239     return true;
240   return false;
241 }
242
243
244 /* Return true if DECL is a function symbol representing a built-in.  */
245
246 bool
247 is_builtin_fn (tree decl)
248 {
249   return TREE_CODE (decl) == FUNCTION_DECL && DECL_BUILT_IN (decl);
250 }
251
252
253 /* Return true if NODE should be considered for inline expansion regardless
254    of the optimization level.  This means whenever a function is invoked with
255    its "internal" name, which normally contains the prefix "__builtin".  */
256
257 static bool
258 called_as_built_in (tree node)
259 {
260   /* Note that we must use DECL_NAME, not DECL_ASSEMBLER_NAME_SET_P since
261      we want the name used to call the function, not the name it
262      will have. */
263   const char *name = IDENTIFIER_POINTER (DECL_NAME (node));
264   return is_builtin_name (name);
265 }
266
267 /* Compute values M and N such that M divides (address of EXP - N) and
268    such that N < M.  Store N in *BITPOSP and return M.
269
270    Note that the address (and thus the alignment) computed here is based
271    on the address to which a symbol resolves, whereas DECL_ALIGN is based
272    on the address at which an object is actually located.  These two
273    addresses are not always the same.  For example, on ARM targets,
274    the address &foo of a Thumb function foo() has the lowest bit set,
275    whereas foo() itself starts on an even address.  */
276
277 unsigned int
278 get_object_alignment_1 (tree exp, unsigned HOST_WIDE_INT *bitposp)
279 {
280   HOST_WIDE_INT bitsize, bitpos;
281   tree offset;
282   enum machine_mode mode;
283   int unsignedp, volatilep;
284   unsigned int align, inner;
285
286   /* Get the innermost object and the constant (bitpos) and possibly
287      variable (offset) offset of the access.  */
288   exp = get_inner_reference (exp, &bitsize, &bitpos, &offset,
289                              &mode, &unsignedp, &volatilep, true);
290
291   /* Extract alignment information from the innermost object and
292      possibly adjust bitpos and offset.  */
293   if (TREE_CODE (exp) == CONST_DECL)
294     exp = DECL_INITIAL (exp);
295   if (DECL_P (exp)
296       && TREE_CODE (exp) != LABEL_DECL)
297     {
298       if (TREE_CODE (exp) == FUNCTION_DECL)
299         {
300           /* Function addresses can encode extra information besides their
301              alignment.  However, if TARGET_PTRMEMFUNC_VBIT_LOCATION
302              allows the low bit to be used as a virtual bit, we know
303              that the address itself must be 2-byte aligned.  */
304           if (TARGET_PTRMEMFUNC_VBIT_LOCATION == ptrmemfunc_vbit_in_pfn)
305             align = 2 * BITS_PER_UNIT;
306           else
307             align = BITS_PER_UNIT;
308         }
309       else
310         align = DECL_ALIGN (exp);
311     }
312   else if (CONSTANT_CLASS_P (exp))
313     {
314       align = TYPE_ALIGN (TREE_TYPE (exp));
315 #ifdef CONSTANT_ALIGNMENT
316       align = (unsigned)CONSTANT_ALIGNMENT (exp, align);
317 #endif
318     }
319   else if (TREE_CODE (exp) == VIEW_CONVERT_EXPR)
320     align = TYPE_ALIGN (TREE_TYPE (exp));
321   else if (TREE_CODE (exp) == INDIRECT_REF)
322     align = TYPE_ALIGN (TREE_TYPE (exp));
323   else if (TREE_CODE (exp) == MEM_REF)
324     {
325       tree addr = TREE_OPERAND (exp, 0);
326       struct ptr_info_def *pi;
327       if (TREE_CODE (addr) == BIT_AND_EXPR
328           && TREE_CODE (TREE_OPERAND (addr, 1)) == INTEGER_CST)
329         {
330           align = (TREE_INT_CST_LOW (TREE_OPERAND (addr, 1))
331                     & -TREE_INT_CST_LOW (TREE_OPERAND (addr, 1)));
332           align *= BITS_PER_UNIT;
333           addr = TREE_OPERAND (addr, 0);
334         }
335       else
336         align = BITS_PER_UNIT;
337       if (TREE_CODE (addr) == SSA_NAME
338           && (pi = SSA_NAME_PTR_INFO (addr)))
339         {
340           bitpos += (pi->misalign * BITS_PER_UNIT) & ~(align - 1);
341           align = MAX (pi->align * BITS_PER_UNIT, align);
342         }
343       else if (TREE_CODE (addr) == ADDR_EXPR)
344         align = MAX (align, get_object_alignment (TREE_OPERAND (addr, 0)));
345       bitpos += mem_ref_offset (exp).low * BITS_PER_UNIT;
346     }
347   else if (TREE_CODE (exp) == TARGET_MEM_REF)
348     {
349       struct ptr_info_def *pi;
350       tree addr = TMR_BASE (exp);
351       if (TREE_CODE (addr) == BIT_AND_EXPR
352           && TREE_CODE (TREE_OPERAND (addr, 1)) == INTEGER_CST)
353         {
354           align = (TREE_INT_CST_LOW (TREE_OPERAND (addr, 1))
355                    & -TREE_INT_CST_LOW (TREE_OPERAND (addr, 1)));
356           align *= BITS_PER_UNIT;
357           addr = TREE_OPERAND (addr, 0);
358         }
359       else
360         align = BITS_PER_UNIT;
361       if (TREE_CODE (addr) == SSA_NAME
362           && (pi = SSA_NAME_PTR_INFO (addr)))
363         {
364           bitpos += (pi->misalign * BITS_PER_UNIT) & ~(align - 1);
365           align = MAX (pi->align * BITS_PER_UNIT, align);
366         }
367       else if (TREE_CODE (addr) == ADDR_EXPR)
368         align = MAX (align, get_object_alignment (TREE_OPERAND (addr, 0)));
369       if (TMR_OFFSET (exp))
370         bitpos += TREE_INT_CST_LOW (TMR_OFFSET (exp)) * BITS_PER_UNIT;
371       if (TMR_INDEX (exp) && TMR_STEP (exp))
372         {
373           unsigned HOST_WIDE_INT step = TREE_INT_CST_LOW (TMR_STEP (exp));
374           align = MIN (align, (step & -step) * BITS_PER_UNIT);
375         }
376       else if (TMR_INDEX (exp))
377         align = BITS_PER_UNIT;
378       if (TMR_INDEX2 (exp))
379         align = BITS_PER_UNIT;
380     }
381   else
382     align = BITS_PER_UNIT;
383
384   /* If there is a non-constant offset part extract the maximum
385      alignment that can prevail.  */
386   inner = ~0U;
387   while (offset)
388     {
389       tree next_offset;
390
391       if (TREE_CODE (offset) == PLUS_EXPR)
392         {
393           next_offset = TREE_OPERAND (offset, 0);
394           offset = TREE_OPERAND (offset, 1);
395         }
396       else
397         next_offset = NULL;
398       if (host_integerp (offset, 1))
399         {
400           /* Any overflow in calculating offset_bits won't change
401              the alignment.  */
402           unsigned offset_bits
403             = ((unsigned) tree_low_cst (offset, 1) * BITS_PER_UNIT);
404
405           if (offset_bits)
406             inner = MIN (inner, (offset_bits & -offset_bits));
407         }
408       else if (TREE_CODE (offset) == MULT_EXPR
409                && host_integerp (TREE_OPERAND (offset, 1), 1))
410         {
411           /* Any overflow in calculating offset_factor won't change
412              the alignment.  */
413           unsigned offset_factor
414             = ((unsigned) tree_low_cst (TREE_OPERAND (offset, 1), 1)
415                * BITS_PER_UNIT);
416
417           if (offset_factor)
418             inner = MIN (inner, (offset_factor & -offset_factor));
419         }
420       else
421         {
422           inner = MIN (inner, BITS_PER_UNIT);
423           break;
424         }
425       offset = next_offset;
426     }
427
428   /* Alignment is innermost object alignment adjusted by the constant
429      and non-constant offset parts.  */
430   align = MIN (align, inner);
431   bitpos = bitpos & (align - 1);
432
433   *bitposp = bitpos;
434   return align;
435 }
436
437 /* Return the alignment in bits of EXP, an object.  */
438
439 unsigned int
440 get_object_alignment (tree exp)
441 {
442   unsigned HOST_WIDE_INT bitpos = 0;
443   unsigned int align;
444
445   align = get_object_alignment_1 (exp, &bitpos);
446
447   /* align and bitpos now specify known low bits of the pointer.
448      ptr & (align - 1) == bitpos.  */
449
450   if (bitpos != 0)
451     align = (bitpos & -bitpos);
452
453   return align;
454 }
455
456 /* Returns true iff we can trust that alignment information has been
457    calculated properly.  */
458
459 bool
460 can_trust_pointer_alignment (void)
461 {
462   /* We rely on TER to compute accurate alignment information.  */
463   return (optimize && flag_tree_ter);
464 }
465
466 /* Return the alignment in bits of EXP, a pointer valued expression.
467    The alignment returned is, by default, the alignment of the thing that
468    EXP points to.  If it is not a POINTER_TYPE, 0 is returned.
469
470    Otherwise, look at the expression to see if we can do better, i.e., if the
471    expression is actually pointing at an object whose alignment is tighter.  */
472
473 unsigned int
474 get_pointer_alignment (tree exp)
475 {
476   STRIP_NOPS (exp);
477
478   if (TREE_CODE (exp) == ADDR_EXPR)
479     return get_object_alignment (TREE_OPERAND (exp, 0));
480   else if (TREE_CODE (exp) == SSA_NAME
481            && POINTER_TYPE_P (TREE_TYPE (exp)))
482     {
483       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (exp);
484       unsigned align;
485       if (!pi)
486         return BITS_PER_UNIT;
487       if (pi->misalign != 0)
488         align = (pi->misalign & -pi->misalign);
489       else
490         align = pi->align;
491       return align * BITS_PER_UNIT;
492     }
493
494   return POINTER_TYPE_P (TREE_TYPE (exp)) ? BITS_PER_UNIT : 0;
495 }
496
497 /* Compute the length of a C string.  TREE_STRING_LENGTH is not the right
498    way, because it could contain a zero byte in the middle.
499    TREE_STRING_LENGTH is the size of the character array, not the string.
500
501    ONLY_VALUE should be nonzero if the result is not going to be emitted
502    into the instruction stream and zero if it is going to be expanded.
503    E.g. with i++ ? "foo" : "bar", if ONLY_VALUE is nonzero, constant 3
504    is returned, otherwise NULL, since
505    len = c_strlen (src, 1); if (len) expand_expr (len, ...); would not
506    evaluate the side-effects.
507
508    The value returned is of type `ssizetype'.
509
510    Unfortunately, string_constant can't access the values of const char
511    arrays with initializers, so neither can we do so here.  */
512
513 tree
514 c_strlen (tree src, int only_value)
515 {
516   tree offset_node;
517   HOST_WIDE_INT offset;
518   int max;
519   const char *ptr;
520   location_t loc;
521
522   STRIP_NOPS (src);
523   if (TREE_CODE (src) == COND_EXPR
524       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
525     {
526       tree len1, len2;
527
528       len1 = c_strlen (TREE_OPERAND (src, 1), only_value);
529       len2 = c_strlen (TREE_OPERAND (src, 2), only_value);
530       if (tree_int_cst_equal (len1, len2))
531         return len1;
532     }
533
534   if (TREE_CODE (src) == COMPOUND_EXPR
535       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
536     return c_strlen (TREE_OPERAND (src, 1), only_value);
537
538   loc = EXPR_LOC_OR_HERE (src);
539
540   src = string_constant (src, &offset_node);
541   if (src == 0)
542     return NULL_TREE;
543
544   max = TREE_STRING_LENGTH (src) - 1;
545   ptr = TREE_STRING_POINTER (src);
546
547   if (offset_node && TREE_CODE (offset_node) != INTEGER_CST)
548     {
549       /* If the string has an internal zero byte (e.g., "foo\0bar"), we can't
550          compute the offset to the following null if we don't know where to
551          start searching for it.  */
552       int i;
553
554       for (i = 0; i < max; i++)
555         if (ptr[i] == 0)
556           return NULL_TREE;
557
558       /* We don't know the starting offset, but we do know that the string
559          has no internal zero bytes.  We can assume that the offset falls
560          within the bounds of the string; otherwise, the programmer deserves
561          what he gets.  Subtract the offset from the length of the string,
562          and return that.  This would perhaps not be valid if we were dealing
563          with named arrays in addition to literal string constants.  */
564
565       return size_diffop_loc (loc, size_int (max), offset_node);
566     }
567
568   /* We have a known offset into the string.  Start searching there for
569      a null character if we can represent it as a single HOST_WIDE_INT.  */
570   if (offset_node == 0)
571     offset = 0;
572   else if (! host_integerp (offset_node, 0))
573     offset = -1;
574   else
575     offset = tree_low_cst (offset_node, 0);
576
577   /* If the offset is known to be out of bounds, warn, and call strlen at
578      runtime.  */
579   if (offset < 0 || offset > max)
580     {
581      /* Suppress multiple warnings for propagated constant strings.  */
582       if (! TREE_NO_WARNING (src))
583         {
584           warning_at (loc, 0, "offset outside bounds of constant string");
585           TREE_NO_WARNING (src) = 1;
586         }
587       return NULL_TREE;
588     }
589
590   /* Use strlen to search for the first zero byte.  Since any strings
591      constructed with build_string will have nulls appended, we win even
592      if we get handed something like (char[4])"abcd".
593
594      Since OFFSET is our starting index into the string, no further
595      calculation is needed.  */
596   return ssize_int (strlen (ptr + offset));
597 }
598
599 /* Return a char pointer for a C string if it is a string constant
600    or sum of string constant and integer constant.  */
601
602 static const char *
603 c_getstr (tree src)
604 {
605   tree offset_node;
606
607   src = string_constant (src, &offset_node);
608   if (src == 0)
609     return 0;
610
611   if (offset_node == 0)
612     return TREE_STRING_POINTER (src);
613   else if (!host_integerp (offset_node, 1)
614            || compare_tree_int (offset_node, TREE_STRING_LENGTH (src) - 1) > 0)
615     return 0;
616
617   return TREE_STRING_POINTER (src) + tree_low_cst (offset_node, 1);
618 }
619
620 /* Return a CONST_INT or CONST_DOUBLE corresponding to target reading
621    GET_MODE_BITSIZE (MODE) bits from string constant STR.  */
622
623 static rtx
624 c_readstr (const char *str, enum machine_mode mode)
625 {
626   HOST_WIDE_INT c[2];
627   HOST_WIDE_INT ch;
628   unsigned int i, j;
629
630   gcc_assert (GET_MODE_CLASS (mode) == MODE_INT);
631
632   c[0] = 0;
633   c[1] = 0;
634   ch = 1;
635   for (i = 0; i < GET_MODE_SIZE (mode); i++)
636     {
637       j = i;
638       if (WORDS_BIG_ENDIAN)
639         j = GET_MODE_SIZE (mode) - i - 1;
640       if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN
641           && GET_MODE_SIZE (mode) >= UNITS_PER_WORD)
642         j = j + UNITS_PER_WORD - 2 * (j % UNITS_PER_WORD) - 1;
643       j *= BITS_PER_UNIT;
644       gcc_assert (j < 2 * HOST_BITS_PER_WIDE_INT);
645
646       if (ch)
647         ch = (unsigned char) str[i];
648       c[j / HOST_BITS_PER_WIDE_INT] |= ch << (j % HOST_BITS_PER_WIDE_INT);
649     }
650   return immed_double_const (c[0], c[1], mode);
651 }
652
653 /* Cast a target constant CST to target CHAR and if that value fits into
654    host char type, return zero and put that value into variable pointed to by
655    P.  */
656
657 static int
658 target_char_cast (tree cst, char *p)
659 {
660   unsigned HOST_WIDE_INT val, hostval;
661
662   if (TREE_CODE (cst) != INTEGER_CST
663       || CHAR_TYPE_SIZE > HOST_BITS_PER_WIDE_INT)
664     return 1;
665
666   val = TREE_INT_CST_LOW (cst);
667   if (CHAR_TYPE_SIZE < HOST_BITS_PER_WIDE_INT)
668     val &= (((unsigned HOST_WIDE_INT) 1) << CHAR_TYPE_SIZE) - 1;
669
670   hostval = val;
671   if (HOST_BITS_PER_CHAR < HOST_BITS_PER_WIDE_INT)
672     hostval &= (((unsigned HOST_WIDE_INT) 1) << HOST_BITS_PER_CHAR) - 1;
673
674   if (val != hostval)
675     return 1;
676
677   *p = hostval;
678   return 0;
679 }
680
681 /* Similar to save_expr, but assumes that arbitrary code is not executed
682    in between the multiple evaluations.  In particular, we assume that a
683    non-addressable local variable will not be modified.  */
684
685 static tree
686 builtin_save_expr (tree exp)
687 {
688   if (TREE_CODE (exp) == SSA_NAME
689       || (TREE_ADDRESSABLE (exp) == 0
690           && (TREE_CODE (exp) == PARM_DECL
691               || (TREE_CODE (exp) == VAR_DECL && !TREE_STATIC (exp)))))
692     return exp;
693
694   return save_expr (exp);
695 }
696
697 /* Given TEM, a pointer to a stack frame, follow the dynamic chain COUNT
698    times to get the address of either a higher stack frame, or a return
699    address located within it (depending on FNDECL_CODE).  */
700
701 static rtx
702 expand_builtin_return_addr (enum built_in_function fndecl_code, int count)
703 {
704   int i;
705
706 #ifdef INITIAL_FRAME_ADDRESS_RTX
707   rtx tem = INITIAL_FRAME_ADDRESS_RTX;
708 #else
709   rtx tem;
710
711   /* For a zero count with __builtin_return_address, we don't care what
712      frame address we return, because target-specific definitions will
713      override us.  Therefore frame pointer elimination is OK, and using
714      the soft frame pointer is OK.
715
716      For a nonzero count, or a zero count with __builtin_frame_address,
717      we require a stable offset from the current frame pointer to the
718      previous one, so we must use the hard frame pointer, and
719      we must disable frame pointer elimination.  */
720   if (count == 0 && fndecl_code == BUILT_IN_RETURN_ADDRESS)
721     tem = frame_pointer_rtx;
722   else
723     {
724       tem = hard_frame_pointer_rtx;
725
726       /* Tell reload not to eliminate the frame pointer.  */
727       crtl->accesses_prior_frames = 1;
728     }
729 #endif
730
731   /* Some machines need special handling before we can access
732      arbitrary frames.  For example, on the SPARC, we must first flush
733      all register windows to the stack.  */
734 #ifdef SETUP_FRAME_ADDRESSES
735   if (count > 0)
736     SETUP_FRAME_ADDRESSES ();
737 #endif
738
739   /* On the SPARC, the return address is not in the frame, it is in a
740      register.  There is no way to access it off of the current frame
741      pointer, but it can be accessed off the previous frame pointer by
742      reading the value from the register window save area.  */
743 #ifdef RETURN_ADDR_IN_PREVIOUS_FRAME
744   if (fndecl_code == BUILT_IN_RETURN_ADDRESS)
745     count--;
746 #endif
747
748   /* Scan back COUNT frames to the specified frame.  */
749   for (i = 0; i < count; i++)
750     {
751       /* Assume the dynamic chain pointer is in the word that the
752          frame address points to, unless otherwise specified.  */
753 #ifdef DYNAMIC_CHAIN_ADDRESS
754       tem = DYNAMIC_CHAIN_ADDRESS (tem);
755 #endif
756       tem = memory_address (Pmode, tem);
757       tem = gen_frame_mem (Pmode, tem);
758       tem = copy_to_reg (tem);
759     }
760
761   /* For __builtin_frame_address, return what we've got.  But, on
762      the SPARC for example, we may have to add a bias.  */
763   if (fndecl_code == BUILT_IN_FRAME_ADDRESS)
764 #ifdef FRAME_ADDR_RTX
765     return FRAME_ADDR_RTX (tem);
766 #else
767     return tem;
768 #endif
769
770   /* For __builtin_return_address, get the return address from that frame.  */
771 #ifdef RETURN_ADDR_RTX
772   tem = RETURN_ADDR_RTX (count, tem);
773 #else
774   tem = memory_address (Pmode,
775                         plus_constant (tem, GET_MODE_SIZE (Pmode)));
776   tem = gen_frame_mem (Pmode, tem);
777 #endif
778   return tem;
779 }
780
781 /* Alias set used for setjmp buffer.  */
782 static alias_set_type setjmp_alias_set = -1;
783
784 /* Construct the leading half of a __builtin_setjmp call.  Control will
785    return to RECEIVER_LABEL.  This is also called directly by the SJLJ
786    exception handling code.  */
787
788 void
789 expand_builtin_setjmp_setup (rtx buf_addr, rtx receiver_label)
790 {
791   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
792   rtx stack_save;
793   rtx mem;
794
795   if (setjmp_alias_set == -1)
796     setjmp_alias_set = new_alias_set ();
797
798   buf_addr = convert_memory_address (Pmode, buf_addr);
799
800   buf_addr = force_reg (Pmode, force_operand (buf_addr, NULL_RTX));
801
802   /* We store the frame pointer and the address of receiver_label in
803      the buffer and use the rest of it for the stack save area, which
804      is machine-dependent.  */
805
806   mem = gen_rtx_MEM (Pmode, buf_addr);
807   set_mem_alias_set (mem, setjmp_alias_set);
808   emit_move_insn (mem, targetm.builtin_setjmp_frame_value ());
809
810   mem = gen_rtx_MEM (Pmode, plus_constant (buf_addr, GET_MODE_SIZE (Pmode))),
811   set_mem_alias_set (mem, setjmp_alias_set);
812
813   emit_move_insn (validize_mem (mem),
814                   force_reg (Pmode, gen_rtx_LABEL_REF (Pmode, receiver_label)));
815
816   stack_save = gen_rtx_MEM (sa_mode,
817                             plus_constant (buf_addr,
818                                            2 * GET_MODE_SIZE (Pmode)));
819   set_mem_alias_set (stack_save, setjmp_alias_set);
820   emit_stack_save (SAVE_NONLOCAL, &stack_save);
821
822   /* If there is further processing to do, do it.  */
823 #ifdef HAVE_builtin_setjmp_setup
824   if (HAVE_builtin_setjmp_setup)
825     emit_insn (gen_builtin_setjmp_setup (buf_addr));
826 #endif
827
828   /* We have a nonlocal label.   */
829   cfun->has_nonlocal_label = 1;
830 }
831
832 /* Construct the trailing part of a __builtin_setjmp call.  This is
833    also called directly by the SJLJ exception handling code.  */
834
835 void
836 expand_builtin_setjmp_receiver (rtx receiver_label ATTRIBUTE_UNUSED)
837 {
838   rtx chain;
839
840   /* Clobber the FP when we get here, so we have to make sure it's
841      marked as used by this function.  */
842   emit_use (hard_frame_pointer_rtx);
843
844   /* Mark the static chain as clobbered here so life information
845      doesn't get messed up for it.  */
846   chain = targetm.calls.static_chain (current_function_decl, true);
847   if (chain && REG_P (chain))
848     emit_clobber (chain);
849
850   /* Now put in the code to restore the frame pointer, and argument
851      pointer, if needed.  */
852 #ifdef HAVE_nonlocal_goto
853   if (! HAVE_nonlocal_goto)
854 #endif
855     {
856       emit_move_insn (virtual_stack_vars_rtx, hard_frame_pointer_rtx);
857       /* This might change the hard frame pointer in ways that aren't
858          apparent to early optimization passes, so force a clobber.  */
859       emit_clobber (hard_frame_pointer_rtx);
860     }
861
862 #if !HARD_FRAME_POINTER_IS_ARG_POINTER
863   if (fixed_regs[ARG_POINTER_REGNUM])
864     {
865 #ifdef ELIMINABLE_REGS
866       size_t i;
867       static const struct elims {const int from, to;} elim_regs[] = ELIMINABLE_REGS;
868
869       for (i = 0; i < ARRAY_SIZE (elim_regs); i++)
870         if (elim_regs[i].from == ARG_POINTER_REGNUM
871             && elim_regs[i].to == HARD_FRAME_POINTER_REGNUM)
872           break;
873
874       if (i == ARRAY_SIZE (elim_regs))
875 #endif
876         {
877           /* Now restore our arg pointer from the address at which it
878              was saved in our stack frame.  */
879           emit_move_insn (crtl->args.internal_arg_pointer,
880                           copy_to_reg (get_arg_pointer_save_area ()));
881         }
882     }
883 #endif
884
885 #ifdef HAVE_builtin_setjmp_receiver
886   if (HAVE_builtin_setjmp_receiver)
887     emit_insn (gen_builtin_setjmp_receiver (receiver_label));
888   else
889 #endif
890 #ifdef HAVE_nonlocal_goto_receiver
891     if (HAVE_nonlocal_goto_receiver)
892       emit_insn (gen_nonlocal_goto_receiver ());
893     else
894 #endif
895       { /* Nothing */ }
896
897   /* We must not allow the code we just generated to be reordered by
898      scheduling.  Specifically, the update of the frame pointer must
899      happen immediately, not later.  */
900   emit_insn (gen_blockage ());
901 }
902
903 /* __builtin_longjmp is passed a pointer to an array of five words (not
904    all will be used on all machines).  It operates similarly to the C
905    library function of the same name, but is more efficient.  Much of
906    the code below is copied from the handling of non-local gotos.  */
907
908 static void
909 expand_builtin_longjmp (rtx buf_addr, rtx value)
910 {
911   rtx fp, lab, stack, insn, last;
912   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
913
914   /* DRAP is needed for stack realign if longjmp is expanded to current
915      function  */
916   if (SUPPORTS_STACK_ALIGNMENT)
917     crtl->need_drap = true;
918
919   if (setjmp_alias_set == -1)
920     setjmp_alias_set = new_alias_set ();
921
922   buf_addr = convert_memory_address (Pmode, buf_addr);
923
924   buf_addr = force_reg (Pmode, buf_addr);
925
926   /* We require that the user must pass a second argument of 1, because
927      that is what builtin_setjmp will return.  */
928   gcc_assert (value == const1_rtx);
929
930   last = get_last_insn ();
931 #ifdef HAVE_builtin_longjmp
932   if (HAVE_builtin_longjmp)
933     emit_insn (gen_builtin_longjmp (buf_addr));
934   else
935 #endif
936     {
937       fp = gen_rtx_MEM (Pmode, buf_addr);
938       lab = gen_rtx_MEM (Pmode, plus_constant (buf_addr,
939                                                GET_MODE_SIZE (Pmode)));
940
941       stack = gen_rtx_MEM (sa_mode, plus_constant (buf_addr,
942                                                    2 * GET_MODE_SIZE (Pmode)));
943       set_mem_alias_set (fp, setjmp_alias_set);
944       set_mem_alias_set (lab, setjmp_alias_set);
945       set_mem_alias_set (stack, setjmp_alias_set);
946
947       /* Pick up FP, label, and SP from the block and jump.  This code is
948          from expand_goto in stmt.c; see there for detailed comments.  */
949 #ifdef HAVE_nonlocal_goto
950       if (HAVE_nonlocal_goto)
951         /* We have to pass a value to the nonlocal_goto pattern that will
952            get copied into the static_chain pointer, but it does not matter
953            what that value is, because builtin_setjmp does not use it.  */
954         emit_insn (gen_nonlocal_goto (value, lab, stack, fp));
955       else
956 #endif
957         {
958           lab = copy_to_reg (lab);
959
960           emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
961           emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
962
963           emit_move_insn (hard_frame_pointer_rtx, fp);
964           emit_stack_restore (SAVE_NONLOCAL, stack);
965
966           emit_use (hard_frame_pointer_rtx);
967           emit_use (stack_pointer_rtx);
968           emit_indirect_jump (lab);
969         }
970     }
971
972   /* Search backwards and mark the jump insn as a non-local goto.
973      Note that this precludes the use of __builtin_longjmp to a
974      __builtin_setjmp target in the same function.  However, we've
975      already cautioned the user that these functions are for
976      internal exception handling use only.  */
977   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
978     {
979       gcc_assert (insn != last);
980
981       if (JUMP_P (insn))
982         {
983           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
984           break;
985         }
986       else if (CALL_P (insn))
987         break;
988     }
989 }
990
991 /* Expand a call to __builtin_nonlocal_goto.  We're passed the target label
992    and the address of the save area.  */
993
994 static rtx
995 expand_builtin_nonlocal_goto (tree exp)
996 {
997   tree t_label, t_save_area;
998   rtx r_label, r_save_area, r_fp, r_sp, insn;
999
1000   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
1001     return NULL_RTX;
1002
1003   t_label = CALL_EXPR_ARG (exp, 0);
1004   t_save_area = CALL_EXPR_ARG (exp, 1);
1005
1006   r_label = expand_normal (t_label);
1007   r_label = convert_memory_address (Pmode, r_label);
1008   r_save_area = expand_normal (t_save_area);
1009   r_save_area = convert_memory_address (Pmode, r_save_area);
1010   /* Copy the address of the save location to a register just in case it was
1011      based on the frame pointer.   */
1012   r_save_area = copy_to_reg (r_save_area);
1013   r_fp = gen_rtx_MEM (Pmode, r_save_area);
1014   r_sp = gen_rtx_MEM (STACK_SAVEAREA_MODE (SAVE_NONLOCAL),
1015                       plus_constant (r_save_area, GET_MODE_SIZE (Pmode)));
1016
1017   crtl->has_nonlocal_goto = 1;
1018
1019 #ifdef HAVE_nonlocal_goto
1020   /* ??? We no longer need to pass the static chain value, afaik.  */
1021   if (HAVE_nonlocal_goto)
1022     emit_insn (gen_nonlocal_goto (const0_rtx, r_label, r_sp, r_fp));
1023   else
1024 #endif
1025     {
1026       r_label = copy_to_reg (r_label);
1027
1028       emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
1029       emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
1030
1031       /* Restore frame pointer for containing function.  */
1032       emit_move_insn (hard_frame_pointer_rtx, r_fp);
1033       emit_stack_restore (SAVE_NONLOCAL, r_sp);
1034
1035       /* USE of hard_frame_pointer_rtx added for consistency;
1036          not clear if really needed.  */
1037       emit_use (hard_frame_pointer_rtx);
1038       emit_use (stack_pointer_rtx);
1039
1040       /* If the architecture is using a GP register, we must
1041          conservatively assume that the target function makes use of it.
1042          The prologue of functions with nonlocal gotos must therefore
1043          initialize the GP register to the appropriate value, and we
1044          must then make sure that this value is live at the point
1045          of the jump.  (Note that this doesn't necessarily apply
1046          to targets with a nonlocal_goto pattern; they are free
1047          to implement it in their own way.  Note also that this is
1048          a no-op if the GP register is a global invariant.)  */
1049       if ((unsigned) PIC_OFFSET_TABLE_REGNUM != INVALID_REGNUM
1050           && fixed_regs[PIC_OFFSET_TABLE_REGNUM])
1051         emit_use (pic_offset_table_rtx);
1052
1053       emit_indirect_jump (r_label);
1054     }
1055
1056   /* Search backwards to the jump insn and mark it as a
1057      non-local goto.  */
1058   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
1059     {
1060       if (JUMP_P (insn))
1061         {
1062           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
1063           break;
1064         }
1065       else if (CALL_P (insn))
1066         break;
1067     }
1068
1069   return const0_rtx;
1070 }
1071
1072 /* __builtin_update_setjmp_buf is passed a pointer to an array of five words
1073    (not all will be used on all machines) that was passed to __builtin_setjmp.
1074    It updates the stack pointer in that block to correspond to the current
1075    stack pointer.  */
1076
1077 static void
1078 expand_builtin_update_setjmp_buf (rtx buf_addr)
1079 {
1080   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
1081   rtx stack_save
1082     = gen_rtx_MEM (sa_mode,
1083                    memory_address
1084                    (sa_mode,
1085                     plus_constant (buf_addr, 2 * GET_MODE_SIZE (Pmode))));
1086
1087   emit_stack_save (SAVE_NONLOCAL, &stack_save);
1088 }
1089
1090 /* Expand a call to __builtin_prefetch.  For a target that does not support
1091    data prefetch, evaluate the memory address argument in case it has side
1092    effects.  */
1093
1094 static void
1095 expand_builtin_prefetch (tree exp)
1096 {
1097   tree arg0, arg1, arg2;
1098   int nargs;
1099   rtx op0, op1, op2;
1100
1101   if (!validate_arglist (exp, POINTER_TYPE, 0))
1102     return;
1103
1104   arg0 = CALL_EXPR_ARG (exp, 0);
1105
1106   /* Arguments 1 and 2 are optional; argument 1 (read/write) defaults to
1107      zero (read) and argument 2 (locality) defaults to 3 (high degree of
1108      locality).  */
1109   nargs = call_expr_nargs (exp);
1110   if (nargs > 1)
1111     arg1 = CALL_EXPR_ARG (exp, 1);
1112   else
1113     arg1 = integer_zero_node;
1114   if (nargs > 2)
1115     arg2 = CALL_EXPR_ARG (exp, 2);
1116   else
1117     arg2 = integer_three_node;
1118
1119   /* Argument 0 is an address.  */
1120   op0 = expand_expr (arg0, NULL_RTX, Pmode, EXPAND_NORMAL);
1121
1122   /* Argument 1 (read/write flag) must be a compile-time constant int.  */
1123   if (TREE_CODE (arg1) != INTEGER_CST)
1124     {
1125       error ("second argument to %<__builtin_prefetch%> must be a constant");
1126       arg1 = integer_zero_node;
1127     }
1128   op1 = expand_normal (arg1);
1129   /* Argument 1 must be either zero or one.  */
1130   if (INTVAL (op1) != 0 && INTVAL (op1) != 1)
1131     {
1132       warning (0, "invalid second argument to %<__builtin_prefetch%>;"
1133                " using zero");
1134       op1 = const0_rtx;
1135     }
1136
1137   /* Argument 2 (locality) must be a compile-time constant int.  */
1138   if (TREE_CODE (arg2) != INTEGER_CST)
1139     {
1140       error ("third argument to %<__builtin_prefetch%> must be a constant");
1141       arg2 = integer_zero_node;
1142     }
1143   op2 = expand_normal (arg2);
1144   /* Argument 2 must be 0, 1, 2, or 3.  */
1145   if (INTVAL (op2) < 0 || INTVAL (op2) > 3)
1146     {
1147       warning (0, "invalid third argument to %<__builtin_prefetch%>; using zero");
1148       op2 = const0_rtx;
1149     }
1150
1151 #ifdef HAVE_prefetch
1152   if (HAVE_prefetch)
1153     {
1154       struct expand_operand ops[3];
1155
1156       create_address_operand (&ops[0], op0);
1157       create_integer_operand (&ops[1], INTVAL (op1));
1158       create_integer_operand (&ops[2], INTVAL (op2));
1159       if (maybe_expand_insn (CODE_FOR_prefetch, 3, ops))
1160         return;
1161     }
1162 #endif
1163
1164   /* Don't do anything with direct references to volatile memory, but
1165      generate code to handle other side effects.  */
1166   if (!MEM_P (op0) && side_effects_p (op0))
1167     emit_insn (op0);
1168 }
1169
1170 /* Get a MEM rtx for expression EXP which is the address of an operand
1171    to be used in a string instruction (cmpstrsi, movmemsi, ..).  LEN is
1172    the maximum length of the block of memory that might be accessed or
1173    NULL if unknown.  */
1174
1175 static rtx
1176 get_memory_rtx (tree exp, tree len)
1177 {
1178   tree orig_exp = exp;
1179   rtx addr, mem;
1180   HOST_WIDE_INT off;
1181
1182   /* When EXP is not resolved SAVE_EXPR, MEM_ATTRS can be still derived
1183      from its expression, for expr->a.b only <variable>.a.b is recorded.  */
1184   if (TREE_CODE (exp) == SAVE_EXPR && !SAVE_EXPR_RESOLVED_P (exp))
1185     exp = TREE_OPERAND (exp, 0);
1186
1187   addr = expand_expr (orig_exp, NULL_RTX, ptr_mode, EXPAND_NORMAL);
1188   mem = gen_rtx_MEM (BLKmode, memory_address (BLKmode, addr));
1189
1190   /* Get an expression we can use to find the attributes to assign to MEM.
1191      If it is an ADDR_EXPR, use the operand.  Otherwise, dereference it if
1192      we can.  First remove any nops.  */
1193   while (CONVERT_EXPR_P (exp)
1194          && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (exp, 0))))
1195     exp = TREE_OPERAND (exp, 0);
1196
1197   off = 0;
1198   if (TREE_CODE (exp) == POINTER_PLUS_EXPR
1199       && TREE_CODE (TREE_OPERAND (exp, 0)) == ADDR_EXPR
1200       && host_integerp (TREE_OPERAND (exp, 1), 0)
1201       && (off = tree_low_cst (TREE_OPERAND (exp, 1), 0)) > 0)
1202     exp = TREE_OPERAND (TREE_OPERAND (exp, 0), 0);
1203   else if (TREE_CODE (exp) == ADDR_EXPR)
1204     exp = TREE_OPERAND (exp, 0);
1205   else if (POINTER_TYPE_P (TREE_TYPE (exp)))
1206     exp = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (exp)), exp);
1207   else
1208     exp = NULL;
1209
1210   /* Honor attributes derived from exp, except for the alias set
1211      (as builtin stringops may alias with anything) and the size
1212      (as stringops may access multiple array elements).  */
1213   if (exp)
1214     {
1215       set_mem_attributes (mem, exp, 0);
1216
1217       if (off)
1218         mem = adjust_automodify_address_nv (mem, BLKmode, NULL, off);
1219
1220       /* Allow the string and memory builtins to overflow from one
1221          field into another, see http://gcc.gnu.org/PR23561.
1222          Thus avoid COMPONENT_REFs in MEM_EXPR unless we know the whole
1223          memory accessed by the string or memory builtin will fit
1224          within the field.  */
1225       if (MEM_EXPR (mem) && TREE_CODE (MEM_EXPR (mem)) == COMPONENT_REF)
1226         {
1227           tree mem_expr = MEM_EXPR (mem);
1228           HOST_WIDE_INT offset = -1, length = -1;
1229           tree inner = exp;
1230
1231           while (TREE_CODE (inner) == ARRAY_REF
1232                  || CONVERT_EXPR_P (inner)
1233                  || TREE_CODE (inner) == VIEW_CONVERT_EXPR
1234                  || TREE_CODE (inner) == SAVE_EXPR)
1235             inner = TREE_OPERAND (inner, 0);
1236
1237           gcc_assert (TREE_CODE (inner) == COMPONENT_REF);
1238
1239           if (MEM_OFFSET_KNOWN_P (mem))
1240             offset = MEM_OFFSET (mem);
1241
1242           if (offset >= 0 && len && host_integerp (len, 0))
1243             length = tree_low_cst (len, 0);
1244
1245           while (TREE_CODE (inner) == COMPONENT_REF)
1246             {
1247               tree field = TREE_OPERAND (inner, 1);
1248               gcc_assert (TREE_CODE (mem_expr) == COMPONENT_REF);
1249               gcc_assert (field == TREE_OPERAND (mem_expr, 1));
1250
1251               /* Bitfields are generally not byte-addressable.  */
1252               gcc_assert (!DECL_BIT_FIELD (field)
1253                           || ((tree_low_cst (DECL_FIELD_BIT_OFFSET (field), 1)
1254                                % BITS_PER_UNIT) == 0
1255                               && host_integerp (DECL_SIZE (field), 0)
1256                               && (TREE_INT_CST_LOW (DECL_SIZE (field))
1257                                   % BITS_PER_UNIT) == 0));
1258
1259               /* If we can prove that the memory starting at XEXP (mem, 0) and
1260                  ending at XEXP (mem, 0) + LENGTH will fit into this field, we
1261                  can keep the COMPONENT_REF in MEM_EXPR.  But be careful with
1262                  fields without DECL_SIZE_UNIT like flexible array members.  */
1263               if (length >= 0
1264                   && DECL_SIZE_UNIT (field)
1265                   && host_integerp (DECL_SIZE_UNIT (field), 0))
1266                 {
1267                   HOST_WIDE_INT size
1268                     = TREE_INT_CST_LOW (DECL_SIZE_UNIT (field));
1269                   if (offset <= size
1270                       && length <= size
1271                       && offset + length <= size)
1272                     break;
1273                 }
1274
1275               if (offset >= 0
1276                   && host_integerp (DECL_FIELD_OFFSET (field), 0))
1277                 offset += TREE_INT_CST_LOW (DECL_FIELD_OFFSET (field))
1278                           + tree_low_cst (DECL_FIELD_BIT_OFFSET (field), 1)
1279                             / BITS_PER_UNIT;
1280               else
1281                 {
1282                   offset = -1;
1283                   length = -1;
1284                 }
1285
1286               mem_expr = TREE_OPERAND (mem_expr, 0);
1287               inner = TREE_OPERAND (inner, 0);
1288             }
1289
1290           if (mem_expr == NULL)
1291             offset = -1;
1292           if (mem_expr != MEM_EXPR (mem))
1293             {
1294               set_mem_expr (mem, mem_expr);
1295               if (offset >= 0)
1296                 set_mem_offset (mem, offset);
1297               else
1298                 clear_mem_offset (mem);
1299             }
1300         }
1301       set_mem_alias_set (mem, 0);
1302       clear_mem_size (mem);
1303     }
1304
1305   return mem;
1306 }
1307 \f
1308 /* Built-in functions to perform an untyped call and return.  */
1309
1310 #define apply_args_mode \
1311   (this_target_builtins->x_apply_args_mode)
1312 #define apply_result_mode \
1313   (this_target_builtins->x_apply_result_mode)
1314
1315 /* Return the size required for the block returned by __builtin_apply_args,
1316    and initialize apply_args_mode.  */
1317
1318 static int
1319 apply_args_size (void)
1320 {
1321   static int size = -1;
1322   int align;
1323   unsigned int regno;
1324   enum machine_mode mode;
1325
1326   /* The values computed by this function never change.  */
1327   if (size < 0)
1328     {
1329       /* The first value is the incoming arg-pointer.  */
1330       size = GET_MODE_SIZE (Pmode);
1331
1332       /* The second value is the structure value address unless this is
1333          passed as an "invisible" first argument.  */
1334       if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1335         size += GET_MODE_SIZE (Pmode);
1336
1337       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1338         if (FUNCTION_ARG_REGNO_P (regno))
1339           {
1340             mode = targetm.calls.get_raw_arg_mode (regno);
1341
1342             gcc_assert (mode != VOIDmode);
1343
1344             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1345             if (size % align != 0)
1346               size = CEIL (size, align) * align;
1347             size += GET_MODE_SIZE (mode);
1348             apply_args_mode[regno] = mode;
1349           }
1350         else
1351           {
1352             apply_args_mode[regno] = VOIDmode;
1353           }
1354     }
1355   return size;
1356 }
1357
1358 /* Return the size required for the block returned by __builtin_apply,
1359    and initialize apply_result_mode.  */
1360
1361 static int
1362 apply_result_size (void)
1363 {
1364   static int size = -1;
1365   int align, regno;
1366   enum machine_mode mode;
1367
1368   /* The values computed by this function never change.  */
1369   if (size < 0)
1370     {
1371       size = 0;
1372
1373       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1374         if (targetm.calls.function_value_regno_p (regno))
1375           {
1376             mode = targetm.calls.get_raw_result_mode (regno);
1377
1378             gcc_assert (mode != VOIDmode);
1379
1380             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1381             if (size % align != 0)
1382               size = CEIL (size, align) * align;
1383             size += GET_MODE_SIZE (mode);
1384             apply_result_mode[regno] = mode;
1385           }
1386         else
1387           apply_result_mode[regno] = VOIDmode;
1388
1389       /* Allow targets that use untyped_call and untyped_return to override
1390          the size so that machine-specific information can be stored here.  */
1391 #ifdef APPLY_RESULT_SIZE
1392       size = APPLY_RESULT_SIZE;
1393 #endif
1394     }
1395   return size;
1396 }
1397
1398 #if defined (HAVE_untyped_call) || defined (HAVE_untyped_return)
1399 /* Create a vector describing the result block RESULT.  If SAVEP is true,
1400    the result block is used to save the values; otherwise it is used to
1401    restore the values.  */
1402
1403 static rtx
1404 result_vector (int savep, rtx result)
1405 {
1406   int regno, size, align, nelts;
1407   enum machine_mode mode;
1408   rtx reg, mem;
1409   rtx *savevec = XALLOCAVEC (rtx, FIRST_PSEUDO_REGISTER);
1410
1411   size = nelts = 0;
1412   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1413     if ((mode = apply_result_mode[regno]) != VOIDmode)
1414       {
1415         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1416         if (size % align != 0)
1417           size = CEIL (size, align) * align;
1418         reg = gen_rtx_REG (mode, savep ? regno : INCOMING_REGNO (regno));
1419         mem = adjust_address (result, mode, size);
1420         savevec[nelts++] = (savep
1421                             ? gen_rtx_SET (VOIDmode, mem, reg)
1422                             : gen_rtx_SET (VOIDmode, reg, mem));
1423         size += GET_MODE_SIZE (mode);
1424       }
1425   return gen_rtx_PARALLEL (VOIDmode, gen_rtvec_v (nelts, savevec));
1426 }
1427 #endif /* HAVE_untyped_call or HAVE_untyped_return */
1428
1429 /* Save the state required to perform an untyped call with the same
1430    arguments as were passed to the current function.  */
1431
1432 static rtx
1433 expand_builtin_apply_args_1 (void)
1434 {
1435   rtx registers, tem;
1436   int size, align, regno;
1437   enum machine_mode mode;
1438   rtx struct_incoming_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 1);
1439
1440   /* Create a block where the arg-pointer, structure value address,
1441      and argument registers can be saved.  */
1442   registers = assign_stack_local (BLKmode, apply_args_size (), -1);
1443
1444   /* Walk past the arg-pointer and structure value address.  */
1445   size = GET_MODE_SIZE (Pmode);
1446   if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1447     size += GET_MODE_SIZE (Pmode);
1448
1449   /* Save each register used in calling a function to the block.  */
1450   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1451     if ((mode = apply_args_mode[regno]) != VOIDmode)
1452       {
1453         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1454         if (size % align != 0)
1455           size = CEIL (size, align) * align;
1456
1457         tem = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1458
1459         emit_move_insn (adjust_address (registers, mode, size), tem);
1460         size += GET_MODE_SIZE (mode);
1461       }
1462
1463   /* Save the arg pointer to the block.  */
1464   tem = copy_to_reg (crtl->args.internal_arg_pointer);
1465 #ifdef STACK_GROWS_DOWNWARD
1466   /* We need the pointer as the caller actually passed them to us, not
1467      as we might have pretended they were passed.  Make sure it's a valid
1468      operand, as emit_move_insn isn't expected to handle a PLUS.  */
1469   tem
1470     = force_operand (plus_constant (tem, crtl->args.pretend_args_size),
1471                      NULL_RTX);
1472 #endif
1473   emit_move_insn (adjust_address (registers, Pmode, 0), tem);
1474
1475   size = GET_MODE_SIZE (Pmode);
1476
1477   /* Save the structure value address unless this is passed as an
1478      "invisible" first argument.  */
1479   if (struct_incoming_value)
1480     {
1481       emit_move_insn (adjust_address (registers, Pmode, size),
1482                       copy_to_reg (struct_incoming_value));
1483       size += GET_MODE_SIZE (Pmode);
1484     }
1485
1486   /* Return the address of the block.  */
1487   return copy_addr_to_reg (XEXP (registers, 0));
1488 }
1489
1490 /* __builtin_apply_args returns block of memory allocated on
1491    the stack into which is stored the arg pointer, structure
1492    value address, static chain, and all the registers that might
1493    possibly be used in performing a function call.  The code is
1494    moved to the start of the function so the incoming values are
1495    saved.  */
1496
1497 static rtx
1498 expand_builtin_apply_args (void)
1499 {
1500   /* Don't do __builtin_apply_args more than once in a function.
1501      Save the result of the first call and reuse it.  */
1502   if (apply_args_value != 0)
1503     return apply_args_value;
1504   {
1505     /* When this function is called, it means that registers must be
1506        saved on entry to this function.  So we migrate the
1507        call to the first insn of this function.  */
1508     rtx temp;
1509     rtx seq;
1510
1511     start_sequence ();
1512     temp = expand_builtin_apply_args_1 ();
1513     seq = get_insns ();
1514     end_sequence ();
1515
1516     apply_args_value = temp;
1517
1518     /* Put the insns after the NOTE that starts the function.
1519        If this is inside a start_sequence, make the outer-level insn
1520        chain current, so the code is placed at the start of the
1521        function.  If internal_arg_pointer is a non-virtual pseudo,
1522        it needs to be placed after the function that initializes
1523        that pseudo.  */
1524     push_topmost_sequence ();
1525     if (REG_P (crtl->args.internal_arg_pointer)
1526         && REGNO (crtl->args.internal_arg_pointer) > LAST_VIRTUAL_REGISTER)
1527       emit_insn_before (seq, parm_birth_insn);
1528     else
1529       emit_insn_before (seq, NEXT_INSN (entry_of_function ()));
1530     pop_topmost_sequence ();
1531     return temp;
1532   }
1533 }
1534
1535 /* Perform an untyped call and save the state required to perform an
1536    untyped return of whatever value was returned by the given function.  */
1537
1538 static rtx
1539 expand_builtin_apply (rtx function, rtx arguments, rtx argsize)
1540 {
1541   int size, align, regno;
1542   enum machine_mode mode;
1543   rtx incoming_args, result, reg, dest, src, call_insn;
1544   rtx old_stack_level = 0;
1545   rtx call_fusage = 0;
1546   rtx struct_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0);
1547
1548   arguments = convert_memory_address (Pmode, arguments);
1549
1550   /* Create a block where the return registers can be saved.  */
1551   result = assign_stack_local (BLKmode, apply_result_size (), -1);
1552
1553   /* Fetch the arg pointer from the ARGUMENTS block.  */
1554   incoming_args = gen_reg_rtx (Pmode);
1555   emit_move_insn (incoming_args, gen_rtx_MEM (Pmode, arguments));
1556 #ifndef STACK_GROWS_DOWNWARD
1557   incoming_args = expand_simple_binop (Pmode, MINUS, incoming_args, argsize,
1558                                        incoming_args, 0, OPTAB_LIB_WIDEN);
1559 #endif
1560
1561   /* Push a new argument block and copy the arguments.  Do not allow
1562      the (potential) memcpy call below to interfere with our stack
1563      manipulations.  */
1564   do_pending_stack_adjust ();
1565   NO_DEFER_POP;
1566
1567   /* Save the stack with nonlocal if available.  */
1568 #ifdef HAVE_save_stack_nonlocal
1569   if (HAVE_save_stack_nonlocal)
1570     emit_stack_save (SAVE_NONLOCAL, &old_stack_level);
1571   else
1572 #endif
1573     emit_stack_save (SAVE_BLOCK, &old_stack_level);
1574
1575   /* Allocate a block of memory onto the stack and copy the memory
1576      arguments to the outgoing arguments address.  We can pass TRUE
1577      as the 4th argument because we just saved the stack pointer
1578      and will restore it right after the call.  */
1579   allocate_dynamic_stack_space (argsize, 0, BIGGEST_ALIGNMENT, true);
1580
1581   /* Set DRAP flag to true, even though allocate_dynamic_stack_space
1582      may have already set current_function_calls_alloca to true.
1583      current_function_calls_alloca won't be set if argsize is zero,
1584      so we have to guarantee need_drap is true here.  */
1585   if (SUPPORTS_STACK_ALIGNMENT)
1586     crtl->need_drap = true;
1587
1588   dest = virtual_outgoing_args_rtx;
1589 #ifndef STACK_GROWS_DOWNWARD
1590   if (CONST_INT_P (argsize))
1591     dest = plus_constant (dest, -INTVAL (argsize));
1592   else
1593     dest = gen_rtx_PLUS (Pmode, dest, negate_rtx (Pmode, argsize));
1594 #endif
1595   dest = gen_rtx_MEM (BLKmode, dest);
1596   set_mem_align (dest, PARM_BOUNDARY);
1597   src = gen_rtx_MEM (BLKmode, incoming_args);
1598   set_mem_align (src, PARM_BOUNDARY);
1599   emit_block_move (dest, src, argsize, BLOCK_OP_NORMAL);
1600
1601   /* Refer to the argument block.  */
1602   apply_args_size ();
1603   arguments = gen_rtx_MEM (BLKmode, arguments);
1604   set_mem_align (arguments, PARM_BOUNDARY);
1605
1606   /* Walk past the arg-pointer and structure value address.  */
1607   size = GET_MODE_SIZE (Pmode);
1608   if (struct_value)
1609     size += GET_MODE_SIZE (Pmode);
1610
1611   /* Restore each of the registers previously saved.  Make USE insns
1612      for each of these registers for use in making the call.  */
1613   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1614     if ((mode = apply_args_mode[regno]) != VOIDmode)
1615       {
1616         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1617         if (size % align != 0)
1618           size = CEIL (size, align) * align;
1619         reg = gen_rtx_REG (mode, regno);
1620         emit_move_insn (reg, adjust_address (arguments, mode, size));
1621         use_reg (&call_fusage, reg);
1622         size += GET_MODE_SIZE (mode);
1623       }
1624
1625   /* Restore the structure value address unless this is passed as an
1626      "invisible" first argument.  */
1627   size = GET_MODE_SIZE (Pmode);
1628   if (struct_value)
1629     {
1630       rtx value = gen_reg_rtx (Pmode);
1631       emit_move_insn (value, adjust_address (arguments, Pmode, size));
1632       emit_move_insn (struct_value, value);
1633       if (REG_P (struct_value))
1634         use_reg (&call_fusage, struct_value);
1635       size += GET_MODE_SIZE (Pmode);
1636     }
1637
1638   /* All arguments and registers used for the call are set up by now!  */
1639   function = prepare_call_address (NULL, function, NULL, &call_fusage, 0, 0);
1640
1641   /* Ensure address is valid.  SYMBOL_REF is already valid, so no need,
1642      and we don't want to load it into a register as an optimization,
1643      because prepare_call_address already did it if it should be done.  */
1644   if (GET_CODE (function) != SYMBOL_REF)
1645     function = memory_address (FUNCTION_MODE, function);
1646
1647   /* Generate the actual call instruction and save the return value.  */
1648 #ifdef HAVE_untyped_call
1649   if (HAVE_untyped_call)
1650     emit_call_insn (gen_untyped_call (gen_rtx_MEM (FUNCTION_MODE, function),
1651                                       result, result_vector (1, result)));
1652   else
1653 #endif
1654 #ifdef HAVE_call_value
1655   if (HAVE_call_value)
1656     {
1657       rtx valreg = 0;
1658
1659       /* Locate the unique return register.  It is not possible to
1660          express a call that sets more than one return register using
1661          call_value; use untyped_call for that.  In fact, untyped_call
1662          only needs to save the return registers in the given block.  */
1663       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1664         if ((mode = apply_result_mode[regno]) != VOIDmode)
1665           {
1666             gcc_assert (!valreg); /* HAVE_untyped_call required.  */
1667
1668             valreg = gen_rtx_REG (mode, regno);
1669           }
1670
1671       emit_call_insn (GEN_CALL_VALUE (valreg,
1672                                       gen_rtx_MEM (FUNCTION_MODE, function),
1673                                       const0_rtx, NULL_RTX, const0_rtx));
1674
1675       emit_move_insn (adjust_address (result, GET_MODE (valreg), 0), valreg);
1676     }
1677   else
1678 #endif
1679     gcc_unreachable ();
1680
1681   /* Find the CALL insn we just emitted, and attach the register usage
1682      information.  */
1683   call_insn = last_call_insn ();
1684   add_function_usage_to (call_insn, call_fusage);
1685
1686   /* Restore the stack.  */
1687 #ifdef HAVE_save_stack_nonlocal
1688   if (HAVE_save_stack_nonlocal)
1689     emit_stack_restore (SAVE_NONLOCAL, old_stack_level);
1690   else
1691 #endif
1692     emit_stack_restore (SAVE_BLOCK, old_stack_level);
1693
1694   OK_DEFER_POP;
1695
1696   /* Return the address of the result block.  */
1697   result = copy_addr_to_reg (XEXP (result, 0));
1698   return convert_memory_address (ptr_mode, result);
1699 }
1700
1701 /* Perform an untyped return.  */
1702
1703 static void
1704 expand_builtin_return (rtx result)
1705 {
1706   int size, align, regno;
1707   enum machine_mode mode;
1708   rtx reg;
1709   rtx call_fusage = 0;
1710
1711   result = convert_memory_address (Pmode, result);
1712
1713   apply_result_size ();
1714   result = gen_rtx_MEM (BLKmode, result);
1715
1716 #ifdef HAVE_untyped_return
1717   if (HAVE_untyped_return)
1718     {
1719       emit_jump_insn (gen_untyped_return (result, result_vector (0, result)));
1720       emit_barrier ();
1721       return;
1722     }
1723 #endif
1724
1725   /* Restore the return value and note that each value is used.  */
1726   size = 0;
1727   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1728     if ((mode = apply_result_mode[regno]) != VOIDmode)
1729       {
1730         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1731         if (size % align != 0)
1732           size = CEIL (size, align) * align;
1733         reg = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1734         emit_move_insn (reg, adjust_address (result, mode, size));
1735
1736         push_to_sequence (call_fusage);
1737         emit_use (reg);
1738         call_fusage = get_insns ();
1739         end_sequence ();
1740         size += GET_MODE_SIZE (mode);
1741       }
1742
1743   /* Put the USE insns before the return.  */
1744   emit_insn (call_fusage);
1745
1746   /* Return whatever values was restored by jumping directly to the end
1747      of the function.  */
1748   expand_naked_return ();
1749 }
1750
1751 /* Used by expand_builtin_classify_type and fold_builtin_classify_type.  */
1752
1753 static enum type_class
1754 type_to_class (tree type)
1755 {
1756   switch (TREE_CODE (type))
1757     {
1758     case VOID_TYPE:        return void_type_class;
1759     case INTEGER_TYPE:     return integer_type_class;
1760     case ENUMERAL_TYPE:    return enumeral_type_class;
1761     case BOOLEAN_TYPE:     return boolean_type_class;
1762     case POINTER_TYPE:     return pointer_type_class;
1763     case REFERENCE_TYPE:   return reference_type_class;
1764     case OFFSET_TYPE:      return offset_type_class;
1765     case REAL_TYPE:        return real_type_class;
1766     case COMPLEX_TYPE:     return complex_type_class;
1767     case FUNCTION_TYPE:    return function_type_class;
1768     case METHOD_TYPE:      return method_type_class;
1769     case RECORD_TYPE:      return record_type_class;
1770     case UNION_TYPE:
1771     case QUAL_UNION_TYPE:  return union_type_class;
1772     case ARRAY_TYPE:       return (TYPE_STRING_FLAG (type)
1773                                    ? string_type_class : array_type_class);
1774     case LANG_TYPE:        return lang_type_class;
1775     default:               return no_type_class;
1776     }
1777 }
1778
1779 /* Expand a call EXP to __builtin_classify_type.  */
1780
1781 static rtx
1782 expand_builtin_classify_type (tree exp)
1783 {
1784   if (call_expr_nargs (exp))
1785     return GEN_INT (type_to_class (TREE_TYPE (CALL_EXPR_ARG (exp, 0))));
1786   return GEN_INT (no_type_class);
1787 }
1788
1789 /* This helper macro, meant to be used in mathfn_built_in below,
1790    determines which among a set of three builtin math functions is
1791    appropriate for a given type mode.  The `F' and `L' cases are
1792    automatically generated from the `double' case.  */
1793 #define CASE_MATHFN(BUILT_IN_MATHFN) \
1794   case BUILT_IN_MATHFN: case BUILT_IN_MATHFN##F: case BUILT_IN_MATHFN##L: \
1795   fcode = BUILT_IN_MATHFN; fcodef = BUILT_IN_MATHFN##F ; \
1796   fcodel = BUILT_IN_MATHFN##L ; break;
1797 /* Similar to above, but appends _R after any F/L suffix.  */
1798 #define CASE_MATHFN_REENT(BUILT_IN_MATHFN) \
1799   case BUILT_IN_MATHFN##_R: case BUILT_IN_MATHFN##F_R: case BUILT_IN_MATHFN##L_R: \
1800   fcode = BUILT_IN_MATHFN##_R; fcodef = BUILT_IN_MATHFN##F_R ; \
1801   fcodel = BUILT_IN_MATHFN##L_R ; break;
1802
1803 /* Return mathematic function equivalent to FN but operating directly
1804    on TYPE, if available.  If IMPLICIT is true find the function in
1805    implicit_built_in_decls[], otherwise use built_in_decls[].  If we
1806    can't do the conversion, return zero.  */
1807
1808 static tree
1809 mathfn_built_in_1 (tree type, enum built_in_function fn, bool implicit)
1810 {
1811   tree const *const fn_arr
1812     = implicit ? implicit_built_in_decls : built_in_decls;
1813   enum built_in_function fcode, fcodef, fcodel;
1814
1815   switch (fn)
1816     {
1817       CASE_MATHFN (BUILT_IN_ACOS)
1818       CASE_MATHFN (BUILT_IN_ACOSH)
1819       CASE_MATHFN (BUILT_IN_ASIN)
1820       CASE_MATHFN (BUILT_IN_ASINH)
1821       CASE_MATHFN (BUILT_IN_ATAN)
1822       CASE_MATHFN (BUILT_IN_ATAN2)
1823       CASE_MATHFN (BUILT_IN_ATANH)
1824       CASE_MATHFN (BUILT_IN_CBRT)
1825       CASE_MATHFN (BUILT_IN_CEIL)
1826       CASE_MATHFN (BUILT_IN_CEXPI)
1827       CASE_MATHFN (BUILT_IN_COPYSIGN)
1828       CASE_MATHFN (BUILT_IN_COS)
1829       CASE_MATHFN (BUILT_IN_COSH)
1830       CASE_MATHFN (BUILT_IN_DREM)
1831       CASE_MATHFN (BUILT_IN_ERF)
1832       CASE_MATHFN (BUILT_IN_ERFC)
1833       CASE_MATHFN (BUILT_IN_EXP)
1834       CASE_MATHFN (BUILT_IN_EXP10)
1835       CASE_MATHFN (BUILT_IN_EXP2)
1836       CASE_MATHFN (BUILT_IN_EXPM1)
1837       CASE_MATHFN (BUILT_IN_FABS)
1838       CASE_MATHFN (BUILT_IN_FDIM)
1839       CASE_MATHFN (BUILT_IN_FLOOR)
1840       CASE_MATHFN (BUILT_IN_FMA)
1841       CASE_MATHFN (BUILT_IN_FMAX)
1842       CASE_MATHFN (BUILT_IN_FMIN)
1843       CASE_MATHFN (BUILT_IN_FMOD)
1844       CASE_MATHFN (BUILT_IN_FREXP)
1845       CASE_MATHFN (BUILT_IN_GAMMA)
1846       CASE_MATHFN_REENT (BUILT_IN_GAMMA) /* GAMMA_R */
1847       CASE_MATHFN (BUILT_IN_HUGE_VAL)
1848       CASE_MATHFN (BUILT_IN_HYPOT)
1849       CASE_MATHFN (BUILT_IN_ILOGB)
1850       CASE_MATHFN (BUILT_IN_INF)
1851       CASE_MATHFN (BUILT_IN_ISINF)
1852       CASE_MATHFN (BUILT_IN_J0)
1853       CASE_MATHFN (BUILT_IN_J1)
1854       CASE_MATHFN (BUILT_IN_JN)
1855       CASE_MATHFN (BUILT_IN_LCEIL)
1856       CASE_MATHFN (BUILT_IN_LDEXP)
1857       CASE_MATHFN (BUILT_IN_LFLOOR)
1858       CASE_MATHFN (BUILT_IN_LGAMMA)
1859       CASE_MATHFN_REENT (BUILT_IN_LGAMMA) /* LGAMMA_R */
1860       CASE_MATHFN (BUILT_IN_LLCEIL)
1861       CASE_MATHFN (BUILT_IN_LLFLOOR)
1862       CASE_MATHFN (BUILT_IN_LLRINT)
1863       CASE_MATHFN (BUILT_IN_LLROUND)
1864       CASE_MATHFN (BUILT_IN_LOG)
1865       CASE_MATHFN (BUILT_IN_LOG10)
1866       CASE_MATHFN (BUILT_IN_LOG1P)
1867       CASE_MATHFN (BUILT_IN_LOG2)
1868       CASE_MATHFN (BUILT_IN_LOGB)
1869       CASE_MATHFN (BUILT_IN_LRINT)
1870       CASE_MATHFN (BUILT_IN_LROUND)
1871       CASE_MATHFN (BUILT_IN_MODF)
1872       CASE_MATHFN (BUILT_IN_NAN)
1873       CASE_MATHFN (BUILT_IN_NANS)
1874       CASE_MATHFN (BUILT_IN_NEARBYINT)
1875       CASE_MATHFN (BUILT_IN_NEXTAFTER)
1876       CASE_MATHFN (BUILT_IN_NEXTTOWARD)
1877       CASE_MATHFN (BUILT_IN_POW)
1878       CASE_MATHFN (BUILT_IN_POWI)
1879       CASE_MATHFN (BUILT_IN_POW10)
1880       CASE_MATHFN (BUILT_IN_REMAINDER)
1881       CASE_MATHFN (BUILT_IN_REMQUO)
1882       CASE_MATHFN (BUILT_IN_RINT)
1883       CASE_MATHFN (BUILT_IN_ROUND)
1884       CASE_MATHFN (BUILT_IN_SCALB)
1885       CASE_MATHFN (BUILT_IN_SCALBLN)
1886       CASE_MATHFN (BUILT_IN_SCALBN)
1887       CASE_MATHFN (BUILT_IN_SIGNBIT)
1888       CASE_MATHFN (BUILT_IN_SIGNIFICAND)
1889       CASE_MATHFN (BUILT_IN_SIN)
1890       CASE_MATHFN (BUILT_IN_SINCOS)
1891       CASE_MATHFN (BUILT_IN_SINH)
1892       CASE_MATHFN (BUILT_IN_SQRT)
1893       CASE_MATHFN (BUILT_IN_TAN)
1894       CASE_MATHFN (BUILT_IN_TANH)
1895       CASE_MATHFN (BUILT_IN_TGAMMA)
1896       CASE_MATHFN (BUILT_IN_TRUNC)
1897       CASE_MATHFN (BUILT_IN_Y0)
1898       CASE_MATHFN (BUILT_IN_Y1)
1899       CASE_MATHFN (BUILT_IN_YN)
1900
1901       default:
1902         return NULL_TREE;
1903       }
1904
1905   if (TYPE_MAIN_VARIANT (type) == double_type_node)
1906     return fn_arr[fcode];
1907   else if (TYPE_MAIN_VARIANT (type) == float_type_node)
1908     return fn_arr[fcodef];
1909   else if (TYPE_MAIN_VARIANT (type) == long_double_type_node)
1910     return fn_arr[fcodel];
1911   else
1912     return NULL_TREE;
1913 }
1914
1915 /* Like mathfn_built_in_1(), but always use the implicit array.  */
1916
1917 tree
1918 mathfn_built_in (tree type, enum built_in_function fn)
1919 {
1920   return mathfn_built_in_1 (type, fn, /*implicit=*/ 1);
1921 }
1922
1923 /* If errno must be maintained, expand the RTL to check if the result,
1924    TARGET, of a built-in function call, EXP, is NaN, and if so set
1925    errno to EDOM.  */
1926
1927 static void
1928 expand_errno_check (tree exp, rtx target)
1929 {
1930   rtx lab = gen_label_rtx ();
1931
1932   /* Test the result; if it is NaN, set errno=EDOM because
1933      the argument was not in the domain.  */
1934   do_compare_rtx_and_jump (target, target, EQ, 0, GET_MODE (target),
1935                            NULL_RTX, NULL_RTX, lab,
1936                            /* The jump is very likely.  */
1937                            REG_BR_PROB_BASE - (REG_BR_PROB_BASE / 2000 - 1));
1938
1939 #ifdef TARGET_EDOM
1940   /* If this built-in doesn't throw an exception, set errno directly.  */
1941   if (TREE_NOTHROW (TREE_OPERAND (CALL_EXPR_FN (exp), 0)))
1942     {
1943 #ifdef GEN_ERRNO_RTX
1944       rtx errno_rtx = GEN_ERRNO_RTX;
1945 #else
1946       rtx errno_rtx
1947           = gen_rtx_MEM (word_mode, gen_rtx_SYMBOL_REF (Pmode, "errno"));
1948 #endif
1949       emit_move_insn (errno_rtx, GEN_INT (TARGET_EDOM));
1950       emit_label (lab);
1951       return;
1952     }
1953 #endif
1954
1955   /* Make sure the library call isn't expanded as a tail call.  */
1956   CALL_EXPR_TAILCALL (exp) = 0;
1957
1958   /* We can't set errno=EDOM directly; let the library call do it.
1959      Pop the arguments right away in case the call gets deleted.  */
1960   NO_DEFER_POP;
1961   expand_call (exp, target, 0);
1962   OK_DEFER_POP;
1963   emit_label (lab);
1964 }
1965
1966 /* Expand a call to one of the builtin math functions (sqrt, exp, or log).
1967    Return NULL_RTX if a normal call should be emitted rather than expanding
1968    the function in-line.  EXP is the expression that is a call to the builtin
1969    function; if convenient, the result should be placed in TARGET.
1970    SUBTARGET may be used as the target for computing one of EXP's operands.  */
1971
1972 static rtx
1973 expand_builtin_mathfn (tree exp, rtx target, rtx subtarget)
1974 {
1975   optab builtin_optab;
1976   rtx op0, insns;
1977   tree fndecl = get_callee_fndecl (exp);
1978   enum machine_mode mode;
1979   bool errno_set = false;
1980   tree arg;
1981
1982   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
1983     return NULL_RTX;
1984
1985   arg = CALL_EXPR_ARG (exp, 0);
1986
1987   switch (DECL_FUNCTION_CODE (fndecl))
1988     {
1989     CASE_FLT_FN (BUILT_IN_SQRT):
1990       errno_set = ! tree_expr_nonnegative_p (arg);
1991       builtin_optab = sqrt_optab;
1992       break;
1993     CASE_FLT_FN (BUILT_IN_EXP):
1994       errno_set = true; builtin_optab = exp_optab; break;
1995     CASE_FLT_FN (BUILT_IN_EXP10):
1996     CASE_FLT_FN (BUILT_IN_POW10):
1997       errno_set = true; builtin_optab = exp10_optab; break;
1998     CASE_FLT_FN (BUILT_IN_EXP2):
1999       errno_set = true; builtin_optab = exp2_optab; break;
2000     CASE_FLT_FN (BUILT_IN_EXPM1):
2001       errno_set = true; builtin_optab = expm1_optab; break;
2002     CASE_FLT_FN (BUILT_IN_LOGB):
2003       errno_set = true; builtin_optab = logb_optab; break;
2004     CASE_FLT_FN (BUILT_IN_LOG):
2005       errno_set = true; builtin_optab = log_optab; break;
2006     CASE_FLT_FN (BUILT_IN_LOG10):
2007       errno_set = true; builtin_optab = log10_optab; break;
2008     CASE_FLT_FN (BUILT_IN_LOG2):
2009       errno_set = true; builtin_optab = log2_optab; break;
2010     CASE_FLT_FN (BUILT_IN_LOG1P):
2011       errno_set = true; builtin_optab = log1p_optab; break;
2012     CASE_FLT_FN (BUILT_IN_ASIN):
2013       builtin_optab = asin_optab; break;
2014     CASE_FLT_FN (BUILT_IN_ACOS):
2015       builtin_optab = acos_optab; break;
2016     CASE_FLT_FN (BUILT_IN_TAN):
2017       builtin_optab = tan_optab; break;
2018     CASE_FLT_FN (BUILT_IN_ATAN):
2019       builtin_optab = atan_optab; break;
2020     CASE_FLT_FN (BUILT_IN_FLOOR):
2021       builtin_optab = floor_optab; break;
2022     CASE_FLT_FN (BUILT_IN_CEIL):
2023       builtin_optab = ceil_optab; break;
2024     CASE_FLT_FN (BUILT_IN_TRUNC):
2025       builtin_optab = btrunc_optab; break;
2026     CASE_FLT_FN (BUILT_IN_ROUND):
2027       builtin_optab = round_optab; break;
2028     CASE_FLT_FN (BUILT_IN_NEARBYINT):
2029       builtin_optab = nearbyint_optab;
2030       if (flag_trapping_math)
2031         break;
2032       /* Else fallthrough and expand as rint.  */
2033     CASE_FLT_FN (BUILT_IN_RINT):
2034       builtin_optab = rint_optab; break;
2035     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
2036       builtin_optab = significand_optab; break;
2037     default:
2038       gcc_unreachable ();
2039     }
2040
2041   /* Make a suitable register to place result in.  */
2042   mode = TYPE_MODE (TREE_TYPE (exp));
2043
2044   if (! flag_errno_math || ! HONOR_NANS (mode))
2045     errno_set = false;
2046
2047   /* Before working hard, check whether the instruction is available.  */
2048   if (optab_handler (builtin_optab, mode) != CODE_FOR_nothing
2049       && (!errno_set || !optimize_insn_for_size_p ()))
2050     {
2051       target = gen_reg_rtx (mode);
2052
2053       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2054          need to expand the argument again.  This way, we will not perform
2055          side-effects more the once.  */
2056       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2057
2058       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2059
2060       start_sequence ();
2061
2062       /* Compute into TARGET.
2063          Set TARGET to wherever the result comes back.  */
2064       target = expand_unop (mode, builtin_optab, op0, target, 0);
2065
2066       if (target != 0)
2067         {
2068           if (errno_set)
2069             expand_errno_check (exp, target);
2070
2071           /* Output the entire sequence.  */
2072           insns = get_insns ();
2073           end_sequence ();
2074           emit_insn (insns);
2075           return target;
2076         }
2077
2078       /* If we were unable to expand via the builtin, stop the sequence
2079          (without outputting the insns) and call to the library function
2080          with the stabilized argument list.  */
2081       end_sequence ();
2082     }
2083
2084   return expand_call (exp, target, target == const0_rtx);
2085 }
2086
2087 /* Expand a call to the builtin binary math functions (pow and atan2).
2088    Return NULL_RTX if a normal call should be emitted rather than expanding the
2089    function in-line.  EXP is the expression that is a call to the builtin
2090    function; if convenient, the result should be placed in TARGET.
2091    SUBTARGET may be used as the target for computing one of EXP's
2092    operands.  */
2093
2094 static rtx
2095 expand_builtin_mathfn_2 (tree exp, rtx target, rtx subtarget)
2096 {
2097   optab builtin_optab;
2098   rtx op0, op1, insns;
2099   int op1_type = REAL_TYPE;
2100   tree fndecl = get_callee_fndecl (exp);
2101   tree arg0, arg1;
2102   enum machine_mode mode;
2103   bool errno_set = true;
2104
2105   switch (DECL_FUNCTION_CODE (fndecl))
2106     {
2107     CASE_FLT_FN (BUILT_IN_SCALBN):
2108     CASE_FLT_FN (BUILT_IN_SCALBLN):
2109     CASE_FLT_FN (BUILT_IN_LDEXP):
2110       op1_type = INTEGER_TYPE;
2111     default:
2112       break;
2113     }
2114
2115   if (!validate_arglist (exp, REAL_TYPE, op1_type, VOID_TYPE))
2116     return NULL_RTX;
2117
2118   arg0 = CALL_EXPR_ARG (exp, 0);
2119   arg1 = CALL_EXPR_ARG (exp, 1);
2120
2121   switch (DECL_FUNCTION_CODE (fndecl))
2122     {
2123     CASE_FLT_FN (BUILT_IN_POW):
2124       builtin_optab = pow_optab; break;
2125     CASE_FLT_FN (BUILT_IN_ATAN2):
2126       builtin_optab = atan2_optab; break;
2127     CASE_FLT_FN (BUILT_IN_SCALB):
2128       if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (exp)))->b != 2)
2129         return 0;
2130       builtin_optab = scalb_optab; break;
2131     CASE_FLT_FN (BUILT_IN_SCALBN):
2132     CASE_FLT_FN (BUILT_IN_SCALBLN):
2133       if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (exp)))->b != 2)
2134         return 0;
2135     /* Fall through... */
2136     CASE_FLT_FN (BUILT_IN_LDEXP):
2137       builtin_optab = ldexp_optab; break;
2138     CASE_FLT_FN (BUILT_IN_FMOD):
2139       builtin_optab = fmod_optab; break;
2140     CASE_FLT_FN (BUILT_IN_REMAINDER):
2141     CASE_FLT_FN (BUILT_IN_DREM):
2142       builtin_optab = remainder_optab; break;
2143     default:
2144       gcc_unreachable ();
2145     }
2146
2147   /* Make a suitable register to place result in.  */
2148   mode = TYPE_MODE (TREE_TYPE (exp));
2149
2150   /* Before working hard, check whether the instruction is available.  */
2151   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2152     return NULL_RTX;
2153
2154   target = gen_reg_rtx (mode);
2155
2156   if (! flag_errno_math || ! HONOR_NANS (mode))
2157     errno_set = false;
2158
2159   if (errno_set && optimize_insn_for_size_p ())
2160     return 0;
2161
2162   /* Always stabilize the argument list.  */
2163   CALL_EXPR_ARG (exp, 0) = arg0 = builtin_save_expr (arg0);
2164   CALL_EXPR_ARG (exp, 1) = arg1 = builtin_save_expr (arg1);
2165
2166   op0 = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
2167   op1 = expand_normal (arg1);
2168
2169   start_sequence ();
2170
2171   /* Compute into TARGET.
2172      Set TARGET to wherever the result comes back.  */
2173   target = expand_binop (mode, builtin_optab, op0, op1,
2174                          target, 0, OPTAB_DIRECT);
2175
2176   /* If we were unable to expand via the builtin, stop the sequence
2177      (without outputting the insns) and call to the library function
2178      with the stabilized argument list.  */
2179   if (target == 0)
2180     {
2181       end_sequence ();
2182       return expand_call (exp, target, target == const0_rtx);
2183     }
2184
2185   if (errno_set)
2186     expand_errno_check (exp, target);
2187
2188   /* Output the entire sequence.  */
2189   insns = get_insns ();
2190   end_sequence ();
2191   emit_insn (insns);
2192
2193   return target;
2194 }
2195
2196 /* Expand a call to the builtin trinary math functions (fma).
2197    Return NULL_RTX if a normal call should be emitted rather than expanding the
2198    function in-line.  EXP is the expression that is a call to the builtin
2199    function; if convenient, the result should be placed in TARGET.
2200    SUBTARGET may be used as the target for computing one of EXP's
2201    operands.  */
2202
2203 static rtx
2204 expand_builtin_mathfn_ternary (tree exp, rtx target, rtx subtarget)
2205 {
2206   optab builtin_optab;
2207   rtx op0, op1, op2, insns;
2208   tree fndecl = get_callee_fndecl (exp);
2209   tree arg0, arg1, arg2;
2210   enum machine_mode mode;
2211
2212   if (!validate_arglist (exp, REAL_TYPE, REAL_TYPE, REAL_TYPE, VOID_TYPE))
2213     return NULL_RTX;
2214
2215   arg0 = CALL_EXPR_ARG (exp, 0);
2216   arg1 = CALL_EXPR_ARG (exp, 1);
2217   arg2 = CALL_EXPR_ARG (exp, 2);
2218
2219   switch (DECL_FUNCTION_CODE (fndecl))
2220     {
2221     CASE_FLT_FN (BUILT_IN_FMA):
2222       builtin_optab = fma_optab; break;
2223     default:
2224       gcc_unreachable ();
2225     }
2226
2227   /* Make a suitable register to place result in.  */
2228   mode = TYPE_MODE (TREE_TYPE (exp));
2229
2230   /* Before working hard, check whether the instruction is available.  */
2231   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2232     return NULL_RTX;
2233
2234   target = gen_reg_rtx (mode);
2235
2236   /* Always stabilize the argument list.  */
2237   CALL_EXPR_ARG (exp, 0) = arg0 = builtin_save_expr (arg0);
2238   CALL_EXPR_ARG (exp, 1) = arg1 = builtin_save_expr (arg1);
2239   CALL_EXPR_ARG (exp, 2) = arg2 = builtin_save_expr (arg2);
2240
2241   op0 = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
2242   op1 = expand_normal (arg1);
2243   op2 = expand_normal (arg2);
2244
2245   start_sequence ();
2246
2247   /* Compute into TARGET.
2248      Set TARGET to wherever the result comes back.  */
2249   target = expand_ternary_op (mode, builtin_optab, op0, op1, op2,
2250                               target, 0);
2251
2252   /* If we were unable to expand via the builtin, stop the sequence
2253      (without outputting the insns) and call to the library function
2254      with the stabilized argument list.  */
2255   if (target == 0)
2256     {
2257       end_sequence ();
2258       return expand_call (exp, target, target == const0_rtx);
2259     }
2260
2261   /* Output the entire sequence.  */
2262   insns = get_insns ();
2263   end_sequence ();
2264   emit_insn (insns);
2265
2266   return target;
2267 }
2268
2269 /* Expand a call to the builtin sin and cos math functions.
2270    Return NULL_RTX if a normal call should be emitted rather than expanding the
2271    function in-line.  EXP is the expression that is a call to the builtin
2272    function; if convenient, the result should be placed in TARGET.
2273    SUBTARGET may be used as the target for computing one of EXP's
2274    operands.  */
2275
2276 static rtx
2277 expand_builtin_mathfn_3 (tree exp, rtx target, rtx subtarget)
2278 {
2279   optab builtin_optab;
2280   rtx op0, insns;
2281   tree fndecl = get_callee_fndecl (exp);
2282   enum machine_mode mode;
2283   tree arg;
2284
2285   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2286     return NULL_RTX;
2287
2288   arg = CALL_EXPR_ARG (exp, 0);
2289
2290   switch (DECL_FUNCTION_CODE (fndecl))
2291     {
2292     CASE_FLT_FN (BUILT_IN_SIN):
2293     CASE_FLT_FN (BUILT_IN_COS):
2294       builtin_optab = sincos_optab; break;
2295     default:
2296       gcc_unreachable ();
2297     }
2298
2299   /* Make a suitable register to place result in.  */
2300   mode = TYPE_MODE (TREE_TYPE (exp));
2301
2302   /* Check if sincos insn is available, otherwise fallback
2303      to sin or cos insn.  */
2304   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2305     switch (DECL_FUNCTION_CODE (fndecl))
2306       {
2307       CASE_FLT_FN (BUILT_IN_SIN):
2308         builtin_optab = sin_optab; break;
2309       CASE_FLT_FN (BUILT_IN_COS):
2310         builtin_optab = cos_optab; break;
2311       default:
2312         gcc_unreachable ();
2313       }
2314
2315   /* Before working hard, check whether the instruction is available.  */
2316   if (optab_handler (builtin_optab, mode) != CODE_FOR_nothing)
2317     {
2318       target = gen_reg_rtx (mode);
2319
2320       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2321          need to expand the argument again.  This way, we will not perform
2322          side-effects more the once.  */
2323       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2324
2325       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2326
2327       start_sequence ();
2328
2329       /* Compute into TARGET.
2330          Set TARGET to wherever the result comes back.  */
2331       if (builtin_optab == sincos_optab)
2332         {
2333           int result;
2334
2335           switch (DECL_FUNCTION_CODE (fndecl))
2336             {
2337             CASE_FLT_FN (BUILT_IN_SIN):
2338               result = expand_twoval_unop (builtin_optab, op0, 0, target, 0);
2339               break;
2340             CASE_FLT_FN (BUILT_IN_COS):
2341               result = expand_twoval_unop (builtin_optab, op0, target, 0, 0);
2342               break;
2343             default:
2344               gcc_unreachable ();
2345             }
2346           gcc_assert (result);
2347         }
2348       else
2349         {
2350           target = expand_unop (mode, builtin_optab, op0, target, 0);
2351         }
2352
2353       if (target != 0)
2354         {
2355           /* Output the entire sequence.  */
2356           insns = get_insns ();
2357           end_sequence ();
2358           emit_insn (insns);
2359           return target;
2360         }
2361
2362       /* If we were unable to expand via the builtin, stop the sequence
2363          (without outputting the insns) and call to the library function
2364          with the stabilized argument list.  */
2365       end_sequence ();
2366     }
2367
2368   target = expand_call (exp, target, target == const0_rtx);
2369
2370   return target;
2371 }
2372
2373 /* Given an interclass math builtin decl FNDECL and it's argument ARG
2374    return an RTL instruction code that implements the functionality.
2375    If that isn't possible or available return CODE_FOR_nothing.  */
2376
2377 static enum insn_code
2378 interclass_mathfn_icode (tree arg, tree fndecl)
2379 {
2380   bool errno_set = false;
2381   optab builtin_optab = 0;
2382   enum machine_mode mode;
2383
2384   switch (DECL_FUNCTION_CODE (fndecl))
2385     {
2386     CASE_FLT_FN (BUILT_IN_ILOGB):
2387       errno_set = true; builtin_optab = ilogb_optab; break;
2388     CASE_FLT_FN (BUILT_IN_ISINF):
2389       builtin_optab = isinf_optab; break;
2390     case BUILT_IN_ISNORMAL:
2391     case BUILT_IN_ISFINITE:
2392     CASE_FLT_FN (BUILT_IN_FINITE):
2393     case BUILT_IN_FINITED32:
2394     case BUILT_IN_FINITED64:
2395     case BUILT_IN_FINITED128:
2396     case BUILT_IN_ISINFD32:
2397     case BUILT_IN_ISINFD64:
2398     case BUILT_IN_ISINFD128:
2399       /* These builtins have no optabs (yet).  */
2400       break;
2401     default:
2402       gcc_unreachable ();
2403     }
2404
2405   /* There's no easy way to detect the case we need to set EDOM.  */
2406   if (flag_errno_math && errno_set)
2407     return CODE_FOR_nothing;
2408
2409   /* Optab mode depends on the mode of the input argument.  */
2410   mode = TYPE_MODE (TREE_TYPE (arg));
2411
2412   if (builtin_optab)
2413     return optab_handler (builtin_optab, mode);
2414   return CODE_FOR_nothing;
2415 }
2416
2417 /* Expand a call to one of the builtin math functions that operate on
2418    floating point argument and output an integer result (ilogb, isinf,
2419    isnan, etc).
2420    Return 0 if a normal call should be emitted rather than expanding the
2421    function in-line.  EXP is the expression that is a call to the builtin
2422    function; if convenient, the result should be placed in TARGET.  */
2423
2424 static rtx
2425 expand_builtin_interclass_mathfn (tree exp, rtx target)
2426 {
2427   enum insn_code icode = CODE_FOR_nothing;
2428   rtx op0;
2429   tree fndecl = get_callee_fndecl (exp);
2430   enum machine_mode mode;
2431   tree arg;
2432
2433   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2434     return NULL_RTX;
2435
2436   arg = CALL_EXPR_ARG (exp, 0);
2437   icode = interclass_mathfn_icode (arg, fndecl);
2438   mode = TYPE_MODE (TREE_TYPE (arg));
2439
2440   if (icode != CODE_FOR_nothing)
2441     {
2442       struct expand_operand ops[1];
2443       rtx last = get_last_insn ();
2444       tree orig_arg = arg;
2445
2446       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2447          need to expand the argument again.  This way, we will not perform
2448          side-effects more the once.  */
2449       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2450
2451       op0 = expand_expr (arg, NULL_RTX, VOIDmode, EXPAND_NORMAL);
2452
2453       if (mode != GET_MODE (op0))
2454         op0 = convert_to_mode (mode, op0, 0);
2455
2456       create_output_operand (&ops[0], target, TYPE_MODE (TREE_TYPE (exp)));
2457       if (maybe_legitimize_operands (icode, 0, 1, ops)
2458           && maybe_emit_unop_insn (icode, ops[0].value, op0, UNKNOWN))
2459         return ops[0].value;
2460
2461       delete_insns_since (last);
2462       CALL_EXPR_ARG (exp, 0) = orig_arg;
2463     }
2464
2465   return NULL_RTX;
2466 }
2467
2468 /* Expand a call to the builtin sincos math function.
2469    Return NULL_RTX if a normal call should be emitted rather than expanding the
2470    function in-line.  EXP is the expression that is a call to the builtin
2471    function.  */
2472
2473 static rtx
2474 expand_builtin_sincos (tree exp)
2475 {
2476   rtx op0, op1, op2, target1, target2;
2477   enum machine_mode mode;
2478   tree arg, sinp, cosp;
2479   int result;
2480   location_t loc = EXPR_LOCATION (exp);
2481   tree alias_type, alias_off;
2482
2483   if (!validate_arglist (exp, REAL_TYPE,
2484                          POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
2485     return NULL_RTX;
2486
2487   arg = CALL_EXPR_ARG (exp, 0);
2488   sinp = CALL_EXPR_ARG (exp, 1);
2489   cosp = CALL_EXPR_ARG (exp, 2);
2490
2491   /* Make a suitable register to place result in.  */
2492   mode = TYPE_MODE (TREE_TYPE (arg));
2493
2494   /* Check if sincos insn is available, otherwise emit the call.  */
2495   if (optab_handler (sincos_optab, mode) == CODE_FOR_nothing)
2496     return NULL_RTX;
2497
2498   target1 = gen_reg_rtx (mode);
2499   target2 = gen_reg_rtx (mode);
2500
2501   op0 = expand_normal (arg);
2502   alias_type = build_pointer_type_for_mode (TREE_TYPE (arg), ptr_mode, true);
2503   alias_off = build_int_cst (alias_type, 0);
2504   op1 = expand_normal (fold_build2_loc (loc, MEM_REF, TREE_TYPE (arg),
2505                                         sinp, alias_off));
2506   op2 = expand_normal (fold_build2_loc (loc, MEM_REF, TREE_TYPE (arg),
2507                                         cosp, alias_off));
2508
2509   /* Compute into target1 and target2.
2510      Set TARGET to wherever the result comes back.  */
2511   result = expand_twoval_unop (sincos_optab, op0, target2, target1, 0);
2512   gcc_assert (result);
2513
2514   /* Move target1 and target2 to the memory locations indicated
2515      by op1 and op2.  */
2516   emit_move_insn (op1, target1);
2517   emit_move_insn (op2, target2);
2518
2519   return const0_rtx;
2520 }
2521
2522 /* Expand a call to the internal cexpi builtin to the sincos math function.
2523    EXP is the expression that is a call to the builtin function; if convenient,
2524    the result should be placed in TARGET.  */
2525
2526 static rtx
2527 expand_builtin_cexpi (tree exp, rtx target)
2528 {
2529   tree fndecl = get_callee_fndecl (exp);
2530   tree arg, type;
2531   enum machine_mode mode;
2532   rtx op0, op1, op2;
2533   location_t loc = EXPR_LOCATION (exp);
2534
2535   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2536     return NULL_RTX;
2537
2538   arg = CALL_EXPR_ARG (exp, 0);
2539   type = TREE_TYPE (arg);
2540   mode = TYPE_MODE (TREE_TYPE (arg));
2541
2542   /* Try expanding via a sincos optab, fall back to emitting a libcall
2543      to sincos or cexp.  We are sure we have sincos or cexp because cexpi
2544      is only generated from sincos, cexp or if we have either of them.  */
2545   if (optab_handler (sincos_optab, mode) != CODE_FOR_nothing)
2546     {
2547       op1 = gen_reg_rtx (mode);
2548       op2 = gen_reg_rtx (mode);
2549
2550       op0 = expand_expr (arg, NULL_RTX, VOIDmode, EXPAND_NORMAL);
2551
2552       /* Compute into op1 and op2.  */
2553       expand_twoval_unop (sincos_optab, op0, op2, op1, 0);
2554     }
2555   else if (TARGET_HAS_SINCOS)
2556     {
2557       tree call, fn = NULL_TREE;
2558       tree top1, top2;
2559       rtx op1a, op2a;
2560
2561       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2562         fn = built_in_decls[BUILT_IN_SINCOSF];
2563       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2564         fn = built_in_decls[BUILT_IN_SINCOS];
2565       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2566         fn = built_in_decls[BUILT_IN_SINCOSL];
2567       else
2568         gcc_unreachable ();
2569
2570       op1 = assign_temp (TREE_TYPE (arg), 0, 1, 1);
2571       op2 = assign_temp (TREE_TYPE (arg), 0, 1, 1);
2572       op1a = copy_to_mode_reg (Pmode, XEXP (op1, 0));
2573       op2a = copy_to_mode_reg (Pmode, XEXP (op2, 0));
2574       top1 = make_tree (build_pointer_type (TREE_TYPE (arg)), op1a);
2575       top2 = make_tree (build_pointer_type (TREE_TYPE (arg)), op2a);
2576
2577       /* Make sure not to fold the sincos call again.  */
2578       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2579       expand_normal (build_call_nary (TREE_TYPE (TREE_TYPE (fn)),
2580                                       call, 3, arg, top1, top2));
2581     }
2582   else
2583     {
2584       tree call, fn = NULL_TREE, narg;
2585       tree ctype = build_complex_type (type);
2586
2587       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2588         fn = built_in_decls[BUILT_IN_CEXPF];
2589       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2590         fn = built_in_decls[BUILT_IN_CEXP];
2591       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2592         fn = built_in_decls[BUILT_IN_CEXPL];
2593       else
2594         gcc_unreachable ();
2595
2596       /* If we don't have a decl for cexp create one.  This is the
2597          friendliest fallback if the user calls __builtin_cexpi
2598          without full target C99 function support.  */
2599       if (fn == NULL_TREE)
2600         {
2601           tree fntype;
2602           const char *name = NULL;
2603
2604           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2605             name = "cexpf";
2606           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2607             name = "cexp";
2608           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2609             name = "cexpl";
2610
2611           fntype = build_function_type_list (ctype, ctype, NULL_TREE);
2612           fn = build_fn_decl (name, fntype);
2613         }
2614
2615       narg = fold_build2_loc (loc, COMPLEX_EXPR, ctype,
2616                           build_real (type, dconst0), arg);
2617
2618       /* Make sure not to fold the cexp call again.  */
2619       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2620       return expand_expr (build_call_nary (ctype, call, 1, narg),
2621                           target, VOIDmode, EXPAND_NORMAL);
2622     }
2623
2624   /* Now build the proper return type.  */
2625   return expand_expr (build2 (COMPLEX_EXPR, build_complex_type (type),
2626                               make_tree (TREE_TYPE (arg), op2),
2627                               make_tree (TREE_TYPE (arg), op1)),
2628                       target, VOIDmode, EXPAND_NORMAL);
2629 }
2630
2631 /* Conveniently construct a function call expression.  FNDECL names the
2632    function to be called, N is the number of arguments, and the "..."
2633    parameters are the argument expressions.  Unlike build_call_exr
2634    this doesn't fold the call, hence it will always return a CALL_EXPR.  */
2635
2636 static tree
2637 build_call_nofold_loc (location_t loc, tree fndecl, int n, ...)
2638 {
2639   va_list ap;
2640   tree fntype = TREE_TYPE (fndecl);
2641   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
2642
2643   va_start (ap, n);
2644   fn = build_call_valist (TREE_TYPE (fntype), fn, n, ap);
2645   va_end (ap);
2646   SET_EXPR_LOCATION (fn, loc);
2647   return fn;
2648 }
2649
2650 /* Expand a call to one of the builtin rounding functions gcc defines
2651    as an extension (lfloor and lceil).  As these are gcc extensions we
2652    do not need to worry about setting errno to EDOM.
2653    If expanding via optab fails, lower expression to (int)(floor(x)).
2654    EXP is the expression that is a call to the builtin function;
2655    if convenient, the result should be placed in TARGET.  */
2656
2657 static rtx
2658 expand_builtin_int_roundingfn (tree exp, rtx target)
2659 {
2660   convert_optab builtin_optab;
2661   rtx op0, insns, tmp;
2662   tree fndecl = get_callee_fndecl (exp);
2663   enum built_in_function fallback_fn;
2664   tree fallback_fndecl;
2665   enum machine_mode mode;
2666   tree arg;
2667
2668   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2669     gcc_unreachable ();
2670
2671   arg = CALL_EXPR_ARG (exp, 0);
2672
2673   switch (DECL_FUNCTION_CODE (fndecl))
2674     {
2675     CASE_FLT_FN (BUILT_IN_LCEIL):
2676     CASE_FLT_FN (BUILT_IN_LLCEIL):
2677       builtin_optab = lceil_optab;
2678       fallback_fn = BUILT_IN_CEIL;
2679       break;
2680
2681     CASE_FLT_FN (BUILT_IN_LFLOOR):
2682     CASE_FLT_FN (BUILT_IN_LLFLOOR):
2683       builtin_optab = lfloor_optab;
2684       fallback_fn = BUILT_IN_FLOOR;
2685       break;
2686
2687     default:
2688       gcc_unreachable ();
2689     }
2690
2691   /* Make a suitable register to place result in.  */
2692   mode = TYPE_MODE (TREE_TYPE (exp));
2693
2694   target = gen_reg_rtx (mode);
2695
2696   /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2697      need to expand the argument again.  This way, we will not perform
2698      side-effects more the once.  */
2699   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2700
2701   op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2702
2703   start_sequence ();
2704
2705   /* Compute into TARGET.  */
2706   if (expand_sfix_optab (target, op0, builtin_optab))
2707     {
2708       /* Output the entire sequence.  */
2709       insns = get_insns ();
2710       end_sequence ();
2711       emit_insn (insns);
2712       return target;
2713     }
2714
2715   /* If we were unable to expand via the builtin, stop the sequence
2716      (without outputting the insns).  */
2717   end_sequence ();
2718
2719   /* Fall back to floating point rounding optab.  */
2720   fallback_fndecl = mathfn_built_in (TREE_TYPE (arg), fallback_fn);
2721
2722   /* For non-C99 targets we may end up without a fallback fndecl here
2723      if the user called __builtin_lfloor directly.  In this case emit
2724      a call to the floor/ceil variants nevertheless.  This should result
2725      in the best user experience for not full C99 targets.  */
2726   if (fallback_fndecl == NULL_TREE)
2727     {
2728       tree fntype;
2729       const char *name = NULL;
2730
2731       switch (DECL_FUNCTION_CODE (fndecl))
2732         {
2733         case BUILT_IN_LCEIL:
2734         case BUILT_IN_LLCEIL:
2735           name = "ceil";
2736           break;
2737         case BUILT_IN_LCEILF:
2738         case BUILT_IN_LLCEILF:
2739           name = "ceilf";
2740           break;
2741         case BUILT_IN_LCEILL:
2742         case BUILT_IN_LLCEILL:
2743           name = "ceill";
2744           break;
2745         case BUILT_IN_LFLOOR:
2746         case BUILT_IN_LLFLOOR:
2747           name = "floor";
2748           break;
2749         case BUILT_IN_LFLOORF:
2750         case BUILT_IN_LLFLOORF:
2751           name = "floorf";
2752           break;
2753         case BUILT_IN_LFLOORL:
2754         case BUILT_IN_LLFLOORL:
2755           name = "floorl";
2756           break;
2757         default:
2758           gcc_unreachable ();
2759         }
2760
2761       fntype = build_function_type_list (TREE_TYPE (arg),
2762                                          TREE_TYPE (arg), NULL_TREE);
2763       fallback_fndecl = build_fn_decl (name, fntype);
2764     }
2765
2766   exp = build_call_nofold_loc (EXPR_LOCATION (exp), fallback_fndecl, 1, arg);
2767
2768   tmp = expand_normal (exp);
2769
2770   /* Truncate the result of floating point optab to integer
2771      via expand_fix ().  */
2772   target = gen_reg_rtx (mode);
2773   expand_fix (target, tmp, 0);
2774
2775   return target;
2776 }
2777
2778 /* Expand a call to one of the builtin math functions doing integer
2779    conversion (lrint).
2780    Return 0 if a normal call should be emitted rather than expanding the
2781    function in-line.  EXP is the expression that is a call to the builtin
2782    function; if convenient, the result should be placed in TARGET.  */
2783
2784 static rtx
2785 expand_builtin_int_roundingfn_2 (tree exp, rtx target)
2786 {
2787   convert_optab builtin_optab;
2788   rtx op0, insns;
2789   tree fndecl = get_callee_fndecl (exp);
2790   tree arg;
2791   enum machine_mode mode;
2792
2793   /* There's no easy way to detect the case we need to set EDOM.  */
2794   if (flag_errno_math)
2795     return NULL_RTX;
2796
2797   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2798      gcc_unreachable ();
2799
2800   arg = CALL_EXPR_ARG (exp, 0);
2801
2802   switch (DECL_FUNCTION_CODE (fndecl))
2803     {
2804     CASE_FLT_FN (BUILT_IN_LRINT):
2805     CASE_FLT_FN (BUILT_IN_LLRINT):
2806       builtin_optab = lrint_optab; break;
2807     CASE_FLT_FN (BUILT_IN_LROUND):
2808     CASE_FLT_FN (BUILT_IN_LLROUND):
2809       builtin_optab = lround_optab; break;
2810     default:
2811       gcc_unreachable ();
2812     }
2813
2814   /* Make a suitable register to place result in.  */
2815   mode = TYPE_MODE (TREE_TYPE (exp));
2816
2817   target = gen_reg_rtx (mode);
2818
2819   /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2820      need to expand the argument again.  This way, we will not perform
2821      side-effects more the once.  */
2822   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2823
2824   op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2825
2826   start_sequence ();
2827
2828   if (expand_sfix_optab (target, op0, builtin_optab))
2829     {
2830       /* Output the entire sequence.  */
2831       insns = get_insns ();
2832       end_sequence ();
2833       emit_insn (insns);
2834       return target;
2835     }
2836
2837   /* If we were unable to expand via the builtin, stop the sequence
2838      (without outputting the insns) and call to the library function
2839      with the stabilized argument list.  */
2840   end_sequence ();
2841
2842   target = expand_call (exp, target, target == const0_rtx);
2843
2844   return target;
2845 }
2846
2847 /* Expand a call to the powi built-in mathematical function.  Return NULL_RTX if
2848    a normal call should be emitted rather than expanding the function
2849    in-line.  EXP is the expression that is a call to the builtin
2850    function; if convenient, the result should be placed in TARGET.  */
2851
2852 static rtx
2853 expand_builtin_powi (tree exp, rtx target)
2854 {
2855   tree arg0, arg1;
2856   rtx op0, op1;
2857   enum machine_mode mode;
2858   enum machine_mode mode2;
2859
2860   if (! validate_arglist (exp, REAL_TYPE, INTEGER_TYPE, VOID_TYPE))
2861     return NULL_RTX;
2862
2863   arg0 = CALL_EXPR_ARG (exp, 0);
2864   arg1 = CALL_EXPR_ARG (exp, 1);
2865   mode = TYPE_MODE (TREE_TYPE (exp));
2866
2867   /* Emit a libcall to libgcc.  */
2868
2869   /* Mode of the 2nd argument must match that of an int.  */
2870   mode2 = mode_for_size (INT_TYPE_SIZE, MODE_INT, 0);
2871
2872   if (target == NULL_RTX)
2873     target = gen_reg_rtx (mode);
2874
2875   op0 = expand_expr (arg0, NULL_RTX, mode, EXPAND_NORMAL);
2876   if (GET_MODE (op0) != mode)
2877     op0 = convert_to_mode (mode, op0, 0);
2878   op1 = expand_expr (arg1, NULL_RTX, mode2, EXPAND_NORMAL);
2879   if (GET_MODE (op1) != mode2)
2880     op1 = convert_to_mode (mode2, op1, 0);
2881
2882   target = emit_library_call_value (optab_libfunc (powi_optab, mode),
2883                                     target, LCT_CONST, mode, 2,
2884                                     op0, mode, op1, mode2);
2885
2886   return target;
2887 }
2888
2889 /* Expand expression EXP which is a call to the strlen builtin.  Return
2890    NULL_RTX if we failed the caller should emit a normal call, otherwise
2891    try to get the result in TARGET, if convenient.  */
2892
2893 static rtx
2894 expand_builtin_strlen (tree exp, rtx target,
2895                        enum machine_mode target_mode)
2896 {
2897   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
2898     return NULL_RTX;
2899   else
2900     {
2901       struct expand_operand ops[4];
2902       rtx pat;
2903       tree len;
2904       tree src = CALL_EXPR_ARG (exp, 0);
2905       rtx src_reg, before_strlen;
2906       enum machine_mode insn_mode = target_mode;
2907       enum insn_code icode = CODE_FOR_nothing;
2908       unsigned int align;
2909
2910       /* If the length can be computed at compile-time, return it.  */
2911       len = c_strlen (src, 0);
2912       if (len)
2913         return expand_expr (len, target, target_mode, EXPAND_NORMAL);
2914
2915       /* If the length can be computed at compile-time and is constant
2916          integer, but there are side-effects in src, evaluate
2917          src for side-effects, then return len.
2918          E.g. x = strlen (i++ ? "xfoo" + 1 : "bar");
2919          can be optimized into: i++; x = 3;  */
2920       len = c_strlen (src, 1);
2921       if (len && TREE_CODE (len) == INTEGER_CST)
2922         {
2923           expand_expr (src, const0_rtx, VOIDmode, EXPAND_NORMAL);
2924           return expand_expr (len, target, target_mode, EXPAND_NORMAL);
2925         }
2926
2927       align = get_pointer_alignment (src) / BITS_PER_UNIT;
2928
2929       /* If SRC is not a pointer type, don't do this operation inline.  */
2930       if (align == 0)
2931         return NULL_RTX;
2932
2933       /* Bail out if we can't compute strlen in the right mode.  */
2934       while (insn_mode != VOIDmode)
2935         {
2936           icode = optab_handler (strlen_optab, insn_mode);
2937           if (icode != CODE_FOR_nothing)
2938             break;
2939
2940           insn_mode = GET_MODE_WIDER_MODE (insn_mode);
2941         }
2942       if (insn_mode == VOIDmode)
2943         return NULL_RTX;
2944
2945       /* Make a place to hold the source address.  We will not expand
2946          the actual source until we are sure that the expansion will
2947          not fail -- there are trees that cannot be expanded twice.  */
2948       src_reg = gen_reg_rtx (Pmode);
2949
2950       /* Mark the beginning of the strlen sequence so we can emit the
2951          source operand later.  */
2952       before_strlen = get_last_insn ();
2953
2954       create_output_operand (&ops[0], target, insn_mode);
2955       create_fixed_operand (&ops[1], gen_rtx_MEM (BLKmode, src_reg));
2956       create_integer_operand (&ops[2], 0);
2957       create_integer_operand (&ops[3], align);
2958       if (!maybe_expand_insn (icode, 4, ops))
2959         return NULL_RTX;
2960
2961       /* Now that we are assured of success, expand the source.  */
2962       start_sequence ();
2963       pat = expand_expr (src, src_reg, Pmode, EXPAND_NORMAL);
2964       if (pat != src_reg)
2965         {
2966 #ifdef POINTERS_EXTEND_UNSIGNED
2967           if (GET_MODE (pat) != Pmode)
2968             pat = convert_to_mode (Pmode, pat,
2969                                    POINTERS_EXTEND_UNSIGNED);
2970 #endif
2971           emit_move_insn (src_reg, pat);
2972         }
2973       pat = get_insns ();
2974       end_sequence ();
2975
2976       if (before_strlen)
2977         emit_insn_after (pat, before_strlen);
2978       else
2979         emit_insn_before (pat, get_insns ());
2980
2981       /* Return the value in the proper mode for this function.  */
2982       if (GET_MODE (ops[0].value) == target_mode)
2983         target = ops[0].value;
2984       else if (target != 0)
2985         convert_move (target, ops[0].value, 0);
2986       else
2987         target = convert_to_mode (target_mode, ops[0].value, 0);
2988
2989       return target;
2990     }
2991 }
2992
2993 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
2994    bytes from constant string DATA + OFFSET and return it as target
2995    constant.  */
2996
2997 static rtx
2998 builtin_memcpy_read_str (void *data, HOST_WIDE_INT offset,
2999                          enum machine_mode mode)
3000 {
3001   const char *str = (const char *) data;
3002
3003   gcc_assert (offset >= 0
3004               && ((unsigned HOST_WIDE_INT) offset + GET_MODE_SIZE (mode)
3005                   <= strlen (str) + 1));
3006
3007   return c_readstr (str + offset, mode);
3008 }
3009
3010 /* Expand a call EXP to the memcpy builtin.
3011    Return NULL_RTX if we failed, the caller should emit a normal call,
3012    otherwise try to get the result in TARGET, if convenient (and in
3013    mode MODE if that's convenient).  */
3014
3015 static rtx
3016 expand_builtin_memcpy (tree exp, rtx target)
3017 {
3018   if (!validate_arglist (exp,
3019                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3020     return NULL_RTX;
3021   else
3022     {
3023       tree dest = CALL_EXPR_ARG (exp, 0);
3024       tree src = CALL_EXPR_ARG (exp, 1);
3025       tree len = CALL_EXPR_ARG (exp, 2);
3026       const char *src_str;
3027       unsigned int src_align = get_pointer_alignment (src);
3028       unsigned int dest_align = get_pointer_alignment (dest);
3029       rtx dest_mem, src_mem, dest_addr, len_rtx;
3030       HOST_WIDE_INT expected_size = -1;
3031       unsigned int expected_align = 0;
3032
3033       /* If DEST is not a pointer type, call the normal function.  */
3034       if (dest_align == 0)
3035         return NULL_RTX;
3036
3037       /* If either SRC is not a pointer type, don't do this
3038          operation in-line.  */
3039       if (src_align == 0)
3040         return NULL_RTX;
3041
3042       if (currently_expanding_gimple_stmt)
3043         stringop_block_profile (currently_expanding_gimple_stmt,
3044                                 &expected_align, &expected_size);
3045
3046       if (expected_align < dest_align)
3047         expected_align = dest_align;
3048       dest_mem = get_memory_rtx (dest, len);
3049       set_mem_align (dest_mem, dest_align);
3050       len_rtx = expand_normal (len);
3051       src_str = c_getstr (src);
3052
3053       /* If SRC is a string constant and block move would be done
3054          by pieces, we can avoid loading the string from memory
3055          and only stored the computed constants.  */
3056       if (src_str
3057           && CONST_INT_P (len_rtx)
3058           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
3059           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
3060                                   CONST_CAST (char *, src_str),
3061                                   dest_align, false))
3062         {
3063           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
3064                                       builtin_memcpy_read_str,
3065                                       CONST_CAST (char *, src_str),
3066                                       dest_align, false, 0);
3067           dest_mem = force_operand (XEXP (dest_mem, 0), target);
3068           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3069           return dest_mem;
3070         }
3071
3072       src_mem = get_memory_rtx (src, len);
3073       set_mem_align (src_mem, src_align);
3074
3075       /* Copy word part most expediently.  */
3076       dest_addr = emit_block_move_hints (dest_mem, src_mem, len_rtx,
3077                                          CALL_EXPR_TAILCALL (exp)
3078                                          ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
3079                                          expected_align, expected_size);
3080
3081       if (dest_addr == 0)
3082         {
3083           dest_addr = force_operand (XEXP (dest_mem, 0), target);
3084           dest_addr = convert_memory_address (ptr_mode, dest_addr);
3085         }
3086       return dest_addr;
3087     }
3088 }
3089
3090 /* Expand a call EXP to the mempcpy builtin.
3091    Return NULL_RTX if we failed; the caller should emit a normal call,
3092    otherwise try to get the result in TARGET, if convenient (and in
3093    mode MODE if that's convenient).  If ENDP is 0 return the
3094    destination pointer, if ENDP is 1 return the end pointer ala
3095    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3096    stpcpy.  */
3097
3098 static rtx
3099 expand_builtin_mempcpy (tree exp, rtx target, enum machine_mode mode)
3100 {
3101   if (!validate_arglist (exp,
3102                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3103     return NULL_RTX;
3104   else
3105     {
3106       tree dest = CALL_EXPR_ARG (exp, 0);
3107       tree src = CALL_EXPR_ARG (exp, 1);
3108       tree len = CALL_EXPR_ARG (exp, 2);
3109       return expand_builtin_mempcpy_args (dest, src, len,
3110                                           target, mode, /*endp=*/ 1);
3111     }
3112 }
3113
3114 /* Helper function to do the actual work for expand_builtin_mempcpy.  The
3115    arguments to the builtin_mempcpy call DEST, SRC, and LEN are broken out
3116    so that this can also be called without constructing an actual CALL_EXPR.
3117    The other arguments and return value are the same as for
3118    expand_builtin_mempcpy.  */
3119
3120 static rtx
3121 expand_builtin_mempcpy_args (tree dest, tree src, tree len,
3122                              rtx target, enum machine_mode mode, int endp)
3123 {
3124     /* If return value is ignored, transform mempcpy into memcpy.  */
3125   if (target == const0_rtx && implicit_built_in_decls[BUILT_IN_MEMCPY])
3126     {
3127       tree fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
3128       tree result = build_call_nofold_loc (UNKNOWN_LOCATION, fn, 3,
3129                                            dest, src, len);
3130       return expand_expr (result, target, mode, EXPAND_NORMAL);
3131     }
3132   else
3133     {
3134       const char *src_str;
3135       unsigned int src_align = get_pointer_alignment (src);
3136       unsigned int dest_align = get_pointer_alignment (dest);
3137       rtx dest_mem, src_mem, len_rtx;
3138
3139       /* If either SRC or DEST is not a pointer type, don't do this
3140          operation in-line.  */
3141       if (dest_align == 0 || src_align == 0)
3142         return NULL_RTX;
3143
3144       /* If LEN is not constant, call the normal function.  */
3145       if (! host_integerp (len, 1))
3146         return NULL_RTX;
3147
3148       len_rtx = expand_normal (len);
3149       src_str = c_getstr (src);
3150
3151       /* If SRC is a string constant and block move would be done
3152          by pieces, we can avoid loading the string from memory
3153          and only stored the computed constants.  */
3154       if (src_str
3155           && CONST_INT_P (len_rtx)
3156           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
3157           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
3158                                   CONST_CAST (char *, src_str),
3159                                   dest_align, false))
3160         {
3161           dest_mem = get_memory_rtx (dest, len);
3162           set_mem_align (dest_mem, dest_align);
3163           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
3164                                       builtin_memcpy_read_str,
3165                                       CONST_CAST (char *, src_str),
3166                                       dest_align, false, endp);
3167           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3168           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3169           return dest_mem;
3170         }
3171
3172       if (CONST_INT_P (len_rtx)
3173           && can_move_by_pieces (INTVAL (len_rtx),
3174                                  MIN (dest_align, src_align)))
3175         {
3176           dest_mem = get_memory_rtx (dest, len);
3177           set_mem_align (dest_mem, dest_align);
3178           src_mem = get_memory_rtx (src, len);
3179           set_mem_align (src_mem, src_align);
3180           dest_mem = move_by_pieces (dest_mem, src_mem, INTVAL (len_rtx),
3181                                      MIN (dest_align, src_align), endp);
3182           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3183           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3184           return dest_mem;
3185         }
3186
3187       return NULL_RTX;
3188     }
3189 }
3190
3191 #ifndef HAVE_movstr
3192 # define HAVE_movstr 0
3193 # define CODE_FOR_movstr CODE_FOR_nothing
3194 #endif
3195
3196 /* Expand into a movstr instruction, if one is available.  Return NULL_RTX if
3197    we failed, the caller should emit a normal call, otherwise try to
3198    get the result in TARGET, if convenient.  If ENDP is 0 return the
3199    destination pointer, if ENDP is 1 return the end pointer ala
3200    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3201    stpcpy.  */
3202
3203 static rtx
3204 expand_movstr (tree dest, tree src, rtx target, int endp)
3205 {
3206   struct expand_operand ops[3];
3207   rtx dest_mem;
3208   rtx src_mem;
3209
3210   if (!HAVE_movstr)
3211     return NULL_RTX;
3212
3213   dest_mem = get_memory_rtx (dest, NULL);
3214   src_mem = get_memory_rtx (src, NULL);
3215   if (!endp)
3216     {
3217       target = force_reg (Pmode, XEXP (dest_mem, 0));
3218       dest_mem = replace_equiv_address (dest_mem, target);
3219     }
3220
3221   create_output_operand (&ops[0], endp ? target : NULL_RTX, Pmode);
3222   create_fixed_operand (&ops[1], dest_mem);
3223   create_fixed_operand (&ops[2], src_mem);
3224   expand_insn (CODE_FOR_movstr, 3, ops);
3225
3226   if (endp && target != const0_rtx)
3227     {
3228       target = ops[0].value;
3229       /* movstr is supposed to set end to the address of the NUL
3230          terminator.  If the caller requested a mempcpy-like return value,
3231          adjust it.  */
3232       if (endp == 1)
3233         {
3234           rtx tem = plus_constant (gen_lowpart (GET_MODE (target), target), 1);
3235           emit_move_insn (target, force_operand (tem, NULL_RTX));
3236         }
3237     }
3238   return target;
3239 }
3240
3241 /* Expand expression EXP, which is a call to the strcpy builtin.  Return
3242    NULL_RTX if we failed the caller should emit a normal call, otherwise
3243    try to get the result in TARGET, if convenient (and in mode MODE if that's
3244    convenient).  */
3245
3246 static rtx
3247 expand_builtin_strcpy (tree exp, rtx target)
3248 {
3249   if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3250    {
3251      tree dest = CALL_EXPR_ARG (exp, 0);
3252      tree src = CALL_EXPR_ARG (exp, 1);
3253      return expand_builtin_strcpy_args (dest, src, target);
3254    }
3255    return NULL_RTX;
3256 }
3257
3258 /* Helper function to do the actual work for expand_builtin_strcpy.  The
3259    arguments to the builtin_strcpy call DEST and SRC are broken out
3260    so that this can also be called without constructing an actual CALL_EXPR.
3261    The other arguments and return value are the same as for
3262    expand_builtin_strcpy.  */
3263
3264 static rtx
3265 expand_builtin_strcpy_args (tree dest, tree src, rtx target)
3266 {
3267   return expand_movstr (dest, src, target, /*endp=*/0);
3268 }
3269
3270 /* Expand a call EXP to the stpcpy builtin.
3271    Return NULL_RTX if we failed the caller should emit a normal call,
3272    otherwise try to get the result in TARGET, if convenient (and in
3273    mode MODE if that's convenient).  */
3274
3275 static rtx
3276 expand_builtin_stpcpy (tree exp, rtx target, enum machine_mode mode)
3277 {
3278   tree dst, src;
3279   location_t loc = EXPR_LOCATION (exp);
3280
3281   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3282     return NULL_RTX;
3283
3284   dst = CALL_EXPR_ARG (exp, 0);
3285   src = CALL_EXPR_ARG (exp, 1);
3286
3287   /* If return value is ignored, transform stpcpy into strcpy.  */
3288   if (target == const0_rtx && implicit_built_in_decls[BUILT_IN_STRCPY])
3289     {
3290       tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
3291       tree result = build_call_nofold_loc (loc, fn, 2, dst, src);
3292       return expand_expr (result, target, mode, EXPAND_NORMAL);
3293     }
3294   else
3295     {
3296       tree len, lenp1;
3297       rtx ret;
3298
3299       /* Ensure we get an actual string whose length can be evaluated at
3300          compile-time, not an expression containing a string.  This is
3301          because the latter will potentially produce pessimized code
3302          when used to produce the return value.  */
3303       if (! c_getstr (src) || ! (len = c_strlen (src, 0)))
3304         return expand_movstr (dst, src, target, /*endp=*/2);
3305
3306       lenp1 = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
3307       ret = expand_builtin_mempcpy_args (dst, src, lenp1,
3308                                          target, mode, /*endp=*/2);
3309
3310       if (ret)
3311         return ret;
3312
3313       if (TREE_CODE (len) == INTEGER_CST)
3314         {
3315           rtx len_rtx = expand_normal (len);
3316
3317           if (CONST_INT_P (len_rtx))
3318             {
3319               ret = expand_builtin_strcpy_args (dst, src, target);
3320
3321               if (ret)
3322                 {
3323                   if (! target)
3324                     {
3325                       if (mode != VOIDmode)
3326                         target = gen_reg_rtx (mode);
3327                       else
3328                         target = gen_reg_rtx (GET_MODE (ret));
3329                     }
3330                   if (GET_MODE (target) != GET_MODE (ret))
3331                     ret = gen_lowpart (GET_MODE (target), ret);
3332
3333                   ret = plus_constant (ret, INTVAL (len_rtx));
3334                   ret = emit_move_insn (target, force_operand (ret, NULL_RTX));
3335                   gcc_assert (ret);
3336
3337                   return target;
3338                 }
3339             }
3340         }
3341
3342       return expand_movstr (dst, src, target, /*endp=*/2);
3343     }
3344 }
3345
3346 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3347    bytes from constant string DATA + OFFSET and return it as target
3348    constant.  */
3349
3350 rtx
3351 builtin_strncpy_read_str (void *data, HOST_WIDE_INT offset,
3352                           enum machine_mode mode)
3353 {
3354   const char *str = (const char *) data;
3355
3356   if ((unsigned HOST_WIDE_INT) offset > strlen (str))
3357     return const0_rtx;
3358
3359   return c_readstr (str + offset, mode);
3360 }
3361
3362 /* Expand expression EXP, which is a call to the strncpy builtin.  Return
3363    NULL_RTX if we failed the caller should emit a normal call.  */
3364
3365 static rtx
3366 expand_builtin_strncpy (tree exp, rtx target)
3367 {
3368   location_t loc = EXPR_LOCATION (exp);
3369
3370   if (validate_arglist (exp,
3371                         POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3372     {
3373       tree dest = CALL_EXPR_ARG (exp, 0);
3374       tree src = CALL_EXPR_ARG (exp, 1);
3375       tree len = CALL_EXPR_ARG (exp, 2);
3376       tree slen = c_strlen (src, 1);
3377
3378       /* We must be passed a constant len and src parameter.  */
3379       if (!host_integerp (len, 1) || !slen || !host_integerp (slen, 1))
3380         return NULL_RTX;
3381
3382       slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
3383
3384       /* We're required to pad with trailing zeros if the requested
3385          len is greater than strlen(s2)+1.  In that case try to
3386          use store_by_pieces, if it fails, punt.  */
3387       if (tree_int_cst_lt (slen, len))
3388         {
3389           unsigned int dest_align = get_pointer_alignment (dest);
3390           const char *p = c_getstr (src);
3391           rtx dest_mem;
3392
3393           if (!p || dest_align == 0 || !host_integerp (len, 1)
3394               || !can_store_by_pieces (tree_low_cst (len, 1),
3395                                        builtin_strncpy_read_str,
3396                                        CONST_CAST (char *, p),
3397                                        dest_align, false))
3398             return NULL_RTX;
3399
3400           dest_mem = get_memory_rtx (dest, len);
3401           store_by_pieces (dest_mem, tree_low_cst (len, 1),
3402                            builtin_strncpy_read_str,
3403                            CONST_CAST (char *, p), dest_align, false, 0);
3404           dest_mem = force_operand (XEXP (dest_mem, 0), target);
3405           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3406           return dest_mem;
3407         }
3408     }
3409   return NULL_RTX;
3410 }
3411
3412 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3413    bytes from constant string DATA + OFFSET and return it as target
3414    constant.  */
3415
3416 rtx
3417 builtin_memset_read_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3418                          enum machine_mode mode)
3419 {
3420   const char *c = (const char *) data;
3421   char *p = XALLOCAVEC (char, GET_MODE_SIZE (mode));
3422
3423   memset (p, *c, GET_MODE_SIZE (mode));
3424
3425   return c_readstr (p, mode);
3426 }
3427
3428 /* Callback routine for store_by_pieces.  Return the RTL of a register
3429    containing GET_MODE_SIZE (MODE) consecutive copies of the unsigned
3430    char value given in the RTL register data.  For example, if mode is
3431    4 bytes wide, return the RTL for 0x01010101*data.  */
3432
3433 static rtx
3434 builtin_memset_gen_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3435                         enum machine_mode mode)
3436 {
3437   rtx target, coeff;
3438   size_t size;
3439   char *p;
3440
3441   size = GET_MODE_SIZE (mode);
3442   if (size == 1)
3443     return (rtx) data;
3444
3445   p = XALLOCAVEC (char, size);
3446   memset (p, 1, size);
3447   coeff = c_readstr (p, mode);
3448
3449   target = convert_to_mode (mode, (rtx) data, 1);
3450   target = expand_mult (mode, target, coeff, NULL_RTX, 1);
3451   return force_reg (mode, target);
3452 }
3453
3454 /* Expand expression EXP, which is a call to the memset builtin.  Return
3455    NULL_RTX if we failed the caller should emit a normal call, otherwise
3456    try to get the result in TARGET, if convenient (and in mode MODE if that's
3457    convenient).  */
3458
3459 static rtx
3460 expand_builtin_memset (tree exp, rtx target, enum machine_mode mode)
3461 {
3462   if (!validate_arglist (exp,
3463                          POINTER_TYPE, INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
3464     return NULL_RTX;
3465   else
3466     {
3467       tree dest = CALL_EXPR_ARG (exp, 0);
3468       tree val = CALL_EXPR_ARG (exp, 1);
3469       tree len = CALL_EXPR_ARG (exp, 2);
3470       return expand_builtin_memset_args (dest, val, len, target, mode, exp);
3471     }
3472 }
3473
3474 /* Helper function to do the actual work for expand_builtin_memset.  The
3475    arguments to the builtin_memset call DEST, VAL, and LEN are broken out
3476    so that this can also be called without constructing an actual CALL_EXPR.
3477    The other arguments and return value are the same as for
3478    expand_builtin_memset.  */
3479
3480 static rtx
3481 expand_builtin_memset_args (tree dest, tree val, tree len,
3482                             rtx target, enum machine_mode mode, tree orig_exp)
3483 {
3484   tree fndecl, fn;
3485   enum built_in_function fcode;
3486   enum machine_mode val_mode;
3487   char c;
3488   unsigned int dest_align;
3489   rtx dest_mem, dest_addr, len_rtx;
3490   HOST_WIDE_INT expected_size = -1;
3491   unsigned int expected_align = 0;
3492
3493   dest_align = get_pointer_alignment (dest);
3494
3495   /* If DEST is not a pointer type, don't do this operation in-line.  */
3496   if (dest_align == 0)
3497     return NULL_RTX;
3498
3499   if (currently_expanding_gimple_stmt)
3500     stringop_block_profile (currently_expanding_gimple_stmt,
3501                             &expected_align, &expected_size);
3502
3503   if (expected_align < dest_align)
3504     expected_align = dest_align;
3505
3506   /* If the LEN parameter is zero, return DEST.  */
3507   if (integer_zerop (len))
3508     {
3509       /* Evaluate and ignore VAL in case it has side-effects.  */
3510       expand_expr (val, const0_rtx, VOIDmode, EXPAND_NORMAL);
3511       return expand_expr (dest, target, mode, EXPAND_NORMAL);
3512     }
3513
3514   /* Stabilize the arguments in case we fail.  */
3515   dest = builtin_save_expr (dest);
3516   val = builtin_save_expr (val);
3517   len = builtin_save_expr (len);
3518
3519   len_rtx = expand_normal (len);
3520   dest_mem = get_memory_rtx (dest, len);
3521   val_mode = TYPE_MODE (unsigned_char_type_node);
3522
3523   if (TREE_CODE (val) != INTEGER_CST)
3524     {
3525       rtx val_rtx;
3526
3527       val_rtx = expand_normal (val);
3528       val_rtx = convert_to_mode (val_mode, val_rtx, 0);
3529
3530       /* Assume that we can memset by pieces if we can store
3531        * the coefficients by pieces (in the required modes).
3532        * We can't pass builtin_memset_gen_str as that emits RTL.  */
3533       c = 1;
3534       if (host_integerp (len, 1)
3535           && can_store_by_pieces (tree_low_cst (len, 1),
3536                                   builtin_memset_read_str, &c, dest_align,
3537                                   true))
3538         {
3539           val_rtx = force_reg (val_mode, val_rtx);
3540           store_by_pieces (dest_mem, tree_low_cst (len, 1),
3541                            builtin_memset_gen_str, val_rtx, dest_align,
3542                            true, 0);
3543         }
3544       else if (!set_storage_via_setmem (dest_mem, len_rtx, val_rtx,
3545                                         dest_align, expected_align,
3546                                         expected_size))
3547         goto do_libcall;
3548
3549       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3550       dest_mem = convert_memory_address (ptr_mode, dest_mem);
3551       return dest_mem;
3552     }
3553
3554   if (target_char_cast (val, &c))
3555     goto do_libcall;
3556
3557   if (c)
3558     {
3559       if (host_integerp (len, 1)
3560           && can_store_by_pieces (tree_low_cst (len, 1),
3561                                   builtin_memset_read_str, &c, dest_align,
3562                                   true))
3563         store_by_pieces (dest_mem, tree_low_cst (len, 1),
3564                          builtin_memset_read_str, &c, dest_align, true, 0);
3565       else if (!set_storage_via_setmem (dest_mem, len_rtx,
3566                                         gen_int_mode (c, val_mode),
3567                                         dest_align, expected_align,
3568                                         expected_size))
3569         goto do_libcall;
3570
3571       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3572       dest_mem = convert_memory_address (ptr_mode, dest_mem);
3573       return dest_mem;
3574     }
3575
3576   set_mem_align (dest_mem, dest_align);
3577   dest_addr = clear_storage_hints (dest_mem, len_rtx,
3578                                    CALL_EXPR_TAILCALL (orig_exp)
3579                                    ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
3580                                    expected_align, expected_size);
3581
3582   if (dest_addr == 0)
3583     {
3584       dest_addr = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3585       dest_addr = convert_memory_address (ptr_mode, dest_addr);
3586     }
3587
3588   return dest_addr;
3589
3590  do_libcall:
3591   fndecl = get_callee_fndecl (orig_exp);
3592   fcode = DECL_FUNCTION_CODE (fndecl);
3593   if (fcode == BUILT_IN_MEMSET)
3594     fn = build_call_nofold_loc (EXPR_LOCATION (orig_exp), fndecl, 3,
3595                                 dest, val, len);
3596   else if (fcode == BUILT_IN_BZERO)
3597     fn = build_call_nofold_loc (EXPR_LOCATION (orig_exp), fndecl, 2,
3598                                 dest, len);
3599   else
3600     gcc_unreachable ();
3601   gcc_assert (TREE_CODE (fn) == CALL_EXPR);
3602   CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (orig_exp);
3603   return expand_call (fn, target, target == const0_rtx);
3604 }
3605
3606 /* Expand expression EXP, which is a call to the bzero builtin.  Return
3607    NULL_RTX if we failed the caller should emit a normal call.  */
3608
3609 static rtx
3610 expand_builtin_bzero (tree exp)
3611 {
3612   tree dest, size;
3613   location_t loc = EXPR_LOCATION (exp);
3614
3615   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3616     return NULL_RTX;
3617
3618   dest = CALL_EXPR_ARG (exp, 0);
3619   size = CALL_EXPR_ARG (exp, 1);
3620
3621   /* New argument list transforming bzero(ptr x, int y) to
3622      memset(ptr x, int 0, size_t y).   This is done this way
3623      so that if it isn't expanded inline, we fallback to
3624      calling bzero instead of memset.  */
3625
3626   return expand_builtin_memset_args (dest, integer_zero_node,
3627                                      fold_convert_loc (loc, sizetype, size),
3628                                      const0_rtx, VOIDmode, exp);
3629 }
3630
3631 /* Expand expression EXP, which is a call to the memcmp built-in function.
3632    Return NULL_RTX if we failed and the
3633    caller should emit a normal call, otherwise try to get the result in
3634    TARGET, if convenient (and in mode MODE, if that's convenient).  */
3635
3636 static rtx
3637 expand_builtin_memcmp (tree exp, ATTRIBUTE_UNUSED rtx target,
3638                        ATTRIBUTE_UNUSED enum machine_mode mode)
3639 {
3640   location_t loc ATTRIBUTE_UNUSED = EXPR_LOCATION (exp);
3641
3642   if (!validate_arglist (exp,
3643                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3644     return NULL_RTX;
3645
3646 #if defined HAVE_cmpmemsi || defined HAVE_cmpstrnsi
3647   {
3648     rtx arg1_rtx, arg2_rtx, arg3_rtx;
3649     rtx result;
3650     rtx insn;
3651     tree arg1 = CALL_EXPR_ARG (exp, 0);
3652     tree arg2 = CALL_EXPR_ARG (exp, 1);
3653     tree len = CALL_EXPR_ARG (exp, 2);
3654
3655     unsigned int arg1_align = get_pointer_alignment (arg1) / BITS_PER_UNIT;
3656     unsigned int arg2_align = get_pointer_alignment (arg2) / BITS_PER_UNIT;
3657     enum machine_mode insn_mode;
3658
3659 #ifdef HAVE_cmpmemsi
3660     if (HAVE_cmpmemsi)
3661       insn_mode = insn_data[(int) CODE_FOR_cmpmemsi].operand[0].mode;
3662     else
3663 #endif
3664 #ifdef HAVE_cmpstrnsi
3665     if (HAVE_cmpstrnsi)
3666       insn_mode = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
3667     else
3668 #endif
3669       return NULL_RTX;
3670
3671     /* If we don't have POINTER_TYPE, call the function.  */
3672     if (arg1_align == 0 || arg2_align == 0)
3673       return NULL_RTX;
3674
3675     /* Make a place to write the result of the instruction.  */
3676     result = target;
3677     if (! (result != 0
3678            && REG_P (result) && GET_MODE (result) == insn_mode
3679            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3680       result = gen_reg_rtx (insn_mode);
3681
3682     arg1_rtx = get_memory_rtx (arg1, len);
3683     arg2_rtx = get_memory_rtx (arg2, len);
3684     arg3_rtx = expand_normal (fold_convert_loc (loc, sizetype, len));
3685
3686     /* Set MEM_SIZE as appropriate.  */
3687     if (CONST_INT_P (arg3_rtx))
3688       {
3689         set_mem_size (arg1_rtx, INTVAL (arg3_rtx));
3690         set_mem_size (arg2_rtx, INTVAL (arg3_rtx));
3691       }
3692
3693 #ifdef HAVE_cmpmemsi
3694     if (HAVE_cmpmemsi)
3695       insn = gen_cmpmemsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3696                            GEN_INT (MIN (arg1_align, arg2_align)));
3697     else
3698 #endif
3699 #ifdef HAVE_cmpstrnsi
3700     if (HAVE_cmpstrnsi)
3701       insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3702                             GEN_INT (MIN (arg1_align, arg2_align)));
3703     else
3704 #endif
3705       gcc_unreachable ();
3706
3707     if (insn)
3708       emit_insn (insn);
3709     else
3710       emit_library_call_value (memcmp_libfunc, result, LCT_PURE,
3711                                TYPE_MODE (integer_type_node), 3,
3712                                XEXP (arg1_rtx, 0), Pmode,
3713                                XEXP (arg2_rtx, 0), Pmode,
3714                                convert_to_mode (TYPE_MODE (sizetype), arg3_rtx,
3715                                                 TYPE_UNSIGNED (sizetype)),
3716                                TYPE_MODE (sizetype));
3717
3718     /* Return the value in the proper mode for this function.  */
3719     mode = TYPE_MODE (TREE_TYPE (exp));
3720     if (GET_MODE (result) == mode)
3721       return result;
3722     else if (target != 0)
3723       {
3724         convert_move (target, result, 0);
3725         return target;
3726       }
3727     else
3728       return convert_to_mode (mode, result, 0);
3729   }
3730 #endif
3731
3732   return NULL_RTX;
3733 }
3734
3735 /* Expand expression EXP, which is a call to the strcmp builtin.  Return NULL_RTX
3736    if we failed the caller should emit a normal call, otherwise try to get
3737    the result in TARGET, if convenient.  */
3738
3739 static rtx
3740 expand_builtin_strcmp (tree exp, ATTRIBUTE_UNUSED rtx target)
3741 {
3742   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3743     return NULL_RTX;
3744
3745 #if defined HAVE_cmpstrsi || defined HAVE_cmpstrnsi
3746   if (direct_optab_handler (cmpstr_optab, SImode) != CODE_FOR_nothing
3747       || direct_optab_handler (cmpstrn_optab, SImode) != CODE_FOR_nothing)
3748     {
3749       rtx arg1_rtx, arg2_rtx;
3750       rtx result, insn = NULL_RTX;
3751       tree fndecl, fn;
3752       tree arg1 = CALL_EXPR_ARG (exp, 0);
3753       tree arg2 = CALL_EXPR_ARG (exp, 1);
3754
3755       unsigned int arg1_align = get_pointer_alignment (arg1) / BITS_PER_UNIT;
3756       unsigned int arg2_align = get_pointer_alignment (arg2) / BITS_PER_UNIT;
3757
3758       /* If we don't have POINTER_TYPE, call the function.  */
3759       if (arg1_align == 0 || arg2_align == 0)
3760         return NULL_RTX;
3761
3762       /* Stabilize the arguments in case gen_cmpstr(n)si fail.  */
3763       arg1 = builtin_save_expr (arg1);
3764       arg2 = builtin_save_expr (arg2);
3765
3766       arg1_rtx = get_memory_rtx (arg1, NULL);
3767       arg2_rtx = get_memory_rtx (arg2, NULL);
3768
3769 #ifdef HAVE_cmpstrsi
3770       /* Try to call cmpstrsi.  */
3771       if (HAVE_cmpstrsi)
3772         {
3773           enum machine_mode insn_mode
3774             = insn_data[(int) CODE_FOR_cmpstrsi].operand[0].mode;
3775
3776           /* Make a place to write the result of the instruction.  */
3777           result = target;
3778           if (! (result != 0
3779                  && REG_P (result) && GET_MODE (result) == insn_mode
3780                  && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3781             result = gen_reg_rtx (insn_mode);
3782
3783           insn = gen_cmpstrsi (result, arg1_rtx, arg2_rtx,
3784                                GEN_INT (MIN (arg1_align, arg2_align)));
3785         }
3786 #endif
3787 #ifdef HAVE_cmpstrnsi
3788       /* Try to determine at least one length and call cmpstrnsi.  */
3789       if (!insn && HAVE_cmpstrnsi)
3790         {
3791           tree len;
3792           rtx arg3_rtx;
3793
3794           enum machine_mode insn_mode
3795             = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
3796           tree len1 = c_strlen (arg1, 1);
3797           tree len2 = c_strlen (arg2, 1);
3798
3799           if (len1)
3800             len1 = size_binop (PLUS_EXPR, ssize_int (1), len1);
3801           if (len2)
3802             len2 = size_binop (PLUS_EXPR, ssize_int (1), len2);
3803
3804           /* If we don't have a constant length for the first, use the length
3805              of the second, if we know it.  We don't require a constant for
3806              this case; some cost analysis could be done if both are available
3807              but neither is constant.  For now, assume they're equally cheap,
3808              unless one has side effects.  If both strings have constant lengths,
3809              use the smaller.  */
3810
3811           if (!len1)
3812             len = len2;
3813           else if (!len2)
3814             len = len1;
3815           else if (TREE_SIDE_EFFECTS (len1))
3816             len = len2;
3817           else if (TREE_SIDE_EFFECTS (len2))
3818             len = len1;
3819           else if (TREE_CODE (len1) != INTEGER_CST)
3820             len = len2;
3821           else if (TREE_CODE (len2) != INTEGER_CST)
3822             len = len1;
3823           else if (tree_int_cst_lt (len1, len2))
3824             len = len1;
3825           else
3826             len = len2;
3827
3828           /* If both arguments have side effects, we cannot optimize.  */
3829           if (!len || TREE_SIDE_EFFECTS (len))
3830             goto do_libcall;
3831
3832           arg3_rtx = expand_normal (len);
3833
3834           /* Make a place to write the result of the instruction.  */
3835           result = target;
3836           if (! (result != 0
3837                  && REG_P (result) && GET_MODE (result) == insn_mode
3838                  && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3839             result = gen_reg_rtx (insn_mode);
3840
3841           insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3842                                 GEN_INT (MIN (arg1_align, arg2_align)));
3843         }
3844 #endif
3845
3846       if (insn)
3847         {
3848           enum machine_mode mode;
3849           emit_insn (insn);
3850
3851           /* Return the value in the proper mode for this function.  */
3852           mode = TYPE_MODE (TREE_TYPE (exp));
3853           if (GET_MODE (result) == mode)
3854             return result;
3855           if (target == 0)
3856             return convert_to_mode (mode, result, 0);
3857           convert_move (target, result, 0);
3858           return target;
3859         }
3860
3861       /* Expand the library call ourselves using a stabilized argument
3862          list to avoid re-evaluating the function's arguments twice.  */
3863 #ifdef HAVE_cmpstrnsi
3864     do_libcall:
3865 #endif
3866       fndecl = get_callee_fndecl (exp);
3867       fn = build_call_nofold_loc (EXPR_LOCATION (exp), fndecl, 2, arg1, arg2);
3868       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
3869       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
3870       return expand_call (fn, target, target == const0_rtx);
3871     }
3872 #endif
3873   return NULL_RTX;
3874 }
3875
3876 /* Expand expression EXP, which is a call to the strncmp builtin. Return
3877    NULL_RTX if we failed the caller should emit a normal call, otherwise try to get
3878    the result in TARGET, if convenient.  */
3879
3880 static rtx
3881 expand_builtin_strncmp (tree exp, ATTRIBUTE_UNUSED rtx target,
3882                         ATTRIBUTE_UNUSED enum machine_mode mode)
3883 {
3884   location_t loc ATTRIBUTE_UNUSED = EXPR_LOCATION (exp);
3885
3886   if (!validate_arglist (exp,
3887                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3888     return NULL_RTX;
3889
3890   /* If c_strlen can determine an expression for one of the string
3891      lengths, and it doesn't have side effects, then emit cmpstrnsi
3892      using length MIN(strlen(string)+1, arg3).  */
3893 #ifdef HAVE_cmpstrnsi
3894   if (HAVE_cmpstrnsi)
3895   {
3896     tree len, len1, len2;
3897     rtx arg1_rtx, arg2_rtx, arg3_rtx;
3898     rtx result, insn;
3899     tree fndecl, fn;
3900     tree arg1 = CALL_EXPR_ARG (exp, 0);
3901     tree arg2 = CALL_EXPR_ARG (exp, 1);
3902     tree arg3 = CALL_EXPR_ARG (exp, 2);
3903
3904     unsigned int arg1_align = get_pointer_alignment (arg1) / BITS_PER_UNIT;
3905     unsigned int arg2_align = get_pointer_alignment (arg2) / BITS_PER_UNIT;
3906     enum machine_mode insn_mode
3907       = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
3908
3909     len1 = c_strlen (arg1, 1);
3910     len2 = c_strlen (arg2, 1);
3911
3912     if (len1)
3913       len1 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len1);
3914     if (len2)
3915       len2 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len2);
3916
3917     /* If we don't have a constant length for the first, use the length
3918        of the second, if we know it.  We don't require a constant for
3919        this case; some cost analysis could be done if both are available
3920        but neither is constant.  For now, assume they're equally cheap,
3921        unless one has side effects.  If both strings have constant lengths,
3922        use the smaller.  */
3923
3924     if (!len1)
3925       len = len2;
3926     else if (!len2)
3927       len = len1;
3928     else if (TREE_SIDE_EFFECTS (len1))
3929       len = len2;
3930     else if (TREE_SIDE_EFFECTS (len2))
3931       len = len1;
3932     else if (TREE_CODE (len1) != INTEGER_CST)
3933       len = len2;
3934     else if (TREE_CODE (len2) != INTEGER_CST)
3935       len = len1;
3936     else if (tree_int_cst_lt (len1, len2))
3937       len = len1;
3938     else
3939       len = len2;
3940
3941     /* If both arguments have side effects, we cannot optimize.  */
3942     if (!len || TREE_SIDE_EFFECTS (len))
3943       return NULL_RTX;
3944
3945     /* The actual new length parameter is MIN(len,arg3).  */
3946     len = fold_build2_loc (loc, MIN_EXPR, TREE_TYPE (len), len,
3947                        fold_convert_loc (loc, TREE_TYPE (len), arg3));
3948
3949     /* If we don't have POINTER_TYPE, call the function.  */
3950     if (arg1_align == 0 || arg2_align == 0)
3951       return NULL_RTX;
3952
3953     /* Make a place to write the result of the instruction.  */
3954     result = target;
3955     if (! (result != 0
3956            && REG_P (result) && GET_MODE (result) == insn_mode
3957            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3958       result = gen_reg_rtx (insn_mode);
3959
3960     /* Stabilize the arguments in case gen_cmpstrnsi fails.  */
3961     arg1 = builtin_save_expr (arg1);
3962     arg2 = builtin_save_expr (arg2);
3963     len = builtin_save_expr (len);
3964
3965     arg1_rtx = get_memory_rtx (arg1, len);
3966     arg2_rtx = get_memory_rtx (arg2, len);
3967     arg3_rtx = expand_normal (len);
3968     insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3969                           GEN_INT (MIN (arg1_align, arg2_align)));
3970     if (insn)
3971       {
3972         emit_insn (insn);
3973
3974         /* Return the value in the proper mode for this function.  */
3975         mode = TYPE_MODE (TREE_TYPE (exp));
3976         if (GET_MODE (result) == mode)
3977           return result;
3978         if (target == 0)
3979           return convert_to_mode (mode, result, 0);
3980         convert_move (target, result, 0);
3981         return target;
3982       }
3983
3984     /* Expand the library call ourselves using a stabilized argument
3985        list to avoid re-evaluating the function's arguments twice.  */
3986     fndecl = get_callee_fndecl (exp);
3987     fn = build_call_nofold_loc (EXPR_LOCATION (exp), fndecl, 3,
3988                                 arg1, arg2, len);
3989     gcc_assert (TREE_CODE (fn) == CALL_EXPR);
3990     CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
3991     return expand_call (fn, target, target == const0_rtx);
3992   }
3993 #endif
3994   return NULL_RTX;
3995 }
3996
3997 /* Expand a call to __builtin_saveregs, generating the result in TARGET,
3998    if that's convenient.  */
3999
4000 rtx
4001 expand_builtin_saveregs (void)
4002 {
4003   rtx val, seq;
4004
4005   /* Don't do __builtin_saveregs more than once in a function.
4006      Save the result of the first call and reuse it.  */
4007   if (saveregs_value != 0)
4008     return saveregs_value;
4009
4010   /* When this function is called, it means that registers must be
4011      saved on entry to this function.  So we migrate the call to the
4012      first insn of this function.  */
4013
4014   start_sequence ();
4015
4016   /* Do whatever the machine needs done in this case.  */
4017   val = targetm.calls.expand_builtin_saveregs ();
4018
4019   seq = get_insns ();
4020   end_sequence ();
4021
4022   saveregs_value = val;
4023
4024   /* Put the insns after the NOTE that starts the function.  If this
4025      is inside a start_sequence, make the outer-level insn chain current, so
4026      the code is placed at the start of the function.  */
4027   push_topmost_sequence ();
4028   emit_insn_after (seq, entry_of_function ());
4029   pop_topmost_sequence ();
4030
4031   return val;
4032 }
4033
4034 /* Expand a call to __builtin_next_arg.  */
4035
4036 static rtx
4037 expand_builtin_next_arg (void)
4038 {
4039   /* Checking arguments is already done in fold_builtin_next_arg
4040      that must be called before this function.  */
4041   return expand_binop (ptr_mode, add_optab,
4042                        crtl->args.internal_arg_pointer,
4043                        crtl->args.arg_offset_rtx,
4044                        NULL_RTX, 0, OPTAB_LIB_WIDEN);
4045 }
4046
4047 /* Make it easier for the backends by protecting the valist argument
4048    from multiple evaluations.  */
4049
4050 static tree
4051 stabilize_va_list_loc (location_t loc, tree valist, int needs_lvalue)
4052 {
4053   tree vatype = targetm.canonical_va_list_type (TREE_TYPE (valist));
4054
4055   /* The current way of determining the type of valist is completely
4056      bogus.  We should have the information on the va builtin instead.  */
4057   if (!vatype)
4058     vatype = targetm.fn_abi_va_list (cfun->decl);
4059
4060   if (TREE_CODE (vatype) == ARRAY_TYPE)
4061     {
4062       if (TREE_SIDE_EFFECTS (valist))
4063         valist = save_expr (valist);
4064
4065       /* For this case, the backends will be expecting a pointer to
4066          vatype, but it's possible we've actually been given an array
4067          (an actual TARGET_CANONICAL_VA_LIST_TYPE (valist)).
4068          So fix it.  */
4069       if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
4070         {
4071           tree p1 = build_pointer_type (TREE_TYPE (vatype));
4072           valist = build_fold_addr_expr_with_type_loc (loc, valist, p1);
4073         }
4074     }
4075   else
4076     {
4077       tree pt = build_pointer_type (vatype);
4078
4079       if (! needs_lvalue)
4080         {
4081           if (! TREE_SIDE_EFFECTS (valist))
4082             return valist;
4083
4084           valist = fold_build1_loc (loc, ADDR_EXPR, pt, valist);
4085           TREE_SIDE_EFFECTS (valist) = 1;
4086         }
4087
4088       if (TREE_SIDE_EFFECTS (valist))
4089         valist = save_expr (valist);
4090       valist = fold_build2_loc (loc, MEM_REF,
4091                                 vatype, valist, build_int_cst (pt, 0));
4092     }
4093
4094   return valist;
4095 }
4096
4097 /* The "standard" definition of va_list is void*.  */
4098
4099 tree
4100 std_build_builtin_va_list (void)
4101 {
4102   return ptr_type_node;
4103 }
4104
4105 /* The "standard" abi va_list is va_list_type_node.  */
4106
4107 tree
4108 std_fn_abi_va_list (tree fndecl ATTRIBUTE_UNUSED)
4109 {
4110   return va_list_type_node;
4111 }
4112
4113 /* The "standard" type of va_list is va_list_type_node.  */
4114
4115 tree
4116 std_canonical_va_list_type (tree type)
4117 {
4118   tree wtype, htype;
4119
4120   if (INDIRECT_REF_P (type))
4121     type = TREE_TYPE (type);
4122   else if (POINTER_TYPE_P (type) && POINTER_TYPE_P (TREE_TYPE(type)))
4123     type = TREE_TYPE (type);
4124   wtype = va_list_type_node;
4125   htype = type;
4126   /* Treat structure va_list types.  */
4127   if (TREE_CODE (wtype) == RECORD_TYPE && POINTER_TYPE_P (htype))
4128     htype = TREE_TYPE (htype);
4129   else if (TREE_CODE (wtype) == ARRAY_TYPE)
4130     {
4131       /* If va_list is an array type, the argument may have decayed
4132          to a pointer type, e.g. by being passed to another function.
4133          In that case, unwrap both types so that we can compare the
4134          underlying records.  */
4135       if (TREE_CODE (htype) == ARRAY_TYPE
4136           || POINTER_TYPE_P (htype))
4137         {
4138           wtype = TREE_TYPE (wtype);
4139           htype = TREE_TYPE (htype);
4140         }
4141     }
4142   if (TYPE_MAIN_VARIANT (wtype) == TYPE_MAIN_VARIANT (htype))
4143     return va_list_type_node;
4144
4145   return NULL_TREE;
4146 }
4147
4148 /* The "standard" implementation of va_start: just assign `nextarg' to
4149    the variable.  */
4150
4151 void
4152 std_expand_builtin_va_start (tree valist, rtx nextarg)
4153 {
4154   rtx va_r = expand_expr (valist, NULL_RTX, VOIDmode, EXPAND_WRITE);
4155   convert_move (va_r, nextarg, 0);
4156 }
4157
4158 /* Expand EXP, a call to __builtin_va_start.  */
4159
4160 static rtx
4161 expand_builtin_va_start (tree exp)
4162 {
4163   rtx nextarg;
4164   tree valist;
4165   location_t loc = EXPR_LOCATION (exp);
4166
4167   if (call_expr_nargs (exp) < 2)
4168     {
4169       error_at (loc, "too few arguments to function %<va_start%>");
4170       return const0_rtx;
4171     }
4172
4173   if (fold_builtin_next_arg (exp, true))
4174     return const0_rtx;
4175
4176   nextarg = expand_builtin_next_arg ();
4177   valist = stabilize_va_list_loc (loc, CALL_EXPR_ARG (exp, 0), 1);
4178
4179   if (targetm.expand_builtin_va_start)
4180     targetm.expand_builtin_va_start (valist, nextarg);
4181   else
4182     std_expand_builtin_va_start (valist, nextarg);
4183
4184   return const0_rtx;
4185 }
4186
4187 /* The "standard" implementation of va_arg: read the value from the
4188    current (padded) address and increment by the (padded) size.  */
4189
4190 tree
4191 std_gimplify_va_arg_expr (tree valist, tree type, gimple_seq *pre_p,
4192                           gimple_seq *post_p)
4193 {
4194   tree addr, t, type_size, rounded_size, valist_tmp;
4195   unsigned HOST_WIDE_INT align, boundary;
4196   bool indirect;
4197
4198 #ifdef ARGS_GROW_DOWNWARD
4199   /* All of the alignment and movement below is for args-grow-up machines.
4200      As of 2004, there are only 3 ARGS_GROW_DOWNWARD targets, and they all
4201      implement their own specialized gimplify_va_arg_expr routines.  */
4202   gcc_unreachable ();
4203 #endif
4204
4205   indirect = pass_by_reference (NULL, TYPE_MODE (type), type, false);
4206   if (indirect)
4207     type = build_pointer_type (type);
4208
4209   align = PARM_BOUNDARY / BITS_PER_UNIT;
4210   boundary = targetm.calls.function_arg_boundary (TYPE_MODE (type), type);
4211
4212   /* When we align parameter on stack for caller, if the parameter
4213      alignment is beyond MAX_SUPPORTED_STACK_ALIGNMENT, it will be
4214      aligned at MAX_SUPPORTED_STACK_ALIGNMENT.  We will match callee
4215      here with caller.  */
4216   if (boundary > MAX_SUPPORTED_STACK_ALIGNMENT)
4217     boundary = MAX_SUPPORTED_STACK_ALIGNMENT;
4218
4219   boundary /= BITS_PER_UNIT;
4220
4221   /* Hoist the valist value into a temporary for the moment.  */
4222   valist_tmp = get_initialized_tmp_var (valist, pre_p, NULL);
4223
4224   /* va_list pointer is aligned to PARM_BOUNDARY.  If argument actually
4225      requires greater alignment, we must perform dynamic alignment.  */
4226   if (boundary > align
4227       && !integer_zerop (TYPE_SIZE (type)))
4228     {
4229       t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
4230                   fold_build_pointer_plus_hwi (valist_tmp, boundary - 1));
4231       gimplify_and_add (t, pre_p);
4232
4233       t = fold_convert (sizetype, valist_tmp);
4234       t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
4235                   fold_convert (TREE_TYPE (valist),
4236                                 fold_build2 (BIT_AND_EXPR, sizetype, t,
4237                                              size_int (-boundary))));
4238       gimplify_and_add (t, pre_p);
4239     }
4240   else
4241     boundary = align;
4242
4243   /* If the actual alignment is less than the alignment of the type,
4244      adjust the type accordingly so that we don't assume strict alignment
4245      when dereferencing the pointer.  */
4246   boundary *= BITS_PER_UNIT;
4247   if (boundary < TYPE_ALIGN (type))
4248     {
4249       type = build_variant_type_copy (type);
4250       TYPE_ALIGN (type) = boundary;
4251     }
4252
4253   /* Compute the rounded size of the type.  */
4254   type_size = size_in_bytes (type);
4255   rounded_size = round_up (type_size, align);
4256
4257   /* Reduce rounded_size so it's sharable with the postqueue.  */
4258   gimplify_expr (&rounded_size, pre_p, post_p, is_gimple_val, fb_rvalue);
4259
4260   /* Get AP.  */
4261   addr = valist_tmp;
4262   if (PAD_VARARGS_DOWN && !integer_zerop (rounded_size))
4263     {
4264       /* Small args are padded downward.  */
4265       t = fold_build2_loc (input_location, GT_EXPR, sizetype,
4266                        rounded_size, size_int (align));
4267       t = fold_build3 (COND_EXPR, sizetype, t, size_zero_node,
4268                        size_binop (MINUS_EXPR, rounded_size, type_size));
4269       addr = fold_build_pointer_plus (addr, t);
4270     }
4271
4272   /* Compute new value for AP.  */
4273   t = fold_build_pointer_plus (valist_tmp, rounded_size);
4274   t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist, t);
4275   gimplify_and_add (t, pre_p);
4276
4277   addr = fold_convert (build_pointer_type (type), addr);
4278
4279   if (indirect)
4280     addr = build_va_arg_indirect_ref (addr);
4281
4282   return build_va_arg_indirect_ref (addr);
4283 }
4284
4285 /* Build an indirect-ref expression over the given TREE, which represents a
4286    piece of a va_arg() expansion.  */
4287 tree
4288 build_va_arg_indirect_ref (tree addr)
4289 {
4290   addr = build_simple_mem_ref_loc (EXPR_LOCATION (addr), addr);
4291
4292   if (flag_mudflap) /* Don't instrument va_arg INDIRECT_REF.  */
4293     mf_mark (addr);
4294
4295   return addr;
4296 }
4297
4298 /* Return a dummy expression of type TYPE in order to keep going after an
4299    error.  */
4300
4301 static tree
4302 dummy_object (tree type)
4303 {
4304   tree t = build_int_cst (build_pointer_type (type), 0);
4305   return build2 (MEM_REF, type, t, t);
4306 }
4307
4308 /* Gimplify __builtin_va_arg, aka VA_ARG_EXPR, which is not really a
4309    builtin function, but a very special sort of operator.  */
4310
4311 enum gimplify_status
4312 gimplify_va_arg_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p)
4313 {
4314   tree promoted_type, have_va_type;
4315   tree valist = TREE_OPERAND (*expr_p, 0);
4316   tree type = TREE_TYPE (*expr_p);
4317   tree t;
4318   location_t loc = EXPR_LOCATION (*expr_p);
4319
4320   /* Verify that valist is of the proper type.  */
4321   have_va_type = TREE_TYPE (valist);
4322   if (have_va_type == error_mark_node)
4323     return GS_ERROR;
4324   have_va_type = targetm.canonical_va_list_type (have_va_type);
4325
4326   if (have_va_type == NULL_TREE)
4327     {
4328       error_at (loc, "first argument to %<va_arg%> not of type %<va_list%>");
4329       return GS_ERROR;
4330     }
4331
4332   /* Generate a diagnostic for requesting data of a type that cannot
4333      be passed through `...' due to type promotion at the call site.  */
4334   if ((promoted_type = lang_hooks.types.type_promotes_to (type))
4335            != type)
4336     {
4337       static bool gave_help;
4338       bool warned;
4339
4340       /* Unfortunately, this is merely undefined, rather than a constraint
4341          violation, so we cannot make this an error.  If this call is never
4342          executed, the program is still strictly conforming.  */
4343       warned = warning_at (loc, 0,
4344                            "%qT is promoted to %qT when passed through %<...%>",
4345                            type, promoted_type);
4346       if (!gave_help && warned)
4347         {
4348           gave_help = true;
4349           inform (loc, "(so you should pass %qT not %qT to %<va_arg%>)",
4350                   promoted_type, type);
4351         }
4352
4353       /* We can, however, treat "undefined" any way we please.
4354          Call abort to encourage the user to fix the program.  */
4355       if (warned)
4356         inform (loc, "if this code is reached, the program will abort");
4357       /* Before the abort, allow the evaluation of the va_list
4358          expression to exit or longjmp.  */
4359       gimplify_and_add (valist, pre_p);
4360       t = build_call_expr_loc (loc,
4361                                implicit_built_in_decls[BUILT_IN_TRAP], 0);
4362       gimplify_and_add (t, pre_p);
4363
4364       /* This is dead code, but go ahead and finish so that the
4365          mode of the result comes out right.  */
4366       *expr_p = dummy_object (type);
4367       return GS_ALL_DONE;
4368     }
4369   else
4370     {
4371       /* Make it easier for the backends by protecting the valist argument
4372          from multiple evaluations.  */
4373       if (TREE_CODE (have_va_type) == ARRAY_TYPE)
4374         {
4375           /* For this case, the backends will be expecting a pointer to
4376              TREE_TYPE (abi), but it's possible we've
4377              actually been given an array (an actual TARGET_FN_ABI_VA_LIST).
4378              So fix it.  */
4379           if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
4380             {
4381               tree p1 = build_pointer_type (TREE_TYPE (have_va_type));
4382               valist = fold_convert_loc (loc, p1,
4383                                          build_fold_addr_expr_loc (loc, valist));
4384             }
4385
4386           gimplify_expr (&valist, pre_p, post_p, is_gimple_val, fb_rvalue);
4387         }
4388       else
4389         gimplify_expr (&valist, pre_p, post_p, is_gimple_min_lval, fb_lvalue);
4390
4391       if (!targetm.gimplify_va_arg_expr)
4392         /* FIXME: Once most targets are converted we should merely
4393            assert this is non-null.  */
4394         return GS_ALL_DONE;
4395
4396       *expr_p = targetm.gimplify_va_arg_expr (valist, type, pre_p, post_p);
4397       return GS_OK;
4398     }
4399 }
4400
4401 /* Expand EXP, a call to __builtin_va_end.  */
4402
4403 static rtx
4404 expand_builtin_va_end (tree exp)
4405 {
4406   tree valist = CALL_EXPR_ARG (exp, 0);
4407
4408   /* Evaluate for side effects, if needed.  I hate macros that don't
4409      do that.  */
4410   if (TREE_SIDE_EFFECTS (valist))
4411     expand_expr (valist, const0_rtx, VOIDmode, EXPAND_NORMAL);
4412
4413   return const0_rtx;
4414 }
4415
4416 /* Expand EXP, a call to __builtin_va_copy.  We do this as a
4417    builtin rather than just as an assignment in stdarg.h because of the
4418    nastiness of array-type va_list types.  */
4419
4420 static rtx
4421 expand_builtin_va_copy (tree exp)
4422 {
4423   tree dst, src, t;
4424   location_t loc = EXPR_LOCATION (exp);
4425
4426   dst = CALL_EXPR_ARG (exp, 0);
4427   src = CALL_EXPR_ARG (exp, 1);
4428
4429   dst = stabilize_va_list_loc (loc, dst, 1);
4430   src = stabilize_va_list_loc (loc, src, 0);
4431
4432   gcc_assert (cfun != NULL && cfun->decl != NULL_TREE);
4433
4434   if (TREE_CODE (targetm.fn_abi_va_list (cfun->decl)) != ARRAY_TYPE)
4435     {
4436       t = build2 (MODIFY_EXPR, targetm.fn_abi_va_list (cfun->decl), dst, src);
4437       TREE_SIDE_EFFECTS (t) = 1;
4438       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4439     }
4440   else
4441     {
4442       rtx dstb, srcb, size;
4443
4444       /* Evaluate to pointers.  */
4445       dstb = expand_expr (dst, NULL_RTX, Pmode, EXPAND_NORMAL);
4446       srcb = expand_expr (src, NULL_RTX, Pmode, EXPAND_NORMAL);
4447       size = expand_expr (TYPE_SIZE_UNIT (targetm.fn_abi_va_list (cfun->decl)),
4448                   NULL_RTX, VOIDmode, EXPAND_NORMAL);
4449
4450       dstb = convert_memory_address (Pmode, dstb);
4451       srcb = convert_memory_address (Pmode, srcb);
4452
4453       /* "Dereference" to BLKmode memories.  */
4454       dstb = gen_rtx_MEM (BLKmode, dstb);
4455       set_mem_alias_set (dstb, get_alias_set (TREE_TYPE (TREE_TYPE (dst))));
4456       set_mem_align (dstb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4457       srcb = gen_rtx_MEM (BLKmode, srcb);
4458       set_mem_alias_set (srcb, get_alias_set (TREE_TYPE (TREE_TYPE (src))));
4459       set_mem_align (srcb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4460
4461       /* Copy.  */
4462       emit_block_move (dstb, srcb, size, BLOCK_OP_NORMAL);
4463     }
4464
4465   return const0_rtx;
4466 }
4467
4468 /* Expand a call to one of the builtin functions __builtin_frame_address or
4469    __builtin_return_address.  */
4470
4471 static rtx
4472 expand_builtin_frame_address (tree fndecl, tree exp)
4473 {
4474   /* The argument must be a nonnegative integer constant.
4475      It counts the number of frames to scan up the stack.
4476      The value is the return address saved in that frame.  */
4477   if (call_expr_nargs (exp) == 0)
4478     /* Warning about missing arg was already issued.  */
4479     return const0_rtx;
4480   else if (! host_integerp (CALL_EXPR_ARG (exp, 0), 1))
4481     {
4482       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4483         error ("invalid argument to %<__builtin_frame_address%>");
4484       else
4485         error ("invalid argument to %<__builtin_return_address%>");
4486       return const0_rtx;
4487     }
4488   else
4489     {
4490       rtx tem
4491         = expand_builtin_return_addr (DECL_FUNCTION_CODE (fndecl),
4492                                       tree_low_cst (CALL_EXPR_ARG (exp, 0), 1));
4493
4494       /* Some ports cannot access arbitrary stack frames.  */
4495       if (tem == NULL)
4496         {
4497           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4498             warning (0, "unsupported argument to %<__builtin_frame_address%>");
4499           else
4500             warning (0, "unsupported argument to %<__builtin_return_address%>");
4501           return const0_rtx;
4502         }
4503
4504       /* For __builtin_frame_address, return what we've got.  */
4505       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4506         return tem;
4507
4508       if (!REG_P (tem)
4509           && ! CONSTANT_P (tem))
4510         tem = copy_to_mode_reg (Pmode, tem);
4511       return tem;
4512     }
4513 }
4514
4515 /* Expand EXP, a call to the alloca builtin.  Return NULL_RTX if we
4516    failed and the caller should emit a normal call.  CANNOT_ACCUMULATE
4517    is the same as for allocate_dynamic_stack_space.  */
4518
4519 static rtx
4520 expand_builtin_alloca (tree exp, bool cannot_accumulate)
4521 {
4522   rtx op0;
4523   rtx result;
4524
4525   /* Emit normal call if marked not-inlineable.  */
4526   if (CALL_CANNOT_INLINE_P (exp))
4527     return NULL_RTX;
4528
4529   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4530     return NULL_RTX;
4531
4532   /* Compute the argument.  */
4533   op0 = expand_normal (CALL_EXPR_ARG (exp, 0));
4534
4535   /* Allocate the desired space.  */
4536   result = allocate_dynamic_stack_space (op0, 0, BIGGEST_ALIGNMENT,
4537                                          cannot_accumulate);
4538   result = convert_memory_address (ptr_mode, result);
4539
4540   return result;
4541 }
4542
4543 /* Expand a call to a bswap builtin with argument ARG0.  MODE
4544    is the mode to expand with.  */
4545
4546 static rtx
4547 expand_builtin_bswap (tree exp, rtx target, rtx subtarget)
4548 {
4549   enum machine_mode mode;
4550   tree arg;
4551   rtx op0;
4552
4553   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4554     return NULL_RTX;
4555
4556   arg = CALL_EXPR_ARG (exp, 0);
4557   mode = TYPE_MODE (TREE_TYPE (arg));
4558   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
4559
4560   target = expand_unop (mode, bswap_optab, op0, target, 1);
4561
4562   gcc_assert (target);
4563
4564   return convert_to_mode (mode, target, 0);
4565 }
4566
4567 /* Expand a call to a unary builtin in EXP.
4568    Return NULL_RTX if a normal call should be emitted rather than expanding the
4569    function in-line.  If convenient, the result should be placed in TARGET.
4570    SUBTARGET may be used as the target for computing one of EXP's operands.  */
4571
4572 static rtx
4573 expand_builtin_unop (enum machine_mode target_mode, tree exp, rtx target,
4574                      rtx subtarget, optab op_optab)
4575 {
4576   rtx op0;
4577
4578   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4579     return NULL_RTX;
4580
4581   /* Compute the argument.  */
4582   op0 = expand_expr (CALL_EXPR_ARG (exp, 0),
4583                      (subtarget
4584                       && (TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 0)))
4585                           == GET_MODE (subtarget))) ? subtarget : NULL_RTX,
4586                      VOIDmode, EXPAND_NORMAL);
4587   /* Compute op, into TARGET if possible.
4588      Set TARGET to wherever the result comes back.  */
4589   target = expand_unop (TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 0))),
4590                         op_optab, op0, target, op_optab != clrsb_optab);
4591   gcc_assert (target);
4592
4593   return convert_to_mode (target_mode, target, 0);
4594 }
4595
4596 /* Expand a call to __builtin_expect.  We just return our argument
4597    as the builtin_expect semantic should've been already executed by
4598    tree branch prediction pass. */
4599
4600 static rtx
4601 expand_builtin_expect (tree exp, rtx target)
4602 {
4603   tree arg;
4604
4605   if (call_expr_nargs (exp) < 2)
4606     return const0_rtx;
4607   arg = CALL_EXPR_ARG (exp, 0);
4608
4609   target = expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
4610   /* When guessing was done, the hints should be already stripped away.  */
4611   gcc_assert (!flag_guess_branch_prob
4612               || optimize == 0 || seen_error ());
4613   return target;
4614 }
4615
4616 /* Expand a call to __builtin_assume_aligned.  We just return our first
4617    argument as the builtin_assume_aligned semantic should've been already
4618    executed by CCP.  */
4619
4620 static rtx
4621 expand_builtin_assume_aligned (tree exp, rtx target)
4622 {
4623   if (call_expr_nargs (exp) < 2)
4624     return const0_rtx;
4625   target = expand_expr (CALL_EXPR_ARG (exp, 0), target, VOIDmode,
4626                         EXPAND_NORMAL);
4627   gcc_assert (!TREE_SIDE_EFFECTS (CALL_EXPR_ARG (exp, 1))
4628               && (call_expr_nargs (exp) < 3
4629                   || !TREE_SIDE_EFFECTS (CALL_EXPR_ARG (exp, 2))));
4630   return target;
4631 }
4632
4633 void
4634 expand_builtin_trap (void)
4635 {
4636 #ifdef HAVE_trap
4637   if (HAVE_trap)
4638     emit_insn (gen_trap ());
4639   else
4640 #endif
4641     emit_library_call (abort_libfunc, LCT_NORETURN, VOIDmode, 0);
4642   emit_barrier ();
4643 }
4644
4645 /* Expand a call to __builtin_unreachable.  We do nothing except emit
4646    a barrier saying that control flow will not pass here.
4647
4648    It is the responsibility of the program being compiled to ensure
4649    that control flow does never reach __builtin_unreachable.  */
4650 static void
4651 expand_builtin_unreachable (void)
4652 {
4653   emit_barrier ();
4654 }
4655
4656 /* Expand EXP, a call to fabs, fabsf or fabsl.
4657    Return NULL_RTX if a normal call should be emitted rather than expanding
4658    the function inline.  If convenient, the result should be placed
4659    in TARGET.  SUBTARGET may be used as the target for computing
4660    the operand.  */
4661
4662 static rtx
4663 expand_builtin_fabs (tree exp, rtx target, rtx subtarget)
4664 {
4665   enum machine_mode mode;
4666   tree arg;
4667   rtx op0;
4668
4669   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
4670     return NULL_RTX;
4671
4672   arg = CALL_EXPR_ARG (exp, 0);
4673   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
4674   mode = TYPE_MODE (TREE_TYPE (arg));
4675   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
4676   return expand_abs (mode, op0, target, 0, safe_from_p (target, arg, 1));
4677 }
4678
4679 /* Expand EXP, a call to copysign, copysignf, or copysignl.
4680    Return NULL is a normal call should be emitted rather than expanding the
4681    function inline.  If convenient, the result should be placed in TARGET.
4682    SUBTARGET may be used as the target for computing the operand.  */
4683
4684 static rtx
4685 expand_builtin_copysign (tree exp, rtx target, rtx subtarget)
4686 {
4687   rtx op0, op1;
4688   tree arg;
4689
4690   if (!validate_arglist (exp, REAL_TYPE, REAL_TYPE, VOID_TYPE))
4691     return NULL_RTX;
4692
4693   arg = CALL_EXPR_ARG (exp, 0);
4694   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
4695
4696   arg = CALL_EXPR_ARG (exp, 1);
4697   op1 = expand_normal (arg);
4698
4699   return expand_copysign (op0, op1, target);
4700 }
4701
4702 /* Create a new constant string literal and return a char* pointer to it.
4703    The STRING_CST value is the LEN characters at STR.  */
4704 tree
4705 build_string_literal (int len, const char *str)
4706 {
4707   tree t, elem, index, type;
4708
4709   t = build_string (len, str);
4710   elem = build_type_variant (char_type_node, 1, 0);
4711   index = build_index_type (size_int (len - 1));
4712   type = build_array_type (elem, index);
4713   TREE_TYPE (t) = type;
4714   TREE_CONSTANT (t) = 1;
4715   TREE_READONLY (t) = 1;
4716   TREE_STATIC (t) = 1;
4717
4718   type = build_pointer_type (elem);
4719   t = build1 (ADDR_EXPR, type,
4720               build4 (ARRAY_REF, elem,
4721                       t, integer_zero_node, NULL_TREE, NULL_TREE));
4722   return t;
4723 }
4724
4725 /* Expand a call to __builtin___clear_cache.  */
4726
4727 static rtx
4728 expand_builtin___clear_cache (tree exp ATTRIBUTE_UNUSED)
4729 {
4730 #ifndef HAVE_clear_cache
4731 #ifdef CLEAR_INSN_CACHE
4732   /* There is no "clear_cache" insn, and __clear_cache() in libgcc
4733      does something.  Just do the default expansion to a call to
4734      __clear_cache().  */
4735   return NULL_RTX;
4736 #else
4737   /* There is no "clear_cache" insn, and __clear_cache() in libgcc
4738      does nothing.  There is no need to call it.  Do nothing.  */
4739   return const0_rtx;
4740 #endif /* CLEAR_INSN_CACHE */
4741 #else
4742   /* We have a "clear_cache" insn, and it will handle everything.  */
4743   tree begin, end;
4744   rtx begin_rtx, end_rtx;
4745
4746   /* We must not expand to a library call.  If we did, any
4747      fallback library function in libgcc that might contain a call to
4748      __builtin___clear_cache() would recurse infinitely.  */
4749   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
4750     {
4751       error ("both arguments to %<__builtin___clear_cache%> must be pointers");
4752       return const0_rtx;
4753     }
4754
4755   if (HAVE_clear_cache)
4756     {
4757       struct expand_operand ops[2];
4758
4759       begin = CALL_EXPR_ARG (exp, 0);
4760       begin_rtx = expand_expr (begin, NULL_RTX, Pmode, EXPAND_NORMAL);
4761
4762       end = CALL_EXPR_ARG (exp, 1);
4763       end_rtx = expand_expr (end, NULL_RTX, Pmode, EXPAND_NORMAL);
4764
4765       create_address_operand (&ops[0], begin_rtx);
4766       create_address_operand (&ops[1], end_rtx);
4767       if (maybe_expand_insn (CODE_FOR_clear_cache, 2, ops))
4768         return const0_rtx;
4769     }
4770   return const0_rtx;
4771 #endif /* HAVE_clear_cache */
4772 }
4773
4774 /* Given a trampoline address, make sure it satisfies TRAMPOLINE_ALIGNMENT.  */
4775
4776 static rtx
4777 round_trampoline_addr (rtx tramp)
4778 {
4779   rtx temp, addend, mask;
4780
4781   /* If we don't need too much alignment, we'll have been guaranteed
4782      proper alignment by get_trampoline_type.  */
4783   if (TRAMPOLINE_ALIGNMENT <= STACK_BOUNDARY)
4784     return tramp;
4785
4786   /* Round address up to desired boundary.  */
4787   temp = gen_reg_rtx (Pmode);
4788   addend = GEN_INT (TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT - 1);
4789   mask = GEN_INT (-TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT);
4790
4791   temp  = expand_simple_binop (Pmode, PLUS, tramp, addend,
4792                                temp, 0, OPTAB_LIB_WIDEN);
4793   tramp = expand_simple_binop (Pmode, AND, temp, mask,
4794                                temp, 0, OPTAB_LIB_WIDEN);
4795
4796   return tramp;
4797 }
4798
4799 static rtx
4800 expand_builtin_init_trampoline (tree exp)
4801 {
4802   tree t_tramp, t_func, t_chain;
4803   rtx m_tramp, r_tramp, r_chain, tmp;
4804
4805   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE,
4806                          POINTER_TYPE, VOID_TYPE))
4807     return NULL_RTX;
4808
4809   t_tramp = CALL_EXPR_ARG (exp, 0);
4810   t_func = CALL_EXPR_ARG (exp, 1);
4811   t_chain = CALL_EXPR_ARG (exp, 2);
4812
4813   r_tramp = expand_normal (t_tramp);
4814   m_tramp = gen_rtx_MEM (BLKmode, r_tramp);
4815   MEM_NOTRAP_P (m_tramp) = 1;
4816
4817   /* The TRAMP argument should be the address of a field within the
4818      local function's FRAME decl.  Let's see if we can fill in the
4819      to fill in the MEM_ATTRs for this memory.  */
4820   if (TREE_CODE (t_tramp) == ADDR_EXPR)
4821     set_mem_attributes_minus_bitpos (m_tramp, TREE_OPERAND (t_tramp, 0),
4822                                      true, 0);
4823
4824   tmp = round_trampoline_addr (r_tramp);
4825   if (tmp != r_tramp)
4826     {
4827       m_tramp = change_address (m_tramp, BLKmode, tmp);
4828       set_mem_align (m_tramp, TRAMPOLINE_ALIGNMENT);
4829       set_mem_size (m_tramp, TRAMPOLINE_SIZE);
4830     }
4831
4832   /* The FUNC argument should be the address of the nested function.
4833      Extract the actual function decl to pass to the hook.  */
4834   gcc_assert (TREE_CODE (t_func) == ADDR_EXPR);
4835   t_func = TREE_OPERAND (t_func, 0);
4836   gcc_assert (TREE_CODE (t_func) == FUNCTION_DECL);
4837
4838   r_chain = expand_normal (t_chain);
4839
4840   /* Generate insns to initialize the trampoline.  */
4841   targetm.calls.trampoline_init (m_tramp, t_func, r_chain);
4842
4843   trampolines_created = 1;
4844
4845   warning_at (DECL_SOURCE_LOCATION (t_func), OPT_Wtrampolines,
4846               "trampoline generated for nested function %qD", t_func);
4847
4848   return const0_rtx;
4849 }
4850
4851 static rtx
4852 expand_builtin_adjust_trampoline (tree exp)
4853 {
4854   rtx tramp;
4855
4856   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
4857     return NULL_RTX;
4858
4859   tramp = expand_normal (CALL_EXPR_ARG (exp, 0));
4860   tramp = round_trampoline_addr (tramp);
4861   if (targetm.calls.trampoline_adjust_address)
4862     tramp = targetm.calls.trampoline_adjust_address (tramp);
4863
4864   return tramp;
4865 }
4866
4867 /* Expand the call EXP to the built-in signbit, signbitf or signbitl
4868    function.  The function first checks whether the back end provides
4869    an insn to implement signbit for the respective mode.  If not, it
4870    checks whether the floating point format of the value is such that
4871    the sign bit can be extracted.  If that is not the case, the
4872    function returns NULL_RTX to indicate that a normal call should be
4873    emitted rather than expanding the function in-line.  EXP is the
4874    expression that is a call to the builtin function; if convenient,
4875    the result should be placed in TARGET.  */
4876 static rtx
4877 expand_builtin_signbit (tree exp, rtx target)
4878 {
4879   const struct real_format *fmt;
4880   enum machine_mode fmode, imode, rmode;
4881   tree arg;
4882   int word, bitpos;
4883   enum insn_code icode;
4884   rtx temp;
4885   location_t loc = EXPR_LOCATION (exp);
4886
4887   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
4888     return NULL_RTX;
4889
4890   arg = CALL_EXPR_ARG (exp, 0);
4891   fmode = TYPE_MODE (TREE_TYPE (arg));
4892   rmode = TYPE_MODE (TREE_TYPE (exp));
4893   fmt = REAL_MODE_FORMAT (fmode);
4894
4895   arg = builtin_save_expr (arg);
4896
4897   /* Expand the argument yielding a RTX expression. */
4898   temp = expand_normal (arg);
4899
4900   /* Check if the back end provides an insn that handles signbit for the
4901      argument's mode. */
4902   icode = optab_handler (signbit_optab, fmode);
4903   if (icode != CODE_FOR_nothing)
4904     {
4905       rtx last = get_last_insn ();
4906       target = gen_reg_rtx (TYPE_MODE (TREE_TYPE (exp)));
4907       if (maybe_emit_unop_insn (icode, target, temp, UNKNOWN))
4908         return target;
4909       delete_insns_since (last);
4910     }
4911
4912   /* For floating point formats without a sign bit, implement signbit
4913      as "ARG < 0.0".  */
4914   bitpos = fmt->signbit_ro;
4915   if (bitpos < 0)
4916   {
4917     /* But we can't do this if the format supports signed zero.  */
4918     if (fmt->has_signed_zero && HONOR_SIGNED_ZEROS (fmode))
4919       return NULL_RTX;
4920
4921     arg = fold_build2_loc (loc, LT_EXPR, TREE_TYPE (exp), arg,
4922                        build_real (TREE_TYPE (arg), dconst0));
4923     return expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
4924   }
4925
4926   if (GET_MODE_SIZE (fmode) <= UNITS_PER_WORD)
4927     {
4928       imode = int_mode_for_mode (fmode);
4929       if (imode == BLKmode)
4930         return NULL_RTX;
4931       temp = gen_lowpart (imode, temp);
4932     }
4933   else
4934     {
4935       imode = word_mode;
4936       /* Handle targets with different FP word orders.  */
4937       if (FLOAT_WORDS_BIG_ENDIAN)
4938         word = (GET_MODE_BITSIZE (fmode) - bitpos) / BITS_PER_WORD;
4939       else
4940         word = bitpos / BITS_PER_WORD;
4941       temp = operand_subword_force (temp, word, fmode);
4942       bitpos = bitpos % BITS_PER_WORD;
4943     }
4944
4945   /* Force the intermediate word_mode (or narrower) result into a
4946      register.  This avoids attempting to create paradoxical SUBREGs
4947      of floating point modes below.  */
4948   temp = force_reg (imode, temp);
4949
4950   /* If the bitpos is within the "result mode" lowpart, the operation
4951      can be implement with a single bitwise AND.  Otherwise, we need
4952      a right shift and an AND.  */
4953
4954   if (bitpos < GET_MODE_BITSIZE (rmode))
4955     {
4956       double_int mask = double_int_setbit (double_int_zero, bitpos);
4957
4958       if (GET_MODE_SIZE (imode) > GET_MODE_SIZE (rmode))
4959         temp = gen_lowpart (rmode, temp);
4960       temp = expand_binop (rmode, and_optab, temp,
4961                            immed_double_int_const (mask, rmode),
4962                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
4963     }
4964   else
4965     {
4966       /* Perform a logical right shift to place the signbit in the least
4967          significant bit, then truncate the result to the desired mode
4968          and mask just this bit.  */
4969       temp = expand_shift (RSHIFT_EXPR, imode, temp, bitpos, NULL_RTX, 1);
4970       temp = gen_lowpart (rmode, temp);
4971       temp = expand_binop (rmode, and_optab, temp, const1_rtx,
4972                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
4973     }
4974
4975   return temp;
4976 }
4977
4978 /* Expand fork or exec calls.  TARGET is the desired target of the
4979    call.  EXP is the call. FN is the
4980    identificator of the actual function.  IGNORE is nonzero if the
4981    value is to be ignored.  */
4982
4983 static rtx
4984 expand_builtin_fork_or_exec (tree fn, tree exp, rtx target, int ignore)
4985 {
4986   tree id, decl;
4987   tree call;
4988
4989   /* If we are not profiling, just call the function.  */
4990   if (!profile_arc_flag)
4991     return NULL_RTX;
4992
4993   /* Otherwise call the wrapper.  This should be equivalent for the rest of
4994      compiler, so the code does not diverge, and the wrapper may run the
4995      code necessary for keeping the profiling sane.  */
4996
4997   switch (DECL_FUNCTION_CODE (fn))
4998     {
4999     case BUILT_IN_FORK:
5000       id = get_identifier ("__gcov_fork");
5001       break;
5002
5003     case BUILT_IN_EXECL:
5004       id = get_identifier ("__gcov_execl");
5005       break;
5006
5007     case BUILT_IN_EXECV:
5008       id = get_identifier ("__gcov_execv");
5009       break;
5010
5011     case BUILT_IN_EXECLP:
5012       id = get_identifier ("__gcov_execlp");
5013       break;
5014
5015     case BUILT_IN_EXECLE:
5016       id = get_identifier ("__gcov_execle");
5017       break;
5018
5019     case BUILT_IN_EXECVP:
5020       id = get_identifier ("__gcov_execvp");
5021       break;
5022
5023     case BUILT_IN_EXECVE:
5024       id = get_identifier ("__gcov_execve");
5025       break;
5026
5027     default:
5028       gcc_unreachable ();
5029     }
5030
5031   decl = build_decl (DECL_SOURCE_LOCATION (fn),
5032                      FUNCTION_DECL, id, TREE_TYPE (fn));
5033   DECL_EXTERNAL (decl) = 1;
5034   TREE_PUBLIC (decl) = 1;
5035   DECL_ARTIFICIAL (decl) = 1;
5036   TREE_NOTHROW (decl) = 1;
5037   DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
5038   DECL_VISIBILITY_SPECIFIED (decl) = 1;
5039   call = rewrite_call_expr (EXPR_LOCATION (exp), exp, 0, decl, 0);
5040   return expand_call (call, target, ignore);
5041  }
5042
5043
5044 \f
5045 /* Reconstitute a mode for a __sync intrinsic operation.  Since the type of
5046    the pointer in these functions is void*, the tree optimizers may remove
5047    casts.  The mode computed in expand_builtin isn't reliable either, due
5048    to __sync_bool_compare_and_swap.
5049
5050    FCODE_DIFF should be fcode - base, where base is the FOO_1 code for the
5051    group of builtins.  This gives us log2 of the mode size.  */
5052
5053 static inline enum machine_mode
5054 get_builtin_sync_mode (int fcode_diff)
5055 {
5056   /* The size is not negotiable, so ask not to get BLKmode in return
5057      if the target indicates that a smaller size would be better.  */
5058   return mode_for_size (BITS_PER_UNIT << fcode_diff, MODE_INT, 0);
5059 }
5060
5061 /* Expand the memory expression LOC and return the appropriate memory operand
5062    for the builtin_sync operations.  */
5063
5064 static rtx
5065 get_builtin_sync_mem (tree loc, enum machine_mode mode)
5066 {
5067   rtx addr, mem;
5068
5069   addr = expand_expr (loc, NULL_RTX, ptr_mode, EXPAND_SUM);
5070   addr = convert_memory_address (Pmode, addr);
5071
5072   /* Note that we explicitly do not want any alias information for this
5073      memory, so that we kill all other live memories.  Otherwise we don't
5074      satisfy the full barrier semantics of the intrinsic.  */
5075   mem = validize_mem (gen_rtx_MEM (mode, addr));
5076
5077   /* The alignment needs to be at least according to that of the mode.  */
5078   set_mem_align (mem, MAX (GET_MODE_ALIGNMENT (mode),
5079                            get_pointer_alignment (loc)));
5080   set_mem_alias_set (mem, ALIAS_SET_MEMORY_BARRIER);
5081   MEM_VOLATILE_P (mem) = 1;
5082
5083   return mem;
5084 }
5085
5086 /* Expand the __sync_xxx_and_fetch and __sync_fetch_and_xxx intrinsics.
5087    EXP is the CALL_EXPR.  CODE is the rtx code
5088    that corresponds to the arithmetic or logical operation from the name;
5089    an exception here is that NOT actually means NAND.  TARGET is an optional
5090    place for us to store the results; AFTER is true if this is the
5091    fetch_and_xxx form.  IGNORE is true if we don't actually care about
5092    the result of the operation at all.  */
5093
5094 static rtx
5095 expand_builtin_sync_operation (enum machine_mode mode, tree exp,
5096                                enum rtx_code code, bool after,
5097                                rtx target, bool ignore)
5098 {
5099   rtx val, mem;
5100   enum machine_mode old_mode;
5101   location_t loc = EXPR_LOCATION (exp);
5102
5103   if (code == NOT && warn_sync_nand)
5104     {
5105       tree fndecl = get_callee_fndecl (exp);
5106       enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5107
5108       static bool warned_f_a_n, warned_n_a_f;
5109
5110       switch (fcode)
5111         {
5112         case BUILT_IN_SYNC_FETCH_AND_NAND_1:
5113         case BUILT_IN_SYNC_FETCH_AND_NAND_2:
5114         case BUILT_IN_SYNC_FETCH_AND_NAND_4:
5115         case BUILT_IN_SYNC_FETCH_AND_NAND_8:
5116         case BUILT_IN_SYNC_FETCH_AND_NAND_16:
5117
5118           if (warned_f_a_n)
5119             break;
5120
5121           fndecl = implicit_built_in_decls[BUILT_IN_SYNC_FETCH_AND_NAND_N];
5122           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
5123           warned_f_a_n = true;
5124           break;
5125
5126         case BUILT_IN_SYNC_NAND_AND_FETCH_1:
5127         case BUILT_IN_SYNC_NAND_AND_FETCH_2:
5128         case BUILT_IN_SYNC_NAND_AND_FETCH_4:
5129         case BUILT_IN_SYNC_NAND_AND_FETCH_8:
5130         case BUILT_IN_SYNC_NAND_AND_FETCH_16:
5131
5132           if (warned_n_a_f)
5133             break;
5134
5135           fndecl = implicit_built_in_decls[BUILT_IN_SYNC_NAND_AND_FETCH_N];
5136           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
5137           warned_n_a_f = true;
5138           break;
5139
5140         default:
5141           gcc_unreachable ();
5142         }
5143     }
5144
5145   /* Expand the operands.  */
5146   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5147
5148   val = expand_expr (CALL_EXPR_ARG (exp, 1), NULL_RTX, mode, EXPAND_NORMAL);
5149   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5150      of CONST_INTs, where we know the old_mode only from the call argument.  */
5151   old_mode = GET_MODE (val);
5152   if (old_mode == VOIDmode)
5153     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 1)));
5154   val = convert_modes (mode, old_mode, val, 1);
5155
5156   if (ignore)
5157     return expand_sync_operation (mem, val, code);
5158   else
5159     return expand_sync_fetch_operation (mem, val, code, after, target);
5160 }
5161
5162 /* Expand the __sync_val_compare_and_swap and __sync_bool_compare_and_swap
5163    intrinsics. EXP is the CALL_EXPR.  IS_BOOL is
5164    true if this is the boolean form.  TARGET is a place for us to store the
5165    results; this is NOT optional if IS_BOOL is true.  */
5166
5167 static rtx
5168 expand_builtin_compare_and_swap (enum machine_mode mode, tree exp,
5169                                  bool is_bool, rtx target)
5170 {
5171   rtx old_val, new_val, mem;
5172   enum machine_mode old_mode;
5173
5174   /* Expand the operands.  */
5175   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5176
5177
5178   old_val = expand_expr (CALL_EXPR_ARG (exp, 1), NULL_RTX,
5179                          mode, EXPAND_NORMAL);
5180   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5181      of CONST_INTs, where we know the old_mode only from the call argument.  */
5182   old_mode = GET_MODE (old_val);
5183   if (old_mode == VOIDmode)
5184     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 1)));
5185   old_val = convert_modes (mode, old_mode, old_val, 1);
5186
5187   new_val = expand_expr (CALL_EXPR_ARG (exp, 2), NULL_RTX,
5188                          mode, EXPAND_NORMAL);
5189   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5190      of CONST_INTs, where we know the old_mode only from the call argument.  */
5191   old_mode = GET_MODE (new_val);
5192   if (old_mode == VOIDmode)
5193     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 2)));
5194   new_val = convert_modes (mode, old_mode, new_val, 1);
5195
5196   if (is_bool)
5197     return expand_bool_compare_and_swap (mem, old_val, new_val, target);
5198   else
5199     return expand_val_compare_and_swap (mem, old_val, new_val, target);
5200 }
5201
5202 /* Expand the __sync_lock_test_and_set intrinsic.  Note that the most
5203    general form is actually an atomic exchange, and some targets only
5204    support a reduced form with the second argument being a constant 1.
5205    EXP is the CALL_EXPR; TARGET is an optional place for us to store
5206    the results.  */
5207
5208 static rtx
5209 expand_builtin_sync_lock_test_and_set (enum machine_mode mode, tree exp,
5210                                   rtx target)
5211 {
5212   rtx val, mem;
5213   enum machine_mode old_mode;
5214
5215   /* Expand the operands.  */
5216   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5217   val = expand_expr (CALL_EXPR_ARG (exp, 1), NULL_RTX, mode, EXPAND_NORMAL);
5218   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5219      of CONST_INTs, where we know the old_mode only from the call argument.  */
5220   old_mode = GET_MODE (val);
5221   if (old_mode == VOIDmode)
5222     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 1)));
5223   val = convert_modes (mode, old_mode, val, 1);
5224
5225   return expand_sync_lock_test_and_set (mem, val, target);
5226 }
5227
5228 /* Expand the __sync_synchronize intrinsic.  */
5229
5230 static void
5231 expand_builtin_sync_synchronize (void)
5232 {
5233   gimple x;
5234   VEC (tree, gc) *v_clobbers;
5235
5236 #ifdef HAVE_memory_barrier
5237   if (HAVE_memory_barrier)
5238     {
5239       emit_insn (gen_memory_barrier ());
5240       return;
5241     }
5242 #endif
5243
5244   if (synchronize_libfunc != NULL_RTX)
5245     {
5246       emit_library_call (synchronize_libfunc, LCT_NORMAL, VOIDmode, 0);
5247       return;
5248     }
5249
5250   /* If no explicit memory barrier instruction is available, create an
5251      empty asm stmt with a memory clobber.  */
5252   v_clobbers = VEC_alloc (tree, gc, 1);
5253   VEC_quick_push (tree, v_clobbers,
5254                   tree_cons (NULL, build_string (6, "memory"), NULL));
5255   x = gimple_build_asm_vec ("", NULL, NULL, v_clobbers, NULL);
5256   gimple_asm_set_volatile (x, true);
5257   expand_asm_stmt (x);
5258 }
5259
5260 /* Expand the __sync_lock_release intrinsic.  EXP is the CALL_EXPR.  */
5261
5262 static void
5263 expand_builtin_sync_lock_release (enum machine_mode mode, tree exp)
5264 {
5265   struct expand_operand ops[2];
5266   enum insn_code icode;
5267   rtx mem;
5268
5269   /* Expand the operands.  */
5270   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5271
5272   /* If there is an explicit operation in the md file, use it.  */
5273   icode = direct_optab_handler (sync_lock_release_optab, mode);
5274   if (icode != CODE_FOR_nothing)
5275     {
5276       create_fixed_operand (&ops[0], mem);
5277       create_input_operand (&ops[1], const0_rtx, mode);
5278       if (maybe_expand_insn (icode, 2, ops))
5279         return;
5280     }
5281
5282   /* Otherwise we can implement this operation by emitting a barrier
5283      followed by a store of zero.  */
5284   expand_builtin_sync_synchronize ();
5285   emit_move_insn (mem, const0_rtx);
5286 }
5287 \f
5288 /* Expand an expression EXP that calls a built-in function,
5289    with result going to TARGET if that's convenient
5290    (and in mode MODE if that's convenient).
5291    SUBTARGET may be used as the target for computing one of EXP's operands.
5292    IGNORE is nonzero if the value is to be ignored.  */
5293
5294 rtx
5295 expand_builtin (tree exp, rtx target, rtx subtarget, enum machine_mode mode,
5296                 int ignore)
5297 {
5298   tree fndecl = get_callee_fndecl (exp);
5299   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5300   enum machine_mode target_mode = TYPE_MODE (TREE_TYPE (exp));
5301   int flags;
5302
5303   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
5304     return targetm.expand_builtin (exp, target, subtarget, mode, ignore);
5305
5306   /* When not optimizing, generate calls to library functions for a certain
5307      set of builtins.  */
5308   if (!optimize
5309       && !called_as_built_in (fndecl)
5310       && DECL_ASSEMBLER_NAME_SET_P (fndecl)
5311       && fcode != BUILT_IN_ALLOCA
5312       && fcode != BUILT_IN_FREE)
5313     return expand_call (exp, target, ignore);
5314
5315   /* The built-in function expanders test for target == const0_rtx
5316      to determine whether the function's result will be ignored.  */
5317   if (ignore)
5318     target = const0_rtx;
5319
5320   /* If the result of a pure or const built-in function is ignored, and
5321      none of its arguments are volatile, we can avoid expanding the
5322      built-in call and just evaluate the arguments for side-effects.  */
5323   if (target == const0_rtx
5324       && ((flags = flags_from_decl_or_type (fndecl)) & (ECF_CONST | ECF_PURE))
5325       && !(flags & ECF_LOOPING_CONST_OR_PURE))
5326     {
5327       bool volatilep = false;
5328       tree arg;
5329       call_expr_arg_iterator iter;
5330
5331       FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5332         if (TREE_THIS_VOLATILE (arg))
5333           {
5334             volatilep = true;
5335             break;
5336           }
5337
5338       if (! volatilep)
5339         {
5340           FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5341             expand_expr (arg, const0_rtx, VOIDmode, EXPAND_NORMAL);
5342           return const0_rtx;
5343         }
5344     }
5345
5346   switch (fcode)
5347     {
5348     CASE_FLT_FN (BUILT_IN_FABS):
5349       target = expand_builtin_fabs (exp, target, subtarget);
5350       if (target)
5351         return target;
5352       break;
5353
5354     CASE_FLT_FN (BUILT_IN_COPYSIGN):
5355       target = expand_builtin_copysign (exp, target, subtarget);
5356       if (target)
5357         return target;
5358       break;
5359
5360       /* Just do a normal library call if we were unable to fold
5361          the values.  */
5362     CASE_FLT_FN (BUILT_IN_CABS):
5363       break;
5364
5365     CASE_FLT_FN (BUILT_IN_EXP):
5366     CASE_FLT_FN (BUILT_IN_EXP10):
5367     CASE_FLT_FN (BUILT_IN_POW10):
5368     CASE_FLT_FN (BUILT_IN_EXP2):
5369     CASE_FLT_FN (BUILT_IN_EXPM1):
5370     CASE_FLT_FN (BUILT_IN_LOGB):
5371     CASE_FLT_FN (BUILT_IN_LOG):
5372     CASE_FLT_FN (BUILT_IN_LOG10):
5373     CASE_FLT_FN (BUILT_IN_LOG2):
5374     CASE_FLT_FN (BUILT_IN_LOG1P):
5375     CASE_FLT_FN (BUILT_IN_TAN):
5376     CASE_FLT_FN (BUILT_IN_ASIN):
5377     CASE_FLT_FN (BUILT_IN_ACOS):
5378     CASE_FLT_FN (BUILT_IN_ATAN):
5379     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
5380       /* Treat these like sqrt only if unsafe math optimizations are allowed,
5381          because of possible accuracy problems.  */
5382       if (! flag_unsafe_math_optimizations)
5383         break;
5384     CASE_FLT_FN (BUILT_IN_SQRT):
5385     CASE_FLT_FN (BUILT_IN_FLOOR):
5386     CASE_FLT_FN (BUILT_IN_CEIL):
5387     CASE_FLT_FN (BUILT_IN_TRUNC):
5388     CASE_FLT_FN (BUILT_IN_ROUND):
5389     CASE_FLT_FN (BUILT_IN_NEARBYINT):
5390     CASE_FLT_FN (BUILT_IN_RINT):
5391       target = expand_builtin_mathfn (exp, target, subtarget);
5392       if (target)
5393         return target;
5394       break;
5395
5396     CASE_FLT_FN (BUILT_IN_FMA):
5397       target = expand_builtin_mathfn_ternary (exp, target, subtarget);
5398       if (target)
5399         return target;
5400       break;
5401
5402     CASE_FLT_FN (BUILT_IN_ILOGB):
5403       if (! flag_unsafe_math_optimizations)
5404         break;
5405     CASE_FLT_FN (BUILT_IN_ISINF):
5406     CASE_FLT_FN (BUILT_IN_FINITE):
5407     case BUILT_IN_ISFINITE:
5408     case BUILT_IN_ISNORMAL:
5409       target = expand_builtin_interclass_mathfn (exp, target);
5410       if (target)
5411         return target;
5412       break;
5413
5414     CASE_FLT_FN (BUILT_IN_LCEIL):
5415     CASE_FLT_FN (BUILT_IN_LLCEIL):
5416     CASE_FLT_FN (BUILT_IN_LFLOOR):
5417     CASE_FLT_FN (BUILT_IN_LLFLOOR):
5418       target = expand_builtin_int_roundingfn (exp, target);
5419       if (target)
5420         return target;
5421       break;
5422
5423     CASE_FLT_FN (BUILT_IN_LRINT):
5424     CASE_FLT_FN (BUILT_IN_LLRINT):
5425     CASE_FLT_FN (BUILT_IN_LROUND):
5426     CASE_FLT_FN (BUILT_IN_LLROUND):
5427       target = expand_builtin_int_roundingfn_2 (exp, target);
5428       if (target)
5429         return target;
5430       break;
5431
5432     CASE_FLT_FN (BUILT_IN_POWI):
5433       target = expand_builtin_powi (exp, target);
5434       if (target)
5435         return target;
5436       break;
5437
5438     CASE_FLT_FN (BUILT_IN_ATAN2):
5439     CASE_FLT_FN (BUILT_IN_LDEXP):
5440     CASE_FLT_FN (BUILT_IN_SCALB):
5441     CASE_FLT_FN (BUILT_IN_SCALBN):
5442     CASE_FLT_FN (BUILT_IN_SCALBLN):
5443       if (! flag_unsafe_math_optimizations)
5444         break;
5445
5446     CASE_FLT_FN (BUILT_IN_FMOD):
5447     CASE_FLT_FN (BUILT_IN_REMAINDER):
5448     CASE_FLT_FN (BUILT_IN_DREM):
5449     CASE_FLT_FN (BUILT_IN_POW):
5450       target = expand_builtin_mathfn_2 (exp, target, subtarget);
5451       if (target)
5452         return target;
5453       break;
5454
5455     CASE_FLT_FN (BUILT_IN_CEXPI):
5456       target = expand_builtin_cexpi (exp, target);
5457       gcc_assert (target);
5458       return target;
5459
5460     CASE_FLT_FN (BUILT_IN_SIN):
5461     CASE_FLT_FN (BUILT_IN_COS):
5462       if (! flag_unsafe_math_optimizations)
5463         break;
5464       target = expand_builtin_mathfn_3 (exp, target, subtarget);
5465       if (target)
5466         return target;
5467       break;
5468
5469     CASE_FLT_FN (BUILT_IN_SINCOS):
5470       if (! flag_unsafe_math_optimizations)
5471         break;
5472       target = expand_builtin_sincos (exp);
5473       if (target)
5474         return target;
5475       break;
5476
5477     case BUILT_IN_APPLY_ARGS:
5478       return expand_builtin_apply_args ();
5479
5480       /* __builtin_apply (FUNCTION, ARGUMENTS, ARGSIZE) invokes
5481          FUNCTION with a copy of the parameters described by
5482          ARGUMENTS, and ARGSIZE.  It returns a block of memory
5483          allocated on the stack into which is stored all the registers
5484          that might possibly be used for returning the result of a
5485          function.  ARGUMENTS is the value returned by
5486          __builtin_apply_args.  ARGSIZE is the number of bytes of
5487          arguments that must be copied.  ??? How should this value be
5488          computed?  We'll also need a safe worst case value for varargs
5489          functions.  */
5490     case BUILT_IN_APPLY:
5491       if (!validate_arglist (exp, POINTER_TYPE,
5492                              POINTER_TYPE, INTEGER_TYPE, VOID_TYPE)
5493           && !validate_arglist (exp, REFERENCE_TYPE,
5494                                 POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
5495         return const0_rtx;
5496       else
5497         {
5498           rtx ops[3];
5499
5500           ops[0] = expand_normal (CALL_EXPR_ARG (exp, 0));
5501           ops[1] = expand_normal (CALL_EXPR_ARG (exp, 1));
5502           ops[2] = expand_normal (CALL_EXPR_ARG (exp, 2));
5503
5504           return expand_builtin_apply (ops[0], ops[1], ops[2]);
5505         }
5506
5507       /* __builtin_return (RESULT) causes the function to return the
5508          value described by RESULT.  RESULT is address of the block of
5509          memory returned by __builtin_apply.  */
5510     case BUILT_IN_RETURN:
5511       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
5512         expand_builtin_return (expand_normal (CALL_EXPR_ARG (exp, 0)));
5513       return const0_rtx;
5514
5515     case BUILT_IN_SAVEREGS:
5516       return expand_builtin_saveregs ();
5517
5518     case BUILT_IN_VA_ARG_PACK:
5519       /* All valid uses of __builtin_va_arg_pack () are removed during
5520          inlining.  */
5521       error ("%Kinvalid use of %<__builtin_va_arg_pack ()%>", exp);
5522       return const0_rtx;
5523
5524     case BUILT_IN_VA_ARG_PACK_LEN:
5525       /* All valid uses of __builtin_va_arg_pack_len () are removed during
5526          inlining.  */
5527       error ("%Kinvalid use of %<__builtin_va_arg_pack_len ()%>", exp);
5528       return const0_rtx;
5529
5530       /* Return the address of the first anonymous stack arg.  */
5531     case BUILT_IN_NEXT_ARG:
5532       if (fold_builtin_next_arg (exp, false))
5533         return const0_rtx;
5534       return expand_builtin_next_arg ();
5535
5536     case BUILT_IN_CLEAR_CACHE:
5537       target = expand_builtin___clear_cache (exp);
5538       if (target)
5539         return target;
5540       break;
5541
5542     case BUILT_IN_CLASSIFY_TYPE:
5543       return expand_builtin_classify_type (exp);
5544
5545     case BUILT_IN_CONSTANT_P:
5546       return const0_rtx;
5547
5548     case BUILT_IN_FRAME_ADDRESS:
5549     case BUILT_IN_RETURN_ADDRESS:
5550       return expand_builtin_frame_address (fndecl, exp);
5551
5552     /* Returns the address of the area where the structure is returned.
5553        0 otherwise.  */
5554     case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
5555       if (call_expr_nargs (exp) != 0
5556           || ! AGGREGATE_TYPE_P (TREE_TYPE (TREE_TYPE (current_function_decl)))
5557           || !MEM_P (DECL_RTL (DECL_RESULT (current_function_decl))))
5558         return const0_rtx;
5559       else
5560         return XEXP (DECL_RTL (DECL_RESULT (current_function_decl)), 0);
5561
5562     case BUILT_IN_ALLOCA:
5563       /* If the allocation stems from the declaration of a variable-sized
5564          object, it cannot accumulate.  */
5565       target = expand_builtin_alloca (exp, CALL_ALLOCA_FOR_VAR_P (exp));
5566       if (target)
5567         return target;
5568       break;
5569
5570     case BUILT_IN_STACK_SAVE:
5571       return expand_stack_save ();
5572
5573     case BUILT_IN_STACK_RESTORE:
5574       expand_stack_restore (CALL_EXPR_ARG (exp, 0));
5575       return const0_rtx;
5576
5577     case BUILT_IN_BSWAP32:
5578     case BUILT_IN_BSWAP64:
5579       target = expand_builtin_bswap (exp, target, subtarget);
5580
5581       if (target)
5582         return target;
5583       break;
5584
5585     CASE_INT_FN (BUILT_IN_FFS):
5586     case BUILT_IN_FFSIMAX:
5587       target = expand_builtin_unop (target_mode, exp, target,
5588                                     subtarget, ffs_optab);
5589       if (target)
5590         return target;
5591       break;
5592
5593     CASE_INT_FN (BUILT_IN_CLZ):
5594     case BUILT_IN_CLZIMAX:
5595       target = expand_builtin_unop (target_mode, exp, target,
5596                                     subtarget, clz_optab);
5597       if (target)
5598         return target;
5599       break;
5600
5601     CASE_INT_FN (BUILT_IN_CTZ):
5602     case BUILT_IN_CTZIMAX:
5603       target = expand_builtin_unop (target_mode, exp, target,
5604                                     subtarget, ctz_optab);
5605       if (target)
5606         return target;
5607       break;
5608
5609     CASE_INT_FN (BUILT_IN_CLRSB):
5610     case BUILT_IN_CLRSBIMAX:
5611       target = expand_builtin_unop (target_mode, exp, target,
5612                                     subtarget, clrsb_optab);
5613       if (target)
5614         return target;
5615       break;
5616
5617     CASE_INT_FN (BUILT_IN_POPCOUNT):
5618     case BUILT_IN_POPCOUNTIMAX:
5619       target = expand_builtin_unop (target_mode, exp, target,
5620                                     subtarget, popcount_optab);
5621       if (target)
5622         return target;
5623       break;
5624
5625     CASE_INT_FN (BUILT_IN_PARITY):
5626     case BUILT_IN_PARITYIMAX:
5627       target = expand_builtin_unop (target_mode, exp, target,
5628                                     subtarget, parity_optab);
5629       if (target)
5630         return target;
5631       break;
5632
5633     case BUILT_IN_STRLEN:
5634       target = expand_builtin_strlen (exp, target, target_mode);
5635       if (target)
5636         return target;
5637       break;
5638
5639     case BUILT_IN_STRCPY:
5640       target = expand_builtin_strcpy (exp, target);
5641       if (target)
5642         return target;
5643       break;
5644
5645     case BUILT_IN_STRNCPY:
5646       target = expand_builtin_strncpy (exp, target);
5647       if (target)
5648         return target;
5649       break;
5650
5651     case BUILT_IN_STPCPY:
5652       target = expand_builtin_stpcpy (exp, target, mode);
5653       if (target)
5654         return target;
5655       break;
5656
5657     case BUILT_IN_MEMCPY:
5658       target = expand_builtin_memcpy (exp, target);
5659       if (target)
5660         return target;
5661       break;
5662
5663     case BUILT_IN_MEMPCPY:
5664       target = expand_builtin_mempcpy (exp, target, mode);
5665       if (target)
5666         return target;
5667       break;
5668
5669     case BUILT_IN_MEMSET:
5670       target = expand_builtin_memset (exp, target, mode);
5671       if (target)
5672         return target;
5673       break;
5674
5675     case BUILT_IN_BZERO:
5676       target = expand_builtin_bzero (exp);
5677       if (target)
5678         return target;
5679       break;
5680
5681     case BUILT_IN_STRCMP:
5682       target = expand_builtin_strcmp (exp, target);
5683       if (target)
5684         return target;
5685       break;
5686
5687     case BUILT_IN_STRNCMP:
5688       target = expand_builtin_strncmp (exp, target, mode);
5689       if (target)
5690         return target;
5691       break;
5692
5693     case BUILT_IN_BCMP:
5694     case BUILT_IN_MEMCMP:
5695       target = expand_builtin_memcmp (exp, target, mode);
5696       if (target)
5697         return target;
5698       break;
5699
5700     case BUILT_IN_SETJMP:
5701       /* This should have been lowered to the builtins below.  */
5702       gcc_unreachable ();
5703
5704     case BUILT_IN_SETJMP_SETUP:
5705       /* __builtin_setjmp_setup is passed a pointer to an array of five words
5706           and the receiver label.  */
5707       if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
5708         {
5709           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
5710                                       VOIDmode, EXPAND_NORMAL);
5711           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 1), 0);
5712           rtx label_r = label_rtx (label);
5713
5714           /* This is copied from the handling of non-local gotos.  */
5715           expand_builtin_setjmp_setup (buf_addr, label_r);
5716           nonlocal_goto_handler_labels
5717             = gen_rtx_EXPR_LIST (VOIDmode, label_r,
5718                                  nonlocal_goto_handler_labels);
5719           /* ??? Do not let expand_label treat us as such since we would
5720              not want to be both on the list of non-local labels and on
5721              the list of forced labels.  */
5722           FORCED_LABEL (label) = 0;
5723           return const0_rtx;
5724         }
5725       break;
5726
5727     case BUILT_IN_SETJMP_DISPATCHER:
5728        /* __builtin_setjmp_dispatcher is passed the dispatcher label.  */
5729       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
5730         {
5731           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
5732           rtx label_r = label_rtx (label);
5733
5734           /* Remove the dispatcher label from the list of non-local labels
5735              since the receiver labels have been added to it above.  */
5736           remove_node_from_expr_list (label_r, &nonlocal_goto_handler_labels);
5737           return const0_rtx;
5738         }
5739       break;
5740
5741     case BUILT_IN_SETJMP_RECEIVER:
5742        /* __builtin_setjmp_receiver is passed the receiver label.  */
5743       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
5744         {
5745           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
5746           rtx label_r = label_rtx (label);
5747
5748           expand_builtin_setjmp_receiver (label_r);
5749           return const0_rtx;
5750         }
5751       break;
5752
5753       /* __builtin_longjmp is passed a pointer to an array of five words.
5754          It's similar to the C library longjmp function but works with
5755          __builtin_setjmp above.  */
5756     case BUILT_IN_LONGJMP:
5757       if (validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
5758         {
5759           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
5760                                       VOIDmode, EXPAND_NORMAL);
5761           rtx value = expand_normal (CALL_EXPR_ARG (exp, 1));
5762
5763           if (value != const1_rtx)
5764             {
5765               error ("%<__builtin_longjmp%> second argument must be 1");
5766               return const0_rtx;
5767             }
5768
5769           expand_builtin_longjmp (buf_addr, value);
5770           return const0_rtx;
5771         }
5772       break;
5773
5774     case BUILT_IN_NONLOCAL_GOTO:
5775       target = expand_builtin_nonlocal_goto (exp);
5776       if (target)
5777         return target;
5778       break;
5779
5780       /* This updates the setjmp buffer that is its argument with the value
5781          of the current stack pointer.  */
5782     case BUILT_IN_UPDATE_SETJMP_BUF:
5783       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
5784         {
5785           rtx buf_addr
5786             = expand_normal (CALL_EXPR_ARG (exp, 0));
5787
5788           expand_builtin_update_setjmp_buf (buf_addr);
5789           return const0_rtx;
5790         }
5791       break;
5792
5793     case BUILT_IN_TRAP:
5794       expand_builtin_trap ();
5795       return const0_rtx;
5796
5797     case BUILT_IN_UNREACHABLE:
5798       expand_builtin_unreachable ();
5799       return const0_rtx;
5800
5801     CASE_FLT_FN (BUILT_IN_SIGNBIT):
5802     case BUILT_IN_SIGNBITD32:
5803     case BUILT_IN_SIGNBITD64:
5804     case BUILT_IN_SIGNBITD128:
5805       target = expand_builtin_signbit (exp, target);
5806       if (target)
5807         return target;
5808       break;
5809
5810       /* Various hooks for the DWARF 2 __throw routine.  */
5811     case BUILT_IN_UNWIND_INIT:
5812       expand_builtin_unwind_init ();
5813       return const0_rtx;
5814     case BUILT_IN_DWARF_CFA:
5815       return virtual_cfa_rtx;
5816 #ifdef DWARF2_UNWIND_INFO
5817     case BUILT_IN_DWARF_SP_COLUMN:
5818       return expand_builtin_dwarf_sp_column ();
5819     case BUILT_IN_INIT_DWARF_REG_SIZES:
5820       expand_builtin_init_dwarf_reg_sizes (CALL_EXPR_ARG (exp, 0));
5821       return const0_rtx;
5822 #endif
5823     case BUILT_IN_FROB_RETURN_ADDR:
5824       return expand_builtin_frob_return_addr (CALL_EXPR_ARG (exp, 0));
5825     case BUILT_IN_EXTRACT_RETURN_ADDR:
5826       return expand_builtin_extract_return_addr (CALL_EXPR_ARG (exp, 0));
5827     case BUILT_IN_EH_RETURN:
5828       expand_builtin_eh_return (CALL_EXPR_ARG (exp, 0),
5829                                 CALL_EXPR_ARG (exp, 1));
5830       return const0_rtx;
5831 #ifdef EH_RETURN_DATA_REGNO
5832     case BUILT_IN_EH_RETURN_DATA_REGNO:
5833       return expand_builtin_eh_return_data_regno (exp);
5834 #endif
5835     case BUILT_IN_EXTEND_POINTER:
5836       return expand_builtin_extend_pointer (CALL_EXPR_ARG (exp, 0));
5837     case BUILT_IN_EH_POINTER:
5838       return expand_builtin_eh_pointer (exp);
5839     case BUILT_IN_EH_FILTER:
5840       return expand_builtin_eh_filter (exp);
5841     case BUILT_IN_EH_COPY_VALUES:
5842       return expand_builtin_eh_copy_values (exp);
5843
5844     case BUILT_IN_VA_START:
5845       return expand_builtin_va_start (exp);
5846     case BUILT_IN_VA_END:
5847       return expand_builtin_va_end (exp);
5848     case BUILT_IN_VA_COPY:
5849       return expand_builtin_va_copy (exp);
5850     case BUILT_IN_EXPECT:
5851       return expand_builtin_expect (exp, target);
5852     case BUILT_IN_ASSUME_ALIGNED:
5853       return expand_builtin_assume_aligned (exp, target);
5854     case BUILT_IN_PREFETCH:
5855       expand_builtin_prefetch (exp);
5856       return const0_rtx;
5857
5858     case BUILT_IN_INIT_TRAMPOLINE:
5859       return expand_builtin_init_trampoline (exp);
5860     case BUILT_IN_ADJUST_TRAMPOLINE:
5861       return expand_builtin_adjust_trampoline (exp);
5862
5863     case BUILT_IN_FORK:
5864     case BUILT_IN_EXECL:
5865     case BUILT_IN_EXECV:
5866     case BUILT_IN_EXECLP:
5867     case BUILT_IN_EXECLE:
5868     case BUILT_IN_EXECVP:
5869     case BUILT_IN_EXECVE:
5870       target = expand_builtin_fork_or_exec (fndecl, exp, target, ignore);
5871       if (target)
5872         return target;
5873       break;
5874
5875     case BUILT_IN_SYNC_FETCH_AND_ADD_1:
5876     case BUILT_IN_SYNC_FETCH_AND_ADD_2:
5877     case BUILT_IN_SYNC_FETCH_AND_ADD_4:
5878     case BUILT_IN_SYNC_FETCH_AND_ADD_8:
5879     case BUILT_IN_SYNC_FETCH_AND_ADD_16:
5880       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_ADD_1);
5881       target = expand_builtin_sync_operation (mode, exp, PLUS,
5882                                               false, target, ignore);
5883       if (target)
5884         return target;
5885       break;
5886
5887     case BUILT_IN_SYNC_FETCH_AND_SUB_1:
5888     case BUILT_IN_SYNC_FETCH_AND_SUB_2:
5889     case BUILT_IN_SYNC_FETCH_AND_SUB_4:
5890     case BUILT_IN_SYNC_FETCH_AND_SUB_8:
5891     case BUILT_IN_SYNC_FETCH_AND_SUB_16:
5892       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_SUB_1);
5893       target = expand_builtin_sync_operation (mode, exp, MINUS,
5894                                               false, target, ignore);
5895       if (target)
5896         return target;
5897       break;
5898
5899     case BUILT_IN_SYNC_FETCH_AND_OR_1:
5900     case BUILT_IN_SYNC_FETCH_AND_OR_2:
5901     case BUILT_IN_SYNC_FETCH_AND_OR_4:
5902     case BUILT_IN_SYNC_FETCH_AND_OR_8:
5903     case BUILT_IN_SYNC_FETCH_AND_OR_16:
5904       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_OR_1);
5905       target = expand_builtin_sync_operation (mode, exp, IOR,
5906                                               false, target, ignore);
5907       if (target)
5908         return target;
5909       break;
5910
5911     case BUILT_IN_SYNC_FETCH_AND_AND_1:
5912     case BUILT_IN_SYNC_FETCH_AND_AND_2:
5913     case BUILT_IN_SYNC_FETCH_AND_AND_4:
5914     case BUILT_IN_SYNC_FETCH_AND_AND_8:
5915     case BUILT_IN_SYNC_FETCH_AND_AND_16:
5916       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_AND_1);
5917       target = expand_builtin_sync_operation (mode, exp, AND,
5918                                               false, target, ignore);
5919       if (target)
5920         return target;
5921       break;
5922
5923     case BUILT_IN_SYNC_FETCH_AND_XOR_1:
5924     case BUILT_IN_SYNC_FETCH_AND_XOR_2:
5925     case BUILT_IN_SYNC_FETCH_AND_XOR_4:
5926     case BUILT_IN_SYNC_FETCH_AND_XOR_8:
5927     case BUILT_IN_SYNC_FETCH_AND_XOR_16:
5928       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_XOR_1);
5929       target = expand_builtin_sync_operation (mode, exp, XOR,
5930                                               false, target, ignore);
5931       if (target)
5932         return target;
5933       break;
5934
5935     case BUILT_IN_SYNC_FETCH_AND_NAND_1:
5936     case BUILT_IN_SYNC_FETCH_AND_NAND_2:
5937     case BUILT_IN_SYNC_FETCH_AND_NAND_4:
5938     case BUILT_IN_SYNC_FETCH_AND_NAND_8:
5939     case BUILT_IN_SYNC_FETCH_AND_NAND_16:
5940       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_NAND_1);
5941       target = expand_builtin_sync_operation (mode, exp, NOT,
5942                                               false, target, ignore);
5943       if (target)
5944         return target;
5945       break;
5946
5947     case BUILT_IN_SYNC_ADD_AND_FETCH_1:
5948     case BUILT_IN_SYNC_ADD_AND_FETCH_2:
5949     case BUILT_IN_SYNC_ADD_AND_FETCH_4:
5950     case BUILT_IN_SYNC_ADD_AND_FETCH_8:
5951     case BUILT_IN_SYNC_ADD_AND_FETCH_16:
5952       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_ADD_AND_FETCH_1);
5953       target = expand_builtin_sync_operation (mode, exp, PLUS,
5954                                               true, target, ignore);
5955       if (target)
5956         return target;
5957       break;
5958
5959     case BUILT_IN_SYNC_SUB_AND_FETCH_1:
5960     case BUILT_IN_SYNC_SUB_AND_FETCH_2:
5961     case BUILT_IN_SYNC_SUB_AND_FETCH_4:
5962     case BUILT_IN_SYNC_SUB_AND_FETCH_8:
5963     case BUILT_IN_SYNC_SUB_AND_FETCH_16:
5964       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_SUB_AND_FETCH_1);
5965       target = expand_builtin_sync_operation (mode, exp, MINUS,
5966                                               true, target, ignore);
5967       if (target)
5968         return target;
5969       break;
5970
5971     case BUILT_IN_SYNC_OR_AND_FETCH_1:
5972     case BUILT_IN_SYNC_OR_AND_FETCH_2:
5973     case BUILT_IN_SYNC_OR_AND_FETCH_4:
5974     case BUILT_IN_SYNC_OR_AND_FETCH_8:
5975     case BUILT_IN_SYNC_OR_AND_FETCH_16:
5976       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_OR_AND_FETCH_1);
5977       target = expand_builtin_sync_operation (mode, exp, IOR,
5978                                               true, target, ignore);
5979       if (target)
5980         return target;
5981       break;
5982
5983     case BUILT_IN_SYNC_AND_AND_FETCH_1:
5984     case BUILT_IN_SYNC_AND_AND_FETCH_2:
5985     case BUILT_IN_SYNC_AND_AND_FETCH_4:
5986     case BUILT_IN_SYNC_AND_AND_FETCH_8:
5987     case BUILT_IN_SYNC_AND_AND_FETCH_16:
5988       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_AND_AND_FETCH_1);
5989       target = expand_builtin_sync_operation (mode, exp, AND,
5990                                               true, target, ignore);
5991       if (target)
5992         return target;
5993       break;
5994
5995     case BUILT_IN_SYNC_XOR_AND_FETCH_1:
5996     case BUILT_IN_SYNC_XOR_AND_FETCH_2:
5997     case BUILT_IN_SYNC_XOR_AND_FETCH_4:
5998     case BUILT_IN_SYNC_XOR_AND_FETCH_8:
5999     case BUILT_IN_SYNC_XOR_AND_FETCH_16:
6000       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_XOR_AND_FETCH_1);
6001       target = expand_builtin_sync_operation (mode, exp, XOR,
6002                                               true, target, ignore);
6003       if (target)
6004         return target;
6005       break;
6006
6007     case BUILT_IN_SYNC_NAND_AND_FETCH_1:
6008     case BUILT_IN_SYNC_NAND_AND_FETCH_2:
6009     case BUILT_IN_SYNC_NAND_AND_FETCH_4:
6010     case BUILT_IN_SYNC_NAND_AND_FETCH_8:
6011     case BUILT_IN_SYNC_NAND_AND_FETCH_16:
6012       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_NAND_AND_FETCH_1);
6013       target = expand_builtin_sync_operation (mode, exp, NOT,
6014                                               true, target, ignore);
6015       if (target)
6016         return target;
6017       break;
6018
6019     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1:
6020     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_2:
6021     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_4:
6022     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_8:
6023     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_16:
6024       if (mode == VOIDmode)
6025         mode = TYPE_MODE (boolean_type_node);
6026       if (!target || !register_operand (target, mode))
6027         target = gen_reg_rtx (mode);
6028
6029       mode = get_builtin_sync_mode 
6030                                 (fcode - BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1);
6031       target = expand_builtin_compare_and_swap (mode, exp, true, target);
6032       if (target)
6033         return target;
6034       break;
6035
6036     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_1:
6037     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_2:
6038     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_4:
6039     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_8:
6040     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_16:
6041       mode = get_builtin_sync_mode 
6042                                 (fcode - BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_1);
6043       target = expand_builtin_compare_and_swap (mode, exp, false, target);
6044       if (target)
6045         return target;
6046       break;
6047
6048     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_1:
6049     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_2:
6050     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_4:
6051     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_8:
6052     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_16:
6053       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_LOCK_TEST_AND_SET_1);
6054       target = expand_builtin_sync_lock_test_and_set (mode, exp, target);
6055       if (target)
6056         return target;
6057       break;
6058
6059     case BUILT_IN_SYNC_LOCK_RELEASE_1:
6060     case BUILT_IN_SYNC_LOCK_RELEASE_2:
6061     case BUILT_IN_SYNC_LOCK_RELEASE_4:
6062     case BUILT_IN_SYNC_LOCK_RELEASE_8:
6063     case BUILT_IN_SYNC_LOCK_RELEASE_16:
6064       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_LOCK_RELEASE_1);
6065       expand_builtin_sync_lock_release (mode, exp);
6066       return const0_rtx;
6067
6068     case BUILT_IN_SYNC_SYNCHRONIZE:
6069       expand_builtin_sync_synchronize ();
6070       return const0_rtx;
6071
6072     case BUILT_IN_OBJECT_SIZE:
6073       return expand_builtin_object_size (exp);
6074
6075     case BUILT_IN_MEMCPY_CHK:
6076     case BUILT_IN_MEMPCPY_CHK:
6077     case BUILT_IN_MEMMOVE_CHK:
6078     case BUILT_IN_MEMSET_CHK:
6079       target = expand_builtin_memory_chk (exp, target, mode, fcode);
6080       if (target)
6081         return target;
6082       break;
6083
6084     case BUILT_IN_STRCPY_CHK:
6085     case BUILT_IN_STPCPY_CHK:
6086     case BUILT_IN_STRNCPY_CHK:
6087     case BUILT_IN_STRCAT_CHK:
6088     case BUILT_IN_STRNCAT_CHK:
6089     case BUILT_IN_SNPRINTF_CHK:
6090     case BUILT_IN_VSNPRINTF_CHK:
6091       maybe_emit_chk_warning (exp, fcode);
6092       break;
6093
6094     case BUILT_IN_SPRINTF_CHK:
6095     case BUILT_IN_VSPRINTF_CHK:
6096       maybe_emit_sprintf_chk_warning (exp, fcode);
6097       break;
6098
6099     case BUILT_IN_FREE:
6100       maybe_emit_free_warning (exp);
6101       break;
6102
6103     default:    /* just do library call, if unknown builtin */
6104       break;
6105     }
6106
6107   /* The switch statement above can drop through to cause the function
6108      to be called normally.  */
6109   return expand_call (exp, target, ignore);
6110 }
6111
6112 /* Determine whether a tree node represents a call to a built-in
6113    function.  If the tree T is a call to a built-in function with
6114    the right number of arguments of the appropriate types, return
6115    the DECL_FUNCTION_CODE of the call, e.g. BUILT_IN_SQRT.
6116    Otherwise the return value is END_BUILTINS.  */
6117
6118 enum built_in_function
6119 builtin_mathfn_code (const_tree t)
6120 {
6121   const_tree fndecl, arg, parmlist;
6122   const_tree argtype, parmtype;
6123   const_call_expr_arg_iterator iter;
6124
6125   if (TREE_CODE (t) != CALL_EXPR
6126       || TREE_CODE (CALL_EXPR_FN (t)) != ADDR_EXPR)
6127     return END_BUILTINS;
6128
6129   fndecl = get_callee_fndecl (t);
6130   if (fndecl == NULL_TREE
6131       || TREE_CODE (fndecl) != FUNCTION_DECL
6132       || ! DECL_BUILT_IN (fndecl)
6133       || DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
6134     return END_BUILTINS;
6135
6136   parmlist = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
6137   init_const_call_expr_arg_iterator (t, &iter);
6138   for (; parmlist; parmlist = TREE_CHAIN (parmlist))
6139     {
6140       /* If a function doesn't take a variable number of arguments,
6141          the last element in the list will have type `void'.  */
6142       parmtype = TREE_VALUE (parmlist);
6143       if (VOID_TYPE_P (parmtype))
6144         {
6145           if (more_const_call_expr_args_p (&iter))
6146             return END_BUILTINS;
6147           return DECL_FUNCTION_CODE (fndecl);
6148         }
6149
6150       if (! more_const_call_expr_args_p (&iter))
6151         return END_BUILTINS;
6152
6153       arg = next_const_call_expr_arg (&iter);
6154       argtype = TREE_TYPE (arg);
6155
6156       if (SCALAR_FLOAT_TYPE_P (parmtype))
6157         {
6158           if (! SCALAR_FLOAT_TYPE_P (argtype))
6159             return END_BUILTINS;
6160         }
6161       else if (COMPLEX_FLOAT_TYPE_P (parmtype))
6162         {
6163           if (! COMPLEX_FLOAT_TYPE_P (argtype))
6164             return END_BUILTINS;
6165         }
6166       else if (POINTER_TYPE_P (parmtype))
6167         {
6168           if (! POINTER_TYPE_P (argtype))
6169             return END_BUILTINS;
6170         }
6171       else if (INTEGRAL_TYPE_P (parmtype))
6172         {
6173           if (! INTEGRAL_TYPE_P (argtype))
6174             return END_BUILTINS;
6175         }
6176       else
6177         return END_BUILTINS;
6178     }
6179
6180   /* Variable-length argument list.  */
6181   return DECL_FUNCTION_CODE (fndecl);
6182 }
6183
6184 /* Fold a call to __builtin_constant_p, if we know its argument ARG will
6185    evaluate to a constant.  */
6186
6187 static tree
6188 fold_builtin_constant_p (tree arg)
6189 {
6190   /* We return 1 for a numeric type that's known to be a constant
6191      value at compile-time or for an aggregate type that's a
6192      literal constant.  */
6193   STRIP_NOPS (arg);
6194
6195   /* If we know this is a constant, emit the constant of one.  */
6196   if (CONSTANT_CLASS_P (arg)
6197       || (TREE_CODE (arg) == CONSTRUCTOR
6198           && TREE_CONSTANT (arg)))
6199     return integer_one_node;
6200   if (TREE_CODE (arg) == ADDR_EXPR)
6201     {
6202        tree op = TREE_OPERAND (arg, 0);
6203        if (TREE_CODE (op) == STRING_CST
6204            || (TREE_CODE (op) == ARRAY_REF
6205                && integer_zerop (TREE_OPERAND (op, 1))
6206                && TREE_CODE (TREE_OPERAND (op, 0)) == STRING_CST))
6207          return integer_one_node;
6208     }
6209
6210   /* If this expression has side effects, show we don't know it to be a
6211      constant.  Likewise if it's a pointer or aggregate type since in
6212      those case we only want literals, since those are only optimized
6213      when generating RTL, not later.
6214      And finally, if we are compiling an initializer, not code, we
6215      need to return a definite result now; there's not going to be any
6216      more optimization done.  */
6217   if (TREE_SIDE_EFFECTS (arg)
6218       || AGGREGATE_TYPE_P (TREE_TYPE (arg))
6219       || POINTER_TYPE_P (TREE_TYPE (arg))
6220       || cfun == 0
6221       || folding_initializer)
6222     return integer_zero_node;
6223
6224   return NULL_TREE;
6225 }
6226
6227 /* Create builtin_expect with PRED and EXPECTED as its arguments and
6228    return it as a truthvalue.  */
6229
6230 static tree
6231 build_builtin_expect_predicate (location_t loc, tree pred, tree expected)
6232 {
6233   tree fn, arg_types, pred_type, expected_type, call_expr, ret_type;
6234
6235   fn = built_in_decls[BUILT_IN_EXPECT];
6236   arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
6237   ret_type = TREE_TYPE (TREE_TYPE (fn));
6238   pred_type = TREE_VALUE (arg_types);
6239   expected_type = TREE_VALUE (TREE_CHAIN (arg_types));
6240
6241   pred = fold_convert_loc (loc, pred_type, pred);
6242   expected = fold_convert_loc (loc, expected_type, expected);
6243   call_expr = build_call_expr_loc (loc, fn, 2, pred, expected);
6244
6245   return build2 (NE_EXPR, TREE_TYPE (pred), call_expr,
6246                  build_int_cst (ret_type, 0));
6247 }
6248
6249 /* Fold a call to builtin_expect with arguments ARG0 and ARG1.  Return
6250    NULL_TREE if no simplification is possible.  */
6251
6252 static tree
6253 fold_builtin_expect (location_t loc, tree arg0, tree arg1)
6254 {
6255   tree inner, fndecl, inner_arg0;
6256   enum tree_code code;
6257
6258   /* Distribute the expected value over short-circuiting operators.
6259      See through the cast from truthvalue_type_node to long.  */
6260   inner_arg0 = arg0;
6261   while (TREE_CODE (inner_arg0) == NOP_EXPR
6262          && INTEGRAL_TYPE_P (TREE_TYPE (inner_arg0))
6263          && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (inner_arg0, 0))))
6264     inner_arg0 = TREE_OPERAND (inner_arg0, 0);
6265
6266   /* If this is a builtin_expect within a builtin_expect keep the
6267      inner one.  See through a comparison against a constant.  It
6268      might have been added to create a thruthvalue.  */
6269   inner = inner_arg0;
6270
6271   if (COMPARISON_CLASS_P (inner)
6272       && TREE_CODE (TREE_OPERAND (inner, 1)) == INTEGER_CST)
6273     inner = TREE_OPERAND (inner, 0);
6274
6275   if (TREE_CODE (inner) == CALL_EXPR
6276       && (fndecl = get_callee_fndecl (inner))
6277       && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
6278       && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT)
6279     return arg0;
6280
6281   inner = inner_arg0;
6282   code = TREE_CODE (inner);
6283   if (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR)
6284     {
6285       tree op0 = TREE_OPERAND (inner, 0);
6286       tree op1 = TREE_OPERAND (inner, 1);
6287
6288       op0 = build_builtin_expect_predicate (loc, op0, arg1);
6289       op1 = build_builtin_expect_predicate (loc, op1, arg1);
6290       inner = build2 (code, TREE_TYPE (inner), op0, op1);
6291
6292       return fold_convert_loc (loc, TREE_TYPE (arg0), inner);
6293     }
6294
6295   /* If the argument isn't invariant then there's nothing else we can do.  */
6296   if (!TREE_CONSTANT (inner_arg0))
6297     return NULL_TREE;
6298
6299   /* If we expect that a comparison against the argument will fold to
6300      a constant return the constant.  In practice, this means a true
6301      constant or the address of a non-weak symbol.  */
6302   inner = inner_arg0;
6303   STRIP_NOPS (inner);
6304   if (TREE_CODE (inner) == ADDR_EXPR)
6305     {
6306       do
6307         {
6308           inner = TREE_OPERAND (inner, 0);
6309         }
6310       while (TREE_CODE (inner) == COMPONENT_REF
6311              || TREE_CODE (inner) == ARRAY_REF);
6312       if ((TREE_CODE (inner) == VAR_DECL
6313            || TREE_CODE (inner) == FUNCTION_DECL)
6314           && DECL_WEAK (inner))
6315         return NULL_TREE;
6316     }
6317
6318   /* Otherwise, ARG0 already has the proper type for the return value.  */
6319   return arg0;
6320 }
6321
6322 /* Fold a call to __builtin_classify_type with argument ARG.  */
6323
6324 static tree
6325 fold_builtin_classify_type (tree arg)
6326 {
6327   if (arg == 0)
6328     return build_int_cst (integer_type_node, no_type_class);
6329
6330   return build_int_cst (integer_type_node, type_to_class (TREE_TYPE (arg)));
6331 }
6332
6333 /* Fold a call to __builtin_strlen with argument ARG.  */
6334
6335 static tree
6336 fold_builtin_strlen (location_t loc, tree type, tree arg)
6337 {
6338   if (!validate_arg (arg, POINTER_TYPE))
6339     return NULL_TREE;
6340   else
6341     {
6342       tree len = c_strlen (arg, 0);
6343
6344       if (len)
6345         return fold_convert_loc (loc, type, len);
6346
6347       return NULL_TREE;
6348     }
6349 }
6350
6351 /* Fold a call to __builtin_inf or __builtin_huge_val.  */
6352
6353 static tree
6354 fold_builtin_inf (location_t loc, tree type, int warn)
6355 {
6356   REAL_VALUE_TYPE real;
6357
6358   /* __builtin_inff is intended to be usable to define INFINITY on all
6359      targets.  If an infinity is not available, INFINITY expands "to a
6360      positive constant of type float that overflows at translation
6361      time", footnote "In this case, using INFINITY will violate the
6362      constraint in 6.4.4 and thus require a diagnostic." (C99 7.12#4).
6363      Thus we pedwarn to ensure this constraint violation is
6364      diagnosed.  */
6365   if (!MODE_HAS_INFINITIES (TYPE_MODE (type)) && warn)
6366     pedwarn (loc, 0, "target format does not support infinity");
6367
6368   real_inf (&real);
6369   return build_real (type, real);
6370 }
6371
6372 /* Fold a call to __builtin_nan or __builtin_nans with argument ARG.  */
6373
6374 static tree
6375 fold_builtin_nan (tree arg, tree type, int quiet)
6376 {
6377   REAL_VALUE_TYPE real;
6378   const char *str;
6379
6380   if (!validate_arg (arg, POINTER_TYPE))
6381     return NULL_TREE;
6382   str = c_getstr (arg);
6383   if (!str)
6384     return NULL_TREE;
6385
6386   if (!real_nan (&real, str, quiet, TYPE_MODE (type)))
6387     return NULL_TREE;
6388
6389   return build_real (type, real);
6390 }
6391
6392 /* Return true if the floating point expression T has an integer value.
6393    We also allow +Inf, -Inf and NaN to be considered integer values.  */
6394
6395 static bool
6396 integer_valued_real_p (tree t)
6397 {
6398   switch (TREE_CODE (t))
6399     {
6400     case FLOAT_EXPR:
6401       return true;
6402
6403     case ABS_EXPR:
6404     case SAVE_EXPR:
6405       return integer_valued_real_p (TREE_OPERAND (t, 0));
6406
6407     case COMPOUND_EXPR:
6408     case MODIFY_EXPR:
6409     case BIND_EXPR:
6410       return integer_valued_real_p (TREE_OPERAND (t, 1));
6411
6412     case PLUS_EXPR:
6413     case MINUS_EXPR:
6414     case MULT_EXPR:
6415     case MIN_EXPR:
6416     case MAX_EXPR:
6417       return integer_valued_real_p (TREE_OPERAND (t, 0))
6418              && integer_valued_real_p (TREE_OPERAND (t, 1));
6419
6420     case COND_EXPR:
6421       return integer_valued_real_p (TREE_OPERAND (t, 1))
6422              && integer_valued_real_p (TREE_OPERAND (t, 2));
6423
6424     case REAL_CST:
6425       return real_isinteger (TREE_REAL_CST_PTR (t), TYPE_MODE (TREE_TYPE (t)));
6426
6427     case NOP_EXPR:
6428       {
6429         tree type = TREE_TYPE (TREE_OPERAND (t, 0));
6430         if (TREE_CODE (type) == INTEGER_TYPE)
6431           return true;
6432         if (TREE_CODE (type) == REAL_TYPE)
6433           return integer_valued_real_p (TREE_OPERAND (t, 0));
6434         break;
6435       }
6436
6437     case CALL_EXPR:
6438       switch (builtin_mathfn_code (t))
6439         {
6440         CASE_FLT_FN (BUILT_IN_CEIL):
6441         CASE_FLT_FN (BUILT_IN_FLOOR):
6442         CASE_FLT_FN (BUILT_IN_NEARBYINT):
6443         CASE_FLT_FN (BUILT_IN_RINT):
6444         CASE_FLT_FN (BUILT_IN_ROUND):
6445         CASE_FLT_FN (BUILT_IN_TRUNC):
6446           return true;
6447
6448         CASE_FLT_FN (BUILT_IN_FMIN):
6449         CASE_FLT_FN (BUILT_IN_FMAX):
6450           return integer_valued_real_p (CALL_EXPR_ARG (t, 0))
6451             && integer_valued_real_p (CALL_EXPR_ARG (t, 1));
6452
6453         default:
6454           break;
6455         }
6456       break;
6457
6458     default:
6459       break;
6460     }
6461   return false;
6462 }
6463
6464 /* FNDECL is assumed to be a builtin where truncation can be propagated
6465    across (for instance floor((double)f) == (double)floorf (f).
6466    Do the transformation for a call with argument ARG.  */
6467
6468 static tree
6469 fold_trunc_transparent_mathfn (location_t loc, tree fndecl, tree arg)
6470 {
6471   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
6472
6473   if (!validate_arg (arg, REAL_TYPE))
6474     return NULL_TREE;
6475
6476   /* Integer rounding functions are idempotent.  */
6477   if (fcode == builtin_mathfn_code (arg))
6478     return arg;
6479
6480   /* If argument is already integer valued, and we don't need to worry
6481      about setting errno, there's no need to perform rounding.  */
6482   if (! flag_errno_math && integer_valued_real_p (arg))
6483     return arg;
6484
6485   if (optimize)
6486     {
6487       tree arg0 = strip_float_extensions (arg);
6488       tree ftype = TREE_TYPE (TREE_TYPE (fndecl));
6489       tree newtype = TREE_TYPE (arg0);
6490       tree decl;
6491
6492       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
6493           && (decl = mathfn_built_in (newtype, fcode)))
6494         return fold_convert_loc (loc, ftype,
6495                                  build_call_expr_loc (loc, decl, 1,
6496                                                   fold_convert_loc (loc,
6497                                                                     newtype,
6498                                                                     arg0)));
6499     }
6500   return NULL_TREE;
6501 }
6502
6503 /* FNDECL is assumed to be builtin which can narrow the FP type of
6504    the argument, for instance lround((double)f) -> lroundf (f).
6505    Do the transformation for a call with argument ARG.  */
6506
6507 static tree
6508 fold_fixed_mathfn (location_t loc, tree fndecl, tree arg)
6509 {
6510   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
6511
6512   if (!validate_arg (arg, REAL_TYPE))
6513     return NULL_TREE;
6514
6515   /* If argument is already integer valued, and we don't need to worry
6516      about setting errno, there's no need to perform rounding.  */
6517   if (! flag_errno_math && integer_valued_real_p (arg))
6518     return fold_build1_loc (loc, FIX_TRUNC_EXPR,
6519                         TREE_TYPE (TREE_TYPE (fndecl)), arg);
6520
6521   if (optimize)
6522     {
6523       tree ftype = TREE_TYPE (arg);
6524       tree arg0 = strip_float_extensions (arg);
6525       tree newtype = TREE_TYPE (arg0);
6526       tree decl;
6527
6528       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
6529           && (decl = mathfn_built_in (newtype, fcode)))
6530         return build_call_expr_loc (loc, decl, 1,
6531                                 fold_convert_loc (loc, newtype, arg0));
6532     }
6533
6534   /* Canonicalize llround (x) to lround (x) on LP64 targets where
6535      sizeof (long long) == sizeof (long).  */
6536   if (TYPE_PRECISION (long_long_integer_type_node)
6537       == TYPE_PRECISION (long_integer_type_node))
6538     {
6539       tree newfn = NULL_TREE;
6540       switch (fcode)
6541         {
6542         CASE_FLT_FN (BUILT_IN_LLCEIL):
6543           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LCEIL);
6544           break;
6545
6546         CASE_FLT_FN (BUILT_IN_LLFLOOR):
6547           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LFLOOR);
6548           break;
6549
6550         CASE_FLT_FN (BUILT_IN_LLROUND):
6551           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LROUND);
6552           break;
6553
6554         CASE_FLT_FN (BUILT_IN_LLRINT):
6555           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LRINT);
6556           break;
6557
6558         default:
6559           break;
6560         }
6561
6562       if (newfn)
6563         {
6564           tree newcall = build_call_expr_loc (loc, newfn, 1, arg);
6565           return fold_convert_loc (loc,
6566                                    TREE_TYPE (TREE_TYPE (fndecl)), newcall);
6567         }
6568     }
6569
6570   return NULL_TREE;
6571 }
6572
6573 /* Fold call to builtin cabs, cabsf or cabsl with argument ARG.  TYPE is the
6574    return type.  Return NULL_TREE if no simplification can be made.  */
6575
6576 static tree
6577 fold_builtin_cabs (location_t loc, tree arg, tree type, tree fndecl)
6578 {
6579   tree res;
6580
6581   if (!validate_arg (arg, COMPLEX_TYPE)
6582       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) != REAL_TYPE)
6583     return NULL_TREE;
6584
6585   /* Calculate the result when the argument is a constant.  */
6586   if (TREE_CODE (arg) == COMPLEX_CST
6587       && (res = do_mpfr_arg2 (TREE_REALPART (arg), TREE_IMAGPART (arg),
6588                               type, mpfr_hypot)))
6589     return res;
6590
6591   if (TREE_CODE (arg) == COMPLEX_EXPR)
6592     {
6593       tree real = TREE_OPERAND (arg, 0);
6594       tree imag = TREE_OPERAND (arg, 1);
6595
6596       /* If either part is zero, cabs is fabs of the other.  */
6597       if (real_zerop (real))
6598         return fold_build1_loc (loc, ABS_EXPR, type, imag);
6599       if (real_zerop (imag))
6600         return fold_build1_loc (loc, ABS_EXPR, type, real);
6601
6602       /* cabs(x+xi) -> fabs(x)*sqrt(2).  */
6603       if (flag_unsafe_math_optimizations
6604           && operand_equal_p (real, imag, OEP_PURE_SAME))
6605         {
6606           const REAL_VALUE_TYPE sqrt2_trunc
6607             = real_value_truncate (TYPE_MODE (type), dconst_sqrt2 ());
6608           STRIP_NOPS (real);
6609           return fold_build2_loc (loc, MULT_EXPR, type,
6610                               fold_build1_loc (loc, ABS_EXPR, type, real),
6611                               build_real (type, sqrt2_trunc));
6612         }
6613     }
6614
6615   /* Optimize cabs(-z) and cabs(conj(z)) as cabs(z).  */
6616   if (TREE_CODE (arg) == NEGATE_EXPR
6617       || TREE_CODE (arg) == CONJ_EXPR)
6618     return build_call_expr_loc (loc, fndecl, 1, TREE_OPERAND (arg, 0));
6619
6620   /* Don't do this when optimizing for size.  */
6621   if (flag_unsafe_math_optimizations
6622       && optimize && optimize_function_for_speed_p (cfun))
6623     {
6624       tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
6625
6626       if (sqrtfn != NULL_TREE)
6627         {
6628           tree rpart, ipart, result;
6629
6630           arg = builtin_save_expr (arg);
6631
6632           rpart = fold_build1_loc (loc, REALPART_EXPR, type, arg);
6633           ipart = fold_build1_loc (loc, IMAGPART_EXPR, type, arg);
6634
6635           rpart = builtin_save_expr (rpart);
6636           ipart = builtin_save_expr (ipart);
6637
6638           result = fold_build2_loc (loc, PLUS_EXPR, type,
6639                                 fold_build2_loc (loc, MULT_EXPR, type,
6640                                              rpart, rpart),
6641                                 fold_build2_loc (loc, MULT_EXPR, type,
6642                                              ipart, ipart));
6643
6644           return build_call_expr_loc (loc, sqrtfn, 1, result);
6645         }
6646     }
6647
6648   return NULL_TREE;
6649 }
6650
6651 /* Build a complex (inf +- 0i) for the result of cproj.  TYPE is the
6652    complex tree type of the result.  If NEG is true, the imaginary
6653    zero is negative.  */
6654
6655 static tree
6656 build_complex_cproj (tree type, bool neg)
6657 {
6658   REAL_VALUE_TYPE rinf, rzero = dconst0;
6659   
6660   real_inf (&rinf);
6661   rzero.sign = neg;
6662   return build_complex (type, build_real (TREE_TYPE (type), rinf),
6663                         build_real (TREE_TYPE (type), rzero));
6664 }
6665
6666 /* Fold call to builtin cproj, cprojf or cprojl with argument ARG.  TYPE is the
6667    return type.  Return NULL_TREE if no simplification can be made.  */
6668
6669 static tree
6670 fold_builtin_cproj (location_t loc, tree arg, tree type)
6671 {
6672   if (!validate_arg (arg, COMPLEX_TYPE)
6673       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) != REAL_TYPE)
6674     return NULL_TREE;
6675
6676   /* If there are no infinities, return arg.  */
6677   if (! HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (type))))
6678     return non_lvalue_loc (loc, arg);
6679
6680   /* Calculate the result when the argument is a constant.  */
6681   if (TREE_CODE (arg) == COMPLEX_CST)
6682     {
6683       const REAL_VALUE_TYPE *real = TREE_REAL_CST_PTR (TREE_REALPART (arg));
6684       const REAL_VALUE_TYPE *imag = TREE_REAL_CST_PTR (TREE_IMAGPART (arg));
6685       
6686       if (real_isinf (real) || real_isinf (imag))
6687         return build_complex_cproj (type, imag->sign);
6688       else
6689         return arg;
6690     }
6691   else if (TREE_CODE (arg) == COMPLEX_EXPR)
6692     {
6693       tree real = TREE_OPERAND (arg, 0);
6694       tree imag = TREE_OPERAND (arg, 1);
6695
6696       STRIP_NOPS (real);
6697       STRIP_NOPS (imag);
6698       
6699       /* If the real part is inf and the imag part is known to be
6700          nonnegative, return (inf + 0i).  Remember side-effects are
6701          possible in the imag part.  */
6702       if (TREE_CODE (real) == REAL_CST
6703           && real_isinf (TREE_REAL_CST_PTR (real))
6704           && tree_expr_nonnegative_p (imag))
6705         return omit_one_operand_loc (loc, type,
6706                                      build_complex_cproj (type, false),
6707                                      arg);
6708       
6709       /* If the imag part is inf, return (inf+I*copysign(0,imag)).
6710          Remember side-effects are possible in the real part.  */
6711       if (TREE_CODE (imag) == REAL_CST
6712           && real_isinf (TREE_REAL_CST_PTR (imag)))
6713         return
6714           omit_one_operand_loc (loc, type,
6715                                 build_complex_cproj (type, TREE_REAL_CST_PTR
6716                                                      (imag)->sign), arg);
6717     }
6718
6719   return NULL_TREE;
6720 }
6721
6722 /* Fold a builtin function call to sqrt, sqrtf, or sqrtl with argument ARG.
6723    Return NULL_TREE if no simplification can be made.  */
6724
6725 static tree
6726 fold_builtin_sqrt (location_t loc, tree arg, tree type)
6727 {
6728
6729   enum built_in_function fcode;
6730   tree res;
6731
6732   if (!validate_arg (arg, REAL_TYPE))
6733     return NULL_TREE;
6734
6735   /* Calculate the result when the argument is a constant.  */
6736   if ((res = do_mpfr_arg1 (arg, type, mpfr_sqrt, &dconst0, NULL, true)))
6737     return res;
6738
6739   /* Optimize sqrt(expN(x)) = expN(x*0.5).  */
6740   fcode = builtin_mathfn_code (arg);
6741   if (flag_unsafe_math_optimizations && BUILTIN_EXPONENT_P (fcode))
6742     {
6743       tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
6744       arg = fold_build2_loc (loc, MULT_EXPR, type,
6745                          CALL_EXPR_ARG (arg, 0),
6746                          build_real (type, dconsthalf));
6747       return build_call_expr_loc (loc, expfn, 1, arg);
6748     }
6749
6750   /* Optimize sqrt(Nroot(x)) -> pow(x,1/(2*N)).  */
6751   if (flag_unsafe_math_optimizations && BUILTIN_ROOT_P (fcode))
6752     {
6753       tree powfn = mathfn_built_in (type, BUILT_IN_POW);
6754
6755       if (powfn)
6756         {
6757           tree arg0 = CALL_EXPR_ARG (arg, 0);
6758           tree tree_root;
6759           /* The inner root was either sqrt or cbrt.  */
6760           /* This was a conditional expression but it triggered a bug
6761              in Sun C 5.5.  */
6762           REAL_VALUE_TYPE dconstroot;
6763           if (BUILTIN_SQRT_P (fcode))
6764             dconstroot = dconsthalf;
6765           else
6766             dconstroot = dconst_third ();
6767
6768           /* Adjust for the outer root.  */
6769           SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
6770           dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
6771           tree_root = build_real (type, dconstroot);
6772           return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
6773         }
6774     }
6775
6776   /* Optimize sqrt(pow(x,y)) = pow(|x|,y*0.5).  */
6777   if (flag_unsafe_math_optimizations
6778       && (fcode == BUILT_IN_POW
6779           || fcode == BUILT_IN_POWF
6780           || fcode == BUILT_IN_POWL))
6781     {
6782       tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
6783       tree arg0 = CALL_EXPR_ARG (arg, 0);
6784       tree arg1 = CALL_EXPR_ARG (arg, 1);
6785       tree narg1;
6786       if (!tree_expr_nonnegative_p (arg0))
6787         arg0 = build1 (ABS_EXPR, type, arg0);
6788       narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
6789                            build_real (type, dconsthalf));
6790       return build_call_expr_loc (loc, powfn, 2, arg0, narg1);
6791     }
6792
6793   return NULL_TREE;
6794 }
6795
6796 /* Fold a builtin function call to cbrt, cbrtf, or cbrtl with argument ARG.
6797    Return NULL_TREE if no simplification can be made.  */
6798
6799 static tree
6800 fold_builtin_cbrt (location_t loc, tree arg, tree type)
6801 {
6802   const enum built_in_function fcode = builtin_mathfn_code (arg);
6803   tree res;
6804
6805   if (!validate_arg (arg, REAL_TYPE))
6806     return NULL_TREE;
6807
6808   /* Calculate the result when the argument is a constant.  */
6809   if ((res = do_mpfr_arg1 (arg, type, mpfr_cbrt, NULL, NULL, 0)))
6810     return res;
6811
6812   if (flag_unsafe_math_optimizations)
6813     {
6814       /* Optimize cbrt(expN(x)) -> expN(x/3).  */
6815       if (BUILTIN_EXPONENT_P (fcode))
6816         {
6817           tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
6818           const REAL_VALUE_TYPE third_trunc =
6819             real_value_truncate (TYPE_MODE (type), dconst_third ());
6820           arg = fold_build2_loc (loc, MULT_EXPR, type,
6821                              CALL_EXPR_ARG (arg, 0),
6822                              build_real (type, third_trunc));
6823           return build_call_expr_loc (loc, expfn, 1, arg);
6824         }
6825
6826       /* Optimize cbrt(sqrt(x)) -> pow(x,1/6).  */
6827       if (BUILTIN_SQRT_P (fcode))
6828         {
6829           tree powfn = mathfn_built_in (type, BUILT_IN_POW);
6830
6831           if (powfn)
6832             {
6833               tree arg0 = CALL_EXPR_ARG (arg, 0);
6834               tree tree_root;
6835               REAL_VALUE_TYPE dconstroot = dconst_third ();
6836
6837               SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
6838               dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
6839               tree_root = build_real (type, dconstroot);
6840               return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
6841             }
6842         }
6843
6844       /* Optimize cbrt(cbrt(x)) -> pow(x,1/9) iff x is nonnegative.  */
6845       if (BUILTIN_CBRT_P (fcode))
6846         {
6847           tree arg0 = CALL_EXPR_ARG (arg, 0);
6848           if (tree_expr_nonnegative_p (arg0))
6849             {
6850               tree powfn = mathfn_built_in (type, BUILT_IN_POW);
6851
6852               if (powfn)
6853                 {
6854                   tree tree_root;
6855                   REAL_VALUE_TYPE dconstroot;
6856
6857                   real_arithmetic (&dconstroot, MULT_EXPR,
6858                                    dconst_third_ptr (), dconst_third_ptr ());
6859                   dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
6860                   tree_root = build_real (type, dconstroot);
6861                   return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
6862                 }
6863             }
6864         }
6865
6866       /* Optimize cbrt(pow(x,y)) -> pow(x,y/3) iff x is nonnegative.  */
6867       if (fcode == BUILT_IN_POW
6868           || fcode == BUILT_IN_POWF
6869           || fcode == BUILT_IN_POWL)
6870         {
6871           tree arg00 = CALL_EXPR_ARG (arg, 0);
6872           tree arg01 = CALL_EXPR_ARG (arg, 1);
6873           if (tree_expr_nonnegative_p (arg00))
6874             {
6875               tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
6876               const REAL_VALUE_TYPE dconstroot
6877                 = real_value_truncate (TYPE_MODE (type), dconst_third ());
6878               tree narg01 = fold_build2_loc (loc, MULT_EXPR, type, arg01,
6879                                          build_real (type, dconstroot));
6880               return build_call_expr_loc (loc, powfn, 2, arg00, narg01);
6881             }
6882         }
6883     }
6884   return NULL_TREE;
6885 }
6886
6887 /* Fold function call to builtin cos, cosf, or cosl with argument ARG.
6888    TYPE is the type of the return value.  Return NULL_TREE if no
6889    simplification can be made.  */
6890
6891 static tree
6892 fold_builtin_cos (location_t loc,
6893                   tree arg, tree type, tree fndecl)
6894 {
6895   tree res, narg;
6896
6897   if (!validate_arg (arg, REAL_TYPE))
6898     return NULL_TREE;
6899
6900   /* Calculate the result when the argument is a constant.  */
6901   if ((res = do_mpfr_arg1 (arg, type, mpfr_cos, NULL, NULL, 0)))
6902     return res;
6903
6904   /* Optimize cos(-x) into cos (x).  */
6905   if ((narg = fold_strip_sign_ops (arg)))
6906     return build_call_expr_loc (loc, fndecl, 1, narg);
6907
6908   return NULL_TREE;
6909 }
6910
6911 /* Fold function call to builtin cosh, coshf, or coshl with argument ARG.
6912    Return NULL_TREE if no simplification can be made.  */
6913
6914 static tree
6915 fold_builtin_cosh (location_t loc, tree arg, tree type, tree fndecl)
6916 {
6917   if (validate_arg (arg, REAL_TYPE))
6918     {
6919       tree res, narg;
6920
6921       /* Calculate the result when the argument is a constant.  */
6922       if ((res = do_mpfr_arg1 (arg, type, mpfr_cosh, NULL, NULL, 0)))
6923         return res;
6924
6925       /* Optimize cosh(-x) into cosh (x).  */
6926       if ((narg = fold_strip_sign_ops (arg)))
6927         return build_call_expr_loc (loc, fndecl, 1, narg);
6928     }
6929
6930   return NULL_TREE;
6931 }
6932
6933 /* Fold function call to builtin ccos (or ccosh if HYPER is TRUE) with
6934    argument ARG.  TYPE is the type of the return value.  Return
6935    NULL_TREE if no simplification can be made.  */
6936
6937 static tree
6938 fold_builtin_ccos (location_t loc, tree arg, tree type, tree fndecl,
6939                    bool hyper)
6940 {
6941   if (validate_arg (arg, COMPLEX_TYPE)
6942       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE)
6943     {
6944       tree tmp;
6945
6946       /* Calculate the result when the argument is a constant.  */
6947       if ((tmp = do_mpc_arg1 (arg, type, (hyper ? mpc_cosh : mpc_cos))))
6948         return tmp;
6949
6950       /* Optimize fn(-x) into fn(x).  */
6951       if ((tmp = fold_strip_sign_ops (arg)))
6952         return build_call_expr_loc (loc, fndecl, 1, tmp);
6953     }
6954
6955   return NULL_TREE;
6956 }
6957
6958 /* Fold function call to builtin tan, tanf, or tanl with argument ARG.
6959    Return NULL_TREE if no simplification can be made.  */
6960
6961 static tree
6962 fold_builtin_tan (tree arg, tree type)
6963 {
6964   enum built_in_function fcode;
6965   tree res;
6966
6967   if (!validate_arg (arg, REAL_TYPE))
6968     return NULL_TREE;
6969
6970   /* Calculate the result when the argument is a constant.  */
6971   if ((res = do_mpfr_arg1 (arg, type, mpfr_tan, NULL, NULL, 0)))
6972     return res;
6973
6974   /* Optimize tan(atan(x)) = x.  */
6975   fcode = builtin_mathfn_code (arg);
6976   if (flag_unsafe_math_optimizations
6977       && (fcode == BUILT_IN_ATAN
6978           || fcode == BUILT_IN_ATANF
6979           || fcode == BUILT_IN_ATANL))
6980     return CALL_EXPR_ARG (arg, 0);
6981
6982   return NULL_TREE;
6983 }
6984
6985 /* Fold function call to builtin sincos, sincosf, or sincosl.  Return
6986    NULL_TREE if no simplification can be made.  */
6987
6988 static tree
6989 fold_builtin_sincos (location_t loc,
6990                      tree arg0, tree arg1, tree arg2)
6991 {
6992   tree type;
6993   tree res, fn, call;
6994
6995   if (!validate_arg (arg0, REAL_TYPE)
6996       || !validate_arg (arg1, POINTER_TYPE)
6997       || !validate_arg (arg2, POINTER_TYPE))
6998     return NULL_TREE;
6999
7000   type = TREE_TYPE (arg0);
7001
7002   /* Calculate the result when the argument is a constant.  */
7003   if ((res = do_mpfr_sincos (arg0, arg1, arg2)))
7004     return res;
7005
7006   /* Canonicalize sincos to cexpi.  */
7007   if (!TARGET_C99_FUNCTIONS)
7008     return NULL_TREE;
7009   fn = mathfn_built_in (type, BUILT_IN_CEXPI);
7010   if (!fn)
7011     return NULL_TREE;
7012
7013   call = build_call_expr_loc (loc, fn, 1, arg0);
7014   call = builtin_save_expr (call);
7015
7016   return build2 (COMPOUND_EXPR, void_type_node,
7017                  build2 (MODIFY_EXPR, void_type_node,
7018                          build_fold_indirect_ref_loc (loc, arg1),
7019                          build1 (IMAGPART_EXPR, type, call)),
7020                  build2 (MODIFY_EXPR, void_type_node,
7021                          build_fold_indirect_ref_loc (loc, arg2),
7022                          build1 (REALPART_EXPR, type, call)));
7023 }
7024
7025 /* Fold function call to builtin cexp, cexpf, or cexpl.  Return
7026    NULL_TREE if no simplification can be made.  */
7027
7028 static tree
7029 fold_builtin_cexp (location_t loc, tree arg0, tree type)
7030 {
7031   tree rtype;
7032   tree realp, imagp, ifn;
7033   tree res;
7034
7035   if (!validate_arg (arg0, COMPLEX_TYPE)
7036       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) != REAL_TYPE)
7037     return NULL_TREE;
7038
7039   /* Calculate the result when the argument is a constant.  */
7040   if ((res = do_mpc_arg1 (arg0, type, mpc_exp)))
7041     return res;
7042
7043   rtype = TREE_TYPE (TREE_TYPE (arg0));
7044
7045   /* In case we can figure out the real part of arg0 and it is constant zero
7046      fold to cexpi.  */
7047   if (!TARGET_C99_FUNCTIONS)
7048     return NULL_TREE;
7049   ifn = mathfn_built_in (rtype, BUILT_IN_CEXPI);
7050   if (!ifn)
7051     return NULL_TREE;
7052
7053   if ((realp = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0))
7054       && real_zerop (realp))
7055     {
7056       tree narg = fold_build1_loc (loc, IMAGPART_EXPR, rtype, arg0);
7057       return build_call_expr_loc (loc, ifn, 1, narg);
7058     }
7059
7060   /* In case we can easily decompose real and imaginary parts split cexp
7061      to exp (r) * cexpi (i).  */
7062   if (flag_unsafe_math_optimizations
7063       && realp)
7064     {
7065       tree rfn, rcall, icall;
7066
7067       rfn = mathfn_built_in (rtype, BUILT_IN_EXP);
7068       if (!rfn)
7069         return NULL_TREE;
7070
7071       imagp = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
7072       if (!imagp)
7073         return NULL_TREE;
7074
7075       icall = build_call_expr_loc (loc, ifn, 1, imagp);
7076       icall = builtin_save_expr (icall);
7077       rcall = build_call_expr_loc (loc, rfn, 1, realp);
7078       rcall = builtin_save_expr (rcall);
7079       return fold_build2_loc (loc, COMPLEX_EXPR, type,
7080                           fold_build2_loc (loc, MULT_EXPR, rtype,
7081                                        rcall,
7082                                        fold_build1_loc (loc, REALPART_EXPR,
7083                                                     rtype, icall)),
7084                           fold_build2_loc (loc, MULT_EXPR, rtype,
7085                                        rcall,
7086                                        fold_build1_loc (loc, IMAGPART_EXPR,
7087                                                     rtype, icall)));
7088     }
7089
7090   return NULL_TREE;
7091 }
7092
7093 /* Fold function call to builtin trunc, truncf or truncl with argument ARG.
7094    Return NULL_TREE if no simplification can be made.  */
7095
7096 static tree
7097 fold_builtin_trunc (location_t loc, tree fndecl, tree arg)
7098 {
7099   if (!validate_arg (arg, REAL_TYPE))
7100     return NULL_TREE;
7101
7102   /* Optimize trunc of constant value.  */
7103   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7104     {
7105       REAL_VALUE_TYPE r, x;
7106       tree type = TREE_TYPE (TREE_TYPE (fndecl));
7107
7108       x = TREE_REAL_CST (arg);
7109       real_trunc (&r, TYPE_MODE (type), &x);
7110       return build_real (type, r);
7111     }
7112
7113   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7114 }
7115
7116 /* Fold function call to builtin floor, floorf or floorl with argument ARG.
7117    Return NULL_TREE if no simplification can be made.  */
7118
7119 static tree
7120 fold_builtin_floor (location_t loc, tree fndecl, tree arg)
7121 {
7122   if (!validate_arg (arg, REAL_TYPE))
7123     return NULL_TREE;
7124
7125   /* Optimize floor of constant value.  */
7126   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7127     {
7128       REAL_VALUE_TYPE x;
7129
7130       x = TREE_REAL_CST (arg);
7131       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7132         {
7133           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7134           REAL_VALUE_TYPE r;
7135
7136           real_floor (&r, TYPE_MODE (type), &x);
7137           return build_real (type, r);
7138         }
7139     }
7140
7141   /* Fold floor (x) where x is nonnegative to trunc (x).  */
7142   if (tree_expr_nonnegative_p (arg))
7143     {
7144       tree truncfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_TRUNC);
7145       if (truncfn)
7146         return build_call_expr_loc (loc, truncfn, 1, arg);
7147     }
7148
7149   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7150 }
7151
7152 /* Fold function call to builtin ceil, ceilf or ceill with argument ARG.
7153    Return NULL_TREE if no simplification can be made.  */
7154
7155 static tree
7156 fold_builtin_ceil (location_t loc, tree fndecl, tree arg)
7157 {
7158   if (!validate_arg (arg, REAL_TYPE))
7159     return NULL_TREE;
7160
7161   /* Optimize ceil of constant value.  */
7162   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7163     {
7164       REAL_VALUE_TYPE x;
7165
7166       x = TREE_REAL_CST (arg);
7167       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7168         {
7169           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7170           REAL_VALUE_TYPE r;
7171
7172           real_ceil (&r, TYPE_MODE (type), &x);
7173           return build_real (type, r);
7174         }
7175     }
7176
7177   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7178 }
7179
7180 /* Fold function call to builtin round, roundf or roundl with argument ARG.
7181    Return NULL_TREE if no simplification can be made.  */
7182
7183 static tree
7184 fold_builtin_round (location_t loc, tree fndecl, tree arg)
7185 {
7186   if (!validate_arg (arg, REAL_TYPE))
7187     return NULL_TREE;
7188
7189   /* Optimize round of constant value.  */
7190   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7191     {
7192       REAL_VALUE_TYPE x;
7193
7194       x = TREE_REAL_CST (arg);
7195       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7196         {
7197           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7198           REAL_VALUE_TYPE r;
7199
7200           real_round (&r, TYPE_MODE (type), &x);
7201           return build_real (type, r);
7202         }
7203     }
7204
7205   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7206 }
7207
7208 /* Fold function call to builtin lround, lroundf or lroundl (or the
7209    corresponding long long versions) and other rounding functions.  ARG
7210    is the argument to the call.  Return NULL_TREE if no simplification
7211    can be made.  */
7212
7213 static tree
7214 fold_builtin_int_roundingfn (location_t loc, tree fndecl, tree arg)
7215 {
7216   if (!validate_arg (arg, REAL_TYPE))
7217     return NULL_TREE;
7218
7219   /* Optimize lround of constant value.  */
7220   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7221     {
7222       const REAL_VALUE_TYPE x = TREE_REAL_CST (arg);
7223
7224       if (real_isfinite (&x))
7225         {
7226           tree itype = TREE_TYPE (TREE_TYPE (fndecl));
7227           tree ftype = TREE_TYPE (arg);
7228           double_int val;
7229           REAL_VALUE_TYPE r;
7230
7231           switch (DECL_FUNCTION_CODE (fndecl))
7232             {
7233             CASE_FLT_FN (BUILT_IN_LFLOOR):
7234             CASE_FLT_FN (BUILT_IN_LLFLOOR):
7235               real_floor (&r, TYPE_MODE (ftype), &x);
7236               break;
7237
7238             CASE_FLT_FN (BUILT_IN_LCEIL):
7239             CASE_FLT_FN (BUILT_IN_LLCEIL):
7240               real_ceil (&r, TYPE_MODE (ftype), &x);
7241               break;
7242
7243             CASE_FLT_FN (BUILT_IN_LROUND):
7244             CASE_FLT_FN (BUILT_IN_LLROUND):
7245               real_round (&r, TYPE_MODE (ftype), &x);
7246               break;
7247
7248             default:
7249               gcc_unreachable ();
7250             }
7251
7252           real_to_integer2 ((HOST_WIDE_INT *)&val.low, &val.high, &r);
7253           if (double_int_fits_to_tree_p (itype, val))
7254             return double_int_to_tree (itype, val);
7255         }
7256     }
7257
7258   switch (DECL_FUNCTION_CODE (fndecl))
7259     {
7260     CASE_FLT_FN (BUILT_IN_LFLOOR):
7261     CASE_FLT_FN (BUILT_IN_LLFLOOR):
7262       /* Fold lfloor (x) where x is nonnegative to FIX_TRUNC (x).  */
7263       if (tree_expr_nonnegative_p (arg))
7264         return fold_build1_loc (loc, FIX_TRUNC_EXPR,
7265                             TREE_TYPE (TREE_TYPE (fndecl)), arg);
7266       break;
7267     default:;
7268     }
7269
7270   return fold_fixed_mathfn (loc, fndecl, arg);
7271 }
7272
7273 /* Fold function call to builtin ffs, clz, ctz, popcount and parity
7274    and their long and long long variants (i.e. ffsl and ffsll).  ARG is
7275    the argument to the call.  Return NULL_TREE if no simplification can
7276    be made.  */
7277
7278 static tree
7279 fold_builtin_bitop (tree fndecl, tree arg)
7280 {
7281   if (!validate_arg (arg, INTEGER_TYPE))
7282     return NULL_TREE;
7283
7284   /* Optimize for constant argument.  */
7285   if (TREE_CODE (arg) == INTEGER_CST && !TREE_OVERFLOW (arg))
7286     {
7287       HOST_WIDE_INT hi, width, result;
7288       unsigned HOST_WIDE_INT lo;
7289       tree type;
7290
7291       type = TREE_TYPE (arg);
7292       width = TYPE_PRECISION (type);
7293       lo = TREE_INT_CST_LOW (arg);
7294
7295       /* Clear all the bits that are beyond the type's precision.  */
7296       if (width > HOST_BITS_PER_WIDE_INT)
7297         {
7298           hi = TREE_INT_CST_HIGH (arg);
7299           if (width < 2 * HOST_BITS_PER_WIDE_INT)
7300             hi &= ~((unsigned HOST_WIDE_INT) (-1)
7301                     << (width - HOST_BITS_PER_WIDE_INT));
7302         }
7303       else
7304         {
7305           hi = 0;
7306           if (width < HOST_BITS_PER_WIDE_INT)
7307             lo &= ~((unsigned HOST_WIDE_INT) (-1) << width);
7308         }
7309
7310       switch (DECL_FUNCTION_CODE (fndecl))
7311         {
7312         CASE_INT_FN (BUILT_IN_FFS):
7313           if (lo != 0)
7314             result = ffs_hwi (lo);
7315           else if (hi != 0)
7316             result = HOST_BITS_PER_WIDE_INT + ffs_hwi (hi);
7317           else
7318             result = 0;
7319           break;
7320
7321         CASE_INT_FN (BUILT_IN_CLZ):
7322           if (hi != 0)
7323             result = width - floor_log2 (hi) - 1 - HOST_BITS_PER_WIDE_INT;
7324           else if (lo != 0)
7325             result = width - floor_log2 (lo) - 1;
7326           else if (! CLZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
7327             result = width;
7328           break;
7329
7330         CASE_INT_FN (BUILT_IN_CTZ):
7331           if (lo != 0)
7332             result = ctz_hwi (lo);
7333           else if (hi != 0)
7334             result = HOST_BITS_PER_WIDE_INT + ctz_hwi (hi);
7335           else if (! CTZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
7336             result = width;
7337           break;
7338
7339         CASE_INT_FN (BUILT_IN_CLRSB):
7340           if (width > HOST_BITS_PER_WIDE_INT
7341               && (hi & ((unsigned HOST_WIDE_INT) 1
7342                         << (width - HOST_BITS_PER_WIDE_INT - 1))) != 0)
7343             {
7344               hi = ~hi & ~((unsigned HOST_WIDE_INT) (-1)
7345                            << (width - HOST_BITS_PER_WIDE_INT - 1));
7346               lo = ~lo;
7347             }
7348           else if (width <= HOST_BITS_PER_WIDE_INT
7349                    && (lo & ((unsigned HOST_WIDE_INT) 1 << (width - 1))) != 0)
7350             lo = ~lo & ~((unsigned HOST_WIDE_INT) (-1) << (width - 1));
7351           if (hi != 0)
7352             result = width - floor_log2 (hi) - 2 - HOST_BITS_PER_WIDE_INT;
7353           else if (lo != 0)
7354             result = width - floor_log2 (lo) - 2;
7355           else
7356             result = width - 1;
7357           break;
7358
7359         CASE_INT_FN (BUILT_IN_POPCOUNT):
7360           result = 0;
7361           while (lo)
7362             result++, lo &= lo - 1;
7363           while (hi)
7364             result++, hi &= (unsigned HOST_WIDE_INT) hi - 1;
7365           break;
7366
7367         CASE_INT_FN (BUILT_IN_PARITY):
7368           result = 0;
7369           while (lo)
7370             result++, lo &= lo - 1;
7371           while (hi)
7372             result++, hi &= (unsigned HOST_WIDE_INT) hi - 1;
7373           result &= 1;
7374           break;
7375
7376         default:
7377           gcc_unreachable ();
7378         }
7379
7380       return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), result);
7381     }
7382
7383   return NULL_TREE;
7384 }
7385
7386 /* Fold function call to builtin_bswap and the long and long long
7387    variants.  Return NULL_TREE if no simplification can be made.  */
7388 static tree
7389 fold_builtin_bswap (tree fndecl, tree arg)
7390 {
7391   if (! validate_arg (arg, INTEGER_TYPE))
7392     return NULL_TREE;
7393
7394   /* Optimize constant value.  */
7395   if (TREE_CODE (arg) == INTEGER_CST && !TREE_OVERFLOW (arg))
7396     {
7397       HOST_WIDE_INT hi, width, r_hi = 0;
7398       unsigned HOST_WIDE_INT lo, r_lo = 0;
7399       tree type;
7400
7401       type = TREE_TYPE (arg);
7402       width = TYPE_PRECISION (type);
7403       lo = TREE_INT_CST_LOW (arg);
7404       hi = TREE_INT_CST_HIGH (arg);
7405
7406       switch (DECL_FUNCTION_CODE (fndecl))
7407         {
7408           case BUILT_IN_BSWAP32:
7409           case BUILT_IN_BSWAP64:
7410             {
7411               int s;
7412
7413               for (s = 0; s < width; s += 8)
7414                 {
7415                   int d = width - s - 8;
7416                   unsigned HOST_WIDE_INT byte;
7417
7418                   if (s < HOST_BITS_PER_WIDE_INT)
7419                     byte = (lo >> s) & 0xff;
7420                   else
7421                     byte = (hi >> (s - HOST_BITS_PER_WIDE_INT)) & 0xff;
7422
7423                   if (d < HOST_BITS_PER_WIDE_INT)
7424                     r_lo |= byte << d;
7425                   else
7426                     r_hi |= byte << (d - HOST_BITS_PER_WIDE_INT);
7427                 }
7428             }
7429
7430             break;
7431
7432         default:
7433           gcc_unreachable ();
7434         }
7435
7436       if (width < HOST_BITS_PER_WIDE_INT)
7437         return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), r_lo);
7438       else
7439         return build_int_cst_wide (TREE_TYPE (TREE_TYPE (fndecl)), r_lo, r_hi);
7440     }
7441
7442   return NULL_TREE;
7443 }
7444
7445 /* A subroutine of fold_builtin to fold the various logarithmic
7446    functions.  Return NULL_TREE if no simplification can me made.
7447    FUNC is the corresponding MPFR logarithm function.  */
7448
7449 static tree
7450 fold_builtin_logarithm (location_t loc, tree fndecl, tree arg,
7451                         int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t))
7452 {
7453   if (validate_arg (arg, REAL_TYPE))
7454     {
7455       tree type = TREE_TYPE (TREE_TYPE (fndecl));
7456       tree res;
7457       const enum built_in_function fcode = builtin_mathfn_code (arg);
7458
7459       /* Calculate the result when the argument is a constant.  */
7460       if ((res = do_mpfr_arg1 (arg, type, func, &dconst0, NULL, false)))
7461         return res;
7462
7463       /* Special case, optimize logN(expN(x)) = x.  */
7464       if (flag_unsafe_math_optimizations
7465           && ((func == mpfr_log
7466                && (fcode == BUILT_IN_EXP
7467                    || fcode == BUILT_IN_EXPF
7468                    || fcode == BUILT_IN_EXPL))
7469               || (func == mpfr_log2
7470                   && (fcode == BUILT_IN_EXP2
7471                       || fcode == BUILT_IN_EXP2F
7472                       || fcode == BUILT_IN_EXP2L))
7473               || (func == mpfr_log10 && (BUILTIN_EXP10_P (fcode)))))
7474         return fold_convert_loc (loc, type, CALL_EXPR_ARG (arg, 0));
7475
7476       /* Optimize logN(func()) for various exponential functions.  We
7477          want to determine the value "x" and the power "exponent" in
7478          order to transform logN(x**exponent) into exponent*logN(x).  */
7479       if (flag_unsafe_math_optimizations)
7480         {
7481           tree exponent = 0, x = 0;
7482
7483           switch (fcode)
7484           {
7485           CASE_FLT_FN (BUILT_IN_EXP):
7486             /* Prepare to do logN(exp(exponent) -> exponent*logN(e).  */
7487             x = build_real (type, real_value_truncate (TYPE_MODE (type),
7488                                                        dconst_e ()));
7489             exponent = CALL_EXPR_ARG (arg, 0);
7490             break;
7491           CASE_FLT_FN (BUILT_IN_EXP2):
7492             /* Prepare to do logN(exp2(exponent) -> exponent*logN(2).  */
7493             x = build_real (type, dconst2);
7494             exponent = CALL_EXPR_ARG (arg, 0);
7495             break;
7496           CASE_FLT_FN (BUILT_IN_EXP10):
7497           CASE_FLT_FN (BUILT_IN_POW10):
7498             /* Prepare to do logN(exp10(exponent) -> exponent*logN(10).  */
7499             {
7500               REAL_VALUE_TYPE dconst10;
7501               real_from_integer (&dconst10, VOIDmode, 10, 0, 0);
7502               x = build_real (type, dconst10);
7503             }
7504             exponent = CALL_EXPR_ARG (arg, 0);
7505             break;
7506           CASE_FLT_FN (BUILT_IN_SQRT):
7507             /* Prepare to do logN(sqrt(x) -> 0.5*logN(x).  */
7508             x = CALL_EXPR_ARG (arg, 0);
7509             exponent = build_real (type, dconsthalf);
7510             break;
7511           CASE_FLT_FN (BUILT_IN_CBRT):
7512             /* Prepare to do logN(cbrt(x) -> (1/3)*logN(x).  */
7513             x = CALL_EXPR_ARG (arg, 0);
7514             exponent = build_real (type, real_value_truncate (TYPE_MODE (type),
7515                                                               dconst_third ()));
7516             break;
7517           CASE_FLT_FN (BUILT_IN_POW):
7518             /* Prepare to do logN(pow(x,exponent) -> exponent*logN(x).  */
7519             x = CALL_EXPR_ARG (arg, 0);
7520             exponent = CALL_EXPR_ARG (arg, 1);
7521             break;
7522           default:
7523             break;
7524           }
7525
7526           /* Now perform the optimization.  */
7527           if (x && exponent)
7528             {
7529               tree logfn = build_call_expr_loc (loc, fndecl, 1, x);
7530               return fold_build2_loc (loc, MULT_EXPR, type, exponent, logfn);
7531             }
7532         }
7533     }
7534
7535   return NULL_TREE;
7536 }
7537
7538 /* Fold a builtin function call to hypot, hypotf, or hypotl.  Return
7539    NULL_TREE if no simplification can be made.  */
7540
7541 static tree
7542 fold_builtin_hypot (location_t loc, tree fndecl,
7543                     tree arg0, tree arg1, tree type)
7544 {
7545   tree res, narg0, narg1;
7546
7547   if (!validate_arg (arg0, REAL_TYPE)
7548       || !validate_arg (arg1, REAL_TYPE))
7549     return NULL_TREE;
7550
7551   /* Calculate the result when the argument is a constant.  */
7552   if ((res = do_mpfr_arg2 (arg0, arg1, type, mpfr_hypot)))
7553     return res;
7554
7555   /* If either argument to hypot has a negate or abs, strip that off.
7556      E.g. hypot(-x,fabs(y)) -> hypot(x,y).  */
7557   narg0 = fold_strip_sign_ops (arg0);
7558   narg1 = fold_strip_sign_ops (arg1);
7559   if (narg0 || narg1)
7560     {
7561       return build_call_expr_loc (loc, fndecl, 2, narg0 ? narg0 : arg0,
7562                               narg1 ? narg1 : arg1);
7563     }
7564
7565   /* If either argument is zero, hypot is fabs of the other.  */
7566   if (real_zerop (arg0))
7567     return fold_build1_loc (loc, ABS_EXPR, type, arg1);
7568   else if (real_zerop (arg1))
7569     return fold_build1_loc (loc, ABS_EXPR, type, arg0);
7570
7571   /* hypot(x,x) -> fabs(x)*sqrt(2).  */
7572   if (flag_unsafe_math_optimizations
7573       && operand_equal_p (arg0, arg1, OEP_PURE_SAME))
7574     {
7575       const REAL_VALUE_TYPE sqrt2_trunc
7576         = real_value_truncate (TYPE_MODE (type), dconst_sqrt2 ());
7577       return fold_build2_loc (loc, MULT_EXPR, type,
7578                           fold_build1_loc (loc, ABS_EXPR, type, arg0),
7579                           build_real (type, sqrt2_trunc));
7580     }
7581
7582   return NULL_TREE;
7583 }
7584
7585
7586 /* Fold a builtin function call to pow, powf, or powl.  Return
7587    NULL_TREE if no simplification can be made.  */
7588 static tree
7589 fold_builtin_pow (location_t loc, tree fndecl, tree arg0, tree arg1, tree type)
7590 {
7591   tree res;
7592
7593   if (!validate_arg (arg0, REAL_TYPE)
7594        || !validate_arg (arg1, REAL_TYPE))
7595     return NULL_TREE;
7596
7597   /* Calculate the result when the argument is a constant.  */
7598   if ((res = do_mpfr_arg2 (arg0, arg1, type, mpfr_pow)))
7599     return res;
7600
7601   /* Optimize pow(1.0,y) = 1.0.  */
7602   if (real_onep (arg0))
7603     return omit_one_operand_loc (loc, type, build_real (type, dconst1), arg1);
7604
7605   if (TREE_CODE (arg1) == REAL_CST
7606       && !TREE_OVERFLOW (arg1))
7607     {
7608       REAL_VALUE_TYPE cint;
7609       REAL_VALUE_TYPE c;
7610       HOST_WIDE_INT n;
7611
7612       c = TREE_REAL_CST (arg1);
7613
7614       /* Optimize pow(x,0.0) = 1.0.  */
7615       if (REAL_VALUES_EQUAL (c, dconst0))
7616         return omit_one_operand_loc (loc, type, build_real (type, dconst1),
7617                                  arg0);
7618
7619       /* Optimize pow(x,1.0) = x.  */
7620       if (REAL_VALUES_EQUAL (c, dconst1))
7621         return arg0;
7622
7623       /* Optimize pow(x,-1.0) = 1.0/x.  */
7624       if (REAL_VALUES_EQUAL (c, dconstm1))
7625         return fold_build2_loc (loc, RDIV_EXPR, type,
7626                             build_real (type, dconst1), arg0);
7627
7628       /* Optimize pow(x,0.5) = sqrt(x).  */
7629       if (flag_unsafe_math_optimizations
7630           && REAL_VALUES_EQUAL (c, dconsthalf))
7631         {
7632           tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
7633
7634           if (sqrtfn != NULL_TREE)
7635             return build_call_expr_loc (loc, sqrtfn, 1, arg0);
7636         }
7637
7638       /* Optimize pow(x,1.0/3.0) = cbrt(x).  */
7639       if (flag_unsafe_math_optimizations)
7640         {
7641           const REAL_VALUE_TYPE dconstroot
7642             = real_value_truncate (TYPE_MODE (type), dconst_third ());
7643
7644           if (REAL_VALUES_EQUAL (c, dconstroot))
7645             {
7646               tree cbrtfn = mathfn_built_in (type, BUILT_IN_CBRT);
7647               if (cbrtfn != NULL_TREE)
7648                 return build_call_expr_loc (loc, cbrtfn, 1, arg0);
7649             }
7650         }
7651
7652       /* Check for an integer exponent.  */
7653       n = real_to_integer (&c);
7654       real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
7655       if (real_identical (&c, &cint))
7656         {
7657           /* Attempt to evaluate pow at compile-time, unless this should
7658              raise an exception.  */
7659           if (TREE_CODE (arg0) == REAL_CST
7660               && !TREE_OVERFLOW (arg0)
7661               && (n > 0
7662                   || (!flag_trapping_math && !flag_errno_math)
7663                   || !REAL_VALUES_EQUAL (TREE_REAL_CST (arg0), dconst0)))
7664             {
7665               REAL_VALUE_TYPE x;
7666               bool inexact;
7667
7668               x = TREE_REAL_CST (arg0);
7669               inexact = real_powi (&x, TYPE_MODE (type), &x, n);
7670               if (flag_unsafe_math_optimizations || !inexact)
7671                 return build_real (type, x);
7672             }
7673
7674           /* Strip sign ops from even integer powers.  */
7675           if ((n & 1) == 0 && flag_unsafe_math_optimizations)
7676             {
7677               tree narg0 = fold_strip_sign_ops (arg0);
7678               if (narg0)
7679                 return build_call_expr_loc (loc, fndecl, 2, narg0, arg1);
7680             }
7681         }
7682     }
7683
7684   if (flag_unsafe_math_optimizations)
7685     {
7686       const enum built_in_function fcode = builtin_mathfn_code (arg0);
7687
7688       /* Optimize pow(expN(x),y) = expN(x*y).  */
7689       if (BUILTIN_EXPONENT_P (fcode))
7690         {
7691           tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
7692           tree arg = CALL_EXPR_ARG (arg0, 0);
7693           arg = fold_build2_loc (loc, MULT_EXPR, type, arg, arg1);
7694           return build_call_expr_loc (loc, expfn, 1, arg);
7695         }
7696
7697       /* Optimize pow(sqrt(x),y) = pow(x,y*0.5).  */
7698       if (BUILTIN_SQRT_P (fcode))
7699         {
7700           tree narg0 = CALL_EXPR_ARG (arg0, 0);
7701           tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
7702                                     build_real (type, dconsthalf));
7703           return build_call_expr_loc (loc, fndecl, 2, narg0, narg1);
7704         }
7705
7706       /* Optimize pow(cbrt(x),y) = pow(x,y/3) iff x is nonnegative.  */
7707       if (BUILTIN_CBRT_P (fcode))
7708         {
7709           tree arg = CALL_EXPR_ARG (arg0, 0);
7710           if (tree_expr_nonnegative_p (arg))
7711             {
7712               const REAL_VALUE_TYPE dconstroot
7713                 = real_value_truncate (TYPE_MODE (type), dconst_third ());
7714               tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
7715                                         build_real (type, dconstroot));
7716               return build_call_expr_loc (loc, fndecl, 2, arg, narg1);
7717             }
7718         }
7719
7720       /* Optimize pow(pow(x,y),z) = pow(x,y*z) iff x is nonnegative.  */
7721       if (fcode == BUILT_IN_POW
7722           || fcode == BUILT_IN_POWF
7723           || fcode == BUILT_IN_POWL)
7724         {
7725           tree arg00 = CALL_EXPR_ARG (arg0, 0);
7726           if (tree_expr_nonnegative_p (arg00))
7727             {
7728               tree arg01 = CALL_EXPR_ARG (arg0, 1);
7729               tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg01, arg1);
7730               return build_call_expr_loc (loc, fndecl, 2, arg00, narg1);
7731             }
7732         }
7733     }
7734
7735   return NULL_TREE;
7736 }
7737
7738 /* Fold a builtin function call to powi, powif, or powil with argument ARG.
7739    Return NULL_TREE if no simplification can be made.  */
7740 static tree
7741 fold_builtin_powi (location_t loc, tree fndecl ATTRIBUTE_UNUSED,
7742                    tree arg0, tree arg1, tree type)
7743 {
7744   if (!validate_arg (arg0, REAL_TYPE)
7745       || !validate_arg (arg1, INTEGER_TYPE))
7746     return NULL_TREE;
7747
7748   /* Optimize pow(1.0,y) = 1.0.  */
7749   if (real_onep (arg0))
7750     return omit_one_operand_loc (loc, type, build_real (type, dconst1), arg1);
7751
7752   if (host_integerp (arg1, 0))
7753     {
7754       HOST_WIDE_INT c = TREE_INT_CST_LOW (arg1);
7755
7756       /* Evaluate powi at compile-time.  */
7757       if (TREE_CODE (arg0) == REAL_CST
7758           && !TREE_OVERFLOW (arg0))
7759         {
7760           REAL_VALUE_TYPE x;
7761           x = TREE_REAL_CST (arg0);
7762           real_powi (&x, TYPE_MODE (type), &x, c);
7763           return build_real (type, x);
7764         }
7765
7766       /* Optimize pow(x,0) = 1.0.  */
7767       if (c == 0)
7768         return omit_one_operand_loc (loc, type, build_real (type, dconst1),
7769                                  arg0);
7770
7771       /* Optimize pow(x,1) = x.  */
7772       if (c == 1)
7773         return arg0;
7774
7775       /* Optimize pow(x,-1) = 1.0/x.  */
7776       if (c == -1)
7777         return fold_build2_loc (loc, RDIV_EXPR, type,
7778                            build_real (type, dconst1), arg0);
7779     }
7780
7781   return NULL_TREE;
7782 }
7783
7784 /* A subroutine of fold_builtin to fold the various exponent
7785    functions.  Return NULL_TREE if no simplification can be made.
7786    FUNC is the corresponding MPFR exponent function.  */
7787
7788 static tree
7789 fold_builtin_exponent (location_t loc, tree fndecl, tree arg,
7790                        int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t))
7791 {
7792   if (validate_arg (arg, REAL_TYPE))
7793     {
7794       tree type = TREE_TYPE (TREE_TYPE (fndecl));
7795       tree res;
7796
7797       /* Calculate the result when the argument is a constant.  */
7798       if ((res = do_mpfr_arg1 (arg, type, func, NULL, NULL, 0)))
7799         return res;
7800
7801       /* Optimize expN(logN(x)) = x.  */
7802       if (flag_unsafe_math_optimizations)
7803         {
7804           const enum built_in_function fcode = builtin_mathfn_code (arg);
7805
7806           if ((func == mpfr_exp
7807                && (fcode == BUILT_IN_LOG
7808                    || fcode == BUILT_IN_LOGF
7809                    || fcode == BUILT_IN_LOGL))
7810               || (func == mpfr_exp2
7811                   && (fcode == BUILT_IN_LOG2
7812                       || fcode == BUILT_IN_LOG2F
7813                       || fcode == BUILT_IN_LOG2L))
7814               || (func == mpfr_exp10
7815                   && (fcode == BUILT_IN_LOG10
7816                       || fcode == BUILT_IN_LOG10F
7817                       || fcode == BUILT_IN_LOG10L)))
7818             return fold_convert_loc (loc, type, CALL_EXPR_ARG (arg, 0));
7819         }
7820     }
7821
7822   return NULL_TREE;
7823 }
7824
7825 /* Return true if VAR is a VAR_DECL or a component thereof.  */
7826
7827 static bool
7828 var_decl_component_p (tree var)
7829 {
7830   tree inner = var;
7831   while (handled_component_p (inner))
7832     inner = TREE_OPERAND (inner, 0);
7833   return SSA_VAR_P (inner);
7834 }
7835
7836 /* Fold function call to builtin memset.  Return
7837    NULL_TREE if no simplification can be made.  */
7838
7839 static tree
7840 fold_builtin_memset (location_t loc, tree dest, tree c, tree len,
7841                      tree type, bool ignore)
7842 {
7843   tree var, ret, etype;
7844   unsigned HOST_WIDE_INT length, cval;
7845
7846   if (! validate_arg (dest, POINTER_TYPE)
7847       || ! validate_arg (c, INTEGER_TYPE)
7848       || ! validate_arg (len, INTEGER_TYPE))
7849     return NULL_TREE;
7850
7851   if (! host_integerp (len, 1))
7852     return NULL_TREE;
7853
7854   /* If the LEN parameter is zero, return DEST.  */
7855   if (integer_zerop (len))
7856     return omit_one_operand_loc (loc, type, dest, c);
7857
7858   if (TREE_CODE (c) != INTEGER_CST || TREE_SIDE_EFFECTS (dest))
7859     return NULL_TREE;
7860
7861   var = dest;
7862   STRIP_NOPS (var);
7863   if (TREE_CODE (var) != ADDR_EXPR)
7864     return NULL_TREE;
7865
7866   var = TREE_OPERAND (var, 0);
7867   if (TREE_THIS_VOLATILE (var))
7868     return NULL_TREE;
7869
7870   etype = TREE_TYPE (var);
7871   if (TREE_CODE (etype) == ARRAY_TYPE)
7872     etype = TREE_TYPE (etype);
7873
7874   if (!INTEGRAL_TYPE_P (etype)
7875       && !POINTER_TYPE_P (etype))
7876     return NULL_TREE;
7877
7878   if (! var_decl_component_p (var))
7879     return NULL_TREE;
7880
7881   length = tree_low_cst (len, 1);
7882   if (GET_MODE_SIZE (TYPE_MODE (etype)) != length
7883       || get_pointer_alignment (dest) / BITS_PER_UNIT < length)
7884     return NULL_TREE;
7885
7886   if (length > HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT)
7887     return NULL_TREE;
7888
7889   if (integer_zerop (c))
7890     cval = 0;
7891   else
7892     {
7893       if (CHAR_BIT != 8 || BITS_PER_UNIT != 8 || HOST_BITS_PER_WIDE_INT > 64)
7894         return NULL_TREE;
7895
7896       cval = TREE_INT_CST_LOW (c);
7897       cval &= 0xff;
7898       cval |= cval << 8;
7899       cval |= cval << 16;
7900       cval |= (cval << 31) << 1;
7901     }
7902
7903   ret = build_int_cst_type (etype, cval);
7904   var = build_fold_indirect_ref_loc (loc,
7905                                  fold_convert_loc (loc,
7906                                                    build_pointer_type (etype),
7907                                                    dest));
7908   ret = build2 (MODIFY_EXPR, etype, var, ret);
7909   if (ignore)
7910     return ret;
7911
7912   return omit_one_operand_loc (loc, type, dest, ret);
7913 }
7914
7915 /* Fold function call to builtin memset.  Return
7916    NULL_TREE if no simplification can be made.  */
7917
7918 static tree
7919 fold_builtin_bzero (location_t loc, tree dest, tree size, bool ignore)
7920 {
7921   if (! validate_arg (dest, POINTER_TYPE)
7922       || ! validate_arg (size, INTEGER_TYPE))
7923     return NULL_TREE;
7924
7925   if (!ignore)
7926     return NULL_TREE;
7927
7928   /* New argument list transforming bzero(ptr x, int y) to
7929      memset(ptr x, int 0, size_t y).   This is done this way
7930      so that if it isn't expanded inline, we fallback to
7931      calling bzero instead of memset.  */
7932
7933   return fold_builtin_memset (loc, dest, integer_zero_node,
7934                               fold_convert_loc (loc, sizetype, size),
7935                               void_type_node, ignore);
7936 }
7937
7938 /* Fold function call to builtin mem{{,p}cpy,move}.  Return
7939    NULL_TREE if no simplification can be made.
7940    If ENDP is 0, return DEST (like memcpy).
7941    If ENDP is 1, return DEST+LEN (like mempcpy).
7942    If ENDP is 2, return DEST+LEN-1 (like stpcpy).
7943    If ENDP is 3, return DEST, additionally *SRC and *DEST may overlap
7944    (memmove).   */
7945
7946 static tree
7947 fold_builtin_memory_op (location_t loc, tree dest, tree src,
7948                         tree len, tree type, bool ignore, int endp)
7949 {
7950   tree destvar, srcvar, expr;
7951
7952   if (! validate_arg (dest, POINTER_TYPE)
7953       || ! validate_arg (src, POINTER_TYPE)
7954       || ! validate_arg (len, INTEGER_TYPE))
7955     return NULL_TREE;
7956
7957   /* If the LEN parameter is zero, return DEST.  */
7958   if (integer_zerop (len))
7959     return omit_one_operand_loc (loc, type, dest, src);
7960
7961   /* If SRC and DEST are the same (and not volatile), return
7962      DEST{,+LEN,+LEN-1}.  */
7963   if (operand_equal_p (src, dest, 0))
7964     expr = len;
7965   else
7966     {
7967       tree srctype, desttype;
7968       unsigned int src_align, dest_align;
7969       tree off0;
7970
7971       if (endp == 3)
7972         {
7973           src_align = get_pointer_alignment (src);
7974           dest_align = get_pointer_alignment (dest);
7975
7976           /* Both DEST and SRC must be pointer types.
7977              ??? This is what old code did.  Is the testing for pointer types
7978              really mandatory?
7979
7980              If either SRC is readonly or length is 1, we can use memcpy.  */
7981           if (!dest_align || !src_align)
7982             return NULL_TREE;
7983           if (readonly_data_expr (src)
7984               || (host_integerp (len, 1)
7985                   && (MIN (src_align, dest_align) / BITS_PER_UNIT
7986                       >= (unsigned HOST_WIDE_INT) tree_low_cst (len, 1))))
7987             {
7988               tree fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
7989               if (!fn)
7990                 return NULL_TREE;
7991               return build_call_expr_loc (loc, fn, 3, dest, src, len);
7992             }
7993
7994           /* If *src and *dest can't overlap, optimize into memcpy as well.  */
7995           if (TREE_CODE (src) == ADDR_EXPR
7996               && TREE_CODE (dest) == ADDR_EXPR)
7997             {
7998               tree src_base, dest_base, fn;
7999               HOST_WIDE_INT src_offset = 0, dest_offset = 0;
8000               HOST_WIDE_INT size = -1;
8001               HOST_WIDE_INT maxsize = -1;
8002
8003               srcvar = TREE_OPERAND (src, 0);
8004               src_base = get_ref_base_and_extent (srcvar, &src_offset,
8005                                                   &size, &maxsize);
8006               destvar = TREE_OPERAND (dest, 0);
8007               dest_base = get_ref_base_and_extent (destvar, &dest_offset,
8008                                                    &size, &maxsize);
8009               if (host_integerp (len, 1))
8010                 maxsize = tree_low_cst (len, 1);
8011               else
8012                 maxsize = -1;
8013               src_offset /= BITS_PER_UNIT;
8014               dest_offset /= BITS_PER_UNIT;
8015               if (SSA_VAR_P (src_base)
8016                   && SSA_VAR_P (dest_base))
8017                 {
8018                   if (operand_equal_p (src_base, dest_base, 0)
8019                       && ranges_overlap_p (src_offset, maxsize,
8020                                            dest_offset, maxsize))
8021                     return NULL_TREE;
8022                 }
8023               else if (TREE_CODE (src_base) == MEM_REF
8024                        && TREE_CODE (dest_base) == MEM_REF)
8025                 {
8026                   double_int off;
8027                   if (! operand_equal_p (TREE_OPERAND (src_base, 0),
8028                                          TREE_OPERAND (dest_base, 0), 0))
8029                     return NULL_TREE;
8030                   off = double_int_add (mem_ref_offset (src_base),
8031                                         shwi_to_double_int (src_offset));
8032                   if (!double_int_fits_in_shwi_p (off))
8033                     return NULL_TREE;
8034                   src_offset = off.low;
8035                   off = double_int_add (mem_ref_offset (dest_base),
8036                                         shwi_to_double_int (dest_offset));
8037                   if (!double_int_fits_in_shwi_p (off))
8038                     return NULL_TREE;
8039                   dest_offset = off.low;
8040                   if (ranges_overlap_p (src_offset, maxsize,
8041                                         dest_offset, maxsize))
8042                     return NULL_TREE;
8043                 }
8044               else
8045                 return NULL_TREE;
8046
8047               fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8048               if (!fn)
8049                 return NULL_TREE;
8050               return build_call_expr_loc (loc, fn, 3, dest, src, len);
8051             }
8052
8053           /* If the destination and source do not alias optimize into
8054              memcpy as well.  */
8055           if ((is_gimple_min_invariant (dest)
8056                || TREE_CODE (dest) == SSA_NAME)
8057               && (is_gimple_min_invariant (src)
8058                   || TREE_CODE (src) == SSA_NAME))
8059             {
8060               ao_ref destr, srcr;
8061               ao_ref_init_from_ptr_and_size (&destr, dest, len);
8062               ao_ref_init_from_ptr_and_size (&srcr, src, len);
8063               if (!refs_may_alias_p_1 (&destr, &srcr, false))
8064                 {
8065                   tree fn;
8066                   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8067                   if (!fn)
8068                     return NULL_TREE;
8069                   return build_call_expr_loc (loc, fn, 3, dest, src, len);
8070                 }
8071             }
8072
8073           return NULL_TREE;
8074         }
8075
8076       if (!host_integerp (len, 0))
8077         return NULL_TREE;
8078       /* FIXME:
8079          This logic lose for arguments like (type *)malloc (sizeof (type)),
8080          since we strip the casts of up to VOID return value from malloc.
8081          Perhaps we ought to inherit type from non-VOID argument here?  */
8082       STRIP_NOPS (src);
8083       STRIP_NOPS (dest);
8084       if (!POINTER_TYPE_P (TREE_TYPE (src))
8085           || !POINTER_TYPE_P (TREE_TYPE (dest)))
8086         return NULL_TREE;
8087       /* As we fold (void *)(p + CST) to (void *)p + CST undo this here.  */
8088       if (TREE_CODE (src) == POINTER_PLUS_EXPR)
8089         {
8090           tree tem = TREE_OPERAND (src, 0);
8091           STRIP_NOPS (tem);
8092           if (tem != TREE_OPERAND (src, 0))
8093             src = build1 (NOP_EXPR, TREE_TYPE (tem), src);
8094         }
8095       if (TREE_CODE (dest) == POINTER_PLUS_EXPR)
8096         {
8097           tree tem = TREE_OPERAND (dest, 0);
8098           STRIP_NOPS (tem);
8099           if (tem != TREE_OPERAND (dest, 0))
8100             dest = build1 (NOP_EXPR, TREE_TYPE (tem), dest);
8101         }
8102       srctype = TREE_TYPE (TREE_TYPE (src));
8103       if (TREE_CODE (srctype) == ARRAY_TYPE
8104           && !tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
8105         {
8106           srctype = TREE_TYPE (srctype);
8107           STRIP_NOPS (src);
8108           src = build1 (NOP_EXPR, build_pointer_type (srctype), src);
8109         }
8110       desttype = TREE_TYPE (TREE_TYPE (dest));
8111       if (TREE_CODE (desttype) == ARRAY_TYPE
8112           && !tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
8113         {
8114           desttype = TREE_TYPE (desttype);
8115           STRIP_NOPS (dest);
8116           dest = build1 (NOP_EXPR, build_pointer_type (desttype), dest);
8117         }
8118       if (TREE_ADDRESSABLE (srctype)
8119           || TREE_ADDRESSABLE (desttype))
8120         return NULL_TREE;
8121
8122       src_align = get_pointer_alignment (src);
8123       dest_align = get_pointer_alignment (dest);
8124       if (dest_align < TYPE_ALIGN (desttype)
8125           || src_align < TYPE_ALIGN (srctype))
8126         return NULL_TREE;
8127
8128       if (!ignore)
8129         dest = builtin_save_expr (dest);
8130
8131       /* Build accesses at offset zero with a ref-all character type.  */
8132       off0 = build_int_cst (build_pointer_type_for_mode (char_type_node,
8133                                                          ptr_mode, true), 0);
8134
8135       destvar = dest;
8136       STRIP_NOPS (destvar);
8137       if (TREE_CODE (destvar) == ADDR_EXPR
8138           && var_decl_component_p (TREE_OPERAND (destvar, 0))
8139           && tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
8140         destvar = fold_build2 (MEM_REF, desttype, destvar, off0);
8141       else
8142         destvar = NULL_TREE;
8143
8144       srcvar = src;
8145       STRIP_NOPS (srcvar);
8146       if (TREE_CODE (srcvar) == ADDR_EXPR
8147           && var_decl_component_p (TREE_OPERAND (srcvar, 0))
8148           && tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
8149         {
8150           if (!destvar
8151               || src_align >= TYPE_ALIGN (desttype))
8152             srcvar = fold_build2 (MEM_REF, destvar ? desttype : srctype,
8153                                   srcvar, off0);
8154           else if (!STRICT_ALIGNMENT)
8155             {
8156               srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
8157                                             src_align);
8158               srcvar = fold_build2 (MEM_REF, srctype, srcvar, off0);
8159             }
8160           else
8161             srcvar = NULL_TREE;
8162         }
8163       else
8164         srcvar = NULL_TREE;
8165
8166       if (srcvar == NULL_TREE && destvar == NULL_TREE)
8167         return NULL_TREE;
8168
8169       if (srcvar == NULL_TREE)
8170         {
8171           STRIP_NOPS (src);
8172           if (src_align >= TYPE_ALIGN (desttype))
8173             srcvar = fold_build2 (MEM_REF, desttype, src, off0);
8174           else
8175             {
8176               if (STRICT_ALIGNMENT)
8177                 return NULL_TREE;
8178               srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
8179                                             src_align);
8180               srcvar = fold_build2 (MEM_REF, srctype, src, off0);
8181             }
8182         }
8183       else if (destvar == NULL_TREE)
8184         {
8185           STRIP_NOPS (dest);
8186           if (dest_align >= TYPE_ALIGN (srctype))
8187             destvar = fold_build2 (MEM_REF, srctype, dest, off0);
8188           else
8189             {
8190               if (STRICT_ALIGNMENT)
8191                 return NULL_TREE;
8192               desttype = build_aligned_type (TYPE_MAIN_VARIANT (srctype),
8193                                              dest_align);
8194               destvar = fold_build2 (MEM_REF, desttype, dest, off0);
8195             }
8196         }
8197
8198       expr = build2 (MODIFY_EXPR, TREE_TYPE (destvar), destvar, srcvar);
8199     }
8200
8201   if (ignore)
8202     return expr;
8203
8204   if (endp == 0 || endp == 3)
8205     return omit_one_operand_loc (loc, type, dest, expr);
8206
8207   if (expr == len)
8208     expr = NULL_TREE;
8209
8210   if (endp == 2)
8211     len = fold_build2_loc (loc, MINUS_EXPR, TREE_TYPE (len), len,
8212                        ssize_int (1));
8213
8214   dest = fold_build_pointer_plus_loc (loc, dest, len);
8215   dest = fold_convert_loc (loc, type, dest);
8216   if (expr)
8217     dest = omit_one_operand_loc (loc, type, dest, expr);
8218   return dest;
8219 }
8220
8221 /* Fold function call to builtin strcpy with arguments DEST and SRC.
8222    If LEN is not NULL, it represents the length of the string to be
8223    copied.  Return NULL_TREE if no simplification can be made.  */
8224
8225 tree
8226 fold_builtin_strcpy (location_t loc, tree fndecl, tree dest, tree src, tree len)
8227 {
8228   tree fn;
8229
8230   if (!validate_arg (dest, POINTER_TYPE)
8231       || !validate_arg (src, POINTER_TYPE))
8232     return NULL_TREE;
8233
8234   /* If SRC and DEST are the same (and not volatile), return DEST.  */
8235   if (operand_equal_p (src, dest, 0))
8236     return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest);
8237
8238   if (optimize_function_for_size_p (cfun))
8239     return NULL_TREE;
8240
8241   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8242   if (!fn)
8243     return NULL_TREE;
8244
8245   if (!len)
8246     {
8247       len = c_strlen (src, 1);
8248       if (! len || TREE_SIDE_EFFECTS (len))
8249         return NULL_TREE;
8250     }
8251
8252   len = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
8253   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
8254                            build_call_expr_loc (loc, fn, 3, dest, src, len));
8255 }
8256
8257 /* Fold function call to builtin stpcpy with arguments DEST and SRC.
8258    Return NULL_TREE if no simplification can be made.  */
8259
8260 static tree
8261 fold_builtin_stpcpy (location_t loc, tree fndecl, tree dest, tree src)
8262 {
8263   tree fn, len, lenp1, call, type;
8264
8265   if (!validate_arg (dest, POINTER_TYPE)
8266       || !validate_arg (src, POINTER_TYPE))
8267     return NULL_TREE;
8268
8269   len = c_strlen (src, 1);
8270   if (!len
8271       || TREE_CODE (len) != INTEGER_CST)
8272     return NULL_TREE;
8273
8274   if (optimize_function_for_size_p (cfun)
8275       /* If length is zero it's small enough.  */
8276       && !integer_zerop (len))
8277     return NULL_TREE;
8278
8279   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8280   if (!fn)
8281     return NULL_TREE;
8282
8283   lenp1 = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
8284   /* We use dest twice in building our expression.  Save it from
8285      multiple expansions.  */
8286   dest = builtin_save_expr (dest);
8287   call = build_call_expr_loc (loc, fn, 3, dest, src, lenp1);
8288
8289   type = TREE_TYPE (TREE_TYPE (fndecl));
8290   dest = fold_build_pointer_plus_loc (loc, dest, len);
8291   dest = fold_convert_loc (loc, type, dest);
8292   dest = omit_one_operand_loc (loc, type, dest, call);
8293   return dest;
8294 }
8295
8296 /* Fold function call to builtin strncpy with arguments DEST, SRC, and LEN.
8297    If SLEN is not NULL, it represents the length of the source string.
8298    Return NULL_TREE if no simplification can be made.  */
8299
8300 tree
8301 fold_builtin_strncpy (location_t loc, tree fndecl, tree dest,
8302                       tree src, tree len, tree slen)
8303 {
8304   tree fn;
8305
8306   if (!validate_arg (dest, POINTER_TYPE)
8307       || !validate_arg (src, POINTER_TYPE)
8308       || !validate_arg (len, INTEGER_TYPE))
8309     return NULL_TREE;
8310
8311   /* If the LEN parameter is zero, return DEST.  */
8312   if (integer_zerop (len))
8313     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
8314
8315   /* We can't compare slen with len as constants below if len is not a
8316      constant.  */
8317   if (len == 0 || TREE_CODE (len) != INTEGER_CST)
8318     return NULL_TREE;
8319
8320   if (!slen)
8321     slen = c_strlen (src, 1);
8322
8323   /* Now, we must be passed a constant src ptr parameter.  */
8324   if (slen == 0 || TREE_CODE (slen) != INTEGER_CST)
8325     return NULL_TREE;
8326
8327   slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
8328
8329   /* We do not support simplification of this case, though we do
8330      support it when expanding trees into RTL.  */
8331   /* FIXME: generate a call to __builtin_memset.  */
8332   if (tree_int_cst_lt (slen, len))
8333     return NULL_TREE;
8334
8335   /* OK transform into builtin memcpy.  */
8336   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8337   if (!fn)
8338     return NULL_TREE;
8339   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
8340                            build_call_expr_loc (loc, fn, 3, dest, src, len));
8341 }
8342
8343 /* Fold function call to builtin memchr.  ARG1, ARG2 and LEN are the
8344    arguments to the call, and TYPE is its return type.
8345    Return NULL_TREE if no simplification can be made.  */
8346
8347 static tree
8348 fold_builtin_memchr (location_t loc, tree arg1, tree arg2, tree len, tree type)
8349 {
8350   if (!validate_arg (arg1, POINTER_TYPE)
8351       || !validate_arg (arg2, INTEGER_TYPE)
8352       || !validate_arg (len, INTEGER_TYPE))
8353     return NULL_TREE;
8354   else
8355     {
8356       const char *p1;
8357
8358       if (TREE_CODE (arg2) != INTEGER_CST
8359           || !host_integerp (len, 1))
8360         return NULL_TREE;
8361
8362       p1 = c_getstr (arg1);
8363       if (p1 && compare_tree_int (len, strlen (p1) + 1) <= 0)
8364         {
8365           char c;
8366           const char *r;
8367           tree tem;
8368
8369           if (target_char_cast (arg2, &c))
8370             return NULL_TREE;
8371
8372           r = (char *) memchr (p1, c, tree_low_cst (len, 1));
8373
8374           if (r == NULL)
8375             return build_int_cst (TREE_TYPE (arg1), 0);
8376
8377           tem = fold_build_pointer_plus_hwi_loc (loc, arg1, r - p1);
8378           return fold_convert_loc (loc, type, tem);
8379         }
8380       return NULL_TREE;
8381     }
8382 }
8383
8384 /* Fold function call to builtin memcmp with arguments ARG1 and ARG2.
8385    Return NULL_TREE if no simplification can be made.  */
8386
8387 static tree
8388 fold_builtin_memcmp (location_t loc, tree arg1, tree arg2, tree len)
8389 {
8390   const char *p1, *p2;
8391
8392   if (!validate_arg (arg1, POINTER_TYPE)
8393       || !validate_arg (arg2, POINTER_TYPE)
8394       || !validate_arg (len, INTEGER_TYPE))
8395     return NULL_TREE;
8396
8397   /* If the LEN parameter is zero, return zero.  */
8398   if (integer_zerop (len))
8399     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
8400                               arg1, arg2);
8401
8402   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
8403   if (operand_equal_p (arg1, arg2, 0))
8404     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
8405
8406   p1 = c_getstr (arg1);
8407   p2 = c_getstr (arg2);
8408
8409   /* If all arguments are constant, and the value of len is not greater
8410      than the lengths of arg1 and arg2, evaluate at compile-time.  */
8411   if (host_integerp (len, 1) && p1 && p2
8412       && compare_tree_int (len, strlen (p1) + 1) <= 0
8413       && compare_tree_int (len, strlen (p2) + 1) <= 0)
8414     {
8415       const int r = memcmp (p1, p2, tree_low_cst (len, 1));
8416
8417       if (r > 0)
8418         return integer_one_node;
8419       else if (r < 0)
8420         return integer_minus_one_node;
8421       else
8422         return integer_zero_node;
8423     }
8424
8425   /* If len parameter is one, return an expression corresponding to
8426      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
8427   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
8428     {
8429       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8430       tree cst_uchar_ptr_node
8431         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8432
8433       tree ind1
8434         = fold_convert_loc (loc, integer_type_node,
8435                             build1 (INDIRECT_REF, cst_uchar_node,
8436                                     fold_convert_loc (loc,
8437                                                       cst_uchar_ptr_node,
8438                                                       arg1)));
8439       tree ind2
8440         = fold_convert_loc (loc, integer_type_node,
8441                             build1 (INDIRECT_REF, cst_uchar_node,
8442                                     fold_convert_loc (loc,
8443                                                       cst_uchar_ptr_node,
8444                                                       arg2)));
8445       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
8446     }
8447
8448   return NULL_TREE;
8449 }
8450
8451 /* Fold function call to builtin strcmp with arguments ARG1 and ARG2.
8452    Return NULL_TREE if no simplification can be made.  */
8453
8454 static tree
8455 fold_builtin_strcmp (location_t loc, tree arg1, tree arg2)
8456 {
8457   const char *p1, *p2;
8458
8459   if (!validate_arg (arg1, POINTER_TYPE)
8460       || !validate_arg (arg2, POINTER_TYPE))
8461     return NULL_TREE;
8462
8463   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
8464   if (operand_equal_p (arg1, arg2, 0))
8465     return integer_zero_node;
8466
8467   p1 = c_getstr (arg1);
8468   p2 = c_getstr (arg2);
8469
8470   if (p1 && p2)
8471     {
8472       const int i = strcmp (p1, p2);
8473       if (i < 0)
8474         return integer_minus_one_node;
8475       else if (i > 0)
8476         return integer_one_node;
8477       else
8478         return integer_zero_node;
8479     }
8480
8481   /* If the second arg is "", return *(const unsigned char*)arg1.  */
8482   if (p2 && *p2 == '\0')
8483     {
8484       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8485       tree cst_uchar_ptr_node
8486         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8487
8488       return fold_convert_loc (loc, integer_type_node,
8489                                build1 (INDIRECT_REF, cst_uchar_node,
8490                                        fold_convert_loc (loc,
8491                                                          cst_uchar_ptr_node,
8492                                                          arg1)));
8493     }
8494
8495   /* If the first arg is "", return -*(const unsigned char*)arg2.  */
8496   if (p1 && *p1 == '\0')
8497     {
8498       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8499       tree cst_uchar_ptr_node
8500         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8501
8502       tree temp
8503         = fold_convert_loc (loc, integer_type_node,
8504                             build1 (INDIRECT_REF, cst_uchar_node,
8505                                     fold_convert_loc (loc,
8506                                                       cst_uchar_ptr_node,
8507                                                       arg2)));
8508       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
8509     }
8510
8511   return NULL_TREE;
8512 }
8513
8514 /* Fold function call to builtin strncmp with arguments ARG1, ARG2, and LEN.
8515    Return NULL_TREE if no simplification can be made.  */
8516
8517 static tree
8518 fold_builtin_strncmp (location_t loc, tree arg1, tree arg2, tree len)
8519 {
8520   const char *p1, *p2;
8521
8522   if (!validate_arg (arg1, POINTER_TYPE)
8523       || !validate_arg (arg2, POINTER_TYPE)
8524       || !validate_arg (len, INTEGER_TYPE))
8525     return NULL_TREE;
8526
8527   /* If the LEN parameter is zero, return zero.  */
8528   if (integer_zerop (len))
8529     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
8530                               arg1, arg2);
8531
8532   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
8533   if (operand_equal_p (arg1, arg2, 0))
8534     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
8535
8536   p1 = c_getstr (arg1);
8537   p2 = c_getstr (arg2);
8538
8539   if (host_integerp (len, 1) && p1 && p2)
8540     {
8541       const int i = strncmp (p1, p2, tree_low_cst (len, 1));
8542       if (i > 0)
8543         return integer_one_node;
8544       else if (i < 0)
8545         return integer_minus_one_node;
8546       else
8547         return integer_zero_node;
8548     }
8549
8550   /* If the second arg is "", and the length is greater than zero,
8551      return *(const unsigned char*)arg1.  */
8552   if (p2 && *p2 == '\0'
8553       && TREE_CODE (len) == INTEGER_CST
8554       && tree_int_cst_sgn (len) == 1)
8555     {
8556       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8557       tree cst_uchar_ptr_node
8558         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8559
8560       return fold_convert_loc (loc, integer_type_node,
8561                                build1 (INDIRECT_REF, cst_uchar_node,
8562                                        fold_convert_loc (loc,
8563                                                          cst_uchar_ptr_node,
8564                                                          arg1)));
8565     }
8566
8567   /* If the first arg is "", and the length is greater than zero,
8568      return -*(const unsigned char*)arg2.  */
8569   if (p1 && *p1 == '\0'
8570       && TREE_CODE (len) == INTEGER_CST
8571       && tree_int_cst_sgn (len) == 1)
8572     {
8573       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8574       tree cst_uchar_ptr_node
8575         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8576
8577       tree temp = fold_convert_loc (loc, integer_type_node,
8578                                     build1 (INDIRECT_REF, cst_uchar_node,
8579                                             fold_convert_loc (loc,
8580                                                               cst_uchar_ptr_node,
8581                                                               arg2)));
8582       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
8583     }
8584
8585   /* If len parameter is one, return an expression corresponding to
8586      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
8587   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
8588     {
8589       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8590       tree cst_uchar_ptr_node
8591         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8592
8593       tree ind1 = fold_convert_loc (loc, integer_type_node,
8594                                     build1 (INDIRECT_REF, cst_uchar_node,
8595                                             fold_convert_loc (loc,
8596                                                               cst_uchar_ptr_node,
8597                                                               arg1)));
8598       tree ind2 = fold_convert_loc (loc, integer_type_node,
8599                                     build1 (INDIRECT_REF, cst_uchar_node,
8600                                             fold_convert_loc (loc,
8601                                                               cst_uchar_ptr_node,
8602                                                               arg2)));
8603       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
8604     }
8605
8606   return NULL_TREE;
8607 }
8608
8609 /* Fold function call to builtin signbit, signbitf or signbitl with argument
8610    ARG.  Return NULL_TREE if no simplification can be made.  */
8611
8612 static tree
8613 fold_builtin_signbit (location_t loc, tree arg, tree type)
8614 {
8615   if (!validate_arg (arg, REAL_TYPE))
8616     return NULL_TREE;
8617
8618   /* If ARG is a compile-time constant, determine the result.  */
8619   if (TREE_CODE (arg) == REAL_CST
8620       && !TREE_OVERFLOW (arg))
8621     {
8622       REAL_VALUE_TYPE c;
8623
8624       c = TREE_REAL_CST (arg);
8625       return (REAL_VALUE_NEGATIVE (c)
8626               ? build_one_cst (type)
8627               : build_zero_cst (type));
8628     }
8629
8630   /* If ARG is non-negative, the result is always zero.  */
8631   if (tree_expr_nonnegative_p (arg))
8632     return omit_one_operand_loc (loc, type, integer_zero_node, arg);
8633
8634   /* If ARG's format doesn't have signed zeros, return "arg < 0.0".  */
8635   if (!HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (arg))))
8636     return fold_convert (type,
8637                          fold_build2_loc (loc, LT_EXPR, boolean_type_node, arg,
8638                         build_real (TREE_TYPE (arg), dconst0)));
8639
8640   return NULL_TREE;
8641 }
8642
8643 /* Fold function call to builtin copysign, copysignf or copysignl with
8644    arguments ARG1 and ARG2.  Return NULL_TREE if no simplification can
8645    be made.  */
8646
8647 static tree
8648 fold_builtin_copysign (location_t loc, tree fndecl,
8649                        tree arg1, tree arg2, tree type)
8650 {
8651   tree tem;
8652
8653   if (!validate_arg (arg1, REAL_TYPE)
8654       || !validate_arg (arg2, REAL_TYPE))
8655     return NULL_TREE;
8656
8657   /* copysign(X,X) is X.  */
8658   if (operand_equal_p (arg1, arg2, 0))
8659     return fold_convert_loc (loc, type, arg1);
8660
8661   /* If ARG1 and ARG2 are compile-time constants, determine the result.  */
8662   if (TREE_CODE (arg1) == REAL_CST
8663       && TREE_CODE (arg2) == REAL_CST
8664       && !TREE_OVERFLOW (arg1)
8665       && !TREE_OVERFLOW (arg2))
8666     {
8667       REAL_VALUE_TYPE c1, c2;
8668
8669       c1 = TREE_REAL_CST (arg1);
8670       c2 = TREE_REAL_CST (arg2);
8671       /* c1.sign := c2.sign.  */
8672       real_copysign (&c1, &c2);
8673       return build_real (type, c1);
8674     }
8675
8676   /* copysign(X, Y) is fabs(X) when Y is always non-negative.
8677      Remember to evaluate Y for side-effects.  */
8678   if (tree_expr_nonnegative_p (arg2))
8679     return omit_one_operand_loc (loc, type,
8680                              fold_build1_loc (loc, ABS_EXPR, type, arg1),
8681                              arg2);
8682
8683   /* Strip sign changing operations for the first argument.  */
8684   tem = fold_strip_sign_ops (arg1);
8685   if (tem)
8686     return build_call_expr_loc (loc, fndecl, 2, tem, arg2);
8687
8688   return NULL_TREE;
8689 }
8690
8691 /* Fold a call to builtin isascii with argument ARG.  */
8692
8693 static tree
8694 fold_builtin_isascii (location_t loc, tree arg)
8695 {
8696   if (!validate_arg (arg, INTEGER_TYPE))
8697     return NULL_TREE;
8698   else
8699     {
8700       /* Transform isascii(c) -> ((c & ~0x7f) == 0).  */
8701       arg = fold_build2 (BIT_AND_EXPR, integer_type_node, arg,
8702                          build_int_cst (integer_type_node,
8703                                         ~ (unsigned HOST_WIDE_INT) 0x7f));
8704       return fold_build2_loc (loc, EQ_EXPR, integer_type_node,
8705                               arg, integer_zero_node);
8706     }
8707 }
8708
8709 /* Fold a call to builtin toascii with argument ARG.  */
8710
8711 static tree
8712 fold_builtin_toascii (location_t loc, tree arg)
8713 {
8714   if (!validate_arg (arg, INTEGER_TYPE))
8715     return NULL_TREE;
8716
8717   /* Transform toascii(c) -> (c & 0x7f).  */
8718   return fold_build2_loc (loc, BIT_AND_EXPR, integer_type_node, arg,
8719                           build_int_cst (integer_type_node, 0x7f));
8720 }
8721
8722 /* Fold a call to builtin isdigit with argument ARG.  */
8723
8724 static tree
8725 fold_builtin_isdigit (location_t loc, tree arg)
8726 {
8727   if (!validate_arg (arg, INTEGER_TYPE))
8728     return NULL_TREE;
8729   else
8730     {
8731       /* Transform isdigit(c) -> (unsigned)(c) - '0' <= 9.  */
8732       /* According to the C standard, isdigit is unaffected by locale.
8733          However, it definitely is affected by the target character set.  */
8734       unsigned HOST_WIDE_INT target_digit0
8735         = lang_hooks.to_target_charset ('0');
8736
8737       if (target_digit0 == 0)
8738         return NULL_TREE;
8739
8740       arg = fold_convert_loc (loc, unsigned_type_node, arg);
8741       arg = fold_build2 (MINUS_EXPR, unsigned_type_node, arg,
8742                          build_int_cst (unsigned_type_node, target_digit0));
8743       return fold_build2_loc (loc, LE_EXPR, integer_type_node, arg,
8744                           build_int_cst (unsigned_type_node, 9));
8745     }
8746 }
8747
8748 /* Fold a call to fabs, fabsf or fabsl with argument ARG.  */
8749
8750 static tree
8751 fold_builtin_fabs (location_t loc, tree arg, tree type)
8752 {
8753   if (!validate_arg (arg, REAL_TYPE))
8754     return NULL_TREE;
8755
8756   arg = fold_convert_loc (loc, type, arg);
8757   if (TREE_CODE (arg) == REAL_CST)
8758     return fold_abs_const (arg, type);
8759   return fold_build1_loc (loc, ABS_EXPR, type, arg);
8760 }
8761
8762 /* Fold a call to abs, labs, llabs or imaxabs with argument ARG.  */
8763
8764 static tree
8765 fold_builtin_abs (location_t loc, tree arg, tree type)
8766 {
8767   if (!validate_arg (arg, INTEGER_TYPE))
8768     return NULL_TREE;
8769
8770   arg = fold_convert_loc (loc, type, arg);
8771   if (TREE_CODE (arg) == INTEGER_CST)
8772     return fold_abs_const (arg, type);
8773   return fold_build1_loc (loc, ABS_EXPR, type, arg);
8774 }
8775
8776 /* Fold a fma operation with arguments ARG[012].  */
8777
8778 tree
8779 fold_fma (location_t loc ATTRIBUTE_UNUSED,
8780           tree type, tree arg0, tree arg1, tree arg2)
8781 {
8782   if (TREE_CODE (arg0) == REAL_CST
8783       && TREE_CODE (arg1) == REAL_CST
8784       && TREE_CODE (arg2) == REAL_CST)
8785     return do_mpfr_arg3 (arg0, arg1, arg2, type, mpfr_fma);
8786
8787   return NULL_TREE;
8788 }
8789
8790 /* Fold a call to fma, fmaf, or fmal with arguments ARG[012].  */
8791
8792 static tree
8793 fold_builtin_fma (location_t loc, tree arg0, tree arg1, tree arg2, tree type)
8794 {
8795   if (validate_arg (arg0, REAL_TYPE)
8796       && validate_arg(arg1, REAL_TYPE)
8797       && validate_arg(arg2, REAL_TYPE))
8798     {
8799       tree tem = fold_fma (loc, type, arg0, arg1, arg2);
8800       if (tem)
8801         return tem;
8802
8803       /* ??? Only expand to FMA_EXPR if it's directly supported.  */
8804       if (optab_handler (fma_optab, TYPE_MODE (type)) != CODE_FOR_nothing)
8805         return fold_build3_loc (loc, FMA_EXPR, type, arg0, arg1, arg2);
8806     }
8807   return NULL_TREE;
8808 }
8809
8810 /* Fold a call to builtin fmin or fmax.  */
8811
8812 static tree
8813 fold_builtin_fmin_fmax (location_t loc, tree arg0, tree arg1,
8814                         tree type, bool max)
8815 {
8816   if (validate_arg (arg0, REAL_TYPE) && validate_arg (arg1, REAL_TYPE))
8817     {
8818       /* Calculate the result when the argument is a constant.  */
8819       tree res = do_mpfr_arg2 (arg0, arg1, type, (max ? mpfr_max : mpfr_min));
8820
8821       if (res)
8822         return res;
8823
8824       /* If either argument is NaN, return the other one.  Avoid the
8825          transformation if we get (and honor) a signalling NaN.  Using
8826          omit_one_operand() ensures we create a non-lvalue.  */
8827       if (TREE_CODE (arg0) == REAL_CST
8828           && real_isnan (&TREE_REAL_CST (arg0))
8829           && (! HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg0)))
8830               || ! TREE_REAL_CST (arg0).signalling))
8831         return omit_one_operand_loc (loc, type, arg1, arg0);
8832       if (TREE_CODE (arg1) == REAL_CST
8833           && real_isnan (&TREE_REAL_CST (arg1))
8834           && (! HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg1)))
8835               || ! TREE_REAL_CST (arg1).signalling))
8836         return omit_one_operand_loc (loc, type, arg0, arg1);
8837
8838       /* Transform fmin/fmax(x,x) -> x.  */
8839       if (operand_equal_p (arg0, arg1, OEP_PURE_SAME))
8840         return omit_one_operand_loc (loc, type, arg0, arg1);
8841
8842       /* Convert fmin/fmax to MIN_EXPR/MAX_EXPR.  C99 requires these
8843          functions to return the numeric arg if the other one is NaN.
8844          These tree codes don't honor that, so only transform if
8845          -ffinite-math-only is set.  C99 doesn't require -0.0 to be
8846          handled, so we don't have to worry about it either.  */
8847       if (flag_finite_math_only)
8848         return fold_build2_loc (loc, (max ? MAX_EXPR : MIN_EXPR), type,
8849                             fold_convert_loc (loc, type, arg0),
8850                             fold_convert_loc (loc, type, arg1));
8851     }
8852   return NULL_TREE;
8853 }
8854
8855 /* Fold a call to builtin carg(a+bi) -> atan2(b,a).  */
8856
8857 static tree
8858 fold_builtin_carg (location_t loc, tree arg, tree type)
8859 {
8860   if (validate_arg (arg, COMPLEX_TYPE)
8861       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE)
8862     {
8863       tree atan2_fn = mathfn_built_in (type, BUILT_IN_ATAN2);
8864
8865       if (atan2_fn)
8866         {
8867           tree new_arg = builtin_save_expr (arg);
8868           tree r_arg = fold_build1_loc (loc, REALPART_EXPR, type, new_arg);
8869           tree i_arg = fold_build1_loc (loc, IMAGPART_EXPR, type, new_arg);
8870           return build_call_expr_loc (loc, atan2_fn, 2, i_arg, r_arg);
8871         }
8872     }
8873
8874   return NULL_TREE;
8875 }
8876
8877 /* Fold a call to builtin logb/ilogb.  */
8878
8879 static tree
8880 fold_builtin_logb (location_t loc, tree arg, tree rettype)
8881 {
8882   if (! validate_arg (arg, REAL_TYPE))
8883     return NULL_TREE;
8884
8885   STRIP_NOPS (arg);
8886
8887   if (TREE_CODE (arg) == REAL_CST && ! TREE_OVERFLOW (arg))
8888     {
8889       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg);
8890
8891       switch (value->cl)
8892       {
8893       case rvc_nan:
8894       case rvc_inf:
8895         /* If arg is Inf or NaN and we're logb, return it.  */
8896         if (TREE_CODE (rettype) == REAL_TYPE)
8897           return fold_convert_loc (loc, rettype, arg);
8898         /* Fall through... */
8899       case rvc_zero:
8900         /* Zero may set errno and/or raise an exception for logb, also
8901            for ilogb we don't know FP_ILOGB0.  */
8902         return NULL_TREE;
8903       case rvc_normal:
8904         /* For normal numbers, proceed iff radix == 2.  In GCC,
8905            normalized significands are in the range [0.5, 1.0).  We
8906            want the exponent as if they were [1.0, 2.0) so get the
8907            exponent and subtract 1.  */
8908         if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->b == 2)
8909           return fold_convert_loc (loc, rettype,
8910                                    build_int_cst (integer_type_node,
8911                                                   REAL_EXP (value)-1));
8912         break;
8913       }
8914     }
8915
8916   return NULL_TREE;
8917 }
8918
8919 /* Fold a call to builtin significand, if radix == 2.  */
8920
8921 static tree
8922 fold_builtin_significand (location_t loc, tree arg, tree rettype)
8923 {
8924   if (! validate_arg (arg, REAL_TYPE))
8925     return NULL_TREE;
8926
8927   STRIP_NOPS (arg);
8928
8929   if (TREE_CODE (arg) == REAL_CST && ! TREE_OVERFLOW (arg))
8930     {
8931       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg);
8932
8933       switch (value->cl)
8934       {
8935       case rvc_zero:
8936       case rvc_nan:
8937       case rvc_inf:
8938         /* If arg is +-0, +-Inf or +-NaN, then return it.  */
8939         return fold_convert_loc (loc, rettype, arg);
8940       case rvc_normal:
8941         /* For normal numbers, proceed iff radix == 2.  */
8942         if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->b == 2)
8943           {
8944             REAL_VALUE_TYPE result = *value;
8945             /* In GCC, normalized significands are in the range [0.5,
8946                1.0).  We want them to be [1.0, 2.0) so set the
8947                exponent to 1.  */
8948             SET_REAL_EXP (&result, 1);
8949             return build_real (rettype, result);
8950           }
8951         break;
8952       }
8953     }
8954
8955   return NULL_TREE;
8956 }
8957
8958 /* Fold a call to builtin frexp, we can assume the base is 2.  */
8959
8960 static tree
8961 fold_builtin_frexp (location_t loc, tree arg0, tree arg1, tree rettype)
8962 {
8963   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
8964     return NULL_TREE;
8965
8966   STRIP_NOPS (arg0);
8967
8968   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
8969     return NULL_TREE;
8970
8971   arg1 = build_fold_indirect_ref_loc (loc, arg1);
8972
8973   /* Proceed if a valid pointer type was passed in.  */
8974   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == integer_type_node)
8975     {
8976       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
8977       tree frac, exp;
8978
8979       switch (value->cl)
8980       {
8981       case rvc_zero:
8982         /* For +-0, return (*exp = 0, +-0).  */
8983         exp = integer_zero_node;
8984         frac = arg0;
8985         break;
8986       case rvc_nan:
8987       case rvc_inf:
8988         /* For +-NaN or +-Inf, *exp is unspecified, return arg0.  */
8989         return omit_one_operand_loc (loc, rettype, arg0, arg1);
8990       case rvc_normal:
8991         {
8992           /* Since the frexp function always expects base 2, and in
8993              GCC normalized significands are already in the range
8994              [0.5, 1.0), we have exactly what frexp wants.  */
8995           REAL_VALUE_TYPE frac_rvt = *value;
8996           SET_REAL_EXP (&frac_rvt, 0);
8997           frac = build_real (rettype, frac_rvt);
8998           exp = build_int_cst (integer_type_node, REAL_EXP (value));
8999         }
9000         break;
9001       default:
9002         gcc_unreachable ();
9003       }
9004
9005       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
9006       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1, exp);
9007       TREE_SIDE_EFFECTS (arg1) = 1;
9008       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1, frac);
9009     }
9010
9011   return NULL_TREE;
9012 }
9013
9014 /* Fold a call to builtin ldexp or scalbn/scalbln.  If LDEXP is true
9015    then we can assume the base is two.  If it's false, then we have to
9016    check the mode of the TYPE parameter in certain cases.  */
9017
9018 static tree
9019 fold_builtin_load_exponent (location_t loc, tree arg0, tree arg1,
9020                             tree type, bool ldexp)
9021 {
9022   if (validate_arg (arg0, REAL_TYPE) && validate_arg (arg1, INTEGER_TYPE))
9023     {
9024       STRIP_NOPS (arg0);
9025       STRIP_NOPS (arg1);
9026
9027       /* If arg0 is 0, Inf or NaN, or if arg1 is 0, then return arg0.  */
9028       if (real_zerop (arg0) || integer_zerop (arg1)
9029           || (TREE_CODE (arg0) == REAL_CST
9030               && !real_isfinite (&TREE_REAL_CST (arg0))))
9031         return omit_one_operand_loc (loc, type, arg0, arg1);
9032
9033       /* If both arguments are constant, then try to evaluate it.  */
9034       if ((ldexp || REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2)
9035           && TREE_CODE (arg0) == REAL_CST && !TREE_OVERFLOW (arg0)
9036           && host_integerp (arg1, 0))
9037         {
9038           /* Bound the maximum adjustment to twice the range of the
9039              mode's valid exponents.  Use abs to ensure the range is
9040              positive as a sanity check.  */
9041           const long max_exp_adj = 2 *
9042             labs (REAL_MODE_FORMAT (TYPE_MODE (type))->emax
9043                  - REAL_MODE_FORMAT (TYPE_MODE (type))->emin);
9044
9045           /* Get the user-requested adjustment.  */
9046           const HOST_WIDE_INT req_exp_adj = tree_low_cst (arg1, 0);
9047
9048           /* The requested adjustment must be inside this range.  This
9049              is a preliminary cap to avoid things like overflow, we
9050              may still fail to compute the result for other reasons.  */
9051           if (-max_exp_adj < req_exp_adj && req_exp_adj < max_exp_adj)
9052             {
9053               REAL_VALUE_TYPE initial_result;
9054
9055               real_ldexp (&initial_result, &TREE_REAL_CST (arg0), req_exp_adj);
9056
9057               /* Ensure we didn't overflow.  */
9058               if (! real_isinf (&initial_result))
9059                 {
9060                   const REAL_VALUE_TYPE trunc_result
9061                     = real_value_truncate (TYPE_MODE (type), initial_result);
9062
9063                   /* Only proceed if the target mode can hold the
9064                      resulting value.  */
9065                   if (REAL_VALUES_EQUAL (initial_result, trunc_result))
9066                     return build_real (type, trunc_result);
9067                 }
9068             }
9069         }
9070     }
9071
9072   return NULL_TREE;
9073 }
9074
9075 /* Fold a call to builtin modf.  */
9076
9077 static tree
9078 fold_builtin_modf (location_t loc, tree arg0, tree arg1, tree rettype)
9079 {
9080   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
9081     return NULL_TREE;
9082
9083   STRIP_NOPS (arg0);
9084
9085   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
9086     return NULL_TREE;
9087
9088   arg1 = build_fold_indirect_ref_loc (loc, arg1);
9089
9090   /* Proceed if a valid pointer type was passed in.  */
9091   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == TYPE_MAIN_VARIANT (rettype))
9092     {
9093       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
9094       REAL_VALUE_TYPE trunc, frac;
9095
9096       switch (value->cl)
9097       {
9098       case rvc_nan:
9099       case rvc_zero:
9100         /* For +-NaN or +-0, return (*arg1 = arg0, arg0).  */
9101         trunc = frac = *value;
9102         break;
9103       case rvc_inf:
9104         /* For +-Inf, return (*arg1 = arg0, +-0).  */
9105         frac = dconst0;
9106         frac.sign = value->sign;
9107         trunc = *value;
9108         break;
9109       case rvc_normal:
9110         /* Return (*arg1 = trunc(arg0), arg0-trunc(arg0)).  */
9111         real_trunc (&trunc, VOIDmode, value);
9112         real_arithmetic (&frac, MINUS_EXPR, value, &trunc);
9113         /* If the original number was negative and already
9114            integral, then the fractional part is -0.0.  */
9115         if (value->sign && frac.cl == rvc_zero)
9116           frac.sign = value->sign;
9117         break;
9118       }
9119
9120       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
9121       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1,
9122                           build_real (rettype, trunc));
9123       TREE_SIDE_EFFECTS (arg1) = 1;
9124       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1,
9125                           build_real (rettype, frac));
9126     }
9127
9128   return NULL_TREE;
9129 }
9130
9131 /* Given a location LOC, an interclass builtin function decl FNDECL
9132    and its single argument ARG, return an folded expression computing
9133    the same, or NULL_TREE if we either couldn't or didn't want to fold
9134    (the latter happen if there's an RTL instruction available).  */
9135
9136 static tree
9137 fold_builtin_interclass_mathfn (location_t loc, tree fndecl, tree arg)
9138 {
9139   enum machine_mode mode;
9140
9141   if (!validate_arg (arg, REAL_TYPE))
9142     return NULL_TREE;
9143
9144   if (interclass_mathfn_icode (arg, fndecl) != CODE_FOR_nothing)
9145     return NULL_TREE;
9146
9147   mode = TYPE_MODE (TREE_TYPE (arg));
9148
9149   /* If there is no optab, try generic code.  */
9150   switch (DECL_FUNCTION_CODE (fndecl))
9151     {
9152       tree result;
9153
9154     CASE_FLT_FN (BUILT_IN_ISINF):
9155       {
9156         /* isinf(x) -> isgreater(fabs(x),DBL_MAX).  */
9157         tree const isgr_fn = built_in_decls[BUILT_IN_ISGREATER];
9158         tree const type = TREE_TYPE (arg);
9159         REAL_VALUE_TYPE r;
9160         char buf[128];
9161
9162         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9163         real_from_string (&r, buf);
9164         result = build_call_expr (isgr_fn, 2,
9165                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9166                                   build_real (type, r));
9167         return result;
9168       }
9169     CASE_FLT_FN (BUILT_IN_FINITE):
9170     case BUILT_IN_ISFINITE:
9171       {
9172         /* isfinite(x) -> islessequal(fabs(x),DBL_MAX).  */
9173         tree const isle_fn = built_in_decls[BUILT_IN_ISLESSEQUAL];
9174         tree const type = TREE_TYPE (arg);
9175         REAL_VALUE_TYPE r;
9176         char buf[128];
9177
9178         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9179         real_from_string (&r, buf);
9180         result = build_call_expr (isle_fn, 2,
9181                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9182                                   build_real (type, r));
9183         /*result = fold_build2_loc (loc, UNGT_EXPR,
9184                                   TREE_TYPE (TREE_TYPE (fndecl)),
9185                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9186                                   build_real (type, r));
9187         result = fold_build1_loc (loc, TRUTH_NOT_EXPR,
9188                                   TREE_TYPE (TREE_TYPE (fndecl)),
9189                                   result);*/
9190         return result;
9191       }
9192     case BUILT_IN_ISNORMAL:
9193       {
9194         /* isnormal(x) -> isgreaterequal(fabs(x),DBL_MIN) &
9195            islessequal(fabs(x),DBL_MAX).  */
9196         tree const isle_fn = built_in_decls[BUILT_IN_ISLESSEQUAL];
9197         tree const isge_fn = built_in_decls[BUILT_IN_ISGREATEREQUAL];
9198         tree const type = TREE_TYPE (arg);
9199         REAL_VALUE_TYPE rmax, rmin;
9200         char buf[128];
9201
9202         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9203         real_from_string (&rmax, buf);
9204         sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (mode)->emin - 1);
9205         real_from_string (&rmin, buf);
9206         arg = builtin_save_expr (fold_build1_loc (loc, ABS_EXPR, type, arg));
9207         result = build_call_expr (isle_fn, 2, arg,
9208                                   build_real (type, rmax));
9209         result = fold_build2 (BIT_AND_EXPR, integer_type_node, result,
9210                               build_call_expr (isge_fn, 2, arg,
9211                                                build_real (type, rmin)));
9212         return result;
9213       }
9214     default:
9215       break;
9216     }
9217
9218   return NULL_TREE;
9219 }
9220
9221 /* Fold a call to __builtin_isnan(), __builtin_isinf, __builtin_finite.
9222    ARG is the argument for the call.  */
9223
9224 static tree
9225 fold_builtin_classify (location_t loc, tree fndecl, tree arg, int builtin_index)
9226 {
9227   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9228   REAL_VALUE_TYPE r;
9229
9230   if (!validate_arg (arg, REAL_TYPE))
9231     return NULL_TREE;
9232
9233   switch (builtin_index)
9234     {
9235     case BUILT_IN_ISINF:
9236       if (!HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
9237         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9238
9239       if (TREE_CODE (arg) == REAL_CST)
9240         {
9241           r = TREE_REAL_CST (arg);
9242           if (real_isinf (&r))
9243             return real_compare (GT_EXPR, &r, &dconst0)
9244                    ? integer_one_node : integer_minus_one_node;
9245           else
9246             return integer_zero_node;
9247         }
9248
9249       return NULL_TREE;
9250
9251     case BUILT_IN_ISINF_SIGN:
9252       {
9253         /* isinf_sign(x) -> isinf(x) ? (signbit(x) ? -1 : 1) : 0 */
9254         /* In a boolean context, GCC will fold the inner COND_EXPR to
9255            1.  So e.g. "if (isinf_sign(x))" would be folded to just
9256            "if (isinf(x) ? 1 : 0)" which becomes "if (isinf(x))". */
9257         tree signbit_fn = mathfn_built_in_1 (TREE_TYPE (arg), BUILT_IN_SIGNBIT, 0);
9258         tree isinf_fn = built_in_decls[BUILT_IN_ISINF];
9259         tree tmp = NULL_TREE;
9260
9261         arg = builtin_save_expr (arg);
9262
9263         if (signbit_fn && isinf_fn)
9264           {
9265             tree signbit_call = build_call_expr_loc (loc, signbit_fn, 1, arg);
9266             tree isinf_call = build_call_expr_loc (loc, isinf_fn, 1, arg);
9267
9268             signbit_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
9269                                         signbit_call, integer_zero_node);
9270             isinf_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
9271                                       isinf_call, integer_zero_node);
9272
9273             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node, signbit_call,
9274                                integer_minus_one_node, integer_one_node);
9275             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node,
9276                                isinf_call, tmp,
9277                                integer_zero_node);
9278           }
9279
9280         return tmp;
9281       }
9282
9283     case BUILT_IN_ISFINITE:
9284       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg)))
9285           && !HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
9286         return omit_one_operand_loc (loc, type, integer_one_node, arg);
9287
9288       if (TREE_CODE (arg) == REAL_CST)
9289         {
9290           r = TREE_REAL_CST (arg);
9291           return real_isfinite (&r) ? integer_one_node : integer_zero_node;
9292         }
9293
9294       return NULL_TREE;
9295
9296     case BUILT_IN_ISNAN:
9297       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg))))
9298         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9299
9300       if (TREE_CODE (arg) == REAL_CST)
9301         {
9302           r = TREE_REAL_CST (arg);
9303           return real_isnan (&r) ? integer_one_node : integer_zero_node;
9304         }
9305
9306       arg = builtin_save_expr (arg);
9307       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg, arg);
9308
9309     default:
9310       gcc_unreachable ();
9311     }
9312 }
9313
9314 /* Fold a call to __builtin_fpclassify(int, int, int, int, int, ...).
9315    This builtin will generate code to return the appropriate floating
9316    point classification depending on the value of the floating point
9317    number passed in.  The possible return values must be supplied as
9318    int arguments to the call in the following order: FP_NAN, FP_INFINITE,
9319    FP_NORMAL, FP_SUBNORMAL and FP_ZERO.  The ellipses is for exactly
9320    one floating point argument which is "type generic".  */
9321
9322 static tree
9323 fold_builtin_fpclassify (location_t loc, tree exp)
9324 {
9325   tree fp_nan, fp_infinite, fp_normal, fp_subnormal, fp_zero,
9326     arg, type, res, tmp;
9327   enum machine_mode mode;
9328   REAL_VALUE_TYPE r;
9329   char buf[128];
9330
9331   /* Verify the required arguments in the original call.  */
9332   if (!validate_arglist (exp, INTEGER_TYPE, INTEGER_TYPE,
9333                          INTEGER_TYPE, INTEGER_TYPE,
9334                          INTEGER_TYPE, REAL_TYPE, VOID_TYPE))
9335     return NULL_TREE;
9336
9337   fp_nan = CALL_EXPR_ARG (exp, 0);
9338   fp_infinite = CALL_EXPR_ARG (exp, 1);
9339   fp_normal = CALL_EXPR_ARG (exp, 2);
9340   fp_subnormal = CALL_EXPR_ARG (exp, 3);
9341   fp_zero = CALL_EXPR_ARG (exp, 4);
9342   arg = CALL_EXPR_ARG (exp, 5);
9343   type = TREE_TYPE (arg);
9344   mode = TYPE_MODE (type);
9345   arg = builtin_save_expr (fold_build1_loc (loc, ABS_EXPR, type, arg));
9346
9347   /* fpclassify(x) ->
9348        isnan(x) ? FP_NAN :
9349          (fabs(x) == Inf ? FP_INFINITE :
9350            (fabs(x) >= DBL_MIN ? FP_NORMAL :
9351              (x == 0 ? FP_ZERO : FP_SUBNORMAL))).  */
9352
9353   tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
9354                      build_real (type, dconst0));
9355   res = fold_build3_loc (loc, COND_EXPR, integer_type_node,
9356                      tmp, fp_zero, fp_subnormal);
9357
9358   sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (mode)->emin - 1);
9359   real_from_string (&r, buf);
9360   tmp = fold_build2_loc (loc, GE_EXPR, integer_type_node,
9361                      arg, build_real (type, r));
9362   res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, fp_normal, res);
9363
9364   if (HONOR_INFINITIES (mode))
9365     {
9366       real_inf (&r);
9367       tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
9368                          build_real (type, r));
9369       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp,
9370                          fp_infinite, res);
9371     }
9372
9373   if (HONOR_NANS (mode))
9374     {
9375       tmp = fold_build2_loc (loc, ORDERED_EXPR, integer_type_node, arg, arg);
9376       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, res, fp_nan);
9377     }
9378
9379   return res;
9380 }
9381
9382 /* Fold a call to an unordered comparison function such as
9383    __builtin_isgreater().  FNDECL is the FUNCTION_DECL for the function
9384    being called and ARG0 and ARG1 are the arguments for the call.
9385    UNORDERED_CODE and ORDERED_CODE are comparison codes that give
9386    the opposite of the desired result.  UNORDERED_CODE is used
9387    for modes that can hold NaNs and ORDERED_CODE is used for
9388    the rest.  */
9389
9390 static tree
9391 fold_builtin_unordered_cmp (location_t loc, tree fndecl, tree arg0, tree arg1,
9392                             enum tree_code unordered_code,
9393                             enum tree_code ordered_code)
9394 {
9395   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9396   enum tree_code code;
9397   tree type0, type1;
9398   enum tree_code code0, code1;
9399   tree cmp_type = NULL_TREE;
9400
9401   type0 = TREE_TYPE (arg0);
9402   type1 = TREE_TYPE (arg1);
9403
9404   code0 = TREE_CODE (type0);
9405   code1 = TREE_CODE (type1);
9406
9407   if (code0 == REAL_TYPE && code1 == REAL_TYPE)
9408     /* Choose the wider of two real types.  */
9409     cmp_type = TYPE_PRECISION (type0) >= TYPE_PRECISION (type1)
9410       ? type0 : type1;
9411   else if (code0 == REAL_TYPE && code1 == INTEGER_TYPE)
9412     cmp_type = type0;
9413   else if (code0 == INTEGER_TYPE && code1 == REAL_TYPE)
9414     cmp_type = type1;
9415
9416   arg0 = fold_convert_loc (loc, cmp_type, arg0);
9417   arg1 = fold_convert_loc (loc, cmp_type, arg1);
9418
9419   if (unordered_code == UNORDERED_EXPR)
9420     {
9421       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))))
9422         return omit_two_operands_loc (loc, type, integer_zero_node, arg0, arg1);
9423       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg0, arg1);
9424     }
9425
9426   code = HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))) ? unordered_code
9427                                                    : ordered_code;
9428   return fold_build1_loc (loc, TRUTH_NOT_EXPR, type,
9429                       fold_build2_loc (loc, code, type, arg0, arg1));
9430 }
9431
9432 /* Fold a call to built-in function FNDECL with 0 arguments.
9433    IGNORE is true if the result of the function call is ignored.  This
9434    function returns NULL_TREE if no simplification was possible.  */
9435
9436 static tree
9437 fold_builtin_0 (location_t loc, tree fndecl, bool ignore ATTRIBUTE_UNUSED)
9438 {
9439   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9440   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
9441   switch (fcode)
9442     {
9443     CASE_FLT_FN (BUILT_IN_INF):
9444     case BUILT_IN_INFD32:
9445     case BUILT_IN_INFD64:
9446     case BUILT_IN_INFD128:
9447       return fold_builtin_inf (loc, type, true);
9448
9449     CASE_FLT_FN (BUILT_IN_HUGE_VAL):
9450       return fold_builtin_inf (loc, type, false);
9451
9452     case BUILT_IN_CLASSIFY_TYPE:
9453       return fold_builtin_classify_type (NULL_TREE);
9454
9455     default:
9456       break;
9457     }
9458   return NULL_TREE;
9459 }
9460
9461 /* Fold a call to built-in function FNDECL with 1 argument, ARG0.
9462    IGNORE is true if the result of the function call is ignored.  This
9463    function returns NULL_TREE if no simplification was possible.  */
9464
9465 static tree
9466 fold_builtin_1 (location_t loc, tree fndecl, tree arg0, bool ignore)
9467 {
9468   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9469   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
9470   switch (fcode)
9471     {
9472     case BUILT_IN_CONSTANT_P:
9473       {
9474         tree val = fold_builtin_constant_p (arg0);
9475
9476         /* Gimplification will pull the CALL_EXPR for the builtin out of
9477            an if condition.  When not optimizing, we'll not CSE it back.
9478            To avoid link error types of regressions, return false now.  */
9479         if (!val && !optimize)
9480           val = integer_zero_node;
9481
9482         return val;
9483       }
9484
9485     case BUILT_IN_CLASSIFY_TYPE:
9486       return fold_builtin_classify_type (arg0);
9487
9488     case BUILT_IN_STRLEN:
9489       return fold_builtin_strlen (loc, type, arg0);
9490
9491     CASE_FLT_FN (BUILT_IN_FABS):
9492       return fold_builtin_fabs (loc, arg0, type);
9493
9494     case BUILT_IN_ABS:
9495     case BUILT_IN_LABS:
9496     case BUILT_IN_LLABS:
9497     case BUILT_IN_IMAXABS:
9498       return fold_builtin_abs (loc, arg0, type);
9499
9500     CASE_FLT_FN (BUILT_IN_CONJ):
9501       if (validate_arg (arg0, COMPLEX_TYPE)
9502         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9503         return fold_build1_loc (loc, CONJ_EXPR, type, arg0);
9504     break;
9505
9506     CASE_FLT_FN (BUILT_IN_CREAL):
9507       if (validate_arg (arg0, COMPLEX_TYPE)
9508         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9509         return non_lvalue_loc (loc, fold_build1_loc (loc, REALPART_EXPR, type, arg0));;
9510     break;
9511
9512     CASE_FLT_FN (BUILT_IN_CIMAG):
9513       if (validate_arg (arg0, COMPLEX_TYPE)
9514           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9515         return non_lvalue_loc (loc, fold_build1_loc (loc, IMAGPART_EXPR, type, arg0));
9516     break;
9517
9518     CASE_FLT_FN (BUILT_IN_CCOS):
9519       return fold_builtin_ccos(loc, arg0, type, fndecl, /*hyper=*/ false);
9520
9521     CASE_FLT_FN (BUILT_IN_CCOSH):
9522       return fold_builtin_ccos(loc, arg0, type, fndecl, /*hyper=*/ true);
9523
9524     CASE_FLT_FN (BUILT_IN_CPROJ):
9525       return fold_builtin_cproj(loc, arg0, type);
9526
9527     CASE_FLT_FN (BUILT_IN_CSIN):
9528       if (validate_arg (arg0, COMPLEX_TYPE)
9529           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9530         return do_mpc_arg1 (arg0, type, mpc_sin);
9531     break;
9532
9533     CASE_FLT_FN (BUILT_IN_CSINH):
9534       if (validate_arg (arg0, COMPLEX_TYPE)
9535           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9536         return do_mpc_arg1 (arg0, type, mpc_sinh);
9537     break;
9538
9539     CASE_FLT_FN (BUILT_IN_CTAN):
9540       if (validate_arg (arg0, COMPLEX_TYPE)
9541           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9542         return do_mpc_arg1 (arg0, type, mpc_tan);
9543     break;
9544
9545     CASE_FLT_FN (BUILT_IN_CTANH):
9546       if (validate_arg (arg0, COMPLEX_TYPE)
9547           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9548         return do_mpc_arg1 (arg0, type, mpc_tanh);
9549     break;
9550
9551     CASE_FLT_FN (BUILT_IN_CLOG):
9552       if (validate_arg (arg0, COMPLEX_TYPE)
9553           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9554         return do_mpc_arg1 (arg0, type, mpc_log);
9555     break;
9556
9557     CASE_FLT_FN (BUILT_IN_CSQRT):
9558       if (validate_arg (arg0, COMPLEX_TYPE)
9559           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9560         return do_mpc_arg1 (arg0, type, mpc_sqrt);
9561     break;
9562
9563     CASE_FLT_FN (BUILT_IN_CASIN):
9564       if (validate_arg (arg0, COMPLEX_TYPE)
9565           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9566         return do_mpc_arg1 (arg0, type, mpc_asin);
9567     break;
9568
9569     CASE_FLT_FN (BUILT_IN_CACOS):
9570       if (validate_arg (arg0, COMPLEX_TYPE)
9571           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9572         return do_mpc_arg1 (arg0, type, mpc_acos);
9573     break;
9574
9575     CASE_FLT_FN (BUILT_IN_CATAN):
9576       if (validate_arg (arg0, COMPLEX_TYPE)
9577           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9578         return do_mpc_arg1 (arg0, type, mpc_atan);
9579     break;
9580
9581     CASE_FLT_FN (BUILT_IN_CASINH):
9582       if (validate_arg (arg0, COMPLEX_TYPE)
9583           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9584         return do_mpc_arg1 (arg0, type, mpc_asinh);
9585     break;
9586
9587     CASE_FLT_FN (BUILT_IN_CACOSH):
9588       if (validate_arg (arg0, COMPLEX_TYPE)
9589           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9590         return do_mpc_arg1 (arg0, type, mpc_acosh);
9591     break;
9592
9593     CASE_FLT_FN (BUILT_IN_CATANH):
9594       if (validate_arg (arg0, COMPLEX_TYPE)
9595           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9596         return do_mpc_arg1 (arg0, type, mpc_atanh);
9597     break;
9598
9599     CASE_FLT_FN (BUILT_IN_CABS):
9600       return fold_builtin_cabs (loc, arg0, type, fndecl);
9601
9602     CASE_FLT_FN (BUILT_IN_CARG):
9603       return fold_builtin_carg (loc, arg0, type);
9604
9605     CASE_FLT_FN (BUILT_IN_SQRT):
9606       return fold_builtin_sqrt (loc, arg0, type);
9607
9608     CASE_FLT_FN (BUILT_IN_CBRT):
9609       return fold_builtin_cbrt (loc, arg0, type);
9610
9611     CASE_FLT_FN (BUILT_IN_ASIN):
9612       if (validate_arg (arg0, REAL_TYPE))
9613         return do_mpfr_arg1 (arg0, type, mpfr_asin,
9614                              &dconstm1, &dconst1, true);
9615     break;
9616
9617     CASE_FLT_FN (BUILT_IN_ACOS):
9618       if (validate_arg (arg0, REAL_TYPE))
9619         return do_mpfr_arg1 (arg0, type, mpfr_acos,
9620                              &dconstm1, &dconst1, true);
9621     break;
9622
9623     CASE_FLT_FN (BUILT_IN_ATAN):
9624       if (validate_arg (arg0, REAL_TYPE))
9625         return do_mpfr_arg1 (arg0, type, mpfr_atan, NULL, NULL, 0);
9626     break;
9627
9628     CASE_FLT_FN (BUILT_IN_ASINH):
9629       if (validate_arg (arg0, REAL_TYPE))
9630         return do_mpfr_arg1 (arg0, type, mpfr_asinh, NULL, NULL, 0);
9631     break;
9632
9633     CASE_FLT_FN (BUILT_IN_ACOSH):
9634       if (validate_arg (arg0, REAL_TYPE))
9635         return do_mpfr_arg1 (arg0, type, mpfr_acosh,
9636                              &dconst1, NULL, true);
9637     break;
9638
9639     CASE_FLT_FN (BUILT_IN_ATANH):
9640       if (validate_arg (arg0, REAL_TYPE))
9641         return do_mpfr_arg1 (arg0, type, mpfr_atanh,
9642                              &dconstm1, &dconst1, false);
9643     break;
9644
9645     CASE_FLT_FN (BUILT_IN_SIN):
9646       if (validate_arg (arg0, REAL_TYPE))
9647         return do_mpfr_arg1 (arg0, type, mpfr_sin, NULL, NULL, 0);
9648     break;
9649
9650     CASE_FLT_FN (BUILT_IN_COS):
9651       return fold_builtin_cos (loc, arg0, type, fndecl);
9652
9653     CASE_FLT_FN (BUILT_IN_TAN):
9654       return fold_builtin_tan (arg0, type);
9655
9656     CASE_FLT_FN (BUILT_IN_CEXP):
9657       return fold_builtin_cexp (loc, arg0, type);
9658
9659     CASE_FLT_FN (BUILT_IN_CEXPI):
9660       if (validate_arg (arg0, REAL_TYPE))
9661         return do_mpfr_sincos (arg0, NULL_TREE, NULL_TREE);
9662     break;
9663
9664     CASE_FLT_FN (BUILT_IN_SINH):
9665       if (validate_arg (arg0, REAL_TYPE))
9666         return do_mpfr_arg1 (arg0, type, mpfr_sinh, NULL, NULL, 0);
9667     break;
9668
9669     CASE_FLT_FN (BUILT_IN_COSH):
9670       return fold_builtin_cosh (loc, arg0, type, fndecl);
9671
9672     CASE_FLT_FN (BUILT_IN_TANH):
9673       if (validate_arg (arg0, REAL_TYPE))
9674         return do_mpfr_arg1 (arg0, type, mpfr_tanh, NULL, NULL, 0);
9675     break;
9676
9677     CASE_FLT_FN (BUILT_IN_ERF):
9678       if (validate_arg (arg0, REAL_TYPE))
9679         return do_mpfr_arg1 (arg0, type, mpfr_erf, NULL, NULL, 0);
9680     break;
9681
9682     CASE_FLT_FN (BUILT_IN_ERFC):
9683       if (validate_arg (arg0, REAL_TYPE))
9684         return do_mpfr_arg1 (arg0, type, mpfr_erfc, NULL, NULL, 0);
9685     break;
9686
9687     CASE_FLT_FN (BUILT_IN_TGAMMA):
9688       if (validate_arg (arg0, REAL_TYPE))
9689         return do_mpfr_arg1 (arg0, type, mpfr_gamma, NULL, NULL, 0);
9690     break;
9691
9692     CASE_FLT_FN (BUILT_IN_EXP):
9693       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp);
9694
9695     CASE_FLT_FN (BUILT_IN_EXP2):
9696       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp2);
9697
9698     CASE_FLT_FN (BUILT_IN_EXP10):
9699     CASE_FLT_FN (BUILT_IN_POW10):
9700       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp10);
9701
9702     CASE_FLT_FN (BUILT_IN_EXPM1):
9703       if (validate_arg (arg0, REAL_TYPE))
9704         return do_mpfr_arg1 (arg0, type, mpfr_expm1, NULL, NULL, 0);
9705     break;
9706
9707     CASE_FLT_FN (BUILT_IN_LOG):
9708     return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log);
9709
9710     CASE_FLT_FN (BUILT_IN_LOG2):
9711       return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log2);
9712
9713     CASE_FLT_FN (BUILT_IN_LOG10):
9714       return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log10);
9715
9716     CASE_FLT_FN (BUILT_IN_LOG1P):
9717       if (validate_arg (arg0, REAL_TYPE))
9718         return do_mpfr_arg1 (arg0, type, mpfr_log1p,
9719                              &dconstm1, NULL, false);
9720     break;
9721
9722     CASE_FLT_FN (BUILT_IN_J0):
9723       if (validate_arg (arg0, REAL_TYPE))
9724         return do_mpfr_arg1 (arg0, type, mpfr_j0,
9725                              NULL, NULL, 0);
9726     break;
9727
9728     CASE_FLT_FN (BUILT_IN_J1):
9729       if (validate_arg (arg0, REAL_TYPE))
9730         return do_mpfr_arg1 (arg0, type, mpfr_j1,
9731                              NULL, NULL, 0);
9732     break;
9733
9734     CASE_FLT_FN (BUILT_IN_Y0):
9735       if (validate_arg (arg0, REAL_TYPE))
9736         return do_mpfr_arg1 (arg0, type, mpfr_y0,
9737                              &dconst0, NULL, false);
9738     break;
9739
9740     CASE_FLT_FN (BUILT_IN_Y1):
9741       if (validate_arg (arg0, REAL_TYPE))
9742         return do_mpfr_arg1 (arg0, type, mpfr_y1,
9743                              &dconst0, NULL, false);
9744     break;
9745
9746     CASE_FLT_FN (BUILT_IN_NAN):
9747     case BUILT_IN_NAND32:
9748     case BUILT_IN_NAND64:
9749     case BUILT_IN_NAND128:
9750       return fold_builtin_nan (arg0, type, true);
9751
9752     CASE_FLT_FN (BUILT_IN_NANS):
9753       return fold_builtin_nan (arg0, type, false);
9754
9755     CASE_FLT_FN (BUILT_IN_FLOOR):
9756       return fold_builtin_floor (loc, fndecl, arg0);
9757
9758     CASE_FLT_FN (BUILT_IN_CEIL):
9759       return fold_builtin_ceil (loc, fndecl, arg0);
9760
9761     CASE_FLT_FN (BUILT_IN_TRUNC):
9762       return fold_builtin_trunc (loc, fndecl, arg0);
9763
9764     CASE_FLT_FN (BUILT_IN_ROUND):
9765       return fold_builtin_round (loc, fndecl, arg0);
9766
9767     CASE_FLT_FN (BUILT_IN_NEARBYINT):
9768     CASE_FLT_FN (BUILT_IN_RINT):
9769       return fold_trunc_transparent_mathfn (loc, fndecl, arg0);
9770
9771     CASE_FLT_FN (BUILT_IN_LCEIL):
9772     CASE_FLT_FN (BUILT_IN_LLCEIL):
9773     CASE_FLT_FN (BUILT_IN_LFLOOR):
9774     CASE_FLT_FN (BUILT_IN_LLFLOOR):
9775     CASE_FLT_FN (BUILT_IN_LROUND):
9776     CASE_FLT_FN (BUILT_IN_LLROUND):
9777       return fold_builtin_int_roundingfn (loc, fndecl, arg0);
9778
9779     CASE_FLT_FN (BUILT_IN_LRINT):
9780     CASE_FLT_FN (BUILT_IN_LLRINT):
9781       return fold_fixed_mathfn (loc, fndecl, arg0);
9782
9783     case BUILT_IN_BSWAP32:
9784     case BUILT_IN_BSWAP64:
9785       return fold_builtin_bswap (fndecl, arg0);
9786
9787     CASE_INT_FN (BUILT_IN_FFS):
9788     CASE_INT_FN (BUILT_IN_CLZ):
9789     CASE_INT_FN (BUILT_IN_CTZ):
9790     CASE_INT_FN (BUILT_IN_CLRSB):
9791     CASE_INT_FN (BUILT_IN_POPCOUNT):
9792     CASE_INT_FN (BUILT_IN_PARITY):
9793       return fold_builtin_bitop (fndecl, arg0);
9794
9795     CASE_FLT_FN (BUILT_IN_SIGNBIT):
9796       return fold_builtin_signbit (loc, arg0, type);
9797
9798     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
9799       return fold_builtin_significand (loc, arg0, type);
9800
9801     CASE_FLT_FN (BUILT_IN_ILOGB):
9802     CASE_FLT_FN (BUILT_IN_LOGB):
9803       return fold_builtin_logb (loc, arg0, type);
9804
9805     case BUILT_IN_ISASCII:
9806       return fold_builtin_isascii (loc, arg0);
9807
9808     case BUILT_IN_TOASCII:
9809       return fold_builtin_toascii (loc, arg0);
9810
9811     case BUILT_IN_ISDIGIT:
9812       return fold_builtin_isdigit (loc, arg0);
9813
9814     CASE_FLT_FN (BUILT_IN_FINITE):
9815     case BUILT_IN_FINITED32:
9816     case BUILT_IN_FINITED64:
9817     case BUILT_IN_FINITED128:
9818     case BUILT_IN_ISFINITE:
9819       {
9820         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISFINITE);
9821         if (ret)
9822           return ret;
9823         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
9824       }
9825
9826     CASE_FLT_FN (BUILT_IN_ISINF):
9827     case BUILT_IN_ISINFD32:
9828     case BUILT_IN_ISINFD64:
9829     case BUILT_IN_ISINFD128:
9830       {
9831         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF);
9832         if (ret)
9833           return ret;
9834         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
9835       }
9836
9837     case BUILT_IN_ISNORMAL:
9838       return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
9839
9840     case BUILT_IN_ISINF_SIGN:
9841       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF_SIGN);
9842
9843     CASE_FLT_FN (BUILT_IN_ISNAN):
9844     case BUILT_IN_ISNAND32:
9845     case BUILT_IN_ISNAND64:
9846     case BUILT_IN_ISNAND128:
9847       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISNAN);
9848
9849     case BUILT_IN_PRINTF:
9850     case BUILT_IN_PRINTF_UNLOCKED:
9851     case BUILT_IN_VPRINTF:
9852       return fold_builtin_printf (loc, fndecl, arg0, NULL_TREE, ignore, fcode);
9853
9854     case BUILT_IN_FREE:
9855       if (integer_zerop (arg0))
9856         return build_empty_stmt (loc);
9857       break;
9858
9859     default:
9860       break;
9861     }
9862
9863   return NULL_TREE;
9864
9865 }
9866
9867 /* Fold a call to built-in function FNDECL with 2 arguments, ARG0 and ARG1.
9868    IGNORE is true if the result of the function call is ignored.  This
9869    function returns NULL_TREE if no simplification was possible.  */
9870
9871 static tree
9872 fold_builtin_2 (location_t loc, tree fndecl, tree arg0, tree arg1, bool ignore)
9873 {
9874   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9875   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
9876
9877   switch (fcode)
9878     {
9879     CASE_FLT_FN (BUILT_IN_JN):
9880       if (validate_arg (arg0, INTEGER_TYPE)
9881           && validate_arg (arg1, REAL_TYPE))
9882         return do_mpfr_bessel_n (arg0, arg1, type, mpfr_jn, NULL, 0);
9883     break;
9884
9885     CASE_FLT_FN (BUILT_IN_YN):
9886       if (validate_arg (arg0, INTEGER_TYPE)
9887           && validate_arg (arg1, REAL_TYPE))
9888         return do_mpfr_bessel_n (arg0, arg1, type, mpfr_yn,
9889                                  &dconst0, false);
9890     break;
9891
9892     CASE_FLT_FN (BUILT_IN_DREM):
9893     CASE_FLT_FN (BUILT_IN_REMAINDER):
9894       if (validate_arg (arg0, REAL_TYPE)
9895           && validate_arg(arg1, REAL_TYPE))
9896         return do_mpfr_arg2 (arg0, arg1, type, mpfr_remainder);
9897     break;
9898
9899     CASE_FLT_FN_REENT (BUILT_IN_GAMMA): /* GAMMA_R */
9900     CASE_FLT_FN_REENT (BUILT_IN_LGAMMA): /* LGAMMA_R */
9901       if (validate_arg (arg0, REAL_TYPE)
9902           && validate_arg(arg1, POINTER_TYPE))
9903         return do_mpfr_lgamma_r (arg0, arg1, type);
9904     break;
9905
9906     CASE_FLT_FN (BUILT_IN_ATAN2):
9907       if (validate_arg (arg0, REAL_TYPE)
9908           && validate_arg(arg1, REAL_TYPE))
9909         return do_mpfr_arg2 (arg0, arg1, type, mpfr_atan2);
9910     break;
9911
9912     CASE_FLT_FN (BUILT_IN_FDIM):
9913       if (validate_arg (arg0, REAL_TYPE)
9914           && validate_arg(arg1, REAL_TYPE))
9915         return do_mpfr_arg2 (arg0, arg1, type, mpfr_dim);
9916     break;
9917
9918     CASE_FLT_FN (BUILT_IN_HYPOT):
9919       return fold_builtin_hypot (loc, fndecl, arg0, arg1, type);
9920
9921     CASE_FLT_FN (BUILT_IN_CPOW):
9922       if (validate_arg (arg0, COMPLEX_TYPE)
9923           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE
9924           && validate_arg (arg1, COMPLEX_TYPE)
9925           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg1))) == REAL_TYPE)
9926         return do_mpc_arg2 (arg0, arg1, type, /*do_nonfinite=*/ 0, mpc_pow);
9927     break;
9928
9929     CASE_FLT_FN (BUILT_IN_LDEXP):
9930       return fold_builtin_load_exponent (loc, arg0, arg1, type, /*ldexp=*/true);
9931     CASE_FLT_FN (BUILT_IN_SCALBN):
9932     CASE_FLT_FN (BUILT_IN_SCALBLN):
9933       return fold_builtin_load_exponent (loc, arg0, arg1,
9934                                          type, /*ldexp=*/false);
9935
9936     CASE_FLT_FN (BUILT_IN_FREXP):
9937       return fold_builtin_frexp (loc, arg0, arg1, type);
9938
9939     CASE_FLT_FN (BUILT_IN_MODF):
9940       return fold_builtin_modf (loc, arg0, arg1, type);
9941
9942     case BUILT_IN_BZERO:
9943       return fold_builtin_bzero (loc, arg0, arg1, ignore);
9944
9945     case BUILT_IN_FPUTS:
9946       return fold_builtin_fputs (loc, arg0, arg1, ignore, false, NULL_TREE);
9947
9948     case BUILT_IN_FPUTS_UNLOCKED:
9949       return fold_builtin_fputs (loc, arg0, arg1, ignore, true, NULL_TREE);
9950
9951     case BUILT_IN_STRSTR:
9952       return fold_builtin_strstr (loc, arg0, arg1, type);
9953
9954     case BUILT_IN_STRCAT:
9955       return fold_builtin_strcat (loc, arg0, arg1);
9956
9957     case BUILT_IN_STRSPN:
9958       return fold_builtin_strspn (loc, arg0, arg1);
9959
9960     case BUILT_IN_STRCSPN:
9961       return fold_builtin_strcspn (loc, arg0, arg1);
9962
9963     case BUILT_IN_STRCHR:
9964     case BUILT_IN_INDEX:
9965       return fold_builtin_strchr (loc, arg0, arg1, type);
9966
9967     case BUILT_IN_STRRCHR:
9968     case BUILT_IN_RINDEX:
9969       return fold_builtin_strrchr (loc, arg0, arg1, type);
9970
9971     case BUILT_IN_STRCPY:
9972       return fold_builtin_strcpy (loc, fndecl, arg0, arg1, NULL_TREE);
9973
9974     case BUILT_IN_STPCPY:
9975       if (ignore)
9976         {
9977           tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
9978           if (!fn)
9979             break;
9980
9981           return build_call_expr_loc (loc, fn, 2, arg0, arg1);
9982         }
9983       else
9984         return fold_builtin_stpcpy (loc, fndecl, arg0, arg1);
9985       break;
9986
9987     case BUILT_IN_STRCMP:
9988       return fold_builtin_strcmp (loc, arg0, arg1);
9989
9990     case BUILT_IN_STRPBRK:
9991       return fold_builtin_strpbrk (loc, arg0, arg1, type);
9992
9993     case BUILT_IN_EXPECT:
9994       return fold_builtin_expect (loc, arg0, arg1);
9995
9996     CASE_FLT_FN (BUILT_IN_POW):
9997       return fold_builtin_pow (loc, fndecl, arg0, arg1, type);
9998
9999     CASE_FLT_FN (BUILT_IN_POWI):
10000       return fold_builtin_powi (loc, fndecl, arg0, arg1, type);
10001
10002     CASE_FLT_FN (BUILT_IN_COPYSIGN):
10003       return fold_builtin_copysign (loc, fndecl, arg0, arg1, type);
10004
10005     CASE_FLT_FN (BUILT_IN_FMIN):
10006       return fold_builtin_fmin_fmax (loc, arg0, arg1, type, /*max=*/false);
10007
10008     CASE_FLT_FN (BUILT_IN_FMAX):
10009       return fold_builtin_fmin_fmax (loc, arg0, arg1, type, /*max=*/true);
10010
10011     case BUILT_IN_ISGREATER:
10012       return fold_builtin_unordered_cmp (loc, fndecl,
10013                                          arg0, arg1, UNLE_EXPR, LE_EXPR);
10014     case BUILT_IN_ISGREATEREQUAL:
10015       return fold_builtin_unordered_cmp (loc, fndecl,
10016                                          arg0, arg1, UNLT_EXPR, LT_EXPR);
10017     case BUILT_IN_ISLESS:
10018       return fold_builtin_unordered_cmp (loc, fndecl,
10019                                          arg0, arg1, UNGE_EXPR, GE_EXPR);
10020     case BUILT_IN_ISLESSEQUAL:
10021       return fold_builtin_unordered_cmp (loc, fndecl,
10022                                          arg0, arg1, UNGT_EXPR, GT_EXPR);
10023     case BUILT_IN_ISLESSGREATER:
10024       return fold_builtin_unordered_cmp (loc, fndecl,
10025                                          arg0, arg1, UNEQ_EXPR, EQ_EXPR);
10026     case BUILT_IN_ISUNORDERED:
10027       return fold_builtin_unordered_cmp (loc, fndecl,
10028                                          arg0, arg1, UNORDERED_EXPR,
10029                                          NOP_EXPR);
10030
10031       /* We do the folding for va_start in the expander.  */
10032     case BUILT_IN_VA_START:
10033       break;
10034
10035     case BUILT_IN_SPRINTF:
10036       return fold_builtin_sprintf (loc, arg0, arg1, NULL_TREE, ignore);
10037
10038     case BUILT_IN_OBJECT_SIZE:
10039       return fold_builtin_object_size (arg0, arg1);
10040
10041     case BUILT_IN_PRINTF:
10042     case BUILT_IN_PRINTF_UNLOCKED:
10043     case BUILT_IN_VPRINTF:
10044       return fold_builtin_printf (loc, fndecl, arg0, arg1, ignore, fcode);
10045
10046     case BUILT_IN_PRINTF_CHK:
10047     case BUILT_IN_VPRINTF_CHK:
10048       if (!validate_arg (arg0, INTEGER_TYPE)
10049           || TREE_SIDE_EFFECTS (arg0))
10050         return NULL_TREE;
10051       else
10052         return fold_builtin_printf (loc, fndecl,
10053                                     arg1, NULL_TREE, ignore, fcode);
10054     break;
10055
10056     case BUILT_IN_FPRINTF:
10057     case BUILT_IN_FPRINTF_UNLOCKED:
10058     case BUILT_IN_VFPRINTF:
10059       return fold_builtin_fprintf (loc, fndecl, arg0, arg1, NULL_TREE,
10060                                    ignore, fcode);
10061
10062     default:
10063       break;
10064     }
10065   return NULL_TREE;
10066 }
10067
10068 /* Fold a call to built-in function FNDECL with 3 arguments, ARG0, ARG1,
10069    and ARG2.  IGNORE is true if the result of the function call is ignored.
10070    This function returns NULL_TREE if no simplification was possible.  */
10071
10072 static tree
10073 fold_builtin_3 (location_t loc, tree fndecl,
10074                 tree arg0, tree arg1, tree arg2, bool ignore)
10075 {
10076   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10077   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10078   switch (fcode)
10079     {
10080
10081     CASE_FLT_FN (BUILT_IN_SINCOS):
10082       return fold_builtin_sincos (loc, arg0, arg1, arg2);
10083
10084     CASE_FLT_FN (BUILT_IN_FMA):
10085       return fold_builtin_fma (loc, arg0, arg1, arg2, type);
10086     break;
10087
10088     CASE_FLT_FN (BUILT_IN_REMQUO):
10089       if (validate_arg (arg0, REAL_TYPE)
10090           && validate_arg(arg1, REAL_TYPE)
10091           && validate_arg(arg2, POINTER_TYPE))
10092         return do_mpfr_remquo (arg0, arg1, arg2);
10093     break;
10094
10095     case BUILT_IN_MEMSET:
10096       return fold_builtin_memset (loc, arg0, arg1, arg2, type, ignore);
10097
10098     case BUILT_IN_BCOPY:
10099       return fold_builtin_memory_op (loc, arg1, arg0, arg2,
10100                                      void_type_node, true, /*endp=*/3);
10101
10102     case BUILT_IN_MEMCPY:
10103       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10104                                      type, ignore, /*endp=*/0);
10105
10106     case BUILT_IN_MEMPCPY:
10107       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10108                                      type, ignore, /*endp=*/1);
10109
10110     case BUILT_IN_MEMMOVE:
10111       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10112                                      type, ignore, /*endp=*/3);
10113
10114     case BUILT_IN_STRNCAT:
10115       return fold_builtin_strncat (loc, arg0, arg1, arg2);
10116
10117     case BUILT_IN_STRNCPY:
10118       return fold_builtin_strncpy (loc, fndecl, arg0, arg1, arg2, NULL_TREE);
10119
10120     case BUILT_IN_STRNCMP:
10121       return fold_builtin_strncmp (loc, arg0, arg1, arg2);
10122
10123     case BUILT_IN_MEMCHR:
10124       return fold_builtin_memchr (loc, arg0, arg1, arg2, type);
10125
10126     case BUILT_IN_BCMP:
10127     case BUILT_IN_MEMCMP:
10128       return fold_builtin_memcmp (loc, arg0, arg1, arg2);;
10129
10130     case BUILT_IN_SPRINTF:
10131       return fold_builtin_sprintf (loc, arg0, arg1, arg2, ignore);
10132
10133     case BUILT_IN_SNPRINTF:
10134       return fold_builtin_snprintf (loc, arg0, arg1, arg2, NULL_TREE, ignore);
10135
10136     case BUILT_IN_STRCPY_CHK:
10137     case BUILT_IN_STPCPY_CHK:
10138       return fold_builtin_stxcpy_chk (loc, fndecl, arg0, arg1, arg2, NULL_TREE,
10139                                       ignore, fcode);
10140
10141     case BUILT_IN_STRCAT_CHK:
10142       return fold_builtin_strcat_chk (loc, fndecl, arg0, arg1, arg2);
10143
10144     case BUILT_IN_PRINTF_CHK:
10145     case BUILT_IN_VPRINTF_CHK:
10146       if (!validate_arg (arg0, INTEGER_TYPE)
10147           || TREE_SIDE_EFFECTS (arg0))
10148         return NULL_TREE;
10149       else
10150         return fold_builtin_printf (loc, fndecl, arg1, arg2, ignore, fcode);
10151     break;
10152
10153     case BUILT_IN_FPRINTF:
10154     case BUILT_IN_FPRINTF_UNLOCKED:
10155     case BUILT_IN_VFPRINTF:
10156       return fold_builtin_fprintf (loc, fndecl, arg0, arg1, arg2,
10157                                    ignore, fcode);
10158
10159     case BUILT_IN_FPRINTF_CHK:
10160     case BUILT_IN_VFPRINTF_CHK:
10161       if (!validate_arg (arg1, INTEGER_TYPE)
10162           || TREE_SIDE_EFFECTS (arg1))
10163         return NULL_TREE;
10164       else
10165         return fold_builtin_fprintf (loc, fndecl, arg0, arg2, NULL_TREE,
10166                                      ignore, fcode);
10167
10168     default:
10169       break;
10170     }
10171   return NULL_TREE;
10172 }
10173
10174 /* Fold a call to built-in function FNDECL with 4 arguments, ARG0, ARG1,
10175    ARG2, and ARG3.  IGNORE is true if the result of the function call is
10176    ignored.  This function returns NULL_TREE if no simplification was
10177    possible.  */
10178
10179 static tree
10180 fold_builtin_4 (location_t loc, tree fndecl,
10181                 tree arg0, tree arg1, tree arg2, tree arg3, bool ignore)
10182 {
10183   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10184
10185   switch (fcode)
10186     {
10187     case BUILT_IN_MEMCPY_CHK:
10188     case BUILT_IN_MEMPCPY_CHK:
10189     case BUILT_IN_MEMMOVE_CHK:
10190     case BUILT_IN_MEMSET_CHK:
10191       return fold_builtin_memory_chk (loc, fndecl, arg0, arg1, arg2, arg3,
10192                                       NULL_TREE, ignore,
10193                                       DECL_FUNCTION_CODE (fndecl));
10194
10195     case BUILT_IN_STRNCPY_CHK:
10196       return fold_builtin_strncpy_chk (loc, arg0, arg1, arg2, arg3, NULL_TREE);
10197
10198     case BUILT_IN_STRNCAT_CHK:
10199       return fold_builtin_strncat_chk (loc, fndecl, arg0, arg1, arg2, arg3);
10200
10201     case BUILT_IN_SNPRINTF:
10202       return fold_builtin_snprintf (loc, arg0, arg1, arg2, arg3, ignore);
10203
10204     case BUILT_IN_FPRINTF_CHK:
10205     case BUILT_IN_VFPRINTF_CHK:
10206       if (!validate_arg (arg1, INTEGER_TYPE)
10207           || TREE_SIDE_EFFECTS (arg1))
10208         return NULL_TREE;
10209       else
10210         return fold_builtin_fprintf (loc, fndecl, arg0, arg2, arg3,
10211                                      ignore, fcode);
10212     break;
10213
10214     default:
10215       break;
10216     }
10217   return NULL_TREE;
10218 }
10219
10220 /* Fold a call to built-in function FNDECL.  ARGS is an array of NARGS
10221     arguments, where NARGS <= 4.  IGNORE is true if the result of the
10222     function call is ignored.  This function returns NULL_TREE if no
10223     simplification was possible.  Note that this only folds builtins with
10224     fixed argument patterns.  Foldings that do varargs-to-varargs
10225     transformations, or that match calls with more than 4 arguments,
10226     need to be handled with fold_builtin_varargs instead.  */
10227
10228 #define MAX_ARGS_TO_FOLD_BUILTIN 4
10229
10230 static tree
10231 fold_builtin_n (location_t loc, tree fndecl, tree *args, int nargs, bool ignore)
10232 {
10233   tree ret = NULL_TREE;
10234
10235   switch (nargs)
10236     {
10237     case 0:
10238       ret = fold_builtin_0 (loc, fndecl, ignore);
10239       break;
10240     case 1:
10241       ret = fold_builtin_1 (loc, fndecl, args[0], ignore);
10242       break;
10243     case 2:
10244       ret = fold_builtin_2 (loc, fndecl, args[0], args[1], ignore);
10245       break;
10246     case 3:
10247       ret = fold_builtin_3 (loc, fndecl, args[0], args[1], args[2], ignore);
10248       break;
10249     case 4:
10250       ret = fold_builtin_4 (loc, fndecl, args[0], args[1], args[2], args[3],
10251                             ignore);
10252       break;
10253     default:
10254       break;
10255     }
10256   if (ret)
10257     {
10258       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
10259       SET_EXPR_LOCATION (ret, loc);
10260       TREE_NO_WARNING (ret) = 1;
10261       return ret;
10262     }
10263   return NULL_TREE;
10264 }
10265
10266 /* Builtins with folding operations that operate on "..." arguments
10267    need special handling; we need to store the arguments in a convenient
10268    data structure before attempting any folding.  Fortunately there are
10269    only a few builtins that fall into this category.  FNDECL is the
10270    function, EXP is the CALL_EXPR for the call, and IGNORE is true if the
10271    result of the function call is ignored.  */
10272
10273 static tree
10274 fold_builtin_varargs (location_t loc, tree fndecl, tree exp,
10275                       bool ignore ATTRIBUTE_UNUSED)
10276 {
10277   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10278   tree ret = NULL_TREE;
10279
10280   switch (fcode)
10281     {
10282     case BUILT_IN_SPRINTF_CHK:
10283     case BUILT_IN_VSPRINTF_CHK:
10284       ret = fold_builtin_sprintf_chk (loc, exp, fcode);
10285       break;
10286
10287     case BUILT_IN_SNPRINTF_CHK:
10288     case BUILT_IN_VSNPRINTF_CHK:
10289       ret = fold_builtin_snprintf_chk (loc, exp, NULL_TREE, fcode);
10290       break;
10291
10292     case BUILT_IN_FPCLASSIFY:
10293       ret = fold_builtin_fpclassify (loc, exp);
10294       break;
10295
10296     default:
10297       break;
10298     }
10299   if (ret)
10300     {
10301       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
10302       SET_EXPR_LOCATION (ret, loc);
10303       TREE_NO_WARNING (ret) = 1;
10304       return ret;
10305     }
10306   return NULL_TREE;
10307 }
10308
10309 /* Return true if FNDECL shouldn't be folded right now.
10310    If a built-in function has an inline attribute always_inline
10311    wrapper, defer folding it after always_inline functions have
10312    been inlined, otherwise e.g. -D_FORTIFY_SOURCE checking
10313    might not be performed.  */
10314
10315 static bool
10316 avoid_folding_inline_builtin (tree fndecl)
10317 {
10318   return (DECL_DECLARED_INLINE_P (fndecl)
10319           && DECL_DISREGARD_INLINE_LIMITS (fndecl)
10320           && cfun
10321           && !cfun->always_inline_functions_inlined
10322           && lookup_attribute ("always_inline", DECL_ATTRIBUTES (fndecl)));
10323 }
10324
10325 /* A wrapper function for builtin folding that prevents warnings for
10326    "statement without effect" and the like, caused by removing the
10327    call node earlier than the warning is generated.  */
10328
10329 tree
10330 fold_call_expr (location_t loc, tree exp, bool ignore)
10331 {
10332   tree ret = NULL_TREE;
10333   tree fndecl = get_callee_fndecl (exp);
10334   if (fndecl
10335       && TREE_CODE (fndecl) == FUNCTION_DECL
10336       && DECL_BUILT_IN (fndecl)
10337       /* If CALL_EXPR_VA_ARG_PACK is set, the arguments aren't finalized
10338          yet.  Defer folding until we see all the arguments
10339          (after inlining).  */
10340       && !CALL_EXPR_VA_ARG_PACK (exp))
10341     {
10342       int nargs = call_expr_nargs (exp);
10343
10344       /* Before gimplification CALL_EXPR_VA_ARG_PACK is not set, but
10345          instead last argument is __builtin_va_arg_pack ().  Defer folding
10346          even in that case, until arguments are finalized.  */
10347       if (nargs && TREE_CODE (CALL_EXPR_ARG (exp, nargs - 1)) == CALL_EXPR)
10348         {
10349           tree fndecl2 = get_callee_fndecl (CALL_EXPR_ARG (exp, nargs - 1));
10350           if (fndecl2
10351               && TREE_CODE (fndecl2) == FUNCTION_DECL
10352               && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
10353               && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
10354             return NULL_TREE;
10355         }
10356
10357       if (avoid_folding_inline_builtin (fndecl))
10358         return NULL_TREE;
10359
10360       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
10361         return targetm.fold_builtin (fndecl, call_expr_nargs (exp),
10362                                      CALL_EXPR_ARGP (exp), ignore);
10363       else
10364         {
10365           if (nargs <= MAX_ARGS_TO_FOLD_BUILTIN)
10366             {
10367               tree *args = CALL_EXPR_ARGP (exp);
10368               ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
10369             }
10370           if (!ret)
10371             ret = fold_builtin_varargs (loc, fndecl, exp, ignore);
10372           if (ret)
10373             return ret;
10374         }
10375     }
10376   return NULL_TREE;
10377 }
10378
10379 /* Conveniently construct a function call expression.  FNDECL names the
10380    function to be called and N arguments are passed in the array
10381    ARGARRAY.  */
10382
10383 tree
10384 build_call_expr_loc_array (location_t loc, tree fndecl, int n, tree *argarray)
10385 {
10386   tree fntype = TREE_TYPE (fndecl);
10387   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
10388  
10389   return fold_builtin_call_array (loc, TREE_TYPE (fntype), fn, n, argarray);
10390 }
10391
10392 /* Conveniently construct a function call expression.  FNDECL names the
10393    function to be called and the arguments are passed in the vector
10394    VEC.  */
10395
10396 tree
10397 build_call_expr_loc_vec (location_t loc, tree fndecl, VEC(tree,gc) *vec)
10398 {
10399   return build_call_expr_loc_array (loc, fndecl, VEC_length (tree, vec),
10400                                     VEC_address (tree, vec));
10401 }
10402
10403
10404 /* Conveniently construct a function call expression.  FNDECL names the
10405    function to be called, N is the number of arguments, and the "..."
10406    parameters are the argument expressions.  */
10407
10408 tree
10409 build_call_expr_loc (location_t loc, tree fndecl, int n, ...)
10410 {
10411   va_list ap;
10412   tree *argarray = XALLOCAVEC (tree, n);
10413   int i;
10414
10415   va_start (ap, n);
10416   for (i = 0; i < n; i++)
10417     argarray[i] = va_arg (ap, tree);
10418   va_end (ap);
10419   return build_call_expr_loc_array (loc, fndecl, n, argarray);
10420 }
10421
10422 /* Like build_call_expr_loc (UNKNOWN_LOCATION, ...).  Duplicated because
10423    varargs macros aren't supported by all bootstrap compilers.  */
10424
10425 tree
10426 build_call_expr (tree fndecl, int n, ...)
10427 {
10428   va_list ap;
10429   tree *argarray = XALLOCAVEC (tree, n);
10430   int i;
10431
10432   va_start (ap, n);
10433   for (i = 0; i < n; i++)
10434     argarray[i] = va_arg (ap, tree);
10435   va_end (ap);
10436   return build_call_expr_loc_array (UNKNOWN_LOCATION, fndecl, n, argarray);
10437 }
10438
10439 /* Construct a CALL_EXPR with type TYPE with FN as the function expression.
10440    N arguments are passed in the array ARGARRAY.  */
10441
10442 tree
10443 fold_builtin_call_array (location_t loc, tree type,
10444                          tree fn,
10445                          int n,
10446                          tree *argarray)
10447 {
10448   tree ret = NULL_TREE;
10449    tree exp;
10450
10451   if (TREE_CODE (fn) == ADDR_EXPR)
10452   {
10453     tree fndecl = TREE_OPERAND (fn, 0);
10454     if (TREE_CODE (fndecl) == FUNCTION_DECL
10455         && DECL_BUILT_IN (fndecl))
10456       {
10457         /* If last argument is __builtin_va_arg_pack (), arguments to this
10458            function are not finalized yet.  Defer folding until they are.  */
10459         if (n && TREE_CODE (argarray[n - 1]) == CALL_EXPR)
10460           {
10461             tree fndecl2 = get_callee_fndecl (argarray[n - 1]);
10462             if (fndecl2
10463                 && TREE_CODE (fndecl2) == FUNCTION_DECL
10464                 && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
10465                 && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
10466               return build_call_array_loc (loc, type, fn, n, argarray);
10467           }
10468         if (avoid_folding_inline_builtin (fndecl))
10469           return build_call_array_loc (loc, type, fn, n, argarray);
10470         if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
10471           {
10472             ret = targetm.fold_builtin (fndecl, n, argarray, false);
10473             if (ret)
10474               return ret;
10475
10476             return build_call_array_loc (loc, type, fn, n, argarray);
10477           }
10478         else if (n <= MAX_ARGS_TO_FOLD_BUILTIN)
10479           {
10480             /* First try the transformations that don't require consing up
10481                an exp.  */
10482             ret = fold_builtin_n (loc, fndecl, argarray, n, false);
10483             if (ret)
10484               return ret;
10485           }
10486
10487         /* If we got this far, we need to build an exp.  */
10488         exp = build_call_array_loc (loc, type, fn, n, argarray);
10489         ret = fold_builtin_varargs (loc, fndecl, exp, false);
10490         return ret ? ret : exp;
10491       }
10492   }
10493
10494   return build_call_array_loc (loc, type, fn, n, argarray);
10495 }
10496
10497 /* Construct a new CALL_EXPR to FNDECL using the tail of the argument
10498    list ARGS along with N new arguments in NEWARGS.  SKIP is the number
10499    of arguments in ARGS to be omitted.  OLDNARGS is the number of
10500    elements in ARGS.  */
10501
10502 static tree
10503 rewrite_call_expr_valist (location_t loc, int oldnargs, tree *args,
10504                           int skip, tree fndecl, int n, va_list newargs)
10505 {
10506   int nargs = oldnargs - skip + n;
10507   tree *buffer;
10508
10509   if (n > 0)
10510     {
10511       int i, j;
10512
10513       buffer = XALLOCAVEC (tree, nargs);
10514       for (i = 0; i < n; i++)
10515         buffer[i] = va_arg (newargs, tree);
10516       for (j = skip; j < oldnargs; j++, i++)
10517         buffer[i] = args[j];
10518     }
10519   else
10520     buffer = args + skip;
10521
10522   return build_call_expr_loc_array (loc, fndecl, nargs, buffer);
10523 }
10524
10525 /* Construct a new CALL_EXPR to FNDECL using the tail of the argument
10526    list ARGS along with N new arguments specified as the "..."
10527    parameters.  SKIP is the number of arguments in ARGS to be omitted.
10528    OLDNARGS is the number of elements in ARGS.  */
10529
10530 static tree
10531 rewrite_call_expr_array (location_t loc, int oldnargs, tree *args,
10532                          int skip, tree fndecl, int n, ...)
10533 {
10534   va_list ap;
10535   tree t;
10536
10537   va_start (ap, n);
10538   t = rewrite_call_expr_valist (loc, oldnargs, args, skip, fndecl, n, ap);
10539   va_end (ap);
10540
10541   return t;
10542 }
10543
10544 /* Construct a new CALL_EXPR using the tail of the argument list of EXP
10545    along with N new arguments specified as the "..." parameters.  SKIP
10546    is the number of arguments in EXP to be omitted.  This function is used
10547    to do varargs-to-varargs transformations.  */
10548
10549 static tree
10550 rewrite_call_expr (location_t loc, tree exp, int skip, tree fndecl, int n, ...)
10551 {
10552   va_list ap;
10553   tree t;
10554
10555   va_start (ap, n);
10556   t = rewrite_call_expr_valist (loc, call_expr_nargs (exp),
10557                                 CALL_EXPR_ARGP (exp), skip, fndecl, n, ap);
10558   va_end (ap);
10559
10560   return t;
10561 }
10562
10563 /* Validate a single argument ARG against a tree code CODE representing
10564    a type.  */
10565
10566 static bool
10567 validate_arg (const_tree arg, enum tree_code code)
10568 {
10569   if (!arg)
10570     return false;
10571   else if (code == POINTER_TYPE)
10572     return POINTER_TYPE_P (TREE_TYPE (arg));
10573   else if (code == INTEGER_TYPE)
10574     return INTEGRAL_TYPE_P (TREE_TYPE (arg));
10575   return code == TREE_CODE (TREE_TYPE (arg));
10576 }
10577
10578 /* This function validates the types of a function call argument list
10579    against a specified list of tree_codes.  If the last specifier is a 0,
10580    that represents an ellipses, otherwise the last specifier must be a
10581    VOID_TYPE.
10582
10583    This is the GIMPLE version of validate_arglist.  Eventually we want to
10584    completely convert builtins.c to work from GIMPLEs and the tree based
10585    validate_arglist will then be removed.  */
10586
10587 bool
10588 validate_gimple_arglist (const_gimple call, ...)
10589 {
10590   enum tree_code code;
10591   bool res = 0;
10592   va_list ap;
10593   const_tree arg;
10594   size_t i;
10595
10596   va_start (ap, call);
10597   i = 0;
10598
10599   do
10600     {
10601       code = (enum tree_code) va_arg (ap, int);
10602       switch (code)
10603         {
10604         case 0:
10605           /* This signifies an ellipses, any further arguments are all ok.  */
10606           res = true;
10607           goto end;
10608         case VOID_TYPE:
10609           /* This signifies an endlink, if no arguments remain, return
10610              true, otherwise return false.  */
10611           res = (i == gimple_call_num_args (call));
10612           goto end;
10613         default:
10614           /* If no parameters remain or the parameter's code does not
10615              match the specified code, return false.  Otherwise continue
10616              checking any remaining arguments.  */
10617           arg = gimple_call_arg (call, i++);
10618           if (!validate_arg (arg, code))
10619             goto end;
10620           break;
10621         }
10622     }
10623   while (1);
10624
10625   /* We need gotos here since we can only have one VA_CLOSE in a
10626      function.  */
10627  end: ;
10628   va_end (ap);
10629
10630   return res;
10631 }
10632
10633 /* This function validates the types of a function call argument list
10634    against a specified list of tree_codes.  If the last specifier is a 0,
10635    that represents an ellipses, otherwise the last specifier must be a
10636    VOID_TYPE.  */
10637
10638 bool
10639 validate_arglist (const_tree callexpr, ...)
10640 {
10641   enum tree_code code;
10642   bool res = 0;
10643   va_list ap;
10644   const_call_expr_arg_iterator iter;
10645   const_tree arg;
10646
10647   va_start (ap, callexpr);
10648   init_const_call_expr_arg_iterator (callexpr, &iter);
10649
10650   do
10651     {
10652       code = (enum tree_code) va_arg (ap, int);
10653       switch (code)
10654         {
10655         case 0:
10656           /* This signifies an ellipses, any further arguments are all ok.  */
10657           res = true;
10658           goto end;
10659         case VOID_TYPE:
10660           /* This signifies an endlink, if no arguments remain, return
10661              true, otherwise return false.  */
10662           res = !more_const_call_expr_args_p (&iter);
10663           goto end;
10664         default:
10665           /* If no parameters remain or the parameter's code does not
10666              match the specified code, return false.  Otherwise continue
10667              checking any remaining arguments.  */
10668           arg = next_const_call_expr_arg (&iter);
10669           if (!validate_arg (arg, code))
10670             goto end;
10671           break;
10672         }
10673     }
10674   while (1);
10675
10676   /* We need gotos here since we can only have one VA_CLOSE in a
10677      function.  */
10678  end: ;
10679   va_end (ap);
10680
10681   return res;
10682 }
10683
10684 /* Default target-specific builtin expander that does nothing.  */
10685
10686 rtx
10687 default_expand_builtin (tree exp ATTRIBUTE_UNUSED,
10688                         rtx target ATTRIBUTE_UNUSED,
10689                         rtx subtarget ATTRIBUTE_UNUSED,
10690                         enum machine_mode mode ATTRIBUTE_UNUSED,
10691                         int ignore ATTRIBUTE_UNUSED)
10692 {
10693   return NULL_RTX;
10694 }
10695
10696 /* Returns true is EXP represents data that would potentially reside
10697    in a readonly section.  */
10698
10699 static bool
10700 readonly_data_expr (tree exp)
10701 {
10702   STRIP_NOPS (exp);
10703
10704   if (TREE_CODE (exp) != ADDR_EXPR)
10705     return false;
10706
10707   exp = get_base_address (TREE_OPERAND (exp, 0));
10708   if (!exp)
10709     return false;
10710
10711   /* Make sure we call decl_readonly_section only for trees it
10712      can handle (since it returns true for everything it doesn't
10713      understand).  */
10714   if (TREE_CODE (exp) == STRING_CST
10715       || TREE_CODE (exp) == CONSTRUCTOR
10716       || (TREE_CODE (exp) == VAR_DECL && TREE_STATIC (exp)))
10717     return decl_readonly_section (exp, 0);
10718   else
10719     return false;
10720 }
10721
10722 /* Simplify a call to the strstr builtin.  S1 and S2 are the arguments
10723    to the call, and TYPE is its return type.
10724
10725    Return NULL_TREE if no simplification was possible, otherwise return the
10726    simplified form of the call as a tree.
10727
10728    The simplified form may be a constant or other expression which
10729    computes the same value, but in a more efficient manner (including
10730    calls to other builtin functions).
10731
10732    The call may contain arguments which need to be evaluated, but
10733    which are not useful to determine the result of the call.  In
10734    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
10735    COMPOUND_EXPR will be an argument which must be evaluated.
10736    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
10737    COMPOUND_EXPR in the chain will contain the tree for the simplified
10738    form of the builtin function call.  */
10739
10740 static tree
10741 fold_builtin_strstr (location_t loc, tree s1, tree s2, tree type)
10742 {
10743   if (!validate_arg (s1, POINTER_TYPE)
10744       || !validate_arg (s2, POINTER_TYPE))
10745     return NULL_TREE;
10746   else
10747     {
10748       tree fn;
10749       const char *p1, *p2;
10750
10751       p2 = c_getstr (s2);
10752       if (p2 == NULL)
10753         return NULL_TREE;
10754
10755       p1 = c_getstr (s1);
10756       if (p1 != NULL)
10757         {
10758           const char *r = strstr (p1, p2);
10759           tree tem;
10760
10761           if (r == NULL)
10762             return build_int_cst (TREE_TYPE (s1), 0);
10763
10764           /* Return an offset into the constant string argument.  */
10765           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
10766           return fold_convert_loc (loc, type, tem);
10767         }
10768
10769       /* The argument is const char *, and the result is char *, so we need
10770          a type conversion here to avoid a warning.  */
10771       if (p2[0] == '\0')
10772         return fold_convert_loc (loc, type, s1);
10773
10774       if (p2[1] != '\0')
10775         return NULL_TREE;
10776
10777       fn = implicit_built_in_decls[BUILT_IN_STRCHR];
10778       if (!fn)
10779         return NULL_TREE;
10780
10781       /* New argument list transforming strstr(s1, s2) to
10782          strchr(s1, s2[0]).  */
10783       return build_call_expr_loc (loc, fn, 2, s1,
10784                                   build_int_cst (integer_type_node, p2[0]));
10785     }
10786 }
10787
10788 /* Simplify a call to the strchr builtin.  S1 and S2 are the arguments to
10789    the call, and TYPE is its return type.
10790
10791    Return NULL_TREE if no simplification was possible, otherwise return the
10792    simplified form of the call as a tree.
10793
10794    The simplified form may be a constant or other expression which
10795    computes the same value, but in a more efficient manner (including
10796    calls to other builtin functions).
10797
10798    The call may contain arguments which need to be evaluated, but
10799    which are not useful to determine the result of the call.  In
10800    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
10801    COMPOUND_EXPR will be an argument which must be evaluated.
10802    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
10803    COMPOUND_EXPR in the chain will contain the tree for the simplified
10804    form of the builtin function call.  */
10805
10806 static tree
10807 fold_builtin_strchr (location_t loc, tree s1, tree s2, tree type)
10808 {
10809   if (!validate_arg (s1, POINTER_TYPE)
10810       || !validate_arg (s2, INTEGER_TYPE))
10811     return NULL_TREE;
10812   else
10813     {
10814       const char *p1;
10815
10816       if (TREE_CODE (s2) != INTEGER_CST)
10817         return NULL_TREE;
10818
10819       p1 = c_getstr (s1);
10820       if (p1 != NULL)
10821         {
10822           char c;
10823           const char *r;
10824           tree tem;
10825
10826           if (target_char_cast (s2, &c))
10827             return NULL_TREE;
10828
10829           r = strchr (p1, c);
10830
10831           if (r == NULL)
10832             return build_int_cst (TREE_TYPE (s1), 0);
10833
10834           /* Return an offset into the constant string argument.  */
10835           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
10836           return fold_convert_loc (loc, type, tem);
10837         }
10838       return NULL_TREE;
10839     }
10840 }
10841
10842 /* Simplify a call to the strrchr builtin.  S1 and S2 are the arguments to
10843    the call, and TYPE is its return type.
10844
10845    Return NULL_TREE if no simplification was possible, otherwise return the
10846    simplified form of the call as a tree.
10847
10848    The simplified form may be a constant or other expression which
10849    computes the same value, but in a more efficient manner (including
10850    calls to other builtin functions).
10851
10852    The call may contain arguments which need to be evaluated, but
10853    which are not useful to determine the result of the call.  In
10854    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
10855    COMPOUND_EXPR will be an argument which must be evaluated.
10856    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
10857    COMPOUND_EXPR in the chain will contain the tree for the simplified
10858    form of the builtin function call.  */
10859
10860 static tree
10861 fold_builtin_strrchr (location_t loc, tree s1, tree s2, tree type)
10862 {
10863   if (!validate_arg (s1, POINTER_TYPE)
10864       || !validate_arg (s2, INTEGER_TYPE))
10865     return NULL_TREE;
10866   else
10867     {
10868       tree fn;
10869       const char *p1;
10870
10871       if (TREE_CODE (s2) != INTEGER_CST)
10872         return NULL_TREE;
10873
10874       p1 = c_getstr (s1);
10875       if (p1 != NULL)
10876         {
10877           char c;
10878           const char *r;
10879           tree tem;
10880
10881           if (target_char_cast (s2, &c))
10882             return NULL_TREE;
10883
10884           r = strrchr (p1, c);
10885
10886           if (r == NULL)
10887             return build_int_cst (TREE_TYPE (s1), 0);
10888
10889           /* Return an offset into the constant string argument.  */
10890           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
10891           return fold_convert_loc (loc, type, tem);
10892         }
10893
10894       if (! integer_zerop (s2))
10895         return NULL_TREE;
10896
10897       fn = implicit_built_in_decls[BUILT_IN_STRCHR];
10898       if (!fn)
10899         return NULL_TREE;
10900
10901       /* Transform strrchr(s1, '\0') to strchr(s1, '\0').  */
10902       return build_call_expr_loc (loc, fn, 2, s1, s2);
10903     }
10904 }
10905
10906 /* Simplify a call to the strpbrk builtin.  S1 and S2 are the arguments
10907    to the call, and TYPE is its return type.
10908
10909    Return NULL_TREE if no simplification was possible, otherwise return the
10910    simplified form of the call as a tree.
10911
10912    The simplified form may be a constant or other expression which
10913    computes the same value, but in a more efficient manner (including
10914    calls to other builtin functions).
10915
10916    The call may contain arguments which need to be evaluated, but
10917    which are not useful to determine the result of the call.  In
10918    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
10919    COMPOUND_EXPR will be an argument which must be evaluated.
10920    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
10921    COMPOUND_EXPR in the chain will contain the tree for the simplified
10922    form of the builtin function call.  */
10923
10924 static tree
10925 fold_builtin_strpbrk (location_t loc, tree s1, tree s2, tree type)
10926 {
10927   if (!validate_arg (s1, POINTER_TYPE)
10928       || !validate_arg (s2, POINTER_TYPE))
10929     return NULL_TREE;
10930   else
10931     {
10932       tree fn;
10933       const char *p1, *p2;
10934
10935       p2 = c_getstr (s2);
10936       if (p2 == NULL)
10937         return NULL_TREE;
10938
10939       p1 = c_getstr (s1);
10940       if (p1 != NULL)
10941         {
10942           const char *r = strpbrk (p1, p2);
10943           tree tem;
10944
10945           if (r == NULL)
10946             return build_int_cst (TREE_TYPE (s1), 0);
10947
10948           /* Return an offset into the constant string argument.  */
10949           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
10950           return fold_convert_loc (loc, type, tem);
10951         }
10952
10953       if (p2[0] == '\0')
10954         /* strpbrk(x, "") == NULL.
10955            Evaluate and ignore s1 in case it had side-effects.  */
10956         return omit_one_operand_loc (loc, TREE_TYPE (s1), integer_zero_node, s1);
10957
10958       if (p2[1] != '\0')
10959         return NULL_TREE;  /* Really call strpbrk.  */
10960
10961       fn = implicit_built_in_decls[BUILT_IN_STRCHR];
10962       if (!fn)
10963         return NULL_TREE;
10964
10965       /* New argument list transforming strpbrk(s1, s2) to
10966          strchr(s1, s2[0]).  */
10967       return build_call_expr_loc (loc, fn, 2, s1,
10968                                   build_int_cst (integer_type_node, p2[0]));
10969     }
10970 }
10971
10972 /* Simplify a call to the strcat builtin.  DST and SRC are the arguments
10973    to the call.
10974
10975    Return NULL_TREE if no simplification was possible, otherwise return the
10976    simplified form of the call as a tree.
10977
10978    The simplified form may be a constant or other expression which
10979    computes the same value, but in a more efficient manner (including
10980    calls to other builtin functions).
10981
10982    The call may contain arguments which need to be evaluated, but
10983    which are not useful to determine the result of the call.  In
10984    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
10985    COMPOUND_EXPR will be an argument which must be evaluated.
10986    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
10987    COMPOUND_EXPR in the chain will contain the tree for the simplified
10988    form of the builtin function call.  */
10989
10990 static tree
10991 fold_builtin_strcat (location_t loc ATTRIBUTE_UNUSED, tree dst, tree src)
10992 {
10993   if (!validate_arg (dst, POINTER_TYPE)
10994       || !validate_arg (src, POINTER_TYPE))
10995     return NULL_TREE;
10996   else
10997     {
10998       const char *p = c_getstr (src);
10999
11000       /* If the string length is zero, return the dst parameter.  */
11001       if (p && *p == '\0')
11002         return dst;
11003
11004       if (optimize_insn_for_speed_p ())
11005         {
11006           /* See if we can store by pieces into (dst + strlen(dst)).  */
11007           tree newdst, call;
11008           tree strlen_fn = implicit_built_in_decls[BUILT_IN_STRLEN];
11009           tree strcpy_fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11010
11011           if (!strlen_fn || !strcpy_fn)
11012             return NULL_TREE;
11013
11014           /* If we don't have a movstr we don't want to emit an strcpy
11015              call.  We have to do that if the length of the source string
11016              isn't computable (in that case we can use memcpy probably
11017              later expanding to a sequence of mov instructions).  If we
11018              have movstr instructions we can emit strcpy calls.  */
11019           if (!HAVE_movstr)
11020             {
11021               tree len = c_strlen (src, 1);
11022               if (! len || TREE_SIDE_EFFECTS (len))
11023                 return NULL_TREE;
11024             }
11025
11026           /* Stabilize the argument list.  */
11027           dst = builtin_save_expr (dst);
11028
11029           /* Create strlen (dst).  */
11030           newdst = build_call_expr_loc (loc, strlen_fn, 1, dst);
11031           /* Create (dst p+ strlen (dst)).  */
11032
11033           newdst = fold_build_pointer_plus_loc (loc, dst, newdst);
11034           newdst = builtin_save_expr (newdst);
11035
11036           call = build_call_expr_loc (loc, strcpy_fn, 2, newdst, src);
11037           return build2 (COMPOUND_EXPR, TREE_TYPE (dst), call, dst);
11038         }
11039       return NULL_TREE;
11040     }
11041 }
11042
11043 /* Simplify a call to the strncat builtin.  DST, SRC, and LEN are the
11044    arguments to the call.
11045
11046    Return NULL_TREE if no simplification was possible, otherwise return the
11047    simplified form of the call as a tree.
11048
11049    The simplified form may be a constant or other expression which
11050    computes the same value, but in a more efficient manner (including
11051    calls to other builtin functions).
11052
11053    The call may contain arguments which need to be evaluated, but
11054    which are not useful to determine the result of the call.  In
11055    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11056    COMPOUND_EXPR will be an argument which must be evaluated.
11057    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11058    COMPOUND_EXPR in the chain will contain the tree for the simplified
11059    form of the builtin function call.  */
11060
11061 static tree
11062 fold_builtin_strncat (location_t loc, tree dst, tree src, tree len)
11063 {
11064   if (!validate_arg (dst, POINTER_TYPE)
11065       || !validate_arg (src, POINTER_TYPE)
11066       || !validate_arg (len, INTEGER_TYPE))
11067     return NULL_TREE;
11068   else
11069     {
11070       const char *p = c_getstr (src);
11071
11072       /* If the requested length is zero, or the src parameter string
11073          length is zero, return the dst parameter.  */
11074       if (integer_zerop (len) || (p && *p == '\0'))
11075         return omit_two_operands_loc (loc, TREE_TYPE (dst), dst, src, len);
11076
11077       /* If the requested len is greater than or equal to the string
11078          length, call strcat.  */
11079       if (TREE_CODE (len) == INTEGER_CST && p
11080           && compare_tree_int (len, strlen (p)) >= 0)
11081         {
11082           tree fn = implicit_built_in_decls[BUILT_IN_STRCAT];
11083
11084           /* If the replacement _DECL isn't initialized, don't do the
11085              transformation.  */
11086           if (!fn)
11087             return NULL_TREE;
11088
11089           return build_call_expr_loc (loc, fn, 2, dst, src);
11090         }
11091       return NULL_TREE;
11092     }
11093 }
11094
11095 /* Simplify a call to the strspn builtin.  S1 and S2 are the arguments
11096    to the call.
11097
11098    Return NULL_TREE if no simplification was possible, otherwise return the
11099    simplified form of the call as a tree.
11100
11101    The simplified form may be a constant or other expression which
11102    computes the same value, but in a more efficient manner (including
11103    calls to other builtin functions).
11104
11105    The call may contain arguments which need to be evaluated, but
11106    which are not useful to determine the result of the call.  In
11107    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11108    COMPOUND_EXPR will be an argument which must be evaluated.
11109    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11110    COMPOUND_EXPR in the chain will contain the tree for the simplified
11111    form of the builtin function call.  */
11112
11113 static tree
11114 fold_builtin_strspn (location_t loc, tree s1, tree s2)
11115 {
11116   if (!validate_arg (s1, POINTER_TYPE)
11117       || !validate_arg (s2, POINTER_TYPE))
11118     return NULL_TREE;
11119   else
11120     {
11121       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
11122
11123       /* If both arguments are constants, evaluate at compile-time.  */
11124       if (p1 && p2)
11125         {
11126           const size_t r = strspn (p1, p2);
11127           return size_int (r);
11128         }
11129
11130       /* If either argument is "", return NULL_TREE.  */
11131       if ((p1 && *p1 == '\0') || (p2 && *p2 == '\0'))
11132         /* Evaluate and ignore both arguments in case either one has
11133            side-effects.  */
11134         return omit_two_operands_loc (loc, size_type_node, size_zero_node,
11135                                   s1, s2);
11136       return NULL_TREE;
11137     }
11138 }
11139
11140 /* Simplify a call to the strcspn builtin.  S1 and S2 are the arguments
11141    to the call.
11142
11143    Return NULL_TREE if no simplification was possible, otherwise return the
11144    simplified form of the call as a tree.
11145
11146    The simplified form may be a constant or other expression which
11147    computes the same value, but in a more efficient manner (including
11148    calls to other builtin functions).
11149
11150    The call may contain arguments which need to be evaluated, but
11151    which are not useful to determine the result of the call.  In
11152    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11153    COMPOUND_EXPR will be an argument which must be evaluated.
11154    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11155    COMPOUND_EXPR in the chain will contain the tree for the simplified
11156    form of the builtin function call.  */
11157
11158 static tree
11159 fold_builtin_strcspn (location_t loc, tree s1, tree s2)
11160 {
11161   if (!validate_arg (s1, POINTER_TYPE)
11162       || !validate_arg (s2, POINTER_TYPE))
11163     return NULL_TREE;
11164   else
11165     {
11166       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
11167
11168       /* If both arguments are constants, evaluate at compile-time.  */
11169       if (p1 && p2)
11170         {
11171           const size_t r = strcspn (p1, p2);
11172           return size_int (r);
11173         }
11174
11175       /* If the first argument is "", return NULL_TREE.  */
11176       if (p1 && *p1 == '\0')
11177         {
11178           /* Evaluate and ignore argument s2 in case it has
11179              side-effects.  */
11180           return omit_one_operand_loc (loc, size_type_node,
11181                                    size_zero_node, s2);
11182         }
11183
11184       /* If the second argument is "", return __builtin_strlen(s1).  */
11185       if (p2 && *p2 == '\0')
11186         {
11187           tree fn = implicit_built_in_decls[BUILT_IN_STRLEN];
11188
11189           /* If the replacement _DECL isn't initialized, don't do the
11190              transformation.  */
11191           if (!fn)
11192             return NULL_TREE;
11193
11194           return build_call_expr_loc (loc, fn, 1, s1);
11195         }
11196       return NULL_TREE;
11197     }
11198 }
11199
11200 /* Fold a call to the fputs builtin.  ARG0 and ARG1 are the arguments
11201    to the call.  IGNORE is true if the value returned
11202    by the builtin will be ignored.  UNLOCKED is true is true if this
11203    actually a call to fputs_unlocked.  If LEN in non-NULL, it represents
11204    the known length of the string.  Return NULL_TREE if no simplification
11205    was possible.  */
11206
11207 tree
11208 fold_builtin_fputs (location_t loc, tree arg0, tree arg1,
11209                     bool ignore, bool unlocked, tree len)
11210 {
11211   /* If we're using an unlocked function, assume the other unlocked
11212      functions exist explicitly.  */
11213   tree const fn_fputc = unlocked ? built_in_decls[BUILT_IN_FPUTC_UNLOCKED]
11214     : implicit_built_in_decls[BUILT_IN_FPUTC];
11215   tree const fn_fwrite = unlocked ? built_in_decls[BUILT_IN_FWRITE_UNLOCKED]
11216     : implicit_built_in_decls[BUILT_IN_FWRITE];
11217
11218   /* If the return value is used, don't do the transformation.  */
11219   if (!ignore)
11220     return NULL_TREE;
11221
11222   /* Verify the arguments in the original call.  */
11223   if (!validate_arg (arg0, POINTER_TYPE)
11224       || !validate_arg (arg1, POINTER_TYPE))
11225     return NULL_TREE;
11226
11227   if (! len)
11228     len = c_strlen (arg0, 0);
11229
11230   /* Get the length of the string passed to fputs.  If the length
11231      can't be determined, punt.  */
11232   if (!len
11233       || TREE_CODE (len) != INTEGER_CST)
11234     return NULL_TREE;
11235
11236   switch (compare_tree_int (len, 1))
11237     {
11238     case -1: /* length is 0, delete the call entirely .  */
11239       return omit_one_operand_loc (loc, integer_type_node,
11240                                integer_zero_node, arg1);;
11241
11242     case 0: /* length is 1, call fputc.  */
11243       {
11244         const char *p = c_getstr (arg0);
11245
11246         if (p != NULL)
11247           {
11248             if (fn_fputc)
11249               return build_call_expr_loc (loc, fn_fputc, 2,
11250                                           build_int_cst
11251                                             (integer_type_node, p[0]), arg1);
11252             else
11253               return NULL_TREE;
11254           }
11255       }
11256       /* FALLTHROUGH */
11257     case 1: /* length is greater than 1, call fwrite.  */
11258       {
11259         /* If optimizing for size keep fputs.  */
11260         if (optimize_function_for_size_p (cfun))
11261           return NULL_TREE;
11262         /* New argument list transforming fputs(string, stream) to
11263            fwrite(string, 1, len, stream).  */
11264         if (fn_fwrite)
11265           return build_call_expr_loc (loc, fn_fwrite, 4, arg0,
11266                                   size_one_node, len, arg1);
11267         else
11268           return NULL_TREE;
11269       }
11270     default:
11271       gcc_unreachable ();
11272     }
11273   return NULL_TREE;
11274 }
11275
11276 /* Fold the next_arg or va_start call EXP. Returns true if there was an error
11277    produced.  False otherwise.  This is done so that we don't output the error
11278    or warning twice or three times.  */
11279
11280 bool
11281 fold_builtin_next_arg (tree exp, bool va_start_p)
11282 {
11283   tree fntype = TREE_TYPE (current_function_decl);
11284   int nargs = call_expr_nargs (exp);
11285   tree arg;
11286
11287   if (!stdarg_p (fntype))
11288     {
11289       error ("%<va_start%> used in function with fixed args");
11290       return true;
11291     }
11292
11293   if (va_start_p)
11294     {
11295       if (va_start_p && (nargs != 2))
11296         {
11297           error ("wrong number of arguments to function %<va_start%>");
11298           return true;
11299         }
11300       arg = CALL_EXPR_ARG (exp, 1);
11301     }
11302   /* We use __builtin_va_start (ap, 0, 0) or __builtin_next_arg (0, 0)
11303      when we checked the arguments and if needed issued a warning.  */
11304   else
11305     {
11306       if (nargs == 0)
11307         {
11308           /* Evidently an out of date version of <stdarg.h>; can't validate
11309              va_start's second argument, but can still work as intended.  */
11310           warning (0, "%<__builtin_next_arg%> called without an argument");
11311           return true;
11312         }
11313       else if (nargs > 1)
11314         {
11315           error ("wrong number of arguments to function %<__builtin_next_arg%>");
11316           return true;
11317         }
11318       arg = CALL_EXPR_ARG (exp, 0);
11319     }
11320
11321   if (TREE_CODE (arg) == SSA_NAME)
11322     arg = SSA_NAME_VAR (arg);
11323
11324   /* We destructively modify the call to be __builtin_va_start (ap, 0)
11325      or __builtin_next_arg (0) the first time we see it, after checking
11326      the arguments and if needed issuing a warning.  */
11327   if (!integer_zerop (arg))
11328     {
11329       tree last_parm = tree_last (DECL_ARGUMENTS (current_function_decl));
11330
11331       /* Strip off all nops for the sake of the comparison.  This
11332          is not quite the same as STRIP_NOPS.  It does more.
11333          We must also strip off INDIRECT_EXPR for C++ reference
11334          parameters.  */
11335       while (CONVERT_EXPR_P (arg)
11336              || TREE_CODE (arg) == INDIRECT_REF)
11337         arg = TREE_OPERAND (arg, 0);
11338       if (arg != last_parm)
11339         {
11340           /* FIXME: Sometimes with the tree optimizers we can get the
11341              not the last argument even though the user used the last
11342              argument.  We just warn and set the arg to be the last
11343              argument so that we will get wrong-code because of
11344              it.  */
11345           warning (0, "second parameter of %<va_start%> not last named argument");
11346         }
11347
11348       /* Undefined by C99 7.15.1.4p4 (va_start):
11349          "If the parameter parmN is declared with the register storage
11350          class, with a function or array type, or with a type that is
11351          not compatible with the type that results after application of
11352          the default argument promotions, the behavior is undefined."
11353       */
11354       else if (DECL_REGISTER (arg))
11355         warning (0, "undefined behaviour when second parameter of "
11356                  "%<va_start%> is declared with %<register%> storage");
11357
11358       /* We want to verify the second parameter just once before the tree
11359          optimizers are run and then avoid keeping it in the tree,
11360          as otherwise we could warn even for correct code like:
11361          void foo (int i, ...)
11362          { va_list ap; i++; va_start (ap, i); va_end (ap); }  */
11363       if (va_start_p)
11364         CALL_EXPR_ARG (exp, 1) = integer_zero_node;
11365       else
11366         CALL_EXPR_ARG (exp, 0) = integer_zero_node;
11367     }
11368   return false;
11369 }
11370
11371
11372 /* Simplify a call to the sprintf builtin with arguments DEST, FMT, and ORIG.
11373    ORIG may be null if this is a 2-argument call.  We don't attempt to
11374    simplify calls with more than 3 arguments.
11375
11376    Return NULL_TREE if no simplification was possible, otherwise return the
11377    simplified form of the call as a tree.  If IGNORED is true, it means that
11378    the caller does not use the returned value of the function.  */
11379
11380 static tree
11381 fold_builtin_sprintf (location_t loc, tree dest, tree fmt,
11382                       tree orig, int ignored)
11383 {
11384   tree call, retval;
11385   const char *fmt_str = NULL;
11386
11387   /* Verify the required arguments in the original call.  We deal with two
11388      types of sprintf() calls: 'sprintf (str, fmt)' and
11389      'sprintf (dest, "%s", orig)'.  */
11390   if (!validate_arg (dest, POINTER_TYPE)
11391       || !validate_arg (fmt, POINTER_TYPE))
11392     return NULL_TREE;
11393   if (orig && !validate_arg (orig, POINTER_TYPE))
11394     return NULL_TREE;
11395
11396   /* Check whether the format is a literal string constant.  */
11397   fmt_str = c_getstr (fmt);
11398   if (fmt_str == NULL)
11399     return NULL_TREE;
11400
11401   call = NULL_TREE;
11402   retval = NULL_TREE;
11403
11404   if (!init_target_chars ())
11405     return NULL_TREE;
11406
11407   /* If the format doesn't contain % args or %%, use strcpy.  */
11408   if (strchr (fmt_str, target_percent) == NULL)
11409     {
11410       tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11411
11412       if (!fn)
11413         return NULL_TREE;
11414
11415       /* Don't optimize sprintf (buf, "abc", ptr++).  */
11416       if (orig)
11417         return NULL_TREE;
11418
11419       /* Convert sprintf (str, fmt) into strcpy (str, fmt) when
11420          'format' is known to contain no % formats.  */
11421       call = build_call_expr_loc (loc, fn, 2, dest, fmt);
11422       if (!ignored)
11423         retval = build_int_cst (integer_type_node, strlen (fmt_str));
11424     }
11425
11426   /* If the format is "%s", use strcpy if the result isn't used.  */
11427   else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
11428     {
11429       tree fn;
11430       fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11431
11432       if (!fn)
11433         return NULL_TREE;
11434
11435       /* Don't crash on sprintf (str1, "%s").  */
11436       if (!orig)
11437         return NULL_TREE;
11438
11439       /* Convert sprintf (str1, "%s", str2) into strcpy (str1, str2).  */
11440       if (!ignored)
11441         {
11442           retval = c_strlen (orig, 1);
11443           if (!retval || TREE_CODE (retval) != INTEGER_CST)
11444             return NULL_TREE;
11445         }
11446       call = build_call_expr_loc (loc, fn, 2, dest, orig);
11447     }
11448
11449   if (call && retval)
11450     {
11451       retval = fold_convert_loc
11452         (loc, TREE_TYPE (TREE_TYPE (implicit_built_in_decls[BUILT_IN_SPRINTF])),
11453          retval);
11454       return build2 (COMPOUND_EXPR, TREE_TYPE (retval), call, retval);
11455     }
11456   else
11457     return call;
11458 }
11459
11460 /* Simplify a call to the snprintf builtin with arguments DEST, DESTSIZE,
11461    FMT, and ORIG.  ORIG may be null if this is a 3-argument call.  We don't
11462    attempt to simplify calls with more than 4 arguments.
11463
11464    Return NULL_TREE if no simplification was possible, otherwise return the
11465    simplified form of the call as a tree.  If IGNORED is true, it means that
11466    the caller does not use the returned value of the function.  */
11467
11468 static tree
11469 fold_builtin_snprintf (location_t loc, tree dest, tree destsize, tree fmt,
11470                        tree orig, int ignored)
11471 {
11472   tree call, retval;
11473   const char *fmt_str = NULL;
11474   unsigned HOST_WIDE_INT destlen;
11475
11476   /* Verify the required arguments in the original call.  We deal with two
11477      types of snprintf() calls: 'snprintf (str, cst, fmt)' and
11478      'snprintf (dest, cst, "%s", orig)'.  */
11479   if (!validate_arg (dest, POINTER_TYPE)
11480       || !validate_arg (destsize, INTEGER_TYPE)
11481       || !validate_arg (fmt, POINTER_TYPE))
11482     return NULL_TREE;
11483   if (orig && !validate_arg (orig, POINTER_TYPE))
11484     return NULL_TREE;
11485
11486   if (!host_integerp (destsize, 1))
11487     return NULL_TREE;
11488
11489   /* Check whether the format is a literal string constant.  */
11490   fmt_str = c_getstr (fmt);
11491   if (fmt_str == NULL)
11492     return NULL_TREE;
11493
11494   call = NULL_TREE;
11495   retval = NULL_TREE;
11496
11497   if (!init_target_chars ())
11498     return NULL_TREE;
11499
11500   destlen = tree_low_cst (destsize, 1);
11501
11502   /* If the format doesn't contain % args or %%, use strcpy.  */
11503   if (strchr (fmt_str, target_percent) == NULL)
11504     {
11505       tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11506       size_t len = strlen (fmt_str);
11507
11508       /* Don't optimize snprintf (buf, 4, "abc", ptr++).  */
11509       if (orig)
11510         return NULL_TREE;
11511
11512       /* We could expand this as
11513          memcpy (str, fmt, cst - 1); str[cst - 1] = '\0';
11514          or to
11515          memcpy (str, fmt_with_nul_at_cstm1, cst);
11516          but in the former case that might increase code size
11517          and in the latter case grow .rodata section too much.
11518          So punt for now.  */
11519       if (len >= destlen)
11520         return NULL_TREE;
11521
11522       if (!fn)
11523         return NULL_TREE;
11524
11525       /* Convert snprintf (str, cst, fmt) into strcpy (str, fmt) when
11526          'format' is known to contain no % formats and
11527          strlen (fmt) < cst.  */
11528       call = build_call_expr_loc (loc, fn, 2, dest, fmt);
11529
11530       if (!ignored)
11531         retval = build_int_cst (integer_type_node, strlen (fmt_str));
11532     }
11533
11534   /* If the format is "%s", use strcpy if the result isn't used.  */
11535   else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
11536     {
11537       tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11538       unsigned HOST_WIDE_INT origlen;
11539
11540       /* Don't crash on snprintf (str1, cst, "%s").  */
11541       if (!orig)
11542         return NULL_TREE;
11543
11544       retval = c_strlen (orig, 1);
11545       if (!retval || !host_integerp (retval, 1))  
11546         return NULL_TREE;
11547
11548       origlen = tree_low_cst (retval, 1);
11549       /* We could expand this as
11550          memcpy (str1, str2, cst - 1); str1[cst - 1] = '\0';
11551          or to
11552          memcpy (str1, str2_with_nul_at_cstm1, cst);
11553          but in the former case that might increase code size
11554          and in the latter case grow .rodata section too much.
11555          So punt for now.  */
11556       if (origlen >= destlen)
11557         return NULL_TREE;
11558
11559       /* Convert snprintf (str1, cst, "%s", str2) into
11560          strcpy (str1, str2) if strlen (str2) < cst.  */
11561       if (!fn)
11562         return NULL_TREE;
11563
11564       call = build_call_expr_loc (loc, fn, 2, dest, orig);
11565
11566       if (ignored)
11567         retval = NULL_TREE;
11568     }
11569
11570   if (call && retval)
11571     {
11572       tree fn = built_in_decls[BUILT_IN_SNPRINTF];
11573       retval = fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fn)), retval);
11574       return build2 (COMPOUND_EXPR, TREE_TYPE (retval), call, retval);
11575     }
11576   else
11577     return call;
11578 }
11579
11580 /* Expand a call EXP to __builtin_object_size.  */
11581
11582 rtx
11583 expand_builtin_object_size (tree exp)
11584 {
11585   tree ost;
11586   int object_size_type;
11587   tree fndecl = get_callee_fndecl (exp);
11588
11589   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
11590     {
11591       error ("%Kfirst argument of %D must be a pointer, second integer constant",
11592              exp, fndecl);
11593       expand_builtin_trap ();
11594       return const0_rtx;
11595     }
11596
11597   ost = CALL_EXPR_ARG (exp, 1);
11598   STRIP_NOPS (ost);
11599
11600   if (TREE_CODE (ost) != INTEGER_CST
11601       || tree_int_cst_sgn (ost) < 0
11602       || compare_tree_int (ost, 3) > 0)
11603     {
11604       error ("%Klast argument of %D is not integer constant between 0 and 3",
11605              exp, fndecl);
11606       expand_builtin_trap ();
11607       return const0_rtx;
11608     }
11609
11610   object_size_type = tree_low_cst (ost, 0);
11611
11612   return object_size_type < 2 ? constm1_rtx : const0_rtx;
11613 }
11614
11615 /* Expand EXP, a call to the __mem{cpy,pcpy,move,set}_chk builtin.
11616    FCODE is the BUILT_IN_* to use.
11617    Return NULL_RTX if we failed; the caller should emit a normal call,
11618    otherwise try to get the result in TARGET, if convenient (and in
11619    mode MODE if that's convenient).  */
11620
11621 static rtx
11622 expand_builtin_memory_chk (tree exp, rtx target, enum machine_mode mode,
11623                            enum built_in_function fcode)
11624 {
11625   tree dest, src, len, size;
11626
11627   if (!validate_arglist (exp,
11628                          POINTER_TYPE,
11629                          fcode == BUILT_IN_MEMSET_CHK
11630                          ? INTEGER_TYPE : POINTER_TYPE,
11631                          INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
11632     return NULL_RTX;
11633
11634   dest = CALL_EXPR_ARG (exp, 0);
11635   src = CALL_EXPR_ARG (exp, 1);
11636   len = CALL_EXPR_ARG (exp, 2);
11637   size = CALL_EXPR_ARG (exp, 3);
11638
11639   if (! host_integerp (size, 1))
11640     return NULL_RTX;
11641
11642   if (host_integerp (len, 1) || integer_all_onesp (size))
11643     {
11644       tree fn;
11645
11646       if (! integer_all_onesp (size) && tree_int_cst_lt (size, len))
11647         {
11648           warning_at (tree_nonartificial_location (exp),
11649                       0, "%Kcall to %D will always overflow destination buffer",
11650                       exp, get_callee_fndecl (exp));
11651           return NULL_RTX;
11652         }
11653
11654       fn = NULL_TREE;
11655       /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
11656          mem{cpy,pcpy,move,set} is available.  */
11657       switch (fcode)
11658         {
11659         case BUILT_IN_MEMCPY_CHK:
11660           fn = built_in_decls[BUILT_IN_MEMCPY];
11661           break;
11662         case BUILT_IN_MEMPCPY_CHK:
11663           fn = built_in_decls[BUILT_IN_MEMPCPY];
11664           break;
11665         case BUILT_IN_MEMMOVE_CHK:
11666           fn = built_in_decls[BUILT_IN_MEMMOVE];
11667           break;
11668         case BUILT_IN_MEMSET_CHK:
11669           fn = built_in_decls[BUILT_IN_MEMSET];
11670           break;
11671         default:
11672           break;
11673         }
11674
11675       if (! fn)
11676         return NULL_RTX;
11677
11678       fn = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 3, dest, src, len);
11679       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
11680       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
11681       return expand_expr (fn, target, mode, EXPAND_NORMAL);
11682     }
11683   else if (fcode == BUILT_IN_MEMSET_CHK)
11684     return NULL_RTX;
11685   else
11686     {
11687       unsigned int dest_align = get_pointer_alignment (dest);
11688
11689       /* If DEST is not a pointer type, call the normal function.  */
11690       if (dest_align == 0)
11691         return NULL_RTX;
11692
11693       /* If SRC and DEST are the same (and not volatile), do nothing.  */
11694       if (operand_equal_p (src, dest, 0))
11695         {
11696           tree expr;
11697
11698           if (fcode != BUILT_IN_MEMPCPY_CHK)
11699             {
11700               /* Evaluate and ignore LEN in case it has side-effects.  */
11701               expand_expr (len, const0_rtx, VOIDmode, EXPAND_NORMAL);
11702               return expand_expr (dest, target, mode, EXPAND_NORMAL);
11703             }
11704
11705           expr = fold_build_pointer_plus (dest, len);
11706           return expand_expr (expr, target, mode, EXPAND_NORMAL);
11707         }
11708
11709       /* __memmove_chk special case.  */
11710       if (fcode == BUILT_IN_MEMMOVE_CHK)
11711         {
11712           unsigned int src_align = get_pointer_alignment (src);
11713
11714           if (src_align == 0)
11715             return NULL_RTX;
11716
11717           /* If src is categorized for a readonly section we can use
11718              normal __memcpy_chk.  */
11719           if (readonly_data_expr (src))
11720             {
11721               tree fn = built_in_decls[BUILT_IN_MEMCPY_CHK];
11722               if (!fn)
11723                 return NULL_RTX;
11724               fn = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 4,
11725                                           dest, src, len, size);
11726               gcc_assert (TREE_CODE (fn) == CALL_EXPR);
11727               CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
11728               return expand_expr (fn, target, mode, EXPAND_NORMAL);
11729             }
11730         }
11731       return NULL_RTX;
11732     }
11733 }
11734
11735 /* Emit warning if a buffer overflow is detected at compile time.  */
11736
11737 static void
11738 maybe_emit_chk_warning (tree exp, enum built_in_function fcode)
11739 {
11740   int is_strlen = 0;
11741   tree len, size;
11742   location_t loc = tree_nonartificial_location (exp);
11743
11744   switch (fcode)
11745     {
11746     case BUILT_IN_STRCPY_CHK:
11747     case BUILT_IN_STPCPY_CHK:
11748     /* For __strcat_chk the warning will be emitted only if overflowing
11749        by at least strlen (dest) + 1 bytes.  */
11750     case BUILT_IN_STRCAT_CHK:
11751       len = CALL_EXPR_ARG (exp, 1);
11752       size = CALL_EXPR_ARG (exp, 2);
11753       is_strlen = 1;
11754       break;
11755     case BUILT_IN_STRNCAT_CHK:
11756     case BUILT_IN_STRNCPY_CHK:
11757       len = CALL_EXPR_ARG (exp, 2);
11758       size = CALL_EXPR_ARG (exp, 3);
11759       break;
11760     case BUILT_IN_SNPRINTF_CHK:
11761     case BUILT_IN_VSNPRINTF_CHK:
11762       len = CALL_EXPR_ARG (exp, 1);
11763       size = CALL_EXPR_ARG (exp, 3);
11764       break;
11765     default:
11766       gcc_unreachable ();
11767     }
11768
11769   if (!len || !size)
11770     return;
11771
11772   if (! host_integerp (size, 1) || integer_all_onesp (size))
11773     return;
11774
11775   if (is_strlen)
11776     {
11777       len = c_strlen (len, 1);
11778       if (! len || ! host_integerp (len, 1) || tree_int_cst_lt (len, size))
11779         return;
11780     }
11781   else if (fcode == BUILT_IN_STRNCAT_CHK)
11782     {
11783       tree src = CALL_EXPR_ARG (exp, 1);
11784       if (! src || ! host_integerp (len, 1) || tree_int_cst_lt (len, size))
11785         return;
11786       src = c_strlen (src, 1);
11787       if (! src || ! host_integerp (src, 1))
11788         {
11789           warning_at (loc, 0, "%Kcall to %D might overflow destination buffer",
11790                       exp, get_callee_fndecl (exp));
11791           return;
11792         }
11793       else if (tree_int_cst_lt (src, size))
11794         return;
11795     }
11796   else if (! host_integerp (len, 1) || ! tree_int_cst_lt (size, len))
11797     return;
11798
11799   warning_at (loc, 0, "%Kcall to %D will always overflow destination buffer",
11800               exp, get_callee_fndecl (exp));
11801 }
11802
11803 /* Emit warning if a buffer overflow is detected at compile time
11804    in __sprintf_chk/__vsprintf_chk calls.  */
11805
11806 static void
11807 maybe_emit_sprintf_chk_warning (tree exp, enum built_in_function fcode)
11808 {
11809   tree size, len, fmt;
11810   const char *fmt_str;
11811   int nargs = call_expr_nargs (exp);
11812
11813   /* Verify the required arguments in the original call.  */
11814
11815   if (nargs < 4)
11816     return;
11817   size = CALL_EXPR_ARG (exp, 2);
11818   fmt = CALL_EXPR_ARG (exp, 3);
11819
11820   if (! host_integerp (size, 1) || integer_all_onesp (size))
11821     return;
11822
11823   /* Check whether the format is a literal string constant.  */
11824   fmt_str = c_getstr (fmt);
11825   if (fmt_str == NULL)
11826     return;
11827
11828   if (!init_target_chars ())
11829     return;
11830
11831   /* If the format doesn't contain % args or %%, we know its size.  */
11832   if (strchr (fmt_str, target_percent) == 0)
11833     len = build_int_cstu (size_type_node, strlen (fmt_str));
11834   /* If the format is "%s" and first ... argument is a string literal,
11835      we know it too.  */
11836   else if (fcode == BUILT_IN_SPRINTF_CHK
11837            && strcmp (fmt_str, target_percent_s) == 0)
11838     {
11839       tree arg;
11840
11841       if (nargs < 5)
11842         return;
11843       arg = CALL_EXPR_ARG (exp, 4);
11844       if (! POINTER_TYPE_P (TREE_TYPE (arg)))
11845         return;
11846
11847       len = c_strlen (arg, 1);
11848       if (!len || ! host_integerp (len, 1))
11849         return;
11850     }
11851   else
11852     return;
11853
11854   if (! tree_int_cst_lt (len, size))
11855     warning_at (tree_nonartificial_location (exp),
11856                 0, "%Kcall to %D will always overflow destination buffer",
11857                 exp, get_callee_fndecl (exp));
11858 }
11859
11860 /* Emit warning if a free is called with address of a variable.  */
11861
11862 static void
11863 maybe_emit_free_warning (tree exp)
11864 {
11865   tree arg = CALL_EXPR_ARG (exp, 0);
11866
11867   STRIP_NOPS (arg);
11868   if (TREE_CODE (arg) != ADDR_EXPR)
11869     return;
11870
11871   arg = get_base_address (TREE_OPERAND (arg, 0));
11872   if (arg == NULL || INDIRECT_REF_P (arg) || TREE_CODE (arg) == MEM_REF)
11873     return;
11874
11875   if (SSA_VAR_P (arg))
11876     warning_at (tree_nonartificial_location (exp),
11877                 0, "%Kattempt to free a non-heap object %qD", exp, arg);
11878   else
11879     warning_at (tree_nonartificial_location (exp),
11880                 0, "%Kattempt to free a non-heap object", exp);
11881 }
11882
11883 /* Fold a call to __builtin_object_size with arguments PTR and OST,
11884    if possible.  */
11885
11886 tree
11887 fold_builtin_object_size (tree ptr, tree ost)
11888 {
11889   unsigned HOST_WIDE_INT bytes;
11890   int object_size_type;
11891
11892   if (!validate_arg (ptr, POINTER_TYPE)
11893       || !validate_arg (ost, INTEGER_TYPE))
11894     return NULL_TREE;
11895
11896   STRIP_NOPS (ost);
11897
11898   if (TREE_CODE (ost) != INTEGER_CST
11899       || tree_int_cst_sgn (ost) < 0
11900       || compare_tree_int (ost, 3) > 0)
11901     return NULL_TREE;
11902
11903   object_size_type = tree_low_cst (ost, 0);
11904
11905   /* __builtin_object_size doesn't evaluate side-effects in its arguments;
11906      if there are any side-effects, it returns (size_t) -1 for types 0 and 1
11907      and (size_t) 0 for types 2 and 3.  */
11908   if (TREE_SIDE_EFFECTS (ptr))
11909     return build_int_cst_type (size_type_node, object_size_type < 2 ? -1 : 0);
11910
11911   if (TREE_CODE (ptr) == ADDR_EXPR)
11912     {
11913       bytes = compute_builtin_object_size (ptr, object_size_type);
11914       if (double_int_fits_to_tree_p (size_type_node,
11915                                      uhwi_to_double_int (bytes)))
11916         return build_int_cstu (size_type_node, bytes);
11917     }
11918   else if (TREE_CODE (ptr) == SSA_NAME)
11919     {
11920       /* If object size is not known yet, delay folding until
11921        later.  Maybe subsequent passes will help determining
11922        it.  */
11923       bytes = compute_builtin_object_size (ptr, object_size_type);
11924       if (bytes != (unsigned HOST_WIDE_INT) (object_size_type < 2 ? -1 : 0)
11925           && double_int_fits_to_tree_p (size_type_node,
11926                                         uhwi_to_double_int (bytes)))
11927         return build_int_cstu (size_type_node, bytes);
11928     }
11929
11930   return NULL_TREE;
11931 }
11932
11933 /* Fold a call to the __mem{cpy,pcpy,move,set}_chk builtin.
11934    DEST, SRC, LEN, and SIZE are the arguments to the call.
11935    IGNORE is true, if return value can be ignored.  FCODE is the BUILT_IN_*
11936    code of the builtin.  If MAXLEN is not NULL, it is maximum length
11937    passed as third argument.  */
11938
11939 tree
11940 fold_builtin_memory_chk (location_t loc, tree fndecl,
11941                          tree dest, tree src, tree len, tree size,
11942                          tree maxlen, bool ignore,
11943                          enum built_in_function fcode)
11944 {
11945   tree fn;
11946
11947   if (!validate_arg (dest, POINTER_TYPE)
11948       || !validate_arg (src,
11949                         (fcode == BUILT_IN_MEMSET_CHK
11950                          ? INTEGER_TYPE : POINTER_TYPE))
11951       || !validate_arg (len, INTEGER_TYPE)
11952       || !validate_arg (size, INTEGER_TYPE))
11953     return NULL_TREE;
11954
11955   /* If SRC and DEST are the same (and not volatile), return DEST
11956      (resp. DEST+LEN for __mempcpy_chk).  */
11957   if (fcode != BUILT_IN_MEMSET_CHK && operand_equal_p (src, dest, 0))
11958     {
11959       if (fcode != BUILT_IN_MEMPCPY_CHK)
11960         return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
11961                                  dest, len);
11962       else
11963         {
11964           tree temp = fold_build_pointer_plus_loc (loc, dest, len);
11965           return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), temp);
11966         }
11967     }
11968
11969   if (! host_integerp (size, 1))
11970     return NULL_TREE;
11971
11972   if (! integer_all_onesp (size))
11973     {
11974       if (! host_integerp (len, 1))
11975         {
11976           /* If LEN is not constant, try MAXLEN too.
11977              For MAXLEN only allow optimizing into non-_ocs function
11978              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
11979           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
11980             {
11981               if (fcode == BUILT_IN_MEMPCPY_CHK && ignore)
11982                 {
11983                   /* (void) __mempcpy_chk () can be optimized into
11984                      (void) __memcpy_chk ().  */
11985                   fn = built_in_decls[BUILT_IN_MEMCPY_CHK];
11986                   if (!fn)
11987                     return NULL_TREE;
11988
11989                   return build_call_expr_loc (loc, fn, 4, dest, src, len, size);
11990                 }
11991               return NULL_TREE;
11992             }
11993         }
11994       else
11995         maxlen = len;
11996
11997       if (tree_int_cst_lt (size, maxlen))
11998         return NULL_TREE;
11999     }
12000
12001   fn = NULL_TREE;
12002   /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
12003      mem{cpy,pcpy,move,set} is available.  */
12004   switch (fcode)
12005     {
12006     case BUILT_IN_MEMCPY_CHK:
12007       fn = built_in_decls[BUILT_IN_MEMCPY];
12008       break;
12009     case BUILT_IN_MEMPCPY_CHK:
12010       fn = built_in_decls[BUILT_IN_MEMPCPY];
12011       break;
12012     case BUILT_IN_MEMMOVE_CHK:
12013       fn = built_in_decls[BUILT_IN_MEMMOVE];
12014       break;
12015     case BUILT_IN_MEMSET_CHK:
12016       fn = built_in_decls[BUILT_IN_MEMSET];
12017       break;
12018     default:
12019       break;
12020     }
12021
12022   if (!fn)
12023     return NULL_TREE;
12024
12025   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12026 }
12027
12028 /* Fold a call to the __st[rp]cpy_chk builtin.
12029    DEST, SRC, and SIZE are the arguments to the call.
12030    IGNORE is true if return value can be ignored.  FCODE is the BUILT_IN_*
12031    code of the builtin.  If MAXLEN is not NULL, it is maximum length of
12032    strings passed as second argument.  */
12033
12034 tree
12035 fold_builtin_stxcpy_chk (location_t loc, tree fndecl, tree dest,
12036                          tree src, tree size,
12037                          tree maxlen, bool ignore,
12038                          enum built_in_function fcode)
12039 {
12040   tree len, fn;
12041
12042   if (!validate_arg (dest, POINTER_TYPE)
12043       || !validate_arg (src, POINTER_TYPE)
12044       || !validate_arg (size, INTEGER_TYPE))
12045     return NULL_TREE;
12046
12047   /* If SRC and DEST are the same (and not volatile), return DEST.  */
12048   if (fcode == BUILT_IN_STRCPY_CHK && operand_equal_p (src, dest, 0))
12049     return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest);
12050
12051   if (! host_integerp (size, 1))
12052     return NULL_TREE;
12053
12054   if (! integer_all_onesp (size))
12055     {
12056       len = c_strlen (src, 1);
12057       if (! len || ! host_integerp (len, 1))
12058         {
12059           /* If LEN is not constant, try MAXLEN too.
12060              For MAXLEN only allow optimizing into non-_ocs function
12061              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12062           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12063             {
12064               if (fcode == BUILT_IN_STPCPY_CHK)
12065                 {
12066                   if (! ignore)
12067                     return NULL_TREE;
12068
12069                   /* If return value of __stpcpy_chk is ignored,
12070                      optimize into __strcpy_chk.  */
12071                   fn = built_in_decls[BUILT_IN_STRCPY_CHK];
12072                   if (!fn)
12073                     return NULL_TREE;
12074
12075                   return build_call_expr_loc (loc, fn, 3, dest, src, size);
12076                 }
12077
12078               if (! len || TREE_SIDE_EFFECTS (len))
12079                 return NULL_TREE;
12080
12081               /* If c_strlen returned something, but not a constant,
12082                  transform __strcpy_chk into __memcpy_chk.  */
12083               fn = built_in_decls[BUILT_IN_MEMCPY_CHK];
12084               if (!fn)
12085                 return NULL_TREE;
12086
12087               len = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
12088               return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
12089                                        build_call_expr_loc (loc, fn, 4,
12090                                                         dest, src, len, size));
12091             }
12092         }
12093       else
12094         maxlen = len;
12095
12096       if (! tree_int_cst_lt (maxlen, size))
12097         return NULL_TREE;
12098     }
12099
12100   /* If __builtin_st{r,p}cpy_chk is used, assume st{r,p}cpy is available.  */
12101   fn = built_in_decls[fcode == BUILT_IN_STPCPY_CHK
12102                       ? BUILT_IN_STPCPY : BUILT_IN_STRCPY];
12103   if (!fn)
12104     return NULL_TREE;
12105
12106   return build_call_expr_loc (loc, fn, 2, dest, src);
12107 }
12108
12109 /* Fold a call to the __strncpy_chk builtin.  DEST, SRC, LEN, and SIZE
12110    are the arguments to the call.  If MAXLEN is not NULL, it is maximum
12111    length passed as third argument.  */
12112
12113 tree
12114 fold_builtin_strncpy_chk (location_t loc, tree dest, tree src,
12115                           tree len, tree size, tree maxlen)
12116 {
12117   tree fn;
12118
12119   if (!validate_arg (dest, POINTER_TYPE)
12120       || !validate_arg (src, POINTER_TYPE)
12121       || !validate_arg (len, INTEGER_TYPE)
12122       || !validate_arg (size, INTEGER_TYPE))
12123     return NULL_TREE;
12124
12125   if (! host_integerp (size, 1))
12126     return NULL_TREE;
12127
12128   if (! integer_all_onesp (size))
12129     {
12130       if (! host_integerp (len, 1))
12131         {
12132           /* If LEN is not constant, try MAXLEN too.
12133              For MAXLEN only allow optimizing into non-_ocs function
12134              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12135           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12136             return NULL_TREE;
12137         }
12138       else
12139         maxlen = len;
12140
12141       if (tree_int_cst_lt (size, maxlen))
12142         return NULL_TREE;
12143     }
12144
12145   /* If __builtin_strncpy_chk is used, assume strncpy is available.  */
12146   fn = built_in_decls[BUILT_IN_STRNCPY];
12147   if (!fn)
12148     return NULL_TREE;
12149
12150   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12151 }
12152
12153 /* Fold a call to the __strcat_chk builtin FNDECL.  DEST, SRC, and SIZE
12154    are the arguments to the call.  */
12155
12156 static tree
12157 fold_builtin_strcat_chk (location_t loc, tree fndecl, tree dest,
12158                          tree src, tree size)
12159 {
12160   tree fn;
12161   const char *p;
12162
12163   if (!validate_arg (dest, POINTER_TYPE)
12164       || !validate_arg (src, POINTER_TYPE)
12165       || !validate_arg (size, INTEGER_TYPE))
12166     return NULL_TREE;
12167
12168   p = c_getstr (src);
12169   /* If the SRC parameter is "", return DEST.  */
12170   if (p && *p == '\0')
12171     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
12172
12173   if (! host_integerp (size, 1) || ! integer_all_onesp (size))
12174     return NULL_TREE;
12175
12176   /* If __builtin_strcat_chk is used, assume strcat is available.  */
12177   fn = built_in_decls[BUILT_IN_STRCAT];
12178   if (!fn)
12179     return NULL_TREE;
12180
12181   return build_call_expr_loc (loc, fn, 2, dest, src);
12182 }
12183
12184 /* Fold a call to the __strncat_chk builtin with arguments DEST, SRC,
12185    LEN, and SIZE.  */
12186
12187 static tree
12188 fold_builtin_strncat_chk (location_t loc, tree fndecl,
12189                           tree dest, tree src, tree len, tree size)
12190 {
12191   tree fn;
12192   const char *p;
12193
12194   if (!validate_arg (dest, POINTER_TYPE)
12195       || !validate_arg (src, POINTER_TYPE)
12196       || !validate_arg (size, INTEGER_TYPE)
12197       || !validate_arg (size, INTEGER_TYPE))
12198     return NULL_TREE;
12199
12200   p = c_getstr (src);
12201   /* If the SRC parameter is "" or if LEN is 0, return DEST.  */
12202   if (p && *p == '\0')
12203     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, len);
12204   else if (integer_zerop (len))
12205     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
12206
12207   if (! host_integerp (size, 1))
12208     return NULL_TREE;
12209
12210   if (! integer_all_onesp (size))
12211     {
12212       tree src_len = c_strlen (src, 1);
12213       if (src_len
12214           && host_integerp (src_len, 1)
12215           && host_integerp (len, 1)
12216           && ! tree_int_cst_lt (len, src_len))
12217         {
12218           /* If LEN >= strlen (SRC), optimize into __strcat_chk.  */
12219           fn = built_in_decls[BUILT_IN_STRCAT_CHK];
12220           if (!fn)
12221             return NULL_TREE;
12222
12223           return build_call_expr_loc (loc, fn, 3, dest, src, size);
12224         }
12225       return NULL_TREE;
12226     }
12227
12228   /* If __builtin_strncat_chk is used, assume strncat is available.  */
12229   fn = built_in_decls[BUILT_IN_STRNCAT];
12230   if (!fn)
12231     return NULL_TREE;
12232
12233   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12234 }
12235
12236 /* Fold a call EXP to __{,v}sprintf_chk having NARGS passed as ARGS.
12237    Return NULL_TREE if a normal call should be emitted rather than
12238    expanding the function inline.  FCODE is either BUILT_IN_SPRINTF_CHK
12239    or BUILT_IN_VSPRINTF_CHK.  */
12240
12241 static tree
12242 fold_builtin_sprintf_chk_1 (location_t loc, int nargs, tree *args,
12243                             enum built_in_function fcode)
12244 {
12245   tree dest, size, len, fn, fmt, flag;
12246   const char *fmt_str;
12247
12248   /* Verify the required arguments in the original call.  */
12249   if (nargs < 4)
12250     return NULL_TREE;
12251   dest = args[0];
12252   if (!validate_arg (dest, POINTER_TYPE))
12253     return NULL_TREE;
12254   flag = args[1];
12255   if (!validate_arg (flag, INTEGER_TYPE))
12256     return NULL_TREE;
12257   size = args[2];
12258   if (!validate_arg (size, INTEGER_TYPE))
12259     return NULL_TREE;
12260   fmt = args[3];
12261   if (!validate_arg (fmt, POINTER_TYPE))
12262     return NULL_TREE;
12263
12264   if (! host_integerp (size, 1))
12265     return NULL_TREE;
12266
12267   len = NULL_TREE;
12268
12269   if (!init_target_chars ())
12270     return NULL_TREE;
12271
12272   /* Check whether the format is a literal string constant.  */
12273   fmt_str = c_getstr (fmt);
12274   if (fmt_str != NULL)
12275     {
12276       /* If the format doesn't contain % args or %%, we know the size.  */
12277       if (strchr (fmt_str, target_percent) == 0)
12278         {
12279           if (fcode != BUILT_IN_SPRINTF_CHK || nargs == 4)
12280             len = build_int_cstu (size_type_node, strlen (fmt_str));
12281         }
12282       /* If the format is "%s" and first ... argument is a string literal,
12283          we know the size too.  */
12284       else if (fcode == BUILT_IN_SPRINTF_CHK
12285                && strcmp (fmt_str, target_percent_s) == 0)
12286         {
12287           tree arg;
12288
12289           if (nargs == 5)
12290             {
12291               arg = args[4];
12292               if (validate_arg (arg, POINTER_TYPE))
12293                 {
12294                   len = c_strlen (arg, 1);
12295                   if (! len || ! host_integerp (len, 1))
12296                     len = NULL_TREE;
12297                 }
12298             }
12299         }
12300     }
12301
12302   if (! integer_all_onesp (size))
12303     {
12304       if (! len || ! tree_int_cst_lt (len, size))
12305         return NULL_TREE;
12306     }
12307
12308   /* Only convert __{,v}sprintf_chk to {,v}sprintf if flag is 0
12309      or if format doesn't contain % chars or is "%s".  */
12310   if (! integer_zerop (flag))
12311     {
12312       if (fmt_str == NULL)
12313         return NULL_TREE;
12314       if (strchr (fmt_str, target_percent) != NULL
12315           && strcmp (fmt_str, target_percent_s))
12316         return NULL_TREE;
12317     }
12318
12319   /* If __builtin_{,v}sprintf_chk is used, assume {,v}sprintf is available.  */
12320   fn = built_in_decls[fcode == BUILT_IN_VSPRINTF_CHK
12321                       ? BUILT_IN_VSPRINTF : BUILT_IN_SPRINTF];
12322   if (!fn)
12323     return NULL_TREE;
12324
12325   return rewrite_call_expr_array (loc, nargs, args, 4, fn, 2, dest, fmt);
12326 }
12327
12328 /* Fold a call EXP to __{,v}sprintf_chk.  Return NULL_TREE if
12329    a normal call should be emitted rather than expanding the function
12330    inline.  FCODE is either BUILT_IN_SPRINTF_CHK or BUILT_IN_VSPRINTF_CHK.  */
12331
12332 static tree
12333 fold_builtin_sprintf_chk (location_t loc, tree exp,
12334                           enum built_in_function fcode)
12335 {
12336   return fold_builtin_sprintf_chk_1 (loc, call_expr_nargs (exp),
12337                                      CALL_EXPR_ARGP (exp), fcode);
12338 }
12339
12340 /* Fold a call EXP to {,v}snprintf having NARGS passed as ARGS.  Return
12341    NULL_TREE if a normal call should be emitted rather than expanding
12342    the function inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
12343    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
12344    passed as second argument.  */
12345
12346 static tree
12347 fold_builtin_snprintf_chk_1 (location_t loc, int nargs, tree *args,
12348                              tree maxlen, enum built_in_function fcode)
12349 {
12350   tree dest, size, len, fn, fmt, flag;
12351   const char *fmt_str;
12352
12353   /* Verify the required arguments in the original call.  */
12354   if (nargs < 5)
12355     return NULL_TREE;
12356   dest = args[0];
12357   if (!validate_arg (dest, POINTER_TYPE))
12358     return NULL_TREE;
12359   len = args[1];
12360   if (!validate_arg (len, INTEGER_TYPE))
12361     return NULL_TREE;
12362   flag = args[2];
12363   if (!validate_arg (flag, INTEGER_TYPE))
12364     return NULL_TREE;
12365   size = args[3];
12366   if (!validate_arg (size, INTEGER_TYPE))
12367     return NULL_TREE;
12368   fmt = args[4];
12369   if (!validate_arg (fmt, POINTER_TYPE))
12370     return NULL_TREE;
12371
12372   if (! host_integerp (size, 1))
12373     return NULL_TREE;
12374
12375   if (! integer_all_onesp (size))
12376     {
12377       if (! host_integerp (len, 1))
12378         {
12379           /* If LEN is not constant, try MAXLEN too.
12380              For MAXLEN only allow optimizing into non-_ocs function
12381              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12382           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12383             return NULL_TREE;
12384         }
12385       else
12386         maxlen = len;
12387
12388       if (tree_int_cst_lt (size, maxlen))
12389         return NULL_TREE;
12390     }
12391
12392   if (!init_target_chars ())
12393     return NULL_TREE;
12394
12395   /* Only convert __{,v}snprintf_chk to {,v}snprintf if flag is 0
12396      or if format doesn't contain % chars or is "%s".  */
12397   if (! integer_zerop (flag))
12398     {
12399       fmt_str = c_getstr (fmt);
12400       if (fmt_str == NULL)
12401         return NULL_TREE;
12402       if (strchr (fmt_str, target_percent) != NULL
12403           && strcmp (fmt_str, target_percent_s))
12404         return NULL_TREE;
12405     }
12406
12407   /* If __builtin_{,v}snprintf_chk is used, assume {,v}snprintf is
12408      available.  */
12409   fn = built_in_decls[fcode == BUILT_IN_VSNPRINTF_CHK
12410                       ? BUILT_IN_VSNPRINTF : BUILT_IN_SNPRINTF];
12411   if (!fn)
12412     return NULL_TREE;
12413
12414   return rewrite_call_expr_array (loc, nargs, args, 5, fn, 3, dest, len, fmt);
12415 }
12416
12417 /* Fold a call EXP to {,v}snprintf.  Return NULL_TREE if
12418    a normal call should be emitted rather than expanding the function
12419    inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
12420    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
12421    passed as second argument.  */
12422
12423 tree
12424 fold_builtin_snprintf_chk (location_t loc, tree exp, tree maxlen,
12425                            enum built_in_function fcode)
12426 {
12427   return fold_builtin_snprintf_chk_1 (loc, call_expr_nargs (exp),
12428                                       CALL_EXPR_ARGP (exp), maxlen, fcode);
12429 }
12430
12431 /* Fold a call to the {,v}printf{,_unlocked} and __{,v}printf_chk builtins.
12432    FMT and ARG are the arguments to the call; we don't fold cases with
12433    more than 2 arguments, and ARG may be null if this is a 1-argument case.
12434
12435    Return NULL_TREE if no simplification was possible, otherwise return the
12436    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
12437    code of the function to be simplified.  */
12438
12439 static tree
12440 fold_builtin_printf (location_t loc, tree fndecl, tree fmt,
12441                      tree arg, bool ignore,
12442                      enum built_in_function fcode)
12443 {
12444   tree fn_putchar, fn_puts, newarg, call = NULL_TREE;
12445   const char *fmt_str = NULL;
12446
12447   /* If the return value is used, don't do the transformation.  */
12448   if (! ignore)
12449     return NULL_TREE;
12450
12451   /* Verify the required arguments in the original call.  */
12452   if (!validate_arg (fmt, POINTER_TYPE))
12453     return NULL_TREE;
12454
12455   /* Check whether the format is a literal string constant.  */
12456   fmt_str = c_getstr (fmt);
12457   if (fmt_str == NULL)
12458     return NULL_TREE;
12459
12460   if (fcode == BUILT_IN_PRINTF_UNLOCKED)
12461     {
12462       /* If we're using an unlocked function, assume the other
12463          unlocked functions exist explicitly.  */
12464       fn_putchar = built_in_decls[BUILT_IN_PUTCHAR_UNLOCKED];
12465       fn_puts = built_in_decls[BUILT_IN_PUTS_UNLOCKED];
12466     }
12467   else
12468     {
12469       fn_putchar = implicit_built_in_decls[BUILT_IN_PUTCHAR];
12470       fn_puts = implicit_built_in_decls[BUILT_IN_PUTS];
12471     }
12472
12473   if (!init_target_chars ())
12474     return NULL_TREE;
12475
12476   if (strcmp (fmt_str, target_percent_s) == 0
12477       || strchr (fmt_str, target_percent) == NULL)
12478     {
12479       const char *str;
12480
12481       if (strcmp (fmt_str, target_percent_s) == 0)
12482         {
12483           if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
12484             return NULL_TREE;
12485
12486           if (!arg || !validate_arg (arg, POINTER_TYPE))
12487             return NULL_TREE;
12488
12489           str = c_getstr (arg);
12490           if (str == NULL)
12491             return NULL_TREE;
12492         }
12493       else
12494         {
12495           /* The format specifier doesn't contain any '%' characters.  */
12496           if (fcode != BUILT_IN_VPRINTF && fcode != BUILT_IN_VPRINTF_CHK
12497               && arg)
12498             return NULL_TREE;
12499           str = fmt_str;
12500         }
12501
12502       /* If the string was "", printf does nothing.  */
12503       if (str[0] == '\0')
12504         return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
12505
12506       /* If the string has length of 1, call putchar.  */
12507       if (str[1] == '\0')
12508         {
12509           /* Given printf("c"), (where c is any one character,)
12510              convert "c"[0] to an int and pass that to the replacement
12511              function.  */
12512           newarg = build_int_cst (integer_type_node, str[0]);
12513           if (fn_putchar)
12514             call = build_call_expr_loc (loc, fn_putchar, 1, newarg);
12515         }
12516       else
12517         {
12518           /* If the string was "string\n", call puts("string").  */
12519           size_t len = strlen (str);
12520           if ((unsigned char)str[len - 1] == target_newline
12521               && (size_t) (int) len == len
12522               && (int) len > 0)
12523             {
12524               char *newstr;
12525               tree offset_node, string_cst;
12526
12527               /* Create a NUL-terminated string that's one char shorter
12528                  than the original, stripping off the trailing '\n'.  */
12529               newarg = build_string_literal (len, str);
12530               string_cst = string_constant (newarg, &offset_node);
12531               gcc_checking_assert (string_cst
12532                                    && (TREE_STRING_LENGTH (string_cst)
12533                                        == (int) len)
12534                                    && integer_zerop (offset_node)
12535                                    && (unsigned char)
12536                                       TREE_STRING_POINTER (string_cst)[len - 1]
12537                                       == target_newline);
12538               /* build_string_literal creates a new STRING_CST,
12539                  modify it in place to avoid double copying.  */
12540               newstr = CONST_CAST (char *, TREE_STRING_POINTER (string_cst));
12541               newstr[len - 1] = '\0';
12542               if (fn_puts)
12543                 call = build_call_expr_loc (loc, fn_puts, 1, newarg);
12544             }
12545           else
12546             /* We'd like to arrange to call fputs(string,stdout) here,
12547                but we need stdout and don't have a way to get it yet.  */
12548             return NULL_TREE;
12549         }
12550     }
12551
12552   /* The other optimizations can be done only on the non-va_list variants.  */
12553   else if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
12554     return NULL_TREE;
12555
12556   /* If the format specifier was "%s\n", call __builtin_puts(arg).  */
12557   else if (strcmp (fmt_str, target_percent_s_newline) == 0)
12558     {
12559       if (!arg || !validate_arg (arg, POINTER_TYPE))
12560         return NULL_TREE;
12561       if (fn_puts)
12562         call = build_call_expr_loc (loc, fn_puts, 1, arg);
12563     }
12564
12565   /* If the format specifier was "%c", call __builtin_putchar(arg).  */
12566   else if (strcmp (fmt_str, target_percent_c) == 0)
12567     {
12568       if (!arg || !validate_arg (arg, INTEGER_TYPE))
12569         return NULL_TREE;
12570       if (fn_putchar)
12571         call = build_call_expr_loc (loc, fn_putchar, 1, arg);
12572     }
12573
12574   if (!call)
12575     return NULL_TREE;
12576
12577   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), call);
12578 }
12579
12580 /* Fold a call to the {,v}fprintf{,_unlocked} and __{,v}printf_chk builtins.
12581    FP, FMT, and ARG are the arguments to the call.  We don't fold calls with
12582    more than 3 arguments, and ARG may be null in the 2-argument case.
12583
12584    Return NULL_TREE if no simplification was possible, otherwise return the
12585    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
12586    code of the function to be simplified.  */
12587
12588 static tree
12589 fold_builtin_fprintf (location_t loc, tree fndecl, tree fp,
12590                       tree fmt, tree arg, bool ignore,
12591                       enum built_in_function fcode)
12592 {
12593   tree fn_fputc, fn_fputs, call = NULL_TREE;
12594   const char *fmt_str = NULL;
12595
12596   /* If the return value is used, don't do the transformation.  */
12597   if (! ignore)
12598     return NULL_TREE;
12599
12600   /* Verify the required arguments in the original call.  */
12601   if (!validate_arg (fp, POINTER_TYPE))
12602     return NULL_TREE;
12603   if (!validate_arg (fmt, POINTER_TYPE))
12604     return NULL_TREE;
12605
12606   /* Check whether the format is a literal string constant.  */
12607   fmt_str = c_getstr (fmt);
12608   if (fmt_str == NULL)
12609     return NULL_TREE;
12610
12611   if (fcode == BUILT_IN_FPRINTF_UNLOCKED)
12612     {
12613       /* If we're using an unlocked function, assume the other
12614          unlocked functions exist explicitly.  */
12615       fn_fputc = built_in_decls[BUILT_IN_FPUTC_UNLOCKED];
12616       fn_fputs = built_in_decls[BUILT_IN_FPUTS_UNLOCKED];
12617     }
12618   else
12619     {
12620       fn_fputc = implicit_built_in_decls[BUILT_IN_FPUTC];
12621       fn_fputs = implicit_built_in_decls[BUILT_IN_FPUTS];
12622     }
12623
12624   if (!init_target_chars ())
12625     return NULL_TREE;
12626
12627   /* If the format doesn't contain % args or %%, use strcpy.  */
12628   if (strchr (fmt_str, target_percent) == NULL)
12629     {
12630       if (fcode != BUILT_IN_VFPRINTF && fcode != BUILT_IN_VFPRINTF_CHK
12631           && arg)
12632         return NULL_TREE;
12633
12634       /* If the format specifier was "", fprintf does nothing.  */
12635       if (fmt_str[0] == '\0')
12636         {
12637           /* If FP has side-effects, just wait until gimplification is
12638              done.  */
12639           if (TREE_SIDE_EFFECTS (fp))
12640             return NULL_TREE;
12641
12642           return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
12643         }
12644
12645       /* When "string" doesn't contain %, replace all cases of
12646          fprintf (fp, string) with fputs (string, fp).  The fputs
12647          builtin will take care of special cases like length == 1.  */
12648       if (fn_fputs)
12649         call = build_call_expr_loc (loc, fn_fputs, 2, fmt, fp);
12650     }
12651
12652   /* The other optimizations can be done only on the non-va_list variants.  */
12653   else if (fcode == BUILT_IN_VFPRINTF || fcode == BUILT_IN_VFPRINTF_CHK)
12654     return NULL_TREE;
12655
12656   /* If the format specifier was "%s", call __builtin_fputs (arg, fp).  */
12657   else if (strcmp (fmt_str, target_percent_s) == 0)
12658     {
12659       if (!arg || !validate_arg (arg, POINTER_TYPE))
12660         return NULL_TREE;
12661       if (fn_fputs)
12662         call = build_call_expr_loc (loc, fn_fputs, 2, arg, fp);
12663     }
12664
12665   /* If the format specifier was "%c", call __builtin_fputc (arg, fp).  */
12666   else if (strcmp (fmt_str, target_percent_c) == 0)
12667     {
12668       if (!arg || !validate_arg (arg, INTEGER_TYPE))
12669         return NULL_TREE;
12670       if (fn_fputc)
12671         call = build_call_expr_loc (loc, fn_fputc, 2, arg, fp);
12672     }
12673
12674   if (!call)
12675     return NULL_TREE;
12676   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), call);
12677 }
12678
12679 /* Initialize format string characters in the target charset.  */
12680
12681 static bool
12682 init_target_chars (void)
12683 {
12684   static bool init;
12685   if (!init)
12686     {
12687       target_newline = lang_hooks.to_target_charset ('\n');
12688       target_percent = lang_hooks.to_target_charset ('%');
12689       target_c = lang_hooks.to_target_charset ('c');
12690       target_s = lang_hooks.to_target_charset ('s');
12691       if (target_newline == 0 || target_percent == 0 || target_c == 0
12692           || target_s == 0)
12693         return false;
12694
12695       target_percent_c[0] = target_percent;
12696       target_percent_c[1] = target_c;
12697       target_percent_c[2] = '\0';
12698
12699       target_percent_s[0] = target_percent;
12700       target_percent_s[1] = target_s;
12701       target_percent_s[2] = '\0';
12702
12703       target_percent_s_newline[0] = target_percent;
12704       target_percent_s_newline[1] = target_s;
12705       target_percent_s_newline[2] = target_newline;
12706       target_percent_s_newline[3] = '\0';
12707
12708       init = true;
12709     }
12710   return true;
12711 }
12712
12713 /* Helper function for do_mpfr_arg*().  Ensure M is a normal number
12714    and no overflow/underflow occurred.  INEXACT is true if M was not
12715    exactly calculated.  TYPE is the tree type for the result.  This
12716    function assumes that you cleared the MPFR flags and then
12717    calculated M to see if anything subsequently set a flag prior to
12718    entering this function.  Return NULL_TREE if any checks fail.  */
12719
12720 static tree
12721 do_mpfr_ckconv (mpfr_srcptr m, tree type, int inexact)
12722 {
12723   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
12724      overflow/underflow occurred.  If -frounding-math, proceed iff the
12725      result of calling FUNC was exact.  */
12726   if (mpfr_number_p (m) && !mpfr_overflow_p () && !mpfr_underflow_p ()
12727       && (!flag_rounding_math || !inexact))
12728     {
12729       REAL_VALUE_TYPE rr;
12730
12731       real_from_mpfr (&rr, m, type, GMP_RNDN);
12732       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR value,
12733          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
12734          but the mpft_t is not, then we underflowed in the
12735          conversion.  */
12736       if (real_isfinite (&rr)
12737           && (rr.cl == rvc_zero) == (mpfr_zero_p (m) != 0))
12738         {
12739           REAL_VALUE_TYPE rmode;
12740
12741           real_convert (&rmode, TYPE_MODE (type), &rr);
12742           /* Proceed iff the specified mode can hold the value.  */
12743           if (real_identical (&rmode, &rr))
12744             return build_real (type, rmode);
12745         }
12746     }
12747   return NULL_TREE;
12748 }
12749
12750 /* Helper function for do_mpc_arg*().  Ensure M is a normal complex
12751    number and no overflow/underflow occurred.  INEXACT is true if M
12752    was not exactly calculated.  TYPE is the tree type for the result.
12753    This function assumes that you cleared the MPFR flags and then
12754    calculated M to see if anything subsequently set a flag prior to
12755    entering this function.  Return NULL_TREE if any checks fail, if
12756    FORCE_CONVERT is true, then bypass the checks.  */
12757
12758 static tree
12759 do_mpc_ckconv (mpc_srcptr m, tree type, int inexact, int force_convert)
12760 {
12761   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
12762      overflow/underflow occurred.  If -frounding-math, proceed iff the
12763      result of calling FUNC was exact.  */
12764   if (force_convert
12765       || (mpfr_number_p (mpc_realref (m)) && mpfr_number_p (mpc_imagref (m))
12766           && !mpfr_overflow_p () && !mpfr_underflow_p ()
12767           && (!flag_rounding_math || !inexact)))
12768     {
12769       REAL_VALUE_TYPE re, im;
12770
12771       real_from_mpfr (&re, mpc_realref (m), TREE_TYPE (type), GMP_RNDN);
12772       real_from_mpfr (&im, mpc_imagref (m), TREE_TYPE (type), GMP_RNDN);
12773       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR values,
12774          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
12775          but the mpft_t is not, then we underflowed in the
12776          conversion.  */
12777       if (force_convert
12778           || (real_isfinite (&re) && real_isfinite (&im)
12779               && (re.cl == rvc_zero) == (mpfr_zero_p (mpc_realref (m)) != 0)
12780               && (im.cl == rvc_zero) == (mpfr_zero_p (mpc_imagref (m)) != 0)))
12781         {
12782           REAL_VALUE_TYPE re_mode, im_mode;
12783
12784           real_convert (&re_mode, TYPE_MODE (TREE_TYPE (type)), &re);
12785           real_convert (&im_mode, TYPE_MODE (TREE_TYPE (type)), &im);
12786           /* Proceed iff the specified mode can hold the value.  */
12787           if (force_convert
12788               || (real_identical (&re_mode, &re)
12789                   && real_identical (&im_mode, &im)))
12790             return build_complex (type, build_real (TREE_TYPE (type), re_mode),
12791                                   build_real (TREE_TYPE (type), im_mode));
12792         }
12793     }
12794   return NULL_TREE;
12795 }
12796
12797 /* If argument ARG is a REAL_CST, call the one-argument mpfr function
12798    FUNC on it and return the resulting value as a tree with type TYPE.
12799    If MIN and/or MAX are not NULL, then the supplied ARG must be
12800    within those bounds.  If INCLUSIVE is true, then MIN/MAX are
12801    acceptable values, otherwise they are not.  The mpfr precision is
12802    set to the precision of TYPE.  We assume that function FUNC returns
12803    zero if the result could be calculated exactly within the requested
12804    precision.  */
12805
12806 static tree
12807 do_mpfr_arg1 (tree arg, tree type, int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t),
12808               const REAL_VALUE_TYPE *min, const REAL_VALUE_TYPE *max,
12809               bool inclusive)
12810 {
12811   tree result = NULL_TREE;
12812
12813   STRIP_NOPS (arg);
12814
12815   /* To proceed, MPFR must exactly represent the target floating point
12816      format, which only happens when the target base equals two.  */
12817   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
12818       && TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
12819     {
12820       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg);
12821
12822       if (real_isfinite (ra)
12823           && (!min || real_compare (inclusive ? GE_EXPR: GT_EXPR , ra, min))
12824           && (!max || real_compare (inclusive ? LE_EXPR: LT_EXPR , ra, max)))
12825         {
12826           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
12827           const int prec = fmt->p;
12828           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
12829           int inexact;
12830           mpfr_t m;
12831
12832           mpfr_init2 (m, prec);
12833           mpfr_from_real (m, ra, GMP_RNDN);
12834           mpfr_clear_flags ();
12835           inexact = func (m, m, rnd);
12836           result = do_mpfr_ckconv (m, type, inexact);
12837           mpfr_clear (m);
12838         }
12839     }
12840
12841   return result;
12842 }
12843
12844 /* If argument ARG is a REAL_CST, call the two-argument mpfr function
12845    FUNC on it and return the resulting value as a tree with type TYPE.
12846    The mpfr precision is set to the precision of TYPE.  We assume that
12847    function FUNC returns zero if the result could be calculated
12848    exactly within the requested precision.  */
12849
12850 static tree
12851 do_mpfr_arg2 (tree arg1, tree arg2, tree type,
12852               int (*func)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t))
12853 {
12854   tree result = NULL_TREE;
12855
12856   STRIP_NOPS (arg1);
12857   STRIP_NOPS (arg2);
12858
12859   /* To proceed, MPFR must exactly represent the target floating point
12860      format, which only happens when the target base equals two.  */
12861   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
12862       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1)
12863       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2))
12864     {
12865       const REAL_VALUE_TYPE *const ra1 = &TREE_REAL_CST (arg1);
12866       const REAL_VALUE_TYPE *const ra2 = &TREE_REAL_CST (arg2);
12867
12868       if (real_isfinite (ra1) && real_isfinite (ra2))
12869         {
12870           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
12871           const int prec = fmt->p;
12872           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
12873           int inexact;
12874           mpfr_t m1, m2;
12875
12876           mpfr_inits2 (prec, m1, m2, NULL);
12877           mpfr_from_real (m1, ra1, GMP_RNDN);
12878           mpfr_from_real (m2, ra2, GMP_RNDN);
12879           mpfr_clear_flags ();
12880           inexact = func (m1, m1, m2, rnd);
12881           result = do_mpfr_ckconv (m1, type, inexact);
12882           mpfr_clears (m1, m2, NULL);
12883         }
12884     }
12885
12886   return result;
12887 }
12888
12889 /* If argument ARG is a REAL_CST, call the three-argument mpfr function
12890    FUNC on it and return the resulting value as a tree with type TYPE.
12891    The mpfr precision is set to the precision of TYPE.  We assume that
12892    function FUNC returns zero if the result could be calculated
12893    exactly within the requested precision.  */
12894
12895 static tree
12896 do_mpfr_arg3 (tree arg1, tree arg2, tree arg3, tree type,
12897               int (*func)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t))
12898 {
12899   tree result = NULL_TREE;
12900
12901   STRIP_NOPS (arg1);
12902   STRIP_NOPS (arg2);
12903   STRIP_NOPS (arg3);
12904
12905   /* To proceed, MPFR must exactly represent the target floating point
12906      format, which only happens when the target base equals two.  */
12907   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
12908       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1)
12909       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2)
12910       && TREE_CODE (arg3) == REAL_CST && !TREE_OVERFLOW (arg3))
12911     {
12912       const REAL_VALUE_TYPE *const ra1 = &TREE_REAL_CST (arg1);
12913       const REAL_VALUE_TYPE *const ra2 = &TREE_REAL_CST (arg2);
12914       const REAL_VALUE_TYPE *const ra3 = &TREE_REAL_CST (arg3);
12915
12916       if (real_isfinite (ra1) && real_isfinite (ra2) && real_isfinite (ra3))
12917         {
12918           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
12919           const int prec = fmt->p;
12920           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
12921           int inexact;
12922           mpfr_t m1, m2, m3;
12923
12924           mpfr_inits2 (prec, m1, m2, m3, NULL);
12925           mpfr_from_real (m1, ra1, GMP_RNDN);
12926           mpfr_from_real (m2, ra2, GMP_RNDN);
12927           mpfr_from_real (m3, ra3, GMP_RNDN);
12928           mpfr_clear_flags ();
12929           inexact = func (m1, m1, m2, m3, rnd);
12930           result = do_mpfr_ckconv (m1, type, inexact);
12931           mpfr_clears (m1, m2, m3, NULL);
12932         }
12933     }
12934
12935   return result;
12936 }
12937
12938 /* If argument ARG is a REAL_CST, call mpfr_sin_cos() on it and set
12939    the pointers *(ARG_SINP) and *(ARG_COSP) to the resulting values.
12940    If ARG_SINP and ARG_COSP are NULL then the result is returned
12941    as a complex value.
12942    The type is taken from the type of ARG and is used for setting the
12943    precision of the calculation and results.  */
12944
12945 static tree
12946 do_mpfr_sincos (tree arg, tree arg_sinp, tree arg_cosp)
12947 {
12948   tree const type = TREE_TYPE (arg);
12949   tree result = NULL_TREE;
12950
12951   STRIP_NOPS (arg);
12952
12953   /* To proceed, MPFR must exactly represent the target floating point
12954      format, which only happens when the target base equals two.  */
12955   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
12956       && TREE_CODE (arg) == REAL_CST
12957       && !TREE_OVERFLOW (arg))
12958     {
12959       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg);
12960
12961       if (real_isfinite (ra))
12962         {
12963           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
12964           const int prec = fmt->p;
12965           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
12966           tree result_s, result_c;
12967           int inexact;
12968           mpfr_t m, ms, mc;
12969
12970           mpfr_inits2 (prec, m, ms, mc, NULL);
12971           mpfr_from_real (m, ra, GMP_RNDN);
12972           mpfr_clear_flags ();
12973           inexact = mpfr_sin_cos (ms, mc, m, rnd);
12974           result_s = do_mpfr_ckconv (ms, type, inexact);
12975           result_c = do_mpfr_ckconv (mc, type, inexact);
12976           mpfr_clears (m, ms, mc, NULL);
12977           if (result_s && result_c)
12978             {
12979               /* If we are to return in a complex value do so.  */
12980               if (!arg_sinp && !arg_cosp)
12981                 return build_complex (build_complex_type (type),
12982                                       result_c, result_s);
12983
12984               /* Dereference the sin/cos pointer arguments.  */
12985               arg_sinp = build_fold_indirect_ref (arg_sinp);
12986               arg_cosp = build_fold_indirect_ref (arg_cosp);
12987               /* Proceed if valid pointer type were passed in.  */
12988               if (TYPE_MAIN_VARIANT (TREE_TYPE (arg_sinp)) == TYPE_MAIN_VARIANT (type)
12989                   && TYPE_MAIN_VARIANT (TREE_TYPE (arg_cosp)) == TYPE_MAIN_VARIANT (type))
12990                 {
12991                   /* Set the values. */
12992                   result_s = fold_build2 (MODIFY_EXPR, type, arg_sinp,
12993                                           result_s);
12994                   TREE_SIDE_EFFECTS (result_s) = 1;
12995                   result_c = fold_build2 (MODIFY_EXPR, type, arg_cosp,
12996                                           result_c);
12997                   TREE_SIDE_EFFECTS (result_c) = 1;
12998                   /* Combine the assignments into a compound expr.  */
12999                   result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13000                                                     result_s, result_c));
13001                 }
13002             }
13003         }
13004     }
13005   return result;
13006 }
13007
13008 /* If argument ARG1 is an INTEGER_CST and ARG2 is a REAL_CST, call the
13009    two-argument mpfr order N Bessel function FUNC on them and return
13010    the resulting value as a tree with type TYPE.  The mpfr precision
13011    is set to the precision of TYPE.  We assume that function FUNC
13012    returns zero if the result could be calculated exactly within the
13013    requested precision.  */
13014 static tree
13015 do_mpfr_bessel_n (tree arg1, tree arg2, tree type,
13016                   int (*func)(mpfr_ptr, long, mpfr_srcptr, mp_rnd_t),
13017                   const REAL_VALUE_TYPE *min, bool inclusive)
13018 {
13019   tree result = NULL_TREE;
13020
13021   STRIP_NOPS (arg1);
13022   STRIP_NOPS (arg2);
13023
13024   /* To proceed, MPFR must exactly represent the target floating point
13025      format, which only happens when the target base equals two.  */
13026   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13027       && host_integerp (arg1, 0)
13028       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2))
13029     {
13030       const HOST_WIDE_INT n = tree_low_cst(arg1, 0);
13031       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg2);
13032
13033       if (n == (long)n
13034           && real_isfinite (ra)
13035           && (!min || real_compare (inclusive ? GE_EXPR: GT_EXPR , ra, min)))
13036         {
13037           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13038           const int prec = fmt->p;
13039           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13040           int inexact;
13041           mpfr_t m;
13042
13043           mpfr_init2 (m, prec);
13044           mpfr_from_real (m, ra, GMP_RNDN);
13045           mpfr_clear_flags ();
13046           inexact = func (m, n, m, rnd);
13047           result = do_mpfr_ckconv (m, type, inexact);
13048           mpfr_clear (m);
13049         }
13050     }
13051
13052   return result;
13053 }
13054
13055 /* If arguments ARG0 and ARG1 are REAL_CSTs, call mpfr_remquo() to set
13056    the pointer *(ARG_QUO) and return the result.  The type is taken
13057    from the type of ARG0 and is used for setting the precision of the
13058    calculation and results.  */
13059
13060 static tree
13061 do_mpfr_remquo (tree arg0, tree arg1, tree arg_quo)
13062 {
13063   tree const type = TREE_TYPE (arg0);
13064   tree result = NULL_TREE;
13065
13066   STRIP_NOPS (arg0);
13067   STRIP_NOPS (arg1);
13068
13069   /* To proceed, MPFR must exactly represent the target floating point
13070      format, which only happens when the target base equals two.  */
13071   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13072       && TREE_CODE (arg0) == REAL_CST && !TREE_OVERFLOW (arg0)
13073       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1))
13074     {
13075       const REAL_VALUE_TYPE *const ra0 = TREE_REAL_CST_PTR (arg0);
13076       const REAL_VALUE_TYPE *const ra1 = TREE_REAL_CST_PTR (arg1);
13077
13078       if (real_isfinite (ra0) && real_isfinite (ra1))
13079         {
13080           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13081           const int prec = fmt->p;
13082           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13083           tree result_rem;
13084           long integer_quo;
13085           mpfr_t m0, m1;
13086
13087           mpfr_inits2 (prec, m0, m1, NULL);
13088           mpfr_from_real (m0, ra0, GMP_RNDN);
13089           mpfr_from_real (m1, ra1, GMP_RNDN);
13090           mpfr_clear_flags ();
13091           mpfr_remquo (m0, &integer_quo, m0, m1, rnd);
13092           /* Remquo is independent of the rounding mode, so pass
13093              inexact=0 to do_mpfr_ckconv().  */
13094           result_rem = do_mpfr_ckconv (m0, type, /*inexact=*/ 0);
13095           mpfr_clears (m0, m1, NULL);
13096           if (result_rem)
13097             {
13098               /* MPFR calculates quo in the host's long so it may
13099                  return more bits in quo than the target int can hold
13100                  if sizeof(host long) > sizeof(target int).  This can
13101                  happen even for native compilers in LP64 mode.  In
13102                  these cases, modulo the quo value with the largest
13103                  number that the target int can hold while leaving one
13104                  bit for the sign.  */
13105               if (sizeof (integer_quo) * CHAR_BIT > INT_TYPE_SIZE)
13106                 integer_quo %= (long)(1UL << (INT_TYPE_SIZE - 1));
13107
13108               /* Dereference the quo pointer argument.  */
13109               arg_quo = build_fold_indirect_ref (arg_quo);
13110               /* Proceed iff a valid pointer type was passed in.  */
13111               if (TYPE_MAIN_VARIANT (TREE_TYPE (arg_quo)) == integer_type_node)
13112                 {
13113                   /* Set the value. */
13114                   tree result_quo
13115                     = fold_build2 (MODIFY_EXPR, TREE_TYPE (arg_quo), arg_quo,
13116                                    build_int_cst (TREE_TYPE (arg_quo),
13117                                                   integer_quo));
13118                   TREE_SIDE_EFFECTS (result_quo) = 1;
13119                   /* Combine the quo assignment with the rem.  */
13120                   result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13121                                                     result_quo, result_rem));
13122                 }
13123             }
13124         }
13125     }
13126   return result;
13127 }
13128
13129 /* If ARG is a REAL_CST, call mpfr_lgamma() on it and return the
13130    resulting value as a tree with type TYPE.  The mpfr precision is
13131    set to the precision of TYPE.  We assume that this mpfr function
13132    returns zero if the result could be calculated exactly within the
13133    requested precision.  In addition, the integer pointer represented
13134    by ARG_SG will be dereferenced and set to the appropriate signgam
13135    (-1,1) value.  */
13136
13137 static tree
13138 do_mpfr_lgamma_r (tree arg, tree arg_sg, tree type)
13139 {
13140   tree result = NULL_TREE;
13141
13142   STRIP_NOPS (arg);
13143
13144   /* To proceed, MPFR must exactly represent the target floating point
13145      format, which only happens when the target base equals two.  Also
13146      verify ARG is a constant and that ARG_SG is an int pointer.  */
13147   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13148       && TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg)
13149       && TREE_CODE (TREE_TYPE (arg_sg)) == POINTER_TYPE
13150       && TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (arg_sg))) == integer_type_node)
13151     {
13152       const REAL_VALUE_TYPE *const ra = TREE_REAL_CST_PTR (arg);
13153
13154       /* In addition to NaN and Inf, the argument cannot be zero or a
13155          negative integer.  */
13156       if (real_isfinite (ra)
13157           && ra->cl != rvc_zero
13158           && !(real_isneg(ra) && real_isinteger(ra, TYPE_MODE (type))))
13159         {
13160           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13161           const int prec = fmt->p;
13162           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13163           int inexact, sg;
13164           mpfr_t m;
13165           tree result_lg;
13166
13167           mpfr_init2 (m, prec);
13168           mpfr_from_real (m, ra, GMP_RNDN);
13169           mpfr_clear_flags ();
13170           inexact = mpfr_lgamma (m, &sg, m, rnd);
13171           result_lg = do_mpfr_ckconv (m, type, inexact);
13172           mpfr_clear (m);
13173           if (result_lg)
13174             {
13175               tree result_sg;
13176
13177               /* Dereference the arg_sg pointer argument.  */
13178               arg_sg = build_fold_indirect_ref (arg_sg);
13179               /* Assign the signgam value into *arg_sg. */
13180               result_sg = fold_build2 (MODIFY_EXPR,
13181                                        TREE_TYPE (arg_sg), arg_sg,
13182                                        build_int_cst (TREE_TYPE (arg_sg), sg));
13183               TREE_SIDE_EFFECTS (result_sg) = 1;
13184               /* Combine the signgam assignment with the lgamma result.  */
13185               result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13186                                                 result_sg, result_lg));
13187             }
13188         }
13189     }
13190
13191   return result;
13192 }
13193
13194 /* If argument ARG is a COMPLEX_CST, call the one-argument mpc
13195    function FUNC on it and return the resulting value as a tree with
13196    type TYPE.  The mpfr precision is set to the precision of TYPE.  We
13197    assume that function FUNC returns zero if the result could be
13198    calculated exactly within the requested precision.  */
13199
13200 static tree
13201 do_mpc_arg1 (tree arg, tree type, int (*func)(mpc_ptr, mpc_srcptr, mpc_rnd_t))
13202 {
13203   tree result = NULL_TREE;
13204
13205   STRIP_NOPS (arg);
13206
13207   /* To proceed, MPFR must exactly represent the target floating point
13208      format, which only happens when the target base equals two.  */
13209   if (TREE_CODE (arg) == COMPLEX_CST && !TREE_OVERFLOW (arg)
13210       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE
13211       && REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (TREE_TYPE (arg))))->b == 2)
13212     {
13213       const REAL_VALUE_TYPE *const re = TREE_REAL_CST_PTR (TREE_REALPART (arg));
13214       const REAL_VALUE_TYPE *const im = TREE_REAL_CST_PTR (TREE_IMAGPART (arg));
13215
13216       if (real_isfinite (re) && real_isfinite (im))
13217         {
13218           const struct real_format *const fmt =
13219             REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (type)));
13220           const int prec = fmt->p;
13221           const mp_rnd_t rnd = fmt->round_towards_zero ? GMP_RNDZ : GMP_RNDN;
13222           const mpc_rnd_t crnd = fmt->round_towards_zero ? MPC_RNDZZ : MPC_RNDNN;
13223           int inexact;
13224           mpc_t m;
13225
13226           mpc_init2 (m, prec);
13227           mpfr_from_real (mpc_realref(m), re, rnd);
13228           mpfr_from_real (mpc_imagref(m), im, rnd);
13229           mpfr_clear_flags ();
13230           inexact = func (m, m, crnd);
13231           result = do_mpc_ckconv (m, type, inexact, /*force_convert=*/ 0);
13232           mpc_clear (m);
13233         }
13234     }
13235
13236   return result;
13237 }
13238
13239 /* If arguments ARG0 and ARG1 are a COMPLEX_CST, call the two-argument
13240    mpc function FUNC on it and return the resulting value as a tree
13241    with type TYPE.  The mpfr precision is set to the precision of
13242    TYPE.  We assume that function FUNC returns zero if the result
13243    could be calculated exactly within the requested precision.  If
13244    DO_NONFINITE is true, then fold expressions containing Inf or NaN
13245    in the arguments and/or results.  */
13246
13247 tree
13248 do_mpc_arg2 (tree arg0, tree arg1, tree type, int do_nonfinite,
13249              int (*func)(mpc_ptr, mpc_srcptr, mpc_srcptr, mpc_rnd_t))
13250 {
13251   tree result = NULL_TREE;
13252
13253   STRIP_NOPS (arg0);
13254   STRIP_NOPS (arg1);
13255
13256   /* To proceed, MPFR must exactly represent the target floating point
13257      format, which only happens when the target base equals two.  */
13258   if (TREE_CODE (arg0) == COMPLEX_CST && !TREE_OVERFLOW (arg0)
13259       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE
13260       && TREE_CODE (arg1) == COMPLEX_CST && !TREE_OVERFLOW (arg1)
13261       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg1))) == REAL_TYPE
13262       && REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (TREE_TYPE (arg0))))->b == 2)
13263     {
13264       const REAL_VALUE_TYPE *const re0 = TREE_REAL_CST_PTR (TREE_REALPART (arg0));
13265       const REAL_VALUE_TYPE *const im0 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg0));
13266       const REAL_VALUE_TYPE *const re1 = TREE_REAL_CST_PTR (TREE_REALPART (arg1));
13267       const REAL_VALUE_TYPE *const im1 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg1));
13268
13269       if (do_nonfinite
13270           || (real_isfinite (re0) && real_isfinite (im0)
13271               && real_isfinite (re1) && real_isfinite (im1)))
13272         {
13273           const struct real_format *const fmt =
13274             REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (type)));
13275           const int prec = fmt->p;
13276           const mp_rnd_t rnd = fmt->round_towards_zero ? GMP_RNDZ : GMP_RNDN;
13277           const mpc_rnd_t crnd = fmt->round_towards_zero ? MPC_RNDZZ : MPC_RNDNN;
13278           int inexact;
13279           mpc_t m0, m1;
13280
13281           mpc_init2 (m0, prec);
13282           mpc_init2 (m1, prec);
13283           mpfr_from_real (mpc_realref(m0), re0, rnd);
13284           mpfr_from_real (mpc_imagref(m0), im0, rnd);
13285           mpfr_from_real (mpc_realref(m1), re1, rnd);
13286           mpfr_from_real (mpc_imagref(m1), im1, rnd);
13287           mpfr_clear_flags ();
13288           inexact = func (m0, m0, m1, crnd);
13289           result = do_mpc_ckconv (m0, type, inexact, do_nonfinite);
13290           mpc_clear (m0);
13291           mpc_clear (m1);
13292         }
13293     }
13294
13295   return result;
13296 }
13297
13298 /* Fold a call STMT to __{,v}sprintf_chk.  Return NULL_TREE if
13299    a normal call should be emitted rather than expanding the function
13300    inline.  FCODE is either BUILT_IN_SPRINTF_CHK or BUILT_IN_VSPRINTF_CHK.  */
13301
13302 static tree
13303 gimple_fold_builtin_sprintf_chk (gimple stmt, enum built_in_function fcode)
13304 {
13305   int nargs = gimple_call_num_args (stmt);
13306
13307   return fold_builtin_sprintf_chk_1 (gimple_location (stmt), nargs,
13308                                      (nargs > 0
13309                                       ? gimple_call_arg_ptr (stmt, 0)
13310                                       : &error_mark_node), fcode);
13311 }
13312
13313 /* Fold a call STMT to {,v}snprintf.  Return NULL_TREE if
13314    a normal call should be emitted rather than expanding the function
13315    inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
13316    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
13317    passed as second argument.  */
13318
13319 tree
13320 gimple_fold_builtin_snprintf_chk (gimple stmt, tree maxlen,
13321                                   enum built_in_function fcode)
13322 {
13323   int nargs = gimple_call_num_args (stmt);
13324
13325   return fold_builtin_snprintf_chk_1 (gimple_location (stmt), nargs,
13326                                       (nargs > 0
13327                                        ? gimple_call_arg_ptr (stmt, 0)
13328                                        : &error_mark_node), maxlen, fcode);
13329 }
13330
13331 /* Builtins with folding operations that operate on "..." arguments
13332    need special handling; we need to store the arguments in a convenient
13333    data structure before attempting any folding.  Fortunately there are
13334    only a few builtins that fall into this category.  FNDECL is the
13335    function, EXP is the CALL_EXPR for the call, and IGNORE is true if the
13336    result of the function call is ignored.  */
13337
13338 static tree
13339 gimple_fold_builtin_varargs (tree fndecl, gimple stmt,
13340                              bool ignore ATTRIBUTE_UNUSED)
13341 {
13342   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
13343   tree ret = NULL_TREE;
13344
13345   switch (fcode)
13346     {
13347     case BUILT_IN_SPRINTF_CHK:
13348     case BUILT_IN_VSPRINTF_CHK:
13349       ret = gimple_fold_builtin_sprintf_chk (stmt, fcode);
13350       break;
13351
13352     case BUILT_IN_SNPRINTF_CHK:
13353     case BUILT_IN_VSNPRINTF_CHK:
13354       ret = gimple_fold_builtin_snprintf_chk (stmt, NULL_TREE, fcode);
13355
13356     default:
13357       break;
13358     }
13359   if (ret)
13360     {
13361       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
13362       TREE_NO_WARNING (ret) = 1;
13363       return ret;
13364     }
13365   return NULL_TREE;
13366 }
13367
13368 /* A wrapper function for builtin folding that prevents warnings for
13369    "statement without effect" and the like, caused by removing the
13370    call node earlier than the warning is generated.  */
13371
13372 tree
13373 fold_call_stmt (gimple stmt, bool ignore)
13374 {
13375   tree ret = NULL_TREE;
13376   tree fndecl = gimple_call_fndecl (stmt);
13377   location_t loc = gimple_location (stmt);
13378   if (fndecl
13379       && TREE_CODE (fndecl) == FUNCTION_DECL
13380       && DECL_BUILT_IN (fndecl)
13381       && !gimple_call_va_arg_pack_p (stmt))
13382     {
13383       int nargs = gimple_call_num_args (stmt);
13384       tree *args = (nargs > 0
13385                     ? gimple_call_arg_ptr (stmt, 0)
13386                     : &error_mark_node);
13387
13388       if (avoid_folding_inline_builtin (fndecl))
13389         return NULL_TREE;
13390       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
13391         {
13392           return targetm.fold_builtin (fndecl, nargs, args, ignore);
13393         }
13394       else
13395         {
13396           if (nargs <= MAX_ARGS_TO_FOLD_BUILTIN)
13397             ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
13398           if (!ret)
13399             ret = gimple_fold_builtin_varargs (fndecl, stmt, ignore);
13400           if (ret)
13401             {
13402               /* Propagate location information from original call to
13403                  expansion of builtin.  Otherwise things like
13404                  maybe_emit_chk_warning, that operate on the expansion
13405                  of a builtin, will use the wrong location information.  */
13406               if (gimple_has_location (stmt))
13407                 {
13408                   tree realret = ret;
13409                   if (TREE_CODE (ret) == NOP_EXPR)
13410                     realret = TREE_OPERAND (ret, 0);
13411                   if (CAN_HAVE_LOCATION_P (realret)
13412                       && !EXPR_HAS_LOCATION (realret))
13413                     SET_EXPR_LOCATION (realret, loc);
13414                   return realret;
13415                 }
13416               return ret;
13417             }
13418         }
13419     }
13420   return NULL_TREE;
13421 }
13422
13423 /* Look up the function in built_in_decls that corresponds to DECL
13424    and set ASMSPEC as its user assembler name.  DECL must be a
13425    function decl that declares a builtin.  */
13426
13427 void
13428 set_builtin_user_assembler_name (tree decl, const char *asmspec)
13429 {
13430   tree builtin;
13431   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
13432               && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
13433               && asmspec != 0);
13434
13435   builtin = built_in_decls [DECL_FUNCTION_CODE (decl)];
13436   set_user_assembler_name (builtin, asmspec);
13437   switch (DECL_FUNCTION_CODE (decl))
13438     {
13439     case BUILT_IN_MEMCPY:
13440       init_block_move_fn (asmspec);
13441       memcpy_libfunc = set_user_assembler_libfunc ("memcpy", asmspec);
13442       break;
13443     case BUILT_IN_MEMSET:
13444       init_block_clear_fn (asmspec);
13445       memset_libfunc = set_user_assembler_libfunc ("memset", asmspec);
13446       break;
13447     case BUILT_IN_MEMMOVE:
13448       memmove_libfunc = set_user_assembler_libfunc ("memmove", asmspec);
13449       break;
13450     case BUILT_IN_MEMCMP:
13451       memcmp_libfunc = set_user_assembler_libfunc ("memcmp", asmspec);
13452       break;
13453     case BUILT_IN_ABORT:
13454       abort_libfunc = set_user_assembler_libfunc ("abort", asmspec);
13455       break;
13456     case BUILT_IN_FFS:
13457       if (INT_TYPE_SIZE < BITS_PER_WORD)
13458         {
13459           set_user_assembler_libfunc ("ffs", asmspec);
13460           set_optab_libfunc (ffs_optab, mode_for_size (INT_TYPE_SIZE,
13461                                                        MODE_INT, 0), "ffs");
13462         }
13463       break;
13464     default:
13465       break;
13466     }
13467 }
13468
13469 /* Return true if DECL is a builtin that expands to a constant or similarly
13470    simple code.  */
13471 bool
13472 is_simple_builtin (tree decl)
13473 {
13474   if (decl && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
13475     switch (DECL_FUNCTION_CODE (decl))
13476       {
13477         /* Builtins that expand to constants.  */
13478       case BUILT_IN_CONSTANT_P:
13479       case BUILT_IN_EXPECT:
13480       case BUILT_IN_OBJECT_SIZE:
13481       case BUILT_IN_UNREACHABLE:
13482         /* Simple register moves or loads from stack.  */
13483       case BUILT_IN_ASSUME_ALIGNED:
13484       case BUILT_IN_RETURN_ADDRESS:
13485       case BUILT_IN_EXTRACT_RETURN_ADDR:
13486       case BUILT_IN_FROB_RETURN_ADDR:
13487       case BUILT_IN_RETURN:
13488       case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
13489       case BUILT_IN_FRAME_ADDRESS:
13490       case BUILT_IN_VA_END:
13491       case BUILT_IN_STACK_SAVE:
13492       case BUILT_IN_STACK_RESTORE:
13493         /* Exception state returns or moves registers around.  */
13494       case BUILT_IN_EH_FILTER:
13495       case BUILT_IN_EH_POINTER:
13496       case BUILT_IN_EH_COPY_VALUES:
13497         return true;
13498
13499       default:
13500         return false;
13501       }
13502
13503   return false;
13504 }
13505
13506 /* Return true if DECL is a builtin that is not expensive, i.e., they are
13507    most probably expanded inline into reasonably simple code.  This is a
13508    superset of is_simple_builtin.  */
13509 bool
13510 is_inexpensive_builtin (tree decl)
13511 {
13512   if (!decl)
13513     return false;
13514   else if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_MD)
13515     return true;
13516   else if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
13517     switch (DECL_FUNCTION_CODE (decl))
13518       {
13519       case BUILT_IN_ABS:
13520       case BUILT_IN_ALLOCA:
13521       case BUILT_IN_BSWAP32:
13522       case BUILT_IN_BSWAP64:
13523       case BUILT_IN_CLZ:
13524       case BUILT_IN_CLZIMAX:
13525       case BUILT_IN_CLZL:
13526       case BUILT_IN_CLZLL:
13527       case BUILT_IN_CTZ:
13528       case BUILT_IN_CTZIMAX:
13529       case BUILT_IN_CTZL:
13530       case BUILT_IN_CTZLL:
13531       case BUILT_IN_FFS:
13532       case BUILT_IN_FFSIMAX:
13533       case BUILT_IN_FFSL:
13534       case BUILT_IN_FFSLL:
13535       case BUILT_IN_IMAXABS:
13536       case BUILT_IN_FINITE:
13537       case BUILT_IN_FINITEF:
13538       case BUILT_IN_FINITEL:
13539       case BUILT_IN_FINITED32:
13540       case BUILT_IN_FINITED64:
13541       case BUILT_IN_FINITED128:
13542       case BUILT_IN_FPCLASSIFY:
13543       case BUILT_IN_ISFINITE:
13544       case BUILT_IN_ISINF_SIGN:
13545       case BUILT_IN_ISINF:
13546       case BUILT_IN_ISINFF:
13547       case BUILT_IN_ISINFL:
13548       case BUILT_IN_ISINFD32:
13549       case BUILT_IN_ISINFD64:
13550       case BUILT_IN_ISINFD128:
13551       case BUILT_IN_ISNAN:
13552       case BUILT_IN_ISNANF:
13553       case BUILT_IN_ISNANL:
13554       case BUILT_IN_ISNAND32:
13555       case BUILT_IN_ISNAND64:
13556       case BUILT_IN_ISNAND128:
13557       case BUILT_IN_ISNORMAL:
13558       case BUILT_IN_ISGREATER:
13559       case BUILT_IN_ISGREATEREQUAL:
13560       case BUILT_IN_ISLESS:
13561       case BUILT_IN_ISLESSEQUAL:
13562       case BUILT_IN_ISLESSGREATER:
13563       case BUILT_IN_ISUNORDERED:
13564       case BUILT_IN_VA_ARG_PACK:
13565       case BUILT_IN_VA_ARG_PACK_LEN:
13566       case BUILT_IN_VA_COPY:
13567       case BUILT_IN_TRAP:
13568       case BUILT_IN_SAVEREGS:
13569       case BUILT_IN_POPCOUNTL:
13570       case BUILT_IN_POPCOUNTLL:
13571       case BUILT_IN_POPCOUNTIMAX:
13572       case BUILT_IN_POPCOUNT:
13573       case BUILT_IN_PARITYL:
13574       case BUILT_IN_PARITYLL:
13575       case BUILT_IN_PARITYIMAX:
13576       case BUILT_IN_PARITY:
13577       case BUILT_IN_LABS:
13578       case BUILT_IN_LLABS:
13579       case BUILT_IN_PREFETCH:
13580         return true;
13581
13582       default:
13583         return is_simple_builtin (decl);
13584       }
13585
13586   return false;
13587 }