config.gcc (powerpc*-linux*-*): Add support for 64-bit little endian Linux systems...
[platform/upstream/gcc.git] / gcc / config / rs6000 / rs6000.c
1 /* Subroutines used for code generation on IBM RS/6000.
2    Copyright (C) 1991-2018 Free Software Foundation, Inc.
3    Contributed by Richard Kenner (kenner@vlsi1.ultra.nyu.edu)
4
5    This file is part of GCC.
6
7    GCC is free software; you can redistribute it and/or modify it
8    under the terms of the GNU General Public License as published
9    by the Free Software Foundation; either version 3, or (at your
10    option) any later version.
11
12    GCC is distributed in the hope that it will be useful, but WITHOUT
13    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
15    License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GCC; see the file COPYING3.  If not see
19    <http://www.gnu.org/licenses/>.  */
20
21 #define IN_TARGET_CODE 1
22
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "backend.h"
27 #include "rtl.h"
28 #include "tree.h"
29 #include "memmodel.h"
30 #include "gimple.h"
31 #include "cfghooks.h"
32 #include "cfgloop.h"
33 #include "df.h"
34 #include "tm_p.h"
35 #include "stringpool.h"
36 #include "expmed.h"
37 #include "optabs.h"
38 #include "regs.h"
39 #include "ira.h"
40 #include "recog.h"
41 #include "cgraph.h"
42 #include "diagnostic-core.h"
43 #include "insn-attr.h"
44 #include "flags.h"
45 #include "alias.h"
46 #include "fold-const.h"
47 #include "attribs.h"
48 #include "stor-layout.h"
49 #include "calls.h"
50 #include "print-tree.h"
51 #include "varasm.h"
52 #include "explow.h"
53 #include "expr.h"
54 #include "output.h"
55 #include "dbxout.h"
56 #include "common/common-target.h"
57 #include "langhooks.h"
58 #include "reload.h"
59 #include "sched-int.h"
60 #include "gimplify.h"
61 #include "gimple-fold.h"
62 #include "gimple-iterator.h"
63 #include "gimple-ssa.h"
64 #include "gimple-walk.h"
65 #include "intl.h"
66 #include "params.h"
67 #include "tm-constrs.h"
68 #include "tree-vectorizer.h"
69 #include "target-globals.h"
70 #include "builtins.h"
71 #include "context.h"
72 #include "tree-pass.h"
73 #include "except.h"
74 #if TARGET_XCOFF
75 #include "xcoffout.h"  /* get declarations of xcoff_*_section_name */
76 #endif
77 #if TARGET_MACHO
78 #include "gstab.h"  /* for N_SLINE */
79 #endif
80 #include "case-cfn-macros.h"
81 #include "ppc-auxv.h"
82 #include "tree-ssa-propagate.h"
83
84 /* This file should be included last.  */
85 #include "target-def.h"
86
87 #ifndef TARGET_NO_PROTOTYPE
88 #define TARGET_NO_PROTOTYPE 0
89 #endif
90
91   /* Set -mabi=ieeelongdouble on some old targets.  In the future, power server
92      systems will also set long double to be IEEE 128-bit.  AIX and Darwin
93      explicitly redefine TARGET_IEEEQUAD and TARGET_IEEEQUAD_DEFAULT to 0, so
94      those systems will not pick up this default.  This needs to be after all
95      of the include files, so that POWERPC_LINUX and POWERPC_FREEBSD are
96      properly defined.  */
97 #ifndef TARGET_IEEEQUAD_DEFAULT
98 #if !defined (POWERPC_LINUX) && !defined (POWERPC_FREEBSD)
99 #define TARGET_IEEEQUAD_DEFAULT 1
100 #else
101 #define TARGET_IEEEQUAD_DEFAULT 0
102 #endif
103 #endif
104
105 #define min(A,B)        ((A) < (B) ? (A) : (B))
106 #define max(A,B)        ((A) > (B) ? (A) : (B))
107
108 static pad_direction rs6000_function_arg_padding (machine_mode, const_tree);
109
110 /* Structure used to define the rs6000 stack */
111 typedef struct rs6000_stack {
112   int reload_completed;         /* stack info won't change from here on */
113   int first_gp_reg_save;        /* first callee saved GP register used */
114   int first_fp_reg_save;        /* first callee saved FP register used */
115   int first_altivec_reg_save;   /* first callee saved AltiVec register used */
116   int lr_save_p;                /* true if the link reg needs to be saved */
117   int cr_save_p;                /* true if the CR reg needs to be saved */
118   unsigned int vrsave_mask;     /* mask of vec registers to save */
119   int push_p;                   /* true if we need to allocate stack space */
120   int calls_p;                  /* true if the function makes any calls */
121   int world_save_p;             /* true if we're saving *everything*:
122                                    r13-r31, cr, f14-f31, vrsave, v20-v31  */
123   enum rs6000_abi abi;          /* which ABI to use */
124   int gp_save_offset;           /* offset to save GP regs from initial SP */
125   int fp_save_offset;           /* offset to save FP regs from initial SP */
126   int altivec_save_offset;      /* offset to save AltiVec regs from initial SP */
127   int lr_save_offset;           /* offset to save LR from initial SP */
128   int cr_save_offset;           /* offset to save CR from initial SP */
129   int vrsave_save_offset;       /* offset to save VRSAVE from initial SP */
130   int varargs_save_offset;      /* offset to save the varargs registers */
131   int ehrd_offset;              /* offset to EH return data */
132   int ehcr_offset;              /* offset to EH CR field data */
133   int reg_size;                 /* register size (4 or 8) */
134   HOST_WIDE_INT vars_size;      /* variable save area size */
135   int parm_size;                /* outgoing parameter size */
136   int save_size;                /* save area size */
137   int fixed_size;               /* fixed size of stack frame */
138   int gp_size;                  /* size of saved GP registers */
139   int fp_size;                  /* size of saved FP registers */
140   int altivec_size;             /* size of saved AltiVec registers */
141   int cr_size;                  /* size to hold CR if not in fixed area */
142   int vrsave_size;              /* size to hold VRSAVE */
143   int altivec_padding_size;     /* size of altivec alignment padding */
144   HOST_WIDE_INT total_size;     /* total bytes allocated for stack */
145   int savres_strategy;
146 } rs6000_stack_t;
147
148 /* A C structure for machine-specific, per-function data.
149    This is added to the cfun structure.  */
150 typedef struct GTY(()) machine_function
151 {
152   /* Flags if __builtin_return_address (n) with n >= 1 was used.  */
153   int ra_needs_full_frame;
154   /* Flags if __builtin_return_address (0) was used.  */
155   int ra_need_lr;
156   /* Cache lr_save_p after expansion of builtin_eh_return.  */
157   int lr_save_state;
158   /* Whether we need to save the TOC to the reserved stack location in the
159      function prologue.  */
160   bool save_toc_in_prologue;
161   /* Offset from virtual_stack_vars_rtx to the start of the ABI_V4
162      varargs save area.  */
163   HOST_WIDE_INT varargs_save_offset;
164   /* Alternative internal arg pointer for -fsplit-stack.  */
165   rtx split_stack_arg_pointer;
166   bool split_stack_argp_used;
167   /* Flag if r2 setup is needed with ELFv2 ABI.  */
168   bool r2_setup_needed;
169   /* The number of components we use for separate shrink-wrapping.  */
170   int n_components;
171   /* The components already handled by separate shrink-wrapping, which should
172      not be considered by the prologue and epilogue.  */
173   bool gpr_is_wrapped_separately[32];
174   bool fpr_is_wrapped_separately[32];
175   bool lr_is_wrapped_separately;
176   bool toc_is_wrapped_separately;
177 } machine_function;
178
179 /* Support targetm.vectorize.builtin_mask_for_load.  */
180 static GTY(()) tree altivec_builtin_mask_for_load;
181
182 /* Set to nonzero once AIX common-mode calls have been defined.  */
183 static GTY(()) int common_mode_defined;
184
185 /* Label number of label created for -mrelocatable, to call to so we can
186    get the address of the GOT section */
187 static int rs6000_pic_labelno;
188
189 #ifdef USING_ELFOS_H
190 /* Counter for labels which are to be placed in .fixup.  */
191 int fixuplabelno = 0;
192 #endif
193
194 /* Whether to use variant of AIX ABI for PowerPC64 Linux.  */
195 int dot_symbols;
196
197 /* Specify the machine mode that pointers have.  After generation of rtl, the
198    compiler makes no further distinction between pointers and any other objects
199    of this machine mode.  */
200 scalar_int_mode rs6000_pmode;
201
202 /* Width in bits of a pointer.  */
203 unsigned rs6000_pointer_size;
204
205 #ifdef HAVE_AS_GNU_ATTRIBUTE
206 # ifndef HAVE_LD_PPC_GNU_ATTR_LONG_DOUBLE
207 # define HAVE_LD_PPC_GNU_ATTR_LONG_DOUBLE 0
208 # endif
209 /* Flag whether floating point values have been passed/returned.
210    Note that this doesn't say whether fprs are used, since the
211    Tag_GNU_Power_ABI_FP .gnu.attributes value this flag controls
212    should be set for soft-float values passed in gprs and ieee128
213    values passed in vsx registers.  */
214 static bool rs6000_passes_float;
215 static bool rs6000_passes_long_double;
216 /* Flag whether vector values have been passed/returned.  */
217 static bool rs6000_passes_vector;
218 /* Flag whether small (<= 8 byte) structures have been returned.  */
219 static bool rs6000_returns_struct;
220 #endif
221
222 /* Value is TRUE if register/mode pair is acceptable.  */
223 static bool rs6000_hard_regno_mode_ok_p
224   [NUM_MACHINE_MODES][FIRST_PSEUDO_REGISTER];
225
226 /* Maximum number of registers needed for a given register class and mode.  */
227 unsigned char rs6000_class_max_nregs[NUM_MACHINE_MODES][LIM_REG_CLASSES];
228
229 /* How many registers are needed for a given register and mode.  */
230 unsigned char rs6000_hard_regno_nregs[NUM_MACHINE_MODES][FIRST_PSEUDO_REGISTER];
231
232 /* Map register number to register class.  */
233 enum reg_class rs6000_regno_regclass[FIRST_PSEUDO_REGISTER];
234
235 static int dbg_cost_ctrl;
236
237 /* Built in types.  */
238 tree rs6000_builtin_types[RS6000_BTI_MAX];
239 tree rs6000_builtin_decls[RS6000_BUILTIN_COUNT];
240
241 /* Flag to say the TOC is initialized */
242 int toc_initialized, need_toc_init;
243 char toc_label_name[10];
244
245 /* Cached value of rs6000_variable_issue. This is cached in
246    rs6000_variable_issue hook and returned from rs6000_sched_reorder2.  */
247 static short cached_can_issue_more;
248
249 static GTY(()) section *read_only_data_section;
250 static GTY(()) section *private_data_section;
251 static GTY(()) section *tls_data_section;
252 static GTY(()) section *tls_private_data_section;
253 static GTY(()) section *read_only_private_data_section;
254 static GTY(()) section *sdata2_section;
255 static GTY(()) section *toc_section;
256
257 struct builtin_description
258 {
259   const HOST_WIDE_INT mask;
260   const enum insn_code icode;
261   const char *const name;
262   const enum rs6000_builtins code;
263 };
264
265 /* Describe the vector unit used for modes.  */
266 enum rs6000_vector rs6000_vector_unit[NUM_MACHINE_MODES];
267 enum rs6000_vector rs6000_vector_mem[NUM_MACHINE_MODES];
268
269 /* Register classes for various constraints that are based on the target
270    switches.  */
271 enum reg_class rs6000_constraints[RS6000_CONSTRAINT_MAX];
272
273 /* Describe the alignment of a vector.  */
274 int rs6000_vector_align[NUM_MACHINE_MODES];
275
276 /* Map selected modes to types for builtins.  */
277 static GTY(()) tree builtin_mode_to_type[MAX_MACHINE_MODE][2];
278
279 /* What modes to automatically generate reciprocal divide estimate (fre) and
280    reciprocal sqrt (frsqrte) for.  */
281 unsigned char rs6000_recip_bits[MAX_MACHINE_MODE];
282
283 /* Masks to determine which reciprocal esitmate instructions to generate
284    automatically.  */
285 enum rs6000_recip_mask {
286   RECIP_SF_DIV          = 0x001,        /* Use divide estimate */
287   RECIP_DF_DIV          = 0x002,
288   RECIP_V4SF_DIV        = 0x004,
289   RECIP_V2DF_DIV        = 0x008,
290
291   RECIP_SF_RSQRT        = 0x010,        /* Use reciprocal sqrt estimate.  */
292   RECIP_DF_RSQRT        = 0x020,
293   RECIP_V4SF_RSQRT      = 0x040,
294   RECIP_V2DF_RSQRT      = 0x080,
295
296   /* Various combination of flags for -mrecip=xxx.  */
297   RECIP_NONE            = 0,
298   RECIP_ALL             = (RECIP_SF_DIV | RECIP_DF_DIV | RECIP_V4SF_DIV
299                            | RECIP_V2DF_DIV | RECIP_SF_RSQRT | RECIP_DF_RSQRT
300                            | RECIP_V4SF_RSQRT | RECIP_V2DF_RSQRT),
301
302   RECIP_HIGH_PRECISION  = RECIP_ALL,
303
304   /* On low precision machines like the power5, don't enable double precision
305      reciprocal square root estimate, since it isn't accurate enough.  */
306   RECIP_LOW_PRECISION   = (RECIP_ALL & ~(RECIP_DF_RSQRT | RECIP_V2DF_RSQRT))
307 };
308
309 /* -mrecip options.  */
310 static struct
311 {
312   const char *string;           /* option name */
313   unsigned int mask;            /* mask bits to set */
314 } recip_options[] = {
315   { "all",       RECIP_ALL },
316   { "none",      RECIP_NONE },
317   { "div",       (RECIP_SF_DIV | RECIP_DF_DIV | RECIP_V4SF_DIV
318                   | RECIP_V2DF_DIV) },
319   { "divf",      (RECIP_SF_DIV | RECIP_V4SF_DIV) },
320   { "divd",      (RECIP_DF_DIV | RECIP_V2DF_DIV) },
321   { "rsqrt",     (RECIP_SF_RSQRT | RECIP_DF_RSQRT | RECIP_V4SF_RSQRT
322                   | RECIP_V2DF_RSQRT) },
323   { "rsqrtf",    (RECIP_SF_RSQRT | RECIP_V4SF_RSQRT) },
324   { "rsqrtd",    (RECIP_DF_RSQRT | RECIP_V2DF_RSQRT) },
325 };
326
327 /* Used by __builtin_cpu_is(), mapping from PLATFORM names to values.  */
328 static const struct
329 {
330   const char *cpu;
331   unsigned int cpuid;
332 } cpu_is_info[] = {
333   { "power9",      PPC_PLATFORM_POWER9 },
334   { "power8",      PPC_PLATFORM_POWER8 },
335   { "power7",      PPC_PLATFORM_POWER7 },
336   { "power6x",     PPC_PLATFORM_POWER6X },
337   { "power6",      PPC_PLATFORM_POWER6 },
338   { "power5+",     PPC_PLATFORM_POWER5_PLUS },
339   { "power5",      PPC_PLATFORM_POWER5 },
340   { "ppc970",      PPC_PLATFORM_PPC970 },
341   { "power4",      PPC_PLATFORM_POWER4 },
342   { "ppca2",       PPC_PLATFORM_PPCA2 },
343   { "ppc476",      PPC_PLATFORM_PPC476 },
344   { "ppc464",      PPC_PLATFORM_PPC464 },
345   { "ppc440",      PPC_PLATFORM_PPC440 },
346   { "ppc405",      PPC_PLATFORM_PPC405 },
347   { "ppc-cell-be", PPC_PLATFORM_CELL_BE }
348 };
349
350 /* Used by __builtin_cpu_supports(), mapping from HWCAP names to masks.  */
351 static const struct
352 {
353   const char *hwcap;
354   int mask;
355   unsigned int id;
356 } cpu_supports_info[] = {
357   /* AT_HWCAP masks.  */
358   { "4xxmac",           PPC_FEATURE_HAS_4xxMAC,         0 },
359   { "altivec",          PPC_FEATURE_HAS_ALTIVEC,        0 },
360   { "arch_2_05",        PPC_FEATURE_ARCH_2_05,          0 },
361   { "arch_2_06",        PPC_FEATURE_ARCH_2_06,          0 },
362   { "archpmu",          PPC_FEATURE_PERFMON_COMPAT,     0 },
363   { "booke",            PPC_FEATURE_BOOKE,              0 },
364   { "cellbe",           PPC_FEATURE_CELL_BE,            0 },
365   { "dfp",              PPC_FEATURE_HAS_DFP,            0 },
366   { "efpdouble",        PPC_FEATURE_HAS_EFP_DOUBLE,     0 },
367   { "efpsingle",        PPC_FEATURE_HAS_EFP_SINGLE,     0 },
368   { "fpu",              PPC_FEATURE_HAS_FPU,            0 },
369   { "ic_snoop",         PPC_FEATURE_ICACHE_SNOOP,       0 },
370   { "mmu",              PPC_FEATURE_HAS_MMU,            0 },
371   { "notb",             PPC_FEATURE_NO_TB,              0 },
372   { "pa6t",             PPC_FEATURE_PA6T,               0 },
373   { "power4",           PPC_FEATURE_POWER4,             0 },
374   { "power5",           PPC_FEATURE_POWER5,             0 },
375   { "power5+",          PPC_FEATURE_POWER5_PLUS,        0 },
376   { "power6x",          PPC_FEATURE_POWER6_EXT,         0 },
377   { "ppc32",            PPC_FEATURE_32,                 0 },
378   { "ppc601",           PPC_FEATURE_601_INSTR,          0 },
379   { "ppc64",            PPC_FEATURE_64,                 0 },
380   { "ppcle",            PPC_FEATURE_PPC_LE,             0 },
381   { "smt",              PPC_FEATURE_SMT,                0 },
382   { "spe",              PPC_FEATURE_HAS_SPE,            0 },
383   { "true_le",          PPC_FEATURE_TRUE_LE,            0 },
384   { "ucache",           PPC_FEATURE_UNIFIED_CACHE,      0 },
385   { "vsx",              PPC_FEATURE_HAS_VSX,            0 },
386
387   /* AT_HWCAP2 masks.  */
388   { "arch_2_07",        PPC_FEATURE2_ARCH_2_07,         1 },
389   { "dscr",             PPC_FEATURE2_HAS_DSCR,          1 },
390   { "ebb",              PPC_FEATURE2_HAS_EBB,           1 },
391   { "htm",              PPC_FEATURE2_HAS_HTM,           1 },
392   { "htm-nosc",         PPC_FEATURE2_HTM_NOSC,          1 },
393   { "htm-no-suspend",   PPC_FEATURE2_HTM_NO_SUSPEND,    1 },
394   { "isel",             PPC_FEATURE2_HAS_ISEL,          1 },
395   { "tar",              PPC_FEATURE2_HAS_TAR,           1 },
396   { "vcrypto",          PPC_FEATURE2_HAS_VEC_CRYPTO,    1 },
397   { "arch_3_00",        PPC_FEATURE2_ARCH_3_00,         1 },
398   { "ieee128",          PPC_FEATURE2_HAS_IEEE128,       1 },
399   { "darn",             PPC_FEATURE2_DARN,              1 },
400   { "scv",              PPC_FEATURE2_SCV,               1 }
401 };
402
403 /* On PowerPC, we have a limited number of target clones that we care about
404    which means we can use an array to hold the options, rather than having more
405    elaborate data structures to identify each possible variation.  Order the
406    clones from the default to the highest ISA.  */
407 enum {
408   CLONE_DEFAULT         = 0,            /* default clone.  */
409   CLONE_ISA_2_05,                       /* ISA 2.05 (power6).  */
410   CLONE_ISA_2_06,                       /* ISA 2.06 (power7).  */
411   CLONE_ISA_2_07,                       /* ISA 2.07 (power8).  */
412   CLONE_ISA_3_00,                       /* ISA 3.00 (power9).  */
413   CLONE_MAX
414 };
415
416 /* Map compiler ISA bits into HWCAP names.  */
417 struct clone_map {
418   HOST_WIDE_INT isa_mask;       /* rs6000_isa mask */
419   const char *name;             /* name to use in __builtin_cpu_supports.  */
420 };
421
422 static const struct clone_map rs6000_clone_map[CLONE_MAX] = {
423   { 0,                          "" },           /* Default options.  */
424   { OPTION_MASK_CMPB,           "arch_2_05" },  /* ISA 2.05 (power6).  */
425   { OPTION_MASK_POPCNTD,        "arch_2_06" },  /* ISA 2.06 (power7).  */
426   { OPTION_MASK_P8_VECTOR,      "arch_2_07" },  /* ISA 2.07 (power8).  */
427   { OPTION_MASK_P9_VECTOR,      "arch_3_00" },  /* ISA 3.00 (power9).  */
428 };
429
430
431 /* Newer LIBCs explicitly export this symbol to declare that they provide
432    the AT_PLATFORM and AT_HWCAP/AT_HWCAP2 values in the TCB.  We emit a
433    reference to this symbol whenever we expand a CPU builtin, so that
434    we never link against an old LIBC.  */
435 const char *tcb_verification_symbol = "__parse_hwcap_and_convert_at_platform";
436
437 /* True if we have expanded a CPU builtin.  */
438 bool cpu_builtin_p;
439
440 /* Pointer to function (in rs6000-c.c) that can define or undefine target
441    macros that have changed.  Languages that don't support the preprocessor
442    don't link in rs6000-c.c, so we can't call it directly.  */
443 void (*rs6000_target_modify_macros_ptr) (bool, HOST_WIDE_INT, HOST_WIDE_INT);
444
445 /* Simplfy register classes into simpler classifications.  We assume
446    GPR_REG_TYPE - FPR_REG_TYPE are ordered so that we can use a simple range
447    check for standard register classes (gpr/floating/altivec/vsx) and
448    floating/vector classes (float/altivec/vsx).  */
449
450 enum rs6000_reg_type {
451   NO_REG_TYPE,
452   PSEUDO_REG_TYPE,
453   GPR_REG_TYPE,
454   VSX_REG_TYPE,
455   ALTIVEC_REG_TYPE,
456   FPR_REG_TYPE,
457   SPR_REG_TYPE,
458   CR_REG_TYPE
459 };
460
461 /* Map register class to register type.  */
462 static enum rs6000_reg_type reg_class_to_reg_type[N_REG_CLASSES];
463
464 /* First/last register type for the 'normal' register types (i.e. general
465    purpose, floating point, altivec, and VSX registers).  */
466 #define IS_STD_REG_TYPE(RTYPE) IN_RANGE(RTYPE, GPR_REG_TYPE, FPR_REG_TYPE)
467
468 #define IS_FP_VECT_REG_TYPE(RTYPE) IN_RANGE(RTYPE, VSX_REG_TYPE, FPR_REG_TYPE)
469
470
471 /* Register classes we care about in secondary reload or go if legitimate
472    address.  We only need to worry about GPR, FPR, and Altivec registers here,
473    along an ANY field that is the OR of the 3 register classes.  */
474
475 enum rs6000_reload_reg_type {
476   RELOAD_REG_GPR,                       /* General purpose registers.  */
477   RELOAD_REG_FPR,                       /* Traditional floating point regs.  */
478   RELOAD_REG_VMX,                       /* Altivec (VMX) registers.  */
479   RELOAD_REG_ANY,                       /* OR of GPR, FPR, Altivec masks.  */
480   N_RELOAD_REG
481 };
482
483 /* For setting up register classes, loop through the 3 register classes mapping
484    into real registers, and skip the ANY class, which is just an OR of the
485    bits.  */
486 #define FIRST_RELOAD_REG_CLASS  RELOAD_REG_GPR
487 #define LAST_RELOAD_REG_CLASS   RELOAD_REG_VMX
488
489 /* Map reload register type to a register in the register class.  */
490 struct reload_reg_map_type {
491   const char *name;                     /* Register class name.  */
492   int reg;                              /* Register in the register class.  */
493 };
494
495 static const struct reload_reg_map_type reload_reg_map[N_RELOAD_REG] = {
496   { "Gpr",      FIRST_GPR_REGNO },      /* RELOAD_REG_GPR.  */
497   { "Fpr",      FIRST_FPR_REGNO },      /* RELOAD_REG_FPR.  */
498   { "VMX",      FIRST_ALTIVEC_REGNO },  /* RELOAD_REG_VMX.  */
499   { "Any",      -1 },                   /* RELOAD_REG_ANY.  */
500 };
501
502 /* Mask bits for each register class, indexed per mode.  Historically the
503    compiler has been more restrictive which types can do PRE_MODIFY instead of
504    PRE_INC and PRE_DEC, so keep track of sepaate bits for these two.  */
505 typedef unsigned char addr_mask_type;
506
507 #define RELOAD_REG_VALID        0x01    /* Mode valid in register..  */
508 #define RELOAD_REG_MULTIPLE     0x02    /* Mode takes multiple registers.  */
509 #define RELOAD_REG_INDEXED      0x04    /* Reg+reg addressing.  */
510 #define RELOAD_REG_OFFSET       0x08    /* Reg+offset addressing. */
511 #define RELOAD_REG_PRE_INCDEC   0x10    /* PRE_INC/PRE_DEC valid.  */
512 #define RELOAD_REG_PRE_MODIFY   0x20    /* PRE_MODIFY valid.  */
513 #define RELOAD_REG_AND_M16      0x40    /* AND -16 addressing.  */
514 #define RELOAD_REG_QUAD_OFFSET  0x80    /* quad offset is limited.  */
515
516 /* Register type masks based on the type, of valid addressing modes.  */
517 struct rs6000_reg_addr {
518   enum insn_code reload_load;           /* INSN to reload for loading. */
519   enum insn_code reload_store;          /* INSN to reload for storing.  */
520   enum insn_code reload_fpr_gpr;        /* INSN to move from FPR to GPR.  */
521   enum insn_code reload_gpr_vsx;        /* INSN to move from GPR to VSX.  */
522   enum insn_code reload_vsx_gpr;        /* INSN to move from VSX to GPR.  */
523   enum insn_code fusion_gpr_ld;         /* INSN for fusing gpr ADDIS/loads.  */
524                                         /* INSNs for fusing addi with loads
525                                            or stores for each reg. class.  */                                      
526   enum insn_code fusion_addi_ld[(int)N_RELOAD_REG];
527   enum insn_code fusion_addi_st[(int)N_RELOAD_REG];
528                                         /* INSNs for fusing addis with loads
529                                            or stores for each reg. class.  */                                      
530   enum insn_code fusion_addis_ld[(int)N_RELOAD_REG];
531   enum insn_code fusion_addis_st[(int)N_RELOAD_REG];
532   addr_mask_type addr_mask[(int)N_RELOAD_REG]; /* Valid address masks.  */
533   bool scalar_in_vmx_p;                 /* Scalar value can go in VMX.  */
534   bool fused_toc;                       /* Mode supports TOC fusion.  */
535 };
536
537 static struct rs6000_reg_addr reg_addr[NUM_MACHINE_MODES];
538
539 /* Helper function to say whether a mode supports PRE_INC or PRE_DEC.  */
540 static inline bool
541 mode_supports_pre_incdec_p (machine_mode mode)
542 {
543   return ((reg_addr[mode].addr_mask[RELOAD_REG_ANY] & RELOAD_REG_PRE_INCDEC)
544           != 0);
545 }
546
547 /* Helper function to say whether a mode supports PRE_MODIFY.  */
548 static inline bool
549 mode_supports_pre_modify_p (machine_mode mode)
550 {
551   return ((reg_addr[mode].addr_mask[RELOAD_REG_ANY] & RELOAD_REG_PRE_MODIFY)
552           != 0);
553 }
554
555 /* Given that there exists at least one variable that is set (produced)
556    by OUT_INSN and read (consumed) by IN_INSN, return true iff
557    IN_INSN represents one or more memory store operations and none of
558    the variables set by OUT_INSN is used by IN_INSN as the address of a
559    store operation.  If either IN_INSN or OUT_INSN does not represent
560    a "single" RTL SET expression (as loosely defined by the
561    implementation of the single_set function) or a PARALLEL with only
562    SETs, CLOBBERs, and USEs inside, this function returns false.
563
564    This rs6000-specific version of store_data_bypass_p checks for
565    certain conditions that result in assertion failures (and internal
566    compiler errors) in the generic store_data_bypass_p function and
567    returns false rather than calling store_data_bypass_p if one of the
568    problematic conditions is detected.  */
569
570 int
571 rs6000_store_data_bypass_p (rtx_insn *out_insn, rtx_insn *in_insn)
572 {
573   rtx out_set, in_set;
574   rtx out_pat, in_pat;
575   rtx out_exp, in_exp;
576   int i, j;
577
578   in_set = single_set (in_insn);
579   if (in_set)
580     {
581       if (MEM_P (SET_DEST (in_set)))
582         {
583           out_set = single_set (out_insn);
584           if (!out_set)
585             {
586               out_pat = PATTERN (out_insn);
587               if (GET_CODE (out_pat) == PARALLEL)
588                 {
589                   for (i = 0; i < XVECLEN (out_pat, 0); i++)
590                     {
591                       out_exp = XVECEXP (out_pat, 0, i);
592                       if ((GET_CODE (out_exp) == CLOBBER)
593                           || (GET_CODE (out_exp) == USE))
594                         continue;
595                       else if (GET_CODE (out_exp) != SET)
596                         return false;
597                     }
598                 }
599             }
600         }
601     }
602   else
603     {
604       in_pat = PATTERN (in_insn);
605       if (GET_CODE (in_pat) != PARALLEL)
606         return false;
607
608       for (i = 0; i < XVECLEN (in_pat, 0); i++)
609         {
610           in_exp = XVECEXP (in_pat, 0, i);
611           if ((GET_CODE (in_exp) == CLOBBER) || (GET_CODE (in_exp) == USE))
612             continue;
613           else if (GET_CODE (in_exp) != SET)
614             return false;
615
616           if (MEM_P (SET_DEST (in_exp)))
617             {
618               out_set = single_set (out_insn);
619               if (!out_set)
620                 {
621                   out_pat = PATTERN (out_insn);
622                   if (GET_CODE (out_pat) != PARALLEL)
623                     return false;
624                   for (j = 0; j < XVECLEN (out_pat, 0); j++)
625                     {
626                       out_exp = XVECEXP (out_pat, 0, j);
627                       if ((GET_CODE (out_exp) == CLOBBER)
628                           || (GET_CODE (out_exp) == USE))
629                         continue;
630                       else if (GET_CODE (out_exp) != SET)
631                         return false;
632                     }
633                 }
634             }
635         }
636     }
637   return store_data_bypass_p (out_insn, in_insn);
638 }
639
640 /* Return true if we have D-form addressing in altivec registers.  */
641 static inline bool
642 mode_supports_vmx_dform (machine_mode mode)
643 {
644   return ((reg_addr[mode].addr_mask[RELOAD_REG_VMX] & RELOAD_REG_OFFSET) != 0);
645 }
646
647 /* Return true if we have D-form addressing in VSX registers.  This addressing
648    is more limited than normal d-form addressing in that the offset must be
649    aligned on a 16-byte boundary.  */
650 static inline bool
651 mode_supports_vsx_dform_quad (machine_mode mode)
652 {
653   return ((reg_addr[mode].addr_mask[RELOAD_REG_ANY] & RELOAD_REG_QUAD_OFFSET)
654           != 0);
655 }
656
657 \f
658 /* Processor costs (relative to an add) */
659
660 const struct processor_costs *rs6000_cost;
661
662 /* Instruction size costs on 32bit processors.  */
663 static const
664 struct processor_costs size32_cost = {
665   COSTS_N_INSNS (1),    /* mulsi */
666   COSTS_N_INSNS (1),    /* mulsi_const */
667   COSTS_N_INSNS (1),    /* mulsi_const9 */
668   COSTS_N_INSNS (1),    /* muldi */
669   COSTS_N_INSNS (1),    /* divsi */
670   COSTS_N_INSNS (1),    /* divdi */
671   COSTS_N_INSNS (1),    /* fp */
672   COSTS_N_INSNS (1),    /* dmul */
673   COSTS_N_INSNS (1),    /* sdiv */
674   COSTS_N_INSNS (1),    /* ddiv */
675   32,                   /* cache line size */
676   0,                    /* l1 cache */
677   0,                    /* l2 cache */
678   0,                    /* streams */
679   0,                    /* SF->DF convert */
680 };
681
682 /* Instruction size costs on 64bit processors.  */
683 static const
684 struct processor_costs size64_cost = {
685   COSTS_N_INSNS (1),    /* mulsi */
686   COSTS_N_INSNS (1),    /* mulsi_const */
687   COSTS_N_INSNS (1),    /* mulsi_const9 */
688   COSTS_N_INSNS (1),    /* muldi */
689   COSTS_N_INSNS (1),    /* divsi */
690   COSTS_N_INSNS (1),    /* divdi */
691   COSTS_N_INSNS (1),    /* fp */
692   COSTS_N_INSNS (1),    /* dmul */
693   COSTS_N_INSNS (1),    /* sdiv */
694   COSTS_N_INSNS (1),    /* ddiv */
695   128,                  /* cache line size */
696   0,                    /* l1 cache */
697   0,                    /* l2 cache */
698   0,                    /* streams */
699   0,                    /* SF->DF convert */
700 };
701
702 /* Instruction costs on RS64A processors.  */
703 static const
704 struct processor_costs rs64a_cost = {
705   COSTS_N_INSNS (20),   /* mulsi */
706   COSTS_N_INSNS (12),   /* mulsi_const */
707   COSTS_N_INSNS (8),    /* mulsi_const9 */
708   COSTS_N_INSNS (34),   /* muldi */
709   COSTS_N_INSNS (65),   /* divsi */
710   COSTS_N_INSNS (67),   /* divdi */
711   COSTS_N_INSNS (4),    /* fp */
712   COSTS_N_INSNS (4),    /* dmul */
713   COSTS_N_INSNS (31),   /* sdiv */
714   COSTS_N_INSNS (31),   /* ddiv */
715   128,                  /* cache line size */
716   128,                  /* l1 cache */
717   2048,                 /* l2 cache */
718   1,                    /* streams */
719   0,                    /* SF->DF convert */
720 };
721
722 /* Instruction costs on MPCCORE processors.  */
723 static const
724 struct processor_costs mpccore_cost = {
725   COSTS_N_INSNS (2),    /* mulsi */
726   COSTS_N_INSNS (2),    /* mulsi_const */
727   COSTS_N_INSNS (2),    /* mulsi_const9 */
728   COSTS_N_INSNS (2),    /* muldi */
729   COSTS_N_INSNS (6),    /* divsi */
730   COSTS_N_INSNS (6),    /* divdi */
731   COSTS_N_INSNS (4),    /* fp */
732   COSTS_N_INSNS (5),    /* dmul */
733   COSTS_N_INSNS (10),   /* sdiv */
734   COSTS_N_INSNS (17),   /* ddiv */
735   32,                   /* cache line size */
736   4,                    /* l1 cache */
737   16,                   /* l2 cache */
738   1,                    /* streams */
739   0,                    /* SF->DF convert */
740 };
741
742 /* Instruction costs on PPC403 processors.  */
743 static const
744 struct processor_costs ppc403_cost = {
745   COSTS_N_INSNS (4),    /* mulsi */
746   COSTS_N_INSNS (4),    /* mulsi_const */
747   COSTS_N_INSNS (4),    /* mulsi_const9 */
748   COSTS_N_INSNS (4),    /* muldi */
749   COSTS_N_INSNS (33),   /* divsi */
750   COSTS_N_INSNS (33),   /* divdi */
751   COSTS_N_INSNS (11),   /* fp */
752   COSTS_N_INSNS (11),   /* dmul */
753   COSTS_N_INSNS (11),   /* sdiv */
754   COSTS_N_INSNS (11),   /* ddiv */
755   32,                   /* cache line size */
756   4,                    /* l1 cache */
757   16,                   /* l2 cache */
758   1,                    /* streams */
759   0,                    /* SF->DF convert */
760 };
761
762 /* Instruction costs on PPC405 processors.  */
763 static const
764 struct processor_costs ppc405_cost = {
765   COSTS_N_INSNS (5),    /* mulsi */
766   COSTS_N_INSNS (4),    /* mulsi_const */
767   COSTS_N_INSNS (3),    /* mulsi_const9 */
768   COSTS_N_INSNS (5),    /* muldi */
769   COSTS_N_INSNS (35),   /* divsi */
770   COSTS_N_INSNS (35),   /* divdi */
771   COSTS_N_INSNS (11),   /* fp */
772   COSTS_N_INSNS (11),   /* dmul */
773   COSTS_N_INSNS (11),   /* sdiv */
774   COSTS_N_INSNS (11),   /* ddiv */
775   32,                   /* cache line size */
776   16,                   /* l1 cache */
777   128,                  /* l2 cache */
778   1,                    /* streams */
779   0,                    /* SF->DF convert */
780 };
781
782 /* Instruction costs on PPC440 processors.  */
783 static const
784 struct processor_costs ppc440_cost = {
785   COSTS_N_INSNS (3),    /* mulsi */
786   COSTS_N_INSNS (2),    /* mulsi_const */
787   COSTS_N_INSNS (2),    /* mulsi_const9 */
788   COSTS_N_INSNS (3),    /* muldi */
789   COSTS_N_INSNS (34),   /* divsi */
790   COSTS_N_INSNS (34),   /* divdi */
791   COSTS_N_INSNS (5),    /* fp */
792   COSTS_N_INSNS (5),    /* dmul */
793   COSTS_N_INSNS (19),   /* sdiv */
794   COSTS_N_INSNS (33),   /* ddiv */
795   32,                   /* cache line size */
796   32,                   /* l1 cache */
797   256,                  /* l2 cache */
798   1,                    /* streams */
799   0,                    /* SF->DF convert */
800 };
801
802 /* Instruction costs on PPC476 processors.  */
803 static const
804 struct processor_costs ppc476_cost = {
805   COSTS_N_INSNS (4),    /* mulsi */
806   COSTS_N_INSNS (4),    /* mulsi_const */
807   COSTS_N_INSNS (4),    /* mulsi_const9 */
808   COSTS_N_INSNS (4),    /* muldi */
809   COSTS_N_INSNS (11),   /* divsi */
810   COSTS_N_INSNS (11),   /* divdi */
811   COSTS_N_INSNS (6),    /* fp */
812   COSTS_N_INSNS (6),    /* dmul */
813   COSTS_N_INSNS (19),   /* sdiv */
814   COSTS_N_INSNS (33),   /* ddiv */
815   32,                   /* l1 cache line size */
816   32,                   /* l1 cache */
817   512,                  /* l2 cache */
818   1,                    /* streams */
819   0,                    /* SF->DF convert */
820 };
821
822 /* Instruction costs on PPC601 processors.  */
823 static const
824 struct processor_costs ppc601_cost = {
825   COSTS_N_INSNS (5),    /* mulsi */
826   COSTS_N_INSNS (5),    /* mulsi_const */
827   COSTS_N_INSNS (5),    /* mulsi_const9 */
828   COSTS_N_INSNS (5),    /* muldi */
829   COSTS_N_INSNS (36),   /* divsi */
830   COSTS_N_INSNS (36),   /* divdi */
831   COSTS_N_INSNS (4),    /* fp */
832   COSTS_N_INSNS (5),    /* dmul */
833   COSTS_N_INSNS (17),   /* sdiv */
834   COSTS_N_INSNS (31),   /* ddiv */
835   32,                   /* cache line size */
836   32,                   /* l1 cache */
837   256,                  /* l2 cache */
838   1,                    /* streams */
839   0,                    /* SF->DF convert */
840 };
841
842 /* Instruction costs on PPC603 processors.  */
843 static const
844 struct processor_costs ppc603_cost = {
845   COSTS_N_INSNS (5),    /* mulsi */
846   COSTS_N_INSNS (3),    /* mulsi_const */
847   COSTS_N_INSNS (2),    /* mulsi_const9 */
848   COSTS_N_INSNS (5),    /* muldi */
849   COSTS_N_INSNS (37),   /* divsi */
850   COSTS_N_INSNS (37),   /* divdi */
851   COSTS_N_INSNS (3),    /* fp */
852   COSTS_N_INSNS (4),    /* dmul */
853   COSTS_N_INSNS (18),   /* sdiv */
854   COSTS_N_INSNS (33),   /* ddiv */
855   32,                   /* cache line size */
856   8,                    /* l1 cache */
857   64,                   /* l2 cache */
858   1,                    /* streams */
859   0,                    /* SF->DF convert */
860 };
861
862 /* Instruction costs on PPC604 processors.  */
863 static const
864 struct processor_costs ppc604_cost = {
865   COSTS_N_INSNS (4),    /* mulsi */
866   COSTS_N_INSNS (4),    /* mulsi_const */
867   COSTS_N_INSNS (4),    /* mulsi_const9 */
868   COSTS_N_INSNS (4),    /* muldi */
869   COSTS_N_INSNS (20),   /* divsi */
870   COSTS_N_INSNS (20),   /* divdi */
871   COSTS_N_INSNS (3),    /* fp */
872   COSTS_N_INSNS (3),    /* dmul */
873   COSTS_N_INSNS (18),   /* sdiv */
874   COSTS_N_INSNS (32),   /* ddiv */
875   32,                   /* cache line size */
876   16,                   /* l1 cache */
877   512,                  /* l2 cache */
878   1,                    /* streams */
879   0,                    /* SF->DF convert */
880 };
881
882 /* Instruction costs on PPC604e processors.  */
883 static const
884 struct processor_costs ppc604e_cost = {
885   COSTS_N_INSNS (2),    /* mulsi */
886   COSTS_N_INSNS (2),    /* mulsi_const */
887   COSTS_N_INSNS (2),    /* mulsi_const9 */
888   COSTS_N_INSNS (2),    /* muldi */
889   COSTS_N_INSNS (20),   /* divsi */
890   COSTS_N_INSNS (20),   /* divdi */
891   COSTS_N_INSNS (3),    /* fp */
892   COSTS_N_INSNS (3),    /* dmul */
893   COSTS_N_INSNS (18),   /* sdiv */
894   COSTS_N_INSNS (32),   /* ddiv */
895   32,                   /* cache line size */
896   32,                   /* l1 cache */
897   1024,                 /* l2 cache */
898   1,                    /* streams */
899   0,                    /* SF->DF convert */
900 };
901
902 /* Instruction costs on PPC620 processors.  */
903 static const
904 struct processor_costs ppc620_cost = {
905   COSTS_N_INSNS (5),    /* mulsi */
906   COSTS_N_INSNS (4),    /* mulsi_const */
907   COSTS_N_INSNS (3),    /* mulsi_const9 */
908   COSTS_N_INSNS (7),    /* muldi */
909   COSTS_N_INSNS (21),   /* divsi */
910   COSTS_N_INSNS (37),   /* divdi */
911   COSTS_N_INSNS (3),    /* fp */
912   COSTS_N_INSNS (3),    /* dmul */
913   COSTS_N_INSNS (18),   /* sdiv */
914   COSTS_N_INSNS (32),   /* ddiv */
915   128,                  /* cache line size */
916   32,                   /* l1 cache */
917   1024,                 /* l2 cache */
918   1,                    /* streams */
919   0,                    /* SF->DF convert */
920 };
921
922 /* Instruction costs on PPC630 processors.  */
923 static const
924 struct processor_costs ppc630_cost = {
925   COSTS_N_INSNS (5),    /* mulsi */
926   COSTS_N_INSNS (4),    /* mulsi_const */
927   COSTS_N_INSNS (3),    /* mulsi_const9 */
928   COSTS_N_INSNS (7),    /* muldi */
929   COSTS_N_INSNS (21),   /* divsi */
930   COSTS_N_INSNS (37),   /* divdi */
931   COSTS_N_INSNS (3),    /* fp */
932   COSTS_N_INSNS (3),    /* dmul */
933   COSTS_N_INSNS (17),   /* sdiv */
934   COSTS_N_INSNS (21),   /* ddiv */
935   128,                  /* cache line size */
936   64,                   /* l1 cache */
937   1024,                 /* l2 cache */
938   1,                    /* streams */
939   0,                    /* SF->DF convert */
940 };
941
942 /* Instruction costs on Cell processor.  */
943 /* COSTS_N_INSNS (1) ~ one add.  */
944 static const
945 struct processor_costs ppccell_cost = {
946   COSTS_N_INSNS (9/2)+2,    /* mulsi */
947   COSTS_N_INSNS (6/2),    /* mulsi_const */
948   COSTS_N_INSNS (6/2),    /* mulsi_const9 */
949   COSTS_N_INSNS (15/2)+2,   /* muldi */
950   COSTS_N_INSNS (38/2),   /* divsi */
951   COSTS_N_INSNS (70/2),   /* divdi */
952   COSTS_N_INSNS (10/2),   /* fp */
953   COSTS_N_INSNS (10/2),   /* dmul */
954   COSTS_N_INSNS (74/2),   /* sdiv */
955   COSTS_N_INSNS (74/2),   /* ddiv */
956   128,                  /* cache line size */
957   32,                   /* l1 cache */
958   512,                  /* l2 cache */
959   6,                    /* streams */
960   0,                    /* SF->DF convert */
961 };
962
963 /* Instruction costs on PPC750 and PPC7400 processors.  */
964 static const
965 struct processor_costs ppc750_cost = {
966   COSTS_N_INSNS (5),    /* mulsi */
967   COSTS_N_INSNS (3),    /* mulsi_const */
968   COSTS_N_INSNS (2),    /* mulsi_const9 */
969   COSTS_N_INSNS (5),    /* muldi */
970   COSTS_N_INSNS (17),   /* divsi */
971   COSTS_N_INSNS (17),   /* divdi */
972   COSTS_N_INSNS (3),    /* fp */
973   COSTS_N_INSNS (3),    /* dmul */
974   COSTS_N_INSNS (17),   /* sdiv */
975   COSTS_N_INSNS (31),   /* ddiv */
976   32,                   /* cache line size */
977   32,                   /* l1 cache */
978   512,                  /* l2 cache */
979   1,                    /* streams */
980   0,                    /* SF->DF convert */
981 };
982
983 /* Instruction costs on PPC7450 processors.  */
984 static const
985 struct processor_costs ppc7450_cost = {
986   COSTS_N_INSNS (4),    /* mulsi */
987   COSTS_N_INSNS (3),    /* mulsi_const */
988   COSTS_N_INSNS (3),    /* mulsi_const9 */
989   COSTS_N_INSNS (4),    /* muldi */
990   COSTS_N_INSNS (23),   /* divsi */
991   COSTS_N_INSNS (23),   /* divdi */
992   COSTS_N_INSNS (5),    /* fp */
993   COSTS_N_INSNS (5),    /* dmul */
994   COSTS_N_INSNS (21),   /* sdiv */
995   COSTS_N_INSNS (35),   /* ddiv */
996   32,                   /* cache line size */
997   32,                   /* l1 cache */
998   1024,                 /* l2 cache */
999   1,                    /* streams */
1000   0,                    /* SF->DF convert */
1001 };
1002
1003 /* Instruction costs on PPC8540 processors.  */
1004 static const
1005 struct processor_costs ppc8540_cost = {
1006   COSTS_N_INSNS (4),    /* mulsi */
1007   COSTS_N_INSNS (4),    /* mulsi_const */
1008   COSTS_N_INSNS (4),    /* mulsi_const9 */
1009   COSTS_N_INSNS (4),    /* muldi */
1010   COSTS_N_INSNS (19),   /* divsi */
1011   COSTS_N_INSNS (19),   /* divdi */
1012   COSTS_N_INSNS (4),    /* fp */
1013   COSTS_N_INSNS (4),    /* dmul */
1014   COSTS_N_INSNS (29),   /* sdiv */
1015   COSTS_N_INSNS (29),   /* ddiv */
1016   32,                   /* cache line size */
1017   32,                   /* l1 cache */
1018   256,                  /* l2 cache */
1019   1,                    /* prefetch streams /*/
1020   0,                    /* SF->DF convert */
1021 };
1022
1023 /* Instruction costs on E300C2 and E300C3 cores.  */
1024 static const
1025 struct processor_costs ppce300c2c3_cost = {
1026   COSTS_N_INSNS (4),    /* mulsi */
1027   COSTS_N_INSNS (4),    /* mulsi_const */
1028   COSTS_N_INSNS (4),    /* mulsi_const9 */
1029   COSTS_N_INSNS (4),    /* muldi */
1030   COSTS_N_INSNS (19),   /* divsi */
1031   COSTS_N_INSNS (19),   /* divdi */
1032   COSTS_N_INSNS (3),    /* fp */
1033   COSTS_N_INSNS (4),    /* dmul */
1034   COSTS_N_INSNS (18),   /* sdiv */
1035   COSTS_N_INSNS (33),   /* ddiv */
1036   32,
1037   16,                   /* l1 cache */
1038   16,                   /* l2 cache */
1039   1,                    /* prefetch streams /*/
1040   0,                    /* SF->DF convert */
1041 };
1042
1043 /* Instruction costs on PPCE500MC processors.  */
1044 static const
1045 struct processor_costs ppce500mc_cost = {
1046   COSTS_N_INSNS (4),    /* mulsi */
1047   COSTS_N_INSNS (4),    /* mulsi_const */
1048   COSTS_N_INSNS (4),    /* mulsi_const9 */
1049   COSTS_N_INSNS (4),    /* muldi */
1050   COSTS_N_INSNS (14),   /* divsi */
1051   COSTS_N_INSNS (14),   /* divdi */
1052   COSTS_N_INSNS (8),    /* fp */
1053   COSTS_N_INSNS (10),   /* dmul */
1054   COSTS_N_INSNS (36),   /* sdiv */
1055   COSTS_N_INSNS (66),   /* ddiv */
1056   64,                   /* cache line size */
1057   32,                   /* l1 cache */
1058   128,                  /* l2 cache */
1059   1,                    /* prefetch streams /*/
1060   0,                    /* SF->DF convert */
1061 };
1062
1063 /* Instruction costs on PPCE500MC64 processors.  */
1064 static const
1065 struct processor_costs ppce500mc64_cost = {
1066   COSTS_N_INSNS (4),    /* mulsi */
1067   COSTS_N_INSNS (4),    /* mulsi_const */
1068   COSTS_N_INSNS (4),    /* mulsi_const9 */
1069   COSTS_N_INSNS (4),    /* muldi */
1070   COSTS_N_INSNS (14),   /* divsi */
1071   COSTS_N_INSNS (14),   /* divdi */
1072   COSTS_N_INSNS (4),    /* fp */
1073   COSTS_N_INSNS (10),   /* dmul */
1074   COSTS_N_INSNS (36),   /* sdiv */
1075   COSTS_N_INSNS (66),   /* ddiv */
1076   64,                   /* cache line size */
1077   32,                   /* l1 cache */
1078   128,                  /* l2 cache */
1079   1,                    /* prefetch streams /*/
1080   0,                    /* SF->DF convert */
1081 };
1082
1083 /* Instruction costs on PPCE5500 processors.  */
1084 static const
1085 struct processor_costs ppce5500_cost = {
1086   COSTS_N_INSNS (5),    /* mulsi */
1087   COSTS_N_INSNS (5),    /* mulsi_const */
1088   COSTS_N_INSNS (4),    /* mulsi_const9 */
1089   COSTS_N_INSNS (5),    /* muldi */
1090   COSTS_N_INSNS (14),   /* divsi */
1091   COSTS_N_INSNS (14),   /* divdi */
1092   COSTS_N_INSNS (7),    /* fp */
1093   COSTS_N_INSNS (10),   /* dmul */
1094   COSTS_N_INSNS (36),   /* sdiv */
1095   COSTS_N_INSNS (66),   /* ddiv */
1096   64,                   /* cache line size */
1097   32,                   /* l1 cache */
1098   128,                  /* l2 cache */
1099   1,                    /* prefetch streams /*/
1100   0,                    /* SF->DF convert */
1101 };
1102
1103 /* Instruction costs on PPCE6500 processors.  */
1104 static const
1105 struct processor_costs ppce6500_cost = {
1106   COSTS_N_INSNS (5),    /* mulsi */
1107   COSTS_N_INSNS (5),    /* mulsi_const */
1108   COSTS_N_INSNS (4),    /* mulsi_const9 */
1109   COSTS_N_INSNS (5),    /* muldi */
1110   COSTS_N_INSNS (14),   /* divsi */
1111   COSTS_N_INSNS (14),   /* divdi */
1112   COSTS_N_INSNS (7),    /* fp */
1113   COSTS_N_INSNS (10),   /* dmul */
1114   COSTS_N_INSNS (36),   /* sdiv */
1115   COSTS_N_INSNS (66),   /* ddiv */
1116   64,                   /* cache line size */
1117   32,                   /* l1 cache */
1118   128,                  /* l2 cache */
1119   1,                    /* prefetch streams /*/
1120   0,                    /* SF->DF convert */
1121 };
1122
1123 /* Instruction costs on AppliedMicro Titan processors.  */
1124 static const
1125 struct processor_costs titan_cost = {
1126   COSTS_N_INSNS (5),    /* mulsi */
1127   COSTS_N_INSNS (5),    /* mulsi_const */
1128   COSTS_N_INSNS (5),    /* mulsi_const9 */
1129   COSTS_N_INSNS (5),    /* muldi */
1130   COSTS_N_INSNS (18),   /* divsi */
1131   COSTS_N_INSNS (18),   /* divdi */
1132   COSTS_N_INSNS (10),   /* fp */
1133   COSTS_N_INSNS (10),   /* dmul */
1134   COSTS_N_INSNS (46),   /* sdiv */
1135   COSTS_N_INSNS (72),   /* ddiv */
1136   32,                   /* cache line size */
1137   32,                   /* l1 cache */
1138   512,                  /* l2 cache */
1139   1,                    /* prefetch streams /*/
1140   0,                    /* SF->DF convert */
1141 };
1142
1143 /* Instruction costs on POWER4 and POWER5 processors.  */
1144 static const
1145 struct processor_costs power4_cost = {
1146   COSTS_N_INSNS (3),    /* mulsi */
1147   COSTS_N_INSNS (2),    /* mulsi_const */
1148   COSTS_N_INSNS (2),    /* mulsi_const9 */
1149   COSTS_N_INSNS (4),    /* muldi */
1150   COSTS_N_INSNS (18),   /* divsi */
1151   COSTS_N_INSNS (34),   /* divdi */
1152   COSTS_N_INSNS (3),    /* fp */
1153   COSTS_N_INSNS (3),    /* dmul */
1154   COSTS_N_INSNS (17),   /* sdiv */
1155   COSTS_N_INSNS (17),   /* ddiv */
1156   128,                  /* cache line size */
1157   32,                   /* l1 cache */
1158   1024,                 /* l2 cache */
1159   8,                    /* prefetch streams /*/
1160   0,                    /* SF->DF convert */
1161 };
1162
1163 /* Instruction costs on POWER6 processors.  */
1164 static const
1165 struct processor_costs power6_cost = {
1166   COSTS_N_INSNS (8),    /* mulsi */
1167   COSTS_N_INSNS (8),    /* mulsi_const */
1168   COSTS_N_INSNS (8),    /* mulsi_const9 */
1169   COSTS_N_INSNS (8),    /* muldi */
1170   COSTS_N_INSNS (22),   /* divsi */
1171   COSTS_N_INSNS (28),   /* divdi */
1172   COSTS_N_INSNS (3),    /* fp */
1173   COSTS_N_INSNS (3),    /* dmul */
1174   COSTS_N_INSNS (13),   /* sdiv */
1175   COSTS_N_INSNS (16),   /* ddiv */
1176   128,                  /* cache line size */
1177   64,                   /* l1 cache */
1178   2048,                 /* l2 cache */
1179   16,                   /* prefetch streams */
1180   0,                    /* SF->DF convert */
1181 };
1182
1183 /* Instruction costs on POWER7 processors.  */
1184 static const
1185 struct processor_costs power7_cost = {
1186   COSTS_N_INSNS (2),    /* mulsi */
1187   COSTS_N_INSNS (2),    /* mulsi_const */
1188   COSTS_N_INSNS (2),    /* mulsi_const9 */
1189   COSTS_N_INSNS (2),    /* muldi */
1190   COSTS_N_INSNS (18),   /* divsi */
1191   COSTS_N_INSNS (34),   /* divdi */
1192   COSTS_N_INSNS (3),    /* fp */
1193   COSTS_N_INSNS (3),    /* dmul */
1194   COSTS_N_INSNS (13),   /* sdiv */
1195   COSTS_N_INSNS (16),   /* ddiv */
1196   128,                  /* cache line size */
1197   32,                   /* l1 cache */
1198   256,                  /* l2 cache */
1199   12,                   /* prefetch streams */
1200   COSTS_N_INSNS (3),    /* SF->DF convert */
1201 };
1202
1203 /* Instruction costs on POWER8 processors.  */
1204 static const
1205 struct processor_costs power8_cost = {
1206   COSTS_N_INSNS (3),    /* mulsi */
1207   COSTS_N_INSNS (3),    /* mulsi_const */
1208   COSTS_N_INSNS (3),    /* mulsi_const9 */
1209   COSTS_N_INSNS (3),    /* muldi */
1210   COSTS_N_INSNS (19),   /* divsi */
1211   COSTS_N_INSNS (35),   /* divdi */
1212   COSTS_N_INSNS (3),    /* fp */
1213   COSTS_N_INSNS (3),    /* dmul */
1214   COSTS_N_INSNS (14),   /* sdiv */
1215   COSTS_N_INSNS (17),   /* ddiv */
1216   128,                  /* cache line size */
1217   32,                   /* l1 cache */
1218   256,                  /* l2 cache */
1219   12,                   /* prefetch streams */
1220   COSTS_N_INSNS (3),    /* SF->DF convert */
1221 };
1222
1223 /* Instruction costs on POWER9 processors.  */
1224 static const
1225 struct processor_costs power9_cost = {
1226   COSTS_N_INSNS (3),    /* mulsi */
1227   COSTS_N_INSNS (3),    /* mulsi_const */
1228   COSTS_N_INSNS (3),    /* mulsi_const9 */
1229   COSTS_N_INSNS (3),    /* muldi */
1230   COSTS_N_INSNS (8),    /* divsi */
1231   COSTS_N_INSNS (12),   /* divdi */
1232   COSTS_N_INSNS (3),    /* fp */
1233   COSTS_N_INSNS (3),    /* dmul */
1234   COSTS_N_INSNS (13),   /* sdiv */
1235   COSTS_N_INSNS (18),   /* ddiv */
1236   128,                  /* cache line size */
1237   32,                   /* l1 cache */
1238   512,                  /* l2 cache */
1239   8,                    /* prefetch streams */
1240   COSTS_N_INSNS (3),    /* SF->DF convert */
1241 };
1242
1243 /* Instruction costs on POWER A2 processors.  */
1244 static const
1245 struct processor_costs ppca2_cost = {
1246   COSTS_N_INSNS (16),    /* mulsi */
1247   COSTS_N_INSNS (16),    /* mulsi_const */
1248   COSTS_N_INSNS (16),    /* mulsi_const9 */
1249   COSTS_N_INSNS (16),   /* muldi */
1250   COSTS_N_INSNS (22),   /* divsi */
1251   COSTS_N_INSNS (28),   /* divdi */
1252   COSTS_N_INSNS (3),    /* fp */
1253   COSTS_N_INSNS (3),    /* dmul */
1254   COSTS_N_INSNS (59),   /* sdiv */
1255   COSTS_N_INSNS (72),   /* ddiv */
1256   64,
1257   16,                   /* l1 cache */
1258   2048,                 /* l2 cache */
1259   16,                   /* prefetch streams */
1260   0,                    /* SF->DF convert */
1261 };
1262
1263 \f
1264 /* Table that classifies rs6000 builtin functions (pure, const, etc.).  */
1265 #undef RS6000_BUILTIN_0
1266 #undef RS6000_BUILTIN_1
1267 #undef RS6000_BUILTIN_2
1268 #undef RS6000_BUILTIN_3
1269 #undef RS6000_BUILTIN_A
1270 #undef RS6000_BUILTIN_D
1271 #undef RS6000_BUILTIN_H
1272 #undef RS6000_BUILTIN_P
1273 #undef RS6000_BUILTIN_Q
1274 #undef RS6000_BUILTIN_X
1275
1276 #define RS6000_BUILTIN_0(ENUM, NAME, MASK, ATTR, ICODE) \
1277   { NAME, ICODE, MASK, ATTR },
1278
1279 #define RS6000_BUILTIN_1(ENUM, NAME, MASK, ATTR, ICODE) \
1280   { NAME, ICODE, MASK, ATTR },
1281
1282 #define RS6000_BUILTIN_2(ENUM, NAME, MASK, ATTR, ICODE)  \
1283   { NAME, ICODE, MASK, ATTR },
1284
1285 #define RS6000_BUILTIN_3(ENUM, NAME, MASK, ATTR, ICODE)  \
1286   { NAME, ICODE, MASK, ATTR },
1287
1288 #define RS6000_BUILTIN_A(ENUM, NAME, MASK, ATTR, ICODE)  \
1289   { NAME, ICODE, MASK, ATTR },
1290
1291 #define RS6000_BUILTIN_D(ENUM, NAME, MASK, ATTR, ICODE)  \
1292   { NAME, ICODE, MASK, ATTR },
1293
1294 #define RS6000_BUILTIN_H(ENUM, NAME, MASK, ATTR, ICODE)  \
1295   { NAME, ICODE, MASK, ATTR },
1296
1297 #define RS6000_BUILTIN_P(ENUM, NAME, MASK, ATTR, ICODE)  \
1298   { NAME, ICODE, MASK, ATTR },
1299
1300 #define RS6000_BUILTIN_Q(ENUM, NAME, MASK, ATTR, ICODE)  \
1301   { NAME, ICODE, MASK, ATTR },
1302
1303 #define RS6000_BUILTIN_X(ENUM, NAME, MASK, ATTR, ICODE)  \
1304   { NAME, ICODE, MASK, ATTR },
1305
1306 struct rs6000_builtin_info_type {
1307   const char *name;
1308   const enum insn_code icode;
1309   const HOST_WIDE_INT mask;
1310   const unsigned attr;
1311 };
1312
1313 static const struct rs6000_builtin_info_type rs6000_builtin_info[] =
1314 {
1315 #include "rs6000-builtin.def"
1316 };
1317
1318 #undef RS6000_BUILTIN_0
1319 #undef RS6000_BUILTIN_1
1320 #undef RS6000_BUILTIN_2
1321 #undef RS6000_BUILTIN_3
1322 #undef RS6000_BUILTIN_A
1323 #undef RS6000_BUILTIN_D
1324 #undef RS6000_BUILTIN_H
1325 #undef RS6000_BUILTIN_P
1326 #undef RS6000_BUILTIN_Q
1327 #undef RS6000_BUILTIN_X
1328
1329 /* Support for -mveclibabi=<xxx> to control which vector library to use.  */
1330 static tree (*rs6000_veclib_handler) (combined_fn, tree, tree);
1331
1332 \f
1333 static bool rs6000_debug_legitimate_address_p (machine_mode, rtx, bool);
1334 static struct machine_function * rs6000_init_machine_status (void);
1335 static int rs6000_ra_ever_killed (void);
1336 static tree rs6000_handle_longcall_attribute (tree *, tree, tree, int, bool *);
1337 static tree rs6000_handle_altivec_attribute (tree *, tree, tree, int, bool *);
1338 static tree rs6000_handle_struct_attribute (tree *, tree, tree, int, bool *);
1339 static tree rs6000_builtin_vectorized_libmass (combined_fn, tree, tree);
1340 static void rs6000_emit_set_long_const (rtx, HOST_WIDE_INT);
1341 static int rs6000_memory_move_cost (machine_mode, reg_class_t, bool);
1342 static bool rs6000_debug_rtx_costs (rtx, machine_mode, int, int, int *, bool);
1343 static int rs6000_debug_address_cost (rtx, machine_mode, addr_space_t,
1344                                       bool);
1345 static int rs6000_debug_adjust_cost (rtx_insn *, int, rtx_insn *, int,
1346                                      unsigned int);
1347 static bool is_microcoded_insn (rtx_insn *);
1348 static bool is_nonpipeline_insn (rtx_insn *);
1349 static bool is_cracked_insn (rtx_insn *);
1350 static bool is_load_insn (rtx, rtx *);
1351 static bool is_store_insn (rtx, rtx *);
1352 static bool set_to_load_agen (rtx_insn *,rtx_insn *);
1353 static bool insn_terminates_group_p (rtx_insn *, enum group_termination);
1354 static bool insn_must_be_first_in_group (rtx_insn *);
1355 static bool insn_must_be_last_in_group (rtx_insn *);
1356 static void altivec_init_builtins (void);
1357 static tree builtin_function_type (machine_mode, machine_mode,
1358                                    machine_mode, machine_mode,
1359                                    enum rs6000_builtins, const char *name);
1360 static void rs6000_common_init_builtins (void);
1361 static void paired_init_builtins (void);
1362 static rtx paired_expand_predicate_builtin (enum insn_code, tree, rtx);
1363 static void htm_init_builtins (void);
1364 static rs6000_stack_t *rs6000_stack_info (void);
1365 static void is_altivec_return_reg (rtx, void *);
1366 int easy_vector_constant (rtx, machine_mode);
1367 static rtx rs6000_debug_legitimize_address (rtx, rtx, machine_mode);
1368 static rtx rs6000_legitimize_tls_address (rtx, enum tls_model);
1369 static rtx rs6000_darwin64_record_arg (CUMULATIVE_ARGS *, const_tree,
1370                                        bool, bool);
1371 #if TARGET_MACHO
1372 static void macho_branch_islands (void);
1373 #endif
1374 static rtx rs6000_legitimize_reload_address (rtx, machine_mode, int, int,
1375                                              int, int *);
1376 static rtx rs6000_debug_legitimize_reload_address (rtx, machine_mode, int,
1377                                                    int, int, int *);
1378 static bool rs6000_mode_dependent_address (const_rtx);
1379 static bool rs6000_debug_mode_dependent_address (const_rtx);
1380 static enum reg_class rs6000_secondary_reload_class (enum reg_class,
1381                                                      machine_mode, rtx);
1382 static enum reg_class rs6000_debug_secondary_reload_class (enum reg_class,
1383                                                            machine_mode,
1384                                                            rtx);
1385 static enum reg_class rs6000_preferred_reload_class (rtx, enum reg_class);
1386 static enum reg_class rs6000_debug_preferred_reload_class (rtx,
1387                                                            enum reg_class);
1388 static bool rs6000_debug_secondary_memory_needed (machine_mode,
1389                                                   reg_class_t,
1390                                                   reg_class_t);
1391 static bool rs6000_debug_can_change_mode_class (machine_mode,
1392                                                 machine_mode,
1393                                                 reg_class_t);
1394 static bool rs6000_save_toc_in_prologue_p (void);
1395 static rtx rs6000_internal_arg_pointer (void);
1396
1397 rtx (*rs6000_legitimize_reload_address_ptr) (rtx, machine_mode, int, int,
1398                                              int, int *)
1399   = rs6000_legitimize_reload_address;
1400
1401 static bool (*rs6000_mode_dependent_address_ptr) (const_rtx)
1402   = rs6000_mode_dependent_address;
1403
1404 enum reg_class (*rs6000_secondary_reload_class_ptr) (enum reg_class,
1405                                                      machine_mode, rtx)
1406   = rs6000_secondary_reload_class;
1407
1408 enum reg_class (*rs6000_preferred_reload_class_ptr) (rtx, enum reg_class)
1409   = rs6000_preferred_reload_class;
1410
1411 const int INSN_NOT_AVAILABLE = -1;
1412
1413 static void rs6000_print_isa_options (FILE *, int, const char *,
1414                                       HOST_WIDE_INT);
1415 static void rs6000_print_builtin_options (FILE *, int, const char *,
1416                                           HOST_WIDE_INT);
1417 static HOST_WIDE_INT rs6000_disable_incompatible_switches (void);
1418
1419 static enum rs6000_reg_type register_to_reg_type (rtx, bool *);
1420 static bool rs6000_secondary_reload_move (enum rs6000_reg_type,
1421                                           enum rs6000_reg_type,
1422                                           machine_mode,
1423                                           secondary_reload_info *,
1424                                           bool);
1425 rtl_opt_pass *make_pass_analyze_swaps (gcc::context*);
1426 static bool rs6000_keep_leaf_when_profiled () __attribute__ ((unused));
1427 static tree rs6000_fold_builtin (tree, int, tree *, bool);
1428
1429 /* Hash table stuff for keeping track of TOC entries.  */
1430
1431 struct GTY((for_user)) toc_hash_struct
1432 {
1433   /* `key' will satisfy CONSTANT_P; in fact, it will satisfy
1434      ASM_OUTPUT_SPECIAL_POOL_ENTRY_P.  */
1435   rtx key;
1436   machine_mode key_mode;
1437   int labelno;
1438 };
1439
1440 struct toc_hasher : ggc_ptr_hash<toc_hash_struct>
1441 {
1442   static hashval_t hash (toc_hash_struct *);
1443   static bool equal (toc_hash_struct *, toc_hash_struct *);
1444 };
1445
1446 static GTY (()) hash_table<toc_hasher> *toc_hash_table;
1447
1448 /* Hash table to keep track of the argument types for builtin functions.  */
1449
1450 struct GTY((for_user)) builtin_hash_struct
1451 {
1452   tree type;
1453   machine_mode mode[4]; /* return value + 3 arguments.  */
1454   unsigned char uns_p[4];       /* and whether the types are unsigned.  */
1455 };
1456
1457 struct builtin_hasher : ggc_ptr_hash<builtin_hash_struct>
1458 {
1459   static hashval_t hash (builtin_hash_struct *);
1460   static bool equal (builtin_hash_struct *, builtin_hash_struct *);
1461 };
1462
1463 static GTY (()) hash_table<builtin_hasher> *builtin_hash_table;
1464
1465 \f
1466 /* Default register names.  */
1467 char rs6000_reg_names[][8] =
1468 {
1469       "0",  "1",  "2",  "3",  "4",  "5",  "6",  "7",
1470       "8",  "9", "10", "11", "12", "13", "14", "15",
1471      "16", "17", "18", "19", "20", "21", "22", "23",
1472      "24", "25", "26", "27", "28", "29", "30", "31",
1473       "0",  "1",  "2",  "3",  "4",  "5",  "6",  "7",
1474       "8",  "9", "10", "11", "12", "13", "14", "15",
1475      "16", "17", "18", "19", "20", "21", "22", "23",
1476      "24", "25", "26", "27", "28", "29", "30", "31",
1477      "mq", "lr", "ctr","ap",
1478       "0",  "1",  "2",  "3",  "4",  "5",  "6",  "7",
1479       "ca",
1480       /* AltiVec registers.  */
1481       "0",  "1",  "2",  "3",  "4",  "5",  "6", "7",
1482       "8",  "9",  "10", "11", "12", "13", "14", "15",
1483       "16", "17", "18", "19", "20", "21", "22", "23",
1484       "24", "25", "26", "27", "28", "29", "30", "31",
1485       "vrsave", "vscr",
1486       /* Soft frame pointer.  */
1487       "sfp",
1488       /* HTM SPR registers.  */
1489       "tfhar", "tfiar", "texasr"
1490 };
1491
1492 #ifdef TARGET_REGNAMES
1493 static const char alt_reg_names[][8] =
1494 {
1495    "%r0",   "%r1",  "%r2",  "%r3",  "%r4",  "%r5",  "%r6",  "%r7",
1496    "%r8",   "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15",
1497   "%r16",  "%r17", "%r18", "%r19", "%r20", "%r21", "%r22", "%r23",
1498   "%r24",  "%r25", "%r26", "%r27", "%r28", "%r29", "%r30", "%r31",
1499    "%f0",   "%f1",  "%f2",  "%f3",  "%f4",  "%f5",  "%f6",  "%f7",
1500    "%f8",   "%f9", "%f10", "%f11", "%f12", "%f13", "%f14", "%f15",
1501   "%f16",  "%f17", "%f18", "%f19", "%f20", "%f21", "%f22", "%f23",
1502   "%f24",  "%f25", "%f26", "%f27", "%f28", "%f29", "%f30", "%f31",
1503     "mq",    "lr",  "ctr",   "ap",
1504   "%cr0",  "%cr1", "%cr2", "%cr3", "%cr4", "%cr5", "%cr6", "%cr7",
1505    "ca",
1506   /* AltiVec registers.  */
1507    "%v0",  "%v1",  "%v2",  "%v3",  "%v4",  "%v5",  "%v6", "%v7",
1508    "%v8",  "%v9", "%v10", "%v11", "%v12", "%v13", "%v14", "%v15",
1509   "%v16", "%v17", "%v18", "%v19", "%v20", "%v21", "%v22", "%v23",
1510   "%v24", "%v25", "%v26", "%v27", "%v28", "%v29", "%v30", "%v31",
1511   "vrsave", "vscr",
1512   /* Soft frame pointer.  */
1513   "sfp",
1514   /* HTM SPR registers.  */
1515   "tfhar", "tfiar", "texasr"
1516 };
1517 #endif
1518
1519 /* Table of valid machine attributes.  */
1520
1521 static const struct attribute_spec rs6000_attribute_table[] =
1522 {
1523   /* { name, min_len, max_len, decl_req, type_req, fn_type_req,
1524        affects_type_identity, handler, exclude } */
1525   { "altivec",   1, 1, false, true,  false, false,
1526     rs6000_handle_altivec_attribute, NULL },
1527   { "longcall",  0, 0, false, true,  true,  false,
1528     rs6000_handle_longcall_attribute, NULL },
1529   { "shortcall", 0, 0, false, true,  true,  false,
1530     rs6000_handle_longcall_attribute, NULL },
1531   { "ms_struct", 0, 0, false, false, false, false,
1532     rs6000_handle_struct_attribute, NULL },
1533   { "gcc_struct", 0, 0, false, false, false, false,
1534     rs6000_handle_struct_attribute, NULL },
1535 #ifdef SUBTARGET_ATTRIBUTE_TABLE
1536   SUBTARGET_ATTRIBUTE_TABLE,
1537 #endif
1538   { NULL,        0, 0, false, false, false, false, NULL, NULL }
1539 };
1540 \f
1541 #ifndef TARGET_PROFILE_KERNEL
1542 #define TARGET_PROFILE_KERNEL 0
1543 #endif
1544
1545 /* The VRSAVE bitmask puts bit %v0 as the most significant bit.  */
1546 #define ALTIVEC_REG_BIT(REGNO) (0x80000000 >> ((REGNO) - FIRST_ALTIVEC_REGNO))
1547 \f
1548 /* Initialize the GCC target structure.  */
1549 #undef TARGET_ATTRIBUTE_TABLE
1550 #define TARGET_ATTRIBUTE_TABLE rs6000_attribute_table
1551 #undef TARGET_SET_DEFAULT_TYPE_ATTRIBUTES
1552 #define TARGET_SET_DEFAULT_TYPE_ATTRIBUTES rs6000_set_default_type_attributes
1553 #undef TARGET_ATTRIBUTE_TAKES_IDENTIFIER_P
1554 #define TARGET_ATTRIBUTE_TAKES_IDENTIFIER_P rs6000_attribute_takes_identifier_p
1555
1556 #undef TARGET_ASM_ALIGNED_DI_OP
1557 #define TARGET_ASM_ALIGNED_DI_OP DOUBLE_INT_ASM_OP
1558
1559 /* Default unaligned ops are only provided for ELF.  Find the ops needed
1560    for non-ELF systems.  */
1561 #ifndef OBJECT_FORMAT_ELF
1562 #if TARGET_XCOFF
1563 /* For XCOFF.  rs6000_assemble_integer will handle unaligned DIs on
1564    64-bit targets.  */
1565 #undef TARGET_ASM_UNALIGNED_HI_OP
1566 #define TARGET_ASM_UNALIGNED_HI_OP "\t.vbyte\t2,"
1567 #undef TARGET_ASM_UNALIGNED_SI_OP
1568 #define TARGET_ASM_UNALIGNED_SI_OP "\t.vbyte\t4,"
1569 #undef TARGET_ASM_UNALIGNED_DI_OP
1570 #define TARGET_ASM_UNALIGNED_DI_OP "\t.vbyte\t8,"
1571 #else
1572 /* For Darwin.  */
1573 #undef TARGET_ASM_UNALIGNED_HI_OP
1574 #define TARGET_ASM_UNALIGNED_HI_OP "\t.short\t"
1575 #undef TARGET_ASM_UNALIGNED_SI_OP
1576 #define TARGET_ASM_UNALIGNED_SI_OP "\t.long\t"
1577 #undef TARGET_ASM_UNALIGNED_DI_OP
1578 #define TARGET_ASM_UNALIGNED_DI_OP "\t.quad\t"
1579 #undef TARGET_ASM_ALIGNED_DI_OP
1580 #define TARGET_ASM_ALIGNED_DI_OP "\t.quad\t"
1581 #endif
1582 #endif
1583
1584 /* This hook deals with fixups for relocatable code and DI-mode objects
1585    in 64-bit code.  */
1586 #undef TARGET_ASM_INTEGER
1587 #define TARGET_ASM_INTEGER rs6000_assemble_integer
1588
1589 #if defined (HAVE_GAS_HIDDEN) && !TARGET_MACHO
1590 #undef TARGET_ASM_ASSEMBLE_VISIBILITY
1591 #define TARGET_ASM_ASSEMBLE_VISIBILITY rs6000_assemble_visibility
1592 #endif
1593
1594 #undef TARGET_SET_UP_BY_PROLOGUE
1595 #define TARGET_SET_UP_BY_PROLOGUE rs6000_set_up_by_prologue
1596
1597 #undef TARGET_SHRINK_WRAP_GET_SEPARATE_COMPONENTS
1598 #define TARGET_SHRINK_WRAP_GET_SEPARATE_COMPONENTS rs6000_get_separate_components
1599 #undef TARGET_SHRINK_WRAP_COMPONENTS_FOR_BB
1600 #define TARGET_SHRINK_WRAP_COMPONENTS_FOR_BB rs6000_components_for_bb
1601 #undef TARGET_SHRINK_WRAP_DISQUALIFY_COMPONENTS
1602 #define TARGET_SHRINK_WRAP_DISQUALIFY_COMPONENTS rs6000_disqualify_components
1603 #undef TARGET_SHRINK_WRAP_EMIT_PROLOGUE_COMPONENTS
1604 #define TARGET_SHRINK_WRAP_EMIT_PROLOGUE_COMPONENTS rs6000_emit_prologue_components
1605 #undef TARGET_SHRINK_WRAP_EMIT_EPILOGUE_COMPONENTS
1606 #define TARGET_SHRINK_WRAP_EMIT_EPILOGUE_COMPONENTS rs6000_emit_epilogue_components
1607 #undef TARGET_SHRINK_WRAP_SET_HANDLED_COMPONENTS
1608 #define TARGET_SHRINK_WRAP_SET_HANDLED_COMPONENTS rs6000_set_handled_components
1609
1610 #undef TARGET_EXTRA_LIVE_ON_ENTRY
1611 #define TARGET_EXTRA_LIVE_ON_ENTRY rs6000_live_on_entry
1612
1613 #undef TARGET_INTERNAL_ARG_POINTER
1614 #define TARGET_INTERNAL_ARG_POINTER rs6000_internal_arg_pointer
1615
1616 #undef TARGET_HAVE_TLS
1617 #define TARGET_HAVE_TLS HAVE_AS_TLS
1618
1619 #undef TARGET_CANNOT_FORCE_CONST_MEM
1620 #define TARGET_CANNOT_FORCE_CONST_MEM rs6000_cannot_force_const_mem
1621
1622 #undef TARGET_DELEGITIMIZE_ADDRESS
1623 #define TARGET_DELEGITIMIZE_ADDRESS rs6000_delegitimize_address
1624
1625 #undef TARGET_CONST_NOT_OK_FOR_DEBUG_P
1626 #define TARGET_CONST_NOT_OK_FOR_DEBUG_P rs6000_const_not_ok_for_debug_p
1627
1628 #undef TARGET_LEGITIMATE_COMBINED_INSN
1629 #define TARGET_LEGITIMATE_COMBINED_INSN rs6000_legitimate_combined_insn
1630
1631 #undef TARGET_ASM_FUNCTION_PROLOGUE
1632 #define TARGET_ASM_FUNCTION_PROLOGUE rs6000_output_function_prologue
1633 #undef TARGET_ASM_FUNCTION_EPILOGUE
1634 #define TARGET_ASM_FUNCTION_EPILOGUE rs6000_output_function_epilogue
1635
1636 #undef TARGET_ASM_OUTPUT_ADDR_CONST_EXTRA
1637 #define TARGET_ASM_OUTPUT_ADDR_CONST_EXTRA rs6000_output_addr_const_extra
1638
1639 #undef TARGET_LEGITIMIZE_ADDRESS
1640 #define TARGET_LEGITIMIZE_ADDRESS rs6000_legitimize_address
1641
1642 #undef  TARGET_SCHED_VARIABLE_ISSUE
1643 #define TARGET_SCHED_VARIABLE_ISSUE rs6000_variable_issue
1644
1645 #undef TARGET_SCHED_ISSUE_RATE
1646 #define TARGET_SCHED_ISSUE_RATE rs6000_issue_rate
1647 #undef TARGET_SCHED_ADJUST_COST
1648 #define TARGET_SCHED_ADJUST_COST rs6000_adjust_cost
1649 #undef TARGET_SCHED_ADJUST_PRIORITY
1650 #define TARGET_SCHED_ADJUST_PRIORITY rs6000_adjust_priority
1651 #undef TARGET_SCHED_IS_COSTLY_DEPENDENCE
1652 #define TARGET_SCHED_IS_COSTLY_DEPENDENCE rs6000_is_costly_dependence
1653 #undef TARGET_SCHED_INIT
1654 #define TARGET_SCHED_INIT rs6000_sched_init
1655 #undef TARGET_SCHED_FINISH
1656 #define TARGET_SCHED_FINISH rs6000_sched_finish
1657 #undef TARGET_SCHED_REORDER
1658 #define TARGET_SCHED_REORDER rs6000_sched_reorder
1659 #undef TARGET_SCHED_REORDER2
1660 #define TARGET_SCHED_REORDER2 rs6000_sched_reorder2
1661
1662 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD
1663 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD rs6000_use_sched_lookahead
1664
1665 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD
1666 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD rs6000_use_sched_lookahead_guard
1667
1668 #undef TARGET_SCHED_ALLOC_SCHED_CONTEXT
1669 #define TARGET_SCHED_ALLOC_SCHED_CONTEXT rs6000_alloc_sched_context
1670 #undef TARGET_SCHED_INIT_SCHED_CONTEXT
1671 #define TARGET_SCHED_INIT_SCHED_CONTEXT rs6000_init_sched_context
1672 #undef TARGET_SCHED_SET_SCHED_CONTEXT
1673 #define TARGET_SCHED_SET_SCHED_CONTEXT rs6000_set_sched_context
1674 #undef TARGET_SCHED_FREE_SCHED_CONTEXT
1675 #define TARGET_SCHED_FREE_SCHED_CONTEXT rs6000_free_sched_context
1676
1677 #undef TARGET_SCHED_CAN_SPECULATE_INSN
1678 #define TARGET_SCHED_CAN_SPECULATE_INSN rs6000_sched_can_speculate_insn
1679
1680 #undef TARGET_VECTORIZE_BUILTIN_MASK_FOR_LOAD
1681 #define TARGET_VECTORIZE_BUILTIN_MASK_FOR_LOAD rs6000_builtin_mask_for_load
1682 #undef TARGET_VECTORIZE_SUPPORT_VECTOR_MISALIGNMENT
1683 #define TARGET_VECTORIZE_SUPPORT_VECTOR_MISALIGNMENT            \
1684   rs6000_builtin_support_vector_misalignment
1685 #undef TARGET_VECTORIZE_VECTOR_ALIGNMENT_REACHABLE
1686 #define TARGET_VECTORIZE_VECTOR_ALIGNMENT_REACHABLE rs6000_vector_alignment_reachable
1687 #undef TARGET_VECTORIZE_BUILTIN_VECTORIZATION_COST
1688 #define TARGET_VECTORIZE_BUILTIN_VECTORIZATION_COST \
1689   rs6000_builtin_vectorization_cost
1690 #undef TARGET_VECTORIZE_PREFERRED_SIMD_MODE
1691 #define TARGET_VECTORIZE_PREFERRED_SIMD_MODE \
1692   rs6000_preferred_simd_mode
1693 #undef TARGET_VECTORIZE_INIT_COST
1694 #define TARGET_VECTORIZE_INIT_COST rs6000_init_cost
1695 #undef TARGET_VECTORIZE_ADD_STMT_COST
1696 #define TARGET_VECTORIZE_ADD_STMT_COST rs6000_add_stmt_cost
1697 #undef TARGET_VECTORIZE_FINISH_COST
1698 #define TARGET_VECTORIZE_FINISH_COST rs6000_finish_cost
1699 #undef TARGET_VECTORIZE_DESTROY_COST_DATA
1700 #define TARGET_VECTORIZE_DESTROY_COST_DATA rs6000_destroy_cost_data
1701
1702 #undef TARGET_INIT_BUILTINS
1703 #define TARGET_INIT_BUILTINS rs6000_init_builtins
1704 #undef TARGET_BUILTIN_DECL
1705 #define TARGET_BUILTIN_DECL rs6000_builtin_decl
1706
1707 #undef TARGET_FOLD_BUILTIN
1708 #define TARGET_FOLD_BUILTIN rs6000_fold_builtin
1709 #undef TARGET_GIMPLE_FOLD_BUILTIN
1710 #define TARGET_GIMPLE_FOLD_BUILTIN rs6000_gimple_fold_builtin
1711
1712 #undef TARGET_EXPAND_BUILTIN
1713 #define TARGET_EXPAND_BUILTIN rs6000_expand_builtin
1714
1715 #undef TARGET_MANGLE_TYPE
1716 #define TARGET_MANGLE_TYPE rs6000_mangle_type
1717
1718 #undef TARGET_INIT_LIBFUNCS
1719 #define TARGET_INIT_LIBFUNCS rs6000_init_libfuncs
1720
1721 #if TARGET_MACHO
1722 #undef TARGET_BINDS_LOCAL_P
1723 #define TARGET_BINDS_LOCAL_P darwin_binds_local_p
1724 #endif
1725
1726 #undef TARGET_MS_BITFIELD_LAYOUT_P
1727 #define TARGET_MS_BITFIELD_LAYOUT_P rs6000_ms_bitfield_layout_p
1728
1729 #undef TARGET_ASM_OUTPUT_MI_THUNK
1730 #define TARGET_ASM_OUTPUT_MI_THUNK rs6000_output_mi_thunk
1731
1732 #undef TARGET_ASM_CAN_OUTPUT_MI_THUNK
1733 #define TARGET_ASM_CAN_OUTPUT_MI_THUNK hook_bool_const_tree_hwi_hwi_const_tree_true
1734
1735 #undef TARGET_FUNCTION_OK_FOR_SIBCALL
1736 #define TARGET_FUNCTION_OK_FOR_SIBCALL rs6000_function_ok_for_sibcall
1737
1738 #undef TARGET_REGISTER_MOVE_COST
1739 #define TARGET_REGISTER_MOVE_COST rs6000_register_move_cost
1740 #undef TARGET_MEMORY_MOVE_COST
1741 #define TARGET_MEMORY_MOVE_COST rs6000_memory_move_cost
1742 #undef TARGET_CANNOT_COPY_INSN_P
1743 #define TARGET_CANNOT_COPY_INSN_P rs6000_cannot_copy_insn_p
1744 #undef TARGET_RTX_COSTS
1745 #define TARGET_RTX_COSTS rs6000_rtx_costs
1746 #undef TARGET_ADDRESS_COST
1747 #define TARGET_ADDRESS_COST hook_int_rtx_mode_as_bool_0
1748 #undef TARGET_INSN_COST
1749 #define TARGET_INSN_COST rs6000_insn_cost
1750
1751 #undef TARGET_INIT_DWARF_REG_SIZES_EXTRA
1752 #define TARGET_INIT_DWARF_REG_SIZES_EXTRA rs6000_init_dwarf_reg_sizes_extra
1753
1754 #undef TARGET_PROMOTE_FUNCTION_MODE
1755 #define TARGET_PROMOTE_FUNCTION_MODE rs6000_promote_function_mode
1756
1757 #undef TARGET_RETURN_IN_MEMORY
1758 #define TARGET_RETURN_IN_MEMORY rs6000_return_in_memory
1759
1760 #undef TARGET_RETURN_IN_MSB
1761 #define TARGET_RETURN_IN_MSB rs6000_return_in_msb
1762
1763 #undef TARGET_SETUP_INCOMING_VARARGS
1764 #define TARGET_SETUP_INCOMING_VARARGS setup_incoming_varargs
1765
1766 /* Always strict argument naming on rs6000.  */
1767 #undef TARGET_STRICT_ARGUMENT_NAMING
1768 #define TARGET_STRICT_ARGUMENT_NAMING hook_bool_CUMULATIVE_ARGS_true
1769 #undef TARGET_PRETEND_OUTGOING_VARARGS_NAMED
1770 #define TARGET_PRETEND_OUTGOING_VARARGS_NAMED hook_bool_CUMULATIVE_ARGS_true
1771 #undef TARGET_SPLIT_COMPLEX_ARG
1772 #define TARGET_SPLIT_COMPLEX_ARG hook_bool_const_tree_true
1773 #undef TARGET_MUST_PASS_IN_STACK
1774 #define TARGET_MUST_PASS_IN_STACK rs6000_must_pass_in_stack
1775 #undef TARGET_PASS_BY_REFERENCE
1776 #define TARGET_PASS_BY_REFERENCE rs6000_pass_by_reference
1777 #undef TARGET_ARG_PARTIAL_BYTES
1778 #define TARGET_ARG_PARTIAL_BYTES rs6000_arg_partial_bytes
1779 #undef TARGET_FUNCTION_ARG_ADVANCE
1780 #define TARGET_FUNCTION_ARG_ADVANCE rs6000_function_arg_advance
1781 #undef TARGET_FUNCTION_ARG
1782 #define TARGET_FUNCTION_ARG rs6000_function_arg
1783 #undef TARGET_FUNCTION_ARG_PADDING
1784 #define TARGET_FUNCTION_ARG_PADDING rs6000_function_arg_padding
1785 #undef TARGET_FUNCTION_ARG_BOUNDARY
1786 #define TARGET_FUNCTION_ARG_BOUNDARY rs6000_function_arg_boundary
1787
1788 #undef TARGET_BUILD_BUILTIN_VA_LIST
1789 #define TARGET_BUILD_BUILTIN_VA_LIST rs6000_build_builtin_va_list
1790
1791 #undef TARGET_EXPAND_BUILTIN_VA_START
1792 #define TARGET_EXPAND_BUILTIN_VA_START rs6000_va_start
1793
1794 #undef TARGET_GIMPLIFY_VA_ARG_EXPR
1795 #define TARGET_GIMPLIFY_VA_ARG_EXPR rs6000_gimplify_va_arg
1796
1797 #undef TARGET_EH_RETURN_FILTER_MODE
1798 #define TARGET_EH_RETURN_FILTER_MODE rs6000_eh_return_filter_mode
1799
1800 #undef TARGET_SCALAR_MODE_SUPPORTED_P
1801 #define TARGET_SCALAR_MODE_SUPPORTED_P rs6000_scalar_mode_supported_p
1802
1803 #undef TARGET_VECTOR_MODE_SUPPORTED_P
1804 #define TARGET_VECTOR_MODE_SUPPORTED_P rs6000_vector_mode_supported_p
1805
1806 #undef TARGET_FLOATN_MODE
1807 #define TARGET_FLOATN_MODE rs6000_floatn_mode
1808
1809 #undef TARGET_INVALID_ARG_FOR_UNPROTOTYPED_FN
1810 #define TARGET_INVALID_ARG_FOR_UNPROTOTYPED_FN invalid_arg_for_unprototyped_fn
1811
1812 #undef TARGET_ASM_LOOP_ALIGN_MAX_SKIP
1813 #define TARGET_ASM_LOOP_ALIGN_MAX_SKIP rs6000_loop_align_max_skip
1814
1815 #undef TARGET_MD_ASM_ADJUST
1816 #define TARGET_MD_ASM_ADJUST rs6000_md_asm_adjust
1817
1818 #undef TARGET_OPTION_OVERRIDE
1819 #define TARGET_OPTION_OVERRIDE rs6000_option_override
1820
1821 #undef TARGET_VECTORIZE_BUILTIN_VECTORIZED_FUNCTION
1822 #define TARGET_VECTORIZE_BUILTIN_VECTORIZED_FUNCTION \
1823   rs6000_builtin_vectorized_function
1824
1825 #undef TARGET_VECTORIZE_BUILTIN_MD_VECTORIZED_FUNCTION
1826 #define TARGET_VECTORIZE_BUILTIN_MD_VECTORIZED_FUNCTION \
1827   rs6000_builtin_md_vectorized_function
1828
1829 #undef TARGET_STACK_PROTECT_GUARD
1830 #define TARGET_STACK_PROTECT_GUARD rs6000_init_stack_protect_guard
1831
1832 #if !TARGET_MACHO
1833 #undef TARGET_STACK_PROTECT_FAIL
1834 #define TARGET_STACK_PROTECT_FAIL rs6000_stack_protect_fail
1835 #endif
1836
1837 #ifdef HAVE_AS_TLS
1838 #undef TARGET_ASM_OUTPUT_DWARF_DTPREL
1839 #define TARGET_ASM_OUTPUT_DWARF_DTPREL rs6000_output_dwarf_dtprel
1840 #endif
1841
1842 /* Use a 32-bit anchor range.  This leads to sequences like:
1843
1844         addis   tmp,anchor,high
1845         add     dest,tmp,low
1846
1847    where tmp itself acts as an anchor, and can be shared between
1848    accesses to the same 64k page.  */
1849 #undef TARGET_MIN_ANCHOR_OFFSET
1850 #define TARGET_MIN_ANCHOR_OFFSET -0x7fffffff - 1
1851 #undef TARGET_MAX_ANCHOR_OFFSET
1852 #define TARGET_MAX_ANCHOR_OFFSET 0x7fffffff
1853 #undef TARGET_USE_BLOCKS_FOR_CONSTANT_P
1854 #define TARGET_USE_BLOCKS_FOR_CONSTANT_P rs6000_use_blocks_for_constant_p
1855 #undef TARGET_USE_BLOCKS_FOR_DECL_P
1856 #define TARGET_USE_BLOCKS_FOR_DECL_P rs6000_use_blocks_for_decl_p
1857
1858 #undef TARGET_BUILTIN_RECIPROCAL
1859 #define TARGET_BUILTIN_RECIPROCAL rs6000_builtin_reciprocal
1860
1861 #undef TARGET_SECONDARY_RELOAD
1862 #define TARGET_SECONDARY_RELOAD rs6000_secondary_reload
1863 #undef TARGET_SECONDARY_MEMORY_NEEDED
1864 #define TARGET_SECONDARY_MEMORY_NEEDED rs6000_secondary_memory_needed
1865 #undef TARGET_SECONDARY_MEMORY_NEEDED_MODE
1866 #define TARGET_SECONDARY_MEMORY_NEEDED_MODE rs6000_secondary_memory_needed_mode
1867
1868 #undef TARGET_LEGITIMATE_ADDRESS_P
1869 #define TARGET_LEGITIMATE_ADDRESS_P rs6000_legitimate_address_p
1870
1871 #undef TARGET_MODE_DEPENDENT_ADDRESS_P
1872 #define TARGET_MODE_DEPENDENT_ADDRESS_P rs6000_mode_dependent_address_p
1873
1874 #undef TARGET_COMPUTE_PRESSURE_CLASSES
1875 #define TARGET_COMPUTE_PRESSURE_CLASSES rs6000_compute_pressure_classes
1876
1877 #undef TARGET_CAN_ELIMINATE
1878 #define TARGET_CAN_ELIMINATE rs6000_can_eliminate
1879
1880 #undef TARGET_CONDITIONAL_REGISTER_USAGE
1881 #define TARGET_CONDITIONAL_REGISTER_USAGE rs6000_conditional_register_usage
1882
1883 #undef TARGET_SCHED_REASSOCIATION_WIDTH
1884 #define TARGET_SCHED_REASSOCIATION_WIDTH rs6000_reassociation_width
1885
1886 #undef TARGET_TRAMPOLINE_INIT
1887 #define TARGET_TRAMPOLINE_INIT rs6000_trampoline_init
1888
1889 #undef TARGET_FUNCTION_VALUE
1890 #define TARGET_FUNCTION_VALUE rs6000_function_value
1891
1892 #undef TARGET_OPTION_VALID_ATTRIBUTE_P
1893 #define TARGET_OPTION_VALID_ATTRIBUTE_P rs6000_valid_attribute_p
1894
1895 #undef TARGET_OPTION_SAVE
1896 #define TARGET_OPTION_SAVE rs6000_function_specific_save
1897
1898 #undef TARGET_OPTION_RESTORE
1899 #define TARGET_OPTION_RESTORE rs6000_function_specific_restore
1900
1901 #undef TARGET_OPTION_PRINT
1902 #define TARGET_OPTION_PRINT rs6000_function_specific_print
1903
1904 #undef TARGET_CAN_INLINE_P
1905 #define TARGET_CAN_INLINE_P rs6000_can_inline_p
1906
1907 #undef TARGET_SET_CURRENT_FUNCTION
1908 #define TARGET_SET_CURRENT_FUNCTION rs6000_set_current_function
1909
1910 #undef TARGET_LEGITIMATE_CONSTANT_P
1911 #define TARGET_LEGITIMATE_CONSTANT_P rs6000_legitimate_constant_p
1912
1913 #undef TARGET_VECTORIZE_VEC_PERM_CONST
1914 #define TARGET_VECTORIZE_VEC_PERM_CONST rs6000_vectorize_vec_perm_const
1915
1916 #undef TARGET_CAN_USE_DOLOOP_P
1917 #define TARGET_CAN_USE_DOLOOP_P can_use_doloop_if_innermost
1918
1919 #undef TARGET_ATOMIC_ASSIGN_EXPAND_FENV
1920 #define TARGET_ATOMIC_ASSIGN_EXPAND_FENV rs6000_atomic_assign_expand_fenv
1921
1922 #undef TARGET_LIBGCC_CMP_RETURN_MODE
1923 #define TARGET_LIBGCC_CMP_RETURN_MODE rs6000_abi_word_mode
1924 #undef TARGET_LIBGCC_SHIFT_COUNT_MODE
1925 #define TARGET_LIBGCC_SHIFT_COUNT_MODE rs6000_abi_word_mode
1926 #undef TARGET_UNWIND_WORD_MODE
1927 #define TARGET_UNWIND_WORD_MODE rs6000_abi_word_mode
1928
1929 #undef TARGET_OFFLOAD_OPTIONS
1930 #define TARGET_OFFLOAD_OPTIONS rs6000_offload_options
1931
1932 #undef TARGET_C_MODE_FOR_SUFFIX
1933 #define TARGET_C_MODE_FOR_SUFFIX rs6000_c_mode_for_suffix
1934
1935 #undef TARGET_INVALID_BINARY_OP
1936 #define TARGET_INVALID_BINARY_OP rs6000_invalid_binary_op
1937
1938 #undef TARGET_OPTAB_SUPPORTED_P
1939 #define TARGET_OPTAB_SUPPORTED_P rs6000_optab_supported_p
1940
1941 #undef TARGET_CUSTOM_FUNCTION_DESCRIPTORS
1942 #define TARGET_CUSTOM_FUNCTION_DESCRIPTORS 1
1943
1944 #undef TARGET_COMPARE_VERSION_PRIORITY
1945 #define TARGET_COMPARE_VERSION_PRIORITY rs6000_compare_version_priority
1946
1947 #undef TARGET_GENERATE_VERSION_DISPATCHER_BODY
1948 #define TARGET_GENERATE_VERSION_DISPATCHER_BODY                         \
1949   rs6000_generate_version_dispatcher_body
1950
1951 #undef TARGET_GET_FUNCTION_VERSIONS_DISPATCHER
1952 #define TARGET_GET_FUNCTION_VERSIONS_DISPATCHER                         \
1953   rs6000_get_function_versions_dispatcher
1954
1955 #undef TARGET_OPTION_FUNCTION_VERSIONS
1956 #define TARGET_OPTION_FUNCTION_VERSIONS common_function_versions
1957
1958 #undef TARGET_HARD_REGNO_NREGS
1959 #define TARGET_HARD_REGNO_NREGS rs6000_hard_regno_nregs_hook
1960 #undef TARGET_HARD_REGNO_MODE_OK
1961 #define TARGET_HARD_REGNO_MODE_OK rs6000_hard_regno_mode_ok
1962
1963 #undef TARGET_MODES_TIEABLE_P
1964 #define TARGET_MODES_TIEABLE_P rs6000_modes_tieable_p
1965
1966 #undef TARGET_HARD_REGNO_CALL_PART_CLOBBERED
1967 #define TARGET_HARD_REGNO_CALL_PART_CLOBBERED \
1968   rs6000_hard_regno_call_part_clobbered
1969
1970 #undef TARGET_SLOW_UNALIGNED_ACCESS
1971 #define TARGET_SLOW_UNALIGNED_ACCESS rs6000_slow_unaligned_access
1972
1973 #undef TARGET_CAN_CHANGE_MODE_CLASS
1974 #define TARGET_CAN_CHANGE_MODE_CLASS rs6000_can_change_mode_class
1975
1976 #undef TARGET_CONSTANT_ALIGNMENT
1977 #define TARGET_CONSTANT_ALIGNMENT rs6000_constant_alignment
1978
1979 #undef TARGET_STARTING_FRAME_OFFSET
1980 #define TARGET_STARTING_FRAME_OFFSET rs6000_starting_frame_offset
1981 \f
1982
1983 /* Processor table.  */
1984 struct rs6000_ptt
1985 {
1986   const char *const name;               /* Canonical processor name.  */
1987   const enum processor_type processor;  /* Processor type enum value.  */
1988   const HOST_WIDE_INT target_enable;    /* Target flags to enable.  */
1989 };
1990
1991 static struct rs6000_ptt const processor_target_table[] =
1992 {
1993 #define RS6000_CPU(NAME, CPU, FLAGS) { NAME, CPU, FLAGS },
1994 #include "rs6000-cpus.def"
1995 #undef RS6000_CPU
1996 };
1997
1998 /* Look up a processor name for -mcpu=xxx and -mtune=xxx.  Return -1 if the
1999    name is invalid.  */
2000
2001 static int
2002 rs6000_cpu_name_lookup (const char *name)
2003 {
2004   size_t i;
2005
2006   if (name != NULL)
2007     {
2008       for (i = 0; i < ARRAY_SIZE (processor_target_table); i++)
2009         if (! strcmp (name, processor_target_table[i].name))
2010           return (int)i;
2011     }
2012
2013   return -1;
2014 }
2015
2016 \f
2017 /* Return number of consecutive hard regs needed starting at reg REGNO
2018    to hold something of mode MODE.
2019    This is ordinarily the length in words of a value of mode MODE
2020    but can be less for certain modes in special long registers.
2021
2022    POWER and PowerPC GPRs hold 32 bits worth;
2023    PowerPC64 GPRs and FPRs point register holds 64 bits worth.  */
2024
2025 static int
2026 rs6000_hard_regno_nregs_internal (int regno, machine_mode mode)
2027 {
2028   unsigned HOST_WIDE_INT reg_size;
2029
2030   /* 128-bit floating point usually takes 2 registers, unless it is IEEE
2031      128-bit floating point that can go in vector registers, which has VSX
2032      memory addressing.  */
2033   if (FP_REGNO_P (regno))
2034     reg_size = (VECTOR_MEM_VSX_P (mode) || FLOAT128_VECTOR_P (mode)
2035                 ? UNITS_PER_VSX_WORD
2036                 : UNITS_PER_FP_WORD);
2037
2038   else if (ALTIVEC_REGNO_P (regno))
2039     reg_size = UNITS_PER_ALTIVEC_WORD;
2040
2041   else
2042     reg_size = UNITS_PER_WORD;
2043
2044   return (GET_MODE_SIZE (mode) + reg_size - 1) / reg_size;
2045 }
2046
2047 /* Value is 1 if hard register REGNO can hold a value of machine-mode
2048    MODE.  */
2049 static int
2050 rs6000_hard_regno_mode_ok_uncached (int regno, machine_mode mode)
2051 {
2052   int last_regno = regno + rs6000_hard_regno_nregs[mode][regno] - 1;
2053
2054   if (COMPLEX_MODE_P (mode))
2055     mode = GET_MODE_INNER (mode);
2056
2057   /* PTImode can only go in GPRs.  Quad word memory operations require even/odd
2058      register combinations, and use PTImode where we need to deal with quad
2059      word memory operations.  Don't allow quad words in the argument or frame
2060      pointer registers, just registers 0..31.  */
2061   if (mode == PTImode)
2062     return (IN_RANGE (regno, FIRST_GPR_REGNO, LAST_GPR_REGNO)
2063             && IN_RANGE (last_regno, FIRST_GPR_REGNO, LAST_GPR_REGNO)
2064             && ((regno & 1) == 0));
2065
2066   /* VSX registers that overlap the FPR registers are larger than for non-VSX
2067      implementations.  Don't allow an item to be split between a FP register
2068      and an Altivec register.  Allow TImode in all VSX registers if the user
2069      asked for it.  */
2070   if (TARGET_VSX && VSX_REGNO_P (regno)
2071       && (VECTOR_MEM_VSX_P (mode)
2072           || FLOAT128_VECTOR_P (mode)
2073           || reg_addr[mode].scalar_in_vmx_p
2074           || mode == TImode
2075           || (TARGET_VADDUQM && mode == V1TImode)))
2076     {
2077       if (FP_REGNO_P (regno))
2078         return FP_REGNO_P (last_regno);
2079
2080       if (ALTIVEC_REGNO_P (regno))
2081         {
2082           if (GET_MODE_SIZE (mode) != 16 && !reg_addr[mode].scalar_in_vmx_p)
2083             return 0;
2084
2085           return ALTIVEC_REGNO_P (last_regno);
2086         }
2087     }
2088
2089   /* The GPRs can hold any mode, but values bigger than one register
2090      cannot go past R31.  */
2091   if (INT_REGNO_P (regno))
2092     return INT_REGNO_P (last_regno);
2093
2094   /* The float registers (except for VSX vector modes) can only hold floating
2095      modes and DImode.  */
2096   if (FP_REGNO_P (regno))
2097     {
2098       if (FLOAT128_VECTOR_P (mode))
2099         return false;
2100
2101       if (SCALAR_FLOAT_MODE_P (mode)
2102           && (mode != TDmode || (regno % 2) == 0)
2103           && FP_REGNO_P (last_regno))
2104         return 1;
2105
2106       if (GET_MODE_CLASS (mode) == MODE_INT)
2107         {
2108           if(GET_MODE_SIZE (mode) == UNITS_PER_FP_WORD)
2109             return 1;
2110
2111           if (TARGET_P8_VECTOR && (mode == SImode))
2112             return 1;
2113
2114           if (TARGET_P9_VECTOR && (mode == QImode || mode == HImode))
2115             return 1;
2116         }
2117
2118       if (PAIRED_SIMD_REGNO_P (regno) && TARGET_PAIRED_FLOAT
2119           && PAIRED_VECTOR_MODE (mode))
2120         return 1;
2121
2122       return 0;
2123     }
2124
2125   /* The CR register can only hold CC modes.  */
2126   if (CR_REGNO_P (regno))
2127     return GET_MODE_CLASS (mode) == MODE_CC;
2128
2129   if (CA_REGNO_P (regno))
2130     return mode == Pmode || mode == SImode;
2131
2132   /* AltiVec only in AldyVec registers.  */
2133   if (ALTIVEC_REGNO_P (regno))
2134     return (VECTOR_MEM_ALTIVEC_OR_VSX_P (mode)
2135             || mode == V1TImode);
2136
2137   /* We cannot put non-VSX TImode or PTImode anywhere except general register
2138      and it must be able to fit within the register set.  */
2139
2140   return GET_MODE_SIZE (mode) <= UNITS_PER_WORD;
2141 }
2142
2143 /* Implement TARGET_HARD_REGNO_NREGS.  */
2144
2145 static unsigned int
2146 rs6000_hard_regno_nregs_hook (unsigned int regno, machine_mode mode)
2147 {
2148   return rs6000_hard_regno_nregs[mode][regno];
2149 }
2150
2151 /* Implement TARGET_HARD_REGNO_MODE_OK.  */
2152
2153 static bool
2154 rs6000_hard_regno_mode_ok (unsigned int regno, machine_mode mode)
2155 {
2156   return rs6000_hard_regno_mode_ok_p[mode][regno];
2157 }
2158
2159 /* Implement TARGET_MODES_TIEABLE_P.
2160
2161    PTImode cannot tie with other modes because PTImode is restricted to even
2162    GPR registers, and TImode can go in any GPR as well as VSX registers (PR
2163    57744).
2164
2165    Altivec/VSX vector tests were moved ahead of scalar float mode, so that IEEE
2166    128-bit floating point on VSX systems ties with other vectors.  */
2167
2168 static bool
2169 rs6000_modes_tieable_p (machine_mode mode1, machine_mode mode2)
2170 {
2171   if (mode1 == PTImode)
2172     return mode2 == PTImode;
2173   if (mode2 == PTImode)
2174     return false;
2175
2176   if (ALTIVEC_OR_VSX_VECTOR_MODE (mode1))
2177     return ALTIVEC_OR_VSX_VECTOR_MODE (mode2);
2178   if (ALTIVEC_OR_VSX_VECTOR_MODE (mode2))
2179     return false;
2180
2181   if (SCALAR_FLOAT_MODE_P (mode1))
2182     return SCALAR_FLOAT_MODE_P (mode2);
2183   if (SCALAR_FLOAT_MODE_P (mode2))
2184     return false;
2185
2186   if (GET_MODE_CLASS (mode1) == MODE_CC)
2187     return GET_MODE_CLASS (mode2) == MODE_CC;
2188   if (GET_MODE_CLASS (mode2) == MODE_CC)
2189     return false;
2190
2191   if (PAIRED_VECTOR_MODE (mode1))
2192     return PAIRED_VECTOR_MODE (mode2);
2193   if (PAIRED_VECTOR_MODE (mode2))
2194     return false;
2195
2196   return true;
2197 }
2198
2199 /* Implement TARGET_HARD_REGNO_CALL_PART_CLOBBERED.  */
2200
2201 static bool
2202 rs6000_hard_regno_call_part_clobbered (unsigned int regno, machine_mode mode)
2203 {
2204   if (TARGET_32BIT
2205       && TARGET_POWERPC64
2206       && GET_MODE_SIZE (mode) > 4
2207       && INT_REGNO_P (regno))
2208     return true;
2209
2210   if (TARGET_VSX
2211       && FP_REGNO_P (regno)
2212       && GET_MODE_SIZE (mode) > 8
2213       && !FLOAT128_2REG_P (mode))
2214     return true;
2215
2216   return false;
2217 }
2218
2219 /* Print interesting facts about registers.  */
2220 static void
2221 rs6000_debug_reg_print (int first_regno, int last_regno, const char *reg_name)
2222 {
2223   int r, m;
2224
2225   for (r = first_regno; r <= last_regno; ++r)
2226     {
2227       const char *comma = "";
2228       int len;
2229
2230       if (first_regno == last_regno)
2231         fprintf (stderr, "%s:\t", reg_name);
2232       else
2233         fprintf (stderr, "%s%d:\t", reg_name, r - first_regno);
2234
2235       len = 8;
2236       for (m = 0; m < NUM_MACHINE_MODES; ++m)
2237         if (rs6000_hard_regno_mode_ok_p[m][r] && rs6000_hard_regno_nregs[m][r])
2238           {
2239             if (len > 70)
2240               {
2241                 fprintf (stderr, ",\n\t");
2242                 len = 8;
2243                 comma = "";
2244               }
2245
2246             if (rs6000_hard_regno_nregs[m][r] > 1)
2247               len += fprintf (stderr, "%s%s/%d", comma, GET_MODE_NAME (m),
2248                              rs6000_hard_regno_nregs[m][r]);
2249             else
2250               len += fprintf (stderr, "%s%s", comma, GET_MODE_NAME (m));
2251
2252             comma = ", ";
2253           }
2254
2255       if (call_used_regs[r])
2256         {
2257           if (len > 70)
2258             {
2259               fprintf (stderr, ",\n\t");
2260               len = 8;
2261               comma = "";
2262             }
2263
2264           len += fprintf (stderr, "%s%s", comma, "call-used");
2265           comma = ", ";
2266         }
2267
2268       if (fixed_regs[r])
2269         {
2270           if (len > 70)
2271             {
2272               fprintf (stderr, ",\n\t");
2273               len = 8;
2274               comma = "";
2275             }
2276
2277           len += fprintf (stderr, "%s%s", comma, "fixed");
2278           comma = ", ";
2279         }
2280
2281       if (len > 70)
2282         {
2283           fprintf (stderr, ",\n\t");
2284           comma = "";
2285         }
2286
2287       len += fprintf (stderr, "%sreg-class = %s", comma,
2288                       reg_class_names[(int)rs6000_regno_regclass[r]]);
2289       comma = ", ";
2290
2291       if (len > 70)
2292         {
2293           fprintf (stderr, ",\n\t");
2294           comma = "";
2295         }
2296
2297       fprintf (stderr, "%sregno = %d\n", comma, r);
2298     }
2299 }
2300
2301 static const char *
2302 rs6000_debug_vector_unit (enum rs6000_vector v)
2303 {
2304   const char *ret;
2305
2306   switch (v)
2307     {
2308     case VECTOR_NONE:      ret = "none";      break;
2309     case VECTOR_ALTIVEC:   ret = "altivec";   break;
2310     case VECTOR_VSX:       ret = "vsx";       break;
2311     case VECTOR_P8_VECTOR: ret = "p8_vector"; break;
2312     case VECTOR_PAIRED:    ret = "paired";    break;
2313     case VECTOR_OTHER:     ret = "other";     break;
2314     default:               ret = "unknown";   break;
2315     }
2316
2317   return ret;
2318 }
2319
2320 /* Inner function printing just the address mask for a particular reload
2321    register class.  */
2322 DEBUG_FUNCTION char *
2323 rs6000_debug_addr_mask (addr_mask_type mask, bool keep_spaces)
2324 {
2325   static char ret[8];
2326   char *p = ret;
2327
2328   if ((mask & RELOAD_REG_VALID) != 0)
2329     *p++ = 'v';
2330   else if (keep_spaces)
2331     *p++ = ' ';
2332
2333   if ((mask & RELOAD_REG_MULTIPLE) != 0)
2334     *p++ = 'm';
2335   else if (keep_spaces)
2336     *p++ = ' ';
2337
2338   if ((mask & RELOAD_REG_INDEXED) != 0)
2339     *p++ = 'i';
2340   else if (keep_spaces)
2341     *p++ = ' ';
2342
2343   if ((mask & RELOAD_REG_QUAD_OFFSET) != 0)
2344     *p++ = 'O';
2345   else if ((mask & RELOAD_REG_OFFSET) != 0)
2346     *p++ = 'o';
2347   else if (keep_spaces)
2348     *p++ = ' ';
2349
2350   if ((mask & RELOAD_REG_PRE_INCDEC) != 0)
2351     *p++ = '+';
2352   else if (keep_spaces)
2353     *p++ = ' ';
2354
2355   if ((mask & RELOAD_REG_PRE_MODIFY) != 0)
2356     *p++ = '+';
2357   else if (keep_spaces)
2358     *p++ = ' ';
2359
2360   if ((mask & RELOAD_REG_AND_M16) != 0)
2361     *p++ = '&';
2362   else if (keep_spaces)
2363     *p++ = ' ';
2364
2365   *p = '\0';
2366
2367   return ret;
2368 }
2369
2370 /* Print the address masks in a human readble fashion.  */
2371 DEBUG_FUNCTION void
2372 rs6000_debug_print_mode (ssize_t m)
2373 {
2374   ssize_t rc;
2375   int spaces = 0;
2376   bool fuse_extra_p;
2377
2378   fprintf (stderr, "Mode: %-5s", GET_MODE_NAME (m));
2379   for (rc = 0; rc < N_RELOAD_REG; rc++)
2380     fprintf (stderr, " %s: %s", reload_reg_map[rc].name,
2381              rs6000_debug_addr_mask (reg_addr[m].addr_mask[rc], true));
2382
2383   if ((reg_addr[m].reload_store != CODE_FOR_nothing)
2384       || (reg_addr[m].reload_load != CODE_FOR_nothing))
2385     fprintf (stderr, "  Reload=%c%c",
2386              (reg_addr[m].reload_store != CODE_FOR_nothing) ? 's' : '*',
2387              (reg_addr[m].reload_load != CODE_FOR_nothing) ? 'l' : '*');
2388   else
2389     spaces += sizeof ("  Reload=sl") - 1;
2390
2391   if (reg_addr[m].scalar_in_vmx_p)
2392     {
2393       fprintf (stderr, "%*s  Upper=y", spaces, "");
2394       spaces = 0;
2395     }
2396   else
2397     spaces += sizeof ("  Upper=y") - 1;
2398
2399   fuse_extra_p = ((reg_addr[m].fusion_gpr_ld != CODE_FOR_nothing)
2400                   || reg_addr[m].fused_toc);
2401   if (!fuse_extra_p)
2402     {
2403       for (rc = 0; rc < N_RELOAD_REG; rc++)
2404         {
2405           if (rc != RELOAD_REG_ANY)
2406             {
2407               if (reg_addr[m].fusion_addi_ld[rc]     != CODE_FOR_nothing
2408                   || reg_addr[m].fusion_addi_ld[rc]  != CODE_FOR_nothing
2409                   || reg_addr[m].fusion_addi_st[rc]  != CODE_FOR_nothing
2410                   || reg_addr[m].fusion_addis_ld[rc] != CODE_FOR_nothing
2411                   || reg_addr[m].fusion_addis_st[rc] != CODE_FOR_nothing)
2412                 {
2413                   fuse_extra_p = true;
2414                   break;
2415                 }
2416             }
2417         }
2418     }
2419
2420   if (fuse_extra_p)
2421     {
2422       fprintf (stderr, "%*s  Fuse:", spaces, "");
2423       spaces = 0;
2424
2425       for (rc = 0; rc < N_RELOAD_REG; rc++)
2426         {
2427           if (rc != RELOAD_REG_ANY)
2428             {
2429               char load, store;
2430
2431               if (reg_addr[m].fusion_addis_ld[rc] != CODE_FOR_nothing)
2432                 load = 'l';
2433               else if (reg_addr[m].fusion_addi_ld[rc] != CODE_FOR_nothing)
2434                 load = 'L';
2435               else
2436                 load = '-';
2437
2438               if (reg_addr[m].fusion_addis_st[rc] != CODE_FOR_nothing)
2439                 store = 's';
2440               else if (reg_addr[m].fusion_addi_st[rc] != CODE_FOR_nothing)
2441                 store = 'S';
2442               else
2443                 store = '-';
2444
2445               if (load == '-' && store == '-')
2446                 spaces += 5;
2447               else
2448                 {
2449                   fprintf (stderr, "%*s%c=%c%c", (spaces + 1), "",
2450                            reload_reg_map[rc].name[0], load, store);
2451                   spaces = 0;
2452                 }
2453             }
2454         }
2455
2456       if (reg_addr[m].fusion_gpr_ld != CODE_FOR_nothing)
2457         {
2458           fprintf (stderr, "%*sP8gpr", (spaces + 1), "");
2459           spaces = 0;
2460         }
2461       else
2462         spaces += sizeof (" P8gpr") - 1;
2463
2464       if (reg_addr[m].fused_toc)
2465         {
2466           fprintf (stderr, "%*sToc", (spaces + 1), "");
2467           spaces = 0;
2468         }
2469       else
2470         spaces += sizeof (" Toc") - 1;
2471     }
2472   else
2473     spaces += sizeof ("  Fuse: G=ls F=ls v=ls P8gpr Toc") - 1;
2474
2475   if (rs6000_vector_unit[m] != VECTOR_NONE
2476       || rs6000_vector_mem[m] != VECTOR_NONE)
2477     {
2478       fprintf (stderr, "%*s  vector: arith=%-10s mem=%s",
2479                spaces, "",
2480                rs6000_debug_vector_unit (rs6000_vector_unit[m]),
2481                rs6000_debug_vector_unit (rs6000_vector_mem[m]));
2482     }
2483
2484   fputs ("\n", stderr);
2485 }
2486
2487 #define DEBUG_FMT_ID "%-32s= "
2488 #define DEBUG_FMT_D   DEBUG_FMT_ID "%d\n"
2489 #define DEBUG_FMT_WX  DEBUG_FMT_ID "%#.12" HOST_WIDE_INT_PRINT "x: "
2490 #define DEBUG_FMT_S   DEBUG_FMT_ID "%s\n"
2491
2492 /* Print various interesting information with -mdebug=reg.  */
2493 static void
2494 rs6000_debug_reg_global (void)
2495 {
2496   static const char *const tf[2] = { "false", "true" };
2497   const char *nl = (const char *)0;
2498   int m;
2499   size_t m1, m2, v;
2500   char costly_num[20];
2501   char nop_num[20];
2502   char flags_buffer[40];
2503   const char *costly_str;
2504   const char *nop_str;
2505   const char *trace_str;
2506   const char *abi_str;
2507   const char *cmodel_str;
2508   struct cl_target_option cl_opts;
2509
2510   /* Modes we want tieable information on.  */
2511   static const machine_mode print_tieable_modes[] = {
2512     QImode,
2513     HImode,
2514     SImode,
2515     DImode,
2516     TImode,
2517     PTImode,
2518     SFmode,
2519     DFmode,
2520     TFmode,
2521     IFmode,
2522     KFmode,
2523     SDmode,
2524     DDmode,
2525     TDmode,
2526     V2SImode,
2527     V16QImode,
2528     V8HImode,
2529     V4SImode,
2530     V2DImode,
2531     V1TImode,
2532     V32QImode,
2533     V16HImode,
2534     V8SImode,
2535     V4DImode,
2536     V2TImode,
2537     V2SFmode,
2538     V4SFmode,
2539     V2DFmode,
2540     V8SFmode,
2541     V4DFmode,
2542     CCmode,
2543     CCUNSmode,
2544     CCEQmode,
2545   };
2546
2547   /* Virtual regs we are interested in.  */
2548   const static struct {
2549     int regno;                  /* register number.  */
2550     const char *name;           /* register name.  */
2551   } virtual_regs[] = {
2552     { STACK_POINTER_REGNUM,                     "stack pointer:" },
2553     { TOC_REGNUM,                               "toc:          " },
2554     { STATIC_CHAIN_REGNUM,                      "static chain: " },
2555     { RS6000_PIC_OFFSET_TABLE_REGNUM,           "pic offset:   " },
2556     { HARD_FRAME_POINTER_REGNUM,                "hard frame:   " },
2557     { ARG_POINTER_REGNUM,                       "arg pointer:  " },
2558     { FRAME_POINTER_REGNUM,                     "frame pointer:" },
2559     { FIRST_PSEUDO_REGISTER,                    "first pseudo: " },
2560     { FIRST_VIRTUAL_REGISTER,                   "first virtual:" },
2561     { VIRTUAL_INCOMING_ARGS_REGNUM,             "incoming_args:" },
2562     { VIRTUAL_STACK_VARS_REGNUM,                "stack_vars:   " },
2563     { VIRTUAL_STACK_DYNAMIC_REGNUM,             "stack_dynamic:" },
2564     { VIRTUAL_OUTGOING_ARGS_REGNUM,             "outgoing_args:" },
2565     { VIRTUAL_CFA_REGNUM,                       "cfa (frame):  " },
2566     { VIRTUAL_PREFERRED_STACK_BOUNDARY_REGNUM,  "stack boundry:" },
2567     { LAST_VIRTUAL_REGISTER,                    "last virtual: " },
2568   };
2569
2570   fputs ("\nHard register information:\n", stderr);
2571   rs6000_debug_reg_print (FIRST_GPR_REGNO, LAST_GPR_REGNO, "gr");
2572   rs6000_debug_reg_print (FIRST_FPR_REGNO, LAST_FPR_REGNO, "fp");
2573   rs6000_debug_reg_print (FIRST_ALTIVEC_REGNO,
2574                           LAST_ALTIVEC_REGNO,
2575                           "vs");
2576   rs6000_debug_reg_print (LR_REGNO, LR_REGNO, "lr");
2577   rs6000_debug_reg_print (CTR_REGNO, CTR_REGNO, "ctr");
2578   rs6000_debug_reg_print (CR0_REGNO, CR7_REGNO, "cr");
2579   rs6000_debug_reg_print (CA_REGNO, CA_REGNO, "ca");
2580   rs6000_debug_reg_print (VRSAVE_REGNO, VRSAVE_REGNO, "vrsave");
2581   rs6000_debug_reg_print (VSCR_REGNO, VSCR_REGNO, "vscr");
2582
2583   fputs ("\nVirtual/stack/frame registers:\n", stderr);
2584   for (v = 0; v < ARRAY_SIZE (virtual_regs); v++)
2585     fprintf (stderr, "%s regno = %3d\n", virtual_regs[v].name, virtual_regs[v].regno);
2586
2587   fprintf (stderr,
2588            "\n"
2589            "d  reg_class = %s\n"
2590            "f  reg_class = %s\n"
2591            "v  reg_class = %s\n"
2592            "wa reg_class = %s\n"
2593            "wb reg_class = %s\n"
2594            "wd reg_class = %s\n"
2595            "we reg_class = %s\n"
2596            "wf reg_class = %s\n"
2597            "wg reg_class = %s\n"
2598            "wh reg_class = %s\n"
2599            "wi reg_class = %s\n"
2600            "wj reg_class = %s\n"
2601            "wk reg_class = %s\n"
2602            "wl reg_class = %s\n"
2603            "wm reg_class = %s\n"
2604            "wo reg_class = %s\n"
2605            "wp reg_class = %s\n"
2606            "wq reg_class = %s\n"
2607            "wr reg_class = %s\n"
2608            "ws reg_class = %s\n"
2609            "wt reg_class = %s\n"
2610            "wu reg_class = %s\n"
2611            "wv reg_class = %s\n"
2612            "ww reg_class = %s\n"
2613            "wx reg_class = %s\n"
2614            "wy reg_class = %s\n"
2615            "wz reg_class = %s\n"
2616            "wA reg_class = %s\n"
2617            "wH reg_class = %s\n"
2618            "wI reg_class = %s\n"
2619            "wJ reg_class = %s\n"
2620            "wK reg_class = %s\n"
2621            "\n",
2622            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_d]],
2623            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_f]],
2624            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_v]],
2625            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wa]],
2626            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wb]],
2627            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wd]],
2628            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_we]],
2629            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wf]],
2630            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wg]],
2631            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wh]],
2632            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wi]],
2633            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wj]],
2634            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wk]],
2635            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wl]],
2636            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wm]],
2637            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wo]],
2638            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wp]],
2639            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wq]],
2640            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wr]],
2641            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_ws]],
2642            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wt]],
2643            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wu]],
2644            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wv]],
2645            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_ww]],
2646            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wx]],
2647            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wy]],
2648            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wz]],
2649            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wA]],
2650            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wH]],
2651            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wI]],
2652            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wJ]],
2653            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wK]]);
2654
2655   nl = "\n";
2656   for (m = 0; m < NUM_MACHINE_MODES; ++m)
2657     rs6000_debug_print_mode (m);
2658
2659   fputs ("\n", stderr);
2660
2661   for (m1 = 0; m1 < ARRAY_SIZE (print_tieable_modes); m1++)
2662     {
2663       machine_mode mode1 = print_tieable_modes[m1];
2664       bool first_time = true;
2665
2666       nl = (const char *)0;
2667       for (m2 = 0; m2 < ARRAY_SIZE (print_tieable_modes); m2++)
2668         {
2669           machine_mode mode2 = print_tieable_modes[m2];
2670           if (mode1 != mode2 && rs6000_modes_tieable_p (mode1, mode2))
2671             {
2672               if (first_time)
2673                 {
2674                   fprintf (stderr, "Tieable modes %s:", GET_MODE_NAME (mode1));
2675                   nl = "\n";
2676                   first_time = false;
2677                 }
2678
2679               fprintf (stderr, " %s", GET_MODE_NAME (mode2));
2680             }
2681         }
2682
2683       if (!first_time)
2684         fputs ("\n", stderr);
2685     }
2686
2687   if (nl)
2688     fputs (nl, stderr);
2689
2690   if (rs6000_recip_control)
2691     {
2692       fprintf (stderr, "\nReciprocal mask = 0x%x\n", rs6000_recip_control);
2693
2694       for (m = 0; m < NUM_MACHINE_MODES; ++m)
2695         if (rs6000_recip_bits[m])
2696           {
2697             fprintf (stderr,
2698                      "Reciprocal estimate mode: %-5s divide: %s rsqrt: %s\n",
2699                      GET_MODE_NAME (m),
2700                      (RS6000_RECIP_AUTO_RE_P (m)
2701                       ? "auto"
2702                       : (RS6000_RECIP_HAVE_RE_P (m) ? "have" : "none")),
2703                      (RS6000_RECIP_AUTO_RSQRTE_P (m)
2704                       ? "auto"
2705                       : (RS6000_RECIP_HAVE_RSQRTE_P (m) ? "have" : "none")));
2706           }
2707
2708       fputs ("\n", stderr);
2709     }
2710
2711   if (rs6000_cpu_index >= 0)
2712     {
2713       const char *name = processor_target_table[rs6000_cpu_index].name;
2714       HOST_WIDE_INT flags
2715         = processor_target_table[rs6000_cpu_index].target_enable;
2716
2717       sprintf (flags_buffer, "-mcpu=%s flags", name);
2718       rs6000_print_isa_options (stderr, 0, flags_buffer, flags);
2719     }
2720   else
2721     fprintf (stderr, DEBUG_FMT_S, "cpu", "<none>");
2722
2723   if (rs6000_tune_index >= 0)
2724     {
2725       const char *name = processor_target_table[rs6000_tune_index].name;
2726       HOST_WIDE_INT flags
2727         = processor_target_table[rs6000_tune_index].target_enable;
2728
2729       sprintf (flags_buffer, "-mtune=%s flags", name);
2730       rs6000_print_isa_options (stderr, 0, flags_buffer, flags);
2731     }
2732   else
2733     fprintf (stderr, DEBUG_FMT_S, "tune", "<none>");
2734
2735   cl_target_option_save (&cl_opts, &global_options);
2736   rs6000_print_isa_options (stderr, 0, "rs6000_isa_flags",
2737                             rs6000_isa_flags);
2738
2739   rs6000_print_isa_options (stderr, 0, "rs6000_isa_flags_explicit",
2740                             rs6000_isa_flags_explicit);
2741
2742   rs6000_print_builtin_options (stderr, 0, "rs6000_builtin_mask",
2743                                 rs6000_builtin_mask);
2744
2745   rs6000_print_isa_options (stderr, 0, "TARGET_DEFAULT", TARGET_DEFAULT);
2746
2747   fprintf (stderr, DEBUG_FMT_S, "--with-cpu default",
2748            OPTION_TARGET_CPU_DEFAULT ? OPTION_TARGET_CPU_DEFAULT : "<none>");
2749
2750   switch (rs6000_sched_costly_dep)
2751     {
2752     case max_dep_latency:
2753       costly_str = "max_dep_latency";
2754       break;
2755
2756     case no_dep_costly:
2757       costly_str = "no_dep_costly";
2758       break;
2759
2760     case all_deps_costly:
2761       costly_str = "all_deps_costly";
2762       break;
2763
2764     case true_store_to_load_dep_costly:
2765       costly_str = "true_store_to_load_dep_costly";
2766       break;
2767
2768     case store_to_load_dep_costly:
2769       costly_str = "store_to_load_dep_costly";
2770       break;
2771
2772     default:
2773       costly_str = costly_num;
2774       sprintf (costly_num, "%d", (int)rs6000_sched_costly_dep);
2775       break;
2776     }
2777
2778   fprintf (stderr, DEBUG_FMT_S, "sched_costly_dep", costly_str);
2779
2780   switch (rs6000_sched_insert_nops)
2781     {
2782     case sched_finish_regroup_exact:
2783       nop_str = "sched_finish_regroup_exact";
2784       break;
2785
2786     case sched_finish_pad_groups:
2787       nop_str = "sched_finish_pad_groups";
2788       break;
2789
2790     case sched_finish_none:
2791       nop_str = "sched_finish_none";
2792       break;
2793
2794     default:
2795       nop_str = nop_num;
2796       sprintf (nop_num, "%d", (int)rs6000_sched_insert_nops);
2797       break;
2798     }
2799
2800   fprintf (stderr, DEBUG_FMT_S, "sched_insert_nops", nop_str);
2801
2802   switch (rs6000_sdata)
2803     {
2804     default:
2805     case SDATA_NONE:
2806       break;
2807
2808     case SDATA_DATA:
2809       fprintf (stderr, DEBUG_FMT_S, "sdata", "data");
2810       break;
2811
2812     case SDATA_SYSV:
2813       fprintf (stderr, DEBUG_FMT_S, "sdata", "sysv");
2814       break;
2815
2816     case SDATA_EABI:
2817       fprintf (stderr, DEBUG_FMT_S, "sdata", "eabi");
2818       break;
2819
2820     }
2821
2822   switch (rs6000_traceback)
2823     {
2824     case traceback_default:     trace_str = "default";  break;
2825     case traceback_none:        trace_str = "none";     break;
2826     case traceback_part:        trace_str = "part";     break;
2827     case traceback_full:        trace_str = "full";     break;
2828     default:                    trace_str = "unknown";  break;
2829     }
2830
2831   fprintf (stderr, DEBUG_FMT_S, "traceback", trace_str);
2832
2833   switch (rs6000_current_cmodel)
2834     {
2835     case CMODEL_SMALL:  cmodel_str = "small";   break;
2836     case CMODEL_MEDIUM: cmodel_str = "medium";  break;
2837     case CMODEL_LARGE:  cmodel_str = "large";   break;
2838     default:            cmodel_str = "unknown"; break;
2839     }
2840
2841   fprintf (stderr, DEBUG_FMT_S, "cmodel", cmodel_str);
2842
2843   switch (rs6000_current_abi)
2844     {
2845     case ABI_NONE:      abi_str = "none";       break;
2846     case ABI_AIX:       abi_str = "aix";        break;
2847     case ABI_ELFv2:     abi_str = "ELFv2";      break;
2848     case ABI_V4:        abi_str = "V4";         break;
2849     case ABI_DARWIN:    abi_str = "darwin";     break;
2850     default:            abi_str = "unknown";    break;
2851     }
2852
2853   fprintf (stderr, DEBUG_FMT_S, "abi", abi_str);
2854
2855   if (rs6000_altivec_abi)
2856     fprintf (stderr, DEBUG_FMT_S, "altivec_abi", "true");
2857
2858   if (rs6000_darwin64_abi)
2859     fprintf (stderr, DEBUG_FMT_S, "darwin64_abi", "true");
2860
2861   fprintf (stderr, DEBUG_FMT_S, "single_float",
2862            (TARGET_SINGLE_FLOAT ? "true" : "false"));
2863
2864   fprintf (stderr, DEBUG_FMT_S, "double_float",
2865            (TARGET_DOUBLE_FLOAT ? "true" : "false"));
2866
2867   fprintf (stderr, DEBUG_FMT_S, "soft_float",
2868            (TARGET_SOFT_FLOAT ? "true" : "false"));
2869
2870   if (TARGET_LINK_STACK)
2871     fprintf (stderr, DEBUG_FMT_S, "link_stack", "true");
2872
2873   if (TARGET_P8_FUSION)
2874     {
2875       char options[80];
2876
2877       strcpy (options, (TARGET_P9_FUSION) ? "power9" : "power8");
2878       if (TARGET_TOC_FUSION)
2879         strcat (options, ", toc");
2880
2881       if (TARGET_P8_FUSION_SIGN)
2882         strcat (options, ", sign");
2883
2884       fprintf (stderr, DEBUG_FMT_S, "fusion", options);
2885     }
2886
2887   fprintf (stderr, DEBUG_FMT_S, "plt-format",
2888            TARGET_SECURE_PLT ? "secure" : "bss");
2889   fprintf (stderr, DEBUG_FMT_S, "struct-return",
2890            aix_struct_return ? "aix" : "sysv");
2891   fprintf (stderr, DEBUG_FMT_S, "always_hint", tf[!!rs6000_always_hint]);
2892   fprintf (stderr, DEBUG_FMT_S, "sched_groups", tf[!!rs6000_sched_groups]);
2893   fprintf (stderr, DEBUG_FMT_S, "align_branch",
2894            tf[!!rs6000_align_branch_targets]);
2895   fprintf (stderr, DEBUG_FMT_D, "tls_size", rs6000_tls_size);
2896   fprintf (stderr, DEBUG_FMT_D, "long_double_size",
2897            rs6000_long_double_type_size);
2898   if (rs6000_long_double_type_size == 128)
2899     {
2900       fprintf (stderr, DEBUG_FMT_S, "long double type",
2901                TARGET_IEEEQUAD ? "IEEE" : "IBM");
2902       fprintf (stderr, DEBUG_FMT_S, "default long double type",
2903                TARGET_IEEEQUAD_DEFAULT ? "IEEE" : "IBM");
2904     }
2905   fprintf (stderr, DEBUG_FMT_D, "sched_restricted_insns_priority",
2906            (int)rs6000_sched_restricted_insns_priority);
2907   fprintf (stderr, DEBUG_FMT_D, "Number of standard builtins",
2908            (int)END_BUILTINS);
2909   fprintf (stderr, DEBUG_FMT_D, "Number of rs6000 builtins",
2910            (int)RS6000_BUILTIN_COUNT);
2911
2912   fprintf (stderr, DEBUG_FMT_D, "Enable float128 on VSX",
2913            (int)TARGET_FLOAT128_ENABLE_TYPE);
2914
2915   if (TARGET_VSX)
2916     fprintf (stderr, DEBUG_FMT_D, "VSX easy 64-bit scalar element",
2917              (int)VECTOR_ELEMENT_SCALAR_64BIT);
2918
2919   if (TARGET_DIRECT_MOVE_128)
2920     fprintf (stderr, DEBUG_FMT_D, "VSX easy 64-bit mfvsrld element",
2921              (int)VECTOR_ELEMENT_MFVSRLD_64BIT);
2922 }
2923
2924 \f
2925 /* Update the addr mask bits in reg_addr to help secondary reload and go if
2926    legitimate address support to figure out the appropriate addressing to
2927    use.  */
2928
2929 static void
2930 rs6000_setup_reg_addr_masks (void)
2931 {
2932   ssize_t rc, reg, m, nregs;
2933   addr_mask_type any_addr_mask, addr_mask;
2934
2935   for (m = 0; m < NUM_MACHINE_MODES; ++m)
2936     {
2937       machine_mode m2 = (machine_mode) m;
2938       bool complex_p = false;
2939       bool small_int_p = (m2 == QImode || m2 == HImode || m2 == SImode);
2940       size_t msize;
2941
2942       if (COMPLEX_MODE_P (m2))
2943         {
2944           complex_p = true;
2945           m2 = GET_MODE_INNER (m2);
2946         }
2947
2948       msize = GET_MODE_SIZE (m2);
2949
2950       /* SDmode is special in that we want to access it only via REG+REG
2951          addressing on power7 and above, since we want to use the LFIWZX and
2952          STFIWZX instructions to load it.  */
2953       bool indexed_only_p = (m == SDmode && TARGET_NO_SDMODE_STACK);
2954
2955       any_addr_mask = 0;
2956       for (rc = FIRST_RELOAD_REG_CLASS; rc <= LAST_RELOAD_REG_CLASS; rc++)
2957         {
2958           addr_mask = 0;
2959           reg = reload_reg_map[rc].reg;
2960
2961           /* Can mode values go in the GPR/FPR/Altivec registers?  */
2962           if (reg >= 0 && rs6000_hard_regno_mode_ok_p[m][reg])
2963             {
2964               bool small_int_vsx_p = (small_int_p
2965                                       && (rc == RELOAD_REG_FPR
2966                                           || rc == RELOAD_REG_VMX));
2967
2968               nregs = rs6000_hard_regno_nregs[m][reg];
2969               addr_mask |= RELOAD_REG_VALID;
2970
2971               /* Indicate if the mode takes more than 1 physical register.  If
2972                  it takes a single register, indicate it can do REG+REG
2973                  addressing.  Small integers in VSX registers can only do
2974                  REG+REG addressing.  */
2975               if (small_int_vsx_p)
2976                 addr_mask |= RELOAD_REG_INDEXED;
2977               else if (nregs > 1 || m == BLKmode || complex_p)
2978                 addr_mask |= RELOAD_REG_MULTIPLE;
2979               else
2980                 addr_mask |= RELOAD_REG_INDEXED;
2981
2982               /* Figure out if we can do PRE_INC, PRE_DEC, or PRE_MODIFY
2983                  addressing.  If we allow scalars into Altivec registers,
2984                  don't allow PRE_INC, PRE_DEC, or PRE_MODIFY.  */
2985
2986               if (TARGET_UPDATE
2987                   && (rc == RELOAD_REG_GPR || rc == RELOAD_REG_FPR)
2988                   && msize <= 8
2989                   && !VECTOR_MODE_P (m2)
2990                   && !FLOAT128_VECTOR_P (m2)
2991                   && !complex_p
2992                   && !small_int_vsx_p)
2993                 {
2994                   addr_mask |= RELOAD_REG_PRE_INCDEC;
2995
2996                   /* PRE_MODIFY is more restricted than PRE_INC/PRE_DEC in that
2997                      we don't allow PRE_MODIFY for some multi-register
2998                      operations.  */
2999                   switch (m)
3000                     {
3001                     default:
3002                       addr_mask |= RELOAD_REG_PRE_MODIFY;
3003                       break;
3004
3005                     case E_DImode:
3006                       if (TARGET_POWERPC64)
3007                         addr_mask |= RELOAD_REG_PRE_MODIFY;
3008                       break;
3009
3010                     case E_DFmode:
3011                     case E_DDmode:
3012                       if (TARGET_DF_INSN)
3013                         addr_mask |= RELOAD_REG_PRE_MODIFY;
3014                       break;
3015                     }
3016                 }
3017             }
3018
3019           /* GPR and FPR registers can do REG+OFFSET addressing, except
3020              possibly for SDmode.  ISA 3.0 (i.e. power9) adds D-form addressing
3021              for 64-bit scalars and 32-bit SFmode to altivec registers.  */
3022           if ((addr_mask != 0) && !indexed_only_p
3023               && msize <= 8
3024               && (rc == RELOAD_REG_GPR
3025                   || ((msize == 8 || m2 == SFmode)
3026                       && (rc == RELOAD_REG_FPR
3027                           || (rc == RELOAD_REG_VMX && TARGET_P9_VECTOR)))))
3028             addr_mask |= RELOAD_REG_OFFSET;
3029
3030           /* VSX registers can do REG+OFFSET addresssing if ISA 3.0
3031              instructions are enabled.  The offset for 128-bit VSX registers is
3032              only 12-bits.  While GPRs can handle the full offset range, VSX
3033              registers can only handle the restricted range.  */
3034           else if ((addr_mask != 0) && !indexed_only_p
3035                    && msize == 16 && TARGET_P9_VECTOR
3036                    && (ALTIVEC_OR_VSX_VECTOR_MODE (m2)
3037                        || (m2 == TImode && TARGET_VSX)))
3038             {
3039               addr_mask |= RELOAD_REG_OFFSET;
3040               if (rc == RELOAD_REG_FPR || rc == RELOAD_REG_VMX)
3041                 addr_mask |= RELOAD_REG_QUAD_OFFSET;
3042             }
3043
3044           /* VMX registers can do (REG & -16) and ((REG+REG) & -16)
3045              addressing on 128-bit types.  */
3046           if (rc == RELOAD_REG_VMX && msize == 16
3047               && (addr_mask & RELOAD_REG_VALID) != 0)
3048             addr_mask |= RELOAD_REG_AND_M16;
3049
3050           reg_addr[m].addr_mask[rc] = addr_mask;
3051           any_addr_mask |= addr_mask;
3052         }
3053
3054       reg_addr[m].addr_mask[RELOAD_REG_ANY] = any_addr_mask;
3055     }
3056 }
3057
3058 \f
3059 /* Initialize the various global tables that are based on register size.  */
3060 static void
3061 rs6000_init_hard_regno_mode_ok (bool global_init_p)
3062 {
3063   ssize_t r, m, c;
3064   int align64;
3065   int align32;
3066
3067   /* Precalculate REGNO_REG_CLASS.  */
3068   rs6000_regno_regclass[0] = GENERAL_REGS;
3069   for (r = 1; r < 32; ++r)
3070     rs6000_regno_regclass[r] = BASE_REGS;
3071
3072   for (r = 32; r < 64; ++r)
3073     rs6000_regno_regclass[r] = FLOAT_REGS;
3074
3075   for (r = 64; r < FIRST_PSEUDO_REGISTER; ++r)
3076     rs6000_regno_regclass[r] = NO_REGS;
3077
3078   for (r = FIRST_ALTIVEC_REGNO; r <= LAST_ALTIVEC_REGNO; ++r)
3079     rs6000_regno_regclass[r] = ALTIVEC_REGS;
3080
3081   rs6000_regno_regclass[CR0_REGNO] = CR0_REGS;
3082   for (r = CR1_REGNO; r <= CR7_REGNO; ++r)
3083     rs6000_regno_regclass[r] = CR_REGS;
3084
3085   rs6000_regno_regclass[LR_REGNO] = LINK_REGS;
3086   rs6000_regno_regclass[CTR_REGNO] = CTR_REGS;
3087   rs6000_regno_regclass[CA_REGNO] = NO_REGS;
3088   rs6000_regno_regclass[VRSAVE_REGNO] = VRSAVE_REGS;
3089   rs6000_regno_regclass[VSCR_REGNO] = VRSAVE_REGS;
3090   rs6000_regno_regclass[TFHAR_REGNO] = SPR_REGS;
3091   rs6000_regno_regclass[TFIAR_REGNO] = SPR_REGS;
3092   rs6000_regno_regclass[TEXASR_REGNO] = SPR_REGS;
3093   rs6000_regno_regclass[ARG_POINTER_REGNUM] = BASE_REGS;
3094   rs6000_regno_regclass[FRAME_POINTER_REGNUM] = BASE_REGS;
3095
3096   /* Precalculate register class to simpler reload register class.  We don't
3097      need all of the register classes that are combinations of different
3098      classes, just the simple ones that have constraint letters.  */
3099   for (c = 0; c < N_REG_CLASSES; c++)
3100     reg_class_to_reg_type[c] = NO_REG_TYPE;
3101
3102   reg_class_to_reg_type[(int)GENERAL_REGS] = GPR_REG_TYPE;
3103   reg_class_to_reg_type[(int)BASE_REGS] = GPR_REG_TYPE;
3104   reg_class_to_reg_type[(int)VSX_REGS] = VSX_REG_TYPE;
3105   reg_class_to_reg_type[(int)VRSAVE_REGS] = SPR_REG_TYPE;
3106   reg_class_to_reg_type[(int)VSCR_REGS] = SPR_REG_TYPE;
3107   reg_class_to_reg_type[(int)LINK_REGS] = SPR_REG_TYPE;
3108   reg_class_to_reg_type[(int)CTR_REGS] = SPR_REG_TYPE;
3109   reg_class_to_reg_type[(int)LINK_OR_CTR_REGS] = SPR_REG_TYPE;
3110   reg_class_to_reg_type[(int)CR_REGS] = CR_REG_TYPE;
3111   reg_class_to_reg_type[(int)CR0_REGS] = CR_REG_TYPE;
3112
3113   if (TARGET_VSX)
3114     {
3115       reg_class_to_reg_type[(int)FLOAT_REGS] = VSX_REG_TYPE;
3116       reg_class_to_reg_type[(int)ALTIVEC_REGS] = VSX_REG_TYPE;
3117     }
3118   else
3119     {
3120       reg_class_to_reg_type[(int)FLOAT_REGS] = FPR_REG_TYPE;
3121       reg_class_to_reg_type[(int)ALTIVEC_REGS] = ALTIVEC_REG_TYPE;
3122     }
3123
3124   /* Precalculate the valid memory formats as well as the vector information,
3125      this must be set up before the rs6000_hard_regno_nregs_internal calls
3126      below.  */
3127   gcc_assert ((int)VECTOR_NONE == 0);
3128   memset ((void *) &rs6000_vector_unit[0], '\0', sizeof (rs6000_vector_unit));
3129   memset ((void *) &rs6000_vector_mem[0], '\0', sizeof (rs6000_vector_unit));
3130
3131   gcc_assert ((int)CODE_FOR_nothing == 0);
3132   memset ((void *) &reg_addr[0], '\0', sizeof (reg_addr));
3133
3134   gcc_assert ((int)NO_REGS == 0);
3135   memset ((void *) &rs6000_constraints[0], '\0', sizeof (rs6000_constraints));
3136
3137   /* The VSX hardware allows native alignment for vectors, but control whether the compiler
3138      believes it can use native alignment or still uses 128-bit alignment.  */
3139   if (TARGET_VSX && !TARGET_VSX_ALIGN_128)
3140     {
3141       align64 = 64;
3142       align32 = 32;
3143     }
3144   else
3145     {
3146       align64 = 128;
3147       align32 = 128;
3148     }
3149
3150   /* KF mode (IEEE 128-bit in VSX registers).  We do not have arithmetic, so
3151      only set the memory modes.  Include TFmode if -mabi=ieeelongdouble.  */
3152   if (TARGET_FLOAT128_TYPE)
3153     {
3154       rs6000_vector_mem[KFmode] = VECTOR_VSX;
3155       rs6000_vector_align[KFmode] = 128;
3156
3157       if (FLOAT128_IEEE_P (TFmode))
3158         {
3159           rs6000_vector_mem[TFmode] = VECTOR_VSX;
3160           rs6000_vector_align[TFmode] = 128;
3161         }
3162     }
3163
3164   /* V2DF mode, VSX only.  */
3165   if (TARGET_VSX)
3166     {
3167       rs6000_vector_unit[V2DFmode] = VECTOR_VSX;
3168       rs6000_vector_mem[V2DFmode] = VECTOR_VSX;
3169       rs6000_vector_align[V2DFmode] = align64;
3170     }
3171
3172   /* V4SF mode, either VSX or Altivec.  */
3173   if (TARGET_VSX)
3174     {
3175       rs6000_vector_unit[V4SFmode] = VECTOR_VSX;
3176       rs6000_vector_mem[V4SFmode] = VECTOR_VSX;
3177       rs6000_vector_align[V4SFmode] = align32;
3178     }
3179   else if (TARGET_ALTIVEC)
3180     {
3181       rs6000_vector_unit[V4SFmode] = VECTOR_ALTIVEC;
3182       rs6000_vector_mem[V4SFmode] = VECTOR_ALTIVEC;
3183       rs6000_vector_align[V4SFmode] = align32;
3184     }
3185
3186   /* V16QImode, V8HImode, V4SImode are Altivec only, but possibly do VSX loads
3187      and stores. */
3188   if (TARGET_ALTIVEC)
3189     {
3190       rs6000_vector_unit[V4SImode] = VECTOR_ALTIVEC;
3191       rs6000_vector_unit[V8HImode] = VECTOR_ALTIVEC;
3192       rs6000_vector_unit[V16QImode] = VECTOR_ALTIVEC;
3193       rs6000_vector_align[V4SImode] = align32;
3194       rs6000_vector_align[V8HImode] = align32;
3195       rs6000_vector_align[V16QImode] = align32;
3196
3197       if (TARGET_VSX)
3198         {
3199           rs6000_vector_mem[V4SImode] = VECTOR_VSX;
3200           rs6000_vector_mem[V8HImode] = VECTOR_VSX;
3201           rs6000_vector_mem[V16QImode] = VECTOR_VSX;
3202         }
3203       else
3204         {
3205           rs6000_vector_mem[V4SImode] = VECTOR_ALTIVEC;
3206           rs6000_vector_mem[V8HImode] = VECTOR_ALTIVEC;
3207           rs6000_vector_mem[V16QImode] = VECTOR_ALTIVEC;
3208         }
3209     }
3210
3211   /* V2DImode, full mode depends on ISA 2.07 vector mode.  Allow under VSX to
3212      do insert/splat/extract.  Altivec doesn't have 64-bit integer support.  */
3213   if (TARGET_VSX)
3214     {
3215       rs6000_vector_mem[V2DImode] = VECTOR_VSX;
3216       rs6000_vector_unit[V2DImode]
3217         = (TARGET_P8_VECTOR) ? VECTOR_P8_VECTOR : VECTOR_NONE;
3218       rs6000_vector_align[V2DImode] = align64;
3219
3220       rs6000_vector_mem[V1TImode] = VECTOR_VSX;
3221       rs6000_vector_unit[V1TImode]
3222         = (TARGET_P8_VECTOR) ? VECTOR_P8_VECTOR : VECTOR_NONE;
3223       rs6000_vector_align[V1TImode] = 128;
3224     }
3225
3226   /* DFmode, see if we want to use the VSX unit.  Memory is handled
3227      differently, so don't set rs6000_vector_mem.  */
3228   if (TARGET_VSX)
3229     {
3230       rs6000_vector_unit[DFmode] = VECTOR_VSX;
3231       rs6000_vector_align[DFmode] = 64;
3232     }
3233
3234   /* SFmode, see if we want to use the VSX unit.  */
3235   if (TARGET_P8_VECTOR)
3236     {
3237       rs6000_vector_unit[SFmode] = VECTOR_VSX;
3238       rs6000_vector_align[SFmode] = 32;
3239     }
3240
3241   /* Allow TImode in VSX register and set the VSX memory macros.  */
3242   if (TARGET_VSX)
3243     {
3244       rs6000_vector_mem[TImode] = VECTOR_VSX;
3245       rs6000_vector_align[TImode] = align64;
3246     }
3247
3248   /* TODO add paired floating point vector support.  */
3249
3250   /* Register class constraints for the constraints that depend on compile
3251      switches. When the VSX code was added, different constraints were added
3252      based on the type (DFmode, V2DFmode, V4SFmode).  For the vector types, all
3253      of the VSX registers are used.  The register classes for scalar floating
3254      point types is set, based on whether we allow that type into the upper
3255      (Altivec) registers.  GCC has register classes to target the Altivec
3256      registers for load/store operations, to select using a VSX memory
3257      operation instead of the traditional floating point operation.  The
3258      constraints are:
3259
3260         d  - Register class to use with traditional DFmode instructions.
3261         f  - Register class to use with traditional SFmode instructions.
3262         v  - Altivec register.
3263         wa - Any VSX register.
3264         wc - Reserved to represent individual CR bits (used in LLVM).
3265         wd - Preferred register class for V2DFmode.
3266         wf - Preferred register class for V4SFmode.
3267         wg - Float register for power6x move insns.
3268         wh - FP register for direct move instructions.
3269         wi - FP or VSX register to hold 64-bit integers for VSX insns.
3270         wj - FP or VSX register to hold 64-bit integers for direct moves.
3271         wk - FP or VSX register to hold 64-bit doubles for direct moves.
3272         wl - Float register if we can do 32-bit signed int loads.
3273         wm - VSX register for ISA 2.07 direct move operations.
3274         wn - always NO_REGS.
3275         wr - GPR if 64-bit mode is permitted.
3276         ws - Register class to do ISA 2.06 DF operations.
3277         wt - VSX register for TImode in VSX registers.
3278         wu - Altivec register for ISA 2.07 VSX SF/SI load/stores.
3279         wv - Altivec register for ISA 2.06 VSX DF/DI load/stores.
3280         ww - Register class to do SF conversions in with VSX operations.
3281         wx - Float register if we can do 32-bit int stores.
3282         wy - Register class to do ISA 2.07 SF operations.
3283         wz - Float register if we can do 32-bit unsigned int loads.
3284         wH - Altivec register if SImode is allowed in VSX registers.
3285         wI - VSX register if SImode is allowed in VSX registers.
3286         wJ - VSX register if QImode/HImode are allowed in VSX registers.
3287         wK - Altivec register if QImode/HImode are allowed in VSX registers.  */
3288
3289   if (TARGET_HARD_FLOAT)
3290     rs6000_constraints[RS6000_CONSTRAINT_f] = FLOAT_REGS;       /* SFmode  */
3291
3292   if (TARGET_HARD_FLOAT && TARGET_DOUBLE_FLOAT)
3293     rs6000_constraints[RS6000_CONSTRAINT_d]  = FLOAT_REGS;      /* DFmode  */
3294
3295   if (TARGET_VSX)
3296     {
3297       rs6000_constraints[RS6000_CONSTRAINT_wa] = VSX_REGS;
3298       rs6000_constraints[RS6000_CONSTRAINT_wd] = VSX_REGS;      /* V2DFmode  */
3299       rs6000_constraints[RS6000_CONSTRAINT_wf] = VSX_REGS;      /* V4SFmode  */
3300       rs6000_constraints[RS6000_CONSTRAINT_ws] = VSX_REGS;      /* DFmode  */
3301       rs6000_constraints[RS6000_CONSTRAINT_wv] = ALTIVEC_REGS;  /* DFmode  */
3302       rs6000_constraints[RS6000_CONSTRAINT_wi] = VSX_REGS;      /* DImode  */
3303       rs6000_constraints[RS6000_CONSTRAINT_wt] = VSX_REGS;      /* TImode  */
3304     }
3305
3306   /* Add conditional constraints based on various options, to allow us to
3307      collapse multiple insn patterns.  */
3308   if (TARGET_ALTIVEC)
3309     rs6000_constraints[RS6000_CONSTRAINT_v] = ALTIVEC_REGS;
3310
3311   if (TARGET_MFPGPR)                                            /* DFmode  */
3312     rs6000_constraints[RS6000_CONSTRAINT_wg] = FLOAT_REGS;
3313
3314   if (TARGET_LFIWAX)
3315     rs6000_constraints[RS6000_CONSTRAINT_wl] = FLOAT_REGS;      /* DImode  */
3316
3317   if (TARGET_DIRECT_MOVE)
3318     {
3319       rs6000_constraints[RS6000_CONSTRAINT_wh] = FLOAT_REGS;
3320       rs6000_constraints[RS6000_CONSTRAINT_wj]                  /* DImode  */
3321         = rs6000_constraints[RS6000_CONSTRAINT_wi];
3322       rs6000_constraints[RS6000_CONSTRAINT_wk]                  /* DFmode  */
3323         = rs6000_constraints[RS6000_CONSTRAINT_ws];
3324       rs6000_constraints[RS6000_CONSTRAINT_wm] = VSX_REGS;
3325     }
3326
3327   if (TARGET_POWERPC64)
3328     {
3329       rs6000_constraints[RS6000_CONSTRAINT_wr] = GENERAL_REGS;
3330       rs6000_constraints[RS6000_CONSTRAINT_wA] = BASE_REGS;
3331     }
3332
3333   if (TARGET_P8_VECTOR)                                         /* SFmode  */
3334     {
3335       rs6000_constraints[RS6000_CONSTRAINT_wu] = ALTIVEC_REGS;
3336       rs6000_constraints[RS6000_CONSTRAINT_wy] = VSX_REGS;
3337       rs6000_constraints[RS6000_CONSTRAINT_ww] = VSX_REGS;
3338     }
3339   else if (TARGET_VSX)
3340     rs6000_constraints[RS6000_CONSTRAINT_ww] = FLOAT_REGS;
3341
3342   if (TARGET_STFIWX)
3343     rs6000_constraints[RS6000_CONSTRAINT_wx] = FLOAT_REGS;      /* DImode  */
3344
3345   if (TARGET_LFIWZX)
3346     rs6000_constraints[RS6000_CONSTRAINT_wz] = FLOAT_REGS;      /* DImode  */
3347
3348   if (TARGET_FLOAT128_TYPE)
3349     {
3350       rs6000_constraints[RS6000_CONSTRAINT_wq] = VSX_REGS;      /* KFmode  */
3351       if (FLOAT128_IEEE_P (TFmode))
3352         rs6000_constraints[RS6000_CONSTRAINT_wp] = VSX_REGS;    /* TFmode  */
3353     }
3354
3355   if (TARGET_P9_VECTOR)
3356     {
3357       /* Support for new D-form instructions.  */
3358       rs6000_constraints[RS6000_CONSTRAINT_wb] = ALTIVEC_REGS;
3359
3360       /* Support for ISA 3.0 (power9) vectors.  */
3361       rs6000_constraints[RS6000_CONSTRAINT_wo] = VSX_REGS;
3362     }
3363
3364   /* Support for new direct moves (ISA 3.0 + 64bit).  */
3365   if (TARGET_DIRECT_MOVE_128)
3366     rs6000_constraints[RS6000_CONSTRAINT_we] = VSX_REGS;
3367
3368   /* Support small integers in VSX registers.  */
3369   if (TARGET_P8_VECTOR)
3370     {
3371       rs6000_constraints[RS6000_CONSTRAINT_wH] = ALTIVEC_REGS;
3372       rs6000_constraints[RS6000_CONSTRAINT_wI] = FLOAT_REGS;
3373       if (TARGET_P9_VECTOR)
3374         {
3375           rs6000_constraints[RS6000_CONSTRAINT_wJ] = FLOAT_REGS;
3376           rs6000_constraints[RS6000_CONSTRAINT_wK] = ALTIVEC_REGS;
3377         }
3378     }
3379
3380   /* Set up the reload helper and direct move functions.  */
3381   if (TARGET_VSX || TARGET_ALTIVEC)
3382     {
3383       if (TARGET_64BIT)
3384         {
3385           reg_addr[V16QImode].reload_store = CODE_FOR_reload_v16qi_di_store;
3386           reg_addr[V16QImode].reload_load  = CODE_FOR_reload_v16qi_di_load;
3387           reg_addr[V8HImode].reload_store  = CODE_FOR_reload_v8hi_di_store;
3388           reg_addr[V8HImode].reload_load   = CODE_FOR_reload_v8hi_di_load;
3389           reg_addr[V4SImode].reload_store  = CODE_FOR_reload_v4si_di_store;
3390           reg_addr[V4SImode].reload_load   = CODE_FOR_reload_v4si_di_load;
3391           reg_addr[V2DImode].reload_store  = CODE_FOR_reload_v2di_di_store;
3392           reg_addr[V2DImode].reload_load   = CODE_FOR_reload_v2di_di_load;
3393           reg_addr[V1TImode].reload_store  = CODE_FOR_reload_v1ti_di_store;
3394           reg_addr[V1TImode].reload_load   = CODE_FOR_reload_v1ti_di_load;
3395           reg_addr[V4SFmode].reload_store  = CODE_FOR_reload_v4sf_di_store;
3396           reg_addr[V4SFmode].reload_load   = CODE_FOR_reload_v4sf_di_load;
3397           reg_addr[V2DFmode].reload_store  = CODE_FOR_reload_v2df_di_store;
3398           reg_addr[V2DFmode].reload_load   = CODE_FOR_reload_v2df_di_load;
3399           reg_addr[DFmode].reload_store    = CODE_FOR_reload_df_di_store;
3400           reg_addr[DFmode].reload_load     = CODE_FOR_reload_df_di_load;
3401           reg_addr[DDmode].reload_store    = CODE_FOR_reload_dd_di_store;
3402           reg_addr[DDmode].reload_load     = CODE_FOR_reload_dd_di_load;
3403           reg_addr[SFmode].reload_store    = CODE_FOR_reload_sf_di_store;
3404           reg_addr[SFmode].reload_load     = CODE_FOR_reload_sf_di_load;
3405
3406           if (FLOAT128_VECTOR_P (KFmode))
3407             {
3408               reg_addr[KFmode].reload_store = CODE_FOR_reload_kf_di_store;
3409               reg_addr[KFmode].reload_load  = CODE_FOR_reload_kf_di_load;
3410             }
3411
3412           if (FLOAT128_VECTOR_P (TFmode))
3413             {
3414               reg_addr[TFmode].reload_store = CODE_FOR_reload_tf_di_store;
3415               reg_addr[TFmode].reload_load  = CODE_FOR_reload_tf_di_load;
3416             }
3417
3418           /* Only provide a reload handler for SDmode if lfiwzx/stfiwx are
3419              available.  */
3420           if (TARGET_NO_SDMODE_STACK)
3421             {
3422               reg_addr[SDmode].reload_store = CODE_FOR_reload_sd_di_store;
3423               reg_addr[SDmode].reload_load  = CODE_FOR_reload_sd_di_load;
3424             }
3425
3426           if (TARGET_VSX)
3427             {
3428               reg_addr[TImode].reload_store  = CODE_FOR_reload_ti_di_store;
3429               reg_addr[TImode].reload_load   = CODE_FOR_reload_ti_di_load;
3430             }
3431
3432           if (TARGET_DIRECT_MOVE && !TARGET_DIRECT_MOVE_128)
3433             {
3434               reg_addr[TImode].reload_gpr_vsx    = CODE_FOR_reload_gpr_from_vsxti;
3435               reg_addr[V1TImode].reload_gpr_vsx  = CODE_FOR_reload_gpr_from_vsxv1ti;
3436               reg_addr[V2DFmode].reload_gpr_vsx  = CODE_FOR_reload_gpr_from_vsxv2df;
3437               reg_addr[V2DImode].reload_gpr_vsx  = CODE_FOR_reload_gpr_from_vsxv2di;
3438               reg_addr[V4SFmode].reload_gpr_vsx  = CODE_FOR_reload_gpr_from_vsxv4sf;
3439               reg_addr[V4SImode].reload_gpr_vsx  = CODE_FOR_reload_gpr_from_vsxv4si;
3440               reg_addr[V8HImode].reload_gpr_vsx  = CODE_FOR_reload_gpr_from_vsxv8hi;
3441               reg_addr[V16QImode].reload_gpr_vsx = CODE_FOR_reload_gpr_from_vsxv16qi;
3442               reg_addr[SFmode].reload_gpr_vsx    = CODE_FOR_reload_gpr_from_vsxsf;
3443
3444               reg_addr[TImode].reload_vsx_gpr    = CODE_FOR_reload_vsx_from_gprti;
3445               reg_addr[V1TImode].reload_vsx_gpr  = CODE_FOR_reload_vsx_from_gprv1ti;
3446               reg_addr[V2DFmode].reload_vsx_gpr  = CODE_FOR_reload_vsx_from_gprv2df;
3447               reg_addr[V2DImode].reload_vsx_gpr  = CODE_FOR_reload_vsx_from_gprv2di;
3448               reg_addr[V4SFmode].reload_vsx_gpr  = CODE_FOR_reload_vsx_from_gprv4sf;
3449               reg_addr[V4SImode].reload_vsx_gpr  = CODE_FOR_reload_vsx_from_gprv4si;
3450               reg_addr[V8HImode].reload_vsx_gpr  = CODE_FOR_reload_vsx_from_gprv8hi;
3451               reg_addr[V16QImode].reload_vsx_gpr = CODE_FOR_reload_vsx_from_gprv16qi;
3452               reg_addr[SFmode].reload_vsx_gpr    = CODE_FOR_reload_vsx_from_gprsf;
3453
3454               if (FLOAT128_VECTOR_P (KFmode))
3455                 {
3456                   reg_addr[KFmode].reload_gpr_vsx = CODE_FOR_reload_gpr_from_vsxkf;
3457                   reg_addr[KFmode].reload_vsx_gpr = CODE_FOR_reload_vsx_from_gprkf;
3458                 }
3459
3460               if (FLOAT128_VECTOR_P (TFmode))
3461                 {
3462                   reg_addr[TFmode].reload_gpr_vsx = CODE_FOR_reload_gpr_from_vsxtf;
3463                   reg_addr[TFmode].reload_vsx_gpr = CODE_FOR_reload_vsx_from_gprtf;
3464                 }
3465             }
3466         }
3467       else
3468         {
3469           reg_addr[V16QImode].reload_store = CODE_FOR_reload_v16qi_si_store;
3470           reg_addr[V16QImode].reload_load  = CODE_FOR_reload_v16qi_si_load;
3471           reg_addr[V8HImode].reload_store  = CODE_FOR_reload_v8hi_si_store;
3472           reg_addr[V8HImode].reload_load   = CODE_FOR_reload_v8hi_si_load;
3473           reg_addr[V4SImode].reload_store  = CODE_FOR_reload_v4si_si_store;
3474           reg_addr[V4SImode].reload_load   = CODE_FOR_reload_v4si_si_load;
3475           reg_addr[V2DImode].reload_store  = CODE_FOR_reload_v2di_si_store;
3476           reg_addr[V2DImode].reload_load   = CODE_FOR_reload_v2di_si_load;
3477           reg_addr[V1TImode].reload_store  = CODE_FOR_reload_v1ti_si_store;
3478           reg_addr[V1TImode].reload_load   = CODE_FOR_reload_v1ti_si_load;
3479           reg_addr[V4SFmode].reload_store  = CODE_FOR_reload_v4sf_si_store;
3480           reg_addr[V4SFmode].reload_load   = CODE_FOR_reload_v4sf_si_load;
3481           reg_addr[V2DFmode].reload_store  = CODE_FOR_reload_v2df_si_store;
3482           reg_addr[V2DFmode].reload_load   = CODE_FOR_reload_v2df_si_load;
3483           reg_addr[DFmode].reload_store    = CODE_FOR_reload_df_si_store;
3484           reg_addr[DFmode].reload_load     = CODE_FOR_reload_df_si_load;
3485           reg_addr[DDmode].reload_store    = CODE_FOR_reload_dd_si_store;
3486           reg_addr[DDmode].reload_load     = CODE_FOR_reload_dd_si_load;
3487           reg_addr[SFmode].reload_store    = CODE_FOR_reload_sf_si_store;
3488           reg_addr[SFmode].reload_load     = CODE_FOR_reload_sf_si_load;
3489
3490           if (FLOAT128_VECTOR_P (KFmode))
3491             {
3492               reg_addr[KFmode].reload_store = CODE_FOR_reload_kf_si_store;
3493               reg_addr[KFmode].reload_load  = CODE_FOR_reload_kf_si_load;
3494             }
3495
3496           if (FLOAT128_IEEE_P (TFmode))
3497             {
3498               reg_addr[TFmode].reload_store = CODE_FOR_reload_tf_si_store;
3499               reg_addr[TFmode].reload_load  = CODE_FOR_reload_tf_si_load;
3500             }
3501
3502           /* Only provide a reload handler for SDmode if lfiwzx/stfiwx are
3503              available.  */
3504           if (TARGET_NO_SDMODE_STACK)
3505             {
3506               reg_addr[SDmode].reload_store = CODE_FOR_reload_sd_si_store;
3507               reg_addr[SDmode].reload_load  = CODE_FOR_reload_sd_si_load;
3508             }
3509
3510           if (TARGET_VSX)
3511             {
3512               reg_addr[TImode].reload_store  = CODE_FOR_reload_ti_si_store;
3513               reg_addr[TImode].reload_load   = CODE_FOR_reload_ti_si_load;
3514             }
3515
3516           if (TARGET_DIRECT_MOVE)
3517             {
3518               reg_addr[DImode].reload_fpr_gpr = CODE_FOR_reload_fpr_from_gprdi;
3519               reg_addr[DDmode].reload_fpr_gpr = CODE_FOR_reload_fpr_from_gprdd;
3520               reg_addr[DFmode].reload_fpr_gpr = CODE_FOR_reload_fpr_from_gprdf;
3521             }
3522         }
3523
3524       reg_addr[DFmode].scalar_in_vmx_p = true;
3525       reg_addr[DImode].scalar_in_vmx_p = true;
3526
3527       if (TARGET_P8_VECTOR)
3528         {
3529           reg_addr[SFmode].scalar_in_vmx_p = true;
3530           reg_addr[SImode].scalar_in_vmx_p = true;
3531
3532           if (TARGET_P9_VECTOR)
3533             {
3534               reg_addr[HImode].scalar_in_vmx_p = true;
3535               reg_addr[QImode].scalar_in_vmx_p = true;
3536             }
3537         }
3538     }
3539
3540   /* Setup the fusion operations.  */
3541   if (TARGET_P8_FUSION)
3542     {
3543       reg_addr[QImode].fusion_gpr_ld = CODE_FOR_fusion_gpr_load_qi;
3544       reg_addr[HImode].fusion_gpr_ld = CODE_FOR_fusion_gpr_load_hi;
3545       reg_addr[SImode].fusion_gpr_ld = CODE_FOR_fusion_gpr_load_si;
3546       if (TARGET_64BIT)
3547         reg_addr[DImode].fusion_gpr_ld = CODE_FOR_fusion_gpr_load_di;
3548     }
3549
3550   if (TARGET_P9_FUSION)
3551     {
3552       struct fuse_insns {
3553         enum machine_mode mode;                 /* mode of the fused type.  */
3554         enum machine_mode pmode;                /* pointer mode.  */
3555         enum rs6000_reload_reg_type rtype;      /* register type.  */
3556         enum insn_code load;                    /* load insn.  */
3557         enum insn_code store;                   /* store insn.  */
3558       };
3559
3560       static const struct fuse_insns addis_insns[] = {
3561         { E_SFmode, E_DImode, RELOAD_REG_FPR,
3562           CODE_FOR_fusion_vsx_di_sf_load,
3563           CODE_FOR_fusion_vsx_di_sf_store },
3564
3565         { E_SFmode, E_SImode, RELOAD_REG_FPR,
3566           CODE_FOR_fusion_vsx_si_sf_load,
3567           CODE_FOR_fusion_vsx_si_sf_store },
3568
3569         { E_DFmode, E_DImode, RELOAD_REG_FPR,
3570           CODE_FOR_fusion_vsx_di_df_load,
3571           CODE_FOR_fusion_vsx_di_df_store },
3572
3573         { E_DFmode, E_SImode, RELOAD_REG_FPR,
3574           CODE_FOR_fusion_vsx_si_df_load,
3575           CODE_FOR_fusion_vsx_si_df_store },
3576
3577         { E_DImode, E_DImode, RELOAD_REG_FPR,
3578           CODE_FOR_fusion_vsx_di_di_load,
3579           CODE_FOR_fusion_vsx_di_di_store },
3580
3581         { E_DImode, E_SImode, RELOAD_REG_FPR,
3582           CODE_FOR_fusion_vsx_si_di_load,
3583           CODE_FOR_fusion_vsx_si_di_store },
3584
3585         { E_QImode, E_DImode, RELOAD_REG_GPR,
3586           CODE_FOR_fusion_gpr_di_qi_load,
3587           CODE_FOR_fusion_gpr_di_qi_store },
3588
3589         { E_QImode, E_SImode, RELOAD_REG_GPR,
3590           CODE_FOR_fusion_gpr_si_qi_load,
3591           CODE_FOR_fusion_gpr_si_qi_store },
3592
3593         { E_HImode, E_DImode, RELOAD_REG_GPR,
3594           CODE_FOR_fusion_gpr_di_hi_load,
3595           CODE_FOR_fusion_gpr_di_hi_store },
3596
3597         { E_HImode, E_SImode, RELOAD_REG_GPR,
3598           CODE_FOR_fusion_gpr_si_hi_load,
3599           CODE_FOR_fusion_gpr_si_hi_store },
3600
3601         { E_SImode, E_DImode, RELOAD_REG_GPR,
3602           CODE_FOR_fusion_gpr_di_si_load,
3603           CODE_FOR_fusion_gpr_di_si_store },
3604
3605         { E_SImode, E_SImode, RELOAD_REG_GPR,
3606           CODE_FOR_fusion_gpr_si_si_load,
3607           CODE_FOR_fusion_gpr_si_si_store },
3608
3609         { E_SFmode, E_DImode, RELOAD_REG_GPR,
3610           CODE_FOR_fusion_gpr_di_sf_load,
3611           CODE_FOR_fusion_gpr_di_sf_store },
3612
3613         { E_SFmode, E_SImode, RELOAD_REG_GPR,
3614           CODE_FOR_fusion_gpr_si_sf_load,
3615           CODE_FOR_fusion_gpr_si_sf_store },
3616
3617         { E_DImode, E_DImode, RELOAD_REG_GPR,
3618           CODE_FOR_fusion_gpr_di_di_load,
3619           CODE_FOR_fusion_gpr_di_di_store },
3620
3621         { E_DFmode, E_DImode, RELOAD_REG_GPR,
3622           CODE_FOR_fusion_gpr_di_df_load,
3623           CODE_FOR_fusion_gpr_di_df_store },
3624       };
3625
3626       machine_mode cur_pmode = Pmode;
3627       size_t i;
3628
3629       for (i = 0; i < ARRAY_SIZE (addis_insns); i++)
3630         {
3631           machine_mode xmode = addis_insns[i].mode;
3632           enum rs6000_reload_reg_type rtype = addis_insns[i].rtype;
3633
3634           if (addis_insns[i].pmode != cur_pmode)
3635             continue;
3636
3637           if (rtype == RELOAD_REG_FPR && !TARGET_HARD_FLOAT)
3638             continue;
3639
3640           reg_addr[xmode].fusion_addis_ld[rtype] = addis_insns[i].load;
3641           reg_addr[xmode].fusion_addis_st[rtype] = addis_insns[i].store;
3642
3643           if (rtype == RELOAD_REG_FPR && TARGET_P9_VECTOR)
3644             {
3645               reg_addr[xmode].fusion_addis_ld[RELOAD_REG_VMX]
3646                 = addis_insns[i].load;
3647               reg_addr[xmode].fusion_addis_st[RELOAD_REG_VMX]
3648                 = addis_insns[i].store;
3649             }
3650         }
3651     }
3652
3653   /* Note which types we support fusing TOC setup plus memory insn.  We only do
3654      fused TOCs for medium/large code models.  */
3655   if (TARGET_P8_FUSION && TARGET_TOC_FUSION && TARGET_POWERPC64
3656       && (TARGET_CMODEL != CMODEL_SMALL))
3657     {
3658       reg_addr[QImode].fused_toc = true;
3659       reg_addr[HImode].fused_toc = true;
3660       reg_addr[SImode].fused_toc = true;
3661       reg_addr[DImode].fused_toc = true;
3662       if (TARGET_HARD_FLOAT)
3663         {
3664           if (TARGET_SINGLE_FLOAT)
3665             reg_addr[SFmode].fused_toc = true;
3666           if (TARGET_DOUBLE_FLOAT)
3667             reg_addr[DFmode].fused_toc = true;
3668         }
3669     }
3670
3671   /* Precalculate HARD_REGNO_NREGS.  */
3672   for (r = 0; r < FIRST_PSEUDO_REGISTER; ++r)
3673     for (m = 0; m < NUM_MACHINE_MODES; ++m)
3674       rs6000_hard_regno_nregs[m][r]
3675         = rs6000_hard_regno_nregs_internal (r, (machine_mode)m);
3676
3677   /* Precalculate TARGET_HARD_REGNO_MODE_OK.  */
3678   for (r = 0; r < FIRST_PSEUDO_REGISTER; ++r)
3679     for (m = 0; m < NUM_MACHINE_MODES; ++m)
3680       if (rs6000_hard_regno_mode_ok_uncached (r, (machine_mode)m))
3681         rs6000_hard_regno_mode_ok_p[m][r] = true;
3682
3683   /* Precalculate CLASS_MAX_NREGS sizes.  */
3684   for (c = 0; c < LIM_REG_CLASSES; ++c)
3685     {
3686       int reg_size;
3687
3688       if (TARGET_VSX && VSX_REG_CLASS_P (c))
3689         reg_size = UNITS_PER_VSX_WORD;
3690
3691       else if (c == ALTIVEC_REGS)
3692         reg_size = UNITS_PER_ALTIVEC_WORD;
3693
3694       else if (c == FLOAT_REGS)
3695         reg_size = UNITS_PER_FP_WORD;
3696
3697       else
3698         reg_size = UNITS_PER_WORD;
3699
3700       for (m = 0; m < NUM_MACHINE_MODES; ++m)
3701         {
3702           machine_mode m2 = (machine_mode)m;
3703           int reg_size2 = reg_size;
3704
3705           /* TDmode & IBM 128-bit floating point always takes 2 registers, even
3706              in VSX.  */
3707           if (TARGET_VSX && VSX_REG_CLASS_P (c) && FLOAT128_2REG_P (m))
3708             reg_size2 = UNITS_PER_FP_WORD;
3709
3710           rs6000_class_max_nregs[m][c]
3711             = (GET_MODE_SIZE (m2) + reg_size2 - 1) / reg_size2;
3712         }
3713     }
3714
3715   /* Calculate which modes to automatically generate code to use a the
3716      reciprocal divide and square root instructions.  In the future, possibly
3717      automatically generate the instructions even if the user did not specify
3718      -mrecip.  The older machines double precision reciprocal sqrt estimate is
3719      not accurate enough.  */
3720   memset (rs6000_recip_bits, 0, sizeof (rs6000_recip_bits));
3721   if (TARGET_FRES)
3722     rs6000_recip_bits[SFmode] = RS6000_RECIP_MASK_HAVE_RE;
3723   if (TARGET_FRE)
3724     rs6000_recip_bits[DFmode] = RS6000_RECIP_MASK_HAVE_RE;
3725   if (VECTOR_UNIT_ALTIVEC_OR_VSX_P (V4SFmode))
3726     rs6000_recip_bits[V4SFmode] = RS6000_RECIP_MASK_HAVE_RE;
3727   if (VECTOR_UNIT_VSX_P (V2DFmode))
3728     rs6000_recip_bits[V2DFmode] = RS6000_RECIP_MASK_HAVE_RE;
3729
3730   if (TARGET_FRSQRTES)
3731     rs6000_recip_bits[SFmode] |= RS6000_RECIP_MASK_HAVE_RSQRTE;
3732   if (TARGET_FRSQRTE)
3733     rs6000_recip_bits[DFmode] |= RS6000_RECIP_MASK_HAVE_RSQRTE;
3734   if (VECTOR_UNIT_ALTIVEC_OR_VSX_P (V4SFmode))
3735     rs6000_recip_bits[V4SFmode] |= RS6000_RECIP_MASK_HAVE_RSQRTE;
3736   if (VECTOR_UNIT_VSX_P (V2DFmode))
3737     rs6000_recip_bits[V2DFmode] |= RS6000_RECIP_MASK_HAVE_RSQRTE;
3738
3739   if (rs6000_recip_control)
3740     {
3741       if (!flag_finite_math_only)
3742         warning (0, "%qs requires %qs or %qs", "-mrecip", "-ffinite-math",
3743                  "-ffast-math");
3744       if (flag_trapping_math)
3745         warning (0, "%qs requires %qs or %qs", "-mrecip",
3746                  "-fno-trapping-math", "-ffast-math");
3747       if (!flag_reciprocal_math)
3748         warning (0, "%qs requires %qs or %qs", "-mrecip", "-freciprocal-math",
3749                  "-ffast-math");
3750       if (flag_finite_math_only && !flag_trapping_math && flag_reciprocal_math)
3751         {
3752           if (RS6000_RECIP_HAVE_RE_P (SFmode)
3753               && (rs6000_recip_control & RECIP_SF_DIV) != 0)
3754             rs6000_recip_bits[SFmode] |= RS6000_RECIP_MASK_AUTO_RE;
3755
3756           if (RS6000_RECIP_HAVE_RE_P (DFmode)
3757               && (rs6000_recip_control & RECIP_DF_DIV) != 0)
3758             rs6000_recip_bits[DFmode] |= RS6000_RECIP_MASK_AUTO_RE;
3759
3760           if (RS6000_RECIP_HAVE_RE_P (V4SFmode)
3761               && (rs6000_recip_control & RECIP_V4SF_DIV) != 0)
3762             rs6000_recip_bits[V4SFmode] |= RS6000_RECIP_MASK_AUTO_RE;
3763
3764           if (RS6000_RECIP_HAVE_RE_P (V2DFmode)
3765               && (rs6000_recip_control & RECIP_V2DF_DIV) != 0)
3766             rs6000_recip_bits[V2DFmode] |= RS6000_RECIP_MASK_AUTO_RE;
3767
3768           if (RS6000_RECIP_HAVE_RSQRTE_P (SFmode)
3769               && (rs6000_recip_control & RECIP_SF_RSQRT) != 0)
3770             rs6000_recip_bits[SFmode] |= RS6000_RECIP_MASK_AUTO_RSQRTE;
3771
3772           if (RS6000_RECIP_HAVE_RSQRTE_P (DFmode)
3773               && (rs6000_recip_control & RECIP_DF_RSQRT) != 0)
3774             rs6000_recip_bits[DFmode] |= RS6000_RECIP_MASK_AUTO_RSQRTE;
3775
3776           if (RS6000_RECIP_HAVE_RSQRTE_P (V4SFmode)
3777               && (rs6000_recip_control & RECIP_V4SF_RSQRT) != 0)
3778             rs6000_recip_bits[V4SFmode] |= RS6000_RECIP_MASK_AUTO_RSQRTE;
3779
3780           if (RS6000_RECIP_HAVE_RSQRTE_P (V2DFmode)
3781               && (rs6000_recip_control & RECIP_V2DF_RSQRT) != 0)
3782             rs6000_recip_bits[V2DFmode] |= RS6000_RECIP_MASK_AUTO_RSQRTE;
3783         }
3784     }
3785
3786   /* Update the addr mask bits in reg_addr to help secondary reload and go if
3787      legitimate address support to figure out the appropriate addressing to
3788      use.  */
3789   rs6000_setup_reg_addr_masks ();
3790
3791   if (global_init_p || TARGET_DEBUG_TARGET)
3792     {
3793       if (TARGET_DEBUG_REG)
3794         rs6000_debug_reg_global ();
3795
3796       if (TARGET_DEBUG_COST || TARGET_DEBUG_REG)
3797         fprintf (stderr,
3798                  "SImode variable mult cost       = %d\n"
3799                  "SImode constant mult cost       = %d\n"
3800                  "SImode short constant mult cost = %d\n"
3801                  "DImode multipliciation cost     = %d\n"
3802                  "SImode division cost            = %d\n"
3803                  "DImode division cost            = %d\n"
3804                  "Simple fp operation cost        = %d\n"
3805                  "DFmode multiplication cost      = %d\n"
3806                  "SFmode division cost            = %d\n"
3807                  "DFmode division cost            = %d\n"
3808                  "cache line size                 = %d\n"
3809                  "l1 cache size                   = %d\n"
3810                  "l2 cache size                   = %d\n"
3811                  "simultaneous prefetches         = %d\n"
3812                  "\n",
3813                  rs6000_cost->mulsi,
3814                  rs6000_cost->mulsi_const,
3815                  rs6000_cost->mulsi_const9,
3816                  rs6000_cost->muldi,
3817                  rs6000_cost->divsi,
3818                  rs6000_cost->divdi,
3819                  rs6000_cost->fp,
3820                  rs6000_cost->dmul,
3821                  rs6000_cost->sdiv,
3822                  rs6000_cost->ddiv,
3823                  rs6000_cost->cache_line_size,
3824                  rs6000_cost->l1_cache_size,
3825                  rs6000_cost->l2_cache_size,
3826                  rs6000_cost->simultaneous_prefetches);
3827     }
3828 }
3829
3830 #if TARGET_MACHO
3831 /* The Darwin version of SUBTARGET_OVERRIDE_OPTIONS.  */
3832
3833 static void
3834 darwin_rs6000_override_options (void)
3835 {
3836   /* The Darwin ABI always includes AltiVec, can't be (validly) turned
3837      off.  */
3838   rs6000_altivec_abi = 1;
3839   TARGET_ALTIVEC_VRSAVE = 1;
3840   rs6000_current_abi = ABI_DARWIN;
3841
3842   if (DEFAULT_ABI == ABI_DARWIN
3843       && TARGET_64BIT)
3844       darwin_one_byte_bool = 1;
3845
3846   if (TARGET_64BIT && ! TARGET_POWERPC64)
3847     {
3848       rs6000_isa_flags |= OPTION_MASK_POWERPC64;
3849       warning (0, "%qs requires PowerPC64 architecture, enabling", "-m64");
3850     }
3851   if (flag_mkernel)
3852     {
3853       rs6000_default_long_calls = 1;
3854       rs6000_isa_flags |= OPTION_MASK_SOFT_FLOAT;
3855     }
3856
3857   /* Make -m64 imply -maltivec.  Darwin's 64-bit ABI includes
3858      Altivec.  */
3859   if (!flag_mkernel && !flag_apple_kext
3860       && TARGET_64BIT
3861       && ! (rs6000_isa_flags_explicit & OPTION_MASK_ALTIVEC))
3862     rs6000_isa_flags |= OPTION_MASK_ALTIVEC;
3863
3864   /* Unless the user (not the configurer) has explicitly overridden
3865      it with -mcpu=G3 or -mno-altivec, then 10.5+ targets default to
3866      G4 unless targeting the kernel.  */
3867   if (!flag_mkernel
3868       && !flag_apple_kext
3869       && strverscmp (darwin_macosx_version_min, "10.5") >= 0
3870       && ! (rs6000_isa_flags_explicit & OPTION_MASK_ALTIVEC)
3871       && ! global_options_set.x_rs6000_cpu_index)
3872     {
3873       rs6000_isa_flags |= OPTION_MASK_ALTIVEC;
3874     }
3875 }
3876 #endif
3877
3878 /* If not otherwise specified by a target, make 'long double' equivalent to
3879    'double'.  */
3880
3881 #ifndef RS6000_DEFAULT_LONG_DOUBLE_SIZE
3882 #define RS6000_DEFAULT_LONG_DOUBLE_SIZE 64
3883 #endif
3884
3885 /* Return the builtin mask of the various options used that could affect which
3886    builtins were used.  In the past we used target_flags, but we've run out of
3887    bits, and some options like PAIRED are no longer in target_flags.  */
3888
3889 HOST_WIDE_INT
3890 rs6000_builtin_mask_calculate (void)
3891 {
3892   return (((TARGET_ALTIVEC)                 ? RS6000_BTM_ALTIVEC   : 0)
3893           | ((TARGET_CMPB)                  ? RS6000_BTM_CMPB      : 0)
3894           | ((TARGET_VSX)                   ? RS6000_BTM_VSX       : 0)
3895           | ((TARGET_PAIRED_FLOAT)          ? RS6000_BTM_PAIRED    : 0)
3896           | ((TARGET_FRE)                   ? RS6000_BTM_FRE       : 0)
3897           | ((TARGET_FRES)                  ? RS6000_BTM_FRES      : 0)
3898           | ((TARGET_FRSQRTE)               ? RS6000_BTM_FRSQRTE   : 0)
3899           | ((TARGET_FRSQRTES)              ? RS6000_BTM_FRSQRTES  : 0)
3900           | ((TARGET_POPCNTD)               ? RS6000_BTM_POPCNTD   : 0)
3901           | ((rs6000_cpu == PROCESSOR_CELL) ? RS6000_BTM_CELL      : 0)
3902           | ((TARGET_P8_VECTOR)             ? RS6000_BTM_P8_VECTOR : 0)
3903           | ((TARGET_P9_VECTOR)             ? RS6000_BTM_P9_VECTOR : 0)
3904           | ((TARGET_P9_MISC)               ? RS6000_BTM_P9_MISC   : 0)
3905           | ((TARGET_MODULO)                ? RS6000_BTM_MODULO    : 0)
3906           | ((TARGET_64BIT)                 ? RS6000_BTM_64BIT     : 0)
3907           | ((TARGET_CRYPTO)                ? RS6000_BTM_CRYPTO    : 0)
3908           | ((TARGET_HTM)                   ? RS6000_BTM_HTM       : 0)
3909           | ((TARGET_DFP)                   ? RS6000_BTM_DFP       : 0)
3910           | ((TARGET_HARD_FLOAT)            ? RS6000_BTM_HARD_FLOAT : 0)
3911           | ((TARGET_LONG_DOUBLE_128)       ? RS6000_BTM_LDBL128   : 0)
3912           | ((TARGET_FLOAT128_TYPE)         ? RS6000_BTM_FLOAT128  : 0)
3913           | ((TARGET_FLOAT128_HW)           ? RS6000_BTM_FLOAT128_HW : 0));
3914 }
3915
3916 /* Implement TARGET_MD_ASM_ADJUST.  All asm statements are considered
3917    to clobber the XER[CA] bit because clobbering that bit without telling
3918    the compiler worked just fine with versions of GCC before GCC 5, and
3919    breaking a lot of older code in ways that are hard to track down is
3920    not such a great idea.  */
3921
3922 static rtx_insn *
3923 rs6000_md_asm_adjust (vec<rtx> &/*outputs*/, vec<rtx> &/*inputs*/,
3924                       vec<const char *> &/*constraints*/,
3925                       vec<rtx> &clobbers, HARD_REG_SET &clobbered_regs)
3926 {
3927   clobbers.safe_push (gen_rtx_REG (SImode, CA_REGNO));
3928   SET_HARD_REG_BIT (clobbered_regs, CA_REGNO);
3929   return NULL;
3930 }
3931
3932 /* Override command line options.
3933
3934    Combine build-specific configuration information with options
3935    specified on the command line to set various state variables which
3936    influence code generation, optimization, and expansion of built-in
3937    functions.  Assure that command-line configuration preferences are
3938    compatible with each other and with the build configuration; issue
3939    warnings while adjusting configuration or error messages while
3940    rejecting configuration.
3941
3942    Upon entry to this function:
3943
3944      This function is called once at the beginning of
3945      compilation, and then again at the start and end of compiling
3946      each section of code that has a different configuration, as
3947      indicated, for example, by adding the
3948
3949        __attribute__((__target__("cpu=power9")))
3950
3951      qualifier to a function definition or, for example, by bracketing
3952      code between
3953
3954        #pragma GCC target("altivec")
3955
3956      and
3957
3958        #pragma GCC reset_options
3959
3960      directives.  Parameter global_init_p is true for the initial
3961      invocation, which initializes global variables, and false for all
3962      subsequent invocations.
3963
3964
3965      Various global state information is assumed to be valid.  This
3966      includes OPTION_TARGET_CPU_DEFAULT, representing the name of the
3967      default CPU specified at build configure time, TARGET_DEFAULT,
3968      representing the default set of option flags for the default
3969      target, and global_options_set.x_rs6000_isa_flags, representing
3970      which options were requested on the command line.
3971
3972    Upon return from this function:
3973
3974      rs6000_isa_flags_explicit has a non-zero bit for each flag that
3975      was set by name on the command line.  Additionally, if certain
3976      attributes are automatically enabled or disabled by this function
3977      in order to assure compatibility between options and
3978      configuration, the flags associated with those attributes are
3979      also set.  By setting these "explicit bits", we avoid the risk
3980      that other code might accidentally overwrite these particular
3981      attributes with "default values".
3982
3983      The various bits of rs6000_isa_flags are set to indicate the
3984      target options that have been selected for the most current
3985      compilation efforts.  This has the effect of also turning on the
3986      associated TARGET_XXX values since these are macros which are
3987      generally defined to test the corresponding bit of the
3988      rs6000_isa_flags variable.
3989
3990      The variable rs6000_builtin_mask is set to represent the target
3991      options for the most current compilation efforts, consistent with
3992      the current contents of rs6000_isa_flags.  This variable controls
3993      expansion of built-in functions.
3994
3995      Various other global variables and fields of global structures
3996      (over 50 in all) are initialized to reflect the desired options
3997      for the most current compilation efforts.  */
3998
3999 static bool
4000 rs6000_option_override_internal (bool global_init_p)
4001 {
4002   bool ret = true;
4003
4004   HOST_WIDE_INT set_masks;
4005   HOST_WIDE_INT ignore_masks;
4006   int cpu_index = -1;
4007   int tune_index;
4008   struct cl_target_option *main_target_opt
4009     = ((global_init_p || target_option_default_node == NULL)
4010        ? NULL : TREE_TARGET_OPTION (target_option_default_node));
4011
4012   /* Print defaults.  */
4013   if ((TARGET_DEBUG_REG || TARGET_DEBUG_TARGET) && global_init_p)
4014     rs6000_print_isa_options (stderr, 0, "TARGET_DEFAULT", TARGET_DEFAULT);
4015
4016   /* Remember the explicit arguments.  */
4017   if (global_init_p)
4018     rs6000_isa_flags_explicit = global_options_set.x_rs6000_isa_flags;
4019
4020   /* On 64-bit Darwin, power alignment is ABI-incompatible with some C
4021      library functions, so warn about it. The flag may be useful for
4022      performance studies from time to time though, so don't disable it
4023      entirely.  */
4024   if (global_options_set.x_rs6000_alignment_flags
4025       && rs6000_alignment_flags == MASK_ALIGN_POWER
4026       && DEFAULT_ABI == ABI_DARWIN
4027       && TARGET_64BIT)
4028     warning (0, "%qs is not supported for 64-bit Darwin;"
4029              " it is incompatible with the installed C and C++ libraries",
4030              "-malign-power");
4031
4032   /* Numerous experiment shows that IRA based loop pressure
4033      calculation works better for RTL loop invariant motion on targets
4034      with enough (>= 32) registers.  It is an expensive optimization.
4035      So it is on only for peak performance.  */
4036   if (optimize >= 3 && global_init_p
4037       && !global_options_set.x_flag_ira_loop_pressure)
4038     flag_ira_loop_pressure = 1;
4039
4040   /* -fsanitize=address needs to turn on -fasynchronous-unwind-tables in order
4041      for tracebacks to be complete but not if any -fasynchronous-unwind-tables
4042      options were already specified.  */
4043   if (flag_sanitize & SANITIZE_USER_ADDRESS
4044       && !global_options_set.x_flag_asynchronous_unwind_tables)
4045     flag_asynchronous_unwind_tables = 1;
4046
4047   /* Set the pointer size.  */
4048   if (TARGET_64BIT)
4049     {
4050       rs6000_pmode = DImode;
4051       rs6000_pointer_size = 64;
4052     }
4053   else
4054     {
4055       rs6000_pmode = SImode;
4056       rs6000_pointer_size = 32;
4057     }
4058
4059   /* Some OSs don't support saving the high part of 64-bit registers on context
4060      switch.  Other OSs don't support saving Altivec registers.  On those OSs,
4061      we don't touch the OPTION_MASK_POWERPC64 or OPTION_MASK_ALTIVEC settings;
4062      if the user wants either, the user must explicitly specify them and we
4063      won't interfere with the user's specification.  */
4064
4065   set_masks = POWERPC_MASKS;
4066 #ifdef OS_MISSING_POWERPC64
4067   if (OS_MISSING_POWERPC64)
4068     set_masks &= ~OPTION_MASK_POWERPC64;
4069 #endif
4070 #ifdef OS_MISSING_ALTIVEC
4071   if (OS_MISSING_ALTIVEC)
4072     set_masks &= ~(OPTION_MASK_ALTIVEC | OPTION_MASK_VSX
4073                    | OTHER_VSX_VECTOR_MASKS);
4074 #endif
4075
4076   /* Don't override by the processor default if given explicitly.  */
4077   set_masks &= ~rs6000_isa_flags_explicit;
4078
4079   /* Process the -mcpu=<xxx> and -mtune=<xxx> argument.  If the user changed
4080      the cpu in a target attribute or pragma, but did not specify a tuning
4081      option, use the cpu for the tuning option rather than the option specified
4082      with -mtune on the command line.  Process a '--with-cpu' configuration
4083      request as an implicit --cpu.  */
4084   if (rs6000_cpu_index >= 0)
4085     cpu_index = rs6000_cpu_index;
4086   else if (main_target_opt != NULL && main_target_opt->x_rs6000_cpu_index >= 0)
4087     cpu_index = main_target_opt->x_rs6000_cpu_index;
4088   else if (OPTION_TARGET_CPU_DEFAULT)
4089     cpu_index = rs6000_cpu_name_lookup (OPTION_TARGET_CPU_DEFAULT);
4090
4091   if (cpu_index >= 0)
4092     {
4093       const char *unavailable_cpu = NULL;
4094       switch (processor_target_table[cpu_index].processor)
4095         {
4096 #ifndef HAVE_AS_POWER9
4097         case PROCESSOR_POWER9:
4098           unavailable_cpu = "power9";
4099           break;
4100 #endif
4101 #ifndef HAVE_AS_POWER8
4102         case PROCESSOR_POWER8:
4103           unavailable_cpu = "power8";
4104           break;
4105 #endif
4106 #ifndef HAVE_AS_POPCNTD
4107         case PROCESSOR_POWER7:
4108           unavailable_cpu = "power7";
4109           break;
4110 #endif
4111 #ifndef HAVE_AS_DFP
4112         case PROCESSOR_POWER6:
4113           unavailable_cpu = "power6";
4114           break;
4115 #endif
4116 #ifndef HAVE_AS_POPCNTB
4117         case PROCESSOR_POWER5:
4118           unavailable_cpu = "power5";
4119           break;
4120 #endif
4121         default:
4122           break;
4123         }
4124       if (unavailable_cpu)
4125         {
4126           cpu_index = -1;
4127           warning (0, "will not generate %qs instructions because "
4128                    "assembler lacks %qs support", unavailable_cpu,
4129                    unavailable_cpu);
4130         }
4131     }
4132
4133   /* If we have a cpu, either through an explicit -mcpu=<xxx> or if the
4134      compiler was configured with --with-cpu=<xxx>, replace all of the ISA bits
4135      with those from the cpu, except for options that were explicitly set.  If
4136      we don't have a cpu, do not override the target bits set in
4137      TARGET_DEFAULT.  */
4138   if (cpu_index >= 0)
4139     {
4140       rs6000_cpu_index = cpu_index;
4141       rs6000_isa_flags &= ~set_masks;
4142       rs6000_isa_flags |= (processor_target_table[cpu_index].target_enable
4143                            & set_masks);
4144     }
4145   else
4146     {
4147       /* If no -mcpu=<xxx>, inherit any default options that were cleared via
4148          POWERPC_MASKS.  Originally, TARGET_DEFAULT was used to initialize
4149          target_flags via the TARGET_DEFAULT_TARGET_FLAGS hook.  When we switched
4150          to using rs6000_isa_flags, we need to do the initialization here.
4151
4152          If there is a TARGET_DEFAULT, use that.  Otherwise fall back to using
4153          -mcpu=powerpc, -mcpu=powerpc64, or -mcpu=powerpc64le defaults.  */
4154       HOST_WIDE_INT flags;
4155       if (TARGET_DEFAULT)
4156         flags = TARGET_DEFAULT;
4157       else
4158         {
4159           /* PowerPC 64-bit LE requires at least ISA 2.07.  */
4160           const char *default_cpu = (!TARGET_POWERPC64
4161                                      ? "powerpc"
4162                                      : (BYTES_BIG_ENDIAN
4163                                         ? "powerpc64"
4164                                         : "powerpc64le"));
4165           int default_cpu_index = rs6000_cpu_name_lookup (default_cpu);
4166           flags = processor_target_table[default_cpu_index].target_enable;
4167         }
4168       rs6000_isa_flags |= (flags & ~rs6000_isa_flags_explicit);
4169     }
4170
4171   if (rs6000_tune_index >= 0)
4172     tune_index = rs6000_tune_index;
4173   else if (cpu_index >= 0)
4174     rs6000_tune_index = tune_index = cpu_index;
4175   else
4176     {
4177       size_t i;
4178       enum processor_type tune_proc
4179         = (TARGET_POWERPC64 ? PROCESSOR_DEFAULT64 : PROCESSOR_DEFAULT);
4180
4181       tune_index = -1;
4182       for (i = 0; i < ARRAY_SIZE (processor_target_table); i++)
4183         if (processor_target_table[i].processor == tune_proc)
4184           {
4185             tune_index = i;
4186             break;
4187           }
4188     }
4189
4190   if (cpu_index >= 0)
4191     rs6000_cpu = processor_target_table[cpu_index].processor;
4192   else
4193     rs6000_cpu = TARGET_POWERPC64 ? PROCESSOR_DEFAULT64 : PROCESSOR_DEFAULT;
4194
4195   gcc_assert (tune_index >= 0);
4196   rs6000_tune = processor_target_table[tune_index].processor;
4197
4198   if (rs6000_cpu == PROCESSOR_PPCE300C2 || rs6000_cpu == PROCESSOR_PPCE300C3
4199       || rs6000_cpu == PROCESSOR_PPCE500MC || rs6000_cpu == PROCESSOR_PPCE500MC64
4200       || rs6000_cpu == PROCESSOR_PPCE5500)
4201     {
4202       if (TARGET_ALTIVEC)
4203         error ("AltiVec not supported in this target");
4204     }
4205
4206   /* If we are optimizing big endian systems for space, use the load/store
4207      multiple instructions.  */
4208   if (BYTES_BIG_ENDIAN && optimize_size)
4209     rs6000_isa_flags |= ~rs6000_isa_flags_explicit & OPTION_MASK_MULTIPLE;
4210
4211   /* Don't allow -mmultiple on little endian systems unless the cpu is a 750,
4212      because the hardware doesn't support the instructions used in little
4213      endian mode, and causes an alignment trap.  The 750 does not cause an
4214      alignment trap (except when the target is unaligned).  */
4215
4216   if (!BYTES_BIG_ENDIAN && rs6000_cpu != PROCESSOR_PPC750 && TARGET_MULTIPLE)
4217     {
4218       rs6000_isa_flags &= ~OPTION_MASK_MULTIPLE;
4219       if ((rs6000_isa_flags_explicit & OPTION_MASK_MULTIPLE) != 0)
4220         warning (0, "%qs is not supported on little endian systems",
4221                  "-mmultiple");
4222     }
4223
4224   /* If little-endian, default to -mstrict-align on older processors.
4225      Testing for htm matches power8 and later.  */
4226   if (!BYTES_BIG_ENDIAN
4227       && !(processor_target_table[tune_index].target_enable & OPTION_MASK_HTM))
4228     rs6000_isa_flags |= ~rs6000_isa_flags_explicit & OPTION_MASK_STRICT_ALIGN;
4229
4230   /* -maltivec={le,be} implies -maltivec.  */
4231   if (rs6000_altivec_element_order != 0)
4232     rs6000_isa_flags |= OPTION_MASK_ALTIVEC;
4233
4234   /* Disallow -maltivec=le in big endian mode for now.  This is not
4235      known to be useful for anyone.  */
4236   if (BYTES_BIG_ENDIAN && rs6000_altivec_element_order == 1)
4237     {
4238       warning (0, N_("-maltivec=le not allowed for big-endian targets"));
4239       rs6000_altivec_element_order = 0;
4240     }
4241
4242   if (!rs6000_fold_gimple)
4243      fprintf (stderr,
4244               "gimple folding of rs6000 builtins has been disabled.\n");
4245
4246   /* Add some warnings for VSX.  */
4247   if (TARGET_VSX)
4248     {
4249       const char *msg = NULL;
4250       if (!TARGET_HARD_FLOAT || !TARGET_SINGLE_FLOAT || !TARGET_DOUBLE_FLOAT)
4251         {
4252           if (rs6000_isa_flags_explicit & OPTION_MASK_VSX)
4253             msg = N_("-mvsx requires hardware floating point");
4254           else
4255             {
4256               rs6000_isa_flags &= ~ OPTION_MASK_VSX;
4257               rs6000_isa_flags_explicit |= OPTION_MASK_VSX;
4258             }
4259         }
4260       else if (TARGET_PAIRED_FLOAT)
4261         msg = N_("-mvsx and -mpaired are incompatible");
4262       else if (TARGET_AVOID_XFORM > 0)
4263         msg = N_("-mvsx needs indexed addressing");
4264       else if (!TARGET_ALTIVEC && (rs6000_isa_flags_explicit
4265                                    & OPTION_MASK_ALTIVEC))
4266         {
4267           if (rs6000_isa_flags_explicit & OPTION_MASK_VSX)
4268             msg = N_("-mvsx and -mno-altivec are incompatible");
4269           else
4270             msg = N_("-mno-altivec disables vsx");
4271         }
4272
4273       if (msg)
4274         {
4275           warning (0, msg);
4276           rs6000_isa_flags &= ~ OPTION_MASK_VSX;
4277           rs6000_isa_flags_explicit |= OPTION_MASK_VSX;
4278         }
4279     }
4280
4281   /* If hard-float/altivec/vsx were explicitly turned off then don't allow
4282      the -mcpu setting to enable options that conflict. */
4283   if ((!TARGET_HARD_FLOAT || !TARGET_ALTIVEC || !TARGET_VSX)
4284       && (rs6000_isa_flags_explicit & (OPTION_MASK_SOFT_FLOAT
4285                                        | OPTION_MASK_ALTIVEC
4286                                        | OPTION_MASK_VSX)) != 0)
4287     rs6000_isa_flags &= ~((OPTION_MASK_P8_VECTOR | OPTION_MASK_CRYPTO
4288                            | OPTION_MASK_DIRECT_MOVE)
4289                          & ~rs6000_isa_flags_explicit);
4290
4291   if (TARGET_DEBUG_REG || TARGET_DEBUG_TARGET)
4292     rs6000_print_isa_options (stderr, 0, "before defaults", rs6000_isa_flags);
4293
4294   /* Handle explicit -mno-{altivec,vsx,power8-vector,power9-vector} and turn
4295      off all of the options that depend on those flags.  */
4296   ignore_masks = rs6000_disable_incompatible_switches ();
4297
4298   /* For the newer switches (vsx, dfp, etc.) set some of the older options,
4299      unless the user explicitly used the -mno-<option> to disable the code.  */
4300   if (TARGET_P9_VECTOR || TARGET_MODULO || TARGET_P9_MISC)
4301     rs6000_isa_flags |= (ISA_3_0_MASKS_SERVER & ~ignore_masks);
4302   else if (TARGET_P9_MINMAX)
4303     {
4304       if (cpu_index >= 0)
4305         {
4306           if (cpu_index == PROCESSOR_POWER9)
4307             {
4308               /* legacy behavior: allow -mcpu=power9 with certain
4309                  capabilities explicitly disabled.  */
4310               rs6000_isa_flags |= (ISA_3_0_MASKS_SERVER & ~ignore_masks);
4311             }
4312           else
4313             error ("power9 target option is incompatible with %<%s=<xxx>%> "
4314                    "for <xxx> less than power9", "-mcpu");
4315         }
4316       else if ((ISA_3_0_MASKS_SERVER & rs6000_isa_flags_explicit)
4317                != (ISA_3_0_MASKS_SERVER & rs6000_isa_flags
4318                    & rs6000_isa_flags_explicit))
4319         /* Enforce that none of the ISA_3_0_MASKS_SERVER flags
4320            were explicitly cleared.  */
4321         error ("%qs incompatible with explicitly disabled options",
4322                "-mpower9-minmax");
4323       else
4324         rs6000_isa_flags |= ISA_3_0_MASKS_SERVER;
4325     }
4326   else if (TARGET_P8_VECTOR || TARGET_DIRECT_MOVE || TARGET_CRYPTO)
4327     rs6000_isa_flags |= (ISA_2_7_MASKS_SERVER & ~ignore_masks);
4328   else if (TARGET_VSX)
4329     rs6000_isa_flags |= (ISA_2_6_MASKS_SERVER & ~ignore_masks);
4330   else if (TARGET_POPCNTD)
4331     rs6000_isa_flags |= (ISA_2_6_MASKS_EMBEDDED & ~ignore_masks);
4332   else if (TARGET_DFP)
4333     rs6000_isa_flags |= (ISA_2_5_MASKS_SERVER & ~ignore_masks);
4334   else if (TARGET_CMPB)
4335     rs6000_isa_flags |= (ISA_2_5_MASKS_EMBEDDED & ~ignore_masks);
4336   else if (TARGET_FPRND)
4337     rs6000_isa_flags |= (ISA_2_4_MASKS & ~ignore_masks);
4338   else if (TARGET_POPCNTB)
4339     rs6000_isa_flags |= (ISA_2_2_MASKS & ~ignore_masks);
4340   else if (TARGET_ALTIVEC)
4341     rs6000_isa_flags |= (OPTION_MASK_PPC_GFXOPT & ~ignore_masks);
4342
4343   if (TARGET_CRYPTO && !TARGET_ALTIVEC)
4344     {
4345       if (rs6000_isa_flags_explicit & OPTION_MASK_CRYPTO)
4346         error ("%qs requires %qs", "-mcrypto", "-maltivec");
4347       rs6000_isa_flags &= ~OPTION_MASK_CRYPTO;
4348     }
4349
4350   if (TARGET_DIRECT_MOVE && !TARGET_VSX)
4351     {
4352       if (rs6000_isa_flags_explicit & OPTION_MASK_DIRECT_MOVE)
4353         error ("%qs requires %qs", "-mdirect-move", "-mvsx");
4354       rs6000_isa_flags &= ~OPTION_MASK_DIRECT_MOVE;
4355     }
4356
4357   if (TARGET_P8_VECTOR && !TARGET_ALTIVEC)
4358     {
4359       if (rs6000_isa_flags_explicit & OPTION_MASK_P8_VECTOR)
4360         error ("%qs requires %qs", "-mpower8-vector", "-maltivec");
4361       rs6000_isa_flags &= ~OPTION_MASK_P8_VECTOR;
4362     }
4363
4364   if (TARGET_P8_VECTOR && !TARGET_VSX)
4365     {
4366       if ((rs6000_isa_flags_explicit & OPTION_MASK_P8_VECTOR)
4367           && (rs6000_isa_flags_explicit & OPTION_MASK_VSX))
4368         error ("%qs requires %qs", "-mpower8-vector", "-mvsx");
4369       else if ((rs6000_isa_flags_explicit & OPTION_MASK_P8_VECTOR) == 0)
4370         {
4371           rs6000_isa_flags &= ~OPTION_MASK_P8_VECTOR;
4372           if (rs6000_isa_flags_explicit & OPTION_MASK_VSX)
4373             rs6000_isa_flags_explicit |= OPTION_MASK_P8_VECTOR;
4374         }
4375       else
4376         {
4377           /* OPTION_MASK_P8_VECTOR is explicit, and OPTION_MASK_VSX is
4378              not explicit.  */
4379           rs6000_isa_flags |= OPTION_MASK_VSX;
4380           rs6000_isa_flags_explicit |= OPTION_MASK_VSX;
4381         }
4382     }
4383
4384   if (TARGET_DFP && !TARGET_HARD_FLOAT)
4385     {
4386       if (rs6000_isa_flags_explicit & OPTION_MASK_DFP)
4387         error ("%qs requires %qs", "-mhard-dfp", "-mhard-float");
4388       rs6000_isa_flags &= ~OPTION_MASK_DFP;
4389     }
4390
4391   /* The quad memory instructions only works in 64-bit mode. In 32-bit mode,
4392      silently turn off quad memory mode.  */
4393   if ((TARGET_QUAD_MEMORY || TARGET_QUAD_MEMORY_ATOMIC) && !TARGET_POWERPC64)
4394     {
4395       if ((rs6000_isa_flags_explicit & OPTION_MASK_QUAD_MEMORY) != 0)
4396         warning (0, N_("-mquad-memory requires 64-bit mode"));
4397
4398       if ((rs6000_isa_flags_explicit & OPTION_MASK_QUAD_MEMORY_ATOMIC) != 0)
4399         warning (0, N_("-mquad-memory-atomic requires 64-bit mode"));
4400
4401       rs6000_isa_flags &= ~(OPTION_MASK_QUAD_MEMORY
4402                             | OPTION_MASK_QUAD_MEMORY_ATOMIC);
4403     }
4404
4405   /* Non-atomic quad memory load/store are disabled for little endian, since
4406      the words are reversed, but atomic operations can still be done by
4407      swapping the words.  */
4408   if (TARGET_QUAD_MEMORY && !WORDS_BIG_ENDIAN)
4409     {
4410       if ((rs6000_isa_flags_explicit & OPTION_MASK_QUAD_MEMORY) != 0)
4411         warning (0, N_("-mquad-memory is not available in little endian "
4412                        "mode"));
4413
4414       rs6000_isa_flags &= ~OPTION_MASK_QUAD_MEMORY;
4415     }
4416
4417   /* Assume if the user asked for normal quad memory instructions, they want
4418      the atomic versions as well, unless they explicity told us not to use quad
4419      word atomic instructions.  */
4420   if (TARGET_QUAD_MEMORY
4421       && !TARGET_QUAD_MEMORY_ATOMIC
4422       && ((rs6000_isa_flags_explicit & OPTION_MASK_QUAD_MEMORY_ATOMIC) == 0))
4423     rs6000_isa_flags |= OPTION_MASK_QUAD_MEMORY_ATOMIC;
4424
4425   /* If we can shrink-wrap the TOC register save separately, then use
4426      -msave-toc-indirect unless explicitly disabled.  */
4427   if ((rs6000_isa_flags_explicit & OPTION_MASK_SAVE_TOC_INDIRECT) == 0
4428       && flag_shrink_wrap_separate
4429       && optimize_function_for_speed_p (cfun))
4430     rs6000_isa_flags |= OPTION_MASK_SAVE_TOC_INDIRECT;
4431
4432   /* Enable power8 fusion if we are tuning for power8, even if we aren't
4433      generating power8 instructions.  */
4434   if (!(rs6000_isa_flags_explicit & OPTION_MASK_P8_FUSION))
4435     rs6000_isa_flags |= (processor_target_table[tune_index].target_enable
4436                          & OPTION_MASK_P8_FUSION);
4437
4438   /* Setting additional fusion flags turns on base fusion.  */
4439   if (!TARGET_P8_FUSION && (TARGET_P8_FUSION_SIGN || TARGET_TOC_FUSION))
4440     {
4441       if (rs6000_isa_flags_explicit & OPTION_MASK_P8_FUSION)
4442         {
4443           if (TARGET_P8_FUSION_SIGN)
4444             error ("%qs requires %qs", "-mpower8-fusion-sign",
4445                    "-mpower8-fusion");
4446
4447           if (TARGET_TOC_FUSION)
4448             error ("%qs requires %qs", "-mtoc-fusion", "-mpower8-fusion");
4449
4450           rs6000_isa_flags &= ~OPTION_MASK_P8_FUSION;
4451         }
4452       else
4453         rs6000_isa_flags |= OPTION_MASK_P8_FUSION;
4454     }
4455
4456   /* Power9 fusion is a superset over power8 fusion.  */
4457   if (TARGET_P9_FUSION && !TARGET_P8_FUSION)
4458     {
4459       if (rs6000_isa_flags_explicit & OPTION_MASK_P8_FUSION)
4460         {
4461           /* We prefer to not mention undocumented options in
4462              error messages.  However, if users have managed to select
4463              power9-fusion without selecting power8-fusion, they
4464              already know about undocumented flags.  */
4465           error ("%qs requires %qs", "-mpower9-fusion", "-mpower8-fusion");
4466           rs6000_isa_flags &= ~OPTION_MASK_P9_FUSION;
4467         }
4468       else
4469         rs6000_isa_flags |= OPTION_MASK_P8_FUSION;
4470     }
4471
4472   /* Enable power9 fusion if we are tuning for power9, even if we aren't
4473      generating power9 instructions.  */
4474   if (!(rs6000_isa_flags_explicit & OPTION_MASK_P9_FUSION))
4475     rs6000_isa_flags |= (processor_target_table[tune_index].target_enable
4476                          & OPTION_MASK_P9_FUSION);
4477
4478   /* Power8 does not fuse sign extended loads with the addis.  If we are
4479      optimizing at high levels for speed, convert a sign extended load into a
4480      zero extending load, and an explicit sign extension.  */
4481   if (TARGET_P8_FUSION
4482       && !(rs6000_isa_flags_explicit & OPTION_MASK_P8_FUSION_SIGN)
4483       && optimize_function_for_speed_p (cfun)
4484       && optimize >= 3)
4485     rs6000_isa_flags |= OPTION_MASK_P8_FUSION_SIGN;
4486
4487   /* TOC fusion requires 64-bit and medium/large code model.  */
4488   if (TARGET_TOC_FUSION && !TARGET_POWERPC64)
4489     {
4490       rs6000_isa_flags &= ~OPTION_MASK_TOC_FUSION;
4491       if ((rs6000_isa_flags_explicit & OPTION_MASK_TOC_FUSION) != 0)
4492         warning (0, N_("-mtoc-fusion requires 64-bit"));
4493     }
4494
4495   if (TARGET_TOC_FUSION && (TARGET_CMODEL == CMODEL_SMALL))
4496     {
4497       rs6000_isa_flags &= ~OPTION_MASK_TOC_FUSION;
4498       if ((rs6000_isa_flags_explicit & OPTION_MASK_TOC_FUSION) != 0)
4499         warning (0, N_("-mtoc-fusion requires medium/large code model"));
4500     }
4501
4502   /* Turn on -mtoc-fusion by default if p8-fusion and 64-bit medium/large code
4503      model.  */
4504   if (TARGET_P8_FUSION && !TARGET_TOC_FUSION && TARGET_POWERPC64
4505       && (TARGET_CMODEL != CMODEL_SMALL)
4506       && !(rs6000_isa_flags_explicit & OPTION_MASK_TOC_FUSION))
4507     rs6000_isa_flags |= OPTION_MASK_TOC_FUSION;
4508
4509   /* ISA 3.0 vector instructions include ISA 2.07.  */
4510   if (TARGET_P9_VECTOR && !TARGET_P8_VECTOR)
4511     {
4512       /* We prefer to not mention undocumented options in
4513          error messages.  However, if users have managed to select
4514          power9-vector without selecting power8-vector, they
4515          already know about undocumented flags.  */
4516       if ((rs6000_isa_flags_explicit & OPTION_MASK_P9_VECTOR) &&
4517           (rs6000_isa_flags_explicit & OPTION_MASK_P8_VECTOR))
4518         error ("%qs requires %qs", "-mpower9-vector", "-mpower8-vector");
4519       else if ((rs6000_isa_flags_explicit & OPTION_MASK_P9_VECTOR) == 0)
4520         {
4521           rs6000_isa_flags &= ~OPTION_MASK_P9_VECTOR;
4522           if (rs6000_isa_flags_explicit & OPTION_MASK_P8_VECTOR)
4523             rs6000_isa_flags_explicit |= OPTION_MASK_P9_VECTOR;
4524         }
4525       else
4526         {
4527           /* OPTION_MASK_P9_VECTOR is explicit and
4528              OPTION_MASK_P8_VECTOR is not explicit.  */
4529           rs6000_isa_flags |= OPTION_MASK_P8_VECTOR;
4530           rs6000_isa_flags_explicit |= OPTION_MASK_P8_VECTOR;
4531         }
4532     }
4533
4534   /* Set -mallow-movmisalign to explicitly on if we have full ISA 2.07
4535      support. If we only have ISA 2.06 support, and the user did not specify
4536      the switch, leave it set to -1 so the movmisalign patterns are enabled,
4537      but we don't enable the full vectorization support  */
4538   if (TARGET_ALLOW_MOVMISALIGN == -1 && TARGET_P8_VECTOR && TARGET_DIRECT_MOVE)
4539     TARGET_ALLOW_MOVMISALIGN = 1;
4540
4541   else if (TARGET_ALLOW_MOVMISALIGN && !TARGET_VSX)
4542     {
4543       if (TARGET_ALLOW_MOVMISALIGN > 0
4544           && global_options_set.x_TARGET_ALLOW_MOVMISALIGN)
4545         error ("%qs requires %qs", "-mallow-movmisalign", "-mvsx");
4546
4547       TARGET_ALLOW_MOVMISALIGN = 0;
4548     }
4549
4550   /* Determine when unaligned vector accesses are permitted, and when
4551      they are preferred over masked Altivec loads.  Note that if
4552      TARGET_ALLOW_MOVMISALIGN has been disabled by the user, then
4553      TARGET_EFFICIENT_UNALIGNED_VSX must be as well.  The converse is
4554      not true.  */
4555   if (TARGET_EFFICIENT_UNALIGNED_VSX)
4556     {
4557       if (!TARGET_VSX)
4558         {
4559           if (rs6000_isa_flags_explicit & OPTION_MASK_EFFICIENT_UNALIGNED_VSX)
4560             error ("%qs requires %qs", "-mefficient-unaligned-vsx", "-mvsx");
4561
4562           rs6000_isa_flags &= ~OPTION_MASK_EFFICIENT_UNALIGNED_VSX;
4563         }
4564
4565       else if (!TARGET_ALLOW_MOVMISALIGN)
4566         {
4567           if (rs6000_isa_flags_explicit & OPTION_MASK_EFFICIENT_UNALIGNED_VSX)
4568             error ("%qs requires %qs", "-munefficient-unaligned-vsx",
4569                    "-mallow-movmisalign");
4570
4571           rs6000_isa_flags &= ~OPTION_MASK_EFFICIENT_UNALIGNED_VSX;
4572         }
4573     }
4574
4575   /* Set long double size before the IEEE 128-bit tests.  */
4576   if (!global_options_set.x_rs6000_long_double_type_size)
4577     {
4578       if (main_target_opt != NULL
4579           && (main_target_opt->x_rs6000_long_double_type_size
4580               != RS6000_DEFAULT_LONG_DOUBLE_SIZE))
4581         error ("target attribute or pragma changes long double size");
4582       else
4583         rs6000_long_double_type_size = RS6000_DEFAULT_LONG_DOUBLE_SIZE;
4584     }
4585
4586   /* Set -mabi=ieeelongdouble on some old targets.  In the future, power server
4587      systems will also set long double to be IEEE 128-bit.  AIX and Darwin
4588      explicitly redefine TARGET_IEEEQUAD and TARGET_IEEEQUAD_DEFAULT to 0, so
4589      those systems will not pick up this default.  Warn if the user changes the
4590      default unless either the user used the -Wno-psabi option, or the compiler
4591      was built to enable multilibs to switch between the two long double
4592      types.  */
4593   if (!global_options_set.x_rs6000_ieeequad)
4594     rs6000_ieeequad = TARGET_IEEEQUAD_DEFAULT;
4595
4596   else if (!TARGET_IEEEQUAD_MULTILIB
4597            && rs6000_ieeequad != TARGET_IEEEQUAD_DEFAULT
4598            && TARGET_LONG_DOUBLE_128)
4599     {
4600       static bool warned_change_long_double;
4601       if (!warned_change_long_double)
4602         {
4603           warned_change_long_double = true;
4604           if (TARGET_IEEEQUAD)
4605             warning (OPT_Wpsabi, "Using IEEE extended precision long double");
4606           else
4607             warning (OPT_Wpsabi, "Using IBM extended precision long double");
4608         }
4609     }
4610
4611   /* Enable the default support for IEEE 128-bit floating point on Linux VSX
4612      sytems.  In GCC 7, we would enable the the IEEE 128-bit floating point
4613      infrastructure (-mfloat128-type) but not enable the actual __float128 type
4614      unless the user used the explicit -mfloat128.  In GCC 8, we enable both
4615      the keyword as well as the type.  */
4616   TARGET_FLOAT128_TYPE = TARGET_FLOAT128_ENABLE_TYPE && TARGET_VSX;
4617
4618   /* IEEE 128-bit floating point requires VSX support.  */
4619   if (TARGET_FLOAT128_KEYWORD)
4620     {
4621       if (!TARGET_VSX)
4622         {
4623           if ((rs6000_isa_flags_explicit & OPTION_MASK_FLOAT128_KEYWORD) != 0)
4624             error ("%qs requires VSX support", "-mfloat128");
4625
4626           TARGET_FLOAT128_TYPE = 0;
4627           rs6000_isa_flags &= ~(OPTION_MASK_FLOAT128_KEYWORD
4628                                 | OPTION_MASK_FLOAT128_HW);
4629         }
4630       else if (!TARGET_FLOAT128_TYPE)
4631         {
4632           TARGET_FLOAT128_TYPE = 1;
4633           warning (0, "The -mfloat128 option may not be fully supported");
4634         }
4635     }
4636
4637   /* Enable the __float128 keyword under Linux by default.  */
4638   if (TARGET_FLOAT128_TYPE && !TARGET_FLOAT128_KEYWORD
4639       && (rs6000_isa_flags_explicit & OPTION_MASK_FLOAT128_KEYWORD) == 0)
4640     rs6000_isa_flags |= OPTION_MASK_FLOAT128_KEYWORD;
4641
4642   /* If we have are supporting the float128 type and full ISA 3.0 support,
4643      enable -mfloat128-hardware by default.  However, don't enable the
4644      __float128 keyword if it was explicitly turned off.  64-bit mode is needed
4645      because sometimes the compiler wants to put things in an integer
4646      container, and if we don't have __int128 support, it is impossible.  */
4647   if (TARGET_FLOAT128_TYPE && !TARGET_FLOAT128_HW && TARGET_64BIT
4648       && (rs6000_isa_flags & ISA_3_0_MASKS_IEEE) == ISA_3_0_MASKS_IEEE
4649       && !(rs6000_isa_flags_explicit & OPTION_MASK_FLOAT128_HW))
4650     rs6000_isa_flags |= OPTION_MASK_FLOAT128_HW;
4651
4652   if (TARGET_FLOAT128_HW
4653       && (rs6000_isa_flags & ISA_3_0_MASKS_IEEE) != ISA_3_0_MASKS_IEEE)
4654     {
4655       if ((rs6000_isa_flags_explicit & OPTION_MASK_FLOAT128_HW) != 0)
4656         error ("%qs requires full ISA 3.0 support", "-mfloat128-hardware");
4657
4658       rs6000_isa_flags &= ~OPTION_MASK_FLOAT128_HW;
4659     }
4660
4661   if (TARGET_FLOAT128_HW && !TARGET_64BIT)
4662     {
4663       if ((rs6000_isa_flags_explicit & OPTION_MASK_FLOAT128_HW) != 0)
4664         error ("%qs requires %qs", "-mfloat128-hardware", "-m64");
4665
4666       rs6000_isa_flags &= ~OPTION_MASK_FLOAT128_HW;
4667     }
4668
4669   /* Print the options after updating the defaults.  */
4670   if (TARGET_DEBUG_REG || TARGET_DEBUG_TARGET)
4671     rs6000_print_isa_options (stderr, 0, "after defaults", rs6000_isa_flags);
4672
4673   /* E500mc does "better" if we inline more aggressively.  Respect the
4674      user's opinion, though.  */
4675   if (rs6000_block_move_inline_limit == 0
4676       && (rs6000_tune == PROCESSOR_PPCE500MC
4677           || rs6000_tune == PROCESSOR_PPCE500MC64
4678           || rs6000_tune == PROCESSOR_PPCE5500
4679           || rs6000_tune == PROCESSOR_PPCE6500))
4680     rs6000_block_move_inline_limit = 128;
4681
4682   /* store_one_arg depends on expand_block_move to handle at least the
4683      size of reg_parm_stack_space.  */
4684   if (rs6000_block_move_inline_limit < (TARGET_POWERPC64 ? 64 : 32))
4685     rs6000_block_move_inline_limit = (TARGET_POWERPC64 ? 64 : 32);
4686
4687   if (global_init_p)
4688     {
4689       /* If the appropriate debug option is enabled, replace the target hooks
4690          with debug versions that call the real version and then prints
4691          debugging information.  */
4692       if (TARGET_DEBUG_COST)
4693         {
4694           targetm.rtx_costs = rs6000_debug_rtx_costs;
4695           targetm.address_cost = rs6000_debug_address_cost;
4696           targetm.sched.adjust_cost = rs6000_debug_adjust_cost;
4697         }
4698
4699       if (TARGET_DEBUG_ADDR)
4700         {
4701           targetm.legitimate_address_p = rs6000_debug_legitimate_address_p;
4702           targetm.legitimize_address = rs6000_debug_legitimize_address;
4703           rs6000_secondary_reload_class_ptr
4704             = rs6000_debug_secondary_reload_class;
4705           targetm.secondary_memory_needed
4706             = rs6000_debug_secondary_memory_needed;
4707           targetm.can_change_mode_class
4708             = rs6000_debug_can_change_mode_class;
4709           rs6000_preferred_reload_class_ptr
4710             = rs6000_debug_preferred_reload_class;
4711           rs6000_legitimize_reload_address_ptr
4712             = rs6000_debug_legitimize_reload_address;
4713           rs6000_mode_dependent_address_ptr
4714             = rs6000_debug_mode_dependent_address;
4715         }
4716
4717       if (rs6000_veclibabi_name)
4718         {
4719           if (strcmp (rs6000_veclibabi_name, "mass") == 0)
4720             rs6000_veclib_handler = rs6000_builtin_vectorized_libmass;
4721           else
4722             {
4723               error ("unknown vectorization library ABI type (%qs) for "
4724                      "%qs switch", rs6000_veclibabi_name, "-mveclibabi=");
4725               ret = false;
4726             }
4727         }
4728     }
4729
4730   /* Disable VSX and Altivec silently if the user switched cpus to power7 in a
4731      target attribute or pragma which automatically enables both options,
4732      unless the altivec ABI was set.  This is set by default for 64-bit, but
4733      not for 32-bit.  */
4734   if (main_target_opt != NULL && !main_target_opt->x_rs6000_altivec_abi)
4735     {
4736       TARGET_FLOAT128_TYPE = 0;
4737       rs6000_isa_flags &= ~((OPTION_MASK_VSX | OPTION_MASK_ALTIVEC
4738                              | OPTION_MASK_FLOAT128_KEYWORD)
4739                             & ~rs6000_isa_flags_explicit);
4740     }
4741
4742   /* Enable Altivec ABI for AIX -maltivec.  */
4743   if (TARGET_XCOFF && (TARGET_ALTIVEC || TARGET_VSX))
4744     {
4745       if (main_target_opt != NULL && !main_target_opt->x_rs6000_altivec_abi)
4746         error ("target attribute or pragma changes AltiVec ABI");
4747       else
4748         rs6000_altivec_abi = 1;
4749     }
4750
4751   /* The AltiVec ABI is the default for PowerPC-64 GNU/Linux.  For
4752      PowerPC-32 GNU/Linux, -maltivec implies the AltiVec ABI.  It can
4753      be explicitly overridden in either case.  */
4754   if (TARGET_ELF)
4755     {
4756       if (!global_options_set.x_rs6000_altivec_abi
4757           && (TARGET_64BIT || TARGET_ALTIVEC || TARGET_VSX))
4758         {
4759           if (main_target_opt != NULL &&
4760               !main_target_opt->x_rs6000_altivec_abi)
4761             error ("target attribute or pragma changes AltiVec ABI");
4762           else
4763             rs6000_altivec_abi = 1;
4764         }
4765     }
4766
4767   /* Set the Darwin64 ABI as default for 64-bit Darwin.  
4768      So far, the only darwin64 targets are also MACH-O.  */
4769   if (TARGET_MACHO
4770       && DEFAULT_ABI == ABI_DARWIN 
4771       && TARGET_64BIT)
4772     {
4773       if (main_target_opt != NULL && !main_target_opt->x_rs6000_darwin64_abi)
4774         error ("target attribute or pragma changes darwin64 ABI");
4775       else
4776         {
4777           rs6000_darwin64_abi = 1;
4778           /* Default to natural alignment, for better performance.  */
4779           rs6000_alignment_flags = MASK_ALIGN_NATURAL;
4780         }
4781     }
4782
4783   /* Place FP constants in the constant pool instead of TOC
4784      if section anchors enabled.  */
4785   if (flag_section_anchors
4786       && !global_options_set.x_TARGET_NO_FP_IN_TOC)
4787     TARGET_NO_FP_IN_TOC = 1;
4788
4789   if (TARGET_DEBUG_REG || TARGET_DEBUG_TARGET)
4790     rs6000_print_isa_options (stderr, 0, "before subtarget", rs6000_isa_flags);
4791
4792 #ifdef SUBTARGET_OVERRIDE_OPTIONS
4793   SUBTARGET_OVERRIDE_OPTIONS;
4794 #endif
4795 #ifdef SUBSUBTARGET_OVERRIDE_OPTIONS
4796   SUBSUBTARGET_OVERRIDE_OPTIONS;
4797 #endif
4798 #ifdef SUB3TARGET_OVERRIDE_OPTIONS
4799   SUB3TARGET_OVERRIDE_OPTIONS;
4800 #endif
4801
4802   if (TARGET_DEBUG_REG || TARGET_DEBUG_TARGET)
4803     rs6000_print_isa_options (stderr, 0, "after subtarget", rs6000_isa_flags);
4804
4805   /* For the E500 family of cores, reset the single/double FP flags to let us
4806      check that they remain constant across attributes or pragmas.  */
4807
4808   switch (rs6000_cpu)
4809     {
4810     case PROCESSOR_PPC8540:
4811     case PROCESSOR_PPC8548:
4812     case PROCESSOR_PPCE500MC:
4813     case PROCESSOR_PPCE500MC64:
4814     case PROCESSOR_PPCE5500:
4815     case PROCESSOR_PPCE6500:
4816       rs6000_single_float = 0;
4817       rs6000_double_float = 0;
4818       break;
4819
4820     default:
4821       break;
4822     }
4823
4824   if (main_target_opt)
4825     {
4826       if (main_target_opt->x_rs6000_single_float != rs6000_single_float)
4827         error ("target attribute or pragma changes single precision floating "
4828                "point");
4829       if (main_target_opt->x_rs6000_double_float != rs6000_double_float)
4830         error ("target attribute or pragma changes double precision floating "
4831                "point");
4832     }
4833
4834   rs6000_always_hint = (rs6000_tune != PROCESSOR_POWER4
4835                         && rs6000_tune != PROCESSOR_POWER5
4836                         && rs6000_tune != PROCESSOR_POWER6
4837                         && rs6000_tune != PROCESSOR_POWER7
4838                         && rs6000_tune != PROCESSOR_POWER8
4839                         && rs6000_tune != PROCESSOR_POWER9
4840                         && rs6000_tune != PROCESSOR_PPCA2
4841                         && rs6000_tune != PROCESSOR_CELL
4842                         && rs6000_tune != PROCESSOR_PPC476);
4843   rs6000_sched_groups = (rs6000_tune == PROCESSOR_POWER4
4844                          || rs6000_tune == PROCESSOR_POWER5
4845                          || rs6000_tune == PROCESSOR_POWER7
4846                          || rs6000_tune == PROCESSOR_POWER8);
4847   rs6000_align_branch_targets = (rs6000_tune == PROCESSOR_POWER4
4848                                  || rs6000_tune == PROCESSOR_POWER5
4849                                  || rs6000_tune == PROCESSOR_POWER6
4850                                  || rs6000_tune == PROCESSOR_POWER7
4851                                  || rs6000_tune == PROCESSOR_POWER8
4852                                  || rs6000_tune == PROCESSOR_POWER9
4853                                  || rs6000_tune == PROCESSOR_PPCE500MC
4854                                  || rs6000_tune == PROCESSOR_PPCE500MC64
4855                                  || rs6000_tune == PROCESSOR_PPCE5500
4856                                  || rs6000_tune == PROCESSOR_PPCE6500);
4857
4858   /* Allow debug switches to override the above settings.  These are set to -1
4859      in rs6000.opt to indicate the user hasn't directly set the switch.  */
4860   if (TARGET_ALWAYS_HINT >= 0)
4861     rs6000_always_hint = TARGET_ALWAYS_HINT;
4862
4863   if (TARGET_SCHED_GROUPS >= 0)
4864     rs6000_sched_groups = TARGET_SCHED_GROUPS;
4865
4866   if (TARGET_ALIGN_BRANCH_TARGETS >= 0)
4867     rs6000_align_branch_targets = TARGET_ALIGN_BRANCH_TARGETS;
4868
4869   rs6000_sched_restricted_insns_priority
4870     = (rs6000_sched_groups ? 1 : 0);
4871
4872   /* Handle -msched-costly-dep option.  */
4873   rs6000_sched_costly_dep
4874     = (rs6000_sched_groups ? true_store_to_load_dep_costly : no_dep_costly);
4875
4876   if (rs6000_sched_costly_dep_str)
4877     {
4878       if (! strcmp (rs6000_sched_costly_dep_str, "no"))
4879         rs6000_sched_costly_dep = no_dep_costly;
4880       else if (! strcmp (rs6000_sched_costly_dep_str, "all"))
4881         rs6000_sched_costly_dep = all_deps_costly;
4882       else if (! strcmp (rs6000_sched_costly_dep_str, "true_store_to_load"))
4883         rs6000_sched_costly_dep = true_store_to_load_dep_costly;
4884       else if (! strcmp (rs6000_sched_costly_dep_str, "store_to_load"))
4885         rs6000_sched_costly_dep = store_to_load_dep_costly;
4886       else
4887         rs6000_sched_costly_dep = ((enum rs6000_dependence_cost)
4888                                    atoi (rs6000_sched_costly_dep_str));
4889     }
4890
4891   /* Handle -minsert-sched-nops option.  */
4892   rs6000_sched_insert_nops
4893     = (rs6000_sched_groups ? sched_finish_regroup_exact : sched_finish_none);
4894
4895   if (rs6000_sched_insert_nops_str)
4896     {
4897       if (! strcmp (rs6000_sched_insert_nops_str, "no"))
4898         rs6000_sched_insert_nops = sched_finish_none;
4899       else if (! strcmp (rs6000_sched_insert_nops_str, "pad"))
4900         rs6000_sched_insert_nops = sched_finish_pad_groups;
4901       else if (! strcmp (rs6000_sched_insert_nops_str, "regroup_exact"))
4902         rs6000_sched_insert_nops = sched_finish_regroup_exact;
4903       else
4904         rs6000_sched_insert_nops = ((enum rs6000_nop_insertion)
4905                                     atoi (rs6000_sched_insert_nops_str));
4906     }
4907
4908   /* Handle stack protector */
4909   if (!global_options_set.x_rs6000_stack_protector_guard)
4910 #ifdef TARGET_THREAD_SSP_OFFSET
4911     rs6000_stack_protector_guard = SSP_TLS;
4912 #else
4913     rs6000_stack_protector_guard = SSP_GLOBAL;
4914 #endif
4915
4916 #ifdef TARGET_THREAD_SSP_OFFSET
4917   rs6000_stack_protector_guard_offset = TARGET_THREAD_SSP_OFFSET;
4918   rs6000_stack_protector_guard_reg = TARGET_64BIT ? 13 : 2;
4919 #endif
4920
4921   if (global_options_set.x_rs6000_stack_protector_guard_offset_str)
4922     {
4923       char *endp;
4924       const char *str = rs6000_stack_protector_guard_offset_str;
4925
4926       errno = 0;
4927       long offset = strtol (str, &endp, 0);
4928       if (!*str || *endp || errno)
4929         error ("%qs is not a valid number in %qs", str,
4930                "-mstack-protector-guard-offset=");
4931
4932       if (!IN_RANGE (offset, -0x8000, 0x7fff)
4933           || (TARGET_64BIT && (offset & 3)))
4934         error ("%qs is not a valid offset in %qs", str,
4935                "-mstack-protector-guard-offset=");
4936
4937       rs6000_stack_protector_guard_offset = offset;
4938     }
4939
4940   if (global_options_set.x_rs6000_stack_protector_guard_reg_str)
4941     {
4942       const char *str = rs6000_stack_protector_guard_reg_str;
4943       int reg = decode_reg_name (str);
4944
4945       if (!IN_RANGE (reg, 1, 31))
4946         error ("%qs is not a valid base register in %qs", str,
4947                "-mstack-protector-guard-reg=");
4948
4949       rs6000_stack_protector_guard_reg = reg;
4950     }
4951
4952   if (rs6000_stack_protector_guard == SSP_TLS
4953       && !IN_RANGE (rs6000_stack_protector_guard_reg, 1, 31))
4954     error ("%qs needs a valid base register", "-mstack-protector-guard=tls");
4955
4956   if (global_init_p)
4957     {
4958 #ifdef TARGET_REGNAMES
4959       /* If the user desires alternate register names, copy in the
4960          alternate names now.  */
4961       if (TARGET_REGNAMES)
4962         memcpy (rs6000_reg_names, alt_reg_names, sizeof (rs6000_reg_names));
4963 #endif
4964
4965       /* Set aix_struct_return last, after the ABI is determined.
4966          If -maix-struct-return or -msvr4-struct-return was explicitly
4967          used, don't override with the ABI default.  */
4968       if (!global_options_set.x_aix_struct_return)
4969         aix_struct_return = (DEFAULT_ABI != ABI_V4 || DRAFT_V4_STRUCT_RET);
4970
4971 #if 0
4972       /* IBM XL compiler defaults to unsigned bitfields.  */
4973       if (TARGET_XL_COMPAT)
4974         flag_signed_bitfields = 0;
4975 #endif
4976
4977       if (TARGET_LONG_DOUBLE_128 && !TARGET_IEEEQUAD)
4978         REAL_MODE_FORMAT (TFmode) = &ibm_extended_format;
4979
4980       ASM_GENERATE_INTERNAL_LABEL (toc_label_name, "LCTOC", 1);
4981
4982       /* We can only guarantee the availability of DI pseudo-ops when
4983          assembling for 64-bit targets.  */
4984       if (!TARGET_64BIT)
4985         {
4986           targetm.asm_out.aligned_op.di = NULL;
4987           targetm.asm_out.unaligned_op.di = NULL;
4988         }
4989
4990
4991       /* Set branch target alignment, if not optimizing for size.  */
4992       if (!optimize_size)
4993         {
4994           /* Cell wants to be aligned 8byte for dual issue.  Titan wants to be
4995              aligned 8byte to avoid misprediction by the branch predictor.  */
4996           if (rs6000_tune == PROCESSOR_TITAN
4997               || rs6000_tune == PROCESSOR_CELL)
4998             {
4999               if (align_functions <= 0)
5000                 align_functions = 8;
5001               if (align_jumps <= 0)
5002                 align_jumps = 8;
5003               if (align_loops <= 0)
5004                 align_loops = 8;
5005             }
5006           if (rs6000_align_branch_targets)
5007             {
5008               if (align_functions <= 0)
5009                 align_functions = 16;
5010               if (align_jumps <= 0)
5011                 align_jumps = 16;
5012               if (align_loops <= 0)
5013                 {
5014                   can_override_loop_align = 1;
5015                   align_loops = 16;
5016                 }
5017             }
5018           if (align_jumps_max_skip <= 0)
5019             align_jumps_max_skip = 15;
5020           if (align_loops_max_skip <= 0)
5021             align_loops_max_skip = 15;
5022         }
5023
5024       /* Arrange to save and restore machine status around nested functions.  */
5025       init_machine_status = rs6000_init_machine_status;
5026
5027       /* We should always be splitting complex arguments, but we can't break
5028          Linux and Darwin ABIs at the moment.  For now, only AIX is fixed.  */
5029       if (DEFAULT_ABI == ABI_V4 || DEFAULT_ABI == ABI_DARWIN)
5030         targetm.calls.split_complex_arg = NULL;
5031
5032       /* The AIX and ELFv1 ABIs define standard function descriptors.  */
5033       if (DEFAULT_ABI == ABI_AIX)
5034         targetm.calls.custom_function_descriptors = 0;
5035     }
5036
5037   /* Initialize rs6000_cost with the appropriate target costs.  */
5038   if (optimize_size)
5039     rs6000_cost = TARGET_POWERPC64 ? &size64_cost : &size32_cost;
5040   else
5041     switch (rs6000_tune)
5042       {
5043       case PROCESSOR_RS64A:
5044         rs6000_cost = &rs64a_cost;
5045         break;
5046
5047       case PROCESSOR_MPCCORE:
5048         rs6000_cost = &mpccore_cost;
5049         break;
5050
5051       case PROCESSOR_PPC403:
5052         rs6000_cost = &ppc403_cost;
5053         break;
5054
5055       case PROCESSOR_PPC405:
5056         rs6000_cost = &ppc405_cost;
5057         break;
5058
5059       case PROCESSOR_PPC440:
5060         rs6000_cost = &ppc440_cost;
5061         break;
5062
5063       case PROCESSOR_PPC476:
5064         rs6000_cost = &ppc476_cost;
5065         break;
5066
5067       case PROCESSOR_PPC601:
5068         rs6000_cost = &ppc601_cost;
5069         break;
5070
5071       case PROCESSOR_PPC603:
5072         rs6000_cost = &ppc603_cost;
5073         break;
5074
5075       case PROCESSOR_PPC604:
5076         rs6000_cost = &ppc604_cost;
5077         break;
5078
5079       case PROCESSOR_PPC604e:
5080         rs6000_cost = &ppc604e_cost;
5081         break;
5082
5083       case PROCESSOR_PPC620:
5084         rs6000_cost = &ppc620_cost;
5085         break;
5086
5087       case PROCESSOR_PPC630:
5088         rs6000_cost = &ppc630_cost;
5089         break;
5090
5091       case PROCESSOR_CELL:
5092         rs6000_cost = &ppccell_cost;
5093         break;
5094
5095       case PROCESSOR_PPC750:
5096       case PROCESSOR_PPC7400:
5097         rs6000_cost = &ppc750_cost;
5098         break;
5099
5100       case PROCESSOR_PPC7450:
5101         rs6000_cost = &ppc7450_cost;
5102         break;
5103
5104       case PROCESSOR_PPC8540:
5105       case PROCESSOR_PPC8548:
5106         rs6000_cost = &ppc8540_cost;
5107         break;
5108
5109       case PROCESSOR_PPCE300C2:
5110       case PROCESSOR_PPCE300C3:
5111         rs6000_cost = &ppce300c2c3_cost;
5112         break;
5113
5114       case PROCESSOR_PPCE500MC:
5115         rs6000_cost = &ppce500mc_cost;
5116         break;
5117
5118       case PROCESSOR_PPCE500MC64:
5119         rs6000_cost = &ppce500mc64_cost;
5120         break;
5121
5122       case PROCESSOR_PPCE5500:
5123         rs6000_cost = &ppce5500_cost;
5124         break;
5125
5126       case PROCESSOR_PPCE6500:
5127         rs6000_cost = &ppce6500_cost;
5128         break;
5129
5130       case PROCESSOR_TITAN:
5131         rs6000_cost = &titan_cost;
5132         break;
5133
5134       case PROCESSOR_POWER4:
5135       case PROCESSOR_POWER5:
5136         rs6000_cost = &power4_cost;
5137         break;
5138
5139       case PROCESSOR_POWER6:
5140         rs6000_cost = &power6_cost;
5141         break;
5142
5143       case PROCESSOR_POWER7:
5144         rs6000_cost = &power7_cost;
5145         break;
5146
5147       case PROCESSOR_POWER8:
5148         rs6000_cost = &power8_cost;
5149         break;
5150
5151       case PROCESSOR_POWER9:
5152         rs6000_cost = &power9_cost;
5153         break;
5154
5155       case PROCESSOR_PPCA2:
5156         rs6000_cost = &ppca2_cost;
5157         break;
5158
5159       default:
5160         gcc_unreachable ();
5161       }
5162
5163   if (global_init_p)
5164     {
5165       maybe_set_param_value (PARAM_SIMULTANEOUS_PREFETCHES,
5166                              rs6000_cost->simultaneous_prefetches,
5167                              global_options.x_param_values,
5168                              global_options_set.x_param_values);
5169       maybe_set_param_value (PARAM_L1_CACHE_SIZE, rs6000_cost->l1_cache_size,
5170                              global_options.x_param_values,
5171                              global_options_set.x_param_values);
5172       maybe_set_param_value (PARAM_L1_CACHE_LINE_SIZE,
5173                              rs6000_cost->cache_line_size,
5174                              global_options.x_param_values,
5175                              global_options_set.x_param_values);
5176       maybe_set_param_value (PARAM_L2_CACHE_SIZE, rs6000_cost->l2_cache_size,
5177                              global_options.x_param_values,
5178                              global_options_set.x_param_values);
5179
5180       /* Increase loop peeling limits based on performance analysis. */
5181       maybe_set_param_value (PARAM_MAX_PEELED_INSNS, 400,
5182                              global_options.x_param_values,
5183                              global_options_set.x_param_values);
5184       maybe_set_param_value (PARAM_MAX_COMPLETELY_PEELED_INSNS, 400,
5185                              global_options.x_param_values,
5186                              global_options_set.x_param_values);
5187
5188       /* Use the 'model' -fsched-pressure algorithm by default.  */
5189       maybe_set_param_value (PARAM_SCHED_PRESSURE_ALGORITHM,
5190                              SCHED_PRESSURE_MODEL,
5191                              global_options.x_param_values,
5192                              global_options_set.x_param_values);
5193
5194       /* If using typedef char *va_list, signal that
5195          __builtin_va_start (&ap, 0) can be optimized to
5196          ap = __builtin_next_arg (0).  */
5197       if (DEFAULT_ABI != ABI_V4)
5198         targetm.expand_builtin_va_start = NULL;
5199     }
5200
5201   /* Set up single/double float flags.  
5202      If TARGET_HARD_FLOAT is set, but neither single or double is set, 
5203      then set both flags. */
5204   if (TARGET_HARD_FLOAT && rs6000_single_float == 0 && rs6000_double_float == 0)
5205     rs6000_single_float = rs6000_double_float = 1;
5206
5207   /* If not explicitly specified via option, decide whether to generate indexed
5208      load/store instructions.  A value of -1 indicates that the
5209      initial value of this variable has not been overwritten. During
5210      compilation, TARGET_AVOID_XFORM is either 0 or 1. */
5211   if (TARGET_AVOID_XFORM == -1)
5212     /* Avoid indexed addressing when targeting Power6 in order to avoid the
5213      DERAT mispredict penalty.  However the LVE and STVE altivec instructions
5214      need indexed accesses and the type used is the scalar type of the element
5215      being loaded or stored.  */
5216     TARGET_AVOID_XFORM = (rs6000_tune == PROCESSOR_POWER6 && TARGET_CMPB
5217                           && !TARGET_ALTIVEC);
5218
5219   /* Set the -mrecip options.  */
5220   if (rs6000_recip_name)
5221     {
5222       char *p = ASTRDUP (rs6000_recip_name);
5223       char *q;
5224       unsigned int mask, i;
5225       bool invert;
5226
5227       while ((q = strtok (p, ",")) != NULL)
5228         {
5229           p = NULL;
5230           if (*q == '!')
5231             {
5232               invert = true;
5233               q++;
5234             }
5235           else
5236             invert = false;
5237
5238           if (!strcmp (q, "default"))
5239             mask = ((TARGET_RECIP_PRECISION)
5240                     ? RECIP_HIGH_PRECISION : RECIP_LOW_PRECISION);
5241           else
5242             {
5243               for (i = 0; i < ARRAY_SIZE (recip_options); i++)
5244                 if (!strcmp (q, recip_options[i].string))
5245                   {
5246                     mask = recip_options[i].mask;
5247                     break;
5248                   }
5249
5250               if (i == ARRAY_SIZE (recip_options))
5251                 {
5252                   error ("unknown option for %<%s=%s%>", "-mrecip", q);
5253                   invert = false;
5254                   mask = 0;
5255                   ret = false;
5256                 }
5257             }
5258
5259           if (invert)
5260             rs6000_recip_control &= ~mask;
5261           else
5262             rs6000_recip_control |= mask;
5263         }
5264     }
5265
5266   /* Set the builtin mask of the various options used that could affect which
5267      builtins were used.  In the past we used target_flags, but we've run out
5268      of bits, and some options like PAIRED are no longer in target_flags.  */
5269   rs6000_builtin_mask = rs6000_builtin_mask_calculate ();
5270   if (TARGET_DEBUG_BUILTIN || TARGET_DEBUG_TARGET)
5271     rs6000_print_builtin_options (stderr, 0, "builtin mask",
5272                                   rs6000_builtin_mask);
5273
5274   /* Initialize all of the registers.  */
5275   rs6000_init_hard_regno_mode_ok (global_init_p);
5276
5277   /* Save the initial options in case the user does function specific options */
5278   if (global_init_p)
5279     target_option_default_node = target_option_current_node
5280       = build_target_option_node (&global_options);
5281
5282   /* If not explicitly specified via option, decide whether to generate the
5283      extra blr's required to preserve the link stack on some cpus (eg, 476).  */
5284   if (TARGET_LINK_STACK == -1)
5285     SET_TARGET_LINK_STACK (rs6000_tune == PROCESSOR_PPC476 && flag_pic);
5286
5287   return ret;
5288 }
5289
5290 /* Implement TARGET_OPTION_OVERRIDE.  On the RS/6000 this is used to
5291    define the target cpu type.  */
5292
5293 static void
5294 rs6000_option_override (void)
5295 {
5296   (void) rs6000_option_override_internal (true);
5297 }
5298
5299 \f
5300 /* Implement targetm.vectorize.builtin_mask_for_load.  */
5301 static tree
5302 rs6000_builtin_mask_for_load (void)
5303 {
5304   /* Don't use lvsl/vperm for P8 and similarly efficient machines.  */
5305   if ((TARGET_ALTIVEC && !TARGET_VSX)
5306       || (TARGET_VSX && !TARGET_EFFICIENT_UNALIGNED_VSX))
5307     return altivec_builtin_mask_for_load;
5308   else
5309     return 0;
5310 }
5311
5312 /* Implement LOOP_ALIGN. */
5313 int
5314 rs6000_loop_align (rtx label)
5315 {
5316   basic_block bb;
5317   int ninsns;
5318
5319   /* Don't override loop alignment if -falign-loops was specified. */
5320   if (!can_override_loop_align)
5321     return align_loops_log;
5322
5323   bb = BLOCK_FOR_INSN (label);
5324   ninsns = num_loop_insns(bb->loop_father);
5325
5326   /* Align small loops to 32 bytes to fit in an icache sector, otherwise return default. */
5327   if (ninsns > 4 && ninsns <= 8
5328       && (rs6000_tune == PROCESSOR_POWER4
5329           || rs6000_tune == PROCESSOR_POWER5
5330           || rs6000_tune == PROCESSOR_POWER6
5331           || rs6000_tune == PROCESSOR_POWER7
5332           || rs6000_tune == PROCESSOR_POWER8
5333           || rs6000_tune == PROCESSOR_POWER9))
5334     return 5;
5335   else
5336     return align_loops_log;
5337 }
5338
5339 /* Implement TARGET_LOOP_ALIGN_MAX_SKIP. */
5340 static int
5341 rs6000_loop_align_max_skip (rtx_insn *label)
5342 {
5343   return (1 << rs6000_loop_align (label)) - 1;
5344 }
5345
5346 /* Return true iff, data reference of TYPE can reach vector alignment (16)
5347    after applying N number of iterations.  This routine does not determine
5348    how may iterations are required to reach desired alignment.  */
5349
5350 static bool
5351 rs6000_vector_alignment_reachable (const_tree type ATTRIBUTE_UNUSED, bool is_packed)
5352 {
5353   if (is_packed)
5354     return false;
5355
5356   if (TARGET_32BIT)
5357     {
5358       if (rs6000_alignment_flags == MASK_ALIGN_NATURAL)
5359         return true;
5360
5361       if (rs6000_alignment_flags ==  MASK_ALIGN_POWER)
5362         return true;
5363
5364       return false;
5365     }
5366   else
5367     {
5368       if (TARGET_MACHO)
5369         return false;
5370
5371       /* Assuming that all other types are naturally aligned. CHECKME!  */
5372       return true;
5373     }
5374 }
5375
5376 /* Return true if the vector misalignment factor is supported by the
5377    target.  */ 
5378 static bool
5379 rs6000_builtin_support_vector_misalignment (machine_mode mode,
5380                                             const_tree type,
5381                                             int misalignment,
5382                                             bool is_packed)
5383 {
5384   if (TARGET_VSX)
5385     {
5386       if (TARGET_EFFICIENT_UNALIGNED_VSX)
5387         return true;
5388
5389       /* Return if movmisalign pattern is not supported for this mode.  */
5390       if (optab_handler (movmisalign_optab, mode) == CODE_FOR_nothing)
5391         return false;
5392
5393       if (misalignment == -1)
5394         {
5395           /* Misalignment factor is unknown at compile time but we know
5396              it's word aligned.  */
5397           if (rs6000_vector_alignment_reachable (type, is_packed))
5398             {
5399               int element_size = TREE_INT_CST_LOW (TYPE_SIZE (type));
5400
5401               if (element_size == 64 || element_size == 32)
5402                return true;
5403             }
5404
5405           return false;
5406         }
5407
5408       /* VSX supports word-aligned vector.  */
5409       if (misalignment % 4 == 0)
5410         return true;
5411     }
5412   return false;
5413 }
5414
5415 /* Implement targetm.vectorize.builtin_vectorization_cost.  */
5416 static int
5417 rs6000_builtin_vectorization_cost (enum vect_cost_for_stmt type_of_cost,
5418                                    tree vectype, int misalign)
5419 {
5420   unsigned elements;
5421   tree elem_type;
5422
5423   switch (type_of_cost)
5424     {
5425       case scalar_stmt:
5426       case scalar_load:
5427       case scalar_store:
5428       case vector_stmt:
5429       case vector_load:
5430       case vector_store:
5431       case vec_to_scalar:
5432       case scalar_to_vec:
5433       case cond_branch_not_taken:
5434         return 1;
5435
5436       case vec_perm:
5437         if (TARGET_VSX)
5438           return 3;
5439         else
5440           return 1;
5441
5442       case vec_promote_demote:
5443         if (TARGET_VSX)
5444           return 4;
5445         else
5446           return 1;
5447
5448       case cond_branch_taken:
5449         return 3;
5450
5451       case unaligned_load:
5452       case vector_gather_load:
5453         if (TARGET_EFFICIENT_UNALIGNED_VSX)
5454           return 1;
5455
5456         if (TARGET_VSX && TARGET_ALLOW_MOVMISALIGN)
5457           {
5458             elements = TYPE_VECTOR_SUBPARTS (vectype);
5459             if (elements == 2)
5460               /* Double word aligned.  */
5461               return 2;
5462
5463             if (elements == 4)
5464               {
5465                 switch (misalign)
5466                   {
5467                     case 8:
5468                       /* Double word aligned.  */
5469                       return 2;
5470
5471                     case -1:
5472                       /* Unknown misalignment.  */
5473                     case 4:
5474                     case 12:
5475                       /* Word aligned.  */
5476                       return 22;
5477
5478                     default:
5479                       gcc_unreachable ();
5480                   }
5481               }
5482           }
5483
5484         if (TARGET_ALTIVEC)
5485           /* Misaligned loads are not supported.  */
5486           gcc_unreachable ();
5487
5488         return 2;
5489
5490       case unaligned_store:
5491       case vector_scatter_store:
5492         if (TARGET_EFFICIENT_UNALIGNED_VSX)
5493           return 1;
5494
5495         if (TARGET_VSX && TARGET_ALLOW_MOVMISALIGN)
5496           {
5497             elements = TYPE_VECTOR_SUBPARTS (vectype);
5498             if (elements == 2)
5499               /* Double word aligned.  */
5500               return 2;
5501
5502             if (elements == 4)
5503               {
5504                 switch (misalign)
5505                   {
5506                     case 8:
5507                       /* Double word aligned.  */
5508                       return 2;
5509
5510                     case -1:
5511                       /* Unknown misalignment.  */
5512                     case 4:
5513                     case 12:
5514                       /* Word aligned.  */
5515                       return 23;
5516
5517                     default:
5518                       gcc_unreachable ();
5519                   }
5520               }
5521           }
5522
5523         if (TARGET_ALTIVEC)
5524           /* Misaligned stores are not supported.  */
5525           gcc_unreachable ();
5526
5527         return 2;
5528
5529       case vec_construct:
5530         /* This is a rough approximation assuming non-constant elements
5531            constructed into a vector via element insertion.  FIXME:
5532            vec_construct is not granular enough for uniformly good
5533            decisions.  If the initialization is a splat, this is
5534            cheaper than we estimate.  Improve this someday.  */
5535         elem_type = TREE_TYPE (vectype);
5536         /* 32-bit vectors loaded into registers are stored as double
5537            precision, so we need 2 permutes, 2 converts, and 1 merge
5538            to construct a vector of short floats from them.  */
5539         if (SCALAR_FLOAT_TYPE_P (elem_type)
5540             && TYPE_PRECISION (elem_type) == 32)
5541           return 5;
5542         /* On POWER9, integer vector types are built up in GPRs and then
5543            use a direct move (2 cycles).  For POWER8 this is even worse,
5544            as we need two direct moves and a merge, and the direct moves
5545            are five cycles.  */
5546         else if (INTEGRAL_TYPE_P (elem_type))
5547           {
5548             if (TARGET_P9_VECTOR)
5549               return TYPE_VECTOR_SUBPARTS (vectype) - 1 + 2;
5550             else
5551               return TYPE_VECTOR_SUBPARTS (vectype) - 1 + 5;
5552           }
5553         else
5554           /* V2DFmode doesn't need a direct move.  */
5555           return 2;
5556
5557       default:
5558         gcc_unreachable ();
5559     }
5560 }
5561
5562 /* Implement targetm.vectorize.preferred_simd_mode.  */
5563
5564 static machine_mode
5565 rs6000_preferred_simd_mode (scalar_mode mode)
5566 {
5567   if (TARGET_VSX)
5568     switch (mode)
5569       {
5570       case E_DFmode:
5571         return V2DFmode;
5572       default:;
5573       }
5574   if (TARGET_ALTIVEC || TARGET_VSX)
5575     switch (mode)
5576       {
5577       case E_SFmode:
5578         return V4SFmode;
5579       case E_TImode:
5580         return V1TImode;
5581       case E_DImode:
5582         return V2DImode;
5583       case E_SImode:
5584         return V4SImode;
5585       case E_HImode:
5586         return V8HImode;
5587       case E_QImode:
5588         return V16QImode;
5589       default:;
5590       }
5591   if (TARGET_PAIRED_FLOAT
5592       && mode == SFmode)
5593     return V2SFmode;
5594   return word_mode;
5595 }
5596
5597 typedef struct _rs6000_cost_data
5598 {
5599   struct loop *loop_info;
5600   unsigned cost[3];
5601 } rs6000_cost_data;
5602
5603 /* Test for likely overcommitment of vector hardware resources.  If a
5604    loop iteration is relatively large, and too large a percentage of
5605    instructions in the loop are vectorized, the cost model may not
5606    adequately reflect delays from unavailable vector resources.
5607    Penalize the loop body cost for this case.  */
5608
5609 static void
5610 rs6000_density_test (rs6000_cost_data *data)
5611 {
5612   const int DENSITY_PCT_THRESHOLD = 85;
5613   const int DENSITY_SIZE_THRESHOLD = 70;
5614   const int DENSITY_PENALTY = 10;
5615   struct loop *loop = data->loop_info;
5616   basic_block *bbs = get_loop_body (loop);
5617   int nbbs = loop->num_nodes;
5618   int vec_cost = data->cost[vect_body], not_vec_cost = 0;
5619   int i, density_pct;
5620
5621   for (i = 0; i < nbbs; i++)
5622     {
5623       basic_block bb = bbs[i];
5624       gimple_stmt_iterator gsi;
5625
5626       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5627         {
5628           gimple *stmt = gsi_stmt (gsi);
5629           stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
5630
5631           if (!STMT_VINFO_RELEVANT_P (stmt_info)
5632               && !STMT_VINFO_IN_PATTERN_P (stmt_info))
5633             not_vec_cost++;
5634         }
5635     }
5636
5637   free (bbs);
5638   density_pct = (vec_cost * 100) / (vec_cost + not_vec_cost);
5639
5640   if (density_pct > DENSITY_PCT_THRESHOLD
5641       && vec_cost + not_vec_cost > DENSITY_SIZE_THRESHOLD)
5642     {
5643       data->cost[vect_body] = vec_cost * (100 + DENSITY_PENALTY) / 100;
5644       if (dump_enabled_p ())
5645         dump_printf_loc (MSG_NOTE, vect_location,
5646                          "density %d%%, cost %d exceeds threshold, penalizing "
5647                          "loop body cost by %d%%", density_pct,
5648                          vec_cost + not_vec_cost, DENSITY_PENALTY);
5649     }
5650 }
5651
5652 /* Implement targetm.vectorize.init_cost.  */
5653
5654 /* For each vectorized loop, this var holds TRUE iff a non-memory vector
5655    instruction is needed by the vectorization.  */
5656 static bool rs6000_vect_nonmem;
5657
5658 static void *
5659 rs6000_init_cost (struct loop *loop_info)
5660 {
5661   rs6000_cost_data *data = XNEW (struct _rs6000_cost_data);
5662   data->loop_info = loop_info;
5663   data->cost[vect_prologue] = 0;
5664   data->cost[vect_body]     = 0;
5665   data->cost[vect_epilogue] = 0;
5666   rs6000_vect_nonmem = false;
5667   return data;
5668 }
5669
5670 /* Implement targetm.vectorize.add_stmt_cost.  */
5671
5672 static unsigned
5673 rs6000_add_stmt_cost (void *data, int count, enum vect_cost_for_stmt kind,
5674                       struct _stmt_vec_info *stmt_info, int misalign,
5675                       enum vect_cost_model_location where)
5676 {
5677   rs6000_cost_data *cost_data = (rs6000_cost_data*) data;
5678   unsigned retval = 0;
5679
5680   if (flag_vect_cost_model)
5681     {
5682       tree vectype = stmt_info ? stmt_vectype (stmt_info) : NULL_TREE;
5683       int stmt_cost = rs6000_builtin_vectorization_cost (kind, vectype,
5684                                                          misalign);
5685       /* Statements in an inner loop relative to the loop being
5686          vectorized are weighted more heavily.  The value here is
5687          arbitrary and could potentially be improved with analysis.  */
5688       if (where == vect_body && stmt_info && stmt_in_inner_loop_p (stmt_info))
5689         count *= 50;  /* FIXME.  */
5690
5691       retval = (unsigned) (count * stmt_cost);
5692       cost_data->cost[where] += retval;
5693
5694       /* Check whether we're doing something other than just a copy loop.
5695          Not all such loops may be profitably vectorized; see
5696          rs6000_finish_cost.  */
5697       if ((kind == vec_to_scalar || kind == vec_perm
5698            || kind == vec_promote_demote || kind == vec_construct
5699            || kind == scalar_to_vec)
5700           || (where == vect_body && kind == vector_stmt))
5701         rs6000_vect_nonmem = true;
5702     }
5703
5704   return retval;
5705 }
5706
5707 /* Implement targetm.vectorize.finish_cost.  */
5708
5709 static void
5710 rs6000_finish_cost (void *data, unsigned *prologue_cost,
5711                     unsigned *body_cost, unsigned *epilogue_cost)
5712 {
5713   rs6000_cost_data *cost_data = (rs6000_cost_data*) data;
5714
5715   if (cost_data->loop_info)
5716     rs6000_density_test (cost_data);
5717
5718   /* Don't vectorize minimum-vectorization-factor, simple copy loops
5719      that require versioning for any reason.  The vectorization is at
5720      best a wash inside the loop, and the versioning checks make
5721      profitability highly unlikely and potentially quite harmful.  */
5722   if (cost_data->loop_info)
5723     {
5724       loop_vec_info vec_info = loop_vec_info_for_loop (cost_data->loop_info);
5725       if (!rs6000_vect_nonmem
5726           && LOOP_VINFO_VECT_FACTOR (vec_info) == 2
5727           && LOOP_REQUIRES_VERSIONING (vec_info))
5728         cost_data->cost[vect_body] += 10000;
5729     }
5730
5731   *prologue_cost = cost_data->cost[vect_prologue];
5732   *body_cost     = cost_data->cost[vect_body];
5733   *epilogue_cost = cost_data->cost[vect_epilogue];
5734 }
5735
5736 /* Implement targetm.vectorize.destroy_cost_data.  */
5737
5738 static void
5739 rs6000_destroy_cost_data (void *data)
5740 {
5741   free (data);
5742 }
5743
5744 /* Handler for the Mathematical Acceleration Subsystem (mass) interface to a
5745    library with vectorized intrinsics.  */
5746
5747 static tree
5748 rs6000_builtin_vectorized_libmass (combined_fn fn, tree type_out,
5749                                    tree type_in)
5750 {
5751   char name[32];
5752   const char *suffix = NULL;
5753   tree fntype, new_fndecl, bdecl = NULL_TREE;
5754   int n_args = 1;
5755   const char *bname;
5756   machine_mode el_mode, in_mode;
5757   int n, in_n;
5758
5759   /* Libmass is suitable for unsafe math only as it does not correctly support
5760      parts of IEEE with the required precision such as denormals.  Only support
5761      it if we have VSX to use the simd d2 or f4 functions.
5762      XXX: Add variable length support.  */
5763   if (!flag_unsafe_math_optimizations || !TARGET_VSX)
5764     return NULL_TREE;
5765
5766   el_mode = TYPE_MODE (TREE_TYPE (type_out));
5767   n = TYPE_VECTOR_SUBPARTS (type_out);
5768   in_mode = TYPE_MODE (TREE_TYPE (type_in));
5769   in_n = TYPE_VECTOR_SUBPARTS (type_in);
5770   if (el_mode != in_mode
5771       || n != in_n)
5772     return NULL_TREE;
5773
5774   switch (fn)
5775     {
5776     CASE_CFN_ATAN2:
5777     CASE_CFN_HYPOT:
5778     CASE_CFN_POW:
5779       n_args = 2;
5780       gcc_fallthrough ();
5781
5782     CASE_CFN_ACOS:
5783     CASE_CFN_ACOSH:
5784     CASE_CFN_ASIN:
5785     CASE_CFN_ASINH:
5786     CASE_CFN_ATAN:
5787     CASE_CFN_ATANH:
5788     CASE_CFN_CBRT:
5789     CASE_CFN_COS:
5790     CASE_CFN_COSH:
5791     CASE_CFN_ERF:
5792     CASE_CFN_ERFC:
5793     CASE_CFN_EXP2:
5794     CASE_CFN_EXP:
5795     CASE_CFN_EXPM1:
5796     CASE_CFN_LGAMMA:
5797     CASE_CFN_LOG10:
5798     CASE_CFN_LOG1P:
5799     CASE_CFN_LOG2:
5800     CASE_CFN_LOG:
5801     CASE_CFN_SIN:
5802     CASE_CFN_SINH:
5803     CASE_CFN_SQRT:
5804     CASE_CFN_TAN:
5805     CASE_CFN_TANH:
5806       if (el_mode == DFmode && n == 2)
5807         {
5808           bdecl = mathfn_built_in (double_type_node, fn);
5809           suffix = "d2";                                /* pow -> powd2 */
5810         }
5811       else if (el_mode == SFmode && n == 4)
5812         {
5813           bdecl = mathfn_built_in (float_type_node, fn);
5814           suffix = "4";                                 /* powf -> powf4 */
5815         }
5816       else
5817         return NULL_TREE;
5818       if (!bdecl)
5819         return NULL_TREE;
5820       break;
5821
5822     default:
5823       return NULL_TREE;
5824     }
5825
5826   gcc_assert (suffix != NULL);
5827   bname = IDENTIFIER_POINTER (DECL_NAME (bdecl));
5828   if (!bname)
5829     return NULL_TREE;
5830
5831   strcpy (name, bname + sizeof ("__builtin_") - 1);
5832   strcat (name, suffix);
5833
5834   if (n_args == 1)
5835     fntype = build_function_type_list (type_out, type_in, NULL);
5836   else if (n_args == 2)
5837     fntype = build_function_type_list (type_out, type_in, type_in, NULL);
5838   else
5839     gcc_unreachable ();
5840
5841   /* Build a function declaration for the vectorized function.  */
5842   new_fndecl = build_decl (BUILTINS_LOCATION,
5843                            FUNCTION_DECL, get_identifier (name), fntype);
5844   TREE_PUBLIC (new_fndecl) = 1;
5845   DECL_EXTERNAL (new_fndecl) = 1;
5846   DECL_IS_NOVOPS (new_fndecl) = 1;
5847   TREE_READONLY (new_fndecl) = 1;
5848
5849   return new_fndecl;
5850 }
5851
5852 /* Returns a function decl for a vectorized version of the builtin function
5853    with builtin function code FN and the result vector type TYPE, or NULL_TREE
5854    if it is not available.  */
5855
5856 static tree
5857 rs6000_builtin_vectorized_function (unsigned int fn, tree type_out,
5858                                     tree type_in)
5859 {
5860   machine_mode in_mode, out_mode;
5861   int in_n, out_n;
5862
5863   if (TARGET_DEBUG_BUILTIN)
5864     fprintf (stderr, "rs6000_builtin_vectorized_function (%s, %s, %s)\n",
5865              combined_fn_name (combined_fn (fn)),
5866              GET_MODE_NAME (TYPE_MODE (type_out)),
5867              GET_MODE_NAME (TYPE_MODE (type_in)));
5868
5869   if (TREE_CODE (type_out) != VECTOR_TYPE
5870       || TREE_CODE (type_in) != VECTOR_TYPE)
5871     return NULL_TREE;
5872
5873   out_mode = TYPE_MODE (TREE_TYPE (type_out));
5874   out_n = TYPE_VECTOR_SUBPARTS (type_out);
5875   in_mode = TYPE_MODE (TREE_TYPE (type_in));
5876   in_n = TYPE_VECTOR_SUBPARTS (type_in);
5877
5878   switch (fn)
5879     {
5880     CASE_CFN_COPYSIGN:
5881       if (VECTOR_UNIT_VSX_P (V2DFmode)
5882           && out_mode == DFmode && out_n == 2
5883           && in_mode == DFmode && in_n == 2)
5884         return rs6000_builtin_decls[VSX_BUILTIN_CPSGNDP];
5885       if (VECTOR_UNIT_VSX_P (V4SFmode)
5886           && out_mode == SFmode && out_n == 4
5887           && in_mode == SFmode && in_n == 4)
5888         return rs6000_builtin_decls[VSX_BUILTIN_CPSGNSP];
5889       if (VECTOR_UNIT_ALTIVEC_P (V4SFmode)
5890           && out_mode == SFmode && out_n == 4
5891           && in_mode == SFmode && in_n == 4)
5892         return rs6000_builtin_decls[ALTIVEC_BUILTIN_COPYSIGN_V4SF];
5893       break;
5894     CASE_CFN_CEIL:
5895       if (VECTOR_UNIT_VSX_P (V2DFmode)
5896           && out_mode == DFmode && out_n == 2
5897           && in_mode == DFmode && in_n == 2)
5898         return rs6000_builtin_decls[VSX_BUILTIN_XVRDPIP];
5899       if (VECTOR_UNIT_VSX_P (V4SFmode)
5900           && out_mode == SFmode && out_n == 4
5901           && in_mode == SFmode && in_n == 4)
5902         return rs6000_builtin_decls[VSX_BUILTIN_XVRSPIP];
5903       if (VECTOR_UNIT_ALTIVEC_P (V4SFmode)
5904           && out_mode == SFmode && out_n == 4
5905           && in_mode == SFmode && in_n == 4)
5906         return rs6000_builtin_decls[ALTIVEC_BUILTIN_VRFIP];
5907       break;
5908     CASE_CFN_FLOOR:
5909       if (VECTOR_UNIT_VSX_P (V2DFmode)
5910           && out_mode == DFmode && out_n == 2
5911           && in_mode == DFmode && in_n == 2)
5912         return rs6000_builtin_decls[VSX_BUILTIN_XVRDPIM];
5913       if (VECTOR_UNIT_VSX_P (V4SFmode)
5914           && out_mode == SFmode && out_n == 4
5915           && in_mode == SFmode && in_n == 4)
5916         return rs6000_builtin_decls[VSX_BUILTIN_XVRSPIM];
5917       if (VECTOR_UNIT_ALTIVEC_P (V4SFmode)
5918           && out_mode == SFmode && out_n == 4
5919           && in_mode == SFmode && in_n == 4)
5920         return rs6000_builtin_decls[ALTIVEC_BUILTIN_VRFIM];
5921       break;
5922     CASE_CFN_FMA:
5923       if (VECTOR_UNIT_VSX_P (V2DFmode)
5924           && out_mode == DFmode && out_n == 2
5925           && in_mode == DFmode && in_n == 2)
5926         return rs6000_builtin_decls[VSX_BUILTIN_XVMADDDP];
5927       if (VECTOR_UNIT_VSX_P (V4SFmode)
5928           && out_mode == SFmode && out_n == 4
5929           && in_mode == SFmode && in_n == 4)
5930         return rs6000_builtin_decls[VSX_BUILTIN_XVMADDSP];
5931       if (VECTOR_UNIT_ALTIVEC_P (V4SFmode)
5932           && out_mode == SFmode && out_n == 4
5933           && in_mode == SFmode && in_n == 4)
5934         return rs6000_builtin_decls[ALTIVEC_BUILTIN_VMADDFP];
5935       break;
5936     CASE_CFN_TRUNC:
5937       if (VECTOR_UNIT_VSX_P (V2DFmode)
5938           && out_mode == DFmode && out_n == 2
5939           && in_mode == DFmode && in_n == 2)
5940         return rs6000_builtin_decls[VSX_BUILTIN_XVRDPIZ];
5941       if (VECTOR_UNIT_VSX_P (V4SFmode)
5942           && out_mode == SFmode && out_n == 4
5943           && in_mode == SFmode && in_n == 4)
5944         return rs6000_builtin_decls[VSX_BUILTIN_XVRSPIZ];
5945       if (VECTOR_UNIT_ALTIVEC_P (V4SFmode)
5946           && out_mode == SFmode && out_n == 4
5947           && in_mode == SFmode && in_n == 4)
5948         return rs6000_builtin_decls[ALTIVEC_BUILTIN_VRFIZ];
5949       break;
5950     CASE_CFN_NEARBYINT:
5951       if (VECTOR_UNIT_VSX_P (V2DFmode)
5952           && flag_unsafe_math_optimizations
5953           && out_mode == DFmode && out_n == 2
5954           && in_mode == DFmode && in_n == 2)
5955         return rs6000_builtin_decls[VSX_BUILTIN_XVRDPI];
5956       if (VECTOR_UNIT_VSX_P (V4SFmode)
5957           && flag_unsafe_math_optimizations
5958           && out_mode == SFmode && out_n == 4
5959           && in_mode == SFmode && in_n == 4)
5960         return rs6000_builtin_decls[VSX_BUILTIN_XVRSPI];
5961       break;
5962     CASE_CFN_RINT:
5963       if (VECTOR_UNIT_VSX_P (V2DFmode)
5964           && !flag_trapping_math
5965           && out_mode == DFmode && out_n == 2
5966           && in_mode == DFmode && in_n == 2)
5967         return rs6000_builtin_decls[VSX_BUILTIN_XVRDPIC];
5968       if (VECTOR_UNIT_VSX_P (V4SFmode)
5969           && !flag_trapping_math
5970           && out_mode == SFmode && out_n == 4
5971           && in_mode == SFmode && in_n == 4)
5972         return rs6000_builtin_decls[VSX_BUILTIN_XVRSPIC];
5973       break;
5974     default:
5975       break;
5976     }
5977
5978   /* Generate calls to libmass if appropriate.  */
5979   if (rs6000_veclib_handler)
5980     return rs6000_veclib_handler (combined_fn (fn), type_out, type_in);
5981
5982   return NULL_TREE;
5983 }
5984
5985 /* Implement TARGET_VECTORIZE_BUILTIN_MD_VECTORIZED_FUNCTION.  */
5986
5987 static tree
5988 rs6000_builtin_md_vectorized_function (tree fndecl, tree type_out,
5989                                        tree type_in)
5990 {
5991   machine_mode in_mode, out_mode;
5992   int in_n, out_n;
5993
5994   if (TARGET_DEBUG_BUILTIN)
5995     fprintf (stderr, "rs6000_builtin_md_vectorized_function (%s, %s, %s)\n",
5996              IDENTIFIER_POINTER (DECL_NAME (fndecl)),
5997              GET_MODE_NAME (TYPE_MODE (type_out)),
5998              GET_MODE_NAME (TYPE_MODE (type_in)));
5999
6000   if (TREE_CODE (type_out) != VECTOR_TYPE
6001       || TREE_CODE (type_in) != VECTOR_TYPE)
6002     return NULL_TREE;
6003
6004   out_mode = TYPE_MODE (TREE_TYPE (type_out));
6005   out_n = TYPE_VECTOR_SUBPARTS (type_out);
6006   in_mode = TYPE_MODE (TREE_TYPE (type_in));
6007   in_n = TYPE_VECTOR_SUBPARTS (type_in);
6008
6009   enum rs6000_builtins fn
6010     = (enum rs6000_builtins) DECL_FUNCTION_CODE (fndecl);
6011   switch (fn)
6012     {
6013     case RS6000_BUILTIN_RSQRTF:
6014       if (VECTOR_UNIT_ALTIVEC_OR_VSX_P (V4SFmode)
6015           && out_mode == SFmode && out_n == 4
6016           && in_mode == SFmode && in_n == 4)
6017         return rs6000_builtin_decls[ALTIVEC_BUILTIN_VRSQRTFP];
6018       break;
6019     case RS6000_BUILTIN_RSQRT:
6020       if (VECTOR_UNIT_VSX_P (V2DFmode)
6021           && out_mode == DFmode && out_n == 2
6022           && in_mode == DFmode && in_n == 2)
6023         return rs6000_builtin_decls[VSX_BUILTIN_RSQRT_2DF];
6024       break;
6025     case RS6000_BUILTIN_RECIPF:
6026       if (VECTOR_UNIT_ALTIVEC_OR_VSX_P (V4SFmode)
6027           && out_mode == SFmode && out_n == 4
6028           && in_mode == SFmode && in_n == 4)
6029         return rs6000_builtin_decls[ALTIVEC_BUILTIN_VRECIPFP];
6030       break;
6031     case RS6000_BUILTIN_RECIP:
6032       if (VECTOR_UNIT_VSX_P (V2DFmode)
6033           && out_mode == DFmode && out_n == 2
6034           && in_mode == DFmode && in_n == 2)
6035         return rs6000_builtin_decls[VSX_BUILTIN_RECIP_V2DF];
6036       break;
6037     default:
6038       break;
6039     }
6040   return NULL_TREE;
6041 }
6042 \f
6043 /* Default CPU string for rs6000*_file_start functions.  */
6044 static const char *rs6000_default_cpu;
6045
6046 /* Do anything needed at the start of the asm file.  */
6047
6048 static void
6049 rs6000_file_start (void)
6050 {
6051   char buffer[80];
6052   const char *start = buffer;
6053   FILE *file = asm_out_file;
6054
6055   rs6000_default_cpu = TARGET_CPU_DEFAULT;
6056
6057   default_file_start ();
6058
6059   if (flag_verbose_asm)
6060     {
6061       sprintf (buffer, "\n%s rs6000/powerpc options:", ASM_COMMENT_START);
6062
6063       if (rs6000_default_cpu != 0 && rs6000_default_cpu[0] != '\0')
6064         {
6065           fprintf (file, "%s --with-cpu=%s", start, rs6000_default_cpu);
6066           start = "";
6067         }
6068
6069       if (global_options_set.x_rs6000_cpu_index)
6070         {
6071           fprintf (file, "%s -mcpu=%s", start,
6072                    processor_target_table[rs6000_cpu_index].name);
6073           start = "";
6074         }
6075
6076       if (global_options_set.x_rs6000_tune_index)
6077         {
6078           fprintf (file, "%s -mtune=%s", start,
6079                    processor_target_table[rs6000_tune_index].name);
6080           start = "";
6081         }
6082
6083       if (PPC405_ERRATUM77)
6084         {
6085           fprintf (file, "%s PPC405CR_ERRATUM77", start);
6086           start = "";
6087         }
6088
6089 #ifdef USING_ELFOS_H
6090       switch (rs6000_sdata)
6091         {
6092         case SDATA_NONE: fprintf (file, "%s -msdata=none", start); start = ""; break;
6093         case SDATA_DATA: fprintf (file, "%s -msdata=data", start); start = ""; break;
6094         case SDATA_SYSV: fprintf (file, "%s -msdata=sysv", start); start = ""; break;
6095         case SDATA_EABI: fprintf (file, "%s -msdata=eabi", start); start = ""; break;
6096         }
6097
6098       if (rs6000_sdata && g_switch_value)
6099         {
6100           fprintf (file, "%s -G %d", start,
6101                    g_switch_value);
6102           start = "";
6103         }
6104 #endif
6105
6106       if (*start == '\0')
6107         putc ('\n', file);
6108     }
6109
6110 #ifdef USING_ELFOS_H
6111   if (!(rs6000_default_cpu && rs6000_default_cpu[0])
6112       && !global_options_set.x_rs6000_cpu_index)
6113     {
6114       fputs ("\t.machine ", asm_out_file);
6115       if ((rs6000_isa_flags & OPTION_MASK_MODULO) != 0)
6116         fputs ("power9\n", asm_out_file);
6117       else if ((rs6000_isa_flags & OPTION_MASK_DIRECT_MOVE) != 0)
6118         fputs ("power8\n", asm_out_file);
6119       else if ((rs6000_isa_flags & OPTION_MASK_POPCNTD) != 0)
6120         fputs ("power7\n", asm_out_file);
6121       else if ((rs6000_isa_flags & OPTION_MASK_CMPB) != 0)
6122         fputs ("power6\n", asm_out_file);
6123       else if ((rs6000_isa_flags & OPTION_MASK_POPCNTB) != 0)
6124         fputs ("power5\n", asm_out_file);
6125       else if ((rs6000_isa_flags & OPTION_MASK_MFCRF) != 0)
6126         fputs ("power4\n", asm_out_file);
6127       else if ((rs6000_isa_flags & OPTION_MASK_POWERPC64) != 0)
6128         fputs ("ppc64\n", asm_out_file);
6129       else
6130         fputs ("ppc\n", asm_out_file);
6131     }
6132 #endif
6133
6134   if (DEFAULT_ABI == ABI_ELFv2)
6135     fprintf (file, "\t.abiversion 2\n");
6136 }
6137
6138 \f
6139 /* Return nonzero if this function is known to have a null epilogue.  */
6140
6141 int
6142 direct_return (void)
6143 {
6144   if (reload_completed)
6145     {
6146       rs6000_stack_t *info = rs6000_stack_info ();
6147
6148       if (info->first_gp_reg_save == 32
6149           && info->first_fp_reg_save == 64
6150           && info->first_altivec_reg_save == LAST_ALTIVEC_REGNO + 1
6151           && ! info->lr_save_p
6152           && ! info->cr_save_p
6153           && info->vrsave_size == 0
6154           && ! info->push_p)
6155         return 1;
6156     }
6157
6158   return 0;
6159 }
6160
6161 /* Return the number of instructions it takes to form a constant in an
6162    integer register.  */
6163
6164 int
6165 num_insns_constant_wide (HOST_WIDE_INT value)
6166 {
6167   /* signed constant loadable with addi */
6168   if (((unsigned HOST_WIDE_INT) value + 0x8000) < 0x10000)
6169     return 1;
6170
6171   /* constant loadable with addis */
6172   else if ((value & 0xffff) == 0
6173            && (value >> 31 == -1 || value >> 31 == 0))
6174     return 1;
6175
6176   else if (TARGET_POWERPC64)
6177     {
6178       HOST_WIDE_INT low  = ((value & 0xffffffff) ^ 0x80000000) - 0x80000000;
6179       HOST_WIDE_INT high = value >> 31;
6180
6181       if (high == 0 || high == -1)
6182         return 2;
6183
6184       high >>= 1;
6185
6186       if (low == 0)
6187         return num_insns_constant_wide (high) + 1;
6188       else if (high == 0)
6189         return num_insns_constant_wide (low) + 1;
6190       else
6191         return (num_insns_constant_wide (high)
6192                 + num_insns_constant_wide (low) + 1);
6193     }
6194
6195   else
6196     return 2;
6197 }
6198
6199 int
6200 num_insns_constant (rtx op, machine_mode mode)
6201 {
6202   HOST_WIDE_INT low, high;
6203
6204   switch (GET_CODE (op))
6205     {
6206     case CONST_INT:
6207       if ((INTVAL (op) >> 31) != 0 && (INTVAL (op) >> 31) != -1
6208           && rs6000_is_valid_and_mask (op, mode))
6209         return 2;
6210       else
6211         return num_insns_constant_wide (INTVAL (op));
6212
6213     case CONST_WIDE_INT:
6214       {
6215         int i;
6216         int ins = CONST_WIDE_INT_NUNITS (op) - 1;
6217         for (i = 0; i < CONST_WIDE_INT_NUNITS (op); i++)
6218           ins += num_insns_constant_wide (CONST_WIDE_INT_ELT (op, i));
6219         return ins;
6220       }
6221
6222       case CONST_DOUBLE:
6223         if (mode == SFmode || mode == SDmode)
6224           {
6225             long l;
6226
6227             if (DECIMAL_FLOAT_MODE_P (mode))
6228               REAL_VALUE_TO_TARGET_DECIMAL32
6229                 (*CONST_DOUBLE_REAL_VALUE (op), l);
6230             else
6231               REAL_VALUE_TO_TARGET_SINGLE (*CONST_DOUBLE_REAL_VALUE (op), l);
6232             return num_insns_constant_wide ((HOST_WIDE_INT) l);
6233           }
6234
6235         long l[2];
6236         if (DECIMAL_FLOAT_MODE_P (mode))
6237           REAL_VALUE_TO_TARGET_DECIMAL64 (*CONST_DOUBLE_REAL_VALUE (op), l);
6238         else
6239           REAL_VALUE_TO_TARGET_DOUBLE (*CONST_DOUBLE_REAL_VALUE (op), l);
6240         high = l[WORDS_BIG_ENDIAN == 0];
6241         low  = l[WORDS_BIG_ENDIAN != 0];
6242
6243         if (TARGET_32BIT)
6244           return (num_insns_constant_wide (low)
6245                   + num_insns_constant_wide (high));
6246         else
6247           {
6248             if ((high == 0 && low >= 0)
6249                 || (high == -1 && low < 0))
6250               return num_insns_constant_wide (low);
6251
6252             else if (rs6000_is_valid_and_mask (op, mode))
6253               return 2;
6254
6255             else if (low == 0)
6256               return num_insns_constant_wide (high) + 1;
6257
6258             else
6259               return (num_insns_constant_wide (high)
6260                       + num_insns_constant_wide (low) + 1);
6261           }
6262
6263     default:
6264       gcc_unreachable ();
6265     }
6266 }
6267
6268 /* Interpret element ELT of the CONST_VECTOR OP as an integer value.
6269    If the mode of OP is MODE_VECTOR_INT, this simply returns the
6270    corresponding element of the vector, but for V4SFmode and V2SFmode,
6271    the corresponding "float" is interpreted as an SImode integer.  */
6272
6273 HOST_WIDE_INT
6274 const_vector_elt_as_int (rtx op, unsigned int elt)
6275 {
6276   rtx tmp;
6277
6278   /* We can't handle V2DImode and V2DFmode vector constants here yet.  */
6279   gcc_assert (GET_MODE (op) != V2DImode
6280               && GET_MODE (op) != V2DFmode);
6281
6282   tmp = CONST_VECTOR_ELT (op, elt);
6283   if (GET_MODE (op) == V4SFmode
6284       || GET_MODE (op) == V2SFmode)
6285     tmp = gen_lowpart (SImode, tmp);
6286   return INTVAL (tmp);
6287 }
6288
6289 /* Return true if OP can be synthesized with a particular vspltisb, vspltish
6290    or vspltisw instruction.  OP is a CONST_VECTOR.  Which instruction is used
6291    depends on STEP and COPIES, one of which will be 1.  If COPIES > 1,
6292    all items are set to the same value and contain COPIES replicas of the
6293    vsplt's operand; if STEP > 1, one in STEP elements is set to the vsplt's
6294    operand and the others are set to the value of the operand's msb.  */
6295
6296 static bool
6297 vspltis_constant (rtx op, unsigned step, unsigned copies)
6298 {
6299   machine_mode mode = GET_MODE (op);
6300   machine_mode inner = GET_MODE_INNER (mode);
6301
6302   unsigned i;
6303   unsigned nunits;
6304   unsigned bitsize;
6305   unsigned mask;
6306
6307   HOST_WIDE_INT val;
6308   HOST_WIDE_INT splat_val;
6309   HOST_WIDE_INT msb_val;
6310
6311   if (mode == V2DImode || mode == V2DFmode || mode == V1TImode)
6312     return false;
6313
6314   nunits = GET_MODE_NUNITS (mode);
6315   bitsize = GET_MODE_BITSIZE (inner);
6316   mask = GET_MODE_MASK (inner);
6317
6318   val = const_vector_elt_as_int (op, BYTES_BIG_ENDIAN ? nunits - 1 : 0);
6319   splat_val = val;
6320   msb_val = val >= 0 ? 0 : -1;
6321
6322   /* Construct the value to be splatted, if possible.  If not, return 0.  */
6323   for (i = 2; i <= copies; i *= 2)
6324     {
6325       HOST_WIDE_INT small_val;
6326       bitsize /= 2;
6327       small_val = splat_val >> bitsize;
6328       mask >>= bitsize;
6329       if (splat_val != ((HOST_WIDE_INT)
6330           ((unsigned HOST_WIDE_INT) small_val << bitsize)
6331           | (small_val & mask)))
6332         return false;
6333       splat_val = small_val;
6334     }
6335
6336   /* Check if SPLAT_VAL can really be the operand of a vspltis[bhw].  */
6337   if (EASY_VECTOR_15 (splat_val))
6338     ;
6339
6340   /* Also check if we can splat, and then add the result to itself.  Do so if
6341      the value is positive, of if the splat instruction is using OP's mode;
6342      for splat_val < 0, the splat and the add should use the same mode.  */
6343   else if (EASY_VECTOR_15_ADD_SELF (splat_val)
6344            && (splat_val >= 0 || (step == 1 && copies == 1)))
6345     ;
6346
6347   /* Also check if are loading up the most significant bit which can be done by
6348      loading up -1 and shifting the value left by -1.  */
6349   else if (EASY_VECTOR_MSB (splat_val, inner))
6350     ;
6351
6352   else
6353     return false;
6354
6355   /* Check if VAL is present in every STEP-th element, and the
6356      other elements are filled with its most significant bit.  */
6357   for (i = 1; i < nunits; ++i)
6358     {
6359       HOST_WIDE_INT desired_val;
6360       unsigned elt = BYTES_BIG_ENDIAN ? nunits - 1 - i : i;
6361       if ((i & (step - 1)) == 0)
6362         desired_val = val;
6363       else
6364         desired_val = msb_val;
6365
6366       if (desired_val != const_vector_elt_as_int (op, elt))
6367         return false;
6368     }
6369
6370   return true;
6371 }
6372
6373 /* Like vsplitis_constant, but allow the value to be shifted left with a VSLDOI
6374    instruction, filling in the bottom elements with 0 or -1.
6375
6376    Return 0 if the constant cannot be generated with VSLDOI.  Return positive
6377    for the number of zeroes to shift in, or negative for the number of 0xff
6378    bytes to shift in.
6379
6380    OP is a CONST_VECTOR.  */
6381
6382 int
6383 vspltis_shifted (rtx op)
6384 {
6385   machine_mode mode = GET_MODE (op);
6386   machine_mode inner = GET_MODE_INNER (mode);
6387
6388   unsigned i, j;
6389   unsigned nunits;
6390   unsigned mask;
6391
6392   HOST_WIDE_INT val;
6393
6394   if (mode != V16QImode && mode != V8HImode && mode != V4SImode)
6395     return false;
6396
6397   /* We need to create pseudo registers to do the shift, so don't recognize
6398      shift vector constants after reload.  */
6399   if (!can_create_pseudo_p ())
6400     return false;
6401
6402   nunits = GET_MODE_NUNITS (mode);
6403   mask = GET_MODE_MASK (inner);
6404
6405   val = const_vector_elt_as_int (op, BYTES_BIG_ENDIAN ? 0 : nunits - 1);
6406
6407   /* Check if the value can really be the operand of a vspltis[bhw].  */
6408   if (EASY_VECTOR_15 (val))
6409     ;
6410
6411   /* Also check if we are loading up the most significant bit which can be done
6412      by loading up -1 and shifting the value left by -1.  */
6413   else if (EASY_VECTOR_MSB (val, inner))
6414     ;
6415
6416   else
6417     return 0;
6418
6419   /* Check if VAL is present in every STEP-th element until we find elements
6420      that are 0 or all 1 bits.  */
6421   for (i = 1; i < nunits; ++i)
6422     {
6423       unsigned elt = BYTES_BIG_ENDIAN ? i : nunits - 1 - i;
6424       HOST_WIDE_INT elt_val = const_vector_elt_as_int (op, elt);
6425
6426       /* If the value isn't the splat value, check for the remaining elements
6427          being 0/-1.  */
6428       if (val != elt_val)
6429         {
6430           if (elt_val == 0)
6431             {
6432               for (j = i+1; j < nunits; ++j)
6433                 {
6434                   unsigned elt2 = BYTES_BIG_ENDIAN ? j : nunits - 1 - j;
6435                   if (const_vector_elt_as_int (op, elt2) != 0)
6436                     return 0;
6437                 }
6438
6439               return (nunits - i) * GET_MODE_SIZE (inner);
6440             }
6441
6442           else if ((elt_val & mask) == mask)
6443             {
6444               for (j = i+1; j < nunits; ++j)
6445                 {
6446                   unsigned elt2 = BYTES_BIG_ENDIAN ? j : nunits - 1 - j;
6447                   if ((const_vector_elt_as_int (op, elt2) & mask) != mask)
6448                     return 0;
6449                 }
6450
6451               return -((nunits - i) * GET_MODE_SIZE (inner));
6452             }
6453
6454           else
6455             return 0;
6456         }
6457     }
6458
6459   /* If all elements are equal, we don't need to do VLSDOI.  */
6460   return 0;
6461 }
6462
6463
6464 /* Return true if OP is of the given MODE and can be synthesized
6465    with a vspltisb, vspltish or vspltisw.  */
6466
6467 bool
6468 easy_altivec_constant (rtx op, machine_mode mode)
6469 {
6470   unsigned step, copies;
6471
6472   if (mode == VOIDmode)
6473     mode = GET_MODE (op);
6474   else if (mode != GET_MODE (op))
6475     return false;
6476
6477   /* V2DI/V2DF was added with VSX.  Only allow 0 and all 1's as easy
6478      constants.  */
6479   if (mode == V2DFmode)
6480     return zero_constant (op, mode);
6481
6482   else if (mode == V2DImode)
6483     {
6484       if (GET_CODE (CONST_VECTOR_ELT (op, 0)) != CONST_INT
6485           || GET_CODE (CONST_VECTOR_ELT (op, 1)) != CONST_INT)
6486         return false;
6487
6488       if (zero_constant (op, mode))
6489         return true;
6490
6491       if (INTVAL (CONST_VECTOR_ELT (op, 0)) == -1
6492           && INTVAL (CONST_VECTOR_ELT (op, 1)) == -1)
6493         return true;
6494
6495       return false;
6496     }
6497
6498   /* V1TImode is a special container for TImode.  Ignore for now.  */
6499   else if (mode == V1TImode)
6500     return false;
6501
6502   /* Start with a vspltisw.  */
6503   step = GET_MODE_NUNITS (mode) / 4;
6504   copies = 1;
6505
6506   if (vspltis_constant (op, step, copies))
6507     return true;
6508
6509   /* Then try with a vspltish.  */
6510   if (step == 1)
6511     copies <<= 1;
6512   else
6513     step >>= 1;
6514
6515   if (vspltis_constant (op, step, copies))
6516     return true;
6517
6518   /* And finally a vspltisb.  */
6519   if (step == 1)
6520     copies <<= 1;
6521   else
6522     step >>= 1;
6523
6524   if (vspltis_constant (op, step, copies))
6525     return true;
6526
6527   if (vspltis_shifted (op) != 0)
6528     return true;
6529
6530   return false;
6531 }
6532
6533 /* Generate a VEC_DUPLICATE representing a vspltis[bhw] instruction whose
6534    result is OP.  Abort if it is not possible.  */
6535
6536 rtx
6537 gen_easy_altivec_constant (rtx op)
6538 {
6539   machine_mode mode = GET_MODE (op);
6540   int nunits = GET_MODE_NUNITS (mode);
6541   rtx val = CONST_VECTOR_ELT (op, BYTES_BIG_ENDIAN ? nunits - 1 : 0);
6542   unsigned step = nunits / 4;
6543   unsigned copies = 1;
6544
6545   /* Start with a vspltisw.  */
6546   if (vspltis_constant (op, step, copies))
6547     return gen_rtx_VEC_DUPLICATE (V4SImode, gen_lowpart (SImode, val));
6548
6549   /* Then try with a vspltish.  */
6550   if (step == 1)
6551     copies <<= 1;
6552   else
6553     step >>= 1;
6554
6555   if (vspltis_constant (op, step, copies))
6556     return gen_rtx_VEC_DUPLICATE (V8HImode, gen_lowpart (HImode, val));
6557
6558   /* And finally a vspltisb.  */
6559   if (step == 1)
6560     copies <<= 1;
6561   else
6562     step >>= 1;
6563
6564   if (vspltis_constant (op, step, copies))
6565     return gen_rtx_VEC_DUPLICATE (V16QImode, gen_lowpart (QImode, val));
6566
6567   gcc_unreachable ();
6568 }
6569
6570 /* Return true if OP is of the given MODE and can be synthesized with ISA 3.0
6571    instructions (xxspltib, vupkhsb/vextsb2w/vextb2d).
6572
6573    Return the number of instructions needed (1 or 2) into the address pointed
6574    via NUM_INSNS_PTR.
6575
6576    Return the constant that is being split via CONSTANT_PTR.  */
6577
6578 bool
6579 xxspltib_constant_p (rtx op,
6580                      machine_mode mode,
6581                      int *num_insns_ptr,
6582                      int *constant_ptr)
6583 {
6584   size_t nunits = GET_MODE_NUNITS (mode);
6585   size_t i;
6586   HOST_WIDE_INT value;
6587   rtx element;
6588
6589   /* Set the returned values to out of bound values.  */
6590   *num_insns_ptr = -1;
6591   *constant_ptr = 256;
6592
6593   if (!TARGET_P9_VECTOR)
6594     return false;
6595
6596   if (mode == VOIDmode)
6597     mode = GET_MODE (op);
6598
6599   else if (mode != GET_MODE (op) && GET_MODE (op) != VOIDmode)
6600     return false;
6601
6602   /* Handle (vec_duplicate <constant>).  */
6603   if (GET_CODE (op) == VEC_DUPLICATE)
6604     {
6605       if (mode != V16QImode && mode != V8HImode && mode != V4SImode
6606           && mode != V2DImode)
6607         return false;
6608
6609       element = XEXP (op, 0);
6610       if (!CONST_INT_P (element))
6611         return false;
6612
6613       value = INTVAL (element);
6614       if (!IN_RANGE (value, -128, 127))
6615         return false;
6616     }
6617
6618   /* Handle (const_vector [...]).  */
6619   else if (GET_CODE (op) == CONST_VECTOR)
6620     {
6621       if (mode != V16QImode && mode != V8HImode && mode != V4SImode
6622           && mode != V2DImode)
6623         return false;
6624
6625       element = CONST_VECTOR_ELT (op, 0);
6626       if (!CONST_INT_P (element))
6627         return false;
6628
6629       value = INTVAL (element);
6630       if (!IN_RANGE (value, -128, 127))
6631         return false;
6632
6633       for (i = 1; i < nunits; i++)
6634         {
6635           element = CONST_VECTOR_ELT (op, i);
6636           if (!CONST_INT_P (element))
6637             return false;
6638
6639           if (value != INTVAL (element))
6640             return false;
6641         }
6642     }
6643
6644   /* Handle integer constants being loaded into the upper part of the VSX
6645      register as a scalar.  If the value isn't 0/-1, only allow it if the mode
6646      can go in Altivec registers.  Prefer VSPLTISW/VUPKHSW over XXSPLITIB.  */
6647   else if (CONST_INT_P (op))
6648     {
6649       if (!SCALAR_INT_MODE_P (mode))
6650         return false;
6651
6652       value = INTVAL (op);
6653       if (!IN_RANGE (value, -128, 127))
6654         return false;
6655
6656       if (!IN_RANGE (value, -1, 0))
6657         {
6658           if (!(reg_addr[mode].addr_mask[RELOAD_REG_VMX] & RELOAD_REG_VALID))
6659             return false;
6660
6661           if (EASY_VECTOR_15 (value))
6662             return false;
6663         }
6664     }
6665
6666   else
6667     return false;
6668
6669   /* See if we could generate vspltisw/vspltish directly instead of xxspltib +
6670      sign extend.  Special case 0/-1 to allow getting any VSX register instead
6671      of an Altivec register.  */
6672   if ((mode == V4SImode || mode == V8HImode) && !IN_RANGE (value, -1, 0)
6673       && EASY_VECTOR_15 (value))
6674     return false;
6675
6676   /* Return # of instructions and the constant byte for XXSPLTIB.  */
6677   if (mode == V16QImode)
6678     *num_insns_ptr = 1;
6679
6680   else if (IN_RANGE (value, -1, 0))
6681     *num_insns_ptr = 1;
6682
6683   else
6684     *num_insns_ptr = 2;
6685
6686   *constant_ptr = (int) value;
6687   return true;
6688 }
6689
6690 const char *
6691 output_vec_const_move (rtx *operands)
6692 {
6693   int shift;
6694   machine_mode mode;
6695   rtx dest, vec;
6696
6697   dest = operands[0];
6698   vec = operands[1];
6699   mode = GET_MODE (dest);
6700
6701   if (TARGET_VSX)
6702     {
6703       bool dest_vmx_p = ALTIVEC_REGNO_P (REGNO (dest));
6704       int xxspltib_value = 256;
6705       int num_insns = -1;
6706
6707       if (zero_constant (vec, mode))
6708         {
6709           if (TARGET_P9_VECTOR)
6710             return "xxspltib %x0,0";
6711
6712           else if (dest_vmx_p)
6713             return "vspltisw %0,0";
6714
6715           else
6716             return "xxlxor %x0,%x0,%x0";
6717         }
6718
6719       if (all_ones_constant (vec, mode))
6720         {
6721           if (TARGET_P9_VECTOR)
6722             return "xxspltib %x0,255";
6723
6724           else if (dest_vmx_p)
6725             return "vspltisw %0,-1";
6726
6727           else if (TARGET_P8_VECTOR)
6728             return "xxlorc %x0,%x0,%x0";
6729
6730           else
6731             gcc_unreachable ();
6732         }
6733
6734       if (TARGET_P9_VECTOR
6735           && xxspltib_constant_p (vec, mode, &num_insns, &xxspltib_value))
6736         {
6737           if (num_insns == 1)
6738             {
6739               operands[2] = GEN_INT (xxspltib_value & 0xff);
6740               return "xxspltib %x0,%2";
6741             }
6742
6743           return "#";
6744         }
6745     }
6746
6747   if (TARGET_ALTIVEC)
6748     {
6749       rtx splat_vec;
6750
6751       gcc_assert (ALTIVEC_REGNO_P (REGNO (dest)));
6752       if (zero_constant (vec, mode))
6753         return "vspltisw %0,0";
6754
6755       if (all_ones_constant (vec, mode))
6756         return "vspltisw %0,-1";
6757
6758       /* Do we need to construct a value using VSLDOI?  */
6759       shift = vspltis_shifted (vec);
6760       if (shift != 0)
6761         return "#";
6762
6763       splat_vec = gen_easy_altivec_constant (vec);
6764       gcc_assert (GET_CODE (splat_vec) == VEC_DUPLICATE);
6765       operands[1] = XEXP (splat_vec, 0);
6766       if (!EASY_VECTOR_15 (INTVAL (operands[1])))
6767         return "#";
6768
6769       switch (GET_MODE (splat_vec))
6770         {
6771         case E_V4SImode:
6772           return "vspltisw %0,%1";
6773
6774         case E_V8HImode:
6775           return "vspltish %0,%1";
6776
6777         case E_V16QImode:
6778           return "vspltisb %0,%1";
6779
6780         default:
6781           gcc_unreachable ();
6782         }
6783     }
6784
6785   gcc_unreachable ();
6786 }
6787
6788 /* Initialize TARGET of vector PAIRED to VALS.  */
6789
6790 void
6791 paired_expand_vector_init (rtx target, rtx vals)
6792 {
6793   machine_mode mode = GET_MODE (target);
6794   int n_elts = GET_MODE_NUNITS (mode);
6795   int n_var = 0;
6796   rtx x, new_rtx, tmp, constant_op, op1, op2;
6797   int i;
6798
6799   for (i = 0; i < n_elts; ++i)
6800     {
6801       x = XVECEXP (vals, 0, i);
6802       if (!(CONST_SCALAR_INT_P (x) || CONST_DOUBLE_P (x) || CONST_FIXED_P (x)))
6803         ++n_var;
6804     }
6805   if (n_var == 0)
6806     {
6807       /* Load from constant pool.  */
6808       emit_move_insn (target, gen_rtx_CONST_VECTOR (mode, XVEC (vals, 0)));
6809       return;
6810     }
6811
6812   if (n_var == 2)
6813     {
6814       /* The vector is initialized only with non-constants.  */
6815       new_rtx = gen_rtx_VEC_CONCAT (V2SFmode, XVECEXP (vals, 0, 0),
6816                                 XVECEXP (vals, 0, 1));
6817
6818       emit_move_insn (target, new_rtx);
6819       return;
6820     }
6821   
6822   /* One field is non-constant and the other one is a constant.  Load the
6823      constant from the constant pool and use ps_merge instruction to
6824      construct the whole vector.  */
6825   op1 = XVECEXP (vals, 0, 0);
6826   op2 = XVECEXP (vals, 0, 1);
6827
6828   constant_op = (CONSTANT_P (op1)) ? op1 : op2;
6829
6830   tmp = gen_reg_rtx (GET_MODE (constant_op));
6831   emit_move_insn (tmp, constant_op);
6832
6833   if (CONSTANT_P (op1))
6834     new_rtx = gen_rtx_VEC_CONCAT (V2SFmode, tmp, op2);
6835   else
6836     new_rtx = gen_rtx_VEC_CONCAT (V2SFmode, op1, tmp);
6837
6838   emit_move_insn (target, new_rtx);
6839 }
6840
6841 void
6842 paired_expand_vector_move (rtx operands[])
6843 {
6844   rtx op0 = operands[0], op1 = operands[1];
6845
6846   emit_move_insn (op0, op1);
6847 }
6848
6849 /* Emit vector compare for code RCODE.  DEST is destination, OP1 and
6850    OP2 are two VEC_COND_EXPR operands, CC_OP0 and CC_OP1 are the two
6851    operands for the relation operation COND.  This is a recursive
6852    function.  */
6853
6854 static void
6855 paired_emit_vector_compare (enum rtx_code rcode,
6856                             rtx dest, rtx op0, rtx op1,
6857                             rtx cc_op0, rtx cc_op1)
6858 {
6859   rtx tmp = gen_reg_rtx (V2SFmode);
6860   rtx tmp1, max, min;
6861
6862   gcc_assert (TARGET_PAIRED_FLOAT);
6863   gcc_assert (GET_MODE (op0) == GET_MODE (op1));
6864
6865   switch (rcode)
6866     {
6867     case LT:
6868     case LTU:
6869       paired_emit_vector_compare (GE, dest, op1, op0, cc_op0, cc_op1);
6870       return;
6871     case GE:
6872     case GEU:
6873       emit_insn (gen_subv2sf3 (tmp, cc_op0, cc_op1));
6874       emit_insn (gen_selv2sf4 (dest, tmp, op0, op1, CONST0_RTX (SFmode)));
6875       return;
6876     case LE:
6877     case LEU:
6878       paired_emit_vector_compare (GE, dest, op0, op1, cc_op1, cc_op0);
6879       return;
6880     case GT:
6881       paired_emit_vector_compare (LE, dest, op1, op0, cc_op0, cc_op1);
6882       return;
6883     case EQ:
6884       tmp1 = gen_reg_rtx (V2SFmode);
6885       max = gen_reg_rtx (V2SFmode);
6886       min = gen_reg_rtx (V2SFmode);
6887       gen_reg_rtx (V2SFmode);
6888       
6889       emit_insn (gen_subv2sf3 (tmp, cc_op0, cc_op1));
6890       emit_insn (gen_selv2sf4
6891                  (max, tmp, cc_op0, cc_op1, CONST0_RTX (SFmode)));
6892       emit_insn (gen_subv2sf3 (tmp, cc_op1, cc_op0));
6893       emit_insn (gen_selv2sf4
6894                  (min, tmp, cc_op0, cc_op1, CONST0_RTX (SFmode)));
6895       emit_insn (gen_subv2sf3 (tmp1, min, max));
6896       emit_insn (gen_selv2sf4 (dest, tmp1, op0, op1, CONST0_RTX (SFmode)));
6897       return;
6898     case NE:
6899       paired_emit_vector_compare (EQ, dest, op1, op0, cc_op0, cc_op1);
6900       return;
6901     case UNLE:
6902       paired_emit_vector_compare (LE, dest, op1, op0, cc_op0, cc_op1);
6903       return;
6904     case UNLT:
6905       paired_emit_vector_compare (LT, dest, op1, op0, cc_op0, cc_op1);
6906       return;
6907     case UNGE:
6908       paired_emit_vector_compare (GE, dest, op1, op0, cc_op0, cc_op1);
6909       return;
6910     case UNGT:
6911       paired_emit_vector_compare (GT, dest, op1, op0, cc_op0, cc_op1);
6912       return;
6913     default:
6914       gcc_unreachable ();
6915     }
6916
6917   return;
6918 }
6919
6920 /* Emit vector conditional expression.
6921    DEST is destination. OP1 and OP2 are two VEC_COND_EXPR operands.
6922    CC_OP0 and CC_OP1 are the two operands for the relation operation COND.  */
6923
6924 int
6925 paired_emit_vector_cond_expr (rtx dest, rtx op1, rtx op2,
6926                               rtx cond, rtx cc_op0, rtx cc_op1)
6927 {
6928   enum rtx_code rcode = GET_CODE (cond);
6929
6930   if (!TARGET_PAIRED_FLOAT)
6931     return 0;
6932
6933   paired_emit_vector_compare (rcode, dest, op1, op2, cc_op0, cc_op1);
6934
6935   return 1;
6936 }
6937
6938 /* Initialize vector TARGET to VALS.  */
6939
6940 void
6941 rs6000_expand_vector_init (rtx target, rtx vals)
6942 {
6943   machine_mode mode = GET_MODE (target);
6944   machine_mode inner_mode = GET_MODE_INNER (mode);
6945   int n_elts = GET_MODE_NUNITS (mode);
6946   int n_var = 0, one_var = -1;
6947   bool all_same = true, all_const_zero = true;
6948   rtx x, mem;
6949   int i;
6950
6951   for (i = 0; i < n_elts; ++i)
6952     {
6953       x = XVECEXP (vals, 0, i);
6954       if (!(CONST_SCALAR_INT_P (x) || CONST_DOUBLE_P (x) || CONST_FIXED_P (x)))
6955         ++n_var, one_var = i;
6956       else if (x != CONST0_RTX (inner_mode))
6957         all_const_zero = false;
6958
6959       if (i > 0 && !rtx_equal_p (x, XVECEXP (vals, 0, 0)))
6960         all_same = false;
6961     }
6962
6963   if (n_var == 0)
6964     {
6965       rtx const_vec = gen_rtx_CONST_VECTOR (mode, XVEC (vals, 0));
6966       bool int_vector_p = (GET_MODE_CLASS (mode) == MODE_VECTOR_INT);
6967       if ((int_vector_p || TARGET_VSX) && all_const_zero)
6968         {
6969           /* Zero register.  */
6970           emit_move_insn (target, CONST0_RTX (mode));
6971           return;
6972         }
6973       else if (int_vector_p && easy_vector_constant (const_vec, mode))
6974         {
6975           /* Splat immediate.  */
6976           emit_insn (gen_rtx_SET (target, const_vec));
6977           return;
6978         }
6979       else
6980         {
6981           /* Load from constant pool.  */
6982           emit_move_insn (target, const_vec);
6983           return;
6984         }
6985     }
6986
6987   /* Double word values on VSX can use xxpermdi or lxvdsx.  */
6988   if (VECTOR_MEM_VSX_P (mode) && (mode == V2DFmode || mode == V2DImode))
6989     {
6990       rtx op[2];
6991       size_t i;
6992       size_t num_elements = all_same ? 1 : 2;
6993       for (i = 0; i < num_elements; i++)
6994         {
6995           op[i] = XVECEXP (vals, 0, i);
6996           /* Just in case there is a SUBREG with a smaller mode, do a
6997              conversion.  */
6998           if (GET_MODE (op[i]) != inner_mode)
6999             {
7000               rtx tmp = gen_reg_rtx (inner_mode);
7001               convert_move (tmp, op[i], 0);
7002               op[i] = tmp;
7003             }
7004           /* Allow load with splat double word.  */
7005           else if (MEM_P (op[i]))
7006             {
7007               if (!all_same)
7008                 op[i] = force_reg (inner_mode, op[i]);
7009             }
7010           else if (!REG_P (op[i]))
7011             op[i] = force_reg (inner_mode, op[i]);
7012         }
7013
7014       if (all_same)
7015         {
7016           if (mode == V2DFmode)
7017             emit_insn (gen_vsx_splat_v2df (target, op[0]));
7018           else
7019             emit_insn (gen_vsx_splat_v2di (target, op[0]));
7020         }
7021       else
7022         {
7023           if (mode == V2DFmode)
7024             emit_insn (gen_vsx_concat_v2df (target, op[0], op[1]));
7025           else
7026             emit_insn (gen_vsx_concat_v2di (target, op[0], op[1]));
7027         }
7028       return;
7029     }
7030
7031   /* Special case initializing vector int if we are on 64-bit systems with
7032      direct move or we have the ISA 3.0 instructions.  */
7033   if (mode == V4SImode  && VECTOR_MEM_VSX_P (V4SImode)
7034       && TARGET_DIRECT_MOVE_64BIT)
7035     {
7036       if (all_same)
7037         {
7038           rtx element0 = XVECEXP (vals, 0, 0);
7039           if (MEM_P (element0))
7040             element0 = rs6000_address_for_fpconvert (element0);
7041           else
7042             element0 = force_reg (SImode, element0);
7043
7044           if (TARGET_P9_VECTOR)
7045             emit_insn (gen_vsx_splat_v4si (target, element0));
7046           else
7047             {
7048               rtx tmp = gen_reg_rtx (DImode);
7049               emit_insn (gen_zero_extendsidi2 (tmp, element0));
7050               emit_insn (gen_vsx_splat_v4si_di (target, tmp));
7051             }
7052           return;
7053         }
7054       else
7055         {
7056           rtx elements[4];
7057           size_t i;
7058
7059           for (i = 0; i < 4; i++)
7060             {
7061               elements[i] = XVECEXP (vals, 0, i);
7062               if (!CONST_INT_P (elements[i]) && !REG_P (elements[i]))
7063                 elements[i] = copy_to_mode_reg (SImode, elements[i]);
7064             }
7065
7066           emit_insn (gen_vsx_init_v4si (target, elements[0], elements[1],
7067                                         elements[2], elements[3]));
7068           return;
7069         }
7070     }
7071
7072   /* With single precision floating point on VSX, know that internally single
7073      precision is actually represented as a double, and either make 2 V2DF
7074      vectors, and convert these vectors to single precision, or do one
7075      conversion, and splat the result to the other elements.  */
7076   if (mode == V4SFmode && VECTOR_MEM_VSX_P (V4SFmode))
7077     {
7078       if (all_same)
7079         {
7080           rtx element0 = XVECEXP (vals, 0, 0);
7081
7082           if (TARGET_P9_VECTOR)
7083             {
7084               if (MEM_P (element0))
7085                 element0 = rs6000_address_for_fpconvert (element0);
7086
7087               emit_insn (gen_vsx_splat_v4sf (target, element0));
7088             }
7089
7090           else
7091             {
7092               rtx freg = gen_reg_rtx (V4SFmode);
7093               rtx sreg = force_reg (SFmode, element0);
7094               rtx cvt  = (TARGET_XSCVDPSPN
7095                           ? gen_vsx_xscvdpspn_scalar (freg, sreg)
7096                           : gen_vsx_xscvdpsp_scalar (freg, sreg));
7097
7098               emit_insn (cvt);
7099               emit_insn (gen_vsx_xxspltw_v4sf_direct (target, freg,
7100                                                       const0_rtx));
7101             }
7102         }
7103       else
7104         {
7105           rtx dbl_even = gen_reg_rtx (V2DFmode);
7106           rtx dbl_odd  = gen_reg_rtx (V2DFmode);
7107           rtx flt_even = gen_reg_rtx (V4SFmode);
7108           rtx flt_odd  = gen_reg_rtx (V4SFmode);
7109           rtx op0 = force_reg (SFmode, XVECEXP (vals, 0, 0));
7110           rtx op1 = force_reg (SFmode, XVECEXP (vals, 0, 1));
7111           rtx op2 = force_reg (SFmode, XVECEXP (vals, 0, 2));
7112           rtx op3 = force_reg (SFmode, XVECEXP (vals, 0, 3));
7113
7114           /* Use VMRGEW if we can instead of doing a permute.  */
7115           if (TARGET_P8_VECTOR)
7116             {
7117               emit_insn (gen_vsx_concat_v2sf (dbl_even, op0, op2));
7118               emit_insn (gen_vsx_concat_v2sf (dbl_odd, op1, op3));
7119               emit_insn (gen_vsx_xvcvdpsp (flt_even, dbl_even));
7120               emit_insn (gen_vsx_xvcvdpsp (flt_odd, dbl_odd));
7121               if (BYTES_BIG_ENDIAN)
7122                 emit_insn (gen_p8_vmrgew_v4sf_direct (target, flt_even, flt_odd));
7123               else
7124                 emit_insn (gen_p8_vmrgew_v4sf_direct (target, flt_odd, flt_even));
7125             }
7126           else
7127             {
7128               emit_insn (gen_vsx_concat_v2sf (dbl_even, op0, op1));
7129               emit_insn (gen_vsx_concat_v2sf (dbl_odd, op2, op3));
7130               emit_insn (gen_vsx_xvcvdpsp (flt_even, dbl_even));
7131               emit_insn (gen_vsx_xvcvdpsp (flt_odd, dbl_odd));
7132               rs6000_expand_extract_even (target, flt_even, flt_odd);
7133             }
7134         }
7135       return;
7136     }
7137
7138   /* Special case initializing vector short/char that are splats if we are on
7139      64-bit systems with direct move.  */
7140   if (all_same && TARGET_DIRECT_MOVE_64BIT
7141       && (mode == V16QImode || mode == V8HImode))
7142     {
7143       rtx op0 = XVECEXP (vals, 0, 0);
7144       rtx di_tmp = gen_reg_rtx (DImode);
7145
7146       if (!REG_P (op0))
7147         op0 = force_reg (GET_MODE_INNER (mode), op0);
7148
7149       if (mode == V16QImode)
7150         {
7151           emit_insn (gen_zero_extendqidi2 (di_tmp, op0));
7152           emit_insn (gen_vsx_vspltb_di (target, di_tmp));
7153           return;
7154         }
7155
7156       if (mode == V8HImode)
7157         {
7158           emit_insn (gen_zero_extendhidi2 (di_tmp, op0));
7159           emit_insn (gen_vsx_vsplth_di (target, di_tmp));
7160           return;
7161         }
7162     }
7163
7164   /* Store value to stack temp.  Load vector element.  Splat.  However, splat
7165      of 64-bit items is not supported on Altivec.  */
7166   if (all_same && GET_MODE_SIZE (inner_mode) <= 4)
7167     {
7168       mem = assign_stack_temp (mode, GET_MODE_SIZE (inner_mode));
7169       emit_move_insn (adjust_address_nv (mem, inner_mode, 0),
7170                       XVECEXP (vals, 0, 0));
7171       x = gen_rtx_UNSPEC (VOIDmode,
7172                           gen_rtvec (1, const0_rtx), UNSPEC_LVE);
7173       emit_insn (gen_rtx_PARALLEL (VOIDmode,
7174                                    gen_rtvec (2,
7175                                               gen_rtx_SET (target, mem),
7176                                               x)));
7177       x = gen_rtx_VEC_SELECT (inner_mode, target,
7178                               gen_rtx_PARALLEL (VOIDmode,
7179                                                 gen_rtvec (1, const0_rtx)));
7180       emit_insn (gen_rtx_SET (target, gen_rtx_VEC_DUPLICATE (mode, x)));
7181       return;
7182     }
7183
7184   /* One field is non-constant.  Load constant then overwrite
7185      varying field.  */
7186   if (n_var == 1)
7187     {
7188       rtx copy = copy_rtx (vals);
7189
7190       /* Load constant part of vector, substitute neighboring value for
7191          varying element.  */
7192       XVECEXP (copy, 0, one_var) = XVECEXP (vals, 0, (one_var + 1) % n_elts);
7193       rs6000_expand_vector_init (target, copy);
7194
7195       /* Insert variable.  */
7196       rs6000_expand_vector_set (target, XVECEXP (vals, 0, one_var), one_var);
7197       return;
7198     }
7199
7200   /* Construct the vector in memory one field at a time
7201      and load the whole vector.  */
7202   mem = assign_stack_temp (mode, GET_MODE_SIZE (mode));
7203   for (i = 0; i < n_elts; i++)
7204     emit_move_insn (adjust_address_nv (mem, inner_mode,
7205                                     i * GET_MODE_SIZE (inner_mode)),
7206                     XVECEXP (vals, 0, i));
7207   emit_move_insn (target, mem);
7208 }
7209
7210 /* Set field ELT of TARGET to VAL.  */
7211
7212 void
7213 rs6000_expand_vector_set (rtx target, rtx val, int elt)
7214 {
7215   machine_mode mode = GET_MODE (target);
7216   machine_mode inner_mode = GET_MODE_INNER (mode);
7217   rtx reg = gen_reg_rtx (mode);
7218   rtx mask, mem, x;
7219   int width = GET_MODE_SIZE (inner_mode);
7220   int i;
7221
7222   val = force_reg (GET_MODE (val), val);
7223
7224   if (VECTOR_MEM_VSX_P (mode))
7225     {
7226       rtx insn = NULL_RTX;
7227       rtx elt_rtx = GEN_INT (elt);
7228
7229       if (mode == V2DFmode)
7230         insn = gen_vsx_set_v2df (target, target, val, elt_rtx);
7231
7232       else if (mode == V2DImode)
7233         insn = gen_vsx_set_v2di (target, target, val, elt_rtx);
7234
7235       else if (TARGET_P9_VECTOR && TARGET_POWERPC64)
7236         {
7237           if (mode == V4SImode)
7238             insn = gen_vsx_set_v4si_p9 (target, target, val, elt_rtx);
7239           else if (mode == V8HImode)
7240             insn = gen_vsx_set_v8hi_p9 (target, target, val, elt_rtx);
7241           else if (mode == V16QImode)
7242             insn = gen_vsx_set_v16qi_p9 (target, target, val, elt_rtx);
7243           else if (mode == V4SFmode)
7244             insn = gen_vsx_set_v4sf_p9 (target, target, val, elt_rtx);
7245         }
7246
7247       if (insn)
7248         {
7249           emit_insn (insn);
7250           return;
7251         }
7252     }
7253
7254   /* Simplify setting single element vectors like V1TImode.  */
7255   if (GET_MODE_SIZE (mode) == GET_MODE_SIZE (inner_mode) && elt == 0)
7256     {
7257       emit_move_insn (target, gen_lowpart (mode, val));
7258       return;
7259     }
7260
7261   /* Load single variable value.  */
7262   mem = assign_stack_temp (mode, GET_MODE_SIZE (inner_mode));
7263   emit_move_insn (adjust_address_nv (mem, inner_mode, 0), val);
7264   x = gen_rtx_UNSPEC (VOIDmode,
7265                       gen_rtvec (1, const0_rtx), UNSPEC_LVE);
7266   emit_insn (gen_rtx_PARALLEL (VOIDmode,
7267                                gen_rtvec (2,
7268                                           gen_rtx_SET (reg, mem),
7269                                           x)));
7270
7271   /* Linear sequence.  */
7272   mask = gen_rtx_PARALLEL (V16QImode, rtvec_alloc (16));
7273   for (i = 0; i < 16; ++i)
7274     XVECEXP (mask, 0, i) = GEN_INT (i);
7275
7276   /* Set permute mask to insert element into target.  */
7277   for (i = 0; i < width; ++i)
7278     XVECEXP (mask, 0, elt*width + i)
7279       = GEN_INT (i + 0x10);
7280   x = gen_rtx_CONST_VECTOR (V16QImode, XVEC (mask, 0));
7281
7282   if (BYTES_BIG_ENDIAN)
7283     x = gen_rtx_UNSPEC (mode,
7284                         gen_rtvec (3, target, reg,
7285                                    force_reg (V16QImode, x)),
7286                         UNSPEC_VPERM);
7287   else
7288     {
7289       if (TARGET_P9_VECTOR)
7290         x = gen_rtx_UNSPEC (mode,
7291                             gen_rtvec (3, reg, target,
7292                                        force_reg (V16QImode, x)),
7293                             UNSPEC_VPERMR);
7294       else
7295         {
7296           /* Invert selector.  We prefer to generate VNAND on P8 so
7297              that future fusion opportunities can kick in, but must
7298              generate VNOR elsewhere.  */
7299           rtx notx = gen_rtx_NOT (V16QImode, force_reg (V16QImode, x));
7300           rtx iorx = (TARGET_P8_VECTOR
7301                       ? gen_rtx_IOR (V16QImode, notx, notx)
7302                       : gen_rtx_AND (V16QImode, notx, notx));
7303           rtx tmp = gen_reg_rtx (V16QImode);
7304           emit_insn (gen_rtx_SET (tmp, iorx));
7305
7306           /* Permute with operands reversed and adjusted selector.  */
7307           x = gen_rtx_UNSPEC (mode, gen_rtvec (3, reg, target, tmp),
7308                               UNSPEC_VPERM);
7309         }
7310     }
7311
7312   emit_insn (gen_rtx_SET (target, x));
7313 }
7314
7315 /* Extract field ELT from VEC into TARGET.  */
7316
7317 void
7318 rs6000_expand_vector_extract (rtx target, rtx vec, rtx elt)
7319 {
7320   machine_mode mode = GET_MODE (vec);
7321   machine_mode inner_mode = GET_MODE_INNER (mode);
7322   rtx mem;
7323
7324   if (VECTOR_MEM_VSX_P (mode) && CONST_INT_P (elt))
7325     {
7326       switch (mode)
7327         {
7328         default:
7329           break;
7330         case E_V1TImode:
7331           gcc_assert (INTVAL (elt) == 0 && inner_mode == TImode);
7332           emit_move_insn (target, gen_lowpart (TImode, vec));
7333           break;
7334         case E_V2DFmode:
7335           emit_insn (gen_vsx_extract_v2df (target, vec, elt));
7336           return;
7337         case E_V2DImode:
7338           emit_insn (gen_vsx_extract_v2di (target, vec, elt));
7339           return;
7340         case E_V4SFmode:
7341           emit_insn (gen_vsx_extract_v4sf (target, vec, elt));
7342           return;
7343         case E_V16QImode:
7344           if (TARGET_DIRECT_MOVE_64BIT)
7345             {
7346               emit_insn (gen_vsx_extract_v16qi (target, vec, elt));
7347               return;
7348             }
7349           else
7350             break;
7351         case E_V8HImode:
7352           if (TARGET_DIRECT_MOVE_64BIT)
7353             {
7354               emit_insn (gen_vsx_extract_v8hi (target, vec, elt));
7355               return;
7356             }
7357           else
7358             break;
7359         case E_V4SImode:
7360           if (TARGET_DIRECT_MOVE_64BIT)
7361             {
7362               emit_insn (gen_vsx_extract_v4si (target, vec, elt));
7363               return;
7364             }
7365           break;
7366         }
7367     }
7368   else if (VECTOR_MEM_VSX_P (mode) && !CONST_INT_P (elt)
7369            && TARGET_DIRECT_MOVE_64BIT)
7370     {
7371       if (GET_MODE (elt) != DImode)
7372         {
7373           rtx tmp = gen_reg_rtx (DImode);
7374           convert_move (tmp, elt, 0);
7375           elt = tmp;
7376         }
7377       else if (!REG_P (elt))
7378         elt = force_reg (DImode, elt);
7379
7380       switch (mode)
7381         {
7382         case E_V2DFmode:
7383           emit_insn (gen_vsx_extract_v2df_var (target, vec, elt));
7384           return;
7385
7386         case E_V2DImode:
7387           emit_insn (gen_vsx_extract_v2di_var (target, vec, elt));
7388           return;
7389
7390         case E_V4SFmode:
7391           emit_insn (gen_vsx_extract_v4sf_var (target, vec, elt));
7392           return;
7393
7394         case E_V4SImode:
7395           emit_insn (gen_vsx_extract_v4si_var (target, vec, elt));
7396           return;
7397
7398         case E_V8HImode:
7399           emit_insn (gen_vsx_extract_v8hi_var (target, vec, elt));
7400           return;
7401
7402         case E_V16QImode:
7403           emit_insn (gen_vsx_extract_v16qi_var (target, vec, elt));
7404           return;
7405
7406         default:
7407           gcc_unreachable ();
7408         }
7409     }
7410
7411   gcc_assert (CONST_INT_P (elt));
7412
7413   /* Allocate mode-sized buffer.  */
7414   mem = assign_stack_temp (mode, GET_MODE_SIZE (mode));
7415
7416   emit_move_insn (mem, vec);
7417
7418   /* Add offset to field within buffer matching vector element.  */
7419   mem = adjust_address_nv (mem, inner_mode,
7420                            INTVAL (elt) * GET_MODE_SIZE (inner_mode));
7421
7422   emit_move_insn (target, adjust_address_nv (mem, inner_mode, 0));
7423 }
7424
7425 /* Helper function to return the register number of a RTX.  */
7426 static inline int
7427 regno_or_subregno (rtx op)
7428 {
7429   if (REG_P (op))
7430     return REGNO (op);
7431   else if (SUBREG_P (op))
7432     return subreg_regno (op);
7433   else
7434     gcc_unreachable ();
7435 }
7436
7437 /* Adjust a memory address (MEM) of a vector type to point to a scalar field
7438    within the vector (ELEMENT) with a mode (SCALAR_MODE).  Use a base register
7439    temporary (BASE_TMP) to fixup the address.  Return the new memory address
7440    that is valid for reads or writes to a given register (SCALAR_REG).  */
7441
7442 rtx
7443 rs6000_adjust_vec_address (rtx scalar_reg,
7444                            rtx mem,
7445                            rtx element,
7446                            rtx base_tmp,
7447                            machine_mode scalar_mode)
7448 {
7449   unsigned scalar_size = GET_MODE_SIZE (scalar_mode);
7450   rtx addr = XEXP (mem, 0);
7451   rtx element_offset;
7452   rtx new_addr;
7453   bool valid_addr_p;
7454
7455   /* Vector addresses should not have PRE_INC, PRE_DEC, or PRE_MODIFY.  */
7456   gcc_assert (GET_RTX_CLASS (GET_CODE (addr)) != RTX_AUTOINC);
7457
7458   /* Calculate what we need to add to the address to get the element
7459      address.  */
7460   if (CONST_INT_P (element))
7461     element_offset = GEN_INT (INTVAL (element) * scalar_size);
7462   else
7463     {
7464       int byte_shift = exact_log2 (scalar_size);
7465       gcc_assert (byte_shift >= 0);
7466
7467       if (byte_shift == 0)
7468         element_offset = element;
7469
7470       else
7471         {
7472           if (TARGET_POWERPC64)
7473             emit_insn (gen_ashldi3 (base_tmp, element, GEN_INT (byte_shift)));
7474           else
7475             emit_insn (gen_ashlsi3 (base_tmp, element, GEN_INT (byte_shift)));
7476
7477           element_offset = base_tmp;
7478         }
7479     }
7480
7481   /* Create the new address pointing to the element within the vector.  If we
7482      are adding 0, we don't have to change the address.  */
7483   if (element_offset == const0_rtx)
7484     new_addr = addr;
7485
7486   /* A simple indirect address can be converted into a reg + offset
7487      address.  */
7488   else if (REG_P (addr) || SUBREG_P (addr))
7489     new_addr = gen_rtx_PLUS (Pmode, addr, element_offset);
7490
7491   /* Optimize D-FORM addresses with constant offset with a constant element, to
7492      include the element offset in the address directly.  */
7493   else if (GET_CODE (addr) == PLUS)
7494     {
7495       rtx op0 = XEXP (addr, 0);
7496       rtx op1 = XEXP (addr, 1);
7497       rtx insn;
7498
7499       gcc_assert (REG_P (op0) || SUBREG_P (op0));
7500       if (CONST_INT_P (op1) && CONST_INT_P (element_offset))
7501         {
7502           HOST_WIDE_INT offset = INTVAL (op1) + INTVAL (element_offset);
7503           rtx offset_rtx = GEN_INT (offset);
7504
7505           if (IN_RANGE (offset, -32768, 32767)
7506               && (scalar_size < 8 || (offset & 0x3) == 0))
7507             new_addr = gen_rtx_PLUS (Pmode, op0, offset_rtx);
7508           else
7509             {
7510               emit_move_insn (base_tmp, offset_rtx);
7511               new_addr = gen_rtx_PLUS (Pmode, op0, base_tmp);
7512             }
7513         }
7514       else
7515         {
7516           bool op1_reg_p = (REG_P (op1) || SUBREG_P (op1));
7517           bool ele_reg_p = (REG_P (element_offset) || SUBREG_P (element_offset));
7518
7519           /* Note, ADDI requires the register being added to be a base
7520              register.  If the register was R0, load it up into the temporary
7521              and do the add.  */
7522           if (op1_reg_p
7523               && (ele_reg_p || reg_or_subregno (op1) != FIRST_GPR_REGNO))
7524             {
7525               insn = gen_add3_insn (base_tmp, op1, element_offset);
7526               gcc_assert (insn != NULL_RTX);
7527               emit_insn (insn);
7528             }
7529
7530           else if (ele_reg_p
7531                    && reg_or_subregno (element_offset) != FIRST_GPR_REGNO)
7532             {
7533               insn = gen_add3_insn (base_tmp, element_offset, op1);
7534               gcc_assert (insn != NULL_RTX);
7535               emit_insn (insn);
7536             }
7537
7538           else
7539             {
7540               emit_move_insn (base_tmp, op1);
7541               emit_insn (gen_add2_insn (base_tmp, element_offset));
7542             }
7543
7544           new_addr = gen_rtx_PLUS (Pmode, op0, base_tmp);
7545         }
7546     }
7547
7548   else
7549     {
7550       emit_move_insn (base_tmp, addr);
7551       new_addr = gen_rtx_PLUS (Pmode, base_tmp, element_offset);
7552     }
7553
7554   /* If we have a PLUS, we need to see whether the particular register class
7555      allows for D-FORM or X-FORM addressing.  */
7556   if (GET_CODE (new_addr) == PLUS)
7557     {
7558       rtx op1 = XEXP (new_addr, 1);
7559       addr_mask_type addr_mask;
7560       int scalar_regno = regno_or_subregno (scalar_reg);
7561
7562       gcc_assert (scalar_regno < FIRST_PSEUDO_REGISTER);
7563       if (INT_REGNO_P (scalar_regno))
7564         addr_mask = reg_addr[scalar_mode].addr_mask[RELOAD_REG_GPR];
7565
7566       else if (FP_REGNO_P (scalar_regno))
7567         addr_mask = reg_addr[scalar_mode].addr_mask[RELOAD_REG_FPR];
7568
7569       else if (ALTIVEC_REGNO_P (scalar_regno))
7570         addr_mask = reg_addr[scalar_mode].addr_mask[RELOAD_REG_VMX];
7571
7572       else
7573         gcc_unreachable ();
7574
7575       if (REG_P (op1) || SUBREG_P (op1))
7576         valid_addr_p = (addr_mask & RELOAD_REG_INDEXED) != 0;
7577       else
7578         valid_addr_p = (addr_mask & RELOAD_REG_OFFSET) != 0;
7579     }
7580
7581   else if (REG_P (new_addr) || SUBREG_P (new_addr))
7582     valid_addr_p = true;
7583
7584   else
7585     valid_addr_p = false;
7586
7587   if (!valid_addr_p)
7588     {
7589       emit_move_insn (base_tmp, new_addr);
7590       new_addr = base_tmp;
7591     }
7592
7593   return change_address (mem, scalar_mode, new_addr);
7594 }
7595
7596 /* Split a variable vec_extract operation into the component instructions.  */
7597
7598 void
7599 rs6000_split_vec_extract_var (rtx dest, rtx src, rtx element, rtx tmp_gpr,
7600                               rtx tmp_altivec)
7601 {
7602   machine_mode mode = GET_MODE (src);
7603   machine_mode scalar_mode = GET_MODE (dest);
7604   unsigned scalar_size = GET_MODE_SIZE (scalar_mode);
7605   int byte_shift = exact_log2 (scalar_size);
7606
7607   gcc_assert (byte_shift >= 0);
7608
7609   /* If we are given a memory address, optimize to load just the element.  We
7610      don't have to adjust the vector element number on little endian
7611      systems.  */
7612   if (MEM_P (src))
7613     {
7614       gcc_assert (REG_P (tmp_gpr));
7615       emit_move_insn (dest, rs6000_adjust_vec_address (dest, src, element,
7616                                                        tmp_gpr, scalar_mode));
7617       return;
7618     }
7619
7620   else if (REG_P (src) || SUBREG_P (src))
7621     {
7622       int bit_shift = byte_shift + 3;
7623       rtx element2;
7624       int dest_regno = regno_or_subregno (dest);
7625       int src_regno = regno_or_subregno (src);
7626       int element_regno = regno_or_subregno (element);
7627
7628       gcc_assert (REG_P (tmp_gpr));
7629
7630       /* See if we want to generate VEXTU{B,H,W}{L,R}X if the destination is in
7631          a general purpose register.  */
7632       if (TARGET_P9_VECTOR
7633           && (mode == V16QImode || mode == V8HImode || mode == V4SImode)
7634           && INT_REGNO_P (dest_regno)
7635           && ALTIVEC_REGNO_P (src_regno)
7636           && INT_REGNO_P (element_regno))
7637         {
7638           rtx dest_si = gen_rtx_REG (SImode, dest_regno);
7639           rtx element_si = gen_rtx_REG (SImode, element_regno);
7640
7641           if (mode == V16QImode)
7642             emit_insn (VECTOR_ELT_ORDER_BIG
7643                        ? gen_vextublx (dest_si, element_si, src)
7644                        : gen_vextubrx (dest_si, element_si, src));
7645
7646           else if (mode == V8HImode)
7647             {
7648               rtx tmp_gpr_si = gen_rtx_REG (SImode, REGNO (tmp_gpr));
7649               emit_insn (gen_ashlsi3 (tmp_gpr_si, element_si, const1_rtx));
7650               emit_insn (VECTOR_ELT_ORDER_BIG
7651                          ? gen_vextuhlx (dest_si, tmp_gpr_si, src)
7652                          : gen_vextuhrx (dest_si, tmp_gpr_si, src));
7653             }
7654
7655
7656           else
7657             {
7658               rtx tmp_gpr_si = gen_rtx_REG (SImode, REGNO (tmp_gpr));
7659               emit_insn (gen_ashlsi3 (tmp_gpr_si, element_si, const2_rtx));
7660               emit_insn (VECTOR_ELT_ORDER_BIG
7661                          ? gen_vextuwlx (dest_si, tmp_gpr_si, src)
7662                          : gen_vextuwrx (dest_si, tmp_gpr_si, src));
7663             }
7664
7665           return;
7666         }
7667
7668
7669       gcc_assert (REG_P (tmp_altivec));
7670
7671       /* For little endian, adjust element ordering.  For V2DI/V2DF, we can use
7672          an XOR, otherwise we need to subtract.  The shift amount is so VSLO
7673          will shift the element into the upper position (adding 3 to convert a
7674          byte shift into a bit shift).  */
7675       if (scalar_size == 8)
7676         {
7677           if (!VECTOR_ELT_ORDER_BIG)
7678             {
7679               emit_insn (gen_xordi3 (tmp_gpr, element, const1_rtx));
7680               element2 = tmp_gpr;
7681             }
7682           else
7683             element2 = element;
7684
7685           /* Generate RLDIC directly to shift left 6 bits and retrieve 1
7686              bit.  */
7687           emit_insn (gen_rtx_SET (tmp_gpr,
7688                                   gen_rtx_AND (DImode,
7689                                                gen_rtx_ASHIFT (DImode,
7690                                                                element2,
7691                                                                GEN_INT (6)),
7692                                                GEN_INT (64))));
7693         }
7694       else
7695         {
7696           if (!VECTOR_ELT_ORDER_BIG)
7697             {
7698               rtx num_ele_m1 = GEN_INT (GET_MODE_NUNITS (mode) - 1);
7699
7700               emit_insn (gen_anddi3 (tmp_gpr, element, num_ele_m1));
7701               emit_insn (gen_subdi3 (tmp_gpr, num_ele_m1, tmp_gpr));
7702               element2 = tmp_gpr;
7703             }
7704           else
7705             element2 = element;
7706
7707           emit_insn (gen_ashldi3 (tmp_gpr, element2, GEN_INT (bit_shift)));
7708         }
7709
7710       /* Get the value into the lower byte of the Altivec register where VSLO
7711          expects it.  */
7712       if (TARGET_P9_VECTOR)
7713         emit_insn (gen_vsx_splat_v2di (tmp_altivec, tmp_gpr));
7714       else if (can_create_pseudo_p ())
7715         emit_insn (gen_vsx_concat_v2di (tmp_altivec, tmp_gpr, tmp_gpr));
7716       else
7717         {
7718           rtx tmp_di = gen_rtx_REG (DImode, REGNO (tmp_altivec));
7719           emit_move_insn (tmp_di, tmp_gpr);
7720           emit_insn (gen_vsx_concat_v2di (tmp_altivec, tmp_di, tmp_di));
7721         }
7722
7723       /* Do the VSLO to get the value into the final location.  */
7724       switch (mode)
7725         {
7726         case E_V2DFmode:
7727           emit_insn (gen_vsx_vslo_v2df (dest, src, tmp_altivec));
7728           return;
7729
7730         case E_V2DImode:
7731           emit_insn (gen_vsx_vslo_v2di (dest, src, tmp_altivec));
7732           return;
7733
7734         case E_V4SFmode:
7735           {
7736             rtx tmp_altivec_di = gen_rtx_REG (DImode, REGNO (tmp_altivec));
7737             rtx tmp_altivec_v4sf = gen_rtx_REG (V4SFmode, REGNO (tmp_altivec));
7738             rtx src_v2di = gen_rtx_REG (V2DImode, REGNO (src));
7739             emit_insn (gen_vsx_vslo_v2di (tmp_altivec_di, src_v2di,
7740                                           tmp_altivec));
7741
7742             emit_insn (gen_vsx_xscvspdp_scalar2 (dest, tmp_altivec_v4sf));
7743             return;
7744           }
7745
7746         case E_V4SImode:
7747         case E_V8HImode:
7748         case E_V16QImode:
7749           {
7750             rtx tmp_altivec_di = gen_rtx_REG (DImode, REGNO (tmp_altivec));
7751             rtx src_v2di = gen_rtx_REG (V2DImode, REGNO (src));
7752             rtx tmp_gpr_di = gen_rtx_REG (DImode, REGNO (dest));
7753             emit_insn (gen_vsx_vslo_v2di (tmp_altivec_di, src_v2di,
7754                                           tmp_altivec));
7755             emit_move_insn (tmp_gpr_di, tmp_altivec_di);
7756             emit_insn (gen_ashrdi3 (tmp_gpr_di, tmp_gpr_di,
7757                                     GEN_INT (64 - (8 * scalar_size))));
7758             return;
7759           }
7760
7761         default:
7762           gcc_unreachable ();
7763         }
7764
7765       return;
7766     }
7767   else
7768     gcc_unreachable ();
7769  }
7770
7771 /* Helper function for rs6000_split_v4si_init to build up a DImode value from
7772    two SImode values.  */
7773
7774 static void
7775 rs6000_split_v4si_init_di_reg (rtx dest, rtx si1, rtx si2, rtx tmp)
7776 {
7777   const unsigned HOST_WIDE_INT mask_32bit = HOST_WIDE_INT_C (0xffffffff);
7778
7779   if (CONST_INT_P (si1) && CONST_INT_P (si2))
7780     {
7781       unsigned HOST_WIDE_INT const1 = (UINTVAL (si1) & mask_32bit) << 32;
7782       unsigned HOST_WIDE_INT const2 = UINTVAL (si2) & mask_32bit;
7783
7784       emit_move_insn (dest, GEN_INT (const1 | const2));
7785       return;
7786     }
7787
7788   /* Put si1 into upper 32-bits of dest.  */
7789   if (CONST_INT_P (si1))
7790     emit_move_insn (dest, GEN_INT ((UINTVAL (si1) & mask_32bit) << 32));
7791   else
7792     {
7793       /* Generate RLDIC.  */
7794       rtx si1_di = gen_rtx_REG (DImode, regno_or_subregno (si1));
7795       rtx shift_rtx = gen_rtx_ASHIFT (DImode, si1_di, GEN_INT (32));
7796       rtx mask_rtx = GEN_INT (mask_32bit << 32);
7797       rtx and_rtx = gen_rtx_AND (DImode, shift_rtx, mask_rtx);
7798       gcc_assert (!reg_overlap_mentioned_p (dest, si1));
7799       emit_insn (gen_rtx_SET (dest, and_rtx));
7800     }
7801
7802   /* Put si2 into the temporary.  */
7803   gcc_assert (!reg_overlap_mentioned_p (dest, tmp));
7804   if (CONST_INT_P (si2))
7805     emit_move_insn (tmp, GEN_INT (UINTVAL (si2) & mask_32bit));
7806   else
7807     emit_insn (gen_zero_extendsidi2 (tmp, si2));
7808
7809   /* Combine the two parts.  */
7810   emit_insn (gen_iordi3 (dest, dest, tmp));
7811   return;
7812 }
7813
7814 /* Split a V4SI initialization.  */
7815
7816 void
7817 rs6000_split_v4si_init (rtx operands[])
7818 {
7819   rtx dest = operands[0];
7820
7821   /* Destination is a GPR, build up the two DImode parts in place.  */
7822   if (REG_P (dest) || SUBREG_P (dest))
7823     {
7824       int d_regno = regno_or_subregno (dest);
7825       rtx scalar1 = operands[1];
7826       rtx scalar2 = operands[2];
7827       rtx scalar3 = operands[3];
7828       rtx scalar4 = operands[4];
7829       rtx tmp1 = operands[5];
7830       rtx tmp2 = operands[6];
7831
7832       /* Even though we only need one temporary (plus the destination, which
7833          has an early clobber constraint, try to use two temporaries, one for
7834          each double word created.  That way the 2nd insn scheduling pass can
7835          rearrange things so the two parts are done in parallel.  */
7836       if (BYTES_BIG_ENDIAN)
7837         {
7838           rtx di_lo = gen_rtx_REG (DImode, d_regno);
7839           rtx di_hi = gen_rtx_REG (DImode, d_regno + 1);
7840           rs6000_split_v4si_init_di_reg (di_lo, scalar1, scalar2, tmp1);
7841           rs6000_split_v4si_init_di_reg (di_hi, scalar3, scalar4, tmp2);
7842         }
7843       else
7844         {
7845           rtx di_lo = gen_rtx_REG (DImode, d_regno + 1);
7846           rtx di_hi = gen_rtx_REG (DImode, d_regno);
7847           gcc_assert (!VECTOR_ELT_ORDER_BIG);
7848           rs6000_split_v4si_init_di_reg (di_lo, scalar4, scalar3, tmp1);
7849           rs6000_split_v4si_init_di_reg (di_hi, scalar2, scalar1, tmp2);
7850         }
7851       return;
7852     }
7853
7854   else
7855     gcc_unreachable ();
7856 }
7857
7858 /* Return alignment of TYPE.  Existing alignment is ALIGN.  HOW
7859    selects whether the alignment is abi mandated, optional, or
7860    both abi and optional alignment.  */
7861    
7862 unsigned int
7863 rs6000_data_alignment (tree type, unsigned int align, enum data_align how)
7864 {
7865   if (how != align_opt)
7866     {
7867       if (TREE_CODE (type) == VECTOR_TYPE)
7868         {
7869           if (TARGET_PAIRED_FLOAT && PAIRED_VECTOR_MODE (TYPE_MODE (type)))
7870             {
7871               if (align < 64)
7872                 align = 64;
7873             }
7874           else if (align < 128)
7875             align = 128;
7876         }
7877     }
7878
7879   if (how != align_abi)
7880     {
7881       if (TREE_CODE (type) == ARRAY_TYPE
7882           && TYPE_MODE (TREE_TYPE (type)) == QImode)
7883         {
7884           if (align < BITS_PER_WORD)
7885             align = BITS_PER_WORD;
7886         }
7887     }
7888
7889   return align;
7890 }
7891
7892 /* Implement TARGET_SLOW_UNALIGNED_ACCESS.  Altivec vector memory
7893    instructions simply ignore the low bits; VSX memory instructions
7894    are aligned to 4 or 8 bytes.  */
7895
7896 static bool
7897 rs6000_slow_unaligned_access (machine_mode mode, unsigned int align)
7898 {
7899   return (STRICT_ALIGNMENT
7900           || (!TARGET_EFFICIENT_UNALIGNED_VSX
7901               && ((SCALAR_FLOAT_MODE_NOT_VECTOR_P (mode) && align < 32)
7902                   || ((VECTOR_MODE_P (mode) || FLOAT128_VECTOR_P (mode))
7903                       && (int) align < VECTOR_ALIGN (mode)))));
7904 }
7905
7906 /* Previous GCC releases forced all vector types to have 16-byte alignment.  */
7907
7908 bool
7909 rs6000_special_adjust_field_align_p (tree type, unsigned int computed)
7910 {
7911   if (TARGET_ALTIVEC && TREE_CODE (type) == VECTOR_TYPE)
7912     {
7913       if (computed != 128)
7914         {
7915           static bool warned;
7916           if (!warned && warn_psabi)
7917             {
7918               warned = true;
7919               inform (input_location,
7920                       "the layout of aggregates containing vectors with"
7921                       " %d-byte alignment has changed in GCC 5",
7922                       computed / BITS_PER_UNIT);
7923             }
7924         }
7925       /* In current GCC there is no special case.  */
7926       return false;
7927     }
7928
7929   return false;
7930 }
7931
7932 /* AIX increases natural record alignment to doubleword if the first
7933    field is an FP double while the FP fields remain word aligned.  */
7934
7935 unsigned int
7936 rs6000_special_round_type_align (tree type, unsigned int computed,
7937                                  unsigned int specified)
7938 {
7939   unsigned int align = MAX (computed, specified);
7940   tree field = TYPE_FIELDS (type);
7941
7942   /* Skip all non field decls */
7943   while (field != NULL && TREE_CODE (field) != FIELD_DECL)
7944     field = DECL_CHAIN (field);
7945
7946   if (field != NULL && field != type)
7947     {
7948       type = TREE_TYPE (field);
7949       while (TREE_CODE (type) == ARRAY_TYPE)
7950         type = TREE_TYPE (type);
7951
7952       if (type != error_mark_node && TYPE_MODE (type) == DFmode)
7953         align = MAX (align, 64);
7954     }
7955
7956   return align;
7957 }
7958
7959 /* Darwin increases record alignment to the natural alignment of
7960    the first field.  */
7961
7962 unsigned int
7963 darwin_rs6000_special_round_type_align (tree type, unsigned int computed,
7964                                         unsigned int specified)
7965 {
7966   unsigned int align = MAX (computed, specified);
7967
7968   if (TYPE_PACKED (type))
7969     return align;
7970
7971   /* Find the first field, looking down into aggregates.  */
7972   do {
7973     tree field = TYPE_FIELDS (type);
7974     /* Skip all non field decls */
7975     while (field != NULL && TREE_CODE (field) != FIELD_DECL)
7976       field = DECL_CHAIN (field);
7977     if (! field)
7978       break;
7979     /* A packed field does not contribute any extra alignment.  */
7980     if (DECL_PACKED (field))
7981       return align;
7982     type = TREE_TYPE (field);
7983     while (TREE_CODE (type) == ARRAY_TYPE)
7984       type = TREE_TYPE (type);
7985   } while (AGGREGATE_TYPE_P (type));
7986
7987   if (! AGGREGATE_TYPE_P (type) && type != error_mark_node)
7988     align = MAX (align, TYPE_ALIGN (type));
7989
7990   return align;
7991 }
7992
7993 /* Return 1 for an operand in small memory on V.4/eabi.  */
7994
7995 int
7996 small_data_operand (rtx op ATTRIBUTE_UNUSED,
7997                     machine_mode mode ATTRIBUTE_UNUSED)
7998 {
7999 #if TARGET_ELF
8000   rtx sym_ref;
8001
8002   if (rs6000_sdata == SDATA_NONE || rs6000_sdata == SDATA_DATA)
8003     return 0;
8004
8005   if (DEFAULT_ABI != ABI_V4)
8006     return 0;
8007
8008   if (GET_CODE (op) == SYMBOL_REF)
8009     sym_ref = op;
8010
8011   else if (GET_CODE (op) != CONST
8012            || GET_CODE (XEXP (op, 0)) != PLUS
8013            || GET_CODE (XEXP (XEXP (op, 0), 0)) != SYMBOL_REF
8014            || GET_CODE (XEXP (XEXP (op, 0), 1)) != CONST_INT)
8015     return 0;
8016
8017   else
8018     {
8019       rtx sum = XEXP (op, 0);
8020       HOST_WIDE_INT summand;
8021
8022       /* We have to be careful here, because it is the referenced address
8023          that must be 32k from _SDA_BASE_, not just the symbol.  */
8024       summand = INTVAL (XEXP (sum, 1));
8025       if (summand < 0 || summand > g_switch_value)
8026         return 0;
8027
8028       sym_ref = XEXP (sum, 0);
8029     }
8030
8031   return SYMBOL_REF_SMALL_P (sym_ref);
8032 #else
8033   return 0;
8034 #endif
8035 }
8036
8037 /* Return true if either operand is a general purpose register.  */
8038
8039 bool
8040 gpr_or_gpr_p (rtx op0, rtx op1)
8041 {
8042   return ((REG_P (op0) && INT_REGNO_P (REGNO (op0)))
8043           || (REG_P (op1) && INT_REGNO_P (REGNO (op1))));
8044 }
8045
8046 /* Return true if this is a move direct operation between GPR registers and
8047    floating point/VSX registers.  */
8048
8049 bool
8050 direct_move_p (rtx op0, rtx op1)
8051 {
8052   int regno0, regno1;
8053
8054   if (!REG_P (op0) || !REG_P (op1))
8055     return false;
8056
8057   if (!TARGET_DIRECT_MOVE && !TARGET_MFPGPR)
8058     return false;
8059
8060   regno0 = REGNO (op0);
8061   regno1 = REGNO (op1);
8062   if (regno0 >= FIRST_PSEUDO_REGISTER || regno1 >= FIRST_PSEUDO_REGISTER)
8063     return false;
8064
8065   if (INT_REGNO_P (regno0))
8066     return (TARGET_DIRECT_MOVE) ? VSX_REGNO_P (regno1) : FP_REGNO_P (regno1);
8067
8068   else if (INT_REGNO_P (regno1))
8069     {
8070       if (TARGET_MFPGPR && FP_REGNO_P (regno0))
8071         return true;
8072
8073       else if (TARGET_DIRECT_MOVE && VSX_REGNO_P (regno0))
8074         return true;
8075     }
8076
8077   return false;
8078 }
8079
8080 /* Return true if the OFFSET is valid for the quad address instructions that
8081    use d-form (register + offset) addressing.  */
8082
8083 static inline bool
8084 quad_address_offset_p (HOST_WIDE_INT offset)
8085 {
8086   return (IN_RANGE (offset, -32768, 32767) && ((offset) & 0xf) == 0);
8087 }
8088
8089 /* Return true if the ADDR is an acceptable address for a quad memory
8090    operation of mode MODE (either LQ/STQ for general purpose registers, or
8091    LXV/STXV for vector registers under ISA 3.0.  GPR_P is true if this address
8092    is intended for LQ/STQ.  If it is false, the address is intended for the ISA
8093    3.0 LXV/STXV instruction.  */
8094
8095 bool
8096 quad_address_p (rtx addr, machine_mode mode, bool strict)
8097 {
8098   rtx op0, op1;
8099
8100   if (GET_MODE_SIZE (mode) != 16)
8101     return false;
8102
8103   if (legitimate_indirect_address_p (addr, strict))
8104     return true;
8105
8106   if (VECTOR_MODE_P (mode) && !mode_supports_vsx_dform_quad (mode))
8107     return false;
8108
8109   if (GET_CODE (addr) != PLUS)
8110     return false;
8111
8112   op0 = XEXP (addr, 0);
8113   if (!REG_P (op0) || !INT_REG_OK_FOR_BASE_P (op0, strict))
8114     return false;
8115
8116   op1 = XEXP (addr, 1);
8117   if (!CONST_INT_P (op1))
8118     return false;
8119
8120   return quad_address_offset_p (INTVAL (op1));
8121 }
8122
8123 /* Return true if this is a load or store quad operation.  This function does
8124    not handle the atomic quad memory instructions.  */
8125
8126 bool
8127 quad_load_store_p (rtx op0, rtx op1)
8128 {
8129   bool ret;
8130
8131   if (!TARGET_QUAD_MEMORY)
8132     ret = false;
8133
8134   else if (REG_P (op0) && MEM_P (op1))
8135     ret = (quad_int_reg_operand (op0, GET_MODE (op0))
8136            && quad_memory_operand (op1, GET_MODE (op1))
8137            && !reg_overlap_mentioned_p (op0, op1));
8138
8139   else if (MEM_P (op0) && REG_P (op1))
8140     ret = (quad_memory_operand (op0, GET_MODE (op0))
8141            && quad_int_reg_operand (op1, GET_MODE (op1)));
8142
8143   else
8144     ret = false;
8145
8146   if (TARGET_DEBUG_ADDR)
8147     {
8148       fprintf (stderr, "\n========== quad_load_store, return %s\n",
8149                ret ? "true" : "false");
8150       debug_rtx (gen_rtx_SET (op0, op1));
8151     }
8152
8153   return ret;
8154 }
8155
8156 /* Given an address, return a constant offset term if one exists.  */
8157
8158 static rtx
8159 address_offset (rtx op)
8160 {
8161   if (GET_CODE (op) == PRE_INC
8162       || GET_CODE (op) == PRE_DEC)
8163     op = XEXP (op, 0);
8164   else if (GET_CODE (op) == PRE_MODIFY
8165            || GET_CODE (op) == LO_SUM)
8166     op = XEXP (op, 1);
8167
8168   if (GET_CODE (op) == CONST)
8169     op = XEXP (op, 0);
8170
8171   if (GET_CODE (op) == PLUS)
8172     op = XEXP (op, 1);
8173
8174   if (CONST_INT_P (op))
8175     return op;
8176
8177   return NULL_RTX;
8178 }
8179
8180 /* Return true if the MEM operand is a memory operand suitable for use
8181    with a (full width, possibly multiple) gpr load/store.  On
8182    powerpc64 this means the offset must be divisible by 4.
8183    Implements 'Y' constraint.
8184
8185    Accept direct, indexed, offset, lo_sum and tocref.  Since this is
8186    a constraint function we know the operand has satisfied a suitable
8187    memory predicate.  Also accept some odd rtl generated by reload
8188    (see rs6000_legitimize_reload_address for various forms).  It is
8189    important that reload rtl be accepted by appropriate constraints
8190    but not by the operand predicate.
8191
8192    Offsetting a lo_sum should not be allowed, except where we know by
8193    alignment that a 32k boundary is not crossed, but see the ???
8194    comment in rs6000_legitimize_reload_address.  Note that by
8195    "offsetting" here we mean a further offset to access parts of the
8196    MEM.  It's fine to have a lo_sum where the inner address is offset
8197    from a sym, since the same sym+offset will appear in the high part
8198    of the address calculation.  */
8199
8200 bool
8201 mem_operand_gpr (rtx op, machine_mode mode)
8202 {
8203   unsigned HOST_WIDE_INT offset;
8204   int extra;
8205   rtx addr = XEXP (op, 0);
8206
8207   op = address_offset (addr);
8208   if (op == NULL_RTX)
8209     return true;
8210
8211   offset = INTVAL (op);
8212   if (TARGET_POWERPC64 && (offset & 3) != 0)
8213     return false;
8214
8215   extra = GET_MODE_SIZE (mode) - UNITS_PER_WORD;
8216   if (extra < 0)
8217     extra = 0;
8218
8219   if (GET_CODE (addr) == LO_SUM)
8220     /* For lo_sum addresses, we must allow any offset except one that
8221        causes a wrap, so test only the low 16 bits.  */
8222     offset = ((offset & 0xffff) ^ 0x8000) - 0x8000;
8223
8224   return offset + 0x8000 < 0x10000u - extra;
8225 }
8226
8227 /* As above, but for DS-FORM VSX insns.  Unlike mem_operand_gpr,
8228    enforce an offset divisible by 4 even for 32-bit.  */
8229
8230 bool
8231 mem_operand_ds_form (rtx op, machine_mode mode)
8232 {
8233   unsigned HOST_WIDE_INT offset;
8234   int extra;
8235   rtx addr = XEXP (op, 0);
8236
8237   if (!offsettable_address_p (false, mode, addr))
8238     return false;
8239
8240   op = address_offset (addr);
8241   if (op == NULL_RTX)
8242     return true;
8243
8244   offset = INTVAL (op);
8245   if ((offset & 3) != 0)
8246     return false;
8247
8248   extra = GET_MODE_SIZE (mode) - UNITS_PER_WORD;
8249   if (extra < 0)
8250     extra = 0;
8251
8252   if (GET_CODE (addr) == LO_SUM)
8253     /* For lo_sum addresses, we must allow any offset except one that
8254        causes a wrap, so test only the low 16 bits.  */
8255     offset = ((offset & 0xffff) ^ 0x8000) - 0x8000;
8256
8257   return offset + 0x8000 < 0x10000u - extra;
8258 }
8259 \f
8260 /* Subroutines of rs6000_legitimize_address and rs6000_legitimate_address_p.  */
8261
8262 static bool
8263 reg_offset_addressing_ok_p (machine_mode mode)
8264 {
8265   switch (mode)
8266     {
8267     case E_V16QImode:
8268     case E_V8HImode:
8269     case E_V4SFmode:
8270     case E_V4SImode:
8271     case E_V2DFmode:
8272     case E_V2DImode:
8273     case E_V1TImode:
8274     case E_TImode:
8275     case E_TFmode:
8276     case E_KFmode:
8277       /* AltiVec/VSX vector modes.  Only reg+reg addressing was valid until the
8278          ISA 3.0 vector d-form addressing mode was added.  While TImode is not
8279          a vector mode, if we want to use the VSX registers to move it around,
8280          we need to restrict ourselves to reg+reg addressing.  Similarly for
8281          IEEE 128-bit floating point that is passed in a single vector
8282          register.  */
8283       if (VECTOR_MEM_ALTIVEC_OR_VSX_P (mode))
8284         return mode_supports_vsx_dform_quad (mode);
8285       break;
8286
8287     case E_V2SImode:
8288     case E_V2SFmode:
8289        /* Paired vector modes.  Only reg+reg addressing is valid.  */
8290       if (TARGET_PAIRED_FLOAT)
8291         return false;
8292       break;
8293
8294     case E_SDmode:
8295       /* If we can do direct load/stores of SDmode, restrict it to reg+reg
8296          addressing for the LFIWZX and STFIWX instructions.  */
8297       if (TARGET_NO_SDMODE_STACK)
8298         return false;
8299       break;
8300
8301     default:
8302       break;
8303     }
8304
8305   return true;
8306 }
8307
8308 static bool
8309 virtual_stack_registers_memory_p (rtx op)
8310 {
8311   int regnum;
8312
8313   if (GET_CODE (op) == REG)
8314     regnum = REGNO (op);
8315
8316   else if (GET_CODE (op) == PLUS
8317            && GET_CODE (XEXP (op, 0)) == REG
8318            && GET_CODE (XEXP (op, 1)) == CONST_INT)
8319     regnum = REGNO (XEXP (op, 0));
8320
8321   else
8322     return false;
8323
8324   return (regnum >= FIRST_VIRTUAL_REGISTER
8325           && regnum <= LAST_VIRTUAL_POINTER_REGISTER);
8326 }
8327
8328 /* Return true if a MODE sized memory accesses to OP plus OFFSET
8329    is known to not straddle a 32k boundary.  This function is used
8330    to determine whether -mcmodel=medium code can use TOC pointer
8331    relative addressing for OP.  This means the alignment of the TOC
8332    pointer must also be taken into account, and unfortunately that is
8333    only 8 bytes.  */ 
8334
8335 #ifndef POWERPC64_TOC_POINTER_ALIGNMENT
8336 #define POWERPC64_TOC_POINTER_ALIGNMENT 8
8337 #endif
8338
8339 static bool
8340 offsettable_ok_by_alignment (rtx op, HOST_WIDE_INT offset,
8341                              machine_mode mode)
8342 {
8343   tree decl;
8344   unsigned HOST_WIDE_INT dsize, dalign, lsb, mask;
8345
8346   if (GET_CODE (op) != SYMBOL_REF)
8347     return false;
8348
8349   /* ISA 3.0 vector d-form addressing is restricted, don't allow
8350      SYMBOL_REF.  */
8351   if (mode_supports_vsx_dform_quad (mode))
8352     return false;
8353
8354   dsize = GET_MODE_SIZE (mode);
8355   decl = SYMBOL_REF_DECL (op);
8356   if (!decl)
8357     {
8358       if (dsize == 0)
8359         return false;
8360
8361       /* -fsection-anchors loses the original SYMBOL_REF_DECL when
8362          replacing memory addresses with an anchor plus offset.  We
8363          could find the decl by rummaging around in the block->objects
8364          VEC for the given offset but that seems like too much work.  */
8365       dalign = BITS_PER_UNIT;
8366       if (SYMBOL_REF_HAS_BLOCK_INFO_P (op)
8367           && SYMBOL_REF_ANCHOR_P (op)
8368           && SYMBOL_REF_BLOCK (op) != NULL)
8369         {
8370           struct object_block *block = SYMBOL_REF_BLOCK (op);
8371
8372           dalign = block->alignment;
8373           offset += SYMBOL_REF_BLOCK_OFFSET (op);
8374         }
8375       else if (CONSTANT_POOL_ADDRESS_P (op))
8376         {
8377           /* It would be nice to have get_pool_align()..  */
8378           machine_mode cmode = get_pool_mode (op);
8379
8380           dalign = GET_MODE_ALIGNMENT (cmode);
8381         }
8382     }
8383   else if (DECL_P (decl))
8384     {
8385       dalign = DECL_ALIGN (decl);
8386
8387       if (dsize == 0)
8388         {
8389           /* Allow BLKmode when the entire object is known to not
8390              cross a 32k boundary.  */
8391           if (!DECL_SIZE_UNIT (decl))
8392             return false;
8393
8394           if (!tree_fits_uhwi_p (DECL_SIZE_UNIT (decl)))
8395             return false;
8396
8397           dsize = tree_to_uhwi (DECL_SIZE_UNIT (decl));
8398           if (dsize > 32768)
8399             return false;
8400
8401           dalign /= BITS_PER_UNIT;
8402           if (dalign > POWERPC64_TOC_POINTER_ALIGNMENT)
8403             dalign = POWERPC64_TOC_POINTER_ALIGNMENT;
8404           return dalign >= dsize;
8405         }
8406     }
8407   else
8408     gcc_unreachable ();
8409
8410   /* Find how many bits of the alignment we know for this access.  */
8411   dalign /= BITS_PER_UNIT;
8412   if (dalign > POWERPC64_TOC_POINTER_ALIGNMENT)
8413     dalign = POWERPC64_TOC_POINTER_ALIGNMENT;
8414   mask = dalign - 1;
8415   lsb = offset & -offset;
8416   mask &= lsb - 1;
8417   dalign = mask + 1;
8418
8419   return dalign >= dsize;
8420 }
8421
8422 static bool
8423 constant_pool_expr_p (rtx op)
8424 {
8425   rtx base, offset;
8426
8427   split_const (op, &base, &offset);
8428   return (GET_CODE (base) == SYMBOL_REF
8429           && CONSTANT_POOL_ADDRESS_P (base)
8430           && ASM_OUTPUT_SPECIAL_POOL_ENTRY_P (get_pool_constant (base), Pmode));
8431 }
8432
8433 /* These are only used to pass through from print_operand/print_operand_address
8434    to rs6000_output_addr_const_extra over the intervening function
8435    output_addr_const which is not target code.  */
8436 static const_rtx tocrel_base_oac, tocrel_offset_oac;
8437
8438 /* Return true if OP is a toc pointer relative address (the output
8439    of create_TOC_reference).  If STRICT, do not match non-split
8440    -mcmodel=large/medium toc pointer relative addresses.  If the pointers 
8441    are non-NULL, place base and offset pieces in TOCREL_BASE_RET and 
8442    TOCREL_OFFSET_RET respectively.  */
8443
8444 bool
8445 toc_relative_expr_p (const_rtx op, bool strict, const_rtx *tocrel_base_ret,
8446                      const_rtx *tocrel_offset_ret)
8447 {
8448   if (!TARGET_TOC)
8449     return false;
8450
8451   if (TARGET_CMODEL != CMODEL_SMALL)
8452     {
8453       /* When strict ensure we have everything tidy.  */
8454       if (strict
8455           && !(GET_CODE (op) == LO_SUM
8456                && REG_P (XEXP (op, 0))
8457                && INT_REG_OK_FOR_BASE_P (XEXP (op, 0), strict)))
8458         return false;
8459
8460       /* When not strict, allow non-split TOC addresses and also allow
8461          (lo_sum (high ..)) TOC addresses created during reload.  */
8462       if (GET_CODE (op) == LO_SUM)
8463         op = XEXP (op, 1);
8464     }
8465
8466   const_rtx tocrel_base = op;
8467   const_rtx tocrel_offset = const0_rtx;
8468
8469   if (GET_CODE (op) == PLUS && add_cint_operand (XEXP (op, 1), GET_MODE (op)))
8470     {
8471       tocrel_base = XEXP (op, 0);
8472       tocrel_offset = XEXP (op, 1);
8473     }
8474
8475   if (tocrel_base_ret)
8476     *tocrel_base_ret = tocrel_base;
8477   if (tocrel_offset_ret)
8478     *tocrel_offset_ret = tocrel_offset;
8479
8480   return (GET_CODE (tocrel_base) == UNSPEC
8481           && XINT (tocrel_base, 1) == UNSPEC_TOCREL);
8482 }
8483
8484 /* Return true if X is a constant pool address, and also for cmodel=medium
8485    if X is a toc-relative address known to be offsettable within MODE.  */
8486
8487 bool
8488 legitimate_constant_pool_address_p (const_rtx x, machine_mode mode,
8489                                     bool strict)
8490 {
8491   const_rtx tocrel_base, tocrel_offset;
8492   return (toc_relative_expr_p (x, strict, &tocrel_base, &tocrel_offset)
8493           && (TARGET_CMODEL != CMODEL_MEDIUM
8494               || constant_pool_expr_p (XVECEXP (tocrel_base, 0, 0))
8495               || mode == QImode
8496               || offsettable_ok_by_alignment (XVECEXP (tocrel_base, 0, 0),
8497                                               INTVAL (tocrel_offset), mode)));
8498 }
8499
8500 static bool
8501 legitimate_small_data_p (machine_mode mode, rtx x)
8502 {
8503   return (DEFAULT_ABI == ABI_V4
8504           && !flag_pic && !TARGET_TOC
8505           && (GET_CODE (x) == SYMBOL_REF || GET_CODE (x) == CONST)
8506           && small_data_operand (x, mode));
8507 }
8508
8509 bool
8510 rs6000_legitimate_offset_address_p (machine_mode mode, rtx x,
8511                                     bool strict, bool worst_case)
8512 {
8513   unsigned HOST_WIDE_INT offset;
8514   unsigned int extra;
8515
8516   if (GET_CODE (x) != PLUS)
8517     return false;
8518   if (!REG_P (XEXP (x, 0)))
8519     return false;
8520   if (!INT_REG_OK_FOR_BASE_P (XEXP (x, 0), strict))
8521     return false;
8522   if (mode_supports_vsx_dform_quad (mode))
8523     return quad_address_p (x, mode, strict);
8524   if (!reg_offset_addressing_ok_p (mode))
8525     return virtual_stack_registers_memory_p (x);
8526   if (legitimate_constant_pool_address_p (x, mode, strict || lra_in_progress))
8527     return true;
8528   if (GET_CODE (XEXP (x, 1)) != CONST_INT)
8529     return false;
8530
8531   offset = INTVAL (XEXP (x, 1));
8532   extra = 0;
8533   switch (mode)
8534     {
8535     case E_V2SImode:
8536     case E_V2SFmode:
8537       /* Paired single modes: offset addressing isn't valid.  */
8538       return false;
8539
8540     case E_DFmode:
8541     case E_DDmode:
8542     case E_DImode:
8543       /* If we are using VSX scalar loads, restrict ourselves to reg+reg
8544          addressing.  */
8545       if (VECTOR_MEM_VSX_P (mode))
8546         return false;
8547
8548       if (!worst_case)
8549         break;
8550       if (!TARGET_POWERPC64)
8551         extra = 4;
8552       else if (offset & 3)
8553         return false;
8554       break;
8555
8556     case E_TFmode:
8557     case E_IFmode:
8558     case E_KFmode:
8559     case E_TDmode:
8560     case E_TImode:
8561     case E_PTImode:
8562       extra = 8;
8563       if (!worst_case)
8564         break;
8565       if (!TARGET_POWERPC64)
8566         extra = 12;
8567       else if (offset & 3)
8568         return false;
8569       break;
8570
8571     default:
8572       break;
8573     }
8574
8575   offset += 0x8000;
8576   return offset < 0x10000 - extra;
8577 }
8578
8579 bool
8580 legitimate_indexed_address_p (rtx x, int strict)
8581 {
8582   rtx op0, op1;
8583
8584   if (GET_CODE (x) != PLUS)
8585     return false;
8586
8587   op0 = XEXP (x, 0);
8588   op1 = XEXP (x, 1);
8589
8590   return (REG_P (op0) && REG_P (op1)
8591           && ((INT_REG_OK_FOR_BASE_P (op0, strict)
8592                && INT_REG_OK_FOR_INDEX_P (op1, strict))
8593               || (INT_REG_OK_FOR_BASE_P (op1, strict)
8594                   && INT_REG_OK_FOR_INDEX_P (op0, strict))));
8595 }
8596
8597 bool
8598 avoiding_indexed_address_p (machine_mode mode)
8599 {
8600   /* Avoid indexed addressing for modes that have non-indexed
8601      load/store instruction forms.  */
8602   return (TARGET_AVOID_XFORM && VECTOR_MEM_NONE_P (mode));
8603 }
8604
8605 bool
8606 legitimate_indirect_address_p (rtx x, int strict)
8607 {
8608   return GET_CODE (x) == REG && INT_REG_OK_FOR_BASE_P (x, strict);
8609 }
8610
8611 bool
8612 macho_lo_sum_memory_operand (rtx x, machine_mode mode)
8613 {
8614   if (!TARGET_MACHO || !flag_pic
8615       || mode != SImode || GET_CODE (x) != MEM)
8616     return false;
8617   x = XEXP (x, 0);
8618
8619   if (GET_CODE (x) != LO_SUM)
8620     return false;
8621   if (GET_CODE (XEXP (x, 0)) != REG)
8622     return false;
8623   if (!INT_REG_OK_FOR_BASE_P (XEXP (x, 0), 0))
8624     return false;
8625   x = XEXP (x, 1);
8626
8627   return CONSTANT_P (x);
8628 }
8629
8630 static bool
8631 legitimate_lo_sum_address_p (machine_mode mode, rtx x, int strict)
8632 {
8633   if (GET_CODE (x) != LO_SUM)
8634     return false;
8635   if (GET_CODE (XEXP (x, 0)) != REG)
8636     return false;
8637   if (!INT_REG_OK_FOR_BASE_P (XEXP (x, 0), strict))
8638     return false;
8639   /* quad word addresses are restricted, and we can't use LO_SUM.  */
8640   if (mode_supports_vsx_dform_quad (mode))
8641     return false;
8642   x = XEXP (x, 1);
8643
8644   if (TARGET_ELF || TARGET_MACHO)
8645     {
8646       bool large_toc_ok;
8647
8648       if (DEFAULT_ABI == ABI_V4 && flag_pic)
8649         return false;
8650       /* LRA doesn't use LEGITIMIZE_RELOAD_ADDRESS as it usually calls
8651          push_reload from reload pass code.  LEGITIMIZE_RELOAD_ADDRESS
8652          recognizes some LO_SUM addresses as valid although this
8653          function says opposite.  In most cases, LRA through different
8654          transformations can generate correct code for address reloads.
8655          It can not manage only some LO_SUM cases.  So we need to add
8656          code analogous to one in rs6000_legitimize_reload_address for
8657          LOW_SUM here saying that some addresses are still valid.  */
8658       large_toc_ok = (lra_in_progress && TARGET_CMODEL != CMODEL_SMALL
8659                       && small_toc_ref (x, VOIDmode));
8660       if (TARGET_TOC && ! large_toc_ok)
8661         return false;
8662       if (GET_MODE_NUNITS (mode) != 1)
8663         return false;
8664       if (GET_MODE_SIZE (mode) > UNITS_PER_WORD
8665           && !(/* ??? Assume floating point reg based on mode?  */
8666                TARGET_HARD_FLOAT && TARGET_DOUBLE_FLOAT
8667                && (mode == DFmode || mode == DDmode)))
8668         return false;
8669
8670       return CONSTANT_P (x) || large_toc_ok;
8671     }
8672
8673   return false;
8674 }
8675
8676
8677 /* Try machine-dependent ways of modifying an illegitimate address
8678    to be legitimate.  If we find one, return the new, valid address.
8679    This is used from only one place: `memory_address' in explow.c.
8680
8681    OLDX is the address as it was before break_out_memory_refs was
8682    called.  In some cases it is useful to look at this to decide what
8683    needs to be done.
8684
8685    It is always safe for this function to do nothing.  It exists to
8686    recognize opportunities to optimize the output.
8687
8688    On RS/6000, first check for the sum of a register with a constant
8689    integer that is out of range.  If so, generate code to add the
8690    constant with the low-order 16 bits masked to the register and force
8691    this result into another register (this can be done with `cau').
8692    Then generate an address of REG+(CONST&0xffff), allowing for the
8693    possibility of bit 16 being a one.
8694
8695    Then check for the sum of a register and something not constant, try to
8696    load the other things into a register and return the sum.  */
8697
8698 static rtx
8699 rs6000_legitimize_address (rtx x, rtx oldx ATTRIBUTE_UNUSED,
8700                            machine_mode mode)
8701 {
8702   unsigned int extra;
8703
8704   if (!reg_offset_addressing_ok_p (mode)
8705       || mode_supports_vsx_dform_quad (mode))
8706     {
8707       if (virtual_stack_registers_memory_p (x))
8708         return x;
8709
8710       /* In theory we should not be seeing addresses of the form reg+0,
8711          but just in case it is generated, optimize it away.  */
8712       if (GET_CODE (x) == PLUS && XEXP (x, 1) == const0_rtx)
8713         return force_reg (Pmode, XEXP (x, 0));
8714
8715       /* For TImode with load/store quad, restrict addresses to just a single
8716          pointer, so it works with both GPRs and VSX registers.  */
8717       /* Make sure both operands are registers.  */
8718       else if (GET_CODE (x) == PLUS
8719                && (mode != TImode || !TARGET_VSX))
8720         return gen_rtx_PLUS (Pmode,
8721                              force_reg (Pmode, XEXP (x, 0)),
8722                              force_reg (Pmode, XEXP (x, 1)));
8723       else
8724         return force_reg (Pmode, x);
8725     }
8726   if (GET_CODE (x) == SYMBOL_REF)
8727     {
8728       enum tls_model model = SYMBOL_REF_TLS_MODEL (x);
8729       if (model != 0)
8730         return rs6000_legitimize_tls_address (x, model);
8731     }
8732
8733   extra = 0;
8734   switch (mode)
8735     {
8736     case E_TFmode:
8737     case E_TDmode:
8738     case E_TImode:
8739     case E_PTImode:
8740     case E_IFmode:
8741     case E_KFmode:
8742       /* As in legitimate_offset_address_p we do not assume
8743          worst-case.  The mode here is just a hint as to the registers
8744          used.  A TImode is usually in gprs, but may actually be in
8745          fprs.  Leave worst-case scenario for reload to handle via
8746          insn constraints.  PTImode is only GPRs.  */
8747       extra = 8;
8748       break;
8749     default:
8750       break;
8751     }
8752
8753   if (GET_CODE (x) == PLUS
8754       && GET_CODE (XEXP (x, 0)) == REG
8755       && GET_CODE (XEXP (x, 1)) == CONST_INT
8756       && ((unsigned HOST_WIDE_INT) (INTVAL (XEXP (x, 1)) + 0x8000)
8757           >= 0x10000 - extra)
8758       && !PAIRED_VECTOR_MODE (mode))
8759     {
8760       HOST_WIDE_INT high_int, low_int;
8761       rtx sum;
8762       low_int = ((INTVAL (XEXP (x, 1)) & 0xffff) ^ 0x8000) - 0x8000;
8763       if (low_int >= 0x8000 - extra)
8764         low_int = 0;
8765       high_int = INTVAL (XEXP (x, 1)) - low_int;
8766       sum = force_operand (gen_rtx_PLUS (Pmode, XEXP (x, 0),
8767                                          GEN_INT (high_int)), 0);
8768       return plus_constant (Pmode, sum, low_int);
8769     }
8770   else if (GET_CODE (x) == PLUS
8771            && GET_CODE (XEXP (x, 0)) == REG
8772            && GET_CODE (XEXP (x, 1)) != CONST_INT
8773            && GET_MODE_NUNITS (mode) == 1
8774            && (GET_MODE_SIZE (mode) <= UNITS_PER_WORD
8775                || (/* ??? Assume floating point reg based on mode?  */
8776                    (TARGET_HARD_FLOAT && TARGET_DOUBLE_FLOAT)
8777                    && (mode == DFmode || mode == DDmode)))
8778            && !avoiding_indexed_address_p (mode))
8779     {
8780       return gen_rtx_PLUS (Pmode, XEXP (x, 0),
8781                            force_reg (Pmode, force_operand (XEXP (x, 1), 0)));
8782     }
8783   else if (PAIRED_VECTOR_MODE (mode))
8784     {
8785       if (mode == DImode)
8786         return x;
8787       /* We accept [reg + reg].  */
8788
8789       if (GET_CODE (x) == PLUS)
8790        {
8791          rtx op1 = XEXP (x, 0);
8792          rtx op2 = XEXP (x, 1);
8793          rtx y;
8794
8795          op1 = force_reg (Pmode, op1);
8796          op2 = force_reg (Pmode, op2);
8797
8798          /* We can't always do [reg + reg] for these, because [reg +
8799             reg + offset] is not a legitimate addressing mode.  */
8800          y = gen_rtx_PLUS (Pmode, op1, op2);
8801
8802          if ((GET_MODE_SIZE (mode) > 8 || mode == DDmode) && REG_P (op2))
8803            return force_reg (Pmode, y);
8804          else
8805            return y;
8806        }
8807
8808       return force_reg (Pmode, x);
8809     }
8810   else if ((TARGET_ELF
8811 #if TARGET_MACHO
8812             || !MACHO_DYNAMIC_NO_PIC_P
8813 #endif
8814             )
8815            && TARGET_32BIT
8816            && TARGET_NO_TOC
8817            && ! flag_pic
8818            && GET_CODE (x) != CONST_INT
8819            && GET_CODE (x) != CONST_WIDE_INT
8820            && GET_CODE (x) != CONST_DOUBLE
8821            && CONSTANT_P (x)
8822            && GET_MODE_NUNITS (mode) == 1
8823            && (GET_MODE_SIZE (mode) <= UNITS_PER_WORD
8824                || (/* ??? Assume floating point reg based on mode?  */
8825                    (TARGET_HARD_FLOAT && TARGET_DOUBLE_FLOAT)
8826                    && (mode == DFmode || mode == DDmode))))
8827     {
8828       rtx reg = gen_reg_rtx (Pmode);
8829       if (TARGET_ELF)
8830         emit_insn (gen_elf_high (reg, x));
8831       else
8832         emit_insn (gen_macho_high (reg, x));
8833       return gen_rtx_LO_SUM (Pmode, reg, x);
8834     }
8835   else if (TARGET_TOC
8836            && GET_CODE (x) == SYMBOL_REF
8837            && constant_pool_expr_p (x)
8838            && ASM_OUTPUT_SPECIAL_POOL_ENTRY_P (get_pool_constant (x), Pmode))
8839     return create_TOC_reference (x, NULL_RTX);
8840   else
8841     return x;
8842 }
8843
8844 /* Debug version of rs6000_legitimize_address.  */
8845 static rtx
8846 rs6000_debug_legitimize_address (rtx x, rtx oldx, machine_mode mode)
8847 {
8848   rtx ret;
8849   rtx_insn *insns;
8850
8851   start_sequence ();
8852   ret = rs6000_legitimize_address (x, oldx, mode);
8853   insns = get_insns ();
8854   end_sequence ();
8855
8856   if (ret != x)
8857     {
8858       fprintf (stderr,
8859                "\nrs6000_legitimize_address: mode %s, old code %s, "
8860                "new code %s, modified\n",
8861                GET_MODE_NAME (mode), GET_RTX_NAME (GET_CODE (x)),
8862                GET_RTX_NAME (GET_CODE (ret)));
8863
8864       fprintf (stderr, "Original address:\n");
8865       debug_rtx (x);
8866
8867       fprintf (stderr, "oldx:\n");
8868       debug_rtx (oldx);
8869
8870       fprintf (stderr, "New address:\n");
8871       debug_rtx (ret);
8872
8873       if (insns)
8874         {
8875           fprintf (stderr, "Insns added:\n");
8876           debug_rtx_list (insns, 20);
8877         }
8878     }
8879   else
8880     {
8881       fprintf (stderr,
8882                "\nrs6000_legitimize_address: mode %s, code %s, no change:\n",
8883                GET_MODE_NAME (mode), GET_RTX_NAME (GET_CODE (x)));
8884
8885       debug_rtx (x);
8886     }
8887
8888   if (insns)
8889     emit_insn (insns);
8890
8891   return ret;
8892 }
8893
8894 /* This is called from dwarf2out.c via TARGET_ASM_OUTPUT_DWARF_DTPREL.
8895    We need to emit DTP-relative relocations.  */
8896
8897 static void rs6000_output_dwarf_dtprel (FILE *, int, rtx) ATTRIBUTE_UNUSED;
8898 static void
8899 rs6000_output_dwarf_dtprel (FILE *file, int size, rtx x)
8900 {
8901   switch (size)
8902     {
8903     case 4:
8904       fputs ("\t.long\t", file);
8905       break;
8906     case 8:
8907       fputs (DOUBLE_INT_ASM_OP, file);
8908       break;
8909     default:
8910       gcc_unreachable ();
8911     }
8912   output_addr_const (file, x);
8913   if (TARGET_ELF)
8914     fputs ("@dtprel+0x8000", file);
8915   else if (TARGET_XCOFF && GET_CODE (x) == SYMBOL_REF)
8916     {
8917       switch (SYMBOL_REF_TLS_MODEL (x))
8918         {
8919         case 0:
8920           break;
8921         case TLS_MODEL_LOCAL_EXEC:
8922           fputs ("@le", file);
8923           break;
8924         case TLS_MODEL_INITIAL_EXEC:
8925           fputs ("@ie", file);
8926           break;
8927         case TLS_MODEL_GLOBAL_DYNAMIC:
8928         case TLS_MODEL_LOCAL_DYNAMIC:
8929           fputs ("@m", file);
8930           break;
8931         default:
8932           gcc_unreachable ();
8933         }
8934     }
8935 }
8936
8937 /* Return true if X is a symbol that refers to real (rather than emulated)
8938    TLS.  */
8939
8940 static bool
8941 rs6000_real_tls_symbol_ref_p (rtx x)
8942 {
8943   return (GET_CODE (x) == SYMBOL_REF
8944           && SYMBOL_REF_TLS_MODEL (x) >= TLS_MODEL_REAL);
8945 }
8946
8947 /* In the name of slightly smaller debug output, and to cater to
8948    general assembler lossage, recognize various UNSPEC sequences
8949    and turn them back into a direct symbol reference.  */
8950
8951 static rtx
8952 rs6000_delegitimize_address (rtx orig_x)
8953 {
8954   rtx x, y, offset;
8955
8956   orig_x = delegitimize_mem_from_attrs (orig_x);
8957   x = orig_x;
8958   if (MEM_P (x))
8959     x = XEXP (x, 0);
8960
8961   y = x;
8962   if (TARGET_CMODEL != CMODEL_SMALL
8963       && GET_CODE (y) == LO_SUM)
8964     y = XEXP (y, 1);
8965
8966   offset = NULL_RTX;
8967   if (GET_CODE (y) == PLUS
8968       && GET_MODE (y) == Pmode
8969       && CONST_INT_P (XEXP (y, 1)))
8970     {
8971       offset = XEXP (y, 1);
8972       y = XEXP (y, 0);
8973     }
8974
8975   if (GET_CODE (y) == UNSPEC
8976       && XINT (y, 1) == UNSPEC_TOCREL)
8977     {
8978       y = XVECEXP (y, 0, 0);
8979
8980 #ifdef HAVE_AS_TLS
8981       /* Do not associate thread-local symbols with the original
8982          constant pool symbol.  */
8983       if (TARGET_XCOFF
8984           && GET_CODE (y) == SYMBOL_REF
8985           && CONSTANT_POOL_ADDRESS_P (y)
8986           && rs6000_real_tls_symbol_ref_p (get_pool_constant (y)))
8987         return orig_x;
8988 #endif
8989
8990       if (offset != NULL_RTX)
8991         y = gen_rtx_PLUS (Pmode, y, offset);
8992       if (!MEM_P (orig_x))
8993         return y;
8994       else
8995         return replace_equiv_address_nv (orig_x, y);
8996     }
8997
8998   if (TARGET_MACHO
8999       && GET_CODE (orig_x) == LO_SUM
9000       && GET_CODE (XEXP (orig_x, 1)) == CONST)
9001     {
9002       y = XEXP (XEXP (orig_x, 1), 0);
9003       if (GET_CODE (y) == UNSPEC
9004           && XINT (y, 1) == UNSPEC_MACHOPIC_OFFSET)
9005         return XVECEXP (y, 0, 0);
9006     }
9007
9008   return orig_x;
9009 }
9010
9011 /* Return true if X shouldn't be emitted into the debug info.
9012    The linker doesn't like .toc section references from
9013    .debug_* sections, so reject .toc section symbols.  */
9014
9015 static bool
9016 rs6000_const_not_ok_for_debug_p (rtx x)
9017 {
9018   if (GET_CODE (x) == UNSPEC)
9019     return true;
9020   if (GET_CODE (x) == SYMBOL_REF
9021       && CONSTANT_POOL_ADDRESS_P (x))
9022     {
9023       rtx c = get_pool_constant (x);
9024       machine_mode cmode = get_pool_mode (x);
9025       if (ASM_OUTPUT_SPECIAL_POOL_ENTRY_P (c, cmode))
9026         return true;
9027     }
9028
9029   return false;
9030 }
9031
9032
9033 /* Implement the TARGET_LEGITIMATE_COMBINED_INSN hook.  */
9034
9035 static bool
9036 rs6000_legitimate_combined_insn (rtx_insn *insn)
9037 {
9038   int icode = INSN_CODE (insn);
9039
9040   /* Reject creating doloop insns.  Combine should not be allowed
9041      to create these for a number of reasons:
9042      1) In a nested loop, if combine creates one of these in an
9043      outer loop and the register allocator happens to allocate ctr
9044      to the outer loop insn, then the inner loop can't use ctr.
9045      Inner loops ought to be more highly optimized.
9046      2) Combine often wants to create one of these from what was
9047      originally a three insn sequence, first combining the three
9048      insns to two, then to ctrsi/ctrdi.  When ctrsi/ctrdi is not
9049      allocated ctr, the splitter takes use back to the three insn
9050      sequence.  It's better to stop combine at the two insn
9051      sequence.
9052      3) Faced with not being able to allocate ctr for ctrsi/crtdi
9053      insns, the register allocator sometimes uses floating point
9054      or vector registers for the pseudo.  Since ctrsi/ctrdi is a
9055      jump insn and output reloads are not implemented for jumps,
9056      the ctrsi/ctrdi splitters need to handle all possible cases.
9057      That's a pain, and it gets to be seriously difficult when a
9058      splitter that runs after reload needs memory to transfer from
9059      a gpr to fpr.  See PR70098 and PR71763 which are not fixed
9060      for the difficult case.  It's better to not create problems
9061      in the first place.  */
9062   if (icode != CODE_FOR_nothing
9063       && (icode == CODE_FOR_bdz_si
9064           || icode == CODE_FOR_bdz_di
9065           || icode == CODE_FOR_bdnz_si
9066           || icode == CODE_FOR_bdnz_di
9067           || icode == CODE_FOR_bdztf_si
9068           || icode == CODE_FOR_bdztf_di
9069           || icode == CODE_FOR_bdnztf_si
9070           || icode == CODE_FOR_bdnztf_di))
9071     return false;
9072
9073   return true;
9074 }
9075
9076 /* Construct the SYMBOL_REF for the tls_get_addr function.  */
9077
9078 static GTY(()) rtx rs6000_tls_symbol;
9079 static rtx
9080 rs6000_tls_get_addr (void)
9081 {
9082   if (!rs6000_tls_symbol)
9083     rs6000_tls_symbol = init_one_libfunc ("__tls_get_addr");
9084
9085   return rs6000_tls_symbol;
9086 }
9087
9088 /* Construct the SYMBOL_REF for TLS GOT references.  */
9089
9090 static GTY(()) rtx rs6000_got_symbol;
9091 static rtx
9092 rs6000_got_sym (void)
9093 {
9094   if (!rs6000_got_symbol)
9095     {
9096       rs6000_got_symbol = gen_rtx_SYMBOL_REF (Pmode, "_GLOBAL_OFFSET_TABLE_");
9097       SYMBOL_REF_FLAGS (rs6000_got_symbol) |= SYMBOL_FLAG_LOCAL;
9098       SYMBOL_REF_FLAGS (rs6000_got_symbol) |= SYMBOL_FLAG_EXTERNAL;
9099     }
9100
9101   return rs6000_got_symbol;
9102 }
9103
9104 /* AIX Thread-Local Address support.  */
9105
9106 static rtx
9107 rs6000_legitimize_tls_address_aix (rtx addr, enum tls_model model)
9108 {
9109   rtx sym, mem, tocref, tlsreg, tmpreg, dest, tlsaddr;
9110   const char *name;
9111   char *tlsname;
9112
9113   name = XSTR (addr, 0);
9114   /* Append TLS CSECT qualifier, unless the symbol already is qualified
9115      or the symbol will be in TLS private data section.  */
9116   if (name[strlen (name) - 1] != ']'
9117       && (TREE_PUBLIC (SYMBOL_REF_DECL (addr))
9118           || bss_initializer_p (SYMBOL_REF_DECL (addr))))
9119     {
9120       tlsname = XALLOCAVEC (char, strlen (name) + 4);
9121       strcpy (tlsname, name);
9122       strcat (tlsname,
9123               bss_initializer_p (SYMBOL_REF_DECL (addr)) ? "[UL]" : "[TL]");
9124       tlsaddr = copy_rtx (addr);
9125       XSTR (tlsaddr, 0) = ggc_strdup (tlsname);
9126     }
9127   else
9128     tlsaddr = addr;
9129
9130   /* Place addr into TOC constant pool.  */
9131   sym = force_const_mem (GET_MODE (tlsaddr), tlsaddr);
9132
9133   /* Output the TOC entry and create the MEM referencing the value.  */
9134   if (constant_pool_expr_p (XEXP (sym, 0))
9135       && ASM_OUTPUT_SPECIAL_POOL_ENTRY_P (get_pool_constant (XEXP (sym, 0)), Pmode))
9136     {
9137       tocref = create_TOC_reference (XEXP (sym, 0), NULL_RTX);
9138       mem = gen_const_mem (Pmode, tocref);
9139       set_mem_alias_set (mem, get_TOC_alias_set ());
9140     }
9141   else
9142     return sym;
9143
9144   /* Use global-dynamic for local-dynamic.  */
9145   if (model == TLS_MODEL_GLOBAL_DYNAMIC
9146       || model == TLS_MODEL_LOCAL_DYNAMIC)
9147     {
9148       /* Create new TOC reference for @m symbol.  */
9149       name = XSTR (XVECEXP (XEXP (mem, 0), 0, 0), 0);
9150       tlsname = XALLOCAVEC (char, strlen (name) + 1);
9151       strcpy (tlsname, "*LCM");
9152       strcat (tlsname, name + 3);
9153       rtx modaddr = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (tlsname));
9154       SYMBOL_REF_FLAGS (modaddr) |= SYMBOL_FLAG_LOCAL;
9155       tocref = create_TOC_reference (modaddr, NULL_RTX);
9156       rtx modmem = gen_const_mem (Pmode, tocref);
9157       set_mem_alias_set (modmem, get_TOC_alias_set ());
9158       
9159       rtx modreg = gen_reg_rtx (Pmode);
9160       emit_insn (gen_rtx_SET (modreg, modmem));
9161
9162       tmpreg = gen_reg_rtx (Pmode);
9163       emit_insn (gen_rtx_SET (tmpreg, mem));
9164
9165       dest = gen_reg_rtx (Pmode);
9166       if (TARGET_32BIT)
9167         emit_insn (gen_tls_get_addrsi (dest, modreg, tmpreg));
9168       else
9169         emit_insn (gen_tls_get_addrdi (dest, modreg, tmpreg));
9170       return dest;
9171     }
9172   /* Obtain TLS pointer: 32 bit call or 64 bit GPR 13.  */
9173   else if (TARGET_32BIT)
9174     {
9175       tlsreg = gen_reg_rtx (SImode);
9176       emit_insn (gen_tls_get_tpointer (tlsreg));
9177     }
9178   else
9179     tlsreg = gen_rtx_REG (DImode, 13);
9180
9181   /* Load the TOC value into temporary register.  */
9182   tmpreg = gen_reg_rtx (Pmode);
9183   emit_insn (gen_rtx_SET (tmpreg, mem));
9184   set_unique_reg_note (get_last_insn (), REG_EQUAL,
9185                        gen_rtx_MINUS (Pmode, addr, tlsreg));
9186
9187   /* Add TOC symbol value to TLS pointer.  */
9188   dest = force_reg (Pmode, gen_rtx_PLUS (Pmode, tmpreg, tlsreg));
9189
9190   return dest;
9191 }
9192
9193 /* ADDR contains a thread-local SYMBOL_REF.  Generate code to compute
9194    this (thread-local) address.  */
9195
9196 static rtx
9197 rs6000_legitimize_tls_address (rtx addr, enum tls_model model)
9198 {
9199   rtx dest, insn;
9200
9201   if (TARGET_XCOFF)
9202     return rs6000_legitimize_tls_address_aix (addr, model);
9203
9204   dest = gen_reg_rtx (Pmode);
9205   if (model == TLS_MODEL_LOCAL_EXEC && rs6000_tls_size == 16)
9206     {
9207       rtx tlsreg;
9208
9209       if (TARGET_64BIT)
9210         {
9211           tlsreg = gen_rtx_REG (Pmode, 13);
9212           insn = gen_tls_tprel_64 (dest, tlsreg, addr);
9213         }
9214       else
9215         {
9216           tlsreg = gen_rtx_REG (Pmode, 2);
9217           insn = gen_tls_tprel_32 (dest, tlsreg, addr);
9218         }
9219       emit_insn (insn);
9220     }
9221   else if (model == TLS_MODEL_LOCAL_EXEC && rs6000_tls_size == 32)
9222     {
9223       rtx tlsreg, tmp;
9224
9225       tmp = gen_reg_rtx (Pmode);
9226       if (TARGET_64BIT)
9227         {
9228           tlsreg = gen_rtx_REG (Pmode, 13);
9229           insn = gen_tls_tprel_ha_64 (tmp, tlsreg, addr);
9230         }
9231       else
9232         {
9233           tlsreg = gen_rtx_REG (Pmode, 2);
9234           insn = gen_tls_tprel_ha_32 (tmp, tlsreg, addr);
9235         }
9236       emit_insn (insn);
9237       if (TARGET_64BIT)
9238         insn = gen_tls_tprel_lo_64 (dest, tmp, addr);
9239       else
9240         insn = gen_tls_tprel_lo_32 (dest, tmp, addr);
9241       emit_insn (insn);
9242     }
9243   else
9244     {
9245       rtx r3, got, tga, tmp1, tmp2, call_insn;
9246
9247       /* We currently use relocations like @got@tlsgd for tls, which
9248          means the linker will handle allocation of tls entries, placing
9249          them in the .got section.  So use a pointer to the .got section,
9250          not one to secondary TOC sections used by 64-bit -mminimal-toc,
9251          or to secondary GOT sections used by 32-bit -fPIC.  */
9252       if (TARGET_64BIT)
9253         got = gen_rtx_REG (Pmode, 2);
9254       else
9255         {
9256           if (flag_pic == 1)
9257             got = gen_rtx_REG (Pmode, RS6000_PIC_OFFSET_TABLE_REGNUM);
9258           else
9259             {
9260               rtx gsym = rs6000_got_sym ();
9261               got = gen_reg_rtx (Pmode);
9262               if (flag_pic == 0)
9263                 rs6000_emit_move (got, gsym, Pmode);
9264               else
9265                 {
9266                   rtx mem, lab;
9267
9268                   tmp1 = gen_reg_rtx (Pmode);
9269                   tmp2 = gen_reg_rtx (Pmode);
9270                   mem = gen_const_mem (Pmode, tmp1);
9271                   lab = gen_label_rtx ();
9272                   emit_insn (gen_load_toc_v4_PIC_1b (gsym, lab));
9273                   emit_move_insn (tmp1, gen_rtx_REG (Pmode, LR_REGNO));
9274                   if (TARGET_LINK_STACK)
9275                     emit_insn (gen_addsi3 (tmp1, tmp1, GEN_INT (4)));
9276                   emit_move_insn (tmp2, mem);
9277                   rtx_insn *last = emit_insn (gen_addsi3 (got, tmp1, tmp2));
9278                   set_unique_reg_note (last, REG_EQUAL, gsym);
9279                 }
9280             }
9281         }
9282
9283       if (model == TLS_MODEL_GLOBAL_DYNAMIC)
9284         {
9285           tga = rs6000_tls_get_addr ();
9286           emit_library_call_value (tga, dest, LCT_CONST, Pmode,
9287                                    const0_rtx, Pmode);
9288
9289           r3 = gen_rtx_REG (Pmode, 3);
9290           if (DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
9291             {
9292               if (TARGET_64BIT)
9293                 insn = gen_tls_gd_aix64 (r3, got, addr, tga, const0_rtx);
9294               else
9295                 insn = gen_tls_gd_aix32 (r3, got, addr, tga, const0_rtx);
9296             }
9297           else if (DEFAULT_ABI == ABI_V4)
9298             insn = gen_tls_gd_sysvsi (r3, got, addr, tga, const0_rtx);
9299           else
9300             gcc_unreachable ();
9301           call_insn = last_call_insn ();
9302           PATTERN (call_insn) = insn;
9303           if (DEFAULT_ABI == ABI_V4 && TARGET_SECURE_PLT && flag_pic)
9304             use_reg (&CALL_INSN_FUNCTION_USAGE (call_insn),
9305                      pic_offset_table_rtx);
9306         }
9307       else if (model == TLS_MODEL_LOCAL_DYNAMIC)
9308         {
9309           tga = rs6000_tls_get_addr ();
9310           tmp1 = gen_reg_rtx (Pmode);
9311           emit_library_call_value (tga, tmp1, LCT_CONST, Pmode,
9312                                    const0_rtx, Pmode);
9313
9314           r3 = gen_rtx_REG (Pmode, 3);
9315           if (DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
9316             {
9317               if (TARGET_64BIT)
9318                 insn = gen_tls_ld_aix64 (r3, got, tga, const0_rtx);
9319               else
9320                 insn = gen_tls_ld_aix32 (r3, got, tga, const0_rtx);
9321             }
9322           else if (DEFAULT_ABI == ABI_V4)
9323             insn = gen_tls_ld_sysvsi (r3, got, tga, const0_rtx);
9324           else
9325             gcc_unreachable ();
9326           call_insn = last_call_insn ();
9327           PATTERN (call_insn) = insn;
9328           if (DEFAULT_ABI == ABI_V4 && TARGET_SECURE_PLT && flag_pic)
9329             use_reg (&CALL_INSN_FUNCTION_USAGE (call_insn),
9330                      pic_offset_table_rtx);
9331
9332           if (rs6000_tls_size == 16)
9333             {
9334               if (TARGET_64BIT)
9335                 insn = gen_tls_dtprel_64 (dest, tmp1, addr);
9336               else
9337                 insn = gen_tls_dtprel_32 (dest, tmp1, addr);
9338             }
9339           else if (rs6000_tls_size == 32)
9340             {
9341               tmp2 = gen_reg_rtx (Pmode);
9342               if (TARGET_64BIT)
9343                 insn = gen_tls_dtprel_ha_64 (tmp2, tmp1, addr);
9344               else
9345                 insn = gen_tls_dtprel_ha_32 (tmp2, tmp1, addr);
9346               emit_insn (insn);
9347               if (TARGET_64BIT)
9348                 insn = gen_tls_dtprel_lo_64 (dest, tmp2, addr);
9349               else
9350                 insn = gen_tls_dtprel_lo_32 (dest, tmp2, addr);
9351             }
9352           else
9353             {
9354               tmp2 = gen_reg_rtx (Pmode);
9355               if (TARGET_64BIT)
9356                 insn = gen_tls_got_dtprel_64 (tmp2, got, addr);
9357               else
9358                 insn = gen_tls_got_dtprel_32 (tmp2, got, addr);
9359               emit_insn (insn);
9360               insn = gen_rtx_SET (dest, gen_rtx_PLUS (Pmode, tmp2, tmp1));
9361             }
9362           emit_insn (insn);
9363         }
9364       else
9365         {
9366           /* IE, or 64-bit offset LE.  */
9367           tmp2 = gen_reg_rtx (Pmode);
9368           if (TARGET_64BIT)
9369             insn = gen_tls_got_tprel_64 (tmp2, got, addr);
9370           else
9371             insn = gen_tls_got_tprel_32 (tmp2, got, addr);
9372           emit_insn (insn);
9373           if (TARGET_64BIT)
9374             insn = gen_tls_tls_64 (dest, tmp2, addr);
9375           else
9376             insn = gen_tls_tls_32 (dest, tmp2, addr);
9377           emit_insn (insn);
9378         }
9379     }
9380
9381   return dest;
9382 }
9383
9384 /* Only create the global variable for the stack protect guard if we are using
9385    the global flavor of that guard.  */
9386 static tree
9387 rs6000_init_stack_protect_guard (void)
9388 {
9389   if (rs6000_stack_protector_guard == SSP_GLOBAL)
9390     return default_stack_protect_guard ();
9391
9392   return NULL_TREE;
9393 }
9394
9395 /* Implement TARGET_CANNOT_FORCE_CONST_MEM.  */
9396
9397 static bool
9398 rs6000_cannot_force_const_mem (machine_mode mode ATTRIBUTE_UNUSED, rtx x)
9399 {
9400   if (GET_CODE (x) == HIGH
9401       && GET_CODE (XEXP (x, 0)) == UNSPEC)
9402     return true;
9403
9404   /* A TLS symbol in the TOC cannot contain a sum.  */
9405   if (GET_CODE (x) == CONST
9406       && GET_CODE (XEXP (x, 0)) == PLUS
9407       && GET_CODE (XEXP (XEXP (x, 0), 0)) == SYMBOL_REF
9408       && SYMBOL_REF_TLS_MODEL (XEXP (XEXP (x, 0), 0)) != 0)
9409     return true;
9410
9411   /* Do not place an ELF TLS symbol in the constant pool.  */
9412   return TARGET_ELF && tls_referenced_p (x);
9413 }
9414
9415 /* Return true iff the given SYMBOL_REF refers to a constant pool entry
9416    that we have put in the TOC, or for cmodel=medium, if the SYMBOL_REF
9417    can be addressed relative to the toc pointer.  */
9418
9419 static bool
9420 use_toc_relative_ref (rtx sym, machine_mode mode)
9421 {
9422   return ((constant_pool_expr_p (sym)
9423            && ASM_OUTPUT_SPECIAL_POOL_ENTRY_P (get_pool_constant (sym),
9424                                                get_pool_mode (sym)))
9425           || (TARGET_CMODEL == CMODEL_MEDIUM
9426               && SYMBOL_REF_LOCAL_P (sym)
9427               && GET_MODE_SIZE (mode) <= POWERPC64_TOC_POINTER_ALIGNMENT));
9428 }
9429
9430 /* Our implementation of LEGITIMIZE_RELOAD_ADDRESS.  Returns a value to
9431    replace the input X, or the original X if no replacement is called for.
9432    The output parameter *WIN is 1 if the calling macro should goto WIN,
9433    0 if it should not.
9434
9435    For RS/6000, we wish to handle large displacements off a base
9436    register by splitting the addend across an addiu/addis and the mem insn.
9437    This cuts number of extra insns needed from 3 to 1.
9438
9439    On Darwin, we use this to generate code for floating point constants.
9440    A movsf_low is generated so we wind up with 2 instructions rather than 3.
9441    The Darwin code is inside #if TARGET_MACHO because only then are the
9442    machopic_* functions defined.  */
9443 static rtx
9444 rs6000_legitimize_reload_address (rtx x, machine_mode mode,
9445                                   int opnum, int type,
9446                                   int ind_levels ATTRIBUTE_UNUSED, int *win)
9447 {
9448   bool reg_offset_p = reg_offset_addressing_ok_p (mode);
9449   bool quad_offset_p = mode_supports_vsx_dform_quad (mode);
9450
9451   /* Nasty hack for vsx_splat_v2df/v2di load from mem, which takes a
9452      DFmode/DImode MEM.  Ditto for ISA 3.0 vsx_splat_v4sf/v4si.  */
9453   if (reg_offset_p
9454       && opnum == 1
9455       && ((mode == DFmode && recog_data.operand_mode[0] == V2DFmode)
9456           || (mode == DImode && recog_data.operand_mode[0] == V2DImode)
9457           || (mode == SFmode && recog_data.operand_mode[0] == V4SFmode
9458               && TARGET_P9_VECTOR)
9459           || (mode == SImode && recog_data.operand_mode[0] == V4SImode
9460               && TARGET_P9_VECTOR)))
9461     reg_offset_p = false;
9462
9463   /* We must recognize output that we have already generated ourselves.  */
9464   if (GET_CODE (x) == PLUS
9465       && GET_CODE (XEXP (x, 0)) == PLUS
9466       && GET_CODE (XEXP (XEXP (x, 0), 0)) == REG
9467       && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT
9468       && GET_CODE (XEXP (x, 1)) == CONST_INT)
9469     {
9470       if (TARGET_DEBUG_ADDR)
9471         {
9472           fprintf (stderr, "\nlegitimize_reload_address push_reload #1:\n");
9473           debug_rtx (x);
9474         }
9475       push_reload (XEXP (x, 0), NULL_RTX, &XEXP (x, 0), NULL,
9476                    BASE_REG_CLASS, GET_MODE (x), VOIDmode, 0, 0,
9477                    opnum, (enum reload_type) type);
9478       *win = 1;
9479       return x;
9480     }
9481
9482   /* Likewise for (lo_sum (high ...) ...) output we have generated.  */
9483   if (GET_CODE (x) == LO_SUM
9484       && GET_CODE (XEXP (x, 0)) == HIGH)
9485     {
9486       if (TARGET_DEBUG_ADDR)
9487         {
9488           fprintf (stderr, "\nlegitimize_reload_address push_reload #2:\n");
9489           debug_rtx (x);
9490         }
9491       push_reload (XEXP (x, 0), NULL_RTX, &XEXP (x, 0), NULL,
9492                    BASE_REG_CLASS, Pmode, VOIDmode, 0, 0,
9493                    opnum, (enum reload_type) type);
9494       *win = 1;
9495       return x;
9496     }
9497
9498 #if TARGET_MACHO
9499   if (DEFAULT_ABI == ABI_DARWIN && flag_pic
9500       && GET_CODE (x) == LO_SUM
9501       && GET_CODE (XEXP (x, 0)) == PLUS
9502       && XEXP (XEXP (x, 0), 0) == pic_offset_table_rtx
9503       && GET_CODE (XEXP (XEXP (x, 0), 1)) == HIGH
9504       && XEXP (XEXP (XEXP (x, 0), 1), 0) == XEXP (x, 1)
9505       && machopic_operand_p (XEXP (x, 1)))
9506     {
9507       /* Result of previous invocation of this function on Darwin
9508          floating point constant.  */
9509       push_reload (XEXP (x, 0), NULL_RTX, &XEXP (x, 0), NULL,
9510                    BASE_REG_CLASS, Pmode, VOIDmode, 0, 0,
9511                    opnum, (enum reload_type) type);
9512       *win = 1;
9513       return x;
9514     }
9515 #endif
9516
9517   if (TARGET_CMODEL != CMODEL_SMALL
9518       && reg_offset_p
9519       && !quad_offset_p
9520       && small_toc_ref (x, VOIDmode))
9521     {
9522       rtx hi = gen_rtx_HIGH (Pmode, copy_rtx (x));
9523       x = gen_rtx_LO_SUM (Pmode, hi, x);
9524       if (TARGET_DEBUG_ADDR)
9525         {
9526           fprintf (stderr, "\nlegitimize_reload_address push_reload #3:\n");
9527           debug_rtx (x);
9528         }
9529       push_reload (XEXP (x, 0), NULL_RTX, &XEXP (x, 0), NULL,
9530                    BASE_REG_CLASS, Pmode, VOIDmode, 0, 0,
9531                    opnum, (enum reload_type) type);
9532       *win = 1;
9533       return x;
9534     }
9535
9536   if (GET_CODE (x) == PLUS
9537       && REG_P (XEXP (x, 0))
9538       && REGNO (XEXP (x, 0)) < FIRST_PSEUDO_REGISTER
9539       && INT_REG_OK_FOR_BASE_P (XEXP (x, 0), 1)
9540       && CONST_INT_P (XEXP (x, 1))
9541       && reg_offset_p
9542       && !PAIRED_VECTOR_MODE (mode)
9543       && (quad_offset_p || !VECTOR_MODE_P (mode) || VECTOR_MEM_NONE_P (mode)))
9544     {
9545       HOST_WIDE_INT val = INTVAL (XEXP (x, 1));
9546       HOST_WIDE_INT low = ((val & 0xffff) ^ 0x8000) - 0x8000;
9547       HOST_WIDE_INT high
9548         = (((val - low) & 0xffffffff) ^ 0x80000000) - 0x80000000;
9549
9550       /* Check for 32-bit overflow or quad addresses with one of the
9551          four least significant bits set.  */
9552       if (high + low != val
9553           || (quad_offset_p && (low & 0xf)))
9554         {
9555           *win = 0;
9556           return x;
9557         }
9558
9559       /* Reload the high part into a base reg; leave the low part
9560          in the mem directly.  */
9561
9562       x = gen_rtx_PLUS (GET_MODE (x),
9563                         gen_rtx_PLUS (GET_MODE (x), XEXP (x, 0),
9564                                       GEN_INT (high)),
9565                         GEN_INT (low));
9566
9567       if (TARGET_DEBUG_ADDR)
9568         {
9569           fprintf (stderr, "\nlegitimize_reload_address push_reload #4:\n");
9570           debug_rtx (x);
9571         }
9572       push_reload (XEXP (x, 0), NULL_RTX, &XEXP (x, 0), NULL,
9573                    BASE_REG_CLASS, GET_MODE (x), VOIDmode, 0, 0,
9574                    opnum, (enum reload_type) type);
9575       *win = 1;
9576       return x;
9577     }
9578
9579   if (GET_CODE (x) == SYMBOL_REF
9580       && reg_offset_p
9581       && !quad_offset_p
9582       && (!VECTOR_MODE_P (mode) || VECTOR_MEM_NONE_P (mode))
9583       && !PAIRED_VECTOR_MODE (mode)
9584 #if TARGET_MACHO
9585       && DEFAULT_ABI == ABI_DARWIN
9586       && (flag_pic || MACHO_DYNAMIC_NO_PIC_P)
9587       && machopic_symbol_defined_p (x)
9588 #else
9589       && DEFAULT_ABI == ABI_V4
9590       && !flag_pic
9591 #endif
9592       /* Don't do this for TFmode or TDmode, since the result isn't offsettable.
9593          The same goes for DImode without 64-bit gprs and DFmode and DDmode
9594          without fprs.
9595          ??? Assume floating point reg based on mode?  This assumption is
9596          violated by eg. powerpc-linux -m32 compile of gcc.dg/pr28796-2.c
9597          where reload ends up doing a DFmode load of a constant from
9598          mem using two gprs.  Unfortunately, at this point reload
9599          hasn't yet selected regs so poking around in reload data
9600          won't help and even if we could figure out the regs reliably,
9601          we'd still want to allow this transformation when the mem is
9602          naturally aligned.  Since we say the address is good here, we
9603          can't disable offsets from LO_SUMs in mem_operand_gpr.
9604          FIXME: Allow offset from lo_sum for other modes too, when
9605          mem is sufficiently aligned.
9606
9607          Also disallow this if the type can go in VMX/Altivec registers, since
9608          those registers do not have d-form (reg+offset) address modes.  */
9609       && !reg_addr[mode].scalar_in_vmx_p
9610       && mode != TFmode
9611       && mode != TDmode
9612       && mode != IFmode
9613       && mode != KFmode
9614       && (mode != TImode || !TARGET_VSX)
9615       && mode != PTImode
9616       && (mode != DImode || TARGET_POWERPC64)
9617       && ((mode != DFmode && mode != DDmode) || TARGET_POWERPC64
9618           || (TARGET_HARD_FLOAT && TARGET_DOUBLE_FLOAT)))
9619     {
9620 #if TARGET_MACHO
9621       if (flag_pic)
9622         {
9623           rtx offset = machopic_gen_offset (x);
9624           x = gen_rtx_LO_SUM (GET_MODE (x),
9625                 gen_rtx_PLUS (Pmode, pic_offset_table_rtx,
9626                   gen_rtx_HIGH (Pmode, offset)), offset);
9627         }
9628       else
9629 #endif
9630         x = gen_rtx_LO_SUM (GET_MODE (x),
9631               gen_rtx_HIGH (Pmode, x), x);
9632
9633       if (TARGET_DEBUG_ADDR)
9634         {
9635           fprintf (stderr, "\nlegitimize_reload_address push_reload #5:\n");
9636           debug_rtx (x);
9637         }
9638       push_reload (XEXP (x, 0), NULL_RTX, &XEXP (x, 0), NULL,
9639                    BASE_REG_CLASS, Pmode, VOIDmode, 0, 0,
9640                    opnum, (enum reload_type) type);
9641       *win = 1;
9642       return x;
9643     }
9644
9645   /* Reload an offset address wrapped by an AND that represents the
9646      masking of the lower bits.  Strip the outer AND and let reload
9647      convert the offset address into an indirect address.  For VSX,
9648      force reload to create the address with an AND in a separate
9649      register, because we can't guarantee an altivec register will
9650      be used.  */
9651   if (VECTOR_MEM_ALTIVEC_P (mode)
9652       && GET_CODE (x) == AND
9653       && GET_CODE (XEXP (x, 0)) == PLUS
9654       && GET_CODE (XEXP (XEXP (x, 0), 0)) == REG
9655       && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT
9656       && GET_CODE (XEXP (x, 1)) == CONST_INT
9657       && INTVAL (XEXP (x, 1)) == -16)
9658     {
9659       x = XEXP (x, 0);
9660       *win = 1;
9661       return x;
9662     }
9663
9664   if (TARGET_TOC
9665       && reg_offset_p
9666       && !quad_offset_p
9667       && GET_CODE (x) == SYMBOL_REF
9668       && use_toc_relative_ref (x, mode))
9669     {
9670       x = create_TOC_reference (x, NULL_RTX);
9671       if (TARGET_CMODEL != CMODEL_SMALL)
9672         {
9673           if (TARGET_DEBUG_ADDR)
9674             {
9675               fprintf (stderr, "\nlegitimize_reload_address push_reload #6:\n");
9676               debug_rtx (x);
9677             }
9678           push_reload (XEXP (x, 0), NULL_RTX, &XEXP (x, 0), NULL,
9679                        BASE_REG_CLASS, Pmode, VOIDmode, 0, 0,
9680                        opnum, (enum reload_type) type);
9681         }
9682       *win = 1;
9683       return x;
9684     }
9685   *win = 0;
9686   return x;
9687 }
9688
9689 /* Debug version of rs6000_legitimize_reload_address.  */
9690 static rtx
9691 rs6000_debug_legitimize_reload_address (rtx x, machine_mode mode,
9692                                         int opnum, int type,
9693                                         int ind_levels, int *win)
9694 {
9695   rtx ret = rs6000_legitimize_reload_address (x, mode, opnum, type,
9696                                               ind_levels, win);
9697   fprintf (stderr,
9698            "\nrs6000_legitimize_reload_address: mode = %s, opnum = %d, "
9699            "type = %d, ind_levels = %d, win = %d, original addr:\n",
9700            GET_MODE_NAME (mode), opnum, type, ind_levels, *win);
9701   debug_rtx (x);
9702
9703   if (x == ret)
9704     fprintf (stderr, "Same address returned\n");
9705   else if (!ret)
9706     fprintf (stderr, "NULL returned\n");
9707   else
9708     {
9709       fprintf (stderr, "New address:\n");
9710       debug_rtx (ret);
9711     }
9712
9713   return ret;
9714 }
9715
9716 /* TARGET_LEGITIMATE_ADDRESS_P recognizes an RTL expression
9717    that is a valid memory address for an instruction.
9718    The MODE argument is the machine mode for the MEM expression
9719    that wants to use this address.
9720
9721    On the RS/6000, there are four valid address: a SYMBOL_REF that
9722    refers to a constant pool entry of an address (or the sum of it
9723    plus a constant), a short (16-bit signed) constant plus a register,
9724    the sum of two registers, or a register indirect, possibly with an
9725    auto-increment.  For DFmode, DDmode and DImode with a constant plus
9726    register, we must ensure that both words are addressable or PowerPC64
9727    with offset word aligned.
9728
9729    For modes spanning multiple registers (DFmode and DDmode in 32-bit GPRs,
9730    32-bit DImode, TImode, TFmode, TDmode), indexed addressing cannot be used
9731    because adjacent memory cells are accessed by adding word-sized offsets
9732    during assembly output.  */
9733 static bool
9734 rs6000_legitimate_address_p (machine_mode mode, rtx x, bool reg_ok_strict)
9735 {
9736   bool reg_offset_p = reg_offset_addressing_ok_p (mode);
9737   bool quad_offset_p = mode_supports_vsx_dform_quad (mode);
9738
9739   /* If this is an unaligned stvx/ldvx type address, discard the outer AND.  */
9740   if (VECTOR_MEM_ALTIVEC_P (mode)
9741       && GET_CODE (x) == AND
9742       && GET_CODE (XEXP (x, 1)) == CONST_INT
9743       && INTVAL (XEXP (x, 1)) == -16)
9744     x = XEXP (x, 0);
9745
9746   if (TARGET_ELF && RS6000_SYMBOL_REF_TLS_P (x))
9747     return 0;
9748   if (legitimate_indirect_address_p (x, reg_ok_strict))
9749     return 1;
9750   if (TARGET_UPDATE
9751       && (GET_CODE (x) == PRE_INC || GET_CODE (x) == PRE_DEC)
9752       && mode_supports_pre_incdec_p (mode)
9753       && legitimate_indirect_address_p (XEXP (x, 0), reg_ok_strict))
9754     return 1;
9755   /* Handle restricted vector d-form offsets in ISA 3.0.  */
9756   if (quad_offset_p)
9757     {
9758       if (quad_address_p (x, mode, reg_ok_strict))
9759         return 1;
9760     }
9761   else if (virtual_stack_registers_memory_p (x))
9762     return 1;
9763
9764   else if (reg_offset_p)
9765     {
9766       if (legitimate_small_data_p (mode, x))
9767         return 1;
9768       if (legitimate_constant_pool_address_p (x, mode,
9769                                              reg_ok_strict || lra_in_progress))
9770         return 1;
9771       if (reg_addr[mode].fused_toc && GET_CODE (x) == UNSPEC
9772           && XINT (x, 1) == UNSPEC_FUSION_ADDIS)
9773         return 1;
9774     }
9775
9776   /* For TImode, if we have TImode in VSX registers, only allow register
9777      indirect addresses.  This will allow the values to go in either GPRs
9778      or VSX registers without reloading.  The vector types would tend to
9779      go into VSX registers, so we allow REG+REG, while TImode seems
9780      somewhat split, in that some uses are GPR based, and some VSX based.  */
9781   /* FIXME: We could loosen this by changing the following to
9782        if (mode == TImode && TARGET_QUAD_MEMORY && TARGET_VSX)
9783      but currently we cannot allow REG+REG addressing for TImode.  See
9784      PR72827 for complete details on how this ends up hoodwinking DSE.  */
9785   if (mode == TImode && TARGET_VSX)
9786     return 0;
9787   /* If not REG_OK_STRICT (before reload) let pass any stack offset.  */
9788   if (! reg_ok_strict
9789       && reg_offset_p
9790       && GET_CODE (x) == PLUS
9791       && GET_CODE (XEXP (x, 0)) == REG
9792       && (XEXP (x, 0) == virtual_stack_vars_rtx
9793           || XEXP (x, 0) == arg_pointer_rtx)
9794       && GET_CODE (XEXP (x, 1)) == CONST_INT)
9795     return 1;
9796   if (rs6000_legitimate_offset_address_p (mode, x, reg_ok_strict, false))
9797     return 1;
9798   if (!FLOAT128_2REG_P (mode)
9799       && ((TARGET_HARD_FLOAT && TARGET_DOUBLE_FLOAT)
9800           || TARGET_POWERPC64
9801           || (mode != DFmode && mode != DDmode))
9802       && (TARGET_POWERPC64 || mode != DImode)
9803       && (mode != TImode || VECTOR_MEM_VSX_P (TImode))
9804       && mode != PTImode
9805       && !avoiding_indexed_address_p (mode)
9806       && legitimate_indexed_address_p (x, reg_ok_strict))
9807     return 1;
9808   if (TARGET_UPDATE && GET_CODE (x) == PRE_MODIFY
9809       && mode_supports_pre_modify_p (mode)
9810       && legitimate_indirect_address_p (XEXP (x, 0), reg_ok_strict)
9811       && (rs6000_legitimate_offset_address_p (mode, XEXP (x, 1),
9812                                               reg_ok_strict, false)
9813           || (!avoiding_indexed_address_p (mode)
9814               && legitimate_indexed_address_p (XEXP (x, 1), reg_ok_strict)))
9815       && rtx_equal_p (XEXP (XEXP (x, 1), 0), XEXP (x, 0)))
9816     return 1;
9817   if (reg_offset_p && !quad_offset_p
9818       && legitimate_lo_sum_address_p (mode, x, reg_ok_strict))
9819     return 1;
9820   return 0;
9821 }
9822
9823 /* Debug version of rs6000_legitimate_address_p.  */
9824 static bool
9825 rs6000_debug_legitimate_address_p (machine_mode mode, rtx x,
9826                                    bool reg_ok_strict)
9827 {
9828   bool ret = rs6000_legitimate_address_p (mode, x, reg_ok_strict);
9829   fprintf (stderr,
9830            "\nrs6000_legitimate_address_p: return = %s, mode = %s, "
9831            "strict = %d, reload = %s, code = %s\n",
9832            ret ? "true" : "false",
9833            GET_MODE_NAME (mode),
9834            reg_ok_strict,
9835            (reload_completed ? "after" : "before"),
9836            GET_RTX_NAME (GET_CODE (x)));
9837   debug_rtx (x);
9838
9839   return ret;
9840 }
9841
9842 /* Implement TARGET_MODE_DEPENDENT_ADDRESS_P.  */
9843
9844 static bool
9845 rs6000_mode_dependent_address_p (const_rtx addr,
9846                                  addr_space_t as ATTRIBUTE_UNUSED)
9847 {
9848   return rs6000_mode_dependent_address_ptr (addr);
9849 }
9850
9851 /* Go to LABEL if ADDR (a legitimate address expression)
9852    has an effect that depends on the machine mode it is used for.
9853
9854    On the RS/6000 this is true of all integral offsets (since AltiVec
9855    and VSX modes don't allow them) or is a pre-increment or decrement.
9856
9857    ??? Except that due to conceptual problems in offsettable_address_p
9858    we can't really report the problems of integral offsets.  So leave
9859    this assuming that the adjustable offset must be valid for the
9860    sub-words of a TFmode operand, which is what we had before.  */
9861
9862 static bool
9863 rs6000_mode_dependent_address (const_rtx addr)
9864 {
9865   switch (GET_CODE (addr))
9866     {
9867     case PLUS:
9868       /* Any offset from virtual_stack_vars_rtx and arg_pointer_rtx
9869          is considered a legitimate address before reload, so there
9870          are no offset restrictions in that case.  Note that this
9871          condition is safe in strict mode because any address involving
9872          virtual_stack_vars_rtx or arg_pointer_rtx would already have
9873          been rejected as illegitimate.  */
9874       if (XEXP (addr, 0) != virtual_stack_vars_rtx
9875           && XEXP (addr, 0) != arg_pointer_rtx
9876           && GET_CODE (XEXP (addr, 1)) == CONST_INT)
9877         {
9878           unsigned HOST_WIDE_INT val = INTVAL (XEXP (addr, 1));
9879           return val + 0x8000 >= 0x10000 - (TARGET_POWERPC64 ? 8 : 12);
9880         }
9881       break;
9882
9883     case LO_SUM:
9884       /* Anything in the constant pool is sufficiently aligned that
9885          all bytes have the same high part address.  */
9886       return !legitimate_constant_pool_address_p (addr, QImode, false);
9887
9888     /* Auto-increment cases are now treated generically in recog.c.  */
9889     case PRE_MODIFY:
9890       return TARGET_UPDATE;
9891
9892     /* AND is only allowed in Altivec loads.  */
9893     case AND:
9894       return true;
9895
9896     default:
9897       break;
9898     }
9899
9900   return false;
9901 }
9902
9903 /* Debug version of rs6000_mode_dependent_address.  */
9904 static bool
9905 rs6000_debug_mode_dependent_address (const_rtx addr)
9906 {
9907   bool ret = rs6000_mode_dependent_address (addr);
9908
9909   fprintf (stderr, "\nrs6000_mode_dependent_address: ret = %s\n",
9910            ret ? "true" : "false");
9911   debug_rtx (addr);
9912
9913   return ret;
9914 }
9915
9916 /* Implement FIND_BASE_TERM.  */
9917
9918 rtx
9919 rs6000_find_base_term (rtx op)
9920 {
9921   rtx base;
9922
9923   base = op;
9924   if (GET_CODE (base) == CONST)
9925     base = XEXP (base, 0);
9926   if (GET_CODE (base) == PLUS)
9927     base = XEXP (base, 0);
9928   if (GET_CODE (base) == UNSPEC)
9929     switch (XINT (base, 1))
9930       {
9931       case UNSPEC_TOCREL:
9932       case UNSPEC_MACHOPIC_OFFSET:
9933         /* OP represents SYM [+ OFFSET] - ANCHOR.  SYM is the base term
9934            for aliasing purposes.  */
9935         return XVECEXP (base, 0, 0);
9936       }
9937
9938   return op;
9939 }
9940
9941 /* More elaborate version of recog's offsettable_memref_p predicate
9942    that works around the ??? note of rs6000_mode_dependent_address.
9943    In particular it accepts
9944
9945      (mem:DI (plus:SI (reg/f:SI 31 31) (const_int 32760 [0x7ff8])))
9946
9947    in 32-bit mode, that the recog predicate rejects.  */
9948
9949 static bool
9950 rs6000_offsettable_memref_p (rtx op, machine_mode reg_mode)
9951 {
9952   bool worst_case;
9953
9954   if (!MEM_P (op))
9955     return false;
9956
9957   /* First mimic offsettable_memref_p.  */
9958   if (offsettable_address_p (true, GET_MODE (op), XEXP (op, 0)))
9959     return true;
9960
9961   /* offsettable_address_p invokes rs6000_mode_dependent_address, but
9962      the latter predicate knows nothing about the mode of the memory
9963      reference and, therefore, assumes that it is the largest supported
9964      mode (TFmode).  As a consequence, legitimate offsettable memory
9965      references are rejected.  rs6000_legitimate_offset_address_p contains
9966      the correct logic for the PLUS case of rs6000_mode_dependent_address,
9967      at least with a little bit of help here given that we know the
9968      actual registers used.  */
9969   worst_case = ((TARGET_POWERPC64 && GET_MODE_CLASS (reg_mode) == MODE_INT)
9970                 || GET_MODE_SIZE (reg_mode) == 4);
9971   return rs6000_legitimate_offset_address_p (GET_MODE (op), XEXP (op, 0),
9972                                              true, worst_case);
9973 }
9974
9975 /* Determine the reassociation width to be used in reassociate_bb.
9976    This takes into account how many parallel operations we
9977    can actually do of a given type, and also the latency.
9978    P8:
9979      int add/sub 6/cycle     
9980          mul 2/cycle
9981      vect add/sub/mul 2/cycle
9982      fp   add/sub/mul 2/cycle
9983      dfp  1/cycle
9984 */
9985  
9986 static int
9987 rs6000_reassociation_width (unsigned int opc ATTRIBUTE_UNUSED,
9988                             machine_mode mode)
9989 {
9990   switch (rs6000_tune)
9991     {
9992     case PROCESSOR_POWER8:
9993     case PROCESSOR_POWER9:
9994       if (DECIMAL_FLOAT_MODE_P (mode))
9995         return 1;
9996       if (VECTOR_MODE_P (mode))
9997         return 4;
9998       if (INTEGRAL_MODE_P (mode)) 
9999         return opc == MULT_EXPR ? 4 : 6;
10000       if (FLOAT_MODE_P (mode))
10001         return 4;
10002       break;
10003     default:
10004       break;
10005     }
10006   return 1;
10007 }
10008
10009 /* Change register usage conditional on target flags.  */
10010 static void
10011 rs6000_conditional_register_usage (void)
10012 {
10013   int i;
10014
10015   if (TARGET_DEBUG_TARGET)
10016     fprintf (stderr, "rs6000_conditional_register_usage called\n");
10017
10018   /* Set MQ register fixed (already call_used) so that it will not be
10019      allocated.  */
10020   fixed_regs[64] = 1;
10021
10022   /* 64-bit AIX and Linux reserve GPR13 for thread-private data.  */
10023   if (TARGET_64BIT)
10024     fixed_regs[13] = call_used_regs[13]
10025       = call_really_used_regs[13] = 1;
10026
10027   /* Conditionally disable FPRs.  */
10028   if (TARGET_SOFT_FLOAT)
10029     for (i = 32; i < 64; i++)
10030       fixed_regs[i] = call_used_regs[i]
10031         = call_really_used_regs[i] = 1;
10032
10033   /* The TOC register is not killed across calls in a way that is
10034      visible to the compiler.  */
10035   if (DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
10036     call_really_used_regs[2] = 0;
10037
10038   if (DEFAULT_ABI == ABI_V4 && flag_pic == 2)
10039     fixed_regs[RS6000_PIC_OFFSET_TABLE_REGNUM] = 1;
10040
10041   if (DEFAULT_ABI == ABI_V4 && flag_pic == 1)
10042     fixed_regs[RS6000_PIC_OFFSET_TABLE_REGNUM]
10043       = call_used_regs[RS6000_PIC_OFFSET_TABLE_REGNUM]
10044       = call_really_used_regs[RS6000_PIC_OFFSET_TABLE_REGNUM] = 1;
10045
10046   if (DEFAULT_ABI == ABI_DARWIN && flag_pic)
10047     fixed_regs[RS6000_PIC_OFFSET_TABLE_REGNUM]
10048       = call_used_regs[RS6000_PIC_OFFSET_TABLE_REGNUM]
10049       = call_really_used_regs[RS6000_PIC_OFFSET_TABLE_REGNUM] = 1;
10050
10051   if (TARGET_TOC && TARGET_MINIMAL_TOC)
10052     fixed_regs[RS6000_PIC_OFFSET_TABLE_REGNUM]
10053       = call_used_regs[RS6000_PIC_OFFSET_TABLE_REGNUM] = 1;
10054
10055   if (!TARGET_ALTIVEC && !TARGET_VSX)
10056     {
10057       for (i = FIRST_ALTIVEC_REGNO; i <= LAST_ALTIVEC_REGNO; ++i)
10058         fixed_regs[i] = call_used_regs[i] = call_really_used_regs[i] = 1;
10059       call_really_used_regs[VRSAVE_REGNO] = 1;
10060     }
10061
10062   if (TARGET_ALTIVEC || TARGET_VSX)
10063     global_regs[VSCR_REGNO] = 1;
10064
10065   if (TARGET_ALTIVEC_ABI)
10066     {
10067       for (i = FIRST_ALTIVEC_REGNO; i < FIRST_ALTIVEC_REGNO + 20; ++i)
10068         call_used_regs[i] = call_really_used_regs[i] = 1;
10069
10070       /* AIX reserves VR20:31 in non-extended ABI mode.  */
10071       if (TARGET_XCOFF)
10072         for (i = FIRST_ALTIVEC_REGNO + 20; i < FIRST_ALTIVEC_REGNO + 32; ++i)
10073           fixed_regs[i] = call_used_regs[i] = call_really_used_regs[i] = 1;
10074     }
10075 }
10076
10077 \f
10078 /* Output insns to set DEST equal to the constant SOURCE as a series of
10079    lis, ori and shl instructions and return TRUE.  */
10080
10081 bool
10082 rs6000_emit_set_const (rtx dest, rtx source)
10083 {
10084   machine_mode mode = GET_MODE (dest);
10085   rtx temp, set;
10086   rtx_insn *insn;
10087   HOST_WIDE_INT c;
10088
10089   gcc_checking_assert (CONST_INT_P (source));
10090   c = INTVAL (source);
10091   switch (mode)
10092     {
10093     case E_QImode:
10094     case E_HImode:
10095       emit_insn (gen_rtx_SET (dest, source));
10096       return true;
10097
10098     case E_SImode:
10099       temp = !can_create_pseudo_p () ? dest : gen_reg_rtx (SImode);
10100
10101       emit_insn (gen_rtx_SET (copy_rtx (temp),
10102                               GEN_INT (c & ~(HOST_WIDE_INT) 0xffff)));
10103       emit_insn (gen_rtx_SET (dest,
10104                               gen_rtx_IOR (SImode, copy_rtx (temp),
10105                                            GEN_INT (c & 0xffff))));
10106       break;
10107
10108     case E_DImode:
10109       if (!TARGET_POWERPC64)
10110         {
10111           rtx hi, lo;
10112
10113           hi = operand_subword_force (copy_rtx (dest), WORDS_BIG_ENDIAN == 0,
10114                                       DImode);
10115           lo = operand_subword_force (dest, WORDS_BIG_ENDIAN != 0,
10116                                       DImode);
10117           emit_move_insn (hi, GEN_INT (c >> 32));
10118           c = ((c & 0xffffffff) ^ 0x80000000) - 0x80000000;
10119           emit_move_insn (lo, GEN_INT (c));
10120         }
10121       else
10122         rs6000_emit_set_long_const (dest, c);
10123       break;
10124
10125     default:
10126       gcc_unreachable ();
10127     }
10128
10129   insn = get_last_insn ();
10130   set = single_set (insn);
10131   if (! CONSTANT_P (SET_SRC (set)))
10132     set_unique_reg_note (insn, REG_EQUAL, GEN_INT (c));
10133
10134   return true;
10135 }
10136
10137 /* Subroutine of rs6000_emit_set_const, handling PowerPC64 DImode.
10138    Output insns to set DEST equal to the constant C as a series of
10139    lis, ori and shl instructions.  */
10140
10141 static void
10142 rs6000_emit_set_long_const (rtx dest, HOST_WIDE_INT c)
10143 {
10144   rtx temp;
10145   HOST_WIDE_INT ud1, ud2, ud3, ud4;
10146
10147   ud1 = c & 0xffff;
10148   c = c >> 16;
10149   ud2 = c & 0xffff;
10150   c = c >> 16;
10151   ud3 = c & 0xffff;
10152   c = c >> 16;
10153   ud4 = c & 0xffff;
10154
10155   if ((ud4 == 0xffff && ud3 == 0xffff && ud2 == 0xffff && (ud1 & 0x8000))
10156       || (ud4 == 0 && ud3 == 0 && ud2 == 0 && ! (ud1 & 0x8000)))
10157     emit_move_insn (dest, GEN_INT ((ud1 ^ 0x8000) - 0x8000));
10158
10159   else if ((ud4 == 0xffff && ud3 == 0xffff && (ud2 & 0x8000))
10160            || (ud4 == 0 && ud3 == 0 && ! (ud2 & 0x8000)))
10161     {
10162       temp = !can_create_pseudo_p () ? dest : gen_reg_rtx (DImode);
10163
10164       emit_move_insn (ud1 != 0 ? copy_rtx (temp) : dest,
10165                       GEN_INT (((ud2 << 16) ^ 0x80000000) - 0x80000000));
10166       if (ud1 != 0)
10167         emit_move_insn (dest,
10168                         gen_rtx_IOR (DImode, copy_rtx (temp),
10169                                      GEN_INT (ud1)));
10170     }
10171   else if (ud3 == 0 && ud4 == 0)
10172     {
10173       temp = !can_create_pseudo_p () ? dest : gen_reg_rtx (DImode);
10174
10175       gcc_assert (ud2 & 0x8000);
10176       emit_move_insn (copy_rtx (temp),
10177                       GEN_INT (((ud2 << 16) ^ 0x80000000) - 0x80000000));
10178       if (ud1 != 0)
10179         emit_move_insn (copy_rtx (temp),
10180                         gen_rtx_IOR (DImode, copy_rtx (temp),
10181                                      GEN_INT (ud1)));
10182       emit_move_insn (dest,
10183                       gen_rtx_ZERO_EXTEND (DImode,
10184                                            gen_lowpart (SImode,
10185                                                         copy_rtx (temp))));
10186     }
10187   else if ((ud4 == 0xffff && (ud3 & 0x8000))
10188            || (ud4 == 0 && ! (ud3 & 0x8000)))
10189     {
10190       temp = !can_create_pseudo_p () ? dest : gen_reg_rtx (DImode);
10191
10192       emit_move_insn (copy_rtx (temp),
10193                       GEN_INT (((ud3 << 16) ^ 0x80000000) - 0x80000000));
10194       if (ud2 != 0)
10195         emit_move_insn (copy_rtx (temp),
10196                         gen_rtx_IOR (DImode, copy_rtx (temp),
10197                                      GEN_INT (ud2)));
10198       emit_move_insn (ud1 != 0 ? copy_rtx (temp) : dest,
10199                       gen_rtx_ASHIFT (DImode, copy_rtx (temp),
10200                                       GEN_INT (16)));
10201       if (ud1 != 0)
10202         emit_move_insn (dest,
10203                         gen_rtx_IOR (DImode, copy_rtx (temp),
10204                                      GEN_INT (ud1)));
10205     }
10206   else
10207     {
10208       temp = !can_create_pseudo_p () ? dest : gen_reg_rtx (DImode);
10209
10210       emit_move_insn (copy_rtx (temp),
10211                       GEN_INT (((ud4 << 16) ^ 0x80000000) - 0x80000000));
10212       if (ud3 != 0)
10213         emit_move_insn (copy_rtx (temp),
10214                         gen_rtx_IOR (DImode, copy_rtx (temp),
10215                                      GEN_INT (ud3)));
10216
10217       emit_move_insn (ud2 != 0 || ud1 != 0 ? copy_rtx (temp) : dest,
10218                       gen_rtx_ASHIFT (DImode, copy_rtx (temp),
10219                                       GEN_INT (32)));
10220       if (ud2 != 0)
10221         emit_move_insn (ud1 != 0 ? copy_rtx (temp) : dest,
10222                         gen_rtx_IOR (DImode, copy_rtx (temp),
10223                                      GEN_INT (ud2 << 16)));
10224       if (ud1 != 0)
10225         emit_move_insn (dest,
10226                         gen_rtx_IOR (DImode, copy_rtx (temp),
10227                                      GEN_INT (ud1)));
10228     }
10229 }
10230
10231 /* Helper for the following.  Get rid of [r+r] memory refs
10232    in cases where it won't work (TImode, TFmode, TDmode, PTImode).  */
10233
10234 static void
10235 rs6000_eliminate_indexed_memrefs (rtx operands[2])
10236 {
10237   if (GET_CODE (operands[0]) == MEM
10238       && GET_CODE (XEXP (operands[0], 0)) != REG
10239       && ! legitimate_constant_pool_address_p (XEXP (operands[0], 0),
10240                                                GET_MODE (operands[0]), false))
10241     operands[0]
10242       = replace_equiv_address (operands[0],
10243                                copy_addr_to_reg (XEXP (operands[0], 0)));
10244
10245   if (GET_CODE (operands[1]) == MEM
10246       && GET_CODE (XEXP (operands[1], 0)) != REG
10247       && ! legitimate_constant_pool_address_p (XEXP (operands[1], 0),
10248                                                GET_MODE (operands[1]), false))
10249     operands[1]
10250       = replace_equiv_address (operands[1],
10251                                copy_addr_to_reg (XEXP (operands[1], 0)));
10252 }
10253
10254 /* Generate a vector of constants to permute MODE for a little-endian
10255    storage operation by swapping the two halves of a vector.  */
10256 static rtvec
10257 rs6000_const_vec (machine_mode mode)
10258 {
10259   int i, subparts;
10260   rtvec v;
10261
10262   switch (mode)
10263     {
10264     case E_V1TImode:
10265       subparts = 1;
10266       break;
10267     case E_V2DFmode:
10268     case E_V2DImode:
10269       subparts = 2;
10270       break;
10271     case E_V4SFmode:
10272     case E_V4SImode:
10273       subparts = 4;
10274       break;
10275     case E_V8HImode:
10276       subparts = 8;
10277       break;
10278     case E_V16QImode:
10279       subparts = 16;
10280       break;
10281     default:
10282       gcc_unreachable();
10283     }
10284
10285   v = rtvec_alloc (subparts);
10286
10287   for (i = 0; i < subparts / 2; ++i)
10288     RTVEC_ELT (v, i) = gen_rtx_CONST_INT (DImode, i + subparts / 2);
10289   for (i = subparts / 2; i < subparts; ++i)
10290     RTVEC_ELT (v, i) = gen_rtx_CONST_INT (DImode, i - subparts / 2);
10291
10292   return v;
10293 }
10294
10295 /* Emit an lxvd2x, stxvd2x, or xxpermdi instruction for a VSX load or
10296    store operation.  */
10297 void
10298 rs6000_emit_le_vsx_permute (rtx dest, rtx source, machine_mode mode)
10299 {
10300   /* Scalar permutations are easier to express in integer modes rather than
10301      floating-point modes, so cast them here.  We use V1TImode instead
10302      of TImode to ensure that the values don't go through GPRs.  */
10303   if (FLOAT128_VECTOR_P (mode))
10304     {
10305       dest = gen_lowpart (V1TImode, dest);
10306       source = gen_lowpart (V1TImode, source);
10307       mode = V1TImode;
10308     }
10309
10310   /* Use ROTATE instead of VEC_SELECT if the mode contains only a single
10311      scalar.  */
10312   if (mode == TImode || mode == V1TImode)
10313     emit_insn (gen_rtx_SET (dest, gen_rtx_ROTATE (mode, source,
10314                                                   GEN_INT (64))));
10315   else
10316     {
10317       rtx par = gen_rtx_PARALLEL (VOIDmode, rs6000_const_vec (mode));
10318       emit_insn (gen_rtx_SET (dest, gen_rtx_VEC_SELECT (mode, source, par)));
10319     }
10320 }
10321
10322 /* Emit a little-endian load from vector memory location SOURCE to VSX
10323    register DEST in mode MODE.  The load is done with two permuting
10324    insn's that represent an lxvd2x and xxpermdi.  */
10325 void
10326 rs6000_emit_le_vsx_load (rtx dest, rtx source, machine_mode mode)
10327 {
10328   /* Use V2DImode to do swaps of types with 128-bit scalare parts (TImode,
10329      V1TImode).  */
10330   if (mode == TImode || mode == V1TImode)
10331     {
10332       mode = V2DImode;
10333       dest = gen_lowpart (V2DImode, dest);
10334       source = adjust_address (source, V2DImode, 0);
10335     }
10336
10337   rtx tmp = can_create_pseudo_p () ? gen_reg_rtx_and_attrs (dest) : dest;
10338   rs6000_emit_le_vsx_permute (tmp, source, mode);
10339   rs6000_emit_le_vsx_permute (dest, tmp, mode);
10340 }
10341
10342 /* Emit a little-endian store to vector memory location DEST from VSX
10343    register SOURCE in mode MODE.  The store is done with two permuting
10344    insn's that represent an xxpermdi and an stxvd2x.  */
10345 void
10346 rs6000_emit_le_vsx_store (rtx dest, rtx source, machine_mode mode)
10347 {
10348   /* This should never be called during or after LRA, because it does
10349      not re-permute the source register.  It is intended only for use
10350      during expand.  */
10351   gcc_assert (!lra_in_progress && !reload_completed);
10352
10353   /* Use V2DImode to do swaps of types with 128-bit scalar parts (TImode,
10354      V1TImode).  */
10355   if (mode == TImode || mode == V1TImode)
10356     {
10357       mode = V2DImode;
10358       dest = adjust_address (dest, V2DImode, 0);
10359       source = gen_lowpart (V2DImode, source);
10360     }
10361
10362   rtx tmp = can_create_pseudo_p () ? gen_reg_rtx_and_attrs (source) : source;
10363   rs6000_emit_le_vsx_permute (tmp, source, mode);
10364   rs6000_emit_le_vsx_permute (dest, tmp, mode);
10365 }
10366
10367 /* Emit a sequence representing a little-endian VSX load or store,
10368    moving data from SOURCE to DEST in mode MODE.  This is done
10369    separately from rs6000_emit_move to ensure it is called only
10370    during expand.  LE VSX loads and stores introduced later are
10371    handled with a split.  The expand-time RTL generation allows
10372    us to optimize away redundant pairs of register-permutes.  */
10373 void
10374 rs6000_emit_le_vsx_move (rtx dest, rtx source, machine_mode mode)
10375 {
10376   gcc_assert (!BYTES_BIG_ENDIAN
10377               && VECTOR_MEM_VSX_P (mode)
10378               && !TARGET_P9_VECTOR
10379               && !gpr_or_gpr_p (dest, source)
10380               && (MEM_P (source) ^ MEM_P (dest)));
10381
10382   if (MEM_P (source))
10383     {
10384       gcc_assert (REG_P (dest) || GET_CODE (dest) == SUBREG);
10385       rs6000_emit_le_vsx_load (dest, source, mode);
10386     }
10387   else
10388     {
10389       if (!REG_P (source))
10390         source = force_reg (mode, source);
10391       rs6000_emit_le_vsx_store (dest, source, mode);
10392     }
10393 }
10394
10395 /* Return whether a SFmode or SImode move can be done without converting one
10396    mode to another.  This arrises when we have:
10397
10398         (SUBREG:SF (REG:SI ...))
10399         (SUBREG:SI (REG:SF ...))
10400
10401    and one of the values is in a floating point/vector register, where SFmode
10402    scalars are stored in DFmode format.  */
10403
10404 bool
10405 valid_sf_si_move (rtx dest, rtx src, machine_mode mode)
10406 {
10407   if (TARGET_ALLOW_SF_SUBREG)
10408     return true;
10409
10410   if (mode != SFmode && GET_MODE_CLASS (mode) != MODE_INT)
10411     return true;
10412
10413   if (!SUBREG_P (src) || !sf_subreg_operand (src, mode))
10414     return true;
10415
10416   /*.  Allow (set (SUBREG:SI (REG:SF)) (SUBREG:SI (REG:SF))).  */
10417   if (SUBREG_P (dest))
10418     {
10419       rtx dest_subreg = SUBREG_REG (dest);
10420       rtx src_subreg = SUBREG_REG (src);
10421       return GET_MODE (dest_subreg) == GET_MODE (src_subreg);
10422     }
10423
10424   return false;
10425 }
10426
10427
10428 /* Helper function to change moves with:
10429
10430         (SUBREG:SF (REG:SI)) and
10431         (SUBREG:SI (REG:SF))
10432
10433    into separate UNSPEC insns.  In the PowerPC architecture, scalar SFmode
10434    values are stored as DFmode values in the VSX registers.  We need to convert
10435    the bits before we can use a direct move or operate on the bits in the
10436    vector register as an integer type.
10437
10438    Skip things like (set (SUBREG:SI (...) (SUBREG:SI (...)).  */
10439
10440 static bool
10441 rs6000_emit_move_si_sf_subreg (rtx dest, rtx source, machine_mode mode)
10442 {
10443   if (TARGET_DIRECT_MOVE_64BIT && !lra_in_progress && !reload_completed
10444       && (!SUBREG_P (dest) || !sf_subreg_operand (dest, mode))
10445       && SUBREG_P (source) && sf_subreg_operand (source, mode))
10446     {
10447       rtx inner_source = SUBREG_REG (source);
10448       machine_mode inner_mode = GET_MODE (inner_source);
10449
10450       if (mode == SImode && inner_mode == SFmode)
10451         {
10452           emit_insn (gen_movsi_from_sf (dest, inner_source));
10453           return true;
10454         }
10455
10456       if (mode == SFmode && inner_mode == SImode)
10457         {
10458           emit_insn (gen_movsf_from_si (dest, inner_source));
10459           return true;
10460         }
10461     }
10462
10463   return false;
10464 }
10465
10466 /* Emit a move from SOURCE to DEST in mode MODE.  */
10467 void
10468 rs6000_emit_move (rtx dest, rtx source, machine_mode mode)
10469 {
10470   rtx operands[2];
10471   operands[0] = dest;
10472   operands[1] = source;
10473
10474   if (TARGET_DEBUG_ADDR)
10475     {
10476       fprintf (stderr,
10477                "\nrs6000_emit_move: mode = %s, lra_in_progress = %d, "
10478                "reload_completed = %d, can_create_pseudos = %d.\ndest:\n",
10479                GET_MODE_NAME (mode),
10480                lra_in_progress,
10481                reload_completed,
10482                can_create_pseudo_p ());
10483       debug_rtx (dest);
10484       fprintf (stderr, "source:\n");
10485       debug_rtx (source);
10486     }
10487
10488   /* Sanity checks.  Check that we get CONST_DOUBLE only when we should.  */
10489   if (CONST_WIDE_INT_P (operands[1])
10490       && GET_MODE_BITSIZE (mode) <= HOST_BITS_PER_WIDE_INT)
10491     {
10492       /* This should be fixed with the introduction of CONST_WIDE_INT.  */
10493       gcc_unreachable ();
10494     }
10495
10496   /* See if we need to special case SImode/SFmode SUBREG moves.  */
10497   if ((mode == SImode || mode == SFmode) && SUBREG_P (source)
10498       && rs6000_emit_move_si_sf_subreg (dest, source, mode))
10499     return;
10500
10501   /* Check if GCC is setting up a block move that will end up using FP
10502      registers as temporaries.  We must make sure this is acceptable.  */
10503   if (GET_CODE (operands[0]) == MEM
10504       && GET_CODE (operands[1]) == MEM
10505       && mode == DImode
10506       && (rs6000_slow_unaligned_access (DImode, MEM_ALIGN (operands[0]))
10507           || rs6000_slow_unaligned_access (DImode, MEM_ALIGN (operands[1])))
10508       && ! (rs6000_slow_unaligned_access (SImode,
10509                                           (MEM_ALIGN (operands[0]) > 32
10510                                            ? 32 : MEM_ALIGN (operands[0])))
10511             || rs6000_slow_unaligned_access (SImode,
10512                                              (MEM_ALIGN (operands[1]) > 32
10513                                               ? 32 : MEM_ALIGN (operands[1]))))
10514       && ! MEM_VOLATILE_P (operands [0])
10515       && ! MEM_VOLATILE_P (operands [1]))
10516     {
10517       emit_move_insn (adjust_address (operands[0], SImode, 0),
10518                       adjust_address (operands[1], SImode, 0));
10519       emit_move_insn (adjust_address (copy_rtx (operands[0]), SImode, 4),
10520                       adjust_address (copy_rtx (operands[1]), SImode, 4));
10521       return;
10522     }
10523
10524   if (can_create_pseudo_p () && GET_CODE (operands[0]) == MEM
10525       && !gpc_reg_operand (operands[1], mode))
10526     operands[1] = force_reg (mode, operands[1]);
10527
10528   /* Recognize the case where operand[1] is a reference to thread-local
10529      data and load its address to a register.  */
10530   if (tls_referenced_p (operands[1]))
10531     {
10532       enum tls_model model;
10533       rtx tmp = operands[1];
10534       rtx addend = NULL;
10535
10536       if (GET_CODE (tmp) == CONST && GET_CODE (XEXP (tmp, 0)) == PLUS)
10537         {
10538           addend = XEXP (XEXP (tmp, 0), 1);
10539           tmp = XEXP (XEXP (tmp, 0), 0);
10540         }
10541
10542       gcc_assert (GET_CODE (tmp) == SYMBOL_REF);
10543       model = SYMBOL_REF_TLS_MODEL (tmp);
10544       gcc_assert (model != 0);
10545
10546       tmp = rs6000_legitimize_tls_address (tmp, model);
10547       if (addend)
10548         {
10549           tmp = gen_rtx_PLUS (mode, tmp, addend);
10550           tmp = force_operand (tmp, operands[0]);
10551         }
10552       operands[1] = tmp;
10553     }
10554
10555   /* 128-bit constant floating-point values on Darwin should really be loaded
10556      as two parts.  However, this premature splitting is a problem when DFmode
10557      values can go into Altivec registers.  */
10558   if (FLOAT128_IBM_P (mode) && !reg_addr[DFmode].scalar_in_vmx_p
10559       && GET_CODE (operands[1]) == CONST_DOUBLE)
10560     {
10561       rs6000_emit_move (simplify_gen_subreg (DFmode, operands[0], mode, 0),
10562                         simplify_gen_subreg (DFmode, operands[1], mode, 0),
10563                         DFmode);
10564       rs6000_emit_move (simplify_gen_subreg (DFmode, operands[0], mode,
10565                                              GET_MODE_SIZE (DFmode)),
10566                         simplify_gen_subreg (DFmode, operands[1], mode,
10567                                              GET_MODE_SIZE (DFmode)),
10568                         DFmode);
10569       return;
10570     }
10571
10572   /* Transform (p0:DD, (SUBREG:DD p1:SD)) to ((SUBREG:SD p0:DD),
10573      p1:SD) if p1 is not of floating point class and p0 is spilled as
10574      we can have no analogous movsd_store for this.  */
10575   if (lra_in_progress && mode == DDmode
10576       && REG_P (operands[0]) && REGNO (operands[0]) >= FIRST_PSEUDO_REGISTER
10577       && reg_preferred_class (REGNO (operands[0])) == NO_REGS
10578       && GET_CODE (operands[1]) == SUBREG && REG_P (SUBREG_REG (operands[1]))
10579       && GET_MODE (SUBREG_REG (operands[1])) == SDmode)
10580     {
10581       enum reg_class cl;
10582       int regno = REGNO (SUBREG_REG (operands[1]));
10583
10584       if (regno >= FIRST_PSEUDO_REGISTER)
10585         {
10586           cl = reg_preferred_class (regno);
10587           regno = cl == NO_REGS ? -1 : ira_class_hard_regs[cl][1];
10588         }
10589       if (regno >= 0 && ! FP_REGNO_P (regno))
10590         {
10591           mode = SDmode;
10592           operands[0] = gen_lowpart_SUBREG (SDmode, operands[0]);
10593           operands[1] = SUBREG_REG (operands[1]);
10594         }
10595     }
10596   if (lra_in_progress
10597       && mode == SDmode
10598       && REG_P (operands[0]) && REGNO (operands[0]) >= FIRST_PSEUDO_REGISTER
10599       && reg_preferred_class (REGNO (operands[0])) == NO_REGS
10600       && (REG_P (operands[1])
10601           || (GET_CODE (operands[1]) == SUBREG
10602               && REG_P (SUBREG_REG (operands[1])))))
10603     {
10604       int regno = REGNO (GET_CODE (operands[1]) == SUBREG
10605                          ? SUBREG_REG (operands[1]) : operands[1]);
10606       enum reg_class cl;
10607
10608       if (regno >= FIRST_PSEUDO_REGISTER)
10609         {
10610           cl = reg_preferred_class (regno);
10611           gcc_assert (cl != NO_REGS);
10612           regno = ira_class_hard_regs[cl][0];
10613         }
10614       if (FP_REGNO_P (regno))
10615         {
10616           if (GET_MODE (operands[0]) != DDmode)
10617             operands[0] = gen_rtx_SUBREG (DDmode, operands[0], 0);
10618           emit_insn (gen_movsd_store (operands[0], operands[1]));
10619         }
10620       else if (INT_REGNO_P (regno))
10621         emit_insn (gen_movsd_hardfloat (operands[0], operands[1]));
10622       else
10623         gcc_unreachable();
10624       return;
10625     }
10626   /* Transform ((SUBREG:DD p0:SD), p1:DD) to (p0:SD, (SUBREG:SD
10627      p:DD)) if p0 is not of floating point class and p1 is spilled as
10628      we can have no analogous movsd_load for this.  */
10629   if (lra_in_progress && mode == DDmode
10630       && GET_CODE (operands[0]) == SUBREG && REG_P (SUBREG_REG (operands[0]))
10631       && GET_MODE (SUBREG_REG (operands[0])) == SDmode
10632       && REG_P (operands[1]) && REGNO (operands[1]) >= FIRST_PSEUDO_REGISTER
10633       && reg_preferred_class (REGNO (operands[1])) == NO_REGS)
10634     {
10635       enum reg_class cl;
10636       int regno = REGNO (SUBREG_REG (operands[0]));
10637
10638       if (regno >= FIRST_PSEUDO_REGISTER)
10639         {
10640           cl = reg_preferred_class (regno);
10641           regno = cl == NO_REGS ? -1 : ira_class_hard_regs[cl][0];
10642         }
10643       if (regno >= 0 && ! FP_REGNO_P (regno))
10644         {
10645           mode = SDmode;
10646           operands[0] = SUBREG_REG (operands[0]);
10647           operands[1] = gen_lowpart_SUBREG (SDmode, operands[1]);
10648         }
10649     }
10650   if (lra_in_progress
10651       && mode == SDmode
10652       && (REG_P (operands[0])
10653           || (GET_CODE (operands[0]) == SUBREG
10654               && REG_P (SUBREG_REG (operands[0]))))
10655       && REG_P (operands[1]) && REGNO (operands[1]) >= FIRST_PSEUDO_REGISTER
10656       && reg_preferred_class (REGNO (operands[1])) == NO_REGS)
10657     {
10658       int regno = REGNO (GET_CODE (operands[0]) == SUBREG
10659                          ? SUBREG_REG (operands[0]) : operands[0]);
10660       enum reg_class cl;
10661
10662       if (regno >= FIRST_PSEUDO_REGISTER)
10663         {
10664           cl = reg_preferred_class (regno);
10665           gcc_assert (cl != NO_REGS);
10666           regno = ira_class_hard_regs[cl][0];
10667         }
10668       if (FP_REGNO_P (regno))
10669         {
10670           if (GET_MODE (operands[1]) != DDmode)
10671             operands[1] = gen_rtx_SUBREG (DDmode, operands[1], 0);
10672           emit_insn (gen_movsd_load (operands[0], operands[1]));
10673         }
10674       else if (INT_REGNO_P (regno))
10675         emit_insn (gen_movsd_hardfloat (operands[0], operands[1]));
10676       else
10677         gcc_unreachable();
10678       return;
10679     }
10680
10681   /* FIXME:  In the long term, this switch statement should go away
10682      and be replaced by a sequence of tests based on things like
10683      mode == Pmode.  */
10684   switch (mode)
10685     {
10686     case E_HImode:
10687     case E_QImode:
10688       if (CONSTANT_P (operands[1])
10689           && GET_CODE (operands[1]) != CONST_INT)
10690         operands[1] = force_const_mem (mode, operands[1]);
10691       break;
10692
10693     case E_TFmode:
10694     case E_TDmode:
10695     case E_IFmode:
10696     case E_KFmode:
10697       if (FLOAT128_2REG_P (mode))
10698         rs6000_eliminate_indexed_memrefs (operands);
10699       /* fall through */
10700
10701     case E_DFmode:
10702     case E_DDmode:
10703     case E_SFmode:
10704     case E_SDmode:
10705       if (CONSTANT_P (operands[1])
10706           && ! easy_fp_constant (operands[1], mode))
10707         operands[1] = force_const_mem (mode, operands[1]);
10708       break;
10709
10710     case E_V16QImode:
10711     case E_V8HImode:
10712     case E_V4SFmode:
10713     case E_V4SImode:
10714     case E_V2SFmode:
10715     case E_V2SImode:
10716     case E_V2DFmode:
10717     case E_V2DImode:
10718     case E_V1TImode:
10719       if (CONSTANT_P (operands[1])
10720           && !easy_vector_constant (operands[1], mode))
10721         operands[1] = force_const_mem (mode, operands[1]);
10722       break;
10723
10724     case E_SImode:
10725     case E_DImode:
10726       /* Use default pattern for address of ELF small data */
10727       if (TARGET_ELF
10728           && mode == Pmode
10729           && DEFAULT_ABI == ABI_V4
10730           && (GET_CODE (operands[1]) == SYMBOL_REF
10731               || GET_CODE (operands[1]) == CONST)
10732           && small_data_operand (operands[1], mode))
10733         {
10734           emit_insn (gen_rtx_SET (operands[0], operands[1]));
10735           return;
10736         }
10737
10738       if (DEFAULT_ABI == ABI_V4
10739           && mode == Pmode && mode == SImode
10740           && flag_pic == 1 && got_operand (operands[1], mode))
10741         {
10742           emit_insn (gen_movsi_got (operands[0], operands[1]));
10743           return;
10744         }
10745
10746       if ((TARGET_ELF || DEFAULT_ABI == ABI_DARWIN)
10747           && TARGET_NO_TOC
10748           && ! flag_pic
10749           && mode == Pmode
10750           && CONSTANT_P (operands[1])
10751           && GET_CODE (operands[1]) != HIGH
10752           && GET_CODE (operands[1]) != CONST_INT)
10753         {
10754           rtx target = (!can_create_pseudo_p ()
10755                         ? operands[0]
10756                         : gen_reg_rtx (mode));
10757
10758           /* If this is a function address on -mcall-aixdesc,
10759              convert it to the address of the descriptor.  */
10760           if (DEFAULT_ABI == ABI_AIX
10761               && GET_CODE (operands[1]) == SYMBOL_REF
10762               && XSTR (operands[1], 0)[0] == '.')
10763             {
10764               const char *name = XSTR (operands[1], 0);
10765               rtx new_ref;
10766               while (*name == '.')
10767                 name++;
10768               new_ref = gen_rtx_SYMBOL_REF (Pmode, name);
10769               CONSTANT_POOL_ADDRESS_P (new_ref)
10770                 = CONSTANT_POOL_ADDRESS_P (operands[1]);
10771               SYMBOL_REF_FLAGS (new_ref) = SYMBOL_REF_FLAGS (operands[1]);
10772               SYMBOL_REF_USED (new_ref) = SYMBOL_REF_USED (operands[1]);
10773               SYMBOL_REF_DATA (new_ref) = SYMBOL_REF_DATA (operands[1]);
10774               operands[1] = new_ref;
10775             }
10776
10777           if (DEFAULT_ABI == ABI_DARWIN)
10778             {
10779 #if TARGET_MACHO
10780               if (MACHO_DYNAMIC_NO_PIC_P)
10781                 {
10782                   /* Take care of any required data indirection.  */
10783                   operands[1] = rs6000_machopic_legitimize_pic_address (
10784                                   operands[1], mode, operands[0]);
10785                   if (operands[0] != operands[1])
10786                     emit_insn (gen_rtx_SET (operands[0], operands[1]));
10787                   return;
10788                 }
10789 #endif
10790               emit_insn (gen_macho_high (target, operands[1]));
10791               emit_insn (gen_macho_low (operands[0], target, operands[1]));
10792               return;
10793             }
10794
10795           emit_insn (gen_elf_high (target, operands[1]));
10796           emit_insn (gen_elf_low (operands[0], target, operands[1]));
10797           return;
10798         }
10799
10800       /* If this is a SYMBOL_REF that refers to a constant pool entry,
10801          and we have put it in the TOC, we just need to make a TOC-relative
10802          reference to it.  */
10803       if (TARGET_TOC
10804           && GET_CODE (operands[1]) == SYMBOL_REF
10805           && use_toc_relative_ref (operands[1], mode))
10806         operands[1] = create_TOC_reference (operands[1], operands[0]);
10807       else if (mode == Pmode
10808                && CONSTANT_P (operands[1])
10809                && GET_CODE (operands[1]) != HIGH
10810                && ((GET_CODE (operands[1]) != CONST_INT
10811                     && ! easy_fp_constant (operands[1], mode))
10812                    || (GET_CODE (operands[1]) == CONST_INT
10813                        && (num_insns_constant (operands[1], mode)
10814                            > (TARGET_CMODEL != CMODEL_SMALL ? 3 : 2)))
10815                    || (GET_CODE (operands[0]) == REG
10816                        && FP_REGNO_P (REGNO (operands[0]))))
10817                && !toc_relative_expr_p (operands[1], false, NULL, NULL)
10818                && (TARGET_CMODEL == CMODEL_SMALL
10819                    || can_create_pseudo_p ()
10820                    || (REG_P (operands[0])
10821                        && INT_REG_OK_FOR_BASE_P (operands[0], true))))
10822         {
10823
10824 #if TARGET_MACHO
10825           /* Darwin uses a special PIC legitimizer.  */
10826           if (DEFAULT_ABI == ABI_DARWIN && MACHOPIC_INDIRECT)
10827             {
10828               operands[1] =
10829                 rs6000_machopic_legitimize_pic_address (operands[1], mode,
10830                                                         operands[0]);
10831               if (operands[0] != operands[1])
10832                 emit_insn (gen_rtx_SET (operands[0], operands[1]));
10833               return;
10834             }
10835 #endif
10836
10837           /* If we are to limit the number of things we put in the TOC and
10838              this is a symbol plus a constant we can add in one insn,
10839              just put the symbol in the TOC and add the constant.  */
10840           if (GET_CODE (operands[1]) == CONST
10841               && TARGET_NO_SUM_IN_TOC
10842               && GET_CODE (XEXP (operands[1], 0)) == PLUS
10843               && add_operand (XEXP (XEXP (operands[1], 0), 1), mode)
10844               && (GET_CODE (XEXP (XEXP (operands[1], 0), 0)) == LABEL_REF
10845                   || GET_CODE (XEXP (XEXP (operands[1], 0), 0)) == SYMBOL_REF)
10846               && ! side_effects_p (operands[0]))
10847             {
10848               rtx sym =
10849                 force_const_mem (mode, XEXP (XEXP (operands[1], 0), 0));
10850               rtx other = XEXP (XEXP (operands[1], 0), 1);
10851
10852               sym = force_reg (mode, sym);
10853               emit_insn (gen_add3_insn (operands[0], sym, other));
10854               return;
10855             }
10856
10857           operands[1] = force_const_mem (mode, operands[1]);
10858
10859           if (TARGET_TOC
10860               && GET_CODE (XEXP (operands[1], 0)) == SYMBOL_REF
10861               && use_toc_relative_ref (XEXP (operands[1], 0), mode))
10862             {
10863               rtx tocref = create_TOC_reference (XEXP (operands[1], 0),
10864                                                  operands[0]);
10865               operands[1] = gen_const_mem (mode, tocref);
10866               set_mem_alias_set (operands[1], get_TOC_alias_set ());
10867             }
10868         }
10869       break;
10870
10871     case E_TImode:
10872       if (!VECTOR_MEM_VSX_P (TImode))
10873         rs6000_eliminate_indexed_memrefs (operands);
10874       break;
10875
10876     case E_PTImode:
10877       rs6000_eliminate_indexed_memrefs (operands);
10878       break;
10879
10880     default:
10881       fatal_insn ("bad move", gen_rtx_SET (dest, source));
10882     }
10883
10884   /* Above, we may have called force_const_mem which may have returned
10885      an invalid address.  If we can, fix this up; otherwise, reload will
10886      have to deal with it.  */
10887   if (GET_CODE (operands[1]) == MEM)
10888     operands[1] = validize_mem (operands[1]);
10889
10890   emit_insn (gen_rtx_SET (operands[0], operands[1]));
10891 }
10892 \f
10893 /* Nonzero if we can use a floating-point register to pass this arg.  */
10894 #define USE_FP_FOR_ARG_P(CUM,MODE)              \
10895   (SCALAR_FLOAT_MODE_NOT_VECTOR_P (MODE)                \
10896    && (CUM)->fregno <= FP_ARG_MAX_REG           \
10897    && TARGET_HARD_FLOAT)
10898
10899 /* Nonzero if we can use an AltiVec register to pass this arg.  */
10900 #define USE_ALTIVEC_FOR_ARG_P(CUM,MODE,NAMED)                   \
10901   (ALTIVEC_OR_VSX_VECTOR_MODE (MODE)                            \
10902    && (CUM)->vregno <= ALTIVEC_ARG_MAX_REG                      \
10903    && TARGET_ALTIVEC_ABI                                        \
10904    && (NAMED))
10905
10906 /* Walk down the type tree of TYPE counting consecutive base elements.
10907    If *MODEP is VOIDmode, then set it to the first valid floating point
10908    or vector type.  If a non-floating point or vector type is found, or
10909    if a floating point or vector type that doesn't match a non-VOIDmode
10910    *MODEP is found, then return -1, otherwise return the count in the
10911    sub-tree.  */
10912
10913 static int
10914 rs6000_aggregate_candidate (const_tree type, machine_mode *modep)
10915 {
10916   machine_mode mode;
10917   HOST_WIDE_INT size;
10918
10919   switch (TREE_CODE (type))
10920     {
10921     case REAL_TYPE:
10922       mode = TYPE_MODE (type);
10923       if (!SCALAR_FLOAT_MODE_P (mode))
10924         return -1;
10925
10926       if (*modep == VOIDmode)
10927         *modep = mode;
10928
10929       if (*modep == mode)
10930         return 1;
10931
10932       break;
10933
10934     case COMPLEX_TYPE:
10935       mode = TYPE_MODE (TREE_TYPE (type));
10936       if (!SCALAR_FLOAT_MODE_P (mode))
10937         return -1;
10938
10939       if (*modep == VOIDmode)
10940         *modep = mode;
10941
10942       if (*modep == mode)
10943         return 2;
10944
10945       break;
10946
10947     case VECTOR_TYPE:
10948       if (!TARGET_ALTIVEC_ABI || !TARGET_ALTIVEC)
10949         return -1;
10950
10951       /* Use V4SImode as representative of all 128-bit vector types.  */
10952       size = int_size_in_bytes (type);
10953       switch (size)
10954         {
10955         case 16:
10956           mode = V4SImode;
10957           break;
10958         default:
10959           return -1;
10960         }
10961
10962       if (*modep == VOIDmode)
10963         *modep = mode;
10964
10965       /* Vector modes are considered to be opaque: two vectors are
10966          equivalent for the purposes of being homogeneous aggregates
10967          if they are the same size.  */
10968       if (*modep == mode)
10969         return 1;
10970
10971       break;
10972
10973     case ARRAY_TYPE:
10974       {
10975         int count;
10976         tree index = TYPE_DOMAIN (type);
10977
10978         /* Can't handle incomplete types nor sizes that are not
10979            fixed.  */
10980         if (!COMPLETE_TYPE_P (type)
10981             || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST)
10982           return -1;
10983
10984         count = rs6000_aggregate_candidate (TREE_TYPE (type), modep);
10985         if (count == -1
10986             || !index
10987             || !TYPE_MAX_VALUE (index)
10988             || !tree_fits_uhwi_p (TYPE_MAX_VALUE (index))
10989             || !TYPE_MIN_VALUE (index)
10990             || !tree_fits_uhwi_p (TYPE_MIN_VALUE (index))
10991             || count < 0)
10992           return -1;
10993
10994         count *= (1 + tree_to_uhwi (TYPE_MAX_VALUE (index))
10995                       - tree_to_uhwi (TYPE_MIN_VALUE (index)));
10996
10997         /* There must be no padding.  */
10998         if (wi::to_wide (TYPE_SIZE (type))
10999             != count * GET_MODE_BITSIZE (*modep))
11000           return -1;
11001
11002         return count;
11003       }
11004
11005     case RECORD_TYPE:
11006       {
11007         int count = 0;
11008         int sub_count;
11009         tree field;
11010
11011         /* Can't handle incomplete types nor sizes that are not
11012            fixed.  */
11013         if (!COMPLETE_TYPE_P (type)
11014             || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST)
11015           return -1;
11016
11017         for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
11018           {
11019             if (TREE_CODE (field) != FIELD_DECL)
11020               continue;
11021
11022             sub_count = rs6000_aggregate_candidate (TREE_TYPE (field), modep);
11023             if (sub_count < 0)
11024               return -1;
11025             count += sub_count;
11026           }
11027
11028         /* There must be no padding.  */
11029         if (wi::to_wide (TYPE_SIZE (type))
11030             != count * GET_MODE_BITSIZE (*modep))
11031           return -1;
11032
11033         return count;
11034       }
11035
11036     case UNION_TYPE:
11037     case QUAL_UNION_TYPE:
11038       {
11039         /* These aren't very interesting except in a degenerate case.  */
11040         int count = 0;
11041         int sub_count;
11042         tree field;
11043
11044         /* Can't handle incomplete types nor sizes that are not
11045            fixed.  */
11046         if (!COMPLETE_TYPE_P (type)
11047             || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST)
11048           return -1;
11049
11050         for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
11051           {
11052             if (TREE_CODE (field) != FIELD_DECL)
11053               continue;
11054
11055             sub_count = rs6000_aggregate_candidate (TREE_TYPE (field), modep);
11056             if (sub_count < 0)
11057               return -1;
11058             count = count > sub_count ? count : sub_count;
11059           }
11060
11061         /* There must be no padding.  */
11062         if (wi::to_wide (TYPE_SIZE (type))
11063             != count * GET_MODE_BITSIZE (*modep))
11064           return -1;
11065
11066         return count;
11067       }
11068
11069     default:
11070       break;
11071     }
11072
11073   return -1;
11074 }
11075
11076 /* If an argument, whose type is described by TYPE and MODE, is a homogeneous
11077    float or vector aggregate that shall be passed in FP/vector registers
11078    according to the ELFv2 ABI, return the homogeneous element mode in
11079    *ELT_MODE and the number of elements in *N_ELTS, and return TRUE.
11080
11081    Otherwise, set *ELT_MODE to MODE and *N_ELTS to 1, and return FALSE.  */
11082
11083 static bool
11084 rs6000_discover_homogeneous_aggregate (machine_mode mode, const_tree type,
11085                                        machine_mode *elt_mode,
11086                                        int *n_elts)
11087 {
11088   /* Note that we do not accept complex types at the top level as
11089      homogeneous aggregates; these types are handled via the
11090      targetm.calls.split_complex_arg mechanism.  Complex types
11091      can be elements of homogeneous aggregates, however.  */
11092   if (TARGET_HARD_FLOAT && DEFAULT_ABI == ABI_ELFv2 && type
11093       && AGGREGATE_TYPE_P (type))
11094     {
11095       machine_mode field_mode = VOIDmode;
11096       int field_count = rs6000_aggregate_candidate (type, &field_mode);
11097
11098       if (field_count > 0)
11099         {
11100           int n_regs = (SCALAR_FLOAT_MODE_P (field_mode) ?
11101                         (GET_MODE_SIZE (field_mode) + 7) >> 3 : 1);
11102
11103           /* The ELFv2 ABI allows homogeneous aggregates to occupy
11104              up to AGGR_ARG_NUM_REG registers.  */
11105           if (field_count * n_regs <= AGGR_ARG_NUM_REG)
11106             {
11107               if (elt_mode)
11108                 *elt_mode = field_mode;
11109               if (n_elts)
11110                 *n_elts = field_count;
11111               return true;
11112             }
11113         }
11114     }
11115
11116   if (elt_mode)
11117     *elt_mode = mode;
11118   if (n_elts)
11119     *n_elts = 1;
11120   return false;
11121 }
11122
11123 /* Return a nonzero value to say to return the function value in
11124    memory, just as large structures are always returned.  TYPE will be
11125    the data type of the value, and FNTYPE will be the type of the
11126    function doing the returning, or @code{NULL} for libcalls.
11127
11128    The AIX ABI for the RS/6000 specifies that all structures are
11129    returned in memory.  The Darwin ABI does the same.
11130    
11131    For the Darwin 64 Bit ABI, a function result can be returned in
11132    registers or in memory, depending on the size of the return data
11133    type.  If it is returned in registers, the value occupies the same
11134    registers as it would if it were the first and only function
11135    argument.  Otherwise, the function places its result in memory at
11136    the location pointed to by GPR3.
11137    
11138    The SVR4 ABI specifies that structures <= 8 bytes are returned in r3/r4, 
11139    but a draft put them in memory, and GCC used to implement the draft
11140    instead of the final standard.  Therefore, aix_struct_return
11141    controls this instead of DEFAULT_ABI; V.4 targets needing backward
11142    compatibility can change DRAFT_V4_STRUCT_RET to override the
11143    default, and -m switches get the final word.  See
11144    rs6000_option_override_internal for more details.
11145
11146    The PPC32 SVR4 ABI uses IEEE double extended for long double, if 128-bit
11147    long double support is enabled.  These values are returned in memory.
11148
11149    int_size_in_bytes returns -1 for variable size objects, which go in
11150    memory always.  The cast to unsigned makes -1 > 8.  */
11151
11152 static bool
11153 rs6000_return_in_memory (const_tree type, const_tree fntype ATTRIBUTE_UNUSED)
11154 {
11155   /* For the Darwin64 ABI, test if we can fit the return value in regs.  */
11156   if (TARGET_MACHO
11157       && rs6000_darwin64_abi
11158       && TREE_CODE (type) == RECORD_TYPE
11159       && int_size_in_bytes (type) > 0)
11160     {
11161       CUMULATIVE_ARGS valcum;
11162       rtx valret;
11163
11164       valcum.words = 0;
11165       valcum.fregno = FP_ARG_MIN_REG;
11166       valcum.vregno = ALTIVEC_ARG_MIN_REG;
11167       /* Do a trial code generation as if this were going to be passed
11168          as an argument; if any part goes in memory, we return NULL.  */
11169       valret = rs6000_darwin64_record_arg (&valcum, type, true, true);
11170       if (valret)
11171         return false;
11172       /* Otherwise fall through to more conventional ABI rules.  */
11173     }
11174
11175   /* The ELFv2 ABI returns homogeneous VFP aggregates in registers */
11176   if (rs6000_discover_homogeneous_aggregate (TYPE_MODE (type), type,
11177                                              NULL, NULL))
11178     return false;
11179
11180   /* The ELFv2 ABI returns aggregates up to 16B in registers */
11181   if (DEFAULT_ABI == ABI_ELFv2 && AGGREGATE_TYPE_P (type)
11182       && (unsigned HOST_WIDE_INT) int_size_in_bytes (type) <= 16)
11183     return false;
11184
11185   if (AGGREGATE_TYPE_P (type)
11186       && (aix_struct_return
11187           || (unsigned HOST_WIDE_INT) int_size_in_bytes (type) > 8))
11188     return true;
11189
11190   /* Allow -maltivec -mabi=no-altivec without warning.  Altivec vector
11191      modes only exist for GCC vector types if -maltivec.  */
11192   if (TARGET_32BIT && !TARGET_ALTIVEC_ABI
11193       && ALTIVEC_VECTOR_MODE (TYPE_MODE (type)))
11194     return false;
11195
11196   /* Return synthetic vectors in memory.  */
11197   if (TREE_CODE (type) == VECTOR_TYPE
11198       && int_size_in_bytes (type) > (TARGET_ALTIVEC_ABI ? 16 : 8))
11199     {
11200       static bool warned_for_return_big_vectors = false;
11201       if (!warned_for_return_big_vectors)
11202         {
11203           warning (OPT_Wpsabi, "GCC vector returned by reference: "
11204                    "non-standard ABI extension with no compatibility "
11205                    "guarantee");
11206           warned_for_return_big_vectors = true;
11207         }
11208       return true;
11209     }
11210
11211   if (DEFAULT_ABI == ABI_V4 && TARGET_IEEEQUAD
11212       && FLOAT128_IEEE_P (TYPE_MODE (type)))
11213     return true;
11214
11215   return false;
11216 }
11217
11218 /* Specify whether values returned in registers should be at the most
11219    significant end of a register.  We want aggregates returned by
11220    value to match the way aggregates are passed to functions.  */
11221
11222 static bool
11223 rs6000_return_in_msb (const_tree valtype)
11224 {
11225   return (DEFAULT_ABI == ABI_ELFv2
11226           && BYTES_BIG_ENDIAN
11227           && AGGREGATE_TYPE_P (valtype)
11228           && (rs6000_function_arg_padding (TYPE_MODE (valtype), valtype)
11229               == PAD_UPWARD));
11230 }
11231
11232 #ifdef HAVE_AS_GNU_ATTRIBUTE
11233 /* Return TRUE if a call to function FNDECL may be one that
11234    potentially affects the function calling ABI of the object file.  */
11235
11236 static bool
11237 call_ABI_of_interest (tree fndecl)
11238 {
11239   if (rs6000_gnu_attr && symtab->state == EXPANSION)
11240     {
11241       struct cgraph_node *c_node;
11242
11243       /* Libcalls are always interesting.  */
11244       if (fndecl == NULL_TREE)
11245         return true;
11246
11247       /* Any call to an external function is interesting.  */
11248       if (DECL_EXTERNAL (fndecl))
11249         return true;
11250
11251       /* Interesting functions that we are emitting in this object file.  */
11252       c_node = cgraph_node::get (fndecl);
11253       c_node = c_node->ultimate_alias_target ();
11254       return !c_node->only_called_directly_p ();
11255     }
11256   return false;
11257 }
11258 #endif
11259
11260 /* Initialize a variable CUM of type CUMULATIVE_ARGS
11261    for a call to a function whose data type is FNTYPE.
11262    For a library call, FNTYPE is 0 and RETURN_MODE the return value mode.
11263
11264    For incoming args we set the number of arguments in the prototype large
11265    so we never return a PARALLEL.  */
11266
11267 void
11268 init_cumulative_args (CUMULATIVE_ARGS *cum, tree fntype,
11269                       rtx libname ATTRIBUTE_UNUSED, int incoming,
11270                       int libcall, int n_named_args,
11271                       tree fndecl ATTRIBUTE_UNUSED,
11272                       machine_mode return_mode ATTRIBUTE_UNUSED)
11273 {
11274   static CUMULATIVE_ARGS zero_cumulative;
11275
11276   *cum = zero_cumulative;
11277   cum->words = 0;
11278   cum->fregno = FP_ARG_MIN_REG;
11279   cum->vregno = ALTIVEC_ARG_MIN_REG;
11280   cum->prototype = (fntype && prototype_p (fntype));
11281   cum->call_cookie = ((DEFAULT_ABI == ABI_V4 && libcall)
11282                       ? CALL_LIBCALL : CALL_NORMAL);
11283   cum->sysv_gregno = GP_ARG_MIN_REG;
11284   cum->stdarg = stdarg_p (fntype);
11285   cum->libcall = libcall;
11286
11287   cum->nargs_prototype = 0;
11288   if (incoming || cum->prototype)
11289     cum->nargs_prototype = n_named_args;
11290
11291   /* Check for a longcall attribute.  */
11292   if ((!fntype && rs6000_default_long_calls)
11293       || (fntype
11294           && lookup_attribute ("longcall", TYPE_ATTRIBUTES (fntype))
11295           && !lookup_attribute ("shortcall", TYPE_ATTRIBUTES (fntype))))
11296     cum->call_cookie |= CALL_LONG;
11297
11298   if (TARGET_DEBUG_ARG)
11299     {
11300       fprintf (stderr, "\ninit_cumulative_args:");
11301       if (fntype)
11302         {
11303           tree ret_type = TREE_TYPE (fntype);
11304           fprintf (stderr, " ret code = %s,",
11305                    get_tree_code_name (TREE_CODE (ret_type)));
11306         }
11307
11308       if (cum->call_cookie & CALL_LONG)
11309         fprintf (stderr, " longcall,");
11310
11311       fprintf (stderr, " proto = %d, nargs = %d\n",
11312                cum->prototype, cum->nargs_prototype);
11313     }
11314
11315 #ifdef HAVE_AS_GNU_ATTRIBUTE
11316   if (TARGET_ELF && (TARGET_64BIT || DEFAULT_ABI == ABI_V4))
11317     {
11318       cum->escapes = call_ABI_of_interest (fndecl);
11319       if (cum->escapes)
11320         {
11321           tree return_type;
11322
11323           if (fntype)
11324             {
11325               return_type = TREE_TYPE (fntype);
11326               return_mode = TYPE_MODE (return_type);
11327             }
11328           else
11329             return_type = lang_hooks.types.type_for_mode (return_mode, 0);
11330
11331           if (return_type != NULL)
11332             {
11333               if (TREE_CODE (return_type) == RECORD_TYPE
11334                   && TYPE_TRANSPARENT_AGGR (return_type))
11335                 {
11336                   return_type = TREE_TYPE (first_field (return_type));
11337                   return_mode = TYPE_MODE (return_type);
11338                 }
11339               if (AGGREGATE_TYPE_P (return_type)
11340                   && ((unsigned HOST_WIDE_INT) int_size_in_bytes (return_type)
11341                       <= 8))
11342                 rs6000_returns_struct = true;
11343             }
11344           if (SCALAR_FLOAT_MODE_P (return_mode))
11345             {
11346               rs6000_passes_float = true;
11347               if ((HAVE_LD_PPC_GNU_ATTR_LONG_DOUBLE || TARGET_64BIT)
11348                   && (FLOAT128_IBM_P (return_mode)
11349                       || FLOAT128_IEEE_P (return_mode)
11350                       || (return_type != NULL
11351                           && (TYPE_MAIN_VARIANT (return_type)
11352                               == long_double_type_node))))
11353                 rs6000_passes_long_double = true;
11354             }
11355           if (ALTIVEC_OR_VSX_VECTOR_MODE (return_mode)
11356               || PAIRED_VECTOR_MODE (return_mode))
11357             rs6000_passes_vector = true;
11358         }
11359     }
11360 #endif
11361
11362   if (fntype
11363       && !TARGET_ALTIVEC
11364       && TARGET_ALTIVEC_ABI
11365       && ALTIVEC_VECTOR_MODE (TYPE_MODE (TREE_TYPE (fntype))))
11366     {
11367       error ("cannot return value in vector register because"
11368              " altivec instructions are disabled, use %qs"
11369              " to enable them", "-maltivec");
11370     }
11371 }
11372 \f
11373 /* The mode the ABI uses for a word.  This is not the same as word_mode
11374    for -m32 -mpowerpc64.  This is used to implement various target hooks.  */
11375
11376 static scalar_int_mode
11377 rs6000_abi_word_mode (void)
11378 {
11379   return TARGET_32BIT ? SImode : DImode;
11380 }
11381
11382 /* Implement the TARGET_OFFLOAD_OPTIONS hook.  */
11383 static char *
11384 rs6000_offload_options (void)
11385 {
11386   if (TARGET_64BIT)
11387     return xstrdup ("-foffload-abi=lp64");
11388   else
11389     return xstrdup ("-foffload-abi=ilp32");
11390 }
11391
11392 /* On rs6000, function arguments are promoted, as are function return
11393    values.  */
11394
11395 static machine_mode
11396 rs6000_promote_function_mode (const_tree type ATTRIBUTE_UNUSED,
11397                               machine_mode mode,
11398                               int *punsignedp ATTRIBUTE_UNUSED,
11399                               const_tree, int)
11400 {
11401   PROMOTE_MODE (mode, *punsignedp, type);
11402
11403   return mode;
11404 }
11405
11406 /* Return true if TYPE must be passed on the stack and not in registers.  */
11407
11408 static bool
11409 rs6000_must_pass_in_stack (machine_mode mode, const_tree type)
11410 {
11411   if (DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2 || TARGET_64BIT)
11412     return must_pass_in_stack_var_size (mode, type);
11413   else
11414     return must_pass_in_stack_var_size_or_pad (mode, type);
11415 }
11416
11417 static inline bool
11418 is_complex_IBM_long_double (machine_mode mode)
11419 {
11420   return mode == ICmode || (mode == TCmode && FLOAT128_IBM_P (TCmode));
11421 }
11422
11423 /* Whether ABI_V4 passes MODE args to a function in floating point
11424    registers.  */
11425
11426 static bool
11427 abi_v4_pass_in_fpr (machine_mode mode)
11428 {
11429   if (!TARGET_HARD_FLOAT)
11430     return false;
11431   if (TARGET_SINGLE_FLOAT && mode == SFmode)
11432     return true;
11433   if (TARGET_DOUBLE_FLOAT && mode == DFmode)
11434     return true;
11435   /* ABI_V4 passes complex IBM long double in 8 gprs.
11436      Stupid, but we can't change the ABI now.  */
11437   if (is_complex_IBM_long_double (mode))
11438     return false;
11439   if (FLOAT128_2REG_P (mode))
11440     return true;
11441   if (DECIMAL_FLOAT_MODE_P (mode))
11442     return true;
11443   return false;
11444 }
11445
11446 /* Implement TARGET_FUNCTION_ARG_PADDING.
11447
11448    For the AIX ABI structs are always stored left shifted in their
11449    argument slot.  */
11450
11451 static pad_direction
11452 rs6000_function_arg_padding (machine_mode mode, const_tree type)
11453 {
11454 #ifndef AGGREGATE_PADDING_FIXED
11455 #define AGGREGATE_PADDING_FIXED 0
11456 #endif
11457 #ifndef AGGREGATES_PAD_UPWARD_ALWAYS
11458 #define AGGREGATES_PAD_UPWARD_ALWAYS 0
11459 #endif
11460
11461   if (!AGGREGATE_PADDING_FIXED)
11462     {
11463       /* GCC used to pass structures of the same size as integer types as
11464          if they were in fact integers, ignoring TARGET_FUNCTION_ARG_PADDING.
11465          i.e. Structures of size 1 or 2 (or 4 when TARGET_64BIT) were
11466          passed padded downward, except that -mstrict-align further
11467          muddied the water in that multi-component structures of 2 and 4
11468          bytes in size were passed padded upward.
11469
11470          The following arranges for best compatibility with previous
11471          versions of gcc, but removes the -mstrict-align dependency.  */
11472       if (BYTES_BIG_ENDIAN)
11473         {
11474           HOST_WIDE_INT size = 0;
11475
11476           if (mode == BLKmode)
11477             {
11478               if (type && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST)
11479                 size = int_size_in_bytes (type);
11480             }
11481           else
11482             size = GET_MODE_SIZE (mode);
11483
11484           if (size == 1 || size == 2 || size == 4)
11485             return PAD_DOWNWARD;
11486         }
11487       return PAD_UPWARD;
11488     }
11489
11490   if (AGGREGATES_PAD_UPWARD_ALWAYS)
11491     {
11492       if (type != 0 && AGGREGATE_TYPE_P (type))
11493         return PAD_UPWARD;
11494     }
11495
11496   /* Fall back to the default.  */
11497   return default_function_arg_padding (mode, type);
11498 }
11499
11500 /* If defined, a C expression that gives the alignment boundary, in bits,
11501    of an argument with the specified mode and type.  If it is not defined,
11502    PARM_BOUNDARY is used for all arguments.
11503
11504    V.4 wants long longs and doubles to be double word aligned.  Just
11505    testing the mode size is a boneheaded way to do this as it means
11506    that other types such as complex int are also double word aligned.
11507    However, we're stuck with this because changing the ABI might break
11508    existing library interfaces.
11509
11510    Quadword align Altivec/VSX vectors.
11511    Quadword align large synthetic vector types.   */
11512
11513 static unsigned int
11514 rs6000_function_arg_boundary (machine_mode mode, const_tree type)
11515 {
11516   machine_mode elt_mode;
11517   int n_elts;
11518
11519   rs6000_discover_homogeneous_aggregate (mode, type, &elt_mode, &n_elts);
11520
11521   if (DEFAULT_ABI == ABI_V4
11522       && (GET_MODE_SIZE (mode) == 8
11523           || (TARGET_HARD_FLOAT
11524               && !is_complex_IBM_long_double (mode)
11525               && FLOAT128_2REG_P (mode))))
11526     return 64;
11527   else if (FLOAT128_VECTOR_P (mode))
11528     return 128;
11529   else if (PAIRED_VECTOR_MODE (mode)
11530            || (type && TREE_CODE (type) == VECTOR_TYPE
11531                && int_size_in_bytes (type) >= 8
11532                && int_size_in_bytes (type) < 16))
11533     return 64;
11534   else if (ALTIVEC_OR_VSX_VECTOR_MODE (elt_mode)
11535            || (type && TREE_CODE (type) == VECTOR_TYPE
11536                && int_size_in_bytes (type) >= 16))
11537     return 128;
11538
11539   /* Aggregate types that need > 8 byte alignment are quadword-aligned
11540      in the parameter area in the ELFv2 ABI, and in the AIX ABI unless
11541      -mcompat-align-parm is used.  */
11542   if (((DEFAULT_ABI == ABI_AIX && !rs6000_compat_align_parm)
11543        || DEFAULT_ABI == ABI_ELFv2)
11544       && type && TYPE_ALIGN (type) > 64)
11545     {
11546       /* "Aggregate" means any AGGREGATE_TYPE except for single-element
11547          or homogeneous float/vector aggregates here.  We already handled
11548          vector aggregates above, but still need to check for float here. */
11549       bool aggregate_p = (AGGREGATE_TYPE_P (type)
11550                           && !SCALAR_FLOAT_MODE_P (elt_mode));
11551
11552       /* We used to check for BLKmode instead of the above aggregate type
11553          check.  Warn when this results in any difference to the ABI.  */
11554       if (aggregate_p != (mode == BLKmode))
11555         {
11556           static bool warned;
11557           if (!warned && warn_psabi)
11558             {
11559               warned = true;
11560               inform (input_location,
11561                       "the ABI of passing aggregates with %d-byte alignment"
11562                       " has changed in GCC 5",
11563                       (int) TYPE_ALIGN (type) / BITS_PER_UNIT);
11564             }
11565         }
11566
11567       if (aggregate_p)
11568         return 128;
11569     }
11570
11571   /* Similar for the Darwin64 ABI.  Note that for historical reasons we
11572      implement the "aggregate type" check as a BLKmode check here; this
11573      means certain aggregate types are in fact not aligned.  */
11574   if (TARGET_MACHO && rs6000_darwin64_abi
11575       && mode == BLKmode
11576       && type && TYPE_ALIGN (type) > 64)
11577     return 128;
11578
11579   return PARM_BOUNDARY;
11580 }
11581
11582 /* The offset in words to the start of the parameter save area.  */
11583
11584 static unsigned int
11585 rs6000_parm_offset (void)
11586 {
11587   return (DEFAULT_ABI == ABI_V4 ? 2
11588           : DEFAULT_ABI == ABI_ELFv2 ? 4
11589           : 6);
11590 }
11591
11592 /* For a function parm of MODE and TYPE, return the starting word in
11593    the parameter area.  NWORDS of the parameter area are already used.  */
11594
11595 static unsigned int
11596 rs6000_parm_start (machine_mode mode, const_tree type,
11597                    unsigned int nwords)
11598 {
11599   unsigned int align;
11600
11601   align = rs6000_function_arg_boundary (mode, type) / PARM_BOUNDARY - 1;
11602   return nwords + (-(rs6000_parm_offset () + nwords) & align);
11603 }
11604
11605 /* Compute the size (in words) of a function argument.  */
11606
11607 static unsigned long
11608 rs6000_arg_size (machine_mode mode, const_tree type)
11609 {
11610   unsigned long size;
11611
11612   if (mode != BLKmode)
11613     size = GET_MODE_SIZE (mode);
11614   else
11615     size = int_size_in_bytes (type);
11616
11617   if (TARGET_32BIT)
11618     return (size + 3) >> 2;
11619   else
11620     return (size + 7) >> 3;
11621 }
11622 \f
11623 /* Use this to flush pending int fields.  */
11624
11625 static void
11626 rs6000_darwin64_record_arg_advance_flush (CUMULATIVE_ARGS *cum,
11627                                           HOST_WIDE_INT bitpos, int final)
11628 {
11629   unsigned int startbit, endbit;
11630   int intregs, intoffset;
11631
11632   /* Handle the situations where a float is taking up the first half
11633      of the GPR, and the other half is empty (typically due to
11634      alignment restrictions). We can detect this by a 8-byte-aligned
11635      int field, or by seeing that this is the final flush for this
11636      argument. Count the word and continue on.  */
11637   if (cum->floats_in_gpr == 1
11638       && (cum->intoffset % 64 == 0
11639           || (cum->intoffset == -1 && final)))
11640     {
11641       cum->words++;
11642       cum->floats_in_gpr = 0;
11643     }
11644
11645   if (cum->intoffset == -1)
11646     return;
11647
11648   intoffset = cum->intoffset;
11649   cum->intoffset = -1;
11650   cum->floats_in_gpr = 0;
11651
11652   if (intoffset % BITS_PER_WORD != 0)
11653     {
11654       unsigned int bits = BITS_PER_WORD - intoffset % BITS_PER_WORD;
11655       if (!int_mode_for_size (bits, 0).exists ())
11656         {
11657           /* We couldn't find an appropriate mode, which happens,
11658              e.g., in packed structs when there are 3 bytes to load.
11659              Back intoffset back to the beginning of the word in this
11660              case.  */
11661           intoffset = ROUND_DOWN (intoffset, BITS_PER_WORD);
11662         }
11663     }
11664
11665   startbit = ROUND_DOWN (intoffset, BITS_PER_WORD);
11666   endbit = ROUND_UP (bitpos, BITS_PER_WORD);
11667   intregs = (endbit - startbit) / BITS_PER_WORD;
11668   cum->words += intregs;
11669   /* words should be unsigned. */
11670   if ((unsigned)cum->words < (endbit/BITS_PER_WORD))
11671     {
11672       int pad = (endbit/BITS_PER_WORD) - cum->words;
11673       cum->words += pad;
11674     }
11675 }
11676
11677 /* The darwin64 ABI calls for us to recurse down through structs,
11678    looking for elements passed in registers.  Unfortunately, we have
11679    to track int register count here also because of misalignments
11680    in powerpc alignment mode.  */
11681
11682 static void
11683 rs6000_darwin64_record_arg_advance_recurse (CUMULATIVE_ARGS *cum,
11684                                             const_tree type,
11685                                             HOST_WIDE_INT startbitpos)
11686 {
11687   tree f;
11688
11689   for (f = TYPE_FIELDS (type); f ; f = DECL_CHAIN (f))
11690     if (TREE_CODE (f) == FIELD_DECL)
11691       {
11692         HOST_WIDE_INT bitpos = startbitpos;
11693         tree ftype = TREE_TYPE (f);
11694         machine_mode mode;
11695         if (ftype == error_mark_node)
11696           continue;
11697         mode = TYPE_MODE (ftype);
11698
11699         if (DECL_SIZE (f) != 0
11700             && tree_fits_uhwi_p (bit_position (f)))
11701           bitpos += int_bit_position (f);
11702
11703         /* ??? FIXME: else assume zero offset.  */
11704
11705         if (TREE_CODE (ftype) == RECORD_TYPE)
11706           rs6000_darwin64_record_arg_advance_recurse (cum, ftype, bitpos);
11707         else if (USE_FP_FOR_ARG_P (cum, mode))
11708           {
11709             unsigned n_fpregs = (GET_MODE_SIZE (mode) + 7) >> 3;
11710             rs6000_darwin64_record_arg_advance_flush (cum, bitpos, 0);
11711             cum->fregno += n_fpregs;
11712             /* Single-precision floats present a special problem for
11713                us, because they are smaller than an 8-byte GPR, and so
11714                the structure-packing rules combined with the standard
11715                varargs behavior mean that we want to pack float/float
11716                and float/int combinations into a single register's
11717                space. This is complicated by the arg advance flushing,
11718                which works on arbitrarily large groups of int-type
11719                fields.  */
11720             if (mode == SFmode)
11721               {
11722                 if (cum->floats_in_gpr == 1)
11723                   {
11724                     /* Two floats in a word; count the word and reset
11725                        the float count.  */
11726                     cum->words++;
11727                     cum->floats_in_gpr = 0;
11728                   }
11729                 else if (bitpos % 64 == 0)
11730                   {
11731                     /* A float at the beginning of an 8-byte word;
11732                        count it and put off adjusting cum->words until
11733                        we see if a arg advance flush is going to do it
11734                        for us.  */
11735                     cum->floats_in_gpr++;
11736                   }
11737                 else
11738                   {
11739                     /* The float is at the end of a word, preceded
11740                        by integer fields, so the arg advance flush
11741                        just above has already set cum->words and
11742                        everything is taken care of.  */
11743                   }
11744               }
11745             else
11746               cum->words += n_fpregs;
11747           }
11748         else if (USE_ALTIVEC_FOR_ARG_P (cum, mode, 1))
11749           {
11750             rs6000_darwin64_record_arg_advance_flush (cum, bitpos, 0);
11751             cum->vregno++;
11752             cum->words += 2;
11753           }
11754         else if (cum->intoffset == -1)
11755           cum->intoffset = bitpos;
11756       }
11757 }
11758
11759 /* Check for an item that needs to be considered specially under the darwin 64
11760    bit ABI.  These are record types where the mode is BLK or the structure is
11761    8 bytes in size.  */
11762 static int
11763 rs6000_darwin64_struct_check_p (machine_mode mode, const_tree type)
11764 {
11765   return rs6000_darwin64_abi
11766          && ((mode == BLKmode 
11767               && TREE_CODE (type) == RECORD_TYPE 
11768               && int_size_in_bytes (type) > 0)
11769           || (type && TREE_CODE (type) == RECORD_TYPE 
11770               && int_size_in_bytes (type) == 8)) ? 1 : 0;
11771 }
11772
11773 /* Update the data in CUM to advance over an argument
11774    of mode MODE and data type TYPE.
11775    (TYPE is null for libcalls where that information may not be available.)
11776
11777    Note that for args passed by reference, function_arg will be called
11778    with MODE and TYPE set to that of the pointer to the arg, not the arg
11779    itself.  */
11780
11781 static void
11782 rs6000_function_arg_advance_1 (CUMULATIVE_ARGS *cum, machine_mode mode,
11783                                const_tree type, bool named, int depth)
11784 {
11785   machine_mode elt_mode;
11786   int n_elts;
11787
11788   rs6000_discover_homogeneous_aggregate (mode, type, &elt_mode, &n_elts);
11789
11790   /* Only tick off an argument if we're not recursing.  */
11791   if (depth == 0)
11792     cum->nargs_prototype--;
11793
11794 #ifdef HAVE_AS_GNU_ATTRIBUTE
11795   if (TARGET_ELF && (TARGET_64BIT || DEFAULT_ABI == ABI_V4)
11796       && cum->escapes)
11797     {
11798       if (SCALAR_FLOAT_MODE_P (mode))
11799         {
11800           rs6000_passes_float = true;
11801           if ((HAVE_LD_PPC_GNU_ATTR_LONG_DOUBLE || TARGET_64BIT)
11802               && (FLOAT128_IBM_P (mode)
11803                   || FLOAT128_IEEE_P (mode)
11804                   || (type != NULL
11805                       && TYPE_MAIN_VARIANT (type) == long_double_type_node)))
11806             rs6000_passes_long_double = true;
11807         }
11808       if ((named && ALTIVEC_OR_VSX_VECTOR_MODE (mode))
11809           || (PAIRED_VECTOR_MODE (mode)
11810               && !cum->stdarg
11811               && cum->sysv_gregno <= GP_ARG_MAX_REG))
11812         rs6000_passes_vector = true;
11813     }
11814 #endif
11815
11816   if (TARGET_ALTIVEC_ABI
11817       && (ALTIVEC_OR_VSX_VECTOR_MODE (elt_mode)
11818           || (type && TREE_CODE (type) == VECTOR_TYPE
11819               && int_size_in_bytes (type) == 16)))
11820     {
11821       bool stack = false;
11822
11823       if (USE_ALTIVEC_FOR_ARG_P (cum, elt_mode, named))
11824         {
11825           cum->vregno += n_elts;
11826
11827           if (!TARGET_ALTIVEC)
11828             error ("cannot pass argument in vector register because"
11829                    " altivec instructions are disabled, use %qs"
11830                    " to enable them", "-maltivec");
11831
11832           /* PowerPC64 Linux and AIX allocate GPRs for a vector argument
11833              even if it is going to be passed in a vector register.
11834              Darwin does the same for variable-argument functions.  */
11835           if (((DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
11836                && TARGET_64BIT)
11837               || (cum->stdarg && DEFAULT_ABI != ABI_V4))
11838             stack = true;
11839         }
11840       else
11841         stack = true;
11842
11843       if (stack)
11844         {
11845           int align;
11846
11847           /* Vector parameters must be 16-byte aligned.  In 32-bit
11848              mode this means we need to take into account the offset
11849              to the parameter save area.  In 64-bit mode, they just
11850              have to start on an even word, since the parameter save
11851              area is 16-byte aligned.  */
11852           if (TARGET_32BIT)
11853             align = -(rs6000_parm_offset () + cum->words) & 3;
11854           else
11855             align = cum->words & 1;
11856           cum->words += align + rs6000_arg_size (mode, type);
11857
11858           if (TARGET_DEBUG_ARG)
11859             {
11860               fprintf (stderr, "function_adv: words = %2d, align=%d, ",
11861                        cum->words, align);
11862               fprintf (stderr, "nargs = %4d, proto = %d, mode = %4s\n",
11863                        cum->nargs_prototype, cum->prototype,
11864                        GET_MODE_NAME (mode));
11865             }
11866         }
11867     }
11868   else if (TARGET_MACHO && rs6000_darwin64_struct_check_p (mode, type))
11869     {
11870       int size = int_size_in_bytes (type);
11871       /* Variable sized types have size == -1 and are
11872          treated as if consisting entirely of ints.
11873          Pad to 16 byte boundary if needed.  */
11874       if (TYPE_ALIGN (type) >= 2 * BITS_PER_WORD
11875           && (cum->words % 2) != 0)
11876         cum->words++;
11877       /* For varargs, we can just go up by the size of the struct. */
11878       if (!named)
11879         cum->words += (size + 7) / 8;
11880       else
11881         {
11882           /* It is tempting to say int register count just goes up by
11883              sizeof(type)/8, but this is wrong in a case such as
11884              { int; double; int; } [powerpc alignment].  We have to
11885              grovel through the fields for these too.  */
11886           cum->intoffset = 0;
11887           cum->floats_in_gpr = 0;
11888           rs6000_darwin64_record_arg_advance_recurse (cum, type, 0);
11889           rs6000_darwin64_record_arg_advance_flush (cum,
11890                                                     size * BITS_PER_UNIT, 1);
11891         }
11892           if (TARGET_DEBUG_ARG)
11893             {
11894               fprintf (stderr, "function_adv: words = %2d, align=%d, size=%d",
11895                        cum->words, TYPE_ALIGN (type), size);
11896               fprintf (stderr, 
11897                    "nargs = %4d, proto = %d, mode = %4s (darwin64 abi)\n",
11898                        cum->nargs_prototype, cum->prototype,
11899                        GET_MODE_NAME (mode));
11900             }
11901     }
11902   else if (DEFAULT_ABI == ABI_V4)
11903     {
11904       if (abi_v4_pass_in_fpr (mode))
11905         {
11906           /* _Decimal128 must use an even/odd register pair.  This assumes
11907              that the register number is odd when fregno is odd.  */
11908           if (mode == TDmode && (cum->fregno % 2) == 1)
11909             cum->fregno++;
11910
11911           if (cum->fregno + (FLOAT128_2REG_P (mode) ? 1 : 0)
11912               <= FP_ARG_V4_MAX_REG)
11913             cum->fregno += (GET_MODE_SIZE (mode) + 7) >> 3;
11914           else
11915             {
11916               cum->fregno = FP_ARG_V4_MAX_REG + 1;
11917               if (mode == DFmode || FLOAT128_IBM_P (mode)
11918                   || mode == DDmode || mode == TDmode)
11919                 cum->words += cum->words & 1;
11920               cum->words += rs6000_arg_size (mode, type);
11921             }
11922         }
11923       else
11924         {
11925           int n_words = rs6000_arg_size (mode, type);
11926           int gregno = cum->sysv_gregno;
11927
11928           /* Long long is put in (r3,r4), (r5,r6), (r7,r8) or (r9,r10).
11929              As does any other 2 word item such as complex int due to a
11930              historical mistake.  */
11931           if (n_words == 2)
11932             gregno += (1 - gregno) & 1;
11933
11934           /* Multi-reg args are not split between registers and stack.  */
11935           if (gregno + n_words - 1 > GP_ARG_MAX_REG)
11936             {
11937               /* Long long is aligned on the stack.  So are other 2 word
11938                  items such as complex int due to a historical mistake.  */
11939               if (n_words == 2)
11940                 cum->words += cum->words & 1;
11941               cum->words += n_words;
11942             }
11943
11944           /* Note: continuing to accumulate gregno past when we've started
11945              spilling to the stack indicates the fact that we've started
11946              spilling to the stack to expand_builtin_saveregs.  */
11947           cum->sysv_gregno = gregno + n_words;
11948         }
11949
11950       if (TARGET_DEBUG_ARG)
11951         {
11952           fprintf (stderr, "function_adv: words = %2d, fregno = %2d, ",
11953                    cum->words, cum->fregno);
11954           fprintf (stderr, "gregno = %2d, nargs = %4d, proto = %d, ",
11955                    cum->sysv_gregno, cum->nargs_prototype, cum->prototype);
11956           fprintf (stderr, "mode = %4s, named = %d\n",
11957                    GET_MODE_NAME (mode), named);
11958         }
11959     }
11960   else
11961     {
11962       int n_words = rs6000_arg_size (mode, type);
11963       int start_words = cum->words;
11964       int align_words = rs6000_parm_start (mode, type, start_words);
11965
11966       cum->words = align_words + n_words;
11967
11968       if (SCALAR_FLOAT_MODE_P (elt_mode) && TARGET_HARD_FLOAT)
11969         {
11970           /* _Decimal128 must be passed in an even/odd float register pair.
11971              This assumes that the register number is odd when fregno is
11972              odd.  */
11973           if (elt_mode == TDmode && (cum->fregno % 2) == 1)
11974             cum->fregno++;
11975           cum->fregno += n_elts * ((GET_MODE_SIZE (elt_mode) + 7) >> 3);
11976         }
11977
11978       if (TARGET_DEBUG_ARG)
11979         {
11980           fprintf (stderr, "function_adv: words = %2d, fregno = %2d, ",
11981                    cum->words, cum->fregno);
11982           fprintf (stderr, "nargs = %4d, proto = %d, mode = %4s, ",
11983                    cum->nargs_prototype, cum->prototype, GET_MODE_NAME (mode));
11984           fprintf (stderr, "named = %d, align = %d, depth = %d\n",
11985                    named, align_words - start_words, depth);
11986         }
11987     }
11988 }
11989
11990 static void
11991 rs6000_function_arg_advance (cumulative_args_t cum, machine_mode mode,
11992                              const_tree type, bool named)
11993 {
11994   rs6000_function_arg_advance_1 (get_cumulative_args (cum), mode, type, named,
11995                                  0);
11996 }
11997
11998 /* A subroutine of rs6000_darwin64_record_arg.  Assign the bits of the
11999    structure between cum->intoffset and bitpos to integer registers.  */
12000
12001 static void
12002 rs6000_darwin64_record_arg_flush (CUMULATIVE_ARGS *cum,
12003                                   HOST_WIDE_INT bitpos, rtx rvec[], int *k)
12004 {
12005   machine_mode mode;
12006   unsigned int regno;
12007   unsigned int startbit, endbit;
12008   int this_regno, intregs, intoffset;
12009   rtx reg;
12010
12011   if (cum->intoffset == -1)
12012     return;
12013
12014   intoffset = cum->intoffset;
12015   cum->intoffset = -1;
12016
12017   /* If this is the trailing part of a word, try to only load that
12018      much into the register.  Otherwise load the whole register.  Note
12019      that in the latter case we may pick up unwanted bits.  It's not a
12020      problem at the moment but may wish to revisit.  */
12021
12022   if (intoffset % BITS_PER_WORD != 0)
12023     {
12024       unsigned int bits = BITS_PER_WORD - intoffset % BITS_PER_WORD;
12025       if (!int_mode_for_size (bits, 0).exists (&mode))
12026         {
12027           /* We couldn't find an appropriate mode, which happens,
12028              e.g., in packed structs when there are 3 bytes to load.
12029              Back intoffset back to the beginning of the word in this
12030              case.  */
12031           intoffset = ROUND_DOWN (intoffset, BITS_PER_WORD);
12032           mode = word_mode;
12033         }
12034     }
12035   else
12036     mode = word_mode;
12037
12038   startbit = ROUND_DOWN (intoffset, BITS_PER_WORD);
12039   endbit = ROUND_UP (bitpos, BITS_PER_WORD);
12040   intregs = (endbit - startbit) / BITS_PER_WORD;
12041   this_regno = cum->words + intoffset / BITS_PER_WORD;
12042
12043   if (intregs > 0 && intregs > GP_ARG_NUM_REG - this_regno)
12044     cum->use_stack = 1;
12045
12046   intregs = MIN (intregs, GP_ARG_NUM_REG - this_regno);
12047   if (intregs <= 0)
12048     return;
12049
12050   intoffset /= BITS_PER_UNIT;
12051   do
12052     {
12053       regno = GP_ARG_MIN_REG + this_regno;
12054       reg = gen_rtx_REG (mode, regno);
12055       rvec[(*k)++] =
12056         gen_rtx_EXPR_LIST (VOIDmode, reg, GEN_INT (intoffset));
12057
12058       this_regno += 1;
12059       intoffset = (intoffset | (UNITS_PER_WORD-1)) + 1;
12060       mode = word_mode;
12061       intregs -= 1;
12062     }
12063   while (intregs > 0);
12064 }
12065
12066 /* Recursive workhorse for the following.  */
12067
12068 static void
12069 rs6000_darwin64_record_arg_recurse (CUMULATIVE_ARGS *cum, const_tree type,
12070                                     HOST_WIDE_INT startbitpos, rtx rvec[],
12071                                     int *k)
12072 {
12073   tree f;
12074
12075   for (f = TYPE_FIELDS (type); f ; f = DECL_CHAIN (f))
12076     if (TREE_CODE (f) == FIELD_DECL)
12077       {
12078         HOST_WIDE_INT bitpos = startbitpos;
12079         tree ftype = TREE_TYPE (f);
12080         machine_mode mode;
12081         if (ftype == error_mark_node)
12082           continue;
12083         mode = TYPE_MODE (ftype);
12084
12085         if (DECL_SIZE (f) != 0
12086             && tree_fits_uhwi_p (bit_position (f)))
12087           bitpos += int_bit_position (f);
12088
12089         /* ??? FIXME: else assume zero offset.  */
12090
12091         if (TREE_CODE (ftype) == RECORD_TYPE)
12092           rs6000_darwin64_record_arg_recurse (cum, ftype, bitpos, rvec, k);
12093         else if (cum->named && USE_FP_FOR_ARG_P (cum, mode))
12094           {
12095             unsigned n_fpreg = (GET_MODE_SIZE (mode) + 7) >> 3;
12096 #if 0
12097             switch (mode)
12098               {
12099               case E_SCmode: mode = SFmode; break;
12100               case E_DCmode: mode = DFmode; break;
12101               case E_TCmode: mode = TFmode; break;
12102               default: break;
12103               }
12104 #endif
12105             rs6000_darwin64_record_arg_flush (cum, bitpos, rvec, k);
12106             if (cum->fregno + n_fpreg > FP_ARG_MAX_REG + 1)
12107               {
12108                 gcc_assert (cum->fregno == FP_ARG_MAX_REG
12109                             && (mode == TFmode || mode == TDmode));
12110                 /* Long double or _Decimal128 split over regs and memory.  */
12111                 mode = DECIMAL_FLOAT_MODE_P (mode) ? DDmode : DFmode;
12112                 cum->use_stack=1;
12113               }
12114             rvec[(*k)++]
12115               = gen_rtx_EXPR_LIST (VOIDmode,
12116                                    gen_rtx_REG (mode, cum->fregno++),
12117                                    GEN_INT (bitpos / BITS_PER_UNIT));
12118             if (FLOAT128_2REG_P (mode))
12119               cum->fregno++;
12120           }
12121         else if (cum->named && USE_ALTIVEC_FOR_ARG_P (cum, mode, 1))
12122           {
12123             rs6000_darwin64_record_arg_flush (cum, bitpos, rvec, k);
12124             rvec[(*k)++]
12125               = gen_rtx_EXPR_LIST (VOIDmode,
12126                                    gen_rtx_REG (mode, cum->vregno++),
12127                                    GEN_INT (bitpos / BITS_PER_UNIT));
12128           }
12129         else if (cum->intoffset == -1)
12130           cum->intoffset = bitpos;
12131       }
12132 }
12133
12134 /* For the darwin64 ABI, we want to construct a PARALLEL consisting of
12135    the register(s) to be used for each field and subfield of a struct
12136    being passed by value, along with the offset of where the
12137    register's value may be found in the block.  FP fields go in FP
12138    register, vector fields go in vector registers, and everything
12139    else goes in int registers, packed as in memory.
12140
12141    This code is also used for function return values.  RETVAL indicates
12142    whether this is the case.
12143
12144    Much of this is taken from the SPARC V9 port, which has a similar
12145    calling convention.  */
12146
12147 static rtx
12148 rs6000_darwin64_record_arg (CUMULATIVE_ARGS *orig_cum, const_tree type,
12149                             bool named, bool retval)
12150 {
12151   rtx rvec[FIRST_PSEUDO_REGISTER];
12152   int k = 1, kbase = 1;
12153   HOST_WIDE_INT typesize = int_size_in_bytes (type);
12154   /* This is a copy; modifications are not visible to our caller.  */
12155   CUMULATIVE_ARGS copy_cum = *orig_cum;
12156   CUMULATIVE_ARGS *cum = &copy_cum;
12157
12158   /* Pad to 16 byte boundary if needed.  */
12159   if (!retval && TYPE_ALIGN (type) >= 2 * BITS_PER_WORD
12160       && (cum->words % 2) != 0)
12161     cum->words++;
12162
12163   cum->intoffset = 0;
12164   cum->use_stack = 0;
12165   cum->named = named;
12166
12167   /* Put entries into rvec[] for individual FP and vector fields, and
12168      for the chunks of memory that go in int regs.  Note we start at
12169      element 1; 0 is reserved for an indication of using memory, and
12170      may or may not be filled in below. */
12171   rs6000_darwin64_record_arg_recurse (cum, type, /* startbit pos= */ 0, rvec, &k);
12172   rs6000_darwin64_record_arg_flush (cum, typesize * BITS_PER_UNIT, rvec, &k);
12173
12174   /* If any part of the struct went on the stack put all of it there.
12175      This hack is because the generic code for
12176      FUNCTION_ARG_PARTIAL_NREGS cannot handle cases where the register
12177      parts of the struct are not at the beginning.  */
12178   if (cum->use_stack)
12179     {
12180       if (retval)
12181         return NULL_RTX;    /* doesn't go in registers at all */
12182       kbase = 0;
12183       rvec[0] = gen_rtx_EXPR_LIST (VOIDmode, NULL_RTX, const0_rtx);
12184     }
12185   if (k > 1 || cum->use_stack)
12186     return gen_rtx_PARALLEL (BLKmode, gen_rtvec_v (k - kbase, &rvec[kbase]));
12187   else
12188     return NULL_RTX;
12189 }
12190
12191 /* Determine where to place an argument in 64-bit mode with 32-bit ABI.  */
12192
12193 static rtx
12194 rs6000_mixed_function_arg (machine_mode mode, const_tree type,
12195                            int align_words)
12196 {
12197   int n_units;
12198   int i, k;
12199   rtx rvec[GP_ARG_NUM_REG + 1];
12200
12201   if (align_words >= GP_ARG_NUM_REG)
12202     return NULL_RTX;
12203
12204   n_units = rs6000_arg_size (mode, type);
12205
12206   /* Optimize the simple case where the arg fits in one gpr, except in
12207      the case of BLKmode due to assign_parms assuming that registers are
12208      BITS_PER_WORD wide.  */
12209   if (n_units == 0
12210       || (n_units == 1 && mode != BLKmode))
12211     return gen_rtx_REG (mode, GP_ARG_MIN_REG + align_words);
12212
12213   k = 0;
12214   if (align_words + n_units > GP_ARG_NUM_REG)
12215     /* Not all of the arg fits in gprs.  Say that it goes in memory too,
12216        using a magic NULL_RTX component.
12217        This is not strictly correct.  Only some of the arg belongs in
12218        memory, not all of it.  However, the normal scheme using
12219        function_arg_partial_nregs can result in unusual subregs, eg.
12220        (subreg:SI (reg:DF) 4), which are not handled well.  The code to
12221        store the whole arg to memory is often more efficient than code
12222        to store pieces, and we know that space is available in the right
12223        place for the whole arg.  */
12224     rvec[k++] = gen_rtx_EXPR_LIST (VOIDmode, NULL_RTX, const0_rtx);
12225
12226   i = 0;
12227   do
12228     {
12229       rtx r = gen_rtx_REG (SImode, GP_ARG_MIN_REG + align_words);
12230       rtx off = GEN_INT (i++ * 4);
12231       rvec[k++] = gen_rtx_EXPR_LIST (VOIDmode, r, off);
12232     }
12233   while (++align_words < GP_ARG_NUM_REG && --n_units != 0);
12234
12235   return gen_rtx_PARALLEL (mode, gen_rtvec_v (k, rvec));
12236 }
12237
12238 /* We have an argument of MODE and TYPE that goes into FPRs or VRs,
12239    but must also be copied into the parameter save area starting at
12240    offset ALIGN_WORDS.  Fill in RVEC with the elements corresponding
12241    to the GPRs and/or memory.  Return the number of elements used.  */
12242
12243 static int
12244 rs6000_psave_function_arg (machine_mode mode, const_tree type,
12245                            int align_words, rtx *rvec)
12246 {
12247   int k = 0;
12248
12249   if (align_words < GP_ARG_NUM_REG)
12250     {
12251       int n_words = rs6000_arg_size (mode, type);
12252
12253       if (align_words + n_words > GP_ARG_NUM_REG
12254           || mode == BLKmode
12255           || (TARGET_32BIT && TARGET_POWERPC64))
12256         {
12257           /* If this is partially on the stack, then we only
12258              include the portion actually in registers here.  */
12259           machine_mode rmode = TARGET_32BIT ? SImode : DImode;
12260           int i = 0;
12261
12262           if (align_words + n_words > GP_ARG_NUM_REG)
12263             {
12264               /* Not all of the arg fits in gprs.  Say that it goes in memory
12265                  too, using a magic NULL_RTX component.  Also see comment in
12266                  rs6000_mixed_function_arg for why the normal
12267                  function_arg_partial_nregs scheme doesn't work in this case. */
12268               rvec[k++] = gen_rtx_EXPR_LIST (VOIDmode, NULL_RTX, const0_rtx);
12269             }
12270
12271           do
12272             {
12273               rtx r = gen_rtx_REG (rmode, GP_ARG_MIN_REG + align_words);
12274               rtx off = GEN_INT (i++ * GET_MODE_SIZE (rmode));
12275               rvec[k++] = gen_rtx_EXPR_LIST (VOIDmode, r, off);
12276             }
12277           while (++align_words < GP_ARG_NUM_REG && --n_words != 0);
12278         }
12279       else
12280         {
12281           /* The whole arg fits in gprs.  */
12282           rtx r = gen_rtx_REG (mode, GP_ARG_MIN_REG + align_words);
12283           rvec[k++] = gen_rtx_EXPR_LIST (VOIDmode, r, const0_rtx);
12284         }
12285     }
12286   else
12287     {
12288       /* It's entirely in memory.  */
12289       rvec[k++] = gen_rtx_EXPR_LIST (VOIDmode, NULL_RTX, const0_rtx);
12290     }
12291
12292   return k;
12293 }
12294
12295 /* RVEC is a vector of K components of an argument of mode MODE.
12296    Construct the final function_arg return value from it.  */
12297
12298 static rtx
12299 rs6000_finish_function_arg (machine_mode mode, rtx *rvec, int k)
12300 {
12301   gcc_assert (k >= 1);
12302
12303   /* Avoid returning a PARALLEL in the trivial cases.  */
12304   if (k == 1)
12305     {
12306       if (XEXP (rvec[0], 0) == NULL_RTX)
12307         return NULL_RTX;
12308
12309       if (GET_MODE (XEXP (rvec[0], 0)) == mode)
12310         return XEXP (rvec[0], 0);
12311     }
12312
12313   return gen_rtx_PARALLEL (mode, gen_rtvec_v (k, rvec));
12314 }
12315
12316 /* Determine where to put an argument to a function.
12317    Value is zero to push the argument on the stack,
12318    or a hard register in which to store the argument.
12319
12320    MODE is the argument's machine mode.
12321    TYPE is the data type of the argument (as a tree).
12322     This is null for libcalls where that information may
12323     not be available.
12324    CUM is a variable of type CUMULATIVE_ARGS which gives info about
12325     the preceding args and about the function being called.  It is
12326     not modified in this routine.
12327    NAMED is nonzero if this argument is a named parameter
12328     (otherwise it is an extra parameter matching an ellipsis).
12329
12330    On RS/6000 the first eight words of non-FP are normally in registers
12331    and the rest are pushed.  Under AIX, the first 13 FP args are in registers.
12332    Under V.4, the first 8 FP args are in registers.
12333
12334    If this is floating-point and no prototype is specified, we use
12335    both an FP and integer register (or possibly FP reg and stack).  Library
12336    functions (when CALL_LIBCALL is set) always have the proper types for args,
12337    so we can pass the FP value just in one register.  emit_library_function
12338    doesn't support PARALLEL anyway.
12339
12340    Note that for args passed by reference, function_arg will be called
12341    with MODE and TYPE set to that of the pointer to the arg, not the arg
12342    itself.  */
12343
12344 static rtx
12345 rs6000_function_arg (cumulative_args_t cum_v, machine_mode mode,
12346                      const_tree type, bool named)
12347 {
12348   CUMULATIVE_ARGS *cum = get_cumulative_args (cum_v);
12349   enum rs6000_abi abi = DEFAULT_ABI;
12350   machine_mode elt_mode;
12351   int n_elts;
12352
12353   /* Return a marker to indicate whether CR1 needs to set or clear the
12354      bit that V.4 uses to say fp args were passed in registers.
12355      Assume that we don't need the marker for software floating point,
12356      or compiler generated library calls.  */
12357   if (mode == VOIDmode)
12358     {
12359       if (abi == ABI_V4
12360           && (cum->call_cookie & CALL_LIBCALL) == 0
12361           && (cum->stdarg
12362               || (cum->nargs_prototype < 0
12363                   && (cum->prototype || TARGET_NO_PROTOTYPE)))
12364           && TARGET_HARD_FLOAT)
12365         return GEN_INT (cum->call_cookie
12366                         | ((cum->fregno == FP_ARG_MIN_REG)
12367                            ? CALL_V4_SET_FP_ARGS
12368                            : CALL_V4_CLEAR_FP_ARGS));
12369
12370       return GEN_INT (cum->call_cookie & ~CALL_LIBCALL);
12371     }
12372
12373   rs6000_discover_homogeneous_aggregate (mode, type, &elt_mode, &n_elts);
12374
12375   if (TARGET_MACHO && rs6000_darwin64_struct_check_p (mode, type))
12376     {
12377       rtx rslt = rs6000_darwin64_record_arg (cum, type, named, /*retval= */false);
12378       if (rslt != NULL_RTX)
12379         return rslt;
12380       /* Else fall through to usual handling.  */
12381     }
12382
12383   if (USE_ALTIVEC_FOR_ARG_P (cum, elt_mode, named))
12384     {
12385       rtx rvec[GP_ARG_NUM_REG + AGGR_ARG_NUM_REG + 1];
12386       rtx r, off;
12387       int i, k = 0;
12388
12389       /* Do we also need to pass this argument in the parameter save area?
12390          Library support functions for IEEE 128-bit are assumed to not need the
12391          value passed both in GPRs and in vector registers.  */
12392       if (TARGET_64BIT && !cum->prototype
12393           && (!cum->libcall || !FLOAT128_VECTOR_P (elt_mode)))
12394         {
12395           int align_words = ROUND_UP (cum->words, 2);
12396           k = rs6000_psave_function_arg (mode, type, align_words, rvec);
12397         }
12398
12399       /* Describe where this argument goes in the vector registers.  */
12400       for (i = 0; i < n_elts && cum->vregno + i <= ALTIVEC_ARG_MAX_REG; i++)
12401         {
12402           r = gen_rtx_REG (elt_mode, cum->vregno + i);
12403           off = GEN_INT (i * GET_MODE_SIZE (elt_mode));
12404           rvec[k++] =  gen_rtx_EXPR_LIST (VOIDmode, r, off);
12405         }
12406
12407       return rs6000_finish_function_arg (mode, rvec, k);
12408     }
12409   else if (TARGET_ALTIVEC_ABI
12410            && (ALTIVEC_OR_VSX_VECTOR_MODE (mode)
12411                || (type && TREE_CODE (type) == VECTOR_TYPE
12412                    && int_size_in_bytes (type) == 16)))
12413     {
12414       if (named || abi == ABI_V4)
12415         return NULL_RTX;
12416       else
12417         {
12418           /* Vector parameters to varargs functions under AIX or Darwin
12419              get passed in memory and possibly also in GPRs.  */
12420           int align, align_words, n_words;
12421           machine_mode part_mode;
12422
12423           /* Vector parameters must be 16-byte aligned.  In 32-bit
12424              mode this means we need to take into account the offset
12425              to the parameter save area.  In 64-bit mode, they just
12426              have to start on an even word, since the parameter save
12427              area is 16-byte aligned.  */
12428           if (TARGET_32BIT)
12429             align = -(rs6000_parm_offset () + cum->words) & 3;
12430           else
12431             align = cum->words & 1;
12432           align_words = cum->words + align;
12433
12434           /* Out of registers?  Memory, then.  */
12435           if (align_words >= GP_ARG_NUM_REG)
12436             return NULL_RTX;
12437
12438           if (TARGET_32BIT && TARGET_POWERPC64)
12439             return rs6000_mixed_function_arg (mode, type, align_words);
12440
12441           /* The vector value goes in GPRs.  Only the part of the
12442              value in GPRs is reported here.  */
12443           part_mode = mode;
12444           n_words = rs6000_arg_size (mode, type);
12445           if (align_words + n_words > GP_ARG_NUM_REG)
12446             /* Fortunately, there are only two possibilities, the value
12447                is either wholly in GPRs or half in GPRs and half not.  */
12448             part_mode = DImode;
12449
12450           return gen_rtx_REG (part_mode, GP_ARG_MIN_REG + align_words);
12451         }
12452     }
12453
12454   else if (abi == ABI_V4)
12455     {
12456       if (abi_v4_pass_in_fpr (mode))
12457         {
12458           /* _Decimal128 must use an even/odd register pair.  This assumes
12459              that the register number is odd when fregno is odd.  */
12460           if (mode == TDmode && (cum->fregno % 2) == 1)
12461             cum->fregno++;
12462
12463           if (cum->fregno + (FLOAT128_2REG_P (mode) ? 1 : 0)
12464               <= FP_ARG_V4_MAX_REG)
12465             return gen_rtx_REG (mode, cum->fregno);
12466           else
12467             return NULL_RTX;
12468         }
12469       else
12470         {
12471           int n_words = rs6000_arg_size (mode, type);
12472           int gregno = cum->sysv_gregno;
12473
12474           /* Long long is put in (r3,r4), (r5,r6), (r7,r8) or (r9,r10).
12475              As does any other 2 word item such as complex int due to a
12476              historical mistake.  */
12477           if (n_words == 2)
12478             gregno += (1 - gregno) & 1;
12479
12480           /* Multi-reg args are not split between registers and stack.  */
12481           if (gregno + n_words - 1 > GP_ARG_MAX_REG)
12482             return NULL_RTX;
12483
12484           if (TARGET_32BIT && TARGET_POWERPC64)
12485             return rs6000_mixed_function_arg (mode, type,
12486                                               gregno - GP_ARG_MIN_REG);
12487           return gen_rtx_REG (mode, gregno);
12488         }
12489     }
12490   else
12491     {
12492       int align_words = rs6000_parm_start (mode, type, cum->words);
12493
12494       /* _Decimal128 must be passed in an even/odd float register pair.
12495          This assumes that the register number is odd when fregno is odd.  */
12496       if (elt_mode == TDmode && (cum->fregno % 2) == 1)
12497         cum->fregno++;
12498
12499       if (USE_FP_FOR_ARG_P (cum, elt_mode))
12500         {
12501           rtx rvec[GP_ARG_NUM_REG + AGGR_ARG_NUM_REG + 1];
12502           rtx r, off;
12503           int i, k = 0;
12504           unsigned long n_fpreg = (GET_MODE_SIZE (elt_mode) + 7) >> 3;
12505           int fpr_words;
12506
12507           /* Do we also need to pass this argument in the parameter
12508              save area?  */
12509           if (type && (cum->nargs_prototype <= 0
12510                        || ((DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
12511                            && TARGET_XL_COMPAT
12512                            && align_words >= GP_ARG_NUM_REG)))
12513             k = rs6000_psave_function_arg (mode, type, align_words, rvec);
12514
12515           /* Describe where this argument goes in the fprs.  */
12516           for (i = 0; i < n_elts
12517                       && cum->fregno + i * n_fpreg <= FP_ARG_MAX_REG; i++)
12518             {
12519               /* Check if the argument is split over registers and memory.
12520                  This can only ever happen for long double or _Decimal128;
12521                  complex types are handled via split_complex_arg.  */
12522               machine_mode fmode = elt_mode;
12523               if (cum->fregno + (i + 1) * n_fpreg > FP_ARG_MAX_REG + 1)
12524                 {
12525                   gcc_assert (FLOAT128_2REG_P (fmode));
12526                   fmode = DECIMAL_FLOAT_MODE_P (fmode) ? DDmode : DFmode;
12527                 }
12528
12529               r = gen_rtx_REG (fmode, cum->fregno + i * n_fpreg);
12530               off = GEN_INT (i * GET_MODE_SIZE (elt_mode));
12531               rvec[k++] = gen_rtx_EXPR_LIST (VOIDmode, r, off);
12532             }
12533
12534           /* If there were not enough FPRs to hold the argument, the rest
12535              usually goes into memory.  However, if the current position
12536              is still within the register parameter area, a portion may
12537              actually have to go into GPRs.
12538
12539              Note that it may happen that the portion of the argument
12540              passed in the first "half" of the first GPR was already
12541              passed in the last FPR as well.
12542
12543              For unnamed arguments, we already set up GPRs to cover the
12544              whole argument in rs6000_psave_function_arg, so there is
12545              nothing further to do at this point.  */
12546           fpr_words = (i * GET_MODE_SIZE (elt_mode)) / (TARGET_32BIT ? 4 : 8);
12547           if (i < n_elts && align_words + fpr_words < GP_ARG_NUM_REG
12548               && cum->nargs_prototype > 0)
12549             {
12550               static bool warned;
12551
12552               machine_mode rmode = TARGET_32BIT ? SImode : DImode;
12553               int n_words = rs6000_arg_size (mode, type);
12554
12555               align_words += fpr_words;
12556               n_words -= fpr_words;
12557
12558               do
12559                 {
12560                   r = gen_rtx_REG (rmode, GP_ARG_MIN_REG + align_words);
12561                   off = GEN_INT (fpr_words++ * GET_MODE_SIZE (rmode));
12562                   rvec[k++] = gen_rtx_EXPR_LIST (VOIDmode, r, off);
12563                 }
12564               while (++align_words < GP_ARG_NUM_REG && --n_words != 0);
12565
12566               if (!warned && warn_psabi)
12567                 {
12568                   warned = true;
12569                   inform (input_location,
12570                           "the ABI of passing homogeneous float aggregates"
12571                           " has changed in GCC 5");
12572                 }
12573             }
12574
12575           return rs6000_finish_function_arg (mode, rvec, k);
12576         }
12577       else if (align_words < GP_ARG_NUM_REG)
12578         {
12579           if (TARGET_32BIT && TARGET_POWERPC64)
12580             return rs6000_mixed_function_arg (mode, type, align_words);
12581
12582           return gen_rtx_REG (mode, GP_ARG_MIN_REG + align_words);
12583         }
12584       else
12585         return NULL_RTX;
12586     }
12587 }
12588 \f
12589 /* For an arg passed partly in registers and partly in memory, this is
12590    the number of bytes passed in registers.  For args passed entirely in
12591    registers or entirely in memory, zero.  When an arg is described by a
12592    PARALLEL, perhaps using more than one register type, this function
12593    returns the number of bytes used by the first element of the PARALLEL.  */
12594
12595 static int
12596 rs6000_arg_partial_bytes (cumulative_args_t cum_v, machine_mode mode,
12597                           tree type, bool named)
12598 {
12599   CUMULATIVE_ARGS *cum = get_cumulative_args (cum_v);
12600   bool passed_in_gprs = true;
12601   int ret = 0;
12602   int align_words;
12603   machine_mode elt_mode;
12604   int n_elts;
12605
12606   rs6000_discover_homogeneous_aggregate (mode, type, &elt_mode, &n_elts);
12607
12608   if (DEFAULT_ABI == ABI_V4)
12609     return 0;
12610
12611   if (USE_ALTIVEC_FOR_ARG_P (cum, elt_mode, named))
12612     {
12613       /* If we are passing this arg in the fixed parameter save area (gprs or
12614          memory) as well as VRs, we do not use the partial bytes mechanism;
12615          instead, rs6000_function_arg will return a PARALLEL including a memory
12616          element as necessary.  Library support functions for IEEE 128-bit are
12617          assumed to not need the value passed both in GPRs and in vector
12618          registers.  */
12619       if (TARGET_64BIT && !cum->prototype
12620           && (!cum->libcall || !FLOAT128_VECTOR_P (elt_mode)))
12621         return 0;
12622
12623       /* Otherwise, we pass in VRs only.  Check for partial copies.  */
12624       passed_in_gprs = false;
12625       if (cum->vregno + n_elts > ALTIVEC_ARG_MAX_REG + 1)
12626         ret = (ALTIVEC_ARG_MAX_REG + 1 - cum->vregno) * 16;
12627     }
12628
12629   /* In this complicated case we just disable the partial_nregs code.  */
12630   if (TARGET_MACHO && rs6000_darwin64_struct_check_p (mode, type))
12631     return 0;
12632
12633   align_words = rs6000_parm_start (mode, type, cum->words);
12634
12635   if (USE_FP_FOR_ARG_P (cum, elt_mode))
12636     {
12637       unsigned long n_fpreg = (GET_MODE_SIZE (elt_mode) + 7) >> 3;
12638
12639       /* If we are passing this arg in the fixed parameter save area
12640          (gprs or memory) as well as FPRs, we do not use the partial
12641          bytes mechanism; instead, rs6000_function_arg will return a
12642          PARALLEL including a memory element as necessary.  */
12643       if (type
12644           && (cum->nargs_prototype <= 0
12645               || ((DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
12646                   && TARGET_XL_COMPAT
12647                   && align_words >= GP_ARG_NUM_REG)))
12648         return 0;
12649
12650       /* Otherwise, we pass in FPRs only.  Check for partial copies.  */
12651       passed_in_gprs = false;
12652       if (cum->fregno + n_elts * n_fpreg > FP_ARG_MAX_REG + 1)
12653         {
12654           /* Compute number of bytes / words passed in FPRs.  If there
12655              is still space available in the register parameter area
12656              *after* that amount, a part of the argument will be passed
12657              in GPRs.  In that case, the total amount passed in any
12658              registers is equal to the amount that would have been passed
12659              in GPRs if everything were passed there, so we fall back to
12660              the GPR code below to compute the appropriate value.  */
12661           int fpr = ((FP_ARG_MAX_REG + 1 - cum->fregno)
12662                      * MIN (8, GET_MODE_SIZE (elt_mode)));
12663           int fpr_words = fpr / (TARGET_32BIT ? 4 : 8);
12664
12665           if (align_words + fpr_words < GP_ARG_NUM_REG)
12666             passed_in_gprs = true;
12667           else
12668             ret = fpr;
12669         }
12670     }
12671
12672   if (passed_in_gprs
12673       && align_words < GP_ARG_NUM_REG
12674       && GP_ARG_NUM_REG < align_words + rs6000_arg_size (mode, type))
12675     ret = (GP_ARG_NUM_REG - align_words) * (TARGET_32BIT ? 4 : 8);
12676
12677   if (ret != 0 && TARGET_DEBUG_ARG)
12678     fprintf (stderr, "rs6000_arg_partial_bytes: %d\n", ret);
12679
12680   return ret;
12681 }
12682 \f
12683 /* A C expression that indicates when an argument must be passed by
12684    reference.  If nonzero for an argument, a copy of that argument is
12685    made in memory and a pointer to the argument is passed instead of
12686    the argument itself.  The pointer is passed in whatever way is
12687    appropriate for passing a pointer to that type.
12688
12689    Under V.4, aggregates and long double are passed by reference.
12690
12691    As an extension to all 32-bit ABIs, AltiVec vectors are passed by
12692    reference unless the AltiVec vector extension ABI is in force.
12693
12694    As an extension to all ABIs, variable sized types are passed by
12695    reference.  */
12696
12697 static bool
12698 rs6000_pass_by_reference (cumulative_args_t cum ATTRIBUTE_UNUSED,
12699                           machine_mode mode, const_tree type,
12700                           bool named ATTRIBUTE_UNUSED)
12701 {
12702   if (!type)
12703     return 0;
12704
12705   if (DEFAULT_ABI == ABI_V4 && TARGET_IEEEQUAD
12706       && FLOAT128_IEEE_P (TYPE_MODE (type)))
12707     {
12708       if (TARGET_DEBUG_ARG)
12709         fprintf (stderr, "function_arg_pass_by_reference: V4 IEEE 128-bit\n");
12710       return 1;
12711     }
12712
12713   if (DEFAULT_ABI == ABI_V4 && AGGREGATE_TYPE_P (type))
12714     {
12715       if (TARGET_DEBUG_ARG)
12716         fprintf (stderr, "function_arg_pass_by_reference: V4 aggregate\n");
12717       return 1;
12718     }
12719
12720   if (int_size_in_bytes (type) < 0)
12721     {
12722       if (TARGET_DEBUG_ARG)
12723         fprintf (stderr, "function_arg_pass_by_reference: variable size\n");
12724       return 1;
12725     }
12726
12727   /* Allow -maltivec -mabi=no-altivec without warning.  Altivec vector
12728      modes only exist for GCC vector types if -maltivec.  */
12729   if (TARGET_32BIT && !TARGET_ALTIVEC_ABI && ALTIVEC_VECTOR_MODE (mode))
12730     {
12731       if (TARGET_DEBUG_ARG)
12732         fprintf (stderr, "function_arg_pass_by_reference: AltiVec\n");
12733       return 1;
12734     }
12735
12736   /* Pass synthetic vectors in memory.  */
12737   if (TREE_CODE (type) == VECTOR_TYPE
12738       && int_size_in_bytes (type) > (TARGET_ALTIVEC_ABI ? 16 : 8))
12739     {
12740       static bool warned_for_pass_big_vectors = false;
12741       if (TARGET_DEBUG_ARG)
12742         fprintf (stderr, "function_arg_pass_by_reference: synthetic vector\n");
12743       if (!warned_for_pass_big_vectors)
12744         {
12745           warning (OPT_Wpsabi, "GCC vector passed by reference: "
12746                    "non-standard ABI extension with no compatibility "
12747                    "guarantee");
12748           warned_for_pass_big_vectors = true;
12749         }
12750       return 1;
12751     }
12752
12753   return 0;
12754 }
12755
12756 /* Process parameter of type TYPE after ARGS_SO_FAR parameters were
12757    already processes.  Return true if the parameter must be passed
12758    (fully or partially) on the stack.  */
12759
12760 static bool
12761 rs6000_parm_needs_stack (cumulative_args_t args_so_far, tree type)
12762 {
12763   machine_mode mode;
12764   int unsignedp;
12765   rtx entry_parm;
12766
12767   /* Catch errors.  */
12768   if (type == NULL || type == error_mark_node)
12769     return true;
12770
12771   /* Handle types with no storage requirement.  */
12772   if (TYPE_MODE (type) == VOIDmode)
12773     return false;
12774
12775   /* Handle complex types.  */
12776   if (TREE_CODE (type) == COMPLEX_TYPE)
12777     return (rs6000_parm_needs_stack (args_so_far, TREE_TYPE (type))
12778             || rs6000_parm_needs_stack (args_so_far, TREE_TYPE (type)));
12779
12780   /* Handle transparent aggregates.  */
12781   if ((TREE_CODE (type) == UNION_TYPE || TREE_CODE (type) == RECORD_TYPE)
12782       && TYPE_TRANSPARENT_AGGR (type))
12783     type = TREE_TYPE (first_field (type));
12784
12785   /* See if this arg was passed by invisible reference.  */
12786   if (pass_by_reference (get_cumulative_args (args_so_far),
12787                          TYPE_MODE (type), type, true))
12788     type = build_pointer_type (type);
12789
12790   /* Find mode as it is passed by the ABI.  */
12791   unsignedp = TYPE_UNSIGNED (type);
12792   mode = promote_mode (type, TYPE_MODE (type), &unsignedp);
12793
12794   /* If we must pass in stack, we need a stack.  */
12795   if (rs6000_must_pass_in_stack (mode, type))
12796     return true;
12797
12798   /* If there is no incoming register, we need a stack.  */
12799   entry_parm = rs6000_function_arg (args_so_far, mode, type, true);
12800   if (entry_parm == NULL)
12801     return true;
12802
12803   /* Likewise if we need to pass both in registers and on the stack.  */
12804   if (GET_CODE (entry_parm) == PARALLEL
12805       && XEXP (XVECEXP (entry_parm, 0, 0), 0) == NULL_RTX)
12806     return true;
12807
12808   /* Also true if we're partially in registers and partially not.  */
12809   if (rs6000_arg_partial_bytes (args_so_far, mode, type, true) != 0)
12810     return true;
12811
12812   /* Update info on where next arg arrives in registers.  */
12813   rs6000_function_arg_advance (args_so_far, mode, type, true);
12814   return false;
12815 }
12816
12817 /* Return true if FUN has no prototype, has a variable argument
12818    list, or passes any parameter in memory.  */
12819
12820 static bool
12821 rs6000_function_parms_need_stack (tree fun, bool incoming)
12822 {
12823   tree fntype, result;
12824   CUMULATIVE_ARGS args_so_far_v;
12825   cumulative_args_t args_so_far;
12826
12827   if (!fun)
12828     /* Must be a libcall, all of which only use reg parms.  */
12829     return false;
12830
12831   fntype = fun;
12832   if (!TYPE_P (fun))
12833     fntype = TREE_TYPE (fun);
12834
12835   /* Varargs functions need the parameter save area.  */
12836   if ((!incoming && !prototype_p (fntype)) || stdarg_p (fntype))
12837     return true;
12838
12839   INIT_CUMULATIVE_INCOMING_ARGS (args_so_far_v, fntype, NULL_RTX);
12840   args_so_far = pack_cumulative_args (&args_so_far_v);
12841
12842   /* When incoming, we will have been passed the function decl.
12843      It is necessary to use the decl to handle K&R style functions,
12844      where TYPE_ARG_TYPES may not be available.  */
12845   if (incoming)
12846     {
12847       gcc_assert (DECL_P (fun));
12848       result = DECL_RESULT (fun);
12849     }
12850   else
12851     result = TREE_TYPE (fntype);
12852
12853   if (result && aggregate_value_p (result, fntype))
12854     {
12855       if (!TYPE_P (result))
12856         result = TREE_TYPE (result);
12857       result = build_pointer_type (result);
12858       rs6000_parm_needs_stack (args_so_far, result);
12859     }
12860
12861   if (incoming)
12862     {
12863       tree parm;
12864
12865       for (parm = DECL_ARGUMENTS (fun);
12866            parm && parm != void_list_node;
12867            parm = TREE_CHAIN (parm))
12868         if (rs6000_parm_needs_stack (args_so_far, TREE_TYPE (parm)))
12869           return true;
12870     }
12871   else
12872     {
12873       function_args_iterator args_iter;
12874       tree arg_type;
12875
12876       FOREACH_FUNCTION_ARGS (fntype, arg_type, args_iter)
12877         if (rs6000_parm_needs_stack (args_so_far, arg_type))
12878           return true;
12879     }
12880
12881   return false;
12882 }
12883
12884 /* Return the size of the REG_PARM_STACK_SPACE are for FUN.  This is
12885    usually a constant depending on the ABI.  However, in the ELFv2 ABI
12886    the register parameter area is optional when calling a function that
12887    has a prototype is scope, has no variable argument list, and passes
12888    all parameters in registers.  */
12889
12890 int
12891 rs6000_reg_parm_stack_space (tree fun, bool incoming)
12892 {
12893   int reg_parm_stack_space;
12894
12895   switch (DEFAULT_ABI)
12896     {
12897     default:
12898       reg_parm_stack_space = 0;
12899       break;
12900
12901     case ABI_AIX:
12902     case ABI_DARWIN:
12903       reg_parm_stack_space = TARGET_64BIT ? 64 : 32;
12904       break;
12905
12906     case ABI_ELFv2:
12907       /* ??? Recomputing this every time is a bit expensive.  Is there
12908          a place to cache this information?  */
12909       if (rs6000_function_parms_need_stack (fun, incoming))
12910         reg_parm_stack_space = TARGET_64BIT ? 64 : 32;
12911       else
12912         reg_parm_stack_space = 0;
12913       break;
12914     }
12915
12916   return reg_parm_stack_space;
12917 }
12918
12919 static void
12920 rs6000_move_block_from_reg (int regno, rtx x, int nregs)
12921 {
12922   int i;
12923   machine_mode reg_mode = TARGET_32BIT ? SImode : DImode;
12924
12925   if (nregs == 0)
12926     return;
12927
12928   for (i = 0; i < nregs; i++)
12929     {
12930       rtx tem = adjust_address_nv (x, reg_mode, i * GET_MODE_SIZE (reg_mode));
12931       if (reload_completed)
12932         {
12933           if (! strict_memory_address_p (reg_mode, XEXP (tem, 0)))
12934             tem = NULL_RTX;
12935           else
12936             tem = simplify_gen_subreg (reg_mode, x, BLKmode,
12937                                        i * GET_MODE_SIZE (reg_mode));
12938         }
12939       else
12940         tem = replace_equiv_address (tem, XEXP (tem, 0));
12941
12942       gcc_assert (tem);
12943
12944       emit_move_insn (tem, gen_rtx_REG (reg_mode, regno + i));
12945     }
12946 }
12947 \f
12948 /* Perform any needed actions needed for a function that is receiving a
12949    variable number of arguments.
12950
12951    CUM is as above.
12952
12953    MODE and TYPE are the mode and type of the current parameter.
12954
12955    PRETEND_SIZE is a variable that should be set to the amount of stack
12956    that must be pushed by the prolog to pretend that our caller pushed
12957    it.
12958
12959    Normally, this macro will push all remaining incoming registers on the
12960    stack and set PRETEND_SIZE to the length of the registers pushed.  */
12961
12962 static void
12963 setup_incoming_varargs (cumulative_args_t cum, machine_mode mode,
12964                         tree type, int *pretend_size ATTRIBUTE_UNUSED,
12965                         int no_rtl)
12966 {
12967   CUMULATIVE_ARGS next_cum;
12968   int reg_size = TARGET_32BIT ? 4 : 8;
12969   rtx save_area = NULL_RTX, mem;
12970   int first_reg_offset;
12971   alias_set_type set;
12972
12973   /* Skip the last named argument.  */
12974   next_cum = *get_cumulative_args (cum);
12975   rs6000_function_arg_advance_1 (&next_cum, mode, type, true, 0);
12976
12977   if (DEFAULT_ABI == ABI_V4)
12978     {
12979       first_reg_offset = next_cum.sysv_gregno - GP_ARG_MIN_REG;
12980
12981       if (! no_rtl)
12982         {
12983           int gpr_reg_num = 0, gpr_size = 0, fpr_size = 0;
12984           HOST_WIDE_INT offset = 0;
12985
12986           /* Try to optimize the size of the varargs save area.
12987              The ABI requires that ap.reg_save_area is doubleword
12988              aligned, but we don't need to allocate space for all
12989              the bytes, only those to which we actually will save
12990              anything.  */
12991           if (cfun->va_list_gpr_size && first_reg_offset < GP_ARG_NUM_REG)
12992             gpr_reg_num = GP_ARG_NUM_REG - first_reg_offset;
12993           if (TARGET_HARD_FLOAT
12994               && next_cum.fregno <= FP_ARG_V4_MAX_REG
12995               && cfun->va_list_fpr_size)
12996             {
12997               if (gpr_reg_num)
12998                 fpr_size = (next_cum.fregno - FP_ARG_MIN_REG)
12999                            * UNITS_PER_FP_WORD;
13000               if (cfun->va_list_fpr_size
13001                   < FP_ARG_V4_MAX_REG + 1 - next_cum.fregno)
13002                 fpr_size += cfun->va_list_fpr_size * UNITS_PER_FP_WORD;
13003               else
13004                 fpr_size += (FP_ARG_V4_MAX_REG + 1 - next_cum.fregno)
13005                             * UNITS_PER_FP_WORD;
13006             }
13007           if (gpr_reg_num)
13008             {
13009               offset = -((first_reg_offset * reg_size) & ~7);
13010               if (!fpr_size && gpr_reg_num > cfun->va_list_gpr_size)
13011                 {
13012                   gpr_reg_num = cfun->va_list_gpr_size;
13013                   if (reg_size == 4 && (first_reg_offset & 1))
13014                     gpr_reg_num++;
13015                 }
13016               gpr_size = (gpr_reg_num * reg_size + 7) & ~7;
13017             }
13018           else if (fpr_size)
13019             offset = - (int) (next_cum.fregno - FP_ARG_MIN_REG)
13020                        * UNITS_PER_FP_WORD
13021                      - (int) (GP_ARG_NUM_REG * reg_size);
13022
13023           if (gpr_size + fpr_size)
13024             {
13025               rtx reg_save_area
13026                 = assign_stack_local (BLKmode, gpr_size + fpr_size, 64);
13027               gcc_assert (GET_CODE (reg_save_area) == MEM);
13028               reg_save_area = XEXP (reg_save_area, 0);
13029               if (GET_CODE (reg_save_area) == PLUS)
13030                 {
13031                   gcc_assert (XEXP (reg_save_area, 0)
13032                               == virtual_stack_vars_rtx);
13033                   gcc_assert (GET_CODE (XEXP (reg_save_area, 1)) == CONST_INT);
13034                   offset += INTVAL (XEXP (reg_save_area, 1));
13035                 }
13036               else
13037                 gcc_assert (reg_save_area == virtual_stack_vars_rtx);
13038             }
13039
13040           cfun->machine->varargs_save_offset = offset;
13041           save_area = plus_constant (Pmode, virtual_stack_vars_rtx, offset);
13042         }
13043     }
13044   else
13045     {
13046       first_reg_offset = next_cum.words;
13047       save_area = crtl->args.internal_arg_pointer;
13048
13049       if (targetm.calls.must_pass_in_stack (mode, type))
13050         first_reg_offset += rs6000_arg_size (TYPE_MODE (type), type);
13051     }
13052
13053   set = get_varargs_alias_set ();
13054   if (! no_rtl && first_reg_offset < GP_ARG_NUM_REG
13055       && cfun->va_list_gpr_size)
13056     {
13057       int n_gpr, nregs = GP_ARG_NUM_REG - first_reg_offset;
13058
13059       if (va_list_gpr_counter_field)
13060         /* V4 va_list_gpr_size counts number of registers needed.  */
13061         n_gpr = cfun->va_list_gpr_size;
13062       else
13063         /* char * va_list instead counts number of bytes needed.  */
13064         n_gpr = (cfun->va_list_gpr_size + reg_size - 1) / reg_size;
13065
13066       if (nregs > n_gpr)
13067         nregs = n_gpr;
13068
13069       mem = gen_rtx_MEM (BLKmode,
13070                          plus_constant (Pmode, save_area,
13071                                         first_reg_offset * reg_size));
13072       MEM_NOTRAP_P (mem) = 1;
13073       set_mem_alias_set (mem, set);
13074       set_mem_align (mem, BITS_PER_WORD);
13075
13076       rs6000_move_block_from_reg (GP_ARG_MIN_REG + first_reg_offset, mem,
13077                                   nregs);
13078     }
13079
13080   /* Save FP registers if needed.  */
13081   if (DEFAULT_ABI == ABI_V4
13082       && TARGET_HARD_FLOAT
13083       && ! no_rtl
13084       && next_cum.fregno <= FP_ARG_V4_MAX_REG
13085       && cfun->va_list_fpr_size)
13086     {
13087       int fregno = next_cum.fregno, nregs;
13088       rtx cr1 = gen_rtx_REG (CCmode, CR1_REGNO);
13089       rtx lab = gen_label_rtx ();
13090       int off = (GP_ARG_NUM_REG * reg_size) + ((fregno - FP_ARG_MIN_REG)
13091                                                * UNITS_PER_FP_WORD);
13092
13093       emit_jump_insn
13094         (gen_rtx_SET (pc_rtx,
13095                       gen_rtx_IF_THEN_ELSE (VOIDmode,
13096                                             gen_rtx_NE (VOIDmode, cr1,
13097                                                         const0_rtx),
13098                                             gen_rtx_LABEL_REF (VOIDmode, lab),
13099                                             pc_rtx)));
13100
13101       for (nregs = 0;
13102            fregno <= FP_ARG_V4_MAX_REG && nregs < cfun->va_list_fpr_size;
13103            fregno++, off += UNITS_PER_FP_WORD, nregs++)
13104         {
13105           mem = gen_rtx_MEM ((TARGET_HARD_FLOAT && TARGET_DOUBLE_FLOAT)
13106                               ? DFmode : SFmode, 
13107                              plus_constant (Pmode, save_area, off));
13108           MEM_NOTRAP_P (mem) = 1;
13109           set_mem_alias_set (mem, set);
13110           set_mem_align (mem, GET_MODE_ALIGNMENT (
13111                          (TARGET_HARD_FLOAT && TARGET_DOUBLE_FLOAT)
13112                           ? DFmode : SFmode));
13113           emit_move_insn (mem, gen_rtx_REG (
13114                           (TARGET_HARD_FLOAT && TARGET_DOUBLE_FLOAT)
13115                            ? DFmode : SFmode, fregno));
13116         }
13117
13118       emit_label (lab);
13119     }
13120 }
13121
13122 /* Create the va_list data type.  */
13123
13124 static tree
13125 rs6000_build_builtin_va_list (void)
13126 {
13127   tree f_gpr, f_fpr, f_res, f_ovf, f_sav, record, type_decl;
13128
13129   /* For AIX, prefer 'char *' because that's what the system
13130      header files like.  */
13131   if (DEFAULT_ABI != ABI_V4)
13132     return build_pointer_type (char_type_node);
13133
13134   record = (*lang_hooks.types.make_type) (RECORD_TYPE);
13135   type_decl = build_decl (BUILTINS_LOCATION, TYPE_DECL,
13136                           get_identifier ("__va_list_tag"), record);
13137
13138   f_gpr = build_decl (BUILTINS_LOCATION, FIELD_DECL, get_identifier ("gpr"),
13139                       unsigned_char_type_node);
13140   f_fpr = build_decl (BUILTINS_LOCATION, FIELD_DECL, get_identifier ("fpr"),
13141                       unsigned_char_type_node);
13142   /* Give the two bytes of padding a name, so that -Wpadded won't warn on
13143      every user file.  */
13144   f_res = build_decl (BUILTINS_LOCATION, FIELD_DECL,
13145                       get_identifier ("reserved"), short_unsigned_type_node);
13146   f_ovf = build_decl (BUILTINS_LOCATION, FIELD_DECL,
13147                       get_identifier ("overflow_arg_area"),
13148                       ptr_type_node);
13149   f_sav = build_decl (BUILTINS_LOCATION, FIELD_DECL,
13150                       get_identifier ("reg_save_area"),
13151                       ptr_type_node);
13152
13153   va_list_gpr_counter_field = f_gpr;
13154   va_list_fpr_counter_field = f_fpr;
13155
13156   DECL_FIELD_CONTEXT (f_gpr) = record;
13157   DECL_FIELD_CONTEXT (f_fpr) = record;
13158   DECL_FIELD_CONTEXT (f_res) = record;
13159   DECL_FIELD_CONTEXT (f_ovf) = record;
13160   DECL_FIELD_CONTEXT (f_sav) = record;
13161
13162   TYPE_STUB_DECL (record) = type_decl;
13163   TYPE_NAME (record) = type_decl;
13164   TYPE_FIELDS (record) = f_gpr;
13165   DECL_CHAIN (f_gpr) = f_fpr;
13166   DECL_CHAIN (f_fpr) = f_res;
13167   DECL_CHAIN (f_res) = f_ovf;
13168   DECL_CHAIN (f_ovf) = f_sav;
13169
13170   layout_type (record);
13171
13172   /* The correct type is an array type of one element.  */
13173   return build_array_type (record, build_index_type (size_zero_node));
13174 }
13175
13176 /* Implement va_start.  */
13177
13178 static void
13179 rs6000_va_start (tree valist, rtx nextarg)
13180 {
13181   HOST_WIDE_INT words, n_gpr, n_fpr;
13182   tree f_gpr, f_fpr, f_res, f_ovf, f_sav;
13183   tree gpr, fpr, ovf, sav, t;
13184
13185   /* Only SVR4 needs something special.  */
13186   if (DEFAULT_ABI != ABI_V4)
13187     {
13188       std_expand_builtin_va_start (valist, nextarg);
13189       return;
13190     }
13191
13192   f_gpr = TYPE_FIELDS (TREE_TYPE (va_list_type_node));
13193   f_fpr = DECL_CHAIN (f_gpr);
13194   f_res = DECL_CHAIN (f_fpr);
13195   f_ovf = DECL_CHAIN (f_res);
13196   f_sav = DECL_CHAIN (f_ovf);
13197
13198   valist = build_simple_mem_ref (valist);
13199   gpr = build3 (COMPONENT_REF, TREE_TYPE (f_gpr), valist, f_gpr, NULL_TREE);
13200   fpr = build3 (COMPONENT_REF, TREE_TYPE (f_fpr), unshare_expr (valist),
13201                 f_fpr, NULL_TREE);
13202   ovf = build3 (COMPONENT_REF, TREE_TYPE (f_ovf), unshare_expr (valist),
13203                 f_ovf, NULL_TREE);
13204   sav = build3 (COMPONENT_REF, TREE_TYPE (f_sav), unshare_expr (valist),
13205                 f_sav, NULL_TREE);
13206
13207   /* Count number of gp and fp argument registers used.  */
13208   words = crtl->args.info.words;
13209   n_gpr = MIN (crtl->args.info.sysv_gregno - GP_ARG_MIN_REG,
13210                GP_ARG_NUM_REG);
13211   n_fpr = MIN (crtl->args.info.fregno - FP_ARG_MIN_REG,
13212                FP_ARG_NUM_REG);
13213
13214   if (TARGET_DEBUG_ARG)
13215     fprintf (stderr, "va_start: words = " HOST_WIDE_INT_PRINT_DEC", n_gpr = "
13216              HOST_WIDE_INT_PRINT_DEC", n_fpr = " HOST_WIDE_INT_PRINT_DEC"\n",
13217              words, n_gpr, n_fpr);
13218
13219   if (cfun->va_list_gpr_size)
13220     {
13221       t = build2 (MODIFY_EXPR, TREE_TYPE (gpr), gpr,
13222                   build_int_cst (NULL_TREE, n_gpr));
13223       TREE_SIDE_EFFECTS (t) = 1;
13224       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
13225     }
13226
13227   if (cfun->va_list_fpr_size)
13228     {
13229       t = build2 (MODIFY_EXPR, TREE_TYPE (fpr), fpr,
13230                   build_int_cst (NULL_TREE, n_fpr));
13231       TREE_SIDE_EFFECTS (t) = 1;
13232       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
13233
13234 #ifdef HAVE_AS_GNU_ATTRIBUTE
13235       if (call_ABI_of_interest (cfun->decl))
13236         rs6000_passes_float = true;
13237 #endif
13238     }
13239
13240   /* Find the overflow area.  */
13241   t = make_tree (TREE_TYPE (ovf), crtl->args.internal_arg_pointer);
13242   if (words != 0)
13243     t = fold_build_pointer_plus_hwi (t, words * MIN_UNITS_PER_WORD);
13244   t = build2 (MODIFY_EXPR, TREE_TYPE (ovf), ovf, t);
13245   TREE_SIDE_EFFECTS (t) = 1;
13246   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
13247
13248   /* If there were no va_arg invocations, don't set up the register
13249      save area.  */
13250   if (!cfun->va_list_gpr_size
13251       && !cfun->va_list_fpr_size
13252       && n_gpr < GP_ARG_NUM_REG
13253       && n_fpr < FP_ARG_V4_MAX_REG)
13254     return;
13255
13256   /* Find the register save area.  */
13257   t = make_tree (TREE_TYPE (sav), virtual_stack_vars_rtx);
13258   if (cfun->machine->varargs_save_offset)
13259     t = fold_build_pointer_plus_hwi (t, cfun->machine->varargs_save_offset);
13260   t = build2 (MODIFY_EXPR, TREE_TYPE (sav), sav, t);
13261   TREE_SIDE_EFFECTS (t) = 1;
13262   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
13263 }
13264
13265 /* Implement va_arg.  */
13266
13267 static tree
13268 rs6000_gimplify_va_arg (tree valist, tree type, gimple_seq *pre_p,
13269                         gimple_seq *post_p)
13270 {
13271   tree f_gpr, f_fpr, f_res, f_ovf, f_sav;
13272   tree gpr, fpr, ovf, sav, reg, t, u;
13273   int size, rsize, n_reg, sav_ofs, sav_scale;
13274   tree lab_false, lab_over, addr;
13275   int align;
13276   tree ptrtype = build_pointer_type_for_mode (type, ptr_mode, true);
13277   int regalign = 0;
13278   gimple *stmt;
13279
13280   if (pass_by_reference (NULL, TYPE_MODE (type), type, false))
13281     {
13282       t = rs6000_gimplify_va_arg (valist, ptrtype, pre_p, post_p);
13283       return build_va_arg_indirect_ref (t);
13284     }
13285
13286   /* We need to deal with the fact that the darwin ppc64 ABI is defined by an
13287      earlier version of gcc, with the property that it always applied alignment
13288      adjustments to the va-args (even for zero-sized types).  The cheapest way
13289      to deal with this is to replicate the effect of the part of 
13290      std_gimplify_va_arg_expr that carries out the align adjust, for the case 
13291      of relevance.  
13292      We don't need to check for pass-by-reference because of the test above.
13293      We can return a simplifed answer, since we know there's no offset to add.  */
13294
13295   if (((TARGET_MACHO
13296         && rs6000_darwin64_abi)
13297        || DEFAULT_ABI == ABI_ELFv2
13298        || (DEFAULT_ABI == ABI_AIX && !rs6000_compat_align_parm))
13299       && integer_zerop (TYPE_SIZE (type)))
13300     {
13301       unsigned HOST_WIDE_INT align, boundary;
13302       tree valist_tmp = get_initialized_tmp_var (valist, pre_p, NULL);
13303       align = PARM_BOUNDARY / BITS_PER_UNIT;
13304       boundary = rs6000_function_arg_boundary (TYPE_MODE (type), type);
13305       if (boundary > MAX_SUPPORTED_STACK_ALIGNMENT)
13306         boundary = MAX_SUPPORTED_STACK_ALIGNMENT;
13307       boundary /= BITS_PER_UNIT;
13308       if (boundary > align)
13309         {
13310           tree t ;
13311           /* This updates arg ptr by the amount that would be necessary
13312              to align the zero-sized (but not zero-alignment) item.  */
13313           t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
13314                       fold_build_pointer_plus_hwi (valist_tmp, boundary - 1));
13315           gimplify_and_add (t, pre_p);
13316
13317           t = fold_convert (sizetype, valist_tmp);
13318           t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
13319                   fold_convert (TREE_TYPE (valist),
13320                                 fold_build2 (BIT_AND_EXPR, sizetype, t,
13321                                              size_int (-boundary))));
13322           t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist, t);
13323           gimplify_and_add (t, pre_p);
13324         }
13325       /* Since it is zero-sized there's no increment for the item itself. */
13326       valist_tmp = fold_convert (build_pointer_type (type), valist_tmp);
13327       return build_va_arg_indirect_ref (valist_tmp);
13328     }
13329
13330   if (DEFAULT_ABI != ABI_V4)
13331     {
13332       if (targetm.calls.split_complex_arg && TREE_CODE (type) == COMPLEX_TYPE)
13333         {
13334           tree elem_type = TREE_TYPE (type);
13335           machine_mode elem_mode = TYPE_MODE (elem_type);
13336           int elem_size = GET_MODE_SIZE (elem_mode);
13337
13338           if (elem_size < UNITS_PER_WORD)
13339             {
13340               tree real_part, imag_part;
13341               gimple_seq post = NULL;
13342
13343               real_part = rs6000_gimplify_va_arg (valist, elem_type, pre_p,
13344                                                   &post);
13345               /* Copy the value into a temporary, lest the formal temporary
13346                  be reused out from under us.  */
13347               real_part = get_initialized_tmp_var (real_part, pre_p, &post);
13348               gimple_seq_add_seq (pre_p, post);
13349
13350               imag_part = rs6000_gimplify_va_arg (valist, elem_type, pre_p,
13351                                                   post_p);
13352
13353               return build2 (COMPLEX_EXPR, type, real_part, imag_part);
13354             }
13355         }
13356
13357       return std_gimplify_va_arg_expr (valist, type, pre_p, post_p);
13358     }
13359
13360   f_gpr = TYPE_FIELDS (TREE_TYPE (va_list_type_node));
13361   f_fpr = DECL_CHAIN (f_gpr);
13362   f_res = DECL_CHAIN (f_fpr);
13363   f_ovf = DECL_CHAIN (f_res);
13364   f_sav = DECL_CHAIN (f_ovf);
13365
13366   gpr = build3 (COMPONENT_REF, TREE_TYPE (f_gpr), valist, f_gpr, NULL_TREE);
13367   fpr = build3 (COMPONENT_REF, TREE_TYPE (f_fpr), unshare_expr (valist),
13368                 f_fpr, NULL_TREE);
13369   ovf = build3 (COMPONENT_REF, TREE_TYPE (f_ovf), unshare_expr (valist),
13370                 f_ovf, NULL_TREE);
13371   sav = build3 (COMPONENT_REF, TREE_TYPE (f_sav), unshare_expr (valist),
13372                 f_sav, NULL_TREE);
13373
13374   size = int_size_in_bytes (type);
13375   rsize = (size + 3) / 4;
13376   int pad = 4 * rsize - size;
13377   align = 1;
13378
13379   machine_mode mode = TYPE_MODE (type);
13380   if (abi_v4_pass_in_fpr (mode))
13381     {
13382       /* FP args go in FP registers, if present.  */
13383       reg = fpr;
13384       n_reg = (size + 7) / 8;
13385       sav_ofs = ((TARGET_HARD_FLOAT && TARGET_DOUBLE_FLOAT) ? 8 : 4) * 4;
13386       sav_scale = ((TARGET_HARD_FLOAT && TARGET_DOUBLE_FLOAT) ? 8 : 4);
13387       if (mode != SFmode && mode != SDmode)
13388         align = 8;
13389     }
13390   else
13391     {
13392       /* Otherwise into GP registers.  */
13393       reg = gpr;
13394       n_reg = rsize;
13395       sav_ofs = 0;
13396       sav_scale = 4;
13397       if (n_reg == 2)
13398         align = 8;
13399     }
13400
13401   /* Pull the value out of the saved registers....  */
13402
13403   lab_over = NULL;
13404   addr = create_tmp_var (ptr_type_node, "addr");
13405
13406   /*  AltiVec vectors never go in registers when -mabi=altivec.  */
13407   if (TARGET_ALTIVEC_ABI && ALTIVEC_VECTOR_MODE (mode))
13408     align = 16;
13409   else
13410     {
13411       lab_false = create_artificial_label (input_location);
13412       lab_over = create_artificial_label (input_location);
13413
13414       /* Long long is aligned in the registers.  As are any other 2 gpr
13415          item such as complex int due to a historical mistake.  */
13416       u = reg;
13417       if (n_reg == 2 && reg == gpr)
13418         {
13419           regalign = 1;
13420           u = build2 (BIT_AND_EXPR, TREE_TYPE (reg), unshare_expr (reg),
13421                      build_int_cst (TREE_TYPE (reg), n_reg - 1));
13422           u = build2 (POSTINCREMENT_EXPR, TREE_TYPE (reg),
13423                       unshare_expr (reg), u);
13424         }
13425       /* _Decimal128 is passed in even/odd fpr pairs; the stored
13426          reg number is 0 for f1, so we want to make it odd.  */
13427       else if (reg == fpr && mode == TDmode)
13428         {
13429           t = build2 (BIT_IOR_EXPR, TREE_TYPE (reg), unshare_expr (reg),
13430                       build_int_cst (TREE_TYPE (reg), 1));
13431           u = build2 (MODIFY_EXPR, void_type_node, unshare_expr (reg), t);
13432         }
13433
13434       t = fold_convert (TREE_TYPE (reg), size_int (8 - n_reg + 1));
13435       t = build2 (GE_EXPR, boolean_type_node, u, t);
13436       u = build1 (GOTO_EXPR, void_type_node, lab_false);
13437       t = build3 (COND_EXPR, void_type_node, t, u, NULL_TREE);
13438       gimplify_and_add (t, pre_p);
13439
13440       t = sav;
13441       if (sav_ofs)
13442         t = fold_build_pointer_plus_hwi (sav, sav_ofs);
13443
13444       u = build2 (POSTINCREMENT_EXPR, TREE_TYPE (reg), unshare_expr (reg),
13445                   build_int_cst (TREE_TYPE (reg), n_reg));
13446       u = fold_convert (sizetype, u);
13447       u = build2 (MULT_EXPR, sizetype, u, size_int (sav_scale));
13448       t = fold_build_pointer_plus (t, u);
13449
13450       /* _Decimal32 varargs are located in the second word of the 64-bit
13451          FP register for 32-bit binaries.  */
13452       if (TARGET_32BIT && TARGET_HARD_FLOAT && mode == SDmode)
13453         t = fold_build_pointer_plus_hwi (t, size);
13454
13455       /* Args are passed right-aligned.  */
13456       if (BYTES_BIG_ENDIAN)
13457         t = fold_build_pointer_plus_hwi (t, pad);
13458
13459       gimplify_assign (addr, t, pre_p);
13460
13461       gimple_seq_add_stmt (pre_p, gimple_build_goto (lab_over));
13462
13463       stmt = gimple_build_label (lab_false);
13464       gimple_seq_add_stmt (pre_p, stmt);
13465
13466       if ((n_reg == 2 && !regalign) || n_reg > 2)
13467         {
13468           /* Ensure that we don't find any more args in regs.
13469              Alignment has taken care of for special cases.  */
13470           gimplify_assign (reg, build_int_cst (TREE_TYPE (reg), 8), pre_p);
13471         }
13472     }
13473
13474   /* ... otherwise out of the overflow area.  */
13475
13476   /* Care for on-stack alignment if needed.  */
13477   t = ovf;
13478   if (align != 1)
13479     {
13480       t = fold_build_pointer_plus_hwi (t, align - 1);
13481       t = build2 (BIT_AND_EXPR, TREE_TYPE (t), t,
13482                   build_int_cst (TREE_TYPE (t), -align));
13483     }
13484
13485   /* Args are passed right-aligned.  */
13486   if (BYTES_BIG_ENDIAN)
13487     t = fold_build_pointer_plus_hwi (t, pad);
13488
13489   gimplify_expr (&t, pre_p, NULL, is_gimple_val, fb_rvalue);
13490
13491   gimplify_assign (unshare_expr (addr), t, pre_p);
13492
13493   t = fold_build_pointer_plus_hwi (t, size);
13494   gimplify_assign (unshare_expr (ovf), t, pre_p);
13495
13496   if (lab_over)
13497     {
13498       stmt = gimple_build_label (lab_over);
13499       gimple_seq_add_stmt (pre_p, stmt);
13500     }
13501
13502   if (STRICT_ALIGNMENT
13503       && (TYPE_ALIGN (type)
13504           > (unsigned) BITS_PER_UNIT * (align < 4 ? 4 : align)))
13505     {
13506       /* The value (of type complex double, for example) may not be
13507          aligned in memory in the saved registers, so copy via a
13508          temporary.  (This is the same code as used for SPARC.)  */
13509       tree tmp = create_tmp_var (type, "va_arg_tmp");
13510       tree dest_addr = build_fold_addr_expr (tmp);
13511
13512       tree copy = build_call_expr (builtin_decl_implicit (BUILT_IN_MEMCPY),
13513                                    3, dest_addr, addr, size_int (rsize * 4));
13514
13515       gimplify_and_add (copy, pre_p);
13516       addr = dest_addr;
13517     }
13518
13519   addr = fold_convert (ptrtype, addr);
13520   return build_va_arg_indirect_ref (addr);
13521 }
13522
13523 /* Builtins.  */
13524
13525 static void
13526 def_builtin (const char *name, tree type, enum rs6000_builtins code)
13527 {
13528   tree t;
13529   unsigned classify = rs6000_builtin_info[(int)code].attr;
13530   const char *attr_string = "";
13531
13532   gcc_assert (name != NULL);
13533   gcc_assert (IN_RANGE ((int)code, 0, (int)RS6000_BUILTIN_COUNT));
13534
13535   if (rs6000_builtin_decls[(int)code])
13536     fatal_error (input_location,
13537                  "internal error: builtin function %qs already processed",
13538                  name);
13539
13540   rs6000_builtin_decls[(int)code] = t =
13541     add_builtin_function (name, type, (int)code, BUILT_IN_MD, NULL, NULL_TREE);
13542
13543   /* Set any special attributes.  */
13544   if ((classify & RS6000_BTC_CONST) != 0)
13545     {
13546       /* const function, function only depends on the inputs.  */
13547       TREE_READONLY (t) = 1;
13548       TREE_NOTHROW (t) = 1;
13549       attr_string = ", const";
13550     }
13551   else if ((classify & RS6000_BTC_PURE) != 0)
13552     {
13553       /* pure function, function can read global memory, but does not set any
13554          external state.  */
13555       DECL_PURE_P (t) = 1;
13556       TREE_NOTHROW (t) = 1;
13557       attr_string = ", pure";
13558     }
13559   else if ((classify & RS6000_BTC_FP) != 0)
13560     {
13561       /* Function is a math function.  If rounding mode is on, then treat the
13562          function as not reading global memory, but it can have arbitrary side
13563          effects.  If it is off, then assume the function is a const function.
13564          This mimics the ATTR_MATHFN_FPROUNDING attribute in
13565          builtin-attribute.def that is used for the math functions. */
13566       TREE_NOTHROW (t) = 1;
13567       if (flag_rounding_math)
13568         {
13569           DECL_PURE_P (t) = 1;
13570           DECL_IS_NOVOPS (t) = 1;
13571           attr_string = ", fp, pure";
13572         }
13573       else
13574         {
13575           TREE_READONLY (t) = 1;
13576           attr_string = ", fp, const";
13577         }
13578     }
13579   else if ((classify & RS6000_BTC_ATTR_MASK) != 0)
13580     gcc_unreachable ();
13581
13582   if (TARGET_DEBUG_BUILTIN)
13583     fprintf (stderr, "rs6000_builtin, code = %4d, %s%s\n",
13584              (int)code, name, attr_string);
13585 }
13586
13587 /* Simple ternary operations: VECd = foo (VECa, VECb, VECc).  */
13588
13589 #undef RS6000_BUILTIN_0
13590 #undef RS6000_BUILTIN_1
13591 #undef RS6000_BUILTIN_2
13592 #undef RS6000_BUILTIN_3
13593 #undef RS6000_BUILTIN_A
13594 #undef RS6000_BUILTIN_D
13595 #undef RS6000_BUILTIN_H
13596 #undef RS6000_BUILTIN_P
13597 #undef RS6000_BUILTIN_Q
13598 #undef RS6000_BUILTIN_X
13599
13600 #define RS6000_BUILTIN_0(ENUM, NAME, MASK, ATTR, ICODE)
13601 #define RS6000_BUILTIN_1(ENUM, NAME, MASK, ATTR, ICODE)
13602 #define RS6000_BUILTIN_2(ENUM, NAME, MASK, ATTR, ICODE)
13603 #define RS6000_BUILTIN_3(ENUM, NAME, MASK, ATTR, ICODE) \
13604   { MASK, ICODE, NAME, ENUM },
13605
13606 #define RS6000_BUILTIN_A(ENUM, NAME, MASK, ATTR, ICODE)
13607 #define RS6000_BUILTIN_D(ENUM, NAME, MASK, ATTR, ICODE)
13608 #define RS6000_BUILTIN_H(ENUM, NAME, MASK, ATTR, ICODE)
13609 #define RS6000_BUILTIN_P(ENUM, NAME, MASK, ATTR, ICODE)
13610 #define RS6000_BUILTIN_Q(ENUM, NAME, MASK, ATTR, ICODE)
13611 #define RS6000_BUILTIN_X(ENUM, NAME, MASK, ATTR, ICODE)
13612
13613 static const struct builtin_description bdesc_3arg[] =
13614 {
13615 #include "rs6000-builtin.def"
13616 };
13617
13618 /* DST operations: void foo (void *, const int, const char).  */
13619
13620 #undef RS6000_BUILTIN_0
13621 #undef RS6000_BUILTIN_1
13622 #undef RS6000_BUILTIN_2
13623 #undef RS6000_BUILTIN_3
13624 #undef RS6000_BUILTIN_A
13625 #undef RS6000_BUILTIN_D
13626 #undef RS6000_BUILTIN_H
13627 #undef RS6000_BUILTIN_P
13628 #undef RS6000_BUILTIN_Q
13629 #undef RS6000_BUILTIN_X
13630
13631 #define RS6000_BUILTIN_0(ENUM, NAME, MASK, ATTR, ICODE)
13632 #define RS6000_BUILTIN_1(ENUM, NAME, MASK, ATTR, ICODE)
13633 #define RS6000_BUILTIN_2(ENUM, NAME, MASK, ATTR, ICODE)
13634 #define RS6000_BUILTIN_3(ENUM, NAME, MASK, ATTR, ICODE)
13635 #define RS6000_BUILTIN_A(ENUM, NAME, MASK, ATTR, ICODE)
13636 #define RS6000_BUILTIN_D(ENUM, NAME, MASK, ATTR, ICODE) \
13637   { MASK, ICODE, NAME, ENUM },
13638
13639 #define RS6000_BUILTIN_H(ENUM, NAME, MASK, ATTR, ICODE)
13640 #define RS6000_BUILTIN_P(ENUM, NAME, MASK, ATTR, ICODE)
13641 #define RS6000_BUILTIN_Q(ENUM, NAME, MASK, ATTR, ICODE)
13642 #define RS6000_BUILTIN_X(ENUM, NAME, MASK, ATTR, ICODE)
13643
13644 static const struct builtin_description bdesc_dst[] =
13645 {
13646 #include "rs6000-builtin.def"
13647 };
13648
13649 /* Simple binary operations: VECc = foo (VECa, VECb).  */
13650
13651 #undef RS6000_BUILTIN_0
13652 #undef RS6000_BUILTIN_1
13653 #undef RS6000_BUILTIN_2
13654 #undef RS6000_BUILTIN_3
13655 #undef RS6000_BUILTIN_A
13656 #undef RS6000_BUILTIN_D
13657 #undef RS6000_BUILTIN_H
13658 #undef RS6000_BUILTIN_P
13659 #undef RS6000_BUILTIN_Q
13660 #undef RS6000_BUILTIN_X
13661
13662 #define RS6000_BUILTIN_0(ENUM, NAME, MASK, ATTR, ICODE)
13663 #define RS6000_BUILTIN_1(ENUM, NAME, MASK, ATTR, ICODE)
13664 #define RS6000_BUILTIN_2(ENUM, NAME, MASK, ATTR, ICODE) \
13665   { MASK, ICODE, NAME, ENUM },
13666
13667 #define RS6000_BUILTIN_3(ENUM, NAME, MASK, ATTR, ICODE)
13668 #define RS6000_BUILTIN_A(ENUM, NAME, MASK, ATTR, ICODE)
13669 #define RS6000_BUILTIN_D(ENUM, NAME, MASK, ATTR, ICODE)
13670 #define RS6000_BUILTIN_H(ENUM, NAME, MASK, ATTR, ICODE)
13671 #define RS6000_BUILTIN_P(ENUM, NAME, MASK, ATTR, ICODE)
13672 #define RS6000_BUILTIN_Q(ENUM, NAME, MASK, ATTR, ICODE)
13673 #define RS6000_BUILTIN_X(ENUM, NAME, MASK, ATTR, ICODE)
13674
13675 static const struct builtin_description bdesc_2arg[] =
13676 {
13677 #include "rs6000-builtin.def"
13678 };
13679
13680 #undef RS6000_BUILTIN_0
13681 #undef RS6000_BUILTIN_1
13682 #undef RS6000_BUILTIN_2
13683 #undef RS6000_BUILTIN_3
13684 #undef RS6000_BUILTIN_A
13685 #undef RS6000_BUILTIN_D
13686 #undef RS6000_BUILTIN_H
13687 #undef RS6000_BUILTIN_P
13688 #undef RS6000_BUILTIN_Q
13689 #undef RS6000_BUILTIN_X
13690
13691 #define RS6000_BUILTIN_0(ENUM, NAME, MASK, ATTR, ICODE)
13692 #define RS6000_BUILTIN_1(ENUM, NAME, MASK, ATTR, ICODE)
13693 #define RS6000_BUILTIN_2(ENUM, NAME, MASK, ATTR, ICODE)
13694 #define RS6000_BUILTIN_3(ENUM, NAME, MASK, ATTR, ICODE)
13695 #define RS6000_BUILTIN_A(ENUM, NAME, MASK, ATTR, ICODE)
13696 #define RS6000_BUILTIN_D(ENUM, NAME, MASK, ATTR, ICODE)
13697 #define RS6000_BUILTIN_H(ENUM, NAME, MASK, ATTR, ICODE)
13698 #define RS6000_BUILTIN_P(ENUM, NAME, MASK, ATTR, ICODE) \
13699   { MASK, ICODE, NAME, ENUM },
13700
13701 #define RS6000_BUILTIN_Q(ENUM, NAME, MASK, ATTR, ICODE)
13702 #define RS6000_BUILTIN_X(ENUM, NAME, MASK, ATTR, ICODE)
13703
13704 /* AltiVec predicates.  */
13705
13706 static const struct builtin_description bdesc_altivec_preds[] =
13707 {
13708 #include "rs6000-builtin.def"
13709 };
13710
13711 /* PAIRED predicates.  */
13712 #undef RS6000_BUILTIN_0
13713 #undef RS6000_BUILTIN_1
13714 #undef RS6000_BUILTIN_2
13715 #undef RS6000_BUILTIN_3
13716 #undef RS6000_BUILTIN_A
13717 #undef RS6000_BUILTIN_D
13718 #undef RS6000_BUILTIN_H
13719 #undef RS6000_BUILTIN_P
13720 #undef RS6000_BUILTIN_Q
13721 #undef RS6000_BUILTIN_X
13722
13723 #define RS6000_BUILTIN_0(ENUM, NAME, MASK, ATTR, ICODE)
13724 #define RS6000_BUILTIN_1(ENUM, NAME, MASK, ATTR, ICODE)
13725 #define RS6000_BUILTIN_2(ENUM, NAME, MASK, ATTR, ICODE)
13726 #define RS6000_BUILTIN_3(ENUM, NAME, MASK, ATTR, ICODE)
13727 #define RS6000_BUILTIN_A(ENUM, NAME, MASK, ATTR, ICODE)
13728 #define RS6000_BUILTIN_D(ENUM, NAME, MASK, ATTR, ICODE)
13729 #define RS6000_BUILTIN_H(ENUM, NAME, MASK, ATTR, ICODE)
13730 #define RS6000_BUILTIN_P(ENUM, NAME, MASK, ATTR, ICODE)
13731 #define RS6000_BUILTIN_Q(ENUM, NAME, MASK, ATTR, ICODE) \
13732   { MASK, ICODE, NAME, ENUM },
13733
13734 #define RS6000_BUILTIN_X(ENUM, NAME, MASK, ATTR, ICODE)
13735
13736 static const struct builtin_description bdesc_paired_preds[] =
13737 {
13738 #include "rs6000-builtin.def"
13739 };
13740
13741 /* ABS* operations.  */
13742
13743 #undef RS6000_BUILTIN_0
13744 #undef RS6000_BUILTIN_1
13745 #undef RS6000_BUILTIN_2
13746 #undef RS6000_BUILTIN_3
13747 #undef RS6000_BUILTIN_A
13748 #undef RS6000_BUILTIN_D
13749 #undef RS6000_BUILTIN_H
13750 #undef RS6000_BUILTIN_P
13751 #undef RS6000_BUILTIN_Q
13752 #undef RS6000_BUILTIN_X
13753
13754 #define RS6000_BUILTIN_0(ENUM, NAME, MASK, ATTR, ICODE)
13755 #define RS6000_BUILTIN_1(ENUM, NAME, MASK, ATTR, ICODE)
13756 #define RS6000_BUILTIN_2(ENUM, NAME, MASK, ATTR, ICODE)
13757 #define RS6000_BUILTIN_3(ENUM, NAME, MASK, ATTR, ICODE)
13758 #define RS6000_BUILTIN_A(ENUM, NAME, MASK, ATTR, ICODE) \
13759   { MASK, ICODE, NAME, ENUM },
13760
13761 #define RS6000_BUILTIN_D(ENUM, NAME, MASK, ATTR, ICODE)
13762 #define RS6000_BUILTIN_H(ENUM, NAME, MASK, ATTR, ICODE)
13763 #define RS6000_BUILTIN_P(ENUM, NAME, MASK, ATTR, ICODE)
13764 #define RS6000_BUILTIN_Q(ENUM, NAME, MASK, ATTR, ICODE)
13765 #define RS6000_BUILTIN_X(ENUM, NAME, MASK, ATTR, ICODE)
13766
13767 static const struct builtin_description bdesc_abs[] =
13768 {
13769 #include "rs6000-builtin.def"
13770 };
13771
13772 /* Simple unary operations: VECb = foo (unsigned literal) or VECb =
13773    foo (VECa).  */
13774
13775 #undef RS6000_BUILTIN_0
13776 #undef RS6000_BUILTIN_1
13777 #undef RS6000_BUILTIN_2
13778 #undef RS6000_BUILTIN_3
13779 #undef RS6000_BUILTIN_A
13780 #undef RS6000_BUILTIN_D
13781 #undef RS6000_BUILTIN_H
13782 #undef RS6000_BUILTIN_P
13783 #undef RS6000_BUILTIN_Q
13784 #undef RS6000_BUILTIN_X
13785
13786 #define RS6000_BUILTIN_0(ENUM, NAME, MASK, ATTR, ICODE)
13787 #define RS6000_BUILTIN_1(ENUM, NAME, MASK, ATTR, ICODE) \
13788   { MASK, ICODE, NAME, ENUM },
13789
13790 #define RS6000_BUILTIN_2(ENUM, NAME, MASK, ATTR, ICODE)
13791 #define RS6000_BUILTIN_3(ENUM, NAME, MASK, ATTR, ICODE)
13792 #define RS6000_BUILTIN_A(ENUM, NAME, MASK, ATTR, ICODE)
13793 #define RS6000_BUILTIN_D(ENUM, NAME, MASK, ATTR, ICODE)
13794 #define RS6000_BUILTIN_H(ENUM, NAME, MASK, ATTR, ICODE)
13795 #define RS6000_BUILTIN_P(ENUM, NAME, MASK, ATTR, ICODE)
13796 #define RS6000_BUILTIN_Q(ENUM, NAME, MASK, ATTR, ICODE)
13797 #define RS6000_BUILTIN_X(ENUM, NAME, MASK, ATTR, ICODE)
13798
13799 static const struct builtin_description bdesc_1arg[] =
13800 {
13801 #include "rs6000-builtin.def"
13802 };
13803
13804 /* Simple no-argument operations: result = __builtin_darn_32 () */
13805
13806 #undef RS6000_BUILTIN_0
13807 #undef RS6000_BUILTIN_1
13808 #undef RS6000_BUILTIN_2
13809 #undef RS6000_BUILTIN_3
13810 #undef RS6000_BUILTIN_A
13811 #undef RS6000_BUILTIN_D
13812 #undef RS6000_BUILTIN_H
13813 #undef RS6000_BUILTIN_P
13814 #undef RS6000_BUILTIN_Q
13815 #undef RS6000_BUILTIN_X
13816
13817 #define RS6000_BUILTIN_0(ENUM, NAME, MASK, ATTR, ICODE) \
13818   { MASK, ICODE, NAME, ENUM },
13819
13820 #define RS6000_BUILTIN_1(ENUM, NAME, MASK, ATTR, ICODE)
13821 #define RS6000_BUILTIN_2(ENUM, NAME, MASK, ATTR, ICODE)
13822 #define RS6000_BUILTIN_3(ENUM, NAME, MASK, ATTR, ICODE)
13823 #define RS6000_BUILTIN_A(ENUM, NAME, MASK, ATTR, ICODE)
13824 #define RS6000_BUILTIN_D(ENUM, NAME, MASK, ATTR, ICODE)
13825 #define RS6000_BUILTIN_H(ENUM, NAME, MASK, ATTR, ICODE)
13826 #define RS6000_BUILTIN_P(ENUM, NAME, MASK, ATTR, ICODE)
13827 #define RS6000_BUILTIN_Q(ENUM, NAME, MASK, ATTR, ICODE)
13828 #define RS6000_BUILTIN_X(ENUM, NAME, MASK, ATTR, ICODE)
13829
13830 static const struct builtin_description bdesc_0arg[] =
13831 {
13832 #include "rs6000-builtin.def"
13833 };
13834
13835 /* HTM builtins.  */
13836 #undef RS6000_BUILTIN_0
13837 #undef RS6000_BUILTIN_1
13838 #undef RS6000_BUILTIN_2
13839 #undef RS6000_BUILTIN_3
13840 #undef RS6000_BUILTIN_A
13841 #undef RS6000_BUILTIN_D
13842 #undef RS6000_BUILTIN_H
13843 #undef RS6000_BUILTIN_P
13844 #undef RS6000_BUILTIN_Q
13845 #undef RS6000_BUILTIN_X
13846
13847 #define RS6000_BUILTIN_0(ENUM, NAME, MASK, ATTR, ICODE)
13848 #define RS6000_BUILTIN_1(ENUM, NAME, MASK, ATTR, ICODE)
13849 #define RS6000_BUILTIN_2(ENUM, NAME, MASK, ATTR, ICODE)
13850 #define RS6000_BUILTIN_3(ENUM, NAME, MASK, ATTR, ICODE)
13851 #define RS6000_BUILTIN_A(ENUM, NAME, MASK, ATTR, ICODE)
13852 #define RS6000_BUILTIN_D(ENUM, NAME, MASK, ATTR, ICODE)
13853 #define RS6000_BUILTIN_H(ENUM, NAME, MASK, ATTR, ICODE) \
13854   { MASK, ICODE, NAME, ENUM },
13855
13856 #define RS6000_BUILTIN_P(ENUM, NAME, MASK, ATTR, ICODE)
13857 #define RS6000_BUILTIN_Q(ENUM, NAME, MASK, ATTR, ICODE)
13858 #define RS6000_BUILTIN_X(ENUM, NAME, MASK, ATTR, ICODE)
13859
13860 static const struct builtin_description bdesc_htm[] =
13861 {
13862 #include "rs6000-builtin.def"
13863 };
13864
13865 #undef RS6000_BUILTIN_0
13866 #undef RS6000_BUILTIN_1
13867 #undef RS6000_BUILTIN_2
13868 #undef RS6000_BUILTIN_3
13869 #undef RS6000_BUILTIN_A
13870 #undef RS6000_BUILTIN_D
13871 #undef RS6000_BUILTIN_H
13872 #undef RS6000_BUILTIN_P
13873 #undef RS6000_BUILTIN_Q
13874
13875 /* Return true if a builtin function is overloaded.  */
13876 bool
13877 rs6000_overloaded_builtin_p (enum rs6000_builtins fncode)
13878 {
13879   return (rs6000_builtin_info[(int)fncode].attr & RS6000_BTC_OVERLOADED) != 0;
13880 }
13881
13882 const char *
13883 rs6000_overloaded_builtin_name (enum rs6000_builtins fncode)
13884 {
13885   return rs6000_builtin_info[(int)fncode].name;
13886 }
13887
13888 /* Expand an expression EXP that calls a builtin without arguments.  */
13889 static rtx
13890 rs6000_expand_zeroop_builtin (enum insn_code icode, rtx target)
13891 {
13892   rtx pat;
13893   machine_mode tmode = insn_data[icode].operand[0].mode;
13894
13895   if (icode == CODE_FOR_nothing)
13896     /* Builtin not supported on this processor.  */
13897     return 0;
13898
13899   if (target == 0
13900       || GET_MODE (target) != tmode
13901       || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
13902     target = gen_reg_rtx (tmode);
13903
13904   pat = GEN_FCN (icode) (target);
13905   if (! pat)
13906     return 0;
13907   emit_insn (pat);
13908
13909   return target;
13910 }
13911
13912
13913 static rtx
13914 rs6000_expand_mtfsf_builtin (enum insn_code icode, tree exp)
13915 {
13916   rtx pat;
13917   tree arg0 = CALL_EXPR_ARG (exp, 0);
13918   tree arg1 = CALL_EXPR_ARG (exp, 1);
13919   rtx op0 = expand_normal (arg0);
13920   rtx op1 = expand_normal (arg1);
13921   machine_mode mode0 = insn_data[icode].operand[0].mode;
13922   machine_mode mode1 = insn_data[icode].operand[1].mode;
13923
13924   if (icode == CODE_FOR_nothing)
13925     /* Builtin not supported on this processor.  */
13926     return 0;
13927
13928   /* If we got invalid arguments bail out before generating bad rtl.  */
13929   if (arg0 == error_mark_node || arg1 == error_mark_node)
13930     return const0_rtx;
13931
13932   if (GET_CODE (op0) != CONST_INT
13933       || INTVAL (op0) > 255
13934       || INTVAL (op0) < 0)
13935     {
13936       error ("argument 1 must be an 8-bit field value");
13937       return const0_rtx;
13938     }
13939
13940   if (! (*insn_data[icode].operand[0].predicate) (op0, mode0))
13941     op0 = copy_to_mode_reg (mode0, op0);
13942
13943   if (! (*insn_data[icode].operand[1].predicate) (op1, mode1))
13944     op1 = copy_to_mode_reg (mode1, op1);
13945
13946   pat = GEN_FCN (icode) (op0, op1);
13947   if (! pat)
13948     return const0_rtx;
13949   emit_insn (pat);
13950
13951   return NULL_RTX;
13952 }
13953
13954 static rtx
13955 rs6000_expand_unop_builtin (enum insn_code icode, tree exp, rtx target)
13956 {
13957   rtx pat;
13958   tree arg0 = CALL_EXPR_ARG (exp, 0);
13959   rtx op0 = expand_normal (arg0);
13960   machine_mode tmode = insn_data[icode].operand[0].mode;
13961   machine_mode mode0 = insn_data[icode].operand[1].mode;
13962
13963   if (icode == CODE_FOR_nothing)
13964     /* Builtin not supported on this processor.  */
13965     return 0;
13966
13967   /* If we got invalid arguments bail out before generating bad rtl.  */
13968   if (arg0 == error_mark_node)
13969     return const0_rtx;
13970
13971   if (icode == CODE_FOR_altivec_vspltisb
13972       || icode == CODE_FOR_altivec_vspltish
13973       || icode == CODE_FOR_altivec_vspltisw)
13974     {
13975       /* Only allow 5-bit *signed* literals.  */
13976       if (GET_CODE (op0) != CONST_INT
13977           || INTVAL (op0) > 15
13978           || INTVAL (op0) < -16)
13979         {
13980           error ("argument 1 must be a 5-bit signed literal");
13981           return CONST0_RTX (tmode);
13982         }
13983     }
13984
13985   if (target == 0
13986       || GET_MODE (target) != tmode
13987       || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
13988     target = gen_reg_rtx (tmode);
13989
13990   if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
13991     op0 = copy_to_mode_reg (mode0, op0);
13992
13993   pat = GEN_FCN (icode) (target, op0);
13994   if (! pat)
13995     return 0;
13996   emit_insn (pat);
13997
13998   return target;
13999 }
14000
14001 static rtx
14002 altivec_expand_abs_builtin (enum insn_code icode, tree exp, rtx target)
14003 {
14004   rtx pat, scratch1, scratch2;
14005   tree arg0 = CALL_EXPR_ARG (exp, 0);
14006   rtx op0 = expand_normal (arg0);
14007   machine_mode tmode = insn_data[icode].operand[0].mode;
14008   machine_mode mode0 = insn_data[icode].operand[1].mode;
14009
14010   /* If we have invalid arguments, bail out before generating bad rtl.  */
14011   if (arg0 == error_mark_node)
14012     return const0_rtx;
14013
14014   if (target == 0
14015       || GET_MODE (target) != tmode
14016       || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
14017     target = gen_reg_rtx (tmode);
14018
14019   if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
14020     op0 = copy_to_mode_reg (mode0, op0);
14021
14022   scratch1 = gen_reg_rtx (mode0);
14023   scratch2 = gen_reg_rtx (mode0);
14024
14025   pat = GEN_FCN (icode) (target, op0, scratch1, scratch2);
14026   if (! pat)
14027     return 0;
14028   emit_insn (pat);
14029
14030   return target;
14031 }
14032
14033 static rtx
14034 rs6000_expand_binop_builtin (enum insn_code icode, tree exp, rtx target)
14035 {
14036   rtx pat;
14037   tree arg0 = CALL_EXPR_ARG (exp, 0);
14038   tree arg1 = CALL_EXPR_ARG (exp, 1);
14039   rtx op0 = expand_normal (arg0);
14040   rtx op1 = expand_normal (arg1);
14041   machine_mode tmode = insn_data[icode].operand[0].mode;
14042   machine_mode mode0 = insn_data[icode].operand[1].mode;
14043   machine_mode mode1 = insn_data[icode].operand[2].mode;
14044
14045   if (icode == CODE_FOR_nothing)
14046     /* Builtin not supported on this processor.  */
14047     return 0;
14048
14049   /* If we got invalid arguments bail out before generating bad rtl.  */
14050   if (arg0 == error_mark_node || arg1 == error_mark_node)
14051     return const0_rtx;
14052
14053   if (icode == CODE_FOR_altivec_vcfux
14054       || icode == CODE_FOR_altivec_vcfsx
14055       || icode == CODE_FOR_altivec_vctsxs
14056       || icode == CODE_FOR_altivec_vctuxs
14057       || icode == CODE_FOR_altivec_vspltb
14058       || icode == CODE_FOR_altivec_vsplth
14059       || icode == CODE_FOR_altivec_vspltw)
14060     {
14061       /* Only allow 5-bit unsigned literals.  */
14062       STRIP_NOPS (arg1);
14063       if (TREE_CODE (arg1) != INTEGER_CST
14064           || TREE_INT_CST_LOW (arg1) & ~0x1f)
14065         {
14066           error ("argument 2 must be a 5-bit unsigned literal");
14067           return CONST0_RTX (tmode);
14068         }
14069     }
14070   else if (icode == CODE_FOR_dfptstsfi_eq_dd
14071       || icode == CODE_FOR_dfptstsfi_lt_dd
14072       || icode == CODE_FOR_dfptstsfi_gt_dd
14073       || icode == CODE_FOR_dfptstsfi_unordered_dd
14074       || icode == CODE_FOR_dfptstsfi_eq_td
14075       || icode == CODE_FOR_dfptstsfi_lt_td
14076       || icode == CODE_FOR_dfptstsfi_gt_td
14077       || icode == CODE_FOR_dfptstsfi_unordered_td)
14078     {
14079       /* Only allow 6-bit unsigned literals.  */
14080       STRIP_NOPS (arg0);
14081       if (TREE_CODE (arg0) != INTEGER_CST
14082           || !IN_RANGE (TREE_INT_CST_LOW (arg0), 0, 63))
14083         {
14084           error ("argument 1 must be a 6-bit unsigned literal");
14085           return CONST0_RTX (tmode);
14086         }
14087     }
14088   else if (icode == CODE_FOR_xststdcqp_kf
14089            || icode == CODE_FOR_xststdcqp_tf
14090            || icode == CODE_FOR_xststdcdp
14091            || icode == CODE_FOR_xststdcsp
14092            || icode == CODE_FOR_xvtstdcdp
14093            || icode == CODE_FOR_xvtstdcsp)
14094     {
14095       /* Only allow 7-bit unsigned literals. */
14096       STRIP_NOPS (arg1);
14097       if (TREE_CODE (arg1) != INTEGER_CST
14098           || !IN_RANGE (TREE_INT_CST_LOW (arg1), 0, 127))
14099         {
14100           error ("argument 2 must be a 7-bit unsigned literal");
14101           return CONST0_RTX (tmode);
14102         }
14103     }
14104   else if (icode == CODE_FOR_unpackv1ti
14105            || icode == CODE_FOR_unpackkf
14106            || icode == CODE_FOR_unpacktf
14107            || icode == CODE_FOR_unpackif
14108            || icode == CODE_FOR_unpacktd)
14109     {
14110       /* Only allow 1-bit unsigned literals. */
14111       STRIP_NOPS (arg1);
14112       if (TREE_CODE (arg1) != INTEGER_CST
14113           || !IN_RANGE (TREE_INT_CST_LOW (arg1), 0, 1))
14114         {
14115           error ("argument 2 must be a 1-bit unsigned literal");
14116           return CONST0_RTX (tmode);
14117         }
14118     }
14119
14120   if (target == 0
14121       || GET_MODE (target) != tmode
14122       || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
14123     target = gen_reg_rtx (tmode);
14124
14125   if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
14126     op0 = copy_to_mode_reg (mode0, op0);
14127   if (! (*insn_data[icode].operand[2].predicate) (op1, mode1))
14128     op1 = copy_to_mode_reg (mode1, op1);
14129
14130   pat = GEN_FCN (icode) (target, op0, op1);
14131   if (! pat)
14132     return 0;
14133   emit_insn (pat);
14134
14135   return target;
14136 }
14137
14138 static rtx
14139 altivec_expand_predicate_builtin (enum insn_code icode, tree exp, rtx target)
14140 {
14141   rtx pat, scratch;
14142   tree cr6_form = CALL_EXPR_ARG (exp, 0);
14143   tree arg0 = CALL_EXPR_ARG (exp, 1);
14144   tree arg1 = CALL_EXPR_ARG (exp, 2);
14145   rtx op0 = expand_normal (arg0);
14146   rtx op1 = expand_normal (arg1);
14147   machine_mode tmode = SImode;
14148   machine_mode mode0 = insn_data[icode].operand[1].mode;
14149   machine_mode mode1 = insn_data[icode].operand[2].mode;
14150   int cr6_form_int;
14151
14152   if (TREE_CODE (cr6_form) != INTEGER_CST)
14153     {
14154       error ("argument 1 of %qs must be a constant",
14155              "__builtin_altivec_predicate");
14156       return const0_rtx;
14157     }
14158   else
14159     cr6_form_int = TREE_INT_CST_LOW (cr6_form);
14160
14161   gcc_assert (mode0 == mode1);
14162
14163   /* If we have invalid arguments, bail out before generating bad rtl.  */
14164   if (arg0 == error_mark_node || arg1 == error_mark_node)
14165     return const0_rtx;
14166
14167   if (target == 0
14168       || GET_MODE (target) != tmode
14169       || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
14170     target = gen_reg_rtx (tmode);
14171
14172   if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
14173     op0 = copy_to_mode_reg (mode0, op0);
14174   if (! (*insn_data[icode].operand[2].predicate) (op1, mode1))
14175     op1 = copy_to_mode_reg (mode1, op1);
14176
14177   /* Note that for many of the relevant operations (e.g. cmpne or
14178      cmpeq) with float or double operands, it makes more sense for the
14179      mode of the allocated scratch register to select a vector of
14180      integer.  But the choice to copy the mode of operand 0 was made
14181      long ago and there are no plans to change it.  */
14182   scratch = gen_reg_rtx (mode0);
14183
14184   pat = GEN_FCN (icode) (scratch, op0, op1);
14185   if (! pat)
14186     return 0;
14187   emit_insn (pat);
14188
14189   /* The vec_any* and vec_all* predicates use the same opcodes for two
14190      different operations, but the bits in CR6 will be different
14191      depending on what information we want.  So we have to play tricks
14192      with CR6 to get the right bits out.
14193
14194      If you think this is disgusting, look at the specs for the
14195      AltiVec predicates.  */
14196
14197   switch (cr6_form_int)
14198     {
14199     case 0:
14200       emit_insn (gen_cr6_test_for_zero (target));
14201       break;
14202     case 1:
14203       emit_insn (gen_cr6_test_for_zero_reverse (target));
14204       break;
14205     case 2:
14206       emit_insn (gen_cr6_test_for_lt (target));
14207       break;
14208     case 3:
14209       emit_insn (gen_cr6_test_for_lt_reverse (target));
14210       break;
14211     default:
14212       error ("argument 1 of %qs is out of range",
14213              "__builtin_altivec_predicate");
14214       break;
14215     }
14216
14217   return target;
14218 }
14219
14220 static rtx
14221 paired_expand_lv_builtin (enum insn_code icode, tree exp, rtx target)
14222 {
14223   rtx pat, addr;
14224   tree arg0 = CALL_EXPR_ARG (exp, 0);
14225   tree arg1 = CALL_EXPR_ARG (exp, 1);
14226   machine_mode tmode = insn_data[icode].operand[0].mode;
14227   machine_mode mode0 = Pmode;
14228   machine_mode mode1 = Pmode;
14229   rtx op0 = expand_normal (arg0);
14230   rtx op1 = expand_normal (arg1);
14231
14232   if (icode == CODE_FOR_nothing)
14233     /* Builtin not supported on this processor.  */
14234     return 0;
14235
14236   /* If we got invalid arguments bail out before generating bad rtl.  */
14237   if (arg0 == error_mark_node || arg1 == error_mark_node)
14238     return const0_rtx;
14239
14240   if (target == 0
14241       || GET_MODE (target) != tmode
14242       || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
14243     target = gen_reg_rtx (tmode);
14244
14245   op1 = copy_to_mode_reg (mode1, op1);
14246
14247   if (op0 == const0_rtx)
14248     {
14249       addr = gen_rtx_MEM (tmode, op1);
14250     }
14251   else
14252     {
14253       op0 = copy_to_mode_reg (mode0, op0);
14254       addr = gen_rtx_MEM (tmode, gen_rtx_PLUS (Pmode, op0, op1));
14255     }
14256
14257   pat = GEN_FCN (icode) (target, addr);
14258
14259   if (! pat)
14260     return 0;
14261   emit_insn (pat);
14262
14263   return target;
14264 }
14265
14266 /* Return a constant vector for use as a little-endian permute control vector
14267    to reverse the order of elements of the given vector mode.  */
14268 static rtx
14269 swap_selector_for_mode (machine_mode mode)
14270 {
14271   /* These are little endian vectors, so their elements are reversed
14272      from what you would normally expect for a permute control vector.  */
14273   unsigned int swap2[16] = {7,6,5,4,3,2,1,0,15,14,13,12,11,10,9,8};
14274   unsigned int swap4[16] = {3,2,1,0,7,6,5,4,11,10,9,8,15,14,13,12};
14275   unsigned int swap8[16] = {1,0,3,2,5,4,7,6,9,8,11,10,13,12,15,14};
14276   unsigned int swap16[16] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
14277   unsigned int *swaparray, i;
14278   rtx perm[16];
14279
14280   switch (mode)
14281     {
14282     case E_V2DFmode:
14283     case E_V2DImode:
14284       swaparray = swap2;
14285       break;
14286     case E_V4SFmode:
14287     case E_V4SImode:
14288       swaparray = swap4;
14289       break;
14290     case E_V8HImode:
14291       swaparray = swap8;
14292       break;
14293     case E_V16QImode:
14294       swaparray = swap16;
14295       break;
14296     default:
14297       gcc_unreachable ();
14298     }
14299
14300   for (i = 0; i < 16; ++i)
14301     perm[i] = GEN_INT (swaparray[i]);
14302
14303   return force_reg (V16QImode, gen_rtx_CONST_VECTOR (V16QImode, gen_rtvec_v (16, perm)));
14304 }
14305
14306 rtx
14307 swap_endian_selector_for_mode (machine_mode mode)
14308 {
14309   unsigned int swap1[16] = {15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0};
14310   unsigned int swap2[16] = {7,6,5,4,3,2,1,0,15,14,13,12,11,10,9,8};
14311   unsigned int swap4[16] = {3,2,1,0,7,6,5,4,11,10,9,8,15,14,13,12};
14312   unsigned int swap8[16] = {1,0,3,2,5,4,7,6,9,8,11,10,13,12,15,14};
14313
14314   unsigned int *swaparray, i;
14315   rtx perm[16];
14316
14317   switch (mode)
14318     {
14319     case E_V1TImode:
14320       swaparray = swap1;
14321       break;
14322     case E_V2DFmode:
14323     case E_V2DImode:
14324       swaparray = swap2;
14325       break;
14326     case E_V4SFmode:
14327     case E_V4SImode:
14328       swaparray = swap4;
14329       break;
14330     case E_V8HImode:
14331       swaparray = swap8;
14332       break;
14333     default:
14334       gcc_unreachable ();
14335     }
14336
14337   for (i = 0; i < 16; ++i)
14338     perm[i] = GEN_INT (swaparray[i]);
14339
14340   return force_reg (V16QImode, gen_rtx_CONST_VECTOR (V16QImode,
14341                                                      gen_rtvec_v (16, perm)));
14342 }
14343
14344 /* Generate code for an "lvxl", or "lve*x" built-in for a little endian target
14345    with -maltivec=be specified.  Issue the load followed by an element-
14346    reversing permute.  */
14347 void
14348 altivec_expand_lvx_be (rtx op0, rtx op1, machine_mode mode, unsigned unspec)
14349 {
14350   rtx tmp = gen_reg_rtx (mode);
14351   rtx load = gen_rtx_SET (tmp, op1);
14352   rtx lvx = gen_rtx_UNSPEC (mode, gen_rtvec (1, const0_rtx), unspec);
14353   rtx par = gen_rtx_PARALLEL (mode, gen_rtvec (2, load, lvx));
14354   rtx sel = swap_selector_for_mode (mode);
14355   rtx vperm = gen_rtx_UNSPEC (mode, gen_rtvec (3, tmp, tmp, sel), UNSPEC_VPERM);
14356
14357   gcc_assert (REG_P (op0));
14358   emit_insn (par);
14359   emit_insn (gen_rtx_SET (op0, vperm));
14360 }
14361
14362 /* Generate code for a "stvxl" built-in for a little endian target with
14363    -maltivec=be specified.  Issue the store preceded by an element-reversing
14364    permute.  */
14365 void
14366 altivec_expand_stvx_be (rtx op0, rtx op1, machine_mode mode, unsigned unspec)
14367 {
14368   rtx tmp = gen_reg_rtx (mode);
14369   rtx store = gen_rtx_SET (op0, tmp);
14370   rtx stvx = gen_rtx_UNSPEC (mode, gen_rtvec (1, const0_rtx), unspec);
14371   rtx par = gen_rtx_PARALLEL (mode, gen_rtvec (2, store, stvx));
14372   rtx sel = swap_selector_for_mode (mode);
14373   rtx vperm;
14374
14375   gcc_assert (REG_P (op1));
14376   vperm = gen_rtx_UNSPEC (mode, gen_rtvec (3, op1, op1, sel), UNSPEC_VPERM);
14377   emit_insn (gen_rtx_SET (tmp, vperm));
14378   emit_insn (par);
14379 }
14380
14381 /* Generate code for a "stve*x" built-in for a little endian target with -maltivec=be
14382    specified.  Issue the store preceded by an element-reversing permute.  */
14383 void
14384 altivec_expand_stvex_be (rtx op0, rtx op1, machine_mode mode, unsigned unspec)
14385 {
14386   machine_mode inner_mode = GET_MODE_INNER (mode);
14387   rtx tmp = gen_reg_rtx (mode);
14388   rtx stvx = gen_rtx_UNSPEC (inner_mode, gen_rtvec (1, tmp), unspec);
14389   rtx sel = swap_selector_for_mode (mode);
14390   rtx vperm;
14391
14392   gcc_assert (REG_P (op1));
14393   vperm = gen_rtx_UNSPEC (mode, gen_rtvec (3, op1, op1, sel), UNSPEC_VPERM);
14394   emit_insn (gen_rtx_SET (tmp, vperm));
14395   emit_insn (gen_rtx_SET (op0, stvx));
14396 }
14397
14398 static rtx
14399 altivec_expand_lv_builtin (enum insn_code icode, tree exp, rtx target, bool blk)
14400 {
14401   rtx pat, addr;
14402   tree arg0 = CALL_EXPR_ARG (exp, 0);
14403   tree arg1 = CALL_EXPR_ARG (exp, 1);
14404   machine_mode tmode = insn_data[icode].operand[0].mode;
14405   machine_mode mode0 = Pmode;
14406   machine_mode mode1 = Pmode;
14407   rtx op0 = expand_normal (arg0);
14408   rtx op1 = expand_normal (arg1);
14409
14410   if (icode == CODE_FOR_nothing)
14411     /* Builtin not supported on this processor.  */
14412     return 0;
14413
14414   /* If we got invalid arguments bail out before generating bad rtl.  */
14415   if (arg0 == error_mark_node || arg1 == error_mark_node)
14416     return const0_rtx;
14417
14418   if (target == 0
14419       || GET_MODE (target) != tmode
14420       || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
14421     target = gen_reg_rtx (tmode);
14422
14423   op1 = copy_to_mode_reg (mode1, op1);
14424
14425   /* For LVX, express the RTL accurately by ANDing the address with -16.
14426      LVXL and LVE*X expand to use UNSPECs to hide their special behavior,
14427      so the raw address is fine.  */
14428   if (icode == CODE_FOR_altivec_lvx_v2df_2op
14429       || icode == CODE_FOR_altivec_lvx_v2di_2op
14430       || icode == CODE_FOR_altivec_lvx_v4sf_2op
14431       || icode == CODE_FOR_altivec_lvx_v4si_2op
14432       || icode == CODE_FOR_altivec_lvx_v8hi_2op
14433       || icode == CODE_FOR_altivec_lvx_v16qi_2op)
14434     {
14435       rtx rawaddr;
14436       if (op0 == const0_rtx)
14437         rawaddr = op1;
14438       else
14439         {
14440           op0 = copy_to_mode_reg (mode0, op0);
14441           rawaddr = gen_rtx_PLUS (Pmode, op1, op0);
14442         }
14443       addr = gen_rtx_AND (Pmode, rawaddr, gen_rtx_CONST_INT (Pmode, -16));
14444       addr = gen_rtx_MEM (blk ? BLKmode : tmode, addr);
14445
14446       /* For -maltivec=be, emit the load and follow it up with a
14447          permute to swap the elements.  */
14448       if (!BYTES_BIG_ENDIAN && VECTOR_ELT_ORDER_BIG)
14449         {
14450           rtx temp = gen_reg_rtx (tmode);
14451           emit_insn (gen_rtx_SET (temp, addr));
14452
14453           rtx sel = swap_selector_for_mode (tmode);
14454           rtx vperm = gen_rtx_UNSPEC (tmode, gen_rtvec (3, temp, temp, sel),
14455                                       UNSPEC_VPERM);
14456           emit_insn (gen_rtx_SET (target, vperm));
14457         }
14458       else
14459         emit_insn (gen_rtx_SET (target, addr));
14460     }
14461   else
14462     {
14463       if (op0 == const0_rtx)
14464         addr = gen_rtx_MEM (blk ? BLKmode : tmode, op1);
14465       else
14466         {
14467           op0 = copy_to_mode_reg (mode0, op0);
14468           addr = gen_rtx_MEM (blk ? BLKmode : tmode,
14469                               gen_rtx_PLUS (Pmode, op1, op0));
14470         }
14471
14472       pat = GEN_FCN (icode) (target, addr);
14473       if (! pat)
14474         return 0;
14475       emit_insn (pat);
14476     }
14477
14478   return target;
14479 }
14480
14481 static rtx
14482 paired_expand_stv_builtin (enum insn_code icode, tree exp)
14483 {
14484   tree arg0 = CALL_EXPR_ARG (exp, 0);
14485   tree arg1 = CALL_EXPR_ARG (exp, 1);
14486   tree arg2 = CALL_EXPR_ARG (exp, 2);
14487   rtx op0 = expand_normal (arg0);
14488   rtx op1 = expand_normal (arg1);
14489   rtx op2 = expand_normal (arg2);
14490   rtx pat, addr;
14491   machine_mode tmode = insn_data[icode].operand[0].mode;
14492   machine_mode mode1 = Pmode;
14493   machine_mode mode2 = Pmode;
14494
14495   /* Invalid arguments.  Bail before doing anything stoopid!  */
14496   if (arg0 == error_mark_node
14497       || arg1 == error_mark_node
14498       || arg2 == error_mark_node)
14499     return const0_rtx;
14500
14501   if (! (*insn_data[icode].operand[1].predicate) (op0, tmode))
14502     op0 = copy_to_mode_reg (tmode, op0);
14503
14504   op2 = copy_to_mode_reg (mode2, op2);
14505
14506   if (op1 == const0_rtx)
14507     {
14508       addr = gen_rtx_MEM (tmode, op2);
14509     }
14510   else
14511     {
14512       op1 = copy_to_mode_reg (mode1, op1);
14513       addr = gen_rtx_MEM (tmode, gen_rtx_PLUS (Pmode, op1, op2));
14514     }
14515
14516   pat = GEN_FCN (icode) (addr, op0);
14517   if (pat)
14518     emit_insn (pat);
14519   return NULL_RTX;
14520 }
14521
14522 static rtx
14523 altivec_expand_stxvl_builtin (enum insn_code icode, tree exp)
14524 {
14525   rtx pat;
14526   tree arg0 = CALL_EXPR_ARG (exp, 0);
14527   tree arg1 = CALL_EXPR_ARG (exp, 1);
14528   tree arg2 = CALL_EXPR_ARG (exp, 2);
14529   rtx op0 = expand_normal (arg0);
14530   rtx op1 = expand_normal (arg1);
14531   rtx op2 = expand_normal (arg2);
14532   machine_mode mode0 = insn_data[icode].operand[0].mode;
14533   machine_mode mode1 = insn_data[icode].operand[1].mode;
14534   machine_mode mode2 = insn_data[icode].operand[2].mode;
14535
14536   if (icode == CODE_FOR_nothing)
14537     /* Builtin not supported on this processor.  */
14538     return NULL_RTX;
14539
14540   /* If we got invalid arguments bail out before generating bad rtl.  */
14541   if (arg0 == error_mark_node
14542       || arg1 == error_mark_node
14543       || arg2 == error_mark_node)
14544     return NULL_RTX;
14545
14546   if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
14547     op0 = copy_to_mode_reg (mode0, op0);
14548   if (! (*insn_data[icode].operand[2].predicate) (op1, mode1))
14549     op1 = copy_to_mode_reg (mode1, op1);
14550   if (! (*insn_data[icode].operand[3].predicate) (op2, mode2))
14551     op2 = copy_to_mode_reg (mode2, op2);
14552
14553   pat = GEN_FCN (icode) (op0, op1, op2);
14554   if (pat)
14555     emit_insn (pat);
14556
14557   return NULL_RTX;
14558 }
14559
14560 static rtx
14561 altivec_expand_stv_builtin (enum insn_code icode, tree exp)
14562 {
14563   tree arg0 = CALL_EXPR_ARG (exp, 0);
14564   tree arg1 = CALL_EXPR_ARG (exp, 1);
14565   tree arg2 = CALL_EXPR_ARG (exp, 2);
14566   rtx op0 = expand_normal (arg0);
14567   rtx op1 = expand_normal (arg1);
14568   rtx op2 = expand_normal (arg2);
14569   rtx pat, addr, rawaddr;
14570   machine_mode tmode = insn_data[icode].operand[0].mode;
14571   machine_mode smode = insn_data[icode].operand[1].mode;
14572   machine_mode mode1 = Pmode;
14573   machine_mode mode2 = Pmode;
14574
14575   /* Invalid arguments.  Bail before doing anything stoopid!  */
14576   if (arg0 == error_mark_node
14577       || arg1 == error_mark_node
14578       || arg2 == error_mark_node)
14579     return const0_rtx;
14580
14581   op2 = copy_to_mode_reg (mode2, op2);
14582
14583   /* For STVX, express the RTL accurately by ANDing the address with -16.
14584      STVXL and STVE*X expand to use UNSPECs to hide their special behavior,
14585      so the raw address is fine.  */
14586   if (icode == CODE_FOR_altivec_stvx_v2df_2op
14587       || icode == CODE_FOR_altivec_stvx_v2di_2op
14588       || icode == CODE_FOR_altivec_stvx_v4sf_2op
14589       || icode == CODE_FOR_altivec_stvx_v4si_2op
14590       || icode == CODE_FOR_altivec_stvx_v8hi_2op
14591       || icode == CODE_FOR_altivec_stvx_v16qi_2op)
14592     {
14593       if (op1 == const0_rtx)
14594         rawaddr = op2;
14595       else
14596         {
14597           op1 = copy_to_mode_reg (mode1, op1);
14598           rawaddr = gen_rtx_PLUS (Pmode, op2, op1);
14599         }
14600
14601       addr = gen_rtx_AND (Pmode, rawaddr, gen_rtx_CONST_INT (Pmode, -16));
14602       addr = gen_rtx_MEM (tmode, addr);
14603
14604       op0 = copy_to_mode_reg (tmode, op0);
14605
14606       /* For -maltivec=be, emit a permute to swap the elements, followed
14607         by the store.  */
14608      if (!BYTES_BIG_ENDIAN && VECTOR_ELT_ORDER_BIG)
14609         {
14610           rtx temp = gen_reg_rtx (tmode);
14611           rtx sel = swap_selector_for_mode (tmode);
14612           rtx vperm = gen_rtx_UNSPEC (tmode, gen_rtvec (3, op0, op0, sel),
14613                                       UNSPEC_VPERM);
14614           emit_insn (gen_rtx_SET (temp, vperm));
14615           emit_insn (gen_rtx_SET (addr, temp));
14616         }
14617       else
14618         emit_insn (gen_rtx_SET (addr, op0));
14619     }
14620   else
14621     {
14622       if (! (*insn_data[icode].operand[1].predicate) (op0, smode))
14623         op0 = copy_to_mode_reg (smode, op0);
14624
14625       if (op1 == const0_rtx)
14626         addr = gen_rtx_MEM (tmode, op2);
14627       else
14628         {
14629           op1 = copy_to_mode_reg (mode1, op1);
14630           addr = gen_rtx_MEM (tmode, gen_rtx_PLUS (Pmode, op2, op1));
14631         }
14632
14633       pat = GEN_FCN (icode) (addr, op0);
14634       if (pat)
14635         emit_insn (pat);
14636     }
14637
14638   return NULL_RTX;
14639 }
14640
14641 /* Return the appropriate SPR number associated with the given builtin.  */
14642 static inline HOST_WIDE_INT
14643 htm_spr_num (enum rs6000_builtins code)
14644 {
14645   if (code == HTM_BUILTIN_GET_TFHAR
14646       || code == HTM_BUILTIN_SET_TFHAR)
14647     return TFHAR_SPR;
14648   else if (code == HTM_BUILTIN_GET_TFIAR
14649            || code == HTM_BUILTIN_SET_TFIAR)
14650     return TFIAR_SPR;
14651   else if (code == HTM_BUILTIN_GET_TEXASR
14652            || code == HTM_BUILTIN_SET_TEXASR)
14653     return TEXASR_SPR;
14654   gcc_assert (code == HTM_BUILTIN_GET_TEXASRU
14655               || code == HTM_BUILTIN_SET_TEXASRU);
14656   return TEXASRU_SPR;
14657 }
14658
14659 /* Return the appropriate SPR regno associated with the given builtin.  */
14660 static inline HOST_WIDE_INT
14661 htm_spr_regno (enum rs6000_builtins code)
14662 {
14663   if (code == HTM_BUILTIN_GET_TFHAR
14664       || code == HTM_BUILTIN_SET_TFHAR)
14665     return TFHAR_REGNO;
14666   else if (code == HTM_BUILTIN_GET_TFIAR
14667            || code == HTM_BUILTIN_SET_TFIAR)
14668     return TFIAR_REGNO;
14669   gcc_assert (code == HTM_BUILTIN_GET_TEXASR
14670               || code == HTM_BUILTIN_SET_TEXASR
14671               || code == HTM_BUILTIN_GET_TEXASRU
14672               || code == HTM_BUILTIN_SET_TEXASRU);
14673   return TEXASR_REGNO;
14674 }
14675
14676 /* Return the correct ICODE value depending on whether we are
14677    setting or reading the HTM SPRs.  */
14678 static inline enum insn_code
14679 rs6000_htm_spr_icode (bool nonvoid)
14680 {
14681   if (nonvoid)
14682     return (TARGET_POWERPC64) ? CODE_FOR_htm_mfspr_di : CODE_FOR_htm_mfspr_si;
14683   else
14684     return (TARGET_POWERPC64) ? CODE_FOR_htm_mtspr_di : CODE_FOR_htm_mtspr_si;
14685 }
14686
14687 /* Expand the HTM builtin in EXP and store the result in TARGET.
14688    Store true in *EXPANDEDP if we found a builtin to expand.  */
14689 static rtx
14690 htm_expand_builtin (tree exp, rtx target, bool * expandedp)
14691 {
14692   tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
14693   bool nonvoid = TREE_TYPE (TREE_TYPE (fndecl)) != void_type_node;
14694   enum rs6000_builtins fcode = (enum rs6000_builtins) DECL_FUNCTION_CODE (fndecl);
14695   const struct builtin_description *d;
14696   size_t i;
14697
14698   *expandedp = true;
14699
14700   if (!TARGET_POWERPC64
14701       && (fcode == HTM_BUILTIN_TABORTDC
14702           || fcode == HTM_BUILTIN_TABORTDCI))
14703     {
14704       size_t uns_fcode = (size_t)fcode;
14705       const char *name = rs6000_builtin_info[uns_fcode].name;
14706       error ("builtin %qs is only valid in 64-bit mode", name);
14707       return const0_rtx;
14708     }
14709
14710   /* Expand the HTM builtins.  */
14711   d = bdesc_htm;
14712   for (i = 0; i < ARRAY_SIZE (bdesc_htm); i++, d++)
14713     if (d->code == fcode)
14714       {
14715         rtx op[MAX_HTM_OPERANDS], pat;
14716         int nopnds = 0;
14717         tree arg;
14718         call_expr_arg_iterator iter;
14719         unsigned attr = rs6000_builtin_info[fcode].attr;
14720         enum insn_code icode = d->icode;
14721         const struct insn_operand_data *insn_op;
14722         bool uses_spr = (attr & RS6000_BTC_SPR);
14723         rtx cr = NULL_RTX;
14724
14725         if (uses_spr)
14726           icode = rs6000_htm_spr_icode (nonvoid);
14727         insn_op = &insn_data[icode].operand[0];
14728
14729         if (nonvoid)
14730           {
14731             machine_mode tmode = (uses_spr) ? insn_op->mode : E_SImode;
14732             if (!target
14733                 || GET_MODE (target) != tmode
14734                 || (uses_spr && !(*insn_op->predicate) (target, tmode)))
14735               target = gen_reg_rtx (tmode);
14736             if (uses_spr)
14737               op[nopnds++] = target;
14738           }
14739
14740         FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
14741         {
14742           if (arg == error_mark_node || nopnds >= MAX_HTM_OPERANDS)
14743             return const0_rtx;
14744
14745           insn_op = &insn_data[icode].operand[nopnds];
14746
14747           op[nopnds] = expand_normal (arg);
14748
14749           if (!(*insn_op->predicate) (op[nopnds], insn_op->mode))
14750             {
14751               if (!strcmp (insn_op->constraint, "n"))
14752                 {
14753                   int arg_num = (nonvoid) ? nopnds : nopnds + 1;
14754                   if (!CONST_INT_P (op[nopnds]))
14755                     error ("argument %d must be an unsigned literal", arg_num);
14756                   else
14757                     error ("argument %d is an unsigned literal that is "
14758                            "out of range", arg_num);
14759                   return const0_rtx;
14760                 }
14761               op[nopnds] = copy_to_mode_reg (insn_op->mode, op[nopnds]);
14762             }
14763
14764           nopnds++;
14765         }
14766
14767         /* Handle the builtins for extended mnemonics.  These accept
14768            no arguments, but map to builtins that take arguments.  */
14769         switch (fcode)
14770           {
14771           case HTM_BUILTIN_TENDALL:  /* Alias for: tend. 1  */
14772           case HTM_BUILTIN_TRESUME:  /* Alias for: tsr. 1  */
14773             op[nopnds++] = GEN_INT (1);
14774             if (flag_checking)
14775               attr |= RS6000_BTC_UNARY;
14776             break;
14777           case HTM_BUILTIN_TSUSPEND: /* Alias for: tsr. 0  */
14778             op[nopnds++] = GEN_INT (0);
14779             if (flag_checking)
14780               attr |= RS6000_BTC_UNARY;
14781             break;
14782           default:
14783             break;
14784           }
14785
14786         /* If this builtin accesses SPRs, then pass in the appropriate
14787            SPR number and SPR regno as the last two operands.  */
14788         if (uses_spr)
14789           {
14790             machine_mode mode = (TARGET_POWERPC64) ? DImode : SImode;
14791             op[nopnds++] = gen_rtx_CONST_INT (mode, htm_spr_num (fcode));
14792             op[nopnds++] = gen_rtx_REG (mode, htm_spr_regno (fcode));
14793           }
14794         /* If this builtin accesses a CR, then pass in a scratch
14795            CR as the last operand.  */
14796         else if (attr & RS6000_BTC_CR)
14797           { cr = gen_reg_rtx (CCmode);
14798             op[nopnds++] = cr;
14799           }
14800
14801         if (flag_checking)
14802           {
14803             int expected_nopnds = 0;
14804             if ((attr & RS6000_BTC_TYPE_MASK) == RS6000_BTC_UNARY)
14805               expected_nopnds = 1;
14806             else if ((attr & RS6000_BTC_TYPE_MASK) == RS6000_BTC_BINARY)
14807               expected_nopnds = 2;
14808             else if ((attr & RS6000_BTC_TYPE_MASK) == RS6000_BTC_TERNARY)
14809               expected_nopnds = 3;
14810             if (!(attr & RS6000_BTC_VOID))
14811               expected_nopnds += 1;
14812             if (uses_spr)
14813               expected_nopnds += 2;
14814
14815             gcc_assert (nopnds == expected_nopnds
14816                         && nopnds <= MAX_HTM_OPERANDS);
14817           }
14818
14819         switch (nopnds)
14820           {
14821           case 1:
14822             pat = GEN_FCN (icode) (op[0]);
14823             break;
14824           case 2:
14825             pat = GEN_FCN (icode) (op[0], op[1]);
14826             break;
14827           case 3:
14828             pat = GEN_FCN (icode) (op[0], op[1], op[2]);
14829             break;
14830           case 4:
14831             pat = GEN_FCN (icode) (op[0], op[1], op[2], op[3]);
14832             break;
14833           default:
14834             gcc_unreachable ();
14835           }
14836         if (!pat)
14837           return NULL_RTX;
14838         emit_insn (pat);
14839
14840         if (attr & RS6000_BTC_CR)
14841           {
14842             if (fcode == HTM_BUILTIN_TBEGIN)
14843               {
14844                 /* Emit code to set TARGET to true or false depending on
14845                    whether the tbegin. instruction successfully or failed
14846                    to start a transaction.  We do this by placing the 1's
14847                    complement of CR's EQ bit into TARGET.  */
14848                 rtx scratch = gen_reg_rtx (SImode);
14849                 emit_insn (gen_rtx_SET (scratch,
14850                                         gen_rtx_EQ (SImode, cr,
14851                                                      const0_rtx)));
14852                 emit_insn (gen_rtx_SET (target,
14853                                         gen_rtx_XOR (SImode, scratch,
14854                                                      GEN_INT (1))));
14855               }
14856             else
14857               {
14858                 /* Emit code to copy the 4-bit condition register field
14859                    CR into the least significant end of register TARGET.  */
14860                 rtx scratch1 = gen_reg_rtx (SImode);
14861                 rtx scratch2 = gen_reg_rtx (SImode);
14862                 rtx subreg = simplify_gen_subreg (CCmode, scratch1, SImode, 0);
14863                 emit_insn (gen_movcc (subreg, cr));
14864                 emit_insn (gen_lshrsi3 (scratch2, scratch1, GEN_INT (28)));
14865                 emit_insn (gen_andsi3 (target, scratch2, GEN_INT (0xf)));
14866               }
14867           }
14868
14869         if (nonvoid)
14870           return target;
14871         return const0_rtx;
14872       }
14873
14874   *expandedp = false;
14875   return NULL_RTX;
14876 }
14877
14878 /* Expand the CPU builtin in FCODE and store the result in TARGET.  */
14879
14880 static rtx
14881 cpu_expand_builtin (enum rs6000_builtins fcode, tree exp ATTRIBUTE_UNUSED,
14882                     rtx target)
14883 {
14884   /* __builtin_cpu_init () is a nop, so expand to nothing.  */
14885   if (fcode == RS6000_BUILTIN_CPU_INIT)
14886     return const0_rtx;
14887
14888   if (target == 0 || GET_MODE (target) != SImode)
14889     target = gen_reg_rtx (SImode);
14890
14891 #ifdef TARGET_LIBC_PROVIDES_HWCAP_IN_TCB
14892   tree arg = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
14893   /* Target clones creates an ARRAY_REF instead of STRING_CST, convert it back
14894      to a STRING_CST.  */
14895   if (TREE_CODE (arg) == ARRAY_REF
14896       && TREE_CODE (TREE_OPERAND (arg, 0)) == STRING_CST
14897       && TREE_CODE (TREE_OPERAND (arg, 1)) == INTEGER_CST
14898       && compare_tree_int (TREE_OPERAND (arg, 1), 0) == 0)
14899     arg = TREE_OPERAND (arg, 0);
14900
14901   if (TREE_CODE (arg) != STRING_CST)
14902     {
14903       error ("builtin %qs only accepts a string argument",
14904              rs6000_builtin_info[(size_t) fcode].name);
14905       return const0_rtx;
14906     }
14907
14908   if (fcode == RS6000_BUILTIN_CPU_IS)
14909     {
14910       const char *cpu = TREE_STRING_POINTER (arg);
14911       rtx cpuid = NULL_RTX;
14912       for (size_t i = 0; i < ARRAY_SIZE (cpu_is_info); i++)
14913         if (strcmp (cpu, cpu_is_info[i].cpu) == 0)
14914           {
14915             /* The CPUID value in the TCB is offset by _DL_FIRST_PLATFORM.  */
14916             cpuid = GEN_INT (cpu_is_info[i].cpuid + _DL_FIRST_PLATFORM);
14917             break;
14918           }
14919       if (cpuid == NULL_RTX)
14920         {
14921           /* Invalid CPU argument.  */
14922           error ("cpu %qs is an invalid argument to builtin %qs",
14923                  cpu, rs6000_builtin_info[(size_t) fcode].name);
14924           return const0_rtx;
14925         }
14926
14927       rtx platform = gen_reg_rtx (SImode);
14928       rtx tcbmem = gen_const_mem (SImode,
14929                                   gen_rtx_PLUS (Pmode,
14930                                                 gen_rtx_REG (Pmode, TLS_REGNUM),
14931                                                 GEN_INT (TCB_PLATFORM_OFFSET)));
14932       emit_move_insn (platform, tcbmem);
14933       emit_insn (gen_eqsi3 (target, platform, cpuid));
14934     }
14935   else if (fcode == RS6000_BUILTIN_CPU_SUPPORTS)
14936     {
14937       const char *hwcap = TREE_STRING_POINTER (arg);
14938       rtx mask = NULL_RTX;
14939       int hwcap_offset;
14940       for (size_t i = 0; i < ARRAY_SIZE (cpu_supports_info); i++)
14941         if (strcmp (hwcap, cpu_supports_info[i].hwcap) == 0)
14942           {
14943             mask = GEN_INT (cpu_supports_info[i].mask);
14944             hwcap_offset = TCB_HWCAP_OFFSET (cpu_supports_info[i].id);
14945             break;
14946           }
14947       if (mask == NULL_RTX)
14948         {
14949           /* Invalid HWCAP argument.  */
14950           error ("%s %qs is an invalid argument to builtin %qs",
14951                  "hwcap", hwcap, rs6000_builtin_info[(size_t) fcode].name);
14952           return const0_rtx;
14953         }
14954
14955       rtx tcb_hwcap = gen_reg_rtx (SImode);
14956       rtx tcbmem = gen_const_mem (SImode,
14957                                   gen_rtx_PLUS (Pmode,
14958                                                 gen_rtx_REG (Pmode, TLS_REGNUM),
14959                                                 GEN_INT (hwcap_offset)));
14960       emit_move_insn (tcb_hwcap, tcbmem);
14961       rtx scratch1 = gen_reg_rtx (SImode);
14962       emit_insn (gen_rtx_SET (scratch1, gen_rtx_AND (SImode, tcb_hwcap, mask)));
14963       rtx scratch2 = gen_reg_rtx (SImode);
14964       emit_insn (gen_eqsi3 (scratch2, scratch1, const0_rtx));
14965       emit_insn (gen_rtx_SET (target, gen_rtx_XOR (SImode, scratch2, const1_rtx)));
14966     }
14967   else
14968     gcc_unreachable ();
14969
14970   /* Record that we have expanded a CPU builtin, so that we can later
14971      emit a reference to the special symbol exported by LIBC to ensure we
14972      do not link against an old LIBC that doesn't support this feature.  */
14973   cpu_builtin_p = true;
14974
14975 #else
14976   warning (0, "builtin %qs needs GLIBC (2.23 and newer) that exports hardware "
14977            "capability bits", rs6000_builtin_info[(size_t) fcode].name);
14978   
14979   /* For old LIBCs, always return FALSE.  */
14980   emit_move_insn (target, GEN_INT (0));
14981 #endif /* TARGET_LIBC_PROVIDES_HWCAP_IN_TCB */
14982
14983   return target;
14984 }
14985
14986 static rtx
14987 rs6000_expand_ternop_builtin (enum insn_code icode, tree exp, rtx target)
14988 {
14989   rtx pat;
14990   tree arg0 = CALL_EXPR_ARG (exp, 0);
14991   tree arg1 = CALL_EXPR_ARG (exp, 1);
14992   tree arg2 = CALL_EXPR_ARG (exp, 2);
14993   rtx op0 = expand_normal (arg0);
14994   rtx op1 = expand_normal (arg1);
14995   rtx op2 = expand_normal (arg2);
14996   machine_mode tmode = insn_data[icode].operand[0].mode;
14997   machine_mode mode0 = insn_data[icode].operand[1].mode;
14998   machine_mode mode1 = insn_data[icode].operand[2].mode;
14999   machine_mode mode2 = insn_data[icode].operand[3].mode;
15000
15001   if (icode == CODE_FOR_nothing)
15002     /* Builtin not supported on this processor.  */
15003     return 0;
15004
15005   /* If we got invalid arguments bail out before generating bad rtl.  */
15006   if (arg0 == error_mark_node
15007       || arg1 == error_mark_node
15008       || arg2 == error_mark_node)
15009     return const0_rtx;
15010
15011   /* Check and prepare argument depending on the instruction code.
15012
15013      Note that a switch statement instead of the sequence of tests
15014      would be incorrect as many of the CODE_FOR values could be
15015      CODE_FOR_nothing and that would yield multiple alternatives
15016      with identical values.  We'd never reach here at runtime in
15017      this case.  */
15018   if (icode == CODE_FOR_altivec_vsldoi_v4sf
15019       || icode == CODE_FOR_altivec_vsldoi_v2df
15020       || icode == CODE_FOR_altivec_vsldoi_v4si
15021       || icode == CODE_FOR_altivec_vsldoi_v8hi
15022       || icode == CODE_FOR_altivec_vsldoi_v16qi)
15023     {
15024       /* Only allow 4-bit unsigned literals.  */
15025       STRIP_NOPS (arg2);
15026       if (TREE_CODE (arg2) != INTEGER_CST
15027           || TREE_INT_CST_LOW (arg2) & ~0xf)
15028         {
15029           error ("argument 3 must be a 4-bit unsigned literal");
15030           return CONST0_RTX (tmode);
15031         }
15032     }
15033   else if (icode == CODE_FOR_vsx_xxpermdi_v2df
15034            || icode == CODE_FOR_vsx_xxpermdi_v2di
15035            || icode == CODE_FOR_vsx_xxpermdi_v2df_be
15036            || icode == CODE_FOR_vsx_xxpermdi_v2di_be
15037            || icode == CODE_FOR_vsx_xxpermdi_v1ti
15038            || icode == CODE_FOR_vsx_xxpermdi_v4sf
15039            || icode == CODE_FOR_vsx_xxpermdi_v4si
15040            || icode == CODE_FOR_vsx_xxpermdi_v8hi
15041            || icode == CODE_FOR_vsx_xxpermdi_v16qi
15042            || icode == CODE_FOR_vsx_xxsldwi_v16qi
15043            || icode == CODE_FOR_vsx_xxsldwi_v8hi
15044            || icode == CODE_FOR_vsx_xxsldwi_v4si
15045            || icode == CODE_FOR_vsx_xxsldwi_v4sf
15046            || icode == CODE_FOR_vsx_xxsldwi_v2di
15047            || icode == CODE_FOR_vsx_xxsldwi_v2df)
15048     {
15049       /* Only allow 2-bit unsigned literals.  */
15050       STRIP_NOPS (arg2);
15051       if (TREE_CODE (arg2) != INTEGER_CST
15052           || TREE_INT_CST_LOW (arg2) & ~0x3)
15053         {
15054           error ("argument 3 must be a 2-bit unsigned literal");
15055           return CONST0_RTX (tmode);
15056         }
15057     }
15058   else if (icode == CODE_FOR_vsx_set_v2df
15059            || icode == CODE_FOR_vsx_set_v2di
15060            || icode == CODE_FOR_bcdadd
15061            || icode == CODE_FOR_bcdadd_lt
15062            || icode == CODE_FOR_bcdadd_eq
15063            || icode == CODE_FOR_bcdadd_gt
15064            || icode == CODE_FOR_bcdsub
15065            || icode == CODE_FOR_bcdsub_lt
15066            || icode == CODE_FOR_bcdsub_eq
15067            || icode == CODE_FOR_bcdsub_gt)
15068     {
15069       /* Only allow 1-bit unsigned literals.  */
15070       STRIP_NOPS (arg2);
15071       if (TREE_CODE (arg2) != INTEGER_CST
15072           || TREE_INT_CST_LOW (arg2) & ~0x1)
15073         {
15074           error ("argument 3 must be a 1-bit unsigned literal");
15075           return CONST0_RTX (tmode);
15076         }
15077     }
15078   else if (icode == CODE_FOR_dfp_ddedpd_dd
15079            || icode == CODE_FOR_dfp_ddedpd_td)
15080     {
15081       /* Only allow 2-bit unsigned literals where the value is 0 or 2.  */
15082       STRIP_NOPS (arg0);
15083       if (TREE_CODE (arg0) != INTEGER_CST
15084           || TREE_INT_CST_LOW (arg2) & ~0x3)
15085         {
15086           error ("argument 1 must be 0 or 2");
15087           return CONST0_RTX (tmode);
15088         }
15089     }
15090   else if (icode == CODE_FOR_dfp_denbcd_dd
15091            || icode == CODE_FOR_dfp_denbcd_td)
15092     {
15093       /* Only allow 1-bit unsigned literals.  */
15094       STRIP_NOPS (arg0);
15095       if (TREE_CODE (arg0) != INTEGER_CST
15096           || TREE_INT_CST_LOW (arg0) & ~0x1)
15097         {
15098           error ("argument 1 must be a 1-bit unsigned literal");
15099           return CONST0_RTX (tmode);
15100         }
15101     }
15102   else if (icode == CODE_FOR_dfp_dscli_dd
15103            || icode == CODE_FOR_dfp_dscli_td
15104            || icode == CODE_FOR_dfp_dscri_dd
15105            || icode == CODE_FOR_dfp_dscri_td)
15106     {
15107       /* Only allow 6-bit unsigned literals.  */
15108       STRIP_NOPS (arg1);
15109       if (TREE_CODE (arg1) != INTEGER_CST
15110           || TREE_INT_CST_LOW (arg1) & ~0x3f)
15111         {
15112           error ("argument 2 must be a 6-bit unsigned literal");
15113           return CONST0_RTX (tmode);
15114         }
15115     }
15116   else if (icode == CODE_FOR_crypto_vshasigmaw
15117            || icode == CODE_FOR_crypto_vshasigmad)
15118     {
15119       /* Check whether the 2nd and 3rd arguments are integer constants and in
15120          range and prepare arguments.  */
15121       STRIP_NOPS (arg1);
15122       if (TREE_CODE (arg1) != INTEGER_CST || wi::geu_p (wi::to_wide (arg1), 2))
15123         {
15124           error ("argument 2 must be 0 or 1");
15125           return CONST0_RTX (tmode);
15126         }
15127
15128       STRIP_NOPS (arg2);
15129       if (TREE_CODE (arg2) != INTEGER_CST
15130           || wi::geu_p (wi::to_wide (arg2), 16))
15131         {
15132           error ("argument 3 must be in the range 0..15");
15133           return CONST0_RTX (tmode);
15134         }
15135     }
15136
15137   if (target == 0
15138       || GET_MODE (target) != tmode
15139       || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
15140     target = gen_reg_rtx (tmode);
15141
15142   if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
15143     op0 = copy_to_mode_reg (mode0, op0);
15144   if (! (*insn_data[icode].operand[2].predicate) (op1, mode1))
15145     op1 = copy_to_mode_reg (mode1, op1);
15146   if (! (*insn_data[icode].operand[3].predicate) (op2, mode2))
15147     op2 = copy_to_mode_reg (mode2, op2);
15148
15149   if (TARGET_PAIRED_FLOAT && icode == CODE_FOR_selv2sf4)
15150     pat = GEN_FCN (icode) (target, op0, op1, op2, CONST0_RTX (SFmode));
15151   else 
15152     pat = GEN_FCN (icode) (target, op0, op1, op2);
15153   if (! pat)
15154     return 0;
15155   emit_insn (pat);
15156
15157   return target;
15158 }
15159
15160 /* Expand the lvx builtins.  */
15161 static rtx
15162 altivec_expand_ld_builtin (tree exp, rtx target, bool *expandedp)
15163 {
15164   tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
15165   unsigned int fcode = DECL_FUNCTION_CODE (fndecl);
15166   tree arg0;
15167   machine_mode tmode, mode0;
15168   rtx pat, op0;
15169   enum insn_code icode;
15170
15171   switch (fcode)
15172     {
15173     case ALTIVEC_BUILTIN_LD_INTERNAL_16qi:
15174       icode = CODE_FOR_vector_altivec_load_v16qi;
15175       break;
15176     case ALTIVEC_BUILTIN_LD_INTERNAL_8hi:
15177       icode = CODE_FOR_vector_altivec_load_v8hi;
15178       break;
15179     case ALTIVEC_BUILTIN_LD_INTERNAL_4si:
15180       icode = CODE_FOR_vector_altivec_load_v4si;
15181       break;
15182     case ALTIVEC_BUILTIN_LD_INTERNAL_4sf:
15183       icode = CODE_FOR_vector_altivec_load_v4sf;
15184       break;
15185     case ALTIVEC_BUILTIN_LD_INTERNAL_2df:
15186       icode = CODE_FOR_vector_altivec_load_v2df;
15187       break;
15188     case ALTIVEC_BUILTIN_LD_INTERNAL_2di:
15189       icode = CODE_FOR_vector_altivec_load_v2di;
15190       break;
15191     case ALTIVEC_BUILTIN_LD_INTERNAL_1ti:
15192       icode = CODE_FOR_vector_altivec_load_v1ti;
15193       break;
15194     default:
15195       *expandedp = false;
15196       return NULL_RTX;
15197     }
15198
15199   *expandedp = true;
15200
15201   arg0 = CALL_EXPR_ARG (exp, 0);
15202   op0 = expand_normal (arg0);
15203   tmode = insn_data[icode].operand[0].mode;
15204   mode0 = insn_data[icode].operand[1].mode;
15205
15206   if (target == 0
15207       || GET_MODE (target) != tmode
15208       || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
15209     target = gen_reg_rtx (tmode);
15210
15211   if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
15212     op0 = gen_rtx_MEM (mode0, copy_to_mode_reg (Pmode, op0));
15213
15214   pat = GEN_FCN (icode) (target, op0);
15215   if (! pat)
15216     return 0;
15217   emit_insn (pat);
15218   return target;
15219 }
15220
15221 /* Expand the stvx builtins.  */
15222 static rtx
15223 altivec_expand_st_builtin (tree exp, rtx target ATTRIBUTE_UNUSED,
15224                            bool *expandedp)
15225 {
15226   tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
15227   unsigned int fcode = DECL_FUNCTION_CODE (fndecl);
15228   tree arg0, arg1;
15229   machine_mode mode0, mode1;
15230   rtx pat, op0, op1;
15231   enum insn_code icode;
15232
15233   switch (fcode)
15234     {
15235     case ALTIVEC_BUILTIN_ST_INTERNAL_16qi:
15236       icode = CODE_FOR_vector_altivec_store_v16qi;
15237       break;
15238     case ALTIVEC_BUILTIN_ST_INTERNAL_8hi:
15239       icode = CODE_FOR_vector_altivec_store_v8hi;
15240       break;
15241     case ALTIVEC_BUILTIN_ST_INTERNAL_4si:
15242       icode = CODE_FOR_vector_altivec_store_v4si;
15243       break;
15244     case ALTIVEC_BUILTIN_ST_INTERNAL_4sf:
15245       icode = CODE_FOR_vector_altivec_store_v4sf;
15246       break;
15247     case ALTIVEC_BUILTIN_ST_INTERNAL_2df:
15248       icode = CODE_FOR_vector_altivec_store_v2df;
15249       break;
15250     case ALTIVEC_BUILTIN_ST_INTERNAL_2di:
15251       icode = CODE_FOR_vector_altivec_store_v2di;
15252       break;
15253     case ALTIVEC_BUILTIN_ST_INTERNAL_1ti:
15254       icode = CODE_FOR_vector_altivec_store_v1ti;
15255       break;
15256     default:
15257       *expandedp = false;
15258       return NULL_RTX;
15259     }
15260
15261   arg0 = CALL_EXPR_ARG (exp, 0);
15262   arg1 = CALL_EXPR_ARG (exp, 1);
15263   op0 = expand_normal (arg0);
15264   op1 = expand_normal (arg1);
15265   mode0 = insn_data[icode].operand[0].mode;
15266   mode1 = insn_data[icode].operand[1].mode;
15267
15268   if (! (*insn_data[icode].operand[0].predicate) (op0, mode0))
15269     op0 = gen_rtx_MEM (mode0, copy_to_mode_reg (Pmode, op0));
15270   if (! (*insn_data[icode].operand[1].predicate) (op1, mode1))
15271     op1 = copy_to_mode_reg (mode1, op1);
15272
15273   pat = GEN_FCN (icode) (op0, op1);
15274   if (pat)
15275     emit_insn (pat);
15276
15277   *expandedp = true;
15278   return NULL_RTX;
15279 }
15280
15281 /* Expand the dst builtins.  */
15282 static rtx
15283 altivec_expand_dst_builtin (tree exp, rtx target ATTRIBUTE_UNUSED,
15284                             bool *expandedp)
15285 {
15286   tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
15287   enum rs6000_builtins fcode = (enum rs6000_builtins) DECL_FUNCTION_CODE (fndecl);
15288   tree arg0, arg1, arg2;
15289   machine_mode mode0, mode1;
15290   rtx pat, op0, op1, op2;
15291   const struct builtin_description *d;
15292   size_t i;
15293
15294   *expandedp = false;
15295
15296   /* Handle DST variants.  */
15297   d = bdesc_dst;
15298   for (i = 0; i < ARRAY_SIZE (bdesc_dst); i++, d++)
15299     if (d->code == fcode)
15300       {
15301         arg0 = CALL_EXPR_ARG (exp, 0);
15302         arg1 = CALL_EXPR_ARG (exp, 1);
15303         arg2 = CALL_EXPR_ARG (exp, 2);
15304         op0 = expand_normal (arg0);
15305         op1 = expand_normal (arg1);
15306         op2 = expand_normal (arg2);
15307         mode0 = insn_data[d->icode].operand[0].mode;
15308         mode1 = insn_data[d->icode].operand[1].mode;
15309
15310         /* Invalid arguments, bail out before generating bad rtl.  */
15311         if (arg0 == error_mark_node
15312             || arg1 == error_mark_node
15313             || arg2 == error_mark_node)
15314           return const0_rtx;
15315
15316         *expandedp = true;
15317         STRIP_NOPS (arg2);
15318         if (TREE_CODE (arg2) != INTEGER_CST
15319             || TREE_INT_CST_LOW (arg2) & ~0x3)
15320           {
15321             error ("argument to %qs must be a 2-bit unsigned literal", d->name);
15322             return const0_rtx;
15323           }
15324
15325         if (! (*insn_data[d->icode].operand[0].predicate) (op0, mode0))
15326           op0 = copy_to_mode_reg (Pmode, op0);
15327         if (! (*insn_data[d->icode].operand[1].predicate) (op1, mode1))
15328           op1 = copy_to_mode_reg (mode1, op1);
15329
15330         pat = GEN_FCN (d->icode) (op0, op1, op2);
15331         if (pat != 0)
15332           emit_insn (pat);
15333
15334         return NULL_RTX;
15335       }
15336
15337   return NULL_RTX;
15338 }
15339
15340 /* Expand vec_init builtin.  */
15341 static rtx
15342 altivec_expand_vec_init_builtin (tree type, tree exp, rtx target)
15343 {
15344   machine_mode tmode = TYPE_MODE (type);
15345   machine_mode inner_mode = GET_MODE_INNER (tmode);
15346   int i, n_elt = GET_MODE_NUNITS (tmode);
15347
15348   gcc_assert (VECTOR_MODE_P (tmode));
15349   gcc_assert (n_elt == call_expr_nargs (exp));
15350
15351   if (!target || !register_operand (target, tmode))
15352     target = gen_reg_rtx (tmode);
15353
15354   /* If we have a vector compromised of a single element, such as V1TImode, do
15355      the initialization directly.  */
15356   if (n_elt == 1 && GET_MODE_SIZE (tmode) == GET_MODE_SIZE (inner_mode))
15357     {
15358       rtx x = expand_normal (CALL_EXPR_ARG (exp, 0));
15359       emit_move_insn (target, gen_lowpart (tmode, x));
15360     }
15361   else
15362     {
15363       rtvec v = rtvec_alloc (n_elt);
15364
15365       for (i = 0; i < n_elt; ++i)
15366         {
15367           rtx x = expand_normal (CALL_EXPR_ARG (exp, i));
15368           RTVEC_ELT (v, i) = gen_lowpart (inner_mode, x);
15369         }
15370
15371       rs6000_expand_vector_init (target, gen_rtx_PARALLEL (tmode, v));
15372     }
15373
15374   return target;
15375 }
15376
15377 /* Return the integer constant in ARG.  Constrain it to be in the range
15378    of the subparts of VEC_TYPE; issue an error if not.  */
15379
15380 static int
15381 get_element_number (tree vec_type, tree arg)
15382 {
15383   unsigned HOST_WIDE_INT elt, max = TYPE_VECTOR_SUBPARTS (vec_type) - 1;
15384
15385   if (!tree_fits_uhwi_p (arg)
15386       || (elt = tree_to_uhwi (arg), elt > max))
15387     {
15388       error ("selector must be an integer constant in the range 0..%wi", max);
15389       return 0;
15390     }
15391
15392   return elt;
15393 }
15394
15395 /* Expand vec_set builtin.  */
15396 static rtx
15397 altivec_expand_vec_set_builtin (tree exp)
15398 {
15399   machine_mode tmode, mode1;
15400   tree arg0, arg1, arg2;
15401   int elt;
15402   rtx op0, op1;
15403
15404   arg0 = CALL_EXPR_ARG (exp, 0);
15405   arg1 = CALL_EXPR_ARG (exp, 1);
15406   arg2 = CALL_EXPR_ARG (exp, 2);
15407
15408   tmode = TYPE_MODE (TREE_TYPE (arg0));
15409   mode1 = TYPE_MODE (TREE_TYPE (TREE_TYPE (arg0)));
15410   gcc_assert (VECTOR_MODE_P (tmode));
15411
15412   op0 = expand_expr (arg0, NULL_RTX, tmode, EXPAND_NORMAL);
15413   op1 = expand_expr (arg1, NULL_RTX, mode1, EXPAND_NORMAL);
15414   elt = get_element_number (TREE_TYPE (arg0), arg2);
15415
15416   if (GET_MODE (op1) != mode1 && GET_MODE (op1) != VOIDmode)
15417     op1 = convert_modes (mode1, GET_MODE (op1), op1, true);
15418
15419   op0 = force_reg (tmode, op0);
15420   op1 = force_reg (mode1, op1);
15421
15422   rs6000_expand_vector_set (op0, op1, elt);
15423
15424   return op0;
15425 }
15426
15427 /* Expand vec_ext builtin.  */
15428 static rtx
15429 altivec_expand_vec_ext_builtin (tree exp, rtx target)
15430 {
15431   machine_mode tmode, mode0;
15432   tree arg0, arg1;
15433   rtx op0;
15434   rtx op1;
15435
15436   arg0 = CALL_EXPR_ARG (exp, 0);
15437   arg1 = CALL_EXPR_ARG (exp, 1);
15438
15439   op0 = expand_normal (arg0);
15440   op1 = expand_normal (arg1);
15441
15442   /* Call get_element_number to validate arg1 if it is a constant.  */
15443   if (TREE_CODE (arg1) == INTEGER_CST)
15444     (void) get_element_number (TREE_TYPE (arg0), arg1);
15445
15446   tmode = TYPE_MODE (TREE_TYPE (TREE_TYPE (arg0)));
15447   mode0 = TYPE_MODE (TREE_TYPE (arg0));
15448   gcc_assert (VECTOR_MODE_P (mode0));
15449
15450   op0 = force_reg (mode0, op0);
15451
15452   if (optimize || !target || !register_operand (target, tmode))
15453     target = gen_reg_rtx (tmode);
15454
15455   rs6000_expand_vector_extract (target, op0, op1);
15456
15457   return target;
15458 }
15459
15460 /* Expand the builtin in EXP and store the result in TARGET.  Store
15461    true in *EXPANDEDP if we found a builtin to expand.  */
15462 static rtx
15463 altivec_expand_builtin (tree exp, rtx target, bool *expandedp)
15464 {
15465   const struct builtin_description *d;
15466   size_t i;
15467   enum insn_code icode;
15468   tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
15469   tree arg0, arg1, arg2;
15470   rtx op0, pat;
15471   machine_mode tmode, mode0;
15472   enum rs6000_builtins fcode
15473     = (enum rs6000_builtins) DECL_FUNCTION_CODE (fndecl);
15474
15475   if (rs6000_overloaded_builtin_p (fcode))
15476     {
15477       *expandedp = true;
15478       error ("unresolved overload for Altivec builtin %qF", fndecl);
15479
15480       /* Given it is invalid, just generate a normal call.  */
15481       return expand_call (exp, target, false);
15482     }
15483
15484   target = altivec_expand_ld_builtin (exp, target, expandedp);
15485   if (*expandedp)
15486     return target;
15487
15488   target = altivec_expand_st_builtin (exp, target, expandedp);
15489   if (*expandedp)
15490     return target;
15491
15492   target = altivec_expand_dst_builtin (exp, target, expandedp);
15493   if (*expandedp)
15494     return target;
15495
15496   *expandedp = true;
15497
15498   switch (fcode)
15499     {
15500     case ALTIVEC_BUILTIN_STVX_V2DF:
15501       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvx_v2df_2op, exp);
15502     case ALTIVEC_BUILTIN_STVX_V2DI:
15503       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvx_v2di_2op, exp);
15504     case ALTIVEC_BUILTIN_STVX_V4SF:
15505       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvx_v4sf_2op, exp);
15506     case ALTIVEC_BUILTIN_STVX:
15507     case ALTIVEC_BUILTIN_STVX_V4SI:
15508       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvx_v4si_2op, exp);
15509     case ALTIVEC_BUILTIN_STVX_V8HI:
15510       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvx_v8hi_2op, exp);
15511     case ALTIVEC_BUILTIN_STVX_V16QI:
15512       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvx_v16qi_2op, exp);
15513     case ALTIVEC_BUILTIN_STVEBX:
15514       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvebx, exp);
15515     case ALTIVEC_BUILTIN_STVEHX:
15516       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvehx, exp);
15517     case ALTIVEC_BUILTIN_STVEWX:
15518       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvewx, exp);
15519     case ALTIVEC_BUILTIN_STVXL_V2DF:
15520       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvxl_v2df, exp);
15521     case ALTIVEC_BUILTIN_STVXL_V2DI:
15522       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvxl_v2di, exp);
15523     case ALTIVEC_BUILTIN_STVXL_V4SF:
15524       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvxl_v4sf, exp);
15525     case ALTIVEC_BUILTIN_STVXL:
15526     case ALTIVEC_BUILTIN_STVXL_V4SI:
15527       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvxl_v4si, exp);
15528     case ALTIVEC_BUILTIN_STVXL_V8HI:
15529       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvxl_v8hi, exp);
15530     case ALTIVEC_BUILTIN_STVXL_V16QI:
15531       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvxl_v16qi, exp);
15532
15533     case ALTIVEC_BUILTIN_STVLX:
15534       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvlx, exp);
15535     case ALTIVEC_BUILTIN_STVLXL:
15536       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvlxl, exp);
15537     case ALTIVEC_BUILTIN_STVRX:
15538       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvrx, exp);
15539     case ALTIVEC_BUILTIN_STVRXL:
15540       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvrxl, exp);
15541
15542     case P9V_BUILTIN_STXVL:
15543       return altivec_expand_stxvl_builtin (CODE_FOR_stxvl, exp);
15544
15545     case P9V_BUILTIN_XST_LEN_R:
15546       return altivec_expand_stxvl_builtin (CODE_FOR_xst_len_r, exp);
15547
15548     case VSX_BUILTIN_STXVD2X_V1TI:
15549       return altivec_expand_stv_builtin (CODE_FOR_vsx_store_v1ti, exp);
15550     case VSX_BUILTIN_STXVD2X_V2DF:
15551       return altivec_expand_stv_builtin (CODE_FOR_vsx_store_v2df, exp);
15552     case VSX_BUILTIN_STXVD2X_V2DI:
15553       return altivec_expand_stv_builtin (CODE_FOR_vsx_store_v2di, exp);
15554     case VSX_BUILTIN_STXVW4X_V4SF:
15555       return altivec_expand_stv_builtin (CODE_FOR_vsx_store_v4sf, exp);
15556     case VSX_BUILTIN_STXVW4X_V4SI:
15557       return altivec_expand_stv_builtin (CODE_FOR_vsx_store_v4si, exp);
15558     case VSX_BUILTIN_STXVW4X_V8HI:
15559       return altivec_expand_stv_builtin (CODE_FOR_vsx_store_v8hi, exp);
15560     case VSX_BUILTIN_STXVW4X_V16QI:
15561       return altivec_expand_stv_builtin (CODE_FOR_vsx_store_v16qi, exp);
15562
15563     /* For the following on big endian, it's ok to use any appropriate
15564        unaligned-supporting store, so use a generic expander.  For
15565        little-endian, the exact element-reversing instruction must
15566        be used.  */
15567     case VSX_BUILTIN_ST_ELEMREV_V2DF:
15568       {
15569         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_store_v2df
15570                                : CODE_FOR_vsx_st_elemrev_v2df);
15571         return altivec_expand_stv_builtin (code, exp);
15572       }
15573     case VSX_BUILTIN_ST_ELEMREV_V2DI:
15574       {
15575         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_store_v2di
15576                                : CODE_FOR_vsx_st_elemrev_v2di);
15577         return altivec_expand_stv_builtin (code, exp);
15578       }
15579     case VSX_BUILTIN_ST_ELEMREV_V4SF:
15580       {
15581         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_store_v4sf
15582                                : CODE_FOR_vsx_st_elemrev_v4sf);
15583         return altivec_expand_stv_builtin (code, exp);
15584       }
15585     case VSX_BUILTIN_ST_ELEMREV_V4SI:
15586       {
15587         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_store_v4si
15588                                : CODE_FOR_vsx_st_elemrev_v4si);
15589         return altivec_expand_stv_builtin (code, exp);
15590       }
15591     case VSX_BUILTIN_ST_ELEMREV_V8HI:
15592       {
15593         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_store_v8hi
15594                                : CODE_FOR_vsx_st_elemrev_v8hi);
15595         return altivec_expand_stv_builtin (code, exp);
15596       }
15597     case VSX_BUILTIN_ST_ELEMREV_V16QI:
15598       {
15599         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_store_v16qi
15600                                : CODE_FOR_vsx_st_elemrev_v16qi);
15601         return altivec_expand_stv_builtin (code, exp);
15602       }
15603
15604     case ALTIVEC_BUILTIN_MFVSCR:
15605       icode = CODE_FOR_altivec_mfvscr;
15606       tmode = insn_data[icode].operand[0].mode;
15607
15608       if (target == 0
15609           || GET_MODE (target) != tmode
15610           || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
15611         target = gen_reg_rtx (tmode);
15612
15613       pat = GEN_FCN (icode) (target);
15614       if (! pat)
15615         return 0;
15616       emit_insn (pat);
15617       return target;
15618
15619     case ALTIVEC_BUILTIN_MTVSCR:
15620       icode = CODE_FOR_altivec_mtvscr;
15621       arg0 = CALL_EXPR_ARG (exp, 0);
15622       op0 = expand_normal (arg0);
15623       mode0 = insn_data[icode].operand[0].mode;
15624
15625       /* If we got invalid arguments bail out before generating bad rtl.  */
15626       if (arg0 == error_mark_node)
15627         return const0_rtx;
15628
15629       if (! (*insn_data[icode].operand[0].predicate) (op0, mode0))
15630         op0 = copy_to_mode_reg (mode0, op0);
15631
15632       pat = GEN_FCN (icode) (op0);
15633       if (pat)
15634         emit_insn (pat);
15635       return NULL_RTX;
15636
15637     case ALTIVEC_BUILTIN_DSSALL:
15638       emit_insn (gen_altivec_dssall ());
15639       return NULL_RTX;
15640
15641     case ALTIVEC_BUILTIN_DSS:
15642       icode = CODE_FOR_altivec_dss;
15643       arg0 = CALL_EXPR_ARG (exp, 0);
15644       STRIP_NOPS (arg0);
15645       op0 = expand_normal (arg0);
15646       mode0 = insn_data[icode].operand[0].mode;
15647
15648       /* If we got invalid arguments bail out before generating bad rtl.  */
15649       if (arg0 == error_mark_node)
15650         return const0_rtx;
15651
15652       if (TREE_CODE (arg0) != INTEGER_CST
15653           || TREE_INT_CST_LOW (arg0) & ~0x3)
15654         {
15655           error ("argument to %qs must be a 2-bit unsigned literal", "dss");
15656           return const0_rtx;
15657         }
15658
15659       if (! (*insn_data[icode].operand[0].predicate) (op0, mode0))
15660         op0 = copy_to_mode_reg (mode0, op0);
15661
15662       emit_insn (gen_altivec_dss (op0));
15663       return NULL_RTX;
15664
15665     case ALTIVEC_BUILTIN_VEC_INIT_V4SI:
15666     case ALTIVEC_BUILTIN_VEC_INIT_V8HI:
15667     case ALTIVEC_BUILTIN_VEC_INIT_V16QI:
15668     case ALTIVEC_BUILTIN_VEC_INIT_V4SF:
15669     case VSX_BUILTIN_VEC_INIT_V2DF:
15670     case VSX_BUILTIN_VEC_INIT_V2DI:
15671     case VSX_BUILTIN_VEC_INIT_V1TI:
15672       return altivec_expand_vec_init_builtin (TREE_TYPE (exp), exp, target);
15673
15674     case ALTIVEC_BUILTIN_VEC_SET_V4SI:
15675     case ALTIVEC_BUILTIN_VEC_SET_V8HI:
15676     case ALTIVEC_BUILTIN_VEC_SET_V16QI:
15677     case ALTIVEC_BUILTIN_VEC_SET_V4SF:
15678     case VSX_BUILTIN_VEC_SET_V2DF:
15679     case VSX_BUILTIN_VEC_SET_V2DI:
15680     case VSX_BUILTIN_VEC_SET_V1TI:
15681       return altivec_expand_vec_set_builtin (exp);
15682
15683     case ALTIVEC_BUILTIN_VEC_EXT_V4SI:
15684     case ALTIVEC_BUILTIN_VEC_EXT_V8HI:
15685     case ALTIVEC_BUILTIN_VEC_EXT_V16QI:
15686     case ALTIVEC_BUILTIN_VEC_EXT_V4SF:
15687     case VSX_BUILTIN_VEC_EXT_V2DF:
15688     case VSX_BUILTIN_VEC_EXT_V2DI:
15689     case VSX_BUILTIN_VEC_EXT_V1TI:
15690       return altivec_expand_vec_ext_builtin (exp, target);
15691
15692     case P9V_BUILTIN_VEXTRACT4B:
15693     case P9V_BUILTIN_VEC_VEXTRACT4B:
15694       arg1 = CALL_EXPR_ARG (exp, 1);
15695       STRIP_NOPS (arg1);
15696
15697       /* Generate a normal call if it is invalid.  */
15698       if (arg1 == error_mark_node)
15699         return expand_call (exp, target, false);
15700
15701       if (TREE_CODE (arg1) != INTEGER_CST || TREE_INT_CST_LOW (arg1) > 12)
15702         {
15703           error ("second argument to %qs must be 0..12", "vec_vextract4b");
15704           return expand_call (exp, target, false);
15705         }
15706       break;
15707
15708     case P9V_BUILTIN_VINSERT4B:
15709     case P9V_BUILTIN_VINSERT4B_DI:
15710     case P9V_BUILTIN_VEC_VINSERT4B:
15711       arg2 = CALL_EXPR_ARG (exp, 2);
15712       STRIP_NOPS (arg2);
15713
15714       /* Generate a normal call if it is invalid.  */
15715       if (arg2 == error_mark_node)
15716         return expand_call (exp, target, false);
15717
15718       if (TREE_CODE (arg2) != INTEGER_CST || TREE_INT_CST_LOW (arg2) > 12)
15719         {
15720           error ("third argument to %qs must be 0..12", "vec_vinsert4b");
15721           return expand_call (exp, target, false);
15722         }
15723       break;
15724
15725     default:
15726       break;
15727       /* Fall through.  */
15728     }
15729
15730   /* Expand abs* operations.  */
15731   d = bdesc_abs;
15732   for (i = 0; i < ARRAY_SIZE (bdesc_abs); i++, d++)
15733     if (d->code == fcode)
15734       return altivec_expand_abs_builtin (d->icode, exp, target);
15735
15736   /* Expand the AltiVec predicates.  */
15737   d = bdesc_altivec_preds;
15738   for (i = 0; i < ARRAY_SIZE (bdesc_altivec_preds); i++, d++)
15739     if (d->code == fcode)
15740       return altivec_expand_predicate_builtin (d->icode, exp, target);
15741
15742   /* LV* are funky.  We initialized them differently.  */
15743   switch (fcode)
15744     {
15745     case ALTIVEC_BUILTIN_LVSL:
15746       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvsl,
15747                                         exp, target, false);
15748     case ALTIVEC_BUILTIN_LVSR:
15749       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvsr,
15750                                         exp, target, false);
15751     case ALTIVEC_BUILTIN_LVEBX:
15752       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvebx,
15753                                         exp, target, false);
15754     case ALTIVEC_BUILTIN_LVEHX:
15755       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvehx,
15756                                         exp, target, false);
15757     case ALTIVEC_BUILTIN_LVEWX:
15758       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvewx,
15759                                         exp, target, false);
15760     case ALTIVEC_BUILTIN_LVXL_V2DF:
15761       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvxl_v2df,
15762                                         exp, target, false);
15763     case ALTIVEC_BUILTIN_LVXL_V2DI:
15764       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvxl_v2di,
15765                                         exp, target, false);
15766     case ALTIVEC_BUILTIN_LVXL_V4SF:
15767       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvxl_v4sf,
15768                                         exp, target, false);
15769     case ALTIVEC_BUILTIN_LVXL:
15770     case ALTIVEC_BUILTIN_LVXL_V4SI:
15771       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvxl_v4si,
15772                                         exp, target, false);
15773     case ALTIVEC_BUILTIN_LVXL_V8HI:
15774       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvxl_v8hi,
15775                                         exp, target, false);
15776     case ALTIVEC_BUILTIN_LVXL_V16QI:
15777       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvxl_v16qi,
15778                                         exp, target, false);
15779     case ALTIVEC_BUILTIN_LVX_V2DF:
15780       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvx_v2df_2op,
15781                                         exp, target, false);
15782     case ALTIVEC_BUILTIN_LVX_V2DI:
15783       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvx_v2di_2op,
15784                                         exp, target, false);
15785     case ALTIVEC_BUILTIN_LVX_V4SF:
15786       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvx_v4sf_2op,
15787                                         exp, target, false);
15788     case ALTIVEC_BUILTIN_LVX:
15789     case ALTIVEC_BUILTIN_LVX_V4SI:
15790       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvx_v4si_2op,
15791                                         exp, target, false);
15792     case ALTIVEC_BUILTIN_LVX_V8HI:
15793       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvx_v8hi_2op,
15794                                         exp, target, false);
15795     case ALTIVEC_BUILTIN_LVX_V16QI:
15796       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvx_v16qi_2op,
15797                                         exp, target, false);
15798     case ALTIVEC_BUILTIN_LVLX:
15799       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvlx,
15800                                         exp, target, true);
15801     case ALTIVEC_BUILTIN_LVLXL:
15802       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvlxl,
15803                                         exp, target, true);
15804     case ALTIVEC_BUILTIN_LVRX:
15805       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvrx,
15806                                         exp, target, true);
15807     case ALTIVEC_BUILTIN_LVRXL:
15808       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvrxl,
15809                                         exp, target, true);
15810     case VSX_BUILTIN_LXVD2X_V1TI:
15811       return altivec_expand_lv_builtin (CODE_FOR_vsx_load_v1ti,
15812                                         exp, target, false);
15813     case VSX_BUILTIN_LXVD2X_V2DF:
15814       return altivec_expand_lv_builtin (CODE_FOR_vsx_load_v2df,
15815                                         exp, target, false);
15816     case VSX_BUILTIN_LXVD2X_V2DI:
15817       return altivec_expand_lv_builtin (CODE_FOR_vsx_load_v2di,
15818                                         exp, target, false);
15819     case VSX_BUILTIN_LXVW4X_V4SF:
15820       return altivec_expand_lv_builtin (CODE_FOR_vsx_load_v4sf,
15821                                         exp, target, false);
15822     case VSX_BUILTIN_LXVW4X_V4SI:
15823       return altivec_expand_lv_builtin (CODE_FOR_vsx_load_v4si,
15824                                         exp, target, false);
15825     case VSX_BUILTIN_LXVW4X_V8HI:
15826       return altivec_expand_lv_builtin (CODE_FOR_vsx_load_v8hi,
15827                                         exp, target, false);
15828     case VSX_BUILTIN_LXVW4X_V16QI:
15829       return altivec_expand_lv_builtin (CODE_FOR_vsx_load_v16qi,
15830                                         exp, target, false);
15831     /* For the following on big endian, it's ok to use any appropriate
15832        unaligned-supporting load, so use a generic expander.  For
15833        little-endian, the exact element-reversing instruction must
15834        be used.  */
15835     case VSX_BUILTIN_LD_ELEMREV_V2DF:
15836       {
15837         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_load_v2df
15838                                : CODE_FOR_vsx_ld_elemrev_v2df);
15839         return altivec_expand_lv_builtin (code, exp, target, false);
15840       }
15841     case VSX_BUILTIN_LD_ELEMREV_V2DI:
15842       {
15843         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_load_v2di
15844                                : CODE_FOR_vsx_ld_elemrev_v2di);
15845         return altivec_expand_lv_builtin (code, exp, target, false);
15846       }
15847     case VSX_BUILTIN_LD_ELEMREV_V4SF:
15848       {
15849         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_load_v4sf
15850                                : CODE_FOR_vsx_ld_elemrev_v4sf);
15851         return altivec_expand_lv_builtin (code, exp, target, false);
15852       }
15853     case VSX_BUILTIN_LD_ELEMREV_V4SI:
15854       {
15855         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_load_v4si
15856                                : CODE_FOR_vsx_ld_elemrev_v4si);
15857         return altivec_expand_lv_builtin (code, exp, target, false);
15858       }
15859     case VSX_BUILTIN_LD_ELEMREV_V8HI:
15860       {
15861         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_load_v8hi
15862                                : CODE_FOR_vsx_ld_elemrev_v8hi);
15863         return altivec_expand_lv_builtin (code, exp, target, false);
15864       }
15865     case VSX_BUILTIN_LD_ELEMREV_V16QI:
15866       {
15867         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_load_v16qi
15868                                : CODE_FOR_vsx_ld_elemrev_v16qi);
15869         return altivec_expand_lv_builtin (code, exp, target, false);
15870       }
15871       break;
15872     default:
15873       break;
15874       /* Fall through.  */
15875     }
15876
15877   *expandedp = false;
15878   return NULL_RTX;
15879 }
15880
15881 /* Expand the builtin in EXP and store the result in TARGET.  Store
15882    true in *EXPANDEDP if we found a builtin to expand.  */
15883 static rtx
15884 paired_expand_builtin (tree exp, rtx target, bool * expandedp)
15885 {
15886   tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
15887   enum rs6000_builtins fcode = (enum rs6000_builtins) DECL_FUNCTION_CODE (fndecl);
15888   const struct builtin_description *d;
15889   size_t i;
15890
15891   *expandedp = true;
15892
15893   switch (fcode)
15894     {
15895     case PAIRED_BUILTIN_STX:
15896       return paired_expand_stv_builtin (CODE_FOR_paired_stx, exp);
15897     case PAIRED_BUILTIN_LX:
15898       return paired_expand_lv_builtin (CODE_FOR_paired_lx, exp, target);
15899     default:
15900       break;
15901       /* Fall through.  */
15902     }
15903
15904   /* Expand the paired predicates.  */
15905   d = bdesc_paired_preds;
15906   for (i = 0; i < ARRAY_SIZE (bdesc_paired_preds); i++, d++)
15907     if (d->code == fcode)
15908       return paired_expand_predicate_builtin (d->icode, exp, target);
15909
15910   *expandedp = false;
15911   return NULL_RTX;
15912 }
15913
15914 static rtx
15915 paired_expand_predicate_builtin (enum insn_code icode, tree exp, rtx target)
15916 {
15917   rtx pat, scratch, tmp;
15918   tree form = CALL_EXPR_ARG (exp, 0);
15919   tree arg0 = CALL_EXPR_ARG (exp, 1);
15920   tree arg1 = CALL_EXPR_ARG (exp, 2);
15921   rtx op0 = expand_normal (arg0);
15922   rtx op1 = expand_normal (arg1);
15923   machine_mode mode0 = insn_data[icode].operand[1].mode;
15924   machine_mode mode1 = insn_data[icode].operand[2].mode;
15925   int form_int;
15926   enum rtx_code code;
15927
15928   if (TREE_CODE (form) != INTEGER_CST)
15929     {
15930       error ("argument 1 of %s must be a constant",
15931              "__builtin_paired_predicate");
15932       return const0_rtx;
15933     }
15934   else
15935     form_int = TREE_INT_CST_LOW (form);
15936
15937   gcc_assert (mode0 == mode1);
15938
15939   if (arg0 == error_mark_node || arg1 == error_mark_node)
15940     return const0_rtx;
15941
15942   if (target == 0
15943       || GET_MODE (target) != SImode
15944       || !(*insn_data[icode].operand[0].predicate) (target, SImode))
15945     target = gen_reg_rtx (SImode);
15946   if (!(*insn_data[icode].operand[1].predicate) (op0, mode0))
15947     op0 = copy_to_mode_reg (mode0, op0);
15948   if (!(*insn_data[icode].operand[2].predicate) (op1, mode1))
15949     op1 = copy_to_mode_reg (mode1, op1);
15950
15951   scratch = gen_reg_rtx (CCFPmode);
15952
15953   pat = GEN_FCN (icode) (scratch, op0, op1);
15954   if (!pat)
15955     return const0_rtx;
15956
15957   emit_insn (pat);
15958
15959   switch (form_int)
15960     {
15961       /* LT bit.  */
15962     case 0:
15963       code = LT;
15964       break;
15965       /* GT bit.  */
15966     case 1:
15967       code = GT;
15968       break;
15969       /* EQ bit.  */
15970     case 2:
15971       code = EQ;
15972       break;
15973       /* UN bit.  */
15974     case 3:
15975       emit_insn (gen_move_from_CR_ov_bit (target, scratch));
15976       return target;
15977     default:
15978       error ("argument 1 of %qs is out of range",
15979              "__builtin_paired_predicate");
15980       return const0_rtx;
15981     }
15982
15983   tmp = gen_rtx_fmt_ee (code, SImode, scratch, const0_rtx);
15984   emit_move_insn (target, tmp);
15985   return target;
15986 }
15987
15988 /* Raise an error message for a builtin function that is called without the
15989    appropriate target options being set.  */
15990
15991 static void
15992 rs6000_invalid_builtin (enum rs6000_builtins fncode)
15993 {
15994   size_t uns_fncode = (size_t) fncode;
15995   const char *name = rs6000_builtin_info[uns_fncode].name;
15996   HOST_WIDE_INT fnmask = rs6000_builtin_info[uns_fncode].mask;
15997
15998   gcc_assert (name != NULL);
15999   if ((fnmask & RS6000_BTM_CELL) != 0)
16000     error ("builtin function %qs is only valid for the cell processor", name);
16001   else if ((fnmask & RS6000_BTM_VSX) != 0)
16002     error ("builtin function %qs requires the %qs option", name, "-mvsx");
16003   else if ((fnmask & RS6000_BTM_HTM) != 0)
16004     error ("builtin function %qs requires the %qs option", name, "-mhtm");
16005   else if ((fnmask & RS6000_BTM_ALTIVEC) != 0)
16006     error ("builtin function %qs requires the %qs option", name, "-maltivec");
16007   else if ((fnmask & RS6000_BTM_PAIRED) != 0)
16008     error ("builtin function %qs requires the %qs option", name, "-mpaired");
16009   else if ((fnmask & (RS6000_BTM_DFP | RS6000_BTM_P8_VECTOR))
16010            == (RS6000_BTM_DFP | RS6000_BTM_P8_VECTOR))
16011     error ("builtin function %qs requires the %qs and %qs options",
16012            name, "-mhard-dfp", "-mpower8-vector");
16013   else if ((fnmask & RS6000_BTM_DFP) != 0)
16014     error ("builtin function %qs requires the %qs option", name, "-mhard-dfp");
16015   else if ((fnmask & RS6000_BTM_P8_VECTOR) != 0)
16016     error ("builtin function %qs requires the %qs option", name,
16017            "-mpower8-vector");
16018   else if ((fnmask & (RS6000_BTM_P9_VECTOR | RS6000_BTM_64BIT))
16019            == (RS6000_BTM_P9_VECTOR | RS6000_BTM_64BIT))
16020     error ("builtin function %qs requires the %qs and %qs options",
16021            name, "-mcpu=power9", "-m64");
16022   else if ((fnmask & RS6000_BTM_P9_VECTOR) != 0)
16023     error ("builtin function %qs requires the %qs option", name,
16024            "-mcpu=power9");
16025   else if ((fnmask & (RS6000_BTM_P9_MISC | RS6000_BTM_64BIT))
16026            == (RS6000_BTM_P9_MISC | RS6000_BTM_64BIT))
16027     error ("builtin function %qs requires the %qs and %qs options",
16028            name, "-mcpu=power9", "-m64");
16029   else if ((fnmask & RS6000_BTM_P9_MISC) == RS6000_BTM_P9_MISC)
16030     error ("builtin function %qs requires the %qs option", name,
16031            "-mcpu=power9");
16032   else if ((fnmask & (RS6000_BTM_HARD_FLOAT | RS6000_BTM_LDBL128))
16033            == (RS6000_BTM_HARD_FLOAT | RS6000_BTM_LDBL128))
16034     error ("builtin function %qs requires the %qs and %qs options",
16035            name, "-mhard-float", "-mlong-double-128");
16036   else if ((fnmask & RS6000_BTM_HARD_FLOAT) != 0)
16037     error ("builtin function %qs requires the %qs option", name,
16038            "-mhard-float");
16039   else if ((fnmask & RS6000_BTM_FLOAT128_HW) != 0)
16040     error ("builtin function %qs requires ISA 3.0 IEEE 128-bit floating point",
16041            name);
16042   else if ((fnmask & RS6000_BTM_FLOAT128) != 0)
16043     error ("builtin function %qs requires the %qs option", name, "-mfloat128");
16044   else
16045     error ("builtin function %qs is not supported with the current options",
16046            name);
16047 }
16048
16049 /* Target hook for early folding of built-ins, shamelessly stolen
16050    from ia64.c.  */
16051
16052 static tree
16053 rs6000_fold_builtin (tree fndecl ATTRIBUTE_UNUSED,
16054                      int n_args ATTRIBUTE_UNUSED,
16055                      tree *args ATTRIBUTE_UNUSED,
16056                      bool ignore ATTRIBUTE_UNUSED)
16057 {
16058 #ifdef SUBTARGET_FOLD_BUILTIN
16059   return SUBTARGET_FOLD_BUILTIN (fndecl, n_args, args, ignore);
16060 #else
16061   return NULL_TREE;
16062 #endif
16063 }
16064
16065 /*  Helper function to sort out which built-ins may be valid without having
16066     a LHS.  */
16067 static bool
16068 rs6000_builtin_valid_without_lhs (enum rs6000_builtins fn_code)
16069 {
16070   switch (fn_code)
16071     {
16072     case ALTIVEC_BUILTIN_STVX_V16QI:
16073     case ALTIVEC_BUILTIN_STVX_V8HI:
16074     case ALTIVEC_BUILTIN_STVX_V4SI:
16075     case ALTIVEC_BUILTIN_STVX_V4SF:
16076     case ALTIVEC_BUILTIN_STVX_V2DI:
16077     case ALTIVEC_BUILTIN_STVX_V2DF:
16078       return true;
16079     default:
16080       return false;
16081     }
16082 }
16083
16084 /* Helper function to handle the gimple folding of a vector compare
16085    operation.  This sets up true/false vectors, and uses the
16086    VEC_COND_EXPR operation.
16087    CODE indicates which comparison is to be made. (EQ, GT, ...).
16088    TYPE indicates the type of the result.  */
16089 static tree
16090 fold_build_vec_cmp (tree_code code, tree type,
16091                     tree arg0, tree arg1)
16092 {
16093   tree cmp_type = build_same_sized_truth_vector_type (type);
16094   tree zero_vec = build_zero_cst (type);
16095   tree minus_one_vec = build_minus_one_cst (type);
16096   tree cmp = fold_build2 (code, cmp_type, arg0, arg1);
16097   return fold_build3 (VEC_COND_EXPR, type, cmp, minus_one_vec, zero_vec);
16098 }
16099
16100 /* Helper function to handle the in-between steps for the
16101    vector compare built-ins.  */
16102 static void
16103 fold_compare_helper (gimple_stmt_iterator *gsi, tree_code code, gimple *stmt)
16104 {
16105   tree arg0 = gimple_call_arg (stmt, 0);
16106   tree arg1 = gimple_call_arg (stmt, 1);
16107   tree lhs = gimple_call_lhs (stmt);
16108   tree cmp = fold_build_vec_cmp (code, TREE_TYPE (lhs), arg0, arg1);
16109   gimple *g = gimple_build_assign (lhs, cmp);
16110   gimple_set_location (g, gimple_location (stmt));
16111   gsi_replace (gsi, g, true);
16112 }
16113
16114 /* Fold a machine-dependent built-in in GIMPLE.  (For folding into
16115    a constant, use rs6000_fold_builtin.)  */
16116
16117 bool
16118 rs6000_gimple_fold_builtin (gimple_stmt_iterator *gsi)
16119 {
16120   gimple *stmt = gsi_stmt (*gsi);
16121   tree fndecl = gimple_call_fndecl (stmt);
16122   gcc_checking_assert (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD);
16123   enum rs6000_builtins fn_code
16124     = (enum rs6000_builtins) DECL_FUNCTION_CODE (fndecl);
16125   tree arg0, arg1, lhs, temp;
16126   gimple *g;
16127
16128   size_t uns_fncode = (size_t) fn_code;
16129   enum insn_code icode = rs6000_builtin_info[uns_fncode].icode;
16130   const char *fn_name1 = rs6000_builtin_info[uns_fncode].name;
16131   const char *fn_name2 = (icode != CODE_FOR_nothing)
16132                           ? get_insn_name ((int) icode)
16133                           : "nothing";
16134
16135   if (TARGET_DEBUG_BUILTIN)
16136       fprintf (stderr, "rs6000_gimple_fold_builtin %d %s %s\n",
16137                fn_code, fn_name1, fn_name2);
16138
16139   if (!rs6000_fold_gimple)
16140     return false;
16141
16142   /* Prevent gimple folding for code that does not have a LHS, unless it is
16143      allowed per the rs6000_builtin_valid_without_lhs helper function.  */
16144   if (!gimple_call_lhs (stmt) && !rs6000_builtin_valid_without_lhs (fn_code))
16145     return false;
16146
16147   /* Don't fold invalid builtins, let rs6000_expand_builtin diagnose it.  */
16148   HOST_WIDE_INT mask = rs6000_builtin_info[uns_fncode].mask;
16149   bool func_valid_p = (rs6000_builtin_mask & mask) == mask;
16150   if (!func_valid_p)
16151     return false;
16152
16153   switch (fn_code)
16154     {
16155     /* Flavors of vec_add.  We deliberately don't expand
16156        P8V_BUILTIN_VADDUQM as it gets lowered from V1TImode to
16157        TImode, resulting in much poorer code generation.  */
16158     case ALTIVEC_BUILTIN_VADDUBM:
16159     case ALTIVEC_BUILTIN_VADDUHM:
16160     case ALTIVEC_BUILTIN_VADDUWM:
16161     case P8V_BUILTIN_VADDUDM:
16162     case ALTIVEC_BUILTIN_VADDFP:
16163     case VSX_BUILTIN_XVADDDP:
16164       arg0 = gimple_call_arg (stmt, 0);
16165       arg1 = gimple_call_arg (stmt, 1);
16166       lhs = gimple_call_lhs (stmt);
16167       g = gimple_build_assign (lhs, PLUS_EXPR, arg0, arg1);
16168       gimple_set_location (g, gimple_location (stmt));
16169       gsi_replace (gsi, g, true);
16170       return true;
16171     /* Flavors of vec_sub.  We deliberately don't expand
16172        P8V_BUILTIN_VSUBUQM. */
16173     case ALTIVEC_BUILTIN_VSUBUBM:
16174     case ALTIVEC_BUILTIN_VSUBUHM:
16175     case ALTIVEC_BUILTIN_VSUBUWM:
16176     case P8V_BUILTIN_VSUBUDM:
16177     case ALTIVEC_BUILTIN_VSUBFP:
16178     case VSX_BUILTIN_XVSUBDP:
16179       arg0 = gimple_call_arg (stmt, 0);
16180       arg1 = gimple_call_arg (stmt, 1);
16181       lhs = gimple_call_lhs (stmt);
16182       g = gimple_build_assign (lhs, MINUS_EXPR, arg0, arg1);
16183       gimple_set_location (g, gimple_location (stmt));
16184       gsi_replace (gsi, g, true);
16185       return true;
16186     case VSX_BUILTIN_XVMULSP:
16187     case VSX_BUILTIN_XVMULDP:
16188       arg0 = gimple_call_arg (stmt, 0);
16189       arg1 = gimple_call_arg (stmt, 1);
16190       lhs = gimple_call_lhs (stmt);
16191       g = gimple_build_assign (lhs, MULT_EXPR, arg0, arg1);
16192       gimple_set_location (g, gimple_location (stmt));
16193       gsi_replace (gsi, g, true);
16194       return true;
16195     /* Even element flavors of vec_mul (signed). */
16196     case ALTIVEC_BUILTIN_VMULESB:
16197     case ALTIVEC_BUILTIN_VMULESH:
16198     case ALTIVEC_BUILTIN_VMULESW:
16199     /* Even element flavors of vec_mul (unsigned).  */
16200     case ALTIVEC_BUILTIN_VMULEUB:
16201     case ALTIVEC_BUILTIN_VMULEUH:
16202     case ALTIVEC_BUILTIN_VMULEUW:
16203       arg0 = gimple_call_arg (stmt, 0);
16204       arg1 = gimple_call_arg (stmt, 1);
16205       lhs = gimple_call_lhs (stmt);
16206       g = gimple_build_assign (lhs, VEC_WIDEN_MULT_EVEN_EXPR, arg0, arg1);
16207       gimple_set_location (g, gimple_location (stmt));
16208       gsi_replace (gsi, g, true);
16209       return true;
16210     /* Odd element flavors of vec_mul (signed).  */
16211     case ALTIVEC_BUILTIN_VMULOSB:
16212     case ALTIVEC_BUILTIN_VMULOSH:
16213     case ALTIVEC_BUILTIN_VMULOSW:
16214     /* Odd element flavors of vec_mul (unsigned). */
16215     case ALTIVEC_BUILTIN_VMULOUB:
16216     case ALTIVEC_BUILTIN_VMULOUH:
16217     case ALTIVEC_BUILTIN_VMULOUW:
16218       arg0 = gimple_call_arg (stmt, 0);
16219       arg1 = gimple_call_arg (stmt, 1);
16220       lhs = gimple_call_lhs (stmt);
16221       g = gimple_build_assign (lhs, VEC_WIDEN_MULT_ODD_EXPR, arg0, arg1);
16222       gimple_set_location (g, gimple_location (stmt));
16223       gsi_replace (gsi, g, true);
16224       return true;
16225     /* Flavors of vec_div (Integer).  */
16226     case VSX_BUILTIN_DIV_V2DI:
16227     case VSX_BUILTIN_UDIV_V2DI:
16228       arg0 = gimple_call_arg (stmt, 0);
16229       arg1 = gimple_call_arg (stmt, 1);
16230       lhs = gimple_call_lhs (stmt);
16231       g = gimple_build_assign (lhs, TRUNC_DIV_EXPR, arg0, arg1);
16232       gimple_set_location (g, gimple_location (stmt));
16233       gsi_replace (gsi, g, true);
16234       return true;
16235     /* Flavors of vec_div (Float).  */
16236     case VSX_BUILTIN_XVDIVSP:
16237     case VSX_BUILTIN_XVDIVDP:
16238       arg0 = gimple_call_arg (stmt, 0);
16239       arg1 = gimple_call_arg (stmt, 1);
16240       lhs = gimple_call_lhs (stmt);
16241       g = gimple_build_assign (lhs, RDIV_EXPR, arg0, arg1);
16242       gimple_set_location (g, gimple_location (stmt));
16243       gsi_replace (gsi, g, true);
16244       return true;
16245     /* Flavors of vec_and.  */
16246     case ALTIVEC_BUILTIN_VAND:
16247       arg0 = gimple_call_arg (stmt, 0);
16248       arg1 = gimple_call_arg (stmt, 1);
16249       lhs = gimple_call_lhs (stmt);
16250       g = gimple_build_assign (lhs, BIT_AND_EXPR, arg0, arg1);
16251       gimple_set_location (g, gimple_location (stmt));
16252       gsi_replace (gsi, g, true);
16253       return true;
16254     /* Flavors of vec_andc.  */
16255     case ALTIVEC_BUILTIN_VANDC:
16256       arg0 = gimple_call_arg (stmt, 0);
16257       arg1 = gimple_call_arg (stmt, 1);
16258       lhs = gimple_call_lhs (stmt);
16259       temp = create_tmp_reg_or_ssa_name (TREE_TYPE (arg1));
16260       g = gimple_build_assign (temp, BIT_NOT_EXPR, arg1);
16261       gimple_set_location (g, gimple_location (stmt));
16262       gsi_insert_before (gsi, g, GSI_SAME_STMT);
16263       g = gimple_build_assign (lhs, BIT_AND_EXPR, arg0, temp);
16264       gimple_set_location (g, gimple_location (stmt));
16265       gsi_replace (gsi, g, true);
16266       return true;
16267     /* Flavors of vec_nand.  */
16268     case P8V_BUILTIN_VEC_NAND:
16269     case P8V_BUILTIN_NAND_V16QI:
16270     case P8V_BUILTIN_NAND_V8HI:
16271     case P8V_BUILTIN_NAND_V4SI:
16272     case P8V_BUILTIN_NAND_V4SF:
16273     case P8V_BUILTIN_NAND_V2DF:
16274     case P8V_BUILTIN_NAND_V2DI:
16275       arg0 = gimple_call_arg (stmt, 0);
16276       arg1 = gimple_call_arg (stmt, 1);
16277       lhs = gimple_call_lhs (stmt);
16278       temp = create_tmp_reg_or_ssa_name (TREE_TYPE (arg1));
16279       g = gimple_build_assign (temp, BIT_AND_EXPR, arg0, arg1);
16280       gimple_set_location (g, gimple_location (stmt));
16281       gsi_insert_before (gsi, g, GSI_SAME_STMT);
16282       g = gimple_build_assign (lhs, BIT_NOT_EXPR, temp);
16283       gimple_set_location (g, gimple_location (stmt));
16284       gsi_replace (gsi, g, true);
16285       return true;
16286     /* Flavors of vec_or.  */
16287     case ALTIVEC_BUILTIN_VOR:
16288       arg0 = gimple_call_arg (stmt, 0);
16289       arg1 = gimple_call_arg (stmt, 1);
16290       lhs = gimple_call_lhs (stmt);
16291       g = gimple_build_assign (lhs, BIT_IOR_EXPR, arg0, arg1);
16292       gimple_set_location (g, gimple_location (stmt));
16293       gsi_replace (gsi, g, true);
16294       return true;
16295     /* flavors of vec_orc.  */
16296     case P8V_BUILTIN_ORC_V16QI:
16297     case P8V_BUILTIN_ORC_V8HI:
16298     case P8V_BUILTIN_ORC_V4SI:
16299     case P8V_BUILTIN_ORC_V4SF:
16300     case P8V_BUILTIN_ORC_V2DF:
16301     case P8V_BUILTIN_ORC_V2DI:
16302       arg0 = gimple_call_arg (stmt, 0);
16303       arg1 = gimple_call_arg (stmt, 1);
16304       lhs = gimple_call_lhs (stmt);
16305       temp = create_tmp_reg_or_ssa_name (TREE_TYPE (arg1));
16306       g = gimple_build_assign (temp, BIT_NOT_EXPR, arg1);
16307       gimple_set_location (g, gimple_location (stmt));
16308       gsi_insert_before (gsi, g, GSI_SAME_STMT);
16309       g = gimple_build_assign (lhs, BIT_IOR_EXPR, arg0, temp);
16310       gimple_set_location (g, gimple_location (stmt));
16311       gsi_replace (gsi, g, true);
16312       return true;
16313     /* Flavors of vec_xor.  */
16314     case ALTIVEC_BUILTIN_VXOR:
16315       arg0 = gimple_call_arg (stmt, 0);
16316       arg1 = gimple_call_arg (stmt, 1);
16317       lhs = gimple_call_lhs (stmt);
16318       g = gimple_build_assign (lhs, BIT_XOR_EXPR, arg0, arg1);
16319       gimple_set_location (g, gimple_location (stmt));
16320       gsi_replace (gsi, g, true);
16321       return true;
16322     /* Flavors of vec_nor.  */
16323     case ALTIVEC_BUILTIN_VNOR:
16324       arg0 = gimple_call_arg (stmt, 0);
16325       arg1 = gimple_call_arg (stmt, 1);
16326       lhs = gimple_call_lhs (stmt);
16327       temp = create_tmp_reg_or_ssa_name (TREE_TYPE (arg1));
16328       g = gimple_build_assign (temp, BIT_IOR_EXPR, arg0, arg1);
16329       gimple_set_location (g, gimple_location (stmt));
16330       gsi_insert_before (gsi, g, GSI_SAME_STMT);
16331       g = gimple_build_assign (lhs, BIT_NOT_EXPR, temp);
16332       gimple_set_location (g, gimple_location (stmt));
16333       gsi_replace (gsi, g, true);
16334       return true;
16335     /* flavors of vec_abs.  */
16336     case ALTIVEC_BUILTIN_ABS_V16QI:
16337     case ALTIVEC_BUILTIN_ABS_V8HI:
16338     case ALTIVEC_BUILTIN_ABS_V4SI:
16339     case ALTIVEC_BUILTIN_ABS_V4SF:
16340     case P8V_BUILTIN_ABS_V2DI:
16341     case VSX_BUILTIN_XVABSDP:
16342       arg0 = gimple_call_arg (stmt, 0);
16343       if (INTEGRAL_TYPE_P (TREE_TYPE (TREE_TYPE (arg0)))
16344           && !TYPE_OVERFLOW_WRAPS (TREE_TYPE (TREE_TYPE (arg0))))
16345         return false;
16346       lhs = gimple_call_lhs (stmt);
16347       g = gimple_build_assign (lhs, ABS_EXPR, arg0);
16348       gimple_set_location (g, gimple_location (stmt));
16349       gsi_replace (gsi, g, true);
16350       return true;
16351     /* flavors of vec_min.  */
16352     case VSX_BUILTIN_XVMINDP:
16353     case P8V_BUILTIN_VMINSD:
16354     case P8V_BUILTIN_VMINUD:
16355     case ALTIVEC_BUILTIN_VMINSB:
16356     case ALTIVEC_BUILTIN_VMINSH:
16357     case ALTIVEC_BUILTIN_VMINSW:
16358     case ALTIVEC_BUILTIN_VMINUB:
16359     case ALTIVEC_BUILTIN_VMINUH:
16360     case ALTIVEC_BUILTIN_VMINUW:
16361     case ALTIVEC_BUILTIN_VMINFP:
16362       arg0 = gimple_call_arg (stmt, 0);
16363       arg1 = gimple_call_arg (stmt, 1);
16364       lhs = gimple_call_lhs (stmt);
16365       g = gimple_build_assign (lhs, MIN_EXPR, arg0, arg1);
16366       gimple_set_location (g, gimple_location (stmt));
16367       gsi_replace (gsi, g, true);
16368       return true;
16369     /* flavors of vec_max.  */
16370     case VSX_BUILTIN_XVMAXDP:
16371     case P8V_BUILTIN_VMAXSD:
16372     case P8V_BUILTIN_VMAXUD:
16373     case ALTIVEC_BUILTIN_VMAXSB:
16374     case ALTIVEC_BUILTIN_VMAXSH:
16375     case ALTIVEC_BUILTIN_VMAXSW:
16376     case ALTIVEC_BUILTIN_VMAXUB:
16377     case ALTIVEC_BUILTIN_VMAXUH:
16378     case ALTIVEC_BUILTIN_VMAXUW:
16379     case ALTIVEC_BUILTIN_VMAXFP:
16380       arg0 = gimple_call_arg (stmt, 0);
16381       arg1 = gimple_call_arg (stmt, 1);
16382       lhs = gimple_call_lhs (stmt);
16383       g = gimple_build_assign (lhs, MAX_EXPR, arg0, arg1);
16384       gimple_set_location (g, gimple_location (stmt));
16385       gsi_replace (gsi, g, true);
16386       return true;
16387     /* Flavors of vec_eqv.  */
16388     case P8V_BUILTIN_EQV_V16QI:
16389     case P8V_BUILTIN_EQV_V8HI:
16390     case P8V_BUILTIN_EQV_V4SI:
16391     case P8V_BUILTIN_EQV_V4SF:
16392     case P8V_BUILTIN_EQV_V2DF:
16393     case P8V_BUILTIN_EQV_V2DI:
16394       arg0 = gimple_call_arg (stmt, 0);
16395       arg1 = gimple_call_arg (stmt, 1);
16396       lhs = gimple_call_lhs (stmt);
16397       temp = create_tmp_reg_or_ssa_name (TREE_TYPE (arg1));
16398       g = gimple_build_assign (temp, BIT_XOR_EXPR, arg0, arg1);
16399       gimple_set_location (g, gimple_location (stmt));
16400       gsi_insert_before (gsi, g, GSI_SAME_STMT);
16401       g = gimple_build_assign (lhs, BIT_NOT_EXPR, temp);
16402       gimple_set_location (g, gimple_location (stmt));
16403       gsi_replace (gsi, g, true);
16404       return true;
16405     /* Flavors of vec_rotate_left.  */
16406     case ALTIVEC_BUILTIN_VRLB:
16407     case ALTIVEC_BUILTIN_VRLH:
16408     case ALTIVEC_BUILTIN_VRLW:
16409     case P8V_BUILTIN_VRLD:
16410       arg0 = gimple_call_arg (stmt, 0);
16411       arg1 = gimple_call_arg (stmt, 1);
16412       lhs = gimple_call_lhs (stmt);
16413       g = gimple_build_assign (lhs, LROTATE_EXPR, arg0, arg1);
16414       gimple_set_location (g, gimple_location (stmt));
16415       gsi_replace (gsi, g, true);
16416       return true;
16417   /* Flavors of vector shift right algebraic.
16418      vec_sra{b,h,w} -> vsra{b,h,w}.  */
16419     case ALTIVEC_BUILTIN_VSRAB:
16420     case ALTIVEC_BUILTIN_VSRAH:
16421     case ALTIVEC_BUILTIN_VSRAW:
16422     case P8V_BUILTIN_VSRAD:
16423       arg0 = gimple_call_arg (stmt, 0);
16424       arg1 = gimple_call_arg (stmt, 1);
16425       lhs = gimple_call_lhs (stmt);
16426       g = gimple_build_assign (lhs, RSHIFT_EXPR, arg0, arg1);
16427       gimple_set_location (g, gimple_location (stmt));
16428       gsi_replace (gsi, g, true);
16429       return true;
16430    /* Flavors of vector shift left.
16431       builtin_altivec_vsl{b,h,w} -> vsl{b,h,w}.  */
16432     case ALTIVEC_BUILTIN_VSLB:
16433     case ALTIVEC_BUILTIN_VSLH:
16434     case ALTIVEC_BUILTIN_VSLW:
16435     case P8V_BUILTIN_VSLD:
16436       arg0 = gimple_call_arg (stmt, 0);
16437       if (INTEGRAL_TYPE_P (TREE_TYPE (TREE_TYPE (arg0)))
16438           && !TYPE_OVERFLOW_WRAPS (TREE_TYPE (TREE_TYPE (arg0))))
16439         return false;
16440       arg1 = gimple_call_arg (stmt, 1);
16441       lhs = gimple_call_lhs (stmt);
16442       g = gimple_build_assign (lhs, LSHIFT_EXPR, arg0, arg1);
16443       gimple_set_location (g, gimple_location (stmt));
16444       gsi_replace (gsi, g, true);
16445       return true;
16446     /* Flavors of vector shift right.  */
16447     case ALTIVEC_BUILTIN_VSRB:
16448     case ALTIVEC_BUILTIN_VSRH:
16449     case ALTIVEC_BUILTIN_VSRW:
16450     case P8V_BUILTIN_VSRD:
16451       {
16452         arg0 = gimple_call_arg (stmt, 0);
16453         arg1 = gimple_call_arg (stmt, 1);
16454         lhs = gimple_call_lhs (stmt);
16455         gimple_seq stmts = NULL;
16456         /* Convert arg0 to unsigned.  */
16457         tree arg0_unsigned
16458           = gimple_build (&stmts, VIEW_CONVERT_EXPR,
16459                           unsigned_type_for (TREE_TYPE (arg0)), arg0);
16460         tree res
16461           = gimple_build (&stmts, RSHIFT_EXPR,
16462                           TREE_TYPE (arg0_unsigned), arg0_unsigned, arg1);
16463         /* Convert result back to the lhs type.  */
16464         res = gimple_build (&stmts, VIEW_CONVERT_EXPR, TREE_TYPE (lhs), res);
16465         gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
16466         update_call_from_tree (gsi, res);
16467         return true;
16468       }
16469     /* Vector loads.  */
16470     case ALTIVEC_BUILTIN_LVX_V16QI:
16471     case ALTIVEC_BUILTIN_LVX_V8HI:
16472     case ALTIVEC_BUILTIN_LVX_V4SI:
16473     case ALTIVEC_BUILTIN_LVX_V4SF:
16474     case ALTIVEC_BUILTIN_LVX_V2DI:
16475     case ALTIVEC_BUILTIN_LVX_V2DF:
16476       {
16477         arg0 = gimple_call_arg (stmt, 0);  // offset
16478         arg1 = gimple_call_arg (stmt, 1);  // address
16479         /* Do not fold for -maltivec=be on LE targets.  */
16480         if (VECTOR_ELT_ORDER_BIG && !BYTES_BIG_ENDIAN)
16481           return false;
16482         lhs = gimple_call_lhs (stmt);
16483         location_t loc = gimple_location (stmt);
16484         /* Since arg1 may be cast to a different type, just use ptr_type_node
16485            here instead of trying to enforce TBAA on pointer types.  */
16486         tree arg1_type = ptr_type_node;
16487         tree lhs_type = TREE_TYPE (lhs);
16488         /* POINTER_PLUS_EXPR wants the offset to be of type 'sizetype'.  Create
16489            the tree using the value from arg0.  The resulting type will match
16490            the type of arg1.  */
16491         gimple_seq stmts = NULL;
16492         tree temp_offset = gimple_convert (&stmts, loc, sizetype, arg0);
16493         tree temp_addr = gimple_build (&stmts, loc, POINTER_PLUS_EXPR,
16494                                        arg1_type, arg1, temp_offset);
16495         /* Mask off any lower bits from the address.  */
16496         tree aligned_addr = gimple_build (&stmts, loc, BIT_AND_EXPR,
16497                                           arg1_type, temp_addr,
16498                                           build_int_cst (arg1_type, -16));
16499         gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
16500         /* Use the build2 helper to set up the mem_ref.  The MEM_REF could also
16501            take an offset, but since we've already incorporated the offset
16502            above, here we just pass in a zero.  */
16503         gimple *g
16504           = gimple_build_assign (lhs, build2 (MEM_REF, lhs_type, aligned_addr,
16505                                               build_int_cst (arg1_type, 0)));
16506         gimple_set_location (g, loc);
16507         gsi_replace (gsi, g, true);
16508         return true;
16509       }
16510     /* Vector stores.  */
16511     case ALTIVEC_BUILTIN_STVX_V16QI:
16512     case ALTIVEC_BUILTIN_STVX_V8HI:
16513     case ALTIVEC_BUILTIN_STVX_V4SI:
16514     case ALTIVEC_BUILTIN_STVX_V4SF:
16515     case ALTIVEC_BUILTIN_STVX_V2DI:
16516     case ALTIVEC_BUILTIN_STVX_V2DF:
16517       {
16518         /* Do not fold for -maltivec=be on LE targets.  */
16519         if (VECTOR_ELT_ORDER_BIG && !BYTES_BIG_ENDIAN)
16520           return false;
16521         arg0 = gimple_call_arg (stmt, 0); /* Value to be stored.  */
16522         arg1 = gimple_call_arg (stmt, 1); /* Offset.  */
16523         tree arg2 = gimple_call_arg (stmt, 2); /* Store-to address.  */
16524         location_t loc = gimple_location (stmt);
16525         tree arg0_type = TREE_TYPE (arg0);
16526         /* Use ptr_type_node (no TBAA) for the arg2_type.
16527            FIXME: (Richard)  "A proper fix would be to transition this type as
16528            seen from the frontend to GIMPLE, for example in a similar way we
16529            do for MEM_REFs by piggy-backing that on an extra argument, a
16530            constant zero pointer of the alias pointer type to use (which would
16531            also serve as a type indicator of the store itself).  I'd use a
16532            target specific internal function for this (not sure if we can have
16533            those target specific, but I guess if it's folded away then that's
16534            fine) and get away with the overload set."  */
16535         tree arg2_type = ptr_type_node;
16536         /* POINTER_PLUS_EXPR wants the offset to be of type 'sizetype'.  Create
16537            the tree using the value from arg0.  The resulting type will match
16538            the type of arg2.  */
16539         gimple_seq stmts = NULL;
16540         tree temp_offset = gimple_convert (&stmts, loc, sizetype, arg1);
16541         tree temp_addr = gimple_build (&stmts, loc, POINTER_PLUS_EXPR,
16542                                        arg2_type, arg2, temp_offset);
16543         /* Mask off any lower bits from the address.  */
16544         tree aligned_addr = gimple_build (&stmts, loc, BIT_AND_EXPR,
16545                                           arg2_type, temp_addr,
16546                                           build_int_cst (arg2_type, -16));
16547         gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
16548         /* The desired gimple result should be similar to:
16549            MEM[(__vector floatD.1407 *)_1] = vf1D.2697;  */
16550         gimple *g
16551           = gimple_build_assign (build2 (MEM_REF, arg0_type, aligned_addr,
16552                                          build_int_cst (arg2_type, 0)), arg0);
16553         gimple_set_location (g, loc);
16554         gsi_replace (gsi, g, true);
16555         return true;
16556       }
16557
16558     /* Vector Fused multiply-add (fma).  */
16559     case ALTIVEC_BUILTIN_VMADDFP:
16560     case VSX_BUILTIN_XVMADDDP:
16561     case ALTIVEC_BUILTIN_VMLADDUHM:
16562       {
16563         arg0 = gimple_call_arg (stmt, 0);
16564         arg1 = gimple_call_arg (stmt, 1);
16565         tree arg2 = gimple_call_arg (stmt, 2);
16566         lhs = gimple_call_lhs (stmt);
16567         gimple *g = gimple_build_assign (lhs, FMA_EXPR, arg0, arg1, arg2);
16568         gimple_set_location (g, gimple_location (stmt));
16569         gsi_replace (gsi, g, true);
16570         return true;
16571       }
16572
16573     /* Vector compares; EQ, NE, GE, GT, LE.  */
16574     case ALTIVEC_BUILTIN_VCMPEQUB:
16575     case ALTIVEC_BUILTIN_VCMPEQUH:
16576     case ALTIVEC_BUILTIN_VCMPEQUW:
16577     case P8V_BUILTIN_VCMPEQUD:
16578       fold_compare_helper (gsi, EQ_EXPR, stmt);
16579       return true;
16580
16581     case P9V_BUILTIN_CMPNEB:
16582     case P9V_BUILTIN_CMPNEH:
16583     case P9V_BUILTIN_CMPNEW:
16584       fold_compare_helper (gsi, NE_EXPR, stmt);
16585       return true;
16586
16587     case VSX_BUILTIN_CMPGE_16QI:
16588     case VSX_BUILTIN_CMPGE_U16QI:
16589     case VSX_BUILTIN_CMPGE_8HI:
16590     case VSX_BUILTIN_CMPGE_U8HI:
16591     case VSX_BUILTIN_CMPGE_4SI:
16592     case VSX_BUILTIN_CMPGE_U4SI:
16593     case VSX_BUILTIN_CMPGE_2DI:
16594     case VSX_BUILTIN_CMPGE_U2DI:
16595       fold_compare_helper (gsi, GE_EXPR, stmt);
16596       return true;
16597
16598     case ALTIVEC_BUILTIN_VCMPGTSB:
16599     case ALTIVEC_BUILTIN_VCMPGTUB:
16600     case ALTIVEC_BUILTIN_VCMPGTSH:
16601     case ALTIVEC_BUILTIN_VCMPGTUH:
16602     case ALTIVEC_BUILTIN_VCMPGTSW:
16603     case ALTIVEC_BUILTIN_VCMPGTUW:
16604     case P8V_BUILTIN_VCMPGTUD:
16605     case P8V_BUILTIN_VCMPGTSD:
16606       fold_compare_helper (gsi, GT_EXPR, stmt);
16607       return true;
16608
16609     case VSX_BUILTIN_CMPLE_16QI:
16610     case VSX_BUILTIN_CMPLE_U16QI:
16611     case VSX_BUILTIN_CMPLE_8HI:
16612     case VSX_BUILTIN_CMPLE_U8HI:
16613     case VSX_BUILTIN_CMPLE_4SI:
16614     case VSX_BUILTIN_CMPLE_U4SI:
16615     case VSX_BUILTIN_CMPLE_2DI:
16616     case VSX_BUILTIN_CMPLE_U2DI:
16617       fold_compare_helper (gsi, LE_EXPR, stmt);
16618       return true;
16619
16620     /* flavors of vec_splat_[us]{8,16,32}.  */
16621     case ALTIVEC_BUILTIN_VSPLTISB:
16622     case ALTIVEC_BUILTIN_VSPLTISH:
16623     case ALTIVEC_BUILTIN_VSPLTISW:
16624       {
16625          arg0 = gimple_call_arg (stmt, 0);
16626          lhs = gimple_call_lhs (stmt);
16627          /* Only fold the vec_splat_*() if arg0 is constant.  */
16628          if (TREE_CODE (arg0) != INTEGER_CST)
16629            return false;
16630          gimple_seq stmts = NULL;
16631          location_t loc = gimple_location (stmt);
16632          tree splat_value = gimple_convert (&stmts, loc,
16633                                             TREE_TYPE (TREE_TYPE (lhs)), arg0);
16634          gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
16635          tree splat_tree = build_vector_from_val (TREE_TYPE (lhs), splat_value);
16636          g = gimple_build_assign (lhs, splat_tree);
16637          gimple_set_location (g, gimple_location (stmt));
16638          gsi_replace (gsi, g, true);
16639          return true;
16640       }
16641
16642     default:
16643       if (TARGET_DEBUG_BUILTIN)
16644         fprintf (stderr, "gimple builtin intrinsic not matched:%d %s %s\n",
16645                  fn_code, fn_name1, fn_name2);
16646       break;
16647     }
16648
16649   return false;
16650 }
16651
16652 /* Expand an expression EXP that calls a built-in function,
16653    with result going to TARGET if that's convenient
16654    (and in mode MODE if that's convenient).
16655    SUBTARGET may be used as the target for computing one of EXP's operands.
16656    IGNORE is nonzero if the value is to be ignored.  */
16657
16658 static rtx
16659 rs6000_expand_builtin (tree exp, rtx target, rtx subtarget ATTRIBUTE_UNUSED,
16660                        machine_mode mode ATTRIBUTE_UNUSED,
16661                        int ignore ATTRIBUTE_UNUSED)
16662 {
16663   tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
16664   enum rs6000_builtins fcode
16665     = (enum rs6000_builtins)DECL_FUNCTION_CODE (fndecl);
16666   size_t uns_fcode = (size_t)fcode;
16667   const struct builtin_description *d;
16668   size_t i;
16669   rtx ret;
16670   bool success;
16671   HOST_WIDE_INT mask = rs6000_builtin_info[uns_fcode].mask;
16672   bool func_valid_p = ((rs6000_builtin_mask & mask) == mask);
16673   enum insn_code icode = rs6000_builtin_info[uns_fcode].icode;
16674
16675   /* We have two different modes (KFmode, TFmode) that are the IEEE 128-bit
16676      floating point type, depending on whether long double is the IBM extended
16677      double (KFmode) or long double is IEEE 128-bit (TFmode).  It is simpler if
16678      we only define one variant of the built-in function, and switch the code
16679      when defining it, rather than defining two built-ins and using the
16680      overload table in rs6000-c.c to switch between the two.  If we don't have
16681      the proper assembler, don't do this switch because CODE_FOR_*kf* and
16682      CODE_FOR_*tf* will be CODE_FOR_nothing.  */
16683 #ifdef HAVE_AS_POWER9
16684   if (FLOAT128_IEEE_P (TFmode))
16685     switch (icode)
16686       {
16687       default:
16688         break;
16689
16690       case CODE_FOR_sqrtkf2_odd:        icode = CODE_FOR_sqrttf2_odd;   break;
16691       case CODE_FOR_trunckfdf2_odd:     icode = CODE_FOR_trunctfdf2_odd; break;
16692       case CODE_FOR_addkf3_odd:         icode = CODE_FOR_addtf3_odd;    break;
16693       case CODE_FOR_subkf3_odd:         icode = CODE_FOR_subtf3_odd;    break;
16694       case CODE_FOR_mulkf3_odd:         icode = CODE_FOR_multf3_odd;    break;
16695       case CODE_FOR_divkf3_odd:         icode = CODE_FOR_divtf3_odd;    break;
16696       case CODE_FOR_fmakf4_odd:         icode = CODE_FOR_fmatf4_odd;    break;
16697       case CODE_FOR_xsxexpqp_kf:        icode = CODE_FOR_xsxexpqp_tf;   break;
16698       case CODE_FOR_xsxsigqp_kf:        icode = CODE_FOR_xsxsigqp_tf;   break;
16699       case CODE_FOR_xststdcnegqp_kf:    icode = CODE_FOR_xststdcnegqp_tf; break;
16700       case CODE_FOR_xsiexpqp_kf:        icode = CODE_FOR_xsiexpqp_tf;   break;
16701       case CODE_FOR_xsiexpqpf_kf:       icode = CODE_FOR_xsiexpqpf_tf;  break;
16702       case CODE_FOR_xststdcqp_kf:       icode = CODE_FOR_xststdcqp_tf;  break;
16703       }
16704 #endif
16705
16706   if (TARGET_DEBUG_BUILTIN)
16707     {
16708       const char *name1 = rs6000_builtin_info[uns_fcode].name;
16709       const char *name2 = (icode != CODE_FOR_nothing)
16710                            ? get_insn_name ((int) icode)
16711                            : "nothing";
16712       const char *name3;
16713
16714       switch (rs6000_builtin_info[uns_fcode].attr & RS6000_BTC_TYPE_MASK)
16715         {
16716         default:                   name3 = "unknown";   break;
16717         case RS6000_BTC_SPECIAL:   name3 = "special";   break;
16718         case RS6000_BTC_UNARY:     name3 = "unary";     break;
16719         case RS6000_BTC_BINARY:    name3 = "binary";    break;
16720         case RS6000_BTC_TERNARY:   name3 = "ternary";   break;
16721         case RS6000_BTC_PREDICATE: name3 = "predicate"; break;
16722         case RS6000_BTC_ABS:       name3 = "abs";       break;
16723         case RS6000_BTC_DST:       name3 = "dst";       break;
16724         }
16725
16726
16727       fprintf (stderr,
16728                "rs6000_expand_builtin, %s (%d), insn = %s (%d), type=%s%s\n",
16729                (name1) ? name1 : "---", fcode,
16730                (name2) ? name2 : "---", (int) icode,
16731                name3,
16732                func_valid_p ? "" : ", not valid");
16733     }        
16734
16735   if (!func_valid_p)
16736     {
16737       rs6000_invalid_builtin (fcode);
16738
16739       /* Given it is invalid, just generate a normal call.  */
16740       return expand_call (exp, target, ignore);
16741     }
16742
16743   switch (fcode)
16744     {
16745     case RS6000_BUILTIN_RECIP:
16746       return rs6000_expand_binop_builtin (CODE_FOR_recipdf3, exp, target);
16747
16748     case RS6000_BUILTIN_RECIPF:
16749       return rs6000_expand_binop_builtin (CODE_FOR_recipsf3, exp, target);
16750
16751     case RS6000_BUILTIN_RSQRTF:
16752       return rs6000_expand_unop_builtin (CODE_FOR_rsqrtsf2, exp, target);
16753
16754     case RS6000_BUILTIN_RSQRT:
16755       return rs6000_expand_unop_builtin (CODE_FOR_rsqrtdf2, exp, target);
16756
16757     case POWER7_BUILTIN_BPERMD:
16758       return rs6000_expand_binop_builtin (((TARGET_64BIT)
16759                                            ? CODE_FOR_bpermd_di
16760                                            : CODE_FOR_bpermd_si), exp, target);
16761
16762     case RS6000_BUILTIN_GET_TB:
16763       return rs6000_expand_zeroop_builtin (CODE_FOR_rs6000_get_timebase,
16764                                            target);
16765
16766     case RS6000_BUILTIN_MFTB:
16767       return rs6000_expand_zeroop_builtin (((TARGET_64BIT)
16768                                             ? CODE_FOR_rs6000_mftb_di
16769                                             : CODE_FOR_rs6000_mftb_si),
16770                                            target);
16771
16772     case RS6000_BUILTIN_MFFS:
16773       return rs6000_expand_zeroop_builtin (CODE_FOR_rs6000_mffs, target);
16774
16775     case RS6000_BUILTIN_MTFSF:
16776       return rs6000_expand_mtfsf_builtin (CODE_FOR_rs6000_mtfsf, exp);
16777
16778     case RS6000_BUILTIN_CPU_INIT:
16779     case RS6000_BUILTIN_CPU_IS:
16780     case RS6000_BUILTIN_CPU_SUPPORTS:
16781       return cpu_expand_builtin (fcode, exp, target);
16782
16783     case MISC_BUILTIN_SPEC_BARRIER:
16784       {
16785         emit_insn (gen_rs6000_speculation_barrier ());
16786         return NULL_RTX;
16787       }
16788
16789     case ALTIVEC_BUILTIN_MASK_FOR_LOAD:
16790     case ALTIVEC_BUILTIN_MASK_FOR_STORE:
16791       {
16792         int icode2 = (BYTES_BIG_ENDIAN ? (int) CODE_FOR_altivec_lvsr_direct
16793                      : (int) CODE_FOR_altivec_lvsl_direct);
16794         machine_mode tmode = insn_data[icode2].operand[0].mode;
16795         machine_mode mode = insn_data[icode2].operand[1].mode;
16796         tree arg;
16797         rtx op, addr, pat;
16798
16799         gcc_assert (TARGET_ALTIVEC);
16800
16801         arg = CALL_EXPR_ARG (exp, 0);
16802         gcc_assert (POINTER_TYPE_P (TREE_TYPE (arg)));
16803         op = expand_expr (arg, NULL_RTX, Pmode, EXPAND_NORMAL);
16804         addr = memory_address (mode, op);
16805         if (fcode == ALTIVEC_BUILTIN_MASK_FOR_STORE)
16806           op = addr;
16807         else
16808           {
16809             /* For the load case need to negate the address.  */
16810             op = gen_reg_rtx (GET_MODE (addr));
16811             emit_insn (gen_rtx_SET (op, gen_rtx_NEG (GET_MODE (addr), addr)));
16812           }
16813         op = gen_rtx_MEM (mode, op);
16814
16815         if (target == 0
16816             || GET_MODE (target) != tmode
16817             || ! (*insn_data[icode2].operand[0].predicate) (target, tmode))
16818           target = gen_reg_rtx (tmode);
16819
16820         pat = GEN_FCN (icode2) (target, op);
16821         if (!pat)
16822           return 0;
16823         emit_insn (pat);
16824
16825         return target;
16826       }
16827
16828     case ALTIVEC_BUILTIN_VCFUX:
16829     case ALTIVEC_BUILTIN_VCFSX:
16830     case ALTIVEC_BUILTIN_VCTUXS:
16831     case ALTIVEC_BUILTIN_VCTSXS:
16832   /* FIXME: There's got to be a nicer way to handle this case than
16833      constructing a new CALL_EXPR.  */
16834       if (call_expr_nargs (exp) == 1)
16835         {
16836           exp = build_call_nary (TREE_TYPE (exp), CALL_EXPR_FN (exp),
16837                                  2, CALL_EXPR_ARG (exp, 0), integer_zero_node);
16838         }
16839       break;
16840
16841     default:
16842       break;
16843     }
16844
16845   if (TARGET_ALTIVEC)
16846     {
16847       ret = altivec_expand_builtin (exp, target, &success);
16848
16849       if (success)
16850         return ret;
16851     }
16852   if (TARGET_PAIRED_FLOAT)
16853     {
16854       ret = paired_expand_builtin (exp, target, &success);
16855
16856       if (success)
16857         return ret;
16858     }  
16859   if (TARGET_HTM)
16860     {
16861       ret = htm_expand_builtin (exp, target, &success);
16862
16863       if (success)
16864         return ret;
16865     }  
16866
16867   unsigned attr = rs6000_builtin_info[uns_fcode].attr & RS6000_BTC_TYPE_MASK;
16868   /* RS6000_BTC_SPECIAL represents no-operand operators.  */
16869   gcc_assert (attr == RS6000_BTC_UNARY
16870               || attr == RS6000_BTC_BINARY
16871               || attr == RS6000_BTC_TERNARY
16872               || attr == RS6000_BTC_SPECIAL);
16873   
16874   /* Handle simple unary operations.  */
16875   d = bdesc_1arg;
16876   for (i = 0; i < ARRAY_SIZE (bdesc_1arg); i++, d++)
16877     if (d->code == fcode)
16878       return rs6000_expand_unop_builtin (icode, exp, target);
16879
16880   /* Handle simple binary operations.  */
16881   d = bdesc_2arg;
16882   for (i = 0; i < ARRAY_SIZE (bdesc_2arg); i++, d++)
16883     if (d->code == fcode)
16884       return rs6000_expand_binop_builtin (icode, exp, target);
16885
16886   /* Handle simple ternary operations.  */
16887   d = bdesc_3arg;
16888   for (i = 0; i < ARRAY_SIZE  (bdesc_3arg); i++, d++)
16889     if (d->code == fcode)
16890       return rs6000_expand_ternop_builtin (icode, exp, target);
16891
16892   /* Handle simple no-argument operations. */
16893   d = bdesc_0arg;
16894   for (i = 0; i < ARRAY_SIZE (bdesc_0arg); i++, d++)
16895     if (d->code == fcode)
16896       return rs6000_expand_zeroop_builtin (icode, target);
16897
16898   gcc_unreachable ();
16899 }
16900
16901 /* Create a builtin vector type with a name.  Taking care not to give
16902    the canonical type a name.  */
16903
16904 static tree
16905 rs6000_vector_type (const char *name, tree elt_type, unsigned num_elts)
16906 {
16907   tree result = build_vector_type (elt_type, num_elts);
16908
16909   /* Copy so we don't give the canonical type a name.  */
16910   result = build_variant_type_copy (result);
16911
16912   add_builtin_type (name, result);
16913
16914   return result;
16915 }
16916
16917 static void
16918 rs6000_init_builtins (void)
16919 {
16920   tree tdecl;
16921   tree ftype;
16922   machine_mode mode;
16923
16924   if (TARGET_DEBUG_BUILTIN)
16925     fprintf (stderr, "rs6000_init_builtins%s%s%s\n",
16926              (TARGET_PAIRED_FLOAT) ? ", paired"  : "",
16927              (TARGET_ALTIVEC)      ? ", altivec" : "",
16928              (TARGET_VSX)          ? ", vsx"     : "");
16929
16930   V2SI_type_node = build_vector_type (intSI_type_node, 2);
16931   V2SF_type_node = build_vector_type (float_type_node, 2);
16932   V2DI_type_node = rs6000_vector_type (TARGET_POWERPC64 ? "__vector long"
16933                                        : "__vector long long",
16934                                        intDI_type_node, 2);
16935   V2DF_type_node = rs6000_vector_type ("__vector double", double_type_node, 2);
16936   V4SI_type_node = rs6000_vector_type ("__vector signed int",
16937                                        intSI_type_node, 4);
16938   V4SF_type_node = rs6000_vector_type ("__vector float", float_type_node, 4);
16939   V8HI_type_node = rs6000_vector_type ("__vector signed short",
16940                                        intHI_type_node, 8);
16941   V16QI_type_node = rs6000_vector_type ("__vector signed char",
16942                                         intQI_type_node, 16);
16943
16944   unsigned_V16QI_type_node = rs6000_vector_type ("__vector unsigned char",
16945                                         unsigned_intQI_type_node, 16);
16946   unsigned_V8HI_type_node = rs6000_vector_type ("__vector unsigned short",
16947                                        unsigned_intHI_type_node, 8);
16948   unsigned_V4SI_type_node = rs6000_vector_type ("__vector unsigned int",
16949                                        unsigned_intSI_type_node, 4);
16950   unsigned_V2DI_type_node = rs6000_vector_type (TARGET_POWERPC64
16951                                        ? "__vector unsigned long"
16952                                        : "__vector unsigned long long",
16953                                        unsigned_intDI_type_node, 2);
16954
16955   opaque_V2SF_type_node = build_opaque_vector_type (float_type_node, 2);
16956   opaque_V2SI_type_node = build_opaque_vector_type (intSI_type_node, 2);
16957   opaque_p_V2SI_type_node = build_pointer_type (opaque_V2SI_type_node);
16958   opaque_V4SI_type_node = build_opaque_vector_type (intSI_type_node, 4);
16959
16960   const_str_type_node
16961     = build_pointer_type (build_qualified_type (char_type_node,
16962                                                 TYPE_QUAL_CONST));
16963
16964   /* We use V1TI mode as a special container to hold __int128_t items that
16965      must live in VSX registers.  */
16966   if (intTI_type_node)
16967     {
16968       V1TI_type_node = rs6000_vector_type ("__vector __int128",
16969                                            intTI_type_node, 1);
16970       unsigned_V1TI_type_node
16971         = rs6000_vector_type ("__vector unsigned __int128",
16972                               unsigned_intTI_type_node, 1);
16973     }
16974
16975   /* The 'vector bool ...' types must be kept distinct from 'vector unsigned ...'
16976      types, especially in C++ land.  Similarly, 'vector pixel' is distinct from
16977      'vector unsigned short'.  */
16978
16979   bool_char_type_node = build_distinct_type_copy (unsigned_intQI_type_node);
16980   bool_short_type_node = build_distinct_type_copy (unsigned_intHI_type_node);
16981   bool_int_type_node = build_distinct_type_copy (unsigned_intSI_type_node);
16982   bool_long_type_node = build_distinct_type_copy (unsigned_intDI_type_node);
16983   pixel_type_node = build_distinct_type_copy (unsigned_intHI_type_node);
16984
16985   long_integer_type_internal_node = long_integer_type_node;
16986   long_unsigned_type_internal_node = long_unsigned_type_node;
16987   long_long_integer_type_internal_node = long_long_integer_type_node;
16988   long_long_unsigned_type_internal_node = long_long_unsigned_type_node;
16989   intQI_type_internal_node = intQI_type_node;
16990   uintQI_type_internal_node = unsigned_intQI_type_node;
16991   intHI_type_internal_node = intHI_type_node;
16992   uintHI_type_internal_node = unsigned_intHI_type_node;
16993   intSI_type_internal_node = intSI_type_node;
16994   uintSI_type_internal_node = unsigned_intSI_type_node;
16995   intDI_type_internal_node = intDI_type_node;
16996   uintDI_type_internal_node = unsigned_intDI_type_node;
16997   intTI_type_internal_node = intTI_type_node;
16998   uintTI_type_internal_node = unsigned_intTI_type_node;
16999   float_type_internal_node = float_type_node;
17000   double_type_internal_node = double_type_node;
17001   long_double_type_internal_node = long_double_type_node;
17002   dfloat64_type_internal_node = dfloat64_type_node;
17003   dfloat128_type_internal_node = dfloat128_type_node;
17004   void_type_internal_node = void_type_node;
17005
17006   /* 128-bit floating point support.  KFmode is IEEE 128-bit floating point.
17007      IFmode is the IBM extended 128-bit format that is a pair of doubles.
17008      TFmode will be either IEEE 128-bit floating point or the IBM double-double
17009      format that uses a pair of doubles, depending on the switches and
17010      defaults.
17011
17012      If we don't support for either 128-bit IBM double double or IEEE 128-bit
17013      floating point, we need make sure the type is non-zero or else self-test
17014      fails during bootstrap.
17015
17016      We don't register a built-in type for __ibm128 if the type is the same as
17017      long double.  Instead we add a #define for __ibm128 in
17018      rs6000_cpu_cpp_builtins to long double.
17019
17020      For IEEE 128-bit floating point, always create the type __ieee128.  If the
17021      user used -mfloat128, rs6000-c.c will create a define from __float128 to
17022      __ieee128.  */
17023   if (TARGET_LONG_DOUBLE_128 && FLOAT128_IEEE_P (TFmode))
17024     {
17025       ibm128_float_type_node = make_node (REAL_TYPE);
17026       TYPE_PRECISION (ibm128_float_type_node) = 128;
17027       SET_TYPE_MODE (ibm128_float_type_node, IFmode);
17028       layout_type (ibm128_float_type_node);
17029
17030       lang_hooks.types.register_builtin_type (ibm128_float_type_node,
17031                                               "__ibm128");
17032     }
17033   else
17034     ibm128_float_type_node = long_double_type_node;
17035
17036   if (TARGET_FLOAT128_TYPE)
17037     {
17038       ieee128_float_type_node = float128_type_node;
17039       lang_hooks.types.register_builtin_type (ieee128_float_type_node,
17040                                               "__ieee128");
17041     }
17042
17043   else
17044     ieee128_float_type_node = long_double_type_node;
17045
17046   /* Initialize the modes for builtin_function_type, mapping a machine mode to
17047      tree type node.  */
17048   builtin_mode_to_type[QImode][0] = integer_type_node;
17049   builtin_mode_to_type[HImode][0] = integer_type_node;
17050   builtin_mode_to_type[SImode][0] = intSI_type_node;
17051   builtin_mode_to_type[SImode][1] = unsigned_intSI_type_node;
17052   builtin_mode_to_type[DImode][0] = intDI_type_node;
17053   builtin_mode_to_type[DImode][1] = unsigned_intDI_type_node;
17054   builtin_mode_to_type[TImode][0] = intTI_type_node;
17055   builtin_mode_to_type[TImode][1] = unsigned_intTI_type_node;
17056   builtin_mode_to_type[SFmode][0] = float_type_node;
17057   builtin_mode_to_type[DFmode][0] = double_type_node;
17058   builtin_mode_to_type[IFmode][0] = ibm128_float_type_node;
17059   builtin_mode_to_type[KFmode][0] = ieee128_float_type_node;
17060   builtin_mode_to_type[TFmode][0] = long_double_type_node;
17061   builtin_mode_to_type[DDmode][0] = dfloat64_type_node;
17062   builtin_mode_to_type[TDmode][0] = dfloat128_type_node;
17063   builtin_mode_to_type[V1TImode][0] = V1TI_type_node;
17064   builtin_mode_to_type[V1TImode][1] = unsigned_V1TI_type_node;
17065   builtin_mode_to_type[V2SImode][0] = V2SI_type_node;
17066   builtin_mode_to_type[V2SFmode][0] = V2SF_type_node;
17067   builtin_mode_to_type[V2DImode][0] = V2DI_type_node;
17068   builtin_mode_to_type[V2DImode][1] = unsigned_V2DI_type_node;
17069   builtin_mode_to_type[V2DFmode][0] = V2DF_type_node;
17070   builtin_mode_to_type[V4SImode][0] = V4SI_type_node;
17071   builtin_mode_to_type[V4SImode][1] = unsigned_V4SI_type_node;
17072   builtin_mode_to_type[V4SFmode][0] = V4SF_type_node;
17073   builtin_mode_to_type[V8HImode][0] = V8HI_type_node;
17074   builtin_mode_to_type[V8HImode][1] = unsigned_V8HI_type_node;
17075   builtin_mode_to_type[V16QImode][0] = V16QI_type_node;
17076   builtin_mode_to_type[V16QImode][1] = unsigned_V16QI_type_node;
17077
17078   tdecl = add_builtin_type ("__bool char", bool_char_type_node);
17079   TYPE_NAME (bool_char_type_node) = tdecl;
17080
17081   tdecl = add_builtin_type ("__bool short", bool_short_type_node);
17082   TYPE_NAME (bool_short_type_node) = tdecl;
17083
17084   tdecl = add_builtin_type ("__bool int", bool_int_type_node);
17085   TYPE_NAME (bool_int_type_node) = tdecl;
17086
17087   tdecl = add_builtin_type ("__pixel", pixel_type_node);
17088   TYPE_NAME (pixel_type_node) = tdecl;
17089
17090   bool_V16QI_type_node = rs6000_vector_type ("__vector __bool char",
17091                                              bool_char_type_node, 16);
17092   bool_V8HI_type_node = rs6000_vector_type ("__vector __bool short",
17093                                             bool_short_type_node, 8);
17094   bool_V4SI_type_node = rs6000_vector_type ("__vector __bool int",
17095                                             bool_int_type_node, 4);
17096   bool_V2DI_type_node = rs6000_vector_type (TARGET_POWERPC64
17097                                             ? "__vector __bool long"
17098                                             : "__vector __bool long long",
17099                                             bool_long_type_node, 2);
17100   pixel_V8HI_type_node = rs6000_vector_type ("__vector __pixel",
17101                                              pixel_type_node, 8);
17102
17103   /* Paired builtins are only available if you build a compiler with the
17104      appropriate options, so only create those builtins with the appropriate
17105      compiler option.  Create Altivec and VSX builtins on machines with at
17106      least the general purpose extensions (970 and newer) to allow the use of
17107      the target attribute.  */
17108   if (TARGET_PAIRED_FLOAT)
17109     paired_init_builtins ();
17110   if (TARGET_EXTRA_BUILTINS)
17111     altivec_init_builtins ();
17112   if (TARGET_HTM)
17113     htm_init_builtins ();
17114
17115   if (TARGET_EXTRA_BUILTINS || TARGET_PAIRED_FLOAT)
17116     rs6000_common_init_builtins ();
17117
17118   ftype = builtin_function_type (DFmode, DFmode, DFmode, VOIDmode,
17119                                  RS6000_BUILTIN_RECIP, "__builtin_recipdiv");
17120   def_builtin ("__builtin_recipdiv", ftype, RS6000_BUILTIN_RECIP);
17121
17122   ftype = builtin_function_type (SFmode, SFmode, SFmode, VOIDmode,
17123                                  RS6000_BUILTIN_RECIPF, "__builtin_recipdivf");
17124   def_builtin ("__builtin_recipdivf", ftype, RS6000_BUILTIN_RECIPF);
17125
17126   ftype = builtin_function_type (DFmode, DFmode, VOIDmode, VOIDmode,
17127                                  RS6000_BUILTIN_RSQRT, "__builtin_rsqrt");
17128   def_builtin ("__builtin_rsqrt", ftype, RS6000_BUILTIN_RSQRT);
17129
17130   ftype = builtin_function_type (SFmode, SFmode, VOIDmode, VOIDmode,
17131                                  RS6000_BUILTIN_RSQRTF, "__builtin_rsqrtf");
17132   def_builtin ("__builtin_rsqrtf", ftype, RS6000_BUILTIN_RSQRTF);
17133
17134   mode = (TARGET_64BIT) ? DImode : SImode;
17135   ftype = builtin_function_type (mode, mode, mode, VOIDmode,
17136                                  POWER7_BUILTIN_BPERMD, "__builtin_bpermd");
17137   def_builtin ("__builtin_bpermd", ftype, POWER7_BUILTIN_BPERMD);
17138
17139   ftype = build_function_type_list (unsigned_intDI_type_node,
17140                                     NULL_TREE);
17141   def_builtin ("__builtin_ppc_get_timebase", ftype, RS6000_BUILTIN_GET_TB);
17142
17143   if (TARGET_64BIT)
17144     ftype = build_function_type_list (unsigned_intDI_type_node,
17145                                       NULL_TREE);
17146   else
17147     ftype = build_function_type_list (unsigned_intSI_type_node,
17148                                       NULL_TREE);
17149   def_builtin ("__builtin_ppc_mftb", ftype, RS6000_BUILTIN_MFTB);
17150
17151   ftype = build_function_type_list (double_type_node, NULL_TREE);
17152   def_builtin ("__builtin_mffs", ftype, RS6000_BUILTIN_MFFS);
17153
17154   ftype = build_function_type_list (void_type_node,
17155                                     intSI_type_node, double_type_node,
17156                                     NULL_TREE);
17157   def_builtin ("__builtin_mtfsf", ftype, RS6000_BUILTIN_MTFSF);
17158
17159   ftype = build_function_type_list (void_type_node, NULL_TREE);
17160   def_builtin ("__builtin_cpu_init", ftype, RS6000_BUILTIN_CPU_INIT);
17161   def_builtin ("__builtin_rs6000_speculation_barrier", ftype,
17162                MISC_BUILTIN_SPEC_BARRIER);
17163
17164   ftype = build_function_type_list (bool_int_type_node, const_ptr_type_node,
17165                                     NULL_TREE);
17166   def_builtin ("__builtin_cpu_is", ftype, RS6000_BUILTIN_CPU_IS);
17167   def_builtin ("__builtin_cpu_supports", ftype, RS6000_BUILTIN_CPU_SUPPORTS);
17168
17169   /* AIX libm provides clog as __clog.  */
17170   if (TARGET_XCOFF &&
17171       (tdecl = builtin_decl_explicit (BUILT_IN_CLOG)) != NULL_TREE)
17172     set_user_assembler_name (tdecl, "__clog");
17173
17174 #ifdef SUBTARGET_INIT_BUILTINS
17175   SUBTARGET_INIT_BUILTINS;
17176 #endif
17177 }
17178
17179 /* Returns the rs6000 builtin decl for CODE.  */
17180
17181 static tree
17182 rs6000_builtin_decl (unsigned code, bool initialize_p ATTRIBUTE_UNUSED)
17183 {
17184   HOST_WIDE_INT fnmask;
17185
17186   if (code >= RS6000_BUILTIN_COUNT)
17187     return error_mark_node;
17188
17189   fnmask = rs6000_builtin_info[code].mask;
17190   if ((fnmask & rs6000_builtin_mask) != fnmask)
17191     {
17192       rs6000_invalid_builtin ((enum rs6000_builtins)code);
17193       return error_mark_node;
17194     }
17195
17196   return rs6000_builtin_decls[code];
17197 }
17198
17199 static void
17200 paired_init_builtins (void)
17201 {
17202   const struct builtin_description *d;
17203   size_t i;
17204   HOST_WIDE_INT builtin_mask = rs6000_builtin_mask;
17205
17206    tree int_ftype_int_v2sf_v2sf
17207     = build_function_type_list (integer_type_node,
17208                                 integer_type_node,
17209                                 V2SF_type_node,
17210                                 V2SF_type_node,
17211                                 NULL_TREE);
17212   tree pcfloat_type_node =
17213     build_pointer_type (build_qualified_type
17214                         (float_type_node, TYPE_QUAL_CONST));
17215
17216   tree v2sf_ftype_long_pcfloat = build_function_type_list (V2SF_type_node,
17217                                                            long_integer_type_node,
17218                                                            pcfloat_type_node,
17219                                                            NULL_TREE);
17220   tree void_ftype_v2sf_long_pcfloat =
17221     build_function_type_list (void_type_node,
17222                               V2SF_type_node,
17223                               long_integer_type_node,
17224                               pcfloat_type_node,
17225                               NULL_TREE);
17226
17227
17228   def_builtin ("__builtin_paired_lx", v2sf_ftype_long_pcfloat,
17229                PAIRED_BUILTIN_LX);
17230
17231
17232   def_builtin ("__builtin_paired_stx", void_ftype_v2sf_long_pcfloat,
17233                PAIRED_BUILTIN_STX);
17234
17235   /* Predicates.  */
17236   d = bdesc_paired_preds;
17237   for (i = 0; i < ARRAY_SIZE (bdesc_paired_preds); ++i, d++)
17238     {
17239       tree type;
17240       HOST_WIDE_INT mask = d->mask;
17241
17242       if ((mask & builtin_mask) != mask)
17243         {
17244           if (TARGET_DEBUG_BUILTIN)
17245             fprintf (stderr, "paired_init_builtins, skip predicate %s\n",
17246                      d->name);
17247           continue;
17248         }
17249
17250       /* Cannot define builtin if the instruction is disabled.  */
17251       gcc_assert (d->icode != CODE_FOR_nothing);
17252
17253       if (TARGET_DEBUG_BUILTIN)
17254         fprintf (stderr, "paired pred #%d, insn = %s [%d], mode = %s\n",
17255                  (int)i, get_insn_name (d->icode), (int)d->icode,
17256                  GET_MODE_NAME (insn_data[d->icode].operand[1].mode));
17257
17258       switch (insn_data[d->icode].operand[1].mode)
17259         {
17260         case E_V2SFmode:
17261           type = int_ftype_int_v2sf_v2sf;
17262           break;
17263         default:
17264           gcc_unreachable ();
17265         }
17266
17267       def_builtin (d->name, type, d->code);
17268     }
17269 }
17270
17271 static void
17272 altivec_init_builtins (void)
17273 {
17274   const struct builtin_description *d;
17275   size_t i;
17276   tree ftype;
17277   tree decl;
17278   HOST_WIDE_INT builtin_mask = rs6000_builtin_mask;
17279
17280   tree pvoid_type_node = build_pointer_type (void_type_node);
17281
17282   tree pcvoid_type_node
17283     = build_pointer_type (build_qualified_type (void_type_node,
17284                                                 TYPE_QUAL_CONST));
17285
17286   tree int_ftype_opaque
17287     = build_function_type_list (integer_type_node,
17288                                 opaque_V4SI_type_node, NULL_TREE);
17289   tree opaque_ftype_opaque
17290     = build_function_type_list (integer_type_node, NULL_TREE);
17291   tree opaque_ftype_opaque_int
17292     = build_function_type_list (opaque_V4SI_type_node,
17293                                 opaque_V4SI_type_node, integer_type_node, NULL_TREE);
17294   tree opaque_ftype_opaque_opaque_int
17295     = build_function_type_list (opaque_V4SI_type_node,
17296                                 opaque_V4SI_type_node, opaque_V4SI_type_node,
17297                                 integer_type_node, NULL_TREE);
17298   tree opaque_ftype_opaque_opaque_opaque
17299     = build_function_type_list (opaque_V4SI_type_node,
17300                                 opaque_V4SI_type_node, opaque_V4SI_type_node,
17301                                 opaque_V4SI_type_node, NULL_TREE);
17302   tree opaque_ftype_opaque_opaque
17303     = build_function_type_list (opaque_V4SI_type_node,
17304                                 opaque_V4SI_type_node, opaque_V4SI_type_node,
17305                                 NULL_TREE);
17306   tree int_ftype_int_opaque_opaque
17307     = build_function_type_list (integer_type_node,
17308                                 integer_type_node, opaque_V4SI_type_node,
17309                                 opaque_V4SI_type_node, NULL_TREE);
17310   tree int_ftype_int_v4si_v4si
17311     = build_function_type_list (integer_type_node,
17312                                 integer_type_node, V4SI_type_node,
17313                                 V4SI_type_node, NULL_TREE);
17314   tree int_ftype_int_v2di_v2di
17315     = build_function_type_list (integer_type_node,
17316                                 integer_type_node, V2DI_type_node,
17317                                 V2DI_type_node, NULL_TREE);
17318   tree void_ftype_v4si
17319     = build_function_type_list (void_type_node, V4SI_type_node, NULL_TREE);
17320   tree v8hi_ftype_void
17321     = build_function_type_list (V8HI_type_node, NULL_TREE);
17322   tree void_ftype_void
17323     = build_function_type_list (void_type_node, NULL_TREE);
17324   tree void_ftype_int
17325     = build_function_type_list (void_type_node, integer_type_node, NULL_TREE);
17326
17327   tree opaque_ftype_long_pcvoid
17328     = build_function_type_list (opaque_V4SI_type_node,
17329                                 long_integer_type_node, pcvoid_type_node,
17330                                 NULL_TREE);
17331   tree v16qi_ftype_long_pcvoid
17332     = build_function_type_list (V16QI_type_node,
17333                                 long_integer_type_node, pcvoid_type_node,
17334                                 NULL_TREE);
17335   tree v8hi_ftype_long_pcvoid
17336     = build_function_type_list (V8HI_type_node,
17337                                 long_integer_type_node, pcvoid_type_node,
17338                                 NULL_TREE);
17339   tree v4si_ftype_long_pcvoid
17340     = build_function_type_list (V4SI_type_node,
17341                                 long_integer_type_node, pcvoid_type_node,
17342                                 NULL_TREE);
17343   tree v4sf_ftype_long_pcvoid
17344     = build_function_type_list (V4SF_type_node,
17345                                 long_integer_type_node, pcvoid_type_node,
17346                                 NULL_TREE);
17347   tree v2df_ftype_long_pcvoid
17348     = build_function_type_list (V2DF_type_node,
17349                                 long_integer_type_node, pcvoid_type_node,
17350                                 NULL_TREE);
17351   tree v2di_ftype_long_pcvoid
17352     = build_function_type_list (V2DI_type_node,
17353                                 long_integer_type_node, pcvoid_type_node,
17354                                 NULL_TREE);
17355
17356   tree void_ftype_opaque_long_pvoid
17357     = build_function_type_list (void_type_node,
17358                                 opaque_V4SI_type_node, long_integer_type_node,
17359                                 pvoid_type_node, NULL_TREE);
17360   tree void_ftype_v4si_long_pvoid
17361     = build_function_type_list (void_type_node,
17362                                 V4SI_type_node, long_integer_type_node,
17363                                 pvoid_type_node, NULL_TREE);
17364   tree void_ftype_v16qi_long_pvoid
17365     = build_function_type_list (void_type_node,
17366                                 V16QI_type_node, long_integer_type_node,
17367                                 pvoid_type_node, NULL_TREE);
17368
17369   tree void_ftype_v16qi_pvoid_long
17370     = build_function_type_list (void_type_node,
17371                                 V16QI_type_node, pvoid_type_node,
17372                                 long_integer_type_node, NULL_TREE);
17373
17374   tree void_ftype_v8hi_long_pvoid
17375     = build_function_type_list (void_type_node,
17376                                 V8HI_type_node, long_integer_type_node,
17377                                 pvoid_type_node, NULL_TREE);
17378   tree void_ftype_v4sf_long_pvoid
17379     = build_function_type_list (void_type_node,
17380                                 V4SF_type_node, long_integer_type_node,
17381                                 pvoid_type_node, NULL_TREE);
17382   tree void_ftype_v2df_long_pvoid
17383     = build_function_type_list (void_type_node,
17384                                 V2DF_type_node, long_integer_type_node,
17385                                 pvoid_type_node, NULL_TREE);
17386   tree void_ftype_v2di_long_pvoid
17387     = build_function_type_list (void_type_node,
17388                                 V2DI_type_node, long_integer_type_node,
17389                                 pvoid_type_node, NULL_TREE);
17390   tree int_ftype_int_v8hi_v8hi
17391     = build_function_type_list (integer_type_node,
17392                                 integer_type_node, V8HI_type_node,
17393                                 V8HI_type_node, NULL_TREE);
17394   tree int_ftype_int_v16qi_v16qi
17395     = build_function_type_list (integer_type_node,
17396                                 integer_type_node, V16QI_type_node,
17397                                 V16QI_type_node, NULL_TREE);
17398   tree int_ftype_int_v4sf_v4sf
17399     = build_function_type_list (integer_type_node,
17400                                 integer_type_node, V4SF_type_node,
17401                                 V4SF_type_node, NULL_TREE);
17402   tree int_ftype_int_v2df_v2df
17403     = build_function_type_list (integer_type_node,
17404                                 integer_type_node, V2DF_type_node,
17405                                 V2DF_type_node, NULL_TREE);
17406   tree v2di_ftype_v2di
17407     = build_function_type_list (V2DI_type_node, V2DI_type_node, NULL_TREE);
17408   tree v4si_ftype_v4si
17409     = build_function_type_list (V4SI_type_node, V4SI_type_node, NULL_TREE);
17410   tree v8hi_ftype_v8hi
17411     = build_function_type_list (V8HI_type_node, V8HI_type_node, NULL_TREE);
17412   tree v16qi_ftype_v16qi
17413     = build_function_type_list (V16QI_type_node, V16QI_type_node, NULL_TREE);
17414   tree v4sf_ftype_v4sf
17415     = build_function_type_list (V4SF_type_node, V4SF_type_node, NULL_TREE);
17416   tree v2df_ftype_v2df
17417     = build_function_type_list (V2DF_type_node, V2DF_type_node, NULL_TREE);
17418   tree void_ftype_pcvoid_int_int
17419     = build_function_type_list (void_type_node,
17420                                 pcvoid_type_node, integer_type_node,
17421                                 integer_type_node, NULL_TREE);
17422
17423   def_builtin ("__builtin_altivec_mtvscr", void_ftype_v4si, ALTIVEC_BUILTIN_MTVSCR);
17424   def_builtin ("__builtin_altivec_mfvscr", v8hi_ftype_void, ALTIVEC_BUILTIN_MFVSCR);
17425   def_builtin ("__builtin_altivec_dssall", void_ftype_void, ALTIVEC_BUILTIN_DSSALL);
17426   def_builtin ("__builtin_altivec_dss", void_ftype_int, ALTIVEC_BUILTIN_DSS);
17427   def_builtin ("__builtin_altivec_lvsl", v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVSL);
17428   def_builtin ("__builtin_altivec_lvsr", v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVSR);
17429   def_builtin ("__builtin_altivec_lvebx", v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVEBX);
17430   def_builtin ("__builtin_altivec_lvehx", v8hi_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVEHX);
17431   def_builtin ("__builtin_altivec_lvewx", v4si_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVEWX);
17432   def_builtin ("__builtin_altivec_lvxl", v4si_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVXL);
17433   def_builtin ("__builtin_altivec_lvxl_v2df", v2df_ftype_long_pcvoid,
17434                ALTIVEC_BUILTIN_LVXL_V2DF);
17435   def_builtin ("__builtin_altivec_lvxl_v2di", v2di_ftype_long_pcvoid,
17436                ALTIVEC_BUILTIN_LVXL_V2DI);
17437   def_builtin ("__builtin_altivec_lvxl_v4sf", v4sf_ftype_long_pcvoid,
17438                ALTIVEC_BUILTIN_LVXL_V4SF);
17439   def_builtin ("__builtin_altivec_lvxl_v4si", v4si_ftype_long_pcvoid,
17440                ALTIVEC_BUILTIN_LVXL_V4SI);
17441   def_builtin ("__builtin_altivec_lvxl_v8hi", v8hi_ftype_long_pcvoid,
17442                ALTIVEC_BUILTIN_LVXL_V8HI);
17443   def_builtin ("__builtin_altivec_lvxl_v16qi", v16qi_ftype_long_pcvoid,
17444                ALTIVEC_BUILTIN_LVXL_V16QI);
17445   def_builtin ("__builtin_altivec_lvx", v4si_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVX);
17446   def_builtin ("__builtin_altivec_lvx_v2df", v2df_ftype_long_pcvoid,
17447                ALTIVEC_BUILTIN_LVX_V2DF);
17448   def_builtin ("__builtin_altivec_lvx_v2di", v2di_ftype_long_pcvoid,
17449                ALTIVEC_BUILTIN_LVX_V2DI);
17450   def_builtin ("__builtin_altivec_lvx_v4sf", v4sf_ftype_long_pcvoid,
17451                ALTIVEC_BUILTIN_LVX_V4SF);
17452   def_builtin ("__builtin_altivec_lvx_v4si", v4si_ftype_long_pcvoid,
17453                ALTIVEC_BUILTIN_LVX_V4SI);
17454   def_builtin ("__builtin_altivec_lvx_v8hi", v8hi_ftype_long_pcvoid,
17455                ALTIVEC_BUILTIN_LVX_V8HI);
17456   def_builtin ("__builtin_altivec_lvx_v16qi", v16qi_ftype_long_pcvoid,
17457                ALTIVEC_BUILTIN_LVX_V16QI);
17458   def_builtin ("__builtin_altivec_stvx", void_ftype_v4si_long_pvoid, ALTIVEC_BUILTIN_STVX);
17459   def_builtin ("__builtin_altivec_stvx_v2df", void_ftype_v2df_long_pvoid,
17460                ALTIVEC_BUILTIN_STVX_V2DF);
17461   def_builtin ("__builtin_altivec_stvx_v2di", void_ftype_v2di_long_pvoid,
17462                ALTIVEC_BUILTIN_STVX_V2DI);
17463   def_builtin ("__builtin_altivec_stvx_v4sf", void_ftype_v4sf_long_pvoid,
17464                ALTIVEC_BUILTIN_STVX_V4SF);
17465   def_builtin ("__builtin_altivec_stvx_v4si", void_ftype_v4si_long_pvoid,
17466                ALTIVEC_BUILTIN_STVX_V4SI);
17467   def_builtin ("__builtin_altivec_stvx_v8hi", void_ftype_v8hi_long_pvoid,
17468                ALTIVEC_BUILTIN_STVX_V8HI);
17469   def_builtin ("__builtin_altivec_stvx_v16qi", void_ftype_v16qi_long_pvoid,
17470                ALTIVEC_BUILTIN_STVX_V16QI);
17471   def_builtin ("__builtin_altivec_stvewx", void_ftype_v4si_long_pvoid, ALTIVEC_BUILTIN_STVEWX);
17472   def_builtin ("__builtin_altivec_stvxl", void_ftype_v4si_long_pvoid, ALTIVEC_BUILTIN_STVXL);
17473   def_builtin ("__builtin_altivec_stvxl_v2df", void_ftype_v2df_long_pvoid,
17474                ALTIVEC_BUILTIN_STVXL_V2DF);
17475   def_builtin ("__builtin_altivec_stvxl_v2di", void_ftype_v2di_long_pvoid,
17476                ALTIVEC_BUILTIN_STVXL_V2DI);
17477   def_builtin ("__builtin_altivec_stvxl_v4sf", void_ftype_v4sf_long_pvoid,
17478                ALTIVEC_BUILTIN_STVXL_V4SF);
17479   def_builtin ("__builtin_altivec_stvxl_v4si", void_ftype_v4si_long_pvoid,
17480                ALTIVEC_BUILTIN_STVXL_V4SI);
17481   def_builtin ("__builtin_altivec_stvxl_v8hi", void_ftype_v8hi_long_pvoid,
17482                ALTIVEC_BUILTIN_STVXL_V8HI);
17483   def_builtin ("__builtin_altivec_stvxl_v16qi", void_ftype_v16qi_long_pvoid,
17484                ALTIVEC_BUILTIN_STVXL_V16QI);
17485   def_builtin ("__builtin_altivec_stvebx", void_ftype_v16qi_long_pvoid, ALTIVEC_BUILTIN_STVEBX);
17486   def_builtin ("__builtin_altivec_stvehx", void_ftype_v8hi_long_pvoid, ALTIVEC_BUILTIN_STVEHX);
17487   def_builtin ("__builtin_vec_ld", opaque_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LD);
17488   def_builtin ("__builtin_vec_lde", opaque_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LDE);
17489   def_builtin ("__builtin_vec_ldl", opaque_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LDL);
17490   def_builtin ("__builtin_vec_lvsl", v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LVSL);
17491   def_builtin ("__builtin_vec_lvsr", v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LVSR);
17492   def_builtin ("__builtin_vec_lvebx", v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LVEBX);
17493   def_builtin ("__builtin_vec_lvehx", v8hi_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LVEHX);
17494   def_builtin ("__builtin_vec_lvewx", v4si_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LVEWX);
17495   def_builtin ("__builtin_vec_st", void_ftype_opaque_long_pvoid, ALTIVEC_BUILTIN_VEC_ST);
17496   def_builtin ("__builtin_vec_ste", void_ftype_opaque_long_pvoid, ALTIVEC_BUILTIN_VEC_STE);
17497   def_builtin ("__builtin_vec_stl", void_ftype_opaque_long_pvoid, ALTIVEC_BUILTIN_VEC_STL);
17498   def_builtin ("__builtin_vec_stvewx", void_ftype_opaque_long_pvoid, ALTIVEC_BUILTIN_VEC_STVEWX);
17499   def_builtin ("__builtin_vec_stvebx", void_ftype_opaque_long_pvoid, ALTIVEC_BUILTIN_VEC_STVEBX);
17500   def_builtin ("__builtin_vec_stvehx", void_ftype_opaque_long_pvoid, ALTIVEC_BUILTIN_VEC_STVEHX);
17501
17502   def_builtin ("__builtin_vsx_lxvd2x_v2df", v2df_ftype_long_pcvoid,
17503                VSX_BUILTIN_LXVD2X_V2DF);
17504   def_builtin ("__builtin_vsx_lxvd2x_v2di", v2di_ftype_long_pcvoid,
17505                VSX_BUILTIN_LXVD2X_V2DI);
17506   def_builtin ("__builtin_vsx_lxvw4x_v4sf", v4sf_ftype_long_pcvoid,
17507                VSX_BUILTIN_LXVW4X_V4SF);
17508   def_builtin ("__builtin_vsx_lxvw4x_v4si", v4si_ftype_long_pcvoid,
17509                VSX_BUILTIN_LXVW4X_V4SI);
17510   def_builtin ("__builtin_vsx_lxvw4x_v8hi", v8hi_ftype_long_pcvoid,
17511                VSX_BUILTIN_LXVW4X_V8HI);
17512   def_builtin ("__builtin_vsx_lxvw4x_v16qi", v16qi_ftype_long_pcvoid,
17513                VSX_BUILTIN_LXVW4X_V16QI);
17514   def_builtin ("__builtin_vsx_stxvd2x_v2df", void_ftype_v2df_long_pvoid,
17515                VSX_BUILTIN_STXVD2X_V2DF);
17516   def_builtin ("__builtin_vsx_stxvd2x_v2di", void_ftype_v2di_long_pvoid,
17517                VSX_BUILTIN_STXVD2X_V2DI);
17518   def_builtin ("__builtin_vsx_stxvw4x_v4sf", void_ftype_v4sf_long_pvoid,
17519                VSX_BUILTIN_STXVW4X_V4SF);
17520   def_builtin ("__builtin_vsx_stxvw4x_v4si", void_ftype_v4si_long_pvoid,
17521                VSX_BUILTIN_STXVW4X_V4SI);
17522   def_builtin ("__builtin_vsx_stxvw4x_v8hi", void_ftype_v8hi_long_pvoid,
17523                VSX_BUILTIN_STXVW4X_V8HI);
17524   def_builtin ("__builtin_vsx_stxvw4x_v16qi", void_ftype_v16qi_long_pvoid,
17525                VSX_BUILTIN_STXVW4X_V16QI);
17526
17527   def_builtin ("__builtin_vsx_ld_elemrev_v2df", v2df_ftype_long_pcvoid,
17528                VSX_BUILTIN_LD_ELEMREV_V2DF);
17529   def_builtin ("__builtin_vsx_ld_elemrev_v2di", v2di_ftype_long_pcvoid,
17530                VSX_BUILTIN_LD_ELEMREV_V2DI);
17531   def_builtin ("__builtin_vsx_ld_elemrev_v4sf", v4sf_ftype_long_pcvoid,
17532                VSX_BUILTIN_LD_ELEMREV_V4SF);
17533   def_builtin ("__builtin_vsx_ld_elemrev_v4si", v4si_ftype_long_pcvoid,
17534                VSX_BUILTIN_LD_ELEMREV_V4SI);
17535   def_builtin ("__builtin_vsx_ld_elemrev_v8hi", v8hi_ftype_long_pcvoid,
17536                VSX_BUILTIN_LD_ELEMREV_V8HI);
17537   def_builtin ("__builtin_vsx_ld_elemrev_v16qi", v16qi_ftype_long_pcvoid,
17538                VSX_BUILTIN_LD_ELEMREV_V16QI);
17539   def_builtin ("__builtin_vsx_st_elemrev_v2df", void_ftype_v2df_long_pvoid,
17540                VSX_BUILTIN_ST_ELEMREV_V2DF);
17541   def_builtin ("__builtin_vsx_st_elemrev_v2di", void_ftype_v2di_long_pvoid,
17542                VSX_BUILTIN_ST_ELEMREV_V2DI);
17543   def_builtin ("__builtin_vsx_st_elemrev_v4sf", void_ftype_v4sf_long_pvoid,
17544                VSX_BUILTIN_ST_ELEMREV_V4SF);
17545   def_builtin ("__builtin_vsx_st_elemrev_v4si", void_ftype_v4si_long_pvoid,
17546                VSX_BUILTIN_ST_ELEMREV_V4SI);
17547   def_builtin ("__builtin_vsx_st_elemrev_v8hi", void_ftype_v8hi_long_pvoid,
17548                VSX_BUILTIN_ST_ELEMREV_V8HI);
17549   def_builtin ("__builtin_vsx_st_elemrev_v16qi", void_ftype_v16qi_long_pvoid,
17550                VSX_BUILTIN_ST_ELEMREV_V16QI);
17551
17552   def_builtin ("__builtin_vec_vsx_ld", opaque_ftype_long_pcvoid,
17553                VSX_BUILTIN_VEC_LD);
17554   def_builtin ("__builtin_vec_vsx_st", void_ftype_opaque_long_pvoid,
17555                VSX_BUILTIN_VEC_ST);
17556   def_builtin ("__builtin_vec_xl", opaque_ftype_long_pcvoid,
17557                VSX_BUILTIN_VEC_XL);
17558   def_builtin ("__builtin_vec_xl_be", opaque_ftype_long_pcvoid,
17559                VSX_BUILTIN_VEC_XL_BE);
17560   def_builtin ("__builtin_vec_xst", void_ftype_opaque_long_pvoid,
17561                VSX_BUILTIN_VEC_XST);
17562   def_builtin ("__builtin_vec_xst_be", void_ftype_opaque_long_pvoid,
17563                VSX_BUILTIN_VEC_XST_BE);
17564
17565   def_builtin ("__builtin_vec_step", int_ftype_opaque, ALTIVEC_BUILTIN_VEC_STEP);
17566   def_builtin ("__builtin_vec_splats", opaque_ftype_opaque, ALTIVEC_BUILTIN_VEC_SPLATS);
17567   def_builtin ("__builtin_vec_promote", opaque_ftype_opaque, ALTIVEC_BUILTIN_VEC_PROMOTE);
17568
17569   def_builtin ("__builtin_vec_sld", opaque_ftype_opaque_opaque_int, ALTIVEC_BUILTIN_VEC_SLD);
17570   def_builtin ("__builtin_vec_splat", opaque_ftype_opaque_int, ALTIVEC_BUILTIN_VEC_SPLAT);
17571   def_builtin ("__builtin_vec_extract", opaque_ftype_opaque_int, ALTIVEC_BUILTIN_VEC_EXTRACT);
17572   def_builtin ("__builtin_vec_insert", opaque_ftype_opaque_opaque_int, ALTIVEC_BUILTIN_VEC_INSERT);
17573   def_builtin ("__builtin_vec_vspltw", opaque_ftype_opaque_int, ALTIVEC_BUILTIN_VEC_VSPLTW);
17574   def_builtin ("__builtin_vec_vsplth", opaque_ftype_opaque_int, ALTIVEC_BUILTIN_VEC_VSPLTH);
17575   def_builtin ("__builtin_vec_vspltb", opaque_ftype_opaque_int, ALTIVEC_BUILTIN_VEC_VSPLTB);
17576   def_builtin ("__builtin_vec_ctf", opaque_ftype_opaque_int, ALTIVEC_BUILTIN_VEC_CTF);
17577   def_builtin ("__builtin_vec_vcfsx", opaque_ftype_opaque_int, ALTIVEC_BUILTIN_VEC_VCFSX);
17578   def_builtin ("__builtin_vec_vcfux", opaque_ftype_opaque_int, ALTIVEC_BUILTIN_VEC_VCFUX);
17579   def_builtin ("__builtin_vec_cts", opaque_ftype_opaque_int, ALTIVEC_BUILTIN_VEC_CTS);
17580   def_builtin ("__builtin_vec_ctu", opaque_ftype_opaque_int, ALTIVEC_BUILTIN_VEC_CTU);
17581
17582   def_builtin ("__builtin_vec_adde", opaque_ftype_opaque_opaque_opaque,
17583                 ALTIVEC_BUILTIN_VEC_ADDE);
17584   def_builtin ("__builtin_vec_addec", opaque_ftype_opaque_opaque_opaque,
17585                 ALTIVEC_BUILTIN_VEC_ADDEC);
17586   def_builtin ("__builtin_vec_cmpne", opaque_ftype_opaque_opaque,
17587                 ALTIVEC_BUILTIN_VEC_CMPNE);
17588   def_builtin ("__builtin_vec_mul", opaque_ftype_opaque_opaque,
17589                 ALTIVEC_BUILTIN_VEC_MUL);
17590   def_builtin ("__builtin_vec_sube", opaque_ftype_opaque_opaque_opaque,
17591                 ALTIVEC_BUILTIN_VEC_SUBE);
17592   def_builtin ("__builtin_vec_subec", opaque_ftype_opaque_opaque_opaque,
17593                 ALTIVEC_BUILTIN_VEC_SUBEC);
17594
17595   /* Cell builtins.  */
17596   def_builtin ("__builtin_altivec_lvlx",  v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVLX);
17597   def_builtin ("__builtin_altivec_lvlxl", v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVLXL);
17598   def_builtin ("__builtin_altivec_lvrx",  v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVRX);
17599   def_builtin ("__builtin_altivec_lvrxl", v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVRXL);
17600
17601   def_builtin ("__builtin_vec_lvlx",  v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LVLX);
17602   def_builtin ("__builtin_vec_lvlxl", v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LVLXL);
17603   def_builtin ("__builtin_vec_lvrx",  v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LVRX);
17604   def_builtin ("__builtin_vec_lvrxl", v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LVRXL);
17605
17606   def_builtin ("__builtin_altivec_stvlx",  void_ftype_v16qi_long_pvoid, ALTIVEC_BUILTIN_STVLX);
17607   def_builtin ("__builtin_altivec_stvlxl", void_ftype_v16qi_long_pvoid, ALTIVEC_BUILTIN_STVLXL);
17608   def_builtin ("__builtin_altivec_stvrx",  void_ftype_v16qi_long_pvoid, ALTIVEC_BUILTIN_STVRX);
17609   def_builtin ("__builtin_altivec_stvrxl", void_ftype_v16qi_long_pvoid, ALTIVEC_BUILTIN_STVRXL);
17610
17611   def_builtin ("__builtin_vec_stvlx",  void_ftype_v16qi_long_pvoid, ALTIVEC_BUILTIN_VEC_STVLX);
17612   def_builtin ("__builtin_vec_stvlxl", void_ftype_v16qi_long_pvoid, ALTIVEC_BUILTIN_VEC_STVLXL);
17613   def_builtin ("__builtin_vec_stvrx",  void_ftype_v16qi_long_pvoid, ALTIVEC_BUILTIN_VEC_STVRX);
17614   def_builtin ("__builtin_vec_stvrxl", void_ftype_v16qi_long_pvoid, ALTIVEC_BUILTIN_VEC_STVRXL);
17615
17616   if (TARGET_P9_VECTOR)
17617     {
17618       def_builtin ("__builtin_altivec_stxvl", void_ftype_v16qi_pvoid_long,
17619                    P9V_BUILTIN_STXVL);
17620       def_builtin ("__builtin_xst_len_r", void_ftype_v16qi_pvoid_long,
17621                    P9V_BUILTIN_XST_LEN_R);
17622     }
17623
17624   /* Add the DST variants.  */
17625   d = bdesc_dst;
17626   for (i = 0; i < ARRAY_SIZE (bdesc_dst); i++, d++)
17627     {
17628       HOST_WIDE_INT mask = d->mask;
17629
17630       /* It is expected that these dst built-in functions may have
17631          d->icode equal to CODE_FOR_nothing.  */
17632       if ((mask & builtin_mask) != mask)
17633         {
17634           if (TARGET_DEBUG_BUILTIN)
17635             fprintf (stderr, "altivec_init_builtins, skip dst %s\n",
17636                      d->name);
17637           continue;
17638         }
17639       def_builtin (d->name, void_ftype_pcvoid_int_int, d->code);
17640     }
17641
17642   /* Initialize the predicates.  */
17643   d = bdesc_altivec_preds;
17644   for (i = 0; i < ARRAY_SIZE (bdesc_altivec_preds); i++, d++)
17645     {
17646       machine_mode mode1;
17647       tree type;
17648       HOST_WIDE_INT mask = d->mask;
17649
17650       if ((mask & builtin_mask) != mask)
17651         {
17652           if (TARGET_DEBUG_BUILTIN)
17653             fprintf (stderr, "altivec_init_builtins, skip predicate %s\n",
17654                      d->name);
17655           continue;
17656         }
17657
17658       if (rs6000_overloaded_builtin_p (d->code))
17659         mode1 = VOIDmode;
17660       else
17661         {
17662           /* Cannot define builtin if the instruction is disabled.  */
17663           gcc_assert (d->icode != CODE_FOR_nothing);
17664           mode1 = insn_data[d->icode].operand[1].mode;
17665         }
17666
17667       switch (mode1)
17668         {
17669         case E_VOIDmode:
17670           type = int_ftype_int_opaque_opaque;
17671           break;
17672         case E_V2DImode:
17673           type = int_ftype_int_v2di_v2di;
17674           break;
17675         case E_V4SImode:
17676           type = int_ftype_int_v4si_v4si;
17677           break;
17678         case E_V8HImode:
17679           type = int_ftype_int_v8hi_v8hi;
17680           break;
17681         case E_V16QImode:
17682           type = int_ftype_int_v16qi_v16qi;
17683           break;
17684         case E_V4SFmode:
17685           type = int_ftype_int_v4sf_v4sf;
17686           break;
17687         case E_V2DFmode:
17688           type = int_ftype_int_v2df_v2df;
17689           break;
17690         default:
17691           gcc_unreachable ();
17692         }
17693
17694       def_builtin (d->name, type, d->code);
17695     }
17696
17697   /* Initialize the abs* operators.  */
17698   d = bdesc_abs;
17699   for (i = 0; i < ARRAY_SIZE (bdesc_abs); i++, d++)
17700     {
17701       machine_mode mode0;
17702       tree type;
17703       HOST_WIDE_INT mask = d->mask;
17704
17705       if ((mask & builtin_mask) != mask)
17706         {
17707           if (TARGET_DEBUG_BUILTIN)
17708             fprintf (stderr, "altivec_init_builtins, skip abs %s\n",
17709                      d->name);
17710           continue;
17711         }
17712
17713       /* Cannot define builtin if the instruction is disabled.  */
17714       gcc_assert (d->icode != CODE_FOR_nothing);
17715       mode0 = insn_data[d->icode].operand[0].mode;
17716
17717       switch (mode0)
17718         {
17719         case E_V2DImode:
17720           type = v2di_ftype_v2di;
17721           break;
17722         case E_V4SImode:
17723           type = v4si_ftype_v4si;
17724           break;
17725         case E_V8HImode:
17726           type = v8hi_ftype_v8hi;
17727           break;
17728         case E_V16QImode:
17729           type = v16qi_ftype_v16qi;
17730           break;
17731         case E_V4SFmode:
17732           type = v4sf_ftype_v4sf;
17733           break;
17734         case E_V2DFmode:
17735           type = v2df_ftype_v2df;
17736           break;
17737         default:
17738           gcc_unreachable ();
17739         }
17740
17741       def_builtin (d->name, type, d->code);
17742     }
17743
17744   /* Initialize target builtin that implements
17745      targetm.vectorize.builtin_mask_for_load.  */
17746
17747   decl = add_builtin_function ("__builtin_altivec_mask_for_load",
17748                                v16qi_ftype_long_pcvoid,
17749                                ALTIVEC_BUILTIN_MASK_FOR_LOAD,
17750                                BUILT_IN_MD, NULL, NULL_TREE);
17751   TREE_READONLY (decl) = 1;
17752   /* Record the decl. Will be used by rs6000_builtin_mask_for_load.  */
17753   altivec_builtin_mask_for_load = decl;
17754
17755   /* Access to the vec_init patterns.  */
17756   ftype = build_function_type_list (V4SI_type_node, integer_type_node,
17757                                     integer_type_node, integer_type_node,
17758                                     integer_type_node, NULL_TREE);
17759   def_builtin ("__builtin_vec_init_v4si", ftype, ALTIVEC_BUILTIN_VEC_INIT_V4SI);
17760
17761   ftype = build_function_type_list (V8HI_type_node, short_integer_type_node,
17762                                     short_integer_type_node,
17763                                     short_integer_type_node,
17764                                     short_integer_type_node,
17765                                     short_integer_type_node,
17766                                     short_integer_type_node,
17767                                     short_integer_type_node,
17768                                     short_integer_type_node, NULL_TREE);
17769   def_builtin ("__builtin_vec_init_v8hi", ftype, ALTIVEC_BUILTIN_VEC_INIT_V8HI);
17770
17771   ftype = build_function_type_list (V16QI_type_node, char_type_node,
17772                                     char_type_node, char_type_node,
17773                                     char_type_node, char_type_node,
17774                                     char_type_node, char_type_node,
17775                                     char_type_node, char_type_node,
17776                                     char_type_node, char_type_node,
17777                                     char_type_node, char_type_node,
17778                                     char_type_node, char_type_node,
17779                                     char_type_node, NULL_TREE);
17780   def_builtin ("__builtin_vec_init_v16qi", ftype,
17781                ALTIVEC_BUILTIN_VEC_INIT_V16QI);
17782
17783   ftype = build_function_type_list (V4SF_type_node, float_type_node,
17784                                     float_type_node, float_type_node,
17785                                     float_type_node, NULL_TREE);
17786   def_builtin ("__builtin_vec_init_v4sf", ftype, ALTIVEC_BUILTIN_VEC_INIT_V4SF);
17787
17788   /* VSX builtins.  */
17789   ftype = build_function_type_list (V2DF_type_node, double_type_node,
17790                                     double_type_node, NULL_TREE);
17791   def_builtin ("__builtin_vec_init_v2df", ftype, VSX_BUILTIN_VEC_INIT_V2DF);
17792
17793   ftype = build_function_type_list (V2DI_type_node, intDI_type_node,
17794                                     intDI_type_node, NULL_TREE);
17795   def_builtin ("__builtin_vec_init_v2di", ftype, VSX_BUILTIN_VEC_INIT_V2DI);
17796
17797   /* Access to the vec_set patterns.  */
17798   ftype = build_function_type_list (V4SI_type_node, V4SI_type_node,
17799                                     intSI_type_node,
17800                                     integer_type_node, NULL_TREE);
17801   def_builtin ("__builtin_vec_set_v4si", ftype, ALTIVEC_BUILTIN_VEC_SET_V4SI);
17802
17803   ftype = build_function_type_list (V8HI_type_node, V8HI_type_node,
17804                                     intHI_type_node,
17805                                     integer_type_node, NULL_TREE);
17806   def_builtin ("__builtin_vec_set_v8hi", ftype, ALTIVEC_BUILTIN_VEC_SET_V8HI);
17807
17808   ftype = build_function_type_list (V16QI_type_node, V16QI_type_node,
17809                                     intQI_type_node,
17810                                     integer_type_node, NULL_TREE);
17811   def_builtin ("__builtin_vec_set_v16qi", ftype, ALTIVEC_BUILTIN_VEC_SET_V16QI);
17812
17813   ftype = build_function_type_list (V4SF_type_node, V4SF_type_node,
17814                                     float_type_node,
17815                                     integer_type_node, NULL_TREE);
17816   def_builtin ("__builtin_vec_set_v4sf", ftype, ALTIVEC_BUILTIN_VEC_SET_V4SF);
17817
17818   ftype = build_function_type_list (V2DF_type_node, V2DF_type_node,
17819                                     double_type_node,
17820                                     integer_type_node, NULL_TREE);
17821   def_builtin ("__builtin_vec_set_v2df", ftype, VSX_BUILTIN_VEC_SET_V2DF);
17822
17823   ftype = build_function_type_list (V2DI_type_node, V2DI_type_node,
17824                                     intDI_type_node,
17825                                     integer_type_node, NULL_TREE);
17826   def_builtin ("__builtin_vec_set_v2di", ftype, VSX_BUILTIN_VEC_SET_V2DI);
17827
17828   /* Access to the vec_extract patterns.  */
17829   ftype = build_function_type_list (intSI_type_node, V4SI_type_node,
17830                                     integer_type_node, NULL_TREE);
17831   def_builtin ("__builtin_vec_ext_v4si", ftype, ALTIVEC_BUILTIN_VEC_EXT_V4SI);
17832
17833   ftype = build_function_type_list (intHI_type_node, V8HI_type_node,
17834                                     integer_type_node, NULL_TREE);
17835   def_builtin ("__builtin_vec_ext_v8hi", ftype, ALTIVEC_BUILTIN_VEC_EXT_V8HI);
17836
17837   ftype = build_function_type_list (intQI_type_node, V16QI_type_node,
17838                                     integer_type_node, NULL_TREE);
17839   def_builtin ("__builtin_vec_ext_v16qi", ftype, ALTIVEC_BUILTIN_VEC_EXT_V16QI);
17840
17841   ftype = build_function_type_list (float_type_node, V4SF_type_node,
17842                                     integer_type_node, NULL_TREE);
17843   def_builtin ("__builtin_vec_ext_v4sf", ftype, ALTIVEC_BUILTIN_VEC_EXT_V4SF);
17844
17845   ftype = build_function_type_list (double_type_node, V2DF_type_node,
17846                                     integer_type_node, NULL_TREE);
17847   def_builtin ("__builtin_vec_ext_v2df", ftype, VSX_BUILTIN_VEC_EXT_V2DF);
17848
17849   ftype = build_function_type_list (intDI_type_node, V2DI_type_node,
17850                                     integer_type_node, NULL_TREE);
17851   def_builtin ("__builtin_vec_ext_v2di", ftype, VSX_BUILTIN_VEC_EXT_V2DI);
17852
17853
17854   if (V1TI_type_node)
17855     {
17856       tree v1ti_ftype_long_pcvoid
17857         = build_function_type_list (V1TI_type_node,
17858                                     long_integer_type_node, pcvoid_type_node,
17859                                     NULL_TREE);
17860       tree void_ftype_v1ti_long_pvoid
17861         = build_function_type_list (void_type_node,
17862                                     V1TI_type_node, long_integer_type_node,
17863                                     pvoid_type_node, NULL_TREE);
17864       def_builtin ("__builtin_vsx_lxvd2x_v1ti", v1ti_ftype_long_pcvoid,
17865                    VSX_BUILTIN_LXVD2X_V1TI);
17866       def_builtin ("__builtin_vsx_stxvd2x_v1ti", void_ftype_v1ti_long_pvoid,
17867                    VSX_BUILTIN_STXVD2X_V1TI);
17868       ftype = build_function_type_list (V1TI_type_node, intTI_type_node,
17869                                         NULL_TREE, NULL_TREE);
17870       def_builtin ("__builtin_vec_init_v1ti", ftype, VSX_BUILTIN_VEC_INIT_V1TI);
17871       ftype = build_function_type_list (V1TI_type_node, V1TI_type_node,
17872                                         intTI_type_node,
17873                                         integer_type_node, NULL_TREE);
17874       def_builtin ("__builtin_vec_set_v1ti", ftype, VSX_BUILTIN_VEC_SET_V1TI);
17875       ftype = build_function_type_list (intTI_type_node, V1TI_type_node,
17876                                         integer_type_node, NULL_TREE);
17877       def_builtin ("__builtin_vec_ext_v1ti", ftype, VSX_BUILTIN_VEC_EXT_V1TI);
17878     }
17879
17880 }
17881
17882 static void
17883 htm_init_builtins (void)
17884 {
17885   HOST_WIDE_INT builtin_mask = rs6000_builtin_mask;
17886   const struct builtin_description *d;
17887   size_t i;
17888
17889   d = bdesc_htm;
17890   for (i = 0; i < ARRAY_SIZE (bdesc_htm); i++, d++)
17891     {
17892       tree op[MAX_HTM_OPERANDS], type;
17893       HOST_WIDE_INT mask = d->mask;
17894       unsigned attr = rs6000_builtin_info[d->code].attr;
17895       bool void_func = (attr & RS6000_BTC_VOID);
17896       int attr_args = (attr & RS6000_BTC_TYPE_MASK);
17897       int nopnds = 0;
17898       tree gpr_type_node;
17899       tree rettype;
17900       tree argtype;
17901
17902       /* It is expected that these htm built-in functions may have
17903          d->icode equal to CODE_FOR_nothing.  */
17904
17905       if (TARGET_32BIT && TARGET_POWERPC64)
17906         gpr_type_node = long_long_unsigned_type_node;
17907       else
17908         gpr_type_node = long_unsigned_type_node;
17909
17910       if (attr & RS6000_BTC_SPR)
17911         {
17912           rettype = gpr_type_node;
17913           argtype = gpr_type_node;
17914         }
17915       else if (d->code == HTM_BUILTIN_TABORTDC
17916                || d->code == HTM_BUILTIN_TABORTDCI)
17917         {
17918           rettype = unsigned_type_node;
17919           argtype = gpr_type_node;
17920         }
17921       else
17922         {
17923           rettype = unsigned_type_node;
17924           argtype = unsigned_type_node;
17925         }
17926
17927       if ((mask & builtin_mask) != mask)
17928         {
17929           if (TARGET_DEBUG_BUILTIN)
17930             fprintf (stderr, "htm_builtin, skip binary %s\n", d->name);
17931           continue;
17932         }
17933
17934       if (d->name == 0)
17935         {
17936           if (TARGET_DEBUG_BUILTIN)
17937             fprintf (stderr, "htm_builtin, bdesc_htm[%ld] no name\n",
17938                      (long unsigned) i);
17939           continue;
17940         }
17941
17942       op[nopnds++] = (void_func) ? void_type_node : rettype;
17943
17944       if (attr_args == RS6000_BTC_UNARY)
17945         op[nopnds++] = argtype;
17946       else if (attr_args == RS6000_BTC_BINARY)
17947         {
17948           op[nopnds++] = argtype;
17949           op[nopnds++] = argtype;
17950         }
17951       else if (attr_args == RS6000_BTC_TERNARY)
17952         {
17953           op[nopnds++] = argtype;
17954           op[nopnds++] = argtype;
17955           op[nopnds++] = argtype;
17956         }
17957
17958       switch (nopnds)
17959         {
17960         case 1:
17961           type = build_function_type_list (op[0], NULL_TREE);
17962           break;
17963         case 2:
17964           type = build_function_type_list (op[0], op[1], NULL_TREE);
17965           break;
17966         case 3:
17967           type = build_function_type_list (op[0], op[1], op[2], NULL_TREE);
17968           break;
17969         case 4:
17970           type = build_function_type_list (op[0], op[1], op[2], op[3],
17971                                            NULL_TREE);
17972           break;
17973         default:
17974           gcc_unreachable ();
17975         }
17976
17977       def_builtin (d->name, type, d->code);
17978     }
17979 }
17980
17981 /* Hash function for builtin functions with up to 3 arguments and a return
17982    type.  */
17983 hashval_t
17984 builtin_hasher::hash (builtin_hash_struct *bh)
17985 {
17986   unsigned ret = 0;
17987   int i;
17988
17989   for (i = 0; i < 4; i++)
17990     {
17991       ret = (ret * (unsigned)MAX_MACHINE_MODE) + ((unsigned)bh->mode[i]);
17992       ret = (ret * 2) + bh->uns_p[i];
17993     }
17994
17995   return ret;
17996 }
17997
17998 /* Compare builtin hash entries H1 and H2 for equivalence.  */
17999 bool
18000 builtin_hasher::equal (builtin_hash_struct *p1, builtin_hash_struct *p2)
18001 {
18002   return ((p1->mode[0] == p2->mode[0])
18003           && (p1->mode[1] == p2->mode[1])
18004           && (p1->mode[2] == p2->mode[2])
18005           && (p1->mode[3] == p2->mode[3])
18006           && (p1->uns_p[0] == p2->uns_p[0])
18007           && (p1->uns_p[1] == p2->uns_p[1])
18008           && (p1->uns_p[2] == p2->uns_p[2])
18009           && (p1->uns_p[3] == p2->uns_p[3]));
18010 }
18011
18012 /* Map types for builtin functions with an explicit return type and up to 3
18013    arguments.  Functions with fewer than 3 arguments use VOIDmode as the type
18014    of the argument.  */
18015 static tree
18016 builtin_function_type (machine_mode mode_ret, machine_mode mode_arg0,
18017                        machine_mode mode_arg1, machine_mode mode_arg2,
18018                        enum rs6000_builtins builtin, const char *name)
18019 {
18020   struct builtin_hash_struct h;
18021   struct builtin_hash_struct *h2;
18022   int num_args = 3;
18023   int i;
18024   tree ret_type = NULL_TREE;
18025   tree arg_type[3] = { NULL_TREE, NULL_TREE, NULL_TREE };
18026
18027   /* Create builtin_hash_table.  */
18028   if (builtin_hash_table == NULL)
18029     builtin_hash_table = hash_table<builtin_hasher>::create_ggc (1500);
18030
18031   h.type = NULL_TREE;
18032   h.mode[0] = mode_ret;
18033   h.mode[1] = mode_arg0;
18034   h.mode[2] = mode_arg1;
18035   h.mode[3] = mode_arg2;
18036   h.uns_p[0] = 0;
18037   h.uns_p[1] = 0;
18038   h.uns_p[2] = 0;
18039   h.uns_p[3] = 0;
18040
18041   /* If the builtin is a type that produces unsigned results or takes unsigned
18042      arguments, and it is returned as a decl for the vectorizer (such as
18043      widening multiplies, permute), make sure the arguments and return value
18044      are type correct.  */
18045   switch (builtin)
18046     {
18047     /* unsigned 1 argument functions.  */
18048     case CRYPTO_BUILTIN_VSBOX:
18049     case P8V_BUILTIN_VGBBD:
18050     case MISC_BUILTIN_CDTBCD:
18051     case MISC_BUILTIN_CBCDTD:
18052       h.uns_p[0] = 1;
18053       h.uns_p[1] = 1;
18054       break;
18055
18056     /* unsigned 2 argument functions.  */
18057     case ALTIVEC_BUILTIN_VMULEUB:
18058     case ALTIVEC_BUILTIN_VMULEUH:
18059     case ALTIVEC_BUILTIN_VMULEUW:
18060     case ALTIVEC_BUILTIN_VMULOUB:
18061     case ALTIVEC_BUILTIN_VMULOUH:
18062     case ALTIVEC_BUILTIN_VMULOUW:
18063     case CRYPTO_BUILTIN_VCIPHER:
18064     case CRYPTO_BUILTIN_VCIPHERLAST:
18065     case CRYPTO_BUILTIN_VNCIPHER:
18066     case CRYPTO_BUILTIN_VNCIPHERLAST:
18067     case CRYPTO_BUILTIN_VPMSUMB:
18068     case CRYPTO_BUILTIN_VPMSUMH:
18069     case CRYPTO_BUILTIN_VPMSUMW:
18070     case CRYPTO_BUILTIN_VPMSUMD:
18071     case CRYPTO_BUILTIN_VPMSUM:
18072     case MISC_BUILTIN_ADDG6S:
18073     case MISC_BUILTIN_DIVWEU:
18074     case MISC_BUILTIN_DIVWEUO:
18075     case MISC_BUILTIN_DIVDEU:
18076     case MISC_BUILTIN_DIVDEUO:
18077     case VSX_BUILTIN_UDIV_V2DI:
18078     case ALTIVEC_BUILTIN_VMAXUB:
18079     case ALTIVEC_BUILTIN_VMINUB:
18080     case ALTIVEC_BUILTIN_VMAXUH:
18081     case ALTIVEC_BUILTIN_VMINUH:
18082     case ALTIVEC_BUILTIN_VMAXUW:
18083     case ALTIVEC_BUILTIN_VMINUW:
18084     case P8V_BUILTIN_VMAXUD:
18085     case P8V_BUILTIN_VMINUD:
18086       h.uns_p[0] = 1;
18087       h.uns_p[1] = 1;
18088       h.uns_p[2] = 1;
18089       break;
18090
18091     /* unsigned 3 argument functions.  */
18092     case ALTIVEC_BUILTIN_VPERM_16QI_UNS:
18093     case ALTIVEC_BUILTIN_VPERM_8HI_UNS:
18094     case ALTIVEC_BUILTIN_VPERM_4SI_UNS:
18095     case ALTIVEC_BUILTIN_VPERM_2DI_UNS:
18096     case ALTIVEC_BUILTIN_VSEL_16QI_UNS:
18097     case ALTIVEC_BUILTIN_VSEL_8HI_UNS:
18098     case ALTIVEC_BUILTIN_VSEL_4SI_UNS:
18099     case ALTIVEC_BUILTIN_VSEL_2DI_UNS:
18100     case VSX_BUILTIN_VPERM_16QI_UNS:
18101     case VSX_BUILTIN_VPERM_8HI_UNS:
18102     case VSX_BUILTIN_VPERM_4SI_UNS:
18103     case VSX_BUILTIN_VPERM_2DI_UNS:
18104     case VSX_BUILTIN_XXSEL_16QI_UNS:
18105     case VSX_BUILTIN_XXSEL_8HI_UNS:
18106     case VSX_BUILTIN_XXSEL_4SI_UNS:
18107     case VSX_BUILTIN_XXSEL_2DI_UNS:
18108     case CRYPTO_BUILTIN_VPERMXOR:
18109     case CRYPTO_BUILTIN_VPERMXOR_V2DI:
18110     case CRYPTO_BUILTIN_VPERMXOR_V4SI:
18111     case CRYPTO_BUILTIN_VPERMXOR_V8HI:
18112     case CRYPTO_BUILTIN_VPERMXOR_V16QI:
18113     case CRYPTO_BUILTIN_VSHASIGMAW:
18114     case CRYPTO_BUILTIN_VSHASIGMAD:
18115     case CRYPTO_BUILTIN_VSHASIGMA:
18116       h.uns_p[0] = 1;
18117       h.uns_p[1] = 1;
18118       h.uns_p[2] = 1;
18119       h.uns_p[3] = 1;
18120       break;
18121
18122     /* signed permute functions with unsigned char mask.  */
18123     case ALTIVEC_BUILTIN_VPERM_16QI:
18124     case ALTIVEC_BUILTIN_VPERM_8HI:
18125     case ALTIVEC_BUILTIN_VPERM_4SI:
18126     case ALTIVEC_BUILTIN_VPERM_4SF:
18127     case ALTIVEC_BUILTIN_VPERM_2DI:
18128     case ALTIVEC_BUILTIN_VPERM_2DF:
18129     case VSX_BUILTIN_VPERM_16QI:
18130     case VSX_BUILTIN_VPERM_8HI:
18131     case VSX_BUILTIN_VPERM_4SI:
18132     case VSX_BUILTIN_VPERM_4SF:
18133     case VSX_BUILTIN_VPERM_2DI:
18134     case VSX_BUILTIN_VPERM_2DF:
18135       h.uns_p[3] = 1;
18136       break;
18137
18138     /* unsigned args, signed return.  */
18139     case VSX_BUILTIN_XVCVUXDSP:
18140     case VSX_BUILTIN_XVCVUXDDP_UNS:
18141     case ALTIVEC_BUILTIN_UNSFLOAT_V4SI_V4SF:
18142       h.uns_p[1] = 1;
18143       break;
18144
18145     /* signed args, unsigned return.  */
18146     case VSX_BUILTIN_XVCVDPUXDS_UNS:
18147     case ALTIVEC_BUILTIN_FIXUNS_V4SF_V4SI:
18148     case MISC_BUILTIN_UNPACK_TD:
18149     case MISC_BUILTIN_UNPACK_V1TI:
18150       h.uns_p[0] = 1;
18151       break;
18152
18153     /* unsigned arguments, bool return (compares).  */
18154     case ALTIVEC_BUILTIN_VCMPEQUB:
18155     case ALTIVEC_BUILTIN_VCMPEQUH:
18156     case ALTIVEC_BUILTIN_VCMPEQUW:
18157     case P8V_BUILTIN_VCMPEQUD:
18158     case VSX_BUILTIN_CMPGE_U16QI:
18159     case VSX_BUILTIN_CMPGE_U8HI:
18160     case VSX_BUILTIN_CMPGE_U4SI:
18161     case VSX_BUILTIN_CMPGE_U2DI:
18162     case ALTIVEC_BUILTIN_VCMPGTUB:
18163     case ALTIVEC_BUILTIN_VCMPGTUH:
18164     case ALTIVEC_BUILTIN_VCMPGTUW:
18165     case P8V_BUILTIN_VCMPGTUD:
18166       h.uns_p[1] = 1;
18167       h.uns_p[2] = 1;
18168       break;
18169
18170     /* unsigned arguments for 128-bit pack instructions.  */
18171     case MISC_BUILTIN_PACK_TD:
18172     case MISC_BUILTIN_PACK_V1TI:
18173       h.uns_p[1] = 1;
18174       h.uns_p[2] = 1;
18175       break;
18176
18177     /* unsigned second arguments (vector shift right).  */
18178     case ALTIVEC_BUILTIN_VSRB:
18179     case ALTIVEC_BUILTIN_VSRH:
18180     case ALTIVEC_BUILTIN_VSRW:
18181     case P8V_BUILTIN_VSRD:
18182       h.uns_p[2] = 1;
18183       break;
18184
18185     default:
18186       break;
18187     }
18188
18189   /* Figure out how many args are present.  */
18190   while (num_args > 0 && h.mode[num_args] == VOIDmode)
18191     num_args--;
18192
18193   ret_type = builtin_mode_to_type[h.mode[0]][h.uns_p[0]];
18194   if (!ret_type && h.uns_p[0])
18195     ret_type = builtin_mode_to_type[h.mode[0]][0];
18196
18197   if (!ret_type)
18198     fatal_error (input_location,
18199                  "internal error: builtin function %qs had an unexpected "
18200                  "return type %qs", name, GET_MODE_NAME (h.mode[0]));
18201
18202   for (i = 0; i < (int) ARRAY_SIZE (arg_type); i++)
18203     arg_type[i] = NULL_TREE;
18204
18205   for (i = 0; i < num_args; i++)
18206     {
18207       int m = (int) h.mode[i+1];
18208       int uns_p = h.uns_p[i+1];
18209
18210       arg_type[i] = builtin_mode_to_type[m][uns_p];
18211       if (!arg_type[i] && uns_p)
18212         arg_type[i] = builtin_mode_to_type[m][0];
18213
18214       if (!arg_type[i])
18215         fatal_error (input_location,
18216                      "internal error: builtin function %qs, argument %d "
18217                      "had unexpected argument type %qs", name, i,
18218                      GET_MODE_NAME (m));
18219     }
18220
18221   builtin_hash_struct **found = builtin_hash_table->find_slot (&h, INSERT);
18222   if (*found == NULL)
18223     {
18224       h2 = ggc_alloc<builtin_hash_struct> ();
18225       *h2 = h;
18226       *found = h2;
18227
18228       h2->type = build_function_type_list (ret_type, arg_type[0], arg_type[1],
18229                                            arg_type[2], NULL_TREE);
18230     }
18231
18232   return (*found)->type;
18233 }
18234
18235 static void
18236 rs6000_common_init_builtins (void)
18237 {
18238   const struct builtin_description *d;
18239   size_t i;
18240
18241   tree opaque_ftype_opaque = NULL_TREE;
18242   tree opaque_ftype_opaque_opaque = NULL_TREE;
18243   tree opaque_ftype_opaque_opaque_opaque = NULL_TREE;
18244   tree v2si_ftype = NULL_TREE;
18245   tree v2si_ftype_qi = NULL_TREE;
18246   tree v2si_ftype_v2si_qi = NULL_TREE;
18247   tree v2si_ftype_int_qi = NULL_TREE;
18248   HOST_WIDE_INT builtin_mask = rs6000_builtin_mask;
18249
18250   if (!TARGET_PAIRED_FLOAT)
18251     {
18252       builtin_mode_to_type[V2SImode][0] = opaque_V2SI_type_node;
18253       builtin_mode_to_type[V2SFmode][0] = opaque_V2SF_type_node;
18254     }
18255
18256   /* Paired builtins are only available if you build a compiler with the
18257      appropriate options, so only create those builtins with the appropriate
18258      compiler option.  Create Altivec and VSX builtins on machines with at
18259      least the general purpose extensions (970 and newer) to allow the use of
18260      the target attribute..  */
18261
18262   if (TARGET_EXTRA_BUILTINS)
18263     builtin_mask |= RS6000_BTM_COMMON;
18264
18265   /* Add the ternary operators.  */
18266   d = bdesc_3arg;
18267   for (i = 0; i < ARRAY_SIZE (bdesc_3arg); i++, d++)
18268     {
18269       tree type;
18270       HOST_WIDE_INT mask = d->mask;
18271
18272       if ((mask & builtin_mask) != mask)
18273         {
18274           if (TARGET_DEBUG_BUILTIN)
18275             fprintf (stderr, "rs6000_builtin, skip ternary %s\n", d->name);
18276           continue;
18277         }
18278
18279       if (rs6000_overloaded_builtin_p (d->code))
18280         {
18281           if (! (type = opaque_ftype_opaque_opaque_opaque))
18282             type = opaque_ftype_opaque_opaque_opaque
18283               = build_function_type_list (opaque_V4SI_type_node,
18284                                           opaque_V4SI_type_node,
18285                                           opaque_V4SI_type_node,
18286                                           opaque_V4SI_type_node,
18287                                           NULL_TREE);
18288         }
18289       else
18290         {
18291           enum insn_code icode = d->icode;
18292           if (d->name == 0)
18293             {
18294               if (TARGET_DEBUG_BUILTIN)
18295                 fprintf (stderr, "rs6000_builtin, bdesc_3arg[%ld] no name\n",
18296                          (long unsigned)i);
18297
18298               continue;
18299             }
18300
18301           if (icode == CODE_FOR_nothing)
18302             {
18303               if (TARGET_DEBUG_BUILTIN)
18304                 fprintf (stderr, "rs6000_builtin, skip ternary %s (no code)\n",
18305                          d->name);
18306
18307               continue;
18308             }
18309
18310           type = builtin_function_type (insn_data[icode].operand[0].mode,
18311                                         insn_data[icode].operand[1].mode,
18312                                         insn_data[icode].operand[2].mode,
18313                                         insn_data[icode].operand[3].mode,
18314                                         d->code, d->name);
18315         }
18316
18317       def_builtin (d->name, type, d->code);
18318     }
18319
18320   /* Add the binary operators.  */
18321   d = bdesc_2arg;
18322   for (i = 0; i < ARRAY_SIZE (bdesc_2arg); i++, d++)
18323     {
18324       machine_mode mode0, mode1, mode2;
18325       tree type;
18326       HOST_WIDE_INT mask = d->mask;
18327
18328       if ((mask & builtin_mask) != mask)
18329         {
18330           if (TARGET_DEBUG_BUILTIN)
18331             fprintf (stderr, "rs6000_builtin, skip binary %s\n", d->name);
18332           continue;
18333         }
18334
18335       if (rs6000_overloaded_builtin_p (d->code))
18336         {
18337           if (! (type = opaque_ftype_opaque_opaque))
18338             type = opaque_ftype_opaque_opaque
18339               = build_function_type_list (opaque_V4SI_type_node,
18340                                           opaque_V4SI_type_node,
18341                                           opaque_V4SI_type_node,
18342                                           NULL_TREE);
18343         }
18344       else
18345         {
18346           enum insn_code icode = d->icode;
18347           if (d->name == 0)
18348             {
18349               if (TARGET_DEBUG_BUILTIN)
18350                 fprintf (stderr, "rs6000_builtin, bdesc_2arg[%ld] no name\n",
18351                          (long unsigned)i);
18352
18353               continue;
18354             }
18355
18356           if (icode == CODE_FOR_nothing)
18357             {
18358               if (TARGET_DEBUG_BUILTIN)
18359                 fprintf (stderr, "rs6000_builtin, skip binary %s (no code)\n",
18360                          d->name);
18361
18362               continue;
18363             }
18364
18365           mode0 = insn_data[icode].operand[0].mode;
18366           mode1 = insn_data[icode].operand[1].mode;
18367           mode2 = insn_data[icode].operand[2].mode;
18368
18369           if (mode0 == V2SImode && mode1 == V2SImode && mode2 == QImode)
18370             {
18371               if (! (type = v2si_ftype_v2si_qi))
18372                 type = v2si_ftype_v2si_qi
18373                   = build_function_type_list (opaque_V2SI_type_node,
18374                                               opaque_V2SI_type_node,
18375                                               char_type_node,
18376                                               NULL_TREE);
18377             }
18378
18379           else if (mode0 == V2SImode && GET_MODE_CLASS (mode1) == MODE_INT
18380                    && mode2 == QImode)
18381             {
18382               if (! (type = v2si_ftype_int_qi))
18383                 type = v2si_ftype_int_qi
18384                   = build_function_type_list (opaque_V2SI_type_node,
18385                                               integer_type_node,
18386                                               char_type_node,
18387                                               NULL_TREE);
18388             }
18389
18390           else
18391             type = builtin_function_type (mode0, mode1, mode2, VOIDmode,
18392                                           d->code, d->name);
18393         }
18394
18395       def_builtin (d->name, type, d->code);
18396     }
18397
18398   /* Add the simple unary operators.  */
18399   d = bdesc_1arg;
18400   for (i = 0; i < ARRAY_SIZE (bdesc_1arg); i++, d++)
18401     {
18402       machine_mode mode0, mode1;
18403       tree type;
18404       HOST_WIDE_INT mask = d->mask;
18405
18406       if ((mask & builtin_mask) != mask)
18407         {
18408           if (TARGET_DEBUG_BUILTIN)
18409             fprintf (stderr, "rs6000_builtin, skip unary %s\n", d->name);
18410           continue;
18411         }
18412
18413       if (rs6000_overloaded_builtin_p (d->code))
18414         {
18415           if (! (type = opaque_ftype_opaque))
18416             type = opaque_ftype_opaque
18417               = build_function_type_list (opaque_V4SI_type_node,
18418                                           opaque_V4SI_type_node,
18419                                           NULL_TREE);
18420         }
18421       else
18422         {
18423           enum insn_code icode = d->icode;
18424           if (d->name == 0)
18425             {
18426               if (TARGET_DEBUG_BUILTIN)
18427                 fprintf (stderr, "rs6000_builtin, bdesc_1arg[%ld] no name\n",
18428                          (long unsigned)i);
18429
18430               continue;
18431             }
18432
18433           if (icode == CODE_FOR_nothing)
18434             {
18435               if (TARGET_DEBUG_BUILTIN)
18436                 fprintf (stderr, "rs6000_builtin, skip unary %s (no code)\n",
18437                          d->name);
18438
18439               continue;
18440             }
18441
18442           mode0 = insn_data[icode].operand[0].mode;
18443           mode1 = insn_data[icode].operand[1].mode;
18444
18445           if (mode0 == V2SImode && mode1 == QImode)
18446             {
18447               if (! (type = v2si_ftype_qi))
18448                 type = v2si_ftype_qi
18449                   = build_function_type_list (opaque_V2SI_type_node,
18450                                               char_type_node,
18451                                               NULL_TREE);
18452             }
18453
18454           else
18455             type = builtin_function_type (mode0, mode1, VOIDmode, VOIDmode,
18456                                           d->code, d->name);
18457         }
18458
18459       def_builtin (d->name, type, d->code);
18460     }
18461
18462   /* Add the simple no-argument operators.  */
18463   d = bdesc_0arg;
18464   for (i = 0; i < ARRAY_SIZE (bdesc_0arg); i++, d++)
18465     {
18466       machine_mode mode0;
18467       tree type;
18468       HOST_WIDE_INT mask = d->mask;
18469
18470       if ((mask & builtin_mask) != mask)
18471         {
18472           if (TARGET_DEBUG_BUILTIN)
18473             fprintf (stderr, "rs6000_builtin, skip no-argument %s\n", d->name);
18474           continue;
18475         }
18476       if (rs6000_overloaded_builtin_p (d->code))
18477         {
18478           if (!opaque_ftype_opaque)
18479             opaque_ftype_opaque
18480               = build_function_type_list (opaque_V4SI_type_node, NULL_TREE);
18481           type = opaque_ftype_opaque;
18482         }
18483       else
18484         {
18485           enum insn_code icode = d->icode;
18486           if (d->name == 0)
18487             {
18488               if (TARGET_DEBUG_BUILTIN)
18489                 fprintf (stderr, "rs6000_builtin, bdesc_0arg[%lu] no name\n",
18490                          (long unsigned) i);
18491               continue;
18492             }
18493           if (icode == CODE_FOR_nothing)
18494             {
18495               if (TARGET_DEBUG_BUILTIN)
18496                 fprintf (stderr,
18497                          "rs6000_builtin, skip no-argument %s (no code)\n",
18498                          d->name);
18499               continue;
18500             }
18501           mode0 = insn_data[icode].operand[0].mode;
18502           if (mode0 == V2SImode)
18503             {
18504               /* code for paired single */
18505               if (! (type = v2si_ftype))
18506                 {
18507                   v2si_ftype
18508                     = build_function_type_list (opaque_V2SI_type_node, 
18509                                                 NULL_TREE);
18510                   type = v2si_ftype;
18511                 }
18512             }
18513           else
18514             type = builtin_function_type (mode0, VOIDmode, VOIDmode, VOIDmode,
18515                                           d->code, d->name);
18516         }
18517       def_builtin (d->name, type, d->code);
18518     }
18519 }
18520
18521 /* Set up AIX/Darwin/64-bit Linux quad floating point routines.  */
18522 static void
18523 init_float128_ibm (machine_mode mode)
18524 {
18525   if (!TARGET_XL_COMPAT)
18526     {
18527       set_optab_libfunc (add_optab, mode, "__gcc_qadd");
18528       set_optab_libfunc (sub_optab, mode, "__gcc_qsub");
18529       set_optab_libfunc (smul_optab, mode, "__gcc_qmul");
18530       set_optab_libfunc (sdiv_optab, mode, "__gcc_qdiv");
18531
18532       if (!TARGET_HARD_FLOAT)
18533         {
18534           set_optab_libfunc (neg_optab, mode, "__gcc_qneg");
18535           set_optab_libfunc (eq_optab, mode, "__gcc_qeq");
18536           set_optab_libfunc (ne_optab, mode, "__gcc_qne");
18537           set_optab_libfunc (gt_optab, mode, "__gcc_qgt");
18538           set_optab_libfunc (ge_optab, mode, "__gcc_qge");
18539           set_optab_libfunc (lt_optab, mode, "__gcc_qlt");
18540           set_optab_libfunc (le_optab, mode, "__gcc_qle");
18541           set_optab_libfunc (unord_optab, mode, "__gcc_qunord");
18542
18543           set_conv_libfunc (sext_optab, mode, SFmode, "__gcc_stoq");
18544           set_conv_libfunc (sext_optab, mode, DFmode, "__gcc_dtoq");
18545           set_conv_libfunc (trunc_optab, SFmode, mode, "__gcc_qtos");
18546           set_conv_libfunc (trunc_optab, DFmode, mode, "__gcc_qtod");
18547           set_conv_libfunc (sfix_optab, SImode, mode, "__gcc_qtoi");
18548           set_conv_libfunc (ufix_optab, SImode, mode, "__gcc_qtou");
18549           set_conv_libfunc (sfloat_optab, mode, SImode, "__gcc_itoq");
18550           set_conv_libfunc (ufloat_optab, mode, SImode, "__gcc_utoq");
18551         }
18552     }
18553   else
18554     {
18555       set_optab_libfunc (add_optab, mode, "_xlqadd");
18556       set_optab_libfunc (sub_optab, mode, "_xlqsub");
18557       set_optab_libfunc (smul_optab, mode, "_xlqmul");
18558       set_optab_libfunc (sdiv_optab, mode, "_xlqdiv");
18559     }
18560
18561   /* Add various conversions for IFmode to use the traditional TFmode
18562      names.  */
18563   if (mode == IFmode)
18564     {
18565       set_conv_libfunc (sext_optab, mode, SDmode, "__dpd_extendsdtf2");
18566       set_conv_libfunc (sext_optab, mode, DDmode, "__dpd_extendddtf2");
18567       set_conv_libfunc (trunc_optab, mode, TDmode, "__dpd_trunctftd2");
18568       set_conv_libfunc (trunc_optab, SDmode, mode, "__dpd_trunctfsd2");
18569       set_conv_libfunc (trunc_optab, DDmode, mode, "__dpd_trunctfdd2");
18570       set_conv_libfunc (sext_optab, TDmode, mode, "__dpd_extendtdtf2");
18571
18572       if (TARGET_POWERPC64)
18573         {
18574           set_conv_libfunc (sfix_optab, TImode, mode, "__fixtfti");
18575           set_conv_libfunc (ufix_optab, TImode, mode, "__fixunstfti");
18576           set_conv_libfunc (sfloat_optab, mode, TImode, "__floattitf");
18577           set_conv_libfunc (ufloat_optab, mode, TImode, "__floatuntitf");
18578         }
18579     }
18580 }
18581
18582 /* Set up IEEE 128-bit floating point routines.  Use different names if the
18583    arguments can be passed in a vector register.  The historical PowerPC
18584    implementation of IEEE 128-bit floating point used _q_<op> for the names, so
18585    continue to use that if we aren't using vector registers to pass IEEE
18586    128-bit floating point.  */
18587
18588 static void
18589 init_float128_ieee (machine_mode mode)
18590 {
18591   if (FLOAT128_VECTOR_P (mode))
18592     {
18593       set_optab_libfunc (add_optab, mode, "__addkf3");
18594       set_optab_libfunc (sub_optab, mode, "__subkf3");
18595       set_optab_libfunc (neg_optab, mode, "__negkf2");
18596       set_optab_libfunc (smul_optab, mode, "__mulkf3");
18597       set_optab_libfunc (sdiv_optab, mode, "__divkf3");
18598       set_optab_libfunc (sqrt_optab, mode, "__sqrtkf2");
18599       set_optab_libfunc (abs_optab, mode, "__abstkf2");
18600
18601       set_optab_libfunc (eq_optab, mode, "__eqkf2");
18602       set_optab_libfunc (ne_optab, mode, "__nekf2");
18603       set_optab_libfunc (gt_optab, mode, "__gtkf2");
18604       set_optab_libfunc (ge_optab, mode, "__gekf2");
18605       set_optab_libfunc (lt_optab, mode, "__ltkf2");
18606       set_optab_libfunc (le_optab, mode, "__lekf2");
18607       set_optab_libfunc (unord_optab, mode, "__unordkf2");
18608
18609       set_conv_libfunc (sext_optab, mode, SFmode, "__extendsfkf2");
18610       set_conv_libfunc (sext_optab, mode, DFmode, "__extenddfkf2");
18611       set_conv_libfunc (trunc_optab, SFmode, mode, "__trunckfsf2");
18612       set_conv_libfunc (trunc_optab, DFmode, mode, "__trunckfdf2");
18613
18614       set_conv_libfunc (sext_optab, mode, IFmode, "__extendtfkf2");
18615       if (mode != TFmode && FLOAT128_IBM_P (TFmode))
18616         set_conv_libfunc (sext_optab, mode, TFmode, "__extendtfkf2");
18617
18618       set_conv_libfunc (trunc_optab, IFmode, mode, "__trunckftf2");
18619       if (mode != TFmode && FLOAT128_IBM_P (TFmode))
18620         set_conv_libfunc (trunc_optab, TFmode, mode, "__trunckftf2");
18621
18622       set_conv_libfunc (sext_optab, mode, SDmode, "__dpd_extendsdkf2");
18623       set_conv_libfunc (sext_optab, mode, DDmode, "__dpd_extendddkf2");
18624       set_conv_libfunc (trunc_optab, mode, TDmode, "__dpd_trunckftd2");
18625       set_conv_libfunc (trunc_optab, SDmode, mode, "__dpd_trunckfsd2");
18626       set_conv_libfunc (trunc_optab, DDmode, mode, "__dpd_trunckfdd2");
18627       set_conv_libfunc (sext_optab, TDmode, mode, "__dpd_extendtdkf2");
18628
18629       set_conv_libfunc (sfix_optab, SImode, mode, "__fixkfsi");
18630       set_conv_libfunc (ufix_optab, SImode, mode, "__fixunskfsi");
18631       set_conv_libfunc (sfix_optab, DImode, mode, "__fixkfdi");
18632       set_conv_libfunc (ufix_optab, DImode, mode, "__fixunskfdi");
18633
18634       set_conv_libfunc (sfloat_optab, mode, SImode, "__floatsikf");
18635       set_conv_libfunc (ufloat_optab, mode, SImode, "__floatunsikf");
18636       set_conv_libfunc (sfloat_optab, mode, DImode, "__floatdikf");
18637       set_conv_libfunc (ufloat_optab, mode, DImode, "__floatundikf");
18638
18639       if (TARGET_POWERPC64)
18640         {
18641           set_conv_libfunc (sfix_optab, TImode, mode, "__fixkfti");
18642           set_conv_libfunc (ufix_optab, TImode, mode, "__fixunskfti");
18643           set_conv_libfunc (sfloat_optab, mode, TImode, "__floattikf");
18644           set_conv_libfunc (ufloat_optab, mode, TImode, "__floatuntikf");
18645         }
18646     }
18647
18648   else
18649     {
18650       set_optab_libfunc (add_optab, mode, "_q_add");
18651       set_optab_libfunc (sub_optab, mode, "_q_sub");
18652       set_optab_libfunc (neg_optab, mode, "_q_neg");
18653       set_optab_libfunc (smul_optab, mode, "_q_mul");
18654       set_optab_libfunc (sdiv_optab, mode, "_q_div");
18655       if (TARGET_PPC_GPOPT)
18656         set_optab_libfunc (sqrt_optab, mode, "_q_sqrt");
18657
18658       set_optab_libfunc (eq_optab, mode, "_q_feq");
18659       set_optab_libfunc (ne_optab, mode, "_q_fne");
18660       set_optab_libfunc (gt_optab, mode, "_q_fgt");
18661       set_optab_libfunc (ge_optab, mode, "_q_fge");
18662       set_optab_libfunc (lt_optab, mode, "_q_flt");
18663       set_optab_libfunc (le_optab, mode, "_q_fle");
18664
18665       set_conv_libfunc (sext_optab, mode, SFmode, "_q_stoq");
18666       set_conv_libfunc (sext_optab, mode, DFmode, "_q_dtoq");
18667       set_conv_libfunc (trunc_optab, SFmode, mode, "_q_qtos");
18668       set_conv_libfunc (trunc_optab, DFmode, mode, "_q_qtod");
18669       set_conv_libfunc (sfix_optab, SImode, mode, "_q_qtoi");
18670       set_conv_libfunc (ufix_optab, SImode, mode, "_q_qtou");
18671       set_conv_libfunc (sfloat_optab, mode, SImode, "_q_itoq");
18672       set_conv_libfunc (ufloat_optab, mode, SImode, "_q_utoq");
18673     }
18674 }
18675
18676 static void
18677 rs6000_init_libfuncs (void)
18678 {
18679   /* __float128 support.  */
18680   if (TARGET_FLOAT128_TYPE)
18681     {
18682       init_float128_ibm (IFmode);
18683       init_float128_ieee (KFmode);
18684     }
18685
18686   /* AIX/Darwin/64-bit Linux quad floating point routines.  */
18687   if (TARGET_LONG_DOUBLE_128)
18688     {
18689       if (!TARGET_IEEEQUAD)
18690         init_float128_ibm (TFmode);
18691
18692       /* IEEE 128-bit including 32-bit SVR4 quad floating point routines.  */
18693       else
18694         init_float128_ieee (TFmode);
18695     }
18696 }
18697
18698 /* Emit a potentially record-form instruction, setting DST from SRC.
18699    If DOT is 0, that is all; otherwise, set CCREG to the result of the
18700    signed comparison of DST with zero.  If DOT is 1, the generated RTL
18701    doesn't care about the DST result; if DOT is 2, it does.  If CCREG
18702    is CR0 do a single dot insn (as a PARALLEL); otherwise, do a SET and
18703    a separate COMPARE.  */
18704
18705 void
18706 rs6000_emit_dot_insn (rtx dst, rtx src, int dot, rtx ccreg)
18707 {
18708   if (dot == 0)
18709     {
18710       emit_move_insn (dst, src);
18711       return;
18712     }
18713
18714   if (cc_reg_not_cr0_operand (ccreg, CCmode))
18715     {
18716       emit_move_insn (dst, src);
18717       emit_move_insn (ccreg, gen_rtx_COMPARE (CCmode, dst, const0_rtx));
18718       return;
18719     }
18720
18721   rtx ccset = gen_rtx_SET (ccreg, gen_rtx_COMPARE (CCmode, src, const0_rtx));
18722   if (dot == 1)
18723     {
18724       rtx clobber = gen_rtx_CLOBBER (VOIDmode, dst);
18725       emit_insn (gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, ccset, clobber)));
18726     }
18727   else
18728     {
18729       rtx set = gen_rtx_SET (dst, src);
18730       emit_insn (gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, ccset, set)));
18731     }
18732 }
18733
18734 \f
18735 /* A validation routine: say whether CODE, a condition code, and MODE
18736    match.  The other alternatives either don't make sense or should
18737    never be generated.  */
18738
18739 void
18740 validate_condition_mode (enum rtx_code code, machine_mode mode)
18741 {
18742   gcc_assert ((GET_RTX_CLASS (code) == RTX_COMPARE
18743                || GET_RTX_CLASS (code) == RTX_COMM_COMPARE)
18744               && GET_MODE_CLASS (mode) == MODE_CC);
18745
18746   /* These don't make sense.  */
18747   gcc_assert ((code != GT && code != LT && code != GE && code != LE)
18748               || mode != CCUNSmode);
18749
18750   gcc_assert ((code != GTU && code != LTU && code != GEU && code != LEU)
18751               || mode == CCUNSmode);
18752
18753   gcc_assert (mode == CCFPmode
18754               || (code != ORDERED && code != UNORDERED
18755                   && code != UNEQ && code != LTGT
18756                   && code != UNGT && code != UNLT
18757                   && code != UNGE && code != UNLE));
18758
18759   /* These should never be generated except for
18760      flag_finite_math_only.  */
18761   gcc_assert (mode != CCFPmode
18762               || flag_finite_math_only
18763               || (code != LE && code != GE
18764                   && code != UNEQ && code != LTGT
18765                   && code != UNGT && code != UNLT));
18766
18767   /* These are invalid; the information is not there.  */
18768   gcc_assert (mode != CCEQmode || code == EQ || code == NE);
18769 }
18770
18771 \f
18772 /* Return whether MASK (a CONST_INT) is a valid mask for any rlwinm,
18773    rldicl, rldicr, or rldic instruction in mode MODE.  If so, if E is
18774    not zero, store there the bit offset (counted from the right) where
18775    the single stretch of 1 bits begins; and similarly for B, the bit
18776    offset where it ends.  */
18777
18778 bool
18779 rs6000_is_valid_mask (rtx mask, int *b, int *e, machine_mode mode)
18780 {
18781   unsigned HOST_WIDE_INT val = INTVAL (mask);
18782   unsigned HOST_WIDE_INT bit;
18783   int nb, ne;
18784   int n = GET_MODE_PRECISION (mode);
18785
18786   if (mode != DImode && mode != SImode)
18787     return false;
18788
18789   if (INTVAL (mask) >= 0)
18790     {
18791       bit = val & -val;
18792       ne = exact_log2 (bit);
18793       nb = exact_log2 (val + bit);
18794     }
18795   else if (val + 1 == 0)
18796     {
18797       nb = n;
18798       ne = 0;
18799     }
18800   else if (val & 1)
18801     {
18802       val = ~val;
18803       bit = val & -val;
18804       nb = exact_log2 (bit);
18805       ne = exact_log2 (val + bit);
18806     }
18807   else
18808     {
18809       bit = val & -val;
18810       ne = exact_log2 (bit);
18811       if (val + bit == 0)
18812         nb = n;
18813       else
18814         nb = 0;
18815     }
18816
18817   nb--;
18818
18819   if (nb < 0 || ne < 0 || nb >= n || ne >= n)
18820     return false;
18821
18822   if (b)
18823     *b = nb;
18824   if (e)
18825     *e = ne;
18826
18827   return true;
18828 }
18829
18830 /* Return whether MASK (a CONST_INT) is a valid mask for any rlwinm, rldicl,
18831    or rldicr instruction, to implement an AND with it in mode MODE.  */
18832
18833 bool
18834 rs6000_is_valid_and_mask (rtx mask, machine_mode mode)
18835 {
18836   int nb, ne;
18837
18838   if (!rs6000_is_valid_mask (mask, &nb, &ne, mode))
18839     return false;
18840
18841   /* For DImode, we need a rldicl, rldicr, or a rlwinm with mask that
18842      does not wrap.  */
18843   if (mode == DImode)
18844     return (ne == 0 || nb == 63 || (nb < 32 && ne <= nb));
18845
18846   /* For SImode, rlwinm can do everything.  */
18847   if (mode == SImode)
18848     return (nb < 32 && ne < 32);
18849
18850   return false;
18851 }
18852
18853 /* Return the instruction template for an AND with mask in mode MODE, with
18854    operands OPERANDS.  If DOT is true, make it a record-form instruction.  */
18855
18856 const char *
18857 rs6000_insn_for_and_mask (machine_mode mode, rtx *operands, bool dot)
18858 {
18859   int nb, ne;
18860
18861   if (!rs6000_is_valid_mask (operands[2], &nb, &ne, mode))
18862     gcc_unreachable ();
18863
18864   if (mode == DImode && ne == 0)
18865     {
18866       operands[3] = GEN_INT (63 - nb);
18867       if (dot)
18868         return "rldicl. %0,%1,0,%3";
18869       return "rldicl %0,%1,0,%3";
18870     }
18871
18872   if (mode == DImode && nb == 63)
18873     {
18874       operands[3] = GEN_INT (63 - ne);
18875       if (dot)
18876         return "rldicr. %0,%1,0,%3";
18877       return "rldicr %0,%1,0,%3";
18878     }
18879
18880   if (nb < 32 && ne < 32)
18881     {
18882       operands[3] = GEN_INT (31 - nb);
18883       operands[4] = GEN_INT (31 - ne);
18884       if (dot)
18885         return "rlwinm. %0,%1,0,%3,%4";
18886       return "rlwinm %0,%1,0,%3,%4";
18887     }
18888
18889   gcc_unreachable ();
18890 }
18891
18892 /* Return whether MASK (a CONST_INT) is a valid mask for any rlw[i]nm,
18893    rld[i]cl, rld[i]cr, or rld[i]c instruction, to implement an AND with
18894    shift SHIFT (a ROTATE, ASHIFT, or LSHIFTRT) in mode MODE.  */
18895
18896 bool
18897 rs6000_is_valid_shift_mask (rtx mask, rtx shift, machine_mode mode)
18898 {
18899   int nb, ne;
18900
18901   if (!rs6000_is_valid_mask (mask, &nb, &ne, mode))
18902     return false;
18903
18904   int n = GET_MODE_PRECISION (mode);
18905   int sh = -1;
18906
18907   if (CONST_INT_P (XEXP (shift, 1)))
18908     {
18909       sh = INTVAL (XEXP (shift, 1));
18910       if (sh < 0 || sh >= n)
18911         return false;
18912     }
18913
18914   rtx_code code = GET_CODE (shift);
18915
18916   /* Convert any shift by 0 to a rotate, to simplify below code.  */
18917   if (sh == 0)
18918     code = ROTATE;
18919
18920   /* Convert rotate to simple shift if we can, to make analysis simpler.  */
18921   if (code == ROTATE && sh >= 0 && nb >= ne && ne >= sh)
18922     code = ASHIFT;
18923   if (code == ROTATE && sh >= 0 && nb >= ne && nb < sh)
18924     {
18925       code = LSHIFTRT;
18926       sh = n - sh;
18927     }
18928
18929   /* DImode rotates need rld*.  */
18930   if (mode == DImode && code == ROTATE)
18931     return (nb == 63 || ne == 0 || ne == sh);
18932
18933   /* SImode rotates need rlw*.  */
18934   if (mode == SImode && code == ROTATE)
18935     return (nb < 32 && ne < 32 && sh < 32);
18936
18937   /* Wrap-around masks are only okay for rotates.  */
18938   if (ne > nb)
18939     return false;
18940
18941   /* Variable shifts are only okay for rotates.  */
18942   if (sh < 0)
18943     return false;
18944
18945   /* Don't allow ASHIFT if the mask is wrong for that.  */
18946   if (code == ASHIFT && ne < sh)
18947     return false;
18948
18949   /* If we can do it with an rlw*, we can do it.  Don't allow LSHIFTRT
18950      if the mask is wrong for that.  */
18951   if (nb < 32 && ne < 32 && sh < 32
18952       && !(code == LSHIFTRT && nb >= 32 - sh))
18953     return true;
18954
18955   /* If we can do it with an rld*, we can do it.  Don't allow LSHIFTRT
18956      if the mask is wrong for that.  */
18957   if (code == LSHIFTRT)
18958     sh = 64 - sh;
18959   if (nb == 63 || ne == 0 || ne == sh)
18960     return !(code == LSHIFTRT && nb >= sh);
18961
18962   return false;
18963 }
18964
18965 /* Return the instruction template for a shift with mask in mode MODE, with
18966    operands OPERANDS.  If DOT is true, make it a record-form instruction.  */
18967
18968 const char *
18969 rs6000_insn_for_shift_mask (machine_mode mode, rtx *operands, bool dot)
18970 {
18971   int nb, ne;
18972
18973   if (!rs6000_is_valid_mask (operands[3], &nb, &ne, mode))
18974     gcc_unreachable ();
18975
18976   if (mode == DImode && ne == 0)
18977     {
18978       if (GET_CODE (operands[4]) == LSHIFTRT && INTVAL (operands[2]))
18979         operands[2] = GEN_INT (64 - INTVAL (operands[2]));
18980       operands[3] = GEN_INT (63 - nb);
18981       if (dot)
18982         return "rld%I2cl. %0,%1,%2,%3";
18983       return "rld%I2cl %0,%1,%2,%3";
18984     }
18985
18986   if (mode == DImode && nb == 63)
18987     {
18988       operands[3] = GEN_INT (63 - ne);
18989       if (dot)
18990         return "rld%I2cr. %0,%1,%2,%3";
18991       return "rld%I2cr %0,%1,%2,%3";
18992     }
18993
18994   if (mode == DImode
18995       && GET_CODE (operands[4]) != LSHIFTRT
18996       && CONST_INT_P (operands[2])
18997       && ne == INTVAL (operands[2]))
18998     {
18999       operands[3] = GEN_INT (63 - nb);
19000       if (dot)
19001         return "rld%I2c. %0,%1,%2,%3";
19002       return "rld%I2c %0,%1,%2,%3";
19003     }
19004
19005   if (nb < 32 && ne < 32)
19006     {
19007       if (GET_CODE (operands[4]) == LSHIFTRT && INTVAL (operands[2]))
19008         operands[2] = GEN_INT (32 - INTVAL (operands[2]));
19009       operands[3] = GEN_INT (31 - nb);
19010       operands[4] = GEN_INT (31 - ne);
19011       /* This insn can also be a 64-bit rotate with mask that really makes
19012          it just a shift right (with mask); the %h below are to adjust for
19013          that situation (shift count is >= 32 in that case).  */
19014       if (dot)
19015         return "rlw%I2nm. %0,%1,%h2,%3,%4";
19016       return "rlw%I2nm %0,%1,%h2,%3,%4";
19017     }
19018
19019   gcc_unreachable ();
19020 }
19021
19022 /* Return whether MASK (a CONST_INT) is a valid mask for any rlwimi or
19023    rldimi instruction, to implement an insert with shift SHIFT (a ROTATE,
19024    ASHIFT, or LSHIFTRT) in mode MODE.  */
19025
19026 bool
19027 rs6000_is_valid_insert_mask (rtx mask, rtx shift, machine_mode mode)
19028 {
19029   int nb, ne;
19030
19031   if (!rs6000_is_valid_mask (mask, &nb, &ne, mode))
19032     return false;
19033
19034   int n = GET_MODE_PRECISION (mode);
19035
19036   int sh = INTVAL (XEXP (shift, 1));
19037   if (sh < 0 || sh >= n)
19038     return false;
19039
19040   rtx_code code = GET_CODE (shift);
19041
19042   /* Convert any shift by 0 to a rotate, to simplify below code.  */
19043   if (sh == 0)
19044     code = ROTATE;
19045
19046   /* Convert rotate to simple shift if we can, to make analysis simpler.  */
19047   if (code == ROTATE && sh >= 0 && nb >= ne && ne >= sh)
19048     code = ASHIFT;
19049   if (code == ROTATE && sh >= 0 && nb >= ne && nb < sh)
19050     {
19051       code = LSHIFTRT;
19052       sh = n - sh;
19053     }
19054
19055   /* DImode rotates need rldimi.  */
19056   if (mode == DImode && code == ROTATE)
19057     return (ne == sh);
19058
19059   /* SImode rotates need rlwimi.  */
19060   if (mode == SImode && code == ROTATE)
19061     return (nb < 32 && ne < 32 && sh < 32);
19062
19063   /* Wrap-around masks are only okay for rotates.  */
19064   if (ne > nb)
19065     return false;
19066
19067   /* Don't allow ASHIFT if the mask is wrong for that.  */
19068   if (code == ASHIFT && ne < sh)
19069     return false;
19070
19071   /* If we can do it with an rlwimi, we can do it.  Don't allow LSHIFTRT
19072      if the mask is wrong for that.  */
19073   if (nb < 32 && ne < 32 && sh < 32
19074       && !(code == LSHIFTRT && nb >= 32 - sh))
19075     return true;
19076
19077   /* If we can do it with an rldimi, we can do it.  Don't allow LSHIFTRT
19078      if the mask is wrong for that.  */
19079   if (code == LSHIFTRT)
19080     sh = 64 - sh;
19081   if (ne == sh)
19082     return !(code == LSHIFTRT && nb >= sh);
19083
19084   return false;
19085 }
19086
19087 /* Return the instruction template for an insert with mask in mode MODE, with
19088    operands OPERANDS.  If DOT is true, make it a record-form instruction.  */
19089
19090 const char *
19091 rs6000_insn_for_insert_mask (machine_mode mode, rtx *operands, bool dot)
19092 {
19093   int nb, ne;
19094
19095   if (!rs6000_is_valid_mask (operands[3], &nb, &ne, mode))
19096     gcc_unreachable ();
19097
19098   /* Prefer rldimi because rlwimi is cracked.  */
19099   if (TARGET_POWERPC64
19100       && (!dot || mode == DImode)
19101       && GET_CODE (operands[4]) != LSHIFTRT
19102       && ne == INTVAL (operands[2]))
19103     {
19104       operands[3] = GEN_INT (63 - nb);
19105       if (dot)
19106         return "rldimi. %0,%1,%2,%3";
19107       return "rldimi %0,%1,%2,%3";
19108     }
19109
19110   if (nb < 32 && ne < 32)
19111     {
19112       if (GET_CODE (operands[4]) == LSHIFTRT && INTVAL (operands[2]))
19113         operands[2] = GEN_INT (32 - INTVAL (operands[2]));
19114       operands[3] = GEN_INT (31 - nb);
19115       operands[4] = GEN_INT (31 - ne);
19116       if (dot)
19117         return "rlwimi. %0,%1,%2,%3,%4";
19118       return "rlwimi %0,%1,%2,%3,%4";
19119     }
19120
19121   gcc_unreachable ();
19122 }
19123
19124 /* Return whether an AND with C (a CONST_INT) in mode MODE can be done
19125    using two machine instructions.  */
19126
19127 bool
19128 rs6000_is_valid_2insn_and (rtx c, machine_mode mode)
19129 {
19130   /* There are two kinds of AND we can handle with two insns:
19131      1) those we can do with two rl* insn;
19132      2) ori[s];xori[s].
19133
19134      We do not handle that last case yet.  */
19135
19136   /* If there is just one stretch of ones, we can do it.  */
19137   if (rs6000_is_valid_mask (c, NULL, NULL, mode))
19138     return true;
19139
19140   /* Otherwise, fill in the lowest "hole"; if we can do the result with
19141      one insn, we can do the whole thing with two.  */
19142   unsigned HOST_WIDE_INT val = INTVAL (c);
19143   unsigned HOST_WIDE_INT bit1 = val & -val;
19144   unsigned HOST_WIDE_INT bit2 = (val + bit1) & ~val;
19145   unsigned HOST_WIDE_INT val1 = (val + bit1) & val;
19146   unsigned HOST_WIDE_INT bit3 = val1 & -val1;
19147   return rs6000_is_valid_and_mask (GEN_INT (val + bit3 - bit2), mode);
19148 }
19149
19150 /* Emit the two insns to do an AND in mode MODE, with operands OPERANDS.
19151    If EXPAND is true, split rotate-and-mask instructions we generate to
19152    their constituent parts as well (this is used during expand); if DOT
19153    is 1, make the last insn a record-form instruction clobbering the
19154    destination GPR and setting the CC reg (from operands[3]); if 2, set
19155    that GPR as well as the CC reg.  */
19156
19157 void
19158 rs6000_emit_2insn_and (machine_mode mode, rtx *operands, bool expand, int dot)
19159 {
19160   gcc_assert (!(expand && dot));
19161
19162   unsigned HOST_WIDE_INT val = INTVAL (operands[2]);
19163
19164   /* If it is one stretch of ones, it is DImode; shift left, mask, then
19165      shift right.  This generates better code than doing the masks without
19166      shifts, or shifting first right and then left.  */
19167   int nb, ne;
19168   if (rs6000_is_valid_mask (operands[2], &nb, &ne, mode) && nb >= ne)
19169     {
19170       gcc_assert (mode == DImode);
19171
19172       int shift = 63 - nb;
19173       if (expand)
19174         {
19175           rtx tmp1 = gen_reg_rtx (DImode);
19176           rtx tmp2 = gen_reg_rtx (DImode);
19177           emit_insn (gen_ashldi3 (tmp1, operands[1], GEN_INT (shift)));
19178           emit_insn (gen_anddi3 (tmp2, tmp1, GEN_INT (val << shift)));
19179           emit_insn (gen_lshrdi3 (operands[0], tmp2, GEN_INT (shift)));
19180         }
19181       else
19182         {
19183           rtx tmp = gen_rtx_ASHIFT (mode, operands[1], GEN_INT (shift));
19184           tmp = gen_rtx_AND (mode, tmp, GEN_INT (val << shift));
19185           emit_move_insn (operands[0], tmp);
19186           tmp = gen_rtx_LSHIFTRT (mode, operands[0], GEN_INT (shift));
19187           rs6000_emit_dot_insn (operands[0], tmp, dot, dot ? operands[3] : 0);
19188         }
19189       return;
19190     }
19191
19192   /* Otherwise, make a mask2 that cuts out the lowest "hole", and a mask1
19193      that does the rest.  */
19194   unsigned HOST_WIDE_INT bit1 = val & -val;
19195   unsigned HOST_WIDE_INT bit2 = (val + bit1) & ~val;
19196   unsigned HOST_WIDE_INT val1 = (val + bit1) & val;
19197   unsigned HOST_WIDE_INT bit3 = val1 & -val1;
19198
19199   unsigned HOST_WIDE_INT mask1 = -bit3 + bit2 - 1;
19200   unsigned HOST_WIDE_INT mask2 = val + bit3 - bit2;
19201
19202   gcc_assert (rs6000_is_valid_and_mask (GEN_INT (mask2), mode));
19203
19204   /* Two "no-rotate"-and-mask instructions, for SImode.  */
19205   if (rs6000_is_valid_and_mask (GEN_INT (mask1), mode))
19206     {
19207       gcc_assert (mode == SImode);
19208
19209       rtx reg = expand ? gen_reg_rtx (mode) : operands[0];
19210       rtx tmp = gen_rtx_AND (mode, operands[1], GEN_INT (mask1));
19211       emit_move_insn (reg, tmp);
19212       tmp = gen_rtx_AND (mode, reg, GEN_INT (mask2));
19213       rs6000_emit_dot_insn (operands[0], tmp, dot, dot ? operands[3] : 0);
19214       return;
19215     }
19216
19217   gcc_assert (mode == DImode);
19218
19219   /* Two "no-rotate"-and-mask instructions, for DImode: both are rlwinm
19220      insns; we have to do the first in SImode, because it wraps.  */
19221   if (mask2 <= 0xffffffff
19222       && rs6000_is_valid_and_mask (GEN_INT (mask1), SImode))
19223     {
19224       rtx reg = expand ? gen_reg_rtx (mode) : operands[0];
19225       rtx tmp = gen_rtx_AND (SImode, gen_lowpart (SImode, operands[1]),
19226                              GEN_INT (mask1));
19227       rtx reg_low = gen_lowpart (SImode, reg);
19228       emit_move_insn (reg_low, tmp);
19229       tmp = gen_rtx_AND (mode, reg, GEN_INT (mask2));
19230       rs6000_emit_dot_insn (operands[0], tmp, dot, dot ? operands[3] : 0);
19231       return;
19232     }
19233
19234   /* Two rld* insns: rotate, clear the hole in the middle (which now is
19235      at the top end), rotate back and clear the other hole.  */
19236   int right = exact_log2 (bit3);
19237   int left = 64 - right;
19238
19239   /* Rotate the mask too.  */
19240   mask1 = (mask1 >> right) | ((bit2 - 1) << left);
19241
19242   if (expand)
19243     {
19244       rtx tmp1 = gen_reg_rtx (DImode);
19245       rtx tmp2 = gen_reg_rtx (DImode);
19246       rtx tmp3 = gen_reg_rtx (DImode);
19247       emit_insn (gen_rotldi3 (tmp1, operands[1], GEN_INT (left)));
19248       emit_insn (gen_anddi3 (tmp2, tmp1, GEN_INT (mask1)));
19249       emit_insn (gen_rotldi3 (tmp3, tmp2, GEN_INT (right)));
19250       emit_insn (gen_anddi3 (operands[0], tmp3, GEN_INT (mask2)));
19251     }
19252   else
19253     {
19254       rtx tmp = gen_rtx_ROTATE (mode, operands[1], GEN_INT (left));
19255       tmp = gen_rtx_AND (mode, tmp, GEN_INT (mask1));
19256       emit_move_insn (operands[0], tmp);
19257       tmp = gen_rtx_ROTATE (mode, operands[0], GEN_INT (right));
19258       tmp = gen_rtx_AND (mode, tmp, GEN_INT (mask2));
19259       rs6000_emit_dot_insn (operands[0], tmp, dot, dot ? operands[3] : 0);
19260     }
19261 }
19262 \f
19263 /* Return 1 if REGNO (reg1) == REGNO (reg2) - 1 making them candidates
19264    for lfq and stfq insns iff the registers are hard registers.   */
19265
19266 int
19267 registers_ok_for_quad_peep (rtx reg1, rtx reg2)
19268 {
19269   /* We might have been passed a SUBREG.  */
19270   if (GET_CODE (reg1) != REG || GET_CODE (reg2) != REG)
19271     return 0;
19272
19273   /* We might have been passed non floating point registers.  */
19274   if (!FP_REGNO_P (REGNO (reg1))
19275       || !FP_REGNO_P (REGNO (reg2)))
19276     return 0;
19277
19278   return (REGNO (reg1) == REGNO (reg2) - 1);
19279 }
19280
19281 /* Return 1 if addr1 and addr2 are suitable for lfq or stfq insn.
19282    addr1 and addr2 must be in consecutive memory locations
19283    (addr2 == addr1 + 8).  */
19284
19285 int
19286 mems_ok_for_quad_peep (rtx mem1, rtx mem2)
19287 {
19288   rtx addr1, addr2;
19289   unsigned int reg1, reg2;
19290   int offset1, offset2;
19291
19292   /* The mems cannot be volatile.  */
19293   if (MEM_VOLATILE_P (mem1) || MEM_VOLATILE_P (mem2))
19294     return 0;
19295
19296   addr1 = XEXP (mem1, 0);
19297   addr2 = XEXP (mem2, 0);
19298
19299   /* Extract an offset (if used) from the first addr.  */
19300   if (GET_CODE (addr1) == PLUS)
19301     {
19302       /* If not a REG, return zero.  */
19303       if (GET_CODE (XEXP (addr1, 0)) != REG)
19304         return 0;
19305       else
19306         {
19307           reg1 = REGNO (XEXP (addr1, 0));
19308           /* The offset must be constant!  */
19309           if (GET_CODE (XEXP (addr1, 1)) != CONST_INT)
19310             return 0;
19311           offset1 = INTVAL (XEXP (addr1, 1));
19312         }
19313     }
19314   else if (GET_CODE (addr1) != REG)
19315     return 0;
19316   else
19317     {
19318       reg1 = REGNO (addr1);
19319       /* This was a simple (mem (reg)) expression.  Offset is 0.  */
19320       offset1 = 0;
19321     }
19322
19323   /* And now for the second addr.  */
19324   if (GET_CODE (addr2) == PLUS)
19325     {
19326       /* If not a REG, return zero.  */
19327       if (GET_CODE (XEXP (addr2, 0)) != REG)
19328         return 0;
19329       else
19330         {
19331           reg2 = REGNO (XEXP (addr2, 0));
19332           /* The offset must be constant. */
19333           if (GET_CODE (XEXP (addr2, 1)) != CONST_INT)
19334             return 0;
19335           offset2 = INTVAL (XEXP (addr2, 1));
19336         }
19337     }
19338   else if (GET_CODE (addr2) != REG)
19339     return 0;
19340   else
19341     {
19342       reg2 = REGNO (addr2);
19343       /* This was a simple (mem (reg)) expression.  Offset is 0.  */
19344       offset2 = 0;
19345     }
19346
19347   /* Both of these must have the same base register.  */
19348   if (reg1 != reg2)
19349     return 0;
19350
19351   /* The offset for the second addr must be 8 more than the first addr.  */
19352   if (offset2 != offset1 + 8)
19353     return 0;
19354
19355   /* All the tests passed.  addr1 and addr2 are valid for lfq or stfq
19356      instructions.  */
19357   return 1;
19358 }
19359 \f
19360 /* Implement TARGET_SECONDARY_RELOAD_NEEDED_MODE.  For SDmode values we
19361    need to use DDmode, in all other cases we can use the same mode.  */
19362 static machine_mode
19363 rs6000_secondary_memory_needed_mode (machine_mode mode)
19364 {
19365   if (lra_in_progress && mode == SDmode)
19366     return DDmode;
19367   return mode;
19368 }
19369
19370 /* Classify a register type.  Because the FMRGOW/FMRGEW instructions only work
19371    on traditional floating point registers, and the VMRGOW/VMRGEW instructions
19372    only work on the traditional altivec registers, note if an altivec register
19373    was chosen.  */
19374
19375 static enum rs6000_reg_type
19376 register_to_reg_type (rtx reg, bool *is_altivec)
19377 {
19378   HOST_WIDE_INT regno;
19379   enum reg_class rclass;
19380
19381   if (GET_CODE (reg) == SUBREG)
19382     reg = SUBREG_REG (reg);
19383
19384   if (!REG_P (reg))
19385     return NO_REG_TYPE;
19386
19387   regno = REGNO (reg);
19388   if (regno >= FIRST_PSEUDO_REGISTER)
19389     {
19390       if (!lra_in_progress && !reload_completed)
19391         return PSEUDO_REG_TYPE;
19392
19393       regno = true_regnum (reg);
19394       if (regno < 0 || regno >= FIRST_PSEUDO_REGISTER)
19395         return PSEUDO_REG_TYPE;
19396     }
19397
19398   gcc_assert (regno >= 0);
19399
19400   if (is_altivec && ALTIVEC_REGNO_P (regno))
19401     *is_altivec = true;
19402
19403   rclass = rs6000_regno_regclass[regno];
19404   return reg_class_to_reg_type[(int)rclass];
19405 }
19406
19407 /* Helper function to return the cost of adding a TOC entry address.  */
19408
19409 static inline int
19410 rs6000_secondary_reload_toc_costs (addr_mask_type addr_mask)
19411 {
19412   int ret;
19413
19414   if (TARGET_CMODEL != CMODEL_SMALL)
19415     ret = ((addr_mask & RELOAD_REG_OFFSET) == 0) ? 1 : 2;
19416
19417   else
19418     ret = (TARGET_MINIMAL_TOC) ? 6 : 3;
19419
19420   return ret;
19421 }
19422
19423 /* Helper function for rs6000_secondary_reload to determine whether the memory
19424    address (ADDR) with a given register class (RCLASS) and machine mode (MODE)
19425    needs reloading.  Return negative if the memory is not handled by the memory
19426    helper functions and to try a different reload method, 0 if no additional
19427    instructions are need, and positive to give the extra cost for the
19428    memory.  */
19429
19430 static int
19431 rs6000_secondary_reload_memory (rtx addr,
19432                                 enum reg_class rclass,
19433                                 machine_mode mode)
19434 {
19435   int extra_cost = 0;
19436   rtx reg, and_arg, plus_arg0, plus_arg1;
19437   addr_mask_type addr_mask;
19438   const char *type = NULL;
19439   const char *fail_msg = NULL;
19440
19441   if (GPR_REG_CLASS_P (rclass))
19442     addr_mask = reg_addr[mode].addr_mask[RELOAD_REG_GPR];
19443
19444   else if (rclass == FLOAT_REGS)
19445     addr_mask = reg_addr[mode].addr_mask[RELOAD_REG_FPR];
19446
19447   else if (rclass == ALTIVEC_REGS)
19448     addr_mask = reg_addr[mode].addr_mask[RELOAD_REG_VMX];
19449
19450   /* For the combined VSX_REGS, turn off Altivec AND -16.  */
19451   else if (rclass == VSX_REGS)
19452     addr_mask = (reg_addr[mode].addr_mask[RELOAD_REG_VMX]
19453                  & ~RELOAD_REG_AND_M16);
19454
19455   /* If the register allocator hasn't made up its mind yet on the register
19456      class to use, settle on defaults to use.  */
19457   else if (rclass == NO_REGS)
19458     {
19459       addr_mask = (reg_addr[mode].addr_mask[RELOAD_REG_ANY]
19460                    & ~RELOAD_REG_AND_M16);
19461
19462       if ((addr_mask & RELOAD_REG_MULTIPLE) != 0)
19463         addr_mask &= ~(RELOAD_REG_INDEXED
19464                        | RELOAD_REG_PRE_INCDEC
19465                        | RELOAD_REG_PRE_MODIFY);
19466     }
19467
19468   else
19469     addr_mask = 0;
19470
19471   /* If the register isn't valid in this register class, just return now.  */
19472   if ((addr_mask & RELOAD_REG_VALID) == 0)
19473     {
19474       if (TARGET_DEBUG_ADDR)
19475         {
19476           fprintf (stderr,
19477                    "rs6000_secondary_reload_memory: mode = %s, class = %s, "
19478                    "not valid in class\n",
19479                    GET_MODE_NAME (mode), reg_class_names[rclass]);
19480           debug_rtx (addr);
19481         }
19482
19483       return -1;
19484     }
19485
19486   switch (GET_CODE (addr))
19487     {
19488       /* Does the register class supports auto update forms for this mode?  We
19489          don't need a scratch register, since the powerpc only supports
19490          PRE_INC, PRE_DEC, and PRE_MODIFY.  */
19491     case PRE_INC:
19492     case PRE_DEC:
19493       reg = XEXP (addr, 0);
19494       if (!base_reg_operand (addr, GET_MODE (reg)))
19495         {
19496           fail_msg = "no base register #1";
19497           extra_cost = -1;
19498         }
19499
19500       else if ((addr_mask & RELOAD_REG_PRE_INCDEC) == 0)
19501         {
19502           extra_cost = 1;
19503           type = "update";
19504         }
19505       break;
19506
19507     case PRE_MODIFY:
19508       reg = XEXP (addr, 0);
19509       plus_arg1 = XEXP (addr, 1);
19510       if (!base_reg_operand (reg, GET_MODE (reg))
19511           || GET_CODE (plus_arg1) != PLUS
19512           || !rtx_equal_p (reg, XEXP (plus_arg1, 0)))
19513         {
19514           fail_msg = "bad PRE_MODIFY";
19515           extra_cost = -1;
19516         }
19517
19518       else if ((addr_mask & RELOAD_REG_PRE_MODIFY) == 0)
19519         {
19520           extra_cost = 1;
19521           type = "update";
19522         }
19523       break;
19524
19525       /* Do we need to simulate AND -16 to clear the bottom address bits used
19526          in VMX load/stores?  Only allow the AND for vector sizes.  */
19527     case AND:
19528       and_arg = XEXP (addr, 0);
19529       if (GET_MODE_SIZE (mode) != 16
19530           || GET_CODE (XEXP (addr, 1)) != CONST_INT
19531           || INTVAL (XEXP (addr, 1)) != -16)
19532         {
19533           fail_msg = "bad Altivec AND #1";
19534           extra_cost = -1;
19535         }
19536
19537       if (rclass != ALTIVEC_REGS)
19538         {
19539           if (legitimate_indirect_address_p (and_arg, false))
19540             extra_cost = 1;
19541
19542           else if (legitimate_indexed_address_p (and_arg, false))
19543             extra_cost = 2;
19544
19545           else
19546             {
19547               fail_msg = "bad Altivec AND #2";
19548               extra_cost = -1;
19549             }
19550
19551           type = "and";
19552         }
19553       break;
19554
19555       /* If this is an indirect address, make sure it is a base register.  */
19556     case REG:
19557     case SUBREG:
19558       if (!legitimate_indirect_address_p (addr, false))
19559         {
19560           extra_cost = 1;
19561           type = "move";
19562         }
19563       break;
19564
19565       /* If this is an indexed address, make sure the register class can handle
19566          indexed addresses for this mode.  */
19567     case PLUS:
19568       plus_arg0 = XEXP (addr, 0);
19569       plus_arg1 = XEXP (addr, 1);
19570
19571       /* (plus (plus (reg) (constant)) (constant)) is generated during
19572          push_reload processing, so handle it now.  */
19573       if (GET_CODE (plus_arg0) == PLUS && CONST_INT_P (plus_arg1))
19574         {
19575           if ((addr_mask & RELOAD_REG_OFFSET) == 0)
19576             {
19577               extra_cost = 1;
19578               type = "offset";
19579             }
19580         }
19581
19582       /* (plus (plus (reg) (constant)) (reg)) is also generated during
19583          push_reload processing, so handle it now.  */
19584       else if (GET_CODE (plus_arg0) == PLUS && REG_P (plus_arg1))
19585         {
19586           if ((addr_mask & RELOAD_REG_INDEXED) == 0)
19587             {
19588               extra_cost = 1;
19589               type = "indexed #2";
19590             }
19591         }
19592
19593       else if (!base_reg_operand (plus_arg0, GET_MODE (plus_arg0)))
19594         {
19595           fail_msg = "no base register #2";
19596           extra_cost = -1;
19597         }
19598
19599       else if (int_reg_operand (plus_arg1, GET_MODE (plus_arg1)))
19600         {
19601           if ((addr_mask & RELOAD_REG_INDEXED) == 0
19602               || !legitimate_indexed_address_p (addr, false))
19603             {
19604               extra_cost = 1;
19605               type = "indexed";
19606             }
19607         }
19608
19609       else if ((addr_mask & RELOAD_REG_QUAD_OFFSET) != 0
19610                && CONST_INT_P (plus_arg1))
19611         {
19612           if (!quad_address_offset_p (INTVAL (plus_arg1)))
19613             {
19614               extra_cost = 1;
19615               type = "vector d-form offset";
19616             }
19617         }
19618
19619       /* Make sure the register class can handle offset addresses.  */
19620       else if (rs6000_legitimate_offset_address_p (mode, addr, false, true))
19621         {
19622           if ((addr_mask & RELOAD_REG_OFFSET) == 0)
19623             {
19624               extra_cost = 1;
19625               type = "offset #2";
19626             }
19627         }
19628
19629       else
19630         {
19631           fail_msg = "bad PLUS";
19632           extra_cost = -1;
19633         }
19634
19635       break;
19636
19637     case LO_SUM:
19638       /* Quad offsets are restricted and can't handle normal addresses.  */
19639       if ((addr_mask & RELOAD_REG_QUAD_OFFSET) != 0)
19640         {
19641           extra_cost = -1;
19642           type = "vector d-form lo_sum";
19643         }
19644
19645       else if (!legitimate_lo_sum_address_p (mode, addr, false))
19646         {
19647           fail_msg = "bad LO_SUM";
19648           extra_cost = -1;
19649         }
19650
19651       if ((addr_mask & RELOAD_REG_OFFSET) == 0)
19652         {
19653           extra_cost = 1;
19654           type = "lo_sum";
19655         }
19656       break;
19657
19658       /* Static addresses need to create a TOC entry.  */
19659     case CONST:
19660     case SYMBOL_REF:
19661     case LABEL_REF:
19662       if ((addr_mask & RELOAD_REG_QUAD_OFFSET) != 0)
19663         {
19664           extra_cost = -1;
19665           type = "vector d-form lo_sum #2";
19666         }
19667
19668       else
19669         {
19670           type = "address";
19671           extra_cost = rs6000_secondary_reload_toc_costs (addr_mask);
19672         }
19673       break;
19674
19675       /* TOC references look like offsetable memory.  */
19676     case UNSPEC:
19677       if (TARGET_CMODEL == CMODEL_SMALL || XINT (addr, 1) != UNSPEC_TOCREL)
19678         {
19679           fail_msg = "bad UNSPEC";
19680           extra_cost = -1;
19681         }
19682
19683       else if ((addr_mask & RELOAD_REG_QUAD_OFFSET) != 0)
19684         {
19685           extra_cost = -1;
19686           type = "vector d-form lo_sum #3";
19687         }
19688
19689       else if ((addr_mask & RELOAD_REG_OFFSET) == 0)
19690         {
19691           extra_cost = 1;
19692           type = "toc reference";
19693         }
19694       break;
19695
19696     default:
19697         {
19698           fail_msg = "bad address";
19699           extra_cost = -1;
19700         }
19701     }
19702
19703   if (TARGET_DEBUG_ADDR /* && extra_cost != 0 */)
19704     {
19705       if (extra_cost < 0)
19706         fprintf (stderr,
19707                  "rs6000_secondary_reload_memory error: mode = %s, "
19708                  "class = %s, addr_mask = '%s', %s\n",
19709                  GET_MODE_NAME (mode),
19710                  reg_class_names[rclass],
19711                  rs6000_debug_addr_mask (addr_mask, false),
19712                  (fail_msg != NULL) ? fail_msg : "<bad address>");
19713
19714       else
19715         fprintf (stderr,
19716                  "rs6000_secondary_reload_memory: mode = %s, class = %s, "
19717                  "addr_mask = '%s', extra cost = %d, %s\n",
19718                  GET_MODE_NAME (mode),
19719                  reg_class_names[rclass],
19720                  rs6000_debug_addr_mask (addr_mask, false),
19721                  extra_cost,
19722                  (type) ? type : "<none>");
19723
19724       debug_rtx (addr);
19725     }
19726
19727   return extra_cost;
19728 }
19729
19730 /* Helper function for rs6000_secondary_reload to return true if a move to a
19731    different register classe is really a simple move.  */
19732
19733 static bool
19734 rs6000_secondary_reload_simple_move (enum rs6000_reg_type to_type,
19735                                      enum rs6000_reg_type from_type,
19736                                      machine_mode mode)
19737 {
19738   int size = GET_MODE_SIZE (mode);
19739
19740   /* Add support for various direct moves available.  In this function, we only
19741      look at cases where we don't need any extra registers, and one or more
19742      simple move insns are issued.  Originally small integers are not allowed
19743      in FPR/VSX registers.  Single precision binary floating is not a simple
19744      move because we need to convert to the single precision memory layout.
19745      The 4-byte SDmode can be moved.  TDmode values are disallowed since they
19746      need special direct move handling, which we do not support yet.  */
19747   if (TARGET_DIRECT_MOVE
19748       && ((to_type == GPR_REG_TYPE && from_type == VSX_REG_TYPE)
19749           || (to_type == VSX_REG_TYPE && from_type == GPR_REG_TYPE)))
19750     {
19751       if (TARGET_POWERPC64)
19752         {
19753           /* ISA 2.07: MTVSRD or MVFVSRD.  */
19754           if (size == 8)
19755             return true;
19756
19757           /* ISA 3.0: MTVSRDD or MFVSRD + MFVSRLD.  */
19758           if (size == 16 && TARGET_P9_VECTOR && mode != TDmode)
19759             return true;
19760         }
19761
19762       /* ISA 2.07: MTVSRWZ or  MFVSRWZ.  */
19763       if (TARGET_P8_VECTOR)
19764         {
19765           if (mode == SImode)
19766             return true;
19767
19768           if (TARGET_P9_VECTOR && (mode == HImode || mode == QImode))
19769             return true;
19770         }
19771
19772       /* ISA 2.07: MTVSRWZ or  MFVSRWZ.  */
19773       if (mode == SDmode)
19774         return true;
19775     }
19776
19777   /* Power6+: MFTGPR or MFFGPR.  */
19778   else if (TARGET_MFPGPR && TARGET_POWERPC64 && size == 8
19779       && ((to_type == GPR_REG_TYPE && from_type == FPR_REG_TYPE)
19780           || (to_type == FPR_REG_TYPE && from_type == GPR_REG_TYPE)))
19781     return true;
19782
19783   /* Move to/from SPR.  */
19784   else if ((size == 4 || (TARGET_POWERPC64 && size == 8))
19785            && ((to_type == GPR_REG_TYPE && from_type == SPR_REG_TYPE)
19786                || (to_type == SPR_REG_TYPE && from_type == GPR_REG_TYPE)))
19787     return true;
19788
19789   return false;
19790 }
19791
19792 /* Direct move helper function for rs6000_secondary_reload, handle all of the
19793    special direct moves that involve allocating an extra register, return the
19794    insn code of the helper function if there is such a function or
19795    CODE_FOR_nothing if not.  */
19796
19797 static bool
19798 rs6000_secondary_reload_direct_move (enum rs6000_reg_type to_type,
19799                                      enum rs6000_reg_type from_type,
19800                                      machine_mode mode,
19801                                      secondary_reload_info *sri,
19802                                      bool altivec_p)
19803 {
19804   bool ret = false;
19805   enum insn_code icode = CODE_FOR_nothing;
19806   int cost = 0;
19807   int size = GET_MODE_SIZE (mode);
19808
19809   if (TARGET_POWERPC64 && size == 16)
19810     {
19811       /* Handle moving 128-bit values from GPRs to VSX point registers on
19812          ISA 2.07 (power8, power9) when running in 64-bit mode using
19813          XXPERMDI to glue the two 64-bit values back together.  */
19814       if (to_type == VSX_REG_TYPE && from_type == GPR_REG_TYPE)
19815         {
19816           cost = 3;                     /* 2 mtvsrd's, 1 xxpermdi.  */
19817           icode = reg_addr[mode].reload_vsx_gpr;
19818         }
19819
19820       /* Handle moving 128-bit values from VSX point registers to GPRs on
19821          ISA 2.07 when running in 64-bit mode using XXPERMDI to get access to the
19822          bottom 64-bit value.  */
19823       else if (to_type == GPR_REG_TYPE && from_type == VSX_REG_TYPE)
19824         {
19825           cost = 3;                     /* 2 mfvsrd's, 1 xxpermdi.  */
19826           icode = reg_addr[mode].reload_gpr_vsx;
19827         }
19828     }
19829
19830   else if (TARGET_POWERPC64 && mode == SFmode)
19831     {
19832       if (to_type == GPR_REG_TYPE && from_type == VSX_REG_TYPE)
19833         {
19834           cost = 3;                     /* xscvdpspn, mfvsrd, and.  */
19835           icode = reg_addr[mode].reload_gpr_vsx;
19836         }
19837
19838       else if (to_type == VSX_REG_TYPE && from_type == GPR_REG_TYPE)
19839         {
19840           cost = 2;                     /* mtvsrz, xscvspdpn.  */
19841           icode = reg_addr[mode].reload_vsx_gpr;
19842         }
19843     }
19844
19845   else if (!TARGET_POWERPC64 && size == 8)
19846     {
19847       /* Handle moving 64-bit values from GPRs to floating point registers on
19848          ISA 2.07 when running in 32-bit mode using FMRGOW to glue the two
19849          32-bit values back together.  Altivec register classes must be handled
19850          specially since a different instruction is used, and the secondary
19851          reload support requires a single instruction class in the scratch
19852          register constraint.  However, right now TFmode is not allowed in
19853          Altivec registers, so the pattern will never match.  */
19854       if (to_type == VSX_REG_TYPE && from_type == GPR_REG_TYPE && !altivec_p)
19855         {
19856           cost = 3;                     /* 2 mtvsrwz's, 1 fmrgow.  */
19857           icode = reg_addr[mode].reload_fpr_gpr;
19858         }
19859     }
19860
19861   if (icode != CODE_FOR_nothing)
19862     {
19863       ret = true;
19864       if (sri)
19865         {
19866           sri->icode = icode;
19867           sri->extra_cost = cost;
19868         }
19869     }
19870
19871   return ret;
19872 }
19873
19874 /* Return whether a move between two register classes can be done either
19875    directly (simple move) or via a pattern that uses a single extra temporary
19876    (using ISA 2.07's direct move in this case.  */
19877
19878 static bool
19879 rs6000_secondary_reload_move (enum rs6000_reg_type to_type,
19880                               enum rs6000_reg_type from_type,
19881                               machine_mode mode,
19882                               secondary_reload_info *sri,
19883                               bool altivec_p)
19884 {
19885   /* Fall back to load/store reloads if either type is not a register.  */
19886   if (to_type == NO_REG_TYPE || from_type == NO_REG_TYPE)
19887     return false;
19888
19889   /* If we haven't allocated registers yet, assume the move can be done for the
19890      standard register types.  */
19891   if ((to_type == PSEUDO_REG_TYPE && from_type == PSEUDO_REG_TYPE)
19892       || (to_type == PSEUDO_REG_TYPE && IS_STD_REG_TYPE (from_type))
19893       || (from_type == PSEUDO_REG_TYPE && IS_STD_REG_TYPE (to_type)))
19894     return true;
19895
19896   /* Moves to the same set of registers is a simple move for non-specialized
19897      registers.  */
19898   if (to_type == from_type && IS_STD_REG_TYPE (to_type))
19899     return true;
19900
19901   /* Check whether a simple move can be done directly.  */
19902   if (rs6000_secondary_reload_simple_move (to_type, from_type, mode))
19903     {
19904       if (sri)
19905         {
19906           sri->icode = CODE_FOR_nothing;
19907           sri->extra_cost = 0;
19908         }
19909       return true;
19910     }
19911
19912   /* Now check if we can do it in a few steps.  */
19913   return rs6000_secondary_reload_direct_move (to_type, from_type, mode, sri,
19914                                               altivec_p);
19915 }
19916
19917 /* Inform reload about cases where moving X with a mode MODE to a register in
19918    RCLASS requires an extra scratch or immediate register.  Return the class
19919    needed for the immediate register.
19920
19921    For VSX and Altivec, we may need a register to convert sp+offset into
19922    reg+sp.
19923
19924    For misaligned 64-bit gpr loads and stores we need a register to
19925    convert an offset address to indirect.  */
19926
19927 static reg_class_t
19928 rs6000_secondary_reload (bool in_p,
19929                          rtx x,
19930                          reg_class_t rclass_i,
19931                          machine_mode mode,
19932                          secondary_reload_info *sri)
19933 {
19934   enum reg_class rclass = (enum reg_class) rclass_i;
19935   reg_class_t ret = ALL_REGS;
19936   enum insn_code icode;
19937   bool default_p = false;
19938   bool done_p = false;
19939
19940   /* Allow subreg of memory before/during reload.  */
19941   bool memory_p = (MEM_P (x)
19942                    || (!reload_completed && GET_CODE (x) == SUBREG
19943                        && MEM_P (SUBREG_REG (x))));
19944
19945   sri->icode = CODE_FOR_nothing;
19946   sri->t_icode = CODE_FOR_nothing;
19947   sri->extra_cost = 0;
19948   icode = ((in_p)
19949            ? reg_addr[mode].reload_load
19950            : reg_addr[mode].reload_store);
19951
19952   if (REG_P (x) || register_operand (x, mode))
19953     {
19954       enum rs6000_reg_type to_type = reg_class_to_reg_type[(int)rclass];
19955       bool altivec_p = (rclass == ALTIVEC_REGS);
19956       enum rs6000_reg_type from_type = register_to_reg_type (x, &altivec_p);
19957
19958       if (!in_p)
19959         std::swap (to_type, from_type);
19960
19961       /* Can we do a direct move of some sort?  */
19962       if (rs6000_secondary_reload_move (to_type, from_type, mode, sri,
19963                                         altivec_p))
19964         {
19965           icode = (enum insn_code)sri->icode;
19966           default_p = false;
19967           done_p = true;
19968           ret = NO_REGS;
19969         }
19970     }
19971
19972   /* Make sure 0.0 is not reloaded or forced into memory.  */
19973   if (x == CONST0_RTX (mode) && VSX_REG_CLASS_P (rclass))
19974     {
19975       ret = NO_REGS;
19976       default_p = false;
19977       done_p = true;
19978     }
19979
19980   /* If this is a scalar floating point value and we want to load it into the
19981      traditional Altivec registers, do it via a move via a traditional floating
19982      point register, unless we have D-form addressing.  Also make sure that
19983      non-zero constants use a FPR.  */
19984   if (!done_p && reg_addr[mode].scalar_in_vmx_p
19985       && !mode_supports_vmx_dform (mode)
19986       && (rclass == VSX_REGS || rclass == ALTIVEC_REGS)
19987       && (memory_p || (GET_CODE (x) == CONST_DOUBLE)))
19988     {
19989       ret = FLOAT_REGS;
19990       default_p = false;
19991       done_p = true;
19992     }
19993
19994   /* Handle reload of load/stores if we have reload helper functions.  */
19995   if (!done_p && icode != CODE_FOR_nothing && memory_p)
19996     {
19997       int extra_cost = rs6000_secondary_reload_memory (XEXP (x, 0), rclass,
19998                                                        mode);
19999
20000       if (extra_cost >= 0)
20001         {
20002           done_p = true;
20003           ret = NO_REGS;
20004           if (extra_cost > 0)
20005             {
20006               sri->extra_cost = extra_cost;
20007               sri->icode = icode;
20008             }
20009         }
20010     }
20011
20012   /* Handle unaligned loads and stores of integer registers.  */
20013   if (!done_p && TARGET_POWERPC64
20014       && reg_class_to_reg_type[(int)rclass] == GPR_REG_TYPE
20015       && memory_p
20016       && GET_MODE_SIZE (GET_MODE (x)) >= UNITS_PER_WORD)
20017     {
20018       rtx addr = XEXP (x, 0);
20019       rtx off = address_offset (addr);
20020
20021       if (off != NULL_RTX)
20022         {
20023           unsigned int extra = GET_MODE_SIZE (GET_MODE (x)) - UNITS_PER_WORD;
20024           unsigned HOST_WIDE_INT offset = INTVAL (off);
20025
20026           /* We need a secondary reload when our legitimate_address_p
20027              says the address is good (as otherwise the entire address
20028              will be reloaded), and the offset is not a multiple of
20029              four or we have an address wrap.  Address wrap will only
20030              occur for LO_SUMs since legitimate_offset_address_p
20031              rejects addresses for 16-byte mems that will wrap.  */
20032           if (GET_CODE (addr) == LO_SUM
20033               ? (1 /* legitimate_address_p allows any offset for lo_sum */
20034                  && ((offset & 3) != 0
20035                      || ((offset & 0xffff) ^ 0x8000) >= 0x10000 - extra))
20036               : (offset + 0x8000 < 0x10000 - extra /* legitimate_address_p */
20037                  && (offset & 3) != 0))
20038             {
20039               /* -m32 -mpowerpc64 needs to use a 32-bit scratch register.  */
20040               if (in_p)
20041                 sri->icode = ((TARGET_32BIT) ? CODE_FOR_reload_si_load
20042                               : CODE_FOR_reload_di_load);
20043               else
20044                 sri->icode = ((TARGET_32BIT) ? CODE_FOR_reload_si_store
20045                               : CODE_FOR_reload_di_store);
20046               sri->extra_cost = 2;
20047               ret = NO_REGS;
20048               done_p = true;
20049             }
20050           else
20051             default_p = true;
20052         }
20053       else
20054         default_p = true;
20055     }
20056
20057   if (!done_p && !TARGET_POWERPC64
20058       && reg_class_to_reg_type[(int)rclass] == GPR_REG_TYPE
20059       && memory_p
20060       && GET_MODE_SIZE (GET_MODE (x)) > UNITS_PER_WORD)
20061     {
20062       rtx addr = XEXP (x, 0);
20063       rtx off = address_offset (addr);
20064
20065       if (off != NULL_RTX)
20066         {
20067           unsigned int extra = GET_MODE_SIZE (GET_MODE (x)) - UNITS_PER_WORD;
20068           unsigned HOST_WIDE_INT offset = INTVAL (off);
20069
20070           /* We need a secondary reload when our legitimate_address_p
20071              says the address is good (as otherwise the entire address
20072              will be reloaded), and we have a wrap.
20073
20074              legitimate_lo_sum_address_p allows LO_SUM addresses to
20075              have any offset so test for wrap in the low 16 bits.
20076
20077              legitimate_offset_address_p checks for the range
20078              [-0x8000,0x7fff] for mode size of 8 and [-0x8000,0x7ff7]
20079              for mode size of 16.  We wrap at [0x7ffc,0x7fff] and
20080              [0x7ff4,0x7fff] respectively, so test for the
20081              intersection of these ranges, [0x7ffc,0x7fff] and
20082              [0x7ff4,0x7ff7] respectively.
20083
20084              Note that the address we see here may have been
20085              manipulated by legitimize_reload_address.  */
20086           if (GET_CODE (addr) == LO_SUM
20087               ? ((offset & 0xffff) ^ 0x8000) >= 0x10000 - extra
20088               : offset - (0x8000 - extra) < UNITS_PER_WORD)
20089             {
20090               if (in_p)
20091                 sri->icode = CODE_FOR_reload_si_load;
20092               else
20093                 sri->icode = CODE_FOR_reload_si_store;
20094               sri->extra_cost = 2;
20095               ret = NO_REGS;
20096               done_p = true;
20097             }
20098           else
20099             default_p = true;
20100         }
20101       else
20102         default_p = true;
20103     }
20104
20105   if (!done_p)
20106     default_p = true;
20107
20108   if (default_p)
20109     ret = default_secondary_reload (in_p, x, rclass, mode, sri);
20110
20111   gcc_assert (ret != ALL_REGS);
20112
20113   if (TARGET_DEBUG_ADDR)
20114     {
20115       fprintf (stderr,
20116                "\nrs6000_secondary_reload, return %s, in_p = %s, rclass = %s, "
20117                "mode = %s",
20118                reg_class_names[ret],
20119                in_p ? "true" : "false",
20120                reg_class_names[rclass],
20121                GET_MODE_NAME (mode));
20122
20123       if (reload_completed)
20124         fputs (", after reload", stderr);
20125
20126       if (!done_p)
20127         fputs (", done_p not set", stderr);
20128
20129       if (default_p)
20130         fputs (", default secondary reload", stderr);
20131
20132       if (sri->icode != CODE_FOR_nothing)
20133         fprintf (stderr, ", reload func = %s, extra cost = %d",
20134                  insn_data[sri->icode].name, sri->extra_cost);
20135
20136       else if (sri->extra_cost > 0)
20137         fprintf (stderr, ", extra cost = %d", sri->extra_cost);
20138
20139       fputs ("\n", stderr);
20140       debug_rtx (x);
20141     }
20142
20143   return ret;
20144 }
20145
20146 /* Better tracing for rs6000_secondary_reload_inner.  */
20147
20148 static void
20149 rs6000_secondary_reload_trace (int line, rtx reg, rtx mem, rtx scratch,
20150                                bool store_p)
20151 {
20152   rtx set, clobber;
20153
20154   gcc_assert (reg != NULL_RTX && mem != NULL_RTX && scratch != NULL_RTX);
20155
20156   fprintf (stderr, "rs6000_secondary_reload_inner:%d, type = %s\n", line,
20157            store_p ? "store" : "load");
20158
20159   if (store_p)
20160     set = gen_rtx_SET (mem, reg);
20161   else
20162     set = gen_rtx_SET (reg, mem);
20163
20164   clobber = gen_rtx_CLOBBER (VOIDmode, scratch);
20165   debug_rtx (gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, set, clobber)));
20166 }
20167
20168 static void rs6000_secondary_reload_fail (int, rtx, rtx, rtx, bool)
20169   ATTRIBUTE_NORETURN;
20170
20171 static void
20172 rs6000_secondary_reload_fail (int line, rtx reg, rtx mem, rtx scratch,
20173                               bool store_p)
20174 {
20175   rs6000_secondary_reload_trace (line, reg, mem, scratch, store_p);
20176   gcc_unreachable ();
20177 }
20178
20179 /* Fixup reload addresses for values in GPR, FPR, and VMX registers that have
20180    reload helper functions.  These were identified in
20181    rs6000_secondary_reload_memory, and if reload decided to use the secondary
20182    reload, it calls the insns:
20183         reload_<RELOAD:mode>_<P:mptrsize>_store
20184         reload_<RELOAD:mode>_<P:mptrsize>_load
20185
20186    which in turn calls this function, to do whatever is necessary to create
20187    valid addresses.  */
20188
20189 void
20190 rs6000_secondary_reload_inner (rtx reg, rtx mem, rtx scratch, bool store_p)
20191 {
20192   int regno = true_regnum (reg);
20193   machine_mode mode = GET_MODE (reg);
20194   addr_mask_type addr_mask;
20195   rtx addr;
20196   rtx new_addr;
20197   rtx op_reg, op0, op1;
20198   rtx and_op;
20199   rtx cc_clobber;
20200   rtvec rv;
20201
20202   if (regno < 0 || regno >= FIRST_PSEUDO_REGISTER || !MEM_P (mem)
20203       || !base_reg_operand (scratch, GET_MODE (scratch)))
20204     rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
20205
20206   if (IN_RANGE (regno, FIRST_GPR_REGNO, LAST_GPR_REGNO))
20207     addr_mask = reg_addr[mode].addr_mask[RELOAD_REG_GPR];
20208
20209   else if (IN_RANGE (regno, FIRST_FPR_REGNO, LAST_FPR_REGNO))
20210     addr_mask = reg_addr[mode].addr_mask[RELOAD_REG_FPR];
20211
20212   else if (IN_RANGE (regno, FIRST_ALTIVEC_REGNO, LAST_ALTIVEC_REGNO))
20213     addr_mask = reg_addr[mode].addr_mask[RELOAD_REG_VMX];
20214
20215   else
20216     rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
20217
20218   /* Make sure the mode is valid in this register class.  */
20219   if ((addr_mask & RELOAD_REG_VALID) == 0)
20220     rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
20221
20222   if (TARGET_DEBUG_ADDR)
20223     rs6000_secondary_reload_trace (__LINE__, reg, mem, scratch, store_p);
20224
20225   new_addr = addr = XEXP (mem, 0);
20226   switch (GET_CODE (addr))
20227     {
20228       /* Does the register class support auto update forms for this mode?  If
20229          not, do the update now.  We don't need a scratch register, since the
20230          powerpc only supports PRE_INC, PRE_DEC, and PRE_MODIFY.  */
20231     case PRE_INC:
20232     case PRE_DEC:
20233       op_reg = XEXP (addr, 0);
20234       if (!base_reg_operand (op_reg, Pmode))
20235         rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
20236
20237       if ((addr_mask & RELOAD_REG_PRE_INCDEC) == 0)
20238         {
20239           emit_insn (gen_add2_insn (op_reg, GEN_INT (GET_MODE_SIZE (mode))));
20240           new_addr = op_reg;
20241         }
20242       break;
20243
20244     case PRE_MODIFY:
20245       op0 = XEXP (addr, 0);
20246       op1 = XEXP (addr, 1);
20247       if (!base_reg_operand (op0, Pmode)
20248           || GET_CODE (op1) != PLUS
20249           || !rtx_equal_p (op0, XEXP (op1, 0)))
20250         rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
20251
20252       if ((addr_mask & RELOAD_REG_PRE_MODIFY) == 0)
20253         {
20254           emit_insn (gen_rtx_SET (op0, op1));
20255           new_addr = reg;
20256         }
20257       break;
20258
20259       /* Do we need to simulate AND -16 to clear the bottom address bits used
20260          in VMX load/stores?  */
20261     case AND:
20262       op0 = XEXP (addr, 0);
20263       op1 = XEXP (addr, 1);
20264       if ((addr_mask & RELOAD_REG_AND_M16) == 0)
20265         {
20266           if (REG_P (op0) || GET_CODE (op0) == SUBREG)
20267             op_reg = op0;
20268
20269           else if (GET_CODE (op1) == PLUS)
20270             {
20271               emit_insn (gen_rtx_SET (scratch, op1));
20272               op_reg = scratch;
20273             }
20274
20275           else
20276             rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
20277
20278           and_op = gen_rtx_AND (GET_MODE (scratch), op_reg, op1);
20279           cc_clobber = gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (CCmode));
20280           rv = gen_rtvec (2, gen_rtx_SET (scratch, and_op), cc_clobber);
20281           emit_insn (gen_rtx_PARALLEL (VOIDmode, rv));
20282           new_addr = scratch;
20283         }
20284       break;
20285
20286       /* If this is an indirect address, make sure it is a base register.  */
20287     case REG:
20288     case SUBREG:
20289       if (!base_reg_operand (addr, GET_MODE (addr)))
20290         {
20291           emit_insn (gen_rtx_SET (scratch, addr));
20292           new_addr = scratch;
20293         }
20294       break;
20295
20296       /* If this is an indexed address, make sure the register class can handle
20297          indexed addresses for this mode.  */
20298     case PLUS:
20299       op0 = XEXP (addr, 0);
20300       op1 = XEXP (addr, 1);
20301       if (!base_reg_operand (op0, Pmode))
20302         rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
20303
20304       else if (int_reg_operand (op1, Pmode))
20305         {
20306           if ((addr_mask & RELOAD_REG_INDEXED) == 0)
20307             {
20308               emit_insn (gen_rtx_SET (scratch, addr));
20309               new_addr = scratch;
20310             }
20311         }
20312
20313       else if (mode_supports_vsx_dform_quad (mode) && CONST_INT_P (op1))
20314         {
20315           if (((addr_mask & RELOAD_REG_QUAD_OFFSET) == 0)
20316               || !quad_address_p (addr, mode, false))
20317             {
20318               emit_insn (gen_rtx_SET (scratch, addr));
20319               new_addr = scratch;
20320             }
20321         }
20322
20323       /* Make sure the register class can handle offset addresses.  */
20324       else if (rs6000_legitimate_offset_address_p (mode, addr, false, true))
20325         {
20326           if ((addr_mask & RELOAD_REG_OFFSET) == 0)
20327             {
20328               emit_insn (gen_rtx_SET (scratch, addr));
20329               new_addr = scratch;
20330             }
20331         }
20332
20333       else
20334         rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
20335
20336       break;
20337
20338     case LO_SUM:
20339       op0 = XEXP (addr, 0);
20340       op1 = XEXP (addr, 1);
20341       if (!base_reg_operand (op0, Pmode))
20342         rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
20343
20344       else if (int_reg_operand (op1, Pmode))
20345         {
20346           if ((addr_mask & RELOAD_REG_INDEXED) == 0)
20347             {
20348               emit_insn (gen_rtx_SET (scratch, addr));
20349               new_addr = scratch;
20350             }
20351         }
20352
20353       /* Quad offsets are restricted and can't handle normal addresses.  */
20354       else if (mode_supports_vsx_dform_quad (mode))
20355         {
20356           emit_insn (gen_rtx_SET (scratch, addr));
20357           new_addr = scratch;
20358         }
20359
20360       /* Make sure the register class can handle offset addresses.  */
20361       else if (legitimate_lo_sum_address_p (mode, addr, false))
20362         {
20363           if ((addr_mask & RELOAD_REG_OFFSET) == 0)
20364             {
20365               emit_insn (gen_rtx_SET (scratch, addr));
20366               new_addr = scratch;
20367             }
20368         }
20369
20370       else
20371         rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
20372
20373       break;
20374
20375     case SYMBOL_REF:
20376     case CONST:
20377     case LABEL_REF:
20378       rs6000_emit_move (scratch, addr, Pmode);
20379       new_addr = scratch;
20380       break;
20381
20382     default:
20383       rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
20384     }
20385
20386   /* Adjust the address if it changed.  */
20387   if (addr != new_addr)
20388     {
20389       mem = replace_equiv_address_nv (mem, new_addr);
20390       if (TARGET_DEBUG_ADDR)
20391         fprintf (stderr, "\nrs6000_secondary_reload_inner, mem adjusted.\n");
20392     }
20393
20394   /* Now create the move.  */
20395   if (store_p)
20396     emit_insn (gen_rtx_SET (mem, reg));
20397   else
20398     emit_insn (gen_rtx_SET (reg, mem));
20399
20400   return;
20401 }
20402
20403 /* Convert reloads involving 64-bit gprs and misaligned offset
20404    addressing, or multiple 32-bit gprs and offsets that are too large,
20405    to use indirect addressing.  */
20406
20407 void
20408 rs6000_secondary_reload_gpr (rtx reg, rtx mem, rtx scratch, bool store_p)
20409 {
20410   int regno = true_regnum (reg);
20411   enum reg_class rclass;
20412   rtx addr;
20413   rtx scratch_or_premodify = scratch;
20414
20415   if (TARGET_DEBUG_ADDR)
20416     {
20417       fprintf (stderr, "\nrs6000_secondary_reload_gpr, type = %s\n",
20418                store_p ? "store" : "load");
20419       fprintf (stderr, "reg:\n");
20420       debug_rtx (reg);
20421       fprintf (stderr, "mem:\n");
20422       debug_rtx (mem);
20423       fprintf (stderr, "scratch:\n");
20424       debug_rtx (scratch);
20425     }
20426
20427   gcc_assert (regno >= 0 && regno < FIRST_PSEUDO_REGISTER);
20428   gcc_assert (GET_CODE (mem) == MEM);
20429   rclass = REGNO_REG_CLASS (regno);
20430   gcc_assert (rclass == GENERAL_REGS || rclass == BASE_REGS);
20431   addr = XEXP (mem, 0);
20432
20433   if (GET_CODE (addr) == PRE_MODIFY)
20434     {
20435       gcc_assert (REG_P (XEXP (addr, 0))
20436                   && GET_CODE (XEXP (addr, 1)) == PLUS
20437                   && XEXP (XEXP (addr, 1), 0) == XEXP (addr, 0));
20438       scratch_or_premodify = XEXP (addr, 0);
20439       if (!HARD_REGISTER_P (scratch_or_premodify))
20440         /* If we have a pseudo here then reload will have arranged
20441            to have it replaced, but only in the original insn.
20442            Use the replacement here too.  */
20443         scratch_or_premodify = find_replacement (&XEXP (addr, 0));
20444
20445       /* RTL emitted by rs6000_secondary_reload_gpr uses RTL
20446          expressions from the original insn, without unsharing them.
20447          Any RTL that points into the original insn will of course
20448          have register replacements applied.  That is why we don't
20449          need to look for replacements under the PLUS.  */
20450       addr = XEXP (addr, 1);
20451     }
20452   gcc_assert (GET_CODE (addr) == PLUS || GET_CODE (addr) == LO_SUM);
20453
20454   rs6000_emit_move (scratch_or_premodify, addr, Pmode);
20455
20456   mem = replace_equiv_address_nv (mem, scratch_or_premodify);
20457
20458   /* Now create the move.  */
20459   if (store_p)
20460     emit_insn (gen_rtx_SET (mem, reg));
20461   else
20462     emit_insn (gen_rtx_SET (reg, mem));
20463
20464   return;
20465 }
20466
20467 /* Given an rtx X being reloaded into a reg required to be
20468    in class CLASS, return the class of reg to actually use.
20469    In general this is just CLASS; but on some machines
20470    in some cases it is preferable to use a more restrictive class.
20471
20472    On the RS/6000, we have to return NO_REGS when we want to reload a
20473    floating-point CONST_DOUBLE to force it to be copied to memory.
20474
20475    We also don't want to reload integer values into floating-point
20476    registers if we can at all help it.  In fact, this can
20477    cause reload to die, if it tries to generate a reload of CTR
20478    into a FP register and discovers it doesn't have the memory location
20479    required.
20480
20481    ??? Would it be a good idea to have reload do the converse, that is
20482    try to reload floating modes into FP registers if possible?
20483  */
20484
20485 static enum reg_class
20486 rs6000_preferred_reload_class (rtx x, enum reg_class rclass)
20487 {
20488   machine_mode mode = GET_MODE (x);
20489   bool is_constant = CONSTANT_P (x);
20490
20491   /* If a mode can't go in FPR/ALTIVEC/VSX registers, don't return a preferred
20492      reload class for it.  */
20493   if ((rclass == ALTIVEC_REGS || rclass == VSX_REGS)
20494       && (reg_addr[mode].addr_mask[RELOAD_REG_VMX] & RELOAD_REG_VALID) == 0)
20495     return NO_REGS;
20496
20497   if ((rclass == FLOAT_REGS || rclass == VSX_REGS)
20498       && (reg_addr[mode].addr_mask[RELOAD_REG_FPR] & RELOAD_REG_VALID) == 0)
20499     return NO_REGS;
20500
20501   /* For VSX, see if we should prefer FLOAT_REGS or ALTIVEC_REGS.  Do not allow
20502      the reloading of address expressions using PLUS into floating point
20503      registers.  */
20504   if (TARGET_VSX && VSX_REG_CLASS_P (rclass) && GET_CODE (x) != PLUS)
20505     {
20506       if (is_constant)
20507         {
20508           /* Zero is always allowed in all VSX registers.  */
20509           if (x == CONST0_RTX (mode))
20510             return rclass;
20511
20512           /* If this is a vector constant that can be formed with a few Altivec
20513              instructions, we want altivec registers.  */
20514           if (GET_CODE (x) == CONST_VECTOR && easy_vector_constant (x, mode))
20515             return ALTIVEC_REGS;
20516
20517           /* If this is an integer constant that can easily be loaded into
20518              vector registers, allow it.  */
20519           if (CONST_INT_P (x))
20520             {
20521               HOST_WIDE_INT value = INTVAL (x);
20522
20523               /* ISA 2.07 can generate -1 in all registers with XXLORC.  ISA
20524                  2.06 can generate it in the Altivec registers with
20525                  VSPLTI<x>.  */
20526               if (value == -1)
20527                 {
20528                   if (TARGET_P8_VECTOR)
20529                     return rclass;
20530                   else if (rclass == ALTIVEC_REGS || rclass == VSX_REGS)
20531                     return ALTIVEC_REGS;
20532                   else
20533                     return NO_REGS;
20534                 }
20535
20536               /* ISA 3.0 can load -128..127 using the XXSPLTIB instruction and
20537                  a sign extend in the Altivec registers.  */
20538               if (IN_RANGE (value, -128, 127) && TARGET_P9_VECTOR
20539                   && (rclass == ALTIVEC_REGS || rclass == VSX_REGS))
20540                 return ALTIVEC_REGS;
20541             }
20542
20543           /* Force constant to memory.  */
20544           return NO_REGS;
20545         }
20546
20547       /* D-form addressing can easily reload the value.  */
20548       if (mode_supports_vmx_dform (mode)
20549           || mode_supports_vsx_dform_quad (mode))
20550         return rclass;
20551
20552       /* If this is a scalar floating point value and we don't have D-form
20553          addressing, prefer the traditional floating point registers so that we
20554          can use D-form (register+offset) addressing.  */
20555       if (rclass == VSX_REGS
20556           && (mode == SFmode || GET_MODE_SIZE (mode) == 8))
20557         return FLOAT_REGS;
20558
20559       /* Prefer the Altivec registers if Altivec is handling the vector
20560          operations (i.e. V16QI, V8HI, and V4SI), or if we prefer Altivec
20561          loads.  */
20562       if (VECTOR_UNIT_ALTIVEC_P (mode) || VECTOR_MEM_ALTIVEC_P (mode)
20563           || mode == V1TImode)
20564         return ALTIVEC_REGS;
20565
20566       return rclass;
20567     }
20568
20569   if (is_constant || GET_CODE (x) == PLUS)
20570     {
20571       if (reg_class_subset_p (GENERAL_REGS, rclass))
20572         return GENERAL_REGS;
20573       if (reg_class_subset_p (BASE_REGS, rclass))
20574         return BASE_REGS;
20575       return NO_REGS;
20576     }
20577
20578   if (GET_MODE_CLASS (mode) == MODE_INT && rclass == NON_SPECIAL_REGS)
20579     return GENERAL_REGS;
20580
20581   return rclass;
20582 }
20583
20584 /* Debug version of rs6000_preferred_reload_class.  */
20585 static enum reg_class
20586 rs6000_debug_preferred_reload_class (rtx x, enum reg_class rclass)
20587 {
20588   enum reg_class ret = rs6000_preferred_reload_class (x, rclass);
20589
20590   fprintf (stderr,
20591            "\nrs6000_preferred_reload_class, return %s, rclass = %s, "
20592            "mode = %s, x:\n",
20593            reg_class_names[ret], reg_class_names[rclass],
20594            GET_MODE_NAME (GET_MODE (x)));
20595   debug_rtx (x);
20596
20597   return ret;
20598 }
20599
20600 /* If we are copying between FP or AltiVec registers and anything else, we need
20601    a memory location.  The exception is when we are targeting ppc64 and the
20602    move to/from fpr to gpr instructions are available.  Also, under VSX, you
20603    can copy vector registers from the FP register set to the Altivec register
20604    set and vice versa.  */
20605
20606 static bool
20607 rs6000_secondary_memory_needed (machine_mode mode,
20608                                 reg_class_t from_class,
20609                                 reg_class_t to_class)
20610 {
20611   enum rs6000_reg_type from_type, to_type;
20612   bool altivec_p = ((from_class == ALTIVEC_REGS)
20613                     || (to_class == ALTIVEC_REGS));
20614
20615   /* If a simple/direct move is available, we don't need secondary memory  */
20616   from_type = reg_class_to_reg_type[(int)from_class];
20617   to_type = reg_class_to_reg_type[(int)to_class];
20618
20619   if (rs6000_secondary_reload_move (to_type, from_type, mode,
20620                                     (secondary_reload_info *)0, altivec_p))
20621     return false;
20622
20623   /* If we have a floating point or vector register class, we need to use
20624      memory to transfer the data.  */
20625   if (IS_FP_VECT_REG_TYPE (from_type) || IS_FP_VECT_REG_TYPE (to_type))
20626     return true;
20627
20628   return false;
20629 }
20630
20631 /* Debug version of rs6000_secondary_memory_needed.  */
20632 static bool
20633 rs6000_debug_secondary_memory_needed (machine_mode mode,
20634                                       reg_class_t from_class,
20635                                       reg_class_t to_class)
20636 {
20637   bool ret = rs6000_secondary_memory_needed (mode, from_class, to_class);
20638
20639   fprintf (stderr,
20640            "rs6000_secondary_memory_needed, return: %s, from_class = %s, "
20641            "to_class = %s, mode = %s\n",
20642            ret ? "true" : "false",
20643            reg_class_names[from_class],
20644            reg_class_names[to_class],
20645            GET_MODE_NAME (mode));
20646
20647   return ret;
20648 }
20649
20650 /* Return the register class of a scratch register needed to copy IN into
20651    or out of a register in RCLASS in MODE.  If it can be done directly,
20652    NO_REGS is returned.  */
20653
20654 static enum reg_class
20655 rs6000_secondary_reload_class (enum reg_class rclass, machine_mode mode,
20656                                rtx in)
20657 {
20658   int regno;
20659
20660   if (TARGET_ELF || (DEFAULT_ABI == ABI_DARWIN
20661 #if TARGET_MACHO
20662                      && MACHOPIC_INDIRECT
20663 #endif
20664                      ))
20665     {
20666       /* We cannot copy a symbolic operand directly into anything
20667          other than BASE_REGS for TARGET_ELF.  So indicate that a
20668          register from BASE_REGS is needed as an intermediate
20669          register.
20670
20671          On Darwin, pic addresses require a load from memory, which
20672          needs a base register.  */
20673       if (rclass != BASE_REGS
20674           && (GET_CODE (in) == SYMBOL_REF
20675               || GET_CODE (in) == HIGH
20676               || GET_CODE (in) == LABEL_REF
20677               || GET_CODE (in) == CONST))
20678         return BASE_REGS;
20679     }
20680
20681   if (GET_CODE (in) == REG)
20682     {
20683       regno = REGNO (in);
20684       if (regno >= FIRST_PSEUDO_REGISTER)
20685         {
20686           regno = true_regnum (in);
20687           if (regno >= FIRST_PSEUDO_REGISTER)
20688             regno = -1;
20689         }
20690     }
20691   else if (GET_CODE (in) == SUBREG)
20692     {
20693       regno = true_regnum (in);
20694       if (regno >= FIRST_PSEUDO_REGISTER)
20695         regno = -1;
20696     }
20697   else
20698     regno = -1;
20699
20700   /* If we have VSX register moves, prefer moving scalar values between
20701      Altivec registers and GPR by going via an FPR (and then via memory)
20702      instead of reloading the secondary memory address for Altivec moves.  */
20703   if (TARGET_VSX
20704       && GET_MODE_SIZE (mode) < 16
20705       && !mode_supports_vmx_dform (mode)
20706       && (((rclass == GENERAL_REGS || rclass == BASE_REGS)
20707            && (regno >= 0 && ALTIVEC_REGNO_P (regno)))
20708           || ((rclass == VSX_REGS || rclass == ALTIVEC_REGS)
20709               && (regno >= 0 && INT_REGNO_P (regno)))))
20710     return FLOAT_REGS;
20711
20712   /* We can place anything into GENERAL_REGS and can put GENERAL_REGS
20713      into anything.  */
20714   if (rclass == GENERAL_REGS || rclass == BASE_REGS
20715       || (regno >= 0 && INT_REGNO_P (regno)))
20716     return NO_REGS;
20717
20718   /* Constants, memory, and VSX registers can go into VSX registers (both the
20719      traditional floating point and the altivec registers).  */
20720   if (rclass == VSX_REGS
20721       && (regno == -1 || VSX_REGNO_P (regno)))
20722     return NO_REGS;
20723
20724   /* Constants, memory, and FP registers can go into FP registers.  */
20725   if ((regno == -1 || FP_REGNO_P (regno))
20726       && (rclass == FLOAT_REGS || rclass == NON_SPECIAL_REGS))
20727     return (mode != SDmode || lra_in_progress) ? NO_REGS : GENERAL_REGS;
20728
20729   /* Memory, and AltiVec registers can go into AltiVec registers.  */
20730   if ((regno == -1 || ALTIVEC_REGNO_P (regno))
20731       && rclass == ALTIVEC_REGS)
20732     return NO_REGS;
20733
20734   /* We can copy among the CR registers.  */
20735   if ((rclass == CR_REGS || rclass == CR0_REGS)
20736       && regno >= 0 && CR_REGNO_P (regno))
20737     return NO_REGS;
20738
20739   /* Otherwise, we need GENERAL_REGS.  */
20740   return GENERAL_REGS;
20741 }
20742
20743 /* Debug version of rs6000_secondary_reload_class.  */
20744 static enum reg_class
20745 rs6000_debug_secondary_reload_class (enum reg_class rclass,
20746                                      machine_mode mode, rtx in)
20747 {
20748   enum reg_class ret = rs6000_secondary_reload_class (rclass, mode, in);
20749   fprintf (stderr,
20750            "\nrs6000_secondary_reload_class, return %s, rclass = %s, "
20751            "mode = %s, input rtx:\n",
20752            reg_class_names[ret], reg_class_names[rclass],
20753            GET_MODE_NAME (mode));
20754   debug_rtx (in);
20755
20756   return ret;
20757 }
20758
20759 /* Implement TARGET_CAN_CHANGE_MODE_CLASS.  */
20760
20761 static bool
20762 rs6000_can_change_mode_class (machine_mode from,
20763                               machine_mode to,
20764                               reg_class_t rclass)
20765 {
20766   unsigned from_size = GET_MODE_SIZE (from);
20767   unsigned to_size = GET_MODE_SIZE (to);
20768
20769   if (from_size != to_size)
20770     {
20771       enum reg_class xclass = (TARGET_VSX) ? VSX_REGS : FLOAT_REGS;
20772
20773       if (reg_classes_intersect_p (xclass, rclass))
20774         {
20775           unsigned to_nregs = hard_regno_nregs (FIRST_FPR_REGNO, to);
20776           unsigned from_nregs = hard_regno_nregs (FIRST_FPR_REGNO, from);
20777           bool to_float128_vector_p = FLOAT128_VECTOR_P (to);
20778           bool from_float128_vector_p = FLOAT128_VECTOR_P (from);
20779
20780           /* Don't allow 64-bit types to overlap with 128-bit types that take a
20781              single register under VSX because the scalar part of the register
20782              is in the upper 64-bits, and not the lower 64-bits.  Types like
20783              TFmode/TDmode that take 2 scalar register can overlap.  128-bit
20784              IEEE floating point can't overlap, and neither can small
20785              values.  */
20786
20787           if (to_float128_vector_p && from_float128_vector_p)
20788             return true;
20789
20790           else if (to_float128_vector_p || from_float128_vector_p)
20791             return false;
20792
20793           /* TDmode in floating-mode registers must always go into a register
20794              pair with the most significant word in the even-numbered register
20795              to match ISA requirements.  In little-endian mode, this does not
20796              match subreg numbering, so we cannot allow subregs.  */
20797           if (!BYTES_BIG_ENDIAN && (to == TDmode || from == TDmode))
20798             return false;
20799
20800           if (from_size < 8 || to_size < 8)
20801             return false;
20802
20803           if (from_size == 8 && (8 * to_nregs) != to_size)
20804             return false;
20805
20806           if (to_size == 8 && (8 * from_nregs) != from_size)
20807             return false;
20808
20809           return true;
20810         }
20811       else
20812         return true;
20813     }
20814
20815   /* Since the VSX register set includes traditional floating point registers
20816      and altivec registers, just check for the size being different instead of
20817      trying to check whether the modes are vector modes.  Otherwise it won't
20818      allow say DF and DI to change classes.  For types like TFmode and TDmode
20819      that take 2 64-bit registers, rather than a single 128-bit register, don't
20820      allow subregs of those types to other 128 bit types.  */
20821   if (TARGET_VSX && VSX_REG_CLASS_P (rclass))
20822     {
20823       unsigned num_regs = (from_size + 15) / 16;
20824       if (hard_regno_nregs (FIRST_FPR_REGNO, to) > num_regs
20825           || hard_regno_nregs (FIRST_FPR_REGNO, from) > num_regs)
20826         return false;
20827
20828       return (from_size == 8 || from_size == 16);
20829     }
20830
20831   if (TARGET_ALTIVEC && rclass == ALTIVEC_REGS
20832       && (ALTIVEC_VECTOR_MODE (from) + ALTIVEC_VECTOR_MODE (to)) == 1)
20833     return false;
20834
20835   return true;
20836 }
20837
20838 /* Debug version of rs6000_can_change_mode_class.  */
20839 static bool
20840 rs6000_debug_can_change_mode_class (machine_mode from,
20841                                     machine_mode to,
20842                                     reg_class_t rclass)
20843 {
20844   bool ret = rs6000_can_change_mode_class (from, to, rclass);
20845
20846   fprintf (stderr,
20847            "rs6000_can_change_mode_class, return %s, from = %s, "
20848            "to = %s, rclass = %s\n",
20849            ret ? "true" : "false",
20850            GET_MODE_NAME (from), GET_MODE_NAME (to),
20851            reg_class_names[rclass]);
20852
20853   return ret;
20854 }
20855 \f
20856 /* Return a string to do a move operation of 128 bits of data.  */
20857
20858 const char *
20859 rs6000_output_move_128bit (rtx operands[])
20860 {
20861   rtx dest = operands[0];
20862   rtx src = operands[1];
20863   machine_mode mode = GET_MODE (dest);
20864   int dest_regno;
20865   int src_regno;
20866   bool dest_gpr_p, dest_fp_p, dest_vmx_p, dest_vsx_p;
20867   bool src_gpr_p, src_fp_p, src_vmx_p, src_vsx_p;
20868
20869   if (REG_P (dest))
20870     {
20871       dest_regno = REGNO (dest);
20872       dest_gpr_p = INT_REGNO_P (dest_regno);
20873       dest_fp_p = FP_REGNO_P (dest_regno);
20874       dest_vmx_p = ALTIVEC_REGNO_P (dest_regno);
20875       dest_vsx_p = dest_fp_p | dest_vmx_p;
20876     }
20877   else
20878     {
20879       dest_regno = -1;
20880       dest_gpr_p = dest_fp_p = dest_vmx_p = dest_vsx_p = false;
20881     }
20882
20883   if (REG_P (src))
20884     {
20885       src_regno = REGNO (src);
20886       src_gpr_p = INT_REGNO_P (src_regno);
20887       src_fp_p = FP_REGNO_P (src_regno);
20888       src_vmx_p = ALTIVEC_REGNO_P (src_regno);
20889       src_vsx_p = src_fp_p | src_vmx_p;
20890     }
20891   else
20892     {
20893       src_regno = -1;
20894       src_gpr_p = src_fp_p = src_vmx_p = src_vsx_p = false;
20895     }
20896
20897   /* Register moves.  */
20898   if (dest_regno >= 0 && src_regno >= 0)
20899     {
20900       if (dest_gpr_p)
20901         {
20902           if (src_gpr_p)
20903             return "#";
20904
20905           if (TARGET_DIRECT_MOVE_128 && src_vsx_p)
20906             return (WORDS_BIG_ENDIAN
20907                     ? "mfvsrd %0,%x1\n\tmfvsrld %L0,%x1"
20908                     : "mfvsrd %L0,%x1\n\tmfvsrld %0,%x1");
20909
20910           else if (TARGET_VSX && TARGET_DIRECT_MOVE && src_vsx_p)
20911             return "#";
20912         }
20913
20914       else if (TARGET_VSX && dest_vsx_p)
20915         {
20916           if (src_vsx_p)
20917             return "xxlor %x0,%x1,%x1";
20918
20919           else if (TARGET_DIRECT_MOVE_128 && src_gpr_p)
20920             return (WORDS_BIG_ENDIAN
20921                     ? "mtvsrdd %x0,%1,%L1"
20922                     : "mtvsrdd %x0,%L1,%1");
20923
20924           else if (TARGET_DIRECT_MOVE && src_gpr_p)
20925             return "#";
20926         }
20927
20928       else if (TARGET_ALTIVEC && dest_vmx_p && src_vmx_p)
20929         return "vor %0,%1,%1";
20930
20931       else if (dest_fp_p && src_fp_p)
20932         return "#";
20933     }
20934
20935   /* Loads.  */
20936   else if (dest_regno >= 0 && MEM_P (src))
20937     {
20938       if (dest_gpr_p)
20939         {
20940           if (TARGET_QUAD_MEMORY && quad_load_store_p (dest, src))
20941             return "lq %0,%1";
20942           else
20943             return "#";
20944         }
20945
20946       else if (TARGET_ALTIVEC && dest_vmx_p
20947                && altivec_indexed_or_indirect_operand (src, mode))
20948         return "lvx %0,%y1";
20949
20950       else if (TARGET_VSX && dest_vsx_p)
20951         {
20952           if (mode_supports_vsx_dform_quad (mode)
20953               && quad_address_p (XEXP (src, 0), mode, true))
20954             return "lxv %x0,%1";
20955
20956           else if (TARGET_P9_VECTOR)
20957             return "lxvx %x0,%y1";
20958
20959           else if (mode == V16QImode || mode == V8HImode || mode == V4SImode)
20960             return "lxvw4x %x0,%y1";
20961
20962           else
20963             return "lxvd2x %x0,%y1";
20964         }
20965
20966       else if (TARGET_ALTIVEC && dest_vmx_p)
20967         return "lvx %0,%y1";
20968
20969       else if (dest_fp_p)
20970         return "#";
20971     }
20972
20973   /* Stores.  */
20974   else if (src_regno >= 0 && MEM_P (dest))
20975     {
20976       if (src_gpr_p)
20977         {
20978           if (TARGET_QUAD_MEMORY && quad_load_store_p (dest, src))
20979             return "stq %1,%0";
20980           else
20981             return "#";
20982         }
20983
20984       else if (TARGET_ALTIVEC && src_vmx_p
20985                && altivec_indexed_or_indirect_operand (src, mode))
20986         return "stvx %1,%y0";
20987
20988       else if (TARGET_VSX && src_vsx_p)
20989         {
20990           if (mode_supports_vsx_dform_quad (mode)
20991               && quad_address_p (XEXP (dest, 0), mode, true))
20992             return "stxv %x1,%0";
20993
20994           else if (TARGET_P9_VECTOR)
20995             return "stxvx %x1,%y0";
20996
20997           else if (mode == V16QImode || mode == V8HImode || mode == V4SImode)
20998             return "stxvw4x %x1,%y0";
20999
21000           else
21001             return "stxvd2x %x1,%y0";
21002         }
21003
21004       else if (TARGET_ALTIVEC && src_vmx_p)
21005         return "stvx %1,%y0";
21006
21007       else if (src_fp_p)
21008         return "#";
21009     }
21010
21011   /* Constants.  */
21012   else if (dest_regno >= 0
21013            && (GET_CODE (src) == CONST_INT
21014                || GET_CODE (src) == CONST_WIDE_INT
21015                || GET_CODE (src) == CONST_DOUBLE
21016                || GET_CODE (src) == CONST_VECTOR))
21017     {
21018       if (dest_gpr_p)
21019         return "#";
21020
21021       else if ((dest_vmx_p && TARGET_ALTIVEC)
21022                || (dest_vsx_p && TARGET_VSX))
21023         return output_vec_const_move (operands);
21024     }
21025
21026   fatal_insn ("Bad 128-bit move", gen_rtx_SET (dest, src));
21027 }
21028
21029 /* Validate a 128-bit move.  */
21030 bool
21031 rs6000_move_128bit_ok_p (rtx operands[])
21032 {
21033   machine_mode mode = GET_MODE (operands[0]);
21034   return (gpc_reg_operand (operands[0], mode)
21035           || gpc_reg_operand (operands[1], mode));
21036 }
21037
21038 /* Return true if a 128-bit move needs to be split.  */
21039 bool
21040 rs6000_split_128bit_ok_p (rtx operands[])
21041 {
21042   if (!reload_completed)
21043     return false;
21044
21045   if (!gpr_or_gpr_p (operands[0], operands[1]))
21046     return false;
21047
21048   if (quad_load_store_p (operands[0], operands[1]))
21049     return false;
21050
21051   return true;
21052 }
21053
21054 \f
21055 /* Given a comparison operation, return the bit number in CCR to test.  We
21056    know this is a valid comparison.
21057
21058    SCC_P is 1 if this is for an scc.  That means that %D will have been
21059    used instead of %C, so the bits will be in different places.
21060
21061    Return -1 if OP isn't a valid comparison for some reason.  */
21062
21063 int
21064 ccr_bit (rtx op, int scc_p)
21065 {
21066   enum rtx_code code = GET_CODE (op);
21067   machine_mode cc_mode;
21068   int cc_regnum;
21069   int base_bit;
21070   rtx reg;
21071
21072   if (!COMPARISON_P (op))
21073     return -1;
21074
21075   reg = XEXP (op, 0);
21076
21077   gcc_assert (GET_CODE (reg) == REG && CR_REGNO_P (REGNO (reg)));
21078
21079   cc_mode = GET_MODE (reg);
21080   cc_regnum = REGNO (reg);
21081   base_bit = 4 * (cc_regnum - CR0_REGNO);
21082
21083   validate_condition_mode (code, cc_mode);
21084
21085   /* When generating a sCOND operation, only positive conditions are
21086      allowed.  */
21087   gcc_assert (!scc_p
21088               || code == EQ || code == GT || code == LT || code == UNORDERED
21089               || code == GTU || code == LTU);
21090
21091   switch (code)
21092     {
21093     case NE:
21094       return scc_p ? base_bit + 3 : base_bit + 2;
21095     case EQ:
21096       return base_bit + 2;
21097     case GT:  case GTU:  case UNLE:
21098       return base_bit + 1;
21099     case LT:  case LTU:  case UNGE:
21100       return base_bit;
21101     case ORDERED:  case UNORDERED:
21102       return base_bit + 3;
21103
21104     case GE:  case GEU:
21105       /* If scc, we will have done a cror to put the bit in the
21106          unordered position.  So test that bit.  For integer, this is ! LT
21107          unless this is an scc insn.  */
21108       return scc_p ? base_bit + 3 : base_bit;
21109
21110     case LE:  case LEU:
21111       return scc_p ? base_bit + 3 : base_bit + 1;
21112
21113     default:
21114       gcc_unreachable ();
21115     }
21116 }
21117 \f
21118 /* Return the GOT register.  */
21119
21120 rtx
21121 rs6000_got_register (rtx value ATTRIBUTE_UNUSED)
21122 {
21123   /* The second flow pass currently (June 1999) can't update
21124      regs_ever_live without disturbing other parts of the compiler, so
21125      update it here to make the prolog/epilogue code happy.  */
21126   if (!can_create_pseudo_p ()
21127       && !df_regs_ever_live_p (RS6000_PIC_OFFSET_TABLE_REGNUM))
21128     df_set_regs_ever_live (RS6000_PIC_OFFSET_TABLE_REGNUM, true);
21129
21130   crtl->uses_pic_offset_table = 1;
21131
21132   return pic_offset_table_rtx;
21133 }
21134 \f
21135 static rs6000_stack_t stack_info;
21136
21137 /* Function to init struct machine_function.
21138    This will be called, via a pointer variable,
21139    from push_function_context.  */
21140
21141 static struct machine_function *
21142 rs6000_init_machine_status (void)
21143 {
21144   stack_info.reload_completed = 0;
21145   return ggc_cleared_alloc<machine_function> ();
21146 }
21147 \f
21148 #define INT_P(X) (GET_CODE (X) == CONST_INT && GET_MODE (X) == VOIDmode)
21149
21150 /* Write out a function code label.  */
21151
21152 void
21153 rs6000_output_function_entry (FILE *file, const char *fname)
21154 {
21155   if (fname[0] != '.')
21156     {
21157       switch (DEFAULT_ABI)
21158         {
21159         default:
21160           gcc_unreachable ();
21161
21162         case ABI_AIX:
21163           if (DOT_SYMBOLS)
21164             putc ('.', file);
21165           else
21166             ASM_OUTPUT_INTERNAL_LABEL_PREFIX (file, "L.");
21167           break;
21168
21169         case ABI_ELFv2:
21170         case ABI_V4:
21171         case ABI_DARWIN:
21172           break;
21173         }
21174     }
21175
21176   RS6000_OUTPUT_BASENAME (file, fname);
21177 }
21178
21179 /* Print an operand.  Recognize special options, documented below.  */
21180
21181 #if TARGET_ELF
21182 #define SMALL_DATA_RELOC ((rs6000_sdata == SDATA_EABI) ? "sda21" : "sdarel")
21183 #define SMALL_DATA_REG ((rs6000_sdata == SDATA_EABI) ? 0 : 13)
21184 #else
21185 #define SMALL_DATA_RELOC "sda21"
21186 #define SMALL_DATA_REG 0
21187 #endif
21188
21189 void
21190 print_operand (FILE *file, rtx x, int code)
21191 {
21192   int i;
21193   unsigned HOST_WIDE_INT uval;
21194
21195   switch (code)
21196     {
21197       /* %a is output_address.  */
21198
21199       /* %c is output_addr_const if a CONSTANT_ADDRESS_P, otherwise
21200          output_operand.  */
21201
21202     case 'D':
21203       /* Like 'J' but get to the GT bit only.  */
21204       gcc_assert (REG_P (x));
21205
21206       /* Bit 1 is GT bit.  */
21207       i = 4 * (REGNO (x) - CR0_REGNO) + 1;
21208
21209       /* Add one for shift count in rlinm for scc.  */
21210       fprintf (file, "%d", i + 1);
21211       return;
21212
21213     case 'e':
21214       /* If the low 16 bits are 0, but some other bit is set, write 's'.  */
21215       if (! INT_P (x))
21216         {
21217           output_operand_lossage ("invalid %%e value");
21218           return;
21219         }
21220
21221       uval = INTVAL (x);
21222       if ((uval & 0xffff) == 0 && uval != 0)
21223         putc ('s', file);
21224       return;
21225
21226     case 'E':
21227       /* X is a CR register.  Print the number of the EQ bit of the CR */
21228       if (GET_CODE (x) != REG || ! CR_REGNO_P (REGNO (x)))
21229         output_operand_lossage ("invalid %%E value");
21230       else
21231         fprintf (file, "%d", 4 * (REGNO (x) - CR0_REGNO) + 2);
21232       return;
21233
21234     case 'f':
21235       /* X is a CR register.  Print the shift count needed to move it
21236          to the high-order four bits.  */
21237       if (GET_CODE (x) != REG || ! CR_REGNO_P (REGNO (x)))
21238         output_operand_lossage ("invalid %%f value");
21239       else
21240         fprintf (file, "%d", 4 * (REGNO (x) - CR0_REGNO));
21241       return;
21242
21243     case 'F':
21244       /* Similar, but print the count for the rotate in the opposite
21245          direction.  */
21246       if (GET_CODE (x) != REG || ! CR_REGNO_P (REGNO (x)))
21247         output_operand_lossage ("invalid %%F value");
21248       else
21249         fprintf (file, "%d", 32 - 4 * (REGNO (x) - CR0_REGNO));
21250       return;
21251
21252     case 'G':
21253       /* X is a constant integer.  If it is negative, print "m",
21254          otherwise print "z".  This is to make an aze or ame insn.  */
21255       if (GET_CODE (x) != CONST_INT)
21256         output_operand_lossage ("invalid %%G value");
21257       else if (INTVAL (x) >= 0)
21258         putc ('z', file);
21259       else
21260         putc ('m', file);
21261       return;
21262
21263     case 'h':
21264       /* If constant, output low-order five bits.  Otherwise, write
21265          normally.  */
21266       if (INT_P (x))
21267         fprintf (file, HOST_WIDE_INT_PRINT_DEC, INTVAL (x) & 31);
21268       else
21269         print_operand (file, x, 0);
21270       return;
21271
21272     case 'H':
21273       /* If constant, output low-order six bits.  Otherwise, write
21274          normally.  */
21275       if (INT_P (x))
21276         fprintf (file, HOST_WIDE_INT_PRINT_DEC, INTVAL (x) & 63);
21277       else
21278         print_operand (file, x, 0);
21279       return;
21280
21281     case 'I':
21282       /* Print `i' if this is a constant, else nothing.  */
21283       if (INT_P (x))
21284         putc ('i', file);
21285       return;
21286
21287     case 'j':
21288       /* Write the bit number in CCR for jump.  */
21289       i = ccr_bit (x, 0);
21290       if (i == -1)
21291         output_operand_lossage ("invalid %%j code");
21292       else
21293         fprintf (file, "%d", i);
21294       return;
21295
21296     case 'J':
21297       /* Similar, but add one for shift count in rlinm for scc and pass
21298          scc flag to `ccr_bit'.  */
21299       i = ccr_bit (x, 1);
21300       if (i == -1)
21301         output_operand_lossage ("invalid %%J code");
21302       else
21303         /* If we want bit 31, write a shift count of zero, not 32.  */
21304         fprintf (file, "%d", i == 31 ? 0 : i + 1);
21305       return;
21306
21307     case 'k':
21308       /* X must be a constant.  Write the 1's complement of the
21309          constant.  */
21310       if (! INT_P (x))
21311         output_operand_lossage ("invalid %%k value");
21312       else
21313         fprintf (file, HOST_WIDE_INT_PRINT_DEC, ~ INTVAL (x));
21314       return;
21315
21316     case 'K':
21317       /* X must be a symbolic constant on ELF.  Write an
21318          expression suitable for an 'addi' that adds in the low 16
21319          bits of the MEM.  */
21320       if (GET_CODE (x) == CONST)
21321         {
21322           if (GET_CODE (XEXP (x, 0)) != PLUS
21323               || (GET_CODE (XEXP (XEXP (x, 0), 0)) != SYMBOL_REF
21324                   && GET_CODE (XEXP (XEXP (x, 0), 0)) != LABEL_REF)
21325               || GET_CODE (XEXP (XEXP (x, 0), 1)) != CONST_INT)
21326             output_operand_lossage ("invalid %%K value");
21327         }
21328       print_operand_address (file, x);
21329       fputs ("@l", file);
21330       return;
21331
21332       /* %l is output_asm_label.  */
21333
21334     case 'L':
21335       /* Write second word of DImode or DFmode reference.  Works on register
21336          or non-indexed memory only.  */
21337       if (REG_P (x))
21338         fputs (reg_names[REGNO (x) + 1], file);
21339       else if (MEM_P (x))
21340         {
21341           machine_mode mode = GET_MODE (x);
21342           /* Handle possible auto-increment.  Since it is pre-increment and
21343              we have already done it, we can just use an offset of word.  */
21344           if (GET_CODE (XEXP (x, 0)) == PRE_INC
21345               || GET_CODE (XEXP (x, 0)) == PRE_DEC)
21346             output_address (mode, plus_constant (Pmode, XEXP (XEXP (x, 0), 0),
21347                                                  UNITS_PER_WORD));
21348           else if (GET_CODE (XEXP (x, 0)) == PRE_MODIFY)
21349             output_address (mode, plus_constant (Pmode, XEXP (XEXP (x, 0), 0),
21350                                                  UNITS_PER_WORD));
21351           else
21352             output_address (mode, XEXP (adjust_address_nv (x, SImode,
21353                                                            UNITS_PER_WORD),
21354                                   0));
21355
21356           if (small_data_operand (x, GET_MODE (x)))
21357             fprintf (file, "@%s(%s)", SMALL_DATA_RELOC,
21358                      reg_names[SMALL_DATA_REG]);
21359         }
21360       return;
21361
21362     case 'N': /* Unused */
21363       /* Write the number of elements in the vector times 4.  */
21364       if (GET_CODE (x) != PARALLEL)
21365         output_operand_lossage ("invalid %%N value");
21366       else
21367         fprintf (file, "%d", XVECLEN (x, 0) * 4);
21368       return;
21369
21370     case 'O': /* Unused */
21371       /* Similar, but subtract 1 first.  */
21372       if (GET_CODE (x) != PARALLEL)
21373         output_operand_lossage ("invalid %%O value");
21374       else
21375         fprintf (file, "%d", (XVECLEN (x, 0) - 1) * 4);
21376       return;
21377
21378     case 'p':
21379       /* X is a CONST_INT that is a power of two.  Output the logarithm.  */
21380       if (! INT_P (x)
21381           || INTVAL (x) < 0
21382           || (i = exact_log2 (INTVAL (x))) < 0)
21383         output_operand_lossage ("invalid %%p value");
21384       else
21385         fprintf (file, "%d", i);
21386       return;
21387
21388     case 'P':
21389       /* The operand must be an indirect memory reference.  The result
21390          is the register name.  */
21391       if (GET_CODE (x) != MEM || GET_CODE (XEXP (x, 0)) != REG
21392           || REGNO (XEXP (x, 0)) >= 32)
21393         output_operand_lossage ("invalid %%P value");
21394       else
21395         fputs (reg_names[REGNO (XEXP (x, 0))], file);
21396       return;
21397
21398     case 'q':
21399       /* This outputs the logical code corresponding to a boolean
21400          expression.  The expression may have one or both operands
21401          negated (if one, only the first one).  For condition register
21402          logical operations, it will also treat the negated
21403          CR codes as NOTs, but not handle NOTs of them.  */
21404       {
21405         const char *const *t = 0;
21406         const char *s;
21407         enum rtx_code code = GET_CODE (x);
21408         static const char * const tbl[3][3] = {
21409           { "and", "andc", "nor" },
21410           { "or", "orc", "nand" },
21411           { "xor", "eqv", "xor" } };
21412
21413         if (code == AND)
21414           t = tbl[0];
21415         else if (code == IOR)
21416           t = tbl[1];
21417         else if (code == XOR)
21418           t = tbl[2];
21419         else
21420           output_operand_lossage ("invalid %%q value");
21421
21422         if (GET_CODE (XEXP (x, 0)) != NOT)
21423           s = t[0];
21424         else
21425           {
21426             if (GET_CODE (XEXP (x, 1)) == NOT)
21427               s = t[2];
21428             else
21429               s = t[1];
21430           }
21431
21432         fputs (s, file);
21433       }
21434       return;
21435
21436     case 'Q':
21437       if (! TARGET_MFCRF)
21438         return;
21439       fputc (',', file);
21440       /* FALLTHRU */
21441
21442     case 'R':
21443       /* X is a CR register.  Print the mask for `mtcrf'.  */
21444       if (GET_CODE (x) != REG || ! CR_REGNO_P (REGNO (x)))
21445         output_operand_lossage ("invalid %%R value");
21446       else
21447         fprintf (file, "%d", 128 >> (REGNO (x) - CR0_REGNO));
21448       return;
21449
21450     case 's':
21451       /* Low 5 bits of 32 - value */
21452       if (! INT_P (x))
21453         output_operand_lossage ("invalid %%s value");
21454       else
21455         fprintf (file, HOST_WIDE_INT_PRINT_DEC, (32 - INTVAL (x)) & 31);
21456       return;
21457
21458     case 't':
21459       /* Like 'J' but get to the OVERFLOW/UNORDERED bit.  */
21460       gcc_assert (REG_P (x) && GET_MODE (x) == CCmode);
21461
21462       /* Bit 3 is OV bit.  */
21463       i = 4 * (REGNO (x) - CR0_REGNO) + 3;
21464
21465       /* If we want bit 31, write a shift count of zero, not 32.  */
21466       fprintf (file, "%d", i == 31 ? 0 : i + 1);
21467       return;
21468
21469     case 'T':
21470       /* Print the symbolic name of a branch target register.  */
21471       if (GET_CODE (x) != REG || (REGNO (x) != LR_REGNO
21472                                   && REGNO (x) != CTR_REGNO))
21473         output_operand_lossage ("invalid %%T value");
21474       else if (REGNO (x) == LR_REGNO)
21475         fputs ("lr", file);
21476       else
21477         fputs ("ctr", file);
21478       return;
21479
21480     case 'u':
21481       /* High-order or low-order 16 bits of constant, whichever is non-zero,
21482          for use in unsigned operand.  */
21483       if (! INT_P (x))
21484         {
21485           output_operand_lossage ("invalid %%u value");
21486           return;
21487         }
21488
21489       uval = INTVAL (x);
21490       if ((uval & 0xffff) == 0)
21491         uval >>= 16;
21492
21493       fprintf (file, HOST_WIDE_INT_PRINT_HEX, uval & 0xffff);
21494       return;
21495
21496     case 'v':
21497       /* High-order 16 bits of constant for use in signed operand.  */
21498       if (! INT_P (x))
21499         output_operand_lossage ("invalid %%v value");
21500       else
21501         fprintf (file, HOST_WIDE_INT_PRINT_HEX,
21502                  (INTVAL (x) >> 16) & 0xffff);
21503       return;
21504
21505     case 'U':
21506       /* Print `u' if this has an auto-increment or auto-decrement.  */
21507       if (MEM_P (x)
21508           && (GET_CODE (XEXP (x, 0)) == PRE_INC
21509               || GET_CODE (XEXP (x, 0)) == PRE_DEC
21510               || GET_CODE (XEXP (x, 0)) == PRE_MODIFY))
21511         putc ('u', file);
21512       return;
21513
21514     case 'V':
21515       /* Print the trap code for this operand.  */
21516       switch (GET_CODE (x))
21517         {
21518         case EQ:
21519           fputs ("eq", file);   /* 4 */
21520           break;
21521         case NE:
21522           fputs ("ne", file);   /* 24 */
21523           break;
21524         case LT:
21525           fputs ("lt", file);   /* 16 */
21526           break;
21527         case LE:
21528           fputs ("le", file);   /* 20 */
21529           break;
21530         case GT:
21531           fputs ("gt", file);   /* 8 */
21532           break;
21533         case GE:
21534           fputs ("ge", file);   /* 12 */
21535           break;
21536         case LTU:
21537           fputs ("llt", file);  /* 2 */
21538           break;
21539         case LEU:
21540           fputs ("lle", file);  /* 6 */
21541           break;
21542         case GTU:
21543           fputs ("lgt", file);  /* 1 */
21544           break;
21545         case GEU:
21546           fputs ("lge", file);  /* 5 */
21547           break;
21548         default:
21549           gcc_unreachable ();
21550         }
21551       break;
21552
21553     case 'w':
21554       /* If constant, low-order 16 bits of constant, signed.  Otherwise, write
21555          normally.  */
21556       if (INT_P (x))
21557         fprintf (file, HOST_WIDE_INT_PRINT_DEC,
21558                  ((INTVAL (x) & 0xffff) ^ 0x8000) - 0x8000);
21559       else
21560         print_operand (file, x, 0);
21561       return;
21562
21563     case 'x':
21564       /* X is a FPR or Altivec register used in a VSX context.  */
21565       if (GET_CODE (x) != REG || !VSX_REGNO_P (REGNO (x)))
21566         output_operand_lossage ("invalid %%x value");
21567       else
21568         {
21569           int reg = REGNO (x);
21570           int vsx_reg = (FP_REGNO_P (reg)
21571                          ? reg - 32
21572                          : reg - FIRST_ALTIVEC_REGNO + 32);
21573
21574 #ifdef TARGET_REGNAMES      
21575           if (TARGET_REGNAMES)
21576             fprintf (file, "%%vs%d", vsx_reg);
21577           else
21578 #endif
21579             fprintf (file, "%d", vsx_reg);
21580         }
21581       return;
21582
21583     case 'X':
21584       if (MEM_P (x)
21585           && (legitimate_indexed_address_p (XEXP (x, 0), 0)
21586               || (GET_CODE (XEXP (x, 0)) == PRE_MODIFY
21587                   && legitimate_indexed_address_p (XEXP (XEXP (x, 0), 1), 0))))
21588         putc ('x', file);
21589       return;
21590
21591     case 'Y':
21592       /* Like 'L', for third word of TImode/PTImode  */
21593       if (REG_P (x))
21594         fputs (reg_names[REGNO (x) + 2], file);
21595       else if (MEM_P (x))
21596         {
21597           machine_mode mode = GET_MODE (x);
21598           if (GET_CODE (XEXP (x, 0)) == PRE_INC
21599               || GET_CODE (XEXP (x, 0)) == PRE_DEC)
21600             output_address (mode, plus_constant (Pmode,
21601                                                  XEXP (XEXP (x, 0), 0), 8));
21602           else if (GET_CODE (XEXP (x, 0)) == PRE_MODIFY)
21603             output_address (mode, plus_constant (Pmode,
21604                                                  XEXP (XEXP (x, 0), 0), 8));
21605           else
21606             output_address (mode, XEXP (adjust_address_nv (x, SImode, 8), 0));
21607           if (small_data_operand (x, GET_MODE (x)))
21608             fprintf (file, "@%s(%s)", SMALL_DATA_RELOC,
21609                      reg_names[SMALL_DATA_REG]);
21610         }
21611       return;
21612
21613     case 'z':
21614       /* X is a SYMBOL_REF.  Write out the name preceded by a
21615          period and without any trailing data in brackets.  Used for function
21616          names.  If we are configured for System V (or the embedded ABI) on
21617          the PowerPC, do not emit the period, since those systems do not use
21618          TOCs and the like.  */
21619       gcc_assert (GET_CODE (x) == SYMBOL_REF);
21620
21621       /* For macho, check to see if we need a stub.  */
21622       if (TARGET_MACHO)
21623         {
21624           const char *name = XSTR (x, 0);
21625 #if TARGET_MACHO
21626           if (darwin_emit_branch_islands
21627               && MACHOPIC_INDIRECT
21628               && machopic_classify_symbol (x) == MACHOPIC_UNDEFINED_FUNCTION)
21629             name = machopic_indirection_name (x, /*stub_p=*/true);
21630 #endif
21631           assemble_name (file, name);
21632         }
21633       else if (!DOT_SYMBOLS)
21634         assemble_name (file, XSTR (x, 0));
21635       else
21636         rs6000_output_function_entry (file, XSTR (x, 0));
21637       return;
21638
21639     case 'Z':
21640       /* Like 'L', for last word of TImode/PTImode.  */
21641       if (REG_P (x))
21642         fputs (reg_names[REGNO (x) + 3], file);
21643       else if (MEM_P (x))
21644         {
21645           machine_mode mode = GET_MODE (x);
21646           if (GET_CODE (XEXP (x, 0)) == PRE_INC
21647               || GET_CODE (XEXP (x, 0)) == PRE_DEC)
21648             output_address (mode, plus_constant (Pmode,
21649                                                  XEXP (XEXP (x, 0), 0), 12));
21650           else if (GET_CODE (XEXP (x, 0)) == PRE_MODIFY)
21651             output_address (mode, plus_constant (Pmode,
21652                                                  XEXP (XEXP (x, 0), 0), 12));
21653           else
21654             output_address (mode, XEXP (adjust_address_nv (x, SImode, 12), 0));
21655           if (small_data_operand (x, GET_MODE (x)))
21656             fprintf (file, "@%s(%s)", SMALL_DATA_RELOC,
21657                      reg_names[SMALL_DATA_REG]);
21658         }
21659       return;
21660
21661       /* Print AltiVec memory operand.  */
21662     case 'y':
21663       {
21664         rtx tmp;
21665
21666         gcc_assert (MEM_P (x));
21667
21668         tmp = XEXP (x, 0);
21669
21670         if (VECTOR_MEM_ALTIVEC_OR_VSX_P (GET_MODE (x))
21671             && GET_CODE (tmp) == AND
21672             && GET_CODE (XEXP (tmp, 1)) == CONST_INT
21673             && INTVAL (XEXP (tmp, 1)) == -16)
21674           tmp = XEXP (tmp, 0);
21675         else if (VECTOR_MEM_VSX_P (GET_MODE (x))
21676                  && GET_CODE (tmp) == PRE_MODIFY)
21677           tmp = XEXP (tmp, 1);
21678         if (REG_P (tmp))
21679           fprintf (file, "0,%s", reg_names[REGNO (tmp)]);
21680         else
21681           {
21682             if (GET_CODE (tmp) != PLUS
21683                 || !REG_P (XEXP (tmp, 0))
21684                 || !REG_P (XEXP (tmp, 1)))
21685               {
21686                 output_operand_lossage ("invalid %%y value, try using the 'Z' constraint");
21687                 break;
21688               }
21689
21690             if (REGNO (XEXP (tmp, 0)) == 0)
21691               fprintf (file, "%s,%s", reg_names[ REGNO (XEXP (tmp, 1)) ],
21692                        reg_names[ REGNO (XEXP (tmp, 0)) ]);
21693             else
21694               fprintf (file, "%s,%s", reg_names[ REGNO (XEXP (tmp, 0)) ],
21695                        reg_names[ REGNO (XEXP (tmp, 1)) ]);
21696           }
21697         break;
21698       }
21699
21700     case 0:
21701       if (REG_P (x))
21702         fprintf (file, "%s", reg_names[REGNO (x)]);
21703       else if (MEM_P (x))
21704         {
21705           /* We need to handle PRE_INC and PRE_DEC here, since we need to
21706              know the width from the mode.  */
21707           if (GET_CODE (XEXP (x, 0)) == PRE_INC)
21708             fprintf (file, "%d(%s)", GET_MODE_SIZE (GET_MODE (x)),
21709                      reg_names[REGNO (XEXP (XEXP (x, 0), 0))]);
21710           else if (GET_CODE (XEXP (x, 0)) == PRE_DEC)
21711             fprintf (file, "%d(%s)", - GET_MODE_SIZE (GET_MODE (x)),
21712                      reg_names[REGNO (XEXP (XEXP (x, 0), 0))]);
21713           else if (GET_CODE (XEXP (x, 0)) == PRE_MODIFY)
21714             output_address (GET_MODE (x), XEXP (XEXP (x, 0), 1));
21715           else
21716             output_address (GET_MODE (x), XEXP (x, 0));
21717         }
21718       else
21719         {
21720           if (toc_relative_expr_p (x, false, &tocrel_base_oac, &tocrel_offset_oac))
21721             /* This hack along with a corresponding hack in
21722                rs6000_output_addr_const_extra arranges to output addends
21723                where the assembler expects to find them.  eg.
21724                (plus (unspec [(symbol_ref ("x")) (reg 2)] tocrel) 4)
21725                without this hack would be output as "x@toc+4".  We
21726                want "x+4@toc".  */
21727             output_addr_const (file, CONST_CAST_RTX (tocrel_base_oac));
21728           else
21729             output_addr_const (file, x);
21730         }
21731       return;
21732
21733     case '&':
21734       if (const char *name = get_some_local_dynamic_name ())
21735         assemble_name (file, name);
21736       else
21737         output_operand_lossage ("'%%&' used without any "
21738                                 "local dynamic TLS references");
21739       return;
21740
21741     default:
21742       output_operand_lossage ("invalid %%xn code");
21743     }
21744 }
21745 \f
21746 /* Print the address of an operand.  */
21747
21748 void
21749 print_operand_address (FILE *file, rtx x)
21750 {
21751   if (REG_P (x))
21752     fprintf (file, "0(%s)", reg_names[ REGNO (x) ]);
21753   else if (GET_CODE (x) == SYMBOL_REF || GET_CODE (x) == CONST
21754            || GET_CODE (x) == LABEL_REF)
21755     {
21756       output_addr_const (file, x);
21757       if (small_data_operand (x, GET_MODE (x)))
21758         fprintf (file, "@%s(%s)", SMALL_DATA_RELOC,
21759                  reg_names[SMALL_DATA_REG]);
21760       else
21761         gcc_assert (!TARGET_TOC);
21762     }
21763   else if (GET_CODE (x) == PLUS && REG_P (XEXP (x, 0))
21764            && REG_P (XEXP (x, 1)))
21765     {
21766       if (REGNO (XEXP (x, 0)) == 0)
21767         fprintf (file, "%s,%s", reg_names[ REGNO (XEXP (x, 1)) ],
21768                  reg_names[ REGNO (XEXP (x, 0)) ]);
21769       else
21770         fprintf (file, "%s,%s", reg_names[ REGNO (XEXP (x, 0)) ],
21771                  reg_names[ REGNO (XEXP (x, 1)) ]);
21772     }
21773   else if (GET_CODE (x) == PLUS && REG_P (XEXP (x, 0))
21774            && GET_CODE (XEXP (x, 1)) == CONST_INT)
21775     fprintf (file, HOST_WIDE_INT_PRINT_DEC "(%s)",
21776              INTVAL (XEXP (x, 1)), reg_names[ REGNO (XEXP (x, 0)) ]);
21777 #if TARGET_MACHO
21778   else if (GET_CODE (x) == LO_SUM && REG_P (XEXP (x, 0))
21779            && CONSTANT_P (XEXP (x, 1)))
21780     {
21781       fprintf (file, "lo16(");
21782       output_addr_const (file, XEXP (x, 1));
21783       fprintf (file, ")(%s)", reg_names[ REGNO (XEXP (x, 0)) ]);
21784     }
21785 #endif
21786 #if TARGET_ELF
21787   else if (GET_CODE (x) == LO_SUM && REG_P (XEXP (x, 0))
21788            && CONSTANT_P (XEXP (x, 1)))
21789     {
21790       output_addr_const (file, XEXP (x, 1));
21791       fprintf (file, "@l(%s)", reg_names[ REGNO (XEXP (x, 0)) ]);
21792     }
21793 #endif
21794   else if (toc_relative_expr_p (x, false, &tocrel_base_oac, &tocrel_offset_oac))
21795     {
21796       /* This hack along with a corresponding hack in
21797          rs6000_output_addr_const_extra arranges to output addends
21798          where the assembler expects to find them.  eg.
21799          (lo_sum (reg 9)
21800          .       (plus (unspec [(symbol_ref ("x")) (reg 2)] tocrel) 8))
21801          without this hack would be output as "x@toc+8@l(9)".  We
21802          want "x+8@toc@l(9)".  */
21803       output_addr_const (file, CONST_CAST_RTX (tocrel_base_oac));
21804       if (GET_CODE (x) == LO_SUM)
21805         fprintf (file, "@l(%s)", reg_names[REGNO (XEXP (x, 0))]);
21806       else
21807         fprintf (file, "(%s)", reg_names[REGNO (XVECEXP (tocrel_base_oac, 0, 1))]);
21808     }
21809   else
21810     gcc_unreachable ();
21811 }
21812 \f
21813 /* Implement TARGET_ASM_OUTPUT_ADDR_CONST_EXTRA.  */
21814
21815 static bool
21816 rs6000_output_addr_const_extra (FILE *file, rtx x)
21817 {
21818   if (GET_CODE (x) == UNSPEC)
21819     switch (XINT (x, 1))
21820       {
21821       case UNSPEC_TOCREL:
21822         gcc_checking_assert (GET_CODE (XVECEXP (x, 0, 0)) == SYMBOL_REF
21823                              && REG_P (XVECEXP (x, 0, 1))
21824                              && REGNO (XVECEXP (x, 0, 1)) == TOC_REGISTER);
21825         output_addr_const (file, XVECEXP (x, 0, 0));
21826         if (x == tocrel_base_oac && tocrel_offset_oac != const0_rtx)
21827           {
21828             if (INTVAL (tocrel_offset_oac) >= 0)
21829               fprintf (file, "+");
21830             output_addr_const (file, CONST_CAST_RTX (tocrel_offset_oac));
21831           }
21832         if (!TARGET_AIX || (TARGET_ELF && TARGET_MINIMAL_TOC))
21833           {
21834             putc ('-', file);
21835             assemble_name (file, toc_label_name);
21836             need_toc_init = 1;
21837           }
21838         else if (TARGET_ELF)
21839           fputs ("@toc", file);
21840         return true;
21841
21842 #if TARGET_MACHO
21843       case UNSPEC_MACHOPIC_OFFSET:
21844         output_addr_const (file, XVECEXP (x, 0, 0));
21845         putc ('-', file);
21846         machopic_output_function_base_name (file);
21847         return true;
21848 #endif
21849       }
21850   return false;
21851 }
21852 \f
21853 /* Target hook for assembling integer objects.  The PowerPC version has
21854    to handle fixup entries for relocatable code if RELOCATABLE_NEEDS_FIXUP
21855    is defined.  It also needs to handle DI-mode objects on 64-bit
21856    targets.  */
21857
21858 static bool
21859 rs6000_assemble_integer (rtx x, unsigned int size, int aligned_p)
21860 {
21861 #ifdef RELOCATABLE_NEEDS_FIXUP
21862   /* Special handling for SI values.  */
21863   if (RELOCATABLE_NEEDS_FIXUP && size == 4 && aligned_p)
21864     {
21865       static int recurse = 0;
21866
21867       /* For -mrelocatable, we mark all addresses that need to be fixed up in
21868          the .fixup section.  Since the TOC section is already relocated, we
21869          don't need to mark it here.  We used to skip the text section, but it
21870          should never be valid for relocated addresses to be placed in the text
21871          section.  */
21872       if (DEFAULT_ABI == ABI_V4
21873           && (TARGET_RELOCATABLE || flag_pic > 1)
21874           && in_section != toc_section
21875           && !recurse
21876           && !CONST_SCALAR_INT_P (x)
21877           && CONSTANT_P (x))
21878         {
21879           char buf[256];
21880
21881           recurse = 1;
21882           ASM_GENERATE_INTERNAL_LABEL (buf, "LCP", fixuplabelno);
21883           fixuplabelno++;
21884           ASM_OUTPUT_LABEL (asm_out_file, buf);
21885           fprintf (asm_out_file, "\t.long\t(");
21886           output_addr_const (asm_out_file, x);
21887           fprintf (asm_out_file, ")@fixup\n");
21888           fprintf (asm_out_file, "\t.section\t\".fixup\",\"aw\"\n");
21889           ASM_OUTPUT_ALIGN (asm_out_file, 2);
21890           fprintf (asm_out_file, "\t.long\t");
21891           assemble_name (asm_out_file, buf);
21892           fprintf (asm_out_file, "\n\t.previous\n");
21893           recurse = 0;
21894           return true;
21895         }
21896       /* Remove initial .'s to turn a -mcall-aixdesc function
21897          address into the address of the descriptor, not the function
21898          itself.  */
21899       else if (GET_CODE (x) == SYMBOL_REF
21900                && XSTR (x, 0)[0] == '.'
21901                && DEFAULT_ABI == ABI_AIX)
21902         {
21903           const char *name = XSTR (x, 0);
21904           while (*name == '.')
21905             name++;
21906
21907           fprintf (asm_out_file, "\t.long\t%s\n", name);
21908           return true;
21909         }
21910     }
21911 #endif /* RELOCATABLE_NEEDS_FIXUP */
21912   return default_assemble_integer (x, size, aligned_p);
21913 }
21914
21915 #if defined (HAVE_GAS_HIDDEN) && !TARGET_MACHO
21916 /* Emit an assembler directive to set symbol visibility for DECL to
21917    VISIBILITY_TYPE.  */
21918
21919 static void
21920 rs6000_assemble_visibility (tree decl, int vis)
21921 {
21922   if (TARGET_XCOFF)
21923     return;
21924
21925   /* Functions need to have their entry point symbol visibility set as
21926      well as their descriptor symbol visibility.  */
21927   if (DEFAULT_ABI == ABI_AIX
21928       && DOT_SYMBOLS
21929       && TREE_CODE (decl) == FUNCTION_DECL)
21930     {
21931       static const char * const visibility_types[] = {
21932         NULL, "protected", "hidden", "internal"
21933       };
21934
21935       const char *name, *type;
21936
21937       name = ((* targetm.strip_name_encoding)
21938               (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl))));
21939       type = visibility_types[vis];
21940
21941       fprintf (asm_out_file, "\t.%s\t%s\n", type, name);
21942       fprintf (asm_out_file, "\t.%s\t.%s\n", type, name);
21943     }
21944   else
21945     default_assemble_visibility (decl, vis);
21946 }
21947 #endif
21948 \f
21949 enum rtx_code
21950 rs6000_reverse_condition (machine_mode mode, enum rtx_code code)
21951 {
21952   /* Reversal of FP compares takes care -- an ordered compare
21953      becomes an unordered compare and vice versa.  */
21954   if (mode == CCFPmode
21955       && (!flag_finite_math_only
21956           || code == UNLT || code == UNLE || code == UNGT || code == UNGE
21957           || code == UNEQ || code == LTGT))
21958     return reverse_condition_maybe_unordered (code);
21959   else
21960     return reverse_condition (code);
21961 }
21962
21963 /* Generate a compare for CODE.  Return a brand-new rtx that
21964    represents the result of the compare.  */
21965
21966 static rtx
21967 rs6000_generate_compare (rtx cmp, machine_mode mode)
21968 {
21969   machine_mode comp_mode;
21970   rtx compare_result;
21971   enum rtx_code code = GET_CODE (cmp);
21972   rtx op0 = XEXP (cmp, 0);
21973   rtx op1 = XEXP (cmp, 1);
21974
21975   if (!TARGET_FLOAT128_HW && FLOAT128_VECTOR_P (mode))
21976     comp_mode = CCmode;
21977   else if (FLOAT_MODE_P (mode))
21978     comp_mode = CCFPmode;
21979   else if (code == GTU || code == LTU
21980            || code == GEU || code == LEU)
21981     comp_mode = CCUNSmode;
21982   else if ((code == EQ || code == NE)
21983            && unsigned_reg_p (op0)
21984            && (unsigned_reg_p (op1)
21985                || (CONST_INT_P (op1) && INTVAL (op1) != 0)))
21986     /* These are unsigned values, perhaps there will be a later
21987        ordering compare that can be shared with this one.  */
21988     comp_mode = CCUNSmode;
21989   else
21990     comp_mode = CCmode;
21991
21992   /* If we have an unsigned compare, make sure we don't have a signed value as
21993      an immediate.  */
21994   if (comp_mode == CCUNSmode && GET_CODE (op1) == CONST_INT
21995       && INTVAL (op1) < 0)
21996     {
21997       op0 = copy_rtx_if_shared (op0);
21998       op1 = force_reg (GET_MODE (op0), op1);
21999       cmp = gen_rtx_fmt_ee (code, GET_MODE (cmp), op0, op1);
22000     }
22001
22002   /* First, the compare.  */
22003   compare_result = gen_reg_rtx (comp_mode);
22004
22005   /* IEEE 128-bit support in VSX registers when we do not have hardware
22006      support.  */
22007   if (!TARGET_FLOAT128_HW && FLOAT128_VECTOR_P (mode))
22008     {
22009       rtx libfunc = NULL_RTX;
22010       bool check_nan = false;
22011       rtx dest;
22012
22013       switch (code)
22014         {
22015         case EQ:
22016         case NE:
22017           libfunc = optab_libfunc (eq_optab, mode);
22018           break;
22019
22020         case GT:
22021         case GE:
22022           libfunc = optab_libfunc (ge_optab, mode);
22023           break;
22024
22025         case LT:
22026         case LE:
22027           libfunc = optab_libfunc (le_optab, mode);
22028           break;
22029
22030         case UNORDERED:
22031         case ORDERED:
22032           libfunc = optab_libfunc (unord_optab, mode);
22033           code = (code == UNORDERED) ? NE : EQ;
22034           break;
22035
22036         case UNGE:
22037         case UNGT:
22038           check_nan = true;
22039           libfunc = optab_libfunc (ge_optab, mode);
22040           code = (code == UNGE) ? GE : GT;
22041           break;
22042
22043         case UNLE:
22044         case UNLT:
22045           check_nan = true;
22046           libfunc = optab_libfunc (le_optab, mode);
22047           code = (code == UNLE) ? LE : LT;
22048           break;
22049
22050         case UNEQ:
22051         case LTGT:
22052           check_nan = true;
22053           libfunc = optab_libfunc (eq_optab, mode);
22054           code = (code = UNEQ) ? EQ : NE;
22055           break;
22056
22057         default:
22058           gcc_unreachable ();
22059         }
22060
22061       gcc_assert (libfunc);
22062
22063       if (!check_nan)
22064         dest = emit_library_call_value (libfunc, NULL_RTX, LCT_CONST,
22065                                         SImode, op0, mode, op1, mode);
22066
22067       /* The library signals an exception for signalling NaNs, so we need to
22068          handle isgreater, etc. by first checking isordered.  */
22069       else
22070         {
22071           rtx ne_rtx, normal_dest, unord_dest;
22072           rtx unord_func = optab_libfunc (unord_optab, mode);
22073           rtx join_label = gen_label_rtx ();
22074           rtx join_ref = gen_rtx_LABEL_REF (VOIDmode, join_label);
22075           rtx unord_cmp = gen_reg_rtx (comp_mode);
22076
22077
22078           /* Test for either value being a NaN.  */
22079           gcc_assert (unord_func);
22080           unord_dest = emit_library_call_value (unord_func, NULL_RTX, LCT_CONST,
22081                                                 SImode, op0, mode, op1, mode);
22082
22083           /* Set value (0) if either value is a NaN, and jump to the join
22084              label.  */
22085           dest = gen_reg_rtx (SImode);
22086           emit_move_insn (dest, const1_rtx);
22087           emit_insn (gen_rtx_SET (unord_cmp,
22088                                   gen_rtx_COMPARE (comp_mode, unord_dest,
22089                                                    const0_rtx)));
22090
22091           ne_rtx = gen_rtx_NE (comp_mode, unord_cmp, const0_rtx);
22092           emit_jump_insn (gen_rtx_SET (pc_rtx,
22093                                        gen_rtx_IF_THEN_ELSE (VOIDmode, ne_rtx,
22094                                                              join_ref,
22095                                                              pc_rtx)));
22096
22097           /* Do the normal comparison, knowing that the values are not
22098              NaNs.  */
22099           normal_dest = emit_library_call_value (libfunc, NULL_RTX, LCT_CONST,
22100                                                  SImode, op0, mode, op1, mode);
22101
22102           emit_insn (gen_cstoresi4 (dest,
22103                                     gen_rtx_fmt_ee (code, SImode, normal_dest,
22104                                                     const0_rtx),
22105                                     normal_dest, const0_rtx));
22106
22107           /* Join NaN and non-Nan paths.  Compare dest against 0.  */
22108           emit_label (join_label);
22109           code = NE;
22110         }
22111
22112       emit_insn (gen_rtx_SET (compare_result,
22113                               gen_rtx_COMPARE (comp_mode, dest, const0_rtx)));
22114     }
22115
22116   else
22117     {
22118       /* Generate XLC-compatible TFmode compare as PARALLEL with extra
22119          CLOBBERs to match cmptf_internal2 pattern.  */
22120       if (comp_mode == CCFPmode && TARGET_XL_COMPAT
22121           && FLOAT128_IBM_P (GET_MODE (op0))
22122           && TARGET_HARD_FLOAT)
22123         emit_insn (gen_rtx_PARALLEL (VOIDmode,
22124           gen_rtvec (10,
22125                      gen_rtx_SET (compare_result,
22126                                   gen_rtx_COMPARE (comp_mode, op0, op1)),
22127                      gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (DFmode)),
22128                      gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (DFmode)),
22129                      gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (DFmode)),
22130                      gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (DFmode)),
22131                      gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (DFmode)),
22132                      gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (DFmode)),
22133                      gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (DFmode)),
22134                      gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (DFmode)),
22135                      gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (Pmode)))));
22136       else if (GET_CODE (op1) == UNSPEC
22137                && XINT (op1, 1) == UNSPEC_SP_TEST)
22138         {
22139           rtx op1b = XVECEXP (op1, 0, 0);
22140           comp_mode = CCEQmode;
22141           compare_result = gen_reg_rtx (CCEQmode);
22142           if (TARGET_64BIT)
22143             emit_insn (gen_stack_protect_testdi (compare_result, op0, op1b));
22144           else
22145             emit_insn (gen_stack_protect_testsi (compare_result, op0, op1b));
22146         }
22147       else
22148         emit_insn (gen_rtx_SET (compare_result,
22149                                 gen_rtx_COMPARE (comp_mode, op0, op1)));
22150     }
22151
22152   /* Some kinds of FP comparisons need an OR operation;
22153      under flag_finite_math_only we don't bother.  */
22154   if (FLOAT_MODE_P (mode)
22155       && (!FLOAT128_IEEE_P (mode) || TARGET_FLOAT128_HW)
22156       && !flag_finite_math_only
22157       && (code == LE || code == GE
22158           || code == UNEQ || code == LTGT
22159           || code == UNGT || code == UNLT))
22160     {
22161       enum rtx_code or1, or2;
22162       rtx or1_rtx, or2_rtx, compare2_rtx;
22163       rtx or_result = gen_reg_rtx (CCEQmode);
22164
22165       switch (code)
22166         {
22167         case LE: or1 = LT;  or2 = EQ;  break;
22168         case GE: or1 = GT;  or2 = EQ;  break;
22169         case UNEQ: or1 = UNORDERED;  or2 = EQ;  break;
22170         case LTGT: or1 = LT;  or2 = GT;  break;
22171         case UNGT: or1 = UNORDERED;  or2 = GT;  break;
22172         case UNLT: or1 = UNORDERED;  or2 = LT;  break;
22173         default:  gcc_unreachable ();
22174         }
22175       validate_condition_mode (or1, comp_mode);
22176       validate_condition_mode (or2, comp_mode);
22177       or1_rtx = gen_rtx_fmt_ee (or1, SImode, compare_result, const0_rtx);
22178       or2_rtx = gen_rtx_fmt_ee (or2, SImode, compare_result, const0_rtx);
22179       compare2_rtx = gen_rtx_COMPARE (CCEQmode,
22180                                       gen_rtx_IOR (SImode, or1_rtx, or2_rtx),
22181                                       const_true_rtx);
22182       emit_insn (gen_rtx_SET (or_result, compare2_rtx));
22183
22184       compare_result = or_result;
22185       code = EQ;
22186     }
22187
22188   validate_condition_mode (code, GET_MODE (compare_result));
22189
22190   return gen_rtx_fmt_ee (code, VOIDmode, compare_result, const0_rtx);
22191 }
22192
22193 \f
22194 /* Return the diagnostic message string if the binary operation OP is
22195    not permitted on TYPE1 and TYPE2, NULL otherwise.  */
22196
22197 static const char*
22198 rs6000_invalid_binary_op (int op ATTRIBUTE_UNUSED,
22199                           const_tree type1,
22200                           const_tree type2)
22201 {
22202   machine_mode mode1 = TYPE_MODE (type1);
22203   machine_mode mode2 = TYPE_MODE (type2);
22204
22205   /* For complex modes, use the inner type.  */
22206   if (COMPLEX_MODE_P (mode1))
22207     mode1 = GET_MODE_INNER (mode1);
22208
22209   if (COMPLEX_MODE_P (mode2))
22210     mode2 = GET_MODE_INNER (mode2);
22211
22212   /* Don't allow IEEE 754R 128-bit binary floating point and IBM extended
22213      double to intermix unless -mfloat128-convert.  */
22214   if (mode1 == mode2)
22215     return NULL;
22216
22217   if (!TARGET_FLOAT128_CVT)
22218     {
22219       if ((mode1 == KFmode && mode2 == IFmode)
22220           || (mode1 == IFmode && mode2 == KFmode))
22221         return N_("__float128 and __ibm128 cannot be used in the same "
22222                   "expression");
22223
22224       if (TARGET_IEEEQUAD
22225           && ((mode1 == IFmode && mode2 == TFmode)
22226               || (mode1 == TFmode && mode2 == IFmode)))
22227         return N_("__ibm128 and long double cannot be used in the same "
22228                   "expression");
22229
22230       if (!TARGET_IEEEQUAD
22231           && ((mode1 == KFmode && mode2 == TFmode)
22232               || (mode1 == TFmode && mode2 == KFmode)))
22233         return N_("__float128 and long double cannot be used in the same "
22234                   "expression");
22235     }
22236
22237   return NULL;
22238 }
22239
22240 \f
22241 /* Expand floating point conversion to/from __float128 and __ibm128.  */
22242
22243 void
22244 rs6000_expand_float128_convert (rtx dest, rtx src, bool unsigned_p)
22245 {
22246   machine_mode dest_mode = GET_MODE (dest);
22247   machine_mode src_mode = GET_MODE (src);
22248   convert_optab cvt = unknown_optab;
22249   bool do_move = false;
22250   rtx libfunc = NULL_RTX;
22251   rtx dest2;
22252   typedef rtx (*rtx_2func_t) (rtx, rtx);
22253   rtx_2func_t hw_convert = (rtx_2func_t)0;
22254   size_t kf_or_tf;
22255
22256   struct hw_conv_t {
22257     rtx_2func_t from_df;
22258     rtx_2func_t from_sf;
22259     rtx_2func_t from_si_sign;
22260     rtx_2func_t from_si_uns;
22261     rtx_2func_t from_di_sign;
22262     rtx_2func_t from_di_uns;
22263     rtx_2func_t to_df;
22264     rtx_2func_t to_sf;
22265     rtx_2func_t to_si_sign;
22266     rtx_2func_t to_si_uns;
22267     rtx_2func_t to_di_sign;
22268     rtx_2func_t to_di_uns;
22269   } hw_conversions[2] = {
22270     /* convertions to/from KFmode */
22271     {
22272       gen_extenddfkf2_hw,               /* KFmode <- DFmode.  */
22273       gen_extendsfkf2_hw,               /* KFmode <- SFmode.  */
22274       gen_float_kfsi2_hw,               /* KFmode <- SImode (signed).  */
22275       gen_floatuns_kfsi2_hw,            /* KFmode <- SImode (unsigned).  */
22276       gen_float_kfdi2_hw,               /* KFmode <- DImode (signed).  */
22277       gen_floatuns_kfdi2_hw,            /* KFmode <- DImode (unsigned).  */
22278       gen_trunckfdf2_hw,                /* DFmode <- KFmode.  */
22279       gen_trunckfsf2_hw,                /* SFmode <- KFmode.  */
22280       gen_fix_kfsi2_hw,                 /* SImode <- KFmode (signed).  */
22281       gen_fixuns_kfsi2_hw,              /* SImode <- KFmode (unsigned).  */
22282       gen_fix_kfdi2_hw,                 /* DImode <- KFmode (signed).  */
22283       gen_fixuns_kfdi2_hw,              /* DImode <- KFmode (unsigned).  */
22284     },
22285
22286     /* convertions to/from TFmode */
22287     {
22288       gen_extenddftf2_hw,               /* TFmode <- DFmode.  */
22289       gen_extendsftf2_hw,               /* TFmode <- SFmode.  */
22290       gen_float_tfsi2_hw,               /* TFmode <- SImode (signed).  */
22291       gen_floatuns_tfsi2_hw,            /* TFmode <- SImode (unsigned).  */
22292       gen_float_tfdi2_hw,               /* TFmode <- DImode (signed).  */
22293       gen_floatuns_tfdi2_hw,            /* TFmode <- DImode (unsigned).  */
22294       gen_trunctfdf2_hw,                /* DFmode <- TFmode.  */
22295       gen_trunctfsf2_hw,                /* SFmode <- TFmode.  */
22296       gen_fix_tfsi2_hw,                 /* SImode <- TFmode (signed).  */
22297       gen_fixuns_tfsi2_hw,              /* SImode <- TFmode (unsigned).  */
22298       gen_fix_tfdi2_hw,                 /* DImode <- TFmode (signed).  */
22299       gen_fixuns_tfdi2_hw,              /* DImode <- TFmode (unsigned).  */
22300     },
22301   };
22302
22303   if (dest_mode == src_mode)
22304     gcc_unreachable ();
22305
22306   /* Eliminate memory operations.  */
22307   if (MEM_P (src))
22308     src = force_reg (src_mode, src);
22309
22310   if (MEM_P (dest))
22311     {
22312       rtx tmp = gen_reg_rtx (dest_mode);
22313       rs6000_expand_float128_convert (tmp, src, unsigned_p);
22314       rs6000_emit_move (dest, tmp, dest_mode);
22315       return;
22316     }
22317
22318   /* Convert to IEEE 128-bit floating point.  */
22319   if (FLOAT128_IEEE_P (dest_mode))
22320     {
22321       if (dest_mode == KFmode)
22322         kf_or_tf = 0;
22323       else if (dest_mode == TFmode)
22324         kf_or_tf = 1;
22325       else
22326         gcc_unreachable ();
22327
22328       switch (src_mode)
22329         {
22330         case E_DFmode:
22331           cvt = sext_optab;
22332           hw_convert = hw_conversions[kf_or_tf].from_df;
22333           break;
22334
22335         case E_SFmode:
22336           cvt = sext_optab;
22337           hw_convert = hw_conversions[kf_or_tf].from_sf;
22338           break;
22339
22340         case E_KFmode:
22341         case E_IFmode:
22342         case E_TFmode:
22343           if (FLOAT128_IBM_P (src_mode))
22344             cvt = sext_optab;
22345           else
22346             do_move = true;
22347           break;
22348
22349         case E_SImode:
22350           if (unsigned_p)
22351             {
22352               cvt = ufloat_optab;
22353               hw_convert = hw_conversions[kf_or_tf].from_si_uns;
22354             }
22355           else
22356             {
22357               cvt = sfloat_optab;
22358               hw_convert = hw_conversions[kf_or_tf].from_si_sign;
22359             }
22360           break;
22361
22362         case E_DImode:
22363           if (unsigned_p)
22364             {
22365               cvt = ufloat_optab;
22366               hw_convert = hw_conversions[kf_or_tf].from_di_uns;
22367             }
22368           else
22369             {
22370               cvt = sfloat_optab;
22371               hw_convert = hw_conversions[kf_or_tf].from_di_sign;
22372             }
22373           break;
22374
22375         default:
22376           gcc_unreachable ();
22377         }
22378     }
22379
22380   /* Convert from IEEE 128-bit floating point.  */
22381   else if (FLOAT128_IEEE_P (src_mode))
22382     {
22383       if (src_mode == KFmode)
22384         kf_or_tf = 0;
22385       else if (src_mode == TFmode)
22386         kf_or_tf = 1;
22387       else
22388         gcc_unreachable ();
22389
22390       switch (dest_mode)
22391         {
22392         case E_DFmode:
22393           cvt = trunc_optab;
22394           hw_convert = hw_conversions[kf_or_tf].to_df;
22395           break;
22396
22397         case E_SFmode:
22398           cvt = trunc_optab;
22399           hw_convert = hw_conversions[kf_or_tf].to_sf;
22400           break;
22401
22402         case E_KFmode:
22403         case E_IFmode:
22404         case E_TFmode:
22405           if (FLOAT128_IBM_P (dest_mode))
22406             cvt = trunc_optab;
22407           else
22408             do_move = true;
22409           break;
22410
22411         case E_SImode:
22412           if (unsigned_p)
22413             {
22414               cvt = ufix_optab;
22415               hw_convert = hw_conversions[kf_or_tf].to_si_uns;
22416             }
22417           else
22418             {
22419               cvt = sfix_optab;
22420               hw_convert = hw_conversions[kf_or_tf].to_si_sign;
22421             }
22422           break;
22423
22424         case E_DImode:
22425           if (unsigned_p)
22426             {
22427               cvt = ufix_optab;
22428               hw_convert = hw_conversions[kf_or_tf].to_di_uns;
22429             }
22430           else
22431             {
22432               cvt = sfix_optab;
22433               hw_convert = hw_conversions[kf_or_tf].to_di_sign;
22434             }
22435           break;
22436
22437         default:
22438           gcc_unreachable ();
22439         }
22440     }
22441
22442   /* Both IBM format.  */
22443   else if (FLOAT128_IBM_P (dest_mode) && FLOAT128_IBM_P (src_mode))
22444     do_move = true;
22445
22446   else
22447     gcc_unreachable ();
22448
22449   /* Handle conversion between TFmode/KFmode.  */
22450   if (do_move)
22451     emit_move_insn (dest, gen_lowpart (dest_mode, src));
22452
22453   /* Handle conversion if we have hardware support.  */
22454   else if (TARGET_FLOAT128_HW && hw_convert)
22455     emit_insn ((hw_convert) (dest, src));
22456
22457   /* Call an external function to do the conversion.  */
22458   else if (cvt != unknown_optab)
22459     {
22460       libfunc = convert_optab_libfunc (cvt, dest_mode, src_mode);
22461       gcc_assert (libfunc != NULL_RTX);
22462
22463       dest2 = emit_library_call_value (libfunc, dest, LCT_CONST, dest_mode,
22464                                        src, src_mode);
22465
22466       gcc_assert (dest2 != NULL_RTX);
22467       if (!rtx_equal_p (dest, dest2))
22468         emit_move_insn (dest, dest2);
22469     }
22470
22471   else
22472     gcc_unreachable ();
22473
22474   return;
22475 }
22476
22477 \f
22478 /* Emit RTL that sets a register to zero if OP1 and OP2 are equal.  SCRATCH
22479    can be used as that dest register.  Return the dest register.  */
22480
22481 rtx
22482 rs6000_emit_eqne (machine_mode mode, rtx op1, rtx op2, rtx scratch)
22483 {
22484   if (op2 == const0_rtx)
22485     return op1;
22486
22487   if (GET_CODE (scratch) == SCRATCH)
22488     scratch = gen_reg_rtx (mode);
22489
22490   if (logical_operand (op2, mode))
22491     emit_insn (gen_rtx_SET (scratch, gen_rtx_XOR (mode, op1, op2)));
22492   else
22493     emit_insn (gen_rtx_SET (scratch,
22494                             gen_rtx_PLUS (mode, op1, negate_rtx (mode, op2))));
22495
22496   return scratch;
22497 }
22498
22499 void
22500 rs6000_emit_sCOND (machine_mode mode, rtx operands[])
22501 {
22502   rtx condition_rtx;
22503   machine_mode op_mode;
22504   enum rtx_code cond_code;
22505   rtx result = operands[0];
22506
22507   condition_rtx = rs6000_generate_compare (operands[1], mode);
22508   cond_code = GET_CODE (condition_rtx);
22509
22510   if (cond_code == NE
22511       || cond_code == GE || cond_code == LE
22512       || cond_code == GEU || cond_code == LEU
22513       || cond_code == ORDERED || cond_code == UNGE || cond_code == UNLE)
22514     {
22515       rtx not_result = gen_reg_rtx (CCEQmode);
22516       rtx not_op, rev_cond_rtx;
22517       machine_mode cc_mode;
22518
22519       cc_mode = GET_MODE (XEXP (condition_rtx, 0));
22520
22521       rev_cond_rtx = gen_rtx_fmt_ee (rs6000_reverse_condition (cc_mode, cond_code),
22522                                      SImode, XEXP (condition_rtx, 0), const0_rtx);
22523       not_op = gen_rtx_COMPARE (CCEQmode, rev_cond_rtx, const0_rtx);
22524       emit_insn (gen_rtx_SET (not_result, not_op));
22525       condition_rtx = gen_rtx_EQ (VOIDmode, not_result, const0_rtx);
22526     }
22527
22528   op_mode = GET_MODE (XEXP (operands[1], 0));
22529   if (op_mode == VOIDmode)
22530     op_mode = GET_MODE (XEXP (operands[1], 1));
22531
22532   if (TARGET_POWERPC64 && (op_mode == DImode || FLOAT_MODE_P (mode)))
22533     {
22534       PUT_MODE (condition_rtx, DImode);
22535       convert_move (result, condition_rtx, 0);
22536     }
22537   else
22538     {
22539       PUT_MODE (condition_rtx, SImode);
22540       emit_insn (gen_rtx_SET (result, condition_rtx));
22541     }
22542 }
22543
22544 /* Emit a branch of kind CODE to location LOC.  */
22545
22546 void
22547 rs6000_emit_cbranch (machine_mode mode, rtx operands[])
22548 {
22549   rtx condition_rtx, loc_ref;
22550
22551   condition_rtx = rs6000_generate_compare (operands[0], mode);
22552   loc_ref = gen_rtx_LABEL_REF (VOIDmode, operands[3]);
22553   emit_jump_insn (gen_rtx_SET (pc_rtx,
22554                                gen_rtx_IF_THEN_ELSE (VOIDmode, condition_rtx,
22555                                                      loc_ref, pc_rtx)));
22556 }
22557
22558 /* Return the string to output a conditional branch to LABEL, which is
22559    the operand template of the label, or NULL if the branch is really a
22560    conditional return.
22561
22562    OP is the conditional expression.  XEXP (OP, 0) is assumed to be a
22563    condition code register and its mode specifies what kind of
22564    comparison we made.
22565
22566    REVERSED is nonzero if we should reverse the sense of the comparison.
22567
22568    INSN is the insn.  */
22569
22570 char *
22571 output_cbranch (rtx op, const char *label, int reversed, rtx_insn *insn)
22572 {
22573   static char string[64];
22574   enum rtx_code code = GET_CODE (op);
22575   rtx cc_reg = XEXP (op, 0);
22576   machine_mode mode = GET_MODE (cc_reg);
22577   int cc_regno = REGNO (cc_reg) - CR0_REGNO;
22578   int need_longbranch = label != NULL && get_attr_length (insn) == 8;
22579   int really_reversed = reversed ^ need_longbranch;
22580   char *s = string;
22581   const char *ccode;
22582   const char *pred;
22583   rtx note;
22584
22585   validate_condition_mode (code, mode);
22586
22587   /* Work out which way this really branches.  We could use
22588      reverse_condition_maybe_unordered here always but this
22589      makes the resulting assembler clearer.  */
22590   if (really_reversed)
22591     {
22592       /* Reversal of FP compares takes care -- an ordered compare
22593          becomes an unordered compare and vice versa.  */
22594       if (mode == CCFPmode)
22595         code = reverse_condition_maybe_unordered (code);
22596       else
22597         code = reverse_condition (code);
22598     }
22599
22600   switch (code)
22601     {
22602       /* Not all of these are actually distinct opcodes, but
22603          we distinguish them for clarity of the resulting assembler.  */
22604     case NE: case LTGT:
22605       ccode = "ne"; break;
22606     case EQ: case UNEQ:
22607       ccode = "eq"; break;
22608     case GE: case GEU:
22609       ccode = "ge"; break;
22610     case GT: case GTU: case UNGT:
22611       ccode = "gt"; break;
22612     case LE: case LEU:
22613       ccode = "le"; break;
22614     case LT: case LTU: case UNLT:
22615       ccode = "lt"; break;
22616     case UNORDERED: ccode = "un"; break;
22617     case ORDERED: ccode = "nu"; break;
22618     case UNGE: ccode = "nl"; break;
22619     case UNLE: ccode = "ng"; break;
22620     default:
22621       gcc_unreachable ();
22622     }
22623
22624   /* Maybe we have a guess as to how likely the branch is.  */
22625   pred = "";
22626   note = find_reg_note (insn, REG_BR_PROB, NULL_RTX);
22627   if (note != NULL_RTX)
22628     {
22629       /* PROB is the difference from 50%.  */
22630       int prob = profile_probability::from_reg_br_prob_note (XINT (note, 0))
22631                    .to_reg_br_prob_base () - REG_BR_PROB_BASE / 2;
22632
22633       /* Only hint for highly probable/improbable branches on newer cpus when
22634          we have real profile data, as static prediction overrides processor
22635          dynamic prediction.  For older cpus we may as well always hint, but
22636          assume not taken for branches that are very close to 50% as a
22637          mispredicted taken branch is more expensive than a
22638          mispredicted not-taken branch.  */
22639       if (rs6000_always_hint
22640           || (abs (prob) > REG_BR_PROB_BASE / 100 * 48
22641               && (profile_status_for_fn (cfun) != PROFILE_GUESSED)
22642               && br_prob_note_reliable_p (note)))
22643         {
22644           if (abs (prob) > REG_BR_PROB_BASE / 20
22645               && ((prob > 0) ^ need_longbranch))
22646             pred = "+";
22647           else
22648             pred = "-";
22649         }
22650     }
22651
22652   if (label == NULL)
22653     s += sprintf (s, "b%slr%s ", ccode, pred);
22654   else
22655     s += sprintf (s, "b%s%s ", ccode, pred);
22656
22657   /* We need to escape any '%' characters in the reg_names string.
22658      Assume they'd only be the first character....  */
22659   if (reg_names[cc_regno + CR0_REGNO][0] == '%')
22660     *s++ = '%';
22661   s += sprintf (s, "%s", reg_names[cc_regno + CR0_REGNO]);
22662
22663   if (label != NULL)
22664     {
22665       /* If the branch distance was too far, we may have to use an
22666          unconditional branch to go the distance.  */
22667       if (need_longbranch)
22668         s += sprintf (s, ",$+8\n\tb %s", label);
22669       else
22670         s += sprintf (s, ",%s", label);
22671     }
22672
22673   return string;
22674 }
22675
22676 /* Return insn for VSX or Altivec comparisons.  */
22677
22678 static rtx
22679 rs6000_emit_vector_compare_inner (enum rtx_code code, rtx op0, rtx op1)
22680 {
22681   rtx mask;
22682   machine_mode mode = GET_MODE (op0);
22683
22684   switch (code)
22685     {
22686     default:
22687       break;
22688
22689     case GE:
22690       if (GET_MODE_CLASS (mode) == MODE_VECTOR_INT)
22691         return NULL_RTX;
22692       /* FALLTHRU */
22693
22694     case EQ:
22695     case GT:
22696     case GTU:
22697     case ORDERED:
22698     case UNORDERED:
22699     case UNEQ:
22700     case LTGT:
22701       mask = gen_reg_rtx (mode);
22702       emit_insn (gen_rtx_SET (mask, gen_rtx_fmt_ee (code, mode, op0, op1)));
22703       return mask;
22704     }
22705
22706   return NULL_RTX;
22707 }
22708
22709 /* Emit vector compare for operands OP0 and OP1 using code RCODE.
22710    DMODE is expected destination mode. This is a recursive function.  */
22711
22712 static rtx
22713 rs6000_emit_vector_compare (enum rtx_code rcode,
22714                             rtx op0, rtx op1,
22715                             machine_mode dmode)
22716 {
22717   rtx mask;
22718   bool swap_operands = false;
22719   bool try_again = false;
22720
22721   gcc_assert (VECTOR_UNIT_ALTIVEC_OR_VSX_P (dmode));
22722   gcc_assert (GET_MODE (op0) == GET_MODE (op1));
22723
22724   /* See if the comparison works as is.  */
22725   mask = rs6000_emit_vector_compare_inner (rcode, op0, op1);
22726   if (mask)
22727     return mask;
22728
22729   switch (rcode)
22730     {
22731     case LT:
22732       rcode = GT;
22733       swap_operands = true;
22734       try_again = true;
22735       break;
22736     case LTU:
22737       rcode = GTU;
22738       swap_operands = true;
22739       try_again = true;
22740       break;
22741     case NE:
22742     case UNLE:
22743     case UNLT:
22744     case UNGE:
22745     case UNGT:
22746       /* Invert condition and try again.
22747          e.g., A != B becomes ~(A==B).  */
22748       {
22749         enum rtx_code rev_code;
22750         enum insn_code nor_code;
22751         rtx mask2;
22752
22753         rev_code = reverse_condition_maybe_unordered (rcode);
22754         if (rev_code == UNKNOWN)
22755           return NULL_RTX;
22756
22757         nor_code = optab_handler (one_cmpl_optab, dmode);
22758         if (nor_code == CODE_FOR_nothing)
22759           return NULL_RTX;
22760
22761         mask2 = rs6000_emit_vector_compare (rev_code, op0, op1, dmode);
22762         if (!mask2)
22763           return NULL_RTX;
22764
22765         mask = gen_reg_rtx (dmode);
22766         emit_insn (GEN_FCN (nor_code) (mask, mask2));
22767         return mask;
22768       }
22769       break;
22770     case GE:
22771     case GEU:
22772     case LE:
22773     case LEU:
22774       /* Try GT/GTU/LT/LTU OR EQ */
22775       {
22776         rtx c_rtx, eq_rtx;
22777         enum insn_code ior_code;
22778         enum rtx_code new_code;
22779
22780         switch (rcode)
22781           {
22782           case  GE:
22783             new_code = GT;
22784             break;
22785
22786           case GEU:
22787             new_code = GTU;
22788             break;
22789
22790           case LE:
22791             new_code = LT;
22792             break;
22793
22794           case LEU:
22795             new_code = LTU;
22796             break;
22797
22798           default:
22799             gcc_unreachable ();
22800           }
22801
22802         ior_code = optab_handler (ior_optab, dmode);
22803         if (ior_code == CODE_FOR_nothing)
22804           return NULL_RTX;
22805
22806         c_rtx = rs6000_emit_vector_compare (new_code, op0, op1, dmode);
22807         if (!c_rtx)
22808           return NULL_RTX;
22809
22810         eq_rtx = rs6000_emit_vector_compare (EQ, op0, op1, dmode);
22811         if (!eq_rtx)
22812           return NULL_RTX;
22813
22814         mask = gen_reg_rtx (dmode);
22815         emit_insn (GEN_FCN (ior_code) (mask, c_rtx, eq_rtx));
22816         return mask;
22817       }
22818       break;
22819     default:
22820       return NULL_RTX;
22821     }
22822
22823   if (try_again)
22824     {
22825       if (swap_operands)
22826         std::swap (op0, op1);
22827
22828       mask = rs6000_emit_vector_compare_inner (rcode, op0, op1);
22829       if (mask)
22830         return mask;
22831     }
22832
22833   /* You only get two chances.  */
22834   return NULL_RTX;
22835 }
22836
22837 /* Emit vector conditional expression.  DEST is destination. OP_TRUE and
22838    OP_FALSE are two VEC_COND_EXPR operands.  CC_OP0 and CC_OP1 are the two
22839    operands for the relation operation COND.  */
22840
22841 int
22842 rs6000_emit_vector_cond_expr (rtx dest, rtx op_true, rtx op_false,
22843                               rtx cond, rtx cc_op0, rtx cc_op1)
22844 {
22845   machine_mode dest_mode = GET_MODE (dest);
22846   machine_mode mask_mode = GET_MODE (cc_op0);
22847   enum rtx_code rcode = GET_CODE (cond);
22848   machine_mode cc_mode = CCmode;
22849   rtx mask;
22850   rtx cond2;
22851   bool invert_move = false;
22852
22853   if (VECTOR_UNIT_NONE_P (dest_mode))
22854     return 0;
22855
22856   gcc_assert (GET_MODE_SIZE (dest_mode) == GET_MODE_SIZE (mask_mode)
22857               && GET_MODE_NUNITS (dest_mode) == GET_MODE_NUNITS (mask_mode));
22858
22859   switch (rcode)
22860     {
22861       /* Swap operands if we can, and fall back to doing the operation as
22862          specified, and doing a NOR to invert the test.  */
22863     case NE:
22864     case UNLE:
22865     case UNLT:
22866     case UNGE:
22867     case UNGT:
22868       /* Invert condition and try again.
22869          e.g., A  = (B != C) ? D : E becomes A = (B == C) ? E : D.  */
22870       invert_move = true;
22871       rcode = reverse_condition_maybe_unordered (rcode);
22872       if (rcode == UNKNOWN)
22873         return 0;
22874       break;
22875
22876     case GE:
22877     case LE:
22878       if (GET_MODE_CLASS (mask_mode) == MODE_VECTOR_INT)
22879         {
22880           /* Invert condition to avoid compound test.  */
22881           invert_move = true;
22882           rcode = reverse_condition (rcode);
22883         }
22884       break;
22885
22886     case GTU:
22887     case GEU:
22888     case LTU:
22889     case LEU:
22890       /* Mark unsigned tests with CCUNSmode.  */
22891       cc_mode = CCUNSmode;
22892
22893       /* Invert condition to avoid compound test if necessary.  */
22894       if (rcode == GEU || rcode == LEU)
22895         {
22896           invert_move = true;
22897           rcode = reverse_condition (rcode);
22898         }
22899       break;
22900
22901     default:
22902       break;
22903     }
22904
22905   /* Get the vector mask for the given relational operations.  */
22906   mask = rs6000_emit_vector_compare (rcode, cc_op0, cc_op1, mask_mode);
22907
22908   if (!mask)
22909     return 0;
22910
22911   if (invert_move)
22912     std::swap (op_true, op_false);
22913
22914   /* Optimize vec1 == vec2, to know the mask generates -1/0.  */
22915   if (GET_MODE_CLASS (dest_mode) == MODE_VECTOR_INT
22916       && (GET_CODE (op_true) == CONST_VECTOR
22917           || GET_CODE (op_false) == CONST_VECTOR))
22918     {
22919       rtx constant_0 = CONST0_RTX (dest_mode);
22920       rtx constant_m1 = CONSTM1_RTX (dest_mode);
22921
22922       if (op_true == constant_m1 && op_false == constant_0)
22923         {
22924           emit_move_insn (dest, mask);
22925           return 1;
22926         }
22927
22928       else if (op_true == constant_0 && op_false == constant_m1)
22929         {
22930           emit_insn (gen_rtx_SET (dest, gen_rtx_NOT (dest_mode, mask)));
22931           return 1;
22932         }
22933
22934       /* If we can't use the vector comparison directly, perhaps we can use
22935          the mask for the true or false fields, instead of loading up a
22936          constant.  */
22937       if (op_true == constant_m1)
22938         op_true = mask;
22939
22940       if (op_false == constant_0)
22941         op_false = mask;
22942     }
22943
22944   if (!REG_P (op_true) && !SUBREG_P (op_true))
22945     op_true = force_reg (dest_mode, op_true);
22946
22947   if (!REG_P (op_false) && !SUBREG_P (op_false))
22948     op_false = force_reg (dest_mode, op_false);
22949
22950   cond2 = gen_rtx_fmt_ee (NE, cc_mode, gen_lowpart (dest_mode, mask),
22951                           CONST0_RTX (dest_mode));
22952   emit_insn (gen_rtx_SET (dest,
22953                           gen_rtx_IF_THEN_ELSE (dest_mode,
22954                                                 cond2,
22955                                                 op_true,
22956                                                 op_false)));
22957   return 1;
22958 }
22959
22960 /* ISA 3.0 (power9) minmax subcase to emit a XSMAXCDP or XSMINCDP instruction
22961    for SF/DF scalars.  Move TRUE_COND to DEST if OP of the operands of the last
22962    comparison is nonzero/true, FALSE_COND if it is zero/false.  Return 0 if the
22963    hardware has no such operation.  */
22964
22965 static int
22966 rs6000_emit_p9_fp_minmax (rtx dest, rtx op, rtx true_cond, rtx false_cond)
22967 {
22968   enum rtx_code code = GET_CODE (op);
22969   rtx op0 = XEXP (op, 0);
22970   rtx op1 = XEXP (op, 1);
22971   machine_mode compare_mode = GET_MODE (op0);
22972   machine_mode result_mode = GET_MODE (dest);
22973   bool max_p = false;
22974
22975   if (result_mode != compare_mode)
22976     return 0;
22977
22978   if (code == GE || code == GT)
22979     max_p = true;
22980   else if (code == LE || code == LT)
22981     max_p = false;
22982   else
22983     return 0;
22984
22985   if (rtx_equal_p (op0, true_cond) && rtx_equal_p (op1, false_cond))
22986     ;
22987
22988   else if (rtx_equal_p (op1, true_cond) && rtx_equal_p (op0, false_cond))
22989     max_p = !max_p;
22990
22991   else
22992     return 0;
22993
22994   rs6000_emit_minmax (dest, max_p ? SMAX : SMIN, op0, op1);
22995   return 1;
22996 }
22997
22998 /* ISA 3.0 (power9) conditional move subcase to emit XSCMP{EQ,GE,GT,NE}DP and
22999    XXSEL instructions for SF/DF scalars.  Move TRUE_COND to DEST if OP of the
23000    operands of the last comparison is nonzero/true, FALSE_COND if it is
23001    zero/false.  Return 0 if the hardware has no such operation.  */
23002
23003 static int
23004 rs6000_emit_p9_fp_cmove (rtx dest, rtx op, rtx true_cond, rtx false_cond)
23005 {
23006   enum rtx_code code = GET_CODE (op);
23007   rtx op0 = XEXP (op, 0);
23008   rtx op1 = XEXP (op, 1);
23009   machine_mode result_mode = GET_MODE (dest);
23010   rtx compare_rtx;
23011   rtx cmove_rtx;
23012   rtx clobber_rtx;
23013
23014   if (!can_create_pseudo_p ())
23015     return 0;
23016
23017   switch (code)
23018     {
23019     case EQ:
23020     case GE:
23021     case GT:
23022       break;
23023
23024     case NE:
23025     case LT:
23026     case LE:
23027       code = swap_condition (code);
23028       std::swap (op0, op1);
23029       break;
23030
23031     default:
23032       return 0;
23033     }
23034
23035   /* Generate:  [(parallel [(set (dest)
23036                                  (if_then_else (op (cmp1) (cmp2))
23037                                                (true)
23038                                                (false)))
23039                             (clobber (scratch))])].  */
23040
23041   compare_rtx = gen_rtx_fmt_ee (code, CCFPmode, op0, op1);
23042   cmove_rtx = gen_rtx_SET (dest,
23043                            gen_rtx_IF_THEN_ELSE (result_mode,
23044                                                  compare_rtx,
23045                                                  true_cond,
23046                                                  false_cond));
23047
23048   clobber_rtx = gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (V2DImode));
23049   emit_insn (gen_rtx_PARALLEL (VOIDmode,
23050                                gen_rtvec (2, cmove_rtx, clobber_rtx)));
23051
23052   return 1;
23053 }
23054
23055 /* Emit a conditional move: move TRUE_COND to DEST if OP of the
23056    operands of the last comparison is nonzero/true, FALSE_COND if it
23057    is zero/false.  Return 0 if the hardware has no such operation.  */
23058
23059 int
23060 rs6000_emit_cmove (rtx dest, rtx op, rtx true_cond, rtx false_cond)
23061 {
23062   enum rtx_code code = GET_CODE (op);
23063   rtx op0 = XEXP (op, 0);
23064   rtx op1 = XEXP (op, 1);
23065   machine_mode compare_mode = GET_MODE (op0);
23066   machine_mode result_mode = GET_MODE (dest);
23067   rtx temp;
23068   bool is_against_zero;
23069
23070   /* These modes should always match.  */
23071   if (GET_MODE (op1) != compare_mode
23072       /* In the isel case however, we can use a compare immediate, so
23073          op1 may be a small constant.  */
23074       && (!TARGET_ISEL || !short_cint_operand (op1, VOIDmode)))
23075     return 0;
23076   if (GET_MODE (true_cond) != result_mode)
23077     return 0;
23078   if (GET_MODE (false_cond) != result_mode)
23079     return 0;
23080
23081   /* See if we can use the ISA 3.0 (power9) min/max/compare functions.  */
23082   if (TARGET_P9_MINMAX
23083       && (compare_mode == SFmode || compare_mode == DFmode)
23084       && (result_mode == SFmode || result_mode == DFmode))
23085     {
23086       if (rs6000_emit_p9_fp_minmax (dest, op, true_cond, false_cond))
23087         return 1;
23088
23089       if (rs6000_emit_p9_fp_cmove (dest, op, true_cond, false_cond))
23090         return 1;
23091     }
23092
23093   /* Don't allow using floating point comparisons for integer results for
23094      now.  */
23095   if (FLOAT_MODE_P (compare_mode) && !FLOAT_MODE_P (result_mode))
23096     return 0;
23097
23098   /* First, work out if the hardware can do this at all, or
23099      if it's too slow....  */
23100   if (!FLOAT_MODE_P (compare_mode))
23101     {
23102       if (TARGET_ISEL)
23103         return rs6000_emit_int_cmove (dest, op, true_cond, false_cond);
23104       return 0;
23105     }
23106
23107   is_against_zero = op1 == CONST0_RTX (compare_mode);
23108
23109   /* A floating-point subtract might overflow, underflow, or produce
23110      an inexact result, thus changing the floating-point flags, so it
23111      can't be generated if we care about that.  It's safe if one side
23112      of the construct is zero, since then no subtract will be
23113      generated.  */
23114   if (SCALAR_FLOAT_MODE_P (compare_mode)
23115       && flag_trapping_math && ! is_against_zero)
23116     return 0;
23117
23118   /* Eliminate half of the comparisons by switching operands, this
23119      makes the remaining code simpler.  */
23120   if (code == UNLT || code == UNGT || code == UNORDERED || code == NE
23121       || code == LTGT || code == LT || code == UNLE)
23122     {
23123       code = reverse_condition_maybe_unordered (code);
23124       temp = true_cond;
23125       true_cond = false_cond;
23126       false_cond = temp;
23127     }
23128
23129   /* UNEQ and LTGT take four instructions for a comparison with zero,
23130      it'll probably be faster to use a branch here too.  */
23131   if (code == UNEQ && HONOR_NANS (compare_mode))
23132     return 0;
23133
23134   /* We're going to try to implement comparisons by performing
23135      a subtract, then comparing against zero.  Unfortunately,
23136      Inf - Inf is NaN which is not zero, and so if we don't
23137      know that the operand is finite and the comparison
23138      would treat EQ different to UNORDERED, we can't do it.  */
23139   if (HONOR_INFINITIES (compare_mode)
23140       && code != GT && code != UNGE
23141       && (GET_CODE (op1) != CONST_DOUBLE
23142           || real_isinf (CONST_DOUBLE_REAL_VALUE (op1)))
23143       /* Constructs of the form (a OP b ? a : b) are safe.  */
23144       && ((! rtx_equal_p (op0, false_cond) && ! rtx_equal_p (op1, false_cond))
23145           || (! rtx_equal_p (op0, true_cond)
23146               && ! rtx_equal_p (op1, true_cond))))
23147     return 0;
23148
23149   /* At this point we know we can use fsel.  */
23150
23151   /* Reduce the comparison to a comparison against zero.  */
23152   if (! is_against_zero)
23153     {
23154       temp = gen_reg_rtx (compare_mode);
23155       emit_insn (gen_rtx_SET (temp, gen_rtx_MINUS (compare_mode, op0, op1)));
23156       op0 = temp;
23157       op1 = CONST0_RTX (compare_mode);
23158     }
23159
23160   /* If we don't care about NaNs we can reduce some of the comparisons
23161      down to faster ones.  */
23162   if (! HONOR_NANS (compare_mode))
23163     switch (code)
23164       {
23165       case GT:
23166         code = LE;
23167         temp = true_cond;
23168         true_cond = false_cond;
23169         false_cond = temp;
23170         break;
23171       case UNGE:
23172         code = GE;
23173         break;
23174       case UNEQ:
23175         code = EQ;
23176         break;
23177       default:
23178         break;
23179       }
23180
23181   /* Now, reduce everything down to a GE.  */
23182   switch (code)
23183     {
23184     case GE:
23185       break;
23186
23187     case LE:
23188       temp = gen_reg_rtx (compare_mode);
23189       emit_insn (gen_rtx_SET (temp, gen_rtx_NEG (compare_mode, op0)));
23190       op0 = temp;
23191       break;
23192
23193     case ORDERED:
23194       temp = gen_reg_rtx (compare_mode);
23195       emit_insn (gen_rtx_SET (temp, gen_rtx_ABS (compare_mode, op0)));
23196       op0 = temp;
23197       break;
23198
23199     case EQ:
23200       temp = gen_reg_rtx (compare_mode);
23201       emit_insn (gen_rtx_SET (temp,
23202                               gen_rtx_NEG (compare_mode,
23203                                            gen_rtx_ABS (compare_mode, op0))));
23204       op0 = temp;
23205       break;
23206
23207     case UNGE:
23208       /* a UNGE 0 <-> (a GE 0 || -a UNLT 0) */
23209       temp = gen_reg_rtx (result_mode);
23210       emit_insn (gen_rtx_SET (temp,
23211                               gen_rtx_IF_THEN_ELSE (result_mode,
23212                                                     gen_rtx_GE (VOIDmode,
23213                                                                 op0, op1),
23214                                                     true_cond, false_cond)));
23215       false_cond = true_cond;
23216       true_cond = temp;
23217
23218       temp = gen_reg_rtx (compare_mode);
23219       emit_insn (gen_rtx_SET (temp, gen_rtx_NEG (compare_mode, op0)));
23220       op0 = temp;
23221       break;
23222
23223     case GT:
23224       /* a GT 0 <-> (a GE 0 && -a UNLT 0) */
23225       temp = gen_reg_rtx (result_mode);
23226       emit_insn (gen_rtx_SET (temp,
23227                               gen_rtx_IF_THEN_ELSE (result_mode,
23228                                                     gen_rtx_GE (VOIDmode,
23229                                                                 op0, op1),
23230                                                     true_cond, false_cond)));
23231       true_cond = false_cond;
23232       false_cond = temp;
23233
23234       temp = gen_reg_rtx (compare_mode);
23235       emit_insn (gen_rtx_SET (temp, gen_rtx_NEG (compare_mode, op0)));
23236       op0 = temp;
23237       break;
23238
23239     default:
23240       gcc_unreachable ();
23241     }
23242
23243   emit_insn (gen_rtx_SET (dest,
23244                           gen_rtx_IF_THEN_ELSE (result_mode,
23245                                                 gen_rtx_GE (VOIDmode,
23246                                                             op0, op1),
23247                                                 true_cond, false_cond)));
23248   return 1;
23249 }
23250
23251 /* Same as above, but for ints (isel).  */
23252
23253 int
23254 rs6000_emit_int_cmove (rtx dest, rtx op, rtx true_cond, rtx false_cond)
23255 {
23256   rtx condition_rtx, cr;
23257   machine_mode mode = GET_MODE (dest);
23258   enum rtx_code cond_code;
23259   rtx (*isel_func) (rtx, rtx, rtx, rtx, rtx);
23260   bool signedp;
23261
23262   if (mode != SImode && (!TARGET_POWERPC64 || mode != DImode))
23263     return 0;
23264
23265   /* We still have to do the compare, because isel doesn't do a
23266      compare, it just looks at the CRx bits set by a previous compare
23267      instruction.  */
23268   condition_rtx = rs6000_generate_compare (op, mode);
23269   cond_code = GET_CODE (condition_rtx);
23270   cr = XEXP (condition_rtx, 0);
23271   signedp = GET_MODE (cr) == CCmode;
23272
23273   isel_func = (mode == SImode
23274                ? (signedp ? gen_isel_signed_si : gen_isel_unsigned_si)
23275                : (signedp ? gen_isel_signed_di : gen_isel_unsigned_di));
23276
23277   switch (cond_code)
23278     {
23279     case LT: case GT: case LTU: case GTU: case EQ:
23280       /* isel handles these directly.  */
23281       break;
23282
23283     default:
23284       /* We need to swap the sense of the comparison.  */
23285       {
23286         std::swap (false_cond, true_cond);
23287         PUT_CODE (condition_rtx, reverse_condition (cond_code));
23288       }
23289       break;
23290     }
23291
23292   false_cond = force_reg (mode, false_cond);
23293   if (true_cond != const0_rtx)
23294     true_cond = force_reg (mode, true_cond);
23295
23296   emit_insn (isel_func (dest, condition_rtx, true_cond, false_cond, cr));
23297
23298   return 1;
23299 }
23300
23301 void
23302 rs6000_emit_minmax (rtx dest, enum rtx_code code, rtx op0, rtx op1)
23303 {
23304   machine_mode mode = GET_MODE (op0);
23305   enum rtx_code c;
23306   rtx target;
23307
23308   /* VSX/altivec have direct min/max insns.  */
23309   if ((code == SMAX || code == SMIN)
23310       && (VECTOR_UNIT_ALTIVEC_OR_VSX_P (mode)
23311           || (mode == SFmode && VECTOR_UNIT_VSX_P (DFmode))))
23312     {
23313       emit_insn (gen_rtx_SET (dest, gen_rtx_fmt_ee (code, mode, op0, op1)));
23314       return;
23315     }
23316
23317   if (code == SMAX || code == SMIN)
23318     c = GE;
23319   else
23320     c = GEU;
23321
23322   if (code == SMAX || code == UMAX)
23323     target = emit_conditional_move (dest, c, op0, op1, mode,
23324                                     op0, op1, mode, 0);
23325   else
23326     target = emit_conditional_move (dest, c, op0, op1, mode,
23327                                     op1, op0, mode, 0);
23328   gcc_assert (target);
23329   if (target != dest)
23330     emit_move_insn (dest, target);
23331 }
23332
23333 /* Split a signbit operation on 64-bit machines with direct move.  Also allow
23334    for the value to come from memory or if it is already loaded into a GPR.  */
23335
23336 void
23337 rs6000_split_signbit (rtx dest, rtx src)
23338 {
23339   machine_mode d_mode = GET_MODE (dest);
23340   machine_mode s_mode = GET_MODE (src);
23341   rtx dest_di = (d_mode == DImode) ? dest : gen_lowpart (DImode, dest);
23342   rtx shift_reg = dest_di;
23343
23344   gcc_assert (FLOAT128_IEEE_P (s_mode) && TARGET_POWERPC64);
23345
23346   if (MEM_P (src))
23347     {
23348       rtx mem = (WORDS_BIG_ENDIAN
23349                  ? adjust_address (src, DImode, 0)
23350                  : adjust_address (src, DImode, 8));
23351       emit_insn (gen_rtx_SET (dest_di, mem));
23352     }
23353
23354   else
23355     {
23356       unsigned int r = reg_or_subregno (src);
23357
23358       if (INT_REGNO_P (r))
23359         shift_reg = gen_rtx_REG (DImode, r + (BYTES_BIG_ENDIAN == 0));
23360
23361       else
23362         {
23363           /* Generate the special mfvsrd instruction to get it in a GPR.  */
23364           gcc_assert (VSX_REGNO_P (r));
23365           if (s_mode == KFmode)
23366             emit_insn (gen_signbitkf2_dm2 (dest_di, src));
23367           else
23368             emit_insn (gen_signbittf2_dm2 (dest_di, src));
23369         }
23370     }
23371
23372   emit_insn (gen_lshrdi3 (dest_di, shift_reg, GEN_INT (63)));
23373   return;
23374 }
23375
23376 /* A subroutine of the atomic operation splitters.  Jump to LABEL if
23377    COND is true.  Mark the jump as unlikely to be taken.  */
23378
23379 static void
23380 emit_unlikely_jump (rtx cond, rtx label)
23381 {
23382   rtx x = gen_rtx_IF_THEN_ELSE (VOIDmode, cond, label, pc_rtx);
23383   rtx_insn *insn = emit_jump_insn (gen_rtx_SET (pc_rtx, x));
23384   add_reg_br_prob_note (insn, profile_probability::very_unlikely ());
23385 }
23386
23387 /* A subroutine of the atomic operation splitters.  Emit a load-locked
23388    instruction in MODE.  For QI/HImode, possibly use a pattern than includes
23389    the zero_extend operation.  */
23390
23391 static void
23392 emit_load_locked (machine_mode mode, rtx reg, rtx mem)
23393 {
23394   rtx (*fn) (rtx, rtx) = NULL;
23395
23396   switch (mode)
23397     {
23398     case E_QImode:
23399       fn = gen_load_lockedqi;
23400       break;
23401     case E_HImode:
23402       fn = gen_load_lockedhi;
23403       break;
23404     case E_SImode:
23405       if (GET_MODE (mem) == QImode)
23406         fn = gen_load_lockedqi_si;
23407       else if (GET_MODE (mem) == HImode)
23408         fn = gen_load_lockedhi_si;
23409       else
23410         fn = gen_load_lockedsi;
23411       break;
23412     case E_DImode:
23413       fn = gen_load_lockeddi;
23414       break;
23415     case E_TImode:
23416       fn = gen_load_lockedti;
23417       break;
23418     default:
23419       gcc_unreachable ();
23420     }
23421   emit_insn (fn (reg, mem));
23422 }
23423
23424 /* A subroutine of the atomic operation splitters.  Emit a store-conditional
23425    instruction in MODE.  */
23426
23427 static void
23428 emit_store_conditional (machine_mode mode, rtx res, rtx mem, rtx val)
23429 {
23430   rtx (*fn) (rtx, rtx, rtx) = NULL;
23431
23432   switch (mode)
23433     {
23434     case E_QImode:
23435       fn = gen_store_conditionalqi;
23436       break;
23437     case E_HImode:
23438       fn = gen_store_conditionalhi;
23439       break;
23440     case E_SImode:
23441       fn = gen_store_conditionalsi;
23442       break;
23443     case E_DImode:
23444       fn = gen_store_conditionaldi;
23445       break;
23446     case E_TImode:
23447       fn = gen_store_conditionalti;
23448       break;
23449     default:
23450       gcc_unreachable ();
23451     }
23452
23453   /* Emit sync before stwcx. to address PPC405 Erratum.  */
23454   if (PPC405_ERRATUM77)
23455     emit_insn (gen_hwsync ());
23456
23457   emit_insn (fn (res, mem, val));
23458 }
23459
23460 /* Expand barriers before and after a load_locked/store_cond sequence.  */
23461
23462 static rtx
23463 rs6000_pre_atomic_barrier (rtx mem, enum memmodel model)
23464 {
23465   rtx addr = XEXP (mem, 0);
23466
23467   if (!legitimate_indirect_address_p (addr, reload_completed)
23468       && !legitimate_indexed_address_p (addr, reload_completed))
23469     {
23470       addr = force_reg (Pmode, addr);
23471       mem = replace_equiv_address_nv (mem, addr);
23472     }
23473
23474   switch (model)
23475     {
23476     case MEMMODEL_RELAXED:
23477     case MEMMODEL_CONSUME:
23478     case MEMMODEL_ACQUIRE:
23479       break;
23480     case MEMMODEL_RELEASE:
23481     case MEMMODEL_ACQ_REL:
23482       emit_insn (gen_lwsync ());
23483       break;
23484     case MEMMODEL_SEQ_CST:
23485       emit_insn (gen_hwsync ());
23486       break;
23487     default:
23488       gcc_unreachable ();
23489     }
23490   return mem;
23491 }
23492
23493 static void
23494 rs6000_post_atomic_barrier (enum memmodel model)
23495 {
23496   switch (model)
23497     {
23498     case MEMMODEL_RELAXED:
23499     case MEMMODEL_CONSUME:
23500     case MEMMODEL_RELEASE:
23501       break;
23502     case MEMMODEL_ACQUIRE:
23503     case MEMMODEL_ACQ_REL:
23504     case MEMMODEL_SEQ_CST:
23505       emit_insn (gen_isync ());
23506       break;
23507     default:
23508       gcc_unreachable ();
23509     }
23510 }
23511
23512 /* A subroutine of the various atomic expanders.  For sub-word operations,
23513    we must adjust things to operate on SImode.  Given the original MEM,
23514    return a new aligned memory.  Also build and return the quantities by
23515    which to shift and mask.  */
23516
23517 static rtx
23518 rs6000_adjust_atomic_subword (rtx orig_mem, rtx *pshift, rtx *pmask)
23519 {
23520   rtx addr, align, shift, mask, mem;
23521   HOST_WIDE_INT shift_mask;
23522   machine_mode mode = GET_MODE (orig_mem);
23523
23524   /* For smaller modes, we have to implement this via SImode.  */
23525   shift_mask = (mode == QImode ? 0x18 : 0x10);
23526
23527   addr = XEXP (orig_mem, 0);
23528   addr = force_reg (GET_MODE (addr), addr);
23529
23530   /* Aligned memory containing subword.  Generate a new memory.  We
23531      do not want any of the existing MEM_ATTR data, as we're now
23532      accessing memory outside the original object.  */
23533   align = expand_simple_binop (Pmode, AND, addr, GEN_INT (-4),
23534                                NULL_RTX, 1, OPTAB_LIB_WIDEN);
23535   mem = gen_rtx_MEM (SImode, align);
23536   MEM_VOLATILE_P (mem) = MEM_VOLATILE_P (orig_mem);
23537   if (MEM_ALIAS_SET (orig_mem) == ALIAS_SET_MEMORY_BARRIER)
23538     set_mem_alias_set (mem, ALIAS_SET_MEMORY_BARRIER);
23539
23540   /* Shift amount for subword relative to aligned word.  */
23541   shift = gen_reg_rtx (SImode);
23542   addr = gen_lowpart (SImode, addr);
23543   rtx tmp = gen_reg_rtx (SImode);
23544   emit_insn (gen_ashlsi3 (tmp, addr, GEN_INT (3)));
23545   emit_insn (gen_andsi3 (shift, tmp, GEN_INT (shift_mask)));
23546   if (BYTES_BIG_ENDIAN)
23547     shift = expand_simple_binop (SImode, XOR, shift, GEN_INT (shift_mask),
23548                                  shift, 1, OPTAB_LIB_WIDEN);
23549   *pshift = shift;
23550
23551   /* Mask for insertion.  */
23552   mask = expand_simple_binop (SImode, ASHIFT, GEN_INT (GET_MODE_MASK (mode)),
23553                               shift, NULL_RTX, 1, OPTAB_LIB_WIDEN);
23554   *pmask = mask;
23555
23556   return mem;
23557 }
23558
23559 /* A subroutine of the various atomic expanders.  For sub-word operands,
23560    combine OLDVAL and NEWVAL via MASK.  Returns a new pseduo.  */
23561
23562 static rtx
23563 rs6000_mask_atomic_subword (rtx oldval, rtx newval, rtx mask)
23564 {
23565   rtx x;
23566
23567   x = gen_reg_rtx (SImode);
23568   emit_insn (gen_rtx_SET (x, gen_rtx_AND (SImode,
23569                                           gen_rtx_NOT (SImode, mask),
23570                                           oldval)));
23571
23572   x = expand_simple_binop (SImode, IOR, newval, x, x, 1, OPTAB_LIB_WIDEN);
23573
23574   return x;
23575 }
23576
23577 /* A subroutine of the various atomic expanders.  For sub-word operands,
23578    extract WIDE to NARROW via SHIFT.  */
23579
23580 static void
23581 rs6000_finish_atomic_subword (rtx narrow, rtx wide, rtx shift)
23582 {
23583   wide = expand_simple_binop (SImode, LSHIFTRT, wide, shift,
23584                               wide, 1, OPTAB_LIB_WIDEN);
23585   emit_move_insn (narrow, gen_lowpart (GET_MODE (narrow), wide));
23586 }
23587
23588 /* Expand an atomic compare and swap operation.  */
23589
23590 void
23591 rs6000_expand_atomic_compare_and_swap (rtx operands[])
23592 {
23593   rtx boolval, retval, mem, oldval, newval, cond;
23594   rtx label1, label2, x, mask, shift;
23595   machine_mode mode, orig_mode;
23596   enum memmodel mod_s, mod_f;
23597   bool is_weak;
23598
23599   boolval = operands[0];
23600   retval = operands[1];
23601   mem = operands[2];
23602   oldval = operands[3];
23603   newval = operands[4];
23604   is_weak = (INTVAL (operands[5]) != 0);
23605   mod_s = memmodel_base (INTVAL (operands[6]));
23606   mod_f = memmodel_base (INTVAL (operands[7]));
23607   orig_mode = mode = GET_MODE (mem);
23608
23609   mask = shift = NULL_RTX;
23610   if (mode == QImode || mode == HImode)
23611     {
23612       /* Before power8, we didn't have access to lbarx/lharx, so generate a
23613          lwarx and shift/mask operations.  With power8, we need to do the
23614          comparison in SImode, but the store is still done in QI/HImode.  */
23615       oldval = convert_modes (SImode, mode, oldval, 1);
23616
23617       if (!TARGET_SYNC_HI_QI)
23618         {
23619           mem = rs6000_adjust_atomic_subword (mem, &shift, &mask);
23620
23621           /* Shift and mask OLDVAL into position with the word.  */
23622           oldval = expand_simple_binop (SImode, ASHIFT, oldval, shift,
23623                                         NULL_RTX, 1, OPTAB_LIB_WIDEN);
23624
23625           /* Shift and mask NEWVAL into position within the word.  */
23626           newval = convert_modes (SImode, mode, newval, 1);
23627           newval = expand_simple_binop (SImode, ASHIFT, newval, shift,
23628                                         NULL_RTX, 1, OPTAB_LIB_WIDEN);
23629         }
23630
23631       /* Prepare to adjust the return value.  */
23632       retval = gen_reg_rtx (SImode);
23633       mode = SImode;
23634     }
23635   else if (reg_overlap_mentioned_p (retval, oldval))
23636     oldval = copy_to_reg (oldval);
23637
23638   if (mode != TImode && !reg_or_short_operand (oldval, mode))
23639     oldval = copy_to_mode_reg (mode, oldval);
23640
23641   if (reg_overlap_mentioned_p (retval, newval))
23642     newval = copy_to_reg (newval);
23643
23644   mem = rs6000_pre_atomic_barrier (mem, mod_s);
23645
23646   label1 = NULL_RTX;
23647   if (!is_weak)
23648     {
23649       label1 = gen_rtx_LABEL_REF (VOIDmode, gen_label_rtx ());
23650       emit_label (XEXP (label1, 0));
23651     }
23652   label2 = gen_rtx_LABEL_REF (VOIDmode, gen_label_rtx ());
23653
23654   emit_load_locked (mode, retval, mem);
23655
23656   x = retval;
23657   if (mask)
23658     x = expand_simple_binop (SImode, AND, retval, mask,
23659                              NULL_RTX, 1, OPTAB_LIB_WIDEN);
23660
23661   cond = gen_reg_rtx (CCmode);
23662   /* If we have TImode, synthesize a comparison.  */
23663   if (mode != TImode)
23664     x = gen_rtx_COMPARE (CCmode, x, oldval);
23665   else
23666     {
23667       rtx xor1_result = gen_reg_rtx (DImode);
23668       rtx xor2_result = gen_reg_rtx (DImode);
23669       rtx or_result = gen_reg_rtx (DImode);
23670       rtx new_word0 = simplify_gen_subreg (DImode, x, TImode, 0);
23671       rtx new_word1 = simplify_gen_subreg (DImode, x, TImode, 8);
23672       rtx old_word0 = simplify_gen_subreg (DImode, oldval, TImode, 0);
23673       rtx old_word1 = simplify_gen_subreg (DImode, oldval, TImode, 8);
23674
23675       emit_insn (gen_xordi3 (xor1_result, new_word0, old_word0));
23676       emit_insn (gen_xordi3 (xor2_result, new_word1, old_word1));
23677       emit_insn (gen_iordi3 (or_result, xor1_result, xor2_result));
23678       x = gen_rtx_COMPARE (CCmode, or_result, const0_rtx);
23679     }
23680
23681   emit_insn (gen_rtx_SET (cond, x));
23682
23683   x = gen_rtx_NE (VOIDmode, cond, const0_rtx);
23684   emit_unlikely_jump (x, label2);
23685
23686   x = newval;
23687   if (mask)
23688     x = rs6000_mask_atomic_subword (retval, newval, mask);
23689
23690   emit_store_conditional (orig_mode, cond, mem, x);
23691
23692   if (!is_weak)
23693     {
23694       x = gen_rtx_NE (VOIDmode, cond, const0_rtx);
23695       emit_unlikely_jump (x, label1);
23696     }
23697
23698   if (!is_mm_relaxed (mod_f))
23699     emit_label (XEXP (label2, 0));
23700
23701   rs6000_post_atomic_barrier (mod_s);
23702
23703   if (is_mm_relaxed (mod_f))
23704     emit_label (XEXP (label2, 0));
23705
23706   if (shift)
23707     rs6000_finish_atomic_subword (operands[1], retval, shift);
23708   else if (mode != GET_MODE (operands[1]))
23709     convert_move (operands[1], retval, 1);
23710
23711   /* In all cases, CR0 contains EQ on success, and NE on failure.  */
23712   x = gen_rtx_EQ (SImode, cond, const0_rtx);
23713   emit_insn (gen_rtx_SET (boolval, x));
23714 }
23715
23716 /* Expand an atomic exchange operation.  */
23717
23718 void
23719 rs6000_expand_atomic_exchange (rtx operands[])
23720 {
23721   rtx retval, mem, val, cond;
23722   machine_mode mode;
23723   enum memmodel model;
23724   rtx label, x, mask, shift;
23725
23726   retval = operands[0];
23727   mem = operands[1];
23728   val = operands[2];
23729   model = memmodel_base (INTVAL (operands[3]));
23730   mode = GET_MODE (mem);
23731
23732   mask = shift = NULL_RTX;
23733   if (!TARGET_SYNC_HI_QI && (mode == QImode || mode == HImode))
23734     {
23735       mem = rs6000_adjust_atomic_subword (mem, &shift, &mask);
23736
23737       /* Shift and mask VAL into position with the word.  */
23738       val = convert_modes (SImode, mode, val, 1);
23739       val = expand_simple_binop (SImode, ASHIFT, val, shift,
23740                                  NULL_RTX, 1, OPTAB_LIB_WIDEN);
23741
23742       /* Prepare to adjust the return value.  */
23743       retval = gen_reg_rtx (SImode);
23744       mode = SImode;
23745     }
23746
23747   mem = rs6000_pre_atomic_barrier (mem, model);
23748
23749   label = gen_rtx_LABEL_REF (VOIDmode, gen_label_rtx ());
23750   emit_label (XEXP (label, 0));
23751
23752   emit_load_locked (mode, retval, mem);
23753
23754   x = val;
23755   if (mask)
23756     x = rs6000_mask_atomic_subword (retval, val, mask);
23757
23758   cond = gen_reg_rtx (CCmode);
23759   emit_store_conditional (mode, cond, mem, x);
23760
23761   x = gen_rtx_NE (VOIDmode, cond, const0_rtx);
23762   emit_unlikely_jump (x, label);
23763
23764   rs6000_post_atomic_barrier (model);
23765
23766   if (shift)
23767     rs6000_finish_atomic_subword (operands[0], retval, shift);
23768 }
23769
23770 /* Expand an atomic fetch-and-operate pattern.  CODE is the binary operation
23771    to perform.  MEM is the memory on which to operate.  VAL is the second
23772    operand of the binary operator.  BEFORE and AFTER are optional locations to
23773    return the value of MEM either before of after the operation.  MODEL_RTX
23774    is a CONST_INT containing the memory model to use.  */
23775
23776 void
23777 rs6000_expand_atomic_op (enum rtx_code code, rtx mem, rtx val,
23778                          rtx orig_before, rtx orig_after, rtx model_rtx)
23779 {
23780   enum memmodel model = memmodel_base (INTVAL (model_rtx));
23781   machine_mode mode = GET_MODE (mem);
23782   machine_mode store_mode = mode;
23783   rtx label, x, cond, mask, shift;
23784   rtx before = orig_before, after = orig_after;
23785
23786   mask = shift = NULL_RTX;
23787   /* On power8, we want to use SImode for the operation.  On previous systems,
23788      use the operation in a subword and shift/mask to get the proper byte or
23789      halfword.  */
23790   if (mode == QImode || mode == HImode)
23791     {
23792       if (TARGET_SYNC_HI_QI)
23793         {
23794           val = convert_modes (SImode, mode, val, 1);
23795
23796           /* Prepare to adjust the return value.  */
23797           before = gen_reg_rtx (SImode);
23798           if (after)
23799             after = gen_reg_rtx (SImode);
23800           mode = SImode;
23801         }
23802       else
23803         {
23804           mem = rs6000_adjust_atomic_subword (mem, &shift, &mask);
23805
23806           /* Shift and mask VAL into position with the word.  */
23807           val = convert_modes (SImode, mode, val, 1);
23808           val = expand_simple_binop (SImode, ASHIFT, val, shift,
23809                                      NULL_RTX, 1, OPTAB_LIB_WIDEN);
23810
23811           switch (code)
23812             {
23813             case IOR:
23814             case XOR:
23815               /* We've already zero-extended VAL.  That is sufficient to
23816                  make certain that it does not affect other bits.  */
23817               mask = NULL;
23818               break;
23819
23820             case AND:
23821               /* If we make certain that all of the other bits in VAL are
23822                  set, that will be sufficient to not affect other bits.  */
23823               x = gen_rtx_NOT (SImode, mask);
23824               x = gen_rtx_IOR (SImode, x, val);
23825               emit_insn (gen_rtx_SET (val, x));
23826               mask = NULL;
23827               break;
23828
23829             case NOT:
23830             case PLUS:
23831             case MINUS:
23832               /* These will all affect bits outside the field and need
23833                  adjustment via MASK within the loop.  */
23834               break;
23835
23836             default:
23837               gcc_unreachable ();
23838             }
23839
23840           /* Prepare to adjust the return value.  */
23841           before = gen_reg_rtx (SImode);
23842           if (after)
23843             after = gen_reg_rtx (SImode);
23844           store_mode = mode = SImode;
23845         }
23846     }
23847
23848   mem = rs6000_pre_atomic_barrier (mem, model);
23849
23850   label = gen_label_rtx ();
23851   emit_label (label);
23852   label = gen_rtx_LABEL_REF (VOIDmode, label);
23853
23854   if (before == NULL_RTX)
23855     before = gen_reg_rtx (mode);
23856
23857   emit_load_locked (mode, before, mem);
23858
23859   if (code == NOT)
23860     {
23861       x = expand_simple_binop (mode, AND, before, val,
23862                                NULL_RTX, 1, OPTAB_LIB_WIDEN);
23863       after = expand_simple_unop (mode, NOT, x, after, 1);
23864     }
23865   else
23866     {
23867       after = expand_simple_binop (mode, code, before, val,
23868                                    after, 1, OPTAB_LIB_WIDEN);
23869     }
23870
23871   x = after;
23872   if (mask)
23873     {
23874       x = expand_simple_binop (SImode, AND, after, mask,
23875                                NULL_RTX, 1, OPTAB_LIB_WIDEN);
23876       x = rs6000_mask_atomic_subword (before, x, mask);
23877     }
23878   else if (store_mode != mode)
23879     x = convert_modes (store_mode, mode, x, 1);
23880
23881   cond = gen_reg_rtx (CCmode);
23882   emit_store_conditional (store_mode, cond, mem, x);
23883
23884   x = gen_rtx_NE (VOIDmode, cond, const0_rtx);
23885   emit_unlikely_jump (x, label);
23886
23887   rs6000_post_atomic_barrier (model);
23888
23889   if (shift)
23890     {
23891       /* QImode/HImode on machines without lbarx/lharx where we do a lwarx and
23892          then do the calcuations in a SImode register.  */
23893       if (orig_before)
23894         rs6000_finish_atomic_subword (orig_before, before, shift);
23895       if (orig_after)
23896         rs6000_finish_atomic_subword (orig_after, after, shift);
23897     }
23898   else if (store_mode != mode)
23899     {
23900       /* QImode/HImode on machines with lbarx/lharx where we do the native
23901          operation and then do the calcuations in a SImode register.  */
23902       if (orig_before)
23903         convert_move (orig_before, before, 1);
23904       if (orig_after)
23905         convert_move (orig_after, after, 1);
23906     }
23907   else if (orig_after && after != orig_after)
23908     emit_move_insn (orig_after, after);
23909 }
23910
23911 /* Emit instructions to move SRC to DST.  Called by splitters for
23912    multi-register moves.  It will emit at most one instruction for
23913    each register that is accessed; that is, it won't emit li/lis pairs
23914    (or equivalent for 64-bit code).  One of SRC or DST must be a hard
23915    register.  */
23916
23917 void
23918 rs6000_split_multireg_move (rtx dst, rtx src)
23919 {
23920   /* The register number of the first register being moved.  */
23921   int reg;
23922   /* The mode that is to be moved.  */
23923   machine_mode mode;
23924   /* The mode that the move is being done in, and its size.  */
23925   machine_mode reg_mode;
23926   int reg_mode_size;
23927   /* The number of registers that will be moved.  */
23928   int nregs;
23929
23930   reg = REG_P (dst) ? REGNO (dst) : REGNO (src);
23931   mode = GET_MODE (dst);
23932   nregs = hard_regno_nregs (reg, mode);
23933   if (FP_REGNO_P (reg))
23934     reg_mode = DECIMAL_FLOAT_MODE_P (mode) ? DDmode : 
23935         ((TARGET_HARD_FLOAT && TARGET_DOUBLE_FLOAT) ? DFmode : SFmode);
23936   else if (ALTIVEC_REGNO_P (reg))
23937     reg_mode = V16QImode;
23938   else
23939     reg_mode = word_mode;
23940   reg_mode_size = GET_MODE_SIZE (reg_mode);
23941
23942   gcc_assert (reg_mode_size * nregs == GET_MODE_SIZE (mode));
23943
23944   /* TDmode residing in FP registers is special, since the ISA requires that
23945      the lower-numbered word of a register pair is always the most significant
23946      word, even in little-endian mode.  This does not match the usual subreg
23947      semantics, so we cannnot use simplify_gen_subreg in those cases.  Access
23948      the appropriate constituent registers "by hand" in little-endian mode.
23949
23950      Note we do not need to check for destructive overlap here since TDmode
23951      can only reside in even/odd register pairs.  */
23952   if (FP_REGNO_P (reg) && DECIMAL_FLOAT_MODE_P (mode) && !BYTES_BIG_ENDIAN)
23953     {
23954       rtx p_src, p_dst;
23955       int i;
23956
23957       for (i = 0; i < nregs; i++)
23958         {
23959           if (REG_P (src) && FP_REGNO_P (REGNO (src)))
23960             p_src = gen_rtx_REG (reg_mode, REGNO (src) + nregs - 1 - i);
23961           else
23962             p_src = simplify_gen_subreg (reg_mode, src, mode,
23963                                          i * reg_mode_size);
23964
23965           if (REG_P (dst) && FP_REGNO_P (REGNO (dst)))
23966             p_dst = gen_rtx_REG (reg_mode, REGNO (dst) + nregs - 1 - i);
23967           else
23968             p_dst = simplify_gen_subreg (reg_mode, dst, mode,
23969                                          i * reg_mode_size);
23970
23971           emit_insn (gen_rtx_SET (p_dst, p_src));
23972         }
23973
23974       return;
23975     }
23976
23977   if (REG_P (src) && REG_P (dst) && (REGNO (src) < REGNO (dst)))
23978     {
23979       /* Move register range backwards, if we might have destructive
23980          overlap.  */
23981       int i;
23982       for (i = nregs - 1; i >= 0; i--)
23983         emit_insn (gen_rtx_SET (simplify_gen_subreg (reg_mode, dst, mode,
23984                                                      i * reg_mode_size),
23985                                 simplify_gen_subreg (reg_mode, src, mode,
23986                                                      i * reg_mode_size)));
23987     }
23988   else
23989     {
23990       int i;
23991       int j = -1;
23992       bool used_update = false;
23993       rtx restore_basereg = NULL_RTX;
23994
23995       if (MEM_P (src) && INT_REGNO_P (reg))
23996         {
23997           rtx breg;
23998
23999           if (GET_CODE (XEXP (src, 0)) == PRE_INC
24000               || GET_CODE (XEXP (src, 0)) == PRE_DEC)
24001             {
24002               rtx delta_rtx;
24003               breg = XEXP (XEXP (src, 0), 0);
24004               delta_rtx = (GET_CODE (XEXP (src, 0)) == PRE_INC
24005                            ? GEN_INT (GET_MODE_SIZE (GET_MODE (src)))
24006                            : GEN_INT (-GET_MODE_SIZE (GET_MODE (src))));
24007               emit_insn (gen_add3_insn (breg, breg, delta_rtx));
24008               src = replace_equiv_address (src, breg);
24009             }
24010           else if (! rs6000_offsettable_memref_p (src, reg_mode))
24011             {
24012               if (GET_CODE (XEXP (src, 0)) == PRE_MODIFY)
24013                 {
24014                   rtx basereg = XEXP (XEXP (src, 0), 0);
24015                   if (TARGET_UPDATE)
24016                     {
24017                       rtx ndst = simplify_gen_subreg (reg_mode, dst, mode, 0);
24018                       emit_insn (gen_rtx_SET (ndst,
24019                                               gen_rtx_MEM (reg_mode,
24020                                                            XEXP (src, 0))));
24021                       used_update = true;
24022                     }
24023                   else
24024                     emit_insn (gen_rtx_SET (basereg,
24025                                             XEXP (XEXP (src, 0), 1)));
24026                   src = replace_equiv_address (src, basereg);
24027                 }
24028               else
24029                 {
24030                   rtx basereg = gen_rtx_REG (Pmode, reg);
24031                   emit_insn (gen_rtx_SET (basereg, XEXP (src, 0)));
24032                   src = replace_equiv_address (src, basereg);
24033                 }
24034             }
24035
24036           breg = XEXP (src, 0);
24037           if (GET_CODE (breg) == PLUS || GET_CODE (breg) == LO_SUM)
24038             breg = XEXP (breg, 0);
24039
24040           /* If the base register we are using to address memory is
24041              also a destination reg, then change that register last.  */
24042           if (REG_P (breg)
24043               && REGNO (breg) >= REGNO (dst)
24044               && REGNO (breg) < REGNO (dst) + nregs)
24045             j = REGNO (breg) - REGNO (dst);
24046         }
24047       else if (MEM_P (dst) && INT_REGNO_P (reg))
24048         {
24049           rtx breg;
24050
24051           if (GET_CODE (XEXP (dst, 0)) == PRE_INC
24052               || GET_CODE (XEXP (dst, 0)) == PRE_DEC)
24053             {
24054               rtx delta_rtx;
24055               breg = XEXP (XEXP (dst, 0), 0);
24056               delta_rtx = (GET_CODE (XEXP (dst, 0)) == PRE_INC
24057                            ? GEN_INT (GET_MODE_SIZE (GET_MODE (dst)))
24058                            : GEN_INT (-GET_MODE_SIZE (GET_MODE (dst))));
24059
24060               /* We have to update the breg before doing the store.
24061                  Use store with update, if available.  */
24062
24063               if (TARGET_UPDATE)
24064                 {
24065                   rtx nsrc = simplify_gen_subreg (reg_mode, src, mode, 0);
24066                   emit_insn (TARGET_32BIT
24067                              ? (TARGET_POWERPC64
24068                                 ? gen_movdi_si_update (breg, breg, delta_rtx, nsrc)
24069                                 : gen_movsi_update (breg, breg, delta_rtx, nsrc))
24070                              : gen_movdi_di_update (breg, breg, delta_rtx, nsrc));
24071                   used_update = true;
24072                 }
24073               else
24074                 emit_insn (gen_add3_insn (breg, breg, delta_rtx));
24075               dst = replace_equiv_address (dst, breg);
24076             }
24077           else if (!rs6000_offsettable_memref_p (dst, reg_mode)
24078                    && GET_CODE (XEXP (dst, 0)) != LO_SUM)
24079             {
24080               if (GET_CODE (XEXP (dst, 0)) == PRE_MODIFY)
24081                 {
24082                   rtx basereg = XEXP (XEXP (dst, 0), 0);
24083                   if (TARGET_UPDATE)
24084                     {
24085                       rtx nsrc = simplify_gen_subreg (reg_mode, src, mode, 0);
24086                       emit_insn (gen_rtx_SET (gen_rtx_MEM (reg_mode,
24087                                                            XEXP (dst, 0)),
24088                                               nsrc));
24089                       used_update = true;
24090                     }
24091                   else
24092                     emit_insn (gen_rtx_SET (basereg,
24093                                             XEXP (XEXP (dst, 0), 1)));
24094                   dst = replace_equiv_address (dst, basereg);
24095                 }
24096               else
24097                 {
24098                   rtx basereg = XEXP (XEXP (dst, 0), 0);
24099                   rtx offsetreg = XEXP (XEXP (dst, 0), 1);
24100                   gcc_assert (GET_CODE (XEXP (dst, 0)) == PLUS
24101                               && REG_P (basereg)
24102                               && REG_P (offsetreg)
24103                               && REGNO (basereg) != REGNO (offsetreg));
24104                   if (REGNO (basereg) == 0)
24105                     {
24106                       rtx tmp = offsetreg;
24107                       offsetreg = basereg;
24108                       basereg = tmp;
24109                     }
24110                   emit_insn (gen_add3_insn (basereg, basereg, offsetreg));
24111                   restore_basereg = gen_sub3_insn (basereg, basereg, offsetreg);
24112                   dst = replace_equiv_address (dst, basereg);
24113                 }
24114             }
24115           else if (GET_CODE (XEXP (dst, 0)) != LO_SUM)
24116             gcc_assert (rs6000_offsettable_memref_p (dst, reg_mode));
24117         }
24118
24119       for (i = 0; i < nregs; i++)
24120         {
24121           /* Calculate index to next subword.  */
24122           ++j;
24123           if (j == nregs)
24124             j = 0;
24125
24126           /* If compiler already emitted move of first word by
24127              store with update, no need to do anything.  */
24128           if (j == 0 && used_update)
24129             continue;
24130
24131           emit_insn (gen_rtx_SET (simplify_gen_subreg (reg_mode, dst, mode,
24132                                                        j * reg_mode_size),
24133                                   simplify_gen_subreg (reg_mode, src, mode,
24134                                                        j * reg_mode_size)));
24135         }
24136       if (restore_basereg != NULL_RTX)
24137         emit_insn (restore_basereg);
24138     }
24139 }
24140
24141 \f
24142 /* This page contains routines that are used to determine what the
24143    function prologue and epilogue code will do and write them out.  */
24144
24145 /* Determine whether the REG is really used.  */
24146
24147 static bool
24148 save_reg_p (int reg)
24149 {
24150   /* We need to mark the PIC offset register live for the same conditions
24151      as it is set up, or otherwise it won't be saved before we clobber it.  */
24152
24153   if (reg == RS6000_PIC_OFFSET_TABLE_REGNUM && !TARGET_SINGLE_PIC_BASE)
24154     {
24155       /* When calling eh_return, we must return true for all the cases
24156          where conditional_register_usage marks the PIC offset reg
24157          call used.  */
24158       if (TARGET_TOC && TARGET_MINIMAL_TOC
24159           && (crtl->calls_eh_return
24160               || df_regs_ever_live_p (reg)
24161               || !constant_pool_empty_p ()))
24162         return true;
24163
24164       if ((DEFAULT_ABI == ABI_V4 || DEFAULT_ABI == ABI_DARWIN)
24165           && flag_pic)
24166         return true;
24167     }
24168
24169   return !call_used_regs[reg] && df_regs_ever_live_p (reg);
24170 }
24171
24172 /* Return the first fixed-point register that is required to be
24173    saved. 32 if none.  */
24174
24175 int
24176 first_reg_to_save (void)
24177 {
24178   int first_reg;
24179
24180   /* Find lowest numbered live register.  */
24181   for (first_reg = 13; first_reg <= 31; first_reg++)
24182     if (save_reg_p (first_reg))
24183       break;
24184
24185 #if TARGET_MACHO
24186   if (flag_pic
24187       && crtl->uses_pic_offset_table
24188       && first_reg > RS6000_PIC_OFFSET_TABLE_REGNUM)
24189     return RS6000_PIC_OFFSET_TABLE_REGNUM;
24190 #endif
24191
24192   return first_reg;
24193 }
24194
24195 /* Similar, for FP regs.  */
24196
24197 int
24198 first_fp_reg_to_save (void)
24199 {
24200   int first_reg;
24201
24202   /* Find lowest numbered live register.  */
24203   for (first_reg = 14 + 32; first_reg <= 63; first_reg++)
24204     if (save_reg_p (first_reg))
24205       break;
24206
24207   return first_reg;
24208 }
24209
24210 /* Similar, for AltiVec regs.  */
24211
24212 static int
24213 first_altivec_reg_to_save (void)
24214 {
24215   int i;
24216
24217   /* Stack frame remains as is unless we are in AltiVec ABI.  */
24218   if (! TARGET_ALTIVEC_ABI)
24219     return LAST_ALTIVEC_REGNO + 1;
24220
24221   /* On Darwin, the unwind routines are compiled without
24222      TARGET_ALTIVEC, and use save_world to save/restore the
24223      altivec registers when necessary.  */
24224   if (DEFAULT_ABI == ABI_DARWIN && crtl->calls_eh_return
24225       && ! TARGET_ALTIVEC)
24226     return FIRST_ALTIVEC_REGNO + 20;
24227
24228   /* Find lowest numbered live register.  */
24229   for (i = FIRST_ALTIVEC_REGNO + 20; i <= LAST_ALTIVEC_REGNO; ++i)
24230     if (save_reg_p (i))
24231       break;
24232
24233   return i;
24234 }
24235
24236 /* Return a 32-bit mask of the AltiVec registers we need to set in
24237    VRSAVE.  Bit n of the return value is 1 if Vn is live.  The MSB in
24238    the 32-bit word is 0.  */
24239
24240 static unsigned int
24241 compute_vrsave_mask (void)
24242 {
24243   unsigned int i, mask = 0;
24244
24245   /* On Darwin, the unwind routines are compiled without
24246      TARGET_ALTIVEC, and use save_world to save/restore the
24247      call-saved altivec registers when necessary.  */
24248   if (DEFAULT_ABI == ABI_DARWIN && crtl->calls_eh_return
24249       && ! TARGET_ALTIVEC)
24250     mask |= 0xFFF;
24251
24252   /* First, find out if we use _any_ altivec registers.  */
24253   for (i = FIRST_ALTIVEC_REGNO; i <= LAST_ALTIVEC_REGNO; ++i)
24254     if (df_regs_ever_live_p (i))
24255       mask |= ALTIVEC_REG_BIT (i);
24256
24257   if (mask == 0)
24258     return mask;
24259
24260   /* Next, remove the argument registers from the set.  These must
24261      be in the VRSAVE mask set by the caller, so we don't need to add
24262      them in again.  More importantly, the mask we compute here is
24263      used to generate CLOBBERs in the set_vrsave insn, and we do not
24264      wish the argument registers to die.  */
24265   for (i = ALTIVEC_ARG_MIN_REG; i < (unsigned) crtl->args.info.vregno; i++)
24266     mask &= ~ALTIVEC_REG_BIT (i);
24267
24268   /* Similarly, remove the return value from the set.  */
24269   {
24270     bool yes = false;
24271     diddle_return_value (is_altivec_return_reg, &yes);
24272     if (yes)
24273       mask &= ~ALTIVEC_REG_BIT (ALTIVEC_ARG_RETURN);
24274   }
24275
24276   return mask;
24277 }
24278
24279 /* For a very restricted set of circumstances, we can cut down the
24280    size of prologues/epilogues by calling our own save/restore-the-world
24281    routines.  */
24282
24283 static void
24284 compute_save_world_info (rs6000_stack_t *info)
24285 {
24286   info->world_save_p = 1;
24287   info->world_save_p
24288     = (WORLD_SAVE_P (info)
24289        && DEFAULT_ABI == ABI_DARWIN
24290        && !cfun->has_nonlocal_label
24291        && info->first_fp_reg_save == FIRST_SAVED_FP_REGNO
24292        && info->first_gp_reg_save == FIRST_SAVED_GP_REGNO
24293        && info->first_altivec_reg_save == FIRST_SAVED_ALTIVEC_REGNO
24294        && info->cr_save_p);
24295
24296   /* This will not work in conjunction with sibcalls.  Make sure there
24297      are none.  (This check is expensive, but seldom executed.) */
24298   if (WORLD_SAVE_P (info))
24299     {
24300       rtx_insn *insn;
24301       for (insn = get_last_insn_anywhere (); insn; insn = PREV_INSN (insn))
24302         if (CALL_P (insn) && SIBLING_CALL_P (insn))
24303           {
24304             info->world_save_p = 0;
24305             break;
24306           }
24307     }
24308
24309   if (WORLD_SAVE_P (info))
24310     {
24311       /* Even if we're not touching VRsave, make sure there's room on the
24312          stack for it, if it looks like we're calling SAVE_WORLD, which
24313          will attempt to save it. */
24314       info->vrsave_size  = 4;
24315
24316       /* If we are going to save the world, we need to save the link register too.  */
24317       info->lr_save_p = 1;
24318
24319       /* "Save" the VRsave register too if we're saving the world.  */
24320       if (info->vrsave_mask == 0)
24321         info->vrsave_mask = compute_vrsave_mask ();
24322
24323       /* Because the Darwin register save/restore routines only handle
24324          F14 .. F31 and V20 .. V31 as per the ABI, perform a consistency
24325          check.  */
24326       gcc_assert (info->first_fp_reg_save >= FIRST_SAVED_FP_REGNO
24327                   && (info->first_altivec_reg_save
24328                       >= FIRST_SAVED_ALTIVEC_REGNO));
24329     }
24330
24331   return;
24332 }
24333
24334
24335 static void
24336 is_altivec_return_reg (rtx reg, void *xyes)
24337 {
24338   bool *yes = (bool *) xyes;
24339   if (REGNO (reg) == ALTIVEC_ARG_RETURN)
24340     *yes = true;
24341 }
24342
24343 \f
24344 /* Return whether REG is a global user reg or has been specifed by
24345    -ffixed-REG.  We should not restore these, and so cannot use
24346    lmw or out-of-line restore functions if there are any.  We also
24347    can't save them (well, emit frame notes for them), because frame
24348    unwinding during exception handling will restore saved registers.  */
24349
24350 static bool
24351 fixed_reg_p (int reg)
24352 {
24353   /* Ignore fixed_regs[RS6000_PIC_OFFSET_TABLE_REGNUM] when the
24354      backend sets it, overriding anything the user might have given.  */
24355   if (reg == RS6000_PIC_OFFSET_TABLE_REGNUM
24356       && ((DEFAULT_ABI == ABI_V4 && flag_pic)
24357           || (DEFAULT_ABI == ABI_DARWIN && flag_pic)
24358           || (TARGET_TOC && TARGET_MINIMAL_TOC)))
24359     return false;
24360
24361   return fixed_regs[reg];
24362 }
24363
24364 /* Determine the strategy for savings/restoring registers.  */
24365
24366 enum {
24367   SAVE_MULTIPLE = 0x1,
24368   SAVE_INLINE_GPRS = 0x2,
24369   SAVE_INLINE_FPRS = 0x4,
24370   SAVE_NOINLINE_GPRS_SAVES_LR = 0x8,
24371   SAVE_NOINLINE_FPRS_SAVES_LR = 0x10,
24372   SAVE_INLINE_VRS = 0x20,
24373   REST_MULTIPLE = 0x100,
24374   REST_INLINE_GPRS = 0x200,
24375   REST_INLINE_FPRS = 0x400,
24376   REST_NOINLINE_FPRS_DOESNT_RESTORE_LR = 0x800,
24377   REST_INLINE_VRS = 0x1000
24378 };
24379
24380 static int
24381 rs6000_savres_strategy (rs6000_stack_t *info,
24382                         bool using_static_chain_p)
24383 {
24384   int strategy = 0;
24385
24386   /* Select between in-line and out-of-line save and restore of regs.
24387      First, all the obvious cases where we don't use out-of-line.  */
24388   if (crtl->calls_eh_return
24389       || cfun->machine->ra_need_lr)
24390     strategy |= (SAVE_INLINE_FPRS | REST_INLINE_FPRS
24391                  | SAVE_INLINE_GPRS | REST_INLINE_GPRS
24392                  | SAVE_INLINE_VRS | REST_INLINE_VRS);
24393
24394   if (info->first_gp_reg_save == 32)
24395     strategy |= SAVE_INLINE_GPRS | REST_INLINE_GPRS;
24396
24397   if (info->first_fp_reg_save == 64
24398       /* The out-of-line FP routines use double-precision stores;
24399          we can't use those routines if we don't have such stores.  */
24400       || (TARGET_HARD_FLOAT && !TARGET_DOUBLE_FLOAT))
24401     strategy |= SAVE_INLINE_FPRS | REST_INLINE_FPRS;
24402
24403   if (info->first_altivec_reg_save == LAST_ALTIVEC_REGNO + 1)
24404     strategy |= SAVE_INLINE_VRS | REST_INLINE_VRS;
24405
24406   /* Define cutoff for using out-of-line functions to save registers.  */
24407   if (DEFAULT_ABI == ABI_V4 || TARGET_ELF)
24408     {
24409       if (!optimize_size)
24410         {
24411           strategy |= SAVE_INLINE_FPRS | REST_INLINE_FPRS;
24412           strategy |= SAVE_INLINE_GPRS | REST_INLINE_GPRS;
24413           strategy |= SAVE_INLINE_VRS | REST_INLINE_VRS;
24414         }
24415       else
24416         {
24417           /* Prefer out-of-line restore if it will exit.  */
24418           if (info->first_fp_reg_save > 61)
24419             strategy |= SAVE_INLINE_FPRS;
24420           if (info->first_gp_reg_save > 29)
24421             {
24422               if (info->first_fp_reg_save == 64)
24423                 strategy |= SAVE_INLINE_GPRS;
24424               else
24425                 strategy |= SAVE_INLINE_GPRS | REST_INLINE_GPRS;
24426             }
24427           if (info->first_altivec_reg_save == LAST_ALTIVEC_REGNO)
24428             strategy |= SAVE_INLINE_VRS | REST_INLINE_VRS;
24429         }
24430     }
24431   else if (DEFAULT_ABI == ABI_DARWIN)
24432     {
24433       if (info->first_fp_reg_save > 60)
24434         strategy |= SAVE_INLINE_FPRS | REST_INLINE_FPRS;
24435       if (info->first_gp_reg_save > 29)
24436         strategy |= SAVE_INLINE_GPRS | REST_INLINE_GPRS;
24437       strategy |= SAVE_INLINE_VRS | REST_INLINE_VRS;
24438     }
24439   else
24440     {
24441       gcc_checking_assert (DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2);
24442       if ((flag_shrink_wrap_separate && optimize_function_for_speed_p (cfun))
24443           || info->first_fp_reg_save > 61)
24444         strategy |= SAVE_INLINE_FPRS | REST_INLINE_FPRS;
24445       strategy |= SAVE_INLINE_GPRS | REST_INLINE_GPRS;
24446       strategy |= SAVE_INLINE_VRS | REST_INLINE_VRS;
24447     }
24448
24449   /* Don't bother to try to save things out-of-line if r11 is occupied
24450      by the static chain.  It would require too much fiddling and the
24451      static chain is rarely used anyway.  FPRs are saved w.r.t the stack
24452      pointer on Darwin, and AIX uses r1 or r12.  */
24453   if (using_static_chain_p
24454       && (DEFAULT_ABI == ABI_V4 || DEFAULT_ABI == ABI_DARWIN))
24455     strategy |= ((DEFAULT_ABI == ABI_DARWIN ? 0 : SAVE_INLINE_FPRS)
24456                  | SAVE_INLINE_GPRS
24457                  | SAVE_INLINE_VRS);
24458
24459   /* Don't ever restore fixed regs.  That means we can't use the
24460      out-of-line register restore functions if a fixed reg is in the
24461      range of regs restored.   */
24462   if (!(strategy & REST_INLINE_FPRS))
24463     for (int i = info->first_fp_reg_save; i < 64; i++)
24464       if (fixed_regs[i])
24465         {
24466           strategy |= REST_INLINE_FPRS;
24467           break;
24468         }
24469
24470   /* We can only use the out-of-line routines to restore fprs if we've
24471      saved all the registers from first_fp_reg_save in the prologue.
24472      Otherwise, we risk loading garbage.  Of course, if we have saved
24473      out-of-line then we know we haven't skipped any fprs.  */
24474   if ((strategy & SAVE_INLINE_FPRS)
24475       && !(strategy & REST_INLINE_FPRS))
24476     for (int i = info->first_fp_reg_save; i < 64; i++)
24477       if (!save_reg_p (i))
24478         {
24479           strategy |= REST_INLINE_FPRS;
24480           break;
24481         }
24482
24483   /* Similarly, for altivec regs.  */
24484   if (!(strategy & REST_INLINE_VRS))
24485     for (int i = info->first_altivec_reg_save; i < LAST_ALTIVEC_REGNO + 1; i++)
24486       if (fixed_regs[i])
24487         {
24488           strategy |= REST_INLINE_VRS;
24489           break;
24490         }
24491
24492   if ((strategy & SAVE_INLINE_VRS)
24493       && !(strategy & REST_INLINE_VRS))
24494     for (int i = info->first_altivec_reg_save; i < LAST_ALTIVEC_REGNO + 1; i++)
24495       if (!save_reg_p (i))
24496         {
24497           strategy |= REST_INLINE_VRS;
24498           break;
24499         }
24500
24501   /* info->lr_save_p isn't yet set if the only reason lr needs to be
24502      saved is an out-of-line save or restore.  Set up the value for
24503      the next test (excluding out-of-line gprs).  */
24504   bool lr_save_p = (info->lr_save_p
24505                     || !(strategy & SAVE_INLINE_FPRS)
24506                     || !(strategy & SAVE_INLINE_VRS)
24507                     || !(strategy & REST_INLINE_FPRS)
24508                     || !(strategy & REST_INLINE_VRS));
24509
24510   if (TARGET_MULTIPLE
24511       && !TARGET_POWERPC64
24512       && info->first_gp_reg_save < 31
24513       && !(flag_shrink_wrap
24514            && flag_shrink_wrap_separate
24515            && optimize_function_for_speed_p (cfun)))
24516     {
24517       int count = 0;
24518       for (int i = info->first_gp_reg_save; i < 32; i++)
24519         if (save_reg_p (i))
24520           count++;
24521
24522       if (count <= 1)
24523         /* Don't use store multiple if only one reg needs to be
24524            saved.  This can occur for example when the ABI_V4 pic reg
24525            (r30) needs to be saved to make calls, but r31 is not
24526            used.  */
24527         strategy |= SAVE_INLINE_GPRS | REST_INLINE_GPRS;
24528       else
24529         {
24530           /* Prefer store multiple for saves over out-of-line
24531              routines, since the store-multiple instruction will
24532              always be smaller.  */
24533           strategy |= SAVE_INLINE_GPRS | SAVE_MULTIPLE;
24534
24535           /* The situation is more complicated with load multiple.
24536              We'd prefer to use the out-of-line routines for restores,
24537              since the "exit" out-of-line routines can handle the
24538              restore of LR and the frame teardown.  However if doesn't
24539              make sense to use the out-of-line routine if that is the
24540              only reason we'd need to save LR, and we can't use the
24541              "exit" out-of-line gpr restore if we have saved some
24542              fprs; In those cases it is advantageous to use load
24543              multiple when available.  */
24544           if (info->first_fp_reg_save != 64 || !lr_save_p)
24545             strategy |= REST_INLINE_GPRS | REST_MULTIPLE;
24546         }
24547     }
24548
24549   /* Using the "exit" out-of-line routine does not improve code size
24550      if using it would require lr to be saved and if only saving one
24551      or two gprs.  */
24552   else if (!lr_save_p && info->first_gp_reg_save > 29)
24553     strategy |= SAVE_INLINE_GPRS | REST_INLINE_GPRS;
24554
24555   /* Don't ever restore fixed regs.  */
24556   if ((strategy & (REST_INLINE_GPRS | REST_MULTIPLE)) != REST_INLINE_GPRS)
24557     for (int i = info->first_gp_reg_save; i < 32; i++)
24558       if (fixed_reg_p (i))
24559         {
24560           strategy |= REST_INLINE_GPRS;
24561           strategy &= ~REST_MULTIPLE;
24562           break;
24563         }
24564
24565   /* We can only use load multiple or the out-of-line routines to
24566      restore gprs if we've saved all the registers from
24567      first_gp_reg_save.  Otherwise, we risk loading garbage.
24568      Of course, if we have saved out-of-line or used stmw then we know
24569      we haven't skipped any gprs.  */
24570   if ((strategy & (SAVE_INLINE_GPRS | SAVE_MULTIPLE)) == SAVE_INLINE_GPRS
24571       && (strategy & (REST_INLINE_GPRS | REST_MULTIPLE)) != REST_INLINE_GPRS)
24572     for (int i = info->first_gp_reg_save; i < 32; i++)
24573       if (!save_reg_p (i))
24574         {
24575           strategy |= REST_INLINE_GPRS;
24576           strategy &= ~REST_MULTIPLE;
24577           break;
24578         }
24579
24580   if (TARGET_ELF && TARGET_64BIT)
24581     {
24582       if (!(strategy & SAVE_INLINE_FPRS))
24583         strategy |= SAVE_NOINLINE_FPRS_SAVES_LR;
24584       else if (!(strategy & SAVE_INLINE_GPRS)
24585                && info->first_fp_reg_save == 64)
24586         strategy |= SAVE_NOINLINE_GPRS_SAVES_LR;
24587     }
24588   else if (TARGET_AIX && !(strategy & REST_INLINE_FPRS))
24589     strategy |= REST_NOINLINE_FPRS_DOESNT_RESTORE_LR;
24590
24591   if (TARGET_MACHO && !(strategy & SAVE_INLINE_FPRS))
24592     strategy |= SAVE_NOINLINE_FPRS_SAVES_LR;
24593
24594   return strategy;
24595 }
24596
24597 /* Calculate the stack information for the current function.  This is
24598    complicated by having two separate calling sequences, the AIX calling
24599    sequence and the V.4 calling sequence.
24600
24601    AIX (and Darwin/Mac OS X) stack frames look like:
24602                                                           32-bit  64-bit
24603         SP----> +---------------------------------------+
24604                 | back chain to caller                  | 0       0
24605                 +---------------------------------------+
24606                 | saved CR                              | 4       8 (8-11)
24607                 +---------------------------------------+
24608                 | saved LR                              | 8       16
24609                 +---------------------------------------+
24610                 | reserved for compilers                | 12      24
24611                 +---------------------------------------+
24612                 | reserved for binders                  | 16      32
24613                 +---------------------------------------+
24614                 | saved TOC pointer                     | 20      40
24615                 +---------------------------------------+
24616                 | Parameter save area (+padding*) (P)   | 24      48
24617                 +---------------------------------------+
24618                 | Alloca space (A)                      | 24+P    etc.
24619                 +---------------------------------------+
24620                 | Local variable space (L)              | 24+P+A
24621                 +---------------------------------------+
24622                 | Float/int conversion temporary (X)    | 24+P+A+L
24623                 +---------------------------------------+
24624                 | Save area for AltiVec registers (W)   | 24+P+A+L+X
24625                 +---------------------------------------+
24626                 | AltiVec alignment padding (Y)         | 24+P+A+L+X+W
24627                 +---------------------------------------+
24628                 | Save area for VRSAVE register (Z)     | 24+P+A+L+X+W+Y
24629                 +---------------------------------------+
24630                 | Save area for GP registers (G)        | 24+P+A+X+L+X+W+Y+Z
24631                 +---------------------------------------+
24632                 | Save area for FP registers (F)        | 24+P+A+X+L+X+W+Y+Z+G
24633                 +---------------------------------------+
24634         old SP->| back chain to caller's caller         |
24635                 +---------------------------------------+
24636
24637      * If the alloca area is present, the parameter save area is
24638        padded so that the former starts 16-byte aligned.
24639
24640    The required alignment for AIX configurations is two words (i.e., 8
24641    or 16 bytes).
24642
24643    The ELFv2 ABI is a variant of the AIX ABI.  Stack frames look like:
24644
24645         SP----> +---------------------------------------+
24646                 | Back chain to caller                  |  0
24647                 +---------------------------------------+
24648                 | Save area for CR                      |  8
24649                 +---------------------------------------+
24650                 | Saved LR                              |  16
24651                 +---------------------------------------+
24652                 | Saved TOC pointer                     |  24
24653                 +---------------------------------------+
24654                 | Parameter save area (+padding*) (P)   |  32
24655                 +---------------------------------------+
24656                 | Alloca space (A)                      |  32+P
24657                 +---------------------------------------+
24658                 | Local variable space (L)              |  32+P+A
24659                 +---------------------------------------+
24660                 | Save area for AltiVec registers (W)   |  32+P+A+L
24661                 +---------------------------------------+
24662                 | AltiVec alignment padding (Y)         |  32+P+A+L+W
24663                 +---------------------------------------+
24664                 | Save area for GP registers (G)        |  32+P+A+L+W+Y
24665                 +---------------------------------------+
24666                 | Save area for FP registers (F)        |  32+P+A+L+W+Y+G
24667                 +---------------------------------------+
24668         old SP->| back chain to caller's caller         |  32+P+A+L+W+Y+G+F
24669                 +---------------------------------------+
24670
24671      * If the alloca area is present, the parameter save area is
24672        padded so that the former starts 16-byte aligned.
24673
24674    V.4 stack frames look like:
24675
24676         SP----> +---------------------------------------+
24677                 | back chain to caller                  | 0
24678                 +---------------------------------------+
24679                 | caller's saved LR                     | 4
24680                 +---------------------------------------+
24681                 | Parameter save area (+padding*) (P)   | 8
24682                 +---------------------------------------+
24683                 | Alloca space (A)                      | 8+P
24684                 +---------------------------------------+
24685                 | Varargs save area (V)                 | 8+P+A
24686                 +---------------------------------------+
24687                 | Local variable space (L)              | 8+P+A+V
24688                 +---------------------------------------+
24689                 | Float/int conversion temporary (X)    | 8+P+A+V+L
24690                 +---------------------------------------+
24691                 | Save area for AltiVec registers (W)   | 8+P+A+V+L+X
24692                 +---------------------------------------+
24693                 | AltiVec alignment padding (Y)         | 8+P+A+V+L+X+W
24694                 +---------------------------------------+
24695                 | Save area for VRSAVE register (Z)     | 8+P+A+V+L+X+W+Y
24696                 +---------------------------------------+
24697                 | saved CR (C)                          | 8+P+A+V+L+X+W+Y+Z
24698                 +---------------------------------------+
24699                 | Save area for GP registers (G)        | 8+P+A+V+L+X+W+Y+Z+C
24700                 +---------------------------------------+
24701                 | Save area for FP registers (F)        | 8+P+A+V+L+X+W+Y+Z+C+G
24702                 +---------------------------------------+
24703         old SP->| back chain to caller's caller         |
24704                 +---------------------------------------+
24705
24706      * If the alloca area is present and the required alignment is
24707        16 bytes, the parameter save area is padded so that the
24708        alloca area starts 16-byte aligned.
24709
24710    The required alignment for V.4 is 16 bytes, or 8 bytes if -meabi is
24711    given.  (But note below and in sysv4.h that we require only 8 and
24712    may round up the size of our stack frame anyways.  The historical
24713    reason is early versions of powerpc-linux which didn't properly
24714    align the stack at program startup.  A happy side-effect is that
24715    -mno-eabi libraries can be used with -meabi programs.)
24716
24717    The EABI configuration defaults to the V.4 layout.  However,
24718    the stack alignment requirements may differ.  If -mno-eabi is not
24719    given, the required stack alignment is 8 bytes; if -mno-eabi is
24720    given, the required alignment is 16 bytes.  (But see V.4 comment
24721    above.)  */
24722
24723 #ifndef ABI_STACK_BOUNDARY
24724 #define ABI_STACK_BOUNDARY STACK_BOUNDARY
24725 #endif
24726
24727 static rs6000_stack_t *
24728 rs6000_stack_info (void)
24729 {
24730   /* We should never be called for thunks, we are not set up for that.  */
24731   gcc_assert (!cfun->is_thunk);
24732
24733   rs6000_stack_t *info = &stack_info;
24734   int reg_size = TARGET_32BIT ? 4 : 8;
24735   int ehrd_size;
24736   int ehcr_size;
24737   int save_align;
24738   int first_gp;
24739   HOST_WIDE_INT non_fixed_size;
24740   bool using_static_chain_p;
24741
24742   if (reload_completed && info->reload_completed)
24743     return info;
24744
24745   memset (info, 0, sizeof (*info));
24746   info->reload_completed = reload_completed;
24747
24748   /* Select which calling sequence.  */
24749   info->abi = DEFAULT_ABI;
24750
24751   /* Calculate which registers need to be saved & save area size.  */
24752   info->first_gp_reg_save = first_reg_to_save ();
24753   /* Assume that we will have to save RS6000_PIC_OFFSET_TABLE_REGNUM,
24754      even if it currently looks like we won't.  Reload may need it to
24755      get at a constant; if so, it will have already created a constant
24756      pool entry for it.  */
24757   if (((TARGET_TOC && TARGET_MINIMAL_TOC)
24758        || (flag_pic == 1 && DEFAULT_ABI == ABI_V4)
24759        || (flag_pic && DEFAULT_ABI == ABI_DARWIN))
24760       && crtl->uses_const_pool
24761       && info->first_gp_reg_save > RS6000_PIC_OFFSET_TABLE_REGNUM)
24762     first_gp = RS6000_PIC_OFFSET_TABLE_REGNUM;
24763   else
24764     first_gp = info->first_gp_reg_save;
24765
24766   info->gp_size = reg_size * (32 - first_gp);
24767
24768   info->first_fp_reg_save = first_fp_reg_to_save ();
24769   info->fp_size = 8 * (64 - info->first_fp_reg_save);
24770
24771   info->first_altivec_reg_save = first_altivec_reg_to_save ();
24772   info->altivec_size = 16 * (LAST_ALTIVEC_REGNO + 1
24773                                  - info->first_altivec_reg_save);
24774
24775   /* Does this function call anything?  */
24776   info->calls_p = (!crtl->is_leaf || cfun->machine->ra_needs_full_frame);
24777
24778   /* Determine if we need to save the condition code registers.  */
24779   if (save_reg_p (CR2_REGNO)
24780       || save_reg_p (CR3_REGNO)
24781       || save_reg_p (CR4_REGNO))
24782     {
24783       info->cr_save_p = 1;
24784       if (DEFAULT_ABI == ABI_V4)
24785         info->cr_size = reg_size;
24786     }
24787
24788   /* If the current function calls __builtin_eh_return, then we need
24789      to allocate stack space for registers that will hold data for
24790      the exception handler.  */
24791   if (crtl->calls_eh_return)
24792     {
24793       unsigned int i;
24794       for (i = 0; EH_RETURN_DATA_REGNO (i) != INVALID_REGNUM; ++i)
24795         continue;
24796
24797       ehrd_size = i * UNITS_PER_WORD;
24798     }
24799   else
24800     ehrd_size = 0;
24801
24802   /* In the ELFv2 ABI, we also need to allocate space for separate
24803      CR field save areas if the function calls __builtin_eh_return.  */
24804   if (DEFAULT_ABI == ABI_ELFv2 && crtl->calls_eh_return)
24805     {
24806       /* This hard-codes that we have three call-saved CR fields.  */
24807       ehcr_size = 3 * reg_size;
24808       /* We do *not* use the regular CR save mechanism.  */
24809       info->cr_save_p = 0;
24810     }
24811   else
24812     ehcr_size = 0;
24813
24814   /* Determine various sizes.  */
24815   info->reg_size     = reg_size;
24816   info->fixed_size   = RS6000_SAVE_AREA;
24817   info->vars_size    = RS6000_ALIGN (get_frame_size (), 8);
24818   if (cfun->calls_alloca)
24819     info->parm_size  =
24820       RS6000_ALIGN (crtl->outgoing_args_size + info->fixed_size,
24821                     STACK_BOUNDARY / BITS_PER_UNIT) - info->fixed_size;
24822   else
24823     info->parm_size  = RS6000_ALIGN (crtl->outgoing_args_size,
24824                                      TARGET_ALTIVEC ? 16 : 8);
24825   if (FRAME_GROWS_DOWNWARD)
24826     info->vars_size
24827       += RS6000_ALIGN (info->fixed_size + info->vars_size + info->parm_size,
24828                        ABI_STACK_BOUNDARY / BITS_PER_UNIT)
24829          - (info->fixed_size + info->vars_size + info->parm_size);
24830
24831   if (TARGET_ALTIVEC_ABI)
24832     info->vrsave_mask = compute_vrsave_mask ();
24833
24834   if (TARGET_ALTIVEC_VRSAVE && info->vrsave_mask)
24835     info->vrsave_size = 4;
24836
24837   compute_save_world_info (info);
24838
24839   /* Calculate the offsets.  */
24840   switch (DEFAULT_ABI)
24841     {
24842     case ABI_NONE:
24843     default:
24844       gcc_unreachable ();
24845
24846     case ABI_AIX:
24847     case ABI_ELFv2:
24848     case ABI_DARWIN:
24849       info->fp_save_offset = -info->fp_size;
24850       info->gp_save_offset = info->fp_save_offset - info->gp_size;
24851
24852       if (TARGET_ALTIVEC_ABI)
24853         {
24854           info->vrsave_save_offset = info->gp_save_offset - info->vrsave_size;
24855
24856           /* Align stack so vector save area is on a quadword boundary.
24857              The padding goes above the vectors.  */
24858           if (info->altivec_size != 0)
24859             info->altivec_padding_size = info->vrsave_save_offset & 0xF;
24860
24861           info->altivec_save_offset = info->vrsave_save_offset
24862                                       - info->altivec_padding_size
24863                                       - info->altivec_size;
24864           gcc_assert (info->altivec_size == 0
24865                       || info->altivec_save_offset % 16 == 0);
24866
24867           /* Adjust for AltiVec case.  */
24868           info->ehrd_offset = info->altivec_save_offset - ehrd_size;
24869         }
24870       else
24871         info->ehrd_offset = info->gp_save_offset - ehrd_size;
24872
24873       info->ehcr_offset = info->ehrd_offset - ehcr_size;
24874       info->cr_save_offset = reg_size; /* first word when 64-bit.  */
24875       info->lr_save_offset = 2*reg_size;
24876       break;
24877
24878     case ABI_V4:
24879       info->fp_save_offset = -info->fp_size;
24880       info->gp_save_offset = info->fp_save_offset - info->gp_size;
24881       info->cr_save_offset = info->gp_save_offset - info->cr_size;
24882
24883       if (TARGET_ALTIVEC_ABI)
24884         {
24885           info->vrsave_save_offset = info->cr_save_offset - info->vrsave_size;
24886
24887           /* Align stack so vector save area is on a quadword boundary.  */
24888           if (info->altivec_size != 0)
24889             info->altivec_padding_size = 16 - (-info->vrsave_save_offset % 16);
24890
24891           info->altivec_save_offset = info->vrsave_save_offset
24892                                       - info->altivec_padding_size
24893                                       - info->altivec_size;
24894
24895           /* Adjust for AltiVec case.  */
24896           info->ehrd_offset = info->altivec_save_offset;
24897         }
24898       else
24899         info->ehrd_offset = info->cr_save_offset;
24900
24901       info->ehrd_offset -= ehrd_size;
24902       info->lr_save_offset = reg_size;
24903     }
24904
24905   save_align = (TARGET_ALTIVEC_ABI || DEFAULT_ABI == ABI_DARWIN) ? 16 : 8;
24906   info->save_size = RS6000_ALIGN (info->fp_size
24907                                   + info->gp_size
24908                                   + info->altivec_size
24909                                   + info->altivec_padding_size
24910                                   + ehrd_size
24911                                   + ehcr_size
24912                                   + info->cr_size
24913                                   + info->vrsave_size,
24914                                   save_align);
24915
24916   non_fixed_size = info->vars_size + info->parm_size + info->save_size;
24917
24918   info->total_size = RS6000_ALIGN (non_fixed_size + info->fixed_size,
24919                                    ABI_STACK_BOUNDARY / BITS_PER_UNIT);
24920
24921   /* Determine if we need to save the link register.  */
24922   if (info->calls_p
24923       || ((DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
24924           && crtl->profile
24925           && !TARGET_PROFILE_KERNEL)
24926       || (DEFAULT_ABI == ABI_V4 && cfun->calls_alloca)
24927 #ifdef TARGET_RELOCATABLE
24928       || (DEFAULT_ABI == ABI_V4
24929           && (TARGET_RELOCATABLE || flag_pic > 1)
24930           && !constant_pool_empty_p ())
24931 #endif
24932       || rs6000_ra_ever_killed ())
24933     info->lr_save_p = 1;
24934
24935   using_static_chain_p = (cfun->static_chain_decl != NULL_TREE
24936                           && df_regs_ever_live_p (STATIC_CHAIN_REGNUM)
24937                           && call_used_regs[STATIC_CHAIN_REGNUM]);
24938   info->savres_strategy = rs6000_savres_strategy (info, using_static_chain_p);
24939
24940   if (!(info->savres_strategy & SAVE_INLINE_GPRS)
24941       || !(info->savres_strategy & SAVE_INLINE_FPRS)
24942       || !(info->savres_strategy & SAVE_INLINE_VRS)
24943       || !(info->savres_strategy & REST_INLINE_GPRS)
24944       || !(info->savres_strategy & REST_INLINE_FPRS)
24945       || !(info->savres_strategy & REST_INLINE_VRS))
24946     info->lr_save_p = 1;
24947
24948   if (info->lr_save_p)
24949     df_set_regs_ever_live (LR_REGNO, true);
24950
24951   /* Determine if we need to allocate any stack frame:
24952
24953      For AIX we need to push the stack if a frame pointer is needed
24954      (because the stack might be dynamically adjusted), if we are
24955      debugging, if we make calls, or if the sum of fp_save, gp_save,
24956      and local variables are more than the space needed to save all
24957      non-volatile registers: 32-bit: 18*8 + 19*4 = 220 or 64-bit: 18*8
24958      + 18*8 = 288 (GPR13 reserved).
24959
24960      For V.4 we don't have the stack cushion that AIX uses, but assume
24961      that the debugger can handle stackless frames.  */
24962
24963   if (info->calls_p)
24964     info->push_p = 1;
24965
24966   else if (DEFAULT_ABI == ABI_V4)
24967     info->push_p = non_fixed_size != 0;
24968
24969   else if (frame_pointer_needed)
24970     info->push_p = 1;
24971
24972   else if (TARGET_XCOFF && write_symbols != NO_DEBUG)
24973     info->push_p = 1;
24974
24975   else
24976     info->push_p = non_fixed_size > (TARGET_32BIT ? 220 : 288);
24977
24978   return info;
24979 }
24980
24981 static void
24982 debug_stack_info (rs6000_stack_t *info)
24983 {
24984   const char *abi_string;
24985
24986   if (! info)
24987     info = rs6000_stack_info ();
24988
24989   fprintf (stderr, "\nStack information for function %s:\n",
24990            ((current_function_decl && DECL_NAME (current_function_decl))
24991             ? IDENTIFIER_POINTER (DECL_NAME (current_function_decl))
24992             : "<unknown>"));
24993
24994   switch (info->abi)
24995     {
24996     default:             abi_string = "Unknown";        break;
24997     case ABI_NONE:       abi_string = "NONE";           break;
24998     case ABI_AIX:        abi_string = "AIX";            break;
24999     case ABI_ELFv2:      abi_string = "ELFv2";          break;
25000     case ABI_DARWIN:     abi_string = "Darwin";         break;
25001     case ABI_V4:         abi_string = "V.4";            break;
25002     }
25003
25004   fprintf (stderr, "\tABI                 = %5s\n", abi_string);
25005
25006   if (TARGET_ALTIVEC_ABI)
25007     fprintf (stderr, "\tALTIVEC ABI extensions enabled.\n");
25008
25009   if (info->first_gp_reg_save != 32)
25010     fprintf (stderr, "\tfirst_gp_reg_save   = %5d\n", info->first_gp_reg_save);
25011
25012   if (info->first_fp_reg_save != 64)
25013     fprintf (stderr, "\tfirst_fp_reg_save   = %5d\n", info->first_fp_reg_save);
25014
25015   if (info->first_altivec_reg_save <= LAST_ALTIVEC_REGNO)
25016     fprintf (stderr, "\tfirst_altivec_reg_save = %5d\n",
25017              info->first_altivec_reg_save);
25018
25019   if (info->lr_save_p)
25020     fprintf (stderr, "\tlr_save_p           = %5d\n", info->lr_save_p);
25021
25022   if (info->cr_save_p)
25023     fprintf (stderr, "\tcr_save_p           = %5d\n", info->cr_save_p);
25024
25025   if (info->vrsave_mask)
25026     fprintf (stderr, "\tvrsave_mask         = 0x%x\n", info->vrsave_mask);
25027
25028   if (info->push_p)
25029     fprintf (stderr, "\tpush_p              = %5d\n", info->push_p);
25030
25031   if (info->calls_p)
25032     fprintf (stderr, "\tcalls_p             = %5d\n", info->calls_p);
25033
25034   if (info->gp_size)
25035     fprintf (stderr, "\tgp_save_offset      = %5d\n", info->gp_save_offset);
25036
25037   if (info->fp_size)
25038     fprintf (stderr, "\tfp_save_offset      = %5d\n", info->fp_save_offset);
25039
25040   if (info->altivec_size)
25041     fprintf (stderr, "\taltivec_save_offset = %5d\n",
25042              info->altivec_save_offset);
25043
25044   if (info->vrsave_size)
25045     fprintf (stderr, "\tvrsave_save_offset  = %5d\n",
25046              info->vrsave_save_offset);
25047
25048   if (info->lr_save_p)
25049     fprintf (stderr, "\tlr_save_offset      = %5d\n", info->lr_save_offset);
25050
25051   if (info->cr_save_p)
25052     fprintf (stderr, "\tcr_save_offset      = %5d\n", info->cr_save_offset);
25053
25054   if (info->varargs_save_offset)
25055     fprintf (stderr, "\tvarargs_save_offset = %5d\n", info->varargs_save_offset);
25056
25057   if (info->total_size)
25058     fprintf (stderr, "\ttotal_size          = " HOST_WIDE_INT_PRINT_DEC"\n",
25059              info->total_size);
25060
25061   if (info->vars_size)
25062     fprintf (stderr, "\tvars_size           = " HOST_WIDE_INT_PRINT_DEC"\n",
25063              info->vars_size);
25064
25065   if (info->parm_size)
25066     fprintf (stderr, "\tparm_size           = %5d\n", info->parm_size);
25067
25068   if (info->fixed_size)
25069     fprintf (stderr, "\tfixed_size          = %5d\n", info->fixed_size);
25070
25071   if (info->gp_size)
25072     fprintf (stderr, "\tgp_size             = %5d\n", info->gp_size);
25073
25074   if (info->fp_size)
25075     fprintf (stderr, "\tfp_size             = %5d\n", info->fp_size);
25076
25077   if (info->altivec_size)
25078     fprintf (stderr, "\taltivec_size        = %5d\n", info->altivec_size);
25079
25080   if (info->vrsave_size)
25081     fprintf (stderr, "\tvrsave_size         = %5d\n", info->vrsave_size);
25082
25083   if (info->altivec_padding_size)
25084     fprintf (stderr, "\taltivec_padding_size= %5d\n",
25085              info->altivec_padding_size);
25086
25087   if (info->cr_size)
25088     fprintf (stderr, "\tcr_size             = %5d\n", info->cr_size);
25089
25090   if (info->save_size)
25091     fprintf (stderr, "\tsave_size           = %5d\n", info->save_size);
25092
25093   if (info->reg_size != 4)
25094     fprintf (stderr, "\treg_size            = %5d\n", info->reg_size);
25095
25096     fprintf (stderr, "\tsave-strategy       =  %04x\n", info->savres_strategy);
25097
25098   fprintf (stderr, "\n");
25099 }
25100
25101 rtx
25102 rs6000_return_addr (int count, rtx frame)
25103 {
25104   /* We can't use get_hard_reg_initial_val for LR when count == 0 if LR
25105      is trashed by the prologue, as it is for PIC on ABI_V4 and Darwin.  */
25106   if (count != 0
25107       || ((DEFAULT_ABI == ABI_V4 || DEFAULT_ABI == ABI_DARWIN) && flag_pic))
25108     {
25109       cfun->machine->ra_needs_full_frame = 1;
25110
25111       if (count == 0)
25112         /* FRAME is set to frame_pointer_rtx by the generic code, but that
25113            is good for loading 0(r1) only when !FRAME_GROWS_DOWNWARD.  */
25114         frame = stack_pointer_rtx;
25115       rtx prev_frame_addr = memory_address (Pmode, frame);
25116       rtx prev_frame = copy_to_reg (gen_rtx_MEM (Pmode, prev_frame_addr));
25117       rtx lr_save_off = plus_constant (Pmode,
25118                                        prev_frame, RETURN_ADDRESS_OFFSET);
25119       rtx lr_save_addr = memory_address (Pmode, lr_save_off);
25120       return gen_rtx_MEM (Pmode, lr_save_addr);
25121     }
25122
25123   cfun->machine->ra_need_lr = 1;
25124   return get_hard_reg_initial_val (Pmode, LR_REGNO);
25125 }
25126
25127 /* Say whether a function is a candidate for sibcall handling or not.  */
25128
25129 static bool
25130 rs6000_function_ok_for_sibcall (tree decl, tree exp)
25131 {
25132   tree fntype;
25133
25134   if (decl)
25135     fntype = TREE_TYPE (decl);
25136   else
25137     fntype = TREE_TYPE (TREE_TYPE (CALL_EXPR_FN (exp)));
25138
25139   /* We can't do it if the called function has more vector parameters
25140      than the current function; there's nowhere to put the VRsave code.  */
25141   if (TARGET_ALTIVEC_ABI
25142       && TARGET_ALTIVEC_VRSAVE
25143       && !(decl && decl == current_function_decl))
25144     {
25145       function_args_iterator args_iter;
25146       tree type;
25147       int nvreg = 0;
25148
25149       /* Functions with vector parameters are required to have a
25150          prototype, so the argument type info must be available
25151          here.  */
25152       FOREACH_FUNCTION_ARGS(fntype, type, args_iter)
25153         if (TREE_CODE (type) == VECTOR_TYPE
25154             && ALTIVEC_OR_VSX_VECTOR_MODE (TYPE_MODE (type)))
25155           nvreg++;
25156
25157       FOREACH_FUNCTION_ARGS(TREE_TYPE (current_function_decl), type, args_iter)
25158         if (TREE_CODE (type) == VECTOR_TYPE
25159             && ALTIVEC_OR_VSX_VECTOR_MODE (TYPE_MODE (type)))
25160           nvreg--;
25161
25162       if (nvreg > 0)
25163         return false;
25164     }
25165
25166   /* Under the AIX or ELFv2 ABIs we can't allow calls to non-local
25167      functions, because the callee may have a different TOC pointer to
25168      the caller and there's no way to ensure we restore the TOC when
25169      we return.  With the secure-plt SYSV ABI we can't make non-local
25170      calls when -fpic/PIC because the plt call stubs use r30.  */
25171   if (DEFAULT_ABI == ABI_DARWIN
25172       || ((DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
25173           && decl
25174           && !DECL_EXTERNAL (decl)
25175           && !DECL_WEAK (decl)
25176           && (*targetm.binds_local_p) (decl))
25177       || (DEFAULT_ABI == ABI_V4
25178           && (!TARGET_SECURE_PLT
25179               || !flag_pic
25180               || (decl
25181                   && (*targetm.binds_local_p) (decl)))))
25182     {
25183       tree attr_list = TYPE_ATTRIBUTES (fntype);
25184
25185       if (!lookup_attribute ("longcall", attr_list)
25186           || lookup_attribute ("shortcall", attr_list))
25187         return true;
25188     }
25189
25190   return false;
25191 }
25192
25193 static int
25194 rs6000_ra_ever_killed (void)
25195 {
25196   rtx_insn *top;
25197   rtx reg;
25198   rtx_insn *insn;
25199
25200   if (cfun->is_thunk)
25201     return 0;
25202
25203   if (cfun->machine->lr_save_state)
25204     return cfun->machine->lr_save_state - 1;
25205
25206   /* regs_ever_live has LR marked as used if any sibcalls are present,
25207      but this should not force saving and restoring in the
25208      pro/epilogue.  Likewise, reg_set_between_p thinks a sibcall
25209      clobbers LR, so that is inappropriate.  */
25210
25211   /* Also, the prologue can generate a store into LR that
25212      doesn't really count, like this:
25213
25214         move LR->R0
25215         bcl to set PIC register
25216         move LR->R31
25217         move R0->LR
25218
25219      When we're called from the epilogue, we need to avoid counting
25220      this as a store.  */
25221
25222   push_topmost_sequence ();
25223   top = get_insns ();
25224   pop_topmost_sequence ();
25225   reg = gen_rtx_REG (Pmode, LR_REGNO);
25226
25227   for (insn = NEXT_INSN (top); insn != NULL_RTX; insn = NEXT_INSN (insn))
25228     {
25229       if (INSN_P (insn))
25230         {
25231           if (CALL_P (insn))
25232             {
25233               if (!SIBLING_CALL_P (insn))
25234                 return 1;
25235             }
25236           else if (find_regno_note (insn, REG_INC, LR_REGNO))
25237             return 1;
25238           else if (set_of (reg, insn) != NULL_RTX
25239                    && !prologue_epilogue_contains (insn))
25240             return 1;
25241         }
25242     }
25243   return 0;
25244 }
25245 \f
25246 /* Emit instructions needed to load the TOC register.
25247    This is only needed when TARGET_TOC, TARGET_MINIMAL_TOC, and there is
25248    a constant pool; or for SVR4 -fpic.  */
25249
25250 void
25251 rs6000_emit_load_toc_table (int fromprolog)
25252 {
25253   rtx dest;
25254   dest = gen_rtx_REG (Pmode, RS6000_PIC_OFFSET_TABLE_REGNUM);
25255
25256   if (TARGET_ELF && TARGET_SECURE_PLT && DEFAULT_ABI == ABI_V4 && flag_pic)
25257     {
25258       char buf[30];
25259       rtx lab, tmp1, tmp2, got;
25260
25261       lab = gen_label_rtx ();
25262       ASM_GENERATE_INTERNAL_LABEL (buf, "L", CODE_LABEL_NUMBER (lab));
25263       lab = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (buf));
25264       if (flag_pic == 2)
25265         {
25266           got = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (toc_label_name));
25267           need_toc_init = 1;
25268         }
25269       else
25270         got = rs6000_got_sym ();
25271       tmp1 = tmp2 = dest;
25272       if (!fromprolog)
25273         {
25274           tmp1 = gen_reg_rtx (Pmode);
25275           tmp2 = gen_reg_rtx (Pmode);
25276         }
25277       emit_insn (gen_load_toc_v4_PIC_1 (lab));
25278       emit_move_insn (tmp1, gen_rtx_REG (Pmode, LR_REGNO));
25279       emit_insn (gen_load_toc_v4_PIC_3b (tmp2, tmp1, got, lab));
25280       emit_insn (gen_load_toc_v4_PIC_3c (dest, tmp2, got, lab));
25281     }
25282   else if (TARGET_ELF && DEFAULT_ABI == ABI_V4 && flag_pic == 1)
25283     {
25284       emit_insn (gen_load_toc_v4_pic_si ());
25285       emit_move_insn (dest, gen_rtx_REG (Pmode, LR_REGNO));
25286     }
25287   else if (TARGET_ELF && DEFAULT_ABI == ABI_V4 && flag_pic == 2)
25288     {
25289       char buf[30];
25290       rtx temp0 = (fromprolog
25291                    ? gen_rtx_REG (Pmode, 0)
25292                    : gen_reg_rtx (Pmode));
25293
25294       if (fromprolog)
25295         {
25296           rtx symF, symL;
25297
25298           ASM_GENERATE_INTERNAL_LABEL (buf, "LCF", rs6000_pic_labelno);
25299           symF = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (buf));
25300
25301           ASM_GENERATE_INTERNAL_LABEL (buf, "LCL", rs6000_pic_labelno);
25302           symL = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (buf));
25303
25304           emit_insn (gen_load_toc_v4_PIC_1 (symF));
25305           emit_move_insn (dest, gen_rtx_REG (Pmode, LR_REGNO));
25306           emit_insn (gen_load_toc_v4_PIC_2 (temp0, dest, symL, symF));
25307         }
25308       else
25309         {
25310           rtx tocsym, lab;
25311
25312           tocsym = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (toc_label_name));
25313           need_toc_init = 1;
25314           lab = gen_label_rtx ();
25315           emit_insn (gen_load_toc_v4_PIC_1b (tocsym, lab));
25316           emit_move_insn (dest, gen_rtx_REG (Pmode, LR_REGNO));
25317           if (TARGET_LINK_STACK)
25318             emit_insn (gen_addsi3 (dest, dest, GEN_INT (4)));
25319           emit_move_insn (temp0, gen_rtx_MEM (Pmode, dest));
25320         }
25321       emit_insn (gen_addsi3 (dest, temp0, dest));
25322     }
25323   else if (TARGET_ELF && !TARGET_AIX && flag_pic == 0 && TARGET_MINIMAL_TOC)
25324     {
25325       /* This is for AIX code running in non-PIC ELF32.  */
25326       rtx realsym = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (toc_label_name));
25327
25328       need_toc_init = 1;
25329       emit_insn (gen_elf_high (dest, realsym));
25330       emit_insn (gen_elf_low (dest, dest, realsym));
25331     }
25332   else
25333     {
25334       gcc_assert (DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2);
25335
25336       if (TARGET_32BIT)
25337         emit_insn (gen_load_toc_aix_si (dest));
25338       else
25339         emit_insn (gen_load_toc_aix_di (dest));
25340     }
25341 }
25342
25343 /* Emit instructions to restore the link register after determining where
25344    its value has been stored.  */
25345
25346 void
25347 rs6000_emit_eh_reg_restore (rtx source, rtx scratch)
25348 {
25349   rs6000_stack_t *info = rs6000_stack_info ();
25350   rtx operands[2];
25351
25352   operands[0] = source;
25353   operands[1] = scratch;
25354
25355   if (info->lr_save_p)
25356     {
25357       rtx frame_rtx = stack_pointer_rtx;
25358       HOST_WIDE_INT sp_offset = 0;
25359       rtx tmp;
25360
25361       if (frame_pointer_needed
25362           || cfun->calls_alloca
25363           || info->total_size > 32767)
25364         {
25365           tmp = gen_frame_mem (Pmode, frame_rtx);
25366           emit_move_insn (operands[1], tmp);
25367           frame_rtx = operands[1];
25368         }
25369       else if (info->push_p)
25370         sp_offset = info->total_size;
25371
25372       tmp = plus_constant (Pmode, frame_rtx,
25373                            info->lr_save_offset + sp_offset);
25374       tmp = gen_frame_mem (Pmode, tmp);
25375       emit_move_insn (tmp, operands[0]);
25376     }
25377   else
25378     emit_move_insn (gen_rtx_REG (Pmode, LR_REGNO), operands[0]);
25379
25380   /* Freeze lr_save_p.  We've just emitted rtl that depends on the
25381      state of lr_save_p so any change from here on would be a bug.  In
25382      particular, stop rs6000_ra_ever_killed from considering the SET
25383      of lr we may have added just above.  */ 
25384   cfun->machine->lr_save_state = info->lr_save_p + 1;
25385 }
25386
25387 static GTY(()) alias_set_type set = -1;
25388
25389 alias_set_type
25390 get_TOC_alias_set (void)
25391 {
25392   if (set == -1)
25393     set = new_alias_set ();
25394   return set;
25395 }
25396
25397 /* This returns nonzero if the current function uses the TOC.  This is
25398    determined by the presence of (use (unspec ... UNSPEC_TOC)), which
25399    is generated by the ABI_V4 load_toc_* patterns.
25400    Return 2 instead of 1 if the load_toc_* pattern is in the function
25401    partition that doesn't start the function.  */
25402 #if TARGET_ELF
25403 static int
25404 uses_TOC (void)
25405 {
25406   rtx_insn *insn;
25407   int ret = 1;
25408
25409   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
25410     {
25411       if (INSN_P (insn))
25412         {
25413           rtx pat = PATTERN (insn);
25414           int i;
25415
25416           if (GET_CODE (pat) == PARALLEL)
25417             for (i = 0; i < XVECLEN (pat, 0); i++)
25418               {
25419                 rtx sub = XVECEXP (pat, 0, i);
25420                 if (GET_CODE (sub) == USE)
25421                   {
25422                     sub = XEXP (sub, 0);
25423                     if (GET_CODE (sub) == UNSPEC
25424                         && XINT (sub, 1) == UNSPEC_TOC)
25425                       return ret;
25426                   }
25427               }
25428         }
25429       else if (crtl->has_bb_partition
25430                && NOTE_P (insn)
25431                && NOTE_KIND (insn) == NOTE_INSN_SWITCH_TEXT_SECTIONS)
25432         ret = 2;
25433     }
25434   return 0;
25435 }
25436 #endif
25437
25438 rtx
25439 create_TOC_reference (rtx symbol, rtx largetoc_reg)
25440 {
25441   rtx tocrel, tocreg, hi;
25442
25443   if (TARGET_DEBUG_ADDR)
25444     {
25445       if (GET_CODE (symbol) == SYMBOL_REF)
25446         fprintf (stderr, "\ncreate_TOC_reference, (symbol_ref %s)\n",
25447                  XSTR (symbol, 0));
25448       else
25449         {
25450           fprintf (stderr, "\ncreate_TOC_reference, code %s:\n",
25451                    GET_RTX_NAME (GET_CODE (symbol)));
25452           debug_rtx (symbol);
25453         }
25454     }
25455
25456   if (!can_create_pseudo_p ())
25457     df_set_regs_ever_live (TOC_REGISTER, true);
25458
25459   tocreg = gen_rtx_REG (Pmode, TOC_REGISTER);
25460   tocrel = gen_rtx_UNSPEC (Pmode, gen_rtvec (2, symbol, tocreg), UNSPEC_TOCREL);
25461   if (TARGET_CMODEL == CMODEL_SMALL || can_create_pseudo_p ())
25462     return tocrel;
25463
25464   hi = gen_rtx_HIGH (Pmode, copy_rtx (tocrel));
25465   if (largetoc_reg != NULL)
25466     {
25467       emit_move_insn (largetoc_reg, hi);
25468       hi = largetoc_reg;
25469     }
25470   return gen_rtx_LO_SUM (Pmode, hi, tocrel);
25471 }
25472
25473 /* Issue assembly directives that create a reference to the given DWARF
25474    FRAME_TABLE_LABEL from the current function section.  */
25475 void
25476 rs6000_aix_asm_output_dwarf_table_ref (char * frame_table_label)
25477 {
25478   fprintf (asm_out_file, "\t.ref %s\n",
25479            (* targetm.strip_name_encoding) (frame_table_label));
25480 }
25481 \f
25482 /* This ties together stack memory (MEM with an alias set of frame_alias_set)
25483    and the change to the stack pointer.  */
25484
25485 static void
25486 rs6000_emit_stack_tie (rtx fp, bool hard_frame_needed)
25487 {
25488   rtvec p;
25489   int i;
25490   rtx regs[3];
25491
25492   i = 0;
25493   regs[i++] = gen_rtx_REG (Pmode, STACK_POINTER_REGNUM);
25494   if (hard_frame_needed)
25495     regs[i++] = gen_rtx_REG (Pmode, HARD_FRAME_POINTER_REGNUM);
25496   if (!(REGNO (fp) == STACK_POINTER_REGNUM
25497         || (hard_frame_needed
25498             && REGNO (fp) == HARD_FRAME_POINTER_REGNUM)))
25499     regs[i++] = fp;
25500
25501   p = rtvec_alloc (i);
25502   while (--i >= 0)
25503     {
25504       rtx mem = gen_frame_mem (BLKmode, regs[i]);
25505       RTVEC_ELT (p, i) = gen_rtx_SET (mem, const0_rtx);
25506     }
25507
25508   emit_insn (gen_stack_tie (gen_rtx_PARALLEL (VOIDmode, p)));
25509 }
25510
25511 /* Allocate SIZE_INT bytes on the stack using a store with update style insn
25512    and set the appropriate attributes for the generated insn.  Return the
25513    first insn which adjusts the stack pointer or the last insn before
25514    the stack adjustment loop. 
25515
25516    SIZE_INT is used to create the CFI note for the allocation.
25517
25518    SIZE_RTX is an rtx containing the size of the adjustment.  Note that
25519    since stacks grow to lower addresses its runtime value is -SIZE_INT.
25520
25521    ORIG_SP contains the backchain value that must be stored at *sp.  */
25522
25523 static rtx_insn *
25524 rs6000_emit_allocate_stack_1 (HOST_WIDE_INT size_int, rtx orig_sp)
25525 {
25526   rtx_insn *insn;
25527
25528   rtx size_rtx = GEN_INT (-size_int);
25529   if (size_int > 32767)
25530     {
25531       rtx tmp_reg = gen_rtx_REG (Pmode, 0);
25532       /* Need a note here so that try_split doesn't get confused.  */
25533       if (get_last_insn () == NULL_RTX)
25534         emit_note (NOTE_INSN_DELETED);
25535       insn = emit_move_insn (tmp_reg, size_rtx);
25536       try_split (PATTERN (insn), insn, 0);
25537       size_rtx = tmp_reg;
25538     }
25539   
25540   if (Pmode == SImode)
25541     insn = emit_insn (gen_movsi_update_stack (stack_pointer_rtx,
25542                                               stack_pointer_rtx,
25543                                               size_rtx,
25544                                               orig_sp));
25545   else
25546     insn = emit_insn (gen_movdi_di_update_stack (stack_pointer_rtx,
25547                                                  stack_pointer_rtx,
25548                                                  size_rtx,
25549                                                  orig_sp));
25550   rtx par = PATTERN (insn);
25551   gcc_assert (GET_CODE (par) == PARALLEL);
25552   rtx set = XVECEXP (par, 0, 0);
25553   gcc_assert (GET_CODE (set) == SET);
25554   rtx mem = SET_DEST (set);
25555   gcc_assert (MEM_P (mem));
25556   MEM_NOTRAP_P (mem) = 1;
25557   set_mem_alias_set (mem, get_frame_alias_set ());
25558
25559   RTX_FRAME_RELATED_P (insn) = 1;
25560   add_reg_note (insn, REG_FRAME_RELATED_EXPR,
25561                 gen_rtx_SET (stack_pointer_rtx,
25562                              gen_rtx_PLUS (Pmode,
25563                                            stack_pointer_rtx,
25564                                            GEN_INT (-size_int))));
25565
25566   /* Emit a blockage to ensure the allocation/probing insns are
25567      not optimized, combined, removed, etc.  Add REG_STACK_CHECK
25568      note for similar reasons.  */
25569   if (flag_stack_clash_protection)
25570     {
25571       add_reg_note (insn, REG_STACK_CHECK, const0_rtx);
25572       emit_insn (gen_blockage ());
25573     }
25574
25575   return insn;
25576 }
25577
25578 static HOST_WIDE_INT
25579 get_stack_clash_protection_probe_interval (void)
25580 {
25581   return (HOST_WIDE_INT_1U
25582           << PARAM_VALUE (PARAM_STACK_CLASH_PROTECTION_PROBE_INTERVAL));
25583 }
25584
25585 static HOST_WIDE_INT
25586 get_stack_clash_protection_guard_size (void)
25587 {
25588   return (HOST_WIDE_INT_1U
25589           << PARAM_VALUE (PARAM_STACK_CLASH_PROTECTION_GUARD_SIZE));
25590 }
25591
25592 /* Allocate ORIG_SIZE bytes on the stack and probe the newly
25593    allocated space every STACK_CLASH_PROTECTION_PROBE_INTERVAL bytes.
25594
25595    COPY_REG, if non-null, should contain a copy of the original
25596    stack pointer at exit from this function.
25597
25598    This is subtly different than the Ada probing in that it tries hard to
25599    prevent attacks that jump the stack guard.  Thus it is never allowed to
25600    allocate more than STACK_CLASH_PROTECTION_PROBE_INTERVAL bytes of stack
25601    space without a suitable probe.  */
25602 static rtx_insn *
25603 rs6000_emit_probe_stack_range_stack_clash (HOST_WIDE_INT orig_size,
25604                                            rtx copy_reg)
25605 {
25606   rtx orig_sp = copy_reg;
25607
25608   HOST_WIDE_INT probe_interval = get_stack_clash_protection_probe_interval ();
25609
25610   /* Round the size down to a multiple of PROBE_INTERVAL.  */
25611   HOST_WIDE_INT rounded_size = ROUND_DOWN (orig_size, probe_interval);
25612
25613   /* If explicitly requested,
25614        or the rounded size is not the same as the original size
25615        or the the rounded size is greater than a page,
25616      then we will need a copy of the original stack pointer.  */
25617   if (rounded_size != orig_size
25618       || rounded_size > probe_interval
25619       || copy_reg)
25620     {
25621       /* If the caller did not request a copy of the incoming stack
25622          pointer, then we use r0 to hold the copy.  */
25623       if (!copy_reg)
25624         orig_sp = gen_rtx_REG (Pmode, 0);
25625       emit_move_insn (orig_sp, stack_pointer_rtx);
25626     }
25627
25628   /* There's three cases here.
25629
25630      One is a single probe which is the most common and most efficiently
25631      implemented as it does not have to have a copy of the original
25632      stack pointer if there are no residuals.
25633
25634      Second is unrolled allocation/probes which we use if there's just
25635      a few of them.  It needs to save the original stack pointer into a
25636      temporary for use as a source register in the allocation/probe.
25637
25638      Last is a loop.  This is the most uncommon case and least efficient.  */
25639   rtx_insn *retval = NULL;
25640   if (rounded_size == probe_interval)
25641     {
25642       retval = rs6000_emit_allocate_stack_1 (probe_interval, stack_pointer_rtx);
25643
25644       dump_stack_clash_frame_info (PROBE_INLINE, rounded_size != orig_size);
25645     }
25646   else if (rounded_size <= 8 * probe_interval)
25647     {
25648       /* The ABI requires using the store with update insns to allocate
25649          space and store the backchain into the stack
25650
25651          So we save the current stack pointer into a temporary, then
25652          emit the store-with-update insns to store the saved stack pointer
25653          into the right location in each new page.  */
25654       for (int i = 0; i < rounded_size; i += probe_interval)
25655         {
25656           rtx_insn *insn
25657             = rs6000_emit_allocate_stack_1 (probe_interval, orig_sp);
25658
25659           /* Save the first stack adjustment in RETVAL.  */
25660           if (i == 0)
25661             retval = insn;
25662         }
25663
25664       dump_stack_clash_frame_info (PROBE_INLINE, rounded_size != orig_size);
25665     }
25666   else
25667     {
25668       /* Compute the ending address.  */
25669       rtx end_addr
25670         = copy_reg ? gen_rtx_REG (Pmode, 0) : gen_rtx_REG (Pmode, 12);
25671       rtx rs = GEN_INT (-rounded_size);
25672       rtx_insn *insn;
25673       if (add_operand (rs, Pmode))
25674         insn = emit_insn (gen_add3_insn (end_addr, stack_pointer_rtx, rs));
25675       else
25676         {
25677           emit_move_insn (end_addr, GEN_INT (-rounded_size));
25678           insn = emit_insn (gen_add3_insn (end_addr, end_addr,
25679                                            stack_pointer_rtx));
25680           /* Describe the effect of INSN to the CFI engine.  */
25681           add_reg_note (insn, REG_FRAME_RELATED_EXPR,
25682                         gen_rtx_SET (end_addr,
25683                                      gen_rtx_PLUS (Pmode, stack_pointer_rtx,
25684                                                    rs)));
25685         }
25686       RTX_FRAME_RELATED_P (insn) = 1;
25687
25688       /* Emit the loop.  */
25689       if (TARGET_64BIT)
25690         retval = emit_insn (gen_probe_stack_rangedi (stack_pointer_rtx,
25691                                                      stack_pointer_rtx, orig_sp,
25692                                                      end_addr));
25693       else
25694         retval = emit_insn (gen_probe_stack_rangesi (stack_pointer_rtx,
25695                                                      stack_pointer_rtx, orig_sp,
25696                                                      end_addr));
25697       RTX_FRAME_RELATED_P (retval) = 1;
25698       /* Describe the effect of INSN to the CFI engine.  */
25699       add_reg_note (retval, REG_FRAME_RELATED_EXPR,
25700                     gen_rtx_SET (stack_pointer_rtx, end_addr));
25701
25702       /* Emit a blockage to ensure the allocation/probing insns are
25703          not optimized, combined, removed, etc.  Other cases handle this
25704          within their call to rs6000_emit_allocate_stack_1.  */
25705       emit_insn (gen_blockage ());
25706
25707       dump_stack_clash_frame_info (PROBE_LOOP, rounded_size != orig_size);
25708     }
25709
25710   if (orig_size != rounded_size)
25711     {
25712       /* Allocate (and implicitly probe) any residual space.   */
25713       HOST_WIDE_INT residual = orig_size - rounded_size;
25714
25715       rtx_insn *insn = rs6000_emit_allocate_stack_1 (residual, orig_sp);
25716
25717       /* If the residual was the only allocation, then we can return the
25718          allocating insn.  */
25719       if (!retval)
25720         retval = insn;
25721     }
25722
25723   return retval;
25724 }
25725
25726 /* Emit the correct code for allocating stack space, as insns.
25727    If COPY_REG, make sure a copy of the old frame is left there.
25728    The generated code may use hard register 0 as a temporary.  */
25729
25730 static rtx_insn *
25731 rs6000_emit_allocate_stack (HOST_WIDE_INT size, rtx copy_reg, int copy_off)
25732 {
25733   rtx_insn *insn;
25734   rtx stack_reg = gen_rtx_REG (Pmode, STACK_POINTER_REGNUM);
25735   rtx tmp_reg = gen_rtx_REG (Pmode, 0);
25736   rtx todec = gen_int_mode (-size, Pmode);
25737
25738   if (INTVAL (todec) != -size)
25739     {
25740       warning (0, "stack frame too large");
25741       emit_insn (gen_trap ());
25742       return 0;
25743     }
25744
25745   if (crtl->limit_stack)
25746     {
25747       if (REG_P (stack_limit_rtx)
25748           && REGNO (stack_limit_rtx) > 1
25749           && REGNO (stack_limit_rtx) <= 31)
25750         {
25751           rtx_insn *insn
25752             = gen_add3_insn (tmp_reg, stack_limit_rtx, GEN_INT (size));
25753           gcc_assert (insn);
25754           emit_insn (insn);
25755           emit_insn (gen_cond_trap (LTU, stack_reg, tmp_reg, const0_rtx));
25756         }
25757       else if (GET_CODE (stack_limit_rtx) == SYMBOL_REF
25758                && TARGET_32BIT
25759                && DEFAULT_ABI == ABI_V4
25760                && !flag_pic)
25761         {
25762           rtx toload = gen_rtx_CONST (VOIDmode,
25763                                       gen_rtx_PLUS (Pmode,
25764                                                     stack_limit_rtx,
25765                                                     GEN_INT (size)));
25766
25767           emit_insn (gen_elf_high (tmp_reg, toload));
25768           emit_insn (gen_elf_low (tmp_reg, tmp_reg, toload));
25769           emit_insn (gen_cond_trap (LTU, stack_reg, tmp_reg,
25770                                     const0_rtx));
25771         }
25772       else
25773         warning (0, "stack limit expression is not supported");
25774     }
25775
25776   if (flag_stack_clash_protection)
25777     {
25778       if (size < get_stack_clash_protection_guard_size ())
25779         dump_stack_clash_frame_info (NO_PROBE_SMALL_FRAME, true);
25780       else
25781         {
25782           rtx_insn *insn = rs6000_emit_probe_stack_range_stack_clash (size,
25783                                                                       copy_reg);
25784
25785           /* If we asked for a copy with an offset, then we still need add in
25786              the offset.  */
25787           if (copy_reg && copy_off)
25788             emit_insn (gen_add3_insn (copy_reg, copy_reg, GEN_INT (copy_off)));
25789           return insn;
25790         }
25791     }
25792
25793   if (copy_reg)
25794     {
25795       if (copy_off != 0)
25796         emit_insn (gen_add3_insn (copy_reg, stack_reg, GEN_INT (copy_off)));
25797       else
25798         emit_move_insn (copy_reg, stack_reg);
25799     }
25800
25801   /* Since we didn't use gen_frame_mem to generate the MEM, grab
25802      it now and set the alias set/attributes. The above gen_*_update
25803      calls will generate a PARALLEL with the MEM set being the first
25804      operation. */
25805   insn = rs6000_emit_allocate_stack_1 (size, stack_reg);
25806   return insn;
25807 }
25808
25809 #define PROBE_INTERVAL (1 << STACK_CHECK_PROBE_INTERVAL_EXP)
25810
25811 #if PROBE_INTERVAL > 32768
25812 #error Cannot use indexed addressing mode for stack probing
25813 #endif
25814
25815 /* Emit code to probe a range of stack addresses from FIRST to FIRST+SIZE,
25816    inclusive.  These are offsets from the current stack pointer.  */
25817
25818 static void
25819 rs6000_emit_probe_stack_range (HOST_WIDE_INT first, HOST_WIDE_INT size)
25820 {
25821   /* See if we have a constant small number of probes to generate.  If so,
25822      that's the easy case.  */
25823   if (first + size <= 32768)
25824     {
25825       HOST_WIDE_INT i;
25826
25827       /* Probe at FIRST + N * PROBE_INTERVAL for values of N from 1 until
25828          it exceeds SIZE.  If only one probe is needed, this will not
25829          generate any code.  Then probe at FIRST + SIZE.  */
25830       for (i = PROBE_INTERVAL; i < size; i += PROBE_INTERVAL)
25831         emit_stack_probe (plus_constant (Pmode, stack_pointer_rtx,
25832                                          -(first + i)));
25833
25834       emit_stack_probe (plus_constant (Pmode, stack_pointer_rtx,
25835                                        -(first + size)));
25836     }
25837
25838   /* Otherwise, do the same as above, but in a loop.  Note that we must be
25839      extra careful with variables wrapping around because we might be at
25840      the very top (or the very bottom) of the address space and we have
25841      to be able to handle this case properly; in particular, we use an
25842      equality test for the loop condition.  */
25843   else
25844     {
25845       HOST_WIDE_INT rounded_size;
25846       rtx r12 = gen_rtx_REG (Pmode, 12);
25847       rtx r0 = gen_rtx_REG (Pmode, 0);
25848
25849       /* Sanity check for the addressing mode we're going to use.  */
25850       gcc_assert (first <= 32768);
25851
25852       /* Step 1: round SIZE to the previous multiple of the interval.  */
25853
25854       rounded_size = ROUND_DOWN (size, PROBE_INTERVAL);
25855
25856
25857       /* Step 2: compute initial and final value of the loop counter.  */
25858
25859       /* TEST_ADDR = SP + FIRST.  */
25860       emit_insn (gen_rtx_SET (r12, plus_constant (Pmode, stack_pointer_rtx,
25861                                                   -first)));
25862
25863       /* LAST_ADDR = SP + FIRST + ROUNDED_SIZE.  */
25864       if (rounded_size > 32768)
25865         {
25866           emit_move_insn (r0, GEN_INT (-rounded_size));
25867           emit_insn (gen_rtx_SET (r0, gen_rtx_PLUS (Pmode, r12, r0)));
25868         }
25869       else
25870         emit_insn (gen_rtx_SET (r0, plus_constant (Pmode, r12,
25871                                                    -rounded_size)));
25872
25873
25874       /* Step 3: the loop
25875
25876          do
25877            {
25878              TEST_ADDR = TEST_ADDR + PROBE_INTERVAL
25879              probe at TEST_ADDR
25880            }
25881          while (TEST_ADDR != LAST_ADDR)
25882
25883          probes at FIRST + N * PROBE_INTERVAL for values of N from 1
25884          until it is equal to ROUNDED_SIZE.  */
25885
25886       if (TARGET_64BIT)
25887         emit_insn (gen_probe_stack_rangedi (r12, r12, stack_pointer_rtx, r0));
25888       else
25889         emit_insn (gen_probe_stack_rangesi (r12, r12, stack_pointer_rtx, r0));
25890
25891
25892       /* Step 4: probe at FIRST + SIZE if we cannot assert at compile-time
25893          that SIZE is equal to ROUNDED_SIZE.  */
25894
25895       if (size != rounded_size)
25896         emit_stack_probe (plus_constant (Pmode, r12, rounded_size - size));
25897     }
25898 }
25899
25900 /* Probe a range of stack addresses from REG1 to REG2 inclusive.  These are
25901    addresses, not offsets.  */
25902
25903 static const char *
25904 output_probe_stack_range_1 (rtx reg1, rtx reg2)
25905 {
25906   static int labelno = 0;
25907   char loop_lab[32];
25908   rtx xops[2];
25909
25910   ASM_GENERATE_INTERNAL_LABEL (loop_lab, "LPSRL", labelno++);
25911
25912   /* Loop.  */
25913   ASM_OUTPUT_INTERNAL_LABEL (asm_out_file, loop_lab);
25914
25915   /* TEST_ADDR = TEST_ADDR + PROBE_INTERVAL.  */
25916   xops[0] = reg1;
25917   xops[1] = GEN_INT (-PROBE_INTERVAL);
25918   output_asm_insn ("addi %0,%0,%1", xops);
25919
25920   /* Probe at TEST_ADDR.  */
25921   xops[1] = gen_rtx_REG (Pmode, 0);
25922   output_asm_insn ("stw %1,0(%0)", xops);
25923
25924   /* Test if TEST_ADDR == LAST_ADDR.  */
25925   xops[1] = reg2;
25926   if (TARGET_64BIT)
25927     output_asm_insn ("cmpd 0,%0,%1", xops);
25928   else
25929     output_asm_insn ("cmpw 0,%0,%1", xops);
25930
25931   /* Branch.  */
25932   fputs ("\tbne 0,", asm_out_file);
25933   assemble_name_raw (asm_out_file, loop_lab);
25934   fputc ('\n', asm_out_file);
25935
25936   return "";
25937 }
25938
25939 /* This function is called when rs6000_frame_related is processing
25940    SETs within a PARALLEL, and returns whether the REGNO save ought to
25941    be marked RTX_FRAME_RELATED_P.  The PARALLELs involved are those
25942    for out-of-line register save functions, store multiple, and the
25943    Darwin world_save.  They may contain registers that don't really
25944    need saving.  */
25945
25946 static bool
25947 interesting_frame_related_regno (unsigned int regno)
25948 {
25949   /* Saves apparently of r0 are actually saving LR.  It doesn't make
25950      sense to substitute the regno here to test save_reg_p (LR_REGNO).
25951      We *know* LR needs saving, and dwarf2cfi.c is able to deduce that
25952      (set (mem) (r0)) is saving LR from a prior (set (r0) (lr)) marked
25953      as frame related.  */
25954   if (regno == 0)
25955     return true;
25956   /* If we see CR2 then we are here on a Darwin world save.  Saves of
25957      CR2 signify the whole CR is being saved.  This is a long-standing
25958      ABI wart fixed by ELFv2.  As for r0/lr there is no need to check
25959      that CR needs to be saved.  */
25960   if (regno == CR2_REGNO)
25961     return true;
25962   /* Omit frame info for any user-defined global regs.  If frame info
25963      is supplied for them, frame unwinding will restore a user reg.
25964      Also omit frame info for any reg we don't need to save, as that
25965      bloats frame info and can cause problems with shrink wrapping.
25966      Since global regs won't be seen as needing to be saved, both of
25967      these conditions are covered by save_reg_p.  */
25968   return save_reg_p (regno);
25969 }
25970
25971 /* Probe a range of stack addresses from REG1 to REG3 inclusive.  These are
25972    addresses, not offsets.
25973
25974    REG2 contains the backchain that must be stored into *sp at each allocation.
25975
25976    This is subtly different than the Ada probing above in that it tries hard
25977    to prevent attacks that jump the stack guard.  Thus, it is never allowed
25978    to allocate more than PROBE_INTERVAL bytes of stack space without a
25979    suitable probe.  */
25980
25981 static const char *
25982 output_probe_stack_range_stack_clash (rtx reg1, rtx reg2, rtx reg3)
25983 {
25984   static int labelno = 0;
25985   char loop_lab[32];
25986   rtx xops[3];
25987
25988   HOST_WIDE_INT probe_interval = get_stack_clash_protection_probe_interval ();
25989
25990   ASM_GENERATE_INTERNAL_LABEL (loop_lab, "LPSRL", labelno++);
25991
25992   ASM_OUTPUT_INTERNAL_LABEL (asm_out_file, loop_lab);
25993
25994   /* This allocates and probes.  */
25995   xops[0] = reg1;
25996   xops[1] = reg2;
25997   xops[2] = GEN_INT (-probe_interval);
25998   if (TARGET_64BIT)
25999     output_asm_insn ("stdu %1,%2(%0)", xops);
26000   else
26001     output_asm_insn ("stwu %1,%2(%0)", xops);
26002
26003   /* Jump to LOOP_LAB if TEST_ADDR != LAST_ADDR.  */
26004   xops[0] = reg1;
26005   xops[1] = reg3;
26006   if (TARGET_64BIT)
26007     output_asm_insn ("cmpd 0,%0,%1", xops);
26008   else
26009     output_asm_insn ("cmpw 0,%0,%1", xops);
26010
26011   fputs ("\tbne 0,", asm_out_file);
26012   assemble_name_raw (asm_out_file, loop_lab);
26013   fputc ('\n', asm_out_file);
26014
26015   return "";
26016 }
26017
26018 /* Wrapper around the output_probe_stack_range routines.  */
26019 const char *
26020 output_probe_stack_range (rtx reg1, rtx reg2, rtx reg3)
26021 {
26022   if (flag_stack_clash_protection)
26023     return output_probe_stack_range_stack_clash (reg1, reg2, reg3);
26024   else
26025     return output_probe_stack_range_1 (reg1, reg3);
26026 }
26027
26028 /* Add to 'insn' a note which is PATTERN (INSN) but with REG replaced
26029    with (plus:P (reg 1) VAL), and with REG2 replaced with REPL2 if REG2
26030    is not NULL.  It would be nice if dwarf2out_frame_debug_expr could
26031    deduce these equivalences by itself so it wasn't necessary to hold
26032    its hand so much.  Don't be tempted to always supply d2_f_d_e with
26033    the actual cfa register, ie. r31 when we are using a hard frame
26034    pointer.  That fails when saving regs off r1, and sched moves the
26035    r31 setup past the reg saves.  */
26036
26037 static rtx_insn *
26038 rs6000_frame_related (rtx_insn *insn, rtx reg, HOST_WIDE_INT val,
26039                       rtx reg2, rtx repl2)
26040 {
26041   rtx repl;
26042
26043   if (REGNO (reg) == STACK_POINTER_REGNUM)
26044     {
26045       gcc_checking_assert (val == 0);
26046       repl = NULL_RTX;
26047     }
26048   else
26049     repl = gen_rtx_PLUS (Pmode, gen_rtx_REG (Pmode, STACK_POINTER_REGNUM),
26050                          GEN_INT (val));
26051
26052   rtx pat = PATTERN (insn);
26053   if (!repl && !reg2)
26054     {
26055       /* No need for any replacement.  Just set RTX_FRAME_RELATED_P.  */
26056       if (GET_CODE (pat) == PARALLEL)
26057         for (int i = 0; i < XVECLEN (pat, 0); i++)
26058           if (GET_CODE (XVECEXP (pat, 0, i)) == SET)
26059             {
26060               rtx set = XVECEXP (pat, 0, i);
26061
26062               if (!REG_P (SET_SRC (set))
26063                   || interesting_frame_related_regno (REGNO (SET_SRC (set))))
26064                 RTX_FRAME_RELATED_P (set) = 1;
26065             }
26066       RTX_FRAME_RELATED_P (insn) = 1;
26067       return insn;
26068     }
26069
26070   /* We expect that 'pat' is either a SET or a PARALLEL containing
26071      SETs (and possibly other stuff).  In a PARALLEL, all the SETs
26072      are important so they all have to be marked RTX_FRAME_RELATED_P.
26073      Call simplify_replace_rtx on the SETs rather than the whole insn
26074      so as to leave the other stuff alone (for example USE of r12).  */
26075
26076   set_used_flags (pat);
26077   if (GET_CODE (pat) == SET)
26078     {
26079       if (repl)
26080         pat = simplify_replace_rtx (pat, reg, repl);
26081       if (reg2)
26082         pat = simplify_replace_rtx (pat, reg2, repl2);
26083     }
26084   else if (GET_CODE (pat) == PARALLEL)
26085     {
26086       pat = shallow_copy_rtx (pat);
26087       XVEC (pat, 0) = shallow_copy_rtvec (XVEC (pat, 0));
26088
26089       for (int i = 0; i < XVECLEN (pat, 0); i++)
26090         if (GET_CODE (XVECEXP (pat, 0, i)) == SET)
26091           {
26092             rtx set = XVECEXP (pat, 0, i);
26093
26094             if (repl)
26095               set = simplify_replace_rtx (set, reg, repl);
26096             if (reg2)
26097               set = simplify_replace_rtx (set, reg2, repl2);
26098             XVECEXP (pat, 0, i) = set;
26099
26100             if (!REG_P (SET_SRC (set))
26101                 || interesting_frame_related_regno (REGNO (SET_SRC (set))))
26102               RTX_FRAME_RELATED_P (set) = 1;
26103           }
26104     }
26105   else
26106     gcc_unreachable ();
26107
26108   RTX_FRAME_RELATED_P (insn) = 1;
26109   add_reg_note (insn, REG_FRAME_RELATED_EXPR, copy_rtx_if_shared (pat));
26110
26111   return insn;
26112 }
26113
26114 /* Returns an insn that has a vrsave set operation with the
26115    appropriate CLOBBERs.  */
26116
26117 static rtx
26118 generate_set_vrsave (rtx reg, rs6000_stack_t *info, int epiloguep)
26119 {
26120   int nclobs, i;
26121   rtx insn, clobs[TOTAL_ALTIVEC_REGS + 1];
26122   rtx vrsave = gen_rtx_REG (SImode, VRSAVE_REGNO);
26123
26124   clobs[0]
26125     = gen_rtx_SET (vrsave,
26126                    gen_rtx_UNSPEC_VOLATILE (SImode,
26127                                             gen_rtvec (2, reg, vrsave),
26128                                             UNSPECV_SET_VRSAVE));
26129
26130   nclobs = 1;
26131
26132   /* We need to clobber the registers in the mask so the scheduler
26133      does not move sets to VRSAVE before sets of AltiVec registers.
26134
26135      However, if the function receives nonlocal gotos, reload will set
26136      all call saved registers live.  We will end up with:
26137
26138         (set (reg 999) (mem))
26139         (parallel [ (set (reg vrsave) (unspec blah))
26140                     (clobber (reg 999))])
26141
26142      The clobber will cause the store into reg 999 to be dead, and
26143      flow will attempt to delete an epilogue insn.  In this case, we
26144      need an unspec use/set of the register.  */
26145
26146   for (i = FIRST_ALTIVEC_REGNO; i <= LAST_ALTIVEC_REGNO; ++i)
26147     if (info->vrsave_mask & ALTIVEC_REG_BIT (i))
26148       {
26149         if (!epiloguep || call_used_regs [i])
26150           clobs[nclobs++] = gen_rtx_CLOBBER (VOIDmode,
26151                                              gen_rtx_REG (V4SImode, i));
26152         else
26153           {
26154             rtx reg = gen_rtx_REG (V4SImode, i);
26155
26156             clobs[nclobs++]
26157               = gen_rtx_SET (reg,
26158                              gen_rtx_UNSPEC (V4SImode,
26159                                              gen_rtvec (1, reg), 27));
26160           }
26161       }
26162
26163   insn = gen_rtx_PARALLEL (VOIDmode, rtvec_alloc (nclobs));
26164
26165   for (i = 0; i < nclobs; ++i)
26166     XVECEXP (insn, 0, i) = clobs[i];
26167
26168   return insn;
26169 }
26170
26171 static rtx
26172 gen_frame_set (rtx reg, rtx frame_reg, int offset, bool store)
26173 {
26174   rtx addr, mem;
26175
26176   addr = gen_rtx_PLUS (Pmode, frame_reg, GEN_INT (offset));
26177   mem = gen_frame_mem (GET_MODE (reg), addr);
26178   return gen_rtx_SET (store ? mem : reg, store ? reg : mem);
26179 }
26180
26181 static rtx
26182 gen_frame_load (rtx reg, rtx frame_reg, int offset)
26183 {
26184   return gen_frame_set (reg, frame_reg, offset, false);
26185 }
26186
26187 static rtx
26188 gen_frame_store (rtx reg, rtx frame_reg, int offset)
26189 {
26190   return gen_frame_set (reg, frame_reg, offset, true);
26191 }
26192
26193 /* Save a register into the frame, and emit RTX_FRAME_RELATED_P notes.
26194    Save REGNO into [FRAME_REG + OFFSET] in mode MODE.  */
26195
26196 static rtx_insn *
26197 emit_frame_save (rtx frame_reg, machine_mode mode,
26198                  unsigned int regno, int offset, HOST_WIDE_INT frame_reg_to_sp)
26199 {
26200   rtx reg;
26201
26202   /* Some cases that need register indexed addressing.  */
26203   gcc_checking_assert (!(TARGET_ALTIVEC_ABI && ALTIVEC_VECTOR_MODE (mode))
26204                          || (TARGET_VSX && ALTIVEC_OR_VSX_VECTOR_MODE (mode)));
26205
26206   reg = gen_rtx_REG (mode, regno);
26207   rtx_insn *insn = emit_insn (gen_frame_store (reg, frame_reg, offset));
26208   return rs6000_frame_related (insn, frame_reg, frame_reg_to_sp,
26209                                NULL_RTX, NULL_RTX);
26210 }
26211
26212 /* Emit an offset memory reference suitable for a frame store, while
26213    converting to a valid addressing mode.  */
26214
26215 static rtx
26216 gen_frame_mem_offset (machine_mode mode, rtx reg, int offset)
26217 {
26218   return gen_frame_mem (mode, gen_rtx_PLUS (Pmode, reg, GEN_INT (offset)));
26219 }
26220
26221 #ifndef TARGET_FIX_AND_CONTINUE
26222 #define TARGET_FIX_AND_CONTINUE 0
26223 #endif
26224
26225 /* It's really GPR 13 or 14, FPR 14 and VR 20.  We need the smallest.  */
26226 #define FIRST_SAVRES_REGISTER FIRST_SAVED_GP_REGNO
26227 #define LAST_SAVRES_REGISTER 31
26228 #define N_SAVRES_REGISTERS (LAST_SAVRES_REGISTER - FIRST_SAVRES_REGISTER + 1)
26229
26230 enum {
26231   SAVRES_LR = 0x1,
26232   SAVRES_SAVE = 0x2,
26233   SAVRES_REG = 0x0c,
26234   SAVRES_GPR = 0,
26235   SAVRES_FPR = 4,
26236   SAVRES_VR  = 8
26237 };
26238
26239 static GTY(()) rtx savres_routine_syms[N_SAVRES_REGISTERS][12];
26240
26241 /* Temporary holding space for an out-of-line register save/restore
26242    routine name.  */
26243 static char savres_routine_name[30];
26244
26245 /* Return the name for an out-of-line register save/restore routine.
26246    We are saving/restoring GPRs if GPR is true.  */
26247
26248 static char *
26249 rs6000_savres_routine_name (int regno, int sel)
26250 {
26251   const char *prefix = "";
26252   const char *suffix = "";
26253
26254   /* Different targets are supposed to define
26255      {SAVE,RESTORE}_FP_{PREFIX,SUFFIX} with the idea that the needed
26256      routine name could be defined with:
26257
26258      sprintf (name, "%s%d%s", SAVE_FP_PREFIX, regno, SAVE_FP_SUFFIX)
26259
26260      This is a nice idea in practice, but in reality, things are
26261      complicated in several ways:
26262
26263      - ELF targets have save/restore routines for GPRs.
26264
26265      - PPC64 ELF targets have routines for save/restore of GPRs that
26266        differ in what they do with the link register, so having a set
26267        prefix doesn't work.  (We only use one of the save routines at
26268        the moment, though.)
26269
26270      - PPC32 elf targets have "exit" versions of the restore routines
26271        that restore the link register and can save some extra space.
26272        These require an extra suffix.  (There are also "tail" versions
26273        of the restore routines and "GOT" versions of the save routines,
26274        but we don't generate those at present.  Same problems apply,
26275        though.)
26276
26277      We deal with all this by synthesizing our own prefix/suffix and
26278      using that for the simple sprintf call shown above.  */
26279   if (DEFAULT_ABI == ABI_V4)
26280     {
26281       if (TARGET_64BIT)
26282         goto aix_names;
26283
26284       if ((sel & SAVRES_REG) == SAVRES_GPR)
26285         prefix = (sel & SAVRES_SAVE) ? "_savegpr_" : "_restgpr_";
26286       else if ((sel & SAVRES_REG) == SAVRES_FPR)
26287         prefix = (sel & SAVRES_SAVE) ? "_savefpr_" : "_restfpr_";
26288       else if ((sel & SAVRES_REG) == SAVRES_VR)
26289         prefix = (sel & SAVRES_SAVE) ? "_savevr_" : "_restvr_";
26290       else
26291         abort ();
26292
26293       if ((sel & SAVRES_LR))
26294         suffix = "_x";
26295     }
26296   else if (DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
26297     {
26298 #if !defined (POWERPC_LINUX) && !defined (POWERPC_FREEBSD)
26299       /* No out-of-line save/restore routines for GPRs on AIX.  */
26300       gcc_assert (!TARGET_AIX || (sel & SAVRES_REG) != SAVRES_GPR);
26301 #endif
26302
26303     aix_names:
26304       if ((sel & SAVRES_REG) == SAVRES_GPR)
26305         prefix = ((sel & SAVRES_SAVE)
26306                   ? ((sel & SAVRES_LR) ? "_savegpr0_" : "_savegpr1_")
26307                   : ((sel & SAVRES_LR) ? "_restgpr0_" : "_restgpr1_"));
26308       else if ((sel & SAVRES_REG) == SAVRES_FPR)
26309         {
26310 #if defined (POWERPC_LINUX) || defined (POWERPC_FREEBSD)
26311           if ((sel & SAVRES_LR))
26312             prefix = ((sel & SAVRES_SAVE) ? "_savefpr_" : "_restfpr_");
26313           else
26314 #endif
26315             {
26316               prefix = (sel & SAVRES_SAVE) ? SAVE_FP_PREFIX : RESTORE_FP_PREFIX;
26317               suffix = (sel & SAVRES_SAVE) ? SAVE_FP_SUFFIX : RESTORE_FP_SUFFIX;
26318             }
26319         }
26320       else if ((sel & SAVRES_REG) == SAVRES_VR)
26321         prefix = (sel & SAVRES_SAVE) ? "_savevr_" : "_restvr_";
26322       else
26323         abort ();
26324     }
26325
26326    if (DEFAULT_ABI == ABI_DARWIN)
26327     {
26328       /* The Darwin approach is (slightly) different, in order to be
26329          compatible with code generated by the system toolchain.  There is a
26330          single symbol for the start of save sequence, and the code here
26331          embeds an offset into that code on the basis of the first register
26332          to be saved.  */
26333       prefix = (sel & SAVRES_SAVE) ? "save" : "rest" ;
26334       if ((sel & SAVRES_REG) == SAVRES_GPR)
26335         sprintf (savres_routine_name, "*%sGPR%s%s%.0d ; %s r%d-r31", prefix,
26336                  ((sel & SAVRES_LR) ? "x" : ""), (regno == 13 ? "" : "+"),
26337                  (regno - 13) * 4, prefix, regno);
26338       else if ((sel & SAVRES_REG) == SAVRES_FPR)
26339         sprintf (savres_routine_name, "*%sFP%s%.0d ; %s f%d-f31", prefix,
26340                  (regno == 14 ? "" : "+"), (regno - 14) * 4, prefix, regno);
26341       else if ((sel & SAVRES_REG) == SAVRES_VR)
26342         sprintf (savres_routine_name, "*%sVEC%s%.0d ; %s v%d-v31", prefix,
26343                  (regno == 20 ? "" : "+"), (regno - 20) * 8, prefix, regno);
26344       else
26345         abort ();
26346     }
26347   else
26348     sprintf (savres_routine_name, "%s%d%s", prefix, regno, suffix);
26349
26350   return savres_routine_name;
26351 }
26352
26353 /* Return an RTL SYMBOL_REF for an out-of-line register save/restore routine.
26354    We are saving/restoring GPRs if GPR is true.  */
26355
26356 static rtx
26357 rs6000_savres_routine_sym (rs6000_stack_t *info, int sel)
26358 {
26359   int regno = ((sel & SAVRES_REG) == SAVRES_GPR
26360                ? info->first_gp_reg_save
26361                : (sel & SAVRES_REG) == SAVRES_FPR
26362                ? info->first_fp_reg_save - 32
26363                : (sel & SAVRES_REG) == SAVRES_VR
26364                ? info->first_altivec_reg_save - FIRST_ALTIVEC_REGNO
26365                : -1);
26366   rtx sym;
26367   int select = sel;
26368
26369   /* Don't generate bogus routine names.  */
26370   gcc_assert (FIRST_SAVRES_REGISTER <= regno
26371               && regno <= LAST_SAVRES_REGISTER
26372               && select >= 0 && select <= 12);
26373
26374   sym = savres_routine_syms[regno-FIRST_SAVRES_REGISTER][select];
26375
26376   if (sym == NULL)
26377     {
26378       char *name;
26379
26380       name = rs6000_savres_routine_name (regno, sel);
26381
26382       sym = savres_routine_syms[regno-FIRST_SAVRES_REGISTER][select]
26383         = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (name));
26384       SYMBOL_REF_FLAGS (sym) |= SYMBOL_FLAG_FUNCTION;
26385     }
26386
26387   return sym;
26388 }
26389
26390 /* Emit a sequence of insns, including a stack tie if needed, for
26391    resetting the stack pointer.  If UPDT_REGNO is not 1, then don't
26392    reset the stack pointer, but move the base of the frame into
26393    reg UPDT_REGNO for use by out-of-line register restore routines.  */
26394
26395 static rtx
26396 rs6000_emit_stack_reset (rtx frame_reg_rtx, HOST_WIDE_INT frame_off,
26397                          unsigned updt_regno)
26398 {
26399   /* If there is nothing to do, don't do anything.  */
26400   if (frame_off == 0 && REGNO (frame_reg_rtx) == updt_regno)
26401     return NULL_RTX;
26402
26403   rtx updt_reg_rtx = gen_rtx_REG (Pmode, updt_regno);
26404
26405   /* This blockage is needed so that sched doesn't decide to move
26406      the sp change before the register restores.  */
26407   if (DEFAULT_ABI == ABI_V4)
26408     return emit_insn (gen_stack_restore_tie (updt_reg_rtx, frame_reg_rtx,
26409                                              GEN_INT (frame_off)));
26410
26411   /* If we are restoring registers out-of-line, we will be using the
26412      "exit" variants of the restore routines, which will reset the
26413      stack for us.  But we do need to point updt_reg into the
26414      right place for those routines.  */
26415   if (frame_off != 0)
26416     return emit_insn (gen_add3_insn (updt_reg_rtx,
26417                                      frame_reg_rtx, GEN_INT (frame_off)));
26418   else
26419     return emit_move_insn (updt_reg_rtx, frame_reg_rtx);
26420
26421   return NULL_RTX;
26422 }
26423
26424 /* Return the register number used as a pointer by out-of-line
26425    save/restore functions.  */
26426
26427 static inline unsigned
26428 ptr_regno_for_savres (int sel)
26429 {
26430   if (DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
26431     return (sel & SAVRES_REG) == SAVRES_FPR || (sel & SAVRES_LR) ? 1 : 12;
26432   return DEFAULT_ABI == ABI_DARWIN && (sel & SAVRES_REG) == SAVRES_FPR ? 1 : 11;
26433 }
26434
26435 /* Construct a parallel rtx describing the effect of a call to an
26436    out-of-line register save/restore routine, and emit the insn
26437    or jump_insn as appropriate.  */
26438
26439 static rtx_insn *
26440 rs6000_emit_savres_rtx (rs6000_stack_t *info,
26441                         rtx frame_reg_rtx, int save_area_offset, int lr_offset,
26442                         machine_mode reg_mode, int sel)
26443 {
26444   int i;
26445   int offset, start_reg, end_reg, n_regs, use_reg;
26446   int reg_size = GET_MODE_SIZE (reg_mode);
26447   rtx sym;
26448   rtvec p;
26449   rtx par;
26450   rtx_insn *insn;
26451
26452   offset = 0;
26453   start_reg = ((sel & SAVRES_REG) == SAVRES_GPR
26454                ? info->first_gp_reg_save
26455                : (sel & SAVRES_REG) == SAVRES_FPR
26456                ? info->first_fp_reg_save
26457                : (sel & SAVRES_REG) == SAVRES_VR
26458                ? info->first_altivec_reg_save
26459                : -1);
26460   end_reg = ((sel & SAVRES_REG) == SAVRES_GPR
26461              ? 32
26462              : (sel & SAVRES_REG) == SAVRES_FPR
26463              ? 64
26464              : (sel & SAVRES_REG) == SAVRES_VR
26465              ? LAST_ALTIVEC_REGNO + 1
26466              : -1);
26467   n_regs = end_reg - start_reg;
26468   p = rtvec_alloc (3 + ((sel & SAVRES_LR) ? 1 : 0)
26469                    + ((sel & SAVRES_REG) == SAVRES_VR ? 1 : 0)
26470                    + n_regs);
26471
26472   if (!(sel & SAVRES_SAVE) && (sel & SAVRES_LR))
26473     RTVEC_ELT (p, offset++) = ret_rtx;
26474
26475   RTVEC_ELT (p, offset++)
26476     = gen_rtx_CLOBBER (VOIDmode, gen_rtx_REG (Pmode, LR_REGNO));
26477
26478   sym = rs6000_savres_routine_sym (info, sel);
26479   RTVEC_ELT (p, offset++) = gen_rtx_USE (VOIDmode, sym);
26480
26481   use_reg = ptr_regno_for_savres (sel);
26482   if ((sel & SAVRES_REG) == SAVRES_VR)
26483     {
26484       /* Vector regs are saved/restored using [reg+reg] addressing.  */
26485       RTVEC_ELT (p, offset++)
26486         = gen_rtx_CLOBBER (VOIDmode, gen_rtx_REG (Pmode, use_reg));
26487       RTVEC_ELT (p, offset++)
26488         = gen_rtx_USE (VOIDmode, gen_rtx_REG (Pmode, 0));
26489     }
26490   else
26491     RTVEC_ELT (p, offset++)
26492       = gen_rtx_USE (VOIDmode, gen_rtx_REG (Pmode, use_reg));
26493
26494   for (i = 0; i < end_reg - start_reg; i++)
26495     RTVEC_ELT (p, i + offset)
26496       = gen_frame_set (gen_rtx_REG (reg_mode, start_reg + i),
26497                        frame_reg_rtx, save_area_offset + reg_size * i,
26498                        (sel & SAVRES_SAVE) != 0);
26499
26500   if ((sel & SAVRES_SAVE) && (sel & SAVRES_LR))
26501     RTVEC_ELT (p, i + offset)
26502       = gen_frame_store (gen_rtx_REG (Pmode, 0), frame_reg_rtx, lr_offset);
26503
26504   par = gen_rtx_PARALLEL (VOIDmode, p);
26505
26506   if (!(sel & SAVRES_SAVE) && (sel & SAVRES_LR))
26507     {
26508       insn = emit_jump_insn (par);
26509       JUMP_LABEL (insn) = ret_rtx;
26510     }
26511   else
26512     insn = emit_insn (par);
26513   return insn;
26514 }
26515
26516 /* Emit prologue code to store CR fields that need to be saved into REG.  This
26517    function should only be called when moving the non-volatile CRs to REG, it
26518    is not a general purpose routine to move the entire set of CRs to REG.
26519    Specifically, gen_prologue_movesi_from_cr() does not contain uses of the
26520    volatile CRs.  */
26521
26522 static void
26523 rs6000_emit_prologue_move_from_cr (rtx reg)
26524 {
26525   /* Only the ELFv2 ABI allows storing only selected fields.  */
26526   if (DEFAULT_ABI == ABI_ELFv2 && TARGET_MFCRF)
26527     {
26528       int i, cr_reg[8], count = 0;
26529
26530       /* Collect CR fields that must be saved.  */
26531       for (i = 0; i < 8; i++)
26532         if (save_reg_p (CR0_REGNO + i))
26533           cr_reg[count++] = i;
26534
26535       /* If it's just a single one, use mfcrf.  */
26536       if (count == 1)
26537         {
26538           rtvec p = rtvec_alloc (1);
26539           rtvec r = rtvec_alloc (2);
26540           RTVEC_ELT (r, 0) = gen_rtx_REG (CCmode, CR0_REGNO + cr_reg[0]);
26541           RTVEC_ELT (r, 1) = GEN_INT (1 << (7 - cr_reg[0]));
26542           RTVEC_ELT (p, 0)
26543             = gen_rtx_SET (reg,
26544                            gen_rtx_UNSPEC (SImode, r, UNSPEC_MOVESI_FROM_CR));
26545
26546           emit_insn (gen_rtx_PARALLEL (VOIDmode, p));
26547           return;
26548         }
26549
26550       /* ??? It might be better to handle count == 2 / 3 cases here
26551          as well, using logical operations to combine the values.  */
26552     }
26553
26554   emit_insn (gen_prologue_movesi_from_cr (reg));
26555 }
26556
26557 /* Return whether the split-stack arg pointer (r12) is used.  */
26558
26559 static bool
26560 split_stack_arg_pointer_used_p (void)
26561 {
26562   /* If the pseudo holding the arg pointer is no longer a pseudo,
26563      then the arg pointer is used.  */
26564   if (cfun->machine->split_stack_arg_pointer != NULL_RTX
26565       && (!REG_P (cfun->machine->split_stack_arg_pointer)
26566           || (REGNO (cfun->machine->split_stack_arg_pointer)
26567               < FIRST_PSEUDO_REGISTER)))
26568     return true;
26569
26570   /* Unfortunately we also need to do some code scanning, since
26571      r12 may have been substituted for the pseudo.  */
26572   rtx_insn *insn;
26573   basic_block bb = ENTRY_BLOCK_PTR_FOR_FN (cfun)->next_bb;
26574   FOR_BB_INSNS (bb, insn)
26575     if (NONDEBUG_INSN_P (insn))
26576       {
26577         /* A call destroys r12.  */
26578         if (CALL_P (insn))
26579           return false;
26580
26581         df_ref use;
26582         FOR_EACH_INSN_USE (use, insn)
26583           {
26584             rtx x = DF_REF_REG (use);
26585             if (REG_P (x) && REGNO (x) == 12)
26586               return true;
26587           }
26588         df_ref def;
26589         FOR_EACH_INSN_DEF (def, insn)
26590           {
26591             rtx x = DF_REF_REG (def);
26592             if (REG_P (x) && REGNO (x) == 12)
26593               return false;
26594           }
26595       }
26596   return bitmap_bit_p (DF_LR_OUT (bb), 12);
26597 }
26598
26599 /* Return whether we need to emit an ELFv2 global entry point prologue.  */
26600
26601 static bool
26602 rs6000_global_entry_point_needed_p (void)
26603 {
26604   /* Only needed for the ELFv2 ABI.  */
26605   if (DEFAULT_ABI != ABI_ELFv2)
26606     return false;
26607
26608   /* With -msingle-pic-base, we assume the whole program shares the same
26609      TOC, so no global entry point prologues are needed anywhere.  */
26610   if (TARGET_SINGLE_PIC_BASE)
26611     return false;
26612
26613   /* Ensure we have a global entry point for thunks.   ??? We could
26614      avoid that if the target routine doesn't need a global entry point,
26615      but we do not know whether this is the case at this point.  */
26616   if (cfun->is_thunk)
26617     return true;
26618
26619   /* For regular functions, rs6000_emit_prologue sets this flag if the
26620      routine ever uses the TOC pointer.  */
26621   return cfun->machine->r2_setup_needed;
26622 }
26623
26624 /* Implement TARGET_SHRINK_WRAP_GET_SEPARATE_COMPONENTS.  */
26625 static sbitmap
26626 rs6000_get_separate_components (void)
26627 {
26628   rs6000_stack_t *info = rs6000_stack_info ();
26629
26630   if (WORLD_SAVE_P (info))
26631     return NULL;
26632
26633   gcc_assert (!(info->savres_strategy & SAVE_MULTIPLE)
26634               && !(info->savres_strategy & REST_MULTIPLE));
26635
26636   /* Component 0 is the save/restore of LR (done via GPR0).
26637      Component 2 is the save of the TOC (GPR2).
26638      Components 13..31 are the save/restore of GPR13..GPR31.
26639      Components 46..63 are the save/restore of FPR14..FPR31.  */
26640
26641   cfun->machine->n_components = 64;
26642
26643   sbitmap components = sbitmap_alloc (cfun->machine->n_components);
26644   bitmap_clear (components);
26645
26646   int reg_size = TARGET_32BIT ? 4 : 8;
26647   int fp_reg_size = 8;
26648
26649   /* The GPRs we need saved to the frame.  */
26650   if ((info->savres_strategy & SAVE_INLINE_GPRS)
26651       && (info->savres_strategy & REST_INLINE_GPRS))
26652     {
26653       int offset = info->gp_save_offset;
26654       if (info->push_p)
26655         offset += info->total_size;
26656
26657       for (unsigned regno = info->first_gp_reg_save; regno < 32; regno++)
26658         {
26659           if (IN_RANGE (offset, -0x8000, 0x7fff)
26660               && save_reg_p (regno))
26661             bitmap_set_bit (components, regno);
26662
26663           offset += reg_size;
26664         }
26665     }
26666
26667   /* Don't mess with the hard frame pointer.  */
26668   if (frame_pointer_needed)
26669     bitmap_clear_bit (components, HARD_FRAME_POINTER_REGNUM);
26670
26671   /* Don't mess with the fixed TOC register.  */
26672   if ((TARGET_TOC && TARGET_MINIMAL_TOC)
26673       || (flag_pic == 1 && DEFAULT_ABI == ABI_V4)
26674       || (flag_pic && DEFAULT_ABI == ABI_DARWIN))
26675     bitmap_clear_bit (components, RS6000_PIC_OFFSET_TABLE_REGNUM);
26676
26677   /* The FPRs we need saved to the frame.  */
26678   if ((info->savres_strategy & SAVE_INLINE_FPRS)
26679       && (info->savres_strategy & REST_INLINE_FPRS))
26680     {
26681       int offset = info->fp_save_offset;
26682       if (info->push_p)
26683         offset += info->total_size;
26684
26685       for (unsigned regno = info->first_fp_reg_save; regno < 64; regno++)
26686         {
26687           if (IN_RANGE (offset, -0x8000, 0x7fff) && save_reg_p (regno))
26688             bitmap_set_bit (components, regno);
26689
26690           offset += fp_reg_size;
26691         }
26692     }
26693
26694   /* Optimize LR save and restore if we can.  This is component 0.  Any
26695      out-of-line register save/restore routines need LR.  */
26696   if (info->lr_save_p
26697       && !(flag_pic && (DEFAULT_ABI == ABI_V4 || DEFAULT_ABI == ABI_DARWIN))
26698       && (info->savres_strategy & SAVE_INLINE_GPRS)
26699       && (info->savres_strategy & REST_INLINE_GPRS)
26700       && (info->savres_strategy & SAVE_INLINE_FPRS)
26701       && (info->savres_strategy & REST_INLINE_FPRS)
26702       && (info->savres_strategy & SAVE_INLINE_VRS)
26703       && (info->savres_strategy & REST_INLINE_VRS))
26704     {
26705       int offset = info->lr_save_offset;
26706       if (info->push_p)
26707         offset += info->total_size;
26708       if (IN_RANGE (offset, -0x8000, 0x7fff))
26709         bitmap_set_bit (components, 0);
26710     }
26711
26712   /* Optimize saving the TOC.  This is component 2.  */
26713   if (cfun->machine->save_toc_in_prologue)
26714     bitmap_set_bit (components, 2);
26715
26716   return components;
26717 }
26718
26719 /* Implement TARGET_SHRINK_WRAP_COMPONENTS_FOR_BB.  */
26720 static sbitmap
26721 rs6000_components_for_bb (basic_block bb)
26722 {
26723   rs6000_stack_t *info = rs6000_stack_info ();
26724
26725   bitmap in = DF_LIVE_IN (bb);
26726   bitmap gen = &DF_LIVE_BB_INFO (bb)->gen;
26727   bitmap kill = &DF_LIVE_BB_INFO (bb)->kill;
26728
26729   sbitmap components = sbitmap_alloc (cfun->machine->n_components);
26730   bitmap_clear (components);
26731
26732   /* A register is used in a bb if it is in the IN, GEN, or KILL sets.  */
26733
26734   /* GPRs.  */
26735   for (unsigned regno = info->first_gp_reg_save; regno < 32; regno++)
26736     if (bitmap_bit_p (in, regno)
26737         || bitmap_bit_p (gen, regno)
26738         || bitmap_bit_p (kill, regno))
26739       bitmap_set_bit (components, regno);
26740
26741   /* FPRs.  */
26742   for (unsigned regno = info->first_fp_reg_save; regno < 64; regno++)
26743     if (bitmap_bit_p (in, regno)
26744         || bitmap_bit_p (gen, regno)
26745         || bitmap_bit_p (kill, regno))
26746       bitmap_set_bit (components, regno);
26747
26748   /* The link register.  */
26749   if (bitmap_bit_p (in, LR_REGNO)
26750       || bitmap_bit_p (gen, LR_REGNO)
26751       || bitmap_bit_p (kill, LR_REGNO))
26752     bitmap_set_bit (components, 0);
26753
26754   /* The TOC save.  */
26755   if (bitmap_bit_p (in, TOC_REGNUM)
26756       || bitmap_bit_p (gen, TOC_REGNUM)
26757       || bitmap_bit_p (kill, TOC_REGNUM))
26758     bitmap_set_bit (components, 2);
26759
26760   return components;
26761 }
26762
26763 /* Implement TARGET_SHRINK_WRAP_DISQUALIFY_COMPONENTS.  */
26764 static void
26765 rs6000_disqualify_components (sbitmap components, edge e,
26766                               sbitmap edge_components, bool /*is_prologue*/)
26767 {
26768   /* Our LR pro/epilogue code moves LR via R0, so R0 had better not be
26769      live where we want to place that code.  */
26770   if (bitmap_bit_p (edge_components, 0)
26771       && bitmap_bit_p (DF_LIVE_IN (e->dest), 0))
26772     {
26773       if (dump_file)
26774         fprintf (dump_file, "Disqualifying LR because GPR0 is live "
26775                  "on entry to bb %d\n", e->dest->index);
26776       bitmap_clear_bit (components, 0);
26777     }
26778 }
26779
26780 /* Implement TARGET_SHRINK_WRAP_EMIT_PROLOGUE_COMPONENTS.  */
26781 static void
26782 rs6000_emit_prologue_components (sbitmap components)
26783 {
26784   rs6000_stack_t *info = rs6000_stack_info ();
26785   rtx ptr_reg = gen_rtx_REG (Pmode, frame_pointer_needed
26786                              ? HARD_FRAME_POINTER_REGNUM
26787                              : STACK_POINTER_REGNUM);
26788
26789   machine_mode reg_mode = Pmode;
26790   int reg_size = TARGET_32BIT ? 4 : 8;
26791   machine_mode fp_reg_mode = (TARGET_HARD_FLOAT && TARGET_DOUBLE_FLOAT)
26792                              ? DFmode : SFmode;
26793   int fp_reg_size = 8;
26794
26795   /* Prologue for LR.  */
26796   if (bitmap_bit_p (components, 0))
26797     {
26798       rtx reg = gen_rtx_REG (reg_mode, 0);
26799       rtx_insn *insn = emit_move_insn (reg, gen_rtx_REG (reg_mode, LR_REGNO));
26800       RTX_FRAME_RELATED_P (insn) = 1;
26801       add_reg_note (insn, REG_CFA_REGISTER, NULL);
26802
26803       int offset = info->lr_save_offset;
26804       if (info->push_p)
26805         offset += info->total_size;
26806
26807       insn = emit_insn (gen_frame_store (reg, ptr_reg, offset));
26808       RTX_FRAME_RELATED_P (insn) = 1;
26809       rtx lr = gen_rtx_REG (reg_mode, LR_REGNO);
26810       rtx mem = copy_rtx (SET_DEST (single_set (insn)));
26811       add_reg_note (insn, REG_CFA_OFFSET, gen_rtx_SET (mem, lr));
26812     }
26813
26814   /* Prologue for TOC.  */
26815   if (bitmap_bit_p (components, 2))
26816     {
26817       rtx reg = gen_rtx_REG (reg_mode, TOC_REGNUM);
26818       rtx sp_reg = gen_rtx_REG (Pmode, STACK_POINTER_REGNUM);
26819       emit_insn (gen_frame_store (reg, sp_reg, RS6000_TOC_SAVE_SLOT));
26820     }
26821
26822   /* Prologue for the GPRs.  */
26823   int offset = info->gp_save_offset;
26824   if (info->push_p)
26825     offset += info->total_size;
26826
26827   for (int i = info->first_gp_reg_save; i < 32; i++)
26828     {
26829       if (bitmap_bit_p (components, i))
26830         {
26831           rtx reg = gen_rtx_REG (reg_mode, i);
26832           rtx_insn *insn = emit_insn (gen_frame_store (reg, ptr_reg, offset));
26833           RTX_FRAME_RELATED_P (insn) = 1;
26834           rtx set = copy_rtx (single_set (insn));
26835           add_reg_note (insn, REG_CFA_OFFSET, set);
26836         }
26837
26838       offset += reg_size;
26839     }
26840
26841   /* Prologue for the FPRs.  */
26842   offset = info->fp_save_offset;
26843   if (info->push_p)
26844     offset += info->total_size;
26845
26846   for (int i = info->first_fp_reg_save; i < 64; i++)
26847     {
26848       if (bitmap_bit_p (components, i))
26849         {
26850           rtx reg = gen_rtx_REG (fp_reg_mode, i);
26851           rtx_insn *insn = emit_insn (gen_frame_store (reg, ptr_reg, offset));
26852           RTX_FRAME_RELATED_P (insn) = 1;
26853           rtx set = copy_rtx (single_set (insn));
26854           add_reg_note (insn, REG_CFA_OFFSET, set);
26855         }
26856
26857       offset += fp_reg_size;
26858     }
26859 }
26860
26861 /* Implement TARGET_SHRINK_WRAP_EMIT_EPILOGUE_COMPONENTS.  */
26862 static void
26863 rs6000_emit_epilogue_components (sbitmap components)
26864 {
26865   rs6000_stack_t *info = rs6000_stack_info ();
26866   rtx ptr_reg = gen_rtx_REG (Pmode, frame_pointer_needed
26867                              ? HARD_FRAME_POINTER_REGNUM
26868                              : STACK_POINTER_REGNUM);
26869
26870   machine_mode reg_mode = Pmode;
26871   int reg_size = TARGET_32BIT ? 4 : 8;
26872
26873   machine_mode fp_reg_mode = (TARGET_HARD_FLOAT && TARGET_DOUBLE_FLOAT)
26874                              ? DFmode : SFmode;
26875   int fp_reg_size = 8;
26876
26877   /* Epilogue for the FPRs.  */
26878   int offset = info->fp_save_offset;
26879   if (info->push_p)
26880     offset += info->total_size;
26881
26882   for (int i = info->first_fp_reg_save; i < 64; i++)
26883     {
26884       if (bitmap_bit_p (components, i))
26885         {
26886           rtx reg = gen_rtx_REG (fp_reg_mode, i);
26887           rtx_insn *insn = emit_insn (gen_frame_load (reg, ptr_reg, offset));
26888           RTX_FRAME_RELATED_P (insn) = 1;
26889           add_reg_note (insn, REG_CFA_RESTORE, reg);
26890         }
26891
26892       offset += fp_reg_size;
26893     }
26894
26895   /* Epilogue for the GPRs.  */
26896   offset = info->gp_save_offset;
26897   if (info->push_p)
26898     offset += info->total_size;
26899
26900   for (int i = info->first_gp_reg_save; i < 32; i++)
26901     {
26902       if (bitmap_bit_p (components, i))
26903         {
26904           rtx reg = gen_rtx_REG (reg_mode, i);
26905           rtx_insn *insn = emit_insn (gen_frame_load (reg, ptr_reg, offset));
26906           RTX_FRAME_RELATED_P (insn) = 1;
26907           add_reg_note (insn, REG_CFA_RESTORE, reg);
26908         }
26909
26910       offset += reg_size;
26911     }
26912
26913   /* Epilogue for LR.  */
26914   if (bitmap_bit_p (components, 0))
26915     {
26916       int offset = info->lr_save_offset;
26917       if (info->push_p)
26918         offset += info->total_size;
26919
26920       rtx reg = gen_rtx_REG (reg_mode, 0);
26921       rtx_insn *insn = emit_insn (gen_frame_load (reg, ptr_reg, offset));
26922
26923       rtx lr = gen_rtx_REG (Pmode, LR_REGNO);
26924       insn = emit_move_insn (lr, reg);
26925       RTX_FRAME_RELATED_P (insn) = 1;
26926       add_reg_note (insn, REG_CFA_RESTORE, lr);
26927     }
26928 }
26929
26930 /* Implement TARGET_SHRINK_WRAP_SET_HANDLED_COMPONENTS.  */
26931 static void
26932 rs6000_set_handled_components (sbitmap components)
26933 {
26934   rs6000_stack_t *info = rs6000_stack_info ();
26935
26936   for (int i = info->first_gp_reg_save; i < 32; i++)
26937     if (bitmap_bit_p (components, i))
26938       cfun->machine->gpr_is_wrapped_separately[i] = true;
26939
26940   for (int i = info->first_fp_reg_save; i < 64; i++)
26941     if (bitmap_bit_p (components, i))
26942       cfun->machine->fpr_is_wrapped_separately[i - 32] = true;
26943
26944   if (bitmap_bit_p (components, 0))
26945     cfun->machine->lr_is_wrapped_separately = true;
26946
26947   if (bitmap_bit_p (components, 2))
26948     cfun->machine->toc_is_wrapped_separately = true;
26949 }
26950
26951 /* VRSAVE is a bit vector representing which AltiVec registers
26952    are used.  The OS uses this to determine which vector
26953    registers to save on a context switch.  We need to save
26954    VRSAVE on the stack frame, add whatever AltiVec registers we
26955    used in this function, and do the corresponding magic in the
26956    epilogue.  */
26957 static void
26958 emit_vrsave_prologue (rs6000_stack_t *info, int save_regno,
26959                       HOST_WIDE_INT frame_off, rtx frame_reg_rtx)
26960 {
26961   /* Get VRSAVE into a GPR.  */
26962   rtx reg = gen_rtx_REG (SImode, save_regno);
26963   rtx vrsave = gen_rtx_REG (SImode, VRSAVE_REGNO);
26964   if (TARGET_MACHO)
26965     emit_insn (gen_get_vrsave_internal (reg));
26966   else
26967     emit_insn (gen_rtx_SET (reg, vrsave));
26968
26969   /* Save VRSAVE.  */
26970   int offset = info->vrsave_save_offset + frame_off;
26971   emit_insn (gen_frame_store (reg, frame_reg_rtx, offset));
26972
26973   /* Include the registers in the mask.  */
26974   emit_insn (gen_iorsi3 (reg, reg, GEN_INT (info->vrsave_mask)));
26975
26976   emit_insn (generate_set_vrsave (reg, info, 0));
26977 }
26978
26979 /* Set up the arg pointer (r12) for -fsplit-stack code.  If __morestack was
26980    called, it left the arg pointer to the old stack in r29.  Otherwise, the
26981    arg pointer is the top of the current frame.  */
26982 static void
26983 emit_split_stack_prologue (rs6000_stack_t *info, rtx_insn *sp_adjust,
26984                            HOST_WIDE_INT frame_off, rtx frame_reg_rtx)
26985 {
26986   cfun->machine->split_stack_argp_used = true;
26987
26988   if (sp_adjust)
26989     {
26990       rtx r12 = gen_rtx_REG (Pmode, 12);
26991       rtx sp_reg_rtx = gen_rtx_REG (Pmode, STACK_POINTER_REGNUM);
26992       rtx set_r12 = gen_rtx_SET (r12, sp_reg_rtx);
26993       emit_insn_before (set_r12, sp_adjust);
26994     }
26995   else if (frame_off != 0 || REGNO (frame_reg_rtx) != 12)
26996     {
26997       rtx r12 = gen_rtx_REG (Pmode, 12);
26998       if (frame_off == 0)
26999         emit_move_insn (r12, frame_reg_rtx);
27000       else
27001         emit_insn (gen_add3_insn (r12, frame_reg_rtx, GEN_INT (frame_off)));
27002     }
27003
27004   if (info->push_p)
27005     {
27006       rtx r12 = gen_rtx_REG (Pmode, 12);
27007       rtx r29 = gen_rtx_REG (Pmode, 29);
27008       rtx cr7 = gen_rtx_REG (CCUNSmode, CR7_REGNO);
27009       rtx not_more = gen_label_rtx ();
27010       rtx jump;
27011
27012       jump = gen_rtx_IF_THEN_ELSE (VOIDmode,
27013                                    gen_rtx_GEU (VOIDmode, cr7, const0_rtx),
27014                                    gen_rtx_LABEL_REF (VOIDmode, not_more),
27015                                    pc_rtx);
27016       jump = emit_jump_insn (gen_rtx_SET (pc_rtx, jump));
27017       JUMP_LABEL (jump) = not_more;
27018       LABEL_NUSES (not_more) += 1;
27019       emit_move_insn (r12, r29);
27020       emit_label (not_more);
27021     }
27022 }
27023
27024 /* Emit function prologue as insns.  */
27025
27026 void
27027 rs6000_emit_prologue (void)
27028 {
27029   rs6000_stack_t *info = rs6000_stack_info ();
27030   machine_mode reg_mode = Pmode;
27031   int reg_size = TARGET_32BIT ? 4 : 8;
27032   machine_mode fp_reg_mode = (TARGET_HARD_FLOAT && TARGET_DOUBLE_FLOAT)
27033                              ? DFmode : SFmode;
27034   int fp_reg_size = 8;
27035   rtx sp_reg_rtx = gen_rtx_REG (Pmode, STACK_POINTER_REGNUM);
27036   rtx frame_reg_rtx = sp_reg_rtx;
27037   unsigned int cr_save_regno;
27038   rtx cr_save_rtx = NULL_RTX;
27039   rtx_insn *insn;
27040   int strategy;
27041   int using_static_chain_p = (cfun->static_chain_decl != NULL_TREE
27042                               && df_regs_ever_live_p (STATIC_CHAIN_REGNUM)
27043                               && call_used_regs[STATIC_CHAIN_REGNUM]);
27044   int using_split_stack = (flag_split_stack
27045                            && (lookup_attribute ("no_split_stack",
27046                                                  DECL_ATTRIBUTES (cfun->decl))
27047                                == NULL));
27048  
27049   /* Offset to top of frame for frame_reg and sp respectively.  */
27050   HOST_WIDE_INT frame_off = 0;
27051   HOST_WIDE_INT sp_off = 0;
27052   /* sp_adjust is the stack adjusting instruction, tracked so that the
27053      insn setting up the split-stack arg pointer can be emitted just
27054      prior to it, when r12 is not used here for other purposes.  */
27055   rtx_insn *sp_adjust = 0;
27056
27057 #if CHECKING_P
27058   /* Track and check usage of r0, r11, r12.  */
27059   int reg_inuse = using_static_chain_p ? 1 << 11 : 0;
27060 #define START_USE(R) do \
27061   {                                             \
27062     gcc_assert ((reg_inuse & (1 << (R))) == 0); \
27063     reg_inuse |= 1 << (R);                      \
27064   } while (0)
27065 #define END_USE(R) do \
27066   {                                             \
27067     gcc_assert ((reg_inuse & (1 << (R))) != 0); \
27068     reg_inuse &= ~(1 << (R));                   \
27069   } while (0)
27070 #define NOT_INUSE(R) do \
27071   {                                             \
27072     gcc_assert ((reg_inuse & (1 << (R))) == 0); \
27073   } while (0)
27074 #else
27075 #define START_USE(R) do {} while (0)
27076 #define END_USE(R) do {} while (0)
27077 #define NOT_INUSE(R) do {} while (0)
27078 #endif
27079
27080   if (DEFAULT_ABI == ABI_ELFv2
27081       && !TARGET_SINGLE_PIC_BASE)
27082     {
27083       cfun->machine->r2_setup_needed = df_regs_ever_live_p (TOC_REGNUM);
27084
27085       /* With -mminimal-toc we may generate an extra use of r2 below.  */
27086       if (TARGET_TOC && TARGET_MINIMAL_TOC
27087           && !constant_pool_empty_p ())
27088         cfun->machine->r2_setup_needed = true;
27089     }
27090
27091
27092   if (flag_stack_usage_info)
27093     current_function_static_stack_size = info->total_size;
27094
27095   if (flag_stack_check == STATIC_BUILTIN_STACK_CHECK)
27096     {
27097       HOST_WIDE_INT size = info->total_size;
27098
27099       if (crtl->is_leaf && !cfun->calls_alloca)
27100         {
27101           if (size > PROBE_INTERVAL && size > get_stack_check_protect ())
27102             rs6000_emit_probe_stack_range (get_stack_check_protect (),
27103                                            size - get_stack_check_protect ());
27104         }
27105       else if (size > 0)
27106         rs6000_emit_probe_stack_range (get_stack_check_protect (), size);
27107     }
27108
27109   if (TARGET_FIX_AND_CONTINUE)
27110     {
27111       /* gdb on darwin arranges to forward a function from the old
27112          address by modifying the first 5 instructions of the function
27113          to branch to the overriding function.  This is necessary to
27114          permit function pointers that point to the old function to
27115          actually forward to the new function.  */
27116       emit_insn (gen_nop ());
27117       emit_insn (gen_nop ());
27118       emit_insn (gen_nop ());
27119       emit_insn (gen_nop ());
27120       emit_insn (gen_nop ());
27121     }
27122
27123   /* Handle world saves specially here.  */
27124   if (WORLD_SAVE_P (info))
27125     {
27126       int i, j, sz;
27127       rtx treg;
27128       rtvec p;
27129       rtx reg0;
27130
27131       /* save_world expects lr in r0. */
27132       reg0 = gen_rtx_REG (Pmode, 0);
27133       if (info->lr_save_p)
27134         {
27135           insn = emit_move_insn (reg0,
27136                                  gen_rtx_REG (Pmode, LR_REGNO));
27137           RTX_FRAME_RELATED_P (insn) = 1;
27138         }
27139
27140       /* The SAVE_WORLD and RESTORE_WORLD routines make a number of
27141          assumptions about the offsets of various bits of the stack
27142          frame.  */
27143       gcc_assert (info->gp_save_offset == -220
27144                   && info->fp_save_offset == -144
27145                   && info->lr_save_offset == 8
27146                   && info->cr_save_offset == 4
27147                   && info->push_p
27148                   && info->lr_save_p
27149                   && (!crtl->calls_eh_return
27150                       || info->ehrd_offset == -432)
27151                   && info->vrsave_save_offset == -224
27152                   && info->altivec_save_offset == -416);
27153
27154       treg = gen_rtx_REG (SImode, 11);
27155       emit_move_insn (treg, GEN_INT (-info->total_size));
27156
27157       /* SAVE_WORLD takes the caller's LR in R0 and the frame size
27158          in R11.  It also clobbers R12, so beware!  */
27159
27160       /* Preserve CR2 for save_world prologues */
27161       sz = 5;
27162       sz += 32 - info->first_gp_reg_save;
27163       sz += 64 - info->first_fp_reg_save;
27164       sz += LAST_ALTIVEC_REGNO - info->first_altivec_reg_save + 1;
27165       p = rtvec_alloc (sz);
27166       j = 0;
27167       RTVEC_ELT (p, j++) = gen_rtx_CLOBBER (VOIDmode,
27168                                             gen_rtx_REG (SImode,
27169                                                          LR_REGNO));
27170       RTVEC_ELT (p, j++) = gen_rtx_USE (VOIDmode,
27171                                         gen_rtx_SYMBOL_REF (Pmode,
27172                                                             "*save_world"));
27173       /* We do floats first so that the instruction pattern matches
27174          properly.  */
27175       for (i = 0; i < 64 - info->first_fp_reg_save; i++)
27176         RTVEC_ELT (p, j++)
27177           = gen_frame_store (gen_rtx_REG (TARGET_HARD_FLOAT && TARGET_DOUBLE_FLOAT
27178                                           ? DFmode : SFmode,
27179                                           info->first_fp_reg_save + i),
27180                              frame_reg_rtx,
27181                              info->fp_save_offset + frame_off + 8 * i);
27182       for (i = 0; info->first_altivec_reg_save + i <= LAST_ALTIVEC_REGNO; i++)
27183         RTVEC_ELT (p, j++)
27184           = gen_frame_store (gen_rtx_REG (V4SImode,
27185                                           info->first_altivec_reg_save + i),
27186                              frame_reg_rtx,
27187                              info->altivec_save_offset + frame_off + 16 * i);
27188       for (i = 0; i < 32 - info->first_gp_reg_save; i++)
27189         RTVEC_ELT (p, j++)
27190           = gen_frame_store (gen_rtx_REG (reg_mode, info->first_gp_reg_save + i),
27191                              frame_reg_rtx,
27192                              info->gp_save_offset + frame_off + reg_size * i);
27193
27194       /* CR register traditionally saved as CR2.  */
27195       RTVEC_ELT (p, j++)
27196         = gen_frame_store (gen_rtx_REG (SImode, CR2_REGNO),
27197                            frame_reg_rtx, info->cr_save_offset + frame_off);
27198       /* Explain about use of R0.  */
27199       if (info->lr_save_p)
27200         RTVEC_ELT (p, j++)
27201           = gen_frame_store (reg0,
27202                              frame_reg_rtx, info->lr_save_offset + frame_off);
27203       /* Explain what happens to the stack pointer.  */
27204       {
27205         rtx newval = gen_rtx_PLUS (Pmode, sp_reg_rtx, treg);
27206         RTVEC_ELT (p, j++) = gen_rtx_SET (sp_reg_rtx, newval);
27207       }
27208
27209       insn = emit_insn (gen_rtx_PARALLEL (VOIDmode, p));
27210       rs6000_frame_related (insn, frame_reg_rtx, sp_off - frame_off,
27211                             treg, GEN_INT (-info->total_size));
27212       sp_off = frame_off = info->total_size;
27213     }
27214
27215   strategy = info->savres_strategy;
27216
27217   /* For V.4, update stack before we do any saving and set back pointer.  */
27218   if (! WORLD_SAVE_P (info)
27219       && info->push_p
27220       && (DEFAULT_ABI == ABI_V4
27221           || crtl->calls_eh_return))
27222     {
27223       bool need_r11 = (!(strategy & SAVE_INLINE_FPRS)
27224                        || !(strategy & SAVE_INLINE_GPRS)
27225                        || !(strategy & SAVE_INLINE_VRS));
27226       int ptr_regno = -1;
27227       rtx ptr_reg = NULL_RTX;
27228       int ptr_off = 0;
27229
27230       if (info->total_size < 32767)
27231         frame_off = info->total_size;
27232       else if (need_r11)
27233         ptr_regno = 11;
27234       else if (info->cr_save_p
27235                || info->lr_save_p
27236                || info->first_fp_reg_save < 64
27237                || info->first_gp_reg_save < 32
27238                || info->altivec_size != 0
27239                || info->vrsave_size != 0
27240                || crtl->calls_eh_return)
27241         ptr_regno = 12;
27242       else
27243         {
27244           /* The prologue won't be saving any regs so there is no need
27245              to set up a frame register to access any frame save area.
27246              We also won't be using frame_off anywhere below, but set
27247              the correct value anyway to protect against future
27248              changes to this function.  */
27249           frame_off = info->total_size;
27250         }
27251       if (ptr_regno != -1)
27252         {
27253           /* Set up the frame offset to that needed by the first
27254              out-of-line save function.  */
27255           START_USE (ptr_regno);
27256           ptr_reg = gen_rtx_REG (Pmode, ptr_regno);
27257           frame_reg_rtx = ptr_reg;
27258           if (!(strategy & SAVE_INLINE_FPRS) && info->fp_size != 0)
27259             gcc_checking_assert (info->fp_save_offset + info->fp_size == 0);
27260           else if (!(strategy & SAVE_INLINE_GPRS) && info->first_gp_reg_save < 32)
27261             ptr_off = info->gp_save_offset + info->gp_size;
27262           else if (!(strategy & SAVE_INLINE_VRS) && info->altivec_size != 0)
27263             ptr_off = info->altivec_save_offset + info->altivec_size;
27264           frame_off = -ptr_off;
27265         }
27266       sp_adjust = rs6000_emit_allocate_stack (info->total_size,
27267                                               ptr_reg, ptr_off);
27268       if (REGNO (frame_reg_rtx) == 12)
27269         sp_adjust = 0;
27270       sp_off = info->total_size;
27271       if (frame_reg_rtx != sp_reg_rtx)
27272         rs6000_emit_stack_tie (frame_reg_rtx, false);
27273     }
27274
27275   /* If we use the link register, get it into r0.  */
27276   if (!WORLD_SAVE_P (info) && info->lr_save_p
27277       && !cfun->machine->lr_is_wrapped_separately)
27278     {
27279       rtx addr, reg, mem;
27280
27281       reg = gen_rtx_REG (Pmode, 0);
27282       START_USE (0);
27283       insn = emit_move_insn (reg, gen_rtx_REG (Pmode, LR_REGNO));
27284       RTX_FRAME_RELATED_P (insn) = 1;
27285
27286       if (!(strategy & (SAVE_NOINLINE_GPRS_SAVES_LR
27287                         | SAVE_NOINLINE_FPRS_SAVES_LR)))
27288         {
27289           addr = gen_rtx_PLUS (Pmode, frame_reg_rtx,
27290                                GEN_INT (info->lr_save_offset + frame_off));
27291           mem = gen_rtx_MEM (Pmode, addr);
27292           /* This should not be of rs6000_sr_alias_set, because of
27293              __builtin_return_address.  */
27294
27295           insn = emit_move_insn (mem, reg);
27296           rs6000_frame_related (insn, frame_reg_rtx, sp_off - frame_off,
27297                                 NULL_RTX, NULL_RTX);
27298           END_USE (0);
27299         }
27300     }
27301
27302   /* If we need to save CR, put it into r12 or r11.  Choose r12 except when
27303      r12 will be needed by out-of-line gpr restore.  */
27304   cr_save_regno = ((DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
27305                    && !(strategy & (SAVE_INLINE_GPRS
27306                                     | SAVE_NOINLINE_GPRS_SAVES_LR))
27307                    ? 11 : 12);
27308   if (!WORLD_SAVE_P (info)
27309       && info->cr_save_p
27310       && REGNO (frame_reg_rtx) != cr_save_regno
27311       && !(using_static_chain_p && cr_save_regno == 11)
27312       && !(using_split_stack && cr_save_regno == 12 && sp_adjust))
27313     {
27314       cr_save_rtx = gen_rtx_REG (SImode, cr_save_regno);
27315       START_USE (cr_save_regno);
27316       rs6000_emit_prologue_move_from_cr (cr_save_rtx);
27317     }
27318
27319   /* Do any required saving of fpr's.  If only one or two to save, do
27320      it ourselves.  Otherwise, call function.  */
27321   if (!WORLD_SAVE_P (info) && (strategy & SAVE_INLINE_FPRS))
27322     {
27323       int offset = info->fp_save_offset + frame_off;
27324       for (int i = info->first_fp_reg_save; i < 64; i++)
27325         {
27326           if (save_reg_p (i)
27327               && !cfun->machine->fpr_is_wrapped_separately[i - 32])
27328             emit_frame_save (frame_reg_rtx, fp_reg_mode, i, offset,
27329                              sp_off - frame_off);
27330
27331           offset += fp_reg_size;
27332         }
27333     }
27334   else if (!WORLD_SAVE_P (info) && info->first_fp_reg_save != 64)
27335     {
27336       bool lr = (strategy & SAVE_NOINLINE_FPRS_SAVES_LR) != 0;
27337       int sel = SAVRES_SAVE | SAVRES_FPR | (lr ? SAVRES_LR : 0);
27338       unsigned ptr_regno = ptr_regno_for_savres (sel);
27339       rtx ptr_reg = frame_reg_rtx;
27340
27341       if (REGNO (frame_reg_rtx) == ptr_regno)
27342         gcc_checking_assert (frame_off == 0);
27343       else
27344         {
27345           ptr_reg = gen_rtx_REG (Pmode, ptr_regno);
27346           NOT_INUSE (ptr_regno);
27347           emit_insn (gen_add3_insn (ptr_reg,
27348                                     frame_reg_rtx, GEN_INT (frame_off)));
27349         }
27350       insn = rs6000_emit_savres_rtx (info, ptr_reg,
27351                                      info->fp_save_offset,
27352                                      info->lr_save_offset,
27353                                      DFmode, sel);
27354       rs6000_frame_related (insn, ptr_reg, sp_off,
27355                             NULL_RTX, NULL_RTX);
27356       if (lr)
27357         END_USE (0);
27358     }
27359
27360   /* Save GPRs.  This is done as a PARALLEL if we are using
27361      the store-multiple instructions.  */
27362   if (!WORLD_SAVE_P (info) && !(strategy & SAVE_INLINE_GPRS))
27363     {
27364       bool lr = (strategy & SAVE_NOINLINE_GPRS_SAVES_LR) != 0;
27365       int sel = SAVRES_SAVE | SAVRES_GPR | (lr ? SAVRES_LR : 0);
27366       unsigned ptr_regno = ptr_regno_for_savres (sel);
27367       rtx ptr_reg = frame_reg_rtx;
27368       bool ptr_set_up = REGNO (ptr_reg) == ptr_regno;
27369       int end_save = info->gp_save_offset + info->gp_size;
27370       int ptr_off;
27371
27372       if (ptr_regno == 12)
27373         sp_adjust = 0;
27374       if (!ptr_set_up)
27375         ptr_reg = gen_rtx_REG (Pmode, ptr_regno);
27376
27377       /* Need to adjust r11 (r12) if we saved any FPRs.  */
27378       if (end_save + frame_off != 0)
27379         {
27380           rtx offset = GEN_INT (end_save + frame_off);
27381
27382           if (ptr_set_up)
27383             frame_off = -end_save;
27384           else
27385             NOT_INUSE (ptr_regno);
27386           emit_insn (gen_add3_insn (ptr_reg, frame_reg_rtx, offset));
27387         }
27388       else if (!ptr_set_up)
27389         {
27390           NOT_INUSE (ptr_regno);
27391           emit_move_insn (ptr_reg, frame_reg_rtx);
27392         }
27393       ptr_off = -end_save;
27394       insn = rs6000_emit_savres_rtx (info, ptr_reg,
27395                                      info->gp_save_offset + ptr_off,
27396                                      info->lr_save_offset + ptr_off,
27397                                      reg_mode, sel);
27398       rs6000_frame_related (insn, ptr_reg, sp_off - ptr_off,
27399                             NULL_RTX, NULL_RTX);
27400       if (lr)
27401         END_USE (0);
27402     }
27403   else if (!WORLD_SAVE_P (info) && (strategy & SAVE_MULTIPLE))
27404     {
27405       rtvec p;
27406       int i;
27407       p = rtvec_alloc (32 - info->first_gp_reg_save);
27408       for (i = 0; i < 32 - info->first_gp_reg_save; i++)
27409         RTVEC_ELT (p, i)
27410           = gen_frame_store (gen_rtx_REG (reg_mode, info->first_gp_reg_save + i),
27411                              frame_reg_rtx,
27412                              info->gp_save_offset + frame_off + reg_size * i);
27413       insn = emit_insn (gen_rtx_PARALLEL (VOIDmode, p));
27414       rs6000_frame_related (insn, frame_reg_rtx, sp_off - frame_off,
27415                             NULL_RTX, NULL_RTX);
27416     }
27417   else if (!WORLD_SAVE_P (info))
27418     {
27419       int offset = info->gp_save_offset + frame_off;
27420       for (int i = info->first_gp_reg_save; i < 32; i++)
27421         {
27422           if (save_reg_p (i)
27423               && !cfun->machine->gpr_is_wrapped_separately[i])
27424             emit_frame_save (frame_reg_rtx, reg_mode, i, offset,
27425                              sp_off - frame_off);
27426
27427           offset += reg_size;
27428         }
27429     }
27430
27431   if (crtl->calls_eh_return)
27432     {
27433       unsigned int i;
27434       rtvec p;
27435
27436       for (i = 0; ; ++i)
27437         {
27438           unsigned int regno = EH_RETURN_DATA_REGNO (i);
27439           if (regno == INVALID_REGNUM)
27440             break;
27441         }
27442
27443       p = rtvec_alloc (i);
27444
27445       for (i = 0; ; ++i)
27446         {
27447           unsigned int regno = EH_RETURN_DATA_REGNO (i);
27448           if (regno == INVALID_REGNUM)
27449             break;
27450
27451           rtx set
27452             = gen_frame_store (gen_rtx_REG (reg_mode, regno),
27453                                sp_reg_rtx,
27454                                info->ehrd_offset + sp_off + reg_size * (int) i);
27455           RTVEC_ELT (p, i) = set;
27456           RTX_FRAME_RELATED_P (set) = 1;
27457         }
27458
27459       insn = emit_insn (gen_blockage ());
27460       RTX_FRAME_RELATED_P (insn) = 1;
27461       add_reg_note (insn, REG_FRAME_RELATED_EXPR, gen_rtx_PARALLEL (VOIDmode, p));
27462     }
27463
27464   /* In AIX ABI we need to make sure r2 is really saved.  */
27465   if (TARGET_AIX && crtl->calls_eh_return)
27466     {
27467       rtx tmp_reg, tmp_reg_si, hi, lo, compare_result, toc_save_done, jump;
27468       rtx join_insn, note;
27469       rtx_insn *save_insn;
27470       long toc_restore_insn;
27471
27472       tmp_reg = gen_rtx_REG (Pmode, 11);
27473       tmp_reg_si = gen_rtx_REG (SImode, 11);
27474       if (using_static_chain_p)
27475         {
27476           START_USE (0);
27477           emit_move_insn (gen_rtx_REG (Pmode, 0), tmp_reg);
27478         }
27479       else
27480         START_USE (11);
27481       emit_move_insn (tmp_reg, gen_rtx_REG (Pmode, LR_REGNO));
27482       /* Peek at instruction to which this function returns.  If it's
27483          restoring r2, then we know we've already saved r2.  We can't
27484          unconditionally save r2 because the value we have will already
27485          be updated if we arrived at this function via a plt call or
27486          toc adjusting stub.  */
27487       emit_move_insn (tmp_reg_si, gen_rtx_MEM (SImode, tmp_reg));
27488       toc_restore_insn = ((TARGET_32BIT ? 0x80410000 : 0xE8410000)
27489                           + RS6000_TOC_SAVE_SLOT);
27490       hi = gen_int_mode (toc_restore_insn & ~0xffff, SImode);
27491       emit_insn (gen_xorsi3 (tmp_reg_si, tmp_reg_si, hi));
27492       compare_result = gen_rtx_REG (CCUNSmode, CR0_REGNO);
27493       validate_condition_mode (EQ, CCUNSmode);
27494       lo = gen_int_mode (toc_restore_insn & 0xffff, SImode);
27495       emit_insn (gen_rtx_SET (compare_result,
27496                               gen_rtx_COMPARE (CCUNSmode, tmp_reg_si, lo)));
27497       toc_save_done = gen_label_rtx ();
27498       jump = gen_rtx_IF_THEN_ELSE (VOIDmode,
27499                                    gen_rtx_EQ (VOIDmode, compare_result,
27500                                                const0_rtx),
27501                                    gen_rtx_LABEL_REF (VOIDmode, toc_save_done),
27502                                    pc_rtx);
27503       jump = emit_jump_insn (gen_rtx_SET (pc_rtx, jump));
27504       JUMP_LABEL (jump) = toc_save_done;
27505       LABEL_NUSES (toc_save_done) += 1;
27506
27507       save_insn = emit_frame_save (frame_reg_rtx, reg_mode,
27508                                    TOC_REGNUM, frame_off + RS6000_TOC_SAVE_SLOT,
27509                                    sp_off - frame_off);
27510
27511       emit_label (toc_save_done);
27512
27513       /* ??? If we leave SAVE_INSN as marked as saving R2, then we'll
27514          have a CFG that has different saves along different paths.
27515          Move the note to a dummy blockage insn, which describes that
27516          R2 is unconditionally saved after the label.  */
27517       /* ??? An alternate representation might be a special insn pattern
27518          containing both the branch and the store.  That might let the
27519          code that minimizes the number of DW_CFA_advance opcodes better
27520          freedom in placing the annotations.  */
27521       note = find_reg_note (save_insn, REG_FRAME_RELATED_EXPR, NULL);
27522       if (note)
27523         remove_note (save_insn, note);
27524       else
27525         note = alloc_reg_note (REG_FRAME_RELATED_EXPR,
27526                                copy_rtx (PATTERN (save_insn)), NULL_RTX);
27527       RTX_FRAME_RELATED_P (save_insn) = 0;
27528
27529       join_insn = emit_insn (gen_blockage ());
27530       REG_NOTES (join_insn) = note;
27531       RTX_FRAME_RELATED_P (join_insn) = 1;
27532
27533       if (using_static_chain_p)
27534         {
27535           emit_move_insn (tmp_reg, gen_rtx_REG (Pmode, 0));
27536           END_USE (0);
27537         }
27538       else
27539         END_USE (11);
27540     }
27541
27542   /* Save CR if we use any that must be preserved.  */
27543   if (!WORLD_SAVE_P (info) && info->cr_save_p)
27544     {
27545       rtx addr = gen_rtx_PLUS (Pmode, frame_reg_rtx,
27546                                GEN_INT (info->cr_save_offset + frame_off));
27547       rtx mem = gen_frame_mem (SImode, addr);
27548
27549       /* If we didn't copy cr before, do so now using r0.  */
27550       if (cr_save_rtx == NULL_RTX)
27551         {
27552           START_USE (0);
27553           cr_save_rtx = gen_rtx_REG (SImode, 0);
27554           rs6000_emit_prologue_move_from_cr (cr_save_rtx);
27555         }
27556
27557       /* Saving CR requires a two-instruction sequence: one instruction
27558          to move the CR to a general-purpose register, and a second
27559          instruction that stores the GPR to memory.
27560
27561          We do not emit any DWARF CFI records for the first of these,
27562          because we cannot properly represent the fact that CR is saved in
27563          a register.  One reason is that we cannot express that multiple
27564          CR fields are saved; another reason is that on 64-bit, the size
27565          of the CR register in DWARF (4 bytes) differs from the size of
27566          a general-purpose register.
27567
27568          This means if any intervening instruction were to clobber one of
27569          the call-saved CR fields, we'd have incorrect CFI.  To prevent
27570          this from happening, we mark the store to memory as a use of
27571          those CR fields, which prevents any such instruction from being
27572          scheduled in between the two instructions.  */
27573       rtx crsave_v[9];
27574       int n_crsave = 0;
27575       int i;
27576
27577       crsave_v[n_crsave++] = gen_rtx_SET (mem, cr_save_rtx);
27578       for (i = 0; i < 8; i++)
27579         if (save_reg_p (CR0_REGNO + i))
27580           crsave_v[n_crsave++]
27581             = gen_rtx_USE (VOIDmode, gen_rtx_REG (CCmode, CR0_REGNO + i));
27582
27583       insn = emit_insn (gen_rtx_PARALLEL (VOIDmode,
27584                                           gen_rtvec_v (n_crsave, crsave_v)));
27585       END_USE (REGNO (cr_save_rtx));
27586
27587       /* Now, there's no way that dwarf2out_frame_debug_expr is going to
27588          understand '(unspec:SI [(reg:CC 68) ...] UNSPEC_MOVESI_FROM_CR)',
27589          so we need to construct a frame expression manually.  */
27590       RTX_FRAME_RELATED_P (insn) = 1;
27591
27592       /* Update address to be stack-pointer relative, like
27593          rs6000_frame_related would do.  */
27594       addr = gen_rtx_PLUS (Pmode, gen_rtx_REG (Pmode, STACK_POINTER_REGNUM),
27595                            GEN_INT (info->cr_save_offset + sp_off));
27596       mem = gen_frame_mem (SImode, addr);
27597
27598       if (DEFAULT_ABI == ABI_ELFv2)
27599         {
27600           /* In the ELFv2 ABI we generate separate CFI records for each
27601              CR field that was actually saved.  They all point to the
27602              same 32-bit stack slot.  */
27603           rtx crframe[8];
27604           int n_crframe = 0;
27605
27606           for (i = 0; i < 8; i++)
27607             if (save_reg_p (CR0_REGNO + i))
27608               {
27609                 crframe[n_crframe]
27610                   = gen_rtx_SET (mem, gen_rtx_REG (SImode, CR0_REGNO + i));
27611
27612                 RTX_FRAME_RELATED_P (crframe[n_crframe]) = 1;
27613                 n_crframe++;
27614              }
27615
27616           add_reg_note (insn, REG_FRAME_RELATED_EXPR,
27617                         gen_rtx_PARALLEL (VOIDmode,
27618                                           gen_rtvec_v (n_crframe, crframe)));
27619         }
27620       else
27621         {
27622           /* In other ABIs, by convention, we use a single CR regnum to
27623              represent the fact that all call-saved CR fields are saved.
27624              We use CR2_REGNO to be compatible with gcc-2.95 on Linux.  */
27625           rtx set = gen_rtx_SET (mem, gen_rtx_REG (SImode, CR2_REGNO));
27626           add_reg_note (insn, REG_FRAME_RELATED_EXPR, set);
27627         }
27628     }
27629
27630   /* In the ELFv2 ABI we need to save all call-saved CR fields into
27631      *separate* slots if the routine calls __builtin_eh_return, so
27632      that they can be independently restored by the unwinder.  */
27633   if (DEFAULT_ABI == ABI_ELFv2 && crtl->calls_eh_return)
27634     {
27635       int i, cr_off = info->ehcr_offset;
27636       rtx crsave;
27637
27638       /* ??? We might get better performance by using multiple mfocrf
27639          instructions.  */
27640       crsave = gen_rtx_REG (SImode, 0);
27641       emit_insn (gen_prologue_movesi_from_cr (crsave));
27642
27643       for (i = 0; i < 8; i++)
27644         if (!call_used_regs[CR0_REGNO + i])
27645           {
27646             rtvec p = rtvec_alloc (2);
27647             RTVEC_ELT (p, 0)
27648               = gen_frame_store (crsave, frame_reg_rtx, cr_off + frame_off);
27649             RTVEC_ELT (p, 1)
27650               = gen_rtx_USE (VOIDmode, gen_rtx_REG (CCmode, CR0_REGNO + i));
27651
27652             insn = emit_insn (gen_rtx_PARALLEL (VOIDmode, p));
27653
27654             RTX_FRAME_RELATED_P (insn) = 1;
27655             add_reg_note (insn, REG_FRAME_RELATED_EXPR,
27656                           gen_frame_store (gen_rtx_REG (SImode, CR0_REGNO + i),
27657                                            sp_reg_rtx, cr_off + sp_off));
27658
27659             cr_off += reg_size;
27660           }
27661     }
27662
27663   /* If we are emitting stack probes, but allocate no stack, then
27664      just note that in the dump file.  */
27665   if (flag_stack_clash_protection
27666       && dump_file
27667       && !info->push_p)
27668     dump_stack_clash_frame_info (NO_PROBE_NO_FRAME, false);
27669
27670   /* Update stack and set back pointer unless this is V.4,
27671      for which it was done previously.  */
27672   if (!WORLD_SAVE_P (info) && info->push_p
27673       && !(DEFAULT_ABI == ABI_V4 || crtl->calls_eh_return))
27674     {
27675       rtx ptr_reg = NULL;
27676       int ptr_off = 0;
27677
27678       /* If saving altivec regs we need to be able to address all save
27679          locations using a 16-bit offset.  */
27680       if ((strategy & SAVE_INLINE_VRS) == 0
27681           || (info->altivec_size != 0
27682               && (info->altivec_save_offset + info->altivec_size - 16
27683                   + info->total_size - frame_off) > 32767)
27684           || (info->vrsave_size != 0
27685               && (info->vrsave_save_offset
27686                   + info->total_size - frame_off) > 32767))
27687         {
27688           int sel = SAVRES_SAVE | SAVRES_VR;
27689           unsigned ptr_regno = ptr_regno_for_savres (sel);
27690
27691           if (using_static_chain_p
27692               && ptr_regno == STATIC_CHAIN_REGNUM)
27693             ptr_regno = 12;
27694           if (REGNO (frame_reg_rtx) != ptr_regno)
27695             START_USE (ptr_regno);
27696           ptr_reg = gen_rtx_REG (Pmode, ptr_regno);
27697           frame_reg_rtx = ptr_reg;
27698           ptr_off = info->altivec_save_offset + info->altivec_size;
27699           frame_off = -ptr_off;
27700         }
27701       else if (REGNO (frame_reg_rtx) == 1)
27702         frame_off = info->total_size;
27703       sp_adjust = rs6000_emit_allocate_stack (info->total_size,
27704                                               ptr_reg, ptr_off);
27705       if (REGNO (frame_reg_rtx) == 12)
27706         sp_adjust = 0;
27707       sp_off = info->total_size;
27708       if (frame_reg_rtx != sp_reg_rtx)
27709         rs6000_emit_stack_tie (frame_reg_rtx, false);
27710     }
27711
27712   /* Set frame pointer, if needed.  */
27713   if (frame_pointer_needed)
27714     {
27715       insn = emit_move_insn (gen_rtx_REG (Pmode, HARD_FRAME_POINTER_REGNUM),
27716                              sp_reg_rtx);
27717       RTX_FRAME_RELATED_P (insn) = 1;
27718     }
27719
27720   /* Save AltiVec registers if needed.  Save here because the red zone does
27721      not always include AltiVec registers.  */
27722   if (!WORLD_SAVE_P (info)
27723       && info->altivec_size != 0 && (strategy & SAVE_INLINE_VRS) == 0)
27724     {
27725       int end_save = info->altivec_save_offset + info->altivec_size;
27726       int ptr_off;
27727       /* Oddly, the vector save/restore functions point r0 at the end
27728          of the save area, then use r11 or r12 to load offsets for
27729          [reg+reg] addressing.  */
27730       rtx ptr_reg = gen_rtx_REG (Pmode, 0);
27731       int scratch_regno = ptr_regno_for_savres (SAVRES_SAVE | SAVRES_VR);
27732       rtx scratch_reg = gen_rtx_REG (Pmode, scratch_regno);
27733
27734       gcc_checking_assert (scratch_regno == 11 || scratch_regno == 12);
27735       NOT_INUSE (0);
27736       if (scratch_regno == 12)
27737         sp_adjust = 0;
27738       if (end_save + frame_off != 0)
27739         {
27740           rtx offset = GEN_INT (end_save + frame_off);
27741
27742           emit_insn (gen_add3_insn (ptr_reg, frame_reg_rtx, offset));
27743         }
27744       else
27745         emit_move_insn (ptr_reg, frame_reg_rtx);
27746
27747       ptr_off = -end_save;
27748       insn = rs6000_emit_savres_rtx (info, scratch_reg,
27749                                      info->altivec_save_offset + ptr_off,
27750                                      0, V4SImode, SAVRES_SAVE | SAVRES_VR);
27751       rs6000_frame_related (insn, scratch_reg, sp_off - ptr_off,
27752                             NULL_RTX, NULL_RTX);
27753       if (REGNO (frame_reg_rtx) == REGNO (scratch_reg))
27754         {
27755           /* The oddity mentioned above clobbered our frame reg.  */
27756           emit_move_insn (frame_reg_rtx, ptr_reg);
27757           frame_off = ptr_off;
27758         }
27759     }
27760   else if (!WORLD_SAVE_P (info)
27761            && info->altivec_size != 0)
27762     {
27763       int i;
27764
27765       for (i = info->first_altivec_reg_save; i <= LAST_ALTIVEC_REGNO; ++i)
27766         if (info->vrsave_mask & ALTIVEC_REG_BIT (i))
27767           {
27768             rtx areg, savereg, mem;
27769             HOST_WIDE_INT offset;
27770
27771             offset = (info->altivec_save_offset + frame_off
27772                       + 16 * (i - info->first_altivec_reg_save));
27773
27774             savereg = gen_rtx_REG (V4SImode, i);
27775
27776             if (TARGET_P9_VECTOR && quad_address_offset_p (offset))
27777               {
27778                 mem = gen_frame_mem (V4SImode,
27779                                      gen_rtx_PLUS (Pmode, frame_reg_rtx,
27780                                                    GEN_INT (offset)));
27781                 insn = emit_insn (gen_rtx_SET (mem, savereg));
27782                 areg = NULL_RTX;
27783               }
27784             else
27785               {
27786                 NOT_INUSE (0);
27787                 areg = gen_rtx_REG (Pmode, 0);
27788                 emit_move_insn (areg, GEN_INT (offset));
27789
27790                 /* AltiVec addressing mode is [reg+reg].  */
27791                 mem = gen_frame_mem (V4SImode,
27792                                      gen_rtx_PLUS (Pmode, frame_reg_rtx, areg));
27793
27794                 /* Rather than emitting a generic move, force use of the stvx
27795                    instruction, which we always want on ISA 2.07 (power8) systems.
27796                    In particular we don't want xxpermdi/stxvd2x for little
27797                    endian.  */
27798                 insn = emit_insn (gen_altivec_stvx_v4si_internal (mem, savereg));
27799               }
27800
27801             rs6000_frame_related (insn, frame_reg_rtx, sp_off - frame_off,
27802                                   areg, GEN_INT (offset));
27803           }
27804     }
27805
27806   /* VRSAVE is a bit vector representing which AltiVec registers
27807      are used.  The OS uses this to determine which vector
27808      registers to save on a context switch.  We need to save
27809      VRSAVE on the stack frame, add whatever AltiVec registers we
27810      used in this function, and do the corresponding magic in the
27811      epilogue.  */
27812
27813   if (!WORLD_SAVE_P (info) && info->vrsave_size != 0)
27814     {
27815       /* Get VRSAVE into a GPR.  Note that ABI_V4 and ABI_DARWIN might
27816          be using r12 as frame_reg_rtx and r11 as the static chain
27817          pointer for nested functions.  */
27818       int save_regno = 12;
27819       if ((DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
27820           && !using_static_chain_p)
27821         save_regno = 11;
27822       else if (using_split_stack || REGNO (frame_reg_rtx) == 12)
27823         {
27824           save_regno = 11;
27825           if (using_static_chain_p)
27826             save_regno = 0;
27827         }
27828       NOT_INUSE (save_regno);
27829
27830       emit_vrsave_prologue (info, save_regno, frame_off, frame_reg_rtx);
27831     }
27832
27833   /* If we are using RS6000_PIC_OFFSET_TABLE_REGNUM, we need to set it up.  */
27834   if (!TARGET_SINGLE_PIC_BASE
27835       && ((TARGET_TOC && TARGET_MINIMAL_TOC
27836            && !constant_pool_empty_p ())
27837           || (DEFAULT_ABI == ABI_V4
27838               && (flag_pic == 1 || (flag_pic && TARGET_SECURE_PLT))
27839               && df_regs_ever_live_p (RS6000_PIC_OFFSET_TABLE_REGNUM))))
27840     {
27841       /* If emit_load_toc_table will use the link register, we need to save
27842          it.  We use R12 for this purpose because emit_load_toc_table
27843          can use register 0.  This allows us to use a plain 'blr' to return
27844          from the procedure more often.  */
27845       int save_LR_around_toc_setup = (TARGET_ELF
27846                                       && DEFAULT_ABI == ABI_V4
27847                                       && flag_pic
27848                                       && ! info->lr_save_p
27849                                       && EDGE_COUNT (EXIT_BLOCK_PTR_FOR_FN (cfun)->preds) > 0);
27850       if (save_LR_around_toc_setup)
27851         {
27852           rtx lr = gen_rtx_REG (Pmode, LR_REGNO);
27853           rtx tmp = gen_rtx_REG (Pmode, 12);
27854
27855           sp_adjust = 0;
27856           insn = emit_move_insn (tmp, lr);
27857           RTX_FRAME_RELATED_P (insn) = 1;
27858
27859           rs6000_emit_load_toc_table (TRUE);
27860
27861           insn = emit_move_insn (lr, tmp);
27862           add_reg_note (insn, REG_CFA_RESTORE, lr);
27863           RTX_FRAME_RELATED_P (insn) = 1;
27864         }
27865       else
27866         rs6000_emit_load_toc_table (TRUE);
27867     }
27868
27869 #if TARGET_MACHO
27870   if (!TARGET_SINGLE_PIC_BASE
27871       && DEFAULT_ABI == ABI_DARWIN
27872       && flag_pic && crtl->uses_pic_offset_table)
27873     {
27874       rtx lr = gen_rtx_REG (Pmode, LR_REGNO);
27875       rtx src = gen_rtx_SYMBOL_REF (Pmode, MACHOPIC_FUNCTION_BASE_NAME);
27876
27877       /* Save and restore LR locally around this call (in R0).  */
27878       if (!info->lr_save_p)
27879         emit_move_insn (gen_rtx_REG (Pmode, 0), lr);
27880
27881       emit_insn (gen_load_macho_picbase (src));
27882
27883       emit_move_insn (gen_rtx_REG (Pmode,
27884                                    RS6000_PIC_OFFSET_TABLE_REGNUM),
27885                       lr);
27886
27887       if (!info->lr_save_p)
27888         emit_move_insn (lr, gen_rtx_REG (Pmode, 0));
27889     }
27890 #endif
27891
27892   /* If we need to, save the TOC register after doing the stack setup.
27893      Do not emit eh frame info for this save.  The unwinder wants info,
27894      conceptually attached to instructions in this function, about
27895      register values in the caller of this function.  This R2 may have
27896      already been changed from the value in the caller.
27897      We don't attempt to write accurate DWARF EH frame info for R2
27898      because code emitted by gcc for a (non-pointer) function call
27899      doesn't save and restore R2.  Instead, R2 is managed out-of-line
27900      by a linker generated plt call stub when the function resides in
27901      a shared library.  This behavior is costly to describe in DWARF,
27902      both in terms of the size of DWARF info and the time taken in the
27903      unwinder to interpret it.  R2 changes, apart from the
27904      calls_eh_return case earlier in this function, are handled by
27905      linux-unwind.h frob_update_context.  */
27906   if (rs6000_save_toc_in_prologue_p ()
27907       && !cfun->machine->toc_is_wrapped_separately)
27908     {
27909       rtx reg = gen_rtx_REG (reg_mode, TOC_REGNUM);
27910       emit_insn (gen_frame_store (reg, sp_reg_rtx, RS6000_TOC_SAVE_SLOT));
27911     }
27912
27913   /* Set up the arg pointer (r12) for -fsplit-stack code.  */
27914   if (using_split_stack && split_stack_arg_pointer_used_p ())
27915     emit_split_stack_prologue (info, sp_adjust, frame_off, frame_reg_rtx);
27916 }
27917
27918 /* Output .extern statements for the save/restore routines we use.  */
27919
27920 static void
27921 rs6000_output_savres_externs (FILE *file)
27922 {
27923   rs6000_stack_t *info = rs6000_stack_info ();
27924
27925   if (TARGET_DEBUG_STACK)
27926     debug_stack_info (info);
27927
27928   /* Write .extern for any function we will call to save and restore
27929      fp values.  */
27930   if (info->first_fp_reg_save < 64
27931       && !TARGET_MACHO
27932       && !TARGET_ELF)
27933     {
27934       char *name;
27935       int regno = info->first_fp_reg_save - 32;
27936
27937       if ((info->savres_strategy & SAVE_INLINE_FPRS) == 0)
27938         {
27939           bool lr = (info->savres_strategy & SAVE_NOINLINE_FPRS_SAVES_LR) != 0;
27940           int sel = SAVRES_SAVE | SAVRES_FPR | (lr ? SAVRES_LR : 0);
27941           name = rs6000_savres_routine_name (regno, sel);
27942           fprintf (file, "\t.extern %s\n", name);
27943         }
27944       if ((info->savres_strategy & REST_INLINE_FPRS) == 0)
27945         {
27946           bool lr = (info->savres_strategy
27947                      & REST_NOINLINE_FPRS_DOESNT_RESTORE_LR) == 0;
27948           int sel = SAVRES_FPR | (lr ? SAVRES_LR : 0);
27949           name = rs6000_savres_routine_name (regno, sel);
27950           fprintf (file, "\t.extern %s\n", name);
27951         }
27952     }
27953 }
27954
27955 /* Write function prologue.  */
27956
27957 static void
27958 rs6000_output_function_prologue (FILE *file)
27959 {
27960   if (!cfun->is_thunk)
27961     rs6000_output_savres_externs (file);
27962
27963   /* ELFv2 ABI r2 setup code and local entry point.  This must follow
27964      immediately after the global entry point label.  */
27965   if (rs6000_global_entry_point_needed_p ())
27966     {
27967       const char *name = XSTR (XEXP (DECL_RTL (current_function_decl), 0), 0);
27968
27969       (*targetm.asm_out.internal_label) (file, "LCF", rs6000_pic_labelno);
27970
27971       if (TARGET_CMODEL != CMODEL_LARGE)
27972         {
27973           /* In the small and medium code models, we assume the TOC is less
27974              2 GB away from the text section, so it can be computed via the
27975              following two-instruction sequence.  */
27976           char buf[256];
27977
27978           ASM_GENERATE_INTERNAL_LABEL (buf, "LCF", rs6000_pic_labelno);
27979           fprintf (file, "0:\taddis 2,12,.TOC.-");
27980           assemble_name (file, buf);
27981           fprintf (file, "@ha\n");
27982           fprintf (file, "\taddi 2,2,.TOC.-");
27983           assemble_name (file, buf);
27984           fprintf (file, "@l\n");
27985         }
27986       else
27987         {
27988           /* In the large code model, we allow arbitrary offsets between the
27989              TOC and the text section, so we have to load the offset from
27990              memory.  The data field is emitted directly before the global
27991              entry point in rs6000_elf_declare_function_name.  */
27992           char buf[256];
27993
27994 #ifdef HAVE_AS_ENTRY_MARKERS
27995           /* If supported by the linker, emit a marker relocation.  If the
27996              total code size of the final executable or shared library
27997              happens to fit into 2 GB after all, the linker will replace
27998              this code sequence with the sequence for the small or medium
27999              code model.  */
28000           fprintf (file, "\t.reloc .,R_PPC64_ENTRY\n");
28001 #endif
28002           fprintf (file, "\tld 2,");
28003           ASM_GENERATE_INTERNAL_LABEL (buf, "LCL", rs6000_pic_labelno);
28004           assemble_name (file, buf);
28005           fprintf (file, "-");
28006           ASM_GENERATE_INTERNAL_LABEL (buf, "LCF", rs6000_pic_labelno);
28007           assemble_name (file, buf);
28008           fprintf (file, "(12)\n");
28009           fprintf (file, "\tadd 2,2,12\n");
28010         }
28011
28012       fputs ("\t.localentry\t", file);
28013       assemble_name (file, name);
28014       fputs (",.-", file);
28015       assemble_name (file, name);
28016       fputs ("\n", file);
28017     }
28018
28019   /* Output -mprofile-kernel code.  This needs to be done here instead of
28020      in output_function_profile since it must go after the ELFv2 ABI
28021      local entry point.  */
28022   if (TARGET_PROFILE_KERNEL && crtl->profile)
28023     {
28024       gcc_assert (DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2);
28025       gcc_assert (!TARGET_32BIT);
28026
28027       asm_fprintf (file, "\tmflr %s\n", reg_names[0]);
28028
28029       /* In the ELFv2 ABI we have no compiler stack word.  It must be
28030          the resposibility of _mcount to preserve the static chain
28031          register if required.  */
28032       if (DEFAULT_ABI != ABI_ELFv2
28033           && cfun->static_chain_decl != NULL)
28034         {
28035           asm_fprintf (file, "\tstd %s,24(%s)\n",
28036                        reg_names[STATIC_CHAIN_REGNUM], reg_names[1]);
28037           fprintf (file, "\tbl %s\n", RS6000_MCOUNT);
28038           asm_fprintf (file, "\tld %s,24(%s)\n",
28039                        reg_names[STATIC_CHAIN_REGNUM], reg_names[1]);
28040         }
28041       else
28042         fprintf (file, "\tbl %s\n", RS6000_MCOUNT);
28043     }
28044
28045   rs6000_pic_labelno++;
28046 }
28047
28048 /* -mprofile-kernel code calls mcount before the function prolog,
28049    so a profiled leaf function should stay a leaf function.  */
28050 static bool
28051 rs6000_keep_leaf_when_profiled ()
28052 {
28053   return TARGET_PROFILE_KERNEL;
28054 }
28055
28056 /* Non-zero if vmx regs are restored before the frame pop, zero if
28057    we restore after the pop when possible.  */
28058 #define ALWAYS_RESTORE_ALTIVEC_BEFORE_POP 0
28059
28060 /* Restoring cr is a two step process: loading a reg from the frame
28061    save, then moving the reg to cr.  For ABI_V4 we must let the
28062    unwinder know that the stack location is no longer valid at or
28063    before the stack deallocation, but we can't emit a cfa_restore for
28064    cr at the stack deallocation like we do for other registers.
28065    The trouble is that it is possible for the move to cr to be
28066    scheduled after the stack deallocation.  So say exactly where cr
28067    is located on each of the two insns.  */
28068
28069 static rtx
28070 load_cr_save (int regno, rtx frame_reg_rtx, int offset, bool exit_func)
28071 {
28072   rtx mem = gen_frame_mem_offset (SImode, frame_reg_rtx, offset);
28073   rtx reg = gen_rtx_REG (SImode, regno);
28074   rtx_insn *insn = emit_move_insn (reg, mem);
28075
28076   if (!exit_func && DEFAULT_ABI == ABI_V4)
28077     {
28078       rtx cr = gen_rtx_REG (SImode, CR2_REGNO);
28079       rtx set = gen_rtx_SET (reg, cr);
28080
28081       add_reg_note (insn, REG_CFA_REGISTER, set);
28082       RTX_FRAME_RELATED_P (insn) = 1;
28083     }
28084   return reg;
28085 }
28086
28087 /* Reload CR from REG.  */
28088
28089 static void
28090 restore_saved_cr (rtx reg, int using_mfcr_multiple, bool exit_func)
28091 {
28092   int count = 0;
28093   int i;
28094
28095   if (using_mfcr_multiple)
28096     {
28097       for (i = 0; i < 8; i++)
28098         if (save_reg_p (CR0_REGNO + i))
28099           count++;
28100       gcc_assert (count);
28101     }
28102
28103   if (using_mfcr_multiple && count > 1)
28104     {
28105       rtx_insn *insn;
28106       rtvec p;
28107       int ndx;
28108
28109       p = rtvec_alloc (count);
28110
28111       ndx = 0;
28112       for (i = 0; i < 8; i++)
28113         if (save_reg_p (CR0_REGNO + i))
28114           {
28115             rtvec r = rtvec_alloc (2);
28116             RTVEC_ELT (r, 0) = reg;
28117             RTVEC_ELT (r, 1) = GEN_INT (1 << (7-i));
28118             RTVEC_ELT (p, ndx) =
28119               gen_rtx_SET (gen_rtx_REG (CCmode, CR0_REGNO + i),
28120                            gen_rtx_UNSPEC (CCmode, r, UNSPEC_MOVESI_TO_CR));
28121             ndx++;
28122           }
28123       insn = emit_insn (gen_rtx_PARALLEL (VOIDmode, p));
28124       gcc_assert (ndx == count);
28125
28126       /* For the ELFv2 ABI we generate a CFA_RESTORE for each
28127          CR field separately.  */
28128       if (!exit_func && DEFAULT_ABI == ABI_ELFv2 && flag_shrink_wrap)
28129         {
28130           for (i = 0; i < 8; i++)
28131             if (save_reg_p (CR0_REGNO + i))
28132               add_reg_note (insn, REG_CFA_RESTORE,
28133                             gen_rtx_REG (SImode, CR0_REGNO + i));
28134
28135           RTX_FRAME_RELATED_P (insn) = 1;
28136         }
28137     }
28138   else
28139     for (i = 0; i < 8; i++)
28140       if (save_reg_p (CR0_REGNO + i))
28141         {
28142           rtx insn = emit_insn (gen_movsi_to_cr_one
28143                                  (gen_rtx_REG (CCmode, CR0_REGNO + i), reg));
28144
28145           /* For the ELFv2 ABI we generate a CFA_RESTORE for each
28146              CR field separately, attached to the insn that in fact
28147              restores this particular CR field.  */
28148           if (!exit_func && DEFAULT_ABI == ABI_ELFv2 && flag_shrink_wrap)
28149             {
28150               add_reg_note (insn, REG_CFA_RESTORE,
28151                             gen_rtx_REG (SImode, CR0_REGNO + i));
28152
28153               RTX_FRAME_RELATED_P (insn) = 1;
28154             }
28155         }
28156
28157   /* For other ABIs, we just generate a single CFA_RESTORE for CR2.  */
28158   if (!exit_func && DEFAULT_ABI != ABI_ELFv2
28159       && (DEFAULT_ABI == ABI_V4 || flag_shrink_wrap))
28160     {
28161       rtx_insn *insn = get_last_insn ();
28162       rtx cr = gen_rtx_REG (SImode, CR2_REGNO);
28163
28164       add_reg_note (insn, REG_CFA_RESTORE, cr);
28165       RTX_FRAME_RELATED_P (insn) = 1;
28166     }
28167 }
28168
28169 /* Like cr, the move to lr instruction can be scheduled after the
28170    stack deallocation, but unlike cr, its stack frame save is still
28171    valid.  So we only need to emit the cfa_restore on the correct
28172    instruction.  */
28173
28174 static void
28175 load_lr_save (int regno, rtx frame_reg_rtx, int offset)
28176 {
28177   rtx mem = gen_frame_mem_offset (Pmode, frame_reg_rtx, offset);
28178   rtx reg = gen_rtx_REG (Pmode, regno);
28179
28180   emit_move_insn (reg, mem);
28181 }
28182
28183 static void
28184 restore_saved_lr (int regno, bool exit_func)
28185 {
28186   rtx reg = gen_rtx_REG (Pmode, regno);
28187   rtx lr = gen_rtx_REG (Pmode, LR_REGNO);
28188   rtx_insn *insn = emit_move_insn (lr, reg);
28189
28190   if (!exit_func && flag_shrink_wrap)
28191     {
28192       add_reg_note (insn, REG_CFA_RESTORE, lr);
28193       RTX_FRAME_RELATED_P (insn) = 1;
28194     }
28195 }
28196
28197 static rtx
28198 add_crlr_cfa_restore (const rs6000_stack_t *info, rtx cfa_restores)
28199 {
28200   if (DEFAULT_ABI == ABI_ELFv2)
28201     {
28202       int i;
28203       for (i = 0; i < 8; i++)
28204         if (save_reg_p (CR0_REGNO + i))
28205           {
28206             rtx cr = gen_rtx_REG (SImode, CR0_REGNO + i);
28207             cfa_restores = alloc_reg_note (REG_CFA_RESTORE, cr,
28208                                            cfa_restores);
28209           }
28210     }
28211   else if (info->cr_save_p)
28212     cfa_restores = alloc_reg_note (REG_CFA_RESTORE,
28213                                    gen_rtx_REG (SImode, CR2_REGNO),
28214                                    cfa_restores);
28215
28216   if (info->lr_save_p)
28217     cfa_restores = alloc_reg_note (REG_CFA_RESTORE,
28218                                    gen_rtx_REG (Pmode, LR_REGNO),
28219                                    cfa_restores);
28220   return cfa_restores;
28221 }
28222
28223 /* Return true if OFFSET from stack pointer can be clobbered by signals.
28224    V.4 doesn't have any stack cushion, AIX ABIs have 220 or 288 bytes
28225    below stack pointer not cloberred by signals.  */
28226
28227 static inline bool
28228 offset_below_red_zone_p (HOST_WIDE_INT offset)
28229 {
28230   return offset < (DEFAULT_ABI == ABI_V4
28231                    ? 0
28232                    : TARGET_32BIT ? -220 : -288);
28233 }
28234
28235 /* Append CFA_RESTORES to any existing REG_NOTES on the last insn.  */
28236
28237 static void
28238 emit_cfa_restores (rtx cfa_restores)
28239 {
28240   rtx_insn *insn = get_last_insn ();
28241   rtx *loc = &REG_NOTES (insn);
28242
28243   while (*loc)
28244     loc = &XEXP (*loc, 1);
28245   *loc = cfa_restores;
28246   RTX_FRAME_RELATED_P (insn) = 1;
28247 }
28248
28249 /* Emit function epilogue as insns.  */
28250
28251 void
28252 rs6000_emit_epilogue (int sibcall)
28253 {
28254   rs6000_stack_t *info;
28255   int restoring_GPRs_inline;
28256   int restoring_FPRs_inline;
28257   int using_load_multiple;
28258   int using_mtcr_multiple;
28259   int use_backchain_to_restore_sp;
28260   int restore_lr;
28261   int strategy;
28262   HOST_WIDE_INT frame_off = 0;
28263   rtx sp_reg_rtx = gen_rtx_REG (Pmode, 1);
28264   rtx frame_reg_rtx = sp_reg_rtx;
28265   rtx cfa_restores = NULL_RTX;
28266   rtx insn;
28267   rtx cr_save_reg = NULL_RTX;
28268   machine_mode reg_mode = Pmode;
28269   int reg_size = TARGET_32BIT ? 4 : 8;
28270   machine_mode fp_reg_mode = (TARGET_HARD_FLOAT && TARGET_DOUBLE_FLOAT)
28271                              ? DFmode : SFmode;
28272   int fp_reg_size = 8;
28273   int i;
28274   bool exit_func;
28275   unsigned ptr_regno;
28276
28277   info = rs6000_stack_info ();
28278
28279   strategy = info->savres_strategy;
28280   using_load_multiple = strategy & REST_MULTIPLE;
28281   restoring_FPRs_inline = sibcall || (strategy & REST_INLINE_FPRS);
28282   restoring_GPRs_inline = sibcall || (strategy & REST_INLINE_GPRS);
28283   using_mtcr_multiple = (rs6000_tune == PROCESSOR_PPC601
28284                          || rs6000_tune == PROCESSOR_PPC603
28285                          || rs6000_tune == PROCESSOR_PPC750
28286                          || optimize_size);
28287   /* Restore via the backchain when we have a large frame, since this
28288      is more efficient than an addis, addi pair.  The second condition
28289      here will not trigger at the moment;  We don't actually need a
28290      frame pointer for alloca, but the generic parts of the compiler
28291      give us one anyway.  */
28292   use_backchain_to_restore_sp = (info->total_size + (info->lr_save_p
28293                                                      ? info->lr_save_offset
28294                                                      : 0) > 32767
28295                                  || (cfun->calls_alloca
28296                                      && !frame_pointer_needed));
28297   restore_lr = (info->lr_save_p
28298                 && (restoring_FPRs_inline
28299                     || (strategy & REST_NOINLINE_FPRS_DOESNT_RESTORE_LR))
28300                 && (restoring_GPRs_inline
28301                     || info->first_fp_reg_save < 64)
28302                 && !cfun->machine->lr_is_wrapped_separately);
28303
28304
28305   if (WORLD_SAVE_P (info))
28306     {
28307       int i, j;
28308       char rname[30];
28309       const char *alloc_rname;
28310       rtvec p;
28311
28312       /* eh_rest_world_r10 will return to the location saved in the LR
28313          stack slot (which is not likely to be our caller.)
28314          Input: R10 -- stack adjustment.  Clobbers R0, R11, R12, R7, R8.
28315          rest_world is similar, except any R10 parameter is ignored.
28316          The exception-handling stuff that was here in 2.95 is no
28317          longer necessary.  */
28318
28319       p = rtvec_alloc (9
28320                        + 32 - info->first_gp_reg_save
28321                        + LAST_ALTIVEC_REGNO + 1 - info->first_altivec_reg_save
28322                        + 63 + 1 - info->first_fp_reg_save);
28323
28324       strcpy (rname, ((crtl->calls_eh_return) ?
28325                       "*eh_rest_world_r10" : "*rest_world"));
28326       alloc_rname = ggc_strdup (rname);
28327
28328       j = 0;
28329       RTVEC_ELT (p, j++) = ret_rtx;
28330       RTVEC_ELT (p, j++)
28331         = gen_rtx_USE (VOIDmode, gen_rtx_SYMBOL_REF (Pmode, alloc_rname));
28332       /* The instruction pattern requires a clobber here;
28333          it is shared with the restVEC helper. */
28334       RTVEC_ELT (p, j++)
28335         = gen_rtx_CLOBBER (VOIDmode, gen_rtx_REG (Pmode, 11));
28336
28337       {
28338         /* CR register traditionally saved as CR2.  */
28339         rtx reg = gen_rtx_REG (SImode, CR2_REGNO);
28340         RTVEC_ELT (p, j++)
28341           = gen_frame_load (reg, frame_reg_rtx, info->cr_save_offset);
28342         if (flag_shrink_wrap)
28343           {
28344             cfa_restores = alloc_reg_note (REG_CFA_RESTORE,
28345                                            gen_rtx_REG (Pmode, LR_REGNO),
28346                                            cfa_restores);
28347             cfa_restores = alloc_reg_note (REG_CFA_RESTORE, reg, cfa_restores);
28348           }
28349       }
28350
28351       for (i = 0; i < 32 - info->first_gp_reg_save; i++)
28352         {
28353           rtx reg = gen_rtx_REG (reg_mode, info->first_gp_reg_save + i);
28354           RTVEC_ELT (p, j++)
28355             = gen_frame_load (reg,
28356                               frame_reg_rtx, info->gp_save_offset + reg_size * i);
28357           if (flag_shrink_wrap
28358               && save_reg_p (info->first_gp_reg_save + i))
28359             cfa_restores = alloc_reg_note (REG_CFA_RESTORE, reg, cfa_restores);
28360         }
28361       for (i = 0; info->first_altivec_reg_save + i <= LAST_ALTIVEC_REGNO; i++)
28362         {
28363           rtx reg = gen_rtx_REG (V4SImode, info->first_altivec_reg_save + i);
28364           RTVEC_ELT (p, j++)
28365             = gen_frame_load (reg,
28366                               frame_reg_rtx, info->altivec_save_offset + 16 * i);
28367           if (flag_shrink_wrap
28368               && save_reg_p (info->first_altivec_reg_save + i))
28369             cfa_restores = alloc_reg_note (REG_CFA_RESTORE, reg, cfa_restores);
28370         }
28371       for (i = 0; info->first_fp_reg_save + i <= 63; i++)
28372         {
28373           rtx reg = gen_rtx_REG ((TARGET_HARD_FLOAT && TARGET_DOUBLE_FLOAT
28374                                   ? DFmode : SFmode),
28375                                  info->first_fp_reg_save + i);
28376           RTVEC_ELT (p, j++)
28377             = gen_frame_load (reg, frame_reg_rtx, info->fp_save_offset + 8 * i);
28378           if (flag_shrink_wrap
28379               && save_reg_p (info->first_fp_reg_save + i))
28380             cfa_restores = alloc_reg_note (REG_CFA_RESTORE, reg, cfa_restores);
28381         }
28382       RTVEC_ELT (p, j++)
28383         = gen_rtx_CLOBBER (VOIDmode, gen_rtx_REG (Pmode, 0));
28384       RTVEC_ELT (p, j++)
28385         = gen_rtx_CLOBBER (VOIDmode, gen_rtx_REG (SImode, 12));
28386       RTVEC_ELT (p, j++)
28387         = gen_rtx_CLOBBER (VOIDmode, gen_rtx_REG (SImode, 7));
28388       RTVEC_ELT (p, j++)
28389         = gen_rtx_CLOBBER (VOIDmode, gen_rtx_REG (SImode, 8));
28390       RTVEC_ELT (p, j++)
28391         = gen_rtx_USE (VOIDmode, gen_rtx_REG (SImode, 10));
28392       insn = emit_jump_insn (gen_rtx_PARALLEL (VOIDmode, p));
28393
28394       if (flag_shrink_wrap)
28395         {
28396           REG_NOTES (insn) = cfa_restores;
28397           add_reg_note (insn, REG_CFA_DEF_CFA, sp_reg_rtx);
28398           RTX_FRAME_RELATED_P (insn) = 1;
28399         }
28400       return;
28401     }
28402
28403   /* frame_reg_rtx + frame_off points to the top of this stack frame.  */
28404   if (info->push_p)
28405     frame_off = info->total_size;
28406
28407   /* Restore AltiVec registers if we must do so before adjusting the
28408      stack.  */
28409   if (info->altivec_size != 0
28410       && (ALWAYS_RESTORE_ALTIVEC_BEFORE_POP
28411           || (DEFAULT_ABI != ABI_V4
28412               && offset_below_red_zone_p (info->altivec_save_offset))))
28413     {
28414       int i;
28415       int scratch_regno = ptr_regno_for_savres (SAVRES_VR);
28416
28417       gcc_checking_assert (scratch_regno == 11 || scratch_regno == 12);
28418       if (use_backchain_to_restore_sp)
28419         {
28420           int frame_regno = 11;
28421
28422           if ((strategy & REST_INLINE_VRS) == 0)
28423             {
28424               /* Of r11 and r12, select the one not clobbered by an
28425                  out-of-line restore function for the frame register.  */
28426               frame_regno = 11 + 12 - scratch_regno;
28427             }
28428           frame_reg_rtx = gen_rtx_REG (Pmode, frame_regno);
28429           emit_move_insn (frame_reg_rtx,
28430                           gen_rtx_MEM (Pmode, sp_reg_rtx));
28431           frame_off = 0;
28432         }
28433       else if (frame_pointer_needed)
28434         frame_reg_rtx = hard_frame_pointer_rtx;
28435
28436       if ((strategy & REST_INLINE_VRS) == 0)
28437         {
28438           int end_save = info->altivec_save_offset + info->altivec_size;
28439           int ptr_off;
28440           rtx ptr_reg = gen_rtx_REG (Pmode, 0);
28441           rtx scratch_reg = gen_rtx_REG (Pmode, scratch_regno);
28442
28443           if (end_save + frame_off != 0)
28444             {
28445               rtx offset = GEN_INT (end_save + frame_off);
28446
28447               emit_insn (gen_add3_insn (ptr_reg, frame_reg_rtx, offset));
28448             }
28449           else
28450             emit_move_insn (ptr_reg, frame_reg_rtx);
28451
28452           ptr_off = -end_save;
28453           insn = rs6000_emit_savres_rtx (info, scratch_reg,
28454                                          info->altivec_save_offset + ptr_off,
28455                                          0, V4SImode, SAVRES_VR);
28456         }
28457       else
28458         {
28459           for (i = info->first_altivec_reg_save; i <= LAST_ALTIVEC_REGNO; ++i)
28460             if (info->vrsave_mask & ALTIVEC_REG_BIT (i))
28461               {
28462                 rtx addr, areg, mem, insn;
28463                 rtx reg = gen_rtx_REG (V4SImode, i);
28464                 HOST_WIDE_INT offset
28465                   = (info->altivec_save_offset + frame_off
28466                      + 16 * (i - info->first_altivec_reg_save));
28467
28468                 if (TARGET_P9_VECTOR && quad_address_offset_p (offset))
28469                   {
28470                     mem = gen_frame_mem (V4SImode,
28471                                          gen_rtx_PLUS (Pmode, frame_reg_rtx,
28472                                                        GEN_INT (offset)));
28473                     insn = gen_rtx_SET (reg, mem);
28474                   }
28475                 else
28476                   {
28477                     areg = gen_rtx_REG (Pmode, 0);
28478                     emit_move_insn (areg, GEN_INT (offset));
28479
28480                     /* AltiVec addressing mode is [reg+reg].  */
28481                     addr = gen_rtx_PLUS (Pmode, frame_reg_rtx, areg);
28482                     mem = gen_frame_mem (V4SImode, addr);
28483
28484                     /* Rather than emitting a generic move, force use of the
28485                        lvx instruction, which we always want.  In particular we
28486                        don't want lxvd2x/xxpermdi for little endian.  */
28487                     insn = gen_altivec_lvx_v4si_internal (reg, mem);
28488                   }
28489
28490                 (void) emit_insn (insn);
28491               }
28492         }
28493
28494       for (i = info->first_altivec_reg_save; i <= LAST_ALTIVEC_REGNO; ++i)
28495         if (((strategy & REST_INLINE_VRS) == 0
28496              || (info->vrsave_mask & ALTIVEC_REG_BIT (i)) != 0)
28497             && (flag_shrink_wrap
28498                 || (offset_below_red_zone_p
28499                     (info->altivec_save_offset
28500                      + 16 * (i - info->first_altivec_reg_save))))
28501             && save_reg_p (i))
28502           {
28503             rtx reg = gen_rtx_REG (V4SImode, i);
28504             cfa_restores = alloc_reg_note (REG_CFA_RESTORE, reg, cfa_restores);
28505           }
28506     }
28507
28508   /* Restore VRSAVE if we must do so before adjusting the stack.  */
28509   if (info->vrsave_size != 0
28510       && (ALWAYS_RESTORE_ALTIVEC_BEFORE_POP
28511           || (DEFAULT_ABI != ABI_V4
28512               && offset_below_red_zone_p (info->vrsave_save_offset))))
28513     {
28514       rtx reg;
28515
28516       if (frame_reg_rtx == sp_reg_rtx)
28517         {
28518           if (use_backchain_to_restore_sp)
28519             {
28520               frame_reg_rtx = gen_rtx_REG (Pmode, 11);
28521               emit_move_insn (frame_reg_rtx,
28522                               gen_rtx_MEM (Pmode, sp_reg_rtx));
28523               frame_off = 0;
28524             }
28525           else if (frame_pointer_needed)
28526             frame_reg_rtx = hard_frame_pointer_rtx;
28527         }
28528
28529       reg = gen_rtx_REG (SImode, 12);
28530       emit_insn (gen_frame_load (reg, frame_reg_rtx,
28531                                  info->vrsave_save_offset + frame_off));
28532
28533       emit_insn (generate_set_vrsave (reg, info, 1));
28534     }
28535
28536   insn = NULL_RTX;
28537   /* If we have a large stack frame, restore the old stack pointer
28538      using the backchain.  */
28539   if (use_backchain_to_restore_sp)
28540     {
28541       if (frame_reg_rtx == sp_reg_rtx)
28542         {
28543           /* Under V.4, don't reset the stack pointer until after we're done
28544              loading the saved registers.  */
28545           if (DEFAULT_ABI == ABI_V4)
28546             frame_reg_rtx = gen_rtx_REG (Pmode, 11);
28547
28548           insn = emit_move_insn (frame_reg_rtx,
28549                                  gen_rtx_MEM (Pmode, sp_reg_rtx));
28550           frame_off = 0;
28551         }
28552       else if (ALWAYS_RESTORE_ALTIVEC_BEFORE_POP
28553                && DEFAULT_ABI == ABI_V4)
28554         /* frame_reg_rtx has been set up by the altivec restore.  */
28555         ;
28556       else
28557         {
28558           insn = emit_move_insn (sp_reg_rtx, frame_reg_rtx);
28559           frame_reg_rtx = sp_reg_rtx;
28560         }
28561     }
28562   /* If we have a frame pointer, we can restore the old stack pointer
28563      from it.  */
28564   else if (frame_pointer_needed)
28565     {
28566       frame_reg_rtx = sp_reg_rtx;
28567       if (DEFAULT_ABI == ABI_V4)
28568         frame_reg_rtx = gen_rtx_REG (Pmode, 11);
28569       /* Prevent reordering memory accesses against stack pointer restore.  */
28570       else if (cfun->calls_alloca
28571                || offset_below_red_zone_p (-info->total_size))
28572         rs6000_emit_stack_tie (frame_reg_rtx, true);
28573
28574       insn = emit_insn (gen_add3_insn (frame_reg_rtx, hard_frame_pointer_rtx,
28575                                        GEN_INT (info->total_size)));
28576       frame_off = 0;
28577     }
28578   else if (info->push_p
28579            && DEFAULT_ABI != ABI_V4
28580            && !crtl->calls_eh_return)
28581     {
28582       /* Prevent reordering memory accesses against stack pointer restore.  */
28583       if (cfun->calls_alloca
28584           || offset_below_red_zone_p (-info->total_size))
28585         rs6000_emit_stack_tie (frame_reg_rtx, false);
28586       insn = emit_insn (gen_add3_insn (sp_reg_rtx, sp_reg_rtx,
28587                                        GEN_INT (info->total_size)));
28588       frame_off = 0;
28589     }
28590   if (insn && frame_reg_rtx == sp_reg_rtx)
28591     {
28592       if (cfa_restores)
28593         {
28594           REG_NOTES (insn) = cfa_restores;
28595           cfa_restores = NULL_RTX;
28596         }
28597       add_reg_note (insn, REG_CFA_DEF_CFA, sp_reg_rtx);
28598       RTX_FRAME_RELATED_P (insn) = 1;
28599     }
28600
28601   /* Restore AltiVec registers if we have not done so already.  */
28602   if (!ALWAYS_RESTORE_ALTIVEC_BEFORE_POP
28603       && info->altivec_size != 0
28604       && (DEFAULT_ABI == ABI_V4
28605           || !offset_below_red_zone_p (info->altivec_save_offset)))
28606     {
28607       int i;
28608
28609       if ((strategy & REST_INLINE_VRS) == 0)
28610         {
28611           int end_save = info->altivec_save_offset + info->altivec_size;
28612           int ptr_off;
28613           rtx ptr_reg = gen_rtx_REG (Pmode, 0);
28614           int scratch_regno = ptr_regno_for_savres (SAVRES_VR);
28615           rtx scratch_reg = gen_rtx_REG (Pmode, scratch_regno);
28616
28617           if (end_save + frame_off != 0)
28618             {
28619               rtx offset = GEN_INT (end_save + frame_off);
28620
28621               emit_insn (gen_add3_insn (ptr_reg, frame_reg_rtx, offset));
28622             }
28623           else
28624             emit_move_insn (ptr_reg, frame_reg_rtx);
28625
28626           ptr_off = -end_save;
28627           insn = rs6000_emit_savres_rtx (info, scratch_reg,
28628                                          info->altivec_save_offset + ptr_off,
28629                                          0, V4SImode, SAVRES_VR);
28630           if (REGNO (frame_reg_rtx) == REGNO (scratch_reg))
28631             {
28632               /* Frame reg was clobbered by out-of-line save.  Restore it
28633                  from ptr_reg, and if we are calling out-of-line gpr or
28634                  fpr restore set up the correct pointer and offset.  */
28635               unsigned newptr_regno = 1;
28636               if (!restoring_GPRs_inline)
28637                 {
28638                   bool lr = info->gp_save_offset + info->gp_size == 0;
28639                   int sel = SAVRES_GPR | (lr ? SAVRES_LR : 0);
28640                   newptr_regno = ptr_regno_for_savres (sel);
28641                   end_save = info->gp_save_offset + info->gp_size;
28642                 }
28643               else if (!restoring_FPRs_inline)
28644                 {
28645                   bool lr = !(strategy & REST_NOINLINE_FPRS_DOESNT_RESTORE_LR);
28646                   int sel = SAVRES_FPR | (lr ? SAVRES_LR : 0);
28647                   newptr_regno = ptr_regno_for_savres (sel);
28648                   end_save = info->fp_save_offset + info->fp_size;
28649                 }
28650
28651               if (newptr_regno != 1 && REGNO (frame_reg_rtx) != newptr_regno)
28652                 frame_reg_rtx = gen_rtx_REG (Pmode, newptr_regno);
28653                 
28654               if (end_save + ptr_off != 0)
28655                 {
28656                   rtx offset = GEN_INT (end_save + ptr_off);
28657
28658                   frame_off = -end_save;
28659                   if (TARGET_32BIT)
28660                     emit_insn (gen_addsi3_carry (frame_reg_rtx,
28661                                                  ptr_reg, offset));
28662                   else
28663                     emit_insn (gen_adddi3_carry (frame_reg_rtx,
28664                                                  ptr_reg, offset));
28665                 }
28666               else
28667                 {
28668                   frame_off = ptr_off;
28669                   emit_move_insn (frame_reg_rtx, ptr_reg);
28670                 }
28671             }
28672         }
28673       else
28674         {
28675           for (i = info->first_altivec_reg_save; i <= LAST_ALTIVEC_REGNO; ++i)
28676             if (info->vrsave_mask & ALTIVEC_REG_BIT (i))
28677               {
28678                 rtx addr, areg, mem, insn;
28679                 rtx reg = gen_rtx_REG (V4SImode, i);
28680                 HOST_WIDE_INT offset
28681                   = (info->altivec_save_offset + frame_off
28682                      + 16 * (i - info->first_altivec_reg_save));
28683
28684                 if (TARGET_P9_VECTOR && quad_address_offset_p (offset))
28685                   {
28686                     mem = gen_frame_mem (V4SImode,
28687                                          gen_rtx_PLUS (Pmode, frame_reg_rtx,
28688                                                        GEN_INT (offset)));
28689                     insn = gen_rtx_SET (reg, mem);
28690                   }
28691                 else
28692                   {
28693                     areg = gen_rtx_REG (Pmode, 0);
28694                     emit_move_insn (areg, GEN_INT (offset));
28695
28696                     /* AltiVec addressing mode is [reg+reg].  */
28697                     addr = gen_rtx_PLUS (Pmode, frame_reg_rtx, areg);
28698                     mem = gen_frame_mem (V4SImode, addr);
28699
28700                     /* Rather than emitting a generic move, force use of the
28701                        lvx instruction, which we always want.  In particular we
28702                        don't want lxvd2x/xxpermdi for little endian.  */
28703                     insn = gen_altivec_lvx_v4si_internal (reg, mem);
28704                   }
28705
28706                 (void) emit_insn (insn);
28707               }
28708         }
28709
28710       for (i = info->first_altivec_reg_save; i <= LAST_ALTIVEC_REGNO; ++i)
28711         if (((strategy & REST_INLINE_VRS) == 0
28712              || (info->vrsave_mask & ALTIVEC_REG_BIT (i)) != 0)
28713             && (DEFAULT_ABI == ABI_V4 || flag_shrink_wrap)
28714             && save_reg_p (i))
28715           {
28716             rtx reg = gen_rtx_REG (V4SImode, i);
28717             cfa_restores = alloc_reg_note (REG_CFA_RESTORE, reg, cfa_restores);
28718           }
28719     }
28720
28721   /* Restore VRSAVE if we have not done so already.  */
28722   if (!ALWAYS_RESTORE_ALTIVEC_BEFORE_POP
28723       && info->vrsave_size != 0
28724       && (DEFAULT_ABI == ABI_V4
28725           || !offset_below_red_zone_p (info->vrsave_save_offset)))
28726     {
28727       rtx reg;
28728
28729       reg = gen_rtx_REG (SImode, 12);
28730       emit_insn (gen_frame_load (reg, frame_reg_rtx,
28731                                  info->vrsave_save_offset + frame_off));
28732
28733       emit_insn (generate_set_vrsave (reg, info, 1));
28734     }
28735
28736   /* If we exit by an out-of-line restore function on ABI_V4 then that
28737      function will deallocate the stack, so we don't need to worry
28738      about the unwinder restoring cr from an invalid stack frame
28739      location.  */
28740   exit_func = (!restoring_FPRs_inline
28741                || (!restoring_GPRs_inline
28742                    && info->first_fp_reg_save == 64));
28743
28744   /* In the ELFv2 ABI we need to restore all call-saved CR fields from
28745      *separate* slots if the routine calls __builtin_eh_return, so
28746      that they can be independently restored by the unwinder.  */
28747   if (DEFAULT_ABI == ABI_ELFv2 && crtl->calls_eh_return)
28748     {
28749       int i, cr_off = info->ehcr_offset;
28750
28751       for (i = 0; i < 8; i++)
28752         if (!call_used_regs[CR0_REGNO + i])
28753           {
28754             rtx reg = gen_rtx_REG (SImode, 0);
28755             emit_insn (gen_frame_load (reg, frame_reg_rtx,
28756                                        cr_off + frame_off));
28757
28758             insn = emit_insn (gen_movsi_to_cr_one
28759                                 (gen_rtx_REG (CCmode, CR0_REGNO + i), reg));
28760
28761             if (!exit_func && flag_shrink_wrap)
28762               {
28763                 add_reg_note (insn, REG_CFA_RESTORE,
28764                               gen_rtx_REG (SImode, CR0_REGNO + i));
28765
28766                 RTX_FRAME_RELATED_P (insn) = 1;
28767               }
28768
28769             cr_off += reg_size;
28770           }
28771     }
28772
28773   /* Get the old lr if we saved it.  If we are restoring registers
28774      out-of-line, then the out-of-line routines can do this for us.  */
28775   if (restore_lr && restoring_GPRs_inline)
28776     load_lr_save (0, frame_reg_rtx, info->lr_save_offset + frame_off);
28777
28778   /* Get the old cr if we saved it.  */
28779   if (info->cr_save_p)
28780     {
28781       unsigned cr_save_regno = 12;
28782
28783       if (!restoring_GPRs_inline)
28784         {
28785           /* Ensure we don't use the register used by the out-of-line
28786              gpr register restore below.  */
28787           bool lr = info->gp_save_offset + info->gp_size == 0;
28788           int sel = SAVRES_GPR | (lr ? SAVRES_LR : 0);
28789           int gpr_ptr_regno = ptr_regno_for_savres (sel);
28790
28791           if (gpr_ptr_regno == 12)
28792             cr_save_regno = 11;
28793           gcc_checking_assert (REGNO (frame_reg_rtx) != cr_save_regno);
28794         }
28795       else if (REGNO (frame_reg_rtx) == 12)
28796         cr_save_regno = 11;
28797
28798       cr_save_reg = load_cr_save (cr_save_regno, frame_reg_rtx,
28799                                   info->cr_save_offset + frame_off,
28800                                   exit_func);
28801     }
28802
28803   /* Set LR here to try to overlap restores below.  */
28804   if (restore_lr && restoring_GPRs_inline)
28805     restore_saved_lr (0, exit_func);
28806
28807   /* Load exception handler data registers, if needed.  */
28808   if (crtl->calls_eh_return)
28809     {
28810       unsigned int i, regno;
28811
28812       if (TARGET_AIX)
28813         {
28814           rtx reg = gen_rtx_REG (reg_mode, 2);
28815           emit_insn (gen_frame_load (reg, frame_reg_rtx,
28816                                      frame_off + RS6000_TOC_SAVE_SLOT));
28817         }
28818
28819       for (i = 0; ; ++i)
28820         {
28821           rtx mem;
28822
28823           regno = EH_RETURN_DATA_REGNO (i);
28824           if (regno == INVALID_REGNUM)
28825             break;
28826
28827           mem = gen_frame_mem_offset (reg_mode, frame_reg_rtx,
28828                                       info->ehrd_offset + frame_off
28829                                       + reg_size * (int) i);
28830
28831           emit_move_insn (gen_rtx_REG (reg_mode, regno), mem);
28832         }
28833     }
28834
28835   /* Restore GPRs.  This is done as a PARALLEL if we are using
28836      the load-multiple instructions.  */
28837   if (!restoring_GPRs_inline)
28838     {
28839       /* We are jumping to an out-of-line function.  */
28840       rtx ptr_reg;
28841       int end_save = info->gp_save_offset + info->gp_size;
28842       bool can_use_exit = end_save == 0;
28843       int sel = SAVRES_GPR | (can_use_exit ? SAVRES_LR : 0);
28844       int ptr_off;
28845
28846       /* Emit stack reset code if we need it.  */
28847       ptr_regno = ptr_regno_for_savres (sel);
28848       ptr_reg = gen_rtx_REG (Pmode, ptr_regno);
28849       if (can_use_exit)
28850         rs6000_emit_stack_reset (frame_reg_rtx, frame_off, ptr_regno);
28851       else if (end_save + frame_off != 0)
28852         emit_insn (gen_add3_insn (ptr_reg, frame_reg_rtx,
28853                                   GEN_INT (end_save + frame_off)));
28854       else if (REGNO (frame_reg_rtx) != ptr_regno)
28855         emit_move_insn (ptr_reg, frame_reg_rtx);
28856       if (REGNO (frame_reg_rtx) == ptr_regno)
28857         frame_off = -end_save;
28858
28859       if (can_use_exit && info->cr_save_p)
28860         restore_saved_cr (cr_save_reg, using_mtcr_multiple, true);
28861
28862       ptr_off = -end_save;
28863       rs6000_emit_savres_rtx (info, ptr_reg,
28864                               info->gp_save_offset + ptr_off,
28865                               info->lr_save_offset + ptr_off,
28866                               reg_mode, sel);
28867     }
28868   else if (using_load_multiple)
28869     {
28870       rtvec p;
28871       p = rtvec_alloc (32 - info->first_gp_reg_save);
28872       for (i = 0; i < 32 - info->first_gp_reg_save; i++)
28873         RTVEC_ELT (p, i)
28874           = gen_frame_load (gen_rtx_REG (reg_mode, info->first_gp_reg_save + i),
28875                             frame_reg_rtx,
28876                             info->gp_save_offset + frame_off + reg_size * i);
28877       emit_insn (gen_rtx_PARALLEL (VOIDmode, p));
28878     }
28879   else
28880     {
28881       int offset = info->gp_save_offset + frame_off;
28882       for (i = info->first_gp_reg_save; i < 32; i++)
28883         {
28884           if (save_reg_p (i)
28885               && !cfun->machine->gpr_is_wrapped_separately[i])
28886             {
28887               rtx reg = gen_rtx_REG (reg_mode, i);
28888               emit_insn (gen_frame_load (reg, frame_reg_rtx, offset));
28889             }
28890
28891           offset += reg_size;
28892         }
28893     }
28894
28895   if (DEFAULT_ABI == ABI_V4 || flag_shrink_wrap)
28896     {
28897       /* If the frame pointer was used then we can't delay emitting
28898          a REG_CFA_DEF_CFA note.  This must happen on the insn that
28899          restores the frame pointer, r31.  We may have already emitted
28900          a REG_CFA_DEF_CFA note, but that's OK;  A duplicate is
28901          discarded by dwarf2cfi.c/dwarf2out.c, and in any case would
28902          be harmless if emitted.  */
28903       if (frame_pointer_needed)
28904         {
28905           insn = get_last_insn ();
28906           add_reg_note (insn, REG_CFA_DEF_CFA,
28907                         plus_constant (Pmode, frame_reg_rtx, frame_off));
28908           RTX_FRAME_RELATED_P (insn) = 1;
28909         }
28910
28911       /* Set up cfa_restores.  We always need these when
28912          shrink-wrapping.  If not shrink-wrapping then we only need
28913          the cfa_restore when the stack location is no longer valid.
28914          The cfa_restores must be emitted on or before the insn that
28915          invalidates the stack, and of course must not be emitted
28916          before the insn that actually does the restore.  The latter
28917          is why it is a bad idea to emit the cfa_restores as a group
28918          on the last instruction here that actually does a restore:
28919          That insn may be reordered with respect to others doing
28920          restores.  */
28921       if (flag_shrink_wrap
28922           && !restoring_GPRs_inline
28923           && info->first_fp_reg_save == 64)
28924         cfa_restores = add_crlr_cfa_restore (info, cfa_restores);
28925
28926       for (i = info->first_gp_reg_save; i < 32; i++)
28927         if (save_reg_p (i)
28928             && !cfun->machine->gpr_is_wrapped_separately[i])
28929           {
28930             rtx reg = gen_rtx_REG (reg_mode, i);
28931             cfa_restores = alloc_reg_note (REG_CFA_RESTORE, reg, cfa_restores);
28932           }
28933     }
28934
28935   if (!restoring_GPRs_inline
28936       && info->first_fp_reg_save == 64)
28937     {
28938       /* We are jumping to an out-of-line function.  */
28939       if (cfa_restores)
28940         emit_cfa_restores (cfa_restores);
28941       return;
28942     }
28943
28944   if (restore_lr && !restoring_GPRs_inline)
28945     {
28946       load_lr_save (0, frame_reg_rtx, info->lr_save_offset + frame_off);
28947       restore_saved_lr (0, exit_func);
28948     }
28949
28950   /* Restore fpr's if we need to do it without calling a function.  */
28951   if (restoring_FPRs_inline)
28952     {
28953       int offset = info->fp_save_offset + frame_off;
28954       for (i = info->first_fp_reg_save; i < 64; i++)
28955         {
28956           if (save_reg_p (i)
28957               && !cfun->machine->fpr_is_wrapped_separately[i - 32])
28958             {
28959               rtx reg = gen_rtx_REG (fp_reg_mode, i);
28960               emit_insn (gen_frame_load (reg, frame_reg_rtx, offset));
28961               if (DEFAULT_ABI == ABI_V4 || flag_shrink_wrap)
28962                 cfa_restores = alloc_reg_note (REG_CFA_RESTORE, reg,
28963                                                cfa_restores);
28964             }
28965
28966           offset += fp_reg_size;
28967         }
28968     }
28969
28970   /* If we saved cr, restore it here.  Just those that were used.  */
28971   if (info->cr_save_p)
28972     restore_saved_cr (cr_save_reg, using_mtcr_multiple, exit_func);
28973
28974   /* If this is V.4, unwind the stack pointer after all of the loads
28975      have been done, or set up r11 if we are restoring fp out of line.  */
28976   ptr_regno = 1;
28977   if (!restoring_FPRs_inline)
28978     {
28979       bool lr = (strategy & REST_NOINLINE_FPRS_DOESNT_RESTORE_LR) == 0;
28980       int sel = SAVRES_FPR | (lr ? SAVRES_LR : 0);
28981       ptr_regno = ptr_regno_for_savres (sel);
28982     }
28983
28984   insn = rs6000_emit_stack_reset (frame_reg_rtx, frame_off, ptr_regno);
28985   if (REGNO (frame_reg_rtx) == ptr_regno)
28986     frame_off = 0;
28987
28988   if (insn && restoring_FPRs_inline)
28989     {
28990       if (cfa_restores)
28991         {
28992           REG_NOTES (insn) = cfa_restores;
28993           cfa_restores = NULL_RTX;
28994         }
28995       add_reg_note (insn, REG_CFA_DEF_CFA, sp_reg_rtx);
28996       RTX_FRAME_RELATED_P (insn) = 1;
28997     }
28998
28999   if (crtl->calls_eh_return)
29000     {
29001       rtx sa = EH_RETURN_STACKADJ_RTX;
29002       emit_insn (gen_add3_insn (sp_reg_rtx, sp_reg_rtx, sa));
29003     }
29004
29005   if (!sibcall && restoring_FPRs_inline)
29006     {
29007       if (cfa_restores)
29008         {
29009           /* We can't hang the cfa_restores off a simple return,
29010              since the shrink-wrap code sometimes uses an existing
29011              return.  This means there might be a path from
29012              pre-prologue code to this return, and dwarf2cfi code
29013              wants the eh_frame unwinder state to be the same on
29014              all paths to any point.  So we need to emit the
29015              cfa_restores before the return.  For -m64 we really
29016              don't need epilogue cfa_restores at all, except for
29017              this irritating dwarf2cfi with shrink-wrap
29018              requirement;  The stack red-zone means eh_frame info
29019              from the prologue telling the unwinder to restore
29020              from the stack is perfectly good right to the end of
29021              the function.  */
29022           emit_insn (gen_blockage ());
29023           emit_cfa_restores (cfa_restores);
29024           cfa_restores = NULL_RTX;
29025         }
29026
29027       emit_jump_insn (targetm.gen_simple_return ());
29028     }
29029
29030   if (!sibcall && !restoring_FPRs_inline)
29031     {
29032       bool lr = (strategy & REST_NOINLINE_FPRS_DOESNT_RESTORE_LR) == 0;
29033       rtvec p = rtvec_alloc (3 + !!lr + 64 - info->first_fp_reg_save);
29034       int elt = 0;
29035       RTVEC_ELT (p, elt++) = ret_rtx;
29036       if (lr)
29037         RTVEC_ELT (p, elt++)
29038           = gen_rtx_CLOBBER (VOIDmode, gen_rtx_REG (Pmode, LR_REGNO));
29039
29040       /* We have to restore more than two FP registers, so branch to the
29041          restore function.  It will return to our caller.  */
29042       int i;
29043       int reg;
29044       rtx sym;
29045
29046       if (flag_shrink_wrap)
29047         cfa_restores = add_crlr_cfa_restore (info, cfa_restores);
29048
29049       sym = rs6000_savres_routine_sym (info, SAVRES_FPR | (lr ? SAVRES_LR : 0));
29050       RTVEC_ELT (p, elt++) = gen_rtx_USE (VOIDmode, sym);
29051       reg = (DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)? 1 : 11;
29052       RTVEC_ELT (p, elt++) = gen_rtx_USE (VOIDmode, gen_rtx_REG (Pmode, reg));
29053
29054       for (i = 0; i < 64 - info->first_fp_reg_save; i++)
29055         {
29056           rtx reg = gen_rtx_REG (DFmode, info->first_fp_reg_save + i);
29057
29058           RTVEC_ELT (p, elt++)
29059             = gen_frame_load (reg, sp_reg_rtx, info->fp_save_offset + 8 * i);
29060           if (flag_shrink_wrap
29061               && save_reg_p (info->first_fp_reg_save + i))
29062             cfa_restores = alloc_reg_note (REG_CFA_RESTORE, reg, cfa_restores);
29063         }
29064
29065       emit_jump_insn (gen_rtx_PARALLEL (VOIDmode, p));
29066     }
29067
29068   if (cfa_restores)
29069     {
29070       if (sibcall)
29071         /* Ensure the cfa_restores are hung off an insn that won't
29072            be reordered above other restores.  */
29073         emit_insn (gen_blockage ());
29074
29075       emit_cfa_restores (cfa_restores);
29076     }
29077 }
29078
29079 /* Write function epilogue.  */
29080
29081 static void
29082 rs6000_output_function_epilogue (FILE *file)
29083 {
29084 #if TARGET_MACHO
29085   macho_branch_islands ();
29086
29087   {
29088     rtx_insn *insn = get_last_insn ();
29089     rtx_insn *deleted_debug_label = NULL;
29090
29091     /* Mach-O doesn't support labels at the end of objects, so if
29092        it looks like we might want one, take special action.
29093
29094        First, collect any sequence of deleted debug labels.  */
29095     while (insn
29096            && NOTE_P (insn)
29097            && NOTE_KIND (insn) != NOTE_INSN_DELETED_LABEL)
29098       {
29099         /* Don't insert a nop for NOTE_INSN_DELETED_DEBUG_LABEL
29100            notes only, instead set their CODE_LABEL_NUMBER to -1,
29101            otherwise there would be code generation differences
29102            in between -g and -g0.  */
29103         if (NOTE_P (insn) && NOTE_KIND (insn) == NOTE_INSN_DELETED_DEBUG_LABEL)
29104           deleted_debug_label = insn;
29105         insn = PREV_INSN (insn);
29106       }
29107
29108     /* Second, if we have:
29109        label:
29110          barrier
29111        then this needs to be detected, so skip past the barrier.  */
29112
29113     if (insn && BARRIER_P (insn))
29114       insn = PREV_INSN (insn);
29115
29116     /* Up to now we've only seen notes or barriers.  */
29117     if (insn)
29118       {
29119         if (LABEL_P (insn)
29120             || (NOTE_P (insn)
29121                 && NOTE_KIND (insn) == NOTE_INSN_DELETED_LABEL))
29122           /* Trailing label: <barrier>.  */
29123           fputs ("\tnop\n", file);
29124         else
29125           {
29126             /* Lastly, see if we have a completely empty function body.  */
29127             while (insn && ! INSN_P (insn))
29128               insn = PREV_INSN (insn);
29129             /* If we don't find any insns, we've got an empty function body;
29130                I.e. completely empty - without a return or branch.  This is
29131                taken as the case where a function body has been removed
29132                because it contains an inline __builtin_unreachable().  GCC
29133                states that reaching __builtin_unreachable() means UB so we're
29134                not obliged to do anything special; however, we want
29135                non-zero-sized function bodies.  To meet this, and help the
29136                user out, let's trap the case.  */
29137             if (insn == NULL)
29138               fputs ("\ttrap\n", file);
29139           }
29140       }
29141     else if (deleted_debug_label)
29142       for (insn = deleted_debug_label; insn; insn = NEXT_INSN (insn))
29143         if (NOTE_KIND (insn) == NOTE_INSN_DELETED_DEBUG_LABEL)
29144           CODE_LABEL_NUMBER (insn) = -1;
29145   }
29146 #endif
29147
29148   /* Output a traceback table here.  See /usr/include/sys/debug.h for info
29149      on its format.
29150
29151      We don't output a traceback table if -finhibit-size-directive was
29152      used.  The documentation for -finhibit-size-directive reads
29153      ``don't output a @code{.size} assembler directive, or anything
29154      else that would cause trouble if the function is split in the
29155      middle, and the two halves are placed at locations far apart in
29156      memory.''  The traceback table has this property, since it
29157      includes the offset from the start of the function to the
29158      traceback table itself.
29159
29160      System V.4 Powerpc's (and the embedded ABI derived from it) use a
29161      different traceback table.  */
29162   if ((DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
29163       && ! flag_inhibit_size_directive
29164       && rs6000_traceback != traceback_none && !cfun->is_thunk)
29165     {
29166       const char *fname = NULL;
29167       const char *language_string = lang_hooks.name;
29168       int fixed_parms = 0, float_parms = 0, parm_info = 0;
29169       int i;
29170       int optional_tbtab;
29171       rs6000_stack_t *info = rs6000_stack_info ();
29172
29173       if (rs6000_traceback == traceback_full)
29174         optional_tbtab = 1;
29175       else if (rs6000_traceback == traceback_part)
29176         optional_tbtab = 0;
29177       else
29178         optional_tbtab = !optimize_size && !TARGET_ELF;
29179
29180       if (optional_tbtab)
29181         {
29182           fname = XSTR (XEXP (DECL_RTL (current_function_decl), 0), 0);
29183           while (*fname == '.') /* V.4 encodes . in the name */
29184             fname++;
29185
29186           /* Need label immediately before tbtab, so we can compute
29187              its offset from the function start.  */
29188           ASM_OUTPUT_INTERNAL_LABEL_PREFIX (file, "LT");
29189           ASM_OUTPUT_LABEL (file, fname);
29190         }
29191
29192       /* The .tbtab pseudo-op can only be used for the first eight
29193          expressions, since it can't handle the possibly variable
29194          length fields that follow.  However, if you omit the optional
29195          fields, the assembler outputs zeros for all optional fields
29196          anyways, giving each variable length field is minimum length
29197          (as defined in sys/debug.h).  Thus we can not use the .tbtab
29198          pseudo-op at all.  */
29199
29200       /* An all-zero word flags the start of the tbtab, for debuggers
29201          that have to find it by searching forward from the entry
29202          point or from the current pc.  */
29203       fputs ("\t.long 0\n", file);
29204
29205       /* Tbtab format type.  Use format type 0.  */
29206       fputs ("\t.byte 0,", file);
29207
29208       /* Language type.  Unfortunately, there does not seem to be any
29209          official way to discover the language being compiled, so we
29210          use language_string.
29211          C is 0.  Fortran is 1.  Pascal is 2.  Ada is 3.  C++ is 9.
29212          Java is 13.  Objective-C is 14.  Objective-C++ isn't assigned
29213          a number, so for now use 9.  LTO, Go and JIT aren't assigned numbers
29214          either, so for now use 0.  */
29215       if (lang_GNU_C ()
29216           || ! strcmp (language_string, "GNU GIMPLE")
29217           || ! strcmp (language_string, "GNU Go")
29218           || ! strcmp (language_string, "libgccjit"))
29219         i = 0;
29220       else if (! strcmp (language_string, "GNU F77")
29221                || lang_GNU_Fortran ())
29222         i = 1;
29223       else if (! strcmp (language_string, "GNU Pascal"))
29224         i = 2;
29225       else if (! strcmp (language_string, "GNU Ada"))
29226         i = 3;
29227       else if (lang_GNU_CXX ()
29228                || ! strcmp (language_string, "GNU Objective-C++"))
29229         i = 9;
29230       else if (! strcmp (language_string, "GNU Java"))
29231         i = 13;
29232       else if (! strcmp (language_string, "GNU Objective-C"))
29233         i = 14;
29234       else
29235         gcc_unreachable ();
29236       fprintf (file, "%d,", i);
29237
29238       /* 8 single bit fields: global linkage (not set for C extern linkage,
29239          apparently a PL/I convention?), out-of-line epilogue/prologue, offset
29240          from start of procedure stored in tbtab, internal function, function
29241          has controlled storage, function has no toc, function uses fp,
29242          function logs/aborts fp operations.  */
29243       /* Assume that fp operations are used if any fp reg must be saved.  */
29244       fprintf (file, "%d,",
29245                (optional_tbtab << 5) | ((info->first_fp_reg_save != 64) << 1));
29246
29247       /* 6 bitfields: function is interrupt handler, name present in
29248          proc table, function calls alloca, on condition directives
29249          (controls stack walks, 3 bits), saves condition reg, saves
29250          link reg.  */
29251       /* The `function calls alloca' bit seems to be set whenever reg 31 is
29252          set up as a frame pointer, even when there is no alloca call.  */
29253       fprintf (file, "%d,",
29254                ((optional_tbtab << 6)
29255                 | ((optional_tbtab & frame_pointer_needed) << 5)
29256                 | (info->cr_save_p << 1)
29257                 | (info->lr_save_p)));
29258
29259       /* 3 bitfields: saves backchain, fixup code, number of fpr saved
29260          (6 bits).  */
29261       fprintf (file, "%d,",
29262                (info->push_p << 7) | (64 - info->first_fp_reg_save));
29263
29264       /* 2 bitfields: spare bits (2 bits), number of gpr saved (6 bits).  */
29265       fprintf (file, "%d,", (32 - first_reg_to_save ()));
29266
29267       if (optional_tbtab)
29268         {
29269           /* Compute the parameter info from the function decl argument
29270              list.  */
29271           tree decl;
29272           int next_parm_info_bit = 31;
29273
29274           for (decl = DECL_ARGUMENTS (current_function_decl);
29275                decl; decl = DECL_CHAIN (decl))
29276             {
29277               rtx parameter = DECL_INCOMING_RTL (decl);
29278               machine_mode mode = GET_MODE (parameter);
29279
29280               if (GET_CODE (parameter) == REG)
29281                 {
29282                   if (SCALAR_FLOAT_MODE_P (mode))
29283                     {
29284                       int bits;
29285
29286                       float_parms++;
29287
29288                       switch (mode)
29289                         {
29290                         case E_SFmode:
29291                         case E_SDmode:
29292                           bits = 0x2;
29293                           break;
29294
29295                         case E_DFmode:
29296                         case E_DDmode:
29297                         case E_TFmode:
29298                         case E_TDmode:
29299                         case E_IFmode:
29300                         case E_KFmode:
29301                           bits = 0x3;
29302                           break;
29303
29304                         default:
29305                           gcc_unreachable ();
29306                         }
29307
29308                       /* If only one bit will fit, don't or in this entry.  */
29309                       if (next_parm_info_bit > 0)
29310                         parm_info |= (bits << (next_parm_info_bit - 1));
29311                       next_parm_info_bit -= 2;
29312                     }
29313                   else
29314                     {
29315                       fixed_parms += ((GET_MODE_SIZE (mode)
29316                                        + (UNITS_PER_WORD - 1))
29317                                       / UNITS_PER_WORD);
29318                       next_parm_info_bit -= 1;
29319                     }
29320                 }
29321             }
29322         }
29323
29324       /* Number of fixed point parameters.  */
29325       /* This is actually the number of words of fixed point parameters; thus
29326          an 8 byte struct counts as 2; and thus the maximum value is 8.  */
29327       fprintf (file, "%d,", fixed_parms);
29328
29329       /* 2 bitfields: number of floating point parameters (7 bits), parameters
29330          all on stack.  */
29331       /* This is actually the number of fp registers that hold parameters;
29332          and thus the maximum value is 13.  */
29333       /* Set parameters on stack bit if parameters are not in their original
29334          registers, regardless of whether they are on the stack?  Xlc
29335          seems to set the bit when not optimizing.  */
29336       fprintf (file, "%d\n", ((float_parms << 1) | (! optimize)));
29337
29338       if (optional_tbtab)
29339         {
29340           /* Optional fields follow.  Some are variable length.  */
29341
29342           /* Parameter types, left adjusted bit fields: 0 fixed, 10 single
29343              float, 11 double float.  */
29344           /* There is an entry for each parameter in a register, in the order
29345              that they occur in the parameter list.  Any intervening arguments
29346              on the stack are ignored.  If the list overflows a long (max
29347              possible length 34 bits) then completely leave off all elements
29348              that don't fit.  */
29349           /* Only emit this long if there was at least one parameter.  */
29350           if (fixed_parms || float_parms)
29351             fprintf (file, "\t.long %d\n", parm_info);
29352
29353           /* Offset from start of code to tb table.  */
29354           fputs ("\t.long ", file);
29355           ASM_OUTPUT_INTERNAL_LABEL_PREFIX (file, "LT");
29356           RS6000_OUTPUT_BASENAME (file, fname);
29357           putc ('-', file);
29358           rs6000_output_function_entry (file, fname);
29359           putc ('\n', file);
29360
29361           /* Interrupt handler mask.  */
29362           /* Omit this long, since we never set the interrupt handler bit
29363              above.  */
29364
29365           /* Number of CTL (controlled storage) anchors.  */
29366           /* Omit this long, since the has_ctl bit is never set above.  */
29367
29368           /* Displacement into stack of each CTL anchor.  */
29369           /* Omit this list of longs, because there are no CTL anchors.  */
29370
29371           /* Length of function name.  */
29372           if (*fname == '*')
29373             ++fname;
29374           fprintf (file, "\t.short %d\n", (int) strlen (fname));
29375
29376           /* Function name.  */
29377           assemble_string (fname, strlen (fname));
29378
29379           /* Register for alloca automatic storage; this is always reg 31.
29380              Only emit this if the alloca bit was set above.  */
29381           if (frame_pointer_needed)
29382             fputs ("\t.byte 31\n", file);
29383
29384           fputs ("\t.align 2\n", file);
29385         }
29386     }
29387
29388   /* Arrange to define .LCTOC1 label, if not already done.  */
29389   if (need_toc_init)
29390     {
29391       need_toc_init = 0;
29392       if (!toc_initialized)
29393         {
29394           switch_to_section (toc_section);
29395           switch_to_section (current_function_section ());
29396         }
29397     }
29398 }
29399
29400 /* -fsplit-stack support.  */
29401
29402 /* A SYMBOL_REF for __morestack.  */
29403 static GTY(()) rtx morestack_ref;
29404
29405 static rtx
29406 gen_add3_const (rtx rt, rtx ra, long c)
29407 {
29408   if (TARGET_64BIT)
29409     return gen_adddi3 (rt, ra, GEN_INT (c));
29410  else
29411     return gen_addsi3 (rt, ra, GEN_INT (c));
29412 }
29413
29414 /* Emit -fsplit-stack prologue, which goes before the regular function
29415    prologue (at local entry point in the case of ELFv2).  */
29416
29417 void
29418 rs6000_expand_split_stack_prologue (void)
29419 {
29420   rs6000_stack_t *info = rs6000_stack_info ();
29421   unsigned HOST_WIDE_INT allocate;
29422   long alloc_hi, alloc_lo;
29423   rtx r0, r1, r12, lr, ok_label, compare, jump, call_fusage;
29424   rtx_insn *insn;
29425
29426   gcc_assert (flag_split_stack && reload_completed);
29427
29428   if (!info->push_p)
29429     return;
29430
29431   if (global_regs[29])
29432     {
29433       error ("%qs uses register r29", "-fsplit-stack");
29434       inform (DECL_SOURCE_LOCATION (global_regs_decl[29]),
29435               "conflicts with %qD", global_regs_decl[29]);
29436     }
29437
29438   allocate = info->total_size;
29439   if (allocate > (unsigned HOST_WIDE_INT) 1 << 31)
29440     {
29441       sorry ("Stack frame larger than 2G is not supported for -fsplit-stack");
29442       return;
29443     }
29444   if (morestack_ref == NULL_RTX)
29445     {
29446       morestack_ref = gen_rtx_SYMBOL_REF (Pmode, "__morestack");
29447       SYMBOL_REF_FLAGS (morestack_ref) |= (SYMBOL_FLAG_LOCAL
29448                                            | SYMBOL_FLAG_FUNCTION);
29449     }
29450
29451   r0 = gen_rtx_REG (Pmode, 0);
29452   r1 = gen_rtx_REG (Pmode, STACK_POINTER_REGNUM);
29453   r12 = gen_rtx_REG (Pmode, 12);
29454   emit_insn (gen_load_split_stack_limit (r0));
29455   /* Always emit two insns here to calculate the requested stack,
29456      so that the linker can edit them when adjusting size for calling
29457      non-split-stack code.  */
29458   alloc_hi = (-allocate + 0x8000) & ~0xffffL;
29459   alloc_lo = -allocate - alloc_hi;
29460   if (alloc_hi != 0)
29461     {
29462       emit_insn (gen_add3_const (r12, r1, alloc_hi));
29463       if (alloc_lo != 0)
29464         emit_insn (gen_add3_const (r12, r12, alloc_lo));
29465       else
29466         emit_insn (gen_nop ());
29467     }
29468   else
29469     {
29470       emit_insn (gen_add3_const (r12, r1, alloc_lo));
29471       emit_insn (gen_nop ());
29472     }
29473
29474   compare = gen_rtx_REG (CCUNSmode, CR7_REGNO);
29475   emit_insn (gen_rtx_SET (compare, gen_rtx_COMPARE (CCUNSmode, r12, r0)));
29476   ok_label = gen_label_rtx ();
29477   jump = gen_rtx_IF_THEN_ELSE (VOIDmode,
29478                                gen_rtx_GEU (VOIDmode, compare, const0_rtx),
29479                                gen_rtx_LABEL_REF (VOIDmode, ok_label),
29480                                pc_rtx);
29481   insn = emit_jump_insn (gen_rtx_SET (pc_rtx, jump));
29482   JUMP_LABEL (insn) = ok_label;
29483   /* Mark the jump as very likely to be taken.  */
29484   add_reg_br_prob_note (insn, profile_probability::very_likely ());
29485
29486   lr = gen_rtx_REG (Pmode, LR_REGNO);
29487   insn = emit_move_insn (r0, lr);
29488   RTX_FRAME_RELATED_P (insn) = 1;
29489   insn = emit_insn (gen_frame_store (r0, r1, info->lr_save_offset));
29490   RTX_FRAME_RELATED_P (insn) = 1;
29491
29492   insn = emit_call_insn (gen_call (gen_rtx_MEM (SImode, morestack_ref),
29493                                    const0_rtx, const0_rtx));
29494   call_fusage = NULL_RTX;
29495   use_reg (&call_fusage, r12);
29496   /* Say the call uses r0, even though it doesn't, to stop regrename
29497      from twiddling with the insns saving lr, trashing args for cfun.
29498      The insns restoring lr are similarly protected by making
29499      split_stack_return use r0.  */
29500   use_reg (&call_fusage, r0);
29501   add_function_usage_to (insn, call_fusage);
29502   /* Indicate that this function can't jump to non-local gotos.  */
29503   make_reg_eh_region_note_nothrow_nononlocal (insn);
29504   emit_insn (gen_frame_load (r0, r1, info->lr_save_offset));
29505   insn = emit_move_insn (lr, r0);
29506   add_reg_note (insn, REG_CFA_RESTORE, lr);
29507   RTX_FRAME_RELATED_P (insn) = 1;
29508   emit_insn (gen_split_stack_return ());
29509
29510   emit_label (ok_label);
29511   LABEL_NUSES (ok_label) = 1;
29512 }
29513
29514 /* Return the internal arg pointer used for function incoming
29515    arguments.  When -fsplit-stack, the arg pointer is r12 so we need
29516    to copy it to a pseudo in order for it to be preserved over calls
29517    and suchlike.  We'd really like to use a pseudo here for the
29518    internal arg pointer but data-flow analysis is not prepared to
29519    accept pseudos as live at the beginning of a function.  */
29520
29521 static rtx
29522 rs6000_internal_arg_pointer (void)
29523 {
29524   if (flag_split_stack
29525      && (lookup_attribute ("no_split_stack", DECL_ATTRIBUTES (cfun->decl))
29526          == NULL))
29527
29528     {
29529       if (cfun->machine->split_stack_arg_pointer == NULL_RTX)
29530         {
29531           rtx pat;
29532
29533           cfun->machine->split_stack_arg_pointer = gen_reg_rtx (Pmode);
29534           REG_POINTER (cfun->machine->split_stack_arg_pointer) = 1;
29535
29536           /* Put the pseudo initialization right after the note at the
29537              beginning of the function.  */
29538           pat = gen_rtx_SET (cfun->machine->split_stack_arg_pointer,
29539                              gen_rtx_REG (Pmode, 12));
29540           push_topmost_sequence ();
29541           emit_insn_after (pat, get_insns ());
29542           pop_topmost_sequence ();
29543         }
29544       return plus_constant (Pmode, cfun->machine->split_stack_arg_pointer,
29545                             FIRST_PARM_OFFSET (current_function_decl));
29546     }
29547   return virtual_incoming_args_rtx;
29548 }
29549
29550 /* We may have to tell the dataflow pass that the split stack prologue
29551    is initializing a register.  */
29552
29553 static void
29554 rs6000_live_on_entry (bitmap regs)
29555 {
29556   if (flag_split_stack)
29557     bitmap_set_bit (regs, 12);
29558 }
29559
29560 /* Emit -fsplit-stack dynamic stack allocation space check.  */
29561
29562 void
29563 rs6000_split_stack_space_check (rtx size, rtx label)
29564 {
29565   rtx sp = gen_rtx_REG (Pmode, STACK_POINTER_REGNUM);
29566   rtx limit = gen_reg_rtx (Pmode);
29567   rtx requested = gen_reg_rtx (Pmode);
29568   rtx cmp = gen_reg_rtx (CCUNSmode);
29569   rtx jump;
29570
29571   emit_insn (gen_load_split_stack_limit (limit));
29572   if (CONST_INT_P (size))
29573     emit_insn (gen_add3_insn (requested, sp, GEN_INT (-INTVAL (size))));
29574   else
29575     {
29576       size = force_reg (Pmode, size);
29577       emit_move_insn (requested, gen_rtx_MINUS (Pmode, sp, size));
29578     }
29579   emit_insn (gen_rtx_SET (cmp, gen_rtx_COMPARE (CCUNSmode, requested, limit)));
29580   jump = gen_rtx_IF_THEN_ELSE (VOIDmode,
29581                                gen_rtx_GEU (VOIDmode, cmp, const0_rtx),
29582                                gen_rtx_LABEL_REF (VOIDmode, label),
29583                                pc_rtx);
29584   jump = emit_jump_insn (gen_rtx_SET (pc_rtx, jump));
29585   JUMP_LABEL (jump) = label;
29586 }
29587 \f
29588 /* A C compound statement that outputs the assembler code for a thunk
29589    function, used to implement C++ virtual function calls with
29590    multiple inheritance.  The thunk acts as a wrapper around a virtual
29591    function, adjusting the implicit object parameter before handing
29592    control off to the real function.
29593
29594    First, emit code to add the integer DELTA to the location that
29595    contains the incoming first argument.  Assume that this argument
29596    contains a pointer, and is the one used to pass the `this' pointer
29597    in C++.  This is the incoming argument *before* the function
29598    prologue, e.g. `%o0' on a sparc.  The addition must preserve the
29599    values of all other incoming arguments.
29600
29601    After the addition, emit code to jump to FUNCTION, which is a
29602    `FUNCTION_DECL'.  This is a direct pure jump, not a call, and does
29603    not touch the return address.  Hence returning from FUNCTION will
29604    return to whoever called the current `thunk'.
29605
29606    The effect must be as if FUNCTION had been called directly with the
29607    adjusted first argument.  This macro is responsible for emitting
29608    all of the code for a thunk function; output_function_prologue()
29609    and output_function_epilogue() are not invoked.
29610
29611    The THUNK_FNDECL is redundant.  (DELTA and FUNCTION have already
29612    been extracted from it.)  It might possibly be useful on some
29613    targets, but probably not.
29614
29615    If you do not define this macro, the target-independent code in the
29616    C++ frontend will generate a less efficient heavyweight thunk that
29617    calls FUNCTION instead of jumping to it.  The generic approach does
29618    not support varargs.  */
29619
29620 static void
29621 rs6000_output_mi_thunk (FILE *file, tree thunk_fndecl ATTRIBUTE_UNUSED,
29622                         HOST_WIDE_INT delta, HOST_WIDE_INT vcall_offset,
29623                         tree function)
29624 {
29625   rtx this_rtx, funexp;
29626   rtx_insn *insn;
29627
29628   reload_completed = 1;
29629   epilogue_completed = 1;
29630
29631   /* Mark the end of the (empty) prologue.  */
29632   emit_note (NOTE_INSN_PROLOGUE_END);
29633
29634   /* Find the "this" pointer.  If the function returns a structure,
29635      the structure return pointer is in r3.  */
29636   if (aggregate_value_p (TREE_TYPE (TREE_TYPE (function)), function))
29637     this_rtx = gen_rtx_REG (Pmode, 4);
29638   else
29639     this_rtx = gen_rtx_REG (Pmode, 3);
29640
29641   /* Apply the constant offset, if required.  */
29642   if (delta)
29643     emit_insn (gen_add3_insn (this_rtx, this_rtx, GEN_INT (delta)));
29644
29645   /* Apply the offset from the vtable, if required.  */
29646   if (vcall_offset)
29647     {
29648       rtx vcall_offset_rtx = GEN_INT (vcall_offset);
29649       rtx tmp = gen_rtx_REG (Pmode, 12);
29650
29651       emit_move_insn (tmp, gen_rtx_MEM (Pmode, this_rtx));
29652       if (((unsigned HOST_WIDE_INT) vcall_offset) + 0x8000 >= 0x10000)
29653         {
29654           emit_insn (gen_add3_insn (tmp, tmp, vcall_offset_rtx));
29655           emit_move_insn (tmp, gen_rtx_MEM (Pmode, tmp));
29656         }
29657       else
29658         {
29659           rtx loc = gen_rtx_PLUS (Pmode, tmp, vcall_offset_rtx);
29660
29661           emit_move_insn (tmp, gen_rtx_MEM (Pmode, loc));
29662         }
29663       emit_insn (gen_add3_insn (this_rtx, this_rtx, tmp));
29664     }
29665
29666   /* Generate a tail call to the target function.  */
29667   if (!TREE_USED (function))
29668     {
29669       assemble_external (function);
29670       TREE_USED (function) = 1;
29671     }
29672   funexp = XEXP (DECL_RTL (function), 0);
29673   funexp = gen_rtx_MEM (FUNCTION_MODE, funexp);
29674
29675 #if TARGET_MACHO
29676   if (MACHOPIC_INDIRECT)
29677     funexp = machopic_indirect_call_target (funexp);
29678 #endif
29679
29680   /* gen_sibcall expects reload to convert scratch pseudo to LR so we must
29681      generate sibcall RTL explicitly.  */
29682   insn = emit_call_insn (
29683            gen_rtx_PARALLEL (VOIDmode,
29684              gen_rtvec (3,
29685                         gen_rtx_CALL (VOIDmode,
29686                                       funexp, const0_rtx),
29687                         gen_rtx_USE (VOIDmode, const0_rtx),
29688                         simple_return_rtx)));
29689   SIBLING_CALL_P (insn) = 1;
29690   emit_barrier ();
29691
29692   /* Run just enough of rest_of_compilation to get the insns emitted.
29693      There's not really enough bulk here to make other passes such as
29694      instruction scheduling worth while.  Note that use_thunk calls
29695      assemble_start_function and assemble_end_function.  */
29696   insn = get_insns ();
29697   shorten_branches (insn);
29698   final_start_function (insn, file, 1);
29699   final (insn, file, 1);
29700   final_end_function ();
29701
29702   reload_completed = 0;
29703   epilogue_completed = 0;
29704 }
29705 \f
29706 /* A quick summary of the various types of 'constant-pool tables'
29707    under PowerPC:
29708
29709    Target       Flags           Name            One table per
29710    AIX          (none)          AIX TOC         object file
29711    AIX          -mfull-toc      AIX TOC         object file
29712    AIX          -mminimal-toc   AIX minimal TOC translation unit
29713    SVR4/EABI    (none)          SVR4 SDATA      object file
29714    SVR4/EABI    -fpic           SVR4 pic        object file
29715    SVR4/EABI    -fPIC           SVR4 PIC        translation unit
29716    SVR4/EABI    -mrelocatable   EABI TOC        function
29717    SVR4/EABI    -maix           AIX TOC         object file
29718    SVR4/EABI    -maix -mminimal-toc
29719                                 AIX minimal TOC translation unit
29720
29721    Name                 Reg.    Set by  entries       contains:
29722                                         made by  addrs? fp?     sum?
29723
29724    AIX TOC              2       crt0    as       Y      option  option
29725    AIX minimal TOC      30      prolog  gcc      Y      Y       option
29726    SVR4 SDATA           13      crt0    gcc      N      Y       N
29727    SVR4 pic             30      prolog  ld       Y      not yet N
29728    SVR4 PIC             30      prolog  gcc      Y      option  option
29729    EABI TOC             30      prolog  gcc      Y      option  option
29730
29731 */
29732
29733 /* Hash functions for the hash table.  */
29734
29735 static unsigned
29736 rs6000_hash_constant (rtx k)
29737 {
29738   enum rtx_code code = GET_CODE (k);
29739   machine_mode mode = GET_MODE (k);
29740   unsigned result = (code << 3) ^ mode;
29741   const char *format;
29742   int flen, fidx;
29743
29744   format = GET_RTX_FORMAT (code);
29745   flen = strlen (format);
29746   fidx = 0;
29747
29748   switch (code)
29749     {
29750     case LABEL_REF:
29751       return result * 1231 + (unsigned) INSN_UID (XEXP (k, 0));
29752
29753     case CONST_WIDE_INT:
29754       {
29755         int i;
29756         flen = CONST_WIDE_INT_NUNITS (k);
29757         for (i = 0; i < flen; i++)
29758           result = result * 613 + CONST_WIDE_INT_ELT (k, i);
29759         return result;
29760       }
29761
29762     case CONST_DOUBLE:
29763       if (mode != VOIDmode)
29764         return real_hash (CONST_DOUBLE_REAL_VALUE (k)) * result;
29765       flen = 2;
29766       break;
29767
29768     case CODE_LABEL:
29769       fidx = 3;
29770       break;
29771
29772     default:
29773       break;
29774     }
29775
29776   for (; fidx < flen; fidx++)
29777     switch (format[fidx])
29778       {
29779       case 's':
29780         {
29781           unsigned i, len;
29782           const char *str = XSTR (k, fidx);
29783           len = strlen (str);
29784           result = result * 613 + len;
29785           for (i = 0; i < len; i++)
29786             result = result * 613 + (unsigned) str[i];
29787           break;
29788         }
29789       case 'u':
29790       case 'e':
29791         result = result * 1231 + rs6000_hash_constant (XEXP (k, fidx));
29792         break;
29793       case 'i':
29794       case 'n':
29795         result = result * 613 + (unsigned) XINT (k, fidx);
29796         break;
29797       case 'w':
29798         if (sizeof (unsigned) >= sizeof (HOST_WIDE_INT))
29799           result = result * 613 + (unsigned) XWINT (k, fidx);
29800         else
29801           {
29802             size_t i;
29803             for (i = 0; i < sizeof (HOST_WIDE_INT) / sizeof (unsigned); i++)
29804               result = result * 613 + (unsigned) (XWINT (k, fidx)
29805                                                   >> CHAR_BIT * i);
29806           }
29807         break;
29808       case '0':
29809         break;
29810       default:
29811         gcc_unreachable ();
29812       }
29813
29814   return result;
29815 }
29816
29817 hashval_t
29818 toc_hasher::hash (toc_hash_struct *thc)
29819 {
29820   return rs6000_hash_constant (thc->key) ^ thc->key_mode;
29821 }
29822
29823 /* Compare H1 and H2 for equivalence.  */
29824
29825 bool
29826 toc_hasher::equal (toc_hash_struct *h1, toc_hash_struct *h2)
29827 {
29828   rtx r1 = h1->key;
29829   rtx r2 = h2->key;
29830
29831   if (h1->key_mode != h2->key_mode)
29832     return 0;
29833
29834   return rtx_equal_p (r1, r2);
29835 }
29836
29837 /* These are the names given by the C++ front-end to vtables, and
29838    vtable-like objects.  Ideally, this logic should not be here;
29839    instead, there should be some programmatic way of inquiring as
29840    to whether or not an object is a vtable.  */
29841
29842 #define VTABLE_NAME_P(NAME)                             \
29843   (strncmp ("_vt.", name, strlen ("_vt.")) == 0         \
29844   || strncmp ("_ZTV", name, strlen ("_ZTV")) == 0       \
29845   || strncmp ("_ZTT", name, strlen ("_ZTT")) == 0       \
29846   || strncmp ("_ZTI", name, strlen ("_ZTI")) == 0       \
29847   || strncmp ("_ZTC", name, strlen ("_ZTC")) == 0)
29848
29849 #ifdef NO_DOLLAR_IN_LABEL
29850 /* Return a GGC-allocated character string translating dollar signs in
29851    input NAME to underscores.  Used by XCOFF ASM_OUTPUT_LABELREF.  */
29852
29853 const char *
29854 rs6000_xcoff_strip_dollar (const char *name)
29855 {
29856   char *strip, *p;
29857   const char *q;
29858   size_t len;
29859
29860   q = (const char *) strchr (name, '$');
29861
29862   if (q == 0 || q == name)
29863     return name;
29864
29865   len = strlen (name);
29866   strip = XALLOCAVEC (char, len + 1);
29867   strcpy (strip, name);
29868   p = strip + (q - name);
29869   while (p)
29870     {
29871       *p = '_';
29872       p = strchr (p + 1, '$');
29873     }
29874
29875   return ggc_alloc_string (strip, len);
29876 }
29877 #endif
29878
29879 void
29880 rs6000_output_symbol_ref (FILE *file, rtx x)
29881 {
29882   const char *name = XSTR (x, 0);
29883
29884   /* Currently C++ toc references to vtables can be emitted before it
29885      is decided whether the vtable is public or private.  If this is
29886      the case, then the linker will eventually complain that there is
29887      a reference to an unknown section.  Thus, for vtables only,
29888      we emit the TOC reference to reference the identifier and not the
29889      symbol.  */
29890   if (VTABLE_NAME_P (name))
29891     {
29892       RS6000_OUTPUT_BASENAME (file, name);
29893     }
29894   else
29895     assemble_name (file, name);
29896 }
29897
29898 /* Output a TOC entry.  We derive the entry name from what is being
29899    written.  */
29900
29901 void
29902 output_toc (FILE *file, rtx x, int labelno, machine_mode mode)
29903 {
29904   char buf[256];
29905   const char *name = buf;
29906   rtx base = x;
29907   HOST_WIDE_INT offset = 0;
29908
29909   gcc_assert (!TARGET_NO_TOC);
29910
29911   /* When the linker won't eliminate them, don't output duplicate
29912      TOC entries (this happens on AIX if there is any kind of TOC,
29913      and on SVR4 under -fPIC or -mrelocatable).  Don't do this for
29914      CODE_LABELs.  */
29915   if (TARGET_TOC && GET_CODE (x) != LABEL_REF)
29916     {
29917       struct toc_hash_struct *h;
29918
29919       /* Create toc_hash_table.  This can't be done at TARGET_OPTION_OVERRIDE
29920          time because GGC is not initialized at that point.  */
29921       if (toc_hash_table == NULL)
29922         toc_hash_table = hash_table<toc_hasher>::create_ggc (1021);
29923
29924       h = ggc_alloc<toc_hash_struct> ();
29925       h->key = x;
29926       h->key_mode = mode;
29927       h->labelno = labelno;
29928
29929       toc_hash_struct **found = toc_hash_table->find_slot (h, INSERT);
29930       if (*found == NULL)
29931         *found = h;
29932       else  /* This is indeed a duplicate.
29933                Set this label equal to that label.  */
29934         {
29935           fputs ("\t.set ", file);
29936           ASM_OUTPUT_INTERNAL_LABEL_PREFIX (file, "LC");
29937           fprintf (file, "%d,", labelno);
29938           ASM_OUTPUT_INTERNAL_LABEL_PREFIX (file, "LC");
29939           fprintf (file, "%d\n", ((*found)->labelno));
29940
29941 #ifdef HAVE_AS_TLS
29942           if (TARGET_XCOFF && GET_CODE (x) == SYMBOL_REF
29943               && (SYMBOL_REF_TLS_MODEL (x) == TLS_MODEL_GLOBAL_DYNAMIC
29944                   || SYMBOL_REF_TLS_MODEL (x) == TLS_MODEL_LOCAL_DYNAMIC))
29945             {
29946               fputs ("\t.set ", file);
29947               ASM_OUTPUT_INTERNAL_LABEL_PREFIX (file, "LCM");
29948               fprintf (file, "%d,", labelno);
29949               ASM_OUTPUT_INTERNAL_LABEL_PREFIX (file, "LCM");
29950               fprintf (file, "%d\n", ((*found)->labelno));
29951             }
29952 #endif
29953           return;
29954         }
29955     }
29956
29957   /* If we're going to put a double constant in the TOC, make sure it's
29958      aligned properly when strict alignment is on.  */
29959   if ((CONST_DOUBLE_P (x) || CONST_WIDE_INT_P (x))
29960       && STRICT_ALIGNMENT
29961       && GET_MODE_BITSIZE (mode) >= 64
29962       && ! (TARGET_NO_FP_IN_TOC && ! TARGET_MINIMAL_TOC)) {
29963     ASM_OUTPUT_ALIGN (file, 3);
29964   }
29965
29966   (*targetm.asm_out.internal_label) (file, "LC", labelno);
29967
29968   /* Handle FP constants specially.  Note that if we have a minimal
29969      TOC, things we put here aren't actually in the TOC, so we can allow
29970      FP constants.  */
29971   if (GET_CODE (x) == CONST_DOUBLE &&
29972       (GET_MODE (x) == TFmode || GET_MODE (x) == TDmode
29973        || GET_MODE (x) == IFmode || GET_MODE (x) == KFmode))
29974     {
29975       long k[4];
29976
29977       if (DECIMAL_FLOAT_MODE_P (GET_MODE (x)))
29978         REAL_VALUE_TO_TARGET_DECIMAL128 (*CONST_DOUBLE_REAL_VALUE (x), k);
29979       else
29980         REAL_VALUE_TO_TARGET_LONG_DOUBLE (*CONST_DOUBLE_REAL_VALUE (x), k);
29981
29982       if (TARGET_64BIT)
29983         {
29984           if (TARGET_ELF || TARGET_MINIMAL_TOC)
29985             fputs (DOUBLE_INT_ASM_OP, file);
29986           else
29987             fprintf (file, "\t.tc FT_%lx_%lx_%lx_%lx[TC],",
29988                      k[0] & 0xffffffff, k[1] & 0xffffffff,
29989                      k[2] & 0xffffffff, k[3] & 0xffffffff);
29990           fprintf (file, "0x%lx%08lx,0x%lx%08lx\n",
29991                    k[WORDS_BIG_ENDIAN ? 0 : 1] & 0xffffffff,
29992                    k[WORDS_BIG_ENDIAN ? 1 : 0] & 0xffffffff,
29993                    k[WORDS_BIG_ENDIAN ? 2 : 3] & 0xffffffff,
29994                    k[WORDS_BIG_ENDIAN ? 3 : 2] & 0xffffffff);
29995           return;
29996         }
29997       else
29998         {
29999           if (TARGET_ELF || TARGET_MINIMAL_TOC)
30000             fputs ("\t.long ", file);
30001           else
30002             fprintf (file, "\t.tc FT_%lx_%lx_%lx_%lx[TC],",
30003                      k[0] & 0xffffffff, k[1] & 0xffffffff,
30004                      k[2] & 0xffffffff, k[3] & 0xffffffff);
30005           fprintf (file, "0x%lx,0x%lx,0x%lx,0x%lx\n",
30006                    k[0] & 0xffffffff, k[1] & 0xffffffff,
30007                    k[2] & 0xffffffff, k[3] & 0xffffffff);
30008           return;
30009         }
30010     }
30011   else if (GET_CODE (x) == CONST_DOUBLE &&
30012            (GET_MODE (x) == DFmode || GET_MODE (x) == DDmode))
30013     {
30014       long k[2];
30015
30016       if (DECIMAL_FLOAT_MODE_P (GET_MODE (x)))
30017         REAL_VALUE_TO_TARGET_DECIMAL64 (*CONST_DOUBLE_REAL_VALUE (x), k);
30018       else
30019         REAL_VALUE_TO_TARGET_DOUBLE (*CONST_DOUBLE_REAL_VALUE (x), k);
30020
30021       if (TARGET_64BIT)
30022         {
30023           if (TARGET_ELF || TARGET_MINIMAL_TOC)
30024             fputs (DOUBLE_INT_ASM_OP, file);
30025           else
30026             fprintf (file, "\t.tc FD_%lx_%lx[TC],",
30027                      k[0] & 0xffffffff, k[1] & 0xffffffff);
30028           fprintf (file, "0x%lx%08lx\n",
30029                    k[WORDS_BIG_ENDIAN ? 0 : 1] & 0xffffffff,
30030                    k[WORDS_BIG_ENDIAN ? 1 : 0] & 0xffffffff);
30031           return;
30032         }
30033       else
30034         {
30035           if (TARGET_ELF || TARGET_MINIMAL_TOC)
30036             fputs ("\t.long ", file);
30037           else
30038             fprintf (file, "\t.tc FD_%lx_%lx[TC],",
30039                      k[0] & 0xffffffff, k[1] & 0xffffffff);
30040           fprintf (file, "0x%lx,0x%lx\n",
30041                    k[0] & 0xffffffff, k[1] & 0xffffffff);
30042           return;
30043         }
30044     }
30045   else if (GET_CODE (x) == CONST_DOUBLE &&
30046            (GET_MODE (x) == SFmode || GET_MODE (x) == SDmode))
30047     {
30048       long l;
30049
30050       if (DECIMAL_FLOAT_MODE_P (GET_MODE (x)))
30051         REAL_VALUE_TO_TARGET_DECIMAL32 (*CONST_DOUBLE_REAL_VALUE (x), l);
30052       else
30053         REAL_VALUE_TO_TARGET_SINGLE (*CONST_DOUBLE_REAL_VALUE (x), l);
30054
30055       if (TARGET_64BIT)
30056         {
30057           if (TARGET_ELF || TARGET_MINIMAL_TOC)
30058             fputs (DOUBLE_INT_ASM_OP, file);
30059           else
30060             fprintf (file, "\t.tc FS_%lx[TC],", l & 0xffffffff);
30061           if (WORDS_BIG_ENDIAN)
30062             fprintf (file, "0x%lx00000000\n", l & 0xffffffff);
30063           else
30064             fprintf (file, "0x%lx\n", l & 0xffffffff);
30065           return;
30066         }
30067       else
30068         {
30069           if (TARGET_ELF || TARGET_MINIMAL_TOC)
30070             fputs ("\t.long ", file);
30071           else
30072             fprintf (file, "\t.tc FS_%lx[TC],", l & 0xffffffff);
30073           fprintf (file, "0x%lx\n", l & 0xffffffff);
30074           return;
30075         }
30076     }
30077   else if (GET_MODE (x) == VOIDmode && GET_CODE (x) == CONST_INT)
30078     {
30079       unsigned HOST_WIDE_INT low;
30080       HOST_WIDE_INT high;
30081
30082       low = INTVAL (x) & 0xffffffff;
30083       high = (HOST_WIDE_INT) INTVAL (x) >> 32;
30084
30085       /* TOC entries are always Pmode-sized, so when big-endian
30086          smaller integer constants in the TOC need to be padded.
30087          (This is still a win over putting the constants in
30088          a separate constant pool, because then we'd have
30089          to have both a TOC entry _and_ the actual constant.)
30090
30091          For a 32-bit target, CONST_INT values are loaded and shifted
30092          entirely within `low' and can be stored in one TOC entry.  */
30093
30094       /* It would be easy to make this work, but it doesn't now.  */
30095       gcc_assert (!TARGET_64BIT || POINTER_SIZE >= GET_MODE_BITSIZE (mode));
30096
30097       if (WORDS_BIG_ENDIAN && POINTER_SIZE > GET_MODE_BITSIZE (mode))
30098         {
30099           low |= high << 32;
30100           low <<= POINTER_SIZE - GET_MODE_BITSIZE (mode);
30101           high = (HOST_WIDE_INT) low >> 32;
30102           low &= 0xffffffff;
30103         }
30104
30105       if (TARGET_64BIT)
30106         {
30107           if (TARGET_ELF || TARGET_MINIMAL_TOC)
30108             fputs (DOUBLE_INT_ASM_OP, file);
30109           else
30110             fprintf (file, "\t.tc ID_%lx_%lx[TC],",
30111                      (long) high & 0xffffffff, (long) low & 0xffffffff);
30112           fprintf (file, "0x%lx%08lx\n",
30113                    (long) high & 0xffffffff, (long) low & 0xffffffff);
30114           return;
30115         }
30116       else
30117         {
30118           if (POINTER_SIZE < GET_MODE_BITSIZE (mode))
30119             {
30120               if (TARGET_ELF || TARGET_MINIMAL_TOC)
30121                 fputs ("\t.long ", file);
30122               else
30123                 fprintf (file, "\t.tc ID_%lx_%lx[TC],",
30124                          (long) high & 0xffffffff, (long) low & 0xffffffff);
30125               fprintf (file, "0x%lx,0x%lx\n",
30126                        (long) high & 0xffffffff, (long) low & 0xffffffff);
30127             }
30128           else
30129             {
30130               if (TARGET_ELF || TARGET_MINIMAL_TOC)
30131                 fputs ("\t.long ", file);
30132               else
30133                 fprintf (file, "\t.tc IS_%lx[TC],", (long) low & 0xffffffff);
30134               fprintf (file, "0x%lx\n", (long) low & 0xffffffff);
30135             }
30136           return;
30137         }
30138     }
30139
30140   if (GET_CODE (x) == CONST)
30141     {
30142       gcc_assert (GET_CODE (XEXP (x, 0)) == PLUS
30143                   && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT);
30144
30145       base = XEXP (XEXP (x, 0), 0);
30146       offset = INTVAL (XEXP (XEXP (x, 0), 1));
30147     }
30148
30149   switch (GET_CODE (base))
30150     {
30151     case SYMBOL_REF:
30152       name = XSTR (base, 0);
30153       break;
30154
30155     case LABEL_REF:
30156       ASM_GENERATE_INTERNAL_LABEL (buf, "L",
30157                                    CODE_LABEL_NUMBER (XEXP (base, 0)));
30158       break;
30159
30160     case CODE_LABEL:
30161       ASM_GENERATE_INTERNAL_LABEL (buf, "L", CODE_LABEL_NUMBER (base));
30162       break;
30163
30164     default:
30165       gcc_unreachable ();
30166     }
30167
30168   if (TARGET_ELF || TARGET_MINIMAL_TOC)
30169     fputs (TARGET_32BIT ? "\t.long " : DOUBLE_INT_ASM_OP, file);
30170   else
30171     {
30172       fputs ("\t.tc ", file);
30173       RS6000_OUTPUT_BASENAME (file, name);
30174
30175       if (offset < 0)
30176         fprintf (file, ".N" HOST_WIDE_INT_PRINT_UNSIGNED, - offset);
30177       else if (offset)
30178         fprintf (file, ".P" HOST_WIDE_INT_PRINT_UNSIGNED, offset);
30179
30180       /* Mark large TOC symbols on AIX with [TE] so they are mapped
30181          after other TOC symbols, reducing overflow of small TOC access
30182          to [TC] symbols.  */
30183       fputs (TARGET_XCOFF && TARGET_CMODEL != CMODEL_SMALL
30184              ? "[TE]," : "[TC],", file);
30185     }
30186
30187   /* Currently C++ toc references to vtables can be emitted before it
30188      is decided whether the vtable is public or private.  If this is
30189      the case, then the linker will eventually complain that there is
30190      a TOC reference to an unknown section.  Thus, for vtables only,
30191      we emit the TOC reference to reference the symbol and not the
30192      section.  */
30193   if (VTABLE_NAME_P (name))
30194     {
30195       RS6000_OUTPUT_BASENAME (file, name);
30196       if (offset < 0)
30197         fprintf (file, HOST_WIDE_INT_PRINT_DEC, offset);
30198       else if (offset > 0)
30199         fprintf (file, "+" HOST_WIDE_INT_PRINT_DEC, offset);
30200     }
30201   else
30202     output_addr_const (file, x);
30203
30204 #if HAVE_AS_TLS
30205   if (TARGET_XCOFF && GET_CODE (base) == SYMBOL_REF)
30206     {
30207       switch (SYMBOL_REF_TLS_MODEL (base))
30208         {
30209         case 0:
30210           break;
30211         case TLS_MODEL_LOCAL_EXEC:
30212           fputs ("@le", file);
30213           break;
30214         case TLS_MODEL_INITIAL_EXEC:
30215           fputs ("@ie", file);
30216           break;
30217         /* Use global-dynamic for local-dynamic.  */
30218         case TLS_MODEL_GLOBAL_DYNAMIC:
30219         case TLS_MODEL_LOCAL_DYNAMIC:
30220           putc ('\n', file);
30221           (*targetm.asm_out.internal_label) (file, "LCM", labelno);
30222           fputs ("\t.tc .", file);
30223           RS6000_OUTPUT_BASENAME (file, name);
30224           fputs ("[TC],", file);
30225           output_addr_const (file, x);
30226           fputs ("@m", file);
30227           break;
30228         default:
30229           gcc_unreachable ();
30230         }
30231     }
30232 #endif
30233
30234   putc ('\n', file);
30235 }
30236 \f
30237 /* Output an assembler pseudo-op to write an ASCII string of N characters
30238    starting at P to FILE.
30239
30240    On the RS/6000, we have to do this using the .byte operation and
30241    write out special characters outside the quoted string.
30242    Also, the assembler is broken; very long strings are truncated,
30243    so we must artificially break them up early.  */
30244
30245 void
30246 output_ascii (FILE *file, const char *p, int n)
30247 {
30248   char c;
30249   int i, count_string;
30250   const char *for_string = "\t.byte \"";
30251   const char *for_decimal = "\t.byte ";
30252   const char *to_close = NULL;
30253
30254   count_string = 0;
30255   for (i = 0; i < n; i++)
30256     {
30257       c = *p++;
30258       if (c >= ' ' && c < 0177)
30259         {
30260           if (for_string)
30261             fputs (for_string, file);
30262           putc (c, file);
30263
30264           /* Write two quotes to get one.  */
30265           if (c == '"')
30266             {
30267               putc (c, file);
30268               ++count_string;
30269             }
30270
30271           for_string = NULL;
30272           for_decimal = "\"\n\t.byte ";
30273           to_close = "\"\n";
30274           ++count_string;
30275
30276           if (count_string >= 512)
30277             {
30278               fputs (to_close, file);
30279
30280               for_string = "\t.byte \"";
30281               for_decimal = "\t.byte ";
30282               to_close = NULL;
30283               count_string = 0;
30284             }
30285         }
30286       else
30287         {
30288           if (for_decimal)
30289             fputs (for_decimal, file);
30290           fprintf (file, "%d", c);
30291
30292           for_string = "\n\t.byte \"";
30293           for_decimal = ", ";
30294           to_close = "\n";
30295           count_string = 0;
30296         }
30297     }
30298
30299   /* Now close the string if we have written one.  Then end the line.  */
30300   if (to_close)
30301     fputs (to_close, file);
30302 }
30303 \f
30304 /* Generate a unique section name for FILENAME for a section type
30305    represented by SECTION_DESC.  Output goes into BUF.
30306
30307    SECTION_DESC can be any string, as long as it is different for each
30308    possible section type.
30309
30310    We name the section in the same manner as xlc.  The name begins with an
30311    underscore followed by the filename (after stripping any leading directory
30312    names) with the last period replaced by the string SECTION_DESC.  If
30313    FILENAME does not contain a period, SECTION_DESC is appended to the end of
30314    the name.  */
30315
30316 void
30317 rs6000_gen_section_name (char **buf, const char *filename,
30318                          const char *section_desc)
30319 {
30320   const char *q, *after_last_slash, *last_period = 0;
30321   char *p;
30322   int len;
30323
30324   after_last_slash = filename;
30325   for (q = filename; *q; q++)
30326     {
30327       if (*q == '/')
30328         after_last_slash = q + 1;
30329       else if (*q == '.')
30330         last_period = q;
30331     }
30332
30333   len = strlen (after_last_slash) + strlen (section_desc) + 2;
30334   *buf = (char *) xmalloc (len);
30335
30336   p = *buf;
30337   *p++ = '_';
30338
30339   for (q = after_last_slash; *q; q++)
30340     {
30341       if (q == last_period)
30342         {
30343           strcpy (p, section_desc);
30344           p += strlen (section_desc);
30345           break;
30346         }
30347
30348       else if (ISALNUM (*q))
30349         *p++ = *q;
30350     }
30351
30352   if (last_period == 0)
30353     strcpy (p, section_desc);
30354   else
30355     *p = '\0';
30356 }
30357 \f
30358 /* Emit profile function.  */
30359
30360 void
30361 output_profile_hook (int labelno ATTRIBUTE_UNUSED)
30362 {
30363   /* Non-standard profiling for kernels, which just saves LR then calls
30364      _mcount without worrying about arg saves.  The idea is to change
30365      the function prologue as little as possible as it isn't easy to
30366      account for arg save/restore code added just for _mcount.  */
30367   if (TARGET_PROFILE_KERNEL)
30368     return;
30369
30370   if (DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
30371     {
30372 #ifndef NO_PROFILE_COUNTERS
30373 # define NO_PROFILE_COUNTERS 0
30374 #endif
30375       if (NO_PROFILE_COUNTERS)
30376         emit_library_call (init_one_libfunc (RS6000_MCOUNT),
30377                            LCT_NORMAL, VOIDmode);
30378       else
30379         {
30380           char buf[30];
30381           const char *label_name;
30382           rtx fun;
30383
30384           ASM_GENERATE_INTERNAL_LABEL (buf, "LP", labelno);
30385           label_name = ggc_strdup ((*targetm.strip_name_encoding) (buf));
30386           fun = gen_rtx_SYMBOL_REF (Pmode, label_name);
30387
30388           emit_library_call (init_one_libfunc (RS6000_MCOUNT),
30389                              LCT_NORMAL, VOIDmode, fun, Pmode);
30390         }
30391     }
30392   else if (DEFAULT_ABI == ABI_DARWIN)
30393     {
30394       const char *mcount_name = RS6000_MCOUNT;
30395       int caller_addr_regno = LR_REGNO;
30396
30397       /* Be conservative and always set this, at least for now.  */
30398       crtl->uses_pic_offset_table = 1;
30399
30400 #if TARGET_MACHO
30401       /* For PIC code, set up a stub and collect the caller's address
30402          from r0, which is where the prologue puts it.  */
30403       if (MACHOPIC_INDIRECT
30404           && crtl->uses_pic_offset_table)
30405         caller_addr_regno = 0;
30406 #endif
30407       emit_library_call (gen_rtx_SYMBOL_REF (Pmode, mcount_name),
30408                          LCT_NORMAL, VOIDmode,
30409                          gen_rtx_REG (Pmode, caller_addr_regno), Pmode);
30410     }
30411 }
30412
30413 /* Write function profiler code.  */
30414
30415 void
30416 output_function_profiler (FILE *file, int labelno)
30417 {
30418   char buf[100];
30419
30420   switch (DEFAULT_ABI)
30421     {
30422     default:
30423       gcc_unreachable ();
30424
30425     case ABI_V4:
30426       if (!TARGET_32BIT)
30427         {
30428           warning (0, "no profiling of 64-bit code for this ABI");
30429           return;
30430         }
30431       ASM_GENERATE_INTERNAL_LABEL (buf, "LP", labelno);
30432       fprintf (file, "\tmflr %s\n", reg_names[0]);
30433       if (NO_PROFILE_COUNTERS)
30434         {
30435           asm_fprintf (file, "\tstw %s,4(%s)\n",
30436                        reg_names[0], reg_names[1]);
30437         }
30438       else if (TARGET_SECURE_PLT && flag_pic)
30439         {
30440           if (TARGET_LINK_STACK)
30441             {
30442               char name[32];
30443               get_ppc476_thunk_name (name);
30444               asm_fprintf (file, "\tbl %s\n", name);
30445             }
30446           else
30447             asm_fprintf (file, "\tbcl 20,31,1f\n1:\n");
30448           asm_fprintf (file, "\tstw %s,4(%s)\n",
30449                        reg_names[0], reg_names[1]);
30450           asm_fprintf (file, "\tmflr %s\n", reg_names[12]);
30451           asm_fprintf (file, "\taddis %s,%s,",
30452                        reg_names[12], reg_names[12]);
30453           assemble_name (file, buf);
30454           asm_fprintf (file, "-1b@ha\n\tla %s,", reg_names[0]);
30455           assemble_name (file, buf);
30456           asm_fprintf (file, "-1b@l(%s)\n", reg_names[12]);
30457         }
30458       else if (flag_pic == 1)
30459         {
30460           fputs ("\tbl _GLOBAL_OFFSET_TABLE_@local-4\n", file);
30461           asm_fprintf (file, "\tstw %s,4(%s)\n",
30462                        reg_names[0], reg_names[1]);
30463           asm_fprintf (file, "\tmflr %s\n", reg_names[12]);
30464           asm_fprintf (file, "\tlwz %s,", reg_names[0]);
30465           assemble_name (file, buf);
30466           asm_fprintf (file, "@got(%s)\n", reg_names[12]);
30467         }
30468       else if (flag_pic > 1)
30469         {
30470           asm_fprintf (file, "\tstw %s,4(%s)\n",
30471                        reg_names[0], reg_names[1]);
30472           /* Now, we need to get the address of the label.  */
30473           if (TARGET_LINK_STACK)
30474             {
30475               char name[32];
30476               get_ppc476_thunk_name (name);
30477               asm_fprintf (file, "\tbl %s\n\tb 1f\n\t.long ", name);
30478               assemble_name (file, buf);
30479               fputs ("-.\n1:", file);
30480               asm_fprintf (file, "\tmflr %s\n", reg_names[11]);
30481               asm_fprintf (file, "\taddi %s,%s,4\n",
30482                            reg_names[11], reg_names[11]);
30483             }
30484           else
30485             {
30486               fputs ("\tbcl 20,31,1f\n\t.long ", file);
30487               assemble_name (file, buf);
30488               fputs ("-.\n1:", file);
30489               asm_fprintf (file, "\tmflr %s\n", reg_names[11]);
30490             }
30491           asm_fprintf (file, "\tlwz %s,0(%s)\n",
30492                        reg_names[0], reg_names[11]);
30493           asm_fprintf (file, "\tadd %s,%s,%s\n",
30494                        reg_names[0], reg_names[0], reg_names[11]);
30495         }
30496       else
30497         {
30498           asm_fprintf (file, "\tlis %s,", reg_names[12]);
30499           assemble_name (file, buf);
30500           fputs ("@ha\n", file);
30501           asm_fprintf (file, "\tstw %s,4(%s)\n",
30502                        reg_names[0], reg_names[1]);
30503           asm_fprintf (file, "\tla %s,", reg_names[0]);
30504           assemble_name (file, buf);
30505           asm_fprintf (file, "@l(%s)\n", reg_names[12]);
30506         }
30507
30508       /* ABI_V4 saves the static chain reg with ASM_OUTPUT_REG_PUSH.  */
30509       fprintf (file, "\tbl %s%s\n",
30510                RS6000_MCOUNT, flag_pic ? "@plt" : "");
30511       break;
30512
30513     case ABI_AIX:
30514     case ABI_ELFv2:
30515     case ABI_DARWIN:
30516       /* Don't do anything, done in output_profile_hook ().  */
30517       break;
30518     }
30519 }
30520
30521 \f
30522
30523 /* The following variable value is the last issued insn.  */
30524
30525 static rtx_insn *last_scheduled_insn;
30526
30527 /* The following variable helps to balance issuing of load and
30528    store instructions */
30529
30530 static int load_store_pendulum;
30531
30532 /* The following variable helps pair divide insns during scheduling.  */
30533 static int divide_cnt;
30534 /* The following variable helps pair and alternate vector and vector load
30535    insns during scheduling.  */
30536 static int vec_pairing;
30537
30538
30539 /* Power4 load update and store update instructions are cracked into a
30540    load or store and an integer insn which are executed in the same cycle.
30541    Branches have their own dispatch slot which does not count against the
30542    GCC issue rate, but it changes the program flow so there are no other
30543    instructions to issue in this cycle.  */
30544
30545 static int
30546 rs6000_variable_issue_1 (rtx_insn *insn, int more)
30547 {
30548   last_scheduled_insn = insn;
30549   if (GET_CODE (PATTERN (insn)) == USE
30550       || GET_CODE (PATTERN (insn)) == CLOBBER)
30551     {
30552       cached_can_issue_more = more;
30553       return cached_can_issue_more;
30554     }
30555
30556   if (insn_terminates_group_p (insn, current_group))
30557     {
30558       cached_can_issue_more = 0;
30559       return cached_can_issue_more;
30560     }
30561
30562   /* If no reservation, but reach here */
30563   if (recog_memoized (insn) < 0)
30564     return more;
30565
30566   if (rs6000_sched_groups)
30567     {
30568       if (is_microcoded_insn (insn))
30569         cached_can_issue_more = 0;
30570       else if (is_cracked_insn (insn))
30571         cached_can_issue_more = more > 2 ? more - 2 : 0;
30572       else
30573         cached_can_issue_more = more - 1;
30574
30575       return cached_can_issue_more;
30576     }
30577
30578   if (rs6000_tune == PROCESSOR_CELL && is_nonpipeline_insn (insn))
30579     return 0;
30580
30581   cached_can_issue_more = more - 1;
30582   return cached_can_issue_more;
30583 }
30584
30585 static int
30586 rs6000_variable_issue (FILE *stream, int verbose, rtx_insn *insn, int more)
30587 {
30588   int r = rs6000_variable_issue_1 (insn, more);
30589   if (verbose)
30590     fprintf (stream, "// rs6000_variable_issue (more = %d) = %d\n", more, r);
30591   return r;
30592 }
30593
30594 /* Adjust the cost of a scheduling dependency.  Return the new cost of
30595    a dependency LINK or INSN on DEP_INSN.  COST is the current cost.  */
30596
30597 static int
30598 rs6000_adjust_cost (rtx_insn *insn, int dep_type, rtx_insn *dep_insn, int cost,
30599                     unsigned int)
30600 {
30601   enum attr_type attr_type;
30602
30603   if (recog_memoized (insn) < 0 || recog_memoized (dep_insn) < 0)
30604     return cost;
30605
30606   switch (dep_type)
30607     {
30608     case REG_DEP_TRUE:
30609       {
30610         /* Data dependency; DEP_INSN writes a register that INSN reads
30611            some cycles later.  */
30612
30613         /* Separate a load from a narrower, dependent store.  */
30614         if ((rs6000_sched_groups || rs6000_tune == PROCESSOR_POWER9)
30615             && GET_CODE (PATTERN (insn)) == SET
30616             && GET_CODE (PATTERN (dep_insn)) == SET
30617             && GET_CODE (XEXP (PATTERN (insn), 1)) == MEM
30618             && GET_CODE (XEXP (PATTERN (dep_insn), 0)) == MEM
30619             && (GET_MODE_SIZE (GET_MODE (XEXP (PATTERN (insn), 1)))
30620                 > GET_MODE_SIZE (GET_MODE (XEXP (PATTERN (dep_insn), 0)))))
30621           return cost + 14;
30622
30623         attr_type = get_attr_type (insn);
30624
30625         switch (attr_type)
30626           {
30627           case TYPE_JMPREG:
30628             /* Tell the first scheduling pass about the latency between
30629                a mtctr and bctr (and mtlr and br/blr).  The first
30630                scheduling pass will not know about this latency since
30631                the mtctr instruction, which has the latency associated
30632                to it, will be generated by reload.  */
30633             return 4;
30634           case TYPE_BRANCH:
30635             /* Leave some extra cycles between a compare and its
30636                dependent branch, to inhibit expensive mispredicts.  */
30637             if ((rs6000_tune == PROCESSOR_PPC603
30638                  || rs6000_tune == PROCESSOR_PPC604
30639                  || rs6000_tune == PROCESSOR_PPC604e
30640                  || rs6000_tune == PROCESSOR_PPC620
30641                  || rs6000_tune == PROCESSOR_PPC630
30642                  || rs6000_tune == PROCESSOR_PPC750
30643                  || rs6000_tune == PROCESSOR_PPC7400
30644                  || rs6000_tune == PROCESSOR_PPC7450
30645                  || rs6000_tune == PROCESSOR_PPCE5500
30646                  || rs6000_tune == PROCESSOR_PPCE6500
30647                  || rs6000_tune == PROCESSOR_POWER4
30648                  || rs6000_tune == PROCESSOR_POWER5
30649                  || rs6000_tune == PROCESSOR_POWER7
30650                  || rs6000_tune == PROCESSOR_POWER8
30651                  || rs6000_tune == PROCESSOR_POWER9
30652                  || rs6000_tune == PROCESSOR_CELL)
30653                 && recog_memoized (dep_insn)
30654                 && (INSN_CODE (dep_insn) >= 0))
30655
30656               switch (get_attr_type (dep_insn))
30657                 {
30658                 case TYPE_CMP:
30659                 case TYPE_FPCOMPARE:
30660                 case TYPE_CR_LOGICAL:
30661                   return cost + 2;
30662                 case TYPE_EXTS:
30663                 case TYPE_MUL:
30664                   if (get_attr_dot (dep_insn) == DOT_YES)
30665                     return cost + 2;
30666                   else
30667                     break;
30668                 case TYPE_SHIFT:
30669                   if (get_attr_dot (dep_insn) == DOT_YES
30670                       && get_attr_var_shift (dep_insn) == VAR_SHIFT_NO)
30671                     return cost + 2;
30672                   else
30673                     break;
30674                 default:
30675                   break;
30676                 }
30677             break;
30678
30679           case TYPE_STORE:
30680           case TYPE_FPSTORE:
30681             if ((rs6000_tune == PROCESSOR_POWER6)
30682                 && recog_memoized (dep_insn)
30683                 && (INSN_CODE (dep_insn) >= 0))
30684               {
30685
30686                 if (GET_CODE (PATTERN (insn)) != SET)
30687                   /* If this happens, we have to extend this to schedule
30688                      optimally.  Return default for now.  */
30689                   return cost;
30690
30691                 /* Adjust the cost for the case where the value written
30692                    by a fixed point operation is used as the address
30693                    gen value on a store. */
30694                 switch (get_attr_type (dep_insn))
30695                   {
30696                   case TYPE_LOAD:
30697                   case TYPE_CNTLZ:
30698                     {
30699                       if (! rs6000_store_data_bypass_p (dep_insn, insn))
30700                         return get_attr_sign_extend (dep_insn)
30701                                == SIGN_EXTEND_YES ? 6 : 4;
30702                       break;
30703                     }
30704                   case TYPE_SHIFT:
30705                     {
30706                       if (! rs6000_store_data_bypass_p (dep_insn, insn))
30707                         return get_attr_var_shift (dep_insn) == VAR_SHIFT_YES ?
30708                                6 : 3;
30709                       break;
30710                     }
30711                   case TYPE_INTEGER:
30712                   case TYPE_ADD:
30713                   case TYPE_LOGICAL:
30714                   case TYPE_EXTS:
30715                   case TYPE_INSERT:
30716                     {
30717                       if (! rs6000_store_data_bypass_p (dep_insn, insn))
30718                         return 3;
30719                       break;
30720                     }
30721                   case TYPE_STORE:
30722                   case TYPE_FPLOAD:
30723                   case TYPE_FPSTORE:
30724                     {
30725                       if (get_attr_update (dep_insn) == UPDATE_YES
30726                           && ! rs6000_store_data_bypass_p (dep_insn, insn))
30727                         return 3;
30728                       break;
30729                     }
30730                   case TYPE_MUL:
30731                     {
30732                       if (! rs6000_store_data_bypass_p (dep_insn, insn))
30733                         return 17;
30734                       break;
30735                     }
30736                   case TYPE_DIV:
30737                     {
30738                       if (! rs6000_store_data_bypass_p (dep_insn, insn))
30739                         return get_attr_size (dep_insn) == SIZE_32 ? 45 : 57;
30740                       break;
30741                     }
30742                   default:
30743                     break;
30744                   }
30745               }
30746             break;
30747
30748           case TYPE_LOAD:
30749             if ((rs6000_tune == PROCESSOR_POWER6)
30750                 && recog_memoized (dep_insn)
30751                 && (INSN_CODE (dep_insn) >= 0))
30752               {
30753
30754                 /* Adjust the cost for the case where the value written
30755                    by a fixed point instruction is used within the address
30756                    gen portion of a subsequent load(u)(x) */
30757                 switch (get_attr_type (dep_insn))
30758                   {
30759                   case TYPE_LOAD:
30760                   case TYPE_CNTLZ:
30761                     {
30762                       if (set_to_load_agen (dep_insn, insn))
30763                         return get_attr_sign_extend (dep_insn)
30764                                == SIGN_EXTEND_YES ? 6 : 4;
30765                       break;
30766                     }
30767                   case TYPE_SHIFT:
30768                     {
30769                       if (set_to_load_agen (dep_insn, insn))
30770                         return get_attr_var_shift (dep_insn) == VAR_SHIFT_YES ?
30771                                6 : 3;
30772                       break;
30773                     }
30774                   case TYPE_INTEGER:
30775                   case TYPE_ADD:
30776                   case TYPE_LOGICAL:
30777                   case TYPE_EXTS:
30778                   case TYPE_INSERT:
30779                     {
30780                       if (set_to_load_agen (dep_insn, insn))
30781                         return 3;
30782                       break;
30783                     }
30784                   case TYPE_STORE:
30785                   case TYPE_FPLOAD:
30786                   case TYPE_FPSTORE:
30787                     {
30788                       if (get_attr_update (dep_insn) == UPDATE_YES
30789                           && set_to_load_agen (dep_insn, insn))
30790                         return 3;
30791                       break;
30792                     }
30793                   case TYPE_MUL:
30794                     {
30795                       if (set_to_load_agen (dep_insn, insn))
30796                         return 17;
30797                       break;
30798                     }
30799                   case TYPE_DIV:
30800                     {
30801                       if (set_to_load_agen (dep_insn, insn))
30802                         return get_attr_size (dep_insn) == SIZE_32 ? 45 : 57;
30803                       break;
30804                     }
30805                   default:
30806                     break;
30807                   }
30808               }
30809             break;
30810
30811           case TYPE_FPLOAD:
30812             if ((rs6000_tune == PROCESSOR_POWER6)
30813                 && get_attr_update (insn) == UPDATE_NO
30814                 && recog_memoized (dep_insn)
30815                 && (INSN_CODE (dep_insn) >= 0)
30816                 && (get_attr_type (dep_insn) == TYPE_MFFGPR))
30817               return 2;
30818
30819           default:
30820             break;
30821           }
30822
30823         /* Fall out to return default cost.  */
30824       }
30825       break;
30826
30827     case REG_DEP_OUTPUT:
30828       /* Output dependency; DEP_INSN writes a register that INSN writes some
30829          cycles later.  */
30830       if ((rs6000_tune == PROCESSOR_POWER6)
30831           && recog_memoized (dep_insn)
30832           && (INSN_CODE (dep_insn) >= 0))
30833         {
30834           attr_type = get_attr_type (insn);
30835
30836           switch (attr_type)
30837             {
30838             case TYPE_FP:
30839             case TYPE_FPSIMPLE:
30840               if (get_attr_type (dep_insn) == TYPE_FP
30841                   || get_attr_type (dep_insn) == TYPE_FPSIMPLE)
30842                 return 1;
30843               break;
30844             case TYPE_FPLOAD:
30845               if (get_attr_update (insn) == UPDATE_NO
30846                   && get_attr_type (dep_insn) == TYPE_MFFGPR)
30847                 return 2;
30848               break;
30849             default:
30850               break;
30851             }
30852         }
30853       /* Fall through, no cost for output dependency.  */
30854       /* FALLTHRU */
30855
30856     case REG_DEP_ANTI:
30857       /* Anti dependency; DEP_INSN reads a register that INSN writes some
30858          cycles later.  */
30859       return 0;
30860
30861     default:
30862       gcc_unreachable ();
30863     }
30864
30865   return cost;
30866 }
30867
30868 /* Debug version of rs6000_adjust_cost.  */
30869
30870 static int
30871 rs6000_debug_adjust_cost (rtx_insn *insn, int dep_type, rtx_insn *dep_insn,
30872                           int cost, unsigned int dw)
30873 {
30874   int ret = rs6000_adjust_cost (insn, dep_type, dep_insn, cost, dw);
30875
30876   if (ret != cost)
30877     {
30878       const char *dep;
30879
30880       switch (dep_type)
30881         {
30882         default:             dep = "unknown depencency"; break;
30883         case REG_DEP_TRUE:   dep = "data dependency";    break;
30884         case REG_DEP_OUTPUT: dep = "output dependency";  break;
30885         case REG_DEP_ANTI:   dep = "anti depencency";    break;
30886         }
30887
30888       fprintf (stderr,
30889                "\nrs6000_adjust_cost, final cost = %d, orig cost = %d, "
30890                "%s, insn:\n", ret, cost, dep);
30891
30892       debug_rtx (insn);
30893     }
30894
30895   return ret;
30896 }
30897
30898 /* The function returns a true if INSN is microcoded.
30899    Return false otherwise.  */
30900
30901 static bool
30902 is_microcoded_insn (rtx_insn *insn)
30903 {
30904   if (!insn || !NONDEBUG_INSN_P (insn)
30905       || GET_CODE (PATTERN (insn)) == USE
30906       || GET_CODE (PATTERN (insn)) == CLOBBER)
30907     return false;
30908
30909   if (rs6000_tune == PROCESSOR_CELL)
30910     return get_attr_cell_micro (insn) == CELL_MICRO_ALWAYS;
30911
30912   if (rs6000_sched_groups
30913       && (rs6000_tune == PROCESSOR_POWER4 || rs6000_tune == PROCESSOR_POWER5))
30914     {
30915       enum attr_type type = get_attr_type (insn);
30916       if ((type == TYPE_LOAD
30917            && get_attr_update (insn) == UPDATE_YES
30918            && get_attr_sign_extend (insn) == SIGN_EXTEND_YES)
30919           || ((type == TYPE_LOAD || type == TYPE_STORE)
30920               && get_attr_update (insn) == UPDATE_YES
30921               && get_attr_indexed (insn) == INDEXED_YES)
30922           || type == TYPE_MFCR)
30923         return true;
30924     }
30925
30926   return false;
30927 }
30928
30929 /* The function returns true if INSN is cracked into 2 instructions
30930    by the processor (and therefore occupies 2 issue slots).  */
30931
30932 static bool
30933 is_cracked_insn (rtx_insn *insn)
30934 {
30935   if (!insn || !NONDEBUG_INSN_P (insn)
30936       || GET_CODE (PATTERN (insn)) == USE
30937       || GET_CODE (PATTERN (insn)) == CLOBBER)
30938     return false;
30939
30940   if (rs6000_sched_groups
30941       && (rs6000_tune == PROCESSOR_POWER4 || rs6000_tune == PROCESSOR_POWER5))
30942     {
30943       enum attr_type type = get_attr_type (insn);
30944       if ((type == TYPE_LOAD
30945            && get_attr_sign_extend (insn) == SIGN_EXTEND_YES
30946            && get_attr_update (insn) == UPDATE_NO)
30947           || (type == TYPE_LOAD
30948               && get_attr_sign_extend (insn) == SIGN_EXTEND_NO
30949               && get_attr_update (insn) == UPDATE_YES
30950               && get_attr_indexed (insn) == INDEXED_NO)
30951           || (type == TYPE_STORE
30952               && get_attr_update (insn) == UPDATE_YES
30953               && get_attr_indexed (insn) == INDEXED_NO)
30954           || ((type == TYPE_FPLOAD || type == TYPE_FPSTORE)
30955               && get_attr_update (insn) == UPDATE_YES)
30956           || (type == TYPE_CR_LOGICAL
30957               && get_attr_cr_logical_3op (insn) == CR_LOGICAL_3OP_YES)
30958           || (type == TYPE_EXTS
30959               && get_attr_dot (insn) == DOT_YES)
30960           || (type == TYPE_SHIFT
30961               && get_attr_dot (insn) == DOT_YES
30962               && get_attr_var_shift (insn) == VAR_SHIFT_NO)
30963           || (type == TYPE_MUL
30964               && get_attr_dot (insn) == DOT_YES)
30965           || type == TYPE_DIV
30966           || (type == TYPE_INSERT
30967               && get_attr_size (insn) == SIZE_32))
30968         return true;
30969     }
30970
30971   return false;
30972 }
30973
30974 /* The function returns true if INSN can be issued only from
30975    the branch slot.  */
30976
30977 static bool
30978 is_branch_slot_insn (rtx_insn *insn)
30979 {
30980   if (!insn || !NONDEBUG_INSN_P (insn)
30981       || GET_CODE (PATTERN (insn)) == USE
30982       || GET_CODE (PATTERN (insn)) == CLOBBER)
30983     return false;
30984
30985   if (rs6000_sched_groups)
30986     {
30987       enum attr_type type = get_attr_type (insn);
30988       if (type == TYPE_BRANCH || type == TYPE_JMPREG)
30989         return true;
30990       return false;
30991     }
30992
30993   return false;
30994 }
30995
30996 /* The function returns true if out_inst sets a value that is
30997    used in the address generation computation of in_insn */
30998 static bool
30999 set_to_load_agen (rtx_insn *out_insn, rtx_insn *in_insn)
31000 {
31001   rtx out_set, in_set;
31002
31003   /* For performance reasons, only handle the simple case where
31004      both loads are a single_set. */
31005   out_set = single_set (out_insn);
31006   if (out_set)
31007     {
31008       in_set = single_set (in_insn);
31009       if (in_set)
31010         return reg_mentioned_p (SET_DEST (out_set), SET_SRC (in_set));
31011     }
31012
31013   return false;
31014 }
31015
31016 /* Try to determine base/offset/size parts of the given MEM.
31017    Return true if successful, false if all the values couldn't
31018    be determined.
31019
31020    This function only looks for REG or REG+CONST address forms.
31021    REG+REG address form will return false. */
31022
31023 static bool
31024 get_memref_parts (rtx mem, rtx *base, HOST_WIDE_INT *offset,
31025                   HOST_WIDE_INT *size)
31026 {
31027   rtx addr_rtx;
31028   if MEM_SIZE_KNOWN_P (mem)
31029     *size = MEM_SIZE (mem);
31030   else
31031     return false;
31032
31033   addr_rtx = (XEXP (mem, 0));
31034   if (GET_CODE (addr_rtx) == PRE_MODIFY)
31035     addr_rtx = XEXP (addr_rtx, 1);
31036
31037   *offset = 0;
31038   while (GET_CODE (addr_rtx) == PLUS
31039          && CONST_INT_P (XEXP (addr_rtx, 1)))
31040     {
31041       *offset += INTVAL (XEXP (addr_rtx, 1));
31042       addr_rtx = XEXP (addr_rtx, 0);
31043     }
31044   if (!REG_P (addr_rtx))
31045     return false;
31046
31047   *base = addr_rtx;
31048   return true;
31049 }
31050
31051 /* The function returns true if the target storage location of
31052    mem1 is adjacent to the target storage location of mem2 */
31053 /* Return 1 if memory locations are adjacent.  */
31054
31055 static bool
31056 adjacent_mem_locations (rtx mem1, rtx mem2)
31057 {
31058   rtx reg1, reg2;
31059   HOST_WIDE_INT off1, size1, off2, size2;
31060
31061   if (get_memref_parts (mem1, &reg1, &off1, &size1)
31062       && get_memref_parts (mem2, &reg2, &off2, &size2))
31063     return ((REGNO (reg1) == REGNO (reg2))
31064             && ((off1 + size1 == off2)
31065                 || (off2 + size2 == off1)));
31066
31067   return false;
31068 }
31069
31070 /* This function returns true if it can be determined that the two MEM
31071    locations overlap by at least 1 byte based on base reg/offset/size. */
31072
31073 static bool
31074 mem_locations_overlap (rtx mem1, rtx mem2)
31075 {
31076   rtx reg1, reg2;
31077   HOST_WIDE_INT off1, size1, off2, size2;
31078
31079   if (get_memref_parts (mem1, &reg1, &off1, &size1)
31080       && get_memref_parts (mem2, &reg2, &off2, &size2))
31081     return ((REGNO (reg1) == REGNO (reg2))
31082             && (((off1 <= off2) && (off1 + size1 > off2))
31083                 || ((off2 <= off1) && (off2 + size2 > off1))));
31084
31085   return false;
31086 }
31087
31088 /* A C statement (sans semicolon) to update the integer scheduling
31089    priority INSN_PRIORITY (INSN). Increase the priority to execute the
31090    INSN earlier, reduce the priority to execute INSN later.  Do not
31091    define this macro if you do not need to adjust the scheduling
31092    priorities of insns.  */
31093
31094 static int
31095 rs6000_adjust_priority (rtx_insn *insn ATTRIBUTE_UNUSED, int priority)
31096 {
31097   rtx load_mem, str_mem;
31098   /* On machines (like the 750) which have asymmetric integer units,
31099      where one integer unit can do multiply and divides and the other
31100      can't, reduce the priority of multiply/divide so it is scheduled
31101      before other integer operations.  */
31102
31103 #if 0
31104   if (! INSN_P (insn))
31105     return priority;
31106
31107   if (GET_CODE (PATTERN (insn)) == USE)
31108     return priority;
31109
31110   switch (rs6000_tune) {
31111   case PROCESSOR_PPC750:
31112     switch (get_attr_type (insn))
31113       {
31114       default:
31115         break;
31116
31117       case TYPE_MUL:
31118       case TYPE_DIV:
31119         fprintf (stderr, "priority was %#x (%d) before adjustment\n",
31120                  priority, priority);
31121         if (priority >= 0 && priority < 0x01000000)
31122           priority >>= 3;
31123         break;
31124       }
31125   }
31126 #endif
31127
31128   if (insn_must_be_first_in_group (insn)
31129       && reload_completed
31130       && current_sched_info->sched_max_insns_priority
31131       && rs6000_sched_restricted_insns_priority)
31132     {
31133
31134       /* Prioritize insns that can be dispatched only in the first
31135          dispatch slot.  */
31136       if (rs6000_sched_restricted_insns_priority == 1)
31137         /* Attach highest priority to insn. This means that in
31138            haifa-sched.c:ready_sort(), dispatch-slot restriction considerations
31139            precede 'priority' (critical path) considerations.  */
31140         return current_sched_info->sched_max_insns_priority;
31141       else if (rs6000_sched_restricted_insns_priority == 2)
31142         /* Increase priority of insn by a minimal amount. This means that in
31143            haifa-sched.c:ready_sort(), only 'priority' (critical path)
31144            considerations precede dispatch-slot restriction considerations.  */
31145         return (priority + 1);
31146     }
31147
31148   if (rs6000_tune == PROCESSOR_POWER6
31149       && ((load_store_pendulum == -2 && is_load_insn (insn, &load_mem))
31150           || (load_store_pendulum == 2 && is_store_insn (insn, &str_mem))))
31151     /* Attach highest priority to insn if the scheduler has just issued two
31152        stores and this instruction is a load, or two loads and this instruction
31153        is a store. Power6 wants loads and stores scheduled alternately
31154        when possible */
31155     return current_sched_info->sched_max_insns_priority;
31156
31157   return priority;
31158 }
31159
31160 /* Return true if the instruction is nonpipelined on the Cell. */
31161 static bool
31162 is_nonpipeline_insn (rtx_insn *insn)
31163 {
31164   enum attr_type type;
31165   if (!insn || !NONDEBUG_INSN_P (insn)
31166       || GET_CODE (PATTERN (insn)) == USE
31167       || GET_CODE (PATTERN (insn)) == CLOBBER)
31168     return false;
31169
31170   type = get_attr_type (insn);
31171   if (type == TYPE_MUL
31172       || type == TYPE_DIV
31173       || type == TYPE_SDIV
31174       || type == TYPE_DDIV
31175       || type == TYPE_SSQRT
31176       || type == TYPE_DSQRT
31177       || type == TYPE_MFCR
31178       || type == TYPE_MFCRF
31179       || type == TYPE_MFJMPR)
31180     {
31181       return true;
31182     }
31183   return false;
31184 }
31185
31186
31187 /* Return how many instructions the machine can issue per cycle.  */
31188
31189 static int
31190 rs6000_issue_rate (void)
31191 {
31192   /* Unless scheduling for register pressure, use issue rate of 1 for
31193      first scheduling pass to decrease degradation.  */
31194   if (!reload_completed && !flag_sched_pressure)
31195     return 1;
31196
31197   switch (rs6000_tune) {
31198   case PROCESSOR_RS64A:
31199   case PROCESSOR_PPC601: /* ? */
31200   case PROCESSOR_PPC7450:
31201     return 3;
31202   case PROCESSOR_PPC440:
31203   case PROCESSOR_PPC603:
31204   case PROCESSOR_PPC750:
31205   case PROCESSOR_PPC7400:
31206   case PROCESSOR_PPC8540:
31207   case PROCESSOR_PPC8548:
31208   case PROCESSOR_CELL:
31209   case PROCESSOR_PPCE300C2:
31210   case PROCESSOR_PPCE300C3:
31211   case PROCESSOR_PPCE500MC:
31212   case PROCESSOR_PPCE500MC64:
31213   case PROCESSOR_PPCE5500:
31214   case PROCESSOR_PPCE6500:
31215   case PROCESSOR_TITAN:
31216     return 2;
31217   case PROCESSOR_PPC476:
31218   case PROCESSOR_PPC604:
31219   case PROCESSOR_PPC604e:
31220   case PROCESSOR_PPC620:
31221   case PROCESSOR_PPC630:
31222     return 4;
31223   case PROCESSOR_POWER4:
31224   case PROCESSOR_POWER5:
31225   case PROCESSOR_POWER6:
31226   case PROCESSOR_POWER7:
31227     return 5;
31228   case PROCESSOR_POWER8:
31229     return 7;
31230   case PROCESSOR_POWER9:
31231     return 6;
31232   default:
31233     return 1;
31234   }
31235 }
31236
31237 /* Return how many instructions to look ahead for better insn
31238    scheduling.  */
31239
31240 static int
31241 rs6000_use_sched_lookahead (void)
31242 {
31243   switch (rs6000_tune)
31244     {
31245     case PROCESSOR_PPC8540:
31246     case PROCESSOR_PPC8548:
31247       return 4;
31248
31249     case PROCESSOR_CELL:
31250       return (reload_completed ? 8 : 0);
31251
31252     default:
31253       return 0;
31254     }
31255 }
31256
31257 /* We are choosing insn from the ready queue.  Return zero if INSN can be
31258    chosen.  */
31259 static int
31260 rs6000_use_sched_lookahead_guard (rtx_insn *insn, int ready_index)
31261 {
31262   if (ready_index == 0)
31263     return 0;
31264
31265   if (rs6000_tune != PROCESSOR_CELL)
31266     return 0;
31267
31268   gcc_assert (insn != NULL_RTX && INSN_P (insn));
31269
31270   if (!reload_completed
31271       || is_nonpipeline_insn (insn)
31272       || is_microcoded_insn (insn))
31273     return 1;
31274
31275   return 0;
31276 }
31277
31278 /* Determine if PAT refers to memory. If so, set MEM_REF to the MEM rtx
31279    and return true.  */
31280
31281 static bool
31282 find_mem_ref (rtx pat, rtx *mem_ref)
31283 {
31284   const char * fmt;
31285   int i, j;
31286
31287   /* stack_tie does not produce any real memory traffic.  */
31288   if (tie_operand (pat, VOIDmode))
31289     return false;
31290
31291   if (GET_CODE (pat) == MEM)
31292     {
31293       *mem_ref = pat;
31294       return true;
31295     }
31296
31297   /* Recursively process the pattern.  */
31298   fmt = GET_RTX_FORMAT (GET_CODE (pat));
31299
31300   for (i = GET_RTX_LENGTH (GET_CODE (pat)) - 1; i >= 0; i--)
31301     {
31302       if (fmt[i] == 'e')
31303         {
31304           if (find_mem_ref (XEXP (pat, i), mem_ref))
31305             return true;
31306         }
31307       else if (fmt[i] == 'E')
31308         for (j = XVECLEN (pat, i) - 1; j >= 0; j--)
31309           {
31310             if (find_mem_ref (XVECEXP (pat, i, j), mem_ref))
31311               return true;
31312           }
31313     }
31314
31315   return false;
31316 }
31317
31318 /* Determine if PAT is a PATTERN of a load insn.  */
31319
31320 static bool
31321 is_load_insn1 (rtx pat, rtx *load_mem)
31322 {
31323   if (!pat || pat == NULL_RTX)
31324     return false;
31325
31326   if (GET_CODE (pat) == SET)
31327     return find_mem_ref (SET_SRC (pat), load_mem);
31328
31329   if (GET_CODE (pat) == PARALLEL)
31330     {
31331       int i;
31332
31333       for (i = 0; i < XVECLEN (pat, 0); i++)
31334         if (is_load_insn1 (XVECEXP (pat, 0, i), load_mem))
31335           return true;
31336     }
31337
31338   return false;
31339 }
31340
31341 /* Determine if INSN loads from memory.  */
31342
31343 static bool
31344 is_load_insn (rtx insn, rtx *load_mem)
31345 {
31346   if (!insn || !INSN_P (insn))
31347     return false;
31348
31349   if (CALL_P (insn))
31350     return false;
31351
31352   return is_load_insn1 (PATTERN (insn), load_mem);
31353 }
31354
31355 /* Determine if PAT is a PATTERN of a store insn.  */
31356
31357 static bool
31358 is_store_insn1 (rtx pat, rtx *str_mem)
31359 {
31360   if (!pat || pat == NULL_RTX)
31361     return false;
31362
31363   if (GET_CODE (pat) == SET)
31364     return find_mem_ref (SET_DEST (pat), str_mem);
31365
31366   if (GET_CODE (pat) == PARALLEL)
31367     {
31368       int i;
31369
31370       for (i = 0; i < XVECLEN (pat, 0); i++)
31371         if (is_store_insn1 (XVECEXP (pat, 0, i), str_mem))
31372           return true;
31373     }
31374
31375   return false;
31376 }
31377
31378 /* Determine if INSN stores to memory.  */
31379
31380 static bool
31381 is_store_insn (rtx insn, rtx *str_mem)
31382 {
31383   if (!insn || !INSN_P (insn))
31384     return false;
31385
31386   return is_store_insn1 (PATTERN (insn), str_mem);
31387 }
31388
31389 /* Return whether TYPE is a Power9 pairable vector instruction type.  */
31390
31391 static bool
31392 is_power9_pairable_vec_type (enum attr_type type)
31393 {
31394   switch (type)
31395     {
31396       case TYPE_VECSIMPLE:
31397       case TYPE_VECCOMPLEX:
31398       case TYPE_VECDIV:
31399       case TYPE_VECCMP:
31400       case TYPE_VECPERM:
31401       case TYPE_VECFLOAT:
31402       case TYPE_VECFDIV:
31403       case TYPE_VECDOUBLE:
31404         return true;
31405       default:
31406         break;
31407     }
31408   return false;
31409 }
31410
31411 /* Returns whether the dependence between INSN and NEXT is considered
31412    costly by the given target.  */
31413
31414 static bool
31415 rs6000_is_costly_dependence (dep_t dep, int cost, int distance)
31416 {
31417   rtx insn;
31418   rtx next;
31419   rtx load_mem, str_mem;
31420
31421   /* If the flag is not enabled - no dependence is considered costly;
31422      allow all dependent insns in the same group.
31423      This is the most aggressive option.  */
31424   if (rs6000_sched_costly_dep == no_dep_costly)
31425     return false;
31426
31427   /* If the flag is set to 1 - a dependence is always considered costly;
31428      do not allow dependent instructions in the same group.
31429      This is the most conservative option.  */
31430   if (rs6000_sched_costly_dep == all_deps_costly)
31431     return true;
31432
31433   insn = DEP_PRO (dep);
31434   next = DEP_CON (dep);
31435
31436   if (rs6000_sched_costly_dep == store_to_load_dep_costly
31437       && is_load_insn (next, &load_mem)
31438       && is_store_insn (insn, &str_mem))
31439     /* Prevent load after store in the same group.  */
31440     return true;
31441
31442   if (rs6000_sched_costly_dep == true_store_to_load_dep_costly
31443       && is_load_insn (next, &load_mem)
31444       && is_store_insn (insn, &str_mem)
31445       && DEP_TYPE (dep) == REG_DEP_TRUE
31446       && mem_locations_overlap(str_mem, load_mem))
31447      /* Prevent load after store in the same group if it is a true
31448         dependence.  */
31449      return true;
31450
31451   /* The flag is set to X; dependences with latency >= X are considered costly,
31452      and will not be scheduled in the same group.  */
31453   if (rs6000_sched_costly_dep <= max_dep_latency
31454       && ((cost - distance) >= (int)rs6000_sched_costly_dep))
31455     return true;
31456
31457   return false;
31458 }
31459
31460 /* Return the next insn after INSN that is found before TAIL is reached,
31461    skipping any "non-active" insns - insns that will not actually occupy
31462    an issue slot.  Return NULL_RTX if such an insn is not found.  */
31463
31464 static rtx_insn *
31465 get_next_active_insn (rtx_insn *insn, rtx_insn *tail)
31466 {
31467   if (insn == NULL_RTX || insn == tail)
31468     return NULL;
31469
31470   while (1)
31471     {
31472       insn = NEXT_INSN (insn);
31473       if (insn == NULL_RTX || insn == tail)
31474         return NULL;
31475
31476       if (CALL_P (insn)
31477           || JUMP_P (insn) || JUMP_TABLE_DATA_P (insn)
31478           || (NONJUMP_INSN_P (insn)
31479               && GET_CODE (PATTERN (insn)) != USE
31480               && GET_CODE (PATTERN (insn)) != CLOBBER
31481               && INSN_CODE (insn) != CODE_FOR_stack_tie))
31482         break;
31483     }
31484   return insn;
31485 }
31486
31487 /* Do Power9 specific sched_reorder2 reordering of ready list.  */
31488
31489 static int
31490 power9_sched_reorder2 (rtx_insn **ready, int lastpos)
31491 {
31492   int pos;
31493   int i;
31494   rtx_insn *tmp;
31495   enum attr_type type, type2;
31496
31497   type = get_attr_type (last_scheduled_insn);
31498
31499   /* Try to issue fixed point divides back-to-back in pairs so they will be
31500      routed to separate execution units and execute in parallel.  */
31501   if (type == TYPE_DIV && divide_cnt == 0)
31502     {
31503       /* First divide has been scheduled.  */
31504       divide_cnt = 1;
31505
31506       /* Scan the ready list looking for another divide, if found move it
31507          to the end of the list so it is chosen next.  */
31508       pos = lastpos;
31509       while (pos >= 0)
31510         {
31511           if (recog_memoized (ready[pos]) >= 0
31512               && get_attr_type (ready[pos]) == TYPE_DIV)
31513             {
31514               tmp = ready[pos];
31515               for (i = pos; i < lastpos; i++)
31516                 ready[i] = ready[i + 1];
31517               ready[lastpos] = tmp;
31518               break;
31519             }
31520           pos--;
31521         }
31522     }
31523   else
31524     {
31525       /* Last insn was the 2nd divide or not a divide, reset the counter.  */
31526       divide_cnt = 0;
31527
31528       /* The best dispatch throughput for vector and vector load insns can be
31529          achieved by interleaving a vector and vector load such that they'll
31530          dispatch to the same superslice. If this pairing cannot be achieved
31531          then it is best to pair vector insns together and vector load insns
31532          together.
31533
31534          To aid in this pairing, vec_pairing maintains the current state with
31535          the following values:
31536
31537              0  : Initial state, no vecload/vector pairing has been started.
31538
31539              1  : A vecload or vector insn has been issued and a candidate for
31540                   pairing has been found and moved to the end of the ready
31541                   list.  */
31542       if (type == TYPE_VECLOAD)
31543         {
31544           /* Issued a vecload.  */
31545           if (vec_pairing == 0)
31546             {
31547               int vecload_pos = -1;
31548               /* We issued a single vecload, look for a vector insn to pair it
31549                  with.  If one isn't found, try to pair another vecload.  */
31550               pos = lastpos;
31551               while (pos >= 0)
31552                 {
31553                   if (recog_memoized (ready[pos]) >= 0)
31554                     {
31555                       type2 = get_attr_type (ready[pos]);
31556                       if (is_power9_pairable_vec_type (type2))
31557                         {
31558                           /* Found a vector insn to pair with, move it to the
31559                              end of the ready list so it is scheduled next.  */
31560                           tmp = ready[pos];
31561                           for (i = pos; i < lastpos; i++)
31562                             ready[i] = ready[i + 1];
31563                           ready[lastpos] = tmp;
31564                           vec_pairing = 1;
31565                           return cached_can_issue_more;
31566                         }
31567                       else if (type2 == TYPE_VECLOAD && vecload_pos == -1)
31568                         /* Remember position of first vecload seen.  */
31569                         vecload_pos = pos;
31570                     }
31571                   pos--;
31572                 }
31573               if (vecload_pos >= 0)
31574                 {
31575                   /* Didn't find a vector to pair with but did find a vecload,
31576                      move it to the end of the ready list.  */
31577                   tmp = ready[vecload_pos];
31578                   for (i = vecload_pos; i < lastpos; i++)
31579                     ready[i] = ready[i + 1];
31580                   ready[lastpos] = tmp;
31581                   vec_pairing = 1;
31582                   return cached_can_issue_more;
31583                 }
31584             }
31585         }
31586       else if (is_power9_pairable_vec_type (type))
31587         {
31588           /* Issued a vector operation.  */
31589           if (vec_pairing == 0)
31590             {
31591               int vec_pos = -1;
31592               /* We issued a single vector insn, look for a vecload to pair it
31593                  with.  If one isn't found, try to pair another vector.  */
31594               pos = lastpos;
31595               while (pos >= 0)
31596                 {
31597                   if (recog_memoized (ready[pos]) >= 0)
31598                     {
31599                       type2 = get_attr_type (ready[pos]);
31600                       if (type2 == TYPE_VECLOAD)
31601                         {
31602                           /* Found a vecload insn to pair with, move it to the
31603                              end of the ready list so it is scheduled next.  */
31604                           tmp = ready[pos];
31605                           for (i = pos; i < lastpos; i++)
31606                             ready[i] = ready[i + 1];
31607                           ready[lastpos] = tmp;
31608                           vec_pairing = 1;
31609                           return cached_can_issue_more;
31610                         }
31611                       else if (is_power9_pairable_vec_type (type2)
31612                                && vec_pos == -1)
31613                         /* Remember position of first vector insn seen.  */
31614                         vec_pos = pos;
31615                     }
31616                   pos--;
31617                 }
31618               if (vec_pos >= 0)
31619                 {
31620                   /* Didn't find a vecload to pair with but did find a vector
31621                      insn, move it to the end of the ready list.  */
31622                   tmp = ready[vec_pos];
31623                   for (i = vec_pos; i < lastpos; i++)
31624                     ready[i] = ready[i + 1];
31625                   ready[lastpos] = tmp;
31626                   vec_pairing = 1;
31627                   return cached_can_issue_more;
31628                 }
31629             }
31630         }
31631
31632       /* We've either finished a vec/vecload pair, couldn't find an insn to
31633          continue the current pair, or the last insn had nothing to do with
31634          with pairing.  In any case, reset the state.  */
31635       vec_pairing = 0;
31636     }
31637
31638   return cached_can_issue_more;
31639 }
31640
31641 /* We are about to begin issuing insns for this clock cycle. */
31642
31643 static int
31644 rs6000_sched_reorder (FILE *dump ATTRIBUTE_UNUSED, int sched_verbose,
31645                         rtx_insn **ready ATTRIBUTE_UNUSED,
31646                         int *pn_ready ATTRIBUTE_UNUSED,
31647                         int clock_var ATTRIBUTE_UNUSED)
31648 {
31649   int n_ready = *pn_ready;
31650
31651   if (sched_verbose)
31652     fprintf (dump, "// rs6000_sched_reorder :\n");
31653
31654   /* Reorder the ready list, if the second to last ready insn
31655      is a nonepipeline insn.  */
31656   if (rs6000_tune == PROCESSOR_CELL && n_ready > 1)
31657   {
31658     if (is_nonpipeline_insn (ready[n_ready - 1])
31659         && (recog_memoized (ready[n_ready - 2]) > 0))
31660       /* Simply swap first two insns.  */
31661       std::swap (ready[n_ready - 1], ready[n_ready - 2]);
31662   }
31663
31664   if (rs6000_tune == PROCESSOR_POWER6)
31665     load_store_pendulum = 0;
31666
31667   return rs6000_issue_rate ();
31668 }
31669
31670 /* Like rs6000_sched_reorder, but called after issuing each insn.  */
31671
31672 static int
31673 rs6000_sched_reorder2 (FILE *dump, int sched_verbose, rtx_insn **ready,
31674                          int *pn_ready, int clock_var ATTRIBUTE_UNUSED)
31675 {
31676   if (sched_verbose)
31677     fprintf (dump, "// rs6000_sched_reorder2 :\n");
31678
31679   /* For Power6, we need to handle some special cases to try and keep the
31680      store queue from overflowing and triggering expensive flushes.
31681
31682      This code monitors how load and store instructions are being issued
31683      and skews the ready list one way or the other to increase the likelihood
31684      that a desired instruction is issued at the proper time.
31685
31686      A couple of things are done.  First, we maintain a "load_store_pendulum"
31687      to track the current state of load/store issue.
31688
31689        - If the pendulum is at zero, then no loads or stores have been
31690          issued in the current cycle so we do nothing.
31691
31692        - If the pendulum is 1, then a single load has been issued in this
31693          cycle and we attempt to locate another load in the ready list to
31694          issue with it.
31695
31696        - If the pendulum is -2, then two stores have already been
31697          issued in this cycle, so we increase the priority of the first load
31698          in the ready list to increase it's likelihood of being chosen first
31699          in the next cycle.
31700
31701        - If the pendulum is -1, then a single store has been issued in this
31702          cycle and we attempt to locate another store in the ready list to
31703          issue with it, preferring a store to an adjacent memory location to
31704          facilitate store pairing in the store queue.
31705
31706        - If the pendulum is 2, then two loads have already been
31707          issued in this cycle, so we increase the priority of the first store
31708          in the ready list to increase it's likelihood of being chosen first
31709          in the next cycle.
31710
31711        - If the pendulum < -2 or > 2, then do nothing.
31712
31713        Note: This code covers the most common scenarios.  There exist non
31714              load/store instructions which make use of the LSU and which
31715              would need to be accounted for to strictly model the behavior
31716              of the machine.  Those instructions are currently unaccounted
31717              for to help minimize compile time overhead of this code.
31718    */
31719   if (rs6000_tune == PROCESSOR_POWER6 && last_scheduled_insn)
31720     {
31721       int pos;
31722       int i;
31723       rtx_insn *tmp;
31724       rtx load_mem, str_mem;
31725
31726       if (is_store_insn (last_scheduled_insn, &str_mem))
31727         /* Issuing a store, swing the load_store_pendulum to the left */
31728         load_store_pendulum--;
31729       else if (is_load_insn (last_scheduled_insn, &load_mem))
31730         /* Issuing a load, swing the load_store_pendulum to the right */
31731         load_store_pendulum++;
31732       else
31733         return cached_can_issue_more;
31734
31735       /* If the pendulum is balanced, or there is only one instruction on
31736          the ready list, then all is well, so return. */
31737       if ((load_store_pendulum == 0) || (*pn_ready <= 1))
31738         return cached_can_issue_more;
31739
31740       if (load_store_pendulum == 1)
31741         {
31742           /* A load has been issued in this cycle.  Scan the ready list
31743              for another load to issue with it */
31744           pos = *pn_ready-1;
31745
31746           while (pos >= 0)
31747             {
31748               if (is_load_insn (ready[pos], &load_mem))
31749                 {
31750                   /* Found a load.  Move it to the head of the ready list,
31751                      and adjust it's priority so that it is more likely to
31752                      stay there */
31753                   tmp = ready[pos];
31754                   for (i=pos; i<*pn_ready-1; i++)
31755                     ready[i] = ready[i + 1];
31756                   ready[*pn_ready-1] = tmp;
31757
31758                   if (!sel_sched_p () && INSN_PRIORITY_KNOWN (tmp))
31759                     INSN_PRIORITY (tmp)++;
31760                   break;
31761                 }
31762               pos--;
31763             }
31764         }
31765       else if (load_store_pendulum == -2)
31766         {
31767           /* Two stores have been issued in this cycle.  Increase the
31768              priority of the first load in the ready list to favor it for
31769              issuing in the next cycle. */
31770           pos = *pn_ready-1;
31771
31772           while (pos >= 0)
31773             {
31774               if (is_load_insn (ready[pos], &load_mem)
31775                   && !sel_sched_p ()
31776                   && INSN_PRIORITY_KNOWN (ready[pos]))
31777                 {
31778                   INSN_PRIORITY (ready[pos])++;
31779
31780                   /* Adjust the pendulum to account for the fact that a load
31781                      was found and increased in priority.  This is to prevent
31782                      increasing the priority of multiple loads */
31783                   load_store_pendulum--;
31784
31785                   break;
31786                 }
31787               pos--;
31788             }
31789         }
31790       else if (load_store_pendulum == -1)
31791         {
31792           /* A store has been issued in this cycle.  Scan the ready list for
31793              another store to issue with it, preferring a store to an adjacent
31794              memory location */
31795           int first_store_pos = -1;
31796
31797           pos = *pn_ready-1;
31798
31799           while (pos >= 0)
31800             {
31801               if (is_store_insn (ready[pos], &str_mem))
31802                 {
31803                   rtx str_mem2;
31804                   /* Maintain the index of the first store found on the
31805                      list */
31806                   if (first_store_pos == -1)
31807                     first_store_pos = pos;
31808
31809                   if (is_store_insn (last_scheduled_insn, &str_mem2)
31810                       && adjacent_mem_locations (str_mem, str_mem2))
31811                     {
31812                       /* Found an adjacent store.  Move it to the head of the
31813                          ready list, and adjust it's priority so that it is
31814                          more likely to stay there */
31815                       tmp = ready[pos];
31816                       for (i=pos; i<*pn_ready-1; i++)
31817                         ready[i] = ready[i + 1];
31818                       ready[*pn_ready-1] = tmp;
31819
31820                       if (!sel_sched_p () && INSN_PRIORITY_KNOWN (tmp))
31821                         INSN_PRIORITY (tmp)++;
31822
31823                       first_store_pos = -1;
31824
31825                       break;
31826                     };
31827                 }
31828               pos--;
31829             }
31830
31831           if (first_store_pos >= 0)
31832             {
31833               /* An adjacent store wasn't found, but a non-adjacent store was,
31834                  so move the non-adjacent store to the front of the ready
31835                  list, and adjust its priority so that it is more likely to
31836                  stay there. */
31837               tmp = ready[first_store_pos];
31838               for (i=first_store_pos; i<*pn_ready-1; i++)
31839                 ready[i] = ready[i + 1];
31840               ready[*pn_ready-1] = tmp;
31841               if (!sel_sched_p () && INSN_PRIORITY_KNOWN (tmp))
31842                 INSN_PRIORITY (tmp)++;
31843             }
31844         }
31845       else if (load_store_pendulum == 2)
31846        {
31847            /* Two loads have been issued in this cycle.  Increase the priority
31848               of the first store in the ready list to favor it for issuing in
31849               the next cycle. */
31850           pos = *pn_ready-1;
31851
31852           while (pos >= 0)
31853             {
31854               if (is_store_insn (ready[pos], &str_mem)
31855                   && !sel_sched_p ()
31856                   && INSN_PRIORITY_KNOWN (ready[pos]))
31857                 {
31858                   INSN_PRIORITY (ready[pos])++;
31859
31860                   /* Adjust the pendulum to account for the fact that a store
31861                      was found and increased in priority.  This is to prevent
31862                      increasing the priority of multiple stores */
31863                   load_store_pendulum++;
31864
31865                   break;
31866                 }
31867               pos--;
31868             }
31869         }
31870     }
31871
31872   /* Do Power9 dependent reordering if necessary.  */
31873   if (rs6000_tune == PROCESSOR_POWER9 && last_scheduled_insn
31874       && recog_memoized (last_scheduled_insn) >= 0)
31875     return power9_sched_reorder2 (ready, *pn_ready - 1);
31876
31877   return cached_can_issue_more;
31878 }
31879
31880 /* Return whether the presence of INSN causes a dispatch group termination
31881    of group WHICH_GROUP.
31882
31883    If WHICH_GROUP == current_group, this function will return true if INSN
31884    causes the termination of the current group (i.e, the dispatch group to
31885    which INSN belongs). This means that INSN will be the last insn in the
31886    group it belongs to.
31887
31888    If WHICH_GROUP == previous_group, this function will return true if INSN
31889    causes the termination of the previous group (i.e, the dispatch group that
31890    precedes the group to which INSN belongs).  This means that INSN will be
31891    the first insn in the group it belongs to).  */
31892
31893 static bool
31894 insn_terminates_group_p (rtx_insn *insn, enum group_termination which_group)
31895 {
31896   bool first, last;
31897
31898   if (! insn)
31899     return false;
31900
31901   first = insn_must_be_first_in_group (insn);
31902   last = insn_must_be_last_in_group (insn);
31903
31904   if (first && last)
31905     return true;
31906
31907   if (which_group == current_group)
31908     return last;
31909   else if (which_group == previous_group)
31910     return first;
31911
31912   return false;
31913 }
31914
31915
31916 static bool
31917 insn_must_be_first_in_group (rtx_insn *insn)
31918 {
31919   enum attr_type type;
31920
31921   if (!insn
31922       || NOTE_P (insn)
31923       || DEBUG_INSN_P (insn)
31924       || GET_CODE (PATTERN (insn)) == USE
31925       || GET_CODE (PATTERN (insn)) == CLOBBER)
31926     return false;
31927
31928   switch (rs6000_tune)
31929     {
31930     case PROCESSOR_POWER5:
31931       if (is_cracked_insn (insn))
31932         return true;
31933       /* FALLTHRU */
31934     case PROCESSOR_POWER4:
31935       if (is_microcoded_insn (insn))
31936         return true;
31937
31938       if (!rs6000_sched_groups)
31939         return false;
31940
31941       type = get_attr_type (insn);
31942
31943       switch (type)
31944         {
31945         case TYPE_MFCR:
31946         case TYPE_MFCRF:
31947         case TYPE_MTCR:
31948         case TYPE_CR_LOGICAL:
31949         case TYPE_MTJMPR:
31950         case TYPE_MFJMPR:
31951         case TYPE_DIV:
31952         case TYPE_LOAD_L:
31953         case TYPE_STORE_C:
31954         case TYPE_ISYNC:
31955         case TYPE_SYNC:
31956           return true;
31957         default:
31958           break;
31959         }
31960       break;
31961     case PROCESSOR_POWER6:
31962       type = get_attr_type (insn);
31963
31964       switch (type)
31965         {
31966         case TYPE_EXTS:
31967         case TYPE_CNTLZ:
31968         case TYPE_TRAP:
31969         case TYPE_MUL:
31970         case TYPE_INSERT:
31971         case TYPE_FPCOMPARE:
31972         case TYPE_MFCR:
31973         case TYPE_MTCR:
31974         case TYPE_MFJMPR:
31975         case TYPE_MTJMPR:
31976         case TYPE_ISYNC:
31977         case TYPE_SYNC:
31978         case TYPE_LOAD_L:
31979         case TYPE_STORE_C:
31980           return true;
31981         case TYPE_SHIFT:
31982           if (get_attr_dot (insn) == DOT_NO
31983               || get_attr_var_shift (insn) == VAR_SHIFT_NO)
31984             return true;
31985           else
31986             break;
31987         case TYPE_DIV:
31988           if (get_attr_size (insn) == SIZE_32)
31989             return true;
31990           else
31991             break;
31992         case TYPE_LOAD:
31993         case TYPE_STORE:
31994         case TYPE_FPLOAD:
31995         case TYPE_FPSTORE:
31996           if (get_attr_update (insn) == UPDATE_YES)
31997             return true;
31998           else
31999             break;
32000         default:
32001           break;
32002         }
32003       break;
32004     case PROCESSOR_POWER7:
32005       type = get_attr_type (insn);
32006
32007       switch (type)
32008         {
32009         case TYPE_CR_LOGICAL:
32010         case TYPE_MFCR:
32011         case TYPE_MFCRF:
32012         case TYPE_MTCR:
32013         case TYPE_DIV:
32014         case TYPE_ISYNC:
32015         case TYPE_LOAD_L:
32016         case TYPE_STORE_C:
32017         case TYPE_MFJMPR:
32018         case TYPE_MTJMPR:
32019           return true;
32020         case TYPE_MUL:
32021         case TYPE_SHIFT:
32022         case TYPE_EXTS:
32023           if (get_attr_dot (insn) == DOT_YES)
32024             return true;
32025           else
32026             break;
32027         case TYPE_LOAD:
32028           if (get_attr_sign_extend (insn) == SIGN_EXTEND_YES
32029               || get_attr_update (insn) == UPDATE_YES)
32030             return true;
32031           else
32032             break;
32033         case TYPE_STORE:
32034         case TYPE_FPLOAD:
32035         case TYPE_FPSTORE:
32036           if (get_attr_update (insn) == UPDATE_YES)
32037             return true;
32038           else
32039             break;
32040         default:
32041           break;
32042         }
32043       break;
32044     case PROCESSOR_POWER8:
32045       type = get_attr_type (insn);
32046
32047       switch (type)
32048         {
32049         case TYPE_CR_LOGICAL:
32050         case TYPE_MFCR:
32051         case TYPE_MFCRF:
32052         case TYPE_MTCR:
32053         case TYPE_SYNC:
32054         case TYPE_ISYNC:
32055         case TYPE_LOAD_L:
32056         case TYPE_STORE_C:
32057         case TYPE_VECSTORE:
32058         case TYPE_MFJMPR:
32059         case TYPE_MTJMPR:
32060           return true;
32061         case TYPE_SHIFT:
32062         case TYPE_EXTS:
32063         case TYPE_MUL:
32064           if (get_attr_dot (insn) == DOT_YES)
32065             return true;
32066           else
32067             break;
32068         case TYPE_LOAD:
32069           if (get_attr_sign_extend (insn) == SIGN_EXTEND_YES
32070               || get_attr_update (insn) == UPDATE_YES)
32071             return true;
32072           else
32073             break;
32074         case TYPE_STORE:
32075           if (get_attr_update (insn) == UPDATE_YES
32076               && get_attr_indexed (insn) == INDEXED_YES)
32077             return true;
32078           else
32079             break;
32080         default:
32081           break;
32082         }
32083       break;
32084     default:
32085       break;
32086     }
32087
32088   return false;
32089 }
32090
32091 static bool
32092 insn_must_be_last_in_group (rtx_insn *insn)
32093 {
32094   enum attr_type type;
32095
32096   if (!insn
32097       || NOTE_P (insn)
32098       || DEBUG_INSN_P (insn)
32099       || GET_CODE (PATTERN (insn)) == USE
32100       || GET_CODE (PATTERN (insn)) == CLOBBER)
32101     return false;
32102
32103   switch (rs6000_tune) {
32104   case PROCESSOR_POWER4:
32105   case PROCESSOR_POWER5:
32106     if (is_microcoded_insn (insn))
32107       return true;
32108
32109     if (is_branch_slot_insn (insn))
32110       return true;
32111
32112     break;
32113   case PROCESSOR_POWER6:
32114     type = get_attr_type (insn);
32115
32116     switch (type)
32117       {
32118       case TYPE_EXTS:
32119       case TYPE_CNTLZ:
32120       case TYPE_TRAP:
32121       case TYPE_MUL:
32122       case TYPE_FPCOMPARE:
32123       case TYPE_MFCR:
32124       case TYPE_MTCR:
32125       case TYPE_MFJMPR:
32126       case TYPE_MTJMPR:
32127       case TYPE_ISYNC:
32128       case TYPE_SYNC:
32129       case TYPE_LOAD_L:
32130       case TYPE_STORE_C:
32131         return true;
32132       case TYPE_SHIFT:
32133         if (get_attr_dot (insn) == DOT_NO
32134             || get_attr_var_shift (insn) == VAR_SHIFT_NO)
32135           return true;
32136         else
32137           break;
32138       case TYPE_DIV:
32139         if (get_attr_size (insn) == SIZE_32)
32140           return true;
32141         else
32142           break;
32143       default:
32144         break;
32145     }
32146     break;
32147   case PROCESSOR_POWER7:
32148     type = get_attr_type (insn);
32149
32150     switch (type)
32151       {
32152       case TYPE_ISYNC:
32153       case TYPE_SYNC:
32154       case TYPE_LOAD_L:
32155       case TYPE_STORE_C:
32156         return true;
32157       case TYPE_LOAD:
32158         if (get_attr_sign_extend (insn) == SIGN_EXTEND_YES
32159             && get_attr_update (insn) == UPDATE_YES)
32160           return true;
32161         else
32162           break;
32163       case TYPE_STORE:
32164         if (get_attr_update (insn) == UPDATE_YES
32165             && get_attr_indexed (insn) == INDEXED_YES)
32166           return true;
32167         else
32168           break;
32169       default:
32170         break;
32171     }
32172     break;
32173   case PROCESSOR_POWER8:
32174     type = get_attr_type (insn);
32175
32176     switch (type)
32177       {
32178       case TYPE_MFCR:
32179       case TYPE_MTCR:
32180       case TYPE_ISYNC:
32181       case TYPE_SYNC:
32182       case TYPE_LOAD_L:
32183       case TYPE_STORE_C:
32184         return true;
32185       case TYPE_LOAD:
32186         if (get_attr_sign_extend (insn) == SIGN_EXTEND_YES
32187             && get_attr_update (insn) == UPDATE_YES)
32188           return true;
32189         else
32190           break;
32191       case TYPE_STORE:
32192         if (get_attr_update (insn) == UPDATE_YES
32193             && get_attr_indexed (insn) == INDEXED_YES)
32194           return true;
32195         else
32196           break;
32197       default:
32198         break;
32199     }
32200     break;
32201   default:
32202     break;
32203   }
32204
32205   return false;
32206 }
32207
32208 /* Return true if it is recommended to keep NEXT_INSN "far" (in a separate
32209    dispatch group) from the insns in GROUP_INSNS.  Return false otherwise.  */
32210
32211 static bool
32212 is_costly_group (rtx *group_insns, rtx next_insn)
32213 {
32214   int i;
32215   int issue_rate = rs6000_issue_rate ();
32216
32217   for (i = 0; i < issue_rate; i++)
32218     {
32219       sd_iterator_def sd_it;
32220       dep_t dep;
32221       rtx insn = group_insns[i];
32222
32223       if (!insn)
32224         continue;
32225
32226       FOR_EACH_DEP (insn, SD_LIST_RES_FORW, sd_it, dep)
32227         {
32228           rtx next = DEP_CON (dep);
32229
32230           if (next == next_insn
32231               && rs6000_is_costly_dependence (dep, dep_cost (dep), 0))
32232             return true;
32233         }
32234     }
32235
32236   return false;
32237 }
32238
32239 /* Utility of the function redefine_groups.
32240    Check if it is too costly to schedule NEXT_INSN together with GROUP_INSNS
32241    in the same dispatch group.  If so, insert nops before NEXT_INSN, in order
32242    to keep it "far" (in a separate group) from GROUP_INSNS, following
32243    one of the following schemes, depending on the value of the flag
32244    -minsert_sched_nops = X:
32245    (1) X == sched_finish_regroup_exact: insert exactly as many nops as needed
32246        in order to force NEXT_INSN into a separate group.
32247    (2) X < sched_finish_regroup_exact: insert exactly X nops.
32248    GROUP_END, CAN_ISSUE_MORE and GROUP_COUNT record the state after nop
32249    insertion (has a group just ended, how many vacant issue slots remain in the
32250    last group, and how many dispatch groups were encountered so far).  */
32251
32252 static int
32253 force_new_group (int sched_verbose, FILE *dump, rtx *group_insns,
32254                  rtx_insn *next_insn, bool *group_end, int can_issue_more,
32255                  int *group_count)
32256 {
32257   rtx nop;
32258   bool force;
32259   int issue_rate = rs6000_issue_rate ();
32260   bool end = *group_end;
32261   int i;
32262
32263   if (next_insn == NULL_RTX || DEBUG_INSN_P (next_insn))
32264     return can_issue_more;
32265
32266   if (rs6000_sched_insert_nops > sched_finish_regroup_exact)
32267     return can_issue_more;
32268
32269   force = is_costly_group (group_insns, next_insn);
32270   if (!force)
32271     return can_issue_more;
32272
32273   if (sched_verbose > 6)
32274     fprintf (dump,"force: group count = %d, can_issue_more = %d\n",
32275              *group_count ,can_issue_more);
32276
32277   if (rs6000_sched_insert_nops == sched_finish_regroup_exact)
32278     {
32279       if (*group_end)
32280         can_issue_more = 0;
32281
32282       /* Since only a branch can be issued in the last issue_slot, it is
32283          sufficient to insert 'can_issue_more - 1' nops if next_insn is not
32284          a branch. If next_insn is a branch, we insert 'can_issue_more' nops;
32285          in this case the last nop will start a new group and the branch
32286          will be forced to the new group.  */
32287       if (can_issue_more && !is_branch_slot_insn (next_insn))
32288         can_issue_more--;
32289
32290       /* Do we have a special group ending nop? */
32291       if (rs6000_tune == PROCESSOR_POWER6 || rs6000_tune == PROCESSOR_POWER7
32292           || rs6000_tune == PROCESSOR_POWER8)
32293         {
32294           nop = gen_group_ending_nop ();
32295           emit_insn_before (nop, next_insn);
32296           can_issue_more = 0;
32297         }
32298       else
32299         while (can_issue_more > 0)
32300           {
32301             nop = gen_nop ();
32302             emit_insn_before (nop, next_insn);
32303             can_issue_more--;
32304           }
32305
32306       *group_end = true;
32307       return 0;
32308     }
32309
32310   if (rs6000_sched_insert_nops < sched_finish_regroup_exact)
32311     {
32312       int n_nops = rs6000_sched_insert_nops;
32313
32314       /* Nops can't be issued from the branch slot, so the effective
32315          issue_rate for nops is 'issue_rate - 1'.  */
32316       if (can_issue_more == 0)
32317         can_issue_more = issue_rate;
32318       can_issue_more--;
32319       if (can_issue_more == 0)
32320         {
32321           can_issue_more = issue_rate - 1;
32322           (*group_count)++;
32323           end = true;
32324           for (i = 0; i < issue_rate; i++)
32325             {
32326               group_insns[i] = 0;
32327             }
32328         }
32329
32330       while (n_nops > 0)
32331         {
32332           nop = gen_nop ();
32333           emit_insn_before (nop, next_insn);
32334           if (can_issue_more == issue_rate - 1) /* new group begins */
32335             end = false;
32336           can_issue_more--;
32337           if (can_issue_more == 0)
32338             {
32339               can_issue_more = issue_rate - 1;
32340               (*group_count)++;
32341               end = true;
32342               for (i = 0; i < issue_rate; i++)
32343                 {
32344                   group_insns[i] = 0;
32345                 }
32346             }
32347           n_nops--;
32348         }
32349
32350       /* Scale back relative to 'issue_rate' (instead of 'issue_rate - 1').  */
32351       can_issue_more++;
32352
32353       /* Is next_insn going to start a new group?  */
32354       *group_end
32355         = (end
32356            || (can_issue_more == 1 && !is_branch_slot_insn (next_insn))
32357            || (can_issue_more <= 2 && is_cracked_insn (next_insn))
32358            || (can_issue_more < issue_rate &&
32359                insn_terminates_group_p (next_insn, previous_group)));
32360       if (*group_end && end)
32361         (*group_count)--;
32362
32363       if (sched_verbose > 6)
32364         fprintf (dump, "done force: group count = %d, can_issue_more = %d\n",
32365                  *group_count, can_issue_more);
32366       return can_issue_more;
32367     }
32368
32369   return can_issue_more;
32370 }
32371
32372 /* This function tries to synch the dispatch groups that the compiler "sees"
32373    with the dispatch groups that the processor dispatcher is expected to
32374    form in practice.  It tries to achieve this synchronization by forcing the
32375    estimated processor grouping on the compiler (as opposed to the function
32376    'pad_goups' which tries to force the scheduler's grouping on the processor).
32377
32378    The function scans the insn sequence between PREV_HEAD_INSN and TAIL and
32379    examines the (estimated) dispatch groups that will be formed by the processor
32380    dispatcher.  It marks these group boundaries to reflect the estimated
32381    processor grouping, overriding the grouping that the scheduler had marked.
32382    Depending on the value of the flag '-minsert-sched-nops' this function can
32383    force certain insns into separate groups or force a certain distance between
32384    them by inserting nops, for example, if there exists a "costly dependence"
32385    between the insns.
32386
32387    The function estimates the group boundaries that the processor will form as
32388    follows:  It keeps track of how many vacant issue slots are available after
32389    each insn.  A subsequent insn will start a new group if one of the following
32390    4 cases applies:
32391    - no more vacant issue slots remain in the current dispatch group.
32392    - only the last issue slot, which is the branch slot, is vacant, but the next
32393      insn is not a branch.
32394    - only the last 2 or less issue slots, including the branch slot, are vacant,
32395      which means that a cracked insn (which occupies two issue slots) can't be
32396      issued in this group.
32397    - less than 'issue_rate' slots are vacant, and the next insn always needs to
32398      start a new group.  */
32399
32400 static int
32401 redefine_groups (FILE *dump, int sched_verbose, rtx_insn *prev_head_insn,
32402                  rtx_insn *tail)
32403 {
32404   rtx_insn *insn, *next_insn;
32405   int issue_rate;
32406   int can_issue_more;
32407   int slot, i;
32408   bool group_end;
32409   int group_count = 0;
32410   rtx *group_insns;
32411
32412   /* Initialize.  */
32413   issue_rate = rs6000_issue_rate ();
32414   group_insns = XALLOCAVEC (rtx, issue_rate);
32415   for (i = 0; i < issue_rate; i++)
32416     {
32417       group_insns[i] = 0;
32418     }
32419   can_issue_more = issue_rate;
32420   slot = 0;
32421   insn = get_next_active_insn (prev_head_insn, tail);
32422   group_end = false;
32423
32424   while (insn != NULL_RTX)
32425     {
32426       slot = (issue_rate - can_issue_more);
32427       group_insns[slot] = insn;
32428       can_issue_more =
32429         rs6000_variable_issue (dump, sched_verbose, insn, can_issue_more);
32430       if (insn_terminates_group_p (insn, current_group))
32431         can_issue_more = 0;
32432
32433       next_insn = get_next_active_insn (insn, tail);
32434       if (next_insn == NULL_RTX)
32435         return group_count + 1;
32436
32437       /* Is next_insn going to start a new group?  */
32438       group_end
32439         = (can_issue_more == 0
32440            || (can_issue_more == 1 && !is_branch_slot_insn (next_insn))
32441            || (can_issue_more <= 2 && is_cracked_insn (next_insn))
32442            || (can_issue_more < issue_rate &&
32443                insn_terminates_group_p (next_insn, previous_group)));
32444
32445       can_issue_more = force_new_group (sched_verbose, dump, group_insns,
32446                                         next_insn, &group_end, can_issue_more,
32447                                         &group_count);
32448
32449       if (group_end)
32450         {
32451           group_count++;
32452           can_issue_more = 0;
32453           for (i = 0; i < issue_rate; i++)
32454             {
32455               group_insns[i] = 0;
32456             }
32457         }
32458
32459       if (GET_MODE (next_insn) == TImode && can_issue_more)
32460         PUT_MODE (next_insn, VOIDmode);
32461       else if (!can_issue_more && GET_MODE (next_insn) != TImode)
32462         PUT_MODE (next_insn, TImode);
32463
32464       insn = next_insn;
32465       if (can_issue_more == 0)
32466         can_issue_more = issue_rate;
32467     } /* while */
32468
32469   return group_count;
32470 }
32471
32472 /* Scan the insn sequence between PREV_HEAD_INSN and TAIL and examine the
32473    dispatch group boundaries that the scheduler had marked.  Pad with nops
32474    any dispatch groups which have vacant issue slots, in order to force the
32475    scheduler's grouping on the processor dispatcher.  The function
32476    returns the number of dispatch groups found.  */
32477
32478 static int
32479 pad_groups (FILE *dump, int sched_verbose, rtx_insn *prev_head_insn,
32480             rtx_insn *tail)
32481 {
32482   rtx_insn *insn, *next_insn;
32483   rtx nop;
32484   int issue_rate;
32485   int can_issue_more;
32486   int group_end;
32487   int group_count = 0;
32488
32489   /* Initialize issue_rate.  */
32490   issue_rate = rs6000_issue_rate ();
32491   can_issue_more = issue_rate;
32492
32493   insn = get_next_active_insn (prev_head_insn, tail);
32494   next_insn = get_next_active_insn (insn, tail);
32495
32496   while (insn != NULL_RTX)
32497     {
32498       can_issue_more =
32499         rs6000_variable_issue (dump, sched_verbose, insn, can_issue_more);
32500
32501       group_end = (next_insn == NULL_RTX || GET_MODE (next_insn) == TImode);
32502
32503       if (next_insn == NULL_RTX)
32504         break;
32505
32506       if (group_end)
32507         {
32508           /* If the scheduler had marked group termination at this location
32509              (between insn and next_insn), and neither insn nor next_insn will
32510              force group termination, pad the group with nops to force group
32511              termination.  */
32512           if (can_issue_more
32513               && (rs6000_sched_insert_nops == sched_finish_pad_groups)
32514               && !insn_terminates_group_p (insn, current_group)
32515               && !insn_terminates_group_p (next_insn, previous_group))
32516             {
32517               if (!is_branch_slot_insn (next_insn))
32518                 can_issue_more--;
32519
32520               while (can_issue_more)
32521                 {
32522                   nop = gen_nop ();
32523                   emit_insn_before (nop, next_insn);
32524                   can_issue_more--;
32525                 }
32526             }
32527
32528           can_issue_more = issue_rate;
32529           group_count++;
32530         }
32531
32532       insn = next_insn;
32533       next_insn = get_next_active_insn (insn, tail);
32534     }
32535
32536   return group_count;
32537 }
32538
32539 /* We're beginning a new block.  Initialize data structures as necessary.  */
32540
32541 static void
32542 rs6000_sched_init (FILE *dump ATTRIBUTE_UNUSED,
32543                      int sched_verbose ATTRIBUTE_UNUSED,
32544                      int max_ready ATTRIBUTE_UNUSED)
32545 {
32546   last_scheduled_insn = NULL;
32547   load_store_pendulum = 0;
32548   divide_cnt = 0;
32549   vec_pairing = 0;
32550 }
32551
32552 /* The following function is called at the end of scheduling BB.
32553    After reload, it inserts nops at insn group bundling.  */
32554
32555 static void
32556 rs6000_sched_finish (FILE *dump, int sched_verbose)
32557 {
32558   int n_groups;
32559
32560   if (sched_verbose)
32561     fprintf (dump, "=== Finishing schedule.\n");
32562
32563   if (reload_completed && rs6000_sched_groups)
32564     {
32565       /* Do not run sched_finish hook when selective scheduling enabled.  */
32566       if (sel_sched_p ())
32567         return;
32568
32569       if (rs6000_sched_insert_nops == sched_finish_none)
32570         return;
32571
32572       if (rs6000_sched_insert_nops == sched_finish_pad_groups)
32573         n_groups = pad_groups (dump, sched_verbose,
32574                                current_sched_info->prev_head,
32575                                current_sched_info->next_tail);
32576       else
32577         n_groups = redefine_groups (dump, sched_verbose,
32578                                     current_sched_info->prev_head,
32579                                     current_sched_info->next_tail);
32580
32581       if (sched_verbose >= 6)
32582         {
32583           fprintf (dump, "ngroups = %d\n", n_groups);
32584           print_rtl (dump, current_sched_info->prev_head);
32585           fprintf (dump, "Done finish_sched\n");
32586         }
32587     }
32588 }
32589
32590 struct rs6000_sched_context
32591 {
32592   short cached_can_issue_more;
32593   rtx_insn *last_scheduled_insn;
32594   int load_store_pendulum;
32595   int divide_cnt;
32596   int vec_pairing;
32597 };
32598
32599 typedef struct rs6000_sched_context rs6000_sched_context_def;
32600 typedef rs6000_sched_context_def *rs6000_sched_context_t;
32601
32602 /* Allocate store for new scheduling context.  */
32603 static void *
32604 rs6000_alloc_sched_context (void)
32605 {
32606   return xmalloc (sizeof (rs6000_sched_context_def));
32607 }
32608
32609 /* If CLEAN_P is true then initializes _SC with clean data,
32610    and from the global context otherwise.  */
32611 static void
32612 rs6000_init_sched_context (void *_sc, bool clean_p)
32613 {
32614   rs6000_sched_context_t sc = (rs6000_sched_context_t) _sc;
32615
32616   if (clean_p)
32617     {
32618       sc->cached_can_issue_more = 0;
32619       sc->last_scheduled_insn = NULL;
32620       sc->load_store_pendulum = 0;
32621       sc->divide_cnt = 0;
32622       sc->vec_pairing = 0;
32623     }
32624   else
32625     {
32626       sc->cached_can_issue_more = cached_can_issue_more;
32627       sc->last_scheduled_insn = last_scheduled_insn;
32628       sc->load_store_pendulum = load_store_pendulum;
32629       sc->divide_cnt = divide_cnt;
32630       sc->vec_pairing = vec_pairing;
32631     }
32632 }
32633
32634 /* Sets the global scheduling context to the one pointed to by _SC.  */
32635 static void
32636 rs6000_set_sched_context (void *_sc)
32637 {
32638   rs6000_sched_context_t sc = (rs6000_sched_context_t) _sc;
32639
32640   gcc_assert (sc != NULL);
32641
32642   cached_can_issue_more = sc->cached_can_issue_more;
32643   last_scheduled_insn = sc->last_scheduled_insn;
32644   load_store_pendulum = sc->load_store_pendulum;
32645   divide_cnt = sc->divide_cnt;
32646   vec_pairing = sc->vec_pairing;
32647 }
32648
32649 /* Free _SC.  */
32650 static void
32651 rs6000_free_sched_context (void *_sc)
32652 {
32653   gcc_assert (_sc != NULL);
32654
32655   free (_sc);
32656 }
32657
32658 static bool
32659 rs6000_sched_can_speculate_insn (rtx_insn *insn)
32660 {
32661   switch (get_attr_type (insn))
32662     {
32663     case TYPE_DIV:
32664     case TYPE_SDIV:
32665     case TYPE_DDIV:
32666     case TYPE_VECDIV:
32667     case TYPE_SSQRT:
32668     case TYPE_DSQRT:
32669       return false;
32670
32671     default:
32672       return true;
32673   }
32674 }
32675 \f
32676 /* Length in units of the trampoline for entering a nested function.  */
32677
32678 int
32679 rs6000_trampoline_size (void)
32680 {
32681   int ret = 0;
32682
32683   switch (DEFAULT_ABI)
32684     {
32685     default:
32686       gcc_unreachable ();
32687
32688     case ABI_AIX:
32689       ret = (TARGET_32BIT) ? 12 : 24;
32690       break;
32691
32692     case ABI_ELFv2:
32693       gcc_assert (!TARGET_32BIT);
32694       ret = 32;
32695       break;
32696
32697     case ABI_DARWIN:
32698     case ABI_V4:
32699       ret = (TARGET_32BIT) ? 40 : 48;
32700       break;
32701     }
32702
32703   return ret;
32704 }
32705
32706 /* Emit RTL insns to initialize the variable parts of a trampoline.
32707    FNADDR is an RTX for the address of the function's pure code.
32708    CXT is an RTX for the static chain value for the function.  */
32709
32710 static void
32711 rs6000_trampoline_init (rtx m_tramp, tree fndecl, rtx cxt)
32712 {
32713   int regsize = (TARGET_32BIT) ? 4 : 8;
32714   rtx fnaddr = XEXP (DECL_RTL (fndecl), 0);
32715   rtx ctx_reg = force_reg (Pmode, cxt);
32716   rtx addr = force_reg (Pmode, XEXP (m_tramp, 0));
32717
32718   switch (DEFAULT_ABI)
32719     {
32720     default:
32721       gcc_unreachable ();
32722
32723     /* Under AIX, just build the 3 word function descriptor */
32724     case ABI_AIX:
32725       {
32726         rtx fnmem, fn_reg, toc_reg;
32727
32728         if (!TARGET_POINTERS_TO_NESTED_FUNCTIONS)
32729           error ("you cannot take the address of a nested function if you use "
32730                  "the %qs option", "-mno-pointers-to-nested-functions");
32731
32732         fnmem = gen_const_mem (Pmode, force_reg (Pmode, fnaddr));
32733         fn_reg = gen_reg_rtx (Pmode);
32734         toc_reg = gen_reg_rtx (Pmode);
32735
32736   /* Macro to shorten the code expansions below.  */
32737 # define MEM_PLUS(MEM, OFFSET) adjust_address (MEM, Pmode, OFFSET)
32738
32739         m_tramp = replace_equiv_address (m_tramp, addr);
32740
32741         emit_move_insn (fn_reg, MEM_PLUS (fnmem, 0));
32742         emit_move_insn (toc_reg, MEM_PLUS (fnmem, regsize));
32743         emit_move_insn (MEM_PLUS (m_tramp, 0), fn_reg);
32744         emit_move_insn (MEM_PLUS (m_tramp, regsize), toc_reg);
32745         emit_move_insn (MEM_PLUS (m_tramp, 2*regsize), ctx_reg);
32746
32747 # undef MEM_PLUS
32748       }
32749       break;
32750
32751     /* Under V.4/eabi/darwin, __trampoline_setup does the real work.  */
32752     case ABI_ELFv2:
32753     case ABI_DARWIN:
32754     case ABI_V4:
32755       emit_library_call (gen_rtx_SYMBOL_REF (Pmode, "__trampoline_setup"),
32756                          LCT_NORMAL, VOIDmode,
32757                          addr, Pmode,
32758                          GEN_INT (rs6000_trampoline_size ()), SImode,
32759                          fnaddr, Pmode,
32760                          ctx_reg, Pmode);
32761       break;
32762     }
32763 }
32764
32765 \f
32766 /* Returns TRUE iff the target attribute indicated by ATTR_ID takes a plain
32767    identifier as an argument, so the front end shouldn't look it up.  */
32768
32769 static bool
32770 rs6000_attribute_takes_identifier_p (const_tree attr_id)
32771 {
32772   return is_attribute_p ("altivec", attr_id);
32773 }
32774
32775 /* Handle the "altivec" attribute.  The attribute may have
32776    arguments as follows:
32777
32778         __attribute__((altivec(vector__)))
32779         __attribute__((altivec(pixel__)))       (always followed by 'unsigned short')
32780         __attribute__((altivec(bool__)))        (always followed by 'unsigned')
32781
32782   and may appear more than once (e.g., 'vector bool char') in a
32783   given declaration.  */
32784
32785 static tree
32786 rs6000_handle_altivec_attribute (tree *node,
32787                                  tree name ATTRIBUTE_UNUSED,
32788                                  tree args,
32789                                  int flags ATTRIBUTE_UNUSED,
32790                                  bool *no_add_attrs)
32791 {
32792   tree type = *node, result = NULL_TREE;
32793   machine_mode mode;
32794   int unsigned_p;
32795   char altivec_type
32796     = ((args && TREE_CODE (args) == TREE_LIST && TREE_VALUE (args)
32797         && TREE_CODE (TREE_VALUE (args)) == IDENTIFIER_NODE)
32798        ? *IDENTIFIER_POINTER (TREE_VALUE (args))
32799        : '?');
32800
32801   while (POINTER_TYPE_P (type)
32802          || TREE_CODE (type) == FUNCTION_TYPE
32803          || TREE_CODE (type) == METHOD_TYPE
32804          || TREE_CODE (type) == ARRAY_TYPE)
32805     type = TREE_TYPE (type);
32806
32807   mode = TYPE_MODE (type);
32808
32809   /* Check for invalid AltiVec type qualifiers.  */
32810   if (type == long_double_type_node)
32811     error ("use of %<long double%> in AltiVec types is invalid");
32812   else if (type == boolean_type_node)
32813     error ("use of boolean types in AltiVec types is invalid");
32814   else if (TREE_CODE (type) == COMPLEX_TYPE)
32815     error ("use of %<complex%> in AltiVec types is invalid");
32816   else if (DECIMAL_FLOAT_MODE_P (mode))
32817     error ("use of decimal floating point types in AltiVec types is invalid");
32818   else if (!TARGET_VSX)
32819     {
32820       if (type == long_unsigned_type_node || type == long_integer_type_node)
32821         {
32822           if (TARGET_64BIT)
32823             error ("use of %<long%> in AltiVec types is invalid for "
32824                    "64-bit code without %qs", "-mvsx");
32825           else if (rs6000_warn_altivec_long)
32826             warning (0, "use of %<long%> in AltiVec types is deprecated; "
32827                      "use %<int%>");
32828         }
32829       else if (type == long_long_unsigned_type_node
32830                || type == long_long_integer_type_node)
32831         error ("use of %<long long%> in AltiVec types is invalid without %qs",
32832                "-mvsx");
32833       else if (type == double_type_node)
32834         error ("use of %<double%> in AltiVec types is invalid without %qs",
32835                "-mvsx");
32836     }
32837
32838   switch (altivec_type)
32839     {
32840     case 'v':
32841       unsigned_p = TYPE_UNSIGNED (type);
32842       switch (mode)
32843         {
32844         case E_TImode:
32845           result = (unsigned_p ? unsigned_V1TI_type_node : V1TI_type_node);
32846           break;
32847         case E_DImode:
32848           result = (unsigned_p ? unsigned_V2DI_type_node : V2DI_type_node);
32849           break;
32850         case E_SImode:
32851           result = (unsigned_p ? unsigned_V4SI_type_node : V4SI_type_node);
32852           break;
32853         case E_HImode:
32854           result = (unsigned_p ? unsigned_V8HI_type_node : V8HI_type_node);
32855           break;
32856         case E_QImode:
32857           result = (unsigned_p ? unsigned_V16QI_type_node : V16QI_type_node);
32858           break;
32859         case E_SFmode: result = V4SF_type_node; break;
32860         case E_DFmode: result = V2DF_type_node; break;
32861           /* If the user says 'vector int bool', we may be handed the 'bool'
32862              attribute _before_ the 'vector' attribute, and so select the
32863              proper type in the 'b' case below.  */
32864         case E_V4SImode: case E_V8HImode: case E_V16QImode: case E_V4SFmode:
32865         case E_V2DImode: case E_V2DFmode:
32866           result = type;
32867         default: break;
32868         }
32869       break;
32870     case 'b':
32871       switch (mode)
32872         {
32873         case E_DImode: case E_V2DImode: result = bool_V2DI_type_node; break;
32874         case E_SImode: case E_V4SImode: result = bool_V4SI_type_node; break;
32875         case E_HImode: case E_V8HImode: result = bool_V8HI_type_node; break;
32876         case E_QImode: case E_V16QImode: result = bool_V16QI_type_node;
32877         default: break;
32878         }
32879       break;
32880     case 'p':
32881       switch (mode)
32882         {
32883         case E_V8HImode: result = pixel_V8HI_type_node;
32884         default: break;
32885         }
32886     default: break;
32887     }
32888
32889   /* Propagate qualifiers attached to the element type
32890      onto the vector type.  */
32891   if (result && result != type && TYPE_QUALS (type))
32892     result = build_qualified_type (result, TYPE_QUALS (type));
32893
32894   *no_add_attrs = true;  /* No need to hang on to the attribute.  */
32895
32896   if (result)
32897     *node = lang_hooks.types.reconstruct_complex_type (*node, result);
32898
32899   return NULL_TREE;
32900 }
32901
32902 /* AltiVec defines four built-in scalar types that serve as vector
32903    elements; we must teach the compiler how to mangle them.  */
32904
32905 static const char *
32906 rs6000_mangle_type (const_tree type)
32907 {
32908   type = TYPE_MAIN_VARIANT (type);
32909
32910   if (TREE_CODE (type) != VOID_TYPE && TREE_CODE (type) != BOOLEAN_TYPE
32911       && TREE_CODE (type) != INTEGER_TYPE && TREE_CODE (type) != REAL_TYPE)
32912     return NULL;
32913
32914   if (type == bool_char_type_node) return "U6__boolc";
32915   if (type == bool_short_type_node) return "U6__bools";
32916   if (type == pixel_type_node) return "u7__pixel";
32917   if (type == bool_int_type_node) return "U6__booli";
32918   if (type == bool_long_type_node) return "U6__booll";
32919
32920   /* Use a unique name for __float128 rather than trying to use "e" or "g". Use
32921      "g" for IBM extended double, no matter whether it is long double (using
32922      -mabi=ibmlongdouble) or the distinct __ibm128 type.  */
32923   if (TARGET_FLOAT128_TYPE)
32924     {
32925       if (type == ieee128_float_type_node)
32926         return "U10__float128";
32927
32928       if (TARGET_LONG_DOUBLE_128)
32929         {
32930           if (type == long_double_type_node)
32931             return (TARGET_IEEEQUAD) ? "U10__float128" : "g";
32932
32933           if (type == ibm128_float_type_node)
32934             return "g";
32935         }
32936     }
32937
32938   /* Mangle IBM extended float long double as `g' (__float128) on
32939      powerpc*-linux where long-double-64 previously was the default.  */
32940   if (TYPE_MAIN_VARIANT (type) == long_double_type_node
32941       && TARGET_ELF
32942       && TARGET_LONG_DOUBLE_128
32943       && !TARGET_IEEEQUAD)
32944     return "g";
32945
32946   /* For all other types, use normal C++ mangling.  */
32947   return NULL;
32948 }
32949
32950 /* Handle a "longcall" or "shortcall" attribute; arguments as in
32951    struct attribute_spec.handler.  */
32952
32953 static tree
32954 rs6000_handle_longcall_attribute (tree *node, tree name,
32955                                   tree args ATTRIBUTE_UNUSED,
32956                                   int flags ATTRIBUTE_UNUSED,
32957                                   bool *no_add_attrs)
32958 {
32959   if (TREE_CODE (*node) != FUNCTION_TYPE
32960       && TREE_CODE (*node) != FIELD_DECL
32961       && TREE_CODE (*node) != TYPE_DECL)
32962     {
32963       warning (OPT_Wattributes, "%qE attribute only applies to functions",
32964                name);
32965       *no_add_attrs = true;
32966     }
32967
32968   return NULL_TREE;
32969 }
32970
32971 /* Set longcall attributes on all functions declared when
32972    rs6000_default_long_calls is true.  */
32973 static void
32974 rs6000_set_default_type_attributes (tree type)
32975 {
32976   if (rs6000_default_long_calls
32977       && (TREE_CODE (type) == FUNCTION_TYPE
32978           || TREE_CODE (type) == METHOD_TYPE))
32979     TYPE_ATTRIBUTES (type) = tree_cons (get_identifier ("longcall"),
32980                                         NULL_TREE,
32981                                         TYPE_ATTRIBUTES (type));
32982
32983 #if TARGET_MACHO
32984   darwin_set_default_type_attributes (type);
32985 #endif
32986 }
32987
32988 /* Return a reference suitable for calling a function with the
32989    longcall attribute.  */
32990
32991 rtx
32992 rs6000_longcall_ref (rtx call_ref)
32993 {
32994   const char *call_name;
32995   tree node;
32996
32997   if (GET_CODE (call_ref) != SYMBOL_REF)
32998     return call_ref;
32999
33000   /* System V adds '.' to the internal name, so skip them.  */
33001   call_name = XSTR (call_ref, 0);
33002   if (*call_name == '.')
33003     {
33004       while (*call_name == '.')
33005         call_name++;
33006
33007       node = get_identifier (call_name);
33008       call_ref = gen_rtx_SYMBOL_REF (VOIDmode, IDENTIFIER_POINTER (node));
33009     }
33010
33011   return force_reg (Pmode, call_ref);
33012 }
33013 \f
33014 #ifndef TARGET_USE_MS_BITFIELD_LAYOUT
33015 #define TARGET_USE_MS_BITFIELD_LAYOUT 0
33016 #endif
33017
33018 /* Handle a "ms_struct" or "gcc_struct" attribute; arguments as in
33019    struct attribute_spec.handler.  */
33020 static tree
33021 rs6000_handle_struct_attribute (tree *node, tree name,
33022                                 tree args ATTRIBUTE_UNUSED,
33023                                 int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
33024 {
33025   tree *type = NULL;
33026   if (DECL_P (*node))
33027     {
33028       if (TREE_CODE (*node) == TYPE_DECL)
33029         type = &TREE_TYPE (*node);
33030     }
33031   else
33032     type = node;
33033
33034   if (!(type && (TREE_CODE (*type) == RECORD_TYPE
33035                  || TREE_CODE (*type) == UNION_TYPE)))
33036     {
33037       warning (OPT_Wattributes, "%qE attribute ignored", name);
33038       *no_add_attrs = true;
33039     }
33040
33041   else if ((is_attribute_p ("ms_struct", name)
33042             && lookup_attribute ("gcc_struct", TYPE_ATTRIBUTES (*type)))
33043            || ((is_attribute_p ("gcc_struct", name)
33044                 && lookup_attribute ("ms_struct", TYPE_ATTRIBUTES (*type)))))
33045     {
33046       warning (OPT_Wattributes, "%qE incompatible attribute ignored",
33047                name);
33048       *no_add_attrs = true;
33049     }
33050
33051   return NULL_TREE;
33052 }
33053
33054 static bool
33055 rs6000_ms_bitfield_layout_p (const_tree record_type)
33056 {
33057   return (TARGET_USE_MS_BITFIELD_LAYOUT &&
33058           !lookup_attribute ("gcc_struct", TYPE_ATTRIBUTES (record_type)))
33059     || lookup_attribute ("ms_struct", TYPE_ATTRIBUTES (record_type));
33060 }
33061 \f
33062 #ifdef USING_ELFOS_H
33063
33064 /* A get_unnamed_section callback, used for switching to toc_section.  */
33065
33066 static void
33067 rs6000_elf_output_toc_section_asm_op (const void *data ATTRIBUTE_UNUSED)
33068 {
33069   if ((DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
33070       && TARGET_MINIMAL_TOC)
33071     {
33072       if (!toc_initialized)
33073         {
33074           fprintf (asm_out_file, "%s\n", TOC_SECTION_ASM_OP);
33075           ASM_OUTPUT_ALIGN (asm_out_file, TARGET_64BIT ? 3 : 2);
33076           (*targetm.asm_out.internal_label) (asm_out_file, "LCTOC", 0);
33077           fprintf (asm_out_file, "\t.tc ");
33078           ASM_OUTPUT_INTERNAL_LABEL_PREFIX (asm_out_file, "LCTOC1[TC],");
33079           ASM_OUTPUT_INTERNAL_LABEL_PREFIX (asm_out_file, "LCTOC1");
33080           fprintf (asm_out_file, "\n");
33081
33082           fprintf (asm_out_file, "%s\n", MINIMAL_TOC_SECTION_ASM_OP);
33083           ASM_OUTPUT_ALIGN (asm_out_file, TARGET_64BIT ? 3 : 2);
33084           ASM_OUTPUT_INTERNAL_LABEL_PREFIX (asm_out_file, "LCTOC1");
33085           fprintf (asm_out_file, " = .+32768\n");
33086           toc_initialized = 1;
33087         }
33088       else
33089         fprintf (asm_out_file, "%s\n", MINIMAL_TOC_SECTION_ASM_OP);
33090     }
33091   else if (DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
33092     {
33093       fprintf (asm_out_file, "%s\n", TOC_SECTION_ASM_OP);
33094       if (!toc_initialized)
33095         {
33096           ASM_OUTPUT_ALIGN (asm_out_file, TARGET_64BIT ? 3 : 2);
33097           toc_initialized = 1;
33098         }
33099     }
33100   else
33101     {
33102       fprintf (asm_out_file, "%s\n", MINIMAL_TOC_SECTION_ASM_OP);
33103       if (!toc_initialized)
33104         {
33105           ASM_OUTPUT_ALIGN (asm_out_file, TARGET_64BIT ? 3 : 2);
33106           ASM_OUTPUT_INTERNAL_LABEL_PREFIX (asm_out_file, "LCTOC1");
33107           fprintf (asm_out_file, " = .+32768\n");
33108           toc_initialized = 1;
33109         }
33110     }
33111 }
33112
33113 /* Implement TARGET_ASM_INIT_SECTIONS.  */
33114
33115 static void
33116 rs6000_elf_asm_init_sections (void)
33117 {
33118   toc_section
33119     = get_unnamed_section (0, rs6000_elf_output_toc_section_asm_op, NULL);
33120
33121   sdata2_section
33122     = get_unnamed_section (SECTION_WRITE, output_section_asm_op,
33123                            SDATA2_SECTION_ASM_OP);
33124 }
33125
33126 /* Implement TARGET_SELECT_RTX_SECTION.  */
33127
33128 static section *
33129 rs6000_elf_select_rtx_section (machine_mode mode, rtx x,
33130                                unsigned HOST_WIDE_INT align)
33131 {
33132   if (ASM_OUTPUT_SPECIAL_POOL_ENTRY_P (x, mode))
33133     return toc_section;
33134   else
33135     return default_elf_select_rtx_section (mode, x, align);
33136 }
33137 \f
33138 /* For a SYMBOL_REF, set generic flags and then perform some
33139    target-specific processing.
33140
33141    When the AIX ABI is requested on a non-AIX system, replace the
33142    function name with the real name (with a leading .) rather than the
33143    function descriptor name.  This saves a lot of overriding code to
33144    read the prefixes.  */
33145
33146 static void rs6000_elf_encode_section_info (tree, rtx, int) ATTRIBUTE_UNUSED;
33147 static void
33148 rs6000_elf_encode_section_info (tree decl, rtx rtl, int first)
33149 {
33150   default_encode_section_info (decl, rtl, first);
33151
33152   if (first
33153       && TREE_CODE (decl) == FUNCTION_DECL
33154       && !TARGET_AIX
33155       && DEFAULT_ABI == ABI_AIX)
33156     {
33157       rtx sym_ref = XEXP (rtl, 0);
33158       size_t len = strlen (XSTR (sym_ref, 0));
33159       char *str = XALLOCAVEC (char, len + 2);
33160       str[0] = '.';
33161       memcpy (str + 1, XSTR (sym_ref, 0), len + 1);
33162       XSTR (sym_ref, 0) = ggc_alloc_string (str, len + 1);
33163     }
33164 }
33165
33166 static inline bool
33167 compare_section_name (const char *section, const char *templ)
33168 {
33169   int len;
33170
33171   len = strlen (templ);
33172   return (strncmp (section, templ, len) == 0
33173           && (section[len] == 0 || section[len] == '.'));
33174 }
33175
33176 bool
33177 rs6000_elf_in_small_data_p (const_tree decl)
33178 {
33179   if (rs6000_sdata == SDATA_NONE)
33180     return false;
33181
33182   /* We want to merge strings, so we never consider them small data.  */
33183   if (TREE_CODE (decl) == STRING_CST)
33184     return false;
33185
33186   /* Functions are never in the small data area.  */
33187   if (TREE_CODE (decl) == FUNCTION_DECL)
33188     return false;
33189
33190   if (TREE_CODE (decl) == VAR_DECL && DECL_SECTION_NAME (decl))
33191     {
33192       const char *section = DECL_SECTION_NAME (decl);
33193       if (compare_section_name (section, ".sdata")
33194           || compare_section_name (section, ".sdata2")
33195           || compare_section_name (section, ".gnu.linkonce.s")
33196           || compare_section_name (section, ".sbss")
33197           || compare_section_name (section, ".sbss2")
33198           || compare_section_name (section, ".gnu.linkonce.sb")
33199           || strcmp (section, ".PPC.EMB.sdata0") == 0
33200           || strcmp (section, ".PPC.EMB.sbss0") == 0)
33201         return true;
33202     }
33203   else
33204     {
33205       HOST_WIDE_INT size = int_size_in_bytes (TREE_TYPE (decl));
33206
33207       if (size > 0
33208           && size <= g_switch_value
33209           /* If it's not public, and we're not going to reference it there,
33210              there's no need to put it in the small data section.  */
33211           && (rs6000_sdata != SDATA_DATA || TREE_PUBLIC (decl)))
33212         return true;
33213     }
33214
33215   return false;
33216 }
33217
33218 #endif /* USING_ELFOS_H */
33219 \f
33220 /* Implement TARGET_USE_BLOCKS_FOR_CONSTANT_P.  */
33221
33222 static bool
33223 rs6000_use_blocks_for_constant_p (machine_mode mode, const_rtx x)
33224 {
33225   return !ASM_OUTPUT_SPECIAL_POOL_ENTRY_P (x, mode);
33226 }
33227
33228 /* Do not place thread-local symbols refs in the object blocks.  */
33229
33230 static bool
33231 rs6000_use_blocks_for_decl_p (const_tree decl)
33232 {
33233   return !DECL_THREAD_LOCAL_P (decl);
33234 }
33235 \f
33236 /* Return a REG that occurs in ADDR with coefficient 1.
33237    ADDR can be effectively incremented by incrementing REG.
33238
33239    r0 is special and we must not select it as an address
33240    register by this routine since our caller will try to
33241    increment the returned register via an "la" instruction.  */
33242
33243 rtx
33244 find_addr_reg (rtx addr)
33245 {
33246   while (GET_CODE (addr) == PLUS)
33247     {
33248       if (GET_CODE (XEXP (addr, 0)) == REG
33249           && REGNO (XEXP (addr, 0)) != 0)
33250         addr = XEXP (addr, 0);
33251       else if (GET_CODE (XEXP (addr, 1)) == REG
33252                && REGNO (XEXP (addr, 1)) != 0)
33253         addr = XEXP (addr, 1);
33254       else if (CONSTANT_P (XEXP (addr, 0)))
33255         addr = XEXP (addr, 1);
33256       else if (CONSTANT_P (XEXP (addr, 1)))
33257         addr = XEXP (addr, 0);
33258       else
33259         gcc_unreachable ();
33260     }
33261   gcc_assert (GET_CODE (addr) == REG && REGNO (addr) != 0);
33262   return addr;
33263 }
33264
33265 void
33266 rs6000_fatal_bad_address (rtx op)
33267 {
33268   fatal_insn ("bad address", op);
33269 }
33270
33271 #if TARGET_MACHO
33272
33273 typedef struct branch_island_d {
33274   tree function_name;
33275   tree label_name;
33276   int line_number;
33277 } branch_island;
33278
33279
33280 static vec<branch_island, va_gc> *branch_islands;
33281
33282 /* Remember to generate a branch island for far calls to the given
33283    function.  */
33284
33285 static void
33286 add_compiler_branch_island (tree label_name, tree function_name,
33287                             int line_number)
33288 {
33289   branch_island bi = {function_name, label_name, line_number};
33290   vec_safe_push (branch_islands, bi);
33291 }
33292
33293 /* Generate far-jump branch islands for everything recorded in
33294    branch_islands.  Invoked immediately after the last instruction of
33295    the epilogue has been emitted; the branch islands must be appended
33296    to, and contiguous with, the function body.  Mach-O stubs are
33297    generated in machopic_output_stub().  */
33298
33299 static void
33300 macho_branch_islands (void)
33301 {
33302   char tmp_buf[512];
33303
33304   while (!vec_safe_is_empty (branch_islands))
33305     {
33306       branch_island *bi = &branch_islands->last ();
33307       const char *label = IDENTIFIER_POINTER (bi->label_name);
33308       const char *name = IDENTIFIER_POINTER (bi->function_name);
33309       char name_buf[512];
33310       /* Cheap copy of the details from the Darwin ASM_OUTPUT_LABELREF().  */
33311       if (name[0] == '*' || name[0] == '&')
33312         strcpy (name_buf, name+1);
33313       else
33314         {
33315           name_buf[0] = '_';
33316           strcpy (name_buf+1, name);
33317         }
33318       strcpy (tmp_buf, "\n");
33319       strcat (tmp_buf, label);
33320 #if defined (DBX_DEBUGGING_INFO) || defined (XCOFF_DEBUGGING_INFO)
33321       if (write_symbols == DBX_DEBUG || write_symbols == XCOFF_DEBUG)
33322         dbxout_stabd (N_SLINE, bi->line_number);
33323 #endif /* DBX_DEBUGGING_INFO || XCOFF_DEBUGGING_INFO */
33324       if (flag_pic)
33325         {
33326           if (TARGET_LINK_STACK)
33327             {
33328               char name[32];
33329               get_ppc476_thunk_name (name);
33330               strcat (tmp_buf, ":\n\tmflr r0\n\tbl ");
33331               strcat (tmp_buf, name);
33332               strcat (tmp_buf, "\n");
33333               strcat (tmp_buf, label);
33334               strcat (tmp_buf, "_pic:\n\tmflr r11\n");
33335             }
33336           else
33337             {
33338               strcat (tmp_buf, ":\n\tmflr r0\n\tbcl 20,31,");
33339               strcat (tmp_buf, label);
33340               strcat (tmp_buf, "_pic\n");
33341               strcat (tmp_buf, label);
33342               strcat (tmp_buf, "_pic:\n\tmflr r11\n");
33343             }
33344
33345           strcat (tmp_buf, "\taddis r11,r11,ha16(");
33346           strcat (tmp_buf, name_buf);
33347           strcat (tmp_buf, " - ");
33348           strcat (tmp_buf, label);
33349           strcat (tmp_buf, "_pic)\n");
33350
33351           strcat (tmp_buf, "\tmtlr r0\n");
33352
33353           strcat (tmp_buf, "\taddi r12,r11,lo16(");
33354           strcat (tmp_buf, name_buf);
33355           strcat (tmp_buf, " - ");
33356           strcat (tmp_buf, label);
33357           strcat (tmp_buf, "_pic)\n");
33358
33359           strcat (tmp_buf, "\tmtctr r12\n\tbctr\n");
33360         }
33361       else
33362         {
33363           strcat (tmp_buf, ":\nlis r12,hi16(");
33364           strcat (tmp_buf, name_buf);
33365           strcat (tmp_buf, ")\n\tori r12,r12,lo16(");
33366           strcat (tmp_buf, name_buf);
33367           strcat (tmp_buf, ")\n\tmtctr r12\n\tbctr");
33368         }
33369       output_asm_insn (tmp_buf, 0);
33370 #if defined (DBX_DEBUGGING_INFO) || defined (XCOFF_DEBUGGING_INFO)
33371       if (write_symbols == DBX_DEBUG || write_symbols == XCOFF_DEBUG)
33372         dbxout_stabd (N_SLINE, bi->line_number);
33373 #endif /* DBX_DEBUGGING_INFO || XCOFF_DEBUGGING_INFO */
33374       branch_islands->pop ();
33375     }
33376 }
33377
33378 /* NO_PREVIOUS_DEF checks in the link list whether the function name is
33379    already there or not.  */
33380
33381 static int
33382 no_previous_def (tree function_name)
33383 {
33384   branch_island *bi;
33385   unsigned ix;
33386
33387   FOR_EACH_VEC_SAFE_ELT (branch_islands, ix, bi)
33388     if (function_name == bi->function_name)
33389       return 0;
33390   return 1;
33391 }
33392
33393 /* GET_PREV_LABEL gets the label name from the previous definition of
33394    the function.  */
33395
33396 static tree
33397 get_prev_label (tree function_name)
33398 {
33399   branch_island *bi;
33400   unsigned ix;
33401
33402   FOR_EACH_VEC_SAFE_ELT (branch_islands, ix, bi)
33403     if (function_name == bi->function_name)
33404       return bi->label_name;
33405   return NULL_TREE;
33406 }
33407
33408 /* INSN is either a function call or a millicode call.  It may have an
33409    unconditional jump in its delay slot.
33410
33411    CALL_DEST is the routine we are calling.  */
33412
33413 char *
33414 output_call (rtx_insn *insn, rtx *operands, int dest_operand_number,
33415              int cookie_operand_number)
33416 {
33417   static char buf[256];
33418   if (darwin_emit_branch_islands
33419       && GET_CODE (operands[dest_operand_number]) == SYMBOL_REF
33420       && (INTVAL (operands[cookie_operand_number]) & CALL_LONG))
33421     {
33422       tree labelname;
33423       tree funname = get_identifier (XSTR (operands[dest_operand_number], 0));
33424
33425       if (no_previous_def (funname))
33426         {
33427           rtx label_rtx = gen_label_rtx ();
33428           char *label_buf, temp_buf[256];
33429           ASM_GENERATE_INTERNAL_LABEL (temp_buf, "L",
33430                                        CODE_LABEL_NUMBER (label_rtx));
33431           label_buf = temp_buf[0] == '*' ? temp_buf + 1 : temp_buf;
33432           labelname = get_identifier (label_buf);
33433           add_compiler_branch_island (labelname, funname, insn_line (insn));
33434         }
33435       else
33436         labelname = get_prev_label (funname);
33437
33438       /* "jbsr foo, L42" is Mach-O for "Link as 'bl foo' if a 'bl'
33439          instruction will reach 'foo', otherwise link as 'bl L42'".
33440          "L42" should be a 'branch island', that will do a far jump to
33441          'foo'.  Branch islands are generated in
33442          macho_branch_islands().  */
33443       sprintf (buf, "jbsr %%z%d,%.246s",
33444                dest_operand_number, IDENTIFIER_POINTER (labelname));
33445     }
33446   else
33447     sprintf (buf, "bl %%z%d", dest_operand_number);
33448   return buf;
33449 }
33450
33451 /* Generate PIC and indirect symbol stubs.  */
33452
33453 void
33454 machopic_output_stub (FILE *file, const char *symb, const char *stub)
33455 {
33456   unsigned int length;
33457   char *symbol_name, *lazy_ptr_name;
33458   char *local_label_0;
33459   static int label = 0;
33460
33461   /* Lose our funky encoding stuff so it doesn't contaminate the stub.  */
33462   symb = (*targetm.strip_name_encoding) (symb);
33463
33464
33465   length = strlen (symb);
33466   symbol_name = XALLOCAVEC (char, length + 32);
33467   GEN_SYMBOL_NAME_FOR_SYMBOL (symbol_name, symb, length);
33468
33469   lazy_ptr_name = XALLOCAVEC (char, length + 32);
33470   GEN_LAZY_PTR_NAME_FOR_SYMBOL (lazy_ptr_name, symb, length);
33471
33472   if (flag_pic == 2)
33473     switch_to_section (darwin_sections[machopic_picsymbol_stub1_section]);
33474   else
33475     switch_to_section (darwin_sections[machopic_symbol_stub1_section]);
33476
33477   if (flag_pic == 2)
33478     {
33479       fprintf (file, "\t.align 5\n");
33480
33481       fprintf (file, "%s:\n", stub);
33482       fprintf (file, "\t.indirect_symbol %s\n", symbol_name);
33483
33484       label++;
33485       local_label_0 = XALLOCAVEC (char, sizeof ("\"L00000000000$spb\""));
33486       sprintf (local_label_0, "\"L%011d$spb\"", label);
33487
33488       fprintf (file, "\tmflr r0\n");
33489       if (TARGET_LINK_STACK)
33490         {
33491           char name[32];
33492           get_ppc476_thunk_name (name);
33493           fprintf (file, "\tbl %s\n", name);
33494           fprintf (file, "%s:\n\tmflr r11\n", local_label_0);
33495         }
33496       else
33497         {
33498           fprintf (file, "\tbcl 20,31,%s\n", local_label_0);
33499           fprintf (file, "%s:\n\tmflr r11\n", local_label_0);
33500         }
33501       fprintf (file, "\taddis r11,r11,ha16(%s-%s)\n",
33502                lazy_ptr_name, local_label_0);
33503       fprintf (file, "\tmtlr r0\n");
33504       fprintf (file, "\t%s r12,lo16(%s-%s)(r11)\n",
33505                (TARGET_64BIT ? "ldu" : "lwzu"),
33506                lazy_ptr_name, local_label_0);
33507       fprintf (file, "\tmtctr r12\n");
33508       fprintf (file, "\tbctr\n");
33509     }
33510   else
33511     {
33512       fprintf (file, "\t.align 4\n");
33513
33514       fprintf (file, "%s:\n", stub);
33515       fprintf (file, "\t.indirect_symbol %s\n", symbol_name);
33516
33517       fprintf (file, "\tlis r11,ha16(%s)\n", lazy_ptr_name);
33518       fprintf (file, "\t%s r12,lo16(%s)(r11)\n",
33519                (TARGET_64BIT ? "ldu" : "lwzu"),
33520                lazy_ptr_name);
33521       fprintf (file, "\tmtctr r12\n");
33522       fprintf (file, "\tbctr\n");
33523     }
33524
33525   switch_to_section (darwin_sections[machopic_lazy_symbol_ptr_section]);
33526   fprintf (file, "%s:\n", lazy_ptr_name);
33527   fprintf (file, "\t.indirect_symbol %s\n", symbol_name);
33528   fprintf (file, "%sdyld_stub_binding_helper\n",
33529            (TARGET_64BIT ? DOUBLE_INT_ASM_OP : "\t.long\t"));
33530 }
33531
33532 /* Legitimize PIC addresses.  If the address is already
33533    position-independent, we return ORIG.  Newly generated
33534    position-independent addresses go into a reg.  This is REG if non
33535    zero, otherwise we allocate register(s) as necessary.  */
33536
33537 #define SMALL_INT(X) ((UINTVAL (X) + 0x8000) < 0x10000)
33538
33539 rtx
33540 rs6000_machopic_legitimize_pic_address (rtx orig, machine_mode mode,
33541                                         rtx reg)
33542 {
33543   rtx base, offset;
33544
33545   if (reg == NULL && !reload_completed)
33546     reg = gen_reg_rtx (Pmode);
33547
33548   if (GET_CODE (orig) == CONST)
33549     {
33550       rtx reg_temp;
33551
33552       if (GET_CODE (XEXP (orig, 0)) == PLUS
33553           && XEXP (XEXP (orig, 0), 0) == pic_offset_table_rtx)
33554         return orig;
33555
33556       gcc_assert (GET_CODE (XEXP (orig, 0)) == PLUS);
33557
33558       /* Use a different reg for the intermediate value, as
33559          it will be marked UNCHANGING.  */
33560       reg_temp = !can_create_pseudo_p () ? reg : gen_reg_rtx (Pmode);
33561       base = rs6000_machopic_legitimize_pic_address (XEXP (XEXP (orig, 0), 0),
33562                                                      Pmode, reg_temp);
33563       offset =
33564         rs6000_machopic_legitimize_pic_address (XEXP (XEXP (orig, 0), 1),
33565                                                 Pmode, reg);
33566
33567       if (GET_CODE (offset) == CONST_INT)
33568         {
33569           if (SMALL_INT (offset))
33570             return plus_constant (Pmode, base, INTVAL (offset));
33571           else if (!reload_completed)
33572             offset = force_reg (Pmode, offset);
33573           else
33574             {
33575               rtx mem = force_const_mem (Pmode, orig);
33576               return machopic_legitimize_pic_address (mem, Pmode, reg);
33577             }
33578         }
33579       return gen_rtx_PLUS (Pmode, base, offset);
33580     }
33581
33582   /* Fall back on generic machopic code.  */
33583   return machopic_legitimize_pic_address (orig, mode, reg);
33584 }
33585
33586 /* Output a .machine directive for the Darwin assembler, and call
33587    the generic start_file routine.  */
33588
33589 static void
33590 rs6000_darwin_file_start (void)
33591 {
33592   static const struct
33593   {
33594     const char *arg;
33595     const char *name;
33596     HOST_WIDE_INT if_set;
33597   } mapping[] = {
33598     { "ppc64", "ppc64", MASK_64BIT },
33599     { "970", "ppc970", MASK_PPC_GPOPT | MASK_MFCRF | MASK_POWERPC64 },
33600     { "power4", "ppc970", 0 },
33601     { "G5", "ppc970", 0 },
33602     { "7450", "ppc7450", 0 },
33603     { "7400", "ppc7400", MASK_ALTIVEC },
33604     { "G4", "ppc7400", 0 },
33605     { "750", "ppc750", 0 },
33606     { "740", "ppc750", 0 },
33607     { "G3", "ppc750", 0 },
33608     { "604e", "ppc604e", 0 },
33609     { "604", "ppc604", 0 },
33610     { "603e", "ppc603", 0 },
33611     { "603", "ppc603", 0 },
33612     { "601", "ppc601", 0 },
33613     { NULL, "ppc", 0 } };
33614   const char *cpu_id = "";
33615   size_t i;
33616
33617   rs6000_file_start ();
33618   darwin_file_start ();
33619
33620   /* Determine the argument to -mcpu=.  Default to G3 if not specified.  */
33621   
33622   if (rs6000_default_cpu != 0 && rs6000_default_cpu[0] != '\0')
33623     cpu_id = rs6000_default_cpu;
33624
33625   if (global_options_set.x_rs6000_cpu_index)
33626     cpu_id = processor_target_table[rs6000_cpu_index].name;
33627
33628   /* Look through the mapping array.  Pick the first name that either
33629      matches the argument, has a bit set in IF_SET that is also set
33630      in the target flags, or has a NULL name.  */
33631
33632   i = 0;
33633   while (mapping[i].arg != NULL
33634          && strcmp (mapping[i].arg, cpu_id) != 0
33635          && (mapping[i].if_set & rs6000_isa_flags) == 0)
33636     i++;
33637
33638   fprintf (asm_out_file, "\t.machine %s\n", mapping[i].name);
33639 }
33640
33641 #endif /* TARGET_MACHO */
33642
33643 #if TARGET_ELF
33644 static int
33645 rs6000_elf_reloc_rw_mask (void)
33646 {
33647   if (flag_pic)
33648     return 3;
33649   else if (DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
33650     return 2;
33651   else
33652     return 0;
33653 }
33654
33655 /* Record an element in the table of global constructors.  SYMBOL is
33656    a SYMBOL_REF of the function to be called; PRIORITY is a number
33657    between 0 and MAX_INIT_PRIORITY.
33658
33659    This differs from default_named_section_asm_out_constructor in
33660    that we have special handling for -mrelocatable.  */
33661
33662 static void rs6000_elf_asm_out_constructor (rtx, int) ATTRIBUTE_UNUSED;
33663 static void
33664 rs6000_elf_asm_out_constructor (rtx symbol, int priority)
33665 {
33666   const char *section = ".ctors";
33667   char buf[18];
33668
33669   if (priority != DEFAULT_INIT_PRIORITY)
33670     {
33671       sprintf (buf, ".ctors.%.5u",
33672                /* Invert the numbering so the linker puts us in the proper
33673                   order; constructors are run from right to left, and the
33674                   linker sorts in increasing order.  */
33675                MAX_INIT_PRIORITY - priority);
33676       section = buf;
33677     }
33678
33679   switch_to_section (get_section (section, SECTION_WRITE, NULL));
33680   assemble_align (POINTER_SIZE);
33681
33682   if (DEFAULT_ABI == ABI_V4
33683       && (TARGET_RELOCATABLE || flag_pic > 1))
33684     {
33685       fputs ("\t.long (", asm_out_file);
33686       output_addr_const (asm_out_file, symbol);
33687       fputs (")@fixup\n", asm_out_file);
33688     }
33689   else
33690     assemble_integer (symbol, POINTER_SIZE / BITS_PER_UNIT, POINTER_SIZE, 1);
33691 }
33692
33693 static void rs6000_elf_asm_out_destructor (rtx, int) ATTRIBUTE_UNUSED;
33694 static void
33695 rs6000_elf_asm_out_destructor (rtx symbol, int priority)
33696 {
33697   const char *section = ".dtors";
33698   char buf[18];
33699
33700   if (priority != DEFAULT_INIT_PRIORITY)
33701     {
33702       sprintf (buf, ".dtors.%.5u",
33703                /* Invert the numbering so the linker puts us in the proper
33704                   order; constructors are run from right to left, and the
33705                   linker sorts in increasing order.  */
33706                MAX_INIT_PRIORITY - priority);
33707       section = buf;
33708     }
33709
33710   switch_to_section (get_section (section, SECTION_WRITE, NULL));
33711   assemble_align (POINTER_SIZE);
33712
33713   if (DEFAULT_ABI == ABI_V4
33714       && (TARGET_RELOCATABLE || flag_pic > 1))
33715     {
33716       fputs ("\t.long (", asm_out_file);
33717       output_addr_const (asm_out_file, symbol);
33718       fputs (")@fixup\n", asm_out_file);
33719     }
33720   else
33721     assemble_integer (symbol, POINTER_SIZE / BITS_PER_UNIT, POINTER_SIZE, 1);
33722 }
33723
33724 void
33725 rs6000_elf_declare_function_name (FILE *file, const char *name, tree decl)
33726 {
33727   if (TARGET_64BIT && DEFAULT_ABI != ABI_ELFv2)
33728     {
33729       fputs ("\t.section\t\".opd\",\"aw\"\n\t.align 3\n", file);
33730       ASM_OUTPUT_LABEL (file, name);
33731       fputs (DOUBLE_INT_ASM_OP, file);
33732       rs6000_output_function_entry (file, name);
33733       fputs (",.TOC.@tocbase,0\n\t.previous\n", file);
33734       if (DOT_SYMBOLS)
33735         {
33736           fputs ("\t.size\t", file);
33737           assemble_name (file, name);
33738           fputs (",24\n\t.type\t.", file);
33739           assemble_name (file, name);
33740           fputs (",@function\n", file);
33741           if (TREE_PUBLIC (decl) && ! DECL_WEAK (decl))
33742             {
33743               fputs ("\t.globl\t.", file);
33744               assemble_name (file, name);
33745               putc ('\n', file);
33746             }
33747         }
33748       else
33749         ASM_OUTPUT_TYPE_DIRECTIVE (file, name, "function");
33750       ASM_DECLARE_RESULT (file, DECL_RESULT (decl));
33751       rs6000_output_function_entry (file, name);
33752       fputs (":\n", file);
33753       return;
33754     }
33755
33756   int uses_toc;
33757   if (DEFAULT_ABI == ABI_V4
33758       && (TARGET_RELOCATABLE || flag_pic > 1)
33759       && !TARGET_SECURE_PLT
33760       && (!constant_pool_empty_p () || crtl->profile)
33761       && (uses_toc = uses_TOC ()))
33762     {
33763       char buf[256];
33764
33765       if (uses_toc == 2)
33766         switch_to_other_text_partition ();
33767       (*targetm.asm_out.internal_label) (file, "LCL", rs6000_pic_labelno);
33768
33769       fprintf (file, "\t.long ");
33770       assemble_name (file, toc_label_name);
33771       need_toc_init = 1;
33772       putc ('-', file);
33773       ASM_GENERATE_INTERNAL_LABEL (buf, "LCF", rs6000_pic_labelno);
33774       assemble_name (file, buf);
33775       putc ('\n', file);
33776       if (uses_toc == 2)
33777         switch_to_other_text_partition ();
33778     }
33779
33780   ASM_OUTPUT_TYPE_DIRECTIVE (file, name, "function");
33781   ASM_DECLARE_RESULT (file, DECL_RESULT (decl));
33782
33783   if (TARGET_CMODEL == CMODEL_LARGE && rs6000_global_entry_point_needed_p ())
33784     {
33785       char buf[256];
33786
33787       (*targetm.asm_out.internal_label) (file, "LCL", rs6000_pic_labelno);
33788
33789       fprintf (file, "\t.quad .TOC.-");
33790       ASM_GENERATE_INTERNAL_LABEL (buf, "LCF", rs6000_pic_labelno);
33791       assemble_name (file, buf);
33792       putc ('\n', file);
33793     }
33794
33795   if (DEFAULT_ABI == ABI_AIX)
33796     {
33797       const char *desc_name, *orig_name;
33798
33799       orig_name = (*targetm.strip_name_encoding) (name);
33800       desc_name = orig_name;
33801       while (*desc_name == '.')
33802         desc_name++;
33803
33804       if (TREE_PUBLIC (decl))
33805         fprintf (file, "\t.globl %s\n", desc_name);
33806
33807       fprintf (file, "%s\n", MINIMAL_TOC_SECTION_ASM_OP);
33808       fprintf (file, "%s:\n", desc_name);
33809       fprintf (file, "\t.long %s\n", orig_name);
33810       fputs ("\t.long _GLOBAL_OFFSET_TABLE_\n", file);
33811       fputs ("\t.long 0\n", file);
33812       fprintf (file, "\t.previous\n");
33813     }
33814   ASM_OUTPUT_LABEL (file, name);
33815 }
33816
33817 static void rs6000_elf_file_end (void) ATTRIBUTE_UNUSED;
33818 static void
33819 rs6000_elf_file_end (void)
33820 {
33821 #ifdef HAVE_AS_GNU_ATTRIBUTE
33822   /* ??? The value emitted depends on options active at file end.
33823      Assume anyone using #pragma or attributes that might change
33824      options knows what they are doing.  */
33825   if ((TARGET_64BIT || DEFAULT_ABI == ABI_V4)
33826       && rs6000_passes_float)
33827     {
33828       int fp;
33829
33830       if (TARGET_DF_FPR)
33831         fp = 1;
33832       else if (TARGET_SF_FPR)
33833         fp = 3;
33834       else
33835         fp = 2;
33836       if (rs6000_passes_long_double)
33837         {
33838           if (!TARGET_LONG_DOUBLE_128)
33839             fp |= 2 * 4;
33840           else if (TARGET_IEEEQUAD)
33841             fp |= 3 * 4;
33842           else
33843             fp |= 1 * 4;
33844         }
33845       fprintf (asm_out_file, "\t.gnu_attribute 4, %d\n", fp);
33846     }
33847   if (TARGET_32BIT && DEFAULT_ABI == ABI_V4)
33848     {
33849       if (rs6000_passes_vector)
33850         fprintf (asm_out_file, "\t.gnu_attribute 8, %d\n",
33851                  (TARGET_ALTIVEC_ABI ? 2 : 1));
33852       if (rs6000_returns_struct)
33853         fprintf (asm_out_file, "\t.gnu_attribute 12, %d\n",
33854                  aix_struct_return ? 2 : 1);
33855     }
33856 #endif
33857 #if defined (POWERPC_LINUX) || defined (POWERPC_FREEBSD)
33858   if (TARGET_32BIT || DEFAULT_ABI == ABI_ELFv2)
33859     file_end_indicate_exec_stack ();
33860 #endif
33861
33862   if (flag_split_stack)
33863     file_end_indicate_split_stack ();
33864
33865   if (cpu_builtin_p)
33866     {
33867       /* We have expanded a CPU builtin, so we need to emit a reference to
33868          the special symbol that LIBC uses to declare it supports the
33869          AT_PLATFORM and AT_HWCAP/AT_HWCAP2 in the TCB feature.  */
33870       switch_to_section (data_section);
33871       fprintf (asm_out_file, "\t.align %u\n", TARGET_32BIT ? 2 : 3);
33872       fprintf (asm_out_file, "\t%s %s\n",
33873                TARGET_32BIT ? ".long" : ".quad", tcb_verification_symbol);
33874     }
33875 }
33876 #endif
33877
33878 #if TARGET_XCOFF
33879
33880 #ifndef HAVE_XCOFF_DWARF_EXTRAS
33881 #define HAVE_XCOFF_DWARF_EXTRAS 0
33882 #endif
33883
33884 static enum unwind_info_type
33885 rs6000_xcoff_debug_unwind_info (void)
33886 {
33887   return UI_NONE;
33888 }
33889
33890 static void
33891 rs6000_xcoff_asm_output_anchor (rtx symbol)
33892 {
33893   char buffer[100];
33894
33895   sprintf (buffer, "$ + " HOST_WIDE_INT_PRINT_DEC,
33896            SYMBOL_REF_BLOCK_OFFSET (symbol));
33897   fprintf (asm_out_file, "%s", SET_ASM_OP);
33898   RS6000_OUTPUT_BASENAME (asm_out_file, XSTR (symbol, 0));
33899   fprintf (asm_out_file, ",");
33900   RS6000_OUTPUT_BASENAME (asm_out_file, buffer);
33901   fprintf (asm_out_file, "\n");
33902 }
33903
33904 static void
33905 rs6000_xcoff_asm_globalize_label (FILE *stream, const char *name)
33906 {
33907   fputs (GLOBAL_ASM_OP, stream);
33908   RS6000_OUTPUT_BASENAME (stream, name);
33909   putc ('\n', stream);
33910 }
33911
33912 /* A get_unnamed_decl callback, used for read-only sections.  PTR
33913    points to the section string variable.  */
33914
33915 static void
33916 rs6000_xcoff_output_readonly_section_asm_op (const void *directive)
33917 {
33918   fprintf (asm_out_file, "\t.csect %s[RO],%s\n",
33919            *(const char *const *) directive,
33920            XCOFF_CSECT_DEFAULT_ALIGNMENT_STR);
33921 }
33922
33923 /* Likewise for read-write sections.  */
33924
33925 static void
33926 rs6000_xcoff_output_readwrite_section_asm_op (const void *directive)
33927 {
33928   fprintf (asm_out_file, "\t.csect %s[RW],%s\n",
33929            *(const char *const *) directive,
33930            XCOFF_CSECT_DEFAULT_ALIGNMENT_STR);
33931 }
33932
33933 static void
33934 rs6000_xcoff_output_tls_section_asm_op (const void *directive)
33935 {
33936   fprintf (asm_out_file, "\t.csect %s[TL],%s\n",
33937            *(const char *const *) directive,
33938            XCOFF_CSECT_DEFAULT_ALIGNMENT_STR);
33939 }
33940
33941 /* A get_unnamed_section callback, used for switching to toc_section.  */
33942
33943 static void
33944 rs6000_xcoff_output_toc_section_asm_op (const void *data ATTRIBUTE_UNUSED)
33945 {
33946   if (TARGET_MINIMAL_TOC)
33947     {
33948       /* toc_section is always selected at least once from
33949          rs6000_xcoff_file_start, so this is guaranteed to
33950          always be defined once and only once in each file.  */
33951       if (!toc_initialized)
33952         {
33953           fputs ("\t.toc\nLCTOC..1:\n", asm_out_file);
33954           fputs ("\t.tc toc_table[TC],toc_table[RW]\n", asm_out_file);
33955           toc_initialized = 1;
33956         }
33957       fprintf (asm_out_file, "\t.csect toc_table[RW]%s\n",
33958                (TARGET_32BIT ? "" : ",3"));
33959     }
33960   else
33961     fputs ("\t.toc\n", asm_out_file);
33962 }
33963
33964 /* Implement TARGET_ASM_INIT_SECTIONS.  */
33965
33966 static void
33967 rs6000_xcoff_asm_init_sections (void)
33968 {
33969   read_only_data_section
33970     = get_unnamed_section (0, rs6000_xcoff_output_readonly_section_asm_op,
33971                            &xcoff_read_only_section_name);
33972
33973   private_data_section
33974     = get_unnamed_section (SECTION_WRITE,
33975                            rs6000_xcoff_output_readwrite_section_asm_op,
33976                            &xcoff_private_data_section_name);
33977
33978   tls_data_section
33979     = get_unnamed_section (SECTION_TLS,
33980                            rs6000_xcoff_output_tls_section_asm_op,
33981                            &xcoff_tls_data_section_name);
33982
33983   tls_private_data_section
33984     = get_unnamed_section (SECTION_TLS,
33985                            rs6000_xcoff_output_tls_section_asm_op,
33986                            &xcoff_private_data_section_name);
33987
33988   read_only_private_data_section
33989     = get_unnamed_section (0, rs6000_xcoff_output_readonly_section_asm_op,
33990                            &xcoff_private_data_section_name);
33991
33992   toc_section
33993     = get_unnamed_section (0, rs6000_xcoff_output_toc_section_asm_op, NULL);
33994
33995   readonly_data_section = read_only_data_section;
33996 }
33997
33998 static int
33999 rs6000_xcoff_reloc_rw_mask (void)
34000 {
34001   return 3;
34002 }
34003
34004 static void
34005 rs6000_xcoff_asm_named_section (const char *name, unsigned int flags,
34006                                 tree decl ATTRIBUTE_UNUSED)
34007 {
34008   int smclass;
34009   static const char * const suffix[5] = { "PR", "RO", "RW", "TL", "XO" };
34010
34011   if (flags & SECTION_EXCLUDE)
34012     smclass = 4;
34013   else if (flags & SECTION_DEBUG)
34014     {
34015       fprintf (asm_out_file, "\t.dwsect %s\n", name);
34016       return;
34017     }
34018   else if (flags & SECTION_CODE)
34019     smclass = 0;
34020   else if (flags & SECTION_TLS)
34021     smclass = 3;
34022   else if (flags & SECTION_WRITE)
34023     smclass = 2;
34024   else
34025     smclass = 1;
34026
34027   fprintf (asm_out_file, "\t.csect %s%s[%s],%u\n",
34028            (flags & SECTION_CODE) ? "." : "",
34029            name, suffix[smclass], flags & SECTION_ENTSIZE);
34030 }
34031
34032 #define IN_NAMED_SECTION(DECL) \
34033   ((TREE_CODE (DECL) == FUNCTION_DECL || TREE_CODE (DECL) == VAR_DECL) \
34034    && DECL_SECTION_NAME (DECL) != NULL)
34035
34036 static section *
34037 rs6000_xcoff_select_section (tree decl, int reloc,
34038                              unsigned HOST_WIDE_INT align)
34039 {
34040   /* Place variables with alignment stricter than BIGGEST_ALIGNMENT into
34041      named section.  */
34042   if (align > BIGGEST_ALIGNMENT)
34043     {
34044       resolve_unique_section (decl, reloc, true);
34045       if (IN_NAMED_SECTION (decl))
34046         return get_named_section (decl, NULL, reloc);
34047     }
34048
34049   if (decl_readonly_section (decl, reloc))
34050     {
34051       if (TREE_PUBLIC (decl))
34052         return read_only_data_section;
34053       else
34054         return read_only_private_data_section;
34055     }
34056   else
34057     {
34058 #if HAVE_AS_TLS
34059       if (TREE_CODE (decl) == VAR_DECL && DECL_THREAD_LOCAL_P (decl))
34060         {
34061           if (TREE_PUBLIC (decl))
34062             return tls_data_section;
34063           else if (bss_initializer_p (decl))
34064             {
34065               /* Convert to COMMON to emit in BSS.  */
34066               DECL_COMMON (decl) = 1;
34067               return tls_comm_section;
34068             }
34069           else
34070             return tls_private_data_section;
34071         }
34072       else
34073 #endif
34074         if (TREE_PUBLIC (decl))
34075         return data_section;
34076       else
34077         return private_data_section;
34078     }
34079 }
34080
34081 static void
34082 rs6000_xcoff_unique_section (tree decl, int reloc ATTRIBUTE_UNUSED)
34083 {
34084   const char *name;
34085
34086   /* Use select_section for private data and uninitialized data with
34087      alignment <= BIGGEST_ALIGNMENT.  */
34088   if (!TREE_PUBLIC (decl)
34089       || DECL_COMMON (decl)
34090       || (DECL_INITIAL (decl) == NULL_TREE
34091           && DECL_ALIGN (decl) <= BIGGEST_ALIGNMENT)
34092       || DECL_INITIAL (decl) == error_mark_node
34093       || (flag_zero_initialized_in_bss
34094           && initializer_zerop (DECL_INITIAL (decl))))
34095     return;
34096
34097   name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl));
34098   name = (*targetm.strip_name_encoding) (name);
34099   set_decl_section_name (decl, name);
34100 }
34101
34102 /* Select section for constant in constant pool.
34103
34104    On RS/6000, all constants are in the private read-only data area.
34105    However, if this is being placed in the TOC it must be output as a
34106    toc entry.  */
34107
34108 static section *
34109 rs6000_xcoff_select_rtx_section (machine_mode mode, rtx x,
34110                                  unsigned HOST_WIDE_INT align ATTRIBUTE_UNUSED)
34111 {
34112   if (ASM_OUTPUT_SPECIAL_POOL_ENTRY_P (x, mode))
34113     return toc_section;
34114   else
34115     return read_only_private_data_section;
34116 }
34117
34118 /* Remove any trailing [DS] or the like from the symbol name.  */
34119
34120 static const char *
34121 rs6000_xcoff_strip_name_encoding (const char *name)
34122 {
34123   size_t len;
34124   if (*name == '*')
34125     name++;
34126   len = strlen (name);
34127   if (name[len - 1] == ']')
34128     return ggc_alloc_string (name, len - 4);
34129   else
34130     return name;
34131 }
34132
34133 /* Section attributes.  AIX is always PIC.  */
34134
34135 static unsigned int
34136 rs6000_xcoff_section_type_flags (tree decl, const char *name, int reloc)
34137 {
34138   unsigned int align;
34139   unsigned int flags = default_section_type_flags (decl, name, reloc);
34140
34141   /* Align to at least UNIT size.  */
34142   if ((flags & SECTION_CODE) != 0 || !decl || !DECL_P (decl))
34143     align = MIN_UNITS_PER_WORD;
34144   else
34145     /* Increase alignment of large objects if not already stricter.  */
34146     align = MAX ((DECL_ALIGN (decl) / BITS_PER_UNIT),
34147                  int_size_in_bytes (TREE_TYPE (decl)) > MIN_UNITS_PER_WORD
34148                  ? UNITS_PER_FP_WORD : MIN_UNITS_PER_WORD);
34149
34150   return flags | (exact_log2 (align) & SECTION_ENTSIZE);
34151 }
34152
34153 /* Output at beginning of assembler file.
34154
34155    Initialize the section names for the RS/6000 at this point.
34156
34157    Specify filename, including full path, to assembler.
34158
34159    We want to go into the TOC section so at least one .toc will be emitted.
34160    Also, in order to output proper .bs/.es pairs, we need at least one static
34161    [RW] section emitted.
34162
34163    Finally, declare mcount when profiling to make the assembler happy.  */
34164
34165 static void
34166 rs6000_xcoff_file_start (void)
34167 {
34168   rs6000_gen_section_name (&xcoff_bss_section_name,
34169                            main_input_filename, ".bss_");
34170   rs6000_gen_section_name (&xcoff_private_data_section_name,
34171                            main_input_filename, ".rw_");
34172   rs6000_gen_section_name (&xcoff_read_only_section_name,
34173                            main_input_filename, ".ro_");
34174   rs6000_gen_section_name (&xcoff_tls_data_section_name,
34175                            main_input_filename, ".tls_");
34176   rs6000_gen_section_name (&xcoff_tbss_section_name,
34177                            main_input_filename, ".tbss_[UL]");
34178
34179   fputs ("\t.file\t", asm_out_file);
34180   output_quoted_string (asm_out_file, main_input_filename);
34181   fputc ('\n', asm_out_file);
34182   if (write_symbols != NO_DEBUG)
34183     switch_to_section (private_data_section);
34184   switch_to_section (toc_section);
34185   switch_to_section (text_section);
34186   if (profile_flag)
34187     fprintf (asm_out_file, "\t.extern %s\n", RS6000_MCOUNT);
34188   rs6000_file_start ();
34189 }
34190
34191 /* Output at end of assembler file.
34192    On the RS/6000, referencing data should automatically pull in text.  */
34193
34194 static void
34195 rs6000_xcoff_file_end (void)
34196 {
34197   switch_to_section (text_section);
34198   fputs ("_section_.text:\n", asm_out_file);
34199   switch_to_section (data_section);
34200   fputs (TARGET_32BIT
34201          ? "\t.long _section_.text\n" : "\t.llong _section_.text\n",
34202          asm_out_file);
34203 }
34204
34205 struct declare_alias_data
34206 {
34207   FILE *file;
34208   bool function_descriptor;
34209 };
34210
34211 /* Declare alias N.  A helper function for for_node_and_aliases.  */
34212
34213 static bool
34214 rs6000_declare_alias (struct symtab_node *n, void *d)
34215 {
34216   struct declare_alias_data *data = (struct declare_alias_data *)d;
34217   /* Main symbol is output specially, because varasm machinery does part of
34218      the job for us - we do not need to declare .globl/lglobs and such.  */
34219   if (!n->alias || n->weakref)
34220     return false;
34221
34222   if (lookup_attribute ("ifunc", DECL_ATTRIBUTES (n->decl)))
34223     return false;
34224
34225   /* Prevent assemble_alias from trying to use .set pseudo operation
34226      that does not behave as expected by the middle-end.  */
34227   TREE_ASM_WRITTEN (n->decl) = true;
34228
34229   const char *name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (n->decl));
34230   char *buffer = (char *) alloca (strlen (name) + 2);
34231   char *p;
34232   int dollar_inside = 0;
34233
34234   strcpy (buffer, name);
34235   p = strchr (buffer, '$');
34236   while (p) {
34237     *p = '_';
34238     dollar_inside++;
34239     p = strchr (p + 1, '$');
34240   }
34241   if (TREE_PUBLIC (n->decl))
34242     {
34243       if (!RS6000_WEAK || !DECL_WEAK (n->decl))
34244         {
34245           if (dollar_inside) {
34246               if (data->function_descriptor)
34247                 fprintf(data->file, "\t.rename .%s,\".%s\"\n", buffer, name);
34248               fprintf(data->file, "\t.rename %s,\"%s\"\n", buffer, name);
34249             }
34250           if (data->function_descriptor)
34251             {
34252               fputs ("\t.globl .", data->file);
34253               RS6000_OUTPUT_BASENAME (data->file, buffer);
34254               putc ('\n', data->file);
34255             }
34256           fputs ("\t.globl ", data->file);
34257           RS6000_OUTPUT_BASENAME (data->file, buffer);
34258           putc ('\n', data->file);
34259         }
34260 #ifdef ASM_WEAKEN_DECL
34261       else if (DECL_WEAK (n->decl) && !data->function_descriptor)
34262         ASM_WEAKEN_DECL (data->file, n->decl, name, NULL);
34263 #endif
34264     }
34265   else
34266     {
34267       if (dollar_inside)
34268         {
34269           if (data->function_descriptor)
34270             fprintf(data->file, "\t.rename .%s,\".%s\"\n", buffer, name);
34271           fprintf(data->file, "\t.rename %s,\"%s\"\n", buffer, name);
34272         }
34273       if (data->function_descriptor)
34274         {
34275           fputs ("\t.lglobl .", data->file);
34276           RS6000_OUTPUT_BASENAME (data->file, buffer);
34277           putc ('\n', data->file);
34278         }
34279       fputs ("\t.lglobl ", data->file);
34280       RS6000_OUTPUT_BASENAME (data->file, buffer);
34281       putc ('\n', data->file);
34282     }
34283   if (data->function_descriptor)
34284     fputs (".", data->file);
34285   RS6000_OUTPUT_BASENAME (data->file, buffer);
34286   fputs (":\n", data->file);
34287   return false;
34288 }
34289
34290
34291 #ifdef HAVE_GAS_HIDDEN
34292 /* Helper function to calculate visibility of a DECL
34293    and return the value as a const string.  */
34294
34295 static const char *
34296 rs6000_xcoff_visibility (tree decl)
34297 {
34298   static const char * const visibility_types[] = {
34299     "", ",protected", ",hidden", ",internal"
34300   };
34301
34302   enum symbol_visibility vis = DECL_VISIBILITY (decl);
34303
34304   if (TREE_CODE (decl) == FUNCTION_DECL
34305       && cgraph_node::get (decl)
34306       && cgraph_node::get (decl)->instrumentation_clone
34307       && cgraph_node::get (decl)->instrumented_version)
34308     vis = DECL_VISIBILITY (cgraph_node::get (decl)->instrumented_version->decl);
34309
34310   return visibility_types[vis];
34311 }
34312 #endif
34313
34314
34315 /* This macro produces the initial definition of a function name.
34316    On the RS/6000, we need to place an extra '.' in the function name and
34317    output the function descriptor.
34318    Dollar signs are converted to underscores.
34319
34320    The csect for the function will have already been created when
34321    text_section was selected.  We do have to go back to that csect, however.
34322
34323    The third and fourth parameters to the .function pseudo-op (16 and 044)
34324    are placeholders which no longer have any use.
34325
34326    Because AIX assembler's .set command has unexpected semantics, we output
34327    all aliases as alternative labels in front of the definition.  */
34328
34329 void
34330 rs6000_xcoff_declare_function_name (FILE *file, const char *name, tree decl)
34331 {
34332   char *buffer = (char *) alloca (strlen (name) + 1);
34333   char *p;
34334   int dollar_inside = 0;
34335   struct declare_alias_data data = {file, false};
34336
34337   strcpy (buffer, name);
34338   p = strchr (buffer, '$');
34339   while (p) {
34340     *p = '_';
34341     dollar_inside++;
34342     p = strchr (p + 1, '$');
34343   }
34344   if (TREE_PUBLIC (decl))
34345     {
34346       if (!RS6000_WEAK || !DECL_WEAK (decl))
34347         {
34348           if (dollar_inside) {
34349               fprintf(file, "\t.rename .%s,\".%s\"\n", buffer, name);
34350               fprintf(file, "\t.rename %s,\"%s\"\n", buffer, name);
34351             }
34352           fputs ("\t.globl .", file);
34353           RS6000_OUTPUT_BASENAME (file, buffer);
34354 #ifdef HAVE_GAS_HIDDEN
34355           fputs (rs6000_xcoff_visibility (decl), file);
34356 #endif
34357           putc ('\n', file);
34358         }
34359     }
34360   else
34361     {
34362       if (dollar_inside) {
34363           fprintf(file, "\t.rename .%s,\".%s\"\n", buffer, name);
34364           fprintf(file, "\t.rename %s,\"%s\"\n", buffer, name);
34365         }
34366       fputs ("\t.lglobl .", file);
34367       RS6000_OUTPUT_BASENAME (file, buffer);
34368       putc ('\n', file);
34369     }
34370   fputs ("\t.csect ", file);
34371   RS6000_OUTPUT_BASENAME (file, buffer);
34372   fputs (TARGET_32BIT ? "[DS]\n" : "[DS],3\n", file);
34373   RS6000_OUTPUT_BASENAME (file, buffer);
34374   fputs (":\n", file);
34375   symtab_node::get (decl)->call_for_symbol_and_aliases (rs6000_declare_alias,
34376                                                         &data, true);
34377   fputs (TARGET_32BIT ? "\t.long ." : "\t.llong .", file);
34378   RS6000_OUTPUT_BASENAME (file, buffer);
34379   fputs (", TOC[tc0], 0\n", file);
34380   in_section = NULL;
34381   switch_to_section (function_section (decl));
34382   putc ('.', file);
34383   RS6000_OUTPUT_BASENAME (file, buffer);
34384   fputs (":\n", file);
34385   data.function_descriptor = true;
34386   symtab_node::get (decl)->call_for_symbol_and_aliases (rs6000_declare_alias,
34387                                                         &data, true);
34388   if (!DECL_IGNORED_P (decl))
34389     {
34390       if (write_symbols == DBX_DEBUG || write_symbols == XCOFF_DEBUG)
34391         xcoffout_declare_function (file, decl, buffer);
34392       else if (write_symbols == DWARF2_DEBUG)
34393         {
34394           name = (*targetm.strip_name_encoding) (name);
34395           fprintf (file, "\t.function .%s,.%s,2,0\n", name, name);
34396         }
34397     }
34398   return;
34399 }
34400
34401
34402 /* Output assembly language to globalize a symbol from a DECL,
34403    possibly with visibility.  */
34404
34405 void
34406 rs6000_xcoff_asm_globalize_decl_name (FILE *stream, tree decl)
34407 {
34408   const char *name = XSTR (XEXP (DECL_RTL (decl), 0), 0);
34409   fputs (GLOBAL_ASM_OP, stream);
34410   RS6000_OUTPUT_BASENAME (stream, name);
34411 #ifdef HAVE_GAS_HIDDEN
34412   fputs (rs6000_xcoff_visibility (decl), stream);
34413 #endif
34414   putc ('\n', stream);
34415 }
34416
34417 /* Output assembly language to define a symbol as COMMON from a DECL,
34418    possibly with visibility.  */
34419
34420 void
34421 rs6000_xcoff_asm_output_aligned_decl_common (FILE *stream,
34422                                              tree decl ATTRIBUTE_UNUSED,
34423                                              const char *name,
34424                                              unsigned HOST_WIDE_INT size,
34425                                              unsigned HOST_WIDE_INT align)
34426 {
34427   unsigned HOST_WIDE_INT align2 = 2;
34428
34429   if (align > 32)
34430     align2 = floor_log2 (align / BITS_PER_UNIT);
34431   else if (size > 4)
34432     align2 = 3;
34433
34434   fputs (COMMON_ASM_OP, stream);
34435   RS6000_OUTPUT_BASENAME (stream, name);
34436
34437   fprintf (stream,
34438            "," HOST_WIDE_INT_PRINT_UNSIGNED "," HOST_WIDE_INT_PRINT_UNSIGNED,
34439            size, align2);
34440
34441 #ifdef HAVE_GAS_HIDDEN
34442   if (decl != NULL)
34443     fputs (rs6000_xcoff_visibility (decl), stream);
34444 #endif
34445   putc ('\n', stream);
34446 }
34447
34448 /* This macro produces the initial definition of a object (variable) name.
34449    Because AIX assembler's .set command has unexpected semantics, we output
34450    all aliases as alternative labels in front of the definition.  */
34451
34452 void
34453 rs6000_xcoff_declare_object_name (FILE *file, const char *name, tree decl)
34454 {
34455   struct declare_alias_data data = {file, false};
34456   RS6000_OUTPUT_BASENAME (file, name);
34457   fputs (":\n", file);
34458   symtab_node::get_create (decl)->call_for_symbol_and_aliases (rs6000_declare_alias,
34459                                                                &data, true);
34460 }
34461
34462 /* Overide the default 'SYMBOL-.' syntax with AIX compatible 'SYMBOL-$'. */
34463
34464 void
34465 rs6000_asm_output_dwarf_pcrel (FILE *file, int size, const char *label)
34466 {
34467   fputs (integer_asm_op (size, FALSE), file);
34468   assemble_name (file, label);
34469   fputs ("-$", file);
34470 }
34471
34472 /* Output a symbol offset relative to the dbase for the current object.
34473    We use __gcc_unwind_dbase as an arbitrary base for dbase and assume
34474    signed offsets.
34475
34476    __gcc_unwind_dbase is embedded in all executables/libraries through
34477    libgcc/config/rs6000/crtdbase.S.  */
34478
34479 void
34480 rs6000_asm_output_dwarf_datarel (FILE *file, int size, const char *label)
34481 {
34482   fputs (integer_asm_op (size, FALSE), file);
34483   assemble_name (file, label);
34484   fputs("-__gcc_unwind_dbase", file);
34485 }
34486
34487 #ifdef HAVE_AS_TLS
34488 static void
34489 rs6000_xcoff_encode_section_info (tree decl, rtx rtl, int first)
34490 {
34491   rtx symbol;
34492   int flags;
34493   const char *symname;
34494
34495   default_encode_section_info (decl, rtl, first);
34496
34497   /* Careful not to prod global register variables.  */
34498   if (!MEM_P (rtl))
34499     return;
34500   symbol = XEXP (rtl, 0);
34501   if (GET_CODE (symbol) != SYMBOL_REF)
34502     return;
34503
34504   flags = SYMBOL_REF_FLAGS (symbol);
34505
34506   if (TREE_CODE (decl) == VAR_DECL && DECL_THREAD_LOCAL_P (decl))
34507     flags &= ~SYMBOL_FLAG_HAS_BLOCK_INFO;
34508
34509   SYMBOL_REF_FLAGS (symbol) = flags;
34510
34511   /* Append mapping class to extern decls.  */
34512   symname = XSTR (symbol, 0);
34513   if (decl /* sync condition with assemble_external () */
34514       && DECL_P (decl) && DECL_EXTERNAL (decl) && TREE_PUBLIC (decl)
34515       && ((TREE_CODE (decl) == VAR_DECL && !DECL_THREAD_LOCAL_P (decl))
34516           || TREE_CODE (decl) == FUNCTION_DECL)
34517       && symname[strlen (symname) - 1] != ']')
34518     {
34519       char *newname = (char *) alloca (strlen (symname) + 5);
34520       strcpy (newname, symname);
34521       strcat (newname, (TREE_CODE (decl) == FUNCTION_DECL
34522                         ? "[DS]" : "[UA]"));
34523       XSTR (symbol, 0) = ggc_strdup (newname);
34524     }
34525 }
34526 #endif /* HAVE_AS_TLS */
34527 #endif /* TARGET_XCOFF */
34528
34529 void
34530 rs6000_asm_weaken_decl (FILE *stream, tree decl,
34531                         const char *name, const char *val)
34532 {
34533   fputs ("\t.weak\t", stream);
34534   RS6000_OUTPUT_BASENAME (stream, name);
34535   if (decl && TREE_CODE (decl) == FUNCTION_DECL
34536       && DEFAULT_ABI == ABI_AIX && DOT_SYMBOLS)
34537     {
34538       if (TARGET_XCOFF)                                         
34539         fputs ("[DS]", stream);
34540 #if TARGET_XCOFF && HAVE_GAS_HIDDEN
34541       if (TARGET_XCOFF)
34542         fputs (rs6000_xcoff_visibility (decl), stream);
34543 #endif
34544       fputs ("\n\t.weak\t.", stream);
34545       RS6000_OUTPUT_BASENAME (stream, name);
34546     }
34547 #if TARGET_XCOFF && HAVE_GAS_HIDDEN
34548   if (TARGET_XCOFF)
34549     fputs (rs6000_xcoff_visibility (decl), stream);
34550 #endif
34551   fputc ('\n', stream);
34552   if (val)
34553     {
34554 #ifdef ASM_OUTPUT_DEF
34555       ASM_OUTPUT_DEF (stream, name, val);
34556 #endif
34557       if (decl && TREE_CODE (decl) == FUNCTION_DECL
34558           && DEFAULT_ABI == ABI_AIX && DOT_SYMBOLS)
34559         {
34560           fputs ("\t.set\t.", stream);
34561           RS6000_OUTPUT_BASENAME (stream, name);
34562           fputs (",.", stream);
34563           RS6000_OUTPUT_BASENAME (stream, val);
34564           fputc ('\n', stream);
34565         }
34566     }
34567 }
34568
34569
34570 /* Return true if INSN should not be copied.  */
34571
34572 static bool
34573 rs6000_cannot_copy_insn_p (rtx_insn *insn)
34574 {
34575   return recog_memoized (insn) >= 0
34576          && get_attr_cannot_copy (insn);
34577 }
34578
34579 /* Compute a (partial) cost for rtx X.  Return true if the complete
34580    cost has been computed, and false if subexpressions should be
34581    scanned.  In either case, *TOTAL contains the cost result.  */
34582
34583 static bool
34584 rs6000_rtx_costs (rtx x, machine_mode mode, int outer_code,
34585                   int opno ATTRIBUTE_UNUSED, int *total, bool speed)
34586 {
34587   int code = GET_CODE (x);
34588
34589   switch (code)
34590     {
34591       /* On the RS/6000, if it is valid in the insn, it is free.  */
34592     case CONST_INT:
34593       if (((outer_code == SET
34594             || outer_code == PLUS
34595             || outer_code == MINUS)
34596            && (satisfies_constraint_I (x)
34597                || satisfies_constraint_L (x)))
34598           || (outer_code == AND
34599               && (satisfies_constraint_K (x)
34600                   || (mode == SImode
34601                       ? satisfies_constraint_L (x)
34602                       : satisfies_constraint_J (x))))
34603           || ((outer_code == IOR || outer_code == XOR)
34604               && (satisfies_constraint_K (x)
34605                   || (mode == SImode
34606                       ? satisfies_constraint_L (x)
34607                       : satisfies_constraint_J (x))))
34608           || outer_code == ASHIFT
34609           || outer_code == ASHIFTRT
34610           || outer_code == LSHIFTRT
34611           || outer_code == ROTATE
34612           || outer_code == ROTATERT
34613           || outer_code == ZERO_EXTRACT
34614           || (outer_code == MULT
34615               && satisfies_constraint_I (x))
34616           || ((outer_code == DIV || outer_code == UDIV
34617                || outer_code == MOD || outer_code == UMOD)
34618               && exact_log2 (INTVAL (x)) >= 0)
34619           || (outer_code == COMPARE
34620               && (satisfies_constraint_I (x)
34621                   || satisfies_constraint_K (x)))
34622           || ((outer_code == EQ || outer_code == NE)
34623               && (satisfies_constraint_I (x)
34624                   || satisfies_constraint_K (x)
34625                   || (mode == SImode
34626                       ? satisfies_constraint_L (x)
34627                       : satisfies_constraint_J (x))))
34628           || (outer_code == GTU
34629               && satisfies_constraint_I (x))
34630           || (outer_code == LTU
34631               && satisfies_constraint_P (x)))
34632         {
34633           *total = 0;
34634           return true;
34635         }
34636       else if ((outer_code == PLUS
34637                 && reg_or_add_cint_operand (x, VOIDmode))
34638                || (outer_code == MINUS
34639                    && reg_or_sub_cint_operand (x, VOIDmode))
34640                || ((outer_code == SET
34641                     || outer_code == IOR
34642                     || outer_code == XOR)
34643                    && (INTVAL (x)
34644                        & ~ (unsigned HOST_WIDE_INT) 0xffffffff) == 0))
34645         {
34646           *total = COSTS_N_INSNS (1);
34647           return true;
34648         }
34649       /* FALLTHRU */
34650
34651     case CONST_DOUBLE:
34652     case CONST_WIDE_INT:
34653     case CONST:
34654     case HIGH:
34655     case SYMBOL_REF:
34656       *total = !speed ? COSTS_N_INSNS (1) + 1 : COSTS_N_INSNS (2);
34657       return true;
34658
34659     case MEM:
34660       /* When optimizing for size, MEM should be slightly more expensive
34661          than generating address, e.g., (plus (reg) (const)).
34662          L1 cache latency is about two instructions.  */
34663       *total = !speed ? COSTS_N_INSNS (1) + 1 : COSTS_N_INSNS (2);
34664       if (rs6000_slow_unaligned_access (mode, MEM_ALIGN (x)))
34665         *total += COSTS_N_INSNS (100);
34666       return true;
34667
34668     case LABEL_REF:
34669       *total = 0;
34670       return true;
34671
34672     case PLUS:
34673     case MINUS:
34674       if (FLOAT_MODE_P (mode))
34675         *total = rs6000_cost->fp;
34676       else
34677         *total = COSTS_N_INSNS (1);
34678       return false;
34679
34680     case MULT:
34681       if (GET_CODE (XEXP (x, 1)) == CONST_INT
34682           && satisfies_constraint_I (XEXP (x, 1)))
34683         {
34684           if (INTVAL (XEXP (x, 1)) >= -256
34685               && INTVAL (XEXP (x, 1)) <= 255)
34686             *total = rs6000_cost->mulsi_const9;
34687           else
34688             *total = rs6000_cost->mulsi_const;
34689         }
34690       else if (mode == SFmode)
34691         *total = rs6000_cost->fp;
34692       else if (FLOAT_MODE_P (mode))
34693         *total = rs6000_cost->dmul;
34694       else if (mode == DImode)
34695         *total = rs6000_cost->muldi;
34696       else
34697         *total = rs6000_cost->mulsi;
34698       return false;
34699
34700     case FMA:
34701       if (mode == SFmode)
34702         *total = rs6000_cost->fp;
34703       else
34704         *total = rs6000_cost->dmul;
34705       break;
34706
34707     case DIV:
34708     case MOD:
34709       if (FLOAT_MODE_P (mode))
34710         {
34711           *total = mode == DFmode ? rs6000_cost->ddiv
34712                                   : rs6000_cost->sdiv;
34713           return false;
34714         }
34715       /* FALLTHRU */
34716
34717     case UDIV:
34718     case UMOD:
34719       if (GET_CODE (XEXP (x, 1)) == CONST_INT
34720           && exact_log2 (INTVAL (XEXP (x, 1))) >= 0)
34721         {
34722           if (code == DIV || code == MOD)
34723             /* Shift, addze */
34724             *total = COSTS_N_INSNS (2);
34725           else
34726             /* Shift */
34727             *total = COSTS_N_INSNS (1);
34728         }
34729       else
34730         {
34731           if (GET_MODE (XEXP (x, 1)) == DImode)
34732             *total = rs6000_cost->divdi;
34733           else
34734             *total = rs6000_cost->divsi;
34735         }
34736       /* Add in shift and subtract for MOD unless we have a mod instruction. */
34737       if (!TARGET_MODULO && (code == MOD || code == UMOD))
34738         *total += COSTS_N_INSNS (2);
34739       return false;
34740
34741     case CTZ:
34742       *total = COSTS_N_INSNS (TARGET_CTZ ? 1 : 4);
34743       return false;
34744
34745     case FFS:
34746       *total = COSTS_N_INSNS (4);
34747       return false;
34748
34749     case POPCOUNT:
34750       *total = COSTS_N_INSNS (TARGET_POPCNTD ? 1 : 6);
34751       return false;
34752
34753     case PARITY:
34754       *total = COSTS_N_INSNS (TARGET_CMPB ? 2 : 6);
34755       return false;
34756
34757     case NOT:
34758       if (outer_code == AND || outer_code == IOR || outer_code == XOR)
34759         *total = 0;
34760       else
34761         *total = COSTS_N_INSNS (1);
34762       return false;
34763
34764     case AND:
34765       if (CONST_INT_P (XEXP (x, 1)))
34766         {
34767           rtx left = XEXP (x, 0);
34768           rtx_code left_code = GET_CODE (left);
34769
34770           /* rotate-and-mask: 1 insn.  */
34771           if ((left_code == ROTATE
34772                || left_code == ASHIFT
34773                || left_code == LSHIFTRT)
34774               && rs6000_is_valid_shift_mask (XEXP (x, 1), left, mode))
34775             {
34776               *total = rtx_cost (XEXP (left, 0), mode, left_code, 0, speed);
34777               if (!CONST_INT_P (XEXP (left, 1)))
34778                 *total += rtx_cost (XEXP (left, 1), SImode, left_code, 1, speed);
34779               *total += COSTS_N_INSNS (1);
34780               return true;
34781             }
34782
34783           /* rotate-and-mask (no rotate), andi., andis.: 1 insn.  */
34784           HOST_WIDE_INT val = INTVAL (XEXP (x, 1));
34785           if (rs6000_is_valid_and_mask (XEXP (x, 1), mode)
34786               || (val & 0xffff) == val
34787               || (val & 0xffff0000) == val
34788               || ((val & 0xffff) == 0 && mode == SImode))
34789             {
34790               *total = rtx_cost (left, mode, AND, 0, speed);
34791               *total += COSTS_N_INSNS (1);
34792               return true;
34793             }
34794
34795           /* 2 insns.  */
34796           if (rs6000_is_valid_2insn_and (XEXP (x, 1), mode))
34797             {
34798               *total = rtx_cost (left, mode, AND, 0, speed);
34799               *total += COSTS_N_INSNS (2);
34800               return true;
34801             }
34802         }
34803
34804       *total = COSTS_N_INSNS (1);
34805       return false;
34806
34807     case IOR:
34808       /* FIXME */
34809       *total = COSTS_N_INSNS (1);
34810       return true;
34811
34812     case CLZ:
34813     case XOR:
34814     case ZERO_EXTRACT:
34815       *total = COSTS_N_INSNS (1);
34816       return false;
34817
34818     case ASHIFT:
34819       /* The EXTSWSLI instruction is a combined instruction.  Don't count both
34820          the sign extend and shift separately within the insn.  */
34821       if (TARGET_EXTSWSLI && mode == DImode
34822           && GET_CODE (XEXP (x, 0)) == SIGN_EXTEND
34823           && GET_MODE (XEXP (XEXP (x, 0), 0)) == SImode)
34824         {
34825           *total = 0;
34826           return false;
34827         }
34828       /* fall through */
34829           
34830     case ASHIFTRT:
34831     case LSHIFTRT:
34832     case ROTATE:
34833     case ROTATERT:
34834       /* Handle mul_highpart.  */
34835       if (outer_code == TRUNCATE
34836           && GET_CODE (XEXP (x, 0)) == MULT)
34837         {
34838           if (mode == DImode)
34839             *total = rs6000_cost->muldi;
34840           else
34841             *total = rs6000_cost->mulsi;
34842           return true;
34843         }
34844       else if (outer_code == AND)
34845         *total = 0;
34846       else
34847         *total = COSTS_N_INSNS (1);
34848       return false;
34849
34850     case SIGN_EXTEND:
34851     case ZERO_EXTEND:
34852       if (GET_CODE (XEXP (x, 0)) == MEM)
34853         *total = 0;
34854       else
34855         *total = COSTS_N_INSNS (1);
34856       return false;
34857
34858     case COMPARE:
34859     case NEG:
34860     case ABS:
34861       if (!FLOAT_MODE_P (mode))
34862         {
34863           *total = COSTS_N_INSNS (1);
34864           return false;
34865         }
34866       /* FALLTHRU */
34867
34868     case FLOAT:
34869     case UNSIGNED_FLOAT:
34870     case FIX:
34871     case UNSIGNED_FIX:
34872     case FLOAT_TRUNCATE:
34873       *total = rs6000_cost->fp;
34874       return false;
34875
34876     case FLOAT_EXTEND:
34877       if (mode == DFmode)
34878         *total = rs6000_cost->sfdf_convert;
34879       else
34880         *total = rs6000_cost->fp;
34881       return false;
34882
34883     case UNSPEC:
34884       switch (XINT (x, 1))
34885         {
34886         case UNSPEC_FRSP:
34887           *total = rs6000_cost->fp;
34888           return true;
34889
34890         default:
34891           break;
34892         }
34893       break;
34894
34895     case CALL:
34896     case IF_THEN_ELSE:
34897       if (!speed)
34898         {
34899           *total = COSTS_N_INSNS (1);
34900           return true;
34901         }
34902       else if (FLOAT_MODE_P (mode) && TARGET_PPC_GFXOPT && TARGET_HARD_FLOAT)
34903         {
34904           *total = rs6000_cost->fp;
34905           return false;
34906         }
34907       break;
34908
34909     case NE:
34910     case EQ:
34911     case GTU:
34912     case LTU:
34913       /* Carry bit requires mode == Pmode.
34914          NEG or PLUS already counted so only add one.  */
34915       if (mode == Pmode
34916           && (outer_code == NEG || outer_code == PLUS))
34917         {
34918           *total = COSTS_N_INSNS (1);
34919           return true;
34920         }
34921       /* FALLTHRU */
34922
34923     case GT:
34924     case LT:
34925     case UNORDERED:
34926       if (outer_code == SET)
34927         {
34928           if (XEXP (x, 1) == const0_rtx)
34929             {
34930               *total = COSTS_N_INSNS (2);
34931               return true;
34932             }
34933           else
34934             {
34935               *total = COSTS_N_INSNS (3);
34936               return false;
34937             }
34938         }
34939       /* CC COMPARE.  */
34940       if (outer_code == COMPARE)
34941         {
34942           *total = 0;
34943           return true;
34944         }
34945       break;
34946
34947     default:
34948       break;
34949     }
34950
34951   return false;
34952 }
34953
34954 /* Debug form of r6000_rtx_costs that is selected if -mdebug=cost.  */
34955
34956 static bool
34957 rs6000_debug_rtx_costs (rtx x, machine_mode mode, int outer_code,
34958                         int opno, int *total, bool speed)
34959 {
34960   bool ret = rs6000_rtx_costs (x, mode, outer_code, opno, total, speed);
34961
34962   fprintf (stderr,
34963            "\nrs6000_rtx_costs, return = %s, mode = %s, outer_code = %s, "
34964            "opno = %d, total = %d, speed = %s, x:\n",
34965            ret ? "complete" : "scan inner",
34966            GET_MODE_NAME (mode),
34967            GET_RTX_NAME (outer_code),
34968            opno,
34969            *total,
34970            speed ? "true" : "false");
34971
34972   debug_rtx (x);
34973
34974   return ret;
34975 }
34976
34977 static int
34978 rs6000_insn_cost (rtx_insn *insn, bool speed)
34979 {
34980   if (recog_memoized (insn) < 0)
34981     return 0;
34982
34983   if (!speed)
34984     return get_attr_length (insn);
34985
34986   int cost = get_attr_cost (insn);
34987   if (cost > 0)
34988     return cost;
34989
34990   int n = get_attr_length (insn) / 4;
34991   enum attr_type type = get_attr_type (insn);
34992
34993   switch (type)
34994     {
34995     case TYPE_LOAD:
34996     case TYPE_FPLOAD:
34997     case TYPE_VECLOAD:
34998       cost = COSTS_N_INSNS (n + 1);
34999       break;
35000
35001     case TYPE_MUL:
35002       switch (get_attr_size (insn))
35003         {
35004         case SIZE_8:
35005           cost = COSTS_N_INSNS (n - 1) + rs6000_cost->mulsi_const9;
35006           break;
35007         case SIZE_16:
35008           cost = COSTS_N_INSNS (n - 1) + rs6000_cost->mulsi_const;
35009           break;
35010         case SIZE_32:
35011           cost = COSTS_N_INSNS (n - 1) + rs6000_cost->mulsi;
35012           break;
35013         case SIZE_64:
35014           cost = COSTS_N_INSNS (n - 1) + rs6000_cost->muldi;
35015           break;
35016         default:
35017           gcc_unreachable ();
35018         }
35019       break;
35020     case TYPE_DIV:
35021       switch (get_attr_size (insn))
35022         {
35023         case SIZE_32:
35024           cost = COSTS_N_INSNS (n - 1) + rs6000_cost->divsi;
35025           break;
35026         case SIZE_64:
35027           cost = COSTS_N_INSNS (n - 1) + rs6000_cost->divdi;
35028           break;
35029         default:
35030           gcc_unreachable ();
35031         }
35032       break;
35033
35034     case TYPE_FP:
35035       cost = n * rs6000_cost->fp;
35036       break;
35037     case TYPE_DMUL:
35038       cost = n * rs6000_cost->dmul;
35039       break;
35040     case TYPE_SDIV:
35041       cost = n * rs6000_cost->sdiv;
35042       break;
35043     case TYPE_DDIV:
35044       cost = n * rs6000_cost->ddiv;
35045       break;
35046
35047     case TYPE_SYNC:
35048     case TYPE_LOAD_L:
35049     case TYPE_MFCR:
35050     case TYPE_MFCRF:
35051       cost = COSTS_N_INSNS (n + 2);
35052       break;
35053
35054     default:
35055       cost = COSTS_N_INSNS (n);
35056     }
35057
35058   return cost;
35059 }
35060
35061 /* Debug form of ADDRESS_COST that is selected if -mdebug=cost.  */
35062
35063 static int
35064 rs6000_debug_address_cost (rtx x, machine_mode mode,
35065                            addr_space_t as, bool speed)
35066 {
35067   int ret = TARGET_ADDRESS_COST (x, mode, as, speed);
35068
35069   fprintf (stderr, "\nrs6000_address_cost, return = %d, speed = %s, x:\n",
35070            ret, speed ? "true" : "false");
35071   debug_rtx (x);
35072
35073   return ret;
35074 }
35075
35076
35077 /* A C expression returning the cost of moving data from a register of class
35078    CLASS1 to one of CLASS2.  */
35079
35080 static int
35081 rs6000_register_move_cost (machine_mode mode,
35082                            reg_class_t from, reg_class_t to)
35083 {
35084   int ret;
35085
35086   if (TARGET_DEBUG_COST)
35087     dbg_cost_ctrl++;
35088
35089   /*  Moves from/to GENERAL_REGS.  */
35090   if (reg_classes_intersect_p (to, GENERAL_REGS)
35091       || reg_classes_intersect_p (from, GENERAL_REGS))
35092     {
35093       reg_class_t rclass = from;
35094
35095       if (! reg_classes_intersect_p (to, GENERAL_REGS))
35096         rclass = to;
35097
35098       if (rclass == FLOAT_REGS || rclass == ALTIVEC_REGS || rclass == VSX_REGS)
35099         ret = (rs6000_memory_move_cost (mode, rclass, false)
35100                + rs6000_memory_move_cost (mode, GENERAL_REGS, false));
35101
35102       /* It's more expensive to move CR_REGS than CR0_REGS because of the
35103          shift.  */
35104       else if (rclass == CR_REGS)
35105         ret = 4;
35106
35107       /* For those processors that have slow LR/CTR moves, make them more
35108          expensive than memory in order to bias spills to memory .*/
35109       else if ((rs6000_tune == PROCESSOR_POWER6
35110                 || rs6000_tune == PROCESSOR_POWER7
35111                 || rs6000_tune == PROCESSOR_POWER8
35112                 || rs6000_tune == PROCESSOR_POWER9)
35113                && reg_classes_intersect_p (rclass, LINK_OR_CTR_REGS))
35114         ret = 6 * hard_regno_nregs (0, mode);
35115
35116       else
35117         /* A move will cost one instruction per GPR moved.  */
35118         ret = 2 * hard_regno_nregs (0, mode);
35119     }
35120
35121   /* If we have VSX, we can easily move between FPR or Altivec registers.  */
35122   else if (VECTOR_MEM_VSX_P (mode)
35123            && reg_classes_intersect_p (to, VSX_REGS)
35124            && reg_classes_intersect_p (from, VSX_REGS))
35125     ret = 2 * hard_regno_nregs (FIRST_FPR_REGNO, mode);
35126
35127   /* Moving between two similar registers is just one instruction.  */
35128   else if (reg_classes_intersect_p (to, from))
35129     ret = (FLOAT128_2REG_P (mode)) ? 4 : 2;
35130
35131   /* Everything else has to go through GENERAL_REGS.  */
35132   else
35133     ret = (rs6000_register_move_cost (mode, GENERAL_REGS, to)
35134            + rs6000_register_move_cost (mode, from, GENERAL_REGS));
35135
35136   if (TARGET_DEBUG_COST)
35137     {
35138       if (dbg_cost_ctrl == 1)
35139         fprintf (stderr,
35140                  "rs6000_register_move_cost:, ret=%d, mode=%s, from=%s, to=%s\n",
35141                  ret, GET_MODE_NAME (mode), reg_class_names[from],
35142                  reg_class_names[to]);
35143       dbg_cost_ctrl--;
35144     }
35145
35146   return ret;
35147 }
35148
35149 /* A C expressions returning the cost of moving data of MODE from a register to
35150    or from memory.  */
35151
35152 static int
35153 rs6000_memory_move_cost (machine_mode mode, reg_class_t rclass,
35154                          bool in ATTRIBUTE_UNUSED)
35155 {
35156   int ret;
35157
35158   if (TARGET_DEBUG_COST)
35159     dbg_cost_ctrl++;
35160
35161   if (reg_classes_intersect_p (rclass, GENERAL_REGS))
35162     ret = 4 * hard_regno_nregs (0, mode);
35163   else if ((reg_classes_intersect_p (rclass, FLOAT_REGS)
35164             || reg_classes_intersect_p (rclass, VSX_REGS)))
35165     ret = 4 * hard_regno_nregs (32, mode);
35166   else if (reg_classes_intersect_p (rclass, ALTIVEC_REGS))
35167     ret = 4 * hard_regno_nregs (FIRST_ALTIVEC_REGNO, mode);
35168   else
35169     ret = 4 + rs6000_register_move_cost (mode, rclass, GENERAL_REGS);
35170
35171   if (TARGET_DEBUG_COST)
35172     {
35173       if (dbg_cost_ctrl == 1)
35174         fprintf (stderr,
35175                  "rs6000_memory_move_cost: ret=%d, mode=%s, rclass=%s, in=%d\n",
35176                  ret, GET_MODE_NAME (mode), reg_class_names[rclass], in);
35177       dbg_cost_ctrl--;
35178     }
35179
35180   return ret;
35181 }
35182
35183 /* Returns a code for a target-specific builtin that implements
35184    reciprocal of the function, or NULL_TREE if not available.  */
35185
35186 static tree
35187 rs6000_builtin_reciprocal (tree fndecl)
35188 {
35189   switch (DECL_FUNCTION_CODE (fndecl))
35190     {
35191     case VSX_BUILTIN_XVSQRTDP:
35192       if (!RS6000_RECIP_AUTO_RSQRTE_P (V2DFmode))
35193         return NULL_TREE;
35194
35195       return rs6000_builtin_decls[VSX_BUILTIN_RSQRT_2DF];
35196
35197     case VSX_BUILTIN_XVSQRTSP:
35198       if (!RS6000_RECIP_AUTO_RSQRTE_P (V4SFmode))
35199         return NULL_TREE;
35200
35201       return rs6000_builtin_decls[VSX_BUILTIN_RSQRT_4SF];
35202
35203     default:
35204       return NULL_TREE;
35205     }
35206 }
35207
35208 /* Load up a constant.  If the mode is a vector mode, splat the value across
35209    all of the vector elements.  */
35210
35211 static rtx
35212 rs6000_load_constant_and_splat (machine_mode mode, REAL_VALUE_TYPE dconst)
35213 {
35214   rtx reg;
35215
35216   if (mode == SFmode || mode == DFmode)
35217     {
35218       rtx d = const_double_from_real_value (dconst, mode);
35219       reg = force_reg (mode, d);
35220     }
35221   else if (mode == V4SFmode)
35222     {
35223       rtx d = const_double_from_real_value (dconst, SFmode);
35224       rtvec v = gen_rtvec (4, d, d, d, d);
35225       reg = gen_reg_rtx (mode);
35226       rs6000_expand_vector_init (reg, gen_rtx_PARALLEL (mode, v));
35227     }
35228   else if (mode == V2DFmode)
35229     {
35230       rtx d = const_double_from_real_value (dconst, DFmode);
35231       rtvec v = gen_rtvec (2, d, d);
35232       reg = gen_reg_rtx (mode);
35233       rs6000_expand_vector_init (reg, gen_rtx_PARALLEL (mode, v));
35234     }
35235   else
35236     gcc_unreachable ();
35237
35238   return reg;
35239 }
35240
35241 /* Generate an FMA instruction.  */
35242
35243 static void
35244 rs6000_emit_madd (rtx target, rtx m1, rtx m2, rtx a)
35245 {
35246   machine_mode mode = GET_MODE (target);
35247   rtx dst;
35248
35249   dst = expand_ternary_op (mode, fma_optab, m1, m2, a, target, 0);
35250   gcc_assert (dst != NULL);
35251
35252   if (dst != target)
35253     emit_move_insn (target, dst);
35254 }
35255
35256 /* Generate a FNMSUB instruction: dst = -fma(m1, m2, -a).  */
35257
35258 static void
35259 rs6000_emit_nmsub (rtx dst, rtx m1, rtx m2, rtx a)
35260 {
35261   machine_mode mode = GET_MODE (dst);
35262   rtx r;
35263
35264   /* This is a tad more complicated, since the fnma_optab is for
35265      a different expression: fma(-m1, m2, a), which is the same
35266      thing except in the case of signed zeros.
35267
35268      Fortunately we know that if FMA is supported that FNMSUB is
35269      also supported in the ISA.  Just expand it directly.  */
35270
35271   gcc_assert (optab_handler (fma_optab, mode) != CODE_FOR_nothing);
35272
35273   r = gen_rtx_NEG (mode, a);
35274   r = gen_rtx_FMA (mode, m1, m2, r);
35275   r = gen_rtx_NEG (mode, r);
35276   emit_insn (gen_rtx_SET (dst, r));
35277 }
35278
35279 /* Newton-Raphson approximation of floating point divide DST = N/D.  If NOTE_P,
35280    add a reg_note saying that this was a division.  Support both scalar and
35281    vector divide.  Assumes no trapping math and finite arguments.  */
35282
35283 void
35284 rs6000_emit_swdiv (rtx dst, rtx n, rtx d, bool note_p)
35285 {
35286   machine_mode mode = GET_MODE (dst);
35287   rtx one, x0, e0, x1, xprev, eprev, xnext, enext, u, v;
35288   int i;
35289
35290   /* Low precision estimates guarantee 5 bits of accuracy.  High
35291      precision estimates guarantee 14 bits of accuracy.  SFmode
35292      requires 23 bits of accuracy.  DFmode requires 52 bits of
35293      accuracy.  Each pass at least doubles the accuracy, leading
35294      to the following.  */
35295   int passes = (TARGET_RECIP_PRECISION) ? 1 : 3;
35296   if (mode == DFmode || mode == V2DFmode)
35297     passes++;
35298
35299   enum insn_code code = optab_handler (smul_optab, mode);
35300   insn_gen_fn gen_mul = GEN_FCN (code);
35301
35302   gcc_assert (code != CODE_FOR_nothing);
35303
35304   one = rs6000_load_constant_and_splat (mode, dconst1);
35305
35306   /* x0 = 1./d estimate */
35307   x0 = gen_reg_rtx (mode);
35308   emit_insn (gen_rtx_SET (x0, gen_rtx_UNSPEC (mode, gen_rtvec (1, d),
35309                                               UNSPEC_FRES)));
35310
35311   /* Each iteration but the last calculates x_(i+1) = x_i * (2 - d * x_i).  */
35312   if (passes > 1) {
35313
35314     /* e0 = 1. - d * x0  */
35315     e0 = gen_reg_rtx (mode);
35316     rs6000_emit_nmsub (e0, d, x0, one);
35317
35318     /* x1 = x0 + e0 * x0  */
35319     x1 = gen_reg_rtx (mode);
35320     rs6000_emit_madd (x1, e0, x0, x0);
35321
35322     for (i = 0, xprev = x1, eprev = e0; i < passes - 2;
35323          ++i, xprev = xnext, eprev = enext) {
35324       
35325       /* enext = eprev * eprev  */
35326       enext = gen_reg_rtx (mode);
35327       emit_insn (gen_mul (enext, eprev, eprev));
35328
35329       /* xnext = xprev + enext * xprev  */
35330       xnext = gen_reg_rtx (mode);
35331       rs6000_emit_madd (xnext, enext, xprev, xprev);
35332     }
35333
35334   } else
35335     xprev = x0;
35336
35337   /* The last iteration calculates x_(i+1) = n * x_i * (2 - d * x_i).  */
35338
35339   /* u = n * xprev  */
35340   u = gen_reg_rtx (mode);
35341   emit_insn (gen_mul (u, n, xprev));
35342
35343   /* v = n - (d * u)  */
35344   v = gen_reg_rtx (mode);
35345   rs6000_emit_nmsub (v, d, u, n);
35346
35347   /* dst = (v * xprev) + u  */
35348   rs6000_emit_madd (dst, v, xprev, u);
35349
35350   if (note_p)
35351     add_reg_note (get_last_insn (), REG_EQUAL, gen_rtx_DIV (mode, n, d));
35352 }
35353
35354 /* Goldschmidt's Algorithm for single/double-precision floating point
35355    sqrt and rsqrt.  Assumes no trapping math and finite arguments.  */
35356
35357 void
35358 rs6000_emit_swsqrt (rtx dst, rtx src, bool recip)
35359 {
35360   machine_mode mode = GET_MODE (src);
35361   rtx e = gen_reg_rtx (mode);
35362   rtx g = gen_reg_rtx (mode);
35363   rtx h = gen_reg_rtx (mode);
35364
35365   /* Low precision estimates guarantee 5 bits of accuracy.  High
35366      precision estimates guarantee 14 bits of accuracy.  SFmode
35367      requires 23 bits of accuracy.  DFmode requires 52 bits of
35368      accuracy.  Each pass at least doubles the accuracy, leading
35369      to the following.  */
35370   int passes = (TARGET_RECIP_PRECISION) ? 1 : 3;
35371   if (mode == DFmode || mode == V2DFmode)
35372     passes++;
35373
35374   int i;
35375   rtx mhalf;
35376   enum insn_code code = optab_handler (smul_optab, mode);
35377   insn_gen_fn gen_mul = GEN_FCN (code);
35378
35379   gcc_assert (code != CODE_FOR_nothing);
35380
35381   mhalf = rs6000_load_constant_and_splat (mode, dconsthalf);
35382
35383   /* e = rsqrt estimate */
35384   emit_insn (gen_rtx_SET (e, gen_rtx_UNSPEC (mode, gen_rtvec (1, src),
35385                                              UNSPEC_RSQRT)));
35386
35387   /* If (src == 0.0) filter infinity to prevent NaN for sqrt(0.0).  */
35388   if (!recip)
35389     {
35390       rtx zero = force_reg (mode, CONST0_RTX (mode));
35391
35392       if (mode == SFmode)
35393         {
35394           rtx target = emit_conditional_move (e, GT, src, zero, mode,
35395                                               e, zero, mode, 0);
35396           if (target != e)
35397             emit_move_insn (e, target);
35398         }
35399       else
35400         {
35401           rtx cond = gen_rtx_GT (VOIDmode, e, zero);
35402           rs6000_emit_vector_cond_expr (e, e, zero, cond, src, zero);
35403         }
35404     }
35405
35406   /* g = sqrt estimate.  */
35407   emit_insn (gen_mul (g, e, src));
35408   /* h = 1/(2*sqrt) estimate.  */
35409   emit_insn (gen_mul (h, e, mhalf));
35410
35411   if (recip)
35412     {
35413       if (passes == 1)
35414         {
35415           rtx t = gen_reg_rtx (mode);
35416           rs6000_emit_nmsub (t, g, h, mhalf);
35417           /* Apply correction directly to 1/rsqrt estimate.  */
35418           rs6000_emit_madd (dst, e, t, e);
35419         }
35420       else
35421         {
35422           for (i = 0; i < passes; i++)
35423             {
35424               rtx t1 = gen_reg_rtx (mode);
35425               rtx g1 = gen_reg_rtx (mode);
35426               rtx h1 = gen_reg_rtx (mode);
35427
35428               rs6000_emit_nmsub (t1, g, h, mhalf);
35429               rs6000_emit_madd (g1, g, t1, g);
35430               rs6000_emit_madd (h1, h, t1, h);
35431
35432               g = g1;
35433               h = h1;
35434             }
35435           /* Multiply by 2 for 1/rsqrt.  */
35436           emit_insn (gen_add3_insn (dst, h, h));
35437         }
35438     }
35439   else
35440     {
35441       rtx t = gen_reg_rtx (mode);
35442       rs6000_emit_nmsub (t, g, h, mhalf);
35443       rs6000_emit_madd (dst, g, t, g);
35444     }
35445
35446   return;
35447 }
35448
35449 /* Emit popcount intrinsic on TARGET_POPCNTB (Power5) and TARGET_POPCNTD
35450    (Power7) targets.  DST is the target, and SRC is the argument operand.  */
35451
35452 void
35453 rs6000_emit_popcount (rtx dst, rtx src)
35454 {
35455   machine_mode mode = GET_MODE (dst);
35456   rtx tmp1, tmp2;
35457
35458   /* Use the PPC ISA 2.06 popcnt{w,d} instruction if we can.  */
35459   if (TARGET_POPCNTD)
35460     {
35461       if (mode == SImode)
35462         emit_insn (gen_popcntdsi2 (dst, src));
35463       else
35464         emit_insn (gen_popcntddi2 (dst, src));
35465       return;
35466     }
35467
35468   tmp1 = gen_reg_rtx (mode);
35469
35470   if (mode == SImode)
35471     {
35472       emit_insn (gen_popcntbsi2 (tmp1, src));
35473       tmp2 = expand_mult (SImode, tmp1, GEN_INT (0x01010101),
35474                            NULL_RTX, 0);
35475       tmp2 = force_reg (SImode, tmp2);
35476       emit_insn (gen_lshrsi3 (dst, tmp2, GEN_INT (24)));
35477     }
35478   else
35479     {
35480       emit_insn (gen_popcntbdi2 (tmp1, src));
35481       tmp2 = expand_mult (DImode, tmp1,
35482                           GEN_INT ((HOST_WIDE_INT)
35483                                    0x01010101 << 32 | 0x01010101),
35484                           NULL_RTX, 0);
35485       tmp2 = force_reg (DImode, tmp2);
35486       emit_insn (gen_lshrdi3 (dst, tmp2, GEN_INT (56)));
35487     }
35488 }
35489
35490
35491 /* Emit parity intrinsic on TARGET_POPCNTB targets.  DST is the
35492    target, and SRC is the argument operand.  */
35493
35494 void
35495 rs6000_emit_parity (rtx dst, rtx src)
35496 {
35497   machine_mode mode = GET_MODE (dst);
35498   rtx tmp;
35499
35500   tmp = gen_reg_rtx (mode);
35501
35502   /* Use the PPC ISA 2.05 prtyw/prtyd instruction if we can.  */
35503   if (TARGET_CMPB)
35504     {
35505       if (mode == SImode)
35506         {
35507           emit_insn (gen_popcntbsi2 (tmp, src));
35508           emit_insn (gen_paritysi2_cmpb (dst, tmp));
35509         }
35510       else
35511         {
35512           emit_insn (gen_popcntbdi2 (tmp, src));
35513           emit_insn (gen_paritydi2_cmpb (dst, tmp));
35514         }
35515       return;
35516     }
35517
35518   if (mode == SImode)
35519     {
35520       /* Is mult+shift >= shift+xor+shift+xor?  */
35521       if (rs6000_cost->mulsi_const >= COSTS_N_INSNS (3))
35522         {
35523           rtx tmp1, tmp2, tmp3, tmp4;
35524
35525           tmp1 = gen_reg_rtx (SImode);
35526           emit_insn (gen_popcntbsi2 (tmp1, src));
35527
35528           tmp2 = gen_reg_rtx (SImode);
35529           emit_insn (gen_lshrsi3 (tmp2, tmp1, GEN_INT (16)));
35530           tmp3 = gen_reg_rtx (SImode);
35531           emit_insn (gen_xorsi3 (tmp3, tmp1, tmp2));
35532
35533           tmp4 = gen_reg_rtx (SImode);
35534           emit_insn (gen_lshrsi3 (tmp4, tmp3, GEN_INT (8)));
35535           emit_insn (gen_xorsi3 (tmp, tmp3, tmp4));
35536         }
35537       else
35538         rs6000_emit_popcount (tmp, src);
35539       emit_insn (gen_andsi3 (dst, tmp, const1_rtx));
35540     }
35541   else
35542     {
35543       /* Is mult+shift >= shift+xor+shift+xor+shift+xor?  */
35544       if (rs6000_cost->muldi >= COSTS_N_INSNS (5))
35545         {
35546           rtx tmp1, tmp2, tmp3, tmp4, tmp5, tmp6;
35547
35548           tmp1 = gen_reg_rtx (DImode);
35549           emit_insn (gen_popcntbdi2 (tmp1, src));
35550
35551           tmp2 = gen_reg_rtx (DImode);
35552           emit_insn (gen_lshrdi3 (tmp2, tmp1, GEN_INT (32)));
35553           tmp3 = gen_reg_rtx (DImode);
35554           emit_insn (gen_xordi3 (tmp3, tmp1, tmp2));
35555
35556           tmp4 = gen_reg_rtx (DImode);
35557           emit_insn (gen_lshrdi3 (tmp4, tmp3, GEN_INT (16)));
35558           tmp5 = gen_reg_rtx (DImode);
35559           emit_insn (gen_xordi3 (tmp5, tmp3, tmp4));
35560
35561           tmp6 = gen_reg_rtx (DImode);
35562           emit_insn (gen_lshrdi3 (tmp6, tmp5, GEN_INT (8)));
35563           emit_insn (gen_xordi3 (tmp, tmp5, tmp6));
35564         }
35565       else
35566         rs6000_emit_popcount (tmp, src);
35567       emit_insn (gen_anddi3 (dst, tmp, const1_rtx));
35568     }
35569 }
35570
35571 /* Expand an Altivec constant permutation for little endian mode.
35572    OP0 and OP1 are the input vectors and TARGET is the output vector.
35573    SEL specifies the constant permutation vector.
35574
35575    There are two issues: First, the two input operands must be
35576    swapped so that together they form a double-wide array in LE
35577    order.  Second, the vperm instruction has surprising behavior
35578    in LE mode:  it interprets the elements of the source vectors
35579    in BE mode ("left to right") and interprets the elements of
35580    the destination vector in LE mode ("right to left").  To
35581    correct for this, we must subtract each element of the permute
35582    control vector from 31.
35583
35584    For example, suppose we want to concatenate vr10 = {0, 1, 2, 3}
35585    with vr11 = {4, 5, 6, 7} and extract {0, 2, 4, 6} using a vperm.
35586    We place {0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27} in vr12 to
35587    serve as the permute control vector.  Then, in BE mode,
35588
35589      vperm 9,10,11,12
35590
35591    places the desired result in vr9.  However, in LE mode the 
35592    vector contents will be
35593
35594      vr10 = 00000003 00000002 00000001 00000000
35595      vr11 = 00000007 00000006 00000005 00000004
35596
35597    The result of the vperm using the same permute control vector is
35598
35599      vr9  = 05000000 07000000 01000000 03000000
35600
35601    That is, the leftmost 4 bytes of vr10 are interpreted as the
35602    source for the rightmost 4 bytes of vr9, and so on.
35603
35604    If we change the permute control vector to
35605
35606      vr12 = {31,20,29,28,23,22,21,20,15,14,13,12,7,6,5,4}
35607
35608    and issue
35609
35610      vperm 9,11,10,12
35611
35612    we get the desired
35613
35614    vr9  = 00000006 00000004 00000002 00000000.  */
35615
35616 static void
35617 altivec_expand_vec_perm_const_le (rtx target, rtx op0, rtx op1,
35618                                   const vec_perm_indices &sel)
35619 {
35620   unsigned int i;
35621   rtx perm[16];
35622   rtx constv, unspec;
35623
35624   /* Unpack and adjust the constant selector.  */
35625   for (i = 0; i < 16; ++i)
35626     {
35627       unsigned int elt = 31 - (sel[i] & 31);
35628       perm[i] = GEN_INT (elt);
35629     }
35630
35631   /* Expand to a permute, swapping the inputs and using the
35632      adjusted selector.  */
35633   if (!REG_P (op0))
35634     op0 = force_reg (V16QImode, op0);
35635   if (!REG_P (op1))
35636     op1 = force_reg (V16QImode, op1);
35637
35638   constv = gen_rtx_CONST_VECTOR (V16QImode, gen_rtvec_v (16, perm));
35639   constv = force_reg (V16QImode, constv);
35640   unspec = gen_rtx_UNSPEC (V16QImode, gen_rtvec (3, op1, op0, constv),
35641                            UNSPEC_VPERM);
35642   if (!REG_P (target))
35643     {
35644       rtx tmp = gen_reg_rtx (V16QImode);
35645       emit_move_insn (tmp, unspec);
35646       unspec = tmp;
35647     }
35648
35649   emit_move_insn (target, unspec);
35650 }
35651
35652 /* Similarly to altivec_expand_vec_perm_const_le, we must adjust the
35653    permute control vector.  But here it's not a constant, so we must
35654    generate a vector NAND or NOR to do the adjustment.  */
35655
35656 void
35657 altivec_expand_vec_perm_le (rtx operands[4])
35658 {
35659   rtx notx, iorx, unspec;
35660   rtx target = operands[0];
35661   rtx op0 = operands[1];
35662   rtx op1 = operands[2];
35663   rtx sel = operands[3];
35664   rtx tmp = target;
35665   rtx norreg = gen_reg_rtx (V16QImode);
35666   machine_mode mode = GET_MODE (target);
35667
35668   /* Get everything in regs so the pattern matches.  */
35669   if (!REG_P (op0))
35670     op0 = force_reg (mode, op0);
35671   if (!REG_P (op1))
35672     op1 = force_reg (mode, op1);
35673   if (!REG_P (sel))
35674     sel = force_reg (V16QImode, sel);
35675   if (!REG_P (target))
35676     tmp = gen_reg_rtx (mode);
35677
35678   if (TARGET_P9_VECTOR)
35679     {
35680       unspec = gen_rtx_UNSPEC (mode, gen_rtvec (3, op1, op0, sel),
35681                                UNSPEC_VPERMR);
35682     }
35683   else
35684     {
35685       /* Invert the selector with a VNAND if available, else a VNOR.
35686          The VNAND is preferred for future fusion opportunities.  */
35687       notx = gen_rtx_NOT (V16QImode, sel);
35688       iorx = (TARGET_P8_VECTOR
35689               ? gen_rtx_IOR (V16QImode, notx, notx)
35690               : gen_rtx_AND (V16QImode, notx, notx));
35691       emit_insn (gen_rtx_SET (norreg, iorx));
35692
35693       /* Permute with operands reversed and adjusted selector.  */
35694       unspec = gen_rtx_UNSPEC (mode, gen_rtvec (3, op1, op0, norreg),
35695                                UNSPEC_VPERM);
35696     }
35697
35698   /* Copy into target, possibly by way of a register.  */
35699   if (!REG_P (target))
35700     {
35701       emit_move_insn (tmp, unspec);
35702       unspec = tmp;
35703     }
35704
35705   emit_move_insn (target, unspec);
35706 }
35707
35708 /* Expand an Altivec constant permutation.  Return true if we match
35709    an efficient implementation; false to fall back to VPERM.
35710
35711    OP0 and OP1 are the input vectors and TARGET is the output vector.
35712    SEL specifies the constant permutation vector.  */
35713
35714 static bool
35715 altivec_expand_vec_perm_const (rtx target, rtx op0, rtx op1,
35716                                const vec_perm_indices &sel)
35717 {
35718   struct altivec_perm_insn {
35719     HOST_WIDE_INT mask;
35720     enum insn_code impl;
35721     unsigned char perm[16];
35722   };
35723   static const struct altivec_perm_insn patterns[] = {
35724     { OPTION_MASK_ALTIVEC, CODE_FOR_altivec_vpkuhum_direct,
35725       {  1,  3,  5,  7,  9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
35726     { OPTION_MASK_ALTIVEC, CODE_FOR_altivec_vpkuwum_direct,
35727       {  2,  3,  6,  7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
35728     { OPTION_MASK_ALTIVEC, 
35729       (BYTES_BIG_ENDIAN ? CODE_FOR_altivec_vmrghb_direct
35730        : CODE_FOR_altivec_vmrglb_direct),
35731       {  0, 16,  1, 17,  2, 18,  3, 19,  4, 20,  5, 21,  6, 22,  7, 23 } },
35732     { OPTION_MASK_ALTIVEC,
35733       (BYTES_BIG_ENDIAN ? CODE_FOR_altivec_vmrghh_direct
35734        : CODE_FOR_altivec_vmrglh_direct),
35735       {  0,  1, 16, 17,  2,  3, 18, 19,  4,  5, 20, 21,  6,  7, 22, 23 } },
35736     { OPTION_MASK_ALTIVEC,
35737       (BYTES_BIG_ENDIAN ? CODE_FOR_altivec_vmrghw_direct
35738        : CODE_FOR_altivec_vmrglw_direct),
35739       {  0,  1,  2,  3, 16, 17, 18, 19,  4,  5,  6,  7, 20, 21, 22, 23 } },
35740     { OPTION_MASK_ALTIVEC,
35741       (BYTES_BIG_ENDIAN ? CODE_FOR_altivec_vmrglb_direct
35742        : CODE_FOR_altivec_vmrghb_direct),
35743       {  8, 24,  9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
35744     { OPTION_MASK_ALTIVEC,
35745       (BYTES_BIG_ENDIAN ? CODE_FOR_altivec_vmrglh_direct
35746        : CODE_FOR_altivec_vmrghh_direct),
35747       {  8,  9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
35748     { OPTION_MASK_ALTIVEC,
35749       (BYTES_BIG_ENDIAN ? CODE_FOR_altivec_vmrglw_direct
35750        : CODE_FOR_altivec_vmrghw_direct),
35751       {  8,  9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
35752     { OPTION_MASK_P8_VECTOR,
35753       (BYTES_BIG_ENDIAN ? CODE_FOR_p8_vmrgew_v4sf_direct
35754        : CODE_FOR_p8_vmrgow_v4sf_direct),
35755       {  0,  1,  2,  3, 16, 17, 18, 19,  8,  9, 10, 11, 24, 25, 26, 27 } },
35756     { OPTION_MASK_P8_VECTOR,
35757       (BYTES_BIG_ENDIAN ? CODE_FOR_p8_vmrgow_v4sf_direct
35758        : CODE_FOR_p8_vmrgew_v4sf_direct),
35759       {  4,  5,  6,  7, 20, 21, 22, 23, 12, 13, 14, 15, 28, 29, 30, 31 } }
35760   };
35761
35762   unsigned int i, j, elt, which;
35763   unsigned char perm[16];
35764   rtx x;
35765   bool one_vec;
35766
35767   /* Unpack the constant selector.  */
35768   for (i = which = 0; i < 16; ++i)
35769     {
35770       elt = sel[i] & 31;
35771       which |= (elt < 16 ? 1 : 2);
35772       perm[i] = elt;
35773     }
35774
35775   /* Simplify the constant selector based on operands.  */
35776   switch (which)
35777     {
35778     default:
35779       gcc_unreachable ();
35780
35781     case 3:
35782       one_vec = false;
35783       if (!rtx_equal_p (op0, op1))
35784         break;
35785       /* FALLTHRU */
35786
35787     case 2:
35788       for (i = 0; i < 16; ++i)
35789         perm[i] &= 15;
35790       op0 = op1;
35791       one_vec = true;
35792       break;
35793
35794     case 1:
35795       op1 = op0;
35796       one_vec = true;
35797       break;
35798     }
35799  
35800   /* Look for splat patterns.  */
35801   if (one_vec)
35802     {
35803       elt = perm[0];
35804
35805       for (i = 0; i < 16; ++i)
35806         if (perm[i] != elt)
35807           break;
35808       if (i == 16)
35809         {
35810           if (!BYTES_BIG_ENDIAN)
35811             elt = 15 - elt;
35812           emit_insn (gen_altivec_vspltb_direct (target, op0, GEN_INT (elt)));
35813           return true;
35814         }
35815
35816       if (elt % 2 == 0)
35817         {
35818           for (i = 0; i < 16; i += 2)
35819             if (perm[i] != elt || perm[i + 1] != elt + 1)
35820               break;
35821           if (i == 16)
35822             {
35823               int field = BYTES_BIG_ENDIAN ? elt / 2 : 7 - elt / 2;
35824               x = gen_reg_rtx (V8HImode);
35825               emit_insn (gen_altivec_vsplth_direct (x, gen_lowpart (V8HImode, op0),
35826                                                     GEN_INT (field)));
35827               emit_move_insn (target, gen_lowpart (V16QImode, x));
35828               return true;
35829             }
35830         }
35831
35832       if (elt % 4 == 0)
35833         {
35834           for (i = 0; i < 16; i += 4)
35835             if (perm[i] != elt
35836                 || perm[i + 1] != elt + 1
35837                 || perm[i + 2] != elt + 2
35838                 || perm[i + 3] != elt + 3)
35839               break;
35840           if (i == 16)
35841             {
35842               int field = BYTES_BIG_ENDIAN ? elt / 4 : 3 - elt / 4;
35843               x = gen_reg_rtx (V4SImode);
35844               emit_insn (gen_altivec_vspltw_direct (x, gen_lowpart (V4SImode, op0),
35845                                                     GEN_INT (field)));
35846               emit_move_insn (target, gen_lowpart (V16QImode, x));
35847               return true;
35848             }
35849         }
35850     }
35851
35852   /* Look for merge and pack patterns.  */
35853   for (j = 0; j < ARRAY_SIZE (patterns); ++j)
35854     {
35855       bool swapped;
35856
35857       if ((patterns[j].mask & rs6000_isa_flags) == 0)
35858         continue;
35859
35860       elt = patterns[j].perm[0];
35861       if (perm[0] == elt)
35862         swapped = false;
35863       else if (perm[0] == elt + 16)
35864         swapped = true;
35865       else
35866         continue;
35867       for (i = 1; i < 16; ++i)
35868         {
35869           elt = patterns[j].perm[i];
35870           if (swapped)
35871             elt = (elt >= 16 ? elt - 16 : elt + 16);
35872           else if (one_vec && elt >= 16)
35873             elt -= 16;
35874           if (perm[i] != elt)
35875             break;
35876         }
35877       if (i == 16)
35878         {
35879           enum insn_code icode = patterns[j].impl;
35880           machine_mode omode = insn_data[icode].operand[0].mode;
35881           machine_mode imode = insn_data[icode].operand[1].mode;
35882
35883           /* For little-endian, don't use vpkuwum and vpkuhum if the
35884              underlying vector type is not V4SI and V8HI, respectively.
35885              For example, using vpkuwum with a V8HI picks up the even
35886              halfwords (BE numbering) when the even halfwords (LE
35887              numbering) are what we need.  */
35888           if (!BYTES_BIG_ENDIAN
35889               && icode == CODE_FOR_altivec_vpkuwum_direct
35890               && ((GET_CODE (op0) == REG
35891                    && GET_MODE (op0) != V4SImode)
35892                   || (GET_CODE (op0) == SUBREG
35893                       && GET_MODE (XEXP (op0, 0)) != V4SImode)))
35894             continue;
35895           if (!BYTES_BIG_ENDIAN
35896               && icode == CODE_FOR_altivec_vpkuhum_direct
35897               && ((GET_CODE (op0) == REG
35898                    && GET_MODE (op0) != V8HImode)
35899                   || (GET_CODE (op0) == SUBREG
35900                       && GET_MODE (XEXP (op0, 0)) != V8HImode)))
35901             continue;
35902
35903           /* For little-endian, the two input operands must be swapped
35904              (or swapped back) to ensure proper right-to-left numbering
35905              from 0 to 2N-1.  */
35906           if (swapped ^ !BYTES_BIG_ENDIAN)
35907             std::swap (op0, op1);
35908           if (imode != V16QImode)
35909             {
35910               op0 = gen_lowpart (imode, op0);
35911               op1 = gen_lowpart (imode, op1);
35912             }
35913           if (omode == V16QImode)
35914             x = target;
35915           else
35916             x = gen_reg_rtx (omode);
35917           emit_insn (GEN_FCN (icode) (x, op0, op1));
35918           if (omode != V16QImode)
35919             emit_move_insn (target, gen_lowpart (V16QImode, x));
35920           return true;
35921         }
35922     }
35923
35924   if (!BYTES_BIG_ENDIAN)
35925     {
35926       altivec_expand_vec_perm_const_le (target, op0, op1, sel);
35927       return true;
35928     }
35929
35930   return false;
35931 }
35932
35933 /* Expand a Paired Single or VSX Permute Doubleword constant permutation.
35934    Return true if we match an efficient implementation.  */
35935
35936 static bool
35937 rs6000_expand_vec_perm_const_1 (rtx target, rtx op0, rtx op1,
35938                                 unsigned char perm0, unsigned char perm1)
35939 {
35940   rtx x;
35941
35942   /* If both selectors come from the same operand, fold to single op.  */
35943   if ((perm0 & 2) == (perm1 & 2))
35944     {
35945       if (perm0 & 2)
35946         op0 = op1;
35947       else
35948         op1 = op0;
35949     }
35950   /* If both operands are equal, fold to simpler permutation.  */
35951   if (rtx_equal_p (op0, op1))
35952     {
35953       perm0 = perm0 & 1;
35954       perm1 = (perm1 & 1) + 2;
35955     }
35956   /* If the first selector comes from the second operand, swap.  */
35957   else if (perm0 & 2)
35958     {
35959       if (perm1 & 2)
35960         return false;
35961       perm0 -= 2;
35962       perm1 += 2;
35963       std::swap (op0, op1);
35964     }
35965   /* If the second selector does not come from the second operand, fail.  */
35966   else if ((perm1 & 2) == 0)
35967     return false;
35968
35969   /* Success! */
35970   if (target != NULL)
35971     {
35972       machine_mode vmode, dmode;
35973       rtvec v;
35974
35975       vmode = GET_MODE (target);
35976       gcc_assert (GET_MODE_NUNITS (vmode) == 2);
35977       dmode = mode_for_vector (GET_MODE_INNER (vmode), 4).require ();
35978       x = gen_rtx_VEC_CONCAT (dmode, op0, op1);
35979       v = gen_rtvec (2, GEN_INT (perm0), GEN_INT (perm1));
35980       x = gen_rtx_VEC_SELECT (vmode, x, gen_rtx_PARALLEL (VOIDmode, v));
35981       emit_insn (gen_rtx_SET (target, x));
35982     }
35983   return true;
35984 }
35985
35986 /* Implement TARGET_VECTORIZE_VEC_PERM_CONST.  */
35987
35988 static bool
35989 rs6000_vectorize_vec_perm_const (machine_mode vmode, rtx target, rtx op0,
35990                                  rtx op1, const vec_perm_indices &sel)
35991 {
35992   bool testing_p = !target;
35993
35994   /* AltiVec (and thus VSX) can handle arbitrary permutations.  */
35995   if (TARGET_ALTIVEC && testing_p)
35996     return true;
35997
35998   /* Check for ps_merge* or xxpermdi insns.  */
35999   if ((vmode == V2SFmode && TARGET_PAIRED_FLOAT)
36000       || ((vmode == V2DFmode || vmode == V2DImode)
36001           && VECTOR_MEM_VSX_P (vmode)))
36002     {
36003       if (testing_p)
36004         {
36005           op0 = gen_raw_REG (vmode, LAST_VIRTUAL_REGISTER + 1);
36006           op1 = gen_raw_REG (vmode, LAST_VIRTUAL_REGISTER + 2);
36007         }
36008       if (rs6000_expand_vec_perm_const_1 (target, op0, op1, sel[0], sel[1]))
36009         return true;
36010     }
36011
36012   if (TARGET_ALTIVEC)
36013     {
36014       /* Force the target-independent code to lower to V16QImode.  */
36015       if (vmode != V16QImode)
36016         return false;
36017       if (altivec_expand_vec_perm_const (target, op0, op1, sel))
36018         return true;
36019     }
36020
36021   return false;
36022 }
36023
36024 /* A subroutine for rs6000_expand_extract_even & rs6000_expand_interleave.
36025    OP0 and OP1 are the input vectors and TARGET is the output vector.
36026    PERM specifies the constant permutation vector.  */
36027
36028 static void
36029 rs6000_do_expand_vec_perm (rtx target, rtx op0, rtx op1,
36030                            machine_mode vmode, const vec_perm_builder &perm)
36031 {
36032   rtx x = expand_vec_perm_const (vmode, op0, op1, perm, BLKmode, target);
36033   if (x != target)
36034     emit_move_insn (target, x);
36035 }
36036
36037 /* Expand an extract even operation.  */
36038
36039 void
36040 rs6000_expand_extract_even (rtx target, rtx op0, rtx op1)
36041 {
36042   machine_mode vmode = GET_MODE (target);
36043   unsigned i, nelt = GET_MODE_NUNITS (vmode);
36044   vec_perm_builder perm (nelt, nelt, 1);
36045
36046   for (i = 0; i < nelt; i++)
36047     perm.quick_push (i * 2);
36048
36049   rs6000_do_expand_vec_perm (target, op0, op1, vmode, perm);
36050 }
36051
36052 /* Expand a vector interleave operation.  */
36053
36054 void
36055 rs6000_expand_interleave (rtx target, rtx op0, rtx op1, bool highp)
36056 {
36057   machine_mode vmode = GET_MODE (target);
36058   unsigned i, high, nelt = GET_MODE_NUNITS (vmode);
36059   vec_perm_builder perm (nelt, nelt, 1);
36060
36061   high = (highp ? 0 : nelt / 2);
36062   for (i = 0; i < nelt / 2; i++)
36063     {
36064       perm.quick_push (i + high);
36065       perm.quick_push (i + nelt + high);
36066     }
36067
36068   rs6000_do_expand_vec_perm (target, op0, op1, vmode, perm);
36069 }
36070
36071 /* Scale a V2DF vector SRC by two to the SCALE and place in TGT.  */
36072 void
36073 rs6000_scale_v2df (rtx tgt, rtx src, int scale)
36074 {
36075   HOST_WIDE_INT hwi_scale (scale);
36076   REAL_VALUE_TYPE r_pow;
36077   rtvec v = rtvec_alloc (2);
36078   rtx elt;
36079   rtx scale_vec = gen_reg_rtx (V2DFmode);
36080   (void)real_powi (&r_pow, DFmode, &dconst2, hwi_scale);
36081   elt = const_double_from_real_value (r_pow, DFmode);
36082   RTVEC_ELT (v, 0) = elt;
36083   RTVEC_ELT (v, 1) = elt;
36084   rs6000_expand_vector_init (scale_vec, gen_rtx_PARALLEL (V2DFmode, v));
36085   emit_insn (gen_mulv2df3 (tgt, src, scale_vec));
36086 }
36087
36088 /* Return an RTX representing where to find the function value of a
36089    function returning MODE.  */
36090 static rtx
36091 rs6000_complex_function_value (machine_mode mode)
36092 {
36093   unsigned int regno;
36094   rtx r1, r2;
36095   machine_mode inner = GET_MODE_INNER (mode);
36096   unsigned int inner_bytes = GET_MODE_UNIT_SIZE (mode);
36097
36098   if (TARGET_FLOAT128_TYPE
36099       && (mode == KCmode
36100           || (mode == TCmode && TARGET_IEEEQUAD)))
36101     regno = ALTIVEC_ARG_RETURN;
36102
36103   else if (FLOAT_MODE_P (mode) && TARGET_HARD_FLOAT)
36104     regno = FP_ARG_RETURN;
36105
36106   else
36107     {
36108       regno = GP_ARG_RETURN;
36109
36110       /* 32-bit is OK since it'll go in r3/r4.  */
36111       if (TARGET_32BIT && inner_bytes >= 4)
36112         return gen_rtx_REG (mode, regno);
36113     }
36114
36115   if (inner_bytes >= 8)
36116     return gen_rtx_REG (mode, regno);
36117
36118   r1 = gen_rtx_EXPR_LIST (inner, gen_rtx_REG (inner, regno),
36119                           const0_rtx);
36120   r2 = gen_rtx_EXPR_LIST (inner, gen_rtx_REG (inner, regno + 1),
36121                           GEN_INT (inner_bytes));
36122   return gen_rtx_PARALLEL (mode, gen_rtvec (2, r1, r2));
36123 }
36124
36125 /* Return an rtx describing a return value of MODE as a PARALLEL
36126    in N_ELTS registers, each of mode ELT_MODE, starting at REGNO,
36127    stride REG_STRIDE.  */
36128
36129 static rtx
36130 rs6000_parallel_return (machine_mode mode,
36131                         int n_elts, machine_mode elt_mode,
36132                         unsigned int regno, unsigned int reg_stride)
36133 {
36134   rtx par = gen_rtx_PARALLEL (mode, rtvec_alloc (n_elts));
36135
36136   int i;
36137   for (i = 0; i < n_elts; i++)
36138     {
36139       rtx r = gen_rtx_REG (elt_mode, regno);
36140       rtx off = GEN_INT (i * GET_MODE_SIZE (elt_mode));
36141       XVECEXP (par, 0, i) = gen_rtx_EXPR_LIST (VOIDmode, r, off);
36142       regno += reg_stride;
36143     }
36144
36145   return par;
36146 }
36147
36148 /* Target hook for TARGET_FUNCTION_VALUE.
36149
36150    An integer value is in r3 and a floating-point value is in fp1,
36151    unless -msoft-float.  */
36152
36153 static rtx
36154 rs6000_function_value (const_tree valtype,
36155                        const_tree fn_decl_or_type ATTRIBUTE_UNUSED,
36156                        bool outgoing ATTRIBUTE_UNUSED)
36157 {
36158   machine_mode mode;
36159   unsigned int regno;
36160   machine_mode elt_mode;
36161   int n_elts;
36162
36163   /* Special handling for structs in darwin64.  */
36164   if (TARGET_MACHO 
36165       && rs6000_darwin64_struct_check_p (TYPE_MODE (valtype), valtype))
36166     {
36167       CUMULATIVE_ARGS valcum;
36168       rtx valret;
36169
36170       valcum.words = 0;
36171       valcum.fregno = FP_ARG_MIN_REG;
36172       valcum.vregno = ALTIVEC_ARG_MIN_REG;
36173       /* Do a trial code generation as if this were going to be passed as
36174          an argument; if any part goes in memory, we return NULL.  */
36175       valret = rs6000_darwin64_record_arg (&valcum, valtype, true, /* retval= */ true);
36176       if (valret)
36177         return valret;
36178       /* Otherwise fall through to standard ABI rules.  */
36179     }
36180
36181   mode = TYPE_MODE (valtype);
36182
36183   /* The ELFv2 ABI returns homogeneous VFP aggregates in registers.  */
36184   if (rs6000_discover_homogeneous_aggregate (mode, valtype, &elt_mode, &n_elts))
36185     {
36186       int first_reg, n_regs;
36187
36188       if (SCALAR_FLOAT_MODE_NOT_VECTOR_P (elt_mode))
36189         {
36190           /* _Decimal128 must use even/odd register pairs.  */
36191           first_reg = (elt_mode == TDmode) ? FP_ARG_RETURN + 1 : FP_ARG_RETURN;
36192           n_regs = (GET_MODE_SIZE (elt_mode) + 7) >> 3;
36193         }
36194       else
36195         {
36196           first_reg = ALTIVEC_ARG_RETURN;
36197           n_regs = 1;
36198         }
36199
36200       return rs6000_parallel_return (mode, n_elts, elt_mode, first_reg, n_regs);
36201     }
36202
36203   /* Some return value types need be split in -mpowerpc64, 32bit ABI.  */
36204   if (TARGET_32BIT && TARGET_POWERPC64)
36205     switch (mode)
36206       {
36207       default:
36208         break;
36209       case E_DImode:
36210       case E_SCmode:
36211       case E_DCmode:
36212       case E_TCmode:
36213         int count = GET_MODE_SIZE (mode) / 4;
36214         return rs6000_parallel_return (mode, count, SImode, GP_ARG_RETURN, 1);
36215       }
36216
36217   if ((INTEGRAL_TYPE_P (valtype)
36218        && GET_MODE_BITSIZE (mode) < (TARGET_32BIT ? 32 : 64))
36219       || POINTER_TYPE_P (valtype))
36220     mode = TARGET_32BIT ? SImode : DImode;
36221
36222   if (DECIMAL_FLOAT_MODE_P (mode) && TARGET_HARD_FLOAT)
36223     /* _Decimal128 must use an even/odd register pair.  */
36224     regno = (mode == TDmode) ? FP_ARG_RETURN + 1 : FP_ARG_RETURN;
36225   else if (SCALAR_FLOAT_TYPE_P (valtype) && TARGET_HARD_FLOAT
36226            && !FLOAT128_VECTOR_P (mode)
36227            && ((TARGET_SINGLE_FLOAT && (mode == SFmode)) || TARGET_DOUBLE_FLOAT))
36228     regno = FP_ARG_RETURN;
36229   else if (TREE_CODE (valtype) == COMPLEX_TYPE
36230            && targetm.calls.split_complex_arg)
36231     return rs6000_complex_function_value (mode);
36232   /* VSX is a superset of Altivec and adds V2DImode/V2DFmode.  Since the same
36233      return register is used in both cases, and we won't see V2DImode/V2DFmode
36234      for pure altivec, combine the two cases.  */
36235   else if ((TREE_CODE (valtype) == VECTOR_TYPE || FLOAT128_VECTOR_P (mode))
36236            && TARGET_ALTIVEC && TARGET_ALTIVEC_ABI
36237            && ALTIVEC_OR_VSX_VECTOR_MODE (mode))
36238     regno = ALTIVEC_ARG_RETURN;
36239   else
36240     regno = GP_ARG_RETURN;
36241
36242   return gen_rtx_REG (mode, regno);
36243 }
36244
36245 /* Define how to find the value returned by a library function
36246    assuming the value has mode MODE.  */
36247 rtx
36248 rs6000_libcall_value (machine_mode mode)
36249 {
36250   unsigned int regno;
36251
36252   /* Long long return value need be split in -mpowerpc64, 32bit ABI.  */
36253   if (TARGET_32BIT && TARGET_POWERPC64 && mode == DImode)
36254     return rs6000_parallel_return (mode, 2, SImode, GP_ARG_RETURN, 1);
36255
36256   if (DECIMAL_FLOAT_MODE_P (mode) && TARGET_HARD_FLOAT)
36257     /* _Decimal128 must use an even/odd register pair.  */
36258     regno = (mode == TDmode) ? FP_ARG_RETURN + 1 : FP_ARG_RETURN;
36259   else if (SCALAR_FLOAT_MODE_NOT_VECTOR_P (mode)
36260            && TARGET_HARD_FLOAT
36261            && ((TARGET_SINGLE_FLOAT && mode == SFmode) || TARGET_DOUBLE_FLOAT))
36262     regno = FP_ARG_RETURN;
36263   /* VSX is a superset of Altivec and adds V2DImode/V2DFmode.  Since the same
36264      return register is used in both cases, and we won't see V2DImode/V2DFmode
36265      for pure altivec, combine the two cases.  */
36266   else if (ALTIVEC_OR_VSX_VECTOR_MODE (mode)
36267            && TARGET_ALTIVEC && TARGET_ALTIVEC_ABI)
36268     regno = ALTIVEC_ARG_RETURN;
36269   else if (COMPLEX_MODE_P (mode) && targetm.calls.split_complex_arg)
36270     return rs6000_complex_function_value (mode);
36271   else
36272     regno = GP_ARG_RETURN;
36273
36274   return gen_rtx_REG (mode, regno);
36275 }
36276
36277 /* Compute register pressure classes.  We implement the target hook to avoid
36278    IRA picking something like NON_SPECIAL_REGS as a pressure class, which can
36279    lead to incorrect estimates of number of available registers and therefor
36280    increased register pressure/spill.   */
36281 static int
36282 rs6000_compute_pressure_classes (enum reg_class *pressure_classes)
36283 {
36284   int n;
36285
36286   n = 0;
36287   pressure_classes[n++] = GENERAL_REGS;
36288   if (TARGET_VSX)
36289     pressure_classes[n++] = VSX_REGS;
36290   else
36291     {
36292       if (TARGET_ALTIVEC)
36293         pressure_classes[n++] = ALTIVEC_REGS;
36294       if (TARGET_HARD_FLOAT)
36295         pressure_classes[n++] = FLOAT_REGS;
36296     }
36297   pressure_classes[n++] = CR_REGS;
36298   pressure_classes[n++] = SPECIAL_REGS;
36299
36300   return n;
36301 }
36302
36303 /* Given FROM and TO register numbers, say whether this elimination is allowed.
36304    Frame pointer elimination is automatically handled.
36305
36306    For the RS/6000, if frame pointer elimination is being done, we would like
36307    to convert ap into fp, not sp.
36308
36309    We need r30 if -mminimal-toc was specified, and there are constant pool
36310    references.  */
36311
36312 static bool
36313 rs6000_can_eliminate (const int from, const int to)
36314 {
36315   return (from == ARG_POINTER_REGNUM && to == STACK_POINTER_REGNUM
36316           ? ! frame_pointer_needed
36317           : from == RS6000_PIC_OFFSET_TABLE_REGNUM
36318             ? ! TARGET_MINIMAL_TOC || TARGET_NO_TOC
36319                 || constant_pool_empty_p ()
36320             : true);
36321 }
36322
36323 /* Define the offset between two registers, FROM to be eliminated and its
36324    replacement TO, at the start of a routine.  */
36325 HOST_WIDE_INT
36326 rs6000_initial_elimination_offset (int from, int to)
36327 {
36328   rs6000_stack_t *info = rs6000_stack_info ();
36329   HOST_WIDE_INT offset;
36330
36331   if (from == HARD_FRAME_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
36332     offset = info->push_p ? 0 : -info->total_size;
36333   else if (from == FRAME_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
36334     {
36335       offset = info->push_p ? 0 : -info->total_size;
36336       if (FRAME_GROWS_DOWNWARD)
36337         offset += info->fixed_size + info->vars_size + info->parm_size;
36338     }
36339   else if (from == FRAME_POINTER_REGNUM && to == HARD_FRAME_POINTER_REGNUM)
36340     offset = FRAME_GROWS_DOWNWARD
36341              ? info->fixed_size + info->vars_size + info->parm_size
36342              : 0;
36343   else if (from == ARG_POINTER_REGNUM && to == HARD_FRAME_POINTER_REGNUM)
36344     offset = info->total_size;
36345   else if (from == ARG_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
36346     offset = info->push_p ? info->total_size : 0;
36347   else if (from == RS6000_PIC_OFFSET_TABLE_REGNUM)
36348     offset = 0;
36349   else
36350     gcc_unreachable ();
36351
36352   return offset;
36353 }
36354
36355 /* Fill in sizes of registers used by unwinder.  */
36356
36357 static void
36358 rs6000_init_dwarf_reg_sizes_extra (tree address)
36359 {
36360   if (TARGET_MACHO && ! TARGET_ALTIVEC)
36361     {
36362       int i;
36363       machine_mode mode = TYPE_MODE (char_type_node);
36364       rtx addr = expand_expr (address, NULL_RTX, VOIDmode, EXPAND_NORMAL);
36365       rtx mem = gen_rtx_MEM (BLKmode, addr);
36366       rtx value = gen_int_mode (16, mode);
36367
36368       /* On Darwin, libgcc may be built to run on both G3 and G4/5.
36369          The unwinder still needs to know the size of Altivec registers.  */
36370
36371       for (i = FIRST_ALTIVEC_REGNO; i < LAST_ALTIVEC_REGNO+1; i++)
36372         {
36373           int column = DWARF_REG_TO_UNWIND_COLUMN
36374                 (DWARF2_FRAME_REG_OUT (DWARF_FRAME_REGNUM (i), true));
36375           HOST_WIDE_INT offset = column * GET_MODE_SIZE (mode);
36376
36377           emit_move_insn (adjust_address (mem, mode, offset), value);
36378         }
36379     }
36380 }
36381
36382 /* Map internal gcc register numbers to debug format register numbers.
36383    FORMAT specifies the type of debug register number to use:
36384      0 -- debug information, except for frame-related sections
36385      1 -- DWARF .debug_frame section
36386      2 -- DWARF .eh_frame section  */
36387
36388 unsigned int
36389 rs6000_dbx_register_number (unsigned int regno, unsigned int format)
36390 {
36391   /* Except for the above, we use the internal number for non-DWARF
36392      debug information, and also for .eh_frame.  */
36393   if ((format == 0 && write_symbols != DWARF2_DEBUG) || format == 2)
36394     return regno;
36395
36396   /* On some platforms, we use the standard DWARF register
36397      numbering for .debug_info and .debug_frame.  */
36398 #ifdef RS6000_USE_DWARF_NUMBERING
36399   if (regno <= 63)
36400     return regno;
36401   if (regno == LR_REGNO)
36402     return 108;
36403   if (regno == CTR_REGNO)
36404     return 109;
36405   /* Special handling for CR for .debug_frame: rs6000_emit_prologue has
36406      translated any combination of CR2, CR3, CR4 saves to a save of CR2.
36407      The actual code emitted saves the whole of CR, so we map CR2_REGNO
36408      to the DWARF reg for CR.  */
36409   if (format == 1 && regno == CR2_REGNO)
36410     return 64;
36411   if (CR_REGNO_P (regno))
36412     return regno - CR0_REGNO + 86;
36413   if (regno == CA_REGNO)
36414     return 101;  /* XER */
36415   if (ALTIVEC_REGNO_P (regno))
36416     return regno - FIRST_ALTIVEC_REGNO + 1124;
36417   if (regno == VRSAVE_REGNO)
36418     return 356;
36419   if (regno == VSCR_REGNO)
36420     return 67;
36421 #endif
36422   return regno;
36423 }
36424
36425 /* target hook eh_return_filter_mode */
36426 static scalar_int_mode
36427 rs6000_eh_return_filter_mode (void)
36428 {
36429   return TARGET_32BIT ? SImode : word_mode;
36430 }
36431
36432 /* Target hook for scalar_mode_supported_p.  */
36433 static bool
36434 rs6000_scalar_mode_supported_p (scalar_mode mode)
36435 {
36436   /* -m32 does not support TImode.  This is the default, from
36437      default_scalar_mode_supported_p.  For -m32 -mpowerpc64 we want the
36438      same ABI as for -m32.  But default_scalar_mode_supported_p allows
36439      integer modes of precision 2 * BITS_PER_WORD, which matches TImode
36440      for -mpowerpc64.  */
36441   if (TARGET_32BIT && mode == TImode)
36442     return false;
36443
36444   if (DECIMAL_FLOAT_MODE_P (mode))
36445     return default_decimal_float_supported_p ();
36446   else if (TARGET_FLOAT128_TYPE && (mode == KFmode || mode == IFmode))
36447     return true;
36448   else
36449     return default_scalar_mode_supported_p (mode);
36450 }
36451
36452 /* Target hook for vector_mode_supported_p.  */
36453 static bool
36454 rs6000_vector_mode_supported_p (machine_mode mode)
36455 {
36456
36457   if (TARGET_PAIRED_FLOAT && PAIRED_VECTOR_MODE (mode))
36458     return true;
36459
36460   /* There is no vector form for IEEE 128-bit.  If we return true for IEEE
36461      128-bit, the compiler might try to widen IEEE 128-bit to IBM
36462      double-double.  */
36463   else if (VECTOR_MEM_ALTIVEC_OR_VSX_P (mode) && !FLOAT128_IEEE_P (mode))
36464     return true;
36465
36466   else
36467     return false;
36468 }
36469
36470 /* Target hook for floatn_mode.  */
36471 static opt_scalar_float_mode
36472 rs6000_floatn_mode (int n, bool extended)
36473 {
36474   if (extended)
36475     {
36476       switch (n)
36477         {
36478         case 32:
36479           return DFmode;
36480
36481         case 64:
36482           if (TARGET_FLOAT128_TYPE)
36483             return (FLOAT128_IEEE_P (TFmode)) ? TFmode : KFmode;
36484           else
36485             return opt_scalar_float_mode ();
36486
36487         case 128:
36488           return opt_scalar_float_mode ();
36489
36490         default:
36491           /* Those are the only valid _FloatNx types.  */
36492           gcc_unreachable ();
36493         }
36494     }
36495   else
36496     {
36497       switch (n)
36498         {
36499         case 32:
36500           return SFmode;
36501
36502         case 64:
36503           return DFmode;
36504
36505         case 128:
36506           if (TARGET_FLOAT128_TYPE)
36507             return (FLOAT128_IEEE_P (TFmode)) ? TFmode : KFmode;
36508           else
36509             return opt_scalar_float_mode ();
36510
36511         default:
36512           return opt_scalar_float_mode ();
36513         }
36514     }
36515
36516 }
36517
36518 /* Target hook for c_mode_for_suffix.  */
36519 static machine_mode
36520 rs6000_c_mode_for_suffix (char suffix)
36521 {
36522   if (TARGET_FLOAT128_TYPE)
36523     {
36524       if (suffix == 'q' || suffix == 'Q')
36525         return (FLOAT128_IEEE_P (TFmode)) ? TFmode : KFmode;
36526
36527       /* At the moment, we are not defining a suffix for IBM extended double.
36528          If/when the default for -mabi=ieeelongdouble is changed, and we want
36529          to support __ibm128 constants in legacy library code, we may need to
36530          re-evalaute this decision.  Currently, c-lex.c only supports 'w' and
36531          'q' as machine dependent suffixes.  The x86_64 port uses 'w' for
36532          __float80 constants.  */
36533     }
36534
36535   return VOIDmode;
36536 }
36537
36538 /* Target hook for invalid_arg_for_unprototyped_fn. */
36539 static const char *
36540 invalid_arg_for_unprototyped_fn (const_tree typelist, const_tree funcdecl, const_tree val)
36541 {
36542   return (!rs6000_darwin64_abi
36543           && typelist == 0
36544           && TREE_CODE (TREE_TYPE (val)) == VECTOR_TYPE
36545           && (funcdecl == NULL_TREE
36546               || (TREE_CODE (funcdecl) == FUNCTION_DECL
36547                   && DECL_BUILT_IN_CLASS (funcdecl) != BUILT_IN_MD)))
36548           ? N_("AltiVec argument passed to unprototyped function")
36549           : NULL;
36550 }
36551
36552 /* For TARGET_SECURE_PLT 32-bit PIC code we can save PIC register
36553    setup by using __stack_chk_fail_local hidden function instead of
36554    calling __stack_chk_fail directly.  Otherwise it is better to call
36555    __stack_chk_fail directly.  */
36556
36557 static tree ATTRIBUTE_UNUSED
36558 rs6000_stack_protect_fail (void)
36559 {
36560   return (DEFAULT_ABI == ABI_V4 && TARGET_SECURE_PLT && flag_pic)
36561          ? default_hidden_stack_protect_fail ()
36562          : default_external_stack_protect_fail ();
36563 }
36564
36565 /* Implement the TARGET_ASAN_SHADOW_OFFSET hook.  */
36566
36567 #if TARGET_ELF
36568 static unsigned HOST_WIDE_INT
36569 rs6000_asan_shadow_offset (void)
36570 {
36571   return (unsigned HOST_WIDE_INT) 1 << (TARGET_64BIT ? 41 : 29);
36572 }
36573 #endif
36574 \f
36575 /* Mask options that we want to support inside of attribute((target)) and
36576    #pragma GCC target operations.  Note, we do not include things like
36577    64/32-bit, endianness, hard/soft floating point, etc. that would have
36578    different calling sequences.  */
36579
36580 struct rs6000_opt_mask {
36581   const char *name;             /* option name */
36582   HOST_WIDE_INT mask;           /* mask to set */
36583   bool invert;                  /* invert sense of mask */
36584   bool valid_target;            /* option is a target option */
36585 };
36586
36587 static struct rs6000_opt_mask const rs6000_opt_masks[] =
36588 {
36589   { "altivec",                  OPTION_MASK_ALTIVEC,            false, true  },
36590   { "cmpb",                     OPTION_MASK_CMPB,               false, true  },
36591   { "crypto",                   OPTION_MASK_CRYPTO,             false, true  },
36592   { "direct-move",              OPTION_MASK_DIRECT_MOVE,        false, true  },
36593   { "dlmzb",                    OPTION_MASK_DLMZB,              false, true  },
36594   { "efficient-unaligned-vsx",  OPTION_MASK_EFFICIENT_UNALIGNED_VSX,
36595                                                                 false, true  },
36596   { "float128",                 OPTION_MASK_FLOAT128_KEYWORD,   false, true  },
36597   { "float128-hardware",        OPTION_MASK_FLOAT128_HW,        false, true  },
36598   { "fprnd",                    OPTION_MASK_FPRND,              false, true  },
36599   { "hard-dfp",                 OPTION_MASK_DFP,                false, true  },
36600   { "htm",                      OPTION_MASK_HTM,                false, true  },
36601   { "isel",                     OPTION_MASK_ISEL,               false, true  },
36602   { "mfcrf",                    OPTION_MASK_MFCRF,              false, true  },
36603   { "mfpgpr",                   OPTION_MASK_MFPGPR,             false, true  },
36604   { "modulo",                   OPTION_MASK_MODULO,             false, true  },
36605   { "mulhw",                    OPTION_MASK_MULHW,              false, true  },
36606   { "multiple",                 OPTION_MASK_MULTIPLE,           false, true  },
36607   { "popcntb",                  OPTION_MASK_POPCNTB,            false, true  },
36608   { "popcntd",                  OPTION_MASK_POPCNTD,            false, true  },
36609   { "power8-fusion",            OPTION_MASK_P8_FUSION,          false, true  },
36610   { "power8-fusion-sign",       OPTION_MASK_P8_FUSION_SIGN,     false, true  },
36611   { "power8-vector",            OPTION_MASK_P8_VECTOR,          false, true  },
36612   { "power9-fusion",            OPTION_MASK_P9_FUSION,          false, true  },
36613   { "power9-minmax",            OPTION_MASK_P9_MINMAX,          false, true  },
36614   { "power9-misc",              OPTION_MASK_P9_MISC,            false, true  },
36615   { "power9-vector",            OPTION_MASK_P9_VECTOR,          false, true  },
36616   { "powerpc-gfxopt",           OPTION_MASK_PPC_GFXOPT,         false, true  },
36617   { "powerpc-gpopt",            OPTION_MASK_PPC_GPOPT,          false, true  },
36618   { "quad-memory",              OPTION_MASK_QUAD_MEMORY,        false, true  },
36619   { "quad-memory-atomic",       OPTION_MASK_QUAD_MEMORY_ATOMIC, false, true  },
36620   { "recip-precision",          OPTION_MASK_RECIP_PRECISION,    false, true  },
36621   { "save-toc-indirect",        OPTION_MASK_SAVE_TOC_INDIRECT,  false, true  },
36622   { "string",                   0,                              false, true  },
36623   { "toc-fusion",               OPTION_MASK_TOC_FUSION,         false, true  },
36624   { "update",                   OPTION_MASK_NO_UPDATE,          true , true  },
36625   { "vsx",                      OPTION_MASK_VSX,                false, true  },
36626 #ifdef OPTION_MASK_64BIT
36627 #if TARGET_AIX_OS
36628   { "aix64",                    OPTION_MASK_64BIT,              false, false },
36629   { "aix32",                    OPTION_MASK_64BIT,              true,  false },
36630 #else
36631   { "64",                       OPTION_MASK_64BIT,              false, false },
36632   { "32",                       OPTION_MASK_64BIT,              true,  false },
36633 #endif
36634 #endif
36635 #ifdef OPTION_MASK_EABI
36636   { "eabi",                     OPTION_MASK_EABI,               false, false },
36637 #endif
36638 #ifdef OPTION_MASK_LITTLE_ENDIAN
36639   { "little",                   OPTION_MASK_LITTLE_ENDIAN,      false, false },
36640   { "big",                      OPTION_MASK_LITTLE_ENDIAN,      true,  false },
36641 #endif
36642 #ifdef OPTION_MASK_RELOCATABLE
36643   { "relocatable",              OPTION_MASK_RELOCATABLE,        false, false },
36644 #endif
36645 #ifdef OPTION_MASK_STRICT_ALIGN
36646   { "strict-align",             OPTION_MASK_STRICT_ALIGN,       false, false },
36647 #endif
36648   { "soft-float",               OPTION_MASK_SOFT_FLOAT,         false, false },
36649   { "string",                   0,                              false, false },
36650 };
36651
36652 /* Builtin mask mapping for printing the flags.  */
36653 static struct rs6000_opt_mask const rs6000_builtin_mask_names[] =
36654 {
36655   { "altivec",           RS6000_BTM_ALTIVEC,    false, false },
36656   { "vsx",               RS6000_BTM_VSX,        false, false },
36657   { "paired",            RS6000_BTM_PAIRED,     false, false },
36658   { "fre",               RS6000_BTM_FRE,        false, false },
36659   { "fres",              RS6000_BTM_FRES,       false, false },
36660   { "frsqrte",           RS6000_BTM_FRSQRTE,    false, false },
36661   { "frsqrtes",          RS6000_BTM_FRSQRTES,   false, false },
36662   { "popcntd",           RS6000_BTM_POPCNTD,    false, false },
36663   { "cell",              RS6000_BTM_CELL,       false, false },
36664   { "power8-vector",     RS6000_BTM_P8_VECTOR,  false, false },
36665   { "power9-vector",     RS6000_BTM_P9_VECTOR,  false, false },
36666   { "power9-misc",       RS6000_BTM_P9_MISC,    false, false },
36667   { "crypto",            RS6000_BTM_CRYPTO,     false, false },
36668   { "htm",               RS6000_BTM_HTM,        false, false },
36669   { "hard-dfp",          RS6000_BTM_DFP,        false, false },
36670   { "hard-float",        RS6000_BTM_HARD_FLOAT, false, false },
36671   { "long-double-128",   RS6000_BTM_LDBL128,    false, false },
36672   { "float128",          RS6000_BTM_FLOAT128,   false, false },
36673   { "float128-hw",       RS6000_BTM_FLOAT128_HW,false, false },
36674 };
36675
36676 /* Option variables that we want to support inside attribute((target)) and
36677    #pragma GCC target operations.  */
36678
36679 struct rs6000_opt_var {
36680   const char *name;             /* option name */
36681   size_t global_offset;         /* offset of the option in global_options.  */
36682   size_t target_offset;         /* offset of the option in target options.  */
36683 };
36684
36685 static struct rs6000_opt_var const rs6000_opt_vars[] =
36686 {
36687   { "friz",
36688     offsetof (struct gcc_options, x_TARGET_FRIZ),
36689     offsetof (struct cl_target_option, x_TARGET_FRIZ), },
36690   { "avoid-indexed-addresses",
36691     offsetof (struct gcc_options, x_TARGET_AVOID_XFORM),
36692     offsetof (struct cl_target_option, x_TARGET_AVOID_XFORM) },
36693   { "paired",
36694     offsetof (struct gcc_options, x_rs6000_paired_float),
36695     offsetof (struct cl_target_option, x_rs6000_paired_float), },
36696   { "longcall",
36697     offsetof (struct gcc_options, x_rs6000_default_long_calls),
36698     offsetof (struct cl_target_option, x_rs6000_default_long_calls), },
36699   { "optimize-swaps",
36700     offsetof (struct gcc_options, x_rs6000_optimize_swaps),
36701     offsetof (struct cl_target_option, x_rs6000_optimize_swaps), },
36702   { "allow-movmisalign",
36703     offsetof (struct gcc_options, x_TARGET_ALLOW_MOVMISALIGN),
36704     offsetof (struct cl_target_option, x_TARGET_ALLOW_MOVMISALIGN), },
36705   { "sched-groups",
36706     offsetof (struct gcc_options, x_TARGET_SCHED_GROUPS),
36707     offsetof (struct cl_target_option, x_TARGET_SCHED_GROUPS), },
36708   { "always-hint",
36709     offsetof (struct gcc_options, x_TARGET_ALWAYS_HINT),
36710     offsetof (struct cl_target_option, x_TARGET_ALWAYS_HINT), },
36711   { "align-branch-targets",
36712     offsetof (struct gcc_options, x_TARGET_ALIGN_BRANCH_TARGETS),
36713     offsetof (struct cl_target_option, x_TARGET_ALIGN_BRANCH_TARGETS), },
36714   { "tls-markers",
36715     offsetof (struct gcc_options, x_tls_markers),
36716     offsetof (struct cl_target_option, x_tls_markers), },
36717   { "sched-prolog",
36718     offsetof (struct gcc_options, x_TARGET_SCHED_PROLOG),
36719     offsetof (struct cl_target_option, x_TARGET_SCHED_PROLOG), },
36720   { "sched-epilog",
36721     offsetof (struct gcc_options, x_TARGET_SCHED_PROLOG),
36722     offsetof (struct cl_target_option, x_TARGET_SCHED_PROLOG), },
36723   { "speculate-indirect-jumps",
36724     offsetof (struct gcc_options, x_rs6000_speculate_indirect_jumps),
36725     offsetof (struct cl_target_option, x_rs6000_speculate_indirect_jumps), },
36726 };
36727
36728 /* Inner function to handle attribute((target("..."))) and #pragma GCC target
36729    parsing.  Return true if there were no errors.  */
36730
36731 static bool
36732 rs6000_inner_target_options (tree args, bool attr_p)
36733 {
36734   bool ret = true;
36735
36736   if (args == NULL_TREE)
36737     ;
36738
36739   else if (TREE_CODE (args) == STRING_CST)
36740     {
36741       char *p = ASTRDUP (TREE_STRING_POINTER (args));
36742       char *q;
36743
36744       while ((q = strtok (p, ",")) != NULL)
36745         {
36746           bool error_p = false;
36747           bool not_valid_p = false;
36748           const char *cpu_opt = NULL;
36749
36750           p = NULL;
36751           if (strncmp (q, "cpu=", 4) == 0)
36752             {
36753               int cpu_index = rs6000_cpu_name_lookup (q+4);
36754               if (cpu_index >= 0)
36755                 rs6000_cpu_index = cpu_index;
36756               else
36757                 {
36758                   error_p = true;
36759                   cpu_opt = q+4;
36760                 }
36761             }
36762           else if (strncmp (q, "tune=", 5) == 0)
36763             {
36764               int tune_index = rs6000_cpu_name_lookup (q+5);
36765               if (tune_index >= 0)
36766                 rs6000_tune_index = tune_index;
36767               else
36768                 {
36769                   error_p = true;
36770                   cpu_opt = q+5;
36771                 }
36772             }
36773           else
36774             {
36775               size_t i;
36776               bool invert = false;
36777               char *r = q;
36778
36779               error_p = true;
36780               if (strncmp (r, "no-", 3) == 0)
36781                 {
36782                   invert = true;
36783                   r += 3;
36784                 }
36785
36786               for (i = 0; i < ARRAY_SIZE (rs6000_opt_masks); i++)
36787                 if (strcmp (r, rs6000_opt_masks[i].name) == 0)
36788                   {
36789                     HOST_WIDE_INT mask = rs6000_opt_masks[i].mask;
36790
36791                     if (!rs6000_opt_masks[i].valid_target)
36792                       not_valid_p = true;
36793                     else
36794                       {
36795                         error_p = false;
36796                         rs6000_isa_flags_explicit |= mask;
36797
36798                         /* VSX needs altivec, so -mvsx automagically sets
36799                            altivec and disables -mavoid-indexed-addresses.  */
36800                         if (!invert)
36801                           {
36802                             if (mask == OPTION_MASK_VSX)
36803                               {
36804                                 mask |= OPTION_MASK_ALTIVEC;
36805                                 TARGET_AVOID_XFORM = 0;
36806                               }
36807                           }
36808
36809                         if (rs6000_opt_masks[i].invert)
36810                           invert = !invert;
36811
36812                         if (invert)
36813                           rs6000_isa_flags &= ~mask;
36814                         else
36815                           rs6000_isa_flags |= mask;
36816                       }
36817                     break;
36818                   }
36819
36820               if (error_p && !not_valid_p)
36821                 {
36822                   for (i = 0; i < ARRAY_SIZE (rs6000_opt_vars); i++)
36823                     if (strcmp (r, rs6000_opt_vars[i].name) == 0)
36824                       {
36825                         size_t j = rs6000_opt_vars[i].global_offset;
36826                         *((int *) ((char *)&global_options + j)) = !invert;
36827                         error_p = false;
36828                         not_valid_p = false;
36829                         break;
36830                       }
36831                 }
36832             }
36833
36834           if (error_p)
36835             {
36836               const char *eprefix, *esuffix;
36837
36838               ret = false;
36839               if (attr_p)
36840                 {
36841                   eprefix = "__attribute__((__target__(";
36842                   esuffix = ")))";
36843                 }
36844               else
36845                 {
36846                   eprefix = "#pragma GCC target ";
36847                   esuffix = "";
36848                 }
36849
36850               if (cpu_opt)
36851                 error ("invalid cpu %qs for %s%qs%s", cpu_opt, eprefix,
36852                        q, esuffix);
36853               else if (not_valid_p)
36854                 error ("%s%qs%s is not allowed", eprefix, q, esuffix);
36855               else
36856                 error ("%s%qs%s is invalid", eprefix, q, esuffix);
36857             }
36858         }
36859     }
36860
36861   else if (TREE_CODE (args) == TREE_LIST)
36862     {
36863       do
36864         {
36865           tree value = TREE_VALUE (args);
36866           if (value)
36867             {
36868               bool ret2 = rs6000_inner_target_options (value, attr_p);
36869               if (!ret2)
36870                 ret = false;
36871             }
36872           args = TREE_CHAIN (args);
36873         }
36874       while (args != NULL_TREE);
36875     }
36876
36877   else
36878     {
36879       error ("attribute %<target%> argument not a string");
36880       return false;
36881     }
36882
36883   return ret;
36884 }
36885
36886 /* Print out the target options as a list for -mdebug=target.  */
36887
36888 static void
36889 rs6000_debug_target_options (tree args, const char *prefix)
36890 {
36891   if (args == NULL_TREE)
36892     fprintf (stderr, "%s<NULL>", prefix);
36893
36894   else if (TREE_CODE (args) == STRING_CST)
36895     {
36896       char *p = ASTRDUP (TREE_STRING_POINTER (args));
36897       char *q;
36898
36899       while ((q = strtok (p, ",")) != NULL)
36900         {
36901           p = NULL;
36902           fprintf (stderr, "%s\"%s\"", prefix, q);
36903           prefix = ", ";
36904         }
36905     }
36906
36907   else if (TREE_CODE (args) == TREE_LIST)
36908     {
36909       do
36910         {
36911           tree value = TREE_VALUE (args);
36912           if (value)
36913             {
36914               rs6000_debug_target_options (value, prefix);
36915               prefix = ", ";
36916             }
36917           args = TREE_CHAIN (args);
36918         }
36919       while (args != NULL_TREE);
36920     }
36921
36922   else
36923     gcc_unreachable ();
36924
36925   return;
36926 }
36927
36928 \f
36929 /* Hook to validate attribute((target("..."))).  */
36930
36931 static bool
36932 rs6000_valid_attribute_p (tree fndecl,
36933                           tree ARG_UNUSED (name),
36934                           tree args,
36935                           int flags)
36936 {
36937   struct cl_target_option cur_target;
36938   bool ret;
36939   tree old_optimize;
36940   tree new_target, new_optimize;
36941   tree func_optimize;
36942
36943   gcc_assert ((fndecl != NULL_TREE) && (args != NULL_TREE));
36944
36945   if (TARGET_DEBUG_TARGET)
36946     {
36947       tree tname = DECL_NAME (fndecl);
36948       fprintf (stderr, "\n==================== rs6000_valid_attribute_p:\n");
36949       if (tname)
36950         fprintf (stderr, "function: %.*s\n",
36951                  (int) IDENTIFIER_LENGTH (tname),
36952                  IDENTIFIER_POINTER (tname));
36953       else
36954         fprintf (stderr, "function: unknown\n");
36955   
36956       fprintf (stderr, "args:");
36957       rs6000_debug_target_options (args, " ");
36958       fprintf (stderr, "\n");
36959
36960       if (flags)
36961         fprintf (stderr, "flags: 0x%x\n", flags);
36962
36963       fprintf (stderr, "--------------------\n");
36964     }
36965
36966   /* attribute((target("default"))) does nothing, beyond
36967      affecting multi-versioning.  */
36968   if (TREE_VALUE (args)
36969       && TREE_CODE (TREE_VALUE (args)) == STRING_CST
36970       && TREE_CHAIN (args) == NULL_TREE
36971       && strcmp (TREE_STRING_POINTER (TREE_VALUE (args)), "default") == 0)
36972     return true;
36973
36974   old_optimize = build_optimization_node (&global_options);
36975   func_optimize = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (fndecl);
36976
36977   /* If the function changed the optimization levels as well as setting target
36978      options, start with the optimizations specified.  */
36979   if (func_optimize && func_optimize != old_optimize)
36980     cl_optimization_restore (&global_options,
36981                              TREE_OPTIMIZATION (func_optimize));
36982
36983   /* The target attributes may also change some optimization flags, so update
36984      the optimization options if necessary.  */
36985   cl_target_option_save (&cur_target, &global_options);
36986   rs6000_cpu_index = rs6000_tune_index = -1;
36987   ret = rs6000_inner_target_options (args, true);
36988
36989   /* Set up any additional state.  */
36990   if (ret)
36991     {
36992       ret = rs6000_option_override_internal (false);
36993       new_target = build_target_option_node (&global_options);
36994     }
36995   else
36996     new_target = NULL;
36997
36998   new_optimize = build_optimization_node (&global_options);
36999
37000   if (!new_target)
37001     ret = false;
37002
37003   else if (fndecl)
37004     {
37005       DECL_FUNCTION_SPECIFIC_TARGET (fndecl) = new_target;
37006
37007       if (old_optimize != new_optimize)
37008         DECL_FUNCTION_SPECIFIC_OPTIMIZATION (fndecl) = new_optimize;
37009     }
37010
37011   cl_target_option_restore (&global_options, &cur_target);
37012
37013   if (old_optimize != new_optimize)
37014     cl_optimization_restore (&global_options,
37015                              TREE_OPTIMIZATION (old_optimize));
37016
37017   return ret;
37018 }
37019
37020 \f
37021 /* Hook to validate the current #pragma GCC target and set the state, and
37022    update the macros based on what was changed.  If ARGS is NULL, then
37023    POP_TARGET is used to reset the options.  */
37024
37025 bool
37026 rs6000_pragma_target_parse (tree args, tree pop_target)
37027 {
37028   tree prev_tree = build_target_option_node (&global_options);
37029   tree cur_tree;
37030   struct cl_target_option *prev_opt, *cur_opt;
37031   HOST_WIDE_INT prev_flags, cur_flags, diff_flags;
37032   HOST_WIDE_INT prev_bumask, cur_bumask, diff_bumask;
37033
37034   if (TARGET_DEBUG_TARGET)
37035     {
37036       fprintf (stderr, "\n==================== rs6000_pragma_target_parse\n");
37037       fprintf (stderr, "args:");
37038       rs6000_debug_target_options (args, " ");
37039       fprintf (stderr, "\n");
37040
37041       if (pop_target)
37042         {
37043           fprintf (stderr, "pop_target:\n");
37044           debug_tree (pop_target);
37045         }
37046       else
37047         fprintf (stderr, "pop_target: <NULL>\n");
37048
37049       fprintf (stderr, "--------------------\n");
37050     }
37051
37052   if (! args)
37053     {
37054       cur_tree = ((pop_target)
37055                   ? pop_target
37056                   : target_option_default_node);
37057       cl_target_option_restore (&global_options,
37058                                 TREE_TARGET_OPTION (cur_tree));
37059     }
37060   else
37061     {
37062       rs6000_cpu_index = rs6000_tune_index = -1;
37063       if (!rs6000_inner_target_options (args, false)
37064           || !rs6000_option_override_internal (false)
37065           || (cur_tree = build_target_option_node (&global_options))
37066              == NULL_TREE)
37067         {
37068           if (TARGET_DEBUG_BUILTIN || TARGET_DEBUG_TARGET)
37069             fprintf (stderr, "invalid pragma\n");
37070
37071           return false;
37072         }
37073     }
37074
37075   target_option_current_node = cur_tree;
37076   rs6000_activate_target_options (target_option_current_node);
37077
37078   /* If we have the preprocessor linked in (i.e. C or C++ languages), possibly
37079      change the macros that are defined.  */
37080   if (rs6000_target_modify_macros_ptr)
37081     {
37082       prev_opt    = TREE_TARGET_OPTION (prev_tree);
37083       prev_bumask = prev_opt->x_rs6000_builtin_mask;
37084       prev_flags  = prev_opt->x_rs6000_isa_flags;
37085
37086       cur_opt     = TREE_TARGET_OPTION (cur_tree);
37087       cur_flags   = cur_opt->x_rs6000_isa_flags;
37088       cur_bumask  = cur_opt->x_rs6000_builtin_mask;
37089
37090       diff_bumask = (prev_bumask ^ cur_bumask);
37091       diff_flags  = (prev_flags ^ cur_flags);
37092
37093       if ((diff_flags != 0) || (diff_bumask != 0))
37094         {
37095           /* Delete old macros.  */
37096           rs6000_target_modify_macros_ptr (false,
37097                                            prev_flags & diff_flags,
37098                                            prev_bumask & diff_bumask);
37099
37100           /* Define new macros.  */
37101           rs6000_target_modify_macros_ptr (true,
37102                                            cur_flags & diff_flags,
37103                                            cur_bumask & diff_bumask);
37104         }
37105     }
37106
37107   return true;
37108 }
37109
37110 \f
37111 /* Remember the last target of rs6000_set_current_function.  */
37112 static GTY(()) tree rs6000_previous_fndecl;
37113
37114 /* Restore target's globals from NEW_TREE and invalidate the
37115    rs6000_previous_fndecl cache.  */
37116
37117 void
37118 rs6000_activate_target_options (tree new_tree)
37119 {
37120   cl_target_option_restore (&global_options, TREE_TARGET_OPTION (new_tree));
37121   if (TREE_TARGET_GLOBALS (new_tree))
37122     restore_target_globals (TREE_TARGET_GLOBALS (new_tree));
37123   else if (new_tree == target_option_default_node)
37124     restore_target_globals (&default_target_globals);
37125   else
37126     TREE_TARGET_GLOBALS (new_tree) = save_target_globals_default_opts ();
37127   rs6000_previous_fndecl = NULL_TREE;
37128 }
37129
37130 /* Establish appropriate back-end context for processing the function
37131    FNDECL.  The argument might be NULL to indicate processing at top
37132    level, outside of any function scope.  */
37133 static void
37134 rs6000_set_current_function (tree fndecl)
37135 {
37136   if (TARGET_DEBUG_TARGET)
37137     {
37138       fprintf (stderr, "\n==================== rs6000_set_current_function");
37139
37140       if (fndecl)
37141         fprintf (stderr, ", fndecl %s (%p)",
37142                  (DECL_NAME (fndecl)
37143                   ? IDENTIFIER_POINTER (DECL_NAME (fndecl))
37144                   : "<unknown>"), (void *)fndecl);
37145
37146       if (rs6000_previous_fndecl)
37147         fprintf (stderr, ", prev_fndecl (%p)", (void *)rs6000_previous_fndecl);
37148
37149       fprintf (stderr, "\n");
37150     }
37151
37152   /* Only change the context if the function changes.  This hook is called
37153      several times in the course of compiling a function, and we don't want to
37154      slow things down too much or call target_reinit when it isn't safe.  */
37155   if (fndecl == rs6000_previous_fndecl)
37156     return;
37157
37158   tree old_tree;
37159   if (rs6000_previous_fndecl == NULL_TREE)
37160     old_tree = target_option_current_node;
37161   else if (DECL_FUNCTION_SPECIFIC_TARGET (rs6000_previous_fndecl))
37162     old_tree = DECL_FUNCTION_SPECIFIC_TARGET (rs6000_previous_fndecl);
37163   else
37164     old_tree = target_option_default_node;
37165
37166   tree new_tree;
37167   if (fndecl == NULL_TREE)
37168     {
37169       if (old_tree != target_option_current_node)
37170         new_tree = target_option_current_node;
37171       else
37172         new_tree = NULL_TREE;
37173     }
37174   else
37175     {
37176       new_tree = DECL_FUNCTION_SPECIFIC_TARGET (fndecl);
37177       if (new_tree == NULL_TREE)
37178         new_tree = target_option_default_node;
37179     }
37180
37181   if (TARGET_DEBUG_TARGET)
37182     {
37183       if (new_tree)
37184         {
37185           fprintf (stderr, "\nnew fndecl target specific options:\n");
37186           debug_tree (new_tree);
37187         }
37188
37189       if (old_tree)
37190         {
37191           fprintf (stderr, "\nold fndecl target specific options:\n");
37192           debug_tree (old_tree);
37193         }
37194
37195       if (old_tree != NULL_TREE || new_tree != NULL_TREE)
37196         fprintf (stderr, "--------------------\n");
37197     }
37198
37199   if (new_tree && old_tree != new_tree)
37200     rs6000_activate_target_options (new_tree);
37201
37202   if (fndecl)
37203     rs6000_previous_fndecl = fndecl;
37204 }
37205
37206 \f
37207 /* Save the current options */
37208
37209 static void
37210 rs6000_function_specific_save (struct cl_target_option *ptr,
37211                                struct gcc_options *opts)
37212 {
37213   ptr->x_rs6000_isa_flags = opts->x_rs6000_isa_flags;
37214   ptr->x_rs6000_isa_flags_explicit = opts->x_rs6000_isa_flags_explicit;
37215 }
37216
37217 /* Restore the current options */
37218
37219 static void
37220 rs6000_function_specific_restore (struct gcc_options *opts,
37221                                   struct cl_target_option *ptr)
37222                                   
37223 {
37224   opts->x_rs6000_isa_flags = ptr->x_rs6000_isa_flags;
37225   opts->x_rs6000_isa_flags_explicit = ptr->x_rs6000_isa_flags_explicit;
37226   (void) rs6000_option_override_internal (false);
37227 }
37228
37229 /* Print the current options */
37230
37231 static void
37232 rs6000_function_specific_print (FILE *file, int indent,
37233                                 struct cl_target_option *ptr)
37234 {
37235   rs6000_print_isa_options (file, indent, "Isa options set",
37236                             ptr->x_rs6000_isa_flags);
37237
37238   rs6000_print_isa_options (file, indent, "Isa options explicit",
37239                             ptr->x_rs6000_isa_flags_explicit);
37240 }
37241
37242 /* Helper function to print the current isa or misc options on a line.  */
37243
37244 static void
37245 rs6000_print_options_internal (FILE *file,
37246                                int indent,
37247                                const char *string,
37248                                HOST_WIDE_INT flags,
37249                                const char *prefix,
37250                                const struct rs6000_opt_mask *opts,
37251                                size_t num_elements)
37252 {
37253   size_t i;
37254   size_t start_column = 0;
37255   size_t cur_column;
37256   size_t max_column = 120;
37257   size_t prefix_len = strlen (prefix);
37258   size_t comma_len = 0;
37259   const char *comma = "";
37260
37261   if (indent)
37262     start_column += fprintf (file, "%*s", indent, "");
37263
37264   if (!flags)
37265     {
37266       fprintf (stderr, DEBUG_FMT_S, string, "<none>");
37267       return;
37268     }
37269
37270   start_column += fprintf (stderr, DEBUG_FMT_WX, string, flags);
37271
37272   /* Print the various mask options.  */
37273   cur_column = start_column;
37274   for (i = 0; i < num_elements; i++)
37275     {
37276       bool invert = opts[i].invert;
37277       const char *name = opts[i].name;
37278       const char *no_str = "";
37279       HOST_WIDE_INT mask = opts[i].mask;
37280       size_t len = comma_len + prefix_len + strlen (name);
37281
37282       if (!invert)
37283         {
37284           if ((flags & mask) == 0)
37285             {
37286               no_str = "no-";
37287               len += sizeof ("no-") - 1;
37288             }
37289
37290           flags &= ~mask;
37291         }
37292
37293       else
37294         {
37295           if ((flags & mask) != 0)
37296             {
37297               no_str = "no-";
37298               len += sizeof ("no-") - 1;
37299             }
37300
37301           flags |= mask;
37302         }
37303
37304       cur_column += len;
37305       if (cur_column > max_column)
37306         {
37307           fprintf (stderr, ", \\\n%*s", (int)start_column, "");
37308           cur_column = start_column + len;
37309           comma = "";
37310         }
37311
37312       fprintf (file, "%s%s%s%s", comma, prefix, no_str, name);
37313       comma = ", ";
37314       comma_len = sizeof (", ") - 1;
37315     }
37316
37317   fputs ("\n", file);
37318 }
37319
37320 /* Helper function to print the current isa options on a line.  */
37321
37322 static void
37323 rs6000_print_isa_options (FILE *file, int indent, const char *string,
37324                           HOST_WIDE_INT flags)
37325 {
37326   rs6000_print_options_internal (file, indent, string, flags, "-m",
37327                                  &rs6000_opt_masks[0],
37328                                  ARRAY_SIZE (rs6000_opt_masks));
37329 }
37330
37331 static void
37332 rs6000_print_builtin_options (FILE *file, int indent, const char *string,
37333                               HOST_WIDE_INT flags)
37334 {
37335   rs6000_print_options_internal (file, indent, string, flags, "",
37336                                  &rs6000_builtin_mask_names[0],
37337                                  ARRAY_SIZE (rs6000_builtin_mask_names));
37338 }
37339
37340 /* If the user used -mno-vsx, we need turn off all of the implicit ISA 2.06,
37341    2.07, and 3.0 options that relate to the vector unit (-mdirect-move,
37342    -mupper-regs-df, etc.).
37343
37344    If the user used -mno-power8-vector, we need to turn off all of the implicit
37345    ISA 2.07 and 3.0 options that relate to the vector unit.
37346
37347    If the user used -mno-power9-vector, we need to turn off all of the implicit
37348    ISA 3.0 options that relate to the vector unit.
37349
37350    This function does not handle explicit options such as the user specifying
37351    -mdirect-move.  These are handled in rs6000_option_override_internal, and
37352    the appropriate error is given if needed.
37353
37354    We return a mask of all of the implicit options that should not be enabled
37355    by default.  */
37356
37357 static HOST_WIDE_INT
37358 rs6000_disable_incompatible_switches (void)
37359 {
37360   HOST_WIDE_INT ignore_masks = rs6000_isa_flags_explicit;
37361   size_t i, j;
37362
37363   static const struct {
37364     const HOST_WIDE_INT no_flag;        /* flag explicitly turned off.  */
37365     const HOST_WIDE_INT dep_flags;      /* flags that depend on this option.  */
37366     const char *const name;             /* name of the switch.  */
37367   } flags[] = {
37368     { OPTION_MASK_P9_VECTOR,    OTHER_P9_VECTOR_MASKS,  "power9-vector" },
37369     { OPTION_MASK_P8_VECTOR,    OTHER_P8_VECTOR_MASKS,  "power8-vector" },
37370     { OPTION_MASK_VSX,          OTHER_VSX_VECTOR_MASKS, "vsx"           },
37371   };
37372
37373   for (i = 0; i < ARRAY_SIZE (flags); i++)
37374     {
37375       HOST_WIDE_INT no_flag = flags[i].no_flag;
37376
37377       if ((rs6000_isa_flags & no_flag) == 0
37378           && (rs6000_isa_flags_explicit & no_flag) != 0)
37379         {
37380           HOST_WIDE_INT dep_flags = flags[i].dep_flags;
37381           HOST_WIDE_INT set_flags = (rs6000_isa_flags_explicit
37382                                      & rs6000_isa_flags
37383                                      & dep_flags);
37384
37385           if (set_flags)
37386             {
37387               for (j = 0; j < ARRAY_SIZE (rs6000_opt_masks); j++)
37388                 if ((set_flags & rs6000_opt_masks[j].mask) != 0)
37389                   {
37390                     set_flags &= ~rs6000_opt_masks[j].mask;
37391                     error ("%<-mno-%s%> turns off %<-m%s%>",
37392                            flags[i].name,
37393                            rs6000_opt_masks[j].name);
37394                   }
37395
37396               gcc_assert (!set_flags);
37397             }
37398
37399           rs6000_isa_flags &= ~dep_flags;
37400           ignore_masks |= no_flag | dep_flags;
37401         }
37402     }
37403
37404   return ignore_masks;
37405 }
37406
37407 \f
37408 /* Helper function for printing the function name when debugging.  */
37409
37410 static const char *
37411 get_decl_name (tree fn)
37412 {
37413   tree name;
37414
37415   if (!fn)
37416     return "<null>";
37417
37418   name = DECL_NAME (fn);
37419   if (!name)
37420     return "<no-name>";
37421
37422   return IDENTIFIER_POINTER (name);
37423 }
37424
37425 /* Return the clone id of the target we are compiling code for in a target
37426    clone.  The clone id is ordered from 0 (default) to CLONE_MAX-1 and gives
37427    the priority list for the target clones (ordered from lowest to
37428    highest).  */
37429
37430 static int
37431 rs6000_clone_priority (tree fndecl)
37432 {
37433   tree fn_opts = DECL_FUNCTION_SPECIFIC_TARGET (fndecl);
37434   HOST_WIDE_INT isa_masks;
37435   int ret = CLONE_DEFAULT;
37436   tree attrs = lookup_attribute ("target", DECL_ATTRIBUTES (fndecl));
37437   const char *attrs_str = NULL;
37438
37439   attrs = TREE_VALUE (TREE_VALUE (attrs));
37440   attrs_str = TREE_STRING_POINTER (attrs);
37441
37442   /* Return priority zero for default function.  Return the ISA needed for the
37443      function if it is not the default.  */
37444   if (strcmp (attrs_str, "default") != 0)
37445     {
37446       if (fn_opts == NULL_TREE)
37447         fn_opts = target_option_default_node;
37448
37449       if (!fn_opts || !TREE_TARGET_OPTION (fn_opts))
37450         isa_masks = rs6000_isa_flags;
37451       else
37452         isa_masks = TREE_TARGET_OPTION (fn_opts)->x_rs6000_isa_flags;
37453
37454       for (ret = CLONE_MAX - 1; ret != 0; ret--)
37455         if ((rs6000_clone_map[ret].isa_mask & isa_masks) != 0)
37456           break;
37457     }
37458
37459   if (TARGET_DEBUG_TARGET)
37460     fprintf (stderr, "rs6000_get_function_version_priority (%s) => %d\n",
37461              get_decl_name (fndecl), ret);
37462
37463   return ret;
37464 }
37465
37466 /* This compares the priority of target features in function DECL1 and DECL2.
37467    It returns positive value if DECL1 is higher priority, negative value if
37468    DECL2 is higher priority and 0 if they are the same.  Note, priorities are
37469    ordered from lowest (CLONE_DEFAULT) to highest (currently CLONE_ISA_3_0).  */
37470
37471 static int
37472 rs6000_compare_version_priority (tree decl1, tree decl2)
37473 {
37474   int priority1 = rs6000_clone_priority (decl1);
37475   int priority2 = rs6000_clone_priority (decl2);
37476   int ret = priority1 - priority2;
37477
37478   if (TARGET_DEBUG_TARGET)
37479     fprintf (stderr, "rs6000_compare_version_priority (%s, %s) => %d\n",
37480              get_decl_name (decl1), get_decl_name (decl2), ret);
37481
37482   return ret;
37483 }
37484
37485 /* Make a dispatcher declaration for the multi-versioned function DECL.
37486    Calls to DECL function will be replaced with calls to the dispatcher
37487    by the front-end.  Returns the decl of the dispatcher function.  */
37488
37489 static tree
37490 rs6000_get_function_versions_dispatcher (void *decl)
37491 {
37492   tree fn = (tree) decl;
37493   struct cgraph_node *node = NULL;
37494   struct cgraph_node *default_node = NULL;
37495   struct cgraph_function_version_info *node_v = NULL;
37496   struct cgraph_function_version_info *first_v = NULL;
37497
37498   tree dispatch_decl = NULL;
37499
37500   struct cgraph_function_version_info *default_version_info = NULL;
37501   gcc_assert (fn != NULL && DECL_FUNCTION_VERSIONED (fn));
37502
37503   if (TARGET_DEBUG_TARGET)
37504     fprintf (stderr, "rs6000_get_function_versions_dispatcher (%s)\n",
37505              get_decl_name (fn));
37506
37507   node = cgraph_node::get (fn);
37508   gcc_assert (node != NULL);
37509
37510   node_v = node->function_version ();
37511   gcc_assert (node_v != NULL);
37512
37513   if (node_v->dispatcher_resolver != NULL)
37514     return node_v->dispatcher_resolver;
37515
37516   /* Find the default version and make it the first node.  */
37517   first_v = node_v;
37518   /* Go to the beginning of the chain.  */
37519   while (first_v->prev != NULL)
37520     first_v = first_v->prev;
37521
37522   default_version_info = first_v;
37523   while (default_version_info != NULL)
37524     {
37525       const tree decl2 = default_version_info->this_node->decl;
37526       if (is_function_default_version (decl2))
37527         break;
37528       default_version_info = default_version_info->next;
37529     }
37530
37531   /* If there is no default node, just return NULL.  */
37532   if (default_version_info == NULL)
37533     return NULL;
37534
37535   /* Make default info the first node.  */
37536   if (first_v != default_version_info)
37537     {
37538       default_version_info->prev->next = default_version_info->next;
37539       if (default_version_info->next)
37540         default_version_info->next->prev = default_version_info->prev;
37541       first_v->prev = default_version_info;
37542       default_version_info->next = first_v;
37543       default_version_info->prev = NULL;
37544     }
37545
37546   default_node = default_version_info->this_node;
37547
37548 #ifndef TARGET_LIBC_PROVIDES_HWCAP_IN_TCB
37549   error_at (DECL_SOURCE_LOCATION (default_node->decl),
37550             "target_clones attribute needs GLIBC (2.23 and newer) that "
37551             "exports hardware capability bits");
37552 #else
37553
37554   if (targetm.has_ifunc_p ())
37555     {
37556       struct cgraph_function_version_info *it_v = NULL;
37557       struct cgraph_node *dispatcher_node = NULL;
37558       struct cgraph_function_version_info *dispatcher_version_info = NULL;
37559
37560       /* Right now, the dispatching is done via ifunc.  */
37561       dispatch_decl = make_dispatcher_decl (default_node->decl);
37562
37563       dispatcher_node = cgraph_node::get_create (dispatch_decl);
37564       gcc_assert (dispatcher_node != NULL);
37565       dispatcher_node->dispatcher_function = 1;
37566       dispatcher_version_info
37567         = dispatcher_node->insert_new_function_version ();
37568       dispatcher_version_info->next = default_version_info;
37569       dispatcher_node->definition = 1;
37570
37571       /* Set the dispatcher for all the versions.  */
37572       it_v = default_version_info;
37573       while (it_v != NULL)
37574         {
37575           it_v->dispatcher_resolver = dispatch_decl;
37576           it_v = it_v->next;
37577         }
37578     }
37579   else
37580     {
37581       error_at (DECL_SOURCE_LOCATION (default_node->decl),
37582                 "multiversioning needs ifunc which is not supported "
37583                 "on this target");
37584     }
37585 #endif
37586
37587   return dispatch_decl;
37588 }
37589
37590 /* Make the resolver function decl to dispatch the versions of a multi-
37591    versioned function, DEFAULT_DECL.  Create an empty basic block in the
37592    resolver and store the pointer in EMPTY_BB.  Return the decl of the resolver
37593    function.  */
37594
37595 static tree
37596 make_resolver_func (const tree default_decl,
37597                     const tree dispatch_decl,
37598                     basic_block *empty_bb)
37599 {
37600   /* Make the resolver function static.  The resolver function returns
37601      void *.  */
37602   tree decl_name = clone_function_name (default_decl, "resolver");
37603   const char *resolver_name = IDENTIFIER_POINTER (decl_name);
37604   tree type = build_function_type_list (ptr_type_node, NULL_TREE);
37605   tree decl = build_fn_decl (resolver_name, type);
37606   SET_DECL_ASSEMBLER_NAME (decl, decl_name);
37607
37608   DECL_NAME (decl) = decl_name;
37609   TREE_USED (decl) = 1;
37610   DECL_ARTIFICIAL (decl) = 1;
37611   DECL_IGNORED_P (decl) = 0;
37612   TREE_PUBLIC (decl) = 0;
37613   DECL_UNINLINABLE (decl) = 1;
37614
37615   /* Resolver is not external, body is generated.  */
37616   DECL_EXTERNAL (decl) = 0;
37617   DECL_EXTERNAL (dispatch_decl) = 0;
37618
37619   DECL_CONTEXT (decl) = NULL_TREE;
37620   DECL_INITIAL (decl) = make_node (BLOCK);
37621   DECL_STATIC_CONSTRUCTOR (decl) = 0;
37622
37623   /* Build result decl and add to function_decl.  */
37624   tree t = build_decl (UNKNOWN_LOCATION, RESULT_DECL, NULL_TREE, ptr_type_node);
37625   DECL_ARTIFICIAL (t) = 1;
37626   DECL_IGNORED_P (t) = 1;
37627   DECL_RESULT (decl) = t;
37628
37629   gimplify_function_tree (decl);
37630   push_cfun (DECL_STRUCT_FUNCTION (decl));
37631   *empty_bb = init_lowered_empty_function (decl, false,
37632                                            profile_count::uninitialized ());
37633
37634   cgraph_node::add_new_function (decl, true);
37635   symtab->call_cgraph_insertion_hooks (cgraph_node::get_create (decl));
37636
37637   pop_cfun ();
37638
37639   /* Mark dispatch_decl as "ifunc" with resolver as resolver_name.  */
37640   DECL_ATTRIBUTES (dispatch_decl)
37641     = make_attribute ("ifunc", resolver_name, DECL_ATTRIBUTES (dispatch_decl));
37642
37643   cgraph_node::create_same_body_alias (dispatch_decl, decl);
37644
37645   return decl;
37646 }
37647
37648 /* This adds a condition to the basic_block NEW_BB in function FUNCTION_DECL to
37649    return a pointer to VERSION_DECL if we are running on a machine that
37650    supports the index CLONE_ISA hardware architecture bits.  This function will
37651    be called during version dispatch to decide which function version to
37652    execute.  It returns the basic block at the end, to which more conditions
37653    can be added.  */
37654
37655 static basic_block
37656 add_condition_to_bb (tree function_decl, tree version_decl,
37657                      int clone_isa, basic_block new_bb)
37658 {
37659   push_cfun (DECL_STRUCT_FUNCTION (function_decl));
37660
37661   gcc_assert (new_bb != NULL);
37662   gimple_seq gseq = bb_seq (new_bb);
37663
37664
37665   tree convert_expr = build1 (CONVERT_EXPR, ptr_type_node,
37666                               build_fold_addr_expr (version_decl));
37667   tree result_var = create_tmp_var (ptr_type_node);
37668   gimple *convert_stmt = gimple_build_assign (result_var, convert_expr);
37669   gimple *return_stmt = gimple_build_return (result_var);
37670
37671   if (clone_isa == CLONE_DEFAULT)
37672     {
37673       gimple_seq_add_stmt (&gseq, convert_stmt);
37674       gimple_seq_add_stmt (&gseq, return_stmt);
37675       set_bb_seq (new_bb, gseq);
37676       gimple_set_bb (convert_stmt, new_bb);
37677       gimple_set_bb (return_stmt, new_bb);
37678       pop_cfun ();
37679       return new_bb;
37680     }
37681
37682   tree bool_zero = build_int_cst (bool_int_type_node, 0);
37683   tree cond_var = create_tmp_var (bool_int_type_node);
37684   tree predicate_decl = rs6000_builtin_decls [(int) RS6000_BUILTIN_CPU_SUPPORTS];
37685   const char *arg_str = rs6000_clone_map[clone_isa].name;
37686   tree predicate_arg = build_string_literal (strlen (arg_str) + 1, arg_str);
37687   gimple *call_cond_stmt = gimple_build_call (predicate_decl, 1, predicate_arg);
37688   gimple_call_set_lhs (call_cond_stmt, cond_var);
37689
37690   gimple_set_block (call_cond_stmt, DECL_INITIAL (function_decl));
37691   gimple_set_bb (call_cond_stmt, new_bb);
37692   gimple_seq_add_stmt (&gseq, call_cond_stmt);
37693
37694   gimple *if_else_stmt = gimple_build_cond (NE_EXPR, cond_var, bool_zero,
37695                                             NULL_TREE, NULL_TREE);
37696   gimple_set_block (if_else_stmt, DECL_INITIAL (function_decl));
37697   gimple_set_bb (if_else_stmt, new_bb);
37698   gimple_seq_add_stmt (&gseq, if_else_stmt);
37699
37700   gimple_seq_add_stmt (&gseq, convert_stmt);
37701   gimple_seq_add_stmt (&gseq, return_stmt);
37702   set_bb_seq (new_bb, gseq);
37703
37704   basic_block bb1 = new_bb;
37705   edge e12 = split_block (bb1, if_else_stmt);
37706   basic_block bb2 = e12->dest;
37707   e12->flags &= ~EDGE_FALLTHRU;
37708   e12->flags |= EDGE_TRUE_VALUE;
37709
37710   edge e23 = split_block (bb2, return_stmt);
37711   gimple_set_bb (convert_stmt, bb2);
37712   gimple_set_bb (return_stmt, bb2);
37713
37714   basic_block bb3 = e23->dest;
37715   make_edge (bb1, bb3, EDGE_FALSE_VALUE);
37716
37717   remove_edge (e23);
37718   make_edge (bb2, EXIT_BLOCK_PTR_FOR_FN (cfun), 0);
37719
37720   pop_cfun ();
37721   return bb3;
37722 }
37723
37724 /* This function generates the dispatch function for multi-versioned functions.
37725    DISPATCH_DECL is the function which will contain the dispatch logic.
37726    FNDECLS are the function choices for dispatch, and is a tree chain.
37727    EMPTY_BB is the basic block pointer in DISPATCH_DECL in which the dispatch
37728    code is generated.  */
37729
37730 static int
37731 dispatch_function_versions (tree dispatch_decl,
37732                             void *fndecls_p,
37733                             basic_block *empty_bb)
37734 {
37735   int ix;
37736   tree ele;
37737   vec<tree> *fndecls;
37738   tree clones[CLONE_MAX];
37739
37740   if (TARGET_DEBUG_TARGET)
37741     fputs ("dispatch_function_versions, top\n", stderr);
37742
37743   gcc_assert (dispatch_decl != NULL
37744               && fndecls_p != NULL
37745               && empty_bb != NULL);
37746
37747   /* fndecls_p is actually a vector.  */
37748   fndecls = static_cast<vec<tree> *> (fndecls_p);
37749
37750   /* At least one more version other than the default.  */
37751   gcc_assert (fndecls->length () >= 2);
37752
37753   /* The first version in the vector is the default decl.  */
37754   memset ((void *) clones, '\0', sizeof (clones));
37755   clones[CLONE_DEFAULT] = (*fndecls)[0];
37756
37757   /* On the PowerPC, we do not need to call __builtin_cpu_init, which is a NOP
37758      on the PowerPC (on the x86_64, it is not a NOP).  The builtin function
37759      __builtin_cpu_support ensures that the TOC fields are setup by requiring a
37760      recent glibc.  If we ever need to call __builtin_cpu_init, we would need
37761      to insert the code here to do the call.  */
37762
37763   for (ix = 1; fndecls->iterate (ix, &ele); ++ix)
37764     {
37765       int priority = rs6000_clone_priority (ele);
37766       if (!clones[priority])
37767         clones[priority] = ele;
37768     }
37769
37770   for (ix = CLONE_MAX - 1; ix >= 0; ix--)
37771     if (clones[ix])
37772       {
37773         if (TARGET_DEBUG_TARGET)
37774           fprintf (stderr, "dispatch_function_versions, clone %d, %s\n",
37775                    ix, get_decl_name (clones[ix]));
37776
37777         *empty_bb = add_condition_to_bb (dispatch_decl, clones[ix], ix,
37778                                          *empty_bb);
37779       }
37780
37781   return 0;
37782 }
37783
37784 /* Generate the dispatching code body to dispatch multi-versioned function
37785    DECL.  The target hook is called to process the "target" attributes and
37786    provide the code to dispatch the right function at run-time.  NODE points
37787    to the dispatcher decl whose body will be created.  */
37788
37789 static tree
37790 rs6000_generate_version_dispatcher_body (void *node_p)
37791 {
37792   tree resolver;
37793   basic_block empty_bb;
37794   struct cgraph_node *node = (cgraph_node *) node_p;
37795   struct cgraph_function_version_info *ninfo = node->function_version ();
37796
37797   if (ninfo->dispatcher_resolver)
37798     return ninfo->dispatcher_resolver;
37799
37800   /* node is going to be an alias, so remove the finalized bit.  */
37801   node->definition = false;
37802
37803   /* The first version in the chain corresponds to the default version.  */
37804   ninfo->dispatcher_resolver = resolver
37805     = make_resolver_func (ninfo->next->this_node->decl, node->decl, &empty_bb);
37806
37807   if (TARGET_DEBUG_TARGET)
37808     fprintf (stderr, "rs6000_get_function_versions_dispatcher, %s\n",
37809              get_decl_name (resolver));
37810
37811   push_cfun (DECL_STRUCT_FUNCTION (resolver));
37812   auto_vec<tree, 2> fn_ver_vec;
37813
37814   for (struct cgraph_function_version_info *vinfo = ninfo->next;
37815        vinfo;
37816        vinfo = vinfo->next)
37817     {
37818       struct cgraph_node *version = vinfo->this_node;
37819       /* Check for virtual functions here again, as by this time it should
37820          have been determined if this function needs a vtable index or
37821          not.  This happens for methods in derived classes that override
37822          virtual methods in base classes but are not explicitly marked as
37823          virtual.  */
37824       if (DECL_VINDEX (version->decl))
37825         sorry ("Virtual function multiversioning not supported");
37826
37827       fn_ver_vec.safe_push (version->decl);
37828     }
37829
37830   dispatch_function_versions (resolver, &fn_ver_vec, &empty_bb);
37831   cgraph_edge::rebuild_edges ();
37832   pop_cfun ();
37833   return resolver;
37834 }
37835
37836 \f
37837 /* Hook to determine if one function can safely inline another.  */
37838
37839 static bool
37840 rs6000_can_inline_p (tree caller, tree callee)
37841 {
37842   bool ret = false;
37843   tree caller_tree = DECL_FUNCTION_SPECIFIC_TARGET (caller);
37844   tree callee_tree = DECL_FUNCTION_SPECIFIC_TARGET (callee);
37845
37846   /* If callee has no option attributes, then it is ok to inline.  */
37847   if (!callee_tree)
37848     ret = true;
37849
37850   /* If caller has no option attributes, but callee does then it is not ok to
37851      inline.  */
37852   else if (!caller_tree)
37853     ret = false;
37854
37855   else
37856     {
37857       struct cl_target_option *caller_opts = TREE_TARGET_OPTION (caller_tree);
37858       struct cl_target_option *callee_opts = TREE_TARGET_OPTION (callee_tree);
37859
37860       /* Callee's options should a subset of the caller's, i.e. a vsx function
37861          can inline an altivec function but a non-vsx function can't inline a
37862          vsx function.  */
37863       if ((caller_opts->x_rs6000_isa_flags & callee_opts->x_rs6000_isa_flags)
37864           == callee_opts->x_rs6000_isa_flags)
37865         ret = true;
37866     }
37867
37868   if (TARGET_DEBUG_TARGET)
37869     fprintf (stderr, "rs6000_can_inline_p:, caller %s, callee %s, %s inline\n",
37870              get_decl_name (caller), get_decl_name (callee),
37871              (ret ? "can" : "cannot"));
37872
37873   return ret;
37874 }
37875 \f
37876 /* Allocate a stack temp and fixup the address so it meets the particular
37877    memory requirements (either offetable or REG+REG addressing).  */
37878
37879 rtx
37880 rs6000_allocate_stack_temp (machine_mode mode,
37881                             bool offsettable_p,
37882                             bool reg_reg_p)
37883 {
37884   rtx stack = assign_stack_temp (mode, GET_MODE_SIZE (mode));
37885   rtx addr = XEXP (stack, 0);
37886   int strict_p = reload_completed;
37887
37888   if (!legitimate_indirect_address_p (addr, strict_p))
37889     {
37890       if (offsettable_p
37891           && !rs6000_legitimate_offset_address_p (mode, addr, strict_p, true))
37892         stack = replace_equiv_address (stack, copy_addr_to_reg (addr));
37893
37894       else if (reg_reg_p && !legitimate_indexed_address_p (addr, strict_p))
37895         stack = replace_equiv_address (stack, copy_addr_to_reg (addr));
37896     }
37897
37898   return stack;
37899 }
37900
37901 /* Given a memory reference, if it is not a reg or reg+reg addressing, convert
37902    to such a form to deal with memory reference instructions like STFIWX that
37903    only take reg+reg addressing.  */
37904
37905 rtx
37906 rs6000_address_for_fpconvert (rtx x)
37907 {
37908   rtx addr;
37909
37910   gcc_assert (MEM_P (x));
37911   addr = XEXP (x, 0);
37912   if (can_create_pseudo_p ()
37913       && ! legitimate_indirect_address_p (addr, reload_completed)
37914       && ! legitimate_indexed_address_p (addr, reload_completed))
37915     {
37916       if (GET_CODE (addr) == PRE_INC || GET_CODE (addr) == PRE_DEC)
37917         {
37918           rtx reg = XEXP (addr, 0);
37919           HOST_WIDE_INT size = GET_MODE_SIZE (GET_MODE (x));
37920           rtx size_rtx = GEN_INT ((GET_CODE (addr) == PRE_DEC) ? -size : size);
37921           gcc_assert (REG_P (reg));
37922           emit_insn (gen_add3_insn (reg, reg, size_rtx));
37923           addr = reg;
37924         }
37925       else if (GET_CODE (addr) == PRE_MODIFY)
37926         {
37927           rtx reg = XEXP (addr, 0);
37928           rtx expr = XEXP (addr, 1);
37929           gcc_assert (REG_P (reg));
37930           gcc_assert (GET_CODE (expr) == PLUS);
37931           emit_insn (gen_add3_insn (reg, XEXP (expr, 0), XEXP (expr, 1)));
37932           addr = reg;
37933         }
37934
37935       x = replace_equiv_address (x, copy_addr_to_reg (addr));
37936     }
37937
37938   return x;
37939 }
37940
37941 /* Given a memory reference, if it is not in the form for altivec memory
37942    reference instructions (i.e. reg or reg+reg addressing with AND of -16),
37943    convert to the altivec format.  */
37944
37945 rtx
37946 rs6000_address_for_altivec (rtx x)
37947 {
37948   gcc_assert (MEM_P (x));
37949   if (!altivec_indexed_or_indirect_operand (x, GET_MODE (x)))
37950     {
37951       rtx addr = XEXP (x, 0);
37952
37953       if (!legitimate_indexed_address_p (addr, reload_completed)
37954           && !legitimate_indirect_address_p (addr, reload_completed))
37955         addr = copy_to_mode_reg (Pmode, addr);
37956
37957       addr = gen_rtx_AND (Pmode, addr, GEN_INT (-16));
37958       x = change_address (x, GET_MODE (x), addr);
37959     }
37960
37961   return x;
37962 }
37963
37964 /* Implement TARGET_LEGITIMATE_CONSTANT_P.
37965
37966    On the RS/6000, all integer constants are acceptable, most won't be valid
37967    for particular insns, though.  Only easy FP constants are acceptable.  */
37968
37969 static bool
37970 rs6000_legitimate_constant_p (machine_mode mode, rtx x)
37971 {
37972   if (TARGET_ELF && tls_referenced_p (x))
37973     return false;
37974
37975   return ((GET_CODE (x) != CONST_DOUBLE && GET_CODE (x) != CONST_VECTOR)
37976           || GET_MODE (x) == VOIDmode
37977           || (TARGET_POWERPC64 && mode == DImode)
37978           || easy_fp_constant (x, mode)
37979           || easy_vector_constant (x, mode));
37980 }
37981
37982 \f
37983 /* Return TRUE iff the sequence ending in LAST sets the static chain.  */
37984
37985 static bool
37986 chain_already_loaded (rtx_insn *last)
37987 {
37988   for (; last != NULL; last = PREV_INSN (last))
37989     {
37990       if (NONJUMP_INSN_P (last))
37991         {
37992           rtx patt = PATTERN (last);
37993
37994           if (GET_CODE (patt) == SET)
37995             {
37996               rtx lhs = XEXP (patt, 0);
37997
37998               if (REG_P (lhs) && REGNO (lhs) == STATIC_CHAIN_REGNUM)
37999                 return true;
38000             }
38001         }
38002     }
38003   return false;
38004 }
38005
38006 /* Expand code to perform a call under the AIX or ELFv2 ABI.  */
38007
38008 void
38009 rs6000_call_aix (rtx value, rtx func_desc, rtx flag, rtx cookie)
38010 {
38011   const bool direct_call_p
38012     = GET_CODE (func_desc) == SYMBOL_REF && SYMBOL_REF_FUNCTION_P (func_desc);
38013   rtx toc_reg = gen_rtx_REG (Pmode, TOC_REGNUM);
38014   rtx toc_load = NULL_RTX;
38015   rtx toc_restore = NULL_RTX;
38016   rtx func_addr;
38017   rtx abi_reg = NULL_RTX;
38018   rtx call[4];
38019   int n_call;
38020   rtx insn;
38021
38022   /* Handle longcall attributes.  */
38023   if (INTVAL (cookie) & CALL_LONG)
38024     func_desc = rs6000_longcall_ref (func_desc);
38025
38026   /* Handle indirect calls.  */
38027   if (GET_CODE (func_desc) != SYMBOL_REF
38028       || (DEFAULT_ABI == ABI_AIX && !SYMBOL_REF_FUNCTION_P (func_desc)))
38029     {
38030       /* Save the TOC into its reserved slot before the call,
38031          and prepare to restore it after the call.  */
38032       rtx stack_ptr = gen_rtx_REG (Pmode, STACK_POINTER_REGNUM);
38033       rtx stack_toc_offset = GEN_INT (RS6000_TOC_SAVE_SLOT);
38034       rtx stack_toc_mem = gen_frame_mem (Pmode,
38035                                          gen_rtx_PLUS (Pmode, stack_ptr,
38036                                                        stack_toc_offset));
38037       rtx stack_toc_unspec = gen_rtx_UNSPEC (Pmode,
38038                                              gen_rtvec (1, stack_toc_offset),
38039                                              UNSPEC_TOCSLOT);
38040       toc_restore = gen_rtx_SET (toc_reg, stack_toc_unspec);
38041
38042       /* Can we optimize saving the TOC in the prologue or
38043          do we need to do it at every call?  */
38044       if (TARGET_SAVE_TOC_INDIRECT && !cfun->calls_alloca)
38045         cfun->machine->save_toc_in_prologue = true;
38046       else
38047         {
38048           MEM_VOLATILE_P (stack_toc_mem) = 1;
38049           emit_move_insn (stack_toc_mem, toc_reg);
38050         }
38051
38052       if (DEFAULT_ABI == ABI_ELFv2)
38053         {
38054           /* A function pointer in the ELFv2 ABI is just a plain address, but
38055              the ABI requires it to be loaded into r12 before the call.  */
38056           func_addr = gen_rtx_REG (Pmode, 12);
38057           emit_move_insn (func_addr, func_desc);
38058           abi_reg = func_addr;
38059         }
38060       else
38061         {
38062           /* A function pointer under AIX is a pointer to a data area whose
38063              first word contains the actual address of the function, whose
38064              second word contains a pointer to its TOC, and whose third word
38065              contains a value to place in the static chain register (r11).
38066              Note that if we load the static chain, our "trampoline" need
38067              not have any executable code.  */
38068
38069           /* Load up address of the actual function.  */
38070           func_desc = force_reg (Pmode, func_desc);
38071           func_addr = gen_reg_rtx (Pmode);
38072           emit_move_insn (func_addr, gen_rtx_MEM (Pmode, func_desc));
38073
38074           /* Prepare to load the TOC of the called function.  Note that the
38075              TOC load must happen immediately before the actual call so
38076              that unwinding the TOC registers works correctly.  See the
38077              comment in frob_update_context.  */
38078           rtx func_toc_offset = GEN_INT (GET_MODE_SIZE (Pmode));
38079           rtx func_toc_mem = gen_rtx_MEM (Pmode,
38080                                           gen_rtx_PLUS (Pmode, func_desc,
38081                                                         func_toc_offset));
38082           toc_load = gen_rtx_USE (VOIDmode, func_toc_mem);
38083
38084           /* If we have a static chain, load it up.  But, if the call was
38085              originally direct, the 3rd word has not been written since no
38086              trampoline has been built, so we ought not to load it, lest we
38087              override a static chain value.  */
38088           if (!direct_call_p
38089               && TARGET_POINTERS_TO_NESTED_FUNCTIONS
38090               && !chain_already_loaded (get_current_sequence ()->next->last))
38091             {
38092               rtx sc_reg = gen_rtx_REG (Pmode, STATIC_CHAIN_REGNUM);
38093               rtx func_sc_offset = GEN_INT (2 * GET_MODE_SIZE (Pmode));
38094               rtx func_sc_mem = gen_rtx_MEM (Pmode,
38095                                              gen_rtx_PLUS (Pmode, func_desc,
38096                                                            func_sc_offset));
38097               emit_move_insn (sc_reg, func_sc_mem);
38098               abi_reg = sc_reg;
38099             }
38100         }
38101     }
38102   else
38103     {
38104       /* Direct calls use the TOC: for local calls, the callee will
38105          assume the TOC register is set; for non-local calls, the
38106          PLT stub needs the TOC register.  */
38107       abi_reg = toc_reg;
38108       func_addr = func_desc;
38109     }
38110
38111   /* Create the call.  */
38112   call[0] = gen_rtx_CALL (VOIDmode, gen_rtx_MEM (SImode, func_addr), flag);
38113   if (value != NULL_RTX)
38114     call[0] = gen_rtx_SET (value, call[0]);
38115   n_call = 1;
38116
38117   if (toc_load)
38118     call[n_call++] = toc_load;
38119   if (toc_restore)
38120     call[n_call++] = toc_restore;
38121
38122   call[n_call++] = gen_rtx_CLOBBER (VOIDmode, gen_rtx_REG (Pmode, LR_REGNO));
38123
38124   insn = gen_rtx_PARALLEL (VOIDmode, gen_rtvec_v (n_call, call));
38125   insn = emit_call_insn (insn);
38126
38127   /* Mention all registers defined by the ABI to hold information
38128      as uses in CALL_INSN_FUNCTION_USAGE.  */
38129   if (abi_reg)
38130     use_reg (&CALL_INSN_FUNCTION_USAGE (insn), abi_reg);
38131 }
38132
38133 /* Expand code to perform a sibling call under the AIX or ELFv2 ABI.  */
38134
38135 void
38136 rs6000_sibcall_aix (rtx value, rtx func_desc, rtx flag, rtx cookie)
38137 {
38138   rtx call[2];
38139   rtx insn;
38140
38141   gcc_assert (INTVAL (cookie) == 0);
38142
38143   /* Create the call.  */
38144   call[0] = gen_rtx_CALL (VOIDmode, gen_rtx_MEM (SImode, func_desc), flag);
38145   if (value != NULL_RTX)
38146     call[0] = gen_rtx_SET (value, call[0]);
38147
38148   call[1] = simple_return_rtx;
38149
38150   insn = gen_rtx_PARALLEL (VOIDmode, gen_rtvec_v (2, call));
38151   insn = emit_call_insn (insn);
38152
38153   /* Note use of the TOC register.  */
38154   use_reg (&CALL_INSN_FUNCTION_USAGE (insn), gen_rtx_REG (Pmode, TOC_REGNUM));
38155 }
38156
38157 /* Return whether we need to always update the saved TOC pointer when we update
38158    the stack pointer.  */
38159
38160 static bool
38161 rs6000_save_toc_in_prologue_p (void)
38162 {
38163   return (cfun && cfun->machine && cfun->machine->save_toc_in_prologue);
38164 }
38165
38166 #ifdef HAVE_GAS_HIDDEN
38167 # define USE_HIDDEN_LINKONCE 1
38168 #else
38169 # define USE_HIDDEN_LINKONCE 0
38170 #endif
38171
38172 /* Fills in the label name that should be used for a 476 link stack thunk.  */
38173
38174 void
38175 get_ppc476_thunk_name (char name[32])
38176 {
38177   gcc_assert (TARGET_LINK_STACK);
38178
38179   if (USE_HIDDEN_LINKONCE)
38180     sprintf (name, "__ppc476.get_thunk");
38181   else
38182     ASM_GENERATE_INTERNAL_LABEL (name, "LPPC476_", 0);
38183 }
38184
38185 /* This function emits the simple thunk routine that is used to preserve
38186    the link stack on the 476 cpu.  */
38187
38188 static void rs6000_code_end (void) ATTRIBUTE_UNUSED;
38189 static void
38190 rs6000_code_end (void)
38191 {
38192   char name[32];
38193   tree decl;
38194
38195   if (!TARGET_LINK_STACK)
38196     return;
38197
38198   get_ppc476_thunk_name (name);
38199
38200   decl = build_decl (BUILTINS_LOCATION, FUNCTION_DECL, get_identifier (name),
38201                      build_function_type_list (void_type_node, NULL_TREE));
38202   DECL_RESULT (decl) = build_decl (BUILTINS_LOCATION, RESULT_DECL,
38203                                    NULL_TREE, void_type_node);
38204   TREE_PUBLIC (decl) = 1;
38205   TREE_STATIC (decl) = 1;
38206
38207 #if RS6000_WEAK
38208   if (USE_HIDDEN_LINKONCE && !TARGET_XCOFF)
38209     {
38210       cgraph_node::create (decl)->set_comdat_group (DECL_ASSEMBLER_NAME (decl));
38211       targetm.asm_out.unique_section (decl, 0);
38212       switch_to_section (get_named_section (decl, NULL, 0));
38213       DECL_WEAK (decl) = 1;
38214       ASM_WEAKEN_DECL (asm_out_file, decl, name, 0);
38215       targetm.asm_out.globalize_label (asm_out_file, name);
38216       targetm.asm_out.assemble_visibility (decl, VISIBILITY_HIDDEN);
38217       ASM_DECLARE_FUNCTION_NAME (asm_out_file, name, decl);
38218     }
38219   else
38220 #endif
38221     {
38222       switch_to_section (text_section);
38223       ASM_OUTPUT_LABEL (asm_out_file, name);
38224     }
38225
38226   DECL_INITIAL (decl) = make_node (BLOCK);
38227   current_function_decl = decl;
38228   allocate_struct_function (decl, false);
38229   init_function_start (decl);
38230   first_function_block_is_cold = false;
38231   /* Make sure unwind info is emitted for the thunk if needed.  */
38232   final_start_function (emit_barrier (), asm_out_file, 1);
38233
38234   fputs ("\tblr\n", asm_out_file);
38235
38236   final_end_function ();
38237   init_insn_lengths ();
38238   free_after_compilation (cfun);
38239   set_cfun (NULL);
38240   current_function_decl = NULL;
38241 }
38242
38243 /* Add r30 to hard reg set if the prologue sets it up and it is not
38244    pic_offset_table_rtx.  */
38245
38246 static void
38247 rs6000_set_up_by_prologue (struct hard_reg_set_container *set)
38248 {
38249   if (!TARGET_SINGLE_PIC_BASE
38250       && TARGET_TOC
38251       && TARGET_MINIMAL_TOC
38252       && !constant_pool_empty_p ())
38253     add_to_hard_reg_set (&set->set, Pmode, RS6000_PIC_OFFSET_TABLE_REGNUM);
38254   if (cfun->machine->split_stack_argp_used)
38255     add_to_hard_reg_set (&set->set, Pmode, 12);
38256
38257   /* Make sure the hard reg set doesn't include r2, which was possibly added
38258      via PIC_OFFSET_TABLE_REGNUM.  */
38259   if (TARGET_TOC)
38260     remove_from_hard_reg_set (&set->set, Pmode, TOC_REGNUM);
38261 }
38262
38263 \f
38264 /* Helper function for rs6000_split_logical to emit a logical instruction after
38265    spliting the operation to single GPR registers.
38266
38267    DEST is the destination register.
38268    OP1 and OP2 are the input source registers.
38269    CODE is the base operation (AND, IOR, XOR, NOT).
38270    MODE is the machine mode.
38271    If COMPLEMENT_FINAL_P is true, wrap the whole operation with NOT.
38272    If COMPLEMENT_OP1_P is true, wrap operand1 with NOT.
38273    If COMPLEMENT_OP2_P is true, wrap operand2 with NOT.  */
38274
38275 static void
38276 rs6000_split_logical_inner (rtx dest,
38277                             rtx op1,
38278                             rtx op2,
38279                             enum rtx_code code,
38280                             machine_mode mode,
38281                             bool complement_final_p,
38282                             bool complement_op1_p,
38283                             bool complement_op2_p)
38284 {
38285   rtx bool_rtx;
38286
38287   /* Optimize AND of 0/0xffffffff and IOR/XOR of 0.  */
38288   if (op2 && GET_CODE (op2) == CONST_INT
38289       && (mode == SImode || (mode == DImode && TARGET_POWERPC64))
38290       && !complement_final_p && !complement_op1_p && !complement_op2_p)
38291     {
38292       HOST_WIDE_INT mask = GET_MODE_MASK (mode);
38293       HOST_WIDE_INT value = INTVAL (op2) & mask;
38294
38295       /* Optimize AND of 0 to just set 0.  Optimize AND of -1 to be a move.  */
38296       if (code == AND)
38297         {
38298           if (value == 0)
38299             {
38300               emit_insn (gen_rtx_SET (dest, const0_rtx));
38301               return;
38302             }
38303
38304           else if (value == mask)
38305             {
38306               if (!rtx_equal_p (dest, op1))
38307                 emit_insn (gen_rtx_SET (dest, op1));
38308               return;
38309             }
38310         }
38311
38312       /* Optimize IOR/XOR of 0 to be a simple move.  Split large operations
38313          into separate ORI/ORIS or XORI/XORIS instrucitons.  */
38314       else if (code == IOR || code == XOR)
38315         {
38316           if (value == 0)
38317             {
38318               if (!rtx_equal_p (dest, op1))
38319                 emit_insn (gen_rtx_SET (dest, op1));
38320               return;
38321             }
38322         }
38323     }
38324
38325   if (code == AND && mode == SImode
38326       && !complement_final_p && !complement_op1_p && !complement_op2_p)
38327     {
38328       emit_insn (gen_andsi3 (dest, op1, op2));
38329       return;
38330     }
38331
38332   if (complement_op1_p)
38333     op1 = gen_rtx_NOT (mode, op1);
38334
38335   if (complement_op2_p)
38336     op2 = gen_rtx_NOT (mode, op2);
38337
38338   /* For canonical RTL, if only one arm is inverted it is the first.  */
38339   if (!complement_op1_p && complement_op2_p)
38340     std::swap (op1, op2);
38341
38342   bool_rtx = ((code == NOT)
38343               ? gen_rtx_NOT (mode, op1)
38344               : gen_rtx_fmt_ee (code, mode, op1, op2));
38345
38346   if (complement_final_p)
38347     bool_rtx = gen_rtx_NOT (mode, bool_rtx);
38348
38349   emit_insn (gen_rtx_SET (dest, bool_rtx));
38350 }
38351
38352 /* Split a DImode AND/IOR/XOR with a constant on a 32-bit system.  These
38353    operations are split immediately during RTL generation to allow for more
38354    optimizations of the AND/IOR/XOR.
38355
38356    OPERANDS is an array containing the destination and two input operands.
38357    CODE is the base operation (AND, IOR, XOR, NOT).
38358    MODE is the machine mode.
38359    If COMPLEMENT_FINAL_P is true, wrap the whole operation with NOT.
38360    If COMPLEMENT_OP1_P is true, wrap operand1 with NOT.
38361    If COMPLEMENT_OP2_P is true, wrap operand2 with NOT.
38362    CLOBBER_REG is either NULL or a scratch register of type CC to allow
38363    formation of the AND instructions.  */
38364
38365 static void
38366 rs6000_split_logical_di (rtx operands[3],
38367                          enum rtx_code code,
38368                          bool complement_final_p,
38369                          bool complement_op1_p,
38370                          bool complement_op2_p)
38371 {
38372   const HOST_WIDE_INT lower_32bits = HOST_WIDE_INT_C(0xffffffff);
38373   const HOST_WIDE_INT upper_32bits = ~ lower_32bits;
38374   const HOST_WIDE_INT sign_bit = HOST_WIDE_INT_C(0x80000000);
38375   enum hi_lo { hi = 0, lo = 1 };
38376   rtx op0_hi_lo[2], op1_hi_lo[2], op2_hi_lo[2];
38377   size_t i;
38378
38379   op0_hi_lo[hi] = gen_highpart (SImode, operands[0]);
38380   op1_hi_lo[hi] = gen_highpart (SImode, operands[1]);
38381   op0_hi_lo[lo] = gen_lowpart (SImode, operands[0]);
38382   op1_hi_lo[lo] = gen_lowpart (SImode, operands[1]);
38383
38384   if (code == NOT)
38385     op2_hi_lo[hi] = op2_hi_lo[lo] = NULL_RTX;
38386   else
38387     {
38388       if (GET_CODE (operands[2]) != CONST_INT)
38389         {
38390           op2_hi_lo[hi] = gen_highpart_mode (SImode, DImode, operands[2]);
38391           op2_hi_lo[lo] = gen_lowpart (SImode, operands[2]);
38392         }
38393       else
38394         {
38395           HOST_WIDE_INT value = INTVAL (operands[2]);
38396           HOST_WIDE_INT value_hi_lo[2];
38397
38398           gcc_assert (!complement_final_p);
38399           gcc_assert (!complement_op1_p);
38400           gcc_assert (!complement_op2_p);
38401
38402           value_hi_lo[hi] = value >> 32;
38403           value_hi_lo[lo] = value & lower_32bits;
38404
38405           for (i = 0; i < 2; i++)
38406             {
38407               HOST_WIDE_INT sub_value = value_hi_lo[i];
38408
38409               if (sub_value & sign_bit)
38410                 sub_value |= upper_32bits;
38411
38412               op2_hi_lo[i] = GEN_INT (sub_value);
38413
38414               /* If this is an AND instruction, check to see if we need to load
38415                  the value in a register.  */
38416               if (code == AND && sub_value != -1 && sub_value != 0
38417                   && !and_operand (op2_hi_lo[i], SImode))
38418                 op2_hi_lo[i] = force_reg (SImode, op2_hi_lo[i]);
38419             }
38420         }
38421     }
38422
38423   for (i = 0; i < 2; i++)
38424     {
38425       /* Split large IOR/XOR operations.  */
38426       if ((code == IOR || code == XOR)
38427           && GET_CODE (op2_hi_lo[i]) == CONST_INT
38428           && !complement_final_p
38429           && !complement_op1_p
38430           && !complement_op2_p
38431           && !logical_const_operand (op2_hi_lo[i], SImode))
38432         {
38433           HOST_WIDE_INT value = INTVAL (op2_hi_lo[i]);
38434           HOST_WIDE_INT hi_16bits = value & HOST_WIDE_INT_C(0xffff0000);
38435           HOST_WIDE_INT lo_16bits = value & HOST_WIDE_INT_C(0x0000ffff);
38436           rtx tmp = gen_reg_rtx (SImode);
38437
38438           /* Make sure the constant is sign extended.  */
38439           if ((hi_16bits & sign_bit) != 0)
38440             hi_16bits |= upper_32bits;
38441
38442           rs6000_split_logical_inner (tmp, op1_hi_lo[i], GEN_INT (hi_16bits),
38443                                       code, SImode, false, false, false);
38444
38445           rs6000_split_logical_inner (op0_hi_lo[i], tmp, GEN_INT (lo_16bits),
38446                                       code, SImode, false, false, false);
38447         }
38448       else
38449         rs6000_split_logical_inner (op0_hi_lo[i], op1_hi_lo[i], op2_hi_lo[i],
38450                                     code, SImode, complement_final_p,
38451                                     complement_op1_p, complement_op2_p);
38452     }
38453
38454   return;
38455 }
38456
38457 /* Split the insns that make up boolean operations operating on multiple GPR
38458    registers.  The boolean MD patterns ensure that the inputs either are
38459    exactly the same as the output registers, or there is no overlap.
38460
38461    OPERANDS is an array containing the destination and two input operands.
38462    CODE is the base operation (AND, IOR, XOR, NOT).
38463    If COMPLEMENT_FINAL_P is true, wrap the whole operation with NOT.
38464    If COMPLEMENT_OP1_P is true, wrap operand1 with NOT.
38465    If COMPLEMENT_OP2_P is true, wrap operand2 with NOT.  */
38466
38467 void
38468 rs6000_split_logical (rtx operands[3],
38469                       enum rtx_code code,
38470                       bool complement_final_p,
38471                       bool complement_op1_p,
38472                       bool complement_op2_p)
38473 {
38474   machine_mode mode = GET_MODE (operands[0]);
38475   machine_mode sub_mode;
38476   rtx op0, op1, op2;
38477   int sub_size, regno0, regno1, nregs, i;
38478
38479   /* If this is DImode, use the specialized version that can run before
38480      register allocation.  */
38481   if (mode == DImode && !TARGET_POWERPC64)
38482     {
38483       rs6000_split_logical_di (operands, code, complement_final_p,
38484                                complement_op1_p, complement_op2_p);
38485       return;
38486     }
38487
38488   op0 = operands[0];
38489   op1 = operands[1];
38490   op2 = (code == NOT) ? NULL_RTX : operands[2];
38491   sub_mode = (TARGET_POWERPC64) ? DImode : SImode;
38492   sub_size = GET_MODE_SIZE (sub_mode);
38493   regno0 = REGNO (op0);
38494   regno1 = REGNO (op1);
38495
38496   gcc_assert (reload_completed);
38497   gcc_assert (IN_RANGE (regno0, FIRST_GPR_REGNO, LAST_GPR_REGNO));
38498   gcc_assert (IN_RANGE (regno1, FIRST_GPR_REGNO, LAST_GPR_REGNO));
38499
38500   nregs = rs6000_hard_regno_nregs[(int)mode][regno0];
38501   gcc_assert (nregs > 1);
38502
38503   if (op2 && REG_P (op2))
38504     gcc_assert (IN_RANGE (REGNO (op2), FIRST_GPR_REGNO, LAST_GPR_REGNO));
38505
38506   for (i = 0; i < nregs; i++)
38507     {
38508       int offset = i * sub_size;
38509       rtx sub_op0 = simplify_subreg (sub_mode, op0, mode, offset);
38510       rtx sub_op1 = simplify_subreg (sub_mode, op1, mode, offset);
38511       rtx sub_op2 = ((code == NOT)
38512                      ? NULL_RTX
38513                      : simplify_subreg (sub_mode, op2, mode, offset));
38514
38515       rs6000_split_logical_inner (sub_op0, sub_op1, sub_op2, code, sub_mode,
38516                                   complement_final_p, complement_op1_p,
38517                                   complement_op2_p);
38518     }
38519
38520   return;
38521 }
38522
38523 \f
38524 /* Return true if the peephole2 can combine a load involving a combination of
38525    an addis instruction and a load with an offset that can be fused together on
38526    a power8.  */
38527
38528 bool
38529 fusion_gpr_load_p (rtx addis_reg,       /* register set via addis.  */
38530                    rtx addis_value,     /* addis value.  */
38531                    rtx target,          /* target register that is loaded.  */
38532                    rtx mem)             /* bottom part of the memory addr.  */
38533 {
38534   rtx addr;
38535   rtx base_reg;
38536
38537   /* Validate arguments.  */
38538   if (!base_reg_operand (addis_reg, GET_MODE (addis_reg)))
38539     return false;
38540
38541   if (!base_reg_operand (target, GET_MODE (target)))
38542     return false;
38543
38544   if (!fusion_gpr_addis (addis_value, GET_MODE (addis_value)))
38545     return false;
38546
38547   /* Allow sign/zero extension.  */
38548   if (GET_CODE (mem) == ZERO_EXTEND
38549       || (GET_CODE (mem) == SIGN_EXTEND && TARGET_P8_FUSION_SIGN))
38550     mem = XEXP (mem, 0);
38551
38552   if (!MEM_P (mem))
38553     return false;
38554
38555   if (!fusion_gpr_mem_load (mem, GET_MODE (mem)))
38556     return false;
38557
38558   addr = XEXP (mem, 0);                 /* either PLUS or LO_SUM.  */
38559   if (GET_CODE (addr) != PLUS && GET_CODE (addr) != LO_SUM)
38560     return false;
38561
38562   /* Validate that the register used to load the high value is either the
38563      register being loaded, or we can safely replace its use.
38564
38565      This function is only called from the peephole2 pass and we assume that
38566      there are 2 instructions in the peephole (addis and load), so we want to
38567      check if the target register was not used in the memory address and the
38568      register to hold the addis result is dead after the peephole.  */
38569   if (REGNO (addis_reg) != REGNO (target))
38570     {
38571       if (reg_mentioned_p (target, mem))
38572         return false;
38573
38574       if (!peep2_reg_dead_p (2, addis_reg))
38575         return false;
38576
38577       /* If the target register being loaded is the stack pointer, we must
38578          avoid loading any other value into it, even temporarily.  */
38579       if (REG_P (target) && REGNO (target) == STACK_POINTER_REGNUM)
38580         return false;
38581     }
38582
38583   base_reg = XEXP (addr, 0);
38584   return REGNO (addis_reg) == REGNO (base_reg);
38585 }
38586
38587 /* During the peephole2 pass, adjust and expand the insns for a load fusion
38588    sequence.  We adjust the addis register to use the target register.  If the
38589    load sign extends, we adjust the code to do the zero extending load, and an
38590    explicit sign extension later since the fusion only covers zero extending
38591    loads.
38592
38593    The operands are:
38594         operands[0]     register set with addis (to be replaced with target)
38595         operands[1]     value set via addis
38596         operands[2]     target register being loaded
38597         operands[3]     D-form memory reference using operands[0].  */
38598
38599 void
38600 expand_fusion_gpr_load (rtx *operands)
38601 {
38602   rtx addis_value = operands[1];
38603   rtx target = operands[2];
38604   rtx orig_mem = operands[3];
38605   rtx  new_addr, new_mem, orig_addr, offset;
38606   enum rtx_code plus_or_lo_sum;
38607   machine_mode target_mode = GET_MODE (target);
38608   machine_mode extend_mode = target_mode;
38609   machine_mode ptr_mode = Pmode;
38610   enum rtx_code extend = UNKNOWN;
38611
38612   if (GET_CODE (orig_mem) == ZERO_EXTEND
38613       || (TARGET_P8_FUSION_SIGN && GET_CODE (orig_mem) == SIGN_EXTEND))
38614     {
38615       extend = GET_CODE (orig_mem);
38616       orig_mem = XEXP (orig_mem, 0);
38617       target_mode = GET_MODE (orig_mem);
38618     }
38619
38620   gcc_assert (MEM_P (orig_mem));
38621
38622   orig_addr = XEXP (orig_mem, 0);
38623   plus_or_lo_sum = GET_CODE (orig_addr);
38624   gcc_assert (plus_or_lo_sum == PLUS || plus_or_lo_sum == LO_SUM);
38625
38626   offset = XEXP (orig_addr, 1);
38627   new_addr = gen_rtx_fmt_ee (plus_or_lo_sum, ptr_mode, addis_value, offset);
38628   new_mem = replace_equiv_address_nv (orig_mem, new_addr, false);
38629
38630   if (extend != UNKNOWN)
38631     new_mem = gen_rtx_fmt_e (ZERO_EXTEND, extend_mode, new_mem);
38632
38633   new_mem = gen_rtx_UNSPEC (extend_mode, gen_rtvec (1, new_mem),
38634                             UNSPEC_FUSION_GPR);
38635   emit_insn (gen_rtx_SET (target, new_mem));
38636
38637   if (extend == SIGN_EXTEND)
38638     {
38639       int sub_off = ((BYTES_BIG_ENDIAN)
38640                      ? GET_MODE_SIZE (extend_mode) - GET_MODE_SIZE (target_mode)
38641                      : 0);
38642       rtx sign_reg
38643         = simplify_subreg (target_mode, target, extend_mode, sub_off);
38644
38645       emit_insn (gen_rtx_SET (target,
38646                               gen_rtx_SIGN_EXTEND (extend_mode, sign_reg)));
38647     }
38648
38649   return;
38650 }
38651
38652 /* Emit the addis instruction that will be part of a fused instruction
38653    sequence.  */
38654
38655 void
38656 emit_fusion_addis (rtx target, rtx addis_value)
38657 {
38658   rtx fuse_ops[10];
38659   const char *addis_str = NULL;
38660
38661   /* Emit the addis instruction.  */
38662   fuse_ops[0] = target;
38663   if (satisfies_constraint_L (addis_value))
38664     {
38665       fuse_ops[1] = addis_value;
38666       addis_str = "lis %0,%v1";
38667     }
38668
38669   else if (GET_CODE (addis_value) == PLUS)
38670     {
38671       rtx op0 = XEXP (addis_value, 0);
38672       rtx op1 = XEXP (addis_value, 1);
38673
38674       if (REG_P (op0) && CONST_INT_P (op1)
38675           && satisfies_constraint_L (op1))
38676         {
38677           fuse_ops[1] = op0;
38678           fuse_ops[2] = op1;
38679           addis_str = "addis %0,%1,%v2";
38680         }
38681     }
38682
38683   else if (GET_CODE (addis_value) == HIGH)
38684     {
38685       rtx value = XEXP (addis_value, 0);
38686       if (GET_CODE (value) == UNSPEC && XINT (value, 1) == UNSPEC_TOCREL)
38687         {
38688           fuse_ops[1] = XVECEXP (value, 0, 0);          /* symbol ref.  */
38689           fuse_ops[2] = XVECEXP (value, 0, 1);          /* TOC register.  */
38690           if (TARGET_ELF)
38691             addis_str = "addis %0,%2,%1@toc@ha";
38692
38693           else if (TARGET_XCOFF)
38694             addis_str = "addis %0,%1@u(%2)";
38695
38696           else
38697             gcc_unreachable ();
38698         }
38699
38700       else if (GET_CODE (value) == PLUS)
38701         {
38702           rtx op0 = XEXP (value, 0);
38703           rtx op1 = XEXP (value, 1);
38704
38705           if (GET_CODE (op0) == UNSPEC
38706               && XINT (op0, 1) == UNSPEC_TOCREL
38707               && CONST_INT_P (op1))
38708             {
38709               fuse_ops[1] = XVECEXP (op0, 0, 0);        /* symbol ref.  */
38710               fuse_ops[2] = XVECEXP (op0, 0, 1);        /* TOC register.  */
38711               fuse_ops[3] = op1;
38712               if (TARGET_ELF)
38713                 addis_str = "addis %0,%2,%1+%3@toc@ha";
38714
38715               else if (TARGET_XCOFF)
38716                 addis_str = "addis %0,%1+%3@u(%2)";
38717
38718               else
38719                 gcc_unreachable ();
38720             }
38721         }
38722
38723       else if (satisfies_constraint_L (value))
38724         {
38725           fuse_ops[1] = value;
38726           addis_str = "lis %0,%v1";
38727         }
38728
38729       else if (TARGET_ELF && !TARGET_POWERPC64 && CONSTANT_P (value))
38730         {
38731           fuse_ops[1] = value;
38732           addis_str = "lis %0,%1@ha";
38733         }
38734     }
38735
38736   if (!addis_str)
38737     fatal_insn ("Could not generate addis value for fusion", addis_value);
38738
38739   output_asm_insn (addis_str, fuse_ops);
38740 }
38741
38742 /* Emit a D-form load or store instruction that is the second instruction
38743    of a fusion sequence.  */
38744
38745 void
38746 emit_fusion_load_store (rtx load_store_reg, rtx addis_reg, rtx offset,
38747                         const char *insn_str)
38748 {
38749   rtx fuse_ops[10];
38750   char insn_template[80];
38751
38752   fuse_ops[0] = load_store_reg;
38753   fuse_ops[1] = addis_reg;
38754
38755   if (CONST_INT_P (offset) && satisfies_constraint_I (offset))
38756     {
38757       sprintf (insn_template, "%s %%0,%%2(%%1)", insn_str);
38758       fuse_ops[2] = offset;
38759       output_asm_insn (insn_template, fuse_ops);
38760     }
38761
38762   else if (GET_CODE (offset) == UNSPEC
38763            && XINT (offset, 1) == UNSPEC_TOCREL)
38764     {
38765       if (TARGET_ELF)
38766         sprintf (insn_template, "%s %%0,%%2@toc@l(%%1)", insn_str);
38767
38768       else if (TARGET_XCOFF)
38769         sprintf (insn_template, "%s %%0,%%2@l(%%1)", insn_str);
38770
38771       else
38772         gcc_unreachable ();
38773
38774       fuse_ops[2] = XVECEXP (offset, 0, 0);
38775       output_asm_insn (insn_template, fuse_ops);
38776     }
38777
38778   else if (GET_CODE (offset) == PLUS
38779            && GET_CODE (XEXP (offset, 0)) == UNSPEC
38780            && XINT (XEXP (offset, 0), 1) == UNSPEC_TOCREL
38781            && CONST_INT_P (XEXP (offset, 1)))
38782     {
38783       rtx tocrel_unspec = XEXP (offset, 0);
38784       if (TARGET_ELF)
38785         sprintf (insn_template, "%s %%0,%%2+%%3@toc@l(%%1)", insn_str);
38786
38787       else if (TARGET_XCOFF)
38788         sprintf (insn_template, "%s %%0,%%2+%%3@l(%%1)", insn_str);
38789
38790       else
38791         gcc_unreachable ();
38792
38793       fuse_ops[2] = XVECEXP (tocrel_unspec, 0, 0);
38794       fuse_ops[3] = XEXP (offset, 1);
38795       output_asm_insn (insn_template, fuse_ops);
38796     }
38797
38798   else if (TARGET_ELF && !TARGET_POWERPC64 && CONSTANT_P (offset))
38799     {
38800       sprintf (insn_template, "%s %%0,%%2@l(%%1)", insn_str);
38801
38802       fuse_ops[2] = offset;
38803       output_asm_insn (insn_template, fuse_ops);
38804     }
38805
38806   else
38807     fatal_insn ("Unable to generate load/store offset for fusion", offset);
38808
38809   return;
38810 }
38811
38812 /* Wrap a TOC address that can be fused to indicate that special fusion
38813    processing is needed.  */
38814
38815 rtx
38816 fusion_wrap_memory_address (rtx old_mem)
38817 {
38818   rtx old_addr = XEXP (old_mem, 0);
38819   rtvec v = gen_rtvec (1, old_addr);
38820   rtx new_addr = gen_rtx_UNSPEC (Pmode, v, UNSPEC_FUSION_ADDIS);
38821   return replace_equiv_address_nv (old_mem, new_addr, false);
38822 }
38823
38824 /* Given an address, convert it into the addis and load offset parts.  Addresses
38825    created during the peephole2 process look like:
38826         (lo_sum (high (unspec [(sym)] UNSPEC_TOCREL))
38827                 (unspec [(...)] UNSPEC_TOCREL))
38828
38829    Addresses created via toc fusion look like:
38830         (unspec [(unspec [(...)] UNSPEC_TOCREL)] UNSPEC_FUSION_ADDIS))  */
38831
38832 static void
38833 fusion_split_address (rtx addr, rtx *p_hi, rtx *p_lo)
38834 {
38835   rtx hi, lo;
38836
38837   if (GET_CODE (addr) == UNSPEC && XINT (addr, 1) == UNSPEC_FUSION_ADDIS)
38838     {
38839       lo = XVECEXP (addr, 0, 0);
38840       hi = gen_rtx_HIGH (Pmode, lo);
38841     }
38842   else if (GET_CODE (addr) == PLUS || GET_CODE (addr) == LO_SUM)
38843     {
38844       hi = XEXP (addr, 0);
38845       lo = XEXP (addr, 1);
38846     }
38847   else
38848     gcc_unreachable ();
38849
38850   *p_hi = hi;
38851   *p_lo = lo;
38852 }
38853
38854 /* Return a string to fuse an addis instruction with a gpr load to the same
38855    register that we loaded up the addis instruction.  The address that is used
38856    is the logical address that was formed during peephole2:
38857         (lo_sum (high) (low-part))
38858
38859    Or the address is the TOC address that is wrapped before register allocation:
38860         (unspec [(addr) (toc-reg)] UNSPEC_FUSION_ADDIS)
38861
38862    The code is complicated, so we call output_asm_insn directly, and just
38863    return "".  */
38864
38865 const char *
38866 emit_fusion_gpr_load (rtx target, rtx mem)
38867 {
38868   rtx addis_value;
38869   rtx addr;
38870   rtx load_offset;
38871   const char *load_str = NULL;
38872   machine_mode mode;
38873
38874   if (GET_CODE (mem) == ZERO_EXTEND)
38875     mem = XEXP (mem, 0);
38876
38877   gcc_assert (REG_P (target) && MEM_P (mem));
38878
38879   addr = XEXP (mem, 0);
38880   fusion_split_address (addr, &addis_value, &load_offset);
38881
38882   /* Now emit the load instruction to the same register.  */
38883   mode = GET_MODE (mem);
38884   switch (mode)
38885     {
38886     case E_QImode:
38887       load_str = "lbz";
38888       break;
38889
38890     case E_HImode:
38891       load_str = "lhz";
38892       break;
38893
38894     case E_SImode:
38895     case E_SFmode:
38896       load_str = "lwz";
38897       break;
38898
38899     case E_DImode:
38900     case E_DFmode:
38901       gcc_assert (TARGET_POWERPC64);
38902       load_str = "ld";
38903       break;
38904
38905     default:
38906       fatal_insn ("Bad GPR fusion", gen_rtx_SET (target, mem));
38907     }
38908
38909   /* Emit the addis instruction.  */
38910   emit_fusion_addis (target, addis_value);
38911
38912   /* Emit the D-form load instruction.  */
38913   emit_fusion_load_store (target, target, load_offset, load_str);
38914
38915   return "";
38916 }
38917 \f
38918
38919 /* Return true if the peephole2 can combine a load/store involving a
38920    combination of an addis instruction and the memory operation.  This was
38921    added to the ISA 3.0 (power9) hardware.  */
38922
38923 bool
38924 fusion_p9_p (rtx addis_reg,             /* register set via addis.  */
38925              rtx addis_value,           /* addis value.  */
38926              rtx dest,                  /* destination (memory or register). */
38927              rtx src)                   /* source (register or memory).  */
38928 {
38929   rtx addr, mem, offset;
38930   machine_mode mode = GET_MODE (src);
38931
38932   /* Validate arguments.  */
38933   if (!base_reg_operand (addis_reg, GET_MODE (addis_reg)))
38934     return false;
38935
38936   if (!fusion_gpr_addis (addis_value, GET_MODE (addis_value)))
38937     return false;
38938
38939   /* Ignore extend operations that are part of the load.  */
38940   if (GET_CODE (src) == FLOAT_EXTEND || GET_CODE (src) == ZERO_EXTEND)
38941     src = XEXP (src, 0);
38942
38943   /* Test for memory<-register or register<-memory.  */
38944   if (fpr_reg_operand (src, mode) || int_reg_operand (src, mode))
38945     {
38946       if (!MEM_P (dest))
38947         return false;
38948
38949       mem = dest;
38950     }
38951
38952   else if (MEM_P (src))
38953     {
38954       if (!fpr_reg_operand (dest, mode) && !int_reg_operand (dest, mode))
38955         return false;
38956
38957       mem = src;
38958     }
38959
38960   else
38961     return false;
38962
38963   addr = XEXP (mem, 0);                 /* either PLUS or LO_SUM.  */
38964   if (GET_CODE (addr) == PLUS)
38965     {
38966       if (!rtx_equal_p (addis_reg, XEXP (addr, 0)))
38967         return false;
38968
38969       return satisfies_constraint_I (XEXP (addr, 1));
38970     }
38971
38972   else if (GET_CODE (addr) == LO_SUM)
38973     {
38974       if (!rtx_equal_p (addis_reg, XEXP (addr, 0)))
38975         return false;
38976
38977       offset = XEXP (addr, 1);
38978       if (TARGET_XCOFF || (TARGET_ELF && TARGET_POWERPC64))
38979         return small_toc_ref (offset, GET_MODE (offset));
38980
38981       else if (TARGET_ELF && !TARGET_POWERPC64)
38982         return CONSTANT_P (offset);
38983     }
38984
38985   return false;
38986 }
38987
38988 /* During the peephole2 pass, adjust and expand the insns for an extended fusion
38989    load sequence.
38990
38991    The operands are:
38992         operands[0]     register set with addis
38993         operands[1]     value set via addis
38994         operands[2]     target register being loaded
38995         operands[3]     D-form memory reference using operands[0].
38996
38997   This is similar to the fusion introduced with power8, except it scales to
38998   both loads/stores and does not require the result register to be the same as
38999   the base register.  At the moment, we only do this if register set with addis
39000   is dead.  */
39001
39002 void
39003 expand_fusion_p9_load (rtx *operands)
39004 {
39005   rtx tmp_reg = operands[0];
39006   rtx addis_value = operands[1];
39007   rtx target = operands[2];
39008   rtx orig_mem = operands[3];
39009   rtx  new_addr, new_mem, orig_addr, offset, set, clobber, insn;
39010   enum rtx_code plus_or_lo_sum;
39011   machine_mode target_mode = GET_MODE (target);
39012   machine_mode extend_mode = target_mode;
39013   machine_mode ptr_mode = Pmode;
39014   enum rtx_code extend = UNKNOWN;
39015
39016   if (GET_CODE (orig_mem) == FLOAT_EXTEND || GET_CODE (orig_mem) == ZERO_EXTEND)
39017     {
39018       extend = GET_CODE (orig_mem);
39019       orig_mem = XEXP (orig_mem, 0);
39020       target_mode = GET_MODE (orig_mem);
39021     }
39022
39023   gcc_assert (MEM_P (orig_mem));
39024
39025   orig_addr = XEXP (orig_mem, 0);
39026   plus_or_lo_sum = GET_CODE (orig_addr);
39027   gcc_assert (plus_or_lo_sum == PLUS || plus_or_lo_sum == LO_SUM);
39028
39029   offset = XEXP (orig_addr, 1);
39030   new_addr = gen_rtx_fmt_ee (plus_or_lo_sum, ptr_mode, addis_value, offset);
39031   new_mem = replace_equiv_address_nv (orig_mem, new_addr, false);
39032
39033   if (extend != UNKNOWN)
39034     new_mem = gen_rtx_fmt_e (extend, extend_mode, new_mem);
39035
39036   new_mem = gen_rtx_UNSPEC (extend_mode, gen_rtvec (1, new_mem),
39037                             UNSPEC_FUSION_P9);
39038
39039   set = gen_rtx_SET (target, new_mem);
39040   clobber = gen_rtx_CLOBBER (VOIDmode, tmp_reg);
39041   insn = gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, set, clobber));
39042   emit_insn (insn);
39043
39044   return;
39045 }
39046
39047 /* During the peephole2 pass, adjust and expand the insns for an extended fusion
39048    store sequence.
39049
39050    The operands are:
39051         operands[0]     register set with addis
39052         operands[1]     value set via addis
39053         operands[2]     target D-form memory being stored to
39054         operands[3]     register being stored
39055
39056   This is similar to the fusion introduced with power8, except it scales to
39057   both loads/stores and does not require the result register to be the same as
39058   the base register.  At the moment, we only do this if register set with addis
39059   is dead.  */
39060
39061 void
39062 expand_fusion_p9_store (rtx *operands)
39063 {
39064   rtx tmp_reg = operands[0];
39065   rtx addis_value = operands[1];
39066   rtx orig_mem = operands[2];
39067   rtx src = operands[3];
39068   rtx  new_addr, new_mem, orig_addr, offset, set, clobber, insn, new_src;
39069   enum rtx_code plus_or_lo_sum;
39070   machine_mode target_mode = GET_MODE (orig_mem);
39071   machine_mode ptr_mode = Pmode;
39072
39073   gcc_assert (MEM_P (orig_mem));
39074
39075   orig_addr = XEXP (orig_mem, 0);
39076   plus_or_lo_sum = GET_CODE (orig_addr);
39077   gcc_assert (plus_or_lo_sum == PLUS || plus_or_lo_sum == LO_SUM);
39078
39079   offset = XEXP (orig_addr, 1);
39080   new_addr = gen_rtx_fmt_ee (plus_or_lo_sum, ptr_mode, addis_value, offset);
39081   new_mem = replace_equiv_address_nv (orig_mem, new_addr, false);
39082
39083   new_src = gen_rtx_UNSPEC (target_mode, gen_rtvec (1, src),
39084                             UNSPEC_FUSION_P9);
39085
39086   set = gen_rtx_SET (new_mem, new_src);
39087   clobber = gen_rtx_CLOBBER (VOIDmode, tmp_reg);
39088   insn = gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, set, clobber));
39089   emit_insn (insn);
39090
39091   return;
39092 }
39093
39094 /* Return a string to fuse an addis instruction with a load using extended
39095    fusion.  The address that is used is the logical address that was formed
39096    during peephole2: (lo_sum (high) (low-part))
39097
39098    The code is complicated, so we call output_asm_insn directly, and just
39099    return "".  */
39100
39101 const char *
39102 emit_fusion_p9_load (rtx reg, rtx mem, rtx tmp_reg)
39103 {
39104   machine_mode mode = GET_MODE (reg);
39105   rtx hi;
39106   rtx lo;
39107   rtx addr;
39108   const char *load_string;
39109   int r;
39110
39111   if (GET_CODE (mem) == FLOAT_EXTEND || GET_CODE (mem) == ZERO_EXTEND)
39112     {
39113       mem = XEXP (mem, 0);
39114       mode = GET_MODE (mem);
39115     }
39116
39117   if (GET_CODE (reg) == SUBREG)
39118     {
39119       gcc_assert (SUBREG_BYTE (reg) == 0);
39120       reg = SUBREG_REG (reg);
39121     }
39122
39123   if (!REG_P (reg))
39124     fatal_insn ("emit_fusion_p9_load, bad reg #1", reg);
39125
39126   r = REGNO (reg);
39127   if (FP_REGNO_P (r))
39128     {
39129       if (mode == SFmode)
39130         load_string = "lfs";
39131       else if (mode == DFmode || mode == DImode)
39132         load_string = "lfd";
39133       else
39134         gcc_unreachable ();
39135     }
39136   else if (ALTIVEC_REGNO_P (r) && TARGET_P9_VECTOR)
39137     {
39138       if (mode == SFmode)
39139         load_string = "lxssp";
39140       else if (mode == DFmode || mode == DImode)
39141         load_string = "lxsd";
39142       else
39143         gcc_unreachable ();
39144     }
39145   else if (INT_REGNO_P (r))
39146     {
39147       switch (mode)
39148         {
39149         case E_QImode:
39150           load_string = "lbz";
39151           break;
39152         case E_HImode:
39153           load_string = "lhz";
39154           break;
39155         case E_SImode:
39156         case E_SFmode:
39157           load_string = "lwz";
39158           break;
39159         case E_DImode:
39160         case E_DFmode:
39161           if (!TARGET_POWERPC64)
39162             gcc_unreachable ();
39163           load_string = "ld";
39164           break;
39165         default:
39166           gcc_unreachable ();
39167         }
39168     }
39169   else
39170     fatal_insn ("emit_fusion_p9_load, bad reg #2", reg);
39171
39172   if (!MEM_P (mem))
39173     fatal_insn ("emit_fusion_p9_load not MEM", mem);
39174
39175   addr = XEXP (mem, 0);
39176   fusion_split_address (addr, &hi, &lo);
39177
39178   /* Emit the addis instruction.  */
39179   emit_fusion_addis (tmp_reg, hi);
39180
39181   /* Emit the D-form load instruction.  */
39182   emit_fusion_load_store (reg, tmp_reg, lo, load_string);
39183
39184   return "";
39185 }
39186
39187 /* Return a string to fuse an addis instruction with a store using extended
39188    fusion.  The address that is used is the logical address that was formed
39189    during peephole2: (lo_sum (high) (low-part))
39190
39191    The code is complicated, so we call output_asm_insn directly, and just
39192    return "".  */
39193
39194 const char *
39195 emit_fusion_p9_store (rtx mem, rtx reg, rtx tmp_reg)
39196 {
39197   machine_mode mode = GET_MODE (reg);
39198   rtx hi;
39199   rtx lo;
39200   rtx addr;
39201   const char *store_string;
39202   int r;
39203
39204   if (GET_CODE (reg) == SUBREG)
39205     {
39206       gcc_assert (SUBREG_BYTE (reg) == 0);
39207       reg = SUBREG_REG (reg);
39208     }
39209
39210   if (!REG_P (reg))
39211     fatal_insn ("emit_fusion_p9_store, bad reg #1", reg);
39212
39213   r = REGNO (reg);
39214   if (FP_REGNO_P (r))
39215     {
39216       if (mode == SFmode)
39217         store_string = "stfs";
39218       else if (mode == DFmode)
39219         store_string = "stfd";
39220       else
39221         gcc_unreachable ();
39222     }
39223   else if (ALTIVEC_REGNO_P (r) && TARGET_P9_VECTOR)
39224     {
39225       if (mode == SFmode)
39226         store_string = "stxssp";
39227       else if (mode == DFmode || mode == DImode)
39228         store_string = "stxsd";
39229       else
39230         gcc_unreachable ();
39231     }
39232   else if (INT_REGNO_P (r))
39233     {
39234       switch (mode)
39235         {
39236         case E_QImode:
39237           store_string = "stb";
39238           break;
39239         case E_HImode:
39240           store_string = "sth";
39241           break;
39242         case E_SImode:
39243         case E_SFmode:
39244           store_string = "stw";
39245           break;
39246         case E_DImode:
39247         case E_DFmode:
39248           if (!TARGET_POWERPC64)
39249             gcc_unreachable ();
39250           store_string = "std";
39251           break;
39252         default:
39253           gcc_unreachable ();
39254         }
39255     }
39256   else
39257     fatal_insn ("emit_fusion_p9_store, bad reg #2", reg);
39258
39259   if (!MEM_P (mem))
39260     fatal_insn ("emit_fusion_p9_store not MEM", mem);
39261
39262   addr = XEXP (mem, 0);
39263   fusion_split_address (addr, &hi, &lo);
39264
39265   /* Emit the addis instruction.  */
39266   emit_fusion_addis (tmp_reg, hi);
39267
39268   /* Emit the D-form load instruction.  */
39269   emit_fusion_load_store (reg, tmp_reg, lo, store_string);
39270
39271   return "";
39272 }
39273
39274 #ifdef RS6000_GLIBC_ATOMIC_FENV
39275 /* Function declarations for rs6000_atomic_assign_expand_fenv.  */
39276 static tree atomic_hold_decl, atomic_clear_decl, atomic_update_decl;
39277 #endif
39278
39279 /* Implement TARGET_ATOMIC_ASSIGN_EXPAND_FENV hook.  */
39280
39281 static void
39282 rs6000_atomic_assign_expand_fenv (tree *hold, tree *clear, tree *update)
39283 {
39284   if (!TARGET_HARD_FLOAT)
39285     {
39286 #ifdef RS6000_GLIBC_ATOMIC_FENV
39287       if (atomic_hold_decl == NULL_TREE)
39288         {
39289           atomic_hold_decl
39290             = build_decl (BUILTINS_LOCATION, FUNCTION_DECL,
39291                           get_identifier ("__atomic_feholdexcept"),
39292                           build_function_type_list (void_type_node,
39293                                                     double_ptr_type_node,
39294                                                     NULL_TREE));
39295           TREE_PUBLIC (atomic_hold_decl) = 1;
39296           DECL_EXTERNAL (atomic_hold_decl) = 1;
39297         }
39298
39299       if (atomic_clear_decl == NULL_TREE)
39300         {
39301           atomic_clear_decl
39302             = build_decl (BUILTINS_LOCATION, FUNCTION_DECL,
39303                           get_identifier ("__atomic_feclearexcept"),
39304                           build_function_type_list (void_type_node,
39305                                                     NULL_TREE));
39306           TREE_PUBLIC (atomic_clear_decl) = 1;
39307           DECL_EXTERNAL (atomic_clear_decl) = 1;
39308         }
39309
39310       tree const_double = build_qualified_type (double_type_node,
39311                                                 TYPE_QUAL_CONST);
39312       tree const_double_ptr = build_pointer_type (const_double);
39313       if (atomic_update_decl == NULL_TREE)
39314         {
39315           atomic_update_decl
39316             = build_decl (BUILTINS_LOCATION, FUNCTION_DECL,
39317                           get_identifier ("__atomic_feupdateenv"),
39318                           build_function_type_list (void_type_node,
39319                                                     const_double_ptr,
39320                                                     NULL_TREE));
39321           TREE_PUBLIC (atomic_update_decl) = 1;
39322           DECL_EXTERNAL (atomic_update_decl) = 1;
39323         }
39324
39325       tree fenv_var = create_tmp_var_raw (double_type_node);
39326       TREE_ADDRESSABLE (fenv_var) = 1;
39327       tree fenv_addr = build1 (ADDR_EXPR, double_ptr_type_node, fenv_var);
39328
39329       *hold = build_call_expr (atomic_hold_decl, 1, fenv_addr);
39330       *clear = build_call_expr (atomic_clear_decl, 0);
39331       *update = build_call_expr (atomic_update_decl, 1,
39332                                  fold_convert (const_double_ptr, fenv_addr));
39333 #endif
39334       return;
39335     }
39336
39337   tree mffs = rs6000_builtin_decls[RS6000_BUILTIN_MFFS];
39338   tree mtfsf = rs6000_builtin_decls[RS6000_BUILTIN_MTFSF];
39339   tree call_mffs = build_call_expr (mffs, 0);
39340
39341   /* Generates the equivalent of feholdexcept (&fenv_var)
39342
39343      *fenv_var = __builtin_mffs ();
39344      double fenv_hold;
39345      *(uint64_t*)&fenv_hold = *(uint64_t*)fenv_var & 0xffffffff00000007LL;
39346      __builtin_mtfsf (0xff, fenv_hold);  */
39347
39348   /* Mask to clear everything except for the rounding modes and non-IEEE
39349      arithmetic flag.  */
39350   const unsigned HOST_WIDE_INT hold_exception_mask =
39351     HOST_WIDE_INT_C (0xffffffff00000007);
39352
39353   tree fenv_var = create_tmp_var_raw (double_type_node);
39354
39355   tree hold_mffs = build2 (MODIFY_EXPR, void_type_node, fenv_var, call_mffs);
39356
39357   tree fenv_llu = build1 (VIEW_CONVERT_EXPR, uint64_type_node, fenv_var);
39358   tree fenv_llu_and = build2 (BIT_AND_EXPR, uint64_type_node, fenv_llu,
39359                               build_int_cst (uint64_type_node,
39360                                              hold_exception_mask));
39361
39362   tree fenv_hold_mtfsf = build1 (VIEW_CONVERT_EXPR, double_type_node,
39363                                  fenv_llu_and);
39364
39365   tree hold_mtfsf = build_call_expr (mtfsf, 2,
39366                                      build_int_cst (unsigned_type_node, 0xff),
39367                                      fenv_hold_mtfsf);
39368
39369   *hold = build2 (COMPOUND_EXPR, void_type_node, hold_mffs, hold_mtfsf);
39370
39371   /* Generates the equivalent of feclearexcept (FE_ALL_EXCEPT):
39372
39373      double fenv_clear = __builtin_mffs ();
39374      *(uint64_t)&fenv_clear &= 0xffffffff00000000LL;
39375      __builtin_mtfsf (0xff, fenv_clear);  */
39376
39377   /* Mask to clear everything except for the rounding modes and non-IEEE
39378      arithmetic flag.  */
39379   const unsigned HOST_WIDE_INT clear_exception_mask =
39380     HOST_WIDE_INT_C (0xffffffff00000000);
39381
39382   tree fenv_clear = create_tmp_var_raw (double_type_node);
39383
39384   tree clear_mffs = build2 (MODIFY_EXPR, void_type_node, fenv_clear, call_mffs);
39385
39386   tree fenv_clean_llu = build1 (VIEW_CONVERT_EXPR, uint64_type_node, fenv_clear);
39387   tree fenv_clear_llu_and = build2 (BIT_AND_EXPR, uint64_type_node,
39388                                     fenv_clean_llu,
39389                                     build_int_cst (uint64_type_node,
39390                                                    clear_exception_mask));
39391
39392   tree fenv_clear_mtfsf = build1 (VIEW_CONVERT_EXPR, double_type_node,
39393                                   fenv_clear_llu_and);
39394
39395   tree clear_mtfsf = build_call_expr (mtfsf, 2,
39396                                       build_int_cst (unsigned_type_node, 0xff),
39397                                       fenv_clear_mtfsf);
39398
39399   *clear = build2 (COMPOUND_EXPR, void_type_node, clear_mffs, clear_mtfsf);
39400
39401   /* Generates the equivalent of feupdateenv (&fenv_var)
39402
39403      double old_fenv = __builtin_mffs ();
39404      double fenv_update;
39405      *(uint64_t*)&fenv_update = (*(uint64_t*)&old & 0xffffffff1fffff00LL) |
39406                                 (*(uint64_t*)fenv_var 0x1ff80fff);
39407      __builtin_mtfsf (0xff, fenv_update);  */
39408
39409   const unsigned HOST_WIDE_INT update_exception_mask =
39410     HOST_WIDE_INT_C (0xffffffff1fffff00);
39411   const unsigned HOST_WIDE_INT new_exception_mask =
39412     HOST_WIDE_INT_C (0x1ff80fff);
39413
39414   tree old_fenv = create_tmp_var_raw (double_type_node);
39415   tree update_mffs = build2 (MODIFY_EXPR, void_type_node, old_fenv, call_mffs);
39416
39417   tree old_llu = build1 (VIEW_CONVERT_EXPR, uint64_type_node, old_fenv);
39418   tree old_llu_and = build2 (BIT_AND_EXPR, uint64_type_node, old_llu,
39419                              build_int_cst (uint64_type_node,
39420                                             update_exception_mask));
39421
39422   tree new_llu_and = build2 (BIT_AND_EXPR, uint64_type_node, fenv_llu,
39423                              build_int_cst (uint64_type_node,
39424                                             new_exception_mask));
39425
39426   tree new_llu_mask = build2 (BIT_IOR_EXPR, uint64_type_node,
39427                               old_llu_and, new_llu_and);
39428
39429   tree fenv_update_mtfsf = build1 (VIEW_CONVERT_EXPR, double_type_node,
39430                                    new_llu_mask);
39431
39432   tree update_mtfsf = build_call_expr (mtfsf, 2,
39433                                        build_int_cst (unsigned_type_node, 0xff),
39434                                        fenv_update_mtfsf);
39435
39436   *update = build2 (COMPOUND_EXPR, void_type_node, update_mffs, update_mtfsf);
39437 }
39438
39439 void
39440 rs6000_generate_float2_double_code (rtx dst, rtx src1, rtx src2)
39441 {
39442   rtx rtx_tmp0, rtx_tmp1, rtx_tmp2, rtx_tmp3;
39443
39444   rtx_tmp0 = gen_reg_rtx (V2DFmode);
39445   rtx_tmp1 = gen_reg_rtx (V2DFmode);
39446
39447   /* The destination of the vmrgew instruction layout is:
39448      rtx_tmp2[0] rtx_tmp3[0] rtx_tmp2[1] rtx_tmp3[0].
39449      Setup rtx_tmp0 and rtx_tmp1 to ensure the order of the elements after the
39450      vmrgew instruction will be correct.  */
39451   if (VECTOR_ELT_ORDER_BIG)
39452     {
39453        emit_insn (gen_vsx_xxpermdi_v2df_be (rtx_tmp0, src1, src2,
39454                                             GEN_INT (0)));
39455        emit_insn (gen_vsx_xxpermdi_v2df_be (rtx_tmp1, src1, src2,
39456                                             GEN_INT (3)));
39457     }
39458   else
39459     {
39460        emit_insn (gen_vsx_xxpermdi_v2df (rtx_tmp0, src1, src2, GEN_INT (3)));
39461        emit_insn (gen_vsx_xxpermdi_v2df (rtx_tmp1, src1, src2, GEN_INT (0)));
39462     }
39463
39464   rtx_tmp2 = gen_reg_rtx (V4SFmode);
39465   rtx_tmp3 = gen_reg_rtx (V4SFmode);
39466
39467   emit_insn (gen_vsx_xvcdpsp (rtx_tmp2, rtx_tmp0));
39468   emit_insn (gen_vsx_xvcdpsp (rtx_tmp3, rtx_tmp1));
39469
39470   if (VECTOR_ELT_ORDER_BIG)
39471     emit_insn (gen_p8_vmrgew_v4sf (dst, rtx_tmp2, rtx_tmp3));
39472   else
39473     emit_insn (gen_p8_vmrgew_v4sf (dst, rtx_tmp3, rtx_tmp2));
39474 }
39475
39476 void
39477 rs6000_generate_float2_code (bool signed_convert, rtx dst, rtx src1, rtx src2)
39478 {
39479   rtx rtx_tmp0, rtx_tmp1, rtx_tmp2, rtx_tmp3;
39480
39481   rtx_tmp0 = gen_reg_rtx (V2DImode);
39482   rtx_tmp1 = gen_reg_rtx (V2DImode);
39483
39484   /* The destination of the vmrgew instruction layout is:
39485      rtx_tmp2[0] rtx_tmp3[0] rtx_tmp2[1] rtx_tmp3[0].
39486      Setup rtx_tmp0 and rtx_tmp1 to ensure the order of the elements after the
39487      vmrgew instruction will be correct.  */
39488   if (VECTOR_ELT_ORDER_BIG)
39489     {
39490       emit_insn (gen_vsx_xxpermdi_v2di_be (rtx_tmp0, src1, src2, GEN_INT (0)));
39491       emit_insn (gen_vsx_xxpermdi_v2di_be (rtx_tmp1, src1, src2, GEN_INT (3)));
39492     }
39493   else
39494     {
39495       emit_insn (gen_vsx_xxpermdi_v2di (rtx_tmp0, src1, src2, GEN_INT (3)));
39496       emit_insn (gen_vsx_xxpermdi_v2di (rtx_tmp1, src1, src2, GEN_INT (0)));
39497     }
39498
39499   rtx_tmp2 = gen_reg_rtx (V4SFmode);
39500   rtx_tmp3 = gen_reg_rtx (V4SFmode);
39501
39502   if (signed_convert)
39503     {
39504       emit_insn (gen_vsx_xvcvsxdsp (rtx_tmp2, rtx_tmp0));
39505       emit_insn (gen_vsx_xvcvsxdsp (rtx_tmp3, rtx_tmp1));
39506     }
39507   else
39508     {
39509        emit_insn (gen_vsx_xvcvuxdsp (rtx_tmp2, rtx_tmp0));
39510        emit_insn (gen_vsx_xvcvuxdsp (rtx_tmp3, rtx_tmp1));
39511     }
39512
39513   if (VECTOR_ELT_ORDER_BIG)
39514     emit_insn (gen_p8_vmrgew_v4sf (dst, rtx_tmp2, rtx_tmp3));
39515   else
39516     emit_insn (gen_p8_vmrgew_v4sf (dst, rtx_tmp3, rtx_tmp2));
39517 }
39518
39519 void
39520 rs6000_generate_vsigned2_code (bool signed_convert, rtx dst, rtx src1,
39521                                rtx src2)
39522 {
39523   rtx rtx_tmp0, rtx_tmp1, rtx_tmp2, rtx_tmp3;
39524
39525   rtx_tmp0 = gen_reg_rtx (V2DFmode);
39526   rtx_tmp1 = gen_reg_rtx (V2DFmode);
39527
39528   emit_insn (gen_vsx_xxpermdi_v2df (rtx_tmp0, src1, src2, GEN_INT (0)));
39529   emit_insn (gen_vsx_xxpermdi_v2df (rtx_tmp1, src1, src2, GEN_INT (3)));
39530
39531   rtx_tmp2 = gen_reg_rtx (V4SImode);
39532   rtx_tmp3 = gen_reg_rtx (V4SImode);
39533
39534   if (signed_convert)
39535     {
39536       emit_insn (gen_vsx_xvcvdpsxws (rtx_tmp2, rtx_tmp0));
39537       emit_insn (gen_vsx_xvcvdpsxws (rtx_tmp3, rtx_tmp1));
39538     }
39539   else
39540     {
39541       emit_insn (gen_vsx_xvcvdpuxws (rtx_tmp2, rtx_tmp0));
39542       emit_insn (gen_vsx_xvcvdpuxws (rtx_tmp3, rtx_tmp1));
39543     }
39544
39545   emit_insn (gen_p8_vmrgew_v4si (dst, rtx_tmp2, rtx_tmp3));
39546 }
39547
39548 /* Implement the TARGET_OPTAB_SUPPORTED_P hook.  */
39549
39550 static bool
39551 rs6000_optab_supported_p (int op, machine_mode mode1, machine_mode,
39552                           optimization_type opt_type)
39553 {
39554   switch (op)
39555     {
39556     case rsqrt_optab:
39557       return (opt_type == OPTIMIZE_FOR_SPEED
39558               && RS6000_RECIP_AUTO_RSQRTE_P (mode1));
39559
39560     default:
39561       return true;
39562     }
39563 }
39564
39565 /* Implement TARGET_CONSTANT_ALIGNMENT.  */
39566
39567 static HOST_WIDE_INT
39568 rs6000_constant_alignment (const_tree exp, HOST_WIDE_INT align)
39569 {
39570   if (TREE_CODE (exp) == STRING_CST
39571       && (STRICT_ALIGNMENT || !optimize_size))
39572     return MAX (align, BITS_PER_WORD);
39573   return align;
39574 }
39575
39576 /* Implement TARGET_STARTING_FRAME_OFFSET.  */
39577
39578 static HOST_WIDE_INT
39579 rs6000_starting_frame_offset (void)
39580 {
39581   if (FRAME_GROWS_DOWNWARD)
39582     return 0;
39583   return RS6000_STARTING_FRAME_OFFSET;
39584 }
39585 \f
39586 struct gcc_target targetm = TARGET_INITIALIZER;
39587
39588 #include "gt-rs6000.h"