Re-factor tree.h - Part 1.
[platform/upstream/gcc.git] / gcc / builtins.c
1 /* Expand builtin functions.
2    Copyright (C) 1988-2013 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
10
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3.  If not see
18 <http://www.gnu.org/licenses/>.  */
19
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "machmode.h"
25 #include "rtl.h"
26 #include "tree.h"
27 #include "realmpfr.h"
28 #include "gimple.h"
29 #include "flags.h"
30 #include "regs.h"
31 #include "hard-reg-set.h"
32 #include "except.h"
33 #include "function.h"
34 #include "insn-config.h"
35 #include "expr.h"
36 #include "optabs.h"
37 #include "libfuncs.h"
38 #include "recog.h"
39 #include "output.h"
40 #include "typeclass.h"
41 #include "predict.h"
42 #include "tm_p.h"
43 #include "target.h"
44 #include "langhooks.h"
45 #include "basic-block.h"
46 #include "tree-ssanames.h"
47 #include "tree-dfa.h"
48 #include "value-prof.h"
49 #include "diagnostic-core.h"
50 #include "builtins.h"
51 #include "ubsan.h"
52 #include "cilk.h"
53
54
55 static tree do_mpc_arg1 (tree, tree, int (*)(mpc_ptr, mpc_srcptr, mpc_rnd_t));
56
57 struct target_builtins default_target_builtins;
58 #if SWITCHABLE_TARGET
59 struct target_builtins *this_target_builtins = &default_target_builtins;
60 #endif
61
62 /* Define the names of the builtin function types and codes.  */
63 const char *const built_in_class_names[BUILT_IN_LAST]
64   = {"NOT_BUILT_IN", "BUILT_IN_FRONTEND", "BUILT_IN_MD", "BUILT_IN_NORMAL"};
65
66 #define DEF_BUILTIN(X, N, C, T, LT, B, F, NA, AT, IM, COND) #X,
67 const char * built_in_names[(int) END_BUILTINS] =
68 {
69 #include "builtins.def"
70 };
71 #undef DEF_BUILTIN
72
73 /* Setup an array of _DECL trees, make sure each element is
74    initialized to NULL_TREE.  */
75 builtin_info_type builtin_info;
76
77 /* Non-zero if __builtin_constant_p should be folded right away.  */
78 bool force_folding_builtin_constant_p;
79
80 static const char *c_getstr (tree);
81 static rtx c_readstr (const char *, enum machine_mode);
82 static int target_char_cast (tree, char *);
83 static rtx get_memory_rtx (tree, tree);
84 static int apply_args_size (void);
85 static int apply_result_size (void);
86 #if defined (HAVE_untyped_call) || defined (HAVE_untyped_return)
87 static rtx result_vector (int, rtx);
88 #endif
89 static void expand_builtin_update_setjmp_buf (rtx);
90 static void expand_builtin_prefetch (tree);
91 static rtx expand_builtin_apply_args (void);
92 static rtx expand_builtin_apply_args_1 (void);
93 static rtx expand_builtin_apply (rtx, rtx, rtx);
94 static void expand_builtin_return (rtx);
95 static enum type_class type_to_class (tree);
96 static rtx expand_builtin_classify_type (tree);
97 static void expand_errno_check (tree, rtx);
98 static rtx expand_builtin_mathfn (tree, rtx, rtx);
99 static rtx expand_builtin_mathfn_2 (tree, rtx, rtx);
100 static rtx expand_builtin_mathfn_3 (tree, rtx, rtx);
101 static rtx expand_builtin_mathfn_ternary (tree, rtx, rtx);
102 static rtx expand_builtin_interclass_mathfn (tree, rtx);
103 static rtx expand_builtin_sincos (tree);
104 static rtx expand_builtin_cexpi (tree, rtx);
105 static rtx expand_builtin_int_roundingfn (tree, rtx);
106 static rtx expand_builtin_int_roundingfn_2 (tree, rtx);
107 static rtx expand_builtin_next_arg (void);
108 static rtx expand_builtin_va_start (tree);
109 static rtx expand_builtin_va_end (tree);
110 static rtx expand_builtin_va_copy (tree);
111 static rtx expand_builtin_memcmp (tree, rtx, enum machine_mode);
112 static rtx expand_builtin_strcmp (tree, rtx);
113 static rtx expand_builtin_strncmp (tree, rtx, enum machine_mode);
114 static rtx builtin_memcpy_read_str (void *, HOST_WIDE_INT, enum machine_mode);
115 static rtx expand_builtin_memcpy (tree, rtx);
116 static rtx expand_builtin_mempcpy (tree, rtx, enum machine_mode);
117 static rtx expand_builtin_mempcpy_args (tree, tree, tree, rtx,
118                                         enum machine_mode, int);
119 static rtx expand_builtin_strcpy (tree, rtx);
120 static rtx expand_builtin_strcpy_args (tree, tree, rtx);
121 static rtx expand_builtin_stpcpy (tree, rtx, enum machine_mode);
122 static rtx expand_builtin_strncpy (tree, rtx);
123 static rtx builtin_memset_gen_str (void *, HOST_WIDE_INT, enum machine_mode);
124 static rtx expand_builtin_memset (tree, rtx, enum machine_mode);
125 static rtx expand_builtin_memset_args (tree, tree, tree, rtx, enum machine_mode, tree);
126 static rtx expand_builtin_bzero (tree);
127 static rtx expand_builtin_strlen (tree, rtx, enum machine_mode);
128 static rtx expand_builtin_alloca (tree, bool);
129 static rtx expand_builtin_unop (enum machine_mode, tree, rtx, rtx, optab);
130 static rtx expand_builtin_frame_address (tree, tree);
131 static tree stabilize_va_list_loc (location_t, tree, int);
132 static rtx expand_builtin_expect (tree, rtx);
133 static tree fold_builtin_constant_p (tree);
134 static tree fold_builtin_expect (location_t, tree, tree);
135 static tree fold_builtin_classify_type (tree);
136 static tree fold_builtin_strlen (location_t, tree, tree);
137 static tree fold_builtin_inf (location_t, tree, int);
138 static tree fold_builtin_nan (tree, tree, int);
139 static tree rewrite_call_expr (location_t, tree, int, tree, int, ...);
140 static bool validate_arg (const_tree, enum tree_code code);
141 static bool integer_valued_real_p (tree);
142 static tree fold_trunc_transparent_mathfn (location_t, tree, tree);
143 static bool readonly_data_expr (tree);
144 static rtx expand_builtin_fabs (tree, rtx, rtx);
145 static rtx expand_builtin_signbit (tree, rtx);
146 static tree fold_builtin_sqrt (location_t, tree, tree);
147 static tree fold_builtin_cbrt (location_t, tree, tree);
148 static tree fold_builtin_pow (location_t, tree, tree, tree, tree);
149 static tree fold_builtin_powi (location_t, tree, tree, tree, tree);
150 static tree fold_builtin_cos (location_t, tree, tree, tree);
151 static tree fold_builtin_cosh (location_t, tree, tree, tree);
152 static tree fold_builtin_tan (tree, tree);
153 static tree fold_builtin_trunc (location_t, tree, tree);
154 static tree fold_builtin_floor (location_t, tree, tree);
155 static tree fold_builtin_ceil (location_t, tree, tree);
156 static tree fold_builtin_round (location_t, tree, tree);
157 static tree fold_builtin_int_roundingfn (location_t, tree, tree);
158 static tree fold_builtin_bitop (tree, tree);
159 static tree fold_builtin_memory_op (location_t, tree, tree, tree, tree, bool, int);
160 static tree fold_builtin_strchr (location_t, tree, tree, tree);
161 static tree fold_builtin_memchr (location_t, tree, tree, tree, tree);
162 static tree fold_builtin_memcmp (location_t, tree, tree, tree);
163 static tree fold_builtin_strcmp (location_t, tree, tree);
164 static tree fold_builtin_strncmp (location_t, tree, tree, tree);
165 static tree fold_builtin_signbit (location_t, tree, tree);
166 static tree fold_builtin_copysign (location_t, tree, tree, tree, tree);
167 static tree fold_builtin_isascii (location_t, tree);
168 static tree fold_builtin_toascii (location_t, tree);
169 static tree fold_builtin_isdigit (location_t, tree);
170 static tree fold_builtin_fabs (location_t, tree, tree);
171 static tree fold_builtin_abs (location_t, tree, tree);
172 static tree fold_builtin_unordered_cmp (location_t, tree, tree, tree, enum tree_code,
173                                         enum tree_code);
174 static tree fold_builtin_n (location_t, tree, tree *, int, bool);
175 static tree fold_builtin_0 (location_t, tree, bool);
176 static tree fold_builtin_1 (location_t, tree, tree, bool);
177 static tree fold_builtin_2 (location_t, tree, tree, tree, bool);
178 static tree fold_builtin_3 (location_t, tree, tree, tree, tree, bool);
179 static tree fold_builtin_4 (location_t, tree, tree, tree, tree, tree, bool);
180 static tree fold_builtin_varargs (location_t, tree, tree, bool);
181
182 static tree fold_builtin_strpbrk (location_t, tree, tree, tree);
183 static tree fold_builtin_strstr (location_t, tree, tree, tree);
184 static tree fold_builtin_strrchr (location_t, tree, tree, tree);
185 static tree fold_builtin_strcat (location_t, tree, tree);
186 static tree fold_builtin_strncat (location_t, tree, tree, tree);
187 static tree fold_builtin_strspn (location_t, tree, tree);
188 static tree fold_builtin_strcspn (location_t, tree, tree);
189 static tree fold_builtin_sprintf (location_t, tree, tree, tree, int);
190 static tree fold_builtin_snprintf (location_t, tree, tree, tree, tree, int);
191
192 static rtx expand_builtin_object_size (tree);
193 static rtx expand_builtin_memory_chk (tree, rtx, enum machine_mode,
194                                       enum built_in_function);
195 static void maybe_emit_chk_warning (tree, enum built_in_function);
196 static void maybe_emit_sprintf_chk_warning (tree, enum built_in_function);
197 static void maybe_emit_free_warning (tree);
198 static tree fold_builtin_object_size (tree, tree);
199 static tree fold_builtin_strcat_chk (location_t, tree, tree, tree, tree);
200 static tree fold_builtin_strncat_chk (location_t, tree, tree, tree, tree, tree);
201 static tree fold_builtin_sprintf_chk (location_t, tree, enum built_in_function);
202 static tree fold_builtin_printf (location_t, tree, tree, tree, bool, enum built_in_function);
203 static tree fold_builtin_fprintf (location_t, tree, tree, tree, tree, bool,
204                                   enum built_in_function);
205 static bool init_target_chars (void);
206
207 static unsigned HOST_WIDE_INT target_newline;
208 static unsigned HOST_WIDE_INT target_percent;
209 static unsigned HOST_WIDE_INT target_c;
210 static unsigned HOST_WIDE_INT target_s;
211 static char target_percent_c[3];
212 static char target_percent_s[3];
213 static char target_percent_s_newline[4];
214 static tree do_mpfr_arg1 (tree, tree, int (*)(mpfr_ptr, mpfr_srcptr, mp_rnd_t),
215                           const REAL_VALUE_TYPE *, const REAL_VALUE_TYPE *, bool);
216 static tree do_mpfr_arg2 (tree, tree, tree,
217                           int (*)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t));
218 static tree do_mpfr_arg3 (tree, tree, tree, tree,
219                           int (*)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t));
220 static tree do_mpfr_sincos (tree, tree, tree);
221 static tree do_mpfr_bessel_n (tree, tree, tree,
222                               int (*)(mpfr_ptr, long, mpfr_srcptr, mp_rnd_t),
223                               const REAL_VALUE_TYPE *, bool);
224 static tree do_mpfr_remquo (tree, tree, tree);
225 static tree do_mpfr_lgamma_r (tree, tree, tree);
226 static void expand_builtin_sync_synchronize (void);
227
228 /* Return true if NAME starts with __builtin_ or __sync_.  */
229
230 static bool
231 is_builtin_name (const char *name)
232 {
233   if (strncmp (name, "__builtin_", 10) == 0)
234     return true;
235   if (strncmp (name, "__sync_", 7) == 0)
236     return true;
237   if (strncmp (name, "__atomic_", 9) == 0)
238     return true;
239   if (flag_enable_cilkplus 
240       && (!strcmp (name, "__cilkrts_detach")   
241           || !strcmp (name, "__cilkrts_pop_frame")))
242     return true;
243   return false;
244 }
245
246
247 /* Return true if DECL is a function symbol representing a built-in.  */
248
249 bool
250 is_builtin_fn (tree decl)
251 {
252   return TREE_CODE (decl) == FUNCTION_DECL && DECL_BUILT_IN (decl);
253 }
254
255 /* By default we assume that c99 functions are present at the runtime,
256    but sincos is not.  */
257 bool
258 default_libc_has_function (enum function_class fn_class)
259 {
260   if (fn_class == function_c94
261       || fn_class == function_c99_misc
262       || fn_class == function_c99_math_complex)
263     return true;
264
265   return false;
266 }
267
268 bool
269 gnu_libc_has_function (enum function_class fn_class ATTRIBUTE_UNUSED)
270 {
271   return true;
272 }
273
274 bool
275 no_c99_libc_has_function (enum function_class fn_class ATTRIBUTE_UNUSED)
276 {
277   return false;
278 }
279
280 /* Return true if NODE should be considered for inline expansion regardless
281    of the optimization level.  This means whenever a function is invoked with
282    its "internal" name, which normally contains the prefix "__builtin".  */
283
284 static bool
285 called_as_built_in (tree node)
286 {
287   /* Note that we must use DECL_NAME, not DECL_ASSEMBLER_NAME_SET_P since
288      we want the name used to call the function, not the name it
289      will have. */
290   const char *name = IDENTIFIER_POINTER (DECL_NAME (node));
291   return is_builtin_name (name);
292 }
293
294 /* Compute values M and N such that M divides (address of EXP - N) and such
295    that N < M.  If these numbers can be determined, store M in alignp and N in
296    *BITPOSP and return true.  Otherwise return false and store BITS_PER_UNIT to
297    *alignp and any bit-offset to *bitposp.
298
299    Note that the address (and thus the alignment) computed here is based
300    on the address to which a symbol resolves, whereas DECL_ALIGN is based
301    on the address at which an object is actually located.  These two
302    addresses are not always the same.  For example, on ARM targets,
303    the address &foo of a Thumb function foo() has the lowest bit set,
304    whereas foo() itself starts on an even address.
305
306    If ADDR_P is true we are taking the address of the memory reference EXP
307    and thus cannot rely on the access taking place.  */
308
309 static bool
310 get_object_alignment_2 (tree exp, unsigned int *alignp,
311                         unsigned HOST_WIDE_INT *bitposp, bool addr_p)
312 {
313   HOST_WIDE_INT bitsize, bitpos;
314   tree offset;
315   enum machine_mode mode;
316   int unsignedp, volatilep;
317   unsigned int align = BITS_PER_UNIT;
318   bool known_alignment = false;
319
320   /* Get the innermost object and the constant (bitpos) and possibly
321      variable (offset) offset of the access.  */
322   exp = get_inner_reference (exp, &bitsize, &bitpos, &offset,
323                              &mode, &unsignedp, &volatilep, true);
324
325   /* Extract alignment information from the innermost object and
326      possibly adjust bitpos and offset.  */
327   if (TREE_CODE (exp) == FUNCTION_DECL)
328     {
329       /* Function addresses can encode extra information besides their
330          alignment.  However, if TARGET_PTRMEMFUNC_VBIT_LOCATION
331          allows the low bit to be used as a virtual bit, we know
332          that the address itself must be at least 2-byte aligned.  */
333       if (TARGET_PTRMEMFUNC_VBIT_LOCATION == ptrmemfunc_vbit_in_pfn)
334         align = 2 * BITS_PER_UNIT;
335     }
336   else if (TREE_CODE (exp) == LABEL_DECL)
337     ;
338   else if (TREE_CODE (exp) == CONST_DECL)
339     {
340       /* The alignment of a CONST_DECL is determined by its initializer.  */
341       exp = DECL_INITIAL (exp);
342       align = TYPE_ALIGN (TREE_TYPE (exp));
343 #ifdef CONSTANT_ALIGNMENT
344       if (CONSTANT_CLASS_P (exp))
345         align = (unsigned) CONSTANT_ALIGNMENT (exp, align);
346 #endif
347       known_alignment = true;
348     }
349   else if (DECL_P (exp))
350     {
351       align = DECL_ALIGN (exp);
352       known_alignment = true;
353     }
354   else if (TREE_CODE (exp) == VIEW_CONVERT_EXPR)
355     {
356       align = TYPE_ALIGN (TREE_TYPE (exp));
357     }
358   else if (TREE_CODE (exp) == INDIRECT_REF
359            || TREE_CODE (exp) == MEM_REF
360            || TREE_CODE (exp) == TARGET_MEM_REF)
361     {
362       tree addr = TREE_OPERAND (exp, 0);
363       unsigned ptr_align;
364       unsigned HOST_WIDE_INT ptr_bitpos;
365
366       if (TREE_CODE (addr) == BIT_AND_EXPR
367           && TREE_CODE (TREE_OPERAND (addr, 1)) == INTEGER_CST)
368         {
369           align = (TREE_INT_CST_LOW (TREE_OPERAND (addr, 1))
370                     & -TREE_INT_CST_LOW (TREE_OPERAND (addr, 1)));
371           align *= BITS_PER_UNIT;
372           addr = TREE_OPERAND (addr, 0);
373         }
374
375       known_alignment
376         = get_pointer_alignment_1 (addr, &ptr_align, &ptr_bitpos);
377       align = MAX (ptr_align, align);
378
379       /* The alignment of the pointer operand in a TARGET_MEM_REF
380          has to take the variable offset parts into account.  */
381       if (TREE_CODE (exp) == TARGET_MEM_REF)
382         {
383           if (TMR_INDEX (exp))
384             {
385               unsigned HOST_WIDE_INT step = 1;
386               if (TMR_STEP (exp))
387                 step = TREE_INT_CST_LOW (TMR_STEP (exp));
388               align = MIN (align, (step & -step) * BITS_PER_UNIT);
389             }
390           if (TMR_INDEX2 (exp))
391             align = BITS_PER_UNIT;
392           known_alignment = false;
393         }
394
395       /* When EXP is an actual memory reference then we can use
396          TYPE_ALIGN of a pointer indirection to derive alignment.
397          Do so only if get_pointer_alignment_1 did not reveal absolute
398          alignment knowledge and if using that alignment would
399          improve the situation.  */
400       if (!addr_p && !known_alignment
401           && TYPE_ALIGN (TREE_TYPE (exp)) > align)
402         align = TYPE_ALIGN (TREE_TYPE (exp));
403       else
404         {
405           /* Else adjust bitpos accordingly.  */
406           bitpos += ptr_bitpos;
407           if (TREE_CODE (exp) == MEM_REF
408               || TREE_CODE (exp) == TARGET_MEM_REF)
409             bitpos += mem_ref_offset (exp).low * BITS_PER_UNIT;
410         }
411     }
412   else if (TREE_CODE (exp) == STRING_CST)
413     {
414       /* STRING_CST are the only constant objects we allow to be not
415          wrapped inside a CONST_DECL.  */
416       align = TYPE_ALIGN (TREE_TYPE (exp));
417 #ifdef CONSTANT_ALIGNMENT
418       if (CONSTANT_CLASS_P (exp))
419         align = (unsigned) CONSTANT_ALIGNMENT (exp, align);
420 #endif
421       known_alignment = true;
422     }
423
424   /* If there is a non-constant offset part extract the maximum
425      alignment that can prevail.  */
426   if (offset)
427     {
428       int trailing_zeros = tree_ctz (offset);
429       if (trailing_zeros < HOST_BITS_PER_INT)
430         {
431           unsigned int inner = (1U << trailing_zeros) * BITS_PER_UNIT;
432           if (inner)
433             align = MIN (align, inner);
434         }
435     }
436
437   *alignp = align;
438   *bitposp = bitpos & (*alignp - 1);
439   return known_alignment;
440 }
441
442 /* For a memory reference expression EXP compute values M and N such that M
443    divides (&EXP - N) and such that N < M.  If these numbers can be determined,
444    store M in alignp and N in *BITPOSP and return true.  Otherwise return false
445    and store BITS_PER_UNIT to *alignp and any bit-offset to *bitposp.  */
446
447 bool
448 get_object_alignment_1 (tree exp, unsigned int *alignp,
449                         unsigned HOST_WIDE_INT *bitposp)
450 {
451   return get_object_alignment_2 (exp, alignp, bitposp, false);
452 }
453
454 /* Return the alignment in bits of EXP, an object.  */
455
456 unsigned int
457 get_object_alignment (tree exp)
458 {
459   unsigned HOST_WIDE_INT bitpos = 0;
460   unsigned int align;
461
462   get_object_alignment_1 (exp, &align, &bitpos);
463
464   /* align and bitpos now specify known low bits of the pointer.
465      ptr & (align - 1) == bitpos.  */
466
467   if (bitpos != 0)
468     align = (bitpos & -bitpos);
469   return align;
470 }
471
472 /* For a pointer valued expression EXP compute values M and N such that M
473    divides (EXP - N) and such that N < M.  If these numbers can be determined,
474    store M in alignp and N in *BITPOSP and return true.  Return false if
475    the results are just a conservative approximation.
476
477    If EXP is not a pointer, false is returned too.  */
478
479 bool
480 get_pointer_alignment_1 (tree exp, unsigned int *alignp,
481                          unsigned HOST_WIDE_INT *bitposp)
482 {
483   STRIP_NOPS (exp);
484
485   if (TREE_CODE (exp) == ADDR_EXPR)
486     return get_object_alignment_2 (TREE_OPERAND (exp, 0),
487                                    alignp, bitposp, true);
488   else if (TREE_CODE (exp) == SSA_NAME
489            && POINTER_TYPE_P (TREE_TYPE (exp)))
490     {
491       unsigned int ptr_align, ptr_misalign;
492       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (exp);
493
494       if (pi && get_ptr_info_alignment (pi, &ptr_align, &ptr_misalign))
495         {
496           *bitposp = ptr_misalign * BITS_PER_UNIT;
497           *alignp = ptr_align * BITS_PER_UNIT;
498           /* We cannot really tell whether this result is an approximation.  */
499           return true;
500         }
501       else
502         {
503           *bitposp = 0;
504           *alignp = BITS_PER_UNIT;
505           return false;
506         }
507     }
508   else if (TREE_CODE (exp) == INTEGER_CST)
509     {
510       *alignp = BIGGEST_ALIGNMENT;
511       *bitposp = ((TREE_INT_CST_LOW (exp) * BITS_PER_UNIT)
512                   & (BIGGEST_ALIGNMENT - 1));
513       return true;
514     }
515
516   *bitposp = 0;
517   *alignp = BITS_PER_UNIT;
518   return false;
519 }
520
521 /* Return the alignment in bits of EXP, a pointer valued expression.
522    The alignment returned is, by default, the alignment of the thing that
523    EXP points to.  If it is not a POINTER_TYPE, 0 is returned.
524
525    Otherwise, look at the expression to see if we can do better, i.e., if the
526    expression is actually pointing at an object whose alignment is tighter.  */
527
528 unsigned int
529 get_pointer_alignment (tree exp)
530 {
531   unsigned HOST_WIDE_INT bitpos = 0;
532   unsigned int align;
533
534   get_pointer_alignment_1 (exp, &align, &bitpos);
535
536   /* align and bitpos now specify known low bits of the pointer.
537      ptr & (align - 1) == bitpos.  */
538
539   if (bitpos != 0)
540     align = (bitpos & -bitpos);
541
542   return align;
543 }
544
545 /* Compute the length of a C string.  TREE_STRING_LENGTH is not the right
546    way, because it could contain a zero byte in the middle.
547    TREE_STRING_LENGTH is the size of the character array, not the string.
548
549    ONLY_VALUE should be nonzero if the result is not going to be emitted
550    into the instruction stream and zero if it is going to be expanded.
551    E.g. with i++ ? "foo" : "bar", if ONLY_VALUE is nonzero, constant 3
552    is returned, otherwise NULL, since
553    len = c_strlen (src, 1); if (len) expand_expr (len, ...); would not
554    evaluate the side-effects.
555
556    The value returned is of type `ssizetype'.
557
558    Unfortunately, string_constant can't access the values of const char
559    arrays with initializers, so neither can we do so here.  */
560
561 tree
562 c_strlen (tree src, int only_value)
563 {
564   tree offset_node;
565   HOST_WIDE_INT offset;
566   int max;
567   const char *ptr;
568   location_t loc;
569
570   STRIP_NOPS (src);
571   if (TREE_CODE (src) == COND_EXPR
572       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
573     {
574       tree len1, len2;
575
576       len1 = c_strlen (TREE_OPERAND (src, 1), only_value);
577       len2 = c_strlen (TREE_OPERAND (src, 2), only_value);
578       if (tree_int_cst_equal (len1, len2))
579         return len1;
580     }
581
582   if (TREE_CODE (src) == COMPOUND_EXPR
583       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
584     return c_strlen (TREE_OPERAND (src, 1), only_value);
585
586   loc = EXPR_LOC_OR_HERE (src);
587
588   src = string_constant (src, &offset_node);
589   if (src == 0)
590     return NULL_TREE;
591
592   max = TREE_STRING_LENGTH (src) - 1;
593   ptr = TREE_STRING_POINTER (src);
594
595   if (offset_node && TREE_CODE (offset_node) != INTEGER_CST)
596     {
597       /* If the string has an internal zero byte (e.g., "foo\0bar"), we can't
598          compute the offset to the following null if we don't know where to
599          start searching for it.  */
600       int i;
601
602       for (i = 0; i < max; i++)
603         if (ptr[i] == 0)
604           return NULL_TREE;
605
606       /* We don't know the starting offset, but we do know that the string
607          has no internal zero bytes.  We can assume that the offset falls
608          within the bounds of the string; otherwise, the programmer deserves
609          what he gets.  Subtract the offset from the length of the string,
610          and return that.  This would perhaps not be valid if we were dealing
611          with named arrays in addition to literal string constants.  */
612
613       return size_diffop_loc (loc, size_int (max), offset_node);
614     }
615
616   /* We have a known offset into the string.  Start searching there for
617      a null character if we can represent it as a single HOST_WIDE_INT.  */
618   if (offset_node == 0)
619     offset = 0;
620   else if (! host_integerp (offset_node, 0))
621     offset = -1;
622   else
623     offset = tree_low_cst (offset_node, 0);
624
625   /* If the offset is known to be out of bounds, warn, and call strlen at
626      runtime.  */
627   if (offset < 0 || offset > max)
628     {
629      /* Suppress multiple warnings for propagated constant strings.  */
630       if (! TREE_NO_WARNING (src))
631         {
632           warning_at (loc, 0, "offset outside bounds of constant string");
633           TREE_NO_WARNING (src) = 1;
634         }
635       return NULL_TREE;
636     }
637
638   /* Use strlen to search for the first zero byte.  Since any strings
639      constructed with build_string will have nulls appended, we win even
640      if we get handed something like (char[4])"abcd".
641
642      Since OFFSET is our starting index into the string, no further
643      calculation is needed.  */
644   return ssize_int (strlen (ptr + offset));
645 }
646
647 /* Return a char pointer for a C string if it is a string constant
648    or sum of string constant and integer constant.  */
649
650 static const char *
651 c_getstr (tree src)
652 {
653   tree offset_node;
654
655   src = string_constant (src, &offset_node);
656   if (src == 0)
657     return 0;
658
659   if (offset_node == 0)
660     return TREE_STRING_POINTER (src);
661   else if (!host_integerp (offset_node, 1)
662            || compare_tree_int (offset_node, TREE_STRING_LENGTH (src) - 1) > 0)
663     return 0;
664
665   return TREE_STRING_POINTER (src) + tree_low_cst (offset_node, 1);
666 }
667
668 /* Return a CONST_INT or CONST_DOUBLE corresponding to target reading
669    GET_MODE_BITSIZE (MODE) bits from string constant STR.  */
670
671 static rtx
672 c_readstr (const char *str, enum machine_mode mode)
673 {
674   HOST_WIDE_INT c[2];
675   HOST_WIDE_INT ch;
676   unsigned int i, j;
677
678   gcc_assert (GET_MODE_CLASS (mode) == MODE_INT);
679
680   c[0] = 0;
681   c[1] = 0;
682   ch = 1;
683   for (i = 0; i < GET_MODE_SIZE (mode); i++)
684     {
685       j = i;
686       if (WORDS_BIG_ENDIAN)
687         j = GET_MODE_SIZE (mode) - i - 1;
688       if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN
689           && GET_MODE_SIZE (mode) >= UNITS_PER_WORD)
690         j = j + UNITS_PER_WORD - 2 * (j % UNITS_PER_WORD) - 1;
691       j *= BITS_PER_UNIT;
692       gcc_assert (j < HOST_BITS_PER_DOUBLE_INT);
693
694       if (ch)
695         ch = (unsigned char) str[i];
696       c[j / HOST_BITS_PER_WIDE_INT] |= ch << (j % HOST_BITS_PER_WIDE_INT);
697     }
698   return immed_double_const (c[0], c[1], mode);
699 }
700
701 /* Cast a target constant CST to target CHAR and if that value fits into
702    host char type, return zero and put that value into variable pointed to by
703    P.  */
704
705 static int
706 target_char_cast (tree cst, char *p)
707 {
708   unsigned HOST_WIDE_INT val, hostval;
709
710   if (TREE_CODE (cst) != INTEGER_CST
711       || CHAR_TYPE_SIZE > HOST_BITS_PER_WIDE_INT)
712     return 1;
713
714   val = TREE_INT_CST_LOW (cst);
715   if (CHAR_TYPE_SIZE < HOST_BITS_PER_WIDE_INT)
716     val &= (((unsigned HOST_WIDE_INT) 1) << CHAR_TYPE_SIZE) - 1;
717
718   hostval = val;
719   if (HOST_BITS_PER_CHAR < HOST_BITS_PER_WIDE_INT)
720     hostval &= (((unsigned HOST_WIDE_INT) 1) << HOST_BITS_PER_CHAR) - 1;
721
722   if (val != hostval)
723     return 1;
724
725   *p = hostval;
726   return 0;
727 }
728
729 /* Similar to save_expr, but assumes that arbitrary code is not executed
730    in between the multiple evaluations.  In particular, we assume that a
731    non-addressable local variable will not be modified.  */
732
733 static tree
734 builtin_save_expr (tree exp)
735 {
736   if (TREE_CODE (exp) == SSA_NAME
737       || (TREE_ADDRESSABLE (exp) == 0
738           && (TREE_CODE (exp) == PARM_DECL
739               || (TREE_CODE (exp) == VAR_DECL && !TREE_STATIC (exp)))))
740     return exp;
741
742   return save_expr (exp);
743 }
744
745 /* Given TEM, a pointer to a stack frame, follow the dynamic chain COUNT
746    times to get the address of either a higher stack frame, or a return
747    address located within it (depending on FNDECL_CODE).  */
748
749 static rtx
750 expand_builtin_return_addr (enum built_in_function fndecl_code, int count)
751 {
752   int i;
753
754 #ifdef INITIAL_FRAME_ADDRESS_RTX
755   rtx tem = INITIAL_FRAME_ADDRESS_RTX;
756 #else
757   rtx tem;
758
759   /* For a zero count with __builtin_return_address, we don't care what
760      frame address we return, because target-specific definitions will
761      override us.  Therefore frame pointer elimination is OK, and using
762      the soft frame pointer is OK.
763
764      For a nonzero count, or a zero count with __builtin_frame_address,
765      we require a stable offset from the current frame pointer to the
766      previous one, so we must use the hard frame pointer, and
767      we must disable frame pointer elimination.  */
768   if (count == 0 && fndecl_code == BUILT_IN_RETURN_ADDRESS)
769     tem = frame_pointer_rtx;
770   else
771     {
772       tem = hard_frame_pointer_rtx;
773
774       /* Tell reload not to eliminate the frame pointer.  */
775       crtl->accesses_prior_frames = 1;
776     }
777 #endif
778
779   /* Some machines need special handling before we can access
780      arbitrary frames.  For example, on the SPARC, we must first flush
781      all register windows to the stack.  */
782 #ifdef SETUP_FRAME_ADDRESSES
783   if (count > 0)
784     SETUP_FRAME_ADDRESSES ();
785 #endif
786
787   /* On the SPARC, the return address is not in the frame, it is in a
788      register.  There is no way to access it off of the current frame
789      pointer, but it can be accessed off the previous frame pointer by
790      reading the value from the register window save area.  */
791 #ifdef RETURN_ADDR_IN_PREVIOUS_FRAME
792   if (fndecl_code == BUILT_IN_RETURN_ADDRESS)
793     count--;
794 #endif
795
796   /* Scan back COUNT frames to the specified frame.  */
797   for (i = 0; i < count; i++)
798     {
799       /* Assume the dynamic chain pointer is in the word that the
800          frame address points to, unless otherwise specified.  */
801 #ifdef DYNAMIC_CHAIN_ADDRESS
802       tem = DYNAMIC_CHAIN_ADDRESS (tem);
803 #endif
804       tem = memory_address (Pmode, tem);
805       tem = gen_frame_mem (Pmode, tem);
806       tem = copy_to_reg (tem);
807     }
808
809   /* For __builtin_frame_address, return what we've got.  But, on
810      the SPARC for example, we may have to add a bias.  */
811   if (fndecl_code == BUILT_IN_FRAME_ADDRESS)
812 #ifdef FRAME_ADDR_RTX
813     return FRAME_ADDR_RTX (tem);
814 #else
815     return tem;
816 #endif
817
818   /* For __builtin_return_address, get the return address from that frame.  */
819 #ifdef RETURN_ADDR_RTX
820   tem = RETURN_ADDR_RTX (count, tem);
821 #else
822   tem = memory_address (Pmode,
823                         plus_constant (Pmode, tem, GET_MODE_SIZE (Pmode)));
824   tem = gen_frame_mem (Pmode, tem);
825 #endif
826   return tem;
827 }
828
829 /* Alias set used for setjmp buffer.  */
830 static alias_set_type setjmp_alias_set = -1;
831
832 /* Construct the leading half of a __builtin_setjmp call.  Control will
833    return to RECEIVER_LABEL.  This is also called directly by the SJLJ
834    exception handling code.  */
835
836 void
837 expand_builtin_setjmp_setup (rtx buf_addr, rtx receiver_label)
838 {
839   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
840   rtx stack_save;
841   rtx mem;
842
843   if (setjmp_alias_set == -1)
844     setjmp_alias_set = new_alias_set ();
845
846   buf_addr = convert_memory_address (Pmode, buf_addr);
847
848   buf_addr = force_reg (Pmode, force_operand (buf_addr, NULL_RTX));
849
850   /* We store the frame pointer and the address of receiver_label in
851      the buffer and use the rest of it for the stack save area, which
852      is machine-dependent.  */
853
854   mem = gen_rtx_MEM (Pmode, buf_addr);
855   set_mem_alias_set (mem, setjmp_alias_set);
856   emit_move_insn (mem, targetm.builtin_setjmp_frame_value ());
857
858   mem = gen_rtx_MEM (Pmode, plus_constant (Pmode, buf_addr,
859                                            GET_MODE_SIZE (Pmode))),
860   set_mem_alias_set (mem, setjmp_alias_set);
861
862   emit_move_insn (validize_mem (mem),
863                   force_reg (Pmode, gen_rtx_LABEL_REF (Pmode, receiver_label)));
864
865   stack_save = gen_rtx_MEM (sa_mode,
866                             plus_constant (Pmode, buf_addr,
867                                            2 * GET_MODE_SIZE (Pmode)));
868   set_mem_alias_set (stack_save, setjmp_alias_set);
869   emit_stack_save (SAVE_NONLOCAL, &stack_save);
870
871   /* If there is further processing to do, do it.  */
872 #ifdef HAVE_builtin_setjmp_setup
873   if (HAVE_builtin_setjmp_setup)
874     emit_insn (gen_builtin_setjmp_setup (buf_addr));
875 #endif
876
877   /* We have a nonlocal label.   */
878   cfun->has_nonlocal_label = 1;
879 }
880
881 /* Construct the trailing part of a __builtin_setjmp call.  This is
882    also called directly by the SJLJ exception handling code.
883    If RECEIVER_LABEL is NULL, instead contruct a nonlocal goto handler.  */
884
885 void
886 expand_builtin_setjmp_receiver (rtx receiver_label ATTRIBUTE_UNUSED)
887 {
888   rtx chain;
889
890   /* Mark the FP as used when we get here, so we have to make sure it's
891      marked as used by this function.  */
892   emit_use (hard_frame_pointer_rtx);
893
894   /* Mark the static chain as clobbered here so life information
895      doesn't get messed up for it.  */
896   chain = targetm.calls.static_chain (current_function_decl, true);
897   if (chain && REG_P (chain))
898     emit_clobber (chain);
899
900   /* Now put in the code to restore the frame pointer, and argument
901      pointer, if needed.  */
902 #ifdef HAVE_nonlocal_goto
903   if (! HAVE_nonlocal_goto)
904 #endif
905     /* First adjust our frame pointer to its actual value.  It was
906        previously set to the start of the virtual area corresponding to
907        the stacked variables when we branched here and now needs to be
908        adjusted to the actual hardware fp value.
909
910        Assignments to virtual registers are converted by
911        instantiate_virtual_regs into the corresponding assignment
912        to the underlying register (fp in this case) that makes
913        the original assignment true.
914        So the following insn will actually be decrementing fp by
915        STARTING_FRAME_OFFSET.  */
916     emit_move_insn (virtual_stack_vars_rtx, hard_frame_pointer_rtx);
917
918 #if !HARD_FRAME_POINTER_IS_ARG_POINTER
919   if (fixed_regs[ARG_POINTER_REGNUM])
920     {
921 #ifdef ELIMINABLE_REGS
922       /* If the argument pointer can be eliminated in favor of the
923          frame pointer, we don't need to restore it.  We assume here
924          that if such an elimination is present, it can always be used.
925          This is the case on all known machines; if we don't make this
926          assumption, we do unnecessary saving on many machines.  */
927       size_t i;
928       static const struct elims {const int from, to;} elim_regs[] = ELIMINABLE_REGS;
929
930       for (i = 0; i < ARRAY_SIZE (elim_regs); i++)
931         if (elim_regs[i].from == ARG_POINTER_REGNUM
932             && elim_regs[i].to == HARD_FRAME_POINTER_REGNUM)
933           break;
934
935       if (i == ARRAY_SIZE (elim_regs))
936 #endif
937         {
938           /* Now restore our arg pointer from the address at which it
939              was saved in our stack frame.  */
940           emit_move_insn (crtl->args.internal_arg_pointer,
941                           copy_to_reg (get_arg_pointer_save_area ()));
942         }
943     }
944 #endif
945
946 #ifdef HAVE_builtin_setjmp_receiver
947   if (receiver_label != NULL && HAVE_builtin_setjmp_receiver)
948     emit_insn (gen_builtin_setjmp_receiver (receiver_label));
949   else
950 #endif
951 #ifdef HAVE_nonlocal_goto_receiver
952     if (HAVE_nonlocal_goto_receiver)
953       emit_insn (gen_nonlocal_goto_receiver ());
954     else
955 #endif
956       { /* Nothing */ }
957
958   /* We must not allow the code we just generated to be reordered by
959      scheduling.  Specifically, the update of the frame pointer must
960      happen immediately, not later.  Similarly, we must block
961      (frame-related) register values to be used across this code.  */
962   emit_insn (gen_blockage ());
963 }
964
965 /* __builtin_longjmp is passed a pointer to an array of five words (not
966    all will be used on all machines).  It operates similarly to the C
967    library function of the same name, but is more efficient.  Much of
968    the code below is copied from the handling of non-local gotos.  */
969
970 static void
971 expand_builtin_longjmp (rtx buf_addr, rtx value)
972 {
973   rtx fp, lab, stack, insn, last;
974   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
975
976   /* DRAP is needed for stack realign if longjmp is expanded to current
977      function  */
978   if (SUPPORTS_STACK_ALIGNMENT)
979     crtl->need_drap = true;
980
981   if (setjmp_alias_set == -1)
982     setjmp_alias_set = new_alias_set ();
983
984   buf_addr = convert_memory_address (Pmode, buf_addr);
985
986   buf_addr = force_reg (Pmode, buf_addr);
987
988   /* We require that the user must pass a second argument of 1, because
989      that is what builtin_setjmp will return.  */
990   gcc_assert (value == const1_rtx);
991
992   last = get_last_insn ();
993 #ifdef HAVE_builtin_longjmp
994   if (HAVE_builtin_longjmp)
995     emit_insn (gen_builtin_longjmp (buf_addr));
996   else
997 #endif
998     {
999       fp = gen_rtx_MEM (Pmode, buf_addr);
1000       lab = gen_rtx_MEM (Pmode, plus_constant (Pmode, buf_addr,
1001                                                GET_MODE_SIZE (Pmode)));
1002
1003       stack = gen_rtx_MEM (sa_mode, plus_constant (Pmode, buf_addr,
1004                                                    2 * GET_MODE_SIZE (Pmode)));
1005       set_mem_alias_set (fp, setjmp_alias_set);
1006       set_mem_alias_set (lab, setjmp_alias_set);
1007       set_mem_alias_set (stack, setjmp_alias_set);
1008
1009       /* Pick up FP, label, and SP from the block and jump.  This code is
1010          from expand_goto in stmt.c; see there for detailed comments.  */
1011 #ifdef HAVE_nonlocal_goto
1012       if (HAVE_nonlocal_goto)
1013         /* We have to pass a value to the nonlocal_goto pattern that will
1014            get copied into the static_chain pointer, but it does not matter
1015            what that value is, because builtin_setjmp does not use it.  */
1016         emit_insn (gen_nonlocal_goto (value, lab, stack, fp));
1017       else
1018 #endif
1019         {
1020           lab = copy_to_reg (lab);
1021
1022           emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
1023           emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
1024
1025           emit_move_insn (hard_frame_pointer_rtx, fp);
1026           emit_stack_restore (SAVE_NONLOCAL, stack);
1027
1028           emit_use (hard_frame_pointer_rtx);
1029           emit_use (stack_pointer_rtx);
1030           emit_indirect_jump (lab);
1031         }
1032     }
1033
1034   /* Search backwards and mark the jump insn as a non-local goto.
1035      Note that this precludes the use of __builtin_longjmp to a
1036      __builtin_setjmp target in the same function.  However, we've
1037      already cautioned the user that these functions are for
1038      internal exception handling use only.  */
1039   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
1040     {
1041       gcc_assert (insn != last);
1042
1043       if (JUMP_P (insn))
1044         {
1045           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
1046           break;
1047         }
1048       else if (CALL_P (insn))
1049         break;
1050     }
1051 }
1052
1053 static inline bool
1054 more_const_call_expr_args_p (const const_call_expr_arg_iterator *iter)
1055 {
1056   return (iter->i < iter->n);
1057 }
1058
1059 /* This function validates the types of a function call argument list
1060    against a specified list of tree_codes.  If the last specifier is a 0,
1061    that represents an ellipses, otherwise the last specifier must be a
1062    VOID_TYPE.  */
1063
1064 static bool
1065 validate_arglist (const_tree callexpr, ...)
1066 {
1067   enum tree_code code;
1068   bool res = 0;
1069   va_list ap;
1070   const_call_expr_arg_iterator iter;
1071   const_tree arg;
1072
1073   va_start (ap, callexpr);
1074   init_const_call_expr_arg_iterator (callexpr, &iter);
1075
1076   do
1077     {
1078       code = (enum tree_code) va_arg (ap, int);
1079       switch (code)
1080         {
1081         case 0:
1082           /* This signifies an ellipses, any further arguments are all ok.  */
1083           res = true;
1084           goto end;
1085         case VOID_TYPE:
1086           /* This signifies an endlink, if no arguments remain, return
1087              true, otherwise return false.  */
1088           res = !more_const_call_expr_args_p (&iter);
1089           goto end;
1090         default:
1091           /* If no parameters remain or the parameter's code does not
1092              match the specified code, return false.  Otherwise continue
1093              checking any remaining arguments.  */
1094           arg = next_const_call_expr_arg (&iter);
1095           if (!validate_arg (arg, code))
1096             goto end;
1097           break;
1098         }
1099     }
1100   while (1);
1101
1102   /* We need gotos here since we can only have one VA_CLOSE in a
1103      function.  */
1104  end: ;
1105   va_end (ap);
1106
1107   return res;
1108 }
1109
1110 /* Expand a call to __builtin_nonlocal_goto.  We're passed the target label
1111    and the address of the save area.  */
1112
1113 static rtx
1114 expand_builtin_nonlocal_goto (tree exp)
1115 {
1116   tree t_label, t_save_area;
1117   rtx r_label, r_save_area, r_fp, r_sp, insn;
1118
1119   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
1120     return NULL_RTX;
1121
1122   t_label = CALL_EXPR_ARG (exp, 0);
1123   t_save_area = CALL_EXPR_ARG (exp, 1);
1124
1125   r_label = expand_normal (t_label);
1126   r_label = convert_memory_address (Pmode, r_label);
1127   r_save_area = expand_normal (t_save_area);
1128   r_save_area = convert_memory_address (Pmode, r_save_area);
1129   /* Copy the address of the save location to a register just in case it was
1130      based on the frame pointer.   */
1131   r_save_area = copy_to_reg (r_save_area);
1132   r_fp = gen_rtx_MEM (Pmode, r_save_area);
1133   r_sp = gen_rtx_MEM (STACK_SAVEAREA_MODE (SAVE_NONLOCAL),
1134                       plus_constant (Pmode, r_save_area,
1135                                      GET_MODE_SIZE (Pmode)));
1136
1137   crtl->has_nonlocal_goto = 1;
1138
1139 #ifdef HAVE_nonlocal_goto
1140   /* ??? We no longer need to pass the static chain value, afaik.  */
1141   if (HAVE_nonlocal_goto)
1142     emit_insn (gen_nonlocal_goto (const0_rtx, r_label, r_sp, r_fp));
1143   else
1144 #endif
1145     {
1146       r_label = copy_to_reg (r_label);
1147
1148       emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
1149       emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
1150
1151       /* Restore frame pointer for containing function.  */
1152       emit_move_insn (hard_frame_pointer_rtx, r_fp);
1153       emit_stack_restore (SAVE_NONLOCAL, r_sp);
1154
1155       /* USE of hard_frame_pointer_rtx added for consistency;
1156          not clear if really needed.  */
1157       emit_use (hard_frame_pointer_rtx);
1158       emit_use (stack_pointer_rtx);
1159
1160       /* If the architecture is using a GP register, we must
1161          conservatively assume that the target function makes use of it.
1162          The prologue of functions with nonlocal gotos must therefore
1163          initialize the GP register to the appropriate value, and we
1164          must then make sure that this value is live at the point
1165          of the jump.  (Note that this doesn't necessarily apply
1166          to targets with a nonlocal_goto pattern; they are free
1167          to implement it in their own way.  Note also that this is
1168          a no-op if the GP register is a global invariant.)  */
1169       if ((unsigned) PIC_OFFSET_TABLE_REGNUM != INVALID_REGNUM
1170           && fixed_regs[PIC_OFFSET_TABLE_REGNUM])
1171         emit_use (pic_offset_table_rtx);
1172
1173       emit_indirect_jump (r_label);
1174     }
1175
1176   /* Search backwards to the jump insn and mark it as a
1177      non-local goto.  */
1178   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
1179     {
1180       if (JUMP_P (insn))
1181         {
1182           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
1183           break;
1184         }
1185       else if (CALL_P (insn))
1186         break;
1187     }
1188
1189   return const0_rtx;
1190 }
1191
1192 /* __builtin_update_setjmp_buf is passed a pointer to an array of five words
1193    (not all will be used on all machines) that was passed to __builtin_setjmp.
1194    It updates the stack pointer in that block to correspond to the current
1195    stack pointer.  */
1196
1197 static void
1198 expand_builtin_update_setjmp_buf (rtx buf_addr)
1199 {
1200   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
1201   rtx stack_save
1202     = gen_rtx_MEM (sa_mode,
1203                    memory_address
1204                    (sa_mode,
1205                     plus_constant (Pmode, buf_addr,
1206                                    2 * GET_MODE_SIZE (Pmode))));
1207
1208   emit_stack_save (SAVE_NONLOCAL, &stack_save);
1209 }
1210
1211 /* Expand a call to __builtin_prefetch.  For a target that does not support
1212    data prefetch, evaluate the memory address argument in case it has side
1213    effects.  */
1214
1215 static void
1216 expand_builtin_prefetch (tree exp)
1217 {
1218   tree arg0, arg1, arg2;
1219   int nargs;
1220   rtx op0, op1, op2;
1221
1222   if (!validate_arglist (exp, POINTER_TYPE, 0))
1223     return;
1224
1225   arg0 = CALL_EXPR_ARG (exp, 0);
1226
1227   /* Arguments 1 and 2 are optional; argument 1 (read/write) defaults to
1228      zero (read) and argument 2 (locality) defaults to 3 (high degree of
1229      locality).  */
1230   nargs = call_expr_nargs (exp);
1231   if (nargs > 1)
1232     arg1 = CALL_EXPR_ARG (exp, 1);
1233   else
1234     arg1 = integer_zero_node;
1235   if (nargs > 2)
1236     arg2 = CALL_EXPR_ARG (exp, 2);
1237   else
1238     arg2 = integer_three_node;
1239
1240   /* Argument 0 is an address.  */
1241   op0 = expand_expr (arg0, NULL_RTX, Pmode, EXPAND_NORMAL);
1242
1243   /* Argument 1 (read/write flag) must be a compile-time constant int.  */
1244   if (TREE_CODE (arg1) != INTEGER_CST)
1245     {
1246       error ("second argument to %<__builtin_prefetch%> must be a constant");
1247       arg1 = integer_zero_node;
1248     }
1249   op1 = expand_normal (arg1);
1250   /* Argument 1 must be either zero or one.  */
1251   if (INTVAL (op1) != 0 && INTVAL (op1) != 1)
1252     {
1253       warning (0, "invalid second argument to %<__builtin_prefetch%>;"
1254                " using zero");
1255       op1 = const0_rtx;
1256     }
1257
1258   /* Argument 2 (locality) must be a compile-time constant int.  */
1259   if (TREE_CODE (arg2) != INTEGER_CST)
1260     {
1261       error ("third argument to %<__builtin_prefetch%> must be a constant");
1262       arg2 = integer_zero_node;
1263     }
1264   op2 = expand_normal (arg2);
1265   /* Argument 2 must be 0, 1, 2, or 3.  */
1266   if (INTVAL (op2) < 0 || INTVAL (op2) > 3)
1267     {
1268       warning (0, "invalid third argument to %<__builtin_prefetch%>; using zero");
1269       op2 = const0_rtx;
1270     }
1271
1272 #ifdef HAVE_prefetch
1273   if (HAVE_prefetch)
1274     {
1275       struct expand_operand ops[3];
1276
1277       create_address_operand (&ops[0], op0);
1278       create_integer_operand (&ops[1], INTVAL (op1));
1279       create_integer_operand (&ops[2], INTVAL (op2));
1280       if (maybe_expand_insn (CODE_FOR_prefetch, 3, ops))
1281         return;
1282     }
1283 #endif
1284
1285   /* Don't do anything with direct references to volatile memory, but
1286      generate code to handle other side effects.  */
1287   if (!MEM_P (op0) && side_effects_p (op0))
1288     emit_insn (op0);
1289 }
1290
1291 /* Get a MEM rtx for expression EXP which is the address of an operand
1292    to be used in a string instruction (cmpstrsi, movmemsi, ..).  LEN is
1293    the maximum length of the block of memory that might be accessed or
1294    NULL if unknown.  */
1295
1296 static rtx
1297 get_memory_rtx (tree exp, tree len)
1298 {
1299   tree orig_exp = exp;
1300   rtx addr, mem;
1301
1302   /* When EXP is not resolved SAVE_EXPR, MEM_ATTRS can be still derived
1303      from its expression, for expr->a.b only <variable>.a.b is recorded.  */
1304   if (TREE_CODE (exp) == SAVE_EXPR && !SAVE_EXPR_RESOLVED_P (exp))
1305     exp = TREE_OPERAND (exp, 0);
1306
1307   addr = expand_expr (orig_exp, NULL_RTX, ptr_mode, EXPAND_NORMAL);
1308   mem = gen_rtx_MEM (BLKmode, memory_address (BLKmode, addr));
1309
1310   /* Get an expression we can use to find the attributes to assign to MEM.
1311      First remove any nops.  */
1312   while (CONVERT_EXPR_P (exp)
1313          && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (exp, 0))))
1314     exp = TREE_OPERAND (exp, 0);
1315
1316   /* Build a MEM_REF representing the whole accessed area as a byte blob,
1317      (as builtin stringops may alias with anything).  */
1318   exp = fold_build2 (MEM_REF,
1319                      build_array_type (char_type_node,
1320                                        build_range_type (sizetype,
1321                                                          size_one_node, len)),
1322                      exp, build_int_cst (ptr_type_node, 0));
1323
1324   /* If the MEM_REF has no acceptable address, try to get the base object
1325      from the original address we got, and build an all-aliasing
1326      unknown-sized access to that one.  */
1327   if (is_gimple_mem_ref_addr (TREE_OPERAND (exp, 0)))
1328     set_mem_attributes (mem, exp, 0);
1329   else if (TREE_CODE (TREE_OPERAND (exp, 0)) == ADDR_EXPR
1330            && (exp = get_base_address (TREE_OPERAND (TREE_OPERAND (exp, 0),
1331                                                      0))))
1332     {
1333       exp = build_fold_addr_expr (exp);
1334       exp = fold_build2 (MEM_REF,
1335                          build_array_type (char_type_node,
1336                                            build_range_type (sizetype,
1337                                                              size_zero_node,
1338                                                              NULL)),
1339                          exp, build_int_cst (ptr_type_node, 0));
1340       set_mem_attributes (mem, exp, 0);
1341     }
1342   set_mem_alias_set (mem, 0);
1343   return mem;
1344 }
1345 \f
1346 /* Built-in functions to perform an untyped call and return.  */
1347
1348 #define apply_args_mode \
1349   (this_target_builtins->x_apply_args_mode)
1350 #define apply_result_mode \
1351   (this_target_builtins->x_apply_result_mode)
1352
1353 /* Return the size required for the block returned by __builtin_apply_args,
1354    and initialize apply_args_mode.  */
1355
1356 static int
1357 apply_args_size (void)
1358 {
1359   static int size = -1;
1360   int align;
1361   unsigned int regno;
1362   enum machine_mode mode;
1363
1364   /* The values computed by this function never change.  */
1365   if (size < 0)
1366     {
1367       /* The first value is the incoming arg-pointer.  */
1368       size = GET_MODE_SIZE (Pmode);
1369
1370       /* The second value is the structure value address unless this is
1371          passed as an "invisible" first argument.  */
1372       if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1373         size += GET_MODE_SIZE (Pmode);
1374
1375       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1376         if (FUNCTION_ARG_REGNO_P (regno))
1377           {
1378             mode = targetm.calls.get_raw_arg_mode (regno);
1379
1380             gcc_assert (mode != VOIDmode);
1381
1382             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1383             if (size % align != 0)
1384               size = CEIL (size, align) * align;
1385             size += GET_MODE_SIZE (mode);
1386             apply_args_mode[regno] = mode;
1387           }
1388         else
1389           {
1390             apply_args_mode[regno] = VOIDmode;
1391           }
1392     }
1393   return size;
1394 }
1395
1396 /* Return the size required for the block returned by __builtin_apply,
1397    and initialize apply_result_mode.  */
1398
1399 static int
1400 apply_result_size (void)
1401 {
1402   static int size = -1;
1403   int align, regno;
1404   enum machine_mode mode;
1405
1406   /* The values computed by this function never change.  */
1407   if (size < 0)
1408     {
1409       size = 0;
1410
1411       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1412         if (targetm.calls.function_value_regno_p (regno))
1413           {
1414             mode = targetm.calls.get_raw_result_mode (regno);
1415
1416             gcc_assert (mode != VOIDmode);
1417
1418             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1419             if (size % align != 0)
1420               size = CEIL (size, align) * align;
1421             size += GET_MODE_SIZE (mode);
1422             apply_result_mode[regno] = mode;
1423           }
1424         else
1425           apply_result_mode[regno] = VOIDmode;
1426
1427       /* Allow targets that use untyped_call and untyped_return to override
1428          the size so that machine-specific information can be stored here.  */
1429 #ifdef APPLY_RESULT_SIZE
1430       size = APPLY_RESULT_SIZE;
1431 #endif
1432     }
1433   return size;
1434 }
1435
1436 #if defined (HAVE_untyped_call) || defined (HAVE_untyped_return)
1437 /* Create a vector describing the result block RESULT.  If SAVEP is true,
1438    the result block is used to save the values; otherwise it is used to
1439    restore the values.  */
1440
1441 static rtx
1442 result_vector (int savep, rtx result)
1443 {
1444   int regno, size, align, nelts;
1445   enum machine_mode mode;
1446   rtx reg, mem;
1447   rtx *savevec = XALLOCAVEC (rtx, FIRST_PSEUDO_REGISTER);
1448
1449   size = nelts = 0;
1450   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1451     if ((mode = apply_result_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         reg = gen_rtx_REG (mode, savep ? regno : INCOMING_REGNO (regno));
1457         mem = adjust_address (result, mode, size);
1458         savevec[nelts++] = (savep
1459                             ? gen_rtx_SET (VOIDmode, mem, reg)
1460                             : gen_rtx_SET (VOIDmode, reg, mem));
1461         size += GET_MODE_SIZE (mode);
1462       }
1463   return gen_rtx_PARALLEL (VOIDmode, gen_rtvec_v (nelts, savevec));
1464 }
1465 #endif /* HAVE_untyped_call or HAVE_untyped_return */
1466
1467 /* Save the state required to perform an untyped call with the same
1468    arguments as were passed to the current function.  */
1469
1470 static rtx
1471 expand_builtin_apply_args_1 (void)
1472 {
1473   rtx registers, tem;
1474   int size, align, regno;
1475   enum machine_mode mode;
1476   rtx struct_incoming_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 1);
1477
1478   /* Create a block where the arg-pointer, structure value address,
1479      and argument registers can be saved.  */
1480   registers = assign_stack_local (BLKmode, apply_args_size (), -1);
1481
1482   /* Walk past the arg-pointer and structure value address.  */
1483   size = GET_MODE_SIZE (Pmode);
1484   if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1485     size += GET_MODE_SIZE (Pmode);
1486
1487   /* Save each register used in calling a function to the block.  */
1488   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1489     if ((mode = apply_args_mode[regno]) != VOIDmode)
1490       {
1491         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1492         if (size % align != 0)
1493           size = CEIL (size, align) * align;
1494
1495         tem = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1496
1497         emit_move_insn (adjust_address (registers, mode, size), tem);
1498         size += GET_MODE_SIZE (mode);
1499       }
1500
1501   /* Save the arg pointer to the block.  */
1502   tem = copy_to_reg (crtl->args.internal_arg_pointer);
1503 #ifdef STACK_GROWS_DOWNWARD
1504   /* We need the pointer as the caller actually passed them to us, not
1505      as we might have pretended they were passed.  Make sure it's a valid
1506      operand, as emit_move_insn isn't expected to handle a PLUS.  */
1507   tem
1508     = force_operand (plus_constant (Pmode, tem, crtl->args.pretend_args_size),
1509                      NULL_RTX);
1510 #endif
1511   emit_move_insn (adjust_address (registers, Pmode, 0), tem);
1512
1513   size = GET_MODE_SIZE (Pmode);
1514
1515   /* Save the structure value address unless this is passed as an
1516      "invisible" first argument.  */
1517   if (struct_incoming_value)
1518     {
1519       emit_move_insn (adjust_address (registers, Pmode, size),
1520                       copy_to_reg (struct_incoming_value));
1521       size += GET_MODE_SIZE (Pmode);
1522     }
1523
1524   /* Return the address of the block.  */
1525   return copy_addr_to_reg (XEXP (registers, 0));
1526 }
1527
1528 /* __builtin_apply_args returns block of memory allocated on
1529    the stack into which is stored the arg pointer, structure
1530    value address, static chain, and all the registers that might
1531    possibly be used in performing a function call.  The code is
1532    moved to the start of the function so the incoming values are
1533    saved.  */
1534
1535 static rtx
1536 expand_builtin_apply_args (void)
1537 {
1538   /* Don't do __builtin_apply_args more than once in a function.
1539      Save the result of the first call and reuse it.  */
1540   if (apply_args_value != 0)
1541     return apply_args_value;
1542   {
1543     /* When this function is called, it means that registers must be
1544        saved on entry to this function.  So we migrate the
1545        call to the first insn of this function.  */
1546     rtx temp;
1547     rtx seq;
1548
1549     start_sequence ();
1550     temp = expand_builtin_apply_args_1 ();
1551     seq = get_insns ();
1552     end_sequence ();
1553
1554     apply_args_value = temp;
1555
1556     /* Put the insns after the NOTE that starts the function.
1557        If this is inside a start_sequence, make the outer-level insn
1558        chain current, so the code is placed at the start of the
1559        function.  If internal_arg_pointer is a non-virtual pseudo,
1560        it needs to be placed after the function that initializes
1561        that pseudo.  */
1562     push_topmost_sequence ();
1563     if (REG_P (crtl->args.internal_arg_pointer)
1564         && REGNO (crtl->args.internal_arg_pointer) > LAST_VIRTUAL_REGISTER)
1565       emit_insn_before (seq, parm_birth_insn);
1566     else
1567       emit_insn_before (seq, NEXT_INSN (entry_of_function ()));
1568     pop_topmost_sequence ();
1569     return temp;
1570   }
1571 }
1572
1573 /* Perform an untyped call and save the state required to perform an
1574    untyped return of whatever value was returned by the given function.  */
1575
1576 static rtx
1577 expand_builtin_apply (rtx function, rtx arguments, rtx argsize)
1578 {
1579   int size, align, regno;
1580   enum machine_mode mode;
1581   rtx incoming_args, result, reg, dest, src, call_insn;
1582   rtx old_stack_level = 0;
1583   rtx call_fusage = 0;
1584   rtx struct_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0);
1585
1586   arguments = convert_memory_address (Pmode, arguments);
1587
1588   /* Create a block where the return registers can be saved.  */
1589   result = assign_stack_local (BLKmode, apply_result_size (), -1);
1590
1591   /* Fetch the arg pointer from the ARGUMENTS block.  */
1592   incoming_args = gen_reg_rtx (Pmode);
1593   emit_move_insn (incoming_args, gen_rtx_MEM (Pmode, arguments));
1594 #ifndef STACK_GROWS_DOWNWARD
1595   incoming_args = expand_simple_binop (Pmode, MINUS, incoming_args, argsize,
1596                                        incoming_args, 0, OPTAB_LIB_WIDEN);
1597 #endif
1598
1599   /* Push a new argument block and copy the arguments.  Do not allow
1600      the (potential) memcpy call below to interfere with our stack
1601      manipulations.  */
1602   do_pending_stack_adjust ();
1603   NO_DEFER_POP;
1604
1605   /* Save the stack with nonlocal if available.  */
1606 #ifdef HAVE_save_stack_nonlocal
1607   if (HAVE_save_stack_nonlocal)
1608     emit_stack_save (SAVE_NONLOCAL, &old_stack_level);
1609   else
1610 #endif
1611     emit_stack_save (SAVE_BLOCK, &old_stack_level);
1612
1613   /* Allocate a block of memory onto the stack and copy the memory
1614      arguments to the outgoing arguments address.  We can pass TRUE
1615      as the 4th argument because we just saved the stack pointer
1616      and will restore it right after the call.  */
1617   allocate_dynamic_stack_space (argsize, 0, BIGGEST_ALIGNMENT, true);
1618
1619   /* Set DRAP flag to true, even though allocate_dynamic_stack_space
1620      may have already set current_function_calls_alloca to true.
1621      current_function_calls_alloca won't be set if argsize is zero,
1622      so we have to guarantee need_drap is true here.  */
1623   if (SUPPORTS_STACK_ALIGNMENT)
1624     crtl->need_drap = true;
1625
1626   dest = virtual_outgoing_args_rtx;
1627 #ifndef STACK_GROWS_DOWNWARD
1628   if (CONST_INT_P (argsize))
1629     dest = plus_constant (Pmode, dest, -INTVAL (argsize));
1630   else
1631     dest = gen_rtx_PLUS (Pmode, dest, negate_rtx (Pmode, argsize));
1632 #endif
1633   dest = gen_rtx_MEM (BLKmode, dest);
1634   set_mem_align (dest, PARM_BOUNDARY);
1635   src = gen_rtx_MEM (BLKmode, incoming_args);
1636   set_mem_align (src, PARM_BOUNDARY);
1637   emit_block_move (dest, src, argsize, BLOCK_OP_NORMAL);
1638
1639   /* Refer to the argument block.  */
1640   apply_args_size ();
1641   arguments = gen_rtx_MEM (BLKmode, arguments);
1642   set_mem_align (arguments, PARM_BOUNDARY);
1643
1644   /* Walk past the arg-pointer and structure value address.  */
1645   size = GET_MODE_SIZE (Pmode);
1646   if (struct_value)
1647     size += GET_MODE_SIZE (Pmode);
1648
1649   /* Restore each of the registers previously saved.  Make USE insns
1650      for each of these registers for use in making the call.  */
1651   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1652     if ((mode = apply_args_mode[regno]) != VOIDmode)
1653       {
1654         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1655         if (size % align != 0)
1656           size = CEIL (size, align) * align;
1657         reg = gen_rtx_REG (mode, regno);
1658         emit_move_insn (reg, adjust_address (arguments, mode, size));
1659         use_reg (&call_fusage, reg);
1660         size += GET_MODE_SIZE (mode);
1661       }
1662
1663   /* Restore the structure value address unless this is passed as an
1664      "invisible" first argument.  */
1665   size = GET_MODE_SIZE (Pmode);
1666   if (struct_value)
1667     {
1668       rtx value = gen_reg_rtx (Pmode);
1669       emit_move_insn (value, adjust_address (arguments, Pmode, size));
1670       emit_move_insn (struct_value, value);
1671       if (REG_P (struct_value))
1672         use_reg (&call_fusage, struct_value);
1673       size += GET_MODE_SIZE (Pmode);
1674     }
1675
1676   /* All arguments and registers used for the call are set up by now!  */
1677   function = prepare_call_address (NULL, function, NULL, &call_fusage, 0, 0);
1678
1679   /* Ensure address is valid.  SYMBOL_REF is already valid, so no need,
1680      and we don't want to load it into a register as an optimization,
1681      because prepare_call_address already did it if it should be done.  */
1682   if (GET_CODE (function) != SYMBOL_REF)
1683     function = memory_address (FUNCTION_MODE, function);
1684
1685   /* Generate the actual call instruction and save the return value.  */
1686 #ifdef HAVE_untyped_call
1687   if (HAVE_untyped_call)
1688     emit_call_insn (gen_untyped_call (gen_rtx_MEM (FUNCTION_MODE, function),
1689                                       result, result_vector (1, result)));
1690   else
1691 #endif
1692 #ifdef HAVE_call_value
1693   if (HAVE_call_value)
1694     {
1695       rtx valreg = 0;
1696
1697       /* Locate the unique return register.  It is not possible to
1698          express a call that sets more than one return register using
1699          call_value; use untyped_call for that.  In fact, untyped_call
1700          only needs to save the return registers in the given block.  */
1701       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1702         if ((mode = apply_result_mode[regno]) != VOIDmode)
1703           {
1704             gcc_assert (!valreg); /* HAVE_untyped_call required.  */
1705
1706             valreg = gen_rtx_REG (mode, regno);
1707           }
1708
1709       emit_call_insn (GEN_CALL_VALUE (valreg,
1710                                       gen_rtx_MEM (FUNCTION_MODE, function),
1711                                       const0_rtx, NULL_RTX, const0_rtx));
1712
1713       emit_move_insn (adjust_address (result, GET_MODE (valreg), 0), valreg);
1714     }
1715   else
1716 #endif
1717     gcc_unreachable ();
1718
1719   /* Find the CALL insn we just emitted, and attach the register usage
1720      information.  */
1721   call_insn = last_call_insn ();
1722   add_function_usage_to (call_insn, call_fusage);
1723
1724   /* Restore the stack.  */
1725 #ifdef HAVE_save_stack_nonlocal
1726   if (HAVE_save_stack_nonlocal)
1727     emit_stack_restore (SAVE_NONLOCAL, old_stack_level);
1728   else
1729 #endif
1730     emit_stack_restore (SAVE_BLOCK, old_stack_level);
1731   fixup_args_size_notes (call_insn, get_last_insn (), 0);
1732
1733   OK_DEFER_POP;
1734
1735   /* Return the address of the result block.  */
1736   result = copy_addr_to_reg (XEXP (result, 0));
1737   return convert_memory_address (ptr_mode, result);
1738 }
1739
1740 /* Perform an untyped return.  */
1741
1742 static void
1743 expand_builtin_return (rtx result)
1744 {
1745   int size, align, regno;
1746   enum machine_mode mode;
1747   rtx reg;
1748   rtx call_fusage = 0;
1749
1750   result = convert_memory_address (Pmode, result);
1751
1752   apply_result_size ();
1753   result = gen_rtx_MEM (BLKmode, result);
1754
1755 #ifdef HAVE_untyped_return
1756   if (HAVE_untyped_return)
1757     {
1758       emit_jump_insn (gen_untyped_return (result, result_vector (0, result)));
1759       emit_barrier ();
1760       return;
1761     }
1762 #endif
1763
1764   /* Restore the return value and note that each value is used.  */
1765   size = 0;
1766   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1767     if ((mode = apply_result_mode[regno]) != VOIDmode)
1768       {
1769         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1770         if (size % align != 0)
1771           size = CEIL (size, align) * align;
1772         reg = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1773         emit_move_insn (reg, adjust_address (result, mode, size));
1774
1775         push_to_sequence (call_fusage);
1776         emit_use (reg);
1777         call_fusage = get_insns ();
1778         end_sequence ();
1779         size += GET_MODE_SIZE (mode);
1780       }
1781
1782   /* Put the USE insns before the return.  */
1783   emit_insn (call_fusage);
1784
1785   /* Return whatever values was restored by jumping directly to the end
1786      of the function.  */
1787   expand_naked_return ();
1788 }
1789
1790 /* Used by expand_builtin_classify_type and fold_builtin_classify_type.  */
1791
1792 static enum type_class
1793 type_to_class (tree type)
1794 {
1795   switch (TREE_CODE (type))
1796     {
1797     case VOID_TYPE:        return void_type_class;
1798     case INTEGER_TYPE:     return integer_type_class;
1799     case ENUMERAL_TYPE:    return enumeral_type_class;
1800     case BOOLEAN_TYPE:     return boolean_type_class;
1801     case POINTER_TYPE:     return pointer_type_class;
1802     case REFERENCE_TYPE:   return reference_type_class;
1803     case OFFSET_TYPE:      return offset_type_class;
1804     case REAL_TYPE:        return real_type_class;
1805     case COMPLEX_TYPE:     return complex_type_class;
1806     case FUNCTION_TYPE:    return function_type_class;
1807     case METHOD_TYPE:      return method_type_class;
1808     case RECORD_TYPE:      return record_type_class;
1809     case UNION_TYPE:
1810     case QUAL_UNION_TYPE:  return union_type_class;
1811     case ARRAY_TYPE:       return (TYPE_STRING_FLAG (type)
1812                                    ? string_type_class : array_type_class);
1813     case LANG_TYPE:        return lang_type_class;
1814     default:               return no_type_class;
1815     }
1816 }
1817
1818 /* Expand a call EXP to __builtin_classify_type.  */
1819
1820 static rtx
1821 expand_builtin_classify_type (tree exp)
1822 {
1823   if (call_expr_nargs (exp))
1824     return GEN_INT (type_to_class (TREE_TYPE (CALL_EXPR_ARG (exp, 0))));
1825   return GEN_INT (no_type_class);
1826 }
1827
1828 /* This helper macro, meant to be used in mathfn_built_in below,
1829    determines which among a set of three builtin math functions is
1830    appropriate for a given type mode.  The `F' and `L' cases are
1831    automatically generated from the `double' case.  */
1832 #define CASE_MATHFN(BUILT_IN_MATHFN) \
1833   case BUILT_IN_MATHFN: case BUILT_IN_MATHFN##F: case BUILT_IN_MATHFN##L: \
1834   fcode = BUILT_IN_MATHFN; fcodef = BUILT_IN_MATHFN##F ; \
1835   fcodel = BUILT_IN_MATHFN##L ; break;
1836 /* Similar to above, but appends _R after any F/L suffix.  */
1837 #define CASE_MATHFN_REENT(BUILT_IN_MATHFN) \
1838   case BUILT_IN_MATHFN##_R: case BUILT_IN_MATHFN##F_R: case BUILT_IN_MATHFN##L_R: \
1839   fcode = BUILT_IN_MATHFN##_R; fcodef = BUILT_IN_MATHFN##F_R ; \
1840   fcodel = BUILT_IN_MATHFN##L_R ; break;
1841
1842 /* Return mathematic function equivalent to FN but operating directly on TYPE,
1843    if available.  If IMPLICIT is true use the implicit builtin declaration,
1844    otherwise use the explicit declaration.  If we can't do the conversion,
1845    return zero.  */
1846
1847 static tree
1848 mathfn_built_in_1 (tree type, enum built_in_function fn, bool implicit_p)
1849 {
1850   enum built_in_function fcode, fcodef, fcodel, fcode2;
1851
1852   switch (fn)
1853     {
1854       CASE_MATHFN (BUILT_IN_ACOS)
1855       CASE_MATHFN (BUILT_IN_ACOSH)
1856       CASE_MATHFN (BUILT_IN_ASIN)
1857       CASE_MATHFN (BUILT_IN_ASINH)
1858       CASE_MATHFN (BUILT_IN_ATAN)
1859       CASE_MATHFN (BUILT_IN_ATAN2)
1860       CASE_MATHFN (BUILT_IN_ATANH)
1861       CASE_MATHFN (BUILT_IN_CBRT)
1862       CASE_MATHFN (BUILT_IN_CEIL)
1863       CASE_MATHFN (BUILT_IN_CEXPI)
1864       CASE_MATHFN (BUILT_IN_COPYSIGN)
1865       CASE_MATHFN (BUILT_IN_COS)
1866       CASE_MATHFN (BUILT_IN_COSH)
1867       CASE_MATHFN (BUILT_IN_DREM)
1868       CASE_MATHFN (BUILT_IN_ERF)
1869       CASE_MATHFN (BUILT_IN_ERFC)
1870       CASE_MATHFN (BUILT_IN_EXP)
1871       CASE_MATHFN (BUILT_IN_EXP10)
1872       CASE_MATHFN (BUILT_IN_EXP2)
1873       CASE_MATHFN (BUILT_IN_EXPM1)
1874       CASE_MATHFN (BUILT_IN_FABS)
1875       CASE_MATHFN (BUILT_IN_FDIM)
1876       CASE_MATHFN (BUILT_IN_FLOOR)
1877       CASE_MATHFN (BUILT_IN_FMA)
1878       CASE_MATHFN (BUILT_IN_FMAX)
1879       CASE_MATHFN (BUILT_IN_FMIN)
1880       CASE_MATHFN (BUILT_IN_FMOD)
1881       CASE_MATHFN (BUILT_IN_FREXP)
1882       CASE_MATHFN (BUILT_IN_GAMMA)
1883       CASE_MATHFN_REENT (BUILT_IN_GAMMA) /* GAMMA_R */
1884       CASE_MATHFN (BUILT_IN_HUGE_VAL)
1885       CASE_MATHFN (BUILT_IN_HYPOT)
1886       CASE_MATHFN (BUILT_IN_ILOGB)
1887       CASE_MATHFN (BUILT_IN_ICEIL)
1888       CASE_MATHFN (BUILT_IN_IFLOOR)
1889       CASE_MATHFN (BUILT_IN_INF)
1890       CASE_MATHFN (BUILT_IN_IRINT)
1891       CASE_MATHFN (BUILT_IN_IROUND)
1892       CASE_MATHFN (BUILT_IN_ISINF)
1893       CASE_MATHFN (BUILT_IN_J0)
1894       CASE_MATHFN (BUILT_IN_J1)
1895       CASE_MATHFN (BUILT_IN_JN)
1896       CASE_MATHFN (BUILT_IN_LCEIL)
1897       CASE_MATHFN (BUILT_IN_LDEXP)
1898       CASE_MATHFN (BUILT_IN_LFLOOR)
1899       CASE_MATHFN (BUILT_IN_LGAMMA)
1900       CASE_MATHFN_REENT (BUILT_IN_LGAMMA) /* LGAMMA_R */
1901       CASE_MATHFN (BUILT_IN_LLCEIL)
1902       CASE_MATHFN (BUILT_IN_LLFLOOR)
1903       CASE_MATHFN (BUILT_IN_LLRINT)
1904       CASE_MATHFN (BUILT_IN_LLROUND)
1905       CASE_MATHFN (BUILT_IN_LOG)
1906       CASE_MATHFN (BUILT_IN_LOG10)
1907       CASE_MATHFN (BUILT_IN_LOG1P)
1908       CASE_MATHFN (BUILT_IN_LOG2)
1909       CASE_MATHFN (BUILT_IN_LOGB)
1910       CASE_MATHFN (BUILT_IN_LRINT)
1911       CASE_MATHFN (BUILT_IN_LROUND)
1912       CASE_MATHFN (BUILT_IN_MODF)
1913       CASE_MATHFN (BUILT_IN_NAN)
1914       CASE_MATHFN (BUILT_IN_NANS)
1915       CASE_MATHFN (BUILT_IN_NEARBYINT)
1916       CASE_MATHFN (BUILT_IN_NEXTAFTER)
1917       CASE_MATHFN (BUILT_IN_NEXTTOWARD)
1918       CASE_MATHFN (BUILT_IN_POW)
1919       CASE_MATHFN (BUILT_IN_POWI)
1920       CASE_MATHFN (BUILT_IN_POW10)
1921       CASE_MATHFN (BUILT_IN_REMAINDER)
1922       CASE_MATHFN (BUILT_IN_REMQUO)
1923       CASE_MATHFN (BUILT_IN_RINT)
1924       CASE_MATHFN (BUILT_IN_ROUND)
1925       CASE_MATHFN (BUILT_IN_SCALB)
1926       CASE_MATHFN (BUILT_IN_SCALBLN)
1927       CASE_MATHFN (BUILT_IN_SCALBN)
1928       CASE_MATHFN (BUILT_IN_SIGNBIT)
1929       CASE_MATHFN (BUILT_IN_SIGNIFICAND)
1930       CASE_MATHFN (BUILT_IN_SIN)
1931       CASE_MATHFN (BUILT_IN_SINCOS)
1932       CASE_MATHFN (BUILT_IN_SINH)
1933       CASE_MATHFN (BUILT_IN_SQRT)
1934       CASE_MATHFN (BUILT_IN_TAN)
1935       CASE_MATHFN (BUILT_IN_TANH)
1936       CASE_MATHFN (BUILT_IN_TGAMMA)
1937       CASE_MATHFN (BUILT_IN_TRUNC)
1938       CASE_MATHFN (BUILT_IN_Y0)
1939       CASE_MATHFN (BUILT_IN_Y1)
1940       CASE_MATHFN (BUILT_IN_YN)
1941
1942       default:
1943         return NULL_TREE;
1944       }
1945
1946   if (TYPE_MAIN_VARIANT (type) == double_type_node)
1947     fcode2 = fcode;
1948   else if (TYPE_MAIN_VARIANT (type) == float_type_node)
1949     fcode2 = fcodef;
1950   else if (TYPE_MAIN_VARIANT (type) == long_double_type_node)
1951     fcode2 = fcodel;
1952   else
1953     return NULL_TREE;
1954
1955   if (implicit_p && !builtin_decl_implicit_p (fcode2))
1956     return NULL_TREE;
1957
1958   return builtin_decl_explicit (fcode2);
1959 }
1960
1961 /* Like mathfn_built_in_1(), but always use the implicit array.  */
1962
1963 tree
1964 mathfn_built_in (tree type, enum built_in_function fn)
1965 {
1966   return mathfn_built_in_1 (type, fn, /*implicit=*/ 1);
1967 }
1968
1969 /* If errno must be maintained, expand the RTL to check if the result,
1970    TARGET, of a built-in function call, EXP, is NaN, and if so set
1971    errno to EDOM.  */
1972
1973 static void
1974 expand_errno_check (tree exp, rtx target)
1975 {
1976   rtx lab = gen_label_rtx ();
1977
1978   /* Test the result; if it is NaN, set errno=EDOM because
1979      the argument was not in the domain.  */
1980   do_compare_rtx_and_jump (target, target, EQ, 0, GET_MODE (target),
1981                            NULL_RTX, NULL_RTX, lab,
1982                            /* The jump is very likely.  */
1983                            REG_BR_PROB_BASE - (REG_BR_PROB_BASE / 2000 - 1));
1984
1985 #ifdef TARGET_EDOM
1986   /* If this built-in doesn't throw an exception, set errno directly.  */
1987   if (TREE_NOTHROW (TREE_OPERAND (CALL_EXPR_FN (exp), 0)))
1988     {
1989 #ifdef GEN_ERRNO_RTX
1990       rtx errno_rtx = GEN_ERRNO_RTX;
1991 #else
1992       rtx errno_rtx
1993           = gen_rtx_MEM (word_mode, gen_rtx_SYMBOL_REF (Pmode, "errno"));
1994 #endif
1995       emit_move_insn (errno_rtx,
1996                       gen_int_mode (TARGET_EDOM, GET_MODE (errno_rtx)));
1997       emit_label (lab);
1998       return;
1999     }
2000 #endif
2001
2002   /* Make sure the library call isn't expanded as a tail call.  */
2003   CALL_EXPR_TAILCALL (exp) = 0;
2004
2005   /* We can't set errno=EDOM directly; let the library call do it.
2006      Pop the arguments right away in case the call gets deleted.  */
2007   NO_DEFER_POP;
2008   expand_call (exp, target, 0);
2009   OK_DEFER_POP;
2010   emit_label (lab);
2011 }
2012
2013 /* Expand a call to one of the builtin math functions (sqrt, exp, or log).
2014    Return NULL_RTX if a normal call should be emitted rather than expanding
2015    the function in-line.  EXP is the expression that is a call to the builtin
2016    function; if convenient, the result should be placed in TARGET.
2017    SUBTARGET may be used as the target for computing one of EXP's operands.  */
2018
2019 static rtx
2020 expand_builtin_mathfn (tree exp, rtx target, rtx subtarget)
2021 {
2022   optab builtin_optab;
2023   rtx op0, insns;
2024   tree fndecl = get_callee_fndecl (exp);
2025   enum machine_mode mode;
2026   bool errno_set = false;
2027   bool try_widening = false;
2028   tree arg;
2029
2030   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2031     return NULL_RTX;
2032
2033   arg = CALL_EXPR_ARG (exp, 0);
2034
2035   switch (DECL_FUNCTION_CODE (fndecl))
2036     {
2037     CASE_FLT_FN (BUILT_IN_SQRT):
2038       errno_set = ! tree_expr_nonnegative_p (arg);
2039       try_widening = true;
2040       builtin_optab = sqrt_optab;
2041       break;
2042     CASE_FLT_FN (BUILT_IN_EXP):
2043       errno_set = true; builtin_optab = exp_optab; break;
2044     CASE_FLT_FN (BUILT_IN_EXP10):
2045     CASE_FLT_FN (BUILT_IN_POW10):
2046       errno_set = true; builtin_optab = exp10_optab; break;
2047     CASE_FLT_FN (BUILT_IN_EXP2):
2048       errno_set = true; builtin_optab = exp2_optab; break;
2049     CASE_FLT_FN (BUILT_IN_EXPM1):
2050       errno_set = true; builtin_optab = expm1_optab; break;
2051     CASE_FLT_FN (BUILT_IN_LOGB):
2052       errno_set = true; builtin_optab = logb_optab; break;
2053     CASE_FLT_FN (BUILT_IN_LOG):
2054       errno_set = true; builtin_optab = log_optab; break;
2055     CASE_FLT_FN (BUILT_IN_LOG10):
2056       errno_set = true; builtin_optab = log10_optab; break;
2057     CASE_FLT_FN (BUILT_IN_LOG2):
2058       errno_set = true; builtin_optab = log2_optab; break;
2059     CASE_FLT_FN (BUILT_IN_LOG1P):
2060       errno_set = true; builtin_optab = log1p_optab; break;
2061     CASE_FLT_FN (BUILT_IN_ASIN):
2062       builtin_optab = asin_optab; break;
2063     CASE_FLT_FN (BUILT_IN_ACOS):
2064       builtin_optab = acos_optab; break;
2065     CASE_FLT_FN (BUILT_IN_TAN):
2066       builtin_optab = tan_optab; break;
2067     CASE_FLT_FN (BUILT_IN_ATAN):
2068       builtin_optab = atan_optab; break;
2069     CASE_FLT_FN (BUILT_IN_FLOOR):
2070       builtin_optab = floor_optab; break;
2071     CASE_FLT_FN (BUILT_IN_CEIL):
2072       builtin_optab = ceil_optab; break;
2073     CASE_FLT_FN (BUILT_IN_TRUNC):
2074       builtin_optab = btrunc_optab; break;
2075     CASE_FLT_FN (BUILT_IN_ROUND):
2076       builtin_optab = round_optab; break;
2077     CASE_FLT_FN (BUILT_IN_NEARBYINT):
2078       builtin_optab = nearbyint_optab;
2079       if (flag_trapping_math)
2080         break;
2081       /* Else fallthrough and expand as rint.  */
2082     CASE_FLT_FN (BUILT_IN_RINT):
2083       builtin_optab = rint_optab; break;
2084     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
2085       builtin_optab = significand_optab; break;
2086     default:
2087       gcc_unreachable ();
2088     }
2089
2090   /* Make a suitable register to place result in.  */
2091   mode = TYPE_MODE (TREE_TYPE (exp));
2092
2093   if (! flag_errno_math || ! HONOR_NANS (mode))
2094     errno_set = false;
2095
2096   /* Before working hard, check whether the instruction is available, but try
2097      to widen the mode for specific operations.  */
2098   if ((optab_handler (builtin_optab, mode) != CODE_FOR_nothing
2099        || (try_widening && !excess_precision_type (TREE_TYPE (exp))))
2100       && (!errno_set || !optimize_insn_for_size_p ()))
2101     {
2102       rtx result = gen_reg_rtx (mode);
2103
2104       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2105          need to expand the argument again.  This way, we will not perform
2106          side-effects more the once.  */
2107       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2108
2109       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2110
2111       start_sequence ();
2112
2113       /* Compute into RESULT.
2114          Set RESULT to wherever the result comes back.  */
2115       result = expand_unop (mode, builtin_optab, op0, result, 0);
2116
2117       if (result != 0)
2118         {
2119           if (errno_set)
2120             expand_errno_check (exp, result);
2121
2122           /* Output the entire sequence.  */
2123           insns = get_insns ();
2124           end_sequence ();
2125           emit_insn (insns);
2126           return result;
2127         }
2128
2129       /* If we were unable to expand via the builtin, stop the sequence
2130          (without outputting the insns) and call to the library function
2131          with the stabilized argument list.  */
2132       end_sequence ();
2133     }
2134
2135   return expand_call (exp, target, target == const0_rtx);
2136 }
2137
2138 /* Expand a call to the builtin binary math functions (pow and atan2).
2139    Return NULL_RTX if a normal call should be emitted rather than expanding the
2140    function in-line.  EXP is the expression that is a call to the builtin
2141    function; if convenient, the result should be placed in TARGET.
2142    SUBTARGET may be used as the target for computing one of EXP's
2143    operands.  */
2144
2145 static rtx
2146 expand_builtin_mathfn_2 (tree exp, rtx target, rtx subtarget)
2147 {
2148   optab builtin_optab;
2149   rtx op0, op1, insns, result;
2150   int op1_type = REAL_TYPE;
2151   tree fndecl = get_callee_fndecl (exp);
2152   tree arg0, arg1;
2153   enum machine_mode mode;
2154   bool errno_set = true;
2155
2156   switch (DECL_FUNCTION_CODE (fndecl))
2157     {
2158     CASE_FLT_FN (BUILT_IN_SCALBN):
2159     CASE_FLT_FN (BUILT_IN_SCALBLN):
2160     CASE_FLT_FN (BUILT_IN_LDEXP):
2161       op1_type = INTEGER_TYPE;
2162     default:
2163       break;
2164     }
2165
2166   if (!validate_arglist (exp, REAL_TYPE, op1_type, VOID_TYPE))
2167     return NULL_RTX;
2168
2169   arg0 = CALL_EXPR_ARG (exp, 0);
2170   arg1 = CALL_EXPR_ARG (exp, 1);
2171
2172   switch (DECL_FUNCTION_CODE (fndecl))
2173     {
2174     CASE_FLT_FN (BUILT_IN_POW):
2175       builtin_optab = pow_optab; break;
2176     CASE_FLT_FN (BUILT_IN_ATAN2):
2177       builtin_optab = atan2_optab; break;
2178     CASE_FLT_FN (BUILT_IN_SCALB):
2179       if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (exp)))->b != 2)
2180         return 0;
2181       builtin_optab = scalb_optab; break;
2182     CASE_FLT_FN (BUILT_IN_SCALBN):
2183     CASE_FLT_FN (BUILT_IN_SCALBLN):
2184       if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (exp)))->b != 2)
2185         return 0;
2186     /* Fall through... */
2187     CASE_FLT_FN (BUILT_IN_LDEXP):
2188       builtin_optab = ldexp_optab; break;
2189     CASE_FLT_FN (BUILT_IN_FMOD):
2190       builtin_optab = fmod_optab; break;
2191     CASE_FLT_FN (BUILT_IN_REMAINDER):
2192     CASE_FLT_FN (BUILT_IN_DREM):
2193       builtin_optab = remainder_optab; break;
2194     default:
2195       gcc_unreachable ();
2196     }
2197
2198   /* Make a suitable register to place result in.  */
2199   mode = TYPE_MODE (TREE_TYPE (exp));
2200
2201   /* Before working hard, check whether the instruction is available.  */
2202   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2203     return NULL_RTX;
2204
2205   result = gen_reg_rtx (mode);
2206
2207   if (! flag_errno_math || ! HONOR_NANS (mode))
2208     errno_set = false;
2209
2210   if (errno_set && optimize_insn_for_size_p ())
2211     return 0;
2212
2213   /* Always stabilize the argument list.  */
2214   CALL_EXPR_ARG (exp, 0) = arg0 = builtin_save_expr (arg0);
2215   CALL_EXPR_ARG (exp, 1) = arg1 = builtin_save_expr (arg1);
2216
2217   op0 = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
2218   op1 = expand_normal (arg1);
2219
2220   start_sequence ();
2221
2222   /* Compute into RESULT.
2223      Set RESULT to wherever the result comes back.  */
2224   result = expand_binop (mode, builtin_optab, op0, op1,
2225                          result, 0, OPTAB_DIRECT);
2226
2227   /* If we were unable to expand via the builtin, stop the sequence
2228      (without outputting the insns) and call to the library function
2229      with the stabilized argument list.  */
2230   if (result == 0)
2231     {
2232       end_sequence ();
2233       return expand_call (exp, target, target == const0_rtx);
2234     }
2235
2236   if (errno_set)
2237     expand_errno_check (exp, result);
2238
2239   /* Output the entire sequence.  */
2240   insns = get_insns ();
2241   end_sequence ();
2242   emit_insn (insns);
2243
2244   return result;
2245 }
2246
2247 /* Expand a call to the builtin trinary math functions (fma).
2248    Return NULL_RTX if a normal call should be emitted rather than expanding the
2249    function in-line.  EXP is the expression that is a call to the builtin
2250    function; if convenient, the result should be placed in TARGET.
2251    SUBTARGET may be used as the target for computing one of EXP's
2252    operands.  */
2253
2254 static rtx
2255 expand_builtin_mathfn_ternary (tree exp, rtx target, rtx subtarget)
2256 {
2257   optab builtin_optab;
2258   rtx op0, op1, op2, insns, result;
2259   tree fndecl = get_callee_fndecl (exp);
2260   tree arg0, arg1, arg2;
2261   enum machine_mode mode;
2262
2263   if (!validate_arglist (exp, REAL_TYPE, REAL_TYPE, REAL_TYPE, VOID_TYPE))
2264     return NULL_RTX;
2265
2266   arg0 = CALL_EXPR_ARG (exp, 0);
2267   arg1 = CALL_EXPR_ARG (exp, 1);
2268   arg2 = CALL_EXPR_ARG (exp, 2);
2269
2270   switch (DECL_FUNCTION_CODE (fndecl))
2271     {
2272     CASE_FLT_FN (BUILT_IN_FMA):
2273       builtin_optab = fma_optab; break;
2274     default:
2275       gcc_unreachable ();
2276     }
2277
2278   /* Make a suitable register to place result in.  */
2279   mode = TYPE_MODE (TREE_TYPE (exp));
2280
2281   /* Before working hard, check whether the instruction is available.  */
2282   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2283     return NULL_RTX;
2284
2285   result = gen_reg_rtx (mode);
2286
2287   /* Always stabilize the argument list.  */
2288   CALL_EXPR_ARG (exp, 0) = arg0 = builtin_save_expr (arg0);
2289   CALL_EXPR_ARG (exp, 1) = arg1 = builtin_save_expr (arg1);
2290   CALL_EXPR_ARG (exp, 2) = arg2 = builtin_save_expr (arg2);
2291
2292   op0 = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
2293   op1 = expand_normal (arg1);
2294   op2 = expand_normal (arg2);
2295
2296   start_sequence ();
2297
2298   /* Compute into RESULT.
2299      Set RESULT to wherever the result comes back.  */
2300   result = expand_ternary_op (mode, builtin_optab, op0, op1, op2,
2301                               result, 0);
2302
2303   /* If we were unable to expand via the builtin, stop the sequence
2304      (without outputting the insns) and call to the library function
2305      with the stabilized argument list.  */
2306   if (result == 0)
2307     {
2308       end_sequence ();
2309       return expand_call (exp, target, target == const0_rtx);
2310     }
2311
2312   /* Output the entire sequence.  */
2313   insns = get_insns ();
2314   end_sequence ();
2315   emit_insn (insns);
2316
2317   return result;
2318 }
2319
2320 /* Expand a call to the builtin sin and cos math functions.
2321    Return NULL_RTX if a normal call should be emitted rather than expanding the
2322    function in-line.  EXP is the expression that is a call to the builtin
2323    function; if convenient, the result should be placed in TARGET.
2324    SUBTARGET may be used as the target for computing one of EXP's
2325    operands.  */
2326
2327 static rtx
2328 expand_builtin_mathfn_3 (tree exp, rtx target, rtx subtarget)
2329 {
2330   optab builtin_optab;
2331   rtx op0, insns;
2332   tree fndecl = get_callee_fndecl (exp);
2333   enum machine_mode mode;
2334   tree arg;
2335
2336   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2337     return NULL_RTX;
2338
2339   arg = CALL_EXPR_ARG (exp, 0);
2340
2341   switch (DECL_FUNCTION_CODE (fndecl))
2342     {
2343     CASE_FLT_FN (BUILT_IN_SIN):
2344     CASE_FLT_FN (BUILT_IN_COS):
2345       builtin_optab = sincos_optab; break;
2346     default:
2347       gcc_unreachable ();
2348     }
2349
2350   /* Make a suitable register to place result in.  */
2351   mode = TYPE_MODE (TREE_TYPE (exp));
2352
2353   /* Check if sincos insn is available, otherwise fallback
2354      to sin or cos insn.  */
2355   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2356     switch (DECL_FUNCTION_CODE (fndecl))
2357       {
2358       CASE_FLT_FN (BUILT_IN_SIN):
2359         builtin_optab = sin_optab; break;
2360       CASE_FLT_FN (BUILT_IN_COS):
2361         builtin_optab = cos_optab; break;
2362       default:
2363         gcc_unreachable ();
2364       }
2365
2366   /* Before working hard, check whether the instruction is available.  */
2367   if (optab_handler (builtin_optab, mode) != CODE_FOR_nothing)
2368     {
2369       rtx result = gen_reg_rtx (mode);
2370
2371       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2372          need to expand the argument again.  This way, we will not perform
2373          side-effects more the once.  */
2374       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2375
2376       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2377
2378       start_sequence ();
2379
2380       /* Compute into RESULT.
2381          Set RESULT to wherever the result comes back.  */
2382       if (builtin_optab == sincos_optab)
2383         {
2384           int ok;
2385
2386           switch (DECL_FUNCTION_CODE (fndecl))
2387             {
2388             CASE_FLT_FN (BUILT_IN_SIN):
2389               ok = expand_twoval_unop (builtin_optab, op0, 0, result, 0);
2390               break;
2391             CASE_FLT_FN (BUILT_IN_COS):
2392               ok = expand_twoval_unop (builtin_optab, op0, result, 0, 0);
2393               break;
2394             default:
2395               gcc_unreachable ();
2396             }
2397           gcc_assert (ok);
2398         }
2399       else
2400         result = expand_unop (mode, builtin_optab, op0, result, 0);
2401
2402       if (result != 0)
2403         {
2404           /* Output the entire sequence.  */
2405           insns = get_insns ();
2406           end_sequence ();
2407           emit_insn (insns);
2408           return result;
2409         }
2410
2411       /* If we were unable to expand via the builtin, stop the sequence
2412          (without outputting the insns) and call to the library function
2413          with the stabilized argument list.  */
2414       end_sequence ();
2415     }
2416
2417   return expand_call (exp, target, target == const0_rtx);
2418 }
2419
2420 /* Given an interclass math builtin decl FNDECL and it's argument ARG
2421    return an RTL instruction code that implements the functionality.
2422    If that isn't possible or available return CODE_FOR_nothing.  */
2423
2424 static enum insn_code
2425 interclass_mathfn_icode (tree arg, tree fndecl)
2426 {
2427   bool errno_set = false;
2428   optab builtin_optab = unknown_optab;
2429   enum machine_mode mode;
2430
2431   switch (DECL_FUNCTION_CODE (fndecl))
2432     {
2433     CASE_FLT_FN (BUILT_IN_ILOGB):
2434       errno_set = true; builtin_optab = ilogb_optab; break;
2435     CASE_FLT_FN (BUILT_IN_ISINF):
2436       builtin_optab = isinf_optab; break;
2437     case BUILT_IN_ISNORMAL:
2438     case BUILT_IN_ISFINITE:
2439     CASE_FLT_FN (BUILT_IN_FINITE):
2440     case BUILT_IN_FINITED32:
2441     case BUILT_IN_FINITED64:
2442     case BUILT_IN_FINITED128:
2443     case BUILT_IN_ISINFD32:
2444     case BUILT_IN_ISINFD64:
2445     case BUILT_IN_ISINFD128:
2446       /* These builtins have no optabs (yet).  */
2447       break;
2448     default:
2449       gcc_unreachable ();
2450     }
2451
2452   /* There's no easy way to detect the case we need to set EDOM.  */
2453   if (flag_errno_math && errno_set)
2454     return CODE_FOR_nothing;
2455
2456   /* Optab mode depends on the mode of the input argument.  */
2457   mode = TYPE_MODE (TREE_TYPE (arg));
2458
2459   if (builtin_optab)
2460     return optab_handler (builtin_optab, mode);
2461   return CODE_FOR_nothing;
2462 }
2463
2464 /* Expand a call to one of the builtin math functions that operate on
2465    floating point argument and output an integer result (ilogb, isinf,
2466    isnan, etc).
2467    Return 0 if a normal call should be emitted rather than expanding the
2468    function in-line.  EXP is the expression that is a call to the builtin
2469    function; if convenient, the result should be placed in TARGET.  */
2470
2471 static rtx
2472 expand_builtin_interclass_mathfn (tree exp, rtx target)
2473 {
2474   enum insn_code icode = CODE_FOR_nothing;
2475   rtx op0;
2476   tree fndecl = get_callee_fndecl (exp);
2477   enum machine_mode mode;
2478   tree arg;
2479
2480   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2481     return NULL_RTX;
2482
2483   arg = CALL_EXPR_ARG (exp, 0);
2484   icode = interclass_mathfn_icode (arg, fndecl);
2485   mode = TYPE_MODE (TREE_TYPE (arg));
2486
2487   if (icode != CODE_FOR_nothing)
2488     {
2489       struct expand_operand ops[1];
2490       rtx last = get_last_insn ();
2491       tree orig_arg = arg;
2492
2493       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2494          need to expand the argument again.  This way, we will not perform
2495          side-effects more the once.  */
2496       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2497
2498       op0 = expand_expr (arg, NULL_RTX, VOIDmode, EXPAND_NORMAL);
2499
2500       if (mode != GET_MODE (op0))
2501         op0 = convert_to_mode (mode, op0, 0);
2502
2503       create_output_operand (&ops[0], target, TYPE_MODE (TREE_TYPE (exp)));
2504       if (maybe_legitimize_operands (icode, 0, 1, ops)
2505           && maybe_emit_unop_insn (icode, ops[0].value, op0, UNKNOWN))
2506         return ops[0].value;
2507
2508       delete_insns_since (last);
2509       CALL_EXPR_ARG (exp, 0) = orig_arg;
2510     }
2511
2512   return NULL_RTX;
2513 }
2514
2515 /* Expand a call to the builtin sincos math function.
2516    Return NULL_RTX if a normal call should be emitted rather than expanding the
2517    function in-line.  EXP is the expression that is a call to the builtin
2518    function.  */
2519
2520 static rtx
2521 expand_builtin_sincos (tree exp)
2522 {
2523   rtx op0, op1, op2, target1, target2;
2524   enum machine_mode mode;
2525   tree arg, sinp, cosp;
2526   int result;
2527   location_t loc = EXPR_LOCATION (exp);
2528   tree alias_type, alias_off;
2529
2530   if (!validate_arglist (exp, REAL_TYPE,
2531                          POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
2532     return NULL_RTX;
2533
2534   arg = CALL_EXPR_ARG (exp, 0);
2535   sinp = CALL_EXPR_ARG (exp, 1);
2536   cosp = CALL_EXPR_ARG (exp, 2);
2537
2538   /* Make a suitable register to place result in.  */
2539   mode = TYPE_MODE (TREE_TYPE (arg));
2540
2541   /* Check if sincos insn is available, otherwise emit the call.  */
2542   if (optab_handler (sincos_optab, mode) == CODE_FOR_nothing)
2543     return NULL_RTX;
2544
2545   target1 = gen_reg_rtx (mode);
2546   target2 = gen_reg_rtx (mode);
2547
2548   op0 = expand_normal (arg);
2549   alias_type = build_pointer_type_for_mode (TREE_TYPE (arg), ptr_mode, true);
2550   alias_off = build_int_cst (alias_type, 0);
2551   op1 = expand_normal (fold_build2_loc (loc, MEM_REF, TREE_TYPE (arg),
2552                                         sinp, alias_off));
2553   op2 = expand_normal (fold_build2_loc (loc, MEM_REF, TREE_TYPE (arg),
2554                                         cosp, alias_off));
2555
2556   /* Compute into target1 and target2.
2557      Set TARGET to wherever the result comes back.  */
2558   result = expand_twoval_unop (sincos_optab, op0, target2, target1, 0);
2559   gcc_assert (result);
2560
2561   /* Move target1 and target2 to the memory locations indicated
2562      by op1 and op2.  */
2563   emit_move_insn (op1, target1);
2564   emit_move_insn (op2, target2);
2565
2566   return const0_rtx;
2567 }
2568
2569 /* Expand a call to the internal cexpi builtin to the sincos math function.
2570    EXP is the expression that is a call to the builtin function; if convenient,
2571    the result should be placed in TARGET.  */
2572
2573 static rtx
2574 expand_builtin_cexpi (tree exp, rtx target)
2575 {
2576   tree fndecl = get_callee_fndecl (exp);
2577   tree arg, type;
2578   enum machine_mode mode;
2579   rtx op0, op1, op2;
2580   location_t loc = EXPR_LOCATION (exp);
2581
2582   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2583     return NULL_RTX;
2584
2585   arg = CALL_EXPR_ARG (exp, 0);
2586   type = TREE_TYPE (arg);
2587   mode = TYPE_MODE (TREE_TYPE (arg));
2588
2589   /* Try expanding via a sincos optab, fall back to emitting a libcall
2590      to sincos or cexp.  We are sure we have sincos or cexp because cexpi
2591      is only generated from sincos, cexp or if we have either of them.  */
2592   if (optab_handler (sincos_optab, mode) != CODE_FOR_nothing)
2593     {
2594       op1 = gen_reg_rtx (mode);
2595       op2 = gen_reg_rtx (mode);
2596
2597       op0 = expand_expr (arg, NULL_RTX, VOIDmode, EXPAND_NORMAL);
2598
2599       /* Compute into op1 and op2.  */
2600       expand_twoval_unop (sincos_optab, op0, op2, op1, 0);
2601     }
2602   else if (targetm.libc_has_function (function_sincos))
2603     {
2604       tree call, fn = NULL_TREE;
2605       tree top1, top2;
2606       rtx op1a, op2a;
2607
2608       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2609         fn = builtin_decl_explicit (BUILT_IN_SINCOSF);
2610       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2611         fn = builtin_decl_explicit (BUILT_IN_SINCOS);
2612       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2613         fn = builtin_decl_explicit (BUILT_IN_SINCOSL);
2614       else
2615         gcc_unreachable ();
2616
2617       op1 = assign_temp (TREE_TYPE (arg), 1, 1);
2618       op2 = assign_temp (TREE_TYPE (arg), 1, 1);
2619       op1a = copy_addr_to_reg (XEXP (op1, 0));
2620       op2a = copy_addr_to_reg (XEXP (op2, 0));
2621       top1 = make_tree (build_pointer_type (TREE_TYPE (arg)), op1a);
2622       top2 = make_tree (build_pointer_type (TREE_TYPE (arg)), op2a);
2623
2624       /* Make sure not to fold the sincos call again.  */
2625       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2626       expand_normal (build_call_nary (TREE_TYPE (TREE_TYPE (fn)),
2627                                       call, 3, arg, top1, top2));
2628     }
2629   else
2630     {
2631       tree call, fn = NULL_TREE, narg;
2632       tree ctype = build_complex_type (type);
2633
2634       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2635         fn = builtin_decl_explicit (BUILT_IN_CEXPF);
2636       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2637         fn = builtin_decl_explicit (BUILT_IN_CEXP);
2638       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2639         fn = builtin_decl_explicit (BUILT_IN_CEXPL);
2640       else
2641         gcc_unreachable ();
2642
2643       /* If we don't have a decl for cexp create one.  This is the
2644          friendliest fallback if the user calls __builtin_cexpi
2645          without full target C99 function support.  */
2646       if (fn == NULL_TREE)
2647         {
2648           tree fntype;
2649           const char *name = NULL;
2650
2651           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2652             name = "cexpf";
2653           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2654             name = "cexp";
2655           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2656             name = "cexpl";
2657
2658           fntype = build_function_type_list (ctype, ctype, NULL_TREE);
2659           fn = build_fn_decl (name, fntype);
2660         }
2661
2662       narg = fold_build2_loc (loc, COMPLEX_EXPR, ctype,
2663                           build_real (type, dconst0), arg);
2664
2665       /* Make sure not to fold the cexp call again.  */
2666       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2667       return expand_expr (build_call_nary (ctype, call, 1, narg),
2668                           target, VOIDmode, EXPAND_NORMAL);
2669     }
2670
2671   /* Now build the proper return type.  */
2672   return expand_expr (build2 (COMPLEX_EXPR, build_complex_type (type),
2673                               make_tree (TREE_TYPE (arg), op2),
2674                               make_tree (TREE_TYPE (arg), op1)),
2675                       target, VOIDmode, EXPAND_NORMAL);
2676 }
2677
2678 /* Conveniently construct a function call expression.  FNDECL names the
2679    function to be called, N is the number of arguments, and the "..."
2680    parameters are the argument expressions.  Unlike build_call_exr
2681    this doesn't fold the call, hence it will always return a CALL_EXPR.  */
2682
2683 static tree
2684 build_call_nofold_loc (location_t loc, tree fndecl, int n, ...)
2685 {
2686   va_list ap;
2687   tree fntype = TREE_TYPE (fndecl);
2688   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
2689
2690   va_start (ap, n);
2691   fn = build_call_valist (TREE_TYPE (fntype), fn, n, ap);
2692   va_end (ap);
2693   SET_EXPR_LOCATION (fn, loc);
2694   return fn;
2695 }
2696
2697 /* Expand a call to one of the builtin rounding functions gcc defines
2698    as an extension (lfloor and lceil).  As these are gcc extensions we
2699    do not need to worry about setting errno to EDOM.
2700    If expanding via optab fails, lower expression to (int)(floor(x)).
2701    EXP is the expression that is a call to the builtin function;
2702    if convenient, the result should be placed in TARGET.  */
2703
2704 static rtx
2705 expand_builtin_int_roundingfn (tree exp, rtx target)
2706 {
2707   convert_optab builtin_optab;
2708   rtx op0, insns, tmp;
2709   tree fndecl = get_callee_fndecl (exp);
2710   enum built_in_function fallback_fn;
2711   tree fallback_fndecl;
2712   enum machine_mode mode;
2713   tree arg;
2714
2715   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2716     gcc_unreachable ();
2717
2718   arg = CALL_EXPR_ARG (exp, 0);
2719
2720   switch (DECL_FUNCTION_CODE (fndecl))
2721     {
2722     CASE_FLT_FN (BUILT_IN_ICEIL):
2723     CASE_FLT_FN (BUILT_IN_LCEIL):
2724     CASE_FLT_FN (BUILT_IN_LLCEIL):
2725       builtin_optab = lceil_optab;
2726       fallback_fn = BUILT_IN_CEIL;
2727       break;
2728
2729     CASE_FLT_FN (BUILT_IN_IFLOOR):
2730     CASE_FLT_FN (BUILT_IN_LFLOOR):
2731     CASE_FLT_FN (BUILT_IN_LLFLOOR):
2732       builtin_optab = lfloor_optab;
2733       fallback_fn = BUILT_IN_FLOOR;
2734       break;
2735
2736     default:
2737       gcc_unreachable ();
2738     }
2739
2740   /* Make a suitable register to place result in.  */
2741   mode = TYPE_MODE (TREE_TYPE (exp));
2742
2743   target = gen_reg_rtx (mode);
2744
2745   /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2746      need to expand the argument again.  This way, we will not perform
2747      side-effects more the once.  */
2748   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2749
2750   op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2751
2752   start_sequence ();
2753
2754   /* Compute into TARGET.  */
2755   if (expand_sfix_optab (target, op0, builtin_optab))
2756     {
2757       /* Output the entire sequence.  */
2758       insns = get_insns ();
2759       end_sequence ();
2760       emit_insn (insns);
2761       return target;
2762     }
2763
2764   /* If we were unable to expand via the builtin, stop the sequence
2765      (without outputting the insns).  */
2766   end_sequence ();
2767
2768   /* Fall back to floating point rounding optab.  */
2769   fallback_fndecl = mathfn_built_in (TREE_TYPE (arg), fallback_fn);
2770
2771   /* For non-C99 targets we may end up without a fallback fndecl here
2772      if the user called __builtin_lfloor directly.  In this case emit
2773      a call to the floor/ceil variants nevertheless.  This should result
2774      in the best user experience for not full C99 targets.  */
2775   if (fallback_fndecl == NULL_TREE)
2776     {
2777       tree fntype;
2778       const char *name = NULL;
2779
2780       switch (DECL_FUNCTION_CODE (fndecl))
2781         {
2782         case BUILT_IN_ICEIL:
2783         case BUILT_IN_LCEIL:
2784         case BUILT_IN_LLCEIL:
2785           name = "ceil";
2786           break;
2787         case BUILT_IN_ICEILF:
2788         case BUILT_IN_LCEILF:
2789         case BUILT_IN_LLCEILF:
2790           name = "ceilf";
2791           break;
2792         case BUILT_IN_ICEILL:
2793         case BUILT_IN_LCEILL:
2794         case BUILT_IN_LLCEILL:
2795           name = "ceill";
2796           break;
2797         case BUILT_IN_IFLOOR:
2798         case BUILT_IN_LFLOOR:
2799         case BUILT_IN_LLFLOOR:
2800           name = "floor";
2801           break;
2802         case BUILT_IN_IFLOORF:
2803         case BUILT_IN_LFLOORF:
2804         case BUILT_IN_LLFLOORF:
2805           name = "floorf";
2806           break;
2807         case BUILT_IN_IFLOORL:
2808         case BUILT_IN_LFLOORL:
2809         case BUILT_IN_LLFLOORL:
2810           name = "floorl";
2811           break;
2812         default:
2813           gcc_unreachable ();
2814         }
2815
2816       fntype = build_function_type_list (TREE_TYPE (arg),
2817                                          TREE_TYPE (arg), NULL_TREE);
2818       fallback_fndecl = build_fn_decl (name, fntype);
2819     }
2820
2821   exp = build_call_nofold_loc (EXPR_LOCATION (exp), fallback_fndecl, 1, arg);
2822
2823   tmp = expand_normal (exp);
2824   tmp = maybe_emit_group_store (tmp, TREE_TYPE (exp));
2825
2826   /* Truncate the result of floating point optab to integer
2827      via expand_fix ().  */
2828   target = gen_reg_rtx (mode);
2829   expand_fix (target, tmp, 0);
2830
2831   return target;
2832 }
2833
2834 /* Expand a call to one of the builtin math functions doing integer
2835    conversion (lrint).
2836    Return 0 if a normal call should be emitted rather than expanding the
2837    function in-line.  EXP is the expression that is a call to the builtin
2838    function; if convenient, the result should be placed in TARGET.  */
2839
2840 static rtx
2841 expand_builtin_int_roundingfn_2 (tree exp, rtx target)
2842 {
2843   convert_optab builtin_optab;
2844   rtx op0, insns;
2845   tree fndecl = get_callee_fndecl (exp);
2846   tree arg;
2847   enum machine_mode mode;
2848   enum built_in_function fallback_fn = BUILT_IN_NONE;
2849
2850   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2851      gcc_unreachable ();
2852
2853   arg = CALL_EXPR_ARG (exp, 0);
2854
2855   switch (DECL_FUNCTION_CODE (fndecl))
2856     {
2857     CASE_FLT_FN (BUILT_IN_IRINT):
2858       fallback_fn = BUILT_IN_LRINT;
2859       /* FALLTHRU */
2860     CASE_FLT_FN (BUILT_IN_LRINT):
2861     CASE_FLT_FN (BUILT_IN_LLRINT):
2862       builtin_optab = lrint_optab;
2863       break;
2864
2865     CASE_FLT_FN (BUILT_IN_IROUND):
2866       fallback_fn = BUILT_IN_LROUND;
2867       /* FALLTHRU */
2868     CASE_FLT_FN (BUILT_IN_LROUND):
2869     CASE_FLT_FN (BUILT_IN_LLROUND):
2870       builtin_optab = lround_optab;
2871       break;
2872
2873     default:
2874       gcc_unreachable ();
2875     }
2876
2877   /* There's no easy way to detect the case we need to set EDOM.  */
2878   if (flag_errno_math && fallback_fn == BUILT_IN_NONE)
2879     return NULL_RTX;
2880
2881   /* Make a suitable register to place result in.  */
2882   mode = TYPE_MODE (TREE_TYPE (exp));
2883
2884   /* There's no easy way to detect the case we need to set EDOM.  */
2885   if (!flag_errno_math)
2886     {
2887       rtx result = gen_reg_rtx (mode);
2888
2889       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2890          need to expand the argument again.  This way, we will not perform
2891          side-effects more the once.  */
2892       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2893
2894       op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2895
2896       start_sequence ();
2897
2898       if (expand_sfix_optab (result, op0, builtin_optab))
2899         {
2900           /* Output the entire sequence.  */
2901           insns = get_insns ();
2902           end_sequence ();
2903           emit_insn (insns);
2904           return result;
2905         }
2906
2907       /* If we were unable to expand via the builtin, stop the sequence
2908          (without outputting the insns) and call to the library function
2909          with the stabilized argument list.  */
2910       end_sequence ();
2911     }
2912
2913   if (fallback_fn != BUILT_IN_NONE)
2914     {
2915       /* Fall back to rounding to long int.  Use implicit_p 0 - for non-C99
2916          targets, (int) round (x) should never be transformed into
2917          BUILT_IN_IROUND and if __builtin_iround is called directly, emit
2918          a call to lround in the hope that the target provides at least some
2919          C99 functions.  This should result in the best user experience for
2920          not full C99 targets.  */
2921       tree fallback_fndecl = mathfn_built_in_1 (TREE_TYPE (arg),
2922                                                 fallback_fn, 0);
2923
2924       exp = build_call_nofold_loc (EXPR_LOCATION (exp),
2925                                    fallback_fndecl, 1, arg);
2926
2927       target = expand_call (exp, NULL_RTX, target == const0_rtx);
2928       target = maybe_emit_group_store (target, TREE_TYPE (exp));
2929       return convert_to_mode (mode, target, 0);
2930     }
2931
2932   return expand_call (exp, target, target == const0_rtx);
2933 }
2934
2935 /* Expand a call to the powi built-in mathematical function.  Return NULL_RTX if
2936    a normal call should be emitted rather than expanding the function
2937    in-line.  EXP is the expression that is a call to the builtin
2938    function; if convenient, the result should be placed in TARGET.  */
2939
2940 static rtx
2941 expand_builtin_powi (tree exp, rtx target)
2942 {
2943   tree arg0, arg1;
2944   rtx op0, op1;
2945   enum machine_mode mode;
2946   enum machine_mode mode2;
2947
2948   if (! validate_arglist (exp, REAL_TYPE, INTEGER_TYPE, VOID_TYPE))
2949     return NULL_RTX;
2950
2951   arg0 = CALL_EXPR_ARG (exp, 0);
2952   arg1 = CALL_EXPR_ARG (exp, 1);
2953   mode = TYPE_MODE (TREE_TYPE (exp));
2954
2955   /* Emit a libcall to libgcc.  */
2956
2957   /* Mode of the 2nd argument must match that of an int.  */
2958   mode2 = mode_for_size (INT_TYPE_SIZE, MODE_INT, 0);
2959
2960   if (target == NULL_RTX)
2961     target = gen_reg_rtx (mode);
2962
2963   op0 = expand_expr (arg0, NULL_RTX, mode, EXPAND_NORMAL);
2964   if (GET_MODE (op0) != mode)
2965     op0 = convert_to_mode (mode, op0, 0);
2966   op1 = expand_expr (arg1, NULL_RTX, mode2, EXPAND_NORMAL);
2967   if (GET_MODE (op1) != mode2)
2968     op1 = convert_to_mode (mode2, op1, 0);
2969
2970   target = emit_library_call_value (optab_libfunc (powi_optab, mode),
2971                                     target, LCT_CONST, mode, 2,
2972                                     op0, mode, op1, mode2);
2973
2974   return target;
2975 }
2976
2977 /* Expand expression EXP which is a call to the strlen builtin.  Return
2978    NULL_RTX if we failed the caller should emit a normal call, otherwise
2979    try to get the result in TARGET, if convenient.  */
2980
2981 static rtx
2982 expand_builtin_strlen (tree exp, rtx target,
2983                        enum machine_mode target_mode)
2984 {
2985   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
2986     return NULL_RTX;
2987   else
2988     {
2989       struct expand_operand ops[4];
2990       rtx pat;
2991       tree len;
2992       tree src = CALL_EXPR_ARG (exp, 0);
2993       rtx src_reg, before_strlen;
2994       enum machine_mode insn_mode = target_mode;
2995       enum insn_code icode = CODE_FOR_nothing;
2996       unsigned int align;
2997
2998       /* If the length can be computed at compile-time, return it.  */
2999       len = c_strlen (src, 0);
3000       if (len)
3001         return expand_expr (len, target, target_mode, EXPAND_NORMAL);
3002
3003       /* If the length can be computed at compile-time and is constant
3004          integer, but there are side-effects in src, evaluate
3005          src for side-effects, then return len.
3006          E.g. x = strlen (i++ ? "xfoo" + 1 : "bar");
3007          can be optimized into: i++; x = 3;  */
3008       len = c_strlen (src, 1);
3009       if (len && TREE_CODE (len) == INTEGER_CST)
3010         {
3011           expand_expr (src, const0_rtx, VOIDmode, EXPAND_NORMAL);
3012           return expand_expr (len, target, target_mode, EXPAND_NORMAL);
3013         }
3014
3015       align = get_pointer_alignment (src) / BITS_PER_UNIT;
3016
3017       /* If SRC is not a pointer type, don't do this operation inline.  */
3018       if (align == 0)
3019         return NULL_RTX;
3020
3021       /* Bail out if we can't compute strlen in the right mode.  */
3022       while (insn_mode != VOIDmode)
3023         {
3024           icode = optab_handler (strlen_optab, insn_mode);
3025           if (icode != CODE_FOR_nothing)
3026             break;
3027
3028           insn_mode = GET_MODE_WIDER_MODE (insn_mode);
3029         }
3030       if (insn_mode == VOIDmode)
3031         return NULL_RTX;
3032
3033       /* Make a place to hold the source address.  We will not expand
3034          the actual source until we are sure that the expansion will
3035          not fail -- there are trees that cannot be expanded twice.  */
3036       src_reg = gen_reg_rtx (Pmode);
3037
3038       /* Mark the beginning of the strlen sequence so we can emit the
3039          source operand later.  */
3040       before_strlen = get_last_insn ();
3041
3042       create_output_operand (&ops[0], target, insn_mode);
3043       create_fixed_operand (&ops[1], gen_rtx_MEM (BLKmode, src_reg));
3044       create_integer_operand (&ops[2], 0);
3045       create_integer_operand (&ops[3], align);
3046       if (!maybe_expand_insn (icode, 4, ops))
3047         return NULL_RTX;
3048
3049       /* Now that we are assured of success, expand the source.  */
3050       start_sequence ();
3051       pat = expand_expr (src, src_reg, Pmode, EXPAND_NORMAL);
3052       if (pat != src_reg)
3053         {
3054 #ifdef POINTERS_EXTEND_UNSIGNED
3055           if (GET_MODE (pat) != Pmode)
3056             pat = convert_to_mode (Pmode, pat,
3057                                    POINTERS_EXTEND_UNSIGNED);
3058 #endif
3059           emit_move_insn (src_reg, pat);
3060         }
3061       pat = get_insns ();
3062       end_sequence ();
3063
3064       if (before_strlen)
3065         emit_insn_after (pat, before_strlen);
3066       else
3067         emit_insn_before (pat, get_insns ());
3068
3069       /* Return the value in the proper mode for this function.  */
3070       if (GET_MODE (ops[0].value) == target_mode)
3071         target = ops[0].value;
3072       else if (target != 0)
3073         convert_move (target, ops[0].value, 0);
3074       else
3075         target = convert_to_mode (target_mode, ops[0].value, 0);
3076
3077       return target;
3078     }
3079 }
3080
3081 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3082    bytes from constant string DATA + OFFSET and return it as target
3083    constant.  */
3084
3085 static rtx
3086 builtin_memcpy_read_str (void *data, HOST_WIDE_INT offset,
3087                          enum machine_mode mode)
3088 {
3089   const char *str = (const char *) data;
3090
3091   gcc_assert (offset >= 0
3092               && ((unsigned HOST_WIDE_INT) offset + GET_MODE_SIZE (mode)
3093                   <= strlen (str) + 1));
3094
3095   return c_readstr (str + offset, mode);
3096 }
3097
3098 /* Expand a call EXP to the memcpy builtin.
3099    Return NULL_RTX if we failed, the caller should emit a normal call,
3100    otherwise try to get the result in TARGET, if convenient (and in
3101    mode MODE if that's convenient).  */
3102
3103 static rtx
3104 expand_builtin_memcpy (tree exp, rtx target)
3105 {
3106   if (!validate_arglist (exp,
3107                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3108     return NULL_RTX;
3109   else
3110     {
3111       tree dest = CALL_EXPR_ARG (exp, 0);
3112       tree src = CALL_EXPR_ARG (exp, 1);
3113       tree len = CALL_EXPR_ARG (exp, 2);
3114       const char *src_str;
3115       unsigned int src_align = get_pointer_alignment (src);
3116       unsigned int dest_align = get_pointer_alignment (dest);
3117       rtx dest_mem, src_mem, dest_addr, len_rtx;
3118       HOST_WIDE_INT expected_size = -1;
3119       unsigned int expected_align = 0;
3120
3121       /* If DEST is not a pointer type, call the normal function.  */
3122       if (dest_align == 0)
3123         return NULL_RTX;
3124
3125       /* If either SRC is not a pointer type, don't do this
3126          operation in-line.  */
3127       if (src_align == 0)
3128         return NULL_RTX;
3129
3130       if (currently_expanding_gimple_stmt)
3131         stringop_block_profile (currently_expanding_gimple_stmt,
3132                                 &expected_align, &expected_size);
3133
3134       if (expected_align < dest_align)
3135         expected_align = dest_align;
3136       dest_mem = get_memory_rtx (dest, len);
3137       set_mem_align (dest_mem, dest_align);
3138       len_rtx = expand_normal (len);
3139       src_str = c_getstr (src);
3140
3141       /* If SRC is a string constant and block move would be done
3142          by pieces, we can avoid loading the string from memory
3143          and only stored the computed constants.  */
3144       if (src_str
3145           && CONST_INT_P (len_rtx)
3146           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
3147           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
3148                                   CONST_CAST (char *, src_str),
3149                                   dest_align, false))
3150         {
3151           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
3152                                       builtin_memcpy_read_str,
3153                                       CONST_CAST (char *, src_str),
3154                                       dest_align, false, 0);
3155           dest_mem = force_operand (XEXP (dest_mem, 0), target);
3156           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3157           return dest_mem;
3158         }
3159
3160       src_mem = get_memory_rtx (src, len);
3161       set_mem_align (src_mem, src_align);
3162
3163       /* Copy word part most expediently.  */
3164       dest_addr = emit_block_move_hints (dest_mem, src_mem, len_rtx,
3165                                          CALL_EXPR_TAILCALL (exp)
3166                                          ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
3167                                          expected_align, expected_size);
3168
3169       if (dest_addr == 0)
3170         {
3171           dest_addr = force_operand (XEXP (dest_mem, 0), target);
3172           dest_addr = convert_memory_address (ptr_mode, dest_addr);
3173         }
3174       return dest_addr;
3175     }
3176 }
3177
3178 /* Expand a call EXP to the mempcpy builtin.
3179    Return NULL_RTX if we failed; the caller should emit a normal call,
3180    otherwise try to get the result in TARGET, if convenient (and in
3181    mode MODE if that's convenient).  If ENDP is 0 return the
3182    destination pointer, if ENDP is 1 return the end pointer ala
3183    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3184    stpcpy.  */
3185
3186 static rtx
3187 expand_builtin_mempcpy (tree exp, rtx target, enum machine_mode mode)
3188 {
3189   if (!validate_arglist (exp,
3190                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3191     return NULL_RTX;
3192   else
3193     {
3194       tree dest = CALL_EXPR_ARG (exp, 0);
3195       tree src = CALL_EXPR_ARG (exp, 1);
3196       tree len = CALL_EXPR_ARG (exp, 2);
3197       return expand_builtin_mempcpy_args (dest, src, len,
3198                                           target, mode, /*endp=*/ 1);
3199     }
3200 }
3201
3202 /* Helper function to do the actual work for expand_builtin_mempcpy.  The
3203    arguments to the builtin_mempcpy call DEST, SRC, and LEN are broken out
3204    so that this can also be called without constructing an actual CALL_EXPR.
3205    The other arguments and return value are the same as for
3206    expand_builtin_mempcpy.  */
3207
3208 static rtx
3209 expand_builtin_mempcpy_args (tree dest, tree src, tree len,
3210                              rtx target, enum machine_mode mode, int endp)
3211 {
3212     /* If return value is ignored, transform mempcpy into memcpy.  */
3213   if (target == const0_rtx && builtin_decl_implicit_p (BUILT_IN_MEMCPY))
3214     {
3215       tree fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
3216       tree result = build_call_nofold_loc (UNKNOWN_LOCATION, fn, 3,
3217                                            dest, src, len);
3218       return expand_expr (result, target, mode, EXPAND_NORMAL);
3219     }
3220   else
3221     {
3222       const char *src_str;
3223       unsigned int src_align = get_pointer_alignment (src);
3224       unsigned int dest_align = get_pointer_alignment (dest);
3225       rtx dest_mem, src_mem, len_rtx;
3226
3227       /* If either SRC or DEST is not a pointer type, don't do this
3228          operation in-line.  */
3229       if (dest_align == 0 || src_align == 0)
3230         return NULL_RTX;
3231
3232       /* If LEN is not constant, call the normal function.  */
3233       if (! host_integerp (len, 1))
3234         return NULL_RTX;
3235
3236       len_rtx = expand_normal (len);
3237       src_str = c_getstr (src);
3238
3239       /* If SRC is a string constant and block move would be done
3240          by pieces, we can avoid loading the string from memory
3241          and only stored the computed constants.  */
3242       if (src_str
3243           && CONST_INT_P (len_rtx)
3244           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
3245           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
3246                                   CONST_CAST (char *, src_str),
3247                                   dest_align, false))
3248         {
3249           dest_mem = get_memory_rtx (dest, len);
3250           set_mem_align (dest_mem, dest_align);
3251           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
3252                                       builtin_memcpy_read_str,
3253                                       CONST_CAST (char *, src_str),
3254                                       dest_align, false, endp);
3255           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3256           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3257           return dest_mem;
3258         }
3259
3260       if (CONST_INT_P (len_rtx)
3261           && can_move_by_pieces (INTVAL (len_rtx),
3262                                  MIN (dest_align, src_align)))
3263         {
3264           dest_mem = get_memory_rtx (dest, len);
3265           set_mem_align (dest_mem, dest_align);
3266           src_mem = get_memory_rtx (src, len);
3267           set_mem_align (src_mem, src_align);
3268           dest_mem = move_by_pieces (dest_mem, src_mem, INTVAL (len_rtx),
3269                                      MIN (dest_align, src_align), endp);
3270           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3271           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3272           return dest_mem;
3273         }
3274
3275       return NULL_RTX;
3276     }
3277 }
3278
3279 #ifndef HAVE_movstr
3280 # define HAVE_movstr 0
3281 # define CODE_FOR_movstr CODE_FOR_nothing
3282 #endif
3283
3284 /* Expand into a movstr instruction, if one is available.  Return NULL_RTX if
3285    we failed, the caller should emit a normal call, otherwise try to
3286    get the result in TARGET, if convenient.  If ENDP is 0 return the
3287    destination pointer, if ENDP is 1 return the end pointer ala
3288    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3289    stpcpy.  */
3290
3291 static rtx
3292 expand_movstr (tree dest, tree src, rtx target, int endp)
3293 {
3294   struct expand_operand ops[3];
3295   rtx dest_mem;
3296   rtx src_mem;
3297
3298   if (!HAVE_movstr)
3299     return NULL_RTX;
3300
3301   dest_mem = get_memory_rtx (dest, NULL);
3302   src_mem = get_memory_rtx (src, NULL);
3303   if (!endp)
3304     {
3305       target = force_reg (Pmode, XEXP (dest_mem, 0));
3306       dest_mem = replace_equiv_address (dest_mem, target);
3307     }
3308
3309   create_output_operand (&ops[0], endp ? target : NULL_RTX, Pmode);
3310   create_fixed_operand (&ops[1], dest_mem);
3311   create_fixed_operand (&ops[2], src_mem);
3312   expand_insn (CODE_FOR_movstr, 3, ops);
3313
3314   if (endp && target != const0_rtx)
3315     {
3316       target = ops[0].value;
3317       /* movstr is supposed to set end to the address of the NUL
3318          terminator.  If the caller requested a mempcpy-like return value,
3319          adjust it.  */
3320       if (endp == 1)
3321         {
3322           rtx tem = plus_constant (GET_MODE (target),
3323                                    gen_lowpart (GET_MODE (target), target), 1);
3324           emit_move_insn (target, force_operand (tem, NULL_RTX));
3325         }
3326     }
3327   return target;
3328 }
3329
3330 /* Expand expression EXP, which is a call to the strcpy builtin.  Return
3331    NULL_RTX if we failed the caller should emit a normal call, otherwise
3332    try to get the result in TARGET, if convenient (and in mode MODE if that's
3333    convenient).  */
3334
3335 static rtx
3336 expand_builtin_strcpy (tree exp, rtx target)
3337 {
3338   if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3339    {
3340      tree dest = CALL_EXPR_ARG (exp, 0);
3341      tree src = CALL_EXPR_ARG (exp, 1);
3342      return expand_builtin_strcpy_args (dest, src, target);
3343    }
3344    return NULL_RTX;
3345 }
3346
3347 /* Helper function to do the actual work for expand_builtin_strcpy.  The
3348    arguments to the builtin_strcpy call DEST and SRC are broken out
3349    so that this can also be called without constructing an actual CALL_EXPR.
3350    The other arguments and return value are the same as for
3351    expand_builtin_strcpy.  */
3352
3353 static rtx
3354 expand_builtin_strcpy_args (tree dest, tree src, rtx target)
3355 {
3356   return expand_movstr (dest, src, target, /*endp=*/0);
3357 }
3358
3359 /* Expand a call EXP to the stpcpy builtin.
3360    Return NULL_RTX if we failed the caller should emit a normal call,
3361    otherwise try to get the result in TARGET, if convenient (and in
3362    mode MODE if that's convenient).  */
3363
3364 static rtx
3365 expand_builtin_stpcpy (tree exp, rtx target, enum machine_mode mode)
3366 {
3367   tree dst, src;
3368   location_t loc = EXPR_LOCATION (exp);
3369
3370   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3371     return NULL_RTX;
3372
3373   dst = CALL_EXPR_ARG (exp, 0);
3374   src = CALL_EXPR_ARG (exp, 1);
3375
3376   /* If return value is ignored, transform stpcpy into strcpy.  */
3377   if (target == const0_rtx && builtin_decl_implicit (BUILT_IN_STRCPY))
3378     {
3379       tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
3380       tree result = build_call_nofold_loc (loc, fn, 2, dst, src);
3381       return expand_expr (result, target, mode, EXPAND_NORMAL);
3382     }
3383   else
3384     {
3385       tree len, lenp1;
3386       rtx ret;
3387
3388       /* Ensure we get an actual string whose length can be evaluated at
3389          compile-time, not an expression containing a string.  This is
3390          because the latter will potentially produce pessimized code
3391          when used to produce the return value.  */
3392       if (! c_getstr (src) || ! (len = c_strlen (src, 0)))
3393         return expand_movstr (dst, src, target, /*endp=*/2);
3394
3395       lenp1 = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
3396       ret = expand_builtin_mempcpy_args (dst, src, lenp1,
3397                                          target, mode, /*endp=*/2);
3398
3399       if (ret)
3400         return ret;
3401
3402       if (TREE_CODE (len) == INTEGER_CST)
3403         {
3404           rtx len_rtx = expand_normal (len);
3405
3406           if (CONST_INT_P (len_rtx))
3407             {
3408               ret = expand_builtin_strcpy_args (dst, src, target);
3409
3410               if (ret)
3411                 {
3412                   if (! target)
3413                     {
3414                       if (mode != VOIDmode)
3415                         target = gen_reg_rtx (mode);
3416                       else
3417                         target = gen_reg_rtx (GET_MODE (ret));
3418                     }
3419                   if (GET_MODE (target) != GET_MODE (ret))
3420                     ret = gen_lowpart (GET_MODE (target), ret);
3421
3422                   ret = plus_constant (GET_MODE (ret), ret, INTVAL (len_rtx));
3423                   ret = emit_move_insn (target, force_operand (ret, NULL_RTX));
3424                   gcc_assert (ret);
3425
3426                   return target;
3427                 }
3428             }
3429         }
3430
3431       return expand_movstr (dst, src, target, /*endp=*/2);
3432     }
3433 }
3434
3435 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3436    bytes from constant string DATA + OFFSET and return it as target
3437    constant.  */
3438
3439 rtx
3440 builtin_strncpy_read_str (void *data, HOST_WIDE_INT offset,
3441                           enum machine_mode mode)
3442 {
3443   const char *str = (const char *) data;
3444
3445   if ((unsigned HOST_WIDE_INT) offset > strlen (str))
3446     return const0_rtx;
3447
3448   return c_readstr (str + offset, mode);
3449 }
3450
3451 /* Expand expression EXP, which is a call to the strncpy builtin.  Return
3452    NULL_RTX if we failed the caller should emit a normal call.  */
3453
3454 static rtx
3455 expand_builtin_strncpy (tree exp, rtx target)
3456 {
3457   location_t loc = EXPR_LOCATION (exp);
3458
3459   if (validate_arglist (exp,
3460                         POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3461     {
3462       tree dest = CALL_EXPR_ARG (exp, 0);
3463       tree src = CALL_EXPR_ARG (exp, 1);
3464       tree len = CALL_EXPR_ARG (exp, 2);
3465       tree slen = c_strlen (src, 1);
3466
3467       /* We must be passed a constant len and src parameter.  */
3468       if (!host_integerp (len, 1) || !slen || !host_integerp (slen, 1))
3469         return NULL_RTX;
3470
3471       slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
3472
3473       /* We're required to pad with trailing zeros if the requested
3474          len is greater than strlen(s2)+1.  In that case try to
3475          use store_by_pieces, if it fails, punt.  */
3476       if (tree_int_cst_lt (slen, len))
3477         {
3478           unsigned int dest_align = get_pointer_alignment (dest);
3479           const char *p = c_getstr (src);
3480           rtx dest_mem;
3481
3482           if (!p || dest_align == 0 || !host_integerp (len, 1)
3483               || !can_store_by_pieces (tree_low_cst (len, 1),
3484                                        builtin_strncpy_read_str,
3485                                        CONST_CAST (char *, p),
3486                                        dest_align, false))
3487             return NULL_RTX;
3488
3489           dest_mem = get_memory_rtx (dest, len);
3490           store_by_pieces (dest_mem, tree_low_cst (len, 1),
3491                            builtin_strncpy_read_str,
3492                            CONST_CAST (char *, p), dest_align, false, 0);
3493           dest_mem = force_operand (XEXP (dest_mem, 0), target);
3494           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3495           return dest_mem;
3496         }
3497     }
3498   return NULL_RTX;
3499 }
3500
3501 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3502    bytes from constant string DATA + OFFSET and return it as target
3503    constant.  */
3504
3505 rtx
3506 builtin_memset_read_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3507                          enum machine_mode mode)
3508 {
3509   const char *c = (const char *) data;
3510   char *p = XALLOCAVEC (char, GET_MODE_SIZE (mode));
3511
3512   memset (p, *c, GET_MODE_SIZE (mode));
3513
3514   return c_readstr (p, mode);
3515 }
3516
3517 /* Callback routine for store_by_pieces.  Return the RTL of a register
3518    containing GET_MODE_SIZE (MODE) consecutive copies of the unsigned
3519    char value given in the RTL register data.  For example, if mode is
3520    4 bytes wide, return the RTL for 0x01010101*data.  */
3521
3522 static rtx
3523 builtin_memset_gen_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3524                         enum machine_mode mode)
3525 {
3526   rtx target, coeff;
3527   size_t size;
3528   char *p;
3529
3530   size = GET_MODE_SIZE (mode);
3531   if (size == 1)
3532     return (rtx) data;
3533
3534   p = XALLOCAVEC (char, size);
3535   memset (p, 1, size);
3536   coeff = c_readstr (p, mode);
3537
3538   target = convert_to_mode (mode, (rtx) data, 1);
3539   target = expand_mult (mode, target, coeff, NULL_RTX, 1);
3540   return force_reg (mode, target);
3541 }
3542
3543 /* Expand expression EXP, which is a call to the memset builtin.  Return
3544    NULL_RTX if we failed the caller should emit a normal call, otherwise
3545    try to get the result in TARGET, if convenient (and in mode MODE if that's
3546    convenient).  */
3547
3548 static rtx
3549 expand_builtin_memset (tree exp, rtx target, enum machine_mode mode)
3550 {
3551   if (!validate_arglist (exp,
3552                          POINTER_TYPE, INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
3553     return NULL_RTX;
3554   else
3555     {
3556       tree dest = CALL_EXPR_ARG (exp, 0);
3557       tree val = CALL_EXPR_ARG (exp, 1);
3558       tree len = CALL_EXPR_ARG (exp, 2);
3559       return expand_builtin_memset_args (dest, val, len, target, mode, exp);
3560     }
3561 }
3562
3563 /* Helper function to do the actual work for expand_builtin_memset.  The
3564    arguments to the builtin_memset call DEST, VAL, and LEN are broken out
3565    so that this can also be called without constructing an actual CALL_EXPR.
3566    The other arguments and return value are the same as for
3567    expand_builtin_memset.  */
3568
3569 static rtx
3570 expand_builtin_memset_args (tree dest, tree val, tree len,
3571                             rtx target, enum machine_mode mode, tree orig_exp)
3572 {
3573   tree fndecl, fn;
3574   enum built_in_function fcode;
3575   enum machine_mode val_mode;
3576   char c;
3577   unsigned int dest_align;
3578   rtx dest_mem, dest_addr, len_rtx;
3579   HOST_WIDE_INT expected_size = -1;
3580   unsigned int expected_align = 0;
3581
3582   dest_align = get_pointer_alignment (dest);
3583
3584   /* If DEST is not a pointer type, don't do this operation in-line.  */
3585   if (dest_align == 0)
3586     return NULL_RTX;
3587
3588   if (currently_expanding_gimple_stmt)
3589     stringop_block_profile (currently_expanding_gimple_stmt,
3590                             &expected_align, &expected_size);
3591
3592   if (expected_align < dest_align)
3593     expected_align = dest_align;
3594
3595   /* If the LEN parameter is zero, return DEST.  */
3596   if (integer_zerop (len))
3597     {
3598       /* Evaluate and ignore VAL in case it has side-effects.  */
3599       expand_expr (val, const0_rtx, VOIDmode, EXPAND_NORMAL);
3600       return expand_expr (dest, target, mode, EXPAND_NORMAL);
3601     }
3602
3603   /* Stabilize the arguments in case we fail.  */
3604   dest = builtin_save_expr (dest);
3605   val = builtin_save_expr (val);
3606   len = builtin_save_expr (len);
3607
3608   len_rtx = expand_normal (len);
3609   dest_mem = get_memory_rtx (dest, len);
3610   val_mode = TYPE_MODE (unsigned_char_type_node);
3611
3612   if (TREE_CODE (val) != INTEGER_CST)
3613     {
3614       rtx val_rtx;
3615
3616       val_rtx = expand_normal (val);
3617       val_rtx = convert_to_mode (val_mode, val_rtx, 0);
3618
3619       /* Assume that we can memset by pieces if we can store
3620        * the coefficients by pieces (in the required modes).
3621        * We can't pass builtin_memset_gen_str as that emits RTL.  */
3622       c = 1;
3623       if (host_integerp (len, 1)
3624           && can_store_by_pieces (tree_low_cst (len, 1),
3625                                   builtin_memset_read_str, &c, dest_align,
3626                                   true))
3627         {
3628           val_rtx = force_reg (val_mode, val_rtx);
3629           store_by_pieces (dest_mem, tree_low_cst (len, 1),
3630                            builtin_memset_gen_str, val_rtx, dest_align,
3631                            true, 0);
3632         }
3633       else if (!set_storage_via_setmem (dest_mem, len_rtx, val_rtx,
3634                                         dest_align, expected_align,
3635                                         expected_size))
3636         goto do_libcall;
3637
3638       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3639       dest_mem = convert_memory_address (ptr_mode, dest_mem);
3640       return dest_mem;
3641     }
3642
3643   if (target_char_cast (val, &c))
3644     goto do_libcall;
3645
3646   if (c)
3647     {
3648       if (host_integerp (len, 1)
3649           && can_store_by_pieces (tree_low_cst (len, 1),
3650                                   builtin_memset_read_str, &c, dest_align,
3651                                   true))
3652         store_by_pieces (dest_mem, tree_low_cst (len, 1),
3653                          builtin_memset_read_str, &c, dest_align, true, 0);
3654       else if (!set_storage_via_setmem (dest_mem, len_rtx,
3655                                         gen_int_mode (c, val_mode),
3656                                         dest_align, expected_align,
3657                                         expected_size))
3658         goto do_libcall;
3659
3660       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3661       dest_mem = convert_memory_address (ptr_mode, dest_mem);
3662       return dest_mem;
3663     }
3664
3665   set_mem_align (dest_mem, dest_align);
3666   dest_addr = clear_storage_hints (dest_mem, len_rtx,
3667                                    CALL_EXPR_TAILCALL (orig_exp)
3668                                    ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
3669                                    expected_align, expected_size);
3670
3671   if (dest_addr == 0)
3672     {
3673       dest_addr = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3674       dest_addr = convert_memory_address (ptr_mode, dest_addr);
3675     }
3676
3677   return dest_addr;
3678
3679  do_libcall:
3680   fndecl = get_callee_fndecl (orig_exp);
3681   fcode = DECL_FUNCTION_CODE (fndecl);
3682   if (fcode == BUILT_IN_MEMSET)
3683     fn = build_call_nofold_loc (EXPR_LOCATION (orig_exp), fndecl, 3,
3684                                 dest, val, len);
3685   else if (fcode == BUILT_IN_BZERO)
3686     fn = build_call_nofold_loc (EXPR_LOCATION (orig_exp), fndecl, 2,
3687                                 dest, len);
3688   else
3689     gcc_unreachable ();
3690   gcc_assert (TREE_CODE (fn) == CALL_EXPR);
3691   CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (orig_exp);
3692   return expand_call (fn, target, target == const0_rtx);
3693 }
3694
3695 /* Expand expression EXP, which is a call to the bzero builtin.  Return
3696    NULL_RTX if we failed the caller should emit a normal call.  */
3697
3698 static rtx
3699 expand_builtin_bzero (tree exp)
3700 {
3701   tree dest, size;
3702   location_t loc = EXPR_LOCATION (exp);
3703
3704   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3705     return NULL_RTX;
3706
3707   dest = CALL_EXPR_ARG (exp, 0);
3708   size = CALL_EXPR_ARG (exp, 1);
3709
3710   /* New argument list transforming bzero(ptr x, int y) to
3711      memset(ptr x, int 0, size_t y).   This is done this way
3712      so that if it isn't expanded inline, we fallback to
3713      calling bzero instead of memset.  */
3714
3715   return expand_builtin_memset_args (dest, integer_zero_node,
3716                                      fold_convert_loc (loc,
3717                                                        size_type_node, size),
3718                                      const0_rtx, VOIDmode, exp);
3719 }
3720
3721 /* Expand expression EXP, which is a call to the memcmp built-in function.
3722    Return NULL_RTX if we failed and the caller should emit a normal call,
3723    otherwise try to get the result in TARGET, if convenient (and in mode
3724    MODE, if that's convenient).  */
3725
3726 static rtx
3727 expand_builtin_memcmp (tree exp, ATTRIBUTE_UNUSED rtx target,
3728                        ATTRIBUTE_UNUSED enum machine_mode mode)
3729 {
3730   location_t loc ATTRIBUTE_UNUSED = EXPR_LOCATION (exp);
3731
3732   if (!validate_arglist (exp,
3733                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3734     return NULL_RTX;
3735
3736   /* Note: The cmpstrnsi pattern, if it exists, is not suitable for
3737      implementing memcmp because it will stop if it encounters two
3738      zero bytes.  */
3739 #if defined HAVE_cmpmemsi
3740   {
3741     rtx arg1_rtx, arg2_rtx, arg3_rtx;
3742     rtx result;
3743     rtx insn;
3744     tree arg1 = CALL_EXPR_ARG (exp, 0);
3745     tree arg2 = CALL_EXPR_ARG (exp, 1);
3746     tree len = CALL_EXPR_ARG (exp, 2);
3747
3748     unsigned int arg1_align = get_pointer_alignment (arg1) / BITS_PER_UNIT;
3749     unsigned int arg2_align = get_pointer_alignment (arg2) / BITS_PER_UNIT;
3750     enum machine_mode insn_mode;
3751
3752     if (HAVE_cmpmemsi)
3753       insn_mode = insn_data[(int) CODE_FOR_cmpmemsi].operand[0].mode;
3754     else
3755       return NULL_RTX;
3756
3757     /* If we don't have POINTER_TYPE, call the function.  */
3758     if (arg1_align == 0 || arg2_align == 0)
3759       return NULL_RTX;
3760
3761     /* Make a place to write the result of the instruction.  */
3762     result = target;
3763     if (! (result != 0
3764            && REG_P (result) && GET_MODE (result) == insn_mode
3765            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3766       result = gen_reg_rtx (insn_mode);
3767
3768     arg1_rtx = get_memory_rtx (arg1, len);
3769     arg2_rtx = get_memory_rtx (arg2, len);
3770     arg3_rtx = expand_normal (fold_convert_loc (loc, sizetype, len));
3771
3772     /* Set MEM_SIZE as appropriate.  */
3773     if (CONST_INT_P (arg3_rtx))
3774       {
3775         set_mem_size (arg1_rtx, INTVAL (arg3_rtx));
3776         set_mem_size (arg2_rtx, INTVAL (arg3_rtx));
3777       }
3778
3779     if (HAVE_cmpmemsi)
3780       insn = gen_cmpmemsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3781                            GEN_INT (MIN (arg1_align, arg2_align)));
3782     else
3783       gcc_unreachable ();
3784
3785     if (insn)
3786       emit_insn (insn);
3787     else
3788       emit_library_call_value (memcmp_libfunc, result, LCT_PURE,
3789                                TYPE_MODE (integer_type_node), 3,
3790                                XEXP (arg1_rtx, 0), Pmode,
3791                                XEXP (arg2_rtx, 0), Pmode,
3792                                convert_to_mode (TYPE_MODE (sizetype), arg3_rtx,
3793                                                 TYPE_UNSIGNED (sizetype)),
3794                                TYPE_MODE (sizetype));
3795
3796     /* Return the value in the proper mode for this function.  */
3797     mode = TYPE_MODE (TREE_TYPE (exp));
3798     if (GET_MODE (result) == mode)
3799       return result;
3800     else if (target != 0)
3801       {
3802         convert_move (target, result, 0);
3803         return target;
3804       }
3805     else
3806       return convert_to_mode (mode, result, 0);
3807   }
3808 #endif /* HAVE_cmpmemsi.  */
3809
3810   return NULL_RTX;
3811 }
3812
3813 /* Expand expression EXP, which is a call to the strcmp builtin.  Return NULL_RTX
3814    if we failed the caller should emit a normal call, otherwise try to get
3815    the result in TARGET, if convenient.  */
3816
3817 static rtx
3818 expand_builtin_strcmp (tree exp, ATTRIBUTE_UNUSED rtx target)
3819 {
3820   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3821     return NULL_RTX;
3822
3823 #if defined HAVE_cmpstrsi || defined HAVE_cmpstrnsi
3824   if (direct_optab_handler (cmpstr_optab, SImode) != CODE_FOR_nothing
3825       || direct_optab_handler (cmpstrn_optab, SImode) != CODE_FOR_nothing)
3826     {
3827       rtx arg1_rtx, arg2_rtx;
3828       rtx result, insn = NULL_RTX;
3829       tree fndecl, fn;
3830       tree arg1 = CALL_EXPR_ARG (exp, 0);
3831       tree arg2 = CALL_EXPR_ARG (exp, 1);
3832
3833       unsigned int arg1_align = get_pointer_alignment (arg1) / BITS_PER_UNIT;
3834       unsigned int arg2_align = get_pointer_alignment (arg2) / BITS_PER_UNIT;
3835
3836       /* If we don't have POINTER_TYPE, call the function.  */
3837       if (arg1_align == 0 || arg2_align == 0)
3838         return NULL_RTX;
3839
3840       /* Stabilize the arguments in case gen_cmpstr(n)si fail.  */
3841       arg1 = builtin_save_expr (arg1);
3842       arg2 = builtin_save_expr (arg2);
3843
3844       arg1_rtx = get_memory_rtx (arg1, NULL);
3845       arg2_rtx = get_memory_rtx (arg2, NULL);
3846
3847 #ifdef HAVE_cmpstrsi
3848       /* Try to call cmpstrsi.  */
3849       if (HAVE_cmpstrsi)
3850         {
3851           enum machine_mode insn_mode
3852             = insn_data[(int) CODE_FOR_cmpstrsi].operand[0].mode;
3853
3854           /* Make a place to write the result of the instruction.  */
3855           result = target;
3856           if (! (result != 0
3857                  && REG_P (result) && GET_MODE (result) == insn_mode
3858                  && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3859             result = gen_reg_rtx (insn_mode);
3860
3861           insn = gen_cmpstrsi (result, arg1_rtx, arg2_rtx,
3862                                GEN_INT (MIN (arg1_align, arg2_align)));
3863         }
3864 #endif
3865 #ifdef HAVE_cmpstrnsi
3866       /* Try to determine at least one length and call cmpstrnsi.  */
3867       if (!insn && HAVE_cmpstrnsi)
3868         {
3869           tree len;
3870           rtx arg3_rtx;
3871
3872           enum machine_mode insn_mode
3873             = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
3874           tree len1 = c_strlen (arg1, 1);
3875           tree len2 = c_strlen (arg2, 1);
3876
3877           if (len1)
3878             len1 = size_binop (PLUS_EXPR, ssize_int (1), len1);
3879           if (len2)
3880             len2 = size_binop (PLUS_EXPR, ssize_int (1), len2);
3881
3882           /* If we don't have a constant length for the first, use the length
3883              of the second, if we know it.  We don't require a constant for
3884              this case; some cost analysis could be done if both are available
3885              but neither is constant.  For now, assume they're equally cheap,
3886              unless one has side effects.  If both strings have constant lengths,
3887              use the smaller.  */
3888
3889           if (!len1)
3890             len = len2;
3891           else if (!len2)
3892             len = len1;
3893           else if (TREE_SIDE_EFFECTS (len1))
3894             len = len2;
3895           else if (TREE_SIDE_EFFECTS (len2))
3896             len = len1;
3897           else if (TREE_CODE (len1) != INTEGER_CST)
3898             len = len2;
3899           else if (TREE_CODE (len2) != INTEGER_CST)
3900             len = len1;
3901           else if (tree_int_cst_lt (len1, len2))
3902             len = len1;
3903           else
3904             len = len2;
3905
3906           /* If both arguments have side effects, we cannot optimize.  */
3907           if (!len || TREE_SIDE_EFFECTS (len))
3908             goto do_libcall;
3909
3910           arg3_rtx = expand_normal (len);
3911
3912           /* Make a place to write the result of the instruction.  */
3913           result = target;
3914           if (! (result != 0
3915                  && REG_P (result) && GET_MODE (result) == insn_mode
3916                  && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3917             result = gen_reg_rtx (insn_mode);
3918
3919           insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3920                                 GEN_INT (MIN (arg1_align, arg2_align)));
3921         }
3922 #endif
3923
3924       if (insn)
3925         {
3926           enum machine_mode mode;
3927           emit_insn (insn);
3928
3929           /* Return the value in the proper mode for this function.  */
3930           mode = TYPE_MODE (TREE_TYPE (exp));
3931           if (GET_MODE (result) == mode)
3932             return result;
3933           if (target == 0)
3934             return convert_to_mode (mode, result, 0);
3935           convert_move (target, result, 0);
3936           return target;
3937         }
3938
3939       /* Expand the library call ourselves using a stabilized argument
3940          list to avoid re-evaluating the function's arguments twice.  */
3941 #ifdef HAVE_cmpstrnsi
3942     do_libcall:
3943 #endif
3944       fndecl = get_callee_fndecl (exp);
3945       fn = build_call_nofold_loc (EXPR_LOCATION (exp), fndecl, 2, arg1, arg2);
3946       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
3947       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
3948       return expand_call (fn, target, target == const0_rtx);
3949     }
3950 #endif
3951   return NULL_RTX;
3952 }
3953
3954 /* Expand expression EXP, which is a call to the strncmp builtin. Return
3955    NULL_RTX if we failed the caller should emit a normal call, otherwise try to get
3956    the result in TARGET, if convenient.  */
3957
3958 static rtx
3959 expand_builtin_strncmp (tree exp, ATTRIBUTE_UNUSED rtx target,
3960                         ATTRIBUTE_UNUSED enum machine_mode mode)
3961 {
3962   location_t loc ATTRIBUTE_UNUSED = EXPR_LOCATION (exp);
3963
3964   if (!validate_arglist (exp,
3965                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3966     return NULL_RTX;
3967
3968   /* If c_strlen can determine an expression for one of the string
3969      lengths, and it doesn't have side effects, then emit cmpstrnsi
3970      using length MIN(strlen(string)+1, arg3).  */
3971 #ifdef HAVE_cmpstrnsi
3972   if (HAVE_cmpstrnsi)
3973   {
3974     tree len, len1, len2;
3975     rtx arg1_rtx, arg2_rtx, arg3_rtx;
3976     rtx result, insn;
3977     tree fndecl, fn;
3978     tree arg1 = CALL_EXPR_ARG (exp, 0);
3979     tree arg2 = CALL_EXPR_ARG (exp, 1);
3980     tree arg3 = CALL_EXPR_ARG (exp, 2);
3981
3982     unsigned int arg1_align = get_pointer_alignment (arg1) / BITS_PER_UNIT;
3983     unsigned int arg2_align = get_pointer_alignment (arg2) / BITS_PER_UNIT;
3984     enum machine_mode insn_mode
3985       = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
3986
3987     len1 = c_strlen (arg1, 1);
3988     len2 = c_strlen (arg2, 1);
3989
3990     if (len1)
3991       len1 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len1);
3992     if (len2)
3993       len2 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len2);
3994
3995     /* If we don't have a constant length for the first, use the length
3996        of the second, if we know it.  We don't require a constant for
3997        this case; some cost analysis could be done if both are available
3998        but neither is constant.  For now, assume they're equally cheap,
3999        unless one has side effects.  If both strings have constant lengths,
4000        use the smaller.  */
4001
4002     if (!len1)
4003       len = len2;
4004     else if (!len2)
4005       len = len1;
4006     else if (TREE_SIDE_EFFECTS (len1))
4007       len = len2;
4008     else if (TREE_SIDE_EFFECTS (len2))
4009       len = len1;
4010     else if (TREE_CODE (len1) != INTEGER_CST)
4011       len = len2;
4012     else if (TREE_CODE (len2) != INTEGER_CST)
4013       len = len1;
4014     else if (tree_int_cst_lt (len1, len2))
4015       len = len1;
4016     else
4017       len = len2;
4018
4019     /* If both arguments have side effects, we cannot optimize.  */
4020     if (!len || TREE_SIDE_EFFECTS (len))
4021       return NULL_RTX;
4022
4023     /* The actual new length parameter is MIN(len,arg3).  */
4024     len = fold_build2_loc (loc, MIN_EXPR, TREE_TYPE (len), len,
4025                        fold_convert_loc (loc, TREE_TYPE (len), arg3));
4026
4027     /* If we don't have POINTER_TYPE, call the function.  */
4028     if (arg1_align == 0 || arg2_align == 0)
4029       return NULL_RTX;
4030
4031     /* Make a place to write the result of the instruction.  */
4032     result = target;
4033     if (! (result != 0
4034            && REG_P (result) && GET_MODE (result) == insn_mode
4035            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
4036       result = gen_reg_rtx (insn_mode);
4037
4038     /* Stabilize the arguments in case gen_cmpstrnsi fails.  */
4039     arg1 = builtin_save_expr (arg1);
4040     arg2 = builtin_save_expr (arg2);
4041     len = builtin_save_expr (len);
4042
4043     arg1_rtx = get_memory_rtx (arg1, len);
4044     arg2_rtx = get_memory_rtx (arg2, len);
4045     arg3_rtx = expand_normal (len);
4046     insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
4047                           GEN_INT (MIN (arg1_align, arg2_align)));
4048     if (insn)
4049       {
4050         emit_insn (insn);
4051
4052         /* Return the value in the proper mode for this function.  */
4053         mode = TYPE_MODE (TREE_TYPE (exp));
4054         if (GET_MODE (result) == mode)
4055           return result;
4056         if (target == 0)
4057           return convert_to_mode (mode, result, 0);
4058         convert_move (target, result, 0);
4059         return target;
4060       }
4061
4062     /* Expand the library call ourselves using a stabilized argument
4063        list to avoid re-evaluating the function's arguments twice.  */
4064     fndecl = get_callee_fndecl (exp);
4065     fn = build_call_nofold_loc (EXPR_LOCATION (exp), fndecl, 3,
4066                                 arg1, arg2, len);
4067     gcc_assert (TREE_CODE (fn) == CALL_EXPR);
4068     CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
4069     return expand_call (fn, target, target == const0_rtx);
4070   }
4071 #endif
4072   return NULL_RTX;
4073 }
4074
4075 /* Expand a call to __builtin_saveregs, generating the result in TARGET,
4076    if that's convenient.  */
4077
4078 rtx
4079 expand_builtin_saveregs (void)
4080 {
4081   rtx val, seq;
4082
4083   /* Don't do __builtin_saveregs more than once in a function.
4084      Save the result of the first call and reuse it.  */
4085   if (saveregs_value != 0)
4086     return saveregs_value;
4087
4088   /* When this function is called, it means that registers must be
4089      saved on entry to this function.  So we migrate the call to the
4090      first insn of this function.  */
4091
4092   start_sequence ();
4093
4094   /* Do whatever the machine needs done in this case.  */
4095   val = targetm.calls.expand_builtin_saveregs ();
4096
4097   seq = get_insns ();
4098   end_sequence ();
4099
4100   saveregs_value = val;
4101
4102   /* Put the insns after the NOTE that starts the function.  If this
4103      is inside a start_sequence, make the outer-level insn chain current, so
4104      the code is placed at the start of the function.  */
4105   push_topmost_sequence ();
4106   emit_insn_after (seq, entry_of_function ());
4107   pop_topmost_sequence ();
4108
4109   return val;
4110 }
4111
4112 /* Expand a call to __builtin_next_arg.  */
4113
4114 static rtx
4115 expand_builtin_next_arg (void)
4116 {
4117   /* Checking arguments is already done in fold_builtin_next_arg
4118      that must be called before this function.  */
4119   return expand_binop (ptr_mode, add_optab,
4120                        crtl->args.internal_arg_pointer,
4121                        crtl->args.arg_offset_rtx,
4122                        NULL_RTX, 0, OPTAB_LIB_WIDEN);
4123 }
4124
4125 /* Make it easier for the backends by protecting the valist argument
4126    from multiple evaluations.  */
4127
4128 static tree
4129 stabilize_va_list_loc (location_t loc, tree valist, int needs_lvalue)
4130 {
4131   tree vatype = targetm.canonical_va_list_type (TREE_TYPE (valist));
4132
4133   /* The current way of determining the type of valist is completely
4134      bogus.  We should have the information on the va builtin instead.  */
4135   if (!vatype)
4136     vatype = targetm.fn_abi_va_list (cfun->decl);
4137
4138   if (TREE_CODE (vatype) == ARRAY_TYPE)
4139     {
4140       if (TREE_SIDE_EFFECTS (valist))
4141         valist = save_expr (valist);
4142
4143       /* For this case, the backends will be expecting a pointer to
4144          vatype, but it's possible we've actually been given an array
4145          (an actual TARGET_CANONICAL_VA_LIST_TYPE (valist)).
4146          So fix it.  */
4147       if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
4148         {
4149           tree p1 = build_pointer_type (TREE_TYPE (vatype));
4150           valist = build_fold_addr_expr_with_type_loc (loc, valist, p1);
4151         }
4152     }
4153   else
4154     {
4155       tree pt = build_pointer_type (vatype);
4156
4157       if (! needs_lvalue)
4158         {
4159           if (! TREE_SIDE_EFFECTS (valist))
4160             return valist;
4161
4162           valist = fold_build1_loc (loc, ADDR_EXPR, pt, valist);
4163           TREE_SIDE_EFFECTS (valist) = 1;
4164         }
4165
4166       if (TREE_SIDE_EFFECTS (valist))
4167         valist = save_expr (valist);
4168       valist = fold_build2_loc (loc, MEM_REF,
4169                                 vatype, valist, build_int_cst (pt, 0));
4170     }
4171
4172   return valist;
4173 }
4174
4175 /* The "standard" definition of va_list is void*.  */
4176
4177 tree
4178 std_build_builtin_va_list (void)
4179 {
4180   return ptr_type_node;
4181 }
4182
4183 /* The "standard" abi va_list is va_list_type_node.  */
4184
4185 tree
4186 std_fn_abi_va_list (tree fndecl ATTRIBUTE_UNUSED)
4187 {
4188   return va_list_type_node;
4189 }
4190
4191 /* The "standard" type of va_list is va_list_type_node.  */
4192
4193 tree
4194 std_canonical_va_list_type (tree type)
4195 {
4196   tree wtype, htype;
4197
4198   if (INDIRECT_REF_P (type))
4199     type = TREE_TYPE (type);
4200   else if (POINTER_TYPE_P (type) && POINTER_TYPE_P (TREE_TYPE (type)))
4201     type = TREE_TYPE (type);
4202   wtype = va_list_type_node;
4203   htype = type;
4204   /* Treat structure va_list types.  */
4205   if (TREE_CODE (wtype) == RECORD_TYPE && POINTER_TYPE_P (htype))
4206     htype = TREE_TYPE (htype);
4207   else if (TREE_CODE (wtype) == ARRAY_TYPE)
4208     {
4209       /* If va_list is an array type, the argument may have decayed
4210          to a pointer type, e.g. by being passed to another function.
4211          In that case, unwrap both types so that we can compare the
4212          underlying records.  */
4213       if (TREE_CODE (htype) == ARRAY_TYPE
4214           || POINTER_TYPE_P (htype))
4215         {
4216           wtype = TREE_TYPE (wtype);
4217           htype = TREE_TYPE (htype);
4218         }
4219     }
4220   if (TYPE_MAIN_VARIANT (wtype) == TYPE_MAIN_VARIANT (htype))
4221     return va_list_type_node;
4222
4223   return NULL_TREE;
4224 }
4225
4226 /* The "standard" implementation of va_start: just assign `nextarg' to
4227    the variable.  */
4228
4229 void
4230 std_expand_builtin_va_start (tree valist, rtx nextarg)
4231 {
4232   rtx va_r = expand_expr (valist, NULL_RTX, VOIDmode, EXPAND_WRITE);
4233   convert_move (va_r, nextarg, 0);
4234 }
4235
4236 /* Expand EXP, a call to __builtin_va_start.  */
4237
4238 static rtx
4239 expand_builtin_va_start (tree exp)
4240 {
4241   rtx nextarg;
4242   tree valist;
4243   location_t loc = EXPR_LOCATION (exp);
4244
4245   if (call_expr_nargs (exp) < 2)
4246     {
4247       error_at (loc, "too few arguments to function %<va_start%>");
4248       return const0_rtx;
4249     }
4250
4251   if (fold_builtin_next_arg (exp, true))
4252     return const0_rtx;
4253
4254   nextarg = expand_builtin_next_arg ();
4255   valist = stabilize_va_list_loc (loc, CALL_EXPR_ARG (exp, 0), 1);
4256
4257   if (targetm.expand_builtin_va_start)
4258     targetm.expand_builtin_va_start (valist, nextarg);
4259   else
4260     std_expand_builtin_va_start (valist, nextarg);
4261
4262   return const0_rtx;
4263 }
4264
4265 /* Expand EXP, a call to __builtin_va_end.  */
4266
4267 static rtx
4268 expand_builtin_va_end (tree exp)
4269 {
4270   tree valist = CALL_EXPR_ARG (exp, 0);
4271
4272   /* Evaluate for side effects, if needed.  I hate macros that don't
4273      do that.  */
4274   if (TREE_SIDE_EFFECTS (valist))
4275     expand_expr (valist, const0_rtx, VOIDmode, EXPAND_NORMAL);
4276
4277   return const0_rtx;
4278 }
4279
4280 /* Expand EXP, a call to __builtin_va_copy.  We do this as a
4281    builtin rather than just as an assignment in stdarg.h because of the
4282    nastiness of array-type va_list types.  */
4283
4284 static rtx
4285 expand_builtin_va_copy (tree exp)
4286 {
4287   tree dst, src, t;
4288   location_t loc = EXPR_LOCATION (exp);
4289
4290   dst = CALL_EXPR_ARG (exp, 0);
4291   src = CALL_EXPR_ARG (exp, 1);
4292
4293   dst = stabilize_va_list_loc (loc, dst, 1);
4294   src = stabilize_va_list_loc (loc, src, 0);
4295
4296   gcc_assert (cfun != NULL && cfun->decl != NULL_TREE);
4297
4298   if (TREE_CODE (targetm.fn_abi_va_list (cfun->decl)) != ARRAY_TYPE)
4299     {
4300       t = build2 (MODIFY_EXPR, targetm.fn_abi_va_list (cfun->decl), dst, src);
4301       TREE_SIDE_EFFECTS (t) = 1;
4302       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4303     }
4304   else
4305     {
4306       rtx dstb, srcb, size;
4307
4308       /* Evaluate to pointers.  */
4309       dstb = expand_expr (dst, NULL_RTX, Pmode, EXPAND_NORMAL);
4310       srcb = expand_expr (src, NULL_RTX, Pmode, EXPAND_NORMAL);
4311       size = expand_expr (TYPE_SIZE_UNIT (targetm.fn_abi_va_list (cfun->decl)),
4312                   NULL_RTX, VOIDmode, EXPAND_NORMAL);
4313
4314       dstb = convert_memory_address (Pmode, dstb);
4315       srcb = convert_memory_address (Pmode, srcb);
4316
4317       /* "Dereference" to BLKmode memories.  */
4318       dstb = gen_rtx_MEM (BLKmode, dstb);
4319       set_mem_alias_set (dstb, get_alias_set (TREE_TYPE (TREE_TYPE (dst))));
4320       set_mem_align (dstb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4321       srcb = gen_rtx_MEM (BLKmode, srcb);
4322       set_mem_alias_set (srcb, get_alias_set (TREE_TYPE (TREE_TYPE (src))));
4323       set_mem_align (srcb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4324
4325       /* Copy.  */
4326       emit_block_move (dstb, srcb, size, BLOCK_OP_NORMAL);
4327     }
4328
4329   return const0_rtx;
4330 }
4331
4332 /* Expand a call to one of the builtin functions __builtin_frame_address or
4333    __builtin_return_address.  */
4334
4335 static rtx
4336 expand_builtin_frame_address (tree fndecl, tree exp)
4337 {
4338   /* The argument must be a nonnegative integer constant.
4339      It counts the number of frames to scan up the stack.
4340      The value is the return address saved in that frame.  */
4341   if (call_expr_nargs (exp) == 0)
4342     /* Warning about missing arg was already issued.  */
4343     return const0_rtx;
4344   else if (! host_integerp (CALL_EXPR_ARG (exp, 0), 1))
4345     {
4346       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4347         error ("invalid argument to %<__builtin_frame_address%>");
4348       else
4349         error ("invalid argument to %<__builtin_return_address%>");
4350       return const0_rtx;
4351     }
4352   else
4353     {
4354       rtx tem
4355         = expand_builtin_return_addr (DECL_FUNCTION_CODE (fndecl),
4356                                       tree_low_cst (CALL_EXPR_ARG (exp, 0), 1));
4357
4358       /* Some ports cannot access arbitrary stack frames.  */
4359       if (tem == NULL)
4360         {
4361           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4362             warning (0, "unsupported argument to %<__builtin_frame_address%>");
4363           else
4364             warning (0, "unsupported argument to %<__builtin_return_address%>");
4365           return const0_rtx;
4366         }
4367
4368       /* For __builtin_frame_address, return what we've got.  */
4369       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4370         return tem;
4371
4372       if (!REG_P (tem)
4373           && ! CONSTANT_P (tem))
4374         tem = copy_addr_to_reg (tem);
4375       return tem;
4376     }
4377 }
4378
4379 /* Expand EXP, a call to the alloca builtin.  Return NULL_RTX if we
4380    failed and the caller should emit a normal call.  CANNOT_ACCUMULATE
4381    is the same as for allocate_dynamic_stack_space.  */
4382
4383 static rtx
4384 expand_builtin_alloca (tree exp, bool cannot_accumulate)
4385 {
4386   rtx op0;
4387   rtx result;
4388   bool valid_arglist;
4389   unsigned int align;
4390   bool alloca_with_align = (DECL_FUNCTION_CODE (get_callee_fndecl (exp))
4391                             == BUILT_IN_ALLOCA_WITH_ALIGN);
4392
4393   valid_arglist
4394     = (alloca_with_align
4395        ? validate_arglist (exp, INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE)
4396        : validate_arglist (exp, INTEGER_TYPE, VOID_TYPE));
4397
4398   if (!valid_arglist)
4399     return NULL_RTX;
4400
4401   /* Compute the argument.  */
4402   op0 = expand_normal (CALL_EXPR_ARG (exp, 0));
4403
4404   /* Compute the alignment.  */
4405   align = (alloca_with_align
4406            ? TREE_INT_CST_LOW (CALL_EXPR_ARG (exp, 1))
4407            : BIGGEST_ALIGNMENT);
4408
4409   /* Allocate the desired space.  */
4410   result = allocate_dynamic_stack_space (op0, 0, align, cannot_accumulate);
4411   result = convert_memory_address (ptr_mode, result);
4412
4413   return result;
4414 }
4415
4416 /* Expand a call to bswap builtin in EXP.
4417    Return NULL_RTX if a normal call should be emitted rather than expanding the
4418    function in-line.  If convenient, the result should be placed in TARGET.
4419    SUBTARGET may be used as the target for computing one of EXP's operands.  */
4420
4421 static rtx
4422 expand_builtin_bswap (enum machine_mode target_mode, tree exp, rtx target,
4423                       rtx subtarget)
4424 {
4425   tree arg;
4426   rtx op0;
4427
4428   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4429     return NULL_RTX;
4430
4431   arg = CALL_EXPR_ARG (exp, 0);
4432   op0 = expand_expr (arg,
4433                      subtarget && GET_MODE (subtarget) == target_mode
4434                      ? subtarget : NULL_RTX,
4435                      target_mode, EXPAND_NORMAL);
4436   if (GET_MODE (op0) != target_mode)
4437     op0 = convert_to_mode (target_mode, op0, 1);
4438
4439   target = expand_unop (target_mode, bswap_optab, op0, target, 1);
4440
4441   gcc_assert (target);
4442
4443   return convert_to_mode (target_mode, target, 1);
4444 }
4445
4446 /* Expand a call to a unary builtin in EXP.
4447    Return NULL_RTX if a normal call should be emitted rather than expanding the
4448    function in-line.  If convenient, the result should be placed in TARGET.
4449    SUBTARGET may be used as the target for computing one of EXP's operands.  */
4450
4451 static rtx
4452 expand_builtin_unop (enum machine_mode target_mode, tree exp, rtx target,
4453                      rtx subtarget, optab op_optab)
4454 {
4455   rtx op0;
4456
4457   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4458     return NULL_RTX;
4459
4460   /* Compute the argument.  */
4461   op0 = expand_expr (CALL_EXPR_ARG (exp, 0),
4462                      (subtarget
4463                       && (TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 0)))
4464                           == GET_MODE (subtarget))) ? subtarget : NULL_RTX,
4465                      VOIDmode, EXPAND_NORMAL);
4466   /* Compute op, into TARGET if possible.
4467      Set TARGET to wherever the result comes back.  */
4468   target = expand_unop (TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 0))),
4469                         op_optab, op0, target, op_optab != clrsb_optab);
4470   gcc_assert (target);
4471
4472   return convert_to_mode (target_mode, target, 0);
4473 }
4474
4475 /* Expand a call to __builtin_expect.  We just return our argument
4476    as the builtin_expect semantic should've been already executed by
4477    tree branch prediction pass. */
4478
4479 static rtx
4480 expand_builtin_expect (tree exp, rtx target)
4481 {
4482   tree arg;
4483
4484   if (call_expr_nargs (exp) < 2)
4485     return const0_rtx;
4486   arg = CALL_EXPR_ARG (exp, 0);
4487
4488   target = expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
4489   /* When guessing was done, the hints should be already stripped away.  */
4490   gcc_assert (!flag_guess_branch_prob
4491               || optimize == 0 || seen_error ());
4492   return target;
4493 }
4494
4495 /* Expand a call to __builtin_assume_aligned.  We just return our first
4496    argument as the builtin_assume_aligned semantic should've been already
4497    executed by CCP.  */
4498
4499 static rtx
4500 expand_builtin_assume_aligned (tree exp, rtx target)
4501 {
4502   if (call_expr_nargs (exp) < 2)
4503     return const0_rtx;
4504   target = expand_expr (CALL_EXPR_ARG (exp, 0), target, VOIDmode,
4505                         EXPAND_NORMAL);
4506   gcc_assert (!TREE_SIDE_EFFECTS (CALL_EXPR_ARG (exp, 1))
4507               && (call_expr_nargs (exp) < 3
4508                   || !TREE_SIDE_EFFECTS (CALL_EXPR_ARG (exp, 2))));
4509   return target;
4510 }
4511
4512 void
4513 expand_builtin_trap (void)
4514 {
4515 #ifdef HAVE_trap
4516   if (HAVE_trap)
4517     {
4518       rtx insn = emit_insn (gen_trap ());
4519       /* For trap insns when not accumulating outgoing args force
4520          REG_ARGS_SIZE note to prevent crossjumping of calls with
4521          different args sizes.  */
4522       if (!ACCUMULATE_OUTGOING_ARGS)
4523         add_reg_note (insn, REG_ARGS_SIZE, GEN_INT (stack_pointer_delta));
4524     }
4525   else
4526 #endif
4527     emit_library_call (abort_libfunc, LCT_NORETURN, VOIDmode, 0);
4528   emit_barrier ();
4529 }
4530
4531 /* Expand a call to __builtin_unreachable.  We do nothing except emit
4532    a barrier saying that control flow will not pass here.
4533
4534    It is the responsibility of the program being compiled to ensure
4535    that control flow does never reach __builtin_unreachable.  */
4536 static void
4537 expand_builtin_unreachable (void)
4538 {
4539   emit_barrier ();
4540 }
4541
4542 /* Expand EXP, a call to fabs, fabsf or fabsl.
4543    Return NULL_RTX if a normal call should be emitted rather than expanding
4544    the function inline.  If convenient, the result should be placed
4545    in TARGET.  SUBTARGET may be used as the target for computing
4546    the operand.  */
4547
4548 static rtx
4549 expand_builtin_fabs (tree exp, rtx target, rtx subtarget)
4550 {
4551   enum machine_mode mode;
4552   tree arg;
4553   rtx op0;
4554
4555   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
4556     return NULL_RTX;
4557
4558   arg = CALL_EXPR_ARG (exp, 0);
4559   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
4560   mode = TYPE_MODE (TREE_TYPE (arg));
4561   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
4562   return expand_abs (mode, op0, target, 0, safe_from_p (target, arg, 1));
4563 }
4564
4565 /* Expand EXP, a call to copysign, copysignf, or copysignl.
4566    Return NULL is a normal call should be emitted rather than expanding the
4567    function inline.  If convenient, the result should be placed in TARGET.
4568    SUBTARGET may be used as the target for computing the operand.  */
4569
4570 static rtx
4571 expand_builtin_copysign (tree exp, rtx target, rtx subtarget)
4572 {
4573   rtx op0, op1;
4574   tree arg;
4575
4576   if (!validate_arglist (exp, REAL_TYPE, REAL_TYPE, VOID_TYPE))
4577     return NULL_RTX;
4578
4579   arg = CALL_EXPR_ARG (exp, 0);
4580   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
4581
4582   arg = CALL_EXPR_ARG (exp, 1);
4583   op1 = expand_normal (arg);
4584
4585   return expand_copysign (op0, op1, target);
4586 }
4587
4588 /* Create a new constant string literal and return a char* pointer to it.
4589    The STRING_CST value is the LEN characters at STR.  */
4590 tree
4591 build_string_literal (int len, const char *str)
4592 {
4593   tree t, elem, index, type;
4594
4595   t = build_string (len, str);
4596   elem = build_type_variant (char_type_node, 1, 0);
4597   index = build_index_type (size_int (len - 1));
4598   type = build_array_type (elem, index);
4599   TREE_TYPE (t) = type;
4600   TREE_CONSTANT (t) = 1;
4601   TREE_READONLY (t) = 1;
4602   TREE_STATIC (t) = 1;
4603
4604   type = build_pointer_type (elem);
4605   t = build1 (ADDR_EXPR, type,
4606               build4 (ARRAY_REF, elem,
4607                       t, integer_zero_node, NULL_TREE, NULL_TREE));
4608   return t;
4609 }
4610
4611 /* Expand a call to __builtin___clear_cache.  */
4612
4613 static rtx
4614 expand_builtin___clear_cache (tree exp ATTRIBUTE_UNUSED)
4615 {
4616 #ifndef HAVE_clear_cache
4617 #ifdef CLEAR_INSN_CACHE
4618   /* There is no "clear_cache" insn, and __clear_cache() in libgcc
4619      does something.  Just do the default expansion to a call to
4620      __clear_cache().  */
4621   return NULL_RTX;
4622 #else
4623   /* There is no "clear_cache" insn, and __clear_cache() in libgcc
4624      does nothing.  There is no need to call it.  Do nothing.  */
4625   return const0_rtx;
4626 #endif /* CLEAR_INSN_CACHE */
4627 #else
4628   /* We have a "clear_cache" insn, and it will handle everything.  */
4629   tree begin, end;
4630   rtx begin_rtx, end_rtx;
4631
4632   /* We must not expand to a library call.  If we did, any
4633      fallback library function in libgcc that might contain a call to
4634      __builtin___clear_cache() would recurse infinitely.  */
4635   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
4636     {
4637       error ("both arguments to %<__builtin___clear_cache%> must be pointers");
4638       return const0_rtx;
4639     }
4640
4641   if (HAVE_clear_cache)
4642     {
4643       struct expand_operand ops[2];
4644
4645       begin = CALL_EXPR_ARG (exp, 0);
4646       begin_rtx = expand_expr (begin, NULL_RTX, Pmode, EXPAND_NORMAL);
4647
4648       end = CALL_EXPR_ARG (exp, 1);
4649       end_rtx = expand_expr (end, NULL_RTX, Pmode, EXPAND_NORMAL);
4650
4651       create_address_operand (&ops[0], begin_rtx);
4652       create_address_operand (&ops[1], end_rtx);
4653       if (maybe_expand_insn (CODE_FOR_clear_cache, 2, ops))
4654         return const0_rtx;
4655     }
4656   return const0_rtx;
4657 #endif /* HAVE_clear_cache */
4658 }
4659
4660 /* Given a trampoline address, make sure it satisfies TRAMPOLINE_ALIGNMENT.  */
4661
4662 static rtx
4663 round_trampoline_addr (rtx tramp)
4664 {
4665   rtx temp, addend, mask;
4666
4667   /* If we don't need too much alignment, we'll have been guaranteed
4668      proper alignment by get_trampoline_type.  */
4669   if (TRAMPOLINE_ALIGNMENT <= STACK_BOUNDARY)
4670     return tramp;
4671
4672   /* Round address up to desired boundary.  */
4673   temp = gen_reg_rtx (Pmode);
4674   addend = gen_int_mode (TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT - 1, Pmode);
4675   mask = gen_int_mode (-TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT, Pmode);
4676
4677   temp  = expand_simple_binop (Pmode, PLUS, tramp, addend,
4678                                temp, 0, OPTAB_LIB_WIDEN);
4679   tramp = expand_simple_binop (Pmode, AND, temp, mask,
4680                                temp, 0, OPTAB_LIB_WIDEN);
4681
4682   return tramp;
4683 }
4684
4685 static rtx
4686 expand_builtin_init_trampoline (tree exp, bool onstack)
4687 {
4688   tree t_tramp, t_func, t_chain;
4689   rtx m_tramp, r_tramp, r_chain, tmp;
4690
4691   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE,
4692                          POINTER_TYPE, VOID_TYPE))
4693     return NULL_RTX;
4694
4695   t_tramp = CALL_EXPR_ARG (exp, 0);
4696   t_func = CALL_EXPR_ARG (exp, 1);
4697   t_chain = CALL_EXPR_ARG (exp, 2);
4698
4699   r_tramp = expand_normal (t_tramp);
4700   m_tramp = gen_rtx_MEM (BLKmode, r_tramp);
4701   MEM_NOTRAP_P (m_tramp) = 1;
4702
4703   /* If ONSTACK, the TRAMP argument should be the address of a field
4704      within the local function's FRAME decl.  Either way, let's see if
4705      we can fill in the MEM_ATTRs for this memory.  */
4706   if (TREE_CODE (t_tramp) == ADDR_EXPR)
4707     set_mem_attributes (m_tramp, TREE_OPERAND (t_tramp, 0), true);
4708
4709   /* Creator of a heap trampoline is responsible for making sure the
4710      address is aligned to at least STACK_BOUNDARY.  Normally malloc
4711      will ensure this anyhow.  */
4712   tmp = round_trampoline_addr (r_tramp);
4713   if (tmp != r_tramp)
4714     {
4715       m_tramp = change_address (m_tramp, BLKmode, tmp);
4716       set_mem_align (m_tramp, TRAMPOLINE_ALIGNMENT);
4717       set_mem_size (m_tramp, TRAMPOLINE_SIZE);
4718     }
4719
4720   /* The FUNC argument should be the address of the nested function.
4721      Extract the actual function decl to pass to the hook.  */
4722   gcc_assert (TREE_CODE (t_func) == ADDR_EXPR);
4723   t_func = TREE_OPERAND (t_func, 0);
4724   gcc_assert (TREE_CODE (t_func) == FUNCTION_DECL);
4725
4726   r_chain = expand_normal (t_chain);
4727
4728   /* Generate insns to initialize the trampoline.  */
4729   targetm.calls.trampoline_init (m_tramp, t_func, r_chain);
4730
4731   if (onstack)
4732     {
4733       trampolines_created = 1;
4734
4735       warning_at (DECL_SOURCE_LOCATION (t_func), OPT_Wtrampolines,
4736                   "trampoline generated for nested function %qD", t_func);
4737     }
4738
4739   return const0_rtx;
4740 }
4741
4742 static rtx
4743 expand_builtin_adjust_trampoline (tree exp)
4744 {
4745   rtx tramp;
4746
4747   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
4748     return NULL_RTX;
4749
4750   tramp = expand_normal (CALL_EXPR_ARG (exp, 0));
4751   tramp = round_trampoline_addr (tramp);
4752   if (targetm.calls.trampoline_adjust_address)
4753     tramp = targetm.calls.trampoline_adjust_address (tramp);
4754
4755   return tramp;
4756 }
4757
4758 /* Expand the call EXP to the built-in signbit, signbitf or signbitl
4759    function.  The function first checks whether the back end provides
4760    an insn to implement signbit for the respective mode.  If not, it
4761    checks whether the floating point format of the value is such that
4762    the sign bit can be extracted.  If that is not the case, the
4763    function returns NULL_RTX to indicate that a normal call should be
4764    emitted rather than expanding the function in-line.  EXP is the
4765    expression that is a call to the builtin function; if convenient,
4766    the result should be placed in TARGET.  */
4767 static rtx
4768 expand_builtin_signbit (tree exp, rtx target)
4769 {
4770   const struct real_format *fmt;
4771   enum machine_mode fmode, imode, rmode;
4772   tree arg;
4773   int word, bitpos;
4774   enum insn_code icode;
4775   rtx temp;
4776   location_t loc = EXPR_LOCATION (exp);
4777
4778   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
4779     return NULL_RTX;
4780
4781   arg = CALL_EXPR_ARG (exp, 0);
4782   fmode = TYPE_MODE (TREE_TYPE (arg));
4783   rmode = TYPE_MODE (TREE_TYPE (exp));
4784   fmt = REAL_MODE_FORMAT (fmode);
4785
4786   arg = builtin_save_expr (arg);
4787
4788   /* Expand the argument yielding a RTX expression. */
4789   temp = expand_normal (arg);
4790
4791   /* Check if the back end provides an insn that handles signbit for the
4792      argument's mode. */
4793   icode = optab_handler (signbit_optab, fmode);
4794   if (icode != CODE_FOR_nothing)
4795     {
4796       rtx last = get_last_insn ();
4797       target = gen_reg_rtx (TYPE_MODE (TREE_TYPE (exp)));
4798       if (maybe_emit_unop_insn (icode, target, temp, UNKNOWN))
4799         return target;
4800       delete_insns_since (last);
4801     }
4802
4803   /* For floating point formats without a sign bit, implement signbit
4804      as "ARG < 0.0".  */
4805   bitpos = fmt->signbit_ro;
4806   if (bitpos < 0)
4807   {
4808     /* But we can't do this if the format supports signed zero.  */
4809     if (fmt->has_signed_zero && HONOR_SIGNED_ZEROS (fmode))
4810       return NULL_RTX;
4811
4812     arg = fold_build2_loc (loc, LT_EXPR, TREE_TYPE (exp), arg,
4813                        build_real (TREE_TYPE (arg), dconst0));
4814     return expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
4815   }
4816
4817   if (GET_MODE_SIZE (fmode) <= UNITS_PER_WORD)
4818     {
4819       imode = int_mode_for_mode (fmode);
4820       if (imode == BLKmode)
4821         return NULL_RTX;
4822       temp = gen_lowpart (imode, temp);
4823     }
4824   else
4825     {
4826       imode = word_mode;
4827       /* Handle targets with different FP word orders.  */
4828       if (FLOAT_WORDS_BIG_ENDIAN)
4829         word = (GET_MODE_BITSIZE (fmode) - bitpos) / BITS_PER_WORD;
4830       else
4831         word = bitpos / BITS_PER_WORD;
4832       temp = operand_subword_force (temp, word, fmode);
4833       bitpos = bitpos % BITS_PER_WORD;
4834     }
4835
4836   /* Force the intermediate word_mode (or narrower) result into a
4837      register.  This avoids attempting to create paradoxical SUBREGs
4838      of floating point modes below.  */
4839   temp = force_reg (imode, temp);
4840
4841   /* If the bitpos is within the "result mode" lowpart, the operation
4842      can be implement with a single bitwise AND.  Otherwise, we need
4843      a right shift and an AND.  */
4844
4845   if (bitpos < GET_MODE_BITSIZE (rmode))
4846     {
4847       double_int mask = double_int_zero.set_bit (bitpos);
4848
4849       if (GET_MODE_SIZE (imode) > GET_MODE_SIZE (rmode))
4850         temp = gen_lowpart (rmode, temp);
4851       temp = expand_binop (rmode, and_optab, temp,
4852                            immed_double_int_const (mask, rmode),
4853                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
4854     }
4855   else
4856     {
4857       /* Perform a logical right shift to place the signbit in the least
4858          significant bit, then truncate the result to the desired mode
4859          and mask just this bit.  */
4860       temp = expand_shift (RSHIFT_EXPR, imode, temp, bitpos, NULL_RTX, 1);
4861       temp = gen_lowpart (rmode, temp);
4862       temp = expand_binop (rmode, and_optab, temp, const1_rtx,
4863                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
4864     }
4865
4866   return temp;
4867 }
4868
4869 /* Expand fork or exec calls.  TARGET is the desired target of the
4870    call.  EXP is the call. FN is the
4871    identificator of the actual function.  IGNORE is nonzero if the
4872    value is to be ignored.  */
4873
4874 static rtx
4875 expand_builtin_fork_or_exec (tree fn, tree exp, rtx target, int ignore)
4876 {
4877   tree id, decl;
4878   tree call;
4879
4880   /* If we are not profiling, just call the function.  */
4881   if (!profile_arc_flag)
4882     return NULL_RTX;
4883
4884   /* Otherwise call the wrapper.  This should be equivalent for the rest of
4885      compiler, so the code does not diverge, and the wrapper may run the
4886      code necessary for keeping the profiling sane.  */
4887
4888   switch (DECL_FUNCTION_CODE (fn))
4889     {
4890     case BUILT_IN_FORK:
4891       id = get_identifier ("__gcov_fork");
4892       break;
4893
4894     case BUILT_IN_EXECL:
4895       id = get_identifier ("__gcov_execl");
4896       break;
4897
4898     case BUILT_IN_EXECV:
4899       id = get_identifier ("__gcov_execv");
4900       break;
4901
4902     case BUILT_IN_EXECLP:
4903       id = get_identifier ("__gcov_execlp");
4904       break;
4905
4906     case BUILT_IN_EXECLE:
4907       id = get_identifier ("__gcov_execle");
4908       break;
4909
4910     case BUILT_IN_EXECVP:
4911       id = get_identifier ("__gcov_execvp");
4912       break;
4913
4914     case BUILT_IN_EXECVE:
4915       id = get_identifier ("__gcov_execve");
4916       break;
4917
4918     default:
4919       gcc_unreachable ();
4920     }
4921
4922   decl = build_decl (DECL_SOURCE_LOCATION (fn),
4923                      FUNCTION_DECL, id, TREE_TYPE (fn));
4924   DECL_EXTERNAL (decl) = 1;
4925   TREE_PUBLIC (decl) = 1;
4926   DECL_ARTIFICIAL (decl) = 1;
4927   TREE_NOTHROW (decl) = 1;
4928   DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
4929   DECL_VISIBILITY_SPECIFIED (decl) = 1;
4930   call = rewrite_call_expr (EXPR_LOCATION (exp), exp, 0, decl, 0);
4931   return expand_call (call, target, ignore);
4932  }
4933
4934
4935 \f
4936 /* Reconstitute a mode for a __sync intrinsic operation.  Since the type of
4937    the pointer in these functions is void*, the tree optimizers may remove
4938    casts.  The mode computed in expand_builtin isn't reliable either, due
4939    to __sync_bool_compare_and_swap.
4940
4941    FCODE_DIFF should be fcode - base, where base is the FOO_1 code for the
4942    group of builtins.  This gives us log2 of the mode size.  */
4943
4944 static inline enum machine_mode
4945 get_builtin_sync_mode (int fcode_diff)
4946 {
4947   /* The size is not negotiable, so ask not to get BLKmode in return
4948      if the target indicates that a smaller size would be better.  */
4949   return mode_for_size (BITS_PER_UNIT << fcode_diff, MODE_INT, 0);
4950 }
4951
4952 /* Expand the memory expression LOC and return the appropriate memory operand
4953    for the builtin_sync operations.  */
4954
4955 static rtx
4956 get_builtin_sync_mem (tree loc, enum machine_mode mode)
4957 {
4958   rtx addr, mem;
4959
4960   addr = expand_expr (loc, NULL_RTX, ptr_mode, EXPAND_SUM);
4961   addr = convert_memory_address (Pmode, addr);
4962
4963   /* Note that we explicitly do not want any alias information for this
4964      memory, so that we kill all other live memories.  Otherwise we don't
4965      satisfy the full barrier semantics of the intrinsic.  */
4966   mem = validize_mem (gen_rtx_MEM (mode, addr));
4967
4968   /* The alignment needs to be at least according to that of the mode.  */
4969   set_mem_align (mem, MAX (GET_MODE_ALIGNMENT (mode),
4970                            get_pointer_alignment (loc)));
4971   set_mem_alias_set (mem, ALIAS_SET_MEMORY_BARRIER);
4972   MEM_VOLATILE_P (mem) = 1;
4973
4974   return mem;
4975 }
4976
4977 /* Make sure an argument is in the right mode.
4978    EXP is the tree argument. 
4979    MODE is the mode it should be in.  */
4980
4981 static rtx
4982 expand_expr_force_mode (tree exp, enum machine_mode mode)
4983 {
4984   rtx val;
4985   enum machine_mode old_mode;
4986
4987   val = expand_expr (exp, NULL_RTX, mode, EXPAND_NORMAL);
4988   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
4989      of CONST_INTs, where we know the old_mode only from the call argument.  */
4990
4991   old_mode = GET_MODE (val);
4992   if (old_mode == VOIDmode)
4993     old_mode = TYPE_MODE (TREE_TYPE (exp));
4994   val = convert_modes (mode, old_mode, val, 1);
4995   return val;
4996 }
4997
4998
4999 /* Expand the __sync_xxx_and_fetch and __sync_fetch_and_xxx intrinsics.
5000    EXP is the CALL_EXPR.  CODE is the rtx code
5001    that corresponds to the arithmetic or logical operation from the name;
5002    an exception here is that NOT actually means NAND.  TARGET is an optional
5003    place for us to store the results; AFTER is true if this is the
5004    fetch_and_xxx form.  */
5005
5006 static rtx
5007 expand_builtin_sync_operation (enum machine_mode mode, tree exp,
5008                                enum rtx_code code, bool after,
5009                                rtx target)
5010 {
5011   rtx val, mem;
5012   location_t loc = EXPR_LOCATION (exp);
5013
5014   if (code == NOT && warn_sync_nand)
5015     {
5016       tree fndecl = get_callee_fndecl (exp);
5017       enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5018
5019       static bool warned_f_a_n, warned_n_a_f;
5020
5021       switch (fcode)
5022         {
5023         case BUILT_IN_SYNC_FETCH_AND_NAND_1:
5024         case BUILT_IN_SYNC_FETCH_AND_NAND_2:
5025         case BUILT_IN_SYNC_FETCH_AND_NAND_4:
5026         case BUILT_IN_SYNC_FETCH_AND_NAND_8:
5027         case BUILT_IN_SYNC_FETCH_AND_NAND_16:
5028           if (warned_f_a_n)
5029             break;
5030
5031           fndecl = builtin_decl_implicit (BUILT_IN_SYNC_FETCH_AND_NAND_N);
5032           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
5033           warned_f_a_n = true;
5034           break;
5035
5036         case BUILT_IN_SYNC_NAND_AND_FETCH_1:
5037         case BUILT_IN_SYNC_NAND_AND_FETCH_2:
5038         case BUILT_IN_SYNC_NAND_AND_FETCH_4:
5039         case BUILT_IN_SYNC_NAND_AND_FETCH_8:
5040         case BUILT_IN_SYNC_NAND_AND_FETCH_16:
5041           if (warned_n_a_f)
5042             break;
5043
5044          fndecl = builtin_decl_implicit (BUILT_IN_SYNC_NAND_AND_FETCH_N);
5045           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
5046           warned_n_a_f = true;
5047           break;
5048
5049         default:
5050           gcc_unreachable ();
5051         }
5052     }
5053
5054   /* Expand the operands.  */
5055   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5056   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5057
5058   return expand_atomic_fetch_op (target, mem, val, code, MEMMODEL_SEQ_CST,
5059                                  after);
5060 }
5061
5062 /* Expand the __sync_val_compare_and_swap and __sync_bool_compare_and_swap
5063    intrinsics. EXP is the CALL_EXPR.  IS_BOOL is
5064    true if this is the boolean form.  TARGET is a place for us to store the
5065    results; this is NOT optional if IS_BOOL is true.  */
5066
5067 static rtx
5068 expand_builtin_compare_and_swap (enum machine_mode mode, tree exp,
5069                                  bool is_bool, rtx target)
5070 {
5071   rtx old_val, new_val, mem;
5072   rtx *pbool, *poval;
5073
5074   /* Expand the operands.  */
5075   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5076   old_val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5077   new_val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 2), mode);
5078
5079   pbool = poval = NULL;
5080   if (target != const0_rtx)
5081     {
5082       if (is_bool)
5083         pbool = &target;
5084       else
5085         poval = &target;
5086     }
5087   if (!expand_atomic_compare_and_swap (pbool, poval, mem, old_val, new_val,
5088                                        false, MEMMODEL_SEQ_CST,
5089                                        MEMMODEL_SEQ_CST))
5090     return NULL_RTX;
5091
5092   return target;
5093 }
5094
5095 /* Expand the __sync_lock_test_and_set intrinsic.  Note that the most
5096    general form is actually an atomic exchange, and some targets only
5097    support a reduced form with the second argument being a constant 1.
5098    EXP is the CALL_EXPR; TARGET is an optional place for us to store
5099    the results.  */
5100
5101 static rtx
5102 expand_builtin_sync_lock_test_and_set (enum machine_mode mode, tree exp,
5103                                        rtx target)
5104 {
5105   rtx val, mem;
5106
5107   /* Expand the operands.  */
5108   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5109   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5110
5111   return expand_sync_lock_test_and_set (target, mem, val);
5112 }
5113
5114 /* Expand the __sync_lock_release intrinsic.  EXP is the CALL_EXPR.  */
5115
5116 static void
5117 expand_builtin_sync_lock_release (enum machine_mode mode, tree exp)
5118 {
5119   rtx mem;
5120
5121   /* Expand the operands.  */
5122   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5123
5124   expand_atomic_store (mem, const0_rtx, MEMMODEL_RELEASE, true);
5125 }
5126
5127 /* Given an integer representing an ``enum memmodel'', verify its
5128    correctness and return the memory model enum.  */
5129
5130 static enum memmodel
5131 get_memmodel (tree exp)
5132 {
5133   rtx op;
5134   unsigned HOST_WIDE_INT val;
5135
5136   /* If the parameter is not a constant, it's a run time value so we'll just
5137      convert it to MEMMODEL_SEQ_CST to avoid annoying runtime checking.  */
5138   if (TREE_CODE (exp) != INTEGER_CST)
5139     return MEMMODEL_SEQ_CST;
5140
5141   op = expand_normal (exp);
5142
5143   val = INTVAL (op);
5144   if (targetm.memmodel_check)
5145     val = targetm.memmodel_check (val);
5146   else if (val & ~MEMMODEL_MASK)
5147     {
5148       warning (OPT_Winvalid_memory_model,
5149                "Unknown architecture specifier in memory model to builtin.");
5150       return MEMMODEL_SEQ_CST;
5151     }
5152
5153   if ((INTVAL (op) & MEMMODEL_MASK) >= MEMMODEL_LAST)
5154     {
5155       warning (OPT_Winvalid_memory_model,
5156                "invalid memory model argument to builtin");
5157       return MEMMODEL_SEQ_CST;
5158     }
5159
5160   return (enum memmodel) val;
5161 }
5162
5163 /* Expand the __atomic_exchange intrinsic:
5164         TYPE __atomic_exchange (TYPE *object, TYPE desired, enum memmodel)
5165    EXP is the CALL_EXPR.
5166    TARGET is an optional place for us to store the results.  */
5167
5168 static rtx
5169 expand_builtin_atomic_exchange (enum machine_mode mode, tree exp, rtx target)
5170 {
5171   rtx val, mem;
5172   enum memmodel model;
5173
5174   model = get_memmodel (CALL_EXPR_ARG (exp, 2));
5175   if ((model & MEMMODEL_MASK) == MEMMODEL_CONSUME)
5176     {
5177       error ("invalid memory model for %<__atomic_exchange%>");
5178       return NULL_RTX;
5179     }
5180
5181   if (!flag_inline_atomics)
5182     return NULL_RTX;
5183
5184   /* Expand the operands.  */
5185   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5186   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5187
5188   return expand_atomic_exchange (target, mem, val, model);
5189 }
5190
5191 /* Expand the __atomic_compare_exchange intrinsic:
5192         bool __atomic_compare_exchange (TYPE *object, TYPE *expect, 
5193                                         TYPE desired, BOOL weak, 
5194                                         enum memmodel success,
5195                                         enum memmodel failure)
5196    EXP is the CALL_EXPR.
5197    TARGET is an optional place for us to store the results.  */
5198
5199 static rtx
5200 expand_builtin_atomic_compare_exchange (enum machine_mode mode, tree exp, 
5201                                         rtx target)
5202 {
5203   rtx expect, desired, mem, oldval;
5204   enum memmodel success, failure;
5205   tree weak;
5206   bool is_weak;
5207
5208   success = get_memmodel (CALL_EXPR_ARG (exp, 4));
5209   failure = get_memmodel (CALL_EXPR_ARG (exp, 5));
5210
5211   if ((failure & MEMMODEL_MASK) == MEMMODEL_RELEASE
5212       || (failure & MEMMODEL_MASK) == MEMMODEL_ACQ_REL)
5213     {
5214       error ("invalid failure memory model for %<__atomic_compare_exchange%>");
5215       return NULL_RTX;
5216     }
5217
5218   if (failure > success)
5219     {
5220       error ("failure memory model cannot be stronger than success "
5221              "memory model for %<__atomic_compare_exchange%>");
5222       return NULL_RTX;
5223     }
5224   
5225   if (!flag_inline_atomics)
5226     return NULL_RTX;
5227
5228   /* Expand the operands.  */
5229   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5230
5231   expect = expand_normal (CALL_EXPR_ARG (exp, 1));
5232   expect = convert_memory_address (Pmode, expect);
5233   expect = gen_rtx_MEM (mode, expect);
5234   desired = expand_expr_force_mode (CALL_EXPR_ARG (exp, 2), mode);
5235
5236   weak = CALL_EXPR_ARG (exp, 3);
5237   is_weak = false;
5238   if (host_integerp (weak, 0) && tree_low_cst (weak, 0) != 0)
5239     is_weak = true;
5240
5241   oldval = expect;
5242   if (!expand_atomic_compare_and_swap ((target == const0_rtx ? NULL : &target),
5243                                        &oldval, mem, oldval, desired,
5244                                        is_weak, success, failure))
5245     return NULL_RTX;
5246
5247   if (oldval != expect)
5248     emit_move_insn (expect, oldval);
5249
5250   return target;
5251 }
5252
5253 /* Expand the __atomic_load intrinsic:
5254         TYPE __atomic_load (TYPE *object, enum memmodel)
5255    EXP is the CALL_EXPR.
5256    TARGET is an optional place for us to store the results.  */
5257
5258 static rtx
5259 expand_builtin_atomic_load (enum machine_mode mode, tree exp, rtx target)
5260 {
5261   rtx mem;
5262   enum memmodel model;
5263
5264   model = get_memmodel (CALL_EXPR_ARG (exp, 1));
5265   if ((model & MEMMODEL_MASK) == MEMMODEL_RELEASE
5266       || (model & MEMMODEL_MASK) == MEMMODEL_ACQ_REL)
5267     {
5268       error ("invalid memory model for %<__atomic_load%>");
5269       return NULL_RTX;
5270     }
5271
5272   if (!flag_inline_atomics)
5273     return NULL_RTX;
5274
5275   /* Expand the operand.  */
5276   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5277
5278   return expand_atomic_load (target, mem, model);
5279 }
5280
5281
5282 /* Expand the __atomic_store intrinsic:
5283         void __atomic_store (TYPE *object, TYPE desired, enum memmodel)
5284    EXP is the CALL_EXPR.
5285    TARGET is an optional place for us to store the results.  */
5286
5287 static rtx
5288 expand_builtin_atomic_store (enum machine_mode mode, tree exp)
5289 {
5290   rtx mem, val;
5291   enum memmodel model;
5292
5293   model = get_memmodel (CALL_EXPR_ARG (exp, 2));
5294   if ((model & MEMMODEL_MASK) != MEMMODEL_RELAXED
5295       && (model & MEMMODEL_MASK) != MEMMODEL_SEQ_CST
5296       && (model & MEMMODEL_MASK) != MEMMODEL_RELEASE)
5297     {
5298       error ("invalid memory model for %<__atomic_store%>");
5299       return NULL_RTX;
5300     }
5301
5302   if (!flag_inline_atomics)
5303     return NULL_RTX;
5304
5305   /* Expand the operands.  */
5306   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5307   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5308
5309   return expand_atomic_store (mem, val, model, false);
5310 }
5311
5312 /* Expand the __atomic_fetch_XXX intrinsic:
5313         TYPE __atomic_fetch_XXX (TYPE *object, TYPE val, enum memmodel)
5314    EXP is the CALL_EXPR.
5315    TARGET is an optional place for us to store the results.
5316    CODE is the operation, PLUS, MINUS, ADD, XOR, or IOR.
5317    FETCH_AFTER is true if returning the result of the operation.
5318    FETCH_AFTER is false if returning the value before the operation.
5319    IGNORE is true if the result is not used.
5320    EXT_CALL is the correct builtin for an external call if this cannot be
5321    resolved to an instruction sequence.  */
5322
5323 static rtx
5324 expand_builtin_atomic_fetch_op (enum machine_mode mode, tree exp, rtx target,
5325                                 enum rtx_code code, bool fetch_after,
5326                                 bool ignore, enum built_in_function ext_call)
5327 {
5328   rtx val, mem, ret;
5329   enum memmodel model;
5330   tree fndecl;
5331   tree addr;
5332
5333   model = get_memmodel (CALL_EXPR_ARG (exp, 2));
5334
5335   /* Expand the operands.  */
5336   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5337   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5338
5339   /* Only try generating instructions if inlining is turned on.  */
5340   if (flag_inline_atomics)
5341     {
5342       ret = expand_atomic_fetch_op (target, mem, val, code, model, fetch_after);
5343       if (ret)
5344         return ret;
5345     }
5346
5347   /* Return if a different routine isn't needed for the library call.  */
5348   if (ext_call == BUILT_IN_NONE)
5349     return NULL_RTX;
5350
5351   /* Change the call to the specified function.  */
5352   fndecl = get_callee_fndecl (exp);
5353   addr = CALL_EXPR_FN (exp);
5354   STRIP_NOPS (addr);
5355
5356   gcc_assert (TREE_OPERAND (addr, 0) == fndecl);
5357   TREE_OPERAND (addr, 0) = builtin_decl_explicit (ext_call);
5358
5359   /* Expand the call here so we can emit trailing code.  */
5360   ret = expand_call (exp, target, ignore);
5361
5362   /* Replace the original function just in case it matters.  */
5363   TREE_OPERAND (addr, 0) = fndecl;
5364
5365   /* Then issue the arithmetic correction to return the right result.  */
5366   if (!ignore)
5367     {
5368       if (code == NOT)
5369         {
5370           ret = expand_simple_binop (mode, AND, ret, val, NULL_RTX, true,
5371                                      OPTAB_LIB_WIDEN);
5372           ret = expand_simple_unop (mode, NOT, ret, target, true);
5373         }
5374       else
5375         ret = expand_simple_binop (mode, code, ret, val, target, true,
5376                                    OPTAB_LIB_WIDEN);
5377     }
5378   return ret;
5379 }
5380
5381
5382 #ifndef HAVE_atomic_clear
5383 # define HAVE_atomic_clear 0
5384 # define gen_atomic_clear(x,y) (gcc_unreachable (), NULL_RTX)
5385 #endif
5386
5387 /* Expand an atomic clear operation.
5388         void _atomic_clear (BOOL *obj, enum memmodel)
5389    EXP is the call expression.  */
5390
5391 static rtx
5392 expand_builtin_atomic_clear (tree exp) 
5393 {
5394   enum machine_mode mode;
5395   rtx mem, ret;
5396   enum memmodel model;
5397
5398   mode = mode_for_size (BOOL_TYPE_SIZE, MODE_INT, 0);
5399   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5400   model = get_memmodel (CALL_EXPR_ARG (exp, 1));
5401
5402   if ((model & MEMMODEL_MASK) == MEMMODEL_ACQUIRE
5403       || (model & MEMMODEL_MASK) == MEMMODEL_ACQ_REL)
5404     {
5405       error ("invalid memory model for %<__atomic_store%>");
5406       return const0_rtx;
5407     }
5408
5409   if (HAVE_atomic_clear)
5410     {
5411       emit_insn (gen_atomic_clear (mem, model));
5412       return const0_rtx;
5413     }
5414
5415   /* Try issuing an __atomic_store, and allow fallback to __sync_lock_release.
5416      Failing that, a store is issued by __atomic_store.  The only way this can
5417      fail is if the bool type is larger than a word size.  Unlikely, but
5418      handle it anyway for completeness.  Assume a single threaded model since
5419      there is no atomic support in this case, and no barriers are required.  */
5420   ret = expand_atomic_store (mem, const0_rtx, model, true);
5421   if (!ret)
5422     emit_move_insn (mem, const0_rtx);
5423   return const0_rtx;
5424 }
5425
5426 /* Expand an atomic test_and_set operation.
5427         bool _atomic_test_and_set (BOOL *obj, enum memmodel)
5428    EXP is the call expression.  */
5429
5430 static rtx
5431 expand_builtin_atomic_test_and_set (tree exp, rtx target)
5432 {
5433   rtx mem;
5434   enum memmodel model;
5435   enum machine_mode mode;
5436
5437   mode = mode_for_size (BOOL_TYPE_SIZE, MODE_INT, 0);
5438   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5439   model = get_memmodel (CALL_EXPR_ARG (exp, 1));
5440
5441   return expand_atomic_test_and_set (target, mem, model);
5442 }
5443
5444
5445 /* Return true if (optional) argument ARG1 of size ARG0 is always lock free on
5446    this architecture.  If ARG1 is NULL, use typical alignment for size ARG0.  */
5447
5448 static tree
5449 fold_builtin_atomic_always_lock_free (tree arg0, tree arg1)
5450 {
5451   int size;
5452   enum machine_mode mode;
5453   unsigned int mode_align, type_align;
5454
5455   if (TREE_CODE (arg0) != INTEGER_CST)
5456     return NULL_TREE;
5457
5458   size = INTVAL (expand_normal (arg0)) * BITS_PER_UNIT;
5459   mode = mode_for_size (size, MODE_INT, 0);
5460   mode_align = GET_MODE_ALIGNMENT (mode);
5461
5462   if (TREE_CODE (arg1) == INTEGER_CST && INTVAL (expand_normal (arg1)) == 0)
5463     type_align = mode_align;
5464   else
5465     {
5466       tree ttype = TREE_TYPE (arg1);
5467
5468       /* This function is usually invoked and folded immediately by the front
5469          end before anything else has a chance to look at it.  The pointer
5470          parameter at this point is usually cast to a void *, so check for that
5471          and look past the cast.  */
5472       if (TREE_CODE (arg1) == NOP_EXPR && POINTER_TYPE_P (ttype)
5473           && VOID_TYPE_P (TREE_TYPE (ttype)))
5474         arg1 = TREE_OPERAND (arg1, 0);
5475
5476       ttype = TREE_TYPE (arg1);
5477       gcc_assert (POINTER_TYPE_P (ttype));
5478
5479       /* Get the underlying type of the object.  */
5480       ttype = TREE_TYPE (ttype);
5481       type_align = TYPE_ALIGN (ttype);
5482     }
5483
5484   /* If the object has smaller alignment, the the lock free routines cannot
5485      be used.  */
5486   if (type_align < mode_align)
5487     return boolean_false_node;
5488
5489   /* Check if a compare_and_swap pattern exists for the mode which represents
5490      the required size.  The pattern is not allowed to fail, so the existence
5491      of the pattern indicates support is present.  */
5492   if (can_compare_and_swap_p (mode, true))
5493     return boolean_true_node;
5494   else
5495     return boolean_false_node;
5496 }
5497
5498 /* Return true if the parameters to call EXP represent an object which will
5499    always generate lock free instructions.  The first argument represents the
5500    size of the object, and the second parameter is a pointer to the object 
5501    itself.  If NULL is passed for the object, then the result is based on 
5502    typical alignment for an object of the specified size.  Otherwise return 
5503    false.  */
5504
5505 static rtx
5506 expand_builtin_atomic_always_lock_free (tree exp)
5507 {
5508   tree size;
5509   tree arg0 = CALL_EXPR_ARG (exp, 0);
5510   tree arg1 = CALL_EXPR_ARG (exp, 1);
5511
5512   if (TREE_CODE (arg0) != INTEGER_CST)
5513     {
5514       error ("non-constant argument 1 to __atomic_always_lock_free");
5515       return const0_rtx;
5516     }
5517
5518   size = fold_builtin_atomic_always_lock_free (arg0, arg1);
5519   if (size == boolean_true_node)
5520     return const1_rtx;
5521   return const0_rtx;
5522 }
5523
5524 /* Return a one or zero if it can be determined that object ARG1 of size ARG 
5525    is lock free on this architecture.  */
5526
5527 static tree
5528 fold_builtin_atomic_is_lock_free (tree arg0, tree arg1)
5529 {
5530   if (!flag_inline_atomics)
5531     return NULL_TREE;
5532   
5533   /* If it isn't always lock free, don't generate a result.  */
5534   if (fold_builtin_atomic_always_lock_free (arg0, arg1) == boolean_true_node)
5535     return boolean_true_node;
5536
5537   return NULL_TREE;
5538 }
5539
5540 /* Return true if the parameters to call EXP represent an object which will
5541    always generate lock free instructions.  The first argument represents the
5542    size of the object, and the second parameter is a pointer to the object 
5543    itself.  If NULL is passed for the object, then the result is based on 
5544    typical alignment for an object of the specified size.  Otherwise return 
5545    NULL*/
5546
5547 static rtx
5548 expand_builtin_atomic_is_lock_free (tree exp)
5549 {
5550   tree size;
5551   tree arg0 = CALL_EXPR_ARG (exp, 0);
5552   tree arg1 = CALL_EXPR_ARG (exp, 1);
5553
5554   if (!INTEGRAL_TYPE_P (TREE_TYPE (arg0)))
5555     {
5556       error ("non-integer argument 1 to __atomic_is_lock_free");
5557       return NULL_RTX;
5558     }
5559
5560   if (!flag_inline_atomics)
5561     return NULL_RTX; 
5562
5563   /* If the value is known at compile time, return the RTX for it.  */
5564   size = fold_builtin_atomic_is_lock_free (arg0, arg1);
5565   if (size == boolean_true_node)
5566     return const1_rtx;
5567
5568   return NULL_RTX;
5569 }
5570
5571 /* Expand the __atomic_thread_fence intrinsic:
5572         void __atomic_thread_fence (enum memmodel)
5573    EXP is the CALL_EXPR.  */
5574
5575 static void
5576 expand_builtin_atomic_thread_fence (tree exp)
5577 {
5578   enum memmodel model = get_memmodel (CALL_EXPR_ARG (exp, 0));
5579   expand_mem_thread_fence (model);
5580 }
5581
5582 /* Expand the __atomic_signal_fence intrinsic:
5583         void __atomic_signal_fence (enum memmodel)
5584    EXP is the CALL_EXPR.  */
5585
5586 static void
5587 expand_builtin_atomic_signal_fence (tree exp)
5588 {
5589   enum memmodel model = get_memmodel (CALL_EXPR_ARG (exp, 0));
5590   expand_mem_signal_fence (model);
5591 }
5592
5593 /* Expand the __sync_synchronize intrinsic.  */
5594
5595 static void
5596 expand_builtin_sync_synchronize (void)
5597 {
5598   expand_mem_thread_fence (MEMMODEL_SEQ_CST);
5599 }
5600
5601 static rtx
5602 expand_builtin_thread_pointer (tree exp, rtx target)
5603 {
5604   enum insn_code icode;
5605   if (!validate_arglist (exp, VOID_TYPE))
5606     return const0_rtx;
5607   icode = direct_optab_handler (get_thread_pointer_optab, Pmode);
5608   if (icode != CODE_FOR_nothing)
5609     {
5610       struct expand_operand op;
5611       if (!REG_P (target) || GET_MODE (target) != Pmode)
5612         target = gen_reg_rtx (Pmode);
5613       create_output_operand (&op, target, Pmode);
5614       expand_insn (icode, 1, &op);
5615       return target;
5616     }
5617   error ("__builtin_thread_pointer is not supported on this target");
5618   return const0_rtx;
5619 }
5620
5621 static void
5622 expand_builtin_set_thread_pointer (tree exp)
5623 {
5624   enum insn_code icode;
5625   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
5626     return;
5627   icode = direct_optab_handler (set_thread_pointer_optab, Pmode);
5628   if (icode != CODE_FOR_nothing)
5629     {
5630       struct expand_operand op;
5631       rtx val = expand_expr (CALL_EXPR_ARG (exp, 0), NULL_RTX,
5632                              Pmode, EXPAND_NORMAL);      
5633       create_input_operand (&op, val, Pmode);
5634       expand_insn (icode, 1, &op);
5635       return;
5636     }
5637   error ("__builtin_set_thread_pointer is not supported on this target");
5638 }
5639
5640 \f
5641 /* Emit code to restore the current value of stack.  */
5642
5643 static void
5644 expand_stack_restore (tree var)
5645 {
5646   rtx prev, sa = expand_normal (var);
5647
5648   sa = convert_memory_address (Pmode, sa);
5649
5650   prev = get_last_insn ();
5651   emit_stack_restore (SAVE_BLOCK, sa);
5652   fixup_args_size_notes (prev, get_last_insn (), 0);
5653 }
5654
5655
5656 /* Emit code to save the current value of stack.  */
5657
5658 static rtx
5659 expand_stack_save (void)
5660 {
5661   rtx ret = NULL_RTX;
5662
5663   do_pending_stack_adjust ();
5664   emit_stack_save (SAVE_BLOCK, &ret);
5665   return ret;
5666 }
5667
5668 /* Expand an expression EXP that calls a built-in function,
5669    with result going to TARGET if that's convenient
5670    (and in mode MODE if that's convenient).
5671    SUBTARGET may be used as the target for computing one of EXP's operands.
5672    IGNORE is nonzero if the value is to be ignored.  */
5673
5674 rtx
5675 expand_builtin (tree exp, rtx target, rtx subtarget, enum machine_mode mode,
5676                 int ignore)
5677 {
5678   tree fndecl = get_callee_fndecl (exp);
5679   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5680   enum machine_mode target_mode = TYPE_MODE (TREE_TYPE (exp));
5681   int flags;
5682
5683   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
5684     return targetm.expand_builtin (exp, target, subtarget, mode, ignore);
5685
5686   /* When not optimizing, generate calls to library functions for a certain
5687      set of builtins.  */
5688   if (!optimize
5689       && !called_as_built_in (fndecl)
5690       && fcode != BUILT_IN_FORK
5691       && fcode != BUILT_IN_EXECL
5692       && fcode != BUILT_IN_EXECV
5693       && fcode != BUILT_IN_EXECLP
5694       && fcode != BUILT_IN_EXECLE
5695       && fcode != BUILT_IN_EXECVP
5696       && fcode != BUILT_IN_EXECVE
5697       && fcode != BUILT_IN_ALLOCA
5698       && fcode != BUILT_IN_ALLOCA_WITH_ALIGN
5699       && fcode != BUILT_IN_FREE
5700       && fcode != BUILT_IN_CHKP_SET_PTR_BOUNDS
5701       && fcode != BUILT_IN_CHKP_INIT_PTR_BOUNDS
5702       && fcode != BUILT_IN_CHKP_NULL_PTR_BOUNDS
5703       && fcode != BUILT_IN_CHKP_COPY_PTR_BOUNDS
5704       && fcode != BUILT_IN_CHKP_NARROW_PTR_BOUNDS
5705       && fcode != BUILT_IN_CHKP_STORE_PTR_BOUNDS
5706       && fcode != BUILT_IN_CHKP_CHECK_PTR_LBOUNDS
5707       && fcode != BUILT_IN_CHKP_CHECK_PTR_UBOUNDS
5708       && fcode != BUILT_IN_CHKP_CHECK_PTR_BOUNDS
5709       && fcode != BUILT_IN_CHKP_GET_PTR_LBOUND
5710       && fcode != BUILT_IN_CHKP_GET_PTR_UBOUND)
5711     return expand_call (exp, target, ignore);
5712
5713   /* The built-in function expanders test for target == const0_rtx
5714      to determine whether the function's result will be ignored.  */
5715   if (ignore)
5716     target = const0_rtx;
5717
5718   /* If the result of a pure or const built-in function is ignored, and
5719      none of its arguments are volatile, we can avoid expanding the
5720      built-in call and just evaluate the arguments for side-effects.  */
5721   if (target == const0_rtx
5722       && ((flags = flags_from_decl_or_type (fndecl)) & (ECF_CONST | ECF_PURE))
5723       && !(flags & ECF_LOOPING_CONST_OR_PURE))
5724     {
5725       bool volatilep = false;
5726       tree arg;
5727       call_expr_arg_iterator iter;
5728
5729       FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5730         if (TREE_THIS_VOLATILE (arg))
5731           {
5732             volatilep = true;
5733             break;
5734           }
5735
5736       if (! volatilep)
5737         {
5738           FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5739             expand_expr (arg, const0_rtx, VOIDmode, EXPAND_NORMAL);
5740           return const0_rtx;
5741         }
5742     }
5743
5744   switch (fcode)
5745     {
5746     CASE_FLT_FN (BUILT_IN_FABS):
5747     case BUILT_IN_FABSD32:
5748     case BUILT_IN_FABSD64:
5749     case BUILT_IN_FABSD128:
5750       target = expand_builtin_fabs (exp, target, subtarget);
5751       if (target)
5752         return target;
5753       break;
5754
5755     CASE_FLT_FN (BUILT_IN_COPYSIGN):
5756       target = expand_builtin_copysign (exp, target, subtarget);
5757       if (target)
5758         return target;
5759       break;
5760
5761       /* Just do a normal library call if we were unable to fold
5762          the values.  */
5763     CASE_FLT_FN (BUILT_IN_CABS):
5764       break;
5765
5766     CASE_FLT_FN (BUILT_IN_EXP):
5767     CASE_FLT_FN (BUILT_IN_EXP10):
5768     CASE_FLT_FN (BUILT_IN_POW10):
5769     CASE_FLT_FN (BUILT_IN_EXP2):
5770     CASE_FLT_FN (BUILT_IN_EXPM1):
5771     CASE_FLT_FN (BUILT_IN_LOGB):
5772     CASE_FLT_FN (BUILT_IN_LOG):
5773     CASE_FLT_FN (BUILT_IN_LOG10):
5774     CASE_FLT_FN (BUILT_IN_LOG2):
5775     CASE_FLT_FN (BUILT_IN_LOG1P):
5776     CASE_FLT_FN (BUILT_IN_TAN):
5777     CASE_FLT_FN (BUILT_IN_ASIN):
5778     CASE_FLT_FN (BUILT_IN_ACOS):
5779     CASE_FLT_FN (BUILT_IN_ATAN):
5780     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
5781       /* Treat these like sqrt only if unsafe math optimizations are allowed,
5782          because of possible accuracy problems.  */
5783       if (! flag_unsafe_math_optimizations)
5784         break;
5785     CASE_FLT_FN (BUILT_IN_SQRT):
5786     CASE_FLT_FN (BUILT_IN_FLOOR):
5787     CASE_FLT_FN (BUILT_IN_CEIL):
5788     CASE_FLT_FN (BUILT_IN_TRUNC):
5789     CASE_FLT_FN (BUILT_IN_ROUND):
5790     CASE_FLT_FN (BUILT_IN_NEARBYINT):
5791     CASE_FLT_FN (BUILT_IN_RINT):
5792       target = expand_builtin_mathfn (exp, target, subtarget);
5793       if (target)
5794         return target;
5795       break;
5796
5797     CASE_FLT_FN (BUILT_IN_FMA):
5798       target = expand_builtin_mathfn_ternary (exp, target, subtarget);
5799       if (target)
5800         return target;
5801       break;
5802
5803     CASE_FLT_FN (BUILT_IN_ILOGB):
5804       if (! flag_unsafe_math_optimizations)
5805         break;
5806     CASE_FLT_FN (BUILT_IN_ISINF):
5807     CASE_FLT_FN (BUILT_IN_FINITE):
5808     case BUILT_IN_ISFINITE:
5809     case BUILT_IN_ISNORMAL:
5810       target = expand_builtin_interclass_mathfn (exp, target);
5811       if (target)
5812         return target;
5813       break;
5814
5815     CASE_FLT_FN (BUILT_IN_ICEIL):
5816     CASE_FLT_FN (BUILT_IN_LCEIL):
5817     CASE_FLT_FN (BUILT_IN_LLCEIL):
5818     CASE_FLT_FN (BUILT_IN_LFLOOR):
5819     CASE_FLT_FN (BUILT_IN_IFLOOR):
5820     CASE_FLT_FN (BUILT_IN_LLFLOOR):
5821       target = expand_builtin_int_roundingfn (exp, target);
5822       if (target)
5823         return target;
5824       break;
5825
5826     CASE_FLT_FN (BUILT_IN_IRINT):
5827     CASE_FLT_FN (BUILT_IN_LRINT):
5828     CASE_FLT_FN (BUILT_IN_LLRINT):
5829     CASE_FLT_FN (BUILT_IN_IROUND):
5830     CASE_FLT_FN (BUILT_IN_LROUND):
5831     CASE_FLT_FN (BUILT_IN_LLROUND):
5832       target = expand_builtin_int_roundingfn_2 (exp, target);
5833       if (target)
5834         return target;
5835       break;
5836
5837     CASE_FLT_FN (BUILT_IN_POWI):
5838       target = expand_builtin_powi (exp, target);
5839       if (target)
5840         return target;
5841       break;
5842
5843     CASE_FLT_FN (BUILT_IN_ATAN2):
5844     CASE_FLT_FN (BUILT_IN_LDEXP):
5845     CASE_FLT_FN (BUILT_IN_SCALB):
5846     CASE_FLT_FN (BUILT_IN_SCALBN):
5847     CASE_FLT_FN (BUILT_IN_SCALBLN):
5848       if (! flag_unsafe_math_optimizations)
5849         break;
5850
5851     CASE_FLT_FN (BUILT_IN_FMOD):
5852     CASE_FLT_FN (BUILT_IN_REMAINDER):
5853     CASE_FLT_FN (BUILT_IN_DREM):
5854     CASE_FLT_FN (BUILT_IN_POW):
5855       target = expand_builtin_mathfn_2 (exp, target, subtarget);
5856       if (target)
5857         return target;
5858       break;
5859
5860     CASE_FLT_FN (BUILT_IN_CEXPI):
5861       target = expand_builtin_cexpi (exp, target);
5862       gcc_assert (target);
5863       return target;
5864
5865     CASE_FLT_FN (BUILT_IN_SIN):
5866     CASE_FLT_FN (BUILT_IN_COS):
5867       if (! flag_unsafe_math_optimizations)
5868         break;
5869       target = expand_builtin_mathfn_3 (exp, target, subtarget);
5870       if (target)
5871         return target;
5872       break;
5873
5874     CASE_FLT_FN (BUILT_IN_SINCOS):
5875       if (! flag_unsafe_math_optimizations)
5876         break;
5877       target = expand_builtin_sincos (exp);
5878       if (target)
5879         return target;
5880       break;
5881
5882     case BUILT_IN_APPLY_ARGS:
5883       return expand_builtin_apply_args ();
5884
5885       /* __builtin_apply (FUNCTION, ARGUMENTS, ARGSIZE) invokes
5886          FUNCTION with a copy of the parameters described by
5887          ARGUMENTS, and ARGSIZE.  It returns a block of memory
5888          allocated on the stack into which is stored all the registers
5889          that might possibly be used for returning the result of a
5890          function.  ARGUMENTS is the value returned by
5891          __builtin_apply_args.  ARGSIZE is the number of bytes of
5892          arguments that must be copied.  ??? How should this value be
5893          computed?  We'll also need a safe worst case value for varargs
5894          functions.  */
5895     case BUILT_IN_APPLY:
5896       if (!validate_arglist (exp, POINTER_TYPE,
5897                              POINTER_TYPE, INTEGER_TYPE, VOID_TYPE)
5898           && !validate_arglist (exp, REFERENCE_TYPE,
5899                                 POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
5900         return const0_rtx;
5901       else
5902         {
5903           rtx ops[3];
5904
5905           ops[0] = expand_normal (CALL_EXPR_ARG (exp, 0));
5906           ops[1] = expand_normal (CALL_EXPR_ARG (exp, 1));
5907           ops[2] = expand_normal (CALL_EXPR_ARG (exp, 2));
5908
5909           return expand_builtin_apply (ops[0], ops[1], ops[2]);
5910         }
5911
5912       /* __builtin_return (RESULT) causes the function to return the
5913          value described by RESULT.  RESULT is address of the block of
5914          memory returned by __builtin_apply.  */
5915     case BUILT_IN_RETURN:
5916       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
5917         expand_builtin_return (expand_normal (CALL_EXPR_ARG (exp, 0)));
5918       return const0_rtx;
5919
5920     case BUILT_IN_SAVEREGS:
5921       return expand_builtin_saveregs ();
5922
5923     case BUILT_IN_VA_ARG_PACK:
5924       /* All valid uses of __builtin_va_arg_pack () are removed during
5925          inlining.  */
5926       error ("%Kinvalid use of %<__builtin_va_arg_pack ()%>", exp);
5927       return const0_rtx;
5928
5929     case BUILT_IN_VA_ARG_PACK_LEN:
5930       /* All valid uses of __builtin_va_arg_pack_len () are removed during
5931          inlining.  */
5932       error ("%Kinvalid use of %<__builtin_va_arg_pack_len ()%>", exp);
5933       return const0_rtx;
5934
5935       /* Return the address of the first anonymous stack arg.  */
5936     case BUILT_IN_NEXT_ARG:
5937       if (fold_builtin_next_arg (exp, false))
5938         return const0_rtx;
5939       return expand_builtin_next_arg ();
5940
5941     case BUILT_IN_CLEAR_CACHE:
5942       target = expand_builtin___clear_cache (exp);
5943       if (target)
5944         return target;
5945       break;
5946
5947     case BUILT_IN_CLASSIFY_TYPE:
5948       return expand_builtin_classify_type (exp);
5949
5950     case BUILT_IN_CONSTANT_P:
5951       return const0_rtx;
5952
5953     case BUILT_IN_FRAME_ADDRESS:
5954     case BUILT_IN_RETURN_ADDRESS:
5955       return expand_builtin_frame_address (fndecl, exp);
5956
5957     /* Returns the address of the area where the structure is returned.
5958        0 otherwise.  */
5959     case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
5960       if (call_expr_nargs (exp) != 0
5961           || ! AGGREGATE_TYPE_P (TREE_TYPE (TREE_TYPE (current_function_decl)))
5962           || !MEM_P (DECL_RTL (DECL_RESULT (current_function_decl))))
5963         return const0_rtx;
5964       else
5965         return XEXP (DECL_RTL (DECL_RESULT (current_function_decl)), 0);
5966
5967     case BUILT_IN_ALLOCA:
5968     case BUILT_IN_ALLOCA_WITH_ALIGN:
5969       /* If the allocation stems from the declaration of a variable-sized
5970          object, it cannot accumulate.  */
5971       target = expand_builtin_alloca (exp, CALL_ALLOCA_FOR_VAR_P (exp));
5972       if (target)
5973         return target;
5974       break;
5975
5976     case BUILT_IN_STACK_SAVE:
5977       return expand_stack_save ();
5978
5979     case BUILT_IN_STACK_RESTORE:
5980       expand_stack_restore (CALL_EXPR_ARG (exp, 0));
5981       return const0_rtx;
5982
5983     case BUILT_IN_BSWAP16:
5984     case BUILT_IN_BSWAP32:
5985     case BUILT_IN_BSWAP64:
5986       target = expand_builtin_bswap (target_mode, exp, target, subtarget);
5987       if (target)
5988         return target;
5989       break;
5990
5991     CASE_INT_FN (BUILT_IN_FFS):
5992       target = expand_builtin_unop (target_mode, exp, target,
5993                                     subtarget, ffs_optab);
5994       if (target)
5995         return target;
5996       break;
5997
5998     CASE_INT_FN (BUILT_IN_CLZ):
5999       target = expand_builtin_unop (target_mode, exp, target,
6000                                     subtarget, clz_optab);
6001       if (target)
6002         return target;
6003       break;
6004
6005     CASE_INT_FN (BUILT_IN_CTZ):
6006       target = expand_builtin_unop (target_mode, exp, target,
6007                                     subtarget, ctz_optab);
6008       if (target)
6009         return target;
6010       break;
6011
6012     CASE_INT_FN (BUILT_IN_CLRSB):
6013       target = expand_builtin_unop (target_mode, exp, target,
6014                                     subtarget, clrsb_optab);
6015       if (target)
6016         return target;
6017       break;
6018
6019     CASE_INT_FN (BUILT_IN_POPCOUNT):
6020       target = expand_builtin_unop (target_mode, exp, target,
6021                                     subtarget, popcount_optab);
6022       if (target)
6023         return target;
6024       break;
6025
6026     CASE_INT_FN (BUILT_IN_PARITY):
6027       target = expand_builtin_unop (target_mode, exp, target,
6028                                     subtarget, parity_optab);
6029       if (target)
6030         return target;
6031       break;
6032
6033     case BUILT_IN_STRLEN:
6034       target = expand_builtin_strlen (exp, target, target_mode);
6035       if (target)
6036         return target;
6037       break;
6038
6039     case BUILT_IN_STRCPY:
6040       target = expand_builtin_strcpy (exp, target);
6041       if (target)
6042         return target;
6043       break;
6044
6045     case BUILT_IN_STRNCPY:
6046       target = expand_builtin_strncpy (exp, target);
6047       if (target)
6048         return target;
6049       break;
6050
6051     case BUILT_IN_STPCPY:
6052       target = expand_builtin_stpcpy (exp, target, mode);
6053       if (target)
6054         return target;
6055       break;
6056
6057     case BUILT_IN_MEMCPY:
6058       target = expand_builtin_memcpy (exp, target);
6059       if (target)
6060         return target;
6061       break;
6062
6063     case BUILT_IN_MEMPCPY:
6064       target = expand_builtin_mempcpy (exp, target, mode);
6065       if (target)
6066         return target;
6067       break;
6068
6069     case BUILT_IN_MEMSET:
6070       target = expand_builtin_memset (exp, target, mode);
6071       if (target)
6072         return target;
6073       break;
6074
6075     case BUILT_IN_BZERO:
6076       target = expand_builtin_bzero (exp);
6077       if (target)
6078         return target;
6079       break;
6080
6081     case BUILT_IN_STRCMP:
6082       target = expand_builtin_strcmp (exp, target);
6083       if (target)
6084         return target;
6085       break;
6086
6087     case BUILT_IN_STRNCMP:
6088       target = expand_builtin_strncmp (exp, target, mode);
6089       if (target)
6090         return target;
6091       break;
6092
6093     case BUILT_IN_BCMP:
6094     case BUILT_IN_MEMCMP:
6095       target = expand_builtin_memcmp (exp, target, mode);
6096       if (target)
6097         return target;
6098       break;
6099
6100     case BUILT_IN_SETJMP:
6101       /* This should have been lowered to the builtins below.  */
6102       gcc_unreachable ();
6103
6104     case BUILT_IN_SETJMP_SETUP:
6105       /* __builtin_setjmp_setup is passed a pointer to an array of five words
6106           and the receiver label.  */
6107       if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
6108         {
6109           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
6110                                       VOIDmode, EXPAND_NORMAL);
6111           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 1), 0);
6112           rtx label_r = label_rtx (label);
6113
6114           /* This is copied from the handling of non-local gotos.  */
6115           expand_builtin_setjmp_setup (buf_addr, label_r);
6116           nonlocal_goto_handler_labels
6117             = gen_rtx_EXPR_LIST (VOIDmode, label_r,
6118                                  nonlocal_goto_handler_labels);
6119           /* ??? Do not let expand_label treat us as such since we would
6120              not want to be both on the list of non-local labels and on
6121              the list of forced labels.  */
6122           FORCED_LABEL (label) = 0;
6123           return const0_rtx;
6124         }
6125       break;
6126
6127     case BUILT_IN_SETJMP_DISPATCHER:
6128        /* __builtin_setjmp_dispatcher is passed the dispatcher label.  */
6129       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6130         {
6131           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
6132           rtx label_r = label_rtx (label);
6133
6134           /* Remove the dispatcher label from the list of non-local labels
6135              since the receiver labels have been added to it above.  */
6136           remove_node_from_expr_list (label_r, &nonlocal_goto_handler_labels);
6137           return const0_rtx;
6138         }
6139       break;
6140
6141     case BUILT_IN_SETJMP_RECEIVER:
6142        /* __builtin_setjmp_receiver is passed the receiver label.  */
6143       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6144         {
6145           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
6146           rtx label_r = label_rtx (label);
6147
6148           expand_builtin_setjmp_receiver (label_r);
6149           return const0_rtx;
6150         }
6151       break;
6152
6153       /* __builtin_longjmp is passed a pointer to an array of five words.
6154          It's similar to the C library longjmp function but works with
6155          __builtin_setjmp above.  */
6156     case BUILT_IN_LONGJMP:
6157       if (validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
6158         {
6159           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
6160                                       VOIDmode, EXPAND_NORMAL);
6161           rtx value = expand_normal (CALL_EXPR_ARG (exp, 1));
6162
6163           if (value != const1_rtx)
6164             {
6165               error ("%<__builtin_longjmp%> second argument must be 1");
6166               return const0_rtx;
6167             }
6168
6169           expand_builtin_longjmp (buf_addr, value);
6170           return const0_rtx;
6171         }
6172       break;
6173
6174     case BUILT_IN_NONLOCAL_GOTO:
6175       target = expand_builtin_nonlocal_goto (exp);
6176       if (target)
6177         return target;
6178       break;
6179
6180       /* This updates the setjmp buffer that is its argument with the value
6181          of the current stack pointer.  */
6182     case BUILT_IN_UPDATE_SETJMP_BUF:
6183       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6184         {
6185           rtx buf_addr
6186             = expand_normal (CALL_EXPR_ARG (exp, 0));
6187
6188           expand_builtin_update_setjmp_buf (buf_addr);
6189           return const0_rtx;
6190         }
6191       break;
6192
6193     case BUILT_IN_TRAP:
6194       expand_builtin_trap ();
6195       return const0_rtx;
6196
6197     case BUILT_IN_UNREACHABLE:
6198       expand_builtin_unreachable ();
6199       return const0_rtx;
6200
6201     CASE_FLT_FN (BUILT_IN_SIGNBIT):
6202     case BUILT_IN_SIGNBITD32:
6203     case BUILT_IN_SIGNBITD64:
6204     case BUILT_IN_SIGNBITD128:
6205       target = expand_builtin_signbit (exp, target);
6206       if (target)
6207         return target;
6208       break;
6209
6210       /* Various hooks for the DWARF 2 __throw routine.  */
6211     case BUILT_IN_UNWIND_INIT:
6212       expand_builtin_unwind_init ();
6213       return const0_rtx;
6214     case BUILT_IN_DWARF_CFA:
6215       return virtual_cfa_rtx;
6216 #ifdef DWARF2_UNWIND_INFO
6217     case BUILT_IN_DWARF_SP_COLUMN:
6218       return expand_builtin_dwarf_sp_column ();
6219     case BUILT_IN_INIT_DWARF_REG_SIZES:
6220       expand_builtin_init_dwarf_reg_sizes (CALL_EXPR_ARG (exp, 0));
6221       return const0_rtx;
6222 #endif
6223     case BUILT_IN_FROB_RETURN_ADDR:
6224       return expand_builtin_frob_return_addr (CALL_EXPR_ARG (exp, 0));
6225     case BUILT_IN_EXTRACT_RETURN_ADDR:
6226       return expand_builtin_extract_return_addr (CALL_EXPR_ARG (exp, 0));
6227     case BUILT_IN_EH_RETURN:
6228       expand_builtin_eh_return (CALL_EXPR_ARG (exp, 0),
6229                                 CALL_EXPR_ARG (exp, 1));
6230       return const0_rtx;
6231 #ifdef EH_RETURN_DATA_REGNO
6232     case BUILT_IN_EH_RETURN_DATA_REGNO:
6233       return expand_builtin_eh_return_data_regno (exp);
6234 #endif
6235     case BUILT_IN_EXTEND_POINTER:
6236       return expand_builtin_extend_pointer (CALL_EXPR_ARG (exp, 0));
6237     case BUILT_IN_EH_POINTER:
6238       return expand_builtin_eh_pointer (exp);
6239     case BUILT_IN_EH_FILTER:
6240       return expand_builtin_eh_filter (exp);
6241     case BUILT_IN_EH_COPY_VALUES:
6242       return expand_builtin_eh_copy_values (exp);
6243
6244     case BUILT_IN_VA_START:
6245       return expand_builtin_va_start (exp);
6246     case BUILT_IN_VA_END:
6247       return expand_builtin_va_end (exp);
6248     case BUILT_IN_VA_COPY:
6249       return expand_builtin_va_copy (exp);
6250     case BUILT_IN_EXPECT:
6251       return expand_builtin_expect (exp, target);
6252     case BUILT_IN_ASSUME_ALIGNED:
6253       return expand_builtin_assume_aligned (exp, target);
6254     case BUILT_IN_PREFETCH:
6255       expand_builtin_prefetch (exp);
6256       return const0_rtx;
6257
6258     case BUILT_IN_INIT_TRAMPOLINE:
6259       return expand_builtin_init_trampoline (exp, true);
6260     case BUILT_IN_INIT_HEAP_TRAMPOLINE:
6261       return expand_builtin_init_trampoline (exp, false);
6262     case BUILT_IN_ADJUST_TRAMPOLINE:
6263       return expand_builtin_adjust_trampoline (exp);
6264
6265     case BUILT_IN_FORK:
6266     case BUILT_IN_EXECL:
6267     case BUILT_IN_EXECV:
6268     case BUILT_IN_EXECLP:
6269     case BUILT_IN_EXECLE:
6270     case BUILT_IN_EXECVP:
6271     case BUILT_IN_EXECVE:
6272       target = expand_builtin_fork_or_exec (fndecl, exp, target, ignore);
6273       if (target)
6274         return target;
6275       break;
6276
6277     case BUILT_IN_SYNC_FETCH_AND_ADD_1:
6278     case BUILT_IN_SYNC_FETCH_AND_ADD_2:
6279     case BUILT_IN_SYNC_FETCH_AND_ADD_4:
6280     case BUILT_IN_SYNC_FETCH_AND_ADD_8:
6281     case BUILT_IN_SYNC_FETCH_AND_ADD_16:
6282       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_ADD_1);
6283       target = expand_builtin_sync_operation (mode, exp, PLUS, false, target);
6284       if (target)
6285         return target;
6286       break;
6287
6288     case BUILT_IN_SYNC_FETCH_AND_SUB_1:
6289     case BUILT_IN_SYNC_FETCH_AND_SUB_2:
6290     case BUILT_IN_SYNC_FETCH_AND_SUB_4:
6291     case BUILT_IN_SYNC_FETCH_AND_SUB_8:
6292     case BUILT_IN_SYNC_FETCH_AND_SUB_16:
6293       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_SUB_1);
6294       target = expand_builtin_sync_operation (mode, exp, MINUS, false, target);
6295       if (target)
6296         return target;
6297       break;
6298
6299     case BUILT_IN_SYNC_FETCH_AND_OR_1:
6300     case BUILT_IN_SYNC_FETCH_AND_OR_2:
6301     case BUILT_IN_SYNC_FETCH_AND_OR_4:
6302     case BUILT_IN_SYNC_FETCH_AND_OR_8:
6303     case BUILT_IN_SYNC_FETCH_AND_OR_16:
6304       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_OR_1);
6305       target = expand_builtin_sync_operation (mode, exp, IOR, false, target);
6306       if (target)
6307         return target;
6308       break;
6309
6310     case BUILT_IN_SYNC_FETCH_AND_AND_1:
6311     case BUILT_IN_SYNC_FETCH_AND_AND_2:
6312     case BUILT_IN_SYNC_FETCH_AND_AND_4:
6313     case BUILT_IN_SYNC_FETCH_AND_AND_8:
6314     case BUILT_IN_SYNC_FETCH_AND_AND_16:
6315       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_AND_1);
6316       target = expand_builtin_sync_operation (mode, exp, AND, false, target);
6317       if (target)
6318         return target;
6319       break;
6320
6321     case BUILT_IN_SYNC_FETCH_AND_XOR_1:
6322     case BUILT_IN_SYNC_FETCH_AND_XOR_2:
6323     case BUILT_IN_SYNC_FETCH_AND_XOR_4:
6324     case BUILT_IN_SYNC_FETCH_AND_XOR_8:
6325     case BUILT_IN_SYNC_FETCH_AND_XOR_16:
6326       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_XOR_1);
6327       target = expand_builtin_sync_operation (mode, exp, XOR, false, target);
6328       if (target)
6329         return target;
6330       break;
6331
6332     case BUILT_IN_SYNC_FETCH_AND_NAND_1:
6333     case BUILT_IN_SYNC_FETCH_AND_NAND_2:
6334     case BUILT_IN_SYNC_FETCH_AND_NAND_4:
6335     case BUILT_IN_SYNC_FETCH_AND_NAND_8:
6336     case BUILT_IN_SYNC_FETCH_AND_NAND_16:
6337       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_NAND_1);
6338       target = expand_builtin_sync_operation (mode, exp, NOT, false, target);
6339       if (target)
6340         return target;
6341       break;
6342
6343     case BUILT_IN_SYNC_ADD_AND_FETCH_1:
6344     case BUILT_IN_SYNC_ADD_AND_FETCH_2:
6345     case BUILT_IN_SYNC_ADD_AND_FETCH_4:
6346     case BUILT_IN_SYNC_ADD_AND_FETCH_8:
6347     case BUILT_IN_SYNC_ADD_AND_FETCH_16:
6348       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_ADD_AND_FETCH_1);
6349       target = expand_builtin_sync_operation (mode, exp, PLUS, true, target);
6350       if (target)
6351         return target;
6352       break;
6353
6354     case BUILT_IN_SYNC_SUB_AND_FETCH_1:
6355     case BUILT_IN_SYNC_SUB_AND_FETCH_2:
6356     case BUILT_IN_SYNC_SUB_AND_FETCH_4:
6357     case BUILT_IN_SYNC_SUB_AND_FETCH_8:
6358     case BUILT_IN_SYNC_SUB_AND_FETCH_16:
6359       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_SUB_AND_FETCH_1);
6360       target = expand_builtin_sync_operation (mode, exp, MINUS, true, target);
6361       if (target)
6362         return target;
6363       break;
6364
6365     case BUILT_IN_SYNC_OR_AND_FETCH_1:
6366     case BUILT_IN_SYNC_OR_AND_FETCH_2:
6367     case BUILT_IN_SYNC_OR_AND_FETCH_4:
6368     case BUILT_IN_SYNC_OR_AND_FETCH_8:
6369     case BUILT_IN_SYNC_OR_AND_FETCH_16:
6370       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_OR_AND_FETCH_1);
6371       target = expand_builtin_sync_operation (mode, exp, IOR, true, target);
6372       if (target)
6373         return target;
6374       break;
6375
6376     case BUILT_IN_SYNC_AND_AND_FETCH_1:
6377     case BUILT_IN_SYNC_AND_AND_FETCH_2:
6378     case BUILT_IN_SYNC_AND_AND_FETCH_4:
6379     case BUILT_IN_SYNC_AND_AND_FETCH_8:
6380     case BUILT_IN_SYNC_AND_AND_FETCH_16:
6381       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_AND_AND_FETCH_1);
6382       target = expand_builtin_sync_operation (mode, exp, AND, true, target);
6383       if (target)
6384         return target;
6385       break;
6386
6387     case BUILT_IN_SYNC_XOR_AND_FETCH_1:
6388     case BUILT_IN_SYNC_XOR_AND_FETCH_2:
6389     case BUILT_IN_SYNC_XOR_AND_FETCH_4:
6390     case BUILT_IN_SYNC_XOR_AND_FETCH_8:
6391     case BUILT_IN_SYNC_XOR_AND_FETCH_16:
6392       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_XOR_AND_FETCH_1);
6393       target = expand_builtin_sync_operation (mode, exp, XOR, true, target);
6394       if (target)
6395         return target;
6396       break;
6397
6398     case BUILT_IN_SYNC_NAND_AND_FETCH_1:
6399     case BUILT_IN_SYNC_NAND_AND_FETCH_2:
6400     case BUILT_IN_SYNC_NAND_AND_FETCH_4:
6401     case BUILT_IN_SYNC_NAND_AND_FETCH_8:
6402     case BUILT_IN_SYNC_NAND_AND_FETCH_16:
6403       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_NAND_AND_FETCH_1);
6404       target = expand_builtin_sync_operation (mode, exp, NOT, true, target);
6405       if (target)
6406         return target;
6407       break;
6408
6409     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1:
6410     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_2:
6411     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_4:
6412     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_8:
6413     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_16:
6414       if (mode == VOIDmode)
6415         mode = TYPE_MODE (boolean_type_node);
6416       if (!target || !register_operand (target, mode))
6417         target = gen_reg_rtx (mode);
6418
6419       mode = get_builtin_sync_mode 
6420                                 (fcode - BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1);
6421       target = expand_builtin_compare_and_swap (mode, exp, true, target);
6422       if (target)
6423         return target;
6424       break;
6425
6426     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_1:
6427     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_2:
6428     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_4:
6429     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_8:
6430     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_16:
6431       mode = get_builtin_sync_mode 
6432                                 (fcode - BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_1);
6433       target = expand_builtin_compare_and_swap (mode, exp, false, target);
6434       if (target)
6435         return target;
6436       break;
6437
6438     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_1:
6439     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_2:
6440     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_4:
6441     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_8:
6442     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_16:
6443       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_LOCK_TEST_AND_SET_1);
6444       target = expand_builtin_sync_lock_test_and_set (mode, exp, target);
6445       if (target)
6446         return target;
6447       break;
6448
6449     case BUILT_IN_SYNC_LOCK_RELEASE_1:
6450     case BUILT_IN_SYNC_LOCK_RELEASE_2:
6451     case BUILT_IN_SYNC_LOCK_RELEASE_4:
6452     case BUILT_IN_SYNC_LOCK_RELEASE_8:
6453     case BUILT_IN_SYNC_LOCK_RELEASE_16:
6454       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_LOCK_RELEASE_1);
6455       expand_builtin_sync_lock_release (mode, exp);
6456       return const0_rtx;
6457
6458     case BUILT_IN_SYNC_SYNCHRONIZE:
6459       expand_builtin_sync_synchronize ();
6460       return const0_rtx;
6461
6462     case BUILT_IN_ATOMIC_EXCHANGE_1:
6463     case BUILT_IN_ATOMIC_EXCHANGE_2:
6464     case BUILT_IN_ATOMIC_EXCHANGE_4:
6465     case BUILT_IN_ATOMIC_EXCHANGE_8:
6466     case BUILT_IN_ATOMIC_EXCHANGE_16:
6467       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_EXCHANGE_1);
6468       target = expand_builtin_atomic_exchange (mode, exp, target);
6469       if (target)
6470         return target;
6471       break;
6472
6473     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1:
6474     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2:
6475     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4:
6476     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8:
6477     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16:
6478       {
6479         unsigned int nargs, z;
6480         vec<tree, va_gc> *vec;
6481
6482         mode = 
6483             get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1);
6484         target = expand_builtin_atomic_compare_exchange (mode, exp, target);
6485         if (target)
6486           return target;
6487
6488         /* If this is turned into an external library call, the weak parameter
6489            must be dropped to match the expected parameter list.  */
6490         nargs = call_expr_nargs (exp);
6491         vec_alloc (vec, nargs - 1);
6492         for (z = 0; z < 3; z++)
6493           vec->quick_push (CALL_EXPR_ARG (exp, z));
6494         /* Skip the boolean weak parameter.  */
6495         for (z = 4; z < 6; z++)
6496           vec->quick_push (CALL_EXPR_ARG (exp, z));
6497         exp = build_call_vec (TREE_TYPE (exp), CALL_EXPR_FN (exp), vec);
6498         break;
6499       }
6500
6501     case BUILT_IN_ATOMIC_LOAD_1:
6502     case BUILT_IN_ATOMIC_LOAD_2:
6503     case BUILT_IN_ATOMIC_LOAD_4:
6504     case BUILT_IN_ATOMIC_LOAD_8:
6505     case BUILT_IN_ATOMIC_LOAD_16:
6506       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_LOAD_1);
6507       target = expand_builtin_atomic_load (mode, exp, target);
6508       if (target)
6509         return target;
6510       break;
6511
6512     case BUILT_IN_ATOMIC_STORE_1:
6513     case BUILT_IN_ATOMIC_STORE_2:
6514     case BUILT_IN_ATOMIC_STORE_4:
6515     case BUILT_IN_ATOMIC_STORE_8:
6516     case BUILT_IN_ATOMIC_STORE_16:
6517       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_STORE_1);
6518       target = expand_builtin_atomic_store (mode, exp);
6519       if (target)
6520         return const0_rtx;
6521       break;
6522
6523     case BUILT_IN_ATOMIC_ADD_FETCH_1:
6524     case BUILT_IN_ATOMIC_ADD_FETCH_2:
6525     case BUILT_IN_ATOMIC_ADD_FETCH_4:
6526     case BUILT_IN_ATOMIC_ADD_FETCH_8:
6527     case BUILT_IN_ATOMIC_ADD_FETCH_16:
6528       {
6529         enum built_in_function lib;
6530         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_ADD_FETCH_1);
6531         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_ADD_1 + 
6532                                        (fcode - BUILT_IN_ATOMIC_ADD_FETCH_1));
6533         target = expand_builtin_atomic_fetch_op (mode, exp, target, PLUS, true,
6534                                                  ignore, lib);
6535         if (target)
6536           return target;
6537         break;
6538       }
6539     case BUILT_IN_ATOMIC_SUB_FETCH_1:
6540     case BUILT_IN_ATOMIC_SUB_FETCH_2:
6541     case BUILT_IN_ATOMIC_SUB_FETCH_4:
6542     case BUILT_IN_ATOMIC_SUB_FETCH_8:
6543     case BUILT_IN_ATOMIC_SUB_FETCH_16:
6544       {
6545         enum built_in_function lib;
6546         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_SUB_FETCH_1);
6547         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_SUB_1 + 
6548                                        (fcode - BUILT_IN_ATOMIC_SUB_FETCH_1));
6549         target = expand_builtin_atomic_fetch_op (mode, exp, target, MINUS, true,
6550                                                  ignore, lib);
6551         if (target)
6552           return target;
6553         break;
6554       }
6555     case BUILT_IN_ATOMIC_AND_FETCH_1:
6556     case BUILT_IN_ATOMIC_AND_FETCH_2:
6557     case BUILT_IN_ATOMIC_AND_FETCH_4:
6558     case BUILT_IN_ATOMIC_AND_FETCH_8:
6559     case BUILT_IN_ATOMIC_AND_FETCH_16:
6560       {
6561         enum built_in_function lib;
6562         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_AND_FETCH_1);
6563         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_AND_1 + 
6564                                        (fcode - BUILT_IN_ATOMIC_AND_FETCH_1));
6565         target = expand_builtin_atomic_fetch_op (mode, exp, target, AND, true,
6566                                                  ignore, lib);
6567         if (target)
6568           return target;
6569         break;
6570       }
6571     case BUILT_IN_ATOMIC_NAND_FETCH_1:
6572     case BUILT_IN_ATOMIC_NAND_FETCH_2:
6573     case BUILT_IN_ATOMIC_NAND_FETCH_4:
6574     case BUILT_IN_ATOMIC_NAND_FETCH_8:
6575     case BUILT_IN_ATOMIC_NAND_FETCH_16:
6576       {
6577         enum built_in_function lib;
6578         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_NAND_FETCH_1);
6579         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_NAND_1 + 
6580                                        (fcode - BUILT_IN_ATOMIC_NAND_FETCH_1));
6581         target = expand_builtin_atomic_fetch_op (mode, exp, target, NOT, true,
6582                                                  ignore, lib);
6583         if (target)
6584           return target;
6585         break;
6586       }
6587     case BUILT_IN_ATOMIC_XOR_FETCH_1:
6588     case BUILT_IN_ATOMIC_XOR_FETCH_2:
6589     case BUILT_IN_ATOMIC_XOR_FETCH_4:
6590     case BUILT_IN_ATOMIC_XOR_FETCH_8:
6591     case BUILT_IN_ATOMIC_XOR_FETCH_16:
6592       {
6593         enum built_in_function lib;
6594         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_XOR_FETCH_1);
6595         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_XOR_1 + 
6596                                        (fcode - BUILT_IN_ATOMIC_XOR_FETCH_1));
6597         target = expand_builtin_atomic_fetch_op (mode, exp, target, XOR, true,
6598                                                  ignore, lib);
6599         if (target)
6600           return target;
6601         break;
6602       }
6603     case BUILT_IN_ATOMIC_OR_FETCH_1:
6604     case BUILT_IN_ATOMIC_OR_FETCH_2:
6605     case BUILT_IN_ATOMIC_OR_FETCH_4:
6606     case BUILT_IN_ATOMIC_OR_FETCH_8:
6607     case BUILT_IN_ATOMIC_OR_FETCH_16:
6608       {
6609         enum built_in_function lib;
6610         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_OR_FETCH_1);
6611         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_OR_1 + 
6612                                        (fcode - BUILT_IN_ATOMIC_OR_FETCH_1));
6613         target = expand_builtin_atomic_fetch_op (mode, exp, target, IOR, true,
6614                                                  ignore, lib);
6615         if (target)
6616           return target;
6617         break;
6618       }
6619     case BUILT_IN_ATOMIC_FETCH_ADD_1:
6620     case BUILT_IN_ATOMIC_FETCH_ADD_2:
6621     case BUILT_IN_ATOMIC_FETCH_ADD_4:
6622     case BUILT_IN_ATOMIC_FETCH_ADD_8:
6623     case BUILT_IN_ATOMIC_FETCH_ADD_16:
6624       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_ADD_1);
6625       target = expand_builtin_atomic_fetch_op (mode, exp, target, PLUS, false,
6626                                                ignore, BUILT_IN_NONE);
6627       if (target)
6628         return target;
6629       break;
6630  
6631     case BUILT_IN_ATOMIC_FETCH_SUB_1:
6632     case BUILT_IN_ATOMIC_FETCH_SUB_2:
6633     case BUILT_IN_ATOMIC_FETCH_SUB_4:
6634     case BUILT_IN_ATOMIC_FETCH_SUB_8:
6635     case BUILT_IN_ATOMIC_FETCH_SUB_16:
6636       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_SUB_1);
6637       target = expand_builtin_atomic_fetch_op (mode, exp, target, MINUS, false,
6638                                                ignore, BUILT_IN_NONE);
6639       if (target)
6640         return target;
6641       break;
6642
6643     case BUILT_IN_ATOMIC_FETCH_AND_1:
6644     case BUILT_IN_ATOMIC_FETCH_AND_2:
6645     case BUILT_IN_ATOMIC_FETCH_AND_4:
6646     case BUILT_IN_ATOMIC_FETCH_AND_8:
6647     case BUILT_IN_ATOMIC_FETCH_AND_16:
6648       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_AND_1);
6649       target = expand_builtin_atomic_fetch_op (mode, exp, target, AND, false,
6650                                                ignore, BUILT_IN_NONE);
6651       if (target)
6652         return target;
6653       break;
6654   
6655     case BUILT_IN_ATOMIC_FETCH_NAND_1:
6656     case BUILT_IN_ATOMIC_FETCH_NAND_2:
6657     case BUILT_IN_ATOMIC_FETCH_NAND_4:
6658     case BUILT_IN_ATOMIC_FETCH_NAND_8:
6659     case BUILT_IN_ATOMIC_FETCH_NAND_16:
6660       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_NAND_1);
6661       target = expand_builtin_atomic_fetch_op (mode, exp, target, NOT, false,
6662                                                ignore, BUILT_IN_NONE);
6663       if (target)
6664         return target;
6665       break;
6666  
6667     case BUILT_IN_ATOMIC_FETCH_XOR_1:
6668     case BUILT_IN_ATOMIC_FETCH_XOR_2:
6669     case BUILT_IN_ATOMIC_FETCH_XOR_4:
6670     case BUILT_IN_ATOMIC_FETCH_XOR_8:
6671     case BUILT_IN_ATOMIC_FETCH_XOR_16:
6672       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_XOR_1);
6673       target = expand_builtin_atomic_fetch_op (mode, exp, target, XOR, false,
6674                                                ignore, BUILT_IN_NONE);
6675       if (target)
6676         return target;
6677       break;
6678  
6679     case BUILT_IN_ATOMIC_FETCH_OR_1:
6680     case BUILT_IN_ATOMIC_FETCH_OR_2:
6681     case BUILT_IN_ATOMIC_FETCH_OR_4:
6682     case BUILT_IN_ATOMIC_FETCH_OR_8:
6683     case BUILT_IN_ATOMIC_FETCH_OR_16:
6684       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_OR_1);
6685       target = expand_builtin_atomic_fetch_op (mode, exp, target, IOR, false,
6686                                                ignore, BUILT_IN_NONE);
6687       if (target)
6688         return target;
6689       break;
6690
6691     case BUILT_IN_ATOMIC_TEST_AND_SET:
6692       return expand_builtin_atomic_test_and_set (exp, target);
6693
6694     case BUILT_IN_ATOMIC_CLEAR:
6695       return expand_builtin_atomic_clear (exp);
6696  
6697     case BUILT_IN_ATOMIC_ALWAYS_LOCK_FREE:
6698       return expand_builtin_atomic_always_lock_free (exp);
6699
6700     case BUILT_IN_ATOMIC_IS_LOCK_FREE:
6701       target = expand_builtin_atomic_is_lock_free (exp);
6702       if (target)
6703         return target;
6704       break;
6705
6706     case BUILT_IN_ATOMIC_THREAD_FENCE:
6707       expand_builtin_atomic_thread_fence (exp);
6708       return const0_rtx;
6709
6710     case BUILT_IN_ATOMIC_SIGNAL_FENCE:
6711       expand_builtin_atomic_signal_fence (exp);
6712       return const0_rtx;
6713
6714     case BUILT_IN_OBJECT_SIZE:
6715       return expand_builtin_object_size (exp);
6716
6717     case BUILT_IN_MEMCPY_CHK:
6718     case BUILT_IN_MEMPCPY_CHK:
6719     case BUILT_IN_MEMMOVE_CHK:
6720     case BUILT_IN_MEMSET_CHK:
6721       target = expand_builtin_memory_chk (exp, target, mode, fcode);
6722       if (target)
6723         return target;
6724       break;
6725
6726     case BUILT_IN_STRCPY_CHK:
6727     case BUILT_IN_STPCPY_CHK:
6728     case BUILT_IN_STRNCPY_CHK:
6729     case BUILT_IN_STPNCPY_CHK:
6730     case BUILT_IN_STRCAT_CHK:
6731     case BUILT_IN_STRNCAT_CHK:
6732     case BUILT_IN_SNPRINTF_CHK:
6733     case BUILT_IN_VSNPRINTF_CHK:
6734       maybe_emit_chk_warning (exp, fcode);
6735       break;
6736
6737     case BUILT_IN_SPRINTF_CHK:
6738     case BUILT_IN_VSPRINTF_CHK:
6739       maybe_emit_sprintf_chk_warning (exp, fcode);
6740       break;
6741
6742     case BUILT_IN_FREE:
6743       if (warn_free_nonheap_object)
6744         maybe_emit_free_warning (exp);
6745       break;
6746
6747     case BUILT_IN_THREAD_POINTER:
6748       return expand_builtin_thread_pointer (exp, target);
6749
6750     case BUILT_IN_SET_THREAD_POINTER:
6751       expand_builtin_set_thread_pointer (exp);
6752       return const0_rtx;
6753
6754     case BUILT_IN_CILK_DETACH:
6755       expand_builtin_cilk_detach (exp);
6756       return const0_rtx;
6757       
6758     case BUILT_IN_CILK_POP_FRAME:
6759       expand_builtin_cilk_pop_frame (exp);
6760       return const0_rtx;
6761
6762     case BUILT_IN_CHKP_INIT_PTR_BOUNDS:
6763     case BUILT_IN_CHKP_NULL_PTR_BOUNDS:
6764     case BUILT_IN_CHKP_COPY_PTR_BOUNDS:
6765       return expand_normal (CALL_EXPR_ARG (exp, 0));
6766
6767     case BUILT_IN_CHKP_CHECK_PTR_LBOUNDS:
6768     case BUILT_IN_CHKP_CHECK_PTR_UBOUNDS:
6769     case BUILT_IN_CHKP_CHECK_PTR_BOUNDS:
6770     case BUILT_IN_CHKP_SET_PTR_BOUNDS:
6771     case BUILT_IN_CHKP_NARROW_PTR_BOUNDS:
6772     case BUILT_IN_CHKP_STORE_PTR_BOUNDS:
6773     case BUILT_IN_CHKP_GET_PTR_LBOUND:
6774     case BUILT_IN_CHKP_GET_PTR_UBOUND:
6775       /* We allow user CHKP builtins if Pointer Bounds
6776          Checker is off.  */
6777       if (!flag_check_pointer_bounds)
6778         {
6779           if (fcode == BUILT_IN_CHKP_SET_PTR_BOUNDS
6780               || fcode == BUILT_IN_CHKP_NARROW_PTR_BOUNDS)
6781             return expand_normal (CALL_EXPR_ARG (exp, 0));
6782           else if (fcode == BUILT_IN_CHKP_GET_PTR_LBOUND)
6783             return expand_normal (size_zero_node);
6784           else if (fcode == BUILT_IN_CHKP_GET_PTR_UBOUND)
6785             return expand_normal (size_int (-1));
6786           else
6787             return const0_rtx;
6788         }
6789       /* FALLTHROUGH */
6790
6791     case BUILT_IN_CHKP_BNDMK:
6792     case BUILT_IN_CHKP_BNDSTX:
6793     case BUILT_IN_CHKP_BNDCL:
6794     case BUILT_IN_CHKP_BNDCU:
6795     case BUILT_IN_CHKP_BNDLDX:
6796     case BUILT_IN_CHKP_BNDRET:
6797     case BUILT_IN_CHKP_INTERSECT:
6798     case BUILT_IN_CHKP_ARG_BND:
6799     case BUILT_IN_CHKP_NARROW:
6800     case BUILT_IN_CHKP_EXTRACT_LOWER:
6801     case BUILT_IN_CHKP_EXTRACT_UPPER:
6802       /* Software implementation of pointers checker is NYI.
6803          Target support is required.  */
6804       error ("Your target platform does not support -fcheck-pointers");
6805       break;
6806
6807     default:    /* just do library call, if unknown builtin */
6808       break;
6809     }
6810
6811   /* The switch statement above can drop through to cause the function
6812      to be called normally.  */
6813   return expand_call (exp, target, ignore);
6814 }
6815
6816 /* Determine whether a tree node represents a call to a built-in
6817    function.  If the tree T is a call to a built-in function with
6818    the right number of arguments of the appropriate types, return
6819    the DECL_FUNCTION_CODE of the call, e.g. BUILT_IN_SQRT.
6820    Otherwise the return value is END_BUILTINS.  */
6821
6822 enum built_in_function
6823 builtin_mathfn_code (const_tree t)
6824 {
6825   const_tree fndecl, arg, parmlist;
6826   const_tree argtype, parmtype;
6827   const_call_expr_arg_iterator iter;
6828
6829   if (TREE_CODE (t) != CALL_EXPR
6830       || TREE_CODE (CALL_EXPR_FN (t)) != ADDR_EXPR)
6831     return END_BUILTINS;
6832
6833   fndecl = get_callee_fndecl (t);
6834   if (fndecl == NULL_TREE
6835       || TREE_CODE (fndecl) != FUNCTION_DECL
6836       || ! DECL_BUILT_IN (fndecl)
6837       || DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
6838     return END_BUILTINS;
6839
6840   parmlist = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
6841   init_const_call_expr_arg_iterator (t, &iter);
6842   for (; parmlist; parmlist = TREE_CHAIN (parmlist))
6843     {
6844       /* If a function doesn't take a variable number of arguments,
6845          the last element in the list will have type `void'.  */
6846       parmtype = TREE_VALUE (parmlist);
6847       if (VOID_TYPE_P (parmtype))
6848         {
6849           if (more_const_call_expr_args_p (&iter))
6850             return END_BUILTINS;
6851           return DECL_FUNCTION_CODE (fndecl);
6852         }
6853
6854       if (! more_const_call_expr_args_p (&iter))
6855         return END_BUILTINS;
6856
6857       arg = next_const_call_expr_arg (&iter);
6858       argtype = TREE_TYPE (arg);
6859
6860       if (SCALAR_FLOAT_TYPE_P (parmtype))
6861         {
6862           if (! SCALAR_FLOAT_TYPE_P (argtype))
6863             return END_BUILTINS;
6864         }
6865       else if (COMPLEX_FLOAT_TYPE_P (parmtype))
6866         {
6867           if (! COMPLEX_FLOAT_TYPE_P (argtype))
6868             return END_BUILTINS;
6869         }
6870       else if (POINTER_TYPE_P (parmtype))
6871         {
6872           if (! POINTER_TYPE_P (argtype))
6873             return END_BUILTINS;
6874         }
6875       else if (INTEGRAL_TYPE_P (parmtype))
6876         {
6877           if (! INTEGRAL_TYPE_P (argtype))
6878             return END_BUILTINS;
6879         }
6880       else
6881         return END_BUILTINS;
6882     }
6883
6884   /* Variable-length argument list.  */
6885   return DECL_FUNCTION_CODE (fndecl);
6886 }
6887
6888 /* Fold a call to __builtin_constant_p, if we know its argument ARG will
6889    evaluate to a constant.  */
6890
6891 static tree
6892 fold_builtin_constant_p (tree arg)
6893 {
6894   /* We return 1 for a numeric type that's known to be a constant
6895      value at compile-time or for an aggregate type that's a
6896      literal constant.  */
6897   STRIP_NOPS (arg);
6898
6899   /* If we know this is a constant, emit the constant of one.  */
6900   if (CONSTANT_CLASS_P (arg)
6901       || (TREE_CODE (arg) == CONSTRUCTOR
6902           && TREE_CONSTANT (arg)))
6903     return integer_one_node;
6904   if (TREE_CODE (arg) == ADDR_EXPR)
6905     {
6906        tree op = TREE_OPERAND (arg, 0);
6907        if (TREE_CODE (op) == STRING_CST
6908            || (TREE_CODE (op) == ARRAY_REF
6909                && integer_zerop (TREE_OPERAND (op, 1))
6910                && TREE_CODE (TREE_OPERAND (op, 0)) == STRING_CST))
6911          return integer_one_node;
6912     }
6913
6914   /* If this expression has side effects, show we don't know it to be a
6915      constant.  Likewise if it's a pointer or aggregate type since in
6916      those case we only want literals, since those are only optimized
6917      when generating RTL, not later.
6918      And finally, if we are compiling an initializer, not code, we
6919      need to return a definite result now; there's not going to be any
6920      more optimization done.  */
6921   if (TREE_SIDE_EFFECTS (arg)
6922       || AGGREGATE_TYPE_P (TREE_TYPE (arg))
6923       || POINTER_TYPE_P (TREE_TYPE (arg))
6924       || cfun == 0
6925       || folding_initializer
6926       || force_folding_builtin_constant_p)
6927     return integer_zero_node;
6928
6929   return NULL_TREE;
6930 }
6931
6932 /* Create builtin_expect with PRED and EXPECTED as its arguments and
6933    return it as a truthvalue.  */
6934
6935 static tree
6936 build_builtin_expect_predicate (location_t loc, tree pred, tree expected)
6937 {
6938   tree fn, arg_types, pred_type, expected_type, call_expr, ret_type;
6939
6940   fn = builtin_decl_explicit (BUILT_IN_EXPECT);
6941   arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
6942   ret_type = TREE_TYPE (TREE_TYPE (fn));
6943   pred_type = TREE_VALUE (arg_types);
6944   expected_type = TREE_VALUE (TREE_CHAIN (arg_types));
6945
6946   pred = fold_convert_loc (loc, pred_type, pred);
6947   expected = fold_convert_loc (loc, expected_type, expected);
6948   call_expr = build_call_expr_loc (loc, fn, 2, pred, expected);
6949
6950   return build2 (NE_EXPR, TREE_TYPE (pred), call_expr,
6951                  build_int_cst (ret_type, 0));
6952 }
6953
6954 /* Fold a call to builtin_expect with arguments ARG0 and ARG1.  Return
6955    NULL_TREE if no simplification is possible.  */
6956
6957 static tree
6958 fold_builtin_expect (location_t loc, tree arg0, tree arg1)
6959 {
6960   tree inner, fndecl, inner_arg0;
6961   enum tree_code code;
6962
6963   /* Distribute the expected value over short-circuiting operators.
6964      See through the cast from truthvalue_type_node to long.  */
6965   inner_arg0 = arg0;
6966   while (TREE_CODE (inner_arg0) == NOP_EXPR
6967          && INTEGRAL_TYPE_P (TREE_TYPE (inner_arg0))
6968          && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (inner_arg0, 0))))
6969     inner_arg0 = TREE_OPERAND (inner_arg0, 0);
6970
6971   /* If this is a builtin_expect within a builtin_expect keep the
6972      inner one.  See through a comparison against a constant.  It
6973      might have been added to create a thruthvalue.  */
6974   inner = inner_arg0;
6975
6976   if (COMPARISON_CLASS_P (inner)
6977       && TREE_CODE (TREE_OPERAND (inner, 1)) == INTEGER_CST)
6978     inner = TREE_OPERAND (inner, 0);
6979
6980   if (TREE_CODE (inner) == CALL_EXPR
6981       && (fndecl = get_callee_fndecl (inner))
6982       && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
6983       && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT)
6984     return arg0;
6985
6986   inner = inner_arg0;
6987   code = TREE_CODE (inner);
6988   if (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR)
6989     {
6990       tree op0 = TREE_OPERAND (inner, 0);
6991       tree op1 = TREE_OPERAND (inner, 1);
6992
6993       op0 = build_builtin_expect_predicate (loc, op0, arg1);
6994       op1 = build_builtin_expect_predicate (loc, op1, arg1);
6995       inner = build2 (code, TREE_TYPE (inner), op0, op1);
6996
6997       return fold_convert_loc (loc, TREE_TYPE (arg0), inner);
6998     }
6999
7000   /* If the argument isn't invariant then there's nothing else we can do.  */
7001   if (!TREE_CONSTANT (inner_arg0))
7002     return NULL_TREE;
7003
7004   /* If we expect that a comparison against the argument will fold to
7005      a constant return the constant.  In practice, this means a true
7006      constant or the address of a non-weak symbol.  */
7007   inner = inner_arg0;
7008   STRIP_NOPS (inner);
7009   if (TREE_CODE (inner) == ADDR_EXPR)
7010     {
7011       do
7012         {
7013           inner = TREE_OPERAND (inner, 0);
7014         }
7015       while (TREE_CODE (inner) == COMPONENT_REF
7016              || TREE_CODE (inner) == ARRAY_REF);
7017       if ((TREE_CODE (inner) == VAR_DECL
7018            || TREE_CODE (inner) == FUNCTION_DECL)
7019           && DECL_WEAK (inner))
7020         return NULL_TREE;
7021     }
7022
7023   /* Otherwise, ARG0 already has the proper type for the return value.  */
7024   return arg0;
7025 }
7026
7027 /* Fold a call to __builtin_classify_type with argument ARG.  */
7028
7029 static tree
7030 fold_builtin_classify_type (tree arg)
7031 {
7032   if (arg == 0)
7033     return build_int_cst (integer_type_node, no_type_class);
7034
7035   return build_int_cst (integer_type_node, type_to_class (TREE_TYPE (arg)));
7036 }
7037
7038 /* Fold a call to __builtin_strlen with argument ARG.  */
7039
7040 static tree
7041 fold_builtin_strlen (location_t loc, tree type, tree arg)
7042 {
7043   if (!validate_arg (arg, POINTER_TYPE))
7044     return NULL_TREE;
7045   else
7046     {
7047       tree len = c_strlen (arg, 0);
7048
7049       if (len)
7050         return fold_convert_loc (loc, type, len);
7051
7052       return NULL_TREE;
7053     }
7054 }
7055
7056 /* Fold a call to __builtin_inf or __builtin_huge_val.  */
7057
7058 static tree
7059 fold_builtin_inf (location_t loc, tree type, int warn)
7060 {
7061   REAL_VALUE_TYPE real;
7062
7063   /* __builtin_inff is intended to be usable to define INFINITY on all
7064      targets.  If an infinity is not available, INFINITY expands "to a
7065      positive constant of type float that overflows at translation
7066      time", footnote "In this case, using INFINITY will violate the
7067      constraint in 6.4.4 and thus require a diagnostic." (C99 7.12#4).
7068      Thus we pedwarn to ensure this constraint violation is
7069      diagnosed.  */
7070   if (!MODE_HAS_INFINITIES (TYPE_MODE (type)) && warn)
7071     pedwarn (loc, 0, "target format does not support infinity");
7072
7073   real_inf (&real);
7074   return build_real (type, real);
7075 }
7076
7077 /* Fold a call to __builtin_nan or __builtin_nans with argument ARG.  */
7078
7079 static tree
7080 fold_builtin_nan (tree arg, tree type, int quiet)
7081 {
7082   REAL_VALUE_TYPE real;
7083   const char *str;
7084
7085   if (!validate_arg (arg, POINTER_TYPE))
7086     return NULL_TREE;
7087   str = c_getstr (arg);
7088   if (!str)
7089     return NULL_TREE;
7090
7091   if (!real_nan (&real, str, quiet, TYPE_MODE (type)))
7092     return NULL_TREE;
7093
7094   return build_real (type, real);
7095 }
7096
7097 /* Return true if the floating point expression T has an integer value.
7098    We also allow +Inf, -Inf and NaN to be considered integer values.  */
7099
7100 static bool
7101 integer_valued_real_p (tree t)
7102 {
7103   switch (TREE_CODE (t))
7104     {
7105     case FLOAT_EXPR:
7106       return true;
7107
7108     case ABS_EXPR:
7109     case SAVE_EXPR:
7110       return integer_valued_real_p (TREE_OPERAND (t, 0));
7111
7112     case COMPOUND_EXPR:
7113     case MODIFY_EXPR:
7114     case BIND_EXPR:
7115       return integer_valued_real_p (TREE_OPERAND (t, 1));
7116
7117     case PLUS_EXPR:
7118     case MINUS_EXPR:
7119     case MULT_EXPR:
7120     case MIN_EXPR:
7121     case MAX_EXPR:
7122       return integer_valued_real_p (TREE_OPERAND (t, 0))
7123              && integer_valued_real_p (TREE_OPERAND (t, 1));
7124
7125     case COND_EXPR:
7126       return integer_valued_real_p (TREE_OPERAND (t, 1))
7127              && integer_valued_real_p (TREE_OPERAND (t, 2));
7128
7129     case REAL_CST:
7130       return real_isinteger (TREE_REAL_CST_PTR (t), TYPE_MODE (TREE_TYPE (t)));
7131
7132     case NOP_EXPR:
7133       {
7134         tree type = TREE_TYPE (TREE_OPERAND (t, 0));
7135         if (TREE_CODE (type) == INTEGER_TYPE)
7136           return true;
7137         if (TREE_CODE (type) == REAL_TYPE)
7138           return integer_valued_real_p (TREE_OPERAND (t, 0));
7139         break;
7140       }
7141
7142     case CALL_EXPR:
7143       switch (builtin_mathfn_code (t))
7144         {
7145         CASE_FLT_FN (BUILT_IN_CEIL):
7146         CASE_FLT_FN (BUILT_IN_FLOOR):
7147         CASE_FLT_FN (BUILT_IN_NEARBYINT):
7148         CASE_FLT_FN (BUILT_IN_RINT):
7149         CASE_FLT_FN (BUILT_IN_ROUND):
7150         CASE_FLT_FN (BUILT_IN_TRUNC):
7151           return true;
7152
7153         CASE_FLT_FN (BUILT_IN_FMIN):
7154         CASE_FLT_FN (BUILT_IN_FMAX):
7155           return integer_valued_real_p (CALL_EXPR_ARG (t, 0))
7156             && integer_valued_real_p (CALL_EXPR_ARG (t, 1));
7157
7158         default:
7159           break;
7160         }
7161       break;
7162
7163     default:
7164       break;
7165     }
7166   return false;
7167 }
7168
7169 /* FNDECL is assumed to be a builtin where truncation can be propagated
7170    across (for instance floor((double)f) == (double)floorf (f).
7171    Do the transformation for a call with argument ARG.  */
7172
7173 static tree
7174 fold_trunc_transparent_mathfn (location_t loc, tree fndecl, tree arg)
7175 {
7176   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
7177
7178   if (!validate_arg (arg, REAL_TYPE))
7179     return NULL_TREE;
7180
7181   /* Integer rounding functions are idempotent.  */
7182   if (fcode == builtin_mathfn_code (arg))
7183     return arg;
7184
7185   /* If argument is already integer valued, and we don't need to worry
7186      about setting errno, there's no need to perform rounding.  */
7187   if (! flag_errno_math && integer_valued_real_p (arg))
7188     return arg;
7189
7190   if (optimize)
7191     {
7192       tree arg0 = strip_float_extensions (arg);
7193       tree ftype = TREE_TYPE (TREE_TYPE (fndecl));
7194       tree newtype = TREE_TYPE (arg0);
7195       tree decl;
7196
7197       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
7198           && (decl = mathfn_built_in (newtype, fcode)))
7199         return fold_convert_loc (loc, ftype,
7200                                  build_call_expr_loc (loc, decl, 1,
7201                                                   fold_convert_loc (loc,
7202                                                                     newtype,
7203                                                                     arg0)));
7204     }
7205   return NULL_TREE;
7206 }
7207
7208 /* FNDECL is assumed to be builtin which can narrow the FP type of
7209    the argument, for instance lround((double)f) -> lroundf (f).
7210    Do the transformation for a call with argument ARG.  */
7211
7212 static tree
7213 fold_fixed_mathfn (location_t loc, tree fndecl, tree arg)
7214 {
7215   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
7216
7217   if (!validate_arg (arg, REAL_TYPE))
7218     return NULL_TREE;
7219
7220   /* If argument is already integer valued, and we don't need to worry
7221      about setting errno, there's no need to perform rounding.  */
7222   if (! flag_errno_math && integer_valued_real_p (arg))
7223     return fold_build1_loc (loc, FIX_TRUNC_EXPR,
7224                         TREE_TYPE (TREE_TYPE (fndecl)), arg);
7225
7226   if (optimize)
7227     {
7228       tree ftype = TREE_TYPE (arg);
7229       tree arg0 = strip_float_extensions (arg);
7230       tree newtype = TREE_TYPE (arg0);
7231       tree decl;
7232
7233       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
7234           && (decl = mathfn_built_in (newtype, fcode)))
7235         return build_call_expr_loc (loc, decl, 1,
7236                                 fold_convert_loc (loc, newtype, arg0));
7237     }
7238
7239   /* Canonicalize iround (x) to lround (x) on ILP32 targets where
7240      sizeof (int) == sizeof (long).  */
7241   if (TYPE_PRECISION (integer_type_node)
7242       == TYPE_PRECISION (long_integer_type_node))
7243     {
7244       tree newfn = NULL_TREE;
7245       switch (fcode)
7246         {
7247         CASE_FLT_FN (BUILT_IN_ICEIL):
7248           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LCEIL);
7249           break;
7250
7251         CASE_FLT_FN (BUILT_IN_IFLOOR):
7252           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LFLOOR);
7253           break;
7254
7255         CASE_FLT_FN (BUILT_IN_IROUND):
7256           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LROUND);
7257           break;
7258
7259         CASE_FLT_FN (BUILT_IN_IRINT):
7260           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LRINT);
7261           break;
7262
7263         default:
7264           break;
7265         }
7266
7267       if (newfn)
7268         {
7269           tree newcall = build_call_expr_loc (loc, newfn, 1, arg);
7270           return fold_convert_loc (loc,
7271                                    TREE_TYPE (TREE_TYPE (fndecl)), newcall);
7272         }
7273     }
7274
7275   /* Canonicalize llround (x) to lround (x) on LP64 targets where
7276      sizeof (long long) == sizeof (long).  */
7277   if (TYPE_PRECISION (long_long_integer_type_node)
7278       == TYPE_PRECISION (long_integer_type_node))
7279     {
7280       tree newfn = NULL_TREE;
7281       switch (fcode)
7282         {
7283         CASE_FLT_FN (BUILT_IN_LLCEIL):
7284           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LCEIL);
7285           break;
7286
7287         CASE_FLT_FN (BUILT_IN_LLFLOOR):
7288           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LFLOOR);
7289           break;
7290
7291         CASE_FLT_FN (BUILT_IN_LLROUND):
7292           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LROUND);
7293           break;
7294
7295         CASE_FLT_FN (BUILT_IN_LLRINT):
7296           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LRINT);
7297           break;
7298
7299         default:
7300           break;
7301         }
7302
7303       if (newfn)
7304         {
7305           tree newcall = build_call_expr_loc (loc, newfn, 1, arg);
7306           return fold_convert_loc (loc,
7307                                    TREE_TYPE (TREE_TYPE (fndecl)), newcall);
7308         }
7309     }
7310
7311   return NULL_TREE;
7312 }
7313
7314 /* Fold call to builtin cabs, cabsf or cabsl with argument ARG.  TYPE is the
7315    return type.  Return NULL_TREE if no simplification can be made.  */
7316
7317 static tree
7318 fold_builtin_cabs (location_t loc, tree arg, tree type, tree fndecl)
7319 {
7320   tree res;
7321
7322   if (!validate_arg (arg, COMPLEX_TYPE)
7323       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) != REAL_TYPE)
7324     return NULL_TREE;
7325
7326   /* Calculate the result when the argument is a constant.  */
7327   if (TREE_CODE (arg) == COMPLEX_CST
7328       && (res = do_mpfr_arg2 (TREE_REALPART (arg), TREE_IMAGPART (arg),
7329                               type, mpfr_hypot)))
7330     return res;
7331
7332   if (TREE_CODE (arg) == COMPLEX_EXPR)
7333     {
7334       tree real = TREE_OPERAND (arg, 0);
7335       tree imag = TREE_OPERAND (arg, 1);
7336
7337       /* If either part is zero, cabs is fabs of the other.  */
7338       if (real_zerop (real))
7339         return fold_build1_loc (loc, ABS_EXPR, type, imag);
7340       if (real_zerop (imag))
7341         return fold_build1_loc (loc, ABS_EXPR, type, real);
7342
7343       /* cabs(x+xi) -> fabs(x)*sqrt(2).  */
7344       if (flag_unsafe_math_optimizations
7345           && operand_equal_p (real, imag, OEP_PURE_SAME))
7346         {
7347           const REAL_VALUE_TYPE sqrt2_trunc
7348             = real_value_truncate (TYPE_MODE (type), dconst_sqrt2 ());
7349           STRIP_NOPS (real);
7350           return fold_build2_loc (loc, MULT_EXPR, type,
7351                               fold_build1_loc (loc, ABS_EXPR, type, real),
7352                               build_real (type, sqrt2_trunc));
7353         }
7354     }
7355
7356   /* Optimize cabs(-z) and cabs(conj(z)) as cabs(z).  */
7357   if (TREE_CODE (arg) == NEGATE_EXPR
7358       || TREE_CODE (arg) == CONJ_EXPR)
7359     return build_call_expr_loc (loc, fndecl, 1, TREE_OPERAND (arg, 0));
7360
7361   /* Don't do this when optimizing for size.  */
7362   if (flag_unsafe_math_optimizations
7363       && optimize && optimize_function_for_speed_p (cfun))
7364     {
7365       tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
7366
7367       if (sqrtfn != NULL_TREE)
7368         {
7369           tree rpart, ipart, result;
7370
7371           arg = builtin_save_expr (arg);
7372
7373           rpart = fold_build1_loc (loc, REALPART_EXPR, type, arg);
7374           ipart = fold_build1_loc (loc, IMAGPART_EXPR, type, arg);
7375
7376           rpart = builtin_save_expr (rpart);
7377           ipart = builtin_save_expr (ipart);
7378
7379           result = fold_build2_loc (loc, PLUS_EXPR, type,
7380                                 fold_build2_loc (loc, MULT_EXPR, type,
7381                                              rpart, rpart),
7382                                 fold_build2_loc (loc, MULT_EXPR, type,
7383                                              ipart, ipart));
7384
7385           return build_call_expr_loc (loc, sqrtfn, 1, result);
7386         }
7387     }
7388
7389   return NULL_TREE;
7390 }
7391
7392 /* Build a complex (inf +- 0i) for the result of cproj.  TYPE is the
7393    complex tree type of the result.  If NEG is true, the imaginary
7394    zero is negative.  */
7395
7396 static tree
7397 build_complex_cproj (tree type, bool neg)
7398 {
7399   REAL_VALUE_TYPE rinf, rzero = dconst0;
7400   
7401   real_inf (&rinf);
7402   rzero.sign = neg;
7403   return build_complex (type, build_real (TREE_TYPE (type), rinf),
7404                         build_real (TREE_TYPE (type), rzero));
7405 }
7406
7407 /* Fold call to builtin cproj, cprojf or cprojl with argument ARG.  TYPE is the
7408    return type.  Return NULL_TREE if no simplification can be made.  */
7409
7410 static tree
7411 fold_builtin_cproj (location_t loc, tree arg, tree type)
7412 {
7413   if (!validate_arg (arg, COMPLEX_TYPE)
7414       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) != REAL_TYPE)
7415     return NULL_TREE;
7416
7417   /* If there are no infinities, return arg.  */
7418   if (! HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (type))))
7419     return non_lvalue_loc (loc, arg);
7420
7421   /* Calculate the result when the argument is a constant.  */
7422   if (TREE_CODE (arg) == COMPLEX_CST)
7423     {
7424       const REAL_VALUE_TYPE *real = TREE_REAL_CST_PTR (TREE_REALPART (arg));
7425       const REAL_VALUE_TYPE *imag = TREE_REAL_CST_PTR (TREE_IMAGPART (arg));
7426       
7427       if (real_isinf (real) || real_isinf (imag))
7428         return build_complex_cproj (type, imag->sign);
7429       else
7430         return arg;
7431     }
7432   else if (TREE_CODE (arg) == COMPLEX_EXPR)
7433     {
7434       tree real = TREE_OPERAND (arg, 0);
7435       tree imag = TREE_OPERAND (arg, 1);
7436
7437       STRIP_NOPS (real);
7438       STRIP_NOPS (imag);
7439       
7440       /* If the real part is inf and the imag part is known to be
7441          nonnegative, return (inf + 0i).  Remember side-effects are
7442          possible in the imag part.  */
7443       if (TREE_CODE (real) == REAL_CST
7444           && real_isinf (TREE_REAL_CST_PTR (real))
7445           && tree_expr_nonnegative_p (imag))
7446         return omit_one_operand_loc (loc, type,
7447                                      build_complex_cproj (type, false),
7448                                      arg);
7449       
7450       /* If the imag part is inf, return (inf+I*copysign(0,imag)).
7451          Remember side-effects are possible in the real part.  */
7452       if (TREE_CODE (imag) == REAL_CST
7453           && real_isinf (TREE_REAL_CST_PTR (imag)))
7454         return
7455           omit_one_operand_loc (loc, type,
7456                                 build_complex_cproj (type, TREE_REAL_CST_PTR
7457                                                      (imag)->sign), arg);
7458     }
7459
7460   return NULL_TREE;
7461 }
7462
7463 /* Fold a builtin function call to sqrt, sqrtf, or sqrtl with argument ARG.
7464    Return NULL_TREE if no simplification can be made.  */
7465
7466 static tree
7467 fold_builtin_sqrt (location_t loc, tree arg, tree type)
7468 {
7469
7470   enum built_in_function fcode;
7471   tree res;
7472
7473   if (!validate_arg (arg, REAL_TYPE))
7474     return NULL_TREE;
7475
7476   /* Calculate the result when the argument is a constant.  */
7477   if ((res = do_mpfr_arg1 (arg, type, mpfr_sqrt, &dconst0, NULL, true)))
7478     return res;
7479
7480   /* Optimize sqrt(expN(x)) = expN(x*0.5).  */
7481   fcode = builtin_mathfn_code (arg);
7482   if (flag_unsafe_math_optimizations && BUILTIN_EXPONENT_P (fcode))
7483     {
7484       tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7485       arg = fold_build2_loc (loc, MULT_EXPR, type,
7486                          CALL_EXPR_ARG (arg, 0),
7487                          build_real (type, dconsthalf));
7488       return build_call_expr_loc (loc, expfn, 1, arg);
7489     }
7490
7491   /* Optimize sqrt(Nroot(x)) -> pow(x,1/(2*N)).  */
7492   if (flag_unsafe_math_optimizations && BUILTIN_ROOT_P (fcode))
7493     {
7494       tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7495
7496       if (powfn)
7497         {
7498           tree arg0 = CALL_EXPR_ARG (arg, 0);
7499           tree tree_root;
7500           /* The inner root was either sqrt or cbrt.  */
7501           /* This was a conditional expression but it triggered a bug
7502              in Sun C 5.5.  */
7503           REAL_VALUE_TYPE dconstroot;
7504           if (BUILTIN_SQRT_P (fcode))
7505             dconstroot = dconsthalf;
7506           else
7507             dconstroot = dconst_third ();
7508
7509           /* Adjust for the outer root.  */
7510           SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
7511           dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7512           tree_root = build_real (type, dconstroot);
7513           return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7514         }
7515     }
7516
7517   /* Optimize sqrt(pow(x,y)) = pow(|x|,y*0.5).  */
7518   if (flag_unsafe_math_optimizations
7519       && (fcode == BUILT_IN_POW
7520           || fcode == BUILT_IN_POWF
7521           || fcode == BUILT_IN_POWL))
7522     {
7523       tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7524       tree arg0 = CALL_EXPR_ARG (arg, 0);
7525       tree arg1 = CALL_EXPR_ARG (arg, 1);
7526       tree narg1;
7527       if (!tree_expr_nonnegative_p (arg0))
7528         arg0 = build1 (ABS_EXPR, type, arg0);
7529       narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
7530                            build_real (type, dconsthalf));
7531       return build_call_expr_loc (loc, powfn, 2, arg0, narg1);
7532     }
7533
7534   return NULL_TREE;
7535 }
7536
7537 /* Fold a builtin function call to cbrt, cbrtf, or cbrtl with argument ARG.
7538    Return NULL_TREE if no simplification can be made.  */
7539
7540 static tree
7541 fold_builtin_cbrt (location_t loc, tree arg, tree type)
7542 {
7543   const enum built_in_function fcode = builtin_mathfn_code (arg);
7544   tree res;
7545
7546   if (!validate_arg (arg, REAL_TYPE))
7547     return NULL_TREE;
7548
7549   /* Calculate the result when the argument is a constant.  */
7550   if ((res = do_mpfr_arg1 (arg, type, mpfr_cbrt, NULL, NULL, 0)))
7551     return res;
7552
7553   if (flag_unsafe_math_optimizations)
7554     {
7555       /* Optimize cbrt(expN(x)) -> expN(x/3).  */
7556       if (BUILTIN_EXPONENT_P (fcode))
7557         {
7558           tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7559           const REAL_VALUE_TYPE third_trunc =
7560             real_value_truncate (TYPE_MODE (type), dconst_third ());
7561           arg = fold_build2_loc (loc, MULT_EXPR, type,
7562                              CALL_EXPR_ARG (arg, 0),
7563                              build_real (type, third_trunc));
7564           return build_call_expr_loc (loc, expfn, 1, arg);
7565         }
7566
7567       /* Optimize cbrt(sqrt(x)) -> pow(x,1/6).  */
7568       if (BUILTIN_SQRT_P (fcode))
7569         {
7570           tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7571
7572           if (powfn)
7573             {
7574               tree arg0 = CALL_EXPR_ARG (arg, 0);
7575               tree tree_root;
7576               REAL_VALUE_TYPE dconstroot = dconst_third ();
7577
7578               SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
7579               dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7580               tree_root = build_real (type, dconstroot);
7581               return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7582             }
7583         }
7584
7585       /* Optimize cbrt(cbrt(x)) -> pow(x,1/9) iff x is nonnegative.  */
7586       if (BUILTIN_CBRT_P (fcode))
7587         {
7588           tree arg0 = CALL_EXPR_ARG (arg, 0);
7589           if (tree_expr_nonnegative_p (arg0))
7590             {
7591               tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7592
7593               if (powfn)
7594                 {
7595                   tree tree_root;
7596                   REAL_VALUE_TYPE dconstroot;
7597
7598                   real_arithmetic (&dconstroot, MULT_EXPR,
7599                                    dconst_third_ptr (), dconst_third_ptr ());
7600                   dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7601                   tree_root = build_real (type, dconstroot);
7602                   return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7603                 }
7604             }
7605         }
7606
7607       /* Optimize cbrt(pow(x,y)) -> pow(x,y/3) iff x is nonnegative.  */
7608       if (fcode == BUILT_IN_POW
7609           || fcode == BUILT_IN_POWF
7610           || fcode == BUILT_IN_POWL)
7611         {
7612           tree arg00 = CALL_EXPR_ARG (arg, 0);
7613           tree arg01 = CALL_EXPR_ARG (arg, 1);
7614           if (tree_expr_nonnegative_p (arg00))
7615             {
7616               tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7617               const REAL_VALUE_TYPE dconstroot
7618                 = real_value_truncate (TYPE_MODE (type), dconst_third ());
7619               tree narg01 = fold_build2_loc (loc, MULT_EXPR, type, arg01,
7620                                          build_real (type, dconstroot));
7621               return build_call_expr_loc (loc, powfn, 2, arg00, narg01);
7622             }
7623         }
7624     }
7625   return NULL_TREE;
7626 }
7627
7628 /* Fold function call to builtin cos, cosf, or cosl with argument ARG.
7629    TYPE is the type of the return value.  Return NULL_TREE if no
7630    simplification can be made.  */
7631
7632 static tree
7633 fold_builtin_cos (location_t loc,
7634                   tree arg, tree type, tree fndecl)
7635 {
7636   tree res, narg;
7637
7638   if (!validate_arg (arg, REAL_TYPE))
7639     return NULL_TREE;
7640
7641   /* Calculate the result when the argument is a constant.  */
7642   if ((res = do_mpfr_arg1 (arg, type, mpfr_cos, NULL, NULL, 0)))
7643     return res;
7644
7645   /* Optimize cos(-x) into cos (x).  */
7646   if ((narg = fold_strip_sign_ops (arg)))
7647     return build_call_expr_loc (loc, fndecl, 1, narg);
7648
7649   return NULL_TREE;
7650 }
7651
7652 /* Fold function call to builtin cosh, coshf, or coshl with argument ARG.
7653    Return NULL_TREE if no simplification can be made.  */
7654
7655 static tree
7656 fold_builtin_cosh (location_t loc, tree arg, tree type, tree fndecl)
7657 {
7658   if (validate_arg (arg, REAL_TYPE))
7659     {
7660       tree res, narg;
7661
7662       /* Calculate the result when the argument is a constant.  */
7663       if ((res = do_mpfr_arg1 (arg, type, mpfr_cosh, NULL, NULL, 0)))
7664         return res;
7665
7666       /* Optimize cosh(-x) into cosh (x).  */
7667       if ((narg = fold_strip_sign_ops (arg)))
7668         return build_call_expr_loc (loc, fndecl, 1, narg);
7669     }
7670
7671   return NULL_TREE;
7672 }
7673
7674 /* Fold function call to builtin ccos (or ccosh if HYPER is TRUE) with
7675    argument ARG.  TYPE is the type of the return value.  Return
7676    NULL_TREE if no simplification can be made.  */
7677
7678 static tree
7679 fold_builtin_ccos (location_t loc, tree arg, tree type, tree fndecl,
7680                    bool hyper)
7681 {
7682   if (validate_arg (arg, COMPLEX_TYPE)
7683       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE)
7684     {
7685       tree tmp;
7686
7687       /* Calculate the result when the argument is a constant.  */
7688       if ((tmp = do_mpc_arg1 (arg, type, (hyper ? mpc_cosh : mpc_cos))))
7689         return tmp;
7690
7691       /* Optimize fn(-x) into fn(x).  */
7692       if ((tmp = fold_strip_sign_ops (arg)))
7693         return build_call_expr_loc (loc, fndecl, 1, tmp);
7694     }
7695
7696   return NULL_TREE;
7697 }
7698
7699 /* Fold function call to builtin tan, tanf, or tanl with argument ARG.
7700    Return NULL_TREE if no simplification can be made.  */
7701
7702 static tree
7703 fold_builtin_tan (tree arg, tree type)
7704 {
7705   enum built_in_function fcode;
7706   tree res;
7707
7708   if (!validate_arg (arg, REAL_TYPE))
7709     return NULL_TREE;
7710
7711   /* Calculate the result when the argument is a constant.  */
7712   if ((res = do_mpfr_arg1 (arg, type, mpfr_tan, NULL, NULL, 0)))
7713     return res;
7714
7715   /* Optimize tan(atan(x)) = x.  */
7716   fcode = builtin_mathfn_code (arg);
7717   if (flag_unsafe_math_optimizations
7718       && (fcode == BUILT_IN_ATAN
7719           || fcode == BUILT_IN_ATANF
7720           || fcode == BUILT_IN_ATANL))
7721     return CALL_EXPR_ARG (arg, 0);
7722
7723   return NULL_TREE;
7724 }
7725
7726 /* Fold function call to builtin sincos, sincosf, or sincosl.  Return
7727    NULL_TREE if no simplification can be made.  */
7728
7729 static tree
7730 fold_builtin_sincos (location_t loc,
7731                      tree arg0, tree arg1, tree arg2)
7732 {
7733   tree type;
7734   tree res, fn, call;
7735
7736   if (!validate_arg (arg0, REAL_TYPE)
7737       || !validate_arg (arg1, POINTER_TYPE)
7738       || !validate_arg (arg2, POINTER_TYPE))
7739     return NULL_TREE;
7740
7741   type = TREE_TYPE (arg0);
7742
7743   /* Calculate the result when the argument is a constant.  */
7744   if ((res = do_mpfr_sincos (arg0, arg1, arg2)))
7745     return res;
7746
7747   /* Canonicalize sincos to cexpi.  */
7748   if (!targetm.libc_has_function (function_c99_math_complex))
7749     return NULL_TREE;
7750   fn = mathfn_built_in (type, BUILT_IN_CEXPI);
7751   if (!fn)
7752     return NULL_TREE;
7753
7754   call = build_call_expr_loc (loc, fn, 1, arg0);
7755   call = builtin_save_expr (call);
7756
7757   return build2 (COMPOUND_EXPR, void_type_node,
7758                  build2 (MODIFY_EXPR, void_type_node,
7759                          build_fold_indirect_ref_loc (loc, arg1),
7760                          build1 (IMAGPART_EXPR, type, call)),
7761                  build2 (MODIFY_EXPR, void_type_node,
7762                          build_fold_indirect_ref_loc (loc, arg2),
7763                          build1 (REALPART_EXPR, type, call)));
7764 }
7765
7766 /* Fold function call to builtin cexp, cexpf, or cexpl.  Return
7767    NULL_TREE if no simplification can be made.  */
7768
7769 static tree
7770 fold_builtin_cexp (location_t loc, tree arg0, tree type)
7771 {
7772   tree rtype;
7773   tree realp, imagp, ifn;
7774   tree res;
7775
7776   if (!validate_arg (arg0, COMPLEX_TYPE)
7777       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) != REAL_TYPE)
7778     return NULL_TREE;
7779
7780   /* Calculate the result when the argument is a constant.  */
7781   if ((res = do_mpc_arg1 (arg0, type, mpc_exp)))
7782     return res;
7783
7784   rtype = TREE_TYPE (TREE_TYPE (arg0));
7785
7786   /* In case we can figure out the real part of arg0 and it is constant zero
7787      fold to cexpi.  */
7788   if (!targetm.libc_has_function (function_c99_math_complex))
7789     return NULL_TREE;
7790   ifn = mathfn_built_in (rtype, BUILT_IN_CEXPI);
7791   if (!ifn)
7792     return NULL_TREE;
7793
7794   if ((realp = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0))
7795       && real_zerop (realp))
7796     {
7797       tree narg = fold_build1_loc (loc, IMAGPART_EXPR, rtype, arg0);
7798       return build_call_expr_loc (loc, ifn, 1, narg);
7799     }
7800
7801   /* In case we can easily decompose real and imaginary parts split cexp
7802      to exp (r) * cexpi (i).  */
7803   if (flag_unsafe_math_optimizations
7804       && realp)
7805     {
7806       tree rfn, rcall, icall;
7807
7808       rfn = mathfn_built_in (rtype, BUILT_IN_EXP);
7809       if (!rfn)
7810         return NULL_TREE;
7811
7812       imagp = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
7813       if (!imagp)
7814         return NULL_TREE;
7815
7816       icall = build_call_expr_loc (loc, ifn, 1, imagp);
7817       icall = builtin_save_expr (icall);
7818       rcall = build_call_expr_loc (loc, rfn, 1, realp);
7819       rcall = builtin_save_expr (rcall);
7820       return fold_build2_loc (loc, COMPLEX_EXPR, type,
7821                           fold_build2_loc (loc, MULT_EXPR, rtype,
7822                                        rcall,
7823                                        fold_build1_loc (loc, REALPART_EXPR,
7824                                                     rtype, icall)),
7825                           fold_build2_loc (loc, MULT_EXPR, rtype,
7826                                        rcall,
7827                                        fold_build1_loc (loc, IMAGPART_EXPR,
7828                                                     rtype, icall)));
7829     }
7830
7831   return NULL_TREE;
7832 }
7833
7834 /* Fold function call to builtin trunc, truncf or truncl with argument ARG.
7835    Return NULL_TREE if no simplification can be made.  */
7836
7837 static tree
7838 fold_builtin_trunc (location_t loc, tree fndecl, tree arg)
7839 {
7840   if (!validate_arg (arg, REAL_TYPE))
7841     return NULL_TREE;
7842
7843   /* Optimize trunc of constant value.  */
7844   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7845     {
7846       REAL_VALUE_TYPE r, x;
7847       tree type = TREE_TYPE (TREE_TYPE (fndecl));
7848
7849       x = TREE_REAL_CST (arg);
7850       real_trunc (&r, TYPE_MODE (type), &x);
7851       return build_real (type, r);
7852     }
7853
7854   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7855 }
7856
7857 /* Fold function call to builtin floor, floorf or floorl with argument ARG.
7858    Return NULL_TREE if no simplification can be made.  */
7859
7860 static tree
7861 fold_builtin_floor (location_t loc, tree fndecl, tree arg)
7862 {
7863   if (!validate_arg (arg, REAL_TYPE))
7864     return NULL_TREE;
7865
7866   /* Optimize floor of constant value.  */
7867   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7868     {
7869       REAL_VALUE_TYPE x;
7870
7871       x = TREE_REAL_CST (arg);
7872       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7873         {
7874           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7875           REAL_VALUE_TYPE r;
7876
7877           real_floor (&r, TYPE_MODE (type), &x);
7878           return build_real (type, r);
7879         }
7880     }
7881
7882   /* Fold floor (x) where x is nonnegative to trunc (x).  */
7883   if (tree_expr_nonnegative_p (arg))
7884     {
7885       tree truncfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_TRUNC);
7886       if (truncfn)
7887         return build_call_expr_loc (loc, truncfn, 1, arg);
7888     }
7889
7890   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7891 }
7892
7893 /* Fold function call to builtin ceil, ceilf or ceill with argument ARG.
7894    Return NULL_TREE if no simplification can be made.  */
7895
7896 static tree
7897 fold_builtin_ceil (location_t loc, tree fndecl, tree arg)
7898 {
7899   if (!validate_arg (arg, REAL_TYPE))
7900     return NULL_TREE;
7901
7902   /* Optimize ceil of constant value.  */
7903   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7904     {
7905       REAL_VALUE_TYPE x;
7906
7907       x = TREE_REAL_CST (arg);
7908       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7909         {
7910           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7911           REAL_VALUE_TYPE r;
7912
7913           real_ceil (&r, TYPE_MODE (type), &x);
7914           return build_real (type, r);
7915         }
7916     }
7917
7918   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7919 }
7920
7921 /* Fold function call to builtin round, roundf or roundl with argument ARG.
7922    Return NULL_TREE if no simplification can be made.  */
7923
7924 static tree
7925 fold_builtin_round (location_t loc, tree fndecl, tree arg)
7926 {
7927   if (!validate_arg (arg, REAL_TYPE))
7928     return NULL_TREE;
7929
7930   /* Optimize round of constant value.  */
7931   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7932     {
7933       REAL_VALUE_TYPE x;
7934
7935       x = TREE_REAL_CST (arg);
7936       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7937         {
7938           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7939           REAL_VALUE_TYPE r;
7940
7941           real_round (&r, TYPE_MODE (type), &x);
7942           return build_real (type, r);
7943         }
7944     }
7945
7946   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7947 }
7948
7949 /* Fold function call to builtin lround, lroundf or lroundl (or the
7950    corresponding long long versions) and other rounding functions.  ARG
7951    is the argument to the call.  Return NULL_TREE if no simplification
7952    can be made.  */
7953
7954 static tree
7955 fold_builtin_int_roundingfn (location_t loc, tree fndecl, tree arg)
7956 {
7957   if (!validate_arg (arg, REAL_TYPE))
7958     return NULL_TREE;
7959
7960   /* Optimize lround of constant value.  */
7961   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7962     {
7963       const REAL_VALUE_TYPE x = TREE_REAL_CST (arg);
7964
7965       if (real_isfinite (&x))
7966         {
7967           tree itype = TREE_TYPE (TREE_TYPE (fndecl));
7968           tree ftype = TREE_TYPE (arg);
7969           double_int val;
7970           REAL_VALUE_TYPE r;
7971
7972           switch (DECL_FUNCTION_CODE (fndecl))
7973             {
7974             CASE_FLT_FN (BUILT_IN_IFLOOR):
7975             CASE_FLT_FN (BUILT_IN_LFLOOR):
7976             CASE_FLT_FN (BUILT_IN_LLFLOOR):
7977               real_floor (&r, TYPE_MODE (ftype), &x);
7978               break;
7979
7980             CASE_FLT_FN (BUILT_IN_ICEIL):
7981             CASE_FLT_FN (BUILT_IN_LCEIL):
7982             CASE_FLT_FN (BUILT_IN_LLCEIL):
7983               real_ceil (&r, TYPE_MODE (ftype), &x);
7984               break;
7985
7986             CASE_FLT_FN (BUILT_IN_IROUND):
7987             CASE_FLT_FN (BUILT_IN_LROUND):
7988             CASE_FLT_FN (BUILT_IN_LLROUND):
7989               real_round (&r, TYPE_MODE (ftype), &x);
7990               break;
7991
7992             default:
7993               gcc_unreachable ();
7994             }
7995
7996           real_to_integer2 ((HOST_WIDE_INT *)&val.low, &val.high, &r);
7997           if (double_int_fits_to_tree_p (itype, val))
7998             return double_int_to_tree (itype, val);
7999         }
8000     }
8001
8002   switch (DECL_FUNCTION_CODE (fndecl))
8003     {
8004     CASE_FLT_FN (BUILT_IN_LFLOOR):
8005     CASE_FLT_FN (BUILT_IN_LLFLOOR):
8006       /* Fold lfloor (x) where x is nonnegative to FIX_TRUNC (x).  */
8007       if (tree_expr_nonnegative_p (arg))
8008         return fold_build1_loc (loc, FIX_TRUNC_EXPR,
8009                             TREE_TYPE (TREE_TYPE (fndecl)), arg);
8010       break;
8011     default:;
8012     }
8013
8014   return fold_fixed_mathfn (loc, fndecl, arg);
8015 }
8016
8017 /* Fold function call to builtin ffs, clz, ctz, popcount and parity
8018    and their long and long long variants (i.e. ffsl and ffsll).  ARG is
8019    the argument to the call.  Return NULL_TREE if no simplification can
8020    be made.  */
8021
8022 static tree
8023 fold_builtin_bitop (tree fndecl, tree arg)
8024 {
8025   if (!validate_arg (arg, INTEGER_TYPE))
8026     return NULL_TREE;
8027
8028   /* Optimize for constant argument.  */
8029   if (TREE_CODE (arg) == INTEGER_CST && !TREE_OVERFLOW (arg))
8030     {
8031       HOST_WIDE_INT hi, width, result;
8032       unsigned HOST_WIDE_INT lo;
8033       tree type;
8034
8035       type = TREE_TYPE (arg);
8036       width = TYPE_PRECISION (type);
8037       lo = TREE_INT_CST_LOW (arg);
8038
8039       /* Clear all the bits that are beyond the type's precision.  */
8040       if (width > HOST_BITS_PER_WIDE_INT)
8041         {
8042           hi = TREE_INT_CST_HIGH (arg);
8043           if (width < HOST_BITS_PER_DOUBLE_INT)
8044             hi &= ~(HOST_WIDE_INT_M1U << (width - HOST_BITS_PER_WIDE_INT));
8045         }
8046       else
8047         {
8048           hi = 0;
8049           if (width < HOST_BITS_PER_WIDE_INT)
8050             lo &= ~(HOST_WIDE_INT_M1U << width);
8051         }
8052
8053       switch (DECL_FUNCTION_CODE (fndecl))
8054         {
8055         CASE_INT_FN (BUILT_IN_FFS):
8056           if (lo != 0)
8057             result = ffs_hwi (lo);
8058           else if (hi != 0)
8059             result = HOST_BITS_PER_WIDE_INT + ffs_hwi (hi);
8060           else
8061             result = 0;
8062           break;
8063
8064         CASE_INT_FN (BUILT_IN_CLZ):
8065           if (hi != 0)
8066             result = width - floor_log2 (hi) - 1 - HOST_BITS_PER_WIDE_INT;
8067           else if (lo != 0)
8068             result = width - floor_log2 (lo) - 1;
8069           else if (! CLZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
8070             result = width;
8071           break;
8072
8073         CASE_INT_FN (BUILT_IN_CTZ):
8074           if (lo != 0)
8075             result = ctz_hwi (lo);
8076           else if (hi != 0)
8077             result = HOST_BITS_PER_WIDE_INT + ctz_hwi (hi);
8078           else if (! CTZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
8079             result = width;
8080           break;
8081
8082         CASE_INT_FN (BUILT_IN_CLRSB):
8083           if (width > 2 * HOST_BITS_PER_WIDE_INT)
8084             return NULL_TREE;
8085           if (width > HOST_BITS_PER_WIDE_INT
8086               && (hi & ((unsigned HOST_WIDE_INT) 1
8087                         << (width - HOST_BITS_PER_WIDE_INT - 1))) != 0)
8088             {
8089               hi = ~hi & ~(HOST_WIDE_INT_M1U
8090                            << (width - HOST_BITS_PER_WIDE_INT - 1));
8091               lo = ~lo;
8092             }
8093           else if (width <= HOST_BITS_PER_WIDE_INT
8094                    && (lo & ((unsigned HOST_WIDE_INT) 1 << (width - 1))) != 0)
8095             lo = ~lo & ~(HOST_WIDE_INT_M1U << (width - 1));
8096           if (hi != 0)
8097             result = width - floor_log2 (hi) - 2 - HOST_BITS_PER_WIDE_INT;
8098           else if (lo != 0)
8099             result = width - floor_log2 (lo) - 2;
8100           else
8101             result = width - 1;
8102           break;
8103
8104         CASE_INT_FN (BUILT_IN_POPCOUNT):
8105           result = 0;
8106           while (lo)
8107             result++, lo &= lo - 1;
8108           while (hi)
8109             result++, hi &= (unsigned HOST_WIDE_INT) hi - 1;
8110           break;
8111
8112         CASE_INT_FN (BUILT_IN_PARITY):
8113           result = 0;
8114           while (lo)
8115             result++, lo &= lo - 1;
8116           while (hi)
8117             result++, hi &= (unsigned HOST_WIDE_INT) hi - 1;
8118           result &= 1;
8119           break;
8120
8121         default:
8122           gcc_unreachable ();
8123         }
8124
8125       return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), result);
8126     }
8127
8128   return NULL_TREE;
8129 }
8130
8131 /* Fold function call to builtin_bswap and the short, long and long long
8132    variants.  Return NULL_TREE if no simplification can be made.  */
8133 static tree
8134 fold_builtin_bswap (tree fndecl, tree arg)
8135 {
8136   if (! validate_arg (arg, INTEGER_TYPE))
8137     return NULL_TREE;
8138
8139   /* Optimize constant value.  */
8140   if (TREE_CODE (arg) == INTEGER_CST && !TREE_OVERFLOW (arg))
8141     {
8142       HOST_WIDE_INT hi, width, r_hi = 0;
8143       unsigned HOST_WIDE_INT lo, r_lo = 0;
8144       tree type = TREE_TYPE (TREE_TYPE (fndecl));
8145
8146       width = TYPE_PRECISION (type);
8147       lo = TREE_INT_CST_LOW (arg);
8148       hi = TREE_INT_CST_HIGH (arg);
8149
8150       switch (DECL_FUNCTION_CODE (fndecl))
8151         {
8152           case BUILT_IN_BSWAP16:
8153           case BUILT_IN_BSWAP32:
8154           case BUILT_IN_BSWAP64:
8155             {
8156               int s;
8157
8158               for (s = 0; s < width; s += 8)
8159                 {
8160                   int d = width - s - 8;
8161                   unsigned HOST_WIDE_INT byte;
8162
8163                   if (s < HOST_BITS_PER_WIDE_INT)
8164                     byte = (lo >> s) & 0xff;
8165                   else
8166                     byte = (hi >> (s - HOST_BITS_PER_WIDE_INT)) & 0xff;
8167
8168                   if (d < HOST_BITS_PER_WIDE_INT)
8169                     r_lo |= byte << d;
8170                   else
8171                     r_hi |= byte << (d - HOST_BITS_PER_WIDE_INT);
8172                 }
8173             }
8174
8175             break;
8176
8177         default:
8178           gcc_unreachable ();
8179         }
8180
8181       if (width < HOST_BITS_PER_WIDE_INT)
8182         return build_int_cst (type, r_lo);
8183       else
8184         return build_int_cst_wide (type, r_lo, r_hi);
8185     }
8186
8187   return NULL_TREE;
8188 }
8189
8190 /* A subroutine of fold_builtin to fold the various logarithmic
8191    functions.  Return NULL_TREE if no simplification can me made.
8192    FUNC is the corresponding MPFR logarithm function.  */
8193
8194 static tree
8195 fold_builtin_logarithm (location_t loc, tree fndecl, tree arg,
8196                         int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t))
8197 {
8198   if (validate_arg (arg, REAL_TYPE))
8199     {
8200       tree type = TREE_TYPE (TREE_TYPE (fndecl));
8201       tree res;
8202       const enum built_in_function fcode = builtin_mathfn_code (arg);
8203
8204       /* Calculate the result when the argument is a constant.  */
8205       if ((res = do_mpfr_arg1 (arg, type, func, &dconst0, NULL, false)))
8206         return res;
8207
8208       /* Special case, optimize logN(expN(x)) = x.  */
8209       if (flag_unsafe_math_optimizations
8210           && ((func == mpfr_log
8211                && (fcode == BUILT_IN_EXP
8212                    || fcode == BUILT_IN_EXPF
8213                    || fcode == BUILT_IN_EXPL))
8214               || (func == mpfr_log2
8215                   && (fcode == BUILT_IN_EXP2
8216                       || fcode == BUILT_IN_EXP2F
8217                       || fcode == BUILT_IN_EXP2L))
8218               || (func == mpfr_log10 && (BUILTIN_EXP10_P (fcode)))))
8219         return fold_convert_loc (loc, type, CALL_EXPR_ARG (arg, 0));
8220
8221       /* Optimize logN(func()) for various exponential functions.  We
8222          want to determine the value "x" and the power "exponent" in
8223          order to transform logN(x**exponent) into exponent*logN(x).  */
8224       if (flag_unsafe_math_optimizations)
8225         {
8226           tree exponent = 0, x = 0;
8227
8228           switch (fcode)
8229           {
8230           CASE_FLT_FN (BUILT_IN_EXP):
8231             /* Prepare to do logN(exp(exponent) -> exponent*logN(e).  */
8232             x = build_real (type, real_value_truncate (TYPE_MODE (type),
8233                                                        dconst_e ()));
8234             exponent = CALL_EXPR_ARG (arg, 0);
8235             break;
8236           CASE_FLT_FN (BUILT_IN_EXP2):
8237             /* Prepare to do logN(exp2(exponent) -> exponent*logN(2).  */
8238             x = build_real (type, dconst2);
8239             exponent = CALL_EXPR_ARG (arg, 0);
8240             break;
8241           CASE_FLT_FN (BUILT_IN_EXP10):
8242           CASE_FLT_FN (BUILT_IN_POW10):
8243             /* Prepare to do logN(exp10(exponent) -> exponent*logN(10).  */
8244             {
8245               REAL_VALUE_TYPE dconst10;
8246               real_from_integer (&dconst10, VOIDmode, 10, 0, 0);
8247               x = build_real (type, dconst10);
8248             }
8249             exponent = CALL_EXPR_ARG (arg, 0);
8250             break;
8251           CASE_FLT_FN (BUILT_IN_SQRT):
8252             /* Prepare to do logN(sqrt(x) -> 0.5*logN(x).  */
8253             x = CALL_EXPR_ARG (arg, 0);
8254             exponent = build_real (type, dconsthalf);
8255             break;
8256           CASE_FLT_FN (BUILT_IN_CBRT):
8257             /* Prepare to do logN(cbrt(x) -> (1/3)*logN(x).  */
8258             x = CALL_EXPR_ARG (arg, 0);
8259             exponent = build_real (type, real_value_truncate (TYPE_MODE (type),
8260                                                               dconst_third ()));
8261             break;
8262           CASE_FLT_FN (BUILT_IN_POW):
8263             /* Prepare to do logN(pow(x,exponent) -> exponent*logN(x).  */
8264             x = CALL_EXPR_ARG (arg, 0);
8265             exponent = CALL_EXPR_ARG (arg, 1);
8266             break;
8267           default:
8268             break;
8269           }
8270
8271           /* Now perform the optimization.  */
8272           if (x && exponent)
8273             {
8274               tree logfn = build_call_expr_loc (loc, fndecl, 1, x);
8275               return fold_build2_loc (loc, MULT_EXPR, type, exponent, logfn);
8276             }
8277         }
8278     }
8279
8280   return NULL_TREE;
8281 }
8282
8283 /* Fold a builtin function call to hypot, hypotf, or hypotl.  Return
8284    NULL_TREE if no simplification can be made.  */
8285
8286 static tree
8287 fold_builtin_hypot (location_t loc, tree fndecl,
8288                     tree arg0, tree arg1, tree type)
8289 {
8290   tree res, narg0, narg1;
8291
8292   if (!validate_arg (arg0, REAL_TYPE)
8293       || !validate_arg (arg1, REAL_TYPE))
8294     return NULL_TREE;
8295
8296   /* Calculate the result when the argument is a constant.  */
8297   if ((res = do_mpfr_arg2 (arg0, arg1, type, mpfr_hypot)))
8298     return res;
8299
8300   /* If either argument to hypot has a negate or abs, strip that off.
8301      E.g. hypot(-x,fabs(y)) -> hypot(x,y).  */
8302   narg0 = fold_strip_sign_ops (arg0);
8303   narg1 = fold_strip_sign_ops (arg1);
8304   if (narg0 || narg1)
8305     {
8306       return build_call_expr_loc (loc, fndecl, 2, narg0 ? narg0 : arg0,
8307                               narg1 ? narg1 : arg1);
8308     }
8309
8310   /* If either argument is zero, hypot is fabs of the other.  */
8311   if (real_zerop (arg0))
8312     return fold_build1_loc (loc, ABS_EXPR, type, arg1);
8313   else if (real_zerop (arg1))
8314     return fold_build1_loc (loc, ABS_EXPR, type, arg0);
8315
8316   /* hypot(x,x) -> fabs(x)*sqrt(2).  */
8317   if (flag_unsafe_math_optimizations
8318       && operand_equal_p (arg0, arg1, OEP_PURE_SAME))
8319     {
8320       const REAL_VALUE_TYPE sqrt2_trunc
8321         = real_value_truncate (TYPE_MODE (type), dconst_sqrt2 ());
8322       return fold_build2_loc (loc, MULT_EXPR, type,
8323                           fold_build1_loc (loc, ABS_EXPR, type, arg0),
8324                           build_real (type, sqrt2_trunc));
8325     }
8326
8327   return NULL_TREE;
8328 }
8329
8330
8331 /* Fold a builtin function call to pow, powf, or powl.  Return
8332    NULL_TREE if no simplification can be made.  */
8333 static tree
8334 fold_builtin_pow (location_t loc, tree fndecl, tree arg0, tree arg1, tree type)
8335 {
8336   tree res;
8337
8338   if (!validate_arg (arg0, REAL_TYPE)
8339        || !validate_arg (arg1, REAL_TYPE))
8340     return NULL_TREE;
8341
8342   /* Calculate the result when the argument is a constant.  */
8343   if ((res = do_mpfr_arg2 (arg0, arg1, type, mpfr_pow)))
8344     return res;
8345
8346   /* Optimize pow(1.0,y) = 1.0.  */
8347   if (real_onep (arg0))
8348     return omit_one_operand_loc (loc, type, build_real (type, dconst1), arg1);
8349
8350   if (TREE_CODE (arg1) == REAL_CST
8351       && !TREE_OVERFLOW (arg1))
8352     {
8353       REAL_VALUE_TYPE cint;
8354       REAL_VALUE_TYPE c;
8355       HOST_WIDE_INT n;
8356
8357       c = TREE_REAL_CST (arg1);
8358
8359       /* Optimize pow(x,0.0) = 1.0.  */
8360       if (REAL_VALUES_EQUAL (c, dconst0))
8361         return omit_one_operand_loc (loc, type, build_real (type, dconst1),
8362                                  arg0);
8363
8364       /* Optimize pow(x,1.0) = x.  */
8365       if (REAL_VALUES_EQUAL (c, dconst1))
8366         return arg0;
8367
8368       /* Optimize pow(x,-1.0) = 1.0/x.  */
8369       if (REAL_VALUES_EQUAL (c, dconstm1))
8370         return fold_build2_loc (loc, RDIV_EXPR, type,
8371                             build_real (type, dconst1), arg0);
8372
8373       /* Optimize pow(x,0.5) = sqrt(x).  */
8374       if (flag_unsafe_math_optimizations
8375           && REAL_VALUES_EQUAL (c, dconsthalf))
8376         {
8377           tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
8378
8379           if (sqrtfn != NULL_TREE)
8380             return build_call_expr_loc (loc, sqrtfn, 1, arg0);
8381         }
8382
8383       /* Optimize pow(x,1.0/3.0) = cbrt(x).  */
8384       if (flag_unsafe_math_optimizations)
8385         {
8386           const REAL_VALUE_TYPE dconstroot
8387             = real_value_truncate (TYPE_MODE (type), dconst_third ());
8388
8389           if (REAL_VALUES_EQUAL (c, dconstroot))
8390             {
8391               tree cbrtfn = mathfn_built_in (type, BUILT_IN_CBRT);
8392               if (cbrtfn != NULL_TREE)
8393                 return build_call_expr_loc (loc, cbrtfn, 1, arg0);
8394             }
8395         }
8396
8397       /* Check for an integer exponent.  */
8398       n = real_to_integer (&c);
8399       real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
8400       if (real_identical (&c, &cint))
8401         {
8402           /* Attempt to evaluate pow at compile-time, unless this should
8403              raise an exception.  */
8404           if (TREE_CODE (arg0) == REAL_CST
8405               && !TREE_OVERFLOW (arg0)
8406               && (n > 0
8407                   || (!flag_trapping_math && !flag_errno_math)
8408                   || !REAL_VALUES_EQUAL (TREE_REAL_CST (arg0), dconst0)))
8409             {
8410               REAL_VALUE_TYPE x;
8411               bool inexact;
8412
8413               x = TREE_REAL_CST (arg0);
8414               inexact = real_powi (&x, TYPE_MODE (type), &x, n);
8415               if (flag_unsafe_math_optimizations || !inexact)
8416                 return build_real (type, x);
8417             }
8418
8419           /* Strip sign ops from even integer powers.  */
8420           if ((n & 1) == 0 && flag_unsafe_math_optimizations)
8421             {
8422               tree narg0 = fold_strip_sign_ops (arg0);
8423               if (narg0)
8424                 return build_call_expr_loc (loc, fndecl, 2, narg0, arg1);
8425             }
8426         }
8427     }
8428
8429   if (flag_unsafe_math_optimizations)
8430     {
8431       const enum built_in_function fcode = builtin_mathfn_code (arg0);
8432
8433       /* Optimize pow(expN(x),y) = expN(x*y).  */
8434       if (BUILTIN_EXPONENT_P (fcode))
8435         {
8436           tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
8437           tree arg = CALL_EXPR_ARG (arg0, 0);
8438           arg = fold_build2_loc (loc, MULT_EXPR, type, arg, arg1);
8439           return build_call_expr_loc (loc, expfn, 1, arg);
8440         }
8441
8442       /* Optimize pow(sqrt(x),y) = pow(x,y*0.5).  */
8443       if (BUILTIN_SQRT_P (fcode))
8444         {
8445           tree narg0 = CALL_EXPR_ARG (arg0, 0);
8446           tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
8447                                     build_real (type, dconsthalf));
8448           return build_call_expr_loc (loc, fndecl, 2, narg0, narg1);
8449         }
8450
8451       /* Optimize pow(cbrt(x),y) = pow(x,y/3) iff x is nonnegative.  */
8452       if (BUILTIN_CBRT_P (fcode))
8453         {
8454           tree arg = CALL_EXPR_ARG (arg0, 0);
8455           if (tree_expr_nonnegative_p (arg))
8456             {
8457               const REAL_VALUE_TYPE dconstroot
8458                 = real_value_truncate (TYPE_MODE (type), dconst_third ());
8459               tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
8460                                         build_real (type, dconstroot));
8461               return build_call_expr_loc (loc, fndecl, 2, arg, narg1);
8462             }
8463         }
8464
8465       /* Optimize pow(pow(x,y),z) = pow(x,y*z) iff x is nonnegative.  */
8466       if (fcode == BUILT_IN_POW
8467           || fcode == BUILT_IN_POWF
8468           || fcode == BUILT_IN_POWL)
8469         {
8470           tree arg00 = CALL_EXPR_ARG (arg0, 0);
8471           if (tree_expr_nonnegative_p (arg00))
8472             {
8473               tree arg01 = CALL_EXPR_ARG (arg0, 1);
8474               tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg01, arg1);
8475               return build_call_expr_loc (loc, fndecl, 2, arg00, narg1);
8476             }
8477         }
8478     }
8479
8480   return NULL_TREE;
8481 }
8482
8483 /* Fold a builtin function call to powi, powif, or powil with argument ARG.
8484    Return NULL_TREE if no simplification can be made.  */
8485 static tree
8486 fold_builtin_powi (location_t loc, tree fndecl ATTRIBUTE_UNUSED,
8487                    tree arg0, tree arg1, tree type)
8488 {
8489   if (!validate_arg (arg0, REAL_TYPE)
8490       || !validate_arg (arg1, INTEGER_TYPE))
8491     return NULL_TREE;
8492
8493   /* Optimize pow(1.0,y) = 1.0.  */
8494   if (real_onep (arg0))
8495     return omit_one_operand_loc (loc, type, build_real (type, dconst1), arg1);
8496
8497   if (host_integerp (arg1, 0))
8498     {
8499       HOST_WIDE_INT c = TREE_INT_CST_LOW (arg1);
8500
8501       /* Evaluate powi at compile-time.  */
8502       if (TREE_CODE (arg0) == REAL_CST
8503           && !TREE_OVERFLOW (arg0))
8504         {
8505           REAL_VALUE_TYPE x;
8506           x = TREE_REAL_CST (arg0);
8507           real_powi (&x, TYPE_MODE (type), &x, c);
8508           return build_real (type, x);
8509         }
8510
8511       /* Optimize pow(x,0) = 1.0.  */
8512       if (c == 0)
8513         return omit_one_operand_loc (loc, type, build_real (type, dconst1),
8514                                  arg0);
8515
8516       /* Optimize pow(x,1) = x.  */
8517       if (c == 1)
8518         return arg0;
8519
8520       /* Optimize pow(x,-1) = 1.0/x.  */
8521       if (c == -1)
8522         return fold_build2_loc (loc, RDIV_EXPR, type,
8523                            build_real (type, dconst1), arg0);
8524     }
8525
8526   return NULL_TREE;
8527 }
8528
8529 /* A subroutine of fold_builtin to fold the various exponent
8530    functions.  Return NULL_TREE if no simplification can be made.
8531    FUNC is the corresponding MPFR exponent function.  */
8532
8533 static tree
8534 fold_builtin_exponent (location_t loc, tree fndecl, tree arg,
8535                        int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t))
8536 {
8537   if (validate_arg (arg, REAL_TYPE))
8538     {
8539       tree type = TREE_TYPE (TREE_TYPE (fndecl));
8540       tree res;
8541
8542       /* Calculate the result when the argument is a constant.  */
8543       if ((res = do_mpfr_arg1 (arg, type, func, NULL, NULL, 0)))
8544         return res;
8545
8546       /* Optimize expN(logN(x)) = x.  */
8547       if (flag_unsafe_math_optimizations)
8548         {
8549           const enum built_in_function fcode = builtin_mathfn_code (arg);
8550
8551           if ((func == mpfr_exp
8552                && (fcode == BUILT_IN_LOG
8553                    || fcode == BUILT_IN_LOGF
8554                    || fcode == BUILT_IN_LOGL))
8555               || (func == mpfr_exp2
8556                   && (fcode == BUILT_IN_LOG2
8557                       || fcode == BUILT_IN_LOG2F
8558                       || fcode == BUILT_IN_LOG2L))
8559               || (func == mpfr_exp10
8560                   && (fcode == BUILT_IN_LOG10
8561                       || fcode == BUILT_IN_LOG10F
8562                       || fcode == BUILT_IN_LOG10L)))
8563             return fold_convert_loc (loc, type, CALL_EXPR_ARG (arg, 0));
8564         }
8565     }
8566
8567   return NULL_TREE;
8568 }
8569
8570 /* Return true if VAR is a VAR_DECL or a component thereof.  */
8571
8572 static bool
8573 var_decl_component_p (tree var)
8574 {
8575   tree inner = var;
8576   while (handled_component_p (inner))
8577     inner = TREE_OPERAND (inner, 0);
8578   return SSA_VAR_P (inner);
8579 }
8580
8581 /* Fold function call to builtin memset.  Return
8582    NULL_TREE if no simplification can be made.  */
8583
8584 static tree
8585 fold_builtin_memset (location_t loc, tree dest, tree c, tree len,
8586                      tree type, bool ignore)
8587 {
8588   tree var, ret, etype;
8589   unsigned HOST_WIDE_INT length, cval;
8590
8591   if (! validate_arg (dest, POINTER_TYPE)
8592       || ! validate_arg (c, INTEGER_TYPE)
8593       || ! validate_arg (len, INTEGER_TYPE))
8594     return NULL_TREE;
8595
8596   if (! host_integerp (len, 1))
8597     return NULL_TREE;
8598
8599   /* If the LEN parameter is zero, return DEST.  */
8600   if (integer_zerop (len))
8601     return omit_one_operand_loc (loc, type, dest, c);
8602
8603   if (TREE_CODE (c) != INTEGER_CST || TREE_SIDE_EFFECTS (dest))
8604     return NULL_TREE;
8605
8606   var = dest;
8607   STRIP_NOPS (var);
8608   if (TREE_CODE (var) != ADDR_EXPR)
8609     return NULL_TREE;
8610
8611   var = TREE_OPERAND (var, 0);
8612   if (TREE_THIS_VOLATILE (var))
8613     return NULL_TREE;
8614
8615   etype = TREE_TYPE (var);
8616   if (TREE_CODE (etype) == ARRAY_TYPE)
8617     etype = TREE_TYPE (etype);
8618
8619   if (!INTEGRAL_TYPE_P (etype)
8620       && !POINTER_TYPE_P (etype))
8621     return NULL_TREE;
8622
8623   if (! var_decl_component_p (var))
8624     return NULL_TREE;
8625
8626   length = tree_low_cst (len, 1);
8627   if (GET_MODE_SIZE (TYPE_MODE (etype)) != length
8628       || get_pointer_alignment (dest) / BITS_PER_UNIT < length)
8629     return NULL_TREE;
8630
8631   if (length > HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT)
8632     return NULL_TREE;
8633
8634   if (integer_zerop (c))
8635     cval = 0;
8636   else
8637     {
8638       if (CHAR_BIT != 8 || BITS_PER_UNIT != 8 || HOST_BITS_PER_WIDE_INT > 64)
8639         return NULL_TREE;
8640
8641       cval = TREE_INT_CST_LOW (c);
8642       cval &= 0xff;
8643       cval |= cval << 8;
8644       cval |= cval << 16;
8645       cval |= (cval << 31) << 1;
8646     }
8647
8648   ret = build_int_cst_type (etype, cval);
8649   var = build_fold_indirect_ref_loc (loc,
8650                                  fold_convert_loc (loc,
8651                                                    build_pointer_type (etype),
8652                                                    dest));
8653   ret = build2 (MODIFY_EXPR, etype, var, ret);
8654   if (ignore)
8655     return ret;
8656
8657   return omit_one_operand_loc (loc, type, dest, ret);
8658 }
8659
8660 /* Fold function call to builtin memset.  Return
8661    NULL_TREE if no simplification can be made.  */
8662
8663 static tree
8664 fold_builtin_bzero (location_t loc, tree dest, tree size, bool ignore)
8665 {
8666   if (! validate_arg (dest, POINTER_TYPE)
8667       || ! validate_arg (size, INTEGER_TYPE))
8668     return NULL_TREE;
8669
8670   if (!ignore)
8671     return NULL_TREE;
8672
8673   /* New argument list transforming bzero(ptr x, int y) to
8674      memset(ptr x, int 0, size_t y).   This is done this way
8675      so that if it isn't expanded inline, we fallback to
8676      calling bzero instead of memset.  */
8677
8678   return fold_builtin_memset (loc, dest, integer_zero_node,
8679                               fold_convert_loc (loc, size_type_node, size),
8680                               void_type_node, ignore);
8681 }
8682
8683 /* Fold function call to builtin mem{{,p}cpy,move}.  Return
8684    NULL_TREE if no simplification can be made.
8685    If ENDP is 0, return DEST (like memcpy).
8686    If ENDP is 1, return DEST+LEN (like mempcpy).
8687    If ENDP is 2, return DEST+LEN-1 (like stpcpy).
8688    If ENDP is 3, return DEST, additionally *SRC and *DEST may overlap
8689    (memmove).   */
8690
8691 static tree
8692 fold_builtin_memory_op (location_t loc, tree dest, tree src,
8693                         tree len, tree type, bool ignore, int endp)
8694 {
8695   tree destvar, srcvar, expr;
8696
8697   if (! validate_arg (dest, POINTER_TYPE)
8698       || ! validate_arg (src, POINTER_TYPE)
8699       || ! validate_arg (len, INTEGER_TYPE))
8700     return NULL_TREE;
8701
8702   /* If the LEN parameter is zero, return DEST.  */
8703   if (integer_zerop (len))
8704     return omit_one_operand_loc (loc, type, dest, src);
8705
8706   /* If SRC and DEST are the same (and not volatile), return
8707      DEST{,+LEN,+LEN-1}.  */
8708   if (operand_equal_p (src, dest, 0))
8709     expr = len;
8710   else
8711     {
8712       tree srctype, desttype;
8713       unsigned int src_align, dest_align;
8714       tree off0;
8715
8716       if (endp == 3)
8717         {
8718           src_align = get_pointer_alignment (src);
8719           dest_align = get_pointer_alignment (dest);
8720
8721           /* Both DEST and SRC must be pointer types.
8722              ??? This is what old code did.  Is the testing for pointer types
8723              really mandatory?
8724
8725              If either SRC is readonly or length is 1, we can use memcpy.  */
8726           if (!dest_align || !src_align)
8727             return NULL_TREE;
8728           if (readonly_data_expr (src)
8729               || (host_integerp (len, 1)
8730                   && (MIN (src_align, dest_align) / BITS_PER_UNIT
8731                       >= (unsigned HOST_WIDE_INT) tree_low_cst (len, 1))))
8732             {
8733               tree fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
8734               if (!fn)
8735                 return NULL_TREE;
8736               return build_call_expr_loc (loc, fn, 3, dest, src, len);
8737             }
8738
8739           /* If *src and *dest can't overlap, optimize into memcpy as well.  */
8740           if (TREE_CODE (src) == ADDR_EXPR
8741               && TREE_CODE (dest) == ADDR_EXPR)
8742             {
8743               tree src_base, dest_base, fn;
8744               HOST_WIDE_INT src_offset = 0, dest_offset = 0;
8745               HOST_WIDE_INT size = -1;
8746               HOST_WIDE_INT maxsize = -1;
8747
8748               srcvar = TREE_OPERAND (src, 0);
8749               src_base = get_ref_base_and_extent (srcvar, &src_offset,
8750                                                   &size, &maxsize);
8751               destvar = TREE_OPERAND (dest, 0);
8752               dest_base = get_ref_base_and_extent (destvar, &dest_offset,
8753                                                    &size, &maxsize);
8754               if (host_integerp (len, 1))
8755                 maxsize = tree_low_cst (len, 1);
8756               else
8757                 maxsize = -1;
8758               src_offset /= BITS_PER_UNIT;
8759               dest_offset /= BITS_PER_UNIT;
8760               if (SSA_VAR_P (src_base)
8761                   && SSA_VAR_P (dest_base))
8762                 {
8763                   if (operand_equal_p (src_base, dest_base, 0)
8764                       && ranges_overlap_p (src_offset, maxsize,
8765                                            dest_offset, maxsize))
8766                     return NULL_TREE;
8767                 }
8768               else if (TREE_CODE (src_base) == MEM_REF
8769                        && TREE_CODE (dest_base) == MEM_REF)
8770                 {
8771                   double_int off;
8772                   if (! operand_equal_p (TREE_OPERAND (src_base, 0),
8773                                          TREE_OPERAND (dest_base, 0), 0))
8774                     return NULL_TREE;
8775                   off = mem_ref_offset (src_base) +
8776                                         double_int::from_shwi (src_offset);
8777                   if (!off.fits_shwi ())
8778                     return NULL_TREE;
8779                   src_offset = off.low;
8780                   off = mem_ref_offset (dest_base) +
8781                                         double_int::from_shwi (dest_offset);
8782                   if (!off.fits_shwi ())
8783                     return NULL_TREE;
8784                   dest_offset = off.low;
8785                   if (ranges_overlap_p (src_offset, maxsize,
8786                                         dest_offset, maxsize))
8787                     return NULL_TREE;
8788                 }
8789               else
8790                 return NULL_TREE;
8791
8792               fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
8793               if (!fn)
8794                 return NULL_TREE;
8795               return build_call_expr_loc (loc, fn, 3, dest, src, len);
8796             }
8797
8798           /* If the destination and source do not alias optimize into
8799              memcpy as well.  */
8800           if ((is_gimple_min_invariant (dest)
8801                || TREE_CODE (dest) == SSA_NAME)
8802               && (is_gimple_min_invariant (src)
8803                   || TREE_CODE (src) == SSA_NAME))
8804             {
8805               ao_ref destr, srcr;
8806               ao_ref_init_from_ptr_and_size (&destr, dest, len);
8807               ao_ref_init_from_ptr_and_size (&srcr, src, len);
8808               if (!refs_may_alias_p_1 (&destr, &srcr, false))
8809                 {
8810                   tree fn;
8811                   fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
8812                   if (!fn)
8813                     return NULL_TREE;
8814                   return build_call_expr_loc (loc, fn, 3, dest, src, len);
8815                 }
8816             }
8817
8818           return NULL_TREE;
8819         }
8820
8821       if (!host_integerp (len, 0))
8822         return NULL_TREE;
8823       /* FIXME:
8824          This logic lose for arguments like (type *)malloc (sizeof (type)),
8825          since we strip the casts of up to VOID return value from malloc.
8826          Perhaps we ought to inherit type from non-VOID argument here?  */
8827       STRIP_NOPS (src);
8828       STRIP_NOPS (dest);
8829       if (!POINTER_TYPE_P (TREE_TYPE (src))
8830           || !POINTER_TYPE_P (TREE_TYPE (dest)))
8831         return NULL_TREE;
8832       /* As we fold (void *)(p + CST) to (void *)p + CST undo this here.  */
8833       if (TREE_CODE (src) == POINTER_PLUS_EXPR)
8834         {
8835           tree tem = TREE_OPERAND (src, 0);
8836           STRIP_NOPS (tem);
8837           if (tem != TREE_OPERAND (src, 0))
8838             src = build1 (NOP_EXPR, TREE_TYPE (tem), src);
8839         }
8840       if (TREE_CODE (dest) == POINTER_PLUS_EXPR)
8841         {
8842           tree tem = TREE_OPERAND (dest, 0);
8843           STRIP_NOPS (tem);
8844           if (tem != TREE_OPERAND (dest, 0))
8845             dest = build1 (NOP_EXPR, TREE_TYPE (tem), dest);
8846         }
8847       srctype = TREE_TYPE (TREE_TYPE (src));
8848       if (TREE_CODE (srctype) == ARRAY_TYPE
8849           && !tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
8850         {
8851           srctype = TREE_TYPE (srctype);
8852           STRIP_NOPS (src);
8853           src = build1 (NOP_EXPR, build_pointer_type (srctype), src);
8854         }
8855       desttype = TREE_TYPE (TREE_TYPE (dest));
8856       if (TREE_CODE (desttype) == ARRAY_TYPE
8857           && !tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
8858         {
8859           desttype = TREE_TYPE (desttype);
8860           STRIP_NOPS (dest);
8861           dest = build1 (NOP_EXPR, build_pointer_type (desttype), dest);
8862         }
8863       if (TREE_ADDRESSABLE (srctype)
8864           || TREE_ADDRESSABLE (desttype))
8865         return NULL_TREE;
8866
8867       src_align = get_pointer_alignment (src);
8868       dest_align = get_pointer_alignment (dest);
8869       if (dest_align < TYPE_ALIGN (desttype)
8870           || src_align < TYPE_ALIGN (srctype))
8871         return NULL_TREE;
8872
8873       if (!ignore)
8874         dest = builtin_save_expr (dest);
8875
8876       /* Build accesses at offset zero with a ref-all character type.  */
8877       off0 = build_int_cst (build_pointer_type_for_mode (char_type_node,
8878                                                          ptr_mode, true), 0);
8879
8880       destvar = dest;
8881       STRIP_NOPS (destvar);
8882       if (TREE_CODE (destvar) == ADDR_EXPR
8883           && var_decl_component_p (TREE_OPERAND (destvar, 0))
8884           && tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
8885         destvar = fold_build2 (MEM_REF, desttype, destvar, off0);
8886       else
8887         destvar = NULL_TREE;
8888
8889       srcvar = src;
8890       STRIP_NOPS (srcvar);
8891       if (TREE_CODE (srcvar) == ADDR_EXPR
8892           && var_decl_component_p (TREE_OPERAND (srcvar, 0))
8893           && tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
8894         {
8895           if (!destvar
8896               || src_align >= TYPE_ALIGN (desttype))
8897             srcvar = fold_build2 (MEM_REF, destvar ? desttype : srctype,
8898                                   srcvar, off0);
8899           else if (!STRICT_ALIGNMENT)
8900             {
8901               srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
8902                                             src_align);
8903               srcvar = fold_build2 (MEM_REF, srctype, srcvar, off0);
8904             }
8905           else
8906             srcvar = NULL_TREE;
8907         }
8908       else
8909         srcvar = NULL_TREE;
8910
8911       if (srcvar == NULL_TREE && destvar == NULL_TREE)
8912         return NULL_TREE;
8913
8914       if (srcvar == NULL_TREE)
8915         {
8916           STRIP_NOPS (src);
8917           if (src_align >= TYPE_ALIGN (desttype))
8918             srcvar = fold_build2 (MEM_REF, desttype, src, off0);
8919           else
8920             {
8921               if (STRICT_ALIGNMENT)
8922                 return NULL_TREE;
8923               srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
8924                                             src_align);
8925               srcvar = fold_build2 (MEM_REF, srctype, src, off0);
8926             }
8927         }
8928       else if (destvar == NULL_TREE)
8929         {
8930           STRIP_NOPS (dest);
8931           if (dest_align >= TYPE_ALIGN (srctype))
8932             destvar = fold_build2 (MEM_REF, srctype, dest, off0);
8933           else
8934             {
8935               if (STRICT_ALIGNMENT)
8936                 return NULL_TREE;
8937               desttype = build_aligned_type (TYPE_MAIN_VARIANT (srctype),
8938                                              dest_align);
8939               destvar = fold_build2 (MEM_REF, desttype, dest, off0);
8940             }
8941         }
8942
8943       expr = build2 (MODIFY_EXPR, TREE_TYPE (destvar), destvar, srcvar);
8944     }
8945
8946   if (ignore)
8947     return expr;
8948
8949   if (endp == 0 || endp == 3)
8950     return omit_one_operand_loc (loc, type, dest, expr);
8951
8952   if (expr == len)
8953     expr = NULL_TREE;
8954
8955   if (endp == 2)
8956     len = fold_build2_loc (loc, MINUS_EXPR, TREE_TYPE (len), len,
8957                        ssize_int (1));
8958
8959   dest = fold_build_pointer_plus_loc (loc, dest, len);
8960   dest = fold_convert_loc (loc, type, dest);
8961   if (expr)
8962     dest = omit_one_operand_loc (loc, type, dest, expr);
8963   return dest;
8964 }
8965
8966 /* Fold function call to builtin strcpy with arguments DEST and SRC.
8967    If LEN is not NULL, it represents the length of the string to be
8968    copied.  Return NULL_TREE if no simplification can be made.  */
8969
8970 tree
8971 fold_builtin_strcpy (location_t loc, tree fndecl, tree dest, tree src, tree len)
8972 {
8973   tree fn;
8974
8975   if (!validate_arg (dest, POINTER_TYPE)
8976       || !validate_arg (src, POINTER_TYPE))
8977     return NULL_TREE;
8978
8979   /* If SRC and DEST are the same (and not volatile), return DEST.  */
8980   if (operand_equal_p (src, dest, 0))
8981     return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest);
8982
8983   if (optimize_function_for_size_p (cfun))
8984     return NULL_TREE;
8985
8986   fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
8987   if (!fn)
8988     return NULL_TREE;
8989
8990   if (!len)
8991     {
8992       len = c_strlen (src, 1);
8993       if (! len || TREE_SIDE_EFFECTS (len))
8994         return NULL_TREE;
8995     }
8996
8997   len = fold_convert_loc (loc, size_type_node, len);
8998   len = size_binop_loc (loc, PLUS_EXPR, len, build_int_cst (size_type_node, 1));
8999   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
9000                            build_call_expr_loc (loc, fn, 3, dest, src, len));
9001 }
9002
9003 /* Fold function call to builtin stpcpy with arguments DEST and SRC.
9004    Return NULL_TREE if no simplification can be made.  */
9005
9006 static tree
9007 fold_builtin_stpcpy (location_t loc, tree fndecl, tree dest, tree src)
9008 {
9009   tree fn, len, lenp1, call, type;
9010
9011   if (!validate_arg (dest, POINTER_TYPE)
9012       || !validate_arg (src, POINTER_TYPE))
9013     return NULL_TREE;
9014
9015   len = c_strlen (src, 1);
9016   if (!len
9017       || TREE_CODE (len) != INTEGER_CST)
9018     return NULL_TREE;
9019
9020   if (optimize_function_for_size_p (cfun)
9021       /* If length is zero it's small enough.  */
9022       && !integer_zerop (len))
9023     return NULL_TREE;
9024
9025   fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
9026   if (!fn)
9027     return NULL_TREE;
9028
9029   lenp1 = size_binop_loc (loc, PLUS_EXPR,
9030                           fold_convert_loc (loc, size_type_node, len),
9031                           build_int_cst (size_type_node, 1));
9032   /* We use dest twice in building our expression.  Save it from
9033      multiple expansions.  */
9034   dest = builtin_save_expr (dest);
9035   call = build_call_expr_loc (loc, fn, 3, dest, src, lenp1);
9036
9037   type = TREE_TYPE (TREE_TYPE (fndecl));
9038   dest = fold_build_pointer_plus_loc (loc, dest, len);
9039   dest = fold_convert_loc (loc, type, dest);
9040   dest = omit_one_operand_loc (loc, type, dest, call);
9041   return dest;
9042 }
9043
9044 /* Fold function call to builtin strncpy with arguments DEST, SRC, and LEN.
9045    If SLEN is not NULL, it represents the length of the source string.
9046    Return NULL_TREE if no simplification can be made.  */
9047
9048 tree
9049 fold_builtin_strncpy (location_t loc, tree fndecl, tree dest,
9050                       tree src, tree len, tree slen)
9051 {
9052   tree fn;
9053
9054   if (!validate_arg (dest, POINTER_TYPE)
9055       || !validate_arg (src, POINTER_TYPE)
9056       || !validate_arg (len, INTEGER_TYPE))
9057     return NULL_TREE;
9058
9059   /* If the LEN parameter is zero, return DEST.  */
9060   if (integer_zerop (len))
9061     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
9062
9063   /* We can't compare slen with len as constants below if len is not a
9064      constant.  */
9065   if (len == 0 || TREE_CODE (len) != INTEGER_CST)
9066     return NULL_TREE;
9067
9068   if (!slen)
9069     slen = c_strlen (src, 1);
9070
9071   /* Now, we must be passed a constant src ptr parameter.  */
9072   if (slen == 0 || TREE_CODE (slen) != INTEGER_CST)
9073     return NULL_TREE;
9074
9075   slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
9076
9077   /* We do not support simplification of this case, though we do
9078      support it when expanding trees into RTL.  */
9079   /* FIXME: generate a call to __builtin_memset.  */
9080   if (tree_int_cst_lt (slen, len))
9081     return NULL_TREE;
9082
9083   /* OK transform into builtin memcpy.  */
9084   fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
9085   if (!fn)
9086     return NULL_TREE;
9087
9088   len = fold_convert_loc (loc, size_type_node, len);
9089   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
9090                            build_call_expr_loc (loc, fn, 3, dest, src, len));
9091 }
9092
9093 /* Fold function call to builtin memchr.  ARG1, ARG2 and LEN are the
9094    arguments to the call, and TYPE is its return type.
9095    Return NULL_TREE if no simplification can be made.  */
9096
9097 static tree
9098 fold_builtin_memchr (location_t loc, tree arg1, tree arg2, tree len, tree type)
9099 {
9100   if (!validate_arg (arg1, POINTER_TYPE)
9101       || !validate_arg (arg2, INTEGER_TYPE)
9102       || !validate_arg (len, INTEGER_TYPE))
9103     return NULL_TREE;
9104   else
9105     {
9106       const char *p1;
9107
9108       if (TREE_CODE (arg2) != INTEGER_CST
9109           || !host_integerp (len, 1))
9110         return NULL_TREE;
9111
9112       p1 = c_getstr (arg1);
9113       if (p1 && compare_tree_int (len, strlen (p1) + 1) <= 0)
9114         {
9115           char c;
9116           const char *r;
9117           tree tem;
9118
9119           if (target_char_cast (arg2, &c))
9120             return NULL_TREE;
9121
9122           r = (const char *) memchr (p1, c, tree_low_cst (len, 1));
9123
9124           if (r == NULL)
9125             return build_int_cst (TREE_TYPE (arg1), 0);
9126
9127           tem = fold_build_pointer_plus_hwi_loc (loc, arg1, r - p1);
9128           return fold_convert_loc (loc, type, tem);
9129         }
9130       return NULL_TREE;
9131     }
9132 }
9133
9134 /* Fold function call to builtin memcmp with arguments ARG1 and ARG2.
9135    Return NULL_TREE if no simplification can be made.  */
9136
9137 static tree
9138 fold_builtin_memcmp (location_t loc, tree arg1, tree arg2, tree len)
9139 {
9140   const char *p1, *p2;
9141
9142   if (!validate_arg (arg1, POINTER_TYPE)
9143       || !validate_arg (arg2, POINTER_TYPE)
9144       || !validate_arg (len, INTEGER_TYPE))
9145     return NULL_TREE;
9146
9147   /* If the LEN parameter is zero, return zero.  */
9148   if (integer_zerop (len))
9149     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
9150                               arg1, arg2);
9151
9152   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
9153   if (operand_equal_p (arg1, arg2, 0))
9154     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
9155
9156   p1 = c_getstr (arg1);
9157   p2 = c_getstr (arg2);
9158
9159   /* If all arguments are constant, and the value of len is not greater
9160      than the lengths of arg1 and arg2, evaluate at compile-time.  */
9161   if (host_integerp (len, 1) && p1 && p2
9162       && compare_tree_int (len, strlen (p1) + 1) <= 0
9163       && compare_tree_int (len, strlen (p2) + 1) <= 0)
9164     {
9165       const int r = memcmp (p1, p2, tree_low_cst (len, 1));
9166
9167       if (r > 0)
9168         return integer_one_node;
9169       else if (r < 0)
9170         return integer_minus_one_node;
9171       else
9172         return integer_zero_node;
9173     }
9174
9175   /* If len parameter is one, return an expression corresponding to
9176      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
9177   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
9178     {
9179       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9180       tree cst_uchar_ptr_node
9181         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9182
9183       tree ind1
9184         = fold_convert_loc (loc, integer_type_node,
9185                             build1 (INDIRECT_REF, cst_uchar_node,
9186                                     fold_convert_loc (loc,
9187                                                       cst_uchar_ptr_node,
9188                                                       arg1)));
9189       tree ind2
9190         = fold_convert_loc (loc, integer_type_node,
9191                             build1 (INDIRECT_REF, cst_uchar_node,
9192                                     fold_convert_loc (loc,
9193                                                       cst_uchar_ptr_node,
9194                                                       arg2)));
9195       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
9196     }
9197
9198   return NULL_TREE;
9199 }
9200
9201 /* Fold function call to builtin strcmp with arguments ARG1 and ARG2.
9202    Return NULL_TREE if no simplification can be made.  */
9203
9204 static tree
9205 fold_builtin_strcmp (location_t loc, tree arg1, tree arg2)
9206 {
9207   const char *p1, *p2;
9208
9209   if (!validate_arg (arg1, POINTER_TYPE)
9210       || !validate_arg (arg2, POINTER_TYPE))
9211     return NULL_TREE;
9212
9213   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
9214   if (operand_equal_p (arg1, arg2, 0))
9215     return integer_zero_node;
9216
9217   p1 = c_getstr (arg1);
9218   p2 = c_getstr (arg2);
9219
9220   if (p1 && p2)
9221     {
9222       const int i = strcmp (p1, p2);
9223       if (i < 0)
9224         return integer_minus_one_node;
9225       else if (i > 0)
9226         return integer_one_node;
9227       else
9228         return integer_zero_node;
9229     }
9230
9231   /* If the second arg is "", return *(const unsigned char*)arg1.  */
9232   if (p2 && *p2 == '\0')
9233     {
9234       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9235       tree cst_uchar_ptr_node
9236         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9237
9238       return fold_convert_loc (loc, integer_type_node,
9239                                build1 (INDIRECT_REF, cst_uchar_node,
9240                                        fold_convert_loc (loc,
9241                                                          cst_uchar_ptr_node,
9242                                                          arg1)));
9243     }
9244
9245   /* If the first arg is "", return -*(const unsigned char*)arg2.  */
9246   if (p1 && *p1 == '\0')
9247     {
9248       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9249       tree cst_uchar_ptr_node
9250         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9251
9252       tree temp
9253         = fold_convert_loc (loc, integer_type_node,
9254                             build1 (INDIRECT_REF, cst_uchar_node,
9255                                     fold_convert_loc (loc,
9256                                                       cst_uchar_ptr_node,
9257                                                       arg2)));
9258       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
9259     }
9260
9261   return NULL_TREE;
9262 }
9263
9264 /* Fold function call to builtin strncmp with arguments ARG1, ARG2, and LEN.
9265    Return NULL_TREE if no simplification can be made.  */
9266
9267 static tree
9268 fold_builtin_strncmp (location_t loc, tree arg1, tree arg2, tree len)
9269 {
9270   const char *p1, *p2;
9271
9272   if (!validate_arg (arg1, POINTER_TYPE)
9273       || !validate_arg (arg2, POINTER_TYPE)
9274       || !validate_arg (len, INTEGER_TYPE))
9275     return NULL_TREE;
9276
9277   /* If the LEN parameter is zero, return zero.  */
9278   if (integer_zerop (len))
9279     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
9280                               arg1, arg2);
9281
9282   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
9283   if (operand_equal_p (arg1, arg2, 0))
9284     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
9285
9286   p1 = c_getstr (arg1);
9287   p2 = c_getstr (arg2);
9288
9289   if (host_integerp (len, 1) && p1 && p2)
9290     {
9291       const int i = strncmp (p1, p2, tree_low_cst (len, 1));
9292       if (i > 0)
9293         return integer_one_node;
9294       else if (i < 0)
9295         return integer_minus_one_node;
9296       else
9297         return integer_zero_node;
9298     }
9299
9300   /* If the second arg is "", and the length is greater than zero,
9301      return *(const unsigned char*)arg1.  */
9302   if (p2 && *p2 == '\0'
9303       && TREE_CODE (len) == INTEGER_CST
9304       && tree_int_cst_sgn (len) == 1)
9305     {
9306       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9307       tree cst_uchar_ptr_node
9308         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9309
9310       return fold_convert_loc (loc, integer_type_node,
9311                                build1 (INDIRECT_REF, cst_uchar_node,
9312                                        fold_convert_loc (loc,
9313                                                          cst_uchar_ptr_node,
9314                                                          arg1)));
9315     }
9316
9317   /* If the first arg is "", and the length is greater than zero,
9318      return -*(const unsigned char*)arg2.  */
9319   if (p1 && *p1 == '\0'
9320       && TREE_CODE (len) == INTEGER_CST
9321       && tree_int_cst_sgn (len) == 1)
9322     {
9323       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9324       tree cst_uchar_ptr_node
9325         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9326
9327       tree temp = fold_convert_loc (loc, integer_type_node,
9328                                     build1 (INDIRECT_REF, cst_uchar_node,
9329                                             fold_convert_loc (loc,
9330                                                               cst_uchar_ptr_node,
9331                                                               arg2)));
9332       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
9333     }
9334
9335   /* If len parameter is one, return an expression corresponding to
9336      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
9337   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
9338     {
9339       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9340       tree cst_uchar_ptr_node
9341         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9342
9343       tree ind1 = fold_convert_loc (loc, integer_type_node,
9344                                     build1 (INDIRECT_REF, cst_uchar_node,
9345                                             fold_convert_loc (loc,
9346                                                               cst_uchar_ptr_node,
9347                                                               arg1)));
9348       tree ind2 = fold_convert_loc (loc, integer_type_node,
9349                                     build1 (INDIRECT_REF, cst_uchar_node,
9350                                             fold_convert_loc (loc,
9351                                                               cst_uchar_ptr_node,
9352                                                               arg2)));
9353       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
9354     }
9355
9356   return NULL_TREE;
9357 }
9358
9359 /* Fold function call to builtin signbit, signbitf or signbitl with argument
9360    ARG.  Return NULL_TREE if no simplification can be made.  */
9361
9362 static tree
9363 fold_builtin_signbit (location_t loc, tree arg, tree type)
9364 {
9365   if (!validate_arg (arg, REAL_TYPE))
9366     return NULL_TREE;
9367
9368   /* If ARG is a compile-time constant, determine the result.  */
9369   if (TREE_CODE (arg) == REAL_CST
9370       && !TREE_OVERFLOW (arg))
9371     {
9372       REAL_VALUE_TYPE c;
9373
9374       c = TREE_REAL_CST (arg);
9375       return (REAL_VALUE_NEGATIVE (c)
9376               ? build_one_cst (type)
9377               : build_zero_cst (type));
9378     }
9379
9380   /* If ARG is non-negative, the result is always zero.  */
9381   if (tree_expr_nonnegative_p (arg))
9382     return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9383
9384   /* If ARG's format doesn't have signed zeros, return "arg < 0.0".  */
9385   if (!HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (arg))))
9386     return fold_convert (type,
9387                          fold_build2_loc (loc, LT_EXPR, boolean_type_node, arg,
9388                         build_real (TREE_TYPE (arg), dconst0)));
9389
9390   return NULL_TREE;
9391 }
9392
9393 /* Fold function call to builtin copysign, copysignf or copysignl with
9394    arguments ARG1 and ARG2.  Return NULL_TREE if no simplification can
9395    be made.  */
9396
9397 static tree
9398 fold_builtin_copysign (location_t loc, tree fndecl,
9399                        tree arg1, tree arg2, tree type)
9400 {
9401   tree tem;
9402
9403   if (!validate_arg (arg1, REAL_TYPE)
9404       || !validate_arg (arg2, REAL_TYPE))
9405     return NULL_TREE;
9406
9407   /* copysign(X,X) is X.  */
9408   if (operand_equal_p (arg1, arg2, 0))
9409     return fold_convert_loc (loc, type, arg1);
9410
9411   /* If ARG1 and ARG2 are compile-time constants, determine the result.  */
9412   if (TREE_CODE (arg1) == REAL_CST
9413       && TREE_CODE (arg2) == REAL_CST
9414       && !TREE_OVERFLOW (arg1)
9415       && !TREE_OVERFLOW (arg2))
9416     {
9417       REAL_VALUE_TYPE c1, c2;
9418
9419       c1 = TREE_REAL_CST (arg1);
9420       c2 = TREE_REAL_CST (arg2);
9421       /* c1.sign := c2.sign.  */
9422       real_copysign (&c1, &c2);
9423       return build_real (type, c1);
9424     }
9425
9426   /* copysign(X, Y) is fabs(X) when Y is always non-negative.
9427      Remember to evaluate Y for side-effects.  */
9428   if (tree_expr_nonnegative_p (arg2))
9429     return omit_one_operand_loc (loc, type,
9430                              fold_build1_loc (loc, ABS_EXPR, type, arg1),
9431                              arg2);
9432
9433   /* Strip sign changing operations for the first argument.  */
9434   tem = fold_strip_sign_ops (arg1);
9435   if (tem)
9436     return build_call_expr_loc (loc, fndecl, 2, tem, arg2);
9437
9438   return NULL_TREE;
9439 }
9440
9441 /* Fold a call to builtin isascii with argument ARG.  */
9442
9443 static tree
9444 fold_builtin_isascii (location_t loc, tree arg)
9445 {
9446   if (!validate_arg (arg, INTEGER_TYPE))
9447     return NULL_TREE;
9448   else
9449     {
9450       /* Transform isascii(c) -> ((c & ~0x7f) == 0).  */
9451       arg = fold_build2 (BIT_AND_EXPR, integer_type_node, arg,
9452                          build_int_cst (integer_type_node,
9453                                         ~ (unsigned HOST_WIDE_INT) 0x7f));
9454       return fold_build2_loc (loc, EQ_EXPR, integer_type_node,
9455                               arg, integer_zero_node);
9456     }
9457 }
9458
9459 /* Fold a call to builtin toascii with argument ARG.  */
9460
9461 static tree
9462 fold_builtin_toascii (location_t loc, tree arg)
9463 {
9464   if (!validate_arg (arg, INTEGER_TYPE))
9465     return NULL_TREE;
9466
9467   /* Transform toascii(c) -> (c & 0x7f).  */
9468   return fold_build2_loc (loc, BIT_AND_EXPR, integer_type_node, arg,
9469                           build_int_cst (integer_type_node, 0x7f));
9470 }
9471
9472 /* Fold a call to builtin isdigit with argument ARG.  */
9473
9474 static tree
9475 fold_builtin_isdigit (location_t loc, tree arg)
9476 {
9477   if (!validate_arg (arg, INTEGER_TYPE))
9478     return NULL_TREE;
9479   else
9480     {
9481       /* Transform isdigit(c) -> (unsigned)(c) - '0' <= 9.  */
9482       /* According to the C standard, isdigit is unaffected by locale.
9483          However, it definitely is affected by the target character set.  */
9484       unsigned HOST_WIDE_INT target_digit0
9485         = lang_hooks.to_target_charset ('0');
9486
9487       if (target_digit0 == 0)
9488         return NULL_TREE;
9489
9490       arg = fold_convert_loc (loc, unsigned_type_node, arg);
9491       arg = fold_build2 (MINUS_EXPR, unsigned_type_node, arg,
9492                          build_int_cst (unsigned_type_node, target_digit0));
9493       return fold_build2_loc (loc, LE_EXPR, integer_type_node, arg,
9494                           build_int_cst (unsigned_type_node, 9));
9495     }
9496 }
9497
9498 /* Fold a call to fabs, fabsf or fabsl with argument ARG.  */
9499
9500 static tree
9501 fold_builtin_fabs (location_t loc, tree arg, tree type)
9502 {
9503   if (!validate_arg (arg, REAL_TYPE))
9504     return NULL_TREE;
9505
9506   arg = fold_convert_loc (loc, type, arg);
9507   if (TREE_CODE (arg) == REAL_CST)
9508     return fold_abs_const (arg, type);
9509   return fold_build1_loc (loc, ABS_EXPR, type, arg);
9510 }
9511
9512 /* Fold a call to abs, labs, llabs or imaxabs with argument ARG.  */
9513
9514 static tree
9515 fold_builtin_abs (location_t loc, tree arg, tree type)
9516 {
9517   if (!validate_arg (arg, INTEGER_TYPE))
9518     return NULL_TREE;
9519
9520   arg = fold_convert_loc (loc, type, arg);
9521   if (TREE_CODE (arg) == INTEGER_CST)
9522     return fold_abs_const (arg, type);
9523   return fold_build1_loc (loc, ABS_EXPR, type, arg);
9524 }
9525
9526 /* Fold a fma operation with arguments ARG[012].  */
9527
9528 tree
9529 fold_fma (location_t loc ATTRIBUTE_UNUSED,
9530           tree type, tree arg0, tree arg1, tree arg2)
9531 {
9532   if (TREE_CODE (arg0) == REAL_CST
9533       && TREE_CODE (arg1) == REAL_CST
9534       && TREE_CODE (arg2) == REAL_CST)
9535     return do_mpfr_arg3 (arg0, arg1, arg2, type, mpfr_fma);
9536
9537   return NULL_TREE;
9538 }
9539
9540 /* Fold a call to fma, fmaf, or fmal with arguments ARG[012].  */
9541
9542 static tree
9543 fold_builtin_fma (location_t loc, tree arg0, tree arg1, tree arg2, tree type)
9544 {
9545   if (validate_arg (arg0, REAL_TYPE)
9546       && validate_arg (arg1, REAL_TYPE)
9547       && validate_arg (arg2, REAL_TYPE))
9548     {
9549       tree tem = fold_fma (loc, type, arg0, arg1, arg2);
9550       if (tem)
9551         return tem;
9552
9553       /* ??? Only expand to FMA_EXPR if it's directly supported.  */
9554       if (optab_handler (fma_optab, TYPE_MODE (type)) != CODE_FOR_nothing)
9555         return fold_build3_loc (loc, FMA_EXPR, type, arg0, arg1, arg2);
9556     }
9557   return NULL_TREE;
9558 }
9559
9560 /* Fold a call to builtin fmin or fmax.  */
9561
9562 static tree
9563 fold_builtin_fmin_fmax (location_t loc, tree arg0, tree arg1,
9564                         tree type, bool max)
9565 {
9566   if (validate_arg (arg0, REAL_TYPE) && validate_arg (arg1, REAL_TYPE))
9567     {
9568       /* Calculate the result when the argument is a constant.  */
9569       tree res = do_mpfr_arg2 (arg0, arg1, type, (max ? mpfr_max : mpfr_min));
9570
9571       if (res)
9572         return res;
9573
9574       /* If either argument is NaN, return the other one.  Avoid the
9575          transformation if we get (and honor) a signalling NaN.  Using
9576          omit_one_operand() ensures we create a non-lvalue.  */
9577       if (TREE_CODE (arg0) == REAL_CST
9578           && real_isnan (&TREE_REAL_CST (arg0))
9579           && (! HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg0)))
9580               || ! TREE_REAL_CST (arg0).signalling))
9581         return omit_one_operand_loc (loc, type, arg1, arg0);
9582       if (TREE_CODE (arg1) == REAL_CST
9583           && real_isnan (&TREE_REAL_CST (arg1))
9584           && (! HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg1)))
9585               || ! TREE_REAL_CST (arg1).signalling))
9586         return omit_one_operand_loc (loc, type, arg0, arg1);
9587
9588       /* Transform fmin/fmax(x,x) -> x.  */
9589       if (operand_equal_p (arg0, arg1, OEP_PURE_SAME))
9590         return omit_one_operand_loc (loc, type, arg0, arg1);
9591
9592       /* Convert fmin/fmax to MIN_EXPR/MAX_EXPR.  C99 requires these
9593          functions to return the numeric arg if the other one is NaN.
9594          These tree codes don't honor that, so only transform if
9595          -ffinite-math-only is set.  C99 doesn't require -0.0 to be
9596          handled, so we don't have to worry about it either.  */
9597       if (flag_finite_math_only)
9598         return fold_build2_loc (loc, (max ? MAX_EXPR : MIN_EXPR), type,
9599                             fold_convert_loc (loc, type, arg0),
9600                             fold_convert_loc (loc, type, arg1));
9601     }
9602   return NULL_TREE;
9603 }
9604
9605 /* Fold a call to builtin carg(a+bi) -> atan2(b,a).  */
9606
9607 static tree
9608 fold_builtin_carg (location_t loc, tree arg, tree type)
9609 {
9610   if (validate_arg (arg, COMPLEX_TYPE)
9611       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE)
9612     {
9613       tree atan2_fn = mathfn_built_in (type, BUILT_IN_ATAN2);
9614
9615       if (atan2_fn)
9616         {
9617           tree new_arg = builtin_save_expr (arg);
9618           tree r_arg = fold_build1_loc (loc, REALPART_EXPR, type, new_arg);
9619           tree i_arg = fold_build1_loc (loc, IMAGPART_EXPR, type, new_arg);
9620           return build_call_expr_loc (loc, atan2_fn, 2, i_arg, r_arg);
9621         }
9622     }
9623
9624   return NULL_TREE;
9625 }
9626
9627 /* Fold a call to builtin logb/ilogb.  */
9628
9629 static tree
9630 fold_builtin_logb (location_t loc, tree arg, tree rettype)
9631 {
9632   if (! validate_arg (arg, REAL_TYPE))
9633     return NULL_TREE;
9634
9635   STRIP_NOPS (arg);
9636
9637   if (TREE_CODE (arg) == REAL_CST && ! TREE_OVERFLOW (arg))
9638     {
9639       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg);
9640
9641       switch (value->cl)
9642       {
9643       case rvc_nan:
9644       case rvc_inf:
9645         /* If arg is Inf or NaN and we're logb, return it.  */
9646         if (TREE_CODE (rettype) == REAL_TYPE)
9647           {
9648             /* For logb(-Inf) we have to return +Inf.  */
9649             if (real_isinf (value) && real_isneg (value))
9650               {
9651                 REAL_VALUE_TYPE tem;
9652                 real_inf (&tem);
9653                 return build_real (rettype, tem);
9654               }
9655             return fold_convert_loc (loc, rettype, arg);
9656           }
9657         /* Fall through... */
9658       case rvc_zero:
9659         /* Zero may set errno and/or raise an exception for logb, also
9660            for ilogb we don't know FP_ILOGB0.  */
9661         return NULL_TREE;
9662       case rvc_normal:
9663         /* For normal numbers, proceed iff radix == 2.  In GCC,
9664            normalized significands are in the range [0.5, 1.0).  We
9665            want the exponent as if they were [1.0, 2.0) so get the
9666            exponent and subtract 1.  */
9667         if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->b == 2)
9668           return fold_convert_loc (loc, rettype,
9669                                    build_int_cst (integer_type_node,
9670                                                   REAL_EXP (value)-1));
9671         break;
9672       }
9673     }
9674
9675   return NULL_TREE;
9676 }
9677
9678 /* Fold a call to builtin significand, if radix == 2.  */
9679
9680 static tree
9681 fold_builtin_significand (location_t loc, tree arg, tree rettype)
9682 {
9683   if (! validate_arg (arg, REAL_TYPE))
9684     return NULL_TREE;
9685
9686   STRIP_NOPS (arg);
9687
9688   if (TREE_CODE (arg) == REAL_CST && ! TREE_OVERFLOW (arg))
9689     {
9690       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg);
9691
9692       switch (value->cl)
9693       {
9694       case rvc_zero:
9695       case rvc_nan:
9696       case rvc_inf:
9697         /* If arg is +-0, +-Inf or +-NaN, then return it.  */
9698         return fold_convert_loc (loc, rettype, arg);
9699       case rvc_normal:
9700         /* For normal numbers, proceed iff radix == 2.  */
9701         if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->b == 2)
9702           {
9703             REAL_VALUE_TYPE result = *value;
9704             /* In GCC, normalized significands are in the range [0.5,
9705                1.0).  We want them to be [1.0, 2.0) so set the
9706                exponent to 1.  */
9707             SET_REAL_EXP (&result, 1);
9708             return build_real (rettype, result);
9709           }
9710         break;
9711       }
9712     }
9713
9714   return NULL_TREE;
9715 }
9716
9717 /* Fold a call to builtin frexp, we can assume the base is 2.  */
9718
9719 static tree
9720 fold_builtin_frexp (location_t loc, tree arg0, tree arg1, tree rettype)
9721 {
9722   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
9723     return NULL_TREE;
9724
9725   STRIP_NOPS (arg0);
9726
9727   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
9728     return NULL_TREE;
9729
9730   arg1 = build_fold_indirect_ref_loc (loc, arg1);
9731
9732   /* Proceed if a valid pointer type was passed in.  */
9733   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == integer_type_node)
9734     {
9735       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
9736       tree frac, exp;
9737
9738       switch (value->cl)
9739       {
9740       case rvc_zero:
9741         /* For +-0, return (*exp = 0, +-0).  */
9742         exp = integer_zero_node;
9743         frac = arg0;
9744         break;
9745       case rvc_nan:
9746       case rvc_inf:
9747         /* For +-NaN or +-Inf, *exp is unspecified, return arg0.  */
9748         return omit_one_operand_loc (loc, rettype, arg0, arg1);
9749       case rvc_normal:
9750         {
9751           /* Since the frexp function always expects base 2, and in
9752              GCC normalized significands are already in the range
9753              [0.5, 1.0), we have exactly what frexp wants.  */
9754           REAL_VALUE_TYPE frac_rvt = *value;
9755           SET_REAL_EXP (&frac_rvt, 0);
9756           frac = build_real (rettype, frac_rvt);
9757           exp = build_int_cst (integer_type_node, REAL_EXP (value));
9758         }
9759         break;
9760       default:
9761         gcc_unreachable ();
9762       }
9763
9764       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
9765       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1, exp);
9766       TREE_SIDE_EFFECTS (arg1) = 1;
9767       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1, frac);
9768     }
9769
9770   return NULL_TREE;
9771 }
9772
9773 /* Fold a call to builtin ldexp or scalbn/scalbln.  If LDEXP is true
9774    then we can assume the base is two.  If it's false, then we have to
9775    check the mode of the TYPE parameter in certain cases.  */
9776
9777 static tree
9778 fold_builtin_load_exponent (location_t loc, tree arg0, tree arg1,
9779                             tree type, bool ldexp)
9780 {
9781   if (validate_arg (arg0, REAL_TYPE) && validate_arg (arg1, INTEGER_TYPE))
9782     {
9783       STRIP_NOPS (arg0);
9784       STRIP_NOPS (arg1);
9785
9786       /* If arg0 is 0, Inf or NaN, or if arg1 is 0, then return arg0.  */
9787       if (real_zerop (arg0) || integer_zerop (arg1)
9788           || (TREE_CODE (arg0) == REAL_CST
9789               && !real_isfinite (&TREE_REAL_CST (arg0))))
9790         return omit_one_operand_loc (loc, type, arg0, arg1);
9791
9792       /* If both arguments are constant, then try to evaluate it.  */
9793       if ((ldexp || REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2)
9794           && TREE_CODE (arg0) == REAL_CST && !TREE_OVERFLOW (arg0)
9795           && host_integerp (arg1, 0))
9796         {
9797           /* Bound the maximum adjustment to twice the range of the
9798              mode's valid exponents.  Use abs to ensure the range is
9799              positive as a sanity check.  */
9800           const long max_exp_adj = 2 *
9801             labs (REAL_MODE_FORMAT (TYPE_MODE (type))->emax
9802                  - REAL_MODE_FORMAT (TYPE_MODE (type))->emin);
9803
9804           /* Get the user-requested adjustment.  */
9805           const HOST_WIDE_INT req_exp_adj = tree_low_cst (arg1, 0);
9806
9807           /* The requested adjustment must be inside this range.  This
9808              is a preliminary cap to avoid things like overflow, we
9809              may still fail to compute the result for other reasons.  */
9810           if (-max_exp_adj < req_exp_adj && req_exp_adj < max_exp_adj)
9811             {
9812               REAL_VALUE_TYPE initial_result;
9813
9814               real_ldexp (&initial_result, &TREE_REAL_CST (arg0), req_exp_adj);
9815
9816               /* Ensure we didn't overflow.  */
9817               if (! real_isinf (&initial_result))
9818                 {
9819                   const REAL_VALUE_TYPE trunc_result
9820                     = real_value_truncate (TYPE_MODE (type), initial_result);
9821
9822                   /* Only proceed if the target mode can hold the
9823                      resulting value.  */
9824                   if (REAL_VALUES_EQUAL (initial_result, trunc_result))
9825                     return build_real (type, trunc_result);
9826                 }
9827             }
9828         }
9829     }
9830
9831   return NULL_TREE;
9832 }
9833
9834 /* Fold a call to builtin modf.  */
9835
9836 static tree
9837 fold_builtin_modf (location_t loc, tree arg0, tree arg1, tree rettype)
9838 {
9839   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
9840     return NULL_TREE;
9841
9842   STRIP_NOPS (arg0);
9843
9844   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
9845     return NULL_TREE;
9846
9847   arg1 = build_fold_indirect_ref_loc (loc, arg1);
9848
9849   /* Proceed if a valid pointer type was passed in.  */
9850   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == TYPE_MAIN_VARIANT (rettype))
9851     {
9852       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
9853       REAL_VALUE_TYPE trunc, frac;
9854
9855       switch (value->cl)
9856       {
9857       case rvc_nan:
9858       case rvc_zero:
9859         /* For +-NaN or +-0, return (*arg1 = arg0, arg0).  */
9860         trunc = frac = *value;
9861         break;
9862       case rvc_inf:
9863         /* For +-Inf, return (*arg1 = arg0, +-0).  */
9864         frac = dconst0;
9865         frac.sign = value->sign;
9866         trunc = *value;
9867         break;
9868       case rvc_normal:
9869         /* Return (*arg1 = trunc(arg0), arg0-trunc(arg0)).  */
9870         real_trunc (&trunc, VOIDmode, value);
9871         real_arithmetic (&frac, MINUS_EXPR, value, &trunc);
9872         /* If the original number was negative and already
9873            integral, then the fractional part is -0.0.  */
9874         if (value->sign && frac.cl == rvc_zero)
9875           frac.sign = value->sign;
9876         break;
9877       }
9878
9879       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
9880       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1,
9881                           build_real (rettype, trunc));
9882       TREE_SIDE_EFFECTS (arg1) = 1;
9883       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1,
9884                           build_real (rettype, frac));
9885     }
9886
9887   return NULL_TREE;
9888 }
9889
9890 /* Given a location LOC, an interclass builtin function decl FNDECL
9891    and its single argument ARG, return an folded expression computing
9892    the same, or NULL_TREE if we either couldn't or didn't want to fold
9893    (the latter happen if there's an RTL instruction available).  */
9894
9895 static tree
9896 fold_builtin_interclass_mathfn (location_t loc, tree fndecl, tree arg)
9897 {
9898   enum machine_mode mode;
9899
9900   if (!validate_arg (arg, REAL_TYPE))
9901     return NULL_TREE;
9902
9903   if (interclass_mathfn_icode (arg, fndecl) != CODE_FOR_nothing)
9904     return NULL_TREE;
9905
9906   mode = TYPE_MODE (TREE_TYPE (arg));
9907
9908   /* If there is no optab, try generic code.  */
9909   switch (DECL_FUNCTION_CODE (fndecl))
9910     {
9911       tree result;
9912
9913     CASE_FLT_FN (BUILT_IN_ISINF):
9914       {
9915         /* isinf(x) -> isgreater(fabs(x),DBL_MAX).  */
9916         tree const isgr_fn = builtin_decl_explicit (BUILT_IN_ISGREATER);
9917         tree const type = TREE_TYPE (arg);
9918         REAL_VALUE_TYPE r;
9919         char buf[128];
9920
9921         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9922         real_from_string (&r, buf);
9923         result = build_call_expr (isgr_fn, 2,
9924                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9925                                   build_real (type, r));
9926         return result;
9927       }
9928     CASE_FLT_FN (BUILT_IN_FINITE):
9929     case BUILT_IN_ISFINITE:
9930       {
9931         /* isfinite(x) -> islessequal(fabs(x),DBL_MAX).  */
9932         tree const isle_fn = builtin_decl_explicit (BUILT_IN_ISLESSEQUAL);
9933         tree const type = TREE_TYPE (arg);
9934         REAL_VALUE_TYPE r;
9935         char buf[128];
9936
9937         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9938         real_from_string (&r, buf);
9939         result = build_call_expr (isle_fn, 2,
9940                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9941                                   build_real (type, r));
9942         /*result = fold_build2_loc (loc, UNGT_EXPR,
9943                                   TREE_TYPE (TREE_TYPE (fndecl)),
9944                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9945                                   build_real (type, r));
9946         result = fold_build1_loc (loc, TRUTH_NOT_EXPR,
9947                                   TREE_TYPE (TREE_TYPE (fndecl)),
9948                                   result);*/
9949         return result;
9950       }
9951     case BUILT_IN_ISNORMAL:
9952       {
9953         /* isnormal(x) -> isgreaterequal(fabs(x),DBL_MIN) &
9954            islessequal(fabs(x),DBL_MAX).  */
9955         tree const isle_fn = builtin_decl_explicit (BUILT_IN_ISLESSEQUAL);
9956         tree const isge_fn = builtin_decl_explicit (BUILT_IN_ISGREATEREQUAL);
9957         tree const type = TREE_TYPE (arg);
9958         REAL_VALUE_TYPE rmax, rmin;
9959         char buf[128];
9960
9961         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9962         real_from_string (&rmax, buf);
9963         sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (mode)->emin - 1);
9964         real_from_string (&rmin, buf);
9965         arg = builtin_save_expr (fold_build1_loc (loc, ABS_EXPR, type, arg));
9966         result = build_call_expr (isle_fn, 2, arg,
9967                                   build_real (type, rmax));
9968         result = fold_build2 (BIT_AND_EXPR, integer_type_node, result,
9969                               build_call_expr (isge_fn, 2, arg,
9970                                                build_real (type, rmin)));
9971         return result;
9972       }
9973     default:
9974       break;
9975     }
9976
9977   return NULL_TREE;
9978 }
9979
9980 /* Fold a call to __builtin_isnan(), __builtin_isinf, __builtin_finite.
9981    ARG is the argument for the call.  */
9982
9983 static tree
9984 fold_builtin_classify (location_t loc, tree fndecl, tree arg, int builtin_index)
9985 {
9986   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9987   REAL_VALUE_TYPE r;
9988
9989   if (!validate_arg (arg, REAL_TYPE))
9990     return NULL_TREE;
9991
9992   switch (builtin_index)
9993     {
9994     case BUILT_IN_ISINF:
9995       if (!HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
9996         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9997
9998       if (TREE_CODE (arg) == REAL_CST)
9999         {
10000           r = TREE_REAL_CST (arg);
10001           if (real_isinf (&r))
10002             return real_compare (GT_EXPR, &r, &dconst0)
10003                    ? integer_one_node : integer_minus_one_node;
10004           else
10005             return integer_zero_node;
10006         }
10007
10008       return NULL_TREE;
10009
10010     case BUILT_IN_ISINF_SIGN:
10011       {
10012         /* isinf_sign(x) -> isinf(x) ? (signbit(x) ? -1 : 1) : 0 */
10013         /* In a boolean context, GCC will fold the inner COND_EXPR to
10014            1.  So e.g. "if (isinf_sign(x))" would be folded to just
10015            "if (isinf(x) ? 1 : 0)" which becomes "if (isinf(x))". */
10016         tree signbit_fn = mathfn_built_in_1 (TREE_TYPE (arg), BUILT_IN_SIGNBIT, 0);
10017         tree isinf_fn = builtin_decl_explicit (BUILT_IN_ISINF);
10018         tree tmp = NULL_TREE;
10019
10020         arg = builtin_save_expr (arg);
10021
10022         if (signbit_fn && isinf_fn)
10023           {
10024             tree signbit_call = build_call_expr_loc (loc, signbit_fn, 1, arg);
10025             tree isinf_call = build_call_expr_loc (loc, isinf_fn, 1, arg);
10026
10027             signbit_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
10028                                         signbit_call, integer_zero_node);
10029             isinf_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
10030                                       isinf_call, integer_zero_node);
10031
10032             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node, signbit_call,
10033                                integer_minus_one_node, integer_one_node);
10034             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node,
10035                                isinf_call, tmp,
10036                                integer_zero_node);
10037           }
10038
10039         return tmp;
10040       }
10041
10042     case BUILT_IN_ISFINITE:
10043       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg)))
10044           && !HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
10045         return omit_one_operand_loc (loc, type, integer_one_node, arg);
10046
10047       if (TREE_CODE (arg) == REAL_CST)
10048         {
10049           r = TREE_REAL_CST (arg);
10050           return real_isfinite (&r) ? integer_one_node : integer_zero_node;
10051         }
10052
10053       return NULL_TREE;
10054
10055     case BUILT_IN_ISNAN:
10056       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg))))
10057         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
10058
10059       if (TREE_CODE (arg) == REAL_CST)
10060         {
10061           r = TREE_REAL_CST (arg);
10062           return real_isnan (&r) ? integer_one_node : integer_zero_node;
10063         }
10064
10065       arg = builtin_save_expr (arg);
10066       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg, arg);
10067
10068     default:
10069       gcc_unreachable ();
10070     }
10071 }
10072
10073 /* Fold a call to __builtin_fpclassify(int, int, int, int, int, ...).
10074    This builtin will generate code to return the appropriate floating
10075    point classification depending on the value of the floating point
10076    number passed in.  The possible return values must be supplied as
10077    int arguments to the call in the following order: FP_NAN, FP_INFINITE,
10078    FP_NORMAL, FP_SUBNORMAL and FP_ZERO.  The ellipses is for exactly
10079    one floating point argument which is "type generic".  */
10080
10081 static tree
10082 fold_builtin_fpclassify (location_t loc, tree exp)
10083 {
10084   tree fp_nan, fp_infinite, fp_normal, fp_subnormal, fp_zero,
10085     arg, type, res, tmp;
10086   enum machine_mode mode;
10087   REAL_VALUE_TYPE r;
10088   char buf[128];
10089
10090   /* Verify the required arguments in the original call.  */
10091   if (!validate_arglist (exp, INTEGER_TYPE, INTEGER_TYPE,
10092                          INTEGER_TYPE, INTEGER_TYPE,
10093                          INTEGER_TYPE, REAL_TYPE, VOID_TYPE))
10094     return NULL_TREE;
10095
10096   fp_nan = CALL_EXPR_ARG (exp, 0);
10097   fp_infinite = CALL_EXPR_ARG (exp, 1);
10098   fp_normal = CALL_EXPR_ARG (exp, 2);
10099   fp_subnormal = CALL_EXPR_ARG (exp, 3);
10100   fp_zero = CALL_EXPR_ARG (exp, 4);
10101   arg = CALL_EXPR_ARG (exp, 5);
10102   type = TREE_TYPE (arg);
10103   mode = TYPE_MODE (type);
10104   arg = builtin_save_expr (fold_build1_loc (loc, ABS_EXPR, type, arg));
10105
10106   /* fpclassify(x) ->
10107        isnan(x) ? FP_NAN :
10108          (fabs(x) == Inf ? FP_INFINITE :
10109            (fabs(x) >= DBL_MIN ? FP_NORMAL :
10110              (x == 0 ? FP_ZERO : FP_SUBNORMAL))).  */
10111
10112   tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
10113                      build_real (type, dconst0));
10114   res = fold_build3_loc (loc, COND_EXPR, integer_type_node,
10115                      tmp, fp_zero, fp_subnormal);
10116
10117   sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (mode)->emin - 1);
10118   real_from_string (&r, buf);
10119   tmp = fold_build2_loc (loc, GE_EXPR, integer_type_node,
10120                      arg, build_real (type, r));
10121   res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, fp_normal, res);
10122
10123   if (HONOR_INFINITIES (mode))
10124     {
10125       real_inf (&r);
10126       tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
10127                          build_real (type, r));
10128       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp,
10129                          fp_infinite, res);
10130     }
10131
10132   if (HONOR_NANS (mode))
10133     {
10134       tmp = fold_build2_loc (loc, ORDERED_EXPR, integer_type_node, arg, arg);
10135       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, res, fp_nan);
10136     }
10137
10138   return res;
10139 }
10140
10141 /* Fold a call to an unordered comparison function such as
10142    __builtin_isgreater().  FNDECL is the FUNCTION_DECL for the function
10143    being called and ARG0 and ARG1 are the arguments for the call.
10144    UNORDERED_CODE and ORDERED_CODE are comparison codes that give
10145    the opposite of the desired result.  UNORDERED_CODE is used
10146    for modes that can hold NaNs and ORDERED_CODE is used for
10147    the rest.  */
10148
10149 static tree
10150 fold_builtin_unordered_cmp (location_t loc, tree fndecl, tree arg0, tree arg1,
10151                             enum tree_code unordered_code,
10152                             enum tree_code ordered_code)
10153 {
10154   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10155   enum tree_code code;
10156   tree type0, type1;
10157   enum tree_code code0, code1;
10158   tree cmp_type = NULL_TREE;
10159
10160   type0 = TREE_TYPE (arg0);
10161   type1 = TREE_TYPE (arg1);
10162
10163   code0 = TREE_CODE (type0);
10164   code1 = TREE_CODE (type1);
10165
10166   if (code0 == REAL_TYPE && code1 == REAL_TYPE)
10167     /* Choose the wider of two real types.  */
10168     cmp_type = TYPE_PRECISION (type0) >= TYPE_PRECISION (type1)
10169       ? type0 : type1;
10170   else if (code0 == REAL_TYPE && code1 == INTEGER_TYPE)
10171     cmp_type = type0;
10172   else if (code0 == INTEGER_TYPE && code1 == REAL_TYPE)
10173     cmp_type = type1;
10174
10175   arg0 = fold_convert_loc (loc, cmp_type, arg0);
10176   arg1 = fold_convert_loc (loc, cmp_type, arg1);
10177
10178   if (unordered_code == UNORDERED_EXPR)
10179     {
10180       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))))
10181         return omit_two_operands_loc (loc, type, integer_zero_node, arg0, arg1);
10182       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg0, arg1);
10183     }
10184
10185   code = HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))) ? unordered_code
10186                                                    : ordered_code;
10187   return fold_build1_loc (loc, TRUTH_NOT_EXPR, type,
10188                       fold_build2_loc (loc, code, type, arg0, arg1));
10189 }
10190
10191 /* Fold a call to built-in function FNDECL with 0 arguments.
10192    IGNORE is true if the result of the function call is ignored.  This
10193    function returns NULL_TREE if no simplification was possible.  */
10194
10195 static tree
10196 fold_builtin_0 (location_t loc, tree fndecl, bool ignore ATTRIBUTE_UNUSED)
10197 {
10198   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10199   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10200   switch (fcode)
10201     {
10202     CASE_FLT_FN (BUILT_IN_INF):
10203     case BUILT_IN_INFD32:
10204     case BUILT_IN_INFD64:
10205     case BUILT_IN_INFD128:
10206       return fold_builtin_inf (loc, type, true);
10207
10208     CASE_FLT_FN (BUILT_IN_HUGE_VAL):
10209       return fold_builtin_inf (loc, type, false);
10210
10211     case BUILT_IN_CLASSIFY_TYPE:
10212       return fold_builtin_classify_type (NULL_TREE);
10213
10214     case BUILT_IN_UNREACHABLE:
10215       if (flag_sanitize & SANITIZE_UNREACHABLE
10216           && (current_function_decl == NULL
10217               || !lookup_attribute ("no_sanitize_undefined",
10218                                     DECL_ATTRIBUTES (current_function_decl))))
10219         return ubsan_instrument_unreachable (loc);
10220       break;
10221
10222     default:
10223       break;
10224     }
10225   return NULL_TREE;
10226 }
10227
10228 /* Fold a call to built-in function FNDECL with 1 argument, ARG0.
10229    IGNORE is true if the result of the function call is ignored.  This
10230    function returns NULL_TREE if no simplification was possible.  */
10231
10232 static tree
10233 fold_builtin_1 (location_t loc, tree fndecl, tree arg0, bool ignore)
10234 {
10235   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10236   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10237   switch (fcode)
10238     {
10239     case BUILT_IN_CONSTANT_P:
10240       {
10241         tree val = fold_builtin_constant_p (arg0);
10242
10243         /* Gimplification will pull the CALL_EXPR for the builtin out of
10244            an if condition.  When not optimizing, we'll not CSE it back.
10245            To avoid link error types of regressions, return false now.  */
10246         if (!val && !optimize)
10247           val = integer_zero_node;
10248
10249         return val;
10250       }
10251
10252     case BUILT_IN_CLASSIFY_TYPE:
10253       return fold_builtin_classify_type (arg0);
10254
10255     case BUILT_IN_STRLEN:
10256       return fold_builtin_strlen (loc, type, arg0);
10257
10258     CASE_FLT_FN (BUILT_IN_FABS):
10259     case BUILT_IN_FABSD32:
10260     case BUILT_IN_FABSD64:
10261     case BUILT_IN_FABSD128:
10262       return fold_builtin_fabs (loc, arg0, type);
10263
10264     case BUILT_IN_ABS:
10265     case BUILT_IN_LABS:
10266     case BUILT_IN_LLABS:
10267     case BUILT_IN_IMAXABS:
10268       return fold_builtin_abs (loc, arg0, type);
10269
10270     CASE_FLT_FN (BUILT_IN_CONJ):
10271       if (validate_arg (arg0, COMPLEX_TYPE)
10272         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10273         return fold_build1_loc (loc, CONJ_EXPR, type, arg0);
10274     break;
10275
10276     CASE_FLT_FN (BUILT_IN_CREAL):
10277       if (validate_arg (arg0, COMPLEX_TYPE)
10278         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10279         return non_lvalue_loc (loc, fold_build1_loc (loc, REALPART_EXPR, type, arg0));;
10280     break;
10281
10282     CASE_FLT_FN (BUILT_IN_CIMAG):
10283       if (validate_arg (arg0, COMPLEX_TYPE)
10284           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10285         return non_lvalue_loc (loc, fold_build1_loc (loc, IMAGPART_EXPR, type, arg0));
10286     break;
10287
10288     CASE_FLT_FN (BUILT_IN_CCOS):
10289       return fold_builtin_ccos (loc, arg0, type, fndecl, /*hyper=*/ false);
10290
10291     CASE_FLT_FN (BUILT_IN_CCOSH):
10292       return fold_builtin_ccos (loc, arg0, type, fndecl, /*hyper=*/ true);
10293
10294     CASE_FLT_FN (BUILT_IN_CPROJ):
10295       return fold_builtin_cproj (loc, arg0, type);
10296
10297     CASE_FLT_FN (BUILT_IN_CSIN):
10298       if (validate_arg (arg0, COMPLEX_TYPE)
10299           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10300         return do_mpc_arg1 (arg0, type, mpc_sin);
10301     break;
10302
10303     CASE_FLT_FN (BUILT_IN_CSINH):
10304       if (validate_arg (arg0, COMPLEX_TYPE)
10305           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10306         return do_mpc_arg1 (arg0, type, mpc_sinh);
10307     break;
10308
10309     CASE_FLT_FN (BUILT_IN_CTAN):
10310       if (validate_arg (arg0, COMPLEX_TYPE)
10311           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10312         return do_mpc_arg1 (arg0, type, mpc_tan);
10313     break;
10314
10315     CASE_FLT_FN (BUILT_IN_CTANH):
10316       if (validate_arg (arg0, COMPLEX_TYPE)
10317           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10318         return do_mpc_arg1 (arg0, type, mpc_tanh);
10319     break;
10320
10321     CASE_FLT_FN (BUILT_IN_CLOG):
10322       if (validate_arg (arg0, COMPLEX_TYPE)
10323           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10324         return do_mpc_arg1 (arg0, type, mpc_log);
10325     break;
10326
10327     CASE_FLT_FN (BUILT_IN_CSQRT):
10328       if (validate_arg (arg0, COMPLEX_TYPE)
10329           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10330         return do_mpc_arg1 (arg0, type, mpc_sqrt);
10331     break;
10332
10333     CASE_FLT_FN (BUILT_IN_CASIN):
10334       if (validate_arg (arg0, COMPLEX_TYPE)
10335           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10336         return do_mpc_arg1 (arg0, type, mpc_asin);
10337     break;
10338
10339     CASE_FLT_FN (BUILT_IN_CACOS):
10340       if (validate_arg (arg0, COMPLEX_TYPE)
10341           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10342         return do_mpc_arg1 (arg0, type, mpc_acos);
10343     break;
10344
10345     CASE_FLT_FN (BUILT_IN_CATAN):
10346       if (validate_arg (arg0, COMPLEX_TYPE)
10347           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10348         return do_mpc_arg1 (arg0, type, mpc_atan);
10349     break;
10350
10351     CASE_FLT_FN (BUILT_IN_CASINH):
10352       if (validate_arg (arg0, COMPLEX_TYPE)
10353           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10354         return do_mpc_arg1 (arg0, type, mpc_asinh);
10355     break;
10356
10357     CASE_FLT_FN (BUILT_IN_CACOSH):
10358       if (validate_arg (arg0, COMPLEX_TYPE)
10359           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10360         return do_mpc_arg1 (arg0, type, mpc_acosh);
10361     break;
10362
10363     CASE_FLT_FN (BUILT_IN_CATANH):
10364       if (validate_arg (arg0, COMPLEX_TYPE)
10365           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10366         return do_mpc_arg1 (arg0, type, mpc_atanh);
10367     break;
10368
10369     CASE_FLT_FN (BUILT_IN_CABS):
10370       return fold_builtin_cabs (loc, arg0, type, fndecl);
10371
10372     CASE_FLT_FN (BUILT_IN_CARG):
10373       return fold_builtin_carg (loc, arg0, type);
10374
10375     CASE_FLT_FN (BUILT_IN_SQRT):
10376       return fold_builtin_sqrt (loc, arg0, type);
10377
10378     CASE_FLT_FN (BUILT_IN_CBRT):
10379       return fold_builtin_cbrt (loc, arg0, type);
10380
10381     CASE_FLT_FN (BUILT_IN_ASIN):
10382       if (validate_arg (arg0, REAL_TYPE))
10383         return do_mpfr_arg1 (arg0, type, mpfr_asin,
10384                              &dconstm1, &dconst1, true);
10385     break;
10386
10387     CASE_FLT_FN (BUILT_IN_ACOS):
10388       if (validate_arg (arg0, REAL_TYPE))
10389         return do_mpfr_arg1 (arg0, type, mpfr_acos,
10390                              &dconstm1, &dconst1, true);
10391     break;
10392
10393     CASE_FLT_FN (BUILT_IN_ATAN):
10394       if (validate_arg (arg0, REAL_TYPE))
10395         return do_mpfr_arg1 (arg0, type, mpfr_atan, NULL, NULL, 0);
10396     break;
10397
10398     CASE_FLT_FN (BUILT_IN_ASINH):
10399       if (validate_arg (arg0, REAL_TYPE))
10400         return do_mpfr_arg1 (arg0, type, mpfr_asinh, NULL, NULL, 0);
10401     break;
10402
10403     CASE_FLT_FN (BUILT_IN_ACOSH):
10404       if (validate_arg (arg0, REAL_TYPE))
10405         return do_mpfr_arg1 (arg0, type, mpfr_acosh,
10406                              &dconst1, NULL, true);
10407     break;
10408
10409     CASE_FLT_FN (BUILT_IN_ATANH):
10410       if (validate_arg (arg0, REAL_TYPE))
10411         return do_mpfr_arg1 (arg0, type, mpfr_atanh,
10412                              &dconstm1, &dconst1, false);
10413     break;
10414
10415     CASE_FLT_FN (BUILT_IN_SIN):
10416       if (validate_arg (arg0, REAL_TYPE))
10417         return do_mpfr_arg1 (arg0, type, mpfr_sin, NULL, NULL, 0);
10418     break;
10419
10420     CASE_FLT_FN (BUILT_IN_COS):
10421       return fold_builtin_cos (loc, arg0, type, fndecl);
10422
10423     CASE_FLT_FN (BUILT_IN_TAN):
10424       return fold_builtin_tan (arg0, type);
10425
10426     CASE_FLT_FN (BUILT_IN_CEXP):
10427       return fold_builtin_cexp (loc, arg0, type);
10428
10429     CASE_FLT_FN (BUILT_IN_CEXPI):
10430       if (validate_arg (arg0, REAL_TYPE))
10431         return do_mpfr_sincos (arg0, NULL_TREE, NULL_TREE);
10432     break;
10433
10434     CASE_FLT_FN (BUILT_IN_SINH):
10435       if (validate_arg (arg0, REAL_TYPE))
10436         return do_mpfr_arg1 (arg0, type, mpfr_sinh, NULL, NULL, 0);
10437     break;
10438
10439     CASE_FLT_FN (BUILT_IN_COSH):
10440       return fold_builtin_cosh (loc, arg0, type, fndecl);
10441
10442     CASE_FLT_FN (BUILT_IN_TANH):
10443       if (validate_arg (arg0, REAL_TYPE))
10444         return do_mpfr_arg1 (arg0, type, mpfr_tanh, NULL, NULL, 0);
10445     break;
10446
10447     CASE_FLT_FN (BUILT_IN_ERF):
10448       if (validate_arg (arg0, REAL_TYPE))
10449         return do_mpfr_arg1 (arg0, type, mpfr_erf, NULL, NULL, 0);
10450     break;
10451
10452     CASE_FLT_FN (BUILT_IN_ERFC):
10453       if (validate_arg (arg0, REAL_TYPE))
10454         return do_mpfr_arg1 (arg0, type, mpfr_erfc, NULL, NULL, 0);
10455     break;
10456
10457     CASE_FLT_FN (BUILT_IN_TGAMMA):
10458       if (validate_arg (arg0, REAL_TYPE))
10459         return do_mpfr_arg1 (arg0, type, mpfr_gamma, NULL, NULL, 0);
10460     break;
10461
10462     CASE_FLT_FN (BUILT_IN_EXP):
10463       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp);
10464
10465     CASE_FLT_FN (BUILT_IN_EXP2):
10466       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp2);
10467
10468     CASE_FLT_FN (BUILT_IN_EXP10):
10469     CASE_FLT_FN (BUILT_IN_POW10):
10470       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp10);
10471
10472     CASE_FLT_FN (BUILT_IN_EXPM1):
10473       if (validate_arg (arg0, REAL_TYPE))
10474         return do_mpfr_arg1 (arg0, type, mpfr_expm1, NULL, NULL, 0);
10475     break;
10476
10477     CASE_FLT_FN (BUILT_IN_LOG):
10478     return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log);
10479
10480     CASE_FLT_FN (BUILT_IN_LOG2):
10481       return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log2);
10482
10483     CASE_FLT_FN (BUILT_IN_LOG10):
10484       return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log10);
10485
10486     CASE_FLT_FN (BUILT_IN_LOG1P):
10487       if (validate_arg (arg0, REAL_TYPE))
10488         return do_mpfr_arg1 (arg0, type, mpfr_log1p,
10489                              &dconstm1, NULL, false);
10490     break;
10491
10492     CASE_FLT_FN (BUILT_IN_J0):
10493       if (validate_arg (arg0, REAL_TYPE))
10494         return do_mpfr_arg1 (arg0, type, mpfr_j0,
10495                              NULL, NULL, 0);
10496     break;
10497
10498     CASE_FLT_FN (BUILT_IN_J1):
10499       if (validate_arg (arg0, REAL_TYPE))
10500         return do_mpfr_arg1 (arg0, type, mpfr_j1,
10501                              NULL, NULL, 0);
10502     break;
10503
10504     CASE_FLT_FN (BUILT_IN_Y0):
10505       if (validate_arg (arg0, REAL_TYPE))
10506         return do_mpfr_arg1 (arg0, type, mpfr_y0,
10507                              &dconst0, NULL, false);
10508     break;
10509
10510     CASE_FLT_FN (BUILT_IN_Y1):
10511       if (validate_arg (arg0, REAL_TYPE))
10512         return do_mpfr_arg1 (arg0, type, mpfr_y1,
10513                              &dconst0, NULL, false);
10514     break;
10515
10516     CASE_FLT_FN (BUILT_IN_NAN):
10517     case BUILT_IN_NAND32:
10518     case BUILT_IN_NAND64:
10519     case BUILT_IN_NAND128:
10520       return fold_builtin_nan (arg0, type, true);
10521
10522     CASE_FLT_FN (BUILT_IN_NANS):
10523       return fold_builtin_nan (arg0, type, false);
10524
10525     CASE_FLT_FN (BUILT_IN_FLOOR):
10526       return fold_builtin_floor (loc, fndecl, arg0);
10527
10528     CASE_FLT_FN (BUILT_IN_CEIL):
10529       return fold_builtin_ceil (loc, fndecl, arg0);
10530
10531     CASE_FLT_FN (BUILT_IN_TRUNC):
10532       return fold_builtin_trunc (loc, fndecl, arg0);
10533
10534     CASE_FLT_FN (BUILT_IN_ROUND):
10535       return fold_builtin_round (loc, fndecl, arg0);
10536
10537     CASE_FLT_FN (BUILT_IN_NEARBYINT):
10538     CASE_FLT_FN (BUILT_IN_RINT):
10539       return fold_trunc_transparent_mathfn (loc, fndecl, arg0);
10540
10541     CASE_FLT_FN (BUILT_IN_ICEIL):
10542     CASE_FLT_FN (BUILT_IN_LCEIL):
10543     CASE_FLT_FN (BUILT_IN_LLCEIL):
10544     CASE_FLT_FN (BUILT_IN_LFLOOR):
10545     CASE_FLT_FN (BUILT_IN_IFLOOR):
10546     CASE_FLT_FN (BUILT_IN_LLFLOOR):
10547     CASE_FLT_FN (BUILT_IN_IROUND):
10548     CASE_FLT_FN (BUILT_IN_LROUND):
10549     CASE_FLT_FN (BUILT_IN_LLROUND):
10550       return fold_builtin_int_roundingfn (loc, fndecl, arg0);
10551
10552     CASE_FLT_FN (BUILT_IN_IRINT):
10553     CASE_FLT_FN (BUILT_IN_LRINT):
10554     CASE_FLT_FN (BUILT_IN_LLRINT):
10555       return fold_fixed_mathfn (loc, fndecl, arg0);
10556
10557     case BUILT_IN_BSWAP16:
10558     case BUILT_IN_BSWAP32:
10559     case BUILT_IN_BSWAP64:
10560       return fold_builtin_bswap (fndecl, arg0);
10561
10562     CASE_INT_FN (BUILT_IN_FFS):
10563     CASE_INT_FN (BUILT_IN_CLZ):
10564     CASE_INT_FN (BUILT_IN_CTZ):
10565     CASE_INT_FN (BUILT_IN_CLRSB):
10566     CASE_INT_FN (BUILT_IN_POPCOUNT):
10567     CASE_INT_FN (BUILT_IN_PARITY):
10568       return fold_builtin_bitop (fndecl, arg0);
10569
10570     CASE_FLT_FN (BUILT_IN_SIGNBIT):
10571       return fold_builtin_signbit (loc, arg0, type);
10572
10573     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
10574       return fold_builtin_significand (loc, arg0, type);
10575
10576     CASE_FLT_FN (BUILT_IN_ILOGB):
10577     CASE_FLT_FN (BUILT_IN_LOGB):
10578       return fold_builtin_logb (loc, arg0, type);
10579
10580     case BUILT_IN_ISASCII:
10581       return fold_builtin_isascii (loc, arg0);
10582
10583     case BUILT_IN_TOASCII:
10584       return fold_builtin_toascii (loc, arg0);
10585
10586     case BUILT_IN_ISDIGIT:
10587       return fold_builtin_isdigit (loc, arg0);
10588
10589     CASE_FLT_FN (BUILT_IN_FINITE):
10590     case BUILT_IN_FINITED32:
10591     case BUILT_IN_FINITED64:
10592     case BUILT_IN_FINITED128:
10593     case BUILT_IN_ISFINITE:
10594       {
10595         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISFINITE);
10596         if (ret)
10597           return ret;
10598         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10599       }
10600
10601     CASE_FLT_FN (BUILT_IN_ISINF):
10602     case BUILT_IN_ISINFD32:
10603     case BUILT_IN_ISINFD64:
10604     case BUILT_IN_ISINFD128:
10605       {
10606         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF);
10607         if (ret)
10608           return ret;
10609         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10610       }
10611
10612     case BUILT_IN_ISNORMAL:
10613       return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10614
10615     case BUILT_IN_ISINF_SIGN:
10616       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF_SIGN);
10617
10618     CASE_FLT_FN (BUILT_IN_ISNAN):
10619     case BUILT_IN_ISNAND32:
10620     case BUILT_IN_ISNAND64:
10621     case BUILT_IN_ISNAND128:
10622       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISNAN);
10623
10624     case BUILT_IN_PRINTF:
10625     case BUILT_IN_PRINTF_UNLOCKED:
10626     case BUILT_IN_VPRINTF:
10627       return fold_builtin_printf (loc, fndecl, arg0, NULL_TREE, ignore, fcode);
10628
10629     case BUILT_IN_FREE:
10630       if (integer_zerop (arg0))
10631         return build_empty_stmt (loc);
10632       break;
10633
10634     default:
10635       break;
10636     }
10637
10638   return NULL_TREE;
10639
10640 }
10641
10642 /* Fold a call to built-in function FNDECL with 2 arguments, ARG0 and ARG1.
10643    IGNORE is true if the result of the function call is ignored.  This
10644    function returns NULL_TREE if no simplification was possible.  */
10645
10646 static tree
10647 fold_builtin_2 (location_t loc, tree fndecl, tree arg0, tree arg1, bool ignore)
10648 {
10649   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10650   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10651
10652   switch (fcode)
10653     {
10654     CASE_FLT_FN (BUILT_IN_JN):
10655       if (validate_arg (arg0, INTEGER_TYPE)
10656           && validate_arg (arg1, REAL_TYPE))
10657         return do_mpfr_bessel_n (arg0, arg1, type, mpfr_jn, NULL, 0);
10658     break;
10659
10660     CASE_FLT_FN (BUILT_IN_YN):
10661       if (validate_arg (arg0, INTEGER_TYPE)
10662           && validate_arg (arg1, REAL_TYPE))
10663         return do_mpfr_bessel_n (arg0, arg1, type, mpfr_yn,
10664                                  &dconst0, false);
10665     break;
10666
10667     CASE_FLT_FN (BUILT_IN_DREM):
10668     CASE_FLT_FN (BUILT_IN_REMAINDER):
10669       if (validate_arg (arg0, REAL_TYPE)
10670           && validate_arg (arg1, REAL_TYPE))
10671         return do_mpfr_arg2 (arg0, arg1, type, mpfr_remainder);
10672     break;
10673
10674     CASE_FLT_FN_REENT (BUILT_IN_GAMMA): /* GAMMA_R */
10675     CASE_FLT_FN_REENT (BUILT_IN_LGAMMA): /* LGAMMA_R */
10676       if (validate_arg (arg0, REAL_TYPE)
10677           && validate_arg (arg1, POINTER_TYPE))
10678         return do_mpfr_lgamma_r (arg0, arg1, type);
10679     break;
10680
10681     CASE_FLT_FN (BUILT_IN_ATAN2):
10682       if (validate_arg (arg0, REAL_TYPE)
10683           && validate_arg (arg1, REAL_TYPE))
10684         return do_mpfr_arg2 (arg0, arg1, type, mpfr_atan2);
10685     break;
10686
10687     CASE_FLT_FN (BUILT_IN_FDIM):
10688       if (validate_arg (arg0, REAL_TYPE)
10689           && validate_arg (arg1, REAL_TYPE))
10690         return do_mpfr_arg2 (arg0, arg1, type, mpfr_dim);
10691     break;
10692
10693     CASE_FLT_FN (BUILT_IN_HYPOT):
10694       return fold_builtin_hypot (loc, fndecl, arg0, arg1, type);
10695
10696     CASE_FLT_FN (BUILT_IN_CPOW):
10697       if (validate_arg (arg0, COMPLEX_TYPE)
10698           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE
10699           && validate_arg (arg1, COMPLEX_TYPE)
10700           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg1))) == REAL_TYPE)
10701         return do_mpc_arg2 (arg0, arg1, type, /*do_nonfinite=*/ 0, mpc_pow);
10702     break;
10703
10704     CASE_FLT_FN (BUILT_IN_LDEXP):
10705       return fold_builtin_load_exponent (loc, arg0, arg1, type, /*ldexp=*/true);
10706     CASE_FLT_FN (BUILT_IN_SCALBN):
10707     CASE_FLT_FN (BUILT_IN_SCALBLN):
10708       return fold_builtin_load_exponent (loc, arg0, arg1,
10709                                          type, /*ldexp=*/false);
10710
10711     CASE_FLT_FN (BUILT_IN_FREXP):
10712       return fold_builtin_frexp (loc, arg0, arg1, type);
10713
10714     CASE_FLT_FN (BUILT_IN_MODF):
10715       return fold_builtin_modf (loc, arg0, arg1, type);
10716
10717     case BUILT_IN_BZERO:
10718       return fold_builtin_bzero (loc, arg0, arg1, ignore);
10719
10720     case BUILT_IN_FPUTS:
10721       return fold_builtin_fputs (loc, arg0, arg1, ignore, false, NULL_TREE);
10722
10723     case BUILT_IN_FPUTS_UNLOCKED:
10724       return fold_builtin_fputs (loc, arg0, arg1, ignore, true, NULL_TREE);
10725
10726     case BUILT_IN_STRSTR:
10727       return fold_builtin_strstr (loc, arg0, arg1, type);
10728
10729     case BUILT_IN_STRCAT:
10730       return fold_builtin_strcat (loc, arg0, arg1);
10731
10732     case BUILT_IN_STRSPN:
10733       return fold_builtin_strspn (loc, arg0, arg1);
10734
10735     case BUILT_IN_STRCSPN:
10736       return fold_builtin_strcspn (loc, arg0, arg1);
10737
10738     case BUILT_IN_STRCHR:
10739     case BUILT_IN_INDEX:
10740       return fold_builtin_strchr (loc, arg0, arg1, type);
10741
10742     case BUILT_IN_STRRCHR:
10743     case BUILT_IN_RINDEX:
10744       return fold_builtin_strrchr (loc, arg0, arg1, type);
10745
10746     case BUILT_IN_STRCPY:
10747       return fold_builtin_strcpy (loc, fndecl, arg0, arg1, NULL_TREE);
10748
10749     case BUILT_IN_STPCPY:
10750       if (ignore)
10751         {
10752           tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
10753           if (!fn)
10754             break;
10755
10756           return build_call_expr_loc (loc, fn, 2, arg0, arg1);
10757         }
10758       else
10759         return fold_builtin_stpcpy (loc, fndecl, arg0, arg1);
10760       break;
10761
10762     case BUILT_IN_STRCMP:
10763       return fold_builtin_strcmp (loc, arg0, arg1);
10764
10765     case BUILT_IN_STRPBRK:
10766       return fold_builtin_strpbrk (loc, arg0, arg1, type);
10767
10768     case BUILT_IN_EXPECT:
10769       return fold_builtin_expect (loc, arg0, arg1);
10770
10771     CASE_FLT_FN (BUILT_IN_POW):
10772       return fold_builtin_pow (loc, fndecl, arg0, arg1, type);
10773
10774     CASE_FLT_FN (BUILT_IN_POWI):
10775       return fold_builtin_powi (loc, fndecl, arg0, arg1, type);
10776
10777     CASE_FLT_FN (BUILT_IN_COPYSIGN):
10778       return fold_builtin_copysign (loc, fndecl, arg0, arg1, type);
10779
10780     CASE_FLT_FN (BUILT_IN_FMIN):
10781       return fold_builtin_fmin_fmax (loc, arg0, arg1, type, /*max=*/false);
10782
10783     CASE_FLT_FN (BUILT_IN_FMAX):
10784       return fold_builtin_fmin_fmax (loc, arg0, arg1, type, /*max=*/true);
10785
10786     case BUILT_IN_ISGREATER:
10787       return fold_builtin_unordered_cmp (loc, fndecl,
10788                                          arg0, arg1, UNLE_EXPR, LE_EXPR);
10789     case BUILT_IN_ISGREATEREQUAL:
10790       return fold_builtin_unordered_cmp (loc, fndecl,
10791                                          arg0, arg1, UNLT_EXPR, LT_EXPR);
10792     case BUILT_IN_ISLESS:
10793       return fold_builtin_unordered_cmp (loc, fndecl,
10794                                          arg0, arg1, UNGE_EXPR, GE_EXPR);
10795     case BUILT_IN_ISLESSEQUAL:
10796       return fold_builtin_unordered_cmp (loc, fndecl,
10797                                          arg0, arg1, UNGT_EXPR, GT_EXPR);
10798     case BUILT_IN_ISLESSGREATER:
10799       return fold_builtin_unordered_cmp (loc, fndecl,
10800                                          arg0, arg1, UNEQ_EXPR, EQ_EXPR);
10801     case BUILT_IN_ISUNORDERED:
10802       return fold_builtin_unordered_cmp (loc, fndecl,
10803                                          arg0, arg1, UNORDERED_EXPR,
10804                                          NOP_EXPR);
10805
10806       /* We do the folding for va_start in the expander.  */
10807     case BUILT_IN_VA_START:
10808       break;
10809
10810     case BUILT_IN_SPRINTF:
10811       return fold_builtin_sprintf (loc, arg0, arg1, NULL_TREE, ignore);
10812
10813     case BUILT_IN_OBJECT_SIZE:
10814       return fold_builtin_object_size (arg0, arg1);
10815
10816     case BUILT_IN_PRINTF:
10817     case BUILT_IN_PRINTF_UNLOCKED:
10818     case BUILT_IN_VPRINTF:
10819       return fold_builtin_printf (loc, fndecl, arg0, arg1, ignore, fcode);
10820
10821     case BUILT_IN_PRINTF_CHK:
10822     case BUILT_IN_VPRINTF_CHK:
10823       if (!validate_arg (arg0, INTEGER_TYPE)
10824           || TREE_SIDE_EFFECTS (arg0))
10825         return NULL_TREE;
10826       else
10827         return fold_builtin_printf (loc, fndecl,
10828                                     arg1, NULL_TREE, ignore, fcode);
10829     break;
10830
10831     case BUILT_IN_FPRINTF:
10832     case BUILT_IN_FPRINTF_UNLOCKED:
10833     case BUILT_IN_VFPRINTF:
10834       return fold_builtin_fprintf (loc, fndecl, arg0, arg1, NULL_TREE,
10835                                    ignore, fcode);
10836
10837     case BUILT_IN_ATOMIC_ALWAYS_LOCK_FREE:
10838       return fold_builtin_atomic_always_lock_free (arg0, arg1);
10839
10840     case BUILT_IN_ATOMIC_IS_LOCK_FREE:
10841       return fold_builtin_atomic_is_lock_free (arg0, arg1);
10842
10843     default:
10844       break;
10845     }
10846   return NULL_TREE;
10847 }
10848
10849 /* Fold a call to built-in function FNDECL with 3 arguments, ARG0, ARG1,
10850    and ARG2.  IGNORE is true if the result of the function call is ignored.
10851    This function returns NULL_TREE if no simplification was possible.  */
10852
10853 static tree
10854 fold_builtin_3 (location_t loc, tree fndecl,
10855                 tree arg0, tree arg1, tree arg2, bool ignore)
10856 {
10857   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10858   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10859   switch (fcode)
10860     {
10861
10862     CASE_FLT_FN (BUILT_IN_SINCOS):
10863       return fold_builtin_sincos (loc, arg0, arg1, arg2);
10864
10865     CASE_FLT_FN (BUILT_IN_FMA):
10866       return fold_builtin_fma (loc, arg0, arg1, arg2, type);
10867     break;
10868
10869     CASE_FLT_FN (BUILT_IN_REMQUO):
10870       if (validate_arg (arg0, REAL_TYPE)
10871           && validate_arg (arg1, REAL_TYPE)
10872           && validate_arg (arg2, POINTER_TYPE))
10873         return do_mpfr_remquo (arg0, arg1, arg2);
10874     break;
10875
10876     case BUILT_IN_MEMSET:
10877       return fold_builtin_memset (loc, arg0, arg1, arg2, type, ignore);
10878
10879     case BUILT_IN_BCOPY:
10880       return fold_builtin_memory_op (loc, arg1, arg0, arg2,
10881                                      void_type_node, true, /*endp=*/3);
10882
10883     case BUILT_IN_MEMCPY:
10884       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10885                                      type, ignore, /*endp=*/0);
10886
10887     case BUILT_IN_MEMPCPY:
10888       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10889                                      type, ignore, /*endp=*/1);
10890
10891     case BUILT_IN_MEMMOVE:
10892       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10893                                      type, ignore, /*endp=*/3);
10894
10895     case BUILT_IN_STRNCAT:
10896       return fold_builtin_strncat (loc, arg0, arg1, arg2);
10897
10898     case BUILT_IN_STRNCPY:
10899       return fold_builtin_strncpy (loc, fndecl, arg0, arg1, arg2, NULL_TREE);
10900
10901     case BUILT_IN_STRNCMP:
10902       return fold_builtin_strncmp (loc, arg0, arg1, arg2);
10903
10904     case BUILT_IN_MEMCHR:
10905       return fold_builtin_memchr (loc, arg0, arg1, arg2, type);
10906
10907     case BUILT_IN_BCMP:
10908     case BUILT_IN_MEMCMP:
10909       return fold_builtin_memcmp (loc, arg0, arg1, arg2);;
10910
10911     case BUILT_IN_SPRINTF:
10912       return fold_builtin_sprintf (loc, arg0, arg1, arg2, ignore);
10913
10914     case BUILT_IN_SNPRINTF:
10915       return fold_builtin_snprintf (loc, arg0, arg1, arg2, NULL_TREE, ignore);
10916
10917     case BUILT_IN_STRCPY_CHK:
10918     case BUILT_IN_STPCPY_CHK:
10919       return fold_builtin_stxcpy_chk (loc, fndecl, arg0, arg1, arg2, NULL_TREE,
10920                                       ignore, fcode);
10921
10922     case BUILT_IN_STRCAT_CHK:
10923       return fold_builtin_strcat_chk (loc, fndecl, arg0, arg1, arg2);
10924
10925     case BUILT_IN_PRINTF_CHK:
10926     case BUILT_IN_VPRINTF_CHK:
10927       if (!validate_arg (arg0, INTEGER_TYPE)
10928           || TREE_SIDE_EFFECTS (arg0))
10929         return NULL_TREE;
10930       else
10931         return fold_builtin_printf (loc, fndecl, arg1, arg2, ignore, fcode);
10932     break;
10933
10934     case BUILT_IN_FPRINTF:
10935     case BUILT_IN_FPRINTF_UNLOCKED:
10936     case BUILT_IN_VFPRINTF:
10937       return fold_builtin_fprintf (loc, fndecl, arg0, arg1, arg2,
10938                                    ignore, fcode);
10939
10940     case BUILT_IN_FPRINTF_CHK:
10941     case BUILT_IN_VFPRINTF_CHK:
10942       if (!validate_arg (arg1, INTEGER_TYPE)
10943           || TREE_SIDE_EFFECTS (arg1))
10944         return NULL_TREE;
10945       else
10946         return fold_builtin_fprintf (loc, fndecl, arg0, arg2, NULL_TREE,
10947                                      ignore, fcode);
10948
10949     default:
10950       break;
10951     }
10952   return NULL_TREE;
10953 }
10954
10955 /* Fold a call to built-in function FNDECL with 4 arguments, ARG0, ARG1,
10956    ARG2, and ARG3.  IGNORE is true if the result of the function call is
10957    ignored.  This function returns NULL_TREE if no simplification was
10958    possible.  */
10959
10960 static tree
10961 fold_builtin_4 (location_t loc, tree fndecl,
10962                 tree arg0, tree arg1, tree arg2, tree arg3, bool ignore)
10963 {
10964   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10965
10966   switch (fcode)
10967     {
10968     case BUILT_IN_MEMCPY_CHK:
10969     case BUILT_IN_MEMPCPY_CHK:
10970     case BUILT_IN_MEMMOVE_CHK:
10971     case BUILT_IN_MEMSET_CHK:
10972       return fold_builtin_memory_chk (loc, fndecl, arg0, arg1, arg2, arg3,
10973                                       NULL_TREE, ignore,
10974                                       DECL_FUNCTION_CODE (fndecl));
10975
10976     case BUILT_IN_STRNCPY_CHK:
10977     case BUILT_IN_STPNCPY_CHK:
10978       return fold_builtin_stxncpy_chk (loc, arg0, arg1, arg2, arg3, NULL_TREE,
10979                                        ignore, fcode);
10980
10981     case BUILT_IN_STRNCAT_CHK:
10982       return fold_builtin_strncat_chk (loc, fndecl, arg0, arg1, arg2, arg3);
10983
10984     case BUILT_IN_SNPRINTF:
10985       return fold_builtin_snprintf (loc, arg0, arg1, arg2, arg3, ignore);
10986
10987     case BUILT_IN_FPRINTF_CHK:
10988     case BUILT_IN_VFPRINTF_CHK:
10989       if (!validate_arg (arg1, INTEGER_TYPE)
10990           || TREE_SIDE_EFFECTS (arg1))
10991         return NULL_TREE;
10992       else
10993         return fold_builtin_fprintf (loc, fndecl, arg0, arg2, arg3,
10994                                      ignore, fcode);
10995     break;
10996
10997     default:
10998       break;
10999     }
11000   return NULL_TREE;
11001 }
11002
11003 /* Fold a call to built-in function FNDECL.  ARGS is an array of NARGS
11004     arguments, where NARGS <= 4.  IGNORE is true if the result of the
11005     function call is ignored.  This function returns NULL_TREE if no
11006     simplification was possible.  Note that this only folds builtins with
11007     fixed argument patterns.  Foldings that do varargs-to-varargs
11008     transformations, or that match calls with more than 4 arguments,
11009     need to be handled with fold_builtin_varargs instead.  */
11010
11011 #define MAX_ARGS_TO_FOLD_BUILTIN 4
11012
11013 static tree
11014 fold_builtin_n (location_t loc, tree fndecl, tree *args, int nargs, bool ignore)
11015 {
11016   tree ret = NULL_TREE;
11017
11018   switch (nargs)
11019     {
11020     case 0:
11021       ret = fold_builtin_0 (loc, fndecl, ignore);
11022       break;
11023     case 1:
11024       ret = fold_builtin_1 (loc, fndecl, args[0], ignore);
11025       break;
11026     case 2:
11027       ret = fold_builtin_2 (loc, fndecl, args[0], args[1], ignore);
11028       break;
11029     case 3:
11030       ret = fold_builtin_3 (loc, fndecl, args[0], args[1], args[2], ignore);
11031       break;
11032     case 4:
11033       ret = fold_builtin_4 (loc, fndecl, args[0], args[1], args[2], args[3],
11034                             ignore);
11035       break;
11036     default:
11037       break;
11038     }
11039   if (ret)
11040     {
11041       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
11042       SET_EXPR_LOCATION (ret, loc);
11043       TREE_NO_WARNING (ret) = 1;
11044       return ret;
11045     }
11046   return NULL_TREE;
11047 }
11048
11049 /* Construct a new CALL_EXPR to FNDECL using the tail of the argument
11050    list ARGS along with N new arguments in NEWARGS.  SKIP is the number
11051    of arguments in ARGS to be omitted.  OLDNARGS is the number of
11052    elements in ARGS.  */
11053
11054 static tree
11055 rewrite_call_expr_valist (location_t loc, int oldnargs, tree *args,
11056                           int skip, tree fndecl, int n, va_list newargs)
11057 {
11058   int nargs = oldnargs - skip + n;
11059   tree *buffer;
11060
11061   if (n > 0)
11062     {
11063       int i, j;
11064
11065       buffer = XALLOCAVEC (tree, nargs);
11066       for (i = 0; i < n; i++)
11067         buffer[i] = va_arg (newargs, tree);
11068       for (j = skip; j < oldnargs; j++, i++)
11069         buffer[i] = args[j];
11070     }
11071   else
11072     buffer = args + skip;
11073
11074   return build_call_expr_loc_array (loc, fndecl, nargs, buffer);
11075 }
11076
11077 /* Construct a new CALL_EXPR to FNDECL using the tail of the argument
11078    list ARGS along with N new arguments specified as the "..."
11079    parameters.  SKIP is the number of arguments in ARGS to be omitted.
11080    OLDNARGS is the number of elements in ARGS.  */
11081
11082 static tree
11083 rewrite_call_expr_array (location_t loc, int oldnargs, tree *args,
11084                          int skip, tree fndecl, int n, ...)
11085 {
11086   va_list ap;
11087   tree t;
11088
11089   va_start (ap, n);
11090   t = rewrite_call_expr_valist (loc, oldnargs, args, skip, fndecl, n, ap);
11091   va_end (ap);
11092
11093   return t;
11094 }
11095
11096 /* Return true if FNDECL shouldn't be folded right now.
11097    If a built-in function has an inline attribute always_inline
11098    wrapper, defer folding it after always_inline functions have
11099    been inlined, otherwise e.g. -D_FORTIFY_SOURCE checking
11100    might not be performed.  */
11101
11102 bool
11103 avoid_folding_inline_builtin (tree fndecl)
11104 {
11105   return (DECL_DECLARED_INLINE_P (fndecl)
11106           && DECL_DISREGARD_INLINE_LIMITS (fndecl)
11107           && cfun
11108           && !cfun->always_inline_functions_inlined
11109           && lookup_attribute ("always_inline", DECL_ATTRIBUTES (fndecl)));
11110 }
11111
11112 /* A wrapper function for builtin folding that prevents warnings for
11113    "statement without effect" and the like, caused by removing the
11114    call node earlier than the warning is generated.  */
11115
11116 tree
11117 fold_call_expr (location_t loc, tree exp, bool ignore)
11118 {
11119   tree ret = NULL_TREE;
11120   tree fndecl = get_callee_fndecl (exp);
11121   if (fndecl
11122       && TREE_CODE (fndecl) == FUNCTION_DECL
11123       && DECL_BUILT_IN (fndecl)
11124       /* If CALL_EXPR_VA_ARG_PACK is set, the arguments aren't finalized
11125          yet.  Defer folding until we see all the arguments
11126          (after inlining).  */
11127       && !CALL_EXPR_VA_ARG_PACK (exp))
11128     {
11129       int nargs = call_expr_nargs (exp);
11130
11131       /* Before gimplification CALL_EXPR_VA_ARG_PACK is not set, but
11132          instead last argument is __builtin_va_arg_pack ().  Defer folding
11133          even in that case, until arguments are finalized.  */
11134       if (nargs && TREE_CODE (CALL_EXPR_ARG (exp, nargs - 1)) == CALL_EXPR)
11135         {
11136           tree fndecl2 = get_callee_fndecl (CALL_EXPR_ARG (exp, nargs - 1));
11137           if (fndecl2
11138               && TREE_CODE (fndecl2) == FUNCTION_DECL
11139               && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
11140               && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
11141             return NULL_TREE;
11142         }
11143
11144       if (avoid_folding_inline_builtin (fndecl))
11145         return NULL_TREE;
11146
11147       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
11148         return targetm.fold_builtin (fndecl, call_expr_nargs (exp),
11149                                      CALL_EXPR_ARGP (exp), ignore);
11150       else
11151         {
11152           if (nargs <= MAX_ARGS_TO_FOLD_BUILTIN)
11153             {
11154               tree *args = CALL_EXPR_ARGP (exp);
11155               ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
11156             }
11157           if (!ret)
11158             ret = fold_builtin_varargs (loc, fndecl, exp, ignore);
11159           if (ret)
11160             return ret;
11161         }
11162     }
11163   return NULL_TREE;
11164 }
11165
11166 /* Conveniently construct a function call expression.  FNDECL names the
11167    function to be called and N arguments are passed in the array
11168    ARGARRAY.  */
11169
11170 tree
11171 build_call_expr_loc_array (location_t loc, tree fndecl, int n, tree *argarray)
11172 {
11173   tree fntype = TREE_TYPE (fndecl);
11174   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
11175  
11176   return fold_builtin_call_array (loc, TREE_TYPE (fntype), fn, n, argarray);
11177 }
11178
11179 /* Conveniently construct a function call expression.  FNDECL names the
11180    function to be called and the arguments are passed in the vector
11181    VEC.  */
11182
11183 tree
11184 build_call_expr_loc_vec (location_t loc, tree fndecl, vec<tree, va_gc> *vec)
11185 {
11186   return build_call_expr_loc_array (loc, fndecl, vec_safe_length (vec),
11187                                     vec_safe_address (vec));
11188 }
11189
11190
11191 /* Conveniently construct a function call expression.  FNDECL names the
11192    function to be called, N is the number of arguments, and the "..."
11193    parameters are the argument expressions.  */
11194
11195 tree
11196 build_call_expr_loc (location_t loc, tree fndecl, int n, ...)
11197 {
11198   va_list ap;
11199   tree *argarray = XALLOCAVEC (tree, n);
11200   int i;
11201
11202   va_start (ap, n);
11203   for (i = 0; i < n; i++)
11204     argarray[i] = va_arg (ap, tree);
11205   va_end (ap);
11206   return build_call_expr_loc_array (loc, fndecl, n, argarray);
11207 }
11208
11209 /* Like build_call_expr_loc (UNKNOWN_LOCATION, ...).  Duplicated because
11210    varargs macros aren't supported by all bootstrap compilers.  */
11211
11212 tree
11213 build_call_expr (tree fndecl, int n, ...)
11214 {
11215   va_list ap;
11216   tree *argarray = XALLOCAVEC (tree, n);
11217   int i;
11218
11219   va_start (ap, n);
11220   for (i = 0; i < n; i++)
11221     argarray[i] = va_arg (ap, tree);
11222   va_end (ap);
11223   return build_call_expr_loc_array (UNKNOWN_LOCATION, fndecl, n, argarray);
11224 }
11225
11226 /* Construct a CALL_EXPR with type TYPE with FN as the function expression.
11227    N arguments are passed in the array ARGARRAY.  */
11228
11229 tree
11230 fold_builtin_call_array (location_t loc, tree type,
11231                          tree fn,
11232                          int n,
11233                          tree *argarray)
11234 {
11235   tree ret = NULL_TREE;
11236    tree exp;
11237
11238   if (TREE_CODE (fn) == ADDR_EXPR)
11239   {
11240     tree fndecl = TREE_OPERAND (fn, 0);
11241     if (TREE_CODE (fndecl) == FUNCTION_DECL
11242         && DECL_BUILT_IN (fndecl))
11243       {
11244         /* If last argument is __builtin_va_arg_pack (), arguments to this
11245            function are not finalized yet.  Defer folding until they are.  */
11246         if (n && TREE_CODE (argarray[n - 1]) == CALL_EXPR)
11247           {
11248             tree fndecl2 = get_callee_fndecl (argarray[n - 1]);
11249             if (fndecl2
11250                 && TREE_CODE (fndecl2) == FUNCTION_DECL
11251                 && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
11252                 && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
11253               return build_call_array_loc (loc, type, fn, n, argarray);
11254           }
11255         if (avoid_folding_inline_builtin (fndecl))
11256           return build_call_array_loc (loc, type, fn, n, argarray);
11257         if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
11258           {
11259             ret = targetm.fold_builtin (fndecl, n, argarray, false);
11260             if (ret)
11261               return ret;
11262
11263             return build_call_array_loc (loc, type, fn, n, argarray);
11264           }
11265         else if (n <= MAX_ARGS_TO_FOLD_BUILTIN)
11266           {
11267             /* First try the transformations that don't require consing up
11268                an exp.  */
11269             ret = fold_builtin_n (loc, fndecl, argarray, n, false);
11270             if (ret)
11271               return ret;
11272           }
11273
11274         /* If we got this far, we need to build an exp.  */
11275         exp = build_call_array_loc (loc, type, fn, n, argarray);
11276         ret = fold_builtin_varargs (loc, fndecl, exp, false);
11277         return ret ? ret : exp;
11278       }
11279   }
11280
11281   return build_call_array_loc (loc, type, fn, n, argarray);
11282 }
11283
11284 /* Construct a new CALL_EXPR using the tail of the argument list of EXP
11285    along with N new arguments specified as the "..." parameters.  SKIP
11286    is the number of arguments in EXP to be omitted.  This function is used
11287    to do varargs-to-varargs transformations.  */
11288
11289 static tree
11290 rewrite_call_expr (location_t loc, tree exp, int skip, tree fndecl, int n, ...)
11291 {
11292   va_list ap;
11293   tree t;
11294
11295   va_start (ap, n);
11296   t = rewrite_call_expr_valist (loc, call_expr_nargs (exp),
11297                                 CALL_EXPR_ARGP (exp), skip, fndecl, n, ap);
11298   va_end (ap);
11299
11300   return t;
11301 }
11302
11303 /* Validate a single argument ARG against a tree code CODE representing
11304    a type.  */
11305
11306 static bool
11307 validate_arg (const_tree arg, enum tree_code code)
11308 {
11309   if (!arg)
11310     return false;
11311   else if (code == POINTER_TYPE)
11312     return POINTER_TYPE_P (TREE_TYPE (arg));
11313   else if (code == INTEGER_TYPE)
11314     return INTEGRAL_TYPE_P (TREE_TYPE (arg));
11315   return code == TREE_CODE (TREE_TYPE (arg));
11316 }
11317
11318 /* This function validates the types of a function call argument list
11319    against a specified list of tree_codes.  If the last specifier is a 0,
11320    that represents an ellipses, otherwise the last specifier must be a
11321    VOID_TYPE.
11322
11323    This is the GIMPLE version of validate_arglist.  Eventually we want to
11324    completely convert builtins.c to work from GIMPLEs and the tree based
11325    validate_arglist will then be removed.  */
11326
11327 bool
11328 validate_gimple_arglist (const_gimple call, ...)
11329 {
11330   enum tree_code code;
11331   bool res = 0;
11332   va_list ap;
11333   const_tree arg;
11334   size_t i;
11335
11336   va_start (ap, call);
11337   i = 0;
11338
11339   do
11340     {
11341       code = (enum tree_code) va_arg (ap, int);
11342       switch (code)
11343         {
11344         case 0:
11345           /* This signifies an ellipses, any further arguments are all ok.  */
11346           res = true;
11347           goto end;
11348         case VOID_TYPE:
11349           /* This signifies an endlink, if no arguments remain, return
11350              true, otherwise return false.  */
11351           res = (i == gimple_call_num_args (call));
11352           goto end;
11353         default:
11354           /* If no parameters remain or the parameter's code does not
11355              match the specified code, return false.  Otherwise continue
11356              checking any remaining arguments.  */
11357           arg = gimple_call_arg (call, i++);
11358           if (!validate_arg (arg, code))
11359             goto end;
11360           break;
11361         }
11362     }
11363   while (1);
11364
11365   /* We need gotos here since we can only have one VA_CLOSE in a
11366      function.  */
11367  end: ;
11368   va_end (ap);
11369
11370   return res;
11371 }
11372
11373 /* Default target-specific builtin expander that does nothing.  */
11374
11375 rtx
11376 default_expand_builtin (tree exp ATTRIBUTE_UNUSED,
11377                         rtx target ATTRIBUTE_UNUSED,
11378                         rtx subtarget ATTRIBUTE_UNUSED,
11379                         enum machine_mode mode ATTRIBUTE_UNUSED,
11380                         int ignore ATTRIBUTE_UNUSED)
11381 {
11382   return NULL_RTX;
11383 }
11384
11385 /* Returns true is EXP represents data that would potentially reside
11386    in a readonly section.  */
11387
11388 static bool
11389 readonly_data_expr (tree exp)
11390 {
11391   STRIP_NOPS (exp);
11392
11393   if (TREE_CODE (exp) != ADDR_EXPR)
11394     return false;
11395
11396   exp = get_base_address (TREE_OPERAND (exp, 0));
11397   if (!exp)
11398     return false;
11399
11400   /* Make sure we call decl_readonly_section only for trees it
11401      can handle (since it returns true for everything it doesn't
11402      understand).  */
11403   if (TREE_CODE (exp) == STRING_CST
11404       || TREE_CODE (exp) == CONSTRUCTOR
11405       || (TREE_CODE (exp) == VAR_DECL && TREE_STATIC (exp)))
11406     return decl_readonly_section (exp, 0);
11407   else
11408     return false;
11409 }
11410
11411 /* Simplify a call to the strstr builtin.  S1 and S2 are the arguments
11412    to the call, and TYPE is its return type.
11413
11414    Return NULL_TREE if no simplification was possible, otherwise return the
11415    simplified form of the call as a tree.
11416
11417    The simplified form may be a constant or other expression which
11418    computes the same value, but in a more efficient manner (including
11419    calls to other builtin functions).
11420
11421    The call may contain arguments which need to be evaluated, but
11422    which are not useful to determine the result of the call.  In
11423    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11424    COMPOUND_EXPR will be an argument which must be evaluated.
11425    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11426    COMPOUND_EXPR in the chain will contain the tree for the simplified
11427    form of the builtin function call.  */
11428
11429 static tree
11430 fold_builtin_strstr (location_t loc, tree s1, tree s2, tree type)
11431 {
11432   if (!validate_arg (s1, POINTER_TYPE)
11433       || !validate_arg (s2, POINTER_TYPE))
11434     return NULL_TREE;
11435   else
11436     {
11437       tree fn;
11438       const char *p1, *p2;
11439
11440       p2 = c_getstr (s2);
11441       if (p2 == NULL)
11442         return NULL_TREE;
11443
11444       p1 = c_getstr (s1);
11445       if (p1 != NULL)
11446         {
11447           const char *r = strstr (p1, p2);
11448           tree tem;
11449
11450           if (r == NULL)
11451             return build_int_cst (TREE_TYPE (s1), 0);
11452
11453           /* Return an offset into the constant string argument.  */
11454           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
11455           return fold_convert_loc (loc, type, tem);
11456         }
11457
11458       /* The argument is const char *, and the result is char *, so we need
11459          a type conversion here to avoid a warning.  */
11460       if (p2[0] == '\0')
11461         return fold_convert_loc (loc, type, s1);
11462
11463       if (p2[1] != '\0')
11464         return NULL_TREE;
11465
11466       fn = builtin_decl_implicit (BUILT_IN_STRCHR);
11467       if (!fn)
11468         return NULL_TREE;
11469
11470       /* New argument list transforming strstr(s1, s2) to
11471          strchr(s1, s2[0]).  */
11472       return build_call_expr_loc (loc, fn, 2, s1,
11473                                   build_int_cst (integer_type_node, p2[0]));
11474     }
11475 }
11476
11477 /* Simplify a call to the strchr builtin.  S1 and S2 are the arguments to
11478    the call, and TYPE is its return type.
11479
11480    Return NULL_TREE if no simplification was possible, otherwise return the
11481    simplified form of the call as a tree.
11482
11483    The simplified form may be a constant or other expression which
11484    computes the same value, but in a more efficient manner (including
11485    calls to other builtin functions).
11486
11487    The call may contain arguments which need to be evaluated, but
11488    which are not useful to determine the result of the call.  In
11489    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11490    COMPOUND_EXPR will be an argument which must be evaluated.
11491    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11492    COMPOUND_EXPR in the chain will contain the tree for the simplified
11493    form of the builtin function call.  */
11494
11495 static tree
11496 fold_builtin_strchr (location_t loc, tree s1, tree s2, tree type)
11497 {
11498   if (!validate_arg (s1, POINTER_TYPE)
11499       || !validate_arg (s2, INTEGER_TYPE))
11500     return NULL_TREE;
11501   else
11502     {
11503       const char *p1;
11504
11505       if (TREE_CODE (s2) != INTEGER_CST)
11506         return NULL_TREE;
11507
11508       p1 = c_getstr (s1);
11509       if (p1 != NULL)
11510         {
11511           char c;
11512           const char *r;
11513           tree tem;
11514
11515           if (target_char_cast (s2, &c))
11516             return NULL_TREE;
11517
11518           r = strchr (p1, c);
11519
11520           if (r == NULL)
11521             return build_int_cst (TREE_TYPE (s1), 0);
11522
11523           /* Return an offset into the constant string argument.  */
11524           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
11525           return fold_convert_loc (loc, type, tem);
11526         }
11527       return NULL_TREE;
11528     }
11529 }
11530
11531 /* Simplify a call to the strrchr builtin.  S1 and S2 are the arguments to
11532    the call, and TYPE is its return type.
11533
11534    Return NULL_TREE if no simplification was possible, otherwise return the
11535    simplified form of the call as a tree.
11536
11537    The simplified form may be a constant or other expression which
11538    computes the same value, but in a more efficient manner (including
11539    calls to other builtin functions).
11540
11541    The call may contain arguments which need to be evaluated, but
11542    which are not useful to determine the result of the call.  In
11543    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11544    COMPOUND_EXPR will be an argument which must be evaluated.
11545    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11546    COMPOUND_EXPR in the chain will contain the tree for the simplified
11547    form of the builtin function call.  */
11548
11549 static tree
11550 fold_builtin_strrchr (location_t loc, tree s1, tree s2, tree type)
11551 {
11552   if (!validate_arg (s1, POINTER_TYPE)
11553       || !validate_arg (s2, INTEGER_TYPE))
11554     return NULL_TREE;
11555   else
11556     {
11557       tree fn;
11558       const char *p1;
11559
11560       if (TREE_CODE (s2) != INTEGER_CST)
11561         return NULL_TREE;
11562
11563       p1 = c_getstr (s1);
11564       if (p1 != NULL)
11565         {
11566           char c;
11567           const char *r;
11568           tree tem;
11569
11570           if (target_char_cast (s2, &c))
11571             return NULL_TREE;
11572
11573           r = strrchr (p1, c);
11574
11575           if (r == NULL)
11576             return build_int_cst (TREE_TYPE (s1), 0);
11577
11578           /* Return an offset into the constant string argument.  */
11579           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
11580           return fold_convert_loc (loc, type, tem);
11581         }
11582
11583       if (! integer_zerop (s2))
11584         return NULL_TREE;
11585
11586       fn = builtin_decl_implicit (BUILT_IN_STRCHR);
11587       if (!fn)
11588         return NULL_TREE;
11589
11590       /* Transform strrchr(s1, '\0') to strchr(s1, '\0').  */
11591       return build_call_expr_loc (loc, fn, 2, s1, s2);
11592     }
11593 }
11594
11595 /* Simplify a call to the strpbrk builtin.  S1 and S2 are the arguments
11596    to the call, and TYPE is its return type.
11597
11598    Return NULL_TREE if no simplification was possible, otherwise return the
11599    simplified form of the call as a tree.
11600
11601    The simplified form may be a constant or other expression which
11602    computes the same value, but in a more efficient manner (including
11603    calls to other builtin functions).
11604
11605    The call may contain arguments which need to be evaluated, but
11606    which are not useful to determine the result of the call.  In
11607    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11608    COMPOUND_EXPR will be an argument which must be evaluated.
11609    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11610    COMPOUND_EXPR in the chain will contain the tree for the simplified
11611    form of the builtin function call.  */
11612
11613 static tree
11614 fold_builtin_strpbrk (location_t loc, tree s1, tree s2, tree type)
11615 {
11616   if (!validate_arg (s1, POINTER_TYPE)
11617       || !validate_arg (s2, POINTER_TYPE))
11618     return NULL_TREE;
11619   else
11620     {
11621       tree fn;
11622       const char *p1, *p2;
11623
11624       p2 = c_getstr (s2);
11625       if (p2 == NULL)
11626         return NULL_TREE;
11627
11628       p1 = c_getstr (s1);
11629       if (p1 != NULL)
11630         {
11631           const char *r = strpbrk (p1, p2);
11632           tree tem;
11633
11634           if (r == NULL)
11635             return build_int_cst (TREE_TYPE (s1), 0);
11636
11637           /* Return an offset into the constant string argument.  */
11638           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
11639           return fold_convert_loc (loc, type, tem);
11640         }
11641
11642       if (p2[0] == '\0')
11643         /* strpbrk(x, "") == NULL.
11644            Evaluate and ignore s1 in case it had side-effects.  */
11645         return omit_one_operand_loc (loc, TREE_TYPE (s1), integer_zero_node, s1);
11646
11647       if (p2[1] != '\0')
11648         return NULL_TREE;  /* Really call strpbrk.  */
11649
11650       fn = builtin_decl_implicit (BUILT_IN_STRCHR);
11651       if (!fn)
11652         return NULL_TREE;
11653
11654       /* New argument list transforming strpbrk(s1, s2) to
11655          strchr(s1, s2[0]).  */
11656       return build_call_expr_loc (loc, fn, 2, s1,
11657                                   build_int_cst (integer_type_node, p2[0]));
11658     }
11659 }
11660
11661 /* Simplify a call to the strcat builtin.  DST and SRC are the arguments
11662    to the call.
11663
11664    Return NULL_TREE if no simplification was possible, otherwise return the
11665    simplified form of the call as a tree.
11666
11667    The simplified form may be a constant or other expression which
11668    computes the same value, but in a more efficient manner (including
11669    calls to other builtin functions).
11670
11671    The call may contain arguments which need to be evaluated, but
11672    which are not useful to determine the result of the call.  In
11673    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11674    COMPOUND_EXPR will be an argument which must be evaluated.
11675    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11676    COMPOUND_EXPR in the chain will contain the tree for the simplified
11677    form of the builtin function call.  */
11678
11679 static tree
11680 fold_builtin_strcat (location_t loc ATTRIBUTE_UNUSED, tree dst, tree src)
11681 {
11682   if (!validate_arg (dst, POINTER_TYPE)
11683       || !validate_arg (src, POINTER_TYPE))
11684     return NULL_TREE;
11685   else
11686     {
11687       const char *p = c_getstr (src);
11688
11689       /* If the string length is zero, return the dst parameter.  */
11690       if (p && *p == '\0')
11691         return dst;
11692
11693       if (optimize_insn_for_speed_p ())
11694         {
11695           /* See if we can store by pieces into (dst + strlen(dst)).  */
11696           tree newdst, call;
11697           tree strlen_fn = builtin_decl_implicit (BUILT_IN_STRLEN);
11698           tree strcpy_fn = builtin_decl_implicit (BUILT_IN_STRCPY);
11699
11700           if (!strlen_fn || !strcpy_fn)
11701             return NULL_TREE;
11702
11703           /* If we don't have a movstr we don't want to emit an strcpy
11704              call.  We have to do that if the length of the source string
11705              isn't computable (in that case we can use memcpy probably
11706              later expanding to a sequence of mov instructions).  If we
11707              have movstr instructions we can emit strcpy calls.  */
11708           if (!HAVE_movstr)
11709             {
11710               tree len = c_strlen (src, 1);
11711               if (! len || TREE_SIDE_EFFECTS (len))
11712                 return NULL_TREE;
11713             }
11714
11715           /* Stabilize the argument list.  */
11716           dst = builtin_save_expr (dst);
11717
11718           /* Create strlen (dst).  */
11719           newdst = build_call_expr_loc (loc, strlen_fn, 1, dst);
11720           /* Create (dst p+ strlen (dst)).  */
11721
11722           newdst = fold_build_pointer_plus_loc (loc, dst, newdst);
11723           newdst = builtin_save_expr (newdst);
11724
11725           call = build_call_expr_loc (loc, strcpy_fn, 2, newdst, src);
11726           return build2 (COMPOUND_EXPR, TREE_TYPE (dst), call, dst);
11727         }
11728       return NULL_TREE;
11729     }
11730 }
11731
11732 /* Simplify a call to the strncat builtin.  DST, SRC, and LEN are the
11733    arguments to the call.
11734
11735    Return NULL_TREE if no simplification was possible, otherwise return the
11736    simplified form of the call as a tree.
11737
11738    The simplified form may be a constant or other expression which
11739    computes the same value, but in a more efficient manner (including
11740    calls to other builtin functions).
11741
11742    The call may contain arguments which need to be evaluated, but
11743    which are not useful to determine the result of the call.  In
11744    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11745    COMPOUND_EXPR will be an argument which must be evaluated.
11746    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11747    COMPOUND_EXPR in the chain will contain the tree for the simplified
11748    form of the builtin function call.  */
11749
11750 static tree
11751 fold_builtin_strncat (location_t loc, tree dst, tree src, tree len)
11752 {
11753   if (!validate_arg (dst, POINTER_TYPE)
11754       || !validate_arg (src, POINTER_TYPE)
11755       || !validate_arg (len, INTEGER_TYPE))
11756     return NULL_TREE;
11757   else
11758     {
11759       const char *p = c_getstr (src);
11760
11761       /* If the requested length is zero, or the src parameter string
11762          length is zero, return the dst parameter.  */
11763       if (integer_zerop (len) || (p && *p == '\0'))
11764         return omit_two_operands_loc (loc, TREE_TYPE (dst), dst, src, len);
11765
11766       /* If the requested len is greater than or equal to the string
11767          length, call strcat.  */
11768       if (TREE_CODE (len) == INTEGER_CST && p
11769           && compare_tree_int (len, strlen (p)) >= 0)
11770         {
11771           tree fn = builtin_decl_implicit (BUILT_IN_STRCAT);
11772
11773           /* If the replacement _DECL isn't initialized, don't do the
11774              transformation.  */
11775           if (!fn)
11776             return NULL_TREE;
11777
11778           return build_call_expr_loc (loc, fn, 2, dst, src);
11779         }
11780       return NULL_TREE;
11781     }
11782 }
11783
11784 /* Simplify a call to the strspn builtin.  S1 and S2 are the arguments
11785    to the call.
11786
11787    Return NULL_TREE if no simplification was possible, otherwise return the
11788    simplified form of the call as a tree.
11789
11790    The simplified form may be a constant or other expression which
11791    computes the same value, but in a more efficient manner (including
11792    calls to other builtin functions).
11793
11794    The call may contain arguments which need to be evaluated, but
11795    which are not useful to determine the result of the call.  In
11796    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11797    COMPOUND_EXPR will be an argument which must be evaluated.
11798    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11799    COMPOUND_EXPR in the chain will contain the tree for the simplified
11800    form of the builtin function call.  */
11801
11802 static tree
11803 fold_builtin_strspn (location_t loc, tree s1, tree s2)
11804 {
11805   if (!validate_arg (s1, POINTER_TYPE)
11806       || !validate_arg (s2, POINTER_TYPE))
11807     return NULL_TREE;
11808   else
11809     {
11810       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
11811
11812       /* If both arguments are constants, evaluate at compile-time.  */
11813       if (p1 && p2)
11814         {
11815           const size_t r = strspn (p1, p2);
11816           return build_int_cst (size_type_node, r);
11817         }
11818
11819       /* If either argument is "", return NULL_TREE.  */
11820       if ((p1 && *p1 == '\0') || (p2 && *p2 == '\0'))
11821         /* Evaluate and ignore both arguments in case either one has
11822            side-effects.  */
11823         return omit_two_operands_loc (loc, size_type_node, size_zero_node,
11824                                   s1, s2);
11825       return NULL_TREE;
11826     }
11827 }
11828
11829 /* Simplify a call to the strcspn builtin.  S1 and S2 are the arguments
11830    to the call.
11831
11832    Return NULL_TREE if no simplification was possible, otherwise return the
11833    simplified form of the call as a tree.
11834
11835    The simplified form may be a constant or other expression which
11836    computes the same value, but in a more efficient manner (including
11837    calls to other builtin functions).
11838
11839    The call may contain arguments which need to be evaluated, but
11840    which are not useful to determine the result of the call.  In
11841    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11842    COMPOUND_EXPR will be an argument which must be evaluated.
11843    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11844    COMPOUND_EXPR in the chain will contain the tree for the simplified
11845    form of the builtin function call.  */
11846
11847 static tree
11848 fold_builtin_strcspn (location_t loc, tree s1, tree s2)
11849 {
11850   if (!validate_arg (s1, POINTER_TYPE)
11851       || !validate_arg (s2, POINTER_TYPE))
11852     return NULL_TREE;
11853   else
11854     {
11855       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
11856
11857       /* If both arguments are constants, evaluate at compile-time.  */
11858       if (p1 && p2)
11859         {
11860           const size_t r = strcspn (p1, p2);
11861           return build_int_cst (size_type_node, r);
11862         }
11863
11864       /* If the first argument is "", return NULL_TREE.  */
11865       if (p1 && *p1 == '\0')
11866         {
11867           /* Evaluate and ignore argument s2 in case it has
11868              side-effects.  */
11869           return omit_one_operand_loc (loc, size_type_node,
11870                                    size_zero_node, s2);
11871         }
11872
11873       /* If the second argument is "", return __builtin_strlen(s1).  */
11874       if (p2 && *p2 == '\0')
11875         {
11876           tree fn = builtin_decl_implicit (BUILT_IN_STRLEN);
11877
11878           /* If the replacement _DECL isn't initialized, don't do the
11879              transformation.  */
11880           if (!fn)
11881             return NULL_TREE;
11882
11883           return build_call_expr_loc (loc, fn, 1, s1);
11884         }
11885       return NULL_TREE;
11886     }
11887 }
11888
11889 /* Fold a call to the fputs builtin.  ARG0 and ARG1 are the arguments
11890    to the call.  IGNORE is true if the value returned
11891    by the builtin will be ignored.  UNLOCKED is true is true if this
11892    actually a call to fputs_unlocked.  If LEN in non-NULL, it represents
11893    the known length of the string.  Return NULL_TREE if no simplification
11894    was possible.  */
11895
11896 tree
11897 fold_builtin_fputs (location_t loc, tree arg0, tree arg1,
11898                     bool ignore, bool unlocked, tree len)
11899 {
11900   /* If we're using an unlocked function, assume the other unlocked
11901      functions exist explicitly.  */
11902   tree const fn_fputc = (unlocked
11903                          ? builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED)
11904                          : builtin_decl_implicit (BUILT_IN_FPUTC));
11905   tree const fn_fwrite = (unlocked
11906                           ? builtin_decl_explicit (BUILT_IN_FWRITE_UNLOCKED)
11907                           : builtin_decl_implicit (BUILT_IN_FWRITE));
11908
11909   /* If the return value is used, don't do the transformation.  */
11910   if (!ignore)
11911     return NULL_TREE;
11912
11913   /* Verify the arguments in the original call.  */
11914   if (!validate_arg (arg0, POINTER_TYPE)
11915       || !validate_arg (arg1, POINTER_TYPE))
11916     return NULL_TREE;
11917
11918   if (! len)
11919     len = c_strlen (arg0, 0);
11920
11921   /* Get the length of the string passed to fputs.  If the length
11922      can't be determined, punt.  */
11923   if (!len
11924       || TREE_CODE (len) != INTEGER_CST)
11925     return NULL_TREE;
11926
11927   switch (compare_tree_int (len, 1))
11928     {
11929     case -1: /* length is 0, delete the call entirely .  */
11930       return omit_one_operand_loc (loc, integer_type_node,
11931                                integer_zero_node, arg1);;
11932
11933     case 0: /* length is 1, call fputc.  */
11934       {
11935         const char *p = c_getstr (arg0);
11936
11937         if (p != NULL)
11938           {
11939             if (fn_fputc)
11940               return build_call_expr_loc (loc, fn_fputc, 2,
11941                                           build_int_cst
11942                                             (integer_type_node, p[0]), arg1);
11943             else
11944               return NULL_TREE;
11945           }
11946       }
11947       /* FALLTHROUGH */
11948     case 1: /* length is greater than 1, call fwrite.  */
11949       {
11950         /* If optimizing for size keep fputs.  */
11951         if (optimize_function_for_size_p (cfun))
11952           return NULL_TREE;
11953         /* New argument list transforming fputs(string, stream) to
11954            fwrite(string, 1, len, stream).  */
11955         if (fn_fwrite)
11956           return build_call_expr_loc (loc, fn_fwrite, 4, arg0,
11957                                   size_one_node, len, arg1);
11958         else
11959           return NULL_TREE;
11960       }
11961     default:
11962       gcc_unreachable ();
11963     }
11964   return NULL_TREE;
11965 }
11966
11967 /* Fold the next_arg or va_start call EXP. Returns true if there was an error
11968    produced.  False otherwise.  This is done so that we don't output the error
11969    or warning twice or three times.  */
11970
11971 bool
11972 fold_builtin_next_arg (tree exp, bool va_start_p)
11973 {
11974   tree fntype = TREE_TYPE (current_function_decl);
11975   int nargs = call_expr_nargs (exp);
11976   tree arg;
11977   /* There is good chance the current input_location points inside the
11978      definition of the va_start macro (perhaps on the token for
11979      builtin) in a system header, so warnings will not be emitted.
11980      Use the location in real source code.  */
11981   source_location current_location =
11982     linemap_unwind_to_first_non_reserved_loc (line_table, input_location,
11983                                               NULL);
11984
11985   if (!stdarg_p (fntype))
11986     {
11987       error ("%<va_start%> used in function with fixed args");
11988       return true;
11989     }
11990
11991   if (va_start_p)
11992     {
11993       if (va_start_p && (nargs != 2))
11994         {
11995           error ("wrong number of arguments to function %<va_start%>");
11996           return true;
11997         }
11998       arg = CALL_EXPR_ARG (exp, 1);
11999     }
12000   /* We use __builtin_va_start (ap, 0, 0) or __builtin_next_arg (0, 0)
12001      when we checked the arguments and if needed issued a warning.  */
12002   else
12003     {
12004       if (nargs == 0)
12005         {
12006           /* Evidently an out of date version of <stdarg.h>; can't validate
12007              va_start's second argument, but can still work as intended.  */
12008           warning_at (current_location,
12009                       OPT_Wvarargs,
12010                    "%<__builtin_next_arg%> called without an argument");
12011           return true;
12012         }
12013       else if (nargs > 1)
12014         {
12015           error ("wrong number of arguments to function %<__builtin_next_arg%>");
12016           return true;
12017         }
12018       arg = CALL_EXPR_ARG (exp, 0);
12019     }
12020
12021   if (TREE_CODE (arg) == SSA_NAME)
12022     arg = SSA_NAME_VAR (arg);
12023
12024   /* We destructively modify the call to be __builtin_va_start (ap, 0)
12025      or __builtin_next_arg (0) the first time we see it, after checking
12026      the arguments and if needed issuing a warning.  */
12027   if (!integer_zerop (arg))
12028     {
12029       tree last_parm = tree_last (DECL_ARGUMENTS (current_function_decl));
12030
12031       /* Strip off all nops for the sake of the comparison.  This
12032          is not quite the same as STRIP_NOPS.  It does more.
12033          We must also strip off INDIRECT_EXPR for C++ reference
12034          parameters.  */
12035       while (CONVERT_EXPR_P (arg)
12036              || TREE_CODE (arg) == INDIRECT_REF)
12037         arg = TREE_OPERAND (arg, 0);
12038       if (arg != last_parm)
12039         {
12040           /* FIXME: Sometimes with the tree optimizers we can get the
12041              not the last argument even though the user used the last
12042              argument.  We just warn and set the arg to be the last
12043              argument so that we will get wrong-code because of
12044              it.  */
12045           warning_at (current_location,
12046                       OPT_Wvarargs,
12047                       "second parameter of %<va_start%> not last named argument");
12048         }
12049
12050       /* Undefined by C99 7.15.1.4p4 (va_start):
12051          "If the parameter parmN is declared with the register storage
12052          class, with a function or array type, or with a type that is
12053          not compatible with the type that results after application of
12054          the default argument promotions, the behavior is undefined."
12055       */
12056       else if (DECL_REGISTER (arg))
12057         {
12058           warning_at (current_location,
12059                       OPT_Wvarargs,
12060                       "undefined behaviour when second parameter of "
12061                       "%<va_start%> is declared with %<register%> storage");
12062         }
12063
12064       /* We want to verify the second parameter just once before the tree
12065          optimizers are run and then avoid keeping it in the tree,
12066          as otherwise we could warn even for correct code like:
12067          void foo (int i, ...)
12068          { va_list ap; i++; va_start (ap, i); va_end (ap); }  */
12069       if (va_start_p)
12070         CALL_EXPR_ARG (exp, 1) = integer_zero_node;
12071       else
12072         CALL_EXPR_ARG (exp, 0) = integer_zero_node;
12073     }
12074   return false;
12075 }
12076
12077
12078 /* Simplify a call to the sprintf builtin with arguments DEST, FMT, and ORIG.
12079    ORIG may be null if this is a 2-argument call.  We don't attempt to
12080    simplify calls with more than 3 arguments.
12081
12082    Return NULL_TREE if no simplification was possible, otherwise return the
12083    simplified form of the call as a tree.  If IGNORED is true, it means that
12084    the caller does not use the returned value of the function.  */
12085
12086 static tree
12087 fold_builtin_sprintf (location_t loc, tree dest, tree fmt,
12088                       tree orig, int ignored)
12089 {
12090   tree call, retval;
12091   const char *fmt_str = NULL;
12092
12093   /* Verify the required arguments in the original call.  We deal with two
12094      types of sprintf() calls: 'sprintf (str, fmt)' and
12095      'sprintf (dest, "%s", orig)'.  */
12096   if (!validate_arg (dest, POINTER_TYPE)
12097       || !validate_arg (fmt, POINTER_TYPE))
12098     return NULL_TREE;
12099   if (orig && !validate_arg (orig, POINTER_TYPE))
12100     return NULL_TREE;
12101
12102   /* Check whether the format is a literal string constant.  */
12103   fmt_str = c_getstr (fmt);
12104   if (fmt_str == NULL)
12105     return NULL_TREE;
12106
12107   call = NULL_TREE;
12108   retval = NULL_TREE;
12109
12110   if (!init_target_chars ())
12111     return NULL_TREE;
12112
12113   /* If the format doesn't contain % args or %%, use strcpy.  */
12114   if (strchr (fmt_str, target_percent) == NULL)
12115     {
12116       tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
12117
12118       if (!fn)
12119         return NULL_TREE;
12120
12121       /* Don't optimize sprintf (buf, "abc", ptr++).  */
12122       if (orig)
12123         return NULL_TREE;
12124
12125       /* Convert sprintf (str, fmt) into strcpy (str, fmt) when
12126          'format' is known to contain no % formats.  */
12127       call = build_call_expr_loc (loc, fn, 2, dest, fmt);
12128       if (!ignored)
12129         retval = build_int_cst (integer_type_node, strlen (fmt_str));
12130     }
12131
12132   /* If the format is "%s", use strcpy if the result isn't used.  */
12133   else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
12134     {
12135       tree fn;
12136       fn = builtin_decl_implicit (BUILT_IN_STRCPY);
12137
12138       if (!fn)
12139         return NULL_TREE;
12140
12141       /* Don't crash on sprintf (str1, "%s").  */
12142       if (!orig)
12143         return NULL_TREE;
12144
12145       /* Convert sprintf (str1, "%s", str2) into strcpy (str1, str2).  */
12146       if (!ignored)
12147         {
12148           retval = c_strlen (orig, 1);
12149           if (!retval || TREE_CODE (retval) != INTEGER_CST)
12150             return NULL_TREE;
12151         }
12152       call = build_call_expr_loc (loc, fn, 2, dest, orig);
12153     }
12154
12155   if (call && retval)
12156     {
12157       retval = fold_convert_loc
12158         (loc, TREE_TYPE (TREE_TYPE (builtin_decl_implicit (BUILT_IN_SPRINTF))),
12159          retval);
12160       return build2 (COMPOUND_EXPR, TREE_TYPE (retval), call, retval);
12161     }
12162   else
12163     return call;
12164 }
12165
12166 /* Simplify a call to the snprintf builtin with arguments DEST, DESTSIZE,
12167    FMT, and ORIG.  ORIG may be null if this is a 3-argument call.  We don't
12168    attempt to simplify calls with more than 4 arguments.
12169
12170    Return NULL_TREE if no simplification was possible, otherwise return the
12171    simplified form of the call as a tree.  If IGNORED is true, it means that
12172    the caller does not use the returned value of the function.  */
12173
12174 static tree
12175 fold_builtin_snprintf (location_t loc, tree dest, tree destsize, tree fmt,
12176                        tree orig, int ignored)
12177 {
12178   tree call, retval;
12179   const char *fmt_str = NULL;
12180   unsigned HOST_WIDE_INT destlen;
12181
12182   /* Verify the required arguments in the original call.  We deal with two
12183      types of snprintf() calls: 'snprintf (str, cst, fmt)' and
12184      'snprintf (dest, cst, "%s", orig)'.  */
12185   if (!validate_arg (dest, POINTER_TYPE)
12186       || !validate_arg (destsize, INTEGER_TYPE)
12187       || !validate_arg (fmt, POINTER_TYPE))
12188     return NULL_TREE;
12189   if (orig && !validate_arg (orig, POINTER_TYPE))
12190     return NULL_TREE;
12191
12192   if (!host_integerp (destsize, 1))
12193     return NULL_TREE;
12194
12195   /* Check whether the format is a literal string constant.  */
12196   fmt_str = c_getstr (fmt);
12197   if (fmt_str == NULL)
12198     return NULL_TREE;
12199
12200   call = NULL_TREE;
12201   retval = NULL_TREE;
12202
12203   if (!init_target_chars ())
12204     return NULL_TREE;
12205
12206   destlen = tree_low_cst (destsize, 1);
12207
12208   /* If the format doesn't contain % args or %%, use strcpy.  */
12209   if (strchr (fmt_str, target_percent) == NULL)
12210     {
12211       tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
12212       size_t len = strlen (fmt_str);
12213
12214       /* Don't optimize snprintf (buf, 4, "abc", ptr++).  */
12215       if (orig)
12216         return NULL_TREE;
12217
12218       /* We could expand this as
12219          memcpy (str, fmt, cst - 1); str[cst - 1] = '\0';
12220          or to
12221          memcpy (str, fmt_with_nul_at_cstm1, cst);
12222          but in the former case that might increase code size
12223          and in the latter case grow .rodata section too much.
12224          So punt for now.  */
12225       if (len >= destlen)
12226         return NULL_TREE;
12227
12228       if (!fn)
12229         return NULL_TREE;
12230
12231       /* Convert snprintf (str, cst, fmt) into strcpy (str, fmt) when
12232          'format' is known to contain no % formats and
12233          strlen (fmt) < cst.  */
12234       call = build_call_expr_loc (loc, fn, 2, dest, fmt);
12235
12236       if (!ignored)
12237         retval = build_int_cst (integer_type_node, strlen (fmt_str));
12238     }
12239
12240   /* If the format is "%s", use strcpy if the result isn't used.  */
12241   else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
12242     {
12243       tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
12244       unsigned HOST_WIDE_INT origlen;
12245
12246       /* Don't crash on snprintf (str1, cst, "%s").  */
12247       if (!orig)
12248         return NULL_TREE;
12249
12250       retval = c_strlen (orig, 1);
12251       if (!retval || !host_integerp (retval, 1))  
12252         return NULL_TREE;
12253
12254       origlen = tree_low_cst (retval, 1);
12255       /* We could expand this as
12256          memcpy (str1, str2, cst - 1); str1[cst - 1] = '\0';
12257          or to
12258          memcpy (str1, str2_with_nul_at_cstm1, cst);
12259          but in the former case that might increase code size
12260          and in the latter case grow .rodata section too much.
12261          So punt for now.  */
12262       if (origlen >= destlen)
12263         return NULL_TREE;
12264
12265       /* Convert snprintf (str1, cst, "%s", str2) into
12266          strcpy (str1, str2) if strlen (str2) < cst.  */
12267       if (!fn)
12268         return NULL_TREE;
12269
12270       call = build_call_expr_loc (loc, fn, 2, dest, orig);
12271
12272       if (ignored)
12273         retval = NULL_TREE;
12274     }
12275
12276   if (call && retval)
12277     {
12278       tree fn = builtin_decl_explicit (BUILT_IN_SNPRINTF);
12279       retval = fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fn)), retval);
12280       return build2 (COMPOUND_EXPR, TREE_TYPE (retval), call, retval);
12281     }
12282   else
12283     return call;
12284 }
12285
12286 /* Expand a call EXP to __builtin_object_size.  */
12287
12288 rtx
12289 expand_builtin_object_size (tree exp)
12290 {
12291   tree ost;
12292   int object_size_type;
12293   tree fndecl = get_callee_fndecl (exp);
12294
12295   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
12296     {
12297       error ("%Kfirst argument of %D must be a pointer, second integer constant",
12298              exp, fndecl);
12299       expand_builtin_trap ();
12300       return const0_rtx;
12301     }
12302
12303   ost = CALL_EXPR_ARG (exp, 1);
12304   STRIP_NOPS (ost);
12305
12306   if (TREE_CODE (ost) != INTEGER_CST
12307       || tree_int_cst_sgn (ost) < 0
12308       || compare_tree_int (ost, 3) > 0)
12309     {
12310       error ("%Klast argument of %D is not integer constant between 0 and 3",
12311              exp, fndecl);
12312       expand_builtin_trap ();
12313       return const0_rtx;
12314     }
12315
12316   object_size_type = tree_low_cst (ost, 0);
12317
12318   return object_size_type < 2 ? constm1_rtx : const0_rtx;
12319 }
12320
12321 /* Expand EXP, a call to the __mem{cpy,pcpy,move,set}_chk builtin.
12322    FCODE is the BUILT_IN_* to use.
12323    Return NULL_RTX if we failed; the caller should emit a normal call,
12324    otherwise try to get the result in TARGET, if convenient (and in
12325    mode MODE if that's convenient).  */
12326
12327 static rtx
12328 expand_builtin_memory_chk (tree exp, rtx target, enum machine_mode mode,
12329                            enum built_in_function fcode)
12330 {
12331   tree dest, src, len, size;
12332
12333   if (!validate_arglist (exp,
12334                          POINTER_TYPE,
12335                          fcode == BUILT_IN_MEMSET_CHK
12336                          ? INTEGER_TYPE : POINTER_TYPE,
12337                          INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
12338     return NULL_RTX;
12339
12340   dest = CALL_EXPR_ARG (exp, 0);
12341   src = CALL_EXPR_ARG (exp, 1);
12342   len = CALL_EXPR_ARG (exp, 2);
12343   size = CALL_EXPR_ARG (exp, 3);
12344
12345   if (! host_integerp (size, 1))
12346     return NULL_RTX;
12347
12348   if (host_integerp (len, 1) || integer_all_onesp (size))
12349     {
12350       tree fn;
12351
12352       if (! integer_all_onesp (size) && tree_int_cst_lt (size, len))
12353         {
12354           warning_at (tree_nonartificial_location (exp),
12355                       0, "%Kcall to %D will always overflow destination buffer",
12356                       exp, get_callee_fndecl (exp));
12357           return NULL_RTX;
12358         }
12359
12360       fn = NULL_TREE;
12361       /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
12362          mem{cpy,pcpy,move,set} is available.  */
12363       switch (fcode)
12364         {
12365         case BUILT_IN_MEMCPY_CHK:
12366           fn = builtin_decl_explicit (BUILT_IN_MEMCPY);
12367           break;
12368         case BUILT_IN_MEMPCPY_CHK:
12369           fn = builtin_decl_explicit (BUILT_IN_MEMPCPY);
12370           break;
12371         case BUILT_IN_MEMMOVE_CHK:
12372           fn = builtin_decl_explicit (BUILT_IN_MEMMOVE);
12373           break;
12374         case BUILT_IN_MEMSET_CHK:
12375           fn = builtin_decl_explicit (BUILT_IN_MEMSET);
12376           break;
12377         default:
12378           break;
12379         }
12380
12381       if (! fn)
12382         return NULL_RTX;
12383
12384       fn = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 3, dest, src, len);
12385       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
12386       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
12387       return expand_expr (fn, target, mode, EXPAND_NORMAL);
12388     }
12389   else if (fcode == BUILT_IN_MEMSET_CHK)
12390     return NULL_RTX;
12391   else
12392     {
12393       unsigned int dest_align = get_pointer_alignment (dest);
12394
12395       /* If DEST is not a pointer type, call the normal function.  */
12396       if (dest_align == 0)
12397         return NULL_RTX;
12398
12399       /* If SRC and DEST are the same (and not volatile), do nothing.  */
12400       if (operand_equal_p (src, dest, 0))
12401         {
12402           tree expr;
12403
12404           if (fcode != BUILT_IN_MEMPCPY_CHK)
12405             {
12406               /* Evaluate and ignore LEN in case it has side-effects.  */
12407               expand_expr (len, const0_rtx, VOIDmode, EXPAND_NORMAL);
12408               return expand_expr (dest, target, mode, EXPAND_NORMAL);
12409             }
12410
12411           expr = fold_build_pointer_plus (dest, len);
12412           return expand_expr (expr, target, mode, EXPAND_NORMAL);
12413         }
12414
12415       /* __memmove_chk special case.  */
12416       if (fcode == BUILT_IN_MEMMOVE_CHK)
12417         {
12418           unsigned int src_align = get_pointer_alignment (src);
12419
12420           if (src_align == 0)
12421             return NULL_RTX;
12422
12423           /* If src is categorized for a readonly section we can use
12424              normal __memcpy_chk.  */
12425           if (readonly_data_expr (src))
12426             {
12427               tree fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
12428               if (!fn)
12429                 return NULL_RTX;
12430               fn = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 4,
12431                                           dest, src, len, size);
12432               gcc_assert (TREE_CODE (fn) == CALL_EXPR);
12433               CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
12434               return expand_expr (fn, target, mode, EXPAND_NORMAL);
12435             }
12436         }
12437       return NULL_RTX;
12438     }
12439 }
12440
12441 /* Emit warning if a buffer overflow is detected at compile time.  */
12442
12443 static void
12444 maybe_emit_chk_warning (tree exp, enum built_in_function fcode)
12445 {
12446   int is_strlen = 0;
12447   tree len, size;
12448   location_t loc = tree_nonartificial_location (exp);
12449
12450   switch (fcode)
12451     {
12452     case BUILT_IN_STRCPY_CHK:
12453     case BUILT_IN_STPCPY_CHK:
12454     /* For __strcat_chk the warning will be emitted only if overflowing
12455        by at least strlen (dest) + 1 bytes.  */
12456     case BUILT_IN_STRCAT_CHK:
12457       len = CALL_EXPR_ARG (exp, 1);
12458       size = CALL_EXPR_ARG (exp, 2);
12459       is_strlen = 1;
12460       break;
12461     case BUILT_IN_STRNCAT_CHK:
12462     case BUILT_IN_STRNCPY_CHK:
12463     case BUILT_IN_STPNCPY_CHK:
12464       len = CALL_EXPR_ARG (exp, 2);
12465       size = CALL_EXPR_ARG (exp, 3);
12466       break;
12467     case BUILT_IN_SNPRINTF_CHK:
12468     case BUILT_IN_VSNPRINTF_CHK:
12469       len = CALL_EXPR_ARG (exp, 1);
12470       size = CALL_EXPR_ARG (exp, 3);
12471       break;
12472     default:
12473       gcc_unreachable ();
12474     }
12475
12476   if (!len || !size)
12477     return;
12478
12479   if (! host_integerp (size, 1) || integer_all_onesp (size))
12480     return;
12481
12482   if (is_strlen)
12483     {
12484       len = c_strlen (len, 1);
12485       if (! len || ! host_integerp (len, 1) || tree_int_cst_lt (len, size))
12486         return;
12487     }
12488   else if (fcode == BUILT_IN_STRNCAT_CHK)
12489     {
12490       tree src = CALL_EXPR_ARG (exp, 1);
12491       if (! src || ! host_integerp (len, 1) || tree_int_cst_lt (len, size))
12492         return;
12493       src = c_strlen (src, 1);
12494       if (! src || ! host_integerp (src, 1))
12495         {
12496           warning_at (loc, 0, "%Kcall to %D might overflow destination buffer",
12497                       exp, get_callee_fndecl (exp));
12498           return;
12499         }
12500       else if (tree_int_cst_lt (src, size))
12501         return;
12502     }
12503   else if (! host_integerp (len, 1) || ! tree_int_cst_lt (size, len))
12504     return;
12505
12506   warning_at (loc, 0, "%Kcall to %D will always overflow destination buffer",
12507               exp, get_callee_fndecl (exp));
12508 }
12509
12510 /* Emit warning if a buffer overflow is detected at compile time
12511    in __sprintf_chk/__vsprintf_chk calls.  */
12512
12513 static void
12514 maybe_emit_sprintf_chk_warning (tree exp, enum built_in_function fcode)
12515 {
12516   tree size, len, fmt;
12517   const char *fmt_str;
12518   int nargs = call_expr_nargs (exp);
12519
12520   /* Verify the required arguments in the original call.  */
12521
12522   if (nargs < 4)
12523     return;
12524   size = CALL_EXPR_ARG (exp, 2);
12525   fmt = CALL_EXPR_ARG (exp, 3);
12526
12527   if (! host_integerp (size, 1) || integer_all_onesp (size))
12528     return;
12529
12530   /* Check whether the format is a literal string constant.  */
12531   fmt_str = c_getstr (fmt);
12532   if (fmt_str == NULL)
12533     return;
12534
12535   if (!init_target_chars ())
12536     return;
12537
12538   /* If the format doesn't contain % args or %%, we know its size.  */
12539   if (strchr (fmt_str, target_percent) == 0)
12540     len = build_int_cstu (size_type_node, strlen (fmt_str));
12541   /* If the format is "%s" and first ... argument is a string literal,
12542      we know it too.  */
12543   else if (fcode == BUILT_IN_SPRINTF_CHK
12544            && strcmp (fmt_str, target_percent_s) == 0)
12545     {
12546       tree arg;
12547
12548       if (nargs < 5)
12549         return;
12550       arg = CALL_EXPR_ARG (exp, 4);
12551       if (! POINTER_TYPE_P (TREE_TYPE (arg)))
12552         return;
12553
12554       len = c_strlen (arg, 1);
12555       if (!len || ! host_integerp (len, 1))
12556         return;
12557     }
12558   else
12559     return;
12560
12561   if (! tree_int_cst_lt (len, size))
12562     warning_at (tree_nonartificial_location (exp),
12563                 0, "%Kcall to %D will always overflow destination buffer",
12564                 exp, get_callee_fndecl (exp));
12565 }
12566
12567 /* Emit warning if a free is called with address of a variable.  */
12568
12569 static void
12570 maybe_emit_free_warning (tree exp)
12571 {
12572   tree arg = CALL_EXPR_ARG (exp, 0);
12573
12574   STRIP_NOPS (arg);
12575   if (TREE_CODE (arg) != ADDR_EXPR)
12576     return;
12577
12578   arg = get_base_address (TREE_OPERAND (arg, 0));
12579   if (arg == NULL || INDIRECT_REF_P (arg) || TREE_CODE (arg) == MEM_REF)
12580     return;
12581
12582   if (SSA_VAR_P (arg))
12583     warning_at (tree_nonartificial_location (exp), OPT_Wfree_nonheap_object,
12584                 "%Kattempt to free a non-heap object %qD", exp, arg);
12585   else
12586     warning_at (tree_nonartificial_location (exp), OPT_Wfree_nonheap_object,
12587                 "%Kattempt to free a non-heap object", exp);
12588 }
12589
12590 /* Fold a call to __builtin_object_size with arguments PTR and OST,
12591    if possible.  */
12592
12593 tree
12594 fold_builtin_object_size (tree ptr, tree ost)
12595 {
12596   unsigned HOST_WIDE_INT bytes;
12597   int object_size_type;
12598
12599   if (!validate_arg (ptr, POINTER_TYPE)
12600       || !validate_arg (ost, INTEGER_TYPE))
12601     return NULL_TREE;
12602
12603   STRIP_NOPS (ost);
12604
12605   if (TREE_CODE (ost) != INTEGER_CST
12606       || tree_int_cst_sgn (ost) < 0
12607       || compare_tree_int (ost, 3) > 0)
12608     return NULL_TREE;
12609
12610   object_size_type = tree_low_cst (ost, 0);
12611
12612   /* __builtin_object_size doesn't evaluate side-effects in its arguments;
12613      if there are any side-effects, it returns (size_t) -1 for types 0 and 1
12614      and (size_t) 0 for types 2 and 3.  */
12615   if (TREE_SIDE_EFFECTS (ptr))
12616     return build_int_cst_type (size_type_node, object_size_type < 2 ? -1 : 0);
12617
12618   if (TREE_CODE (ptr) == ADDR_EXPR)
12619     {
12620       bytes = compute_builtin_object_size (ptr, object_size_type);
12621       if (double_int_fits_to_tree_p (size_type_node,
12622                                      double_int::from_uhwi (bytes)))
12623         return build_int_cstu (size_type_node, bytes);
12624     }
12625   else if (TREE_CODE (ptr) == SSA_NAME)
12626     {
12627       /* If object size is not known yet, delay folding until
12628        later.  Maybe subsequent passes will help determining
12629        it.  */
12630       bytes = compute_builtin_object_size (ptr, object_size_type);
12631       if (bytes != (unsigned HOST_WIDE_INT) (object_size_type < 2 ? -1 : 0)
12632           && double_int_fits_to_tree_p (size_type_node,
12633                                         double_int::from_uhwi (bytes)))
12634         return build_int_cstu (size_type_node, bytes);
12635     }
12636
12637   return NULL_TREE;
12638 }
12639
12640 /* Fold a call to the __mem{cpy,pcpy,move,set}_chk builtin.
12641    DEST, SRC, LEN, and SIZE are the arguments to the call.
12642    IGNORE is true, if return value can be ignored.  FCODE is the BUILT_IN_*
12643    code of the builtin.  If MAXLEN is not NULL, it is maximum length
12644    passed as third argument.  */
12645
12646 tree
12647 fold_builtin_memory_chk (location_t loc, tree fndecl,
12648                          tree dest, tree src, tree len, tree size,
12649                          tree maxlen, bool ignore,
12650                          enum built_in_function fcode)
12651 {
12652   tree fn;
12653
12654   if (!validate_arg (dest, POINTER_TYPE)
12655       || !validate_arg (src,
12656                         (fcode == BUILT_IN_MEMSET_CHK
12657                          ? INTEGER_TYPE : POINTER_TYPE))
12658       || !validate_arg (len, INTEGER_TYPE)
12659       || !validate_arg (size, INTEGER_TYPE))
12660     return NULL_TREE;
12661
12662   /* If SRC and DEST are the same (and not volatile), return DEST
12663      (resp. DEST+LEN for __mempcpy_chk).  */
12664   if (fcode != BUILT_IN_MEMSET_CHK && operand_equal_p (src, dest, 0))
12665     {
12666       if (fcode != BUILT_IN_MEMPCPY_CHK)
12667         return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
12668                                  dest, len);
12669       else
12670         {
12671           tree temp = fold_build_pointer_plus_loc (loc, dest, len);
12672           return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), temp);
12673         }
12674     }
12675
12676   if (! host_integerp (size, 1))
12677     return NULL_TREE;
12678
12679   if (! integer_all_onesp (size))
12680     {
12681       if (! host_integerp (len, 1))
12682         {
12683           /* If LEN is not constant, try MAXLEN too.
12684              For MAXLEN only allow optimizing into non-_ocs function
12685              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12686           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12687             {
12688               if (fcode == BUILT_IN_MEMPCPY_CHK && ignore)
12689                 {
12690                   /* (void) __mempcpy_chk () can be optimized into
12691                      (void) __memcpy_chk ().  */
12692                   fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
12693                   if (!fn)
12694                     return NULL_TREE;
12695
12696                   return build_call_expr_loc (loc, fn, 4, dest, src, len, size);
12697                 }
12698               return NULL_TREE;
12699             }
12700         }
12701       else
12702         maxlen = len;
12703
12704       if (tree_int_cst_lt (size, maxlen))
12705         return NULL_TREE;
12706     }
12707
12708   fn = NULL_TREE;
12709   /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
12710      mem{cpy,pcpy,move,set} is available.  */
12711   switch (fcode)
12712     {
12713     case BUILT_IN_MEMCPY_CHK:
12714       fn = builtin_decl_explicit (BUILT_IN_MEMCPY);
12715       break;
12716     case BUILT_IN_MEMPCPY_CHK:
12717       fn = builtin_decl_explicit (BUILT_IN_MEMPCPY);
12718       break;
12719     case BUILT_IN_MEMMOVE_CHK:
12720       fn = builtin_decl_explicit (BUILT_IN_MEMMOVE);
12721       break;
12722     case BUILT_IN_MEMSET_CHK:
12723       fn = builtin_decl_explicit (BUILT_IN_MEMSET);
12724       break;
12725     default:
12726       break;
12727     }
12728
12729   if (!fn)
12730     return NULL_TREE;
12731
12732   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12733 }
12734
12735 /* Fold a call to the __st[rp]cpy_chk builtin.
12736    DEST, SRC, and SIZE are the arguments to the call.
12737    IGNORE is true if return value can be ignored.  FCODE is the BUILT_IN_*
12738    code of the builtin.  If MAXLEN is not NULL, it is maximum length of
12739    strings passed as second argument.  */
12740
12741 tree
12742 fold_builtin_stxcpy_chk (location_t loc, tree fndecl, tree dest,
12743                          tree src, tree size,
12744                          tree maxlen, bool ignore,
12745                          enum built_in_function fcode)
12746 {
12747   tree len, fn;
12748
12749   if (!validate_arg (dest, POINTER_TYPE)
12750       || !validate_arg (src, POINTER_TYPE)
12751       || !validate_arg (size, INTEGER_TYPE))
12752     return NULL_TREE;
12753
12754   /* If SRC and DEST are the same (and not volatile), return DEST.  */
12755   if (fcode == BUILT_IN_STRCPY_CHK && operand_equal_p (src, dest, 0))
12756     return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest);
12757
12758   if (! host_integerp (size, 1))
12759     return NULL_TREE;
12760
12761   if (! integer_all_onesp (size))
12762     {
12763       len = c_strlen (src, 1);
12764       if (! len || ! host_integerp (len, 1))
12765         {
12766           /* If LEN is not constant, try MAXLEN too.
12767              For MAXLEN only allow optimizing into non-_ocs function
12768              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12769           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12770             {
12771               if (fcode == BUILT_IN_STPCPY_CHK)
12772                 {
12773                   if (! ignore)
12774                     return NULL_TREE;
12775
12776                   /* If return value of __stpcpy_chk is ignored,
12777                      optimize into __strcpy_chk.  */
12778                   fn = builtin_decl_explicit (BUILT_IN_STRCPY_CHK);
12779                   if (!fn)
12780                     return NULL_TREE;
12781
12782                   return build_call_expr_loc (loc, fn, 3, dest, src, size);
12783                 }
12784
12785               if (! len || TREE_SIDE_EFFECTS (len))
12786                 return NULL_TREE;
12787
12788               /* If c_strlen returned something, but not a constant,
12789                  transform __strcpy_chk into __memcpy_chk.  */
12790               fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
12791               if (!fn)
12792                 return NULL_TREE;
12793
12794               len = fold_convert_loc (loc, size_type_node, len);
12795               len = size_binop_loc (loc, PLUS_EXPR, len,
12796                                     build_int_cst (size_type_node, 1));
12797               return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
12798                                        build_call_expr_loc (loc, fn, 4,
12799                                                         dest, src, len, size));
12800             }
12801         }
12802       else
12803         maxlen = len;
12804
12805       if (! tree_int_cst_lt (maxlen, size))
12806         return NULL_TREE;
12807     }
12808
12809   /* If __builtin_st{r,p}cpy_chk is used, assume st{r,p}cpy is available.  */
12810   fn = builtin_decl_explicit (fcode == BUILT_IN_STPCPY_CHK
12811                               ? BUILT_IN_STPCPY : BUILT_IN_STRCPY);
12812   if (!fn)
12813     return NULL_TREE;
12814
12815   return build_call_expr_loc (loc, fn, 2, dest, src);
12816 }
12817
12818 /* Fold a call to the __st{r,p}ncpy_chk builtin.  DEST, SRC, LEN, and SIZE
12819    are the arguments to the call.  If MAXLEN is not NULL, it is maximum
12820    length passed as third argument. IGNORE is true if return value can be
12821    ignored. FCODE is the BUILT_IN_* code of the builtin. */
12822
12823 tree
12824 fold_builtin_stxncpy_chk (location_t loc, tree dest, tree src,
12825                           tree len, tree size, tree maxlen, bool ignore,
12826                           enum built_in_function fcode)
12827 {
12828   tree fn;
12829
12830   if (!validate_arg (dest, POINTER_TYPE)
12831       || !validate_arg (src, POINTER_TYPE)
12832       || !validate_arg (len, INTEGER_TYPE)
12833       || !validate_arg (size, INTEGER_TYPE))
12834     return NULL_TREE;
12835
12836   if (fcode == BUILT_IN_STPNCPY_CHK && ignore)
12837     {
12838        /* If return value of __stpncpy_chk is ignored,
12839           optimize into __strncpy_chk.  */
12840        fn = builtin_decl_explicit (BUILT_IN_STRNCPY_CHK);
12841        if (fn)
12842          return build_call_expr_loc (loc, fn, 4, dest, src, len, size);
12843     }
12844
12845   if (! host_integerp (size, 1))
12846     return NULL_TREE;
12847
12848   if (! integer_all_onesp (size))
12849     {
12850       if (! host_integerp (len, 1))
12851         {
12852           /* If LEN is not constant, try MAXLEN too.
12853              For MAXLEN only allow optimizing into non-_ocs function
12854              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12855           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12856             return NULL_TREE;
12857         }
12858       else
12859         maxlen = len;
12860
12861       if (tree_int_cst_lt (size, maxlen))
12862         return NULL_TREE;
12863     }
12864
12865   /* If __builtin_st{r,p}ncpy_chk is used, assume st{r,p}ncpy is available.  */
12866   fn = builtin_decl_explicit (fcode == BUILT_IN_STPNCPY_CHK
12867                               ? BUILT_IN_STPNCPY : BUILT_IN_STRNCPY);
12868   if (!fn)
12869     return NULL_TREE;
12870
12871   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12872 }
12873
12874 /* Fold a call to the __strcat_chk builtin FNDECL.  DEST, SRC, and SIZE
12875    are the arguments to the call.  */
12876
12877 static tree
12878 fold_builtin_strcat_chk (location_t loc, tree fndecl, tree dest,
12879                          tree src, tree size)
12880 {
12881   tree fn;
12882   const char *p;
12883
12884   if (!validate_arg (dest, POINTER_TYPE)
12885       || !validate_arg (src, POINTER_TYPE)
12886       || !validate_arg (size, INTEGER_TYPE))
12887     return NULL_TREE;
12888
12889   p = c_getstr (src);
12890   /* If the SRC parameter is "", return DEST.  */
12891   if (p && *p == '\0')
12892     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
12893
12894   if (! host_integerp (size, 1) || ! integer_all_onesp (size))
12895     return NULL_TREE;
12896
12897   /* If __builtin_strcat_chk is used, assume strcat is available.  */
12898   fn = builtin_decl_explicit (BUILT_IN_STRCAT);
12899   if (!fn)
12900     return NULL_TREE;
12901
12902   return build_call_expr_loc (loc, fn, 2, dest, src);
12903 }
12904
12905 /* Fold a call to the __strncat_chk builtin with arguments DEST, SRC,
12906    LEN, and SIZE.  */
12907
12908 static tree
12909 fold_builtin_strncat_chk (location_t loc, tree fndecl,
12910                           tree dest, tree src, tree len, tree size)
12911 {
12912   tree fn;
12913   const char *p;
12914
12915   if (!validate_arg (dest, POINTER_TYPE)
12916       || !validate_arg (src, POINTER_TYPE)
12917       || !validate_arg (size, INTEGER_TYPE)
12918       || !validate_arg (size, INTEGER_TYPE))
12919     return NULL_TREE;
12920
12921   p = c_getstr (src);
12922   /* If the SRC parameter is "" or if LEN is 0, return DEST.  */
12923   if (p && *p == '\0')
12924     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, len);
12925   else if (integer_zerop (len))
12926     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
12927
12928   if (! host_integerp (size, 1))
12929     return NULL_TREE;
12930
12931   if (! integer_all_onesp (size))
12932     {
12933       tree src_len = c_strlen (src, 1);
12934       if (src_len
12935           && host_integerp (src_len, 1)
12936           && host_integerp (len, 1)
12937           && ! tree_int_cst_lt (len, src_len))
12938         {
12939           /* If LEN >= strlen (SRC), optimize into __strcat_chk.  */
12940           fn = builtin_decl_explicit (BUILT_IN_STRCAT_CHK);
12941           if (!fn)
12942             return NULL_TREE;
12943
12944           return build_call_expr_loc (loc, fn, 3, dest, src, size);
12945         }
12946       return NULL_TREE;
12947     }
12948
12949   /* If __builtin_strncat_chk is used, assume strncat is available.  */
12950   fn = builtin_decl_explicit (BUILT_IN_STRNCAT);
12951   if (!fn)
12952     return NULL_TREE;
12953
12954   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12955 }
12956
12957 /* Fold a call EXP to __{,v}sprintf_chk having NARGS passed as ARGS.
12958    Return NULL_TREE if a normal call should be emitted rather than
12959    expanding the function inline.  FCODE is either BUILT_IN_SPRINTF_CHK
12960    or BUILT_IN_VSPRINTF_CHK.  */
12961
12962 static tree
12963 fold_builtin_sprintf_chk_1 (location_t loc, int nargs, tree *args,
12964                             enum built_in_function fcode)
12965 {
12966   tree dest, size, len, fn, fmt, flag;
12967   const char *fmt_str;
12968
12969   /* Verify the required arguments in the original call.  */
12970   if (nargs < 4)
12971     return NULL_TREE;
12972   dest = args[0];
12973   if (!validate_arg (dest, POINTER_TYPE))
12974     return NULL_TREE;
12975   flag = args[1];
12976   if (!validate_arg (flag, INTEGER_TYPE))
12977     return NULL_TREE;
12978   size = args[2];
12979   if (!validate_arg (size, INTEGER_TYPE))
12980     return NULL_TREE;
12981   fmt = args[3];
12982   if (!validate_arg (fmt, POINTER_TYPE))
12983     return NULL_TREE;
12984
12985   if (! host_integerp (size, 1))
12986     return NULL_TREE;
12987
12988   len = NULL_TREE;
12989
12990   if (!init_target_chars ())
12991     return NULL_TREE;
12992
12993   /* Check whether the format is a literal string constant.  */
12994   fmt_str = c_getstr (fmt);
12995   if (fmt_str != NULL)
12996     {
12997       /* If the format doesn't contain % args or %%, we know the size.  */
12998       if (strchr (fmt_str, target_percent) == 0)
12999         {
13000           if (fcode != BUILT_IN_SPRINTF_CHK || nargs == 4)
13001             len = build_int_cstu (size_type_node, strlen (fmt_str));
13002         }
13003       /* If the format is "%s" and first ... argument is a string literal,
13004          we know the size too.  */
13005       else if (fcode == BUILT_IN_SPRINTF_CHK
13006                && strcmp (fmt_str, target_percent_s) == 0)
13007         {
13008           tree arg;
13009
13010           if (nargs == 5)
13011             {
13012               arg = args[4];
13013               if (validate_arg (arg, POINTER_TYPE))
13014                 {
13015                   len = c_strlen (arg, 1);
13016                   if (! len || ! host_integerp (len, 1))
13017                     len = NULL_TREE;
13018                 }
13019             }
13020         }
13021     }
13022
13023   if (! integer_all_onesp (size))
13024     {
13025       if (! len || ! tree_int_cst_lt (len, size))
13026         return NULL_TREE;
13027     }
13028
13029   /* Only convert __{,v}sprintf_chk to {,v}sprintf if flag is 0
13030      or if format doesn't contain % chars or is "%s".  */
13031   if (! integer_zerop (flag))
13032     {
13033       if (fmt_str == NULL)
13034         return NULL_TREE;
13035       if (strchr (fmt_str, target_percent) != NULL
13036           && strcmp (fmt_str, target_percent_s))
13037         return NULL_TREE;
13038     }
13039
13040   /* If __builtin_{,v}sprintf_chk is used, assume {,v}sprintf is available.  */
13041   fn = builtin_decl_explicit (fcode == BUILT_IN_VSPRINTF_CHK
13042                               ? BUILT_IN_VSPRINTF : BUILT_IN_SPRINTF);
13043   if (!fn)
13044     return NULL_TREE;
13045
13046   return rewrite_call_expr_array (loc, nargs, args, 4, fn, 2, dest, fmt);
13047 }
13048
13049 /* Fold a call EXP to __{,v}sprintf_chk.  Return NULL_TREE if
13050    a normal call should be emitted rather than expanding the function
13051    inline.  FCODE is either BUILT_IN_SPRINTF_CHK or BUILT_IN_VSPRINTF_CHK.  */
13052
13053 static tree
13054 fold_builtin_sprintf_chk (location_t loc, tree exp,
13055                           enum built_in_function fcode)
13056 {
13057   return fold_builtin_sprintf_chk_1 (loc, call_expr_nargs (exp),
13058                                      CALL_EXPR_ARGP (exp), fcode);
13059 }
13060
13061 /* Fold a call EXP to {,v}snprintf having NARGS passed as ARGS.  Return
13062    NULL_TREE if a normal call should be emitted rather than expanding
13063    the function inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
13064    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
13065    passed as second argument.  */
13066
13067 static tree
13068 fold_builtin_snprintf_chk_1 (location_t loc, int nargs, tree *args,
13069                              tree maxlen, enum built_in_function fcode)
13070 {
13071   tree dest, size, len, fn, fmt, flag;
13072   const char *fmt_str;
13073
13074   /* Verify the required arguments in the original call.  */
13075   if (nargs < 5)
13076     return NULL_TREE;
13077   dest = args[0];
13078   if (!validate_arg (dest, POINTER_TYPE))
13079     return NULL_TREE;
13080   len = args[1];
13081   if (!validate_arg (len, INTEGER_TYPE))
13082     return NULL_TREE;
13083   flag = args[2];
13084   if (!validate_arg (flag, INTEGER_TYPE))
13085     return NULL_TREE;
13086   size = args[3];
13087   if (!validate_arg (size, INTEGER_TYPE))
13088     return NULL_TREE;
13089   fmt = args[4];
13090   if (!validate_arg (fmt, POINTER_TYPE))
13091     return NULL_TREE;
13092
13093   if (! host_integerp (size, 1))
13094     return NULL_TREE;
13095
13096   if (! integer_all_onesp (size))
13097     {
13098       if (! host_integerp (len, 1))
13099         {
13100           /* If LEN is not constant, try MAXLEN too.
13101              For MAXLEN only allow optimizing into non-_ocs function
13102              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
13103           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
13104             return NULL_TREE;
13105         }
13106       else
13107         maxlen = len;
13108
13109       if (tree_int_cst_lt (size, maxlen))
13110         return NULL_TREE;
13111     }
13112
13113   if (!init_target_chars ())
13114     return NULL_TREE;
13115
13116   /* Only convert __{,v}snprintf_chk to {,v}snprintf if flag is 0
13117      or if format doesn't contain % chars or is "%s".  */
13118   if (! integer_zerop (flag))
13119     {
13120       fmt_str = c_getstr (fmt);
13121       if (fmt_str == NULL)
13122         return NULL_TREE;
13123       if (strchr (fmt_str, target_percent) != NULL
13124           && strcmp (fmt_str, target_percent_s))
13125         return NULL_TREE;
13126     }
13127
13128   /* If __builtin_{,v}snprintf_chk is used, assume {,v}snprintf is
13129      available.  */
13130   fn = builtin_decl_explicit (fcode == BUILT_IN_VSNPRINTF_CHK
13131                               ? BUILT_IN_VSNPRINTF : BUILT_IN_SNPRINTF);
13132   if (!fn)
13133     return NULL_TREE;
13134
13135   return rewrite_call_expr_array (loc, nargs, args, 5, fn, 3, dest, len, fmt);
13136 }
13137
13138 /* Fold a call EXP to {,v}snprintf.  Return NULL_TREE if
13139    a normal call should be emitted rather than expanding the function
13140    inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
13141    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
13142    passed as second argument.  */
13143
13144 static tree
13145 fold_builtin_snprintf_chk (location_t loc, tree exp, tree maxlen,
13146                            enum built_in_function fcode)
13147 {
13148   return fold_builtin_snprintf_chk_1 (loc, call_expr_nargs (exp),
13149                                       CALL_EXPR_ARGP (exp), maxlen, fcode);
13150 }
13151
13152 /* Builtins with folding operations that operate on "..." arguments
13153    need special handling; we need to store the arguments in a convenient
13154    data structure before attempting any folding.  Fortunately there are
13155    only a few builtins that fall into this category.  FNDECL is the
13156    function, EXP is the CALL_EXPR for the call, and IGNORE is true if the
13157    result of the function call is ignored.  */
13158
13159 static tree
13160 fold_builtin_varargs (location_t loc, tree fndecl, tree exp,
13161                       bool ignore ATTRIBUTE_UNUSED)
13162 {
13163   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
13164   tree ret = NULL_TREE;
13165
13166   switch (fcode)
13167     {
13168     case BUILT_IN_SPRINTF_CHK:
13169     case BUILT_IN_VSPRINTF_CHK:
13170       ret = fold_builtin_sprintf_chk (loc, exp, fcode);
13171       break;
13172
13173     case BUILT_IN_SNPRINTF_CHK:
13174     case BUILT_IN_VSNPRINTF_CHK:
13175       ret = fold_builtin_snprintf_chk (loc, exp, NULL_TREE, fcode);
13176       break;
13177
13178     case BUILT_IN_FPCLASSIFY:
13179       ret = fold_builtin_fpclassify (loc, exp);
13180       break;
13181
13182     default:
13183       break;
13184     }
13185   if (ret)
13186     {
13187       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
13188       SET_EXPR_LOCATION (ret, loc);
13189       TREE_NO_WARNING (ret) = 1;
13190       return ret;
13191     }
13192   return NULL_TREE;
13193 }
13194
13195 /* Fold a call to the {,v}printf{,_unlocked} and __{,v}printf_chk builtins.
13196    FMT and ARG are the arguments to the call; we don't fold cases with
13197    more than 2 arguments, and ARG may be null if this is a 1-argument case.
13198
13199    Return NULL_TREE if no simplification was possible, otherwise return the
13200    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
13201    code of the function to be simplified.  */
13202
13203 static tree
13204 fold_builtin_printf (location_t loc, tree fndecl, tree fmt,
13205                      tree arg, bool ignore,
13206                      enum built_in_function fcode)
13207 {
13208   tree fn_putchar, fn_puts, newarg, call = NULL_TREE;
13209   const char *fmt_str = NULL;
13210
13211   /* If the return value is used, don't do the transformation.  */
13212   if (! ignore)
13213     return NULL_TREE;
13214
13215   /* Verify the required arguments in the original call.  */
13216   if (!validate_arg (fmt, POINTER_TYPE))
13217     return NULL_TREE;
13218
13219   /* Check whether the format is a literal string constant.  */
13220   fmt_str = c_getstr (fmt);
13221   if (fmt_str == NULL)
13222     return NULL_TREE;
13223
13224   if (fcode == BUILT_IN_PRINTF_UNLOCKED)
13225     {
13226       /* If we're using an unlocked function, assume the other
13227          unlocked functions exist explicitly.  */
13228       fn_putchar = builtin_decl_explicit (BUILT_IN_PUTCHAR_UNLOCKED);
13229       fn_puts = builtin_decl_explicit (BUILT_IN_PUTS_UNLOCKED);
13230     }
13231   else
13232     {
13233       fn_putchar = builtin_decl_implicit (BUILT_IN_PUTCHAR);
13234       fn_puts = builtin_decl_implicit (BUILT_IN_PUTS);
13235     }
13236
13237   if (!init_target_chars ())
13238     return NULL_TREE;
13239
13240   if (strcmp (fmt_str, target_percent_s) == 0
13241       || strchr (fmt_str, target_percent) == NULL)
13242     {
13243       const char *str;
13244
13245       if (strcmp (fmt_str, target_percent_s) == 0)
13246         {
13247           if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
13248             return NULL_TREE;
13249
13250           if (!arg || !validate_arg (arg, POINTER_TYPE))
13251             return NULL_TREE;
13252
13253           str = c_getstr (arg);
13254           if (str == NULL)
13255             return NULL_TREE;
13256         }
13257       else
13258         {
13259           /* The format specifier doesn't contain any '%' characters.  */
13260           if (fcode != BUILT_IN_VPRINTF && fcode != BUILT_IN_VPRINTF_CHK
13261               && arg)
13262             return NULL_TREE;
13263           str = fmt_str;
13264         }
13265
13266       /* If the string was "", printf does nothing.  */
13267       if (str[0] == '\0')
13268         return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
13269
13270       /* If the string has length of 1, call putchar.  */
13271       if (str[1] == '\0')
13272         {
13273           /* Given printf("c"), (where c is any one character,)
13274              convert "c"[0] to an int and pass that to the replacement
13275              function.  */
13276           newarg = build_int_cst (integer_type_node, str[0]);
13277           if (fn_putchar)
13278             call = build_call_expr_loc (loc, fn_putchar, 1, newarg);
13279         }
13280       else
13281         {
13282           /* If the string was "string\n", call puts("string").  */
13283           size_t len = strlen (str);
13284           if ((unsigned char)str[len - 1] == target_newline
13285               && (size_t) (int) len == len
13286               && (int) len > 0)
13287             {
13288               char *newstr;
13289               tree offset_node, string_cst;
13290
13291               /* Create a NUL-terminated string that's one char shorter
13292                  than the original, stripping off the trailing '\n'.  */
13293               newarg = build_string_literal (len, str);
13294               string_cst = string_constant (newarg, &offset_node);
13295               gcc_checking_assert (string_cst
13296                                    && (TREE_STRING_LENGTH (string_cst)
13297                                        == (int) len)
13298                                    && integer_zerop (offset_node)
13299                                    && (unsigned char)
13300                                       TREE_STRING_POINTER (string_cst)[len - 1]
13301                                       == target_newline);
13302               /* build_string_literal creates a new STRING_CST,
13303                  modify it in place to avoid double copying.  */
13304               newstr = CONST_CAST (char *, TREE_STRING_POINTER (string_cst));
13305               newstr[len - 1] = '\0';
13306               if (fn_puts)
13307                 call = build_call_expr_loc (loc, fn_puts, 1, newarg);
13308             }
13309           else
13310             /* We'd like to arrange to call fputs(string,stdout) here,
13311                but we need stdout and don't have a way to get it yet.  */
13312             return NULL_TREE;
13313         }
13314     }
13315
13316   /* The other optimizations can be done only on the non-va_list variants.  */
13317   else if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
13318     return NULL_TREE;
13319
13320   /* If the format specifier was "%s\n", call __builtin_puts(arg).  */
13321   else if (strcmp (fmt_str, target_percent_s_newline) == 0)
13322     {
13323       if (!arg || !validate_arg (arg, POINTER_TYPE))
13324         return NULL_TREE;
13325       if (fn_puts)
13326         call = build_call_expr_loc (loc, fn_puts, 1, arg);
13327     }
13328
13329   /* If the format specifier was "%c", call __builtin_putchar(arg).  */
13330   else if (strcmp (fmt_str, target_percent_c) == 0)
13331     {
13332       if (!arg || !validate_arg (arg, INTEGER_TYPE))
13333         return NULL_TREE;
13334       if (fn_putchar)
13335         call = build_call_expr_loc (loc, fn_putchar, 1, arg);
13336     }
13337
13338   if (!call)
13339     return NULL_TREE;
13340
13341   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), call);
13342 }
13343
13344 /* Fold a call to the {,v}fprintf{,_unlocked} and __{,v}printf_chk builtins.
13345    FP, FMT, and ARG are the arguments to the call.  We don't fold calls with
13346    more than 3 arguments, and ARG may be null in the 2-argument case.
13347
13348    Return NULL_TREE if no simplification was possible, otherwise return the
13349    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
13350    code of the function to be simplified.  */
13351
13352 static tree
13353 fold_builtin_fprintf (location_t loc, tree fndecl, tree fp,
13354                       tree fmt, tree arg, bool ignore,
13355                       enum built_in_function fcode)
13356 {
13357   tree fn_fputc, fn_fputs, call = NULL_TREE;
13358   const char *fmt_str = NULL;
13359
13360   /* If the return value is used, don't do the transformation.  */
13361   if (! ignore)
13362     return NULL_TREE;
13363
13364   /* Verify the required arguments in the original call.  */
13365   if (!validate_arg (fp, POINTER_TYPE))
13366     return NULL_TREE;
13367   if (!validate_arg (fmt, POINTER_TYPE))
13368     return NULL_TREE;
13369
13370   /* Check whether the format is a literal string constant.  */
13371   fmt_str = c_getstr (fmt);
13372   if (fmt_str == NULL)
13373     return NULL_TREE;
13374
13375   if (fcode == BUILT_IN_FPRINTF_UNLOCKED)
13376     {
13377       /* If we're using an unlocked function, assume the other
13378          unlocked functions exist explicitly.  */
13379       fn_fputc = builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED);
13380       fn_fputs = builtin_decl_explicit (BUILT_IN_FPUTS_UNLOCKED);
13381     }
13382   else
13383     {
13384       fn_fputc = builtin_decl_implicit (BUILT_IN_FPUTC);
13385       fn_fputs = builtin_decl_implicit (BUILT_IN_FPUTS);
13386     }
13387
13388   if (!init_target_chars ())
13389     return NULL_TREE;
13390
13391   /* If the format doesn't contain % args or %%, use strcpy.  */
13392   if (strchr (fmt_str, target_percent) == NULL)
13393     {
13394       if (fcode != BUILT_IN_VFPRINTF && fcode != BUILT_IN_VFPRINTF_CHK
13395           && arg)
13396         return NULL_TREE;
13397
13398       /* If the format specifier was "", fprintf does nothing.  */
13399       if (fmt_str[0] == '\0')
13400         {
13401           /* If FP has side-effects, just wait until gimplification is
13402              done.  */
13403           if (TREE_SIDE_EFFECTS (fp))
13404             return NULL_TREE;
13405
13406           return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
13407         }
13408
13409       /* When "string" doesn't contain %, replace all cases of
13410          fprintf (fp, string) with fputs (string, fp).  The fputs
13411          builtin will take care of special cases like length == 1.  */
13412       if (fn_fputs)
13413         call = build_call_expr_loc (loc, fn_fputs, 2, fmt, fp);
13414     }
13415
13416   /* The other optimizations can be done only on the non-va_list variants.  */
13417   else if (fcode == BUILT_IN_VFPRINTF || fcode == BUILT_IN_VFPRINTF_CHK)
13418     return NULL_TREE;
13419
13420   /* If the format specifier was "%s", call __builtin_fputs (arg, fp).  */
13421   else if (strcmp (fmt_str, target_percent_s) == 0)
13422     {
13423       if (!arg || !validate_arg (arg, POINTER_TYPE))
13424         return NULL_TREE;
13425       if (fn_fputs)
13426         call = build_call_expr_loc (loc, fn_fputs, 2, arg, fp);
13427     }
13428
13429   /* If the format specifier was "%c", call __builtin_fputc (arg, fp).  */
13430   else if (strcmp (fmt_str, target_percent_c) == 0)
13431     {
13432       if (!arg || !validate_arg (arg, INTEGER_TYPE))
13433         return NULL_TREE;
13434       if (fn_fputc)
13435         call = build_call_expr_loc (loc, fn_fputc, 2, arg, fp);
13436     }
13437
13438   if (!call)
13439     return NULL_TREE;
13440   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), call);
13441 }
13442
13443 /* Initialize format string characters in the target charset.  */
13444
13445 static bool
13446 init_target_chars (void)
13447 {
13448   static bool init;
13449   if (!init)
13450     {
13451       target_newline = lang_hooks.to_target_charset ('\n');
13452       target_percent = lang_hooks.to_target_charset ('%');
13453       target_c = lang_hooks.to_target_charset ('c');
13454       target_s = lang_hooks.to_target_charset ('s');
13455       if (target_newline == 0 || target_percent == 0 || target_c == 0
13456           || target_s == 0)
13457         return false;
13458
13459       target_percent_c[0] = target_percent;
13460       target_percent_c[1] = target_c;
13461       target_percent_c[2] = '\0';
13462
13463       target_percent_s[0] = target_percent;
13464       target_percent_s[1] = target_s;
13465       target_percent_s[2] = '\0';
13466
13467       target_percent_s_newline[0] = target_percent;
13468       target_percent_s_newline[1] = target_s;
13469       target_percent_s_newline[2] = target_newline;
13470       target_percent_s_newline[3] = '\0';
13471
13472       init = true;
13473     }
13474   return true;
13475 }
13476
13477 /* Helper function for do_mpfr_arg*().  Ensure M is a normal number
13478    and no overflow/underflow occurred.  INEXACT is true if M was not
13479    exactly calculated.  TYPE is the tree type for the result.  This
13480    function assumes that you cleared the MPFR flags and then
13481    calculated M to see if anything subsequently set a flag prior to
13482    entering this function.  Return NULL_TREE if any checks fail.  */
13483
13484 static tree
13485 do_mpfr_ckconv (mpfr_srcptr m, tree type, int inexact)
13486 {
13487   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
13488      overflow/underflow occurred.  If -frounding-math, proceed iff the
13489      result of calling FUNC was exact.  */
13490   if (mpfr_number_p (m) && !mpfr_overflow_p () && !mpfr_underflow_p ()
13491       && (!flag_rounding_math || !inexact))
13492     {
13493       REAL_VALUE_TYPE rr;
13494
13495       real_from_mpfr (&rr, m, type, GMP_RNDN);
13496       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR value,
13497          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
13498          but the mpft_t is not, then we underflowed in the
13499          conversion.  */
13500       if (real_isfinite (&rr)
13501           && (rr.cl == rvc_zero) == (mpfr_zero_p (m) != 0))
13502         {
13503           REAL_VALUE_TYPE rmode;
13504
13505           real_convert (&rmode, TYPE_MODE (type), &rr);
13506           /* Proceed iff the specified mode can hold the value.  */
13507           if (real_identical (&rmode, &rr))
13508             return build_real (type, rmode);
13509         }
13510     }
13511   return NULL_TREE;
13512 }
13513
13514 /* Helper function for do_mpc_arg*().  Ensure M is a normal complex
13515    number and no overflow/underflow occurred.  INEXACT is true if M
13516    was not exactly calculated.  TYPE is the tree type for the result.
13517    This function assumes that you cleared the MPFR flags and then
13518    calculated M to see if anything subsequently set a flag prior to
13519    entering this function.  Return NULL_TREE if any checks fail, if
13520    FORCE_CONVERT is true, then bypass the checks.  */
13521
13522 static tree
13523 do_mpc_ckconv (mpc_srcptr m, tree type, int inexact, int force_convert)
13524 {
13525   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
13526      overflow/underflow occurred.  If -frounding-math, proceed iff the
13527      result of calling FUNC was exact.  */
13528   if (force_convert
13529       || (mpfr_number_p (mpc_realref (m)) && mpfr_number_p (mpc_imagref (m))
13530           && !mpfr_overflow_p () && !mpfr_underflow_p ()
13531           && (!flag_rounding_math || !inexact)))
13532     {
13533       REAL_VALUE_TYPE re, im;
13534
13535       real_from_mpfr (&re, mpc_realref (m), TREE_TYPE (type), GMP_RNDN);
13536       real_from_mpfr (&im, mpc_imagref (m), TREE_TYPE (type), GMP_RNDN);
13537       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR values,
13538          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
13539          but the mpft_t is not, then we underflowed in the
13540          conversion.  */
13541       if (force_convert
13542           || (real_isfinite (&re) && real_isfinite (&im)
13543               && (re.cl == rvc_zero) == (mpfr_zero_p (mpc_realref (m)) != 0)
13544               && (im.cl == rvc_zero) == (mpfr_zero_p (mpc_imagref (m)) != 0)))
13545         {
13546           REAL_VALUE_TYPE re_mode, im_mode;
13547
13548           real_convert (&re_mode, TYPE_MODE (TREE_TYPE (type)), &re);
13549           real_convert (&im_mode, TYPE_MODE (TREE_TYPE (type)), &im);
13550           /* Proceed iff the specified mode can hold the value.  */
13551           if (force_convert
13552               || (real_identical (&re_mode, &re)
13553                   && real_identical (&im_mode, &im)))
13554             return build_complex (type, build_real (TREE_TYPE (type), re_mode),
13555                                   build_real (TREE_TYPE (type), im_mode));
13556         }
13557     }
13558   return NULL_TREE;
13559 }
13560
13561 /* If argument ARG is a REAL_CST, call the one-argument mpfr function
13562    FUNC on it and return the resulting value as a tree with type TYPE.
13563    If MIN and/or MAX are not NULL, then the supplied ARG must be
13564    within those bounds.  If INCLUSIVE is true, then MIN/MAX are
13565    acceptable values, otherwise they are not.  The mpfr precision is
13566    set to the precision of TYPE.  We assume that function FUNC returns
13567    zero if the result could be calculated exactly within the requested
13568    precision.  */
13569
13570 static tree
13571 do_mpfr_arg1 (tree arg, tree type, int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t),
13572               const REAL_VALUE_TYPE *min, const REAL_VALUE_TYPE *max,
13573               bool inclusive)
13574 {
13575   tree result = NULL_TREE;
13576
13577   STRIP_NOPS (arg);
13578
13579   /* To proceed, MPFR must exactly represent the target floating point
13580      format, which only happens when the target base equals two.  */
13581   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13582       && TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
13583     {
13584       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg);
13585
13586       if (real_isfinite (ra)
13587           && (!min || real_compare (inclusive ? GE_EXPR: GT_EXPR , ra, min))
13588           && (!max || real_compare (inclusive ? LE_EXPR: LT_EXPR , ra, max)))
13589         {
13590           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13591           const int prec = fmt->p;
13592           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13593           int inexact;
13594           mpfr_t m;
13595
13596           mpfr_init2 (m, prec);
13597           mpfr_from_real (m, ra, GMP_RNDN);
13598           mpfr_clear_flags ();
13599           inexact = func (m, m, rnd);
13600           result = do_mpfr_ckconv (m, type, inexact);
13601           mpfr_clear (m);
13602         }
13603     }
13604
13605   return result;
13606 }
13607
13608 /* If argument ARG is a REAL_CST, call the two-argument mpfr function
13609    FUNC on it and return the resulting value as a tree with type TYPE.
13610    The mpfr precision is set to the precision of TYPE.  We assume that
13611    function FUNC returns zero if the result could be calculated
13612    exactly within the requested precision.  */
13613
13614 static tree
13615 do_mpfr_arg2 (tree arg1, tree arg2, tree type,
13616               int (*func)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t))
13617 {
13618   tree result = NULL_TREE;
13619
13620   STRIP_NOPS (arg1);
13621   STRIP_NOPS (arg2);
13622
13623   /* To proceed, MPFR must exactly represent the target floating point
13624      format, which only happens when the target base equals two.  */
13625   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13626       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1)
13627       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2))
13628     {
13629       const REAL_VALUE_TYPE *const ra1 = &TREE_REAL_CST (arg1);
13630       const REAL_VALUE_TYPE *const ra2 = &TREE_REAL_CST (arg2);
13631
13632       if (real_isfinite (ra1) && real_isfinite (ra2))
13633         {
13634           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13635           const int prec = fmt->p;
13636           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13637           int inexact;
13638           mpfr_t m1, m2;
13639
13640           mpfr_inits2 (prec, m1, m2, NULL);
13641           mpfr_from_real (m1, ra1, GMP_RNDN);
13642           mpfr_from_real (m2, ra2, GMP_RNDN);
13643           mpfr_clear_flags ();
13644           inexact = func (m1, m1, m2, rnd);
13645           result = do_mpfr_ckconv (m1, type, inexact);
13646           mpfr_clears (m1, m2, NULL);
13647         }
13648     }
13649
13650   return result;
13651 }
13652
13653 /* If argument ARG is a REAL_CST, call the three-argument mpfr function
13654    FUNC on it and return the resulting value as a tree with type TYPE.
13655    The mpfr precision is set to the precision of TYPE.  We assume that
13656    function FUNC returns zero if the result could be calculated
13657    exactly within the requested precision.  */
13658
13659 static tree
13660 do_mpfr_arg3 (tree arg1, tree arg2, tree arg3, tree type,
13661               int (*func)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t))
13662 {
13663   tree result = NULL_TREE;
13664
13665   STRIP_NOPS (arg1);
13666   STRIP_NOPS (arg2);
13667   STRIP_NOPS (arg3);
13668
13669   /* To proceed, MPFR must exactly represent the target floating point
13670      format, which only happens when the target base equals two.  */
13671   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13672       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1)
13673       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2)
13674       && TREE_CODE (arg3) == REAL_CST && !TREE_OVERFLOW (arg3))
13675     {
13676       const REAL_VALUE_TYPE *const ra1 = &TREE_REAL_CST (arg1);
13677       const REAL_VALUE_TYPE *const ra2 = &TREE_REAL_CST (arg2);
13678       const REAL_VALUE_TYPE *const ra3 = &TREE_REAL_CST (arg3);
13679
13680       if (real_isfinite (ra1) && real_isfinite (ra2) && real_isfinite (ra3))
13681         {
13682           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13683           const int prec = fmt->p;
13684           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13685           int inexact;
13686           mpfr_t m1, m2, m3;
13687
13688           mpfr_inits2 (prec, m1, m2, m3, NULL);
13689           mpfr_from_real (m1, ra1, GMP_RNDN);
13690           mpfr_from_real (m2, ra2, GMP_RNDN);
13691           mpfr_from_real (m3, ra3, GMP_RNDN);
13692           mpfr_clear_flags ();
13693           inexact = func (m1, m1, m2, m3, rnd);
13694           result = do_mpfr_ckconv (m1, type, inexact);
13695           mpfr_clears (m1, m2, m3, NULL);
13696         }
13697     }
13698
13699   return result;
13700 }
13701
13702 /* If argument ARG is a REAL_CST, call mpfr_sin_cos() on it and set
13703    the pointers *(ARG_SINP) and *(ARG_COSP) to the resulting values.
13704    If ARG_SINP and ARG_COSP are NULL then the result is returned
13705    as a complex value.
13706    The type is taken from the type of ARG and is used for setting the
13707    precision of the calculation and results.  */
13708
13709 static tree
13710 do_mpfr_sincos (tree arg, tree arg_sinp, tree arg_cosp)
13711 {
13712   tree const type = TREE_TYPE (arg);
13713   tree result = NULL_TREE;
13714
13715   STRIP_NOPS (arg);
13716
13717   /* To proceed, MPFR must exactly represent the target floating point
13718      format, which only happens when the target base equals two.  */
13719   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13720       && TREE_CODE (arg) == REAL_CST
13721       && !TREE_OVERFLOW (arg))
13722     {
13723       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg);
13724
13725       if (real_isfinite (ra))
13726         {
13727           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13728           const int prec = fmt->p;
13729           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13730           tree result_s, result_c;
13731           int inexact;
13732           mpfr_t m, ms, mc;
13733
13734           mpfr_inits2 (prec, m, ms, mc, NULL);
13735           mpfr_from_real (m, ra, GMP_RNDN);
13736           mpfr_clear_flags ();
13737           inexact = mpfr_sin_cos (ms, mc, m, rnd);
13738           result_s = do_mpfr_ckconv (ms, type, inexact);
13739           result_c = do_mpfr_ckconv (mc, type, inexact);
13740           mpfr_clears (m, ms, mc, NULL);
13741           if (result_s && result_c)
13742             {
13743               /* If we are to return in a complex value do so.  */
13744               if (!arg_sinp && !arg_cosp)
13745                 return build_complex (build_complex_type (type),
13746                                       result_c, result_s);
13747
13748               /* Dereference the sin/cos pointer arguments.  */
13749               arg_sinp = build_fold_indirect_ref (arg_sinp);
13750               arg_cosp = build_fold_indirect_ref (arg_cosp);
13751               /* Proceed if valid pointer type were passed in.  */
13752               if (TYPE_MAIN_VARIANT (TREE_TYPE (arg_sinp)) == TYPE_MAIN_VARIANT (type)
13753                   && TYPE_MAIN_VARIANT (TREE_TYPE (arg_cosp)) == TYPE_MAIN_VARIANT (type))
13754                 {
13755                   /* Set the values. */
13756                   result_s = fold_build2 (MODIFY_EXPR, type, arg_sinp,
13757                                           result_s);
13758                   TREE_SIDE_EFFECTS (result_s) = 1;
13759                   result_c = fold_build2 (MODIFY_EXPR, type, arg_cosp,
13760                                           result_c);
13761                   TREE_SIDE_EFFECTS (result_c) = 1;
13762                   /* Combine the assignments into a compound expr.  */
13763                   result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13764                                                     result_s, result_c));
13765                 }
13766             }
13767         }
13768     }
13769   return result;
13770 }
13771
13772 /* If argument ARG1 is an INTEGER_CST and ARG2 is a REAL_CST, call the
13773    two-argument mpfr order N Bessel function FUNC on them and return
13774    the resulting value as a tree with type TYPE.  The mpfr precision
13775    is set to the precision of TYPE.  We assume that function FUNC
13776    returns zero if the result could be calculated exactly within the
13777    requested precision.  */
13778 static tree
13779 do_mpfr_bessel_n (tree arg1, tree arg2, tree type,
13780                   int (*func)(mpfr_ptr, long, mpfr_srcptr, mp_rnd_t),
13781                   const REAL_VALUE_TYPE *min, bool inclusive)
13782 {
13783   tree result = NULL_TREE;
13784
13785   STRIP_NOPS (arg1);
13786   STRIP_NOPS (arg2);
13787
13788   /* To proceed, MPFR must exactly represent the target floating point
13789      format, which only happens when the target base equals two.  */
13790   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13791       && host_integerp (arg1, 0)
13792       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2))
13793     {
13794       const HOST_WIDE_INT n = tree_low_cst (arg1, 0);
13795       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg2);
13796
13797       if (n == (long)n
13798           && real_isfinite (ra)
13799           && (!min || real_compare (inclusive ? GE_EXPR: GT_EXPR , ra, min)))
13800         {
13801           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13802           const int prec = fmt->p;
13803           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13804           int inexact;
13805           mpfr_t m;
13806
13807           mpfr_init2 (m, prec);
13808           mpfr_from_real (m, ra, GMP_RNDN);
13809           mpfr_clear_flags ();
13810           inexact = func (m, n, m, rnd);
13811           result = do_mpfr_ckconv (m, type, inexact);
13812           mpfr_clear (m);
13813         }
13814     }
13815
13816   return result;
13817 }
13818
13819 /* If arguments ARG0 and ARG1 are REAL_CSTs, call mpfr_remquo() to set
13820    the pointer *(ARG_QUO) and return the result.  The type is taken
13821    from the type of ARG0 and is used for setting the precision of the
13822    calculation and results.  */
13823
13824 static tree
13825 do_mpfr_remquo (tree arg0, tree arg1, tree arg_quo)
13826 {
13827   tree const type = TREE_TYPE (arg0);
13828   tree result = NULL_TREE;
13829
13830   STRIP_NOPS (arg0);
13831   STRIP_NOPS (arg1);
13832
13833   /* To proceed, MPFR must exactly represent the target floating point
13834      format, which only happens when the target base equals two.  */
13835   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13836       && TREE_CODE (arg0) == REAL_CST && !TREE_OVERFLOW (arg0)
13837       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1))
13838     {
13839       const REAL_VALUE_TYPE *const ra0 = TREE_REAL_CST_PTR (arg0);
13840       const REAL_VALUE_TYPE *const ra1 = TREE_REAL_CST_PTR (arg1);
13841
13842       if (real_isfinite (ra0) && real_isfinite (ra1))
13843         {
13844           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13845           const int prec = fmt->p;
13846           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13847           tree result_rem;
13848           long integer_quo;
13849           mpfr_t m0, m1;
13850
13851           mpfr_inits2 (prec, m0, m1, NULL);
13852           mpfr_from_real (m0, ra0, GMP_RNDN);
13853           mpfr_from_real (m1, ra1, GMP_RNDN);
13854           mpfr_clear_flags ();
13855           mpfr_remquo (m0, &integer_quo, m0, m1, rnd);
13856           /* Remquo is independent of the rounding mode, so pass
13857              inexact=0 to do_mpfr_ckconv().  */
13858           result_rem = do_mpfr_ckconv (m0, type, /*inexact=*/ 0);
13859           mpfr_clears (m0, m1, NULL);
13860           if (result_rem)
13861             {
13862               /* MPFR calculates quo in the host's long so it may
13863                  return more bits in quo than the target int can hold
13864                  if sizeof(host long) > sizeof(target int).  This can
13865                  happen even for native compilers in LP64 mode.  In
13866                  these cases, modulo the quo value with the largest
13867                  number that the target int can hold while leaving one
13868                  bit for the sign.  */
13869               if (sizeof (integer_quo) * CHAR_BIT > INT_TYPE_SIZE)
13870                 integer_quo %= (long)(1UL << (INT_TYPE_SIZE - 1));
13871
13872               /* Dereference the quo pointer argument.  */
13873               arg_quo = build_fold_indirect_ref (arg_quo);
13874               /* Proceed iff a valid pointer type was passed in.  */
13875               if (TYPE_MAIN_VARIANT (TREE_TYPE (arg_quo)) == integer_type_node)
13876                 {
13877                   /* Set the value. */
13878                   tree result_quo
13879                     = fold_build2 (MODIFY_EXPR, TREE_TYPE (arg_quo), arg_quo,
13880                                    build_int_cst (TREE_TYPE (arg_quo),
13881                                                   integer_quo));
13882                   TREE_SIDE_EFFECTS (result_quo) = 1;
13883                   /* Combine the quo assignment with the rem.  */
13884                   result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13885                                                     result_quo, result_rem));
13886                 }
13887             }
13888         }
13889     }
13890   return result;
13891 }
13892
13893 /* If ARG is a REAL_CST, call mpfr_lgamma() on it and return the
13894    resulting value as a tree with type TYPE.  The mpfr precision is
13895    set to the precision of TYPE.  We assume that this mpfr function
13896    returns zero if the result could be calculated exactly within the
13897    requested precision.  In addition, the integer pointer represented
13898    by ARG_SG will be dereferenced and set to the appropriate signgam
13899    (-1,1) value.  */
13900
13901 static tree
13902 do_mpfr_lgamma_r (tree arg, tree arg_sg, tree type)
13903 {
13904   tree result = NULL_TREE;
13905
13906   STRIP_NOPS (arg);
13907
13908   /* To proceed, MPFR must exactly represent the target floating point
13909      format, which only happens when the target base equals two.  Also
13910      verify ARG is a constant and that ARG_SG is an int pointer.  */
13911   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13912       && TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg)
13913       && TREE_CODE (TREE_TYPE (arg_sg)) == POINTER_TYPE
13914       && TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (arg_sg))) == integer_type_node)
13915     {
13916       const REAL_VALUE_TYPE *const ra = TREE_REAL_CST_PTR (arg);
13917
13918       /* In addition to NaN and Inf, the argument cannot be zero or a
13919          negative integer.  */
13920       if (real_isfinite (ra)
13921           && ra->cl != rvc_zero
13922           && !(real_isneg (ra) && real_isinteger (ra, TYPE_MODE (type))))
13923         {
13924           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13925           const int prec = fmt->p;
13926           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13927           int inexact, sg;
13928           mpfr_t m;
13929           tree result_lg;
13930
13931           mpfr_init2 (m, prec);
13932           mpfr_from_real (m, ra, GMP_RNDN);
13933           mpfr_clear_flags ();
13934           inexact = mpfr_lgamma (m, &sg, m, rnd);
13935           result_lg = do_mpfr_ckconv (m, type, inexact);
13936           mpfr_clear (m);
13937           if (result_lg)
13938             {
13939               tree result_sg;
13940
13941               /* Dereference the arg_sg pointer argument.  */
13942               arg_sg = build_fold_indirect_ref (arg_sg);
13943               /* Assign the signgam value into *arg_sg. */
13944               result_sg = fold_build2 (MODIFY_EXPR,
13945                                        TREE_TYPE (arg_sg), arg_sg,
13946                                        build_int_cst (TREE_TYPE (arg_sg), sg));
13947               TREE_SIDE_EFFECTS (result_sg) = 1;
13948               /* Combine the signgam assignment with the lgamma result.  */
13949               result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13950                                                 result_sg, result_lg));
13951             }
13952         }
13953     }
13954
13955   return result;
13956 }
13957
13958 /* If argument ARG is a COMPLEX_CST, call the one-argument mpc
13959    function FUNC on it and return the resulting value as a tree with
13960    type TYPE.  The mpfr precision is set to the precision of TYPE.  We
13961    assume that function FUNC returns zero if the result could be
13962    calculated exactly within the requested precision.  */
13963
13964 static tree
13965 do_mpc_arg1 (tree arg, tree type, int (*func)(mpc_ptr, mpc_srcptr, mpc_rnd_t))
13966 {
13967   tree result = NULL_TREE;
13968
13969   STRIP_NOPS (arg);
13970
13971   /* To proceed, MPFR must exactly represent the target floating point
13972      format, which only happens when the target base equals two.  */
13973   if (TREE_CODE (arg) == COMPLEX_CST && !TREE_OVERFLOW (arg)
13974       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE
13975       && REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (TREE_TYPE (arg))))->b == 2)
13976     {
13977       const REAL_VALUE_TYPE *const re = TREE_REAL_CST_PTR (TREE_REALPART (arg));
13978       const REAL_VALUE_TYPE *const im = TREE_REAL_CST_PTR (TREE_IMAGPART (arg));
13979
13980       if (real_isfinite (re) && real_isfinite (im))
13981         {
13982           const struct real_format *const fmt =
13983             REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (type)));
13984           const int prec = fmt->p;
13985           const mp_rnd_t rnd = fmt->round_towards_zero ? GMP_RNDZ : GMP_RNDN;
13986           const mpc_rnd_t crnd = fmt->round_towards_zero ? MPC_RNDZZ : MPC_RNDNN;
13987           int inexact;
13988           mpc_t m;
13989
13990           mpc_init2 (m, prec);
13991           mpfr_from_real (mpc_realref (m), re, rnd);
13992           mpfr_from_real (mpc_imagref (m), im, rnd);
13993           mpfr_clear_flags ();
13994           inexact = func (m, m, crnd);
13995           result = do_mpc_ckconv (m, type, inexact, /*force_convert=*/ 0);
13996           mpc_clear (m);
13997         }
13998     }
13999
14000   return result;
14001 }
14002
14003 /* If arguments ARG0 and ARG1 are a COMPLEX_CST, call the two-argument
14004    mpc function FUNC on it and return the resulting value as a tree
14005    with type TYPE.  The mpfr precision is set to the precision of
14006    TYPE.  We assume that function FUNC returns zero if the result
14007    could be calculated exactly within the requested precision.  If
14008    DO_NONFINITE is true, then fold expressions containing Inf or NaN
14009    in the arguments and/or results.  */
14010
14011 tree
14012 do_mpc_arg2 (tree arg0, tree arg1, tree type, int do_nonfinite,
14013              int (*func)(mpc_ptr, mpc_srcptr, mpc_srcptr, mpc_rnd_t))
14014 {
14015   tree result = NULL_TREE;
14016
14017   STRIP_NOPS (arg0);
14018   STRIP_NOPS (arg1);
14019
14020   /* To proceed, MPFR must exactly represent the target floating point
14021      format, which only happens when the target base equals two.  */
14022   if (TREE_CODE (arg0) == COMPLEX_CST && !TREE_OVERFLOW (arg0)
14023       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE
14024       && TREE_CODE (arg1) == COMPLEX_CST && !TREE_OVERFLOW (arg1)
14025       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg1))) == REAL_TYPE
14026       && REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (TREE_TYPE (arg0))))->b == 2)
14027     {
14028       const REAL_VALUE_TYPE *const re0 = TREE_REAL_CST_PTR (TREE_REALPART (arg0));
14029       const REAL_VALUE_TYPE *const im0 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg0));
14030       const REAL_VALUE_TYPE *const re1 = TREE_REAL_CST_PTR (TREE_REALPART (arg1));
14031       const REAL_VALUE_TYPE *const im1 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg1));
14032
14033       if (do_nonfinite
14034           || (real_isfinite (re0) && real_isfinite (im0)
14035               && real_isfinite (re1) && real_isfinite (im1)))
14036         {
14037           const struct real_format *const fmt =
14038             REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (type)));
14039           const int prec = fmt->p;
14040           const mp_rnd_t rnd = fmt->round_towards_zero ? GMP_RNDZ : GMP_RNDN;
14041           const mpc_rnd_t crnd = fmt->round_towards_zero ? MPC_RNDZZ : MPC_RNDNN;
14042           int inexact;
14043           mpc_t m0, m1;
14044
14045           mpc_init2 (m0, prec);
14046           mpc_init2 (m1, prec);
14047           mpfr_from_real (mpc_realref (m0), re0, rnd);
14048           mpfr_from_real (mpc_imagref (m0), im0, rnd);
14049           mpfr_from_real (mpc_realref (m1), re1, rnd);
14050           mpfr_from_real (mpc_imagref (m1), im1, rnd);
14051           mpfr_clear_flags ();
14052           inexact = func (m0, m0, m1, crnd);
14053           result = do_mpc_ckconv (m0, type, inexact, do_nonfinite);
14054           mpc_clear (m0);
14055           mpc_clear (m1);
14056         }
14057     }
14058
14059   return result;
14060 }
14061
14062 /* Fold a call STMT to __{,v}sprintf_chk.  Return NULL_TREE if
14063    a normal call should be emitted rather than expanding the function
14064    inline.  FCODE is either BUILT_IN_SPRINTF_CHK or BUILT_IN_VSPRINTF_CHK.  */
14065
14066 static tree
14067 gimple_fold_builtin_sprintf_chk (gimple stmt, enum built_in_function fcode)
14068 {
14069   int nargs = gimple_call_num_args (stmt);
14070
14071   return fold_builtin_sprintf_chk_1 (gimple_location (stmt), nargs,
14072                                      (nargs > 0
14073                                       ? gimple_call_arg_ptr (stmt, 0)
14074                                       : &error_mark_node), fcode);
14075 }
14076
14077 /* Fold a call STMT to {,v}snprintf.  Return NULL_TREE if
14078    a normal call should be emitted rather than expanding the function
14079    inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
14080    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
14081    passed as second argument.  */
14082
14083 tree
14084 gimple_fold_builtin_snprintf_chk (gimple stmt, tree maxlen,
14085                                   enum built_in_function fcode)
14086 {
14087   int nargs = gimple_call_num_args (stmt);
14088
14089   return fold_builtin_snprintf_chk_1 (gimple_location (stmt), nargs,
14090                                       (nargs > 0
14091                                        ? gimple_call_arg_ptr (stmt, 0)
14092                                        : &error_mark_node), maxlen, fcode);
14093 }
14094
14095 /* Builtins with folding operations that operate on "..." arguments
14096    need special handling; we need to store the arguments in a convenient
14097    data structure before attempting any folding.  Fortunately there are
14098    only a few builtins that fall into this category.  FNDECL is the
14099    function, EXP is the CALL_EXPR for the call, and IGNORE is true if the
14100    result of the function call is ignored.  */
14101
14102 static tree
14103 gimple_fold_builtin_varargs (tree fndecl, gimple stmt,
14104                              bool ignore ATTRIBUTE_UNUSED)
14105 {
14106   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
14107   tree ret = NULL_TREE;
14108
14109   switch (fcode)
14110     {
14111     case BUILT_IN_SPRINTF_CHK:
14112     case BUILT_IN_VSPRINTF_CHK:
14113       ret = gimple_fold_builtin_sprintf_chk (stmt, fcode);
14114       break;
14115
14116     case BUILT_IN_SNPRINTF_CHK:
14117     case BUILT_IN_VSNPRINTF_CHK:
14118       ret = gimple_fold_builtin_snprintf_chk (stmt, NULL_TREE, fcode);
14119
14120     default:
14121       break;
14122     }
14123   if (ret)
14124     {
14125       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
14126       TREE_NO_WARNING (ret) = 1;
14127       return ret;
14128     }
14129   return NULL_TREE;
14130 }
14131
14132 /* A wrapper function for builtin folding that prevents warnings for
14133    "statement without effect" and the like, caused by removing the
14134    call node earlier than the warning is generated.  */
14135
14136 tree
14137 fold_call_stmt (gimple stmt, bool ignore)
14138 {
14139   tree ret = NULL_TREE;
14140   tree fndecl = gimple_call_fndecl (stmt);
14141   location_t loc = gimple_location (stmt);
14142   if (fndecl
14143       && TREE_CODE (fndecl) == FUNCTION_DECL
14144       && DECL_BUILT_IN (fndecl)
14145       && !gimple_call_va_arg_pack_p (stmt))
14146     {
14147       int nargs = gimple_call_num_args (stmt);
14148       tree *args = (nargs > 0
14149                     ? gimple_call_arg_ptr (stmt, 0)
14150                     : &error_mark_node);
14151
14152       if (avoid_folding_inline_builtin (fndecl))
14153         return NULL_TREE;
14154       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
14155         {
14156           return targetm.fold_builtin (fndecl, nargs, args, ignore);
14157         }
14158       else
14159         {
14160           if (nargs <= MAX_ARGS_TO_FOLD_BUILTIN)
14161             ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
14162           if (!ret)
14163             ret = gimple_fold_builtin_varargs (fndecl, stmt, ignore);
14164           if (ret)
14165             {
14166               /* Propagate location information from original call to
14167                  expansion of builtin.  Otherwise things like
14168                  maybe_emit_chk_warning, that operate on the expansion
14169                  of a builtin, will use the wrong location information.  */
14170               if (gimple_has_location (stmt))
14171                 {
14172                   tree realret = ret;
14173                   if (TREE_CODE (ret) == NOP_EXPR)
14174                     realret = TREE_OPERAND (ret, 0);
14175                   if (CAN_HAVE_LOCATION_P (realret)
14176                       && !EXPR_HAS_LOCATION (realret))
14177                     SET_EXPR_LOCATION (realret, loc);
14178                   return realret;
14179                 }
14180               return ret;
14181             }
14182         }
14183     }
14184   return NULL_TREE;
14185 }
14186
14187 /* Look up the function in builtin_decl that corresponds to DECL
14188    and set ASMSPEC as its user assembler name.  DECL must be a
14189    function decl that declares a builtin.  */
14190
14191 void
14192 set_builtin_user_assembler_name (tree decl, const char *asmspec)
14193 {
14194   tree builtin;
14195   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
14196               && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
14197               && asmspec != 0);
14198
14199   builtin = builtin_decl_explicit (DECL_FUNCTION_CODE (decl));
14200   set_user_assembler_name (builtin, asmspec);
14201   switch (DECL_FUNCTION_CODE (decl))
14202     {
14203     case BUILT_IN_MEMCPY:
14204       init_block_move_fn (asmspec);
14205       memcpy_libfunc = set_user_assembler_libfunc ("memcpy", asmspec);
14206       break;
14207     case BUILT_IN_MEMSET:
14208       init_block_clear_fn (asmspec);
14209       memset_libfunc = set_user_assembler_libfunc ("memset", asmspec);
14210       break;
14211     case BUILT_IN_MEMMOVE:
14212       memmove_libfunc = set_user_assembler_libfunc ("memmove", asmspec);
14213       break;
14214     case BUILT_IN_MEMCMP:
14215       memcmp_libfunc = set_user_assembler_libfunc ("memcmp", asmspec);
14216       break;
14217     case BUILT_IN_ABORT:
14218       abort_libfunc = set_user_assembler_libfunc ("abort", asmspec);
14219       break;
14220     case BUILT_IN_FFS:
14221       if (INT_TYPE_SIZE < BITS_PER_WORD)
14222         {
14223           set_user_assembler_libfunc ("ffs", asmspec);
14224           set_optab_libfunc (ffs_optab, mode_for_size (INT_TYPE_SIZE,
14225                                                        MODE_INT, 0), "ffs");
14226         }
14227       break;
14228     default:
14229       break;
14230     }
14231 }
14232
14233 /* Return true if DECL is a builtin that expands to a constant or similarly
14234    simple code.  */
14235 bool
14236 is_simple_builtin (tree decl)
14237 {
14238   if (decl && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
14239     switch (DECL_FUNCTION_CODE (decl))
14240       {
14241         /* Builtins that expand to constants.  */
14242       case BUILT_IN_CONSTANT_P:
14243       case BUILT_IN_EXPECT:
14244       case BUILT_IN_OBJECT_SIZE:
14245       case BUILT_IN_UNREACHABLE:
14246         /* Simple register moves or loads from stack.  */
14247       case BUILT_IN_ASSUME_ALIGNED:
14248       case BUILT_IN_RETURN_ADDRESS:
14249       case BUILT_IN_EXTRACT_RETURN_ADDR:
14250       case BUILT_IN_FROB_RETURN_ADDR:
14251       case BUILT_IN_RETURN:
14252       case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
14253       case BUILT_IN_FRAME_ADDRESS:
14254       case BUILT_IN_VA_END:
14255       case BUILT_IN_STACK_SAVE:
14256       case BUILT_IN_STACK_RESTORE:
14257         /* Exception state returns or moves registers around.  */
14258       case BUILT_IN_EH_FILTER:
14259       case BUILT_IN_EH_POINTER:
14260       case BUILT_IN_EH_COPY_VALUES:
14261         return true;
14262
14263       default:
14264         return false;
14265       }
14266
14267   return false;
14268 }
14269
14270 /* Return true if DECL is a builtin that is not expensive, i.e., they are
14271    most probably expanded inline into reasonably simple code.  This is a
14272    superset of is_simple_builtin.  */
14273 bool
14274 is_inexpensive_builtin (tree decl)
14275 {
14276   if (!decl)
14277     return false;
14278   else if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_MD)
14279     return true;
14280   else if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
14281     switch (DECL_FUNCTION_CODE (decl))
14282       {
14283       case BUILT_IN_ABS:
14284       case BUILT_IN_ALLOCA:
14285       case BUILT_IN_ALLOCA_WITH_ALIGN:
14286       case BUILT_IN_BSWAP16:
14287       case BUILT_IN_BSWAP32:
14288       case BUILT_IN_BSWAP64:
14289       case BUILT_IN_CLZ:
14290       case BUILT_IN_CLZIMAX:
14291       case BUILT_IN_CLZL:
14292       case BUILT_IN_CLZLL:
14293       case BUILT_IN_CTZ:
14294       case BUILT_IN_CTZIMAX:
14295       case BUILT_IN_CTZL:
14296       case BUILT_IN_CTZLL:
14297       case BUILT_IN_FFS:
14298       case BUILT_IN_FFSIMAX:
14299       case BUILT_IN_FFSL:
14300       case BUILT_IN_FFSLL:
14301       case BUILT_IN_IMAXABS:
14302       case BUILT_IN_FINITE:
14303       case BUILT_IN_FINITEF:
14304       case BUILT_IN_FINITEL:
14305       case BUILT_IN_FINITED32:
14306       case BUILT_IN_FINITED64:
14307       case BUILT_IN_FINITED128:
14308       case BUILT_IN_FPCLASSIFY:
14309       case BUILT_IN_ISFINITE:
14310       case BUILT_IN_ISINF_SIGN:
14311       case BUILT_IN_ISINF:
14312       case BUILT_IN_ISINFF:
14313       case BUILT_IN_ISINFL:
14314       case BUILT_IN_ISINFD32:
14315       case BUILT_IN_ISINFD64:
14316       case BUILT_IN_ISINFD128:
14317       case BUILT_IN_ISNAN:
14318       case BUILT_IN_ISNANF:
14319       case BUILT_IN_ISNANL:
14320       case BUILT_IN_ISNAND32:
14321       case BUILT_IN_ISNAND64:
14322       case BUILT_IN_ISNAND128:
14323       case BUILT_IN_ISNORMAL:
14324       case BUILT_IN_ISGREATER:
14325       case BUILT_IN_ISGREATEREQUAL:
14326       case BUILT_IN_ISLESS:
14327       case BUILT_IN_ISLESSEQUAL:
14328       case BUILT_IN_ISLESSGREATER:
14329       case BUILT_IN_ISUNORDERED:
14330       case BUILT_IN_VA_ARG_PACK:
14331       case BUILT_IN_VA_ARG_PACK_LEN:
14332       case BUILT_IN_VA_COPY:
14333       case BUILT_IN_TRAP:
14334       case BUILT_IN_SAVEREGS:
14335       case BUILT_IN_POPCOUNTL:
14336       case BUILT_IN_POPCOUNTLL:
14337       case BUILT_IN_POPCOUNTIMAX:
14338       case BUILT_IN_POPCOUNT:
14339       case BUILT_IN_PARITYL:
14340       case BUILT_IN_PARITYLL:
14341       case BUILT_IN_PARITYIMAX:
14342       case BUILT_IN_PARITY:
14343       case BUILT_IN_LABS:
14344       case BUILT_IN_LLABS:
14345       case BUILT_IN_PREFETCH:
14346         return true;
14347
14348       default:
14349         return is_simple_builtin (decl);
14350       }
14351
14352   return false;
14353 }