OSDN Git Service

2004-11-13 Dale Johannesen <dalej@apple.com>
[pf3gnuchains/gcc-fork.git] / gcc / builtins.c
1 /* Expand builtin functions.
2    Copyright (C) 1988, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
3    2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING.  If not, write to the Free
19 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "machmode.h"
27 #include "real.h"
28 #include "rtl.h"
29 #include "tree.h"
30 #include "tree-gimple.h"
31 #include "flags.h"
32 #include "regs.h"
33 #include "hard-reg-set.h"
34 #include "except.h"
35 #include "function.h"
36 #include "insn-config.h"
37 #include "expr.h"
38 #include "optabs.h"
39 #include "libfuncs.h"
40 #include "recog.h"
41 #include "output.h"
42 #include "typeclass.h"
43 #include "toplev.h"
44 #include "predict.h"
45 #include "tm_p.h"
46 #include "target.h"
47 #include "langhooks.h"
48 #include "basic-block.h"
49 #include "tree-mudflap.h"
50
51 #define CALLED_AS_BUILT_IN(NODE) \
52    (!strncmp (IDENTIFIER_POINTER (DECL_NAME (NODE)), "__builtin_", 10))
53
54 #ifndef PAD_VARARGS_DOWN
55 #define PAD_VARARGS_DOWN BYTES_BIG_ENDIAN
56 #endif
57
58 /* Define the names of the builtin function types and codes.  */
59 const char *const built_in_class_names[4]
60   = {"NOT_BUILT_IN", "BUILT_IN_FRONTEND", "BUILT_IN_MD", "BUILT_IN_NORMAL"};
61
62 #define DEF_BUILTIN(X, N, C, T, LT, B, F, NA, AT, IM) #X,
63 const char *const built_in_names[(int) END_BUILTINS] =
64 {
65 #include "builtins.def"
66 };
67 #undef DEF_BUILTIN
68
69 /* Setup an array of _DECL trees, make sure each element is
70    initialized to NULL_TREE.  */
71 tree built_in_decls[(int) END_BUILTINS];
72 /* Declarations used when constructing the builtin implicitly in the compiler.
73    It may be NULL_TREE when this is invalid (for instance runtime is not
74    required to implement the function call in all cases).  */
75 tree implicit_built_in_decls[(int) END_BUILTINS];
76
77 static int get_pointer_alignment (tree, unsigned int);
78 static const char *c_getstr (tree);
79 static rtx c_readstr (const char *, enum machine_mode);
80 static int target_char_cast (tree, char *);
81 static rtx get_memory_rtx (tree);
82 static tree build_string_literal (int, const char *);
83 static int apply_args_size (void);
84 static int apply_result_size (void);
85 #if defined (HAVE_untyped_call) || defined (HAVE_untyped_return)
86 static rtx result_vector (int, rtx);
87 #endif
88 static rtx expand_builtin_setjmp (tree, rtx);
89 static void expand_builtin_update_setjmp_buf (rtx);
90 static void expand_builtin_prefetch (tree);
91 static rtx expand_builtin_apply_args (void);
92 static rtx expand_builtin_apply_args_1 (void);
93 static rtx expand_builtin_apply (rtx, rtx, rtx);
94 static void expand_builtin_return (rtx);
95 static enum type_class type_to_class (tree);
96 static rtx expand_builtin_classify_type (tree);
97 static void expand_errno_check (tree, rtx);
98 static rtx expand_builtin_mathfn (tree, rtx, rtx);
99 static rtx expand_builtin_mathfn_2 (tree, rtx, rtx);
100 static rtx expand_builtin_mathfn_3 (tree, rtx, rtx);
101 static rtx expand_builtin_args_info (tree);
102 static rtx expand_builtin_next_arg (tree);
103 static rtx expand_builtin_va_start (tree);
104 static rtx expand_builtin_va_end (tree);
105 static rtx expand_builtin_va_copy (tree);
106 static rtx expand_builtin_memcmp (tree, tree, rtx, enum machine_mode);
107 static rtx expand_builtin_strcmp (tree, rtx, enum machine_mode);
108 static rtx expand_builtin_strncmp (tree, rtx, enum machine_mode);
109 static rtx builtin_memcpy_read_str (void *, HOST_WIDE_INT, enum machine_mode);
110 static rtx expand_builtin_strcat (tree, tree, rtx, enum machine_mode);
111 static rtx expand_builtin_strncat (tree, rtx, enum machine_mode);
112 static rtx expand_builtin_strspn (tree, rtx, enum machine_mode);
113 static rtx expand_builtin_strcspn (tree, rtx, enum machine_mode);
114 static rtx expand_builtin_memcpy (tree, rtx, enum machine_mode);
115 static rtx expand_builtin_mempcpy (tree, tree, rtx, enum machine_mode, int);
116 static rtx expand_builtin_memmove (tree, tree, rtx, enum machine_mode);
117 static rtx expand_builtin_bcopy (tree, tree);
118 static rtx expand_builtin_strcpy (tree, rtx, enum machine_mode);
119 static rtx expand_builtin_stpcpy (tree, rtx, enum machine_mode);
120 static rtx builtin_strncpy_read_str (void *, HOST_WIDE_INT, enum machine_mode);
121 static rtx expand_builtin_strncpy (tree, rtx, enum machine_mode);
122 static rtx builtin_memset_read_str (void *, HOST_WIDE_INT, enum machine_mode);
123 static rtx builtin_memset_gen_str (void *, HOST_WIDE_INT, enum machine_mode);
124 static rtx expand_builtin_memset (tree, rtx, enum machine_mode);
125 static rtx expand_builtin_bzero (tree);
126 static rtx expand_builtin_strlen (tree, rtx, enum machine_mode);
127 static rtx expand_builtin_strstr (tree, rtx, enum machine_mode);
128 static rtx expand_builtin_strpbrk (tree, rtx, enum machine_mode);
129 static rtx expand_builtin_strchr (tree, rtx, enum machine_mode);
130 static rtx expand_builtin_strrchr (tree, rtx, enum machine_mode);
131 static rtx expand_builtin_alloca (tree, rtx);
132 static rtx expand_builtin_unop (enum machine_mode, tree, rtx, rtx, optab);
133 static rtx expand_builtin_frame_address (tree, tree);
134 static rtx expand_builtin_fputs (tree, rtx, bool);
135 static rtx expand_builtin_printf (tree, rtx, enum machine_mode, bool);
136 static rtx expand_builtin_fprintf (tree, rtx, enum machine_mode, bool);
137 static rtx expand_builtin_sprintf (tree, rtx, enum machine_mode);
138 static tree stabilize_va_list (tree, int);
139 static rtx expand_builtin_expect (tree, rtx);
140 static tree fold_builtin_constant_p (tree);
141 static tree fold_builtin_classify_type (tree);
142 static tree fold_builtin_strlen (tree);
143 static tree fold_builtin_inf (tree, int);
144 static tree fold_builtin_nan (tree, tree, int);
145 static int validate_arglist (tree, ...);
146 static bool integer_valued_real_p (tree);
147 static tree fold_trunc_transparent_mathfn (tree);
148 static bool readonly_data_expr (tree);
149 static rtx expand_builtin_fabs (tree, rtx, rtx);
150 static rtx expand_builtin_signbit (tree, rtx);
151 static tree fold_builtin_cabs (tree, tree);
152 static tree fold_builtin_sqrt (tree, tree);
153 static tree fold_builtin_cbrt (tree, tree);
154 static tree fold_builtin_pow (tree, tree, tree);
155 static tree fold_builtin_sin (tree);
156 static tree fold_builtin_cos (tree, tree, tree);
157 static tree fold_builtin_tan (tree);
158 static tree fold_builtin_atan (tree, tree);
159 static tree fold_builtin_trunc (tree);
160 static tree fold_builtin_floor (tree);
161 static tree fold_builtin_ceil (tree);
162 static tree fold_builtin_round (tree);
163 static tree fold_builtin_bitop (tree);
164 static tree fold_builtin_memcpy (tree);
165 static tree fold_builtin_mempcpy (tree, tree, int);
166 static tree fold_builtin_memmove (tree, tree);
167 static tree fold_builtin_strchr (tree);
168 static tree fold_builtin_memcmp (tree);
169 static tree fold_builtin_strcmp (tree);
170 static tree fold_builtin_strncmp (tree);
171 static tree fold_builtin_signbit (tree);
172 static tree fold_builtin_copysign (tree, tree);
173 static tree fold_builtin_isascii (tree);
174 static tree fold_builtin_toascii (tree);
175 static tree fold_builtin_isdigit (tree);
176 static tree fold_builtin_fabs (tree, tree);
177 static tree fold_builtin_abs (tree, tree);
178 static tree fold_builtin_unordered_cmp (tree, enum tree_code, enum tree_code);
179 static tree fold_builtin_1 (tree, bool);
180
181 static tree fold_builtin_strpbrk (tree);
182 static tree fold_builtin_strstr (tree);
183 static tree fold_builtin_strrchr (tree);
184 static tree fold_builtin_strcat (tree);
185 static tree fold_builtin_strncat (tree);
186 static tree fold_builtin_strspn (tree);
187 static tree fold_builtin_strcspn (tree);
188 static void fold_builtin_next_arg (tree);
189 static tree fold_builtin_sprintf (tree, int);
190
191
192 /* Return the alignment in bits of EXP, a pointer valued expression.
193    But don't return more than MAX_ALIGN no matter what.
194    The alignment returned is, by default, the alignment of the thing that
195    EXP points to.  If it is not a POINTER_TYPE, 0 is returned.
196
197    Otherwise, look at the expression to see if we can do better, i.e., if the
198    expression is actually pointing at an object whose alignment is tighter.  */
199
200 static int
201 get_pointer_alignment (tree exp, unsigned int max_align)
202 {
203   unsigned int align, inner;
204
205   if (TREE_CODE (TREE_TYPE (exp)) != POINTER_TYPE)
206     return 0;
207
208   align = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (exp)));
209   align = MIN (align, max_align);
210
211   while (1)
212     {
213       switch (TREE_CODE (exp))
214         {
215         case NOP_EXPR:
216         case CONVERT_EXPR:
217         case NON_LVALUE_EXPR:
218           exp = TREE_OPERAND (exp, 0);
219           if (TREE_CODE (TREE_TYPE (exp)) != POINTER_TYPE)
220             return align;
221
222           inner = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (exp)));
223           align = MIN (inner, max_align);
224           break;
225
226         case PLUS_EXPR:
227           /* If sum of pointer + int, restrict our maximum alignment to that
228              imposed by the integer.  If not, we can't do any better than
229              ALIGN.  */
230           if (! host_integerp (TREE_OPERAND (exp, 1), 1))
231             return align;
232
233           while (((tree_low_cst (TREE_OPERAND (exp, 1), 1))
234                   & (max_align / BITS_PER_UNIT - 1))
235                  != 0)
236             max_align >>= 1;
237
238           exp = TREE_OPERAND (exp, 0);
239           break;
240
241         case ADDR_EXPR:
242           /* See what we are pointing at and look at its alignment.  */
243           exp = TREE_OPERAND (exp, 0);
244           if (TREE_CODE (exp) == FUNCTION_DECL)
245             align = FUNCTION_BOUNDARY;
246           else if (DECL_P (exp))
247             align = DECL_ALIGN (exp);
248 #ifdef CONSTANT_ALIGNMENT
249           else if (CONSTANT_CLASS_P (exp))
250             align = CONSTANT_ALIGNMENT (exp, align);
251 #endif
252           return MIN (align, max_align);
253
254         default:
255           return align;
256         }
257     }
258 }
259
260 /* Compute the length of a C string.  TREE_STRING_LENGTH is not the right
261    way, because it could contain a zero byte in the middle.
262    TREE_STRING_LENGTH is the size of the character array, not the string.
263
264    ONLY_VALUE should be nonzero if the result is not going to be emitted
265    into the instruction stream and zero if it is going to be expanded.
266    E.g. with i++ ? "foo" : "bar", if ONLY_VALUE is nonzero, constant 3
267    is returned, otherwise NULL, since
268    len = c_strlen (src, 1); if (len) expand_expr (len, ...); would not
269    evaluate the side-effects.
270
271    The value returned is of type `ssizetype'.
272
273    Unfortunately, string_constant can't access the values of const char
274    arrays with initializers, so neither can we do so here.  */
275
276 tree
277 c_strlen (tree src, int only_value)
278 {
279   tree offset_node;
280   HOST_WIDE_INT offset;
281   int max;
282   const char *ptr;
283
284   STRIP_NOPS (src);
285   if (TREE_CODE (src) == COND_EXPR
286       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
287     {
288       tree len1, len2;
289
290       len1 = c_strlen (TREE_OPERAND (src, 1), only_value);
291       len2 = c_strlen (TREE_OPERAND (src, 2), only_value);
292       if (tree_int_cst_equal (len1, len2))
293         return len1;
294     }
295
296   if (TREE_CODE (src) == COMPOUND_EXPR
297       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
298     return c_strlen (TREE_OPERAND (src, 1), only_value);
299
300   src = string_constant (src, &offset_node);
301   if (src == 0)
302     return 0;
303
304   max = TREE_STRING_LENGTH (src) - 1;
305   ptr = TREE_STRING_POINTER (src);
306
307   if (offset_node && TREE_CODE (offset_node) != INTEGER_CST)
308     {
309       /* If the string has an internal zero byte (e.g., "foo\0bar"), we can't
310          compute the offset to the following null if we don't know where to
311          start searching for it.  */
312       int i;
313
314       for (i = 0; i < max; i++)
315         if (ptr[i] == 0)
316           return 0;
317
318       /* We don't know the starting offset, but we do know that the string
319          has no internal zero bytes.  We can assume that the offset falls
320          within the bounds of the string; otherwise, the programmer deserves
321          what he gets.  Subtract the offset from the length of the string,
322          and return that.  This would perhaps not be valid if we were dealing
323          with named arrays in addition to literal string constants.  */
324
325       return size_diffop (size_int (max), offset_node);
326     }
327
328   /* We have a known offset into the string.  Start searching there for
329      a null character if we can represent it as a single HOST_WIDE_INT.  */
330   if (offset_node == 0)
331     offset = 0;
332   else if (! host_integerp (offset_node, 0))
333     offset = -1;
334   else
335     offset = tree_low_cst (offset_node, 0);
336
337   /* If the offset is known to be out of bounds, warn, and call strlen at
338      runtime.  */
339   if (offset < 0 || offset > max)
340     {
341       warning ("offset outside bounds of constant string");
342       return 0;
343     }
344
345   /* Use strlen to search for the first zero byte.  Since any strings
346      constructed with build_string will have nulls appended, we win even
347      if we get handed something like (char[4])"abcd".
348
349      Since OFFSET is our starting index into the string, no further
350      calculation is needed.  */
351   return ssize_int (strlen (ptr + offset));
352 }
353
354 /* Return a char pointer for a C string if it is a string constant
355    or sum of string constant and integer constant.  */
356
357 static const char *
358 c_getstr (tree src)
359 {
360   tree offset_node;
361
362   src = string_constant (src, &offset_node);
363   if (src == 0)
364     return 0;
365
366   if (offset_node == 0)
367     return TREE_STRING_POINTER (src);
368   else if (!host_integerp (offset_node, 1)
369            || compare_tree_int (offset_node, TREE_STRING_LENGTH (src) - 1) > 0)
370     return 0;
371
372   return TREE_STRING_POINTER (src) + tree_low_cst (offset_node, 1);
373 }
374
375 /* Return a CONST_INT or CONST_DOUBLE corresponding to target reading
376    GET_MODE_BITSIZE (MODE) bits from string constant STR.  */
377
378 static rtx
379 c_readstr (const char *str, enum machine_mode mode)
380 {
381   HOST_WIDE_INT c[2];
382   HOST_WIDE_INT ch;
383   unsigned int i, j;
384
385   gcc_assert (GET_MODE_CLASS (mode) == MODE_INT);
386
387   c[0] = 0;
388   c[1] = 0;
389   ch = 1;
390   for (i = 0; i < GET_MODE_SIZE (mode); i++)
391     {
392       j = i;
393       if (WORDS_BIG_ENDIAN)
394         j = GET_MODE_SIZE (mode) - i - 1;
395       if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN
396           && GET_MODE_SIZE (mode) > UNITS_PER_WORD)
397         j = j + UNITS_PER_WORD - 2 * (j % UNITS_PER_WORD) - 1;
398       j *= BITS_PER_UNIT;
399       gcc_assert (j <= 2 * HOST_BITS_PER_WIDE_INT);
400
401       if (ch)
402         ch = (unsigned char) str[i];
403       c[j / HOST_BITS_PER_WIDE_INT] |= ch << (j % HOST_BITS_PER_WIDE_INT);
404     }
405   return immed_double_const (c[0], c[1], mode);
406 }
407
408 /* Cast a target constant CST to target CHAR and if that value fits into
409    host char type, return zero and put that value into variable pointed by
410    P.  */
411
412 static int
413 target_char_cast (tree cst, char *p)
414 {
415   unsigned HOST_WIDE_INT val, hostval;
416
417   if (!host_integerp (cst, 1)
418       || CHAR_TYPE_SIZE > HOST_BITS_PER_WIDE_INT)
419     return 1;
420
421   val = tree_low_cst (cst, 1);
422   if (CHAR_TYPE_SIZE < HOST_BITS_PER_WIDE_INT)
423     val &= (((unsigned HOST_WIDE_INT) 1) << CHAR_TYPE_SIZE) - 1;
424
425   hostval = val;
426   if (HOST_BITS_PER_CHAR < HOST_BITS_PER_WIDE_INT)
427     hostval &= (((unsigned HOST_WIDE_INT) 1) << HOST_BITS_PER_CHAR) - 1;
428
429   if (val != hostval)
430     return 1;
431
432   *p = hostval;
433   return 0;
434 }
435
436 /* Similar to save_expr, but assumes that arbitrary code is not executed
437    in between the multiple evaluations.  In particular, we assume that a
438    non-addressable local variable will not be modified.  */
439
440 static tree
441 builtin_save_expr (tree exp)
442 {
443   if (TREE_ADDRESSABLE (exp) == 0
444       && (TREE_CODE (exp) == PARM_DECL
445           || (TREE_CODE (exp) == VAR_DECL && !TREE_STATIC (exp))))
446     return exp;
447
448   return save_expr (exp);
449 }
450
451 /* Given TEM, a pointer to a stack frame, follow the dynamic chain COUNT
452    times to get the address of either a higher stack frame, or a return
453    address located within it (depending on FNDECL_CODE).  */
454
455 static rtx
456 expand_builtin_return_addr (enum built_in_function fndecl_code, int count,
457                             rtx tem)
458 {
459   int i;
460
461   /* Some machines need special handling before we can access
462      arbitrary frames.  For example, on the sparc, we must first flush
463      all register windows to the stack.  */
464 #ifdef SETUP_FRAME_ADDRESSES
465   if (count > 0)
466     SETUP_FRAME_ADDRESSES ();
467 #endif
468
469   /* On the sparc, the return address is not in the frame, it is in a
470      register.  There is no way to access it off of the current frame
471      pointer, but it can be accessed off the previous frame pointer by
472      reading the value from the register window save area.  */
473 #ifdef RETURN_ADDR_IN_PREVIOUS_FRAME
474   if (fndecl_code == BUILT_IN_RETURN_ADDRESS)
475     count--;
476 #endif
477
478   /* Scan back COUNT frames to the specified frame.  */
479   for (i = 0; i < count; i++)
480     {
481       /* Assume the dynamic chain pointer is in the word that the
482          frame address points to, unless otherwise specified.  */
483 #ifdef DYNAMIC_CHAIN_ADDRESS
484       tem = DYNAMIC_CHAIN_ADDRESS (tem);
485 #endif
486       tem = memory_address (Pmode, tem);
487       tem = gen_rtx_MEM (Pmode, tem);
488       set_mem_alias_set (tem, get_frame_alias_set ());
489       tem = copy_to_reg (tem);
490     }
491
492   /* For __builtin_frame_address, return what we've got.  */
493   if (fndecl_code == BUILT_IN_FRAME_ADDRESS)
494     return tem;
495
496   /* For __builtin_return_address, Get the return address from that
497      frame.  */
498 #ifdef RETURN_ADDR_RTX
499   tem = RETURN_ADDR_RTX (count, tem);
500 #else
501   tem = memory_address (Pmode,
502                         plus_constant (tem, GET_MODE_SIZE (Pmode)));
503   tem = gen_rtx_MEM (Pmode, tem);
504   set_mem_alias_set (tem, get_frame_alias_set ());
505 #endif
506   return tem;
507 }
508
509 /* Alias set used for setjmp buffer.  */
510 static HOST_WIDE_INT setjmp_alias_set = -1;
511
512 /* Construct the leading half of a __builtin_setjmp call.  Control will
513    return to RECEIVER_LABEL.  This is used directly by sjlj exception
514    handling code.  */
515
516 void
517 expand_builtin_setjmp_setup (rtx buf_addr, rtx receiver_label)
518 {
519   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
520   rtx stack_save;
521   rtx mem;
522
523   if (setjmp_alias_set == -1)
524     setjmp_alias_set = new_alias_set ();
525
526   buf_addr = convert_memory_address (Pmode, buf_addr);
527
528   buf_addr = force_reg (Pmode, force_operand (buf_addr, NULL_RTX));
529
530   /* We store the frame pointer and the address of receiver_label in
531      the buffer and use the rest of it for the stack save area, which
532      is machine-dependent.  */
533
534   mem = gen_rtx_MEM (Pmode, buf_addr);
535   set_mem_alias_set (mem, setjmp_alias_set);
536   emit_move_insn (mem, targetm.builtin_setjmp_frame_value ());
537
538   mem = gen_rtx_MEM (Pmode, plus_constant (buf_addr, GET_MODE_SIZE (Pmode))),
539   set_mem_alias_set (mem, setjmp_alias_set);
540
541   emit_move_insn (validize_mem (mem),
542                   force_reg (Pmode, gen_rtx_LABEL_REF (Pmode, receiver_label)));
543
544   stack_save = gen_rtx_MEM (sa_mode,
545                             plus_constant (buf_addr,
546                                            2 * GET_MODE_SIZE (Pmode)));
547   set_mem_alias_set (stack_save, setjmp_alias_set);
548   emit_stack_save (SAVE_NONLOCAL, &stack_save, NULL_RTX);
549
550   /* If there is further processing to do, do it.  */
551 #ifdef HAVE_builtin_setjmp_setup
552   if (HAVE_builtin_setjmp_setup)
553     emit_insn (gen_builtin_setjmp_setup (buf_addr));
554 #endif
555
556   /* Tell optimize_save_area_alloca that extra work is going to
557      need to go on during alloca.  */
558   current_function_calls_setjmp = 1;
559
560   /* Set this so all the registers get saved in our frame; we need to be
561      able to copy the saved values for any registers from frames we unwind.  */
562   current_function_has_nonlocal_label = 1;
563 }
564
565 /* Construct the trailing part of a __builtin_setjmp call.
566    This is used directly by sjlj exception handling code.  */
567
568 void
569 expand_builtin_setjmp_receiver (rtx receiver_label ATTRIBUTE_UNUSED)
570 {
571   /* Clobber the FP when we get here, so we have to make sure it's
572      marked as used by this function.  */
573   emit_insn (gen_rtx_USE (VOIDmode, hard_frame_pointer_rtx));
574
575   /* Mark the static chain as clobbered here so life information
576      doesn't get messed up for it.  */
577   emit_insn (gen_rtx_CLOBBER (VOIDmode, static_chain_rtx));
578
579   /* Now put in the code to restore the frame pointer, and argument
580      pointer, if needed.  */
581 #ifdef HAVE_nonlocal_goto
582   if (! HAVE_nonlocal_goto)
583 #endif
584     emit_move_insn (virtual_stack_vars_rtx, hard_frame_pointer_rtx);
585
586 #if ARG_POINTER_REGNUM != HARD_FRAME_POINTER_REGNUM
587   if (fixed_regs[ARG_POINTER_REGNUM])
588     {
589 #ifdef ELIMINABLE_REGS
590       size_t i;
591       static const struct elims {const int from, to;} elim_regs[] = ELIMINABLE_REGS;
592
593       for (i = 0; i < ARRAY_SIZE (elim_regs); i++)
594         if (elim_regs[i].from == ARG_POINTER_REGNUM
595             && elim_regs[i].to == HARD_FRAME_POINTER_REGNUM)
596           break;
597
598       if (i == ARRAY_SIZE (elim_regs))
599 #endif
600         {
601           /* Now restore our arg pointer from the address at which it
602              was saved in our stack frame.  */
603           emit_move_insn (virtual_incoming_args_rtx,
604                           copy_to_reg (get_arg_pointer_save_area (cfun)));
605         }
606     }
607 #endif
608
609 #ifdef HAVE_builtin_setjmp_receiver
610   if (HAVE_builtin_setjmp_receiver)
611     emit_insn (gen_builtin_setjmp_receiver (receiver_label));
612   else
613 #endif
614 #ifdef HAVE_nonlocal_goto_receiver
615     if (HAVE_nonlocal_goto_receiver)
616       emit_insn (gen_nonlocal_goto_receiver ());
617     else
618 #endif
619       { /* Nothing */ }
620
621   /* @@@ This is a kludge.  Not all machine descriptions define a blockage
622      insn, but we must not allow the code we just generated to be reordered
623      by scheduling.  Specifically, the update of the frame pointer must
624      happen immediately, not later.  So emit an ASM_INPUT to act as blockage
625      insn.  */
626   emit_insn (gen_rtx_ASM_INPUT (VOIDmode, ""));
627 }
628
629 /* __builtin_setjmp is passed a pointer to an array of five words (not
630    all will be used on all machines).  It operates similarly to the C
631    library function of the same name, but is more efficient.  Much of
632    the code below (and for longjmp) is copied from the handling of
633    non-local gotos.
634
635    NOTE: This is intended for use by GNAT and the exception handling
636    scheme in the compiler and will only work in the method used by
637    them.  */
638
639 static rtx
640 expand_builtin_setjmp (tree arglist, rtx target)
641 {
642   rtx buf_addr, next_lab, cont_lab;
643
644   if (!validate_arglist (arglist, POINTER_TYPE, VOID_TYPE))
645     return NULL_RTX;
646
647   if (target == 0 || !REG_P (target)
648       || REGNO (target) < FIRST_PSEUDO_REGISTER)
649     target = gen_reg_rtx (TYPE_MODE (integer_type_node));
650
651   buf_addr = expand_expr (TREE_VALUE (arglist), NULL_RTX, VOIDmode, 0);
652
653   next_lab = gen_label_rtx ();
654   cont_lab = gen_label_rtx ();
655
656   expand_builtin_setjmp_setup (buf_addr, next_lab);
657
658   /* Set TARGET to zero and branch to the continue label.  Use emit_jump to
659      ensure that pending stack adjustments are flushed.  */
660   emit_move_insn (target, const0_rtx);
661   emit_jump (cont_lab);
662
663   emit_label (next_lab);
664
665   expand_builtin_setjmp_receiver (next_lab);
666
667   /* Set TARGET to one.  */
668   emit_move_insn (target, const1_rtx);
669   emit_label (cont_lab);
670
671   /* Tell flow about the strange goings on.  Putting `next_lab' on
672      `nonlocal_goto_handler_labels' to indicates that function
673      calls may traverse the arc back to this label.  */
674
675   current_function_has_nonlocal_label = 1;
676   nonlocal_goto_handler_labels
677     = gen_rtx_EXPR_LIST (VOIDmode, next_lab, nonlocal_goto_handler_labels);
678
679   return target;
680 }
681
682 /* __builtin_longjmp is passed a pointer to an array of five words (not
683    all will be used on all machines).  It operates similarly to the C
684    library function of the same name, but is more efficient.  Much of
685    the code below is copied from the handling of non-local gotos.
686
687    NOTE: This is intended for use by GNAT and the exception handling
688    scheme in the compiler and will only work in the method used by
689    them.  */
690
691 static void
692 expand_builtin_longjmp (rtx buf_addr, rtx value)
693 {
694   rtx fp, lab, stack, insn, last;
695   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
696
697   if (setjmp_alias_set == -1)
698     setjmp_alias_set = new_alias_set ();
699
700   buf_addr = convert_memory_address (Pmode, buf_addr);
701
702   buf_addr = force_reg (Pmode, buf_addr);
703
704   /* We used to store value in static_chain_rtx, but that fails if pointers
705      are smaller than integers.  We instead require that the user must pass
706      a second argument of 1, because that is what builtin_setjmp will
707      return.  This also makes EH slightly more efficient, since we are no
708      longer copying around a value that we don't care about.  */
709   gcc_assert (value == const1_rtx);
710
711   current_function_calls_longjmp = 1;
712
713   last = get_last_insn ();
714 #ifdef HAVE_builtin_longjmp
715   if (HAVE_builtin_longjmp)
716     emit_insn (gen_builtin_longjmp (buf_addr));
717   else
718 #endif
719     {
720       fp = gen_rtx_MEM (Pmode, buf_addr);
721       lab = gen_rtx_MEM (Pmode, plus_constant (buf_addr,
722                                                GET_MODE_SIZE (Pmode)));
723
724       stack = gen_rtx_MEM (sa_mode, plus_constant (buf_addr,
725                                                    2 * GET_MODE_SIZE (Pmode)));
726       set_mem_alias_set (fp, setjmp_alias_set);
727       set_mem_alias_set (lab, setjmp_alias_set);
728       set_mem_alias_set (stack, setjmp_alias_set);
729
730       /* Pick up FP, label, and SP from the block and jump.  This code is
731          from expand_goto in stmt.c; see there for detailed comments.  */
732 #if HAVE_nonlocal_goto
733       if (HAVE_nonlocal_goto)
734         /* We have to pass a value to the nonlocal_goto pattern that will
735            get copied into the static_chain pointer, but it does not matter
736            what that value is, because builtin_setjmp does not use it.  */
737         emit_insn (gen_nonlocal_goto (value, lab, stack, fp));
738       else
739 #endif
740         {
741           lab = copy_to_reg (lab);
742
743           emit_insn (gen_rtx_CLOBBER (VOIDmode,
744                                       gen_rtx_MEM (BLKmode,
745                                                    gen_rtx_SCRATCH (VOIDmode))));
746           emit_insn (gen_rtx_CLOBBER (VOIDmode,
747                                       gen_rtx_MEM (BLKmode,
748                                                    hard_frame_pointer_rtx)));
749
750           emit_move_insn (hard_frame_pointer_rtx, fp);
751           emit_stack_restore (SAVE_NONLOCAL, stack, NULL_RTX);
752
753           emit_insn (gen_rtx_USE (VOIDmode, hard_frame_pointer_rtx));
754           emit_insn (gen_rtx_USE (VOIDmode, stack_pointer_rtx));
755           emit_indirect_jump (lab);
756         }
757     }
758
759   /* Search backwards and mark the jump insn as a non-local goto.
760      Note that this precludes the use of __builtin_longjmp to a
761      __builtin_setjmp target in the same function.  However, we've
762      already cautioned the user that these functions are for
763      internal exception handling use only.  */
764   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
765     {
766       gcc_assert (insn != last);
767
768       if (JUMP_P (insn))
769         {
770           REG_NOTES (insn) = alloc_EXPR_LIST (REG_NON_LOCAL_GOTO, const0_rtx,
771                                               REG_NOTES (insn));
772           break;
773         }
774       else if (CALL_P (insn))
775         break;
776     }
777 }
778
779 /* Expand a call to __builtin_nonlocal_goto.  We're passed the target label
780    and the address of the save area.  */
781
782 static rtx
783 expand_builtin_nonlocal_goto (tree arglist)
784 {
785   tree t_label, t_save_area;
786   rtx r_label, r_save_area, r_fp, r_sp, insn;
787
788   if (!validate_arglist (arglist, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
789     return NULL_RTX;
790
791   t_label = TREE_VALUE (arglist);
792   arglist = TREE_CHAIN (arglist);
793   t_save_area = TREE_VALUE (arglist);
794
795   r_label = expand_expr (t_label, NULL_RTX, VOIDmode, 0);
796   r_label = convert_memory_address (Pmode, r_label);
797   r_save_area = expand_expr (t_save_area, NULL_RTX, VOIDmode, 0);
798   r_save_area = convert_memory_address (Pmode, r_save_area);
799   r_fp = gen_rtx_MEM (Pmode, r_save_area);
800   r_sp = gen_rtx_MEM (STACK_SAVEAREA_MODE (SAVE_NONLOCAL),
801                       plus_constant (r_save_area, GET_MODE_SIZE (Pmode)));
802
803   current_function_has_nonlocal_goto = 1;
804
805 #if HAVE_nonlocal_goto
806   /* ??? We no longer need to pass the static chain value, afaik.  */
807   if (HAVE_nonlocal_goto)
808     emit_insn (gen_nonlocal_goto (const0_rtx, r_label, r_sp, r_fp));
809   else
810 #endif
811     {
812       r_label = copy_to_reg (r_label);
813
814       emit_insn (gen_rtx_CLOBBER (VOIDmode,
815                                   gen_rtx_MEM (BLKmode,
816                                                gen_rtx_SCRATCH (VOIDmode))));
817
818       emit_insn (gen_rtx_CLOBBER (VOIDmode,
819                                   gen_rtx_MEM (BLKmode,
820                                                hard_frame_pointer_rtx)));
821
822       /* Restore frame pointer for containing function.
823          This sets the actual hard register used for the frame pointer
824          to the location of the function's incoming static chain info.
825          The non-local goto handler will then adjust it to contain the
826          proper value and reload the argument pointer, if needed.  */
827       emit_move_insn (hard_frame_pointer_rtx, r_fp);
828       emit_stack_restore (SAVE_NONLOCAL, r_sp, NULL_RTX);
829
830       /* USE of hard_frame_pointer_rtx added for consistency;
831          not clear if really needed.  */
832       emit_insn (gen_rtx_USE (VOIDmode, hard_frame_pointer_rtx));
833       emit_insn (gen_rtx_USE (VOIDmode, stack_pointer_rtx));
834       emit_indirect_jump (r_label);
835     }
836
837   /* Search backwards to the jump insn and mark it as a
838      non-local goto.  */
839   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
840     {
841       if (JUMP_P (insn))
842         {
843           REG_NOTES (insn) = alloc_EXPR_LIST (REG_NON_LOCAL_GOTO,
844                                               const0_rtx, REG_NOTES (insn));
845           break;
846         }
847       else if (CALL_P (insn))
848         break;
849     }
850
851   return const0_rtx;
852 }
853
854 /* __builtin_update_setjmp_buf is passed a pointer to an array of five words
855    (not all will be used on all machines) that was passed to __builtin_setjmp.
856    It updates the stack pointer in that block to correspond to the current
857    stack pointer.  */
858
859 static void
860 expand_builtin_update_setjmp_buf (rtx buf_addr)
861 {
862   enum machine_mode sa_mode = Pmode;
863   rtx stack_save;
864
865
866 #ifdef HAVE_save_stack_nonlocal
867   if (HAVE_save_stack_nonlocal)
868     sa_mode = insn_data[(int) CODE_FOR_save_stack_nonlocal].operand[0].mode;
869 #endif
870 #ifdef STACK_SAVEAREA_MODE
871   sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
872 #endif
873
874   stack_save
875     = gen_rtx_MEM (sa_mode,
876                    memory_address
877                    (sa_mode,
878                     plus_constant (buf_addr, 2 * GET_MODE_SIZE (Pmode))));
879
880 #ifdef HAVE_setjmp
881   if (HAVE_setjmp)
882     emit_insn (gen_setjmp ());
883 #endif
884
885   emit_stack_save (SAVE_NONLOCAL, &stack_save, NULL_RTX);
886 }
887
888 /* Expand a call to __builtin_prefetch.  For a target that does not support
889    data prefetch, evaluate the memory address argument in case it has side
890    effects.  */
891
892 static void
893 expand_builtin_prefetch (tree arglist)
894 {
895   tree arg0, arg1, arg2;
896   rtx op0, op1, op2;
897
898   if (!validate_arglist (arglist, POINTER_TYPE, 0))
899     return;
900
901   arg0 = TREE_VALUE (arglist);
902   /* Arguments 1 and 2 are optional; argument 1 (read/write) defaults to
903      zero (read) and argument 2 (locality) defaults to 3 (high degree of
904      locality).  */
905   if (TREE_CHAIN (arglist))
906     {
907       arg1 = TREE_VALUE (TREE_CHAIN (arglist));
908       if (TREE_CHAIN (TREE_CHAIN (arglist)))
909         arg2 = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (arglist)));
910       else
911         arg2 = build_int_cst (NULL_TREE, 3);
912     }
913   else
914     {
915       arg1 = integer_zero_node;
916       arg2 = build_int_cst (NULL_TREE, 3);
917     }
918
919   /* Argument 0 is an address.  */
920   op0 = expand_expr (arg0, NULL_RTX, Pmode, EXPAND_NORMAL);
921
922   /* Argument 1 (read/write flag) must be a compile-time constant int.  */
923   if (TREE_CODE (arg1) != INTEGER_CST)
924     {
925       error ("second argument to %<__builtin_prefetch%> must be a constant");
926       arg1 = integer_zero_node;
927     }
928   op1 = expand_expr (arg1, NULL_RTX, VOIDmode, 0);
929   /* Argument 1 must be either zero or one.  */
930   if (INTVAL (op1) != 0 && INTVAL (op1) != 1)
931     {
932       warning ("invalid second argument to %<__builtin_prefetch%>;"
933                " using zero");
934       op1 = const0_rtx;
935     }
936
937   /* Argument 2 (locality) must be a compile-time constant int.  */
938   if (TREE_CODE (arg2) != INTEGER_CST)
939     {
940       error ("third argument to %<__builtin_prefetch%> must be a constant");
941       arg2 = integer_zero_node;
942     }
943   op2 = expand_expr (arg2, NULL_RTX, VOIDmode, 0);
944   /* Argument 2 must be 0, 1, 2, or 3.  */
945   if (INTVAL (op2) < 0 || INTVAL (op2) > 3)
946     {
947       warning ("invalid third argument to %<__builtin_prefetch%>; using zero");
948       op2 = const0_rtx;
949     }
950
951 #ifdef HAVE_prefetch
952   if (HAVE_prefetch)
953     {
954       if ((! (*insn_data[(int) CODE_FOR_prefetch].operand[0].predicate)
955              (op0,
956               insn_data[(int) CODE_FOR_prefetch].operand[0].mode))
957           || (GET_MODE (op0) != Pmode))
958         {
959           op0 = convert_memory_address (Pmode, op0);
960           op0 = force_reg (Pmode, op0);
961         }
962       emit_insn (gen_prefetch (op0, op1, op2));
963     }
964 #endif
965
966   /* Don't do anything with direct references to volatile memory, but
967      generate code to handle other side effects.  */
968   if (!MEM_P (op0) && side_effects_p (op0))
969     emit_insn (op0);
970 }
971
972 /* Get a MEM rtx for expression EXP which is the address of an operand
973    to be used to be used in a string instruction (cmpstrsi, movmemsi, ..).  */
974
975 static rtx
976 get_memory_rtx (tree exp)
977 {
978   rtx addr = expand_expr (exp, NULL_RTX, ptr_mode, EXPAND_SUM);
979   rtx mem;
980
981   addr = convert_memory_address (Pmode, addr);
982
983   mem = gen_rtx_MEM (BLKmode, memory_address (BLKmode, addr));
984
985   /* Get an expression we can use to find the attributes to assign to MEM.
986      If it is an ADDR_EXPR, use the operand.  Otherwise, dereference it if
987      we can.  First remove any nops.  */
988   while ((TREE_CODE (exp) == NOP_EXPR || TREE_CODE (exp) == CONVERT_EXPR
989           || TREE_CODE (exp) == NON_LVALUE_EXPR)
990          && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (exp, 0))))
991     exp = TREE_OPERAND (exp, 0);
992
993   if (TREE_CODE (exp) == ADDR_EXPR)
994     exp = TREE_OPERAND (exp, 0);
995   else if (POINTER_TYPE_P (TREE_TYPE (exp)))
996     exp = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (exp)), exp);
997   else
998     exp = NULL;
999
1000   /* Honor attributes derived from exp, except for the alias set
1001      (as builtin stringops may alias with anything) and the size
1002      (as stringops may access multiple array elements).  */
1003   if (exp)
1004     {
1005       set_mem_attributes (mem, exp, 0);
1006       set_mem_alias_set (mem, 0);
1007       set_mem_size (mem, NULL_RTX);
1008     }
1009
1010   return mem;
1011 }
1012 \f
1013 /* Built-in functions to perform an untyped call and return.  */
1014
1015 /* For each register that may be used for calling a function, this
1016    gives a mode used to copy the register's value.  VOIDmode indicates
1017    the register is not used for calling a function.  If the machine
1018    has register windows, this gives only the outbound registers.
1019    INCOMING_REGNO gives the corresponding inbound register.  */
1020 static enum machine_mode apply_args_mode[FIRST_PSEUDO_REGISTER];
1021
1022 /* For each register that may be used for returning values, this gives
1023    a mode used to copy the register's value.  VOIDmode indicates the
1024    register is not used for returning values.  If the machine has
1025    register windows, this gives only the outbound registers.
1026    INCOMING_REGNO gives the corresponding inbound register.  */
1027 static enum machine_mode apply_result_mode[FIRST_PSEUDO_REGISTER];
1028
1029 /* For each register that may be used for calling a function, this
1030    gives the offset of that register into the block returned by
1031    __builtin_apply_args.  0 indicates that the register is not
1032    used for calling a function.  */
1033 static int apply_args_reg_offset[FIRST_PSEUDO_REGISTER];
1034
1035 /* Return the size required for the block returned by __builtin_apply_args,
1036    and initialize apply_args_mode.  */
1037
1038 static int
1039 apply_args_size (void)
1040 {
1041   static int size = -1;
1042   int align;
1043   unsigned int regno;
1044   enum machine_mode mode;
1045
1046   /* The values computed by this function never change.  */
1047   if (size < 0)
1048     {
1049       /* The first value is the incoming arg-pointer.  */
1050       size = GET_MODE_SIZE (Pmode);
1051
1052       /* The second value is the structure value address unless this is
1053          passed as an "invisible" first argument.  */
1054       if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1055         size += GET_MODE_SIZE (Pmode);
1056
1057       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1058         if (FUNCTION_ARG_REGNO_P (regno))
1059           {
1060             mode = reg_raw_mode[regno];
1061
1062             gcc_assert (mode != VOIDmode);
1063
1064             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1065             if (size % align != 0)
1066               size = CEIL (size, align) * align;
1067             apply_args_reg_offset[regno] = size;
1068             size += GET_MODE_SIZE (mode);
1069             apply_args_mode[regno] = mode;
1070           }
1071         else
1072           {
1073             apply_args_mode[regno] = VOIDmode;
1074             apply_args_reg_offset[regno] = 0;
1075           }
1076     }
1077   return size;
1078 }
1079
1080 /* Return the size required for the block returned by __builtin_apply,
1081    and initialize apply_result_mode.  */
1082
1083 static int
1084 apply_result_size (void)
1085 {
1086   static int size = -1;
1087   int align, regno;
1088   enum machine_mode mode;
1089
1090   /* The values computed by this function never change.  */
1091   if (size < 0)
1092     {
1093       size = 0;
1094
1095       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1096         if (FUNCTION_VALUE_REGNO_P (regno))
1097           {
1098             mode = reg_raw_mode[regno];
1099
1100             gcc_assert (mode != VOIDmode);
1101
1102             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1103             if (size % align != 0)
1104               size = CEIL (size, align) * align;
1105             size += GET_MODE_SIZE (mode);
1106             apply_result_mode[regno] = mode;
1107           }
1108         else
1109           apply_result_mode[regno] = VOIDmode;
1110
1111       /* Allow targets that use untyped_call and untyped_return to override
1112          the size so that machine-specific information can be stored here.  */
1113 #ifdef APPLY_RESULT_SIZE
1114       size = APPLY_RESULT_SIZE;
1115 #endif
1116     }
1117   return size;
1118 }
1119
1120 #if defined (HAVE_untyped_call) || defined (HAVE_untyped_return)
1121 /* Create a vector describing the result block RESULT.  If SAVEP is true,
1122    the result block is used to save the values; otherwise it is used to
1123    restore the values.  */
1124
1125 static rtx
1126 result_vector (int savep, rtx result)
1127 {
1128   int regno, size, align, nelts;
1129   enum machine_mode mode;
1130   rtx reg, mem;
1131   rtx *savevec = alloca (FIRST_PSEUDO_REGISTER * sizeof (rtx));
1132
1133   size = nelts = 0;
1134   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1135     if ((mode = apply_result_mode[regno]) != VOIDmode)
1136       {
1137         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1138         if (size % align != 0)
1139           size = CEIL (size, align) * align;
1140         reg = gen_rtx_REG (mode, savep ? regno : INCOMING_REGNO (regno));
1141         mem = adjust_address (result, mode, size);
1142         savevec[nelts++] = (savep
1143                             ? gen_rtx_SET (VOIDmode, mem, reg)
1144                             : gen_rtx_SET (VOIDmode, reg, mem));
1145         size += GET_MODE_SIZE (mode);
1146       }
1147   return gen_rtx_PARALLEL (VOIDmode, gen_rtvec_v (nelts, savevec));
1148 }
1149 #endif /* HAVE_untyped_call or HAVE_untyped_return */
1150
1151 /* Save the state required to perform an untyped call with the same
1152    arguments as were passed to the current function.  */
1153
1154 static rtx
1155 expand_builtin_apply_args_1 (void)
1156 {
1157   rtx registers, tem;
1158   int size, align, regno;
1159   enum machine_mode mode;
1160   rtx struct_incoming_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 1);
1161
1162   /* Create a block where the arg-pointer, structure value address,
1163      and argument registers can be saved.  */
1164   registers = assign_stack_local (BLKmode, apply_args_size (), -1);
1165
1166   /* Walk past the arg-pointer and structure value address.  */
1167   size = GET_MODE_SIZE (Pmode);
1168   if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1169     size += GET_MODE_SIZE (Pmode);
1170
1171   /* Save each register used in calling a function to the block.  */
1172   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1173     if ((mode = apply_args_mode[regno]) != VOIDmode)
1174       {
1175         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1176         if (size % align != 0)
1177           size = CEIL (size, align) * align;
1178
1179         tem = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1180
1181         emit_move_insn (adjust_address (registers, mode, size), tem);
1182         size += GET_MODE_SIZE (mode);
1183       }
1184
1185   /* Save the arg pointer to the block.  */
1186   tem = copy_to_reg (virtual_incoming_args_rtx);
1187 #ifdef STACK_GROWS_DOWNWARD
1188   /* We need the pointer as the caller actually passed them to us, not
1189      as we might have pretended they were passed.  Make sure it's a valid
1190      operand, as emit_move_insn isn't expected to handle a PLUS.  */
1191   tem
1192     = force_operand (plus_constant (tem, current_function_pretend_args_size),
1193                      NULL_RTX);
1194 #endif
1195   emit_move_insn (adjust_address (registers, Pmode, 0), tem);
1196
1197   size = GET_MODE_SIZE (Pmode);
1198
1199   /* Save the structure value address unless this is passed as an
1200      "invisible" first argument.  */
1201   if (struct_incoming_value)
1202     {
1203       emit_move_insn (adjust_address (registers, Pmode, size),
1204                       copy_to_reg (struct_incoming_value));
1205       size += GET_MODE_SIZE (Pmode);
1206     }
1207
1208   /* Return the address of the block.  */
1209   return copy_addr_to_reg (XEXP (registers, 0));
1210 }
1211
1212 /* __builtin_apply_args returns block of memory allocated on
1213    the stack into which is stored the arg pointer, structure
1214    value address, static chain, and all the registers that might
1215    possibly be used in performing a function call.  The code is
1216    moved to the start of the function so the incoming values are
1217    saved.  */
1218
1219 static rtx
1220 expand_builtin_apply_args (void)
1221 {
1222   /* Don't do __builtin_apply_args more than once in a function.
1223      Save the result of the first call and reuse it.  */
1224   if (apply_args_value != 0)
1225     return apply_args_value;
1226   {
1227     /* When this function is called, it means that registers must be
1228        saved on entry to this function.  So we migrate the
1229        call to the first insn of this function.  */
1230     rtx temp;
1231     rtx seq;
1232
1233     start_sequence ();
1234     temp = expand_builtin_apply_args_1 ();
1235     seq = get_insns ();
1236     end_sequence ();
1237
1238     apply_args_value = temp;
1239
1240     /* Put the insns after the NOTE that starts the function.
1241        If this is inside a start_sequence, make the outer-level insn
1242        chain current, so the code is placed at the start of the
1243        function.  */
1244     push_topmost_sequence ();
1245     emit_insn_before (seq, NEXT_INSN (entry_of_function ()));
1246     pop_topmost_sequence ();
1247     return temp;
1248   }
1249 }
1250
1251 /* Perform an untyped call and save the state required to perform an
1252    untyped return of whatever value was returned by the given function.  */
1253
1254 static rtx
1255 expand_builtin_apply (rtx function, rtx arguments, rtx argsize)
1256 {
1257   int size, align, regno;
1258   enum machine_mode mode;
1259   rtx incoming_args, result, reg, dest, src, call_insn;
1260   rtx old_stack_level = 0;
1261   rtx call_fusage = 0;
1262   rtx struct_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0);
1263
1264   arguments = convert_memory_address (Pmode, arguments);
1265
1266   /* Create a block where the return registers can be saved.  */
1267   result = assign_stack_local (BLKmode, apply_result_size (), -1);
1268
1269   /* Fetch the arg pointer from the ARGUMENTS block.  */
1270   incoming_args = gen_reg_rtx (Pmode);
1271   emit_move_insn (incoming_args, gen_rtx_MEM (Pmode, arguments));
1272 #ifndef STACK_GROWS_DOWNWARD
1273   incoming_args = expand_simple_binop (Pmode, MINUS, incoming_args, argsize,
1274                                        incoming_args, 0, OPTAB_LIB_WIDEN);
1275 #endif
1276
1277   /* Push a new argument block and copy the arguments.  Do not allow
1278      the (potential) memcpy call below to interfere with our stack
1279      manipulations.  */
1280   do_pending_stack_adjust ();
1281   NO_DEFER_POP;
1282
1283   /* Save the stack with nonlocal if available.  */
1284 #ifdef HAVE_save_stack_nonlocal
1285   if (HAVE_save_stack_nonlocal)
1286     emit_stack_save (SAVE_NONLOCAL, &old_stack_level, NULL_RTX);
1287   else
1288 #endif
1289     emit_stack_save (SAVE_BLOCK, &old_stack_level, NULL_RTX);
1290
1291   /* Allocate a block of memory onto the stack and copy the memory
1292      arguments to the outgoing arguments address.  */
1293   allocate_dynamic_stack_space (argsize, 0, BITS_PER_UNIT);
1294   dest = virtual_outgoing_args_rtx;
1295 #ifndef STACK_GROWS_DOWNWARD
1296   if (GET_CODE (argsize) == CONST_INT)
1297     dest = plus_constant (dest, -INTVAL (argsize));
1298   else
1299     dest = gen_rtx_PLUS (Pmode, dest, negate_rtx (Pmode, argsize));
1300 #endif
1301   dest = gen_rtx_MEM (BLKmode, dest);
1302   set_mem_align (dest, PARM_BOUNDARY);
1303   src = gen_rtx_MEM (BLKmode, incoming_args);
1304   set_mem_align (src, PARM_BOUNDARY);
1305   emit_block_move (dest, src, argsize, BLOCK_OP_NORMAL);
1306
1307   /* Refer to the argument block.  */
1308   apply_args_size ();
1309   arguments = gen_rtx_MEM (BLKmode, arguments);
1310   set_mem_align (arguments, PARM_BOUNDARY);
1311
1312   /* Walk past the arg-pointer and structure value address.  */
1313   size = GET_MODE_SIZE (Pmode);
1314   if (struct_value)
1315     size += GET_MODE_SIZE (Pmode);
1316
1317   /* Restore each of the registers previously saved.  Make USE insns
1318      for each of these registers for use in making the call.  */
1319   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1320     if ((mode = apply_args_mode[regno]) != VOIDmode)
1321       {
1322         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1323         if (size % align != 0)
1324           size = CEIL (size, align) * align;
1325         reg = gen_rtx_REG (mode, regno);
1326         emit_move_insn (reg, adjust_address (arguments, mode, size));
1327         use_reg (&call_fusage, reg);
1328         size += GET_MODE_SIZE (mode);
1329       }
1330
1331   /* Restore the structure value address unless this is passed as an
1332      "invisible" first argument.  */
1333   size = GET_MODE_SIZE (Pmode);
1334   if (struct_value)
1335     {
1336       rtx value = gen_reg_rtx (Pmode);
1337       emit_move_insn (value, adjust_address (arguments, Pmode, size));
1338       emit_move_insn (struct_value, value);
1339       if (REG_P (struct_value))
1340         use_reg (&call_fusage, struct_value);
1341       size += GET_MODE_SIZE (Pmode);
1342     }
1343
1344   /* All arguments and registers used for the call are set up by now!  */
1345   function = prepare_call_address (function, NULL, &call_fusage, 0, 0);
1346
1347   /* Ensure address is valid.  SYMBOL_REF is already valid, so no need,
1348      and we don't want to load it into a register as an optimization,
1349      because prepare_call_address already did it if it should be done.  */
1350   if (GET_CODE (function) != SYMBOL_REF)
1351     function = memory_address (FUNCTION_MODE, function);
1352
1353   /* Generate the actual call instruction and save the return value.  */
1354 #ifdef HAVE_untyped_call
1355   if (HAVE_untyped_call)
1356     emit_call_insn (gen_untyped_call (gen_rtx_MEM (FUNCTION_MODE, function),
1357                                       result, result_vector (1, result)));
1358   else
1359 #endif
1360 #ifdef HAVE_call_value
1361   if (HAVE_call_value)
1362     {
1363       rtx valreg = 0;
1364
1365       /* Locate the unique return register.  It is not possible to
1366          express a call that sets more than one return register using
1367          call_value; use untyped_call for that.  In fact, untyped_call
1368          only needs to save the return registers in the given block.  */
1369       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1370         if ((mode = apply_result_mode[regno]) != VOIDmode)
1371           {
1372             gcc_assert (!valreg); /* HAVE_untyped_call required.  */
1373
1374             valreg = gen_rtx_REG (mode, regno);
1375           }
1376
1377       emit_call_insn (GEN_CALL_VALUE (valreg,
1378                                       gen_rtx_MEM (FUNCTION_MODE, function),
1379                                       const0_rtx, NULL_RTX, const0_rtx));
1380
1381       emit_move_insn (adjust_address (result, GET_MODE (valreg), 0), valreg);
1382     }
1383   else
1384 #endif
1385     gcc_unreachable ();
1386
1387   /* Find the CALL insn we just emitted, and attach the register usage
1388      information.  */
1389   call_insn = last_call_insn ();
1390   add_function_usage_to (call_insn, call_fusage);
1391
1392   /* Restore the stack.  */
1393 #ifdef HAVE_save_stack_nonlocal
1394   if (HAVE_save_stack_nonlocal)
1395     emit_stack_restore (SAVE_NONLOCAL, old_stack_level, NULL_RTX);
1396   else
1397 #endif
1398     emit_stack_restore (SAVE_BLOCK, old_stack_level, NULL_RTX);
1399
1400   OK_DEFER_POP;
1401
1402   /* Return the address of the result block.  */
1403   result = copy_addr_to_reg (XEXP (result, 0));
1404   return convert_memory_address (ptr_mode, result);
1405 }
1406
1407 /* Perform an untyped return.  */
1408
1409 static void
1410 expand_builtin_return (rtx result)
1411 {
1412   int size, align, regno;
1413   enum machine_mode mode;
1414   rtx reg;
1415   rtx call_fusage = 0;
1416
1417   result = convert_memory_address (Pmode, result);
1418
1419   apply_result_size ();
1420   result = gen_rtx_MEM (BLKmode, result);
1421
1422 #ifdef HAVE_untyped_return
1423   if (HAVE_untyped_return)
1424     {
1425       emit_jump_insn (gen_untyped_return (result, result_vector (0, result)));
1426       emit_barrier ();
1427       return;
1428     }
1429 #endif
1430
1431   /* Restore the return value and note that each value is used.  */
1432   size = 0;
1433   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1434     if ((mode = apply_result_mode[regno]) != VOIDmode)
1435       {
1436         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1437         if (size % align != 0)
1438           size = CEIL (size, align) * align;
1439         reg = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1440         emit_move_insn (reg, adjust_address (result, mode, size));
1441
1442         push_to_sequence (call_fusage);
1443         emit_insn (gen_rtx_USE (VOIDmode, reg));
1444         call_fusage = get_insns ();
1445         end_sequence ();
1446         size += GET_MODE_SIZE (mode);
1447       }
1448
1449   /* Put the USE insns before the return.  */
1450   emit_insn (call_fusage);
1451
1452   /* Return whatever values was restored by jumping directly to the end
1453      of the function.  */
1454   expand_naked_return ();
1455 }
1456
1457 /* Used by expand_builtin_classify_type and fold_builtin_classify_type.  */
1458
1459 static enum type_class
1460 type_to_class (tree type)
1461 {
1462   switch (TREE_CODE (type))
1463     {
1464     case VOID_TYPE:        return void_type_class;
1465     case INTEGER_TYPE:     return integer_type_class;
1466     case CHAR_TYPE:        return char_type_class;
1467     case ENUMERAL_TYPE:    return enumeral_type_class;
1468     case BOOLEAN_TYPE:     return boolean_type_class;
1469     case POINTER_TYPE:     return pointer_type_class;
1470     case REFERENCE_TYPE:   return reference_type_class;
1471     case OFFSET_TYPE:      return offset_type_class;
1472     case REAL_TYPE:        return real_type_class;
1473     case COMPLEX_TYPE:     return complex_type_class;
1474     case FUNCTION_TYPE:    return function_type_class;
1475     case METHOD_TYPE:      return method_type_class;
1476     case RECORD_TYPE:      return record_type_class;
1477     case UNION_TYPE:
1478     case QUAL_UNION_TYPE:  return union_type_class;
1479     case ARRAY_TYPE:       return (TYPE_STRING_FLAG (type)
1480                                    ? string_type_class : array_type_class);
1481     case SET_TYPE:         return set_type_class;
1482     case FILE_TYPE:        return file_type_class;
1483     case LANG_TYPE:        return lang_type_class;
1484     default:               return no_type_class;
1485     }
1486 }
1487
1488 /* Expand a call to __builtin_classify_type with arguments found in
1489    ARGLIST.  */
1490
1491 static rtx
1492 expand_builtin_classify_type (tree arglist)
1493 {
1494   if (arglist != 0)
1495     return GEN_INT (type_to_class (TREE_TYPE (TREE_VALUE (arglist))));
1496   return GEN_INT (no_type_class);
1497 }
1498
1499 /* This helper macro, meant to be used in mathfn_built_in below,
1500    determines which among a set of three builtin math functions is
1501    appropriate for a given type mode.  The `F' and `L' cases are
1502    automatically generated from the `double' case.  */
1503 #define CASE_MATHFN(BUILT_IN_MATHFN) \
1504   case BUILT_IN_MATHFN: case BUILT_IN_MATHFN##F: case BUILT_IN_MATHFN##L: \
1505   fcode = BUILT_IN_MATHFN; fcodef = BUILT_IN_MATHFN##F ; \
1506   fcodel = BUILT_IN_MATHFN##L ; break;
1507
1508 /* Return mathematic function equivalent to FN but operating directly
1509    on TYPE, if available.  If we can't do the conversion, return zero.  */
1510 tree
1511 mathfn_built_in (tree type, enum built_in_function fn)
1512 {
1513   enum built_in_function fcode, fcodef, fcodel;
1514
1515   switch (fn)
1516     {
1517       CASE_MATHFN (BUILT_IN_ACOS)
1518       CASE_MATHFN (BUILT_IN_ACOSH)
1519       CASE_MATHFN (BUILT_IN_ASIN)
1520       CASE_MATHFN (BUILT_IN_ASINH)
1521       CASE_MATHFN (BUILT_IN_ATAN)
1522       CASE_MATHFN (BUILT_IN_ATAN2)
1523       CASE_MATHFN (BUILT_IN_ATANH)
1524       CASE_MATHFN (BUILT_IN_CBRT)
1525       CASE_MATHFN (BUILT_IN_CEIL)
1526       CASE_MATHFN (BUILT_IN_COPYSIGN)
1527       CASE_MATHFN (BUILT_IN_COS)
1528       CASE_MATHFN (BUILT_IN_COSH)
1529       CASE_MATHFN (BUILT_IN_DREM)
1530       CASE_MATHFN (BUILT_IN_ERF)
1531       CASE_MATHFN (BUILT_IN_ERFC)
1532       CASE_MATHFN (BUILT_IN_EXP)
1533       CASE_MATHFN (BUILT_IN_EXP10)
1534       CASE_MATHFN (BUILT_IN_EXP2)
1535       CASE_MATHFN (BUILT_IN_EXPM1)
1536       CASE_MATHFN (BUILT_IN_FABS)
1537       CASE_MATHFN (BUILT_IN_FDIM)
1538       CASE_MATHFN (BUILT_IN_FLOOR)
1539       CASE_MATHFN (BUILT_IN_FMA)
1540       CASE_MATHFN (BUILT_IN_FMAX)
1541       CASE_MATHFN (BUILT_IN_FMIN)
1542       CASE_MATHFN (BUILT_IN_FMOD)
1543       CASE_MATHFN (BUILT_IN_FREXP)
1544       CASE_MATHFN (BUILT_IN_GAMMA)
1545       CASE_MATHFN (BUILT_IN_HUGE_VAL)
1546       CASE_MATHFN (BUILT_IN_HYPOT)
1547       CASE_MATHFN (BUILT_IN_ILOGB)
1548       CASE_MATHFN (BUILT_IN_INF)
1549       CASE_MATHFN (BUILT_IN_J0)
1550       CASE_MATHFN (BUILT_IN_J1)
1551       CASE_MATHFN (BUILT_IN_JN)
1552       CASE_MATHFN (BUILT_IN_LDEXP)
1553       CASE_MATHFN (BUILT_IN_LGAMMA)
1554       CASE_MATHFN (BUILT_IN_LLRINT)
1555       CASE_MATHFN (BUILT_IN_LLROUND)
1556       CASE_MATHFN (BUILT_IN_LOG)
1557       CASE_MATHFN (BUILT_IN_LOG10)
1558       CASE_MATHFN (BUILT_IN_LOG1P)
1559       CASE_MATHFN (BUILT_IN_LOG2)
1560       CASE_MATHFN (BUILT_IN_LOGB)
1561       CASE_MATHFN (BUILT_IN_LRINT)
1562       CASE_MATHFN (BUILT_IN_LROUND)
1563       CASE_MATHFN (BUILT_IN_MODF)
1564       CASE_MATHFN (BUILT_IN_NAN)
1565       CASE_MATHFN (BUILT_IN_NANS)
1566       CASE_MATHFN (BUILT_IN_NEARBYINT)
1567       CASE_MATHFN (BUILT_IN_NEXTAFTER)
1568       CASE_MATHFN (BUILT_IN_NEXTTOWARD)
1569       CASE_MATHFN (BUILT_IN_POW)
1570       CASE_MATHFN (BUILT_IN_POW10)
1571       CASE_MATHFN (BUILT_IN_REMAINDER)
1572       CASE_MATHFN (BUILT_IN_REMQUO)
1573       CASE_MATHFN (BUILT_IN_RINT)
1574       CASE_MATHFN (BUILT_IN_ROUND)
1575       CASE_MATHFN (BUILT_IN_SCALB)
1576       CASE_MATHFN (BUILT_IN_SCALBLN)
1577       CASE_MATHFN (BUILT_IN_SCALBN)
1578       CASE_MATHFN (BUILT_IN_SIGNIFICAND)
1579       CASE_MATHFN (BUILT_IN_SIN)
1580       CASE_MATHFN (BUILT_IN_SINCOS)
1581       CASE_MATHFN (BUILT_IN_SINH)
1582       CASE_MATHFN (BUILT_IN_SQRT)
1583       CASE_MATHFN (BUILT_IN_TAN)
1584       CASE_MATHFN (BUILT_IN_TANH)
1585       CASE_MATHFN (BUILT_IN_TGAMMA)
1586       CASE_MATHFN (BUILT_IN_TRUNC)
1587       CASE_MATHFN (BUILT_IN_Y0)
1588       CASE_MATHFN (BUILT_IN_Y1)
1589       CASE_MATHFN (BUILT_IN_YN)
1590
1591       default:
1592         return 0;
1593       }
1594
1595   if (TYPE_MAIN_VARIANT (type) == double_type_node)
1596     return implicit_built_in_decls[fcode];
1597   else if (TYPE_MAIN_VARIANT (type) == float_type_node)
1598     return implicit_built_in_decls[fcodef];
1599   else if (TYPE_MAIN_VARIANT (type) == long_double_type_node)
1600     return implicit_built_in_decls[fcodel];
1601   else
1602     return 0;
1603 }
1604
1605 /* If errno must be maintained, expand the RTL to check if the result,
1606    TARGET, of a built-in function call, EXP, is NaN, and if so set
1607    errno to EDOM.  */
1608
1609 static void
1610 expand_errno_check (tree exp, rtx target)
1611 {
1612   rtx lab = gen_label_rtx ();
1613
1614   /* Test the result; if it is NaN, set errno=EDOM because
1615      the argument was not in the domain.  */
1616   emit_cmp_and_jump_insns (target, target, EQ, 0, GET_MODE (target),
1617                            0, lab);
1618
1619 #ifdef TARGET_EDOM
1620   /* If this built-in doesn't throw an exception, set errno directly.  */
1621   if (TREE_NOTHROW (TREE_OPERAND (TREE_OPERAND (exp, 0), 0)))
1622     {
1623 #ifdef GEN_ERRNO_RTX
1624       rtx errno_rtx = GEN_ERRNO_RTX;
1625 #else
1626       rtx errno_rtx
1627           = gen_rtx_MEM (word_mode, gen_rtx_SYMBOL_REF (Pmode, "errno"));
1628 #endif
1629       emit_move_insn (errno_rtx, GEN_INT (TARGET_EDOM));
1630       emit_label (lab);
1631       return;
1632     }
1633 #endif
1634
1635   /* We can't set errno=EDOM directly; let the library call do it.
1636      Pop the arguments right away in case the call gets deleted.  */
1637   NO_DEFER_POP;
1638   expand_call (exp, target, 0);
1639   OK_DEFER_POP;
1640   emit_label (lab);
1641 }
1642
1643
1644 /* Expand a call to one of the builtin math functions (sqrt, exp, or log).
1645    Return 0 if a normal call should be emitted rather than expanding the
1646    function in-line.  EXP is the expression that is a call to the builtin
1647    function; if convenient, the result should be placed in TARGET.
1648    SUBTARGET may be used as the target for computing one of EXP's operands.  */
1649
1650 static rtx
1651 expand_builtin_mathfn (tree exp, rtx target, rtx subtarget)
1652 {
1653   optab builtin_optab;
1654   rtx op0, insns, before_call;
1655   tree fndecl = get_callee_fndecl (exp);
1656   tree arglist = TREE_OPERAND (exp, 1);
1657   enum machine_mode mode;
1658   bool errno_set = false;
1659   tree arg, narg;
1660
1661   if (!validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
1662     return 0;
1663
1664   arg = TREE_VALUE (arglist);
1665
1666   switch (DECL_FUNCTION_CODE (fndecl))
1667     {
1668     case BUILT_IN_SQRT:
1669     case BUILT_IN_SQRTF:
1670     case BUILT_IN_SQRTL:
1671       errno_set = ! tree_expr_nonnegative_p (arg);
1672       builtin_optab = sqrt_optab;
1673       break;
1674     case BUILT_IN_EXP:
1675     case BUILT_IN_EXPF:
1676     case BUILT_IN_EXPL:
1677       errno_set = true; builtin_optab = exp_optab; break;
1678     case BUILT_IN_EXP10:
1679     case BUILT_IN_EXP10F:
1680     case BUILT_IN_EXP10L:
1681     case BUILT_IN_POW10:
1682     case BUILT_IN_POW10F:
1683     case BUILT_IN_POW10L:
1684       errno_set = true; builtin_optab = exp10_optab; break;
1685     case BUILT_IN_EXP2:
1686     case BUILT_IN_EXP2F:
1687     case BUILT_IN_EXP2L:
1688       errno_set = true; builtin_optab = exp2_optab; break;
1689     case BUILT_IN_EXPM1:
1690     case BUILT_IN_EXPM1F:
1691     case BUILT_IN_EXPM1L:
1692       errno_set = true; builtin_optab = expm1_optab; break;
1693     case BUILT_IN_LOGB:
1694     case BUILT_IN_LOGBF:
1695     case BUILT_IN_LOGBL:
1696       errno_set = true; builtin_optab = logb_optab; break;
1697     case BUILT_IN_ILOGB:
1698     case BUILT_IN_ILOGBF:
1699     case BUILT_IN_ILOGBL:
1700       errno_set = true; builtin_optab = ilogb_optab; break;
1701     case BUILT_IN_LOG:
1702     case BUILT_IN_LOGF:
1703     case BUILT_IN_LOGL:
1704       errno_set = true; builtin_optab = log_optab; break;
1705     case BUILT_IN_LOG10:
1706     case BUILT_IN_LOG10F:
1707     case BUILT_IN_LOG10L:
1708       errno_set = true; builtin_optab = log10_optab; break;
1709     case BUILT_IN_LOG2:
1710     case BUILT_IN_LOG2F:
1711     case BUILT_IN_LOG2L:
1712       errno_set = true; builtin_optab = log2_optab; break;
1713     case BUILT_IN_LOG1P:
1714     case BUILT_IN_LOG1PF:
1715     case BUILT_IN_LOG1PL:
1716       errno_set = true; builtin_optab = log1p_optab; break;
1717     case BUILT_IN_ASIN:
1718     case BUILT_IN_ASINF:
1719     case BUILT_IN_ASINL:
1720       builtin_optab = asin_optab; break;
1721     case BUILT_IN_ACOS:
1722     case BUILT_IN_ACOSF:
1723     case BUILT_IN_ACOSL:
1724       builtin_optab = acos_optab; break;
1725     case BUILT_IN_TAN:
1726     case BUILT_IN_TANF:
1727     case BUILT_IN_TANL:
1728       builtin_optab = tan_optab; break;
1729     case BUILT_IN_ATAN:
1730     case BUILT_IN_ATANF:
1731     case BUILT_IN_ATANL:
1732       builtin_optab = atan_optab; break;
1733     case BUILT_IN_FLOOR:
1734     case BUILT_IN_FLOORF:
1735     case BUILT_IN_FLOORL:
1736       builtin_optab = floor_optab; break;
1737     case BUILT_IN_CEIL:
1738     case BUILT_IN_CEILF:
1739     case BUILT_IN_CEILL:
1740       builtin_optab = ceil_optab; break;
1741     case BUILT_IN_TRUNC:
1742     case BUILT_IN_TRUNCF:
1743     case BUILT_IN_TRUNCL:
1744       builtin_optab = btrunc_optab; break;
1745     case BUILT_IN_ROUND:
1746     case BUILT_IN_ROUNDF:
1747     case BUILT_IN_ROUNDL:
1748       builtin_optab = round_optab; break;
1749     case BUILT_IN_NEARBYINT:
1750     case BUILT_IN_NEARBYINTF:
1751     case BUILT_IN_NEARBYINTL:
1752       builtin_optab = nearbyint_optab; break;
1753     case BUILT_IN_RINT:
1754     case BUILT_IN_RINTF:
1755     case BUILT_IN_RINTL:
1756       builtin_optab = rint_optab; break;
1757     default:
1758       gcc_unreachable ();
1759     }
1760
1761   /* Make a suitable register to place result in.  */
1762   mode = TYPE_MODE (TREE_TYPE (exp));
1763
1764   if (! flag_errno_math || ! HONOR_NANS (mode))
1765     errno_set = false;
1766
1767   /* Before working hard, check whether the instruction is available.  */
1768   if (builtin_optab->handlers[(int) mode].insn_code != CODE_FOR_nothing)
1769     {
1770       target = gen_reg_rtx (mode);
1771
1772       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
1773          need to expand the argument again.  This way, we will not perform
1774          side-effects more the once.  */
1775       narg = builtin_save_expr (arg);
1776       if (narg != arg)
1777         {
1778           arglist = build_tree_list (NULL_TREE, arg);
1779           exp = build_function_call_expr (fndecl, arglist);
1780         }
1781
1782       op0 = expand_expr (arg, subtarget, VOIDmode, 0);
1783
1784       start_sequence ();
1785
1786       /* Compute into TARGET.
1787          Set TARGET to wherever the result comes back.  */
1788       target = expand_unop (mode, builtin_optab, op0, target, 0);
1789
1790       if (target != 0)
1791         {
1792           if (errno_set)
1793             expand_errno_check (exp, target);
1794
1795           /* Output the entire sequence.  */
1796           insns = get_insns ();
1797           end_sequence ();
1798           emit_insn (insns);
1799           return target;
1800         }
1801
1802       /* If we were unable to expand via the builtin, stop the sequence
1803          (without outputting the insns) and call to the library function
1804          with the stabilized argument list.  */
1805       end_sequence ();
1806     }
1807
1808   before_call = get_last_insn ();
1809
1810   target = expand_call (exp, target, target == const0_rtx);
1811
1812   /* If this is a sqrt operation and we don't care about errno, try to
1813      attach a REG_EQUAL note with a SQRT rtx to the emitted libcall.
1814      This allows the semantics of the libcall to be visible to the RTL
1815      optimizers.  */
1816   if (builtin_optab == sqrt_optab && !errno_set)
1817     {
1818       /* Search backwards through the insns emitted by expand_call looking
1819          for the instruction with the REG_RETVAL note.  */
1820       rtx last = get_last_insn ();
1821       while (last != before_call)
1822         {
1823           if (find_reg_note (last, REG_RETVAL, NULL))
1824             {
1825               rtx note = find_reg_note (last, REG_EQUAL, NULL);
1826               /* Check that the REQ_EQUAL note is an EXPR_LIST with
1827                  two elements, i.e. symbol_ref(sqrt) and the operand.  */
1828               if (note
1829                   && GET_CODE (note) == EXPR_LIST
1830                   && GET_CODE (XEXP (note, 0)) == EXPR_LIST
1831                   && XEXP (XEXP (note, 0), 1) != NULL_RTX
1832                   && XEXP (XEXP (XEXP (note, 0), 1), 1) == NULL_RTX)
1833                 {
1834                   rtx operand = XEXP (XEXP (XEXP (note, 0), 1), 0);
1835                   /* Check operand is a register with expected mode.  */
1836                   if (operand
1837                       && REG_P (operand)
1838                       && GET_MODE (operand) == mode)
1839                     {
1840                       /* Replace the REG_EQUAL note with a SQRT rtx.  */
1841                       rtx equiv = gen_rtx_SQRT (mode, operand);
1842                       set_unique_reg_note (last, REG_EQUAL, equiv);
1843                     }
1844                 }
1845               break;
1846             }
1847           last = PREV_INSN (last);
1848         }
1849     }
1850
1851   return target;
1852 }
1853
1854 /* Expand a call to the builtin binary math functions (pow and atan2).
1855    Return 0 if a normal call should be emitted rather than expanding the
1856    function in-line.  EXP is the expression that is a call to the builtin
1857    function; if convenient, the result should be placed in TARGET.
1858    SUBTARGET may be used as the target for computing one of EXP's
1859    operands.  */
1860
1861 static rtx
1862 expand_builtin_mathfn_2 (tree exp, rtx target, rtx subtarget)
1863 {
1864   optab builtin_optab;
1865   rtx op0, op1, insns;
1866   tree fndecl = get_callee_fndecl (exp);
1867   tree arglist = TREE_OPERAND (exp, 1);
1868   tree arg0, arg1, temp, narg;
1869   enum machine_mode mode;
1870   bool errno_set = true;
1871   bool stable = true;
1872
1873   if (!validate_arglist (arglist, REAL_TYPE, REAL_TYPE, VOID_TYPE))
1874     return 0;
1875
1876   arg0 = TREE_VALUE (arglist);
1877   arg1 = TREE_VALUE (TREE_CHAIN (arglist));
1878
1879   switch (DECL_FUNCTION_CODE (fndecl))
1880     {
1881     case BUILT_IN_POW:
1882     case BUILT_IN_POWF:
1883     case BUILT_IN_POWL:
1884       builtin_optab = pow_optab; break;
1885     case BUILT_IN_ATAN2:
1886     case BUILT_IN_ATAN2F:
1887     case BUILT_IN_ATAN2L:
1888       builtin_optab = atan2_optab; break;
1889     case BUILT_IN_FMOD:
1890     case BUILT_IN_FMODF:
1891     case BUILT_IN_FMODL:
1892       builtin_optab = fmod_optab; break;
1893     case BUILT_IN_DREM:
1894     case BUILT_IN_DREMF:
1895     case BUILT_IN_DREML:
1896       builtin_optab = drem_optab; break;
1897     default:
1898       gcc_unreachable ();
1899     }
1900
1901   /* Make a suitable register to place result in.  */
1902   mode = TYPE_MODE (TREE_TYPE (exp));
1903
1904   /* Before working hard, check whether the instruction is available.  */
1905   if (builtin_optab->handlers[(int) mode].insn_code == CODE_FOR_nothing)
1906     return 0;
1907
1908   target = gen_reg_rtx (mode);
1909
1910   if (! flag_errno_math || ! HONOR_NANS (mode))
1911     errno_set = false;
1912
1913   /* Always stabilize the argument list.  */
1914   narg = builtin_save_expr (arg1);
1915   if (narg != arg1)
1916     {
1917       temp = build_tree_list (NULL_TREE, narg);
1918       stable = false;
1919     }
1920   else
1921     temp = TREE_CHAIN (arglist);
1922
1923   narg = builtin_save_expr (arg0);
1924   if (narg != arg0)
1925     {
1926       arglist = tree_cons (NULL_TREE, narg, temp);
1927       stable = false;
1928     }
1929   else if (! stable)
1930     arglist = tree_cons (NULL_TREE, arg0, temp);
1931
1932   if (! stable)
1933     exp = build_function_call_expr (fndecl, arglist);
1934
1935   op0 = expand_expr (arg0, subtarget, VOIDmode, 0);
1936   op1 = expand_expr (arg1, 0, VOIDmode, 0);
1937
1938   start_sequence ();
1939
1940   /* Compute into TARGET.
1941      Set TARGET to wherever the result comes back.  */
1942   target = expand_binop (mode, builtin_optab, op0, op1,
1943                          target, 0, OPTAB_DIRECT);
1944
1945   /* If we were unable to expand via the builtin, stop the sequence
1946      (without outputting the insns) and call to the library function
1947      with the stabilized argument list.  */
1948   if (target == 0)
1949     {
1950       end_sequence ();
1951       return expand_call (exp, target, target == const0_rtx);
1952     }
1953
1954   if (errno_set)
1955     expand_errno_check (exp, target);
1956
1957   /* Output the entire sequence.  */
1958   insns = get_insns ();
1959   end_sequence ();
1960   emit_insn (insns);
1961
1962   return target;
1963 }
1964
1965 /* Expand a call to the builtin sin and cos math functions.
1966    Return 0 if a normal call should be emitted rather than expanding the
1967    function in-line.  EXP is the expression that is a call to the builtin
1968    function; if convenient, the result should be placed in TARGET.
1969    SUBTARGET may be used as the target for computing one of EXP's
1970    operands.  */
1971
1972 static rtx
1973 expand_builtin_mathfn_3 (tree exp, rtx target, rtx subtarget)
1974 {
1975   optab builtin_optab;
1976   rtx op0, insns, before_call;
1977   tree fndecl = get_callee_fndecl (exp);
1978   tree arglist = TREE_OPERAND (exp, 1);
1979   enum machine_mode mode;
1980   bool errno_set = false;
1981   tree arg, narg;
1982
1983   if (!validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
1984     return 0;
1985
1986   arg = TREE_VALUE (arglist);
1987
1988   switch (DECL_FUNCTION_CODE (fndecl))
1989     {
1990     case BUILT_IN_SIN:
1991     case BUILT_IN_SINF:
1992     case BUILT_IN_SINL:
1993     case BUILT_IN_COS:
1994     case BUILT_IN_COSF:
1995     case BUILT_IN_COSL:
1996       builtin_optab = sincos_optab; break;
1997     default:
1998       gcc_unreachable ();
1999     }
2000
2001   /* Make a suitable register to place result in.  */
2002   mode = TYPE_MODE (TREE_TYPE (exp));
2003
2004   if (! flag_errno_math || ! HONOR_NANS (mode))
2005     errno_set = false;
2006
2007   /* Check if sincos insn is available, otherwise fallback
2008      to sin or cos insn.  */
2009   if (builtin_optab->handlers[(int) mode].insn_code == CODE_FOR_nothing) {
2010     switch (DECL_FUNCTION_CODE (fndecl))
2011       {
2012       case BUILT_IN_SIN:
2013       case BUILT_IN_SINF:
2014       case BUILT_IN_SINL:
2015         builtin_optab = sin_optab; break;
2016       case BUILT_IN_COS:
2017       case BUILT_IN_COSF:
2018       case BUILT_IN_COSL:
2019         builtin_optab = cos_optab; break;
2020       default:
2021         gcc_unreachable ();
2022       }
2023   }
2024
2025   /* Before working hard, check whether the instruction is available.  */
2026   if (builtin_optab->handlers[(int) mode].insn_code != CODE_FOR_nothing)
2027     {
2028       target = gen_reg_rtx (mode);
2029
2030       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2031          need to expand the argument again.  This way, we will not perform
2032          side-effects more the once.  */
2033       narg = save_expr (arg);
2034       if (narg != arg)
2035         {
2036           arglist = build_tree_list (NULL_TREE, arg);
2037           exp = build_function_call_expr (fndecl, arglist);
2038         }
2039
2040       op0 = expand_expr (arg, subtarget, VOIDmode, 0);
2041
2042       start_sequence ();
2043
2044       /* Compute into TARGET.
2045          Set TARGET to wherever the result comes back.  */
2046       if (builtin_optab == sincos_optab)
2047         {
2048           int result;
2049
2050           switch (DECL_FUNCTION_CODE (fndecl))
2051             {
2052             case BUILT_IN_SIN:
2053             case BUILT_IN_SINF:
2054             case BUILT_IN_SINL:
2055               result = expand_twoval_unop (builtin_optab, op0, 0, target, 0);
2056               break;
2057             case BUILT_IN_COS:
2058             case BUILT_IN_COSF:
2059             case BUILT_IN_COSL:
2060               result = expand_twoval_unop (builtin_optab, op0, target, 0, 0);
2061               break;
2062             default:
2063               gcc_unreachable ();
2064             }
2065           gcc_assert (result);
2066         }
2067       else
2068         {
2069           target = expand_unop (mode, builtin_optab, op0, target, 0);
2070         }
2071
2072       if (target != 0)
2073         {
2074           if (errno_set)
2075             expand_errno_check (exp, target);
2076
2077           /* Output the entire sequence.  */
2078           insns = get_insns ();
2079           end_sequence ();
2080           emit_insn (insns);
2081           return target;
2082         }
2083
2084       /* If we were unable to expand via the builtin, stop the sequence
2085          (without outputting the insns) and call to the library function
2086          with the stabilized argument list.  */
2087       end_sequence ();
2088     }
2089
2090   before_call = get_last_insn ();
2091
2092   target = expand_call (exp, target, target == const0_rtx);
2093
2094   return target;
2095 }
2096
2097 /* To evaluate powi(x,n), the floating point value x raised to the
2098    constant integer exponent n, we use a hybrid algorithm that
2099    combines the "window method" with look-up tables.  For an
2100    introduction to exponentiation algorithms and "addition chains",
2101    see section 4.6.3, "Evaluation of Powers" of Donald E. Knuth,
2102    "Seminumerical Algorithms", Vol. 2, "The Art of Computer Programming",
2103    3rd Edition, 1998, and Daniel M. Gordon, "A Survey of Fast Exponentiation
2104    Methods", Journal of Algorithms, Vol. 27, pp. 129-146, 1998.  */
2105
2106 /* Provide a default value for POWI_MAX_MULTS, the maximum number of
2107    multiplications to inline before calling the system library's pow
2108    function.  powi(x,n) requires at worst 2*bits(n)-2 multiplications,
2109    so this default never requires calling pow, powf or powl.  */
2110
2111 #ifndef POWI_MAX_MULTS
2112 #define POWI_MAX_MULTS  (2*HOST_BITS_PER_WIDE_INT-2)
2113 #endif
2114
2115 /* The size of the "optimal power tree" lookup table.  All
2116    exponents less than this value are simply looked up in the
2117    powi_table below.  This threshold is also used to size the
2118    cache of pseudo registers that hold intermediate results.  */
2119 #define POWI_TABLE_SIZE 256
2120
2121 /* The size, in bits of the window, used in the "window method"
2122    exponentiation algorithm.  This is equivalent to a radix of
2123    (1<<POWI_WINDOW_SIZE) in the corresponding "m-ary method".  */
2124 #define POWI_WINDOW_SIZE 3
2125
2126 /* The following table is an efficient representation of an
2127    "optimal power tree".  For each value, i, the corresponding
2128    value, j, in the table states than an optimal evaluation
2129    sequence for calculating pow(x,i) can be found by evaluating
2130    pow(x,j)*pow(x,i-j).  An optimal power tree for the first
2131    100 integers is given in Knuth's "Seminumerical algorithms".  */
2132
2133 static const unsigned char powi_table[POWI_TABLE_SIZE] =
2134   {
2135       0,   1,   1,   2,   2,   3,   3,   4,  /*   0 -   7 */
2136       4,   6,   5,   6,   6,  10,   7,   9,  /*   8 -  15 */
2137       8,  16,   9,  16,  10,  12,  11,  13,  /*  16 -  23 */
2138      12,  17,  13,  18,  14,  24,  15,  26,  /*  24 -  31 */
2139      16,  17,  17,  19,  18,  33,  19,  26,  /*  32 -  39 */
2140      20,  25,  21,  40,  22,  27,  23,  44,  /*  40 -  47 */
2141      24,  32,  25,  34,  26,  29,  27,  44,  /*  48 -  55 */
2142      28,  31,  29,  34,  30,  60,  31,  36,  /*  56 -  63 */
2143      32,  64,  33,  34,  34,  46,  35,  37,  /*  64 -  71 */
2144      36,  65,  37,  50,  38,  48,  39,  69,  /*  72 -  79 */
2145      40,  49,  41,  43,  42,  51,  43,  58,  /*  80 -  87 */
2146      44,  64,  45,  47,  46,  59,  47,  76,  /*  88 -  95 */
2147      48,  65,  49,  66,  50,  67,  51,  66,  /*  96 - 103 */
2148      52,  70,  53,  74,  54, 104,  55,  74,  /* 104 - 111 */
2149      56,  64,  57,  69,  58,  78,  59,  68,  /* 112 - 119 */
2150      60,  61,  61,  80,  62,  75,  63,  68,  /* 120 - 127 */
2151      64,  65,  65, 128,  66, 129,  67,  90,  /* 128 - 135 */
2152      68,  73,  69, 131,  70,  94,  71,  88,  /* 136 - 143 */
2153      72, 128,  73,  98,  74, 132,  75, 121,  /* 144 - 151 */
2154      76, 102,  77, 124,  78, 132,  79, 106,  /* 152 - 159 */
2155      80,  97,  81, 160,  82,  99,  83, 134,  /* 160 - 167 */
2156      84,  86,  85,  95,  86, 160,  87, 100,  /* 168 - 175 */
2157      88, 113,  89,  98,  90, 107,  91, 122,  /* 176 - 183 */
2158      92, 111,  93, 102,  94, 126,  95, 150,  /* 184 - 191 */
2159      96, 128,  97, 130,  98, 133,  99, 195,  /* 192 - 199 */
2160     100, 128, 101, 123, 102, 164, 103, 138,  /* 200 - 207 */
2161     104, 145, 105, 146, 106, 109, 107, 149,  /* 208 - 215 */
2162     108, 200, 109, 146, 110, 170, 111, 157,  /* 216 - 223 */
2163     112, 128, 113, 130, 114, 182, 115, 132,  /* 224 - 231 */
2164     116, 200, 117, 132, 118, 158, 119, 206,  /* 232 - 239 */
2165     120, 240, 121, 162, 122, 147, 123, 152,  /* 240 - 247 */
2166     124, 166, 125, 214, 126, 138, 127, 153,  /* 248 - 255 */
2167   };
2168
2169
2170 /* Return the number of multiplications required to calculate
2171    powi(x,n) where n is less than POWI_TABLE_SIZE.  This is a
2172    subroutine of powi_cost.  CACHE is an array indicating
2173    which exponents have already been calculated.  */
2174
2175 static int
2176 powi_lookup_cost (unsigned HOST_WIDE_INT n, bool *cache)
2177 {
2178   /* If we've already calculated this exponent, then this evaluation
2179      doesn't require any additional multiplications.  */
2180   if (cache[n])
2181     return 0;
2182
2183   cache[n] = true;
2184   return powi_lookup_cost (n - powi_table[n], cache)
2185          + powi_lookup_cost (powi_table[n], cache) + 1;
2186 }
2187
2188 /* Return the number of multiplications required to calculate
2189    powi(x,n) for an arbitrary x, given the exponent N.  This
2190    function needs to be kept in sync with expand_powi below.  */
2191
2192 static int
2193 powi_cost (HOST_WIDE_INT n)
2194 {
2195   bool cache[POWI_TABLE_SIZE];
2196   unsigned HOST_WIDE_INT digit;
2197   unsigned HOST_WIDE_INT val;
2198   int result;
2199
2200   if (n == 0)
2201     return 0;
2202
2203   /* Ignore the reciprocal when calculating the cost.  */
2204   val = (n < 0) ? -n : n;
2205
2206   /* Initialize the exponent cache.  */
2207   memset (cache, 0, POWI_TABLE_SIZE * sizeof (bool));
2208   cache[1] = true;
2209
2210   result = 0;
2211
2212   while (val >= POWI_TABLE_SIZE)
2213     {
2214       if (val & 1)
2215         {
2216           digit = val & ((1 << POWI_WINDOW_SIZE) - 1);
2217           result += powi_lookup_cost (digit, cache)
2218                     + POWI_WINDOW_SIZE + 1;
2219           val >>= POWI_WINDOW_SIZE;
2220         }
2221       else
2222         {
2223           val >>= 1;
2224           result++;
2225         }
2226     }
2227
2228   return result + powi_lookup_cost (val, cache);
2229 }
2230
2231 /* Recursive subroutine of expand_powi.  This function takes the array,
2232    CACHE, of already calculated exponents and an exponent N and returns
2233    an RTX that corresponds to CACHE[1]**N, as calculated in mode MODE.  */
2234
2235 static rtx
2236 expand_powi_1 (enum machine_mode mode, unsigned HOST_WIDE_INT n, rtx *cache)
2237 {
2238   unsigned HOST_WIDE_INT digit;
2239   rtx target, result;
2240   rtx op0, op1;
2241
2242   if (n < POWI_TABLE_SIZE)
2243     {
2244       if (cache[n])
2245         return cache[n];
2246
2247       target = gen_reg_rtx (mode);
2248       cache[n] = target;
2249
2250       op0 = expand_powi_1 (mode, n - powi_table[n], cache);
2251       op1 = expand_powi_1 (mode, powi_table[n], cache);
2252     }
2253   else if (n & 1)
2254     {
2255       target = gen_reg_rtx (mode);
2256       digit = n & ((1 << POWI_WINDOW_SIZE) - 1);
2257       op0 = expand_powi_1 (mode, n - digit, cache);
2258       op1 = expand_powi_1 (mode, digit, cache);
2259     }
2260   else
2261     {
2262       target = gen_reg_rtx (mode);
2263       op0 = expand_powi_1 (mode, n >> 1, cache);
2264       op1 = op0;
2265     }
2266
2267   result = expand_mult (mode, op0, op1, target, 0);
2268   if (result != target)
2269     emit_move_insn (target, result);
2270   return target;
2271 }
2272
2273 /* Expand the RTL to evaluate powi(x,n) in mode MODE.  X is the
2274    floating point operand in mode MODE, and N is the exponent.  This
2275    function needs to be kept in sync with powi_cost above.  */
2276
2277 static rtx
2278 expand_powi (rtx x, enum machine_mode mode, HOST_WIDE_INT n)
2279 {
2280   unsigned HOST_WIDE_INT val;
2281   rtx cache[POWI_TABLE_SIZE];
2282   rtx result;
2283
2284   if (n == 0)
2285     return CONST1_RTX (mode);
2286
2287   val = (n < 0) ? -n : n;
2288
2289   memset (cache, 0, sizeof (cache));
2290   cache[1] = x;
2291
2292   result = expand_powi_1 (mode, (n < 0) ? -n : n, cache);
2293
2294   /* If the original exponent was negative, reciprocate the result.  */
2295   if (n < 0)
2296     result = expand_binop (mode, sdiv_optab, CONST1_RTX (mode),
2297                            result, NULL_RTX, 0, OPTAB_LIB_WIDEN);
2298
2299   return result;
2300 }
2301
2302 /* Expand a call to the pow built-in mathematical function.  Return 0 if
2303    a normal call should be emitted rather than expanding the function
2304    in-line.  EXP is the expression that is a call to the builtin
2305    function; if convenient, the result should be placed in TARGET.  */
2306
2307 static rtx
2308 expand_builtin_pow (tree exp, rtx target, rtx subtarget)
2309 {
2310   tree arglist = TREE_OPERAND (exp, 1);
2311   tree arg0, arg1;
2312
2313   if (! validate_arglist (arglist, REAL_TYPE, REAL_TYPE, VOID_TYPE))
2314     return 0;
2315
2316   arg0 = TREE_VALUE (arglist);
2317   arg1 = TREE_VALUE (TREE_CHAIN (arglist));
2318
2319   if (TREE_CODE (arg1) == REAL_CST
2320       && ! TREE_CONSTANT_OVERFLOW (arg1))
2321     {
2322       REAL_VALUE_TYPE cint;
2323       REAL_VALUE_TYPE c;
2324       HOST_WIDE_INT n;
2325
2326       c = TREE_REAL_CST (arg1);
2327       n = real_to_integer (&c);
2328       real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
2329       if (real_identical (&c, &cint))
2330         {
2331           /* If the exponent is -1, 0, 1 or 2, then expand_powi is exact.
2332              Otherwise, check the number of multiplications required.
2333              Note that pow never sets errno for an integer exponent.  */
2334           if ((n >= -1 && n <= 2)
2335               || (flag_unsafe_math_optimizations
2336                   && ! optimize_size
2337                   && powi_cost (n) <= POWI_MAX_MULTS))
2338             {
2339               enum machine_mode mode = TYPE_MODE (TREE_TYPE (exp));
2340               rtx op = expand_expr (arg0, subtarget, VOIDmode, 0);
2341               op = force_reg (mode, op);
2342               return expand_powi (op, mode, n);
2343             }
2344         }
2345     }
2346
2347   if (! flag_unsafe_math_optimizations)
2348     return NULL_RTX;
2349   return expand_builtin_mathfn_2 (exp, target, subtarget);
2350 }
2351
2352 /* Expand expression EXP which is a call to the strlen builtin.  Return 0
2353    if we failed the caller should emit a normal call, otherwise
2354    try to get the result in TARGET, if convenient.  */
2355
2356 static rtx
2357 expand_builtin_strlen (tree arglist, rtx target,
2358                        enum machine_mode target_mode)
2359 {
2360   if (!validate_arglist (arglist, POINTER_TYPE, VOID_TYPE))
2361     return 0;
2362   else
2363     {
2364       rtx pat;
2365       tree len, src = TREE_VALUE (arglist);
2366       rtx result, src_reg, char_rtx, before_strlen;
2367       enum machine_mode insn_mode = target_mode, char_mode;
2368       enum insn_code icode = CODE_FOR_nothing;
2369       int align;
2370
2371       /* If the length can be computed at compile-time, return it.  */
2372       len = c_strlen (src, 0);
2373       if (len)
2374         return expand_expr (len, target, target_mode, EXPAND_NORMAL);
2375
2376       /* If the length can be computed at compile-time and is constant
2377          integer, but there are side-effects in src, evaluate
2378          src for side-effects, then return len.
2379          E.g. x = strlen (i++ ? "xfoo" + 1 : "bar");
2380          can be optimized into: i++; x = 3;  */
2381       len = c_strlen (src, 1);
2382       if (len && TREE_CODE (len) == INTEGER_CST)
2383         {
2384           expand_expr (src, const0_rtx, VOIDmode, EXPAND_NORMAL);
2385           return expand_expr (len, target, target_mode, EXPAND_NORMAL);
2386         }
2387
2388       align = get_pointer_alignment (src, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
2389
2390       /* If SRC is not a pointer type, don't do this operation inline.  */
2391       if (align == 0)
2392         return 0;
2393
2394       /* Bail out if we can't compute strlen in the right mode.  */
2395       while (insn_mode != VOIDmode)
2396         {
2397           icode = strlen_optab->handlers[(int) insn_mode].insn_code;
2398           if (icode != CODE_FOR_nothing)
2399             break;
2400
2401           insn_mode = GET_MODE_WIDER_MODE (insn_mode);
2402         }
2403       if (insn_mode == VOIDmode)
2404         return 0;
2405
2406       /* Make a place to write the result of the instruction.  */
2407       result = target;
2408       if (! (result != 0
2409              && REG_P (result)
2410              && GET_MODE (result) == insn_mode
2411              && REGNO (result) >= FIRST_PSEUDO_REGISTER))
2412         result = gen_reg_rtx (insn_mode);
2413
2414       /* Make a place to hold the source address.  We will not expand
2415          the actual source until we are sure that the expansion will
2416          not fail -- there are trees that cannot be expanded twice.  */
2417       src_reg = gen_reg_rtx (Pmode);
2418
2419       /* Mark the beginning of the strlen sequence so we can emit the
2420          source operand later.  */
2421       before_strlen = get_last_insn ();
2422
2423       char_rtx = const0_rtx;
2424       char_mode = insn_data[(int) icode].operand[2].mode;
2425       if (! (*insn_data[(int) icode].operand[2].predicate) (char_rtx,
2426                                                             char_mode))
2427         char_rtx = copy_to_mode_reg (char_mode, char_rtx);
2428
2429       pat = GEN_FCN (icode) (result, gen_rtx_MEM (BLKmode, src_reg),
2430                              char_rtx, GEN_INT (align));
2431       if (! pat)
2432         return 0;
2433       emit_insn (pat);
2434
2435       /* Now that we are assured of success, expand the source.  */
2436       start_sequence ();
2437       pat = expand_expr (src, src_reg, ptr_mode, EXPAND_NORMAL);
2438       if (pat != src_reg)
2439         emit_move_insn (src_reg, pat);
2440       pat = get_insns ();
2441       end_sequence ();
2442
2443       if (before_strlen)
2444         emit_insn_after (pat, before_strlen);
2445       else
2446         emit_insn_before (pat, get_insns ());
2447
2448       /* Return the value in the proper mode for this function.  */
2449       if (GET_MODE (result) == target_mode)
2450         target = result;
2451       else if (target != 0)
2452         convert_move (target, result, 0);
2453       else
2454         target = convert_to_mode (target_mode, result, 0);
2455
2456       return target;
2457     }
2458 }
2459
2460 /* Expand a call to the strstr builtin.  Return 0 if we failed the
2461    caller should emit a normal call, otherwise try to get the result
2462    in TARGET, if convenient (and in mode MODE if that's convenient).  */
2463
2464 static rtx
2465 expand_builtin_strstr (tree arglist, rtx target, enum machine_mode mode)
2466 {
2467   if (validate_arglist (arglist, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
2468     {
2469       tree result = fold_builtin_strstr (arglist);
2470       if (result)
2471         return expand_expr (result, target, mode, EXPAND_NORMAL);
2472     }
2473   return 0;
2474 }
2475
2476 /* Expand a call to the strchr builtin.  Return 0 if we failed the
2477    caller should emit a normal call, otherwise try to get the result
2478    in TARGET, if convenient (and in mode MODE if that's convenient).  */
2479
2480 static rtx
2481 expand_builtin_strchr (tree arglist, rtx target, enum machine_mode mode)
2482 {
2483   if (validate_arglist (arglist, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
2484     {
2485       tree result = fold_builtin_strchr (arglist);
2486       if (result)
2487         return expand_expr (result, target, mode, EXPAND_NORMAL);
2488
2489       /* FIXME: Should use strchrM optab so that ports can optimize this.  */
2490     }
2491   return 0;
2492 }
2493
2494 /* Expand a call to the strrchr builtin.  Return 0 if we failed the
2495    caller should emit a normal call, otherwise try to get the result
2496    in TARGET, if convenient (and in mode MODE if that's convenient).  */
2497
2498 static rtx
2499 expand_builtin_strrchr (tree arglist, rtx target, enum machine_mode mode)
2500 {
2501   if (validate_arglist (arglist, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
2502     {
2503       tree result = fold_builtin_strrchr (arglist);
2504       if (result)
2505         return expand_expr (result, target, mode, EXPAND_NORMAL);
2506     }
2507   return 0;
2508 }
2509
2510 /* Expand a call to the strpbrk builtin.  Return 0 if we failed the
2511    caller should emit a normal call, otherwise try to get the result
2512    in TARGET, if convenient (and in mode MODE if that's convenient).  */
2513
2514 static rtx
2515 expand_builtin_strpbrk (tree arglist, rtx target, enum machine_mode mode)
2516 {
2517   if (validate_arglist (arglist, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
2518     {
2519       tree result = fold_builtin_strpbrk (arglist);
2520       if (result)
2521         return expand_expr (result, target, mode, EXPAND_NORMAL);
2522     }
2523   return 0;
2524 }
2525
2526 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
2527    bytes from constant string DATA + OFFSET and return it as target
2528    constant.  */
2529
2530 static rtx
2531 builtin_memcpy_read_str (void *data, HOST_WIDE_INT offset,
2532                          enum machine_mode mode)
2533 {
2534   const char *str = (const char *) data;
2535
2536   gcc_assert (offset >= 0
2537               && ((unsigned HOST_WIDE_INT) offset + GET_MODE_SIZE (mode)
2538                   <= strlen (str) + 1));
2539
2540   return c_readstr (str + offset, mode);
2541 }
2542
2543 /* Expand a call to the memcpy builtin, with arguments in ARGLIST.
2544    Return 0 if we failed, the caller should emit a normal call,
2545    otherwise try to get the result in TARGET, if convenient (and in
2546    mode MODE if that's convenient).  */
2547 static rtx
2548 expand_builtin_memcpy (tree exp, rtx target, enum machine_mode mode)
2549 {
2550   tree arglist = TREE_OPERAND (exp, 1);
2551   if (!validate_arglist (arglist,
2552                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
2553     return 0;
2554   else
2555     {
2556       tree dest = TREE_VALUE (arglist);
2557       tree src = TREE_VALUE (TREE_CHAIN (arglist));
2558       tree len = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (arglist)));
2559       const char *src_str;
2560       unsigned int src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
2561       unsigned int dest_align
2562         = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
2563       rtx dest_mem, src_mem, dest_addr, len_rtx;
2564       tree result = fold_builtin_memcpy (exp);
2565
2566       if (result)
2567         return expand_expr (result, target, mode, EXPAND_NORMAL);
2568
2569       /* If DEST is not a pointer type, call the normal function.  */
2570       if (dest_align == 0)
2571         return 0;
2572
2573       /* If either SRC is not a pointer type, don't do this
2574          operation in-line.  */
2575       if (src_align == 0)
2576         return 0;
2577
2578       dest_mem = get_memory_rtx (dest);
2579       set_mem_align (dest_mem, dest_align);
2580       len_rtx = expand_expr (len, NULL_RTX, VOIDmode, 0);
2581       src_str = c_getstr (src);
2582
2583       /* If SRC is a string constant and block move would be done
2584          by pieces, we can avoid loading the string from memory
2585          and only stored the computed constants.  */
2586       if (src_str
2587           && GET_CODE (len_rtx) == CONST_INT
2588           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
2589           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
2590                                   (void *) src_str, dest_align))
2591         {
2592           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
2593                                       builtin_memcpy_read_str,
2594                                       (void *) src_str, dest_align, 0);
2595           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
2596           dest_mem = convert_memory_address (ptr_mode, dest_mem);
2597           return dest_mem;
2598         }
2599
2600       src_mem = get_memory_rtx (src);
2601       set_mem_align (src_mem, src_align);
2602
2603       /* Copy word part most expediently.  */
2604       dest_addr = emit_block_move (dest_mem, src_mem, len_rtx,
2605                                    BLOCK_OP_NORMAL);
2606
2607       if (dest_addr == 0)
2608         {
2609           dest_addr = force_operand (XEXP (dest_mem, 0), NULL_RTX);
2610           dest_addr = convert_memory_address (ptr_mode, dest_addr);
2611         }
2612       return dest_addr;
2613     }
2614 }
2615
2616 /* Expand a call to the mempcpy builtin, with arguments in ARGLIST.
2617    Return 0 if we failed the caller should emit a normal call,
2618    otherwise try to get the result in TARGET, if convenient (and in
2619    mode MODE if that's convenient).  If ENDP is 0 return the
2620    destination pointer, if ENDP is 1 return the end pointer ala
2621    mempcpy, and if ENDP is 2 return the end pointer minus one ala
2622    stpcpy.  */
2623
2624 static rtx
2625 expand_builtin_mempcpy (tree arglist, tree type, rtx target, enum machine_mode mode,
2626                         int endp)
2627 {
2628   if (!validate_arglist (arglist,
2629                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
2630     return 0;
2631   /* If return value is ignored, transform mempcpy into memcpy.  */
2632   else if (target == const0_rtx)
2633     {
2634       tree fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
2635
2636       if (!fn)
2637         return 0;
2638
2639       return expand_expr (build_function_call_expr (fn, arglist),
2640                           target, mode, EXPAND_NORMAL);
2641     }
2642   else
2643     {
2644       tree dest = TREE_VALUE (arglist);
2645       tree src = TREE_VALUE (TREE_CHAIN (arglist));
2646       tree len = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (arglist)));
2647       const char *src_str;
2648       unsigned int src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
2649       unsigned int dest_align
2650         = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
2651       rtx dest_mem, src_mem, len_rtx;
2652       tree result = fold_builtin_mempcpy (arglist, type, endp);
2653
2654       if (result)
2655         return expand_expr (result, target, mode, EXPAND_NORMAL);
2656       
2657       /* If either SRC or DEST is not a pointer type, don't do this
2658          operation in-line.  */
2659       if (dest_align == 0 || src_align == 0)
2660         return 0;
2661
2662       /* If LEN is not constant, call the normal function.  */
2663       if (! host_integerp (len, 1))
2664         return 0;
2665
2666       len_rtx = expand_expr (len, NULL_RTX, VOIDmode, 0);
2667       src_str = c_getstr (src);
2668
2669       /* If SRC is a string constant and block move would be done
2670          by pieces, we can avoid loading the string from memory
2671          and only stored the computed constants.  */
2672       if (src_str
2673           && GET_CODE (len_rtx) == CONST_INT
2674           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
2675           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
2676                                   (void *) src_str, dest_align))
2677         {
2678           dest_mem = get_memory_rtx (dest);
2679           set_mem_align (dest_mem, dest_align);
2680           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
2681                                       builtin_memcpy_read_str,
2682                                       (void *) src_str, dest_align, endp);
2683           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
2684           dest_mem = convert_memory_address (ptr_mode, dest_mem);
2685           return dest_mem;
2686         }
2687
2688       if (GET_CODE (len_rtx) == CONST_INT
2689           && can_move_by_pieces (INTVAL (len_rtx),
2690                                  MIN (dest_align, src_align)))
2691         {
2692           dest_mem = get_memory_rtx (dest);
2693           set_mem_align (dest_mem, dest_align);
2694           src_mem = get_memory_rtx (src);
2695           set_mem_align (src_mem, src_align);
2696           dest_mem = move_by_pieces (dest_mem, src_mem, INTVAL (len_rtx),
2697                                      MIN (dest_align, src_align), endp);
2698           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
2699           dest_mem = convert_memory_address (ptr_mode, dest_mem);
2700           return dest_mem;
2701         }
2702
2703       return 0;
2704     }
2705 }
2706
2707 /* Expand expression EXP, which is a call to the memmove builtin.  Return 0
2708    if we failed the caller should emit a normal call.  */
2709
2710 static rtx
2711 expand_builtin_memmove (tree arglist, tree type, rtx target,
2712                         enum machine_mode mode)
2713 {
2714   if (!validate_arglist (arglist,
2715                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
2716     return 0;
2717   else
2718     {
2719       tree dest = TREE_VALUE (arglist);
2720       tree src = TREE_VALUE (TREE_CHAIN (arglist));
2721       tree len = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (arglist)));
2722
2723       unsigned int src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
2724       unsigned int dest_align
2725         = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
2726       tree result = fold_builtin_memmove (arglist, type);
2727
2728       if (result)
2729         return expand_expr (result, target, mode, EXPAND_NORMAL);
2730
2731       /* If DEST is not a pointer type, call the normal function.  */
2732       if (dest_align == 0)
2733         return 0;
2734
2735       /* If either SRC is not a pointer type, don't do this
2736          operation in-line.  */
2737       if (src_align == 0)
2738         return 0;
2739
2740       /* If src is categorized for a readonly section we can use
2741          normal memcpy.  */
2742       if (readonly_data_expr (src))
2743         {
2744           tree const fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
2745           if (!fn)
2746             return 0;
2747           return expand_expr (build_function_call_expr (fn, arglist),
2748                               target, mode, EXPAND_NORMAL);
2749         }
2750
2751       /* If length is 1 and we can expand memcpy call inline,
2752          it is ok to use memcpy as well.  */
2753       if (integer_onep (len))
2754         {
2755           rtx ret = expand_builtin_mempcpy (arglist, type, target, mode,
2756                                             /*endp=*/0);
2757           if (ret)
2758             return ret;
2759         }
2760
2761       /* Otherwise, call the normal function.  */
2762       return 0;
2763    }
2764 }
2765
2766 /* Expand expression EXP, which is a call to the bcopy builtin.  Return 0
2767    if we failed the caller should emit a normal call.  */
2768
2769 static rtx
2770 expand_builtin_bcopy (tree arglist, tree type)
2771 {
2772   tree src, dest, size, newarglist;
2773
2774   if (!validate_arglist (arglist,
2775                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
2776     return NULL_RTX;
2777
2778   src = TREE_VALUE (arglist);
2779   dest = TREE_VALUE (TREE_CHAIN (arglist));
2780   size = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (arglist)));
2781
2782   /* New argument list transforming bcopy(ptr x, ptr y, int z) to
2783      memmove(ptr y, ptr x, size_t z).   This is done this way
2784      so that if it isn't expanded inline, we fallback to
2785      calling bcopy instead of memmove.  */
2786
2787   newarglist = build_tree_list (NULL_TREE, fold_convert (sizetype, size));
2788   newarglist = tree_cons (NULL_TREE, src, newarglist);
2789   newarglist = tree_cons (NULL_TREE, dest, newarglist);
2790
2791   return expand_builtin_memmove (newarglist, type, const0_rtx, VOIDmode);
2792 }
2793
2794 #ifndef HAVE_movstr
2795 # define HAVE_movstr 0
2796 # define CODE_FOR_movstr CODE_FOR_nothing
2797 #endif
2798
2799 /* Expand into a movstr instruction, if one is available.  Return 0 if
2800    we failed, the caller should emit a normal call, otherwise try to
2801    get the result in TARGET, if convenient.  If ENDP is 0 return the
2802    destination pointer, if ENDP is 1 return the end pointer ala
2803    mempcpy, and if ENDP is 2 return the end pointer minus one ala
2804    stpcpy.  */
2805
2806 static rtx
2807 expand_movstr (tree dest, tree src, rtx target, int endp)
2808 {
2809   rtx end;
2810   rtx dest_mem;
2811   rtx src_mem;
2812   rtx insn;
2813   const struct insn_data * data;
2814
2815   if (!HAVE_movstr)
2816     return 0;
2817
2818   dest_mem = get_memory_rtx (dest);
2819   src_mem = get_memory_rtx (src);
2820   if (!endp)
2821     {
2822       target = force_reg (Pmode, XEXP (dest_mem, 0));
2823       dest_mem = replace_equiv_address (dest_mem, target);
2824       end = gen_reg_rtx (Pmode);
2825     }
2826   else
2827     {
2828       if (target == 0 || target == const0_rtx)
2829         {
2830           end = gen_reg_rtx (Pmode);
2831           if (target == 0)
2832             target = end;
2833         }
2834       else
2835         end = target;
2836     }
2837
2838   data = insn_data + CODE_FOR_movstr;
2839
2840   if (data->operand[0].mode != VOIDmode)
2841     end = gen_lowpart (data->operand[0].mode, end);
2842
2843   insn = data->genfun (end, dest_mem, src_mem);
2844
2845   gcc_assert (insn);
2846
2847   emit_insn (insn);
2848
2849   /* movstr is supposed to set end to the address of the NUL
2850      terminator.  If the caller requested a mempcpy-like return value,
2851      adjust it.  */
2852   if (endp == 1 && target != const0_rtx)
2853     {
2854       rtx tem = plus_constant (gen_lowpart (GET_MODE (target), end), 1);
2855       emit_move_insn (target, force_operand (tem, NULL_RTX));
2856     }
2857
2858   return target;
2859 }
2860
2861 /* Expand expression EXP, which is a call to the strcpy builtin.  Return 0
2862    if we failed the caller should emit a normal call, otherwise try to get
2863    the result in TARGET, if convenient (and in mode MODE if that's
2864    convenient).  */
2865
2866 static rtx
2867 expand_builtin_strcpy (tree exp, rtx target, enum machine_mode mode)
2868 {
2869   tree arglist = TREE_OPERAND (exp, 1);
2870   if (validate_arglist (arglist, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
2871     {
2872       tree result = fold_builtin_strcpy (exp, 0);
2873       if (result)
2874         return expand_expr (result, target, mode, EXPAND_NORMAL);
2875
2876       return expand_movstr (TREE_VALUE (arglist),
2877                             TREE_VALUE (TREE_CHAIN (arglist)),
2878                             target, /*endp=*/0);
2879     }
2880   return 0;
2881 }
2882
2883 /* Expand a call to the stpcpy builtin, with arguments in ARGLIST.
2884    Return 0 if we failed the caller should emit a normal call,
2885    otherwise try to get the result in TARGET, if convenient (and in
2886    mode MODE if that's convenient).  */
2887
2888 static rtx
2889 expand_builtin_stpcpy (tree exp, rtx target, enum machine_mode mode)
2890 {
2891   tree arglist = TREE_OPERAND (exp, 1);
2892   /* If return value is ignored, transform stpcpy into strcpy.  */
2893   if (target == const0_rtx)
2894     {
2895       tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
2896       if (!fn)
2897         return 0;
2898
2899       return expand_expr (build_function_call_expr (fn, arglist),
2900                           target, mode, EXPAND_NORMAL);
2901     }
2902
2903   if (!validate_arglist (arglist, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
2904     return 0;
2905   else
2906     {
2907       tree dst, src, len, lenp1;
2908       tree narglist;
2909       rtx ret;
2910
2911       /* Ensure we get an actual string whose length can be evaluated at
2912          compile-time, not an expression containing a string.  This is
2913          because the latter will potentially produce pessimized code
2914          when used to produce the return value.  */
2915       src = TREE_VALUE (TREE_CHAIN (arglist));
2916       if (! c_getstr (src) || ! (len = c_strlen (src, 0)))
2917         return expand_movstr (TREE_VALUE (arglist),
2918                               TREE_VALUE (TREE_CHAIN (arglist)),
2919                               target, /*endp=*/2);
2920
2921       dst = TREE_VALUE (arglist);
2922       lenp1 = size_binop (PLUS_EXPR, len, ssize_int (1));
2923       narglist = build_tree_list (NULL_TREE, lenp1);
2924       narglist = tree_cons (NULL_TREE, src, narglist);
2925       narglist = tree_cons (NULL_TREE, dst, narglist);
2926       ret = expand_builtin_mempcpy (narglist, TREE_TYPE (exp),
2927                                     target, mode, /*endp=*/2);
2928
2929       if (ret)
2930         return ret;
2931
2932       if (TREE_CODE (len) == INTEGER_CST)
2933         {
2934           rtx len_rtx = expand_expr (len, NULL_RTX, VOIDmode, 0);
2935
2936           if (GET_CODE (len_rtx) == CONST_INT)
2937             {
2938               ret = expand_builtin_strcpy (exp, target, mode);
2939
2940               if (ret)
2941                 {
2942                   if (! target)
2943                     {
2944                       if (mode != VOIDmode)
2945                         target = gen_reg_rtx (mode);
2946                       else
2947                         target = gen_reg_rtx (GET_MODE (ret));
2948                     }
2949                   if (GET_MODE (target) != GET_MODE (ret))
2950                     ret = gen_lowpart (GET_MODE (target), ret);
2951
2952                   ret = plus_constant (ret, INTVAL (len_rtx));
2953                   ret = emit_move_insn (target, force_operand (ret, NULL_RTX));
2954                   gcc_assert (ret);
2955
2956                   return target;
2957                 }
2958             }
2959         }
2960
2961       return expand_movstr (TREE_VALUE (arglist),
2962                             TREE_VALUE (TREE_CHAIN (arglist)),
2963                             target, /*endp=*/2);
2964     }
2965 }
2966
2967 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
2968    bytes from constant string DATA + OFFSET and return it as target
2969    constant.  */
2970
2971 static rtx
2972 builtin_strncpy_read_str (void *data, HOST_WIDE_INT offset,
2973                           enum machine_mode mode)
2974 {
2975   const char *str = (const char *) data;
2976
2977   if ((unsigned HOST_WIDE_INT) offset > strlen (str))
2978     return const0_rtx;
2979
2980   return c_readstr (str + offset, mode);
2981 }
2982
2983 /* Expand expression EXP, which is a call to the strncpy builtin.  Return 0
2984    if we failed the caller should emit a normal call.  */
2985
2986 static rtx
2987 expand_builtin_strncpy (tree exp, rtx target, enum machine_mode mode)
2988 {
2989   tree arglist = TREE_OPERAND (exp, 1);
2990   if (validate_arglist (arglist,
2991                         POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
2992     {
2993       tree slen = c_strlen (TREE_VALUE (TREE_CHAIN (arglist)), 1);
2994       tree len = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (arglist)));
2995       tree result = fold_builtin_strncpy (exp, slen);
2996       
2997       if (result)
2998         return expand_expr (result, target, mode, EXPAND_NORMAL);
2999
3000       /* We must be passed a constant len and src parameter.  */
3001       if (!host_integerp (len, 1) || !slen || !host_integerp (slen, 1))
3002         return 0;
3003
3004       slen = size_binop (PLUS_EXPR, slen, ssize_int (1));
3005
3006       /* We're required to pad with trailing zeros if the requested
3007          len is greater than strlen(s2)+1.  In that case try to
3008          use store_by_pieces, if it fails, punt.  */
3009       if (tree_int_cst_lt (slen, len))
3010         {
3011           tree dest = TREE_VALUE (arglist);
3012           unsigned int dest_align
3013             = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3014           const char *p = c_getstr (TREE_VALUE (TREE_CHAIN (arglist)));
3015           rtx dest_mem;
3016
3017           if (!p || dest_align == 0 || !host_integerp (len, 1)
3018               || !can_store_by_pieces (tree_low_cst (len, 1),
3019                                        builtin_strncpy_read_str,
3020                                        (void *) p, dest_align))
3021             return 0;
3022
3023           dest_mem = get_memory_rtx (dest);
3024           store_by_pieces (dest_mem, tree_low_cst (len, 1),
3025                            builtin_strncpy_read_str,
3026                            (void *) p, dest_align, 0);
3027           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3028           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3029           return dest_mem;
3030         }
3031     }
3032   return 0;
3033 }
3034
3035 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3036    bytes from constant string DATA + OFFSET and return it as target
3037    constant.  */
3038
3039 static rtx
3040 builtin_memset_read_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3041                          enum machine_mode mode)
3042 {
3043   const char *c = (const char *) data;
3044   char *p = alloca (GET_MODE_SIZE (mode));
3045
3046   memset (p, *c, GET_MODE_SIZE (mode));
3047
3048   return c_readstr (p, mode);
3049 }
3050
3051 /* Callback routine for store_by_pieces.  Return the RTL of a register
3052    containing GET_MODE_SIZE (MODE) consecutive copies of the unsigned
3053    char value given in the RTL register data.  For example, if mode is
3054    4 bytes wide, return the RTL for 0x01010101*data.  */
3055
3056 static rtx
3057 builtin_memset_gen_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3058                         enum machine_mode mode)
3059 {
3060   rtx target, coeff;
3061   size_t size;
3062   char *p;
3063
3064   size = GET_MODE_SIZE (mode);
3065   if (size == 1)
3066     return (rtx) data;
3067
3068   p = alloca (size);
3069   memset (p, 1, size);
3070   coeff = c_readstr (p, mode);
3071
3072   target = convert_to_mode (mode, (rtx) data, 1);
3073   target = expand_mult (mode, target, coeff, NULL_RTX, 1);
3074   return force_reg (mode, target);
3075 }
3076
3077 /* Expand expression EXP, which is a call to the memset builtin.  Return 0
3078    if we failed the caller should emit a normal call, otherwise try to get
3079    the result in TARGET, if convenient (and in mode MODE if that's
3080    convenient).  */
3081
3082 static rtx
3083 expand_builtin_memset (tree arglist, rtx target, enum machine_mode mode)
3084 {
3085   if (!validate_arglist (arglist,
3086                          POINTER_TYPE, INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
3087     return 0;
3088   else
3089     {
3090       tree dest = TREE_VALUE (arglist);
3091       tree val = TREE_VALUE (TREE_CHAIN (arglist));
3092       tree len = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (arglist)));
3093       char c;
3094
3095       unsigned int dest_align
3096         = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3097       rtx dest_mem, dest_addr, len_rtx;
3098
3099       /* If DEST is not a pointer type, don't do this
3100          operation in-line.  */
3101       if (dest_align == 0)
3102         return 0;
3103
3104       /* If the LEN parameter is zero, return DEST.  */
3105       if (integer_zerop (len))
3106         {
3107           /* Evaluate and ignore VAL in case it has side-effects.  */
3108           expand_expr (val, const0_rtx, VOIDmode, EXPAND_NORMAL);
3109           return expand_expr (dest, target, mode, EXPAND_NORMAL);
3110         }
3111
3112       if (TREE_CODE (val) != INTEGER_CST)
3113         {
3114           rtx val_rtx;
3115
3116           if (!host_integerp (len, 1))
3117             return 0;
3118
3119           if (optimize_size && tree_low_cst (len, 1) > 1)
3120             return 0;
3121
3122           /* Assume that we can memset by pieces if we can store the
3123            * the coefficients by pieces (in the required modes).
3124            * We can't pass builtin_memset_gen_str as that emits RTL.  */
3125           c = 1;
3126           if (!can_store_by_pieces (tree_low_cst (len, 1),
3127                                     builtin_memset_read_str,
3128                                     &c, dest_align))
3129             return 0;
3130
3131           val = fold (build1 (CONVERT_EXPR, unsigned_char_type_node, val));
3132           val_rtx = expand_expr (val, NULL_RTX, VOIDmode, 0);
3133           val_rtx = force_reg (TYPE_MODE (unsigned_char_type_node),
3134                                val_rtx);
3135           dest_mem = get_memory_rtx (dest);
3136           store_by_pieces (dest_mem, tree_low_cst (len, 1),
3137                            builtin_memset_gen_str,
3138                            val_rtx, dest_align, 0);
3139           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3140           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3141           return dest_mem;
3142         }
3143
3144       if (target_char_cast (val, &c))
3145         return 0;
3146
3147       if (c)
3148         {
3149           if (!host_integerp (len, 1))
3150             return 0;
3151           if (!can_store_by_pieces (tree_low_cst (len, 1),
3152                                     builtin_memset_read_str, &c,
3153                                     dest_align))
3154             return 0;
3155
3156           dest_mem = get_memory_rtx (dest);
3157           store_by_pieces (dest_mem, tree_low_cst (len, 1),
3158                            builtin_memset_read_str,
3159                            &c, dest_align, 0);
3160           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3161           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3162           return dest_mem;
3163         }
3164
3165       len_rtx = expand_expr (len, NULL_RTX, VOIDmode, 0);
3166
3167       dest_mem = get_memory_rtx (dest);
3168       set_mem_align (dest_mem, dest_align);
3169       dest_addr = clear_storage (dest_mem, len_rtx);
3170
3171       if (dest_addr == 0)
3172         {
3173           dest_addr = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3174           dest_addr = convert_memory_address (ptr_mode, dest_addr);
3175         }
3176
3177       return dest_addr;
3178     }
3179 }
3180
3181 /* Expand expression EXP, which is a call to the bzero builtin.  Return 0
3182    if we failed the caller should emit a normal call.  */
3183
3184 static rtx
3185 expand_builtin_bzero (tree arglist)
3186 {
3187   tree dest, size, newarglist;
3188
3189   if (!validate_arglist (arglist, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3190     return NULL_RTX;
3191
3192   dest = TREE_VALUE (arglist);
3193   size = TREE_VALUE (TREE_CHAIN (arglist));
3194
3195   /* New argument list transforming bzero(ptr x, int y) to
3196      memset(ptr x, int 0, size_t y).   This is done this way
3197      so that if it isn't expanded inline, we fallback to
3198      calling bzero instead of memset.  */
3199
3200   newarglist = build_tree_list (NULL_TREE, fold_convert (sizetype, size));
3201   newarglist = tree_cons (NULL_TREE, integer_zero_node, newarglist);
3202   newarglist = tree_cons (NULL_TREE, dest, newarglist);
3203
3204   return expand_builtin_memset (newarglist, const0_rtx, VOIDmode);
3205 }
3206
3207 /* Expand expression EXP, which is a call to the memcmp built-in function.
3208    ARGLIST is the argument list for this call.  Return 0 if we failed and the
3209    caller should emit a normal call, otherwise try to get the result in
3210    TARGET, if convenient (and in mode MODE, if that's convenient).  */
3211
3212 static rtx
3213 expand_builtin_memcmp (tree exp ATTRIBUTE_UNUSED, tree arglist, rtx target,
3214                        enum machine_mode mode)
3215 {
3216   if (!validate_arglist (arglist,
3217                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3218     return 0;
3219   else
3220     {
3221       tree result = fold_builtin_memcmp (arglist);
3222       if (result)
3223         return expand_expr (result, target, mode, EXPAND_NORMAL);
3224     }
3225
3226 #if defined HAVE_cmpmemsi || defined HAVE_cmpstrsi
3227   {
3228     tree arg1 = TREE_VALUE (arglist);
3229     tree arg2 = TREE_VALUE (TREE_CHAIN (arglist));
3230     tree len = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (arglist)));
3231     rtx arg1_rtx, arg2_rtx, arg3_rtx;
3232     rtx result;
3233     rtx insn;
3234
3235     int arg1_align
3236       = get_pointer_alignment (arg1, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
3237     int arg2_align
3238       = get_pointer_alignment (arg2, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
3239     enum machine_mode insn_mode;
3240
3241 #ifdef HAVE_cmpmemsi
3242     if (HAVE_cmpmemsi)
3243       insn_mode = insn_data[(int) CODE_FOR_cmpmemsi].operand[0].mode;
3244     else
3245 #endif
3246 #ifdef HAVE_cmpstrsi
3247     if (HAVE_cmpstrsi)
3248       insn_mode = insn_data[(int) CODE_FOR_cmpstrsi].operand[0].mode;
3249     else
3250 #endif
3251       return 0;
3252
3253     /* If we don't have POINTER_TYPE, call the function.  */
3254     if (arg1_align == 0 || arg2_align == 0)
3255       return 0;
3256
3257     /* Make a place to write the result of the instruction.  */
3258     result = target;
3259     if (! (result != 0
3260            && REG_P (result) && GET_MODE (result) == insn_mode
3261            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3262       result = gen_reg_rtx (insn_mode);
3263
3264     arg1_rtx = get_memory_rtx (arg1);
3265     arg2_rtx = get_memory_rtx (arg2);
3266     arg3_rtx = expand_expr (len, NULL_RTX, VOIDmode, 0);
3267
3268     /* Set MEM_SIZE as appropriate.  */
3269     if (GET_CODE (arg3_rtx) == CONST_INT)
3270       {
3271         set_mem_size (arg1_rtx, arg3_rtx);
3272         set_mem_size (arg2_rtx, arg3_rtx);
3273       }
3274
3275 #ifdef HAVE_cmpmemsi
3276     if (HAVE_cmpmemsi)
3277       insn = gen_cmpmemsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3278                            GEN_INT (MIN (arg1_align, arg2_align)));
3279     else
3280 #endif
3281 #ifdef HAVE_cmpstrsi
3282     if (HAVE_cmpstrsi)
3283       insn = gen_cmpstrsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3284                            GEN_INT (MIN (arg1_align, arg2_align)));
3285     else
3286 #endif
3287       gcc_unreachable ();
3288
3289     if (insn)
3290       emit_insn (insn);
3291     else
3292       emit_library_call_value (memcmp_libfunc, result, LCT_PURE_MAKE_BLOCK,
3293                                TYPE_MODE (integer_type_node), 3,
3294                                XEXP (arg1_rtx, 0), Pmode,
3295                                XEXP (arg2_rtx, 0), Pmode,
3296                                convert_to_mode (TYPE_MODE (sizetype), arg3_rtx,
3297                                                 TYPE_UNSIGNED (sizetype)),
3298                                TYPE_MODE (sizetype));
3299
3300     /* Return the value in the proper mode for this function.  */
3301     mode = TYPE_MODE (TREE_TYPE (exp));
3302     if (GET_MODE (result) == mode)
3303       return result;
3304     else if (target != 0)
3305       {
3306         convert_move (target, result, 0);
3307         return target;
3308       }
3309     else
3310       return convert_to_mode (mode, result, 0);
3311   }
3312 #endif
3313
3314   return 0;
3315 }
3316
3317 /* Expand expression EXP, which is a call to the strcmp builtin.  Return 0
3318    if we failed the caller should emit a normal call, otherwise try to get
3319    the result in TARGET, if convenient.  */
3320
3321 static rtx
3322 expand_builtin_strcmp (tree exp, rtx target, enum machine_mode mode)
3323 {
3324   tree arglist = TREE_OPERAND (exp, 1);
3325
3326   if (!validate_arglist (arglist, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3327     return 0;
3328   else
3329     {
3330       tree result = fold_builtin_strcmp (arglist);
3331       if (result)
3332         return expand_expr (result, target, mode, EXPAND_NORMAL);
3333     }
3334
3335 #ifdef HAVE_cmpstrsi
3336   if (HAVE_cmpstrsi)
3337   {
3338     tree arg1 = TREE_VALUE (arglist);
3339     tree arg2 = TREE_VALUE (TREE_CHAIN (arglist));
3340     tree len, len1, len2;
3341     rtx arg1_rtx, arg2_rtx, arg3_rtx;
3342     rtx result, insn;
3343     tree fndecl;
3344
3345     int arg1_align
3346       = get_pointer_alignment (arg1, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
3347     int arg2_align
3348       = get_pointer_alignment (arg2, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
3349     enum machine_mode insn_mode
3350       = insn_data[(int) CODE_FOR_cmpstrsi].operand[0].mode;
3351
3352     len1 = c_strlen (arg1, 1);
3353     len2 = c_strlen (arg2, 1);
3354
3355     if (len1)
3356       len1 = size_binop (PLUS_EXPR, ssize_int (1), len1);
3357     if (len2)
3358       len2 = size_binop (PLUS_EXPR, ssize_int (1), len2);
3359
3360     /* If we don't have a constant length for the first, use the length
3361        of the second, if we know it.  We don't require a constant for
3362        this case; some cost analysis could be done if both are available
3363        but neither is constant.  For now, assume they're equally cheap,
3364        unless one has side effects.  If both strings have constant lengths,
3365        use the smaller.  */
3366
3367     if (!len1)
3368       len = len2;
3369     else if (!len2)
3370       len = len1;
3371     else if (TREE_SIDE_EFFECTS (len1))
3372       len = len2;
3373     else if (TREE_SIDE_EFFECTS (len2))
3374       len = len1;
3375     else if (TREE_CODE (len1) != INTEGER_CST)
3376       len = len2;
3377     else if (TREE_CODE (len2) != INTEGER_CST)
3378       len = len1;
3379     else if (tree_int_cst_lt (len1, len2))
3380       len = len1;
3381     else
3382       len = len2;
3383
3384     /* If both arguments have side effects, we cannot optimize.  */
3385     if (!len || TREE_SIDE_EFFECTS (len))
3386       return 0;
3387
3388     /* If we don't have POINTER_TYPE, call the function.  */
3389     if (arg1_align == 0 || arg2_align == 0)
3390       return 0;
3391
3392     /* Make a place to write the result of the instruction.  */
3393     result = target;
3394     if (! (result != 0
3395            && REG_P (result) && GET_MODE (result) == insn_mode
3396            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3397       result = gen_reg_rtx (insn_mode);
3398
3399     /* Stabilize the arguments in case gen_cmpstrsi fails.  */
3400     arg1 = builtin_save_expr (arg1);
3401     arg2 = builtin_save_expr (arg2);
3402
3403     arg1_rtx = get_memory_rtx (arg1);
3404     arg2_rtx = get_memory_rtx (arg2);
3405     arg3_rtx = expand_expr (len, NULL_RTX, VOIDmode, 0);
3406     insn = gen_cmpstrsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3407                          GEN_INT (MIN (arg1_align, arg2_align)));
3408     if (insn)
3409       {
3410         emit_insn (insn);
3411
3412         /* Return the value in the proper mode for this function.  */
3413         mode = TYPE_MODE (TREE_TYPE (exp));
3414         if (GET_MODE (result) == mode)
3415           return result;
3416         if (target == 0)
3417           return convert_to_mode (mode, result, 0);
3418         convert_move (target, result, 0);
3419         return target;
3420       }
3421
3422     /* Expand the library call ourselves using a stabilized argument
3423        list to avoid re-evaluating the function's arguments twice.  */
3424     arglist = build_tree_list (NULL_TREE, arg2);
3425     arglist = tree_cons (NULL_TREE, arg1, arglist);
3426     fndecl = get_callee_fndecl (exp);
3427     exp = build_function_call_expr (fndecl, arglist);
3428     return expand_call (exp, target, target == const0_rtx);
3429   }
3430 #endif
3431   return 0;
3432 }
3433
3434 /* Expand expression EXP, which is a call to the strncmp builtin.  Return 0
3435    if we failed the caller should emit a normal call, otherwise try to get
3436    the result in TARGET, if convenient.  */
3437
3438 static rtx
3439 expand_builtin_strncmp (tree exp, rtx target, enum machine_mode mode)
3440 {
3441   tree arglist = TREE_OPERAND (exp, 1);
3442
3443   if (!validate_arglist (arglist,
3444                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3445     return 0;
3446   else
3447     {
3448       tree result = fold_builtin_strncmp (arglist);
3449       if (result)
3450         return expand_expr (result, target, mode, EXPAND_NORMAL);
3451     }
3452
3453   /* If c_strlen can determine an expression for one of the string
3454      lengths, and it doesn't have side effects, then emit cmpstrsi
3455      using length MIN(strlen(string)+1, arg3).  */
3456 #ifdef HAVE_cmpstrsi
3457   if (HAVE_cmpstrsi)
3458   {
3459     tree arg1 = TREE_VALUE (arglist);
3460     tree arg2 = TREE_VALUE (TREE_CHAIN (arglist));
3461     tree arg3 = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (arglist)));
3462     tree len, len1, len2;
3463     rtx arg1_rtx, arg2_rtx, arg3_rtx;
3464     rtx result, insn;
3465     tree fndecl;
3466
3467     int arg1_align
3468       = get_pointer_alignment (arg1, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
3469     int arg2_align
3470       = get_pointer_alignment (arg2, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
3471     enum machine_mode insn_mode
3472       = insn_data[(int) CODE_FOR_cmpstrsi].operand[0].mode;
3473
3474     len1 = c_strlen (arg1, 1);
3475     len2 = c_strlen (arg2, 1);
3476
3477     if (len1)
3478       len1 = size_binop (PLUS_EXPR, ssize_int (1), len1);
3479     if (len2)
3480       len2 = size_binop (PLUS_EXPR, ssize_int (1), len2);
3481
3482     /* If we don't have a constant length for the first, use the length
3483        of the second, if we know it.  We don't require a constant for
3484        this case; some cost analysis could be done if both are available
3485        but neither is constant.  For now, assume they're equally cheap,
3486        unless one has side effects.  If both strings have constant lengths,
3487        use the smaller.  */
3488
3489     if (!len1)
3490       len = len2;
3491     else if (!len2)
3492       len = len1;
3493     else if (TREE_SIDE_EFFECTS (len1))
3494       len = len2;
3495     else if (TREE_SIDE_EFFECTS (len2))
3496       len = len1;
3497     else if (TREE_CODE (len1) != INTEGER_CST)
3498       len = len2;
3499     else if (TREE_CODE (len2) != INTEGER_CST)
3500       len = len1;
3501     else if (tree_int_cst_lt (len1, len2))
3502       len = len1;
3503     else
3504       len = len2;
3505
3506     /* If both arguments have side effects, we cannot optimize.  */
3507     if (!len || TREE_SIDE_EFFECTS (len))
3508       return 0;
3509
3510     /* The actual new length parameter is MIN(len,arg3).  */
3511     len = fold (build2 (MIN_EXPR, TREE_TYPE (len), len,
3512                         fold_convert (TREE_TYPE (len), arg3)));
3513
3514     /* If we don't have POINTER_TYPE, call the function.  */
3515     if (arg1_align == 0 || arg2_align == 0)
3516       return 0;
3517
3518     /* Make a place to write the result of the instruction.  */
3519     result = target;
3520     if (! (result != 0
3521            && REG_P (result) && GET_MODE (result) == insn_mode
3522            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3523       result = gen_reg_rtx (insn_mode);
3524
3525     /* Stabilize the arguments in case gen_cmpstrsi fails.  */
3526     arg1 = builtin_save_expr (arg1);
3527     arg2 = builtin_save_expr (arg2);
3528     len = builtin_save_expr (len);
3529
3530     arg1_rtx = get_memory_rtx (arg1);
3531     arg2_rtx = get_memory_rtx (arg2);
3532     arg3_rtx = expand_expr (len, NULL_RTX, VOIDmode, 0);
3533     insn = gen_cmpstrsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3534                          GEN_INT (MIN (arg1_align, arg2_align)));
3535     if (insn)
3536       {
3537         emit_insn (insn);
3538
3539         /* Return the value in the proper mode for this function.  */
3540         mode = TYPE_MODE (TREE_TYPE (exp));
3541         if (GET_MODE (result) == mode)
3542           return result;
3543         if (target == 0)
3544           return convert_to_mode (mode, result, 0);
3545         convert_move (target, result, 0);
3546         return target;
3547       }
3548
3549     /* Expand the library call ourselves using a stabilized argument
3550        list to avoid re-evaluating the function's arguments twice.  */
3551     arglist = build_tree_list (NULL_TREE, len);
3552     arglist = tree_cons (NULL_TREE, arg2, arglist);
3553     arglist = tree_cons (NULL_TREE, arg1, arglist);
3554     fndecl = get_callee_fndecl (exp);
3555     exp = build_function_call_expr (fndecl, arglist);
3556     return expand_call (exp, target, target == const0_rtx);
3557   }
3558 #endif
3559   return 0;
3560 }
3561
3562 /* Expand expression EXP, which is a call to the strcat builtin.
3563    Return 0 if we failed the caller should emit a normal call,
3564    otherwise try to get the result in TARGET, if convenient.  */
3565
3566 static rtx
3567 expand_builtin_strcat (tree arglist, tree type, rtx target, enum machine_mode mode)
3568 {
3569   if (!validate_arglist (arglist, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3570     return 0;
3571   else
3572     {
3573       tree dst = TREE_VALUE (arglist),
3574         src = TREE_VALUE (TREE_CHAIN (arglist));
3575       const char *p = c_getstr (src);
3576
3577       if (p)
3578         {
3579           /* If the string length is zero, return the dst parameter.  */
3580           if (*p == '\0')
3581             return expand_expr (dst, target, mode, EXPAND_NORMAL);
3582           else if (!optimize_size)
3583             {
3584               /* Otherwise if !optimize_size, see if we can store by
3585                  pieces into (dst + strlen(dst)).  */
3586               tree newdst, arglist,
3587                 strlen_fn = implicit_built_in_decls[BUILT_IN_STRLEN];
3588
3589               /* This is the length argument.  */
3590               arglist = build_tree_list (NULL_TREE,
3591                                          fold (size_binop (PLUS_EXPR,
3592                                                            c_strlen (src, 0),
3593                                                            ssize_int (1))));
3594               /* Prepend src argument.  */
3595               arglist = tree_cons (NULL_TREE, src, arglist);
3596
3597               /* We're going to use dst more than once.  */
3598               dst = builtin_save_expr (dst);
3599
3600               /* Create strlen (dst).  */
3601               newdst =
3602                 fold (build_function_call_expr (strlen_fn,
3603                                                 build_tree_list (NULL_TREE,
3604                                                                  dst)));
3605               /* Create (dst + strlen (dst)).  */
3606               newdst = fold (build2 (PLUS_EXPR, TREE_TYPE (dst), dst, newdst));
3607
3608               /* Prepend the new dst argument.  */
3609               arglist = tree_cons (NULL_TREE, newdst, arglist);
3610
3611               /* We don't want to get turned into a memcpy if the
3612                  target is const0_rtx, i.e. when the return value
3613                  isn't used.  That would produce pessimized code so
3614                  pass in a target of zero, it should never actually be
3615                  used.  If this was successful return the original
3616                  dst, not the result of mempcpy.  */
3617               if (expand_builtin_mempcpy (arglist, type, /*target=*/0, mode, /*endp=*/0))
3618                 return expand_expr (dst, target, mode, EXPAND_NORMAL);
3619               else
3620                 return 0;
3621             }
3622         }
3623
3624       return 0;
3625     }
3626 }
3627
3628 /* Expand expression EXP, which is a call to the strncat builtin.
3629    Return 0 if we failed the caller should emit a normal call,
3630    otherwise try to get the result in TARGET, if convenient.  */
3631
3632 static rtx
3633 expand_builtin_strncat (tree arglist, rtx target, enum machine_mode mode)
3634 {
3635   if (validate_arglist (arglist,
3636                         POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3637     {
3638       tree result = fold_builtin_strncat (arglist);
3639       if (result)
3640         return expand_expr (result, target, mode, EXPAND_NORMAL);
3641     }
3642   return 0;
3643 }
3644
3645 /* Expand expression EXP, which is a call to the strspn builtin.
3646    Return 0 if we failed the caller should emit a normal call,
3647    otherwise try to get the result in TARGET, if convenient.  */
3648
3649 static rtx
3650 expand_builtin_strspn (tree arglist, rtx target, enum machine_mode mode)
3651 {
3652   if (validate_arglist (arglist, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3653     {
3654       tree result = fold_builtin_strspn (arglist);
3655       if (result)
3656         return expand_expr (result, target, mode, EXPAND_NORMAL);
3657     }
3658   return 0;
3659 }
3660
3661 /* Expand expression EXP, which is a call to the strcspn builtin.
3662    Return 0 if we failed the caller should emit a normal call,
3663    otherwise try to get the result in TARGET, if convenient.  */
3664
3665 static rtx
3666 expand_builtin_strcspn (tree arglist, rtx target, enum machine_mode mode)
3667 {
3668   if (validate_arglist (arglist, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3669     {
3670       tree result = fold_builtin_strcspn (arglist);
3671       if (result)
3672         return expand_expr (result, target, mode, EXPAND_NORMAL);
3673     }
3674   return 0;
3675 }
3676
3677 /* Expand a call to __builtin_saveregs, generating the result in TARGET,
3678    if that's convenient.  */
3679
3680 rtx
3681 expand_builtin_saveregs (void)
3682 {
3683   rtx val, seq;
3684
3685   /* Don't do __builtin_saveregs more than once in a function.
3686      Save the result of the first call and reuse it.  */
3687   if (saveregs_value != 0)
3688     return saveregs_value;
3689
3690   /* When this function is called, it means that registers must be
3691      saved on entry to this function.  So we migrate the call to the
3692      first insn of this function.  */
3693
3694   start_sequence ();
3695
3696   /* Do whatever the machine needs done in this case.  */
3697   val = targetm.calls.expand_builtin_saveregs ();
3698
3699   seq = get_insns ();
3700   end_sequence ();
3701
3702   saveregs_value = val;
3703
3704   /* Put the insns after the NOTE that starts the function.  If this
3705      is inside a start_sequence, make the outer-level insn chain current, so
3706      the code is placed at the start of the function.  */
3707   push_topmost_sequence ();
3708   emit_insn_after (seq, entry_of_function ());
3709   pop_topmost_sequence ();
3710
3711   return val;
3712 }
3713
3714 /* __builtin_args_info (N) returns word N of the arg space info
3715    for the current function.  The number and meanings of words
3716    is controlled by the definition of CUMULATIVE_ARGS.  */
3717
3718 static rtx
3719 expand_builtin_args_info (tree arglist)
3720 {
3721   int nwords = sizeof (CUMULATIVE_ARGS) / sizeof (int);
3722   int *word_ptr = (int *) &current_function_args_info;
3723
3724   gcc_assert (sizeof (CUMULATIVE_ARGS) % sizeof (int) == 0);
3725
3726   if (arglist != 0)
3727     {
3728       if (!host_integerp (TREE_VALUE (arglist), 0))
3729         error ("argument of %<__builtin_args_info%> must be constant");
3730       else
3731         {
3732           HOST_WIDE_INT wordnum = tree_low_cst (TREE_VALUE (arglist), 0);
3733
3734           if (wordnum < 0 || wordnum >= nwords)
3735             error ("argument of %<__builtin_args_info%> out of range");
3736           else
3737             return GEN_INT (word_ptr[wordnum]);
3738         }
3739     }
3740   else
3741     error ("missing argument in %<__builtin_args_info%>");
3742
3743   return const0_rtx;
3744 }
3745
3746 /* Expand ARGLIST, from a call to __builtin_next_arg.  */
3747
3748 static rtx
3749 expand_builtin_next_arg (tree arglist)
3750 {
3751   tree fntype = TREE_TYPE (current_function_decl);
3752
3753   if (TYPE_ARG_TYPES (fntype) == 0
3754       || (TREE_VALUE (tree_last (TYPE_ARG_TYPES (fntype)))
3755           == void_type_node))
3756     {
3757       error ("%<va_start%> used in function with fixed args");
3758       return const0_rtx;
3759     }
3760
3761   if (arglist)
3762     {
3763       tree last_parm = tree_last (DECL_ARGUMENTS (current_function_decl));
3764       tree arg = TREE_VALUE (arglist);
3765
3766       /* Strip off all nops for the sake of the comparison.  This
3767          is not quite the same as STRIP_NOPS.  It does more.
3768          We must also strip off INDIRECT_EXPR for C++ reference
3769          parameters.  */
3770       while (TREE_CODE (arg) == NOP_EXPR
3771              || TREE_CODE (arg) == CONVERT_EXPR
3772              || TREE_CODE (arg) == NON_LVALUE_EXPR
3773              || TREE_CODE (arg) == INDIRECT_REF)
3774         arg = TREE_OPERAND (arg, 0);
3775       if (arg != last_parm)
3776         warning ("second parameter of %<va_start%> not last named argument");
3777     }
3778   else
3779     /* Evidently an out of date version of <stdarg.h>; can't validate
3780        va_start's second argument, but can still work as intended.  */
3781     warning ("%<__builtin_next_arg%> called without an argument");
3782
3783   return expand_binop (Pmode, add_optab,
3784                        current_function_internal_arg_pointer,
3785                        current_function_arg_offset_rtx,
3786                        NULL_RTX, 0, OPTAB_LIB_WIDEN);
3787 }
3788
3789 /* Make it easier for the backends by protecting the valist argument
3790    from multiple evaluations.  */
3791
3792 static tree
3793 stabilize_va_list (tree valist, int needs_lvalue)
3794 {
3795   if (TREE_CODE (va_list_type_node) == ARRAY_TYPE)
3796     {
3797       if (TREE_SIDE_EFFECTS (valist))
3798         valist = save_expr (valist);
3799
3800       /* For this case, the backends will be expecting a pointer to
3801          TREE_TYPE (va_list_type_node), but it's possible we've
3802          actually been given an array (an actual va_list_type_node).
3803          So fix it.  */
3804       if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
3805         {
3806           tree p1 = build_pointer_type (TREE_TYPE (va_list_type_node));
3807           valist = build_fold_addr_expr_with_type (valist, p1);
3808         }
3809     }
3810   else
3811     {
3812       tree pt;
3813
3814       if (! needs_lvalue)
3815         {
3816           if (! TREE_SIDE_EFFECTS (valist))
3817             return valist;
3818
3819           pt = build_pointer_type (va_list_type_node);
3820           valist = fold (build1 (ADDR_EXPR, pt, valist));
3821           TREE_SIDE_EFFECTS (valist) = 1;
3822         }
3823
3824       if (TREE_SIDE_EFFECTS (valist))
3825         valist = save_expr (valist);
3826       valist = build_fold_indirect_ref (valist);
3827     }
3828
3829   return valist;
3830 }
3831
3832 /* The "standard" definition of va_list is void*.  */
3833
3834 tree
3835 std_build_builtin_va_list (void)
3836 {
3837   return ptr_type_node;
3838 }
3839
3840 /* The "standard" implementation of va_start: just assign `nextarg' to
3841    the variable.  */
3842
3843 void
3844 std_expand_builtin_va_start (tree valist, rtx nextarg)
3845 {
3846   tree t;
3847
3848   t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist,
3849               make_tree (ptr_type_node, nextarg));
3850   TREE_SIDE_EFFECTS (t) = 1;
3851
3852   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
3853 }
3854
3855 /* Expand ARGLIST, from a call to __builtin_va_start.  */
3856
3857 static rtx
3858 expand_builtin_va_start (tree arglist)
3859 {
3860   rtx nextarg;
3861   tree chain, valist;
3862
3863   chain = TREE_CHAIN (arglist);
3864
3865   if (!chain)
3866     {
3867       error ("too few arguments to function %<va_start%>");
3868       return const0_rtx;
3869     }
3870   if (TREE_CHAIN (chain))
3871     error ("too many arguments to function %<va_start%>");
3872
3873   fold_builtin_next_arg (chain);
3874
3875   nextarg = expand_builtin_next_arg (chain);
3876   valist = stabilize_va_list (TREE_VALUE (arglist), 1);
3877
3878 #ifdef EXPAND_BUILTIN_VA_START
3879   EXPAND_BUILTIN_VA_START (valist, nextarg);
3880 #else
3881   std_expand_builtin_va_start (valist, nextarg);
3882 #endif
3883
3884   return const0_rtx;
3885 }
3886
3887 /* The "standard" implementation of va_arg: read the value from the
3888    current (padded) address and increment by the (padded) size.  */
3889
3890 tree
3891 std_gimplify_va_arg_expr (tree valist, tree type, tree *pre_p, tree *post_p)
3892 {
3893   tree addr, t, type_size, rounded_size, valist_tmp;
3894   unsigned HOST_WIDE_INT align, boundary;
3895   bool indirect;
3896
3897 #ifdef ARGS_GROW_DOWNWARD
3898   /* All of the alignment and movement below is for args-grow-up machines.
3899      As of 2004, there are only 3 ARGS_GROW_DOWNWARD targets, and they all
3900      implement their own specialized gimplify_va_arg_expr routines.  */
3901   gcc_unreachable ();
3902 #endif
3903
3904   indirect = pass_by_reference (NULL, TYPE_MODE (type), type, false);
3905   if (indirect)
3906     type = build_pointer_type (type);
3907
3908   align = PARM_BOUNDARY / BITS_PER_UNIT;
3909   boundary = FUNCTION_ARG_BOUNDARY (TYPE_MODE (type), type) / BITS_PER_UNIT;
3910
3911   /* Hoist the valist value into a temporary for the moment.  */
3912   valist_tmp = get_initialized_tmp_var (valist, pre_p, NULL);
3913
3914   /* va_list pointer is aligned to PARM_BOUNDARY.  If argument actually
3915      requires greater alignment, we must perform dynamic alignment.  */
3916   if (boundary > align)
3917     {
3918       t = fold_convert (TREE_TYPE (valist), size_int (boundary - 1));
3919       t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
3920                   build2 (PLUS_EXPR, TREE_TYPE (valist), valist_tmp, t));
3921       gimplify_and_add (t, pre_p);
3922
3923       t = fold_convert (TREE_TYPE (valist), size_int (-boundary));
3924       t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
3925                   build2 (BIT_AND_EXPR, TREE_TYPE (valist), valist_tmp, t));
3926       gimplify_and_add (t, pre_p);
3927     }
3928
3929   /* Compute the rounded size of the type.  */
3930   type_size = size_in_bytes (type);
3931   rounded_size = round_up (type_size, align);
3932
3933   /* Reduce rounded_size so it's sharable with the postqueue.  */
3934   gimplify_expr (&rounded_size, pre_p, post_p, is_gimple_val, fb_rvalue);
3935
3936   /* Get AP.  */
3937   addr = valist_tmp;
3938   if (PAD_VARARGS_DOWN && !integer_zerop (rounded_size))
3939     {
3940       /* Small args are padded downward.  */
3941       t = fold (build2 (GT_EXPR, sizetype, rounded_size, size_int (align)));
3942       t = fold (build3 (COND_EXPR, sizetype, t, size_zero_node,
3943                         size_binop (MINUS_EXPR, rounded_size, type_size)));
3944       t = fold_convert (TREE_TYPE (addr), t);
3945       addr = fold (build2 (PLUS_EXPR, TREE_TYPE (addr), addr, t));
3946     }
3947
3948   /* Compute new value for AP.  */
3949   t = fold_convert (TREE_TYPE (valist), rounded_size);
3950   t = build2 (PLUS_EXPR, TREE_TYPE (valist), valist_tmp, t);
3951   t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist, t);
3952   gimplify_and_add (t, pre_p);
3953
3954   addr = fold_convert (build_pointer_type (type), addr);
3955
3956   if (indirect)
3957     addr = build_va_arg_indirect_ref (addr);
3958
3959   return build_va_arg_indirect_ref (addr);
3960 }
3961
3962 /* Build an indirect-ref expression over the given TREE, which represents a
3963    piece of a va_arg() expansion.  */
3964 tree
3965 build_va_arg_indirect_ref (tree addr)
3966 {
3967   addr = build_fold_indirect_ref (addr);
3968
3969   if (flag_mudflap) /* Don't instrument va_arg INDIRECT_REF.  */
3970     mf_mark (addr);
3971
3972   return addr;
3973 }
3974
3975 /* Return a dummy expression of type TYPE in order to keep going after an
3976    error.  */
3977
3978 static tree
3979 dummy_object (tree type)
3980 {
3981   tree t = convert (build_pointer_type (type), null_pointer_node);
3982   return build1 (INDIRECT_REF, type, t);
3983 }
3984
3985 /* Gimplify __builtin_va_arg, aka VA_ARG_EXPR, which is not really a
3986    builtin function, but a very special sort of operator.  */
3987
3988 enum gimplify_status
3989 gimplify_va_arg_expr (tree *expr_p, tree *pre_p, tree *post_p)
3990 {
3991   tree promoted_type, want_va_type, have_va_type;
3992   tree valist = TREE_OPERAND (*expr_p, 0);
3993   tree type = TREE_TYPE (*expr_p);
3994   tree t;
3995
3996   /* Verify that valist is of the proper type.  */
3997   want_va_type = va_list_type_node;
3998   have_va_type = TREE_TYPE (valist);
3999
4000   if (have_va_type == error_mark_node)
4001     return GS_ERROR;
4002
4003   if (TREE_CODE (want_va_type) == ARRAY_TYPE)
4004     {
4005       /* If va_list is an array type, the argument may have decayed
4006          to a pointer type, e.g. by being passed to another function.
4007          In that case, unwrap both types so that we can compare the
4008          underlying records.  */
4009       if (TREE_CODE (have_va_type) == ARRAY_TYPE
4010           || TREE_CODE (have_va_type) == POINTER_TYPE)
4011         {
4012           want_va_type = TREE_TYPE (want_va_type);
4013           have_va_type = TREE_TYPE (have_va_type);
4014         }
4015     }
4016
4017   if (TYPE_MAIN_VARIANT (want_va_type) != TYPE_MAIN_VARIANT (have_va_type))
4018     {
4019       error ("first argument to %<va_arg%> not of type %<va_list%>");
4020       return GS_ERROR;
4021     }
4022
4023   /* Generate a diagnostic for requesting data of a type that cannot
4024      be passed through `...' due to type promotion at the call site.  */
4025   else if ((promoted_type = lang_hooks.types.type_promotes_to (type))
4026            != type)
4027     {
4028       static bool gave_help;
4029
4030       /* Unfortunately, this is merely undefined, rather than a constraint
4031          violation, so we cannot make this an error.  If this call is never
4032          executed, the program is still strictly conforming.  */
4033       warning ("%qT is promoted to %qT when passed through %<...%>",
4034                type, promoted_type);
4035       if (! gave_help)
4036         {
4037           gave_help = true;
4038           warning ("(so you should pass %qT not %qT to %<va_arg%>)",
4039                    promoted_type, type);
4040         }
4041
4042       /* We can, however, treat "undefined" any way we please.
4043          Call abort to encourage the user to fix the program.  */
4044       inform ("if this code is reached, the program will abort");
4045       t = build_function_call_expr (implicit_built_in_decls[BUILT_IN_TRAP],
4046                                     NULL);
4047       append_to_statement_list (t, pre_p);
4048
4049       /* This is dead code, but go ahead and finish so that the
4050          mode of the result comes out right.  */
4051       *expr_p = dummy_object (type);
4052       return GS_ALL_DONE;
4053     }
4054   else
4055     {
4056       /* Make it easier for the backends by protecting the valist argument
4057          from multiple evaluations.  */
4058       if (TREE_CODE (va_list_type_node) == ARRAY_TYPE)
4059         {
4060           /* For this case, the backends will be expecting a pointer to
4061              TREE_TYPE (va_list_type_node), but it's possible we've
4062              actually been given an array (an actual va_list_type_node).
4063              So fix it.  */
4064           if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
4065             {
4066               tree p1 = build_pointer_type (TREE_TYPE (va_list_type_node));
4067               valist = build_fold_addr_expr_with_type (valist, p1);
4068             }
4069           gimplify_expr (&valist, pre_p, post_p, is_gimple_val, fb_rvalue);
4070         }
4071       else
4072         gimplify_expr (&valist, pre_p, post_p, is_gimple_min_lval, fb_lvalue);
4073
4074       if (!targetm.gimplify_va_arg_expr)
4075         /* Once most targets are converted this should abort.  */
4076         return GS_ALL_DONE;
4077
4078       *expr_p = targetm.gimplify_va_arg_expr (valist, type, pre_p, post_p);
4079       return GS_OK;
4080     }
4081 }
4082
4083 /* Expand ARGLIST, from a call to __builtin_va_end.  */
4084
4085 static rtx
4086 expand_builtin_va_end (tree arglist)
4087 {
4088   tree valist = TREE_VALUE (arglist);
4089
4090   /* Evaluate for side effects, if needed.  I hate macros that don't
4091      do that.  */
4092   if (TREE_SIDE_EFFECTS (valist))
4093     expand_expr (valist, const0_rtx, VOIDmode, EXPAND_NORMAL);
4094
4095   return const0_rtx;
4096 }
4097
4098 /* Expand ARGLIST, from a call to __builtin_va_copy.  We do this as a
4099    builtin rather than just as an assignment in stdarg.h because of the
4100    nastiness of array-type va_list types.  */
4101
4102 static rtx
4103 expand_builtin_va_copy (tree arglist)
4104 {
4105   tree dst, src, t;
4106
4107   dst = TREE_VALUE (arglist);
4108   src = TREE_VALUE (TREE_CHAIN (arglist));
4109
4110   dst = stabilize_va_list (dst, 1);
4111   src = stabilize_va_list (src, 0);
4112
4113   if (TREE_CODE (va_list_type_node) != ARRAY_TYPE)
4114     {
4115       t = build2 (MODIFY_EXPR, va_list_type_node, dst, src);
4116       TREE_SIDE_EFFECTS (t) = 1;
4117       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4118     }
4119   else
4120     {
4121       rtx dstb, srcb, size;
4122
4123       /* Evaluate to pointers.  */
4124       dstb = expand_expr (dst, NULL_RTX, Pmode, EXPAND_NORMAL);
4125       srcb = expand_expr (src, NULL_RTX, Pmode, EXPAND_NORMAL);
4126       size = expand_expr (TYPE_SIZE_UNIT (va_list_type_node), NULL_RTX,
4127                           VOIDmode, EXPAND_NORMAL);
4128
4129       dstb = convert_memory_address (Pmode, dstb);
4130       srcb = convert_memory_address (Pmode, srcb);
4131
4132       /* "Dereference" to BLKmode memories.  */
4133       dstb = gen_rtx_MEM (BLKmode, dstb);
4134       set_mem_alias_set (dstb, get_alias_set (TREE_TYPE (TREE_TYPE (dst))));
4135       set_mem_align (dstb, TYPE_ALIGN (va_list_type_node));
4136       srcb = gen_rtx_MEM (BLKmode, srcb);
4137       set_mem_alias_set (srcb, get_alias_set (TREE_TYPE (TREE_TYPE (src))));
4138       set_mem_align (srcb, TYPE_ALIGN (va_list_type_node));
4139
4140       /* Copy.  */
4141       emit_block_move (dstb, srcb, size, BLOCK_OP_NORMAL);
4142     }
4143
4144   return const0_rtx;
4145 }
4146
4147 /* Expand a call to one of the builtin functions __builtin_frame_address or
4148    __builtin_return_address.  */
4149
4150 static rtx
4151 expand_builtin_frame_address (tree fndecl, tree arglist)
4152 {
4153   /* The argument must be a nonnegative integer constant.
4154      It counts the number of frames to scan up the stack.
4155      The value is the return address saved in that frame.  */
4156   if (arglist == 0)
4157     /* Warning about missing arg was already issued.  */
4158     return const0_rtx;
4159   else if (! host_integerp (TREE_VALUE (arglist), 1))
4160     {
4161       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4162         error ("invalid argument to %<__builtin_frame_address%>");
4163       else
4164         error ("invalid argument to %<__builtin_return_address%>");
4165       return const0_rtx;
4166     }
4167   else
4168     {
4169       rtx tem
4170         = expand_builtin_return_addr (DECL_FUNCTION_CODE (fndecl),
4171                                       tree_low_cst (TREE_VALUE (arglist), 1),
4172                                       hard_frame_pointer_rtx);
4173
4174       /* Some ports cannot access arbitrary stack frames.  */
4175       if (tem == NULL)
4176         {
4177           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4178             warning ("unsupported argument to %<__builtin_frame_address%>");
4179           else
4180             warning ("unsupported argument to %<__builtin_return_address%>");
4181           return const0_rtx;
4182         }
4183
4184       /* For __builtin_frame_address, return what we've got.  */
4185       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4186         return tem;
4187
4188       if (!REG_P (tem)
4189           && ! CONSTANT_P (tem))
4190         tem = copy_to_mode_reg (Pmode, tem);
4191       return tem;
4192     }
4193 }
4194
4195 /* Expand a call to the alloca builtin, with arguments ARGLIST.  Return 0 if
4196    we failed and the caller should emit a normal call, otherwise try to get
4197    the result in TARGET, if convenient.  */
4198
4199 static rtx
4200 expand_builtin_alloca (tree arglist, rtx target)
4201 {
4202   rtx op0;
4203   rtx result;
4204
4205   /* In -fmudflap-instrumented code, alloca() and __builtin_alloca()
4206      should always expand to function calls.  These can be intercepted
4207      in libmudflap.  */
4208   if (flag_mudflap)
4209     return 0;
4210
4211   if (!validate_arglist (arglist, INTEGER_TYPE, VOID_TYPE))
4212     return 0;
4213
4214   /* Compute the argument.  */
4215   op0 = expand_expr (TREE_VALUE (arglist), NULL_RTX, VOIDmode, 0);
4216
4217   /* Allocate the desired space.  */
4218   result = allocate_dynamic_stack_space (op0, target, BITS_PER_UNIT);
4219   result = convert_memory_address (ptr_mode, result);
4220
4221   return result;
4222 }
4223
4224 /* Expand a call to a unary builtin.  The arguments are in ARGLIST.
4225    Return 0 if a normal call should be emitted rather than expanding the
4226    function in-line.  If convenient, the result should be placed in TARGET.
4227    SUBTARGET may be used as the target for computing one of EXP's operands.  */
4228
4229 static rtx
4230 expand_builtin_unop (enum machine_mode target_mode, tree arglist, rtx target,
4231                      rtx subtarget, optab op_optab)
4232 {
4233   rtx op0;
4234   if (!validate_arglist (arglist, INTEGER_TYPE, VOID_TYPE))
4235     return 0;
4236
4237   /* Compute the argument.  */
4238   op0 = expand_expr (TREE_VALUE (arglist), subtarget, VOIDmode, 0);
4239   /* Compute op, into TARGET if possible.
4240      Set TARGET to wherever the result comes back.  */
4241   target = expand_unop (TYPE_MODE (TREE_TYPE (TREE_VALUE (arglist))),
4242                         op_optab, op0, target, 1);
4243   gcc_assert (target);
4244
4245   return convert_to_mode (target_mode, target, 0);
4246 }
4247
4248 /* If the string passed to fputs is a constant and is one character
4249    long, we attempt to transform this call into __builtin_fputc().  */
4250
4251 static rtx
4252 expand_builtin_fputs (tree arglist, rtx target, bool unlocked)
4253 {
4254   /* Verify the arguments in the original call.  */
4255   if (validate_arglist (arglist, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
4256     {
4257       tree result = fold_builtin_fputs (arglist, (target == const0_rtx),
4258                                         unlocked, NULL_TREE);
4259       if (result)
4260         return expand_expr (result, target, VOIDmode, EXPAND_NORMAL);
4261     }
4262   return 0;
4263 }
4264
4265 /* Expand a call to __builtin_expect.  We return our argument and emit a
4266    NOTE_INSN_EXPECTED_VALUE note.  This is the expansion of __builtin_expect in
4267    a non-jump context.  */
4268
4269 static rtx
4270 expand_builtin_expect (tree arglist, rtx target)
4271 {
4272   tree exp, c;
4273   rtx note, rtx_c;
4274
4275   if (arglist == NULL_TREE
4276       || TREE_CHAIN (arglist) == NULL_TREE)
4277     return const0_rtx;
4278   exp = TREE_VALUE (arglist);
4279   c = TREE_VALUE (TREE_CHAIN (arglist));
4280
4281   if (TREE_CODE (c) != INTEGER_CST)
4282     {
4283       error ("second argument to %<__builtin_expect%> must be a constant");
4284       c = integer_zero_node;
4285     }
4286
4287   target = expand_expr (exp, target, VOIDmode, EXPAND_NORMAL);
4288
4289   /* Don't bother with expected value notes for integral constants.  */
4290   if (flag_guess_branch_prob && GET_CODE (target) != CONST_INT)
4291     {
4292       /* We do need to force this into a register so that we can be
4293          moderately sure to be able to correctly interpret the branch
4294          condition later.  */
4295       target = force_reg (GET_MODE (target), target);
4296
4297       rtx_c = expand_expr (c, NULL_RTX, GET_MODE (target), EXPAND_NORMAL);
4298
4299       note = emit_note (NOTE_INSN_EXPECTED_VALUE);
4300       NOTE_EXPECTED_VALUE (note) = gen_rtx_EQ (VOIDmode, target, rtx_c);
4301     }
4302
4303   return target;
4304 }
4305
4306 /* Like expand_builtin_expect, except do this in a jump context.  This is
4307    called from do_jump if the conditional is a __builtin_expect.  Return either
4308    a list of insns to emit the jump or NULL if we cannot optimize
4309    __builtin_expect.  We need to optimize this at jump time so that machines
4310    like the PowerPC don't turn the test into a SCC operation, and then jump
4311    based on the test being 0/1.  */
4312
4313 rtx
4314 expand_builtin_expect_jump (tree exp, rtx if_false_label, rtx if_true_label)
4315 {
4316   tree arglist = TREE_OPERAND (exp, 1);
4317   tree arg0 = TREE_VALUE (arglist);
4318   tree arg1 = TREE_VALUE (TREE_CHAIN (arglist));
4319   rtx ret = NULL_RTX;
4320
4321   /* Only handle __builtin_expect (test, 0) and
4322      __builtin_expect (test, 1).  */
4323   if (TREE_CODE (TREE_TYPE (arg1)) == INTEGER_TYPE
4324       && (integer_zerop (arg1) || integer_onep (arg1)))
4325     {
4326       rtx insn, drop_through_label, temp;
4327
4328       /* Expand the jump insns.  */
4329       start_sequence ();
4330       do_jump (arg0, if_false_label, if_true_label);
4331       ret = get_insns ();
4332
4333       drop_through_label = get_last_insn ();
4334       if (drop_through_label && NOTE_P (drop_through_label))
4335         drop_through_label = prev_nonnote_insn (drop_through_label);
4336       if (drop_through_label && !LABEL_P (drop_through_label))
4337         drop_through_label = NULL_RTX;
4338       end_sequence ();
4339
4340       if (! if_true_label)
4341         if_true_label = drop_through_label;
4342       if (! if_false_label)
4343         if_false_label = drop_through_label;
4344
4345       /* Go through and add the expect's to each of the conditional jumps.  */
4346       insn = ret;
4347       while (insn != NULL_RTX)
4348         {
4349           rtx next = NEXT_INSN (insn);
4350
4351           if (JUMP_P (insn) && any_condjump_p (insn))
4352             {
4353               rtx ifelse = SET_SRC (pc_set (insn));
4354               rtx then_dest = XEXP (ifelse, 1);
4355               rtx else_dest = XEXP (ifelse, 2);
4356               int taken = -1;
4357
4358               /* First check if we recognize any of the labels.  */
4359               if (GET_CODE (then_dest) == LABEL_REF
4360                   && XEXP (then_dest, 0) == if_true_label)
4361                 taken = 1;
4362               else if (GET_CODE (then_dest) == LABEL_REF
4363                        && XEXP (then_dest, 0) == if_false_label)
4364                 taken = 0;
4365               else if (GET_CODE (else_dest) == LABEL_REF
4366                        && XEXP (else_dest, 0) == if_false_label)
4367                 taken = 1;
4368               else if (GET_CODE (else_dest) == LABEL_REF
4369                        && XEXP (else_dest, 0) == if_true_label)
4370                 taken = 0;
4371               /* Otherwise check where we drop through.  */
4372               else if (else_dest == pc_rtx)
4373                 {
4374                   if (next && NOTE_P (next))
4375                     next = next_nonnote_insn (next);
4376
4377                   if (next && JUMP_P (next)
4378                       && any_uncondjump_p (next))
4379                     temp = XEXP (SET_SRC (pc_set (next)), 0);
4380                   else
4381                     temp = next;
4382
4383                   /* TEMP is either a CODE_LABEL, NULL_RTX or something
4384                      else that can't possibly match either target label.  */
4385                   if (temp == if_false_label)
4386                     taken = 1;
4387                   else if (temp == if_true_label)
4388                     taken = 0;
4389                 }
4390               else if (then_dest == pc_rtx)
4391                 {
4392                   if (next && NOTE_P (next))
4393                     next = next_nonnote_insn (next);
4394
4395                   if (next && JUMP_P (next)
4396                       && any_uncondjump_p (next))
4397                     temp = XEXP (SET_SRC (pc_set (next)), 0);
4398                   else
4399                     temp = next;
4400
4401                   if (temp == if_false_label)
4402                     taken = 0;
4403                   else if (temp == if_true_label)
4404                     taken = 1;
4405                 }
4406
4407               if (taken != -1)
4408                 {
4409                   /* If the test is expected to fail, reverse the
4410                      probabilities.  */
4411                   if (integer_zerop (arg1))
4412                     taken = 1 - taken;
4413                   predict_insn_def (insn, PRED_BUILTIN_EXPECT, taken);
4414                 }
4415             }
4416
4417           insn = next;
4418         }
4419     }
4420
4421   return ret;
4422 }
4423
4424 static void
4425 expand_builtin_trap (void)
4426 {
4427 #ifdef HAVE_trap
4428   if (HAVE_trap)
4429     emit_insn (gen_trap ());
4430   else
4431 #endif
4432     emit_library_call (abort_libfunc, LCT_NORETURN, VOIDmode, 0);
4433   emit_barrier ();
4434 }
4435
4436 /* Expand a call to fabs, fabsf or fabsl with arguments ARGLIST.
4437    Return 0 if a normal call should be emitted rather than expanding
4438    the function inline.  If convenient, the result should be placed
4439    in TARGET.  SUBTARGET may be used as the target for computing
4440    the operand.  */
4441
4442 static rtx
4443 expand_builtin_fabs (tree arglist, rtx target, rtx subtarget)
4444 {
4445   enum machine_mode mode;
4446   tree arg;
4447   rtx op0;
4448
4449   if (!validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
4450     return 0;
4451
4452   arg = TREE_VALUE (arglist);
4453   mode = TYPE_MODE (TREE_TYPE (arg));
4454   op0 = expand_expr (arg, subtarget, VOIDmode, 0);
4455   return expand_abs (mode, op0, target, 0, safe_from_p (target, arg, 1));
4456 }
4457
4458 /* Create a new constant string literal and return a char* pointer to it.
4459    The STRING_CST value is the LEN characters at STR.  */
4460 static tree
4461 build_string_literal (int len, const char *str)
4462 {
4463   tree t, elem, index, type;
4464
4465   t = build_string (len, str);
4466   elem = build_type_variant (char_type_node, 1, 0);
4467   index = build_index_type (build_int_cst (NULL_TREE, len - 1));
4468   type = build_array_type (elem, index);
4469   TREE_TYPE (t) = type;
4470   TREE_CONSTANT (t) = 1;
4471   TREE_INVARIANT (t) = 1;
4472   TREE_READONLY (t) = 1;
4473   TREE_STATIC (t) = 1;
4474
4475   type = build_pointer_type (type);
4476   t = build1 (ADDR_EXPR, type, t);
4477
4478   type = build_pointer_type (elem);
4479   t = build1 (NOP_EXPR, type, t);
4480   return t;
4481 }
4482
4483 /* Expand a call to printf or printf_unlocked with argument list ARGLIST.
4484    Return 0 if a normal call should be emitted rather than transforming
4485    the function inline.  If convenient, the result should be placed in
4486    TARGET with mode MODE.  UNLOCKED indicates this is a printf_unlocked
4487    call.  */
4488 static rtx
4489 expand_builtin_printf (tree arglist, rtx target, enum machine_mode mode,
4490                        bool unlocked)
4491 {
4492   tree fn_putchar = unlocked
4493                     ? implicit_built_in_decls[BUILT_IN_PUTCHAR_UNLOCKED]
4494                     : implicit_built_in_decls[BUILT_IN_PUTCHAR];
4495   tree fn_puts = unlocked ? implicit_built_in_decls[BUILT_IN_PUTS_UNLOCKED]
4496                           : implicit_built_in_decls[BUILT_IN_PUTS];
4497   const char *fmt_str;
4498   tree fn, fmt, arg;
4499
4500   /* If the return value is used, don't do the transformation.  */
4501   if (target != const0_rtx)
4502     return 0;
4503
4504   /* Verify the required arguments in the original call.  */
4505   if (! arglist)
4506     return 0;
4507   fmt = TREE_VALUE (arglist);
4508   if (TREE_CODE (TREE_TYPE (fmt)) != POINTER_TYPE)
4509     return 0;
4510   arglist = TREE_CHAIN (arglist);
4511
4512   /* Check whether the format is a literal string constant.  */
4513   fmt_str = c_getstr (fmt);
4514   if (fmt_str == NULL)
4515     return 0;
4516
4517   /* If the format specifier was "%s\n", call __builtin_puts(arg).  */
4518   if (strcmp (fmt_str, "%s\n") == 0)
4519     {
4520       if (! arglist
4521           || TREE_CODE (TREE_TYPE (TREE_VALUE (arglist))) != POINTER_TYPE
4522           || TREE_CHAIN (arglist))
4523         return 0;
4524       fn = fn_puts;
4525     }
4526   /* If the format specifier was "%c", call __builtin_putchar(arg).  */
4527   else if (strcmp (fmt_str, "%c") == 0)
4528     {
4529       if (! arglist
4530           || TREE_CODE (TREE_TYPE (TREE_VALUE (arglist))) != INTEGER_TYPE
4531           || TREE_CHAIN (arglist))
4532         return 0;
4533       fn = fn_putchar;
4534     }
4535   else
4536     {
4537       /* We can't handle anything else with % args or %% ... yet.  */
4538       if (strchr (fmt_str, '%'))
4539         return 0;
4540
4541       if (arglist)
4542         return 0;
4543
4544       /* If the format specifier was "", printf does nothing.  */
4545       if (fmt_str[0] == '\0')
4546         return const0_rtx;
4547       /* If the format specifier has length of 1, call putchar.  */
4548       if (fmt_str[1] == '\0')
4549         {
4550           /* Given printf("c"), (where c is any one character,)
4551              convert "c"[0] to an int and pass that to the replacement
4552              function.  */
4553           arg = build_int_cst (NULL_TREE, fmt_str[0]);
4554           arglist = build_tree_list (NULL_TREE, arg);
4555           fn = fn_putchar;
4556         }
4557       else
4558         {
4559           /* If the format specifier was "string\n", call puts("string").  */
4560           size_t len = strlen (fmt_str);
4561           if (fmt_str[len - 1] == '\n')
4562             {
4563               /* Create a NUL-terminated string that's one char shorter
4564                  than the original, stripping off the trailing '\n'.  */
4565               char *newstr = alloca (len);
4566               memcpy (newstr, fmt_str, len - 1);
4567               newstr[len - 1] = 0;
4568
4569               arg = build_string_literal (len, newstr);
4570               arglist = build_tree_list (NULL_TREE, arg);
4571               fn = fn_puts;
4572             }
4573           else
4574             /* We'd like to arrange to call fputs(string,stdout) here,
4575                but we need stdout and don't have a way to get it yet.  */
4576             return 0;
4577         }
4578     }
4579
4580   if (!fn)
4581     return 0;
4582   return expand_expr (build_function_call_expr (fn, arglist),
4583                       target, mode, EXPAND_NORMAL);
4584 }
4585
4586 /* Expand a call to fprintf or fprintf_unlocked with argument list ARGLIST.
4587    Return 0 if a normal call should be emitted rather than transforming
4588    the function inline.  If convenient, the result should be placed in
4589    TARGET with mode MODE.  UNLOCKED indicates this is a fprintf_unlocked
4590    call.  */
4591 static rtx
4592 expand_builtin_fprintf (tree arglist, rtx target, enum machine_mode mode,
4593                         bool unlocked)
4594 {
4595   tree fn_fputc = unlocked ? implicit_built_in_decls[BUILT_IN_FPUTC_UNLOCKED]
4596                            : implicit_built_in_decls[BUILT_IN_FPUTC];
4597   tree fn_fputs = unlocked ? implicit_built_in_decls[BUILT_IN_FPUTS_UNLOCKED]
4598                            : implicit_built_in_decls[BUILT_IN_FPUTS];
4599   const char *fmt_str;
4600   tree fn, fmt, fp, arg;
4601
4602   /* If the return value is used, don't do the transformation.  */
4603   if (target != const0_rtx)
4604     return 0;
4605
4606   /* Verify the required arguments in the original call.  */
4607   if (! arglist)
4608     return 0;
4609   fp = TREE_VALUE (arglist);
4610   if (TREE_CODE (TREE_TYPE (fp)) != POINTER_TYPE)
4611     return 0;
4612   arglist = TREE_CHAIN (arglist);
4613   if (! arglist)
4614     return 0;
4615   fmt = TREE_VALUE (arglist);
4616   if (TREE_CODE (TREE_TYPE (fmt)) != POINTER_TYPE)
4617     return 0;
4618   arglist = TREE_CHAIN (arglist);
4619
4620   /* Check whether the format is a literal string constant.  */
4621   fmt_str = c_getstr (fmt);
4622   if (fmt_str == NULL)
4623     return 0;
4624
4625   /* If the format specifier was "%s", call __builtin_fputs(arg,fp).  */
4626   if (strcmp (fmt_str, "%s") == 0)
4627     {
4628       if (! arglist
4629           || TREE_CODE (TREE_TYPE (TREE_VALUE (arglist))) != POINTER_TYPE
4630           || TREE_CHAIN (arglist))
4631         return 0;
4632       arg = TREE_VALUE (arglist);
4633       arglist = build_tree_list (NULL_TREE, fp);
4634       arglist = tree_cons (NULL_TREE, arg, arglist);
4635       fn = fn_fputs;
4636     }
4637   /* If the format specifier was "%c", call __builtin_fputc(arg,fp).  */
4638   else if (strcmp (fmt_str, "%c") == 0)
4639     {
4640       if (! arglist
4641           || TREE_CODE (TREE_TYPE (TREE_VALUE (arglist))) != INTEGER_TYPE
4642           || TREE_CHAIN (arglist))
4643         return 0;
4644       arg = TREE_VALUE (arglist);
4645       arglist = build_tree_list (NULL_TREE, fp);
4646       arglist = tree_cons (NULL_TREE, arg, arglist);
4647       fn = fn_fputc;
4648     }
4649   else
4650     {
4651       /* We can't handle anything else with % args or %% ... yet.  */
4652       if (strchr (fmt_str, '%'))
4653         return 0;
4654
4655       if (arglist)
4656         return 0;
4657
4658       /* If the format specifier was "", fprintf does nothing.  */
4659       if (fmt_str[0] == '\0')
4660         {
4661           /* Evaluate and ignore FILE* argument for side-effects.  */
4662           expand_expr (fp, const0_rtx, VOIDmode, EXPAND_NORMAL);
4663           return const0_rtx;
4664         }
4665
4666       /* When "string" doesn't contain %, replace all cases of
4667          fprintf(stream,string) with fputs(string,stream).  The fputs
4668          builtin will take care of special cases like length == 1.  */
4669       arglist = build_tree_list (NULL_TREE, fp);
4670       arglist = tree_cons (NULL_TREE, fmt, arglist);
4671       fn = fn_fputs;
4672     }
4673
4674   if (!fn)
4675     return 0;
4676   return expand_expr (build_function_call_expr (fn, arglist),
4677                       target, mode, EXPAND_NORMAL);
4678 }
4679
4680 /* Expand a call to sprintf with argument list ARGLIST.  Return 0 if
4681    a normal call should be emitted rather than expanding the function
4682    inline.  If convenient, the result should be placed in TARGET with
4683    mode MODE.  */
4684
4685 static rtx
4686 expand_builtin_sprintf (tree arglist, rtx target, enum machine_mode mode)
4687 {
4688   tree orig_arglist, dest, fmt;
4689   const char *fmt_str;
4690
4691   orig_arglist = arglist;
4692
4693   /* Verify the required arguments in the original call.  */
4694   if (! arglist)
4695     return 0;
4696   dest = TREE_VALUE (arglist);
4697   if (TREE_CODE (TREE_TYPE (dest)) != POINTER_TYPE)
4698     return 0;
4699   arglist = TREE_CHAIN (arglist);
4700   if (! arglist)
4701     return 0;
4702   fmt = TREE_VALUE (arglist);
4703   if (TREE_CODE (TREE_TYPE (fmt)) != POINTER_TYPE)
4704     return 0;
4705   arglist = TREE_CHAIN (arglist);
4706
4707   /* Check whether the format is a literal string constant.  */
4708   fmt_str = c_getstr (fmt);
4709   if (fmt_str == NULL)
4710     return 0;
4711
4712   /* If the format doesn't contain % args or %%, use strcpy.  */
4713   if (strchr (fmt_str, '%') == 0)
4714     {
4715       tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
4716       tree exp;
4717
4718       if (arglist || ! fn)
4719         return 0;
4720       expand_expr (build_function_call_expr (fn, orig_arglist),
4721                    const0_rtx, VOIDmode, EXPAND_NORMAL);
4722       if (target == const0_rtx)
4723         return const0_rtx;
4724       exp = build_int_cst (NULL_TREE, strlen (fmt_str));
4725       return expand_expr (exp, target, mode, EXPAND_NORMAL);
4726     }
4727   /* If the format is "%s", use strcpy if the result isn't used.  */
4728   else if (strcmp (fmt_str, "%s") == 0)
4729     {
4730       tree fn, arg, len;
4731       fn = implicit_built_in_decls[BUILT_IN_STRCPY];
4732
4733       if (! fn)
4734         return 0;
4735
4736       if (! arglist || TREE_CHAIN (arglist))
4737         return 0;
4738       arg = TREE_VALUE (arglist);
4739       if (TREE_CODE (TREE_TYPE (arg)) != POINTER_TYPE)
4740         return 0;
4741
4742       if (target != const0_rtx)
4743         {
4744           len = c_strlen (arg, 1);
4745           if (! len || TREE_CODE (len) != INTEGER_CST)
4746             return 0;
4747         }
4748       else
4749         len = NULL_TREE;
4750
4751       arglist = build_tree_list (NULL_TREE, arg);
4752       arglist = tree_cons (NULL_TREE, dest, arglist);
4753       expand_expr (build_function_call_expr (fn, arglist),
4754                    const0_rtx, VOIDmode, EXPAND_NORMAL);
4755
4756       if (target == const0_rtx)
4757         return const0_rtx;
4758       return expand_expr (len, target, mode, EXPAND_NORMAL);
4759     }
4760
4761   return 0;
4762 }
4763
4764 /* Expand a call to either the entry or exit function profiler.  */
4765
4766 static rtx
4767 expand_builtin_profile_func (bool exitp)
4768 {
4769   rtx this, which;
4770
4771   this = DECL_RTL (current_function_decl);
4772   gcc_assert (MEM_P (this));
4773   this = XEXP (this, 0);
4774
4775   if (exitp)
4776     which = profile_function_exit_libfunc;
4777   else
4778     which = profile_function_entry_libfunc;
4779
4780   emit_library_call (which, LCT_NORMAL, VOIDmode, 2, this, Pmode,
4781                      expand_builtin_return_addr (BUILT_IN_RETURN_ADDRESS,
4782                                                  0, hard_frame_pointer_rtx),
4783                      Pmode);
4784
4785   return const0_rtx;
4786 }
4787
4788 /* Given a trampoline address, make sure it satisfies TRAMPOLINE_ALIGNMENT.  */
4789
4790 static rtx
4791 round_trampoline_addr (rtx tramp)
4792 {
4793   rtx temp, addend, mask;
4794
4795   /* If we don't need too much alignment, we'll have been guaranteed
4796      proper alignment by get_trampoline_type.  */
4797   if (TRAMPOLINE_ALIGNMENT <= STACK_BOUNDARY)
4798     return tramp;
4799
4800   /* Round address up to desired boundary.  */
4801   temp = gen_reg_rtx (Pmode);
4802   addend = GEN_INT (TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT - 1);
4803   mask = GEN_INT (-TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT);
4804
4805   temp  = expand_simple_binop (Pmode, PLUS, tramp, addend,
4806                                temp, 0, OPTAB_LIB_WIDEN);
4807   tramp = expand_simple_binop (Pmode, AND, temp, mask,
4808                                temp, 0, OPTAB_LIB_WIDEN);
4809
4810   return tramp;
4811 }
4812
4813 static rtx
4814 expand_builtin_init_trampoline (tree arglist)
4815 {
4816   tree t_tramp, t_func, t_chain;
4817   rtx r_tramp, r_func, r_chain;
4818 #ifdef TRAMPOLINE_TEMPLATE
4819   rtx blktramp;
4820 #endif
4821
4822   if (!validate_arglist (arglist, POINTER_TYPE, POINTER_TYPE,
4823                          POINTER_TYPE, VOID_TYPE))
4824     return NULL_RTX;
4825
4826   t_tramp = TREE_VALUE (arglist);
4827   arglist = TREE_CHAIN (arglist);
4828   t_func = TREE_VALUE (arglist);
4829   arglist = TREE_CHAIN (arglist);
4830   t_chain = TREE_VALUE (arglist);
4831
4832   r_tramp = expand_expr (t_tramp, NULL_RTX, VOIDmode, 0);
4833   r_func = expand_expr (t_func, NULL_RTX, VOIDmode, 0);
4834   r_chain = expand_expr (t_chain, NULL_RTX, VOIDmode, 0);
4835
4836   /* Generate insns to initialize the trampoline.  */
4837   r_tramp = round_trampoline_addr (r_tramp);
4838 #ifdef TRAMPOLINE_TEMPLATE
4839   blktramp = gen_rtx_MEM (BLKmode, r_tramp);
4840   set_mem_align (blktramp, TRAMPOLINE_ALIGNMENT);
4841   emit_block_move (blktramp, assemble_trampoline_template (),
4842                    GEN_INT (TRAMPOLINE_SIZE), BLOCK_OP_NORMAL);
4843 #endif
4844   trampolines_created = 1;
4845   INITIALIZE_TRAMPOLINE (r_tramp, r_func, r_chain);
4846
4847   return const0_rtx;
4848 }
4849
4850 static rtx
4851 expand_builtin_adjust_trampoline (tree arglist)
4852 {
4853   rtx tramp;
4854
4855   if (!validate_arglist (arglist, POINTER_TYPE, VOID_TYPE))
4856     return NULL_RTX;
4857
4858   tramp = expand_expr (TREE_VALUE (arglist), NULL_RTX, VOIDmode, 0);
4859   tramp = round_trampoline_addr (tramp);
4860 #ifdef TRAMPOLINE_ADJUST_ADDRESS
4861   TRAMPOLINE_ADJUST_ADDRESS (tramp);
4862 #endif
4863
4864   return tramp;
4865 }
4866
4867 /* Expand a call to the built-in signbit, signbitf or signbitl function.
4868    Return NULL_RTX if a normal call should be emitted rather than expanding
4869    the function in-line.  EXP is the expression that is a call to the builtin
4870    function; if convenient, the result should be placed in TARGET.  */
4871
4872 static rtx
4873 expand_builtin_signbit (tree exp, rtx target)
4874 {
4875   const struct real_format *fmt;
4876   enum machine_mode fmode, imode, rmode;
4877   HOST_WIDE_INT hi, lo;
4878   tree arg, arglist;
4879   int bitpos;
4880   rtx temp;
4881
4882   arglist = TREE_OPERAND (exp, 1);
4883   if (!validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
4884     return 0;
4885
4886   arg = TREE_VALUE (arglist);
4887   fmode = TYPE_MODE (TREE_TYPE (arg));
4888   rmode = TYPE_MODE (TREE_TYPE (exp));
4889   fmt = REAL_MODE_FORMAT (fmode);
4890
4891   /* For floating point formats without a sign bit, implement signbit
4892      as "ARG < 0.0".  */
4893   if (fmt->signbit < 0)
4894   {
4895     /* But we can't do this if the format supports signed zero.  */
4896     if (fmt->has_signed_zero && HONOR_SIGNED_ZEROS (fmode))
4897       return 0;
4898
4899     arg = fold (build2 (LT_EXPR, TREE_TYPE (exp), arg,
4900                         build_real (TREE_TYPE (arg), dconst0)));
4901     return expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
4902   }
4903
4904   imode = int_mode_for_mode (fmode);
4905   if (imode == BLKmode)
4906     return 0;
4907
4908   bitpos = fmt->signbit;
4909   /* Handle targets with different FP word orders.  */
4910   if (FLOAT_WORDS_BIG_ENDIAN != WORDS_BIG_ENDIAN)
4911     {
4912       int nwords = GET_MODE_BITSIZE (fmode) / BITS_PER_WORD;
4913       int word = nwords - (bitpos / BITS_PER_WORD) - 1;
4914       bitpos = word * BITS_PER_WORD + bitpos % BITS_PER_WORD;
4915     }
4916
4917   /* If the sign bit is not in the lowpart and the floating point format
4918      is wider than an integer, check that is twice the size of an integer
4919      so that we can use gen_highpart below.  */
4920   if (bitpos >= GET_MODE_BITSIZE (rmode)
4921       && GET_MODE_BITSIZE (imode) != 2 * GET_MODE_BITSIZE (rmode))
4922     return 0;
4923
4924   temp = expand_expr (arg, NULL_RTX, VOIDmode, 0);
4925   temp = gen_lowpart (imode, temp);
4926
4927   if (GET_MODE_BITSIZE (imode) > GET_MODE_BITSIZE (rmode))
4928     {
4929       if (BYTES_BIG_ENDIAN)
4930         bitpos = GET_MODE_BITSIZE (imode) - 1 - bitpos;
4931       temp = copy_to_mode_reg (imode, temp);
4932       temp = extract_bit_field (temp, 1, bitpos, 1,
4933                                 NULL_RTX, rmode, rmode);
4934     }
4935   else
4936     {
4937       if (GET_MODE_BITSIZE (imode) < GET_MODE_BITSIZE (rmode))
4938         temp = gen_lowpart (rmode, temp);
4939       if (bitpos < HOST_BITS_PER_WIDE_INT)
4940         {
4941           hi = 0;
4942           lo = (HOST_WIDE_INT) 1 << bitpos;
4943         }
4944       else
4945         {
4946           hi = (HOST_WIDE_INT) 1 << (bitpos - HOST_BITS_PER_WIDE_INT);
4947           lo = 0;
4948         }
4949
4950       temp = force_reg (rmode, temp);
4951       temp = expand_binop (rmode, and_optab, temp,
4952                            immed_double_const (lo, hi, rmode),
4953                            target, 1, OPTAB_LIB_WIDEN);
4954     }
4955   return temp;
4956 }
4957
4958 /* Expand fork or exec calls.  TARGET is the desired target of the
4959    call.  ARGLIST is the list of arguments of the call.  FN is the
4960    identificator of the actual function.  IGNORE is nonzero if the
4961    value is to be ignored.  */
4962
4963 static rtx
4964 expand_builtin_fork_or_exec (tree fn, tree arglist, rtx target, int ignore)
4965 {
4966   tree id, decl;
4967   tree call;
4968
4969   /* If we are not profiling, just call the function.  */
4970   if (!profile_arc_flag)
4971     return NULL_RTX;
4972
4973   /* Otherwise call the wrapper.  This should be equivalent for the rest of
4974      compiler, so the code does not diverge, and the wrapper may run the
4975      code necessary for keeping the profiling sane.  */
4976
4977   switch (DECL_FUNCTION_CODE (fn))
4978     {
4979     case BUILT_IN_FORK:
4980       id = get_identifier ("__gcov_fork");
4981       break;
4982
4983     case BUILT_IN_EXECL:
4984       id = get_identifier ("__gcov_execl");
4985       break;
4986
4987     case BUILT_IN_EXECV:
4988       id = get_identifier ("__gcov_execv");
4989       break;
4990
4991     case BUILT_IN_EXECLP:
4992       id = get_identifier ("__gcov_execlp");
4993       break;
4994
4995     case BUILT_IN_EXECLE:
4996       id = get_identifier ("__gcov_execle");
4997       break;
4998
4999     case BUILT_IN_EXECVP:
5000       id = get_identifier ("__gcov_execvp");
5001       break;
5002
5003     case BUILT_IN_EXECVE:
5004       id = get_identifier ("__gcov_execve");
5005       break;
5006
5007     default:
5008       gcc_unreachable ();
5009     }
5010
5011   decl = build_decl (FUNCTION_DECL, id, TREE_TYPE (fn));
5012   DECL_EXTERNAL (decl) = 1;
5013   TREE_PUBLIC (decl) = 1;
5014   DECL_ARTIFICIAL (decl) = 1;
5015   TREE_NOTHROW (decl) = 1;
5016   call = build_function_call_expr (decl, arglist);
5017
5018   return expand_call (call, target, ignore);
5019 }
5020 \f
5021 /* Expand an expression EXP that calls a built-in function,
5022    with result going to TARGET if that's convenient
5023    (and in mode MODE if that's convenient).
5024    SUBTARGET may be used as the target for computing one of EXP's operands.
5025    IGNORE is nonzero if the value is to be ignored.  */
5026
5027 rtx
5028 expand_builtin (tree exp, rtx target, rtx subtarget, enum machine_mode mode,
5029                 int ignore)
5030 {
5031   tree fndecl = get_callee_fndecl (exp);
5032   tree arglist = TREE_OPERAND (exp, 1);
5033   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5034   enum machine_mode target_mode = TYPE_MODE (TREE_TYPE (exp));
5035
5036   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
5037     return targetm.expand_builtin (exp, target, subtarget, mode, ignore);
5038
5039   /* When not optimizing, generate calls to library functions for a certain
5040      set of builtins.  */
5041   if (!optimize
5042       && !CALLED_AS_BUILT_IN (fndecl)
5043       && DECL_ASSEMBLER_NAME_SET_P (fndecl)
5044       && fcode != BUILT_IN_ALLOCA)
5045     return expand_call (exp, target, ignore);
5046
5047   /* The built-in function expanders test for target == const0_rtx
5048      to determine whether the function's result will be ignored.  */
5049   if (ignore)
5050     target = const0_rtx;
5051
5052   /* If the result of a pure or const built-in function is ignored, and
5053      none of its arguments are volatile, we can avoid expanding the
5054      built-in call and just evaluate the arguments for side-effects.  */
5055   if (target == const0_rtx
5056       && (DECL_IS_PURE (fndecl) || TREE_READONLY (fndecl)))
5057     {
5058       bool volatilep = false;
5059       tree arg;
5060
5061       for (arg = arglist; arg; arg = TREE_CHAIN (arg))
5062         if (TREE_THIS_VOLATILE (TREE_VALUE (arg)))
5063           {
5064             volatilep = true;
5065             break;
5066           }
5067
5068       if (! volatilep)
5069         {
5070           for (arg = arglist; arg; arg = TREE_CHAIN (arg))
5071             expand_expr (TREE_VALUE (arg), const0_rtx,
5072                          VOIDmode, EXPAND_NORMAL);
5073           return const0_rtx;
5074         }
5075     }
5076
5077   switch (fcode)
5078     {
5079     case BUILT_IN_FABS:
5080     case BUILT_IN_FABSF:
5081     case BUILT_IN_FABSL:
5082       target = expand_builtin_fabs (arglist, target, subtarget);
5083       if (target)
5084         return target;
5085       break;
5086
5087       /* Just do a normal library call if we were unable to fold
5088          the values.  */
5089     case BUILT_IN_CABS:
5090     case BUILT_IN_CABSF:
5091     case BUILT_IN_CABSL:
5092       break;
5093
5094     case BUILT_IN_EXP:
5095     case BUILT_IN_EXPF:
5096     case BUILT_IN_EXPL:
5097     case BUILT_IN_EXP10:
5098     case BUILT_IN_EXP10F:
5099     case BUILT_IN_EXP10L:
5100     case BUILT_IN_POW10:
5101     case BUILT_IN_POW10F:
5102     case BUILT_IN_POW10L:
5103     case BUILT_IN_EXP2:
5104     case BUILT_IN_EXP2F:
5105     case BUILT_IN_EXP2L:
5106     case BUILT_IN_EXPM1:
5107     case BUILT_IN_EXPM1F:
5108     case BUILT_IN_EXPM1L:
5109     case BUILT_IN_LOGB:
5110     case BUILT_IN_LOGBF:
5111     case BUILT_IN_LOGBL:
5112     case BUILT_IN_ILOGB:
5113     case BUILT_IN_ILOGBF:
5114     case BUILT_IN_ILOGBL:
5115     case BUILT_IN_LOG:
5116     case BUILT_IN_LOGF:
5117     case BUILT_IN_LOGL:
5118     case BUILT_IN_LOG10:
5119     case BUILT_IN_LOG10F:
5120     case BUILT_IN_LOG10L:
5121     case BUILT_IN_LOG2:
5122     case BUILT_IN_LOG2F:
5123     case BUILT_IN_LOG2L:
5124     case BUILT_IN_LOG1P:
5125     case BUILT_IN_LOG1PF:
5126     case BUILT_IN_LOG1PL:
5127     case BUILT_IN_TAN:
5128     case BUILT_IN_TANF:
5129     case BUILT_IN_TANL:
5130     case BUILT_IN_ASIN:
5131     case BUILT_IN_ASINF:
5132     case BUILT_IN_ASINL:
5133     case BUILT_IN_ACOS:
5134     case BUILT_IN_ACOSF:
5135     case BUILT_IN_ACOSL:
5136     case BUILT_IN_ATAN:
5137     case BUILT_IN_ATANF:
5138     case BUILT_IN_ATANL:
5139       /* Treat these like sqrt only if unsafe math optimizations are allowed,
5140          because of possible accuracy problems.  */
5141       if (! flag_unsafe_math_optimizations)
5142         break;
5143     case BUILT_IN_SQRT:
5144     case BUILT_IN_SQRTF:
5145     case BUILT_IN_SQRTL:
5146     case BUILT_IN_FLOOR:
5147     case BUILT_IN_FLOORF:
5148     case BUILT_IN_FLOORL:
5149     case BUILT_IN_CEIL:
5150     case BUILT_IN_CEILF:
5151     case BUILT_IN_CEILL:
5152     case BUILT_IN_TRUNC:
5153     case BUILT_IN_TRUNCF:
5154     case BUILT_IN_TRUNCL:
5155     case BUILT_IN_ROUND:
5156     case BUILT_IN_ROUNDF:
5157     case BUILT_IN_ROUNDL:
5158     case BUILT_IN_NEARBYINT:
5159     case BUILT_IN_NEARBYINTF:
5160     case BUILT_IN_NEARBYINTL:
5161     case BUILT_IN_RINT:
5162     case BUILT_IN_RINTF:
5163     case BUILT_IN_RINTL:
5164       target = expand_builtin_mathfn (exp, target, subtarget);
5165       if (target)
5166         return target;
5167       break;
5168
5169     case BUILT_IN_POW:
5170     case BUILT_IN_POWF:
5171     case BUILT_IN_POWL:
5172       target = expand_builtin_pow (exp, target, subtarget);
5173       if (target)
5174         return target;
5175       break;
5176
5177     case BUILT_IN_ATAN2:
5178     case BUILT_IN_ATAN2F:
5179     case BUILT_IN_ATAN2L:
5180     case BUILT_IN_FMOD:
5181     case BUILT_IN_FMODF:
5182     case BUILT_IN_FMODL:
5183     case BUILT_IN_DREM:
5184     case BUILT_IN_DREMF:
5185     case BUILT_IN_DREML:
5186       if (! flag_unsafe_math_optimizations)
5187         break;
5188       target = expand_builtin_mathfn_2 (exp, target, subtarget);
5189       if (target)
5190         return target;
5191       break;
5192
5193     case BUILT_IN_SIN:
5194     case BUILT_IN_SINF:
5195     case BUILT_IN_SINL:
5196     case BUILT_IN_COS:
5197     case BUILT_IN_COSF:
5198     case BUILT_IN_COSL:
5199       if (! flag_unsafe_math_optimizations)
5200         break;
5201       target = expand_builtin_mathfn_3 (exp, target, subtarget);
5202       if (target)
5203         return target;
5204       break;
5205
5206     case BUILT_IN_APPLY_ARGS:
5207       return expand_builtin_apply_args ();
5208
5209       /* __builtin_apply (FUNCTION, ARGUMENTS, ARGSIZE) invokes
5210          FUNCTION with a copy of the parameters described by
5211          ARGUMENTS, and ARGSIZE.  It returns a block of memory
5212          allocated on the stack into which is stored all the registers
5213          that might possibly be used for returning the result of a
5214          function.  ARGUMENTS is the value returned by
5215          __builtin_apply_args.  ARGSIZE is the number of bytes of
5216          arguments that must be copied.  ??? How should this value be
5217          computed?  We'll also need a safe worst case value for varargs
5218          functions.  */
5219     case BUILT_IN_APPLY:
5220       if (!validate_arglist (arglist, POINTER_TYPE,
5221                              POINTER_TYPE, INTEGER_TYPE, VOID_TYPE)
5222           && !validate_arglist (arglist, REFERENCE_TYPE,
5223                                 POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
5224         return const0_rtx;
5225       else
5226         {
5227           int i;
5228           tree t;
5229           rtx ops[3];
5230
5231           for (t = arglist, i = 0; t; t = TREE_CHAIN (t), i++)
5232             ops[i] = expand_expr (TREE_VALUE (t), NULL_RTX, VOIDmode, 0);
5233
5234           return expand_builtin_apply (ops[0], ops[1], ops[2]);
5235         }
5236
5237       /* __builtin_return (RESULT) causes the function to return the
5238          value described by RESULT.  RESULT is address of the block of
5239          memory returned by __builtin_apply.  */
5240     case BUILT_IN_RETURN:
5241       if (validate_arglist (arglist, POINTER_TYPE, VOID_TYPE))
5242         expand_builtin_return (expand_expr (TREE_VALUE (arglist),
5243                                             NULL_RTX, VOIDmode, 0));
5244       return const0_rtx;
5245
5246     case BUILT_IN_SAVEREGS:
5247       return expand_builtin_saveregs ();
5248
5249     case BUILT_IN_ARGS_INFO:
5250       return expand_builtin_args_info (arglist);
5251
5252       /* Return the address of the first anonymous stack arg.  */
5253     case BUILT_IN_NEXT_ARG:
5254       fold_builtin_next_arg (arglist);
5255       return expand_builtin_next_arg (arglist);
5256
5257     case BUILT_IN_CLASSIFY_TYPE:
5258       return expand_builtin_classify_type (arglist);
5259
5260     case BUILT_IN_CONSTANT_P:
5261       return const0_rtx;
5262
5263     case BUILT_IN_FRAME_ADDRESS:
5264     case BUILT_IN_RETURN_ADDRESS:
5265       return expand_builtin_frame_address (fndecl, arglist);
5266
5267     /* Returns the address of the area where the structure is returned.
5268        0 otherwise.  */
5269     case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
5270       if (arglist != 0
5271           || ! AGGREGATE_TYPE_P (TREE_TYPE (TREE_TYPE (current_function_decl)))
5272           || !MEM_P (DECL_RTL (DECL_RESULT (current_function_decl))))
5273         return const0_rtx;
5274       else
5275         return XEXP (DECL_RTL (DECL_RESULT (current_function_decl)), 0);
5276
5277     case BUILT_IN_ALLOCA:
5278       target = expand_builtin_alloca (arglist, target);
5279       if (target)
5280         return target;
5281       break;
5282
5283     case BUILT_IN_STACK_SAVE:
5284       return expand_stack_save ();
5285
5286     case BUILT_IN_STACK_RESTORE:
5287       expand_stack_restore (TREE_VALUE (arglist));
5288       return const0_rtx;
5289
5290     case BUILT_IN_FFS:
5291     case BUILT_IN_FFSL:
5292     case BUILT_IN_FFSLL:
5293     case BUILT_IN_FFSIMAX:
5294       target = expand_builtin_unop (target_mode, arglist, target,
5295                                     subtarget, ffs_optab);
5296       if (target)
5297         return target;
5298       break;
5299
5300     case BUILT_IN_CLZ:
5301     case BUILT_IN_CLZL:
5302     case BUILT_IN_CLZLL:
5303     case BUILT_IN_CLZIMAX:
5304       target = expand_builtin_unop (target_mode, arglist, target,
5305                                     subtarget, clz_optab);
5306       if (target)
5307         return target;
5308       break;
5309
5310     case BUILT_IN_CTZ:
5311     case BUILT_IN_CTZL:
5312     case BUILT_IN_CTZLL:
5313     case BUILT_IN_CTZIMAX:
5314       target = expand_builtin_unop (target_mode, arglist, target,
5315                                     subtarget, ctz_optab);
5316       if (target)
5317         return target;
5318       break;
5319
5320     case BUILT_IN_POPCOUNT:
5321     case BUILT_IN_POPCOUNTL:
5322     case BUILT_IN_POPCOUNTLL:
5323     case BUILT_IN_POPCOUNTIMAX:
5324       target = expand_builtin_unop (target_mode, arglist, target,
5325                                     subtarget, popcount_optab);
5326       if (target)
5327         return target;
5328       break;
5329
5330     case BUILT_IN_PARITY:
5331     case BUILT_IN_PARITYL:
5332     case BUILT_IN_PARITYLL:
5333     case BUILT_IN_PARITYIMAX:
5334       target = expand_builtin_unop (target_mode, arglist, target,
5335                                     subtarget, parity_optab);
5336       if (target)
5337         return target;
5338       break;
5339
5340     case BUILT_IN_STRLEN:
5341       target = expand_builtin_strlen (arglist, target, target_mode);
5342       if (target)
5343         return target;
5344       break;
5345
5346     case BUILT_IN_STRCPY:
5347       target = expand_builtin_strcpy (exp, target, mode);
5348       if (target)
5349         return target;
5350       break;
5351
5352     case BUILT_IN_STRNCPY:
5353       target = expand_builtin_strncpy (exp, target, mode);
5354       if (target)
5355         return target;
5356       break;
5357
5358     case BUILT_IN_STPCPY:
5359       target = expand_builtin_stpcpy (exp, target, mode);
5360       if (target)
5361         return target;
5362       break;
5363
5364     case BUILT_IN_STRCAT:
5365       target = expand_builtin_strcat (arglist, TREE_TYPE (exp), target, mode);
5366       if (target)
5367         return target;
5368       break;
5369
5370     case BUILT_IN_STRNCAT:
5371       target = expand_builtin_strncat (arglist, target, mode);
5372       if (target)
5373         return target;
5374       break;
5375
5376     case BUILT_IN_STRSPN:
5377       target = expand_builtin_strspn (arglist, target, mode);
5378       if (target)
5379         return target;
5380       break;
5381
5382     case BUILT_IN_STRCSPN:
5383       target = expand_builtin_strcspn (arglist, target, mode);
5384       if (target)
5385         return target;
5386       break;
5387
5388     case BUILT_IN_STRSTR:
5389       target = expand_builtin_strstr (arglist, target, mode);
5390       if (target)
5391         return target;
5392       break;
5393
5394     case BUILT_IN_STRPBRK:
5395       target = expand_builtin_strpbrk (arglist, target, mode);
5396       if (target)
5397         return target;
5398       break;
5399
5400     case BUILT_IN_INDEX:
5401     case BUILT_IN_STRCHR:
5402       target = expand_builtin_strchr (arglist, target, mode);
5403       if (target)
5404         return target;
5405       break;
5406
5407     case BUILT_IN_RINDEX:
5408     case BUILT_IN_STRRCHR:
5409       target = expand_builtin_strrchr (arglist, target, mode);
5410       if (target)
5411         return target;
5412       break;
5413
5414     case BUILT_IN_MEMCPY:
5415       target = expand_builtin_memcpy (exp, target, mode);
5416       if (target)
5417         return target;
5418       break;
5419
5420     case BUILT_IN_MEMPCPY:
5421       target = expand_builtin_mempcpy (arglist, TREE_TYPE (exp), target, mode, /*endp=*/ 1);
5422       if (target)
5423         return target;
5424       break;
5425
5426     case BUILT_IN_MEMMOVE:
5427       target = expand_builtin_memmove (arglist, TREE_TYPE (exp), target, mode);
5428       if (target)
5429         return target;
5430       break;
5431
5432     case BUILT_IN_BCOPY:
5433       target = expand_builtin_bcopy (arglist, TREE_TYPE (exp));
5434       if (target)
5435         return target;
5436       break;
5437
5438     case BUILT_IN_MEMSET:
5439       target = expand_builtin_memset (arglist, target, mode);
5440       if (target)
5441         return target;
5442       break;
5443
5444     case BUILT_IN_BZERO:
5445       target = expand_builtin_bzero (arglist);
5446       if (target)
5447         return target;
5448       break;
5449
5450     case BUILT_IN_STRCMP:
5451       target = expand_builtin_strcmp (exp, target, mode);
5452       if (target)
5453         return target;
5454       break;
5455
5456     case BUILT_IN_STRNCMP:
5457       target = expand_builtin_strncmp (exp, target, mode);
5458       if (target)
5459         return target;
5460       break;
5461
5462     case BUILT_IN_BCMP:
5463     case BUILT_IN_MEMCMP:
5464       target = expand_builtin_memcmp (exp, arglist, target, mode);
5465       if (target)
5466         return target;
5467       break;
5468
5469     case BUILT_IN_SETJMP:
5470       target = expand_builtin_setjmp (arglist, target);
5471       if (target)
5472         return target;
5473       break;
5474
5475       /* __builtin_longjmp is passed a pointer to an array of five words.
5476          It's similar to the C library longjmp function but works with
5477          __builtin_setjmp above.  */
5478     case BUILT_IN_LONGJMP:
5479       if (!validate_arglist (arglist, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
5480         break;
5481       else
5482         {
5483           rtx buf_addr = expand_expr (TREE_VALUE (arglist), subtarget,
5484                                       VOIDmode, 0);
5485           rtx value = expand_expr (TREE_VALUE (TREE_CHAIN (arglist)),
5486                                    NULL_RTX, VOIDmode, 0);
5487
5488           if (value != const1_rtx)
5489             {
5490               error ("%<__builtin_longjmp%> second argument must be 1");
5491               return const0_rtx;
5492             }
5493
5494           expand_builtin_longjmp (buf_addr, value);
5495           return const0_rtx;
5496         }
5497
5498     case BUILT_IN_NONLOCAL_GOTO:
5499       target = expand_builtin_nonlocal_goto (arglist);
5500       if (target)
5501         return target;
5502       break;
5503
5504       /* This updates the setjmp buffer that is its argument with the value
5505          of the current stack pointer.  */
5506     case BUILT_IN_UPDATE_SETJMP_BUF:
5507       if (validate_arglist (arglist, POINTER_TYPE, VOID_TYPE))
5508         {
5509           rtx buf_addr
5510             = expand_expr (TREE_VALUE (arglist), NULL_RTX, VOIDmode, 0);
5511
5512           expand_builtin_update_setjmp_buf (buf_addr);
5513           return const0_rtx;
5514         }
5515       break;
5516
5517     case BUILT_IN_TRAP:
5518       expand_builtin_trap ();
5519       return const0_rtx;
5520
5521     case BUILT_IN_PRINTF:
5522       target = expand_builtin_printf (arglist, target, mode, false);
5523       if (target)
5524         return target;
5525       break;
5526
5527     case BUILT_IN_PRINTF_UNLOCKED:
5528       target = expand_builtin_printf (arglist, target, mode, true);
5529       if (target)
5530         return target;
5531       break;
5532
5533     case BUILT_IN_FPUTS:
5534       target = expand_builtin_fputs (arglist, target, false);
5535       if (target)
5536         return target;
5537       break;
5538     case BUILT_IN_FPUTS_UNLOCKED:
5539       target = expand_builtin_fputs (arglist, target, true);
5540       if (target)
5541         return target;
5542       break;
5543
5544     case BUILT_IN_FPRINTF:
5545       target = expand_builtin_fprintf (arglist, target, mode, false);
5546       if (target)
5547         return target;
5548       break;
5549
5550     case BUILT_IN_FPRINTF_UNLOCKED:
5551       target = expand_builtin_fprintf (arglist, target, mode, true);
5552       if (target)
5553         return target;
5554       break;
5555
5556     case BUILT_IN_SPRINTF:
5557       target = expand_builtin_sprintf (arglist, target, mode);
5558       if (target)
5559         return target;
5560       break;
5561
5562     case BUILT_IN_SIGNBIT:
5563     case BUILT_IN_SIGNBITF:
5564     case BUILT_IN_SIGNBITL:
5565       target = expand_builtin_signbit (exp, target);
5566       if (target)
5567         return target;
5568       break;
5569
5570       /* Various hooks for the DWARF 2 __throw routine.  */
5571     case BUILT_IN_UNWIND_INIT:
5572       expand_builtin_unwind_init ();
5573       return const0_rtx;
5574     case BUILT_IN_DWARF_CFA:
5575       return virtual_cfa_rtx;
5576 #ifdef DWARF2_UNWIND_INFO
5577     case BUILT_IN_DWARF_SP_COLUMN:
5578       return expand_builtin_dwarf_sp_column ();
5579     case BUILT_IN_INIT_DWARF_REG_SIZES:
5580       expand_builtin_init_dwarf_reg_sizes (TREE_VALUE (arglist));
5581       return const0_rtx;
5582 #endif
5583     case BUILT_IN_FROB_RETURN_ADDR:
5584       return expand_builtin_frob_return_addr (TREE_VALUE (arglist));
5585     case BUILT_IN_EXTRACT_RETURN_ADDR:
5586       return expand_builtin_extract_return_addr (TREE_VALUE (arglist));
5587     case BUILT_IN_EH_RETURN:
5588       expand_builtin_eh_return (TREE_VALUE (arglist),
5589                                 TREE_VALUE (TREE_CHAIN (arglist)));
5590       return const0_rtx;
5591 #ifdef EH_RETURN_DATA_REGNO
5592     case BUILT_IN_EH_RETURN_DATA_REGNO:
5593       return expand_builtin_eh_return_data_regno (arglist);
5594 #endif
5595     case BUILT_IN_EXTEND_POINTER:
5596       return expand_builtin_extend_pointer (TREE_VALUE (arglist));
5597
5598     case BUILT_IN_VA_START:
5599     case BUILT_IN_STDARG_START:
5600       return expand_builtin_va_start (arglist);
5601     case BUILT_IN_VA_END:
5602       return expand_builtin_va_end (arglist);
5603     case BUILT_IN_VA_COPY:
5604       return expand_builtin_va_copy (arglist);
5605     case BUILT_IN_EXPECT:
5606       return expand_builtin_expect (arglist, target);
5607     case BUILT_IN_PREFETCH:
5608       expand_builtin_prefetch (arglist);
5609       return const0_rtx;
5610
5611     case BUILT_IN_PROFILE_FUNC_ENTER:
5612       return expand_builtin_profile_func (false);
5613     case BUILT_IN_PROFILE_FUNC_EXIT:
5614       return expand_builtin_profile_func (true);
5615
5616     case BUILT_IN_INIT_TRAMPOLINE:
5617       return expand_builtin_init_trampoline (arglist);
5618     case BUILT_IN_ADJUST_TRAMPOLINE:
5619       return expand_builtin_adjust_trampoline (arglist);
5620
5621     case BUILT_IN_FORK:
5622     case BUILT_IN_EXECL:
5623     case BUILT_IN_EXECV:
5624     case BUILT_IN_EXECLP:
5625     case BUILT_IN_EXECLE:
5626     case BUILT_IN_EXECVP:
5627     case BUILT_IN_EXECVE:
5628       target = expand_builtin_fork_or_exec (fndecl, arglist, target, ignore);
5629       if (target)
5630         return target;
5631       break;
5632
5633     default:    /* just do library call, if unknown builtin */
5634       break;
5635     }
5636
5637   /* The switch statement above can drop through to cause the function
5638      to be called normally.  */
5639   return expand_call (exp, target, ignore);
5640 }
5641
5642 /* Determine whether a tree node represents a call to a built-in
5643    function.  If the tree T is a call to a built-in function with
5644    the right number of arguments of the appropriate types, return
5645    the DECL_FUNCTION_CODE of the call, e.g. BUILT_IN_SQRT.
5646    Otherwise the return value is END_BUILTINS.  */
5647
5648 enum built_in_function
5649 builtin_mathfn_code (tree t)
5650 {
5651   tree fndecl, arglist, parmlist;
5652   tree argtype, parmtype;
5653
5654   if (TREE_CODE (t) != CALL_EXPR
5655       || TREE_CODE (TREE_OPERAND (t, 0)) != ADDR_EXPR)
5656     return END_BUILTINS;
5657
5658   fndecl = get_callee_fndecl (t);
5659   if (fndecl == NULL_TREE
5660       || TREE_CODE (fndecl) != FUNCTION_DECL
5661       || ! DECL_BUILT_IN (fndecl)
5662       || DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
5663     return END_BUILTINS;
5664
5665   arglist = TREE_OPERAND (t, 1);
5666   parmlist = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
5667   for (; parmlist; parmlist = TREE_CHAIN (parmlist))
5668     {
5669       /* If a function doesn't take a variable number of arguments,
5670          the last element in the list will have type `void'.  */
5671       parmtype = TREE_VALUE (parmlist);
5672       if (VOID_TYPE_P (parmtype))
5673         {
5674           if (arglist)
5675             return END_BUILTINS;
5676           return DECL_FUNCTION_CODE (fndecl);
5677         }
5678
5679       if (! arglist)
5680         return END_BUILTINS;
5681
5682       argtype = TREE_TYPE (TREE_VALUE (arglist));
5683
5684       if (SCALAR_FLOAT_TYPE_P (parmtype))
5685         {
5686           if (! SCALAR_FLOAT_TYPE_P (argtype))
5687             return END_BUILTINS;
5688         }
5689       else if (COMPLEX_FLOAT_TYPE_P (parmtype))
5690         {
5691           if (! COMPLEX_FLOAT_TYPE_P (argtype))
5692             return END_BUILTINS;
5693         }
5694       else if (POINTER_TYPE_P (parmtype))
5695         {
5696           if (! POINTER_TYPE_P (argtype))
5697             return END_BUILTINS;
5698         }
5699       else if (INTEGRAL_TYPE_P (parmtype))
5700         {
5701           if (! INTEGRAL_TYPE_P (argtype))
5702             return END_BUILTINS;
5703         }
5704       else
5705         return END_BUILTINS;
5706
5707       arglist = TREE_CHAIN (arglist);
5708     }
5709
5710   /* Variable-length argument list.  */
5711   return DECL_FUNCTION_CODE (fndecl);
5712 }
5713
5714 /* Fold a call to __builtin_constant_p, if we know it will evaluate to a
5715    constant.  ARGLIST is the argument list of the call.  */
5716
5717 static tree
5718 fold_builtin_constant_p (tree arglist)
5719 {
5720   if (arglist == 0)
5721     return 0;
5722
5723   arglist = TREE_VALUE (arglist);
5724
5725   /* We return 1 for a numeric type that's known to be a constant
5726      value at compile-time or for an aggregate type that's a
5727      literal constant.  */
5728   STRIP_NOPS (arglist);
5729
5730   /* If we know this is a constant, emit the constant of one.  */
5731   if (CONSTANT_CLASS_P (arglist)
5732       || (TREE_CODE (arglist) == CONSTRUCTOR
5733           && TREE_CONSTANT (arglist))
5734       || (TREE_CODE (arglist) == ADDR_EXPR
5735           && TREE_CODE (TREE_OPERAND (arglist, 0)) == STRING_CST))
5736     return integer_one_node;
5737
5738   /* If this expression has side effects, show we don't know it to be a
5739      constant.  Likewise if it's a pointer or aggregate type since in
5740      those case we only want literals, since those are only optimized
5741      when generating RTL, not later.
5742      And finally, if we are compiling an initializer, not code, we
5743      need to return a definite result now; there's not going to be any
5744      more optimization done.  */
5745   if (TREE_SIDE_EFFECTS (arglist)
5746       || AGGREGATE_TYPE_P (TREE_TYPE (arglist))
5747       || POINTER_TYPE_P (TREE_TYPE (arglist))
5748       || cfun == 0)
5749     return integer_zero_node;
5750
5751   return 0;
5752 }
5753
5754 /* Fold a call to __builtin_expect, if we expect that a comparison against
5755    the argument will fold to a constant.  In practice, this means a true
5756    constant or the address of a non-weak symbol.  ARGLIST is the argument
5757    list of the call.  */
5758
5759 static tree
5760 fold_builtin_expect (tree arglist)
5761 {
5762   tree arg, inner;
5763
5764   if (arglist == 0)
5765     return 0;
5766
5767   arg = TREE_VALUE (arglist);
5768
5769   /* If the argument isn't invariant, then there's nothing we can do.  */
5770   if (!TREE_INVARIANT (arg))
5771     return 0;
5772
5773   /* If we're looking at an address of a weak decl, then do not fold.  */
5774   inner = arg;
5775   STRIP_NOPS (inner);
5776   if (TREE_CODE (inner) == ADDR_EXPR)
5777     {
5778       do
5779         {
5780           inner = TREE_OPERAND (inner, 0);
5781         }
5782       while (TREE_CODE (inner) == COMPONENT_REF
5783              || TREE_CODE (inner) == ARRAY_REF);
5784       if (DECL_P (inner) && DECL_WEAK (inner))
5785         return 0;
5786     }
5787
5788   /* Otherwise, ARG already has the proper type for the return value.  */
5789   return arg;
5790 }
5791
5792 /* Fold a call to __builtin_classify_type.  */
5793
5794 static tree
5795 fold_builtin_classify_type (tree arglist)
5796 {
5797   if (arglist == 0)
5798     return build_int_cst (NULL_TREE, no_type_class);
5799
5800   return build_int_cst (NULL_TREE,
5801                         type_to_class (TREE_TYPE (TREE_VALUE (arglist))));
5802 }
5803
5804 /* Fold a call to __builtin_strlen.  */
5805
5806 static tree
5807 fold_builtin_strlen (tree arglist)
5808 {
5809   if (!validate_arglist (arglist, POINTER_TYPE, VOID_TYPE))
5810     return NULL_TREE;
5811   else
5812     {
5813       tree len = c_strlen (TREE_VALUE (arglist), 0);
5814
5815       if (len)
5816         {
5817           /* Convert from the internal "sizetype" type to "size_t".  */
5818           if (size_type_node)
5819             len = fold_convert (size_type_node, len);
5820           return len;
5821         }
5822
5823       return NULL_TREE;
5824     }
5825 }
5826
5827 /* Fold a call to __builtin_inf or __builtin_huge_val.  */
5828
5829 static tree
5830 fold_builtin_inf (tree type, int warn)
5831 {
5832   REAL_VALUE_TYPE real;
5833
5834   /* __builtin_inff is intended to be usable to define INFINITY on all
5835      targets.  If an infinity is not available, INFINITY expands "to a
5836      positive constant of type float that overflows at translation
5837      time", footnote "In this case, using INFINITY will violate the
5838      constraint in 6.4.4 and thus require a diagnostic." (C99 7.12#4).
5839      Thus we pedwarn to ensure this constraint violation is
5840      diagnosed.  */
5841   if (!MODE_HAS_INFINITIES (TYPE_MODE (type)) && warn)
5842     pedwarn ("target format does not support infinity");
5843
5844   real_inf (&real);
5845   return build_real (type, real);
5846 }
5847
5848 /* Fold a call to __builtin_nan or __builtin_nans.  */
5849
5850 static tree
5851 fold_builtin_nan (tree arglist, tree type, int quiet)
5852 {
5853   REAL_VALUE_TYPE real;
5854   const char *str;
5855
5856   if (!validate_arglist (arglist, POINTER_TYPE, VOID_TYPE))
5857     return 0;
5858   str = c_getstr (TREE_VALUE (arglist));
5859   if (!str)
5860     return 0;
5861
5862   if (!real_nan (&real, str, quiet, TYPE_MODE (type)))
5863     return 0;
5864
5865   return build_real (type, real);
5866 }
5867
5868 /* Return true if the floating point expression T has an integer value.
5869    We also allow +Inf, -Inf and NaN to be considered integer values.  */
5870
5871 static bool
5872 integer_valued_real_p (tree t)
5873 {
5874   switch (TREE_CODE (t))
5875     {
5876     case FLOAT_EXPR:
5877       return true;
5878
5879     case ABS_EXPR:
5880     case SAVE_EXPR:
5881     case NON_LVALUE_EXPR:
5882       return integer_valued_real_p (TREE_OPERAND (t, 0));
5883
5884     case COMPOUND_EXPR:
5885     case MODIFY_EXPR:
5886     case BIND_EXPR:
5887       return integer_valued_real_p (TREE_OPERAND (t, 1));
5888
5889     case PLUS_EXPR:
5890     case MINUS_EXPR:
5891     case MULT_EXPR:
5892     case MIN_EXPR:
5893     case MAX_EXPR:
5894       return integer_valued_real_p (TREE_OPERAND (t, 0))
5895              && integer_valued_real_p (TREE_OPERAND (t, 1));
5896
5897     case COND_EXPR:
5898       return integer_valued_real_p (TREE_OPERAND (t, 1))
5899              && integer_valued_real_p (TREE_OPERAND (t, 2));
5900
5901     case REAL_CST:
5902       if (! TREE_CONSTANT_OVERFLOW (t))
5903       {
5904         REAL_VALUE_TYPE c, cint;
5905
5906         c = TREE_REAL_CST (t);
5907         real_trunc (&cint, TYPE_MODE (TREE_TYPE (t)), &c);
5908         return real_identical (&c, &cint);
5909       }
5910
5911     case NOP_EXPR:
5912       {
5913         tree type = TREE_TYPE (TREE_OPERAND (t, 0));
5914         if (TREE_CODE (type) == INTEGER_TYPE)
5915           return true;
5916         if (TREE_CODE (type) == REAL_TYPE)
5917           return integer_valued_real_p (TREE_OPERAND (t, 0));
5918         break;
5919       }
5920
5921     case CALL_EXPR:
5922       switch (builtin_mathfn_code (t))
5923         {
5924         case BUILT_IN_CEIL:
5925         case BUILT_IN_CEILF:
5926         case BUILT_IN_CEILL:
5927         case BUILT_IN_FLOOR:
5928         case BUILT_IN_FLOORF:
5929         case BUILT_IN_FLOORL:
5930         case BUILT_IN_NEARBYINT:
5931         case BUILT_IN_NEARBYINTF:
5932         case BUILT_IN_NEARBYINTL:
5933         case BUILT_IN_RINT:
5934         case BUILT_IN_RINTF:
5935         case BUILT_IN_RINTL:
5936         case BUILT_IN_ROUND:
5937         case BUILT_IN_ROUNDF:
5938         case BUILT_IN_ROUNDL:
5939         case BUILT_IN_TRUNC:
5940         case BUILT_IN_TRUNCF:
5941         case BUILT_IN_TRUNCL:
5942           return true;
5943
5944         default:
5945           break;
5946         }
5947       break;
5948
5949     default:
5950       break;
5951     }
5952   return false;
5953 }
5954
5955 /* EXP is assumed to be builtin call where truncation can be propagated
5956    across (for instance floor((double)f) == (double)floorf (f).
5957    Do the transformation.  */
5958
5959 static tree
5960 fold_trunc_transparent_mathfn (tree exp)
5961 {
5962   tree fndecl = get_callee_fndecl (exp);
5963   tree arglist = TREE_OPERAND (exp, 1);
5964   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5965   tree arg;
5966
5967   if (! validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
5968     return 0;
5969
5970   arg = TREE_VALUE (arglist);
5971   /* Integer rounding functions are idempotent.  */
5972   if (fcode == builtin_mathfn_code (arg))
5973     return arg;
5974
5975   /* If argument is already integer valued, and we don't need to worry
5976      about setting errno, there's no need to perform rounding.  */
5977   if (! flag_errno_math && integer_valued_real_p (arg))
5978     return arg;
5979
5980   if (optimize)
5981     {
5982       tree arg0 = strip_float_extensions (arg);
5983       tree ftype = TREE_TYPE (exp);
5984       tree newtype = TREE_TYPE (arg0);
5985       tree decl;
5986
5987       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
5988           && (decl = mathfn_built_in (newtype, fcode)))
5989         {
5990           arglist =
5991             build_tree_list (NULL_TREE, fold_convert (newtype, arg0));
5992           return fold_convert (ftype,
5993                                build_function_call_expr (decl, arglist));
5994         }
5995     }
5996   return 0;
5997 }
5998
5999 /* EXP is assumed to be builtin call which can narrow the FP type of
6000    the argument, for instance lround((double)f) -> lroundf (f).  */
6001
6002 static tree
6003 fold_fixed_mathfn (tree exp)
6004 {
6005   tree fndecl = get_callee_fndecl (exp);
6006   tree arglist = TREE_OPERAND (exp, 1);
6007   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
6008   tree arg;
6009
6010   if (! validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
6011     return 0;
6012
6013   arg = TREE_VALUE (arglist);
6014
6015   /* If argument is already integer valued, and we don't need to worry
6016      about setting errno, there's no need to perform rounding.  */
6017   if (! flag_errno_math && integer_valued_real_p (arg))
6018     return fold (build1 (FIX_TRUNC_EXPR, TREE_TYPE (exp), arg));
6019
6020   if (optimize)
6021     {
6022       tree ftype = TREE_TYPE (arg);
6023       tree arg0 = strip_float_extensions (arg);
6024       tree newtype = TREE_TYPE (arg0);
6025       tree decl;
6026
6027       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
6028           && (decl = mathfn_built_in (newtype, fcode)))
6029         {
6030           arglist =
6031             build_tree_list (NULL_TREE, fold_convert (newtype, arg0));
6032           return build_function_call_expr (decl, arglist);
6033         }
6034     }
6035   return 0;
6036 }
6037
6038 /* Fold function call to builtin cabs, cabsf or cabsl.  ARGLIST
6039    is the argument list and TYPE is the return type.  Return
6040    NULL_TREE if no if no simplification can be made.  */
6041
6042 static tree
6043 fold_builtin_cabs (tree arglist, tree type)
6044 {
6045   tree arg;
6046
6047   if (!arglist || TREE_CHAIN (arglist))
6048     return NULL_TREE;
6049
6050   arg = TREE_VALUE (arglist);
6051   if (TREE_CODE (TREE_TYPE (arg)) != COMPLEX_TYPE
6052       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) != REAL_TYPE)
6053     return NULL_TREE;
6054
6055   /* Evaluate cabs of a constant at compile-time.  */
6056   if (flag_unsafe_math_optimizations
6057       && TREE_CODE (arg) == COMPLEX_CST
6058       && TREE_CODE (TREE_REALPART (arg)) == REAL_CST
6059       && TREE_CODE (TREE_IMAGPART (arg)) == REAL_CST
6060       && ! TREE_CONSTANT_OVERFLOW (TREE_REALPART (arg))
6061       && ! TREE_CONSTANT_OVERFLOW (TREE_IMAGPART (arg)))
6062     {
6063       REAL_VALUE_TYPE r, i;
6064
6065       r = TREE_REAL_CST (TREE_REALPART (arg));
6066       i = TREE_REAL_CST (TREE_IMAGPART (arg));
6067
6068       real_arithmetic (&r, MULT_EXPR, &r, &r);
6069       real_arithmetic (&i, MULT_EXPR, &i, &i);
6070       real_arithmetic (&r, PLUS_EXPR, &r, &i);
6071       if (real_sqrt (&r, TYPE_MODE (type), &r)
6072           || ! flag_trapping_math)
6073         return build_real (type, r);
6074     }
6075
6076   /* If either part is zero, cabs is fabs of the other.  */
6077   if (TREE_CODE (arg) == COMPLEX_EXPR
6078       && real_zerop (TREE_OPERAND (arg, 0)))
6079     return fold (build1 (ABS_EXPR, type, TREE_OPERAND (arg, 1)));
6080   if (TREE_CODE (arg) == COMPLEX_EXPR
6081       && real_zerop (TREE_OPERAND (arg, 1)))
6082     return fold (build1 (ABS_EXPR, type, TREE_OPERAND (arg, 0)));
6083
6084   /* Don't do this when optimizing for size.  */
6085   if (flag_unsafe_math_optimizations
6086       && optimize && !optimize_size)
6087     {
6088       tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
6089
6090       if (sqrtfn != NULL_TREE)
6091         {
6092           tree rpart, ipart, result, arglist;
6093
6094           arg = builtin_save_expr (arg);
6095
6096           rpart = fold (build1 (REALPART_EXPR, type, arg));
6097           ipart = fold (build1 (IMAGPART_EXPR, type, arg));
6098
6099           rpart = builtin_save_expr (rpart);
6100           ipart = builtin_save_expr (ipart);
6101
6102           result = fold (build2 (PLUS_EXPR, type,
6103                                  fold (build2 (MULT_EXPR, type,
6104                                                rpart, rpart)),
6105                                  fold (build2 (MULT_EXPR, type,
6106                                                ipart, ipart))));
6107
6108           arglist = build_tree_list (NULL_TREE, result);
6109           return build_function_call_expr (sqrtfn, arglist);
6110         }
6111     }
6112
6113   return NULL_TREE;
6114 }
6115
6116 /* Fold a builtin function call to sqrt, sqrtf, or sqrtl.  Return
6117    NULL_TREE if no simplification can be made.  */
6118
6119 static tree
6120 fold_builtin_sqrt (tree arglist, tree type)
6121 {
6122
6123   enum built_in_function fcode;
6124   tree arg = TREE_VALUE (arglist);
6125
6126   if (!validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
6127     return NULL_TREE;
6128
6129   /* Optimize sqrt of constant value.  */
6130   if (TREE_CODE (arg) == REAL_CST
6131       && ! TREE_CONSTANT_OVERFLOW (arg))
6132     {
6133       REAL_VALUE_TYPE r, x;
6134
6135       x = TREE_REAL_CST (arg);
6136       if (real_sqrt (&r, TYPE_MODE (type), &x)
6137           || (!flag_trapping_math && !flag_errno_math))
6138         return build_real (type, r);
6139     }
6140
6141   /* Optimize sqrt(expN(x)) = expN(x*0.5).  */
6142   fcode = builtin_mathfn_code (arg);
6143   if (flag_unsafe_math_optimizations && BUILTIN_EXPONENT_P (fcode))
6144     {
6145       tree expfn = TREE_OPERAND (TREE_OPERAND (arg, 0), 0);
6146       arg = fold (build2 (MULT_EXPR, type,
6147                           TREE_VALUE (TREE_OPERAND (arg, 1)),
6148                           build_real (type, dconsthalf)));
6149       arglist = build_tree_list (NULL_TREE, arg);
6150       return build_function_call_expr (expfn, arglist);
6151     }
6152
6153   /* Optimize sqrt(Nroot(x)) -> pow(x,1/(2*N)).  */
6154   if (flag_unsafe_math_optimizations && BUILTIN_ROOT_P (fcode))
6155     {
6156       tree powfn = mathfn_built_in (type, BUILT_IN_POW);
6157
6158       if (powfn)
6159         {
6160           tree arg0 = TREE_VALUE (TREE_OPERAND (arg, 1));
6161           tree tree_root;
6162           /* The inner root was either sqrt or cbrt.  */
6163           REAL_VALUE_TYPE dconstroot =
6164             BUILTIN_SQRT_P (fcode) ? dconsthalf : dconstthird;
6165
6166           /* Adjust for the outer root.  */
6167           SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
6168           dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
6169           tree_root = build_real (type, dconstroot);
6170           arglist = tree_cons (NULL_TREE, arg0,
6171                                build_tree_list (NULL_TREE, tree_root));
6172           return build_function_call_expr (powfn, arglist);
6173         }
6174     }
6175
6176   /* Optimize sqrt(pow(x,y)) = pow(x,y*0.5).  */
6177   if (flag_unsafe_math_optimizations
6178       && (fcode == BUILT_IN_POW
6179           || fcode == BUILT_IN_POWF
6180           || fcode == BUILT_IN_POWL))
6181     {
6182       tree powfn = TREE_OPERAND (TREE_OPERAND (arg, 0), 0);
6183       tree arg0 = TREE_VALUE (TREE_OPERAND (arg, 1));
6184       tree arg1 = TREE_VALUE (TREE_CHAIN (TREE_OPERAND (arg, 1)));
6185       tree narg1 = fold (build2 (MULT_EXPR, type, arg1,
6186                                  build_real (type, dconsthalf)));
6187       arglist = tree_cons (NULL_TREE, arg0,
6188                            build_tree_list (NULL_TREE, narg1));
6189       return build_function_call_expr (powfn, arglist);
6190     }
6191
6192   return NULL_TREE;
6193 }
6194
6195 /* Fold a builtin function call to cbrt, cbrtf, or cbrtl.  Return
6196    NULL_TREE if no simplification can be made.  */
6197 static tree
6198 fold_builtin_cbrt (tree arglist, tree type)
6199 {
6200   tree arg = TREE_VALUE (arglist);
6201   const enum built_in_function fcode = builtin_mathfn_code (arg);
6202
6203   if (!validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
6204     return NULL_TREE;
6205
6206   /* Optimize cbrt of constant value.  */
6207   if (real_zerop (arg) || real_onep (arg) || real_minus_onep (arg))
6208     return arg;
6209
6210   /* Optimize cbrt(expN(x)) -> expN(x/3).  */
6211   if (flag_unsafe_math_optimizations && BUILTIN_EXPONENT_P (fcode))
6212     {
6213       tree expfn = TREE_OPERAND (TREE_OPERAND (arg, 0), 0);
6214       const REAL_VALUE_TYPE third_trunc =
6215         real_value_truncate (TYPE_MODE (type), dconstthird);
6216       arg = fold (build2 (MULT_EXPR, type,
6217                           TREE_VALUE (TREE_OPERAND (arg, 1)),
6218                           build_real (type, third_trunc)));
6219       arglist = build_tree_list (NULL_TREE, arg);
6220       return build_function_call_expr (expfn, arglist);
6221     }
6222
6223   /* Optimize cbrt(sqrt(x)) -> pow(x,1/6).  */
6224   /* We don't optimize cbrt(cbrt(x)) -> pow(x,1/9) because if
6225      x is negative pow will error but cbrt won't.  */
6226   if (flag_unsafe_math_optimizations && BUILTIN_SQRT_P (fcode))
6227     {
6228       tree powfn = mathfn_built_in (type, BUILT_IN_POW);
6229
6230       if (powfn)
6231         {
6232           tree arg0 = TREE_VALUE (TREE_OPERAND (arg, 1));
6233           tree tree_root;
6234           REAL_VALUE_TYPE dconstroot = dconstthird;
6235
6236           SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
6237           dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
6238           tree_root = build_real (type, dconstroot);
6239           arglist = tree_cons (NULL_TREE, arg0,
6240                                build_tree_list (NULL_TREE, tree_root));
6241           return build_function_call_expr (powfn, arglist);
6242         }
6243
6244     }
6245   return NULL_TREE;
6246 }
6247
6248 /* Fold function call to builtin sin, sinf, or sinl.  Return
6249    NULL_TREE if no simplification can be made.  */
6250 static tree
6251 fold_builtin_sin (tree arglist)
6252 {
6253   tree arg = TREE_VALUE (arglist);
6254
6255   if (!validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
6256     return NULL_TREE;
6257
6258   /* Optimize sin (0.0) = 0.0.  */
6259   if (real_zerop (arg))
6260     return arg;
6261
6262   return NULL_TREE;
6263 }
6264
6265 /* Fold function call to builtin cos, cosf, or cosl.  Return
6266    NULL_TREE if no simplification can be made.  */
6267 static tree
6268 fold_builtin_cos (tree arglist, tree type, tree fndecl)
6269 {
6270   tree arg = TREE_VALUE (arglist);
6271
6272   if (!validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
6273     return NULL_TREE;
6274
6275   /* Optimize cos (0.0) = 1.0.  */
6276   if (real_zerop (arg))
6277     return build_real (type, dconst1);
6278
6279   /* Optimize cos(-x) into cos (x).  */
6280   if (TREE_CODE (arg) == NEGATE_EXPR)
6281     {
6282       tree args = build_tree_list (NULL_TREE,
6283                                    TREE_OPERAND (arg, 0));
6284       return build_function_call_expr (fndecl, args);
6285     }
6286
6287   return NULL_TREE;
6288 }
6289
6290 /* Fold function call to builtin tan, tanf, or tanl.  Return
6291    NULL_TREE if no simplification can be made.  */
6292 static tree
6293 fold_builtin_tan (tree arglist)
6294 {
6295   enum built_in_function fcode;
6296   tree arg = TREE_VALUE (arglist);
6297
6298   if (!validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
6299     return NULL_TREE;
6300
6301   /* Optimize tan(0.0) = 0.0.  */
6302   if (real_zerop (arg))
6303     return arg;
6304
6305   /* Optimize tan(atan(x)) = x.  */
6306   fcode = builtin_mathfn_code (arg);
6307   if (flag_unsafe_math_optimizations
6308       && (fcode == BUILT_IN_ATAN
6309           || fcode == BUILT_IN_ATANF
6310           || fcode == BUILT_IN_ATANL))
6311     return TREE_VALUE (TREE_OPERAND (arg, 1));
6312
6313   return NULL_TREE;
6314 }
6315
6316 /* Fold function call to builtin atan, atanf, or atanl.  Return
6317    NULL_TREE if no simplification can be made.  */
6318
6319 static tree
6320 fold_builtin_atan (tree arglist, tree type)
6321 {
6322
6323   tree arg = TREE_VALUE (arglist);
6324
6325   if (!validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
6326     return NULL_TREE;
6327
6328   /* Optimize atan(0.0) = 0.0.  */
6329   if (real_zerop (arg))
6330     return arg;
6331
6332   /* Optimize atan(1.0) = pi/4.  */
6333   if (real_onep (arg))
6334     {
6335       REAL_VALUE_TYPE cst;
6336
6337       real_convert (&cst, TYPE_MODE (type), &dconstpi);
6338       SET_REAL_EXP (&cst, REAL_EXP (&cst) - 2);
6339       return build_real (type, cst);
6340     }
6341
6342   return NULL_TREE;
6343 }
6344
6345 /* Fold function call to builtin trunc, truncf or truncl.  Return
6346    NULL_TREE if no simplification can be made.  */
6347
6348 static tree
6349 fold_builtin_trunc (tree exp)
6350 {
6351   tree arglist = TREE_OPERAND (exp, 1);
6352   tree arg;
6353
6354   if (! validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
6355     return 0;
6356
6357   /* Optimize trunc of constant value.  */
6358   arg = TREE_VALUE (arglist);
6359   if (TREE_CODE (arg) == REAL_CST && ! TREE_CONSTANT_OVERFLOW (arg))
6360     {
6361       REAL_VALUE_TYPE r, x;
6362       tree type = TREE_TYPE (exp);
6363
6364       x = TREE_REAL_CST (arg);
6365       real_trunc (&r, TYPE_MODE (type), &x);
6366       return build_real (type, r);
6367     }
6368
6369   return fold_trunc_transparent_mathfn (exp);
6370 }
6371
6372 /* Fold function call to builtin floor, floorf or floorl.  Return
6373    NULL_TREE if no simplification can be made.  */
6374
6375 static tree
6376 fold_builtin_floor (tree exp)
6377 {
6378   tree arglist = TREE_OPERAND (exp, 1);
6379   tree arg;
6380
6381   if (! validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
6382     return 0;
6383
6384   /* Optimize floor of constant value.  */
6385   arg = TREE_VALUE (arglist);
6386   if (TREE_CODE (arg) == REAL_CST && ! TREE_CONSTANT_OVERFLOW (arg))
6387     {
6388       REAL_VALUE_TYPE x;
6389
6390       x = TREE_REAL_CST (arg);
6391       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
6392         {
6393           tree type = TREE_TYPE (exp);
6394           REAL_VALUE_TYPE r;
6395
6396           real_floor (&r, TYPE_MODE (type), &x);
6397           return build_real (type, r);
6398         }
6399     }
6400
6401   return fold_trunc_transparent_mathfn (exp);
6402 }
6403
6404 /* Fold function call to builtin ceil, ceilf or ceill.  Return
6405    NULL_TREE if no simplification can be made.  */
6406
6407 static tree
6408 fold_builtin_ceil (tree exp)
6409 {
6410   tree arglist = TREE_OPERAND (exp, 1);
6411   tree arg;
6412
6413   if (! validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
6414     return 0;
6415
6416   /* Optimize ceil of constant value.  */
6417   arg = TREE_VALUE (arglist);
6418   if (TREE_CODE (arg) == REAL_CST && ! TREE_CONSTANT_OVERFLOW (arg))
6419     {
6420       REAL_VALUE_TYPE x;
6421
6422       x = TREE_REAL_CST (arg);
6423       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
6424         {
6425           tree type = TREE_TYPE (exp);
6426           REAL_VALUE_TYPE r;
6427
6428           real_ceil (&r, TYPE_MODE (type), &x);
6429           return build_real (type, r);
6430         }
6431     }
6432
6433   return fold_trunc_transparent_mathfn (exp);
6434 }
6435
6436 /* Fold function call to builtin round, roundf or roundl.  Return
6437    NULL_TREE if no simplification can be made.  */
6438
6439 static tree
6440 fold_builtin_round (tree exp)
6441 {
6442   tree arglist = TREE_OPERAND (exp, 1);
6443   tree arg;
6444
6445   if (! validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
6446     return 0;
6447
6448   /* Optimize round of constant value.  */
6449   arg = TREE_VALUE (arglist);
6450   if (TREE_CODE (arg) == REAL_CST && ! TREE_CONSTANT_OVERFLOW (arg))
6451     {
6452       REAL_VALUE_TYPE x;
6453
6454       x = TREE_REAL_CST (arg);
6455       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
6456         {
6457           tree type = TREE_TYPE (exp);
6458           REAL_VALUE_TYPE r;
6459
6460           real_round (&r, TYPE_MODE (type), &x);
6461           return build_real (type, r);
6462         }
6463     }
6464
6465   return fold_trunc_transparent_mathfn (exp);
6466 }
6467
6468 /* Fold function call to builtin lround, lroundf or lroundl (or the
6469    corresponding long long versions).  Return NULL_TREE if no
6470    simplification can be made.  */
6471
6472 static tree
6473 fold_builtin_lround (tree exp)
6474 {
6475   tree arglist = TREE_OPERAND (exp, 1);
6476   tree arg;
6477
6478   if (! validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
6479     return 0;
6480
6481   /* Optimize lround of constant value.  */
6482   arg = TREE_VALUE (arglist);
6483   if (TREE_CODE (arg) == REAL_CST && ! TREE_CONSTANT_OVERFLOW (arg))
6484     {
6485       const REAL_VALUE_TYPE x = TREE_REAL_CST (arg);
6486
6487       if (! REAL_VALUE_ISNAN (x) && ! REAL_VALUE_ISINF (x))
6488         {
6489           tree itype = TREE_TYPE (exp), ftype = TREE_TYPE (arg), result;
6490           HOST_WIDE_INT hi, lo;
6491           REAL_VALUE_TYPE r;
6492
6493           real_round (&r, TYPE_MODE (ftype), &x);
6494           REAL_VALUE_TO_INT (&lo, &hi, r);
6495           result = build_int_cst_wide (NULL_TREE, lo, hi);
6496           if (int_fits_type_p (result, itype))
6497             return fold_convert (itype, result);
6498         }
6499     }
6500
6501   return fold_fixed_mathfn (exp);
6502 }
6503
6504 /* Fold function call to builtin ffs, clz, ctz, popcount and parity
6505    and their long and long long variants (i.e. ffsl and ffsll).
6506    Return NULL_TREE if no simplification can be made.  */
6507
6508 static tree
6509 fold_builtin_bitop (tree exp)
6510 {
6511   tree fndecl = get_callee_fndecl (exp);
6512   tree arglist = TREE_OPERAND (exp, 1);
6513   tree arg;
6514
6515   if (! validate_arglist (arglist, INTEGER_TYPE, VOID_TYPE))
6516     return NULL_TREE;
6517
6518   /* Optimize for constant argument.  */
6519   arg = TREE_VALUE (arglist);
6520   if (TREE_CODE (arg) == INTEGER_CST && ! TREE_CONSTANT_OVERFLOW (arg))
6521     {
6522       HOST_WIDE_INT hi, width, result;
6523       unsigned HOST_WIDE_INT lo;
6524       tree type;
6525
6526       type = TREE_TYPE (arg);
6527       width = TYPE_PRECISION (type);
6528       lo = TREE_INT_CST_LOW (arg);
6529
6530       /* Clear all the bits that are beyond the type's precision.  */
6531       if (width > HOST_BITS_PER_WIDE_INT)
6532         {
6533           hi = TREE_INT_CST_HIGH (arg);
6534           if (width < 2 * HOST_BITS_PER_WIDE_INT)
6535             hi &= ~((HOST_WIDE_INT) (-1) >> (width - HOST_BITS_PER_WIDE_INT));
6536         }
6537       else
6538         {
6539           hi = 0;
6540           if (width < HOST_BITS_PER_WIDE_INT)
6541             lo &= ~((unsigned HOST_WIDE_INT) (-1) << width);
6542         }
6543
6544       switch (DECL_FUNCTION_CODE (fndecl))
6545         {
6546         case BUILT_IN_FFS:
6547         case BUILT_IN_FFSL:
6548         case BUILT_IN_FFSLL:
6549           if (lo != 0)
6550             result = exact_log2 (lo & -lo) + 1;
6551           else if (hi != 0)
6552             result = HOST_BITS_PER_WIDE_INT + exact_log2 (hi & -hi) + 1;
6553           else
6554             result = 0;
6555           break;
6556
6557         case BUILT_IN_CLZ:
6558         case BUILT_IN_CLZL:
6559         case BUILT_IN_CLZLL:
6560           if (hi != 0)
6561             result = width - floor_log2 (hi) - 1 - HOST_BITS_PER_WIDE_INT;
6562           else if (lo != 0)
6563             result = width - floor_log2 (lo) - 1;
6564           else if (! CLZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
6565             result = width;
6566           break;
6567
6568         case BUILT_IN_CTZ:
6569         case BUILT_IN_CTZL:
6570         case BUILT_IN_CTZLL:
6571           if (lo != 0)
6572             result = exact_log2 (lo & -lo);
6573           else if (hi != 0)
6574             result = HOST_BITS_PER_WIDE_INT + exact_log2 (hi & -hi);
6575           else if (! CTZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
6576             result = width;
6577           break;
6578
6579         case BUILT_IN_POPCOUNT:
6580         case BUILT_IN_POPCOUNTL:
6581         case BUILT_IN_POPCOUNTLL:
6582           result = 0;
6583           while (lo)
6584             result++, lo &= lo - 1;
6585           while (hi)
6586             result++, hi &= hi - 1;
6587           break;
6588
6589         case BUILT_IN_PARITY:
6590         case BUILT_IN_PARITYL:
6591         case BUILT_IN_PARITYLL:
6592           result = 0;
6593           while (lo)
6594             result++, lo &= lo - 1;
6595           while (hi)
6596             result++, hi &= hi - 1;
6597           result &= 1;
6598           break;
6599
6600         default:
6601           gcc_unreachable ();
6602         }
6603
6604       return build_int_cst (TREE_TYPE (exp), result);
6605     }
6606
6607   return NULL_TREE;
6608 }
6609
6610 /* Return true if EXPR is the real constant contained in VALUE.  */
6611
6612 static bool
6613 real_dconstp (tree expr, const REAL_VALUE_TYPE *value)
6614 {
6615   STRIP_NOPS (expr);
6616
6617   return ((TREE_CODE (expr) == REAL_CST
6618            && ! TREE_CONSTANT_OVERFLOW (expr)
6619            && REAL_VALUES_EQUAL (TREE_REAL_CST (expr), *value))
6620           || (TREE_CODE (expr) == COMPLEX_CST
6621               && real_dconstp (TREE_REALPART (expr), value)
6622               && real_zerop (TREE_IMAGPART (expr))));
6623 }
6624
6625 /* A subroutine of fold_builtin to fold the various logarithmic
6626    functions.  EXP is the CALL_EXPR of a call to a builtin logN
6627    function.  VALUE is the base of the logN function.  */
6628
6629 static tree
6630 fold_builtin_logarithm (tree exp, const REAL_VALUE_TYPE *value)
6631 {
6632   tree arglist = TREE_OPERAND (exp, 1);
6633
6634   if (validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
6635     {
6636       tree fndecl = get_callee_fndecl (exp);
6637       tree type = TREE_TYPE (TREE_TYPE (fndecl));
6638       tree arg = TREE_VALUE (arglist);
6639       const enum built_in_function fcode = builtin_mathfn_code (arg);
6640
6641       /* Optimize logN(1.0) = 0.0.  */
6642       if (real_onep (arg))
6643         return build_real (type, dconst0);
6644
6645       /* Optimize logN(N) = 1.0.  If N can't be truncated to MODE
6646          exactly, then only do this if flag_unsafe_math_optimizations.  */
6647       if (exact_real_truncate (TYPE_MODE (type), value)
6648           || flag_unsafe_math_optimizations)
6649         {
6650           const REAL_VALUE_TYPE value_truncate =
6651             real_value_truncate (TYPE_MODE (type), *value);
6652           if (real_dconstp (arg, &value_truncate))
6653             return build_real (type, dconst1);
6654         }
6655
6656       /* Special case, optimize logN(expN(x)) = x.  */
6657       if (flag_unsafe_math_optimizations
6658           && ((value == &dconste
6659                && (fcode == BUILT_IN_EXP
6660                    || fcode == BUILT_IN_EXPF
6661                    || fcode == BUILT_IN_EXPL))
6662               || (value == &dconst2
6663                   && (fcode == BUILT_IN_EXP2
6664                       || fcode == BUILT_IN_EXP2F
6665                       || fcode == BUILT_IN_EXP2L))
6666               || (value == &dconst10 && (BUILTIN_EXP10_P (fcode)))))
6667         return fold_convert (type, TREE_VALUE (TREE_OPERAND (arg, 1)));
6668
6669       /* Optimize logN(func()) for various exponential functions.  We
6670          want to determine the value "x" and the power "exponent" in
6671          order to transform logN(x**exponent) into exponent*logN(x).  */
6672       if (flag_unsafe_math_optimizations)
6673         {
6674           tree exponent = 0, x = 0;
6675
6676           switch (fcode)
6677           {
6678           case BUILT_IN_EXP:
6679           case BUILT_IN_EXPF:
6680           case BUILT_IN_EXPL:
6681             /* Prepare to do logN(exp(exponent) -> exponent*logN(e).  */
6682             x = build_real (type,
6683                             real_value_truncate (TYPE_MODE (type), dconste));
6684             exponent = TREE_VALUE (TREE_OPERAND (arg, 1));
6685             break;
6686           case BUILT_IN_EXP2:
6687           case BUILT_IN_EXP2F:
6688           case BUILT_IN_EXP2L:
6689             /* Prepare to do logN(exp2(exponent) -> exponent*logN(2).  */
6690             x = build_real (type, dconst2);
6691             exponent = TREE_VALUE (TREE_OPERAND (arg, 1));
6692             break;
6693           case BUILT_IN_EXP10:
6694           case BUILT_IN_EXP10F:
6695           case BUILT_IN_EXP10L:
6696           case BUILT_IN_POW10:
6697           case BUILT_IN_POW10F:
6698           case BUILT_IN_POW10L:
6699             /* Prepare to do logN(exp10(exponent) -> exponent*logN(10).  */
6700             x = build_real (type, dconst10);
6701             exponent = TREE_VALUE (TREE_OPERAND (arg, 1));
6702             break;
6703           case BUILT_IN_SQRT:
6704           case BUILT_IN_SQRTF:
6705           case BUILT_IN_SQRTL:
6706             /* Prepare to do logN(sqrt(x) -> 0.5*logN(x).  */
6707             x = TREE_VALUE (TREE_OPERAND (arg, 1));
6708             exponent = build_real (type, dconsthalf);
6709             break;
6710           case BUILT_IN_CBRT:
6711           case BUILT_IN_CBRTF:
6712           case BUILT_IN_CBRTL:
6713             /* Prepare to do logN(cbrt(x) -> (1/3)*logN(x).  */
6714             x = TREE_VALUE (TREE_OPERAND (arg, 1));
6715             exponent = build_real (type, real_value_truncate (TYPE_MODE (type),
6716                                                               dconstthird));
6717             break;
6718           case BUILT_IN_POW:
6719           case BUILT_IN_POWF:
6720           case BUILT_IN_POWL:
6721             /* Prepare to do logN(pow(x,exponent) -> exponent*logN(x).  */
6722             x = TREE_VALUE (TREE_OPERAND (arg, 1));
6723             exponent = TREE_VALUE (TREE_CHAIN (TREE_OPERAND (arg, 1)));
6724             break;
6725           default:
6726             break;
6727           }
6728
6729           /* Now perform the optimization.  */
6730           if (x && exponent)
6731             {
6732               tree logfn;
6733               arglist = build_tree_list (NULL_TREE, x);
6734               logfn = build_function_call_expr (fndecl, arglist);
6735               return fold (build2 (MULT_EXPR, type, exponent, logfn));
6736             }
6737         }
6738     }
6739
6740   return 0;
6741 }
6742
6743 /* Fold a builtin function call to pow, powf, or powl.  Return
6744    NULL_TREE if no simplification can be made.  */
6745 static tree
6746 fold_builtin_pow (tree fndecl, tree arglist, tree type)
6747 {
6748   enum built_in_function fcode;
6749   tree arg0 = TREE_VALUE (arglist);
6750   tree arg1 = TREE_VALUE (TREE_CHAIN (arglist));
6751
6752   if (!validate_arglist (arglist, REAL_TYPE, REAL_TYPE, VOID_TYPE))
6753     return NULL_TREE;
6754
6755   /* Optimize pow(1.0,y) = 1.0.  */
6756   if (real_onep (arg0))
6757     return omit_one_operand (type, build_real (type, dconst1), arg1);
6758
6759   if (TREE_CODE (arg1) == REAL_CST
6760       && ! TREE_CONSTANT_OVERFLOW (arg1))
6761     {
6762       REAL_VALUE_TYPE c;
6763       c = TREE_REAL_CST (arg1);
6764
6765       /* Optimize pow(x,0.0) = 1.0.  */
6766       if (REAL_VALUES_EQUAL (c, dconst0))
6767         return omit_one_operand (type, build_real (type, dconst1),
6768                                  arg0);
6769
6770       /* Optimize pow(x,1.0) = x.  */
6771       if (REAL_VALUES_EQUAL (c, dconst1))
6772         return arg0;
6773
6774       /* Optimize pow(x,-1.0) = 1.0/x.  */
6775       if (REAL_VALUES_EQUAL (c, dconstm1))
6776         return fold (build2 (RDIV_EXPR, type,
6777                              build_real (type, dconst1), arg0));
6778
6779       /* Optimize pow(x,0.5) = sqrt(x).  */
6780       if (flag_unsafe_math_optimizations
6781           && REAL_VALUES_EQUAL (c, dconsthalf))
6782         {
6783           tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
6784
6785           if (sqrtfn != NULL_TREE)
6786             {
6787               tree arglist = build_tree_list (NULL_TREE, arg0);
6788               return build_function_call_expr (sqrtfn, arglist);
6789             }
6790         }
6791
6792       /* Attempt to evaluate pow at compile-time.  */
6793       if (TREE_CODE (arg0) == REAL_CST
6794           && ! TREE_CONSTANT_OVERFLOW (arg0))
6795         {
6796           REAL_VALUE_TYPE cint;
6797           HOST_WIDE_INT n;
6798
6799           n = real_to_integer (&c);
6800           real_from_integer (&cint, VOIDmode, n,
6801                              n < 0 ? -1 : 0, 0);
6802           if (real_identical (&c, &cint))
6803             {
6804               REAL_VALUE_TYPE x;
6805               bool inexact;
6806
6807               x = TREE_REAL_CST (arg0);
6808               inexact = real_powi (&x, TYPE_MODE (type), &x, n);
6809               if (flag_unsafe_math_optimizations || !inexact)
6810                 return build_real (type, x);
6811             }
6812         }
6813     }
6814
6815   /* Optimize pow(expN(x),y) = expN(x*y).  */
6816   fcode = builtin_mathfn_code (arg0);
6817   if (flag_unsafe_math_optimizations && BUILTIN_EXPONENT_P (fcode))
6818     {
6819       tree expfn = TREE_OPERAND (TREE_OPERAND (arg0, 0), 0);
6820       tree arg = TREE_VALUE (TREE_OPERAND (arg0, 1));
6821       arg = fold (build2 (MULT_EXPR, type, arg, arg1));
6822       arglist = build_tree_list (NULL_TREE, arg);
6823       return build_function_call_expr (expfn, arglist);
6824     }
6825
6826   /* Optimize pow(sqrt(x),y) = pow(x,y*0.5).  */
6827   if (flag_unsafe_math_optimizations && BUILTIN_SQRT_P (fcode))
6828     {
6829       tree narg0 = TREE_VALUE (TREE_OPERAND (arg0, 1));
6830       tree narg1 = fold (build2 (MULT_EXPR, type, arg1,
6831                                  build_real (type, dconsthalf)));
6832
6833       arglist = tree_cons (NULL_TREE, narg0,
6834                            build_tree_list (NULL_TREE, narg1));
6835       return build_function_call_expr (fndecl, arglist);
6836     }
6837
6838   /* Optimize pow(pow(x,y),z) = pow(x,y*z).  */
6839   if (flag_unsafe_math_optimizations
6840       && (fcode == BUILT_IN_POW
6841           || fcode == BUILT_IN_POWF
6842           || fcode == BUILT_IN_POWL))
6843     {
6844       tree arg00 = TREE_VALUE (TREE_OPERAND (arg0, 1));
6845       tree arg01 = TREE_VALUE (TREE_CHAIN (TREE_OPERAND (arg0, 1)));
6846       tree narg1 = fold (build2 (MULT_EXPR, type, arg01, arg1));
6847       arglist = tree_cons (NULL_TREE, arg00,
6848                            build_tree_list (NULL_TREE, narg1));
6849       return build_function_call_expr (fndecl, arglist);
6850     }
6851   return NULL_TREE;
6852 }
6853
6854 /* A subroutine of fold_builtin to fold the various exponent
6855    functions.  EXP is the CALL_EXPR of a call to a builtin function.
6856    VALUE is the value which will be raised to a power.  */
6857
6858 static tree
6859 fold_builtin_exponent (tree exp, const REAL_VALUE_TYPE *value)
6860 {
6861   tree arglist = TREE_OPERAND (exp, 1);
6862
6863   if (validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
6864     {
6865       tree fndecl = get_callee_fndecl (exp);
6866       tree type = TREE_TYPE (TREE_TYPE (fndecl));
6867       tree arg = TREE_VALUE (arglist);
6868
6869       /* Optimize exp*(0.0) = 1.0.  */
6870       if (real_zerop (arg))
6871         return build_real (type, dconst1);
6872
6873       /* Optimize expN(1.0) = N.  */
6874       if (real_onep (arg))
6875         {
6876           REAL_VALUE_TYPE cst;
6877
6878           real_convert (&cst, TYPE_MODE (type), value);
6879           return build_real (type, cst);
6880         }
6881
6882       /* Attempt to evaluate expN(integer) at compile-time.  */
6883       if (flag_unsafe_math_optimizations
6884           && TREE_CODE (arg) == REAL_CST
6885           && ! TREE_CONSTANT_OVERFLOW (arg))
6886         {
6887           REAL_VALUE_TYPE cint;
6888           REAL_VALUE_TYPE c;
6889           HOST_WIDE_INT n;
6890
6891           c = TREE_REAL_CST (arg);
6892           n = real_to_integer (&c);
6893           real_from_integer (&cint, VOIDmode, n,
6894                              n < 0 ? -1 : 0, 0);
6895           if (real_identical (&c, &cint))
6896             {
6897               REAL_VALUE_TYPE x;
6898
6899               real_powi (&x, TYPE_MODE (type), value, n);
6900               return build_real (type, x);
6901             }
6902         }
6903
6904       /* Optimize expN(logN(x)) = x.  */
6905       if (flag_unsafe_math_optimizations)
6906         {
6907           const enum built_in_function fcode = builtin_mathfn_code (arg);
6908
6909           if ((value == &dconste
6910                && (fcode == BUILT_IN_LOG
6911                    || fcode == BUILT_IN_LOGF
6912                    || fcode == BUILT_IN_LOGL))
6913               || (value == &dconst2
6914                   && (fcode == BUILT_IN_LOG2
6915                       || fcode == BUILT_IN_LOG2F
6916                       || fcode == BUILT_IN_LOG2L))
6917               || (value == &dconst10
6918                   && (fcode == BUILT_IN_LOG10
6919                       || fcode == BUILT_IN_LOG10F
6920                       || fcode == BUILT_IN_LOG10L)))
6921             return fold_convert (type, TREE_VALUE (TREE_OPERAND (arg, 1)));
6922         }
6923     }
6924
6925   return 0;
6926 }
6927
6928 /* Fold function call to builtin memcpy.  Return
6929    NULL_TREE if no simplification can be made.  */
6930
6931 static tree
6932 fold_builtin_memcpy (tree exp)
6933 {
6934   tree arglist = TREE_OPERAND (exp, 1);
6935   tree dest, src, len;
6936
6937   if (!validate_arglist (arglist,
6938                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
6939     return 0;
6940
6941   dest = TREE_VALUE (arglist);
6942   src = TREE_VALUE (TREE_CHAIN (arglist));
6943   len = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (arglist)));
6944
6945   /* If the LEN parameter is zero, return DEST.  */
6946   if (integer_zerop (len))
6947     return omit_one_operand (TREE_TYPE (exp), dest, src);
6948
6949   /* If SRC and DEST are the same (and not volatile), return DEST.  */
6950   if (operand_equal_p (src, dest, 0))
6951     return omit_one_operand (TREE_TYPE (exp), dest, len);
6952
6953   return 0;
6954 }
6955
6956 /* Fold function call to builtin mempcpy.  Return
6957    NULL_TREE if no simplification can be made.  */
6958
6959 static tree
6960 fold_builtin_mempcpy (tree arglist, tree type, int endp)
6961 {
6962   if (validate_arglist (arglist,
6963                         POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
6964     {
6965       tree dest = TREE_VALUE (arglist);
6966       tree src = TREE_VALUE (TREE_CHAIN (arglist));
6967       tree len = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (arglist)));
6968
6969       /* If the LEN parameter is zero, return DEST.  */
6970       if (integer_zerop (len))
6971         return omit_one_operand (type, dest, src);
6972
6973       /* If SRC and DEST are the same (and not volatile), return DEST+LEN.  */
6974       if (operand_equal_p (src, dest, 0))
6975         {
6976           if (endp == 0)
6977             return omit_one_operand (type, dest, len);
6978
6979           if (endp == 2)
6980             len = fold (build2 (MINUS_EXPR, TREE_TYPE (len), len,
6981                                 ssize_int (1)));
6982       
6983           len = fold_convert (TREE_TYPE (dest), len);
6984           len = fold (build2 (PLUS_EXPR, TREE_TYPE (dest), dest, len));
6985           return fold_convert (type, len);
6986         }
6987     }
6988   return 0;
6989 }
6990
6991 /* Fold function call to builtin memmove.  Return
6992    NULL_TREE if no simplification can be made.  */
6993
6994 static tree
6995 fold_builtin_memmove (tree arglist, tree type)
6996 {
6997   tree dest, src, len;
6998
6999   if (!validate_arglist (arglist,
7000                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
7001     return 0;
7002
7003   dest = TREE_VALUE (arglist);
7004   src = TREE_VALUE (TREE_CHAIN (arglist));
7005   len = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (arglist)));
7006
7007   /* If the LEN parameter is zero, return DEST.  */
7008   if (integer_zerop (len))
7009     return omit_one_operand (type, dest, src);
7010
7011   /* If SRC and DEST are the same (and not volatile), return DEST.  */
7012   if (operand_equal_p (src, dest, 0))
7013     return omit_one_operand (type, dest, len);
7014
7015   return 0;
7016 }
7017
7018 /* Fold function call to builtin strcpy.  If LEN is not NULL, it represents
7019    the length of the string to be copied.  Return NULL_TREE if no
7020    simplification can be made.  */
7021
7022 tree
7023 fold_builtin_strcpy (tree exp, tree len)
7024 {
7025   tree arglist = TREE_OPERAND (exp, 1);
7026   tree dest, src, fn;
7027
7028   if (!validate_arglist (arglist,
7029                          POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
7030     return 0;
7031
7032   dest = TREE_VALUE (arglist);
7033   src = TREE_VALUE (TREE_CHAIN (arglist));
7034
7035   /* If SRC and DEST are the same (and not volatile), return DEST.  */
7036   if (operand_equal_p (src, dest, 0))
7037     return fold_convert (TREE_TYPE (exp), dest);
7038
7039   if (optimize_size)
7040     return 0;
7041
7042   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
7043   if (!fn)
7044     return 0;
7045
7046   if (!len)
7047     {
7048       len = c_strlen (src, 1);
7049       if (! len || TREE_SIDE_EFFECTS (len))
7050         return 0;
7051     }
7052
7053   len = size_binop (PLUS_EXPR, len, ssize_int (1));
7054   arglist = build_tree_list (NULL_TREE, len);
7055   arglist = tree_cons (NULL_TREE, src, arglist);
7056   arglist = tree_cons (NULL_TREE, dest, arglist);
7057   return fold_convert (TREE_TYPE (exp),
7058                        build_function_call_expr (fn, arglist));
7059 }
7060
7061 /* Fold function call to builtin strncpy.  If SLEN is not NULL, it represents
7062    the length of the source string.  Return NULL_TREE if no simplification
7063    can be made.  */
7064
7065 tree
7066 fold_builtin_strncpy (tree exp, tree slen)
7067 {
7068   tree arglist = TREE_OPERAND (exp, 1);
7069   tree dest, src, len, fn;
7070
7071   if (!validate_arglist (arglist,
7072                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
7073     return 0;
7074
7075   dest = TREE_VALUE (arglist);
7076   src = TREE_VALUE (TREE_CHAIN (arglist));
7077   len = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (arglist)));
7078
7079   /* If the LEN parameter is zero, return DEST.  */
7080   if (integer_zerop (len))
7081     return omit_one_operand (TREE_TYPE (exp), dest, src);
7082
7083   /* We can't compare slen with len as constants below if len is not a
7084      constant.  */
7085   if (len == 0 || TREE_CODE (len) != INTEGER_CST)
7086     return 0;
7087
7088   if (!slen)
7089     slen = c_strlen (src, 1);
7090
7091   /* Now, we must be passed a constant src ptr parameter.  */
7092   if (slen == 0 || TREE_CODE (slen) != INTEGER_CST)
7093     return 0;
7094
7095   slen = size_binop (PLUS_EXPR, slen, ssize_int (1));
7096
7097   /* We do not support simplification of this case, though we do
7098      support it when expanding trees into RTL.  */
7099   /* FIXME: generate a call to __builtin_memset.  */
7100   if (tree_int_cst_lt (slen, len))
7101     return 0;
7102
7103   /* OK transform into builtin memcpy.  */
7104   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
7105   if (!fn)
7106     return 0;
7107   return fold_convert (TREE_TYPE (exp),
7108                        build_function_call_expr (fn, arglist));
7109 }
7110
7111 /* Fold function call to builtin memcmp.  Return
7112    NULL_TREE if no simplification can be made.  */
7113
7114 static tree
7115 fold_builtin_memcmp (tree arglist)
7116 {
7117   tree arg1, arg2, len;
7118   const char *p1, *p2;
7119
7120   if (!validate_arglist (arglist,
7121                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
7122     return 0;
7123
7124   arg1 = TREE_VALUE (arglist);
7125   arg2 = TREE_VALUE (TREE_CHAIN (arglist));
7126   len = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (arglist)));
7127
7128   /* If the LEN parameter is zero, return zero.  */
7129   if (integer_zerop (len))
7130     return omit_two_operands (integer_type_node, integer_zero_node,
7131                               arg1, arg2);
7132
7133   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
7134   if (operand_equal_p (arg1, arg2, 0))
7135     return omit_one_operand (integer_type_node, integer_zero_node, len);
7136
7137   p1 = c_getstr (arg1);
7138   p2 = c_getstr (arg2);
7139
7140   /* If all arguments are constant, and the value of len is not greater
7141      than the lengths of arg1 and arg2, evaluate at compile-time.  */
7142   if (host_integerp (len, 1) && p1 && p2
7143       && compare_tree_int (len, strlen (p1) + 1) <= 0
7144       && compare_tree_int (len, strlen (p2) + 1) <= 0)
7145     {
7146       const int r = memcmp (p1, p2, tree_low_cst (len, 1));
7147
7148       if (r > 0)
7149         return integer_one_node;
7150       else if (r < 0)
7151         return integer_minus_one_node;
7152       else
7153         return integer_zero_node;
7154     }
7155
7156   /* If len parameter is one, return an expression corresponding to
7157      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
7158   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
7159     {
7160       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
7161       tree cst_uchar_ptr_node = build_pointer_type (cst_uchar_node);
7162       tree ind1 = fold_convert (integer_type_node,
7163                                 build1 (INDIRECT_REF, cst_uchar_node,
7164                                         fold_convert (cst_uchar_ptr_node,
7165                                                       arg1)));
7166       tree ind2 = fold_convert (integer_type_node,
7167                                 build1 (INDIRECT_REF, cst_uchar_node,
7168                                         fold_convert (cst_uchar_ptr_node,
7169                                                       arg2)));
7170       return fold (build2 (MINUS_EXPR, integer_type_node, ind1, ind2));
7171     }
7172
7173   return 0;
7174 }
7175
7176 /* Fold function call to builtin strcmp.  Return
7177    NULL_TREE if no simplification can be made.  */
7178
7179 static tree
7180 fold_builtin_strcmp (tree arglist)
7181 {
7182   tree arg1, arg2;
7183   const char *p1, *p2;
7184
7185   if (!validate_arglist (arglist, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
7186     return 0;
7187
7188   arg1 = TREE_VALUE (arglist);
7189   arg2 = TREE_VALUE (TREE_CHAIN (arglist));
7190
7191   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
7192   if (operand_equal_p (arg1, arg2, 0))
7193     return integer_zero_node;
7194
7195   p1 = c_getstr (arg1);
7196   p2 = c_getstr (arg2);
7197
7198   if (p1 && p2)
7199     {
7200       const int i = strcmp (p1, p2);
7201       if (i < 0)
7202         return integer_minus_one_node;
7203       else if (i > 0)
7204         return integer_one_node;
7205       else
7206         return integer_zero_node;
7207     }
7208
7209   /* If the second arg is "", return *(const unsigned char*)arg1.  */
7210   if (p2 && *p2 == '\0')
7211     {
7212       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
7213       tree cst_uchar_ptr_node = build_pointer_type (cst_uchar_node);
7214       return fold_convert (integer_type_node,
7215                            build1 (INDIRECT_REF, cst_uchar_node,
7216                                    fold_convert (cst_uchar_ptr_node,
7217                                                  arg1)));
7218     }
7219
7220   /* If the first arg is "", return -*(const unsigned char*)arg2.  */
7221   if (p1 && *p1 == '\0')
7222     {
7223       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
7224       tree cst_uchar_ptr_node = build_pointer_type (cst_uchar_node);
7225       tree temp = fold_convert (integer_type_node,
7226                                 build1 (INDIRECT_REF, cst_uchar_node,
7227                                         fold_convert (cst_uchar_ptr_node,
7228                                                       arg2)));
7229       return fold (build1 (NEGATE_EXPR, integer_type_node, temp));
7230     }
7231
7232   return 0;
7233 }
7234
7235 /* Fold function call to builtin strncmp.  Return
7236    NULL_TREE if no simplification can be made.  */
7237
7238 static tree
7239 fold_builtin_strncmp (tree arglist)
7240 {
7241   tree arg1, arg2, len;
7242   const char *p1, *p2;
7243
7244   if (!validate_arglist (arglist,
7245                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
7246     return 0;
7247
7248   arg1 = TREE_VALUE (arglist);
7249   arg2 = TREE_VALUE (TREE_CHAIN (arglist));
7250   len = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (arglist)));
7251
7252   /* If the LEN parameter is zero, return zero.  */
7253   if (integer_zerop (len))
7254     return omit_two_operands (integer_type_node, integer_zero_node,
7255                               arg1, arg2);
7256
7257   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
7258   if (operand_equal_p (arg1, arg2, 0))
7259     return omit_one_operand (integer_type_node, integer_zero_node, len);
7260
7261   p1 = c_getstr (arg1);
7262   p2 = c_getstr (arg2);
7263
7264   if (host_integerp (len, 1) && p1 && p2)
7265     {
7266       const int i = strncmp (p1, p2, tree_low_cst (len, 1));
7267       if (i > 0)
7268         return integer_one_node;
7269       else if (i < 0)
7270         return integer_minus_one_node;
7271       else
7272         return integer_zero_node;
7273     }
7274
7275   /* If the second arg is "", and the length is greater than zero,
7276      return *(const unsigned char*)arg1.  */
7277   if (p2 && *p2 == '\0'
7278       && TREE_CODE (len) == INTEGER_CST
7279       && tree_int_cst_sgn (len) == 1)
7280     {
7281       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
7282       tree cst_uchar_ptr_node = build_pointer_type (cst_uchar_node);
7283       return fold_convert (integer_type_node,
7284                            build1 (INDIRECT_REF, cst_uchar_node,
7285                                    fold_convert (cst_uchar_ptr_node,
7286                                                  arg1)));
7287     }
7288
7289   /* If the first arg is "", and the length is greater than zero,
7290      return -*(const unsigned char*)arg2.  */
7291   if (p1 && *p1 == '\0'
7292       && TREE_CODE (len) == INTEGER_CST
7293       && tree_int_cst_sgn (len) == 1)
7294     {
7295       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
7296       tree cst_uchar_ptr_node = build_pointer_type (cst_uchar_node);
7297       tree temp = fold_convert (integer_type_node,
7298                                 build1 (INDIRECT_REF, cst_uchar_node,
7299                                         fold_convert (cst_uchar_ptr_node,
7300                                                       arg2)));
7301       return fold (build1 (NEGATE_EXPR, integer_type_node, temp));
7302     }
7303
7304   /* If len parameter is one, return an expression corresponding to
7305      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
7306   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
7307     {
7308       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
7309       tree cst_uchar_ptr_node = build_pointer_type (cst_uchar_node);
7310       tree ind1 = fold_convert (integer_type_node,
7311                                 build1 (INDIRECT_REF, cst_uchar_node,
7312                                         fold_convert (cst_uchar_ptr_node,
7313                                                       arg1)));
7314       tree ind2 = fold_convert (integer_type_node,
7315                                 build1 (INDIRECT_REF, cst_uchar_node,
7316                                         fold_convert (cst_uchar_ptr_node,
7317                                                       arg2)));
7318       return fold (build2 (MINUS_EXPR, integer_type_node, ind1, ind2));
7319     }
7320
7321   return 0;
7322 }
7323
7324 /* Fold function call to builtin signbit, signbitf or signbitl.  Return
7325    NULL_TREE if no simplification can be made.  */
7326
7327 static tree
7328 fold_builtin_signbit (tree exp)
7329 {
7330   tree arglist = TREE_OPERAND (exp, 1);
7331   tree arg, temp;
7332
7333   if (!validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
7334     return NULL_TREE;
7335
7336   arg = TREE_VALUE (arglist);
7337
7338   /* If ARG is a compile-time constant, determine the result.  */
7339   if (TREE_CODE (arg) == REAL_CST
7340       && !TREE_CONSTANT_OVERFLOW (arg))
7341     {
7342       REAL_VALUE_TYPE c;
7343
7344       c = TREE_REAL_CST (arg);
7345       temp = REAL_VALUE_NEGATIVE (c) ? integer_one_node : integer_zero_node;
7346       return fold_convert (TREE_TYPE (exp), temp);
7347     }
7348
7349   /* If ARG is non-negative, the result is always zero.  */
7350   if (tree_expr_nonnegative_p (arg))
7351     return omit_one_operand (TREE_TYPE (exp), integer_zero_node, arg);
7352
7353   /* If ARG's format doesn't have signed zeros, return "arg < 0.0".  */
7354   if (!HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (arg))))
7355     return fold (build2 (LT_EXPR, TREE_TYPE (exp), arg,
7356                          build_real (TREE_TYPE (arg), dconst0)));
7357
7358   return NULL_TREE;
7359 }
7360
7361 /* Fold function call to builtin copysign, copysignf or copysignl.
7362    Return NULL_TREE if no simplification can be made.  */
7363
7364 static tree
7365 fold_builtin_copysign (tree arglist, tree type)
7366 {
7367   tree arg1, arg2;
7368
7369   if (!validate_arglist (arglist, REAL_TYPE, REAL_TYPE, VOID_TYPE))
7370     return NULL_TREE;
7371
7372   arg1 = TREE_VALUE (arglist);
7373   arg2 = TREE_VALUE (TREE_CHAIN (arglist));
7374
7375   /* copysign(X,X) is X.  */
7376   if (operand_equal_p (arg1, arg2, 0))
7377     return fold_convert (type, arg1);
7378
7379   /* If ARG1 and ARG2 are compile-time constants, determine the result.  */
7380   if (TREE_CODE (arg1) == REAL_CST
7381       && TREE_CODE (arg2) == REAL_CST
7382       && !TREE_CONSTANT_OVERFLOW (arg1)
7383       && !TREE_CONSTANT_OVERFLOW (arg2))
7384     {
7385       REAL_VALUE_TYPE c1, c2;
7386
7387       c1 = TREE_REAL_CST (arg1);
7388       c2 = TREE_REAL_CST (arg2);
7389       real_copysign (&c1, &c2);
7390       return build_real (type, c1);
7391       c1.sign = c2.sign;
7392     }
7393
7394   /* copysign(X, Y) is fabs(X) when Y is always non-negative.
7395      Remember to evaluate Y for side-effects.  */
7396   if (tree_expr_nonnegative_p (arg2))
7397     return omit_one_operand (type,
7398                              fold (build1 (ABS_EXPR, type, arg1)),
7399                              arg2);
7400
7401   return NULL_TREE;
7402 }
7403
7404 /* Fold a call to builtin isascii.  */
7405
7406 static tree
7407 fold_builtin_isascii (tree arglist)
7408 {
7409   if (! validate_arglist (arglist, INTEGER_TYPE, VOID_TYPE))
7410     return 0;
7411   else
7412     {
7413       /* Transform isascii(c) -> ((c & ~0x7f) == 0).  */
7414       tree arg = TREE_VALUE (arglist);
7415
7416       arg = build2 (BIT_AND_EXPR, integer_type_node, arg,
7417                     build_int_cst (NULL_TREE,
7418                                    ~ (unsigned HOST_WIDE_INT) 0x7f));
7419       arg = fold (build2 (EQ_EXPR, integer_type_node,
7420                           arg, integer_zero_node));
7421
7422       if (in_gimple_form && !TREE_CONSTANT (arg))
7423         return NULL_TREE;
7424       else
7425         return arg;
7426     }
7427 }
7428
7429 /* Fold a call to builtin toascii.  */
7430
7431 static tree
7432 fold_builtin_toascii (tree arglist)
7433 {
7434   if (! validate_arglist (arglist, INTEGER_TYPE, VOID_TYPE))
7435     return 0;
7436   else
7437     {
7438       /* Transform toascii(c) -> (c & 0x7f).  */
7439       tree arg = TREE_VALUE (arglist);
7440
7441       return fold (build2 (BIT_AND_EXPR, integer_type_node, arg,
7442                            build_int_cst (NULL_TREE, 0x7f)));
7443     }
7444 }
7445
7446 /* Fold a call to builtin isdigit.  */
7447
7448 static tree
7449 fold_builtin_isdigit (tree arglist)
7450 {
7451   if (! validate_arglist (arglist, INTEGER_TYPE, VOID_TYPE))
7452     return 0;
7453   else
7454     {
7455       /* Transform isdigit(c) -> (unsigned)(c) - '0' <= 9.  */
7456       /* According to the C standard, isdigit is unaffected by locale.  */
7457       tree arg = TREE_VALUE (arglist);
7458       arg = fold_convert (unsigned_type_node, arg);
7459       arg = build2 (MINUS_EXPR, unsigned_type_node, arg,
7460                     build_int_cst (unsigned_type_node, TARGET_DIGIT0));
7461       arg = build2 (LE_EXPR, integer_type_node, arg,
7462                     build_int_cst (unsigned_type_node, 9));
7463       arg = fold (arg);
7464       if (in_gimple_form && !TREE_CONSTANT (arg))
7465         return NULL_TREE;
7466       else
7467         return arg;
7468     }
7469 }
7470
7471 /* Fold a call to fabs, fabsf or fabsl.  */
7472
7473 static tree
7474 fold_builtin_fabs (tree arglist, tree type)
7475 {
7476   tree arg;
7477
7478   if (!validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
7479     return 0;
7480
7481   arg = TREE_VALUE (arglist);
7482   if (TREE_CODE (arg) == REAL_CST)
7483     return fold_abs_const (arg, type);
7484   return fold (build1 (ABS_EXPR, type, arg));
7485 }
7486
7487 /* Fold a call to abs, labs, llabs or imaxabs.  */
7488
7489 static tree
7490 fold_builtin_abs (tree arglist, tree type)
7491 {
7492   tree arg;
7493
7494   if (!validate_arglist (arglist, INTEGER_TYPE, VOID_TYPE))
7495     return 0;
7496
7497   arg = TREE_VALUE (arglist);
7498   if (TREE_CODE (arg) == INTEGER_CST)
7499     return fold_abs_const (arg, type);
7500   return fold (build1 (ABS_EXPR, type, arg));
7501 }
7502
7503 /* Fold a call to __builtin_isnan(), __builtin_isinf, __builtin_finite.
7504    EXP is the CALL_EXPR for the call.  */
7505
7506 static tree
7507 fold_builtin_classify (tree exp, int builtin_index)
7508 {
7509   tree fndecl = get_callee_fndecl (exp);
7510   tree arglist = TREE_OPERAND (exp, 1);
7511   tree type = TREE_TYPE (TREE_TYPE (fndecl));
7512   tree arg;
7513   REAL_VALUE_TYPE r;
7514
7515   if (!validate_arglist (arglist, REAL_TYPE, VOID_TYPE))
7516     {
7517       /* Check that we have exactly one argument.  */
7518       if (arglist == 0)
7519         {
7520           error ("too few arguments to function %qs",
7521                  IDENTIFIER_POINTER (DECL_NAME (fndecl)));
7522           return error_mark_node;
7523         }
7524       else if (TREE_CHAIN (arglist) != 0)
7525         {
7526           error ("too many arguments to function %qs",
7527                  IDENTIFIER_POINTER (DECL_NAME (fndecl)));
7528           return error_mark_node;
7529         }
7530       else
7531         {
7532           error ("non-floating-point argument to function %qs",
7533                  IDENTIFIER_POINTER (DECL_NAME (fndecl)));
7534           return error_mark_node;
7535         }
7536     }
7537
7538   arg = TREE_VALUE (arglist);
7539   switch (builtin_index)
7540     {
7541     case BUILT_IN_ISINF:
7542       if (!MODE_HAS_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
7543         return omit_one_operand (type, integer_zero_node, arg);
7544
7545       if (TREE_CODE (arg) == REAL_CST)
7546         {
7547           r = TREE_REAL_CST (arg);
7548           if (real_isinf (&r))
7549             return real_compare (GT_EXPR, &r, &dconst0)
7550                    ? integer_one_node : integer_minus_one_node;
7551           else
7552             return integer_zero_node;
7553         }
7554
7555       return NULL_TREE;
7556
7557     case BUILT_IN_FINITE:
7558       if (!MODE_HAS_NANS (TYPE_MODE (TREE_TYPE (arg)))
7559           && !MODE_HAS_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
7560         return omit_one_operand (type, integer_zero_node, arg);
7561
7562       if (TREE_CODE (arg) == REAL_CST)
7563         {
7564           r = TREE_REAL_CST (arg);
7565           return real_isinf (&r) || real_isnan (&r)
7566                  ? integer_zero_node : integer_one_node;
7567         }
7568
7569       return NULL_TREE;
7570
7571     case BUILT_IN_ISNAN:
7572       if (!MODE_HAS_NANS (TYPE_MODE (TREE_TYPE (arg))))
7573         return omit_one_operand (type, integer_zero_node, arg);
7574
7575       if (TREE_CODE (arg) == REAL_CST)
7576         {
7577           r = TREE_REAL_CST (arg);
7578           return real_isnan (&r) ? integer_one_node : integer_zero_node;
7579         }
7580
7581       arg = builtin_save_expr (arg);
7582       return fold (build2 (UNORDERED_EXPR, type, arg, arg));
7583
7584     default:
7585       gcc_unreachable ();
7586     }
7587 }
7588
7589 /* Fold a call to an unordered comparison function such as
7590    __builtin_isgreater().  EXP is the CALL_EXPR for the call.
7591    UNORDERED_CODE and ORDERED_CODE are comparison codes that give
7592    the opposite of the desired result.  UNORDERED_CODE is used
7593    for modes that can hold NaNs and ORDERED_CODE is used for
7594    the rest.  */
7595
7596 static tree
7597 fold_builtin_unordered_cmp (tree exp,
7598                             enum tree_code unordered_code,
7599                             enum tree_code ordered_code)
7600 {
7601   tree fndecl = get_callee_fndecl (exp);
7602   tree arglist = TREE_OPERAND (exp, 1);
7603   tree type = TREE_TYPE (TREE_TYPE (fndecl));
7604   enum tree_code code;
7605   tree arg0, arg1;
7606   tree type0, type1;
7607   enum tree_code code0, code1;
7608   tree cmp_type = NULL_TREE;
7609
7610   if (!validate_arglist (arglist, REAL_TYPE, REAL_TYPE, VOID_TYPE))
7611     {
7612       /* Check that we have exactly two arguments.  */
7613       if (arglist == 0 || TREE_CHAIN (arglist) == 0)
7614         {
7615           error ("too few arguments to function %qs",
7616                  IDENTIFIER_POINTER (DECL_NAME (fndecl)));
7617           return error_mark_node;
7618         }
7619       else if (TREE_CHAIN (TREE_CHAIN (arglist)) != 0)
7620         {
7621           error ("too many arguments to function %qs",
7622                  IDENTIFIER_POINTER (DECL_NAME (fndecl)));
7623           return error_mark_node;
7624         }
7625     }
7626
7627   arg0 = TREE_VALUE (arglist);
7628   arg1 = TREE_VALUE (TREE_CHAIN (arglist));
7629   
7630   type0 = TREE_TYPE (arg0);
7631   type1 = TREE_TYPE (arg1);
7632   
7633   code0 = TREE_CODE (type0);
7634   code1 = TREE_CODE (type1);
7635   
7636   if (code0 == REAL_TYPE && code1 == REAL_TYPE)
7637     /* Choose the wider of two real types.  */
7638     cmp_type = TYPE_PRECISION (type0) >= TYPE_PRECISION (type1)
7639       ? type0 : type1;
7640   else if (code0 == REAL_TYPE && code1 == INTEGER_TYPE)
7641     cmp_type = type0;
7642   else if (code0 == INTEGER_TYPE && code1 == REAL_TYPE)
7643     cmp_type = type1;
7644   else
7645     {
7646       error ("non-floating-point argument to function %qs",
7647                  IDENTIFIER_POINTER (DECL_NAME (fndecl)));
7648       return error_mark_node;
7649     }
7650   
7651   arg0 = fold_convert (cmp_type, arg0);
7652   arg1 = fold_convert (cmp_type, arg1);
7653
7654   if (unordered_code == UNORDERED_EXPR)
7655     {
7656       if (!MODE_HAS_NANS (TYPE_MODE (TREE_TYPE (arg0))))
7657         return omit_two_operands (type, integer_zero_node, arg0, arg1);
7658       return fold (build2 (UNORDERED_EXPR, type, arg0, arg1));
7659     }
7660
7661   code = MODE_HAS_NANS (TYPE_MODE (TREE_TYPE (arg0))) ? unordered_code
7662                                                       : ordered_code;
7663   return fold (build1 (TRUTH_NOT_EXPR, type,
7664                        fold (build2 (code, type, arg0, arg1))));
7665 }
7666
7667 /* Used by constant folding to simplify calls to builtin functions.  EXP is
7668    the CALL_EXPR of a call to a builtin function.  IGNORE is true if the
7669    result of the function call is ignored.  This function returns NULL_TREE
7670    if no simplification was possible.  */
7671
7672 static tree
7673 fold_builtin_1 (tree exp, bool ignore)
7674 {
7675   tree fndecl = get_callee_fndecl (exp);
7676   tree arglist = TREE_OPERAND (exp, 1);
7677   tree type = TREE_TYPE (TREE_TYPE (fndecl));
7678
7679   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
7680     return targetm.fold_builtin (exp, ignore);
7681
7682   switch (DECL_FUNCTION_CODE (fndecl))
7683     {
7684     case BUILT_IN_FPUTS:
7685       return fold_builtin_fputs (arglist, ignore, false, NULL_TREE);
7686
7687     case BUILT_IN_FPUTS_UNLOCKED:
7688       return fold_builtin_fputs (arglist, ignore, true, NULL_TREE);
7689
7690     case BUILT_IN_STRSTR:
7691       return fold_builtin_strstr (arglist);
7692
7693     case BUILT_IN_STRCAT:
7694       return fold_builtin_strcat (arglist);
7695
7696     case BUILT_IN_STRNCAT:
7697       return fold_builtin_strncat (arglist);
7698
7699     case BUILT_IN_STRSPN:
7700       return fold_builtin_strspn (arglist);
7701
7702     case BUILT_IN_STRCSPN:
7703       return fold_builtin_strcspn (arglist);
7704
7705     case BUILT_IN_STRCHR:
7706     case BUILT_IN_INDEX:
7707       return fold_builtin_strchr (arglist);
7708
7709     case BUILT_IN_STRRCHR:
7710     case BUILT_IN_RINDEX:
7711       return fold_builtin_strrchr (arglist);
7712
7713     case BUILT_IN_STRCPY:
7714       return fold_builtin_strcpy (exp, NULL_TREE);
7715
7716     case BUILT_IN_STRNCPY:
7717       return fold_builtin_strncpy (exp, NULL_TREE);
7718
7719     case BUILT_IN_STRCMP:
7720       return fold_builtin_strcmp (arglist);
7721
7722     case BUILT_IN_STRNCMP:
7723       return fold_builtin_strncmp (arglist);
7724
7725     case BUILT_IN_STRPBRK:
7726       return fold_builtin_strpbrk (arglist);
7727
7728     case BUILT_IN_BCMP:
7729     case BUILT_IN_MEMCMP:
7730       return fold_builtin_memcmp (arglist);
7731
7732     case BUILT_IN_SPRINTF:
7733       return fold_builtin_sprintf (arglist, ignore);
7734
7735     case BUILT_IN_CONSTANT_P:
7736       {
7737         tree val;
7738
7739         val = fold_builtin_constant_p (arglist);
7740         /* Gimplification will pull the CALL_EXPR for the builtin out of
7741            an if condition.  When not optimizing, we'll not CSE it back.
7742            To avoid link error types of regressions, return false now.  */
7743         if (!val && !optimize)
7744           val = integer_zero_node;
7745
7746         return val;
7747       }
7748
7749     case BUILT_IN_EXPECT:
7750       return fold_builtin_expect (arglist);
7751
7752     case BUILT_IN_CLASSIFY_TYPE:
7753       return fold_builtin_classify_type (arglist);
7754
7755     case BUILT_IN_STRLEN:
7756       return fold_builtin_strlen (arglist);
7757
7758     case BUILT_IN_FABS:
7759     case BUILT_IN_FABSF:
7760     case BUILT_IN_FABSL:
7761       return fold_builtin_fabs (arglist, type);
7762
7763     case BUILT_IN_ABS:
7764     case BUILT_IN_LABS:
7765     case BUILT_IN_LLABS:
7766     case BUILT_IN_IMAXABS:
7767       return fold_builtin_abs (arglist, type);
7768
7769     case BUILT_IN_CONJ:
7770     case BUILT_IN_CONJF:
7771     case BUILT_IN_CONJL:
7772       if (validate_arglist (arglist, COMPLEX_TYPE, VOID_TYPE))
7773         return fold (build1 (CONJ_EXPR, type, TREE_VALUE (arglist)));
7774       break;
7775
7776     case BUILT_IN_CREAL:
7777     case BUILT_IN_CREALF:
7778     case BUILT_IN_CREALL:
7779       if (validate_arglist (arglist, COMPLEX_TYPE, VOID_TYPE))
7780         return non_lvalue (fold (build1 (REALPART_EXPR, type,
7781                                          TREE_VALUE (arglist))));
7782       break;
7783
7784     case BUILT_IN_CIMAG:
7785     case BUILT_IN_CIMAGF:
7786     case BUILT_IN_CIMAGL:
7787       if (validate_arglist (arglist, COMPLEX_TYPE, VOID_TYPE))
7788         return non_lvalue (fold (build1 (IMAGPART_EXPR, type,
7789                                          TREE_VALUE (arglist))));
7790       break;
7791
7792     case BUILT_IN_CABS:
7793     case BUILT_IN_CABSF:
7794     case BUILT_IN_CABSL:
7795       return fold_builtin_cabs (arglist, type);
7796
7797     case BUILT_IN_SQRT:
7798     case BUILT_IN_SQRTF:
7799     case BUILT_IN_SQRTL:
7800       return fold_builtin_sqrt (arglist, type);
7801
7802     case BUILT_IN_CBRT:
7803     case BUILT_IN_CBRTF:
7804     case BUILT_IN_CBRTL:
7805       return fold_builtin_cbrt (arglist, type);
7806
7807     case BUILT_IN_SIN:
7808     case BUILT_IN_SINF:
7809     case BUILT_IN_SINL:
7810       return fold_builtin_sin (arglist);
7811
7812     case BUILT_IN_COS:
7813     case BUILT_IN_COSF:
7814     case BUILT_IN_COSL:
7815       return fold_builtin_cos (arglist, type, fndecl);
7816
7817     case BUILT_IN_EXP:
7818     case BUILT_IN_EXPF:
7819     case BUILT_IN_EXPL:
7820       return fold_builtin_exponent (exp, &dconste);
7821
7822     case BUILT_IN_EXP2:
7823     case BUILT_IN_EXP2F:
7824     case BUILT_IN_EXP2L:
7825       return fold_builtin_exponent (exp, &dconst2);
7826
7827     case BUILT_IN_EXP10:
7828     case BUILT_IN_EXP10F:
7829     case BUILT_IN_EXP10L:
7830     case BUILT_IN_POW10:
7831     case BUILT_IN_POW10F:
7832     case BUILT_IN_POW10L:
7833       return fold_builtin_exponent (exp, &dconst10);
7834
7835     case BUILT_IN_LOG:
7836     case BUILT_IN_LOGF:
7837     case BUILT_IN_LOGL:
7838       return fold_builtin_logarithm (exp, &dconste);
7839
7840     case BUILT_IN_LOG2:
7841     case BUILT_IN_LOG2F:
7842     case BUILT_IN_LOG2L:
7843       return fold_builtin_logarithm (exp, &dconst2);
7844
7845     case BUILT_IN_LOG10:
7846     case BUILT_IN_LOG10F:
7847     case BUILT_IN_LOG10L:
7848       return fold_builtin_logarithm (exp, &dconst10);
7849
7850     case BUILT_IN_TAN:
7851     case BUILT_IN_TANF:
7852     case BUILT_IN_TANL:
7853       return fold_builtin_tan (arglist);
7854
7855     case BUILT_IN_ATAN:
7856     case BUILT_IN_ATANF:
7857     case BUILT_IN_ATANL:
7858       return fold_builtin_atan (arglist, type);
7859
7860     case BUILT_IN_POW:
7861     case BUILT_IN_POWF:
7862     case BUILT_IN_POWL:
7863       return fold_builtin_pow (fndecl, arglist, type);
7864
7865     case BUILT_IN_INF:
7866     case BUILT_IN_INFF:
7867     case BUILT_IN_INFL:
7868       return fold_builtin_inf (type, true);
7869
7870     case BUILT_IN_HUGE_VAL:
7871     case BUILT_IN_HUGE_VALF:
7872     case BUILT_IN_HUGE_VALL:
7873       return fold_builtin_inf (type, false);
7874
7875     case BUILT_IN_NAN:
7876     case BUILT_IN_NANF:
7877     case BUILT_IN_NANL:
7878       return fold_builtin_nan (arglist, type, true);
7879
7880     case BUILT_IN_NANS:
7881     case BUILT_IN_NANSF:
7882     case BUILT_IN_NANSL:
7883       return fold_builtin_nan (arglist, type, false);
7884
7885     case BUILT_IN_FLOOR:
7886     case BUILT_IN_FLOORF:
7887     case BUILT_IN_FLOORL:
7888       return fold_builtin_floor (exp);
7889
7890     case BUILT_IN_CEIL:
7891     case BUILT_IN_CEILF:
7892     case BUILT_IN_CEILL:
7893       return fold_builtin_ceil (exp);
7894
7895     case BUILT_IN_TRUNC:
7896     case BUILT_IN_TRUNCF:
7897     case BUILT_IN_TRUNCL:
7898       return fold_builtin_trunc (exp);
7899
7900     case BUILT_IN_ROUND:
7901     case BUILT_IN_ROUNDF:
7902     case BUILT_IN_ROUNDL:
7903       return fold_builtin_round (exp);
7904
7905     case BUILT_IN_NEARBYINT:
7906     case BUILT_IN_NEARBYINTF:
7907     case BUILT_IN_NEARBYINTL:
7908     case BUILT_IN_RINT:
7909     case BUILT_IN_RINTF:
7910     case BUILT_IN_RINTL:
7911       return fold_trunc_transparent_mathfn (exp);
7912
7913     case BUILT_IN_LROUND:
7914     case BUILT_IN_LROUNDF:
7915     case BUILT_IN_LROUNDL:
7916     case BUILT_IN_LLROUND:
7917     case BUILT_IN_LLROUNDF:
7918     case BUILT_IN_LLROUNDL:
7919       return fold_builtin_lround (exp);
7920
7921     case BUILT_IN_LRINT:
7922     case BUILT_IN_LRINTF:
7923     case BUILT_IN_LRINTL:
7924     case BUILT_IN_LLRINT:
7925     case BUILT_IN_LLRINTF:
7926     case BUILT_IN_LLRINTL:
7927       return fold_fixed_mathfn (exp);
7928
7929     case BUILT_IN_FFS:
7930     case BUILT_IN_FFSL:
7931     case BUILT_IN_FFSLL:
7932     case BUILT_IN_CLZ:
7933     case BUILT_IN_CLZL:
7934     case BUILT_IN_CLZLL:
7935     case BUILT_IN_CTZ:
7936     case BUILT_IN_CTZL:
7937     case BUILT_IN_CTZLL:
7938     case BUILT_IN_POPCOUNT:
7939     case BUILT_IN_POPCOUNTL:
7940     case BUILT_IN_POPCOUNTLL:
7941     case BUILT_IN_PARITY:
7942     case BUILT_IN_PARITYL:
7943     case BUILT_IN_PARITYLL:
7944       return fold_builtin_bitop (exp);
7945
7946     case BUILT_IN_MEMCPY:
7947       return fold_builtin_memcpy (exp);
7948
7949     case BUILT_IN_MEMPCPY:
7950       return fold_builtin_mempcpy (arglist, type, /*endp=*/1);
7951
7952     case BUILT_IN_MEMMOVE:
7953       return fold_builtin_memmove (arglist, type);
7954
7955     case BUILT_IN_SIGNBIT:
7956     case BUILT_IN_SIGNBITF:
7957     case BUILT_IN_SIGNBITL:
7958       return fold_builtin_signbit (exp);
7959
7960     case BUILT_IN_ISASCII:
7961       return fold_builtin_isascii (arglist);
7962
7963     case BUILT_IN_TOASCII:
7964       return fold_builtin_toascii (arglist);
7965
7966     case BUILT_IN_ISDIGIT:
7967       return fold_builtin_isdigit (arglist);
7968
7969     case BUILT_IN_COPYSIGN:
7970     case BUILT_IN_COPYSIGNF:
7971     case BUILT_IN_COPYSIGNL:
7972       return fold_builtin_copysign (arglist, type);
7973
7974     case BUILT_IN_FINITE:
7975     case BUILT_IN_FINITEF:
7976     case BUILT_IN_FINITEL:
7977       return fold_builtin_classify (exp, BUILT_IN_FINITE);
7978
7979     case BUILT_IN_ISINF:
7980     case BUILT_IN_ISINFF:
7981     case BUILT_IN_ISINFL:
7982       return fold_builtin_classify (exp, BUILT_IN_ISINF);
7983
7984     case BUILT_IN_ISNAN:
7985     case BUILT_IN_ISNANF:
7986     case BUILT_IN_ISNANL:
7987       return fold_builtin_classify (exp, BUILT_IN_ISNAN);
7988
7989     case BUILT_IN_ISGREATER:
7990       return fold_builtin_unordered_cmp (exp, UNLE_EXPR, LE_EXPR);
7991     case BUILT_IN_ISGREATEREQUAL:
7992       return fold_builtin_unordered_cmp (exp, UNLT_EXPR, LT_EXPR);
7993     case BUILT_IN_ISLESS:
7994       return fold_builtin_unordered_cmp (exp, UNGE_EXPR, GE_EXPR);
7995     case BUILT_IN_ISLESSEQUAL:
7996       return fold_builtin_unordered_cmp (exp, UNGT_EXPR, GT_EXPR);
7997     case BUILT_IN_ISLESSGREATER:
7998       return fold_builtin_unordered_cmp (exp, UNEQ_EXPR, EQ_EXPR);
7999     case BUILT_IN_ISUNORDERED:
8000       return fold_builtin_unordered_cmp (exp, UNORDERED_EXPR, NOP_EXPR);
8001
8002       /* We do the folding for va_start in the expander.  */
8003     case BUILT_IN_VA_START:
8004       break;
8005
8006     default:
8007       break;
8008     }
8009
8010   return 0;
8011 }
8012
8013 /* A wrapper function for builtin folding that prevents warnings for
8014    "statement without effect" and the like, caused by removing the
8015    call node earlier than the warning is generated.  */
8016
8017 tree
8018 fold_builtin (tree exp, bool ignore)
8019 {
8020   exp = fold_builtin_1 (exp, ignore);
8021   if (exp)
8022     {
8023       /* ??? Don't clobber shared nodes such as integer_zero_node.  */
8024       if (CONSTANT_CLASS_P (exp))
8025         exp = build1 (NOP_EXPR, TREE_TYPE (exp), exp);
8026       TREE_NO_WARNING (exp) = 1;
8027     }
8028
8029   return exp;
8030 }
8031
8032 /* Conveniently construct a function call expression.  */
8033
8034 tree
8035 build_function_call_expr (tree fn, tree arglist)
8036 {
8037   tree call_expr;
8038
8039   call_expr = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
8040   call_expr = build3 (CALL_EXPR, TREE_TYPE (TREE_TYPE (fn)),
8041                       call_expr, arglist, NULL_TREE);
8042   return fold (call_expr);
8043 }
8044
8045 /* This function validates the types of a function call argument list
8046    represented as a tree chain of parameters against a specified list
8047    of tree_codes.  If the last specifier is a 0, that represents an
8048    ellipses, otherwise the last specifier must be a VOID_TYPE.  */
8049
8050 static int
8051 validate_arglist (tree arglist, ...)
8052 {
8053   enum tree_code code;
8054   int res = 0;
8055   va_list ap;
8056
8057   va_start (ap, arglist);
8058
8059   do
8060     {
8061       code = va_arg (ap, enum tree_code);
8062       switch (code)
8063         {
8064         case 0:
8065           /* This signifies an ellipses, any further arguments are all ok.  */
8066           res = 1;
8067           goto end;
8068         case VOID_TYPE:
8069           /* This signifies an endlink, if no arguments remain, return
8070              true, otherwise return false.  */
8071           res = arglist == 0;
8072           goto end;
8073         default:
8074           /* If no parameters remain or the parameter's code does not
8075              match the specified code, return false.  Otherwise continue
8076              checking any remaining arguments.  */
8077           if (arglist == 0
8078               || code != TREE_CODE (TREE_TYPE (TREE_VALUE (arglist))))
8079             goto end;
8080           break;
8081         }
8082       arglist = TREE_CHAIN (arglist);
8083     }
8084   while (1);
8085
8086   /* We need gotos here since we can only have one VA_CLOSE in a
8087      function.  */
8088  end: ;
8089   va_end (ap);
8090
8091   return res;
8092 }
8093
8094 /* Default target-specific builtin expander that does nothing.  */
8095
8096 rtx
8097 default_expand_builtin (tree exp ATTRIBUTE_UNUSED,
8098                         rtx target ATTRIBUTE_UNUSED,
8099                         rtx subtarget ATTRIBUTE_UNUSED,
8100                         enum machine_mode mode ATTRIBUTE_UNUSED,
8101                         int ignore ATTRIBUTE_UNUSED)
8102 {
8103   return NULL_RTX;
8104 }
8105
8106 /* Returns true is EXP represents data that would potentially reside
8107    in a readonly section.  */
8108
8109 static bool
8110 readonly_data_expr (tree exp)
8111 {
8112   STRIP_NOPS (exp);
8113
8114   if (TREE_CODE (exp) != ADDR_EXPR)
8115     return false;
8116
8117   exp = get_base_address (TREE_OPERAND (exp, 0));
8118   if (!exp)
8119     return false;
8120
8121   /* Make sure we call decl_readonly_section only for trees it
8122      can handle (since it returns true for everything it doesn't
8123      understand).  */
8124   if (TREE_CODE (exp) == STRING_CST
8125       || TREE_CODE (exp) == CONSTRUCTOR
8126       || (TREE_CODE (exp) == VAR_DECL && TREE_STATIC (exp)))
8127     return decl_readonly_section (exp, 0);
8128   else
8129     return false;
8130 }
8131
8132 /* Simplify a call to the strstr builtin.
8133
8134    Return 0 if no simplification was possible, otherwise return the
8135    simplified form of the call as a tree.
8136
8137    The simplified form may be a constant or other expression which
8138    computes the same value, but in a more efficient manner (including
8139    calls to other builtin functions).
8140
8141    The call may contain arguments which need to be evaluated, but
8142    which are not useful to determine the result of the call.  In
8143    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
8144    COMPOUND_EXPR will be an argument which must be evaluated.
8145    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
8146    COMPOUND_EXPR in the chain will contain the tree for the simplified
8147    form of the builtin function call.  */
8148
8149 static tree
8150 fold_builtin_strstr (tree arglist)
8151 {
8152   if (!validate_arglist (arglist, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
8153     return 0;
8154   else
8155     {
8156       tree s1 = TREE_VALUE (arglist), s2 = TREE_VALUE (TREE_CHAIN (arglist));
8157       tree fn;
8158       const char *p1, *p2;
8159
8160       p2 = c_getstr (s2);
8161       if (p2 == NULL)
8162         return 0;
8163
8164       p1 = c_getstr (s1);
8165       if (p1 != NULL)
8166         {
8167           const char *r = strstr (p1, p2);
8168
8169           if (r == NULL)
8170             return build_int_cst (TREE_TYPE (s1), 0);
8171
8172           /* Return an offset into the constant string argument.  */
8173           return fold (build2 (PLUS_EXPR, TREE_TYPE (s1),
8174                                s1, build_int_cst (TREE_TYPE (s1), r - p1)));
8175         }
8176
8177       if (p2[0] == '\0')
8178         return s1;
8179
8180       if (p2[1] != '\0')
8181         return 0;
8182
8183       fn = implicit_built_in_decls[BUILT_IN_STRCHR];
8184       if (!fn)
8185         return 0;
8186
8187       /* New argument list transforming strstr(s1, s2) to
8188          strchr(s1, s2[0]).  */
8189       arglist = build_tree_list (NULL_TREE,
8190                                  build_int_cst (NULL_TREE, p2[0]));
8191       arglist = tree_cons (NULL_TREE, s1, arglist);
8192       return build_function_call_expr (fn, arglist);
8193     }
8194 }
8195
8196 /* Simplify a call to the strchr builtin.
8197
8198    Return 0 if no simplification was possible, otherwise return the
8199    simplified form of the call as a tree.
8200
8201    The simplified form may be a constant or other expression which
8202    computes the same value, but in a more efficient manner (including
8203    calls to other builtin functions).
8204
8205    The call may contain arguments which need to be evaluated, but
8206    which are not useful to determine the result of the call.  In
8207    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
8208    COMPOUND_EXPR will be an argument which must be evaluated.
8209    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
8210    COMPOUND_EXPR in the chain will contain the tree for the simplified
8211    form of the builtin function call.  */
8212
8213 static tree
8214 fold_builtin_strchr (tree arglist)
8215 {
8216   if (!validate_arglist (arglist, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
8217     return 0;
8218   else
8219     {
8220       tree s1 = TREE_VALUE (arglist), s2 = TREE_VALUE (TREE_CHAIN (arglist));
8221       const char *p1;
8222
8223       if (TREE_CODE (s2) != INTEGER_CST)
8224         return 0;
8225
8226       p1 = c_getstr (s1);
8227       if (p1 != NULL)
8228         {
8229           char c;
8230           const char *r;
8231
8232           if (target_char_cast (s2, &c))
8233             return 0;
8234
8235           r = strchr (p1, c);
8236
8237           if (r == NULL)
8238             return build_int_cst (TREE_TYPE (s1), 0);
8239
8240           /* Return an offset into the constant string argument.  */
8241           return fold (build2 (PLUS_EXPR, TREE_TYPE (s1),
8242                                s1, build_int_cst (TREE_TYPE (s1), r - p1)));
8243         }
8244       return 0;
8245     }
8246 }
8247
8248 /* Simplify a call to the strrchr builtin.
8249
8250    Return 0 if no simplification was possible, otherwise return the
8251    simplified form of the call as a tree.
8252
8253    The simplified form may be a constant or other expression which
8254    computes the same value, but in a more efficient manner (including
8255    calls to other builtin functions).
8256
8257    The call may contain arguments which need to be evaluated, but
8258    which are not useful to determine the result of the call.  In
8259    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
8260    COMPOUND_EXPR will be an argument which must be evaluated.
8261    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
8262    COMPOUND_EXPR in the chain will contain the tree for the simplified
8263    form of the builtin function call.  */
8264
8265 static tree
8266 fold_builtin_strrchr (tree arglist)
8267 {
8268   if (!validate_arglist (arglist, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
8269     return 0;
8270   else
8271     {
8272       tree s1 = TREE_VALUE (arglist), s2 = TREE_VALUE (TREE_CHAIN (arglist));
8273       tree fn;
8274       const char *p1;
8275
8276       if (TREE_CODE (s2) != INTEGER_CST)
8277         return 0;
8278
8279       p1 = c_getstr (s1);
8280       if (p1 != NULL)
8281         {
8282           char c;
8283           const char *r;
8284
8285           if (target_char_cast (s2, &c))
8286             return 0;
8287
8288           r = strrchr (p1, c);
8289
8290           if (r == NULL)
8291             return build_int_cst (TREE_TYPE (s1), 0);
8292
8293           /* Return an offset into the constant string argument.  */
8294           return fold (build2 (PLUS_EXPR, TREE_TYPE (s1),
8295                                s1, build_int_cst (TREE_TYPE (s1), r - p1)));
8296         }
8297
8298       if (! integer_zerop (s2))
8299         return 0;
8300
8301       fn = implicit_built_in_decls[BUILT_IN_STRCHR];
8302       if (!fn)
8303         return 0;
8304
8305       /* Transform strrchr(s1, '\0') to strchr(s1, '\0').  */
8306       return build_function_call_expr (fn, arglist);
8307     }
8308 }
8309
8310 /* Simplify a call to the strpbrk builtin.
8311
8312    Return 0 if no simplification was possible, otherwise return the
8313    simplified form of the call as a tree.
8314
8315    The simplified form may be a constant or other expression which
8316    computes the same value, but in a more efficient manner (including
8317    calls to other builtin functions).
8318
8319    The call may contain arguments which need to be evaluated, but
8320    which are not useful to determine the result of the call.  In
8321    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
8322    COMPOUND_EXPR will be an argument which must be evaluated.
8323    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
8324    COMPOUND_EXPR in the chain will contain the tree for the simplified
8325    form of the builtin function call.  */
8326
8327 static tree
8328 fold_builtin_strpbrk (tree arglist)
8329 {
8330   if (!validate_arglist (arglist, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
8331     return 0;
8332   else
8333     {
8334       tree s1 = TREE_VALUE (arglist), s2 = TREE_VALUE (TREE_CHAIN (arglist));
8335       tree fn;
8336       const char *p1, *p2;
8337
8338       p2 = c_getstr (s2);
8339       if (p2 == NULL)
8340         return 0;
8341
8342       p1 = c_getstr (s1);
8343       if (p1 != NULL)
8344         {
8345           const char *r = strpbrk (p1, p2);
8346
8347           if (r == NULL)
8348             return build_int_cst (TREE_TYPE (s1), 0);
8349
8350           /* Return an offset into the constant string argument.  */
8351           return fold (build2 (PLUS_EXPR, TREE_TYPE (s1),
8352                                s1, build_int_cst (TREE_TYPE (s1), r - p1)));
8353         }
8354
8355       if (p2[0] == '\0')
8356         /* strpbrk(x, "") == NULL.
8357            Evaluate and ignore s1 in case it had side-effects.  */
8358         return omit_one_operand (TREE_TYPE (s1), integer_zero_node, s1);
8359
8360       if (p2[1] != '\0')
8361         return 0;  /* Really call strpbrk.  */
8362
8363       fn = implicit_built_in_decls[BUILT_IN_STRCHR];
8364       if (!fn)
8365         return 0;
8366
8367       /* New argument list transforming strpbrk(s1, s2) to
8368          strchr(s1, s2[0]).  */
8369       arglist = build_tree_list (NULL_TREE,
8370                                  build_int_cst (NULL_TREE, p2[0]));
8371       arglist = tree_cons (NULL_TREE, s1, arglist);
8372       return build_function_call_expr (fn, arglist);
8373     }
8374 }
8375
8376 /* Simplify a call to the strcat builtin.
8377
8378    Return 0 if no simplification was possible, otherwise return the
8379    simplified form of the call as a tree.
8380
8381    The simplified form may be a constant or other expression which
8382    computes the same value, but in a more efficient manner (including
8383    calls to other builtin functions).
8384
8385    The call may contain arguments which need to be evaluated, but
8386    which are not useful to determine the result of the call.  In
8387    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
8388    COMPOUND_EXPR will be an argument which must be evaluated.
8389    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
8390    COMPOUND_EXPR in the chain will contain the tree for the simplified
8391    form of the builtin function call.  */
8392
8393 static tree
8394 fold_builtin_strcat (tree arglist)
8395 {
8396   if (!validate_arglist (arglist, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
8397     return 0;
8398   else
8399     {
8400       tree dst = TREE_VALUE (arglist),
8401         src = TREE_VALUE (TREE_CHAIN (arglist));
8402       const char *p = c_getstr (src);
8403
8404       /* If the string length is zero, return the dst parameter.  */
8405       if (p && *p == '\0')
8406         return dst;
8407
8408       return 0;
8409     }
8410 }
8411
8412 /* Simplify a call to the strncat builtin.
8413
8414    Return 0 if no simplification was possible, otherwise return the
8415    simplified form of the call as a tree.
8416
8417    The simplified form may be a constant or other expression which
8418    computes the same value, but in a more efficient manner (including
8419    calls to other builtin functions).
8420
8421    The call may contain arguments which need to be evaluated, but
8422    which are not useful to determine the result of the call.  In
8423    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
8424    COMPOUND_EXPR will be an argument which must be evaluated.
8425    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
8426    COMPOUND_EXPR in the chain will contain the tree for the simplified
8427    form of the builtin function call.  */
8428
8429 static tree
8430 fold_builtin_strncat (tree arglist)
8431 {
8432   if (!validate_arglist (arglist,
8433                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
8434     return 0;
8435   else
8436     {
8437       tree dst = TREE_VALUE (arglist);
8438       tree src = TREE_VALUE (TREE_CHAIN (arglist));
8439       tree len = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (arglist)));
8440       const char *p = c_getstr (src);
8441
8442       /* If the requested length is zero, or the src parameter string
8443           length is zero, return the dst parameter.  */
8444       if (integer_zerop (len) || (p && *p == '\0'))
8445         return omit_two_operands (TREE_TYPE (dst), dst, src, len);
8446
8447       /* If the requested len is greater than or equal to the string
8448          length, call strcat.  */
8449       if (TREE_CODE (len) == INTEGER_CST && p
8450           && compare_tree_int (len, strlen (p)) >= 0)
8451         {
8452           tree newarglist
8453             = tree_cons (NULL_TREE, dst, build_tree_list (NULL_TREE, src));
8454           tree fn = implicit_built_in_decls[BUILT_IN_STRCAT];
8455
8456           /* If the replacement _DECL isn't initialized, don't do the
8457              transformation.  */
8458           if (!fn)
8459             return 0;
8460
8461           return build_function_call_expr (fn, newarglist);
8462         }
8463       return 0;
8464     }
8465 }
8466
8467 /* Simplify a call to the strspn builtin.
8468
8469    Return 0 if no simplification was possible, otherwise return the
8470    simplified form of the call as a tree.
8471
8472    The simplified form may be a constant or other expression which
8473    computes the same value, but in a more efficient manner (including
8474    calls to other builtin functions).
8475
8476    The call may contain arguments which need to be evaluated, but
8477    which are not useful to determine the result of the call.  In
8478    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
8479    COMPOUND_EXPR will be an argument which must be evaluated.
8480    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
8481    COMPOUND_EXPR in the chain will contain the tree for the simplified
8482    form of the builtin function call.  */
8483
8484 static tree
8485 fold_builtin_strspn (tree arglist)
8486 {
8487   if (!validate_arglist (arglist, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
8488     return 0;
8489   else
8490     {
8491       tree s1 = TREE_VALUE (arglist), s2 = TREE_VALUE (TREE_CHAIN (arglist));
8492       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
8493
8494       /* If both arguments are constants, evaluate at compile-time.  */
8495       if (p1 && p2)
8496         {
8497           const size_t r = strspn (p1, p2);
8498           return size_int (r);
8499         }
8500
8501       /* If either argument is "", return 0.  */
8502       if ((p1 && *p1 == '\0') || (p2 && *p2 == '\0'))
8503         /* Evaluate and ignore both arguments in case either one has
8504            side-effects.  */
8505         return omit_two_operands (integer_type_node, integer_zero_node,
8506                                   s1, s2);
8507       return 0;
8508     }
8509 }
8510
8511 /* Simplify a call to the strcspn builtin.
8512
8513    Return 0 if no simplification was possible, otherwise return the
8514    simplified form of the call as a tree.
8515
8516    The simplified form may be a constant or other expression which
8517    computes the same value, but in a more efficient manner (including
8518    calls to other builtin functions).
8519
8520    The call may contain arguments which need to be evaluated, but
8521    which are not useful to determine the result of the call.  In
8522    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
8523    COMPOUND_EXPR will be an argument which must be evaluated.
8524    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
8525    COMPOUND_EXPR in the chain will contain the tree for the simplified
8526    form of the builtin function call.  */
8527
8528 static tree
8529 fold_builtin_strcspn (tree arglist)
8530 {
8531   if (!validate_arglist (arglist, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
8532     return 0;
8533   else
8534     {
8535       tree s1 = TREE_VALUE (arglist), s2 = TREE_VALUE (TREE_CHAIN (arglist));
8536       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
8537
8538       /* If both arguments are constants, evaluate at compile-time.  */
8539       if (p1 && p2)
8540         {
8541           const size_t r = strcspn (p1, p2);
8542           return size_int (r);
8543         }
8544
8545       /* If the first argument is "", return 0.  */
8546       if (p1 && *p1 == '\0')
8547         {
8548           /* Evaluate and ignore argument s2 in case it has
8549              side-effects.  */
8550           return omit_one_operand (integer_type_node,
8551                                    integer_zero_node, s2);
8552         }
8553
8554       /* If the second argument is "", return __builtin_strlen(s1).  */
8555       if (p2 && *p2 == '\0')
8556         {
8557           tree newarglist = build_tree_list (NULL_TREE, s1),
8558             fn = implicit_built_in_decls[BUILT_IN_STRLEN];
8559
8560           /* If the replacement _DECL isn't initialized, don't do the
8561              transformation.  */
8562           if (!fn)
8563             return 0;
8564
8565           return build_function_call_expr (fn, newarglist);
8566         }
8567       return 0;
8568     }
8569 }
8570
8571 /* Fold a call to the fputs builtin.  IGNORE is true if the value returned
8572    by the builtin will be ignored.  UNLOCKED is true is true if this
8573    actually a call to fputs_unlocked.  If LEN in non-NULL, it represents
8574    the known length of the string.  Return NULL_TREE if no simplification
8575    was possible.  */
8576
8577 tree
8578 fold_builtin_fputs (tree arglist, bool ignore, bool unlocked, tree len)
8579 {
8580   tree fn;
8581   tree fn_fputc = unlocked ? implicit_built_in_decls[BUILT_IN_FPUTC_UNLOCKED]
8582     : implicit_built_in_decls[BUILT_IN_FPUTC];
8583   tree fn_fwrite = unlocked ? implicit_built_in_decls[BUILT_IN_FWRITE_UNLOCKED]
8584     : implicit_built_in_decls[BUILT_IN_FWRITE];
8585
8586   /* If the return value is used, or the replacement _DECL isn't
8587      initialized, don't do the transformation.  */
8588   if (!ignore || !fn_fputc || !fn_fwrite)
8589     return 0;
8590
8591   /* Verify the arguments in the original call.  */
8592   if (!validate_arglist (arglist, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
8593     return 0;
8594
8595   if (! len)
8596     len = c_strlen (TREE_VALUE (arglist), 0);
8597
8598   /* Get the length of the string passed to fputs.  If the length
8599      can't be determined, punt.  */
8600   if (!len
8601       || TREE_CODE (len) != INTEGER_CST)
8602     return 0;
8603
8604   switch (compare_tree_int (len, 1))
8605     {
8606     case -1: /* length is 0, delete the call entirely .  */
8607       return omit_one_operand (integer_type_node, integer_zero_node,
8608                                TREE_VALUE (TREE_CHAIN (arglist)));
8609
8610     case 0: /* length is 1, call fputc.  */
8611       {
8612         const char *p = c_getstr (TREE_VALUE (arglist));
8613
8614         if (p != NULL)
8615           {
8616             /* New argument list transforming fputs(string, stream) to
8617                fputc(string[0], stream).  */
8618             arglist = build_tree_list (NULL_TREE,
8619                                        TREE_VALUE (TREE_CHAIN (arglist)));
8620             arglist = tree_cons (NULL_TREE,
8621                                  build_int_cst (NULL_TREE, p[0]),
8622                                  arglist);
8623             fn = fn_fputc;
8624             break;
8625           }
8626       }
8627       /* FALLTHROUGH */
8628     case 1: /* length is greater than 1, call fwrite.  */
8629       {
8630         tree string_arg;
8631
8632         /* If optimizing for size keep fputs.  */
8633         if (optimize_size)
8634           return 0;
8635         string_arg = TREE_VALUE (arglist);
8636         /* New argument list transforming fputs(string, stream) to
8637            fwrite(string, 1, len, stream).  */
8638         arglist = build_tree_list (NULL_TREE,
8639                                    TREE_VALUE (TREE_CHAIN (arglist)));
8640         arglist = tree_cons (NULL_TREE, len, arglist);
8641         arglist = tree_cons (NULL_TREE, size_one_node, arglist);
8642         arglist = tree_cons (NULL_TREE, string_arg, arglist);
8643         fn = fn_fwrite;
8644         break;
8645       }
8646     default:
8647       gcc_unreachable ();
8648     }
8649
8650   /* These optimizations are only performed when the result is ignored,
8651      hence there's no need to cast the result to integer_type_node.  */
8652   return build_function_call_expr (fn, arglist);
8653 }
8654
8655 static void
8656 fold_builtin_next_arg (tree arglist)
8657 {
8658   tree fntype = TREE_TYPE (current_function_decl);
8659
8660   if (TYPE_ARG_TYPES (fntype) == 0
8661       || (TREE_VALUE (tree_last (TYPE_ARG_TYPES (fntype)))
8662           == void_type_node))
8663     error ("%<va_start%> used in function with fixed args");
8664   else if (arglist)
8665     {
8666       tree last_parm = tree_last (DECL_ARGUMENTS (current_function_decl));
8667       tree arg = TREE_VALUE (arglist);
8668
8669       /* Strip off all nops for the sake of the comparison.  This
8670          is not quite the same as STRIP_NOPS.  It does more.
8671          We must also strip off INDIRECT_EXPR for C++ reference
8672          parameters.  */
8673       while (TREE_CODE (arg) == NOP_EXPR
8674              || TREE_CODE (arg) == CONVERT_EXPR
8675              || TREE_CODE (arg) == NON_LVALUE_EXPR
8676              || TREE_CODE (arg) == INDIRECT_REF)
8677         arg = TREE_OPERAND (arg, 0);
8678       if (arg != last_parm)
8679         warning ("second parameter of %<va_start%> not last named argument");
8680       TREE_VALUE (arglist) = arg;
8681     }
8682   else
8683     /* Evidently an out of date version of <stdarg.h>; can't validate
8684        va_start's second argument, but can still work as intended.  */
8685     warning ("%<__builtin_next_arg%> called without an argument");
8686 }
8687
8688
8689 /* Simplify a call to the sprintf builtin.
8690
8691    Return 0 if no simplification was possible, otherwise return the
8692    simplified form of the call as a tree.  If IGNORED is true, it means that
8693    the caller does not use the returned value of the function.  */
8694
8695 static tree
8696 fold_builtin_sprintf (tree arglist, int ignored)
8697 {
8698   tree call, retval, dest, fmt;
8699   const char *fmt_str = NULL;
8700
8701   /* Verify the required arguments in the original call.  We deal with two
8702      types of sprintf() calls: 'sprintf (str, fmt)' and
8703      'sprintf (dest, "%s", orig)'.  */
8704   if (!validate_arglist (arglist, POINTER_TYPE, POINTER_TYPE, VOID_TYPE)
8705       && !validate_arglist (arglist, POINTER_TYPE, POINTER_TYPE, POINTER_TYPE,
8706                             VOID_TYPE))
8707     return NULL_TREE;
8708
8709   /* Get the destination string and the format specifier.  */
8710   dest = TREE_VALUE (arglist);
8711   fmt = TREE_VALUE (TREE_CHAIN (arglist));
8712
8713   /* Check whether the format is a literal string constant.  */
8714   fmt_str = c_getstr (fmt);
8715   if (fmt_str == NULL)
8716     return NULL_TREE;
8717
8718   call = NULL_TREE;
8719   retval = NULL_TREE;
8720
8721   /* If the format doesn't contain % args or %%, use strcpy.  */
8722   if (strchr (fmt_str, '%') == NULL)
8723     {
8724       tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
8725
8726       if (!fn)
8727         return NULL_TREE;
8728
8729       /* Convert sprintf (str, fmt) into strcpy (str, fmt) when
8730          'format' is known to contain no % formats.  */
8731       arglist = build_tree_list (NULL_TREE, fmt);
8732       arglist = tree_cons (NULL_TREE, dest, arglist);
8733       call = build_function_call_expr (fn, arglist);
8734       if (!ignored)
8735         retval = build_int_cst (NULL_TREE, strlen (fmt_str));
8736     }
8737
8738   /* If the format is "%s", use strcpy if the result isn't used.  */
8739   else if (fmt_str && strcmp (fmt_str, "%s") == 0)
8740     {
8741       tree fn, orig;
8742       fn = implicit_built_in_decls[BUILT_IN_STRCPY];
8743
8744       if (!fn)
8745         return NULL_TREE;
8746
8747       /* Convert sprintf (str1, "%s", str2) into strcpy (str1, str2).  */
8748       orig = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (arglist)));
8749       arglist = build_tree_list (NULL_TREE, orig);
8750       arglist = tree_cons (NULL_TREE, dest, arglist);
8751       if (!ignored)
8752         {
8753           retval = c_strlen (orig, 1);
8754           if (!retval || TREE_CODE (retval) != INTEGER_CST)
8755             return NULL_TREE;
8756         }
8757       call = build_function_call_expr (fn, arglist);
8758     }
8759
8760   if (call && retval)
8761     {
8762       retval = convert
8763         (TREE_TYPE (TREE_TYPE (implicit_built_in_decls[BUILT_IN_SPRINTF])),
8764          retval);
8765       return build2 (COMPOUND_EXPR, TREE_TYPE (retval), call, retval);
8766     }
8767   else
8768     return call;
8769 }