invoke.texi (SPARC Options): Document -mfix-ut699.
[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-mudflap.h"
47 #include "tree-flow.h"
48 #include "value-prof.h"
49 #include "diagnostic-core.h"
50 #include "builtins.h"
51
52
53 #ifndef PAD_VARARGS_DOWN
54 #define PAD_VARARGS_DOWN BYTES_BIG_ENDIAN
55 #endif
56 static tree do_mpc_arg1 (tree, tree, int (*)(mpc_ptr, mpc_srcptr, mpc_rnd_t));
57
58 struct target_builtins default_target_builtins;
59 #if SWITCHABLE_TARGET
60 struct target_builtins *this_target_builtins = &default_target_builtins;
61 #endif
62
63 /* Define the names of the builtin function types and codes.  */
64 const char *const built_in_class_names[4]
65   = {"NOT_BUILT_IN", "BUILT_IN_FRONTEND", "BUILT_IN_MD", "BUILT_IN_NORMAL"};
66
67 #define DEF_BUILTIN(X, N, C, T, LT, B, F, NA, AT, IM, COND) #X,
68 const char * built_in_names[(int) END_BUILTINS] =
69 {
70 #include "builtins.def"
71 };
72 #undef DEF_BUILTIN
73
74 /* Setup an array of _DECL trees, make sure each element is
75    initialized to NULL_TREE.  */
76 builtin_info_type builtin_info;
77
78 /* Non-zero if __builtin_constant_p should be folded right away.  */
79 bool force_folding_builtin_constant_p;
80
81 static const char *c_getstr (tree);
82 static rtx c_readstr (const char *, enum machine_mode);
83 static int target_char_cast (tree, char *);
84 static rtx get_memory_rtx (tree, tree);
85 static int apply_args_size (void);
86 static int apply_result_size (void);
87 #if defined (HAVE_untyped_call) || defined (HAVE_untyped_return)
88 static rtx result_vector (int, rtx);
89 #endif
90 static void expand_builtin_update_setjmp_buf (rtx);
91 static void expand_builtin_prefetch (tree);
92 static rtx expand_builtin_apply_args (void);
93 static rtx expand_builtin_apply_args_1 (void);
94 static rtx expand_builtin_apply (rtx, rtx, rtx);
95 static void expand_builtin_return (rtx);
96 static enum type_class type_to_class (tree);
97 static rtx expand_builtin_classify_type (tree);
98 static void expand_errno_check (tree, rtx);
99 static rtx expand_builtin_mathfn (tree, rtx, rtx);
100 static rtx expand_builtin_mathfn_2 (tree, rtx, rtx);
101 static rtx expand_builtin_mathfn_3 (tree, rtx, rtx);
102 static rtx expand_builtin_mathfn_ternary (tree, rtx, rtx);
103 static rtx expand_builtin_interclass_mathfn (tree, rtx);
104 static rtx expand_builtin_sincos (tree);
105 static rtx expand_builtin_cexpi (tree, rtx);
106 static rtx expand_builtin_int_roundingfn (tree, rtx);
107 static rtx expand_builtin_int_roundingfn_2 (tree, rtx);
108 static rtx expand_builtin_next_arg (void);
109 static rtx expand_builtin_va_start (tree);
110 static rtx expand_builtin_va_end (tree);
111 static rtx expand_builtin_va_copy (tree);
112 static rtx expand_builtin_memcmp (tree, rtx, enum machine_mode);
113 static rtx expand_builtin_strcmp (tree, rtx);
114 static rtx expand_builtin_strncmp (tree, rtx, enum machine_mode);
115 static rtx builtin_memcpy_read_str (void *, HOST_WIDE_INT, enum machine_mode);
116 static rtx expand_builtin_memcpy (tree, rtx);
117 static rtx expand_builtin_mempcpy (tree, rtx, enum machine_mode);
118 static rtx expand_builtin_mempcpy_args (tree, tree, tree, rtx,
119                                         enum machine_mode, int);
120 static rtx expand_builtin_strcpy (tree, rtx);
121 static rtx expand_builtin_strcpy_args (tree, tree, rtx);
122 static rtx expand_builtin_stpcpy (tree, rtx, enum machine_mode);
123 static rtx expand_builtin_strncpy (tree, rtx);
124 static rtx builtin_memset_gen_str (void *, HOST_WIDE_INT, enum machine_mode);
125 static rtx expand_builtin_memset (tree, rtx, enum machine_mode);
126 static rtx expand_builtin_memset_args (tree, tree, tree, rtx, enum machine_mode, tree);
127 static rtx expand_builtin_bzero (tree);
128 static rtx expand_builtin_strlen (tree, rtx, enum machine_mode);
129 static rtx expand_builtin_alloca (tree, bool);
130 static rtx expand_builtin_unop (enum machine_mode, tree, rtx, rtx, optab);
131 static rtx expand_builtin_frame_address (tree, tree);
132 static tree stabilize_va_list_loc (location_t, tree, int);
133 static rtx expand_builtin_expect (tree, rtx);
134 static tree fold_builtin_constant_p (tree);
135 static tree fold_builtin_expect (location_t, tree, tree);
136 static tree fold_builtin_classify_type (tree);
137 static tree fold_builtin_strlen (location_t, tree, tree);
138 static tree fold_builtin_inf (location_t, tree, int);
139 static tree fold_builtin_nan (tree, tree, int);
140 static tree rewrite_call_expr (location_t, tree, int, tree, int, ...);
141 static bool validate_arg (const_tree, enum tree_code code);
142 static bool integer_valued_real_p (tree);
143 static tree fold_trunc_transparent_mathfn (location_t, tree, tree);
144 static bool readonly_data_expr (tree);
145 static rtx expand_builtin_fabs (tree, rtx, rtx);
146 static rtx expand_builtin_signbit (tree, rtx);
147 static tree fold_builtin_sqrt (location_t, tree, tree);
148 static tree fold_builtin_cbrt (location_t, tree, tree);
149 static tree fold_builtin_pow (location_t, tree, tree, tree, tree);
150 static tree fold_builtin_powi (location_t, tree, tree, tree, tree);
151 static tree fold_builtin_cos (location_t, tree, tree, tree);
152 static tree fold_builtin_cosh (location_t, tree, tree, tree);
153 static tree fold_builtin_tan (tree, tree);
154 static tree fold_builtin_trunc (location_t, tree, tree);
155 static tree fold_builtin_floor (location_t, tree, tree);
156 static tree fold_builtin_ceil (location_t, tree, tree);
157 static tree fold_builtin_round (location_t, tree, tree);
158 static tree fold_builtin_int_roundingfn (location_t, tree, tree);
159 static tree fold_builtin_bitop (tree, tree);
160 static tree fold_builtin_memory_op (location_t, tree, tree, tree, tree, bool, int);
161 static tree fold_builtin_strchr (location_t, tree, tree, tree);
162 static tree fold_builtin_memchr (location_t, tree, tree, tree, tree);
163 static tree fold_builtin_memcmp (location_t, tree, tree, tree);
164 static tree fold_builtin_strcmp (location_t, tree, tree);
165 static tree fold_builtin_strncmp (location_t, tree, tree, tree);
166 static tree fold_builtin_signbit (location_t, tree, tree);
167 static tree fold_builtin_copysign (location_t, tree, tree, tree, tree);
168 static tree fold_builtin_isascii (location_t, tree);
169 static tree fold_builtin_toascii (location_t, tree);
170 static tree fold_builtin_isdigit (location_t, tree);
171 static tree fold_builtin_fabs (location_t, tree, tree);
172 static tree fold_builtin_abs (location_t, tree, tree);
173 static tree fold_builtin_unordered_cmp (location_t, tree, tree, tree, enum tree_code,
174                                         enum tree_code);
175 static tree fold_builtin_n (location_t, tree, tree *, int, bool);
176 static tree fold_builtin_0 (location_t, tree, bool);
177 static tree fold_builtin_1 (location_t, tree, tree, bool);
178 static tree fold_builtin_2 (location_t, tree, tree, tree, bool);
179 static tree fold_builtin_3 (location_t, tree, tree, tree, tree, bool);
180 static tree fold_builtin_4 (location_t, tree, tree, tree, tree, tree, bool);
181 static tree fold_builtin_varargs (location_t, tree, tree, bool);
182
183 static tree fold_builtin_strpbrk (location_t, tree, tree, tree);
184 static tree fold_builtin_strstr (location_t, tree, tree, tree);
185 static tree fold_builtin_strrchr (location_t, tree, tree, tree);
186 static tree fold_builtin_strcat (location_t, tree, tree);
187 static tree fold_builtin_strncat (location_t, tree, tree, tree);
188 static tree fold_builtin_strspn (location_t, tree, tree);
189 static tree fold_builtin_strcspn (location_t, tree, tree);
190 static tree fold_builtin_sprintf (location_t, tree, tree, tree, int);
191 static tree fold_builtin_snprintf (location_t, tree, tree, tree, tree, int);
192
193 static rtx expand_builtin_object_size (tree);
194 static rtx expand_builtin_memory_chk (tree, rtx, enum machine_mode,
195                                       enum built_in_function);
196 static void maybe_emit_chk_warning (tree, enum built_in_function);
197 static void maybe_emit_sprintf_chk_warning (tree, enum built_in_function);
198 static void maybe_emit_free_warning (tree);
199 static tree fold_builtin_object_size (tree, tree);
200 static tree fold_builtin_strcat_chk (location_t, tree, tree, tree, tree);
201 static tree fold_builtin_strncat_chk (location_t, tree, tree, tree, tree, tree);
202 static tree fold_builtin_sprintf_chk (location_t, tree, enum built_in_function);
203 static tree fold_builtin_printf (location_t, tree, tree, tree, bool, enum built_in_function);
204 static tree fold_builtin_fprintf (location_t, tree, tree, tree, tree, bool,
205                                   enum built_in_function);
206 static bool init_target_chars (void);
207
208 static unsigned HOST_WIDE_INT target_newline;
209 static unsigned HOST_WIDE_INT target_percent;
210 static unsigned HOST_WIDE_INT target_c;
211 static unsigned HOST_WIDE_INT target_s;
212 static char target_percent_c[3];
213 static char target_percent_s[3];
214 static char target_percent_s_newline[4];
215 static tree do_mpfr_arg1 (tree, tree, int (*)(mpfr_ptr, mpfr_srcptr, mp_rnd_t),
216                           const REAL_VALUE_TYPE *, const REAL_VALUE_TYPE *, bool);
217 static tree do_mpfr_arg2 (tree, tree, tree,
218                           int (*)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t));
219 static tree do_mpfr_arg3 (tree, tree, tree, tree,
220                           int (*)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t));
221 static tree do_mpfr_sincos (tree, tree, tree);
222 static tree do_mpfr_bessel_n (tree, tree, tree,
223                               int (*)(mpfr_ptr, long, mpfr_srcptr, mp_rnd_t),
224                               const REAL_VALUE_TYPE *, bool);
225 static tree do_mpfr_remquo (tree, tree, tree);
226 static tree do_mpfr_lgamma_r (tree, tree, tree);
227 static void expand_builtin_sync_synchronize (void);
228
229 /* Return true if NAME starts with __builtin_ or __sync_.  */
230
231 static bool
232 is_builtin_name (const char *name)
233 {
234   if (strncmp (name, "__builtin_", 10) == 0)
235     return true;
236   if (strncmp (name, "__sync_", 7) == 0)
237     return true;
238   if (strncmp (name, "__atomic_", 9) == 0)
239     return true;
240   return false;
241 }
242
243
244 /* Return true if DECL is a function symbol representing a built-in.  */
245
246 bool
247 is_builtin_fn (tree decl)
248 {
249   return TREE_CODE (decl) == FUNCTION_DECL && DECL_BUILT_IN (decl);
250 }
251
252
253 /* Return true if NODE should be considered for inline expansion regardless
254    of the optimization level.  This means whenever a function is invoked with
255    its "internal" name, which normally contains the prefix "__builtin".  */
256
257 static bool
258 called_as_built_in (tree node)
259 {
260   /* Note that we must use DECL_NAME, not DECL_ASSEMBLER_NAME_SET_P since
261      we want the name used to call the function, not the name it
262      will have. */
263   const char *name = IDENTIFIER_POINTER (DECL_NAME (node));
264   return is_builtin_name (name);
265 }
266
267 /* Compute values M and N such that M divides (address of EXP - N) and such
268    that N < M.  If these numbers can be determined, store M in alignp and N in
269    *BITPOSP and return true.  Otherwise return false and store BITS_PER_UNIT to
270    *alignp and any bit-offset to *bitposp.
271
272    Note that the address (and thus the alignment) computed here is based
273    on the address to which a symbol resolves, whereas DECL_ALIGN is based
274    on the address at which an object is actually located.  These two
275    addresses are not always the same.  For example, on ARM targets,
276    the address &foo of a Thumb function foo() has the lowest bit set,
277    whereas foo() itself starts on an even address.
278
279    If ADDR_P is true we are taking the address of the memory reference EXP
280    and thus cannot rely on the access taking place.  */
281
282 static bool
283 get_object_alignment_2 (tree exp, unsigned int *alignp,
284                         unsigned HOST_WIDE_INT *bitposp, bool addr_p)
285 {
286   HOST_WIDE_INT bitsize, bitpos;
287   tree offset;
288   enum machine_mode mode;
289   int unsignedp, volatilep;
290   unsigned int inner, align = BITS_PER_UNIT;
291   bool known_alignment = false;
292
293   /* Get the innermost object and the constant (bitpos) and possibly
294      variable (offset) offset of the access.  */
295   exp = get_inner_reference (exp, &bitsize, &bitpos, &offset,
296                              &mode, &unsignedp, &volatilep, true);
297
298   /* Extract alignment information from the innermost object and
299      possibly adjust bitpos and offset.  */
300   if (TREE_CODE (exp) == FUNCTION_DECL)
301     {
302       /* Function addresses can encode extra information besides their
303          alignment.  However, if TARGET_PTRMEMFUNC_VBIT_LOCATION
304          allows the low bit to be used as a virtual bit, we know
305          that the address itself must be at least 2-byte aligned.  */
306       if (TARGET_PTRMEMFUNC_VBIT_LOCATION == ptrmemfunc_vbit_in_pfn)
307         align = 2 * BITS_PER_UNIT;
308     }
309   else if (TREE_CODE (exp) == LABEL_DECL)
310     ;
311   else if (TREE_CODE (exp) == CONST_DECL)
312     {
313       /* The alignment of a CONST_DECL is determined by its initializer.  */
314       exp = DECL_INITIAL (exp);
315       align = TYPE_ALIGN (TREE_TYPE (exp));
316 #ifdef CONSTANT_ALIGNMENT
317       if (CONSTANT_CLASS_P (exp))
318         align = (unsigned) CONSTANT_ALIGNMENT (exp, align);
319 #endif
320       known_alignment = true;
321     }
322   else if (DECL_P (exp))
323     {
324       align = DECL_ALIGN (exp);
325       known_alignment = true;
326     }
327   else if (TREE_CODE (exp) == VIEW_CONVERT_EXPR)
328     {
329       align = TYPE_ALIGN (TREE_TYPE (exp));
330     }
331   else if (TREE_CODE (exp) == INDIRECT_REF
332            || TREE_CODE (exp) == MEM_REF
333            || TREE_CODE (exp) == TARGET_MEM_REF)
334     {
335       tree addr = TREE_OPERAND (exp, 0);
336       unsigned ptr_align;
337       unsigned HOST_WIDE_INT ptr_bitpos;
338
339       if (TREE_CODE (addr) == BIT_AND_EXPR
340           && TREE_CODE (TREE_OPERAND (addr, 1)) == INTEGER_CST)
341         {
342           align = (TREE_INT_CST_LOW (TREE_OPERAND (addr, 1))
343                     & -TREE_INT_CST_LOW (TREE_OPERAND (addr, 1)));
344           align *= BITS_PER_UNIT;
345           addr = TREE_OPERAND (addr, 0);
346         }
347
348       known_alignment
349         = get_pointer_alignment_1 (addr, &ptr_align, &ptr_bitpos);
350       align = MAX (ptr_align, align);
351
352       /* The alignment of the pointer operand in a TARGET_MEM_REF
353          has to take the variable offset parts into account.  */
354       if (TREE_CODE (exp) == TARGET_MEM_REF)
355         {
356           if (TMR_INDEX (exp))
357             {
358               unsigned HOST_WIDE_INT step = 1;
359               if (TMR_STEP (exp))
360                 step = TREE_INT_CST_LOW (TMR_STEP (exp));
361               align = MIN (align, (step & -step) * BITS_PER_UNIT);
362             }
363           if (TMR_INDEX2 (exp))
364             align = BITS_PER_UNIT;
365           known_alignment = false;
366         }
367
368       /* When EXP is an actual memory reference then we can use
369          TYPE_ALIGN of a pointer indirection to derive alignment.
370          Do so only if get_pointer_alignment_1 did not reveal absolute
371          alignment knowledge and if using that alignment would
372          improve the situation.  */
373       if (!addr_p && !known_alignment
374           && TYPE_ALIGN (TREE_TYPE (exp)) > align)
375         align = TYPE_ALIGN (TREE_TYPE (exp));
376       else
377         {
378           /* Else adjust bitpos accordingly.  */
379           bitpos += ptr_bitpos;
380           if (TREE_CODE (exp) == MEM_REF
381               || TREE_CODE (exp) == TARGET_MEM_REF)
382             bitpos += mem_ref_offset (exp).low * BITS_PER_UNIT;
383         }
384     }
385   else if (TREE_CODE (exp) == STRING_CST)
386     {
387       /* STRING_CST are the only constant objects we allow to be not
388          wrapped inside a CONST_DECL.  */
389       align = TYPE_ALIGN (TREE_TYPE (exp));
390 #ifdef CONSTANT_ALIGNMENT
391       if (CONSTANT_CLASS_P (exp))
392         align = (unsigned) CONSTANT_ALIGNMENT (exp, align);
393 #endif
394       known_alignment = true;
395     }
396
397   /* If there is a non-constant offset part extract the maximum
398      alignment that can prevail.  */
399   inner = ~0U;
400   while (offset)
401     {
402       tree next_offset;
403
404       if (TREE_CODE (offset) == PLUS_EXPR)
405         {
406           next_offset = TREE_OPERAND (offset, 0);
407           offset = TREE_OPERAND (offset, 1);
408         }
409       else
410         next_offset = NULL;
411       if (host_integerp (offset, 1))
412         {
413           /* Any overflow in calculating offset_bits won't change
414              the alignment.  */
415           unsigned offset_bits
416             = ((unsigned) tree_low_cst (offset, 1) * BITS_PER_UNIT);
417
418           if (offset_bits)
419             inner = MIN (inner, (offset_bits & -offset_bits));
420         }
421       else if (TREE_CODE (offset) == MULT_EXPR
422                && host_integerp (TREE_OPERAND (offset, 1), 1))
423         {
424           /* Any overflow in calculating offset_factor won't change
425              the alignment.  */
426           unsigned offset_factor
427             = ((unsigned) tree_low_cst (TREE_OPERAND (offset, 1), 1)
428                * BITS_PER_UNIT);
429
430           if (offset_factor)
431             inner = MIN (inner, (offset_factor & -offset_factor));
432         }
433       else
434         {
435           inner = MIN (inner, BITS_PER_UNIT);
436           break;
437         }
438       offset = next_offset;
439     }
440   /* Alignment is innermost object alignment adjusted by the constant
441      and non-constant offset parts.  */
442   align = MIN (align, inner);
443
444   *alignp = align;
445   *bitposp = bitpos & (*alignp - 1);
446   return known_alignment;
447 }
448
449 /* For a memory reference expression EXP compute values M and N such that M
450    divides (&EXP - N) and such that N < M.  If these numbers can be determined,
451    store M in alignp and N in *BITPOSP and return true.  Otherwise return false
452    and store BITS_PER_UNIT to *alignp and any bit-offset to *bitposp.  */
453
454 bool
455 get_object_alignment_1 (tree exp, unsigned int *alignp,
456                         unsigned HOST_WIDE_INT *bitposp)
457 {
458   return get_object_alignment_2 (exp, alignp, bitposp, false);
459 }
460
461 /* Return the alignment in bits of EXP, an object.  */
462
463 unsigned int
464 get_object_alignment (tree exp)
465 {
466   unsigned HOST_WIDE_INT bitpos = 0;
467   unsigned int align;
468
469   get_object_alignment_1 (exp, &align, &bitpos);
470
471   /* align and bitpos now specify known low bits of the pointer.
472      ptr & (align - 1) == bitpos.  */
473
474   if (bitpos != 0)
475     align = (bitpos & -bitpos);
476   return align;
477 }
478
479 /* For a pointer valued expression EXP compute values M and N such that M
480    divides (EXP - N) and such that N < M.  If these numbers can be determined,
481    store M in alignp and N in *BITPOSP and return true.  Return false if
482    the results are just a conservative approximation.
483
484    If EXP is not a pointer, false is returned too.  */
485
486 bool
487 get_pointer_alignment_1 (tree exp, unsigned int *alignp,
488                          unsigned HOST_WIDE_INT *bitposp)
489 {
490   STRIP_NOPS (exp);
491
492   if (TREE_CODE (exp) == ADDR_EXPR)
493     return get_object_alignment_2 (TREE_OPERAND (exp, 0),
494                                    alignp, bitposp, true);
495   else if (TREE_CODE (exp) == SSA_NAME
496            && POINTER_TYPE_P (TREE_TYPE (exp)))
497     {
498       unsigned int ptr_align, ptr_misalign;
499       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (exp);
500
501       if (pi && get_ptr_info_alignment (pi, &ptr_align, &ptr_misalign))
502         {
503           *bitposp = ptr_misalign * BITS_PER_UNIT;
504           *alignp = ptr_align * BITS_PER_UNIT;
505           /* We cannot really tell whether this result is an approximation.  */
506           return true;
507         }
508       else
509         {
510           *bitposp = 0;
511           *alignp = BITS_PER_UNIT;
512           return false;
513         }
514     }
515   else if (TREE_CODE (exp) == INTEGER_CST)
516     {
517       *alignp = BIGGEST_ALIGNMENT;
518       *bitposp = ((TREE_INT_CST_LOW (exp) * BITS_PER_UNIT)
519                   & (BIGGEST_ALIGNMENT - 1));
520       return true;
521     }
522
523   *bitposp = 0;
524   *alignp = BITS_PER_UNIT;
525   return false;
526 }
527
528 /* Return the alignment in bits of EXP, a pointer valued expression.
529    The alignment returned is, by default, the alignment of the thing that
530    EXP points to.  If it is not a POINTER_TYPE, 0 is returned.
531
532    Otherwise, look at the expression to see if we can do better, i.e., if the
533    expression is actually pointing at an object whose alignment is tighter.  */
534
535 unsigned int
536 get_pointer_alignment (tree exp)
537 {
538   unsigned HOST_WIDE_INT bitpos = 0;
539   unsigned int align;
540
541   get_pointer_alignment_1 (exp, &align, &bitpos);
542
543   /* align and bitpos now specify known low bits of the pointer.
544      ptr & (align - 1) == bitpos.  */
545
546   if (bitpos != 0)
547     align = (bitpos & -bitpos);
548
549   return align;
550 }
551
552 /* Compute the length of a C string.  TREE_STRING_LENGTH is not the right
553    way, because it could contain a zero byte in the middle.
554    TREE_STRING_LENGTH is the size of the character array, not the string.
555
556    ONLY_VALUE should be nonzero if the result is not going to be emitted
557    into the instruction stream and zero if it is going to be expanded.
558    E.g. with i++ ? "foo" : "bar", if ONLY_VALUE is nonzero, constant 3
559    is returned, otherwise NULL, since
560    len = c_strlen (src, 1); if (len) expand_expr (len, ...); would not
561    evaluate the side-effects.
562
563    The value returned is of type `ssizetype'.
564
565    Unfortunately, string_constant can't access the values of const char
566    arrays with initializers, so neither can we do so here.  */
567
568 tree
569 c_strlen (tree src, int only_value)
570 {
571   tree offset_node;
572   HOST_WIDE_INT offset;
573   int max;
574   const char *ptr;
575   location_t loc;
576
577   STRIP_NOPS (src);
578   if (TREE_CODE (src) == COND_EXPR
579       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
580     {
581       tree len1, len2;
582
583       len1 = c_strlen (TREE_OPERAND (src, 1), only_value);
584       len2 = c_strlen (TREE_OPERAND (src, 2), only_value);
585       if (tree_int_cst_equal (len1, len2))
586         return len1;
587     }
588
589   if (TREE_CODE (src) == COMPOUND_EXPR
590       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
591     return c_strlen (TREE_OPERAND (src, 1), only_value);
592
593   loc = EXPR_LOC_OR_HERE (src);
594
595   src = string_constant (src, &offset_node);
596   if (src == 0)
597     return NULL_TREE;
598
599   max = TREE_STRING_LENGTH (src) - 1;
600   ptr = TREE_STRING_POINTER (src);
601
602   if (offset_node && TREE_CODE (offset_node) != INTEGER_CST)
603     {
604       /* If the string has an internal zero byte (e.g., "foo\0bar"), we can't
605          compute the offset to the following null if we don't know where to
606          start searching for it.  */
607       int i;
608
609       for (i = 0; i < max; i++)
610         if (ptr[i] == 0)
611           return NULL_TREE;
612
613       /* We don't know the starting offset, but we do know that the string
614          has no internal zero bytes.  We can assume that the offset falls
615          within the bounds of the string; otherwise, the programmer deserves
616          what he gets.  Subtract the offset from the length of the string,
617          and return that.  This would perhaps not be valid if we were dealing
618          with named arrays in addition to literal string constants.  */
619
620       return size_diffop_loc (loc, size_int (max), offset_node);
621     }
622
623   /* We have a known offset into the string.  Start searching there for
624      a null character if we can represent it as a single HOST_WIDE_INT.  */
625   if (offset_node == 0)
626     offset = 0;
627   else if (! host_integerp (offset_node, 0))
628     offset = -1;
629   else
630     offset = tree_low_cst (offset_node, 0);
631
632   /* If the offset is known to be out of bounds, warn, and call strlen at
633      runtime.  */
634   if (offset < 0 || offset > max)
635     {
636      /* Suppress multiple warnings for propagated constant strings.  */
637       if (! TREE_NO_WARNING (src))
638         {
639           warning_at (loc, 0, "offset outside bounds of constant string");
640           TREE_NO_WARNING (src) = 1;
641         }
642       return NULL_TREE;
643     }
644
645   /* Use strlen to search for the first zero byte.  Since any strings
646      constructed with build_string will have nulls appended, we win even
647      if we get handed something like (char[4])"abcd".
648
649      Since OFFSET is our starting index into the string, no further
650      calculation is needed.  */
651   return ssize_int (strlen (ptr + offset));
652 }
653
654 /* Return a char pointer for a C string if it is a string constant
655    or sum of string constant and integer constant.  */
656
657 static const char *
658 c_getstr (tree src)
659 {
660   tree offset_node;
661
662   src = string_constant (src, &offset_node);
663   if (src == 0)
664     return 0;
665
666   if (offset_node == 0)
667     return TREE_STRING_POINTER (src);
668   else if (!host_integerp (offset_node, 1)
669            || compare_tree_int (offset_node, TREE_STRING_LENGTH (src) - 1) > 0)
670     return 0;
671
672   return TREE_STRING_POINTER (src) + tree_low_cst (offset_node, 1);
673 }
674
675 /* Return a CONST_INT or CONST_DOUBLE corresponding to target reading
676    GET_MODE_BITSIZE (MODE) bits from string constant STR.  */
677
678 static rtx
679 c_readstr (const char *str, enum machine_mode mode)
680 {
681   HOST_WIDE_INT c[2];
682   HOST_WIDE_INT ch;
683   unsigned int i, j;
684
685   gcc_assert (GET_MODE_CLASS (mode) == MODE_INT);
686
687   c[0] = 0;
688   c[1] = 0;
689   ch = 1;
690   for (i = 0; i < GET_MODE_SIZE (mode); i++)
691     {
692       j = i;
693       if (WORDS_BIG_ENDIAN)
694         j = GET_MODE_SIZE (mode) - i - 1;
695       if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN
696           && GET_MODE_SIZE (mode) >= UNITS_PER_WORD)
697         j = j + UNITS_PER_WORD - 2 * (j % UNITS_PER_WORD) - 1;
698       j *= BITS_PER_UNIT;
699       gcc_assert (j < HOST_BITS_PER_DOUBLE_INT);
700
701       if (ch)
702         ch = (unsigned char) str[i];
703       c[j / HOST_BITS_PER_WIDE_INT] |= ch << (j % HOST_BITS_PER_WIDE_INT);
704     }
705   return immed_double_const (c[0], c[1], mode);
706 }
707
708 /* Cast a target constant CST to target CHAR and if that value fits into
709    host char type, return zero and put that value into variable pointed to by
710    P.  */
711
712 static int
713 target_char_cast (tree cst, char *p)
714 {
715   unsigned HOST_WIDE_INT val, hostval;
716
717   if (TREE_CODE (cst) != INTEGER_CST
718       || CHAR_TYPE_SIZE > HOST_BITS_PER_WIDE_INT)
719     return 1;
720
721   val = TREE_INT_CST_LOW (cst);
722   if (CHAR_TYPE_SIZE < HOST_BITS_PER_WIDE_INT)
723     val &= (((unsigned HOST_WIDE_INT) 1) << CHAR_TYPE_SIZE) - 1;
724
725   hostval = val;
726   if (HOST_BITS_PER_CHAR < HOST_BITS_PER_WIDE_INT)
727     hostval &= (((unsigned HOST_WIDE_INT) 1) << HOST_BITS_PER_CHAR) - 1;
728
729   if (val != hostval)
730     return 1;
731
732   *p = hostval;
733   return 0;
734 }
735
736 /* Similar to save_expr, but assumes that arbitrary code is not executed
737    in between the multiple evaluations.  In particular, we assume that a
738    non-addressable local variable will not be modified.  */
739
740 static tree
741 builtin_save_expr (tree exp)
742 {
743   if (TREE_CODE (exp) == SSA_NAME
744       || (TREE_ADDRESSABLE (exp) == 0
745           && (TREE_CODE (exp) == PARM_DECL
746               || (TREE_CODE (exp) == VAR_DECL && !TREE_STATIC (exp)))))
747     return exp;
748
749   return save_expr (exp);
750 }
751
752 /* Given TEM, a pointer to a stack frame, follow the dynamic chain COUNT
753    times to get the address of either a higher stack frame, or a return
754    address located within it (depending on FNDECL_CODE).  */
755
756 static rtx
757 expand_builtin_return_addr (enum built_in_function fndecl_code, int count)
758 {
759   int i;
760
761 #ifdef INITIAL_FRAME_ADDRESS_RTX
762   rtx tem = INITIAL_FRAME_ADDRESS_RTX;
763 #else
764   rtx tem;
765
766   /* For a zero count with __builtin_return_address, we don't care what
767      frame address we return, because target-specific definitions will
768      override us.  Therefore frame pointer elimination is OK, and using
769      the soft frame pointer is OK.
770
771      For a nonzero count, or a zero count with __builtin_frame_address,
772      we require a stable offset from the current frame pointer to the
773      previous one, so we must use the hard frame pointer, and
774      we must disable frame pointer elimination.  */
775   if (count == 0 && fndecl_code == BUILT_IN_RETURN_ADDRESS)
776     tem = frame_pointer_rtx;
777   else
778     {
779       tem = hard_frame_pointer_rtx;
780
781       /* Tell reload not to eliminate the frame pointer.  */
782       crtl->accesses_prior_frames = 1;
783     }
784 #endif
785
786   /* Some machines need special handling before we can access
787      arbitrary frames.  For example, on the SPARC, we must first flush
788      all register windows to the stack.  */
789 #ifdef SETUP_FRAME_ADDRESSES
790   if (count > 0)
791     SETUP_FRAME_ADDRESSES ();
792 #endif
793
794   /* On the SPARC, the return address is not in the frame, it is in a
795      register.  There is no way to access it off of the current frame
796      pointer, but it can be accessed off the previous frame pointer by
797      reading the value from the register window save area.  */
798 #ifdef RETURN_ADDR_IN_PREVIOUS_FRAME
799   if (fndecl_code == BUILT_IN_RETURN_ADDRESS)
800     count--;
801 #endif
802
803   /* Scan back COUNT frames to the specified frame.  */
804   for (i = 0; i < count; i++)
805     {
806       /* Assume the dynamic chain pointer is in the word that the
807          frame address points to, unless otherwise specified.  */
808 #ifdef DYNAMIC_CHAIN_ADDRESS
809       tem = DYNAMIC_CHAIN_ADDRESS (tem);
810 #endif
811       tem = memory_address (Pmode, tem);
812       tem = gen_frame_mem (Pmode, tem);
813       tem = copy_to_reg (tem);
814     }
815
816   /* For __builtin_frame_address, return what we've got.  But, on
817      the SPARC for example, we may have to add a bias.  */
818   if (fndecl_code == BUILT_IN_FRAME_ADDRESS)
819 #ifdef FRAME_ADDR_RTX
820     return FRAME_ADDR_RTX (tem);
821 #else
822     return tem;
823 #endif
824
825   /* For __builtin_return_address, get the return address from that frame.  */
826 #ifdef RETURN_ADDR_RTX
827   tem = RETURN_ADDR_RTX (count, tem);
828 #else
829   tem = memory_address (Pmode,
830                         plus_constant (Pmode, tem, GET_MODE_SIZE (Pmode)));
831   tem = gen_frame_mem (Pmode, tem);
832 #endif
833   return tem;
834 }
835
836 /* Alias set used for setjmp buffer.  */
837 static alias_set_type setjmp_alias_set = -1;
838
839 /* Construct the leading half of a __builtin_setjmp call.  Control will
840    return to RECEIVER_LABEL.  This is also called directly by the SJLJ
841    exception handling code.  */
842
843 void
844 expand_builtin_setjmp_setup (rtx buf_addr, rtx receiver_label)
845 {
846   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
847   rtx stack_save;
848   rtx mem;
849
850   if (setjmp_alias_set == -1)
851     setjmp_alias_set = new_alias_set ();
852
853   buf_addr = convert_memory_address (Pmode, buf_addr);
854
855   buf_addr = force_reg (Pmode, force_operand (buf_addr, NULL_RTX));
856
857   /* We store the frame pointer and the address of receiver_label in
858      the buffer and use the rest of it for the stack save area, which
859      is machine-dependent.  */
860
861   mem = gen_rtx_MEM (Pmode, buf_addr);
862   set_mem_alias_set (mem, setjmp_alias_set);
863   emit_move_insn (mem, targetm.builtin_setjmp_frame_value ());
864
865   mem = gen_rtx_MEM (Pmode, plus_constant (Pmode, buf_addr,
866                                            GET_MODE_SIZE (Pmode))),
867   set_mem_alias_set (mem, setjmp_alias_set);
868
869   emit_move_insn (validize_mem (mem),
870                   force_reg (Pmode, gen_rtx_LABEL_REF (Pmode, receiver_label)));
871
872   stack_save = gen_rtx_MEM (sa_mode,
873                             plus_constant (Pmode, buf_addr,
874                                            2 * GET_MODE_SIZE (Pmode)));
875   set_mem_alias_set (stack_save, setjmp_alias_set);
876   emit_stack_save (SAVE_NONLOCAL, &stack_save);
877
878   /* If there is further processing to do, do it.  */
879 #ifdef HAVE_builtin_setjmp_setup
880   if (HAVE_builtin_setjmp_setup)
881     emit_insn (gen_builtin_setjmp_setup (buf_addr));
882 #endif
883
884   /* We have a nonlocal label.   */
885   cfun->has_nonlocal_label = 1;
886 }
887
888 /* Construct the trailing part of a __builtin_setjmp call.  This is
889    also called directly by the SJLJ exception handling code.  */
890
891 void
892 expand_builtin_setjmp_receiver (rtx receiver_label ATTRIBUTE_UNUSED)
893 {
894   rtx chain;
895
896   /* Clobber the FP when we get here, so we have to make sure it's
897      marked as used by this function.  */
898   emit_use (hard_frame_pointer_rtx);
899
900   /* Mark the static chain as clobbered here so life information
901      doesn't get messed up for it.  */
902   chain = targetm.calls.static_chain (current_function_decl, true);
903   if (chain && REG_P (chain))
904     emit_clobber (chain);
905
906   /* Now put in the code to restore the frame pointer, and argument
907      pointer, if needed.  */
908 #ifdef HAVE_nonlocal_goto
909   if (! HAVE_nonlocal_goto)
910 #endif
911     {
912       emit_move_insn (virtual_stack_vars_rtx, hard_frame_pointer_rtx);
913       /* This might change the hard frame pointer in ways that aren't
914          apparent to early optimization passes, so force a clobber.  */
915       emit_clobber (hard_frame_pointer_rtx);
916     }
917
918 #if !HARD_FRAME_POINTER_IS_ARG_POINTER
919   if (fixed_regs[ARG_POINTER_REGNUM])
920     {
921 #ifdef ELIMINABLE_REGS
922       size_t i;
923       static const struct elims {const int from, to;} elim_regs[] = ELIMINABLE_REGS;
924
925       for (i = 0; i < ARRAY_SIZE (elim_regs); i++)
926         if (elim_regs[i].from == ARG_POINTER_REGNUM
927             && elim_regs[i].to == HARD_FRAME_POINTER_REGNUM)
928           break;
929
930       if (i == ARRAY_SIZE (elim_regs))
931 #endif
932         {
933           /* Now restore our arg pointer from the address at which it
934              was saved in our stack frame.  */
935           emit_move_insn (crtl->args.internal_arg_pointer,
936                           copy_to_reg (get_arg_pointer_save_area ()));
937         }
938     }
939 #endif
940
941 #ifdef HAVE_builtin_setjmp_receiver
942   if (HAVE_builtin_setjmp_receiver)
943     emit_insn (gen_builtin_setjmp_receiver (receiver_label));
944   else
945 #endif
946 #ifdef HAVE_nonlocal_goto_receiver
947     if (HAVE_nonlocal_goto_receiver)
948       emit_insn (gen_nonlocal_goto_receiver ());
949     else
950 #endif
951       { /* Nothing */ }
952
953   /* We must not allow the code we just generated to be reordered by
954      scheduling.  Specifically, the update of the frame pointer must
955      happen immediately, not later.  Similarly, we must block
956      (frame-related) register values to be used across this code.  */
957   emit_insn (gen_blockage ());
958 }
959
960 /* __builtin_longjmp is passed a pointer to an array of five words (not
961    all will be used on all machines).  It operates similarly to the C
962    library function of the same name, but is more efficient.  Much of
963    the code below is copied from the handling of non-local gotos.  */
964
965 static void
966 expand_builtin_longjmp (rtx buf_addr, rtx value)
967 {
968   rtx fp, lab, stack, insn, last;
969   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
970
971   /* DRAP is needed for stack realign if longjmp is expanded to current
972      function  */
973   if (SUPPORTS_STACK_ALIGNMENT)
974     crtl->need_drap = true;
975
976   if (setjmp_alias_set == -1)
977     setjmp_alias_set = new_alias_set ();
978
979   buf_addr = convert_memory_address (Pmode, buf_addr);
980
981   buf_addr = force_reg (Pmode, buf_addr);
982
983   /* We require that the user must pass a second argument of 1, because
984      that is what builtin_setjmp will return.  */
985   gcc_assert (value == const1_rtx);
986
987   last = get_last_insn ();
988 #ifdef HAVE_builtin_longjmp
989   if (HAVE_builtin_longjmp)
990     emit_insn (gen_builtin_longjmp (buf_addr));
991   else
992 #endif
993     {
994       fp = gen_rtx_MEM (Pmode, buf_addr);
995       lab = gen_rtx_MEM (Pmode, plus_constant (Pmode, buf_addr,
996                                                GET_MODE_SIZE (Pmode)));
997
998       stack = gen_rtx_MEM (sa_mode, plus_constant (Pmode, buf_addr,
999                                                    2 * GET_MODE_SIZE (Pmode)));
1000       set_mem_alias_set (fp, setjmp_alias_set);
1001       set_mem_alias_set (lab, setjmp_alias_set);
1002       set_mem_alias_set (stack, setjmp_alias_set);
1003
1004       /* Pick up FP, label, and SP from the block and jump.  This code is
1005          from expand_goto in stmt.c; see there for detailed comments.  */
1006 #ifdef HAVE_nonlocal_goto
1007       if (HAVE_nonlocal_goto)
1008         /* We have to pass a value to the nonlocal_goto pattern that will
1009            get copied into the static_chain pointer, but it does not matter
1010            what that value is, because builtin_setjmp does not use it.  */
1011         emit_insn (gen_nonlocal_goto (value, lab, stack, fp));
1012       else
1013 #endif
1014         {
1015           lab = copy_to_reg (lab);
1016
1017           emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
1018           emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
1019
1020           emit_move_insn (hard_frame_pointer_rtx, fp);
1021           emit_stack_restore (SAVE_NONLOCAL, stack);
1022
1023           emit_use (hard_frame_pointer_rtx);
1024           emit_use (stack_pointer_rtx);
1025           emit_indirect_jump (lab);
1026         }
1027     }
1028
1029   /* Search backwards and mark the jump insn as a non-local goto.
1030      Note that this precludes the use of __builtin_longjmp to a
1031      __builtin_setjmp target in the same function.  However, we've
1032      already cautioned the user that these functions are for
1033      internal exception handling use only.  */
1034   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
1035     {
1036       gcc_assert (insn != last);
1037
1038       if (JUMP_P (insn))
1039         {
1040           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
1041           break;
1042         }
1043       else if (CALL_P (insn))
1044         break;
1045     }
1046 }
1047
1048 /* Expand a call to __builtin_nonlocal_goto.  We're passed the target label
1049    and the address of the save area.  */
1050
1051 static rtx
1052 expand_builtin_nonlocal_goto (tree exp)
1053 {
1054   tree t_label, t_save_area;
1055   rtx r_label, r_save_area, r_fp, r_sp, insn;
1056
1057   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
1058     return NULL_RTX;
1059
1060   t_label = CALL_EXPR_ARG (exp, 0);
1061   t_save_area = CALL_EXPR_ARG (exp, 1);
1062
1063   r_label = expand_normal (t_label);
1064   r_label = convert_memory_address (Pmode, r_label);
1065   r_save_area = expand_normal (t_save_area);
1066   r_save_area = convert_memory_address (Pmode, r_save_area);
1067   /* Copy the address of the save location to a register just in case it was
1068      based on the frame pointer.   */
1069   r_save_area = copy_to_reg (r_save_area);
1070   r_fp = gen_rtx_MEM (Pmode, r_save_area);
1071   r_sp = gen_rtx_MEM (STACK_SAVEAREA_MODE (SAVE_NONLOCAL),
1072                       plus_constant (Pmode, r_save_area,
1073                                      GET_MODE_SIZE (Pmode)));
1074
1075   crtl->has_nonlocal_goto = 1;
1076
1077 #ifdef HAVE_nonlocal_goto
1078   /* ??? We no longer need to pass the static chain value, afaik.  */
1079   if (HAVE_nonlocal_goto)
1080     emit_insn (gen_nonlocal_goto (const0_rtx, r_label, r_sp, r_fp));
1081   else
1082 #endif
1083     {
1084       r_label = copy_to_reg (r_label);
1085
1086       emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
1087       emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
1088
1089       /* Restore frame pointer for containing function.  */
1090       emit_move_insn (hard_frame_pointer_rtx, r_fp);
1091       emit_stack_restore (SAVE_NONLOCAL, r_sp);
1092
1093       /* USE of hard_frame_pointer_rtx added for consistency;
1094          not clear if really needed.  */
1095       emit_use (hard_frame_pointer_rtx);
1096       emit_use (stack_pointer_rtx);
1097
1098       /* If the architecture is using a GP register, we must
1099          conservatively assume that the target function makes use of it.
1100          The prologue of functions with nonlocal gotos must therefore
1101          initialize the GP register to the appropriate value, and we
1102          must then make sure that this value is live at the point
1103          of the jump.  (Note that this doesn't necessarily apply
1104          to targets with a nonlocal_goto pattern; they are free
1105          to implement it in their own way.  Note also that this is
1106          a no-op if the GP register is a global invariant.)  */
1107       if ((unsigned) PIC_OFFSET_TABLE_REGNUM != INVALID_REGNUM
1108           && fixed_regs[PIC_OFFSET_TABLE_REGNUM])
1109         emit_use (pic_offset_table_rtx);
1110
1111       emit_indirect_jump (r_label);
1112     }
1113
1114   /* Search backwards to the jump insn and mark it as a
1115      non-local goto.  */
1116   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
1117     {
1118       if (JUMP_P (insn))
1119         {
1120           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
1121           break;
1122         }
1123       else if (CALL_P (insn))
1124         break;
1125     }
1126
1127   return const0_rtx;
1128 }
1129
1130 /* __builtin_update_setjmp_buf is passed a pointer to an array of five words
1131    (not all will be used on all machines) that was passed to __builtin_setjmp.
1132    It updates the stack pointer in that block to correspond to the current
1133    stack pointer.  */
1134
1135 static void
1136 expand_builtin_update_setjmp_buf (rtx buf_addr)
1137 {
1138   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
1139   rtx stack_save
1140     = gen_rtx_MEM (sa_mode,
1141                    memory_address
1142                    (sa_mode,
1143                     plus_constant (Pmode, buf_addr,
1144                                    2 * GET_MODE_SIZE (Pmode))));
1145
1146   emit_stack_save (SAVE_NONLOCAL, &stack_save);
1147 }
1148
1149 /* Expand a call to __builtin_prefetch.  For a target that does not support
1150    data prefetch, evaluate the memory address argument in case it has side
1151    effects.  */
1152
1153 static void
1154 expand_builtin_prefetch (tree exp)
1155 {
1156   tree arg0, arg1, arg2;
1157   int nargs;
1158   rtx op0, op1, op2;
1159
1160   if (!validate_arglist (exp, POINTER_TYPE, 0))
1161     return;
1162
1163   arg0 = CALL_EXPR_ARG (exp, 0);
1164
1165   /* Arguments 1 and 2 are optional; argument 1 (read/write) defaults to
1166      zero (read) and argument 2 (locality) defaults to 3 (high degree of
1167      locality).  */
1168   nargs = call_expr_nargs (exp);
1169   if (nargs > 1)
1170     arg1 = CALL_EXPR_ARG (exp, 1);
1171   else
1172     arg1 = integer_zero_node;
1173   if (nargs > 2)
1174     arg2 = CALL_EXPR_ARG (exp, 2);
1175   else
1176     arg2 = integer_three_node;
1177
1178   /* Argument 0 is an address.  */
1179   op0 = expand_expr (arg0, NULL_RTX, Pmode, EXPAND_NORMAL);
1180
1181   /* Argument 1 (read/write flag) must be a compile-time constant int.  */
1182   if (TREE_CODE (arg1) != INTEGER_CST)
1183     {
1184       error ("second argument to %<__builtin_prefetch%> must be a constant");
1185       arg1 = integer_zero_node;
1186     }
1187   op1 = expand_normal (arg1);
1188   /* Argument 1 must be either zero or one.  */
1189   if (INTVAL (op1) != 0 && INTVAL (op1) != 1)
1190     {
1191       warning (0, "invalid second argument to %<__builtin_prefetch%>;"
1192                " using zero");
1193       op1 = const0_rtx;
1194     }
1195
1196   /* Argument 2 (locality) must be a compile-time constant int.  */
1197   if (TREE_CODE (arg2) != INTEGER_CST)
1198     {
1199       error ("third argument to %<__builtin_prefetch%> must be a constant");
1200       arg2 = integer_zero_node;
1201     }
1202   op2 = expand_normal (arg2);
1203   /* Argument 2 must be 0, 1, 2, or 3.  */
1204   if (INTVAL (op2) < 0 || INTVAL (op2) > 3)
1205     {
1206       warning (0, "invalid third argument to %<__builtin_prefetch%>; using zero");
1207       op2 = const0_rtx;
1208     }
1209
1210 #ifdef HAVE_prefetch
1211   if (HAVE_prefetch)
1212     {
1213       struct expand_operand ops[3];
1214
1215       create_address_operand (&ops[0], op0);
1216       create_integer_operand (&ops[1], INTVAL (op1));
1217       create_integer_operand (&ops[2], INTVAL (op2));
1218       if (maybe_expand_insn (CODE_FOR_prefetch, 3, ops))
1219         return;
1220     }
1221 #endif
1222
1223   /* Don't do anything with direct references to volatile memory, but
1224      generate code to handle other side effects.  */
1225   if (!MEM_P (op0) && side_effects_p (op0))
1226     emit_insn (op0);
1227 }
1228
1229 /* Get a MEM rtx for expression EXP which is the address of an operand
1230    to be used in a string instruction (cmpstrsi, movmemsi, ..).  LEN is
1231    the maximum length of the block of memory that might be accessed or
1232    NULL if unknown.  */
1233
1234 static rtx
1235 get_memory_rtx (tree exp, tree len)
1236 {
1237   tree orig_exp = exp;
1238   rtx addr, mem;
1239
1240   /* When EXP is not resolved SAVE_EXPR, MEM_ATTRS can be still derived
1241      from its expression, for expr->a.b only <variable>.a.b is recorded.  */
1242   if (TREE_CODE (exp) == SAVE_EXPR && !SAVE_EXPR_RESOLVED_P (exp))
1243     exp = TREE_OPERAND (exp, 0);
1244
1245   addr = expand_expr (orig_exp, NULL_RTX, ptr_mode, EXPAND_NORMAL);
1246   mem = gen_rtx_MEM (BLKmode, memory_address (BLKmode, addr));
1247
1248   /* Get an expression we can use to find the attributes to assign to MEM.
1249      First remove any nops.  */
1250   while (CONVERT_EXPR_P (exp)
1251          && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (exp, 0))))
1252     exp = TREE_OPERAND (exp, 0);
1253
1254   /* Build a MEM_REF representing the whole accessed area as a byte blob,
1255      (as builtin stringops may alias with anything).  */
1256   exp = fold_build2 (MEM_REF,
1257                      build_array_type (char_type_node,
1258                                        build_range_type (sizetype,
1259                                                          size_one_node, len)),
1260                      exp, build_int_cst (ptr_type_node, 0));
1261
1262   /* If the MEM_REF has no acceptable address, try to get the base object
1263      from the original address we got, and build an all-aliasing
1264      unknown-sized access to that one.  */
1265   if (is_gimple_mem_ref_addr (TREE_OPERAND (exp, 0)))
1266     set_mem_attributes (mem, exp, 0);
1267   else if (TREE_CODE (TREE_OPERAND (exp, 0)) == ADDR_EXPR
1268            && (exp = get_base_address (TREE_OPERAND (TREE_OPERAND (exp, 0),
1269                                                      0))))
1270     {
1271       exp = build_fold_addr_expr (exp);
1272       exp = fold_build2 (MEM_REF,
1273                          build_array_type (char_type_node,
1274                                            build_range_type (sizetype,
1275                                                              size_zero_node,
1276                                                              NULL)),
1277                          exp, build_int_cst (ptr_type_node, 0));
1278       set_mem_attributes (mem, exp, 0);
1279     }
1280   set_mem_alias_set (mem, 0);
1281   return mem;
1282 }
1283 \f
1284 /* Built-in functions to perform an untyped call and return.  */
1285
1286 #define apply_args_mode \
1287   (this_target_builtins->x_apply_args_mode)
1288 #define apply_result_mode \
1289   (this_target_builtins->x_apply_result_mode)
1290
1291 /* Return the size required for the block returned by __builtin_apply_args,
1292    and initialize apply_args_mode.  */
1293
1294 static int
1295 apply_args_size (void)
1296 {
1297   static int size = -1;
1298   int align;
1299   unsigned int regno;
1300   enum machine_mode mode;
1301
1302   /* The values computed by this function never change.  */
1303   if (size < 0)
1304     {
1305       /* The first value is the incoming arg-pointer.  */
1306       size = GET_MODE_SIZE (Pmode);
1307
1308       /* The second value is the structure value address unless this is
1309          passed as an "invisible" first argument.  */
1310       if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1311         size += GET_MODE_SIZE (Pmode);
1312
1313       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1314         if (FUNCTION_ARG_REGNO_P (regno))
1315           {
1316             mode = targetm.calls.get_raw_arg_mode (regno);
1317
1318             gcc_assert (mode != VOIDmode);
1319
1320             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1321             if (size % align != 0)
1322               size = CEIL (size, align) * align;
1323             size += GET_MODE_SIZE (mode);
1324             apply_args_mode[regno] = mode;
1325           }
1326         else
1327           {
1328             apply_args_mode[regno] = VOIDmode;
1329           }
1330     }
1331   return size;
1332 }
1333
1334 /* Return the size required for the block returned by __builtin_apply,
1335    and initialize apply_result_mode.  */
1336
1337 static int
1338 apply_result_size (void)
1339 {
1340   static int size = -1;
1341   int align, regno;
1342   enum machine_mode mode;
1343
1344   /* The values computed by this function never change.  */
1345   if (size < 0)
1346     {
1347       size = 0;
1348
1349       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1350         if (targetm.calls.function_value_regno_p (regno))
1351           {
1352             mode = targetm.calls.get_raw_result_mode (regno);
1353
1354             gcc_assert (mode != VOIDmode);
1355
1356             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1357             if (size % align != 0)
1358               size = CEIL (size, align) * align;
1359             size += GET_MODE_SIZE (mode);
1360             apply_result_mode[regno] = mode;
1361           }
1362         else
1363           apply_result_mode[regno] = VOIDmode;
1364
1365       /* Allow targets that use untyped_call and untyped_return to override
1366          the size so that machine-specific information can be stored here.  */
1367 #ifdef APPLY_RESULT_SIZE
1368       size = APPLY_RESULT_SIZE;
1369 #endif
1370     }
1371   return size;
1372 }
1373
1374 #if defined (HAVE_untyped_call) || defined (HAVE_untyped_return)
1375 /* Create a vector describing the result block RESULT.  If SAVEP is true,
1376    the result block is used to save the values; otherwise it is used to
1377    restore the values.  */
1378
1379 static rtx
1380 result_vector (int savep, rtx result)
1381 {
1382   int regno, size, align, nelts;
1383   enum machine_mode mode;
1384   rtx reg, mem;
1385   rtx *savevec = XALLOCAVEC (rtx, FIRST_PSEUDO_REGISTER);
1386
1387   size = nelts = 0;
1388   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1389     if ((mode = apply_result_mode[regno]) != VOIDmode)
1390       {
1391         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1392         if (size % align != 0)
1393           size = CEIL (size, align) * align;
1394         reg = gen_rtx_REG (mode, savep ? regno : INCOMING_REGNO (regno));
1395         mem = adjust_address (result, mode, size);
1396         savevec[nelts++] = (savep
1397                             ? gen_rtx_SET (VOIDmode, mem, reg)
1398                             : gen_rtx_SET (VOIDmode, reg, mem));
1399         size += GET_MODE_SIZE (mode);
1400       }
1401   return gen_rtx_PARALLEL (VOIDmode, gen_rtvec_v (nelts, savevec));
1402 }
1403 #endif /* HAVE_untyped_call or HAVE_untyped_return */
1404
1405 /* Save the state required to perform an untyped call with the same
1406    arguments as were passed to the current function.  */
1407
1408 static rtx
1409 expand_builtin_apply_args_1 (void)
1410 {
1411   rtx registers, tem;
1412   int size, align, regno;
1413   enum machine_mode mode;
1414   rtx struct_incoming_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 1);
1415
1416   /* Create a block where the arg-pointer, structure value address,
1417      and argument registers can be saved.  */
1418   registers = assign_stack_local (BLKmode, apply_args_size (), -1);
1419
1420   /* Walk past the arg-pointer and structure value address.  */
1421   size = GET_MODE_SIZE (Pmode);
1422   if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1423     size += GET_MODE_SIZE (Pmode);
1424
1425   /* Save each register used in calling a function to the block.  */
1426   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1427     if ((mode = apply_args_mode[regno]) != VOIDmode)
1428       {
1429         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1430         if (size % align != 0)
1431           size = CEIL (size, align) * align;
1432
1433         tem = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1434
1435         emit_move_insn (adjust_address (registers, mode, size), tem);
1436         size += GET_MODE_SIZE (mode);
1437       }
1438
1439   /* Save the arg pointer to the block.  */
1440   tem = copy_to_reg (crtl->args.internal_arg_pointer);
1441 #ifdef STACK_GROWS_DOWNWARD
1442   /* We need the pointer as the caller actually passed them to us, not
1443      as we might have pretended they were passed.  Make sure it's a valid
1444      operand, as emit_move_insn isn't expected to handle a PLUS.  */
1445   tem
1446     = force_operand (plus_constant (Pmode, tem, crtl->args.pretend_args_size),
1447                      NULL_RTX);
1448 #endif
1449   emit_move_insn (adjust_address (registers, Pmode, 0), tem);
1450
1451   size = GET_MODE_SIZE (Pmode);
1452
1453   /* Save the structure value address unless this is passed as an
1454      "invisible" first argument.  */
1455   if (struct_incoming_value)
1456     {
1457       emit_move_insn (adjust_address (registers, Pmode, size),
1458                       copy_to_reg (struct_incoming_value));
1459       size += GET_MODE_SIZE (Pmode);
1460     }
1461
1462   /* Return the address of the block.  */
1463   return copy_addr_to_reg (XEXP (registers, 0));
1464 }
1465
1466 /* __builtin_apply_args returns block of memory allocated on
1467    the stack into which is stored the arg pointer, structure
1468    value address, static chain, and all the registers that might
1469    possibly be used in performing a function call.  The code is
1470    moved to the start of the function so the incoming values are
1471    saved.  */
1472
1473 static rtx
1474 expand_builtin_apply_args (void)
1475 {
1476   /* Don't do __builtin_apply_args more than once in a function.
1477      Save the result of the first call and reuse it.  */
1478   if (apply_args_value != 0)
1479     return apply_args_value;
1480   {
1481     /* When this function is called, it means that registers must be
1482        saved on entry to this function.  So we migrate the
1483        call to the first insn of this function.  */
1484     rtx temp;
1485     rtx seq;
1486
1487     start_sequence ();
1488     temp = expand_builtin_apply_args_1 ();
1489     seq = get_insns ();
1490     end_sequence ();
1491
1492     apply_args_value = temp;
1493
1494     /* Put the insns after the NOTE that starts the function.
1495        If this is inside a start_sequence, make the outer-level insn
1496        chain current, so the code is placed at the start of the
1497        function.  If internal_arg_pointer is a non-virtual pseudo,
1498        it needs to be placed after the function that initializes
1499        that pseudo.  */
1500     push_topmost_sequence ();
1501     if (REG_P (crtl->args.internal_arg_pointer)
1502         && REGNO (crtl->args.internal_arg_pointer) > LAST_VIRTUAL_REGISTER)
1503       emit_insn_before (seq, parm_birth_insn);
1504     else
1505       emit_insn_before (seq, NEXT_INSN (entry_of_function ()));
1506     pop_topmost_sequence ();
1507     return temp;
1508   }
1509 }
1510
1511 /* Perform an untyped call and save the state required to perform an
1512    untyped return of whatever value was returned by the given function.  */
1513
1514 static rtx
1515 expand_builtin_apply (rtx function, rtx arguments, rtx argsize)
1516 {
1517   int size, align, regno;
1518   enum machine_mode mode;
1519   rtx incoming_args, result, reg, dest, src, call_insn;
1520   rtx old_stack_level = 0;
1521   rtx call_fusage = 0;
1522   rtx struct_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0);
1523
1524   arguments = convert_memory_address (Pmode, arguments);
1525
1526   /* Create a block where the return registers can be saved.  */
1527   result = assign_stack_local (BLKmode, apply_result_size (), -1);
1528
1529   /* Fetch the arg pointer from the ARGUMENTS block.  */
1530   incoming_args = gen_reg_rtx (Pmode);
1531   emit_move_insn (incoming_args, gen_rtx_MEM (Pmode, arguments));
1532 #ifndef STACK_GROWS_DOWNWARD
1533   incoming_args = expand_simple_binop (Pmode, MINUS, incoming_args, argsize,
1534                                        incoming_args, 0, OPTAB_LIB_WIDEN);
1535 #endif
1536
1537   /* Push a new argument block and copy the arguments.  Do not allow
1538      the (potential) memcpy call below to interfere with our stack
1539      manipulations.  */
1540   do_pending_stack_adjust ();
1541   NO_DEFER_POP;
1542
1543   /* Save the stack with nonlocal if available.  */
1544 #ifdef HAVE_save_stack_nonlocal
1545   if (HAVE_save_stack_nonlocal)
1546     emit_stack_save (SAVE_NONLOCAL, &old_stack_level);
1547   else
1548 #endif
1549     emit_stack_save (SAVE_BLOCK, &old_stack_level);
1550
1551   /* Allocate a block of memory onto the stack and copy the memory
1552      arguments to the outgoing arguments address.  We can pass TRUE
1553      as the 4th argument because we just saved the stack pointer
1554      and will restore it right after the call.  */
1555   allocate_dynamic_stack_space (argsize, 0, BIGGEST_ALIGNMENT, true);
1556
1557   /* Set DRAP flag to true, even though allocate_dynamic_stack_space
1558      may have already set current_function_calls_alloca to true.
1559      current_function_calls_alloca won't be set if argsize is zero,
1560      so we have to guarantee need_drap is true here.  */
1561   if (SUPPORTS_STACK_ALIGNMENT)
1562     crtl->need_drap = true;
1563
1564   dest = virtual_outgoing_args_rtx;
1565 #ifndef STACK_GROWS_DOWNWARD
1566   if (CONST_INT_P (argsize))
1567     dest = plus_constant (Pmode, dest, -INTVAL (argsize));
1568   else
1569     dest = gen_rtx_PLUS (Pmode, dest, negate_rtx (Pmode, argsize));
1570 #endif
1571   dest = gen_rtx_MEM (BLKmode, dest);
1572   set_mem_align (dest, PARM_BOUNDARY);
1573   src = gen_rtx_MEM (BLKmode, incoming_args);
1574   set_mem_align (src, PARM_BOUNDARY);
1575   emit_block_move (dest, src, argsize, BLOCK_OP_NORMAL);
1576
1577   /* Refer to the argument block.  */
1578   apply_args_size ();
1579   arguments = gen_rtx_MEM (BLKmode, arguments);
1580   set_mem_align (arguments, PARM_BOUNDARY);
1581
1582   /* Walk past the arg-pointer and structure value address.  */
1583   size = GET_MODE_SIZE (Pmode);
1584   if (struct_value)
1585     size += GET_MODE_SIZE (Pmode);
1586
1587   /* Restore each of the registers previously saved.  Make USE insns
1588      for each of these registers for use in making the call.  */
1589   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1590     if ((mode = apply_args_mode[regno]) != VOIDmode)
1591       {
1592         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1593         if (size % align != 0)
1594           size = CEIL (size, align) * align;
1595         reg = gen_rtx_REG (mode, regno);
1596         emit_move_insn (reg, adjust_address (arguments, mode, size));
1597         use_reg (&call_fusage, reg);
1598         size += GET_MODE_SIZE (mode);
1599       }
1600
1601   /* Restore the structure value address unless this is passed as an
1602      "invisible" first argument.  */
1603   size = GET_MODE_SIZE (Pmode);
1604   if (struct_value)
1605     {
1606       rtx value = gen_reg_rtx (Pmode);
1607       emit_move_insn (value, adjust_address (arguments, Pmode, size));
1608       emit_move_insn (struct_value, value);
1609       if (REG_P (struct_value))
1610         use_reg (&call_fusage, struct_value);
1611       size += GET_MODE_SIZE (Pmode);
1612     }
1613
1614   /* All arguments and registers used for the call are set up by now!  */
1615   function = prepare_call_address (NULL, function, NULL, &call_fusage, 0, 0);
1616
1617   /* Ensure address is valid.  SYMBOL_REF is already valid, so no need,
1618      and we don't want to load it into a register as an optimization,
1619      because prepare_call_address already did it if it should be done.  */
1620   if (GET_CODE (function) != SYMBOL_REF)
1621     function = memory_address (FUNCTION_MODE, function);
1622
1623   /* Generate the actual call instruction and save the return value.  */
1624 #ifdef HAVE_untyped_call
1625   if (HAVE_untyped_call)
1626     emit_call_insn (gen_untyped_call (gen_rtx_MEM (FUNCTION_MODE, function),
1627                                       result, result_vector (1, result)));
1628   else
1629 #endif
1630 #ifdef HAVE_call_value
1631   if (HAVE_call_value)
1632     {
1633       rtx valreg = 0;
1634
1635       /* Locate the unique return register.  It is not possible to
1636          express a call that sets more than one return register using
1637          call_value; use untyped_call for that.  In fact, untyped_call
1638          only needs to save the return registers in the given block.  */
1639       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1640         if ((mode = apply_result_mode[regno]) != VOIDmode)
1641           {
1642             gcc_assert (!valreg); /* HAVE_untyped_call required.  */
1643
1644             valreg = gen_rtx_REG (mode, regno);
1645           }
1646
1647       emit_call_insn (GEN_CALL_VALUE (valreg,
1648                                       gen_rtx_MEM (FUNCTION_MODE, function),
1649                                       const0_rtx, NULL_RTX, const0_rtx));
1650
1651       emit_move_insn (adjust_address (result, GET_MODE (valreg), 0), valreg);
1652     }
1653   else
1654 #endif
1655     gcc_unreachable ();
1656
1657   /* Find the CALL insn we just emitted, and attach the register usage
1658      information.  */
1659   call_insn = last_call_insn ();
1660   add_function_usage_to (call_insn, call_fusage);
1661
1662   /* Restore the stack.  */
1663 #ifdef HAVE_save_stack_nonlocal
1664   if (HAVE_save_stack_nonlocal)
1665     emit_stack_restore (SAVE_NONLOCAL, old_stack_level);
1666   else
1667 #endif
1668     emit_stack_restore (SAVE_BLOCK, old_stack_level);
1669   fixup_args_size_notes (call_insn, get_last_insn(), 0);
1670
1671   OK_DEFER_POP;
1672
1673   /* Return the address of the result block.  */
1674   result = copy_addr_to_reg (XEXP (result, 0));
1675   return convert_memory_address (ptr_mode, result);
1676 }
1677
1678 /* Perform an untyped return.  */
1679
1680 static void
1681 expand_builtin_return (rtx result)
1682 {
1683   int size, align, regno;
1684   enum machine_mode mode;
1685   rtx reg;
1686   rtx call_fusage = 0;
1687
1688   result = convert_memory_address (Pmode, result);
1689
1690   apply_result_size ();
1691   result = gen_rtx_MEM (BLKmode, result);
1692
1693 #ifdef HAVE_untyped_return
1694   if (HAVE_untyped_return)
1695     {
1696       emit_jump_insn (gen_untyped_return (result, result_vector (0, result)));
1697       emit_barrier ();
1698       return;
1699     }
1700 #endif
1701
1702   /* Restore the return value and note that each value is used.  */
1703   size = 0;
1704   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1705     if ((mode = apply_result_mode[regno]) != VOIDmode)
1706       {
1707         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1708         if (size % align != 0)
1709           size = CEIL (size, align) * align;
1710         reg = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1711         emit_move_insn (reg, adjust_address (result, mode, size));
1712
1713         push_to_sequence (call_fusage);
1714         emit_use (reg);
1715         call_fusage = get_insns ();
1716         end_sequence ();
1717         size += GET_MODE_SIZE (mode);
1718       }
1719
1720   /* Put the USE insns before the return.  */
1721   emit_insn (call_fusage);
1722
1723   /* Return whatever values was restored by jumping directly to the end
1724      of the function.  */
1725   expand_naked_return ();
1726 }
1727
1728 /* Used by expand_builtin_classify_type and fold_builtin_classify_type.  */
1729
1730 static enum type_class
1731 type_to_class (tree type)
1732 {
1733   switch (TREE_CODE (type))
1734     {
1735     case VOID_TYPE:        return void_type_class;
1736     case INTEGER_TYPE:     return integer_type_class;
1737     case ENUMERAL_TYPE:    return enumeral_type_class;
1738     case BOOLEAN_TYPE:     return boolean_type_class;
1739     case POINTER_TYPE:     return pointer_type_class;
1740     case REFERENCE_TYPE:   return reference_type_class;
1741     case OFFSET_TYPE:      return offset_type_class;
1742     case REAL_TYPE:        return real_type_class;
1743     case COMPLEX_TYPE:     return complex_type_class;
1744     case FUNCTION_TYPE:    return function_type_class;
1745     case METHOD_TYPE:      return method_type_class;
1746     case RECORD_TYPE:      return record_type_class;
1747     case UNION_TYPE:
1748     case QUAL_UNION_TYPE:  return union_type_class;
1749     case ARRAY_TYPE:       return (TYPE_STRING_FLAG (type)
1750                                    ? string_type_class : array_type_class);
1751     case LANG_TYPE:        return lang_type_class;
1752     default:               return no_type_class;
1753     }
1754 }
1755
1756 /* Expand a call EXP to __builtin_classify_type.  */
1757
1758 static rtx
1759 expand_builtin_classify_type (tree exp)
1760 {
1761   if (call_expr_nargs (exp))
1762     return GEN_INT (type_to_class (TREE_TYPE (CALL_EXPR_ARG (exp, 0))));
1763   return GEN_INT (no_type_class);
1764 }
1765
1766 /* This helper macro, meant to be used in mathfn_built_in below,
1767    determines which among a set of three builtin math functions is
1768    appropriate for a given type mode.  The `F' and `L' cases are
1769    automatically generated from the `double' case.  */
1770 #define CASE_MATHFN(BUILT_IN_MATHFN) \
1771   case BUILT_IN_MATHFN: case BUILT_IN_MATHFN##F: case BUILT_IN_MATHFN##L: \
1772   fcode = BUILT_IN_MATHFN; fcodef = BUILT_IN_MATHFN##F ; \
1773   fcodel = BUILT_IN_MATHFN##L ; break;
1774 /* Similar to above, but appends _R after any F/L suffix.  */
1775 #define CASE_MATHFN_REENT(BUILT_IN_MATHFN) \
1776   case BUILT_IN_MATHFN##_R: case BUILT_IN_MATHFN##F_R: case BUILT_IN_MATHFN##L_R: \
1777   fcode = BUILT_IN_MATHFN##_R; fcodef = BUILT_IN_MATHFN##F_R ; \
1778   fcodel = BUILT_IN_MATHFN##L_R ; break;
1779
1780 /* Return mathematic function equivalent to FN but operating directly on TYPE,
1781    if available.  If IMPLICIT is true use the implicit builtin declaration,
1782    otherwise use the explicit declaration.  If we can't do the conversion,
1783    return zero.  */
1784
1785 static tree
1786 mathfn_built_in_1 (tree type, enum built_in_function fn, bool implicit_p)
1787 {
1788   enum built_in_function fcode, fcodef, fcodel, fcode2;
1789
1790   switch (fn)
1791     {
1792       CASE_MATHFN (BUILT_IN_ACOS)
1793       CASE_MATHFN (BUILT_IN_ACOSH)
1794       CASE_MATHFN (BUILT_IN_ASIN)
1795       CASE_MATHFN (BUILT_IN_ASINH)
1796       CASE_MATHFN (BUILT_IN_ATAN)
1797       CASE_MATHFN (BUILT_IN_ATAN2)
1798       CASE_MATHFN (BUILT_IN_ATANH)
1799       CASE_MATHFN (BUILT_IN_CBRT)
1800       CASE_MATHFN (BUILT_IN_CEIL)
1801       CASE_MATHFN (BUILT_IN_CEXPI)
1802       CASE_MATHFN (BUILT_IN_COPYSIGN)
1803       CASE_MATHFN (BUILT_IN_COS)
1804       CASE_MATHFN (BUILT_IN_COSH)
1805       CASE_MATHFN (BUILT_IN_DREM)
1806       CASE_MATHFN (BUILT_IN_ERF)
1807       CASE_MATHFN (BUILT_IN_ERFC)
1808       CASE_MATHFN (BUILT_IN_EXP)
1809       CASE_MATHFN (BUILT_IN_EXP10)
1810       CASE_MATHFN (BUILT_IN_EXP2)
1811       CASE_MATHFN (BUILT_IN_EXPM1)
1812       CASE_MATHFN (BUILT_IN_FABS)
1813       CASE_MATHFN (BUILT_IN_FDIM)
1814       CASE_MATHFN (BUILT_IN_FLOOR)
1815       CASE_MATHFN (BUILT_IN_FMA)
1816       CASE_MATHFN (BUILT_IN_FMAX)
1817       CASE_MATHFN (BUILT_IN_FMIN)
1818       CASE_MATHFN (BUILT_IN_FMOD)
1819       CASE_MATHFN (BUILT_IN_FREXP)
1820       CASE_MATHFN (BUILT_IN_GAMMA)
1821       CASE_MATHFN_REENT (BUILT_IN_GAMMA) /* GAMMA_R */
1822       CASE_MATHFN (BUILT_IN_HUGE_VAL)
1823       CASE_MATHFN (BUILT_IN_HYPOT)
1824       CASE_MATHFN (BUILT_IN_ILOGB)
1825       CASE_MATHFN (BUILT_IN_ICEIL)
1826       CASE_MATHFN (BUILT_IN_IFLOOR)
1827       CASE_MATHFN (BUILT_IN_INF)
1828       CASE_MATHFN (BUILT_IN_IRINT)
1829       CASE_MATHFN (BUILT_IN_IROUND)
1830       CASE_MATHFN (BUILT_IN_ISINF)
1831       CASE_MATHFN (BUILT_IN_J0)
1832       CASE_MATHFN (BUILT_IN_J1)
1833       CASE_MATHFN (BUILT_IN_JN)
1834       CASE_MATHFN (BUILT_IN_LCEIL)
1835       CASE_MATHFN (BUILT_IN_LDEXP)
1836       CASE_MATHFN (BUILT_IN_LFLOOR)
1837       CASE_MATHFN (BUILT_IN_LGAMMA)
1838       CASE_MATHFN_REENT (BUILT_IN_LGAMMA) /* LGAMMA_R */
1839       CASE_MATHFN (BUILT_IN_LLCEIL)
1840       CASE_MATHFN (BUILT_IN_LLFLOOR)
1841       CASE_MATHFN (BUILT_IN_LLRINT)
1842       CASE_MATHFN (BUILT_IN_LLROUND)
1843       CASE_MATHFN (BUILT_IN_LOG)
1844       CASE_MATHFN (BUILT_IN_LOG10)
1845       CASE_MATHFN (BUILT_IN_LOG1P)
1846       CASE_MATHFN (BUILT_IN_LOG2)
1847       CASE_MATHFN (BUILT_IN_LOGB)
1848       CASE_MATHFN (BUILT_IN_LRINT)
1849       CASE_MATHFN (BUILT_IN_LROUND)
1850       CASE_MATHFN (BUILT_IN_MODF)
1851       CASE_MATHFN (BUILT_IN_NAN)
1852       CASE_MATHFN (BUILT_IN_NANS)
1853       CASE_MATHFN (BUILT_IN_NEARBYINT)
1854       CASE_MATHFN (BUILT_IN_NEXTAFTER)
1855       CASE_MATHFN (BUILT_IN_NEXTTOWARD)
1856       CASE_MATHFN (BUILT_IN_POW)
1857       CASE_MATHFN (BUILT_IN_POWI)
1858       CASE_MATHFN (BUILT_IN_POW10)
1859       CASE_MATHFN (BUILT_IN_REMAINDER)
1860       CASE_MATHFN (BUILT_IN_REMQUO)
1861       CASE_MATHFN (BUILT_IN_RINT)
1862       CASE_MATHFN (BUILT_IN_ROUND)
1863       CASE_MATHFN (BUILT_IN_SCALB)
1864       CASE_MATHFN (BUILT_IN_SCALBLN)
1865       CASE_MATHFN (BUILT_IN_SCALBN)
1866       CASE_MATHFN (BUILT_IN_SIGNBIT)
1867       CASE_MATHFN (BUILT_IN_SIGNIFICAND)
1868       CASE_MATHFN (BUILT_IN_SIN)
1869       CASE_MATHFN (BUILT_IN_SINCOS)
1870       CASE_MATHFN (BUILT_IN_SINH)
1871       CASE_MATHFN (BUILT_IN_SQRT)
1872       CASE_MATHFN (BUILT_IN_TAN)
1873       CASE_MATHFN (BUILT_IN_TANH)
1874       CASE_MATHFN (BUILT_IN_TGAMMA)
1875       CASE_MATHFN (BUILT_IN_TRUNC)
1876       CASE_MATHFN (BUILT_IN_Y0)
1877       CASE_MATHFN (BUILT_IN_Y1)
1878       CASE_MATHFN (BUILT_IN_YN)
1879
1880       default:
1881         return NULL_TREE;
1882       }
1883
1884   if (TYPE_MAIN_VARIANT (type) == double_type_node)
1885     fcode2 = fcode;
1886   else if (TYPE_MAIN_VARIANT (type) == float_type_node)
1887     fcode2 = fcodef;
1888   else if (TYPE_MAIN_VARIANT (type) == long_double_type_node)
1889     fcode2 = fcodel;
1890   else
1891     return NULL_TREE;
1892
1893   if (implicit_p && !builtin_decl_implicit_p (fcode2))
1894     return NULL_TREE;
1895
1896   return builtin_decl_explicit (fcode2);
1897 }
1898
1899 /* Like mathfn_built_in_1(), but always use the implicit array.  */
1900
1901 tree
1902 mathfn_built_in (tree type, enum built_in_function fn)
1903 {
1904   return mathfn_built_in_1 (type, fn, /*implicit=*/ 1);
1905 }
1906
1907 /* If errno must be maintained, expand the RTL to check if the result,
1908    TARGET, of a built-in function call, EXP, is NaN, and if so set
1909    errno to EDOM.  */
1910
1911 static void
1912 expand_errno_check (tree exp, rtx target)
1913 {
1914   rtx lab = gen_label_rtx ();
1915
1916   /* Test the result; if it is NaN, set errno=EDOM because
1917      the argument was not in the domain.  */
1918   do_compare_rtx_and_jump (target, target, EQ, 0, GET_MODE (target),
1919                            NULL_RTX, NULL_RTX, lab,
1920                            /* The jump is very likely.  */
1921                            REG_BR_PROB_BASE - (REG_BR_PROB_BASE / 2000 - 1));
1922
1923 #ifdef TARGET_EDOM
1924   /* If this built-in doesn't throw an exception, set errno directly.  */
1925   if (TREE_NOTHROW (TREE_OPERAND (CALL_EXPR_FN (exp), 0)))
1926     {
1927 #ifdef GEN_ERRNO_RTX
1928       rtx errno_rtx = GEN_ERRNO_RTX;
1929 #else
1930       rtx errno_rtx
1931           = gen_rtx_MEM (word_mode, gen_rtx_SYMBOL_REF (Pmode, "errno"));
1932 #endif
1933       emit_move_insn (errno_rtx, GEN_INT (TARGET_EDOM));
1934       emit_label (lab);
1935       return;
1936     }
1937 #endif
1938
1939   /* Make sure the library call isn't expanded as a tail call.  */
1940   CALL_EXPR_TAILCALL (exp) = 0;
1941
1942   /* We can't set errno=EDOM directly; let the library call do it.
1943      Pop the arguments right away in case the call gets deleted.  */
1944   NO_DEFER_POP;
1945   expand_call (exp, target, 0);
1946   OK_DEFER_POP;
1947   emit_label (lab);
1948 }
1949
1950 /* Expand a call to one of the builtin math functions (sqrt, exp, or log).
1951    Return NULL_RTX if a normal call should be emitted rather than expanding
1952    the function in-line.  EXP is the expression that is a call to the builtin
1953    function; if convenient, the result should be placed in TARGET.
1954    SUBTARGET may be used as the target for computing one of EXP's operands.  */
1955
1956 static rtx
1957 expand_builtin_mathfn (tree exp, rtx target, rtx subtarget)
1958 {
1959   optab builtin_optab;
1960   rtx op0, insns;
1961   tree fndecl = get_callee_fndecl (exp);
1962   enum machine_mode mode;
1963   bool errno_set = false;
1964   bool try_widening = false;
1965   tree arg;
1966
1967   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
1968     return NULL_RTX;
1969
1970   arg = CALL_EXPR_ARG (exp, 0);
1971
1972   switch (DECL_FUNCTION_CODE (fndecl))
1973     {
1974     CASE_FLT_FN (BUILT_IN_SQRT):
1975       errno_set = ! tree_expr_nonnegative_p (arg);
1976       try_widening = true;
1977       builtin_optab = sqrt_optab;
1978       break;
1979     CASE_FLT_FN (BUILT_IN_EXP):
1980       errno_set = true; builtin_optab = exp_optab; break;
1981     CASE_FLT_FN (BUILT_IN_EXP10):
1982     CASE_FLT_FN (BUILT_IN_POW10):
1983       errno_set = true; builtin_optab = exp10_optab; break;
1984     CASE_FLT_FN (BUILT_IN_EXP2):
1985       errno_set = true; builtin_optab = exp2_optab; break;
1986     CASE_FLT_FN (BUILT_IN_EXPM1):
1987       errno_set = true; builtin_optab = expm1_optab; break;
1988     CASE_FLT_FN (BUILT_IN_LOGB):
1989       errno_set = true; builtin_optab = logb_optab; break;
1990     CASE_FLT_FN (BUILT_IN_LOG):
1991       errno_set = true; builtin_optab = log_optab; break;
1992     CASE_FLT_FN (BUILT_IN_LOG10):
1993       errno_set = true; builtin_optab = log10_optab; break;
1994     CASE_FLT_FN (BUILT_IN_LOG2):
1995       errno_set = true; builtin_optab = log2_optab; break;
1996     CASE_FLT_FN (BUILT_IN_LOG1P):
1997       errno_set = true; builtin_optab = log1p_optab; break;
1998     CASE_FLT_FN (BUILT_IN_ASIN):
1999       builtin_optab = asin_optab; break;
2000     CASE_FLT_FN (BUILT_IN_ACOS):
2001       builtin_optab = acos_optab; break;
2002     CASE_FLT_FN (BUILT_IN_TAN):
2003       builtin_optab = tan_optab; break;
2004     CASE_FLT_FN (BUILT_IN_ATAN):
2005       builtin_optab = atan_optab; break;
2006     CASE_FLT_FN (BUILT_IN_FLOOR):
2007       builtin_optab = floor_optab; break;
2008     CASE_FLT_FN (BUILT_IN_CEIL):
2009       builtin_optab = ceil_optab; break;
2010     CASE_FLT_FN (BUILT_IN_TRUNC):
2011       builtin_optab = btrunc_optab; break;
2012     CASE_FLT_FN (BUILT_IN_ROUND):
2013       builtin_optab = round_optab; break;
2014     CASE_FLT_FN (BUILT_IN_NEARBYINT):
2015       builtin_optab = nearbyint_optab;
2016       if (flag_trapping_math)
2017         break;
2018       /* Else fallthrough and expand as rint.  */
2019     CASE_FLT_FN (BUILT_IN_RINT):
2020       builtin_optab = rint_optab; break;
2021     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
2022       builtin_optab = significand_optab; break;
2023     default:
2024       gcc_unreachable ();
2025     }
2026
2027   /* Make a suitable register to place result in.  */
2028   mode = TYPE_MODE (TREE_TYPE (exp));
2029
2030   if (! flag_errno_math || ! HONOR_NANS (mode))
2031     errno_set = false;
2032
2033   /* Before working hard, check whether the instruction is available, but try
2034      to widen the mode for specific operations.  */
2035   if ((optab_handler (builtin_optab, mode) != CODE_FOR_nothing
2036        || (try_widening && !excess_precision_type (TREE_TYPE (exp))))
2037       && (!errno_set || !optimize_insn_for_size_p ()))
2038     {
2039       rtx result = gen_reg_rtx (mode);
2040
2041       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2042          need to expand the argument again.  This way, we will not perform
2043          side-effects more the once.  */
2044       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2045
2046       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2047
2048       start_sequence ();
2049
2050       /* Compute into RESULT.
2051          Set RESULT to wherever the result comes back.  */
2052       result = expand_unop (mode, builtin_optab, op0, result, 0);
2053
2054       if (result != 0)
2055         {
2056           if (errno_set)
2057             expand_errno_check (exp, result);
2058
2059           /* Output the entire sequence.  */
2060           insns = get_insns ();
2061           end_sequence ();
2062           emit_insn (insns);
2063           return result;
2064         }
2065
2066       /* If we were unable to expand via the builtin, stop the sequence
2067          (without outputting the insns) and call to the library function
2068          with the stabilized argument list.  */
2069       end_sequence ();
2070     }
2071
2072   return expand_call (exp, target, target == const0_rtx);
2073 }
2074
2075 /* Expand a call to the builtin binary math functions (pow and atan2).
2076    Return NULL_RTX if a normal call should be emitted rather than expanding the
2077    function in-line.  EXP is the expression that is a call to the builtin
2078    function; if convenient, the result should be placed in TARGET.
2079    SUBTARGET may be used as the target for computing one of EXP's
2080    operands.  */
2081
2082 static rtx
2083 expand_builtin_mathfn_2 (tree exp, rtx target, rtx subtarget)
2084 {
2085   optab builtin_optab;
2086   rtx op0, op1, insns, result;
2087   int op1_type = REAL_TYPE;
2088   tree fndecl = get_callee_fndecl (exp);
2089   tree arg0, arg1;
2090   enum machine_mode mode;
2091   bool errno_set = true;
2092
2093   switch (DECL_FUNCTION_CODE (fndecl))
2094     {
2095     CASE_FLT_FN (BUILT_IN_SCALBN):
2096     CASE_FLT_FN (BUILT_IN_SCALBLN):
2097     CASE_FLT_FN (BUILT_IN_LDEXP):
2098       op1_type = INTEGER_TYPE;
2099     default:
2100       break;
2101     }
2102
2103   if (!validate_arglist (exp, REAL_TYPE, op1_type, VOID_TYPE))
2104     return NULL_RTX;
2105
2106   arg0 = CALL_EXPR_ARG (exp, 0);
2107   arg1 = CALL_EXPR_ARG (exp, 1);
2108
2109   switch (DECL_FUNCTION_CODE (fndecl))
2110     {
2111     CASE_FLT_FN (BUILT_IN_POW):
2112       builtin_optab = pow_optab; break;
2113     CASE_FLT_FN (BUILT_IN_ATAN2):
2114       builtin_optab = atan2_optab; break;
2115     CASE_FLT_FN (BUILT_IN_SCALB):
2116       if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (exp)))->b != 2)
2117         return 0;
2118       builtin_optab = scalb_optab; break;
2119     CASE_FLT_FN (BUILT_IN_SCALBN):
2120     CASE_FLT_FN (BUILT_IN_SCALBLN):
2121       if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (exp)))->b != 2)
2122         return 0;
2123     /* Fall through... */
2124     CASE_FLT_FN (BUILT_IN_LDEXP):
2125       builtin_optab = ldexp_optab; break;
2126     CASE_FLT_FN (BUILT_IN_FMOD):
2127       builtin_optab = fmod_optab; break;
2128     CASE_FLT_FN (BUILT_IN_REMAINDER):
2129     CASE_FLT_FN (BUILT_IN_DREM):
2130       builtin_optab = remainder_optab; break;
2131     default:
2132       gcc_unreachable ();
2133     }
2134
2135   /* Make a suitable register to place result in.  */
2136   mode = TYPE_MODE (TREE_TYPE (exp));
2137
2138   /* Before working hard, check whether the instruction is available.  */
2139   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2140     return NULL_RTX;
2141
2142   result = gen_reg_rtx (mode);
2143
2144   if (! flag_errno_math || ! HONOR_NANS (mode))
2145     errno_set = false;
2146
2147   if (errno_set && optimize_insn_for_size_p ())
2148     return 0;
2149
2150   /* Always stabilize the argument list.  */
2151   CALL_EXPR_ARG (exp, 0) = arg0 = builtin_save_expr (arg0);
2152   CALL_EXPR_ARG (exp, 1) = arg1 = builtin_save_expr (arg1);
2153
2154   op0 = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
2155   op1 = expand_normal (arg1);
2156
2157   start_sequence ();
2158
2159   /* Compute into RESULT.
2160      Set RESULT to wherever the result comes back.  */
2161   result = expand_binop (mode, builtin_optab, op0, op1,
2162                          result, 0, OPTAB_DIRECT);
2163
2164   /* If we were unable to expand via the builtin, stop the sequence
2165      (without outputting the insns) and call to the library function
2166      with the stabilized argument list.  */
2167   if (result == 0)
2168     {
2169       end_sequence ();
2170       return expand_call (exp, target, target == const0_rtx);
2171     }
2172
2173   if (errno_set)
2174     expand_errno_check (exp, result);
2175
2176   /* Output the entire sequence.  */
2177   insns = get_insns ();
2178   end_sequence ();
2179   emit_insn (insns);
2180
2181   return result;
2182 }
2183
2184 /* Expand a call to the builtin trinary math functions (fma).
2185    Return NULL_RTX if a normal call should be emitted rather than expanding the
2186    function in-line.  EXP is the expression that is a call to the builtin
2187    function; if convenient, the result should be placed in TARGET.
2188    SUBTARGET may be used as the target for computing one of EXP's
2189    operands.  */
2190
2191 static rtx
2192 expand_builtin_mathfn_ternary (tree exp, rtx target, rtx subtarget)
2193 {
2194   optab builtin_optab;
2195   rtx op0, op1, op2, insns, result;
2196   tree fndecl = get_callee_fndecl (exp);
2197   tree arg0, arg1, arg2;
2198   enum machine_mode mode;
2199
2200   if (!validate_arglist (exp, REAL_TYPE, REAL_TYPE, REAL_TYPE, VOID_TYPE))
2201     return NULL_RTX;
2202
2203   arg0 = CALL_EXPR_ARG (exp, 0);
2204   arg1 = CALL_EXPR_ARG (exp, 1);
2205   arg2 = CALL_EXPR_ARG (exp, 2);
2206
2207   switch (DECL_FUNCTION_CODE (fndecl))
2208     {
2209     CASE_FLT_FN (BUILT_IN_FMA):
2210       builtin_optab = fma_optab; break;
2211     default:
2212       gcc_unreachable ();
2213     }
2214
2215   /* Make a suitable register to place result in.  */
2216   mode = TYPE_MODE (TREE_TYPE (exp));
2217
2218   /* Before working hard, check whether the instruction is available.  */
2219   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2220     return NULL_RTX;
2221
2222   result = gen_reg_rtx (mode);
2223
2224   /* Always stabilize the argument list.  */
2225   CALL_EXPR_ARG (exp, 0) = arg0 = builtin_save_expr (arg0);
2226   CALL_EXPR_ARG (exp, 1) = arg1 = builtin_save_expr (arg1);
2227   CALL_EXPR_ARG (exp, 2) = arg2 = builtin_save_expr (arg2);
2228
2229   op0 = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
2230   op1 = expand_normal (arg1);
2231   op2 = expand_normal (arg2);
2232
2233   start_sequence ();
2234
2235   /* Compute into RESULT.
2236      Set RESULT to wherever the result comes back.  */
2237   result = expand_ternary_op (mode, builtin_optab, op0, op1, op2,
2238                               result, 0);
2239
2240   /* If we were unable to expand via the builtin, stop the sequence
2241      (without outputting the insns) and call to the library function
2242      with the stabilized argument list.  */
2243   if (result == 0)
2244     {
2245       end_sequence ();
2246       return expand_call (exp, target, target == const0_rtx);
2247     }
2248
2249   /* Output the entire sequence.  */
2250   insns = get_insns ();
2251   end_sequence ();
2252   emit_insn (insns);
2253
2254   return result;
2255 }
2256
2257 /* Expand a call to the builtin sin and cos math functions.
2258    Return NULL_RTX if a normal call should be emitted rather than expanding the
2259    function in-line.  EXP is the expression that is a call to the builtin
2260    function; if convenient, the result should be placed in TARGET.
2261    SUBTARGET may be used as the target for computing one of EXP's
2262    operands.  */
2263
2264 static rtx
2265 expand_builtin_mathfn_3 (tree exp, rtx target, rtx subtarget)
2266 {
2267   optab builtin_optab;
2268   rtx op0, insns;
2269   tree fndecl = get_callee_fndecl (exp);
2270   enum machine_mode mode;
2271   tree arg;
2272
2273   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2274     return NULL_RTX;
2275
2276   arg = CALL_EXPR_ARG (exp, 0);
2277
2278   switch (DECL_FUNCTION_CODE (fndecl))
2279     {
2280     CASE_FLT_FN (BUILT_IN_SIN):
2281     CASE_FLT_FN (BUILT_IN_COS):
2282       builtin_optab = sincos_optab; break;
2283     default:
2284       gcc_unreachable ();
2285     }
2286
2287   /* Make a suitable register to place result in.  */
2288   mode = TYPE_MODE (TREE_TYPE (exp));
2289
2290   /* Check if sincos insn is available, otherwise fallback
2291      to sin or cos insn.  */
2292   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2293     switch (DECL_FUNCTION_CODE (fndecl))
2294       {
2295       CASE_FLT_FN (BUILT_IN_SIN):
2296         builtin_optab = sin_optab; break;
2297       CASE_FLT_FN (BUILT_IN_COS):
2298         builtin_optab = cos_optab; break;
2299       default:
2300         gcc_unreachable ();
2301       }
2302
2303   /* Before working hard, check whether the instruction is available.  */
2304   if (optab_handler (builtin_optab, mode) != CODE_FOR_nothing)
2305     {
2306       rtx result = gen_reg_rtx (mode);
2307
2308       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2309          need to expand the argument again.  This way, we will not perform
2310          side-effects more the once.  */
2311       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2312
2313       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2314
2315       start_sequence ();
2316
2317       /* Compute into RESULT.
2318          Set RESULT to wherever the result comes back.  */
2319       if (builtin_optab == sincos_optab)
2320         {
2321           int ok;
2322
2323           switch (DECL_FUNCTION_CODE (fndecl))
2324             {
2325             CASE_FLT_FN (BUILT_IN_SIN):
2326               ok = expand_twoval_unop (builtin_optab, op0, 0, result, 0);
2327               break;
2328             CASE_FLT_FN (BUILT_IN_COS):
2329               ok = expand_twoval_unop (builtin_optab, op0, result, 0, 0);
2330               break;
2331             default:
2332               gcc_unreachable ();
2333             }
2334           gcc_assert (ok);
2335         }
2336       else
2337         result = expand_unop (mode, builtin_optab, op0, result, 0);
2338
2339       if (result != 0)
2340         {
2341           /* Output the entire sequence.  */
2342           insns = get_insns ();
2343           end_sequence ();
2344           emit_insn (insns);
2345           return result;
2346         }
2347
2348       /* If we were unable to expand via the builtin, stop the sequence
2349          (without outputting the insns) and call to the library function
2350          with the stabilized argument list.  */
2351       end_sequence ();
2352     }
2353
2354   return expand_call (exp, target, target == const0_rtx);
2355 }
2356
2357 /* Given an interclass math builtin decl FNDECL and it's argument ARG
2358    return an RTL instruction code that implements the functionality.
2359    If that isn't possible or available return CODE_FOR_nothing.  */
2360
2361 static enum insn_code
2362 interclass_mathfn_icode (tree arg, tree fndecl)
2363 {
2364   bool errno_set = false;
2365   optab builtin_optab = unknown_optab;
2366   enum machine_mode mode;
2367
2368   switch (DECL_FUNCTION_CODE (fndecl))
2369     {
2370     CASE_FLT_FN (BUILT_IN_ILOGB):
2371       errno_set = true; builtin_optab = ilogb_optab; break;
2372     CASE_FLT_FN (BUILT_IN_ISINF):
2373       builtin_optab = isinf_optab; break;
2374     case BUILT_IN_ISNORMAL:
2375     case BUILT_IN_ISFINITE:
2376     CASE_FLT_FN (BUILT_IN_FINITE):
2377     case BUILT_IN_FINITED32:
2378     case BUILT_IN_FINITED64:
2379     case BUILT_IN_FINITED128:
2380     case BUILT_IN_ISINFD32:
2381     case BUILT_IN_ISINFD64:
2382     case BUILT_IN_ISINFD128:
2383       /* These builtins have no optabs (yet).  */
2384       break;
2385     default:
2386       gcc_unreachable ();
2387     }
2388
2389   /* There's no easy way to detect the case we need to set EDOM.  */
2390   if (flag_errno_math && errno_set)
2391     return CODE_FOR_nothing;
2392
2393   /* Optab mode depends on the mode of the input argument.  */
2394   mode = TYPE_MODE (TREE_TYPE (arg));
2395
2396   if (builtin_optab)
2397     return optab_handler (builtin_optab, mode);
2398   return CODE_FOR_nothing;
2399 }
2400
2401 /* Expand a call to one of the builtin math functions that operate on
2402    floating point argument and output an integer result (ilogb, isinf,
2403    isnan, etc).
2404    Return 0 if a normal call should be emitted rather than expanding the
2405    function in-line.  EXP is the expression that is a call to the builtin
2406    function; if convenient, the result should be placed in TARGET.  */
2407
2408 static rtx
2409 expand_builtin_interclass_mathfn (tree exp, rtx target)
2410 {
2411   enum insn_code icode = CODE_FOR_nothing;
2412   rtx op0;
2413   tree fndecl = get_callee_fndecl (exp);
2414   enum machine_mode mode;
2415   tree arg;
2416
2417   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2418     return NULL_RTX;
2419
2420   arg = CALL_EXPR_ARG (exp, 0);
2421   icode = interclass_mathfn_icode (arg, fndecl);
2422   mode = TYPE_MODE (TREE_TYPE (arg));
2423
2424   if (icode != CODE_FOR_nothing)
2425     {
2426       struct expand_operand ops[1];
2427       rtx last = get_last_insn ();
2428       tree orig_arg = arg;
2429
2430       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2431          need to expand the argument again.  This way, we will not perform
2432          side-effects more the once.  */
2433       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2434
2435       op0 = expand_expr (arg, NULL_RTX, VOIDmode, EXPAND_NORMAL);
2436
2437       if (mode != GET_MODE (op0))
2438         op0 = convert_to_mode (mode, op0, 0);
2439
2440       create_output_operand (&ops[0], target, TYPE_MODE (TREE_TYPE (exp)));
2441       if (maybe_legitimize_operands (icode, 0, 1, ops)
2442           && maybe_emit_unop_insn (icode, ops[0].value, op0, UNKNOWN))
2443         return ops[0].value;
2444
2445       delete_insns_since (last);
2446       CALL_EXPR_ARG (exp, 0) = orig_arg;
2447     }
2448
2449   return NULL_RTX;
2450 }
2451
2452 /* Expand a call to the builtin sincos math function.
2453    Return NULL_RTX if a normal call should be emitted rather than expanding the
2454    function in-line.  EXP is the expression that is a call to the builtin
2455    function.  */
2456
2457 static rtx
2458 expand_builtin_sincos (tree exp)
2459 {
2460   rtx op0, op1, op2, target1, target2;
2461   enum machine_mode mode;
2462   tree arg, sinp, cosp;
2463   int result;
2464   location_t loc = EXPR_LOCATION (exp);
2465   tree alias_type, alias_off;
2466
2467   if (!validate_arglist (exp, REAL_TYPE,
2468                          POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
2469     return NULL_RTX;
2470
2471   arg = CALL_EXPR_ARG (exp, 0);
2472   sinp = CALL_EXPR_ARG (exp, 1);
2473   cosp = CALL_EXPR_ARG (exp, 2);
2474
2475   /* Make a suitable register to place result in.  */
2476   mode = TYPE_MODE (TREE_TYPE (arg));
2477
2478   /* Check if sincos insn is available, otherwise emit the call.  */
2479   if (optab_handler (sincos_optab, mode) == CODE_FOR_nothing)
2480     return NULL_RTX;
2481
2482   target1 = gen_reg_rtx (mode);
2483   target2 = gen_reg_rtx (mode);
2484
2485   op0 = expand_normal (arg);
2486   alias_type = build_pointer_type_for_mode (TREE_TYPE (arg), ptr_mode, true);
2487   alias_off = build_int_cst (alias_type, 0);
2488   op1 = expand_normal (fold_build2_loc (loc, MEM_REF, TREE_TYPE (arg),
2489                                         sinp, alias_off));
2490   op2 = expand_normal (fold_build2_loc (loc, MEM_REF, TREE_TYPE (arg),
2491                                         cosp, alias_off));
2492
2493   /* Compute into target1 and target2.
2494      Set TARGET to wherever the result comes back.  */
2495   result = expand_twoval_unop (sincos_optab, op0, target2, target1, 0);
2496   gcc_assert (result);
2497
2498   /* Move target1 and target2 to the memory locations indicated
2499      by op1 and op2.  */
2500   emit_move_insn (op1, target1);
2501   emit_move_insn (op2, target2);
2502
2503   return const0_rtx;
2504 }
2505
2506 /* Expand a call to the internal cexpi builtin to the sincos math function.
2507    EXP is the expression that is a call to the builtin function; if convenient,
2508    the result should be placed in TARGET.  */
2509
2510 static rtx
2511 expand_builtin_cexpi (tree exp, rtx target)
2512 {
2513   tree fndecl = get_callee_fndecl (exp);
2514   tree arg, type;
2515   enum machine_mode mode;
2516   rtx op0, op1, op2;
2517   location_t loc = EXPR_LOCATION (exp);
2518
2519   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2520     return NULL_RTX;
2521
2522   arg = CALL_EXPR_ARG (exp, 0);
2523   type = TREE_TYPE (arg);
2524   mode = TYPE_MODE (TREE_TYPE (arg));
2525
2526   /* Try expanding via a sincos optab, fall back to emitting a libcall
2527      to sincos or cexp.  We are sure we have sincos or cexp because cexpi
2528      is only generated from sincos, cexp or if we have either of them.  */
2529   if (optab_handler (sincos_optab, mode) != CODE_FOR_nothing)
2530     {
2531       op1 = gen_reg_rtx (mode);
2532       op2 = gen_reg_rtx (mode);
2533
2534       op0 = expand_expr (arg, NULL_RTX, VOIDmode, EXPAND_NORMAL);
2535
2536       /* Compute into op1 and op2.  */
2537       expand_twoval_unop (sincos_optab, op0, op2, op1, 0);
2538     }
2539   else if (TARGET_HAS_SINCOS)
2540     {
2541       tree call, fn = NULL_TREE;
2542       tree top1, top2;
2543       rtx op1a, op2a;
2544
2545       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2546         fn = builtin_decl_explicit (BUILT_IN_SINCOSF);
2547       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2548         fn = builtin_decl_explicit (BUILT_IN_SINCOS);
2549       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2550         fn = builtin_decl_explicit (BUILT_IN_SINCOSL);
2551       else
2552         gcc_unreachable ();
2553
2554       op1 = assign_temp (TREE_TYPE (arg), 1, 1);
2555       op2 = assign_temp (TREE_TYPE (arg), 1, 1);
2556       op1a = copy_addr_to_reg (XEXP (op1, 0));
2557       op2a = copy_addr_to_reg (XEXP (op2, 0));
2558       top1 = make_tree (build_pointer_type (TREE_TYPE (arg)), op1a);
2559       top2 = make_tree (build_pointer_type (TREE_TYPE (arg)), op2a);
2560
2561       /* Make sure not to fold the sincos call again.  */
2562       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2563       expand_normal (build_call_nary (TREE_TYPE (TREE_TYPE (fn)),
2564                                       call, 3, arg, top1, top2));
2565     }
2566   else
2567     {
2568       tree call, fn = NULL_TREE, narg;
2569       tree ctype = build_complex_type (type);
2570
2571       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2572         fn = builtin_decl_explicit (BUILT_IN_CEXPF);
2573       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2574         fn = builtin_decl_explicit (BUILT_IN_CEXP);
2575       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2576         fn = builtin_decl_explicit (BUILT_IN_CEXPL);
2577       else
2578         gcc_unreachable ();
2579
2580       /* If we don't have a decl for cexp create one.  This is the
2581          friendliest fallback if the user calls __builtin_cexpi
2582          without full target C99 function support.  */
2583       if (fn == NULL_TREE)
2584         {
2585           tree fntype;
2586           const char *name = NULL;
2587
2588           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2589             name = "cexpf";
2590           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2591             name = "cexp";
2592           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2593             name = "cexpl";
2594
2595           fntype = build_function_type_list (ctype, ctype, NULL_TREE);
2596           fn = build_fn_decl (name, fntype);
2597         }
2598
2599       narg = fold_build2_loc (loc, COMPLEX_EXPR, ctype,
2600                           build_real (type, dconst0), arg);
2601
2602       /* Make sure not to fold the cexp call again.  */
2603       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2604       return expand_expr (build_call_nary (ctype, call, 1, narg),
2605                           target, VOIDmode, EXPAND_NORMAL);
2606     }
2607
2608   /* Now build the proper return type.  */
2609   return expand_expr (build2 (COMPLEX_EXPR, build_complex_type (type),
2610                               make_tree (TREE_TYPE (arg), op2),
2611                               make_tree (TREE_TYPE (arg), op1)),
2612                       target, VOIDmode, EXPAND_NORMAL);
2613 }
2614
2615 /* Conveniently construct a function call expression.  FNDECL names the
2616    function to be called, N is the number of arguments, and the "..."
2617    parameters are the argument expressions.  Unlike build_call_exr
2618    this doesn't fold the call, hence it will always return a CALL_EXPR.  */
2619
2620 static tree
2621 build_call_nofold_loc (location_t loc, tree fndecl, int n, ...)
2622 {
2623   va_list ap;
2624   tree fntype = TREE_TYPE (fndecl);
2625   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
2626
2627   va_start (ap, n);
2628   fn = build_call_valist (TREE_TYPE (fntype), fn, n, ap);
2629   va_end (ap);
2630   SET_EXPR_LOCATION (fn, loc);
2631   return fn;
2632 }
2633
2634 /* Expand a call to one of the builtin rounding functions gcc defines
2635    as an extension (lfloor and lceil).  As these are gcc extensions we
2636    do not need to worry about setting errno to EDOM.
2637    If expanding via optab fails, lower expression to (int)(floor(x)).
2638    EXP is the expression that is a call to the builtin function;
2639    if convenient, the result should be placed in TARGET.  */
2640
2641 static rtx
2642 expand_builtin_int_roundingfn (tree exp, rtx target)
2643 {
2644   convert_optab builtin_optab;
2645   rtx op0, insns, tmp;
2646   tree fndecl = get_callee_fndecl (exp);
2647   enum built_in_function fallback_fn;
2648   tree fallback_fndecl;
2649   enum machine_mode mode;
2650   tree arg;
2651
2652   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2653     gcc_unreachable ();
2654
2655   arg = CALL_EXPR_ARG (exp, 0);
2656
2657   switch (DECL_FUNCTION_CODE (fndecl))
2658     {
2659     CASE_FLT_FN (BUILT_IN_ICEIL):
2660     CASE_FLT_FN (BUILT_IN_LCEIL):
2661     CASE_FLT_FN (BUILT_IN_LLCEIL):
2662       builtin_optab = lceil_optab;
2663       fallback_fn = BUILT_IN_CEIL;
2664       break;
2665
2666     CASE_FLT_FN (BUILT_IN_IFLOOR):
2667     CASE_FLT_FN (BUILT_IN_LFLOOR):
2668     CASE_FLT_FN (BUILT_IN_LLFLOOR):
2669       builtin_optab = lfloor_optab;
2670       fallback_fn = BUILT_IN_FLOOR;
2671       break;
2672
2673     default:
2674       gcc_unreachable ();
2675     }
2676
2677   /* Make a suitable register to place result in.  */
2678   mode = TYPE_MODE (TREE_TYPE (exp));
2679
2680   target = gen_reg_rtx (mode);
2681
2682   /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2683      need to expand the argument again.  This way, we will not perform
2684      side-effects more the once.  */
2685   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2686
2687   op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2688
2689   start_sequence ();
2690
2691   /* Compute into TARGET.  */
2692   if (expand_sfix_optab (target, op0, builtin_optab))
2693     {
2694       /* Output the entire sequence.  */
2695       insns = get_insns ();
2696       end_sequence ();
2697       emit_insn (insns);
2698       return target;
2699     }
2700
2701   /* If we were unable to expand via the builtin, stop the sequence
2702      (without outputting the insns).  */
2703   end_sequence ();
2704
2705   /* Fall back to floating point rounding optab.  */
2706   fallback_fndecl = mathfn_built_in (TREE_TYPE (arg), fallback_fn);
2707
2708   /* For non-C99 targets we may end up without a fallback fndecl here
2709      if the user called __builtin_lfloor directly.  In this case emit
2710      a call to the floor/ceil variants nevertheless.  This should result
2711      in the best user experience for not full C99 targets.  */
2712   if (fallback_fndecl == NULL_TREE)
2713     {
2714       tree fntype;
2715       const char *name = NULL;
2716
2717       switch (DECL_FUNCTION_CODE (fndecl))
2718         {
2719         case BUILT_IN_ICEIL:
2720         case BUILT_IN_LCEIL:
2721         case BUILT_IN_LLCEIL:
2722           name = "ceil";
2723           break;
2724         case BUILT_IN_ICEILF:
2725         case BUILT_IN_LCEILF:
2726         case BUILT_IN_LLCEILF:
2727           name = "ceilf";
2728           break;
2729         case BUILT_IN_ICEILL:
2730         case BUILT_IN_LCEILL:
2731         case BUILT_IN_LLCEILL:
2732           name = "ceill";
2733           break;
2734         case BUILT_IN_IFLOOR:
2735         case BUILT_IN_LFLOOR:
2736         case BUILT_IN_LLFLOOR:
2737           name = "floor";
2738           break;
2739         case BUILT_IN_IFLOORF:
2740         case BUILT_IN_LFLOORF:
2741         case BUILT_IN_LLFLOORF:
2742           name = "floorf";
2743           break;
2744         case BUILT_IN_IFLOORL:
2745         case BUILT_IN_LFLOORL:
2746         case BUILT_IN_LLFLOORL:
2747           name = "floorl";
2748           break;
2749         default:
2750           gcc_unreachable ();
2751         }
2752
2753       fntype = build_function_type_list (TREE_TYPE (arg),
2754                                          TREE_TYPE (arg), NULL_TREE);
2755       fallback_fndecl = build_fn_decl (name, fntype);
2756     }
2757
2758   exp = build_call_nofold_loc (EXPR_LOCATION (exp), fallback_fndecl, 1, arg);
2759
2760   tmp = expand_normal (exp);
2761   tmp = maybe_emit_group_store (tmp, TREE_TYPE (exp));
2762
2763   /* Truncate the result of floating point optab to integer
2764      via expand_fix ().  */
2765   target = gen_reg_rtx (mode);
2766   expand_fix (target, tmp, 0);
2767
2768   return target;
2769 }
2770
2771 /* Expand a call to one of the builtin math functions doing integer
2772    conversion (lrint).
2773    Return 0 if a normal call should be emitted rather than expanding the
2774    function in-line.  EXP is the expression that is a call to the builtin
2775    function; if convenient, the result should be placed in TARGET.  */
2776
2777 static rtx
2778 expand_builtin_int_roundingfn_2 (tree exp, rtx target)
2779 {
2780   convert_optab builtin_optab;
2781   rtx op0, insns;
2782   tree fndecl = get_callee_fndecl (exp);
2783   tree arg;
2784   enum machine_mode mode;
2785   enum built_in_function fallback_fn = BUILT_IN_NONE;
2786
2787   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2788      gcc_unreachable ();
2789
2790   arg = CALL_EXPR_ARG (exp, 0);
2791
2792   switch (DECL_FUNCTION_CODE (fndecl))
2793     {
2794     CASE_FLT_FN (BUILT_IN_IRINT):
2795       fallback_fn = BUILT_IN_LRINT;
2796       /* FALLTHRU */
2797     CASE_FLT_FN (BUILT_IN_LRINT):
2798     CASE_FLT_FN (BUILT_IN_LLRINT):
2799       builtin_optab = lrint_optab;
2800       break;
2801
2802     CASE_FLT_FN (BUILT_IN_IROUND):
2803       fallback_fn = BUILT_IN_LROUND;
2804       /* FALLTHRU */
2805     CASE_FLT_FN (BUILT_IN_LROUND):
2806     CASE_FLT_FN (BUILT_IN_LLROUND):
2807       builtin_optab = lround_optab;
2808       break;
2809
2810     default:
2811       gcc_unreachable ();
2812     }
2813
2814   /* There's no easy way to detect the case we need to set EDOM.  */
2815   if (flag_errno_math && fallback_fn == BUILT_IN_NONE)
2816     return NULL_RTX;
2817
2818   /* Make a suitable register to place result in.  */
2819   mode = TYPE_MODE (TREE_TYPE (exp));
2820
2821   /* There's no easy way to detect the case we need to set EDOM.  */
2822   if (!flag_errno_math)
2823     {
2824       rtx result = gen_reg_rtx (mode);
2825
2826       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2827          need to expand the argument again.  This way, we will not perform
2828          side-effects more the once.  */
2829       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2830
2831       op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2832
2833       start_sequence ();
2834
2835       if (expand_sfix_optab (result, op0, builtin_optab))
2836         {
2837           /* Output the entire sequence.  */
2838           insns = get_insns ();
2839           end_sequence ();
2840           emit_insn (insns);
2841           return result;
2842         }
2843
2844       /* If we were unable to expand via the builtin, stop the sequence
2845          (without outputting the insns) and call to the library function
2846          with the stabilized argument list.  */
2847       end_sequence ();
2848     }
2849
2850   if (fallback_fn != BUILT_IN_NONE)
2851     {
2852       /* Fall back to rounding to long int.  Use implicit_p 0 - for non-C99
2853          targets, (int) round (x) should never be transformed into
2854          BUILT_IN_IROUND and if __builtin_iround is called directly, emit
2855          a call to lround in the hope that the target provides at least some
2856          C99 functions.  This should result in the best user experience for
2857          not full C99 targets.  */
2858       tree fallback_fndecl = mathfn_built_in_1 (TREE_TYPE (arg),
2859                                                 fallback_fn, 0);
2860
2861       exp = build_call_nofold_loc (EXPR_LOCATION (exp),
2862                                    fallback_fndecl, 1, arg);
2863
2864       target = expand_call (exp, NULL_RTX, target == const0_rtx);
2865       target = maybe_emit_group_store (target, TREE_TYPE (exp));
2866       return convert_to_mode (mode, target, 0);
2867     }
2868
2869   return expand_call (exp, target, target == const0_rtx);
2870 }
2871
2872 /* Expand a call to the powi built-in mathematical function.  Return NULL_RTX if
2873    a normal call should be emitted rather than expanding the function
2874    in-line.  EXP is the expression that is a call to the builtin
2875    function; if convenient, the result should be placed in TARGET.  */
2876
2877 static rtx
2878 expand_builtin_powi (tree exp, rtx target)
2879 {
2880   tree arg0, arg1;
2881   rtx op0, op1;
2882   enum machine_mode mode;
2883   enum machine_mode mode2;
2884
2885   if (! validate_arglist (exp, REAL_TYPE, INTEGER_TYPE, VOID_TYPE))
2886     return NULL_RTX;
2887
2888   arg0 = CALL_EXPR_ARG (exp, 0);
2889   arg1 = CALL_EXPR_ARG (exp, 1);
2890   mode = TYPE_MODE (TREE_TYPE (exp));
2891
2892   /* Emit a libcall to libgcc.  */
2893
2894   /* Mode of the 2nd argument must match that of an int.  */
2895   mode2 = mode_for_size (INT_TYPE_SIZE, MODE_INT, 0);
2896
2897   if (target == NULL_RTX)
2898     target = gen_reg_rtx (mode);
2899
2900   op0 = expand_expr (arg0, NULL_RTX, mode, EXPAND_NORMAL);
2901   if (GET_MODE (op0) != mode)
2902     op0 = convert_to_mode (mode, op0, 0);
2903   op1 = expand_expr (arg1, NULL_RTX, mode2, EXPAND_NORMAL);
2904   if (GET_MODE (op1) != mode2)
2905     op1 = convert_to_mode (mode2, op1, 0);
2906
2907   target = emit_library_call_value (optab_libfunc (powi_optab, mode),
2908                                     target, LCT_CONST, mode, 2,
2909                                     op0, mode, op1, mode2);
2910
2911   return target;
2912 }
2913
2914 /* Expand expression EXP which is a call to the strlen builtin.  Return
2915    NULL_RTX if we failed the caller should emit a normal call, otherwise
2916    try to get the result in TARGET, if convenient.  */
2917
2918 static rtx
2919 expand_builtin_strlen (tree exp, rtx target,
2920                        enum machine_mode target_mode)
2921 {
2922   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
2923     return NULL_RTX;
2924   else
2925     {
2926       struct expand_operand ops[4];
2927       rtx pat;
2928       tree len;
2929       tree src = CALL_EXPR_ARG (exp, 0);
2930       rtx src_reg, before_strlen;
2931       enum machine_mode insn_mode = target_mode;
2932       enum insn_code icode = CODE_FOR_nothing;
2933       unsigned int align;
2934
2935       /* If the length can be computed at compile-time, return it.  */
2936       len = c_strlen (src, 0);
2937       if (len)
2938         return expand_expr (len, target, target_mode, EXPAND_NORMAL);
2939
2940       /* If the length can be computed at compile-time and is constant
2941          integer, but there are side-effects in src, evaluate
2942          src for side-effects, then return len.
2943          E.g. x = strlen (i++ ? "xfoo" + 1 : "bar");
2944          can be optimized into: i++; x = 3;  */
2945       len = c_strlen (src, 1);
2946       if (len && TREE_CODE (len) == INTEGER_CST)
2947         {
2948           expand_expr (src, const0_rtx, VOIDmode, EXPAND_NORMAL);
2949           return expand_expr (len, target, target_mode, EXPAND_NORMAL);
2950         }
2951
2952       align = get_pointer_alignment (src) / BITS_PER_UNIT;
2953
2954       /* If SRC is not a pointer type, don't do this operation inline.  */
2955       if (align == 0)
2956         return NULL_RTX;
2957
2958       /* Bail out if we can't compute strlen in the right mode.  */
2959       while (insn_mode != VOIDmode)
2960         {
2961           icode = optab_handler (strlen_optab, insn_mode);
2962           if (icode != CODE_FOR_nothing)
2963             break;
2964
2965           insn_mode = GET_MODE_WIDER_MODE (insn_mode);
2966         }
2967       if (insn_mode == VOIDmode)
2968         return NULL_RTX;
2969
2970       /* Make a place to hold the source address.  We will not expand
2971          the actual source until we are sure that the expansion will
2972          not fail -- there are trees that cannot be expanded twice.  */
2973       src_reg = gen_reg_rtx (Pmode);
2974
2975       /* Mark the beginning of the strlen sequence so we can emit the
2976          source operand later.  */
2977       before_strlen = get_last_insn ();
2978
2979       create_output_operand (&ops[0], target, insn_mode);
2980       create_fixed_operand (&ops[1], gen_rtx_MEM (BLKmode, src_reg));
2981       create_integer_operand (&ops[2], 0);
2982       create_integer_operand (&ops[3], align);
2983       if (!maybe_expand_insn (icode, 4, ops))
2984         return NULL_RTX;
2985
2986       /* Now that we are assured of success, expand the source.  */
2987       start_sequence ();
2988       pat = expand_expr (src, src_reg, Pmode, EXPAND_NORMAL);
2989       if (pat != src_reg)
2990         {
2991 #ifdef POINTERS_EXTEND_UNSIGNED
2992           if (GET_MODE (pat) != Pmode)
2993             pat = convert_to_mode (Pmode, pat,
2994                                    POINTERS_EXTEND_UNSIGNED);
2995 #endif
2996           emit_move_insn (src_reg, pat);
2997         }
2998       pat = get_insns ();
2999       end_sequence ();
3000
3001       if (before_strlen)
3002         emit_insn_after (pat, before_strlen);
3003       else
3004         emit_insn_before (pat, get_insns ());
3005
3006       /* Return the value in the proper mode for this function.  */
3007       if (GET_MODE (ops[0].value) == target_mode)
3008         target = ops[0].value;
3009       else if (target != 0)
3010         convert_move (target, ops[0].value, 0);
3011       else
3012         target = convert_to_mode (target_mode, ops[0].value, 0);
3013
3014       return target;
3015     }
3016 }
3017
3018 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3019    bytes from constant string DATA + OFFSET and return it as target
3020    constant.  */
3021
3022 static rtx
3023 builtin_memcpy_read_str (void *data, HOST_WIDE_INT offset,
3024                          enum machine_mode mode)
3025 {
3026   const char *str = (const char *) data;
3027
3028   gcc_assert (offset >= 0
3029               && ((unsigned HOST_WIDE_INT) offset + GET_MODE_SIZE (mode)
3030                   <= strlen (str) + 1));
3031
3032   return c_readstr (str + offset, mode);
3033 }
3034
3035 /* Expand a call EXP to the memcpy builtin.
3036    Return NULL_RTX if we failed, the caller should emit a normal call,
3037    otherwise try to get the result in TARGET, if convenient (and in
3038    mode MODE if that's convenient).  */
3039
3040 static rtx
3041 expand_builtin_memcpy (tree exp, rtx target)
3042 {
3043   if (!validate_arglist (exp,
3044                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3045     return NULL_RTX;
3046   else
3047     {
3048       tree dest = CALL_EXPR_ARG (exp, 0);
3049       tree src = CALL_EXPR_ARG (exp, 1);
3050       tree len = CALL_EXPR_ARG (exp, 2);
3051       const char *src_str;
3052       unsigned int src_align = get_pointer_alignment (src);
3053       unsigned int dest_align = get_pointer_alignment (dest);
3054       rtx dest_mem, src_mem, dest_addr, len_rtx;
3055       HOST_WIDE_INT expected_size = -1;
3056       unsigned int expected_align = 0;
3057
3058       /* If DEST is not a pointer type, call the normal function.  */
3059       if (dest_align == 0)
3060         return NULL_RTX;
3061
3062       /* If either SRC is not a pointer type, don't do this
3063          operation in-line.  */
3064       if (src_align == 0)
3065         return NULL_RTX;
3066
3067       if (currently_expanding_gimple_stmt)
3068         stringop_block_profile (currently_expanding_gimple_stmt,
3069                                 &expected_align, &expected_size);
3070
3071       if (expected_align < dest_align)
3072         expected_align = dest_align;
3073       dest_mem = get_memory_rtx (dest, len);
3074       set_mem_align (dest_mem, dest_align);
3075       len_rtx = expand_normal (len);
3076       src_str = c_getstr (src);
3077
3078       /* If SRC is a string constant and block move would be done
3079          by pieces, we can avoid loading the string from memory
3080          and only stored the computed constants.  */
3081       if (src_str
3082           && CONST_INT_P (len_rtx)
3083           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
3084           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
3085                                   CONST_CAST (char *, src_str),
3086                                   dest_align, false))
3087         {
3088           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
3089                                       builtin_memcpy_read_str,
3090                                       CONST_CAST (char *, src_str),
3091                                       dest_align, false, 0);
3092           dest_mem = force_operand (XEXP (dest_mem, 0), target);
3093           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3094           return dest_mem;
3095         }
3096
3097       src_mem = get_memory_rtx (src, len);
3098       set_mem_align (src_mem, src_align);
3099
3100       /* Copy word part most expediently.  */
3101       dest_addr = emit_block_move_hints (dest_mem, src_mem, len_rtx,
3102                                          CALL_EXPR_TAILCALL (exp)
3103                                          ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
3104                                          expected_align, expected_size);
3105
3106       if (dest_addr == 0)
3107         {
3108           dest_addr = force_operand (XEXP (dest_mem, 0), target);
3109           dest_addr = convert_memory_address (ptr_mode, dest_addr);
3110         }
3111       return dest_addr;
3112     }
3113 }
3114
3115 /* Expand a call EXP to the mempcpy builtin.
3116    Return NULL_RTX if we failed; the caller should emit a normal call,
3117    otherwise try to get the result in TARGET, if convenient (and in
3118    mode MODE if that's convenient).  If ENDP is 0 return the
3119    destination pointer, if ENDP is 1 return the end pointer ala
3120    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3121    stpcpy.  */
3122
3123 static rtx
3124 expand_builtin_mempcpy (tree exp, rtx target, enum machine_mode mode)
3125 {
3126   if (!validate_arglist (exp,
3127                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3128     return NULL_RTX;
3129   else
3130     {
3131       tree dest = CALL_EXPR_ARG (exp, 0);
3132       tree src = CALL_EXPR_ARG (exp, 1);
3133       tree len = CALL_EXPR_ARG (exp, 2);
3134       return expand_builtin_mempcpy_args (dest, src, len,
3135                                           target, mode, /*endp=*/ 1);
3136     }
3137 }
3138
3139 /* Helper function to do the actual work for expand_builtin_mempcpy.  The
3140    arguments to the builtin_mempcpy call DEST, SRC, and LEN are broken out
3141    so that this can also be called without constructing an actual CALL_EXPR.
3142    The other arguments and return value are the same as for
3143    expand_builtin_mempcpy.  */
3144
3145 static rtx
3146 expand_builtin_mempcpy_args (tree dest, tree src, tree len,
3147                              rtx target, enum machine_mode mode, int endp)
3148 {
3149     /* If return value is ignored, transform mempcpy into memcpy.  */
3150   if (target == const0_rtx && builtin_decl_implicit_p (BUILT_IN_MEMCPY))
3151     {
3152       tree fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
3153       tree result = build_call_nofold_loc (UNKNOWN_LOCATION, fn, 3,
3154                                            dest, src, len);
3155       return expand_expr (result, target, mode, EXPAND_NORMAL);
3156     }
3157   else
3158     {
3159       const char *src_str;
3160       unsigned int src_align = get_pointer_alignment (src);
3161       unsigned int dest_align = get_pointer_alignment (dest);
3162       rtx dest_mem, src_mem, len_rtx;
3163
3164       /* If either SRC or DEST is not a pointer type, don't do this
3165          operation in-line.  */
3166       if (dest_align == 0 || src_align == 0)
3167         return NULL_RTX;
3168
3169       /* If LEN is not constant, call the normal function.  */
3170       if (! host_integerp (len, 1))
3171         return NULL_RTX;
3172
3173       len_rtx = expand_normal (len);
3174       src_str = c_getstr (src);
3175
3176       /* If SRC is a string constant and block move would be done
3177          by pieces, we can avoid loading the string from memory
3178          and only stored the computed constants.  */
3179       if (src_str
3180           && CONST_INT_P (len_rtx)
3181           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
3182           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
3183                                   CONST_CAST (char *, src_str),
3184                                   dest_align, false))
3185         {
3186           dest_mem = get_memory_rtx (dest, len);
3187           set_mem_align (dest_mem, dest_align);
3188           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
3189                                       builtin_memcpy_read_str,
3190                                       CONST_CAST (char *, src_str),
3191                                       dest_align, false, endp);
3192           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3193           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3194           return dest_mem;
3195         }
3196
3197       if (CONST_INT_P (len_rtx)
3198           && can_move_by_pieces (INTVAL (len_rtx),
3199                                  MIN (dest_align, src_align)))
3200         {
3201           dest_mem = get_memory_rtx (dest, len);
3202           set_mem_align (dest_mem, dest_align);
3203           src_mem = get_memory_rtx (src, len);
3204           set_mem_align (src_mem, src_align);
3205           dest_mem = move_by_pieces (dest_mem, src_mem, INTVAL (len_rtx),
3206                                      MIN (dest_align, src_align), endp);
3207           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3208           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3209           return dest_mem;
3210         }
3211
3212       return NULL_RTX;
3213     }
3214 }
3215
3216 #ifndef HAVE_movstr
3217 # define HAVE_movstr 0
3218 # define CODE_FOR_movstr CODE_FOR_nothing
3219 #endif
3220
3221 /* Expand into a movstr instruction, if one is available.  Return NULL_RTX if
3222    we failed, the caller should emit a normal call, otherwise try to
3223    get the result in TARGET, if convenient.  If ENDP is 0 return the
3224    destination pointer, if ENDP is 1 return the end pointer ala
3225    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3226    stpcpy.  */
3227
3228 static rtx
3229 expand_movstr (tree dest, tree src, rtx target, int endp)
3230 {
3231   struct expand_operand ops[3];
3232   rtx dest_mem;
3233   rtx src_mem;
3234
3235   if (!HAVE_movstr)
3236     return NULL_RTX;
3237
3238   dest_mem = get_memory_rtx (dest, NULL);
3239   src_mem = get_memory_rtx (src, NULL);
3240   if (!endp)
3241     {
3242       target = force_reg (Pmode, XEXP (dest_mem, 0));
3243       dest_mem = replace_equiv_address (dest_mem, target);
3244     }
3245
3246   create_output_operand (&ops[0], endp ? target : NULL_RTX, Pmode);
3247   create_fixed_operand (&ops[1], dest_mem);
3248   create_fixed_operand (&ops[2], src_mem);
3249   expand_insn (CODE_FOR_movstr, 3, ops);
3250
3251   if (endp && target != const0_rtx)
3252     {
3253       target = ops[0].value;
3254       /* movstr is supposed to set end to the address of the NUL
3255          terminator.  If the caller requested a mempcpy-like return value,
3256          adjust it.  */
3257       if (endp == 1)
3258         {
3259           rtx tem = plus_constant (GET_MODE (target),
3260                                    gen_lowpart (GET_MODE (target), target), 1);
3261           emit_move_insn (target, force_operand (tem, NULL_RTX));
3262         }
3263     }
3264   return target;
3265 }
3266
3267 /* Expand expression EXP, which is a call to the strcpy builtin.  Return
3268    NULL_RTX if we failed the caller should emit a normal call, otherwise
3269    try to get the result in TARGET, if convenient (and in mode MODE if that's
3270    convenient).  */
3271
3272 static rtx
3273 expand_builtin_strcpy (tree exp, rtx target)
3274 {
3275   if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3276    {
3277      tree dest = CALL_EXPR_ARG (exp, 0);
3278      tree src = CALL_EXPR_ARG (exp, 1);
3279      return expand_builtin_strcpy_args (dest, src, target);
3280    }
3281    return NULL_RTX;
3282 }
3283
3284 /* Helper function to do the actual work for expand_builtin_strcpy.  The
3285    arguments to the builtin_strcpy call DEST and SRC are broken out
3286    so that this can also be called without constructing an actual CALL_EXPR.
3287    The other arguments and return value are the same as for
3288    expand_builtin_strcpy.  */
3289
3290 static rtx
3291 expand_builtin_strcpy_args (tree dest, tree src, rtx target)
3292 {
3293   return expand_movstr (dest, src, target, /*endp=*/0);
3294 }
3295
3296 /* Expand a call EXP to the stpcpy builtin.
3297    Return NULL_RTX if we failed the caller should emit a normal call,
3298    otherwise try to get the result in TARGET, if convenient (and in
3299    mode MODE if that's convenient).  */
3300
3301 static rtx
3302 expand_builtin_stpcpy (tree exp, rtx target, enum machine_mode mode)
3303 {
3304   tree dst, src;
3305   location_t loc = EXPR_LOCATION (exp);
3306
3307   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3308     return NULL_RTX;
3309
3310   dst = CALL_EXPR_ARG (exp, 0);
3311   src = CALL_EXPR_ARG (exp, 1);
3312
3313   /* If return value is ignored, transform stpcpy into strcpy.  */
3314   if (target == const0_rtx && builtin_decl_implicit (BUILT_IN_STRCPY))
3315     {
3316       tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
3317       tree result = build_call_nofold_loc (loc, fn, 2, dst, src);
3318       return expand_expr (result, target, mode, EXPAND_NORMAL);
3319     }
3320   else
3321     {
3322       tree len, lenp1;
3323       rtx ret;
3324
3325       /* Ensure we get an actual string whose length can be evaluated at
3326          compile-time, not an expression containing a string.  This is
3327          because the latter will potentially produce pessimized code
3328          when used to produce the return value.  */
3329       if (! c_getstr (src) || ! (len = c_strlen (src, 0)))
3330         return expand_movstr (dst, src, target, /*endp=*/2);
3331
3332       lenp1 = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
3333       ret = expand_builtin_mempcpy_args (dst, src, lenp1,
3334                                          target, mode, /*endp=*/2);
3335
3336       if (ret)
3337         return ret;
3338
3339       if (TREE_CODE (len) == INTEGER_CST)
3340         {
3341           rtx len_rtx = expand_normal (len);
3342
3343           if (CONST_INT_P (len_rtx))
3344             {
3345               ret = expand_builtin_strcpy_args (dst, src, target);
3346
3347               if (ret)
3348                 {
3349                   if (! target)
3350                     {
3351                       if (mode != VOIDmode)
3352                         target = gen_reg_rtx (mode);
3353                       else
3354                         target = gen_reg_rtx (GET_MODE (ret));
3355                     }
3356                   if (GET_MODE (target) != GET_MODE (ret))
3357                     ret = gen_lowpart (GET_MODE (target), ret);
3358
3359                   ret = plus_constant (GET_MODE (ret), ret, INTVAL (len_rtx));
3360                   ret = emit_move_insn (target, force_operand (ret, NULL_RTX));
3361                   gcc_assert (ret);
3362
3363                   return target;
3364                 }
3365             }
3366         }
3367
3368       return expand_movstr (dst, src, target, /*endp=*/2);
3369     }
3370 }
3371
3372 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3373    bytes from constant string DATA + OFFSET and return it as target
3374    constant.  */
3375
3376 rtx
3377 builtin_strncpy_read_str (void *data, HOST_WIDE_INT offset,
3378                           enum machine_mode mode)
3379 {
3380   const char *str = (const char *) data;
3381
3382   if ((unsigned HOST_WIDE_INT) offset > strlen (str))
3383     return const0_rtx;
3384
3385   return c_readstr (str + offset, mode);
3386 }
3387
3388 /* Expand expression EXP, which is a call to the strncpy builtin.  Return
3389    NULL_RTX if we failed the caller should emit a normal call.  */
3390
3391 static rtx
3392 expand_builtin_strncpy (tree exp, rtx target)
3393 {
3394   location_t loc = EXPR_LOCATION (exp);
3395
3396   if (validate_arglist (exp,
3397                         POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3398     {
3399       tree dest = CALL_EXPR_ARG (exp, 0);
3400       tree src = CALL_EXPR_ARG (exp, 1);
3401       tree len = CALL_EXPR_ARG (exp, 2);
3402       tree slen = c_strlen (src, 1);
3403
3404       /* We must be passed a constant len and src parameter.  */
3405       if (!host_integerp (len, 1) || !slen || !host_integerp (slen, 1))
3406         return NULL_RTX;
3407
3408       slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
3409
3410       /* We're required to pad with trailing zeros if the requested
3411          len is greater than strlen(s2)+1.  In that case try to
3412          use store_by_pieces, if it fails, punt.  */
3413       if (tree_int_cst_lt (slen, len))
3414         {
3415           unsigned int dest_align = get_pointer_alignment (dest);
3416           const char *p = c_getstr (src);
3417           rtx dest_mem;
3418
3419           if (!p || dest_align == 0 || !host_integerp (len, 1)
3420               || !can_store_by_pieces (tree_low_cst (len, 1),
3421                                        builtin_strncpy_read_str,
3422                                        CONST_CAST (char *, p),
3423                                        dest_align, false))
3424             return NULL_RTX;
3425
3426           dest_mem = get_memory_rtx (dest, len);
3427           store_by_pieces (dest_mem, tree_low_cst (len, 1),
3428                            builtin_strncpy_read_str,
3429                            CONST_CAST (char *, p), dest_align, false, 0);
3430           dest_mem = force_operand (XEXP (dest_mem, 0), target);
3431           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3432           return dest_mem;
3433         }
3434     }
3435   return NULL_RTX;
3436 }
3437
3438 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3439    bytes from constant string DATA + OFFSET and return it as target
3440    constant.  */
3441
3442 rtx
3443 builtin_memset_read_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3444                          enum machine_mode mode)
3445 {
3446   const char *c = (const char *) data;
3447   char *p = XALLOCAVEC (char, GET_MODE_SIZE (mode));
3448
3449   memset (p, *c, GET_MODE_SIZE (mode));
3450
3451   return c_readstr (p, mode);
3452 }
3453
3454 /* Callback routine for store_by_pieces.  Return the RTL of a register
3455    containing GET_MODE_SIZE (MODE) consecutive copies of the unsigned
3456    char value given in the RTL register data.  For example, if mode is
3457    4 bytes wide, return the RTL for 0x01010101*data.  */
3458
3459 static rtx
3460 builtin_memset_gen_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3461                         enum machine_mode mode)
3462 {
3463   rtx target, coeff;
3464   size_t size;
3465   char *p;
3466
3467   size = GET_MODE_SIZE (mode);
3468   if (size == 1)
3469     return (rtx) data;
3470
3471   p = XALLOCAVEC (char, size);
3472   memset (p, 1, size);
3473   coeff = c_readstr (p, mode);
3474
3475   target = convert_to_mode (mode, (rtx) data, 1);
3476   target = expand_mult (mode, target, coeff, NULL_RTX, 1);
3477   return force_reg (mode, target);
3478 }
3479
3480 /* Expand expression EXP, which is a call to the memset builtin.  Return
3481    NULL_RTX if we failed the caller should emit a normal call, otherwise
3482    try to get the result in TARGET, if convenient (and in mode MODE if that's
3483    convenient).  */
3484
3485 static rtx
3486 expand_builtin_memset (tree exp, rtx target, enum machine_mode mode)
3487 {
3488   if (!validate_arglist (exp,
3489                          POINTER_TYPE, INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
3490     return NULL_RTX;
3491   else
3492     {
3493       tree dest = CALL_EXPR_ARG (exp, 0);
3494       tree val = CALL_EXPR_ARG (exp, 1);
3495       tree len = CALL_EXPR_ARG (exp, 2);
3496       return expand_builtin_memset_args (dest, val, len, target, mode, exp);
3497     }
3498 }
3499
3500 /* Helper function to do the actual work for expand_builtin_memset.  The
3501    arguments to the builtin_memset call DEST, VAL, and LEN are broken out
3502    so that this can also be called without constructing an actual CALL_EXPR.
3503    The other arguments and return value are the same as for
3504    expand_builtin_memset.  */
3505
3506 static rtx
3507 expand_builtin_memset_args (tree dest, tree val, tree len,
3508                             rtx target, enum machine_mode mode, tree orig_exp)
3509 {
3510   tree fndecl, fn;
3511   enum built_in_function fcode;
3512   enum machine_mode val_mode;
3513   char c;
3514   unsigned int dest_align;
3515   rtx dest_mem, dest_addr, len_rtx;
3516   HOST_WIDE_INT expected_size = -1;
3517   unsigned int expected_align = 0;
3518
3519   dest_align = get_pointer_alignment (dest);
3520
3521   /* If DEST is not a pointer type, don't do this operation in-line.  */
3522   if (dest_align == 0)
3523     return NULL_RTX;
3524
3525   if (currently_expanding_gimple_stmt)
3526     stringop_block_profile (currently_expanding_gimple_stmt,
3527                             &expected_align, &expected_size);
3528
3529   if (expected_align < dest_align)
3530     expected_align = dest_align;
3531
3532   /* If the LEN parameter is zero, return DEST.  */
3533   if (integer_zerop (len))
3534     {
3535       /* Evaluate and ignore VAL in case it has side-effects.  */
3536       expand_expr (val, const0_rtx, VOIDmode, EXPAND_NORMAL);
3537       return expand_expr (dest, target, mode, EXPAND_NORMAL);
3538     }
3539
3540   /* Stabilize the arguments in case we fail.  */
3541   dest = builtin_save_expr (dest);
3542   val = builtin_save_expr (val);
3543   len = builtin_save_expr (len);
3544
3545   len_rtx = expand_normal (len);
3546   dest_mem = get_memory_rtx (dest, len);
3547   val_mode = TYPE_MODE (unsigned_char_type_node);
3548
3549   if (TREE_CODE (val) != INTEGER_CST)
3550     {
3551       rtx val_rtx;
3552
3553       val_rtx = expand_normal (val);
3554       val_rtx = convert_to_mode (val_mode, val_rtx, 0);
3555
3556       /* Assume that we can memset by pieces if we can store
3557        * the coefficients by pieces (in the required modes).
3558        * We can't pass builtin_memset_gen_str as that emits RTL.  */
3559       c = 1;
3560       if (host_integerp (len, 1)
3561           && can_store_by_pieces (tree_low_cst (len, 1),
3562                                   builtin_memset_read_str, &c, dest_align,
3563                                   true))
3564         {
3565           val_rtx = force_reg (val_mode, val_rtx);
3566           store_by_pieces (dest_mem, tree_low_cst (len, 1),
3567                            builtin_memset_gen_str, val_rtx, dest_align,
3568                            true, 0);
3569         }
3570       else if (!set_storage_via_setmem (dest_mem, len_rtx, val_rtx,
3571                                         dest_align, expected_align,
3572                                         expected_size))
3573         goto do_libcall;
3574
3575       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3576       dest_mem = convert_memory_address (ptr_mode, dest_mem);
3577       return dest_mem;
3578     }
3579
3580   if (target_char_cast (val, &c))
3581     goto do_libcall;
3582
3583   if (c)
3584     {
3585       if (host_integerp (len, 1)
3586           && can_store_by_pieces (tree_low_cst (len, 1),
3587                                   builtin_memset_read_str, &c, dest_align,
3588                                   true))
3589         store_by_pieces (dest_mem, tree_low_cst (len, 1),
3590                          builtin_memset_read_str, &c, dest_align, true, 0);
3591       else if (!set_storage_via_setmem (dest_mem, len_rtx,
3592                                         gen_int_mode (c, val_mode),
3593                                         dest_align, expected_align,
3594                                         expected_size))
3595         goto do_libcall;
3596
3597       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3598       dest_mem = convert_memory_address (ptr_mode, dest_mem);
3599       return dest_mem;
3600     }
3601
3602   set_mem_align (dest_mem, dest_align);
3603   dest_addr = clear_storage_hints (dest_mem, len_rtx,
3604                                    CALL_EXPR_TAILCALL (orig_exp)
3605                                    ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
3606                                    expected_align, expected_size);
3607
3608   if (dest_addr == 0)
3609     {
3610       dest_addr = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3611       dest_addr = convert_memory_address (ptr_mode, dest_addr);
3612     }
3613
3614   return dest_addr;
3615
3616  do_libcall:
3617   fndecl = get_callee_fndecl (orig_exp);
3618   fcode = DECL_FUNCTION_CODE (fndecl);
3619   if (fcode == BUILT_IN_MEMSET)
3620     fn = build_call_nofold_loc (EXPR_LOCATION (orig_exp), fndecl, 3,
3621                                 dest, val, len);
3622   else if (fcode == BUILT_IN_BZERO)
3623     fn = build_call_nofold_loc (EXPR_LOCATION (orig_exp), fndecl, 2,
3624                                 dest, len);
3625   else
3626     gcc_unreachable ();
3627   gcc_assert (TREE_CODE (fn) == CALL_EXPR);
3628   CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (orig_exp);
3629   return expand_call (fn, target, target == const0_rtx);
3630 }
3631
3632 /* Expand expression EXP, which is a call to the bzero builtin.  Return
3633    NULL_RTX if we failed the caller should emit a normal call.  */
3634
3635 static rtx
3636 expand_builtin_bzero (tree exp)
3637 {
3638   tree dest, size;
3639   location_t loc = EXPR_LOCATION (exp);
3640
3641   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3642     return NULL_RTX;
3643
3644   dest = CALL_EXPR_ARG (exp, 0);
3645   size = CALL_EXPR_ARG (exp, 1);
3646
3647   /* New argument list transforming bzero(ptr x, int y) to
3648      memset(ptr x, int 0, size_t y).   This is done this way
3649      so that if it isn't expanded inline, we fallback to
3650      calling bzero instead of memset.  */
3651
3652   return expand_builtin_memset_args (dest, integer_zero_node,
3653                                      fold_convert_loc (loc,
3654                                                        size_type_node, size),
3655                                      const0_rtx, VOIDmode, exp);
3656 }
3657
3658 /* Expand expression EXP, which is a call to the memcmp built-in function.
3659    Return NULL_RTX if we failed and the caller should emit a normal call,
3660    otherwise try to get the result in TARGET, if convenient (and in mode
3661    MODE, if that's convenient).  */
3662
3663 static rtx
3664 expand_builtin_memcmp (tree exp, ATTRIBUTE_UNUSED rtx target,
3665                        ATTRIBUTE_UNUSED enum machine_mode mode)
3666 {
3667   location_t loc ATTRIBUTE_UNUSED = EXPR_LOCATION (exp);
3668
3669   if (!validate_arglist (exp,
3670                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3671     return NULL_RTX;
3672
3673   /* Note: The cmpstrnsi pattern, if it exists, is not suitable for
3674      implementing memcmp because it will stop if it encounters two
3675      zero bytes.  */
3676 #if defined HAVE_cmpmemsi
3677   {
3678     rtx arg1_rtx, arg2_rtx, arg3_rtx;
3679     rtx result;
3680     rtx insn;
3681     tree arg1 = CALL_EXPR_ARG (exp, 0);
3682     tree arg2 = CALL_EXPR_ARG (exp, 1);
3683     tree len = CALL_EXPR_ARG (exp, 2);
3684
3685     unsigned int arg1_align = get_pointer_alignment (arg1) / BITS_PER_UNIT;
3686     unsigned int arg2_align = get_pointer_alignment (arg2) / BITS_PER_UNIT;
3687     enum machine_mode insn_mode;
3688
3689     if (HAVE_cmpmemsi)
3690       insn_mode = insn_data[(int) CODE_FOR_cmpmemsi].operand[0].mode;
3691     else
3692       return NULL_RTX;
3693
3694     /* If we don't have POINTER_TYPE, call the function.  */
3695     if (arg1_align == 0 || arg2_align == 0)
3696       return NULL_RTX;
3697
3698     /* Make a place to write the result of the instruction.  */
3699     result = target;
3700     if (! (result != 0
3701            && REG_P (result) && GET_MODE (result) == insn_mode
3702            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3703       result = gen_reg_rtx (insn_mode);
3704
3705     arg1_rtx = get_memory_rtx (arg1, len);
3706     arg2_rtx = get_memory_rtx (arg2, len);
3707     arg3_rtx = expand_normal (fold_convert_loc (loc, sizetype, len));
3708
3709     /* Set MEM_SIZE as appropriate.  */
3710     if (CONST_INT_P (arg3_rtx))
3711       {
3712         set_mem_size (arg1_rtx, INTVAL (arg3_rtx));
3713         set_mem_size (arg2_rtx, INTVAL (arg3_rtx));
3714       }
3715
3716     if (HAVE_cmpmemsi)
3717       insn = gen_cmpmemsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3718                            GEN_INT (MIN (arg1_align, arg2_align)));
3719     else
3720       gcc_unreachable ();
3721
3722     if (insn)
3723       emit_insn (insn);
3724     else
3725       emit_library_call_value (memcmp_libfunc, result, LCT_PURE,
3726                                TYPE_MODE (integer_type_node), 3,
3727                                XEXP (arg1_rtx, 0), Pmode,
3728                                XEXP (arg2_rtx, 0), Pmode,
3729                                convert_to_mode (TYPE_MODE (sizetype), arg3_rtx,
3730                                                 TYPE_UNSIGNED (sizetype)),
3731                                TYPE_MODE (sizetype));
3732
3733     /* Return the value in the proper mode for this function.  */
3734     mode = TYPE_MODE (TREE_TYPE (exp));
3735     if (GET_MODE (result) == mode)
3736       return result;
3737     else if (target != 0)
3738       {
3739         convert_move (target, result, 0);
3740         return target;
3741       }
3742     else
3743       return convert_to_mode (mode, result, 0);
3744   }
3745 #endif /* HAVE_cmpmemsi.  */
3746
3747   return NULL_RTX;
3748 }
3749
3750 /* Expand expression EXP, which is a call to the strcmp builtin.  Return NULL_RTX
3751    if we failed the caller should emit a normal call, otherwise try to get
3752    the result in TARGET, if convenient.  */
3753
3754 static rtx
3755 expand_builtin_strcmp (tree exp, ATTRIBUTE_UNUSED rtx target)
3756 {
3757   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3758     return NULL_RTX;
3759
3760 #if defined HAVE_cmpstrsi || defined HAVE_cmpstrnsi
3761   if (direct_optab_handler (cmpstr_optab, SImode) != CODE_FOR_nothing
3762       || direct_optab_handler (cmpstrn_optab, SImode) != CODE_FOR_nothing)
3763     {
3764       rtx arg1_rtx, arg2_rtx;
3765       rtx result, insn = NULL_RTX;
3766       tree fndecl, fn;
3767       tree arg1 = CALL_EXPR_ARG (exp, 0);
3768       tree arg2 = CALL_EXPR_ARG (exp, 1);
3769
3770       unsigned int arg1_align = get_pointer_alignment (arg1) / BITS_PER_UNIT;
3771       unsigned int arg2_align = get_pointer_alignment (arg2) / BITS_PER_UNIT;
3772
3773       /* If we don't have POINTER_TYPE, call the function.  */
3774       if (arg1_align == 0 || arg2_align == 0)
3775         return NULL_RTX;
3776
3777       /* Stabilize the arguments in case gen_cmpstr(n)si fail.  */
3778       arg1 = builtin_save_expr (arg1);
3779       arg2 = builtin_save_expr (arg2);
3780
3781       arg1_rtx = get_memory_rtx (arg1, NULL);
3782       arg2_rtx = get_memory_rtx (arg2, NULL);
3783
3784 #ifdef HAVE_cmpstrsi
3785       /* Try to call cmpstrsi.  */
3786       if (HAVE_cmpstrsi)
3787         {
3788           enum machine_mode insn_mode
3789             = insn_data[(int) CODE_FOR_cmpstrsi].operand[0].mode;
3790
3791           /* Make a place to write the result of the instruction.  */
3792           result = target;
3793           if (! (result != 0
3794                  && REG_P (result) && GET_MODE (result) == insn_mode
3795                  && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3796             result = gen_reg_rtx (insn_mode);
3797
3798           insn = gen_cmpstrsi (result, arg1_rtx, arg2_rtx,
3799                                GEN_INT (MIN (arg1_align, arg2_align)));
3800         }
3801 #endif
3802 #ifdef HAVE_cmpstrnsi
3803       /* Try to determine at least one length and call cmpstrnsi.  */
3804       if (!insn && HAVE_cmpstrnsi)
3805         {
3806           tree len;
3807           rtx arg3_rtx;
3808
3809           enum machine_mode insn_mode
3810             = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
3811           tree len1 = c_strlen (arg1, 1);
3812           tree len2 = c_strlen (arg2, 1);
3813
3814           if (len1)
3815             len1 = size_binop (PLUS_EXPR, ssize_int (1), len1);
3816           if (len2)
3817             len2 = size_binop (PLUS_EXPR, ssize_int (1), len2);
3818
3819           /* If we don't have a constant length for the first, use the length
3820              of the second, if we know it.  We don't require a constant for
3821              this case; some cost analysis could be done if both are available
3822              but neither is constant.  For now, assume they're equally cheap,
3823              unless one has side effects.  If both strings have constant lengths,
3824              use the smaller.  */
3825
3826           if (!len1)
3827             len = len2;
3828           else if (!len2)
3829             len = len1;
3830           else if (TREE_SIDE_EFFECTS (len1))
3831             len = len2;
3832           else if (TREE_SIDE_EFFECTS (len2))
3833             len = len1;
3834           else if (TREE_CODE (len1) != INTEGER_CST)
3835             len = len2;
3836           else if (TREE_CODE (len2) != INTEGER_CST)
3837             len = len1;
3838           else if (tree_int_cst_lt (len1, len2))
3839             len = len1;
3840           else
3841             len = len2;
3842
3843           /* If both arguments have side effects, we cannot optimize.  */
3844           if (!len || TREE_SIDE_EFFECTS (len))
3845             goto do_libcall;
3846
3847           arg3_rtx = expand_normal (len);
3848
3849           /* Make a place to write the result of the instruction.  */
3850           result = target;
3851           if (! (result != 0
3852                  && REG_P (result) && GET_MODE (result) == insn_mode
3853                  && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3854             result = gen_reg_rtx (insn_mode);
3855
3856           insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3857                                 GEN_INT (MIN (arg1_align, arg2_align)));
3858         }
3859 #endif
3860
3861       if (insn)
3862         {
3863           enum machine_mode mode;
3864           emit_insn (insn);
3865
3866           /* Return the value in the proper mode for this function.  */
3867           mode = TYPE_MODE (TREE_TYPE (exp));
3868           if (GET_MODE (result) == mode)
3869             return result;
3870           if (target == 0)
3871             return convert_to_mode (mode, result, 0);
3872           convert_move (target, result, 0);
3873           return target;
3874         }
3875
3876       /* Expand the library call ourselves using a stabilized argument
3877          list to avoid re-evaluating the function's arguments twice.  */
3878 #ifdef HAVE_cmpstrnsi
3879     do_libcall:
3880 #endif
3881       fndecl = get_callee_fndecl (exp);
3882       fn = build_call_nofold_loc (EXPR_LOCATION (exp), fndecl, 2, arg1, arg2);
3883       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
3884       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
3885       return expand_call (fn, target, target == const0_rtx);
3886     }
3887 #endif
3888   return NULL_RTX;
3889 }
3890
3891 /* Expand expression EXP, which is a call to the strncmp builtin. Return
3892    NULL_RTX if we failed the caller should emit a normal call, otherwise try to get
3893    the result in TARGET, if convenient.  */
3894
3895 static rtx
3896 expand_builtin_strncmp (tree exp, ATTRIBUTE_UNUSED rtx target,
3897                         ATTRIBUTE_UNUSED enum machine_mode mode)
3898 {
3899   location_t loc ATTRIBUTE_UNUSED = EXPR_LOCATION (exp);
3900
3901   if (!validate_arglist (exp,
3902                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3903     return NULL_RTX;
3904
3905   /* If c_strlen can determine an expression for one of the string
3906      lengths, and it doesn't have side effects, then emit cmpstrnsi
3907      using length MIN(strlen(string)+1, arg3).  */
3908 #ifdef HAVE_cmpstrnsi
3909   if (HAVE_cmpstrnsi)
3910   {
3911     tree len, len1, len2;
3912     rtx arg1_rtx, arg2_rtx, arg3_rtx;
3913     rtx result, insn;
3914     tree fndecl, fn;
3915     tree arg1 = CALL_EXPR_ARG (exp, 0);
3916     tree arg2 = CALL_EXPR_ARG (exp, 1);
3917     tree arg3 = CALL_EXPR_ARG (exp, 2);
3918
3919     unsigned int arg1_align = get_pointer_alignment (arg1) / BITS_PER_UNIT;
3920     unsigned int arg2_align = get_pointer_alignment (arg2) / BITS_PER_UNIT;
3921     enum machine_mode insn_mode
3922       = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
3923
3924     len1 = c_strlen (arg1, 1);
3925     len2 = c_strlen (arg2, 1);
3926
3927     if (len1)
3928       len1 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len1);
3929     if (len2)
3930       len2 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len2);
3931
3932     /* If we don't have a constant length for the first, use the length
3933        of the second, if we know it.  We don't require a constant for
3934        this case; some cost analysis could be done if both are available
3935        but neither is constant.  For now, assume they're equally cheap,
3936        unless one has side effects.  If both strings have constant lengths,
3937        use the smaller.  */
3938
3939     if (!len1)
3940       len = len2;
3941     else if (!len2)
3942       len = len1;
3943     else if (TREE_SIDE_EFFECTS (len1))
3944       len = len2;
3945     else if (TREE_SIDE_EFFECTS (len2))
3946       len = len1;
3947     else if (TREE_CODE (len1) != INTEGER_CST)
3948       len = len2;
3949     else if (TREE_CODE (len2) != INTEGER_CST)
3950       len = len1;
3951     else if (tree_int_cst_lt (len1, len2))
3952       len = len1;
3953     else
3954       len = len2;
3955
3956     /* If both arguments have side effects, we cannot optimize.  */
3957     if (!len || TREE_SIDE_EFFECTS (len))
3958       return NULL_RTX;
3959
3960     /* The actual new length parameter is MIN(len,arg3).  */
3961     len = fold_build2_loc (loc, MIN_EXPR, TREE_TYPE (len), len,
3962                        fold_convert_loc (loc, TREE_TYPE (len), arg3));
3963
3964     /* If we don't have POINTER_TYPE, call the function.  */
3965     if (arg1_align == 0 || arg2_align == 0)
3966       return NULL_RTX;
3967
3968     /* Make a place to write the result of the instruction.  */
3969     result = target;
3970     if (! (result != 0
3971            && REG_P (result) && GET_MODE (result) == insn_mode
3972            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3973       result = gen_reg_rtx (insn_mode);
3974
3975     /* Stabilize the arguments in case gen_cmpstrnsi fails.  */
3976     arg1 = builtin_save_expr (arg1);
3977     arg2 = builtin_save_expr (arg2);
3978     len = builtin_save_expr (len);
3979
3980     arg1_rtx = get_memory_rtx (arg1, len);
3981     arg2_rtx = get_memory_rtx (arg2, len);
3982     arg3_rtx = expand_normal (len);
3983     insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3984                           GEN_INT (MIN (arg1_align, arg2_align)));
3985     if (insn)
3986       {
3987         emit_insn (insn);
3988
3989         /* Return the value in the proper mode for this function.  */
3990         mode = TYPE_MODE (TREE_TYPE (exp));
3991         if (GET_MODE (result) == mode)
3992           return result;
3993         if (target == 0)
3994           return convert_to_mode (mode, result, 0);
3995         convert_move (target, result, 0);
3996         return target;
3997       }
3998
3999     /* Expand the library call ourselves using a stabilized argument
4000        list to avoid re-evaluating the function's arguments twice.  */
4001     fndecl = get_callee_fndecl (exp);
4002     fn = build_call_nofold_loc (EXPR_LOCATION (exp), fndecl, 3,
4003                                 arg1, arg2, len);
4004     gcc_assert (TREE_CODE (fn) == CALL_EXPR);
4005     CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
4006     return expand_call (fn, target, target == const0_rtx);
4007   }
4008 #endif
4009   return NULL_RTX;
4010 }
4011
4012 /* Expand a call to __builtin_saveregs, generating the result in TARGET,
4013    if that's convenient.  */
4014
4015 rtx
4016 expand_builtin_saveregs (void)
4017 {
4018   rtx val, seq;
4019
4020   /* Don't do __builtin_saveregs more than once in a function.
4021      Save the result of the first call and reuse it.  */
4022   if (saveregs_value != 0)
4023     return saveregs_value;
4024
4025   /* When this function is called, it means that registers must be
4026      saved on entry to this function.  So we migrate the call to the
4027      first insn of this function.  */
4028
4029   start_sequence ();
4030
4031   /* Do whatever the machine needs done in this case.  */
4032   val = targetm.calls.expand_builtin_saveregs ();
4033
4034   seq = get_insns ();
4035   end_sequence ();
4036
4037   saveregs_value = val;
4038
4039   /* Put the insns after the NOTE that starts the function.  If this
4040      is inside a start_sequence, make the outer-level insn chain current, so
4041      the code is placed at the start of the function.  */
4042   push_topmost_sequence ();
4043   emit_insn_after (seq, entry_of_function ());
4044   pop_topmost_sequence ();
4045
4046   return val;
4047 }
4048
4049 /* Expand a call to __builtin_next_arg.  */
4050
4051 static rtx
4052 expand_builtin_next_arg (void)
4053 {
4054   /* Checking arguments is already done in fold_builtin_next_arg
4055      that must be called before this function.  */
4056   return expand_binop (ptr_mode, add_optab,
4057                        crtl->args.internal_arg_pointer,
4058                        crtl->args.arg_offset_rtx,
4059                        NULL_RTX, 0, OPTAB_LIB_WIDEN);
4060 }
4061
4062 /* Make it easier for the backends by protecting the valist argument
4063    from multiple evaluations.  */
4064
4065 static tree
4066 stabilize_va_list_loc (location_t loc, tree valist, int needs_lvalue)
4067 {
4068   tree vatype = targetm.canonical_va_list_type (TREE_TYPE (valist));
4069
4070   /* The current way of determining the type of valist is completely
4071      bogus.  We should have the information on the va builtin instead.  */
4072   if (!vatype)
4073     vatype = targetm.fn_abi_va_list (cfun->decl);
4074
4075   if (TREE_CODE (vatype) == ARRAY_TYPE)
4076     {
4077       if (TREE_SIDE_EFFECTS (valist))
4078         valist = save_expr (valist);
4079
4080       /* For this case, the backends will be expecting a pointer to
4081          vatype, but it's possible we've actually been given an array
4082          (an actual TARGET_CANONICAL_VA_LIST_TYPE (valist)).
4083          So fix it.  */
4084       if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
4085         {
4086           tree p1 = build_pointer_type (TREE_TYPE (vatype));
4087           valist = build_fold_addr_expr_with_type_loc (loc, valist, p1);
4088         }
4089     }
4090   else
4091     {
4092       tree pt = build_pointer_type (vatype);
4093
4094       if (! needs_lvalue)
4095         {
4096           if (! TREE_SIDE_EFFECTS (valist))
4097             return valist;
4098
4099           valist = fold_build1_loc (loc, ADDR_EXPR, pt, valist);
4100           TREE_SIDE_EFFECTS (valist) = 1;
4101         }
4102
4103       if (TREE_SIDE_EFFECTS (valist))
4104         valist = save_expr (valist);
4105       valist = fold_build2_loc (loc, MEM_REF,
4106                                 vatype, valist, build_int_cst (pt, 0));
4107     }
4108
4109   return valist;
4110 }
4111
4112 /* The "standard" definition of va_list is void*.  */
4113
4114 tree
4115 std_build_builtin_va_list (void)
4116 {
4117   return ptr_type_node;
4118 }
4119
4120 /* The "standard" abi va_list is va_list_type_node.  */
4121
4122 tree
4123 std_fn_abi_va_list (tree fndecl ATTRIBUTE_UNUSED)
4124 {
4125   return va_list_type_node;
4126 }
4127
4128 /* The "standard" type of va_list is va_list_type_node.  */
4129
4130 tree
4131 std_canonical_va_list_type (tree type)
4132 {
4133   tree wtype, htype;
4134
4135   if (INDIRECT_REF_P (type))
4136     type = TREE_TYPE (type);
4137   else if (POINTER_TYPE_P (type) && POINTER_TYPE_P (TREE_TYPE(type)))
4138     type = TREE_TYPE (type);
4139   wtype = va_list_type_node;
4140   htype = type;
4141   /* Treat structure va_list types.  */
4142   if (TREE_CODE (wtype) == RECORD_TYPE && POINTER_TYPE_P (htype))
4143     htype = TREE_TYPE (htype);
4144   else if (TREE_CODE (wtype) == ARRAY_TYPE)
4145     {
4146       /* If va_list is an array type, the argument may have decayed
4147          to a pointer type, e.g. by being passed to another function.
4148          In that case, unwrap both types so that we can compare the
4149          underlying records.  */
4150       if (TREE_CODE (htype) == ARRAY_TYPE
4151           || POINTER_TYPE_P (htype))
4152         {
4153           wtype = TREE_TYPE (wtype);
4154           htype = TREE_TYPE (htype);
4155         }
4156     }
4157   if (TYPE_MAIN_VARIANT (wtype) == TYPE_MAIN_VARIANT (htype))
4158     return va_list_type_node;
4159
4160   return NULL_TREE;
4161 }
4162
4163 /* The "standard" implementation of va_start: just assign `nextarg' to
4164    the variable.  */
4165
4166 void
4167 std_expand_builtin_va_start (tree valist, rtx nextarg)
4168 {
4169   rtx va_r = expand_expr (valist, NULL_RTX, VOIDmode, EXPAND_WRITE);
4170   convert_move (va_r, nextarg, 0);
4171 }
4172
4173 /* Expand EXP, a call to __builtin_va_start.  */
4174
4175 static rtx
4176 expand_builtin_va_start (tree exp)
4177 {
4178   rtx nextarg;
4179   tree valist;
4180   location_t loc = EXPR_LOCATION (exp);
4181
4182   if (call_expr_nargs (exp) < 2)
4183     {
4184       error_at (loc, "too few arguments to function %<va_start%>");
4185       return const0_rtx;
4186     }
4187
4188   if (fold_builtin_next_arg (exp, true))
4189     return const0_rtx;
4190
4191   nextarg = expand_builtin_next_arg ();
4192   valist = stabilize_va_list_loc (loc, CALL_EXPR_ARG (exp, 0), 1);
4193
4194   if (targetm.expand_builtin_va_start)
4195     targetm.expand_builtin_va_start (valist, nextarg);
4196   else
4197     std_expand_builtin_va_start (valist, nextarg);
4198
4199   return const0_rtx;
4200 }
4201
4202 /* The "standard" implementation of va_arg: read the value from the
4203    current (padded) address and increment by the (padded) size.  */
4204
4205 tree
4206 std_gimplify_va_arg_expr (tree valist, tree type, gimple_seq *pre_p,
4207                           gimple_seq *post_p)
4208 {
4209   tree addr, t, type_size, rounded_size, valist_tmp;
4210   unsigned HOST_WIDE_INT align, boundary;
4211   bool indirect;
4212
4213 #ifdef ARGS_GROW_DOWNWARD
4214   /* All of the alignment and movement below is for args-grow-up machines.
4215      As of 2004, there are only 3 ARGS_GROW_DOWNWARD targets, and they all
4216      implement their own specialized gimplify_va_arg_expr routines.  */
4217   gcc_unreachable ();
4218 #endif
4219
4220   indirect = pass_by_reference (NULL, TYPE_MODE (type), type, false);
4221   if (indirect)
4222     type = build_pointer_type (type);
4223
4224   align = PARM_BOUNDARY / BITS_PER_UNIT;
4225   boundary = targetm.calls.function_arg_boundary (TYPE_MODE (type), type);
4226
4227   /* When we align parameter on stack for caller, if the parameter
4228      alignment is beyond MAX_SUPPORTED_STACK_ALIGNMENT, it will be
4229      aligned at MAX_SUPPORTED_STACK_ALIGNMENT.  We will match callee
4230      here with caller.  */
4231   if (boundary > MAX_SUPPORTED_STACK_ALIGNMENT)
4232     boundary = MAX_SUPPORTED_STACK_ALIGNMENT;
4233
4234   boundary /= BITS_PER_UNIT;
4235
4236   /* Hoist the valist value into a temporary for the moment.  */
4237   valist_tmp = get_initialized_tmp_var (valist, pre_p, NULL);
4238
4239   /* va_list pointer is aligned to PARM_BOUNDARY.  If argument actually
4240      requires greater alignment, we must perform dynamic alignment.  */
4241   if (boundary > align
4242       && !integer_zerop (TYPE_SIZE (type)))
4243     {
4244       t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
4245                   fold_build_pointer_plus_hwi (valist_tmp, boundary - 1));
4246       gimplify_and_add (t, pre_p);
4247
4248       t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
4249                   fold_build2 (BIT_AND_EXPR, TREE_TYPE (valist),
4250                                valist_tmp,
4251                                build_int_cst (TREE_TYPE (valist), -boundary)));
4252       gimplify_and_add (t, pre_p);
4253     }
4254   else
4255     boundary = align;
4256
4257   /* If the actual alignment is less than the alignment of the type,
4258      adjust the type accordingly so that we don't assume strict alignment
4259      when dereferencing the pointer.  */
4260   boundary *= BITS_PER_UNIT;
4261   if (boundary < TYPE_ALIGN (type))
4262     {
4263       type = build_variant_type_copy (type);
4264       TYPE_ALIGN (type) = boundary;
4265     }
4266
4267   /* Compute the rounded size of the type.  */
4268   type_size = size_in_bytes (type);
4269   rounded_size = round_up (type_size, align);
4270
4271   /* Reduce rounded_size so it's sharable with the postqueue.  */
4272   gimplify_expr (&rounded_size, pre_p, post_p, is_gimple_val, fb_rvalue);
4273
4274   /* Get AP.  */
4275   addr = valist_tmp;
4276   if (PAD_VARARGS_DOWN && !integer_zerop (rounded_size))
4277     {
4278       /* Small args are padded downward.  */
4279       t = fold_build2_loc (input_location, GT_EXPR, sizetype,
4280                        rounded_size, size_int (align));
4281       t = fold_build3 (COND_EXPR, sizetype, t, size_zero_node,
4282                        size_binop (MINUS_EXPR, rounded_size, type_size));
4283       addr = fold_build_pointer_plus (addr, t);
4284     }
4285
4286   /* Compute new value for AP.  */
4287   t = fold_build_pointer_plus (valist_tmp, rounded_size);
4288   t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist, t);
4289   gimplify_and_add (t, pre_p);
4290
4291   addr = fold_convert (build_pointer_type (type), addr);
4292
4293   if (indirect)
4294     addr = build_va_arg_indirect_ref (addr);
4295
4296   return build_va_arg_indirect_ref (addr);
4297 }
4298
4299 /* Build an indirect-ref expression over the given TREE, which represents a
4300    piece of a va_arg() expansion.  */
4301 tree
4302 build_va_arg_indirect_ref (tree addr)
4303 {
4304   addr = build_simple_mem_ref_loc (EXPR_LOCATION (addr), addr);
4305
4306   if (flag_mudflap) /* Don't instrument va_arg INDIRECT_REF.  */
4307     mf_mark (addr);
4308
4309   return addr;
4310 }
4311
4312 /* Return a dummy expression of type TYPE in order to keep going after an
4313    error.  */
4314
4315 static tree
4316 dummy_object (tree type)
4317 {
4318   tree t = build_int_cst (build_pointer_type (type), 0);
4319   return build2 (MEM_REF, type, t, t);
4320 }
4321
4322 /* Gimplify __builtin_va_arg, aka VA_ARG_EXPR, which is not really a
4323    builtin function, but a very special sort of operator.  */
4324
4325 enum gimplify_status
4326 gimplify_va_arg_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p)
4327 {
4328   tree promoted_type, have_va_type;
4329   tree valist = TREE_OPERAND (*expr_p, 0);
4330   tree type = TREE_TYPE (*expr_p);
4331   tree t;
4332   location_t loc = EXPR_LOCATION (*expr_p);
4333
4334   /* Verify that valist is of the proper type.  */
4335   have_va_type = TREE_TYPE (valist);
4336   if (have_va_type == error_mark_node)
4337     return GS_ERROR;
4338   have_va_type = targetm.canonical_va_list_type (have_va_type);
4339
4340   if (have_va_type == NULL_TREE)
4341     {
4342       error_at (loc, "first argument to %<va_arg%> not of type %<va_list%>");
4343       return GS_ERROR;
4344     }
4345
4346   /* Generate a diagnostic for requesting data of a type that cannot
4347      be passed through `...' due to type promotion at the call site.  */
4348   if ((promoted_type = lang_hooks.types.type_promotes_to (type))
4349            != type)
4350     {
4351       static bool gave_help;
4352       bool warned;
4353
4354       /* Unfortunately, this is merely undefined, rather than a constraint
4355          violation, so we cannot make this an error.  If this call is never
4356          executed, the program is still strictly conforming.  */
4357       warned = warning_at (loc, 0,
4358                            "%qT is promoted to %qT when passed through %<...%>",
4359                            type, promoted_type);
4360       if (!gave_help && warned)
4361         {
4362           gave_help = true;
4363           inform (loc, "(so you should pass %qT not %qT to %<va_arg%>)",
4364                   promoted_type, type);
4365         }
4366
4367       /* We can, however, treat "undefined" any way we please.
4368          Call abort to encourage the user to fix the program.  */
4369       if (warned)
4370         inform (loc, "if this code is reached, the program will abort");
4371       /* Before the abort, allow the evaluation of the va_list
4372          expression to exit or longjmp.  */
4373       gimplify_and_add (valist, pre_p);
4374       t = build_call_expr_loc (loc,
4375                                builtin_decl_implicit (BUILT_IN_TRAP), 0);
4376       gimplify_and_add (t, pre_p);
4377
4378       /* This is dead code, but go ahead and finish so that the
4379          mode of the result comes out right.  */
4380       *expr_p = dummy_object (type);
4381       return GS_ALL_DONE;
4382     }
4383   else
4384     {
4385       /* Make it easier for the backends by protecting the valist argument
4386          from multiple evaluations.  */
4387       if (TREE_CODE (have_va_type) == ARRAY_TYPE)
4388         {
4389           /* For this case, the backends will be expecting a pointer to
4390              TREE_TYPE (abi), but it's possible we've
4391              actually been given an array (an actual TARGET_FN_ABI_VA_LIST).
4392              So fix it.  */
4393           if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
4394             {
4395               tree p1 = build_pointer_type (TREE_TYPE (have_va_type));
4396               valist = fold_convert_loc (loc, p1,
4397                                          build_fold_addr_expr_loc (loc, valist));
4398             }
4399
4400           gimplify_expr (&valist, pre_p, post_p, is_gimple_val, fb_rvalue);
4401         }
4402       else
4403         gimplify_expr (&valist, pre_p, post_p, is_gimple_min_lval, fb_lvalue);
4404
4405       if (!targetm.gimplify_va_arg_expr)
4406         /* FIXME: Once most targets are converted we should merely
4407            assert this is non-null.  */
4408         return GS_ALL_DONE;
4409
4410       *expr_p = targetm.gimplify_va_arg_expr (valist, type, pre_p, post_p);
4411       return GS_OK;
4412     }
4413 }
4414
4415 /* Expand EXP, a call to __builtin_va_end.  */
4416
4417 static rtx
4418 expand_builtin_va_end (tree exp)
4419 {
4420   tree valist = CALL_EXPR_ARG (exp, 0);
4421
4422   /* Evaluate for side effects, if needed.  I hate macros that don't
4423      do that.  */
4424   if (TREE_SIDE_EFFECTS (valist))
4425     expand_expr (valist, const0_rtx, VOIDmode, EXPAND_NORMAL);
4426
4427   return const0_rtx;
4428 }
4429
4430 /* Expand EXP, a call to __builtin_va_copy.  We do this as a
4431    builtin rather than just as an assignment in stdarg.h because of the
4432    nastiness of array-type va_list types.  */
4433
4434 static rtx
4435 expand_builtin_va_copy (tree exp)
4436 {
4437   tree dst, src, t;
4438   location_t loc = EXPR_LOCATION (exp);
4439
4440   dst = CALL_EXPR_ARG (exp, 0);
4441   src = CALL_EXPR_ARG (exp, 1);
4442
4443   dst = stabilize_va_list_loc (loc, dst, 1);
4444   src = stabilize_va_list_loc (loc, src, 0);
4445
4446   gcc_assert (cfun != NULL && cfun->decl != NULL_TREE);
4447
4448   if (TREE_CODE (targetm.fn_abi_va_list (cfun->decl)) != ARRAY_TYPE)
4449     {
4450       t = build2 (MODIFY_EXPR, targetm.fn_abi_va_list (cfun->decl), dst, src);
4451       TREE_SIDE_EFFECTS (t) = 1;
4452       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4453     }
4454   else
4455     {
4456       rtx dstb, srcb, size;
4457
4458       /* Evaluate to pointers.  */
4459       dstb = expand_expr (dst, NULL_RTX, Pmode, EXPAND_NORMAL);
4460       srcb = expand_expr (src, NULL_RTX, Pmode, EXPAND_NORMAL);
4461       size = expand_expr (TYPE_SIZE_UNIT (targetm.fn_abi_va_list (cfun->decl)),
4462                   NULL_RTX, VOIDmode, EXPAND_NORMAL);
4463
4464       dstb = convert_memory_address (Pmode, dstb);
4465       srcb = convert_memory_address (Pmode, srcb);
4466
4467       /* "Dereference" to BLKmode memories.  */
4468       dstb = gen_rtx_MEM (BLKmode, dstb);
4469       set_mem_alias_set (dstb, get_alias_set (TREE_TYPE (TREE_TYPE (dst))));
4470       set_mem_align (dstb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4471       srcb = gen_rtx_MEM (BLKmode, srcb);
4472       set_mem_alias_set (srcb, get_alias_set (TREE_TYPE (TREE_TYPE (src))));
4473       set_mem_align (srcb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4474
4475       /* Copy.  */
4476       emit_block_move (dstb, srcb, size, BLOCK_OP_NORMAL);
4477     }
4478
4479   return const0_rtx;
4480 }
4481
4482 /* Expand a call to one of the builtin functions __builtin_frame_address or
4483    __builtin_return_address.  */
4484
4485 static rtx
4486 expand_builtin_frame_address (tree fndecl, tree exp)
4487 {
4488   /* The argument must be a nonnegative integer constant.
4489      It counts the number of frames to scan up the stack.
4490      The value is the return address saved in that frame.  */
4491   if (call_expr_nargs (exp) == 0)
4492     /* Warning about missing arg was already issued.  */
4493     return const0_rtx;
4494   else if (! host_integerp (CALL_EXPR_ARG (exp, 0), 1))
4495     {
4496       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4497         error ("invalid argument to %<__builtin_frame_address%>");
4498       else
4499         error ("invalid argument to %<__builtin_return_address%>");
4500       return const0_rtx;
4501     }
4502   else
4503     {
4504       rtx tem
4505         = expand_builtin_return_addr (DECL_FUNCTION_CODE (fndecl),
4506                                       tree_low_cst (CALL_EXPR_ARG (exp, 0), 1));
4507
4508       /* Some ports cannot access arbitrary stack frames.  */
4509       if (tem == NULL)
4510         {
4511           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4512             warning (0, "unsupported argument to %<__builtin_frame_address%>");
4513           else
4514             warning (0, "unsupported argument to %<__builtin_return_address%>");
4515           return const0_rtx;
4516         }
4517
4518       /* For __builtin_frame_address, return what we've got.  */
4519       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4520         return tem;
4521
4522       if (!REG_P (tem)
4523           && ! CONSTANT_P (tem))
4524         tem = copy_addr_to_reg (tem);
4525       return tem;
4526     }
4527 }
4528
4529 /* Expand EXP, a call to the alloca builtin.  Return NULL_RTX if we
4530    failed and the caller should emit a normal call.  CANNOT_ACCUMULATE
4531    is the same as for allocate_dynamic_stack_space.  */
4532
4533 static rtx
4534 expand_builtin_alloca (tree exp, bool cannot_accumulate)
4535 {
4536   rtx op0;
4537   rtx result;
4538   bool valid_arglist;
4539   unsigned int align;
4540   bool alloca_with_align = (DECL_FUNCTION_CODE (get_callee_fndecl (exp))
4541                             == BUILT_IN_ALLOCA_WITH_ALIGN);
4542
4543   /* Emit normal call if we use mudflap.  */
4544   if (flag_mudflap)
4545     return NULL_RTX;
4546
4547   valid_arglist
4548     = (alloca_with_align
4549        ? validate_arglist (exp, INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE)
4550        : validate_arglist (exp, INTEGER_TYPE, VOID_TYPE));
4551
4552   if (!valid_arglist)
4553     return NULL_RTX;
4554
4555   /* Compute the argument.  */
4556   op0 = expand_normal (CALL_EXPR_ARG (exp, 0));
4557
4558   /* Compute the alignment.  */
4559   align = (alloca_with_align
4560            ? TREE_INT_CST_LOW (CALL_EXPR_ARG (exp, 1))
4561            : BIGGEST_ALIGNMENT);
4562
4563   /* Allocate the desired space.  */
4564   result = allocate_dynamic_stack_space (op0, 0, align, cannot_accumulate);
4565   result = convert_memory_address (ptr_mode, result);
4566
4567   return result;
4568 }
4569
4570 /* Expand a call to bswap builtin in EXP.
4571    Return NULL_RTX if a normal call should be emitted rather than expanding the
4572    function in-line.  If convenient, the result should be placed in TARGET.
4573    SUBTARGET may be used as the target for computing one of EXP's operands.  */
4574
4575 static rtx
4576 expand_builtin_bswap (enum machine_mode target_mode, tree exp, rtx target,
4577                       rtx subtarget)
4578 {
4579   tree arg;
4580   rtx op0;
4581
4582   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4583     return NULL_RTX;
4584
4585   arg = CALL_EXPR_ARG (exp, 0);
4586   op0 = expand_expr (arg,
4587                      subtarget && GET_MODE (subtarget) == target_mode
4588                      ? subtarget : NULL_RTX,
4589                      target_mode, EXPAND_NORMAL);
4590   if (GET_MODE (op0) != target_mode)
4591     op0 = convert_to_mode (target_mode, op0, 1);
4592
4593   target = expand_unop (target_mode, bswap_optab, op0, target, 1);
4594
4595   gcc_assert (target);
4596
4597   return convert_to_mode (target_mode, target, 1);
4598 }
4599
4600 /* Expand a call to a unary builtin in EXP.
4601    Return NULL_RTX if a normal call should be emitted rather than expanding the
4602    function in-line.  If convenient, the result should be placed in TARGET.
4603    SUBTARGET may be used as the target for computing one of EXP's operands.  */
4604
4605 static rtx
4606 expand_builtin_unop (enum machine_mode target_mode, tree exp, rtx target,
4607                      rtx subtarget, optab op_optab)
4608 {
4609   rtx op0;
4610
4611   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4612     return NULL_RTX;
4613
4614   /* Compute the argument.  */
4615   op0 = expand_expr (CALL_EXPR_ARG (exp, 0),
4616                      (subtarget
4617                       && (TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 0)))
4618                           == GET_MODE (subtarget))) ? subtarget : NULL_RTX,
4619                      VOIDmode, EXPAND_NORMAL);
4620   /* Compute op, into TARGET if possible.
4621      Set TARGET to wherever the result comes back.  */
4622   target = expand_unop (TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 0))),
4623                         op_optab, op0, target, op_optab != clrsb_optab);
4624   gcc_assert (target);
4625
4626   return convert_to_mode (target_mode, target, 0);
4627 }
4628
4629 /* Expand a call to __builtin_expect.  We just return our argument
4630    as the builtin_expect semantic should've been already executed by
4631    tree branch prediction pass. */
4632
4633 static rtx
4634 expand_builtin_expect (tree exp, rtx target)
4635 {
4636   tree arg;
4637
4638   if (call_expr_nargs (exp) < 2)
4639     return const0_rtx;
4640   arg = CALL_EXPR_ARG (exp, 0);
4641
4642   target = expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
4643   /* When guessing was done, the hints should be already stripped away.  */
4644   gcc_assert (!flag_guess_branch_prob
4645               || optimize == 0 || seen_error ());
4646   return target;
4647 }
4648
4649 /* Expand a call to __builtin_assume_aligned.  We just return our first
4650    argument as the builtin_assume_aligned semantic should've been already
4651    executed by CCP.  */
4652
4653 static rtx
4654 expand_builtin_assume_aligned (tree exp, rtx target)
4655 {
4656   if (call_expr_nargs (exp) < 2)
4657     return const0_rtx;
4658   target = expand_expr (CALL_EXPR_ARG (exp, 0), target, VOIDmode,
4659                         EXPAND_NORMAL);
4660   gcc_assert (!TREE_SIDE_EFFECTS (CALL_EXPR_ARG (exp, 1))
4661               && (call_expr_nargs (exp) < 3
4662                   || !TREE_SIDE_EFFECTS (CALL_EXPR_ARG (exp, 2))));
4663   return target;
4664 }
4665
4666 void
4667 expand_builtin_trap (void)
4668 {
4669 #ifdef HAVE_trap
4670   if (HAVE_trap)
4671     {
4672       rtx insn = emit_insn (gen_trap ());
4673       /* For trap insns when not accumulating outgoing args force
4674          REG_ARGS_SIZE note to prevent crossjumping of calls with
4675          different args sizes.  */
4676       if (!ACCUMULATE_OUTGOING_ARGS)
4677         add_reg_note (insn, REG_ARGS_SIZE, GEN_INT (stack_pointer_delta));
4678     }
4679   else
4680 #endif
4681     emit_library_call (abort_libfunc, LCT_NORETURN, VOIDmode, 0);
4682   emit_barrier ();
4683 }
4684
4685 /* Expand a call to __builtin_unreachable.  We do nothing except emit
4686    a barrier saying that control flow will not pass here.
4687
4688    It is the responsibility of the program being compiled to ensure
4689    that control flow does never reach __builtin_unreachable.  */
4690 static void
4691 expand_builtin_unreachable (void)
4692 {
4693   emit_barrier ();
4694 }
4695
4696 /* Expand EXP, a call to fabs, fabsf or fabsl.
4697    Return NULL_RTX if a normal call should be emitted rather than expanding
4698    the function inline.  If convenient, the result should be placed
4699    in TARGET.  SUBTARGET may be used as the target for computing
4700    the operand.  */
4701
4702 static rtx
4703 expand_builtin_fabs (tree exp, rtx target, rtx subtarget)
4704 {
4705   enum machine_mode mode;
4706   tree arg;
4707   rtx op0;
4708
4709   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
4710     return NULL_RTX;
4711
4712   arg = CALL_EXPR_ARG (exp, 0);
4713   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
4714   mode = TYPE_MODE (TREE_TYPE (arg));
4715   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
4716   return expand_abs (mode, op0, target, 0, safe_from_p (target, arg, 1));
4717 }
4718
4719 /* Expand EXP, a call to copysign, copysignf, or copysignl.
4720    Return NULL is a normal call should be emitted rather than expanding the
4721    function inline.  If convenient, the result should be placed in TARGET.
4722    SUBTARGET may be used as the target for computing the operand.  */
4723
4724 static rtx
4725 expand_builtin_copysign (tree exp, rtx target, rtx subtarget)
4726 {
4727   rtx op0, op1;
4728   tree arg;
4729
4730   if (!validate_arglist (exp, REAL_TYPE, REAL_TYPE, VOID_TYPE))
4731     return NULL_RTX;
4732
4733   arg = CALL_EXPR_ARG (exp, 0);
4734   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
4735
4736   arg = CALL_EXPR_ARG (exp, 1);
4737   op1 = expand_normal (arg);
4738
4739   return expand_copysign (op0, op1, target);
4740 }
4741
4742 /* Create a new constant string literal and return a char* pointer to it.
4743    The STRING_CST value is the LEN characters at STR.  */
4744 tree
4745 build_string_literal (int len, const char *str)
4746 {
4747   tree t, elem, index, type;
4748
4749   t = build_string (len, str);
4750   elem = build_type_variant (char_type_node, 1, 0);
4751   index = build_index_type (size_int (len - 1));
4752   type = build_array_type (elem, index);
4753   TREE_TYPE (t) = type;
4754   TREE_CONSTANT (t) = 1;
4755   TREE_READONLY (t) = 1;
4756   TREE_STATIC (t) = 1;
4757
4758   type = build_pointer_type (elem);
4759   t = build1 (ADDR_EXPR, type,
4760               build4 (ARRAY_REF, elem,
4761                       t, integer_zero_node, NULL_TREE, NULL_TREE));
4762   return t;
4763 }
4764
4765 /* Expand a call to __builtin___clear_cache.  */
4766
4767 static rtx
4768 expand_builtin___clear_cache (tree exp ATTRIBUTE_UNUSED)
4769 {
4770 #ifndef HAVE_clear_cache
4771 #ifdef CLEAR_INSN_CACHE
4772   /* There is no "clear_cache" insn, and __clear_cache() in libgcc
4773      does something.  Just do the default expansion to a call to
4774      __clear_cache().  */
4775   return NULL_RTX;
4776 #else
4777   /* There is no "clear_cache" insn, and __clear_cache() in libgcc
4778      does nothing.  There is no need to call it.  Do nothing.  */
4779   return const0_rtx;
4780 #endif /* CLEAR_INSN_CACHE */
4781 #else
4782   /* We have a "clear_cache" insn, and it will handle everything.  */
4783   tree begin, end;
4784   rtx begin_rtx, end_rtx;
4785
4786   /* We must not expand to a library call.  If we did, any
4787      fallback library function in libgcc that might contain a call to
4788      __builtin___clear_cache() would recurse infinitely.  */
4789   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
4790     {
4791       error ("both arguments to %<__builtin___clear_cache%> must be pointers");
4792       return const0_rtx;
4793     }
4794
4795   if (HAVE_clear_cache)
4796     {
4797       struct expand_operand ops[2];
4798
4799       begin = CALL_EXPR_ARG (exp, 0);
4800       begin_rtx = expand_expr (begin, NULL_RTX, Pmode, EXPAND_NORMAL);
4801
4802       end = CALL_EXPR_ARG (exp, 1);
4803       end_rtx = expand_expr (end, NULL_RTX, Pmode, EXPAND_NORMAL);
4804
4805       create_address_operand (&ops[0], begin_rtx);
4806       create_address_operand (&ops[1], end_rtx);
4807       if (maybe_expand_insn (CODE_FOR_clear_cache, 2, ops))
4808         return const0_rtx;
4809     }
4810   return const0_rtx;
4811 #endif /* HAVE_clear_cache */
4812 }
4813
4814 /* Given a trampoline address, make sure it satisfies TRAMPOLINE_ALIGNMENT.  */
4815
4816 static rtx
4817 round_trampoline_addr (rtx tramp)
4818 {
4819   rtx temp, addend, mask;
4820
4821   /* If we don't need too much alignment, we'll have been guaranteed
4822      proper alignment by get_trampoline_type.  */
4823   if (TRAMPOLINE_ALIGNMENT <= STACK_BOUNDARY)
4824     return tramp;
4825
4826   /* Round address up to desired boundary.  */
4827   temp = gen_reg_rtx (Pmode);
4828   addend = GEN_INT (TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT - 1);
4829   mask = GEN_INT (-TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT);
4830
4831   temp  = expand_simple_binop (Pmode, PLUS, tramp, addend,
4832                                temp, 0, OPTAB_LIB_WIDEN);
4833   tramp = expand_simple_binop (Pmode, AND, temp, mask,
4834                                temp, 0, OPTAB_LIB_WIDEN);
4835
4836   return tramp;
4837 }
4838
4839 static rtx
4840 expand_builtin_init_trampoline (tree exp, bool onstack)
4841 {
4842   tree t_tramp, t_func, t_chain;
4843   rtx m_tramp, r_tramp, r_chain, tmp;
4844
4845   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE,
4846                          POINTER_TYPE, VOID_TYPE))
4847     return NULL_RTX;
4848
4849   t_tramp = CALL_EXPR_ARG (exp, 0);
4850   t_func = CALL_EXPR_ARG (exp, 1);
4851   t_chain = CALL_EXPR_ARG (exp, 2);
4852
4853   r_tramp = expand_normal (t_tramp);
4854   m_tramp = gen_rtx_MEM (BLKmode, r_tramp);
4855   MEM_NOTRAP_P (m_tramp) = 1;
4856
4857   /* If ONSTACK, the TRAMP argument should be the address of a field
4858      within the local function's FRAME decl.  Either way, let's see if
4859      we can fill in the MEM_ATTRs for this memory.  */
4860   if (TREE_CODE (t_tramp) == ADDR_EXPR)
4861     set_mem_attributes (m_tramp, TREE_OPERAND (t_tramp, 0), true);
4862
4863   /* Creator of a heap trampoline is responsible for making sure the
4864      address is aligned to at least STACK_BOUNDARY.  Normally malloc
4865      will ensure this anyhow.  */
4866   tmp = round_trampoline_addr (r_tramp);
4867   if (tmp != r_tramp)
4868     {
4869       m_tramp = change_address (m_tramp, BLKmode, tmp);
4870       set_mem_align (m_tramp, TRAMPOLINE_ALIGNMENT);
4871       set_mem_size (m_tramp, TRAMPOLINE_SIZE);
4872     }
4873
4874   /* The FUNC argument should be the address of the nested function.
4875      Extract the actual function decl to pass to the hook.  */
4876   gcc_assert (TREE_CODE (t_func) == ADDR_EXPR);
4877   t_func = TREE_OPERAND (t_func, 0);
4878   gcc_assert (TREE_CODE (t_func) == FUNCTION_DECL);
4879
4880   r_chain = expand_normal (t_chain);
4881
4882   /* Generate insns to initialize the trampoline.  */
4883   targetm.calls.trampoline_init (m_tramp, t_func, r_chain);
4884
4885   if (onstack)
4886     {
4887       trampolines_created = 1;
4888
4889       warning_at (DECL_SOURCE_LOCATION (t_func), OPT_Wtrampolines,
4890                   "trampoline generated for nested function %qD", t_func);
4891     }
4892
4893   return const0_rtx;
4894 }
4895
4896 static rtx
4897 expand_builtin_adjust_trampoline (tree exp)
4898 {
4899   rtx tramp;
4900
4901   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
4902     return NULL_RTX;
4903
4904   tramp = expand_normal (CALL_EXPR_ARG (exp, 0));
4905   tramp = round_trampoline_addr (tramp);
4906   if (targetm.calls.trampoline_adjust_address)
4907     tramp = targetm.calls.trampoline_adjust_address (tramp);
4908
4909   return tramp;
4910 }
4911
4912 /* Expand the call EXP to the built-in signbit, signbitf or signbitl
4913    function.  The function first checks whether the back end provides
4914    an insn to implement signbit for the respective mode.  If not, it
4915    checks whether the floating point format of the value is such that
4916    the sign bit can be extracted.  If that is not the case, the
4917    function returns NULL_RTX to indicate that a normal call should be
4918    emitted rather than expanding the function in-line.  EXP is the
4919    expression that is a call to the builtin function; if convenient,
4920    the result should be placed in TARGET.  */
4921 static rtx
4922 expand_builtin_signbit (tree exp, rtx target)
4923 {
4924   const struct real_format *fmt;
4925   enum machine_mode fmode, imode, rmode;
4926   tree arg;
4927   int word, bitpos;
4928   enum insn_code icode;
4929   rtx temp;
4930   location_t loc = EXPR_LOCATION (exp);
4931
4932   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
4933     return NULL_RTX;
4934
4935   arg = CALL_EXPR_ARG (exp, 0);
4936   fmode = TYPE_MODE (TREE_TYPE (arg));
4937   rmode = TYPE_MODE (TREE_TYPE (exp));
4938   fmt = REAL_MODE_FORMAT (fmode);
4939
4940   arg = builtin_save_expr (arg);
4941
4942   /* Expand the argument yielding a RTX expression. */
4943   temp = expand_normal (arg);
4944
4945   /* Check if the back end provides an insn that handles signbit for the
4946      argument's mode. */
4947   icode = optab_handler (signbit_optab, fmode);
4948   if (icode != CODE_FOR_nothing)
4949     {
4950       rtx last = get_last_insn ();
4951       target = gen_reg_rtx (TYPE_MODE (TREE_TYPE (exp)));
4952       if (maybe_emit_unop_insn (icode, target, temp, UNKNOWN))
4953         return target;
4954       delete_insns_since (last);
4955     }
4956
4957   /* For floating point formats without a sign bit, implement signbit
4958      as "ARG < 0.0".  */
4959   bitpos = fmt->signbit_ro;
4960   if (bitpos < 0)
4961   {
4962     /* But we can't do this if the format supports signed zero.  */
4963     if (fmt->has_signed_zero && HONOR_SIGNED_ZEROS (fmode))
4964       return NULL_RTX;
4965
4966     arg = fold_build2_loc (loc, LT_EXPR, TREE_TYPE (exp), arg,
4967                        build_real (TREE_TYPE (arg), dconst0));
4968     return expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
4969   }
4970
4971   if (GET_MODE_SIZE (fmode) <= UNITS_PER_WORD)
4972     {
4973       imode = int_mode_for_mode (fmode);
4974       if (imode == BLKmode)
4975         return NULL_RTX;
4976       temp = gen_lowpart (imode, temp);
4977     }
4978   else
4979     {
4980       imode = word_mode;
4981       /* Handle targets with different FP word orders.  */
4982       if (FLOAT_WORDS_BIG_ENDIAN)
4983         word = (GET_MODE_BITSIZE (fmode) - bitpos) / BITS_PER_WORD;
4984       else
4985         word = bitpos / BITS_PER_WORD;
4986       temp = operand_subword_force (temp, word, fmode);
4987       bitpos = bitpos % BITS_PER_WORD;
4988     }
4989
4990   /* Force the intermediate word_mode (or narrower) result into a
4991      register.  This avoids attempting to create paradoxical SUBREGs
4992      of floating point modes below.  */
4993   temp = force_reg (imode, temp);
4994
4995   /* If the bitpos is within the "result mode" lowpart, the operation
4996      can be implement with a single bitwise AND.  Otherwise, we need
4997      a right shift and an AND.  */
4998
4999   if (bitpos < GET_MODE_BITSIZE (rmode))
5000     {
5001       double_int mask = double_int_zero.set_bit (bitpos);
5002
5003       if (GET_MODE_SIZE (imode) > GET_MODE_SIZE (rmode))
5004         temp = gen_lowpart (rmode, temp);
5005       temp = expand_binop (rmode, and_optab, temp,
5006                            immed_double_int_const (mask, rmode),
5007                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
5008     }
5009   else
5010     {
5011       /* Perform a logical right shift to place the signbit in the least
5012          significant bit, then truncate the result to the desired mode
5013          and mask just this bit.  */
5014       temp = expand_shift (RSHIFT_EXPR, imode, temp, bitpos, NULL_RTX, 1);
5015       temp = gen_lowpart (rmode, temp);
5016       temp = expand_binop (rmode, and_optab, temp, const1_rtx,
5017                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
5018     }
5019
5020   return temp;
5021 }
5022
5023 /* Expand fork or exec calls.  TARGET is the desired target of the
5024    call.  EXP is the call. FN is the
5025    identificator of the actual function.  IGNORE is nonzero if the
5026    value is to be ignored.  */
5027
5028 static rtx
5029 expand_builtin_fork_or_exec (tree fn, tree exp, rtx target, int ignore)
5030 {
5031   tree id, decl;
5032   tree call;
5033
5034   /* If we are not profiling, just call the function.  */
5035   if (!profile_arc_flag)
5036     return NULL_RTX;
5037
5038   /* Otherwise call the wrapper.  This should be equivalent for the rest of
5039      compiler, so the code does not diverge, and the wrapper may run the
5040      code necessary for keeping the profiling sane.  */
5041
5042   switch (DECL_FUNCTION_CODE (fn))
5043     {
5044     case BUILT_IN_FORK:
5045       id = get_identifier ("__gcov_fork");
5046       break;
5047
5048     case BUILT_IN_EXECL:
5049       id = get_identifier ("__gcov_execl");
5050       break;
5051
5052     case BUILT_IN_EXECV:
5053       id = get_identifier ("__gcov_execv");
5054       break;
5055
5056     case BUILT_IN_EXECLP:
5057       id = get_identifier ("__gcov_execlp");
5058       break;
5059
5060     case BUILT_IN_EXECLE:
5061       id = get_identifier ("__gcov_execle");
5062       break;
5063
5064     case BUILT_IN_EXECVP:
5065       id = get_identifier ("__gcov_execvp");
5066       break;
5067
5068     case BUILT_IN_EXECVE:
5069       id = get_identifier ("__gcov_execve");
5070       break;
5071
5072     default:
5073       gcc_unreachable ();
5074     }
5075
5076   decl = build_decl (DECL_SOURCE_LOCATION (fn),
5077                      FUNCTION_DECL, id, TREE_TYPE (fn));
5078   DECL_EXTERNAL (decl) = 1;
5079   TREE_PUBLIC (decl) = 1;
5080   DECL_ARTIFICIAL (decl) = 1;
5081   TREE_NOTHROW (decl) = 1;
5082   DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
5083   DECL_VISIBILITY_SPECIFIED (decl) = 1;
5084   call = rewrite_call_expr (EXPR_LOCATION (exp), exp, 0, decl, 0);
5085   return expand_call (call, target, ignore);
5086  }
5087
5088
5089 \f
5090 /* Reconstitute a mode for a __sync intrinsic operation.  Since the type of
5091    the pointer in these functions is void*, the tree optimizers may remove
5092    casts.  The mode computed in expand_builtin isn't reliable either, due
5093    to __sync_bool_compare_and_swap.
5094
5095    FCODE_DIFF should be fcode - base, where base is the FOO_1 code for the
5096    group of builtins.  This gives us log2 of the mode size.  */
5097
5098 static inline enum machine_mode
5099 get_builtin_sync_mode (int fcode_diff)
5100 {
5101   /* The size is not negotiable, so ask not to get BLKmode in return
5102      if the target indicates that a smaller size would be better.  */
5103   return mode_for_size (BITS_PER_UNIT << fcode_diff, MODE_INT, 0);
5104 }
5105
5106 /* Expand the memory expression LOC and return the appropriate memory operand
5107    for the builtin_sync operations.  */
5108
5109 static rtx
5110 get_builtin_sync_mem (tree loc, enum machine_mode mode)
5111 {
5112   rtx addr, mem;
5113
5114   addr = expand_expr (loc, NULL_RTX, ptr_mode, EXPAND_SUM);
5115   addr = convert_memory_address (Pmode, addr);
5116
5117   /* Note that we explicitly do not want any alias information for this
5118      memory, so that we kill all other live memories.  Otherwise we don't
5119      satisfy the full barrier semantics of the intrinsic.  */
5120   mem = validize_mem (gen_rtx_MEM (mode, addr));
5121
5122   /* The alignment needs to be at least according to that of the mode.  */
5123   set_mem_align (mem, MAX (GET_MODE_ALIGNMENT (mode),
5124                            get_pointer_alignment (loc)));
5125   set_mem_alias_set (mem, ALIAS_SET_MEMORY_BARRIER);
5126   MEM_VOLATILE_P (mem) = 1;
5127
5128   return mem;
5129 }
5130
5131 /* Make sure an argument is in the right mode.
5132    EXP is the tree argument. 
5133    MODE is the mode it should be in.  */
5134
5135 static rtx
5136 expand_expr_force_mode (tree exp, enum machine_mode mode)
5137 {
5138   rtx val;
5139   enum machine_mode old_mode;
5140
5141   val = expand_expr (exp, NULL_RTX, mode, EXPAND_NORMAL);
5142   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5143      of CONST_INTs, where we know the old_mode only from the call argument.  */
5144
5145   old_mode = GET_MODE (val);
5146   if (old_mode == VOIDmode)
5147     old_mode = TYPE_MODE (TREE_TYPE (exp));
5148   val = convert_modes (mode, old_mode, val, 1);
5149   return val;
5150 }
5151
5152
5153 /* Expand the __sync_xxx_and_fetch and __sync_fetch_and_xxx intrinsics.
5154    EXP is the CALL_EXPR.  CODE is the rtx code
5155    that corresponds to the arithmetic or logical operation from the name;
5156    an exception here is that NOT actually means NAND.  TARGET is an optional
5157    place for us to store the results; AFTER is true if this is the
5158    fetch_and_xxx form.  */
5159
5160 static rtx
5161 expand_builtin_sync_operation (enum machine_mode mode, tree exp,
5162                                enum rtx_code code, bool after,
5163                                rtx target)
5164 {
5165   rtx val, mem;
5166   location_t loc = EXPR_LOCATION (exp);
5167
5168   if (code == NOT && warn_sync_nand)
5169     {
5170       tree fndecl = get_callee_fndecl (exp);
5171       enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5172
5173       static bool warned_f_a_n, warned_n_a_f;
5174
5175       switch (fcode)
5176         {
5177         case BUILT_IN_SYNC_FETCH_AND_NAND_1:
5178         case BUILT_IN_SYNC_FETCH_AND_NAND_2:
5179         case BUILT_IN_SYNC_FETCH_AND_NAND_4:
5180         case BUILT_IN_SYNC_FETCH_AND_NAND_8:
5181         case BUILT_IN_SYNC_FETCH_AND_NAND_16:
5182           if (warned_f_a_n)
5183             break;
5184
5185           fndecl = builtin_decl_implicit (BUILT_IN_SYNC_FETCH_AND_NAND_N);
5186           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
5187           warned_f_a_n = true;
5188           break;
5189
5190         case BUILT_IN_SYNC_NAND_AND_FETCH_1:
5191         case BUILT_IN_SYNC_NAND_AND_FETCH_2:
5192         case BUILT_IN_SYNC_NAND_AND_FETCH_4:
5193         case BUILT_IN_SYNC_NAND_AND_FETCH_8:
5194         case BUILT_IN_SYNC_NAND_AND_FETCH_16:
5195           if (warned_n_a_f)
5196             break;
5197
5198          fndecl = builtin_decl_implicit (BUILT_IN_SYNC_NAND_AND_FETCH_N);
5199           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
5200           warned_n_a_f = true;
5201           break;
5202
5203         default:
5204           gcc_unreachable ();
5205         }
5206     }
5207
5208   /* Expand the operands.  */
5209   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5210   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5211
5212   return expand_atomic_fetch_op (target, mem, val, code, MEMMODEL_SEQ_CST,
5213                                  after);
5214 }
5215
5216 /* Expand the __sync_val_compare_and_swap and __sync_bool_compare_and_swap
5217    intrinsics. EXP is the CALL_EXPR.  IS_BOOL is
5218    true if this is the boolean form.  TARGET is a place for us to store the
5219    results; this is NOT optional if IS_BOOL is true.  */
5220
5221 static rtx
5222 expand_builtin_compare_and_swap (enum machine_mode mode, tree exp,
5223                                  bool is_bool, rtx target)
5224 {
5225   rtx old_val, new_val, mem;
5226   rtx *pbool, *poval;
5227
5228   /* Expand the operands.  */
5229   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5230   old_val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5231   new_val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 2), mode);
5232
5233   pbool = poval = NULL;
5234   if (target != const0_rtx)
5235     {
5236       if (is_bool)
5237         pbool = &target;
5238       else
5239         poval = &target;
5240     }
5241   if (!expand_atomic_compare_and_swap (pbool, poval, mem, old_val, new_val,
5242                                        false, MEMMODEL_SEQ_CST,
5243                                        MEMMODEL_SEQ_CST))
5244     return NULL_RTX;
5245
5246   return target;
5247 }
5248
5249 /* Expand the __sync_lock_test_and_set intrinsic.  Note that the most
5250    general form is actually an atomic exchange, and some targets only
5251    support a reduced form with the second argument being a constant 1.
5252    EXP is the CALL_EXPR; TARGET is an optional place for us to store
5253    the results.  */
5254
5255 static rtx
5256 expand_builtin_sync_lock_test_and_set (enum machine_mode mode, tree exp,
5257                                        rtx target)
5258 {
5259   rtx val, mem;
5260
5261   /* Expand the operands.  */
5262   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5263   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5264
5265   return expand_sync_lock_test_and_set (target, mem, val);
5266 }
5267
5268 /* Expand the __sync_lock_release intrinsic.  EXP is the CALL_EXPR.  */
5269
5270 static void
5271 expand_builtin_sync_lock_release (enum machine_mode mode, tree exp)
5272 {
5273   rtx mem;
5274
5275   /* Expand the operands.  */
5276   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5277
5278   expand_atomic_store (mem, const0_rtx, MEMMODEL_RELEASE, true);
5279 }
5280
5281 /* Given an integer representing an ``enum memmodel'', verify its
5282    correctness and return the memory model enum.  */
5283
5284 static enum memmodel
5285 get_memmodel (tree exp)
5286 {
5287   rtx op;
5288   unsigned HOST_WIDE_INT val;
5289
5290   /* If the parameter is not a constant, it's a run time value so we'll just
5291      convert it to MEMMODEL_SEQ_CST to avoid annoying runtime checking.  */
5292   if (TREE_CODE (exp) != INTEGER_CST)
5293     return MEMMODEL_SEQ_CST;
5294
5295   op = expand_normal (exp);
5296
5297   val = INTVAL (op);
5298   if (targetm.memmodel_check)
5299     val = targetm.memmodel_check (val);
5300   else if (val & ~MEMMODEL_MASK)
5301     {
5302       warning (OPT_Winvalid_memory_model,
5303                "Unknown architecture specifier in memory model to builtin.");
5304       return MEMMODEL_SEQ_CST;
5305     }
5306
5307   if ((INTVAL(op) & MEMMODEL_MASK) >= MEMMODEL_LAST)
5308     {
5309       warning (OPT_Winvalid_memory_model,
5310                "invalid memory model argument to builtin");
5311       return MEMMODEL_SEQ_CST;
5312     }
5313
5314   return (enum memmodel) val;
5315 }
5316
5317 /* Expand the __atomic_exchange intrinsic:
5318         TYPE __atomic_exchange (TYPE *object, TYPE desired, enum memmodel)
5319    EXP is the CALL_EXPR.
5320    TARGET is an optional place for us to store the results.  */
5321
5322 static rtx
5323 expand_builtin_atomic_exchange (enum machine_mode mode, tree exp, rtx target)
5324 {
5325   rtx val, mem;
5326   enum memmodel model;
5327
5328   model = get_memmodel (CALL_EXPR_ARG (exp, 2));
5329   if ((model & MEMMODEL_MASK) == MEMMODEL_CONSUME)
5330     {
5331       error ("invalid memory model for %<__atomic_exchange%>");
5332       return NULL_RTX;
5333     }
5334
5335   if (!flag_inline_atomics)
5336     return NULL_RTX;
5337
5338   /* Expand the operands.  */
5339   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5340   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5341
5342   return expand_atomic_exchange (target, mem, val, model);
5343 }
5344
5345 /* Expand the __atomic_compare_exchange intrinsic:
5346         bool __atomic_compare_exchange (TYPE *object, TYPE *expect, 
5347                                         TYPE desired, BOOL weak, 
5348                                         enum memmodel success,
5349                                         enum memmodel failure)
5350    EXP is the CALL_EXPR.
5351    TARGET is an optional place for us to store the results.  */
5352
5353 static rtx
5354 expand_builtin_atomic_compare_exchange (enum machine_mode mode, tree exp, 
5355                                         rtx target)
5356 {
5357   rtx expect, desired, mem, oldval;
5358   enum memmodel success, failure;
5359   tree weak;
5360   bool is_weak;
5361
5362   success = get_memmodel (CALL_EXPR_ARG (exp, 4));
5363   failure = get_memmodel (CALL_EXPR_ARG (exp, 5));
5364
5365   if ((failure & MEMMODEL_MASK) == MEMMODEL_RELEASE
5366       || (failure & MEMMODEL_MASK) == MEMMODEL_ACQ_REL)
5367     {
5368       error ("invalid failure memory model for %<__atomic_compare_exchange%>");
5369       return NULL_RTX;
5370     }
5371
5372   if (failure > success)
5373     {
5374       error ("failure memory model cannot be stronger than success "
5375              "memory model for %<__atomic_compare_exchange%>");
5376       return NULL_RTX;
5377     }
5378   
5379   if (!flag_inline_atomics)
5380     return NULL_RTX;
5381
5382   /* Expand the operands.  */
5383   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5384
5385   expect = expand_normal (CALL_EXPR_ARG (exp, 1));
5386   expect = convert_memory_address (Pmode, expect);
5387   expect = gen_rtx_MEM (mode, expect);
5388   desired = expand_expr_force_mode (CALL_EXPR_ARG (exp, 2), mode);
5389
5390   weak = CALL_EXPR_ARG (exp, 3);
5391   is_weak = false;
5392   if (host_integerp (weak, 0) && tree_low_cst (weak, 0) != 0)
5393     is_weak = true;
5394
5395   oldval = expect;
5396   if (!expand_atomic_compare_and_swap ((target == const0_rtx ? NULL : &target),
5397                                        &oldval, mem, oldval, desired,
5398                                        is_weak, success, failure))
5399     return NULL_RTX;
5400
5401   if (oldval != expect)
5402     emit_move_insn (expect, oldval);
5403
5404   return target;
5405 }
5406
5407 /* Expand the __atomic_load intrinsic:
5408         TYPE __atomic_load (TYPE *object, enum memmodel)
5409    EXP is the CALL_EXPR.
5410    TARGET is an optional place for us to store the results.  */
5411
5412 static rtx
5413 expand_builtin_atomic_load (enum machine_mode mode, tree exp, rtx target)
5414 {
5415   rtx mem;
5416   enum memmodel model;
5417
5418   model = get_memmodel (CALL_EXPR_ARG (exp, 1));
5419   if ((model & MEMMODEL_MASK) == MEMMODEL_RELEASE
5420       || (model & MEMMODEL_MASK) == MEMMODEL_ACQ_REL)
5421     {
5422       error ("invalid memory model for %<__atomic_load%>");
5423       return NULL_RTX;
5424     }
5425
5426   if (!flag_inline_atomics)
5427     return NULL_RTX;
5428
5429   /* Expand the operand.  */
5430   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5431
5432   return expand_atomic_load (target, mem, model);
5433 }
5434
5435
5436 /* Expand the __atomic_store intrinsic:
5437         void __atomic_store (TYPE *object, TYPE desired, enum memmodel)
5438    EXP is the CALL_EXPR.
5439    TARGET is an optional place for us to store the results.  */
5440
5441 static rtx
5442 expand_builtin_atomic_store (enum machine_mode mode, tree exp)
5443 {
5444   rtx mem, val;
5445   enum memmodel model;
5446
5447   model = get_memmodel (CALL_EXPR_ARG (exp, 2));
5448   if ((model & MEMMODEL_MASK) != MEMMODEL_RELAXED
5449       && (model & MEMMODEL_MASK) != MEMMODEL_SEQ_CST
5450       && (model & MEMMODEL_MASK) != MEMMODEL_RELEASE)
5451     {
5452       error ("invalid memory model for %<__atomic_store%>");
5453       return NULL_RTX;
5454     }
5455
5456   if (!flag_inline_atomics)
5457     return NULL_RTX;
5458
5459   /* Expand the operands.  */
5460   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5461   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5462
5463   return expand_atomic_store (mem, val, model, false);
5464 }
5465
5466 /* Expand the __atomic_fetch_XXX intrinsic:
5467         TYPE __atomic_fetch_XXX (TYPE *object, TYPE val, enum memmodel)
5468    EXP is the CALL_EXPR.
5469    TARGET is an optional place for us to store the results.
5470    CODE is the operation, PLUS, MINUS, ADD, XOR, or IOR.
5471    FETCH_AFTER is true if returning the result of the operation.
5472    FETCH_AFTER is false if returning the value before the operation.
5473    IGNORE is true if the result is not used.
5474    EXT_CALL is the correct builtin for an external call if this cannot be
5475    resolved to an instruction sequence.  */
5476
5477 static rtx
5478 expand_builtin_atomic_fetch_op (enum machine_mode mode, tree exp, rtx target,
5479                                 enum rtx_code code, bool fetch_after,
5480                                 bool ignore, enum built_in_function ext_call)
5481 {
5482   rtx val, mem, ret;
5483   enum memmodel model;
5484   tree fndecl;
5485   tree addr;
5486
5487   model = get_memmodel (CALL_EXPR_ARG (exp, 2));
5488
5489   /* Expand the operands.  */
5490   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5491   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5492
5493   /* Only try generating instructions if inlining is turned on.  */
5494   if (flag_inline_atomics)
5495     {
5496       ret = expand_atomic_fetch_op (target, mem, val, code, model, fetch_after);
5497       if (ret)
5498         return ret;
5499     }
5500
5501   /* Return if a different routine isn't needed for the library call.  */
5502   if (ext_call == BUILT_IN_NONE)
5503     return NULL_RTX;
5504
5505   /* Change the call to the specified function.  */
5506   fndecl = get_callee_fndecl (exp);
5507   addr = CALL_EXPR_FN (exp);
5508   STRIP_NOPS (addr);
5509
5510   gcc_assert (TREE_OPERAND (addr, 0) == fndecl);
5511   TREE_OPERAND (addr, 0) = builtin_decl_explicit(ext_call);
5512
5513   /* Expand the call here so we can emit trailing code.  */
5514   ret = expand_call (exp, target, ignore);
5515
5516   /* Replace the original function just in case it matters.  */
5517   TREE_OPERAND (addr, 0) = fndecl;
5518
5519   /* Then issue the arithmetic correction to return the right result.  */
5520   if (!ignore)
5521     {
5522       if (code == NOT)
5523         {
5524           ret = expand_simple_binop (mode, AND, ret, val, NULL_RTX, true,
5525                                      OPTAB_LIB_WIDEN);
5526           ret = expand_simple_unop (mode, NOT, ret, target, true);
5527         }
5528       else
5529         ret = expand_simple_binop (mode, code, ret, val, target, true,
5530                                    OPTAB_LIB_WIDEN);
5531     }
5532   return ret;
5533 }
5534
5535
5536 #ifndef HAVE_atomic_clear
5537 # define HAVE_atomic_clear 0
5538 # define gen_atomic_clear(x,y) (gcc_unreachable (), NULL_RTX)
5539 #endif
5540
5541 /* Expand an atomic clear operation.
5542         void _atomic_clear (BOOL *obj, enum memmodel)
5543    EXP is the call expression.  */
5544
5545 static rtx
5546 expand_builtin_atomic_clear (tree exp) 
5547 {
5548   enum machine_mode mode;
5549   rtx mem, ret;
5550   enum memmodel model;
5551
5552   mode = mode_for_size (BOOL_TYPE_SIZE, MODE_INT, 0);
5553   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5554   model = get_memmodel (CALL_EXPR_ARG (exp, 1));
5555
5556   if ((model & MEMMODEL_MASK) == MEMMODEL_ACQUIRE
5557       || (model & MEMMODEL_MASK) == MEMMODEL_ACQ_REL)
5558     {
5559       error ("invalid memory model for %<__atomic_store%>");
5560       return const0_rtx;
5561     }
5562
5563   if (HAVE_atomic_clear)
5564     {
5565       emit_insn (gen_atomic_clear (mem, model));
5566       return const0_rtx;
5567     }
5568
5569   /* Try issuing an __atomic_store, and allow fallback to __sync_lock_release.
5570      Failing that, a store is issued by __atomic_store.  The only way this can
5571      fail is if the bool type is larger than a word size.  Unlikely, but
5572      handle it anyway for completeness.  Assume a single threaded model since
5573      there is no atomic support in this case, and no barriers are required.  */
5574   ret = expand_atomic_store (mem, const0_rtx, model, true);
5575   if (!ret)
5576     emit_move_insn (mem, const0_rtx);
5577   return const0_rtx;
5578 }
5579
5580 /* Expand an atomic test_and_set operation.
5581         bool _atomic_test_and_set (BOOL *obj, enum memmodel)
5582    EXP is the call expression.  */
5583
5584 static rtx
5585 expand_builtin_atomic_test_and_set (tree exp, rtx target)
5586 {
5587   rtx mem;
5588   enum memmodel model;
5589   enum machine_mode mode;
5590
5591   mode = mode_for_size (BOOL_TYPE_SIZE, MODE_INT, 0);
5592   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5593   model = get_memmodel (CALL_EXPR_ARG (exp, 1));
5594
5595   return expand_atomic_test_and_set (target, mem, model);
5596 }
5597
5598
5599 /* Return true if (optional) argument ARG1 of size ARG0 is always lock free on
5600    this architecture.  If ARG1 is NULL, use typical alignment for size ARG0.  */
5601
5602 static tree
5603 fold_builtin_atomic_always_lock_free (tree arg0, tree arg1)
5604 {
5605   int size;
5606   enum machine_mode mode;
5607   unsigned int mode_align, type_align;
5608
5609   if (TREE_CODE (arg0) != INTEGER_CST)
5610     return NULL_TREE;
5611
5612   size = INTVAL (expand_normal (arg0)) * BITS_PER_UNIT;
5613   mode = mode_for_size (size, MODE_INT, 0);
5614   mode_align = GET_MODE_ALIGNMENT (mode);
5615
5616   if (TREE_CODE (arg1) == INTEGER_CST && INTVAL (expand_normal (arg1)) == 0)
5617     type_align = mode_align;
5618   else
5619     {
5620       tree ttype = TREE_TYPE (arg1);
5621
5622       /* This function is usually invoked and folded immediately by the front
5623          end before anything else has a chance to look at it.  The pointer
5624          parameter at this point is usually cast to a void *, so check for that
5625          and look past the cast.  */
5626       if (TREE_CODE (arg1) == NOP_EXPR && POINTER_TYPE_P (ttype)
5627           && VOID_TYPE_P (TREE_TYPE (ttype)))
5628         arg1 = TREE_OPERAND (arg1, 0);
5629
5630       ttype = TREE_TYPE (arg1);
5631       gcc_assert (POINTER_TYPE_P (ttype));
5632
5633       /* Get the underlying type of the object.  */
5634       ttype = TREE_TYPE (ttype);
5635       type_align = TYPE_ALIGN (ttype);
5636     }
5637
5638   /* If the object has smaller alignment, the the lock free routines cannot
5639      be used.  */
5640   if (type_align < mode_align)
5641     return boolean_false_node;
5642
5643   /* Check if a compare_and_swap pattern exists for the mode which represents
5644      the required size.  The pattern is not allowed to fail, so the existence
5645      of the pattern indicates support is present.  */
5646   if (can_compare_and_swap_p (mode, true))
5647     return boolean_true_node;
5648   else
5649     return boolean_false_node;
5650 }
5651
5652 /* Return true if the parameters to call EXP represent an object which will
5653    always generate lock free instructions.  The first argument represents the
5654    size of the object, and the second parameter is a pointer to the object 
5655    itself.  If NULL is passed for the object, then the result is based on 
5656    typical alignment for an object of the specified size.  Otherwise return 
5657    false.  */
5658
5659 static rtx
5660 expand_builtin_atomic_always_lock_free (tree exp)
5661 {
5662   tree size;
5663   tree arg0 = CALL_EXPR_ARG (exp, 0);
5664   tree arg1 = CALL_EXPR_ARG (exp, 1);
5665
5666   if (TREE_CODE (arg0) != INTEGER_CST)
5667     {
5668       error ("non-constant argument 1 to __atomic_always_lock_free");
5669       return const0_rtx;
5670     }
5671
5672   size = fold_builtin_atomic_always_lock_free (arg0, arg1);
5673   if (size == boolean_true_node)
5674     return const1_rtx;
5675   return const0_rtx;
5676 }
5677
5678 /* Return a one or zero if it can be determined that object ARG1 of size ARG 
5679    is lock free on this architecture.  */
5680
5681 static tree
5682 fold_builtin_atomic_is_lock_free (tree arg0, tree arg1)
5683 {
5684   if (!flag_inline_atomics)
5685     return NULL_TREE;
5686   
5687   /* If it isn't always lock free, don't generate a result.  */
5688   if (fold_builtin_atomic_always_lock_free (arg0, arg1) == boolean_true_node)
5689     return boolean_true_node;
5690
5691   return NULL_TREE;
5692 }
5693
5694 /* Return true if the parameters to call EXP represent an object which will
5695    always generate lock free instructions.  The first argument represents the
5696    size of the object, and the second parameter is a pointer to the object 
5697    itself.  If NULL is passed for the object, then the result is based on 
5698    typical alignment for an object of the specified size.  Otherwise return 
5699    NULL*/
5700
5701 static rtx
5702 expand_builtin_atomic_is_lock_free (tree exp)
5703 {
5704   tree size;
5705   tree arg0 = CALL_EXPR_ARG (exp, 0);
5706   tree arg1 = CALL_EXPR_ARG (exp, 1);
5707
5708   if (!INTEGRAL_TYPE_P (TREE_TYPE (arg0)))
5709     {
5710       error ("non-integer argument 1 to __atomic_is_lock_free");
5711       return NULL_RTX;
5712     }
5713
5714   if (!flag_inline_atomics)
5715     return NULL_RTX; 
5716
5717   /* If the value is known at compile time, return the RTX for it.  */
5718   size = fold_builtin_atomic_is_lock_free (arg0, arg1);
5719   if (size == boolean_true_node)
5720     return const1_rtx;
5721
5722   return NULL_RTX;
5723 }
5724
5725 /* Expand the __atomic_thread_fence intrinsic:
5726         void __atomic_thread_fence (enum memmodel)
5727    EXP is the CALL_EXPR.  */
5728
5729 static void
5730 expand_builtin_atomic_thread_fence (tree exp)
5731 {
5732   enum memmodel model = get_memmodel (CALL_EXPR_ARG (exp, 0));
5733   expand_mem_thread_fence (model);
5734 }
5735
5736 /* Expand the __atomic_signal_fence intrinsic:
5737         void __atomic_signal_fence (enum memmodel)
5738    EXP is the CALL_EXPR.  */
5739
5740 static void
5741 expand_builtin_atomic_signal_fence (tree exp)
5742 {
5743   enum memmodel model = get_memmodel (CALL_EXPR_ARG (exp, 0));
5744   expand_mem_signal_fence (model);
5745 }
5746
5747 /* Expand the __sync_synchronize intrinsic.  */
5748
5749 static void
5750 expand_builtin_sync_synchronize (void)
5751 {
5752   expand_mem_thread_fence (MEMMODEL_SEQ_CST);
5753 }
5754
5755 static rtx
5756 expand_builtin_thread_pointer (tree exp, rtx target)
5757 {
5758   enum insn_code icode;
5759   if (!validate_arglist (exp, VOID_TYPE))
5760     return const0_rtx;
5761   icode = direct_optab_handler (get_thread_pointer_optab, Pmode);
5762   if (icode != CODE_FOR_nothing)
5763     {
5764       struct expand_operand op;
5765       if (!REG_P (target) || GET_MODE (target) != Pmode)
5766         target = gen_reg_rtx (Pmode);
5767       create_output_operand (&op, target, Pmode);
5768       expand_insn (icode, 1, &op);
5769       return target;
5770     }
5771   error ("__builtin_thread_pointer is not supported on this target");
5772   return const0_rtx;
5773 }
5774
5775 static void
5776 expand_builtin_set_thread_pointer (tree exp)
5777 {
5778   enum insn_code icode;
5779   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
5780     return;
5781   icode = direct_optab_handler (set_thread_pointer_optab, Pmode);
5782   if (icode != CODE_FOR_nothing)
5783     {
5784       struct expand_operand op;
5785       rtx val = expand_expr (CALL_EXPR_ARG (exp, 0), NULL_RTX,
5786                              Pmode, EXPAND_NORMAL);      
5787       create_input_operand (&op, val, Pmode);
5788       expand_insn (icode, 1, &op);
5789       return;
5790     }
5791   error ("__builtin_set_thread_pointer is not supported on this target");
5792 }
5793
5794 \f
5795 /* Expand an expression EXP that calls a built-in function,
5796    with result going to TARGET if that's convenient
5797    (and in mode MODE if that's convenient).
5798    SUBTARGET may be used as the target for computing one of EXP's operands.
5799    IGNORE is nonzero if the value is to be ignored.  */
5800
5801 rtx
5802 expand_builtin (tree exp, rtx target, rtx subtarget, enum machine_mode mode,
5803                 int ignore)
5804 {
5805   tree fndecl = get_callee_fndecl (exp);
5806   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5807   enum machine_mode target_mode = TYPE_MODE (TREE_TYPE (exp));
5808   int flags;
5809
5810   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
5811     return targetm.expand_builtin (exp, target, subtarget, mode, ignore);
5812
5813   /* When not optimizing, generate calls to library functions for a certain
5814      set of builtins.  */
5815   if (!optimize
5816       && !called_as_built_in (fndecl)
5817       && fcode != BUILT_IN_ALLOCA
5818       && fcode != BUILT_IN_ALLOCA_WITH_ALIGN
5819       && fcode != BUILT_IN_FREE)
5820     return expand_call (exp, target, ignore);
5821
5822   /* The built-in function expanders test for target == const0_rtx
5823      to determine whether the function's result will be ignored.  */
5824   if (ignore)
5825     target = const0_rtx;
5826
5827   /* If the result of a pure or const built-in function is ignored, and
5828      none of its arguments are volatile, we can avoid expanding the
5829      built-in call and just evaluate the arguments for side-effects.  */
5830   if (target == const0_rtx
5831       && ((flags = flags_from_decl_or_type (fndecl)) & (ECF_CONST | ECF_PURE))
5832       && !(flags & ECF_LOOPING_CONST_OR_PURE))
5833     {
5834       bool volatilep = false;
5835       tree arg;
5836       call_expr_arg_iterator iter;
5837
5838       FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5839         if (TREE_THIS_VOLATILE (arg))
5840           {
5841             volatilep = true;
5842             break;
5843           }
5844
5845       if (! volatilep)
5846         {
5847           FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5848             expand_expr (arg, const0_rtx, VOIDmode, EXPAND_NORMAL);
5849           return const0_rtx;
5850         }
5851     }
5852
5853   switch (fcode)
5854     {
5855     CASE_FLT_FN (BUILT_IN_FABS):
5856       target = expand_builtin_fabs (exp, target, subtarget);
5857       if (target)
5858         return target;
5859       break;
5860
5861     CASE_FLT_FN (BUILT_IN_COPYSIGN):
5862       target = expand_builtin_copysign (exp, target, subtarget);
5863       if (target)
5864         return target;
5865       break;
5866
5867       /* Just do a normal library call if we were unable to fold
5868          the values.  */
5869     CASE_FLT_FN (BUILT_IN_CABS):
5870       break;
5871
5872     CASE_FLT_FN (BUILT_IN_EXP):
5873     CASE_FLT_FN (BUILT_IN_EXP10):
5874     CASE_FLT_FN (BUILT_IN_POW10):
5875     CASE_FLT_FN (BUILT_IN_EXP2):
5876     CASE_FLT_FN (BUILT_IN_EXPM1):
5877     CASE_FLT_FN (BUILT_IN_LOGB):
5878     CASE_FLT_FN (BUILT_IN_LOG):
5879     CASE_FLT_FN (BUILT_IN_LOG10):
5880     CASE_FLT_FN (BUILT_IN_LOG2):
5881     CASE_FLT_FN (BUILT_IN_LOG1P):
5882     CASE_FLT_FN (BUILT_IN_TAN):
5883     CASE_FLT_FN (BUILT_IN_ASIN):
5884     CASE_FLT_FN (BUILT_IN_ACOS):
5885     CASE_FLT_FN (BUILT_IN_ATAN):
5886     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
5887       /* Treat these like sqrt only if unsafe math optimizations are allowed,
5888          because of possible accuracy problems.  */
5889       if (! flag_unsafe_math_optimizations)
5890         break;
5891     CASE_FLT_FN (BUILT_IN_SQRT):
5892     CASE_FLT_FN (BUILT_IN_FLOOR):
5893     CASE_FLT_FN (BUILT_IN_CEIL):
5894     CASE_FLT_FN (BUILT_IN_TRUNC):
5895     CASE_FLT_FN (BUILT_IN_ROUND):
5896     CASE_FLT_FN (BUILT_IN_NEARBYINT):
5897     CASE_FLT_FN (BUILT_IN_RINT):
5898       target = expand_builtin_mathfn (exp, target, subtarget);
5899       if (target)
5900         return target;
5901       break;
5902
5903     CASE_FLT_FN (BUILT_IN_FMA):
5904       target = expand_builtin_mathfn_ternary (exp, target, subtarget);
5905       if (target)
5906         return target;
5907       break;
5908
5909     CASE_FLT_FN (BUILT_IN_ILOGB):
5910       if (! flag_unsafe_math_optimizations)
5911         break;
5912     CASE_FLT_FN (BUILT_IN_ISINF):
5913     CASE_FLT_FN (BUILT_IN_FINITE):
5914     case BUILT_IN_ISFINITE:
5915     case BUILT_IN_ISNORMAL:
5916       target = expand_builtin_interclass_mathfn (exp, target);
5917       if (target)
5918         return target;
5919       break;
5920
5921     CASE_FLT_FN (BUILT_IN_ICEIL):
5922     CASE_FLT_FN (BUILT_IN_LCEIL):
5923     CASE_FLT_FN (BUILT_IN_LLCEIL):
5924     CASE_FLT_FN (BUILT_IN_LFLOOR):
5925     CASE_FLT_FN (BUILT_IN_IFLOOR):
5926     CASE_FLT_FN (BUILT_IN_LLFLOOR):
5927       target = expand_builtin_int_roundingfn (exp, target);
5928       if (target)
5929         return target;
5930       break;
5931
5932     CASE_FLT_FN (BUILT_IN_IRINT):
5933     CASE_FLT_FN (BUILT_IN_LRINT):
5934     CASE_FLT_FN (BUILT_IN_LLRINT):
5935     CASE_FLT_FN (BUILT_IN_IROUND):
5936     CASE_FLT_FN (BUILT_IN_LROUND):
5937     CASE_FLT_FN (BUILT_IN_LLROUND):
5938       target = expand_builtin_int_roundingfn_2 (exp, target);
5939       if (target)
5940         return target;
5941       break;
5942
5943     CASE_FLT_FN (BUILT_IN_POWI):
5944       target = expand_builtin_powi (exp, target);
5945       if (target)
5946         return target;
5947       break;
5948
5949     CASE_FLT_FN (BUILT_IN_ATAN2):
5950     CASE_FLT_FN (BUILT_IN_LDEXP):
5951     CASE_FLT_FN (BUILT_IN_SCALB):
5952     CASE_FLT_FN (BUILT_IN_SCALBN):
5953     CASE_FLT_FN (BUILT_IN_SCALBLN):
5954       if (! flag_unsafe_math_optimizations)
5955         break;
5956
5957     CASE_FLT_FN (BUILT_IN_FMOD):
5958     CASE_FLT_FN (BUILT_IN_REMAINDER):
5959     CASE_FLT_FN (BUILT_IN_DREM):
5960     CASE_FLT_FN (BUILT_IN_POW):
5961       target = expand_builtin_mathfn_2 (exp, target, subtarget);
5962       if (target)
5963         return target;
5964       break;
5965
5966     CASE_FLT_FN (BUILT_IN_CEXPI):
5967       target = expand_builtin_cexpi (exp, target);
5968       gcc_assert (target);
5969       return target;
5970
5971     CASE_FLT_FN (BUILT_IN_SIN):
5972     CASE_FLT_FN (BUILT_IN_COS):
5973       if (! flag_unsafe_math_optimizations)
5974         break;
5975       target = expand_builtin_mathfn_3 (exp, target, subtarget);
5976       if (target)
5977         return target;
5978       break;
5979
5980     CASE_FLT_FN (BUILT_IN_SINCOS):
5981       if (! flag_unsafe_math_optimizations)
5982         break;
5983       target = expand_builtin_sincos (exp);
5984       if (target)
5985         return target;
5986       break;
5987
5988     case BUILT_IN_APPLY_ARGS:
5989       return expand_builtin_apply_args ();
5990
5991       /* __builtin_apply (FUNCTION, ARGUMENTS, ARGSIZE) invokes
5992          FUNCTION with a copy of the parameters described by
5993          ARGUMENTS, and ARGSIZE.  It returns a block of memory
5994          allocated on the stack into which is stored all the registers
5995          that might possibly be used for returning the result of a
5996          function.  ARGUMENTS is the value returned by
5997          __builtin_apply_args.  ARGSIZE is the number of bytes of
5998          arguments that must be copied.  ??? How should this value be
5999          computed?  We'll also need a safe worst case value for varargs
6000          functions.  */
6001     case BUILT_IN_APPLY:
6002       if (!validate_arglist (exp, POINTER_TYPE,
6003                              POINTER_TYPE, INTEGER_TYPE, VOID_TYPE)
6004           && !validate_arglist (exp, REFERENCE_TYPE,
6005                                 POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
6006         return const0_rtx;
6007       else
6008         {
6009           rtx ops[3];
6010
6011           ops[0] = expand_normal (CALL_EXPR_ARG (exp, 0));
6012           ops[1] = expand_normal (CALL_EXPR_ARG (exp, 1));
6013           ops[2] = expand_normal (CALL_EXPR_ARG (exp, 2));
6014
6015           return expand_builtin_apply (ops[0], ops[1], ops[2]);
6016         }
6017
6018       /* __builtin_return (RESULT) causes the function to return the
6019          value described by RESULT.  RESULT is address of the block of
6020          memory returned by __builtin_apply.  */
6021     case BUILT_IN_RETURN:
6022       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6023         expand_builtin_return (expand_normal (CALL_EXPR_ARG (exp, 0)));
6024       return const0_rtx;
6025
6026     case BUILT_IN_SAVEREGS:
6027       return expand_builtin_saveregs ();
6028
6029     case BUILT_IN_VA_ARG_PACK:
6030       /* All valid uses of __builtin_va_arg_pack () are removed during
6031          inlining.  */
6032       error ("%Kinvalid use of %<__builtin_va_arg_pack ()%>", exp);
6033       return const0_rtx;
6034
6035     case BUILT_IN_VA_ARG_PACK_LEN:
6036       /* All valid uses of __builtin_va_arg_pack_len () are removed during
6037          inlining.  */
6038       error ("%Kinvalid use of %<__builtin_va_arg_pack_len ()%>", exp);
6039       return const0_rtx;
6040
6041       /* Return the address of the first anonymous stack arg.  */
6042     case BUILT_IN_NEXT_ARG:
6043       if (fold_builtin_next_arg (exp, false))
6044         return const0_rtx;
6045       return expand_builtin_next_arg ();
6046
6047     case BUILT_IN_CLEAR_CACHE:
6048       target = expand_builtin___clear_cache (exp);
6049       if (target)
6050         return target;
6051       break;
6052
6053     case BUILT_IN_CLASSIFY_TYPE:
6054       return expand_builtin_classify_type (exp);
6055
6056     case BUILT_IN_CONSTANT_P:
6057       return const0_rtx;
6058
6059     case BUILT_IN_FRAME_ADDRESS:
6060     case BUILT_IN_RETURN_ADDRESS:
6061       return expand_builtin_frame_address (fndecl, exp);
6062
6063     /* Returns the address of the area where the structure is returned.
6064        0 otherwise.  */
6065     case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
6066       if (call_expr_nargs (exp) != 0
6067           || ! AGGREGATE_TYPE_P (TREE_TYPE (TREE_TYPE (current_function_decl)))
6068           || !MEM_P (DECL_RTL (DECL_RESULT (current_function_decl))))
6069         return const0_rtx;
6070       else
6071         return XEXP (DECL_RTL (DECL_RESULT (current_function_decl)), 0);
6072
6073     case BUILT_IN_ALLOCA:
6074     case BUILT_IN_ALLOCA_WITH_ALIGN:
6075       /* If the allocation stems from the declaration of a variable-sized
6076          object, it cannot accumulate.  */
6077       target = expand_builtin_alloca (exp, CALL_ALLOCA_FOR_VAR_P (exp));
6078       if (target)
6079         return target;
6080       break;
6081
6082     case BUILT_IN_STACK_SAVE:
6083       return expand_stack_save ();
6084
6085     case BUILT_IN_STACK_RESTORE:
6086       expand_stack_restore (CALL_EXPR_ARG (exp, 0));
6087       return const0_rtx;
6088
6089     case BUILT_IN_BSWAP16:
6090     case BUILT_IN_BSWAP32:
6091     case BUILT_IN_BSWAP64:
6092       target = expand_builtin_bswap (target_mode, exp, target, subtarget);
6093       if (target)
6094         return target;
6095       break;
6096
6097     CASE_INT_FN (BUILT_IN_FFS):
6098     case BUILT_IN_FFSIMAX:
6099       target = expand_builtin_unop (target_mode, exp, target,
6100                                     subtarget, ffs_optab);
6101       if (target)
6102         return target;
6103       break;
6104
6105     CASE_INT_FN (BUILT_IN_CLZ):
6106     case BUILT_IN_CLZIMAX:
6107       target = expand_builtin_unop (target_mode, exp, target,
6108                                     subtarget, clz_optab);
6109       if (target)
6110         return target;
6111       break;
6112
6113     CASE_INT_FN (BUILT_IN_CTZ):
6114     case BUILT_IN_CTZIMAX:
6115       target = expand_builtin_unop (target_mode, exp, target,
6116                                     subtarget, ctz_optab);
6117       if (target)
6118         return target;
6119       break;
6120
6121     CASE_INT_FN (BUILT_IN_CLRSB):
6122     case BUILT_IN_CLRSBIMAX:
6123       target = expand_builtin_unop (target_mode, exp, target,
6124                                     subtarget, clrsb_optab);
6125       if (target)
6126         return target;
6127       break;
6128
6129     CASE_INT_FN (BUILT_IN_POPCOUNT):
6130     case BUILT_IN_POPCOUNTIMAX:
6131       target = expand_builtin_unop (target_mode, exp, target,
6132                                     subtarget, popcount_optab);
6133       if (target)
6134         return target;
6135       break;
6136
6137     CASE_INT_FN (BUILT_IN_PARITY):
6138     case BUILT_IN_PARITYIMAX:
6139       target = expand_builtin_unop (target_mode, exp, target,
6140                                     subtarget, parity_optab);
6141       if (target)
6142         return target;
6143       break;
6144
6145     case BUILT_IN_STRLEN:
6146       target = expand_builtin_strlen (exp, target, target_mode);
6147       if (target)
6148         return target;
6149       break;
6150
6151     case BUILT_IN_STRCPY:
6152       target = expand_builtin_strcpy (exp, target);
6153       if (target)
6154         return target;
6155       break;
6156
6157     case BUILT_IN_STRNCPY:
6158       target = expand_builtin_strncpy (exp, target);
6159       if (target)
6160         return target;
6161       break;
6162
6163     case BUILT_IN_STPCPY:
6164       target = expand_builtin_stpcpy (exp, target, mode);
6165       if (target)
6166         return target;
6167       break;
6168
6169     case BUILT_IN_MEMCPY:
6170       target = expand_builtin_memcpy (exp, target);
6171       if (target)
6172         return target;
6173       break;
6174
6175     case BUILT_IN_MEMPCPY:
6176       target = expand_builtin_mempcpy (exp, target, mode);
6177       if (target)
6178         return target;
6179       break;
6180
6181     case BUILT_IN_MEMSET:
6182       target = expand_builtin_memset (exp, target, mode);
6183       if (target)
6184         return target;
6185       break;
6186
6187     case BUILT_IN_BZERO:
6188       target = expand_builtin_bzero (exp);
6189       if (target)
6190         return target;
6191       break;
6192
6193     case BUILT_IN_STRCMP:
6194       target = expand_builtin_strcmp (exp, target);
6195       if (target)
6196         return target;
6197       break;
6198
6199     case BUILT_IN_STRNCMP:
6200       target = expand_builtin_strncmp (exp, target, mode);
6201       if (target)
6202         return target;
6203       break;
6204
6205     case BUILT_IN_BCMP:
6206     case BUILT_IN_MEMCMP:
6207       target = expand_builtin_memcmp (exp, target, mode);
6208       if (target)
6209         return target;
6210       break;
6211
6212     case BUILT_IN_SETJMP:
6213       /* This should have been lowered to the builtins below.  */
6214       gcc_unreachable ();
6215
6216     case BUILT_IN_SETJMP_SETUP:
6217       /* __builtin_setjmp_setup is passed a pointer to an array of five words
6218           and the receiver label.  */
6219       if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
6220         {
6221           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
6222                                       VOIDmode, EXPAND_NORMAL);
6223           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 1), 0);
6224           rtx label_r = label_rtx (label);
6225
6226           /* This is copied from the handling of non-local gotos.  */
6227           expand_builtin_setjmp_setup (buf_addr, label_r);
6228           nonlocal_goto_handler_labels
6229             = gen_rtx_EXPR_LIST (VOIDmode, label_r,
6230                                  nonlocal_goto_handler_labels);
6231           /* ??? Do not let expand_label treat us as such since we would
6232              not want to be both on the list of non-local labels and on
6233              the list of forced labels.  */
6234           FORCED_LABEL (label) = 0;
6235           return const0_rtx;
6236         }
6237       break;
6238
6239     case BUILT_IN_SETJMP_DISPATCHER:
6240        /* __builtin_setjmp_dispatcher is passed the dispatcher label.  */
6241       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6242         {
6243           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
6244           rtx label_r = label_rtx (label);
6245
6246           /* Remove the dispatcher label from the list of non-local labels
6247              since the receiver labels have been added to it above.  */
6248           remove_node_from_expr_list (label_r, &nonlocal_goto_handler_labels);
6249           return const0_rtx;
6250         }
6251       break;
6252
6253     case BUILT_IN_SETJMP_RECEIVER:
6254        /* __builtin_setjmp_receiver is passed the receiver label.  */
6255       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6256         {
6257           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
6258           rtx label_r = label_rtx (label);
6259
6260           expand_builtin_setjmp_receiver (label_r);
6261           return const0_rtx;
6262         }
6263       break;
6264
6265       /* __builtin_longjmp is passed a pointer to an array of five words.
6266          It's similar to the C library longjmp function but works with
6267          __builtin_setjmp above.  */
6268     case BUILT_IN_LONGJMP:
6269       if (validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
6270         {
6271           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
6272                                       VOIDmode, EXPAND_NORMAL);
6273           rtx value = expand_normal (CALL_EXPR_ARG (exp, 1));
6274
6275           if (value != const1_rtx)
6276             {
6277               error ("%<__builtin_longjmp%> second argument must be 1");
6278               return const0_rtx;
6279             }
6280
6281           expand_builtin_longjmp (buf_addr, value);
6282           return const0_rtx;
6283         }
6284       break;
6285
6286     case BUILT_IN_NONLOCAL_GOTO:
6287       target = expand_builtin_nonlocal_goto (exp);
6288       if (target)
6289         return target;
6290       break;
6291
6292       /* This updates the setjmp buffer that is its argument with the value
6293          of the current stack pointer.  */
6294     case BUILT_IN_UPDATE_SETJMP_BUF:
6295       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6296         {
6297           rtx buf_addr
6298             = expand_normal (CALL_EXPR_ARG (exp, 0));
6299
6300           expand_builtin_update_setjmp_buf (buf_addr);
6301           return const0_rtx;
6302         }
6303       break;
6304
6305     case BUILT_IN_TRAP:
6306       expand_builtin_trap ();
6307       return const0_rtx;
6308
6309     case BUILT_IN_UNREACHABLE:
6310       expand_builtin_unreachable ();
6311       return const0_rtx;
6312
6313     CASE_FLT_FN (BUILT_IN_SIGNBIT):
6314     case BUILT_IN_SIGNBITD32:
6315     case BUILT_IN_SIGNBITD64:
6316     case BUILT_IN_SIGNBITD128:
6317       target = expand_builtin_signbit (exp, target);
6318       if (target)
6319         return target;
6320       break;
6321
6322       /* Various hooks for the DWARF 2 __throw routine.  */
6323     case BUILT_IN_UNWIND_INIT:
6324       expand_builtin_unwind_init ();
6325       return const0_rtx;
6326     case BUILT_IN_DWARF_CFA:
6327       return virtual_cfa_rtx;
6328 #ifdef DWARF2_UNWIND_INFO
6329     case BUILT_IN_DWARF_SP_COLUMN:
6330       return expand_builtin_dwarf_sp_column ();
6331     case BUILT_IN_INIT_DWARF_REG_SIZES:
6332       expand_builtin_init_dwarf_reg_sizes (CALL_EXPR_ARG (exp, 0));
6333       return const0_rtx;
6334 #endif
6335     case BUILT_IN_FROB_RETURN_ADDR:
6336       return expand_builtin_frob_return_addr (CALL_EXPR_ARG (exp, 0));
6337     case BUILT_IN_EXTRACT_RETURN_ADDR:
6338       return expand_builtin_extract_return_addr (CALL_EXPR_ARG (exp, 0));
6339     case BUILT_IN_EH_RETURN:
6340       expand_builtin_eh_return (CALL_EXPR_ARG (exp, 0),
6341                                 CALL_EXPR_ARG (exp, 1));
6342       return const0_rtx;
6343 #ifdef EH_RETURN_DATA_REGNO
6344     case BUILT_IN_EH_RETURN_DATA_REGNO:
6345       return expand_builtin_eh_return_data_regno (exp);
6346 #endif
6347     case BUILT_IN_EXTEND_POINTER:
6348       return expand_builtin_extend_pointer (CALL_EXPR_ARG (exp, 0));
6349     case BUILT_IN_EH_POINTER:
6350       return expand_builtin_eh_pointer (exp);
6351     case BUILT_IN_EH_FILTER:
6352       return expand_builtin_eh_filter (exp);
6353     case BUILT_IN_EH_COPY_VALUES:
6354       return expand_builtin_eh_copy_values (exp);
6355
6356     case BUILT_IN_VA_START:
6357       return expand_builtin_va_start (exp);
6358     case BUILT_IN_VA_END:
6359       return expand_builtin_va_end (exp);
6360     case BUILT_IN_VA_COPY:
6361       return expand_builtin_va_copy (exp);
6362     case BUILT_IN_EXPECT:
6363       return expand_builtin_expect (exp, target);
6364     case BUILT_IN_ASSUME_ALIGNED:
6365       return expand_builtin_assume_aligned (exp, target);
6366     case BUILT_IN_PREFETCH:
6367       expand_builtin_prefetch (exp);
6368       return const0_rtx;
6369
6370     case BUILT_IN_INIT_TRAMPOLINE:
6371       return expand_builtin_init_trampoline (exp, true);
6372     case BUILT_IN_INIT_HEAP_TRAMPOLINE:
6373       return expand_builtin_init_trampoline (exp, false);
6374     case BUILT_IN_ADJUST_TRAMPOLINE:
6375       return expand_builtin_adjust_trampoline (exp);
6376
6377     case BUILT_IN_FORK:
6378     case BUILT_IN_EXECL:
6379     case BUILT_IN_EXECV:
6380     case BUILT_IN_EXECLP:
6381     case BUILT_IN_EXECLE:
6382     case BUILT_IN_EXECVP:
6383     case BUILT_IN_EXECVE:
6384       target = expand_builtin_fork_or_exec (fndecl, exp, target, ignore);
6385       if (target)
6386         return target;
6387       break;
6388
6389     case BUILT_IN_SYNC_FETCH_AND_ADD_1:
6390     case BUILT_IN_SYNC_FETCH_AND_ADD_2:
6391     case BUILT_IN_SYNC_FETCH_AND_ADD_4:
6392     case BUILT_IN_SYNC_FETCH_AND_ADD_8:
6393     case BUILT_IN_SYNC_FETCH_AND_ADD_16:
6394       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_ADD_1);
6395       target = expand_builtin_sync_operation (mode, exp, PLUS, false, target);
6396       if (target)
6397         return target;
6398       break;
6399
6400     case BUILT_IN_SYNC_FETCH_AND_SUB_1:
6401     case BUILT_IN_SYNC_FETCH_AND_SUB_2:
6402     case BUILT_IN_SYNC_FETCH_AND_SUB_4:
6403     case BUILT_IN_SYNC_FETCH_AND_SUB_8:
6404     case BUILT_IN_SYNC_FETCH_AND_SUB_16:
6405       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_SUB_1);
6406       target = expand_builtin_sync_operation (mode, exp, MINUS, false, target);
6407       if (target)
6408         return target;
6409       break;
6410
6411     case BUILT_IN_SYNC_FETCH_AND_OR_1:
6412     case BUILT_IN_SYNC_FETCH_AND_OR_2:
6413     case BUILT_IN_SYNC_FETCH_AND_OR_4:
6414     case BUILT_IN_SYNC_FETCH_AND_OR_8:
6415     case BUILT_IN_SYNC_FETCH_AND_OR_16:
6416       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_OR_1);
6417       target = expand_builtin_sync_operation (mode, exp, IOR, false, target);
6418       if (target)
6419         return target;
6420       break;
6421
6422     case BUILT_IN_SYNC_FETCH_AND_AND_1:
6423     case BUILT_IN_SYNC_FETCH_AND_AND_2:
6424     case BUILT_IN_SYNC_FETCH_AND_AND_4:
6425     case BUILT_IN_SYNC_FETCH_AND_AND_8:
6426     case BUILT_IN_SYNC_FETCH_AND_AND_16:
6427       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_AND_1);
6428       target = expand_builtin_sync_operation (mode, exp, AND, false, target);
6429       if (target)
6430         return target;
6431       break;
6432
6433     case BUILT_IN_SYNC_FETCH_AND_XOR_1:
6434     case BUILT_IN_SYNC_FETCH_AND_XOR_2:
6435     case BUILT_IN_SYNC_FETCH_AND_XOR_4:
6436     case BUILT_IN_SYNC_FETCH_AND_XOR_8:
6437     case BUILT_IN_SYNC_FETCH_AND_XOR_16:
6438       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_XOR_1);
6439       target = expand_builtin_sync_operation (mode, exp, XOR, false, target);
6440       if (target)
6441         return target;
6442       break;
6443
6444     case BUILT_IN_SYNC_FETCH_AND_NAND_1:
6445     case BUILT_IN_SYNC_FETCH_AND_NAND_2:
6446     case BUILT_IN_SYNC_FETCH_AND_NAND_4:
6447     case BUILT_IN_SYNC_FETCH_AND_NAND_8:
6448     case BUILT_IN_SYNC_FETCH_AND_NAND_16:
6449       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_NAND_1);
6450       target = expand_builtin_sync_operation (mode, exp, NOT, false, target);
6451       if (target)
6452         return target;
6453       break;
6454
6455     case BUILT_IN_SYNC_ADD_AND_FETCH_1:
6456     case BUILT_IN_SYNC_ADD_AND_FETCH_2:
6457     case BUILT_IN_SYNC_ADD_AND_FETCH_4:
6458     case BUILT_IN_SYNC_ADD_AND_FETCH_8:
6459     case BUILT_IN_SYNC_ADD_AND_FETCH_16:
6460       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_ADD_AND_FETCH_1);
6461       target = expand_builtin_sync_operation (mode, exp, PLUS, true, target);
6462       if (target)
6463         return target;
6464       break;
6465
6466     case BUILT_IN_SYNC_SUB_AND_FETCH_1:
6467     case BUILT_IN_SYNC_SUB_AND_FETCH_2:
6468     case BUILT_IN_SYNC_SUB_AND_FETCH_4:
6469     case BUILT_IN_SYNC_SUB_AND_FETCH_8:
6470     case BUILT_IN_SYNC_SUB_AND_FETCH_16:
6471       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_SUB_AND_FETCH_1);
6472       target = expand_builtin_sync_operation (mode, exp, MINUS, true, target);
6473       if (target)
6474         return target;
6475       break;
6476
6477     case BUILT_IN_SYNC_OR_AND_FETCH_1:
6478     case BUILT_IN_SYNC_OR_AND_FETCH_2:
6479     case BUILT_IN_SYNC_OR_AND_FETCH_4:
6480     case BUILT_IN_SYNC_OR_AND_FETCH_8:
6481     case BUILT_IN_SYNC_OR_AND_FETCH_16:
6482       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_OR_AND_FETCH_1);
6483       target = expand_builtin_sync_operation (mode, exp, IOR, true, target);
6484       if (target)
6485         return target;
6486       break;
6487
6488     case BUILT_IN_SYNC_AND_AND_FETCH_1:
6489     case BUILT_IN_SYNC_AND_AND_FETCH_2:
6490     case BUILT_IN_SYNC_AND_AND_FETCH_4:
6491     case BUILT_IN_SYNC_AND_AND_FETCH_8:
6492     case BUILT_IN_SYNC_AND_AND_FETCH_16:
6493       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_AND_AND_FETCH_1);
6494       target = expand_builtin_sync_operation (mode, exp, AND, true, target);
6495       if (target)
6496         return target;
6497       break;
6498
6499     case BUILT_IN_SYNC_XOR_AND_FETCH_1:
6500     case BUILT_IN_SYNC_XOR_AND_FETCH_2:
6501     case BUILT_IN_SYNC_XOR_AND_FETCH_4:
6502     case BUILT_IN_SYNC_XOR_AND_FETCH_8:
6503     case BUILT_IN_SYNC_XOR_AND_FETCH_16:
6504       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_XOR_AND_FETCH_1);
6505       target = expand_builtin_sync_operation (mode, exp, XOR, true, target);
6506       if (target)
6507         return target;
6508       break;
6509
6510     case BUILT_IN_SYNC_NAND_AND_FETCH_1:
6511     case BUILT_IN_SYNC_NAND_AND_FETCH_2:
6512     case BUILT_IN_SYNC_NAND_AND_FETCH_4:
6513     case BUILT_IN_SYNC_NAND_AND_FETCH_8:
6514     case BUILT_IN_SYNC_NAND_AND_FETCH_16:
6515       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_NAND_AND_FETCH_1);
6516       target = expand_builtin_sync_operation (mode, exp, NOT, true, target);
6517       if (target)
6518         return target;
6519       break;
6520
6521     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1:
6522     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_2:
6523     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_4:
6524     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_8:
6525     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_16:
6526       if (mode == VOIDmode)
6527         mode = TYPE_MODE (boolean_type_node);
6528       if (!target || !register_operand (target, mode))
6529         target = gen_reg_rtx (mode);
6530
6531       mode = get_builtin_sync_mode 
6532                                 (fcode - BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1);
6533       target = expand_builtin_compare_and_swap (mode, exp, true, target);
6534       if (target)
6535         return target;
6536       break;
6537
6538     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_1:
6539     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_2:
6540     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_4:
6541     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_8:
6542     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_16:
6543       mode = get_builtin_sync_mode 
6544                                 (fcode - BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_1);
6545       target = expand_builtin_compare_and_swap (mode, exp, false, target);
6546       if (target)
6547         return target;
6548       break;
6549
6550     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_1:
6551     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_2:
6552     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_4:
6553     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_8:
6554     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_16:
6555       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_LOCK_TEST_AND_SET_1);
6556       target = expand_builtin_sync_lock_test_and_set (mode, exp, target);
6557       if (target)
6558         return target;
6559       break;
6560
6561     case BUILT_IN_SYNC_LOCK_RELEASE_1:
6562     case BUILT_IN_SYNC_LOCK_RELEASE_2:
6563     case BUILT_IN_SYNC_LOCK_RELEASE_4:
6564     case BUILT_IN_SYNC_LOCK_RELEASE_8:
6565     case BUILT_IN_SYNC_LOCK_RELEASE_16:
6566       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_LOCK_RELEASE_1);
6567       expand_builtin_sync_lock_release (mode, exp);
6568       return const0_rtx;
6569
6570     case BUILT_IN_SYNC_SYNCHRONIZE:
6571       expand_builtin_sync_synchronize ();
6572       return const0_rtx;
6573
6574     case BUILT_IN_ATOMIC_EXCHANGE_1:
6575     case BUILT_IN_ATOMIC_EXCHANGE_2:
6576     case BUILT_IN_ATOMIC_EXCHANGE_4:
6577     case BUILT_IN_ATOMIC_EXCHANGE_8:
6578     case BUILT_IN_ATOMIC_EXCHANGE_16:
6579       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_EXCHANGE_1);
6580       target = expand_builtin_atomic_exchange (mode, exp, target);
6581       if (target)
6582         return target;
6583       break;
6584
6585     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1:
6586     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2:
6587     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4:
6588     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8:
6589     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16:
6590       {
6591         unsigned int nargs, z;
6592         vec<tree, va_gc> *vec;
6593
6594         mode = 
6595             get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1);
6596         target = expand_builtin_atomic_compare_exchange (mode, exp, target);
6597         if (target)
6598           return target;
6599
6600         /* If this is turned into an external library call, the weak parameter
6601            must be dropped to match the expected parameter list.  */
6602         nargs = call_expr_nargs (exp);
6603         vec_alloc (vec, nargs - 1);
6604         for (z = 0; z < 3; z++)
6605           vec->quick_push (CALL_EXPR_ARG (exp, z));
6606         /* Skip the boolean weak parameter.  */
6607         for (z = 4; z < 6; z++)
6608           vec->quick_push (CALL_EXPR_ARG (exp, z));
6609         exp = build_call_vec (TREE_TYPE (exp), CALL_EXPR_FN (exp), vec);
6610         break;
6611       }
6612
6613     case BUILT_IN_ATOMIC_LOAD_1:
6614     case BUILT_IN_ATOMIC_LOAD_2:
6615     case BUILT_IN_ATOMIC_LOAD_4:
6616     case BUILT_IN_ATOMIC_LOAD_8:
6617     case BUILT_IN_ATOMIC_LOAD_16:
6618       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_LOAD_1);
6619       target = expand_builtin_atomic_load (mode, exp, target);
6620       if (target)
6621         return target;
6622       break;
6623
6624     case BUILT_IN_ATOMIC_STORE_1:
6625     case BUILT_IN_ATOMIC_STORE_2:
6626     case BUILT_IN_ATOMIC_STORE_4:
6627     case BUILT_IN_ATOMIC_STORE_8:
6628     case BUILT_IN_ATOMIC_STORE_16:
6629       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_STORE_1);
6630       target = expand_builtin_atomic_store (mode, exp);
6631       if (target)
6632         return const0_rtx;
6633       break;
6634
6635     case BUILT_IN_ATOMIC_ADD_FETCH_1:
6636     case BUILT_IN_ATOMIC_ADD_FETCH_2:
6637     case BUILT_IN_ATOMIC_ADD_FETCH_4:
6638     case BUILT_IN_ATOMIC_ADD_FETCH_8:
6639     case BUILT_IN_ATOMIC_ADD_FETCH_16:
6640       {
6641         enum built_in_function lib;
6642         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_ADD_FETCH_1);
6643         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_ADD_1 + 
6644                                        (fcode - BUILT_IN_ATOMIC_ADD_FETCH_1));
6645         target = expand_builtin_atomic_fetch_op (mode, exp, target, PLUS, true,
6646                                                  ignore, lib);
6647         if (target)
6648           return target;
6649         break;
6650       }
6651     case BUILT_IN_ATOMIC_SUB_FETCH_1:
6652     case BUILT_IN_ATOMIC_SUB_FETCH_2:
6653     case BUILT_IN_ATOMIC_SUB_FETCH_4:
6654     case BUILT_IN_ATOMIC_SUB_FETCH_8:
6655     case BUILT_IN_ATOMIC_SUB_FETCH_16:
6656       {
6657         enum built_in_function lib;
6658         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_SUB_FETCH_1);
6659         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_SUB_1 + 
6660                                        (fcode - BUILT_IN_ATOMIC_SUB_FETCH_1));
6661         target = expand_builtin_atomic_fetch_op (mode, exp, target, MINUS, true,
6662                                                  ignore, lib);
6663         if (target)
6664           return target;
6665         break;
6666       }
6667     case BUILT_IN_ATOMIC_AND_FETCH_1:
6668     case BUILT_IN_ATOMIC_AND_FETCH_2:
6669     case BUILT_IN_ATOMIC_AND_FETCH_4:
6670     case BUILT_IN_ATOMIC_AND_FETCH_8:
6671     case BUILT_IN_ATOMIC_AND_FETCH_16:
6672       {
6673         enum built_in_function lib;
6674         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_AND_FETCH_1);
6675         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_AND_1 + 
6676                                        (fcode - BUILT_IN_ATOMIC_AND_FETCH_1));
6677         target = expand_builtin_atomic_fetch_op (mode, exp, target, AND, true,
6678                                                  ignore, lib);
6679         if (target)
6680           return target;
6681         break;
6682       }
6683     case BUILT_IN_ATOMIC_NAND_FETCH_1:
6684     case BUILT_IN_ATOMIC_NAND_FETCH_2:
6685     case BUILT_IN_ATOMIC_NAND_FETCH_4:
6686     case BUILT_IN_ATOMIC_NAND_FETCH_8:
6687     case BUILT_IN_ATOMIC_NAND_FETCH_16:
6688       {
6689         enum built_in_function lib;
6690         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_NAND_FETCH_1);
6691         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_NAND_1 + 
6692                                        (fcode - BUILT_IN_ATOMIC_NAND_FETCH_1));
6693         target = expand_builtin_atomic_fetch_op (mode, exp, target, NOT, true,
6694                                                  ignore, lib);
6695         if (target)
6696           return target;
6697         break;
6698       }
6699     case BUILT_IN_ATOMIC_XOR_FETCH_1:
6700     case BUILT_IN_ATOMIC_XOR_FETCH_2:
6701     case BUILT_IN_ATOMIC_XOR_FETCH_4:
6702     case BUILT_IN_ATOMIC_XOR_FETCH_8:
6703     case BUILT_IN_ATOMIC_XOR_FETCH_16:
6704       {
6705         enum built_in_function lib;
6706         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_XOR_FETCH_1);
6707         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_XOR_1 + 
6708                                        (fcode - BUILT_IN_ATOMIC_XOR_FETCH_1));
6709         target = expand_builtin_atomic_fetch_op (mode, exp, target, XOR, true,
6710                                                  ignore, lib);
6711         if (target)
6712           return target;
6713         break;
6714       }
6715     case BUILT_IN_ATOMIC_OR_FETCH_1:
6716     case BUILT_IN_ATOMIC_OR_FETCH_2:
6717     case BUILT_IN_ATOMIC_OR_FETCH_4:
6718     case BUILT_IN_ATOMIC_OR_FETCH_8:
6719     case BUILT_IN_ATOMIC_OR_FETCH_16:
6720       {
6721         enum built_in_function lib;
6722         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_OR_FETCH_1);
6723         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_OR_1 + 
6724                                        (fcode - BUILT_IN_ATOMIC_OR_FETCH_1));
6725         target = expand_builtin_atomic_fetch_op (mode, exp, target, IOR, true,
6726                                                  ignore, lib);
6727         if (target)
6728           return target;
6729         break;
6730       }
6731     case BUILT_IN_ATOMIC_FETCH_ADD_1:
6732     case BUILT_IN_ATOMIC_FETCH_ADD_2:
6733     case BUILT_IN_ATOMIC_FETCH_ADD_4:
6734     case BUILT_IN_ATOMIC_FETCH_ADD_8:
6735     case BUILT_IN_ATOMIC_FETCH_ADD_16:
6736       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_ADD_1);
6737       target = expand_builtin_atomic_fetch_op (mode, exp, target, PLUS, false,
6738                                                ignore, BUILT_IN_NONE);
6739       if (target)
6740         return target;
6741       break;
6742  
6743     case BUILT_IN_ATOMIC_FETCH_SUB_1:
6744     case BUILT_IN_ATOMIC_FETCH_SUB_2:
6745     case BUILT_IN_ATOMIC_FETCH_SUB_4:
6746     case BUILT_IN_ATOMIC_FETCH_SUB_8:
6747     case BUILT_IN_ATOMIC_FETCH_SUB_16:
6748       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_SUB_1);
6749       target = expand_builtin_atomic_fetch_op (mode, exp, target, MINUS, false,
6750                                                ignore, BUILT_IN_NONE);
6751       if (target)
6752         return target;
6753       break;
6754
6755     case BUILT_IN_ATOMIC_FETCH_AND_1:
6756     case BUILT_IN_ATOMIC_FETCH_AND_2:
6757     case BUILT_IN_ATOMIC_FETCH_AND_4:
6758     case BUILT_IN_ATOMIC_FETCH_AND_8:
6759     case BUILT_IN_ATOMIC_FETCH_AND_16:
6760       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_AND_1);
6761       target = expand_builtin_atomic_fetch_op (mode, exp, target, AND, false,
6762                                                ignore, BUILT_IN_NONE);
6763       if (target)
6764         return target;
6765       break;
6766   
6767     case BUILT_IN_ATOMIC_FETCH_NAND_1:
6768     case BUILT_IN_ATOMIC_FETCH_NAND_2:
6769     case BUILT_IN_ATOMIC_FETCH_NAND_4:
6770     case BUILT_IN_ATOMIC_FETCH_NAND_8:
6771     case BUILT_IN_ATOMIC_FETCH_NAND_16:
6772       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_NAND_1);
6773       target = expand_builtin_atomic_fetch_op (mode, exp, target, NOT, false,
6774                                                ignore, BUILT_IN_NONE);
6775       if (target)
6776         return target;
6777       break;
6778  
6779     case BUILT_IN_ATOMIC_FETCH_XOR_1:
6780     case BUILT_IN_ATOMIC_FETCH_XOR_2:
6781     case BUILT_IN_ATOMIC_FETCH_XOR_4:
6782     case BUILT_IN_ATOMIC_FETCH_XOR_8:
6783     case BUILT_IN_ATOMIC_FETCH_XOR_16:
6784       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_XOR_1);
6785       target = expand_builtin_atomic_fetch_op (mode, exp, target, XOR, false,
6786                                                ignore, BUILT_IN_NONE);
6787       if (target)
6788         return target;
6789       break;
6790  
6791     case BUILT_IN_ATOMIC_FETCH_OR_1:
6792     case BUILT_IN_ATOMIC_FETCH_OR_2:
6793     case BUILT_IN_ATOMIC_FETCH_OR_4:
6794     case BUILT_IN_ATOMIC_FETCH_OR_8:
6795     case BUILT_IN_ATOMIC_FETCH_OR_16:
6796       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_OR_1);
6797       target = expand_builtin_atomic_fetch_op (mode, exp, target, IOR, false,
6798                                                ignore, BUILT_IN_NONE);
6799       if (target)
6800         return target;
6801       break;
6802
6803     case BUILT_IN_ATOMIC_TEST_AND_SET:
6804       return expand_builtin_atomic_test_and_set (exp, target);
6805
6806     case BUILT_IN_ATOMIC_CLEAR:
6807       return expand_builtin_atomic_clear (exp);
6808  
6809     case BUILT_IN_ATOMIC_ALWAYS_LOCK_FREE:
6810       return expand_builtin_atomic_always_lock_free (exp);
6811
6812     case BUILT_IN_ATOMIC_IS_LOCK_FREE:
6813       target = expand_builtin_atomic_is_lock_free (exp);
6814       if (target)
6815         return target;
6816       break;
6817
6818     case BUILT_IN_ATOMIC_THREAD_FENCE:
6819       expand_builtin_atomic_thread_fence (exp);
6820       return const0_rtx;
6821
6822     case BUILT_IN_ATOMIC_SIGNAL_FENCE:
6823       expand_builtin_atomic_signal_fence (exp);
6824       return const0_rtx;
6825
6826     case BUILT_IN_OBJECT_SIZE:
6827       return expand_builtin_object_size (exp);
6828
6829     case BUILT_IN_MEMCPY_CHK:
6830     case BUILT_IN_MEMPCPY_CHK:
6831     case BUILT_IN_MEMMOVE_CHK:
6832     case BUILT_IN_MEMSET_CHK:
6833       target = expand_builtin_memory_chk (exp, target, mode, fcode);
6834       if (target)
6835         return target;
6836       break;
6837
6838     case BUILT_IN_STRCPY_CHK:
6839     case BUILT_IN_STPCPY_CHK:
6840     case BUILT_IN_STRNCPY_CHK:
6841     case BUILT_IN_STPNCPY_CHK:
6842     case BUILT_IN_STRCAT_CHK:
6843     case BUILT_IN_STRNCAT_CHK:
6844     case BUILT_IN_SNPRINTF_CHK:
6845     case BUILT_IN_VSNPRINTF_CHK:
6846       maybe_emit_chk_warning (exp, fcode);
6847       break;
6848
6849     case BUILT_IN_SPRINTF_CHK:
6850     case BUILT_IN_VSPRINTF_CHK:
6851       maybe_emit_sprintf_chk_warning (exp, fcode);
6852       break;
6853
6854     case BUILT_IN_FREE:
6855       if (warn_free_nonheap_object)
6856         maybe_emit_free_warning (exp);
6857       break;
6858
6859     case BUILT_IN_THREAD_POINTER:
6860       return expand_builtin_thread_pointer (exp, target);
6861
6862     case BUILT_IN_SET_THREAD_POINTER:
6863       expand_builtin_set_thread_pointer (exp);
6864       return const0_rtx;
6865
6866     default:    /* just do library call, if unknown builtin */
6867       break;
6868     }
6869
6870   /* The switch statement above can drop through to cause the function
6871      to be called normally.  */
6872   return expand_call (exp, target, ignore);
6873 }
6874
6875 /* Determine whether a tree node represents a call to a built-in
6876    function.  If the tree T is a call to a built-in function with
6877    the right number of arguments of the appropriate types, return
6878    the DECL_FUNCTION_CODE of the call, e.g. BUILT_IN_SQRT.
6879    Otherwise the return value is END_BUILTINS.  */
6880
6881 enum built_in_function
6882 builtin_mathfn_code (const_tree t)
6883 {
6884   const_tree fndecl, arg, parmlist;
6885   const_tree argtype, parmtype;
6886   const_call_expr_arg_iterator iter;
6887
6888   if (TREE_CODE (t) != CALL_EXPR
6889       || TREE_CODE (CALL_EXPR_FN (t)) != ADDR_EXPR)
6890     return END_BUILTINS;
6891
6892   fndecl = get_callee_fndecl (t);
6893   if (fndecl == NULL_TREE
6894       || TREE_CODE (fndecl) != FUNCTION_DECL
6895       || ! DECL_BUILT_IN (fndecl)
6896       || DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
6897     return END_BUILTINS;
6898
6899   parmlist = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
6900   init_const_call_expr_arg_iterator (t, &iter);
6901   for (; parmlist; parmlist = TREE_CHAIN (parmlist))
6902     {
6903       /* If a function doesn't take a variable number of arguments,
6904          the last element in the list will have type `void'.  */
6905       parmtype = TREE_VALUE (parmlist);
6906       if (VOID_TYPE_P (parmtype))
6907         {
6908           if (more_const_call_expr_args_p (&iter))
6909             return END_BUILTINS;
6910           return DECL_FUNCTION_CODE (fndecl);
6911         }
6912
6913       if (! more_const_call_expr_args_p (&iter))
6914         return END_BUILTINS;
6915
6916       arg = next_const_call_expr_arg (&iter);
6917       argtype = TREE_TYPE (arg);
6918
6919       if (SCALAR_FLOAT_TYPE_P (parmtype))
6920         {
6921           if (! SCALAR_FLOAT_TYPE_P (argtype))
6922             return END_BUILTINS;
6923         }
6924       else if (COMPLEX_FLOAT_TYPE_P (parmtype))
6925         {
6926           if (! COMPLEX_FLOAT_TYPE_P (argtype))
6927             return END_BUILTINS;
6928         }
6929       else if (POINTER_TYPE_P (parmtype))
6930         {
6931           if (! POINTER_TYPE_P (argtype))
6932             return END_BUILTINS;
6933         }
6934       else if (INTEGRAL_TYPE_P (parmtype))
6935         {
6936           if (! INTEGRAL_TYPE_P (argtype))
6937             return END_BUILTINS;
6938         }
6939       else
6940         return END_BUILTINS;
6941     }
6942
6943   /* Variable-length argument list.  */
6944   return DECL_FUNCTION_CODE (fndecl);
6945 }
6946
6947 /* Fold a call to __builtin_constant_p, if we know its argument ARG will
6948    evaluate to a constant.  */
6949
6950 static tree
6951 fold_builtin_constant_p (tree arg)
6952 {
6953   /* We return 1 for a numeric type that's known to be a constant
6954      value at compile-time or for an aggregate type that's a
6955      literal constant.  */
6956   STRIP_NOPS (arg);
6957
6958   /* If we know this is a constant, emit the constant of one.  */
6959   if (CONSTANT_CLASS_P (arg)
6960       || (TREE_CODE (arg) == CONSTRUCTOR
6961           && TREE_CONSTANT (arg)))
6962     return integer_one_node;
6963   if (TREE_CODE (arg) == ADDR_EXPR)
6964     {
6965        tree op = TREE_OPERAND (arg, 0);
6966        if (TREE_CODE (op) == STRING_CST
6967            || (TREE_CODE (op) == ARRAY_REF
6968                && integer_zerop (TREE_OPERAND (op, 1))
6969                && TREE_CODE (TREE_OPERAND (op, 0)) == STRING_CST))
6970          return integer_one_node;
6971     }
6972
6973   /* If this expression has side effects, show we don't know it to be a
6974      constant.  Likewise if it's a pointer or aggregate type since in
6975      those case we only want literals, since those are only optimized
6976      when generating RTL, not later.
6977      And finally, if we are compiling an initializer, not code, we
6978      need to return a definite result now; there's not going to be any
6979      more optimization done.  */
6980   if (TREE_SIDE_EFFECTS (arg)
6981       || AGGREGATE_TYPE_P (TREE_TYPE (arg))
6982       || POINTER_TYPE_P (TREE_TYPE (arg))
6983       || cfun == 0
6984       || folding_initializer
6985       || force_folding_builtin_constant_p)
6986     return integer_zero_node;
6987
6988   return NULL_TREE;
6989 }
6990
6991 /* Create builtin_expect with PRED and EXPECTED as its arguments and
6992    return it as a truthvalue.  */
6993
6994 static tree
6995 build_builtin_expect_predicate (location_t loc, tree pred, tree expected)
6996 {
6997   tree fn, arg_types, pred_type, expected_type, call_expr, ret_type;
6998
6999   fn = builtin_decl_explicit (BUILT_IN_EXPECT);
7000   arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
7001   ret_type = TREE_TYPE (TREE_TYPE (fn));
7002   pred_type = TREE_VALUE (arg_types);
7003   expected_type = TREE_VALUE (TREE_CHAIN (arg_types));
7004
7005   pred = fold_convert_loc (loc, pred_type, pred);
7006   expected = fold_convert_loc (loc, expected_type, expected);
7007   call_expr = build_call_expr_loc (loc, fn, 2, pred, expected);
7008
7009   return build2 (NE_EXPR, TREE_TYPE (pred), call_expr,
7010                  build_int_cst (ret_type, 0));
7011 }
7012
7013 /* Fold a call to builtin_expect with arguments ARG0 and ARG1.  Return
7014    NULL_TREE if no simplification is possible.  */
7015
7016 static tree
7017 fold_builtin_expect (location_t loc, tree arg0, tree arg1)
7018 {
7019   tree inner, fndecl, inner_arg0;
7020   enum tree_code code;
7021
7022   /* Distribute the expected value over short-circuiting operators.
7023      See through the cast from truthvalue_type_node to long.  */
7024   inner_arg0 = arg0;
7025   while (TREE_CODE (inner_arg0) == NOP_EXPR
7026          && INTEGRAL_TYPE_P (TREE_TYPE (inner_arg0))
7027          && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (inner_arg0, 0))))
7028     inner_arg0 = TREE_OPERAND (inner_arg0, 0);
7029
7030   /* If this is a builtin_expect within a builtin_expect keep the
7031      inner one.  See through a comparison against a constant.  It
7032      might have been added to create a thruthvalue.  */
7033   inner = inner_arg0;
7034
7035   if (COMPARISON_CLASS_P (inner)
7036       && TREE_CODE (TREE_OPERAND (inner, 1)) == INTEGER_CST)
7037     inner = TREE_OPERAND (inner, 0);
7038
7039   if (TREE_CODE (inner) == CALL_EXPR
7040       && (fndecl = get_callee_fndecl (inner))
7041       && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
7042       && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT)
7043     return arg0;
7044
7045   inner = inner_arg0;
7046   code = TREE_CODE (inner);
7047   if (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR)
7048     {
7049       tree op0 = TREE_OPERAND (inner, 0);
7050       tree op1 = TREE_OPERAND (inner, 1);
7051
7052       op0 = build_builtin_expect_predicate (loc, op0, arg1);
7053       op1 = build_builtin_expect_predicate (loc, op1, arg1);
7054       inner = build2 (code, TREE_TYPE (inner), op0, op1);
7055
7056       return fold_convert_loc (loc, TREE_TYPE (arg0), inner);
7057     }
7058
7059   /* If the argument isn't invariant then there's nothing else we can do.  */
7060   if (!TREE_CONSTANT (inner_arg0))
7061     return NULL_TREE;
7062
7063   /* If we expect that a comparison against the argument will fold to
7064      a constant return the constant.  In practice, this means a true
7065      constant or the address of a non-weak symbol.  */
7066   inner = inner_arg0;
7067   STRIP_NOPS (inner);
7068   if (TREE_CODE (inner) == ADDR_EXPR)
7069     {
7070       do
7071         {
7072           inner = TREE_OPERAND (inner, 0);
7073         }
7074       while (TREE_CODE (inner) == COMPONENT_REF
7075              || TREE_CODE (inner) == ARRAY_REF);
7076       if ((TREE_CODE (inner) == VAR_DECL
7077            || TREE_CODE (inner) == FUNCTION_DECL)
7078           && DECL_WEAK (inner))
7079         return NULL_TREE;
7080     }
7081
7082   /* Otherwise, ARG0 already has the proper type for the return value.  */
7083   return arg0;
7084 }
7085
7086 /* Fold a call to __builtin_classify_type with argument ARG.  */
7087
7088 static tree
7089 fold_builtin_classify_type (tree arg)
7090 {
7091   if (arg == 0)
7092     return build_int_cst (integer_type_node, no_type_class);
7093
7094   return build_int_cst (integer_type_node, type_to_class (TREE_TYPE (arg)));
7095 }
7096
7097 /* Fold a call to __builtin_strlen with argument ARG.  */
7098
7099 static tree
7100 fold_builtin_strlen (location_t loc, tree type, tree arg)
7101 {
7102   if (!validate_arg (arg, POINTER_TYPE))
7103     return NULL_TREE;
7104   else
7105     {
7106       tree len = c_strlen (arg, 0);
7107
7108       if (len)
7109         return fold_convert_loc (loc, type, len);
7110
7111       return NULL_TREE;
7112     }
7113 }
7114
7115 /* Fold a call to __builtin_inf or __builtin_huge_val.  */
7116
7117 static tree
7118 fold_builtin_inf (location_t loc, tree type, int warn)
7119 {
7120   REAL_VALUE_TYPE real;
7121
7122   /* __builtin_inff is intended to be usable to define INFINITY on all
7123      targets.  If an infinity is not available, INFINITY expands "to a
7124      positive constant of type float that overflows at translation
7125      time", footnote "In this case, using INFINITY will violate the
7126      constraint in 6.4.4 and thus require a diagnostic." (C99 7.12#4).
7127      Thus we pedwarn to ensure this constraint violation is
7128      diagnosed.  */
7129   if (!MODE_HAS_INFINITIES (TYPE_MODE (type)) && warn)
7130     pedwarn (loc, 0, "target format does not support infinity");
7131
7132   real_inf (&real);
7133   return build_real (type, real);
7134 }
7135
7136 /* Fold a call to __builtin_nan or __builtin_nans with argument ARG.  */
7137
7138 static tree
7139 fold_builtin_nan (tree arg, tree type, int quiet)
7140 {
7141   REAL_VALUE_TYPE real;
7142   const char *str;
7143
7144   if (!validate_arg (arg, POINTER_TYPE))
7145     return NULL_TREE;
7146   str = c_getstr (arg);
7147   if (!str)
7148     return NULL_TREE;
7149
7150   if (!real_nan (&real, str, quiet, TYPE_MODE (type)))
7151     return NULL_TREE;
7152
7153   return build_real (type, real);
7154 }
7155
7156 /* Return true if the floating point expression T has an integer value.
7157    We also allow +Inf, -Inf and NaN to be considered integer values.  */
7158
7159 static bool
7160 integer_valued_real_p (tree t)
7161 {
7162   switch (TREE_CODE (t))
7163     {
7164     case FLOAT_EXPR:
7165       return true;
7166
7167     case ABS_EXPR:
7168     case SAVE_EXPR:
7169       return integer_valued_real_p (TREE_OPERAND (t, 0));
7170
7171     case COMPOUND_EXPR:
7172     case MODIFY_EXPR:
7173     case BIND_EXPR:
7174       return integer_valued_real_p (TREE_OPERAND (t, 1));
7175
7176     case PLUS_EXPR:
7177     case MINUS_EXPR:
7178     case MULT_EXPR:
7179     case MIN_EXPR:
7180     case MAX_EXPR:
7181       return integer_valued_real_p (TREE_OPERAND (t, 0))
7182              && integer_valued_real_p (TREE_OPERAND (t, 1));
7183
7184     case COND_EXPR:
7185       return integer_valued_real_p (TREE_OPERAND (t, 1))
7186              && integer_valued_real_p (TREE_OPERAND (t, 2));
7187
7188     case REAL_CST:
7189       return real_isinteger (TREE_REAL_CST_PTR (t), TYPE_MODE (TREE_TYPE (t)));
7190
7191     case NOP_EXPR:
7192       {
7193         tree type = TREE_TYPE (TREE_OPERAND (t, 0));
7194         if (TREE_CODE (type) == INTEGER_TYPE)
7195           return true;
7196         if (TREE_CODE (type) == REAL_TYPE)
7197           return integer_valued_real_p (TREE_OPERAND (t, 0));
7198         break;
7199       }
7200
7201     case CALL_EXPR:
7202       switch (builtin_mathfn_code (t))
7203         {
7204         CASE_FLT_FN (BUILT_IN_CEIL):
7205         CASE_FLT_FN (BUILT_IN_FLOOR):
7206         CASE_FLT_FN (BUILT_IN_NEARBYINT):
7207         CASE_FLT_FN (BUILT_IN_RINT):
7208         CASE_FLT_FN (BUILT_IN_ROUND):
7209         CASE_FLT_FN (BUILT_IN_TRUNC):
7210           return true;
7211
7212         CASE_FLT_FN (BUILT_IN_FMIN):
7213         CASE_FLT_FN (BUILT_IN_FMAX):
7214           return integer_valued_real_p (CALL_EXPR_ARG (t, 0))
7215             && integer_valued_real_p (CALL_EXPR_ARG (t, 1));
7216
7217         default:
7218           break;
7219         }
7220       break;
7221
7222     default:
7223       break;
7224     }
7225   return false;
7226 }
7227
7228 /* FNDECL is assumed to be a builtin where truncation can be propagated
7229    across (for instance floor((double)f) == (double)floorf (f).
7230    Do the transformation for a call with argument ARG.  */
7231
7232 static tree
7233 fold_trunc_transparent_mathfn (location_t loc, tree fndecl, tree arg)
7234 {
7235   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
7236
7237   if (!validate_arg (arg, REAL_TYPE))
7238     return NULL_TREE;
7239
7240   /* Integer rounding functions are idempotent.  */
7241   if (fcode == builtin_mathfn_code (arg))
7242     return arg;
7243
7244   /* If argument is already integer valued, and we don't need to worry
7245      about setting errno, there's no need to perform rounding.  */
7246   if (! flag_errno_math && integer_valued_real_p (arg))
7247     return arg;
7248
7249   if (optimize)
7250     {
7251       tree arg0 = strip_float_extensions (arg);
7252       tree ftype = TREE_TYPE (TREE_TYPE (fndecl));
7253       tree newtype = TREE_TYPE (arg0);
7254       tree decl;
7255
7256       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
7257           && (decl = mathfn_built_in (newtype, fcode)))
7258         return fold_convert_loc (loc, ftype,
7259                                  build_call_expr_loc (loc, decl, 1,
7260                                                   fold_convert_loc (loc,
7261                                                                     newtype,
7262                                                                     arg0)));
7263     }
7264   return NULL_TREE;
7265 }
7266
7267 /* FNDECL is assumed to be builtin which can narrow the FP type of
7268    the argument, for instance lround((double)f) -> lroundf (f).
7269    Do the transformation for a call with argument ARG.  */
7270
7271 static tree
7272 fold_fixed_mathfn (location_t loc, tree fndecl, tree arg)
7273 {
7274   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
7275
7276   if (!validate_arg (arg, REAL_TYPE))
7277     return NULL_TREE;
7278
7279   /* If argument is already integer valued, and we don't need to worry
7280      about setting errno, there's no need to perform rounding.  */
7281   if (! flag_errno_math && integer_valued_real_p (arg))
7282     return fold_build1_loc (loc, FIX_TRUNC_EXPR,
7283                         TREE_TYPE (TREE_TYPE (fndecl)), arg);
7284
7285   if (optimize)
7286     {
7287       tree ftype = TREE_TYPE (arg);
7288       tree arg0 = strip_float_extensions (arg);
7289       tree newtype = TREE_TYPE (arg0);
7290       tree decl;
7291
7292       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
7293           && (decl = mathfn_built_in (newtype, fcode)))
7294         return build_call_expr_loc (loc, decl, 1,
7295                                 fold_convert_loc (loc, newtype, arg0));
7296     }
7297
7298   /* Canonicalize iround (x) to lround (x) on ILP32 targets where
7299      sizeof (int) == sizeof (long).  */
7300   if (TYPE_PRECISION (integer_type_node)
7301       == TYPE_PRECISION (long_integer_type_node))
7302     {
7303       tree newfn = NULL_TREE;
7304       switch (fcode)
7305         {
7306         CASE_FLT_FN (BUILT_IN_ICEIL):
7307           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LCEIL);
7308           break;
7309
7310         CASE_FLT_FN (BUILT_IN_IFLOOR):
7311           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LFLOOR);
7312           break;
7313
7314         CASE_FLT_FN (BUILT_IN_IROUND):
7315           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LROUND);
7316           break;
7317
7318         CASE_FLT_FN (BUILT_IN_IRINT):
7319           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LRINT);
7320           break;
7321
7322         default:
7323           break;
7324         }
7325
7326       if (newfn)
7327         {
7328           tree newcall = build_call_expr_loc (loc, newfn, 1, arg);
7329           return fold_convert_loc (loc,
7330                                    TREE_TYPE (TREE_TYPE (fndecl)), newcall);
7331         }
7332     }
7333
7334   /* Canonicalize llround (x) to lround (x) on LP64 targets where
7335      sizeof (long long) == sizeof (long).  */
7336   if (TYPE_PRECISION (long_long_integer_type_node)
7337       == TYPE_PRECISION (long_integer_type_node))
7338     {
7339       tree newfn = NULL_TREE;
7340       switch (fcode)
7341         {
7342         CASE_FLT_FN (BUILT_IN_LLCEIL):
7343           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LCEIL);
7344           break;
7345
7346         CASE_FLT_FN (BUILT_IN_LLFLOOR):
7347           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LFLOOR);
7348           break;
7349
7350         CASE_FLT_FN (BUILT_IN_LLROUND):
7351           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LROUND);
7352           break;
7353
7354         CASE_FLT_FN (BUILT_IN_LLRINT):
7355           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LRINT);
7356           break;
7357
7358         default:
7359           break;
7360         }
7361
7362       if (newfn)
7363         {
7364           tree newcall = build_call_expr_loc (loc, newfn, 1, arg);
7365           return fold_convert_loc (loc,
7366                                    TREE_TYPE (TREE_TYPE (fndecl)), newcall);
7367         }
7368     }
7369
7370   return NULL_TREE;
7371 }
7372
7373 /* Fold call to builtin cabs, cabsf or cabsl with argument ARG.  TYPE is the
7374    return type.  Return NULL_TREE if no simplification can be made.  */
7375
7376 static tree
7377 fold_builtin_cabs (location_t loc, tree arg, tree type, tree fndecl)
7378 {
7379   tree res;
7380
7381   if (!validate_arg (arg, COMPLEX_TYPE)
7382       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) != REAL_TYPE)
7383     return NULL_TREE;
7384
7385   /* Calculate the result when the argument is a constant.  */
7386   if (TREE_CODE (arg) == COMPLEX_CST
7387       && (res = do_mpfr_arg2 (TREE_REALPART (arg), TREE_IMAGPART (arg),
7388                               type, mpfr_hypot)))
7389     return res;
7390
7391   if (TREE_CODE (arg) == COMPLEX_EXPR)
7392     {
7393       tree real = TREE_OPERAND (arg, 0);
7394       tree imag = TREE_OPERAND (arg, 1);
7395
7396       /* If either part is zero, cabs is fabs of the other.  */
7397       if (real_zerop (real))
7398         return fold_build1_loc (loc, ABS_EXPR, type, imag);
7399       if (real_zerop (imag))
7400         return fold_build1_loc (loc, ABS_EXPR, type, real);
7401
7402       /* cabs(x+xi) -> fabs(x)*sqrt(2).  */
7403       if (flag_unsafe_math_optimizations
7404           && operand_equal_p (real, imag, OEP_PURE_SAME))
7405         {
7406           const REAL_VALUE_TYPE sqrt2_trunc
7407             = real_value_truncate (TYPE_MODE (type), dconst_sqrt2 ());
7408           STRIP_NOPS (real);
7409           return fold_build2_loc (loc, MULT_EXPR, type,
7410                               fold_build1_loc (loc, ABS_EXPR, type, real),
7411                               build_real (type, sqrt2_trunc));
7412         }
7413     }
7414
7415   /* Optimize cabs(-z) and cabs(conj(z)) as cabs(z).  */
7416   if (TREE_CODE (arg) == NEGATE_EXPR
7417       || TREE_CODE (arg) == CONJ_EXPR)
7418     return build_call_expr_loc (loc, fndecl, 1, TREE_OPERAND (arg, 0));
7419
7420   /* Don't do this when optimizing for size.  */
7421   if (flag_unsafe_math_optimizations
7422       && optimize && optimize_function_for_speed_p (cfun))
7423     {
7424       tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
7425
7426       if (sqrtfn != NULL_TREE)
7427         {
7428           tree rpart, ipart, result;
7429
7430           arg = builtin_save_expr (arg);
7431
7432           rpart = fold_build1_loc (loc, REALPART_EXPR, type, arg);
7433           ipart = fold_build1_loc (loc, IMAGPART_EXPR, type, arg);
7434
7435           rpart = builtin_save_expr (rpart);
7436           ipart = builtin_save_expr (ipart);
7437
7438           result = fold_build2_loc (loc, PLUS_EXPR, type,
7439                                 fold_build2_loc (loc, MULT_EXPR, type,
7440                                              rpart, rpart),
7441                                 fold_build2_loc (loc, MULT_EXPR, type,
7442                                              ipart, ipart));
7443
7444           return build_call_expr_loc (loc, sqrtfn, 1, result);
7445         }
7446     }
7447
7448   return NULL_TREE;
7449 }
7450
7451 /* Build a complex (inf +- 0i) for the result of cproj.  TYPE is the
7452    complex tree type of the result.  If NEG is true, the imaginary
7453    zero is negative.  */
7454
7455 static tree
7456 build_complex_cproj (tree type, bool neg)
7457 {
7458   REAL_VALUE_TYPE rinf, rzero = dconst0;
7459   
7460   real_inf (&rinf);
7461   rzero.sign = neg;
7462   return build_complex (type, build_real (TREE_TYPE (type), rinf),
7463                         build_real (TREE_TYPE (type), rzero));
7464 }
7465
7466 /* Fold call to builtin cproj, cprojf or cprojl with argument ARG.  TYPE is the
7467    return type.  Return NULL_TREE if no simplification can be made.  */
7468
7469 static tree
7470 fold_builtin_cproj (location_t loc, tree arg, tree type)
7471 {
7472   if (!validate_arg (arg, COMPLEX_TYPE)
7473       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) != REAL_TYPE)
7474     return NULL_TREE;
7475
7476   /* If there are no infinities, return arg.  */
7477   if (! HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (type))))
7478     return non_lvalue_loc (loc, arg);
7479
7480   /* Calculate the result when the argument is a constant.  */
7481   if (TREE_CODE (arg) == COMPLEX_CST)
7482     {
7483       const REAL_VALUE_TYPE *real = TREE_REAL_CST_PTR (TREE_REALPART (arg));
7484       const REAL_VALUE_TYPE *imag = TREE_REAL_CST_PTR (TREE_IMAGPART (arg));
7485       
7486       if (real_isinf (real) || real_isinf (imag))
7487         return build_complex_cproj (type, imag->sign);
7488       else
7489         return arg;
7490     }
7491   else if (TREE_CODE (arg) == COMPLEX_EXPR)
7492     {
7493       tree real = TREE_OPERAND (arg, 0);
7494       tree imag = TREE_OPERAND (arg, 1);
7495
7496       STRIP_NOPS (real);
7497       STRIP_NOPS (imag);
7498       
7499       /* If the real part is inf and the imag part is known to be
7500          nonnegative, return (inf + 0i).  Remember side-effects are
7501          possible in the imag part.  */
7502       if (TREE_CODE (real) == REAL_CST
7503           && real_isinf (TREE_REAL_CST_PTR (real))
7504           && tree_expr_nonnegative_p (imag))
7505         return omit_one_operand_loc (loc, type,
7506                                      build_complex_cproj (type, false),
7507                                      arg);
7508       
7509       /* If the imag part is inf, return (inf+I*copysign(0,imag)).
7510          Remember side-effects are possible in the real part.  */
7511       if (TREE_CODE (imag) == REAL_CST
7512           && real_isinf (TREE_REAL_CST_PTR (imag)))
7513         return
7514           omit_one_operand_loc (loc, type,
7515                                 build_complex_cproj (type, TREE_REAL_CST_PTR
7516                                                      (imag)->sign), arg);
7517     }
7518
7519   return NULL_TREE;
7520 }
7521
7522 /* Fold a builtin function call to sqrt, sqrtf, or sqrtl with argument ARG.
7523    Return NULL_TREE if no simplification can be made.  */
7524
7525 static tree
7526 fold_builtin_sqrt (location_t loc, tree arg, tree type)
7527 {
7528
7529   enum built_in_function fcode;
7530   tree res;
7531
7532   if (!validate_arg (arg, REAL_TYPE))
7533     return NULL_TREE;
7534
7535   /* Calculate the result when the argument is a constant.  */
7536   if ((res = do_mpfr_arg1 (arg, type, mpfr_sqrt, &dconst0, NULL, true)))
7537     return res;
7538
7539   /* Optimize sqrt(expN(x)) = expN(x*0.5).  */
7540   fcode = builtin_mathfn_code (arg);
7541   if (flag_unsafe_math_optimizations && BUILTIN_EXPONENT_P (fcode))
7542     {
7543       tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7544       arg = fold_build2_loc (loc, MULT_EXPR, type,
7545                          CALL_EXPR_ARG (arg, 0),
7546                          build_real (type, dconsthalf));
7547       return build_call_expr_loc (loc, expfn, 1, arg);
7548     }
7549
7550   /* Optimize sqrt(Nroot(x)) -> pow(x,1/(2*N)).  */
7551   if (flag_unsafe_math_optimizations && BUILTIN_ROOT_P (fcode))
7552     {
7553       tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7554
7555       if (powfn)
7556         {
7557           tree arg0 = CALL_EXPR_ARG (arg, 0);
7558           tree tree_root;
7559           /* The inner root was either sqrt or cbrt.  */
7560           /* This was a conditional expression but it triggered a bug
7561              in Sun C 5.5.  */
7562           REAL_VALUE_TYPE dconstroot;
7563           if (BUILTIN_SQRT_P (fcode))
7564             dconstroot = dconsthalf;
7565           else
7566             dconstroot = dconst_third ();
7567
7568           /* Adjust for the outer root.  */
7569           SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
7570           dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7571           tree_root = build_real (type, dconstroot);
7572           return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7573         }
7574     }
7575
7576   /* Optimize sqrt(pow(x,y)) = pow(|x|,y*0.5).  */
7577   if (flag_unsafe_math_optimizations
7578       && (fcode == BUILT_IN_POW
7579           || fcode == BUILT_IN_POWF
7580           || fcode == BUILT_IN_POWL))
7581     {
7582       tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7583       tree arg0 = CALL_EXPR_ARG (arg, 0);
7584       tree arg1 = CALL_EXPR_ARG (arg, 1);
7585       tree narg1;
7586       if (!tree_expr_nonnegative_p (arg0))
7587         arg0 = build1 (ABS_EXPR, type, arg0);
7588       narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
7589                            build_real (type, dconsthalf));
7590       return build_call_expr_loc (loc, powfn, 2, arg0, narg1);
7591     }
7592
7593   return NULL_TREE;
7594 }
7595
7596 /* Fold a builtin function call to cbrt, cbrtf, or cbrtl with argument ARG.
7597    Return NULL_TREE if no simplification can be made.  */
7598
7599 static tree
7600 fold_builtin_cbrt (location_t loc, tree arg, tree type)
7601 {
7602   const enum built_in_function fcode = builtin_mathfn_code (arg);
7603   tree res;
7604
7605   if (!validate_arg (arg, REAL_TYPE))
7606     return NULL_TREE;
7607
7608   /* Calculate the result when the argument is a constant.  */
7609   if ((res = do_mpfr_arg1 (arg, type, mpfr_cbrt, NULL, NULL, 0)))
7610     return res;
7611
7612   if (flag_unsafe_math_optimizations)
7613     {
7614       /* Optimize cbrt(expN(x)) -> expN(x/3).  */
7615       if (BUILTIN_EXPONENT_P (fcode))
7616         {
7617           tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7618           const REAL_VALUE_TYPE third_trunc =
7619             real_value_truncate (TYPE_MODE (type), dconst_third ());
7620           arg = fold_build2_loc (loc, MULT_EXPR, type,
7621                              CALL_EXPR_ARG (arg, 0),
7622                              build_real (type, third_trunc));
7623           return build_call_expr_loc (loc, expfn, 1, arg);
7624         }
7625
7626       /* Optimize cbrt(sqrt(x)) -> pow(x,1/6).  */
7627       if (BUILTIN_SQRT_P (fcode))
7628         {
7629           tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7630
7631           if (powfn)
7632             {
7633               tree arg0 = CALL_EXPR_ARG (arg, 0);
7634               tree tree_root;
7635               REAL_VALUE_TYPE dconstroot = dconst_third ();
7636
7637               SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
7638               dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7639               tree_root = build_real (type, dconstroot);
7640               return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7641             }
7642         }
7643
7644       /* Optimize cbrt(cbrt(x)) -> pow(x,1/9) iff x is nonnegative.  */
7645       if (BUILTIN_CBRT_P (fcode))
7646         {
7647           tree arg0 = CALL_EXPR_ARG (arg, 0);
7648           if (tree_expr_nonnegative_p (arg0))
7649             {
7650               tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7651
7652               if (powfn)
7653                 {
7654                   tree tree_root;
7655                   REAL_VALUE_TYPE dconstroot;
7656
7657                   real_arithmetic (&dconstroot, MULT_EXPR,
7658                                    dconst_third_ptr (), dconst_third_ptr ());
7659                   dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7660                   tree_root = build_real (type, dconstroot);
7661                   return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7662                 }
7663             }
7664         }
7665
7666       /* Optimize cbrt(pow(x,y)) -> pow(x,y/3) iff x is nonnegative.  */
7667       if (fcode == BUILT_IN_POW
7668           || fcode == BUILT_IN_POWF
7669           || fcode == BUILT_IN_POWL)
7670         {
7671           tree arg00 = CALL_EXPR_ARG (arg, 0);
7672           tree arg01 = CALL_EXPR_ARG (arg, 1);
7673           if (tree_expr_nonnegative_p (arg00))
7674             {
7675               tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7676               const REAL_VALUE_TYPE dconstroot
7677                 = real_value_truncate (TYPE_MODE (type), dconst_third ());
7678               tree narg01 = fold_build2_loc (loc, MULT_EXPR, type, arg01,
7679                                          build_real (type, dconstroot));
7680               return build_call_expr_loc (loc, powfn, 2, arg00, narg01);
7681             }
7682         }
7683     }
7684   return NULL_TREE;
7685 }
7686
7687 /* Fold function call to builtin cos, cosf, or cosl with argument ARG.
7688    TYPE is the type of the return value.  Return NULL_TREE if no
7689    simplification can be made.  */
7690
7691 static tree
7692 fold_builtin_cos (location_t loc,
7693                   tree arg, tree type, tree fndecl)
7694 {
7695   tree res, narg;
7696
7697   if (!validate_arg (arg, REAL_TYPE))
7698     return NULL_TREE;
7699
7700   /* Calculate the result when the argument is a constant.  */
7701   if ((res = do_mpfr_arg1 (arg, type, mpfr_cos, NULL, NULL, 0)))
7702     return res;
7703
7704   /* Optimize cos(-x) into cos (x).  */
7705   if ((narg = fold_strip_sign_ops (arg)))
7706     return build_call_expr_loc (loc, fndecl, 1, narg);
7707
7708   return NULL_TREE;
7709 }
7710
7711 /* Fold function call to builtin cosh, coshf, or coshl with argument ARG.
7712    Return NULL_TREE if no simplification can be made.  */
7713
7714 static tree
7715 fold_builtin_cosh (location_t loc, tree arg, tree type, tree fndecl)
7716 {
7717   if (validate_arg (arg, REAL_TYPE))
7718     {
7719       tree res, narg;
7720
7721       /* Calculate the result when the argument is a constant.  */
7722       if ((res = do_mpfr_arg1 (arg, type, mpfr_cosh, NULL, NULL, 0)))
7723         return res;
7724
7725       /* Optimize cosh(-x) into cosh (x).  */
7726       if ((narg = fold_strip_sign_ops (arg)))
7727         return build_call_expr_loc (loc, fndecl, 1, narg);
7728     }
7729
7730   return NULL_TREE;
7731 }
7732
7733 /* Fold function call to builtin ccos (or ccosh if HYPER is TRUE) with
7734    argument ARG.  TYPE is the type of the return value.  Return
7735    NULL_TREE if no simplification can be made.  */
7736
7737 static tree
7738 fold_builtin_ccos (location_t loc, tree arg, tree type, tree fndecl,
7739                    bool hyper)
7740 {
7741   if (validate_arg (arg, COMPLEX_TYPE)
7742       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE)
7743     {
7744       tree tmp;
7745
7746       /* Calculate the result when the argument is a constant.  */
7747       if ((tmp = do_mpc_arg1 (arg, type, (hyper ? mpc_cosh : mpc_cos))))
7748         return tmp;
7749
7750       /* Optimize fn(-x) into fn(x).  */
7751       if ((tmp = fold_strip_sign_ops (arg)))
7752         return build_call_expr_loc (loc, fndecl, 1, tmp);
7753     }
7754
7755   return NULL_TREE;
7756 }
7757
7758 /* Fold function call to builtin tan, tanf, or tanl with argument ARG.
7759    Return NULL_TREE if no simplification can be made.  */
7760
7761 static tree
7762 fold_builtin_tan (tree arg, tree type)
7763 {
7764   enum built_in_function fcode;
7765   tree res;
7766
7767   if (!validate_arg (arg, REAL_TYPE))
7768     return NULL_TREE;
7769
7770   /* Calculate the result when the argument is a constant.  */
7771   if ((res = do_mpfr_arg1 (arg, type, mpfr_tan, NULL, NULL, 0)))
7772     return res;
7773
7774   /* Optimize tan(atan(x)) = x.  */
7775   fcode = builtin_mathfn_code (arg);
7776   if (flag_unsafe_math_optimizations
7777       && (fcode == BUILT_IN_ATAN
7778           || fcode == BUILT_IN_ATANF
7779           || fcode == BUILT_IN_ATANL))
7780     return CALL_EXPR_ARG (arg, 0);
7781
7782   return NULL_TREE;
7783 }
7784
7785 /* Fold function call to builtin sincos, sincosf, or sincosl.  Return
7786    NULL_TREE if no simplification can be made.  */
7787
7788 static tree
7789 fold_builtin_sincos (location_t loc,
7790                      tree arg0, tree arg1, tree arg2)
7791 {
7792   tree type;
7793   tree res, fn, call;
7794
7795   if (!validate_arg (arg0, REAL_TYPE)
7796       || !validate_arg (arg1, POINTER_TYPE)
7797       || !validate_arg (arg2, POINTER_TYPE))
7798     return NULL_TREE;
7799
7800   type = TREE_TYPE (arg0);
7801
7802   /* Calculate the result when the argument is a constant.  */
7803   if ((res = do_mpfr_sincos (arg0, arg1, arg2)))
7804     return res;
7805
7806   /* Canonicalize sincos to cexpi.  */
7807   if (!TARGET_C99_FUNCTIONS)
7808     return NULL_TREE;
7809   fn = mathfn_built_in (type, BUILT_IN_CEXPI);
7810   if (!fn)
7811     return NULL_TREE;
7812
7813   call = build_call_expr_loc (loc, fn, 1, arg0);
7814   call = builtin_save_expr (call);
7815
7816   return build2 (COMPOUND_EXPR, void_type_node,
7817                  build2 (MODIFY_EXPR, void_type_node,
7818                          build_fold_indirect_ref_loc (loc, arg1),
7819                          build1 (IMAGPART_EXPR, type, call)),
7820                  build2 (MODIFY_EXPR, void_type_node,
7821                          build_fold_indirect_ref_loc (loc, arg2),
7822                          build1 (REALPART_EXPR, type, call)));
7823 }
7824
7825 /* Fold function call to builtin cexp, cexpf, or cexpl.  Return
7826    NULL_TREE if no simplification can be made.  */
7827
7828 static tree
7829 fold_builtin_cexp (location_t loc, tree arg0, tree type)
7830 {
7831   tree rtype;
7832   tree realp, imagp, ifn;
7833   tree res;
7834
7835   if (!validate_arg (arg0, COMPLEX_TYPE)
7836       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) != REAL_TYPE)
7837     return NULL_TREE;
7838
7839   /* Calculate the result when the argument is a constant.  */
7840   if ((res = do_mpc_arg1 (arg0, type, mpc_exp)))
7841     return res;
7842
7843   rtype = TREE_TYPE (TREE_TYPE (arg0));
7844
7845   /* In case we can figure out the real part of arg0 and it is constant zero
7846      fold to cexpi.  */
7847   if (!TARGET_C99_FUNCTIONS)
7848     return NULL_TREE;
7849   ifn = mathfn_built_in (rtype, BUILT_IN_CEXPI);
7850   if (!ifn)
7851     return NULL_TREE;
7852
7853   if ((realp = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0))
7854       && real_zerop (realp))
7855     {
7856       tree narg = fold_build1_loc (loc, IMAGPART_EXPR, rtype, arg0);
7857       return build_call_expr_loc (loc, ifn, 1, narg);
7858     }
7859
7860   /* In case we can easily decompose real and imaginary parts split cexp
7861      to exp (r) * cexpi (i).  */
7862   if (flag_unsafe_math_optimizations
7863       && realp)
7864     {
7865       tree rfn, rcall, icall;
7866
7867       rfn = mathfn_built_in (rtype, BUILT_IN_EXP);
7868       if (!rfn)
7869         return NULL_TREE;
7870
7871       imagp = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
7872       if (!imagp)
7873         return NULL_TREE;
7874
7875       icall = build_call_expr_loc (loc, ifn, 1, imagp);
7876       icall = builtin_save_expr (icall);
7877       rcall = build_call_expr_loc (loc, rfn, 1, realp);
7878       rcall = builtin_save_expr (rcall);
7879       return fold_build2_loc (loc, COMPLEX_EXPR, type,
7880                           fold_build2_loc (loc, MULT_EXPR, rtype,
7881                                        rcall,
7882                                        fold_build1_loc (loc, REALPART_EXPR,
7883                                                     rtype, icall)),
7884                           fold_build2_loc (loc, MULT_EXPR, rtype,
7885                                        rcall,
7886                                        fold_build1_loc (loc, IMAGPART_EXPR,
7887                                                     rtype, icall)));
7888     }
7889
7890   return NULL_TREE;
7891 }
7892
7893 /* Fold function call to builtin trunc, truncf or truncl with argument ARG.
7894    Return NULL_TREE if no simplification can be made.  */
7895
7896 static tree
7897 fold_builtin_trunc (location_t loc, tree fndecl, tree arg)
7898 {
7899   if (!validate_arg (arg, REAL_TYPE))
7900     return NULL_TREE;
7901
7902   /* Optimize trunc of constant value.  */
7903   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7904     {
7905       REAL_VALUE_TYPE r, x;
7906       tree type = TREE_TYPE (TREE_TYPE (fndecl));
7907
7908       x = TREE_REAL_CST (arg);
7909       real_trunc (&r, TYPE_MODE (type), &x);
7910       return build_real (type, r);
7911     }
7912
7913   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7914 }
7915
7916 /* Fold function call to builtin floor, floorf or floorl with argument ARG.
7917    Return NULL_TREE if no simplification can be made.  */
7918
7919 static tree
7920 fold_builtin_floor (location_t loc, tree fndecl, tree arg)
7921 {
7922   if (!validate_arg (arg, REAL_TYPE))
7923     return NULL_TREE;
7924
7925   /* Optimize floor of constant value.  */
7926   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7927     {
7928       REAL_VALUE_TYPE x;
7929
7930       x = TREE_REAL_CST (arg);
7931       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7932         {
7933           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7934           REAL_VALUE_TYPE r;
7935
7936           real_floor (&r, TYPE_MODE (type), &x);
7937           return build_real (type, r);
7938         }
7939     }
7940
7941   /* Fold floor (x) where x is nonnegative to trunc (x).  */
7942   if (tree_expr_nonnegative_p (arg))
7943     {
7944       tree truncfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_TRUNC);
7945       if (truncfn)
7946         return build_call_expr_loc (loc, truncfn, 1, arg);
7947     }
7948
7949   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7950 }
7951
7952 /* Fold function call to builtin ceil, ceilf or ceill with argument ARG.
7953    Return NULL_TREE if no simplification can be made.  */
7954
7955 static tree
7956 fold_builtin_ceil (location_t loc, tree fndecl, tree arg)
7957 {
7958   if (!validate_arg (arg, REAL_TYPE))
7959     return NULL_TREE;
7960
7961   /* Optimize ceil of constant value.  */
7962   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7963     {
7964       REAL_VALUE_TYPE x;
7965
7966       x = TREE_REAL_CST (arg);
7967       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7968         {
7969           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7970           REAL_VALUE_TYPE r;
7971
7972           real_ceil (&r, TYPE_MODE (type), &x);
7973           return build_real (type, r);
7974         }
7975     }
7976
7977   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7978 }
7979
7980 /* Fold function call to builtin round, roundf or roundl with argument ARG.
7981    Return NULL_TREE if no simplification can be made.  */
7982
7983 static tree
7984 fold_builtin_round (location_t loc, tree fndecl, tree arg)
7985 {
7986   if (!validate_arg (arg, REAL_TYPE))
7987     return NULL_TREE;
7988
7989   /* Optimize round of constant value.  */
7990   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7991     {
7992       REAL_VALUE_TYPE x;
7993
7994       x = TREE_REAL_CST (arg);
7995       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7996         {
7997           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7998           REAL_VALUE_TYPE r;
7999
8000           real_round (&r, TYPE_MODE (type), &x);
8001           return build_real (type, r);
8002         }
8003     }
8004
8005   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
8006 }
8007
8008 /* Fold function call to builtin lround, lroundf or lroundl (or the
8009    corresponding long long versions) and other rounding functions.  ARG
8010    is the argument to the call.  Return NULL_TREE if no simplification
8011    can be made.  */
8012
8013 static tree
8014 fold_builtin_int_roundingfn (location_t loc, tree fndecl, tree arg)
8015 {
8016   if (!validate_arg (arg, REAL_TYPE))
8017     return NULL_TREE;
8018
8019   /* Optimize lround of constant value.  */
8020   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
8021     {
8022       const REAL_VALUE_TYPE x = TREE_REAL_CST (arg);
8023
8024       if (real_isfinite (&x))
8025         {
8026           tree itype = TREE_TYPE (TREE_TYPE (fndecl));
8027           tree ftype = TREE_TYPE (arg);
8028           double_int val;
8029           REAL_VALUE_TYPE r;
8030
8031           switch (DECL_FUNCTION_CODE (fndecl))
8032             {
8033             CASE_FLT_FN (BUILT_IN_IFLOOR):
8034             CASE_FLT_FN (BUILT_IN_LFLOOR):
8035             CASE_FLT_FN (BUILT_IN_LLFLOOR):
8036               real_floor (&r, TYPE_MODE (ftype), &x);
8037               break;
8038
8039             CASE_FLT_FN (BUILT_IN_ICEIL):
8040             CASE_FLT_FN (BUILT_IN_LCEIL):
8041             CASE_FLT_FN (BUILT_IN_LLCEIL):
8042               real_ceil (&r, TYPE_MODE (ftype), &x);
8043               break;
8044
8045             CASE_FLT_FN (BUILT_IN_IROUND):
8046             CASE_FLT_FN (BUILT_IN_LROUND):
8047             CASE_FLT_FN (BUILT_IN_LLROUND):
8048               real_round (&r, TYPE_MODE (ftype), &x);
8049               break;
8050
8051             default:
8052               gcc_unreachable ();
8053             }
8054
8055           real_to_integer2 ((HOST_WIDE_INT *)&val.low, &val.high, &r);
8056           if (double_int_fits_to_tree_p (itype, val))
8057             return double_int_to_tree (itype, val);
8058         }
8059     }
8060
8061   switch (DECL_FUNCTION_CODE (fndecl))
8062     {
8063     CASE_FLT_FN (BUILT_IN_LFLOOR):
8064     CASE_FLT_FN (BUILT_IN_LLFLOOR):
8065       /* Fold lfloor (x) where x is nonnegative to FIX_TRUNC (x).  */
8066       if (tree_expr_nonnegative_p (arg))
8067         return fold_build1_loc (loc, FIX_TRUNC_EXPR,
8068                             TREE_TYPE (TREE_TYPE (fndecl)), arg);
8069       break;
8070     default:;
8071     }
8072
8073   return fold_fixed_mathfn (loc, fndecl, arg);
8074 }
8075
8076 /* Fold function call to builtin ffs, clz, ctz, popcount and parity
8077    and their long and long long variants (i.e. ffsl and ffsll).  ARG is
8078    the argument to the call.  Return NULL_TREE if no simplification can
8079    be made.  */
8080
8081 static tree
8082 fold_builtin_bitop (tree fndecl, tree arg)
8083 {
8084   if (!validate_arg (arg, INTEGER_TYPE))
8085     return NULL_TREE;
8086
8087   /* Optimize for constant argument.  */
8088   if (TREE_CODE (arg) == INTEGER_CST && !TREE_OVERFLOW (arg))
8089     {
8090       HOST_WIDE_INT hi, width, result;
8091       unsigned HOST_WIDE_INT lo;
8092       tree type;
8093
8094       type = TREE_TYPE (arg);
8095       width = TYPE_PRECISION (type);
8096       lo = TREE_INT_CST_LOW (arg);
8097
8098       /* Clear all the bits that are beyond the type's precision.  */
8099       if (width > HOST_BITS_PER_WIDE_INT)
8100         {
8101           hi = TREE_INT_CST_HIGH (arg);
8102           if (width < HOST_BITS_PER_DOUBLE_INT)
8103             hi &= ~((unsigned HOST_WIDE_INT) (-1)
8104                     << (width - HOST_BITS_PER_WIDE_INT));
8105         }
8106       else
8107         {
8108           hi = 0;
8109           if (width < HOST_BITS_PER_WIDE_INT)
8110             lo &= ~((unsigned HOST_WIDE_INT) (-1) << width);
8111         }
8112
8113       switch (DECL_FUNCTION_CODE (fndecl))
8114         {
8115         CASE_INT_FN (BUILT_IN_FFS):
8116           if (lo != 0)
8117             result = ffs_hwi (lo);
8118           else if (hi != 0)
8119             result = HOST_BITS_PER_WIDE_INT + ffs_hwi (hi);
8120           else
8121             result = 0;
8122           break;
8123
8124         CASE_INT_FN (BUILT_IN_CLZ):
8125           if (hi != 0)
8126             result = width - floor_log2 (hi) - 1 - HOST_BITS_PER_WIDE_INT;
8127           else if (lo != 0)
8128             result = width - floor_log2 (lo) - 1;
8129           else if (! CLZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
8130             result = width;
8131           break;
8132
8133         CASE_INT_FN (BUILT_IN_CTZ):
8134           if (lo != 0)
8135             result = ctz_hwi (lo);
8136           else if (hi != 0)
8137             result = HOST_BITS_PER_WIDE_INT + ctz_hwi (hi);
8138           else if (! CTZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
8139             result = width;
8140           break;
8141
8142         CASE_INT_FN (BUILT_IN_CLRSB):
8143           if (width > HOST_BITS_PER_WIDE_INT
8144               && (hi & ((unsigned HOST_WIDE_INT) 1
8145                         << (width - HOST_BITS_PER_WIDE_INT - 1))) != 0)
8146             {
8147               hi = ~hi & ~((unsigned HOST_WIDE_INT) (-1)
8148                            << (width - HOST_BITS_PER_WIDE_INT - 1));
8149               lo = ~lo;
8150             }
8151           else if (width <= HOST_BITS_PER_WIDE_INT
8152                    && (lo & ((unsigned HOST_WIDE_INT) 1 << (width - 1))) != 0)
8153             lo = ~lo & ~((unsigned HOST_WIDE_INT) (-1) << (width - 1));
8154           if (hi != 0)
8155             result = width - floor_log2 (hi) - 2 - HOST_BITS_PER_WIDE_INT;
8156           else if (lo != 0)
8157             result = width - floor_log2 (lo) - 2;
8158           else
8159             result = width - 1;
8160           break;
8161
8162         CASE_INT_FN (BUILT_IN_POPCOUNT):
8163           result = 0;
8164           while (lo)
8165             result++, lo &= lo - 1;
8166           while (hi)
8167             result++, hi &= (unsigned HOST_WIDE_INT) hi - 1;
8168           break;
8169
8170         CASE_INT_FN (BUILT_IN_PARITY):
8171           result = 0;
8172           while (lo)
8173             result++, lo &= lo - 1;
8174           while (hi)
8175             result++, hi &= (unsigned HOST_WIDE_INT) hi - 1;
8176           result &= 1;
8177           break;
8178
8179         default:
8180           gcc_unreachable ();
8181         }
8182
8183       return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), result);
8184     }
8185
8186   return NULL_TREE;
8187 }
8188
8189 /* Fold function call to builtin_bswap and the short, long and long long
8190    variants.  Return NULL_TREE if no simplification can be made.  */
8191 static tree
8192 fold_builtin_bswap (tree fndecl, tree arg)
8193 {
8194   if (! validate_arg (arg, INTEGER_TYPE))
8195     return NULL_TREE;
8196
8197   /* Optimize constant value.  */
8198   if (TREE_CODE (arg) == INTEGER_CST && !TREE_OVERFLOW (arg))
8199     {
8200       HOST_WIDE_INT hi, width, r_hi = 0;
8201       unsigned HOST_WIDE_INT lo, r_lo = 0;
8202       tree type = TREE_TYPE (TREE_TYPE (fndecl));
8203
8204       width = TYPE_PRECISION (type);
8205       lo = TREE_INT_CST_LOW (arg);
8206       hi = TREE_INT_CST_HIGH (arg);
8207
8208       switch (DECL_FUNCTION_CODE (fndecl))
8209         {
8210           case BUILT_IN_BSWAP16:
8211           case BUILT_IN_BSWAP32:
8212           case BUILT_IN_BSWAP64:
8213             {
8214               int s;
8215
8216               for (s = 0; s < width; s += 8)
8217                 {
8218                   int d = width - s - 8;
8219                   unsigned HOST_WIDE_INT byte;
8220
8221                   if (s < HOST_BITS_PER_WIDE_INT)
8222                     byte = (lo >> s) & 0xff;
8223                   else
8224                     byte = (hi >> (s - HOST_BITS_PER_WIDE_INT)) & 0xff;
8225
8226                   if (d < HOST_BITS_PER_WIDE_INT)
8227                     r_lo |= byte << d;
8228                   else
8229                     r_hi |= byte << (d - HOST_BITS_PER_WIDE_INT);
8230                 }
8231             }
8232
8233             break;
8234
8235         default:
8236           gcc_unreachable ();
8237         }
8238
8239       if (width < HOST_BITS_PER_WIDE_INT)
8240         return build_int_cst (type, r_lo);
8241       else
8242         return build_int_cst_wide (type, r_lo, r_hi);
8243     }
8244
8245   return NULL_TREE;
8246 }
8247
8248 /* A subroutine of fold_builtin to fold the various logarithmic
8249    functions.  Return NULL_TREE if no simplification can me made.
8250    FUNC is the corresponding MPFR logarithm function.  */
8251
8252 static tree
8253 fold_builtin_logarithm (location_t loc, tree fndecl, tree arg,
8254                         int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t))
8255 {
8256   if (validate_arg (arg, REAL_TYPE))
8257     {
8258       tree type = TREE_TYPE (TREE_TYPE (fndecl));
8259       tree res;
8260       const enum built_in_function fcode = builtin_mathfn_code (arg);
8261
8262       /* Calculate the result when the argument is a constant.  */
8263       if ((res = do_mpfr_arg1 (arg, type, func, &dconst0, NULL, false)))
8264         return res;
8265
8266       /* Special case, optimize logN(expN(x)) = x.  */
8267       if (flag_unsafe_math_optimizations
8268           && ((func == mpfr_log
8269                && (fcode == BUILT_IN_EXP
8270                    || fcode == BUILT_IN_EXPF
8271                    || fcode == BUILT_IN_EXPL))
8272               || (func == mpfr_log2
8273                   && (fcode == BUILT_IN_EXP2
8274                       || fcode == BUILT_IN_EXP2F
8275                       || fcode == BUILT_IN_EXP2L))
8276               || (func == mpfr_log10 && (BUILTIN_EXP10_P (fcode)))))
8277         return fold_convert_loc (loc, type, CALL_EXPR_ARG (arg, 0));
8278
8279       /* Optimize logN(func()) for various exponential functions.  We
8280          want to determine the value "x" and the power "exponent" in
8281          order to transform logN(x**exponent) into exponent*logN(x).  */
8282       if (flag_unsafe_math_optimizations)
8283         {
8284           tree exponent = 0, x = 0;
8285
8286           switch (fcode)
8287           {
8288           CASE_FLT_FN (BUILT_IN_EXP):
8289             /* Prepare to do logN(exp(exponent) -> exponent*logN(e).  */
8290             x = build_real (type, real_value_truncate (TYPE_MODE (type),
8291                                                        dconst_e ()));
8292             exponent = CALL_EXPR_ARG (arg, 0);
8293             break;
8294           CASE_FLT_FN (BUILT_IN_EXP2):
8295             /* Prepare to do logN(exp2(exponent) -> exponent*logN(2).  */
8296             x = build_real (type, dconst2);
8297             exponent = CALL_EXPR_ARG (arg, 0);
8298             break;
8299           CASE_FLT_FN (BUILT_IN_EXP10):
8300           CASE_FLT_FN (BUILT_IN_POW10):
8301             /* Prepare to do logN(exp10(exponent) -> exponent*logN(10).  */
8302             {
8303               REAL_VALUE_TYPE dconst10;
8304               real_from_integer (&dconst10, VOIDmode, 10, 0, 0);
8305               x = build_real (type, dconst10);
8306             }
8307             exponent = CALL_EXPR_ARG (arg, 0);
8308             break;
8309           CASE_FLT_FN (BUILT_IN_SQRT):
8310             /* Prepare to do logN(sqrt(x) -> 0.5*logN(x).  */
8311             x = CALL_EXPR_ARG (arg, 0);
8312             exponent = build_real (type, dconsthalf);
8313             break;
8314           CASE_FLT_FN (BUILT_IN_CBRT):
8315             /* Prepare to do logN(cbrt(x) -> (1/3)*logN(x).  */
8316             x = CALL_EXPR_ARG (arg, 0);
8317             exponent = build_real (type, real_value_truncate (TYPE_MODE (type),
8318                                                               dconst_third ()));
8319             break;
8320           CASE_FLT_FN (BUILT_IN_POW):
8321             /* Prepare to do logN(pow(x,exponent) -> exponent*logN(x).  */
8322             x = CALL_EXPR_ARG (arg, 0);
8323             exponent = CALL_EXPR_ARG (arg, 1);
8324             break;
8325           default:
8326             break;
8327           }
8328
8329           /* Now perform the optimization.  */
8330           if (x && exponent)
8331             {
8332               tree logfn = build_call_expr_loc (loc, fndecl, 1, x);
8333               return fold_build2_loc (loc, MULT_EXPR, type, exponent, logfn);
8334             }
8335         }
8336     }
8337
8338   return NULL_TREE;
8339 }
8340
8341 /* Fold a builtin function call to hypot, hypotf, or hypotl.  Return
8342    NULL_TREE if no simplification can be made.  */
8343
8344 static tree
8345 fold_builtin_hypot (location_t loc, tree fndecl,
8346                     tree arg0, tree arg1, tree type)
8347 {
8348   tree res, narg0, narg1;
8349
8350   if (!validate_arg (arg0, REAL_TYPE)
8351       || !validate_arg (arg1, REAL_TYPE))
8352     return NULL_TREE;
8353
8354   /* Calculate the result when the argument is a constant.  */
8355   if ((res = do_mpfr_arg2 (arg0, arg1, type, mpfr_hypot)))
8356     return res;
8357
8358   /* If either argument to hypot has a negate or abs, strip that off.
8359      E.g. hypot(-x,fabs(y)) -> hypot(x,y).  */
8360   narg0 = fold_strip_sign_ops (arg0);
8361   narg1 = fold_strip_sign_ops (arg1);
8362   if (narg0 || narg1)
8363     {
8364       return build_call_expr_loc (loc, fndecl, 2, narg0 ? narg0 : arg0,
8365                               narg1 ? narg1 : arg1);
8366     }
8367
8368   /* If either argument is zero, hypot is fabs of the other.  */
8369   if (real_zerop (arg0))
8370     return fold_build1_loc (loc, ABS_EXPR, type, arg1);
8371   else if (real_zerop (arg1))
8372     return fold_build1_loc (loc, ABS_EXPR, type, arg0);
8373
8374   /* hypot(x,x) -> fabs(x)*sqrt(2).  */
8375   if (flag_unsafe_math_optimizations
8376       && operand_equal_p (arg0, arg1, OEP_PURE_SAME))
8377     {
8378       const REAL_VALUE_TYPE sqrt2_trunc
8379         = real_value_truncate (TYPE_MODE (type), dconst_sqrt2 ());
8380       return fold_build2_loc (loc, MULT_EXPR, type,
8381                           fold_build1_loc (loc, ABS_EXPR, type, arg0),
8382                           build_real (type, sqrt2_trunc));
8383     }
8384
8385   return NULL_TREE;
8386 }
8387
8388
8389 /* Fold a builtin function call to pow, powf, or powl.  Return
8390    NULL_TREE if no simplification can be made.  */
8391 static tree
8392 fold_builtin_pow (location_t loc, tree fndecl, tree arg0, tree arg1, tree type)
8393 {
8394   tree res;
8395
8396   if (!validate_arg (arg0, REAL_TYPE)
8397        || !validate_arg (arg1, REAL_TYPE))
8398     return NULL_TREE;
8399
8400   /* Calculate the result when the argument is a constant.  */
8401   if ((res = do_mpfr_arg2 (arg0, arg1, type, mpfr_pow)))
8402     return res;
8403
8404   /* Optimize pow(1.0,y) = 1.0.  */
8405   if (real_onep (arg0))
8406     return omit_one_operand_loc (loc, type, build_real (type, dconst1), arg1);
8407
8408   if (TREE_CODE (arg1) == REAL_CST
8409       && !TREE_OVERFLOW (arg1))
8410     {
8411       REAL_VALUE_TYPE cint;
8412       REAL_VALUE_TYPE c;
8413       HOST_WIDE_INT n;
8414
8415       c = TREE_REAL_CST (arg1);
8416
8417       /* Optimize pow(x,0.0) = 1.0.  */
8418       if (REAL_VALUES_EQUAL (c, dconst0))
8419         return omit_one_operand_loc (loc, type, build_real (type, dconst1),
8420                                  arg0);
8421
8422       /* Optimize pow(x,1.0) = x.  */
8423       if (REAL_VALUES_EQUAL (c, dconst1))
8424         return arg0;
8425
8426       /* Optimize pow(x,-1.0) = 1.0/x.  */
8427       if (REAL_VALUES_EQUAL (c, dconstm1))
8428         return fold_build2_loc (loc, RDIV_EXPR, type,
8429                             build_real (type, dconst1), arg0);
8430
8431       /* Optimize pow(x,0.5) = sqrt(x).  */
8432       if (flag_unsafe_math_optimizations
8433           && REAL_VALUES_EQUAL (c, dconsthalf))
8434         {
8435           tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
8436
8437           if (sqrtfn != NULL_TREE)
8438             return build_call_expr_loc (loc, sqrtfn, 1, arg0);
8439         }
8440
8441       /* Optimize pow(x,1.0/3.0) = cbrt(x).  */
8442       if (flag_unsafe_math_optimizations)
8443         {
8444           const REAL_VALUE_TYPE dconstroot
8445             = real_value_truncate (TYPE_MODE (type), dconst_third ());
8446
8447           if (REAL_VALUES_EQUAL (c, dconstroot))
8448             {
8449               tree cbrtfn = mathfn_built_in (type, BUILT_IN_CBRT);
8450               if (cbrtfn != NULL_TREE)
8451                 return build_call_expr_loc (loc, cbrtfn, 1, arg0);
8452             }
8453         }
8454
8455       /* Check for an integer exponent.  */
8456       n = real_to_integer (&c);
8457       real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
8458       if (real_identical (&c, &cint))
8459         {
8460           /* Attempt to evaluate pow at compile-time, unless this should
8461              raise an exception.  */
8462           if (TREE_CODE (arg0) == REAL_CST
8463               && !TREE_OVERFLOW (arg0)
8464               && (n > 0
8465                   || (!flag_trapping_math && !flag_errno_math)
8466                   || !REAL_VALUES_EQUAL (TREE_REAL_CST (arg0), dconst0)))
8467             {
8468               REAL_VALUE_TYPE x;
8469               bool inexact;
8470
8471               x = TREE_REAL_CST (arg0);
8472               inexact = real_powi (&x, TYPE_MODE (type), &x, n);
8473               if (flag_unsafe_math_optimizations || !inexact)
8474                 return build_real (type, x);
8475             }
8476
8477           /* Strip sign ops from even integer powers.  */
8478           if ((n & 1) == 0 && flag_unsafe_math_optimizations)
8479             {
8480               tree narg0 = fold_strip_sign_ops (arg0);
8481               if (narg0)
8482                 return build_call_expr_loc (loc, fndecl, 2, narg0, arg1);
8483             }
8484         }
8485     }
8486
8487   if (flag_unsafe_math_optimizations)
8488     {
8489       const enum built_in_function fcode = builtin_mathfn_code (arg0);
8490
8491       /* Optimize pow(expN(x),y) = expN(x*y).  */
8492       if (BUILTIN_EXPONENT_P (fcode))
8493         {
8494           tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
8495           tree arg = CALL_EXPR_ARG (arg0, 0);
8496           arg = fold_build2_loc (loc, MULT_EXPR, type, arg, arg1);
8497           return build_call_expr_loc (loc, expfn, 1, arg);
8498         }
8499
8500       /* Optimize pow(sqrt(x),y) = pow(x,y*0.5).  */
8501       if (BUILTIN_SQRT_P (fcode))
8502         {
8503           tree narg0 = CALL_EXPR_ARG (arg0, 0);
8504           tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
8505                                     build_real (type, dconsthalf));
8506           return build_call_expr_loc (loc, fndecl, 2, narg0, narg1);
8507         }
8508
8509       /* Optimize pow(cbrt(x),y) = pow(x,y/3) iff x is nonnegative.  */
8510       if (BUILTIN_CBRT_P (fcode))
8511         {
8512           tree arg = CALL_EXPR_ARG (arg0, 0);
8513           if (tree_expr_nonnegative_p (arg))
8514             {
8515               const REAL_VALUE_TYPE dconstroot
8516                 = real_value_truncate (TYPE_MODE (type), dconst_third ());
8517               tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
8518                                         build_real (type, dconstroot));
8519               return build_call_expr_loc (loc, fndecl, 2, arg, narg1);
8520             }
8521         }
8522
8523       /* Optimize pow(pow(x,y),z) = pow(x,y*z) iff x is nonnegative.  */
8524       if (fcode == BUILT_IN_POW
8525           || fcode == BUILT_IN_POWF
8526           || fcode == BUILT_IN_POWL)
8527         {
8528           tree arg00 = CALL_EXPR_ARG (arg0, 0);
8529           if (tree_expr_nonnegative_p (arg00))
8530             {
8531               tree arg01 = CALL_EXPR_ARG (arg0, 1);
8532               tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg01, arg1);
8533               return build_call_expr_loc (loc, fndecl, 2, arg00, narg1);
8534             }
8535         }
8536     }
8537
8538   return NULL_TREE;
8539 }
8540
8541 /* Fold a builtin function call to powi, powif, or powil with argument ARG.
8542    Return NULL_TREE if no simplification can be made.  */
8543 static tree
8544 fold_builtin_powi (location_t loc, tree fndecl ATTRIBUTE_UNUSED,
8545                    tree arg0, tree arg1, tree type)
8546 {
8547   if (!validate_arg (arg0, REAL_TYPE)
8548       || !validate_arg (arg1, INTEGER_TYPE))
8549     return NULL_TREE;
8550
8551   /* Optimize pow(1.0,y) = 1.0.  */
8552   if (real_onep (arg0))
8553     return omit_one_operand_loc (loc, type, build_real (type, dconst1), arg1);
8554
8555   if (host_integerp (arg1, 0))
8556     {
8557       HOST_WIDE_INT c = TREE_INT_CST_LOW (arg1);
8558
8559       /* Evaluate powi at compile-time.  */
8560       if (TREE_CODE (arg0) == REAL_CST
8561           && !TREE_OVERFLOW (arg0))
8562         {
8563           REAL_VALUE_TYPE x;
8564           x = TREE_REAL_CST (arg0);
8565           real_powi (&x, TYPE_MODE (type), &x, c);
8566           return build_real (type, x);
8567         }
8568
8569       /* Optimize pow(x,0) = 1.0.  */
8570       if (c == 0)
8571         return omit_one_operand_loc (loc, type, build_real (type, dconst1),
8572                                  arg0);
8573
8574       /* Optimize pow(x,1) = x.  */
8575       if (c == 1)
8576         return arg0;
8577
8578       /* Optimize pow(x,-1) = 1.0/x.  */
8579       if (c == -1)
8580         return fold_build2_loc (loc, RDIV_EXPR, type,
8581                            build_real (type, dconst1), arg0);
8582     }
8583
8584   return NULL_TREE;
8585 }
8586
8587 /* A subroutine of fold_builtin to fold the various exponent
8588    functions.  Return NULL_TREE if no simplification can be made.
8589    FUNC is the corresponding MPFR exponent function.  */
8590
8591 static tree
8592 fold_builtin_exponent (location_t loc, tree fndecl, tree arg,
8593                        int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t))
8594 {
8595   if (validate_arg (arg, REAL_TYPE))
8596     {
8597       tree type = TREE_TYPE (TREE_TYPE (fndecl));
8598       tree res;
8599
8600       /* Calculate the result when the argument is a constant.  */
8601       if ((res = do_mpfr_arg1 (arg, type, func, NULL, NULL, 0)))
8602         return res;
8603
8604       /* Optimize expN(logN(x)) = x.  */
8605       if (flag_unsafe_math_optimizations)
8606         {
8607           const enum built_in_function fcode = builtin_mathfn_code (arg);
8608
8609           if ((func == mpfr_exp
8610                && (fcode == BUILT_IN_LOG
8611                    || fcode == BUILT_IN_LOGF
8612                    || fcode == BUILT_IN_LOGL))
8613               || (func == mpfr_exp2
8614                   && (fcode == BUILT_IN_LOG2
8615                       || fcode == BUILT_IN_LOG2F
8616                       || fcode == BUILT_IN_LOG2L))
8617               || (func == mpfr_exp10
8618                   && (fcode == BUILT_IN_LOG10
8619                       || fcode == BUILT_IN_LOG10F
8620                       || fcode == BUILT_IN_LOG10L)))
8621             return fold_convert_loc (loc, type, CALL_EXPR_ARG (arg, 0));
8622         }
8623     }
8624
8625   return NULL_TREE;
8626 }
8627
8628 /* Return true if VAR is a VAR_DECL or a component thereof.  */
8629
8630 static bool
8631 var_decl_component_p (tree var)
8632 {
8633   tree inner = var;
8634   while (handled_component_p (inner))
8635     inner = TREE_OPERAND (inner, 0);
8636   return SSA_VAR_P (inner);
8637 }
8638
8639 /* Fold function call to builtin memset.  Return
8640    NULL_TREE if no simplification can be made.  */
8641
8642 static tree
8643 fold_builtin_memset (location_t loc, tree dest, tree c, tree len,
8644                      tree type, bool ignore)
8645 {
8646   tree var, ret, etype;
8647   unsigned HOST_WIDE_INT length, cval;
8648
8649   if (! validate_arg (dest, POINTER_TYPE)
8650       || ! validate_arg (c, INTEGER_TYPE)
8651       || ! validate_arg (len, INTEGER_TYPE))
8652     return NULL_TREE;
8653
8654   if (! host_integerp (len, 1))
8655     return NULL_TREE;
8656
8657   /* If the LEN parameter is zero, return DEST.  */
8658   if (integer_zerop (len))
8659     return omit_one_operand_loc (loc, type, dest, c);
8660
8661   if (TREE_CODE (c) != INTEGER_CST || TREE_SIDE_EFFECTS (dest))
8662     return NULL_TREE;
8663
8664   var = dest;
8665   STRIP_NOPS (var);
8666   if (TREE_CODE (var) != ADDR_EXPR)
8667     return NULL_TREE;
8668
8669   var = TREE_OPERAND (var, 0);
8670   if (TREE_THIS_VOLATILE (var))
8671     return NULL_TREE;
8672
8673   etype = TREE_TYPE (var);
8674   if (TREE_CODE (etype) == ARRAY_TYPE)
8675     etype = TREE_TYPE (etype);
8676
8677   if (!INTEGRAL_TYPE_P (etype)
8678       && !POINTER_TYPE_P (etype))
8679     return NULL_TREE;
8680
8681   if (! var_decl_component_p (var))
8682     return NULL_TREE;
8683
8684   length = tree_low_cst (len, 1);
8685   if (GET_MODE_SIZE (TYPE_MODE (etype)) != length
8686       || get_pointer_alignment (dest) / BITS_PER_UNIT < length)
8687     return NULL_TREE;
8688
8689   if (length > HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT)
8690     return NULL_TREE;
8691
8692   if (integer_zerop (c))
8693     cval = 0;
8694   else
8695     {
8696       if (CHAR_BIT != 8 || BITS_PER_UNIT != 8 || HOST_BITS_PER_WIDE_INT > 64)
8697         return NULL_TREE;
8698
8699       cval = TREE_INT_CST_LOW (c);
8700       cval &= 0xff;
8701       cval |= cval << 8;
8702       cval |= cval << 16;
8703       cval |= (cval << 31) << 1;
8704     }
8705
8706   ret = build_int_cst_type (etype, cval);
8707   var = build_fold_indirect_ref_loc (loc,
8708                                  fold_convert_loc (loc,
8709                                                    build_pointer_type (etype),
8710                                                    dest));
8711   ret = build2 (MODIFY_EXPR, etype, var, ret);
8712   if (ignore)
8713     return ret;
8714
8715   return omit_one_operand_loc (loc, type, dest, ret);
8716 }
8717
8718 /* Fold function call to builtin memset.  Return
8719    NULL_TREE if no simplification can be made.  */
8720
8721 static tree
8722 fold_builtin_bzero (location_t loc, tree dest, tree size, bool ignore)
8723 {
8724   if (! validate_arg (dest, POINTER_TYPE)
8725       || ! validate_arg (size, INTEGER_TYPE))
8726     return NULL_TREE;
8727
8728   if (!ignore)
8729     return NULL_TREE;
8730
8731   /* New argument list transforming bzero(ptr x, int y) to
8732      memset(ptr x, int 0, size_t y).   This is done this way
8733      so that if it isn't expanded inline, we fallback to
8734      calling bzero instead of memset.  */
8735
8736   return fold_builtin_memset (loc, dest, integer_zero_node,
8737                               fold_convert_loc (loc, size_type_node, size),
8738                               void_type_node, ignore);
8739 }
8740
8741 /* Fold function call to builtin mem{{,p}cpy,move}.  Return
8742    NULL_TREE if no simplification can be made.
8743    If ENDP is 0, return DEST (like memcpy).
8744    If ENDP is 1, return DEST+LEN (like mempcpy).
8745    If ENDP is 2, return DEST+LEN-1 (like stpcpy).
8746    If ENDP is 3, return DEST, additionally *SRC and *DEST may overlap
8747    (memmove).   */
8748
8749 static tree
8750 fold_builtin_memory_op (location_t loc, tree dest, tree src,
8751                         tree len, tree type, bool ignore, int endp)
8752 {
8753   tree destvar, srcvar, expr;
8754
8755   if (! validate_arg (dest, POINTER_TYPE)
8756       || ! validate_arg (src, POINTER_TYPE)
8757       || ! validate_arg (len, INTEGER_TYPE))
8758     return NULL_TREE;
8759
8760   /* If the LEN parameter is zero, return DEST.  */
8761   if (integer_zerop (len))
8762     return omit_one_operand_loc (loc, type, dest, src);
8763
8764   /* If SRC and DEST are the same (and not volatile), return
8765      DEST{,+LEN,+LEN-1}.  */
8766   if (operand_equal_p (src, dest, 0))
8767     expr = len;
8768   else
8769     {
8770       tree srctype, desttype;
8771       unsigned int src_align, dest_align;
8772       tree off0;
8773
8774       if (endp == 3)
8775         {
8776           src_align = get_pointer_alignment (src);
8777           dest_align = get_pointer_alignment (dest);
8778
8779           /* Both DEST and SRC must be pointer types.
8780              ??? This is what old code did.  Is the testing for pointer types
8781              really mandatory?
8782
8783              If either SRC is readonly or length is 1, we can use memcpy.  */
8784           if (!dest_align || !src_align)
8785             return NULL_TREE;
8786           if (readonly_data_expr (src)
8787               || (host_integerp (len, 1)
8788                   && (MIN (src_align, dest_align) / BITS_PER_UNIT
8789                       >= (unsigned HOST_WIDE_INT) tree_low_cst (len, 1))))
8790             {
8791               tree fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
8792               if (!fn)
8793                 return NULL_TREE;
8794               return build_call_expr_loc (loc, fn, 3, dest, src, len);
8795             }
8796
8797           /* If *src and *dest can't overlap, optimize into memcpy as well.  */
8798           if (TREE_CODE (src) == ADDR_EXPR
8799               && TREE_CODE (dest) == ADDR_EXPR)
8800             {
8801               tree src_base, dest_base, fn;
8802               HOST_WIDE_INT src_offset = 0, dest_offset = 0;
8803               HOST_WIDE_INT size = -1;
8804               HOST_WIDE_INT maxsize = -1;
8805
8806               srcvar = TREE_OPERAND (src, 0);
8807               src_base = get_ref_base_and_extent (srcvar, &src_offset,
8808                                                   &size, &maxsize);
8809               destvar = TREE_OPERAND (dest, 0);
8810               dest_base = get_ref_base_and_extent (destvar, &dest_offset,
8811                                                    &size, &maxsize);
8812               if (host_integerp (len, 1))
8813                 maxsize = tree_low_cst (len, 1);
8814               else
8815                 maxsize = -1;
8816               src_offset /= BITS_PER_UNIT;
8817               dest_offset /= BITS_PER_UNIT;
8818               if (SSA_VAR_P (src_base)
8819                   && SSA_VAR_P (dest_base))
8820                 {
8821                   if (operand_equal_p (src_base, dest_base, 0)
8822                       && ranges_overlap_p (src_offset, maxsize,
8823                                            dest_offset, maxsize))
8824                     return NULL_TREE;
8825                 }
8826               else if (TREE_CODE (src_base) == MEM_REF
8827                        && TREE_CODE (dest_base) == MEM_REF)
8828                 {
8829                   double_int off;
8830                   if (! operand_equal_p (TREE_OPERAND (src_base, 0),
8831                                          TREE_OPERAND (dest_base, 0), 0))
8832                     return NULL_TREE;
8833                   off = mem_ref_offset (src_base) +
8834                                         double_int::from_shwi (src_offset);
8835                   if (!off.fits_shwi ())
8836                     return NULL_TREE;
8837                   src_offset = off.low;
8838                   off = mem_ref_offset (dest_base) +
8839                                         double_int::from_shwi (dest_offset);
8840                   if (!off.fits_shwi ())
8841                     return NULL_TREE;
8842                   dest_offset = off.low;
8843                   if (ranges_overlap_p (src_offset, maxsize,
8844                                         dest_offset, maxsize))
8845                     return NULL_TREE;
8846                 }
8847               else
8848                 return NULL_TREE;
8849
8850               fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
8851               if (!fn)
8852                 return NULL_TREE;
8853               return build_call_expr_loc (loc, fn, 3, dest, src, len);
8854             }
8855
8856           /* If the destination and source do not alias optimize into
8857              memcpy as well.  */
8858           if ((is_gimple_min_invariant (dest)
8859                || TREE_CODE (dest) == SSA_NAME)
8860               && (is_gimple_min_invariant (src)
8861                   || TREE_CODE (src) == SSA_NAME))
8862             {
8863               ao_ref destr, srcr;
8864               ao_ref_init_from_ptr_and_size (&destr, dest, len);
8865               ao_ref_init_from_ptr_and_size (&srcr, src, len);
8866               if (!refs_may_alias_p_1 (&destr, &srcr, false))
8867                 {
8868                   tree fn;
8869                   fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
8870                   if (!fn)
8871                     return NULL_TREE;
8872                   return build_call_expr_loc (loc, fn, 3, dest, src, len);
8873                 }
8874             }
8875
8876           return NULL_TREE;
8877         }
8878
8879       if (!host_integerp (len, 0))
8880         return NULL_TREE;
8881       /* FIXME:
8882          This logic lose for arguments like (type *)malloc (sizeof (type)),
8883          since we strip the casts of up to VOID return value from malloc.
8884          Perhaps we ought to inherit type from non-VOID argument here?  */
8885       STRIP_NOPS (src);
8886       STRIP_NOPS (dest);
8887       if (!POINTER_TYPE_P (TREE_TYPE (src))
8888           || !POINTER_TYPE_P (TREE_TYPE (dest)))
8889         return NULL_TREE;
8890       /* As we fold (void *)(p + CST) to (void *)p + CST undo this here.  */
8891       if (TREE_CODE (src) == POINTER_PLUS_EXPR)
8892         {
8893           tree tem = TREE_OPERAND (src, 0);
8894           STRIP_NOPS (tem);
8895           if (tem != TREE_OPERAND (src, 0))
8896             src = build1 (NOP_EXPR, TREE_TYPE (tem), src);
8897         }
8898       if (TREE_CODE (dest) == POINTER_PLUS_EXPR)
8899         {
8900           tree tem = TREE_OPERAND (dest, 0);
8901           STRIP_NOPS (tem);
8902           if (tem != TREE_OPERAND (dest, 0))
8903             dest = build1 (NOP_EXPR, TREE_TYPE (tem), dest);
8904         }
8905       srctype = TREE_TYPE (TREE_TYPE (src));
8906       if (TREE_CODE (srctype) == ARRAY_TYPE
8907           && !tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
8908         {
8909           srctype = TREE_TYPE (srctype);
8910           STRIP_NOPS (src);
8911           src = build1 (NOP_EXPR, build_pointer_type (srctype), src);
8912         }
8913       desttype = TREE_TYPE (TREE_TYPE (dest));
8914       if (TREE_CODE (desttype) == ARRAY_TYPE
8915           && !tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
8916         {
8917           desttype = TREE_TYPE (desttype);
8918           STRIP_NOPS (dest);
8919           dest = build1 (NOP_EXPR, build_pointer_type (desttype), dest);
8920         }
8921       if (TREE_ADDRESSABLE (srctype)
8922           || TREE_ADDRESSABLE (desttype))
8923         return NULL_TREE;
8924
8925       src_align = get_pointer_alignment (src);
8926       dest_align = get_pointer_alignment (dest);
8927       if (dest_align < TYPE_ALIGN (desttype)
8928           || src_align < TYPE_ALIGN (srctype))
8929         return NULL_TREE;
8930
8931       if (!ignore)
8932         dest = builtin_save_expr (dest);
8933
8934       /* Build accesses at offset zero with a ref-all character type.  */
8935       off0 = build_int_cst (build_pointer_type_for_mode (char_type_node,
8936                                                          ptr_mode, true), 0);
8937
8938       destvar = dest;
8939       STRIP_NOPS (destvar);
8940       if (TREE_CODE (destvar) == ADDR_EXPR
8941           && var_decl_component_p (TREE_OPERAND (destvar, 0))
8942           && tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
8943         destvar = fold_build2 (MEM_REF, desttype, destvar, off0);
8944       else
8945         destvar = NULL_TREE;
8946
8947       srcvar = src;
8948       STRIP_NOPS (srcvar);
8949       if (TREE_CODE (srcvar) == ADDR_EXPR
8950           && var_decl_component_p (TREE_OPERAND (srcvar, 0))
8951           && tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
8952         {
8953           if (!destvar
8954               || src_align >= TYPE_ALIGN (desttype))
8955             srcvar = fold_build2 (MEM_REF, destvar ? desttype : srctype,
8956                                   srcvar, off0);
8957           else if (!STRICT_ALIGNMENT)
8958             {
8959               srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
8960                                             src_align);
8961               srcvar = fold_build2 (MEM_REF, srctype, srcvar, off0);
8962             }
8963           else
8964             srcvar = NULL_TREE;
8965         }
8966       else
8967         srcvar = NULL_TREE;
8968
8969       if (srcvar == NULL_TREE && destvar == NULL_TREE)
8970         return NULL_TREE;
8971
8972       if (srcvar == NULL_TREE)
8973         {
8974           STRIP_NOPS (src);
8975           if (src_align >= TYPE_ALIGN (desttype))
8976             srcvar = fold_build2 (MEM_REF, desttype, src, off0);
8977           else
8978             {
8979               if (STRICT_ALIGNMENT)
8980                 return NULL_TREE;
8981               srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
8982                                             src_align);
8983               srcvar = fold_build2 (MEM_REF, srctype, src, off0);
8984             }
8985         }
8986       else if (destvar == NULL_TREE)
8987         {
8988           STRIP_NOPS (dest);
8989           if (dest_align >= TYPE_ALIGN (srctype))
8990             destvar = fold_build2 (MEM_REF, srctype, dest, off0);
8991           else
8992             {
8993               if (STRICT_ALIGNMENT)
8994                 return NULL_TREE;
8995               desttype = build_aligned_type (TYPE_MAIN_VARIANT (srctype),
8996                                              dest_align);
8997               destvar = fold_build2 (MEM_REF, desttype, dest, off0);
8998             }
8999         }
9000
9001       expr = build2 (MODIFY_EXPR, TREE_TYPE (destvar), destvar, srcvar);
9002     }
9003
9004   if (ignore)
9005     return expr;
9006
9007   if (endp == 0 || endp == 3)
9008     return omit_one_operand_loc (loc, type, dest, expr);
9009
9010   if (expr == len)
9011     expr = NULL_TREE;
9012
9013   if (endp == 2)
9014     len = fold_build2_loc (loc, MINUS_EXPR, TREE_TYPE (len), len,
9015                        ssize_int (1));
9016
9017   dest = fold_build_pointer_plus_loc (loc, dest, len);
9018   dest = fold_convert_loc (loc, type, dest);
9019   if (expr)
9020     dest = omit_one_operand_loc (loc, type, dest, expr);
9021   return dest;
9022 }
9023
9024 /* Fold function call to builtin strcpy with arguments DEST and SRC.
9025    If LEN is not NULL, it represents the length of the string to be
9026    copied.  Return NULL_TREE if no simplification can be made.  */
9027
9028 tree
9029 fold_builtin_strcpy (location_t loc, tree fndecl, tree dest, tree src, tree len)
9030 {
9031   tree fn;
9032
9033   if (!validate_arg (dest, POINTER_TYPE)
9034       || !validate_arg (src, POINTER_TYPE))
9035     return NULL_TREE;
9036
9037   /* If SRC and DEST are the same (and not volatile), return DEST.  */
9038   if (operand_equal_p (src, dest, 0))
9039     return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest);
9040
9041   if (optimize_function_for_size_p (cfun))
9042     return NULL_TREE;
9043
9044   fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
9045   if (!fn)
9046     return NULL_TREE;
9047
9048   if (!len)
9049     {
9050       len = c_strlen (src, 1);
9051       if (! len || TREE_SIDE_EFFECTS (len))
9052         return NULL_TREE;
9053     }
9054
9055   len = fold_convert_loc (loc, size_type_node, len);
9056   len = size_binop_loc (loc, PLUS_EXPR, len, build_int_cst (size_type_node, 1));
9057   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
9058                            build_call_expr_loc (loc, fn, 3, dest, src, len));
9059 }
9060
9061 /* Fold function call to builtin stpcpy with arguments DEST and SRC.
9062    Return NULL_TREE if no simplification can be made.  */
9063
9064 static tree
9065 fold_builtin_stpcpy (location_t loc, tree fndecl, tree dest, tree src)
9066 {
9067   tree fn, len, lenp1, call, type;
9068
9069   if (!validate_arg (dest, POINTER_TYPE)
9070       || !validate_arg (src, POINTER_TYPE))
9071     return NULL_TREE;
9072
9073   len = c_strlen (src, 1);
9074   if (!len
9075       || TREE_CODE (len) != INTEGER_CST)
9076     return NULL_TREE;
9077
9078   if (optimize_function_for_size_p (cfun)
9079       /* If length is zero it's small enough.  */
9080       && !integer_zerop (len))
9081     return NULL_TREE;
9082
9083   fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
9084   if (!fn)
9085     return NULL_TREE;
9086
9087   lenp1 = size_binop_loc (loc, PLUS_EXPR,
9088                           fold_convert_loc (loc, size_type_node, len),
9089                           build_int_cst (size_type_node, 1));
9090   /* We use dest twice in building our expression.  Save it from
9091      multiple expansions.  */
9092   dest = builtin_save_expr (dest);
9093   call = build_call_expr_loc (loc, fn, 3, dest, src, lenp1);
9094
9095   type = TREE_TYPE (TREE_TYPE (fndecl));
9096   dest = fold_build_pointer_plus_loc (loc, dest, len);
9097   dest = fold_convert_loc (loc, type, dest);
9098   dest = omit_one_operand_loc (loc, type, dest, call);
9099   return dest;
9100 }
9101
9102 /* Fold function call to builtin strncpy with arguments DEST, SRC, and LEN.
9103    If SLEN is not NULL, it represents the length of the source string.
9104    Return NULL_TREE if no simplification can be made.  */
9105
9106 tree
9107 fold_builtin_strncpy (location_t loc, tree fndecl, tree dest,
9108                       tree src, tree len, tree slen)
9109 {
9110   tree fn;
9111
9112   if (!validate_arg (dest, POINTER_TYPE)
9113       || !validate_arg (src, POINTER_TYPE)
9114       || !validate_arg (len, INTEGER_TYPE))
9115     return NULL_TREE;
9116
9117   /* If the LEN parameter is zero, return DEST.  */
9118   if (integer_zerop (len))
9119     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
9120
9121   /* We can't compare slen with len as constants below if len is not a
9122      constant.  */
9123   if (len == 0 || TREE_CODE (len) != INTEGER_CST)
9124     return NULL_TREE;
9125
9126   if (!slen)
9127     slen = c_strlen (src, 1);
9128
9129   /* Now, we must be passed a constant src ptr parameter.  */
9130   if (slen == 0 || TREE_CODE (slen) != INTEGER_CST)
9131     return NULL_TREE;
9132
9133   slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
9134
9135   /* We do not support simplification of this case, though we do
9136      support it when expanding trees into RTL.  */
9137   /* FIXME: generate a call to __builtin_memset.  */
9138   if (tree_int_cst_lt (slen, len))
9139     return NULL_TREE;
9140
9141   /* OK transform into builtin memcpy.  */
9142   fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
9143   if (!fn)
9144     return NULL_TREE;
9145
9146   len = fold_convert_loc (loc, size_type_node, len);
9147   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
9148                            build_call_expr_loc (loc, fn, 3, dest, src, len));
9149 }
9150
9151 /* Fold function call to builtin memchr.  ARG1, ARG2 and LEN are the
9152    arguments to the call, and TYPE is its return type.
9153    Return NULL_TREE if no simplification can be made.  */
9154
9155 static tree
9156 fold_builtin_memchr (location_t loc, tree arg1, tree arg2, tree len, tree type)
9157 {
9158   if (!validate_arg (arg1, POINTER_TYPE)
9159       || !validate_arg (arg2, INTEGER_TYPE)
9160       || !validate_arg (len, INTEGER_TYPE))
9161     return NULL_TREE;
9162   else
9163     {
9164       const char *p1;
9165
9166       if (TREE_CODE (arg2) != INTEGER_CST
9167           || !host_integerp (len, 1))
9168         return NULL_TREE;
9169
9170       p1 = c_getstr (arg1);
9171       if (p1 && compare_tree_int (len, strlen (p1) + 1) <= 0)
9172         {
9173           char c;
9174           const char *r;
9175           tree tem;
9176
9177           if (target_char_cast (arg2, &c))
9178             return NULL_TREE;
9179
9180           r = (const char *) memchr (p1, c, tree_low_cst (len, 1));
9181
9182           if (r == NULL)
9183             return build_int_cst (TREE_TYPE (arg1), 0);
9184
9185           tem = fold_build_pointer_plus_hwi_loc (loc, arg1, r - p1);
9186           return fold_convert_loc (loc, type, tem);
9187         }
9188       return NULL_TREE;
9189     }
9190 }
9191
9192 /* Fold function call to builtin memcmp with arguments ARG1 and ARG2.
9193    Return NULL_TREE if no simplification can be made.  */
9194
9195 static tree
9196 fold_builtin_memcmp (location_t loc, tree arg1, tree arg2, tree len)
9197 {
9198   const char *p1, *p2;
9199
9200   if (!validate_arg (arg1, POINTER_TYPE)
9201       || !validate_arg (arg2, POINTER_TYPE)
9202       || !validate_arg (len, INTEGER_TYPE))
9203     return NULL_TREE;
9204
9205   /* If the LEN parameter is zero, return zero.  */
9206   if (integer_zerop (len))
9207     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
9208                               arg1, arg2);
9209
9210   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
9211   if (operand_equal_p (arg1, arg2, 0))
9212     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
9213
9214   p1 = c_getstr (arg1);
9215   p2 = c_getstr (arg2);
9216
9217   /* If all arguments are constant, and the value of len is not greater
9218      than the lengths of arg1 and arg2, evaluate at compile-time.  */
9219   if (host_integerp (len, 1) && p1 && p2
9220       && compare_tree_int (len, strlen (p1) + 1) <= 0
9221       && compare_tree_int (len, strlen (p2) + 1) <= 0)
9222     {
9223       const int r = memcmp (p1, p2, tree_low_cst (len, 1));
9224
9225       if (r > 0)
9226         return integer_one_node;
9227       else if (r < 0)
9228         return integer_minus_one_node;
9229       else
9230         return integer_zero_node;
9231     }
9232
9233   /* If len parameter is one, return an expression corresponding to
9234      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
9235   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
9236     {
9237       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9238       tree cst_uchar_ptr_node
9239         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9240
9241       tree ind1
9242         = fold_convert_loc (loc, integer_type_node,
9243                             build1 (INDIRECT_REF, cst_uchar_node,
9244                                     fold_convert_loc (loc,
9245                                                       cst_uchar_ptr_node,
9246                                                       arg1)));
9247       tree ind2
9248         = fold_convert_loc (loc, integer_type_node,
9249                             build1 (INDIRECT_REF, cst_uchar_node,
9250                                     fold_convert_loc (loc,
9251                                                       cst_uchar_ptr_node,
9252                                                       arg2)));
9253       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
9254     }
9255
9256   return NULL_TREE;
9257 }
9258
9259 /* Fold function call to builtin strcmp with arguments ARG1 and ARG2.
9260    Return NULL_TREE if no simplification can be made.  */
9261
9262 static tree
9263 fold_builtin_strcmp (location_t loc, tree arg1, tree arg2)
9264 {
9265   const char *p1, *p2;
9266
9267   if (!validate_arg (arg1, POINTER_TYPE)
9268       || !validate_arg (arg2, POINTER_TYPE))
9269     return NULL_TREE;
9270
9271   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
9272   if (operand_equal_p (arg1, arg2, 0))
9273     return integer_zero_node;
9274
9275   p1 = c_getstr (arg1);
9276   p2 = c_getstr (arg2);
9277
9278   if (p1 && p2)
9279     {
9280       const int i = strcmp (p1, p2);
9281       if (i < 0)
9282         return integer_minus_one_node;
9283       else if (i > 0)
9284         return integer_one_node;
9285       else
9286         return integer_zero_node;
9287     }
9288
9289   /* If the second arg is "", return *(const unsigned char*)arg1.  */
9290   if (p2 && *p2 == '\0')
9291     {
9292       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9293       tree cst_uchar_ptr_node
9294         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9295
9296       return fold_convert_loc (loc, integer_type_node,
9297                                build1 (INDIRECT_REF, cst_uchar_node,
9298                                        fold_convert_loc (loc,
9299                                                          cst_uchar_ptr_node,
9300                                                          arg1)));
9301     }
9302
9303   /* If the first arg is "", return -*(const unsigned char*)arg2.  */
9304   if (p1 && *p1 == '\0')
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       tree temp
9311         = fold_convert_loc (loc, integer_type_node,
9312                             build1 (INDIRECT_REF, cst_uchar_node,
9313                                     fold_convert_loc (loc,
9314                                                       cst_uchar_ptr_node,
9315                                                       arg2)));
9316       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
9317     }
9318
9319   return NULL_TREE;
9320 }
9321
9322 /* Fold function call to builtin strncmp with arguments ARG1, ARG2, and LEN.
9323    Return NULL_TREE if no simplification can be made.  */
9324
9325 static tree
9326 fold_builtin_strncmp (location_t loc, tree arg1, tree arg2, tree len)
9327 {
9328   const char *p1, *p2;
9329
9330   if (!validate_arg (arg1, POINTER_TYPE)
9331       || !validate_arg (arg2, POINTER_TYPE)
9332       || !validate_arg (len, INTEGER_TYPE))
9333     return NULL_TREE;
9334
9335   /* If the LEN parameter is zero, return zero.  */
9336   if (integer_zerop (len))
9337     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
9338                               arg1, arg2);
9339
9340   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
9341   if (operand_equal_p (arg1, arg2, 0))
9342     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
9343
9344   p1 = c_getstr (arg1);
9345   p2 = c_getstr (arg2);
9346
9347   if (host_integerp (len, 1) && p1 && p2)
9348     {
9349       const int i = strncmp (p1, p2, tree_low_cst (len, 1));
9350       if (i > 0)
9351         return integer_one_node;
9352       else if (i < 0)
9353         return integer_minus_one_node;
9354       else
9355         return integer_zero_node;
9356     }
9357
9358   /* If the second arg is "", and the length is greater than zero,
9359      return *(const unsigned char*)arg1.  */
9360   if (p2 && *p2 == '\0'
9361       && TREE_CODE (len) == INTEGER_CST
9362       && tree_int_cst_sgn (len) == 1)
9363     {
9364       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9365       tree cst_uchar_ptr_node
9366         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9367
9368       return fold_convert_loc (loc, integer_type_node,
9369                                build1 (INDIRECT_REF, cst_uchar_node,
9370                                        fold_convert_loc (loc,
9371                                                          cst_uchar_ptr_node,
9372                                                          arg1)));
9373     }
9374
9375   /* If the first arg is "", and the length is greater than zero,
9376      return -*(const unsigned char*)arg2.  */
9377   if (p1 && *p1 == '\0'
9378       && TREE_CODE (len) == INTEGER_CST
9379       && tree_int_cst_sgn (len) == 1)
9380     {
9381       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9382       tree cst_uchar_ptr_node
9383         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9384
9385       tree temp = fold_convert_loc (loc, integer_type_node,
9386                                     build1 (INDIRECT_REF, cst_uchar_node,
9387                                             fold_convert_loc (loc,
9388                                                               cst_uchar_ptr_node,
9389                                                               arg2)));
9390       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
9391     }
9392
9393   /* If len parameter is one, return an expression corresponding to
9394      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
9395   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
9396     {
9397       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9398       tree cst_uchar_ptr_node
9399         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9400
9401       tree ind1 = fold_convert_loc (loc, integer_type_node,
9402                                     build1 (INDIRECT_REF, cst_uchar_node,
9403                                             fold_convert_loc (loc,
9404                                                               cst_uchar_ptr_node,
9405                                                               arg1)));
9406       tree ind2 = fold_convert_loc (loc, integer_type_node,
9407                                     build1 (INDIRECT_REF, cst_uchar_node,
9408                                             fold_convert_loc (loc,
9409                                                               cst_uchar_ptr_node,
9410                                                               arg2)));
9411       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
9412     }
9413
9414   return NULL_TREE;
9415 }
9416
9417 /* Fold function call to builtin signbit, signbitf or signbitl with argument
9418    ARG.  Return NULL_TREE if no simplification can be made.  */
9419
9420 static tree
9421 fold_builtin_signbit (location_t loc, tree arg, tree type)
9422 {
9423   if (!validate_arg (arg, REAL_TYPE))
9424     return NULL_TREE;
9425
9426   /* If ARG is a compile-time constant, determine the result.  */
9427   if (TREE_CODE (arg) == REAL_CST
9428       && !TREE_OVERFLOW (arg))
9429     {
9430       REAL_VALUE_TYPE c;
9431
9432       c = TREE_REAL_CST (arg);
9433       return (REAL_VALUE_NEGATIVE (c)
9434               ? build_one_cst (type)
9435               : build_zero_cst (type));
9436     }
9437
9438   /* If ARG is non-negative, the result is always zero.  */
9439   if (tree_expr_nonnegative_p (arg))
9440     return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9441
9442   /* If ARG's format doesn't have signed zeros, return "arg < 0.0".  */
9443   if (!HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (arg))))
9444     return fold_convert (type,
9445                          fold_build2_loc (loc, LT_EXPR, boolean_type_node, arg,
9446                         build_real (TREE_TYPE (arg), dconst0)));
9447
9448   return NULL_TREE;
9449 }
9450
9451 /* Fold function call to builtin copysign, copysignf or copysignl with
9452    arguments ARG1 and ARG2.  Return NULL_TREE if no simplification can
9453    be made.  */
9454
9455 static tree
9456 fold_builtin_copysign (location_t loc, tree fndecl,
9457                        tree arg1, tree arg2, tree type)
9458 {
9459   tree tem;
9460
9461   if (!validate_arg (arg1, REAL_TYPE)
9462       || !validate_arg (arg2, REAL_TYPE))
9463     return NULL_TREE;
9464
9465   /* copysign(X,X) is X.  */
9466   if (operand_equal_p (arg1, arg2, 0))
9467     return fold_convert_loc (loc, type, arg1);
9468
9469   /* If ARG1 and ARG2 are compile-time constants, determine the result.  */
9470   if (TREE_CODE (arg1) == REAL_CST
9471       && TREE_CODE (arg2) == REAL_CST
9472       && !TREE_OVERFLOW (arg1)
9473       && !TREE_OVERFLOW (arg2))
9474     {
9475       REAL_VALUE_TYPE c1, c2;
9476
9477       c1 = TREE_REAL_CST (arg1);
9478       c2 = TREE_REAL_CST (arg2);
9479       /* c1.sign := c2.sign.  */
9480       real_copysign (&c1, &c2);
9481       return build_real (type, c1);
9482     }
9483
9484   /* copysign(X, Y) is fabs(X) when Y is always non-negative.
9485      Remember to evaluate Y for side-effects.  */
9486   if (tree_expr_nonnegative_p (arg2))
9487     return omit_one_operand_loc (loc, type,
9488                              fold_build1_loc (loc, ABS_EXPR, type, arg1),
9489                              arg2);
9490
9491   /* Strip sign changing operations for the first argument.  */
9492   tem = fold_strip_sign_ops (arg1);
9493   if (tem)
9494     return build_call_expr_loc (loc, fndecl, 2, tem, arg2);
9495
9496   return NULL_TREE;
9497 }
9498
9499 /* Fold a call to builtin isascii with argument ARG.  */
9500
9501 static tree
9502 fold_builtin_isascii (location_t loc, tree arg)
9503 {
9504   if (!validate_arg (arg, INTEGER_TYPE))
9505     return NULL_TREE;
9506   else
9507     {
9508       /* Transform isascii(c) -> ((c & ~0x7f) == 0).  */
9509       arg = fold_build2 (BIT_AND_EXPR, integer_type_node, arg,
9510                          build_int_cst (integer_type_node,
9511                                         ~ (unsigned HOST_WIDE_INT) 0x7f));
9512       return fold_build2_loc (loc, EQ_EXPR, integer_type_node,
9513                               arg, integer_zero_node);
9514     }
9515 }
9516
9517 /* Fold a call to builtin toascii with argument ARG.  */
9518
9519 static tree
9520 fold_builtin_toascii (location_t loc, tree arg)
9521 {
9522   if (!validate_arg (arg, INTEGER_TYPE))
9523     return NULL_TREE;
9524
9525   /* Transform toascii(c) -> (c & 0x7f).  */
9526   return fold_build2_loc (loc, BIT_AND_EXPR, integer_type_node, arg,
9527                           build_int_cst (integer_type_node, 0x7f));
9528 }
9529
9530 /* Fold a call to builtin isdigit with argument ARG.  */
9531
9532 static tree
9533 fold_builtin_isdigit (location_t loc, tree arg)
9534 {
9535   if (!validate_arg (arg, INTEGER_TYPE))
9536     return NULL_TREE;
9537   else
9538     {
9539       /* Transform isdigit(c) -> (unsigned)(c) - '0' <= 9.  */
9540       /* According to the C standard, isdigit is unaffected by locale.
9541          However, it definitely is affected by the target character set.  */
9542       unsigned HOST_WIDE_INT target_digit0
9543         = lang_hooks.to_target_charset ('0');
9544
9545       if (target_digit0 == 0)
9546         return NULL_TREE;
9547
9548       arg = fold_convert_loc (loc, unsigned_type_node, arg);
9549       arg = fold_build2 (MINUS_EXPR, unsigned_type_node, arg,
9550                          build_int_cst (unsigned_type_node, target_digit0));
9551       return fold_build2_loc (loc, LE_EXPR, integer_type_node, arg,
9552                           build_int_cst (unsigned_type_node, 9));
9553     }
9554 }
9555
9556 /* Fold a call to fabs, fabsf or fabsl with argument ARG.  */
9557
9558 static tree
9559 fold_builtin_fabs (location_t loc, tree arg, tree type)
9560 {
9561   if (!validate_arg (arg, REAL_TYPE))
9562     return NULL_TREE;
9563
9564   arg = fold_convert_loc (loc, type, arg);
9565   if (TREE_CODE (arg) == REAL_CST)
9566     return fold_abs_const (arg, type);
9567   return fold_build1_loc (loc, ABS_EXPR, type, arg);
9568 }
9569
9570 /* Fold a call to abs, labs, llabs or imaxabs with argument ARG.  */
9571
9572 static tree
9573 fold_builtin_abs (location_t loc, tree arg, tree type)
9574 {
9575   if (!validate_arg (arg, INTEGER_TYPE))
9576     return NULL_TREE;
9577
9578   arg = fold_convert_loc (loc, type, arg);
9579   if (TREE_CODE (arg) == INTEGER_CST)
9580     return fold_abs_const (arg, type);
9581   return fold_build1_loc (loc, ABS_EXPR, type, arg);
9582 }
9583
9584 /* Fold a fma operation with arguments ARG[012].  */
9585
9586 tree
9587 fold_fma (location_t loc ATTRIBUTE_UNUSED,
9588           tree type, tree arg0, tree arg1, tree arg2)
9589 {
9590   if (TREE_CODE (arg0) == REAL_CST
9591       && TREE_CODE (arg1) == REAL_CST
9592       && TREE_CODE (arg2) == REAL_CST)
9593     return do_mpfr_arg3 (arg0, arg1, arg2, type, mpfr_fma);
9594
9595   return NULL_TREE;
9596 }
9597
9598 /* Fold a call to fma, fmaf, or fmal with arguments ARG[012].  */
9599
9600 static tree
9601 fold_builtin_fma (location_t loc, tree arg0, tree arg1, tree arg2, tree type)
9602 {
9603   if (validate_arg (arg0, REAL_TYPE)
9604       && validate_arg(arg1, REAL_TYPE)
9605       && validate_arg(arg2, REAL_TYPE))
9606     {
9607       tree tem = fold_fma (loc, type, arg0, arg1, arg2);
9608       if (tem)
9609         return tem;
9610
9611       /* ??? Only expand to FMA_EXPR if it's directly supported.  */
9612       if (optab_handler (fma_optab, TYPE_MODE (type)) != CODE_FOR_nothing)
9613         return fold_build3_loc (loc, FMA_EXPR, type, arg0, arg1, arg2);
9614     }
9615   return NULL_TREE;
9616 }
9617
9618 /* Fold a call to builtin fmin or fmax.  */
9619
9620 static tree
9621 fold_builtin_fmin_fmax (location_t loc, tree arg0, tree arg1,
9622                         tree type, bool max)
9623 {
9624   if (validate_arg (arg0, REAL_TYPE) && validate_arg (arg1, REAL_TYPE))
9625     {
9626       /* Calculate the result when the argument is a constant.  */
9627       tree res = do_mpfr_arg2 (arg0, arg1, type, (max ? mpfr_max : mpfr_min));
9628
9629       if (res)
9630         return res;
9631
9632       /* If either argument is NaN, return the other one.  Avoid the
9633          transformation if we get (and honor) a signalling NaN.  Using
9634          omit_one_operand() ensures we create a non-lvalue.  */
9635       if (TREE_CODE (arg0) == REAL_CST
9636           && real_isnan (&TREE_REAL_CST (arg0))
9637           && (! HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg0)))
9638               || ! TREE_REAL_CST (arg0).signalling))
9639         return omit_one_operand_loc (loc, type, arg1, arg0);
9640       if (TREE_CODE (arg1) == REAL_CST
9641           && real_isnan (&TREE_REAL_CST (arg1))
9642           && (! HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg1)))
9643               || ! TREE_REAL_CST (arg1).signalling))
9644         return omit_one_operand_loc (loc, type, arg0, arg1);
9645
9646       /* Transform fmin/fmax(x,x) -> x.  */
9647       if (operand_equal_p (arg0, arg1, OEP_PURE_SAME))
9648         return omit_one_operand_loc (loc, type, arg0, arg1);
9649
9650       /* Convert fmin/fmax to MIN_EXPR/MAX_EXPR.  C99 requires these
9651          functions to return the numeric arg if the other one is NaN.
9652          These tree codes don't honor that, so only transform if
9653          -ffinite-math-only is set.  C99 doesn't require -0.0 to be
9654          handled, so we don't have to worry about it either.  */
9655       if (flag_finite_math_only)
9656         return fold_build2_loc (loc, (max ? MAX_EXPR : MIN_EXPR), type,
9657                             fold_convert_loc (loc, type, arg0),
9658                             fold_convert_loc (loc, type, arg1));
9659     }
9660   return NULL_TREE;
9661 }
9662
9663 /* Fold a call to builtin carg(a+bi) -> atan2(b,a).  */
9664
9665 static tree
9666 fold_builtin_carg (location_t loc, tree arg, tree type)
9667 {
9668   if (validate_arg (arg, COMPLEX_TYPE)
9669       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE)
9670     {
9671       tree atan2_fn = mathfn_built_in (type, BUILT_IN_ATAN2);
9672
9673       if (atan2_fn)
9674         {
9675           tree new_arg = builtin_save_expr (arg);
9676           tree r_arg = fold_build1_loc (loc, REALPART_EXPR, type, new_arg);
9677           tree i_arg = fold_build1_loc (loc, IMAGPART_EXPR, type, new_arg);
9678           return build_call_expr_loc (loc, atan2_fn, 2, i_arg, r_arg);
9679         }
9680     }
9681
9682   return NULL_TREE;
9683 }
9684
9685 /* Fold a call to builtin logb/ilogb.  */
9686
9687 static tree
9688 fold_builtin_logb (location_t loc, tree arg, tree rettype)
9689 {
9690   if (! validate_arg (arg, REAL_TYPE))
9691     return NULL_TREE;
9692
9693   STRIP_NOPS (arg);
9694
9695   if (TREE_CODE (arg) == REAL_CST && ! TREE_OVERFLOW (arg))
9696     {
9697       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg);
9698
9699       switch (value->cl)
9700       {
9701       case rvc_nan:
9702       case rvc_inf:
9703         /* If arg is Inf or NaN and we're logb, return it.  */
9704         if (TREE_CODE (rettype) == REAL_TYPE)
9705           {
9706             /* For logb(-Inf) we have to return +Inf.  */
9707             if (real_isinf (value) && real_isneg (value))
9708               {
9709                 REAL_VALUE_TYPE tem;
9710                 real_inf (&tem);
9711                 return build_real (rettype, tem);
9712               }
9713             return fold_convert_loc (loc, rettype, arg);
9714           }
9715         /* Fall through... */
9716       case rvc_zero:
9717         /* Zero may set errno and/or raise an exception for logb, also
9718            for ilogb we don't know FP_ILOGB0.  */
9719         return NULL_TREE;
9720       case rvc_normal:
9721         /* For normal numbers, proceed iff radix == 2.  In GCC,
9722            normalized significands are in the range [0.5, 1.0).  We
9723            want the exponent as if they were [1.0, 2.0) so get the
9724            exponent and subtract 1.  */
9725         if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->b == 2)
9726           return fold_convert_loc (loc, rettype,
9727                                    build_int_cst (integer_type_node,
9728                                                   REAL_EXP (value)-1));
9729         break;
9730       }
9731     }
9732
9733   return NULL_TREE;
9734 }
9735
9736 /* Fold a call to builtin significand, if radix == 2.  */
9737
9738 static tree
9739 fold_builtin_significand (location_t loc, tree arg, tree rettype)
9740 {
9741   if (! validate_arg (arg, REAL_TYPE))
9742     return NULL_TREE;
9743
9744   STRIP_NOPS (arg);
9745
9746   if (TREE_CODE (arg) == REAL_CST && ! TREE_OVERFLOW (arg))
9747     {
9748       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg);
9749
9750       switch (value->cl)
9751       {
9752       case rvc_zero:
9753       case rvc_nan:
9754       case rvc_inf:
9755         /* If arg is +-0, +-Inf or +-NaN, then return it.  */
9756         return fold_convert_loc (loc, rettype, arg);
9757       case rvc_normal:
9758         /* For normal numbers, proceed iff radix == 2.  */
9759         if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->b == 2)
9760           {
9761             REAL_VALUE_TYPE result = *value;
9762             /* In GCC, normalized significands are in the range [0.5,
9763                1.0).  We want them to be [1.0, 2.0) so set the
9764                exponent to 1.  */
9765             SET_REAL_EXP (&result, 1);
9766             return build_real (rettype, result);
9767           }
9768         break;
9769       }
9770     }
9771
9772   return NULL_TREE;
9773 }
9774
9775 /* Fold a call to builtin frexp, we can assume the base is 2.  */
9776
9777 static tree
9778 fold_builtin_frexp (location_t loc, tree arg0, tree arg1, tree rettype)
9779 {
9780   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
9781     return NULL_TREE;
9782
9783   STRIP_NOPS (arg0);
9784
9785   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
9786     return NULL_TREE;
9787
9788   arg1 = build_fold_indirect_ref_loc (loc, arg1);
9789
9790   /* Proceed if a valid pointer type was passed in.  */
9791   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == integer_type_node)
9792     {
9793       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
9794       tree frac, exp;
9795
9796       switch (value->cl)
9797       {
9798       case rvc_zero:
9799         /* For +-0, return (*exp = 0, +-0).  */
9800         exp = integer_zero_node;
9801         frac = arg0;
9802         break;
9803       case rvc_nan:
9804       case rvc_inf:
9805         /* For +-NaN or +-Inf, *exp is unspecified, return arg0.  */
9806         return omit_one_operand_loc (loc, rettype, arg0, arg1);
9807       case rvc_normal:
9808         {
9809           /* Since the frexp function always expects base 2, and in
9810              GCC normalized significands are already in the range
9811              [0.5, 1.0), we have exactly what frexp wants.  */
9812           REAL_VALUE_TYPE frac_rvt = *value;
9813           SET_REAL_EXP (&frac_rvt, 0);
9814           frac = build_real (rettype, frac_rvt);
9815           exp = build_int_cst (integer_type_node, REAL_EXP (value));
9816         }
9817         break;
9818       default:
9819         gcc_unreachable ();
9820       }
9821
9822       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
9823       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1, exp);
9824       TREE_SIDE_EFFECTS (arg1) = 1;
9825       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1, frac);
9826     }
9827
9828   return NULL_TREE;
9829 }
9830
9831 /* Fold a call to builtin ldexp or scalbn/scalbln.  If LDEXP is true
9832    then we can assume the base is two.  If it's false, then we have to
9833    check the mode of the TYPE parameter in certain cases.  */
9834
9835 static tree
9836 fold_builtin_load_exponent (location_t loc, tree arg0, tree arg1,
9837                             tree type, bool ldexp)
9838 {
9839   if (validate_arg (arg0, REAL_TYPE) && validate_arg (arg1, INTEGER_TYPE))
9840     {
9841       STRIP_NOPS (arg0);
9842       STRIP_NOPS (arg1);
9843
9844       /* If arg0 is 0, Inf or NaN, or if arg1 is 0, then return arg0.  */
9845       if (real_zerop (arg0) || integer_zerop (arg1)
9846           || (TREE_CODE (arg0) == REAL_CST
9847               && !real_isfinite (&TREE_REAL_CST (arg0))))
9848         return omit_one_operand_loc (loc, type, arg0, arg1);
9849
9850       /* If both arguments are constant, then try to evaluate it.  */
9851       if ((ldexp || REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2)
9852           && TREE_CODE (arg0) == REAL_CST && !TREE_OVERFLOW (arg0)
9853           && host_integerp (arg1, 0))
9854         {
9855           /* Bound the maximum adjustment to twice the range of the
9856              mode's valid exponents.  Use abs to ensure the range is
9857              positive as a sanity check.  */
9858           const long max_exp_adj = 2 *
9859             labs (REAL_MODE_FORMAT (TYPE_MODE (type))->emax
9860                  - REAL_MODE_FORMAT (TYPE_MODE (type))->emin);
9861
9862           /* Get the user-requested adjustment.  */
9863           const HOST_WIDE_INT req_exp_adj = tree_low_cst (arg1, 0);
9864
9865           /* The requested adjustment must be inside this range.  This
9866              is a preliminary cap to avoid things like overflow, we
9867              may still fail to compute the result for other reasons.  */
9868           if (-max_exp_adj < req_exp_adj && req_exp_adj < max_exp_adj)
9869             {
9870               REAL_VALUE_TYPE initial_result;
9871
9872               real_ldexp (&initial_result, &TREE_REAL_CST (arg0), req_exp_adj);
9873
9874               /* Ensure we didn't overflow.  */
9875               if (! real_isinf (&initial_result))
9876                 {
9877                   const REAL_VALUE_TYPE trunc_result
9878                     = real_value_truncate (TYPE_MODE (type), initial_result);
9879
9880                   /* Only proceed if the target mode can hold the
9881                      resulting value.  */
9882                   if (REAL_VALUES_EQUAL (initial_result, trunc_result))
9883                     return build_real (type, trunc_result);
9884                 }
9885             }
9886         }
9887     }
9888
9889   return NULL_TREE;
9890 }
9891
9892 /* Fold a call to builtin modf.  */
9893
9894 static tree
9895 fold_builtin_modf (location_t loc, tree arg0, tree arg1, tree rettype)
9896 {
9897   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
9898     return NULL_TREE;
9899
9900   STRIP_NOPS (arg0);
9901
9902   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
9903     return NULL_TREE;
9904
9905   arg1 = build_fold_indirect_ref_loc (loc, arg1);
9906
9907   /* Proceed if a valid pointer type was passed in.  */
9908   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == TYPE_MAIN_VARIANT (rettype))
9909     {
9910       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
9911       REAL_VALUE_TYPE trunc, frac;
9912
9913       switch (value->cl)
9914       {
9915       case rvc_nan:
9916       case rvc_zero:
9917         /* For +-NaN or +-0, return (*arg1 = arg0, arg0).  */
9918         trunc = frac = *value;
9919         break;
9920       case rvc_inf:
9921         /* For +-Inf, return (*arg1 = arg0, +-0).  */
9922         frac = dconst0;
9923         frac.sign = value->sign;
9924         trunc = *value;
9925         break;
9926       case rvc_normal:
9927         /* Return (*arg1 = trunc(arg0), arg0-trunc(arg0)).  */
9928         real_trunc (&trunc, VOIDmode, value);
9929         real_arithmetic (&frac, MINUS_EXPR, value, &trunc);
9930         /* If the original number was negative and already
9931            integral, then the fractional part is -0.0.  */
9932         if (value->sign && frac.cl == rvc_zero)
9933           frac.sign = value->sign;
9934         break;
9935       }
9936
9937       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
9938       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1,
9939                           build_real (rettype, trunc));
9940       TREE_SIDE_EFFECTS (arg1) = 1;
9941       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1,
9942                           build_real (rettype, frac));
9943     }
9944
9945   return NULL_TREE;
9946 }
9947
9948 /* Given a location LOC, an interclass builtin function decl FNDECL
9949    and its single argument ARG, return an folded expression computing
9950    the same, or NULL_TREE if we either couldn't or didn't want to fold
9951    (the latter happen if there's an RTL instruction available).  */
9952
9953 static tree
9954 fold_builtin_interclass_mathfn (location_t loc, tree fndecl, tree arg)
9955 {
9956   enum machine_mode mode;
9957
9958   if (!validate_arg (arg, REAL_TYPE))
9959     return NULL_TREE;
9960
9961   if (interclass_mathfn_icode (arg, fndecl) != CODE_FOR_nothing)
9962     return NULL_TREE;
9963
9964   mode = TYPE_MODE (TREE_TYPE (arg));
9965
9966   /* If there is no optab, try generic code.  */
9967   switch (DECL_FUNCTION_CODE (fndecl))
9968     {
9969       tree result;
9970
9971     CASE_FLT_FN (BUILT_IN_ISINF):
9972       {
9973         /* isinf(x) -> isgreater(fabs(x),DBL_MAX).  */
9974         tree const isgr_fn = builtin_decl_explicit (BUILT_IN_ISGREATER);
9975         tree const type = TREE_TYPE (arg);
9976         REAL_VALUE_TYPE r;
9977         char buf[128];
9978
9979         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9980         real_from_string (&r, buf);
9981         result = build_call_expr (isgr_fn, 2,
9982                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9983                                   build_real (type, r));
9984         return result;
9985       }
9986     CASE_FLT_FN (BUILT_IN_FINITE):
9987     case BUILT_IN_ISFINITE:
9988       {
9989         /* isfinite(x) -> islessequal(fabs(x),DBL_MAX).  */
9990         tree const isle_fn = builtin_decl_explicit (BUILT_IN_ISLESSEQUAL);
9991         tree const type = TREE_TYPE (arg);
9992         REAL_VALUE_TYPE r;
9993         char buf[128];
9994
9995         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9996         real_from_string (&r, buf);
9997         result = build_call_expr (isle_fn, 2,
9998                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9999                                   build_real (type, r));
10000         /*result = fold_build2_loc (loc, UNGT_EXPR,
10001                                   TREE_TYPE (TREE_TYPE (fndecl)),
10002                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
10003                                   build_real (type, r));
10004         result = fold_build1_loc (loc, TRUTH_NOT_EXPR,
10005                                   TREE_TYPE (TREE_TYPE (fndecl)),
10006                                   result);*/
10007         return result;
10008       }
10009     case BUILT_IN_ISNORMAL:
10010       {
10011         /* isnormal(x) -> isgreaterequal(fabs(x),DBL_MIN) &
10012            islessequal(fabs(x),DBL_MAX).  */
10013         tree const isle_fn = builtin_decl_explicit (BUILT_IN_ISLESSEQUAL);
10014         tree const isge_fn = builtin_decl_explicit (BUILT_IN_ISGREATEREQUAL);
10015         tree const type = TREE_TYPE (arg);
10016         REAL_VALUE_TYPE rmax, rmin;
10017         char buf[128];
10018
10019         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
10020         real_from_string (&rmax, buf);
10021         sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (mode)->emin - 1);
10022         real_from_string (&rmin, buf);
10023         arg = builtin_save_expr (fold_build1_loc (loc, ABS_EXPR, type, arg));
10024         result = build_call_expr (isle_fn, 2, arg,
10025                                   build_real (type, rmax));
10026         result = fold_build2 (BIT_AND_EXPR, integer_type_node, result,
10027                               build_call_expr (isge_fn, 2, arg,
10028                                                build_real (type, rmin)));
10029         return result;
10030       }
10031     default:
10032       break;
10033     }
10034
10035   return NULL_TREE;
10036 }
10037
10038 /* Fold a call to __builtin_isnan(), __builtin_isinf, __builtin_finite.
10039    ARG is the argument for the call.  */
10040
10041 static tree
10042 fold_builtin_classify (location_t loc, tree fndecl, tree arg, int builtin_index)
10043 {
10044   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10045   REAL_VALUE_TYPE r;
10046
10047   if (!validate_arg (arg, REAL_TYPE))
10048     return NULL_TREE;
10049
10050   switch (builtin_index)
10051     {
10052     case BUILT_IN_ISINF:
10053       if (!HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
10054         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
10055
10056       if (TREE_CODE (arg) == REAL_CST)
10057         {
10058           r = TREE_REAL_CST (arg);
10059           if (real_isinf (&r))
10060             return real_compare (GT_EXPR, &r, &dconst0)
10061                    ? integer_one_node : integer_minus_one_node;
10062           else
10063             return integer_zero_node;
10064         }
10065
10066       return NULL_TREE;
10067
10068     case BUILT_IN_ISINF_SIGN:
10069       {
10070         /* isinf_sign(x) -> isinf(x) ? (signbit(x) ? -1 : 1) : 0 */
10071         /* In a boolean context, GCC will fold the inner COND_EXPR to
10072            1.  So e.g. "if (isinf_sign(x))" would be folded to just
10073            "if (isinf(x) ? 1 : 0)" which becomes "if (isinf(x))". */
10074         tree signbit_fn = mathfn_built_in_1 (TREE_TYPE (arg), BUILT_IN_SIGNBIT, 0);
10075         tree isinf_fn = builtin_decl_explicit (BUILT_IN_ISINF);
10076         tree tmp = NULL_TREE;
10077
10078         arg = builtin_save_expr (arg);
10079
10080         if (signbit_fn && isinf_fn)
10081           {
10082             tree signbit_call = build_call_expr_loc (loc, signbit_fn, 1, arg);
10083             tree isinf_call = build_call_expr_loc (loc, isinf_fn, 1, arg);
10084
10085             signbit_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
10086                                         signbit_call, integer_zero_node);
10087             isinf_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
10088                                       isinf_call, integer_zero_node);
10089
10090             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node, signbit_call,
10091                                integer_minus_one_node, integer_one_node);
10092             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node,
10093                                isinf_call, tmp,
10094                                integer_zero_node);
10095           }
10096
10097         return tmp;
10098       }
10099
10100     case BUILT_IN_ISFINITE:
10101       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg)))
10102           && !HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
10103         return omit_one_operand_loc (loc, type, integer_one_node, arg);
10104
10105       if (TREE_CODE (arg) == REAL_CST)
10106         {
10107           r = TREE_REAL_CST (arg);
10108           return real_isfinite (&r) ? integer_one_node : integer_zero_node;
10109         }
10110
10111       return NULL_TREE;
10112
10113     case BUILT_IN_ISNAN:
10114       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg))))
10115         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
10116
10117       if (TREE_CODE (arg) == REAL_CST)
10118         {
10119           r = TREE_REAL_CST (arg);
10120           return real_isnan (&r) ? integer_one_node : integer_zero_node;
10121         }
10122
10123       arg = builtin_save_expr (arg);
10124       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg, arg);
10125
10126     default:
10127       gcc_unreachable ();
10128     }
10129 }
10130
10131 /* Fold a call to __builtin_fpclassify(int, int, int, int, int, ...).
10132    This builtin will generate code to return the appropriate floating
10133    point classification depending on the value of the floating point
10134    number passed in.  The possible return values must be supplied as
10135    int arguments to the call in the following order: FP_NAN, FP_INFINITE,
10136    FP_NORMAL, FP_SUBNORMAL and FP_ZERO.  The ellipses is for exactly
10137    one floating point argument which is "type generic".  */
10138
10139 static tree
10140 fold_builtin_fpclassify (location_t loc, tree exp)
10141 {
10142   tree fp_nan, fp_infinite, fp_normal, fp_subnormal, fp_zero,
10143     arg, type, res, tmp;
10144   enum machine_mode mode;
10145   REAL_VALUE_TYPE r;
10146   char buf[128];
10147
10148   /* Verify the required arguments in the original call.  */
10149   if (!validate_arglist (exp, INTEGER_TYPE, INTEGER_TYPE,
10150                          INTEGER_TYPE, INTEGER_TYPE,
10151                          INTEGER_TYPE, REAL_TYPE, VOID_TYPE))
10152     return NULL_TREE;
10153
10154   fp_nan = CALL_EXPR_ARG (exp, 0);
10155   fp_infinite = CALL_EXPR_ARG (exp, 1);
10156   fp_normal = CALL_EXPR_ARG (exp, 2);
10157   fp_subnormal = CALL_EXPR_ARG (exp, 3);
10158   fp_zero = CALL_EXPR_ARG (exp, 4);
10159   arg = CALL_EXPR_ARG (exp, 5);
10160   type = TREE_TYPE (arg);
10161   mode = TYPE_MODE (type);
10162   arg = builtin_save_expr (fold_build1_loc (loc, ABS_EXPR, type, arg));
10163
10164   /* fpclassify(x) ->
10165        isnan(x) ? FP_NAN :
10166          (fabs(x) == Inf ? FP_INFINITE :
10167            (fabs(x) >= DBL_MIN ? FP_NORMAL :
10168              (x == 0 ? FP_ZERO : FP_SUBNORMAL))).  */
10169
10170   tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
10171                      build_real (type, dconst0));
10172   res = fold_build3_loc (loc, COND_EXPR, integer_type_node,
10173                      tmp, fp_zero, fp_subnormal);
10174
10175   sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (mode)->emin - 1);
10176   real_from_string (&r, buf);
10177   tmp = fold_build2_loc (loc, GE_EXPR, integer_type_node,
10178                      arg, build_real (type, r));
10179   res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, fp_normal, res);
10180
10181   if (HONOR_INFINITIES (mode))
10182     {
10183       real_inf (&r);
10184       tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
10185                          build_real (type, r));
10186       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp,
10187                          fp_infinite, res);
10188     }
10189
10190   if (HONOR_NANS (mode))
10191     {
10192       tmp = fold_build2_loc (loc, ORDERED_EXPR, integer_type_node, arg, arg);
10193       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, res, fp_nan);
10194     }
10195
10196   return res;
10197 }
10198
10199 /* Fold a call to an unordered comparison function such as
10200    __builtin_isgreater().  FNDECL is the FUNCTION_DECL for the function
10201    being called and ARG0 and ARG1 are the arguments for the call.
10202    UNORDERED_CODE and ORDERED_CODE are comparison codes that give
10203    the opposite of the desired result.  UNORDERED_CODE is used
10204    for modes that can hold NaNs and ORDERED_CODE is used for
10205    the rest.  */
10206
10207 static tree
10208 fold_builtin_unordered_cmp (location_t loc, tree fndecl, tree arg0, tree arg1,
10209                             enum tree_code unordered_code,
10210                             enum tree_code ordered_code)
10211 {
10212   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10213   enum tree_code code;
10214   tree type0, type1;
10215   enum tree_code code0, code1;
10216   tree cmp_type = NULL_TREE;
10217
10218   type0 = TREE_TYPE (arg0);
10219   type1 = TREE_TYPE (arg1);
10220
10221   code0 = TREE_CODE (type0);
10222   code1 = TREE_CODE (type1);
10223
10224   if (code0 == REAL_TYPE && code1 == REAL_TYPE)
10225     /* Choose the wider of two real types.  */
10226     cmp_type = TYPE_PRECISION (type0) >= TYPE_PRECISION (type1)
10227       ? type0 : type1;
10228   else if (code0 == REAL_TYPE && code1 == INTEGER_TYPE)
10229     cmp_type = type0;
10230   else if (code0 == INTEGER_TYPE && code1 == REAL_TYPE)
10231     cmp_type = type1;
10232
10233   arg0 = fold_convert_loc (loc, cmp_type, arg0);
10234   arg1 = fold_convert_loc (loc, cmp_type, arg1);
10235
10236   if (unordered_code == UNORDERED_EXPR)
10237     {
10238       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))))
10239         return omit_two_operands_loc (loc, type, integer_zero_node, arg0, arg1);
10240       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg0, arg1);
10241     }
10242
10243   code = HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))) ? unordered_code
10244                                                    : ordered_code;
10245   return fold_build1_loc (loc, TRUTH_NOT_EXPR, type,
10246                       fold_build2_loc (loc, code, type, arg0, arg1));
10247 }
10248
10249 /* Fold a call to built-in function FNDECL with 0 arguments.
10250    IGNORE is true if the result of the function call is ignored.  This
10251    function returns NULL_TREE if no simplification was possible.  */
10252
10253 static tree
10254 fold_builtin_0 (location_t loc, tree fndecl, bool ignore ATTRIBUTE_UNUSED)
10255 {
10256   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10257   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10258   switch (fcode)
10259     {
10260     CASE_FLT_FN (BUILT_IN_INF):
10261     case BUILT_IN_INFD32:
10262     case BUILT_IN_INFD64:
10263     case BUILT_IN_INFD128:
10264       return fold_builtin_inf (loc, type, true);
10265
10266     CASE_FLT_FN (BUILT_IN_HUGE_VAL):
10267       return fold_builtin_inf (loc, type, false);
10268
10269     case BUILT_IN_CLASSIFY_TYPE:
10270       return fold_builtin_classify_type (NULL_TREE);
10271
10272     default:
10273       break;
10274     }
10275   return NULL_TREE;
10276 }
10277
10278 /* Fold a call to built-in function FNDECL with 1 argument, ARG0.
10279    IGNORE is true if the result of the function call is ignored.  This
10280    function returns NULL_TREE if no simplification was possible.  */
10281
10282 static tree
10283 fold_builtin_1 (location_t loc, tree fndecl, tree arg0, bool ignore)
10284 {
10285   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10286   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10287   switch (fcode)
10288     {
10289     case BUILT_IN_CONSTANT_P:
10290       {
10291         tree val = fold_builtin_constant_p (arg0);
10292
10293         /* Gimplification will pull the CALL_EXPR for the builtin out of
10294            an if condition.  When not optimizing, we'll not CSE it back.
10295            To avoid link error types of regressions, return false now.  */
10296         if (!val && !optimize)
10297           val = integer_zero_node;
10298
10299         return val;
10300       }
10301
10302     case BUILT_IN_CLASSIFY_TYPE:
10303       return fold_builtin_classify_type (arg0);
10304
10305     case BUILT_IN_STRLEN:
10306       return fold_builtin_strlen (loc, type, arg0);
10307
10308     CASE_FLT_FN (BUILT_IN_FABS):
10309       return fold_builtin_fabs (loc, arg0, type);
10310
10311     case BUILT_IN_ABS:
10312     case BUILT_IN_LABS:
10313     case BUILT_IN_LLABS:
10314     case BUILT_IN_IMAXABS:
10315       return fold_builtin_abs (loc, arg0, type);
10316
10317     CASE_FLT_FN (BUILT_IN_CONJ):
10318       if (validate_arg (arg0, COMPLEX_TYPE)
10319         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10320         return fold_build1_loc (loc, CONJ_EXPR, type, arg0);
10321     break;
10322
10323     CASE_FLT_FN (BUILT_IN_CREAL):
10324       if (validate_arg (arg0, COMPLEX_TYPE)
10325         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10326         return non_lvalue_loc (loc, fold_build1_loc (loc, REALPART_EXPR, type, arg0));;
10327     break;
10328
10329     CASE_FLT_FN (BUILT_IN_CIMAG):
10330       if (validate_arg (arg0, COMPLEX_TYPE)
10331           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10332         return non_lvalue_loc (loc, fold_build1_loc (loc, IMAGPART_EXPR, type, arg0));
10333     break;
10334
10335     CASE_FLT_FN (BUILT_IN_CCOS):
10336       return fold_builtin_ccos(loc, arg0, type, fndecl, /*hyper=*/ false);
10337
10338     CASE_FLT_FN (BUILT_IN_CCOSH):
10339       return fold_builtin_ccos(loc, arg0, type, fndecl, /*hyper=*/ true);
10340
10341     CASE_FLT_FN (BUILT_IN_CPROJ):
10342       return fold_builtin_cproj(loc, arg0, type);
10343
10344     CASE_FLT_FN (BUILT_IN_CSIN):
10345       if (validate_arg (arg0, COMPLEX_TYPE)
10346           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10347         return do_mpc_arg1 (arg0, type, mpc_sin);
10348     break;
10349
10350     CASE_FLT_FN (BUILT_IN_CSINH):
10351       if (validate_arg (arg0, COMPLEX_TYPE)
10352           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10353         return do_mpc_arg1 (arg0, type, mpc_sinh);
10354     break;
10355
10356     CASE_FLT_FN (BUILT_IN_CTAN):
10357       if (validate_arg (arg0, COMPLEX_TYPE)
10358           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10359         return do_mpc_arg1 (arg0, type, mpc_tan);
10360     break;
10361
10362     CASE_FLT_FN (BUILT_IN_CTANH):
10363       if (validate_arg (arg0, COMPLEX_TYPE)
10364           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10365         return do_mpc_arg1 (arg0, type, mpc_tanh);
10366     break;
10367
10368     CASE_FLT_FN (BUILT_IN_CLOG):
10369       if (validate_arg (arg0, COMPLEX_TYPE)
10370           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10371         return do_mpc_arg1 (arg0, type, mpc_log);
10372     break;
10373
10374     CASE_FLT_FN (BUILT_IN_CSQRT):
10375       if (validate_arg (arg0, COMPLEX_TYPE)
10376           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10377         return do_mpc_arg1 (arg0, type, mpc_sqrt);
10378     break;
10379
10380     CASE_FLT_FN (BUILT_IN_CASIN):
10381       if (validate_arg (arg0, COMPLEX_TYPE)
10382           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10383         return do_mpc_arg1 (arg0, type, mpc_asin);
10384     break;
10385
10386     CASE_FLT_FN (BUILT_IN_CACOS):
10387       if (validate_arg (arg0, COMPLEX_TYPE)
10388           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10389         return do_mpc_arg1 (arg0, type, mpc_acos);
10390     break;
10391
10392     CASE_FLT_FN (BUILT_IN_CATAN):
10393       if (validate_arg (arg0, COMPLEX_TYPE)
10394           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10395         return do_mpc_arg1 (arg0, type, mpc_atan);
10396     break;
10397
10398     CASE_FLT_FN (BUILT_IN_CASINH):
10399       if (validate_arg (arg0, COMPLEX_TYPE)
10400           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10401         return do_mpc_arg1 (arg0, type, mpc_asinh);
10402     break;
10403
10404     CASE_FLT_FN (BUILT_IN_CACOSH):
10405       if (validate_arg (arg0, COMPLEX_TYPE)
10406           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10407         return do_mpc_arg1 (arg0, type, mpc_acosh);
10408     break;
10409
10410     CASE_FLT_FN (BUILT_IN_CATANH):
10411       if (validate_arg (arg0, COMPLEX_TYPE)
10412           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10413         return do_mpc_arg1 (arg0, type, mpc_atanh);
10414     break;
10415
10416     CASE_FLT_FN (BUILT_IN_CABS):
10417       return fold_builtin_cabs (loc, arg0, type, fndecl);
10418
10419     CASE_FLT_FN (BUILT_IN_CARG):
10420       return fold_builtin_carg (loc, arg0, type);
10421
10422     CASE_FLT_FN (BUILT_IN_SQRT):
10423       return fold_builtin_sqrt (loc, arg0, type);
10424
10425     CASE_FLT_FN (BUILT_IN_CBRT):
10426       return fold_builtin_cbrt (loc, arg0, type);
10427
10428     CASE_FLT_FN (BUILT_IN_ASIN):
10429       if (validate_arg (arg0, REAL_TYPE))
10430         return do_mpfr_arg1 (arg0, type, mpfr_asin,
10431                              &dconstm1, &dconst1, true);
10432     break;
10433
10434     CASE_FLT_FN (BUILT_IN_ACOS):
10435       if (validate_arg (arg0, REAL_TYPE))
10436         return do_mpfr_arg1 (arg0, type, mpfr_acos,
10437                              &dconstm1, &dconst1, true);
10438     break;
10439
10440     CASE_FLT_FN (BUILT_IN_ATAN):
10441       if (validate_arg (arg0, REAL_TYPE))
10442         return do_mpfr_arg1 (arg0, type, mpfr_atan, NULL, NULL, 0);
10443     break;
10444
10445     CASE_FLT_FN (BUILT_IN_ASINH):
10446       if (validate_arg (arg0, REAL_TYPE))
10447         return do_mpfr_arg1 (arg0, type, mpfr_asinh, NULL, NULL, 0);
10448     break;
10449
10450     CASE_FLT_FN (BUILT_IN_ACOSH):
10451       if (validate_arg (arg0, REAL_TYPE))
10452         return do_mpfr_arg1 (arg0, type, mpfr_acosh,
10453                              &dconst1, NULL, true);
10454     break;
10455
10456     CASE_FLT_FN (BUILT_IN_ATANH):
10457       if (validate_arg (arg0, REAL_TYPE))
10458         return do_mpfr_arg1 (arg0, type, mpfr_atanh,
10459                              &dconstm1, &dconst1, false);
10460     break;
10461
10462     CASE_FLT_FN (BUILT_IN_SIN):
10463       if (validate_arg (arg0, REAL_TYPE))
10464         return do_mpfr_arg1 (arg0, type, mpfr_sin, NULL, NULL, 0);
10465     break;
10466
10467     CASE_FLT_FN (BUILT_IN_COS):
10468       return fold_builtin_cos (loc, arg0, type, fndecl);
10469
10470     CASE_FLT_FN (BUILT_IN_TAN):
10471       return fold_builtin_tan (arg0, type);
10472
10473     CASE_FLT_FN (BUILT_IN_CEXP):
10474       return fold_builtin_cexp (loc, arg0, type);
10475
10476     CASE_FLT_FN (BUILT_IN_CEXPI):
10477       if (validate_arg (arg0, REAL_TYPE))
10478         return do_mpfr_sincos (arg0, NULL_TREE, NULL_TREE);
10479     break;
10480
10481     CASE_FLT_FN (BUILT_IN_SINH):
10482       if (validate_arg (arg0, REAL_TYPE))
10483         return do_mpfr_arg1 (arg0, type, mpfr_sinh, NULL, NULL, 0);
10484     break;
10485
10486     CASE_FLT_FN (BUILT_IN_COSH):
10487       return fold_builtin_cosh (loc, arg0, type, fndecl);
10488
10489     CASE_FLT_FN (BUILT_IN_TANH):
10490       if (validate_arg (arg0, REAL_TYPE))
10491         return do_mpfr_arg1 (arg0, type, mpfr_tanh, NULL, NULL, 0);
10492     break;
10493
10494     CASE_FLT_FN (BUILT_IN_ERF):
10495       if (validate_arg (arg0, REAL_TYPE))
10496         return do_mpfr_arg1 (arg0, type, mpfr_erf, NULL, NULL, 0);
10497     break;
10498
10499     CASE_FLT_FN (BUILT_IN_ERFC):
10500       if (validate_arg (arg0, REAL_TYPE))
10501         return do_mpfr_arg1 (arg0, type, mpfr_erfc, NULL, NULL, 0);
10502     break;
10503
10504     CASE_FLT_FN (BUILT_IN_TGAMMA):
10505       if (validate_arg (arg0, REAL_TYPE))
10506         return do_mpfr_arg1 (arg0, type, mpfr_gamma, NULL, NULL, 0);
10507     break;
10508
10509     CASE_FLT_FN (BUILT_IN_EXP):
10510       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp);
10511
10512     CASE_FLT_FN (BUILT_IN_EXP2):
10513       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp2);
10514
10515     CASE_FLT_FN (BUILT_IN_EXP10):
10516     CASE_FLT_FN (BUILT_IN_POW10):
10517       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp10);
10518
10519     CASE_FLT_FN (BUILT_IN_EXPM1):
10520       if (validate_arg (arg0, REAL_TYPE))
10521         return do_mpfr_arg1 (arg0, type, mpfr_expm1, NULL, NULL, 0);
10522     break;
10523
10524     CASE_FLT_FN (BUILT_IN_LOG):
10525     return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log);
10526
10527     CASE_FLT_FN (BUILT_IN_LOG2):
10528       return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log2);
10529
10530     CASE_FLT_FN (BUILT_IN_LOG10):
10531       return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log10);
10532
10533     CASE_FLT_FN (BUILT_IN_LOG1P):
10534       if (validate_arg (arg0, REAL_TYPE))
10535         return do_mpfr_arg1 (arg0, type, mpfr_log1p,
10536                              &dconstm1, NULL, false);
10537     break;
10538
10539     CASE_FLT_FN (BUILT_IN_J0):
10540       if (validate_arg (arg0, REAL_TYPE))
10541         return do_mpfr_arg1 (arg0, type, mpfr_j0,
10542                              NULL, NULL, 0);
10543     break;
10544
10545     CASE_FLT_FN (BUILT_IN_J1):
10546       if (validate_arg (arg0, REAL_TYPE))
10547         return do_mpfr_arg1 (arg0, type, mpfr_j1,
10548                              NULL, NULL, 0);
10549     break;
10550
10551     CASE_FLT_FN (BUILT_IN_Y0):
10552       if (validate_arg (arg0, REAL_TYPE))
10553         return do_mpfr_arg1 (arg0, type, mpfr_y0,
10554                              &dconst0, NULL, false);
10555     break;
10556
10557     CASE_FLT_FN (BUILT_IN_Y1):
10558       if (validate_arg (arg0, REAL_TYPE))
10559         return do_mpfr_arg1 (arg0, type, mpfr_y1,
10560                              &dconst0, NULL, false);
10561     break;
10562
10563     CASE_FLT_FN (BUILT_IN_NAN):
10564     case BUILT_IN_NAND32:
10565     case BUILT_IN_NAND64:
10566     case BUILT_IN_NAND128:
10567       return fold_builtin_nan (arg0, type, true);
10568
10569     CASE_FLT_FN (BUILT_IN_NANS):
10570       return fold_builtin_nan (arg0, type, false);
10571
10572     CASE_FLT_FN (BUILT_IN_FLOOR):
10573       return fold_builtin_floor (loc, fndecl, arg0);
10574
10575     CASE_FLT_FN (BUILT_IN_CEIL):
10576       return fold_builtin_ceil (loc, fndecl, arg0);
10577
10578     CASE_FLT_FN (BUILT_IN_TRUNC):
10579       return fold_builtin_trunc (loc, fndecl, arg0);
10580
10581     CASE_FLT_FN (BUILT_IN_ROUND):
10582       return fold_builtin_round (loc, fndecl, arg0);
10583
10584     CASE_FLT_FN (BUILT_IN_NEARBYINT):
10585     CASE_FLT_FN (BUILT_IN_RINT):
10586       return fold_trunc_transparent_mathfn (loc, fndecl, arg0);
10587
10588     CASE_FLT_FN (BUILT_IN_ICEIL):
10589     CASE_FLT_FN (BUILT_IN_LCEIL):
10590     CASE_FLT_FN (BUILT_IN_LLCEIL):
10591     CASE_FLT_FN (BUILT_IN_LFLOOR):
10592     CASE_FLT_FN (BUILT_IN_IFLOOR):
10593     CASE_FLT_FN (BUILT_IN_LLFLOOR):
10594     CASE_FLT_FN (BUILT_IN_IROUND):
10595     CASE_FLT_FN (BUILT_IN_LROUND):
10596     CASE_FLT_FN (BUILT_IN_LLROUND):
10597       return fold_builtin_int_roundingfn (loc, fndecl, arg0);
10598
10599     CASE_FLT_FN (BUILT_IN_IRINT):
10600     CASE_FLT_FN (BUILT_IN_LRINT):
10601     CASE_FLT_FN (BUILT_IN_LLRINT):
10602       return fold_fixed_mathfn (loc, fndecl, arg0);
10603
10604     case BUILT_IN_BSWAP16:
10605     case BUILT_IN_BSWAP32:
10606     case BUILT_IN_BSWAP64:
10607       return fold_builtin_bswap (fndecl, arg0);
10608
10609     CASE_INT_FN (BUILT_IN_FFS):
10610     CASE_INT_FN (BUILT_IN_CLZ):
10611     CASE_INT_FN (BUILT_IN_CTZ):
10612     CASE_INT_FN (BUILT_IN_CLRSB):
10613     CASE_INT_FN (BUILT_IN_POPCOUNT):
10614     CASE_INT_FN (BUILT_IN_PARITY):
10615       return fold_builtin_bitop (fndecl, arg0);
10616
10617     CASE_FLT_FN (BUILT_IN_SIGNBIT):
10618       return fold_builtin_signbit (loc, arg0, type);
10619
10620     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
10621       return fold_builtin_significand (loc, arg0, type);
10622
10623     CASE_FLT_FN (BUILT_IN_ILOGB):
10624     CASE_FLT_FN (BUILT_IN_LOGB):
10625       return fold_builtin_logb (loc, arg0, type);
10626
10627     case BUILT_IN_ISASCII:
10628       return fold_builtin_isascii (loc, arg0);
10629
10630     case BUILT_IN_TOASCII:
10631       return fold_builtin_toascii (loc, arg0);
10632
10633     case BUILT_IN_ISDIGIT:
10634       return fold_builtin_isdigit (loc, arg0);
10635
10636     CASE_FLT_FN (BUILT_IN_FINITE):
10637     case BUILT_IN_FINITED32:
10638     case BUILT_IN_FINITED64:
10639     case BUILT_IN_FINITED128:
10640     case BUILT_IN_ISFINITE:
10641       {
10642         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISFINITE);
10643         if (ret)
10644           return ret;
10645         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10646       }
10647
10648     CASE_FLT_FN (BUILT_IN_ISINF):
10649     case BUILT_IN_ISINFD32:
10650     case BUILT_IN_ISINFD64:
10651     case BUILT_IN_ISINFD128:
10652       {
10653         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF);
10654         if (ret)
10655           return ret;
10656         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10657       }
10658
10659     case BUILT_IN_ISNORMAL:
10660       return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10661
10662     case BUILT_IN_ISINF_SIGN:
10663       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF_SIGN);
10664
10665     CASE_FLT_FN (BUILT_IN_ISNAN):
10666     case BUILT_IN_ISNAND32:
10667     case BUILT_IN_ISNAND64:
10668     case BUILT_IN_ISNAND128:
10669       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISNAN);
10670
10671     case BUILT_IN_PRINTF:
10672     case BUILT_IN_PRINTF_UNLOCKED:
10673     case BUILT_IN_VPRINTF:
10674       return fold_builtin_printf (loc, fndecl, arg0, NULL_TREE, ignore, fcode);
10675
10676     case BUILT_IN_FREE:
10677       if (integer_zerop (arg0))
10678         return build_empty_stmt (loc);
10679       break;
10680
10681     default:
10682       break;
10683     }
10684
10685   return NULL_TREE;
10686
10687 }
10688
10689 /* Fold a call to built-in function FNDECL with 2 arguments, ARG0 and ARG1.
10690    IGNORE is true if the result of the function call is ignored.  This
10691    function returns NULL_TREE if no simplification was possible.  */
10692
10693 static tree
10694 fold_builtin_2 (location_t loc, tree fndecl, tree arg0, tree arg1, bool ignore)
10695 {
10696   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10697   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10698
10699   switch (fcode)
10700     {
10701     CASE_FLT_FN (BUILT_IN_JN):
10702       if (validate_arg (arg0, INTEGER_TYPE)
10703           && validate_arg (arg1, REAL_TYPE))
10704         return do_mpfr_bessel_n (arg0, arg1, type, mpfr_jn, NULL, 0);
10705     break;
10706
10707     CASE_FLT_FN (BUILT_IN_YN):
10708       if (validate_arg (arg0, INTEGER_TYPE)
10709           && validate_arg (arg1, REAL_TYPE))
10710         return do_mpfr_bessel_n (arg0, arg1, type, mpfr_yn,
10711                                  &dconst0, false);
10712     break;
10713
10714     CASE_FLT_FN (BUILT_IN_DREM):
10715     CASE_FLT_FN (BUILT_IN_REMAINDER):
10716       if (validate_arg (arg0, REAL_TYPE)
10717           && validate_arg(arg1, REAL_TYPE))
10718         return do_mpfr_arg2 (arg0, arg1, type, mpfr_remainder);
10719     break;
10720
10721     CASE_FLT_FN_REENT (BUILT_IN_GAMMA): /* GAMMA_R */
10722     CASE_FLT_FN_REENT (BUILT_IN_LGAMMA): /* LGAMMA_R */
10723       if (validate_arg (arg0, REAL_TYPE)
10724           && validate_arg(arg1, POINTER_TYPE))
10725         return do_mpfr_lgamma_r (arg0, arg1, type);
10726     break;
10727
10728     CASE_FLT_FN (BUILT_IN_ATAN2):
10729       if (validate_arg (arg0, REAL_TYPE)
10730           && validate_arg(arg1, REAL_TYPE))
10731         return do_mpfr_arg2 (arg0, arg1, type, mpfr_atan2);
10732     break;
10733
10734     CASE_FLT_FN (BUILT_IN_FDIM):
10735       if (validate_arg (arg0, REAL_TYPE)
10736           && validate_arg(arg1, REAL_TYPE))
10737         return do_mpfr_arg2 (arg0, arg1, type, mpfr_dim);
10738     break;
10739
10740     CASE_FLT_FN (BUILT_IN_HYPOT):
10741       return fold_builtin_hypot (loc, fndecl, arg0, arg1, type);
10742
10743     CASE_FLT_FN (BUILT_IN_CPOW):
10744       if (validate_arg (arg0, COMPLEX_TYPE)
10745           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE
10746           && validate_arg (arg1, COMPLEX_TYPE)
10747           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg1))) == REAL_TYPE)
10748         return do_mpc_arg2 (arg0, arg1, type, /*do_nonfinite=*/ 0, mpc_pow);
10749     break;
10750
10751     CASE_FLT_FN (BUILT_IN_LDEXP):
10752       return fold_builtin_load_exponent (loc, arg0, arg1, type, /*ldexp=*/true);
10753     CASE_FLT_FN (BUILT_IN_SCALBN):
10754     CASE_FLT_FN (BUILT_IN_SCALBLN):
10755       return fold_builtin_load_exponent (loc, arg0, arg1,
10756                                          type, /*ldexp=*/false);
10757
10758     CASE_FLT_FN (BUILT_IN_FREXP):
10759       return fold_builtin_frexp (loc, arg0, arg1, type);
10760
10761     CASE_FLT_FN (BUILT_IN_MODF):
10762       return fold_builtin_modf (loc, arg0, arg1, type);
10763
10764     case BUILT_IN_BZERO:
10765       return fold_builtin_bzero (loc, arg0, arg1, ignore);
10766
10767     case BUILT_IN_FPUTS:
10768       return fold_builtin_fputs (loc, arg0, arg1, ignore, false, NULL_TREE);
10769
10770     case BUILT_IN_FPUTS_UNLOCKED:
10771       return fold_builtin_fputs (loc, arg0, arg1, ignore, true, NULL_TREE);
10772
10773     case BUILT_IN_STRSTR:
10774       return fold_builtin_strstr (loc, arg0, arg1, type);
10775
10776     case BUILT_IN_STRCAT:
10777       return fold_builtin_strcat (loc, arg0, arg1);
10778
10779     case BUILT_IN_STRSPN:
10780       return fold_builtin_strspn (loc, arg0, arg1);
10781
10782     case BUILT_IN_STRCSPN:
10783       return fold_builtin_strcspn (loc, arg0, arg1);
10784
10785     case BUILT_IN_STRCHR:
10786     case BUILT_IN_INDEX:
10787       return fold_builtin_strchr (loc, arg0, arg1, type);
10788
10789     case BUILT_IN_STRRCHR:
10790     case BUILT_IN_RINDEX:
10791       return fold_builtin_strrchr (loc, arg0, arg1, type);
10792
10793     case BUILT_IN_STRCPY:
10794       return fold_builtin_strcpy (loc, fndecl, arg0, arg1, NULL_TREE);
10795
10796     case BUILT_IN_STPCPY:
10797       if (ignore)
10798         {
10799           tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
10800           if (!fn)
10801             break;
10802
10803           return build_call_expr_loc (loc, fn, 2, arg0, arg1);
10804         }
10805       else
10806         return fold_builtin_stpcpy (loc, fndecl, arg0, arg1);
10807       break;
10808
10809     case BUILT_IN_STRCMP:
10810       return fold_builtin_strcmp (loc, arg0, arg1);
10811
10812     case BUILT_IN_STRPBRK:
10813       return fold_builtin_strpbrk (loc, arg0, arg1, type);
10814
10815     case BUILT_IN_EXPECT:
10816       return fold_builtin_expect (loc, arg0, arg1);
10817
10818     CASE_FLT_FN (BUILT_IN_POW):
10819       return fold_builtin_pow (loc, fndecl, arg0, arg1, type);
10820
10821     CASE_FLT_FN (BUILT_IN_POWI):
10822       return fold_builtin_powi (loc, fndecl, arg0, arg1, type);
10823
10824     CASE_FLT_FN (BUILT_IN_COPYSIGN):
10825       return fold_builtin_copysign (loc, fndecl, arg0, arg1, type);
10826
10827     CASE_FLT_FN (BUILT_IN_FMIN):
10828       return fold_builtin_fmin_fmax (loc, arg0, arg1, type, /*max=*/false);
10829
10830     CASE_FLT_FN (BUILT_IN_FMAX):
10831       return fold_builtin_fmin_fmax (loc, arg0, arg1, type, /*max=*/true);
10832
10833     case BUILT_IN_ISGREATER:
10834       return fold_builtin_unordered_cmp (loc, fndecl,
10835                                          arg0, arg1, UNLE_EXPR, LE_EXPR);
10836     case BUILT_IN_ISGREATEREQUAL:
10837       return fold_builtin_unordered_cmp (loc, fndecl,
10838                                          arg0, arg1, UNLT_EXPR, LT_EXPR);
10839     case BUILT_IN_ISLESS:
10840       return fold_builtin_unordered_cmp (loc, fndecl,
10841                                          arg0, arg1, UNGE_EXPR, GE_EXPR);
10842     case BUILT_IN_ISLESSEQUAL:
10843       return fold_builtin_unordered_cmp (loc, fndecl,
10844                                          arg0, arg1, UNGT_EXPR, GT_EXPR);
10845     case BUILT_IN_ISLESSGREATER:
10846       return fold_builtin_unordered_cmp (loc, fndecl,
10847                                          arg0, arg1, UNEQ_EXPR, EQ_EXPR);
10848     case BUILT_IN_ISUNORDERED:
10849       return fold_builtin_unordered_cmp (loc, fndecl,
10850                                          arg0, arg1, UNORDERED_EXPR,
10851                                          NOP_EXPR);
10852
10853       /* We do the folding for va_start in the expander.  */
10854     case BUILT_IN_VA_START:
10855       break;
10856
10857     case BUILT_IN_SPRINTF:
10858       return fold_builtin_sprintf (loc, arg0, arg1, NULL_TREE, ignore);
10859
10860     case BUILT_IN_OBJECT_SIZE:
10861       return fold_builtin_object_size (arg0, arg1);
10862
10863     case BUILT_IN_PRINTF:
10864     case BUILT_IN_PRINTF_UNLOCKED:
10865     case BUILT_IN_VPRINTF:
10866       return fold_builtin_printf (loc, fndecl, arg0, arg1, ignore, fcode);
10867
10868     case BUILT_IN_PRINTF_CHK:
10869     case BUILT_IN_VPRINTF_CHK:
10870       if (!validate_arg (arg0, INTEGER_TYPE)
10871           || TREE_SIDE_EFFECTS (arg0))
10872         return NULL_TREE;
10873       else
10874         return fold_builtin_printf (loc, fndecl,
10875                                     arg1, NULL_TREE, ignore, fcode);
10876     break;
10877
10878     case BUILT_IN_FPRINTF:
10879     case BUILT_IN_FPRINTF_UNLOCKED:
10880     case BUILT_IN_VFPRINTF:
10881       return fold_builtin_fprintf (loc, fndecl, arg0, arg1, NULL_TREE,
10882                                    ignore, fcode);
10883
10884     case BUILT_IN_ATOMIC_ALWAYS_LOCK_FREE:
10885       return fold_builtin_atomic_always_lock_free (arg0, arg1);
10886
10887     case BUILT_IN_ATOMIC_IS_LOCK_FREE:
10888       return fold_builtin_atomic_is_lock_free (arg0, arg1);
10889
10890     default:
10891       break;
10892     }
10893   return NULL_TREE;
10894 }
10895
10896 /* Fold a call to built-in function FNDECL with 3 arguments, ARG0, ARG1,
10897    and ARG2.  IGNORE is true if the result of the function call is ignored.
10898    This function returns NULL_TREE if no simplification was possible.  */
10899
10900 static tree
10901 fold_builtin_3 (location_t loc, tree fndecl,
10902                 tree arg0, tree arg1, tree arg2, bool ignore)
10903 {
10904   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10905   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10906   switch (fcode)
10907     {
10908
10909     CASE_FLT_FN (BUILT_IN_SINCOS):
10910       return fold_builtin_sincos (loc, arg0, arg1, arg2);
10911
10912     CASE_FLT_FN (BUILT_IN_FMA):
10913       return fold_builtin_fma (loc, arg0, arg1, arg2, type);
10914     break;
10915
10916     CASE_FLT_FN (BUILT_IN_REMQUO):
10917       if (validate_arg (arg0, REAL_TYPE)
10918           && validate_arg(arg1, REAL_TYPE)
10919           && validate_arg(arg2, POINTER_TYPE))
10920         return do_mpfr_remquo (arg0, arg1, arg2);
10921     break;
10922
10923     case BUILT_IN_MEMSET:
10924       return fold_builtin_memset (loc, arg0, arg1, arg2, type, ignore);
10925
10926     case BUILT_IN_BCOPY:
10927       return fold_builtin_memory_op (loc, arg1, arg0, arg2,
10928                                      void_type_node, true, /*endp=*/3);
10929
10930     case BUILT_IN_MEMCPY:
10931       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10932                                      type, ignore, /*endp=*/0);
10933
10934     case BUILT_IN_MEMPCPY:
10935       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10936                                      type, ignore, /*endp=*/1);
10937
10938     case BUILT_IN_MEMMOVE:
10939       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10940                                      type, ignore, /*endp=*/3);
10941
10942     case BUILT_IN_STRNCAT:
10943       return fold_builtin_strncat (loc, arg0, arg1, arg2);
10944
10945     case BUILT_IN_STRNCPY:
10946       return fold_builtin_strncpy (loc, fndecl, arg0, arg1, arg2, NULL_TREE);
10947
10948     case BUILT_IN_STRNCMP:
10949       return fold_builtin_strncmp (loc, arg0, arg1, arg2);
10950
10951     case BUILT_IN_MEMCHR:
10952       return fold_builtin_memchr (loc, arg0, arg1, arg2, type);
10953
10954     case BUILT_IN_BCMP:
10955     case BUILT_IN_MEMCMP:
10956       return fold_builtin_memcmp (loc, arg0, arg1, arg2);;
10957
10958     case BUILT_IN_SPRINTF:
10959       return fold_builtin_sprintf (loc, arg0, arg1, arg2, ignore);
10960
10961     case BUILT_IN_SNPRINTF:
10962       return fold_builtin_snprintf (loc, arg0, arg1, arg2, NULL_TREE, ignore);
10963
10964     case BUILT_IN_STRCPY_CHK:
10965     case BUILT_IN_STPCPY_CHK:
10966       return fold_builtin_stxcpy_chk (loc, fndecl, arg0, arg1, arg2, NULL_TREE,
10967                                       ignore, fcode);
10968
10969     case BUILT_IN_STRCAT_CHK:
10970       return fold_builtin_strcat_chk (loc, fndecl, arg0, arg1, arg2);
10971
10972     case BUILT_IN_PRINTF_CHK:
10973     case BUILT_IN_VPRINTF_CHK:
10974       if (!validate_arg (arg0, INTEGER_TYPE)
10975           || TREE_SIDE_EFFECTS (arg0))
10976         return NULL_TREE;
10977       else
10978         return fold_builtin_printf (loc, fndecl, arg1, arg2, ignore, fcode);
10979     break;
10980
10981     case BUILT_IN_FPRINTF:
10982     case BUILT_IN_FPRINTF_UNLOCKED:
10983     case BUILT_IN_VFPRINTF:
10984       return fold_builtin_fprintf (loc, fndecl, arg0, arg1, arg2,
10985                                    ignore, fcode);
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, NULL_TREE,
10994                                      ignore, fcode);
10995
10996     default:
10997       break;
10998     }
10999   return NULL_TREE;
11000 }
11001
11002 /* Fold a call to built-in function FNDECL with 4 arguments, ARG0, ARG1,
11003    ARG2, and ARG3.  IGNORE is true if the result of the function call is
11004    ignored.  This function returns NULL_TREE if no simplification was
11005    possible.  */
11006
11007 static tree
11008 fold_builtin_4 (location_t loc, tree fndecl,
11009                 tree arg0, tree arg1, tree arg2, tree arg3, bool ignore)
11010 {
11011   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
11012
11013   switch (fcode)
11014     {
11015     case BUILT_IN_MEMCPY_CHK:
11016     case BUILT_IN_MEMPCPY_CHK:
11017     case BUILT_IN_MEMMOVE_CHK:
11018     case BUILT_IN_MEMSET_CHK:
11019       return fold_builtin_memory_chk (loc, fndecl, arg0, arg1, arg2, arg3,
11020                                       NULL_TREE, ignore,
11021                                       DECL_FUNCTION_CODE (fndecl));
11022
11023     case BUILT_IN_STRNCPY_CHK:
11024     case BUILT_IN_STPNCPY_CHK:
11025       return fold_builtin_stxncpy_chk (loc, arg0, arg1, arg2, arg3, NULL_TREE,
11026                                        ignore, fcode);
11027
11028     case BUILT_IN_STRNCAT_CHK:
11029       return fold_builtin_strncat_chk (loc, fndecl, arg0, arg1, arg2, arg3);
11030
11031     case BUILT_IN_SNPRINTF:
11032       return fold_builtin_snprintf (loc, arg0, arg1, arg2, arg3, ignore);
11033
11034     case BUILT_IN_FPRINTF_CHK:
11035     case BUILT_IN_VFPRINTF_CHK:
11036       if (!validate_arg (arg1, INTEGER_TYPE)
11037           || TREE_SIDE_EFFECTS (arg1))
11038         return NULL_TREE;
11039       else
11040         return fold_builtin_fprintf (loc, fndecl, arg0, arg2, arg3,
11041                                      ignore, fcode);
11042     break;
11043
11044     default:
11045       break;
11046     }
11047   return NULL_TREE;
11048 }
11049
11050 /* Fold a call to built-in function FNDECL.  ARGS is an array of NARGS
11051     arguments, where NARGS <= 4.  IGNORE is true if the result of the
11052     function call is ignored.  This function returns NULL_TREE if no
11053     simplification was possible.  Note that this only folds builtins with
11054     fixed argument patterns.  Foldings that do varargs-to-varargs
11055     transformations, or that match calls with more than 4 arguments,
11056     need to be handled with fold_builtin_varargs instead.  */
11057
11058 #define MAX_ARGS_TO_FOLD_BUILTIN 4
11059
11060 static tree
11061 fold_builtin_n (location_t loc, tree fndecl, tree *args, int nargs, bool ignore)
11062 {
11063   tree ret = NULL_TREE;
11064
11065   switch (nargs)
11066     {
11067     case 0:
11068       ret = fold_builtin_0 (loc, fndecl, ignore);
11069       break;
11070     case 1:
11071       ret = fold_builtin_1 (loc, fndecl, args[0], ignore);
11072       break;
11073     case 2:
11074       ret = fold_builtin_2 (loc, fndecl, args[0], args[1], ignore);
11075       break;
11076     case 3:
11077       ret = fold_builtin_3 (loc, fndecl, args[0], args[1], args[2], ignore);
11078       break;
11079     case 4:
11080       ret = fold_builtin_4 (loc, fndecl, args[0], args[1], args[2], args[3],
11081                             ignore);
11082       break;
11083     default:
11084       break;
11085     }
11086   if (ret)
11087     {
11088       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
11089       SET_EXPR_LOCATION (ret, loc);
11090       TREE_NO_WARNING (ret) = 1;
11091       return ret;
11092     }
11093   return NULL_TREE;
11094 }
11095
11096 /* Builtins with folding operations that operate on "..." arguments
11097    need special handling; we need to store the arguments in a convenient
11098    data structure before attempting any folding.  Fortunately there are
11099    only a few builtins that fall into this category.  FNDECL is the
11100    function, EXP is the CALL_EXPR for the call, and IGNORE is true if the
11101    result of the function call is ignored.  */
11102
11103 static tree
11104 fold_builtin_varargs (location_t loc, tree fndecl, tree exp,
11105                       bool ignore ATTRIBUTE_UNUSED)
11106 {
11107   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
11108   tree ret = NULL_TREE;
11109
11110   switch (fcode)
11111     {
11112     case BUILT_IN_SPRINTF_CHK:
11113     case BUILT_IN_VSPRINTF_CHK:
11114       ret = fold_builtin_sprintf_chk (loc, exp, fcode);
11115       break;
11116
11117     case BUILT_IN_SNPRINTF_CHK:
11118     case BUILT_IN_VSNPRINTF_CHK:
11119       ret = fold_builtin_snprintf_chk (loc, exp, NULL_TREE, fcode);
11120       break;
11121
11122     case BUILT_IN_FPCLASSIFY:
11123       ret = fold_builtin_fpclassify (loc, exp);
11124       break;
11125
11126     default:
11127       break;
11128     }
11129   if (ret)
11130     {
11131       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
11132       SET_EXPR_LOCATION (ret, loc);
11133       TREE_NO_WARNING (ret) = 1;
11134       return ret;
11135     }
11136   return NULL_TREE;
11137 }
11138
11139 /* Return true if FNDECL shouldn't be folded right now.
11140    If a built-in function has an inline attribute always_inline
11141    wrapper, defer folding it after always_inline functions have
11142    been inlined, otherwise e.g. -D_FORTIFY_SOURCE checking
11143    might not be performed.  */
11144
11145 bool
11146 avoid_folding_inline_builtin (tree fndecl)
11147 {
11148   return (DECL_DECLARED_INLINE_P (fndecl)
11149           && DECL_DISREGARD_INLINE_LIMITS (fndecl)
11150           && cfun
11151           && !cfun->always_inline_functions_inlined
11152           && lookup_attribute ("always_inline", DECL_ATTRIBUTES (fndecl)));
11153 }
11154
11155 /* A wrapper function for builtin folding that prevents warnings for
11156    "statement without effect" and the like, caused by removing the
11157    call node earlier than the warning is generated.  */
11158
11159 tree
11160 fold_call_expr (location_t loc, tree exp, bool ignore)
11161 {
11162   tree ret = NULL_TREE;
11163   tree fndecl = get_callee_fndecl (exp);
11164   if (fndecl
11165       && TREE_CODE (fndecl) == FUNCTION_DECL
11166       && DECL_BUILT_IN (fndecl)
11167       /* If CALL_EXPR_VA_ARG_PACK is set, the arguments aren't finalized
11168          yet.  Defer folding until we see all the arguments
11169          (after inlining).  */
11170       && !CALL_EXPR_VA_ARG_PACK (exp))
11171     {
11172       int nargs = call_expr_nargs (exp);
11173
11174       /* Before gimplification CALL_EXPR_VA_ARG_PACK is not set, but
11175          instead last argument is __builtin_va_arg_pack ().  Defer folding
11176          even in that case, until arguments are finalized.  */
11177       if (nargs && TREE_CODE (CALL_EXPR_ARG (exp, nargs - 1)) == CALL_EXPR)
11178         {
11179           tree fndecl2 = get_callee_fndecl (CALL_EXPR_ARG (exp, nargs - 1));
11180           if (fndecl2
11181               && TREE_CODE (fndecl2) == FUNCTION_DECL
11182               && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
11183               && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
11184             return NULL_TREE;
11185         }
11186
11187       if (avoid_folding_inline_builtin (fndecl))
11188         return NULL_TREE;
11189
11190       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
11191         return targetm.fold_builtin (fndecl, call_expr_nargs (exp),
11192                                      CALL_EXPR_ARGP (exp), ignore);
11193       else
11194         {
11195           if (nargs <= MAX_ARGS_TO_FOLD_BUILTIN)
11196             {
11197               tree *args = CALL_EXPR_ARGP (exp);
11198               ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
11199             }
11200           if (!ret)
11201             ret = fold_builtin_varargs (loc, fndecl, exp, ignore);
11202           if (ret)
11203             return ret;
11204         }
11205     }
11206   return NULL_TREE;
11207 }
11208
11209 /* Conveniently construct a function call expression.  FNDECL names the
11210    function to be called and N arguments are passed in the array
11211    ARGARRAY.  */
11212
11213 tree
11214 build_call_expr_loc_array (location_t loc, tree fndecl, int n, tree *argarray)
11215 {
11216   tree fntype = TREE_TYPE (fndecl);
11217   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
11218  
11219   return fold_builtin_call_array (loc, TREE_TYPE (fntype), fn, n, argarray);
11220 }
11221
11222 /* Conveniently construct a function call expression.  FNDECL names the
11223    function to be called and the arguments are passed in the vector
11224    VEC.  */
11225
11226 tree
11227 build_call_expr_loc_vec (location_t loc, tree fndecl, vec<tree, va_gc> *vec)
11228 {
11229   return build_call_expr_loc_array (loc, fndecl, vec_safe_length (vec),
11230                                     vec_safe_address (vec));
11231 }
11232
11233
11234 /* Conveniently construct a function call expression.  FNDECL names the
11235    function to be called, N is the number of arguments, and the "..."
11236    parameters are the argument expressions.  */
11237
11238 tree
11239 build_call_expr_loc (location_t loc, tree fndecl, int n, ...)
11240 {
11241   va_list ap;
11242   tree *argarray = XALLOCAVEC (tree, n);
11243   int i;
11244
11245   va_start (ap, n);
11246   for (i = 0; i < n; i++)
11247     argarray[i] = va_arg (ap, tree);
11248   va_end (ap);
11249   return build_call_expr_loc_array (loc, fndecl, n, argarray);
11250 }
11251
11252 /* Like build_call_expr_loc (UNKNOWN_LOCATION, ...).  Duplicated because
11253    varargs macros aren't supported by all bootstrap compilers.  */
11254
11255 tree
11256 build_call_expr (tree fndecl, int n, ...)
11257 {
11258   va_list ap;
11259   tree *argarray = XALLOCAVEC (tree, n);
11260   int i;
11261
11262   va_start (ap, n);
11263   for (i = 0; i < n; i++)
11264     argarray[i] = va_arg (ap, tree);
11265   va_end (ap);
11266   return build_call_expr_loc_array (UNKNOWN_LOCATION, fndecl, n, argarray);
11267 }
11268
11269 /* Construct a CALL_EXPR with type TYPE with FN as the function expression.
11270    N arguments are passed in the array ARGARRAY.  */
11271
11272 tree
11273 fold_builtin_call_array (location_t loc, tree type,
11274                          tree fn,
11275                          int n,
11276                          tree *argarray)
11277 {
11278   tree ret = NULL_TREE;
11279    tree exp;
11280
11281   if (TREE_CODE (fn) == ADDR_EXPR)
11282   {
11283     tree fndecl = TREE_OPERAND (fn, 0);
11284     if (TREE_CODE (fndecl) == FUNCTION_DECL
11285         && DECL_BUILT_IN (fndecl))
11286       {
11287         /* If last argument is __builtin_va_arg_pack (), arguments to this
11288            function are not finalized yet.  Defer folding until they are.  */
11289         if (n && TREE_CODE (argarray[n - 1]) == CALL_EXPR)
11290           {
11291             tree fndecl2 = get_callee_fndecl (argarray[n - 1]);
11292             if (fndecl2
11293                 && TREE_CODE (fndecl2) == FUNCTION_DECL
11294                 && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
11295                 && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
11296               return build_call_array_loc (loc, type, fn, n, argarray);
11297           }
11298         if (avoid_folding_inline_builtin (fndecl))
11299           return build_call_array_loc (loc, type, fn, n, argarray);
11300         if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
11301           {
11302             ret = targetm.fold_builtin (fndecl, n, argarray, false);
11303             if (ret)
11304               return ret;
11305
11306             return build_call_array_loc (loc, type, fn, n, argarray);
11307           }
11308         else if (n <= MAX_ARGS_TO_FOLD_BUILTIN)
11309           {
11310             /* First try the transformations that don't require consing up
11311                an exp.  */
11312             ret = fold_builtin_n (loc, fndecl, argarray, n, false);
11313             if (ret)
11314               return ret;
11315           }
11316
11317         /* If we got this far, we need to build an exp.  */
11318         exp = build_call_array_loc (loc, type, fn, n, argarray);
11319         ret = fold_builtin_varargs (loc, fndecl, exp, false);
11320         return ret ? ret : exp;
11321       }
11322   }
11323
11324   return build_call_array_loc (loc, type, fn, n, argarray);
11325 }
11326
11327 /* Construct a new CALL_EXPR to FNDECL using the tail of the argument
11328    list ARGS along with N new arguments in NEWARGS.  SKIP is the number
11329    of arguments in ARGS to be omitted.  OLDNARGS is the number of
11330    elements in ARGS.  */
11331
11332 static tree
11333 rewrite_call_expr_valist (location_t loc, int oldnargs, tree *args,
11334                           int skip, tree fndecl, int n, va_list newargs)
11335 {
11336   int nargs = oldnargs - skip + n;
11337   tree *buffer;
11338
11339   if (n > 0)
11340     {
11341       int i, j;
11342
11343       buffer = XALLOCAVEC (tree, nargs);
11344       for (i = 0; i < n; i++)
11345         buffer[i] = va_arg (newargs, tree);
11346       for (j = skip; j < oldnargs; j++, i++)
11347         buffer[i] = args[j];
11348     }
11349   else
11350     buffer = args + skip;
11351
11352   return build_call_expr_loc_array (loc, fndecl, nargs, buffer);
11353 }
11354
11355 /* Construct a new CALL_EXPR to FNDECL using the tail of the argument
11356    list ARGS along with N new arguments specified as the "..."
11357    parameters.  SKIP is the number of arguments in ARGS to be omitted.
11358    OLDNARGS is the number of elements in ARGS.  */
11359
11360 static tree
11361 rewrite_call_expr_array (location_t loc, int oldnargs, tree *args,
11362                          int skip, tree fndecl, int n, ...)
11363 {
11364   va_list ap;
11365   tree t;
11366
11367   va_start (ap, n);
11368   t = rewrite_call_expr_valist (loc, oldnargs, args, skip, fndecl, n, ap);
11369   va_end (ap);
11370
11371   return t;
11372 }
11373
11374 /* Construct a new CALL_EXPR using the tail of the argument list of EXP
11375    along with N new arguments specified as the "..." parameters.  SKIP
11376    is the number of arguments in EXP to be omitted.  This function is used
11377    to do varargs-to-varargs transformations.  */
11378
11379 static tree
11380 rewrite_call_expr (location_t loc, tree exp, int skip, tree fndecl, int n, ...)
11381 {
11382   va_list ap;
11383   tree t;
11384
11385   va_start (ap, n);
11386   t = rewrite_call_expr_valist (loc, call_expr_nargs (exp),
11387                                 CALL_EXPR_ARGP (exp), skip, fndecl, n, ap);
11388   va_end (ap);
11389
11390   return t;
11391 }
11392
11393 /* Validate a single argument ARG against a tree code CODE representing
11394    a type.  */
11395
11396 static bool
11397 validate_arg (const_tree arg, enum tree_code code)
11398 {
11399   if (!arg)
11400     return false;
11401   else if (code == POINTER_TYPE)
11402     return POINTER_TYPE_P (TREE_TYPE (arg));
11403   else if (code == INTEGER_TYPE)
11404     return INTEGRAL_TYPE_P (TREE_TYPE (arg));
11405   return code == TREE_CODE (TREE_TYPE (arg));
11406 }
11407
11408 /* This function validates the types of a function call argument list
11409    against a specified list of tree_codes.  If the last specifier is a 0,
11410    that represents an ellipses, otherwise the last specifier must be a
11411    VOID_TYPE.
11412
11413    This is the GIMPLE version of validate_arglist.  Eventually we want to
11414    completely convert builtins.c to work from GIMPLEs and the tree based
11415    validate_arglist will then be removed.  */
11416
11417 bool
11418 validate_gimple_arglist (const_gimple call, ...)
11419 {
11420   enum tree_code code;
11421   bool res = 0;
11422   va_list ap;
11423   const_tree arg;
11424   size_t i;
11425
11426   va_start (ap, call);
11427   i = 0;
11428
11429   do
11430     {
11431       code = (enum tree_code) va_arg (ap, int);
11432       switch (code)
11433         {
11434         case 0:
11435           /* This signifies an ellipses, any further arguments are all ok.  */
11436           res = true;
11437           goto end;
11438         case VOID_TYPE:
11439           /* This signifies an endlink, if no arguments remain, return
11440              true, otherwise return false.  */
11441           res = (i == gimple_call_num_args (call));
11442           goto end;
11443         default:
11444           /* If no parameters remain or the parameter's code does not
11445              match the specified code, return false.  Otherwise continue
11446              checking any remaining arguments.  */
11447           arg = gimple_call_arg (call, i++);
11448           if (!validate_arg (arg, code))
11449             goto end;
11450           break;
11451         }
11452     }
11453   while (1);
11454
11455   /* We need gotos here since we can only have one VA_CLOSE in a
11456      function.  */
11457  end: ;
11458   va_end (ap);
11459
11460   return res;
11461 }
11462
11463 /* This function validates the types of a function call argument list
11464    against a specified list of tree_codes.  If the last specifier is a 0,
11465    that represents an ellipses, otherwise the last specifier must be a
11466    VOID_TYPE.  */
11467
11468 bool
11469 validate_arglist (const_tree callexpr, ...)
11470 {
11471   enum tree_code code;
11472   bool res = 0;
11473   va_list ap;
11474   const_call_expr_arg_iterator iter;
11475   const_tree arg;
11476
11477   va_start (ap, callexpr);
11478   init_const_call_expr_arg_iterator (callexpr, &iter);
11479
11480   do
11481     {
11482       code = (enum tree_code) va_arg (ap, int);
11483       switch (code)
11484         {
11485         case 0:
11486           /* This signifies an ellipses, any further arguments are all ok.  */
11487           res = true;
11488           goto end;
11489         case VOID_TYPE:
11490           /* This signifies an endlink, if no arguments remain, return
11491              true, otherwise return false.  */
11492           res = !more_const_call_expr_args_p (&iter);
11493           goto end;
11494         default:
11495           /* If no parameters remain or the parameter's code does not
11496              match the specified code, return false.  Otherwise continue
11497              checking any remaining arguments.  */
11498           arg = next_const_call_expr_arg (&iter);
11499           if (!validate_arg (arg, code))
11500             goto end;
11501           break;
11502         }
11503     }
11504   while (1);
11505
11506   /* We need gotos here since we can only have one VA_CLOSE in a
11507      function.  */
11508  end: ;
11509   va_end (ap);
11510
11511   return res;
11512 }
11513
11514 /* Default target-specific builtin expander that does nothing.  */
11515
11516 rtx
11517 default_expand_builtin (tree exp ATTRIBUTE_UNUSED,
11518                         rtx target ATTRIBUTE_UNUSED,
11519                         rtx subtarget ATTRIBUTE_UNUSED,
11520                         enum machine_mode mode ATTRIBUTE_UNUSED,
11521                         int ignore ATTRIBUTE_UNUSED)
11522 {
11523   return NULL_RTX;
11524 }
11525
11526 /* Returns true is EXP represents data that would potentially reside
11527    in a readonly section.  */
11528
11529 static bool
11530 readonly_data_expr (tree exp)
11531 {
11532   STRIP_NOPS (exp);
11533
11534   if (TREE_CODE (exp) != ADDR_EXPR)
11535     return false;
11536
11537   exp = get_base_address (TREE_OPERAND (exp, 0));
11538   if (!exp)
11539     return false;
11540
11541   /* Make sure we call decl_readonly_section only for trees it
11542      can handle (since it returns true for everything it doesn't
11543      understand).  */
11544   if (TREE_CODE (exp) == STRING_CST
11545       || TREE_CODE (exp) == CONSTRUCTOR
11546       || (TREE_CODE (exp) == VAR_DECL && TREE_STATIC (exp)))
11547     return decl_readonly_section (exp, 0);
11548   else
11549     return false;
11550 }
11551
11552 /* Simplify a call to the strstr builtin.  S1 and S2 are the arguments
11553    to the call, and TYPE is its return type.
11554
11555    Return NULL_TREE if no simplification was possible, otherwise return the
11556    simplified form of the call as a tree.
11557
11558    The simplified form may be a constant or other expression which
11559    computes the same value, but in a more efficient manner (including
11560    calls to other builtin functions).
11561
11562    The call may contain arguments which need to be evaluated, but
11563    which are not useful to determine the result of the call.  In
11564    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11565    COMPOUND_EXPR will be an argument which must be evaluated.
11566    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11567    COMPOUND_EXPR in the chain will contain the tree for the simplified
11568    form of the builtin function call.  */
11569
11570 static tree
11571 fold_builtin_strstr (location_t loc, tree s1, tree s2, tree type)
11572 {
11573   if (!validate_arg (s1, POINTER_TYPE)
11574       || !validate_arg (s2, POINTER_TYPE))
11575     return NULL_TREE;
11576   else
11577     {
11578       tree fn;
11579       const char *p1, *p2;
11580
11581       p2 = c_getstr (s2);
11582       if (p2 == NULL)
11583         return NULL_TREE;
11584
11585       p1 = c_getstr (s1);
11586       if (p1 != NULL)
11587         {
11588           const char *r = strstr (p1, p2);
11589           tree tem;
11590
11591           if (r == NULL)
11592             return build_int_cst (TREE_TYPE (s1), 0);
11593
11594           /* Return an offset into the constant string argument.  */
11595           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
11596           return fold_convert_loc (loc, type, tem);
11597         }
11598
11599       /* The argument is const char *, and the result is char *, so we need
11600          a type conversion here to avoid a warning.  */
11601       if (p2[0] == '\0')
11602         return fold_convert_loc (loc, type, s1);
11603
11604       if (p2[1] != '\0')
11605         return NULL_TREE;
11606
11607       fn = builtin_decl_implicit (BUILT_IN_STRCHR);
11608       if (!fn)
11609         return NULL_TREE;
11610
11611       /* New argument list transforming strstr(s1, s2) to
11612          strchr(s1, s2[0]).  */
11613       return build_call_expr_loc (loc, fn, 2, s1,
11614                                   build_int_cst (integer_type_node, p2[0]));
11615     }
11616 }
11617
11618 /* Simplify a call to the strchr builtin.  S1 and S2 are the arguments to
11619    the call, and TYPE is its return type.
11620
11621    Return NULL_TREE if no simplification was possible, otherwise return the
11622    simplified form of the call as a tree.
11623
11624    The simplified form may be a constant or other expression which
11625    computes the same value, but in a more efficient manner (including
11626    calls to other builtin functions).
11627
11628    The call may contain arguments which need to be evaluated, but
11629    which are not useful to determine the result of the call.  In
11630    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11631    COMPOUND_EXPR will be an argument which must be evaluated.
11632    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11633    COMPOUND_EXPR in the chain will contain the tree for the simplified
11634    form of the builtin function call.  */
11635
11636 static tree
11637 fold_builtin_strchr (location_t loc, tree s1, tree s2, tree type)
11638 {
11639   if (!validate_arg (s1, POINTER_TYPE)
11640       || !validate_arg (s2, INTEGER_TYPE))
11641     return NULL_TREE;
11642   else
11643     {
11644       const char *p1;
11645
11646       if (TREE_CODE (s2) != INTEGER_CST)
11647         return NULL_TREE;
11648
11649       p1 = c_getstr (s1);
11650       if (p1 != NULL)
11651         {
11652           char c;
11653           const char *r;
11654           tree tem;
11655
11656           if (target_char_cast (s2, &c))
11657             return NULL_TREE;
11658
11659           r = strchr (p1, c);
11660
11661           if (r == NULL)
11662             return build_int_cst (TREE_TYPE (s1), 0);
11663
11664           /* Return an offset into the constant string argument.  */
11665           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
11666           return fold_convert_loc (loc, type, tem);
11667         }
11668       return NULL_TREE;
11669     }
11670 }
11671
11672 /* Simplify a call to the strrchr builtin.  S1 and S2 are the arguments to
11673    the call, and TYPE is its return type.
11674
11675    Return NULL_TREE if no simplification was possible, otherwise return the
11676    simplified form of the call as a tree.
11677
11678    The simplified form may be a constant or other expression which
11679    computes the same value, but in a more efficient manner (including
11680    calls to other builtin functions).
11681
11682    The call may contain arguments which need to be evaluated, but
11683    which are not useful to determine the result of the call.  In
11684    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11685    COMPOUND_EXPR will be an argument which must be evaluated.
11686    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11687    COMPOUND_EXPR in the chain will contain the tree for the simplified
11688    form of the builtin function call.  */
11689
11690 static tree
11691 fold_builtin_strrchr (location_t loc, tree s1, tree s2, tree type)
11692 {
11693   if (!validate_arg (s1, POINTER_TYPE)
11694       || !validate_arg (s2, INTEGER_TYPE))
11695     return NULL_TREE;
11696   else
11697     {
11698       tree fn;
11699       const char *p1;
11700
11701       if (TREE_CODE (s2) != INTEGER_CST)
11702         return NULL_TREE;
11703
11704       p1 = c_getstr (s1);
11705       if (p1 != NULL)
11706         {
11707           char c;
11708           const char *r;
11709           tree tem;
11710
11711           if (target_char_cast (s2, &c))
11712             return NULL_TREE;
11713
11714           r = strrchr (p1, c);
11715
11716           if (r == NULL)
11717             return build_int_cst (TREE_TYPE (s1), 0);
11718
11719           /* Return an offset into the constant string argument.  */
11720           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
11721           return fold_convert_loc (loc, type, tem);
11722         }
11723
11724       if (! integer_zerop (s2))
11725         return NULL_TREE;
11726
11727       fn = builtin_decl_implicit (BUILT_IN_STRCHR);
11728       if (!fn)
11729         return NULL_TREE;
11730
11731       /* Transform strrchr(s1, '\0') to strchr(s1, '\0').  */
11732       return build_call_expr_loc (loc, fn, 2, s1, s2);
11733     }
11734 }
11735
11736 /* Simplify a call to the strpbrk builtin.  S1 and S2 are the arguments
11737    to the call, and TYPE is its return type.
11738
11739    Return NULL_TREE if no simplification was possible, otherwise return the
11740    simplified form of the call as a tree.
11741
11742    The simplified form may be a constant or other expression which
11743    computes the same value, but in a more efficient manner (including
11744    calls to other builtin functions).
11745
11746    The call may contain arguments which need to be evaluated, but
11747    which are not useful to determine the result of the call.  In
11748    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11749    COMPOUND_EXPR will be an argument which must be evaluated.
11750    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11751    COMPOUND_EXPR in the chain will contain the tree for the simplified
11752    form of the builtin function call.  */
11753
11754 static tree
11755 fold_builtin_strpbrk (location_t loc, tree s1, tree s2, tree type)
11756 {
11757   if (!validate_arg (s1, POINTER_TYPE)
11758       || !validate_arg (s2, POINTER_TYPE))
11759     return NULL_TREE;
11760   else
11761     {
11762       tree fn;
11763       const char *p1, *p2;
11764
11765       p2 = c_getstr (s2);
11766       if (p2 == NULL)
11767         return NULL_TREE;
11768
11769       p1 = c_getstr (s1);
11770       if (p1 != NULL)
11771         {
11772           const char *r = strpbrk (p1, p2);
11773           tree tem;
11774
11775           if (r == NULL)
11776             return build_int_cst (TREE_TYPE (s1), 0);
11777
11778           /* Return an offset into the constant string argument.  */
11779           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
11780           return fold_convert_loc (loc, type, tem);
11781         }
11782
11783       if (p2[0] == '\0')
11784         /* strpbrk(x, "") == NULL.
11785            Evaluate and ignore s1 in case it had side-effects.  */
11786         return omit_one_operand_loc (loc, TREE_TYPE (s1), integer_zero_node, s1);
11787
11788       if (p2[1] != '\0')
11789         return NULL_TREE;  /* Really call strpbrk.  */
11790
11791       fn = builtin_decl_implicit (BUILT_IN_STRCHR);
11792       if (!fn)
11793         return NULL_TREE;
11794
11795       /* New argument list transforming strpbrk(s1, s2) to
11796          strchr(s1, s2[0]).  */
11797       return build_call_expr_loc (loc, fn, 2, s1,
11798                                   build_int_cst (integer_type_node, p2[0]));
11799     }
11800 }
11801
11802 /* Simplify a call to the strcat builtin.  DST and SRC are the arguments
11803    to the call.
11804
11805    Return NULL_TREE if no simplification was possible, otherwise return the
11806    simplified form of the call as a tree.
11807
11808    The simplified form may be a constant or other expression which
11809    computes the same value, but in a more efficient manner (including
11810    calls to other builtin functions).
11811
11812    The call may contain arguments which need to be evaluated, but
11813    which are not useful to determine the result of the call.  In
11814    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11815    COMPOUND_EXPR will be an argument which must be evaluated.
11816    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11817    COMPOUND_EXPR in the chain will contain the tree for the simplified
11818    form of the builtin function call.  */
11819
11820 static tree
11821 fold_builtin_strcat (location_t loc ATTRIBUTE_UNUSED, tree dst, tree src)
11822 {
11823   if (!validate_arg (dst, POINTER_TYPE)
11824       || !validate_arg (src, POINTER_TYPE))
11825     return NULL_TREE;
11826   else
11827     {
11828       const char *p = c_getstr (src);
11829
11830       /* If the string length is zero, return the dst parameter.  */
11831       if (p && *p == '\0')
11832         return dst;
11833
11834       if (optimize_insn_for_speed_p ())
11835         {
11836           /* See if we can store by pieces into (dst + strlen(dst)).  */
11837           tree newdst, call;
11838           tree strlen_fn = builtin_decl_implicit (BUILT_IN_STRLEN);
11839           tree strcpy_fn = builtin_decl_implicit (BUILT_IN_STRCPY);
11840
11841           if (!strlen_fn || !strcpy_fn)
11842             return NULL_TREE;
11843
11844           /* If we don't have a movstr we don't want to emit an strcpy
11845              call.  We have to do that if the length of the source string
11846              isn't computable (in that case we can use memcpy probably
11847              later expanding to a sequence of mov instructions).  If we
11848              have movstr instructions we can emit strcpy calls.  */
11849           if (!HAVE_movstr)
11850             {
11851               tree len = c_strlen (src, 1);
11852               if (! len || TREE_SIDE_EFFECTS (len))
11853                 return NULL_TREE;
11854             }
11855
11856           /* Stabilize the argument list.  */
11857           dst = builtin_save_expr (dst);
11858
11859           /* Create strlen (dst).  */
11860           newdst = build_call_expr_loc (loc, strlen_fn, 1, dst);
11861           /* Create (dst p+ strlen (dst)).  */
11862
11863           newdst = fold_build_pointer_plus_loc (loc, dst, newdst);
11864           newdst = builtin_save_expr (newdst);
11865
11866           call = build_call_expr_loc (loc, strcpy_fn, 2, newdst, src);
11867           return build2 (COMPOUND_EXPR, TREE_TYPE (dst), call, dst);
11868         }
11869       return NULL_TREE;
11870     }
11871 }
11872
11873 /* Simplify a call to the strncat builtin.  DST, SRC, and LEN are the
11874    arguments to the call.
11875
11876    Return NULL_TREE if no simplification was possible, otherwise return the
11877    simplified form of the call as a tree.
11878
11879    The simplified form may be a constant or other expression which
11880    computes the same value, but in a more efficient manner (including
11881    calls to other builtin functions).
11882
11883    The call may contain arguments which need to be evaluated, but
11884    which are not useful to determine the result of the call.  In
11885    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11886    COMPOUND_EXPR will be an argument which must be evaluated.
11887    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11888    COMPOUND_EXPR in the chain will contain the tree for the simplified
11889    form of the builtin function call.  */
11890
11891 static tree
11892 fold_builtin_strncat (location_t loc, tree dst, tree src, tree len)
11893 {
11894   if (!validate_arg (dst, POINTER_TYPE)
11895       || !validate_arg (src, POINTER_TYPE)
11896       || !validate_arg (len, INTEGER_TYPE))
11897     return NULL_TREE;
11898   else
11899     {
11900       const char *p = c_getstr (src);
11901
11902       /* If the requested length is zero, or the src parameter string
11903          length is zero, return the dst parameter.  */
11904       if (integer_zerop (len) || (p && *p == '\0'))
11905         return omit_two_operands_loc (loc, TREE_TYPE (dst), dst, src, len);
11906
11907       /* If the requested len is greater than or equal to the string
11908          length, call strcat.  */
11909       if (TREE_CODE (len) == INTEGER_CST && p
11910           && compare_tree_int (len, strlen (p)) >= 0)
11911         {
11912           tree fn = builtin_decl_implicit (BUILT_IN_STRCAT);
11913
11914           /* If the replacement _DECL isn't initialized, don't do the
11915              transformation.  */
11916           if (!fn)
11917             return NULL_TREE;
11918
11919           return build_call_expr_loc (loc, fn, 2, dst, src);
11920         }
11921       return NULL_TREE;
11922     }
11923 }
11924
11925 /* Simplify a call to the strspn builtin.  S1 and S2 are the arguments
11926    to the call.
11927
11928    Return NULL_TREE if no simplification was possible, otherwise return the
11929    simplified form of the call as a tree.
11930
11931    The simplified form may be a constant or other expression which
11932    computes the same value, but in a more efficient manner (including
11933    calls to other builtin functions).
11934
11935    The call may contain arguments which need to be evaluated, but
11936    which are not useful to determine the result of the call.  In
11937    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11938    COMPOUND_EXPR will be an argument which must be evaluated.
11939    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11940    COMPOUND_EXPR in the chain will contain the tree for the simplified
11941    form of the builtin function call.  */
11942
11943 static tree
11944 fold_builtin_strspn (location_t loc, tree s1, tree s2)
11945 {
11946   if (!validate_arg (s1, POINTER_TYPE)
11947       || !validate_arg (s2, POINTER_TYPE))
11948     return NULL_TREE;
11949   else
11950     {
11951       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
11952
11953       /* If both arguments are constants, evaluate at compile-time.  */
11954       if (p1 && p2)
11955         {
11956           const size_t r = strspn (p1, p2);
11957           return build_int_cst (size_type_node, r);
11958         }
11959
11960       /* If either argument is "", return NULL_TREE.  */
11961       if ((p1 && *p1 == '\0') || (p2 && *p2 == '\0'))
11962         /* Evaluate and ignore both arguments in case either one has
11963            side-effects.  */
11964         return omit_two_operands_loc (loc, size_type_node, size_zero_node,
11965                                   s1, s2);
11966       return NULL_TREE;
11967     }
11968 }
11969
11970 /* Simplify a call to the strcspn builtin.  S1 and S2 are the arguments
11971    to the call.
11972
11973    Return NULL_TREE if no simplification was possible, otherwise return the
11974    simplified form of the call as a tree.
11975
11976    The simplified form may be a constant or other expression which
11977    computes the same value, but in a more efficient manner (including
11978    calls to other builtin functions).
11979
11980    The call may contain arguments which need to be evaluated, but
11981    which are not useful to determine the result of the call.  In
11982    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11983    COMPOUND_EXPR will be an argument which must be evaluated.
11984    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11985    COMPOUND_EXPR in the chain will contain the tree for the simplified
11986    form of the builtin function call.  */
11987
11988 static tree
11989 fold_builtin_strcspn (location_t loc, tree s1, tree s2)
11990 {
11991   if (!validate_arg (s1, POINTER_TYPE)
11992       || !validate_arg (s2, POINTER_TYPE))
11993     return NULL_TREE;
11994   else
11995     {
11996       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
11997
11998       /* If both arguments are constants, evaluate at compile-time.  */
11999       if (p1 && p2)
12000         {
12001           const size_t r = strcspn (p1, p2);
12002           return build_int_cst (size_type_node, r);
12003         }
12004
12005       /* If the first argument is "", return NULL_TREE.  */
12006       if (p1 && *p1 == '\0')
12007         {
12008           /* Evaluate and ignore argument s2 in case it has
12009              side-effects.  */
12010           return omit_one_operand_loc (loc, size_type_node,
12011                                    size_zero_node, s2);
12012         }
12013
12014       /* If the second argument is "", return __builtin_strlen(s1).  */
12015       if (p2 && *p2 == '\0')
12016         {
12017           tree fn = builtin_decl_implicit (BUILT_IN_STRLEN);
12018
12019           /* If the replacement _DECL isn't initialized, don't do the
12020              transformation.  */
12021           if (!fn)
12022             return NULL_TREE;
12023
12024           return build_call_expr_loc (loc, fn, 1, s1);
12025         }
12026       return NULL_TREE;
12027     }
12028 }
12029
12030 /* Fold a call to the fputs builtin.  ARG0 and ARG1 are the arguments
12031    to the call.  IGNORE is true if the value returned
12032    by the builtin will be ignored.  UNLOCKED is true is true if this
12033    actually a call to fputs_unlocked.  If LEN in non-NULL, it represents
12034    the known length of the string.  Return NULL_TREE if no simplification
12035    was possible.  */
12036
12037 tree
12038 fold_builtin_fputs (location_t loc, tree arg0, tree arg1,
12039                     bool ignore, bool unlocked, tree len)
12040 {
12041   /* If we're using an unlocked function, assume the other unlocked
12042      functions exist explicitly.  */
12043   tree const fn_fputc = (unlocked
12044                          ? builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED)
12045                          : builtin_decl_implicit (BUILT_IN_FPUTC));
12046   tree const fn_fwrite = (unlocked
12047                           ? builtin_decl_explicit (BUILT_IN_FWRITE_UNLOCKED)
12048                           : builtin_decl_implicit (BUILT_IN_FWRITE));
12049
12050   /* If the return value is used, don't do the transformation.  */
12051   if (!ignore)
12052     return NULL_TREE;
12053
12054   /* Verify the arguments in the original call.  */
12055   if (!validate_arg (arg0, POINTER_TYPE)
12056       || !validate_arg (arg1, POINTER_TYPE))
12057     return NULL_TREE;
12058
12059   if (! len)
12060     len = c_strlen (arg0, 0);
12061
12062   /* Get the length of the string passed to fputs.  If the length
12063      can't be determined, punt.  */
12064   if (!len
12065       || TREE_CODE (len) != INTEGER_CST)
12066     return NULL_TREE;
12067
12068   switch (compare_tree_int (len, 1))
12069     {
12070     case -1: /* length is 0, delete the call entirely .  */
12071       return omit_one_operand_loc (loc, integer_type_node,
12072                                integer_zero_node, arg1);;
12073
12074     case 0: /* length is 1, call fputc.  */
12075       {
12076         const char *p = c_getstr (arg0);
12077
12078         if (p != NULL)
12079           {
12080             if (fn_fputc)
12081               return build_call_expr_loc (loc, fn_fputc, 2,
12082                                           build_int_cst
12083                                             (integer_type_node, p[0]), arg1);
12084             else
12085               return NULL_TREE;
12086           }
12087       }
12088       /* FALLTHROUGH */
12089     case 1: /* length is greater than 1, call fwrite.  */
12090       {
12091         /* If optimizing for size keep fputs.  */
12092         if (optimize_function_for_size_p (cfun))
12093           return NULL_TREE;
12094         /* New argument list transforming fputs(string, stream) to
12095            fwrite(string, 1, len, stream).  */
12096         if (fn_fwrite)
12097           return build_call_expr_loc (loc, fn_fwrite, 4, arg0,
12098                                   size_one_node, len, arg1);
12099         else
12100           return NULL_TREE;
12101       }
12102     default:
12103       gcc_unreachable ();
12104     }
12105   return NULL_TREE;
12106 }
12107
12108 /* Fold the next_arg or va_start call EXP. Returns true if there was an error
12109    produced.  False otherwise.  This is done so that we don't output the error
12110    or warning twice or three times.  */
12111
12112 bool
12113 fold_builtin_next_arg (tree exp, bool va_start_p)
12114 {
12115   tree fntype = TREE_TYPE (current_function_decl);
12116   int nargs = call_expr_nargs (exp);
12117   tree arg;
12118   /* There is good chance the current input_location points inside the
12119      definition of the va_start macro (perhaps on the token for
12120      builtin) in a system header, so warnings will not be emitted.
12121      Use the location in real source code.  */
12122   source_location current_location =
12123     linemap_unwind_to_first_non_reserved_loc (line_table, input_location,
12124                                               NULL);
12125
12126   if (!stdarg_p (fntype))
12127     {
12128       error ("%<va_start%> used in function with fixed args");
12129       return true;
12130     }
12131
12132   if (va_start_p)
12133     {
12134       if (va_start_p && (nargs != 2))
12135         {
12136           error ("wrong number of arguments to function %<va_start%>");
12137           return true;
12138         }
12139       arg = CALL_EXPR_ARG (exp, 1);
12140     }
12141   /* We use __builtin_va_start (ap, 0, 0) or __builtin_next_arg (0, 0)
12142      when we checked the arguments and if needed issued a warning.  */
12143   else
12144     {
12145       if (nargs == 0)
12146         {
12147           /* Evidently an out of date version of <stdarg.h>; can't validate
12148              va_start's second argument, but can still work as intended.  */
12149           warning_at (current_location,
12150                       OPT_Wvarargs,
12151                    "%<__builtin_next_arg%> called without an argument");
12152           return true;
12153         }
12154       else if (nargs > 1)
12155         {
12156           error ("wrong number of arguments to function %<__builtin_next_arg%>");
12157           return true;
12158         }
12159       arg = CALL_EXPR_ARG (exp, 0);
12160     }
12161
12162   if (TREE_CODE (arg) == SSA_NAME)
12163     arg = SSA_NAME_VAR (arg);
12164
12165   /* We destructively modify the call to be __builtin_va_start (ap, 0)
12166      or __builtin_next_arg (0) the first time we see it, after checking
12167      the arguments and if needed issuing a warning.  */
12168   if (!integer_zerop (arg))
12169     {
12170       tree last_parm = tree_last (DECL_ARGUMENTS (current_function_decl));
12171
12172       /* Strip off all nops for the sake of the comparison.  This
12173          is not quite the same as STRIP_NOPS.  It does more.
12174          We must also strip off INDIRECT_EXPR for C++ reference
12175          parameters.  */
12176       while (CONVERT_EXPR_P (arg)
12177              || TREE_CODE (arg) == INDIRECT_REF)
12178         arg = TREE_OPERAND (arg, 0);
12179       if (arg != last_parm)
12180         {
12181           /* FIXME: Sometimes with the tree optimizers we can get the
12182              not the last argument even though the user used the last
12183              argument.  We just warn and set the arg to be the last
12184              argument so that we will get wrong-code because of
12185              it.  */
12186           warning_at (current_location,
12187                       OPT_Wvarargs,
12188                       "second parameter of %<va_start%> not last named argument");
12189         }
12190
12191       /* Undefined by C99 7.15.1.4p4 (va_start):
12192          "If the parameter parmN is declared with the register storage
12193          class, with a function or array type, or with a type that is
12194          not compatible with the type that results after application of
12195          the default argument promotions, the behavior is undefined."
12196       */
12197       else if (DECL_REGISTER (arg))
12198         {
12199           warning_at (current_location,
12200                       OPT_Wvarargs,
12201                       "undefined behaviour when second parameter of "
12202                       "%<va_start%> is declared with %<register%> storage");
12203         }
12204
12205       /* We want to verify the second parameter just once before the tree
12206          optimizers are run and then avoid keeping it in the tree,
12207          as otherwise we could warn even for correct code like:
12208          void foo (int i, ...)
12209          { va_list ap; i++; va_start (ap, i); va_end (ap); }  */
12210       if (va_start_p)
12211         CALL_EXPR_ARG (exp, 1) = integer_zero_node;
12212       else
12213         CALL_EXPR_ARG (exp, 0) = integer_zero_node;
12214     }
12215   return false;
12216 }
12217
12218
12219 /* Simplify a call to the sprintf builtin with arguments DEST, FMT, and ORIG.
12220    ORIG may be null if this is a 2-argument call.  We don't attempt to
12221    simplify calls with more than 3 arguments.
12222
12223    Return NULL_TREE if no simplification was possible, otherwise return the
12224    simplified form of the call as a tree.  If IGNORED is true, it means that
12225    the caller does not use the returned value of the function.  */
12226
12227 static tree
12228 fold_builtin_sprintf (location_t loc, tree dest, tree fmt,
12229                       tree orig, int ignored)
12230 {
12231   tree call, retval;
12232   const char *fmt_str = NULL;
12233
12234   /* Verify the required arguments in the original call.  We deal with two
12235      types of sprintf() calls: 'sprintf (str, fmt)' and
12236      'sprintf (dest, "%s", orig)'.  */
12237   if (!validate_arg (dest, POINTER_TYPE)
12238       || !validate_arg (fmt, POINTER_TYPE))
12239     return NULL_TREE;
12240   if (orig && !validate_arg (orig, POINTER_TYPE))
12241     return NULL_TREE;
12242
12243   /* Check whether the format is a literal string constant.  */
12244   fmt_str = c_getstr (fmt);
12245   if (fmt_str == NULL)
12246     return NULL_TREE;
12247
12248   call = NULL_TREE;
12249   retval = NULL_TREE;
12250
12251   if (!init_target_chars ())
12252     return NULL_TREE;
12253
12254   /* If the format doesn't contain % args or %%, use strcpy.  */
12255   if (strchr (fmt_str, target_percent) == NULL)
12256     {
12257       tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
12258
12259       if (!fn)
12260         return NULL_TREE;
12261
12262       /* Don't optimize sprintf (buf, "abc", ptr++).  */
12263       if (orig)
12264         return NULL_TREE;
12265
12266       /* Convert sprintf (str, fmt) into strcpy (str, fmt) when
12267          'format' is known to contain no % formats.  */
12268       call = build_call_expr_loc (loc, fn, 2, dest, fmt);
12269       if (!ignored)
12270         retval = build_int_cst (integer_type_node, strlen (fmt_str));
12271     }
12272
12273   /* If the format is "%s", use strcpy if the result isn't used.  */
12274   else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
12275     {
12276       tree fn;
12277       fn = builtin_decl_implicit (BUILT_IN_STRCPY);
12278
12279       if (!fn)
12280         return NULL_TREE;
12281
12282       /* Don't crash on sprintf (str1, "%s").  */
12283       if (!orig)
12284         return NULL_TREE;
12285
12286       /* Convert sprintf (str1, "%s", str2) into strcpy (str1, str2).  */
12287       if (!ignored)
12288         {
12289           retval = c_strlen (orig, 1);
12290           if (!retval || TREE_CODE (retval) != INTEGER_CST)
12291             return NULL_TREE;
12292         }
12293       call = build_call_expr_loc (loc, fn, 2, dest, orig);
12294     }
12295
12296   if (call && retval)
12297     {
12298       retval = fold_convert_loc
12299         (loc, TREE_TYPE (TREE_TYPE (builtin_decl_implicit (BUILT_IN_SPRINTF))),
12300          retval);
12301       return build2 (COMPOUND_EXPR, TREE_TYPE (retval), call, retval);
12302     }
12303   else
12304     return call;
12305 }
12306
12307 /* Simplify a call to the snprintf builtin with arguments DEST, DESTSIZE,
12308    FMT, and ORIG.  ORIG may be null if this is a 3-argument call.  We don't
12309    attempt to simplify calls with more than 4 arguments.
12310
12311    Return NULL_TREE if no simplification was possible, otherwise return the
12312    simplified form of the call as a tree.  If IGNORED is true, it means that
12313    the caller does not use the returned value of the function.  */
12314
12315 static tree
12316 fold_builtin_snprintf (location_t loc, tree dest, tree destsize, tree fmt,
12317                        tree orig, int ignored)
12318 {
12319   tree call, retval;
12320   const char *fmt_str = NULL;
12321   unsigned HOST_WIDE_INT destlen;
12322
12323   /* Verify the required arguments in the original call.  We deal with two
12324      types of snprintf() calls: 'snprintf (str, cst, fmt)' and
12325      'snprintf (dest, cst, "%s", orig)'.  */
12326   if (!validate_arg (dest, POINTER_TYPE)
12327       || !validate_arg (destsize, INTEGER_TYPE)
12328       || !validate_arg (fmt, POINTER_TYPE))
12329     return NULL_TREE;
12330   if (orig && !validate_arg (orig, POINTER_TYPE))
12331     return NULL_TREE;
12332
12333   if (!host_integerp (destsize, 1))
12334     return NULL_TREE;
12335
12336   /* Check whether the format is a literal string constant.  */
12337   fmt_str = c_getstr (fmt);
12338   if (fmt_str == NULL)
12339     return NULL_TREE;
12340
12341   call = NULL_TREE;
12342   retval = NULL_TREE;
12343
12344   if (!init_target_chars ())
12345     return NULL_TREE;
12346
12347   destlen = tree_low_cst (destsize, 1);
12348
12349   /* If the format doesn't contain % args or %%, use strcpy.  */
12350   if (strchr (fmt_str, target_percent) == NULL)
12351     {
12352       tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
12353       size_t len = strlen (fmt_str);
12354
12355       /* Don't optimize snprintf (buf, 4, "abc", ptr++).  */
12356       if (orig)
12357         return NULL_TREE;
12358
12359       /* We could expand this as
12360          memcpy (str, fmt, cst - 1); str[cst - 1] = '\0';
12361          or to
12362          memcpy (str, fmt_with_nul_at_cstm1, cst);
12363          but in the former case that might increase code size
12364          and in the latter case grow .rodata section too much.
12365          So punt for now.  */
12366       if (len >= destlen)
12367         return NULL_TREE;
12368
12369       if (!fn)
12370         return NULL_TREE;
12371
12372       /* Convert snprintf (str, cst, fmt) into strcpy (str, fmt) when
12373          'format' is known to contain no % formats and
12374          strlen (fmt) < cst.  */
12375       call = build_call_expr_loc (loc, fn, 2, dest, fmt);
12376
12377       if (!ignored)
12378         retval = build_int_cst (integer_type_node, strlen (fmt_str));
12379     }
12380
12381   /* If the format is "%s", use strcpy if the result isn't used.  */
12382   else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
12383     {
12384       tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
12385       unsigned HOST_WIDE_INT origlen;
12386
12387       /* Don't crash on snprintf (str1, cst, "%s").  */
12388       if (!orig)
12389         return NULL_TREE;
12390
12391       retval = c_strlen (orig, 1);
12392       if (!retval || !host_integerp (retval, 1))  
12393         return NULL_TREE;
12394
12395       origlen = tree_low_cst (retval, 1);
12396       /* We could expand this as
12397          memcpy (str1, str2, cst - 1); str1[cst - 1] = '\0';
12398          or to
12399          memcpy (str1, str2_with_nul_at_cstm1, cst);
12400          but in the former case that might increase code size
12401          and in the latter case grow .rodata section too much.
12402          So punt for now.  */
12403       if (origlen >= destlen)
12404         return NULL_TREE;
12405
12406       /* Convert snprintf (str1, cst, "%s", str2) into
12407          strcpy (str1, str2) if strlen (str2) < cst.  */
12408       if (!fn)
12409         return NULL_TREE;
12410
12411       call = build_call_expr_loc (loc, fn, 2, dest, orig);
12412
12413       if (ignored)
12414         retval = NULL_TREE;
12415     }
12416
12417   if (call && retval)
12418     {
12419       tree fn = builtin_decl_explicit (BUILT_IN_SNPRINTF);
12420       retval = fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fn)), retval);
12421       return build2 (COMPOUND_EXPR, TREE_TYPE (retval), call, retval);
12422     }
12423   else
12424     return call;
12425 }
12426
12427 /* Expand a call EXP to __builtin_object_size.  */
12428
12429 rtx
12430 expand_builtin_object_size (tree exp)
12431 {
12432   tree ost;
12433   int object_size_type;
12434   tree fndecl = get_callee_fndecl (exp);
12435
12436   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
12437     {
12438       error ("%Kfirst argument of %D must be a pointer, second integer constant",
12439              exp, fndecl);
12440       expand_builtin_trap ();
12441       return const0_rtx;
12442     }
12443
12444   ost = CALL_EXPR_ARG (exp, 1);
12445   STRIP_NOPS (ost);
12446
12447   if (TREE_CODE (ost) != INTEGER_CST
12448       || tree_int_cst_sgn (ost) < 0
12449       || compare_tree_int (ost, 3) > 0)
12450     {
12451       error ("%Klast argument of %D is not integer constant between 0 and 3",
12452              exp, fndecl);
12453       expand_builtin_trap ();
12454       return const0_rtx;
12455     }
12456
12457   object_size_type = tree_low_cst (ost, 0);
12458
12459   return object_size_type < 2 ? constm1_rtx : const0_rtx;
12460 }
12461
12462 /* Expand EXP, a call to the __mem{cpy,pcpy,move,set}_chk builtin.
12463    FCODE is the BUILT_IN_* to use.
12464    Return NULL_RTX if we failed; the caller should emit a normal call,
12465    otherwise try to get the result in TARGET, if convenient (and in
12466    mode MODE if that's convenient).  */
12467
12468 static rtx
12469 expand_builtin_memory_chk (tree exp, rtx target, enum machine_mode mode,
12470                            enum built_in_function fcode)
12471 {
12472   tree dest, src, len, size;
12473
12474   if (!validate_arglist (exp,
12475                          POINTER_TYPE,
12476                          fcode == BUILT_IN_MEMSET_CHK
12477                          ? INTEGER_TYPE : POINTER_TYPE,
12478                          INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
12479     return NULL_RTX;
12480
12481   dest = CALL_EXPR_ARG (exp, 0);
12482   src = CALL_EXPR_ARG (exp, 1);
12483   len = CALL_EXPR_ARG (exp, 2);
12484   size = CALL_EXPR_ARG (exp, 3);
12485
12486   if (! host_integerp (size, 1))
12487     return NULL_RTX;
12488
12489   if (host_integerp (len, 1) || integer_all_onesp (size))
12490     {
12491       tree fn;
12492
12493       if (! integer_all_onesp (size) && tree_int_cst_lt (size, len))
12494         {
12495           warning_at (tree_nonartificial_location (exp),
12496                       0, "%Kcall to %D will always overflow destination buffer",
12497                       exp, get_callee_fndecl (exp));
12498           return NULL_RTX;
12499         }
12500
12501       fn = NULL_TREE;
12502       /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
12503          mem{cpy,pcpy,move,set} is available.  */
12504       switch (fcode)
12505         {
12506         case BUILT_IN_MEMCPY_CHK:
12507           fn = builtin_decl_explicit (BUILT_IN_MEMCPY);
12508           break;
12509         case BUILT_IN_MEMPCPY_CHK:
12510           fn = builtin_decl_explicit (BUILT_IN_MEMPCPY);
12511           break;
12512         case BUILT_IN_MEMMOVE_CHK:
12513           fn = builtin_decl_explicit (BUILT_IN_MEMMOVE);
12514           break;
12515         case BUILT_IN_MEMSET_CHK:
12516           fn = builtin_decl_explicit (BUILT_IN_MEMSET);
12517           break;
12518         default:
12519           break;
12520         }
12521
12522       if (! fn)
12523         return NULL_RTX;
12524
12525       fn = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 3, dest, src, len);
12526       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
12527       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
12528       return expand_expr (fn, target, mode, EXPAND_NORMAL);
12529     }
12530   else if (fcode == BUILT_IN_MEMSET_CHK)
12531     return NULL_RTX;
12532   else
12533     {
12534       unsigned int dest_align = get_pointer_alignment (dest);
12535
12536       /* If DEST is not a pointer type, call the normal function.  */
12537       if (dest_align == 0)
12538         return NULL_RTX;
12539
12540       /* If SRC and DEST are the same (and not volatile), do nothing.  */
12541       if (operand_equal_p (src, dest, 0))
12542         {
12543           tree expr;
12544
12545           if (fcode != BUILT_IN_MEMPCPY_CHK)
12546             {
12547               /* Evaluate and ignore LEN in case it has side-effects.  */
12548               expand_expr (len, const0_rtx, VOIDmode, EXPAND_NORMAL);
12549               return expand_expr (dest, target, mode, EXPAND_NORMAL);
12550             }
12551
12552           expr = fold_build_pointer_plus (dest, len);
12553           return expand_expr (expr, target, mode, EXPAND_NORMAL);
12554         }
12555
12556       /* __memmove_chk special case.  */
12557       if (fcode == BUILT_IN_MEMMOVE_CHK)
12558         {
12559           unsigned int src_align = get_pointer_alignment (src);
12560
12561           if (src_align == 0)
12562             return NULL_RTX;
12563
12564           /* If src is categorized for a readonly section we can use
12565              normal __memcpy_chk.  */
12566           if (readonly_data_expr (src))
12567             {
12568               tree fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
12569               if (!fn)
12570                 return NULL_RTX;
12571               fn = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 4,
12572                                           dest, src, len, size);
12573               gcc_assert (TREE_CODE (fn) == CALL_EXPR);
12574               CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
12575               return expand_expr (fn, target, mode, EXPAND_NORMAL);
12576             }
12577         }
12578       return NULL_RTX;
12579     }
12580 }
12581
12582 /* Emit warning if a buffer overflow is detected at compile time.  */
12583
12584 static void
12585 maybe_emit_chk_warning (tree exp, enum built_in_function fcode)
12586 {
12587   int is_strlen = 0;
12588   tree len, size;
12589   location_t loc = tree_nonartificial_location (exp);
12590
12591   switch (fcode)
12592     {
12593     case BUILT_IN_STRCPY_CHK:
12594     case BUILT_IN_STPCPY_CHK:
12595     /* For __strcat_chk the warning will be emitted only if overflowing
12596        by at least strlen (dest) + 1 bytes.  */
12597     case BUILT_IN_STRCAT_CHK:
12598       len = CALL_EXPR_ARG (exp, 1);
12599       size = CALL_EXPR_ARG (exp, 2);
12600       is_strlen = 1;
12601       break;
12602     case BUILT_IN_STRNCAT_CHK:
12603     case BUILT_IN_STRNCPY_CHK:
12604     case BUILT_IN_STPNCPY_CHK:
12605       len = CALL_EXPR_ARG (exp, 2);
12606       size = CALL_EXPR_ARG (exp, 3);
12607       break;
12608     case BUILT_IN_SNPRINTF_CHK:
12609     case BUILT_IN_VSNPRINTF_CHK:
12610       len = CALL_EXPR_ARG (exp, 1);
12611       size = CALL_EXPR_ARG (exp, 3);
12612       break;
12613     default:
12614       gcc_unreachable ();
12615     }
12616
12617   if (!len || !size)
12618     return;
12619
12620   if (! host_integerp (size, 1) || integer_all_onesp (size))
12621     return;
12622
12623   if (is_strlen)
12624     {
12625       len = c_strlen (len, 1);
12626       if (! len || ! host_integerp (len, 1) || tree_int_cst_lt (len, size))
12627         return;
12628     }
12629   else if (fcode == BUILT_IN_STRNCAT_CHK)
12630     {
12631       tree src = CALL_EXPR_ARG (exp, 1);
12632       if (! src || ! host_integerp (len, 1) || tree_int_cst_lt (len, size))
12633         return;
12634       src = c_strlen (src, 1);
12635       if (! src || ! host_integerp (src, 1))
12636         {
12637           warning_at (loc, 0, "%Kcall to %D might overflow destination buffer",
12638                       exp, get_callee_fndecl (exp));
12639           return;
12640         }
12641       else if (tree_int_cst_lt (src, size))
12642         return;
12643     }
12644   else if (! host_integerp (len, 1) || ! tree_int_cst_lt (size, len))
12645     return;
12646
12647   warning_at (loc, 0, "%Kcall to %D will always overflow destination buffer",
12648               exp, get_callee_fndecl (exp));
12649 }
12650
12651 /* Emit warning if a buffer overflow is detected at compile time
12652    in __sprintf_chk/__vsprintf_chk calls.  */
12653
12654 static void
12655 maybe_emit_sprintf_chk_warning (tree exp, enum built_in_function fcode)
12656 {
12657   tree size, len, fmt;
12658   const char *fmt_str;
12659   int nargs = call_expr_nargs (exp);
12660
12661   /* Verify the required arguments in the original call.  */
12662
12663   if (nargs < 4)
12664     return;
12665   size = CALL_EXPR_ARG (exp, 2);
12666   fmt = CALL_EXPR_ARG (exp, 3);
12667
12668   if (! host_integerp (size, 1) || integer_all_onesp (size))
12669     return;
12670
12671   /* Check whether the format is a literal string constant.  */
12672   fmt_str = c_getstr (fmt);
12673   if (fmt_str == NULL)
12674     return;
12675
12676   if (!init_target_chars ())
12677     return;
12678
12679   /* If the format doesn't contain % args or %%, we know its size.  */
12680   if (strchr (fmt_str, target_percent) == 0)
12681     len = build_int_cstu (size_type_node, strlen (fmt_str));
12682   /* If the format is "%s" and first ... argument is a string literal,
12683      we know it too.  */
12684   else if (fcode == BUILT_IN_SPRINTF_CHK
12685            && strcmp (fmt_str, target_percent_s) == 0)
12686     {
12687       tree arg;
12688
12689       if (nargs < 5)
12690         return;
12691       arg = CALL_EXPR_ARG (exp, 4);
12692       if (! POINTER_TYPE_P (TREE_TYPE (arg)))
12693         return;
12694
12695       len = c_strlen (arg, 1);
12696       if (!len || ! host_integerp (len, 1))
12697         return;
12698     }
12699   else
12700     return;
12701
12702   if (! tree_int_cst_lt (len, size))
12703     warning_at (tree_nonartificial_location (exp),
12704                 0, "%Kcall to %D will always overflow destination buffer",
12705                 exp, get_callee_fndecl (exp));
12706 }
12707
12708 /* Emit warning if a free is called with address of a variable.  */
12709
12710 static void
12711 maybe_emit_free_warning (tree exp)
12712 {
12713   tree arg = CALL_EXPR_ARG (exp, 0);
12714
12715   STRIP_NOPS (arg);
12716   if (TREE_CODE (arg) != ADDR_EXPR)
12717     return;
12718
12719   arg = get_base_address (TREE_OPERAND (arg, 0));
12720   if (arg == NULL || INDIRECT_REF_P (arg) || TREE_CODE (arg) == MEM_REF)
12721     return;
12722
12723   if (SSA_VAR_P (arg))
12724     warning_at (tree_nonartificial_location (exp), OPT_Wfree_nonheap_object,
12725                 "%Kattempt to free a non-heap object %qD", exp, arg);
12726   else
12727     warning_at (tree_nonartificial_location (exp), OPT_Wfree_nonheap_object,
12728                 "%Kattempt to free a non-heap object", exp);
12729 }
12730
12731 /* Fold a call to __builtin_object_size with arguments PTR and OST,
12732    if possible.  */
12733
12734 tree
12735 fold_builtin_object_size (tree ptr, tree ost)
12736 {
12737   unsigned HOST_WIDE_INT bytes;
12738   int object_size_type;
12739
12740   if (!validate_arg (ptr, POINTER_TYPE)
12741       || !validate_arg (ost, INTEGER_TYPE))
12742     return NULL_TREE;
12743
12744   STRIP_NOPS (ost);
12745
12746   if (TREE_CODE (ost) != INTEGER_CST
12747       || tree_int_cst_sgn (ost) < 0
12748       || compare_tree_int (ost, 3) > 0)
12749     return NULL_TREE;
12750
12751   object_size_type = tree_low_cst (ost, 0);
12752
12753   /* __builtin_object_size doesn't evaluate side-effects in its arguments;
12754      if there are any side-effects, it returns (size_t) -1 for types 0 and 1
12755      and (size_t) 0 for types 2 and 3.  */
12756   if (TREE_SIDE_EFFECTS (ptr))
12757     return build_int_cst_type (size_type_node, object_size_type < 2 ? -1 : 0);
12758
12759   if (TREE_CODE (ptr) == ADDR_EXPR)
12760     {
12761       bytes = compute_builtin_object_size (ptr, object_size_type);
12762       if (double_int_fits_to_tree_p (size_type_node,
12763                                      double_int::from_uhwi (bytes)))
12764         return build_int_cstu (size_type_node, bytes);
12765     }
12766   else if (TREE_CODE (ptr) == SSA_NAME)
12767     {
12768       /* If object size is not known yet, delay folding until
12769        later.  Maybe subsequent passes will help determining
12770        it.  */
12771       bytes = compute_builtin_object_size (ptr, object_size_type);
12772       if (bytes != (unsigned HOST_WIDE_INT) (object_size_type < 2 ? -1 : 0)
12773           && double_int_fits_to_tree_p (size_type_node,
12774                                         double_int::from_uhwi (bytes)))
12775         return build_int_cstu (size_type_node, bytes);
12776     }
12777
12778   return NULL_TREE;
12779 }
12780
12781 /* Fold a call to the __mem{cpy,pcpy,move,set}_chk builtin.
12782    DEST, SRC, LEN, and SIZE are the arguments to the call.
12783    IGNORE is true, if return value can be ignored.  FCODE is the BUILT_IN_*
12784    code of the builtin.  If MAXLEN is not NULL, it is maximum length
12785    passed as third argument.  */
12786
12787 tree
12788 fold_builtin_memory_chk (location_t loc, tree fndecl,
12789                          tree dest, tree src, tree len, tree size,
12790                          tree maxlen, bool ignore,
12791                          enum built_in_function fcode)
12792 {
12793   tree fn;
12794
12795   if (!validate_arg (dest, POINTER_TYPE)
12796       || !validate_arg (src,
12797                         (fcode == BUILT_IN_MEMSET_CHK
12798                          ? INTEGER_TYPE : POINTER_TYPE))
12799       || !validate_arg (len, INTEGER_TYPE)
12800       || !validate_arg (size, INTEGER_TYPE))
12801     return NULL_TREE;
12802
12803   /* If SRC and DEST are the same (and not volatile), return DEST
12804      (resp. DEST+LEN for __mempcpy_chk).  */
12805   if (fcode != BUILT_IN_MEMSET_CHK && operand_equal_p (src, dest, 0))
12806     {
12807       if (fcode != BUILT_IN_MEMPCPY_CHK)
12808         return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
12809                                  dest, len);
12810       else
12811         {
12812           tree temp = fold_build_pointer_plus_loc (loc, dest, len);
12813           return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), temp);
12814         }
12815     }
12816
12817   if (! host_integerp (size, 1))
12818     return NULL_TREE;
12819
12820   if (! integer_all_onesp (size))
12821     {
12822       if (! host_integerp (len, 1))
12823         {
12824           /* If LEN is not constant, try MAXLEN too.
12825              For MAXLEN only allow optimizing into non-_ocs function
12826              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12827           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12828             {
12829               if (fcode == BUILT_IN_MEMPCPY_CHK && ignore)
12830                 {
12831                   /* (void) __mempcpy_chk () can be optimized into
12832                      (void) __memcpy_chk ().  */
12833                   fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
12834                   if (!fn)
12835                     return NULL_TREE;
12836
12837                   return build_call_expr_loc (loc, fn, 4, dest, src, len, size);
12838                 }
12839               return NULL_TREE;
12840             }
12841         }
12842       else
12843         maxlen = len;
12844
12845       if (tree_int_cst_lt (size, maxlen))
12846         return NULL_TREE;
12847     }
12848
12849   fn = NULL_TREE;
12850   /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
12851      mem{cpy,pcpy,move,set} is available.  */
12852   switch (fcode)
12853     {
12854     case BUILT_IN_MEMCPY_CHK:
12855       fn = builtin_decl_explicit (BUILT_IN_MEMCPY);
12856       break;
12857     case BUILT_IN_MEMPCPY_CHK:
12858       fn = builtin_decl_explicit (BUILT_IN_MEMPCPY);
12859       break;
12860     case BUILT_IN_MEMMOVE_CHK:
12861       fn = builtin_decl_explicit (BUILT_IN_MEMMOVE);
12862       break;
12863     case BUILT_IN_MEMSET_CHK:
12864       fn = builtin_decl_explicit (BUILT_IN_MEMSET);
12865       break;
12866     default:
12867       break;
12868     }
12869
12870   if (!fn)
12871     return NULL_TREE;
12872
12873   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12874 }
12875
12876 /* Fold a call to the __st[rp]cpy_chk builtin.
12877    DEST, SRC, and SIZE are the arguments to the call.
12878    IGNORE is true if return value can be ignored.  FCODE is the BUILT_IN_*
12879    code of the builtin.  If MAXLEN is not NULL, it is maximum length of
12880    strings passed as second argument.  */
12881
12882 tree
12883 fold_builtin_stxcpy_chk (location_t loc, tree fndecl, tree dest,
12884                          tree src, tree size,
12885                          tree maxlen, bool ignore,
12886                          enum built_in_function fcode)
12887 {
12888   tree len, fn;
12889
12890   if (!validate_arg (dest, POINTER_TYPE)
12891       || !validate_arg (src, POINTER_TYPE)
12892       || !validate_arg (size, INTEGER_TYPE))
12893     return NULL_TREE;
12894
12895   /* If SRC and DEST are the same (and not volatile), return DEST.  */
12896   if (fcode == BUILT_IN_STRCPY_CHK && operand_equal_p (src, dest, 0))
12897     return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest);
12898
12899   if (! host_integerp (size, 1))
12900     return NULL_TREE;
12901
12902   if (! integer_all_onesp (size))
12903     {
12904       len = c_strlen (src, 1);
12905       if (! len || ! host_integerp (len, 1))
12906         {
12907           /* If LEN is not constant, try MAXLEN too.
12908              For MAXLEN only allow optimizing into non-_ocs function
12909              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12910           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12911             {
12912               if (fcode == BUILT_IN_STPCPY_CHK)
12913                 {
12914                   if (! ignore)
12915                     return NULL_TREE;
12916
12917                   /* If return value of __stpcpy_chk is ignored,
12918                      optimize into __strcpy_chk.  */
12919                   fn = builtin_decl_explicit (BUILT_IN_STRCPY_CHK);
12920                   if (!fn)
12921                     return NULL_TREE;
12922
12923                   return build_call_expr_loc (loc, fn, 3, dest, src, size);
12924                 }
12925
12926               if (! len || TREE_SIDE_EFFECTS (len))
12927                 return NULL_TREE;
12928
12929               /* If c_strlen returned something, but not a constant,
12930                  transform __strcpy_chk into __memcpy_chk.  */
12931               fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
12932               if (!fn)
12933                 return NULL_TREE;
12934
12935               len = fold_convert_loc (loc, size_type_node, len);
12936               len = size_binop_loc (loc, PLUS_EXPR, len,
12937                                     build_int_cst (size_type_node, 1));
12938               return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
12939                                        build_call_expr_loc (loc, fn, 4,
12940                                                         dest, src, len, size));
12941             }
12942         }
12943       else
12944         maxlen = len;
12945
12946       if (! tree_int_cst_lt (maxlen, size))
12947         return NULL_TREE;
12948     }
12949
12950   /* If __builtin_st{r,p}cpy_chk is used, assume st{r,p}cpy is available.  */
12951   fn = builtin_decl_explicit (fcode == BUILT_IN_STPCPY_CHK
12952                               ? BUILT_IN_STPCPY : BUILT_IN_STRCPY);
12953   if (!fn)
12954     return NULL_TREE;
12955
12956   return build_call_expr_loc (loc, fn, 2, dest, src);
12957 }
12958
12959 /* Fold a call to the __st{r,p}ncpy_chk builtin.  DEST, SRC, LEN, and SIZE
12960    are the arguments to the call.  If MAXLEN is not NULL, it is maximum
12961    length passed as third argument. IGNORE is true if return value can be
12962    ignored. FCODE is the BUILT_IN_* code of the builtin. */
12963
12964 tree
12965 fold_builtin_stxncpy_chk (location_t loc, tree dest, tree src,
12966                           tree len, tree size, tree maxlen, bool ignore,
12967                           enum built_in_function fcode)
12968 {
12969   tree fn;
12970
12971   if (!validate_arg (dest, POINTER_TYPE)
12972       || !validate_arg (src, POINTER_TYPE)
12973       || !validate_arg (len, INTEGER_TYPE)
12974       || !validate_arg (size, INTEGER_TYPE))
12975     return NULL_TREE;
12976
12977   if (fcode == BUILT_IN_STPNCPY_CHK && ignore)
12978     {
12979        /* If return value of __stpncpy_chk is ignored,
12980           optimize into __strncpy_chk.  */
12981        fn = builtin_decl_explicit (BUILT_IN_STRNCPY_CHK);
12982        if (fn)
12983          return build_call_expr_loc (loc, fn, 4, dest, src, len, size);
12984     }
12985
12986   if (! host_integerp (size, 1))
12987     return NULL_TREE;
12988
12989   if (! integer_all_onesp (size))
12990     {
12991       if (! host_integerp (len, 1))
12992         {
12993           /* If LEN is not constant, try MAXLEN too.
12994              For MAXLEN only allow optimizing into non-_ocs function
12995              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12996           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12997             return NULL_TREE;
12998         }
12999       else
13000         maxlen = len;
13001
13002       if (tree_int_cst_lt (size, maxlen))
13003         return NULL_TREE;
13004     }
13005
13006   /* If __builtin_st{r,p}ncpy_chk is used, assume st{r,p}ncpy is available.  */
13007   fn = builtin_decl_explicit (fcode == BUILT_IN_STPNCPY_CHK
13008                               ? BUILT_IN_STPNCPY : BUILT_IN_STRNCPY);
13009   if (!fn)
13010     return NULL_TREE;
13011
13012   return build_call_expr_loc (loc, fn, 3, dest, src, len);
13013 }
13014
13015 /* Fold a call to the __strcat_chk builtin FNDECL.  DEST, SRC, and SIZE
13016    are the arguments to the call.  */
13017
13018 static tree
13019 fold_builtin_strcat_chk (location_t loc, tree fndecl, tree dest,
13020                          tree src, tree size)
13021 {
13022   tree fn;
13023   const char *p;
13024
13025   if (!validate_arg (dest, POINTER_TYPE)
13026       || !validate_arg (src, POINTER_TYPE)
13027       || !validate_arg (size, INTEGER_TYPE))
13028     return NULL_TREE;
13029
13030   p = c_getstr (src);
13031   /* If the SRC parameter is "", return DEST.  */
13032   if (p && *p == '\0')
13033     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
13034
13035   if (! host_integerp (size, 1) || ! integer_all_onesp (size))
13036     return NULL_TREE;
13037
13038   /* If __builtin_strcat_chk is used, assume strcat is available.  */
13039   fn = builtin_decl_explicit (BUILT_IN_STRCAT);
13040   if (!fn)
13041     return NULL_TREE;
13042
13043   return build_call_expr_loc (loc, fn, 2, dest, src);
13044 }
13045
13046 /* Fold a call to the __strncat_chk builtin with arguments DEST, SRC,
13047    LEN, and SIZE.  */
13048
13049 static tree
13050 fold_builtin_strncat_chk (location_t loc, tree fndecl,
13051                           tree dest, tree src, tree len, tree size)
13052 {
13053   tree fn;
13054   const char *p;
13055
13056   if (!validate_arg (dest, POINTER_TYPE)
13057       || !validate_arg (src, POINTER_TYPE)
13058       || !validate_arg (size, INTEGER_TYPE)
13059       || !validate_arg (size, INTEGER_TYPE))
13060     return NULL_TREE;
13061
13062   p = c_getstr (src);
13063   /* If the SRC parameter is "" or if LEN is 0, return DEST.  */
13064   if (p && *p == '\0')
13065     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, len);
13066   else if (integer_zerop (len))
13067     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
13068
13069   if (! host_integerp (size, 1))
13070     return NULL_TREE;
13071
13072   if (! integer_all_onesp (size))
13073     {
13074       tree src_len = c_strlen (src, 1);
13075       if (src_len
13076           && host_integerp (src_len, 1)
13077           && host_integerp (len, 1)
13078           && ! tree_int_cst_lt (len, src_len))
13079         {
13080           /* If LEN >= strlen (SRC), optimize into __strcat_chk.  */
13081           fn = builtin_decl_explicit (BUILT_IN_STRCAT_CHK);
13082           if (!fn)
13083             return NULL_TREE;
13084
13085           return build_call_expr_loc (loc, fn, 3, dest, src, size);
13086         }
13087       return NULL_TREE;
13088     }
13089
13090   /* If __builtin_strncat_chk is used, assume strncat is available.  */
13091   fn = builtin_decl_explicit (BUILT_IN_STRNCAT);
13092   if (!fn)
13093     return NULL_TREE;
13094
13095   return build_call_expr_loc (loc, fn, 3, dest, src, len);
13096 }
13097
13098 /* Fold a call EXP to __{,v}sprintf_chk having NARGS passed as ARGS.
13099    Return NULL_TREE if a normal call should be emitted rather than
13100    expanding the function inline.  FCODE is either BUILT_IN_SPRINTF_CHK
13101    or BUILT_IN_VSPRINTF_CHK.  */
13102
13103 static tree
13104 fold_builtin_sprintf_chk_1 (location_t loc, int nargs, tree *args,
13105                             enum built_in_function fcode)
13106 {
13107   tree dest, size, len, fn, fmt, flag;
13108   const char *fmt_str;
13109
13110   /* Verify the required arguments in the original call.  */
13111   if (nargs < 4)
13112     return NULL_TREE;
13113   dest = args[0];
13114   if (!validate_arg (dest, POINTER_TYPE))
13115     return NULL_TREE;
13116   flag = args[1];
13117   if (!validate_arg (flag, INTEGER_TYPE))
13118     return NULL_TREE;
13119   size = args[2];
13120   if (!validate_arg (size, INTEGER_TYPE))
13121     return NULL_TREE;
13122   fmt = args[3];
13123   if (!validate_arg (fmt, POINTER_TYPE))
13124     return NULL_TREE;
13125
13126   if (! host_integerp (size, 1))
13127     return NULL_TREE;
13128
13129   len = NULL_TREE;
13130
13131   if (!init_target_chars ())
13132     return NULL_TREE;
13133
13134   /* Check whether the format is a literal string constant.  */
13135   fmt_str = c_getstr (fmt);
13136   if (fmt_str != NULL)
13137     {
13138       /* If the format doesn't contain % args or %%, we know the size.  */
13139       if (strchr (fmt_str, target_percent) == 0)
13140         {
13141           if (fcode != BUILT_IN_SPRINTF_CHK || nargs == 4)
13142             len = build_int_cstu (size_type_node, strlen (fmt_str));
13143         }
13144       /* If the format is "%s" and first ... argument is a string literal,
13145          we know the size too.  */
13146       else if (fcode == BUILT_IN_SPRINTF_CHK
13147                && strcmp (fmt_str, target_percent_s) == 0)
13148         {
13149           tree arg;
13150
13151           if (nargs == 5)
13152             {
13153               arg = args[4];
13154               if (validate_arg (arg, POINTER_TYPE))
13155                 {
13156                   len = c_strlen (arg, 1);
13157                   if (! len || ! host_integerp (len, 1))
13158                     len = NULL_TREE;
13159                 }
13160             }
13161         }
13162     }
13163
13164   if (! integer_all_onesp (size))
13165     {
13166       if (! len || ! tree_int_cst_lt (len, size))
13167         return NULL_TREE;
13168     }
13169
13170   /* Only convert __{,v}sprintf_chk to {,v}sprintf if flag is 0
13171      or if format doesn't contain % chars or is "%s".  */
13172   if (! integer_zerop (flag))
13173     {
13174       if (fmt_str == NULL)
13175         return NULL_TREE;
13176       if (strchr (fmt_str, target_percent) != NULL
13177           && strcmp (fmt_str, target_percent_s))
13178         return NULL_TREE;
13179     }
13180
13181   /* If __builtin_{,v}sprintf_chk is used, assume {,v}sprintf is available.  */
13182   fn = builtin_decl_explicit (fcode == BUILT_IN_VSPRINTF_CHK
13183                               ? BUILT_IN_VSPRINTF : BUILT_IN_SPRINTF);
13184   if (!fn)
13185     return NULL_TREE;
13186
13187   return rewrite_call_expr_array (loc, nargs, args, 4, fn, 2, dest, fmt);
13188 }
13189
13190 /* Fold a call EXP to __{,v}sprintf_chk.  Return NULL_TREE if
13191    a normal call should be emitted rather than expanding the function
13192    inline.  FCODE is either BUILT_IN_SPRINTF_CHK or BUILT_IN_VSPRINTF_CHK.  */
13193
13194 static tree
13195 fold_builtin_sprintf_chk (location_t loc, tree exp,
13196                           enum built_in_function fcode)
13197 {
13198   return fold_builtin_sprintf_chk_1 (loc, call_expr_nargs (exp),
13199                                      CALL_EXPR_ARGP (exp), fcode);
13200 }
13201
13202 /* Fold a call EXP to {,v}snprintf having NARGS passed as ARGS.  Return
13203    NULL_TREE if a normal call should be emitted rather than expanding
13204    the function inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
13205    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
13206    passed as second argument.  */
13207
13208 static tree
13209 fold_builtin_snprintf_chk_1 (location_t loc, int nargs, tree *args,
13210                              tree maxlen, enum built_in_function fcode)
13211 {
13212   tree dest, size, len, fn, fmt, flag;
13213   const char *fmt_str;
13214
13215   /* Verify the required arguments in the original call.  */
13216   if (nargs < 5)
13217     return NULL_TREE;
13218   dest = args[0];
13219   if (!validate_arg (dest, POINTER_TYPE))
13220     return NULL_TREE;
13221   len = args[1];
13222   if (!validate_arg (len, INTEGER_TYPE))
13223     return NULL_TREE;
13224   flag = args[2];
13225   if (!validate_arg (flag, INTEGER_TYPE))
13226     return NULL_TREE;
13227   size = args[3];
13228   if (!validate_arg (size, INTEGER_TYPE))
13229     return NULL_TREE;
13230   fmt = args[4];
13231   if (!validate_arg (fmt, POINTER_TYPE))
13232     return NULL_TREE;
13233
13234   if (! host_integerp (size, 1))
13235     return NULL_TREE;
13236
13237   if (! integer_all_onesp (size))
13238     {
13239       if (! host_integerp (len, 1))
13240         {
13241           /* If LEN is not constant, try MAXLEN too.
13242              For MAXLEN only allow optimizing into non-_ocs function
13243              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
13244           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
13245             return NULL_TREE;
13246         }
13247       else
13248         maxlen = len;
13249
13250       if (tree_int_cst_lt (size, maxlen))
13251         return NULL_TREE;
13252     }
13253
13254   if (!init_target_chars ())
13255     return NULL_TREE;
13256
13257   /* Only convert __{,v}snprintf_chk to {,v}snprintf if flag is 0
13258      or if format doesn't contain % chars or is "%s".  */
13259   if (! integer_zerop (flag))
13260     {
13261       fmt_str = c_getstr (fmt);
13262       if (fmt_str == NULL)
13263         return NULL_TREE;
13264       if (strchr (fmt_str, target_percent) != NULL
13265           && strcmp (fmt_str, target_percent_s))
13266         return NULL_TREE;
13267     }
13268
13269   /* If __builtin_{,v}snprintf_chk is used, assume {,v}snprintf is
13270      available.  */
13271   fn = builtin_decl_explicit (fcode == BUILT_IN_VSNPRINTF_CHK
13272                               ? BUILT_IN_VSNPRINTF : BUILT_IN_SNPRINTF);
13273   if (!fn)
13274     return NULL_TREE;
13275
13276   return rewrite_call_expr_array (loc, nargs, args, 5, fn, 3, dest, len, fmt);
13277 }
13278
13279 /* Fold a call EXP to {,v}snprintf.  Return NULL_TREE if
13280    a normal call should be emitted rather than expanding the function
13281    inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
13282    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
13283    passed as second argument.  */
13284
13285 tree
13286 fold_builtin_snprintf_chk (location_t loc, tree exp, tree maxlen,
13287                            enum built_in_function fcode)
13288 {
13289   return fold_builtin_snprintf_chk_1 (loc, call_expr_nargs (exp),
13290                                       CALL_EXPR_ARGP (exp), maxlen, fcode);
13291 }
13292
13293 /* Fold a call to the {,v}printf{,_unlocked} and __{,v}printf_chk builtins.
13294    FMT and ARG are the arguments to the call; we don't fold cases with
13295    more than 2 arguments, and ARG may be null if this is a 1-argument case.
13296
13297    Return NULL_TREE if no simplification was possible, otherwise return the
13298    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
13299    code of the function to be simplified.  */
13300
13301 static tree
13302 fold_builtin_printf (location_t loc, tree fndecl, tree fmt,
13303                      tree arg, bool ignore,
13304                      enum built_in_function fcode)
13305 {
13306   tree fn_putchar, fn_puts, newarg, call = NULL_TREE;
13307   const char *fmt_str = NULL;
13308
13309   /* If the return value is used, don't do the transformation.  */
13310   if (! ignore)
13311     return NULL_TREE;
13312
13313   /* Verify the required arguments in the original call.  */
13314   if (!validate_arg (fmt, POINTER_TYPE))
13315     return NULL_TREE;
13316
13317   /* Check whether the format is a literal string constant.  */
13318   fmt_str = c_getstr (fmt);
13319   if (fmt_str == NULL)
13320     return NULL_TREE;
13321
13322   if (fcode == BUILT_IN_PRINTF_UNLOCKED)
13323     {
13324       /* If we're using an unlocked function, assume the other
13325          unlocked functions exist explicitly.  */
13326       fn_putchar = builtin_decl_explicit (BUILT_IN_PUTCHAR_UNLOCKED);
13327       fn_puts = builtin_decl_explicit (BUILT_IN_PUTS_UNLOCKED);
13328     }
13329   else
13330     {
13331       fn_putchar = builtin_decl_implicit (BUILT_IN_PUTCHAR);
13332       fn_puts = builtin_decl_implicit (BUILT_IN_PUTS);
13333     }
13334
13335   if (!init_target_chars ())
13336     return NULL_TREE;
13337
13338   if (strcmp (fmt_str, target_percent_s) == 0
13339       || strchr (fmt_str, target_percent) == NULL)
13340     {
13341       const char *str;
13342
13343       if (strcmp (fmt_str, target_percent_s) == 0)
13344         {
13345           if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
13346             return NULL_TREE;
13347
13348           if (!arg || !validate_arg (arg, POINTER_TYPE))
13349             return NULL_TREE;
13350
13351           str = c_getstr (arg);
13352           if (str == NULL)
13353             return NULL_TREE;
13354         }
13355       else
13356         {
13357           /* The format specifier doesn't contain any '%' characters.  */
13358           if (fcode != BUILT_IN_VPRINTF && fcode != BUILT_IN_VPRINTF_CHK
13359               && arg)
13360             return NULL_TREE;
13361           str = fmt_str;
13362         }
13363
13364       /* If the string was "", printf does nothing.  */
13365       if (str[0] == '\0')
13366         return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
13367
13368       /* If the string has length of 1, call putchar.  */
13369       if (str[1] == '\0')
13370         {
13371           /* Given printf("c"), (where c is any one character,)
13372              convert "c"[0] to an int and pass that to the replacement
13373              function.  */
13374           newarg = build_int_cst (integer_type_node, str[0]);
13375           if (fn_putchar)
13376             call = build_call_expr_loc (loc, fn_putchar, 1, newarg);
13377         }
13378       else
13379         {
13380           /* If the string was "string\n", call puts("string").  */
13381           size_t len = strlen (str);
13382           if ((unsigned char)str[len - 1] == target_newline
13383               && (size_t) (int) len == len
13384               && (int) len > 0)
13385             {
13386               char *newstr;
13387               tree offset_node, string_cst;
13388
13389               /* Create a NUL-terminated string that's one char shorter
13390                  than the original, stripping off the trailing '\n'.  */
13391               newarg = build_string_literal (len, str);
13392               string_cst = string_constant (newarg, &offset_node);
13393               gcc_checking_assert (string_cst
13394                                    && (TREE_STRING_LENGTH (string_cst)
13395                                        == (int) len)
13396                                    && integer_zerop (offset_node)
13397                                    && (unsigned char)
13398                                       TREE_STRING_POINTER (string_cst)[len - 1]
13399                                       == target_newline);
13400               /* build_string_literal creates a new STRING_CST,
13401                  modify it in place to avoid double copying.  */
13402               newstr = CONST_CAST (char *, TREE_STRING_POINTER (string_cst));
13403               newstr[len - 1] = '\0';
13404               if (fn_puts)
13405                 call = build_call_expr_loc (loc, fn_puts, 1, newarg);
13406             }
13407           else
13408             /* We'd like to arrange to call fputs(string,stdout) here,
13409                but we need stdout and don't have a way to get it yet.  */
13410             return NULL_TREE;
13411         }
13412     }
13413
13414   /* The other optimizations can be done only on the non-va_list variants.  */
13415   else if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
13416     return NULL_TREE;
13417
13418   /* If the format specifier was "%s\n", call __builtin_puts(arg).  */
13419   else if (strcmp (fmt_str, target_percent_s_newline) == 0)
13420     {
13421       if (!arg || !validate_arg (arg, POINTER_TYPE))
13422         return NULL_TREE;
13423       if (fn_puts)
13424         call = build_call_expr_loc (loc, fn_puts, 1, arg);
13425     }
13426
13427   /* If the format specifier was "%c", call __builtin_putchar(arg).  */
13428   else if (strcmp (fmt_str, target_percent_c) == 0)
13429     {
13430       if (!arg || !validate_arg (arg, INTEGER_TYPE))
13431         return NULL_TREE;
13432       if (fn_putchar)
13433         call = build_call_expr_loc (loc, fn_putchar, 1, arg);
13434     }
13435
13436   if (!call)
13437     return NULL_TREE;
13438
13439   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), call);
13440 }
13441
13442 /* Fold a call to the {,v}fprintf{,_unlocked} and __{,v}printf_chk builtins.
13443    FP, FMT, and ARG are the arguments to the call.  We don't fold calls with
13444    more than 3 arguments, and ARG may be null in the 2-argument case.
13445
13446    Return NULL_TREE if no simplification was possible, otherwise return the
13447    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
13448    code of the function to be simplified.  */
13449
13450 static tree
13451 fold_builtin_fprintf (location_t loc, tree fndecl, tree fp,
13452                       tree fmt, tree arg, bool ignore,
13453                       enum built_in_function fcode)
13454 {
13455   tree fn_fputc, fn_fputs, call = NULL_TREE;
13456   const char *fmt_str = NULL;
13457
13458   /* If the return value is used, don't do the transformation.  */
13459   if (! ignore)
13460     return NULL_TREE;
13461
13462   /* Verify the required arguments in the original call.  */
13463   if (!validate_arg (fp, POINTER_TYPE))
13464     return NULL_TREE;
13465   if (!validate_arg (fmt, POINTER_TYPE))
13466     return NULL_TREE;
13467
13468   /* Check whether the format is a literal string constant.  */
13469   fmt_str = c_getstr (fmt);
13470   if (fmt_str == NULL)
13471     return NULL_TREE;
13472
13473   if (fcode == BUILT_IN_FPRINTF_UNLOCKED)
13474     {
13475       /* If we're using an unlocked function, assume the other
13476          unlocked functions exist explicitly.  */
13477       fn_fputc = builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED);
13478       fn_fputs = builtin_decl_explicit (BUILT_IN_FPUTS_UNLOCKED);
13479     }
13480   else
13481     {
13482       fn_fputc = builtin_decl_implicit (BUILT_IN_FPUTC);
13483       fn_fputs = builtin_decl_implicit (BUILT_IN_FPUTS);
13484     }
13485
13486   if (!init_target_chars ())
13487     return NULL_TREE;
13488
13489   /* If the format doesn't contain % args or %%, use strcpy.  */
13490   if (strchr (fmt_str, target_percent) == NULL)
13491     {
13492       if (fcode != BUILT_IN_VFPRINTF && fcode != BUILT_IN_VFPRINTF_CHK
13493           && arg)
13494         return NULL_TREE;
13495
13496       /* If the format specifier was "", fprintf does nothing.  */
13497       if (fmt_str[0] == '\0')
13498         {
13499           /* If FP has side-effects, just wait until gimplification is
13500              done.  */
13501           if (TREE_SIDE_EFFECTS (fp))
13502             return NULL_TREE;
13503
13504           return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
13505         }
13506
13507       /* When "string" doesn't contain %, replace all cases of
13508          fprintf (fp, string) with fputs (string, fp).  The fputs
13509          builtin will take care of special cases like length == 1.  */
13510       if (fn_fputs)
13511         call = build_call_expr_loc (loc, fn_fputs, 2, fmt, fp);
13512     }
13513
13514   /* The other optimizations can be done only on the non-va_list variants.  */
13515   else if (fcode == BUILT_IN_VFPRINTF || fcode == BUILT_IN_VFPRINTF_CHK)
13516     return NULL_TREE;
13517
13518   /* If the format specifier was "%s", call __builtin_fputs (arg, fp).  */
13519   else if (strcmp (fmt_str, target_percent_s) == 0)
13520     {
13521       if (!arg || !validate_arg (arg, POINTER_TYPE))
13522         return NULL_TREE;
13523       if (fn_fputs)
13524         call = build_call_expr_loc (loc, fn_fputs, 2, arg, fp);
13525     }
13526
13527   /* If the format specifier was "%c", call __builtin_fputc (arg, fp).  */
13528   else if (strcmp (fmt_str, target_percent_c) == 0)
13529     {
13530       if (!arg || !validate_arg (arg, INTEGER_TYPE))
13531         return NULL_TREE;
13532       if (fn_fputc)
13533         call = build_call_expr_loc (loc, fn_fputc, 2, arg, fp);
13534     }
13535
13536   if (!call)
13537     return NULL_TREE;
13538   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), call);
13539 }
13540
13541 /* Initialize format string characters in the target charset.  */
13542
13543 static bool
13544 init_target_chars (void)
13545 {
13546   static bool init;
13547   if (!init)
13548     {
13549       target_newline = lang_hooks.to_target_charset ('\n');
13550       target_percent = lang_hooks.to_target_charset ('%');
13551       target_c = lang_hooks.to_target_charset ('c');
13552       target_s = lang_hooks.to_target_charset ('s');
13553       if (target_newline == 0 || target_percent == 0 || target_c == 0
13554           || target_s == 0)
13555         return false;
13556
13557       target_percent_c[0] = target_percent;
13558       target_percent_c[1] = target_c;
13559       target_percent_c[2] = '\0';
13560
13561       target_percent_s[0] = target_percent;
13562       target_percent_s[1] = target_s;
13563       target_percent_s[2] = '\0';
13564
13565       target_percent_s_newline[0] = target_percent;
13566       target_percent_s_newline[1] = target_s;
13567       target_percent_s_newline[2] = target_newline;
13568       target_percent_s_newline[3] = '\0';
13569
13570       init = true;
13571     }
13572   return true;
13573 }
13574
13575 /* Helper function for do_mpfr_arg*().  Ensure M is a normal number
13576    and no overflow/underflow occurred.  INEXACT is true if M was not
13577    exactly calculated.  TYPE is the tree type for the result.  This
13578    function assumes that you cleared the MPFR flags and then
13579    calculated M to see if anything subsequently set a flag prior to
13580    entering this function.  Return NULL_TREE if any checks fail.  */
13581
13582 static tree
13583 do_mpfr_ckconv (mpfr_srcptr m, tree type, int inexact)
13584 {
13585   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
13586      overflow/underflow occurred.  If -frounding-math, proceed iff the
13587      result of calling FUNC was exact.  */
13588   if (mpfr_number_p (m) && !mpfr_overflow_p () && !mpfr_underflow_p ()
13589       && (!flag_rounding_math || !inexact))
13590     {
13591       REAL_VALUE_TYPE rr;
13592
13593       real_from_mpfr (&rr, m, type, GMP_RNDN);
13594       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR value,
13595          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
13596          but the mpft_t is not, then we underflowed in the
13597          conversion.  */
13598       if (real_isfinite (&rr)
13599           && (rr.cl == rvc_zero) == (mpfr_zero_p (m) != 0))
13600         {
13601           REAL_VALUE_TYPE rmode;
13602
13603           real_convert (&rmode, TYPE_MODE (type), &rr);
13604           /* Proceed iff the specified mode can hold the value.  */
13605           if (real_identical (&rmode, &rr))
13606             return build_real (type, rmode);
13607         }
13608     }
13609   return NULL_TREE;
13610 }
13611
13612 /* Helper function for do_mpc_arg*().  Ensure M is a normal complex
13613    number and no overflow/underflow occurred.  INEXACT is true if M
13614    was not exactly calculated.  TYPE is the tree type for the result.
13615    This function assumes that you cleared the MPFR flags and then
13616    calculated M to see if anything subsequently set a flag prior to
13617    entering this function.  Return NULL_TREE if any checks fail, if
13618    FORCE_CONVERT is true, then bypass the checks.  */
13619
13620 static tree
13621 do_mpc_ckconv (mpc_srcptr m, tree type, int inexact, int force_convert)
13622 {
13623   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
13624      overflow/underflow occurred.  If -frounding-math, proceed iff the
13625      result of calling FUNC was exact.  */
13626   if (force_convert
13627       || (mpfr_number_p (mpc_realref (m)) && mpfr_number_p (mpc_imagref (m))
13628           && !mpfr_overflow_p () && !mpfr_underflow_p ()
13629           && (!flag_rounding_math || !inexact)))
13630     {
13631       REAL_VALUE_TYPE re, im;
13632
13633       real_from_mpfr (&re, mpc_realref (m), TREE_TYPE (type), GMP_RNDN);
13634       real_from_mpfr (&im, mpc_imagref (m), TREE_TYPE (type), GMP_RNDN);
13635       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR values,
13636          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
13637          but the mpft_t is not, then we underflowed in the
13638          conversion.  */
13639       if (force_convert
13640           || (real_isfinite (&re) && real_isfinite (&im)
13641               && (re.cl == rvc_zero) == (mpfr_zero_p (mpc_realref (m)) != 0)
13642               && (im.cl == rvc_zero) == (mpfr_zero_p (mpc_imagref (m)) != 0)))
13643         {
13644           REAL_VALUE_TYPE re_mode, im_mode;
13645
13646           real_convert (&re_mode, TYPE_MODE (TREE_TYPE (type)), &re);
13647           real_convert (&im_mode, TYPE_MODE (TREE_TYPE (type)), &im);
13648           /* Proceed iff the specified mode can hold the value.  */
13649           if (force_convert
13650               || (real_identical (&re_mode, &re)
13651                   && real_identical (&im_mode, &im)))
13652             return build_complex (type, build_real (TREE_TYPE (type), re_mode),
13653                                   build_real (TREE_TYPE (type), im_mode));
13654         }
13655     }
13656   return NULL_TREE;
13657 }
13658
13659 /* If argument ARG is a REAL_CST, call the one-argument mpfr function
13660    FUNC on it and return the resulting value as a tree with type TYPE.
13661    If MIN and/or MAX are not NULL, then the supplied ARG must be
13662    within those bounds.  If INCLUSIVE is true, then MIN/MAX are
13663    acceptable values, otherwise they are not.  The mpfr precision is
13664    set to the precision of TYPE.  We assume that function FUNC returns
13665    zero if the result could be calculated exactly within the requested
13666    precision.  */
13667
13668 static tree
13669 do_mpfr_arg1 (tree arg, tree type, int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t),
13670               const REAL_VALUE_TYPE *min, const REAL_VALUE_TYPE *max,
13671               bool inclusive)
13672 {
13673   tree result = NULL_TREE;
13674
13675   STRIP_NOPS (arg);
13676
13677   /* To proceed, MPFR must exactly represent the target floating point
13678      format, which only happens when the target base equals two.  */
13679   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13680       && TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
13681     {
13682       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg);
13683
13684       if (real_isfinite (ra)
13685           && (!min || real_compare (inclusive ? GE_EXPR: GT_EXPR , ra, min))
13686           && (!max || real_compare (inclusive ? LE_EXPR: LT_EXPR , ra, max)))
13687         {
13688           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13689           const int prec = fmt->p;
13690           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13691           int inexact;
13692           mpfr_t m;
13693
13694           mpfr_init2 (m, prec);
13695           mpfr_from_real (m, ra, GMP_RNDN);
13696           mpfr_clear_flags ();
13697           inexact = func (m, m, rnd);
13698           result = do_mpfr_ckconv (m, type, inexact);
13699           mpfr_clear (m);
13700         }
13701     }
13702
13703   return result;
13704 }
13705
13706 /* If argument ARG is a REAL_CST, call the two-argument mpfr function
13707    FUNC on it and return the resulting value as a tree with type TYPE.
13708    The mpfr precision is set to the precision of TYPE.  We assume that
13709    function FUNC returns zero if the result could be calculated
13710    exactly within the requested precision.  */
13711
13712 static tree
13713 do_mpfr_arg2 (tree arg1, tree arg2, tree type,
13714               int (*func)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t))
13715 {
13716   tree result = NULL_TREE;
13717
13718   STRIP_NOPS (arg1);
13719   STRIP_NOPS (arg2);
13720
13721   /* To proceed, MPFR must exactly represent the target floating point
13722      format, which only happens when the target base equals two.  */
13723   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13724       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1)
13725       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2))
13726     {
13727       const REAL_VALUE_TYPE *const ra1 = &TREE_REAL_CST (arg1);
13728       const REAL_VALUE_TYPE *const ra2 = &TREE_REAL_CST (arg2);
13729
13730       if (real_isfinite (ra1) && real_isfinite (ra2))
13731         {
13732           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13733           const int prec = fmt->p;
13734           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13735           int inexact;
13736           mpfr_t m1, m2;
13737
13738           mpfr_inits2 (prec, m1, m2, NULL);
13739           mpfr_from_real (m1, ra1, GMP_RNDN);
13740           mpfr_from_real (m2, ra2, GMP_RNDN);
13741           mpfr_clear_flags ();
13742           inexact = func (m1, m1, m2, rnd);
13743           result = do_mpfr_ckconv (m1, type, inexact);
13744           mpfr_clears (m1, m2, NULL);
13745         }
13746     }
13747
13748   return result;
13749 }
13750
13751 /* If argument ARG is a REAL_CST, call the three-argument mpfr function
13752    FUNC on it and return the resulting value as a tree with type TYPE.
13753    The mpfr precision is set to the precision of TYPE.  We assume that
13754    function FUNC returns zero if the result could be calculated
13755    exactly within the requested precision.  */
13756
13757 static tree
13758 do_mpfr_arg3 (tree arg1, tree arg2, tree arg3, tree type,
13759               int (*func)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t))
13760 {
13761   tree result = NULL_TREE;
13762
13763   STRIP_NOPS (arg1);
13764   STRIP_NOPS (arg2);
13765   STRIP_NOPS (arg3);
13766
13767   /* To proceed, MPFR must exactly represent the target floating point
13768      format, which only happens when the target base equals two.  */
13769   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13770       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1)
13771       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2)
13772       && TREE_CODE (arg3) == REAL_CST && !TREE_OVERFLOW (arg3))
13773     {
13774       const REAL_VALUE_TYPE *const ra1 = &TREE_REAL_CST (arg1);
13775       const REAL_VALUE_TYPE *const ra2 = &TREE_REAL_CST (arg2);
13776       const REAL_VALUE_TYPE *const ra3 = &TREE_REAL_CST (arg3);
13777
13778       if (real_isfinite (ra1) && real_isfinite (ra2) && real_isfinite (ra3))
13779         {
13780           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13781           const int prec = fmt->p;
13782           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13783           int inexact;
13784           mpfr_t m1, m2, m3;
13785
13786           mpfr_inits2 (prec, m1, m2, m3, NULL);
13787           mpfr_from_real (m1, ra1, GMP_RNDN);
13788           mpfr_from_real (m2, ra2, GMP_RNDN);
13789           mpfr_from_real (m3, ra3, GMP_RNDN);
13790           mpfr_clear_flags ();
13791           inexact = func (m1, m1, m2, m3, rnd);
13792           result = do_mpfr_ckconv (m1, type, inexact);
13793           mpfr_clears (m1, m2, m3, NULL);
13794         }
13795     }
13796
13797   return result;
13798 }
13799
13800 /* If argument ARG is a REAL_CST, call mpfr_sin_cos() on it and set
13801    the pointers *(ARG_SINP) and *(ARG_COSP) to the resulting values.
13802    If ARG_SINP and ARG_COSP are NULL then the result is returned
13803    as a complex value.
13804    The type is taken from the type of ARG and is used for setting the
13805    precision of the calculation and results.  */
13806
13807 static tree
13808 do_mpfr_sincos (tree arg, tree arg_sinp, tree arg_cosp)
13809 {
13810   tree const type = TREE_TYPE (arg);
13811   tree result = NULL_TREE;
13812
13813   STRIP_NOPS (arg);
13814
13815   /* To proceed, MPFR must exactly represent the target floating point
13816      format, which only happens when the target base equals two.  */
13817   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13818       && TREE_CODE (arg) == REAL_CST
13819       && !TREE_OVERFLOW (arg))
13820     {
13821       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg);
13822
13823       if (real_isfinite (ra))
13824         {
13825           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13826           const int prec = fmt->p;
13827           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13828           tree result_s, result_c;
13829           int inexact;
13830           mpfr_t m, ms, mc;
13831
13832           mpfr_inits2 (prec, m, ms, mc, NULL);
13833           mpfr_from_real (m, ra, GMP_RNDN);
13834           mpfr_clear_flags ();
13835           inexact = mpfr_sin_cos (ms, mc, m, rnd);
13836           result_s = do_mpfr_ckconv (ms, type, inexact);
13837           result_c = do_mpfr_ckconv (mc, type, inexact);
13838           mpfr_clears (m, ms, mc, NULL);
13839           if (result_s && result_c)
13840             {
13841               /* If we are to return in a complex value do so.  */
13842               if (!arg_sinp && !arg_cosp)
13843                 return build_complex (build_complex_type (type),
13844                                       result_c, result_s);
13845
13846               /* Dereference the sin/cos pointer arguments.  */
13847               arg_sinp = build_fold_indirect_ref (arg_sinp);
13848               arg_cosp = build_fold_indirect_ref (arg_cosp);
13849               /* Proceed if valid pointer type were passed in.  */
13850               if (TYPE_MAIN_VARIANT (TREE_TYPE (arg_sinp)) == TYPE_MAIN_VARIANT (type)
13851                   && TYPE_MAIN_VARIANT (TREE_TYPE (arg_cosp)) == TYPE_MAIN_VARIANT (type))
13852                 {
13853                   /* Set the values. */
13854                   result_s = fold_build2 (MODIFY_EXPR, type, arg_sinp,
13855                                           result_s);
13856                   TREE_SIDE_EFFECTS (result_s) = 1;
13857                   result_c = fold_build2 (MODIFY_EXPR, type, arg_cosp,
13858                                           result_c);
13859                   TREE_SIDE_EFFECTS (result_c) = 1;
13860                   /* Combine the assignments into a compound expr.  */
13861                   result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13862                                                     result_s, result_c));
13863                 }
13864             }
13865         }
13866     }
13867   return result;
13868 }
13869
13870 /* If argument ARG1 is an INTEGER_CST and ARG2 is a REAL_CST, call the
13871    two-argument mpfr order N Bessel function FUNC on them and return
13872    the resulting value as a tree with type TYPE.  The mpfr precision
13873    is set to the precision of TYPE.  We assume that function FUNC
13874    returns zero if the result could be calculated exactly within the
13875    requested precision.  */
13876 static tree
13877 do_mpfr_bessel_n (tree arg1, tree arg2, tree type,
13878                   int (*func)(mpfr_ptr, long, mpfr_srcptr, mp_rnd_t),
13879                   const REAL_VALUE_TYPE *min, bool inclusive)
13880 {
13881   tree result = NULL_TREE;
13882
13883   STRIP_NOPS (arg1);
13884   STRIP_NOPS (arg2);
13885
13886   /* To proceed, MPFR must exactly represent the target floating point
13887      format, which only happens when the target base equals two.  */
13888   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13889       && host_integerp (arg1, 0)
13890       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2))
13891     {
13892       const HOST_WIDE_INT n = tree_low_cst(arg1, 0);
13893       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg2);
13894
13895       if (n == (long)n
13896           && real_isfinite (ra)
13897           && (!min || real_compare (inclusive ? GE_EXPR: GT_EXPR , ra, min)))
13898         {
13899           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13900           const int prec = fmt->p;
13901           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13902           int inexact;
13903           mpfr_t m;
13904
13905           mpfr_init2 (m, prec);
13906           mpfr_from_real (m, ra, GMP_RNDN);
13907           mpfr_clear_flags ();
13908           inexact = func (m, n, m, rnd);
13909           result = do_mpfr_ckconv (m, type, inexact);
13910           mpfr_clear (m);
13911         }
13912     }
13913
13914   return result;
13915 }
13916
13917 /* If arguments ARG0 and ARG1 are REAL_CSTs, call mpfr_remquo() to set
13918    the pointer *(ARG_QUO) and return the result.  The type is taken
13919    from the type of ARG0 and is used for setting the precision of the
13920    calculation and results.  */
13921
13922 static tree
13923 do_mpfr_remquo (tree arg0, tree arg1, tree arg_quo)
13924 {
13925   tree const type = TREE_TYPE (arg0);
13926   tree result = NULL_TREE;
13927
13928   STRIP_NOPS (arg0);
13929   STRIP_NOPS (arg1);
13930
13931   /* To proceed, MPFR must exactly represent the target floating point
13932      format, which only happens when the target base equals two.  */
13933   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13934       && TREE_CODE (arg0) == REAL_CST && !TREE_OVERFLOW (arg0)
13935       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1))
13936     {
13937       const REAL_VALUE_TYPE *const ra0 = TREE_REAL_CST_PTR (arg0);
13938       const REAL_VALUE_TYPE *const ra1 = TREE_REAL_CST_PTR (arg1);
13939
13940       if (real_isfinite (ra0) && real_isfinite (ra1))
13941         {
13942           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13943           const int prec = fmt->p;
13944           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13945           tree result_rem;
13946           long integer_quo;
13947           mpfr_t m0, m1;
13948
13949           mpfr_inits2 (prec, m0, m1, NULL);
13950           mpfr_from_real (m0, ra0, GMP_RNDN);
13951           mpfr_from_real (m1, ra1, GMP_RNDN);
13952           mpfr_clear_flags ();
13953           mpfr_remquo (m0, &integer_quo, m0, m1, rnd);
13954           /* Remquo is independent of the rounding mode, so pass
13955              inexact=0 to do_mpfr_ckconv().  */
13956           result_rem = do_mpfr_ckconv (m0, type, /*inexact=*/ 0);
13957           mpfr_clears (m0, m1, NULL);
13958           if (result_rem)
13959             {
13960               /* MPFR calculates quo in the host's long so it may
13961                  return more bits in quo than the target int can hold
13962                  if sizeof(host long) > sizeof(target int).  This can
13963                  happen even for native compilers in LP64 mode.  In
13964                  these cases, modulo the quo value with the largest
13965                  number that the target int can hold while leaving one
13966                  bit for the sign.  */
13967               if (sizeof (integer_quo) * CHAR_BIT > INT_TYPE_SIZE)
13968                 integer_quo %= (long)(1UL << (INT_TYPE_SIZE - 1));
13969
13970               /* Dereference the quo pointer argument.  */
13971               arg_quo = build_fold_indirect_ref (arg_quo);
13972               /* Proceed iff a valid pointer type was passed in.  */
13973               if (TYPE_MAIN_VARIANT (TREE_TYPE (arg_quo)) == integer_type_node)
13974                 {
13975                   /* Set the value. */
13976                   tree result_quo
13977                     = fold_build2 (MODIFY_EXPR, TREE_TYPE (arg_quo), arg_quo,
13978                                    build_int_cst (TREE_TYPE (arg_quo),
13979                                                   integer_quo));
13980                   TREE_SIDE_EFFECTS (result_quo) = 1;
13981                   /* Combine the quo assignment with the rem.  */
13982                   result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13983                                                     result_quo, result_rem));
13984                 }
13985             }
13986         }
13987     }
13988   return result;
13989 }
13990
13991 /* If ARG is a REAL_CST, call mpfr_lgamma() on it and return the
13992    resulting value as a tree with type TYPE.  The mpfr precision is
13993    set to the precision of TYPE.  We assume that this mpfr function
13994    returns zero if the result could be calculated exactly within the
13995    requested precision.  In addition, the integer pointer represented
13996    by ARG_SG will be dereferenced and set to the appropriate signgam
13997    (-1,1) value.  */
13998
13999 static tree
14000 do_mpfr_lgamma_r (tree arg, tree arg_sg, tree type)
14001 {
14002   tree result = NULL_TREE;
14003
14004   STRIP_NOPS (arg);
14005
14006   /* To proceed, MPFR must exactly represent the target floating point
14007      format, which only happens when the target base equals two.  Also
14008      verify ARG is a constant and that ARG_SG is an int pointer.  */
14009   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
14010       && TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg)
14011       && TREE_CODE (TREE_TYPE (arg_sg)) == POINTER_TYPE
14012       && TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (arg_sg))) == integer_type_node)
14013     {
14014       const REAL_VALUE_TYPE *const ra = TREE_REAL_CST_PTR (arg);
14015
14016       /* In addition to NaN and Inf, the argument cannot be zero or a
14017          negative integer.  */
14018       if (real_isfinite (ra)
14019           && ra->cl != rvc_zero
14020           && !(real_isneg(ra) && real_isinteger(ra, TYPE_MODE (type))))
14021         {
14022           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
14023           const int prec = fmt->p;
14024           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
14025           int inexact, sg;
14026           mpfr_t m;
14027           tree result_lg;
14028
14029           mpfr_init2 (m, prec);
14030           mpfr_from_real (m, ra, GMP_RNDN);
14031           mpfr_clear_flags ();
14032           inexact = mpfr_lgamma (m, &sg, m, rnd);
14033           result_lg = do_mpfr_ckconv (m, type, inexact);
14034           mpfr_clear (m);
14035           if (result_lg)
14036             {
14037               tree result_sg;
14038
14039               /* Dereference the arg_sg pointer argument.  */
14040               arg_sg = build_fold_indirect_ref (arg_sg);
14041               /* Assign the signgam value into *arg_sg. */
14042               result_sg = fold_build2 (MODIFY_EXPR,
14043                                        TREE_TYPE (arg_sg), arg_sg,
14044                                        build_int_cst (TREE_TYPE (arg_sg), sg));
14045               TREE_SIDE_EFFECTS (result_sg) = 1;
14046               /* Combine the signgam assignment with the lgamma result.  */
14047               result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
14048                                                 result_sg, result_lg));
14049             }
14050         }
14051     }
14052
14053   return result;
14054 }
14055
14056 /* If argument ARG is a COMPLEX_CST, call the one-argument mpc
14057    function FUNC on it and return the resulting value as a tree with
14058    type TYPE.  The mpfr precision is set to the precision of TYPE.  We
14059    assume that function FUNC returns zero if the result could be
14060    calculated exactly within the requested precision.  */
14061
14062 static tree
14063 do_mpc_arg1 (tree arg, tree type, int (*func)(mpc_ptr, mpc_srcptr, mpc_rnd_t))
14064 {
14065   tree result = NULL_TREE;
14066
14067   STRIP_NOPS (arg);
14068
14069   /* To proceed, MPFR must exactly represent the target floating point
14070      format, which only happens when the target base equals two.  */
14071   if (TREE_CODE (arg) == COMPLEX_CST && !TREE_OVERFLOW (arg)
14072       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE
14073       && REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (TREE_TYPE (arg))))->b == 2)
14074     {
14075       const REAL_VALUE_TYPE *const re = TREE_REAL_CST_PTR (TREE_REALPART (arg));
14076       const REAL_VALUE_TYPE *const im = TREE_REAL_CST_PTR (TREE_IMAGPART (arg));
14077
14078       if (real_isfinite (re) && real_isfinite (im))
14079         {
14080           const struct real_format *const fmt =
14081             REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (type)));
14082           const int prec = fmt->p;
14083           const mp_rnd_t rnd = fmt->round_towards_zero ? GMP_RNDZ : GMP_RNDN;
14084           const mpc_rnd_t crnd = fmt->round_towards_zero ? MPC_RNDZZ : MPC_RNDNN;
14085           int inexact;
14086           mpc_t m;
14087
14088           mpc_init2 (m, prec);
14089           mpfr_from_real (mpc_realref(m), re, rnd);
14090           mpfr_from_real (mpc_imagref(m), im, rnd);
14091           mpfr_clear_flags ();
14092           inexact = func (m, m, crnd);
14093           result = do_mpc_ckconv (m, type, inexact, /*force_convert=*/ 0);
14094           mpc_clear (m);
14095         }
14096     }
14097
14098   return result;
14099 }
14100
14101 /* If arguments ARG0 and ARG1 are a COMPLEX_CST, call the two-argument
14102    mpc function FUNC on it and return the resulting value as a tree
14103    with type TYPE.  The mpfr precision is set to the precision of
14104    TYPE.  We assume that function FUNC returns zero if the result
14105    could be calculated exactly within the requested precision.  If
14106    DO_NONFINITE is true, then fold expressions containing Inf or NaN
14107    in the arguments and/or results.  */
14108
14109 tree
14110 do_mpc_arg2 (tree arg0, tree arg1, tree type, int do_nonfinite,
14111              int (*func)(mpc_ptr, mpc_srcptr, mpc_srcptr, mpc_rnd_t))
14112 {
14113   tree result = NULL_TREE;
14114
14115   STRIP_NOPS (arg0);
14116   STRIP_NOPS (arg1);
14117
14118   /* To proceed, MPFR must exactly represent the target floating point
14119      format, which only happens when the target base equals two.  */
14120   if (TREE_CODE (arg0) == COMPLEX_CST && !TREE_OVERFLOW (arg0)
14121       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE
14122       && TREE_CODE (arg1) == COMPLEX_CST && !TREE_OVERFLOW (arg1)
14123       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg1))) == REAL_TYPE
14124       && REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (TREE_TYPE (arg0))))->b == 2)
14125     {
14126       const REAL_VALUE_TYPE *const re0 = TREE_REAL_CST_PTR (TREE_REALPART (arg0));
14127       const REAL_VALUE_TYPE *const im0 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg0));
14128       const REAL_VALUE_TYPE *const re1 = TREE_REAL_CST_PTR (TREE_REALPART (arg1));
14129       const REAL_VALUE_TYPE *const im1 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg1));
14130
14131       if (do_nonfinite
14132           || (real_isfinite (re0) && real_isfinite (im0)
14133               && real_isfinite (re1) && real_isfinite (im1)))
14134         {
14135           const struct real_format *const fmt =
14136             REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (type)));
14137           const int prec = fmt->p;
14138           const mp_rnd_t rnd = fmt->round_towards_zero ? GMP_RNDZ : GMP_RNDN;
14139           const mpc_rnd_t crnd = fmt->round_towards_zero ? MPC_RNDZZ : MPC_RNDNN;
14140           int inexact;
14141           mpc_t m0, m1;
14142
14143           mpc_init2 (m0, prec);
14144           mpc_init2 (m1, prec);
14145           mpfr_from_real (mpc_realref(m0), re0, rnd);
14146           mpfr_from_real (mpc_imagref(m0), im0, rnd);
14147           mpfr_from_real (mpc_realref(m1), re1, rnd);
14148           mpfr_from_real (mpc_imagref(m1), im1, rnd);
14149           mpfr_clear_flags ();
14150           inexact = func (m0, m0, m1, crnd);
14151           result = do_mpc_ckconv (m0, type, inexact, do_nonfinite);
14152           mpc_clear (m0);
14153           mpc_clear (m1);
14154         }
14155     }
14156
14157   return result;
14158 }
14159
14160 /* Fold a call STMT to __{,v}sprintf_chk.  Return NULL_TREE if
14161    a normal call should be emitted rather than expanding the function
14162    inline.  FCODE is either BUILT_IN_SPRINTF_CHK or BUILT_IN_VSPRINTF_CHK.  */
14163
14164 static tree
14165 gimple_fold_builtin_sprintf_chk (gimple stmt, enum built_in_function fcode)
14166 {
14167   int nargs = gimple_call_num_args (stmt);
14168
14169   return fold_builtin_sprintf_chk_1 (gimple_location (stmt), nargs,
14170                                      (nargs > 0
14171                                       ? gimple_call_arg_ptr (stmt, 0)
14172                                       : &error_mark_node), fcode);
14173 }
14174
14175 /* Fold a call STMT to {,v}snprintf.  Return NULL_TREE if
14176    a normal call should be emitted rather than expanding the function
14177    inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
14178    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
14179    passed as second argument.  */
14180
14181 tree
14182 gimple_fold_builtin_snprintf_chk (gimple stmt, tree maxlen,
14183                                   enum built_in_function fcode)
14184 {
14185   int nargs = gimple_call_num_args (stmt);
14186
14187   return fold_builtin_snprintf_chk_1 (gimple_location (stmt), nargs,
14188                                       (nargs > 0
14189                                        ? gimple_call_arg_ptr (stmt, 0)
14190                                        : &error_mark_node), maxlen, fcode);
14191 }
14192
14193 /* Builtins with folding operations that operate on "..." arguments
14194    need special handling; we need to store the arguments in a convenient
14195    data structure before attempting any folding.  Fortunately there are
14196    only a few builtins that fall into this category.  FNDECL is the
14197    function, EXP is the CALL_EXPR for the call, and IGNORE is true if the
14198    result of the function call is ignored.  */
14199
14200 static tree
14201 gimple_fold_builtin_varargs (tree fndecl, gimple stmt,
14202                              bool ignore ATTRIBUTE_UNUSED)
14203 {
14204   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
14205   tree ret = NULL_TREE;
14206
14207   switch (fcode)
14208     {
14209     case BUILT_IN_SPRINTF_CHK:
14210     case BUILT_IN_VSPRINTF_CHK:
14211       ret = gimple_fold_builtin_sprintf_chk (stmt, fcode);
14212       break;
14213
14214     case BUILT_IN_SNPRINTF_CHK:
14215     case BUILT_IN_VSNPRINTF_CHK:
14216       ret = gimple_fold_builtin_snprintf_chk (stmt, NULL_TREE, fcode);
14217
14218     default:
14219       break;
14220     }
14221   if (ret)
14222     {
14223       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
14224       TREE_NO_WARNING (ret) = 1;
14225       return ret;
14226     }
14227   return NULL_TREE;
14228 }
14229
14230 /* A wrapper function for builtin folding that prevents warnings for
14231    "statement without effect" and the like, caused by removing the
14232    call node earlier than the warning is generated.  */
14233
14234 tree
14235 fold_call_stmt (gimple stmt, bool ignore)
14236 {
14237   tree ret = NULL_TREE;
14238   tree fndecl = gimple_call_fndecl (stmt);
14239   location_t loc = gimple_location (stmt);
14240   if (fndecl
14241       && TREE_CODE (fndecl) == FUNCTION_DECL
14242       && DECL_BUILT_IN (fndecl)
14243       && !gimple_call_va_arg_pack_p (stmt))
14244     {
14245       int nargs = gimple_call_num_args (stmt);
14246       tree *args = (nargs > 0
14247                     ? gimple_call_arg_ptr (stmt, 0)
14248                     : &error_mark_node);
14249
14250       if (avoid_folding_inline_builtin (fndecl))
14251         return NULL_TREE;
14252       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
14253         {
14254           return targetm.fold_builtin (fndecl, nargs, args, ignore);
14255         }
14256       else
14257         {
14258           if (nargs <= MAX_ARGS_TO_FOLD_BUILTIN)
14259             ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
14260           if (!ret)
14261             ret = gimple_fold_builtin_varargs (fndecl, stmt, ignore);
14262           if (ret)
14263             {
14264               /* Propagate location information from original call to
14265                  expansion of builtin.  Otherwise things like
14266                  maybe_emit_chk_warning, that operate on the expansion
14267                  of a builtin, will use the wrong location information.  */
14268               if (gimple_has_location (stmt))
14269                 {
14270                   tree realret = ret;
14271                   if (TREE_CODE (ret) == NOP_EXPR)
14272                     realret = TREE_OPERAND (ret, 0);
14273                   if (CAN_HAVE_LOCATION_P (realret)
14274                       && !EXPR_HAS_LOCATION (realret))
14275                     SET_EXPR_LOCATION (realret, loc);
14276                   return realret;
14277                 }
14278               return ret;
14279             }
14280         }
14281     }
14282   return NULL_TREE;
14283 }
14284
14285 /* Look up the function in builtin_decl that corresponds to DECL
14286    and set ASMSPEC as its user assembler name.  DECL must be a
14287    function decl that declares a builtin.  */
14288
14289 void
14290 set_builtin_user_assembler_name (tree decl, const char *asmspec)
14291 {
14292   tree builtin;
14293   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
14294               && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
14295               && asmspec != 0);
14296
14297   builtin = builtin_decl_explicit (DECL_FUNCTION_CODE (decl));
14298   set_user_assembler_name (builtin, asmspec);
14299   switch (DECL_FUNCTION_CODE (decl))
14300     {
14301     case BUILT_IN_MEMCPY:
14302       init_block_move_fn (asmspec);
14303       memcpy_libfunc = set_user_assembler_libfunc ("memcpy", asmspec);
14304       break;
14305     case BUILT_IN_MEMSET:
14306       init_block_clear_fn (asmspec);
14307       memset_libfunc = set_user_assembler_libfunc ("memset", asmspec);
14308       break;
14309     case BUILT_IN_MEMMOVE:
14310       memmove_libfunc = set_user_assembler_libfunc ("memmove", asmspec);
14311       break;
14312     case BUILT_IN_MEMCMP:
14313       memcmp_libfunc = set_user_assembler_libfunc ("memcmp", asmspec);
14314       break;
14315     case BUILT_IN_ABORT:
14316       abort_libfunc = set_user_assembler_libfunc ("abort", asmspec);
14317       break;
14318     case BUILT_IN_FFS:
14319       if (INT_TYPE_SIZE < BITS_PER_WORD)
14320         {
14321           set_user_assembler_libfunc ("ffs", asmspec);
14322           set_optab_libfunc (ffs_optab, mode_for_size (INT_TYPE_SIZE,
14323                                                        MODE_INT, 0), "ffs");
14324         }
14325       break;
14326     default:
14327       break;
14328     }
14329 }
14330
14331 /* Return true if DECL is a builtin that expands to a constant or similarly
14332    simple code.  */
14333 bool
14334 is_simple_builtin (tree decl)
14335 {
14336   if (decl && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
14337     switch (DECL_FUNCTION_CODE (decl))
14338       {
14339         /* Builtins that expand to constants.  */
14340       case BUILT_IN_CONSTANT_P:
14341       case BUILT_IN_EXPECT:
14342       case BUILT_IN_OBJECT_SIZE:
14343       case BUILT_IN_UNREACHABLE:
14344         /* Simple register moves or loads from stack.  */
14345       case BUILT_IN_ASSUME_ALIGNED:
14346       case BUILT_IN_RETURN_ADDRESS:
14347       case BUILT_IN_EXTRACT_RETURN_ADDR:
14348       case BUILT_IN_FROB_RETURN_ADDR:
14349       case BUILT_IN_RETURN:
14350       case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
14351       case BUILT_IN_FRAME_ADDRESS:
14352       case BUILT_IN_VA_END:
14353       case BUILT_IN_STACK_SAVE:
14354       case BUILT_IN_STACK_RESTORE:
14355         /* Exception state returns or moves registers around.  */
14356       case BUILT_IN_EH_FILTER:
14357       case BUILT_IN_EH_POINTER:
14358       case BUILT_IN_EH_COPY_VALUES:
14359         return true;
14360
14361       default:
14362         return false;
14363       }
14364
14365   return false;
14366 }
14367
14368 /* Return true if DECL is a builtin that is not expensive, i.e., they are
14369    most probably expanded inline into reasonably simple code.  This is a
14370    superset of is_simple_builtin.  */
14371 bool
14372 is_inexpensive_builtin (tree decl)
14373 {
14374   if (!decl)
14375     return false;
14376   else if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_MD)
14377     return true;
14378   else if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
14379     switch (DECL_FUNCTION_CODE (decl))
14380       {
14381       case BUILT_IN_ABS:
14382       case BUILT_IN_ALLOCA:
14383       case BUILT_IN_ALLOCA_WITH_ALIGN:
14384       case BUILT_IN_BSWAP16:
14385       case BUILT_IN_BSWAP32:
14386       case BUILT_IN_BSWAP64:
14387       case BUILT_IN_CLZ:
14388       case BUILT_IN_CLZIMAX:
14389       case BUILT_IN_CLZL:
14390       case BUILT_IN_CLZLL:
14391       case BUILT_IN_CTZ:
14392       case BUILT_IN_CTZIMAX:
14393       case BUILT_IN_CTZL:
14394       case BUILT_IN_CTZLL:
14395       case BUILT_IN_FFS:
14396       case BUILT_IN_FFSIMAX:
14397       case BUILT_IN_FFSL:
14398       case BUILT_IN_FFSLL:
14399       case BUILT_IN_IMAXABS:
14400       case BUILT_IN_FINITE:
14401       case BUILT_IN_FINITEF:
14402       case BUILT_IN_FINITEL:
14403       case BUILT_IN_FINITED32:
14404       case BUILT_IN_FINITED64:
14405       case BUILT_IN_FINITED128:
14406       case BUILT_IN_FPCLASSIFY:
14407       case BUILT_IN_ISFINITE:
14408       case BUILT_IN_ISINF_SIGN:
14409       case BUILT_IN_ISINF:
14410       case BUILT_IN_ISINFF:
14411       case BUILT_IN_ISINFL:
14412       case BUILT_IN_ISINFD32:
14413       case BUILT_IN_ISINFD64:
14414       case BUILT_IN_ISINFD128:
14415       case BUILT_IN_ISNAN:
14416       case BUILT_IN_ISNANF:
14417       case BUILT_IN_ISNANL:
14418       case BUILT_IN_ISNAND32:
14419       case BUILT_IN_ISNAND64:
14420       case BUILT_IN_ISNAND128:
14421       case BUILT_IN_ISNORMAL:
14422       case BUILT_IN_ISGREATER:
14423       case BUILT_IN_ISGREATEREQUAL:
14424       case BUILT_IN_ISLESS:
14425       case BUILT_IN_ISLESSEQUAL:
14426       case BUILT_IN_ISLESSGREATER:
14427       case BUILT_IN_ISUNORDERED:
14428       case BUILT_IN_VA_ARG_PACK:
14429       case BUILT_IN_VA_ARG_PACK_LEN:
14430       case BUILT_IN_VA_COPY:
14431       case BUILT_IN_TRAP:
14432       case BUILT_IN_SAVEREGS:
14433       case BUILT_IN_POPCOUNTL:
14434       case BUILT_IN_POPCOUNTLL:
14435       case BUILT_IN_POPCOUNTIMAX:
14436       case BUILT_IN_POPCOUNT:
14437       case BUILT_IN_PARITYL:
14438       case BUILT_IN_PARITYLL:
14439       case BUILT_IN_PARITYIMAX:
14440       case BUILT_IN_PARITY:
14441       case BUILT_IN_LABS:
14442       case BUILT_IN_LLABS:
14443       case BUILT_IN_PREFETCH:
14444         return true;
14445
14446       default:
14447         return is_simple_builtin (decl);
14448       }
14449
14450   return false;
14451 }