rs6000: Shut up -Wformat-diag somewhat
[platform/upstream/gcc.git] / gcc / config / rs6000 / rs6000.c
1 /* Subroutines used for code generation on IBM RS/6000.
2    Copyright (C) 1991-2019 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 "common/common-target.h"
56 #include "langhooks.h"
57 #include "reload.h"
58 #include "sched-int.h"
59 #include "gimplify.h"
60 #include "gimple-fold.h"
61 #include "gimple-iterator.h"
62 #include "gimple-ssa.h"
63 #include "gimple-walk.h"
64 #include "intl.h"
65 #include "params.h"
66 #include "tm-constrs.h"
67 #include "tree-vectorizer.h"
68 #include "target-globals.h"
69 #include "builtins.h"
70 #include "tree-vector-builder.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 #include "case-cfn-macros.h"
78 #include "ppc-auxv.h"
79 #include "tree-ssa-propagate.h"
80 #include "tree-vrp.h"
81 #include "tree-ssanames.h"
82 #include "rs6000-internal.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 static pad_direction rs6000_function_arg_padding (machine_mode, const_tree);
106
107 /* Support targetm.vectorize.builtin_mask_for_load.  */
108 static GTY(()) tree altivec_builtin_mask_for_load;
109
110 /* Set to nonzero once AIX common-mode calls have been defined.  */
111 static GTY(()) int common_mode_defined;
112
113 #ifdef USING_ELFOS_H
114 /* Counter for labels which are to be placed in .fixup.  */
115 int fixuplabelno = 0;
116 #endif
117
118 /* Whether to use variant of AIX ABI for PowerPC64 Linux.  */
119 int dot_symbols;
120
121 /* Specify the machine mode that pointers have.  After generation of rtl, the
122    compiler makes no further distinction between pointers and any other objects
123    of this machine mode.  */
124 scalar_int_mode rs6000_pmode;
125
126 #if TARGET_ELF
127 /* Note whether IEEE 128-bit floating point was passed or returned, either as
128    the __float128/_Float128 explicit type, or when long double is IEEE 128-bit
129    floating point.  We changed the default C++ mangling for these types and we
130    may want to generate a weak alias of the old mangling (U10__float128) to the
131    new mangling (u9__ieee128).  */
132 static bool rs6000_passes_ieee128;
133 #endif
134
135 /* Generate the manged name (i.e. U10__float128) used in GCC 8.1, and not the
136    name used in current releases (i.e. u9__ieee128).  */
137 static bool ieee128_mangling_gcc_8_1;
138
139 /* Width in bits of a pointer.  */
140 unsigned rs6000_pointer_size;
141
142 #ifdef HAVE_AS_GNU_ATTRIBUTE
143 # ifndef HAVE_LD_PPC_GNU_ATTR_LONG_DOUBLE
144 # define HAVE_LD_PPC_GNU_ATTR_LONG_DOUBLE 0
145 # endif
146 /* Flag whether floating point values have been passed/returned.
147    Note that this doesn't say whether fprs are used, since the
148    Tag_GNU_Power_ABI_FP .gnu.attributes value this flag controls
149    should be set for soft-float values passed in gprs and ieee128
150    values passed in vsx registers.  */
151 static bool rs6000_passes_float;
152 static bool rs6000_passes_long_double;
153 /* Flag whether vector values have been passed/returned.  */
154 static bool rs6000_passes_vector;
155 /* Flag whether small (<= 8 byte) structures have been returned.  */
156 static bool rs6000_returns_struct;
157 #endif
158
159 /* Value is TRUE if register/mode pair is acceptable.  */
160 static bool rs6000_hard_regno_mode_ok_p
161   [NUM_MACHINE_MODES][FIRST_PSEUDO_REGISTER];
162
163 /* Maximum number of registers needed for a given register class and mode.  */
164 unsigned char rs6000_class_max_nregs[NUM_MACHINE_MODES][LIM_REG_CLASSES];
165
166 /* How many registers are needed for a given register and mode.  */
167 unsigned char rs6000_hard_regno_nregs[NUM_MACHINE_MODES][FIRST_PSEUDO_REGISTER];
168
169 /* Map register number to register class.  */
170 enum reg_class rs6000_regno_regclass[FIRST_PSEUDO_REGISTER];
171
172 static int dbg_cost_ctrl;
173
174 /* Built in types.  */
175 tree rs6000_builtin_types[RS6000_BTI_MAX];
176 tree rs6000_builtin_decls[RS6000_BUILTIN_COUNT];
177
178 /* Flag to say the TOC is initialized */
179 int toc_initialized, need_toc_init;
180 char toc_label_name[10];
181
182 /* Cached value of rs6000_variable_issue. This is cached in
183    rs6000_variable_issue hook and returned from rs6000_sched_reorder2.  */
184 static short cached_can_issue_more;
185
186 static GTY(()) section *read_only_data_section;
187 static GTY(()) section *private_data_section;
188 static GTY(()) section *tls_data_section;
189 static GTY(()) section *tls_private_data_section;
190 static GTY(()) section *read_only_private_data_section;
191 static GTY(()) section *sdata2_section;
192
193 extern GTY(()) section *toc_section;
194 section *toc_section = 0;
195
196 struct builtin_description
197 {
198   const HOST_WIDE_INT mask;
199   const enum insn_code icode;
200   const char *const name;
201   const enum rs6000_builtins code;
202 };
203
204 /* Describe the vector unit used for modes.  */
205 enum rs6000_vector rs6000_vector_unit[NUM_MACHINE_MODES];
206 enum rs6000_vector rs6000_vector_mem[NUM_MACHINE_MODES];
207
208 /* Register classes for various constraints that are based on the target
209    switches.  */
210 enum reg_class rs6000_constraints[RS6000_CONSTRAINT_MAX];
211
212 /* Describe the alignment of a vector.  */
213 int rs6000_vector_align[NUM_MACHINE_MODES];
214
215 /* Map selected modes to types for builtins.  */
216 static GTY(()) tree builtin_mode_to_type[MAX_MACHINE_MODE][2];
217
218 /* What modes to automatically generate reciprocal divide estimate (fre) and
219    reciprocal sqrt (frsqrte) for.  */
220 unsigned char rs6000_recip_bits[MAX_MACHINE_MODE];
221
222 /* Masks to determine which reciprocal esitmate instructions to generate
223    automatically.  */
224 enum rs6000_recip_mask {
225   RECIP_SF_DIV          = 0x001,        /* Use divide estimate */
226   RECIP_DF_DIV          = 0x002,
227   RECIP_V4SF_DIV        = 0x004,
228   RECIP_V2DF_DIV        = 0x008,
229
230   RECIP_SF_RSQRT        = 0x010,        /* Use reciprocal sqrt estimate.  */
231   RECIP_DF_RSQRT        = 0x020,
232   RECIP_V4SF_RSQRT      = 0x040,
233   RECIP_V2DF_RSQRT      = 0x080,
234
235   /* Various combination of flags for -mrecip=xxx.  */
236   RECIP_NONE            = 0,
237   RECIP_ALL             = (RECIP_SF_DIV | RECIP_DF_DIV | RECIP_V4SF_DIV
238                            | RECIP_V2DF_DIV | RECIP_SF_RSQRT | RECIP_DF_RSQRT
239                            | RECIP_V4SF_RSQRT | RECIP_V2DF_RSQRT),
240
241   RECIP_HIGH_PRECISION  = RECIP_ALL,
242
243   /* On low precision machines like the power5, don't enable double precision
244      reciprocal square root estimate, since it isn't accurate enough.  */
245   RECIP_LOW_PRECISION   = (RECIP_ALL & ~(RECIP_DF_RSQRT | RECIP_V2DF_RSQRT))
246 };
247
248 /* -mrecip options.  */
249 static struct
250 {
251   const char *string;           /* option name */
252   unsigned int mask;            /* mask bits to set */
253 } recip_options[] = {
254   { "all",       RECIP_ALL },
255   { "none",      RECIP_NONE },
256   { "div",       (RECIP_SF_DIV | RECIP_DF_DIV | RECIP_V4SF_DIV
257                   | RECIP_V2DF_DIV) },
258   { "divf",      (RECIP_SF_DIV | RECIP_V4SF_DIV) },
259   { "divd",      (RECIP_DF_DIV | RECIP_V2DF_DIV) },
260   { "rsqrt",     (RECIP_SF_RSQRT | RECIP_DF_RSQRT | RECIP_V4SF_RSQRT
261                   | RECIP_V2DF_RSQRT) },
262   { "rsqrtf",    (RECIP_SF_RSQRT | RECIP_V4SF_RSQRT) },
263   { "rsqrtd",    (RECIP_DF_RSQRT | RECIP_V2DF_RSQRT) },
264 };
265
266 /* Used by __builtin_cpu_is(), mapping from PLATFORM names to values.  */
267 static const struct
268 {
269   const char *cpu;
270   unsigned int cpuid;
271 } cpu_is_info[] = {
272   { "power9",      PPC_PLATFORM_POWER9 },
273   { "power8",      PPC_PLATFORM_POWER8 },
274   { "power7",      PPC_PLATFORM_POWER7 },
275   { "power6x",     PPC_PLATFORM_POWER6X },
276   { "power6",      PPC_PLATFORM_POWER6 },
277   { "power5+",     PPC_PLATFORM_POWER5_PLUS },
278   { "power5",      PPC_PLATFORM_POWER5 },
279   { "ppc970",      PPC_PLATFORM_PPC970 },
280   { "power4",      PPC_PLATFORM_POWER4 },
281   { "ppca2",       PPC_PLATFORM_PPCA2 },
282   { "ppc476",      PPC_PLATFORM_PPC476 },
283   { "ppc464",      PPC_PLATFORM_PPC464 },
284   { "ppc440",      PPC_PLATFORM_PPC440 },
285   { "ppc405",      PPC_PLATFORM_PPC405 },
286   { "ppc-cell-be", PPC_PLATFORM_CELL_BE }
287 };
288
289 /* Used by __builtin_cpu_supports(), mapping from HWCAP names to masks.  */
290 static const struct
291 {
292   const char *hwcap;
293   int mask;
294   unsigned int id;
295 } cpu_supports_info[] = {
296   /* AT_HWCAP masks.  */
297   { "4xxmac",           PPC_FEATURE_HAS_4xxMAC,         0 },
298   { "altivec",          PPC_FEATURE_HAS_ALTIVEC,        0 },
299   { "arch_2_05",        PPC_FEATURE_ARCH_2_05,          0 },
300   { "arch_2_06",        PPC_FEATURE_ARCH_2_06,          0 },
301   { "archpmu",          PPC_FEATURE_PERFMON_COMPAT,     0 },
302   { "booke",            PPC_FEATURE_BOOKE,              0 },
303   { "cellbe",           PPC_FEATURE_CELL_BE,            0 },
304   { "dfp",              PPC_FEATURE_HAS_DFP,            0 },
305   { "efpdouble",        PPC_FEATURE_HAS_EFP_DOUBLE,     0 },
306   { "efpsingle",        PPC_FEATURE_HAS_EFP_SINGLE,     0 },
307   { "fpu",              PPC_FEATURE_HAS_FPU,            0 },
308   { "ic_snoop",         PPC_FEATURE_ICACHE_SNOOP,       0 },
309   { "mmu",              PPC_FEATURE_HAS_MMU,            0 },
310   { "notb",             PPC_FEATURE_NO_TB,              0 },
311   { "pa6t",             PPC_FEATURE_PA6T,               0 },
312   { "power4",           PPC_FEATURE_POWER4,             0 },
313   { "power5",           PPC_FEATURE_POWER5,             0 },
314   { "power5+",          PPC_FEATURE_POWER5_PLUS,        0 },
315   { "power6x",          PPC_FEATURE_POWER6_EXT,         0 },
316   { "ppc32",            PPC_FEATURE_32,                 0 },
317   { "ppc601",           PPC_FEATURE_601_INSTR,          0 },
318   { "ppc64",            PPC_FEATURE_64,                 0 },
319   { "ppcle",            PPC_FEATURE_PPC_LE,             0 },
320   { "smt",              PPC_FEATURE_SMT,                0 },
321   { "spe",              PPC_FEATURE_HAS_SPE,            0 },
322   { "true_le",          PPC_FEATURE_TRUE_LE,            0 },
323   { "ucache",           PPC_FEATURE_UNIFIED_CACHE,      0 },
324   { "vsx",              PPC_FEATURE_HAS_VSX,            0 },
325
326   /* AT_HWCAP2 masks.  */
327   { "arch_2_07",        PPC_FEATURE2_ARCH_2_07,         1 },
328   { "dscr",             PPC_FEATURE2_HAS_DSCR,          1 },
329   { "ebb",              PPC_FEATURE2_HAS_EBB,           1 },
330   { "htm",              PPC_FEATURE2_HAS_HTM,           1 },
331   { "htm-nosc",         PPC_FEATURE2_HTM_NOSC,          1 },
332   { "htm-no-suspend",   PPC_FEATURE2_HTM_NO_SUSPEND,    1 },
333   { "isel",             PPC_FEATURE2_HAS_ISEL,          1 },
334   { "tar",              PPC_FEATURE2_HAS_TAR,           1 },
335   { "vcrypto",          PPC_FEATURE2_HAS_VEC_CRYPTO,    1 },
336   { "arch_3_00",        PPC_FEATURE2_ARCH_3_00,         1 },
337   { "ieee128",          PPC_FEATURE2_HAS_IEEE128,       1 },
338   { "darn",             PPC_FEATURE2_DARN,              1 },
339   { "scv",              PPC_FEATURE2_SCV,               1 }
340 };
341
342 /* On PowerPC, we have a limited number of target clones that we care about
343    which means we can use an array to hold the options, rather than having more
344    elaborate data structures to identify each possible variation.  Order the
345    clones from the default to the highest ISA.  */
346 enum {
347   CLONE_DEFAULT         = 0,            /* default clone.  */
348   CLONE_ISA_2_05,                       /* ISA 2.05 (power6).  */
349   CLONE_ISA_2_06,                       /* ISA 2.06 (power7).  */
350   CLONE_ISA_2_07,                       /* ISA 2.07 (power8).  */
351   CLONE_ISA_3_00,                       /* ISA 3.00 (power9).  */
352   CLONE_MAX
353 };
354
355 /* Map compiler ISA bits into HWCAP names.  */
356 struct clone_map {
357   HOST_WIDE_INT isa_mask;       /* rs6000_isa mask */
358   const char *name;             /* name to use in __builtin_cpu_supports.  */
359 };
360
361 static const struct clone_map rs6000_clone_map[CLONE_MAX] = {
362   { 0,                          "" },           /* Default options.  */
363   { OPTION_MASK_CMPB,           "arch_2_05" },  /* ISA 2.05 (power6).  */
364   { OPTION_MASK_POPCNTD,        "arch_2_06" },  /* ISA 2.06 (power7).  */
365   { OPTION_MASK_P8_VECTOR,      "arch_2_07" },  /* ISA 2.07 (power8).  */
366   { OPTION_MASK_P9_VECTOR,      "arch_3_00" },  /* ISA 3.00 (power9).  */
367 };
368
369
370 /* Newer LIBCs explicitly export this symbol to declare that they provide
371    the AT_PLATFORM and AT_HWCAP/AT_HWCAP2 values in the TCB.  We emit a
372    reference to this symbol whenever we expand a CPU builtin, so that
373    we never link against an old LIBC.  */
374 const char *tcb_verification_symbol = "__parse_hwcap_and_convert_at_platform";
375
376 /* True if we have expanded a CPU builtin.  */
377 bool cpu_builtin_p;
378
379 /* Pointer to function (in rs6000-c.c) that can define or undefine target
380    macros that have changed.  Languages that don't support the preprocessor
381    don't link in rs6000-c.c, so we can't call it directly.  */
382 void (*rs6000_target_modify_macros_ptr) (bool, HOST_WIDE_INT, HOST_WIDE_INT);
383
384 /* Simplfy register classes into simpler classifications.  We assume
385    GPR_REG_TYPE - FPR_REG_TYPE are ordered so that we can use a simple range
386    check for standard register classes (gpr/floating/altivec/vsx) and
387    floating/vector classes (float/altivec/vsx).  */
388
389 enum rs6000_reg_type {
390   NO_REG_TYPE,
391   PSEUDO_REG_TYPE,
392   GPR_REG_TYPE,
393   VSX_REG_TYPE,
394   ALTIVEC_REG_TYPE,
395   FPR_REG_TYPE,
396   SPR_REG_TYPE,
397   CR_REG_TYPE
398 };
399
400 /* Map register class to register type.  */
401 static enum rs6000_reg_type reg_class_to_reg_type[N_REG_CLASSES];
402
403 /* First/last register type for the 'normal' register types (i.e. general
404    purpose, floating point, altivec, and VSX registers).  */
405 #define IS_STD_REG_TYPE(RTYPE) IN_RANGE(RTYPE, GPR_REG_TYPE, FPR_REG_TYPE)
406
407 #define IS_FP_VECT_REG_TYPE(RTYPE) IN_RANGE(RTYPE, VSX_REG_TYPE, FPR_REG_TYPE)
408
409
410 /* Register classes we care about in secondary reload or go if legitimate
411    address.  We only need to worry about GPR, FPR, and Altivec registers here,
412    along an ANY field that is the OR of the 3 register classes.  */
413
414 enum rs6000_reload_reg_type {
415   RELOAD_REG_GPR,                       /* General purpose registers.  */
416   RELOAD_REG_FPR,                       /* Traditional floating point regs.  */
417   RELOAD_REG_VMX,                       /* Altivec (VMX) registers.  */
418   RELOAD_REG_ANY,                       /* OR of GPR, FPR, Altivec masks.  */
419   N_RELOAD_REG
420 };
421
422 /* For setting up register classes, loop through the 3 register classes mapping
423    into real registers, and skip the ANY class, which is just an OR of the
424    bits.  */
425 #define FIRST_RELOAD_REG_CLASS  RELOAD_REG_GPR
426 #define LAST_RELOAD_REG_CLASS   RELOAD_REG_VMX
427
428 /* Map reload register type to a register in the register class.  */
429 struct reload_reg_map_type {
430   const char *name;                     /* Register class name.  */
431   int reg;                              /* Register in the register class.  */
432 };
433
434 static const struct reload_reg_map_type reload_reg_map[N_RELOAD_REG] = {
435   { "Gpr",      FIRST_GPR_REGNO },      /* RELOAD_REG_GPR.  */
436   { "Fpr",      FIRST_FPR_REGNO },      /* RELOAD_REG_FPR.  */
437   { "VMX",      FIRST_ALTIVEC_REGNO },  /* RELOAD_REG_VMX.  */
438   { "Any",      -1 },                   /* RELOAD_REG_ANY.  */
439 };
440
441 /* Mask bits for each register class, indexed per mode.  Historically the
442    compiler has been more restrictive which types can do PRE_MODIFY instead of
443    PRE_INC and PRE_DEC, so keep track of sepaate bits for these two.  */
444 typedef unsigned char addr_mask_type;
445
446 #define RELOAD_REG_VALID        0x01    /* Mode valid in register..  */
447 #define RELOAD_REG_MULTIPLE     0x02    /* Mode takes multiple registers.  */
448 #define RELOAD_REG_INDEXED      0x04    /* Reg+reg addressing.  */
449 #define RELOAD_REG_OFFSET       0x08    /* Reg+offset addressing. */
450 #define RELOAD_REG_PRE_INCDEC   0x10    /* PRE_INC/PRE_DEC valid.  */
451 #define RELOAD_REG_PRE_MODIFY   0x20    /* PRE_MODIFY valid.  */
452 #define RELOAD_REG_AND_M16      0x40    /* AND -16 addressing.  */
453 #define RELOAD_REG_QUAD_OFFSET  0x80    /* quad offset is limited.  */
454
455 /* Register type masks based on the type, of valid addressing modes.  */
456 struct rs6000_reg_addr {
457   enum insn_code reload_load;           /* INSN to reload for loading. */
458   enum insn_code reload_store;          /* INSN to reload for storing.  */
459   enum insn_code reload_fpr_gpr;        /* INSN to move from FPR to GPR.  */
460   enum insn_code reload_gpr_vsx;        /* INSN to move from GPR to VSX.  */
461   enum insn_code reload_vsx_gpr;        /* INSN to move from VSX to GPR.  */
462   addr_mask_type addr_mask[(int)N_RELOAD_REG]; /* Valid address masks.  */
463   bool scalar_in_vmx_p;                 /* Scalar value can go in VMX.  */
464 };
465
466 static struct rs6000_reg_addr reg_addr[NUM_MACHINE_MODES];
467
468 /* Helper function to say whether a mode supports PRE_INC or PRE_DEC.  */
469 static inline bool
470 mode_supports_pre_incdec_p (machine_mode mode)
471 {
472   return ((reg_addr[mode].addr_mask[RELOAD_REG_ANY] & RELOAD_REG_PRE_INCDEC)
473           != 0);
474 }
475
476 /* Helper function to say whether a mode supports PRE_MODIFY.  */
477 static inline bool
478 mode_supports_pre_modify_p (machine_mode mode)
479 {
480   return ((reg_addr[mode].addr_mask[RELOAD_REG_ANY] & RELOAD_REG_PRE_MODIFY)
481           != 0);
482 }
483
484 /* Return true if we have D-form addressing in altivec registers.  */
485 static inline bool
486 mode_supports_vmx_dform (machine_mode mode)
487 {
488   return ((reg_addr[mode].addr_mask[RELOAD_REG_VMX] & RELOAD_REG_OFFSET) != 0);
489 }
490
491 /* Return true if we have D-form addressing in VSX registers.  This addressing
492    is more limited than normal d-form addressing in that the offset must be
493    aligned on a 16-byte boundary.  */
494 static inline bool
495 mode_supports_dq_form (machine_mode mode)
496 {
497   return ((reg_addr[mode].addr_mask[RELOAD_REG_ANY] & RELOAD_REG_QUAD_OFFSET)
498           != 0);
499 }
500
501 /* Given that there exists at least one variable that is set (produced)
502    by OUT_INSN and read (consumed) by IN_INSN, return true iff
503    IN_INSN represents one or more memory store operations and none of
504    the variables set by OUT_INSN is used by IN_INSN as the address of a
505    store operation.  If either IN_INSN or OUT_INSN does not represent
506    a "single" RTL SET expression (as loosely defined by the
507    implementation of the single_set function) or a PARALLEL with only
508    SETs, CLOBBERs, and USEs inside, this function returns false.
509
510    This rs6000-specific version of store_data_bypass_p checks for
511    certain conditions that result in assertion failures (and internal
512    compiler errors) in the generic store_data_bypass_p function and
513    returns false rather than calling store_data_bypass_p if one of the
514    problematic conditions is detected.  */
515
516 int
517 rs6000_store_data_bypass_p (rtx_insn *out_insn, rtx_insn *in_insn)
518 {
519   rtx out_set, in_set;
520   rtx out_pat, in_pat;
521   rtx out_exp, in_exp;
522   int i, j;
523
524   in_set = single_set (in_insn);
525   if (in_set)
526     {
527       if (MEM_P (SET_DEST (in_set)))
528         {
529           out_set = single_set (out_insn);
530           if (!out_set)
531             {
532               out_pat = PATTERN (out_insn);
533               if (GET_CODE (out_pat) == PARALLEL)
534                 {
535                   for (i = 0; i < XVECLEN (out_pat, 0); i++)
536                     {
537                       out_exp = XVECEXP (out_pat, 0, i);
538                       if ((GET_CODE (out_exp) == CLOBBER)
539                           || (GET_CODE (out_exp) == USE))
540                         continue;
541                       else if (GET_CODE (out_exp) != SET)
542                         return false;
543                     }
544                 }
545             }
546         }
547     }
548   else
549     {
550       in_pat = PATTERN (in_insn);
551       if (GET_CODE (in_pat) != PARALLEL)
552         return false;
553
554       for (i = 0; i < XVECLEN (in_pat, 0); i++)
555         {
556           in_exp = XVECEXP (in_pat, 0, i);
557           if ((GET_CODE (in_exp) == CLOBBER) || (GET_CODE (in_exp) == USE))
558             continue;
559           else if (GET_CODE (in_exp) != SET)
560             return false;
561
562           if (MEM_P (SET_DEST (in_exp)))
563             {
564               out_set = single_set (out_insn);
565               if (!out_set)
566                 {
567                   out_pat = PATTERN (out_insn);
568                   if (GET_CODE (out_pat) != PARALLEL)
569                     return false;
570                   for (j = 0; j < XVECLEN (out_pat, 0); j++)
571                     {
572                       out_exp = XVECEXP (out_pat, 0, j);
573                       if ((GET_CODE (out_exp) == CLOBBER)
574                           || (GET_CODE (out_exp) == USE))
575                         continue;
576                       else if (GET_CODE (out_exp) != SET)
577                         return false;
578                     }
579                 }
580             }
581         }
582     }
583   return store_data_bypass_p (out_insn, in_insn);
584 }
585
586 \f
587 /* Processor costs (relative to an add) */
588
589 const struct processor_costs *rs6000_cost;
590
591 /* Instruction size costs on 32bit processors.  */
592 static const
593 struct processor_costs size32_cost = {
594   COSTS_N_INSNS (1),    /* mulsi */
595   COSTS_N_INSNS (1),    /* mulsi_const */
596   COSTS_N_INSNS (1),    /* mulsi_const9 */
597   COSTS_N_INSNS (1),    /* muldi */
598   COSTS_N_INSNS (1),    /* divsi */
599   COSTS_N_INSNS (1),    /* divdi */
600   COSTS_N_INSNS (1),    /* fp */
601   COSTS_N_INSNS (1),    /* dmul */
602   COSTS_N_INSNS (1),    /* sdiv */
603   COSTS_N_INSNS (1),    /* ddiv */
604   32,                   /* cache line size */
605   0,                    /* l1 cache */
606   0,                    /* l2 cache */
607   0,                    /* streams */
608   0,                    /* SF->DF convert */
609 };
610
611 /* Instruction size costs on 64bit processors.  */
612 static const
613 struct processor_costs size64_cost = {
614   COSTS_N_INSNS (1),    /* mulsi */
615   COSTS_N_INSNS (1),    /* mulsi_const */
616   COSTS_N_INSNS (1),    /* mulsi_const9 */
617   COSTS_N_INSNS (1),    /* muldi */
618   COSTS_N_INSNS (1),    /* divsi */
619   COSTS_N_INSNS (1),    /* divdi */
620   COSTS_N_INSNS (1),    /* fp */
621   COSTS_N_INSNS (1),    /* dmul */
622   COSTS_N_INSNS (1),    /* sdiv */
623   COSTS_N_INSNS (1),    /* ddiv */
624   128,                  /* cache line size */
625   0,                    /* l1 cache */
626   0,                    /* l2 cache */
627   0,                    /* streams */
628   0,                    /* SF->DF convert */
629 };
630
631 /* Instruction costs on RS64A processors.  */
632 static const
633 struct processor_costs rs64a_cost = {
634   COSTS_N_INSNS (20),   /* mulsi */
635   COSTS_N_INSNS (12),   /* mulsi_const */
636   COSTS_N_INSNS (8),    /* mulsi_const9 */
637   COSTS_N_INSNS (34),   /* muldi */
638   COSTS_N_INSNS (65),   /* divsi */
639   COSTS_N_INSNS (67),   /* divdi */
640   COSTS_N_INSNS (4),    /* fp */
641   COSTS_N_INSNS (4),    /* dmul */
642   COSTS_N_INSNS (31),   /* sdiv */
643   COSTS_N_INSNS (31),   /* ddiv */
644   128,                  /* cache line size */
645   128,                  /* l1 cache */
646   2048,                 /* l2 cache */
647   1,                    /* streams */
648   0,                    /* SF->DF convert */
649 };
650
651 /* Instruction costs on MPCCORE processors.  */
652 static const
653 struct processor_costs mpccore_cost = {
654   COSTS_N_INSNS (2),    /* mulsi */
655   COSTS_N_INSNS (2),    /* mulsi_const */
656   COSTS_N_INSNS (2),    /* mulsi_const9 */
657   COSTS_N_INSNS (2),    /* muldi */
658   COSTS_N_INSNS (6),    /* divsi */
659   COSTS_N_INSNS (6),    /* divdi */
660   COSTS_N_INSNS (4),    /* fp */
661   COSTS_N_INSNS (5),    /* dmul */
662   COSTS_N_INSNS (10),   /* sdiv */
663   COSTS_N_INSNS (17),   /* ddiv */
664   32,                   /* cache line size */
665   4,                    /* l1 cache */
666   16,                   /* l2 cache */
667   1,                    /* streams */
668   0,                    /* SF->DF convert */
669 };
670
671 /* Instruction costs on PPC403 processors.  */
672 static const
673 struct processor_costs ppc403_cost = {
674   COSTS_N_INSNS (4),    /* mulsi */
675   COSTS_N_INSNS (4),    /* mulsi_const */
676   COSTS_N_INSNS (4),    /* mulsi_const9 */
677   COSTS_N_INSNS (4),    /* muldi */
678   COSTS_N_INSNS (33),   /* divsi */
679   COSTS_N_INSNS (33),   /* divdi */
680   COSTS_N_INSNS (11),   /* fp */
681   COSTS_N_INSNS (11),   /* dmul */
682   COSTS_N_INSNS (11),   /* sdiv */
683   COSTS_N_INSNS (11),   /* ddiv */
684   32,                   /* cache line size */
685   4,                    /* l1 cache */
686   16,                   /* l2 cache */
687   1,                    /* streams */
688   0,                    /* SF->DF convert */
689 };
690
691 /* Instruction costs on PPC405 processors.  */
692 static const
693 struct processor_costs ppc405_cost = {
694   COSTS_N_INSNS (5),    /* mulsi */
695   COSTS_N_INSNS (4),    /* mulsi_const */
696   COSTS_N_INSNS (3),    /* mulsi_const9 */
697   COSTS_N_INSNS (5),    /* muldi */
698   COSTS_N_INSNS (35),   /* divsi */
699   COSTS_N_INSNS (35),   /* divdi */
700   COSTS_N_INSNS (11),   /* fp */
701   COSTS_N_INSNS (11),   /* dmul */
702   COSTS_N_INSNS (11),   /* sdiv */
703   COSTS_N_INSNS (11),   /* ddiv */
704   32,                   /* cache line size */
705   16,                   /* l1 cache */
706   128,                  /* l2 cache */
707   1,                    /* streams */
708   0,                    /* SF->DF convert */
709 };
710
711 /* Instruction costs on PPC440 processors.  */
712 static const
713 struct processor_costs ppc440_cost = {
714   COSTS_N_INSNS (3),    /* mulsi */
715   COSTS_N_INSNS (2),    /* mulsi_const */
716   COSTS_N_INSNS (2),    /* mulsi_const9 */
717   COSTS_N_INSNS (3),    /* muldi */
718   COSTS_N_INSNS (34),   /* divsi */
719   COSTS_N_INSNS (34),   /* divdi */
720   COSTS_N_INSNS (5),    /* fp */
721   COSTS_N_INSNS (5),    /* dmul */
722   COSTS_N_INSNS (19),   /* sdiv */
723   COSTS_N_INSNS (33),   /* ddiv */
724   32,                   /* cache line size */
725   32,                   /* l1 cache */
726   256,                  /* l2 cache */
727   1,                    /* streams */
728   0,                    /* SF->DF convert */
729 };
730
731 /* Instruction costs on PPC476 processors.  */
732 static const
733 struct processor_costs ppc476_cost = {
734   COSTS_N_INSNS (4),    /* mulsi */
735   COSTS_N_INSNS (4),    /* mulsi_const */
736   COSTS_N_INSNS (4),    /* mulsi_const9 */
737   COSTS_N_INSNS (4),    /* muldi */
738   COSTS_N_INSNS (11),   /* divsi */
739   COSTS_N_INSNS (11),   /* divdi */
740   COSTS_N_INSNS (6),    /* fp */
741   COSTS_N_INSNS (6),    /* dmul */
742   COSTS_N_INSNS (19),   /* sdiv */
743   COSTS_N_INSNS (33),   /* ddiv */
744   32,                   /* l1 cache line size */
745   32,                   /* l1 cache */
746   512,                  /* l2 cache */
747   1,                    /* streams */
748   0,                    /* SF->DF convert */
749 };
750
751 /* Instruction costs on PPC601 processors.  */
752 static const
753 struct processor_costs ppc601_cost = {
754   COSTS_N_INSNS (5),    /* mulsi */
755   COSTS_N_INSNS (5),    /* mulsi_const */
756   COSTS_N_INSNS (5),    /* mulsi_const9 */
757   COSTS_N_INSNS (5),    /* muldi */
758   COSTS_N_INSNS (36),   /* divsi */
759   COSTS_N_INSNS (36),   /* divdi */
760   COSTS_N_INSNS (4),    /* fp */
761   COSTS_N_INSNS (5),    /* dmul */
762   COSTS_N_INSNS (17),   /* sdiv */
763   COSTS_N_INSNS (31),   /* ddiv */
764   32,                   /* cache line size */
765   32,                   /* l1 cache */
766   256,                  /* l2 cache */
767   1,                    /* streams */
768   0,                    /* SF->DF convert */
769 };
770
771 /* Instruction costs on PPC603 processors.  */
772 static const
773 struct processor_costs ppc603_cost = {
774   COSTS_N_INSNS (5),    /* mulsi */
775   COSTS_N_INSNS (3),    /* mulsi_const */
776   COSTS_N_INSNS (2),    /* mulsi_const9 */
777   COSTS_N_INSNS (5),    /* muldi */
778   COSTS_N_INSNS (37),   /* divsi */
779   COSTS_N_INSNS (37),   /* divdi */
780   COSTS_N_INSNS (3),    /* fp */
781   COSTS_N_INSNS (4),    /* dmul */
782   COSTS_N_INSNS (18),   /* sdiv */
783   COSTS_N_INSNS (33),   /* ddiv */
784   32,                   /* cache line size */
785   8,                    /* l1 cache */
786   64,                   /* l2 cache */
787   1,                    /* streams */
788   0,                    /* SF->DF convert */
789 };
790
791 /* Instruction costs on PPC604 processors.  */
792 static const
793 struct processor_costs ppc604_cost = {
794   COSTS_N_INSNS (4),    /* mulsi */
795   COSTS_N_INSNS (4),    /* mulsi_const */
796   COSTS_N_INSNS (4),    /* mulsi_const9 */
797   COSTS_N_INSNS (4),    /* muldi */
798   COSTS_N_INSNS (20),   /* divsi */
799   COSTS_N_INSNS (20),   /* divdi */
800   COSTS_N_INSNS (3),    /* fp */
801   COSTS_N_INSNS (3),    /* dmul */
802   COSTS_N_INSNS (18),   /* sdiv */
803   COSTS_N_INSNS (32),   /* ddiv */
804   32,                   /* cache line size */
805   16,                   /* l1 cache */
806   512,                  /* l2 cache */
807   1,                    /* streams */
808   0,                    /* SF->DF convert */
809 };
810
811 /* Instruction costs on PPC604e processors.  */
812 static const
813 struct processor_costs ppc604e_cost = {
814   COSTS_N_INSNS (2),    /* mulsi */
815   COSTS_N_INSNS (2),    /* mulsi_const */
816   COSTS_N_INSNS (2),    /* mulsi_const9 */
817   COSTS_N_INSNS (2),    /* muldi */
818   COSTS_N_INSNS (20),   /* divsi */
819   COSTS_N_INSNS (20),   /* divdi */
820   COSTS_N_INSNS (3),    /* fp */
821   COSTS_N_INSNS (3),    /* dmul */
822   COSTS_N_INSNS (18),   /* sdiv */
823   COSTS_N_INSNS (32),   /* ddiv */
824   32,                   /* cache line size */
825   32,                   /* l1 cache */
826   1024,                 /* l2 cache */
827   1,                    /* streams */
828   0,                    /* SF->DF convert */
829 };
830
831 /* Instruction costs on PPC620 processors.  */
832 static const
833 struct processor_costs ppc620_cost = {
834   COSTS_N_INSNS (5),    /* mulsi */
835   COSTS_N_INSNS (4),    /* mulsi_const */
836   COSTS_N_INSNS (3),    /* mulsi_const9 */
837   COSTS_N_INSNS (7),    /* muldi */
838   COSTS_N_INSNS (21),   /* divsi */
839   COSTS_N_INSNS (37),   /* divdi */
840   COSTS_N_INSNS (3),    /* fp */
841   COSTS_N_INSNS (3),    /* dmul */
842   COSTS_N_INSNS (18),   /* sdiv */
843   COSTS_N_INSNS (32),   /* ddiv */
844   128,                  /* cache line size */
845   32,                   /* l1 cache */
846   1024,                 /* l2 cache */
847   1,                    /* streams */
848   0,                    /* SF->DF convert */
849 };
850
851 /* Instruction costs on PPC630 processors.  */
852 static const
853 struct processor_costs ppc630_cost = {
854   COSTS_N_INSNS (5),    /* mulsi */
855   COSTS_N_INSNS (4),    /* mulsi_const */
856   COSTS_N_INSNS (3),    /* mulsi_const9 */
857   COSTS_N_INSNS (7),    /* muldi */
858   COSTS_N_INSNS (21),   /* divsi */
859   COSTS_N_INSNS (37),   /* divdi */
860   COSTS_N_INSNS (3),    /* fp */
861   COSTS_N_INSNS (3),    /* dmul */
862   COSTS_N_INSNS (17),   /* sdiv */
863   COSTS_N_INSNS (21),   /* ddiv */
864   128,                  /* cache line size */
865   64,                   /* l1 cache */
866   1024,                 /* l2 cache */
867   1,                    /* streams */
868   0,                    /* SF->DF convert */
869 };
870
871 /* Instruction costs on Cell processor.  */
872 /* COSTS_N_INSNS (1) ~ one add.  */
873 static const
874 struct processor_costs ppccell_cost = {
875   COSTS_N_INSNS (9/2)+2,    /* mulsi */
876   COSTS_N_INSNS (6/2),    /* mulsi_const */
877   COSTS_N_INSNS (6/2),    /* mulsi_const9 */
878   COSTS_N_INSNS (15/2)+2,   /* muldi */
879   COSTS_N_INSNS (38/2),   /* divsi */
880   COSTS_N_INSNS (70/2),   /* divdi */
881   COSTS_N_INSNS (10/2),   /* fp */
882   COSTS_N_INSNS (10/2),   /* dmul */
883   COSTS_N_INSNS (74/2),   /* sdiv */
884   COSTS_N_INSNS (74/2),   /* ddiv */
885   128,                  /* cache line size */
886   32,                   /* l1 cache */
887   512,                  /* l2 cache */
888   6,                    /* streams */
889   0,                    /* SF->DF convert */
890 };
891
892 /* Instruction costs on PPC750 and PPC7400 processors.  */
893 static const
894 struct processor_costs ppc750_cost = {
895   COSTS_N_INSNS (5),    /* mulsi */
896   COSTS_N_INSNS (3),    /* mulsi_const */
897   COSTS_N_INSNS (2),    /* mulsi_const9 */
898   COSTS_N_INSNS (5),    /* muldi */
899   COSTS_N_INSNS (17),   /* divsi */
900   COSTS_N_INSNS (17),   /* divdi */
901   COSTS_N_INSNS (3),    /* fp */
902   COSTS_N_INSNS (3),    /* dmul */
903   COSTS_N_INSNS (17),   /* sdiv */
904   COSTS_N_INSNS (31),   /* ddiv */
905   32,                   /* cache line size */
906   32,                   /* l1 cache */
907   512,                  /* l2 cache */
908   1,                    /* streams */
909   0,                    /* SF->DF convert */
910 };
911
912 /* Instruction costs on PPC7450 processors.  */
913 static const
914 struct processor_costs ppc7450_cost = {
915   COSTS_N_INSNS (4),    /* mulsi */
916   COSTS_N_INSNS (3),    /* mulsi_const */
917   COSTS_N_INSNS (3),    /* mulsi_const9 */
918   COSTS_N_INSNS (4),    /* muldi */
919   COSTS_N_INSNS (23),   /* divsi */
920   COSTS_N_INSNS (23),   /* divdi */
921   COSTS_N_INSNS (5),    /* fp */
922   COSTS_N_INSNS (5),    /* dmul */
923   COSTS_N_INSNS (21),   /* sdiv */
924   COSTS_N_INSNS (35),   /* ddiv */
925   32,                   /* cache line size */
926   32,                   /* l1 cache */
927   1024,                 /* l2 cache */
928   1,                    /* streams */
929   0,                    /* SF->DF convert */
930 };
931
932 /* Instruction costs on PPC8540 processors.  */
933 static const
934 struct processor_costs ppc8540_cost = {
935   COSTS_N_INSNS (4),    /* mulsi */
936   COSTS_N_INSNS (4),    /* mulsi_const */
937   COSTS_N_INSNS (4),    /* mulsi_const9 */
938   COSTS_N_INSNS (4),    /* muldi */
939   COSTS_N_INSNS (19),   /* divsi */
940   COSTS_N_INSNS (19),   /* divdi */
941   COSTS_N_INSNS (4),    /* fp */
942   COSTS_N_INSNS (4),    /* dmul */
943   COSTS_N_INSNS (29),   /* sdiv */
944   COSTS_N_INSNS (29),   /* ddiv */
945   32,                   /* cache line size */
946   32,                   /* l1 cache */
947   256,                  /* l2 cache */
948   1,                    /* prefetch streams /*/
949   0,                    /* SF->DF convert */
950 };
951
952 /* Instruction costs on E300C2 and E300C3 cores.  */
953 static const
954 struct processor_costs ppce300c2c3_cost = {
955   COSTS_N_INSNS (4),    /* mulsi */
956   COSTS_N_INSNS (4),    /* mulsi_const */
957   COSTS_N_INSNS (4),    /* mulsi_const9 */
958   COSTS_N_INSNS (4),    /* muldi */
959   COSTS_N_INSNS (19),   /* divsi */
960   COSTS_N_INSNS (19),   /* divdi */
961   COSTS_N_INSNS (3),    /* fp */
962   COSTS_N_INSNS (4),    /* dmul */
963   COSTS_N_INSNS (18),   /* sdiv */
964   COSTS_N_INSNS (33),   /* ddiv */
965   32,
966   16,                   /* l1 cache */
967   16,                   /* l2 cache */
968   1,                    /* prefetch streams /*/
969   0,                    /* SF->DF convert */
970 };
971
972 /* Instruction costs on PPCE500MC processors.  */
973 static const
974 struct processor_costs ppce500mc_cost = {
975   COSTS_N_INSNS (4),    /* mulsi */
976   COSTS_N_INSNS (4),    /* mulsi_const */
977   COSTS_N_INSNS (4),    /* mulsi_const9 */
978   COSTS_N_INSNS (4),    /* muldi */
979   COSTS_N_INSNS (14),   /* divsi */
980   COSTS_N_INSNS (14),   /* divdi */
981   COSTS_N_INSNS (8),    /* fp */
982   COSTS_N_INSNS (10),   /* dmul */
983   COSTS_N_INSNS (36),   /* sdiv */
984   COSTS_N_INSNS (66),   /* ddiv */
985   64,                   /* cache line size */
986   32,                   /* l1 cache */
987   128,                  /* l2 cache */
988   1,                    /* prefetch streams /*/
989   0,                    /* SF->DF convert */
990 };
991
992 /* Instruction costs on PPCE500MC64 processors.  */
993 static const
994 struct processor_costs ppce500mc64_cost = {
995   COSTS_N_INSNS (4),    /* mulsi */
996   COSTS_N_INSNS (4),    /* mulsi_const */
997   COSTS_N_INSNS (4),    /* mulsi_const9 */
998   COSTS_N_INSNS (4),    /* muldi */
999   COSTS_N_INSNS (14),   /* divsi */
1000   COSTS_N_INSNS (14),   /* divdi */
1001   COSTS_N_INSNS (4),    /* fp */
1002   COSTS_N_INSNS (10),   /* dmul */
1003   COSTS_N_INSNS (36),   /* sdiv */
1004   COSTS_N_INSNS (66),   /* ddiv */
1005   64,                   /* cache line size */
1006   32,                   /* l1 cache */
1007   128,                  /* l2 cache */
1008   1,                    /* prefetch streams /*/
1009   0,                    /* SF->DF convert */
1010 };
1011
1012 /* Instruction costs on PPCE5500 processors.  */
1013 static const
1014 struct processor_costs ppce5500_cost = {
1015   COSTS_N_INSNS (5),    /* mulsi */
1016   COSTS_N_INSNS (5),    /* mulsi_const */
1017   COSTS_N_INSNS (4),    /* mulsi_const9 */
1018   COSTS_N_INSNS (5),    /* muldi */
1019   COSTS_N_INSNS (14),   /* divsi */
1020   COSTS_N_INSNS (14),   /* divdi */
1021   COSTS_N_INSNS (7),    /* fp */
1022   COSTS_N_INSNS (10),   /* dmul */
1023   COSTS_N_INSNS (36),   /* sdiv */
1024   COSTS_N_INSNS (66),   /* ddiv */
1025   64,                   /* cache line size */
1026   32,                   /* l1 cache */
1027   128,                  /* l2 cache */
1028   1,                    /* prefetch streams /*/
1029   0,                    /* SF->DF convert */
1030 };
1031
1032 /* Instruction costs on PPCE6500 processors.  */
1033 static const
1034 struct processor_costs ppce6500_cost = {
1035   COSTS_N_INSNS (5),    /* mulsi */
1036   COSTS_N_INSNS (5),    /* mulsi_const */
1037   COSTS_N_INSNS (4),    /* mulsi_const9 */
1038   COSTS_N_INSNS (5),    /* muldi */
1039   COSTS_N_INSNS (14),   /* divsi */
1040   COSTS_N_INSNS (14),   /* divdi */
1041   COSTS_N_INSNS (7),    /* fp */
1042   COSTS_N_INSNS (10),   /* dmul */
1043   COSTS_N_INSNS (36),   /* sdiv */
1044   COSTS_N_INSNS (66),   /* ddiv */
1045   64,                   /* cache line size */
1046   32,                   /* l1 cache */
1047   128,                  /* l2 cache */
1048   1,                    /* prefetch streams /*/
1049   0,                    /* SF->DF convert */
1050 };
1051
1052 /* Instruction costs on AppliedMicro Titan processors.  */
1053 static const
1054 struct processor_costs titan_cost = {
1055   COSTS_N_INSNS (5),    /* mulsi */
1056   COSTS_N_INSNS (5),    /* mulsi_const */
1057   COSTS_N_INSNS (5),    /* mulsi_const9 */
1058   COSTS_N_INSNS (5),    /* muldi */
1059   COSTS_N_INSNS (18),   /* divsi */
1060   COSTS_N_INSNS (18),   /* divdi */
1061   COSTS_N_INSNS (10),   /* fp */
1062   COSTS_N_INSNS (10),   /* dmul */
1063   COSTS_N_INSNS (46),   /* sdiv */
1064   COSTS_N_INSNS (72),   /* ddiv */
1065   32,                   /* cache line size */
1066   32,                   /* l1 cache */
1067   512,                  /* l2 cache */
1068   1,                    /* prefetch streams /*/
1069   0,                    /* SF->DF convert */
1070 };
1071
1072 /* Instruction costs on POWER4 and POWER5 processors.  */
1073 static const
1074 struct processor_costs power4_cost = {
1075   COSTS_N_INSNS (3),    /* mulsi */
1076   COSTS_N_INSNS (2),    /* mulsi_const */
1077   COSTS_N_INSNS (2),    /* mulsi_const9 */
1078   COSTS_N_INSNS (4),    /* muldi */
1079   COSTS_N_INSNS (18),   /* divsi */
1080   COSTS_N_INSNS (34),   /* divdi */
1081   COSTS_N_INSNS (3),    /* fp */
1082   COSTS_N_INSNS (3),    /* dmul */
1083   COSTS_N_INSNS (17),   /* sdiv */
1084   COSTS_N_INSNS (17),   /* ddiv */
1085   128,                  /* cache line size */
1086   32,                   /* l1 cache */
1087   1024,                 /* l2 cache */
1088   8,                    /* prefetch streams /*/
1089   0,                    /* SF->DF convert */
1090 };
1091
1092 /* Instruction costs on POWER6 processors.  */
1093 static const
1094 struct processor_costs power6_cost = {
1095   COSTS_N_INSNS (8),    /* mulsi */
1096   COSTS_N_INSNS (8),    /* mulsi_const */
1097   COSTS_N_INSNS (8),    /* mulsi_const9 */
1098   COSTS_N_INSNS (8),    /* muldi */
1099   COSTS_N_INSNS (22),   /* divsi */
1100   COSTS_N_INSNS (28),   /* divdi */
1101   COSTS_N_INSNS (3),    /* fp */
1102   COSTS_N_INSNS (3),    /* dmul */
1103   COSTS_N_INSNS (13),   /* sdiv */
1104   COSTS_N_INSNS (16),   /* ddiv */
1105   128,                  /* cache line size */
1106   64,                   /* l1 cache */
1107   2048,                 /* l2 cache */
1108   16,                   /* prefetch streams */
1109   0,                    /* SF->DF convert */
1110 };
1111
1112 /* Instruction costs on POWER7 processors.  */
1113 static const
1114 struct processor_costs power7_cost = {
1115   COSTS_N_INSNS (2),    /* mulsi */
1116   COSTS_N_INSNS (2),    /* mulsi_const */
1117   COSTS_N_INSNS (2),    /* mulsi_const9 */
1118   COSTS_N_INSNS (2),    /* muldi */
1119   COSTS_N_INSNS (18),   /* divsi */
1120   COSTS_N_INSNS (34),   /* divdi */
1121   COSTS_N_INSNS (3),    /* fp */
1122   COSTS_N_INSNS (3),    /* dmul */
1123   COSTS_N_INSNS (13),   /* sdiv */
1124   COSTS_N_INSNS (16),   /* ddiv */
1125   128,                  /* cache line size */
1126   32,                   /* l1 cache */
1127   256,                  /* l2 cache */
1128   12,                   /* prefetch streams */
1129   COSTS_N_INSNS (3),    /* SF->DF convert */
1130 };
1131
1132 /* Instruction costs on POWER8 processors.  */
1133 static const
1134 struct processor_costs power8_cost = {
1135   COSTS_N_INSNS (3),    /* mulsi */
1136   COSTS_N_INSNS (3),    /* mulsi_const */
1137   COSTS_N_INSNS (3),    /* mulsi_const9 */
1138   COSTS_N_INSNS (3),    /* muldi */
1139   COSTS_N_INSNS (19),   /* divsi */
1140   COSTS_N_INSNS (35),   /* divdi */
1141   COSTS_N_INSNS (3),    /* fp */
1142   COSTS_N_INSNS (3),    /* dmul */
1143   COSTS_N_INSNS (14),   /* sdiv */
1144   COSTS_N_INSNS (17),   /* ddiv */
1145   128,                  /* cache line size */
1146   32,                   /* l1 cache */
1147   256,                  /* l2 cache */
1148   12,                   /* prefetch streams */
1149   COSTS_N_INSNS (3),    /* SF->DF convert */
1150 };
1151
1152 /* Instruction costs on POWER9 processors.  */
1153 static const
1154 struct processor_costs power9_cost = {
1155   COSTS_N_INSNS (3),    /* mulsi */
1156   COSTS_N_INSNS (3),    /* mulsi_const */
1157   COSTS_N_INSNS (3),    /* mulsi_const9 */
1158   COSTS_N_INSNS (3),    /* muldi */
1159   COSTS_N_INSNS (8),    /* divsi */
1160   COSTS_N_INSNS (12),   /* divdi */
1161   COSTS_N_INSNS (3),    /* fp */
1162   COSTS_N_INSNS (3),    /* dmul */
1163   COSTS_N_INSNS (13),   /* sdiv */
1164   COSTS_N_INSNS (18),   /* ddiv */
1165   128,                  /* cache line size */
1166   32,                   /* l1 cache */
1167   512,                  /* l2 cache */
1168   8,                    /* prefetch streams */
1169   COSTS_N_INSNS (3),    /* SF->DF convert */
1170 };
1171
1172 /* Instruction costs on POWER A2 processors.  */
1173 static const
1174 struct processor_costs ppca2_cost = {
1175   COSTS_N_INSNS (16),    /* mulsi */
1176   COSTS_N_INSNS (16),    /* mulsi_const */
1177   COSTS_N_INSNS (16),    /* mulsi_const9 */
1178   COSTS_N_INSNS (16),   /* muldi */
1179   COSTS_N_INSNS (22),   /* divsi */
1180   COSTS_N_INSNS (28),   /* divdi */
1181   COSTS_N_INSNS (3),    /* fp */
1182   COSTS_N_INSNS (3),    /* dmul */
1183   COSTS_N_INSNS (59),   /* sdiv */
1184   COSTS_N_INSNS (72),   /* ddiv */
1185   64,
1186   16,                   /* l1 cache */
1187   2048,                 /* l2 cache */
1188   16,                   /* prefetch streams */
1189   0,                    /* SF->DF convert */
1190 };
1191
1192 \f
1193 /* Table that classifies rs6000 builtin functions (pure, const, etc.).  */
1194 #undef RS6000_BUILTIN_0
1195 #undef RS6000_BUILTIN_1
1196 #undef RS6000_BUILTIN_2
1197 #undef RS6000_BUILTIN_3
1198 #undef RS6000_BUILTIN_A
1199 #undef RS6000_BUILTIN_D
1200 #undef RS6000_BUILTIN_H
1201 #undef RS6000_BUILTIN_P
1202 #undef RS6000_BUILTIN_X
1203
1204 #define RS6000_BUILTIN_0(ENUM, NAME, MASK, ATTR, ICODE) \
1205   { NAME, ICODE, MASK, ATTR },
1206
1207 #define RS6000_BUILTIN_1(ENUM, NAME, MASK, ATTR, ICODE) \
1208   { NAME, ICODE, MASK, ATTR },
1209
1210 #define RS6000_BUILTIN_2(ENUM, NAME, MASK, ATTR, ICODE)  \
1211   { NAME, ICODE, MASK, ATTR },
1212
1213 #define RS6000_BUILTIN_3(ENUM, NAME, MASK, ATTR, ICODE)  \
1214   { NAME, ICODE, MASK, ATTR },
1215
1216 #define RS6000_BUILTIN_A(ENUM, NAME, MASK, ATTR, ICODE)  \
1217   { NAME, ICODE, MASK, ATTR },
1218
1219 #define RS6000_BUILTIN_D(ENUM, NAME, MASK, ATTR, ICODE)  \
1220   { NAME, ICODE, MASK, ATTR },
1221
1222 #define RS6000_BUILTIN_H(ENUM, NAME, MASK, ATTR, ICODE)  \
1223   { NAME, ICODE, MASK, ATTR },
1224
1225 #define RS6000_BUILTIN_P(ENUM, NAME, MASK, ATTR, ICODE)  \
1226   { NAME, ICODE, MASK, ATTR },
1227
1228 #define RS6000_BUILTIN_X(ENUM, NAME, MASK, ATTR, ICODE)  \
1229   { NAME, ICODE, MASK, ATTR },
1230
1231 struct rs6000_builtin_info_type {
1232   const char *name;
1233   const enum insn_code icode;
1234   const HOST_WIDE_INT mask;
1235   const unsigned attr;
1236 };
1237
1238 static const struct rs6000_builtin_info_type rs6000_builtin_info[] =
1239 {
1240 #include "rs6000-builtin.def"
1241 };
1242
1243 #undef RS6000_BUILTIN_0
1244 #undef RS6000_BUILTIN_1
1245 #undef RS6000_BUILTIN_2
1246 #undef RS6000_BUILTIN_3
1247 #undef RS6000_BUILTIN_A
1248 #undef RS6000_BUILTIN_D
1249 #undef RS6000_BUILTIN_H
1250 #undef RS6000_BUILTIN_P
1251 #undef RS6000_BUILTIN_X
1252
1253 /* Support for -mveclibabi=<xxx> to control which vector library to use.  */
1254 static tree (*rs6000_veclib_handler) (combined_fn, tree, tree);
1255
1256 \f
1257 static bool rs6000_debug_legitimate_address_p (machine_mode, rtx, bool);
1258 static tree rs6000_handle_longcall_attribute (tree *, tree, tree, int, bool *);
1259 static tree rs6000_handle_altivec_attribute (tree *, tree, tree, int, bool *);
1260 static tree rs6000_handle_struct_attribute (tree *, tree, tree, int, bool *);
1261 static tree rs6000_builtin_vectorized_libmass (combined_fn, tree, tree);
1262 static void rs6000_emit_set_long_const (rtx, HOST_WIDE_INT);
1263 static int rs6000_memory_move_cost (machine_mode, reg_class_t, bool);
1264 static bool rs6000_debug_rtx_costs (rtx, machine_mode, int, int, int *, bool);
1265 static int rs6000_debug_address_cost (rtx, machine_mode, addr_space_t,
1266                                       bool);
1267 static int rs6000_debug_adjust_cost (rtx_insn *, int, rtx_insn *, int,
1268                                      unsigned int);
1269 static bool is_microcoded_insn (rtx_insn *);
1270 static bool is_nonpipeline_insn (rtx_insn *);
1271 static bool is_cracked_insn (rtx_insn *);
1272 static bool is_load_insn (rtx, rtx *);
1273 static bool is_store_insn (rtx, rtx *);
1274 static bool set_to_load_agen (rtx_insn *,rtx_insn *);
1275 static bool insn_terminates_group_p (rtx_insn *, enum group_termination);
1276 static bool insn_must_be_first_in_group (rtx_insn *);
1277 static bool insn_must_be_last_in_group (rtx_insn *);
1278 static void altivec_init_builtins (void);
1279 static tree builtin_function_type (machine_mode, machine_mode,
1280                                    machine_mode, machine_mode,
1281                                    enum rs6000_builtins, const char *name);
1282 static void rs6000_common_init_builtins (void);
1283 static void htm_init_builtins (void);
1284 int easy_vector_constant (rtx, machine_mode);
1285 static rtx rs6000_debug_legitimize_address (rtx, rtx, machine_mode);
1286 static rtx rs6000_legitimize_tls_address (rtx, enum tls_model);
1287 static rtx rs6000_darwin64_record_arg (CUMULATIVE_ARGS *, const_tree,
1288                                        bool, bool);
1289 #if TARGET_MACHO
1290 static tree get_prev_label (tree);
1291 #endif
1292 static bool rs6000_mode_dependent_address (const_rtx);
1293 static bool rs6000_debug_mode_dependent_address (const_rtx);
1294 static bool rs6000_offsettable_memref_p (rtx, machine_mode, bool);
1295 static enum reg_class rs6000_secondary_reload_class (enum reg_class,
1296                                                      machine_mode, rtx);
1297 static enum reg_class rs6000_debug_secondary_reload_class (enum reg_class,
1298                                                            machine_mode,
1299                                                            rtx);
1300 static enum reg_class rs6000_preferred_reload_class (rtx, enum reg_class);
1301 static enum reg_class rs6000_debug_preferred_reload_class (rtx,
1302                                                            enum reg_class);
1303 static bool rs6000_debug_secondary_memory_needed (machine_mode,
1304                                                   reg_class_t,
1305                                                   reg_class_t);
1306 static bool rs6000_debug_can_change_mode_class (machine_mode,
1307                                                 machine_mode,
1308                                                 reg_class_t);
1309 static rtx rs6000_internal_arg_pointer (void);
1310
1311 static bool (*rs6000_mode_dependent_address_ptr) (const_rtx)
1312   = rs6000_mode_dependent_address;
1313
1314 enum reg_class (*rs6000_secondary_reload_class_ptr) (enum reg_class,
1315                                                      machine_mode, rtx)
1316   = rs6000_secondary_reload_class;
1317
1318 enum reg_class (*rs6000_preferred_reload_class_ptr) (rtx, enum reg_class)
1319   = rs6000_preferred_reload_class;
1320
1321 const int INSN_NOT_AVAILABLE = -1;
1322
1323 static void rs6000_print_isa_options (FILE *, int, const char *,
1324                                       HOST_WIDE_INT);
1325 static void rs6000_print_builtin_options (FILE *, int, const char *,
1326                                           HOST_WIDE_INT);
1327 static HOST_WIDE_INT rs6000_disable_incompatible_switches (void);
1328
1329 static enum rs6000_reg_type register_to_reg_type (rtx, bool *);
1330 static bool rs6000_secondary_reload_move (enum rs6000_reg_type,
1331                                           enum rs6000_reg_type,
1332                                           machine_mode,
1333                                           secondary_reload_info *,
1334                                           bool);
1335 rtl_opt_pass *make_pass_analyze_swaps (gcc::context*);
1336 static tree rs6000_fold_builtin (tree, int, tree *, bool);
1337
1338 /* Hash table stuff for keeping track of TOC entries.  */
1339
1340 struct GTY((for_user)) toc_hash_struct
1341 {
1342   /* `key' will satisfy CONSTANT_P; in fact, it will satisfy
1343      ASM_OUTPUT_SPECIAL_POOL_ENTRY_P.  */
1344   rtx key;
1345   machine_mode key_mode;
1346   int labelno;
1347 };
1348
1349 struct toc_hasher : ggc_ptr_hash<toc_hash_struct>
1350 {
1351   static hashval_t hash (toc_hash_struct *);
1352   static bool equal (toc_hash_struct *, toc_hash_struct *);
1353 };
1354
1355 static GTY (()) hash_table<toc_hasher> *toc_hash_table;
1356
1357 /* Hash table to keep track of the argument types for builtin functions.  */
1358
1359 struct GTY((for_user)) builtin_hash_struct
1360 {
1361   tree type;
1362   machine_mode mode[4]; /* return value + 3 arguments.  */
1363   unsigned char uns_p[4];       /* and whether the types are unsigned.  */
1364 };
1365
1366 struct builtin_hasher : ggc_ptr_hash<builtin_hash_struct>
1367 {
1368   static hashval_t hash (builtin_hash_struct *);
1369   static bool equal (builtin_hash_struct *, builtin_hash_struct *);
1370 };
1371
1372 static GTY (()) hash_table<builtin_hasher> *builtin_hash_table;
1373
1374 \f
1375 /* Default register names.  */
1376 char rs6000_reg_names[][8] =
1377 {
1378   /* GPRs */
1379       "0",  "1",  "2",  "3",  "4",  "5",  "6",  "7",
1380       "8",  "9", "10", "11", "12", "13", "14", "15",
1381      "16", "17", "18", "19", "20", "21", "22", "23",
1382      "24", "25", "26", "27", "28", "29", "30", "31",
1383   /* FPRs */
1384       "0",  "1",  "2",  "3",  "4",  "5",  "6",  "7",
1385       "8",  "9", "10", "11", "12", "13", "14", "15",
1386      "16", "17", "18", "19", "20", "21", "22", "23",
1387      "24", "25", "26", "27", "28", "29", "30", "31",
1388   /* VRs */
1389       "0",  "1",  "2",  "3",  "4",  "5",  "6",  "7",
1390       "8",  "9", "10", "11", "12", "13", "14", "15",
1391      "16", "17", "18", "19", "20", "21", "22", "23",
1392      "24", "25", "26", "27", "28", "29", "30", "31",
1393   /* lr ctr ca ap */
1394      "lr", "ctr", "ca", "ap",
1395   /* cr0..cr7 */
1396       "0",  "1",  "2",  "3",  "4",  "5",  "6",  "7",
1397   /* vrsave vscr sfp */
1398       "vrsave", "vscr", "sfp",
1399 };
1400
1401 #ifdef TARGET_REGNAMES
1402 static const char alt_reg_names[][8] =
1403 {
1404   /* GPRs */
1405    "%r0",  "%r1",  "%r2",  "%r3",  "%r4",  "%r5",  "%r6",  "%r7",
1406    "%r8",  "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15",
1407   "%r16", "%r17", "%r18", "%r19", "%r20", "%r21", "%r22", "%r23",
1408   "%r24", "%r25", "%r26", "%r27", "%r28", "%r29", "%r30", "%r31",
1409   /* FPRs */
1410    "%f0",  "%f1",  "%f2",  "%f3",  "%f4",  "%f5",  "%f6",  "%f7",
1411    "%f8",  "%f9", "%f10", "%f11", "%f12", "%f13", "%f14", "%f15",
1412   "%f16", "%f17", "%f18", "%f19", "%f20", "%f21", "%f22", "%f23",
1413   "%f24", "%f25", "%f26", "%f27", "%f28", "%f29", "%f30", "%f31",
1414   /* VRs */
1415    "%v0",  "%v1",  "%v2",  "%v3",  "%v4",  "%v5",  "%v6",  "%v7",
1416    "%v8",  "%v9", "%v10", "%v11", "%v12", "%v13", "%v14", "%v15",
1417   "%v16", "%v17", "%v18", "%v19", "%v20", "%v21", "%v22", "%v23",
1418   "%v24", "%v25", "%v26", "%v27", "%v28", "%v29", "%v30", "%v31",
1419   /* lr ctr ca ap */
1420     "lr",  "ctr",   "ca",   "ap",
1421   /* cr0..cr7 */
1422   "%cr0",  "%cr1", "%cr2", "%cr3", "%cr4", "%cr5", "%cr6", "%cr7",
1423   /* vrsave vscr sfp */
1424   "vrsave", "vscr", "sfp",
1425 };
1426 #endif
1427
1428 /* Table of valid machine attributes.  */
1429
1430 static const struct attribute_spec rs6000_attribute_table[] =
1431 {
1432   /* { name, min_len, max_len, decl_req, type_req, fn_type_req,
1433        affects_type_identity, handler, exclude } */
1434   { "altivec",   1, 1, false, true,  false, false,
1435     rs6000_handle_altivec_attribute, NULL },
1436   { "longcall",  0, 0, false, true,  true,  false,
1437     rs6000_handle_longcall_attribute, NULL },
1438   { "shortcall", 0, 0, false, true,  true,  false,
1439     rs6000_handle_longcall_attribute, NULL },
1440   { "ms_struct", 0, 0, false, false, false, false,
1441     rs6000_handle_struct_attribute, NULL },
1442   { "gcc_struct", 0, 0, false, false, false, false,
1443     rs6000_handle_struct_attribute, NULL },
1444 #ifdef SUBTARGET_ATTRIBUTE_TABLE
1445   SUBTARGET_ATTRIBUTE_TABLE,
1446 #endif
1447   { NULL,        0, 0, false, false, false, false, NULL, NULL }
1448 };
1449 \f
1450 #ifndef TARGET_PROFILE_KERNEL
1451 #define TARGET_PROFILE_KERNEL 0
1452 #endif
1453 \f
1454 /* Initialize the GCC target structure.  */
1455 #undef TARGET_ATTRIBUTE_TABLE
1456 #define TARGET_ATTRIBUTE_TABLE rs6000_attribute_table
1457 #undef TARGET_SET_DEFAULT_TYPE_ATTRIBUTES
1458 #define TARGET_SET_DEFAULT_TYPE_ATTRIBUTES rs6000_set_default_type_attributes
1459 #undef TARGET_ATTRIBUTE_TAKES_IDENTIFIER_P
1460 #define TARGET_ATTRIBUTE_TAKES_IDENTIFIER_P rs6000_attribute_takes_identifier_p
1461
1462 #undef TARGET_ASM_ALIGNED_DI_OP
1463 #define TARGET_ASM_ALIGNED_DI_OP DOUBLE_INT_ASM_OP
1464
1465 /* Default unaligned ops are only provided for ELF.  Find the ops needed
1466    for non-ELF systems.  */
1467 #ifndef OBJECT_FORMAT_ELF
1468 #if TARGET_XCOFF
1469 /* For XCOFF.  rs6000_assemble_integer will handle unaligned DIs on
1470    64-bit targets.  */
1471 #undef TARGET_ASM_UNALIGNED_HI_OP
1472 #define TARGET_ASM_UNALIGNED_HI_OP "\t.vbyte\t2,"
1473 #undef TARGET_ASM_UNALIGNED_SI_OP
1474 #define TARGET_ASM_UNALIGNED_SI_OP "\t.vbyte\t4,"
1475 #undef TARGET_ASM_UNALIGNED_DI_OP
1476 #define TARGET_ASM_UNALIGNED_DI_OP "\t.vbyte\t8,"
1477 #else
1478 /* For Darwin.  */
1479 #undef TARGET_ASM_UNALIGNED_HI_OP
1480 #define TARGET_ASM_UNALIGNED_HI_OP "\t.short\t"
1481 #undef TARGET_ASM_UNALIGNED_SI_OP
1482 #define TARGET_ASM_UNALIGNED_SI_OP "\t.long\t"
1483 #undef TARGET_ASM_UNALIGNED_DI_OP
1484 #define TARGET_ASM_UNALIGNED_DI_OP "\t.quad\t"
1485 #undef TARGET_ASM_ALIGNED_DI_OP
1486 #define TARGET_ASM_ALIGNED_DI_OP "\t.quad\t"
1487 #endif
1488 #endif
1489
1490 /* This hook deals with fixups for relocatable code and DI-mode objects
1491    in 64-bit code.  */
1492 #undef TARGET_ASM_INTEGER
1493 #define TARGET_ASM_INTEGER rs6000_assemble_integer
1494
1495 #if defined (HAVE_GAS_HIDDEN) && !TARGET_MACHO
1496 #undef TARGET_ASM_ASSEMBLE_VISIBILITY
1497 #define TARGET_ASM_ASSEMBLE_VISIBILITY rs6000_assemble_visibility
1498 #endif
1499
1500 #undef TARGET_SET_UP_BY_PROLOGUE
1501 #define TARGET_SET_UP_BY_PROLOGUE rs6000_set_up_by_prologue
1502
1503 #undef TARGET_SHRINK_WRAP_GET_SEPARATE_COMPONENTS
1504 #define TARGET_SHRINK_WRAP_GET_SEPARATE_COMPONENTS rs6000_get_separate_components
1505 #undef TARGET_SHRINK_WRAP_COMPONENTS_FOR_BB
1506 #define TARGET_SHRINK_WRAP_COMPONENTS_FOR_BB rs6000_components_for_bb
1507 #undef TARGET_SHRINK_WRAP_DISQUALIFY_COMPONENTS
1508 #define TARGET_SHRINK_WRAP_DISQUALIFY_COMPONENTS rs6000_disqualify_components
1509 #undef TARGET_SHRINK_WRAP_EMIT_PROLOGUE_COMPONENTS
1510 #define TARGET_SHRINK_WRAP_EMIT_PROLOGUE_COMPONENTS rs6000_emit_prologue_components
1511 #undef TARGET_SHRINK_WRAP_EMIT_EPILOGUE_COMPONENTS
1512 #define TARGET_SHRINK_WRAP_EMIT_EPILOGUE_COMPONENTS rs6000_emit_epilogue_components
1513 #undef TARGET_SHRINK_WRAP_SET_HANDLED_COMPONENTS
1514 #define TARGET_SHRINK_WRAP_SET_HANDLED_COMPONENTS rs6000_set_handled_components
1515
1516 #undef TARGET_EXTRA_LIVE_ON_ENTRY
1517 #define TARGET_EXTRA_LIVE_ON_ENTRY rs6000_live_on_entry
1518
1519 #undef TARGET_INTERNAL_ARG_POINTER
1520 #define TARGET_INTERNAL_ARG_POINTER rs6000_internal_arg_pointer
1521
1522 #undef TARGET_HAVE_TLS
1523 #define TARGET_HAVE_TLS HAVE_AS_TLS
1524
1525 #undef TARGET_CANNOT_FORCE_CONST_MEM
1526 #define TARGET_CANNOT_FORCE_CONST_MEM rs6000_cannot_force_const_mem
1527
1528 #undef TARGET_DELEGITIMIZE_ADDRESS
1529 #define TARGET_DELEGITIMIZE_ADDRESS rs6000_delegitimize_address
1530
1531 #undef TARGET_CONST_NOT_OK_FOR_DEBUG_P
1532 #define TARGET_CONST_NOT_OK_FOR_DEBUG_P rs6000_const_not_ok_for_debug_p
1533
1534 #undef TARGET_LEGITIMATE_COMBINED_INSN
1535 #define TARGET_LEGITIMATE_COMBINED_INSN rs6000_legitimate_combined_insn
1536
1537 #undef TARGET_ASM_FUNCTION_PROLOGUE
1538 #define TARGET_ASM_FUNCTION_PROLOGUE rs6000_output_function_prologue
1539 #undef TARGET_ASM_FUNCTION_EPILOGUE
1540 #define TARGET_ASM_FUNCTION_EPILOGUE rs6000_output_function_epilogue
1541
1542 #undef TARGET_ASM_OUTPUT_ADDR_CONST_EXTRA
1543 #define TARGET_ASM_OUTPUT_ADDR_CONST_EXTRA rs6000_output_addr_const_extra
1544
1545 #undef TARGET_LEGITIMIZE_ADDRESS
1546 #define TARGET_LEGITIMIZE_ADDRESS rs6000_legitimize_address
1547
1548 #undef  TARGET_SCHED_VARIABLE_ISSUE
1549 #define TARGET_SCHED_VARIABLE_ISSUE rs6000_variable_issue
1550
1551 #undef TARGET_SCHED_ISSUE_RATE
1552 #define TARGET_SCHED_ISSUE_RATE rs6000_issue_rate
1553 #undef TARGET_SCHED_ADJUST_COST
1554 #define TARGET_SCHED_ADJUST_COST rs6000_adjust_cost
1555 #undef TARGET_SCHED_ADJUST_PRIORITY
1556 #define TARGET_SCHED_ADJUST_PRIORITY rs6000_adjust_priority
1557 #undef TARGET_SCHED_IS_COSTLY_DEPENDENCE
1558 #define TARGET_SCHED_IS_COSTLY_DEPENDENCE rs6000_is_costly_dependence
1559 #undef TARGET_SCHED_INIT
1560 #define TARGET_SCHED_INIT rs6000_sched_init
1561 #undef TARGET_SCHED_FINISH
1562 #define TARGET_SCHED_FINISH rs6000_sched_finish
1563 #undef TARGET_SCHED_REORDER
1564 #define TARGET_SCHED_REORDER rs6000_sched_reorder
1565 #undef TARGET_SCHED_REORDER2
1566 #define TARGET_SCHED_REORDER2 rs6000_sched_reorder2
1567
1568 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD
1569 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD rs6000_use_sched_lookahead
1570
1571 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD
1572 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD rs6000_use_sched_lookahead_guard
1573
1574 #undef TARGET_SCHED_ALLOC_SCHED_CONTEXT
1575 #define TARGET_SCHED_ALLOC_SCHED_CONTEXT rs6000_alloc_sched_context
1576 #undef TARGET_SCHED_INIT_SCHED_CONTEXT
1577 #define TARGET_SCHED_INIT_SCHED_CONTEXT rs6000_init_sched_context
1578 #undef TARGET_SCHED_SET_SCHED_CONTEXT
1579 #define TARGET_SCHED_SET_SCHED_CONTEXT rs6000_set_sched_context
1580 #undef TARGET_SCHED_FREE_SCHED_CONTEXT
1581 #define TARGET_SCHED_FREE_SCHED_CONTEXT rs6000_free_sched_context
1582
1583 #undef TARGET_SCHED_CAN_SPECULATE_INSN
1584 #define TARGET_SCHED_CAN_SPECULATE_INSN rs6000_sched_can_speculate_insn
1585
1586 #undef TARGET_VECTORIZE_BUILTIN_MASK_FOR_LOAD
1587 #define TARGET_VECTORIZE_BUILTIN_MASK_FOR_LOAD rs6000_builtin_mask_for_load
1588 #undef TARGET_VECTORIZE_SUPPORT_VECTOR_MISALIGNMENT
1589 #define TARGET_VECTORIZE_SUPPORT_VECTOR_MISALIGNMENT            \
1590   rs6000_builtin_support_vector_misalignment
1591 #undef TARGET_VECTORIZE_VECTOR_ALIGNMENT_REACHABLE
1592 #define TARGET_VECTORIZE_VECTOR_ALIGNMENT_REACHABLE rs6000_vector_alignment_reachable
1593 #undef TARGET_VECTORIZE_BUILTIN_VECTORIZATION_COST
1594 #define TARGET_VECTORIZE_BUILTIN_VECTORIZATION_COST \
1595   rs6000_builtin_vectorization_cost
1596 #undef TARGET_VECTORIZE_PREFERRED_SIMD_MODE
1597 #define TARGET_VECTORIZE_PREFERRED_SIMD_MODE \
1598   rs6000_preferred_simd_mode
1599 #undef TARGET_VECTORIZE_INIT_COST
1600 #define TARGET_VECTORIZE_INIT_COST rs6000_init_cost
1601 #undef TARGET_VECTORIZE_ADD_STMT_COST
1602 #define TARGET_VECTORIZE_ADD_STMT_COST rs6000_add_stmt_cost
1603 #undef TARGET_VECTORIZE_FINISH_COST
1604 #define TARGET_VECTORIZE_FINISH_COST rs6000_finish_cost
1605 #undef TARGET_VECTORIZE_DESTROY_COST_DATA
1606 #define TARGET_VECTORIZE_DESTROY_COST_DATA rs6000_destroy_cost_data
1607
1608 #undef TARGET_INIT_BUILTINS
1609 #define TARGET_INIT_BUILTINS rs6000_init_builtins
1610 #undef TARGET_BUILTIN_DECL
1611 #define TARGET_BUILTIN_DECL rs6000_builtin_decl
1612
1613 #undef TARGET_FOLD_BUILTIN
1614 #define TARGET_FOLD_BUILTIN rs6000_fold_builtin
1615 #undef TARGET_GIMPLE_FOLD_BUILTIN
1616 #define TARGET_GIMPLE_FOLD_BUILTIN rs6000_gimple_fold_builtin
1617
1618 #undef TARGET_EXPAND_BUILTIN
1619 #define TARGET_EXPAND_BUILTIN rs6000_expand_builtin
1620
1621 #undef TARGET_MANGLE_TYPE
1622 #define TARGET_MANGLE_TYPE rs6000_mangle_type
1623
1624 #undef TARGET_INIT_LIBFUNCS
1625 #define TARGET_INIT_LIBFUNCS rs6000_init_libfuncs
1626
1627 #if TARGET_MACHO
1628 #undef TARGET_BINDS_LOCAL_P
1629 #define TARGET_BINDS_LOCAL_P darwin_binds_local_p
1630 #endif
1631
1632 #undef TARGET_MS_BITFIELD_LAYOUT_P
1633 #define TARGET_MS_BITFIELD_LAYOUT_P rs6000_ms_bitfield_layout_p
1634
1635 #undef TARGET_ASM_OUTPUT_MI_THUNK
1636 #define TARGET_ASM_OUTPUT_MI_THUNK rs6000_output_mi_thunk
1637
1638 #undef TARGET_ASM_CAN_OUTPUT_MI_THUNK
1639 #define TARGET_ASM_CAN_OUTPUT_MI_THUNK hook_bool_const_tree_hwi_hwi_const_tree_true
1640
1641 #undef TARGET_FUNCTION_OK_FOR_SIBCALL
1642 #define TARGET_FUNCTION_OK_FOR_SIBCALL rs6000_function_ok_for_sibcall
1643
1644 #undef TARGET_REGISTER_MOVE_COST
1645 #define TARGET_REGISTER_MOVE_COST rs6000_register_move_cost
1646 #undef TARGET_MEMORY_MOVE_COST
1647 #define TARGET_MEMORY_MOVE_COST rs6000_memory_move_cost
1648 #undef TARGET_IRA_CHANGE_PSEUDO_ALLOCNO_CLASS
1649 #define TARGET_IRA_CHANGE_PSEUDO_ALLOCNO_CLASS \
1650   rs6000_ira_change_pseudo_allocno_class
1651 #undef TARGET_CANNOT_COPY_INSN_P
1652 #define TARGET_CANNOT_COPY_INSN_P rs6000_cannot_copy_insn_p
1653 #undef TARGET_RTX_COSTS
1654 #define TARGET_RTX_COSTS rs6000_rtx_costs
1655 #undef TARGET_ADDRESS_COST
1656 #define TARGET_ADDRESS_COST hook_int_rtx_mode_as_bool_0
1657 #undef TARGET_INSN_COST
1658 #define TARGET_INSN_COST rs6000_insn_cost
1659
1660 #undef TARGET_INIT_DWARF_REG_SIZES_EXTRA
1661 #define TARGET_INIT_DWARF_REG_SIZES_EXTRA rs6000_init_dwarf_reg_sizes_extra
1662
1663 #undef TARGET_PROMOTE_FUNCTION_MODE
1664 #define TARGET_PROMOTE_FUNCTION_MODE rs6000_promote_function_mode
1665
1666 #undef TARGET_RETURN_IN_MEMORY
1667 #define TARGET_RETURN_IN_MEMORY rs6000_return_in_memory
1668
1669 #undef TARGET_RETURN_IN_MSB
1670 #define TARGET_RETURN_IN_MSB rs6000_return_in_msb
1671
1672 #undef TARGET_SETUP_INCOMING_VARARGS
1673 #define TARGET_SETUP_INCOMING_VARARGS setup_incoming_varargs
1674
1675 /* Always strict argument naming on rs6000.  */
1676 #undef TARGET_STRICT_ARGUMENT_NAMING
1677 #define TARGET_STRICT_ARGUMENT_NAMING hook_bool_CUMULATIVE_ARGS_true
1678 #undef TARGET_PRETEND_OUTGOING_VARARGS_NAMED
1679 #define TARGET_PRETEND_OUTGOING_VARARGS_NAMED hook_bool_CUMULATIVE_ARGS_true
1680 #undef TARGET_SPLIT_COMPLEX_ARG
1681 #define TARGET_SPLIT_COMPLEX_ARG hook_bool_const_tree_true
1682 #undef TARGET_MUST_PASS_IN_STACK
1683 #define TARGET_MUST_PASS_IN_STACK rs6000_must_pass_in_stack
1684 #undef TARGET_PASS_BY_REFERENCE
1685 #define TARGET_PASS_BY_REFERENCE rs6000_pass_by_reference
1686 #undef TARGET_ARG_PARTIAL_BYTES
1687 #define TARGET_ARG_PARTIAL_BYTES rs6000_arg_partial_bytes
1688 #undef TARGET_FUNCTION_ARG_ADVANCE
1689 #define TARGET_FUNCTION_ARG_ADVANCE rs6000_function_arg_advance
1690 #undef TARGET_FUNCTION_ARG
1691 #define TARGET_FUNCTION_ARG rs6000_function_arg
1692 #undef TARGET_FUNCTION_ARG_PADDING
1693 #define TARGET_FUNCTION_ARG_PADDING rs6000_function_arg_padding
1694 #undef TARGET_FUNCTION_ARG_BOUNDARY
1695 #define TARGET_FUNCTION_ARG_BOUNDARY rs6000_function_arg_boundary
1696
1697 #undef TARGET_BUILD_BUILTIN_VA_LIST
1698 #define TARGET_BUILD_BUILTIN_VA_LIST rs6000_build_builtin_va_list
1699
1700 #undef TARGET_EXPAND_BUILTIN_VA_START
1701 #define TARGET_EXPAND_BUILTIN_VA_START rs6000_va_start
1702
1703 #undef TARGET_GIMPLIFY_VA_ARG_EXPR
1704 #define TARGET_GIMPLIFY_VA_ARG_EXPR rs6000_gimplify_va_arg
1705
1706 #undef TARGET_EH_RETURN_FILTER_MODE
1707 #define TARGET_EH_RETURN_FILTER_MODE rs6000_eh_return_filter_mode
1708
1709 #undef TARGET_TRANSLATE_MODE_ATTRIBUTE
1710 #define TARGET_TRANSLATE_MODE_ATTRIBUTE rs6000_translate_mode_attribute
1711
1712 #undef TARGET_SCALAR_MODE_SUPPORTED_P
1713 #define TARGET_SCALAR_MODE_SUPPORTED_P rs6000_scalar_mode_supported_p
1714
1715 #undef TARGET_VECTOR_MODE_SUPPORTED_P
1716 #define TARGET_VECTOR_MODE_SUPPORTED_P rs6000_vector_mode_supported_p
1717
1718 #undef TARGET_FLOATN_MODE
1719 #define TARGET_FLOATN_MODE rs6000_floatn_mode
1720
1721 #undef TARGET_INVALID_ARG_FOR_UNPROTOTYPED_FN
1722 #define TARGET_INVALID_ARG_FOR_UNPROTOTYPED_FN invalid_arg_for_unprototyped_fn
1723
1724 #undef TARGET_MD_ASM_ADJUST
1725 #define TARGET_MD_ASM_ADJUST rs6000_md_asm_adjust
1726
1727 #undef TARGET_OPTION_OVERRIDE
1728 #define TARGET_OPTION_OVERRIDE rs6000_option_override
1729
1730 #undef TARGET_VECTORIZE_BUILTIN_VECTORIZED_FUNCTION
1731 #define TARGET_VECTORIZE_BUILTIN_VECTORIZED_FUNCTION \
1732   rs6000_builtin_vectorized_function
1733
1734 #undef TARGET_VECTORIZE_BUILTIN_MD_VECTORIZED_FUNCTION
1735 #define TARGET_VECTORIZE_BUILTIN_MD_VECTORIZED_FUNCTION \
1736   rs6000_builtin_md_vectorized_function
1737
1738 #undef TARGET_STACK_PROTECT_GUARD
1739 #define TARGET_STACK_PROTECT_GUARD rs6000_init_stack_protect_guard
1740
1741 #if !TARGET_MACHO
1742 #undef TARGET_STACK_PROTECT_FAIL
1743 #define TARGET_STACK_PROTECT_FAIL rs6000_stack_protect_fail
1744 #endif
1745
1746 #ifdef HAVE_AS_TLS
1747 #undef TARGET_ASM_OUTPUT_DWARF_DTPREL
1748 #define TARGET_ASM_OUTPUT_DWARF_DTPREL rs6000_output_dwarf_dtprel
1749 #endif
1750
1751 /* Use a 32-bit anchor range.  This leads to sequences like:
1752
1753         addis   tmp,anchor,high
1754         add     dest,tmp,low
1755
1756    where tmp itself acts as an anchor, and can be shared between
1757    accesses to the same 64k page.  */
1758 #undef TARGET_MIN_ANCHOR_OFFSET
1759 #define TARGET_MIN_ANCHOR_OFFSET -0x7fffffff - 1
1760 #undef TARGET_MAX_ANCHOR_OFFSET
1761 #define TARGET_MAX_ANCHOR_OFFSET 0x7fffffff
1762 #undef TARGET_USE_BLOCKS_FOR_CONSTANT_P
1763 #define TARGET_USE_BLOCKS_FOR_CONSTANT_P rs6000_use_blocks_for_constant_p
1764 #undef TARGET_USE_BLOCKS_FOR_DECL_P
1765 #define TARGET_USE_BLOCKS_FOR_DECL_P rs6000_use_blocks_for_decl_p
1766
1767 #undef TARGET_BUILTIN_RECIPROCAL
1768 #define TARGET_BUILTIN_RECIPROCAL rs6000_builtin_reciprocal
1769
1770 #undef TARGET_SECONDARY_RELOAD
1771 #define TARGET_SECONDARY_RELOAD rs6000_secondary_reload
1772 #undef TARGET_SECONDARY_MEMORY_NEEDED
1773 #define TARGET_SECONDARY_MEMORY_NEEDED rs6000_secondary_memory_needed
1774 #undef TARGET_SECONDARY_MEMORY_NEEDED_MODE
1775 #define TARGET_SECONDARY_MEMORY_NEEDED_MODE rs6000_secondary_memory_needed_mode
1776
1777 #undef TARGET_LEGITIMATE_ADDRESS_P
1778 #define TARGET_LEGITIMATE_ADDRESS_P rs6000_legitimate_address_p
1779
1780 #undef TARGET_MODE_DEPENDENT_ADDRESS_P
1781 #define TARGET_MODE_DEPENDENT_ADDRESS_P rs6000_mode_dependent_address_p
1782
1783 #undef TARGET_COMPUTE_PRESSURE_CLASSES
1784 #define TARGET_COMPUTE_PRESSURE_CLASSES rs6000_compute_pressure_classes
1785
1786 #undef TARGET_CAN_ELIMINATE
1787 #define TARGET_CAN_ELIMINATE rs6000_can_eliminate
1788
1789 #undef TARGET_CONDITIONAL_REGISTER_USAGE
1790 #define TARGET_CONDITIONAL_REGISTER_USAGE rs6000_conditional_register_usage
1791
1792 #undef TARGET_SCHED_REASSOCIATION_WIDTH
1793 #define TARGET_SCHED_REASSOCIATION_WIDTH rs6000_reassociation_width
1794
1795 #undef TARGET_TRAMPOLINE_INIT
1796 #define TARGET_TRAMPOLINE_INIT rs6000_trampoline_init
1797
1798 #undef TARGET_FUNCTION_VALUE
1799 #define TARGET_FUNCTION_VALUE rs6000_function_value
1800
1801 #undef TARGET_OPTION_VALID_ATTRIBUTE_P
1802 #define TARGET_OPTION_VALID_ATTRIBUTE_P rs6000_valid_attribute_p
1803
1804 #undef TARGET_OPTION_SAVE
1805 #define TARGET_OPTION_SAVE rs6000_function_specific_save
1806
1807 #undef TARGET_OPTION_RESTORE
1808 #define TARGET_OPTION_RESTORE rs6000_function_specific_restore
1809
1810 #undef TARGET_OPTION_PRINT
1811 #define TARGET_OPTION_PRINT rs6000_function_specific_print
1812
1813 #undef TARGET_CAN_INLINE_P
1814 #define TARGET_CAN_INLINE_P rs6000_can_inline_p
1815
1816 #undef TARGET_SET_CURRENT_FUNCTION
1817 #define TARGET_SET_CURRENT_FUNCTION rs6000_set_current_function
1818
1819 #undef TARGET_LEGITIMATE_CONSTANT_P
1820 #define TARGET_LEGITIMATE_CONSTANT_P rs6000_legitimate_constant_p
1821
1822 #undef TARGET_VECTORIZE_VEC_PERM_CONST
1823 #define TARGET_VECTORIZE_VEC_PERM_CONST rs6000_vectorize_vec_perm_const
1824
1825 #undef TARGET_CAN_USE_DOLOOP_P
1826 #define TARGET_CAN_USE_DOLOOP_P can_use_doloop_if_innermost
1827
1828 #undef TARGET_PREDICT_DOLOOP_P
1829 #define TARGET_PREDICT_DOLOOP_P rs6000_predict_doloop_p
1830
1831 #undef TARGET_ATOMIC_ASSIGN_EXPAND_FENV
1832 #define TARGET_ATOMIC_ASSIGN_EXPAND_FENV rs6000_atomic_assign_expand_fenv
1833
1834 #undef TARGET_LIBGCC_CMP_RETURN_MODE
1835 #define TARGET_LIBGCC_CMP_RETURN_MODE rs6000_abi_word_mode
1836 #undef TARGET_LIBGCC_SHIFT_COUNT_MODE
1837 #define TARGET_LIBGCC_SHIFT_COUNT_MODE rs6000_abi_word_mode
1838 #undef TARGET_UNWIND_WORD_MODE
1839 #define TARGET_UNWIND_WORD_MODE rs6000_abi_word_mode
1840
1841 #undef TARGET_OFFLOAD_OPTIONS
1842 #define TARGET_OFFLOAD_OPTIONS rs6000_offload_options
1843
1844 #undef TARGET_C_MODE_FOR_SUFFIX
1845 #define TARGET_C_MODE_FOR_SUFFIX rs6000_c_mode_for_suffix
1846
1847 #undef TARGET_INVALID_BINARY_OP
1848 #define TARGET_INVALID_BINARY_OP rs6000_invalid_binary_op
1849
1850 #undef TARGET_OPTAB_SUPPORTED_P
1851 #define TARGET_OPTAB_SUPPORTED_P rs6000_optab_supported_p
1852
1853 #undef TARGET_CUSTOM_FUNCTION_DESCRIPTORS
1854 #define TARGET_CUSTOM_FUNCTION_DESCRIPTORS 1
1855
1856 #undef TARGET_COMPARE_VERSION_PRIORITY
1857 #define TARGET_COMPARE_VERSION_PRIORITY rs6000_compare_version_priority
1858
1859 #undef TARGET_GENERATE_VERSION_DISPATCHER_BODY
1860 #define TARGET_GENERATE_VERSION_DISPATCHER_BODY                         \
1861   rs6000_generate_version_dispatcher_body
1862
1863 #undef TARGET_GET_FUNCTION_VERSIONS_DISPATCHER
1864 #define TARGET_GET_FUNCTION_VERSIONS_DISPATCHER                         \
1865   rs6000_get_function_versions_dispatcher
1866
1867 #undef TARGET_OPTION_FUNCTION_VERSIONS
1868 #define TARGET_OPTION_FUNCTION_VERSIONS common_function_versions
1869
1870 #undef TARGET_HARD_REGNO_NREGS
1871 #define TARGET_HARD_REGNO_NREGS rs6000_hard_regno_nregs_hook
1872 #undef TARGET_HARD_REGNO_MODE_OK
1873 #define TARGET_HARD_REGNO_MODE_OK rs6000_hard_regno_mode_ok
1874
1875 #undef TARGET_MODES_TIEABLE_P
1876 #define TARGET_MODES_TIEABLE_P rs6000_modes_tieable_p
1877
1878 #undef TARGET_HARD_REGNO_CALL_PART_CLOBBERED
1879 #define TARGET_HARD_REGNO_CALL_PART_CLOBBERED \
1880   rs6000_hard_regno_call_part_clobbered
1881
1882 #undef TARGET_SLOW_UNALIGNED_ACCESS
1883 #define TARGET_SLOW_UNALIGNED_ACCESS rs6000_slow_unaligned_access
1884
1885 #undef TARGET_CAN_CHANGE_MODE_CLASS
1886 #define TARGET_CAN_CHANGE_MODE_CLASS rs6000_can_change_mode_class
1887
1888 #undef TARGET_CONSTANT_ALIGNMENT
1889 #define TARGET_CONSTANT_ALIGNMENT rs6000_constant_alignment
1890
1891 #undef TARGET_STARTING_FRAME_OFFSET
1892 #define TARGET_STARTING_FRAME_OFFSET rs6000_starting_frame_offset
1893
1894 #if TARGET_ELF && RS6000_WEAK
1895 #undef TARGET_ASM_GLOBALIZE_DECL_NAME
1896 #define TARGET_ASM_GLOBALIZE_DECL_NAME rs6000_globalize_decl_name
1897 #endif
1898
1899 #undef TARGET_SETJMP_PRESERVES_NONVOLATILE_REGS_P
1900 #define TARGET_SETJMP_PRESERVES_NONVOLATILE_REGS_P hook_bool_void_true
1901
1902 #undef TARGET_MANGLE_DECL_ASSEMBLER_NAME
1903 #define TARGET_MANGLE_DECL_ASSEMBLER_NAME rs6000_mangle_decl_assembler_name
1904 \f
1905
1906 /* Processor table.  */
1907 struct rs6000_ptt
1908 {
1909   const char *const name;               /* Canonical processor name.  */
1910   const enum processor_type processor;  /* Processor type enum value.  */
1911   const HOST_WIDE_INT target_enable;    /* Target flags to enable.  */
1912 };
1913
1914 static struct rs6000_ptt const processor_target_table[] =
1915 {
1916 #define RS6000_CPU(NAME, CPU, FLAGS) { NAME, CPU, FLAGS },
1917 #include "rs6000-cpus.def"
1918 #undef RS6000_CPU
1919 };
1920
1921 /* Look up a processor name for -mcpu=xxx and -mtune=xxx.  Return -1 if the
1922    name is invalid.  */
1923
1924 static int
1925 rs6000_cpu_name_lookup (const char *name)
1926 {
1927   size_t i;
1928
1929   if (name != NULL)
1930     {
1931       for (i = 0; i < ARRAY_SIZE (processor_target_table); i++)
1932         if (! strcmp (name, processor_target_table[i].name))
1933           return (int)i;
1934     }
1935
1936   return -1;
1937 }
1938
1939 \f
1940 /* Return number of consecutive hard regs needed starting at reg REGNO
1941    to hold something of mode MODE.
1942    This is ordinarily the length in words of a value of mode MODE
1943    but can be less for certain modes in special long registers.
1944
1945    POWER and PowerPC GPRs hold 32 bits worth;
1946    PowerPC64 GPRs and FPRs point register holds 64 bits worth.  */
1947
1948 static int
1949 rs6000_hard_regno_nregs_internal (int regno, machine_mode mode)
1950 {
1951   unsigned HOST_WIDE_INT reg_size;
1952
1953   /* 128-bit floating point usually takes 2 registers, unless it is IEEE
1954      128-bit floating point that can go in vector registers, which has VSX
1955      memory addressing.  */
1956   if (FP_REGNO_P (regno))
1957     reg_size = (VECTOR_MEM_VSX_P (mode) || FLOAT128_VECTOR_P (mode)
1958                 ? UNITS_PER_VSX_WORD
1959                 : UNITS_PER_FP_WORD);
1960
1961   else if (ALTIVEC_REGNO_P (regno))
1962     reg_size = UNITS_PER_ALTIVEC_WORD;
1963
1964   else
1965     reg_size = UNITS_PER_WORD;
1966
1967   return (GET_MODE_SIZE (mode) + reg_size - 1) / reg_size;
1968 }
1969
1970 /* Value is 1 if hard register REGNO can hold a value of machine-mode
1971    MODE.  */
1972 static int
1973 rs6000_hard_regno_mode_ok_uncached (int regno, machine_mode mode)
1974 {
1975   int last_regno = regno + rs6000_hard_regno_nregs[mode][regno] - 1;
1976
1977   if (COMPLEX_MODE_P (mode))
1978     mode = GET_MODE_INNER (mode);
1979
1980   /* PTImode can only go in GPRs.  Quad word memory operations require even/odd
1981      register combinations, and use PTImode where we need to deal with quad
1982      word memory operations.  Don't allow quad words in the argument or frame
1983      pointer registers, just registers 0..31.  */
1984   if (mode == PTImode)
1985     return (IN_RANGE (regno, FIRST_GPR_REGNO, LAST_GPR_REGNO)
1986             && IN_RANGE (last_regno, FIRST_GPR_REGNO, LAST_GPR_REGNO)
1987             && ((regno & 1) == 0));
1988
1989   /* VSX registers that overlap the FPR registers are larger than for non-VSX
1990      implementations.  Don't allow an item to be split between a FP register
1991      and an Altivec register.  Allow TImode in all VSX registers if the user
1992      asked for it.  */
1993   if (TARGET_VSX && VSX_REGNO_P (regno)
1994       && (VECTOR_MEM_VSX_P (mode)
1995           || FLOAT128_VECTOR_P (mode)
1996           || reg_addr[mode].scalar_in_vmx_p
1997           || mode == TImode
1998           || (TARGET_VADDUQM && mode == V1TImode)))
1999     {
2000       if (FP_REGNO_P (regno))
2001         return FP_REGNO_P (last_regno);
2002
2003       if (ALTIVEC_REGNO_P (regno))
2004         {
2005           if (GET_MODE_SIZE (mode) != 16 && !reg_addr[mode].scalar_in_vmx_p)
2006             return 0;
2007
2008           return ALTIVEC_REGNO_P (last_regno);
2009         }
2010     }
2011
2012   /* The GPRs can hold any mode, but values bigger than one register
2013      cannot go past R31.  */
2014   if (INT_REGNO_P (regno))
2015     return INT_REGNO_P (last_regno);
2016
2017   /* The float registers (except for VSX vector modes) can only hold floating
2018      modes and DImode.  */
2019   if (FP_REGNO_P (regno))
2020     {
2021       if (FLOAT128_VECTOR_P (mode))
2022         return false;
2023
2024       if (SCALAR_FLOAT_MODE_P (mode)
2025           && (mode != TDmode || (regno % 2) == 0)
2026           && FP_REGNO_P (last_regno))
2027         return 1;
2028
2029       if (GET_MODE_CLASS (mode) == MODE_INT)
2030         {
2031           if(GET_MODE_SIZE (mode) == UNITS_PER_FP_WORD)
2032             return 1;
2033
2034           if (TARGET_P8_VECTOR && (mode == SImode))
2035             return 1;
2036
2037           if (TARGET_P9_VECTOR && (mode == QImode || mode == HImode))
2038             return 1;
2039         }
2040
2041       return 0;
2042     }
2043
2044   /* The CR register can only hold CC modes.  */
2045   if (CR_REGNO_P (regno))
2046     return GET_MODE_CLASS (mode) == MODE_CC;
2047
2048   if (CA_REGNO_P (regno))
2049     return mode == Pmode || mode == SImode;
2050
2051   /* AltiVec only in AldyVec registers.  */
2052   if (ALTIVEC_REGNO_P (regno))
2053     return (VECTOR_MEM_ALTIVEC_OR_VSX_P (mode)
2054             || mode == V1TImode);
2055
2056   /* We cannot put non-VSX TImode or PTImode anywhere except general register
2057      and it must be able to fit within the register set.  */
2058
2059   return GET_MODE_SIZE (mode) <= UNITS_PER_WORD;
2060 }
2061
2062 /* Implement TARGET_HARD_REGNO_NREGS.  */
2063
2064 static unsigned int
2065 rs6000_hard_regno_nregs_hook (unsigned int regno, machine_mode mode)
2066 {
2067   return rs6000_hard_regno_nregs[mode][regno];
2068 }
2069
2070 /* Implement TARGET_HARD_REGNO_MODE_OK.  */
2071
2072 static bool
2073 rs6000_hard_regno_mode_ok (unsigned int regno, machine_mode mode)
2074 {
2075   return rs6000_hard_regno_mode_ok_p[mode][regno];
2076 }
2077
2078 /* Implement TARGET_MODES_TIEABLE_P.
2079
2080    PTImode cannot tie with other modes because PTImode is restricted to even
2081    GPR registers, and TImode can go in any GPR as well as VSX registers (PR
2082    57744).
2083
2084    Altivec/VSX vector tests were moved ahead of scalar float mode, so that IEEE
2085    128-bit floating point on VSX systems ties with other vectors.  */
2086
2087 static bool
2088 rs6000_modes_tieable_p (machine_mode mode1, machine_mode mode2)
2089 {
2090   if (mode1 == PTImode)
2091     return mode2 == PTImode;
2092   if (mode2 == PTImode)
2093     return false;
2094
2095   if (ALTIVEC_OR_VSX_VECTOR_MODE (mode1))
2096     return ALTIVEC_OR_VSX_VECTOR_MODE (mode2);
2097   if (ALTIVEC_OR_VSX_VECTOR_MODE (mode2))
2098     return false;
2099
2100   if (SCALAR_FLOAT_MODE_P (mode1))
2101     return SCALAR_FLOAT_MODE_P (mode2);
2102   if (SCALAR_FLOAT_MODE_P (mode2))
2103     return false;
2104
2105   if (GET_MODE_CLASS (mode1) == MODE_CC)
2106     return GET_MODE_CLASS (mode2) == MODE_CC;
2107   if (GET_MODE_CLASS (mode2) == MODE_CC)
2108     return false;
2109
2110   return true;
2111 }
2112
2113 /* Implement TARGET_HARD_REGNO_CALL_PART_CLOBBERED.  */
2114
2115 static bool
2116 rs6000_hard_regno_call_part_clobbered (rtx_insn *insn ATTRIBUTE_UNUSED,
2117                                        unsigned int regno, machine_mode mode)
2118 {
2119   if (TARGET_32BIT
2120       && TARGET_POWERPC64
2121       && GET_MODE_SIZE (mode) > 4
2122       && INT_REGNO_P (regno))
2123     return true;
2124
2125   if (TARGET_VSX
2126       && FP_REGNO_P (regno)
2127       && GET_MODE_SIZE (mode) > 8
2128       && !FLOAT128_2REG_P (mode))
2129     return true;
2130
2131   return false;
2132 }
2133
2134 /* Print interesting facts about registers.  */
2135 static void
2136 rs6000_debug_reg_print (int first_regno, int last_regno, const char *reg_name)
2137 {
2138   int r, m;
2139
2140   for (r = first_regno; r <= last_regno; ++r)
2141     {
2142       const char *comma = "";
2143       int len;
2144
2145       if (first_regno == last_regno)
2146         fprintf (stderr, "%s:\t", reg_name);
2147       else
2148         fprintf (stderr, "%s%d:\t", reg_name, r - first_regno);
2149
2150       len = 8;
2151       for (m = 0; m < NUM_MACHINE_MODES; ++m)
2152         if (rs6000_hard_regno_mode_ok_p[m][r] && rs6000_hard_regno_nregs[m][r])
2153           {
2154             if (len > 70)
2155               {
2156                 fprintf (stderr, ",\n\t");
2157                 len = 8;
2158                 comma = "";
2159               }
2160
2161             if (rs6000_hard_regno_nregs[m][r] > 1)
2162               len += fprintf (stderr, "%s%s/%d", comma, GET_MODE_NAME (m),
2163                              rs6000_hard_regno_nregs[m][r]);
2164             else
2165               len += fprintf (stderr, "%s%s", comma, GET_MODE_NAME (m));
2166
2167             comma = ", ";
2168           }
2169
2170       if (call_used_regs[r])
2171         {
2172           if (len > 70)
2173             {
2174               fprintf (stderr, ",\n\t");
2175               len = 8;
2176               comma = "";
2177             }
2178
2179           len += fprintf (stderr, "%s%s", comma, "call-used");
2180           comma = ", ";
2181         }
2182
2183       if (fixed_regs[r])
2184         {
2185           if (len > 70)
2186             {
2187               fprintf (stderr, ",\n\t");
2188               len = 8;
2189               comma = "";
2190             }
2191
2192           len += fprintf (stderr, "%s%s", comma, "fixed");
2193           comma = ", ";
2194         }
2195
2196       if (len > 70)
2197         {
2198           fprintf (stderr, ",\n\t");
2199           comma = "";
2200         }
2201
2202       len += fprintf (stderr, "%sreg-class = %s", comma,
2203                       reg_class_names[(int)rs6000_regno_regclass[r]]);
2204       comma = ", ";
2205
2206       if (len > 70)
2207         {
2208           fprintf (stderr, ",\n\t");
2209           comma = "";
2210         }
2211
2212       fprintf (stderr, "%sregno = %d\n", comma, r);
2213     }
2214 }
2215
2216 static const char *
2217 rs6000_debug_vector_unit (enum rs6000_vector v)
2218 {
2219   const char *ret;
2220
2221   switch (v)
2222     {
2223     case VECTOR_NONE:      ret = "none";      break;
2224     case VECTOR_ALTIVEC:   ret = "altivec";   break;
2225     case VECTOR_VSX:       ret = "vsx";       break;
2226     case VECTOR_P8_VECTOR: ret = "p8_vector"; break;
2227     default:               ret = "unknown";   break;
2228     }
2229
2230   return ret;
2231 }
2232
2233 /* Inner function printing just the address mask for a particular reload
2234    register class.  */
2235 DEBUG_FUNCTION char *
2236 rs6000_debug_addr_mask (addr_mask_type mask, bool keep_spaces)
2237 {
2238   static char ret[8];
2239   char *p = ret;
2240
2241   if ((mask & RELOAD_REG_VALID) != 0)
2242     *p++ = 'v';
2243   else if (keep_spaces)
2244     *p++ = ' ';
2245
2246   if ((mask & RELOAD_REG_MULTIPLE) != 0)
2247     *p++ = 'm';
2248   else if (keep_spaces)
2249     *p++ = ' ';
2250
2251   if ((mask & RELOAD_REG_INDEXED) != 0)
2252     *p++ = 'i';
2253   else if (keep_spaces)
2254     *p++ = ' ';
2255
2256   if ((mask & RELOAD_REG_QUAD_OFFSET) != 0)
2257     *p++ = 'O';
2258   else if ((mask & RELOAD_REG_OFFSET) != 0)
2259     *p++ = 'o';
2260   else if (keep_spaces)
2261     *p++ = ' ';
2262
2263   if ((mask & RELOAD_REG_PRE_INCDEC) != 0)
2264     *p++ = '+';
2265   else if (keep_spaces)
2266     *p++ = ' ';
2267
2268   if ((mask & RELOAD_REG_PRE_MODIFY) != 0)
2269     *p++ = '+';
2270   else if (keep_spaces)
2271     *p++ = ' ';
2272
2273   if ((mask & RELOAD_REG_AND_M16) != 0)
2274     *p++ = '&';
2275   else if (keep_spaces)
2276     *p++ = ' ';
2277
2278   *p = '\0';
2279
2280   return ret;
2281 }
2282
2283 /* Print the address masks in a human readble fashion.  */
2284 DEBUG_FUNCTION void
2285 rs6000_debug_print_mode (ssize_t m)
2286 {
2287   ssize_t rc;
2288   int spaces = 0;
2289
2290   fprintf (stderr, "Mode: %-5s", GET_MODE_NAME (m));
2291   for (rc = 0; rc < N_RELOAD_REG; rc++)
2292     fprintf (stderr, " %s: %s", reload_reg_map[rc].name,
2293              rs6000_debug_addr_mask (reg_addr[m].addr_mask[rc], true));
2294
2295   if ((reg_addr[m].reload_store != CODE_FOR_nothing)
2296       || (reg_addr[m].reload_load != CODE_FOR_nothing))
2297     {
2298       fprintf (stderr, "%*s  Reload=%c%c", spaces, "",
2299                (reg_addr[m].reload_store != CODE_FOR_nothing) ? 's' : '*',
2300                (reg_addr[m].reload_load != CODE_FOR_nothing) ? 'l' : '*');
2301       spaces = 0;
2302     }
2303   else
2304     spaces += sizeof ("  Reload=sl") - 1;
2305
2306   if (reg_addr[m].scalar_in_vmx_p)
2307     {
2308       fprintf (stderr, "%*s  Upper=y", spaces, "");
2309       spaces = 0;
2310     }
2311   else
2312     spaces += sizeof ("  Upper=y") - 1;
2313
2314   if (rs6000_vector_unit[m] != VECTOR_NONE
2315       || rs6000_vector_mem[m] != VECTOR_NONE)
2316     {
2317       fprintf (stderr, "%*s  vector: arith=%-10s mem=%s",
2318                spaces, "",
2319                rs6000_debug_vector_unit (rs6000_vector_unit[m]),
2320                rs6000_debug_vector_unit (rs6000_vector_mem[m]));
2321     }
2322
2323   fputs ("\n", stderr);
2324 }
2325
2326 #define DEBUG_FMT_ID "%-32s= "
2327 #define DEBUG_FMT_D   DEBUG_FMT_ID "%d\n"
2328 #define DEBUG_FMT_WX  DEBUG_FMT_ID "%#.12" HOST_WIDE_INT_PRINT "x: "
2329 #define DEBUG_FMT_S   DEBUG_FMT_ID "%s\n"
2330
2331 /* Print various interesting information with -mdebug=reg.  */
2332 static void
2333 rs6000_debug_reg_global (void)
2334 {
2335   static const char *const tf[2] = { "false", "true" };
2336   const char *nl = (const char *)0;
2337   int m;
2338   size_t m1, m2, v;
2339   char costly_num[20];
2340   char nop_num[20];
2341   char flags_buffer[40];
2342   const char *costly_str;
2343   const char *nop_str;
2344   const char *trace_str;
2345   const char *abi_str;
2346   const char *cmodel_str;
2347   struct cl_target_option cl_opts;
2348
2349   /* Modes we want tieable information on.  */
2350   static const machine_mode print_tieable_modes[] = {
2351     QImode,
2352     HImode,
2353     SImode,
2354     DImode,
2355     TImode,
2356     PTImode,
2357     SFmode,
2358     DFmode,
2359     TFmode,
2360     IFmode,
2361     KFmode,
2362     SDmode,
2363     DDmode,
2364     TDmode,
2365     V16QImode,
2366     V8HImode,
2367     V4SImode,
2368     V2DImode,
2369     V1TImode,
2370     V32QImode,
2371     V16HImode,
2372     V8SImode,
2373     V4DImode,
2374     V2TImode,
2375     V4SFmode,
2376     V2DFmode,
2377     V8SFmode,
2378     V4DFmode,
2379     CCmode,
2380     CCUNSmode,
2381     CCEQmode,
2382   };
2383
2384   /* Virtual regs we are interested in.  */
2385   const static struct {
2386     int regno;                  /* register number.  */
2387     const char *name;           /* register name.  */
2388   } virtual_regs[] = {
2389     { STACK_POINTER_REGNUM,                     "stack pointer:" },
2390     { TOC_REGNUM,                               "toc:          " },
2391     { STATIC_CHAIN_REGNUM,                      "static chain: " },
2392     { RS6000_PIC_OFFSET_TABLE_REGNUM,           "pic offset:   " },
2393     { HARD_FRAME_POINTER_REGNUM,                "hard frame:   " },
2394     { ARG_POINTER_REGNUM,                       "arg pointer:  " },
2395     { FRAME_POINTER_REGNUM,                     "frame pointer:" },
2396     { FIRST_PSEUDO_REGISTER,                    "first pseudo: " },
2397     { FIRST_VIRTUAL_REGISTER,                   "first virtual:" },
2398     { VIRTUAL_INCOMING_ARGS_REGNUM,             "incoming_args:" },
2399     { VIRTUAL_STACK_VARS_REGNUM,                "stack_vars:   " },
2400     { VIRTUAL_STACK_DYNAMIC_REGNUM,             "stack_dynamic:" },
2401     { VIRTUAL_OUTGOING_ARGS_REGNUM,             "outgoing_args:" },
2402     { VIRTUAL_CFA_REGNUM,                       "cfa (frame):  " },
2403     { VIRTUAL_PREFERRED_STACK_BOUNDARY_REGNUM,  "stack boundry:" },
2404     { LAST_VIRTUAL_REGISTER,                    "last virtual: " },
2405   };
2406
2407   fputs ("\nHard register information:\n", stderr);
2408   rs6000_debug_reg_print (FIRST_GPR_REGNO, LAST_GPR_REGNO, "gr");
2409   rs6000_debug_reg_print (FIRST_FPR_REGNO, LAST_FPR_REGNO, "fp");
2410   rs6000_debug_reg_print (FIRST_ALTIVEC_REGNO,
2411                           LAST_ALTIVEC_REGNO,
2412                           "vs");
2413   rs6000_debug_reg_print (LR_REGNO, LR_REGNO, "lr");
2414   rs6000_debug_reg_print (CTR_REGNO, CTR_REGNO, "ctr");
2415   rs6000_debug_reg_print (CR0_REGNO, CR7_REGNO, "cr");
2416   rs6000_debug_reg_print (CA_REGNO, CA_REGNO, "ca");
2417   rs6000_debug_reg_print (VRSAVE_REGNO, VRSAVE_REGNO, "vrsave");
2418   rs6000_debug_reg_print (VSCR_REGNO, VSCR_REGNO, "vscr");
2419
2420   fputs ("\nVirtual/stack/frame registers:\n", stderr);
2421   for (v = 0; v < ARRAY_SIZE (virtual_regs); v++)
2422     fprintf (stderr, "%s regno = %3d\n", virtual_regs[v].name, virtual_regs[v].regno);
2423
2424   fprintf (stderr,
2425            "\n"
2426            "d  reg_class = %s\n"
2427            "f  reg_class = %s\n"
2428            "v  reg_class = %s\n"
2429            "wa reg_class = %s\n"
2430            "we reg_class = %s\n"
2431            "wr reg_class = %s\n"
2432            "wx reg_class = %s\n"
2433            "wA reg_class = %s\n"
2434            "\n",
2435            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_d]],
2436            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_f]],
2437            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_v]],
2438            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wa]],
2439            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_we]],
2440            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wr]],
2441            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wx]],
2442            reg_class_names[rs6000_constraints[RS6000_CONSTRAINT_wA]]);
2443
2444   nl = "\n";
2445   for (m = 0; m < NUM_MACHINE_MODES; ++m)
2446     rs6000_debug_print_mode (m);
2447
2448   fputs ("\n", stderr);
2449
2450   for (m1 = 0; m1 < ARRAY_SIZE (print_tieable_modes); m1++)
2451     {
2452       machine_mode mode1 = print_tieable_modes[m1];
2453       bool first_time = true;
2454
2455       nl = (const char *)0;
2456       for (m2 = 0; m2 < ARRAY_SIZE (print_tieable_modes); m2++)
2457         {
2458           machine_mode mode2 = print_tieable_modes[m2];
2459           if (mode1 != mode2 && rs6000_modes_tieable_p (mode1, mode2))
2460             {
2461               if (first_time)
2462                 {
2463                   fprintf (stderr, "Tieable modes %s:", GET_MODE_NAME (mode1));
2464                   nl = "\n";
2465                   first_time = false;
2466                 }
2467
2468               fprintf (stderr, " %s", GET_MODE_NAME (mode2));
2469             }
2470         }
2471
2472       if (!first_time)
2473         fputs ("\n", stderr);
2474     }
2475
2476   if (nl)
2477     fputs (nl, stderr);
2478
2479   if (rs6000_recip_control)
2480     {
2481       fprintf (stderr, "\nReciprocal mask = 0x%x\n", rs6000_recip_control);
2482
2483       for (m = 0; m < NUM_MACHINE_MODES; ++m)
2484         if (rs6000_recip_bits[m])
2485           {
2486             fprintf (stderr,
2487                      "Reciprocal estimate mode: %-5s divide: %s rsqrt: %s\n",
2488                      GET_MODE_NAME (m),
2489                      (RS6000_RECIP_AUTO_RE_P (m)
2490                       ? "auto"
2491                       : (RS6000_RECIP_HAVE_RE_P (m) ? "have" : "none")),
2492                      (RS6000_RECIP_AUTO_RSQRTE_P (m)
2493                       ? "auto"
2494                       : (RS6000_RECIP_HAVE_RSQRTE_P (m) ? "have" : "none")));
2495           }
2496
2497       fputs ("\n", stderr);
2498     }
2499
2500   if (rs6000_cpu_index >= 0)
2501     {
2502       const char *name = processor_target_table[rs6000_cpu_index].name;
2503       HOST_WIDE_INT flags
2504         = processor_target_table[rs6000_cpu_index].target_enable;
2505
2506       sprintf (flags_buffer, "-mcpu=%s flags", name);
2507       rs6000_print_isa_options (stderr, 0, flags_buffer, flags);
2508     }
2509   else
2510     fprintf (stderr, DEBUG_FMT_S, "cpu", "<none>");
2511
2512   if (rs6000_tune_index >= 0)
2513     {
2514       const char *name = processor_target_table[rs6000_tune_index].name;
2515       HOST_WIDE_INT flags
2516         = processor_target_table[rs6000_tune_index].target_enable;
2517
2518       sprintf (flags_buffer, "-mtune=%s flags", name);
2519       rs6000_print_isa_options (stderr, 0, flags_buffer, flags);
2520     }
2521   else
2522     fprintf (stderr, DEBUG_FMT_S, "tune", "<none>");
2523
2524   cl_target_option_save (&cl_opts, &global_options);
2525   rs6000_print_isa_options (stderr, 0, "rs6000_isa_flags",
2526                             rs6000_isa_flags);
2527
2528   rs6000_print_isa_options (stderr, 0, "rs6000_isa_flags_explicit",
2529                             rs6000_isa_flags_explicit);
2530
2531   rs6000_print_builtin_options (stderr, 0, "rs6000_builtin_mask",
2532                                 rs6000_builtin_mask);
2533
2534   rs6000_print_isa_options (stderr, 0, "TARGET_DEFAULT", TARGET_DEFAULT);
2535
2536   fprintf (stderr, DEBUG_FMT_S, "--with-cpu default",
2537            OPTION_TARGET_CPU_DEFAULT ? OPTION_TARGET_CPU_DEFAULT : "<none>");
2538
2539   switch (rs6000_sched_costly_dep)
2540     {
2541     case max_dep_latency:
2542       costly_str = "max_dep_latency";
2543       break;
2544
2545     case no_dep_costly:
2546       costly_str = "no_dep_costly";
2547       break;
2548
2549     case all_deps_costly:
2550       costly_str = "all_deps_costly";
2551       break;
2552
2553     case true_store_to_load_dep_costly:
2554       costly_str = "true_store_to_load_dep_costly";
2555       break;
2556
2557     case store_to_load_dep_costly:
2558       costly_str = "store_to_load_dep_costly";
2559       break;
2560
2561     default:
2562       costly_str = costly_num;
2563       sprintf (costly_num, "%d", (int)rs6000_sched_costly_dep);
2564       break;
2565     }
2566
2567   fprintf (stderr, DEBUG_FMT_S, "sched_costly_dep", costly_str);
2568
2569   switch (rs6000_sched_insert_nops)
2570     {
2571     case sched_finish_regroup_exact:
2572       nop_str = "sched_finish_regroup_exact";
2573       break;
2574
2575     case sched_finish_pad_groups:
2576       nop_str = "sched_finish_pad_groups";
2577       break;
2578
2579     case sched_finish_none:
2580       nop_str = "sched_finish_none";
2581       break;
2582
2583     default:
2584       nop_str = nop_num;
2585       sprintf (nop_num, "%d", (int)rs6000_sched_insert_nops);
2586       break;
2587     }
2588
2589   fprintf (stderr, DEBUG_FMT_S, "sched_insert_nops", nop_str);
2590
2591   switch (rs6000_sdata)
2592     {
2593     default:
2594     case SDATA_NONE:
2595       break;
2596
2597     case SDATA_DATA:
2598       fprintf (stderr, DEBUG_FMT_S, "sdata", "data");
2599       break;
2600
2601     case SDATA_SYSV:
2602       fprintf (stderr, DEBUG_FMT_S, "sdata", "sysv");
2603       break;
2604
2605     case SDATA_EABI:
2606       fprintf (stderr, DEBUG_FMT_S, "sdata", "eabi");
2607       break;
2608
2609     }
2610
2611   switch (rs6000_traceback)
2612     {
2613     case traceback_default:     trace_str = "default";  break;
2614     case traceback_none:        trace_str = "none";     break;
2615     case traceback_part:        trace_str = "part";     break;
2616     case traceback_full:        trace_str = "full";     break;
2617     default:                    trace_str = "unknown";  break;
2618     }
2619
2620   fprintf (stderr, DEBUG_FMT_S, "traceback", trace_str);
2621
2622   switch (rs6000_current_cmodel)
2623     {
2624     case CMODEL_SMALL:  cmodel_str = "small";   break;
2625     case CMODEL_MEDIUM: cmodel_str = "medium";  break;
2626     case CMODEL_LARGE:  cmodel_str = "large";   break;
2627     default:            cmodel_str = "unknown"; break;
2628     }
2629
2630   fprintf (stderr, DEBUG_FMT_S, "cmodel", cmodel_str);
2631
2632   switch (rs6000_current_abi)
2633     {
2634     case ABI_NONE:      abi_str = "none";       break;
2635     case ABI_AIX:       abi_str = "aix";        break;
2636     case ABI_ELFv2:     abi_str = "ELFv2";      break;
2637     case ABI_V4:        abi_str = "V4";         break;
2638     case ABI_DARWIN:    abi_str = "darwin";     break;
2639     default:            abi_str = "unknown";    break;
2640     }
2641
2642   fprintf (stderr, DEBUG_FMT_S, "abi", abi_str);
2643
2644   if (rs6000_altivec_abi)
2645     fprintf (stderr, DEBUG_FMT_S, "altivec_abi", "true");
2646
2647   if (rs6000_darwin64_abi)
2648     fprintf (stderr, DEBUG_FMT_S, "darwin64_abi", "true");
2649
2650   fprintf (stderr, DEBUG_FMT_S, "soft_float",
2651            (TARGET_SOFT_FLOAT ? "true" : "false"));
2652
2653   if (TARGET_LINK_STACK)
2654     fprintf (stderr, DEBUG_FMT_S, "link_stack", "true");
2655
2656   if (TARGET_P8_FUSION)
2657     {
2658       char options[80];
2659
2660       strcpy (options, "power8");
2661       if (TARGET_P8_FUSION_SIGN)
2662         strcat (options, ", sign");
2663
2664       fprintf (stderr, DEBUG_FMT_S, "fusion", options);
2665     }
2666
2667   fprintf (stderr, DEBUG_FMT_S, "plt-format",
2668            TARGET_SECURE_PLT ? "secure" : "bss");
2669   fprintf (stderr, DEBUG_FMT_S, "struct-return",
2670            aix_struct_return ? "aix" : "sysv");
2671   fprintf (stderr, DEBUG_FMT_S, "always_hint", tf[!!rs6000_always_hint]);
2672   fprintf (stderr, DEBUG_FMT_S, "sched_groups", tf[!!rs6000_sched_groups]);
2673   fprintf (stderr, DEBUG_FMT_S, "align_branch",
2674            tf[!!rs6000_align_branch_targets]);
2675   fprintf (stderr, DEBUG_FMT_D, "tls_size", rs6000_tls_size);
2676   fprintf (stderr, DEBUG_FMT_D, "long_double_size",
2677            rs6000_long_double_type_size);
2678   if (rs6000_long_double_type_size > 64)
2679     {
2680       fprintf (stderr, DEBUG_FMT_S, "long double type",
2681                TARGET_IEEEQUAD ? "IEEE" : "IBM");
2682       fprintf (stderr, DEBUG_FMT_S, "default long double type",
2683                TARGET_IEEEQUAD_DEFAULT ? "IEEE" : "IBM");
2684     }
2685   fprintf (stderr, DEBUG_FMT_D, "sched_restricted_insns_priority",
2686            (int)rs6000_sched_restricted_insns_priority);
2687   fprintf (stderr, DEBUG_FMT_D, "Number of standard builtins",
2688            (int)END_BUILTINS);
2689   fprintf (stderr, DEBUG_FMT_D, "Number of rs6000 builtins",
2690            (int)RS6000_BUILTIN_COUNT);
2691
2692   fprintf (stderr, DEBUG_FMT_D, "Enable float128 on VSX",
2693            (int)TARGET_FLOAT128_ENABLE_TYPE);
2694
2695   if (TARGET_VSX)
2696     fprintf (stderr, DEBUG_FMT_D, "VSX easy 64-bit scalar element",
2697              (int)VECTOR_ELEMENT_SCALAR_64BIT);
2698
2699   if (TARGET_DIRECT_MOVE_128)
2700     fprintf (stderr, DEBUG_FMT_D, "VSX easy 64-bit mfvsrld element",
2701              (int)VECTOR_ELEMENT_MFVSRLD_64BIT);
2702 }
2703
2704 \f
2705 /* Update the addr mask bits in reg_addr to help secondary reload and go if
2706    legitimate address support to figure out the appropriate addressing to
2707    use.  */
2708
2709 static void
2710 rs6000_setup_reg_addr_masks (void)
2711 {
2712   ssize_t rc, reg, m, nregs;
2713   addr_mask_type any_addr_mask, addr_mask;
2714
2715   for (m = 0; m < NUM_MACHINE_MODES; ++m)
2716     {
2717       machine_mode m2 = (machine_mode) m;
2718       bool complex_p = false;
2719       bool small_int_p = (m2 == QImode || m2 == HImode || m2 == SImode);
2720       size_t msize;
2721
2722       if (COMPLEX_MODE_P (m2))
2723         {
2724           complex_p = true;
2725           m2 = GET_MODE_INNER (m2);
2726         }
2727
2728       msize = GET_MODE_SIZE (m2);
2729
2730       /* SDmode is special in that we want to access it only via REG+REG
2731          addressing on power7 and above, since we want to use the LFIWZX and
2732          STFIWZX instructions to load it.  */
2733       bool indexed_only_p = (m == SDmode && TARGET_NO_SDMODE_STACK);
2734
2735       any_addr_mask = 0;
2736       for (rc = FIRST_RELOAD_REG_CLASS; rc <= LAST_RELOAD_REG_CLASS; rc++)
2737         {
2738           addr_mask = 0;
2739           reg = reload_reg_map[rc].reg;
2740
2741           /* Can mode values go in the GPR/FPR/Altivec registers?  */
2742           if (reg >= 0 && rs6000_hard_regno_mode_ok_p[m][reg])
2743             {
2744               bool small_int_vsx_p = (small_int_p
2745                                       && (rc == RELOAD_REG_FPR
2746                                           || rc == RELOAD_REG_VMX));
2747
2748               nregs = rs6000_hard_regno_nregs[m][reg];
2749               addr_mask |= RELOAD_REG_VALID;
2750
2751               /* Indicate if the mode takes more than 1 physical register.  If
2752                  it takes a single register, indicate it can do REG+REG
2753                  addressing.  Small integers in VSX registers can only do
2754                  REG+REG addressing.  */
2755               if (small_int_vsx_p)
2756                 addr_mask |= RELOAD_REG_INDEXED;
2757               else if (nregs > 1 || m == BLKmode || complex_p)
2758                 addr_mask |= RELOAD_REG_MULTIPLE;
2759               else
2760                 addr_mask |= RELOAD_REG_INDEXED;
2761
2762               /* Figure out if we can do PRE_INC, PRE_DEC, or PRE_MODIFY
2763                  addressing.  If we allow scalars into Altivec registers,
2764                  don't allow PRE_INC, PRE_DEC, or PRE_MODIFY.
2765
2766                  For VSX systems, we don't allow update addressing for
2767                  DFmode/SFmode if those registers can go in both the
2768                  traditional floating point registers and Altivec registers.
2769                  The load/store instructions for the Altivec registers do not
2770                  have update forms.  If we allowed update addressing, it seems
2771                  to break IV-OPT code using floating point if the index type is
2772                  int instead of long (PR target/81550 and target/84042).  */
2773
2774               if (TARGET_UPDATE
2775                   && (rc == RELOAD_REG_GPR || rc == RELOAD_REG_FPR)
2776                   && msize <= 8
2777                   && !VECTOR_MODE_P (m2)
2778                   && !FLOAT128_VECTOR_P (m2)
2779                   && !complex_p
2780                   && (m != E_DFmode || !TARGET_VSX)
2781                   && (m != E_SFmode || !TARGET_P8_VECTOR)
2782                   && !small_int_vsx_p)
2783                 {
2784                   addr_mask |= RELOAD_REG_PRE_INCDEC;
2785
2786                   /* PRE_MODIFY is more restricted than PRE_INC/PRE_DEC in that
2787                      we don't allow PRE_MODIFY for some multi-register
2788                      operations.  */
2789                   switch (m)
2790                     {
2791                     default:
2792                       addr_mask |= RELOAD_REG_PRE_MODIFY;
2793                       break;
2794
2795                     case E_DImode:
2796                       if (TARGET_POWERPC64)
2797                         addr_mask |= RELOAD_REG_PRE_MODIFY;
2798                       break;
2799
2800                     case E_DFmode:
2801                     case E_DDmode:
2802                       if (TARGET_HARD_FLOAT)
2803                         addr_mask |= RELOAD_REG_PRE_MODIFY;
2804                       break;
2805                     }
2806                 }
2807             }
2808
2809           /* GPR and FPR registers can do REG+OFFSET addressing, except
2810              possibly for SDmode.  ISA 3.0 (i.e. power9) adds D-form addressing
2811              for 64-bit scalars and 32-bit SFmode to altivec registers.  */
2812           if ((addr_mask != 0) && !indexed_only_p
2813               && msize <= 8
2814               && (rc == RELOAD_REG_GPR
2815                   || ((msize == 8 || m2 == SFmode)
2816                       && (rc == RELOAD_REG_FPR
2817                           || (rc == RELOAD_REG_VMX && TARGET_P9_VECTOR)))))
2818             addr_mask |= RELOAD_REG_OFFSET;
2819
2820           /* VSX registers can do REG+OFFSET addresssing if ISA 3.0
2821              instructions are enabled.  The offset for 128-bit VSX registers is
2822              only 12-bits.  While GPRs can handle the full offset range, VSX
2823              registers can only handle the restricted range.  */
2824           else if ((addr_mask != 0) && !indexed_only_p
2825                    && msize == 16 && TARGET_P9_VECTOR
2826                    && (ALTIVEC_OR_VSX_VECTOR_MODE (m2)
2827                        || (m2 == TImode && TARGET_VSX)))
2828             {
2829               addr_mask |= RELOAD_REG_OFFSET;
2830               if (rc == RELOAD_REG_FPR || rc == RELOAD_REG_VMX)
2831                 addr_mask |= RELOAD_REG_QUAD_OFFSET;
2832             }
2833
2834           /* VMX registers can do (REG & -16) and ((REG+REG) & -16)
2835              addressing on 128-bit types.  */
2836           if (rc == RELOAD_REG_VMX && msize == 16
2837               && (addr_mask & RELOAD_REG_VALID) != 0)
2838             addr_mask |= RELOAD_REG_AND_M16;
2839
2840           reg_addr[m].addr_mask[rc] = addr_mask;
2841           any_addr_mask |= addr_mask;
2842         }
2843
2844       reg_addr[m].addr_mask[RELOAD_REG_ANY] = any_addr_mask;
2845     }
2846 }
2847
2848 \f
2849 /* Initialize the various global tables that are based on register size.  */
2850 static void
2851 rs6000_init_hard_regno_mode_ok (bool global_init_p)
2852 {
2853   ssize_t r, m, c;
2854   int align64;
2855   int align32;
2856
2857   /* Precalculate REGNO_REG_CLASS.  */
2858   rs6000_regno_regclass[0] = GENERAL_REGS;
2859   for (r = 1; r < 32; ++r)
2860     rs6000_regno_regclass[r] = BASE_REGS;
2861
2862   for (r = 32; r < 64; ++r)
2863     rs6000_regno_regclass[r] = FLOAT_REGS;
2864
2865   for (r = 64; HARD_REGISTER_NUM_P (r); ++r)
2866     rs6000_regno_regclass[r] = NO_REGS;
2867
2868   for (r = FIRST_ALTIVEC_REGNO; r <= LAST_ALTIVEC_REGNO; ++r)
2869     rs6000_regno_regclass[r] = ALTIVEC_REGS;
2870
2871   rs6000_regno_regclass[CR0_REGNO] = CR0_REGS;
2872   for (r = CR1_REGNO; r <= CR7_REGNO; ++r)
2873     rs6000_regno_regclass[r] = CR_REGS;
2874
2875   rs6000_regno_regclass[LR_REGNO] = LINK_REGS;
2876   rs6000_regno_regclass[CTR_REGNO] = CTR_REGS;
2877   rs6000_regno_regclass[CA_REGNO] = NO_REGS;
2878   rs6000_regno_regclass[VRSAVE_REGNO] = VRSAVE_REGS;
2879   rs6000_regno_regclass[VSCR_REGNO] = VRSAVE_REGS;
2880   rs6000_regno_regclass[ARG_POINTER_REGNUM] = BASE_REGS;
2881   rs6000_regno_regclass[FRAME_POINTER_REGNUM] = BASE_REGS;
2882
2883   /* Precalculate register class to simpler reload register class.  We don't
2884      need all of the register classes that are combinations of different
2885      classes, just the simple ones that have constraint letters.  */
2886   for (c = 0; c < N_REG_CLASSES; c++)
2887     reg_class_to_reg_type[c] = NO_REG_TYPE;
2888
2889   reg_class_to_reg_type[(int)GENERAL_REGS] = GPR_REG_TYPE;
2890   reg_class_to_reg_type[(int)BASE_REGS] = GPR_REG_TYPE;
2891   reg_class_to_reg_type[(int)VSX_REGS] = VSX_REG_TYPE;
2892   reg_class_to_reg_type[(int)VRSAVE_REGS] = SPR_REG_TYPE;
2893   reg_class_to_reg_type[(int)VSCR_REGS] = SPR_REG_TYPE;
2894   reg_class_to_reg_type[(int)LINK_REGS] = SPR_REG_TYPE;
2895   reg_class_to_reg_type[(int)CTR_REGS] = SPR_REG_TYPE;
2896   reg_class_to_reg_type[(int)LINK_OR_CTR_REGS] = SPR_REG_TYPE;
2897   reg_class_to_reg_type[(int)CR_REGS] = CR_REG_TYPE;
2898   reg_class_to_reg_type[(int)CR0_REGS] = CR_REG_TYPE;
2899
2900   if (TARGET_VSX)
2901     {
2902       reg_class_to_reg_type[(int)FLOAT_REGS] = VSX_REG_TYPE;
2903       reg_class_to_reg_type[(int)ALTIVEC_REGS] = VSX_REG_TYPE;
2904     }
2905   else
2906     {
2907       reg_class_to_reg_type[(int)FLOAT_REGS] = FPR_REG_TYPE;
2908       reg_class_to_reg_type[(int)ALTIVEC_REGS] = ALTIVEC_REG_TYPE;
2909     }
2910
2911   /* Precalculate the valid memory formats as well as the vector information,
2912      this must be set up before the rs6000_hard_regno_nregs_internal calls
2913      below.  */
2914   gcc_assert ((int)VECTOR_NONE == 0);
2915   memset ((void *) &rs6000_vector_unit[0], '\0', sizeof (rs6000_vector_unit));
2916   memset ((void *) &rs6000_vector_mem[0], '\0', sizeof (rs6000_vector_mem));
2917
2918   gcc_assert ((int)CODE_FOR_nothing == 0);
2919   memset ((void *) &reg_addr[0], '\0', sizeof (reg_addr));
2920
2921   gcc_assert ((int)NO_REGS == 0);
2922   memset ((void *) &rs6000_constraints[0], '\0', sizeof (rs6000_constraints));
2923
2924   /* The VSX hardware allows native alignment for vectors, but control whether the compiler
2925      believes it can use native alignment or still uses 128-bit alignment.  */
2926   if (TARGET_VSX && !TARGET_VSX_ALIGN_128)
2927     {
2928       align64 = 64;
2929       align32 = 32;
2930     }
2931   else
2932     {
2933       align64 = 128;
2934       align32 = 128;
2935     }
2936
2937   /* KF mode (IEEE 128-bit in VSX registers).  We do not have arithmetic, so
2938      only set the memory modes.  Include TFmode if -mabi=ieeelongdouble.  */
2939   if (TARGET_FLOAT128_TYPE)
2940     {
2941       rs6000_vector_mem[KFmode] = VECTOR_VSX;
2942       rs6000_vector_align[KFmode] = 128;
2943
2944       if (FLOAT128_IEEE_P (TFmode))
2945         {
2946           rs6000_vector_mem[TFmode] = VECTOR_VSX;
2947           rs6000_vector_align[TFmode] = 128;
2948         }
2949     }
2950
2951   /* V2DF mode, VSX only.  */
2952   if (TARGET_VSX)
2953     {
2954       rs6000_vector_unit[V2DFmode] = VECTOR_VSX;
2955       rs6000_vector_mem[V2DFmode] = VECTOR_VSX;
2956       rs6000_vector_align[V2DFmode] = align64;
2957     }
2958
2959   /* V4SF mode, either VSX or Altivec.  */
2960   if (TARGET_VSX)
2961     {
2962       rs6000_vector_unit[V4SFmode] = VECTOR_VSX;
2963       rs6000_vector_mem[V4SFmode] = VECTOR_VSX;
2964       rs6000_vector_align[V4SFmode] = align32;
2965     }
2966   else if (TARGET_ALTIVEC)
2967     {
2968       rs6000_vector_unit[V4SFmode] = VECTOR_ALTIVEC;
2969       rs6000_vector_mem[V4SFmode] = VECTOR_ALTIVEC;
2970       rs6000_vector_align[V4SFmode] = align32;
2971     }
2972
2973   /* V16QImode, V8HImode, V4SImode are Altivec only, but possibly do VSX loads
2974      and stores. */
2975   if (TARGET_ALTIVEC)
2976     {
2977       rs6000_vector_unit[V4SImode] = VECTOR_ALTIVEC;
2978       rs6000_vector_unit[V8HImode] = VECTOR_ALTIVEC;
2979       rs6000_vector_unit[V16QImode] = VECTOR_ALTIVEC;
2980       rs6000_vector_align[V4SImode] = align32;
2981       rs6000_vector_align[V8HImode] = align32;
2982       rs6000_vector_align[V16QImode] = align32;
2983
2984       if (TARGET_VSX)
2985         {
2986           rs6000_vector_mem[V4SImode] = VECTOR_VSX;
2987           rs6000_vector_mem[V8HImode] = VECTOR_VSX;
2988           rs6000_vector_mem[V16QImode] = VECTOR_VSX;
2989         }
2990       else
2991         {
2992           rs6000_vector_mem[V4SImode] = VECTOR_ALTIVEC;
2993           rs6000_vector_mem[V8HImode] = VECTOR_ALTIVEC;
2994           rs6000_vector_mem[V16QImode] = VECTOR_ALTIVEC;
2995         }
2996     }
2997
2998   /* V2DImode, full mode depends on ISA 2.07 vector mode.  Allow under VSX to
2999      do insert/splat/extract.  Altivec doesn't have 64-bit integer support.  */
3000   if (TARGET_VSX)
3001     {
3002       rs6000_vector_mem[V2DImode] = VECTOR_VSX;
3003       rs6000_vector_unit[V2DImode]
3004         = (TARGET_P8_VECTOR) ? VECTOR_P8_VECTOR : VECTOR_NONE;
3005       rs6000_vector_align[V2DImode] = align64;
3006
3007       rs6000_vector_mem[V1TImode] = VECTOR_VSX;
3008       rs6000_vector_unit[V1TImode]
3009         = (TARGET_P8_VECTOR) ? VECTOR_P8_VECTOR : VECTOR_NONE;
3010       rs6000_vector_align[V1TImode] = 128;
3011     }
3012
3013   /* DFmode, see if we want to use the VSX unit.  Memory is handled
3014      differently, so don't set rs6000_vector_mem.  */
3015   if (TARGET_VSX)
3016     {
3017       rs6000_vector_unit[DFmode] = VECTOR_VSX;
3018       rs6000_vector_align[DFmode] = 64;
3019     }
3020
3021   /* SFmode, see if we want to use the VSX unit.  */
3022   if (TARGET_P8_VECTOR)
3023     {
3024       rs6000_vector_unit[SFmode] = VECTOR_VSX;
3025       rs6000_vector_align[SFmode] = 32;
3026     }
3027
3028   /* Allow TImode in VSX register and set the VSX memory macros.  */
3029   if (TARGET_VSX)
3030     {
3031       rs6000_vector_mem[TImode] = VECTOR_VSX;
3032       rs6000_vector_align[TImode] = align64;
3033     }
3034
3035   /* Register class constraints for the constraints that depend on compile
3036      switches. When the VSX code was added, different constraints were added
3037      based on the type (DFmode, V2DFmode, V4SFmode).  For the vector types, all
3038      of the VSX registers are used.  The register classes for scalar floating
3039      point types is set, based on whether we allow that type into the upper
3040      (Altivec) registers.  GCC has register classes to target the Altivec
3041      registers for load/store operations, to select using a VSX memory
3042      operation instead of the traditional floating point operation.  The
3043      constraints are:
3044
3045         d  - Register class to use with traditional DFmode instructions.
3046         f  - Register class to use with traditional SFmode instructions.
3047         v  - Altivec register.
3048         wa - Any VSX register.
3049         wc - Reserved to represent individual CR bits (used in LLVM).
3050         wn - always NO_REGS.
3051         wr - GPR if 64-bit mode is permitted.
3052         wx - Float register if we can do 32-bit int stores.  */
3053
3054   if (TARGET_HARD_FLOAT)
3055     {
3056       rs6000_constraints[RS6000_CONSTRAINT_f] = FLOAT_REGS;     /* SFmode  */
3057       rs6000_constraints[RS6000_CONSTRAINT_d] = FLOAT_REGS;     /* DFmode  */
3058     }
3059
3060   if (TARGET_VSX)
3061     rs6000_constraints[RS6000_CONSTRAINT_wa] = VSX_REGS;
3062
3063   /* Add conditional constraints based on various options, to allow us to
3064      collapse multiple insn patterns.  */
3065   if (TARGET_ALTIVEC)
3066     rs6000_constraints[RS6000_CONSTRAINT_v] = ALTIVEC_REGS;
3067
3068   if (TARGET_POWERPC64)
3069     {
3070       rs6000_constraints[RS6000_CONSTRAINT_wr] = GENERAL_REGS;
3071       rs6000_constraints[RS6000_CONSTRAINT_wA] = BASE_REGS;
3072     }
3073
3074   if (TARGET_STFIWX)
3075     rs6000_constraints[RS6000_CONSTRAINT_wx] = FLOAT_REGS;      /* DImode  */
3076
3077   /* Support for new direct moves (ISA 3.0 + 64bit).  */
3078   if (TARGET_DIRECT_MOVE_128)
3079     rs6000_constraints[RS6000_CONSTRAINT_we] = VSX_REGS;
3080
3081   /* Set up the reload helper and direct move functions.  */
3082   if (TARGET_VSX || TARGET_ALTIVEC)
3083     {
3084       if (TARGET_64BIT)
3085         {
3086           reg_addr[V16QImode].reload_store = CODE_FOR_reload_v16qi_di_store;
3087           reg_addr[V16QImode].reload_load  = CODE_FOR_reload_v16qi_di_load;
3088           reg_addr[V8HImode].reload_store  = CODE_FOR_reload_v8hi_di_store;
3089           reg_addr[V8HImode].reload_load   = CODE_FOR_reload_v8hi_di_load;
3090           reg_addr[V4SImode].reload_store  = CODE_FOR_reload_v4si_di_store;
3091           reg_addr[V4SImode].reload_load   = CODE_FOR_reload_v4si_di_load;
3092           reg_addr[V2DImode].reload_store  = CODE_FOR_reload_v2di_di_store;
3093           reg_addr[V2DImode].reload_load   = CODE_FOR_reload_v2di_di_load;
3094           reg_addr[V1TImode].reload_store  = CODE_FOR_reload_v1ti_di_store;
3095           reg_addr[V1TImode].reload_load   = CODE_FOR_reload_v1ti_di_load;
3096           reg_addr[V4SFmode].reload_store  = CODE_FOR_reload_v4sf_di_store;
3097           reg_addr[V4SFmode].reload_load   = CODE_FOR_reload_v4sf_di_load;
3098           reg_addr[V2DFmode].reload_store  = CODE_FOR_reload_v2df_di_store;
3099           reg_addr[V2DFmode].reload_load   = CODE_FOR_reload_v2df_di_load;
3100           reg_addr[DFmode].reload_store    = CODE_FOR_reload_df_di_store;
3101           reg_addr[DFmode].reload_load     = CODE_FOR_reload_df_di_load;
3102           reg_addr[DDmode].reload_store    = CODE_FOR_reload_dd_di_store;
3103           reg_addr[DDmode].reload_load     = CODE_FOR_reload_dd_di_load;
3104           reg_addr[SFmode].reload_store    = CODE_FOR_reload_sf_di_store;
3105           reg_addr[SFmode].reload_load     = CODE_FOR_reload_sf_di_load;
3106
3107           if (FLOAT128_VECTOR_P (KFmode))
3108             {
3109               reg_addr[KFmode].reload_store = CODE_FOR_reload_kf_di_store;
3110               reg_addr[KFmode].reload_load  = CODE_FOR_reload_kf_di_load;
3111             }
3112
3113           if (FLOAT128_VECTOR_P (TFmode))
3114             {
3115               reg_addr[TFmode].reload_store = CODE_FOR_reload_tf_di_store;
3116               reg_addr[TFmode].reload_load  = CODE_FOR_reload_tf_di_load;
3117             }
3118
3119           /* Only provide a reload handler for SDmode if lfiwzx/stfiwx are
3120              available.  */
3121           if (TARGET_NO_SDMODE_STACK)
3122             {
3123               reg_addr[SDmode].reload_store = CODE_FOR_reload_sd_di_store;
3124               reg_addr[SDmode].reload_load  = CODE_FOR_reload_sd_di_load;
3125             }
3126
3127           if (TARGET_VSX)
3128             {
3129               reg_addr[TImode].reload_store  = CODE_FOR_reload_ti_di_store;
3130               reg_addr[TImode].reload_load   = CODE_FOR_reload_ti_di_load;
3131             }
3132
3133           if (TARGET_DIRECT_MOVE && !TARGET_DIRECT_MOVE_128)
3134             {
3135               reg_addr[TImode].reload_gpr_vsx    = CODE_FOR_reload_gpr_from_vsxti;
3136               reg_addr[V1TImode].reload_gpr_vsx  = CODE_FOR_reload_gpr_from_vsxv1ti;
3137               reg_addr[V2DFmode].reload_gpr_vsx  = CODE_FOR_reload_gpr_from_vsxv2df;
3138               reg_addr[V2DImode].reload_gpr_vsx  = CODE_FOR_reload_gpr_from_vsxv2di;
3139               reg_addr[V4SFmode].reload_gpr_vsx  = CODE_FOR_reload_gpr_from_vsxv4sf;
3140               reg_addr[V4SImode].reload_gpr_vsx  = CODE_FOR_reload_gpr_from_vsxv4si;
3141               reg_addr[V8HImode].reload_gpr_vsx  = CODE_FOR_reload_gpr_from_vsxv8hi;
3142               reg_addr[V16QImode].reload_gpr_vsx = CODE_FOR_reload_gpr_from_vsxv16qi;
3143               reg_addr[SFmode].reload_gpr_vsx    = CODE_FOR_reload_gpr_from_vsxsf;
3144
3145               reg_addr[TImode].reload_vsx_gpr    = CODE_FOR_reload_vsx_from_gprti;
3146               reg_addr[V1TImode].reload_vsx_gpr  = CODE_FOR_reload_vsx_from_gprv1ti;
3147               reg_addr[V2DFmode].reload_vsx_gpr  = CODE_FOR_reload_vsx_from_gprv2df;
3148               reg_addr[V2DImode].reload_vsx_gpr  = CODE_FOR_reload_vsx_from_gprv2di;
3149               reg_addr[V4SFmode].reload_vsx_gpr  = CODE_FOR_reload_vsx_from_gprv4sf;
3150               reg_addr[V4SImode].reload_vsx_gpr  = CODE_FOR_reload_vsx_from_gprv4si;
3151               reg_addr[V8HImode].reload_vsx_gpr  = CODE_FOR_reload_vsx_from_gprv8hi;
3152               reg_addr[V16QImode].reload_vsx_gpr = CODE_FOR_reload_vsx_from_gprv16qi;
3153               reg_addr[SFmode].reload_vsx_gpr    = CODE_FOR_reload_vsx_from_gprsf;
3154
3155               if (FLOAT128_VECTOR_P (KFmode))
3156                 {
3157                   reg_addr[KFmode].reload_gpr_vsx = CODE_FOR_reload_gpr_from_vsxkf;
3158                   reg_addr[KFmode].reload_vsx_gpr = CODE_FOR_reload_vsx_from_gprkf;
3159                 }
3160
3161               if (FLOAT128_VECTOR_P (TFmode))
3162                 {
3163                   reg_addr[TFmode].reload_gpr_vsx = CODE_FOR_reload_gpr_from_vsxtf;
3164                   reg_addr[TFmode].reload_vsx_gpr = CODE_FOR_reload_vsx_from_gprtf;
3165                 }
3166             }
3167         }
3168       else
3169         {
3170           reg_addr[V16QImode].reload_store = CODE_FOR_reload_v16qi_si_store;
3171           reg_addr[V16QImode].reload_load  = CODE_FOR_reload_v16qi_si_load;
3172           reg_addr[V8HImode].reload_store  = CODE_FOR_reload_v8hi_si_store;
3173           reg_addr[V8HImode].reload_load   = CODE_FOR_reload_v8hi_si_load;
3174           reg_addr[V4SImode].reload_store  = CODE_FOR_reload_v4si_si_store;
3175           reg_addr[V4SImode].reload_load   = CODE_FOR_reload_v4si_si_load;
3176           reg_addr[V2DImode].reload_store  = CODE_FOR_reload_v2di_si_store;
3177           reg_addr[V2DImode].reload_load   = CODE_FOR_reload_v2di_si_load;
3178           reg_addr[V1TImode].reload_store  = CODE_FOR_reload_v1ti_si_store;
3179           reg_addr[V1TImode].reload_load   = CODE_FOR_reload_v1ti_si_load;
3180           reg_addr[V4SFmode].reload_store  = CODE_FOR_reload_v4sf_si_store;
3181           reg_addr[V4SFmode].reload_load   = CODE_FOR_reload_v4sf_si_load;
3182           reg_addr[V2DFmode].reload_store  = CODE_FOR_reload_v2df_si_store;
3183           reg_addr[V2DFmode].reload_load   = CODE_FOR_reload_v2df_si_load;
3184           reg_addr[DFmode].reload_store    = CODE_FOR_reload_df_si_store;
3185           reg_addr[DFmode].reload_load     = CODE_FOR_reload_df_si_load;
3186           reg_addr[DDmode].reload_store    = CODE_FOR_reload_dd_si_store;
3187           reg_addr[DDmode].reload_load     = CODE_FOR_reload_dd_si_load;
3188           reg_addr[SFmode].reload_store    = CODE_FOR_reload_sf_si_store;
3189           reg_addr[SFmode].reload_load     = CODE_FOR_reload_sf_si_load;
3190
3191           if (FLOAT128_VECTOR_P (KFmode))
3192             {
3193               reg_addr[KFmode].reload_store = CODE_FOR_reload_kf_si_store;
3194               reg_addr[KFmode].reload_load  = CODE_FOR_reload_kf_si_load;
3195             }
3196
3197           if (FLOAT128_IEEE_P (TFmode))
3198             {
3199               reg_addr[TFmode].reload_store = CODE_FOR_reload_tf_si_store;
3200               reg_addr[TFmode].reload_load  = CODE_FOR_reload_tf_si_load;
3201             }
3202
3203           /* Only provide a reload handler for SDmode if lfiwzx/stfiwx are
3204              available.  */
3205           if (TARGET_NO_SDMODE_STACK)
3206             {
3207               reg_addr[SDmode].reload_store = CODE_FOR_reload_sd_si_store;
3208               reg_addr[SDmode].reload_load  = CODE_FOR_reload_sd_si_load;
3209             }
3210
3211           if (TARGET_VSX)
3212             {
3213               reg_addr[TImode].reload_store  = CODE_FOR_reload_ti_si_store;
3214               reg_addr[TImode].reload_load   = CODE_FOR_reload_ti_si_load;
3215             }
3216
3217           if (TARGET_DIRECT_MOVE)
3218             {
3219               reg_addr[DImode].reload_fpr_gpr = CODE_FOR_reload_fpr_from_gprdi;
3220               reg_addr[DDmode].reload_fpr_gpr = CODE_FOR_reload_fpr_from_gprdd;
3221               reg_addr[DFmode].reload_fpr_gpr = CODE_FOR_reload_fpr_from_gprdf;
3222             }
3223         }
3224
3225       reg_addr[DFmode].scalar_in_vmx_p = true;
3226       reg_addr[DImode].scalar_in_vmx_p = true;
3227
3228       if (TARGET_P8_VECTOR)
3229         {
3230           reg_addr[SFmode].scalar_in_vmx_p = true;
3231           reg_addr[SImode].scalar_in_vmx_p = true;
3232
3233           if (TARGET_P9_VECTOR)
3234             {
3235               reg_addr[HImode].scalar_in_vmx_p = true;
3236               reg_addr[QImode].scalar_in_vmx_p = true;
3237             }
3238         }
3239     }
3240
3241   /* Precalculate HARD_REGNO_NREGS.  */
3242   for (r = 0; HARD_REGISTER_NUM_P (r); ++r)
3243     for (m = 0; m < NUM_MACHINE_MODES; ++m)
3244       rs6000_hard_regno_nregs[m][r]
3245         = rs6000_hard_regno_nregs_internal (r, (machine_mode) m);
3246
3247   /* Precalculate TARGET_HARD_REGNO_MODE_OK.  */
3248   for (r = 0; HARD_REGISTER_NUM_P (r); ++r)
3249     for (m = 0; m < NUM_MACHINE_MODES; ++m)
3250       rs6000_hard_regno_mode_ok_p[m][r]
3251         = rs6000_hard_regno_mode_ok_uncached (r, (machine_mode) m);
3252
3253   /* Precalculate CLASS_MAX_NREGS sizes.  */
3254   for (c = 0; c < LIM_REG_CLASSES; ++c)
3255     {
3256       int reg_size;
3257
3258       if (TARGET_VSX && VSX_REG_CLASS_P (c))
3259         reg_size = UNITS_PER_VSX_WORD;
3260
3261       else if (c == ALTIVEC_REGS)
3262         reg_size = UNITS_PER_ALTIVEC_WORD;
3263
3264       else if (c == FLOAT_REGS)
3265         reg_size = UNITS_PER_FP_WORD;
3266
3267       else
3268         reg_size = UNITS_PER_WORD;
3269
3270       for (m = 0; m < NUM_MACHINE_MODES; ++m)
3271         {
3272           machine_mode m2 = (machine_mode)m;
3273           int reg_size2 = reg_size;
3274
3275           /* TDmode & IBM 128-bit floating point always takes 2 registers, even
3276              in VSX.  */
3277           if (TARGET_VSX && VSX_REG_CLASS_P (c) && FLOAT128_2REG_P (m))
3278             reg_size2 = UNITS_PER_FP_WORD;
3279
3280           rs6000_class_max_nregs[m][c]
3281             = (GET_MODE_SIZE (m2) + reg_size2 - 1) / reg_size2;
3282         }
3283     }
3284
3285   /* Calculate which modes to automatically generate code to use a the
3286      reciprocal divide and square root instructions.  In the future, possibly
3287      automatically generate the instructions even if the user did not specify
3288      -mrecip.  The older machines double precision reciprocal sqrt estimate is
3289      not accurate enough.  */
3290   memset (rs6000_recip_bits, 0, sizeof (rs6000_recip_bits));
3291   if (TARGET_FRES)
3292     rs6000_recip_bits[SFmode] = RS6000_RECIP_MASK_HAVE_RE;
3293   if (TARGET_FRE)
3294     rs6000_recip_bits[DFmode] = RS6000_RECIP_MASK_HAVE_RE;
3295   if (VECTOR_UNIT_ALTIVEC_OR_VSX_P (V4SFmode))
3296     rs6000_recip_bits[V4SFmode] = RS6000_RECIP_MASK_HAVE_RE;
3297   if (VECTOR_UNIT_VSX_P (V2DFmode))
3298     rs6000_recip_bits[V2DFmode] = RS6000_RECIP_MASK_HAVE_RE;
3299
3300   if (TARGET_FRSQRTES)
3301     rs6000_recip_bits[SFmode] |= RS6000_RECIP_MASK_HAVE_RSQRTE;
3302   if (TARGET_FRSQRTE)
3303     rs6000_recip_bits[DFmode] |= RS6000_RECIP_MASK_HAVE_RSQRTE;
3304   if (VECTOR_UNIT_ALTIVEC_OR_VSX_P (V4SFmode))
3305     rs6000_recip_bits[V4SFmode] |= RS6000_RECIP_MASK_HAVE_RSQRTE;
3306   if (VECTOR_UNIT_VSX_P (V2DFmode))
3307     rs6000_recip_bits[V2DFmode] |= RS6000_RECIP_MASK_HAVE_RSQRTE;
3308
3309   if (rs6000_recip_control)
3310     {
3311       if (!flag_finite_math_only)
3312         warning (0, "%qs requires %qs or %qs", "-mrecip", "-ffinite-math",
3313                  "-ffast-math");
3314       if (flag_trapping_math)
3315         warning (0, "%qs requires %qs or %qs", "-mrecip",
3316                  "-fno-trapping-math", "-ffast-math");
3317       if (!flag_reciprocal_math)
3318         warning (0, "%qs requires %qs or %qs", "-mrecip", "-freciprocal-math",
3319                  "-ffast-math");
3320       if (flag_finite_math_only && !flag_trapping_math && flag_reciprocal_math)
3321         {
3322           if (RS6000_RECIP_HAVE_RE_P (SFmode)
3323               && (rs6000_recip_control & RECIP_SF_DIV) != 0)
3324             rs6000_recip_bits[SFmode] |= RS6000_RECIP_MASK_AUTO_RE;
3325
3326           if (RS6000_RECIP_HAVE_RE_P (DFmode)
3327               && (rs6000_recip_control & RECIP_DF_DIV) != 0)
3328             rs6000_recip_bits[DFmode] |= RS6000_RECIP_MASK_AUTO_RE;
3329
3330           if (RS6000_RECIP_HAVE_RE_P (V4SFmode)
3331               && (rs6000_recip_control & RECIP_V4SF_DIV) != 0)
3332             rs6000_recip_bits[V4SFmode] |= RS6000_RECIP_MASK_AUTO_RE;
3333
3334           if (RS6000_RECIP_HAVE_RE_P (V2DFmode)
3335               && (rs6000_recip_control & RECIP_V2DF_DIV) != 0)
3336             rs6000_recip_bits[V2DFmode] |= RS6000_RECIP_MASK_AUTO_RE;
3337
3338           if (RS6000_RECIP_HAVE_RSQRTE_P (SFmode)
3339               && (rs6000_recip_control & RECIP_SF_RSQRT) != 0)
3340             rs6000_recip_bits[SFmode] |= RS6000_RECIP_MASK_AUTO_RSQRTE;
3341
3342           if (RS6000_RECIP_HAVE_RSQRTE_P (DFmode)
3343               && (rs6000_recip_control & RECIP_DF_RSQRT) != 0)
3344             rs6000_recip_bits[DFmode] |= RS6000_RECIP_MASK_AUTO_RSQRTE;
3345
3346           if (RS6000_RECIP_HAVE_RSQRTE_P (V4SFmode)
3347               && (rs6000_recip_control & RECIP_V4SF_RSQRT) != 0)
3348             rs6000_recip_bits[V4SFmode] |= RS6000_RECIP_MASK_AUTO_RSQRTE;
3349
3350           if (RS6000_RECIP_HAVE_RSQRTE_P (V2DFmode)
3351               && (rs6000_recip_control & RECIP_V2DF_RSQRT) != 0)
3352             rs6000_recip_bits[V2DFmode] |= RS6000_RECIP_MASK_AUTO_RSQRTE;
3353         }
3354     }
3355
3356   /* Update the addr mask bits in reg_addr to help secondary reload and go if
3357      legitimate address support to figure out the appropriate addressing to
3358      use.  */
3359   rs6000_setup_reg_addr_masks ();
3360
3361   if (global_init_p || TARGET_DEBUG_TARGET)
3362     {
3363       if (TARGET_DEBUG_REG)
3364         rs6000_debug_reg_global ();
3365
3366       if (TARGET_DEBUG_COST || TARGET_DEBUG_REG)
3367         fprintf (stderr,
3368                  "SImode variable mult cost       = %d\n"
3369                  "SImode constant mult cost       = %d\n"
3370                  "SImode short constant mult cost = %d\n"
3371                  "DImode multipliciation cost     = %d\n"
3372                  "SImode division cost            = %d\n"
3373                  "DImode division cost            = %d\n"
3374                  "Simple fp operation cost        = %d\n"
3375                  "DFmode multiplication cost      = %d\n"
3376                  "SFmode division cost            = %d\n"
3377                  "DFmode division cost            = %d\n"
3378                  "cache line size                 = %d\n"
3379                  "l1 cache size                   = %d\n"
3380                  "l2 cache size                   = %d\n"
3381                  "simultaneous prefetches         = %d\n"
3382                  "\n",
3383                  rs6000_cost->mulsi,
3384                  rs6000_cost->mulsi_const,
3385                  rs6000_cost->mulsi_const9,
3386                  rs6000_cost->muldi,
3387                  rs6000_cost->divsi,
3388                  rs6000_cost->divdi,
3389                  rs6000_cost->fp,
3390                  rs6000_cost->dmul,
3391                  rs6000_cost->sdiv,
3392                  rs6000_cost->ddiv,
3393                  rs6000_cost->cache_line_size,
3394                  rs6000_cost->l1_cache_size,
3395                  rs6000_cost->l2_cache_size,
3396                  rs6000_cost->simultaneous_prefetches);
3397     }
3398 }
3399
3400 #if TARGET_MACHO
3401 /* The Darwin version of SUBTARGET_OVERRIDE_OPTIONS.  */
3402
3403 static void
3404 darwin_rs6000_override_options (void)
3405 {
3406   /* The Darwin ABI always includes AltiVec, can't be (validly) turned
3407      off.  */
3408   rs6000_altivec_abi = 1;
3409   TARGET_ALTIVEC_VRSAVE = 1;
3410   rs6000_current_abi = ABI_DARWIN;
3411
3412   if (DEFAULT_ABI == ABI_DARWIN
3413       && TARGET_64BIT)
3414       darwin_one_byte_bool = 1;
3415
3416   if (TARGET_64BIT && ! TARGET_POWERPC64)
3417     {
3418       rs6000_isa_flags |= OPTION_MASK_POWERPC64;
3419       warning (0, "%qs requires PowerPC64 architecture, enabling", "-m64");
3420     }
3421
3422   /* The linkers [ld64] that support 64Bit do not need the JBSR longcall
3423      optimisation, and will not work with the most generic case (where the
3424      symbol is undefined external, but there is no symbl stub).  */
3425   if (TARGET_64BIT)
3426     rs6000_default_long_calls = 0;
3427
3428   /* ld_classic is (so far) still used for kernel (static) code, and supports
3429      the JBSR longcall / branch islands.  */
3430   if (flag_mkernel)
3431     {
3432       rs6000_default_long_calls = 1;
3433
3434       /* Allow a kext author to do -mkernel -mhard-float.  */
3435       if (! (rs6000_isa_flags_explicit & OPTION_MASK_SOFT_FLOAT))
3436         rs6000_isa_flags |= OPTION_MASK_SOFT_FLOAT;
3437     }
3438
3439   /* Make -m64 imply -maltivec.  Darwin's 64-bit ABI includes
3440      Altivec.  */
3441   if (!flag_mkernel && !flag_apple_kext
3442       && TARGET_64BIT
3443       && ! (rs6000_isa_flags_explicit & OPTION_MASK_ALTIVEC))
3444     rs6000_isa_flags |= OPTION_MASK_ALTIVEC;
3445
3446   /* Unless the user (not the configurer) has explicitly overridden
3447      it with -mcpu=G3 or -mno-altivec, then 10.5+ targets default to
3448      G4 unless targeting the kernel.  */
3449   if (!flag_mkernel
3450       && !flag_apple_kext
3451       && strverscmp (darwin_macosx_version_min, "10.5") >= 0
3452       && ! (rs6000_isa_flags_explicit & OPTION_MASK_ALTIVEC)
3453       && ! global_options_set.x_rs6000_cpu_index)
3454     {
3455       rs6000_isa_flags |= OPTION_MASK_ALTIVEC;
3456     }
3457 }
3458 #endif
3459
3460 /* If not otherwise specified by a target, make 'long double' equivalent to
3461    'double'.  */
3462
3463 #ifndef RS6000_DEFAULT_LONG_DOUBLE_SIZE
3464 #define RS6000_DEFAULT_LONG_DOUBLE_SIZE 64
3465 #endif
3466
3467 /* Return the builtin mask of the various options used that could affect which
3468    builtins were used.  In the past we used target_flags, but we've run out of
3469    bits, and some options are no longer in target_flags.  */
3470
3471 HOST_WIDE_INT
3472 rs6000_builtin_mask_calculate (void)
3473 {
3474   return (((TARGET_ALTIVEC)                 ? RS6000_BTM_ALTIVEC   : 0)
3475           | ((TARGET_CMPB)                  ? RS6000_BTM_CMPB      : 0)
3476           | ((TARGET_VSX)                   ? RS6000_BTM_VSX       : 0)
3477           | ((TARGET_FRE)                   ? RS6000_BTM_FRE       : 0)
3478           | ((TARGET_FRES)                  ? RS6000_BTM_FRES      : 0)
3479           | ((TARGET_FRSQRTE)               ? RS6000_BTM_FRSQRTE   : 0)
3480           | ((TARGET_FRSQRTES)              ? RS6000_BTM_FRSQRTES  : 0)
3481           | ((TARGET_POPCNTD)               ? RS6000_BTM_POPCNTD   : 0)
3482           | ((rs6000_cpu == PROCESSOR_CELL) ? RS6000_BTM_CELL      : 0)
3483           | ((TARGET_P8_VECTOR)             ? RS6000_BTM_P8_VECTOR : 0)
3484           | ((TARGET_P9_VECTOR)             ? RS6000_BTM_P9_VECTOR : 0)
3485           | ((TARGET_P9_MISC)               ? RS6000_BTM_P9_MISC   : 0)
3486           | ((TARGET_MODULO)                ? RS6000_BTM_MODULO    : 0)
3487           | ((TARGET_64BIT)                 ? RS6000_BTM_64BIT     : 0)
3488           | ((TARGET_POWERPC64)             ? RS6000_BTM_POWERPC64 : 0)
3489           | ((TARGET_CRYPTO)                ? RS6000_BTM_CRYPTO    : 0)
3490           | ((TARGET_HTM)                   ? RS6000_BTM_HTM       : 0)
3491           | ((TARGET_DFP)                   ? RS6000_BTM_DFP       : 0)
3492           | ((TARGET_HARD_FLOAT)            ? RS6000_BTM_HARD_FLOAT : 0)
3493           | ((TARGET_LONG_DOUBLE_128
3494               && TARGET_HARD_FLOAT
3495               && !TARGET_IEEEQUAD)          ? RS6000_BTM_LDBL128   : 0)
3496           | ((TARGET_FLOAT128_TYPE)         ? RS6000_BTM_FLOAT128  : 0)
3497           | ((TARGET_FLOAT128_HW)           ? RS6000_BTM_FLOAT128_HW : 0));
3498 }
3499
3500 /* Implement TARGET_MD_ASM_ADJUST.  All asm statements are considered
3501    to clobber the XER[CA] bit because clobbering that bit without telling
3502    the compiler worked just fine with versions of GCC before GCC 5, and
3503    breaking a lot of older code in ways that are hard to track down is
3504    not such a great idea.  */
3505
3506 static rtx_insn *
3507 rs6000_md_asm_adjust (vec<rtx> &/*outputs*/, vec<rtx> &/*inputs*/,
3508                       vec<const char *> &/*constraints*/,
3509                       vec<rtx> &clobbers, HARD_REG_SET &clobbered_regs)
3510 {
3511   clobbers.safe_push (gen_rtx_REG (SImode, CA_REGNO));
3512   SET_HARD_REG_BIT (clobbered_regs, CA_REGNO);
3513   return NULL;
3514 }
3515
3516 /* Override command line options.
3517
3518    Combine build-specific configuration information with options
3519    specified on the command line to set various state variables which
3520    influence code generation, optimization, and expansion of built-in
3521    functions.  Assure that command-line configuration preferences are
3522    compatible with each other and with the build configuration; issue
3523    warnings while adjusting configuration or error messages while
3524    rejecting configuration.
3525
3526    Upon entry to this function:
3527
3528      This function is called once at the beginning of
3529      compilation, and then again at the start and end of compiling
3530      each section of code that has a different configuration, as
3531      indicated, for example, by adding the
3532
3533        __attribute__((__target__("cpu=power9")))
3534
3535      qualifier to a function definition or, for example, by bracketing
3536      code between
3537
3538        #pragma GCC target("altivec")
3539
3540      and
3541
3542        #pragma GCC reset_options
3543
3544      directives.  Parameter global_init_p is true for the initial
3545      invocation, which initializes global variables, and false for all
3546      subsequent invocations.
3547
3548
3549      Various global state information is assumed to be valid.  This
3550      includes OPTION_TARGET_CPU_DEFAULT, representing the name of the
3551      default CPU specified at build configure time, TARGET_DEFAULT,
3552      representing the default set of option flags for the default
3553      target, and global_options_set.x_rs6000_isa_flags, representing
3554      which options were requested on the command line.
3555
3556    Upon return from this function:
3557
3558      rs6000_isa_flags_explicit has a non-zero bit for each flag that
3559      was set by name on the command line.  Additionally, if certain
3560      attributes are automatically enabled or disabled by this function
3561      in order to assure compatibility between options and
3562      configuration, the flags associated with those attributes are
3563      also set.  By setting these "explicit bits", we avoid the risk
3564      that other code might accidentally overwrite these particular
3565      attributes with "default values".
3566
3567      The various bits of rs6000_isa_flags are set to indicate the
3568      target options that have been selected for the most current
3569      compilation efforts.  This has the effect of also turning on the
3570      associated TARGET_XXX values since these are macros which are
3571      generally defined to test the corresponding bit of the
3572      rs6000_isa_flags variable.
3573
3574      The variable rs6000_builtin_mask is set to represent the target
3575      options for the most current compilation efforts, consistent with
3576      the current contents of rs6000_isa_flags.  This variable controls
3577      expansion of built-in functions.
3578
3579      Various other global variables and fields of global structures
3580      (over 50 in all) are initialized to reflect the desired options
3581      for the most current compilation efforts.  */
3582
3583 static bool
3584 rs6000_option_override_internal (bool global_init_p)
3585 {
3586   bool ret = true;
3587
3588   HOST_WIDE_INT set_masks;
3589   HOST_WIDE_INT ignore_masks;
3590   int cpu_index = -1;
3591   int tune_index;
3592   struct cl_target_option *main_target_opt
3593     = ((global_init_p || target_option_default_node == NULL)
3594        ? NULL : TREE_TARGET_OPTION (target_option_default_node));
3595
3596   /* Print defaults.  */
3597   if ((TARGET_DEBUG_REG || TARGET_DEBUG_TARGET) && global_init_p)
3598     rs6000_print_isa_options (stderr, 0, "TARGET_DEFAULT", TARGET_DEFAULT);
3599
3600   /* Remember the explicit arguments.  */
3601   if (global_init_p)
3602     rs6000_isa_flags_explicit = global_options_set.x_rs6000_isa_flags;
3603
3604   /* On 64-bit Darwin, power alignment is ABI-incompatible with some C
3605      library functions, so warn about it. The flag may be useful for
3606      performance studies from time to time though, so don't disable it
3607      entirely.  */
3608   if (global_options_set.x_rs6000_alignment_flags
3609       && rs6000_alignment_flags == MASK_ALIGN_POWER
3610       && DEFAULT_ABI == ABI_DARWIN
3611       && TARGET_64BIT)
3612     warning (0, "%qs is not supported for 64-bit Darwin;"
3613              " it is incompatible with the installed C and C++ libraries",
3614              "-malign-power");
3615
3616   /* Numerous experiment shows that IRA based loop pressure
3617      calculation works better for RTL loop invariant motion on targets
3618      with enough (>= 32) registers.  It is an expensive optimization.
3619      So it is on only for peak performance.  */
3620   if (optimize >= 3 && global_init_p
3621       && !global_options_set.x_flag_ira_loop_pressure)
3622     flag_ira_loop_pressure = 1;
3623
3624   /* -fsanitize=address needs to turn on -fasynchronous-unwind-tables in order
3625      for tracebacks to be complete but not if any -fasynchronous-unwind-tables
3626      options were already specified.  */
3627   if (flag_sanitize & SANITIZE_USER_ADDRESS
3628       && !global_options_set.x_flag_asynchronous_unwind_tables)
3629     flag_asynchronous_unwind_tables = 1;
3630
3631   /* -fvariable-expansion-in-unroller is a win for POWER whenever the
3632      loop unroller is active.  It is only checked during unrolling, so
3633      we can just set it on by default.  */
3634   if (!global_options_set.x_flag_variable_expansion_in_unroller)
3635     flag_variable_expansion_in_unroller = 1;
3636
3637   /* Set the pointer size.  */
3638   if (TARGET_64BIT)
3639     {
3640       rs6000_pmode = DImode;
3641       rs6000_pointer_size = 64;
3642     }
3643   else
3644     {
3645       rs6000_pmode = SImode;
3646       rs6000_pointer_size = 32;
3647     }
3648
3649   /* Some OSs don't support saving the high part of 64-bit registers on context
3650      switch.  Other OSs don't support saving Altivec registers.  On those OSs,
3651      we don't touch the OPTION_MASK_POWERPC64 or OPTION_MASK_ALTIVEC settings;
3652      if the user wants either, the user must explicitly specify them and we
3653      won't interfere with the user's specification.  */
3654
3655   set_masks = POWERPC_MASKS;
3656 #ifdef OS_MISSING_POWERPC64
3657   if (OS_MISSING_POWERPC64)
3658     set_masks &= ~OPTION_MASK_POWERPC64;
3659 #endif
3660 #ifdef OS_MISSING_ALTIVEC
3661   if (OS_MISSING_ALTIVEC)
3662     set_masks &= ~(OPTION_MASK_ALTIVEC | OPTION_MASK_VSX
3663                    | OTHER_VSX_VECTOR_MASKS);
3664 #endif
3665
3666   /* Don't override by the processor default if given explicitly.  */
3667   set_masks &= ~rs6000_isa_flags_explicit;
3668
3669   if (global_init_p && rs6000_dejagnu_cpu_index >= 0)
3670     rs6000_cpu_index = rs6000_dejagnu_cpu_index;
3671
3672   /* Process the -mcpu=<xxx> and -mtune=<xxx> argument.  If the user changed
3673      the cpu in a target attribute or pragma, but did not specify a tuning
3674      option, use the cpu for the tuning option rather than the option specified
3675      with -mtune on the command line.  Process a '--with-cpu' configuration
3676      request as an implicit --cpu.  */
3677   if (rs6000_cpu_index >= 0)
3678     cpu_index = rs6000_cpu_index;
3679   else if (main_target_opt != NULL && main_target_opt->x_rs6000_cpu_index >= 0)
3680     cpu_index = main_target_opt->x_rs6000_cpu_index;
3681   else if (OPTION_TARGET_CPU_DEFAULT)
3682     cpu_index = rs6000_cpu_name_lookup (OPTION_TARGET_CPU_DEFAULT);
3683
3684   /* If we have a cpu, either through an explicit -mcpu=<xxx> or if the
3685      compiler was configured with --with-cpu=<xxx>, replace all of the ISA bits
3686      with those from the cpu, except for options that were explicitly set.  If
3687      we don't have a cpu, do not override the target bits set in
3688      TARGET_DEFAULT.  */
3689   if (cpu_index >= 0)
3690     {
3691       rs6000_cpu_index = cpu_index;
3692       rs6000_isa_flags &= ~set_masks;
3693       rs6000_isa_flags |= (processor_target_table[cpu_index].target_enable
3694                            & set_masks);
3695     }
3696   else
3697     {
3698       /* If no -mcpu=<xxx>, inherit any default options that were cleared via
3699          POWERPC_MASKS.  Originally, TARGET_DEFAULT was used to initialize
3700          target_flags via the TARGET_DEFAULT_TARGET_FLAGS hook.  When we switched
3701          to using rs6000_isa_flags, we need to do the initialization here.
3702
3703          If there is a TARGET_DEFAULT, use that.  Otherwise fall back to using
3704          -mcpu=powerpc, -mcpu=powerpc64, or -mcpu=powerpc64le defaults.  */
3705       HOST_WIDE_INT flags;
3706       if (TARGET_DEFAULT)
3707         flags = TARGET_DEFAULT;
3708       else
3709         {
3710           /* PowerPC 64-bit LE requires at least ISA 2.07.  */
3711           const char *default_cpu = (!TARGET_POWERPC64
3712                                      ? "powerpc"
3713                                      : (BYTES_BIG_ENDIAN
3714                                         ? "powerpc64"
3715                                         : "powerpc64le"));
3716           int default_cpu_index = rs6000_cpu_name_lookup (default_cpu);
3717           flags = processor_target_table[default_cpu_index].target_enable;
3718         }
3719       rs6000_isa_flags |= (flags & ~rs6000_isa_flags_explicit);
3720     }
3721
3722   if (rs6000_tune_index >= 0)
3723     tune_index = rs6000_tune_index;
3724   else if (cpu_index >= 0)
3725     rs6000_tune_index = tune_index = cpu_index;
3726   else
3727     {
3728       size_t i;
3729       enum processor_type tune_proc
3730         = (TARGET_POWERPC64 ? PROCESSOR_DEFAULT64 : PROCESSOR_DEFAULT);
3731
3732       tune_index = -1;
3733       for (i = 0; i < ARRAY_SIZE (processor_target_table); i++)
3734         if (processor_target_table[i].processor == tune_proc)
3735           {
3736             tune_index = i;
3737             break;
3738           }
3739     }
3740
3741   if (cpu_index >= 0)
3742     rs6000_cpu = processor_target_table[cpu_index].processor;
3743   else
3744     rs6000_cpu = TARGET_POWERPC64 ? PROCESSOR_DEFAULT64 : PROCESSOR_DEFAULT;
3745
3746   gcc_assert (tune_index >= 0);
3747   rs6000_tune = processor_target_table[tune_index].processor;
3748
3749   if (rs6000_cpu == PROCESSOR_PPCE300C2 || rs6000_cpu == PROCESSOR_PPCE300C3
3750       || rs6000_cpu == PROCESSOR_PPCE500MC || rs6000_cpu == PROCESSOR_PPCE500MC64
3751       || rs6000_cpu == PROCESSOR_PPCE5500)
3752     {
3753       if (TARGET_ALTIVEC)
3754         error ("AltiVec not supported in this target");
3755     }
3756
3757   /* If we are optimizing big endian systems for space, use the load/store
3758      multiple instructions.  */
3759   if (BYTES_BIG_ENDIAN && optimize_size)
3760     rs6000_isa_flags |= ~rs6000_isa_flags_explicit & OPTION_MASK_MULTIPLE;
3761
3762   /* Don't allow -mmultiple on little endian systems unless the cpu is a 750,
3763      because the hardware doesn't support the instructions used in little
3764      endian mode, and causes an alignment trap.  The 750 does not cause an
3765      alignment trap (except when the target is unaligned).  */
3766
3767   if (!BYTES_BIG_ENDIAN && rs6000_cpu != PROCESSOR_PPC750 && TARGET_MULTIPLE)
3768     {
3769       rs6000_isa_flags &= ~OPTION_MASK_MULTIPLE;
3770       if ((rs6000_isa_flags_explicit & OPTION_MASK_MULTIPLE) != 0)
3771         warning (0, "%qs is not supported on little endian systems",
3772                  "-mmultiple");
3773     }
3774
3775   /* If little-endian, default to -mstrict-align on older processors.
3776      Testing for htm matches power8 and later.  */
3777   if (!BYTES_BIG_ENDIAN
3778       && !(processor_target_table[tune_index].target_enable & OPTION_MASK_HTM))
3779     rs6000_isa_flags |= ~rs6000_isa_flags_explicit & OPTION_MASK_STRICT_ALIGN;
3780
3781   if (!rs6000_fold_gimple)
3782      fprintf (stderr,
3783               "gimple folding of rs6000 builtins has been disabled.\n");
3784
3785   /* Add some warnings for VSX.  */
3786   if (TARGET_VSX)
3787     {
3788       const char *msg = NULL;
3789       if (!TARGET_HARD_FLOAT)
3790         {
3791           if (rs6000_isa_flags_explicit & OPTION_MASK_VSX)
3792             msg = N_("%<-mvsx%> requires hardware floating point");
3793           else
3794             {
3795               rs6000_isa_flags &= ~ OPTION_MASK_VSX;
3796               rs6000_isa_flags_explicit |= OPTION_MASK_VSX;
3797             }
3798         }
3799       else if (TARGET_AVOID_XFORM > 0)
3800         msg = N_("%<-mvsx%> needs indexed addressing");
3801       else if (!TARGET_ALTIVEC && (rs6000_isa_flags_explicit
3802                                    & OPTION_MASK_ALTIVEC))
3803         {
3804           if (rs6000_isa_flags_explicit & OPTION_MASK_VSX)
3805             msg = N_("%<-mvsx%> and %<-mno-altivec%> are incompatible");
3806           else
3807             msg = N_("%<-mno-altivec%> disables vsx");
3808         }
3809
3810       if (msg)
3811         {
3812           warning (0, msg);
3813           rs6000_isa_flags &= ~ OPTION_MASK_VSX;
3814           rs6000_isa_flags_explicit |= OPTION_MASK_VSX;
3815         }
3816     }
3817
3818   /* If hard-float/altivec/vsx were explicitly turned off then don't allow
3819      the -mcpu setting to enable options that conflict. */
3820   if ((!TARGET_HARD_FLOAT || !TARGET_ALTIVEC || !TARGET_VSX)
3821       && (rs6000_isa_flags_explicit & (OPTION_MASK_SOFT_FLOAT
3822                                        | OPTION_MASK_ALTIVEC
3823                                        | OPTION_MASK_VSX)) != 0)
3824     rs6000_isa_flags &= ~((OPTION_MASK_P8_VECTOR | OPTION_MASK_CRYPTO
3825                            | OPTION_MASK_DIRECT_MOVE)
3826                          & ~rs6000_isa_flags_explicit);
3827
3828   if (TARGET_DEBUG_REG || TARGET_DEBUG_TARGET)
3829     rs6000_print_isa_options (stderr, 0, "before defaults", rs6000_isa_flags);
3830
3831   /* Handle explicit -mno-{altivec,vsx,power8-vector,power9-vector} and turn
3832      off all of the options that depend on those flags.  */
3833   ignore_masks = rs6000_disable_incompatible_switches ();
3834
3835   /* For the newer switches (vsx, dfp, etc.) set some of the older options,
3836      unless the user explicitly used the -mno-<option> to disable the code.  */
3837   if (TARGET_P9_VECTOR || TARGET_MODULO || TARGET_P9_MISC)
3838     rs6000_isa_flags |= (ISA_3_0_MASKS_SERVER & ~ignore_masks);
3839   else if (TARGET_P9_MINMAX)
3840     {
3841       if (cpu_index >= 0)
3842         {
3843           if (cpu_index == PROCESSOR_POWER9)
3844             {
3845               /* legacy behavior: allow -mcpu=power9 with certain
3846                  capabilities explicitly disabled.  */
3847               rs6000_isa_flags |= (ISA_3_0_MASKS_SERVER & ~ignore_masks);
3848             }
3849           else
3850             error ("power9 target option is incompatible with %<%s=<xxx>%> "
3851                    "for <xxx> less than power9", "-mcpu");
3852         }
3853       else if ((ISA_3_0_MASKS_SERVER & rs6000_isa_flags_explicit)
3854                != (ISA_3_0_MASKS_SERVER & rs6000_isa_flags
3855                    & rs6000_isa_flags_explicit))
3856         /* Enforce that none of the ISA_3_0_MASKS_SERVER flags
3857            were explicitly cleared.  */
3858         error ("%qs incompatible with explicitly disabled options",
3859                "-mpower9-minmax");
3860       else
3861         rs6000_isa_flags |= ISA_3_0_MASKS_SERVER;
3862     }
3863   else if (TARGET_P8_VECTOR || TARGET_DIRECT_MOVE || TARGET_CRYPTO)
3864     rs6000_isa_flags |= (ISA_2_7_MASKS_SERVER & ~ignore_masks);
3865   else if (TARGET_VSX)
3866     rs6000_isa_flags |= (ISA_2_6_MASKS_SERVER & ~ignore_masks);
3867   else if (TARGET_POPCNTD)
3868     rs6000_isa_flags |= (ISA_2_6_MASKS_EMBEDDED & ~ignore_masks);
3869   else if (TARGET_DFP)
3870     rs6000_isa_flags |= (ISA_2_5_MASKS_SERVER & ~ignore_masks);
3871   else if (TARGET_CMPB)
3872     rs6000_isa_flags |= (ISA_2_5_MASKS_EMBEDDED & ~ignore_masks);
3873   else if (TARGET_FPRND)
3874     rs6000_isa_flags |= (ISA_2_4_MASKS & ~ignore_masks);
3875   else if (TARGET_POPCNTB)
3876     rs6000_isa_flags |= (ISA_2_2_MASKS & ~ignore_masks);
3877   else if (TARGET_ALTIVEC)
3878     rs6000_isa_flags |= (OPTION_MASK_PPC_GFXOPT & ~ignore_masks);
3879
3880   if (TARGET_CRYPTO && !TARGET_ALTIVEC)
3881     {
3882       if (rs6000_isa_flags_explicit & OPTION_MASK_CRYPTO)
3883         error ("%qs requires %qs", "-mcrypto", "-maltivec");
3884       rs6000_isa_flags &= ~OPTION_MASK_CRYPTO;
3885     }
3886
3887   if (TARGET_DIRECT_MOVE && !TARGET_VSX)
3888     {
3889       if (rs6000_isa_flags_explicit & OPTION_MASK_DIRECT_MOVE)
3890         error ("%qs requires %qs", "-mdirect-move", "-mvsx");
3891       rs6000_isa_flags &= ~OPTION_MASK_DIRECT_MOVE;
3892     }
3893
3894   if (TARGET_P8_VECTOR && !TARGET_ALTIVEC)
3895     {
3896       if (rs6000_isa_flags_explicit & OPTION_MASK_P8_VECTOR)
3897         error ("%qs requires %qs", "-mpower8-vector", "-maltivec");
3898       rs6000_isa_flags &= ~OPTION_MASK_P8_VECTOR;
3899     }
3900
3901   if (TARGET_P8_VECTOR && !TARGET_VSX)
3902     {
3903       if ((rs6000_isa_flags_explicit & OPTION_MASK_P8_VECTOR)
3904           && (rs6000_isa_flags_explicit & OPTION_MASK_VSX))
3905         error ("%qs requires %qs", "-mpower8-vector", "-mvsx");
3906       else if ((rs6000_isa_flags_explicit & OPTION_MASK_P8_VECTOR) == 0)
3907         {
3908           rs6000_isa_flags &= ~OPTION_MASK_P8_VECTOR;
3909           if (rs6000_isa_flags_explicit & OPTION_MASK_VSX)
3910             rs6000_isa_flags_explicit |= OPTION_MASK_P8_VECTOR;
3911         }
3912       else
3913         {
3914           /* OPTION_MASK_P8_VECTOR is explicit, and OPTION_MASK_VSX is
3915              not explicit.  */
3916           rs6000_isa_flags |= OPTION_MASK_VSX;
3917           rs6000_isa_flags_explicit |= OPTION_MASK_VSX;
3918         }
3919     }
3920
3921   if (TARGET_DFP && !TARGET_HARD_FLOAT)
3922     {
3923       if (rs6000_isa_flags_explicit & OPTION_MASK_DFP)
3924         error ("%qs requires %qs", "-mhard-dfp", "-mhard-float");
3925       rs6000_isa_flags &= ~OPTION_MASK_DFP;
3926     }
3927
3928   /* The quad memory instructions only works in 64-bit mode. In 32-bit mode,
3929      silently turn off quad memory mode.  */
3930   if ((TARGET_QUAD_MEMORY || TARGET_QUAD_MEMORY_ATOMIC) && !TARGET_POWERPC64)
3931     {
3932       if ((rs6000_isa_flags_explicit & OPTION_MASK_QUAD_MEMORY) != 0)
3933         warning (0, N_("%<-mquad-memory%> requires 64-bit mode"));
3934
3935       if ((rs6000_isa_flags_explicit & OPTION_MASK_QUAD_MEMORY_ATOMIC) != 0)
3936         warning (0, N_("%<-mquad-memory-atomic%> requires 64-bit mode"));
3937
3938       rs6000_isa_flags &= ~(OPTION_MASK_QUAD_MEMORY
3939                             | OPTION_MASK_QUAD_MEMORY_ATOMIC);
3940     }
3941
3942   /* Non-atomic quad memory load/store are disabled for little endian, since
3943      the words are reversed, but atomic operations can still be done by
3944      swapping the words.  */
3945   if (TARGET_QUAD_MEMORY && !WORDS_BIG_ENDIAN)
3946     {
3947       if ((rs6000_isa_flags_explicit & OPTION_MASK_QUAD_MEMORY) != 0)
3948         warning (0, N_("%<-mquad-memory%> is not available in little endian "
3949                        "mode"));
3950
3951       rs6000_isa_flags &= ~OPTION_MASK_QUAD_MEMORY;
3952     }
3953
3954   /* Assume if the user asked for normal quad memory instructions, they want
3955      the atomic versions as well, unless they explicity told us not to use quad
3956      word atomic instructions.  */
3957   if (TARGET_QUAD_MEMORY
3958       && !TARGET_QUAD_MEMORY_ATOMIC
3959       && ((rs6000_isa_flags_explicit & OPTION_MASK_QUAD_MEMORY_ATOMIC) == 0))
3960     rs6000_isa_flags |= OPTION_MASK_QUAD_MEMORY_ATOMIC;
3961
3962   /* If we can shrink-wrap the TOC register save separately, then use
3963      -msave-toc-indirect unless explicitly disabled.  */
3964   if ((rs6000_isa_flags_explicit & OPTION_MASK_SAVE_TOC_INDIRECT) == 0
3965       && flag_shrink_wrap_separate
3966       && optimize_function_for_speed_p (cfun))
3967     rs6000_isa_flags |= OPTION_MASK_SAVE_TOC_INDIRECT;
3968
3969   /* Enable power8 fusion if we are tuning for power8, even if we aren't
3970      generating power8 instructions.  Power9 does not optimize power8 fusion
3971      cases.  */
3972   if (!(rs6000_isa_flags_explicit & OPTION_MASK_P8_FUSION))
3973     {
3974       if (processor_target_table[tune_index].processor == PROCESSOR_POWER8)
3975         rs6000_isa_flags |= OPTION_MASK_P8_FUSION;
3976       else
3977         rs6000_isa_flags &= ~OPTION_MASK_P8_FUSION;
3978     }
3979
3980   /* Setting additional fusion flags turns on base fusion.  */
3981   if (!TARGET_P8_FUSION && TARGET_P8_FUSION_SIGN)
3982     {
3983       if (rs6000_isa_flags_explicit & OPTION_MASK_P8_FUSION)
3984         {
3985           if (TARGET_P8_FUSION_SIGN)
3986             error ("%qs requires %qs", "-mpower8-fusion-sign",
3987                    "-mpower8-fusion");
3988
3989           rs6000_isa_flags &= ~OPTION_MASK_P8_FUSION;
3990         }
3991       else
3992         rs6000_isa_flags |= OPTION_MASK_P8_FUSION;
3993     }
3994
3995   /* Power8 does not fuse sign extended loads with the addis.  If we are
3996      optimizing at high levels for speed, convert a sign extended load into a
3997      zero extending load, and an explicit sign extension.  */
3998   if (TARGET_P8_FUSION
3999       && !(rs6000_isa_flags_explicit & OPTION_MASK_P8_FUSION_SIGN)
4000       && optimize_function_for_speed_p (cfun)
4001       && optimize >= 3)
4002     rs6000_isa_flags |= OPTION_MASK_P8_FUSION_SIGN;
4003
4004   /* ISA 3.0 vector instructions include ISA 2.07.  */
4005   if (TARGET_P9_VECTOR && !TARGET_P8_VECTOR)
4006     {
4007       /* We prefer to not mention undocumented options in
4008          error messages.  However, if users have managed to select
4009          power9-vector without selecting power8-vector, they
4010          already know about undocumented flags.  */
4011       if ((rs6000_isa_flags_explicit & OPTION_MASK_P9_VECTOR) &&
4012           (rs6000_isa_flags_explicit & OPTION_MASK_P8_VECTOR))
4013         error ("%qs requires %qs", "-mpower9-vector", "-mpower8-vector");
4014       else if ((rs6000_isa_flags_explicit & OPTION_MASK_P9_VECTOR) == 0)
4015         {
4016           rs6000_isa_flags &= ~OPTION_MASK_P9_VECTOR;
4017           if (rs6000_isa_flags_explicit & OPTION_MASK_P8_VECTOR)
4018             rs6000_isa_flags_explicit |= OPTION_MASK_P9_VECTOR;
4019         }
4020       else
4021         {
4022           /* OPTION_MASK_P9_VECTOR is explicit and
4023              OPTION_MASK_P8_VECTOR is not explicit.  */
4024           rs6000_isa_flags |= OPTION_MASK_P8_VECTOR;
4025           rs6000_isa_flags_explicit |= OPTION_MASK_P8_VECTOR;
4026         }
4027     }
4028
4029   /* Set -mallow-movmisalign to explicitly on if we have full ISA 2.07
4030      support. If we only have ISA 2.06 support, and the user did not specify
4031      the switch, leave it set to -1 so the movmisalign patterns are enabled,
4032      but we don't enable the full vectorization support  */
4033   if (TARGET_ALLOW_MOVMISALIGN == -1 && TARGET_P8_VECTOR && TARGET_DIRECT_MOVE)
4034     TARGET_ALLOW_MOVMISALIGN = 1;
4035
4036   else if (TARGET_ALLOW_MOVMISALIGN && !TARGET_VSX)
4037     {
4038       if (TARGET_ALLOW_MOVMISALIGN > 0
4039           && global_options_set.x_TARGET_ALLOW_MOVMISALIGN)
4040         error ("%qs requires %qs", "-mallow-movmisalign", "-mvsx");
4041
4042       TARGET_ALLOW_MOVMISALIGN = 0;
4043     }
4044
4045   /* Determine when unaligned vector accesses are permitted, and when
4046      they are preferred over masked Altivec loads.  Note that if
4047      TARGET_ALLOW_MOVMISALIGN has been disabled by the user, then
4048      TARGET_EFFICIENT_UNALIGNED_VSX must be as well.  The converse is
4049      not true.  */
4050   if (TARGET_EFFICIENT_UNALIGNED_VSX)
4051     {
4052       if (!TARGET_VSX)
4053         {
4054           if (rs6000_isa_flags_explicit & OPTION_MASK_EFFICIENT_UNALIGNED_VSX)
4055             error ("%qs requires %qs", "-mefficient-unaligned-vsx", "-mvsx");
4056
4057           rs6000_isa_flags &= ~OPTION_MASK_EFFICIENT_UNALIGNED_VSX;
4058         }
4059
4060       else if (!TARGET_ALLOW_MOVMISALIGN)
4061         {
4062           if (rs6000_isa_flags_explicit & OPTION_MASK_EFFICIENT_UNALIGNED_VSX)
4063             error ("%qs requires %qs", "-munefficient-unaligned-vsx",
4064                    "-mallow-movmisalign");
4065
4066           rs6000_isa_flags &= ~OPTION_MASK_EFFICIENT_UNALIGNED_VSX;
4067         }
4068     }
4069
4070   /* Use long double size to select the appropriate long double.  We use
4071      TYPE_PRECISION to differentiate the 3 different long double types.  We map
4072      128 into the precision used for TFmode.  */
4073   int default_long_double_size = (RS6000_DEFAULT_LONG_DOUBLE_SIZE == 64
4074                                   ? 64
4075                                   : FLOAT_PRECISION_TFmode);
4076
4077   /* Set long double size before the IEEE 128-bit tests.  */
4078   if (!global_options_set.x_rs6000_long_double_type_size)
4079     {
4080       if (main_target_opt != NULL
4081           && (main_target_opt->x_rs6000_long_double_type_size
4082               != default_long_double_size))
4083         error ("target attribute or pragma changes %<long double%> size");
4084       else
4085         rs6000_long_double_type_size = default_long_double_size;
4086     }
4087   else if (rs6000_long_double_type_size == 128)
4088     rs6000_long_double_type_size = FLOAT_PRECISION_TFmode;
4089   else if (global_options_set.x_rs6000_ieeequad)
4090     {
4091       if (global_options.x_rs6000_ieeequad)
4092         error ("%qs requires %qs", "-mabi=ieeelongdouble", "-mlong-double-128");
4093       else
4094         error ("%qs requires %qs", "-mabi=ibmlongdouble", "-mlong-double-128");
4095     }
4096
4097   /* Set -mabi=ieeelongdouble on some old targets.  In the future, power server
4098      systems will also set long double to be IEEE 128-bit.  AIX and Darwin
4099      explicitly redefine TARGET_IEEEQUAD and TARGET_IEEEQUAD_DEFAULT to 0, so
4100      those systems will not pick up this default.  Warn if the user changes the
4101      default unless -Wno-psabi.  */
4102   if (!global_options_set.x_rs6000_ieeequad)
4103     rs6000_ieeequad = TARGET_IEEEQUAD_DEFAULT;
4104
4105   else
4106     {
4107       if (global_options.x_rs6000_ieeequad
4108           && (!TARGET_POPCNTD || !TARGET_VSX))
4109         error ("%qs requires full ISA 2.06 support", "-mabi=ieeelongdouble");
4110
4111       if (rs6000_ieeequad != TARGET_IEEEQUAD_DEFAULT && TARGET_LONG_DOUBLE_128)
4112         {
4113           static bool warned_change_long_double;
4114           if (!warned_change_long_double)
4115             {
4116               warned_change_long_double = true;
4117               if (TARGET_IEEEQUAD)
4118                 warning (OPT_Wpsabi, "Using IEEE extended precision "
4119                          "%<long double%>");
4120               else
4121                 warning (OPT_Wpsabi, "Using IBM extended precision "
4122                          "%<long double%>");
4123             }
4124         }
4125     }
4126
4127   /* Enable the default support for IEEE 128-bit floating point on Linux VSX
4128      sytems.  In GCC 7, we would enable the the IEEE 128-bit floating point
4129      infrastructure (-mfloat128-type) but not enable the actual __float128 type
4130      unless the user used the explicit -mfloat128.  In GCC 8, we enable both
4131      the keyword as well as the type.  */
4132   TARGET_FLOAT128_TYPE = TARGET_FLOAT128_ENABLE_TYPE && TARGET_VSX;
4133
4134   /* IEEE 128-bit floating point requires VSX support.  */
4135   if (TARGET_FLOAT128_KEYWORD)
4136     {
4137       if (!TARGET_VSX)
4138         {
4139           if ((rs6000_isa_flags_explicit & OPTION_MASK_FLOAT128_KEYWORD) != 0)
4140             error ("%qs requires VSX support", "%<-mfloat128%>");
4141
4142           TARGET_FLOAT128_TYPE = 0;
4143           rs6000_isa_flags &= ~(OPTION_MASK_FLOAT128_KEYWORD
4144                                 | OPTION_MASK_FLOAT128_HW);
4145         }
4146       else if (!TARGET_FLOAT128_TYPE)
4147         {
4148           TARGET_FLOAT128_TYPE = 1;
4149           warning (0, "The %<-mfloat128%> option may not be fully supported");
4150         }
4151     }
4152
4153   /* Enable the __float128 keyword under Linux by default.  */
4154   if (TARGET_FLOAT128_TYPE && !TARGET_FLOAT128_KEYWORD
4155       && (rs6000_isa_flags_explicit & OPTION_MASK_FLOAT128_KEYWORD) == 0)
4156     rs6000_isa_flags |= OPTION_MASK_FLOAT128_KEYWORD;
4157
4158   /* If we have are supporting the float128 type and full ISA 3.0 support,
4159      enable -mfloat128-hardware by default.  However, don't enable the
4160      __float128 keyword if it was explicitly turned off.  64-bit mode is needed
4161      because sometimes the compiler wants to put things in an integer
4162      container, and if we don't have __int128 support, it is impossible.  */
4163   if (TARGET_FLOAT128_TYPE && !TARGET_FLOAT128_HW && TARGET_64BIT
4164       && (rs6000_isa_flags & ISA_3_0_MASKS_IEEE) == ISA_3_0_MASKS_IEEE
4165       && !(rs6000_isa_flags_explicit & OPTION_MASK_FLOAT128_HW))
4166     rs6000_isa_flags |= OPTION_MASK_FLOAT128_HW;
4167
4168   if (TARGET_FLOAT128_HW
4169       && (rs6000_isa_flags & ISA_3_0_MASKS_IEEE) != ISA_3_0_MASKS_IEEE)
4170     {
4171       if ((rs6000_isa_flags_explicit & OPTION_MASK_FLOAT128_HW) != 0)
4172         error ("%qs requires full ISA 3.0 support", "%<-mfloat128-hardware%>");
4173
4174       rs6000_isa_flags &= ~OPTION_MASK_FLOAT128_HW;
4175     }
4176
4177   if (TARGET_FLOAT128_HW && !TARGET_64BIT)
4178     {
4179       if ((rs6000_isa_flags_explicit & OPTION_MASK_FLOAT128_HW) != 0)
4180         error ("%qs requires %qs", "%<-mfloat128-hardware%>", "-m64");
4181
4182       rs6000_isa_flags &= ~OPTION_MASK_FLOAT128_HW;
4183     }
4184
4185   /* -mprefixed-addr (and hence -mpcrel) requires -mcpu=future.  */
4186   if (TARGET_PREFIXED_ADDR && !TARGET_FUTURE)
4187     {
4188       if ((rs6000_isa_flags_explicit & OPTION_MASK_PCREL) != 0)
4189         error ("%qs requires %qs", "-mpcrel", "-mcpu=future");
4190       else if ((rs6000_isa_flags_explicit & OPTION_MASK_PREFIXED_ADDR) != 0)
4191         error ("%qs requires %qs", "-mprefixed-addr", "-mcpu=future");
4192
4193       rs6000_isa_flags &= ~(OPTION_MASK_PCREL | OPTION_MASK_PREFIXED_ADDR);
4194     }
4195
4196   /* -mpcrel requires prefixed load/store addressing.  */
4197   if (TARGET_PCREL && !TARGET_PREFIXED_ADDR)
4198     {
4199       if ((rs6000_isa_flags_explicit & OPTION_MASK_PCREL) != 0)
4200         error ("%qs requires %qs", "-mpcrel", "-mprefixed-addr");
4201
4202       rs6000_isa_flags &= ~OPTION_MASK_PCREL;
4203     }
4204
4205   /* Print the options after updating the defaults.  */
4206   if (TARGET_DEBUG_REG || TARGET_DEBUG_TARGET)
4207     rs6000_print_isa_options (stderr, 0, "after defaults", rs6000_isa_flags);
4208
4209   /* E500mc does "better" if we inline more aggressively.  Respect the
4210      user's opinion, though.  */
4211   if (rs6000_block_move_inline_limit == 0
4212       && (rs6000_tune == PROCESSOR_PPCE500MC
4213           || rs6000_tune == PROCESSOR_PPCE500MC64
4214           || rs6000_tune == PROCESSOR_PPCE5500
4215           || rs6000_tune == PROCESSOR_PPCE6500))
4216     rs6000_block_move_inline_limit = 128;
4217
4218   /* store_one_arg depends on expand_block_move to handle at least the
4219      size of reg_parm_stack_space.  */
4220   if (rs6000_block_move_inline_limit < (TARGET_POWERPC64 ? 64 : 32))
4221     rs6000_block_move_inline_limit = (TARGET_POWERPC64 ? 64 : 32);
4222
4223   if (global_init_p)
4224     {
4225       /* If the appropriate debug option is enabled, replace the target hooks
4226          with debug versions that call the real version and then prints
4227          debugging information.  */
4228       if (TARGET_DEBUG_COST)
4229         {
4230           targetm.rtx_costs = rs6000_debug_rtx_costs;
4231           targetm.address_cost = rs6000_debug_address_cost;
4232           targetm.sched.adjust_cost = rs6000_debug_adjust_cost;
4233         }
4234
4235       if (TARGET_DEBUG_ADDR)
4236         {
4237           targetm.legitimate_address_p = rs6000_debug_legitimate_address_p;
4238           targetm.legitimize_address = rs6000_debug_legitimize_address;
4239           rs6000_secondary_reload_class_ptr
4240             = rs6000_debug_secondary_reload_class;
4241           targetm.secondary_memory_needed
4242             = rs6000_debug_secondary_memory_needed;
4243           targetm.can_change_mode_class
4244             = rs6000_debug_can_change_mode_class;
4245           rs6000_preferred_reload_class_ptr
4246             = rs6000_debug_preferred_reload_class;
4247           rs6000_mode_dependent_address_ptr
4248             = rs6000_debug_mode_dependent_address;
4249         }
4250
4251       if (rs6000_veclibabi_name)
4252         {
4253           if (strcmp (rs6000_veclibabi_name, "mass") == 0)
4254             rs6000_veclib_handler = rs6000_builtin_vectorized_libmass;
4255           else
4256             {
4257               error ("unknown vectorization library ABI type (%qs) for "
4258                      "%qs switch", rs6000_veclibabi_name, "-mveclibabi=");
4259               ret = false;
4260             }
4261         }
4262     }
4263
4264   /* Disable VSX and Altivec silently if the user switched cpus to power7 in a
4265      target attribute or pragma which automatically enables both options,
4266      unless the altivec ABI was set.  This is set by default for 64-bit, but
4267      not for 32-bit.  */
4268   if (main_target_opt != NULL && !main_target_opt->x_rs6000_altivec_abi)
4269     {
4270       TARGET_FLOAT128_TYPE = 0;
4271       rs6000_isa_flags &= ~((OPTION_MASK_VSX | OPTION_MASK_ALTIVEC
4272                              | OPTION_MASK_FLOAT128_KEYWORD)
4273                             & ~rs6000_isa_flags_explicit);
4274     }
4275
4276   /* Enable Altivec ABI for AIX -maltivec.  */
4277   if (TARGET_XCOFF && (TARGET_ALTIVEC || TARGET_VSX))
4278     {
4279       if (main_target_opt != NULL && !main_target_opt->x_rs6000_altivec_abi)
4280         error ("target attribute or pragma changes AltiVec ABI");
4281       else
4282         rs6000_altivec_abi = 1;
4283     }
4284
4285   /* The AltiVec ABI is the default for PowerPC-64 GNU/Linux.  For
4286      PowerPC-32 GNU/Linux, -maltivec implies the AltiVec ABI.  It can
4287      be explicitly overridden in either case.  */
4288   if (TARGET_ELF)
4289     {
4290       if (!global_options_set.x_rs6000_altivec_abi
4291           && (TARGET_64BIT || TARGET_ALTIVEC || TARGET_VSX))
4292         {
4293           if (main_target_opt != NULL &&
4294               !main_target_opt->x_rs6000_altivec_abi)
4295             error ("target attribute or pragma changes AltiVec ABI");
4296           else
4297             rs6000_altivec_abi = 1;
4298         }
4299     }
4300
4301   /* Set the Darwin64 ABI as default for 64-bit Darwin.  
4302      So far, the only darwin64 targets are also MACH-O.  */
4303   if (TARGET_MACHO
4304       && DEFAULT_ABI == ABI_DARWIN 
4305       && TARGET_64BIT)
4306     {
4307       if (main_target_opt != NULL && !main_target_opt->x_rs6000_darwin64_abi)
4308         error ("target attribute or pragma changes darwin64 ABI");
4309       else
4310         {
4311           rs6000_darwin64_abi = 1;
4312           /* Default to natural alignment, for better performance.  */
4313           rs6000_alignment_flags = MASK_ALIGN_NATURAL;
4314         }
4315     }
4316
4317   /* Place FP constants in the constant pool instead of TOC
4318      if section anchors enabled.  */
4319   if (flag_section_anchors
4320       && !global_options_set.x_TARGET_NO_FP_IN_TOC)
4321     TARGET_NO_FP_IN_TOC = 1;
4322
4323   if (TARGET_DEBUG_REG || TARGET_DEBUG_TARGET)
4324     rs6000_print_isa_options (stderr, 0, "before subtarget", rs6000_isa_flags);
4325
4326 #ifdef SUBTARGET_OVERRIDE_OPTIONS
4327   SUBTARGET_OVERRIDE_OPTIONS;
4328 #endif
4329 #ifdef SUBSUBTARGET_OVERRIDE_OPTIONS
4330   SUBSUBTARGET_OVERRIDE_OPTIONS;
4331 #endif
4332 #ifdef SUB3TARGET_OVERRIDE_OPTIONS
4333   SUB3TARGET_OVERRIDE_OPTIONS;
4334 #endif
4335
4336   if (TARGET_DEBUG_REG || TARGET_DEBUG_TARGET)
4337     rs6000_print_isa_options (stderr, 0, "after subtarget", rs6000_isa_flags);
4338
4339   rs6000_always_hint = (rs6000_tune != PROCESSOR_POWER4
4340                         && rs6000_tune != PROCESSOR_POWER5
4341                         && rs6000_tune != PROCESSOR_POWER6
4342                         && rs6000_tune != PROCESSOR_POWER7
4343                         && rs6000_tune != PROCESSOR_POWER8
4344                         && rs6000_tune != PROCESSOR_POWER9
4345                         && rs6000_tune != PROCESSOR_FUTURE
4346                         && rs6000_tune != PROCESSOR_PPCA2
4347                         && rs6000_tune != PROCESSOR_CELL
4348                         && rs6000_tune != PROCESSOR_PPC476);
4349   rs6000_sched_groups = (rs6000_tune == PROCESSOR_POWER4
4350                          || rs6000_tune == PROCESSOR_POWER5
4351                          || rs6000_tune == PROCESSOR_POWER7
4352                          || rs6000_tune == PROCESSOR_POWER8);
4353   rs6000_align_branch_targets = (rs6000_tune == PROCESSOR_POWER4
4354                                  || rs6000_tune == PROCESSOR_POWER5
4355                                  || rs6000_tune == PROCESSOR_POWER6
4356                                  || rs6000_tune == PROCESSOR_POWER7
4357                                  || rs6000_tune == PROCESSOR_POWER8
4358                                  || rs6000_tune == PROCESSOR_POWER9
4359                                  || rs6000_tune == PROCESSOR_FUTURE
4360                                  || rs6000_tune == PROCESSOR_PPCE500MC
4361                                  || rs6000_tune == PROCESSOR_PPCE500MC64
4362                                  || rs6000_tune == PROCESSOR_PPCE5500
4363                                  || rs6000_tune == PROCESSOR_PPCE6500);
4364
4365   /* Allow debug switches to override the above settings.  These are set to -1
4366      in rs6000.opt to indicate the user hasn't directly set the switch.  */
4367   if (TARGET_ALWAYS_HINT >= 0)
4368     rs6000_always_hint = TARGET_ALWAYS_HINT;
4369
4370   if (TARGET_SCHED_GROUPS >= 0)
4371     rs6000_sched_groups = TARGET_SCHED_GROUPS;
4372
4373   if (TARGET_ALIGN_BRANCH_TARGETS >= 0)
4374     rs6000_align_branch_targets = TARGET_ALIGN_BRANCH_TARGETS;
4375
4376   rs6000_sched_restricted_insns_priority
4377     = (rs6000_sched_groups ? 1 : 0);
4378
4379   /* Handle -msched-costly-dep option.  */
4380   rs6000_sched_costly_dep
4381     = (rs6000_sched_groups ? true_store_to_load_dep_costly : no_dep_costly);
4382
4383   if (rs6000_sched_costly_dep_str)
4384     {
4385       if (! strcmp (rs6000_sched_costly_dep_str, "no"))
4386         rs6000_sched_costly_dep = no_dep_costly;
4387       else if (! strcmp (rs6000_sched_costly_dep_str, "all"))
4388         rs6000_sched_costly_dep = all_deps_costly;
4389       else if (! strcmp (rs6000_sched_costly_dep_str, "true_store_to_load"))
4390         rs6000_sched_costly_dep = true_store_to_load_dep_costly;
4391       else if (! strcmp (rs6000_sched_costly_dep_str, "store_to_load"))
4392         rs6000_sched_costly_dep = store_to_load_dep_costly;
4393       else
4394         rs6000_sched_costly_dep = ((enum rs6000_dependence_cost)
4395                                    atoi (rs6000_sched_costly_dep_str));
4396     }
4397
4398   /* Handle -minsert-sched-nops option.  */
4399   rs6000_sched_insert_nops
4400     = (rs6000_sched_groups ? sched_finish_regroup_exact : sched_finish_none);
4401
4402   if (rs6000_sched_insert_nops_str)
4403     {
4404       if (! strcmp (rs6000_sched_insert_nops_str, "no"))
4405         rs6000_sched_insert_nops = sched_finish_none;
4406       else if (! strcmp (rs6000_sched_insert_nops_str, "pad"))
4407         rs6000_sched_insert_nops = sched_finish_pad_groups;
4408       else if (! strcmp (rs6000_sched_insert_nops_str, "regroup_exact"))
4409         rs6000_sched_insert_nops = sched_finish_regroup_exact;
4410       else
4411         rs6000_sched_insert_nops = ((enum rs6000_nop_insertion)
4412                                     atoi (rs6000_sched_insert_nops_str));
4413     }
4414
4415   /* Handle stack protector */
4416   if (!global_options_set.x_rs6000_stack_protector_guard)
4417 #ifdef TARGET_THREAD_SSP_OFFSET
4418     rs6000_stack_protector_guard = SSP_TLS;
4419 #else
4420     rs6000_stack_protector_guard = SSP_GLOBAL;
4421 #endif
4422
4423 #ifdef TARGET_THREAD_SSP_OFFSET
4424   rs6000_stack_protector_guard_offset = TARGET_THREAD_SSP_OFFSET;
4425   rs6000_stack_protector_guard_reg = TARGET_64BIT ? 13 : 2;
4426 #endif
4427
4428   if (global_options_set.x_rs6000_stack_protector_guard_offset_str)
4429     {
4430       char *endp;
4431       const char *str = rs6000_stack_protector_guard_offset_str;
4432
4433       errno = 0;
4434       long offset = strtol (str, &endp, 0);
4435       if (!*str || *endp || errno)
4436         error ("%qs is not a valid number in %qs", str,
4437                "-mstack-protector-guard-offset=");
4438
4439       if (!IN_RANGE (offset, -0x8000, 0x7fff)
4440           || (TARGET_64BIT && (offset & 3)))
4441         error ("%qs is not a valid offset in %qs", str,
4442                "-mstack-protector-guard-offset=");
4443
4444       rs6000_stack_protector_guard_offset = offset;
4445     }
4446
4447   if (global_options_set.x_rs6000_stack_protector_guard_reg_str)
4448     {
4449       const char *str = rs6000_stack_protector_guard_reg_str;
4450       int reg = decode_reg_name (str);
4451
4452       if (!IN_RANGE (reg, 1, 31))
4453         error ("%qs is not a valid base register in %qs", str,
4454                "-mstack-protector-guard-reg=");
4455
4456       rs6000_stack_protector_guard_reg = reg;
4457     }
4458
4459   if (rs6000_stack_protector_guard == SSP_TLS
4460       && !IN_RANGE (rs6000_stack_protector_guard_reg, 1, 31))
4461     error ("%qs needs a valid base register", "-mstack-protector-guard=tls");
4462
4463   if (global_init_p)
4464     {
4465 #ifdef TARGET_REGNAMES
4466       /* If the user desires alternate register names, copy in the
4467          alternate names now.  */
4468       if (TARGET_REGNAMES)
4469         memcpy (rs6000_reg_names, alt_reg_names, sizeof (rs6000_reg_names));
4470 #endif
4471
4472       /* Set aix_struct_return last, after the ABI is determined.
4473          If -maix-struct-return or -msvr4-struct-return was explicitly
4474          used, don't override with the ABI default.  */
4475       if (!global_options_set.x_aix_struct_return)
4476         aix_struct_return = (DEFAULT_ABI != ABI_V4 || DRAFT_V4_STRUCT_RET);
4477
4478 #if 0
4479       /* IBM XL compiler defaults to unsigned bitfields.  */
4480       if (TARGET_XL_COMPAT)
4481         flag_signed_bitfields = 0;
4482 #endif
4483
4484       if (TARGET_LONG_DOUBLE_128 && !TARGET_IEEEQUAD)
4485         REAL_MODE_FORMAT (TFmode) = &ibm_extended_format;
4486
4487       ASM_GENERATE_INTERNAL_LABEL (toc_label_name, "LCTOC", 1);
4488
4489       /* We can only guarantee the availability of DI pseudo-ops when
4490          assembling for 64-bit targets.  */
4491       if (!TARGET_64BIT)
4492         {
4493           targetm.asm_out.aligned_op.di = NULL;
4494           targetm.asm_out.unaligned_op.di = NULL;
4495         }
4496
4497
4498       /* Set branch target alignment, if not optimizing for size.  */
4499       if (!optimize_size)
4500         {
4501           /* Cell wants to be aligned 8byte for dual issue.  Titan wants to be
4502              aligned 8byte to avoid misprediction by the branch predictor.  */
4503           if (rs6000_tune == PROCESSOR_TITAN
4504               || rs6000_tune == PROCESSOR_CELL)
4505             {
4506               if (flag_align_functions && !str_align_functions)
4507                 str_align_functions = "8";
4508               if (flag_align_jumps && !str_align_jumps)
4509                 str_align_jumps = "8";
4510               if (flag_align_loops && !str_align_loops)
4511                 str_align_loops = "8";
4512             }
4513           if (rs6000_align_branch_targets)
4514             {
4515               if (flag_align_functions && !str_align_functions)
4516                 str_align_functions = "16";
4517               if (flag_align_jumps && !str_align_jumps)
4518                 str_align_jumps = "16";
4519               if (flag_align_loops && !str_align_loops)
4520                 {
4521                   can_override_loop_align = 1;
4522                   str_align_loops = "16";
4523                 }
4524             }
4525
4526           if (flag_align_jumps && !str_align_jumps)
4527             str_align_jumps = "16";
4528           if (flag_align_loops && !str_align_loops)
4529             str_align_loops = "16";
4530         }
4531
4532       /* Arrange to save and restore machine status around nested functions.  */
4533       init_machine_status = rs6000_init_machine_status;
4534
4535       /* We should always be splitting complex arguments, but we can't break
4536          Linux and Darwin ABIs at the moment.  For now, only AIX is fixed.  */
4537       if (DEFAULT_ABI == ABI_V4 || DEFAULT_ABI == ABI_DARWIN)
4538         targetm.calls.split_complex_arg = NULL;
4539
4540       /* The AIX and ELFv1 ABIs define standard function descriptors.  */
4541       if (DEFAULT_ABI == ABI_AIX)
4542         targetm.calls.custom_function_descriptors = 0;
4543     }
4544
4545   /* Initialize rs6000_cost with the appropriate target costs.  */
4546   if (optimize_size)
4547     rs6000_cost = TARGET_POWERPC64 ? &size64_cost : &size32_cost;
4548   else
4549     switch (rs6000_tune)
4550       {
4551       case PROCESSOR_RS64A:
4552         rs6000_cost = &rs64a_cost;
4553         break;
4554
4555       case PROCESSOR_MPCCORE:
4556         rs6000_cost = &mpccore_cost;
4557         break;
4558
4559       case PROCESSOR_PPC403:
4560         rs6000_cost = &ppc403_cost;
4561         break;
4562
4563       case PROCESSOR_PPC405:
4564         rs6000_cost = &ppc405_cost;
4565         break;
4566
4567       case PROCESSOR_PPC440:
4568         rs6000_cost = &ppc440_cost;
4569         break;
4570
4571       case PROCESSOR_PPC476:
4572         rs6000_cost = &ppc476_cost;
4573         break;
4574
4575       case PROCESSOR_PPC601:
4576         rs6000_cost = &ppc601_cost;
4577         break;
4578
4579       case PROCESSOR_PPC603:
4580         rs6000_cost = &ppc603_cost;
4581         break;
4582
4583       case PROCESSOR_PPC604:
4584         rs6000_cost = &ppc604_cost;
4585         break;
4586
4587       case PROCESSOR_PPC604e:
4588         rs6000_cost = &ppc604e_cost;
4589         break;
4590
4591       case PROCESSOR_PPC620:
4592         rs6000_cost = &ppc620_cost;
4593         break;
4594
4595       case PROCESSOR_PPC630:
4596         rs6000_cost = &ppc630_cost;
4597         break;
4598
4599       case PROCESSOR_CELL:
4600         rs6000_cost = &ppccell_cost;
4601         break;
4602
4603       case PROCESSOR_PPC750:
4604       case PROCESSOR_PPC7400:
4605         rs6000_cost = &ppc750_cost;
4606         break;
4607
4608       case PROCESSOR_PPC7450:
4609         rs6000_cost = &ppc7450_cost;
4610         break;
4611
4612       case PROCESSOR_PPC8540:
4613       case PROCESSOR_PPC8548:
4614         rs6000_cost = &ppc8540_cost;
4615         break;
4616
4617       case PROCESSOR_PPCE300C2:
4618       case PROCESSOR_PPCE300C3:
4619         rs6000_cost = &ppce300c2c3_cost;
4620         break;
4621
4622       case PROCESSOR_PPCE500MC:
4623         rs6000_cost = &ppce500mc_cost;
4624         break;
4625
4626       case PROCESSOR_PPCE500MC64:
4627         rs6000_cost = &ppce500mc64_cost;
4628         break;
4629
4630       case PROCESSOR_PPCE5500:
4631         rs6000_cost = &ppce5500_cost;
4632         break;
4633
4634       case PROCESSOR_PPCE6500:
4635         rs6000_cost = &ppce6500_cost;
4636         break;
4637
4638       case PROCESSOR_TITAN:
4639         rs6000_cost = &titan_cost;
4640         break;
4641
4642       case PROCESSOR_POWER4:
4643       case PROCESSOR_POWER5:
4644         rs6000_cost = &power4_cost;
4645         break;
4646
4647       case PROCESSOR_POWER6:
4648         rs6000_cost = &power6_cost;
4649         break;
4650
4651       case PROCESSOR_POWER7:
4652         rs6000_cost = &power7_cost;
4653         break;
4654
4655       case PROCESSOR_POWER8:
4656         rs6000_cost = &power8_cost;
4657         break;
4658
4659       case PROCESSOR_POWER9:
4660       case PROCESSOR_FUTURE:
4661         rs6000_cost = &power9_cost;
4662         break;
4663
4664       case PROCESSOR_PPCA2:
4665         rs6000_cost = &ppca2_cost;
4666         break;
4667
4668       default:
4669         gcc_unreachable ();
4670       }
4671
4672   if (global_init_p)
4673     {
4674       maybe_set_param_value (PARAM_SIMULTANEOUS_PREFETCHES,
4675                              rs6000_cost->simultaneous_prefetches,
4676                              global_options.x_param_values,
4677                              global_options_set.x_param_values);
4678       maybe_set_param_value (PARAM_L1_CACHE_SIZE, rs6000_cost->l1_cache_size,
4679                              global_options.x_param_values,
4680                              global_options_set.x_param_values);
4681       maybe_set_param_value (PARAM_L1_CACHE_LINE_SIZE,
4682                              rs6000_cost->cache_line_size,
4683                              global_options.x_param_values,
4684                              global_options_set.x_param_values);
4685       maybe_set_param_value (PARAM_L2_CACHE_SIZE, rs6000_cost->l2_cache_size,
4686                              global_options.x_param_values,
4687                              global_options_set.x_param_values);
4688
4689       /* Increase loop peeling limits based on performance analysis. */
4690       maybe_set_param_value (PARAM_MAX_PEELED_INSNS, 400,
4691                              global_options.x_param_values,
4692                              global_options_set.x_param_values);
4693       maybe_set_param_value (PARAM_MAX_COMPLETELY_PEELED_INSNS, 400,
4694                              global_options.x_param_values,
4695                              global_options_set.x_param_values);
4696
4697       /* Use the 'model' -fsched-pressure algorithm by default.  */
4698       maybe_set_param_value (PARAM_SCHED_PRESSURE_ALGORITHM,
4699                              SCHED_PRESSURE_MODEL,
4700                              global_options.x_param_values,
4701                              global_options_set.x_param_values);
4702
4703       /* If using typedef char *va_list, signal that
4704          __builtin_va_start (&ap, 0) can be optimized to
4705          ap = __builtin_next_arg (0).  */
4706       if (DEFAULT_ABI != ABI_V4)
4707         targetm.expand_builtin_va_start = NULL;
4708     }
4709
4710   /* If not explicitly specified via option, decide whether to generate indexed
4711      load/store instructions.  A value of -1 indicates that the
4712      initial value of this variable has not been overwritten. During
4713      compilation, TARGET_AVOID_XFORM is either 0 or 1. */
4714   if (TARGET_AVOID_XFORM == -1)
4715     /* Avoid indexed addressing when targeting Power6 in order to avoid the
4716      DERAT mispredict penalty.  However the LVE and STVE altivec instructions
4717      need indexed accesses and the type used is the scalar type of the element
4718      being loaded or stored.  */
4719     TARGET_AVOID_XFORM = (rs6000_tune == PROCESSOR_POWER6 && TARGET_CMPB
4720                           && !TARGET_ALTIVEC);
4721
4722   /* Set the -mrecip options.  */
4723   if (rs6000_recip_name)
4724     {
4725       char *p = ASTRDUP (rs6000_recip_name);
4726       char *q;
4727       unsigned int mask, i;
4728       bool invert;
4729
4730       while ((q = strtok (p, ",")) != NULL)
4731         {
4732           p = NULL;
4733           if (*q == '!')
4734             {
4735               invert = true;
4736               q++;
4737             }
4738           else
4739             invert = false;
4740
4741           if (!strcmp (q, "default"))
4742             mask = ((TARGET_RECIP_PRECISION)
4743                     ? RECIP_HIGH_PRECISION : RECIP_LOW_PRECISION);
4744           else
4745             {
4746               for (i = 0; i < ARRAY_SIZE (recip_options); i++)
4747                 if (!strcmp (q, recip_options[i].string))
4748                   {
4749                     mask = recip_options[i].mask;
4750                     break;
4751                   }
4752
4753               if (i == ARRAY_SIZE (recip_options))
4754                 {
4755                   error ("unknown option for %<%s=%s%>", "-mrecip", q);
4756                   invert = false;
4757                   mask = 0;
4758                   ret = false;
4759                 }
4760             }
4761
4762           if (invert)
4763             rs6000_recip_control &= ~mask;
4764           else
4765             rs6000_recip_control |= mask;
4766         }
4767     }
4768
4769   /* Set the builtin mask of the various options used that could affect which
4770      builtins were used.  In the past we used target_flags, but we've run out
4771      of bits, and some options are no longer in target_flags.  */
4772   rs6000_builtin_mask = rs6000_builtin_mask_calculate ();
4773   if (TARGET_DEBUG_BUILTIN || TARGET_DEBUG_TARGET)
4774     rs6000_print_builtin_options (stderr, 0, "builtin mask",
4775                                   rs6000_builtin_mask);
4776
4777   /* Initialize all of the registers.  */
4778   rs6000_init_hard_regno_mode_ok (global_init_p);
4779
4780   /* Save the initial options in case the user does function specific options */
4781   if (global_init_p)
4782     target_option_default_node = target_option_current_node
4783       = build_target_option_node (&global_options);
4784
4785   /* If not explicitly specified via option, decide whether to generate the
4786      extra blr's required to preserve the link stack on some cpus (eg, 476).  */
4787   if (TARGET_LINK_STACK == -1)
4788     SET_TARGET_LINK_STACK (rs6000_tune == PROCESSOR_PPC476 && flag_pic);
4789
4790   /* Deprecate use of -mno-speculate-indirect-jumps.  */
4791   if (!rs6000_speculate_indirect_jumps)
4792     warning (0, "%qs is deprecated and not recommended in any circumstances",
4793              "-mno-speculate-indirect-jumps");
4794
4795   return ret;
4796 }
4797
4798 /* Implement TARGET_OPTION_OVERRIDE.  On the RS/6000 this is used to
4799    define the target cpu type.  */
4800
4801 static void
4802 rs6000_option_override (void)
4803 {
4804   (void) rs6000_option_override_internal (true);
4805 }
4806
4807 \f
4808 /* Implement targetm.vectorize.builtin_mask_for_load.  */
4809 static tree
4810 rs6000_builtin_mask_for_load (void)
4811 {
4812   /* Don't use lvsl/vperm for P8 and similarly efficient machines.  */
4813   if ((TARGET_ALTIVEC && !TARGET_VSX)
4814       || (TARGET_VSX && !TARGET_EFFICIENT_UNALIGNED_VSX))
4815     return altivec_builtin_mask_for_load;
4816   else
4817     return 0;
4818 }
4819
4820 /* Implement LOOP_ALIGN. */
4821 align_flags
4822 rs6000_loop_align (rtx label)
4823 {
4824   basic_block bb;
4825   int ninsns;
4826
4827   /* Don't override loop alignment if -falign-loops was specified. */
4828   if (!can_override_loop_align)
4829     return align_loops;
4830
4831   bb = BLOCK_FOR_INSN (label);
4832   ninsns = num_loop_insns(bb->loop_father);
4833
4834   /* Align small loops to 32 bytes to fit in an icache sector, otherwise return default. */
4835   if (ninsns > 4 && ninsns <= 8
4836       && (rs6000_tune == PROCESSOR_POWER4
4837           || rs6000_tune == PROCESSOR_POWER5
4838           || rs6000_tune == PROCESSOR_POWER6
4839           || rs6000_tune == PROCESSOR_POWER7
4840           || rs6000_tune == PROCESSOR_POWER8))
4841     return align_flags (5);
4842   else
4843     return align_loops;
4844 }
4845
4846 /* Return true iff, data reference of TYPE can reach vector alignment (16)
4847    after applying N number of iterations.  This routine does not determine
4848    how may iterations are required to reach desired alignment.  */
4849
4850 static bool
4851 rs6000_vector_alignment_reachable (const_tree type ATTRIBUTE_UNUSED, bool is_packed)
4852 {
4853   if (is_packed)
4854     return false;
4855
4856   if (TARGET_32BIT)
4857     {
4858       if (rs6000_alignment_flags == MASK_ALIGN_NATURAL)
4859         return true;
4860
4861       if (rs6000_alignment_flags ==  MASK_ALIGN_POWER)
4862         return true;
4863
4864       return false;
4865     }
4866   else
4867     {
4868       if (TARGET_MACHO)
4869         return false;
4870
4871       /* Assuming that all other types are naturally aligned. CHECKME!  */
4872       return true;
4873     }
4874 }
4875
4876 /* Return true if the vector misalignment factor is supported by the
4877    target.  */ 
4878 static bool
4879 rs6000_builtin_support_vector_misalignment (machine_mode mode,
4880                                             const_tree type,
4881                                             int misalignment,
4882                                             bool is_packed)
4883 {
4884   if (TARGET_VSX)
4885     {
4886       if (TARGET_EFFICIENT_UNALIGNED_VSX)
4887         return true;
4888
4889       /* Return if movmisalign pattern is not supported for this mode.  */
4890       if (optab_handler (movmisalign_optab, mode) == CODE_FOR_nothing)
4891         return false;
4892
4893       if (misalignment == -1)
4894         {
4895           /* Misalignment factor is unknown at compile time but we know
4896              it's word aligned.  */
4897           if (rs6000_vector_alignment_reachable (type, is_packed))
4898             {
4899               int element_size = TREE_INT_CST_LOW (TYPE_SIZE (type));
4900
4901               if (element_size == 64 || element_size == 32)
4902                return true;
4903             }
4904
4905           return false;
4906         }
4907
4908       /* VSX supports word-aligned vector.  */
4909       if (misalignment % 4 == 0)
4910         return true;
4911     }
4912   return false;
4913 }
4914
4915 /* Implement targetm.vectorize.builtin_vectorization_cost.  */
4916 static int
4917 rs6000_builtin_vectorization_cost (enum vect_cost_for_stmt type_of_cost,
4918                                    tree vectype, int misalign)
4919 {
4920   unsigned elements;
4921   tree elem_type;
4922
4923   switch (type_of_cost)
4924     {
4925       case scalar_stmt:
4926       case scalar_load:
4927       case scalar_store:
4928       case vector_stmt:
4929       case vector_load:
4930       case vector_store:
4931       case vec_to_scalar:
4932       case scalar_to_vec:
4933       case cond_branch_not_taken:
4934         return 1;
4935
4936       case vec_perm:
4937         if (TARGET_VSX)
4938           return 3;
4939         else
4940           return 1;
4941
4942       case vec_promote_demote:
4943         if (TARGET_VSX)
4944           return 4;
4945         else
4946           return 1;
4947
4948       case cond_branch_taken:
4949         return 3;
4950
4951       case unaligned_load:
4952       case vector_gather_load:
4953         if (TARGET_EFFICIENT_UNALIGNED_VSX)
4954           return 1;
4955
4956         if (TARGET_VSX && TARGET_ALLOW_MOVMISALIGN)
4957           {
4958             elements = TYPE_VECTOR_SUBPARTS (vectype);
4959             if (elements == 2)
4960               /* Double word aligned.  */
4961               return 2;
4962
4963             if (elements == 4)
4964               {
4965                 switch (misalign)
4966                   {
4967                     case 8:
4968                       /* Double word aligned.  */
4969                       return 2;
4970
4971                     case -1:
4972                       /* Unknown misalignment.  */
4973                     case 4:
4974                     case 12:
4975                       /* Word aligned.  */
4976                       return 22;
4977
4978                     default:
4979                       gcc_unreachable ();
4980                   }
4981               }
4982           }
4983
4984         if (TARGET_ALTIVEC)
4985           /* Misaligned loads are not supported.  */
4986           gcc_unreachable ();
4987
4988         return 2;
4989
4990       case unaligned_store:
4991       case vector_scatter_store:
4992         if (TARGET_EFFICIENT_UNALIGNED_VSX)
4993           return 1;
4994
4995         if (TARGET_VSX && TARGET_ALLOW_MOVMISALIGN)
4996           {
4997             elements = TYPE_VECTOR_SUBPARTS (vectype);
4998             if (elements == 2)
4999               /* Double word aligned.  */
5000               return 2;
5001
5002             if (elements == 4)
5003               {
5004                 switch (misalign)
5005                   {
5006                     case 8:
5007                       /* Double word aligned.  */
5008                       return 2;
5009
5010                     case -1:
5011                       /* Unknown misalignment.  */
5012                     case 4:
5013                     case 12:
5014                       /* Word aligned.  */
5015                       return 23;
5016
5017                     default:
5018                       gcc_unreachable ();
5019                   }
5020               }
5021           }
5022
5023         if (TARGET_ALTIVEC)
5024           /* Misaligned stores are not supported.  */
5025           gcc_unreachable ();
5026
5027         return 2;
5028
5029       case vec_construct:
5030         /* This is a rough approximation assuming non-constant elements
5031            constructed into a vector via element insertion.  FIXME:
5032            vec_construct is not granular enough for uniformly good
5033            decisions.  If the initialization is a splat, this is
5034            cheaper than we estimate.  Improve this someday.  */
5035         elem_type = TREE_TYPE (vectype);
5036         /* 32-bit vectors loaded into registers are stored as double
5037            precision, so we need 2 permutes, 2 converts, and 1 merge
5038            to construct a vector of short floats from them.  */
5039         if (SCALAR_FLOAT_TYPE_P (elem_type)
5040             && TYPE_PRECISION (elem_type) == 32)
5041           return 5;
5042         /* On POWER9, integer vector types are built up in GPRs and then
5043            use a direct move (2 cycles).  For POWER8 this is even worse,
5044            as we need two direct moves and a merge, and the direct moves
5045            are five cycles.  */
5046         else if (INTEGRAL_TYPE_P (elem_type))
5047           {
5048             if (TARGET_P9_VECTOR)
5049               return TYPE_VECTOR_SUBPARTS (vectype) - 1 + 2;
5050             else
5051               return TYPE_VECTOR_SUBPARTS (vectype) - 1 + 5;
5052           }
5053         else
5054           /* V2DFmode doesn't need a direct move.  */
5055           return 2;
5056
5057       default:
5058         gcc_unreachable ();
5059     }
5060 }
5061
5062 /* Implement targetm.vectorize.preferred_simd_mode.  */
5063
5064 static machine_mode
5065 rs6000_preferred_simd_mode (scalar_mode mode)
5066 {
5067   if (TARGET_VSX)
5068     switch (mode)
5069       {
5070       case E_DFmode:
5071         return V2DFmode;
5072       default:;
5073       }
5074   if (TARGET_ALTIVEC || TARGET_VSX)
5075     switch (mode)
5076       {
5077       case E_SFmode:
5078         return V4SFmode;
5079       case E_TImode:
5080         return V1TImode;
5081       case E_DImode:
5082         return V2DImode;
5083       case E_SImode:
5084         return V4SImode;
5085       case E_HImode:
5086         return V8HImode;
5087       case E_QImode:
5088         return V16QImode;
5089       default:;
5090       }
5091   return word_mode;
5092 }
5093
5094 typedef struct _rs6000_cost_data
5095 {
5096   struct loop *loop_info;
5097   unsigned cost[3];
5098 } rs6000_cost_data;
5099
5100 /* Test for likely overcommitment of vector hardware resources.  If a
5101    loop iteration is relatively large, and too large a percentage of
5102    instructions in the loop are vectorized, the cost model may not
5103    adequately reflect delays from unavailable vector resources.
5104    Penalize the loop body cost for this case.  */
5105
5106 static void
5107 rs6000_density_test (rs6000_cost_data *data)
5108 {
5109   const int DENSITY_PCT_THRESHOLD = 85;
5110   const int DENSITY_SIZE_THRESHOLD = 70;
5111   const int DENSITY_PENALTY = 10;
5112   struct loop *loop = data->loop_info;
5113   basic_block *bbs = get_loop_body (loop);
5114   int nbbs = loop->num_nodes;
5115   loop_vec_info loop_vinfo = loop_vec_info_for_loop (data->loop_info);
5116   int vec_cost = data->cost[vect_body], not_vec_cost = 0;
5117   int i, density_pct;
5118
5119   for (i = 0; i < nbbs; i++)
5120     {
5121       basic_block bb = bbs[i];
5122       gimple_stmt_iterator gsi;
5123
5124       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5125         {
5126           gimple *stmt = gsi_stmt (gsi);
5127           stmt_vec_info stmt_info = loop_vinfo->lookup_stmt (stmt);
5128
5129           if (!STMT_VINFO_RELEVANT_P (stmt_info)
5130               && !STMT_VINFO_IN_PATTERN_P (stmt_info))
5131             not_vec_cost++;
5132         }
5133     }
5134
5135   free (bbs);
5136   density_pct = (vec_cost * 100) / (vec_cost + not_vec_cost);
5137
5138   if (density_pct > DENSITY_PCT_THRESHOLD
5139       && vec_cost + not_vec_cost > DENSITY_SIZE_THRESHOLD)
5140     {
5141       data->cost[vect_body] = vec_cost * (100 + DENSITY_PENALTY) / 100;
5142       if (dump_enabled_p ())
5143         dump_printf_loc (MSG_NOTE, vect_location,
5144                          "density %d%%, cost %d exceeds threshold, penalizing "
5145                          "loop body cost by %d%%", density_pct,
5146                          vec_cost + not_vec_cost, DENSITY_PENALTY);
5147     }
5148 }
5149
5150 /* Implement targetm.vectorize.init_cost.  */
5151
5152 /* For each vectorized loop, this var holds TRUE iff a non-memory vector
5153    instruction is needed by the vectorization.  */
5154 static bool rs6000_vect_nonmem;
5155
5156 static void *
5157 rs6000_init_cost (struct loop *loop_info)
5158 {
5159   rs6000_cost_data *data = XNEW (struct _rs6000_cost_data);
5160   data->loop_info = loop_info;
5161   data->cost[vect_prologue] = 0;
5162   data->cost[vect_body]     = 0;
5163   data->cost[vect_epilogue] = 0;
5164   rs6000_vect_nonmem = false;
5165   return data;
5166 }
5167
5168 /* Implement targetm.vectorize.add_stmt_cost.  */
5169
5170 static unsigned
5171 rs6000_add_stmt_cost (void *data, int count, enum vect_cost_for_stmt kind,
5172                       struct _stmt_vec_info *stmt_info, int misalign,
5173                       enum vect_cost_model_location where)
5174 {
5175   rs6000_cost_data *cost_data = (rs6000_cost_data*) data;
5176   unsigned retval = 0;
5177
5178   if (flag_vect_cost_model)
5179     {
5180       tree vectype = stmt_info ? stmt_vectype (stmt_info) : NULL_TREE;
5181       int stmt_cost = rs6000_builtin_vectorization_cost (kind, vectype,
5182                                                          misalign);
5183       /* Statements in an inner loop relative to the loop being
5184          vectorized are weighted more heavily.  The value here is
5185          arbitrary and could potentially be improved with analysis.  */
5186       if (where == vect_body && stmt_info && stmt_in_inner_loop_p (stmt_info))
5187         count *= 50;  /* FIXME.  */
5188
5189       retval = (unsigned) (count * stmt_cost);
5190       cost_data->cost[where] += retval;
5191
5192       /* Check whether we're doing something other than just a copy loop.
5193          Not all such loops may be profitably vectorized; see
5194          rs6000_finish_cost.  */
5195       if ((kind == vec_to_scalar || kind == vec_perm
5196            || kind == vec_promote_demote || kind == vec_construct
5197            || kind == scalar_to_vec)
5198           || (where == vect_body && kind == vector_stmt))
5199         rs6000_vect_nonmem = true;
5200     }
5201
5202   return retval;
5203 }
5204
5205 /* Implement targetm.vectorize.finish_cost.  */
5206
5207 static void
5208 rs6000_finish_cost (void *data, unsigned *prologue_cost,
5209                     unsigned *body_cost, unsigned *epilogue_cost)
5210 {
5211   rs6000_cost_data *cost_data = (rs6000_cost_data*) data;
5212
5213   if (cost_data->loop_info)
5214     rs6000_density_test (cost_data);
5215
5216   /* Don't vectorize minimum-vectorization-factor, simple copy loops
5217      that require versioning for any reason.  The vectorization is at
5218      best a wash inside the loop, and the versioning checks make
5219      profitability highly unlikely and potentially quite harmful.  */
5220   if (cost_data->loop_info)
5221     {
5222       loop_vec_info vec_info = loop_vec_info_for_loop (cost_data->loop_info);
5223       if (!rs6000_vect_nonmem
5224           && LOOP_VINFO_VECT_FACTOR (vec_info) == 2
5225           && LOOP_REQUIRES_VERSIONING (vec_info))
5226         cost_data->cost[vect_body] += 10000;
5227     }
5228
5229   *prologue_cost = cost_data->cost[vect_prologue];
5230   *body_cost     = cost_data->cost[vect_body];
5231   *epilogue_cost = cost_data->cost[vect_epilogue];
5232 }
5233
5234 /* Implement targetm.vectorize.destroy_cost_data.  */
5235
5236 static void
5237 rs6000_destroy_cost_data (void *data)
5238 {
5239   free (data);
5240 }
5241
5242 /* Handler for the Mathematical Acceleration Subsystem (mass) interface to a
5243    library with vectorized intrinsics.  */
5244
5245 static tree
5246 rs6000_builtin_vectorized_libmass (combined_fn fn, tree type_out,
5247                                    tree type_in)
5248 {
5249   char name[32];
5250   const char *suffix = NULL;
5251   tree fntype, new_fndecl, bdecl = NULL_TREE;
5252   int n_args = 1;
5253   const char *bname;
5254   machine_mode el_mode, in_mode;
5255   int n, in_n;
5256
5257   /* Libmass is suitable for unsafe math only as it does not correctly support
5258      parts of IEEE with the required precision such as denormals.  Only support
5259      it if we have VSX to use the simd d2 or f4 functions.
5260      XXX: Add variable length support.  */
5261   if (!flag_unsafe_math_optimizations || !TARGET_VSX)
5262     return NULL_TREE;
5263
5264   el_mode = TYPE_MODE (TREE_TYPE (type_out));
5265   n = TYPE_VECTOR_SUBPARTS (type_out);
5266   in_mode = TYPE_MODE (TREE_TYPE (type_in));
5267   in_n = TYPE_VECTOR_SUBPARTS (type_in);
5268   if (el_mode != in_mode
5269       || n != in_n)
5270     return NULL_TREE;
5271
5272   switch (fn)
5273     {
5274     CASE_CFN_ATAN2:
5275     CASE_CFN_HYPOT:
5276     CASE_CFN_POW:
5277       n_args = 2;
5278       gcc_fallthrough ();
5279
5280     CASE_CFN_ACOS:
5281     CASE_CFN_ACOSH:
5282     CASE_CFN_ASIN:
5283     CASE_CFN_ASINH:
5284     CASE_CFN_ATAN:
5285     CASE_CFN_ATANH:
5286     CASE_CFN_CBRT:
5287     CASE_CFN_COS:
5288     CASE_CFN_COSH:
5289     CASE_CFN_ERF:
5290     CASE_CFN_ERFC:
5291     CASE_CFN_EXP2:
5292     CASE_CFN_EXP:
5293     CASE_CFN_EXPM1:
5294     CASE_CFN_LGAMMA:
5295     CASE_CFN_LOG10:
5296     CASE_CFN_LOG1P:
5297     CASE_CFN_LOG2:
5298     CASE_CFN_LOG:
5299     CASE_CFN_SIN:
5300     CASE_CFN_SINH:
5301     CASE_CFN_SQRT:
5302     CASE_CFN_TAN:
5303     CASE_CFN_TANH:
5304       if (el_mode == DFmode && n == 2)
5305         {
5306           bdecl = mathfn_built_in (double_type_node, fn);
5307           suffix = "d2";                                /* pow -> powd2 */
5308         }
5309       else if (el_mode == SFmode && n == 4)
5310         {
5311           bdecl = mathfn_built_in (float_type_node, fn);
5312           suffix = "4";                                 /* powf -> powf4 */
5313         }
5314       else
5315         return NULL_TREE;
5316       if (!bdecl)
5317         return NULL_TREE;
5318       break;
5319
5320     default:
5321       return NULL_TREE;
5322     }
5323
5324   gcc_assert (suffix != NULL);
5325   bname = IDENTIFIER_POINTER (DECL_NAME (bdecl));
5326   if (!bname)
5327     return NULL_TREE;
5328
5329   strcpy (name, bname + sizeof ("__builtin_") - 1);
5330   strcat (name, suffix);
5331
5332   if (n_args == 1)
5333     fntype = build_function_type_list (type_out, type_in, NULL);
5334   else if (n_args == 2)
5335     fntype = build_function_type_list (type_out, type_in, type_in, NULL);
5336   else
5337     gcc_unreachable ();
5338
5339   /* Build a function declaration for the vectorized function.  */
5340   new_fndecl = build_decl (BUILTINS_LOCATION,
5341                            FUNCTION_DECL, get_identifier (name), fntype);
5342   TREE_PUBLIC (new_fndecl) = 1;
5343   DECL_EXTERNAL (new_fndecl) = 1;
5344   DECL_IS_NOVOPS (new_fndecl) = 1;
5345   TREE_READONLY (new_fndecl) = 1;
5346
5347   return new_fndecl;
5348 }
5349
5350 /* Returns a function decl for a vectorized version of the builtin function
5351    with builtin function code FN and the result vector type TYPE, or NULL_TREE
5352    if it is not available.  */
5353
5354 static tree
5355 rs6000_builtin_vectorized_function (unsigned int fn, tree type_out,
5356                                     tree type_in)
5357 {
5358   machine_mode in_mode, out_mode;
5359   int in_n, out_n;
5360
5361   if (TARGET_DEBUG_BUILTIN)
5362     fprintf (stderr, "rs6000_builtin_vectorized_function (%s, %s, %s)\n",
5363              combined_fn_name (combined_fn (fn)),
5364              GET_MODE_NAME (TYPE_MODE (type_out)),
5365              GET_MODE_NAME (TYPE_MODE (type_in)));
5366
5367   if (TREE_CODE (type_out) != VECTOR_TYPE
5368       || TREE_CODE (type_in) != VECTOR_TYPE)
5369     return NULL_TREE;
5370
5371   out_mode = TYPE_MODE (TREE_TYPE (type_out));
5372   out_n = TYPE_VECTOR_SUBPARTS (type_out);
5373   in_mode = TYPE_MODE (TREE_TYPE (type_in));
5374   in_n = TYPE_VECTOR_SUBPARTS (type_in);
5375
5376   switch (fn)
5377     {
5378     CASE_CFN_COPYSIGN:
5379       if (VECTOR_UNIT_VSX_P (V2DFmode)
5380           && out_mode == DFmode && out_n == 2
5381           && in_mode == DFmode && in_n == 2)
5382         return rs6000_builtin_decls[VSX_BUILTIN_CPSGNDP];
5383       if (VECTOR_UNIT_VSX_P (V4SFmode)
5384           && out_mode == SFmode && out_n == 4
5385           && in_mode == SFmode && in_n == 4)
5386         return rs6000_builtin_decls[VSX_BUILTIN_CPSGNSP];
5387       if (VECTOR_UNIT_ALTIVEC_P (V4SFmode)
5388           && out_mode == SFmode && out_n == 4
5389           && in_mode == SFmode && in_n == 4)
5390         return rs6000_builtin_decls[ALTIVEC_BUILTIN_COPYSIGN_V4SF];
5391       break;
5392     CASE_CFN_CEIL:
5393       if (VECTOR_UNIT_VSX_P (V2DFmode)
5394           && out_mode == DFmode && out_n == 2
5395           && in_mode == DFmode && in_n == 2)
5396         return rs6000_builtin_decls[VSX_BUILTIN_XVRDPIP];
5397       if (VECTOR_UNIT_VSX_P (V4SFmode)
5398           && out_mode == SFmode && out_n == 4
5399           && in_mode == SFmode && in_n == 4)
5400         return rs6000_builtin_decls[VSX_BUILTIN_XVRSPIP];
5401       if (VECTOR_UNIT_ALTIVEC_P (V4SFmode)
5402           && out_mode == SFmode && out_n == 4
5403           && in_mode == SFmode && in_n == 4)
5404         return rs6000_builtin_decls[ALTIVEC_BUILTIN_VRFIP];
5405       break;
5406     CASE_CFN_FLOOR:
5407       if (VECTOR_UNIT_VSX_P (V2DFmode)
5408           && out_mode == DFmode && out_n == 2
5409           && in_mode == DFmode && in_n == 2)
5410         return rs6000_builtin_decls[VSX_BUILTIN_XVRDPIM];
5411       if (VECTOR_UNIT_VSX_P (V4SFmode)
5412           && out_mode == SFmode && out_n == 4
5413           && in_mode == SFmode && in_n == 4)
5414         return rs6000_builtin_decls[VSX_BUILTIN_XVRSPIM];
5415       if (VECTOR_UNIT_ALTIVEC_P (V4SFmode)
5416           && out_mode == SFmode && out_n == 4
5417           && in_mode == SFmode && in_n == 4)
5418         return rs6000_builtin_decls[ALTIVEC_BUILTIN_VRFIM];
5419       break;
5420     CASE_CFN_FMA:
5421       if (VECTOR_UNIT_VSX_P (V2DFmode)
5422           && out_mode == DFmode && out_n == 2
5423           && in_mode == DFmode && in_n == 2)
5424         return rs6000_builtin_decls[VSX_BUILTIN_XVMADDDP];
5425       if (VECTOR_UNIT_VSX_P (V4SFmode)
5426           && out_mode == SFmode && out_n == 4
5427           && in_mode == SFmode && in_n == 4)
5428         return rs6000_builtin_decls[VSX_BUILTIN_XVMADDSP];
5429       if (VECTOR_UNIT_ALTIVEC_P (V4SFmode)
5430           && out_mode == SFmode && out_n == 4
5431           && in_mode == SFmode && in_n == 4)
5432         return rs6000_builtin_decls[ALTIVEC_BUILTIN_VMADDFP];
5433       break;
5434     CASE_CFN_TRUNC:
5435       if (VECTOR_UNIT_VSX_P (V2DFmode)
5436           && out_mode == DFmode && out_n == 2
5437           && in_mode == DFmode && in_n == 2)
5438         return rs6000_builtin_decls[VSX_BUILTIN_XVRDPIZ];
5439       if (VECTOR_UNIT_VSX_P (V4SFmode)
5440           && out_mode == SFmode && out_n == 4
5441           && in_mode == SFmode && in_n == 4)
5442         return rs6000_builtin_decls[VSX_BUILTIN_XVRSPIZ];
5443       if (VECTOR_UNIT_ALTIVEC_P (V4SFmode)
5444           && out_mode == SFmode && out_n == 4
5445           && in_mode == SFmode && in_n == 4)
5446         return rs6000_builtin_decls[ALTIVEC_BUILTIN_VRFIZ];
5447       break;
5448     CASE_CFN_NEARBYINT:
5449       if (VECTOR_UNIT_VSX_P (V2DFmode)
5450           && flag_unsafe_math_optimizations
5451           && out_mode == DFmode && out_n == 2
5452           && in_mode == DFmode && in_n == 2)
5453         return rs6000_builtin_decls[VSX_BUILTIN_XVRDPI];
5454       if (VECTOR_UNIT_VSX_P (V4SFmode)
5455           && flag_unsafe_math_optimizations
5456           && out_mode == SFmode && out_n == 4
5457           && in_mode == SFmode && in_n == 4)
5458         return rs6000_builtin_decls[VSX_BUILTIN_XVRSPI];
5459       break;
5460     CASE_CFN_RINT:
5461       if (VECTOR_UNIT_VSX_P (V2DFmode)
5462           && !flag_trapping_math
5463           && out_mode == DFmode && out_n == 2
5464           && in_mode == DFmode && in_n == 2)
5465         return rs6000_builtin_decls[VSX_BUILTIN_XVRDPIC];
5466       if (VECTOR_UNIT_VSX_P (V4SFmode)
5467           && !flag_trapping_math
5468           && out_mode == SFmode && out_n == 4
5469           && in_mode == SFmode && in_n == 4)
5470         return rs6000_builtin_decls[VSX_BUILTIN_XVRSPIC];
5471       break;
5472     default:
5473       break;
5474     }
5475
5476   /* Generate calls to libmass if appropriate.  */
5477   if (rs6000_veclib_handler)
5478     return rs6000_veclib_handler (combined_fn (fn), type_out, type_in);
5479
5480   return NULL_TREE;
5481 }
5482
5483 /* Implement TARGET_VECTORIZE_BUILTIN_MD_VECTORIZED_FUNCTION.  */
5484
5485 static tree
5486 rs6000_builtin_md_vectorized_function (tree fndecl, tree type_out,
5487                                        tree type_in)
5488 {
5489   machine_mode in_mode, out_mode;
5490   int in_n, out_n;
5491
5492   if (TARGET_DEBUG_BUILTIN)
5493     fprintf (stderr, "rs6000_builtin_md_vectorized_function (%s, %s, %s)\n",
5494              IDENTIFIER_POINTER (DECL_NAME (fndecl)),
5495              GET_MODE_NAME (TYPE_MODE (type_out)),
5496              GET_MODE_NAME (TYPE_MODE (type_in)));
5497
5498   if (TREE_CODE (type_out) != VECTOR_TYPE
5499       || TREE_CODE (type_in) != VECTOR_TYPE)
5500     return NULL_TREE;
5501
5502   out_mode = TYPE_MODE (TREE_TYPE (type_out));
5503   out_n = TYPE_VECTOR_SUBPARTS (type_out);
5504   in_mode = TYPE_MODE (TREE_TYPE (type_in));
5505   in_n = TYPE_VECTOR_SUBPARTS (type_in);
5506
5507   enum rs6000_builtins fn
5508     = (enum rs6000_builtins) DECL_FUNCTION_CODE (fndecl);
5509   switch (fn)
5510     {
5511     case RS6000_BUILTIN_RSQRTF:
5512       if (VECTOR_UNIT_ALTIVEC_OR_VSX_P (V4SFmode)
5513           && out_mode == SFmode && out_n == 4
5514           && in_mode == SFmode && in_n == 4)
5515         return rs6000_builtin_decls[ALTIVEC_BUILTIN_VRSQRTFP];
5516       break;
5517     case RS6000_BUILTIN_RSQRT:
5518       if (VECTOR_UNIT_VSX_P (V2DFmode)
5519           && out_mode == DFmode && out_n == 2
5520           && in_mode == DFmode && in_n == 2)
5521         return rs6000_builtin_decls[VSX_BUILTIN_RSQRT_2DF];
5522       break;
5523     case RS6000_BUILTIN_RECIPF:
5524       if (VECTOR_UNIT_ALTIVEC_OR_VSX_P (V4SFmode)
5525           && out_mode == SFmode && out_n == 4
5526           && in_mode == SFmode && in_n == 4)
5527         return rs6000_builtin_decls[ALTIVEC_BUILTIN_VRECIPFP];
5528       break;
5529     case RS6000_BUILTIN_RECIP:
5530       if (VECTOR_UNIT_VSX_P (V2DFmode)
5531           && out_mode == DFmode && out_n == 2
5532           && in_mode == DFmode && in_n == 2)
5533         return rs6000_builtin_decls[VSX_BUILTIN_RECIP_V2DF];
5534       break;
5535     default:
5536       break;
5537     }
5538   return NULL_TREE;
5539 }
5540 \f
5541 /* Default CPU string for rs6000*_file_start functions.  */
5542 static const char *rs6000_default_cpu;
5543
5544 #ifdef USING_ELFOS_H
5545 const char *rs6000_machine;
5546
5547 const char *
5548 rs6000_machine_from_flags (void)
5549 {
5550   HOST_WIDE_INT flags = rs6000_isa_flags;
5551
5552   /* Disable the flags that should never influence the .machine selection.  */
5553   flags &= ~(OPTION_MASK_PPC_GFXOPT | OPTION_MASK_PPC_GPOPT);
5554
5555   if ((flags & (ISA_FUTURE_MASKS_SERVER & ~ISA_3_0_MASKS_SERVER)) != 0)
5556     return "future";
5557   if ((flags & (ISA_3_0_MASKS_SERVER & ~ISA_2_7_MASKS_SERVER)) != 0)
5558     return "power9";
5559   if ((flags & (ISA_2_7_MASKS_SERVER & ~ISA_2_6_MASKS_SERVER)) != 0)
5560     return "power8";
5561   if ((flags & (ISA_2_6_MASKS_SERVER & ~ISA_2_5_MASKS_SERVER)) != 0)
5562     return "power7";
5563   if ((flags & (ISA_2_5_MASKS_SERVER & ~ISA_2_4_MASKS)) != 0)
5564     return "power6";
5565   if ((flags & (ISA_2_4_MASKS & ~ISA_2_1_MASKS)) != 0)
5566     return "power5";
5567   if ((flags & ISA_2_1_MASKS) != 0)
5568     return "power4";
5569   if ((flags & OPTION_MASK_POWERPC64) != 0)
5570     return "ppc64";
5571   return "ppc";
5572 }
5573
5574 void
5575 emit_asm_machine (void)
5576 {
5577   fprintf (asm_out_file, "\t.machine %s\n", rs6000_machine);
5578 }
5579 #endif
5580
5581 /* Do anything needed at the start of the asm file.  */
5582
5583 static void
5584 rs6000_file_start (void)
5585 {
5586   char buffer[80];
5587   const char *start = buffer;
5588   FILE *file = asm_out_file;
5589
5590   rs6000_default_cpu = TARGET_CPU_DEFAULT;
5591
5592   default_file_start ();
5593
5594   if (flag_verbose_asm)
5595     {
5596       sprintf (buffer, "\n%s rs6000/powerpc options:", ASM_COMMENT_START);
5597
5598       if (rs6000_default_cpu != 0 && rs6000_default_cpu[0] != '\0')
5599         {
5600           fprintf (file, "%s --with-cpu=%s", start, rs6000_default_cpu);
5601           start = "";
5602         }
5603
5604       if (global_options_set.x_rs6000_cpu_index)
5605         {
5606           fprintf (file, "%s -mcpu=%s", start,
5607                    processor_target_table[rs6000_cpu_index].name);
5608           start = "";
5609         }
5610
5611       if (global_options_set.x_rs6000_tune_index)
5612         {
5613           fprintf (file, "%s -mtune=%s", start,
5614                    processor_target_table[rs6000_tune_index].name);
5615           start = "";
5616         }
5617
5618       if (PPC405_ERRATUM77)
5619         {
5620           fprintf (file, "%s PPC405CR_ERRATUM77", start);
5621           start = "";
5622         }
5623
5624 #ifdef USING_ELFOS_H
5625       switch (rs6000_sdata)
5626         {
5627         case SDATA_NONE: fprintf (file, "%s -msdata=none", start); start = ""; break;
5628         case SDATA_DATA: fprintf (file, "%s -msdata=data", start); start = ""; break;
5629         case SDATA_SYSV: fprintf (file, "%s -msdata=sysv", start); start = ""; break;
5630         case SDATA_EABI: fprintf (file, "%s -msdata=eabi", start); start = ""; break;
5631         }
5632
5633       if (rs6000_sdata && g_switch_value)
5634         {
5635           fprintf (file, "%s -G %d", start,
5636                    g_switch_value);
5637           start = "";
5638         }
5639 #endif
5640
5641       if (*start == '\0')
5642         putc ('\n', file);
5643     }
5644
5645 #ifdef USING_ELFOS_H
5646   rs6000_machine = rs6000_machine_from_flags ();
5647   if (!(rs6000_default_cpu && rs6000_default_cpu[0])
5648       && !global_options_set.x_rs6000_cpu_index)
5649     emit_asm_machine ();
5650 #endif
5651
5652   if (DEFAULT_ABI == ABI_ELFv2)
5653     fprintf (file, "\t.abiversion 2\n");
5654 }
5655
5656 \f
5657 /* Return nonzero if this function is known to have a null epilogue.  */
5658
5659 int
5660 direct_return (void)
5661 {
5662   if (reload_completed)
5663     {
5664       rs6000_stack_t *info = rs6000_stack_info ();
5665
5666       if (info->first_gp_reg_save == 32
5667           && info->first_fp_reg_save == 64
5668           && info->first_altivec_reg_save == LAST_ALTIVEC_REGNO + 1
5669           && ! info->lr_save_p
5670           && ! info->cr_save_p
5671           && info->vrsave_size == 0
5672           && ! info->push_p)
5673         return 1;
5674     }
5675
5676   return 0;
5677 }
5678
5679 /* Helper for num_insns_constant.  Calculate number of instructions to
5680    load VALUE to a single gpr using combinations of addi, addis, ori,
5681    oris and sldi instructions.  */
5682
5683 static int
5684 num_insns_constant_gpr (HOST_WIDE_INT value)
5685 {
5686   /* signed constant loadable with addi */
5687   if (((unsigned HOST_WIDE_INT) value + 0x8000) < 0x10000)
5688     return 1;
5689
5690   /* constant loadable with addis */
5691   else if ((value & 0xffff) == 0
5692            && (value >> 31 == -1 || value >> 31 == 0))
5693     return 1;
5694
5695   else if (TARGET_POWERPC64)
5696     {
5697       HOST_WIDE_INT low  = ((value & 0xffffffff) ^ 0x80000000) - 0x80000000;
5698       HOST_WIDE_INT high = value >> 31;
5699
5700       if (high == 0 || high == -1)
5701         return 2;
5702
5703       high >>= 1;
5704
5705       if (low == 0)
5706         return num_insns_constant_gpr (high) + 1;
5707       else if (high == 0)
5708         return num_insns_constant_gpr (low) + 1;
5709       else
5710         return (num_insns_constant_gpr (high)
5711                 + num_insns_constant_gpr (low) + 1);
5712     }
5713
5714   else
5715     return 2;
5716 }
5717
5718 /* Helper for num_insns_constant.  Allow constants formed by the
5719    num_insns_constant_gpr sequences, plus li -1, rldicl/rldicr/rlwinm,
5720    and handle modes that require multiple gprs.  */
5721
5722 static int
5723 num_insns_constant_multi (HOST_WIDE_INT value, machine_mode mode)
5724 {
5725   int nregs = (GET_MODE_SIZE (mode) + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
5726   int total = 0;
5727   while (nregs-- > 0)
5728     {
5729       HOST_WIDE_INT low = sext_hwi (value, BITS_PER_WORD);
5730       int insns = num_insns_constant_gpr (low);
5731       if (insns > 2
5732           /* We won't get more than 2 from num_insns_constant_gpr
5733              except when TARGET_POWERPC64 and mode is DImode or
5734              wider, so the register mode must be DImode.  */
5735           && rs6000_is_valid_and_mask (GEN_INT (low), DImode))
5736         insns = 2;
5737       total += insns;
5738       value >>= BITS_PER_WORD;
5739     }
5740   return total;
5741 }
5742
5743 /* Return the number of instructions it takes to form a constant in as
5744    many gprs are needed for MODE.  */
5745
5746 int
5747 num_insns_constant (rtx op, machine_mode mode)
5748 {
5749   HOST_WIDE_INT val;
5750
5751   switch (GET_CODE (op))
5752     {
5753     case CONST_INT:
5754       val = INTVAL (op);
5755       break;
5756
5757     case CONST_WIDE_INT:
5758       {
5759         int insns = 0;
5760         for (int i = 0; i < CONST_WIDE_INT_NUNITS (op); i++)
5761           insns += num_insns_constant_multi (CONST_WIDE_INT_ELT (op, i),
5762                                              DImode);
5763         return insns;
5764       }
5765
5766     case CONST_DOUBLE:
5767       {
5768         const struct real_value *rv = CONST_DOUBLE_REAL_VALUE (op);
5769
5770         if (mode == SFmode || mode == SDmode)
5771           {
5772             long l;
5773
5774             if (mode == SDmode)
5775               REAL_VALUE_TO_TARGET_DECIMAL32 (*rv, l);
5776             else
5777               REAL_VALUE_TO_TARGET_SINGLE (*rv, l);
5778             /* See the first define_split in rs6000.md handling a
5779                const_double_operand.  */
5780             val = l;
5781             mode = SImode;
5782           }
5783         else if (mode == DFmode || mode == DDmode)
5784           {
5785             long l[2];
5786
5787             if (mode == DDmode)
5788               REAL_VALUE_TO_TARGET_DECIMAL64 (*rv, l);
5789             else
5790               REAL_VALUE_TO_TARGET_DOUBLE (*rv, l);
5791
5792             /* See the second (32-bit) and third (64-bit) define_split
5793                in rs6000.md handling a const_double_operand.  */
5794             val = (unsigned HOST_WIDE_INT) l[WORDS_BIG_ENDIAN ? 0 : 1] << 32;
5795             val |= l[WORDS_BIG_ENDIAN ? 1 : 0] & 0xffffffffUL;
5796             mode = DImode;
5797           }
5798         else if (mode == TFmode || mode == TDmode
5799                  || mode == KFmode || mode == IFmode)
5800           {
5801             long l[4];
5802             int insns;
5803
5804             if (mode == TDmode)
5805               REAL_VALUE_TO_TARGET_DECIMAL128 (*rv, l);
5806             else
5807               REAL_VALUE_TO_TARGET_LONG_DOUBLE (*rv, l);
5808
5809             val = (unsigned HOST_WIDE_INT) l[WORDS_BIG_ENDIAN ? 0 : 3] << 32;
5810             val |= l[WORDS_BIG_ENDIAN ? 1 : 2] & 0xffffffffUL;
5811             insns = num_insns_constant_multi (val, DImode);
5812             val = (unsigned HOST_WIDE_INT) l[WORDS_BIG_ENDIAN ? 2 : 1] << 32;
5813             val |= l[WORDS_BIG_ENDIAN ? 3 : 0] & 0xffffffffUL;
5814             insns += num_insns_constant_multi (val, DImode);
5815             return insns;
5816           }
5817         else
5818           gcc_unreachable ();
5819       }
5820       break;
5821
5822     default:
5823       gcc_unreachable ();
5824     }
5825
5826   return num_insns_constant_multi (val, mode);
5827 }
5828
5829 /* Interpret element ELT of the CONST_VECTOR OP as an integer value.
5830    If the mode of OP is MODE_VECTOR_INT, this simply returns the
5831    corresponding element of the vector, but for V4SFmode, the
5832    corresponding "float" is interpreted as an SImode integer.  */
5833
5834 HOST_WIDE_INT
5835 const_vector_elt_as_int (rtx op, unsigned int elt)
5836 {
5837   rtx tmp;
5838
5839   /* We can't handle V2DImode and V2DFmode vector constants here yet.  */
5840   gcc_assert (GET_MODE (op) != V2DImode
5841               && GET_MODE (op) != V2DFmode);
5842
5843   tmp = CONST_VECTOR_ELT (op, elt);
5844   if (GET_MODE (op) == V4SFmode)
5845     tmp = gen_lowpart (SImode, tmp);
5846   return INTVAL (tmp);
5847 }
5848
5849 /* Return true if OP can be synthesized with a particular vspltisb, vspltish
5850    or vspltisw instruction.  OP is a CONST_VECTOR.  Which instruction is used
5851    depends on STEP and COPIES, one of which will be 1.  If COPIES > 1,
5852    all items are set to the same value and contain COPIES replicas of the
5853    vsplt's operand; if STEP > 1, one in STEP elements is set to the vsplt's
5854    operand and the others are set to the value of the operand's msb.  */
5855
5856 static bool
5857 vspltis_constant (rtx op, unsigned step, unsigned copies)
5858 {
5859   machine_mode mode = GET_MODE (op);
5860   machine_mode inner = GET_MODE_INNER (mode);
5861
5862   unsigned i;
5863   unsigned nunits;
5864   unsigned bitsize;
5865   unsigned mask;
5866
5867   HOST_WIDE_INT val;
5868   HOST_WIDE_INT splat_val;
5869   HOST_WIDE_INT msb_val;
5870
5871   if (mode == V2DImode || mode == V2DFmode || mode == V1TImode)
5872     return false;
5873
5874   nunits = GET_MODE_NUNITS (mode);
5875   bitsize = GET_MODE_BITSIZE (inner);
5876   mask = GET_MODE_MASK (inner);
5877
5878   val = const_vector_elt_as_int (op, BYTES_BIG_ENDIAN ? nunits - 1 : 0);
5879   splat_val = val;
5880   msb_val = val >= 0 ? 0 : -1;
5881
5882   /* Construct the value to be splatted, if possible.  If not, return 0.  */
5883   for (i = 2; i <= copies; i *= 2)
5884     {
5885       HOST_WIDE_INT small_val;
5886       bitsize /= 2;
5887       small_val = splat_val >> bitsize;
5888       mask >>= bitsize;
5889       if (splat_val != ((HOST_WIDE_INT)
5890           ((unsigned HOST_WIDE_INT) small_val << bitsize)
5891           | (small_val & mask)))
5892         return false;
5893       splat_val = small_val;
5894     }
5895
5896   /* Check if SPLAT_VAL can really be the operand of a vspltis[bhw].  */
5897   if (EASY_VECTOR_15 (splat_val))
5898     ;
5899
5900   /* Also check if we can splat, and then add the result to itself.  Do so if
5901      the value is positive, of if the splat instruction is using OP's mode;
5902      for splat_val < 0, the splat and the add should use the same mode.  */
5903   else if (EASY_VECTOR_15_ADD_SELF (splat_val)
5904            && (splat_val >= 0 || (step == 1 && copies == 1)))
5905     ;
5906
5907   /* Also check if are loading up the most significant bit which can be done by
5908      loading up -1 and shifting the value left by -1.  */
5909   else if (EASY_VECTOR_MSB (splat_val, inner))
5910     ;
5911
5912   else
5913     return false;
5914
5915   /* Check if VAL is present in every STEP-th element, and the
5916      other elements are filled with its most significant bit.  */
5917   for (i = 1; i < nunits; ++i)
5918     {
5919       HOST_WIDE_INT desired_val;
5920       unsigned elt = BYTES_BIG_ENDIAN ? nunits - 1 - i : i;
5921       if ((i & (step - 1)) == 0)
5922         desired_val = val;
5923       else
5924         desired_val = msb_val;
5925
5926       if (desired_val != const_vector_elt_as_int (op, elt))
5927         return false;
5928     }
5929
5930   return true;
5931 }
5932
5933 /* Like vsplitis_constant, but allow the value to be shifted left with a VSLDOI
5934    instruction, filling in the bottom elements with 0 or -1.
5935
5936    Return 0 if the constant cannot be generated with VSLDOI.  Return positive
5937    for the number of zeroes to shift in, or negative for the number of 0xff
5938    bytes to shift in.
5939
5940    OP is a CONST_VECTOR.  */
5941
5942 int
5943 vspltis_shifted (rtx op)
5944 {
5945   machine_mode mode = GET_MODE (op);
5946   machine_mode inner = GET_MODE_INNER (mode);
5947
5948   unsigned i, j;
5949   unsigned nunits;
5950   unsigned mask;
5951
5952   HOST_WIDE_INT val;
5953
5954   if (mode != V16QImode && mode != V8HImode && mode != V4SImode)
5955     return false;
5956
5957   /* We need to create pseudo registers to do the shift, so don't recognize
5958      shift vector constants after reload.  */
5959   if (!can_create_pseudo_p ())
5960     return false;
5961
5962   nunits = GET_MODE_NUNITS (mode);
5963   mask = GET_MODE_MASK (inner);
5964
5965   val = const_vector_elt_as_int (op, BYTES_BIG_ENDIAN ? 0 : nunits - 1);
5966
5967   /* Check if the value can really be the operand of a vspltis[bhw].  */
5968   if (EASY_VECTOR_15 (val))
5969     ;
5970
5971   /* Also check if we are loading up the most significant bit which can be done
5972      by loading up -1 and shifting the value left by -1.  */
5973   else if (EASY_VECTOR_MSB (val, inner))
5974     ;
5975
5976   else
5977     return 0;
5978
5979   /* Check if VAL is present in every STEP-th element until we find elements
5980      that are 0 or all 1 bits.  */
5981   for (i = 1; i < nunits; ++i)
5982     {
5983       unsigned elt = BYTES_BIG_ENDIAN ? i : nunits - 1 - i;
5984       HOST_WIDE_INT elt_val = const_vector_elt_as_int (op, elt);
5985
5986       /* If the value isn't the splat value, check for the remaining elements
5987          being 0/-1.  */
5988       if (val != elt_val)
5989         {
5990           if (elt_val == 0)
5991             {
5992               for (j = i+1; j < nunits; ++j)
5993                 {
5994                   unsigned elt2 = BYTES_BIG_ENDIAN ? j : nunits - 1 - j;
5995                   if (const_vector_elt_as_int (op, elt2) != 0)
5996                     return 0;
5997                 }
5998
5999               return (nunits - i) * GET_MODE_SIZE (inner);
6000             }
6001
6002           else if ((elt_val & mask) == mask)
6003             {
6004               for (j = i+1; j < nunits; ++j)
6005                 {
6006                   unsigned elt2 = BYTES_BIG_ENDIAN ? j : nunits - 1 - j;
6007                   if ((const_vector_elt_as_int (op, elt2) & mask) != mask)
6008                     return 0;
6009                 }
6010
6011               return -((nunits - i) * GET_MODE_SIZE (inner));
6012             }
6013
6014           else
6015             return 0;
6016         }
6017     }
6018
6019   /* If all elements are equal, we don't need to do VLSDOI.  */
6020   return 0;
6021 }
6022
6023
6024 /* Return true if OP is of the given MODE and can be synthesized
6025    with a vspltisb, vspltish or vspltisw.  */
6026
6027 bool
6028 easy_altivec_constant (rtx op, machine_mode mode)
6029 {
6030   unsigned step, copies;
6031
6032   if (mode == VOIDmode)
6033     mode = GET_MODE (op);
6034   else if (mode != GET_MODE (op))
6035     return false;
6036
6037   /* V2DI/V2DF was added with VSX.  Only allow 0 and all 1's as easy
6038      constants.  */
6039   if (mode == V2DFmode)
6040     return zero_constant (op, mode);
6041
6042   else if (mode == V2DImode)
6043     {
6044       if (!CONST_INT_P (CONST_VECTOR_ELT (op, 0))
6045           || !CONST_INT_P (CONST_VECTOR_ELT (op, 1)))
6046         return false;
6047
6048       if (zero_constant (op, mode))
6049         return true;
6050
6051       if (INTVAL (CONST_VECTOR_ELT (op, 0)) == -1
6052           && INTVAL (CONST_VECTOR_ELT (op, 1)) == -1)
6053         return true;
6054
6055       return false;
6056     }
6057
6058   /* V1TImode is a special container for TImode.  Ignore for now.  */
6059   else if (mode == V1TImode)
6060     return false;
6061
6062   /* Start with a vspltisw.  */
6063   step = GET_MODE_NUNITS (mode) / 4;
6064   copies = 1;
6065
6066   if (vspltis_constant (op, step, copies))
6067     return true;
6068
6069   /* Then try with a vspltish.  */
6070   if (step == 1)
6071     copies <<= 1;
6072   else
6073     step >>= 1;
6074
6075   if (vspltis_constant (op, step, copies))
6076     return true;
6077
6078   /* And finally a vspltisb.  */
6079   if (step == 1)
6080     copies <<= 1;
6081   else
6082     step >>= 1;
6083
6084   if (vspltis_constant (op, step, copies))
6085     return true;
6086
6087   if (vspltis_shifted (op) != 0)
6088     return true;
6089
6090   return false;
6091 }
6092
6093 /* Generate a VEC_DUPLICATE representing a vspltis[bhw] instruction whose
6094    result is OP.  Abort if it is not possible.  */
6095
6096 rtx
6097 gen_easy_altivec_constant (rtx op)
6098 {
6099   machine_mode mode = GET_MODE (op);
6100   int nunits = GET_MODE_NUNITS (mode);
6101   rtx val = CONST_VECTOR_ELT (op, BYTES_BIG_ENDIAN ? nunits - 1 : 0);
6102   unsigned step = nunits / 4;
6103   unsigned copies = 1;
6104
6105   /* Start with a vspltisw.  */
6106   if (vspltis_constant (op, step, copies))
6107     return gen_rtx_VEC_DUPLICATE (V4SImode, gen_lowpart (SImode, val));
6108
6109   /* Then try with a vspltish.  */
6110   if (step == 1)
6111     copies <<= 1;
6112   else
6113     step >>= 1;
6114
6115   if (vspltis_constant (op, step, copies))
6116     return gen_rtx_VEC_DUPLICATE (V8HImode, gen_lowpart (HImode, val));
6117
6118   /* And finally a vspltisb.  */
6119   if (step == 1)
6120     copies <<= 1;
6121   else
6122     step >>= 1;
6123
6124   if (vspltis_constant (op, step, copies))
6125     return gen_rtx_VEC_DUPLICATE (V16QImode, gen_lowpart (QImode, val));
6126
6127   gcc_unreachable ();
6128 }
6129
6130 /* Return true if OP is of the given MODE and can be synthesized with ISA 3.0
6131    instructions (xxspltib, vupkhsb/vextsb2w/vextb2d).
6132
6133    Return the number of instructions needed (1 or 2) into the address pointed
6134    via NUM_INSNS_PTR.
6135
6136    Return the constant that is being split via CONSTANT_PTR.  */
6137
6138 bool
6139 xxspltib_constant_p (rtx op,
6140                      machine_mode mode,
6141                      int *num_insns_ptr,
6142                      int *constant_ptr)
6143 {
6144   size_t nunits = GET_MODE_NUNITS (mode);
6145   size_t i;
6146   HOST_WIDE_INT value;
6147   rtx element;
6148
6149   /* Set the returned values to out of bound values.  */
6150   *num_insns_ptr = -1;
6151   *constant_ptr = 256;
6152
6153   if (!TARGET_P9_VECTOR)
6154     return false;
6155
6156   if (mode == VOIDmode)
6157     mode = GET_MODE (op);
6158
6159   else if (mode != GET_MODE (op) && GET_MODE (op) != VOIDmode)
6160     return false;
6161
6162   /* Handle (vec_duplicate <constant>).  */
6163   if (GET_CODE (op) == VEC_DUPLICATE)
6164     {
6165       if (mode != V16QImode && mode != V8HImode && mode != V4SImode
6166           && mode != V2DImode)
6167         return false;
6168
6169       element = XEXP (op, 0);
6170       if (!CONST_INT_P (element))
6171         return false;
6172
6173       value = INTVAL (element);
6174       if (!IN_RANGE (value, -128, 127))
6175         return false;
6176     }
6177
6178   /* Handle (const_vector [...]).  */
6179   else if (GET_CODE (op) == CONST_VECTOR)
6180     {
6181       if (mode != V16QImode && mode != V8HImode && mode != V4SImode
6182           && mode != V2DImode)
6183         return false;
6184
6185       element = CONST_VECTOR_ELT (op, 0);
6186       if (!CONST_INT_P (element))
6187         return false;
6188
6189       value = INTVAL (element);
6190       if (!IN_RANGE (value, -128, 127))
6191         return false;
6192
6193       for (i = 1; i < nunits; i++)
6194         {
6195           element = CONST_VECTOR_ELT (op, i);
6196           if (!CONST_INT_P (element))
6197             return false;
6198
6199           if (value != INTVAL (element))
6200             return false;
6201         }
6202     }
6203
6204   /* Handle integer constants being loaded into the upper part of the VSX
6205      register as a scalar.  If the value isn't 0/-1, only allow it if the mode
6206      can go in Altivec registers.  Prefer VSPLTISW/VUPKHSW over XXSPLITIB.  */
6207   else if (CONST_INT_P (op))
6208     {
6209       if (!SCALAR_INT_MODE_P (mode))
6210         return false;
6211
6212       value = INTVAL (op);
6213       if (!IN_RANGE (value, -128, 127))
6214         return false;
6215
6216       if (!IN_RANGE (value, -1, 0))
6217         {
6218           if (!(reg_addr[mode].addr_mask[RELOAD_REG_VMX] & RELOAD_REG_VALID))
6219             return false;
6220
6221           if (EASY_VECTOR_15 (value))
6222             return false;
6223         }
6224     }
6225
6226   else
6227     return false;
6228
6229   /* See if we could generate vspltisw/vspltish directly instead of xxspltib +
6230      sign extend.  Special case 0/-1 to allow getting any VSX register instead
6231      of an Altivec register.  */
6232   if ((mode == V4SImode || mode == V8HImode) && !IN_RANGE (value, -1, 0)
6233       && EASY_VECTOR_15 (value))
6234     return false;
6235
6236   /* Return # of instructions and the constant byte for XXSPLTIB.  */
6237   if (mode == V16QImode)
6238     *num_insns_ptr = 1;
6239
6240   else if (IN_RANGE (value, -1, 0))
6241     *num_insns_ptr = 1;
6242
6243   else
6244     *num_insns_ptr = 2;
6245
6246   *constant_ptr = (int) value;
6247   return true;
6248 }
6249
6250 const char *
6251 output_vec_const_move (rtx *operands)
6252 {
6253   int shift;
6254   machine_mode mode;
6255   rtx dest, vec;
6256
6257   dest = operands[0];
6258   vec = operands[1];
6259   mode = GET_MODE (dest);
6260
6261   if (TARGET_VSX)
6262     {
6263       bool dest_vmx_p = ALTIVEC_REGNO_P (REGNO (dest));
6264       int xxspltib_value = 256;
6265       int num_insns = -1;
6266
6267       if (zero_constant (vec, mode))
6268         {
6269           if (TARGET_P9_VECTOR)
6270             return "xxspltib %x0,0";
6271
6272           else if (dest_vmx_p)
6273             return "vspltisw %0,0";
6274
6275           else
6276             return "xxlxor %x0,%x0,%x0";
6277         }
6278
6279       if (all_ones_constant (vec, mode))
6280         {
6281           if (TARGET_P9_VECTOR)
6282             return "xxspltib %x0,255";
6283
6284           else if (dest_vmx_p)
6285             return "vspltisw %0,-1";
6286
6287           else if (TARGET_P8_VECTOR)
6288             return "xxlorc %x0,%x0,%x0";
6289
6290           else
6291             gcc_unreachable ();
6292         }
6293
6294       if (TARGET_P9_VECTOR
6295           && xxspltib_constant_p (vec, mode, &num_insns, &xxspltib_value))
6296         {
6297           if (num_insns == 1)
6298             {
6299               operands[2] = GEN_INT (xxspltib_value & 0xff);
6300               return "xxspltib %x0,%2";
6301             }
6302
6303           return "#";
6304         }
6305     }
6306
6307   if (TARGET_ALTIVEC)
6308     {
6309       rtx splat_vec;
6310
6311       gcc_assert (ALTIVEC_REGNO_P (REGNO (dest)));
6312       if (zero_constant (vec, mode))
6313         return "vspltisw %0,0";
6314
6315       if (all_ones_constant (vec, mode))
6316         return "vspltisw %0,-1";
6317
6318       /* Do we need to construct a value using VSLDOI?  */
6319       shift = vspltis_shifted (vec);
6320       if (shift != 0)
6321         return "#";
6322
6323       splat_vec = gen_easy_altivec_constant (vec);
6324       gcc_assert (GET_CODE (splat_vec) == VEC_DUPLICATE);
6325       operands[1] = XEXP (splat_vec, 0);
6326       if (!EASY_VECTOR_15 (INTVAL (operands[1])))
6327         return "#";
6328
6329       switch (GET_MODE (splat_vec))
6330         {
6331         case E_V4SImode:
6332           return "vspltisw %0,%1";
6333
6334         case E_V8HImode:
6335           return "vspltish %0,%1";
6336
6337         case E_V16QImode:
6338           return "vspltisb %0,%1";
6339
6340         default:
6341           gcc_unreachable ();
6342         }
6343     }
6344
6345   gcc_unreachable ();
6346 }
6347
6348 /* Initialize vector TARGET to VALS.  */
6349
6350 void
6351 rs6000_expand_vector_init (rtx target, rtx vals)
6352 {
6353   machine_mode mode = GET_MODE (target);
6354   machine_mode inner_mode = GET_MODE_INNER (mode);
6355   int n_elts = GET_MODE_NUNITS (mode);
6356   int n_var = 0, one_var = -1;
6357   bool all_same = true, all_const_zero = true;
6358   rtx x, mem;
6359   int i;
6360
6361   for (i = 0; i < n_elts; ++i)
6362     {
6363       x = XVECEXP (vals, 0, i);
6364       if (!(CONST_SCALAR_INT_P (x) || CONST_DOUBLE_P (x) || CONST_FIXED_P (x)))
6365         ++n_var, one_var = i;
6366       else if (x != CONST0_RTX (inner_mode))
6367         all_const_zero = false;
6368
6369       if (i > 0 && !rtx_equal_p (x, XVECEXP (vals, 0, 0)))
6370         all_same = false;
6371     }
6372
6373   if (n_var == 0)
6374     {
6375       rtx const_vec = gen_rtx_CONST_VECTOR (mode, XVEC (vals, 0));
6376       bool int_vector_p = (GET_MODE_CLASS (mode) == MODE_VECTOR_INT);
6377       if ((int_vector_p || TARGET_VSX) && all_const_zero)
6378         {
6379           /* Zero register.  */
6380           emit_move_insn (target, CONST0_RTX (mode));
6381           return;
6382         }
6383       else if (int_vector_p && easy_vector_constant (const_vec, mode))
6384         {
6385           /* Splat immediate.  */
6386           emit_insn (gen_rtx_SET (target, const_vec));
6387           return;
6388         }
6389       else
6390         {
6391           /* Load from constant pool.  */
6392           emit_move_insn (target, const_vec);
6393           return;
6394         }
6395     }
6396
6397   /* Double word values on VSX can use xxpermdi or lxvdsx.  */
6398   if (VECTOR_MEM_VSX_P (mode) && (mode == V2DFmode || mode == V2DImode))
6399     {
6400       rtx op[2];
6401       size_t i;
6402       size_t num_elements = all_same ? 1 : 2;
6403       for (i = 0; i < num_elements; i++)
6404         {
6405           op[i] = XVECEXP (vals, 0, i);
6406           /* Just in case there is a SUBREG with a smaller mode, do a
6407              conversion.  */
6408           if (GET_MODE (op[i]) != inner_mode)
6409             {
6410               rtx tmp = gen_reg_rtx (inner_mode);
6411               convert_move (tmp, op[i], 0);
6412               op[i] = tmp;
6413             }
6414           /* Allow load with splat double word.  */
6415           else if (MEM_P (op[i]))
6416             {
6417               if (!all_same)
6418                 op[i] = force_reg (inner_mode, op[i]);
6419             }
6420           else if (!REG_P (op[i]))
6421             op[i] = force_reg (inner_mode, op[i]);
6422         }
6423
6424       if (all_same)
6425         {
6426           if (mode == V2DFmode)
6427             emit_insn (gen_vsx_splat_v2df (target, op[0]));
6428           else
6429             emit_insn (gen_vsx_splat_v2di (target, op[0]));
6430         }
6431       else
6432         {
6433           if (mode == V2DFmode)
6434             emit_insn (gen_vsx_concat_v2df (target, op[0], op[1]));
6435           else
6436             emit_insn (gen_vsx_concat_v2di (target, op[0], op[1]));
6437         }
6438       return;
6439     }
6440
6441   /* Special case initializing vector int if we are on 64-bit systems with
6442      direct move or we have the ISA 3.0 instructions.  */
6443   if (mode == V4SImode  && VECTOR_MEM_VSX_P (V4SImode)
6444       && TARGET_DIRECT_MOVE_64BIT)
6445     {
6446       if (all_same)
6447         {
6448           rtx element0 = XVECEXP (vals, 0, 0);
6449           if (MEM_P (element0))
6450             element0 = rs6000_force_indexed_or_indirect_mem (element0);
6451           else
6452             element0 = force_reg (SImode, element0);
6453
6454           if (TARGET_P9_VECTOR)
6455             emit_insn (gen_vsx_splat_v4si (target, element0));
6456           else
6457             {
6458               rtx tmp = gen_reg_rtx (DImode);
6459               emit_insn (gen_zero_extendsidi2 (tmp, element0));
6460               emit_insn (gen_vsx_splat_v4si_di (target, tmp));
6461             }
6462           return;
6463         }
6464       else
6465         {
6466           rtx elements[4];
6467           size_t i;
6468
6469           for (i = 0; i < 4; i++)
6470             elements[i] = force_reg (SImode, XVECEXP (vals, 0, i));
6471
6472           emit_insn (gen_vsx_init_v4si (target, elements[0], elements[1],
6473                                         elements[2], elements[3]));
6474           return;
6475         }
6476     }
6477
6478   /* With single precision floating point on VSX, know that internally single
6479      precision is actually represented as a double, and either make 2 V2DF
6480      vectors, and convert these vectors to single precision, or do one
6481      conversion, and splat the result to the other elements.  */
6482   if (mode == V4SFmode && VECTOR_MEM_VSX_P (V4SFmode))
6483     {
6484       if (all_same)
6485         {
6486           rtx element0 = XVECEXP (vals, 0, 0);
6487
6488           if (TARGET_P9_VECTOR)
6489             {
6490               if (MEM_P (element0))
6491                 element0 = rs6000_force_indexed_or_indirect_mem (element0);
6492
6493               emit_insn (gen_vsx_splat_v4sf (target, element0));
6494             }
6495
6496           else
6497             {
6498               rtx freg = gen_reg_rtx (V4SFmode);
6499               rtx sreg = force_reg (SFmode, element0);
6500               rtx cvt  = (TARGET_XSCVDPSPN
6501                           ? gen_vsx_xscvdpspn_scalar (freg, sreg)
6502                           : gen_vsx_xscvdpsp_scalar (freg, sreg));
6503
6504               emit_insn (cvt);
6505               emit_insn (gen_vsx_xxspltw_v4sf_direct (target, freg,
6506                                                       const0_rtx));
6507             }
6508         }
6509       else
6510         {
6511           rtx dbl_even = gen_reg_rtx (V2DFmode);
6512           rtx dbl_odd  = gen_reg_rtx (V2DFmode);
6513           rtx flt_even = gen_reg_rtx (V4SFmode);
6514           rtx flt_odd  = gen_reg_rtx (V4SFmode);
6515           rtx op0 = force_reg (SFmode, XVECEXP (vals, 0, 0));
6516           rtx op1 = force_reg (SFmode, XVECEXP (vals, 0, 1));
6517           rtx op2 = force_reg (SFmode, XVECEXP (vals, 0, 2));
6518           rtx op3 = force_reg (SFmode, XVECEXP (vals, 0, 3));
6519
6520           /* Use VMRGEW if we can instead of doing a permute.  */
6521           if (TARGET_P8_VECTOR)
6522             {
6523               emit_insn (gen_vsx_concat_v2sf (dbl_even, op0, op2));
6524               emit_insn (gen_vsx_concat_v2sf (dbl_odd, op1, op3));
6525               emit_insn (gen_vsx_xvcvdpsp (flt_even, dbl_even));
6526               emit_insn (gen_vsx_xvcvdpsp (flt_odd, dbl_odd));
6527               if (BYTES_BIG_ENDIAN)
6528                 emit_insn (gen_p8_vmrgew_v4sf_direct (target, flt_even, flt_odd));
6529               else
6530                 emit_insn (gen_p8_vmrgew_v4sf_direct (target, flt_odd, flt_even));
6531             }
6532           else
6533             {
6534               emit_insn (gen_vsx_concat_v2sf (dbl_even, op0, op1));
6535               emit_insn (gen_vsx_concat_v2sf (dbl_odd, op2, op3));
6536               emit_insn (gen_vsx_xvcvdpsp (flt_even, dbl_even));
6537               emit_insn (gen_vsx_xvcvdpsp (flt_odd, dbl_odd));
6538               rs6000_expand_extract_even (target, flt_even, flt_odd);
6539             }
6540         }
6541       return;
6542     }
6543
6544   /* Special case initializing vector short/char that are splats if we are on
6545      64-bit systems with direct move.  */
6546   if (all_same && TARGET_DIRECT_MOVE_64BIT
6547       && (mode == V16QImode || mode == V8HImode))
6548     {
6549       rtx op0 = XVECEXP (vals, 0, 0);
6550       rtx di_tmp = gen_reg_rtx (DImode);
6551
6552       if (!REG_P (op0))
6553         op0 = force_reg (GET_MODE_INNER (mode), op0);
6554
6555       if (mode == V16QImode)
6556         {
6557           emit_insn (gen_zero_extendqidi2 (di_tmp, op0));
6558           emit_insn (gen_vsx_vspltb_di (target, di_tmp));
6559           return;
6560         }
6561
6562       if (mode == V8HImode)
6563         {
6564           emit_insn (gen_zero_extendhidi2 (di_tmp, op0));
6565           emit_insn (gen_vsx_vsplth_di (target, di_tmp));
6566           return;
6567         }
6568     }
6569
6570   /* Store value to stack temp.  Load vector element.  Splat.  However, splat
6571      of 64-bit items is not supported on Altivec.  */
6572   if (all_same && GET_MODE_SIZE (inner_mode) <= 4)
6573     {
6574       mem = assign_stack_temp (mode, GET_MODE_SIZE (inner_mode));
6575       emit_move_insn (adjust_address_nv (mem, inner_mode, 0),
6576                       XVECEXP (vals, 0, 0));
6577       x = gen_rtx_UNSPEC (VOIDmode,
6578                           gen_rtvec (1, const0_rtx), UNSPEC_LVE);
6579       emit_insn (gen_rtx_PARALLEL (VOIDmode,
6580                                    gen_rtvec (2,
6581                                               gen_rtx_SET (target, mem),
6582                                               x)));
6583       x = gen_rtx_VEC_SELECT (inner_mode, target,
6584                               gen_rtx_PARALLEL (VOIDmode,
6585                                                 gen_rtvec (1, const0_rtx)));
6586       emit_insn (gen_rtx_SET (target, gen_rtx_VEC_DUPLICATE (mode, x)));
6587       return;
6588     }
6589
6590   /* One field is non-constant.  Load constant then overwrite
6591      varying field.  */
6592   if (n_var == 1)
6593     {
6594       rtx copy = copy_rtx (vals);
6595
6596       /* Load constant part of vector, substitute neighboring value for
6597          varying element.  */
6598       XVECEXP (copy, 0, one_var) = XVECEXP (vals, 0, (one_var + 1) % n_elts);
6599       rs6000_expand_vector_init (target, copy);
6600
6601       /* Insert variable.  */
6602       rs6000_expand_vector_set (target, XVECEXP (vals, 0, one_var), one_var);
6603       return;
6604     }
6605
6606   /* Construct the vector in memory one field at a time
6607      and load the whole vector.  */
6608   mem = assign_stack_temp (mode, GET_MODE_SIZE (mode));
6609   for (i = 0; i < n_elts; i++)
6610     emit_move_insn (adjust_address_nv (mem, inner_mode,
6611                                     i * GET_MODE_SIZE (inner_mode)),
6612                     XVECEXP (vals, 0, i));
6613   emit_move_insn (target, mem);
6614 }
6615
6616 /* Set field ELT of TARGET to VAL.  */
6617
6618 void
6619 rs6000_expand_vector_set (rtx target, rtx val, int elt)
6620 {
6621   machine_mode mode = GET_MODE (target);
6622   machine_mode inner_mode = GET_MODE_INNER (mode);
6623   rtx reg = gen_reg_rtx (mode);
6624   rtx mask, mem, x;
6625   int width = GET_MODE_SIZE (inner_mode);
6626   int i;
6627
6628   val = force_reg (GET_MODE (val), val);
6629
6630   if (VECTOR_MEM_VSX_P (mode))
6631     {
6632       rtx insn = NULL_RTX;
6633       rtx elt_rtx = GEN_INT (elt);
6634
6635       if (mode == V2DFmode)
6636         insn = gen_vsx_set_v2df (target, target, val, elt_rtx);
6637
6638       else if (mode == V2DImode)
6639         insn = gen_vsx_set_v2di (target, target, val, elt_rtx);
6640
6641       else if (TARGET_P9_VECTOR && TARGET_POWERPC64)
6642         {
6643           if (mode == V4SImode)
6644             insn = gen_vsx_set_v4si_p9 (target, target, val, elt_rtx);
6645           else if (mode == V8HImode)
6646             insn = gen_vsx_set_v8hi_p9 (target, target, val, elt_rtx);
6647           else if (mode == V16QImode)
6648             insn = gen_vsx_set_v16qi_p9 (target, target, val, elt_rtx);
6649           else if (mode == V4SFmode)
6650             insn = gen_vsx_set_v4sf_p9 (target, target, val, elt_rtx);
6651         }
6652
6653       if (insn)
6654         {
6655           emit_insn (insn);
6656           return;
6657         }
6658     }
6659
6660   /* Simplify setting single element vectors like V1TImode.  */
6661   if (GET_MODE_SIZE (mode) == GET_MODE_SIZE (inner_mode) && elt == 0)
6662     {
6663       emit_move_insn (target, gen_lowpart (mode, val));
6664       return;
6665     }
6666
6667   /* Load single variable value.  */
6668   mem = assign_stack_temp (mode, GET_MODE_SIZE (inner_mode));
6669   emit_move_insn (adjust_address_nv (mem, inner_mode, 0), val);
6670   x = gen_rtx_UNSPEC (VOIDmode,
6671                       gen_rtvec (1, const0_rtx), UNSPEC_LVE);
6672   emit_insn (gen_rtx_PARALLEL (VOIDmode,
6673                                gen_rtvec (2,
6674                                           gen_rtx_SET (reg, mem),
6675                                           x)));
6676
6677   /* Linear sequence.  */
6678   mask = gen_rtx_PARALLEL (V16QImode, rtvec_alloc (16));
6679   for (i = 0; i < 16; ++i)
6680     XVECEXP (mask, 0, i) = GEN_INT (i);
6681
6682   /* Set permute mask to insert element into target.  */
6683   for (i = 0; i < width; ++i)
6684     XVECEXP (mask, 0, elt*width + i)
6685       = GEN_INT (i + 0x10);
6686   x = gen_rtx_CONST_VECTOR (V16QImode, XVEC (mask, 0));
6687
6688   if (BYTES_BIG_ENDIAN)
6689     x = gen_rtx_UNSPEC (mode,
6690                         gen_rtvec (3, target, reg,
6691                                    force_reg (V16QImode, x)),
6692                         UNSPEC_VPERM);
6693   else
6694     {
6695       if (TARGET_P9_VECTOR)
6696         x = gen_rtx_UNSPEC (mode,
6697                             gen_rtvec (3, reg, target,
6698                                        force_reg (V16QImode, x)),
6699                             UNSPEC_VPERMR);
6700       else
6701         {
6702           /* Invert selector.  We prefer to generate VNAND on P8 so
6703              that future fusion opportunities can kick in, but must
6704              generate VNOR elsewhere.  */
6705           rtx notx = gen_rtx_NOT (V16QImode, force_reg (V16QImode, x));
6706           rtx iorx = (TARGET_P8_VECTOR
6707                       ? gen_rtx_IOR (V16QImode, notx, notx)
6708                       : gen_rtx_AND (V16QImode, notx, notx));
6709           rtx tmp = gen_reg_rtx (V16QImode);
6710           emit_insn (gen_rtx_SET (tmp, iorx));
6711
6712           /* Permute with operands reversed and adjusted selector.  */
6713           x = gen_rtx_UNSPEC (mode, gen_rtvec (3, reg, target, tmp),
6714                               UNSPEC_VPERM);
6715         }
6716     }
6717
6718   emit_insn (gen_rtx_SET (target, x));
6719 }
6720
6721 /* Extract field ELT from VEC into TARGET.  */
6722
6723 void
6724 rs6000_expand_vector_extract (rtx target, rtx vec, rtx elt)
6725 {
6726   machine_mode mode = GET_MODE (vec);
6727   machine_mode inner_mode = GET_MODE_INNER (mode);
6728   rtx mem;
6729
6730   if (VECTOR_MEM_VSX_P (mode) && CONST_INT_P (elt))
6731     {
6732       switch (mode)
6733         {
6734         default:
6735           break;
6736         case E_V1TImode:
6737           emit_move_insn (target, gen_lowpart (TImode, vec));
6738           break;
6739         case E_V2DFmode:
6740           emit_insn (gen_vsx_extract_v2df (target, vec, elt));
6741           return;
6742         case E_V2DImode:
6743           emit_insn (gen_vsx_extract_v2di (target, vec, elt));
6744           return;
6745         case E_V4SFmode:
6746           emit_insn (gen_vsx_extract_v4sf (target, vec, elt));
6747           return;
6748         case E_V16QImode:
6749           if (TARGET_DIRECT_MOVE_64BIT)
6750             {
6751               emit_insn (gen_vsx_extract_v16qi (target, vec, elt));
6752               return;
6753             }
6754           else
6755             break;
6756         case E_V8HImode:
6757           if (TARGET_DIRECT_MOVE_64BIT)
6758             {
6759               emit_insn (gen_vsx_extract_v8hi (target, vec, elt));
6760               return;
6761             }
6762           else
6763             break;
6764         case E_V4SImode:
6765           if (TARGET_DIRECT_MOVE_64BIT)
6766             {
6767               emit_insn (gen_vsx_extract_v4si (target, vec, elt));
6768               return;
6769             }
6770           break;
6771         }
6772     }
6773   else if (VECTOR_MEM_VSX_P (mode) && !CONST_INT_P (elt)
6774            && TARGET_DIRECT_MOVE_64BIT)
6775     {
6776       if (GET_MODE (elt) != DImode)
6777         {
6778           rtx tmp = gen_reg_rtx (DImode);
6779           convert_move (tmp, elt, 0);
6780           elt = tmp;
6781         }
6782       else if (!REG_P (elt))
6783         elt = force_reg (DImode, elt);
6784
6785       switch (mode)
6786         {
6787         case E_V1TImode:
6788           emit_move_insn (target, gen_lowpart (TImode, vec));
6789           return;
6790
6791         case E_V2DFmode:
6792           emit_insn (gen_vsx_extract_v2df_var (target, vec, elt));
6793           return;
6794
6795         case E_V2DImode:
6796           emit_insn (gen_vsx_extract_v2di_var (target, vec, elt));
6797           return;
6798
6799         case E_V4SFmode:
6800           emit_insn (gen_vsx_extract_v4sf_var (target, vec, elt));
6801           return;
6802
6803         case E_V4SImode:
6804           emit_insn (gen_vsx_extract_v4si_var (target, vec, elt));
6805           return;
6806
6807         case E_V8HImode:
6808           emit_insn (gen_vsx_extract_v8hi_var (target, vec, elt));
6809           return;
6810
6811         case E_V16QImode:
6812           emit_insn (gen_vsx_extract_v16qi_var (target, vec, elt));
6813           return;
6814
6815         default:
6816           gcc_unreachable ();
6817         }
6818     }
6819
6820   /* Allocate mode-sized buffer.  */
6821   mem = assign_stack_temp (mode, GET_MODE_SIZE (mode));
6822
6823   emit_move_insn (mem, vec);
6824   if (CONST_INT_P (elt))
6825     {
6826       int modulo_elt = INTVAL (elt) % GET_MODE_NUNITS (mode);
6827
6828       /* Add offset to field within buffer matching vector element.  */
6829       mem = adjust_address_nv (mem, inner_mode,
6830                                modulo_elt * GET_MODE_SIZE (inner_mode));
6831       emit_move_insn (target, adjust_address_nv (mem, inner_mode, 0));
6832     }
6833   else
6834     {
6835       unsigned int ele_size = GET_MODE_SIZE (inner_mode);
6836       rtx num_ele_m1 = GEN_INT (GET_MODE_NUNITS (mode) - 1);
6837       rtx new_addr = gen_reg_rtx (Pmode);
6838
6839       elt = gen_rtx_AND (Pmode, elt, num_ele_m1);
6840       if (ele_size > 1)
6841         elt = gen_rtx_MULT (Pmode, elt, GEN_INT (ele_size));
6842       new_addr = gen_rtx_PLUS (Pmode, XEXP (mem, 0), elt);
6843       new_addr = change_address (mem, inner_mode, new_addr);
6844       emit_move_insn (target, new_addr);
6845     }
6846 }
6847
6848 /* Adjust a memory address (MEM) of a vector type to point to a scalar field
6849    within the vector (ELEMENT) with a mode (SCALAR_MODE).  Use a base register
6850    temporary (BASE_TMP) to fixup the address.  Return the new memory address
6851    that is valid for reads or writes to a given register (SCALAR_REG).  */
6852
6853 rtx
6854 rs6000_adjust_vec_address (rtx scalar_reg,
6855                            rtx mem,
6856                            rtx element,
6857                            rtx base_tmp,
6858                            machine_mode scalar_mode)
6859 {
6860   unsigned scalar_size = GET_MODE_SIZE (scalar_mode);
6861   rtx addr = XEXP (mem, 0);
6862   rtx element_offset;
6863   rtx new_addr;
6864   bool valid_addr_p;
6865
6866   /* Vector addresses should not have PRE_INC, PRE_DEC, or PRE_MODIFY.  */
6867   gcc_assert (GET_RTX_CLASS (GET_CODE (addr)) != RTX_AUTOINC);
6868
6869   /* Calculate what we need to add to the address to get the element
6870      address.  */
6871   if (CONST_INT_P (element))
6872     element_offset = GEN_INT (INTVAL (element) * scalar_size);
6873   else
6874     {
6875       int byte_shift = exact_log2 (scalar_size);
6876       gcc_assert (byte_shift >= 0);
6877
6878       if (byte_shift == 0)
6879         element_offset = element;
6880
6881       else
6882         {
6883           if (TARGET_POWERPC64)
6884             emit_insn (gen_ashldi3 (base_tmp, element, GEN_INT (byte_shift)));
6885           else
6886             emit_insn (gen_ashlsi3 (base_tmp, element, GEN_INT (byte_shift)));
6887
6888           element_offset = base_tmp;
6889         }
6890     }
6891
6892   /* Create the new address pointing to the element within the vector.  If we
6893      are adding 0, we don't have to change the address.  */
6894   if (element_offset == const0_rtx)
6895     new_addr = addr;
6896
6897   /* A simple indirect address can be converted into a reg + offset
6898      address.  */
6899   else if (REG_P (addr) || SUBREG_P (addr))
6900     new_addr = gen_rtx_PLUS (Pmode, addr, element_offset);
6901
6902   /* Optimize D-FORM addresses with constant offset with a constant element, to
6903      include the element offset in the address directly.  */
6904   else if (GET_CODE (addr) == PLUS)
6905     {
6906       rtx op0 = XEXP (addr, 0);
6907       rtx op1 = XEXP (addr, 1);
6908       rtx insn;
6909
6910       gcc_assert (REG_P (op0) || SUBREG_P (op0));
6911       if (CONST_INT_P (op1) && CONST_INT_P (element_offset))
6912         {
6913           HOST_WIDE_INT offset = INTVAL (op1) + INTVAL (element_offset);
6914           rtx offset_rtx = GEN_INT (offset);
6915
6916           if (IN_RANGE (offset, -32768, 32767)
6917               && (scalar_size < 8 || (offset & 0x3) == 0))
6918             new_addr = gen_rtx_PLUS (Pmode, op0, offset_rtx);
6919           else
6920             {
6921               emit_move_insn (base_tmp, offset_rtx);
6922               new_addr = gen_rtx_PLUS (Pmode, op0, base_tmp);
6923             }
6924         }
6925       else
6926         {
6927           bool op1_reg_p = (REG_P (op1) || SUBREG_P (op1));
6928           bool ele_reg_p = (REG_P (element_offset) || SUBREG_P (element_offset));
6929
6930           /* Note, ADDI requires the register being added to be a base
6931              register.  If the register was R0, load it up into the temporary
6932              and do the add.  */
6933           if (op1_reg_p
6934               && (ele_reg_p || reg_or_subregno (op1) != FIRST_GPR_REGNO))
6935             {
6936               insn = gen_add3_insn (base_tmp, op1, element_offset);
6937               gcc_assert (insn != NULL_RTX);
6938               emit_insn (insn);
6939             }
6940
6941           else if (ele_reg_p
6942                    && reg_or_subregno (element_offset) != FIRST_GPR_REGNO)
6943             {
6944               insn = gen_add3_insn (base_tmp, element_offset, op1);
6945               gcc_assert (insn != NULL_RTX);
6946               emit_insn (insn);
6947             }
6948
6949           else
6950             {
6951               emit_move_insn (base_tmp, op1);
6952               emit_insn (gen_add2_insn (base_tmp, element_offset));
6953             }
6954
6955           new_addr = gen_rtx_PLUS (Pmode, op0, base_tmp);
6956         }
6957     }
6958
6959   else
6960     {
6961       emit_move_insn (base_tmp, addr);
6962       new_addr = gen_rtx_PLUS (Pmode, base_tmp, element_offset);
6963     }
6964
6965   /* If we have a PLUS, we need to see whether the particular register class
6966      allows for D-FORM or X-FORM addressing.  */
6967   if (GET_CODE (new_addr) == PLUS)
6968     {
6969       rtx op1 = XEXP (new_addr, 1);
6970       addr_mask_type addr_mask;
6971       unsigned int scalar_regno = reg_or_subregno (scalar_reg);
6972
6973       gcc_assert (HARD_REGISTER_NUM_P (scalar_regno));
6974       if (INT_REGNO_P (scalar_regno))
6975         addr_mask = reg_addr[scalar_mode].addr_mask[RELOAD_REG_GPR];
6976
6977       else if (FP_REGNO_P (scalar_regno))
6978         addr_mask = reg_addr[scalar_mode].addr_mask[RELOAD_REG_FPR];
6979
6980       else if (ALTIVEC_REGNO_P (scalar_regno))
6981         addr_mask = reg_addr[scalar_mode].addr_mask[RELOAD_REG_VMX];
6982
6983       else
6984         gcc_unreachable ();
6985
6986       if (REG_P (op1) || SUBREG_P (op1))
6987         valid_addr_p = (addr_mask & RELOAD_REG_INDEXED) != 0;
6988       else
6989         valid_addr_p = (addr_mask & RELOAD_REG_OFFSET) != 0;
6990     }
6991
6992   else if (REG_P (new_addr) || SUBREG_P (new_addr))
6993     valid_addr_p = true;
6994
6995   else
6996     valid_addr_p = false;
6997
6998   if (!valid_addr_p)
6999     {
7000       emit_move_insn (base_tmp, new_addr);
7001       new_addr = base_tmp;
7002     }
7003
7004   return change_address (mem, scalar_mode, new_addr);
7005 }
7006
7007 /* Split a variable vec_extract operation into the component instructions.  */
7008
7009 void
7010 rs6000_split_vec_extract_var (rtx dest, rtx src, rtx element, rtx tmp_gpr,
7011                               rtx tmp_altivec)
7012 {
7013   machine_mode mode = GET_MODE (src);
7014   machine_mode scalar_mode = GET_MODE_INNER (GET_MODE (src));
7015   unsigned scalar_size = GET_MODE_SIZE (scalar_mode);
7016   int byte_shift = exact_log2 (scalar_size);
7017
7018   gcc_assert (byte_shift >= 0);
7019
7020   /* If we are given a memory address, optimize to load just the element.  We
7021      don't have to adjust the vector element number on little endian
7022      systems.  */
7023   if (MEM_P (src))
7024     {
7025       int num_elements = GET_MODE_NUNITS (mode);
7026       rtx num_ele_m1 = GEN_INT (num_elements - 1);
7027
7028       emit_insn (gen_anddi3 (element, element, num_ele_m1));
7029       gcc_assert (REG_P (tmp_gpr));
7030       emit_move_insn (dest, rs6000_adjust_vec_address (dest, src, element,
7031                                                        tmp_gpr, scalar_mode));
7032       return;
7033     }
7034
7035   else if (REG_P (src) || SUBREG_P (src))
7036     {
7037       int num_elements = GET_MODE_NUNITS (mode);
7038       int bits_in_element = mode_to_bits (GET_MODE_INNER (mode));
7039       int bit_shift = 7 - exact_log2 (num_elements);
7040       rtx element2;
7041       unsigned int dest_regno = reg_or_subregno (dest);
7042       unsigned int src_regno = reg_or_subregno (src);
7043       unsigned int element_regno = reg_or_subregno (element);
7044
7045       gcc_assert (REG_P (tmp_gpr));
7046
7047       /* See if we want to generate VEXTU{B,H,W}{L,R}X if the destination is in
7048          a general purpose register.  */
7049       if (TARGET_P9_VECTOR
7050           && (mode == V16QImode || mode == V8HImode || mode == V4SImode)
7051           && INT_REGNO_P (dest_regno)
7052           && ALTIVEC_REGNO_P (src_regno)
7053           && INT_REGNO_P (element_regno))
7054         {
7055           rtx dest_si = gen_rtx_REG (SImode, dest_regno);
7056           rtx element_si = gen_rtx_REG (SImode, element_regno);
7057
7058           if (mode == V16QImode)
7059             emit_insn (BYTES_BIG_ENDIAN
7060                        ? gen_vextublx (dest_si, element_si, src)
7061                        : gen_vextubrx (dest_si, element_si, src));
7062
7063           else if (mode == V8HImode)
7064             {
7065               rtx tmp_gpr_si = gen_rtx_REG (SImode, REGNO (tmp_gpr));
7066               emit_insn (gen_ashlsi3 (tmp_gpr_si, element_si, const1_rtx));
7067               emit_insn (BYTES_BIG_ENDIAN
7068                          ? gen_vextuhlx (dest_si, tmp_gpr_si, src)
7069                          : gen_vextuhrx (dest_si, tmp_gpr_si, src));
7070             }
7071
7072
7073           else
7074             {
7075               rtx tmp_gpr_si = gen_rtx_REG (SImode, REGNO (tmp_gpr));
7076               emit_insn (gen_ashlsi3 (tmp_gpr_si, element_si, const2_rtx));
7077               emit_insn (BYTES_BIG_ENDIAN
7078                          ? gen_vextuwlx (dest_si, tmp_gpr_si, src)
7079                          : gen_vextuwrx (dest_si, tmp_gpr_si, src));
7080             }
7081
7082           return;
7083         }
7084
7085
7086       gcc_assert (REG_P (tmp_altivec));
7087
7088       /* For little endian, adjust element ordering.  For V2DI/V2DF, we can use
7089          an XOR, otherwise we need to subtract.  The shift amount is so VSLO
7090          will shift the element into the upper position (adding 3 to convert a
7091          byte shift into a bit shift).  */
7092       if (scalar_size == 8)
7093         {
7094           if (!BYTES_BIG_ENDIAN)
7095             {
7096               emit_insn (gen_xordi3 (tmp_gpr, element, const1_rtx));
7097               element2 = tmp_gpr;
7098             }
7099           else
7100             element2 = element;
7101
7102           /* Generate RLDIC directly to shift left 6 bits and retrieve 1
7103              bit.  */
7104           emit_insn (gen_rtx_SET (tmp_gpr,
7105                                   gen_rtx_AND (DImode,
7106                                                gen_rtx_ASHIFT (DImode,
7107                                                                element2,
7108                                                                GEN_INT (6)),
7109                                                GEN_INT (64))));
7110         }
7111       else
7112         {
7113           if (!BYTES_BIG_ENDIAN)
7114             {
7115               rtx num_ele_m1 = GEN_INT (num_elements - 1);
7116
7117               emit_insn (gen_anddi3 (tmp_gpr, element, num_ele_m1));
7118               emit_insn (gen_subdi3 (tmp_gpr, num_ele_m1, tmp_gpr));
7119               element2 = tmp_gpr;
7120             }
7121           else
7122             element2 = element;
7123
7124           emit_insn (gen_ashldi3 (tmp_gpr, element2, GEN_INT (bit_shift)));
7125         }
7126
7127       /* Get the value into the lower byte of the Altivec register where VSLO
7128          expects it.  */
7129       if (TARGET_P9_VECTOR)
7130         emit_insn (gen_vsx_splat_v2di (tmp_altivec, tmp_gpr));
7131       else if (can_create_pseudo_p ())
7132         emit_insn (gen_vsx_concat_v2di (tmp_altivec, tmp_gpr, tmp_gpr));
7133       else
7134         {
7135           rtx tmp_di = gen_rtx_REG (DImode, REGNO (tmp_altivec));
7136           emit_move_insn (tmp_di, tmp_gpr);
7137           emit_insn (gen_vsx_concat_v2di (tmp_altivec, tmp_di, tmp_di));
7138         }
7139
7140       /* Do the VSLO to get the value into the final location.  */
7141       switch (mode)
7142         {
7143         case E_V2DFmode:
7144           emit_insn (gen_vsx_vslo_v2df (dest, src, tmp_altivec));
7145           return;
7146
7147         case E_V2DImode:
7148           emit_insn (gen_vsx_vslo_v2di (dest, src, tmp_altivec));
7149           return;
7150
7151         case E_V4SFmode:
7152           {
7153             rtx tmp_altivec_di = gen_rtx_REG (DImode, REGNO (tmp_altivec));
7154             rtx tmp_altivec_v4sf = gen_rtx_REG (V4SFmode, REGNO (tmp_altivec));
7155             rtx src_v2di = gen_rtx_REG (V2DImode, REGNO (src));
7156             emit_insn (gen_vsx_vslo_v2di (tmp_altivec_di, src_v2di,
7157                                           tmp_altivec));
7158
7159             emit_insn (gen_vsx_xscvspdp_scalar2 (dest, tmp_altivec_v4sf));
7160             return;
7161           }
7162
7163         case E_V4SImode:
7164         case E_V8HImode:
7165         case E_V16QImode:
7166           {
7167             rtx tmp_altivec_di = gen_rtx_REG (DImode, REGNO (tmp_altivec));
7168             rtx src_v2di = gen_rtx_REG (V2DImode, REGNO (src));
7169             rtx tmp_gpr_di = gen_rtx_REG (DImode, REGNO (dest));
7170             emit_insn (gen_vsx_vslo_v2di (tmp_altivec_di, src_v2di,
7171                                           tmp_altivec));
7172             emit_move_insn (tmp_gpr_di, tmp_altivec_di);
7173             emit_insn (gen_lshrdi3 (tmp_gpr_di, tmp_gpr_di,
7174                                     GEN_INT (64 - bits_in_element)));
7175             return;
7176           }
7177
7178         default:
7179           gcc_unreachable ();
7180         }
7181
7182       return;
7183     }
7184   else
7185     gcc_unreachable ();
7186  }
7187
7188 /* Return alignment of TYPE.  Existing alignment is ALIGN.  HOW
7189    selects whether the alignment is abi mandated, optional, or
7190    both abi and optional alignment.  */
7191    
7192 unsigned int
7193 rs6000_data_alignment (tree type, unsigned int align, enum data_align how)
7194 {
7195   if (how != align_opt)
7196     {
7197       if (TREE_CODE (type) == VECTOR_TYPE && align < 128)
7198         align = 128;
7199     }
7200
7201   if (how != align_abi)
7202     {
7203       if (TREE_CODE (type) == ARRAY_TYPE
7204           && TYPE_MODE (TREE_TYPE (type)) == QImode)
7205         {
7206           if (align < BITS_PER_WORD)
7207             align = BITS_PER_WORD;
7208         }
7209     }
7210
7211   return align;
7212 }
7213
7214 /* Implement TARGET_SLOW_UNALIGNED_ACCESS.  Altivec vector memory
7215    instructions simply ignore the low bits; VSX memory instructions
7216    are aligned to 4 or 8 bytes.  */
7217
7218 static bool
7219 rs6000_slow_unaligned_access (machine_mode mode, unsigned int align)
7220 {
7221   return (STRICT_ALIGNMENT
7222           || (!TARGET_EFFICIENT_UNALIGNED_VSX
7223               && ((SCALAR_FLOAT_MODE_NOT_VECTOR_P (mode) && align < 32)
7224                   || ((VECTOR_MODE_P (mode) || FLOAT128_VECTOR_P (mode))
7225                       && (int) align < VECTOR_ALIGN (mode)))));
7226 }
7227
7228 /* Previous GCC releases forced all vector types to have 16-byte alignment.  */
7229
7230 bool
7231 rs6000_special_adjust_field_align_p (tree type, unsigned int computed)
7232 {
7233   if (TARGET_ALTIVEC && TREE_CODE (type) == VECTOR_TYPE)
7234     {
7235       if (computed != 128)
7236         {
7237           static bool warned;
7238           if (!warned && warn_psabi)
7239             {
7240               warned = true;
7241               inform (input_location,
7242                       "the layout of aggregates containing vectors with"
7243                       " %d-byte alignment has changed in GCC 5",
7244                       computed / BITS_PER_UNIT);
7245             }
7246         }
7247       /* In current GCC there is no special case.  */
7248       return false;
7249     }
7250
7251   return false;
7252 }
7253
7254 /* AIX increases natural record alignment to doubleword if the first
7255    field is an FP double while the FP fields remain word aligned.  */
7256
7257 unsigned int
7258 rs6000_special_round_type_align (tree type, unsigned int computed,
7259                                  unsigned int specified)
7260 {
7261   unsigned int align = MAX (computed, specified);
7262   tree field = TYPE_FIELDS (type);
7263
7264   /* Skip all non field decls */
7265   while (field != NULL && TREE_CODE (field) != FIELD_DECL)
7266     field = DECL_CHAIN (field);
7267
7268   if (field != NULL && field != type)
7269     {
7270       type = TREE_TYPE (field);
7271       while (TREE_CODE (type) == ARRAY_TYPE)
7272         type = TREE_TYPE (type);
7273
7274       if (type != error_mark_node && TYPE_MODE (type) == DFmode)
7275         align = MAX (align, 64);
7276     }
7277
7278   return align;
7279 }
7280
7281 /* Darwin increases record alignment to the natural alignment of
7282    the first field.  */
7283
7284 unsigned int
7285 darwin_rs6000_special_round_type_align (tree type, unsigned int computed,
7286                                         unsigned int specified)
7287 {
7288   unsigned int align = MAX (computed, specified);
7289
7290   if (TYPE_PACKED (type))
7291     return align;
7292
7293   /* Find the first field, looking down into aggregates.  */
7294   do {
7295     tree field = TYPE_FIELDS (type);
7296     /* Skip all non field decls */
7297     while (field != NULL && TREE_CODE (field) != FIELD_DECL)
7298       field = DECL_CHAIN (field);
7299     if (! field)
7300       break;
7301     /* A packed field does not contribute any extra alignment.  */
7302     if (DECL_PACKED (field))
7303       return align;
7304     type = TREE_TYPE (field);
7305     while (TREE_CODE (type) == ARRAY_TYPE)
7306       type = TREE_TYPE (type);
7307   } while (AGGREGATE_TYPE_P (type));
7308
7309   if (! AGGREGATE_TYPE_P (type) && type != error_mark_node)
7310     align = MAX (align, TYPE_ALIGN (type));
7311
7312   return align;
7313 }
7314
7315 /* Return 1 for an operand in small memory on V.4/eabi.  */
7316
7317 int
7318 small_data_operand (rtx op ATTRIBUTE_UNUSED,
7319                     machine_mode mode ATTRIBUTE_UNUSED)
7320 {
7321 #if TARGET_ELF
7322   rtx sym_ref;
7323
7324   if (rs6000_sdata == SDATA_NONE || rs6000_sdata == SDATA_DATA)
7325     return 0;
7326
7327   if (DEFAULT_ABI != ABI_V4)
7328     return 0;
7329
7330   if (SYMBOL_REF_P (op))
7331     sym_ref = op;
7332
7333   else if (GET_CODE (op) != CONST
7334            || GET_CODE (XEXP (op, 0)) != PLUS
7335            || !SYMBOL_REF_P (XEXP (XEXP (op, 0), 0))
7336            || !CONST_INT_P (XEXP (XEXP (op, 0), 1)))
7337     return 0;
7338
7339   else
7340     {
7341       rtx sum = XEXP (op, 0);
7342       HOST_WIDE_INT summand;
7343
7344       /* We have to be careful here, because it is the referenced address
7345          that must be 32k from _SDA_BASE_, not just the symbol.  */
7346       summand = INTVAL (XEXP (sum, 1));
7347       if (summand < 0 || summand > g_switch_value)
7348         return 0;
7349
7350       sym_ref = XEXP (sum, 0);
7351     }
7352
7353   return SYMBOL_REF_SMALL_P (sym_ref);
7354 #else
7355   return 0;
7356 #endif
7357 }
7358
7359 /* Return true if either operand is a general purpose register.  */
7360
7361 bool
7362 gpr_or_gpr_p (rtx op0, rtx op1)
7363 {
7364   return ((REG_P (op0) && INT_REGNO_P (REGNO (op0)))
7365           || (REG_P (op1) && INT_REGNO_P (REGNO (op1))));
7366 }
7367
7368 /* Return true if this is a move direct operation between GPR registers and
7369    floating point/VSX registers.  */
7370
7371 bool
7372 direct_move_p (rtx op0, rtx op1)
7373 {
7374   if (!REG_P (op0) || !REG_P (op1))
7375     return false;
7376
7377   if (!TARGET_DIRECT_MOVE)
7378     return false;
7379
7380   int regno0 = REGNO (op0);
7381   int regno1 = REGNO (op1);
7382   if (!HARD_REGISTER_NUM_P (regno0) || !HARD_REGISTER_NUM_P (regno1))
7383     return false;
7384
7385   if (INT_REGNO_P (regno0) && VSX_REGNO_P (regno1))
7386     return true;
7387
7388   if (VSX_REGNO_P (regno0) && INT_REGNO_P (regno1))
7389     return true;
7390
7391   return false;
7392 }
7393
7394 /* Return true if the ADDR is an acceptable address for a quad memory
7395    operation of mode MODE (either LQ/STQ for general purpose registers, or
7396    LXV/STXV for vector registers under ISA 3.0.  GPR_P is true if this address
7397    is intended for LQ/STQ.  If it is false, the address is intended for the ISA
7398    3.0 LXV/STXV instruction.  */
7399
7400 bool
7401 quad_address_p (rtx addr, machine_mode mode, bool strict)
7402 {
7403   rtx op0, op1;
7404
7405   if (GET_MODE_SIZE (mode) != 16)
7406     return false;
7407
7408   if (legitimate_indirect_address_p (addr, strict))
7409     return true;
7410
7411   if (VECTOR_MODE_P (mode) && !mode_supports_dq_form (mode))
7412     return false;
7413
7414   if (GET_CODE (addr) != PLUS)
7415     return false;
7416
7417   op0 = XEXP (addr, 0);
7418   if (!REG_P (op0) || !INT_REG_OK_FOR_BASE_P (op0, strict))
7419     return false;
7420
7421   op1 = XEXP (addr, 1);
7422   if (!CONST_INT_P (op1))
7423     return false;
7424
7425   return quad_address_offset_p (INTVAL (op1));
7426 }
7427
7428 /* Return true if this is a load or store quad operation.  This function does
7429    not handle the atomic quad memory instructions.  */
7430
7431 bool
7432 quad_load_store_p (rtx op0, rtx op1)
7433 {
7434   bool ret;
7435
7436   if (!TARGET_QUAD_MEMORY)
7437     ret = false;
7438
7439   else if (REG_P (op0) && MEM_P (op1))
7440     ret = (quad_int_reg_operand (op0, GET_MODE (op0))
7441            && quad_memory_operand (op1, GET_MODE (op1))
7442            && !reg_overlap_mentioned_p (op0, op1));
7443
7444   else if (MEM_P (op0) && REG_P (op1))
7445     ret = (quad_memory_operand (op0, GET_MODE (op0))
7446            && quad_int_reg_operand (op1, GET_MODE (op1)));
7447
7448   else
7449     ret = false;
7450
7451   if (TARGET_DEBUG_ADDR)
7452     {
7453       fprintf (stderr, "\n========== quad_load_store, return %s\n",
7454                ret ? "true" : "false");
7455       debug_rtx (gen_rtx_SET (op0, op1));
7456     }
7457
7458   return ret;
7459 }
7460
7461 /* Given an address, return a constant offset term if one exists.  */
7462
7463 static rtx
7464 address_offset (rtx op)
7465 {
7466   if (GET_CODE (op) == PRE_INC
7467       || GET_CODE (op) == PRE_DEC)
7468     op = XEXP (op, 0);
7469   else if (GET_CODE (op) == PRE_MODIFY
7470            || GET_CODE (op) == LO_SUM)
7471     op = XEXP (op, 1);
7472
7473   if (GET_CODE (op) == CONST)
7474     op = XEXP (op, 0);
7475
7476   if (GET_CODE (op) == PLUS)
7477     op = XEXP (op, 1);
7478
7479   if (CONST_INT_P (op))
7480     return op;
7481
7482   return NULL_RTX;
7483 }
7484
7485 /* Return true if the MEM operand is a memory operand suitable for use
7486    with a (full width, possibly multiple) gpr load/store.  On
7487    powerpc64 this means the offset must be divisible by 4.
7488    Implements 'Y' constraint.
7489
7490    Accept direct, indexed, offset, lo_sum and tocref.  Since this is
7491    a constraint function we know the operand has satisfied a suitable
7492    memory predicate.
7493
7494    Offsetting a lo_sum should not be allowed, except where we know by
7495    alignment that a 32k boundary is not crossed.  Note that by
7496    "offsetting" here we mean a further offset to access parts of the
7497    MEM.  It's fine to have a lo_sum where the inner address is offset
7498    from a sym, since the same sym+offset will appear in the high part
7499    of the address calculation.  */
7500
7501 bool
7502 mem_operand_gpr (rtx op, machine_mode mode)
7503 {
7504   unsigned HOST_WIDE_INT offset;
7505   int extra;
7506   rtx addr = XEXP (op, 0);
7507
7508   /* PR85755: Allow PRE_INC and PRE_DEC addresses.  */
7509   if (TARGET_UPDATE
7510       && (GET_CODE (addr) == PRE_INC || GET_CODE (addr) == PRE_DEC)
7511       && mode_supports_pre_incdec_p (mode)
7512       && legitimate_indirect_address_p (XEXP (addr, 0), false))
7513     return true;
7514
7515   /* Don't allow non-offsettable addresses.  See PRs 83969 and 84279.  */
7516   if (!rs6000_offsettable_memref_p (op, mode, false))
7517     return false;
7518
7519   op = address_offset (addr);
7520   if (op == NULL_RTX)
7521     return true;
7522
7523   offset = INTVAL (op);
7524   if (TARGET_POWERPC64 && (offset & 3) != 0)
7525     return false;
7526
7527   extra = GET_MODE_SIZE (mode) - UNITS_PER_WORD;
7528   if (extra < 0)
7529     extra = 0;
7530
7531   if (GET_CODE (addr) == LO_SUM)
7532     /* For lo_sum addresses, we must allow any offset except one that
7533        causes a wrap, so test only the low 16 bits.  */
7534     offset = ((offset & 0xffff) ^ 0x8000) - 0x8000;
7535
7536   return offset + 0x8000 < 0x10000u - extra;
7537 }
7538
7539 /* As above, but for DS-FORM VSX insns.  Unlike mem_operand_gpr,
7540    enforce an offset divisible by 4 even for 32-bit.  */
7541
7542 bool
7543 mem_operand_ds_form (rtx op, machine_mode mode)
7544 {
7545   unsigned HOST_WIDE_INT offset;
7546   int extra;
7547   rtx addr = XEXP (op, 0);
7548
7549   if (!offsettable_address_p (false, mode, addr))
7550     return false;
7551
7552   op = address_offset (addr);
7553   if (op == NULL_RTX)
7554     return true;
7555
7556   offset = INTVAL (op);
7557   if ((offset & 3) != 0)
7558     return false;
7559
7560   extra = GET_MODE_SIZE (mode) - UNITS_PER_WORD;
7561   if (extra < 0)
7562     extra = 0;
7563
7564   if (GET_CODE (addr) == LO_SUM)
7565     /* For lo_sum addresses, we must allow any offset except one that
7566        causes a wrap, so test only the low 16 bits.  */
7567     offset = ((offset & 0xffff) ^ 0x8000) - 0x8000;
7568
7569   return offset + 0x8000 < 0x10000u - extra;
7570 }
7571 \f
7572 /* Subroutines of rs6000_legitimize_address and rs6000_legitimate_address_p.  */
7573
7574 static bool
7575 reg_offset_addressing_ok_p (machine_mode mode)
7576 {
7577   switch (mode)
7578     {
7579     case E_V16QImode:
7580     case E_V8HImode:
7581     case E_V4SFmode:
7582     case E_V4SImode:
7583     case E_V2DFmode:
7584     case E_V2DImode:
7585     case E_V1TImode:
7586     case E_TImode:
7587     case E_TFmode:
7588     case E_KFmode:
7589       /* AltiVec/VSX vector modes.  Only reg+reg addressing was valid until the
7590          ISA 3.0 vector d-form addressing mode was added.  While TImode is not
7591          a vector mode, if we want to use the VSX registers to move it around,
7592          we need to restrict ourselves to reg+reg addressing.  Similarly for
7593          IEEE 128-bit floating point that is passed in a single vector
7594          register.  */
7595       if (VECTOR_MEM_ALTIVEC_OR_VSX_P (mode))
7596         return mode_supports_dq_form (mode);
7597       break;
7598
7599     case E_SDmode:
7600       /* If we can do direct load/stores of SDmode, restrict it to reg+reg
7601          addressing for the LFIWZX and STFIWX instructions.  */
7602       if (TARGET_NO_SDMODE_STACK)
7603         return false;
7604       break;
7605
7606     default:
7607       break;
7608     }
7609
7610   return true;
7611 }
7612
7613 static bool
7614 virtual_stack_registers_memory_p (rtx op)
7615 {
7616   int regnum;
7617
7618   if (REG_P (op))
7619     regnum = REGNO (op);
7620
7621   else if (GET_CODE (op) == PLUS
7622            && REG_P (XEXP (op, 0))
7623            && CONST_INT_P (XEXP (op, 1)))
7624     regnum = REGNO (XEXP (op, 0));
7625
7626   else
7627     return false;
7628
7629   return (regnum >= FIRST_VIRTUAL_REGISTER
7630           && regnum <= LAST_VIRTUAL_POINTER_REGISTER);
7631 }
7632
7633 /* Return true if a MODE sized memory accesses to OP plus OFFSET
7634    is known to not straddle a 32k boundary.  This function is used
7635    to determine whether -mcmodel=medium code can use TOC pointer
7636    relative addressing for OP.  This means the alignment of the TOC
7637    pointer must also be taken into account, and unfortunately that is
7638    only 8 bytes.  */ 
7639
7640 #ifndef POWERPC64_TOC_POINTER_ALIGNMENT
7641 #define POWERPC64_TOC_POINTER_ALIGNMENT 8
7642 #endif
7643
7644 static bool
7645 offsettable_ok_by_alignment (rtx op, HOST_WIDE_INT offset,
7646                              machine_mode mode)
7647 {
7648   tree decl;
7649   unsigned HOST_WIDE_INT dsize, dalign, lsb, mask;
7650
7651   if (!SYMBOL_REF_P (op))
7652     return false;
7653
7654   /* ISA 3.0 vector d-form addressing is restricted, don't allow
7655      SYMBOL_REF.  */
7656   if (mode_supports_dq_form (mode))
7657     return false;
7658
7659   dsize = GET_MODE_SIZE (mode);
7660   decl = SYMBOL_REF_DECL (op);
7661   if (!decl)
7662     {
7663       if (dsize == 0)
7664         return false;
7665
7666       /* -fsection-anchors loses the original SYMBOL_REF_DECL when
7667          replacing memory addresses with an anchor plus offset.  We
7668          could find the decl by rummaging around in the block->objects
7669          VEC for the given offset but that seems like too much work.  */
7670       dalign = BITS_PER_UNIT;
7671       if (SYMBOL_REF_HAS_BLOCK_INFO_P (op)
7672           && SYMBOL_REF_ANCHOR_P (op)
7673           && SYMBOL_REF_BLOCK (op) != NULL)
7674         {
7675           struct object_block *block = SYMBOL_REF_BLOCK (op);
7676
7677           dalign = block->alignment;
7678           offset += SYMBOL_REF_BLOCK_OFFSET (op);
7679         }
7680       else if (CONSTANT_POOL_ADDRESS_P (op))
7681         {
7682           /* It would be nice to have get_pool_align()..  */
7683           machine_mode cmode = get_pool_mode (op);
7684
7685           dalign = GET_MODE_ALIGNMENT (cmode);
7686         }
7687     }
7688   else if (DECL_P (decl))
7689     {
7690       dalign = DECL_ALIGN (decl);
7691
7692       if (dsize == 0)
7693         {
7694           /* Allow BLKmode when the entire object is known to not
7695              cross a 32k boundary.  */
7696           if (!DECL_SIZE_UNIT (decl))
7697             return false;
7698
7699           if (!tree_fits_uhwi_p (DECL_SIZE_UNIT (decl)))
7700             return false;
7701
7702           dsize = tree_to_uhwi (DECL_SIZE_UNIT (decl));
7703           if (dsize > 32768)
7704             return false;
7705
7706           dalign /= BITS_PER_UNIT;
7707           if (dalign > POWERPC64_TOC_POINTER_ALIGNMENT)
7708             dalign = POWERPC64_TOC_POINTER_ALIGNMENT;
7709           return dalign >= dsize;
7710         }
7711     }
7712   else
7713     gcc_unreachable ();
7714
7715   /* Find how many bits of the alignment we know for this access.  */
7716   dalign /= BITS_PER_UNIT;
7717   if (dalign > POWERPC64_TOC_POINTER_ALIGNMENT)
7718     dalign = POWERPC64_TOC_POINTER_ALIGNMENT;
7719   mask = dalign - 1;
7720   lsb = offset & -offset;
7721   mask &= lsb - 1;
7722   dalign = mask + 1;
7723
7724   return dalign >= dsize;
7725 }
7726
7727 static bool
7728 constant_pool_expr_p (rtx op)
7729 {
7730   rtx base, offset;
7731
7732   split_const (op, &base, &offset);
7733   return (SYMBOL_REF_P (base)
7734           && CONSTANT_POOL_ADDRESS_P (base)
7735           && ASM_OUTPUT_SPECIAL_POOL_ENTRY_P (get_pool_constant (base), Pmode));
7736 }
7737
7738 /* Create a TOC reference for symbol_ref SYMBOL.  If LARGETOC_REG is non-null,
7739    use that as the register to put the HIGH value into if register allocation
7740    is already done.  */
7741
7742 rtx
7743 create_TOC_reference (rtx symbol, rtx largetoc_reg)
7744 {
7745   rtx tocrel, tocreg, hi;
7746
7747   if (TARGET_DEBUG_ADDR)
7748     {
7749       if (SYMBOL_REF_P (symbol))
7750         fprintf (stderr, "\ncreate_TOC_reference, (symbol_ref %s)\n",
7751                  XSTR (symbol, 0));
7752       else
7753         {
7754           fprintf (stderr, "\ncreate_TOC_reference, code %s:\n",
7755                    GET_RTX_NAME (GET_CODE (symbol)));
7756           debug_rtx (symbol);
7757         }
7758     }
7759
7760   if (!can_create_pseudo_p ())
7761     df_set_regs_ever_live (TOC_REGISTER, true);
7762
7763   tocreg = gen_rtx_REG (Pmode, TOC_REGISTER);
7764   tocrel = gen_rtx_UNSPEC (Pmode, gen_rtvec (2, symbol, tocreg), UNSPEC_TOCREL);
7765   if (TARGET_CMODEL == CMODEL_SMALL || can_create_pseudo_p ())
7766     return tocrel;
7767
7768   hi = gen_rtx_HIGH (Pmode, copy_rtx (tocrel));
7769   if (largetoc_reg != NULL)
7770     {
7771       emit_move_insn (largetoc_reg, hi);
7772       hi = largetoc_reg;
7773     }
7774   return gen_rtx_LO_SUM (Pmode, hi, tocrel);
7775 }
7776
7777 /* These are only used to pass through from print_operand/print_operand_address
7778    to rs6000_output_addr_const_extra over the intervening function
7779    output_addr_const which is not target code.  */
7780 static const_rtx tocrel_base_oac, tocrel_offset_oac;
7781
7782 /* Return true if OP is a toc pointer relative address (the output
7783    of create_TOC_reference).  If STRICT, do not match non-split
7784    -mcmodel=large/medium toc pointer relative addresses.  If the pointers 
7785    are non-NULL, place base and offset pieces in TOCREL_BASE_RET and 
7786    TOCREL_OFFSET_RET respectively.  */
7787
7788 bool
7789 toc_relative_expr_p (const_rtx op, bool strict, const_rtx *tocrel_base_ret,
7790                      const_rtx *tocrel_offset_ret)
7791 {
7792   if (!TARGET_TOC)
7793     return false;
7794
7795   if (TARGET_CMODEL != CMODEL_SMALL)
7796     {
7797       /* When strict ensure we have everything tidy.  */
7798       if (strict
7799           && !(GET_CODE (op) == LO_SUM
7800                && REG_P (XEXP (op, 0))
7801                && INT_REG_OK_FOR_BASE_P (XEXP (op, 0), strict)))
7802         return false;
7803
7804       /* When not strict, allow non-split TOC addresses and also allow
7805          (lo_sum (high ..)) TOC addresses created during reload.  */
7806       if (GET_CODE (op) == LO_SUM)
7807         op = XEXP (op, 1);
7808     }
7809
7810   const_rtx tocrel_base = op;
7811   const_rtx tocrel_offset = const0_rtx;
7812
7813   if (GET_CODE (op) == PLUS && add_cint_operand (XEXP (op, 1), GET_MODE (op)))
7814     {
7815       tocrel_base = XEXP (op, 0);
7816       tocrel_offset = XEXP (op, 1);
7817     }
7818
7819   if (tocrel_base_ret)
7820     *tocrel_base_ret = tocrel_base;
7821   if (tocrel_offset_ret)
7822     *tocrel_offset_ret = tocrel_offset;
7823
7824   return (GET_CODE (tocrel_base) == UNSPEC
7825           && XINT (tocrel_base, 1) == UNSPEC_TOCREL
7826           && REG_P (XVECEXP (tocrel_base, 0, 1))
7827           && REGNO (XVECEXP (tocrel_base, 0, 1)) == TOC_REGISTER);
7828 }
7829
7830 /* Return true if X is a constant pool address, and also for cmodel=medium
7831    if X is a toc-relative address known to be offsettable within MODE.  */
7832
7833 bool
7834 legitimate_constant_pool_address_p (const_rtx x, machine_mode mode,
7835                                     bool strict)
7836 {
7837   const_rtx tocrel_base, tocrel_offset;
7838   return (toc_relative_expr_p (x, strict, &tocrel_base, &tocrel_offset)
7839           && (TARGET_CMODEL != CMODEL_MEDIUM
7840               || constant_pool_expr_p (XVECEXP (tocrel_base, 0, 0))
7841               || mode == QImode
7842               || offsettable_ok_by_alignment (XVECEXP (tocrel_base, 0, 0),
7843                                               INTVAL (tocrel_offset), mode)));
7844 }
7845
7846 static bool
7847 legitimate_small_data_p (machine_mode mode, rtx x)
7848 {
7849   return (DEFAULT_ABI == ABI_V4
7850           && !flag_pic && !TARGET_TOC
7851           && (SYMBOL_REF_P (x) || GET_CODE (x) == CONST)
7852           && small_data_operand (x, mode));
7853 }
7854
7855 bool
7856 rs6000_legitimate_offset_address_p (machine_mode mode, rtx x,
7857                                     bool strict, bool worst_case)
7858 {
7859   unsigned HOST_WIDE_INT offset;
7860   unsigned int extra;
7861
7862   if (GET_CODE (x) != PLUS)
7863     return false;
7864   if (!REG_P (XEXP (x, 0)))
7865     return false;
7866   if (!INT_REG_OK_FOR_BASE_P (XEXP (x, 0), strict))
7867     return false;
7868   if (mode_supports_dq_form (mode))
7869     return quad_address_p (x, mode, strict);
7870   if (!reg_offset_addressing_ok_p (mode))
7871     return virtual_stack_registers_memory_p (x);
7872   if (legitimate_constant_pool_address_p (x, mode, strict || lra_in_progress))
7873     return true;
7874   if (!CONST_INT_P (XEXP (x, 1)))
7875     return false;
7876
7877   offset = INTVAL (XEXP (x, 1));
7878   extra = 0;
7879   switch (mode)
7880     {
7881     case E_DFmode:
7882     case E_DDmode:
7883     case E_DImode:
7884       /* If we are using VSX scalar loads, restrict ourselves to reg+reg
7885          addressing.  */
7886       if (VECTOR_MEM_VSX_P (mode))
7887         return false;
7888
7889       if (!worst_case)
7890         break;
7891       if (!TARGET_POWERPC64)
7892         extra = 4;
7893       else if (offset & 3)
7894         return false;
7895       break;
7896
7897     case E_TFmode:
7898     case E_IFmode:
7899     case E_KFmode:
7900     case E_TDmode:
7901     case E_TImode:
7902     case E_PTImode:
7903       extra = 8;
7904       if (!worst_case)
7905         break;
7906       if (!TARGET_POWERPC64)
7907         extra = 12;
7908       else if (offset & 3)
7909         return false;
7910       break;
7911
7912     default:
7913       break;
7914     }
7915
7916   offset += 0x8000;
7917   return offset < 0x10000 - extra;
7918 }
7919
7920 bool
7921 legitimate_indexed_address_p (rtx x, int strict)
7922 {
7923   rtx op0, op1;
7924
7925   if (GET_CODE (x) != PLUS)
7926     return false;
7927
7928   op0 = XEXP (x, 0);
7929   op1 = XEXP (x, 1);
7930
7931   return (REG_P (op0) && REG_P (op1)
7932           && ((INT_REG_OK_FOR_BASE_P (op0, strict)
7933                && INT_REG_OK_FOR_INDEX_P (op1, strict))
7934               || (INT_REG_OK_FOR_BASE_P (op1, strict)
7935                   && INT_REG_OK_FOR_INDEX_P (op0, strict))));
7936 }
7937
7938 bool
7939 avoiding_indexed_address_p (machine_mode mode)
7940 {
7941   /* Avoid indexed addressing for modes that have non-indexed
7942      load/store instruction forms.  */
7943   return (TARGET_AVOID_XFORM && VECTOR_MEM_NONE_P (mode));
7944 }
7945
7946 bool
7947 legitimate_indirect_address_p (rtx x, int strict)
7948 {
7949   return REG_P (x) && INT_REG_OK_FOR_BASE_P (x, strict);
7950 }
7951
7952 bool
7953 macho_lo_sum_memory_operand (rtx x, machine_mode mode)
7954 {
7955   if (!TARGET_MACHO || !flag_pic
7956       || mode != SImode || !MEM_P (x))
7957     return false;
7958   x = XEXP (x, 0);
7959
7960   if (GET_CODE (x) != LO_SUM)
7961     return false;
7962   if (!REG_P (XEXP (x, 0)))
7963     return false;
7964   if (!INT_REG_OK_FOR_BASE_P (XEXP (x, 0), 0))
7965     return false;
7966   x = XEXP (x, 1);
7967
7968   return CONSTANT_P (x);
7969 }
7970
7971 static bool
7972 legitimate_lo_sum_address_p (machine_mode mode, rtx x, int strict)
7973 {
7974   if (GET_CODE (x) != LO_SUM)
7975     return false;
7976   if (!REG_P (XEXP (x, 0)))
7977     return false;
7978   if (!INT_REG_OK_FOR_BASE_P (XEXP (x, 0), strict))
7979     return false;
7980   /* quad word addresses are restricted, and we can't use LO_SUM.  */
7981   if (mode_supports_dq_form (mode))
7982     return false;
7983   x = XEXP (x, 1);
7984
7985   if (TARGET_ELF || TARGET_MACHO)
7986     {
7987       bool large_toc_ok;
7988
7989       if (DEFAULT_ABI == ABI_V4 && flag_pic)
7990         return false;
7991       /* LRA doesn't use LEGITIMIZE_RELOAD_ADDRESS as it usually calls
7992          push_reload from reload pass code.  LEGITIMIZE_RELOAD_ADDRESS
7993          recognizes some LO_SUM addresses as valid although this
7994          function says opposite.  In most cases, LRA through different
7995          transformations can generate correct code for address reloads.
7996          It cannot manage only some LO_SUM cases.  So we need to add
7997          code here saying that some addresses are still valid.  */
7998       large_toc_ok = (lra_in_progress && TARGET_CMODEL != CMODEL_SMALL
7999                       && small_toc_ref (x, VOIDmode));
8000       if (TARGET_TOC && ! large_toc_ok)
8001         return false;
8002       if (GET_MODE_NUNITS (mode) != 1)
8003         return false;
8004       if (GET_MODE_SIZE (mode) > UNITS_PER_WORD
8005           && !(/* ??? Assume floating point reg based on mode?  */
8006                TARGET_HARD_FLOAT && (mode == DFmode || mode == DDmode)))
8007         return false;
8008
8009       return CONSTANT_P (x) || large_toc_ok;
8010     }
8011
8012   return false;
8013 }
8014
8015
8016 /* Try machine-dependent ways of modifying an illegitimate address
8017    to be legitimate.  If we find one, return the new, valid address.
8018    This is used from only one place: `memory_address' in explow.c.
8019
8020    OLDX is the address as it was before break_out_memory_refs was
8021    called.  In some cases it is useful to look at this to decide what
8022    needs to be done.
8023
8024    It is always safe for this function to do nothing.  It exists to
8025    recognize opportunities to optimize the output.
8026
8027    On RS/6000, first check for the sum of a register with a constant
8028    integer that is out of range.  If so, generate code to add the
8029    constant with the low-order 16 bits masked to the register and force
8030    this result into another register (this can be done with `cau').
8031    Then generate an address of REG+(CONST&0xffff), allowing for the
8032    possibility of bit 16 being a one.
8033
8034    Then check for the sum of a register and something not constant, try to
8035    load the other things into a register and return the sum.  */
8036
8037 static rtx
8038 rs6000_legitimize_address (rtx x, rtx oldx ATTRIBUTE_UNUSED,
8039                            machine_mode mode)
8040 {
8041   unsigned int extra;
8042
8043   if (!reg_offset_addressing_ok_p (mode)
8044       || mode_supports_dq_form (mode))
8045     {
8046       if (virtual_stack_registers_memory_p (x))
8047         return x;
8048
8049       /* In theory we should not be seeing addresses of the form reg+0,
8050          but just in case it is generated, optimize it away.  */
8051       if (GET_CODE (x) == PLUS && XEXP (x, 1) == const0_rtx)
8052         return force_reg (Pmode, XEXP (x, 0));
8053
8054       /* For TImode with load/store quad, restrict addresses to just a single
8055          pointer, so it works with both GPRs and VSX registers.  */
8056       /* Make sure both operands are registers.  */
8057       else if (GET_CODE (x) == PLUS
8058                && (mode != TImode || !TARGET_VSX))
8059         return gen_rtx_PLUS (Pmode,
8060                              force_reg (Pmode, XEXP (x, 0)),
8061                              force_reg (Pmode, XEXP (x, 1)));
8062       else
8063         return force_reg (Pmode, x);
8064     }
8065   if (SYMBOL_REF_P (x))
8066     {
8067       enum tls_model model = SYMBOL_REF_TLS_MODEL (x);
8068       if (model != 0)
8069         return rs6000_legitimize_tls_address (x, model);
8070     }
8071
8072   extra = 0;
8073   switch (mode)
8074     {
8075     case E_TFmode:
8076     case E_TDmode:
8077     case E_TImode:
8078     case E_PTImode:
8079     case E_IFmode:
8080     case E_KFmode:
8081       /* As in legitimate_offset_address_p we do not assume
8082          worst-case.  The mode here is just a hint as to the registers
8083          used.  A TImode is usually in gprs, but may actually be in
8084          fprs.  Leave worst-case scenario for reload to handle via
8085          insn constraints.  PTImode is only GPRs.  */
8086       extra = 8;
8087       break;
8088     default:
8089       break;
8090     }
8091
8092   if (GET_CODE (x) == PLUS
8093       && REG_P (XEXP (x, 0))
8094       && CONST_INT_P (XEXP (x, 1))
8095       && ((unsigned HOST_WIDE_INT) (INTVAL (XEXP (x, 1)) + 0x8000)
8096           >= 0x10000 - extra))
8097     {
8098       HOST_WIDE_INT high_int, low_int;
8099       rtx sum;
8100       low_int = ((INTVAL (XEXP (x, 1)) & 0xffff) ^ 0x8000) - 0x8000;
8101       if (low_int >= 0x8000 - extra)
8102         low_int = 0;
8103       high_int = INTVAL (XEXP (x, 1)) - low_int;
8104       sum = force_operand (gen_rtx_PLUS (Pmode, XEXP (x, 0),
8105                                          GEN_INT (high_int)), 0);
8106       return plus_constant (Pmode, sum, low_int);
8107     }
8108   else if (GET_CODE (x) == PLUS
8109            && REG_P (XEXP (x, 0))
8110            && !CONST_INT_P (XEXP (x, 1))
8111            && GET_MODE_NUNITS (mode) == 1
8112            && (GET_MODE_SIZE (mode) <= UNITS_PER_WORD
8113                || (/* ??? Assume floating point reg based on mode?  */
8114                    TARGET_HARD_FLOAT && (mode == DFmode || mode == DDmode)))
8115            && !avoiding_indexed_address_p (mode))
8116     {
8117       return gen_rtx_PLUS (Pmode, XEXP (x, 0),
8118                            force_reg (Pmode, force_operand (XEXP (x, 1), 0)));
8119     }
8120   else if ((TARGET_ELF
8121 #if TARGET_MACHO
8122             || !MACHO_DYNAMIC_NO_PIC_P
8123 #endif
8124             )
8125            && TARGET_32BIT
8126            && TARGET_NO_TOC
8127            && !flag_pic
8128            && !CONST_INT_P (x)
8129            && !CONST_WIDE_INT_P (x)
8130            && !CONST_DOUBLE_P (x)
8131            && CONSTANT_P (x)
8132            && GET_MODE_NUNITS (mode) == 1
8133            && (GET_MODE_SIZE (mode) <= UNITS_PER_WORD
8134                || (/* ??? Assume floating point reg based on mode?  */
8135                    TARGET_HARD_FLOAT && (mode == DFmode || mode == DDmode))))
8136     {
8137       rtx reg = gen_reg_rtx (Pmode);
8138       if (TARGET_ELF)
8139         emit_insn (gen_elf_high (reg, x));
8140       else
8141         emit_insn (gen_macho_high (reg, x));
8142       return gen_rtx_LO_SUM (Pmode, reg, x);
8143     }
8144   else if (TARGET_TOC
8145            && SYMBOL_REF_P (x)
8146            && constant_pool_expr_p (x)
8147            && ASM_OUTPUT_SPECIAL_POOL_ENTRY_P (get_pool_constant (x), Pmode))
8148     return create_TOC_reference (x, NULL_RTX);
8149   else
8150     return x;
8151 }
8152
8153 /* Debug version of rs6000_legitimize_address.  */
8154 static rtx
8155 rs6000_debug_legitimize_address (rtx x, rtx oldx, machine_mode mode)
8156 {
8157   rtx ret;
8158   rtx_insn *insns;
8159
8160   start_sequence ();
8161   ret = rs6000_legitimize_address (x, oldx, mode);
8162   insns = get_insns ();
8163   end_sequence ();
8164
8165   if (ret != x)
8166     {
8167       fprintf (stderr,
8168                "\nrs6000_legitimize_address: mode %s, old code %s, "
8169                "new code %s, modified\n",
8170                GET_MODE_NAME (mode), GET_RTX_NAME (GET_CODE (x)),
8171                GET_RTX_NAME (GET_CODE (ret)));
8172
8173       fprintf (stderr, "Original address:\n");
8174       debug_rtx (x);
8175
8176       fprintf (stderr, "oldx:\n");
8177       debug_rtx (oldx);
8178
8179       fprintf (stderr, "New address:\n");
8180       debug_rtx (ret);
8181
8182       if (insns)
8183         {
8184           fprintf (stderr, "Insns added:\n");
8185           debug_rtx_list (insns, 20);
8186         }
8187     }
8188   else
8189     {
8190       fprintf (stderr,
8191                "\nrs6000_legitimize_address: mode %s, code %s, no change:\n",
8192                GET_MODE_NAME (mode), GET_RTX_NAME (GET_CODE (x)));
8193
8194       debug_rtx (x);
8195     }
8196
8197   if (insns)
8198     emit_insn (insns);
8199
8200   return ret;
8201 }
8202
8203 /* This is called from dwarf2out.c via TARGET_ASM_OUTPUT_DWARF_DTPREL.
8204    We need to emit DTP-relative relocations.  */
8205
8206 static void rs6000_output_dwarf_dtprel (FILE *, int, rtx) ATTRIBUTE_UNUSED;
8207 static void
8208 rs6000_output_dwarf_dtprel (FILE *file, int size, rtx x)
8209 {
8210   switch (size)
8211     {
8212     case 4:
8213       fputs ("\t.long\t", file);
8214       break;
8215     case 8:
8216       fputs (DOUBLE_INT_ASM_OP, file);
8217       break;
8218     default:
8219       gcc_unreachable ();
8220     }
8221   output_addr_const (file, x);
8222   if (TARGET_ELF)
8223     fputs ("@dtprel+0x8000", file);
8224   else if (TARGET_XCOFF && SYMBOL_REF_P (x))
8225     {
8226       switch (SYMBOL_REF_TLS_MODEL (x))
8227         {
8228         case 0:
8229           break;
8230         case TLS_MODEL_LOCAL_EXEC:
8231           fputs ("@le", file);
8232           break;
8233         case TLS_MODEL_INITIAL_EXEC:
8234           fputs ("@ie", file);
8235           break;
8236         case TLS_MODEL_GLOBAL_DYNAMIC:
8237         case TLS_MODEL_LOCAL_DYNAMIC:
8238           fputs ("@m", file);
8239           break;
8240         default:
8241           gcc_unreachable ();
8242         }
8243     }
8244 }
8245
8246 /* Return true if X is a symbol that refers to real (rather than emulated)
8247    TLS.  */
8248
8249 static bool
8250 rs6000_real_tls_symbol_ref_p (rtx x)
8251 {
8252   return (SYMBOL_REF_P (x)
8253           && SYMBOL_REF_TLS_MODEL (x) >= TLS_MODEL_REAL);
8254 }
8255
8256 /* In the name of slightly smaller debug output, and to cater to
8257    general assembler lossage, recognize various UNSPEC sequences
8258    and turn them back into a direct symbol reference.  */
8259
8260 static rtx
8261 rs6000_delegitimize_address (rtx orig_x)
8262 {
8263   rtx x, y, offset;
8264
8265   if (GET_CODE (orig_x) == UNSPEC && XINT (orig_x, 1) == UNSPEC_FUSION_GPR)
8266     orig_x = XVECEXP (orig_x, 0, 0);
8267
8268   orig_x = delegitimize_mem_from_attrs (orig_x);
8269
8270   x = orig_x;
8271   if (MEM_P (x))
8272     x = XEXP (x, 0);
8273
8274   y = x;
8275   if (TARGET_CMODEL != CMODEL_SMALL && GET_CODE (y) == LO_SUM)
8276     y = XEXP (y, 1);
8277
8278   offset = NULL_RTX;
8279   if (GET_CODE (y) == PLUS
8280       && GET_MODE (y) == Pmode
8281       && CONST_INT_P (XEXP (y, 1)))
8282     {
8283       offset = XEXP (y, 1);
8284       y = XEXP (y, 0);
8285     }
8286
8287   if (GET_CODE (y) == UNSPEC && XINT (y, 1) == UNSPEC_TOCREL)
8288     {
8289       y = XVECEXP (y, 0, 0);
8290
8291 #ifdef HAVE_AS_TLS
8292       /* Do not associate thread-local symbols with the original
8293          constant pool symbol.  */
8294       if (TARGET_XCOFF
8295           && SYMBOL_REF_P (y)
8296           && CONSTANT_POOL_ADDRESS_P (y)
8297           && rs6000_real_tls_symbol_ref_p (get_pool_constant (y)))
8298         return orig_x;
8299 #endif
8300
8301       if (offset != NULL_RTX)
8302         y = gen_rtx_PLUS (Pmode, y, offset);
8303       if (!MEM_P (orig_x))
8304         return y;
8305       else
8306         return replace_equiv_address_nv (orig_x, y);
8307     }
8308
8309   if (TARGET_MACHO
8310       && GET_CODE (orig_x) == LO_SUM
8311       && GET_CODE (XEXP (orig_x, 1)) == CONST)
8312     {
8313       y = XEXP (XEXP (orig_x, 1), 0);
8314       if (GET_CODE (y) == UNSPEC && XINT (y, 1) == UNSPEC_MACHOPIC_OFFSET)
8315         return XVECEXP (y, 0, 0);
8316     }
8317
8318   return orig_x;
8319 }
8320
8321 /* Return true if X shouldn't be emitted into the debug info.
8322    The linker doesn't like .toc section references from
8323    .debug_* sections, so reject .toc section symbols.  */
8324
8325 static bool
8326 rs6000_const_not_ok_for_debug_p (rtx x)
8327 {
8328   if (GET_CODE (x) == UNSPEC)
8329     return true;
8330   if (SYMBOL_REF_P (x)
8331       && CONSTANT_POOL_ADDRESS_P (x))
8332     {
8333       rtx c = get_pool_constant (x);
8334       machine_mode cmode = get_pool_mode (x);
8335       if (ASM_OUTPUT_SPECIAL_POOL_ENTRY_P (c, cmode))
8336         return true;
8337     }
8338
8339   return false;
8340 }
8341
8342 /* Implement the TARGET_LEGITIMATE_COMBINED_INSN hook.  */
8343
8344 static bool
8345 rs6000_legitimate_combined_insn (rtx_insn *insn)
8346 {
8347   int icode = INSN_CODE (insn);
8348
8349   /* Reject creating doloop insns.  Combine should not be allowed
8350      to create these for a number of reasons:
8351      1) In a nested loop, if combine creates one of these in an
8352      outer loop and the register allocator happens to allocate ctr
8353      to the outer loop insn, then the inner loop can't use ctr.
8354      Inner loops ought to be more highly optimized.
8355      2) Combine often wants to create one of these from what was
8356      originally a three insn sequence, first combining the three
8357      insns to two, then to ctrsi/ctrdi.  When ctrsi/ctrdi is not
8358      allocated ctr, the splitter takes use back to the three insn
8359      sequence.  It's better to stop combine at the two insn
8360      sequence.
8361      3) Faced with not being able to allocate ctr for ctrsi/crtdi
8362      insns, the register allocator sometimes uses floating point
8363      or vector registers for the pseudo.  Since ctrsi/ctrdi is a
8364      jump insn and output reloads are not implemented for jumps,
8365      the ctrsi/ctrdi splitters need to handle all possible cases.
8366      That's a pain, and it gets to be seriously difficult when a
8367      splitter that runs after reload needs memory to transfer from
8368      a gpr to fpr.  See PR70098 and PR71763 which are not fixed
8369      for the difficult case.  It's better to not create problems
8370      in the first place.  */
8371   if (icode != CODE_FOR_nothing
8372       && (icode == CODE_FOR_bdz_si
8373           || icode == CODE_FOR_bdz_di
8374           || icode == CODE_FOR_bdnz_si
8375           || icode == CODE_FOR_bdnz_di
8376           || icode == CODE_FOR_bdztf_si
8377           || icode == CODE_FOR_bdztf_di
8378           || icode == CODE_FOR_bdnztf_si
8379           || icode == CODE_FOR_bdnztf_di))
8380     return false;
8381
8382   return true;
8383 }
8384
8385 /* Construct the SYMBOL_REF for the tls_get_addr function.  */
8386
8387 static GTY(()) rtx rs6000_tls_symbol;
8388 static rtx
8389 rs6000_tls_get_addr (void)
8390 {
8391   if (!rs6000_tls_symbol)
8392     rs6000_tls_symbol = init_one_libfunc ("__tls_get_addr");
8393
8394   return rs6000_tls_symbol;
8395 }
8396
8397 /* Construct the SYMBOL_REF for TLS GOT references.  */
8398
8399 static GTY(()) rtx rs6000_got_symbol;
8400 rtx
8401 rs6000_got_sym (void)
8402 {
8403   if (!rs6000_got_symbol)
8404     {
8405       rs6000_got_symbol = gen_rtx_SYMBOL_REF (Pmode, "_GLOBAL_OFFSET_TABLE_");
8406       SYMBOL_REF_FLAGS (rs6000_got_symbol) |= SYMBOL_FLAG_LOCAL;
8407       SYMBOL_REF_FLAGS (rs6000_got_symbol) |= SYMBOL_FLAG_EXTERNAL;
8408     }
8409
8410   return rs6000_got_symbol;
8411 }
8412
8413 /* AIX Thread-Local Address support.  */
8414
8415 static rtx
8416 rs6000_legitimize_tls_address_aix (rtx addr, enum tls_model model)
8417 {
8418   rtx sym, mem, tocref, tlsreg, tmpreg, dest, tlsaddr;
8419   const char *name;
8420   char *tlsname;
8421
8422   name = XSTR (addr, 0);
8423   /* Append TLS CSECT qualifier, unless the symbol already is qualified
8424      or the symbol will be in TLS private data section.  */
8425   if (name[strlen (name) - 1] != ']'
8426       && (TREE_PUBLIC (SYMBOL_REF_DECL (addr))
8427           || bss_initializer_p (SYMBOL_REF_DECL (addr))))
8428     {
8429       tlsname = XALLOCAVEC (char, strlen (name) + 4);
8430       strcpy (tlsname, name);
8431       strcat (tlsname,
8432               bss_initializer_p (SYMBOL_REF_DECL (addr)) ? "[UL]" : "[TL]");
8433       tlsaddr = copy_rtx (addr);
8434       XSTR (tlsaddr, 0) = ggc_strdup (tlsname);
8435     }
8436   else
8437     tlsaddr = addr;
8438
8439   /* Place addr into TOC constant pool.  */
8440   sym = force_const_mem (GET_MODE (tlsaddr), tlsaddr);
8441
8442   /* Output the TOC entry and create the MEM referencing the value.  */
8443   if (constant_pool_expr_p (XEXP (sym, 0))
8444       && ASM_OUTPUT_SPECIAL_POOL_ENTRY_P (get_pool_constant (XEXP (sym, 0)), Pmode))
8445     {
8446       tocref = create_TOC_reference (XEXP (sym, 0), NULL_RTX);
8447       mem = gen_const_mem (Pmode, tocref);
8448       set_mem_alias_set (mem, get_TOC_alias_set ());
8449     }
8450   else
8451     return sym;
8452
8453   /* Use global-dynamic for local-dynamic.  */
8454   if (model == TLS_MODEL_GLOBAL_DYNAMIC
8455       || model == TLS_MODEL_LOCAL_DYNAMIC)
8456     {
8457       /* Create new TOC reference for @m symbol.  */
8458       name = XSTR (XVECEXP (XEXP (mem, 0), 0, 0), 0);
8459       tlsname = XALLOCAVEC (char, strlen (name) + 1);
8460       strcpy (tlsname, "*LCM");
8461       strcat (tlsname, name + 3);
8462       rtx modaddr = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (tlsname));
8463       SYMBOL_REF_FLAGS (modaddr) |= SYMBOL_FLAG_LOCAL;
8464       tocref = create_TOC_reference (modaddr, NULL_RTX);
8465       rtx modmem = gen_const_mem (Pmode, tocref);
8466       set_mem_alias_set (modmem, get_TOC_alias_set ());
8467       
8468       rtx modreg = gen_reg_rtx (Pmode);
8469       emit_insn (gen_rtx_SET (modreg, modmem));
8470
8471       tmpreg = gen_reg_rtx (Pmode);
8472       emit_insn (gen_rtx_SET (tmpreg, mem));
8473
8474       dest = gen_reg_rtx (Pmode);
8475       if (TARGET_32BIT)
8476         emit_insn (gen_tls_get_addrsi (dest, modreg, tmpreg));
8477       else
8478         emit_insn (gen_tls_get_addrdi (dest, modreg, tmpreg));
8479       return dest;
8480     }
8481   /* Obtain TLS pointer: 32 bit call or 64 bit GPR 13.  */
8482   else if (TARGET_32BIT)
8483     {
8484       tlsreg = gen_reg_rtx (SImode);
8485       emit_insn (gen_tls_get_tpointer (tlsreg));
8486     }
8487   else
8488     tlsreg = gen_rtx_REG (DImode, 13);
8489
8490   /* Load the TOC value into temporary register.  */
8491   tmpreg = gen_reg_rtx (Pmode);
8492   emit_insn (gen_rtx_SET (tmpreg, mem));
8493   set_unique_reg_note (get_last_insn (), REG_EQUAL,
8494                        gen_rtx_MINUS (Pmode, addr, tlsreg));
8495
8496   /* Add TOC symbol value to TLS pointer.  */
8497   dest = force_reg (Pmode, gen_rtx_PLUS (Pmode, tmpreg, tlsreg));
8498
8499   return dest;
8500 }
8501
8502 /* Output arg setup instructions for a !TARGET_TLS_MARKERS
8503    __tls_get_addr call.  */
8504
8505 void
8506 rs6000_output_tlsargs (rtx *operands)
8507 {
8508   /* Set up operands for output_asm_insn, without modifying OPERANDS.  */
8509   rtx op[3];
8510
8511   /* The set dest of the call, ie. r3, which is also the first arg reg.  */
8512   op[0] = operands[0];
8513   /* The TLS symbol from global_tlsarg stashed as CALL operand 2.  */
8514   op[1] = XVECEXP (operands[2], 0, 0);
8515   if (XINT (operands[2], 1) == UNSPEC_TLSGD)
8516     {
8517       /* The GOT register.  */
8518       op[2] = XVECEXP (operands[2], 0, 1);
8519       if (TARGET_CMODEL != CMODEL_SMALL)
8520         output_asm_insn ("addis %0,%2,%1@got@tlsgd@ha\n\t"
8521                          "addi %0,%0,%1@got@tlsgd@l", op);
8522       else
8523         output_asm_insn ("addi %0,%2,%1@got@tlsgd", op);
8524     }
8525   else if (XINT (operands[2], 1) == UNSPEC_TLSLD)
8526     {
8527       if (TARGET_CMODEL != CMODEL_SMALL)
8528         output_asm_insn ("addis %0,%1,%&@got@tlsld@ha\n\t"
8529                          "addi %0,%0,%&@got@tlsld@l", op);
8530       else
8531         output_asm_insn ("addi %0,%1,%&@got@tlsld", op);
8532     }
8533   else
8534     gcc_unreachable ();
8535 }
8536
8537 /* Passes the tls arg value for global dynamic and local dynamic
8538    emit_library_call_value in rs6000_legitimize_tls_address to
8539    rs6000_call_aix and rs6000_call_sysv.  This is used to emit the
8540    marker relocs put on __tls_get_addr calls.  */
8541 static rtx global_tlsarg;
8542
8543 /* ADDR contains a thread-local SYMBOL_REF.  Generate code to compute
8544    this (thread-local) address.  */
8545
8546 static rtx
8547 rs6000_legitimize_tls_address (rtx addr, enum tls_model model)
8548 {
8549   rtx dest, insn;
8550
8551   if (TARGET_XCOFF)
8552     return rs6000_legitimize_tls_address_aix (addr, model);
8553
8554   dest = gen_reg_rtx (Pmode);
8555   if (model == TLS_MODEL_LOCAL_EXEC && rs6000_tls_size == 16)
8556     {
8557       rtx tlsreg;
8558
8559       if (TARGET_64BIT)
8560         {
8561           tlsreg = gen_rtx_REG (Pmode, 13);
8562           insn = gen_tls_tprel_64 (dest, tlsreg, addr);
8563         }
8564       else
8565         {
8566           tlsreg = gen_rtx_REG (Pmode, 2);
8567           insn = gen_tls_tprel_32 (dest, tlsreg, addr);
8568         }
8569       emit_insn (insn);
8570     }
8571   else if (model == TLS_MODEL_LOCAL_EXEC && rs6000_tls_size == 32)
8572     {
8573       rtx tlsreg, tmp;
8574
8575       tmp = gen_reg_rtx (Pmode);
8576       if (TARGET_64BIT)
8577         {
8578           tlsreg = gen_rtx_REG (Pmode, 13);
8579           insn = gen_tls_tprel_ha_64 (tmp, tlsreg, addr);
8580         }
8581       else
8582         {
8583           tlsreg = gen_rtx_REG (Pmode, 2);
8584           insn = gen_tls_tprel_ha_32 (tmp, tlsreg, addr);
8585         }
8586       emit_insn (insn);
8587       if (TARGET_64BIT)
8588         insn = gen_tls_tprel_lo_64 (dest, tmp, addr);
8589       else
8590         insn = gen_tls_tprel_lo_32 (dest, tmp, addr);
8591       emit_insn (insn);
8592     }
8593   else
8594     {
8595       rtx got, tga, tmp1, tmp2;
8596
8597       /* We currently use relocations like @got@tlsgd for tls, which
8598          means the linker will handle allocation of tls entries, placing
8599          them in the .got section.  So use a pointer to the .got section,
8600          not one to secondary TOC sections used by 64-bit -mminimal-toc,
8601          or to secondary GOT sections used by 32-bit -fPIC.  */
8602       if (TARGET_64BIT)
8603         got = gen_rtx_REG (Pmode, 2);
8604       else
8605         {
8606           if (flag_pic == 1)
8607             got = gen_rtx_REG (Pmode, RS6000_PIC_OFFSET_TABLE_REGNUM);
8608           else
8609             {
8610               rtx gsym = rs6000_got_sym ();
8611               got = gen_reg_rtx (Pmode);
8612               if (flag_pic == 0)
8613                 rs6000_emit_move (got, gsym, Pmode);
8614               else
8615                 {
8616                   rtx mem, lab;
8617
8618                   tmp1 = gen_reg_rtx (Pmode);
8619                   tmp2 = gen_reg_rtx (Pmode);
8620                   mem = gen_const_mem (Pmode, tmp1);
8621                   lab = gen_label_rtx ();
8622                   emit_insn (gen_load_toc_v4_PIC_1b (gsym, lab));
8623                   emit_move_insn (tmp1, gen_rtx_REG (Pmode, LR_REGNO));
8624                   if (TARGET_LINK_STACK)
8625                     emit_insn (gen_addsi3 (tmp1, tmp1, GEN_INT (4)));
8626                   emit_move_insn (tmp2, mem);
8627                   rtx_insn *last = emit_insn (gen_addsi3 (got, tmp1, tmp2));
8628                   set_unique_reg_note (last, REG_EQUAL, gsym);
8629                 }
8630             }
8631         }
8632
8633       if (model == TLS_MODEL_GLOBAL_DYNAMIC)
8634         {
8635           rtx arg = gen_rtx_UNSPEC (Pmode, gen_rtvec (2, addr, got),
8636                                     UNSPEC_TLSGD);
8637           tga = rs6000_tls_get_addr ();
8638           global_tlsarg = arg;
8639           if (TARGET_TLS_MARKERS)
8640             {
8641               rtx argreg = gen_rtx_REG (Pmode, 3);
8642               emit_insn (gen_rtx_SET (argreg, arg));
8643               emit_library_call_value (tga, dest, LCT_CONST, Pmode,
8644                                        argreg, Pmode);
8645             }
8646           else
8647             emit_library_call_value (tga, dest, LCT_CONST, Pmode);
8648           global_tlsarg = NULL_RTX;
8649
8650           /* Make a note so that the result of this call can be CSEd.  */
8651           rtvec vec = gen_rtvec (1, copy_rtx (arg));
8652           rtx uns = gen_rtx_UNSPEC (Pmode, vec, UNSPEC_TLS_GET_ADDR);
8653           set_unique_reg_note (get_last_insn (), REG_EQUAL, uns);
8654         }
8655       else if (model == TLS_MODEL_LOCAL_DYNAMIC)
8656         {
8657           rtx arg = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, got), UNSPEC_TLSLD);
8658           tga = rs6000_tls_get_addr ();
8659           tmp1 = gen_reg_rtx (Pmode);
8660           global_tlsarg = arg;
8661           if (TARGET_TLS_MARKERS)
8662             {
8663               rtx argreg = gen_rtx_REG (Pmode, 3);
8664               emit_insn (gen_rtx_SET (argreg, arg));
8665               emit_library_call_value (tga, tmp1, LCT_CONST, Pmode,
8666                                        argreg, Pmode);
8667             }
8668           else
8669             emit_library_call_value (tga, tmp1, LCT_CONST, Pmode);
8670           global_tlsarg = NULL_RTX;
8671
8672           /* Make a note so that the result of this call can be CSEd.  */
8673           rtvec vec = gen_rtvec (1, copy_rtx (arg));
8674           rtx uns = gen_rtx_UNSPEC (Pmode, vec, UNSPEC_TLS_GET_ADDR);
8675           set_unique_reg_note (get_last_insn (), REG_EQUAL, uns);
8676
8677           if (rs6000_tls_size == 16)
8678             {
8679               if (TARGET_64BIT)
8680                 insn = gen_tls_dtprel_64 (dest, tmp1, addr);
8681               else
8682                 insn = gen_tls_dtprel_32 (dest, tmp1, addr);
8683             }
8684           else if (rs6000_tls_size == 32)
8685             {
8686               tmp2 = gen_reg_rtx (Pmode);
8687               if (TARGET_64BIT)
8688                 insn = gen_tls_dtprel_ha_64 (tmp2, tmp1, addr);
8689               else
8690                 insn = gen_tls_dtprel_ha_32 (tmp2, tmp1, addr);
8691               emit_insn (insn);
8692               if (TARGET_64BIT)
8693                 insn = gen_tls_dtprel_lo_64 (dest, tmp2, addr);
8694               else
8695                 insn = gen_tls_dtprel_lo_32 (dest, tmp2, addr);
8696             }
8697           else
8698             {
8699               tmp2 = gen_reg_rtx (Pmode);
8700               if (TARGET_64BIT)
8701                 insn = gen_tls_got_dtprel_64 (tmp2, got, addr);
8702               else
8703                 insn = gen_tls_got_dtprel_32 (tmp2, got, addr);
8704               emit_insn (insn);
8705               insn = gen_rtx_SET (dest, gen_rtx_PLUS (Pmode, tmp2, tmp1));
8706             }
8707           emit_insn (insn);
8708         }
8709       else
8710         {
8711           /* IE, or 64-bit offset LE.  */
8712           tmp2 = gen_reg_rtx (Pmode);
8713           if (TARGET_64BIT)
8714             insn = gen_tls_got_tprel_64 (tmp2, got, addr);
8715           else
8716             insn = gen_tls_got_tprel_32 (tmp2, got, addr);
8717           emit_insn (insn);
8718           if (TARGET_64BIT)
8719             insn = gen_tls_tls_64 (dest, tmp2, addr);
8720           else
8721             insn = gen_tls_tls_32 (dest, tmp2, addr);
8722           emit_insn (insn);
8723         }
8724     }
8725
8726   return dest;
8727 }
8728
8729 /* Only create the global variable for the stack protect guard if we are using
8730    the global flavor of that guard.  */
8731 static tree
8732 rs6000_init_stack_protect_guard (void)
8733 {
8734   if (rs6000_stack_protector_guard == SSP_GLOBAL)
8735     return default_stack_protect_guard ();
8736
8737   return NULL_TREE;
8738 }
8739
8740 /* Implement TARGET_CANNOT_FORCE_CONST_MEM.  */
8741
8742 static bool
8743 rs6000_cannot_force_const_mem (machine_mode mode ATTRIBUTE_UNUSED, rtx x)
8744 {
8745   if (GET_CODE (x) == HIGH
8746       && GET_CODE (XEXP (x, 0)) == UNSPEC)
8747     return true;
8748
8749   /* A TLS symbol in the TOC cannot contain a sum.  */
8750   if (GET_CODE (x) == CONST
8751       && GET_CODE (XEXP (x, 0)) == PLUS
8752       && SYMBOL_REF_P (XEXP (XEXP (x, 0), 0))
8753       && SYMBOL_REF_TLS_MODEL (XEXP (XEXP (x, 0), 0)) != 0)
8754     return true;
8755
8756   /* Do not place an ELF TLS symbol in the constant pool.  */
8757   return TARGET_ELF && tls_referenced_p (x);
8758 }
8759
8760 /* Return true iff the given SYMBOL_REF refers to a constant pool entry
8761    that we have put in the TOC, or for cmodel=medium, if the SYMBOL_REF
8762    can be addressed relative to the toc pointer.  */
8763
8764 static bool
8765 use_toc_relative_ref (rtx sym, machine_mode mode)
8766 {
8767   return ((constant_pool_expr_p (sym)
8768            && ASM_OUTPUT_SPECIAL_POOL_ENTRY_P (get_pool_constant (sym),
8769                                                get_pool_mode (sym)))
8770           || (TARGET_CMODEL == CMODEL_MEDIUM
8771               && SYMBOL_REF_LOCAL_P (sym)
8772               && GET_MODE_SIZE (mode) <= POWERPC64_TOC_POINTER_ALIGNMENT));
8773 }
8774
8775 /* TARGET_LEGITIMATE_ADDRESS_P recognizes an RTL expression
8776    that is a valid memory address for an instruction.
8777    The MODE argument is the machine mode for the MEM expression
8778    that wants to use this address.
8779
8780    On the RS/6000, there are four valid address: a SYMBOL_REF that
8781    refers to a constant pool entry of an address (or the sum of it
8782    plus a constant), a short (16-bit signed) constant plus a register,
8783    the sum of two registers, or a register indirect, possibly with an
8784    auto-increment.  For DFmode, DDmode and DImode with a constant plus
8785    register, we must ensure that both words are addressable or PowerPC64
8786    with offset word aligned.
8787
8788    For modes spanning multiple registers (DFmode and DDmode in 32-bit GPRs,
8789    32-bit DImode, TImode, TFmode, TDmode), indexed addressing cannot be used
8790    because adjacent memory cells are accessed by adding word-sized offsets
8791    during assembly output.  */
8792 static bool
8793 rs6000_legitimate_address_p (machine_mode mode, rtx x, bool reg_ok_strict)
8794 {
8795   bool reg_offset_p = reg_offset_addressing_ok_p (mode);
8796   bool quad_offset_p = mode_supports_dq_form (mode);
8797
8798   /* If this is an unaligned stvx/ldvx type address, discard the outer AND.  */
8799   if (VECTOR_MEM_ALTIVEC_P (mode)
8800       && GET_CODE (x) == AND
8801       && CONST_INT_P (XEXP (x, 1))
8802       && INTVAL (XEXP (x, 1)) == -16)
8803     x = XEXP (x, 0);
8804
8805   if (TARGET_ELF && RS6000_SYMBOL_REF_TLS_P (x))
8806     return 0;
8807   if (legitimate_indirect_address_p (x, reg_ok_strict))
8808     return 1;
8809   if (TARGET_UPDATE
8810       && (GET_CODE (x) == PRE_INC || GET_CODE (x) == PRE_DEC)
8811       && mode_supports_pre_incdec_p (mode)
8812       && legitimate_indirect_address_p (XEXP (x, 0), reg_ok_strict))
8813     return 1;
8814   /* Handle restricted vector d-form offsets in ISA 3.0.  */
8815   if (quad_offset_p)
8816     {
8817       if (quad_address_p (x, mode, reg_ok_strict))
8818         return 1;
8819     }
8820   else if (virtual_stack_registers_memory_p (x))
8821     return 1;
8822
8823   else if (reg_offset_p)
8824     {
8825       if (legitimate_small_data_p (mode, x))
8826         return 1;
8827       if (legitimate_constant_pool_address_p (x, mode,
8828                                              reg_ok_strict || lra_in_progress))
8829         return 1;
8830     }
8831
8832   /* For TImode, if we have TImode in VSX registers, only allow register
8833      indirect addresses.  This will allow the values to go in either GPRs
8834      or VSX registers without reloading.  The vector types would tend to
8835      go into VSX registers, so we allow REG+REG, while TImode seems
8836      somewhat split, in that some uses are GPR based, and some VSX based.  */
8837   /* FIXME: We could loosen this by changing the following to
8838        if (mode == TImode && TARGET_QUAD_MEMORY && TARGET_VSX)
8839      but currently we cannot allow REG+REG addressing for TImode.  See
8840      PR72827 for complete details on how this ends up hoodwinking DSE.  */
8841   if (mode == TImode && TARGET_VSX)
8842     return 0;
8843   /* If not REG_OK_STRICT (before reload) let pass any stack offset.  */
8844   if (! reg_ok_strict
8845       && reg_offset_p
8846       && GET_CODE (x) == PLUS
8847       && REG_P (XEXP (x, 0))
8848       && (XEXP (x, 0) == virtual_stack_vars_rtx
8849           || XEXP (x, 0) == arg_pointer_rtx)
8850       && CONST_INT_P (XEXP (x, 1)))
8851     return 1;
8852   if (rs6000_legitimate_offset_address_p (mode, x, reg_ok_strict, false))
8853     return 1;
8854   if (!FLOAT128_2REG_P (mode)
8855       && (TARGET_HARD_FLOAT
8856           || TARGET_POWERPC64
8857           || (mode != DFmode && mode != DDmode))
8858       && (TARGET_POWERPC64 || mode != DImode)
8859       && (mode != TImode || VECTOR_MEM_VSX_P (TImode))
8860       && mode != PTImode
8861       && !avoiding_indexed_address_p (mode)
8862       && legitimate_indexed_address_p (x, reg_ok_strict))
8863     return 1;
8864   if (TARGET_UPDATE && GET_CODE (x) == PRE_MODIFY
8865       && mode_supports_pre_modify_p (mode)
8866       && legitimate_indirect_address_p (XEXP (x, 0), reg_ok_strict)
8867       && (rs6000_legitimate_offset_address_p (mode, XEXP (x, 1),
8868                                               reg_ok_strict, false)
8869           || (!avoiding_indexed_address_p (mode)
8870               && legitimate_indexed_address_p (XEXP (x, 1), reg_ok_strict)))
8871       && rtx_equal_p (XEXP (XEXP (x, 1), 0), XEXP (x, 0)))
8872     return 1;
8873   if (reg_offset_p && !quad_offset_p
8874       && legitimate_lo_sum_address_p (mode, x, reg_ok_strict))
8875     return 1;
8876   return 0;
8877 }
8878
8879 /* Debug version of rs6000_legitimate_address_p.  */
8880 static bool
8881 rs6000_debug_legitimate_address_p (machine_mode mode, rtx x,
8882                                    bool reg_ok_strict)
8883 {
8884   bool ret = rs6000_legitimate_address_p (mode, x, reg_ok_strict);
8885   fprintf (stderr,
8886            "\nrs6000_legitimate_address_p: return = %s, mode = %s, "
8887            "strict = %d, reload = %s, code = %s\n",
8888            ret ? "true" : "false",
8889            GET_MODE_NAME (mode),
8890            reg_ok_strict,
8891            (reload_completed ? "after" : "before"),
8892            GET_RTX_NAME (GET_CODE (x)));
8893   debug_rtx (x);
8894
8895   return ret;
8896 }
8897
8898 /* Implement TARGET_MODE_DEPENDENT_ADDRESS_P.  */
8899
8900 static bool
8901 rs6000_mode_dependent_address_p (const_rtx addr,
8902                                  addr_space_t as ATTRIBUTE_UNUSED)
8903 {
8904   return rs6000_mode_dependent_address_ptr (addr);
8905 }
8906
8907 /* Go to LABEL if ADDR (a legitimate address expression)
8908    has an effect that depends on the machine mode it is used for.
8909
8910    On the RS/6000 this is true of all integral offsets (since AltiVec
8911    and VSX modes don't allow them) or is a pre-increment or decrement.
8912
8913    ??? Except that due to conceptual problems in offsettable_address_p
8914    we can't really report the problems of integral offsets.  So leave
8915    this assuming that the adjustable offset must be valid for the
8916    sub-words of a TFmode operand, which is what we had before.  */
8917
8918 static bool
8919 rs6000_mode_dependent_address (const_rtx addr)
8920 {
8921   switch (GET_CODE (addr))
8922     {
8923     case PLUS:
8924       /* Any offset from virtual_stack_vars_rtx and arg_pointer_rtx
8925          is considered a legitimate address before reload, so there
8926          are no offset restrictions in that case.  Note that this
8927          condition is safe in strict mode because any address involving
8928          virtual_stack_vars_rtx or arg_pointer_rtx would already have
8929          been rejected as illegitimate.  */
8930       if (XEXP (addr, 0) != virtual_stack_vars_rtx
8931           && XEXP (addr, 0) != arg_pointer_rtx
8932           && CONST_INT_P (XEXP (addr, 1)))
8933         {
8934           unsigned HOST_WIDE_INT val = INTVAL (XEXP (addr, 1));
8935           return val + 0x8000 >= 0x10000 - (TARGET_POWERPC64 ? 8 : 12);
8936         }
8937       break;
8938
8939     case LO_SUM:
8940       /* Anything in the constant pool is sufficiently aligned that
8941          all bytes have the same high part address.  */
8942       return !legitimate_constant_pool_address_p (addr, QImode, false);
8943
8944     /* Auto-increment cases are now treated generically in recog.c.  */
8945     case PRE_MODIFY:
8946       return TARGET_UPDATE;
8947
8948     /* AND is only allowed in Altivec loads.  */
8949     case AND:
8950       return true;
8951
8952     default:
8953       break;
8954     }
8955
8956   return false;
8957 }
8958
8959 /* Debug version of rs6000_mode_dependent_address.  */
8960 static bool
8961 rs6000_debug_mode_dependent_address (const_rtx addr)
8962 {
8963   bool ret = rs6000_mode_dependent_address (addr);
8964
8965   fprintf (stderr, "\nrs6000_mode_dependent_address: ret = %s\n",
8966            ret ? "true" : "false");
8967   debug_rtx (addr);
8968
8969   return ret;
8970 }
8971
8972 /* Implement FIND_BASE_TERM.  */
8973
8974 rtx
8975 rs6000_find_base_term (rtx op)
8976 {
8977   rtx base;
8978
8979   base = op;
8980   if (GET_CODE (base) == CONST)
8981     base = XEXP (base, 0);
8982   if (GET_CODE (base) == PLUS)
8983     base = XEXP (base, 0);
8984   if (GET_CODE (base) == UNSPEC)
8985     switch (XINT (base, 1))
8986       {
8987       case UNSPEC_TOCREL:
8988       case UNSPEC_MACHOPIC_OFFSET:
8989         /* OP represents SYM [+ OFFSET] - ANCHOR.  SYM is the base term
8990            for aliasing purposes.  */
8991         return XVECEXP (base, 0, 0);
8992       }
8993
8994   return op;
8995 }
8996
8997 /* More elaborate version of recog's offsettable_memref_p predicate
8998    that works around the ??? note of rs6000_mode_dependent_address.
8999    In particular it accepts
9000
9001      (mem:DI (plus:SI (reg/f:SI 31 31) (const_int 32760 [0x7ff8])))
9002
9003    in 32-bit mode, that the recog predicate rejects.  */
9004
9005 static bool
9006 rs6000_offsettable_memref_p (rtx op, machine_mode reg_mode, bool strict)
9007 {
9008   bool worst_case;
9009
9010   if (!MEM_P (op))
9011     return false;
9012
9013   /* First mimic offsettable_memref_p.  */
9014   if (offsettable_address_p (strict, GET_MODE (op), XEXP (op, 0)))
9015     return true;
9016
9017   /* offsettable_address_p invokes rs6000_mode_dependent_address, but
9018      the latter predicate knows nothing about the mode of the memory
9019      reference and, therefore, assumes that it is the largest supported
9020      mode (TFmode).  As a consequence, legitimate offsettable memory
9021      references are rejected.  rs6000_legitimate_offset_address_p contains
9022      the correct logic for the PLUS case of rs6000_mode_dependent_address,
9023      at least with a little bit of help here given that we know the
9024      actual registers used.  */
9025   worst_case = ((TARGET_POWERPC64 && GET_MODE_CLASS (reg_mode) == MODE_INT)
9026                 || GET_MODE_SIZE (reg_mode) == 4);
9027   return rs6000_legitimate_offset_address_p (GET_MODE (op), XEXP (op, 0),
9028                                              strict, worst_case);
9029 }
9030
9031 /* Determine the reassociation width to be used in reassociate_bb.
9032    This takes into account how many parallel operations we
9033    can actually do of a given type, and also the latency.
9034    P8:
9035      int add/sub 6/cycle     
9036          mul 2/cycle
9037      vect add/sub/mul 2/cycle
9038      fp   add/sub/mul 2/cycle
9039      dfp  1/cycle
9040 */
9041  
9042 static int
9043 rs6000_reassociation_width (unsigned int opc ATTRIBUTE_UNUSED,
9044                             machine_mode mode)
9045 {
9046   switch (rs6000_tune)
9047     {
9048     case PROCESSOR_POWER8:
9049     case PROCESSOR_POWER9:
9050     case PROCESSOR_FUTURE:
9051       if (DECIMAL_FLOAT_MODE_P (mode))
9052         return 1;
9053       if (VECTOR_MODE_P (mode))
9054         return 4;
9055       if (INTEGRAL_MODE_P (mode)) 
9056         return 1;
9057       if (FLOAT_MODE_P (mode))
9058         return 4;
9059       break;
9060     default:
9061       break;
9062     }
9063   return 1;
9064 }
9065
9066 /* Change register usage conditional on target flags.  */
9067 static void
9068 rs6000_conditional_register_usage (void)
9069 {
9070   int i;
9071
9072   if (TARGET_DEBUG_TARGET)
9073     fprintf (stderr, "rs6000_conditional_register_usage called\n");
9074
9075   /* 64-bit AIX and Linux reserve GPR13 for thread-private data.  */
9076   if (TARGET_64BIT)
9077     fixed_regs[13] = call_used_regs[13]
9078       = call_really_used_regs[13] = 1;
9079
9080   /* Conditionally disable FPRs.  */
9081   if (TARGET_SOFT_FLOAT)
9082     for (i = 32; i < 64; i++)
9083       fixed_regs[i] = call_used_regs[i]
9084         = call_really_used_regs[i] = 1;
9085
9086   /* The TOC register is not killed across calls in a way that is
9087      visible to the compiler.  */
9088   if (DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
9089     call_really_used_regs[2] = 0;
9090
9091   if (DEFAULT_ABI == ABI_V4 && flag_pic == 2)
9092     fixed_regs[RS6000_PIC_OFFSET_TABLE_REGNUM] = 1;
9093
9094   if (DEFAULT_ABI == ABI_V4 && flag_pic == 1)
9095     fixed_regs[RS6000_PIC_OFFSET_TABLE_REGNUM]
9096       = call_used_regs[RS6000_PIC_OFFSET_TABLE_REGNUM]
9097       = call_really_used_regs[RS6000_PIC_OFFSET_TABLE_REGNUM] = 1;
9098
9099   if (DEFAULT_ABI == ABI_DARWIN && flag_pic)
9100     fixed_regs[RS6000_PIC_OFFSET_TABLE_REGNUM]
9101       = call_used_regs[RS6000_PIC_OFFSET_TABLE_REGNUM]
9102       = call_really_used_regs[RS6000_PIC_OFFSET_TABLE_REGNUM] = 1;
9103
9104   if (TARGET_TOC && TARGET_MINIMAL_TOC)
9105     fixed_regs[RS6000_PIC_OFFSET_TABLE_REGNUM]
9106       = call_used_regs[RS6000_PIC_OFFSET_TABLE_REGNUM] = 1;
9107
9108   if (!TARGET_ALTIVEC && !TARGET_VSX)
9109     {
9110       for (i = FIRST_ALTIVEC_REGNO; i <= LAST_ALTIVEC_REGNO; ++i)
9111         fixed_regs[i] = call_used_regs[i] = call_really_used_regs[i] = 1;
9112       call_really_used_regs[VRSAVE_REGNO] = 1;
9113     }
9114
9115   if (TARGET_ALTIVEC || TARGET_VSX)
9116     global_regs[VSCR_REGNO] = 1;
9117
9118   if (TARGET_ALTIVEC_ABI)
9119     {
9120       for (i = FIRST_ALTIVEC_REGNO; i < FIRST_ALTIVEC_REGNO + 20; ++i)
9121         call_used_regs[i] = call_really_used_regs[i] = 1;
9122
9123       /* AIX reserves VR20:31 in non-extended ABI mode.  */
9124       if (TARGET_XCOFF)
9125         for (i = FIRST_ALTIVEC_REGNO + 20; i < FIRST_ALTIVEC_REGNO + 32; ++i)
9126           fixed_regs[i] = call_used_regs[i] = call_really_used_regs[i] = 1;
9127     }
9128 }
9129
9130 \f
9131 /* Output insns to set DEST equal to the constant SOURCE as a series of
9132    lis, ori and shl instructions and return TRUE.  */
9133
9134 bool
9135 rs6000_emit_set_const (rtx dest, rtx source)
9136 {
9137   machine_mode mode = GET_MODE (dest);
9138   rtx temp, set;
9139   rtx_insn *insn;
9140   HOST_WIDE_INT c;
9141
9142   gcc_checking_assert (CONST_INT_P (source));
9143   c = INTVAL (source);
9144   switch (mode)
9145     {
9146     case E_QImode:
9147     case E_HImode:
9148       emit_insn (gen_rtx_SET (dest, source));
9149       return true;
9150
9151     case E_SImode:
9152       temp = !can_create_pseudo_p () ? dest : gen_reg_rtx (SImode);
9153
9154       emit_insn (gen_rtx_SET (copy_rtx (temp),
9155                               GEN_INT (c & ~(HOST_WIDE_INT) 0xffff)));
9156       emit_insn (gen_rtx_SET (dest,
9157                               gen_rtx_IOR (SImode, copy_rtx (temp),
9158                                            GEN_INT (c & 0xffff))));
9159       break;
9160
9161     case E_DImode:
9162       if (!TARGET_POWERPC64)
9163         {
9164           rtx hi, lo;
9165
9166           hi = operand_subword_force (copy_rtx (dest), WORDS_BIG_ENDIAN == 0,
9167                                       DImode);
9168           lo = operand_subword_force (dest, WORDS_BIG_ENDIAN != 0,
9169                                       DImode);
9170           emit_move_insn (hi, GEN_INT (c >> 32));
9171           c = ((c & 0xffffffff) ^ 0x80000000) - 0x80000000;
9172           emit_move_insn (lo, GEN_INT (c));
9173         }
9174       else
9175         rs6000_emit_set_long_const (dest, c);
9176       break;
9177
9178     default:
9179       gcc_unreachable ();
9180     }
9181
9182   insn = get_last_insn ();
9183   set = single_set (insn);
9184   if (! CONSTANT_P (SET_SRC (set)))
9185     set_unique_reg_note (insn, REG_EQUAL, GEN_INT (c));
9186
9187   return true;
9188 }
9189
9190 /* Subroutine of rs6000_emit_set_const, handling PowerPC64 DImode.
9191    Output insns to set DEST equal to the constant C as a series of
9192    lis, ori and shl instructions.  */
9193
9194 static void
9195 rs6000_emit_set_long_const (rtx dest, HOST_WIDE_INT c)
9196 {
9197   rtx temp;
9198   HOST_WIDE_INT ud1, ud2, ud3, ud4;
9199
9200   ud1 = c & 0xffff;
9201   c = c >> 16;
9202   ud2 = c & 0xffff;
9203   c = c >> 16;
9204   ud3 = c & 0xffff;
9205   c = c >> 16;
9206   ud4 = c & 0xffff;
9207
9208   if ((ud4 == 0xffff && ud3 == 0xffff && ud2 == 0xffff && (ud1 & 0x8000))
9209       || (ud4 == 0 && ud3 == 0 && ud2 == 0 && ! (ud1 & 0x8000)))
9210     emit_move_insn (dest, GEN_INT ((ud1 ^ 0x8000) - 0x8000));
9211
9212   else if ((ud4 == 0xffff && ud3 == 0xffff && (ud2 & 0x8000))
9213            || (ud4 == 0 && ud3 == 0 && ! (ud2 & 0x8000)))
9214     {
9215       temp = !can_create_pseudo_p () ? dest : gen_reg_rtx (DImode);
9216
9217       emit_move_insn (ud1 != 0 ? copy_rtx (temp) : dest,
9218                       GEN_INT (((ud2 << 16) ^ 0x80000000) - 0x80000000));
9219       if (ud1 != 0)
9220         emit_move_insn (dest,
9221                         gen_rtx_IOR (DImode, copy_rtx (temp),
9222                                      GEN_INT (ud1)));
9223     }
9224   else if (ud3 == 0 && ud4 == 0)
9225     {
9226       temp = !can_create_pseudo_p () ? dest : gen_reg_rtx (DImode);
9227
9228       gcc_assert (ud2 & 0x8000);
9229       emit_move_insn (copy_rtx (temp),
9230                       GEN_INT (((ud2 << 16) ^ 0x80000000) - 0x80000000));
9231       if (ud1 != 0)
9232         emit_move_insn (copy_rtx (temp),
9233                         gen_rtx_IOR (DImode, copy_rtx (temp),
9234                                      GEN_INT (ud1)));
9235       emit_move_insn (dest,
9236                       gen_rtx_ZERO_EXTEND (DImode,
9237                                            gen_lowpart (SImode,
9238                                                         copy_rtx (temp))));
9239     }
9240   else if ((ud4 == 0xffff && (ud3 & 0x8000))
9241            || (ud4 == 0 && ! (ud3 & 0x8000)))
9242     {
9243       temp = !can_create_pseudo_p () ? dest : gen_reg_rtx (DImode);
9244
9245       emit_move_insn (copy_rtx (temp),
9246                       GEN_INT (((ud3 << 16) ^ 0x80000000) - 0x80000000));
9247       if (ud2 != 0)
9248         emit_move_insn (copy_rtx (temp),
9249                         gen_rtx_IOR (DImode, copy_rtx (temp),
9250                                      GEN_INT (ud2)));
9251       emit_move_insn (ud1 != 0 ? copy_rtx (temp) : dest,
9252                       gen_rtx_ASHIFT (DImode, copy_rtx (temp),
9253                                       GEN_INT (16)));
9254       if (ud1 != 0)
9255         emit_move_insn (dest,
9256                         gen_rtx_IOR (DImode, copy_rtx (temp),
9257                                      GEN_INT (ud1)));
9258     }
9259   else
9260     {
9261       temp = !can_create_pseudo_p () ? dest : gen_reg_rtx (DImode);
9262
9263       emit_move_insn (copy_rtx (temp),
9264                       GEN_INT (((ud4 << 16) ^ 0x80000000) - 0x80000000));
9265       if (ud3 != 0)
9266         emit_move_insn (copy_rtx (temp),
9267                         gen_rtx_IOR (DImode, copy_rtx (temp),
9268                                      GEN_INT (ud3)));
9269
9270       emit_move_insn (ud2 != 0 || ud1 != 0 ? copy_rtx (temp) : dest,
9271                       gen_rtx_ASHIFT (DImode, copy_rtx (temp),
9272                                       GEN_INT (32)));
9273       if (ud2 != 0)
9274         emit_move_insn (ud1 != 0 ? copy_rtx (temp) : dest,
9275                         gen_rtx_IOR (DImode, copy_rtx (temp),
9276                                      GEN_INT (ud2 << 16)));
9277       if (ud1 != 0)
9278         emit_move_insn (dest,
9279                         gen_rtx_IOR (DImode, copy_rtx (temp),
9280                                      GEN_INT (ud1)));
9281     }
9282 }
9283
9284 /* Helper for the following.  Get rid of [r+r] memory refs
9285    in cases where it won't work (TImode, TFmode, TDmode, PTImode).  */
9286
9287 static void
9288 rs6000_eliminate_indexed_memrefs (rtx operands[2])
9289 {
9290   if (MEM_P (operands[0])
9291       && !REG_P (XEXP (operands[0], 0))
9292       && ! legitimate_constant_pool_address_p (XEXP (operands[0], 0),
9293                                                GET_MODE (operands[0]), false))
9294     operands[0]
9295       = replace_equiv_address (operands[0],
9296                                copy_addr_to_reg (XEXP (operands[0], 0)));
9297
9298   if (MEM_P (operands[1])
9299       && !REG_P (XEXP (operands[1], 0))
9300       && ! legitimate_constant_pool_address_p (XEXP (operands[1], 0),
9301                                                GET_MODE (operands[1]), false))
9302     operands[1]
9303       = replace_equiv_address (operands[1],
9304                                copy_addr_to_reg (XEXP (operands[1], 0)));
9305 }
9306
9307 /* Generate a vector of constants to permute MODE for a little-endian
9308    storage operation by swapping the two halves of a vector.  */
9309 static rtvec
9310 rs6000_const_vec (machine_mode mode)
9311 {
9312   int i, subparts;
9313   rtvec v;
9314
9315   switch (mode)
9316     {
9317     case E_V1TImode:
9318       subparts = 1;
9319       break;
9320     case E_V2DFmode:
9321     case E_V2DImode:
9322       subparts = 2;
9323       break;
9324     case E_V4SFmode:
9325     case E_V4SImode:
9326       subparts = 4;
9327       break;
9328     case E_V8HImode:
9329       subparts = 8;
9330       break;
9331     case E_V16QImode:
9332       subparts = 16;
9333       break;
9334     default:
9335       gcc_unreachable();
9336     }
9337
9338   v = rtvec_alloc (subparts);
9339
9340   for (i = 0; i < subparts / 2; ++i)
9341     RTVEC_ELT (v, i) = gen_rtx_CONST_INT (DImode, i + subparts / 2);
9342   for (i = subparts / 2; i < subparts; ++i)
9343     RTVEC_ELT (v, i) = gen_rtx_CONST_INT (DImode, i - subparts / 2);
9344
9345   return v;
9346 }
9347
9348 /* Emit an lxvd2x, stxvd2x, or xxpermdi instruction for a VSX load or
9349    store operation.  */
9350 void
9351 rs6000_emit_le_vsx_permute (rtx dest, rtx source, machine_mode mode)
9352 {
9353   /* Scalar permutations are easier to express in integer modes rather than
9354      floating-point modes, so cast them here.  We use V1TImode instead
9355      of TImode to ensure that the values don't go through GPRs.  */
9356   if (FLOAT128_VECTOR_P (mode))
9357     {
9358       dest = gen_lowpart (V1TImode, dest);
9359       source = gen_lowpart (V1TImode, source);
9360       mode = V1TImode;
9361     }
9362
9363   /* Use ROTATE instead of VEC_SELECT if the mode contains only a single
9364      scalar.  */
9365   if (mode == TImode || mode == V1TImode)
9366     emit_insn (gen_rtx_SET (dest, gen_rtx_ROTATE (mode, source,
9367                                                   GEN_INT (64))));
9368   else
9369     {
9370       rtx par = gen_rtx_PARALLEL (VOIDmode, rs6000_const_vec (mode));
9371       emit_insn (gen_rtx_SET (dest, gen_rtx_VEC_SELECT (mode, source, par)));
9372     }
9373 }
9374
9375 /* Emit a little-endian load from vector memory location SOURCE to VSX
9376    register DEST in mode MODE.  The load is done with two permuting
9377    insn's that represent an lxvd2x and xxpermdi.  */
9378 void
9379 rs6000_emit_le_vsx_load (rtx dest, rtx source, machine_mode mode)
9380 {
9381   /* Use V2DImode to do swaps of types with 128-bit scalare parts (TImode,
9382      V1TImode).  */
9383   if (mode == TImode || mode == V1TImode)
9384     {
9385       mode = V2DImode;
9386       dest = gen_lowpart (V2DImode, dest);
9387       source = adjust_address (source, V2DImode, 0);
9388     }
9389
9390   rtx tmp = can_create_pseudo_p () ? gen_reg_rtx_and_attrs (dest) : dest;
9391   rs6000_emit_le_vsx_permute (tmp, source, mode);
9392   rs6000_emit_le_vsx_permute (dest, tmp, mode);
9393 }
9394
9395 /* Emit a little-endian store to vector memory location DEST from VSX
9396    register SOURCE in mode MODE.  The store is done with two permuting
9397    insn's that represent an xxpermdi and an stxvd2x.  */
9398 void
9399 rs6000_emit_le_vsx_store (rtx dest, rtx source, machine_mode mode)
9400 {
9401   /* This should never be called during or after LRA, because it does
9402      not re-permute the source register.  It is intended only for use
9403      during expand.  */
9404   gcc_assert (!lra_in_progress && !reload_completed);
9405
9406   /* Use V2DImode to do swaps of types with 128-bit scalar parts (TImode,
9407      V1TImode).  */
9408   if (mode == TImode || mode == V1TImode)
9409     {
9410       mode = V2DImode;
9411       dest = adjust_address (dest, V2DImode, 0);
9412       source = gen_lowpart (V2DImode, source);
9413     }
9414
9415   rtx tmp = can_create_pseudo_p () ? gen_reg_rtx_and_attrs (source) : source;
9416   rs6000_emit_le_vsx_permute (tmp, source, mode);
9417   rs6000_emit_le_vsx_permute (dest, tmp, mode);
9418 }
9419
9420 /* Emit a sequence representing a little-endian VSX load or store,
9421    moving data from SOURCE to DEST in mode MODE.  This is done
9422    separately from rs6000_emit_move to ensure it is called only
9423    during expand.  LE VSX loads and stores introduced later are
9424    handled with a split.  The expand-time RTL generation allows
9425    us to optimize away redundant pairs of register-permutes.  */
9426 void
9427 rs6000_emit_le_vsx_move (rtx dest, rtx source, machine_mode mode)
9428 {
9429   gcc_assert (!BYTES_BIG_ENDIAN
9430               && VECTOR_MEM_VSX_P (mode)
9431               && !TARGET_P9_VECTOR
9432               && !gpr_or_gpr_p (dest, source)
9433               && (MEM_P (source) ^ MEM_P (dest)));
9434
9435   if (MEM_P (source))
9436     {
9437       gcc_assert (REG_P (dest) || SUBREG_P (dest));
9438       rs6000_emit_le_vsx_load (dest, source, mode);
9439     }
9440   else
9441     {
9442       if (!REG_P (source))
9443         source = force_reg (mode, source);
9444       rs6000_emit_le_vsx_store (dest, source, mode);
9445     }
9446 }
9447
9448 /* Return whether a SFmode or SImode move can be done without converting one
9449    mode to another.  This arrises when we have:
9450
9451         (SUBREG:SF (REG:SI ...))
9452         (SUBREG:SI (REG:SF ...))
9453
9454    and one of the values is in a floating point/vector register, where SFmode
9455    scalars are stored in DFmode format.  */
9456
9457 bool
9458 valid_sf_si_move (rtx dest, rtx src, machine_mode mode)
9459 {
9460   if (TARGET_ALLOW_SF_SUBREG)
9461     return true;
9462
9463   if (mode != SFmode && GET_MODE_CLASS (mode) != MODE_INT)
9464     return true;
9465
9466   if (!SUBREG_P (src) || !sf_subreg_operand (src, mode))
9467     return true;
9468
9469   /*.  Allow (set (SUBREG:SI (REG:SF)) (SUBREG:SI (REG:SF))).  */
9470   if (SUBREG_P (dest))
9471     {
9472       rtx dest_subreg = SUBREG_REG (dest);
9473       rtx src_subreg = SUBREG_REG (src);
9474       return GET_MODE (dest_subreg) == GET_MODE (src_subreg);
9475     }
9476
9477   return false;
9478 }
9479
9480
9481 /* Helper function to change moves with:
9482
9483         (SUBREG:SF (REG:SI)) and
9484         (SUBREG:SI (REG:SF))
9485
9486    into separate UNSPEC insns.  In the PowerPC architecture, scalar SFmode
9487    values are stored as DFmode values in the VSX registers.  We need to convert
9488    the bits before we can use a direct move or operate on the bits in the
9489    vector register as an integer type.
9490
9491    Skip things like (set (SUBREG:SI (...) (SUBREG:SI (...)).  */
9492
9493 static bool
9494 rs6000_emit_move_si_sf_subreg (rtx dest, rtx source, machine_mode mode)
9495 {
9496   if (TARGET_DIRECT_MOVE_64BIT && !reload_completed
9497       && (!SUBREG_P (dest) || !sf_subreg_operand (dest, mode))
9498       && SUBREG_P (source) && sf_subreg_operand (source, mode))
9499     {
9500       rtx inner_source = SUBREG_REG (source);
9501       machine_mode inner_mode = GET_MODE (inner_source);
9502
9503       if (mode == SImode && inner_mode == SFmode)
9504         {
9505           emit_insn (gen_movsi_from_sf (dest, inner_source));
9506           return true;
9507         }
9508
9509       if (mode == SFmode && inner_mode == SImode)
9510         {
9511           emit_insn (gen_movsf_from_si (dest, inner_source));
9512           return true;
9513         }
9514     }
9515
9516   return false;
9517 }
9518
9519 /* Emit a move from SOURCE to DEST in mode MODE.  */
9520 void
9521 rs6000_emit_move (rtx dest, rtx source, machine_mode mode)
9522 {
9523   rtx operands[2];
9524   operands[0] = dest;
9525   operands[1] = source;
9526
9527   if (TARGET_DEBUG_ADDR)
9528     {
9529       fprintf (stderr,
9530                "\nrs6000_emit_move: mode = %s, lra_in_progress = %d, "
9531                "reload_completed = %d, can_create_pseudos = %d.\ndest:\n",
9532                GET_MODE_NAME (mode),
9533                lra_in_progress,
9534                reload_completed,
9535                can_create_pseudo_p ());
9536       debug_rtx (dest);
9537       fprintf (stderr, "source:\n");
9538       debug_rtx (source);
9539     }
9540
9541   /* Check that we get CONST_WIDE_INT only when we should.  */
9542   if (CONST_WIDE_INT_P (operands[1])
9543       && GET_MODE_BITSIZE (mode) <= HOST_BITS_PER_WIDE_INT)
9544     gcc_unreachable ();
9545
9546 #ifdef HAVE_AS_GNU_ATTRIBUTE
9547   /* If we use a long double type, set the flags in .gnu_attribute that say
9548      what the long double type is.  This is to allow the linker's warning
9549      message for the wrong long double to be useful, even if the function does
9550      not do a call (for example, doing a 128-bit add on power9 if the long
9551      double type is IEEE 128-bit.  Do not set this if __ibm128 or __floa128 are
9552      used if they aren't the default long dobule type.  */
9553   if (rs6000_gnu_attr && (HAVE_LD_PPC_GNU_ATTR_LONG_DOUBLE || TARGET_64BIT))
9554     {
9555       if (TARGET_LONG_DOUBLE_128 && (mode == TFmode || mode == TCmode))
9556         rs6000_passes_float = rs6000_passes_long_double = true;
9557
9558       else if (!TARGET_LONG_DOUBLE_128 && (mode == DFmode || mode == DCmode))
9559         rs6000_passes_float = rs6000_passes_long_double = true;
9560     }
9561 #endif
9562
9563   /* See if we need to special case SImode/SFmode SUBREG moves.  */
9564   if ((mode == SImode || mode == SFmode) && SUBREG_P (source)
9565       && rs6000_emit_move_si_sf_subreg (dest, source, mode))
9566     return;
9567
9568   /* Check if GCC is setting up a block move that will end up using FP
9569      registers as temporaries.  We must make sure this is acceptable.  */
9570   if (MEM_P (operands[0])
9571       && MEM_P (operands[1])
9572       && mode == DImode
9573       && (rs6000_slow_unaligned_access (DImode, MEM_ALIGN (operands[0]))
9574           || rs6000_slow_unaligned_access (DImode, MEM_ALIGN (operands[1])))
9575       && ! (rs6000_slow_unaligned_access (SImode,
9576                                           (MEM_ALIGN (operands[0]) > 32
9577                                            ? 32 : MEM_ALIGN (operands[0])))
9578             || rs6000_slow_unaligned_access (SImode,
9579                                              (MEM_ALIGN (operands[1]) > 32
9580                                               ? 32 : MEM_ALIGN (operands[1]))))
9581       && ! MEM_VOLATILE_P (operands [0])
9582       && ! MEM_VOLATILE_P (operands [1]))
9583     {
9584       emit_move_insn (adjust_address (operands[0], SImode, 0),
9585                       adjust_address (operands[1], SImode, 0));
9586       emit_move_insn (adjust_address (copy_rtx (operands[0]), SImode, 4),
9587                       adjust_address (copy_rtx (operands[1]), SImode, 4));
9588       return;
9589     }
9590
9591   if (can_create_pseudo_p () && MEM_P (operands[0])
9592       && !gpc_reg_operand (operands[1], mode))
9593     operands[1] = force_reg (mode, operands[1]);
9594
9595   /* Recognize the case where operand[1] is a reference to thread-local
9596      data and load its address to a register.  */
9597   if (tls_referenced_p (operands[1]))
9598     {
9599       enum tls_model model;
9600       rtx tmp = operands[1];
9601       rtx addend = NULL;
9602
9603       if (GET_CODE (tmp) == CONST && GET_CODE (XEXP (tmp, 0)) == PLUS)
9604         {
9605           addend = XEXP (XEXP (tmp, 0), 1);
9606           tmp = XEXP (XEXP (tmp, 0), 0);
9607         }
9608
9609       gcc_assert (SYMBOL_REF_P (tmp));
9610       model = SYMBOL_REF_TLS_MODEL (tmp);
9611       gcc_assert (model != 0);
9612
9613       tmp = rs6000_legitimize_tls_address (tmp, model);
9614       if (addend)
9615         {
9616           tmp = gen_rtx_PLUS (mode, tmp, addend);
9617           tmp = force_operand (tmp, operands[0]);
9618         }
9619       operands[1] = tmp;
9620     }
9621
9622   /* 128-bit constant floating-point values on Darwin should really be loaded
9623      as two parts.  However, this premature splitting is a problem when DFmode
9624      values can go into Altivec registers.  */
9625   if (TARGET_MACHO && CONST_DOUBLE_P (operands[1]) && FLOAT128_IBM_P (mode)
9626       && !reg_addr[DFmode].scalar_in_vmx_p)
9627     {
9628       rs6000_emit_move (simplify_gen_subreg (DFmode, operands[0], mode, 0),
9629                         simplify_gen_subreg (DFmode, operands[1], mode, 0),
9630                         DFmode);
9631       rs6000_emit_move (simplify_gen_subreg (DFmode, operands[0], mode,
9632                                              GET_MODE_SIZE (DFmode)),
9633                         simplify_gen_subreg (DFmode, operands[1], mode,
9634                                              GET_MODE_SIZE (DFmode)),
9635                         DFmode);
9636       return;
9637     }
9638
9639   /* Transform (p0:DD, (SUBREG:DD p1:SD)) to ((SUBREG:SD p0:DD),
9640      p1:SD) if p1 is not of floating point class and p0 is spilled as
9641      we can have no analogous movsd_store for this.  */
9642   if (lra_in_progress && mode == DDmode
9643       && REG_P (operands[0]) && !HARD_REGISTER_P (operands[0])
9644       && reg_preferred_class (REGNO (operands[0])) == NO_REGS
9645       && SUBREG_P (operands[1]) && REG_P (SUBREG_REG (operands[1]))
9646       && GET_MODE (SUBREG_REG (operands[1])) == SDmode)
9647     {
9648       enum reg_class cl;
9649       int regno = REGNO (SUBREG_REG (operands[1]));
9650
9651       if (!HARD_REGISTER_NUM_P (regno))
9652         {
9653           cl = reg_preferred_class (regno);
9654           regno = reg_renumber[regno];
9655           if (regno < 0)
9656             regno = cl == NO_REGS ? -1 : ira_class_hard_regs[cl][1];
9657         }
9658       if (regno >= 0 && ! FP_REGNO_P (regno))
9659         {
9660           mode = SDmode;
9661           operands[0] = gen_lowpart_SUBREG (SDmode, operands[0]);
9662           operands[1] = SUBREG_REG (operands[1]);
9663         }
9664     }
9665   if (lra_in_progress
9666       && mode == SDmode
9667       && REG_P (operands[0]) && !HARD_REGISTER_P (operands[0])
9668       && reg_preferred_class (REGNO (operands[0])) == NO_REGS
9669       && (REG_P (operands[1])
9670           || (SUBREG_P (operands[1]) && REG_P (SUBREG_REG (operands[1])))))
9671     {
9672       int regno = reg_or_subregno (operands[1]);
9673       enum reg_class cl;
9674
9675       if (!HARD_REGISTER_NUM_P (regno))
9676         {
9677           cl = reg_preferred_class (regno);
9678           gcc_assert (cl != NO_REGS);
9679           regno = reg_renumber[regno];
9680           if (regno < 0)
9681             regno = ira_class_hard_regs[cl][0];
9682         }
9683       if (FP_REGNO_P (regno))
9684         {
9685           if (GET_MODE (operands[0]) != DDmode)
9686             operands[0] = gen_rtx_SUBREG (DDmode, operands[0], 0);
9687           emit_insn (gen_movsd_store (operands[0], operands[1]));
9688         }
9689       else if (INT_REGNO_P (regno))
9690         emit_insn (gen_movsd_hardfloat (operands[0], operands[1]));
9691       else
9692         gcc_unreachable();
9693       return;
9694     }
9695   /* Transform ((SUBREG:DD p0:SD), p1:DD) to (p0:SD, (SUBREG:SD
9696      p:DD)) if p0 is not of floating point class and p1 is spilled as
9697      we can have no analogous movsd_load for this.  */
9698   if (lra_in_progress && mode == DDmode
9699       && SUBREG_P (operands[0]) && REG_P (SUBREG_REG (operands[0]))
9700       && GET_MODE (SUBREG_REG (operands[0])) == SDmode
9701       && REG_P (operands[1]) && !HARD_REGISTER_P (operands[1])
9702       && reg_preferred_class (REGNO (operands[1])) == NO_REGS)
9703     {
9704       enum reg_class cl;
9705       int regno = REGNO (SUBREG_REG (operands[0]));
9706
9707       if (!HARD_REGISTER_NUM_P (regno))
9708         {
9709           cl = reg_preferred_class (regno);
9710           regno = reg_renumber[regno];
9711           if (regno < 0)
9712             regno = cl == NO_REGS ? -1 : ira_class_hard_regs[cl][0];
9713         }
9714       if (regno >= 0 && ! FP_REGNO_P (regno))
9715         {
9716           mode = SDmode;
9717           operands[0] = SUBREG_REG (operands[0]);
9718           operands[1] = gen_lowpart_SUBREG (SDmode, operands[1]);
9719         }
9720     }
9721   if (lra_in_progress
9722       && mode == SDmode
9723       && (REG_P (operands[0])
9724           || (SUBREG_P (operands[0]) && REG_P (SUBREG_REG (operands[0]))))
9725       && REG_P (operands[1]) && !HARD_REGISTER_P (operands[1])
9726       && reg_preferred_class (REGNO (operands[1])) == NO_REGS)
9727     {
9728       int regno = reg_or_subregno (operands[0]);
9729       enum reg_class cl;
9730
9731       if (!HARD_REGISTER_NUM_P (regno))
9732         {
9733           cl = reg_preferred_class (regno);
9734           gcc_assert (cl != NO_REGS);
9735           regno = reg_renumber[regno];
9736           if (regno < 0)
9737             regno = ira_class_hard_regs[cl][0];
9738         }
9739       if (FP_REGNO_P (regno))
9740         {
9741           if (GET_MODE (operands[1]) != DDmode)
9742             operands[1] = gen_rtx_SUBREG (DDmode, operands[1], 0);
9743           emit_insn (gen_movsd_load (operands[0], operands[1]));
9744         }
9745       else if (INT_REGNO_P (regno))
9746         emit_insn (gen_movsd_hardfloat (operands[0], operands[1]));
9747       else
9748         gcc_unreachable();
9749       return;
9750     }
9751
9752   /* FIXME:  In the long term, this switch statement should go away
9753      and be replaced by a sequence of tests based on things like
9754      mode == Pmode.  */
9755   switch (mode)
9756     {
9757     case E_HImode:
9758     case E_QImode:
9759       if (CONSTANT_P (operands[1])
9760           && !CONST_INT_P (operands[1]))
9761         operands[1] = force_const_mem (mode, operands[1]);
9762       break;
9763
9764     case E_TFmode:
9765     case E_TDmode:
9766     case E_IFmode:
9767     case E_KFmode:
9768       if (FLOAT128_2REG_P (mode))
9769         rs6000_eliminate_indexed_memrefs (operands);
9770       /* fall through */
9771
9772     case E_DFmode:
9773     case E_DDmode:
9774     case E_SFmode:
9775     case E_SDmode:
9776       if (CONSTANT_P (operands[1])
9777           && ! easy_fp_constant (operands[1], mode))
9778         operands[1] = force_const_mem (mode, operands[1]);
9779       break;
9780
9781     case E_V16QImode:
9782     case E_V8HImode:
9783     case E_V4SFmode:
9784     case E_V4SImode:
9785     case E_V2DFmode:
9786     case E_V2DImode:
9787     case E_V1TImode:
9788       if (CONSTANT_P (operands[1])
9789           && !easy_vector_constant (operands[1], mode))
9790         operands[1] = force_const_mem (mode, operands[1]);
9791       break;
9792
9793     case E_SImode:
9794     case E_DImode:
9795       /* Use default pattern for address of ELF small data */
9796       if (TARGET_ELF
9797           && mode == Pmode
9798           && DEFAULT_ABI == ABI_V4
9799           && (SYMBOL_REF_P (operands[1])
9800               || GET_CODE (operands[1]) == CONST)
9801           && small_data_operand (operands[1], mode))
9802         {
9803           emit_insn (gen_rtx_SET (operands[0], operands[1]));
9804           return;
9805         }
9806
9807       if (DEFAULT_ABI == ABI_V4
9808           && mode == Pmode && mode == SImode
9809           && flag_pic == 1 && got_operand (operands[1], mode))
9810         {
9811           emit_insn (gen_movsi_got (operands[0], operands[1]));
9812           return;
9813         }
9814
9815       if ((TARGET_ELF || DEFAULT_ABI == ABI_DARWIN)
9816           && TARGET_NO_TOC
9817           && ! flag_pic
9818           && mode == Pmode
9819           && CONSTANT_P (operands[1])
9820           && GET_CODE (operands[1]) != HIGH
9821           && !CONST_INT_P (operands[1]))
9822         {
9823           rtx target = (!can_create_pseudo_p ()
9824                         ? operands[0]
9825                         : gen_reg_rtx (mode));
9826
9827           /* If this is a function address on -mcall-aixdesc,
9828              convert it to the address of the descriptor.  */
9829           if (DEFAULT_ABI == ABI_AIX
9830               && SYMBOL_REF_P (operands[1])
9831               && XSTR (operands[1], 0)[0] == '.')
9832             {
9833               const char *name = XSTR (operands[1], 0);
9834               rtx new_ref;
9835               while (*name == '.')
9836                 name++;
9837               new_ref = gen_rtx_SYMBOL_REF (Pmode, name);
9838               CONSTANT_POOL_ADDRESS_P (new_ref)
9839                 = CONSTANT_POOL_ADDRESS_P (operands[1]);
9840               SYMBOL_REF_FLAGS (new_ref) = SYMBOL_REF_FLAGS (operands[1]);
9841               SYMBOL_REF_USED (new_ref) = SYMBOL_REF_USED (operands[1]);
9842               SYMBOL_REF_DATA (new_ref) = SYMBOL_REF_DATA (operands[1]);
9843               operands[1] = new_ref;
9844             }
9845
9846           if (DEFAULT_ABI == ABI_DARWIN)
9847             {
9848 #if TARGET_MACHO
9849               if (MACHO_DYNAMIC_NO_PIC_P)
9850                 {
9851                   /* Take care of any required data indirection.  */
9852                   operands[1] = rs6000_machopic_legitimize_pic_address (
9853                                   operands[1], mode, operands[0]);
9854                   if (operands[0] != operands[1])
9855                     emit_insn (gen_rtx_SET (operands[0], operands[1]));
9856                   return;
9857                 }
9858 #endif
9859               emit_insn (gen_macho_high (target, operands[1]));
9860               emit_insn (gen_macho_low (operands[0], target, operands[1]));
9861               return;
9862             }
9863
9864           emit_insn (gen_elf_high (target, operands[1]));
9865           emit_insn (gen_elf_low (operands[0], target, operands[1]));
9866           return;
9867         }
9868
9869       /* If this is a SYMBOL_REF that refers to a constant pool entry,
9870          and we have put it in the TOC, we just need to make a TOC-relative
9871          reference to it.  */
9872       if (TARGET_TOC
9873           && SYMBOL_REF_P (operands[1])
9874           && use_toc_relative_ref (operands[1], mode))
9875         operands[1] = create_TOC_reference (operands[1], operands[0]);
9876       else if (mode == Pmode
9877                && CONSTANT_P (operands[1])
9878                && GET_CODE (operands[1]) != HIGH
9879                && ((REG_P (operands[0])
9880                     && FP_REGNO_P (REGNO (operands[0])))
9881                    || !CONST_INT_P (operands[1])
9882                    || (num_insns_constant (operands[1], mode)
9883                        > (TARGET_CMODEL != CMODEL_SMALL ? 3 : 2)))
9884                && !toc_relative_expr_p (operands[1], false, NULL, NULL)
9885                && (TARGET_CMODEL == CMODEL_SMALL
9886                    || can_create_pseudo_p ()
9887                    || (REG_P (operands[0])
9888                        && INT_REG_OK_FOR_BASE_P (operands[0], true))))
9889         {
9890
9891 #if TARGET_MACHO
9892           /* Darwin uses a special PIC legitimizer.  */
9893           if (DEFAULT_ABI == ABI_DARWIN && MACHOPIC_INDIRECT)
9894             {
9895               operands[1] =
9896                 rs6000_machopic_legitimize_pic_address (operands[1], mode,
9897                                                         operands[0]);
9898               if (operands[0] != operands[1])
9899                 emit_insn (gen_rtx_SET (operands[0], operands[1]));
9900               return;
9901             }
9902 #endif
9903
9904           /* If we are to limit the number of things we put in the TOC and
9905              this is a symbol plus a constant we can add in one insn,
9906              just put the symbol in the TOC and add the constant.  */
9907           if (GET_CODE (operands[1]) == CONST
9908               && TARGET_NO_SUM_IN_TOC
9909               && GET_CODE (XEXP (operands[1], 0)) == PLUS
9910               && add_operand (XEXP (XEXP (operands[1], 0), 1), mode)
9911               && (GET_CODE (XEXP (XEXP (operands[1], 0), 0)) == LABEL_REF
9912                   || SYMBOL_REF_P (XEXP (XEXP (operands[1], 0), 0)))
9913               && ! side_effects_p (operands[0]))
9914             {
9915               rtx sym =
9916                 force_const_mem (mode, XEXP (XEXP (operands[1], 0), 0));
9917               rtx other = XEXP (XEXP (operands[1], 0), 1);
9918
9919               sym = force_reg (mode, sym);
9920               emit_insn (gen_add3_insn (operands[0], sym, other));
9921               return;
9922             }
9923
9924           operands[1] = force_const_mem (mode, operands[1]);
9925
9926           if (TARGET_TOC
9927               && SYMBOL_REF_P (XEXP (operands[1], 0))
9928               && use_toc_relative_ref (XEXP (operands[1], 0), mode))
9929             {
9930               rtx tocref = create_TOC_reference (XEXP (operands[1], 0),
9931                                                  operands[0]);
9932               operands[1] = gen_const_mem (mode, tocref);
9933               set_mem_alias_set (operands[1], get_TOC_alias_set ());
9934             }
9935         }
9936       break;
9937
9938     case E_TImode:
9939       if (!VECTOR_MEM_VSX_P (TImode))
9940         rs6000_eliminate_indexed_memrefs (operands);
9941       break;
9942
9943     case E_PTImode:
9944       rs6000_eliminate_indexed_memrefs (operands);
9945       break;
9946
9947     default:
9948       fatal_insn ("bad move", gen_rtx_SET (dest, source));
9949     }
9950
9951   /* Above, we may have called force_const_mem which may have returned
9952      an invalid address.  If we can, fix this up; otherwise, reload will
9953      have to deal with it.  */
9954   if (MEM_P (operands[1]))
9955     operands[1] = validize_mem (operands[1]);
9956
9957   emit_insn (gen_rtx_SET (operands[0], operands[1]));
9958 }
9959 \f
9960 /* Nonzero if we can use a floating-point register to pass this arg.  */
9961 #define USE_FP_FOR_ARG_P(CUM,MODE)              \
9962   (SCALAR_FLOAT_MODE_NOT_VECTOR_P (MODE)                \
9963    && (CUM)->fregno <= FP_ARG_MAX_REG           \
9964    && TARGET_HARD_FLOAT)
9965
9966 /* Nonzero if we can use an AltiVec register to pass this arg.  */
9967 #define USE_ALTIVEC_FOR_ARG_P(CUM,MODE,NAMED)                   \
9968   (ALTIVEC_OR_VSX_VECTOR_MODE (MODE)                            \
9969    && (CUM)->vregno <= ALTIVEC_ARG_MAX_REG                      \
9970    && TARGET_ALTIVEC_ABI                                        \
9971    && (NAMED))
9972
9973 /* Walk down the type tree of TYPE counting consecutive base elements.
9974    If *MODEP is VOIDmode, then set it to the first valid floating point
9975    or vector type.  If a non-floating point or vector type is found, or
9976    if a floating point or vector type that doesn't match a non-VOIDmode
9977    *MODEP is found, then return -1, otherwise return the count in the
9978    sub-tree.  */
9979
9980 static int
9981 rs6000_aggregate_candidate (const_tree type, machine_mode *modep)
9982 {
9983   machine_mode mode;
9984   HOST_WIDE_INT size;
9985
9986   switch (TREE_CODE (type))
9987     {
9988     case REAL_TYPE:
9989       mode = TYPE_MODE (type);
9990       if (!SCALAR_FLOAT_MODE_P (mode))
9991         return -1;
9992
9993       if (*modep == VOIDmode)
9994         *modep = mode;
9995
9996       if (*modep == mode)
9997         return 1;
9998
9999       break;
10000
10001     case COMPLEX_TYPE:
10002       mode = TYPE_MODE (TREE_TYPE (type));
10003       if (!SCALAR_FLOAT_MODE_P (mode))
10004         return -1;
10005
10006       if (*modep == VOIDmode)
10007         *modep = mode;
10008
10009       if (*modep == mode)
10010         return 2;
10011
10012       break;
10013
10014     case VECTOR_TYPE:
10015       if (!TARGET_ALTIVEC_ABI || !TARGET_ALTIVEC)
10016         return -1;
10017
10018       /* Use V4SImode as representative of all 128-bit vector types.  */
10019       size = int_size_in_bytes (type);
10020       switch (size)
10021         {
10022         case 16:
10023           mode = V4SImode;
10024           break;
10025         default:
10026           return -1;
10027         }
10028
10029       if (*modep == VOIDmode)
10030         *modep = mode;
10031
10032       /* Vector modes are considered to be opaque: two vectors are
10033          equivalent for the purposes of being homogeneous aggregates
10034          if they are the same size.  */
10035       if (*modep == mode)
10036         return 1;
10037
10038       break;
10039
10040     case ARRAY_TYPE:
10041       {
10042         int count;
10043         tree index = TYPE_DOMAIN (type);
10044
10045         /* Can't handle incomplete types nor sizes that are not
10046            fixed.  */
10047         if (!COMPLETE_TYPE_P (type)
10048             || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST)
10049           return -1;
10050
10051         count = rs6000_aggregate_candidate (TREE_TYPE (type), modep);
10052         if (count == -1
10053             || !index
10054             || !TYPE_MAX_VALUE (index)
10055             || !tree_fits_uhwi_p (TYPE_MAX_VALUE (index))
10056             || !TYPE_MIN_VALUE (index)
10057             || !tree_fits_uhwi_p (TYPE_MIN_VALUE (index))
10058             || count < 0)
10059           return -1;
10060
10061         count *= (1 + tree_to_uhwi (TYPE_MAX_VALUE (index))
10062                       - tree_to_uhwi (TYPE_MIN_VALUE (index)));
10063
10064         /* There must be no padding.  */
10065         if (wi::to_wide (TYPE_SIZE (type))
10066             != count * GET_MODE_BITSIZE (*modep))
10067           return -1;
10068
10069         return count;
10070       }
10071
10072     case RECORD_TYPE:
10073       {
10074         int count = 0;
10075         int sub_count;
10076         tree field;
10077
10078         /* Can't handle incomplete types nor sizes that are not
10079            fixed.  */
10080         if (!COMPLETE_TYPE_P (type)
10081             || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST)
10082           return -1;
10083
10084         for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
10085           {
10086             if (TREE_CODE (field) != FIELD_DECL)
10087               continue;
10088
10089             sub_count = rs6000_aggregate_candidate (TREE_TYPE (field), modep);
10090             if (sub_count < 0)
10091               return -1;
10092             count += sub_count;
10093           }
10094
10095         /* There must be no padding.  */
10096         if (wi::to_wide (TYPE_SIZE (type))
10097             != count * GET_MODE_BITSIZE (*modep))
10098           return -1;
10099
10100         return count;
10101       }
10102
10103     case UNION_TYPE:
10104     case QUAL_UNION_TYPE:
10105       {
10106         /* These aren't very interesting except in a degenerate case.  */
10107         int count = 0;
10108         int sub_count;
10109         tree field;
10110
10111         /* Can't handle incomplete types nor sizes that are not
10112            fixed.  */
10113         if (!COMPLETE_TYPE_P (type)
10114             || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST)
10115           return -1;
10116
10117         for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
10118           {
10119             if (TREE_CODE (field) != FIELD_DECL)
10120               continue;
10121
10122             sub_count = rs6000_aggregate_candidate (TREE_TYPE (field), modep);
10123             if (sub_count < 0)
10124               return -1;
10125             count = count > sub_count ? count : sub_count;
10126           }
10127
10128         /* There must be no padding.  */
10129         if (wi::to_wide (TYPE_SIZE (type))
10130             != count * GET_MODE_BITSIZE (*modep))
10131           return -1;
10132
10133         return count;
10134       }
10135
10136     default:
10137       break;
10138     }
10139
10140   return -1;
10141 }
10142
10143 /* If an argument, whose type is described by TYPE and MODE, is a homogeneous
10144    float or vector aggregate that shall be passed in FP/vector registers
10145    according to the ELFv2 ABI, return the homogeneous element mode in
10146    *ELT_MODE and the number of elements in *N_ELTS, and return TRUE.
10147
10148    Otherwise, set *ELT_MODE to MODE and *N_ELTS to 1, and return FALSE.  */
10149
10150 static bool
10151 rs6000_discover_homogeneous_aggregate (machine_mode mode, const_tree type,
10152                                        machine_mode *elt_mode,
10153                                        int *n_elts)
10154 {
10155   /* Note that we do not accept complex types at the top level as
10156      homogeneous aggregates; these types are handled via the
10157      targetm.calls.split_complex_arg mechanism.  Complex types
10158      can be elements of homogeneous aggregates, however.  */
10159   if (TARGET_HARD_FLOAT && DEFAULT_ABI == ABI_ELFv2 && type
10160       && AGGREGATE_TYPE_P (type))
10161     {
10162       machine_mode field_mode = VOIDmode;
10163       int field_count = rs6000_aggregate_candidate (type, &field_mode);
10164
10165       if (field_count > 0)
10166         {
10167           int reg_size = ALTIVEC_OR_VSX_VECTOR_MODE (field_mode) ? 16 : 8;
10168           int field_size = ROUND_UP (GET_MODE_SIZE (field_mode), reg_size);
10169
10170           /* The ELFv2 ABI allows homogeneous aggregates to occupy
10171              up to AGGR_ARG_NUM_REG registers.  */
10172           if (field_count * field_size <= AGGR_ARG_NUM_REG * reg_size)
10173             {
10174               if (elt_mode)
10175                 *elt_mode = field_mode;
10176               if (n_elts)
10177                 *n_elts = field_count;
10178               return true;
10179             }
10180         }
10181     }
10182
10183   if (elt_mode)
10184     *elt_mode = mode;
10185   if (n_elts)
10186     *n_elts = 1;
10187   return false;
10188 }
10189
10190 /* Return a nonzero value to say to return the function value in
10191    memory, just as large structures are always returned.  TYPE will be
10192    the data type of the value, and FNTYPE will be the type of the
10193    function doing the returning, or @code{NULL} for libcalls.
10194
10195    The AIX ABI for the RS/6000 specifies that all structures are
10196    returned in memory.  The Darwin ABI does the same.
10197    
10198    For the Darwin 64 Bit ABI, a function result can be returned in
10199    registers or in memory, depending on the size of the return data
10200    type.  If it is returned in registers, the value occupies the same
10201    registers as it would if it were the first and only function
10202    argument.  Otherwise, the function places its result in memory at
10203    the location pointed to by GPR3.
10204    
10205    The SVR4 ABI specifies that structures <= 8 bytes are returned in r3/r4, 
10206    but a draft put them in memory, and GCC used to implement the draft
10207    instead of the final standard.  Therefore, aix_struct_return
10208    controls this instead of DEFAULT_ABI; V.4 targets needing backward
10209    compatibility can change DRAFT_V4_STRUCT_RET to override the
10210    default, and -m switches get the final word.  See
10211    rs6000_option_override_internal for more details.
10212
10213    The PPC32 SVR4 ABI uses IEEE double extended for long double, if 128-bit
10214    long double support is enabled.  These values are returned in memory.
10215
10216    int_size_in_bytes returns -1 for variable size objects, which go in
10217    memory always.  The cast to unsigned makes -1 > 8.  */
10218
10219 static bool
10220 rs6000_return_in_memory (const_tree type, const_tree fntype ATTRIBUTE_UNUSED)
10221 {
10222   /* For the Darwin64 ABI, test if we can fit the return value in regs.  */
10223   if (TARGET_MACHO
10224       && rs6000_darwin64_abi
10225       && TREE_CODE (type) == RECORD_TYPE
10226       && int_size_in_bytes (type) > 0)
10227     {
10228       CUMULATIVE_ARGS valcum;
10229       rtx valret;
10230
10231       valcum.words = 0;
10232       valcum.fregno = FP_ARG_MIN_REG;
10233       valcum.vregno = ALTIVEC_ARG_MIN_REG;
10234       /* Do a trial code generation as if this were going to be passed
10235          as an argument; if any part goes in memory, we return NULL.  */
10236       valret = rs6000_darwin64_record_arg (&valcum, type, true, true);
10237       if (valret)
10238         return false;
10239       /* Otherwise fall through to more conventional ABI rules.  */
10240     }
10241
10242   /* The ELFv2 ABI returns homogeneous VFP aggregates in registers */
10243   if (rs6000_discover_homogeneous_aggregate (TYPE_MODE (type), type,
10244                                              NULL, NULL))
10245     return false;
10246
10247   /* The ELFv2 ABI returns aggregates up to 16B in registers */
10248   if (DEFAULT_ABI == ABI_ELFv2 && AGGREGATE_TYPE_P (type)
10249       && (unsigned HOST_WIDE_INT) int_size_in_bytes (type) <= 16)
10250     return false;
10251
10252   if (AGGREGATE_TYPE_P (type)
10253       && (aix_struct_return
10254           || (unsigned HOST_WIDE_INT) int_size_in_bytes (type) > 8))
10255     return true;
10256
10257   /* Allow -maltivec -mabi=no-altivec without warning.  Altivec vector
10258      modes only exist for GCC vector types if -maltivec.  */
10259   if (TARGET_32BIT && !TARGET_ALTIVEC_ABI
10260       && ALTIVEC_VECTOR_MODE (TYPE_MODE (type)))
10261     return false;
10262
10263   /* Return synthetic vectors in memory.  */
10264   if (TREE_CODE (type) == VECTOR_TYPE
10265       && int_size_in_bytes (type) > (TARGET_ALTIVEC_ABI ? 16 : 8))
10266     {
10267       static bool warned_for_return_big_vectors = false;
10268       if (!warned_for_return_big_vectors)
10269         {
10270           warning (OPT_Wpsabi, "GCC vector returned by reference: "
10271                    "non-standard ABI extension with no compatibility "
10272                    "guarantee");
10273           warned_for_return_big_vectors = true;
10274         }
10275       return true;
10276     }
10277
10278   if (DEFAULT_ABI == ABI_V4 && TARGET_IEEEQUAD
10279       && FLOAT128_IEEE_P (TYPE_MODE (type)))
10280     return true;
10281
10282   return false;
10283 }
10284
10285 /* Specify whether values returned in registers should be at the most
10286    significant end of a register.  We want aggregates returned by
10287    value to match the way aggregates are passed to functions.  */
10288
10289 static bool
10290 rs6000_return_in_msb (const_tree valtype)
10291 {
10292   return (DEFAULT_ABI == ABI_ELFv2
10293           && BYTES_BIG_ENDIAN
10294           && AGGREGATE_TYPE_P (valtype)
10295           && (rs6000_function_arg_padding (TYPE_MODE (valtype), valtype)
10296               == PAD_UPWARD));
10297 }
10298
10299 #ifdef HAVE_AS_GNU_ATTRIBUTE
10300 /* Return TRUE if a call to function FNDECL may be one that
10301    potentially affects the function calling ABI of the object file.  */
10302
10303 static bool
10304 call_ABI_of_interest (tree fndecl)
10305 {
10306   if (rs6000_gnu_attr && symtab->state == EXPANSION)
10307     {
10308       struct cgraph_node *c_node;
10309
10310       /* Libcalls are always interesting.  */
10311       if (fndecl == NULL_TREE)
10312         return true;
10313
10314       /* Any call to an external function is interesting.  */
10315       if (DECL_EXTERNAL (fndecl))
10316         return true;
10317
10318       /* Interesting functions that we are emitting in this object file.  */
10319       c_node = cgraph_node::get (fndecl);
10320       c_node = c_node->ultimate_alias_target ();
10321       return !c_node->only_called_directly_p ();
10322     }
10323   return false;
10324 }
10325 #endif
10326
10327 /* Initialize a variable CUM of type CUMULATIVE_ARGS
10328    for a call to a function whose data type is FNTYPE.
10329    For a library call, FNTYPE is 0 and RETURN_MODE the return value mode.
10330
10331    For incoming args we set the number of arguments in the prototype large
10332    so we never return a PARALLEL.  */
10333
10334 void
10335 init_cumulative_args (CUMULATIVE_ARGS *cum, tree fntype,
10336                       rtx libname ATTRIBUTE_UNUSED, int incoming,
10337                       int libcall, int n_named_args,
10338                       tree fndecl,
10339                       machine_mode return_mode ATTRIBUTE_UNUSED)
10340 {
10341   static CUMULATIVE_ARGS zero_cumulative;
10342
10343   *cum = zero_cumulative;
10344   cum->words = 0;
10345   cum->fregno = FP_ARG_MIN_REG;
10346   cum->vregno = ALTIVEC_ARG_MIN_REG;
10347   cum->prototype = (fntype && prototype_p (fntype));
10348   cum->call_cookie = ((DEFAULT_ABI == ABI_V4 && libcall)
10349                       ? CALL_LIBCALL : CALL_NORMAL);
10350   cum->sysv_gregno = GP_ARG_MIN_REG;
10351   cum->stdarg = stdarg_p (fntype);
10352   cum->libcall = libcall;
10353
10354   cum->nargs_prototype = 0;
10355   if (incoming || cum->prototype)
10356     cum->nargs_prototype = n_named_args;
10357
10358   /* Check for a longcall attribute.  */
10359   if ((!fntype && rs6000_default_long_calls)
10360       || (fntype
10361           && lookup_attribute ("longcall", TYPE_ATTRIBUTES (fntype))
10362           && !lookup_attribute ("shortcall", TYPE_ATTRIBUTES (fntype))))
10363     cum->call_cookie |= CALL_LONG;
10364   else if (DEFAULT_ABI != ABI_DARWIN)
10365     {
10366       bool is_local = (fndecl
10367                        && !DECL_EXTERNAL (fndecl)
10368                        && !DECL_WEAK (fndecl)
10369                        && (*targetm.binds_local_p) (fndecl));
10370       if (is_local)
10371         ;
10372       else if (flag_plt)
10373         {
10374           if (fntype
10375               && lookup_attribute ("noplt", TYPE_ATTRIBUTES (fntype)))
10376             cum->call_cookie |= CALL_LONG;
10377         }
10378       else
10379         {
10380           if (!(fntype
10381                 && lookup_attribute ("plt", TYPE_ATTRIBUTES (fntype))))
10382             cum->call_cookie |= CALL_LONG;
10383         }
10384     }
10385
10386   if (TARGET_DEBUG_ARG)
10387     {
10388       fprintf (stderr, "\ninit_cumulative_args:");
10389       if (fntype)
10390         {
10391           tree ret_type = TREE_TYPE (fntype);
10392           fprintf (stderr, " ret code = %s,",
10393                    get_tree_code_name (TREE_CODE (ret_type)));
10394         }
10395
10396       if (cum->call_cookie & CALL_LONG)
10397         fprintf (stderr, " longcall,");
10398
10399       fprintf (stderr, " proto = %d, nargs = %d\n",
10400                cum->prototype, cum->nargs_prototype);
10401     }
10402
10403 #ifdef HAVE_AS_GNU_ATTRIBUTE
10404   if (TARGET_ELF && (TARGET_64BIT || DEFAULT_ABI == ABI_V4))
10405     {
10406       cum->escapes = call_ABI_of_interest (fndecl);
10407       if (cum->escapes)
10408         {
10409           tree return_type;
10410
10411           if (fntype)
10412             {
10413               return_type = TREE_TYPE (fntype);
10414               return_mode = TYPE_MODE (return_type);
10415             }
10416           else
10417             return_type = lang_hooks.types.type_for_mode (return_mode, 0);
10418
10419           if (return_type != NULL)
10420             {
10421               if (TREE_CODE (return_type) == RECORD_TYPE
10422                   && TYPE_TRANSPARENT_AGGR (return_type))
10423                 {
10424                   return_type = TREE_TYPE (first_field (return_type));
10425                   return_mode = TYPE_MODE (return_type);
10426                 }
10427               if (AGGREGATE_TYPE_P (return_type)
10428                   && ((unsigned HOST_WIDE_INT) int_size_in_bytes (return_type)
10429                       <= 8))
10430                 rs6000_returns_struct = true;
10431             }
10432           if (SCALAR_FLOAT_MODE_P (return_mode))
10433             {
10434               rs6000_passes_float = true;
10435               if ((HAVE_LD_PPC_GNU_ATTR_LONG_DOUBLE || TARGET_64BIT)
10436                   && (FLOAT128_IBM_P (return_mode)
10437                       || FLOAT128_IEEE_P (return_mode)
10438                       || (return_type != NULL
10439                           && (TYPE_MAIN_VARIANT (return_type)
10440                               == long_double_type_node))))
10441                 rs6000_passes_long_double = true;
10442
10443               /* Note if we passed or return a IEEE 128-bit type.  We changed
10444                  the mangling for these types, and we may need to make an alias
10445                  with the old mangling.  */
10446               if (FLOAT128_IEEE_P (return_mode))
10447                 rs6000_passes_ieee128 = true;
10448             }
10449           if (ALTIVEC_OR_VSX_VECTOR_MODE (return_mode))
10450             rs6000_passes_vector = true;
10451         }
10452     }
10453 #endif
10454
10455   if (fntype
10456       && !TARGET_ALTIVEC
10457       && TARGET_ALTIVEC_ABI
10458       && ALTIVEC_VECTOR_MODE (TYPE_MODE (TREE_TYPE (fntype))))
10459     {
10460       error ("cannot return value in vector register because"
10461              " altivec instructions are disabled, use %qs"
10462              " to enable them", "-maltivec");
10463     }
10464 }
10465 \f
10466 /* The mode the ABI uses for a word.  This is not the same as word_mode
10467    for -m32 -mpowerpc64.  This is used to implement various target hooks.  */
10468
10469 static scalar_int_mode
10470 rs6000_abi_word_mode (void)
10471 {
10472   return TARGET_32BIT ? SImode : DImode;
10473 }
10474
10475 /* Implement the TARGET_OFFLOAD_OPTIONS hook.  */
10476 static char *
10477 rs6000_offload_options (void)
10478 {
10479   if (TARGET_64BIT)
10480     return xstrdup ("-foffload-abi=lp64");
10481   else
10482     return xstrdup ("-foffload-abi=ilp32");
10483 }
10484
10485 /* On rs6000, function arguments are promoted, as are function return
10486    values.  */
10487
10488 static machine_mode
10489 rs6000_promote_function_mode (const_tree type ATTRIBUTE_UNUSED,
10490                               machine_mode mode,
10491                               int *punsignedp ATTRIBUTE_UNUSED,
10492                               const_tree, int)
10493 {
10494   PROMOTE_MODE (mode, *punsignedp, type);
10495
10496   return mode;
10497 }
10498
10499 /* Return true if TYPE must be passed on the stack and not in registers.  */
10500
10501 static bool
10502 rs6000_must_pass_in_stack (machine_mode mode, const_tree type)
10503 {
10504   if (DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2 || TARGET_64BIT)
10505     return must_pass_in_stack_var_size (mode, type);
10506   else
10507     return must_pass_in_stack_var_size_or_pad (mode, type);
10508 }
10509
10510 static inline bool
10511 is_complex_IBM_long_double (machine_mode mode)
10512 {
10513   return mode == ICmode || (mode == TCmode && FLOAT128_IBM_P (TCmode));
10514 }
10515
10516 /* Whether ABI_V4 passes MODE args to a function in floating point
10517    registers.  */
10518
10519 static bool
10520 abi_v4_pass_in_fpr (machine_mode mode, bool named)
10521 {
10522   if (!TARGET_HARD_FLOAT)
10523     return false;
10524   if (mode == DFmode)
10525     return true;
10526   if (mode == SFmode && named)
10527     return true;
10528   /* ABI_V4 passes complex IBM long double in 8 gprs.
10529      Stupid, but we can't change the ABI now.  */
10530   if (is_complex_IBM_long_double (mode))
10531     return false;
10532   if (FLOAT128_2REG_P (mode))
10533     return true;
10534   if (DECIMAL_FLOAT_MODE_P (mode))
10535     return true;
10536   return false;
10537 }
10538
10539 /* Implement TARGET_FUNCTION_ARG_PADDING.
10540
10541    For the AIX ABI structs are always stored left shifted in their
10542    argument slot.  */
10543
10544 static pad_direction
10545 rs6000_function_arg_padding (machine_mode mode, const_tree type)
10546 {
10547 #ifndef AGGREGATE_PADDING_FIXED
10548 #define AGGREGATE_PADDING_FIXED 0
10549 #endif
10550 #ifndef AGGREGATES_PAD_UPWARD_ALWAYS
10551 #define AGGREGATES_PAD_UPWARD_ALWAYS 0
10552 #endif
10553
10554   if (!AGGREGATE_PADDING_FIXED)
10555     {
10556       /* GCC used to pass structures of the same size as integer types as
10557          if they were in fact integers, ignoring TARGET_FUNCTION_ARG_PADDING.
10558          i.e. Structures of size 1 or 2 (or 4 when TARGET_64BIT) were
10559          passed padded downward, except that -mstrict-align further
10560          muddied the water in that multi-component structures of 2 and 4
10561          bytes in size were passed padded upward.
10562
10563          The following arranges for best compatibility with previous
10564          versions of gcc, but removes the -mstrict-align dependency.  */
10565       if (BYTES_BIG_ENDIAN)
10566         {
10567           HOST_WIDE_INT size = 0;
10568
10569           if (mode == BLKmode)
10570             {
10571               if (type && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST)
10572                 size = int_size_in_bytes (type);
10573             }
10574           else
10575             size = GET_MODE_SIZE (mode);
10576
10577           if (size == 1 || size == 2 || size == 4)
10578             return PAD_DOWNWARD;
10579         }
10580       return PAD_UPWARD;
10581     }
10582
10583   if (AGGREGATES_PAD_UPWARD_ALWAYS)
10584     {
10585       if (type != 0 && AGGREGATE_TYPE_P (type))
10586         return PAD_UPWARD;
10587     }
10588
10589   /* Fall back to the default.  */
10590   return default_function_arg_padding (mode, type);
10591 }
10592
10593 /* If defined, a C expression that gives the alignment boundary, in bits,
10594    of an argument with the specified mode and type.  If it is not defined,
10595    PARM_BOUNDARY is used for all arguments.
10596
10597    V.4 wants long longs and doubles to be double word aligned.  Just
10598    testing the mode size is a boneheaded way to do this as it means
10599    that other types such as complex int are also double word aligned.
10600    However, we're stuck with this because changing the ABI might break
10601    existing library interfaces.
10602
10603    Quadword align Altivec/VSX vectors.
10604    Quadword align large synthetic vector types.   */
10605
10606 static unsigned int
10607 rs6000_function_arg_boundary (machine_mode mode, const_tree type)
10608 {
10609   machine_mode elt_mode;
10610   int n_elts;
10611
10612   rs6000_discover_homogeneous_aggregate (mode, type, &elt_mode, &n_elts);
10613
10614   if (DEFAULT_ABI == ABI_V4
10615       && (GET_MODE_SIZE (mode) == 8
10616           || (TARGET_HARD_FLOAT
10617               && !is_complex_IBM_long_double (mode)
10618               && FLOAT128_2REG_P (mode))))
10619     return 64;
10620   else if (FLOAT128_VECTOR_P (mode))
10621     return 128;
10622   else if (type && TREE_CODE (type) == VECTOR_TYPE
10623            && int_size_in_bytes (type) >= 8
10624            && int_size_in_bytes (type) < 16)
10625     return 64;
10626   else if (ALTIVEC_OR_VSX_VECTOR_MODE (elt_mode)
10627            || (type && TREE_CODE (type) == VECTOR_TYPE
10628                && int_size_in_bytes (type) >= 16))
10629     return 128;
10630
10631   /* Aggregate types that need > 8 byte alignment are quadword-aligned
10632      in the parameter area in the ELFv2 ABI, and in the AIX ABI unless
10633      -mcompat-align-parm is used.  */
10634   if (((DEFAULT_ABI == ABI_AIX && !rs6000_compat_align_parm)
10635        || DEFAULT_ABI == ABI_ELFv2)
10636       && type && TYPE_ALIGN (type) > 64)
10637     {
10638       /* "Aggregate" means any AGGREGATE_TYPE except for single-element
10639          or homogeneous float/vector aggregates here.  We already handled
10640          vector aggregates above, but still need to check for float here. */
10641       bool aggregate_p = (AGGREGATE_TYPE_P (type)
10642                           && !SCALAR_FLOAT_MODE_P (elt_mode));
10643
10644       /* We used to check for BLKmode instead of the above aggregate type
10645          check.  Warn when this results in any difference to the ABI.  */
10646       if (aggregate_p != (mode == BLKmode))
10647         {
10648           static bool warned;
10649           if (!warned && warn_psabi)
10650             {
10651               warned = true;
10652               inform (input_location,
10653                       "the ABI of passing aggregates with %d-byte alignment"
10654                       " has changed in GCC 5",
10655                       (int) TYPE_ALIGN (type) / BITS_PER_UNIT);
10656             }
10657         }
10658
10659       if (aggregate_p)
10660         return 128;
10661     }
10662
10663   /* Similar for the Darwin64 ABI.  Note that for historical reasons we
10664      implement the "aggregate type" check as a BLKmode check here; this
10665      means certain aggregate types are in fact not aligned.  */
10666   if (TARGET_MACHO && rs6000_darwin64_abi
10667       && mode == BLKmode
10668       && type && TYPE_ALIGN (type) > 64)
10669     return 128;
10670
10671   return PARM_BOUNDARY;
10672 }
10673
10674 /* The offset in words to the start of the parameter save area.  */
10675
10676 static unsigned int
10677 rs6000_parm_offset (void)
10678 {
10679   return (DEFAULT_ABI == ABI_V4 ? 2
10680           : DEFAULT_ABI == ABI_ELFv2 ? 4
10681           : 6);
10682 }
10683
10684 /* For a function parm of MODE and TYPE, return the starting word in
10685    the parameter area.  NWORDS of the parameter area are already used.  */
10686
10687 static unsigned int
10688 rs6000_parm_start (machine_mode mode, const_tree type,
10689                    unsigned int nwords)
10690 {
10691   unsigned int align;
10692
10693   align = rs6000_function_arg_boundary (mode, type) / PARM_BOUNDARY - 1;
10694   return nwords + (-(rs6000_parm_offset () + nwords) & align);
10695 }
10696
10697 /* Compute the size (in words) of a function argument.  */
10698
10699 static unsigned long
10700 rs6000_arg_size (machine_mode mode, const_tree type)
10701 {
10702   unsigned long size;
10703
10704   if (mode != BLKmode)
10705     size = GET_MODE_SIZE (mode);
10706   else
10707     size = int_size_in_bytes (type);
10708
10709   if (TARGET_32BIT)
10710     return (size + 3) >> 2;
10711   else
10712     return (size + 7) >> 3;
10713 }
10714 \f
10715 /* Use this to flush pending int fields.  */
10716
10717 static void
10718 rs6000_darwin64_record_arg_advance_flush (CUMULATIVE_ARGS *cum,
10719                                           HOST_WIDE_INT bitpos, int final)
10720 {
10721   unsigned int startbit, endbit;
10722   int intregs, intoffset;
10723
10724   /* Handle the situations where a float is taking up the first half
10725      of the GPR, and the other half is empty (typically due to
10726      alignment restrictions). We can detect this by a 8-byte-aligned
10727      int field, or by seeing that this is the final flush for this
10728      argument. Count the word and continue on.  */
10729   if (cum->floats_in_gpr == 1
10730       && (cum->intoffset % 64 == 0
10731           || (cum->intoffset == -1 && final)))
10732     {
10733       cum->words++;
10734       cum->floats_in_gpr = 0;
10735     }
10736
10737   if (cum->intoffset == -1)
10738     return;
10739
10740   intoffset = cum->intoffset;
10741   cum->intoffset = -1;
10742   cum->floats_in_gpr = 0;
10743
10744   if (intoffset % BITS_PER_WORD != 0)
10745     {
10746       unsigned int bits = BITS_PER_WORD - intoffset % BITS_PER_WORD;
10747       if (!int_mode_for_size (bits, 0).exists ())
10748         {
10749           /* We couldn't find an appropriate mode, which happens,
10750              e.g., in packed structs when there are 3 bytes to load.
10751              Back intoffset back to the beginning of the word in this
10752              case.  */
10753           intoffset = ROUND_DOWN (intoffset, BITS_PER_WORD);
10754         }
10755     }
10756
10757   startbit = ROUND_DOWN (intoffset, BITS_PER_WORD);
10758   endbit = ROUND_UP (bitpos, BITS_PER_WORD);
10759   intregs = (endbit - startbit) / BITS_PER_WORD;
10760   cum->words += intregs;
10761   /* words should be unsigned. */
10762   if ((unsigned)cum->words < (endbit/BITS_PER_WORD))
10763     {
10764       int pad = (endbit/BITS_PER_WORD) - cum->words;
10765       cum->words += pad;
10766     }
10767 }
10768
10769 /* The darwin64 ABI calls for us to recurse down through structs,
10770    looking for elements passed in registers.  Unfortunately, we have
10771    to track int register count here also because of misalignments
10772    in powerpc alignment mode.  */
10773
10774 static void
10775 rs6000_darwin64_record_arg_advance_recurse (CUMULATIVE_ARGS *cum,
10776                                             const_tree type,
10777                                             HOST_WIDE_INT startbitpos)
10778 {
10779   tree f;
10780
10781   for (f = TYPE_FIELDS (type); f ; f = DECL_CHAIN (f))
10782     if (TREE_CODE (f) == FIELD_DECL)
10783       {
10784         HOST_WIDE_INT bitpos = startbitpos;
10785         tree ftype = TREE_TYPE (f);
10786         machine_mode mode;
10787         if (ftype == error_mark_node)
10788           continue;
10789         mode = TYPE_MODE (ftype);
10790
10791         if (DECL_SIZE (f) != 0
10792             && tree_fits_uhwi_p (bit_position (f)))
10793           bitpos += int_bit_position (f);
10794
10795         /* ??? FIXME: else assume zero offset.  */
10796
10797         if (TREE_CODE (ftype) == RECORD_TYPE)
10798           rs6000_darwin64_record_arg_advance_recurse (cum, ftype, bitpos);
10799         else if (USE_FP_FOR_ARG_P (cum, mode))
10800           {
10801             unsigned n_fpregs = (GET_MODE_SIZE (mode) + 7) >> 3;
10802             rs6000_darwin64_record_arg_advance_flush (cum, bitpos, 0);
10803             cum->fregno += n_fpregs;
10804             /* Single-precision floats present a special problem for
10805                us, because they are smaller than an 8-byte GPR, and so
10806                the structure-packing rules combined with the standard
10807                varargs behavior mean that we want to pack float/float
10808                and float/int combinations into a single register's
10809                space. This is complicated by the arg advance flushing,
10810                which works on arbitrarily large groups of int-type
10811                fields.  */
10812             if (mode == SFmode)
10813               {
10814                 if (cum->floats_in_gpr == 1)
10815                   {
10816                     /* Two floats in a word; count the word and reset
10817                        the float count.  */
10818                     cum->words++;
10819                     cum->floats_in_gpr = 0;
10820                   }
10821                 else if (bitpos % 64 == 0)
10822                   {
10823                     /* A float at the beginning of an 8-byte word;
10824                        count it and put off adjusting cum->words until
10825                        we see if a arg advance flush is going to do it
10826                        for us.  */
10827                     cum->floats_in_gpr++;
10828                   }
10829                 else
10830                   {
10831                     /* The float is at the end of a word, preceded
10832                        by integer fields, so the arg advance flush
10833                        just above has already set cum->words and
10834                        everything is taken care of.  */
10835                   }
10836               }
10837             else
10838               cum->words += n_fpregs;
10839           }
10840         else if (USE_ALTIVEC_FOR_ARG_P (cum, mode, 1))
10841           {
10842             rs6000_darwin64_record_arg_advance_flush (cum, bitpos, 0);
10843             cum->vregno++;
10844             cum->words += 2;
10845           }
10846         else if (cum->intoffset == -1)
10847           cum->intoffset = bitpos;
10848       }
10849 }
10850
10851 /* Check for an item that needs to be considered specially under the darwin 64
10852    bit ABI.  These are record types where the mode is BLK or the structure is
10853    8 bytes in size.  */
10854 static int
10855 rs6000_darwin64_struct_check_p (machine_mode mode, const_tree type)
10856 {
10857   return rs6000_darwin64_abi
10858          && ((mode == BLKmode 
10859               && TREE_CODE (type) == RECORD_TYPE 
10860               && int_size_in_bytes (type) > 0)
10861           || (type && TREE_CODE (type) == RECORD_TYPE 
10862               && int_size_in_bytes (type) == 8)) ? 1 : 0;
10863 }
10864
10865 /* Update the data in CUM to advance over an argument
10866    of mode MODE and data type TYPE.
10867    (TYPE is null for libcalls where that information may not be available.)
10868
10869    Note that for args passed by reference, function_arg will be called
10870    with MODE and TYPE set to that of the pointer to the arg, not the arg
10871    itself.  */
10872
10873 static void
10874 rs6000_function_arg_advance_1 (CUMULATIVE_ARGS *cum, machine_mode mode,
10875                                const_tree type, bool named, int depth)
10876 {
10877   machine_mode elt_mode;
10878   int n_elts;
10879
10880   rs6000_discover_homogeneous_aggregate (mode, type, &elt_mode, &n_elts);
10881
10882   /* Only tick off an argument if we're not recursing.  */
10883   if (depth == 0)
10884     cum->nargs_prototype--;
10885
10886 #ifdef HAVE_AS_GNU_ATTRIBUTE
10887   if (TARGET_ELF && (TARGET_64BIT || DEFAULT_ABI == ABI_V4)
10888       && cum->escapes)
10889     {
10890       if (SCALAR_FLOAT_MODE_P (mode))
10891         {
10892           rs6000_passes_float = true;
10893           if ((HAVE_LD_PPC_GNU_ATTR_LONG_DOUBLE || TARGET_64BIT)
10894               && (FLOAT128_IBM_P (mode)
10895                   || FLOAT128_IEEE_P (mode)
10896                   || (type != NULL
10897                       && TYPE_MAIN_VARIANT (type) == long_double_type_node)))
10898             rs6000_passes_long_double = true;
10899
10900           /* Note if we passed or return a IEEE 128-bit type.  We changed the
10901              mangling for these types, and we may need to make an alias with
10902              the old mangling.  */
10903           if (FLOAT128_IEEE_P (mode))
10904             rs6000_passes_ieee128 = true;
10905         }
10906       if (named && ALTIVEC_OR_VSX_VECTOR_MODE (mode))
10907         rs6000_passes_vector = true;
10908     }
10909 #endif
10910
10911   if (TARGET_ALTIVEC_ABI
10912       && (ALTIVEC_OR_VSX_VECTOR_MODE (elt_mode)
10913           || (type && TREE_CODE (type) == VECTOR_TYPE
10914               && int_size_in_bytes (type) == 16)))
10915     {
10916       bool stack = false;
10917
10918       if (USE_ALTIVEC_FOR_ARG_P (cum, elt_mode, named))
10919         {
10920           cum->vregno += n_elts;
10921
10922           if (!TARGET_ALTIVEC)
10923             error ("cannot pass argument in vector register because"
10924                    " altivec instructions are disabled, use %qs"
10925                    " to enable them", "-maltivec");
10926
10927           /* PowerPC64 Linux and AIX allocate GPRs for a vector argument
10928              even if it is going to be passed in a vector register.
10929              Darwin does the same for variable-argument functions.  */
10930           if (((DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
10931                && TARGET_64BIT)
10932               || (cum->stdarg && DEFAULT_ABI != ABI_V4))
10933             stack = true;
10934         }
10935       else
10936         stack = true;
10937
10938       if (stack)
10939         {
10940           int align;
10941
10942           /* Vector parameters must be 16-byte aligned.  In 32-bit
10943              mode this means we need to take into account the offset
10944              to the parameter save area.  In 64-bit mode, they just
10945              have to start on an even word, since the parameter save
10946              area is 16-byte aligned.  */
10947           if (TARGET_32BIT)
10948             align = -(rs6000_parm_offset () + cum->words) & 3;
10949           else
10950             align = cum->words & 1;
10951           cum->words += align + rs6000_arg_size (mode, type);
10952
10953           if (TARGET_DEBUG_ARG)
10954             {
10955               fprintf (stderr, "function_adv: words = %2d, align=%d, ",
10956                        cum->words, align);
10957               fprintf (stderr, "nargs = %4d, proto = %d, mode = %4s\n",
10958                        cum->nargs_prototype, cum->prototype,
10959                        GET_MODE_NAME (mode));
10960             }
10961         }
10962     }
10963   else if (TARGET_MACHO && rs6000_darwin64_struct_check_p (mode, type))
10964     {
10965       int size = int_size_in_bytes (type);
10966       /* Variable sized types have size == -1 and are
10967          treated as if consisting entirely of ints.
10968          Pad to 16 byte boundary if needed.  */
10969       if (TYPE_ALIGN (type) >= 2 * BITS_PER_WORD
10970           && (cum->words % 2) != 0)
10971         cum->words++;
10972       /* For varargs, we can just go up by the size of the struct. */
10973       if (!named)
10974         cum->words += (size + 7) / 8;
10975       else
10976         {
10977           /* It is tempting to say int register count just goes up by
10978              sizeof(type)/8, but this is wrong in a case such as
10979              { int; double; int; } [powerpc alignment].  We have to
10980              grovel through the fields for these too.  */
10981           cum->intoffset = 0;
10982           cum->floats_in_gpr = 0;
10983           rs6000_darwin64_record_arg_advance_recurse (cum, type, 0);
10984           rs6000_darwin64_record_arg_advance_flush (cum,
10985                                                     size * BITS_PER_UNIT, 1);
10986         }
10987           if (TARGET_DEBUG_ARG)
10988             {
10989               fprintf (stderr, "function_adv: words = %2d, align=%d, size=%d",
10990                        cum->words, TYPE_ALIGN (type), size);
10991               fprintf (stderr, 
10992                    "nargs = %4d, proto = %d, mode = %4s (darwin64 abi)\n",
10993                        cum->nargs_prototype, cum->prototype,
10994                        GET_MODE_NAME (mode));
10995             }
10996     }
10997   else if (DEFAULT_ABI == ABI_V4)
10998     {
10999       if (abi_v4_pass_in_fpr (mode, named))
11000         {
11001           /* _Decimal128 must use an even/odd register pair.  This assumes
11002              that the register number is odd when fregno is odd.  */
11003           if (mode == TDmode && (cum->fregno % 2) == 1)
11004             cum->fregno++;
11005
11006           if (cum->fregno + (FLOAT128_2REG_P (mode) ? 1 : 0)
11007               <= FP_ARG_V4_MAX_REG)
11008             cum->fregno += (GET_MODE_SIZE (mode) + 7) >> 3;
11009           else
11010             {
11011               cum->fregno = FP_ARG_V4_MAX_REG + 1;
11012               if (mode == DFmode || FLOAT128_IBM_P (mode)
11013                   || mode == DDmode || mode == TDmode)
11014                 cum->words += cum->words & 1;
11015               cum->words += rs6000_arg_size (mode, type);
11016             }
11017         }
11018       else
11019         {
11020           int n_words = rs6000_arg_size (mode, type);
11021           int gregno = cum->sysv_gregno;
11022
11023           /* Long long is put in (r3,r4), (r5,r6), (r7,r8) or (r9,r10).
11024              As does any other 2 word item such as complex int due to a
11025              historical mistake.  */
11026           if (n_words == 2)
11027             gregno += (1 - gregno) & 1;
11028
11029           /* Multi-reg args are not split between registers and stack.  */
11030           if (gregno + n_words - 1 > GP_ARG_MAX_REG)
11031             {
11032               /* Long long is aligned on the stack.  So are other 2 word
11033                  items such as complex int due to a historical mistake.  */
11034               if (n_words == 2)
11035                 cum->words += cum->words & 1;
11036               cum->words += n_words;
11037             }
11038
11039           /* Note: continuing to accumulate gregno past when we've started
11040              spilling to the stack indicates the fact that we've started
11041              spilling to the stack to expand_builtin_saveregs.  */
11042           cum->sysv_gregno = gregno + n_words;
11043         }
11044
11045       if (TARGET_DEBUG_ARG)
11046         {
11047           fprintf (stderr, "function_adv: words = %2d, fregno = %2d, ",
11048                    cum->words, cum->fregno);
11049           fprintf (stderr, "gregno = %2d, nargs = %4d, proto = %d, ",
11050                    cum->sysv_gregno, cum->nargs_prototype, cum->prototype);
11051           fprintf (stderr, "mode = %4s, named = %d\n",
11052                    GET_MODE_NAME (mode), named);
11053         }
11054     }
11055   else
11056     {
11057       int n_words = rs6000_arg_size (mode, type);
11058       int start_words = cum->words;
11059       int align_words = rs6000_parm_start (mode, type, start_words);
11060
11061       cum->words = align_words + n_words;
11062
11063       if (SCALAR_FLOAT_MODE_P (elt_mode) && TARGET_HARD_FLOAT)
11064         {
11065           /* _Decimal128 must be passed in an even/odd float register pair.
11066              This assumes that the register number is odd when fregno is
11067              odd.  */
11068           if (elt_mode == TDmode && (cum->fregno % 2) == 1)
11069             cum->fregno++;
11070           cum->fregno += n_elts * ((GET_MODE_SIZE (elt_mode) + 7) >> 3);
11071         }
11072
11073       if (TARGET_DEBUG_ARG)
11074         {
11075           fprintf (stderr, "function_adv: words = %2d, fregno = %2d, ",
11076                    cum->words, cum->fregno);
11077           fprintf (stderr, "nargs = %4d, proto = %d, mode = %4s, ",
11078                    cum->nargs_prototype, cum->prototype, GET_MODE_NAME (mode));
11079           fprintf (stderr, "named = %d, align = %d, depth = %d\n",
11080                    named, align_words - start_words, depth);
11081         }
11082     }
11083 }
11084
11085 static void
11086 rs6000_function_arg_advance (cumulative_args_t cum, machine_mode mode,
11087                              const_tree type, bool named)
11088 {
11089   rs6000_function_arg_advance_1 (get_cumulative_args (cum), mode, type, named,
11090                                  0);
11091 }
11092
11093 /* A subroutine of rs6000_darwin64_record_arg.  Assign the bits of the
11094    structure between cum->intoffset and bitpos to integer registers.  */
11095
11096 static void
11097 rs6000_darwin64_record_arg_flush (CUMULATIVE_ARGS *cum,
11098                                   HOST_WIDE_INT bitpos, rtx rvec[], int *k)
11099 {
11100   machine_mode mode;
11101   unsigned int regno;
11102   unsigned int startbit, endbit;
11103   int this_regno, intregs, intoffset;
11104   rtx reg;
11105
11106   if (cum->intoffset == -1)
11107     return;
11108
11109   intoffset = cum->intoffset;
11110   cum->intoffset = -1;
11111
11112   /* If this is the trailing part of a word, try to only load that
11113      much into the register.  Otherwise load the whole register.  Note
11114      that in the latter case we may pick up unwanted bits.  It's not a
11115      problem at the moment but may wish to revisit.  */
11116
11117   if (intoffset % BITS_PER_WORD != 0)
11118     {
11119       unsigned int bits = BITS_PER_WORD - intoffset % BITS_PER_WORD;
11120       if (!int_mode_for_size (bits, 0).exists (&mode))
11121         {
11122           /* We couldn't find an appropriate mode, which happens,
11123              e.g., in packed structs when there are 3 bytes to load.
11124              Back intoffset back to the beginning of the word in this
11125              case.  */
11126           intoffset = ROUND_DOWN (intoffset, BITS_PER_WORD);
11127           mode = word_mode;
11128         }
11129     }
11130   else
11131     mode = word_mode;
11132
11133   startbit = ROUND_DOWN (intoffset, BITS_PER_WORD);
11134   endbit = ROUND_UP (bitpos, BITS_PER_WORD);
11135   intregs = (endbit - startbit) / BITS_PER_WORD;
11136   this_regno = cum->words + intoffset / BITS_PER_WORD;
11137
11138   if (intregs > 0 && intregs > GP_ARG_NUM_REG - this_regno)
11139     cum->use_stack = 1;
11140
11141   intregs = MIN (intregs, GP_ARG_NUM_REG - this_regno);
11142   if (intregs <= 0)
11143     return;
11144
11145   intoffset /= BITS_PER_UNIT;
11146   do
11147     {
11148       regno = GP_ARG_MIN_REG + this_regno;
11149       reg = gen_rtx_REG (mode, regno);
11150       rvec[(*k)++] =
11151         gen_rtx_EXPR_LIST (VOIDmode, reg, GEN_INT (intoffset));
11152
11153       this_regno += 1;
11154       intoffset = (intoffset | (UNITS_PER_WORD-1)) + 1;
11155       mode = word_mode;
11156       intregs -= 1;
11157     }
11158   while (intregs > 0);
11159 }
11160
11161 /* Recursive workhorse for the following.  */
11162
11163 static void
11164 rs6000_darwin64_record_arg_recurse (CUMULATIVE_ARGS *cum, const_tree type,
11165                                     HOST_WIDE_INT startbitpos, rtx rvec[],
11166                                     int *k)
11167 {
11168   tree f;
11169
11170   for (f = TYPE_FIELDS (type); f ; f = DECL_CHAIN (f))
11171     if (TREE_CODE (f) == FIELD_DECL)
11172       {
11173         HOST_WIDE_INT bitpos = startbitpos;
11174         tree ftype = TREE_TYPE (f);
11175         machine_mode mode;
11176         if (ftype == error_mark_node)
11177           continue;
11178         mode = TYPE_MODE (ftype);
11179
11180         if (DECL_SIZE (f) != 0
11181             && tree_fits_uhwi_p (bit_position (f)))
11182           bitpos += int_bit_position (f);
11183
11184         /* ??? FIXME: else assume zero offset.  */
11185
11186         if (TREE_CODE (ftype) == RECORD_TYPE)
11187           rs6000_darwin64_record_arg_recurse (cum, ftype, bitpos, rvec, k);
11188         else if (cum->named && USE_FP_FOR_ARG_P (cum, mode))
11189           {
11190             unsigned n_fpreg = (GET_MODE_SIZE (mode) + 7) >> 3;
11191 #if 0
11192             switch (mode)
11193               {
11194               case E_SCmode: mode = SFmode; break;
11195               case E_DCmode: mode = DFmode; break;
11196               case E_TCmode: mode = TFmode; break;
11197               default: break;
11198               }
11199 #endif
11200             rs6000_darwin64_record_arg_flush (cum, bitpos, rvec, k);
11201             if (cum->fregno + n_fpreg > FP_ARG_MAX_REG + 1)
11202               {
11203                 gcc_assert (cum->fregno == FP_ARG_MAX_REG
11204                             && (mode == TFmode || mode == TDmode));
11205                 /* Long double or _Decimal128 split over regs and memory.  */
11206                 mode = DECIMAL_FLOAT_MODE_P (mode) ? DDmode : DFmode;
11207                 cum->use_stack=1;
11208               }
11209             rvec[(*k)++]
11210               = gen_rtx_EXPR_LIST (VOIDmode,
11211                                    gen_rtx_REG (mode, cum->fregno++),
11212                                    GEN_INT (bitpos / BITS_PER_UNIT));
11213             if (FLOAT128_2REG_P (mode))
11214               cum->fregno++;
11215           }
11216         else if (cum->named && USE_ALTIVEC_FOR_ARG_P (cum, mode, 1))
11217           {
11218             rs6000_darwin64_record_arg_flush (cum, bitpos, rvec, k);
11219             rvec[(*k)++]
11220               = gen_rtx_EXPR_LIST (VOIDmode,
11221                                    gen_rtx_REG (mode, cum->vregno++),
11222                                    GEN_INT (bitpos / BITS_PER_UNIT));
11223           }
11224         else if (cum->intoffset == -1)
11225           cum->intoffset = bitpos;
11226       }
11227 }
11228
11229 /* For the darwin64 ABI, we want to construct a PARALLEL consisting of
11230    the register(s) to be used for each field and subfield of a struct
11231    being passed by value, along with the offset of where the
11232    register's value may be found in the block.  FP fields go in FP
11233    register, vector fields go in vector registers, and everything
11234    else goes in int registers, packed as in memory.
11235
11236    This code is also used for function return values.  RETVAL indicates
11237    whether this is the case.
11238
11239    Much of this is taken from the SPARC V9 port, which has a similar
11240    calling convention.  */
11241
11242 static rtx
11243 rs6000_darwin64_record_arg (CUMULATIVE_ARGS *orig_cum, const_tree type,
11244                             bool named, bool retval)
11245 {
11246   rtx rvec[FIRST_PSEUDO_REGISTER];
11247   int k = 1, kbase = 1;
11248   HOST_WIDE_INT typesize = int_size_in_bytes (type);
11249   /* This is a copy; modifications are not visible to our caller.  */
11250   CUMULATIVE_ARGS copy_cum = *orig_cum;
11251   CUMULATIVE_ARGS *cum = &copy_cum;
11252
11253   /* Pad to 16 byte boundary if needed.  */
11254   if (!retval && TYPE_ALIGN (type) >= 2 * BITS_PER_WORD
11255       && (cum->words % 2) != 0)
11256     cum->words++;
11257
11258   cum->intoffset = 0;
11259   cum->use_stack = 0;
11260   cum->named = named;
11261
11262   /* Put entries into rvec[] for individual FP and vector fields, and
11263      for the chunks of memory that go in int regs.  Note we start at
11264      element 1; 0 is reserved for an indication of using memory, and
11265      may or may not be filled in below. */
11266   rs6000_darwin64_record_arg_recurse (cum, type, /* startbit pos= */ 0, rvec, &k);
11267   rs6000_darwin64_record_arg_flush (cum, typesize * BITS_PER_UNIT, rvec, &k);
11268
11269   /* If any part of the struct went on the stack put all of it there.
11270      This hack is because the generic code for
11271      FUNCTION_ARG_PARTIAL_NREGS cannot handle cases where the register
11272      parts of the struct are not at the beginning.  */
11273   if (cum->use_stack)
11274     {
11275       if (retval)
11276         return NULL_RTX;    /* doesn't go in registers at all */
11277       kbase = 0;
11278       rvec[0] = gen_rtx_EXPR_LIST (VOIDmode, NULL_RTX, const0_rtx);
11279     }
11280   if (k > 1 || cum->use_stack)
11281     return gen_rtx_PARALLEL (BLKmode, gen_rtvec_v (k - kbase, &rvec[kbase]));
11282   else
11283     return NULL_RTX;
11284 }
11285
11286 /* Determine where to place an argument in 64-bit mode with 32-bit ABI.  */
11287
11288 static rtx
11289 rs6000_mixed_function_arg (machine_mode mode, const_tree type,
11290                            int align_words)
11291 {
11292   int n_units;
11293   int i, k;
11294   rtx rvec[GP_ARG_NUM_REG + 1];
11295
11296   if (align_words >= GP_ARG_NUM_REG)
11297     return NULL_RTX;
11298
11299   n_units = rs6000_arg_size (mode, type);
11300
11301   /* Optimize the simple case where the arg fits in one gpr, except in
11302      the case of BLKmode due to assign_parms assuming that registers are
11303      BITS_PER_WORD wide.  */
11304   if (n_units == 0
11305       || (n_units == 1 && mode != BLKmode))
11306     return gen_rtx_REG (mode, GP_ARG_MIN_REG + align_words);
11307
11308   k = 0;
11309   if (align_words + n_units > GP_ARG_NUM_REG)
11310     /* Not all of the arg fits in gprs.  Say that it goes in memory too,
11311        using a magic NULL_RTX component.
11312        This is not strictly correct.  Only some of the arg belongs in
11313        memory, not all of it.  However, the normal scheme using
11314        function_arg_partial_nregs can result in unusual subregs, eg.
11315        (subreg:SI (reg:DF) 4), which are not handled well.  The code to
11316        store the whole arg to memory is often more efficient than code
11317        to store pieces, and we know that space is available in the right
11318        place for the whole arg.  */
11319     rvec[k++] = gen_rtx_EXPR_LIST (VOIDmode, NULL_RTX, const0_rtx);
11320
11321   i = 0;
11322   do
11323     {
11324       rtx r = gen_rtx_REG (SImode, GP_ARG_MIN_REG + align_words);
11325       rtx off = GEN_INT (i++ * 4);
11326       rvec[k++] = gen_rtx_EXPR_LIST (VOIDmode, r, off);
11327     }
11328   while (++align_words < GP_ARG_NUM_REG && --n_units != 0);
11329
11330   return gen_rtx_PARALLEL (mode, gen_rtvec_v (k, rvec));
11331 }
11332
11333 /* We have an argument of MODE and TYPE that goes into FPRs or VRs,
11334    but must also be copied into the parameter save area starting at
11335    offset ALIGN_WORDS.  Fill in RVEC with the elements corresponding
11336    to the GPRs and/or memory.  Return the number of elements used.  */
11337
11338 static int
11339 rs6000_psave_function_arg (machine_mode mode, const_tree type,
11340                            int align_words, rtx *rvec)
11341 {
11342   int k = 0;
11343
11344   if (align_words < GP_ARG_NUM_REG)
11345     {
11346       int n_words = rs6000_arg_size (mode, type);
11347
11348       if (align_words + n_words > GP_ARG_NUM_REG
11349           || mode == BLKmode
11350           || (TARGET_32BIT && TARGET_POWERPC64))
11351         {
11352           /* If this is partially on the stack, then we only
11353              include the portion actually in registers here.  */
11354           machine_mode rmode = TARGET_32BIT ? SImode : DImode;
11355           int i = 0;
11356
11357           if (align_words + n_words > GP_ARG_NUM_REG)
11358             {
11359               /* Not all of the arg fits in gprs.  Say that it goes in memory
11360                  too, using a magic NULL_RTX component.  Also see comment in
11361                  rs6000_mixed_function_arg for why the normal
11362                  function_arg_partial_nregs scheme doesn't work in this case. */
11363               rvec[k++] = gen_rtx_EXPR_LIST (VOIDmode, NULL_RTX, const0_rtx);
11364             }
11365
11366           do
11367             {
11368               rtx r = gen_rtx_REG (rmode, GP_ARG_MIN_REG + align_words);
11369               rtx off = GEN_INT (i++ * GET_MODE_SIZE (rmode));
11370               rvec[k++] = gen_rtx_EXPR_LIST (VOIDmode, r, off);
11371             }
11372           while (++align_words < GP_ARG_NUM_REG && --n_words != 0);
11373         }
11374       else
11375         {
11376           /* The whole arg fits in gprs.  */
11377           rtx r = gen_rtx_REG (mode, GP_ARG_MIN_REG + align_words);
11378           rvec[k++] = gen_rtx_EXPR_LIST (VOIDmode, r, const0_rtx);
11379         }
11380     }
11381   else
11382     {
11383       /* It's entirely in memory.  */
11384       rvec[k++] = gen_rtx_EXPR_LIST (VOIDmode, NULL_RTX, const0_rtx);
11385     }
11386
11387   return k;
11388 }
11389
11390 /* RVEC is a vector of K components of an argument of mode MODE.
11391    Construct the final function_arg return value from it.  */
11392
11393 static rtx
11394 rs6000_finish_function_arg (machine_mode mode, rtx *rvec, int k)
11395 {
11396   gcc_assert (k >= 1);
11397
11398   /* Avoid returning a PARALLEL in the trivial cases.  */
11399   if (k == 1)
11400     {
11401       if (XEXP (rvec[0], 0) == NULL_RTX)
11402         return NULL_RTX;
11403
11404       if (GET_MODE (XEXP (rvec[0], 0)) == mode)
11405         return XEXP (rvec[0], 0);
11406     }
11407
11408   return gen_rtx_PARALLEL (mode, gen_rtvec_v (k, rvec));
11409 }
11410
11411 /* Determine where to put an argument to a function.
11412    Value is zero to push the argument on the stack,
11413    or a hard register in which to store the argument.
11414
11415    MODE is the argument's machine mode.
11416    TYPE is the data type of the argument (as a tree).
11417     This is null for libcalls where that information may
11418     not be available.
11419    CUM is a variable of type CUMULATIVE_ARGS which gives info about
11420     the preceding args and about the function being called.  It is
11421     not modified in this routine.
11422    NAMED is nonzero if this argument is a named parameter
11423     (otherwise it is an extra parameter matching an ellipsis).
11424
11425    On RS/6000 the first eight words of non-FP are normally in registers
11426    and the rest are pushed.  Under AIX, the first 13 FP args are in registers.
11427    Under V.4, the first 8 FP args are in registers.
11428
11429    If this is floating-point and no prototype is specified, we use
11430    both an FP and integer register (or possibly FP reg and stack).  Library
11431    functions (when CALL_LIBCALL is set) always have the proper types for args,
11432    so we can pass the FP value just in one register.  emit_library_function
11433    doesn't support PARALLEL anyway.
11434
11435    Note that for args passed by reference, function_arg will be called
11436    with MODE and TYPE set to that of the pointer to the arg, not the arg
11437    itself.  */
11438
11439 static rtx
11440 rs6000_function_arg (cumulative_args_t cum_v, machine_mode mode,
11441                      const_tree type, bool named)
11442 {
11443   CUMULATIVE_ARGS *cum = get_cumulative_args (cum_v);
11444   enum rs6000_abi abi = DEFAULT_ABI;
11445   machine_mode elt_mode;
11446   int n_elts;
11447
11448   /* Return a marker to indicate whether CR1 needs to set or clear the
11449      bit that V.4 uses to say fp args were passed in registers.
11450      Assume that we don't need the marker for software floating point,
11451      or compiler generated library calls.  */
11452   if (mode == VOIDmode)
11453     {
11454       if (abi == ABI_V4
11455           && (cum->call_cookie & CALL_LIBCALL) == 0
11456           && (cum->stdarg
11457               || (cum->nargs_prototype < 0
11458                   && (cum->prototype || TARGET_NO_PROTOTYPE)))
11459           && TARGET_HARD_FLOAT)
11460         return GEN_INT (cum->call_cookie
11461                         | ((cum->fregno == FP_ARG_MIN_REG)
11462                            ? CALL_V4_SET_FP_ARGS
11463                            : CALL_V4_CLEAR_FP_ARGS));
11464
11465       return GEN_INT (cum->call_cookie & ~CALL_LIBCALL);
11466     }
11467
11468   rs6000_discover_homogeneous_aggregate (mode, type, &elt_mode, &n_elts);
11469
11470   if (TARGET_MACHO && rs6000_darwin64_struct_check_p (mode, type))
11471     {
11472       rtx rslt = rs6000_darwin64_record_arg (cum, type, named, /*retval= */false);
11473       if (rslt != NULL_RTX)
11474         return rslt;
11475       /* Else fall through to usual handling.  */
11476     }
11477
11478   if (USE_ALTIVEC_FOR_ARG_P (cum, elt_mode, named))
11479     {
11480       rtx rvec[GP_ARG_NUM_REG + AGGR_ARG_NUM_REG + 1];
11481       rtx r, off;
11482       int i, k = 0;
11483
11484       /* Do we also need to pass this argument in the parameter save area?
11485          Library support functions for IEEE 128-bit are assumed to not need the
11486          value passed both in GPRs and in vector registers.  */
11487       if (TARGET_64BIT && !cum->prototype
11488           && (!cum->libcall || !FLOAT128_VECTOR_P (elt_mode)))
11489         {
11490           int align_words = ROUND_UP (cum->words, 2);
11491           k = rs6000_psave_function_arg (mode, type, align_words, rvec);
11492         }
11493
11494       /* Describe where this argument goes in the vector registers.  */
11495       for (i = 0; i < n_elts && cum->vregno + i <= ALTIVEC_ARG_MAX_REG; i++)
11496         {
11497           r = gen_rtx_REG (elt_mode, cum->vregno + i);
11498           off = GEN_INT (i * GET_MODE_SIZE (elt_mode));
11499           rvec[k++] =  gen_rtx_EXPR_LIST (VOIDmode, r, off);
11500         }
11501
11502       return rs6000_finish_function_arg (mode, rvec, k);
11503     }
11504   else if (TARGET_ALTIVEC_ABI
11505            && (ALTIVEC_OR_VSX_VECTOR_MODE (mode)
11506                || (type && TREE_CODE (type) == VECTOR_TYPE
11507                    && int_size_in_bytes (type) == 16)))
11508     {
11509       if (named || abi == ABI_V4)
11510         return NULL_RTX;
11511       else
11512         {
11513           /* Vector parameters to varargs functions under AIX or Darwin
11514              get passed in memory and possibly also in GPRs.  */
11515           int align, align_words, n_words;
11516           machine_mode part_mode;
11517
11518           /* Vector parameters must be 16-byte aligned.  In 32-bit
11519              mode this means we need to take into account the offset
11520              to the parameter save area.  In 64-bit mode, they just
11521              have to start on an even word, since the parameter save
11522              area is 16-byte aligned.  */
11523           if (TARGET_32BIT)
11524             align = -(rs6000_parm_offset () + cum->words) & 3;
11525           else
11526             align = cum->words & 1;
11527           align_words = cum->words + align;
11528
11529           /* Out of registers?  Memory, then.  */
11530           if (align_words >= GP_ARG_NUM_REG)
11531             return NULL_RTX;
11532
11533           if (TARGET_32BIT && TARGET_POWERPC64)
11534             return rs6000_mixed_function_arg (mode, type, align_words);
11535
11536           /* The vector value goes in GPRs.  Only the part of the
11537              value in GPRs is reported here.  */
11538           part_mode = mode;
11539           n_words = rs6000_arg_size (mode, type);
11540           if (align_words + n_words > GP_ARG_NUM_REG)
11541             /* Fortunately, there are only two possibilities, the value
11542                is either wholly in GPRs or half in GPRs and half not.  */
11543             part_mode = DImode;
11544
11545           return gen_rtx_REG (part_mode, GP_ARG_MIN_REG + align_words);
11546         }
11547     }
11548
11549   else if (abi == ABI_V4)
11550     {
11551       if (abi_v4_pass_in_fpr (mode, named))
11552         {
11553           /* _Decimal128 must use an even/odd register pair.  This assumes
11554              that the register number is odd when fregno is odd.  */
11555           if (mode == TDmode && (cum->fregno % 2) == 1)
11556             cum->fregno++;
11557
11558           if (cum->fregno + (FLOAT128_2REG_P (mode) ? 1 : 0)
11559               <= FP_ARG_V4_MAX_REG)
11560             return gen_rtx_REG (mode, cum->fregno);
11561           else
11562             return NULL_RTX;
11563         }
11564       else
11565         {
11566           int n_words = rs6000_arg_size (mode, type);
11567           int gregno = cum->sysv_gregno;
11568
11569           /* Long long is put in (r3,r4), (r5,r6), (r7,r8) or (r9,r10).
11570              As does any other 2 word item such as complex int due to a
11571              historical mistake.  */
11572           if (n_words == 2)
11573             gregno += (1 - gregno) & 1;
11574
11575           /* Multi-reg args are not split between registers and stack.  */
11576           if (gregno + n_words - 1 > GP_ARG_MAX_REG)
11577             return NULL_RTX;
11578
11579           if (TARGET_32BIT && TARGET_POWERPC64)
11580             return rs6000_mixed_function_arg (mode, type,
11581                                               gregno - GP_ARG_MIN_REG);
11582           return gen_rtx_REG (mode, gregno);
11583         }
11584     }
11585   else
11586     {
11587       int align_words = rs6000_parm_start (mode, type, cum->words);
11588
11589       /* _Decimal128 must be passed in an even/odd float register pair.
11590          This assumes that the register number is odd when fregno is odd.  */
11591       if (elt_mode == TDmode && (cum->fregno % 2) == 1)
11592         cum->fregno++;
11593
11594       if (USE_FP_FOR_ARG_P (cum, elt_mode)
11595           && !(TARGET_AIX && !TARGET_ELF
11596                && type != NULL && AGGREGATE_TYPE_P (type)))
11597         {
11598           rtx rvec[GP_ARG_NUM_REG + AGGR_ARG_NUM_REG + 1];
11599           rtx r, off;
11600           int i, k = 0;
11601           unsigned long n_fpreg = (GET_MODE_SIZE (elt_mode) + 7) >> 3;
11602           int fpr_words;
11603
11604           /* Do we also need to pass this argument in the parameter
11605              save area?  */
11606           if (type && (cum->nargs_prototype <= 0
11607                        || ((DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
11608                            && TARGET_XL_COMPAT
11609                            && align_words >= GP_ARG_NUM_REG)))
11610             k = rs6000_psave_function_arg (mode, type, align_words, rvec);
11611
11612           /* Describe where this argument goes in the fprs.  */
11613           for (i = 0; i < n_elts
11614                       && cum->fregno + i * n_fpreg <= FP_ARG_MAX_REG; i++)
11615             {
11616               /* Check if the argument is split over registers and memory.
11617                  This can only ever happen for long double or _Decimal128;
11618                  complex types are handled via split_complex_arg.  */
11619               machine_mode fmode = elt_mode;
11620               if (cum->fregno + (i + 1) * n_fpreg > FP_ARG_MAX_REG + 1)
11621                 {
11622                   gcc_assert (FLOAT128_2REG_P (fmode));
11623                   fmode = DECIMAL_FLOAT_MODE_P (fmode) ? DDmode : DFmode;
11624                 }
11625
11626               r = gen_rtx_REG (fmode, cum->fregno + i * n_fpreg);
11627               off = GEN_INT (i * GET_MODE_SIZE (elt_mode));
11628               rvec[k++] = gen_rtx_EXPR_LIST (VOIDmode, r, off);
11629             }
11630
11631           /* If there were not enough FPRs to hold the argument, the rest
11632              usually goes into memory.  However, if the current position
11633              is still within the register parameter area, a portion may
11634              actually have to go into GPRs.
11635
11636              Note that it may happen that the portion of the argument
11637              passed in the first "half" of the first GPR was already
11638              passed in the last FPR as well.
11639
11640              For unnamed arguments, we already set up GPRs to cover the
11641              whole argument in rs6000_psave_function_arg, so there is
11642              nothing further to do at this point.  */
11643           fpr_words = (i * GET_MODE_SIZE (elt_mode)) / (TARGET_32BIT ? 4 : 8);
11644           if (i < n_elts && align_words + fpr_words < GP_ARG_NUM_REG
11645               && cum->nargs_prototype > 0)
11646             {
11647               static bool warned;
11648
11649               machine_mode rmode = TARGET_32BIT ? SImode : DImode;
11650               int n_words = rs6000_arg_size (mode, type);
11651
11652               align_words += fpr_words;
11653               n_words -= fpr_words;
11654
11655               do
11656                 {
11657                   r = gen_rtx_REG (rmode, GP_ARG_MIN_REG + align_words);
11658                   off = GEN_INT (fpr_words++ * GET_MODE_SIZE (rmode));
11659                   rvec[k++] = gen_rtx_EXPR_LIST (VOIDmode, r, off);
11660                 }
11661               while (++align_words < GP_ARG_NUM_REG && --n_words != 0);
11662
11663               if (!warned && warn_psabi)
11664                 {
11665                   warned = true;
11666                   inform (input_location,
11667                           "the ABI of passing homogeneous %<float%> aggregates"
11668                           " has changed in GCC 5");
11669                 }
11670             }
11671
11672           return rs6000_finish_function_arg (mode, rvec, k);
11673         }
11674       else if (align_words < GP_ARG_NUM_REG)
11675         {
11676           if (TARGET_32BIT && TARGET_POWERPC64)
11677             return rs6000_mixed_function_arg (mode, type, align_words);
11678
11679           return gen_rtx_REG (mode, GP_ARG_MIN_REG + align_words);
11680         }
11681       else
11682         return NULL_RTX;
11683     }
11684 }
11685 \f
11686 /* For an arg passed partly in registers and partly in memory, this is
11687    the number of bytes passed in registers.  For args passed entirely in
11688    registers or entirely in memory, zero.  When an arg is described by a
11689    PARALLEL, perhaps using more than one register type, this function
11690    returns the number of bytes used by the first element of the PARALLEL.  */
11691
11692 static int
11693 rs6000_arg_partial_bytes (cumulative_args_t cum_v, machine_mode mode,
11694                           tree type, bool named)
11695 {
11696   CUMULATIVE_ARGS *cum = get_cumulative_args (cum_v);
11697   bool passed_in_gprs = true;
11698   int ret = 0;
11699   int align_words;
11700   machine_mode elt_mode;
11701   int n_elts;
11702
11703   rs6000_discover_homogeneous_aggregate (mode, type, &elt_mode, &n_elts);
11704
11705   if (DEFAULT_ABI == ABI_V4)
11706     return 0;
11707
11708   if (USE_ALTIVEC_FOR_ARG_P (cum, elt_mode, named))
11709     {
11710       /* If we are passing this arg in the fixed parameter save area (gprs or
11711          memory) as well as VRs, we do not use the partial bytes mechanism;
11712          instead, rs6000_function_arg will return a PARALLEL including a memory
11713          element as necessary.  Library support functions for IEEE 128-bit are
11714          assumed to not need the value passed both in GPRs and in vector
11715          registers.  */
11716       if (TARGET_64BIT && !cum->prototype
11717           && (!cum->libcall || !FLOAT128_VECTOR_P (elt_mode)))
11718         return 0;
11719
11720       /* Otherwise, we pass in VRs only.  Check for partial copies.  */
11721       passed_in_gprs = false;
11722       if (cum->vregno + n_elts > ALTIVEC_ARG_MAX_REG + 1)
11723         ret = (ALTIVEC_ARG_MAX_REG + 1 - cum->vregno) * 16;
11724     }
11725
11726   /* In this complicated case we just disable the partial_nregs code.  */
11727   if (TARGET_MACHO && rs6000_darwin64_struct_check_p (mode, type))
11728     return 0;
11729
11730   align_words = rs6000_parm_start (mode, type, cum->words);
11731
11732   if (USE_FP_FOR_ARG_P (cum, elt_mode)
11733       && !(TARGET_AIX && !TARGET_ELF
11734            && type != NULL && AGGREGATE_TYPE_P (type)))
11735     {
11736       unsigned long n_fpreg = (GET_MODE_SIZE (elt_mode) + 7) >> 3;
11737
11738       /* If we are passing this arg in the fixed parameter save area
11739          (gprs or memory) as well as FPRs, we do not use the partial
11740          bytes mechanism; instead, rs6000_function_arg will return a
11741          PARALLEL including a memory element as necessary.  */
11742       if (type
11743           && (cum->nargs_prototype <= 0
11744               || ((DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
11745                   && TARGET_XL_COMPAT
11746                   && align_words >= GP_ARG_NUM_REG)))
11747         return 0;
11748
11749       /* Otherwise, we pass in FPRs only.  Check for partial copies.  */
11750       passed_in_gprs = false;
11751       if (cum->fregno + n_elts * n_fpreg > FP_ARG_MAX_REG + 1)
11752         {
11753           /* Compute number of bytes / words passed in FPRs.  If there
11754              is still space available in the register parameter area
11755              *after* that amount, a part of the argument will be passed
11756              in GPRs.  In that case, the total amount passed in any
11757              registers is equal to the amount that would have been passed
11758              in GPRs if everything were passed there, so we fall back to
11759              the GPR code below to compute the appropriate value.  */
11760           int fpr = ((FP_ARG_MAX_REG + 1 - cum->fregno)
11761                      * MIN (8, GET_MODE_SIZE (elt_mode)));
11762           int fpr_words = fpr / (TARGET_32BIT ? 4 : 8);
11763
11764           if (align_words + fpr_words < GP_ARG_NUM_REG)
11765             passed_in_gprs = true;
11766           else
11767             ret = fpr;
11768         }
11769     }
11770
11771   if (passed_in_gprs
11772       && align_words < GP_ARG_NUM_REG
11773       && GP_ARG_NUM_REG < align_words + rs6000_arg_size (mode, type))
11774     ret = (GP_ARG_NUM_REG - align_words) * (TARGET_32BIT ? 4 : 8);
11775
11776   if (ret != 0 && TARGET_DEBUG_ARG)
11777     fprintf (stderr, "rs6000_arg_partial_bytes: %d\n", ret);
11778
11779   return ret;
11780 }
11781 \f
11782 /* A C expression that indicates when an argument must be passed by
11783    reference.  If nonzero for an argument, a copy of that argument is
11784    made in memory and a pointer to the argument is passed instead of
11785    the argument itself.  The pointer is passed in whatever way is
11786    appropriate for passing a pointer to that type.
11787
11788    Under V.4, aggregates and long double are passed by reference.
11789
11790    As an extension to all 32-bit ABIs, AltiVec vectors are passed by
11791    reference unless the AltiVec vector extension ABI is in force.
11792
11793    As an extension to all ABIs, variable sized types are passed by
11794    reference.  */
11795
11796 static bool
11797 rs6000_pass_by_reference (cumulative_args_t cum ATTRIBUTE_UNUSED,
11798                           machine_mode mode, const_tree type,
11799                           bool named ATTRIBUTE_UNUSED)
11800 {
11801   if (!type)
11802     return 0;
11803
11804   if (DEFAULT_ABI == ABI_V4 && TARGET_IEEEQUAD
11805       && FLOAT128_IEEE_P (TYPE_MODE (type)))
11806     {
11807       if (TARGET_DEBUG_ARG)
11808         fprintf (stderr, "function_arg_pass_by_reference: V4 IEEE 128-bit\n");
11809       return 1;
11810     }
11811
11812   if (DEFAULT_ABI == ABI_V4 && AGGREGATE_TYPE_P (type))
11813     {
11814       if (TARGET_DEBUG_ARG)
11815         fprintf (stderr, "function_arg_pass_by_reference: V4 aggregate\n");
11816       return 1;
11817     }
11818
11819   if (int_size_in_bytes (type) < 0)
11820     {
11821       if (TARGET_DEBUG_ARG)
11822         fprintf (stderr, "function_arg_pass_by_reference: variable size\n");
11823       return 1;
11824     }
11825
11826   /* Allow -maltivec -mabi=no-altivec without warning.  Altivec vector
11827      modes only exist for GCC vector types if -maltivec.  */
11828   if (TARGET_32BIT && !TARGET_ALTIVEC_ABI && ALTIVEC_VECTOR_MODE (mode))
11829     {
11830       if (TARGET_DEBUG_ARG)
11831         fprintf (stderr, "function_arg_pass_by_reference: AltiVec\n");
11832       return 1;
11833     }
11834
11835   /* Pass synthetic vectors in memory.  */
11836   if (TREE_CODE (type) == VECTOR_TYPE
11837       && int_size_in_bytes (type) > (TARGET_ALTIVEC_ABI ? 16 : 8))
11838     {
11839       static bool warned_for_pass_big_vectors = false;
11840       if (TARGET_DEBUG_ARG)
11841         fprintf (stderr, "function_arg_pass_by_reference: synthetic vector\n");
11842       if (!warned_for_pass_big_vectors)
11843         {
11844           warning (OPT_Wpsabi, "GCC vector passed by reference: "
11845                    "non-standard ABI extension with no compatibility "
11846                    "guarantee");
11847           warned_for_pass_big_vectors = true;
11848         }
11849       return 1;
11850     }
11851
11852   return 0;
11853 }
11854
11855 /* Process parameter of type TYPE after ARGS_SO_FAR parameters were
11856    already processes.  Return true if the parameter must be passed
11857    (fully or partially) on the stack.  */
11858
11859 static bool
11860 rs6000_parm_needs_stack (cumulative_args_t args_so_far, tree type)
11861 {
11862   machine_mode mode;
11863   int unsignedp;
11864   rtx entry_parm;
11865
11866   /* Catch errors.  */
11867   if (type == NULL || type == error_mark_node)
11868     return true;
11869
11870   /* Handle types with no storage requirement.  */
11871   if (TYPE_MODE (type) == VOIDmode)
11872     return false;
11873
11874   /* Handle complex types.  */
11875   if (TREE_CODE (type) == COMPLEX_TYPE)
11876     return (rs6000_parm_needs_stack (args_so_far, TREE_TYPE (type))
11877             || rs6000_parm_needs_stack (args_so_far, TREE_TYPE (type)));
11878
11879   /* Handle transparent aggregates.  */
11880   if ((TREE_CODE (type) == UNION_TYPE || TREE_CODE (type) == RECORD_TYPE)
11881       && TYPE_TRANSPARENT_AGGR (type))
11882     type = TREE_TYPE (first_field (type));
11883
11884   /* See if this arg was passed by invisible reference.  */
11885   if (pass_by_reference (get_cumulative_args (args_so_far),
11886                          TYPE_MODE (type), type, true))
11887     type = build_pointer_type (type);
11888
11889   /* Find mode as it is passed by the ABI.  */
11890   unsignedp = TYPE_UNSIGNED (type);
11891   mode = promote_mode (type, TYPE_MODE (type), &unsignedp);
11892
11893   /* If we must pass in stack, we need a stack.  */
11894   if (rs6000_must_pass_in_stack (mode, type))
11895     return true;
11896
11897   /* If there is no incoming register, we need a stack.  */
11898   entry_parm = rs6000_function_arg (args_so_far, mode, type, true);
11899   if (entry_parm == NULL)
11900     return true;
11901
11902   /* Likewise if we need to pass both in registers and on the stack.  */
11903   if (GET_CODE (entry_parm) == PARALLEL
11904       && XEXP (XVECEXP (entry_parm, 0, 0), 0) == NULL_RTX)
11905     return true;
11906
11907   /* Also true if we're partially in registers and partially not.  */
11908   if (rs6000_arg_partial_bytes (args_so_far, mode, type, true) != 0)
11909     return true;
11910
11911   /* Update info on where next arg arrives in registers.  */
11912   rs6000_function_arg_advance (args_so_far, mode, type, true);
11913   return false;
11914 }
11915
11916 /* Return true if FUN has no prototype, has a variable argument
11917    list, or passes any parameter in memory.  */
11918
11919 static bool
11920 rs6000_function_parms_need_stack (tree fun, bool incoming)
11921 {
11922   tree fntype, result;
11923   CUMULATIVE_ARGS args_so_far_v;
11924   cumulative_args_t args_so_far;
11925
11926   if (!fun)
11927     /* Must be a libcall, all of which only use reg parms.  */
11928     return false;
11929
11930   fntype = fun;
11931   if (!TYPE_P (fun))
11932     fntype = TREE_TYPE (fun);
11933
11934   /* Varargs functions need the parameter save area.  */
11935   if ((!incoming && !prototype_p (fntype)) || stdarg_p (fntype))
11936     return true;
11937
11938   INIT_CUMULATIVE_INCOMING_ARGS (args_so_far_v, fntype, NULL_RTX);
11939   args_so_far = pack_cumulative_args (&args_so_far_v);
11940
11941   /* When incoming, we will have been passed the function decl.
11942      It is necessary to use the decl to handle K&R style functions,
11943      where TYPE_ARG_TYPES may not be available.  */
11944   if (incoming)
11945     {
11946       gcc_assert (DECL_P (fun));
11947       result = DECL_RESULT (fun);
11948     }
11949   else
11950     result = TREE_TYPE (fntype);
11951
11952   if (result && aggregate_value_p (result, fntype))
11953     {
11954       if (!TYPE_P (result))
11955         result = TREE_TYPE (result);
11956       result = build_pointer_type (result);
11957       rs6000_parm_needs_stack (args_so_far, result);
11958     }
11959
11960   if (incoming)
11961     {
11962       tree parm;
11963
11964       for (parm = DECL_ARGUMENTS (fun);
11965            parm && parm != void_list_node;
11966            parm = TREE_CHAIN (parm))
11967         if (rs6000_parm_needs_stack (args_so_far, TREE_TYPE (parm)))
11968           return true;
11969     }
11970   else
11971     {
11972       function_args_iterator args_iter;
11973       tree arg_type;
11974
11975       FOREACH_FUNCTION_ARGS (fntype, arg_type, args_iter)
11976         if (rs6000_parm_needs_stack (args_so_far, arg_type))
11977           return true;
11978     }
11979
11980   return false;
11981 }
11982
11983 /* Return the size of the REG_PARM_STACK_SPACE are for FUN.  This is
11984    usually a constant depending on the ABI.  However, in the ELFv2 ABI
11985    the register parameter area is optional when calling a function that
11986    has a prototype is scope, has no variable argument list, and passes
11987    all parameters in registers.  */
11988
11989 int
11990 rs6000_reg_parm_stack_space (tree fun, bool incoming)
11991 {
11992   int reg_parm_stack_space;
11993
11994   switch (DEFAULT_ABI)
11995     {
11996     default:
11997       reg_parm_stack_space = 0;
11998       break;
11999
12000     case ABI_AIX:
12001     case ABI_DARWIN:
12002       reg_parm_stack_space = TARGET_64BIT ? 64 : 32;
12003       break;
12004
12005     case ABI_ELFv2:
12006       /* ??? Recomputing this every time is a bit expensive.  Is there
12007          a place to cache this information?  */
12008       if (rs6000_function_parms_need_stack (fun, incoming))
12009         reg_parm_stack_space = TARGET_64BIT ? 64 : 32;
12010       else
12011         reg_parm_stack_space = 0;
12012       break;
12013     }
12014
12015   return reg_parm_stack_space;
12016 }
12017
12018 static void
12019 rs6000_move_block_from_reg (int regno, rtx x, int nregs)
12020 {
12021   int i;
12022   machine_mode reg_mode = TARGET_32BIT ? SImode : DImode;
12023
12024   if (nregs == 0)
12025     return;
12026
12027   for (i = 0; i < nregs; i++)
12028     {
12029       rtx tem = adjust_address_nv (x, reg_mode, i * GET_MODE_SIZE (reg_mode));
12030       if (reload_completed)
12031         {
12032           if (! strict_memory_address_p (reg_mode, XEXP (tem, 0)))
12033             tem = NULL_RTX;
12034           else
12035             tem = simplify_gen_subreg (reg_mode, x, BLKmode,
12036                                        i * GET_MODE_SIZE (reg_mode));
12037         }
12038       else
12039         tem = replace_equiv_address (tem, XEXP (tem, 0));
12040
12041       gcc_assert (tem);
12042
12043       emit_move_insn (tem, gen_rtx_REG (reg_mode, regno + i));
12044     }
12045 }
12046 \f
12047 /* Perform any needed actions needed for a function that is receiving a
12048    variable number of arguments.
12049
12050    CUM is as above.
12051
12052    MODE and TYPE are the mode and type of the current parameter.
12053
12054    PRETEND_SIZE is a variable that should be set to the amount of stack
12055    that must be pushed by the prolog to pretend that our caller pushed
12056    it.
12057
12058    Normally, this macro will push all remaining incoming registers on the
12059    stack and set PRETEND_SIZE to the length of the registers pushed.  */
12060
12061 static void
12062 setup_incoming_varargs (cumulative_args_t cum, machine_mode mode,
12063                         tree type, int *pretend_size ATTRIBUTE_UNUSED,
12064                         int no_rtl)
12065 {
12066   CUMULATIVE_ARGS next_cum;
12067   int reg_size = TARGET_32BIT ? 4 : 8;
12068   rtx save_area = NULL_RTX, mem;
12069   int first_reg_offset;
12070   alias_set_type set;
12071
12072   /* Skip the last named argument.  */
12073   next_cum = *get_cumulative_args (cum);
12074   rs6000_function_arg_advance_1 (&next_cum, mode, type, true, 0);
12075
12076   if (DEFAULT_ABI == ABI_V4)
12077     {
12078       first_reg_offset = next_cum.sysv_gregno - GP_ARG_MIN_REG;
12079
12080       if (! no_rtl)
12081         {
12082           int gpr_reg_num = 0, gpr_size = 0, fpr_size = 0;
12083           HOST_WIDE_INT offset = 0;
12084
12085           /* Try to optimize the size of the varargs save area.
12086              The ABI requires that ap.reg_save_area is doubleword
12087              aligned, but we don't need to allocate space for all
12088              the bytes, only those to which we actually will save
12089              anything.  */
12090           if (cfun->va_list_gpr_size && first_reg_offset < GP_ARG_NUM_REG)
12091             gpr_reg_num = GP_ARG_NUM_REG - first_reg_offset;
12092           if (TARGET_HARD_FLOAT
12093               && next_cum.fregno <= FP_ARG_V4_MAX_REG
12094               && cfun->va_list_fpr_size)
12095             {
12096               if (gpr_reg_num)
12097                 fpr_size = (next_cum.fregno - FP_ARG_MIN_REG)
12098                            * UNITS_PER_FP_WORD;
12099               if (cfun->va_list_fpr_size
12100                   < FP_ARG_V4_MAX_REG + 1 - next_cum.fregno)
12101                 fpr_size += cfun->va_list_fpr_size * UNITS_PER_FP_WORD;
12102               else
12103                 fpr_size += (FP_ARG_V4_MAX_REG + 1 - next_cum.fregno)
12104                             * UNITS_PER_FP_WORD;
12105             }
12106           if (gpr_reg_num)
12107             {
12108               offset = -((first_reg_offset * reg_size) & ~7);
12109               if (!fpr_size && gpr_reg_num > cfun->va_list_gpr_size)
12110                 {
12111                   gpr_reg_num = cfun->va_list_gpr_size;
12112                   if (reg_size == 4 && (first_reg_offset & 1))
12113                     gpr_reg_num++;
12114                 }
12115               gpr_size = (gpr_reg_num * reg_size + 7) & ~7;
12116             }
12117           else if (fpr_size)
12118             offset = - (int) (next_cum.fregno - FP_ARG_MIN_REG)
12119                        * UNITS_PER_FP_WORD
12120                      - (int) (GP_ARG_NUM_REG * reg_size);
12121
12122           if (gpr_size + fpr_size)
12123             {
12124               rtx reg_save_area
12125                 = assign_stack_local (BLKmode, gpr_size + fpr_size, 64);
12126               gcc_assert (MEM_P (reg_save_area));
12127               reg_save_area = XEXP (reg_save_area, 0);
12128               if (GET_CODE (reg_save_area) == PLUS)
12129                 {
12130                   gcc_assert (XEXP (reg_save_area, 0)
12131                               == virtual_stack_vars_rtx);
12132                   gcc_assert (CONST_INT_P (XEXP (reg_save_area, 1)));
12133                   offset += INTVAL (XEXP (reg_save_area, 1));
12134                 }
12135               else
12136                 gcc_assert (reg_save_area == virtual_stack_vars_rtx);
12137             }
12138
12139           cfun->machine->varargs_save_offset = offset;
12140           save_area = plus_constant (Pmode, virtual_stack_vars_rtx, offset);
12141         }
12142     }
12143   else
12144     {
12145       first_reg_offset = next_cum.words;
12146       save_area = crtl->args.internal_arg_pointer;
12147
12148       if (targetm.calls.must_pass_in_stack (mode, type))
12149         first_reg_offset += rs6000_arg_size (TYPE_MODE (type), type);
12150     }
12151
12152   set = get_varargs_alias_set ();
12153   if (! no_rtl && first_reg_offset < GP_ARG_NUM_REG
12154       && cfun->va_list_gpr_size)
12155     {
12156       int n_gpr, nregs = GP_ARG_NUM_REG - first_reg_offset;
12157
12158       if (va_list_gpr_counter_field)
12159         /* V4 va_list_gpr_size counts number of registers needed.  */
12160         n_gpr = cfun->va_list_gpr_size;
12161       else
12162         /* char * va_list instead counts number of bytes needed.  */
12163         n_gpr = (cfun->va_list_gpr_size + reg_size - 1) / reg_size;
12164
12165       if (nregs > n_gpr)
12166         nregs = n_gpr;
12167
12168       mem = gen_rtx_MEM (BLKmode,
12169                          plus_constant (Pmode, save_area,
12170                                         first_reg_offset * reg_size));
12171       MEM_NOTRAP_P (mem) = 1;
12172       set_mem_alias_set (mem, set);
12173       set_mem_align (mem, BITS_PER_WORD);
12174
12175       rs6000_move_block_from_reg (GP_ARG_MIN_REG + first_reg_offset, mem,
12176                                   nregs);
12177     }
12178
12179   /* Save FP registers if needed.  */
12180   if (DEFAULT_ABI == ABI_V4
12181       && TARGET_HARD_FLOAT
12182       && ! no_rtl
12183       && next_cum.fregno <= FP_ARG_V4_MAX_REG
12184       && cfun->va_list_fpr_size)
12185     {
12186       int fregno = next_cum.fregno, nregs;
12187       rtx cr1 = gen_rtx_REG (CCmode, CR1_REGNO);
12188       rtx lab = gen_label_rtx ();
12189       int off = (GP_ARG_NUM_REG * reg_size) + ((fregno - FP_ARG_MIN_REG)
12190                                                * UNITS_PER_FP_WORD);
12191
12192       emit_jump_insn
12193         (gen_rtx_SET (pc_rtx,
12194                       gen_rtx_IF_THEN_ELSE (VOIDmode,
12195                                             gen_rtx_NE (VOIDmode, cr1,
12196                                                         const0_rtx),
12197                                             gen_rtx_LABEL_REF (VOIDmode, lab),
12198                                             pc_rtx)));
12199
12200       for (nregs = 0;
12201            fregno <= FP_ARG_V4_MAX_REG && nregs < cfun->va_list_fpr_size;
12202            fregno++, off += UNITS_PER_FP_WORD, nregs++)
12203         {
12204           mem = gen_rtx_MEM (TARGET_HARD_FLOAT ? DFmode : SFmode,
12205                              plus_constant (Pmode, save_area, off));
12206           MEM_NOTRAP_P (mem) = 1;
12207           set_mem_alias_set (mem, set);
12208           set_mem_align (mem, GET_MODE_ALIGNMENT (
12209                          TARGET_HARD_FLOAT ? DFmode : SFmode));
12210           emit_move_insn (mem, gen_rtx_REG (
12211                           TARGET_HARD_FLOAT ? DFmode : SFmode, fregno));
12212         }
12213
12214       emit_label (lab);
12215     }
12216 }
12217
12218 /* Create the va_list data type.  */
12219
12220 static tree
12221 rs6000_build_builtin_va_list (void)
12222 {
12223   tree f_gpr, f_fpr, f_res, f_ovf, f_sav, record, type_decl;
12224
12225   /* For AIX, prefer 'char *' because that's what the system
12226      header files like.  */
12227   if (DEFAULT_ABI != ABI_V4)
12228     return build_pointer_type (char_type_node);
12229
12230   record = (*lang_hooks.types.make_type) (RECORD_TYPE);
12231   type_decl = build_decl (BUILTINS_LOCATION, TYPE_DECL,
12232                           get_identifier ("__va_list_tag"), record);
12233
12234   f_gpr = build_decl (BUILTINS_LOCATION, FIELD_DECL, get_identifier ("gpr"),
12235                       unsigned_char_type_node);
12236   f_fpr = build_decl (BUILTINS_LOCATION, FIELD_DECL, get_identifier ("fpr"),
12237                       unsigned_char_type_node);
12238   /* Give the two bytes of padding a name, so that -Wpadded won't warn on
12239      every user file.  */
12240   f_res = build_decl (BUILTINS_LOCATION, FIELD_DECL,
12241                       get_identifier ("reserved"), short_unsigned_type_node);
12242   f_ovf = build_decl (BUILTINS_LOCATION, FIELD_DECL,
12243                       get_identifier ("overflow_arg_area"),
12244                       ptr_type_node);
12245   f_sav = build_decl (BUILTINS_LOCATION, FIELD_DECL,
12246                       get_identifier ("reg_save_area"),
12247                       ptr_type_node);
12248
12249   va_list_gpr_counter_field = f_gpr;
12250   va_list_fpr_counter_field = f_fpr;
12251
12252   DECL_FIELD_CONTEXT (f_gpr) = record;
12253   DECL_FIELD_CONTEXT (f_fpr) = record;
12254   DECL_FIELD_CONTEXT (f_res) = record;
12255   DECL_FIELD_CONTEXT (f_ovf) = record;
12256   DECL_FIELD_CONTEXT (f_sav) = record;
12257
12258   TYPE_STUB_DECL (record) = type_decl;
12259   TYPE_NAME (record) = type_decl;
12260   TYPE_FIELDS (record) = f_gpr;
12261   DECL_CHAIN (f_gpr) = f_fpr;
12262   DECL_CHAIN (f_fpr) = f_res;
12263   DECL_CHAIN (f_res) = f_ovf;
12264   DECL_CHAIN (f_ovf) = f_sav;
12265
12266   layout_type (record);
12267
12268   /* The correct type is an array type of one element.  */
12269   return build_array_type (record, build_index_type (size_zero_node));
12270 }
12271
12272 /* Implement va_start.  */
12273
12274 static void
12275 rs6000_va_start (tree valist, rtx nextarg)
12276 {
12277   HOST_WIDE_INT words, n_gpr, n_fpr;
12278   tree f_gpr, f_fpr, f_res, f_ovf, f_sav;
12279   tree gpr, fpr, ovf, sav, t;
12280
12281   /* Only SVR4 needs something special.  */
12282   if (DEFAULT_ABI != ABI_V4)
12283     {
12284       std_expand_builtin_va_start (valist, nextarg);
12285       return;
12286     }
12287
12288   f_gpr = TYPE_FIELDS (TREE_TYPE (va_list_type_node));
12289   f_fpr = DECL_CHAIN (f_gpr);
12290   f_res = DECL_CHAIN (f_fpr);
12291   f_ovf = DECL_CHAIN (f_res);
12292   f_sav = DECL_CHAIN (f_ovf);
12293
12294   valist = build_simple_mem_ref (valist);
12295   gpr = build3 (COMPONENT_REF, TREE_TYPE (f_gpr), valist, f_gpr, NULL_TREE);
12296   fpr = build3 (COMPONENT_REF, TREE_TYPE (f_fpr), unshare_expr (valist),
12297                 f_fpr, NULL_TREE);
12298   ovf = build3 (COMPONENT_REF, TREE_TYPE (f_ovf), unshare_expr (valist),
12299                 f_ovf, NULL_TREE);
12300   sav = build3 (COMPONENT_REF, TREE_TYPE (f_sav), unshare_expr (valist),
12301                 f_sav, NULL_TREE);
12302
12303   /* Count number of gp and fp argument registers used.  */
12304   words = crtl->args.info.words;
12305   n_gpr = MIN (crtl->args.info.sysv_gregno - GP_ARG_MIN_REG,
12306                GP_ARG_NUM_REG);
12307   n_fpr = MIN (crtl->args.info.fregno - FP_ARG_MIN_REG,
12308                FP_ARG_NUM_REG);
12309
12310   if (TARGET_DEBUG_ARG)
12311     fprintf (stderr, "va_start: words = " HOST_WIDE_INT_PRINT_DEC", n_gpr = "
12312              HOST_WIDE_INT_PRINT_DEC", n_fpr = " HOST_WIDE_INT_PRINT_DEC"\n",
12313              words, n_gpr, n_fpr);
12314
12315   if (cfun->va_list_gpr_size)
12316     {
12317       t = build2 (MODIFY_EXPR, TREE_TYPE (gpr), gpr,
12318                   build_int_cst (NULL_TREE, n_gpr));
12319       TREE_SIDE_EFFECTS (t) = 1;
12320       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
12321     }
12322
12323   if (cfun->va_list_fpr_size)
12324     {
12325       t = build2 (MODIFY_EXPR, TREE_TYPE (fpr), fpr,
12326                   build_int_cst (NULL_TREE, n_fpr));
12327       TREE_SIDE_EFFECTS (t) = 1;
12328       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
12329
12330 #ifdef HAVE_AS_GNU_ATTRIBUTE
12331       if (call_ABI_of_interest (cfun->decl))
12332         rs6000_passes_float = true;
12333 #endif
12334     }
12335
12336   /* Find the overflow area.  */
12337   t = make_tree (TREE_TYPE (ovf), crtl->args.internal_arg_pointer);
12338   if (words != 0)
12339     t = fold_build_pointer_plus_hwi (t, words * MIN_UNITS_PER_WORD);
12340   t = build2 (MODIFY_EXPR, TREE_TYPE (ovf), ovf, t);
12341   TREE_SIDE_EFFECTS (t) = 1;
12342   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
12343
12344   /* If there were no va_arg invocations, don't set up the register
12345      save area.  */
12346   if (!cfun->va_list_gpr_size
12347       && !cfun->va_list_fpr_size
12348       && n_gpr < GP_ARG_NUM_REG
12349       && n_fpr < FP_ARG_V4_MAX_REG)
12350     return;
12351
12352   /* Find the register save area.  */
12353   t = make_tree (TREE_TYPE (sav), virtual_stack_vars_rtx);
12354   if (cfun->machine->varargs_save_offset)
12355     t = fold_build_pointer_plus_hwi (t, cfun->machine->varargs_save_offset);
12356   t = build2 (MODIFY_EXPR, TREE_TYPE (sav), sav, t);
12357   TREE_SIDE_EFFECTS (t) = 1;
12358   expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
12359 }
12360
12361 /* Implement va_arg.  */
12362
12363 static tree
12364 rs6000_gimplify_va_arg (tree valist, tree type, gimple_seq *pre_p,
12365                         gimple_seq *post_p)
12366 {
12367   tree f_gpr, f_fpr, f_res, f_ovf, f_sav;
12368   tree gpr, fpr, ovf, sav, reg, t, u;
12369   int size, rsize, n_reg, sav_ofs, sav_scale;
12370   tree lab_false, lab_over, addr;
12371   int align;
12372   tree ptrtype = build_pointer_type_for_mode (type, ptr_mode, true);
12373   int regalign = 0;
12374   gimple *stmt;
12375
12376   if (pass_by_reference (NULL, TYPE_MODE (type), type, false))
12377     {
12378       t = rs6000_gimplify_va_arg (valist, ptrtype, pre_p, post_p);
12379       return build_va_arg_indirect_ref (t);
12380     }
12381
12382   /* We need to deal with the fact that the darwin ppc64 ABI is defined by an
12383      earlier version of gcc, with the property that it always applied alignment
12384      adjustments to the va-args (even for zero-sized types).  The cheapest way
12385      to deal with this is to replicate the effect of the part of 
12386      std_gimplify_va_arg_expr that carries out the align adjust, for the case 
12387      of relevance.  
12388      We don't need to check for pass-by-reference because of the test above.
12389      We can return a simplifed answer, since we know there's no offset to add.  */
12390
12391   if (((TARGET_MACHO
12392         && rs6000_darwin64_abi)
12393        || DEFAULT_ABI == ABI_ELFv2
12394        || (DEFAULT_ABI == ABI_AIX && !rs6000_compat_align_parm))
12395       && integer_zerop (TYPE_SIZE (type)))
12396     {
12397       unsigned HOST_WIDE_INT align, boundary;
12398       tree valist_tmp = get_initialized_tmp_var (valist, pre_p, NULL);
12399       align = PARM_BOUNDARY / BITS_PER_UNIT;
12400       boundary = rs6000_function_arg_boundary (TYPE_MODE (type), type);
12401       if (boundary > MAX_SUPPORTED_STACK_ALIGNMENT)
12402         boundary = MAX_SUPPORTED_STACK_ALIGNMENT;
12403       boundary /= BITS_PER_UNIT;
12404       if (boundary > align)
12405         {
12406           tree t ;
12407           /* This updates arg ptr by the amount that would be necessary
12408              to align the zero-sized (but not zero-alignment) item.  */
12409           t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
12410                       fold_build_pointer_plus_hwi (valist_tmp, boundary - 1));
12411           gimplify_and_add (t, pre_p);
12412
12413           t = fold_convert (sizetype, valist_tmp);
12414           t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
12415                   fold_convert (TREE_TYPE (valist),
12416                                 fold_build2 (BIT_AND_EXPR, sizetype, t,
12417                                              size_int (-boundary))));
12418           t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist, t);
12419           gimplify_and_add (t, pre_p);
12420         }
12421       /* Since it is zero-sized there's no increment for the item itself. */
12422       valist_tmp = fold_convert (build_pointer_type (type), valist_tmp);
12423       return build_va_arg_indirect_ref (valist_tmp);
12424     }
12425
12426   if (DEFAULT_ABI != ABI_V4)
12427     {
12428       if (targetm.calls.split_complex_arg && TREE_CODE (type) == COMPLEX_TYPE)
12429         {
12430           tree elem_type = TREE_TYPE (type);
12431           machine_mode elem_mode = TYPE_MODE (elem_type);
12432           int elem_size = GET_MODE_SIZE (elem_mode);
12433
12434           if (elem_size < UNITS_PER_WORD)
12435             {
12436               tree real_part, imag_part;
12437               gimple_seq post = NULL;
12438
12439               real_part = rs6000_gimplify_va_arg (valist, elem_type, pre_p,
12440                                                   &post);
12441               /* Copy the value into a temporary, lest the formal temporary
12442                  be reused out from under us.  */
12443               real_part = get_initialized_tmp_var (real_part, pre_p, &post);
12444               gimple_seq_add_seq (pre_p, post);
12445
12446               imag_part = rs6000_gimplify_va_arg (valist, elem_type, pre_p,
12447                                                   post_p);
12448
12449               return build2 (COMPLEX_EXPR, type, real_part, imag_part);
12450             }
12451         }
12452
12453       return std_gimplify_va_arg_expr (valist, type, pre_p, post_p);
12454     }
12455
12456   f_gpr = TYPE_FIELDS (TREE_TYPE (va_list_type_node));
12457   f_fpr = DECL_CHAIN (f_gpr);
12458   f_res = DECL_CHAIN (f_fpr);
12459   f_ovf = DECL_CHAIN (f_res);
12460   f_sav = DECL_CHAIN (f_ovf);
12461
12462   gpr = build3 (COMPONENT_REF, TREE_TYPE (f_gpr), valist, f_gpr, NULL_TREE);
12463   fpr = build3 (COMPONENT_REF, TREE_TYPE (f_fpr), unshare_expr (valist),
12464                 f_fpr, NULL_TREE);
12465   ovf = build3 (COMPONENT_REF, TREE_TYPE (f_ovf), unshare_expr (valist),
12466                 f_ovf, NULL_TREE);
12467   sav = build3 (COMPONENT_REF, TREE_TYPE (f_sav), unshare_expr (valist),
12468                 f_sav, NULL_TREE);
12469
12470   size = int_size_in_bytes (type);
12471   rsize = (size + 3) / 4;
12472   int pad = 4 * rsize - size;
12473   align = 1;
12474
12475   machine_mode mode = TYPE_MODE (type);
12476   if (abi_v4_pass_in_fpr (mode, false))
12477     {
12478       /* FP args go in FP registers, if present.  */
12479       reg = fpr;
12480       n_reg = (size + 7) / 8;
12481       sav_ofs = (TARGET_HARD_FLOAT ? 8 : 4) * 4;
12482       sav_scale = (TARGET_HARD_FLOAT ? 8 : 4);
12483       if (mode != SFmode && mode != SDmode)
12484         align = 8;
12485     }
12486   else
12487     {
12488       /* Otherwise into GP registers.  */
12489       reg = gpr;
12490       n_reg = rsize;
12491       sav_ofs = 0;
12492       sav_scale = 4;
12493       if (n_reg == 2)
12494         align = 8;
12495     }
12496
12497   /* Pull the value out of the saved registers....  */
12498
12499   lab_over = NULL;
12500   addr = create_tmp_var (ptr_type_node, "addr");
12501
12502   /*  AltiVec vectors never go in registers when -mabi=altivec.  */
12503   if (TARGET_ALTIVEC_ABI && ALTIVEC_VECTOR_MODE (mode))
12504     align = 16;
12505   else
12506     {
12507       lab_false = create_artificial_label (input_location);
12508       lab_over = create_artificial_label (input_location);
12509
12510       /* Long long is aligned in the registers.  As are any other 2 gpr
12511          item such as complex int due to a historical mistake.  */
12512       u = reg;
12513       if (n_reg == 2 && reg == gpr)
12514         {
12515           regalign = 1;
12516           u = build2 (BIT_AND_EXPR, TREE_TYPE (reg), unshare_expr (reg),
12517                      build_int_cst (TREE_TYPE (reg), n_reg - 1));
12518           u = build2 (POSTINCREMENT_EXPR, TREE_TYPE (reg),
12519                       unshare_expr (reg), u);
12520         }
12521       /* _Decimal128 is passed in even/odd fpr pairs; the stored
12522          reg number is 0 for f1, so we want to make it odd.  */
12523       else if (reg == fpr && mode == TDmode)
12524         {
12525           t = build2 (BIT_IOR_EXPR, TREE_TYPE (reg), unshare_expr (reg),
12526                       build_int_cst (TREE_TYPE (reg), 1));
12527           u = build2 (MODIFY_EXPR, void_type_node, unshare_expr (reg), t);
12528         }
12529
12530       t = fold_convert (TREE_TYPE (reg), size_int (8 - n_reg + 1));
12531       t = build2 (GE_EXPR, boolean_type_node, u, t);
12532       u = build1 (GOTO_EXPR, void_type_node, lab_false);
12533       t = build3 (COND_EXPR, void_type_node, t, u, NULL_TREE);
12534       gimplify_and_add (t, pre_p);
12535
12536       t = sav;
12537       if (sav_ofs)
12538         t = fold_build_pointer_plus_hwi (sav, sav_ofs);
12539
12540       u = build2 (POSTINCREMENT_EXPR, TREE_TYPE (reg), unshare_expr (reg),
12541                   build_int_cst (TREE_TYPE (reg), n_reg));
12542       u = fold_convert (sizetype, u);
12543       u = build2 (MULT_EXPR, sizetype, u, size_int (sav_scale));
12544       t = fold_build_pointer_plus (t, u);
12545
12546       /* _Decimal32 varargs are located in the second word of the 64-bit
12547          FP register for 32-bit binaries.  */
12548       if (TARGET_32BIT && TARGET_HARD_FLOAT && mode == SDmode)
12549         t = fold_build_pointer_plus_hwi (t, size);
12550
12551       /* Args are passed right-aligned.  */
12552       if (BYTES_BIG_ENDIAN)
12553         t = fold_build_pointer_plus_hwi (t, pad);
12554
12555       gimplify_assign (addr, t, pre_p);
12556
12557       gimple_seq_add_stmt (pre_p, gimple_build_goto (lab_over));
12558
12559       stmt = gimple_build_label (lab_false);
12560       gimple_seq_add_stmt (pre_p, stmt);
12561
12562       if ((n_reg == 2 && !regalign) || n_reg > 2)
12563         {
12564           /* Ensure that we don't find any more args in regs.
12565              Alignment has taken care of for special cases.  */
12566           gimplify_assign (reg, build_int_cst (TREE_TYPE (reg), 8), pre_p);
12567         }
12568     }
12569
12570   /* ... otherwise out of the overflow area.  */
12571
12572   /* Care for on-stack alignment if needed.  */
12573   t = ovf;
12574   if (align != 1)
12575     {
12576       t = fold_build_pointer_plus_hwi (t, align - 1);
12577       t = build2 (BIT_AND_EXPR, TREE_TYPE (t), t,
12578                   build_int_cst (TREE_TYPE (t), -align));
12579     }
12580
12581   /* Args are passed right-aligned.  */
12582   if (BYTES_BIG_ENDIAN)
12583     t = fold_build_pointer_plus_hwi (t, pad);
12584
12585   gimplify_expr (&t, pre_p, NULL, is_gimple_val, fb_rvalue);
12586
12587   gimplify_assign (unshare_expr (addr), t, pre_p);
12588
12589   t = fold_build_pointer_plus_hwi (t, size);
12590   gimplify_assign (unshare_expr (ovf), t, pre_p);
12591
12592   if (lab_over)
12593     {
12594       stmt = gimple_build_label (lab_over);
12595       gimple_seq_add_stmt (pre_p, stmt);
12596     }
12597
12598   if (STRICT_ALIGNMENT
12599       && (TYPE_ALIGN (type)
12600           > (unsigned) BITS_PER_UNIT * (align < 4 ? 4 : align)))
12601     {
12602       /* The value (of type complex double, for example) may not be
12603          aligned in memory in the saved registers, so copy via a
12604          temporary.  (This is the same code as used for SPARC.)  */
12605       tree tmp = create_tmp_var (type, "va_arg_tmp");
12606       tree dest_addr = build_fold_addr_expr (tmp);
12607
12608       tree copy = build_call_expr (builtin_decl_implicit (BUILT_IN_MEMCPY),
12609                                    3, dest_addr, addr, size_int (rsize * 4));
12610       TREE_ADDRESSABLE (tmp) = 1;
12611
12612       gimplify_and_add (copy, pre_p);
12613       addr = dest_addr;
12614     }
12615
12616   addr = fold_convert (ptrtype, addr);
12617   return build_va_arg_indirect_ref (addr);
12618 }
12619
12620 /* Builtins.  */
12621
12622 static void
12623 def_builtin (const char *name, tree type, enum rs6000_builtins code)
12624 {
12625   tree t;
12626   unsigned classify = rs6000_builtin_info[(int)code].attr;
12627   const char *attr_string = "";
12628
12629   gcc_assert (name != NULL);
12630   gcc_assert (IN_RANGE ((int)code, 0, (int)RS6000_BUILTIN_COUNT));
12631
12632   if (rs6000_builtin_decls[(int)code])
12633     fatal_error (input_location,
12634                  "internal error: builtin function %qs already processed",
12635                  name);
12636
12637   rs6000_builtin_decls[(int)code] = t =
12638     add_builtin_function (name, type, (int)code, BUILT_IN_MD, NULL, NULL_TREE);
12639
12640   /* Set any special attributes.  */
12641   if ((classify & RS6000_BTC_CONST) != 0)
12642     {
12643       /* const function, function only depends on the inputs.  */
12644       TREE_READONLY (t) = 1;
12645       TREE_NOTHROW (t) = 1;
12646       attr_string = ", const";
12647     }
12648   else if ((classify & RS6000_BTC_PURE) != 0)
12649     {
12650       /* pure function, function can read global memory, but does not set any
12651          external state.  */
12652       DECL_PURE_P (t) = 1;
12653       TREE_NOTHROW (t) = 1;
12654       attr_string = ", pure";
12655     }
12656   else if ((classify & RS6000_BTC_FP) != 0)
12657     {
12658       /* Function is a math function.  If rounding mode is on, then treat the
12659          function as not reading global memory, but it can have arbitrary side
12660          effects.  If it is off, then assume the function is a const function.
12661          This mimics the ATTR_MATHFN_FPROUNDING attribute in
12662          builtin-attribute.def that is used for the math functions. */
12663       TREE_NOTHROW (t) = 1;
12664       if (flag_rounding_math)
12665         {
12666           DECL_PURE_P (t) = 1;
12667           DECL_IS_NOVOPS (t) = 1;
12668           attr_string = ", fp, pure";
12669         }
12670       else
12671         {
12672           TREE_READONLY (t) = 1;
12673           attr_string = ", fp, const";
12674         }
12675     }
12676   else if ((classify & RS6000_BTC_ATTR_MASK) != 0)
12677     gcc_unreachable ();
12678
12679   if (TARGET_DEBUG_BUILTIN)
12680     fprintf (stderr, "rs6000_builtin, code = %4d, %s%s\n",
12681              (int)code, name, attr_string);
12682 }
12683
12684 /* Simple ternary operations: VECd = foo (VECa, VECb, VECc).  */
12685
12686 #undef RS6000_BUILTIN_0
12687 #undef RS6000_BUILTIN_1
12688 #undef RS6000_BUILTIN_2
12689 #undef RS6000_BUILTIN_3
12690 #undef RS6000_BUILTIN_A
12691 #undef RS6000_BUILTIN_D
12692 #undef RS6000_BUILTIN_H
12693 #undef RS6000_BUILTIN_P
12694 #undef RS6000_BUILTIN_X
12695
12696 #define RS6000_BUILTIN_0(ENUM, NAME, MASK, ATTR, ICODE)
12697 #define RS6000_BUILTIN_1(ENUM, NAME, MASK, ATTR, ICODE)
12698 #define RS6000_BUILTIN_2(ENUM, NAME, MASK, ATTR, ICODE)
12699 #define RS6000_BUILTIN_3(ENUM, NAME, MASK, ATTR, ICODE) \
12700   { MASK, ICODE, NAME, ENUM },
12701
12702 #define RS6000_BUILTIN_A(ENUM, NAME, MASK, ATTR, ICODE)
12703 #define RS6000_BUILTIN_D(ENUM, NAME, MASK, ATTR, ICODE)
12704 #define RS6000_BUILTIN_H(ENUM, NAME, MASK, ATTR, ICODE)
12705 #define RS6000_BUILTIN_P(ENUM, NAME, MASK, ATTR, ICODE)
12706 #define RS6000_BUILTIN_X(ENUM, NAME, MASK, ATTR, ICODE)
12707
12708 static const struct builtin_description bdesc_3arg[] =
12709 {
12710 #include "rs6000-builtin.def"
12711 };
12712
12713 /* DST operations: void foo (void *, const int, const char).  */
12714
12715 #undef RS6000_BUILTIN_0
12716 #undef RS6000_BUILTIN_1
12717 #undef RS6000_BUILTIN_2
12718 #undef RS6000_BUILTIN_3
12719 #undef RS6000_BUILTIN_A
12720 #undef RS6000_BUILTIN_D
12721 #undef RS6000_BUILTIN_H
12722 #undef RS6000_BUILTIN_P
12723 #undef RS6000_BUILTIN_X
12724
12725 #define RS6000_BUILTIN_0(ENUM, NAME, MASK, ATTR, ICODE)
12726 #define RS6000_BUILTIN_1(ENUM, NAME, MASK, ATTR, ICODE)
12727 #define RS6000_BUILTIN_2(ENUM, NAME, MASK, ATTR, ICODE)
12728 #define RS6000_BUILTIN_3(ENUM, NAME, MASK, ATTR, ICODE)
12729 #define RS6000_BUILTIN_A(ENUM, NAME, MASK, ATTR, ICODE)
12730 #define RS6000_BUILTIN_D(ENUM, NAME, MASK, ATTR, ICODE) \
12731   { MASK, ICODE, NAME, ENUM },
12732
12733 #define RS6000_BUILTIN_H(ENUM, NAME, MASK, ATTR, ICODE)
12734 #define RS6000_BUILTIN_P(ENUM, NAME, MASK, ATTR, ICODE)
12735 #define RS6000_BUILTIN_X(ENUM, NAME, MASK, ATTR, ICODE)
12736
12737 static const struct builtin_description bdesc_dst[] =
12738 {
12739 #include "rs6000-builtin.def"
12740 };
12741
12742 /* Simple binary operations: VECc = foo (VECa, VECb).  */
12743
12744 #undef RS6000_BUILTIN_0
12745 #undef RS6000_BUILTIN_1
12746 #undef RS6000_BUILTIN_2
12747 #undef RS6000_BUILTIN_3
12748 #undef RS6000_BUILTIN_A
12749 #undef RS6000_BUILTIN_D
12750 #undef RS6000_BUILTIN_H
12751 #undef RS6000_BUILTIN_P
12752 #undef RS6000_BUILTIN_X
12753
12754 #define RS6000_BUILTIN_0(ENUM, NAME, MASK, ATTR, ICODE)
12755 #define RS6000_BUILTIN_1(ENUM, NAME, MASK, ATTR, ICODE)
12756 #define RS6000_BUILTIN_2(ENUM, NAME, MASK, ATTR, ICODE) \
12757   { MASK, ICODE, NAME, ENUM },
12758
12759 #define RS6000_BUILTIN_3(ENUM, NAME, MASK, ATTR, ICODE)
12760 #define RS6000_BUILTIN_A(ENUM, NAME, MASK, ATTR, ICODE)
12761 #define RS6000_BUILTIN_D(ENUM, NAME, MASK, ATTR, ICODE)
12762 #define RS6000_BUILTIN_H(ENUM, NAME, MASK, ATTR, ICODE)
12763 #define RS6000_BUILTIN_P(ENUM, NAME, MASK, ATTR, ICODE)
12764 #define RS6000_BUILTIN_X(ENUM, NAME, MASK, ATTR, ICODE)
12765
12766 static const struct builtin_description bdesc_2arg[] =
12767 {
12768 #include "rs6000-builtin.def"
12769 };
12770
12771 #undef RS6000_BUILTIN_0
12772 #undef RS6000_BUILTIN_1
12773 #undef RS6000_BUILTIN_2
12774 #undef RS6000_BUILTIN_3
12775 #undef RS6000_BUILTIN_A
12776 #undef RS6000_BUILTIN_D
12777 #undef RS6000_BUILTIN_H
12778 #undef RS6000_BUILTIN_P
12779 #undef RS6000_BUILTIN_X
12780
12781 #define RS6000_BUILTIN_0(ENUM, NAME, MASK, ATTR, ICODE)
12782 #define RS6000_BUILTIN_1(ENUM, NAME, MASK, ATTR, ICODE)
12783 #define RS6000_BUILTIN_2(ENUM, NAME, MASK, ATTR, ICODE)
12784 #define RS6000_BUILTIN_3(ENUM, NAME, MASK, ATTR, ICODE)
12785 #define RS6000_BUILTIN_A(ENUM, NAME, MASK, ATTR, ICODE)
12786 #define RS6000_BUILTIN_D(ENUM, NAME, MASK, ATTR, ICODE)
12787 #define RS6000_BUILTIN_H(ENUM, NAME, MASK, ATTR, ICODE)
12788 #define RS6000_BUILTIN_P(ENUM, NAME, MASK, ATTR, ICODE) \
12789   { MASK, ICODE, NAME, ENUM },
12790
12791 #define RS6000_BUILTIN_X(ENUM, NAME, MASK, ATTR, ICODE)
12792
12793 /* AltiVec predicates.  */
12794
12795 static const struct builtin_description bdesc_altivec_preds[] =
12796 {
12797 #include "rs6000-builtin.def"
12798 };
12799
12800 /* ABS* operations.  */
12801
12802 #undef RS6000_BUILTIN_0
12803 #undef RS6000_BUILTIN_1
12804 #undef RS6000_BUILTIN_2
12805 #undef RS6000_BUILTIN_3
12806 #undef RS6000_BUILTIN_A
12807 #undef RS6000_BUILTIN_D
12808 #undef RS6000_BUILTIN_H
12809 #undef RS6000_BUILTIN_P
12810 #undef RS6000_BUILTIN_X
12811
12812 #define RS6000_BUILTIN_0(ENUM, NAME, MASK, ATTR, ICODE)
12813 #define RS6000_BUILTIN_1(ENUM, NAME, MASK, ATTR, ICODE)
12814 #define RS6000_BUILTIN_2(ENUM, NAME, MASK, ATTR, ICODE)
12815 #define RS6000_BUILTIN_3(ENUM, NAME, MASK, ATTR, ICODE)
12816 #define RS6000_BUILTIN_A(ENUM, NAME, MASK, ATTR, ICODE) \
12817   { MASK, ICODE, NAME, ENUM },
12818
12819 #define RS6000_BUILTIN_D(ENUM, NAME, MASK, ATTR, ICODE)
12820 #define RS6000_BUILTIN_H(ENUM, NAME, MASK, ATTR, ICODE)
12821 #define RS6000_BUILTIN_P(ENUM, NAME, MASK, ATTR, ICODE)
12822 #define RS6000_BUILTIN_X(ENUM, NAME, MASK, ATTR, ICODE)
12823
12824 static const struct builtin_description bdesc_abs[] =
12825 {
12826 #include "rs6000-builtin.def"
12827 };
12828
12829 /* Simple unary operations: VECb = foo (unsigned literal) or VECb =
12830    foo (VECa).  */
12831
12832 #undef RS6000_BUILTIN_0
12833 #undef RS6000_BUILTIN_1
12834 #undef RS6000_BUILTIN_2
12835 #undef RS6000_BUILTIN_3
12836 #undef RS6000_BUILTIN_A
12837 #undef RS6000_BUILTIN_D
12838 #undef RS6000_BUILTIN_H
12839 #undef RS6000_BUILTIN_P
12840 #undef RS6000_BUILTIN_X
12841
12842 #define RS6000_BUILTIN_0(ENUM, NAME, MASK, ATTR, ICODE)
12843 #define RS6000_BUILTIN_1(ENUM, NAME, MASK, ATTR, ICODE) \
12844   { MASK, ICODE, NAME, ENUM },
12845
12846 #define RS6000_BUILTIN_2(ENUM, NAME, MASK, ATTR, ICODE)
12847 #define RS6000_BUILTIN_3(ENUM, NAME, MASK, ATTR, ICODE)
12848 #define RS6000_BUILTIN_A(ENUM, NAME, MASK, ATTR, ICODE)
12849 #define RS6000_BUILTIN_D(ENUM, NAME, MASK, ATTR, ICODE)
12850 #define RS6000_BUILTIN_H(ENUM, NAME, MASK, ATTR, ICODE)
12851 #define RS6000_BUILTIN_P(ENUM, NAME, MASK, ATTR, ICODE)
12852 #define RS6000_BUILTIN_X(ENUM, NAME, MASK, ATTR, ICODE)
12853
12854 static const struct builtin_description bdesc_1arg[] =
12855 {
12856 #include "rs6000-builtin.def"
12857 };
12858
12859 /* Simple no-argument operations: result = __builtin_darn_32 () */
12860
12861 #undef RS6000_BUILTIN_0
12862 #undef RS6000_BUILTIN_1
12863 #undef RS6000_BUILTIN_2
12864 #undef RS6000_BUILTIN_3
12865 #undef RS6000_BUILTIN_A
12866 #undef RS6000_BUILTIN_D
12867 #undef RS6000_BUILTIN_H
12868 #undef RS6000_BUILTIN_P
12869 #undef RS6000_BUILTIN_X
12870
12871 #define RS6000_BUILTIN_0(ENUM, NAME, MASK, ATTR, ICODE) \
12872   { MASK, ICODE, NAME, ENUM },
12873
12874 #define RS6000_BUILTIN_1(ENUM, NAME, MASK, ATTR, ICODE)
12875 #define RS6000_BUILTIN_2(ENUM, NAME, MASK, ATTR, ICODE)
12876 #define RS6000_BUILTIN_3(ENUM, NAME, MASK, ATTR, ICODE)
12877 #define RS6000_BUILTIN_A(ENUM, NAME, MASK, ATTR, ICODE)
12878 #define RS6000_BUILTIN_D(ENUM, NAME, MASK, ATTR, ICODE)
12879 #define RS6000_BUILTIN_H(ENUM, NAME, MASK, ATTR, ICODE)
12880 #define RS6000_BUILTIN_P(ENUM, NAME, MASK, ATTR, ICODE)
12881 #define RS6000_BUILTIN_X(ENUM, NAME, MASK, ATTR, ICODE)
12882
12883 static const struct builtin_description bdesc_0arg[] =
12884 {
12885 #include "rs6000-builtin.def"
12886 };
12887
12888 /* HTM builtins.  */
12889 #undef RS6000_BUILTIN_0
12890 #undef RS6000_BUILTIN_1
12891 #undef RS6000_BUILTIN_2
12892 #undef RS6000_BUILTIN_3
12893 #undef RS6000_BUILTIN_A
12894 #undef RS6000_BUILTIN_D
12895 #undef RS6000_BUILTIN_H
12896 #undef RS6000_BUILTIN_P
12897 #undef RS6000_BUILTIN_X
12898
12899 #define RS6000_BUILTIN_0(ENUM, NAME, MASK, ATTR, ICODE)
12900 #define RS6000_BUILTIN_1(ENUM, NAME, MASK, ATTR, ICODE)
12901 #define RS6000_BUILTIN_2(ENUM, NAME, MASK, ATTR, ICODE)
12902 #define RS6000_BUILTIN_3(ENUM, NAME, MASK, ATTR, ICODE)
12903 #define RS6000_BUILTIN_A(ENUM, NAME, MASK, ATTR, ICODE)
12904 #define RS6000_BUILTIN_D(ENUM, NAME, MASK, ATTR, ICODE)
12905 #define RS6000_BUILTIN_H(ENUM, NAME, MASK, ATTR, ICODE) \
12906   { MASK, ICODE, NAME, ENUM },
12907
12908 #define RS6000_BUILTIN_P(ENUM, NAME, MASK, ATTR, ICODE)
12909 #define RS6000_BUILTIN_X(ENUM, NAME, MASK, ATTR, ICODE)
12910
12911 static const struct builtin_description bdesc_htm[] =
12912 {
12913 #include "rs6000-builtin.def"
12914 };
12915
12916 #undef RS6000_BUILTIN_0
12917 #undef RS6000_BUILTIN_1
12918 #undef RS6000_BUILTIN_2
12919 #undef RS6000_BUILTIN_3
12920 #undef RS6000_BUILTIN_A
12921 #undef RS6000_BUILTIN_D
12922 #undef RS6000_BUILTIN_H
12923 #undef RS6000_BUILTIN_P
12924
12925 /* Return true if a builtin function is overloaded.  */
12926 bool
12927 rs6000_overloaded_builtin_p (enum rs6000_builtins fncode)
12928 {
12929   return (rs6000_builtin_info[(int)fncode].attr & RS6000_BTC_OVERLOADED) != 0;
12930 }
12931
12932 const char *
12933 rs6000_overloaded_builtin_name (enum rs6000_builtins fncode)
12934 {
12935   return rs6000_builtin_info[(int)fncode].name;
12936 }
12937
12938 /* Expand an expression EXP that calls a builtin without arguments.  */
12939 static rtx
12940 rs6000_expand_zeroop_builtin (enum insn_code icode, rtx target)
12941 {
12942   rtx pat;
12943   machine_mode tmode = insn_data[icode].operand[0].mode;
12944
12945   if (icode == CODE_FOR_nothing)
12946     /* Builtin not supported on this processor.  */
12947     return 0;
12948
12949   if (icode == CODE_FOR_rs6000_mffsl
12950       && rs6000_isa_flags & OPTION_MASK_SOFT_FLOAT)
12951     {
12952       error ("%<__builtin_mffsl%> not supported with %<-msoft-float%>");
12953       return const0_rtx;
12954     }
12955
12956   if (target == 0
12957       || GET_MODE (target) != tmode
12958       || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
12959     target = gen_reg_rtx (tmode);
12960
12961   pat = GEN_FCN (icode) (target);
12962   if (! pat)
12963     return 0;
12964   emit_insn (pat);
12965
12966   return target;
12967 }
12968
12969
12970 static rtx
12971 rs6000_expand_mtfsf_builtin (enum insn_code icode, tree exp)
12972 {
12973   rtx pat;
12974   tree arg0 = CALL_EXPR_ARG (exp, 0);
12975   tree arg1 = CALL_EXPR_ARG (exp, 1);
12976   rtx op0 = expand_normal (arg0);
12977   rtx op1 = expand_normal (arg1);
12978   machine_mode mode0 = insn_data[icode].operand[0].mode;
12979   machine_mode mode1 = insn_data[icode].operand[1].mode;
12980
12981   if (icode == CODE_FOR_nothing)
12982     /* Builtin not supported on this processor.  */
12983     return 0;
12984
12985   /* If we got invalid arguments bail out before generating bad rtl.  */
12986   if (arg0 == error_mark_node || arg1 == error_mark_node)
12987     return const0_rtx;
12988
12989   if (!CONST_INT_P (op0)
12990       || INTVAL (op0) > 255
12991       || INTVAL (op0) < 0)
12992     {
12993       error ("argument 1 must be an 8-bit field value");
12994       return const0_rtx;
12995     }
12996
12997   if (! (*insn_data[icode].operand[0].predicate) (op0, mode0))
12998     op0 = copy_to_mode_reg (mode0, op0);
12999
13000   if (! (*insn_data[icode].operand[1].predicate) (op1, mode1))
13001     op1 = copy_to_mode_reg (mode1, op1);
13002
13003   pat = GEN_FCN (icode) (op0, op1);
13004   if (!pat)
13005     return const0_rtx;
13006   emit_insn (pat);
13007
13008   return NULL_RTX;
13009 }
13010
13011 static rtx
13012 rs6000_expand_mtfsb_builtin (enum insn_code icode, tree exp)
13013 {
13014   rtx pat;
13015   tree arg0 = CALL_EXPR_ARG (exp, 0);
13016   rtx op0 = expand_normal (arg0);
13017
13018   if (icode == CODE_FOR_nothing)
13019     /* Builtin not supported on this processor.  */
13020     return 0;
13021
13022   if (rs6000_isa_flags & OPTION_MASK_SOFT_FLOAT)
13023     {
13024       error ("%<__builtin_mtfsb0%> and %<__builtin_mtfsb1%> not supported with "
13025              "%<-msoft-float%>");
13026       return const0_rtx;
13027     }
13028
13029   /* If we got invalid arguments bail out before generating bad rtl.  */
13030   if (arg0 == error_mark_node)
13031     return const0_rtx;
13032
13033   /* Only allow bit numbers 0 to 31.  */
13034   if (!u5bit_cint_operand (op0, VOIDmode))
13035     {
13036        error ("Argument must be a constant between 0 and 31.");
13037        return const0_rtx;
13038      }
13039
13040   pat = GEN_FCN (icode) (op0);
13041   if (!pat)
13042     return const0_rtx;
13043   emit_insn (pat);
13044
13045   return NULL_RTX;
13046 }
13047
13048 static rtx
13049 rs6000_expand_set_fpscr_rn_builtin (enum insn_code icode, tree exp)
13050 {
13051   rtx pat;
13052   tree arg0 = CALL_EXPR_ARG (exp, 0);
13053   rtx op0 = expand_normal (arg0);
13054   machine_mode mode0 = insn_data[icode].operand[0].mode;
13055
13056   if (icode == CODE_FOR_nothing)
13057     /* Builtin not supported on this processor.  */
13058     return 0;
13059
13060   if (rs6000_isa_flags & OPTION_MASK_SOFT_FLOAT)
13061     {
13062       error ("%<__builtin_set_fpscr_rn%> not supported with %<-msoft-float%>");
13063       return const0_rtx;
13064     }
13065
13066   /* If we got invalid arguments bail out before generating bad rtl.  */
13067   if (arg0 == error_mark_node)
13068     return const0_rtx;
13069
13070   /* If the argument is a constant, check the range. Argument can only be a
13071      2-bit value.  Unfortunately, can't check the range of the value at
13072      compile time if the argument is a variable.  The least significant two
13073      bits of the argument, regardless of type, are used to set the rounding
13074      mode.  All other bits are ignored.  */
13075   if (CONST_INT_P (op0) && !const_0_to_3_operand(op0, VOIDmode))
13076     {
13077       error ("Argument must be a value between 0 and 3.");
13078       return const0_rtx;
13079     }
13080
13081   if (! (*insn_data[icode].operand[0].predicate) (op0, mode0))
13082     op0 = copy_to_mode_reg (mode0, op0);
13083
13084   pat = GEN_FCN (icode) (op0);
13085   if (!pat)
13086     return const0_rtx;
13087   emit_insn (pat);
13088
13089   return NULL_RTX;
13090 }
13091 static rtx
13092 rs6000_expand_set_fpscr_drn_builtin (enum insn_code icode, tree exp)
13093 {
13094   rtx pat;
13095   tree arg0 = CALL_EXPR_ARG (exp, 0);
13096   rtx op0 = expand_normal (arg0);
13097   machine_mode mode0 = insn_data[icode].operand[0].mode;
13098
13099   if (TARGET_32BIT)
13100     /* Builtin not supported in 32-bit mode.  */
13101     fatal_error (input_location,
13102                  "%<__builtin_set_fpscr_drn%> is not supported "
13103                  "in 32-bit mode");
13104
13105   if (rs6000_isa_flags & OPTION_MASK_SOFT_FLOAT)
13106     {
13107       error ("%<__builtin_set_fpscr_drn%> not supported with %<-msoft-float%>");
13108       return const0_rtx;
13109     }
13110
13111   if (icode == CODE_FOR_nothing)
13112     /* Builtin not supported on this processor.  */
13113     return 0;
13114
13115   /* If we got invalid arguments bail out before generating bad rtl.  */
13116   if (arg0 == error_mark_node)
13117     return const0_rtx;
13118
13119   /* If the argument is a constant, check the range. Agrument can only be a
13120      3-bit value.  Unfortunately, can't check the range of the value at
13121      compile time if the argument is a variable. The least significant two
13122      bits of the argument, regardless of type, are used to set the rounding
13123      mode.  All other bits are ignored.  */
13124   if (CONST_INT_P (op0) && !const_0_to_7_operand(op0, VOIDmode))
13125    {
13126       error ("Argument must be a value between 0 and 7.");
13127       return const0_rtx;
13128     }
13129
13130   if (! (*insn_data[icode].operand[0].predicate) (op0, mode0))
13131     op0 = copy_to_mode_reg (mode0, op0);
13132
13133   pat = GEN_FCN (icode) (op0);
13134   if (! pat)
13135     return const0_rtx;
13136   emit_insn (pat);
13137
13138   return NULL_RTX;
13139 }
13140
13141 static rtx
13142 rs6000_expand_unop_builtin (enum insn_code icode, tree exp, rtx target)
13143 {
13144   rtx pat;
13145   tree arg0 = CALL_EXPR_ARG (exp, 0);
13146   rtx op0 = expand_normal (arg0);
13147   machine_mode tmode = insn_data[icode].operand[0].mode;
13148   machine_mode mode0 = insn_data[icode].operand[1].mode;
13149
13150   if (icode == CODE_FOR_nothing)
13151     /* Builtin not supported on this processor.  */
13152     return 0;
13153
13154   /* If we got invalid arguments bail out before generating bad rtl.  */
13155   if (arg0 == error_mark_node)
13156     return const0_rtx;
13157
13158   if (icode == CODE_FOR_altivec_vspltisb
13159       || icode == CODE_FOR_altivec_vspltish
13160       || icode == CODE_FOR_altivec_vspltisw)
13161     {
13162       /* Only allow 5-bit *signed* literals.  */
13163       if (!CONST_INT_P (op0)
13164           || INTVAL (op0) > 15
13165           || INTVAL (op0) < -16)
13166         {
13167           error ("argument 1 must be a 5-bit signed literal");
13168           return CONST0_RTX (tmode);
13169         }
13170     }
13171
13172   if (target == 0
13173       || GET_MODE (target) != tmode
13174       || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
13175     target = gen_reg_rtx (tmode);
13176
13177   if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
13178     op0 = copy_to_mode_reg (mode0, op0);
13179
13180   pat = GEN_FCN (icode) (target, op0);
13181   if (! pat)
13182     return 0;
13183   emit_insn (pat);
13184
13185   return target;
13186 }
13187
13188 static rtx
13189 altivec_expand_abs_builtin (enum insn_code icode, tree exp, rtx target)
13190 {
13191   rtx pat, scratch1, scratch2;
13192   tree arg0 = CALL_EXPR_ARG (exp, 0);
13193   rtx op0 = expand_normal (arg0);
13194   machine_mode tmode = insn_data[icode].operand[0].mode;
13195   machine_mode mode0 = insn_data[icode].operand[1].mode;
13196
13197   /* If we have invalid arguments, bail out before generating bad rtl.  */
13198   if (arg0 == error_mark_node)
13199     return const0_rtx;
13200
13201   if (target == 0
13202       || GET_MODE (target) != tmode
13203       || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
13204     target = gen_reg_rtx (tmode);
13205
13206   if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
13207     op0 = copy_to_mode_reg (mode0, op0);
13208
13209   scratch1 = gen_reg_rtx (mode0);
13210   scratch2 = gen_reg_rtx (mode0);
13211
13212   pat = GEN_FCN (icode) (target, op0, scratch1, scratch2);
13213   if (! pat)
13214     return 0;
13215   emit_insn (pat);
13216
13217   return target;
13218 }
13219
13220 static rtx
13221 rs6000_expand_binop_builtin (enum insn_code icode, tree exp, rtx target)
13222 {
13223   rtx pat;
13224   tree arg0 = CALL_EXPR_ARG (exp, 0);
13225   tree arg1 = CALL_EXPR_ARG (exp, 1);
13226   rtx op0 = expand_normal (arg0);
13227   rtx op1 = expand_normal (arg1);
13228   machine_mode tmode = insn_data[icode].operand[0].mode;
13229   machine_mode mode0 = insn_data[icode].operand[1].mode;
13230   machine_mode mode1 = insn_data[icode].operand[2].mode;
13231
13232   if (icode == CODE_FOR_nothing)
13233     /* Builtin not supported on this processor.  */
13234     return 0;
13235
13236   /* If we got invalid arguments bail out before generating bad rtl.  */
13237   if (arg0 == error_mark_node || arg1 == error_mark_node)
13238     return const0_rtx;
13239
13240   if (icode == CODE_FOR_unpackv1ti
13241            || icode == CODE_FOR_unpackkf
13242            || icode == CODE_FOR_unpacktf
13243            || icode == CODE_FOR_unpackif
13244            || icode == CODE_FOR_unpacktd)
13245     {
13246       /* Only allow 1-bit unsigned literals. */
13247       STRIP_NOPS (arg1);
13248       if (TREE_CODE (arg1) != INTEGER_CST
13249           || !IN_RANGE (TREE_INT_CST_LOW (arg1), 0, 1))
13250         {
13251           error ("argument 2 must be a 1-bit unsigned literal");
13252           return CONST0_RTX (tmode);
13253         }
13254     }
13255   else if (icode == CODE_FOR_altivec_vspltw)
13256     {
13257       /* Only allow 2-bit unsigned literals.  */
13258       STRIP_NOPS (arg1);
13259       if (TREE_CODE (arg1) != INTEGER_CST
13260           || TREE_INT_CST_LOW (arg1) & ~3)
13261         {
13262           error ("argument 2 must be a 2-bit unsigned literal");
13263           return CONST0_RTX (tmode);
13264         }
13265     }
13266   else if (icode == CODE_FOR_altivec_vsplth)
13267     {
13268       /* Only allow 3-bit unsigned literals.  */
13269       STRIP_NOPS (arg1);
13270       if (TREE_CODE (arg1) != INTEGER_CST
13271           || TREE_INT_CST_LOW (arg1) & ~7)
13272         {
13273           error ("argument 2 must be a 3-bit unsigned literal");
13274           return CONST0_RTX (tmode);
13275         }
13276     }
13277   else if (icode == CODE_FOR_altivec_vspltb)
13278     {
13279       /* Only allow 4-bit unsigned literals.  */
13280       STRIP_NOPS (arg1);
13281       if (TREE_CODE (arg1) != INTEGER_CST
13282           || TREE_INT_CST_LOW (arg1) & ~15)
13283         {
13284           error ("argument 2 must be a 4-bit unsigned literal");
13285           return CONST0_RTX (tmode);
13286         }
13287     }
13288   else if (icode == CODE_FOR_altivec_vcfux
13289       || icode == CODE_FOR_altivec_vcfsx
13290       || icode == CODE_FOR_altivec_vctsxs
13291       || icode == CODE_FOR_altivec_vctuxs)
13292     {
13293       /* Only allow 5-bit unsigned literals.  */
13294       STRIP_NOPS (arg1);
13295       if (TREE_CODE (arg1) != INTEGER_CST
13296           || TREE_INT_CST_LOW (arg1) & ~0x1f)
13297         {
13298           error ("argument 2 must be a 5-bit unsigned literal");
13299           return CONST0_RTX (tmode);
13300         }
13301     }
13302   else if (icode == CODE_FOR_dfptstsfi_eq_dd
13303       || icode == CODE_FOR_dfptstsfi_lt_dd
13304       || icode == CODE_FOR_dfptstsfi_gt_dd
13305       || icode == CODE_FOR_dfptstsfi_unordered_dd
13306       || icode == CODE_FOR_dfptstsfi_eq_td
13307       || icode == CODE_FOR_dfptstsfi_lt_td
13308       || icode == CODE_FOR_dfptstsfi_gt_td
13309       || icode == CODE_FOR_dfptstsfi_unordered_td)
13310     {
13311       /* Only allow 6-bit unsigned literals.  */
13312       STRIP_NOPS (arg0);
13313       if (TREE_CODE (arg0) != INTEGER_CST
13314           || !IN_RANGE (TREE_INT_CST_LOW (arg0), 0, 63))
13315         {
13316           error ("argument 1 must be a 6-bit unsigned literal");
13317           return CONST0_RTX (tmode);
13318         }
13319     }
13320   else if (icode == CODE_FOR_xststdcqp_kf
13321            || icode == CODE_FOR_xststdcqp_tf
13322            || icode == CODE_FOR_xststdcdp
13323            || icode == CODE_FOR_xststdcsp
13324            || icode == CODE_FOR_xvtstdcdp
13325            || icode == CODE_FOR_xvtstdcsp)
13326     {
13327       /* Only allow 7-bit unsigned literals. */
13328       STRIP_NOPS (arg1);
13329       if (TREE_CODE (arg1) != INTEGER_CST
13330           || !IN_RANGE (TREE_INT_CST_LOW (arg1), 0, 127))
13331         {
13332           error ("argument 2 must be a 7-bit unsigned literal");
13333           return CONST0_RTX (tmode);
13334         }
13335     }
13336
13337   if (target == 0
13338       || GET_MODE (target) != tmode
13339       || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
13340     target = gen_reg_rtx (tmode);
13341
13342   if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
13343     op0 = copy_to_mode_reg (mode0, op0);
13344   if (! (*insn_data[icode].operand[2].predicate) (op1, mode1))
13345     op1 = copy_to_mode_reg (mode1, op1);
13346
13347   pat = GEN_FCN (icode) (target, op0, op1);
13348   if (! pat)
13349     return 0;
13350   emit_insn (pat);
13351
13352   return target;
13353 }
13354
13355 static rtx
13356 altivec_expand_predicate_builtin (enum insn_code icode, tree exp, rtx target)
13357 {
13358   rtx pat, scratch;
13359   tree cr6_form = CALL_EXPR_ARG (exp, 0);
13360   tree arg0 = CALL_EXPR_ARG (exp, 1);
13361   tree arg1 = CALL_EXPR_ARG (exp, 2);
13362   rtx op0 = expand_normal (arg0);
13363   rtx op1 = expand_normal (arg1);
13364   machine_mode tmode = SImode;
13365   machine_mode mode0 = insn_data[icode].operand[1].mode;
13366   machine_mode mode1 = insn_data[icode].operand[2].mode;
13367   int cr6_form_int;
13368
13369   if (TREE_CODE (cr6_form) != INTEGER_CST)
13370     {
13371       error ("argument 1 of %qs must be a constant",
13372              "__builtin_altivec_predicate");
13373       return const0_rtx;
13374     }
13375   else
13376     cr6_form_int = TREE_INT_CST_LOW (cr6_form);
13377
13378   gcc_assert (mode0 == mode1);
13379
13380   /* If we have invalid arguments, bail out before generating bad rtl.  */
13381   if (arg0 == error_mark_node || arg1 == error_mark_node)
13382     return const0_rtx;
13383
13384   if (target == 0
13385       || GET_MODE (target) != tmode
13386       || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
13387     target = gen_reg_rtx (tmode);
13388
13389   if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
13390     op0 = copy_to_mode_reg (mode0, op0);
13391   if (! (*insn_data[icode].operand[2].predicate) (op1, mode1))
13392     op1 = copy_to_mode_reg (mode1, op1);
13393
13394   /* Note that for many of the relevant operations (e.g. cmpne or
13395      cmpeq) with float or double operands, it makes more sense for the
13396      mode of the allocated scratch register to select a vector of
13397      integer.  But the choice to copy the mode of operand 0 was made
13398      long ago and there are no plans to change it.  */
13399   scratch = gen_reg_rtx (mode0);
13400
13401   pat = GEN_FCN (icode) (scratch, op0, op1);
13402   if (! pat)
13403     return 0;
13404   emit_insn (pat);
13405
13406   /* The vec_any* and vec_all* predicates use the same opcodes for two
13407      different operations, but the bits in CR6 will be different
13408      depending on what information we want.  So we have to play tricks
13409      with CR6 to get the right bits out.
13410
13411      If you think this is disgusting, look at the specs for the
13412      AltiVec predicates.  */
13413
13414   switch (cr6_form_int)
13415     {
13416     case 0:
13417       emit_insn (gen_cr6_test_for_zero (target));
13418       break;
13419     case 1:
13420       emit_insn (gen_cr6_test_for_zero_reverse (target));
13421       break;
13422     case 2:
13423       emit_insn (gen_cr6_test_for_lt (target));
13424       break;
13425     case 3:
13426       emit_insn (gen_cr6_test_for_lt_reverse (target));
13427       break;
13428     default:
13429       error ("argument 1 of %qs is out of range",
13430              "__builtin_altivec_predicate");
13431       break;
13432     }
13433
13434   return target;
13435 }
13436
13437 rtx
13438 swap_endian_selector_for_mode (machine_mode mode)
13439 {
13440   unsigned int swap1[16] = {15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0};
13441   unsigned int swap2[16] = {7,6,5,4,3,2,1,0,15,14,13,12,11,10,9,8};
13442   unsigned int swap4[16] = {3,2,1,0,7,6,5,4,11,10,9,8,15,14,13,12};
13443   unsigned int swap8[16] = {1,0,3,2,5,4,7,6,9,8,11,10,13,12,15,14};
13444
13445   unsigned int *swaparray, i;
13446   rtx perm[16];
13447
13448   switch (mode)
13449     {
13450     case E_V1TImode:
13451       swaparray = swap1;
13452       break;
13453     case E_V2DFmode:
13454     case E_V2DImode:
13455       swaparray = swap2;
13456       break;
13457     case E_V4SFmode:
13458     case E_V4SImode:
13459       swaparray = swap4;
13460       break;
13461     case E_V8HImode:
13462       swaparray = swap8;
13463       break;
13464     default:
13465       gcc_unreachable ();
13466     }
13467
13468   for (i = 0; i < 16; ++i)
13469     perm[i] = GEN_INT (swaparray[i]);
13470
13471   return force_reg (V16QImode, gen_rtx_CONST_VECTOR (V16QImode,
13472                                                      gen_rtvec_v (16, perm)));
13473 }
13474
13475 static rtx
13476 altivec_expand_lv_builtin (enum insn_code icode, tree exp, rtx target, bool blk)
13477 {
13478   rtx pat, addr;
13479   tree arg0 = CALL_EXPR_ARG (exp, 0);
13480   tree arg1 = CALL_EXPR_ARG (exp, 1);
13481   machine_mode tmode = insn_data[icode].operand[0].mode;
13482   machine_mode mode0 = Pmode;
13483   machine_mode mode1 = Pmode;
13484   rtx op0 = expand_normal (arg0);
13485   rtx op1 = expand_normal (arg1);
13486
13487   if (icode == CODE_FOR_nothing)
13488     /* Builtin not supported on this processor.  */
13489     return 0;
13490
13491   /* If we got invalid arguments bail out before generating bad rtl.  */
13492   if (arg0 == error_mark_node || arg1 == error_mark_node)
13493     return const0_rtx;
13494
13495   if (target == 0
13496       || GET_MODE (target) != tmode
13497       || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
13498     target = gen_reg_rtx (tmode);
13499
13500   op1 = copy_to_mode_reg (mode1, op1);
13501
13502   /* For LVX, express the RTL accurately by ANDing the address with -16.
13503      LVXL and LVE*X expand to use UNSPECs to hide their special behavior,
13504      so the raw address is fine.  */
13505   if (icode == CODE_FOR_altivec_lvx_v1ti
13506       || icode == CODE_FOR_altivec_lvx_v2df
13507       || icode == CODE_FOR_altivec_lvx_v2di
13508       || icode == CODE_FOR_altivec_lvx_v4sf
13509       || icode == CODE_FOR_altivec_lvx_v4si
13510       || icode == CODE_FOR_altivec_lvx_v8hi
13511       || icode == CODE_FOR_altivec_lvx_v16qi)
13512     {
13513       rtx rawaddr;
13514       if (op0 == const0_rtx)
13515         rawaddr = op1;
13516       else
13517         {
13518           op0 = copy_to_mode_reg (mode0, op0);
13519           rawaddr = gen_rtx_PLUS (Pmode, op1, op0);
13520         }
13521       addr = gen_rtx_AND (Pmode, rawaddr, gen_rtx_CONST_INT (Pmode, -16));
13522       addr = gen_rtx_MEM (blk ? BLKmode : tmode, addr);
13523
13524       emit_insn (gen_rtx_SET (target, addr));
13525     }
13526   else
13527     {
13528       if (op0 == const0_rtx)
13529         addr = gen_rtx_MEM (blk ? BLKmode : tmode, op1);
13530       else
13531         {
13532           op0 = copy_to_mode_reg (mode0, op0);
13533           addr = gen_rtx_MEM (blk ? BLKmode : tmode,
13534                               gen_rtx_PLUS (Pmode, op1, op0));
13535         }
13536
13537       pat = GEN_FCN (icode) (target, addr);
13538       if (! pat)
13539         return 0;
13540       emit_insn (pat);
13541     }
13542
13543   return target;
13544 }
13545
13546 static rtx
13547 altivec_expand_stxvl_builtin (enum insn_code icode, tree exp)
13548 {
13549   rtx pat;
13550   tree arg0 = CALL_EXPR_ARG (exp, 0);
13551   tree arg1 = CALL_EXPR_ARG (exp, 1);
13552   tree arg2 = CALL_EXPR_ARG (exp, 2);
13553   rtx op0 = expand_normal (arg0);
13554   rtx op1 = expand_normal (arg1);
13555   rtx op2 = expand_normal (arg2);
13556   machine_mode mode0 = insn_data[icode].operand[0].mode;
13557   machine_mode mode1 = insn_data[icode].operand[1].mode;
13558   machine_mode mode2 = insn_data[icode].operand[2].mode;
13559
13560   if (icode == CODE_FOR_nothing)
13561     /* Builtin not supported on this processor.  */
13562     return NULL_RTX;
13563
13564   /* If we got invalid arguments bail out before generating bad rtl.  */
13565   if (arg0 == error_mark_node
13566       || arg1 == error_mark_node
13567       || arg2 == error_mark_node)
13568     return NULL_RTX;
13569
13570   if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
13571     op0 = copy_to_mode_reg (mode0, op0);
13572   if (! (*insn_data[icode].operand[2].predicate) (op1, mode1))
13573     op1 = copy_to_mode_reg (mode1, op1);
13574   if (! (*insn_data[icode].operand[3].predicate) (op2, mode2))
13575     op2 = copy_to_mode_reg (mode2, op2);
13576
13577   pat = GEN_FCN (icode) (op0, op1, op2);
13578   if (pat)
13579     emit_insn (pat);
13580
13581   return NULL_RTX;
13582 }
13583
13584 static rtx
13585 altivec_expand_stv_builtin (enum insn_code icode, tree exp)
13586 {
13587   tree arg0 = CALL_EXPR_ARG (exp, 0);
13588   tree arg1 = CALL_EXPR_ARG (exp, 1);
13589   tree arg2 = CALL_EXPR_ARG (exp, 2);
13590   rtx op0 = expand_normal (arg0);
13591   rtx op1 = expand_normal (arg1);
13592   rtx op2 = expand_normal (arg2);
13593   rtx pat, addr, rawaddr;
13594   machine_mode tmode = insn_data[icode].operand[0].mode;
13595   machine_mode smode = insn_data[icode].operand[1].mode;
13596   machine_mode mode1 = Pmode;
13597   machine_mode mode2 = Pmode;
13598
13599   /* Invalid arguments.  Bail before doing anything stoopid!  */
13600   if (arg0 == error_mark_node
13601       || arg1 == error_mark_node
13602       || arg2 == error_mark_node)
13603     return const0_rtx;
13604
13605   op2 = copy_to_mode_reg (mode2, op2);
13606
13607   /* For STVX, express the RTL accurately by ANDing the address with -16.
13608      STVXL and STVE*X expand to use UNSPECs to hide their special behavior,
13609      so the raw address is fine.  */
13610   if (icode == CODE_FOR_altivec_stvx_v2df
13611       || icode == CODE_FOR_altivec_stvx_v2di
13612       || icode == CODE_FOR_altivec_stvx_v4sf
13613       || icode == CODE_FOR_altivec_stvx_v4si
13614       || icode == CODE_FOR_altivec_stvx_v8hi
13615       || icode == CODE_FOR_altivec_stvx_v16qi)
13616     {
13617       if (op1 == const0_rtx)
13618         rawaddr = op2;
13619       else
13620         {
13621           op1 = copy_to_mode_reg (mode1, op1);
13622           rawaddr = gen_rtx_PLUS (Pmode, op2, op1);
13623         }
13624
13625       addr = gen_rtx_AND (Pmode, rawaddr, gen_rtx_CONST_INT (Pmode, -16));
13626       addr = gen_rtx_MEM (tmode, addr);
13627
13628       op0 = copy_to_mode_reg (tmode, op0);
13629
13630       emit_insn (gen_rtx_SET (addr, op0));
13631     }
13632   else
13633     {
13634       if (! (*insn_data[icode].operand[1].predicate) (op0, smode))
13635         op0 = copy_to_mode_reg (smode, op0);
13636
13637       if (op1 == const0_rtx)
13638         addr = gen_rtx_MEM (tmode, op2);
13639       else
13640         {
13641           op1 = copy_to_mode_reg (mode1, op1);
13642           addr = gen_rtx_MEM (tmode, gen_rtx_PLUS (Pmode, op2, op1));
13643         }
13644
13645       pat = GEN_FCN (icode) (addr, op0);
13646       if (pat)
13647         emit_insn (pat);
13648     }
13649
13650   return NULL_RTX;
13651 }
13652
13653 /* Return the appropriate SPR number associated with the given builtin.  */
13654 static inline HOST_WIDE_INT
13655 htm_spr_num (enum rs6000_builtins code)
13656 {
13657   if (code == HTM_BUILTIN_GET_TFHAR
13658       || code == HTM_BUILTIN_SET_TFHAR)
13659     return TFHAR_SPR;
13660   else if (code == HTM_BUILTIN_GET_TFIAR
13661            || code == HTM_BUILTIN_SET_TFIAR)
13662     return TFIAR_SPR;
13663   else if (code == HTM_BUILTIN_GET_TEXASR
13664            || code == HTM_BUILTIN_SET_TEXASR)
13665     return TEXASR_SPR;
13666   gcc_assert (code == HTM_BUILTIN_GET_TEXASRU
13667               || code == HTM_BUILTIN_SET_TEXASRU);
13668   return TEXASRU_SPR;
13669 }
13670
13671 /* Return the correct ICODE value depending on whether we are
13672    setting or reading the HTM SPRs.  */
13673 static inline enum insn_code
13674 rs6000_htm_spr_icode (bool nonvoid)
13675 {
13676   if (nonvoid)
13677     return (TARGET_POWERPC64) ? CODE_FOR_htm_mfspr_di : CODE_FOR_htm_mfspr_si;
13678   else
13679     return (TARGET_POWERPC64) ? CODE_FOR_htm_mtspr_di : CODE_FOR_htm_mtspr_si;
13680 }
13681
13682 /* Expand the HTM builtin in EXP and store the result in TARGET.
13683    Store true in *EXPANDEDP if we found a builtin to expand.  */
13684 static rtx
13685 htm_expand_builtin (tree exp, rtx target, bool * expandedp)
13686 {
13687   tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
13688   bool nonvoid = TREE_TYPE (TREE_TYPE (fndecl)) != void_type_node;
13689   enum rs6000_builtins fcode = (enum rs6000_builtins) DECL_FUNCTION_CODE (fndecl);
13690   const struct builtin_description *d;
13691   size_t i;
13692
13693   *expandedp = true;
13694
13695   if (!TARGET_POWERPC64
13696       && (fcode == HTM_BUILTIN_TABORTDC
13697           || fcode == HTM_BUILTIN_TABORTDCI))
13698     {
13699       size_t uns_fcode = (size_t)fcode;
13700       const char *name = rs6000_builtin_info[uns_fcode].name;
13701       error ("builtin %qs is only valid in 64-bit mode", name);
13702       return const0_rtx;
13703     }
13704
13705   /* Expand the HTM builtins.  */
13706   d = bdesc_htm;
13707   for (i = 0; i < ARRAY_SIZE (bdesc_htm); i++, d++)
13708     if (d->code == fcode)
13709       {
13710         rtx op[MAX_HTM_OPERANDS], pat;
13711         int nopnds = 0;
13712         tree arg;
13713         call_expr_arg_iterator iter;
13714         unsigned attr = rs6000_builtin_info[fcode].attr;
13715         enum insn_code icode = d->icode;
13716         const struct insn_operand_data *insn_op;
13717         bool uses_spr = (attr & RS6000_BTC_SPR);
13718         rtx cr = NULL_RTX;
13719
13720         if (uses_spr)
13721           icode = rs6000_htm_spr_icode (nonvoid);
13722         insn_op = &insn_data[icode].operand[0];
13723
13724         if (nonvoid)
13725           {
13726             machine_mode tmode = (uses_spr) ? insn_op->mode : E_SImode;
13727             if (!target
13728                 || GET_MODE (target) != tmode
13729                 || (uses_spr && !(*insn_op->predicate) (target, tmode)))
13730               target = gen_reg_rtx (tmode);
13731             if (uses_spr)
13732               op[nopnds++] = target;
13733           }
13734
13735         FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
13736         {
13737           if (arg == error_mark_node || nopnds >= MAX_HTM_OPERANDS)
13738             return const0_rtx;
13739
13740           insn_op = &insn_data[icode].operand[nopnds];
13741
13742           op[nopnds] = expand_normal (arg);
13743
13744           if (!(*insn_op->predicate) (op[nopnds], insn_op->mode))
13745             {
13746               if (!strcmp (insn_op->constraint, "n"))
13747                 {
13748                   int arg_num = (nonvoid) ? nopnds : nopnds + 1;
13749                   if (!CONST_INT_P (op[nopnds]))
13750                     error ("argument %d must be an unsigned literal", arg_num);
13751                   else
13752                     error ("argument %d is an unsigned literal that is "
13753                            "out of range", arg_num);
13754                   return const0_rtx;
13755                 }
13756               op[nopnds] = copy_to_mode_reg (insn_op->mode, op[nopnds]);
13757             }
13758
13759           nopnds++;
13760         }
13761
13762         /* Handle the builtins for extended mnemonics.  These accept
13763            no arguments, but map to builtins that take arguments.  */
13764         switch (fcode)
13765           {
13766           case HTM_BUILTIN_TENDALL:  /* Alias for: tend. 1  */
13767           case HTM_BUILTIN_TRESUME:  /* Alias for: tsr. 1  */
13768             op[nopnds++] = GEN_INT (1);
13769             if (flag_checking)
13770               attr |= RS6000_BTC_UNARY;
13771             break;
13772           case HTM_BUILTIN_TSUSPEND: /* Alias for: tsr. 0  */
13773             op[nopnds++] = GEN_INT (0);
13774             if (flag_checking)
13775               attr |= RS6000_BTC_UNARY;
13776             break;
13777           default:
13778             break;
13779           }
13780
13781         /* If this builtin accesses SPRs, then pass in the appropriate
13782            SPR number and SPR regno as the last two operands.  */
13783         if (uses_spr)
13784           {
13785             machine_mode mode = (TARGET_POWERPC64) ? DImode : SImode;
13786             op[nopnds++] = gen_rtx_CONST_INT (mode, htm_spr_num (fcode));
13787           }
13788         /* If this builtin accesses a CR, then pass in a scratch
13789            CR as the last operand.  */
13790         else if (attr & RS6000_BTC_CR)
13791           { cr = gen_reg_rtx (CCmode);
13792             op[nopnds++] = cr;
13793           }
13794
13795         if (flag_checking)
13796           {
13797             int expected_nopnds = 0;
13798             if ((attr & RS6000_BTC_TYPE_MASK) == RS6000_BTC_UNARY)
13799               expected_nopnds = 1;
13800             else if ((attr & RS6000_BTC_TYPE_MASK) == RS6000_BTC_BINARY)
13801               expected_nopnds = 2;
13802             else if ((attr & RS6000_BTC_TYPE_MASK) == RS6000_BTC_TERNARY)
13803               expected_nopnds = 3;
13804             if (!(attr & RS6000_BTC_VOID))
13805               expected_nopnds += 1;
13806             if (uses_spr)
13807               expected_nopnds += 1;
13808
13809             gcc_assert (nopnds == expected_nopnds
13810                         && nopnds <= MAX_HTM_OPERANDS);
13811           }
13812
13813         switch (nopnds)
13814           {
13815           case 1:
13816             pat = GEN_FCN (icode) (op[0]);
13817             break;
13818           case 2:
13819             pat = GEN_FCN (icode) (op[0], op[1]);
13820             break;
13821           case 3:
13822             pat = GEN_FCN (icode) (op[0], op[1], op[2]);
13823             break;
13824           case 4:
13825             pat = GEN_FCN (icode) (op[0], op[1], op[2], op[3]);
13826             break;
13827           default:
13828             gcc_unreachable ();
13829           }
13830         if (!pat)
13831           return NULL_RTX;
13832         emit_insn (pat);
13833
13834         if (attr & RS6000_BTC_CR)
13835           {
13836             if (fcode == HTM_BUILTIN_TBEGIN)
13837               {
13838                 /* Emit code to set TARGET to true or false depending on
13839                    whether the tbegin. instruction successfully or failed
13840                    to start a transaction.  We do this by placing the 1's
13841                    complement of CR's EQ bit into TARGET.  */
13842                 rtx scratch = gen_reg_rtx (SImode);
13843                 emit_insn (gen_rtx_SET (scratch,
13844                                         gen_rtx_EQ (SImode, cr,
13845                                                      const0_rtx)));
13846                 emit_insn (gen_rtx_SET (target,
13847                                         gen_rtx_XOR (SImode, scratch,
13848                                                      GEN_INT (1))));
13849               }
13850             else
13851               {
13852                 /* Emit code to copy the 4-bit condition register field
13853                    CR into the least significant end of register TARGET.  */
13854                 rtx scratch1 = gen_reg_rtx (SImode);
13855                 rtx scratch2 = gen_reg_rtx (SImode);
13856                 rtx subreg = simplify_gen_subreg (CCmode, scratch1, SImode, 0);
13857                 emit_insn (gen_movcc (subreg, cr));
13858                 emit_insn (gen_lshrsi3 (scratch2, scratch1, GEN_INT (28)));
13859                 emit_insn (gen_andsi3 (target, scratch2, GEN_INT (0xf)));
13860               }
13861           }
13862
13863         if (nonvoid)
13864           return target;
13865         return const0_rtx;
13866       }
13867
13868   *expandedp = false;
13869   return NULL_RTX;
13870 }
13871
13872 /* Expand the CPU builtin in FCODE and store the result in TARGET.  */
13873
13874 static rtx
13875 cpu_expand_builtin (enum rs6000_builtins fcode, tree exp ATTRIBUTE_UNUSED,
13876                     rtx target)
13877 {
13878   /* __builtin_cpu_init () is a nop, so expand to nothing.  */
13879   if (fcode == RS6000_BUILTIN_CPU_INIT)
13880     return const0_rtx;
13881
13882   if (target == 0 || GET_MODE (target) != SImode)
13883     target = gen_reg_rtx (SImode);
13884
13885 #ifdef TARGET_LIBC_PROVIDES_HWCAP_IN_TCB
13886   tree arg = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
13887   /* Target clones creates an ARRAY_REF instead of STRING_CST, convert it back
13888      to a STRING_CST.  */
13889   if (TREE_CODE (arg) == ARRAY_REF
13890       && TREE_CODE (TREE_OPERAND (arg, 0)) == STRING_CST
13891       && TREE_CODE (TREE_OPERAND (arg, 1)) == INTEGER_CST
13892       && compare_tree_int (TREE_OPERAND (arg, 1), 0) == 0)
13893     arg = TREE_OPERAND (arg, 0);
13894
13895   if (TREE_CODE (arg) != STRING_CST)
13896     {
13897       error ("builtin %qs only accepts a string argument",
13898              rs6000_builtin_info[(size_t) fcode].name);
13899       return const0_rtx;
13900     }
13901
13902   if (fcode == RS6000_BUILTIN_CPU_IS)
13903     {
13904       const char *cpu = TREE_STRING_POINTER (arg);
13905       rtx cpuid = NULL_RTX;
13906       for (size_t i = 0; i < ARRAY_SIZE (cpu_is_info); i++)
13907         if (strcmp (cpu, cpu_is_info[i].cpu) == 0)
13908           {
13909             /* The CPUID value in the TCB is offset by _DL_FIRST_PLATFORM.  */
13910             cpuid = GEN_INT (cpu_is_info[i].cpuid + _DL_FIRST_PLATFORM);
13911             break;
13912           }
13913       if (cpuid == NULL_RTX)
13914         {
13915           /* Invalid CPU argument.  */
13916           error ("cpu %qs is an invalid argument to builtin %qs",
13917                  cpu, rs6000_builtin_info[(size_t) fcode].name);
13918           return const0_rtx;
13919         }
13920
13921       rtx platform = gen_reg_rtx (SImode);
13922       rtx tcbmem = gen_const_mem (SImode,
13923                                   gen_rtx_PLUS (Pmode,
13924                                                 gen_rtx_REG (Pmode, TLS_REGNUM),
13925                                                 GEN_INT (TCB_PLATFORM_OFFSET)));
13926       emit_move_insn (platform, tcbmem);
13927       emit_insn (gen_eqsi3 (target, platform, cpuid));
13928     }
13929   else if (fcode == RS6000_BUILTIN_CPU_SUPPORTS)
13930     {
13931       const char *hwcap = TREE_STRING_POINTER (arg);
13932       rtx mask = NULL_RTX;
13933       int hwcap_offset;
13934       for (size_t i = 0; i < ARRAY_SIZE (cpu_supports_info); i++)
13935         if (strcmp (hwcap, cpu_supports_info[i].hwcap) == 0)
13936           {
13937             mask = GEN_INT (cpu_supports_info[i].mask);
13938             hwcap_offset = TCB_HWCAP_OFFSET (cpu_supports_info[i].id);
13939             break;
13940           }
13941       if (mask == NULL_RTX)
13942         {
13943           /* Invalid HWCAP argument.  */
13944           error ("%s %qs is an invalid argument to builtin %qs",
13945                  "hwcap", hwcap, rs6000_builtin_info[(size_t) fcode].name);
13946           return const0_rtx;
13947         }
13948
13949       rtx tcb_hwcap = gen_reg_rtx (SImode);
13950       rtx tcbmem = gen_const_mem (SImode,
13951                                   gen_rtx_PLUS (Pmode,
13952                                                 gen_rtx_REG (Pmode, TLS_REGNUM),
13953                                                 GEN_INT (hwcap_offset)));
13954       emit_move_insn (tcb_hwcap, tcbmem);
13955       rtx scratch1 = gen_reg_rtx (SImode);
13956       emit_insn (gen_rtx_SET (scratch1, gen_rtx_AND (SImode, tcb_hwcap, mask)));
13957       rtx scratch2 = gen_reg_rtx (SImode);
13958       emit_insn (gen_eqsi3 (scratch2, scratch1, const0_rtx));
13959       emit_insn (gen_rtx_SET (target, gen_rtx_XOR (SImode, scratch2, const1_rtx)));
13960     }
13961   else
13962     gcc_unreachable ();
13963
13964   /* Record that we have expanded a CPU builtin, so that we can later
13965      emit a reference to the special symbol exported by LIBC to ensure we
13966      do not link against an old LIBC that doesn't support this feature.  */
13967   cpu_builtin_p = true;
13968
13969 #else
13970   warning (0, "builtin %qs needs GLIBC (2.23 and newer) that exports hardware "
13971            "capability bits", rs6000_builtin_info[(size_t) fcode].name);
13972   
13973   /* For old LIBCs, always return FALSE.  */
13974   emit_move_insn (target, GEN_INT (0));
13975 #endif /* TARGET_LIBC_PROVIDES_HWCAP_IN_TCB */
13976
13977   return target;
13978 }
13979
13980 static rtx
13981 rs6000_expand_ternop_builtin (enum insn_code icode, tree exp, rtx target)
13982 {
13983   rtx pat;
13984   tree arg0 = CALL_EXPR_ARG (exp, 0);
13985   tree arg1 = CALL_EXPR_ARG (exp, 1);
13986   tree arg2 = CALL_EXPR_ARG (exp, 2);
13987   rtx op0 = expand_normal (arg0);
13988   rtx op1 = expand_normal (arg1);
13989   rtx op2 = expand_normal (arg2);
13990   machine_mode tmode = insn_data[icode].operand[0].mode;
13991   machine_mode mode0 = insn_data[icode].operand[1].mode;
13992   machine_mode mode1 = insn_data[icode].operand[2].mode;
13993   machine_mode mode2 = insn_data[icode].operand[3].mode;
13994
13995   if (icode == CODE_FOR_nothing)
13996     /* Builtin not supported on this processor.  */
13997     return 0;
13998
13999   /* If we got invalid arguments bail out before generating bad rtl.  */
14000   if (arg0 == error_mark_node
14001       || arg1 == error_mark_node
14002       || arg2 == error_mark_node)
14003     return const0_rtx;
14004
14005   /* Check and prepare argument depending on the instruction code.
14006
14007      Note that a switch statement instead of the sequence of tests
14008      would be incorrect as many of the CODE_FOR values could be
14009      CODE_FOR_nothing and that would yield multiple alternatives
14010      with identical values.  We'd never reach here at runtime in
14011      this case.  */
14012   if (icode == CODE_FOR_altivec_vsldoi_v4sf
14013       || icode == CODE_FOR_altivec_vsldoi_v2df
14014       || icode == CODE_FOR_altivec_vsldoi_v4si
14015       || icode == CODE_FOR_altivec_vsldoi_v8hi
14016       || icode == CODE_FOR_altivec_vsldoi_v16qi)
14017     {
14018       /* Only allow 4-bit unsigned literals.  */
14019       STRIP_NOPS (arg2);
14020       if (TREE_CODE (arg2) != INTEGER_CST
14021           || TREE_INT_CST_LOW (arg2) & ~0xf)
14022         {
14023           error ("argument 3 must be a 4-bit unsigned literal");
14024           return CONST0_RTX (tmode);
14025         }
14026     }
14027   else if (icode == CODE_FOR_vsx_xxpermdi_v2df
14028            || icode == CODE_FOR_vsx_xxpermdi_v2di
14029            || icode == CODE_FOR_vsx_xxpermdi_v2df_be
14030            || icode == CODE_FOR_vsx_xxpermdi_v2di_be
14031            || icode == CODE_FOR_vsx_xxpermdi_v1ti
14032            || icode == CODE_FOR_vsx_xxpermdi_v4sf
14033            || icode == CODE_FOR_vsx_xxpermdi_v4si
14034            || icode == CODE_FOR_vsx_xxpermdi_v8hi
14035            || icode == CODE_FOR_vsx_xxpermdi_v16qi
14036            || icode == CODE_FOR_vsx_xxsldwi_v16qi
14037            || icode == CODE_FOR_vsx_xxsldwi_v8hi
14038            || icode == CODE_FOR_vsx_xxsldwi_v4si
14039            || icode == CODE_FOR_vsx_xxsldwi_v4sf
14040            || icode == CODE_FOR_vsx_xxsldwi_v2di
14041            || icode == CODE_FOR_vsx_xxsldwi_v2df)
14042     {
14043       /* Only allow 2-bit unsigned literals.  */
14044       STRIP_NOPS (arg2);
14045       if (TREE_CODE (arg2) != INTEGER_CST
14046           || TREE_INT_CST_LOW (arg2) & ~0x3)
14047         {
14048           error ("argument 3 must be a 2-bit unsigned literal");
14049           return CONST0_RTX (tmode);
14050         }
14051     }
14052   else if (icode == CODE_FOR_vsx_set_v2df
14053            || icode == CODE_FOR_vsx_set_v2di
14054            || icode == CODE_FOR_bcdadd
14055            || icode == CODE_FOR_bcdadd_lt
14056            || icode == CODE_FOR_bcdadd_eq
14057            || icode == CODE_FOR_bcdadd_gt
14058            || icode == CODE_FOR_bcdsub
14059            || icode == CODE_FOR_bcdsub_lt
14060            || icode == CODE_FOR_bcdsub_eq
14061            || icode == CODE_FOR_bcdsub_gt)
14062     {
14063       /* Only allow 1-bit unsigned literals.  */
14064       STRIP_NOPS (arg2);
14065       if (TREE_CODE (arg2) != INTEGER_CST
14066           || TREE_INT_CST_LOW (arg2) & ~0x1)
14067         {
14068           error ("argument 3 must be a 1-bit unsigned literal");
14069           return CONST0_RTX (tmode);
14070         }
14071     }
14072   else if (icode == CODE_FOR_dfp_ddedpd_dd
14073            || icode == CODE_FOR_dfp_ddedpd_td)
14074     {
14075       /* Only allow 2-bit unsigned literals where the value is 0 or 2.  */
14076       STRIP_NOPS (arg0);
14077       if (TREE_CODE (arg0) != INTEGER_CST
14078           || TREE_INT_CST_LOW (arg2) & ~0x3)
14079         {
14080           error ("argument 1 must be 0 or 2");
14081           return CONST0_RTX (tmode);
14082         }
14083     }
14084   else if (icode == CODE_FOR_dfp_denbcd_dd
14085            || icode == CODE_FOR_dfp_denbcd_td)
14086     {
14087       /* Only allow 1-bit unsigned literals.  */
14088       STRIP_NOPS (arg0);
14089       if (TREE_CODE (arg0) != INTEGER_CST
14090           || TREE_INT_CST_LOW (arg0) & ~0x1)
14091         {
14092           error ("argument 1 must be a 1-bit unsigned literal");
14093           return CONST0_RTX (tmode);
14094         }
14095     }
14096   else if (icode == CODE_FOR_dfp_dscli_dd
14097            || icode == CODE_FOR_dfp_dscli_td
14098            || icode == CODE_FOR_dfp_dscri_dd
14099            || icode == CODE_FOR_dfp_dscri_td)
14100     {
14101       /* Only allow 6-bit unsigned literals.  */
14102       STRIP_NOPS (arg1);
14103       if (TREE_CODE (arg1) != INTEGER_CST
14104           || TREE_INT_CST_LOW (arg1) & ~0x3f)
14105         {
14106           error ("argument 2 must be a 6-bit unsigned literal");
14107           return CONST0_RTX (tmode);
14108         }
14109     }
14110   else if (icode == CODE_FOR_crypto_vshasigmaw
14111            || icode == CODE_FOR_crypto_vshasigmad)
14112     {
14113       /* Check whether the 2nd and 3rd arguments are integer constants and in
14114          range and prepare arguments.  */
14115       STRIP_NOPS (arg1);
14116       if (TREE_CODE (arg1) != INTEGER_CST || wi::geu_p (wi::to_wide (arg1), 2))
14117         {
14118           error ("argument 2 must be 0 or 1");
14119           return CONST0_RTX (tmode);
14120         }
14121
14122       STRIP_NOPS (arg2);
14123       if (TREE_CODE (arg2) != INTEGER_CST
14124           || wi::geu_p (wi::to_wide (arg2), 16))
14125         {
14126           error ("argument 3 must be in the range [0, 15]");
14127           return CONST0_RTX (tmode);
14128         }
14129     }
14130
14131   if (target == 0
14132       || GET_MODE (target) != tmode
14133       || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
14134     target = gen_reg_rtx (tmode);
14135
14136   if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
14137     op0 = copy_to_mode_reg (mode0, op0);
14138   if (! (*insn_data[icode].operand[2].predicate) (op1, mode1))
14139     op1 = copy_to_mode_reg (mode1, op1);
14140   if (! (*insn_data[icode].operand[3].predicate) (op2, mode2))
14141     op2 = copy_to_mode_reg (mode2, op2);
14142
14143   pat = GEN_FCN (icode) (target, op0, op1, op2);
14144   if (! pat)
14145     return 0;
14146   emit_insn (pat);
14147
14148   return target;
14149 }
14150
14151
14152 /* Expand the dst builtins.  */
14153 static rtx
14154 altivec_expand_dst_builtin (tree exp, rtx target ATTRIBUTE_UNUSED,
14155                             bool *expandedp)
14156 {
14157   tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
14158   enum rs6000_builtins fcode = (enum rs6000_builtins) DECL_FUNCTION_CODE (fndecl);
14159   tree arg0, arg1, arg2;
14160   machine_mode mode0, mode1;
14161   rtx pat, op0, op1, op2;
14162   const struct builtin_description *d;
14163   size_t i;
14164
14165   *expandedp = false;
14166
14167   /* Handle DST variants.  */
14168   d = bdesc_dst;
14169   for (i = 0; i < ARRAY_SIZE (bdesc_dst); i++, d++)
14170     if (d->code == fcode)
14171       {
14172         arg0 = CALL_EXPR_ARG (exp, 0);
14173         arg1 = CALL_EXPR_ARG (exp, 1);
14174         arg2 = CALL_EXPR_ARG (exp, 2);
14175         op0 = expand_normal (arg0);
14176         op1 = expand_normal (arg1);
14177         op2 = expand_normal (arg2);
14178         mode0 = insn_data[d->icode].operand[0].mode;
14179         mode1 = insn_data[d->icode].operand[1].mode;
14180
14181         /* Invalid arguments, bail out before generating bad rtl.  */
14182         if (arg0 == error_mark_node
14183             || arg1 == error_mark_node
14184             || arg2 == error_mark_node)
14185           return const0_rtx;
14186
14187         *expandedp = true;
14188         STRIP_NOPS (arg2);
14189         if (TREE_CODE (arg2) != INTEGER_CST
14190             || TREE_INT_CST_LOW (arg2) & ~0x3)
14191           {
14192             error ("argument to %qs must be a 2-bit unsigned literal", d->name);
14193             return const0_rtx;
14194           }
14195
14196         if (! (*insn_data[d->icode].operand[0].predicate) (op0, mode0))
14197           op0 = copy_to_mode_reg (Pmode, op0);
14198         if (! (*insn_data[d->icode].operand[1].predicate) (op1, mode1))
14199           op1 = copy_to_mode_reg (mode1, op1);
14200
14201         pat = GEN_FCN (d->icode) (op0, op1, op2);
14202         if (pat != 0)
14203           emit_insn (pat);
14204
14205         return NULL_RTX;
14206       }
14207
14208   return NULL_RTX;
14209 }
14210
14211 /* Expand vec_init builtin.  */
14212 static rtx
14213 altivec_expand_vec_init_builtin (tree type, tree exp, rtx target)
14214 {
14215   machine_mode tmode = TYPE_MODE (type);
14216   machine_mode inner_mode = GET_MODE_INNER (tmode);
14217   int i, n_elt = GET_MODE_NUNITS (tmode);
14218
14219   gcc_assert (VECTOR_MODE_P (tmode));
14220   gcc_assert (n_elt == call_expr_nargs (exp));
14221
14222   if (!target || !register_operand (target, tmode))
14223     target = gen_reg_rtx (tmode);
14224
14225   /* If we have a vector compromised of a single element, such as V1TImode, do
14226      the initialization directly.  */
14227   if (n_elt == 1 && GET_MODE_SIZE (tmode) == GET_MODE_SIZE (inner_mode))
14228     {
14229       rtx x = expand_normal (CALL_EXPR_ARG (exp, 0));
14230       emit_move_insn (target, gen_lowpart (tmode, x));
14231     }
14232   else
14233     {
14234       rtvec v = rtvec_alloc (n_elt);
14235
14236       for (i = 0; i < n_elt; ++i)
14237         {
14238           rtx x = expand_normal (CALL_EXPR_ARG (exp, i));
14239           RTVEC_ELT (v, i) = gen_lowpart (inner_mode, x);
14240         }
14241
14242       rs6000_expand_vector_init (target, gen_rtx_PARALLEL (tmode, v));
14243     }
14244
14245   return target;
14246 }
14247
14248 /* Return the integer constant in ARG.  Constrain it to be in the range
14249    of the subparts of VEC_TYPE; issue an error if not.  */
14250
14251 static int
14252 get_element_number (tree vec_type, tree arg)
14253 {
14254   unsigned HOST_WIDE_INT elt, max = TYPE_VECTOR_SUBPARTS (vec_type) - 1;
14255
14256   if (!tree_fits_uhwi_p (arg)
14257       || (elt = tree_to_uhwi (arg), elt > max))
14258     {
14259       error ("selector must be an integer constant in the range [0, %wi]", max);
14260       return 0;
14261     }
14262
14263   return elt;
14264 }
14265
14266 /* Expand vec_set builtin.  */
14267 static rtx
14268 altivec_expand_vec_set_builtin (tree exp)
14269 {
14270   machine_mode tmode, mode1;
14271   tree arg0, arg1, arg2;
14272   int elt;
14273   rtx op0, op1;
14274
14275   arg0 = CALL_EXPR_ARG (exp, 0);
14276   arg1 = CALL_EXPR_ARG (exp, 1);
14277   arg2 = CALL_EXPR_ARG (exp, 2);
14278
14279   tmode = TYPE_MODE (TREE_TYPE (arg0));
14280   mode1 = TYPE_MODE (TREE_TYPE (TREE_TYPE (arg0)));
14281   gcc_assert (VECTOR_MODE_P (tmode));
14282
14283   op0 = expand_expr (arg0, NULL_RTX, tmode, EXPAND_NORMAL);
14284   op1 = expand_expr (arg1, NULL_RTX, mode1, EXPAND_NORMAL);
14285   elt = get_element_number (TREE_TYPE (arg0), arg2);
14286
14287   if (GET_MODE (op1) != mode1 && GET_MODE (op1) != VOIDmode)
14288     op1 = convert_modes (mode1, GET_MODE (op1), op1, true);
14289
14290   op0 = force_reg (tmode, op0);
14291   op1 = force_reg (mode1, op1);
14292
14293   rs6000_expand_vector_set (op0, op1, elt);
14294
14295   return op0;
14296 }
14297
14298 /* Expand vec_ext builtin.  */
14299 static rtx
14300 altivec_expand_vec_ext_builtin (tree exp, rtx target)
14301 {
14302   machine_mode tmode, mode0;
14303   tree arg0, arg1;
14304   rtx op0;
14305   rtx op1;
14306
14307   arg0 = CALL_EXPR_ARG (exp, 0);
14308   arg1 = CALL_EXPR_ARG (exp, 1);
14309
14310   op0 = expand_normal (arg0);
14311   op1 = expand_normal (arg1);
14312
14313   if (TREE_CODE (arg1) == INTEGER_CST)
14314     {
14315       unsigned HOST_WIDE_INT elt;
14316       unsigned HOST_WIDE_INT size = TYPE_VECTOR_SUBPARTS (TREE_TYPE (arg0));
14317       unsigned int truncated_selector;
14318       /* Even if !tree_fits_uhwi_p (arg1)), TREE_INT_CST_LOW (arg0)
14319          returns low-order bits of INTEGER_CST for modulo indexing.  */
14320       elt = TREE_INT_CST_LOW (arg1);
14321       truncated_selector = elt % size;
14322       op1 = GEN_INT (truncated_selector);
14323     }
14324
14325   tmode = TYPE_MODE (TREE_TYPE (TREE_TYPE (arg0)));
14326   mode0 = TYPE_MODE (TREE_TYPE (arg0));
14327   gcc_assert (VECTOR_MODE_P (mode0));
14328
14329   op0 = force_reg (mode0, op0);
14330
14331   if (optimize || !target || !register_operand (target, tmode))
14332     target = gen_reg_rtx (tmode);
14333
14334   rs6000_expand_vector_extract (target, op0, op1);
14335
14336   return target;
14337 }
14338
14339 /* Expand the builtin in EXP and store the result in TARGET.  Store
14340    true in *EXPANDEDP if we found a builtin to expand.  */
14341 static rtx
14342 altivec_expand_builtin (tree exp, rtx target, bool *expandedp)
14343 {
14344   const struct builtin_description *d;
14345   size_t i;
14346   enum insn_code icode;
14347   tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
14348   tree arg0, arg1, arg2;
14349   rtx op0, pat;
14350   machine_mode tmode, mode0;
14351   enum rs6000_builtins fcode
14352     = (enum rs6000_builtins) DECL_FUNCTION_CODE (fndecl);
14353
14354   if (rs6000_overloaded_builtin_p (fcode))
14355     {
14356       *expandedp = true;
14357       error ("unresolved overload for Altivec builtin %qF", fndecl);
14358
14359       /* Given it is invalid, just generate a normal call.  */
14360       return expand_call (exp, target, false);
14361     }
14362
14363   target = altivec_expand_dst_builtin (exp, target, expandedp);
14364   if (*expandedp)
14365     return target;
14366
14367   *expandedp = true;
14368
14369   switch (fcode)
14370     {
14371     case ALTIVEC_BUILTIN_STVX_V2DF:
14372       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvx_v2df, exp);
14373     case ALTIVEC_BUILTIN_STVX_V2DI:
14374       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvx_v2di, exp);
14375     case ALTIVEC_BUILTIN_STVX_V4SF:
14376       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvx_v4sf, exp);
14377     case ALTIVEC_BUILTIN_STVX:
14378     case ALTIVEC_BUILTIN_STVX_V4SI:
14379       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvx_v4si, exp);
14380     case ALTIVEC_BUILTIN_STVX_V8HI:
14381       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvx_v8hi, exp);
14382     case ALTIVEC_BUILTIN_STVX_V16QI:
14383       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvx_v16qi, exp);
14384     case ALTIVEC_BUILTIN_STVEBX:
14385       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvebx, exp);
14386     case ALTIVEC_BUILTIN_STVEHX:
14387       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvehx, exp);
14388     case ALTIVEC_BUILTIN_STVEWX:
14389       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvewx, exp);
14390     case ALTIVEC_BUILTIN_STVXL_V2DF:
14391       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvxl_v2df, exp);
14392     case ALTIVEC_BUILTIN_STVXL_V2DI:
14393       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvxl_v2di, exp);
14394     case ALTIVEC_BUILTIN_STVXL_V4SF:
14395       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvxl_v4sf, exp);
14396     case ALTIVEC_BUILTIN_STVXL:
14397     case ALTIVEC_BUILTIN_STVXL_V4SI:
14398       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvxl_v4si, exp);
14399     case ALTIVEC_BUILTIN_STVXL_V8HI:
14400       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvxl_v8hi, exp);
14401     case ALTIVEC_BUILTIN_STVXL_V16QI:
14402       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvxl_v16qi, exp);
14403
14404     case ALTIVEC_BUILTIN_STVLX:
14405       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvlx, exp);
14406     case ALTIVEC_BUILTIN_STVLXL:
14407       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvlxl, exp);
14408     case ALTIVEC_BUILTIN_STVRX:
14409       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvrx, exp);
14410     case ALTIVEC_BUILTIN_STVRXL:
14411       return altivec_expand_stv_builtin (CODE_FOR_altivec_stvrxl, exp);
14412
14413     case P9V_BUILTIN_STXVL:
14414       return altivec_expand_stxvl_builtin (CODE_FOR_stxvl, exp);
14415
14416     case P9V_BUILTIN_XST_LEN_R:
14417       return altivec_expand_stxvl_builtin (CODE_FOR_xst_len_r, exp);
14418
14419     case VSX_BUILTIN_STXVD2X_V1TI:
14420       return altivec_expand_stv_builtin (CODE_FOR_vsx_store_v1ti, exp);
14421     case VSX_BUILTIN_STXVD2X_V2DF:
14422       return altivec_expand_stv_builtin (CODE_FOR_vsx_store_v2df, exp);
14423     case VSX_BUILTIN_STXVD2X_V2DI:
14424       return altivec_expand_stv_builtin (CODE_FOR_vsx_store_v2di, exp);
14425     case VSX_BUILTIN_STXVW4X_V4SF:
14426       return altivec_expand_stv_builtin (CODE_FOR_vsx_store_v4sf, exp);
14427     case VSX_BUILTIN_STXVW4X_V4SI:
14428       return altivec_expand_stv_builtin (CODE_FOR_vsx_store_v4si, exp);
14429     case VSX_BUILTIN_STXVW4X_V8HI:
14430       return altivec_expand_stv_builtin (CODE_FOR_vsx_store_v8hi, exp);
14431     case VSX_BUILTIN_STXVW4X_V16QI:
14432       return altivec_expand_stv_builtin (CODE_FOR_vsx_store_v16qi, exp);
14433
14434     /* For the following on big endian, it's ok to use any appropriate
14435        unaligned-supporting store, so use a generic expander.  For
14436        little-endian, the exact element-reversing instruction must
14437        be used.  */
14438    case VSX_BUILTIN_ST_ELEMREV_V1TI:
14439      {
14440         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_store_v1ti
14441                                : CODE_FOR_vsx_st_elemrev_v1ti);
14442         return altivec_expand_stv_builtin (code, exp);
14443       }
14444     case VSX_BUILTIN_ST_ELEMREV_V2DF:
14445       {
14446         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_store_v2df
14447                                : CODE_FOR_vsx_st_elemrev_v2df);
14448         return altivec_expand_stv_builtin (code, exp);
14449       }
14450     case VSX_BUILTIN_ST_ELEMREV_V2DI:
14451       {
14452         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_store_v2di
14453                                : CODE_FOR_vsx_st_elemrev_v2di);
14454         return altivec_expand_stv_builtin (code, exp);
14455       }
14456     case VSX_BUILTIN_ST_ELEMREV_V4SF:
14457       {
14458         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_store_v4sf
14459                                : CODE_FOR_vsx_st_elemrev_v4sf);
14460         return altivec_expand_stv_builtin (code, exp);
14461       }
14462     case VSX_BUILTIN_ST_ELEMREV_V4SI:
14463       {
14464         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_store_v4si
14465                                : CODE_FOR_vsx_st_elemrev_v4si);
14466         return altivec_expand_stv_builtin (code, exp);
14467       }
14468     case VSX_BUILTIN_ST_ELEMREV_V8HI:
14469       {
14470         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_store_v8hi
14471                                : CODE_FOR_vsx_st_elemrev_v8hi);
14472         return altivec_expand_stv_builtin (code, exp);
14473       }
14474     case VSX_BUILTIN_ST_ELEMREV_V16QI:
14475       {
14476         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_store_v16qi
14477                                : CODE_FOR_vsx_st_elemrev_v16qi);
14478         return altivec_expand_stv_builtin (code, exp);
14479       }
14480
14481     case ALTIVEC_BUILTIN_MFVSCR:
14482       icode = CODE_FOR_altivec_mfvscr;
14483       tmode = insn_data[icode].operand[0].mode;
14484
14485       if (target == 0
14486           || GET_MODE (target) != tmode
14487           || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
14488         target = gen_reg_rtx (tmode);
14489
14490       pat = GEN_FCN (icode) (target);
14491       if (! pat)
14492         return 0;
14493       emit_insn (pat);
14494       return target;
14495
14496     case ALTIVEC_BUILTIN_MTVSCR:
14497       icode = CODE_FOR_altivec_mtvscr;
14498       arg0 = CALL_EXPR_ARG (exp, 0);
14499       op0 = expand_normal (arg0);
14500       mode0 = insn_data[icode].operand[0].mode;
14501
14502       /* If we got invalid arguments bail out before generating bad rtl.  */
14503       if (arg0 == error_mark_node)
14504         return const0_rtx;
14505
14506       if (! (*insn_data[icode].operand[0].predicate) (op0, mode0))
14507         op0 = copy_to_mode_reg (mode0, op0);
14508
14509       pat = GEN_FCN (icode) (op0);
14510       if (pat)
14511         emit_insn (pat);
14512       return NULL_RTX;
14513
14514     case ALTIVEC_BUILTIN_DSSALL:
14515       emit_insn (gen_altivec_dssall ());
14516       return NULL_RTX;
14517
14518     case ALTIVEC_BUILTIN_DSS:
14519       icode = CODE_FOR_altivec_dss;
14520       arg0 = CALL_EXPR_ARG (exp, 0);
14521       STRIP_NOPS (arg0);
14522       op0 = expand_normal (arg0);
14523       mode0 = insn_data[icode].operand[0].mode;
14524
14525       /* If we got invalid arguments bail out before generating bad rtl.  */
14526       if (arg0 == error_mark_node)
14527         return const0_rtx;
14528
14529       if (TREE_CODE (arg0) != INTEGER_CST
14530           || TREE_INT_CST_LOW (arg0) & ~0x3)
14531         {
14532           error ("argument to %qs must be a 2-bit unsigned literal", "dss");
14533           return const0_rtx;
14534         }
14535
14536       if (! (*insn_data[icode].operand[0].predicate) (op0, mode0))
14537         op0 = copy_to_mode_reg (mode0, op0);
14538
14539       emit_insn (gen_altivec_dss (op0));
14540       return NULL_RTX;
14541
14542     case ALTIVEC_BUILTIN_VEC_INIT_V4SI:
14543     case ALTIVEC_BUILTIN_VEC_INIT_V8HI:
14544     case ALTIVEC_BUILTIN_VEC_INIT_V16QI:
14545     case ALTIVEC_BUILTIN_VEC_INIT_V4SF:
14546     case VSX_BUILTIN_VEC_INIT_V2DF:
14547     case VSX_BUILTIN_VEC_INIT_V2DI:
14548     case VSX_BUILTIN_VEC_INIT_V1TI:
14549       return altivec_expand_vec_init_builtin (TREE_TYPE (exp), exp, target);
14550
14551     case ALTIVEC_BUILTIN_VEC_SET_V4SI:
14552     case ALTIVEC_BUILTIN_VEC_SET_V8HI:
14553     case ALTIVEC_BUILTIN_VEC_SET_V16QI:
14554     case ALTIVEC_BUILTIN_VEC_SET_V4SF:
14555     case VSX_BUILTIN_VEC_SET_V2DF:
14556     case VSX_BUILTIN_VEC_SET_V2DI:
14557     case VSX_BUILTIN_VEC_SET_V1TI:
14558       return altivec_expand_vec_set_builtin (exp);
14559
14560     case ALTIVEC_BUILTIN_VEC_EXT_V4SI:
14561     case ALTIVEC_BUILTIN_VEC_EXT_V8HI:
14562     case ALTIVEC_BUILTIN_VEC_EXT_V16QI:
14563     case ALTIVEC_BUILTIN_VEC_EXT_V4SF:
14564     case VSX_BUILTIN_VEC_EXT_V2DF:
14565     case VSX_BUILTIN_VEC_EXT_V2DI:
14566     case VSX_BUILTIN_VEC_EXT_V1TI:
14567       return altivec_expand_vec_ext_builtin (exp, target);
14568
14569     case P9V_BUILTIN_VEC_EXTRACT4B:
14570       arg1 = CALL_EXPR_ARG (exp, 1);
14571       STRIP_NOPS (arg1);
14572
14573       /* Generate a normal call if it is invalid.  */
14574       if (arg1 == error_mark_node)
14575         return expand_call (exp, target, false);
14576
14577       if (TREE_CODE (arg1) != INTEGER_CST || TREE_INT_CST_LOW (arg1) > 12)
14578         {
14579           error ("second argument to %qs must be [0, 12]", "vec_vextract4b");
14580           return expand_call (exp, target, false);
14581         }
14582       break;
14583
14584     case P9V_BUILTIN_VEC_INSERT4B:
14585       arg2 = CALL_EXPR_ARG (exp, 2);
14586       STRIP_NOPS (arg2);
14587
14588       /* Generate a normal call if it is invalid.  */
14589       if (arg2 == error_mark_node)
14590         return expand_call (exp, target, false);
14591
14592       if (TREE_CODE (arg2) != INTEGER_CST || TREE_INT_CST_LOW (arg2) > 12)
14593         {
14594           error ("third argument to %qs must be [0, 12]", "vec_vinsert4b");
14595           return expand_call (exp, target, false);
14596         }
14597       break;
14598
14599     default:
14600       break;
14601       /* Fall through.  */
14602     }
14603
14604   /* Expand abs* operations.  */
14605   d = bdesc_abs;
14606   for (i = 0; i < ARRAY_SIZE (bdesc_abs); i++, d++)
14607     if (d->code == fcode)
14608       return altivec_expand_abs_builtin (d->icode, exp, target);
14609
14610   /* Expand the AltiVec predicates.  */
14611   d = bdesc_altivec_preds;
14612   for (i = 0; i < ARRAY_SIZE (bdesc_altivec_preds); i++, d++)
14613     if (d->code == fcode)
14614       return altivec_expand_predicate_builtin (d->icode, exp, target);
14615
14616   /* LV* are funky.  We initialized them differently.  */
14617   switch (fcode)
14618     {
14619     case ALTIVEC_BUILTIN_LVSL:
14620       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvsl,
14621                                         exp, target, false);
14622     case ALTIVEC_BUILTIN_LVSR:
14623       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvsr,
14624                                         exp, target, false);
14625     case ALTIVEC_BUILTIN_LVEBX:
14626       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvebx,
14627                                         exp, target, false);
14628     case ALTIVEC_BUILTIN_LVEHX:
14629       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvehx,
14630                                         exp, target, false);
14631     case ALTIVEC_BUILTIN_LVEWX:
14632       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvewx,
14633                                         exp, target, false);
14634     case ALTIVEC_BUILTIN_LVXL_V2DF:
14635       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvxl_v2df,
14636                                         exp, target, false);
14637     case ALTIVEC_BUILTIN_LVXL_V2DI:
14638       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvxl_v2di,
14639                                         exp, target, false);
14640     case ALTIVEC_BUILTIN_LVXL_V4SF:
14641       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvxl_v4sf,
14642                                         exp, target, false);
14643     case ALTIVEC_BUILTIN_LVXL:
14644     case ALTIVEC_BUILTIN_LVXL_V4SI:
14645       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvxl_v4si,
14646                                         exp, target, false);
14647     case ALTIVEC_BUILTIN_LVXL_V8HI:
14648       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvxl_v8hi,
14649                                         exp, target, false);
14650     case ALTIVEC_BUILTIN_LVXL_V16QI:
14651       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvxl_v16qi,
14652                                         exp, target, false);
14653     case ALTIVEC_BUILTIN_LVX_V1TI:
14654       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvx_v1ti,
14655                                         exp, target, false);
14656     case ALTIVEC_BUILTIN_LVX_V2DF:
14657       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvx_v2df,
14658                                         exp, target, false);
14659     case ALTIVEC_BUILTIN_LVX_V2DI:
14660       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvx_v2di,
14661                                         exp, target, false);
14662     case ALTIVEC_BUILTIN_LVX_V4SF:
14663       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvx_v4sf,
14664                                         exp, target, false);
14665     case ALTIVEC_BUILTIN_LVX:
14666     case ALTIVEC_BUILTIN_LVX_V4SI:
14667       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvx_v4si,
14668                                         exp, target, false);
14669     case ALTIVEC_BUILTIN_LVX_V8HI:
14670       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvx_v8hi,
14671                                         exp, target, false);
14672     case ALTIVEC_BUILTIN_LVX_V16QI:
14673       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvx_v16qi,
14674                                         exp, target, false);
14675     case ALTIVEC_BUILTIN_LVLX:
14676       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvlx,
14677                                         exp, target, true);
14678     case ALTIVEC_BUILTIN_LVLXL:
14679       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvlxl,
14680                                         exp, target, true);
14681     case ALTIVEC_BUILTIN_LVRX:
14682       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvrx,
14683                                         exp, target, true);
14684     case ALTIVEC_BUILTIN_LVRXL:
14685       return altivec_expand_lv_builtin (CODE_FOR_altivec_lvrxl,
14686                                         exp, target, true);
14687     case VSX_BUILTIN_LXVD2X_V1TI:
14688       return altivec_expand_lv_builtin (CODE_FOR_vsx_load_v1ti,
14689                                         exp, target, false);
14690     case VSX_BUILTIN_LXVD2X_V2DF:
14691       return altivec_expand_lv_builtin (CODE_FOR_vsx_load_v2df,
14692                                         exp, target, false);
14693     case VSX_BUILTIN_LXVD2X_V2DI:
14694       return altivec_expand_lv_builtin (CODE_FOR_vsx_load_v2di,
14695                                         exp, target, false);
14696     case VSX_BUILTIN_LXVW4X_V4SF:
14697       return altivec_expand_lv_builtin (CODE_FOR_vsx_load_v4sf,
14698                                         exp, target, false);
14699     case VSX_BUILTIN_LXVW4X_V4SI:
14700       return altivec_expand_lv_builtin (CODE_FOR_vsx_load_v4si,
14701                                         exp, target, false);
14702     case VSX_BUILTIN_LXVW4X_V8HI:
14703       return altivec_expand_lv_builtin (CODE_FOR_vsx_load_v8hi,
14704                                         exp, target, false);
14705     case VSX_BUILTIN_LXVW4X_V16QI:
14706       return altivec_expand_lv_builtin (CODE_FOR_vsx_load_v16qi,
14707                                         exp, target, false);
14708     /* For the following on big endian, it's ok to use any appropriate
14709        unaligned-supporting load, so use a generic expander.  For
14710        little-endian, the exact element-reversing instruction must
14711        be used.  */
14712     case VSX_BUILTIN_LD_ELEMREV_V2DF:
14713       {
14714         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_load_v2df
14715                                : CODE_FOR_vsx_ld_elemrev_v2df);
14716         return altivec_expand_lv_builtin (code, exp, target, false);
14717       }
14718     case VSX_BUILTIN_LD_ELEMREV_V1TI:
14719       {
14720         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_load_v1ti
14721                                : CODE_FOR_vsx_ld_elemrev_v1ti);
14722         return altivec_expand_lv_builtin (code, exp, target, false);
14723       }
14724     case VSX_BUILTIN_LD_ELEMREV_V2DI:
14725       {
14726         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_load_v2di
14727                                : CODE_FOR_vsx_ld_elemrev_v2di);
14728         return altivec_expand_lv_builtin (code, exp, target, false);
14729       }
14730     case VSX_BUILTIN_LD_ELEMREV_V4SF:
14731       {
14732         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_load_v4sf
14733                                : CODE_FOR_vsx_ld_elemrev_v4sf);
14734         return altivec_expand_lv_builtin (code, exp, target, false);
14735       }
14736     case VSX_BUILTIN_LD_ELEMREV_V4SI:
14737       {
14738         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_load_v4si
14739                                : CODE_FOR_vsx_ld_elemrev_v4si);
14740         return altivec_expand_lv_builtin (code, exp, target, false);
14741       }
14742     case VSX_BUILTIN_LD_ELEMREV_V8HI:
14743       {
14744         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_load_v8hi
14745                                : CODE_FOR_vsx_ld_elemrev_v8hi);
14746         return altivec_expand_lv_builtin (code, exp, target, false);
14747       }
14748     case VSX_BUILTIN_LD_ELEMREV_V16QI:
14749       {
14750         enum insn_code code = (BYTES_BIG_ENDIAN ? CODE_FOR_vsx_load_v16qi
14751                                : CODE_FOR_vsx_ld_elemrev_v16qi);
14752         return altivec_expand_lv_builtin (code, exp, target, false);
14753       }
14754       break;
14755     default:
14756       break;
14757       /* Fall through.  */
14758     }
14759
14760   *expandedp = false;
14761   return NULL_RTX;
14762 }
14763
14764 /* Check whether a builtin function is supported in this target
14765    configuration.  */
14766 bool
14767 rs6000_builtin_is_supported_p (enum rs6000_builtins fncode)
14768 {
14769   HOST_WIDE_INT fnmask = rs6000_builtin_info[fncode].mask;
14770   if ((fnmask & rs6000_builtin_mask) != fnmask)
14771     return false;
14772   else
14773     return true;
14774 }
14775
14776 /* Raise an error message for a builtin function that is called without the
14777    appropriate target options being set.  */
14778
14779 static void
14780 rs6000_invalid_builtin (enum rs6000_builtins fncode)
14781 {
14782   size_t uns_fncode = (size_t) fncode;
14783   const char *name = rs6000_builtin_info[uns_fncode].name;
14784   HOST_WIDE_INT fnmask = rs6000_builtin_info[uns_fncode].mask;
14785
14786   gcc_assert (name != NULL);
14787   if ((fnmask & RS6000_BTM_CELL) != 0)
14788     error ("%qs is only valid for the cell processor", name);
14789   else if ((fnmask & RS6000_BTM_VSX) != 0)
14790     error ("%qs requires the %qs option", name, "-mvsx");
14791   else if ((fnmask & RS6000_BTM_HTM) != 0)
14792     error ("%qs requires the %qs option", name, "-mhtm");
14793   else if ((fnmask & RS6000_BTM_ALTIVEC) != 0)
14794     error ("%qs requires the %qs option", name, "-maltivec");
14795   else if ((fnmask & (RS6000_BTM_DFP | RS6000_BTM_P8_VECTOR))
14796            == (RS6000_BTM_DFP | RS6000_BTM_P8_VECTOR))
14797     error ("%qs requires the %qs and %qs options", name, "-mhard-dfp",
14798            "-mpower8-vector");
14799   else if ((fnmask & RS6000_BTM_DFP) != 0)
14800     error ("%qs requires the %qs option", name, "-mhard-dfp");
14801   else if ((fnmask & RS6000_BTM_P8_VECTOR) != 0)
14802     error ("%qs requires the %qs option", name, "-mpower8-vector");
14803   else if ((fnmask & (RS6000_BTM_P9_VECTOR | RS6000_BTM_64BIT))
14804            == (RS6000_BTM_P9_VECTOR | RS6000_BTM_64BIT))
14805     error ("%qs requires the %qs and %qs options", name, "-mcpu=power9",
14806            "-m64");
14807   else if ((fnmask & RS6000_BTM_P9_VECTOR) != 0)
14808     error ("%qs requires the %qs option", name, "-mcpu=power9");
14809   else if ((fnmask & (RS6000_BTM_P9_MISC | RS6000_BTM_64BIT))
14810            == (RS6000_BTM_P9_MISC | RS6000_BTM_64BIT))
14811     error ("%qs requires the %qs and %qs options", name, "-mcpu=power9",
14812            "-m64");
14813   else if ((fnmask & RS6000_BTM_P9_MISC) == RS6000_BTM_P9_MISC)
14814     error ("%qs requires the %qs option", name, "-mcpu=power9");
14815   else if ((fnmask & RS6000_BTM_LDBL128) == RS6000_BTM_LDBL128)
14816     {
14817       if (!TARGET_HARD_FLOAT)
14818         error ("%qs requires the %qs option", name, "-mhard-float");
14819       else
14820         error ("%qs requires the %qs option", name,
14821                TARGET_IEEEQUAD ? "-mabi=ibmlongdouble" : "-mlong-double-128");
14822     }
14823   else if ((fnmask & RS6000_BTM_HARD_FLOAT) != 0)
14824     error ("%qs requires the %qs option", name, "-mhard-float");
14825   else if ((fnmask & RS6000_BTM_FLOAT128_HW) != 0)
14826     error ("%qs requires ISA 3.0 IEEE 128-bit floating point", name);
14827   else if ((fnmask & RS6000_BTM_FLOAT128) != 0)
14828     error ("%qs requires the %qs option", name, "%<-mfloat128%>");
14829   else if ((fnmask & (RS6000_BTM_POPCNTD | RS6000_BTM_POWERPC64))
14830            == (RS6000_BTM_POPCNTD | RS6000_BTM_POWERPC64))
14831     error ("%qs requires the %qs (or newer), and %qs or %qs options",
14832            name, "-mcpu=power7", "-m64", "-mpowerpc64");
14833   else
14834     error ("%qs is not supported with the current options", name);
14835 }
14836
14837 /* Target hook for early folding of built-ins, shamelessly stolen
14838    from ia64.c.  */
14839
14840 static tree
14841 rs6000_fold_builtin (tree fndecl ATTRIBUTE_UNUSED,
14842                      int n_args ATTRIBUTE_UNUSED,
14843                      tree *args ATTRIBUTE_UNUSED,
14844                      bool ignore ATTRIBUTE_UNUSED)
14845 {
14846 #ifdef SUBTARGET_FOLD_BUILTIN
14847   return SUBTARGET_FOLD_BUILTIN (fndecl, n_args, args, ignore);
14848 #else
14849   return NULL_TREE;
14850 #endif
14851 }
14852
14853 /*  Helper function to sort out which built-ins may be valid without having
14854     a LHS.  */
14855 static bool
14856 rs6000_builtin_valid_without_lhs (enum rs6000_builtins fn_code)
14857 {
14858   switch (fn_code)
14859     {
14860     case ALTIVEC_BUILTIN_STVX_V16QI:
14861     case ALTIVEC_BUILTIN_STVX_V8HI:
14862     case ALTIVEC_BUILTIN_STVX_V4SI:
14863     case ALTIVEC_BUILTIN_STVX_V4SF:
14864     case ALTIVEC_BUILTIN_STVX_V2DI:
14865     case ALTIVEC_BUILTIN_STVX_V2DF:
14866     case VSX_BUILTIN_STXVW4X_V16QI:
14867     case VSX_BUILTIN_STXVW4X_V8HI:
14868     case VSX_BUILTIN_STXVW4X_V4SF:
14869     case VSX_BUILTIN_STXVW4X_V4SI:
14870     case VSX_BUILTIN_STXVD2X_V2DF:
14871     case VSX_BUILTIN_STXVD2X_V2DI:
14872       return true;
14873     default:
14874       return false;
14875     }
14876 }
14877
14878 /* Helper function to handle the gimple folding of a vector compare
14879    operation.  This sets up true/false vectors, and uses the
14880    VEC_COND_EXPR operation.
14881    CODE indicates which comparison is to be made. (EQ, GT, ...).
14882    TYPE indicates the type of the result.  */
14883 static tree
14884 fold_build_vec_cmp (tree_code code, tree type,
14885                     tree arg0, tree arg1)
14886 {
14887   tree cmp_type = build_same_sized_truth_vector_type (type);
14888   tree zero_vec = build_zero_cst (type);
14889   tree minus_one_vec = build_minus_one_cst (type);
14890   tree cmp = fold_build2 (code, cmp_type, arg0, arg1);
14891   return fold_build3 (VEC_COND_EXPR, type, cmp, minus_one_vec, zero_vec);
14892 }
14893
14894 /* Helper function to handle the in-between steps for the
14895    vector compare built-ins.  */
14896 static void
14897 fold_compare_helper (gimple_stmt_iterator *gsi, tree_code code, gimple *stmt)
14898 {
14899   tree arg0 = gimple_call_arg (stmt, 0);
14900   tree arg1 = gimple_call_arg (stmt, 1);
14901   tree lhs = gimple_call_lhs (stmt);
14902   tree cmp = fold_build_vec_cmp (code, TREE_TYPE (lhs), arg0, arg1);
14903   gimple *g = gimple_build_assign (lhs, cmp);
14904   gimple_set_location (g, gimple_location (stmt));
14905   gsi_replace (gsi, g, true);
14906 }
14907
14908 /* Helper function to map V2DF and V4SF types to their
14909  integral equivalents (V2DI and V4SI).  */
14910 tree map_to_integral_tree_type (tree input_tree_type)
14911 {
14912   if (INTEGRAL_TYPE_P (TREE_TYPE (input_tree_type)))
14913     return input_tree_type;
14914   else
14915     {
14916       if (types_compatible_p (TREE_TYPE (input_tree_type),
14917                               TREE_TYPE (V2DF_type_node)))
14918         return V2DI_type_node;
14919       else if (types_compatible_p (TREE_TYPE (input_tree_type),
14920                                    TREE_TYPE (V4SF_type_node)))
14921         return V4SI_type_node;
14922       else
14923         gcc_unreachable ();
14924     }
14925 }
14926
14927 /* Helper function to handle the vector merge[hl] built-ins.  The
14928    implementation difference between h and l versions for this code are in
14929    the values used when building of the permute vector for high word versus
14930    low word merge.  The variance is keyed off the use_high parameter.  */
14931 static void
14932 fold_mergehl_helper (gimple_stmt_iterator *gsi, gimple *stmt, int use_high)
14933 {
14934   tree arg0 = gimple_call_arg (stmt, 0);
14935   tree arg1 = gimple_call_arg (stmt, 1);
14936   tree lhs = gimple_call_lhs (stmt);
14937   tree lhs_type = TREE_TYPE (lhs);
14938   int n_elts = TYPE_VECTOR_SUBPARTS (lhs_type);
14939   int midpoint = n_elts / 2;
14940   int offset = 0;
14941
14942   if (use_high == 1)
14943     offset = midpoint;
14944
14945   /* The permute_type will match the lhs for integral types.  For double and
14946      float types, the permute type needs to map to the V2 or V4 type that
14947      matches size.  */
14948   tree permute_type;
14949   permute_type = map_to_integral_tree_type (lhs_type);
14950   tree_vector_builder elts (permute_type, VECTOR_CST_NELTS (arg0), 1);
14951
14952   for (int i = 0; i < midpoint; i++)
14953     {
14954       elts.safe_push (build_int_cst (TREE_TYPE (permute_type),
14955                                      offset + i));
14956       elts.safe_push (build_int_cst (TREE_TYPE (permute_type),
14957                                      offset + n_elts + i));
14958     }
14959
14960   tree permute = elts.build ();
14961
14962   gimple *g = gimple_build_assign (lhs, VEC_PERM_EXPR, arg0, arg1, permute);
14963   gimple_set_location (g, gimple_location (stmt));
14964   gsi_replace (gsi, g, true);
14965 }
14966
14967 /* Helper function to handle the vector merge[eo] built-ins.  */
14968 static void
14969 fold_mergeeo_helper (gimple_stmt_iterator *gsi, gimple *stmt, int use_odd)
14970 {
14971   tree arg0 = gimple_call_arg (stmt, 0);
14972   tree arg1 = gimple_call_arg (stmt, 1);
14973   tree lhs = gimple_call_lhs (stmt);
14974   tree lhs_type = TREE_TYPE (lhs);
14975   int n_elts = TYPE_VECTOR_SUBPARTS (lhs_type);
14976
14977   /* The permute_type will match the lhs for integral types.  For double and
14978      float types, the permute type needs to map to the V2 or V4 type that
14979      matches size.  */
14980   tree permute_type;
14981   permute_type = map_to_integral_tree_type (lhs_type);
14982
14983   tree_vector_builder elts (permute_type, VECTOR_CST_NELTS (arg0), 1);
14984
14985  /* Build the permute vector.  */
14986   for (int i = 0; i < n_elts / 2; i++)
14987     {
14988       elts.safe_push (build_int_cst (TREE_TYPE (permute_type),
14989                                      2*i + use_odd));
14990       elts.safe_push (build_int_cst (TREE_TYPE (permute_type),
14991                                      2*i + use_odd + n_elts));
14992     }
14993
14994   tree permute = elts.build ();
14995
14996   gimple *g = gimple_build_assign (lhs, VEC_PERM_EXPR, arg0, arg1, permute);
14997   gimple_set_location (g, gimple_location (stmt));
14998   gsi_replace (gsi, g, true);
14999 }
15000
15001 /* Fold a machine-dependent built-in in GIMPLE.  (For folding into
15002    a constant, use rs6000_fold_builtin.)  */
15003
15004 bool
15005 rs6000_gimple_fold_builtin (gimple_stmt_iterator *gsi)
15006 {
15007   gimple *stmt = gsi_stmt (*gsi);
15008   tree fndecl = gimple_call_fndecl (stmt);
15009   gcc_checking_assert (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD);
15010   enum rs6000_builtins fn_code
15011     = (enum rs6000_builtins) DECL_FUNCTION_CODE (fndecl);
15012   tree arg0, arg1, lhs, temp;
15013   enum tree_code bcode;
15014   gimple *g;
15015
15016   size_t uns_fncode = (size_t) fn_code;
15017   enum insn_code icode = rs6000_builtin_info[uns_fncode].icode;
15018   const char *fn_name1 = rs6000_builtin_info[uns_fncode].name;
15019   const char *fn_name2 = (icode != CODE_FOR_nothing)
15020                           ? get_insn_name ((int) icode)
15021                           : "nothing";
15022
15023   if (TARGET_DEBUG_BUILTIN)
15024       fprintf (stderr, "rs6000_gimple_fold_builtin %d %s %s\n",
15025                fn_code, fn_name1, fn_name2);
15026
15027   if (!rs6000_fold_gimple)
15028     return false;
15029
15030   /* Prevent gimple folding for code that does not have a LHS, unless it is
15031      allowed per the rs6000_builtin_valid_without_lhs helper function.  */
15032   if (!gimple_call_lhs (stmt) && !rs6000_builtin_valid_without_lhs (fn_code))
15033     return false;
15034
15035   /* Don't fold invalid builtins, let rs6000_expand_builtin diagnose it.  */
15036   HOST_WIDE_INT mask = rs6000_builtin_info[uns_fncode].mask;
15037   bool func_valid_p = (rs6000_builtin_mask & mask) == mask;
15038   if (!func_valid_p)
15039     return false;
15040
15041   switch (fn_code)
15042     {
15043     /* Flavors of vec_add.  We deliberately don't expand
15044        P8V_BUILTIN_VADDUQM as it gets lowered from V1TImode to
15045        TImode, resulting in much poorer code generation.  */
15046     case ALTIVEC_BUILTIN_VADDUBM:
15047     case ALTIVEC_BUILTIN_VADDUHM:
15048     case ALTIVEC_BUILTIN_VADDUWM:
15049     case P8V_BUILTIN_VADDUDM:
15050     case ALTIVEC_BUILTIN_VADDFP:
15051     case VSX_BUILTIN_XVADDDP:
15052       bcode = PLUS_EXPR;
15053     do_binary:
15054       arg0 = gimple_call_arg (stmt, 0);
15055       arg1 = gimple_call_arg (stmt, 1);
15056       lhs = gimple_call_lhs (stmt);
15057       if (INTEGRAL_TYPE_P (TREE_TYPE (TREE_TYPE (lhs)))
15058           && !TYPE_OVERFLOW_WRAPS (TREE_TYPE (TREE_TYPE (lhs))))
15059         {
15060           /* Ensure the binary operation is performed in a type
15061              that wraps if it is integral type.  */
15062           gimple_seq stmts = NULL;
15063           tree type = unsigned_type_for (TREE_TYPE (lhs));
15064           tree uarg0 = gimple_build (&stmts, VIEW_CONVERT_EXPR,
15065                                      type, arg0);
15066           tree uarg1 = gimple_build (&stmts, VIEW_CONVERT_EXPR,
15067                                      type, arg1);
15068           tree res = gimple_build (&stmts, gimple_location (stmt), bcode,
15069                                    type, uarg0, uarg1);
15070           gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
15071           g = gimple_build_assign (lhs, VIEW_CONVERT_EXPR,
15072                                    build1 (VIEW_CONVERT_EXPR,
15073                                            TREE_TYPE (lhs), res));
15074           gsi_replace (gsi, g, true);
15075           return true;
15076         }
15077       g = gimple_build_assign (lhs, bcode, arg0, arg1);
15078       gimple_set_location (g, gimple_location (stmt));
15079       gsi_replace (gsi, g, true);
15080       return true;
15081     /* Flavors of vec_sub.  We deliberately don't expand
15082        P8V_BUILTIN_VSUBUQM. */
15083     case ALTIVEC_BUILTIN_VSUBUBM:
15084     case ALTIVEC_BUILTIN_VSUBUHM:
15085     case ALTIVEC_BUILTIN_VSUBUWM:
15086     case P8V_BUILTIN_VSUBUDM:
15087     case ALTIVEC_BUILTIN_VSUBFP:
15088     case VSX_BUILTIN_XVSUBDP:
15089       bcode = MINUS_EXPR;
15090       goto do_binary;
15091     case VSX_BUILTIN_XVMULSP:
15092     case VSX_BUILTIN_XVMULDP:
15093       arg0 = gimple_call_arg (stmt, 0);
15094       arg1 = gimple_call_arg (stmt, 1);
15095       lhs = gimple_call_lhs (stmt);
15096       g = gimple_build_assign (lhs, MULT_EXPR, arg0, arg1);
15097       gimple_set_location (g, gimple_location (stmt));
15098       gsi_replace (gsi, g, true);
15099       return true;
15100     /* Even element flavors of vec_mul (signed). */
15101     case ALTIVEC_BUILTIN_VMULESB:
15102     case ALTIVEC_BUILTIN_VMULESH:
15103     case P8V_BUILTIN_VMULESW:
15104     /* Even element flavors of vec_mul (unsigned).  */
15105     case ALTIVEC_BUILTIN_VMULEUB:
15106     case ALTIVEC_BUILTIN_VMULEUH:
15107     case P8V_BUILTIN_VMULEUW:
15108       arg0 = gimple_call_arg (stmt, 0);
15109       arg1 = gimple_call_arg (stmt, 1);
15110       lhs = gimple_call_lhs (stmt);
15111       g = gimple_build_assign (lhs, VEC_WIDEN_MULT_EVEN_EXPR, arg0, arg1);
15112       gimple_set_location (g, gimple_location (stmt));
15113       gsi_replace (gsi, g, true);
15114       return true;
15115     /* Odd element flavors of vec_mul (signed).  */
15116     case ALTIVEC_BUILTIN_VMULOSB:
15117     case ALTIVEC_BUILTIN_VMULOSH:
15118     case P8V_BUILTIN_VMULOSW:
15119     /* Odd element flavors of vec_mul (unsigned). */
15120     case ALTIVEC_BUILTIN_VMULOUB:
15121     case ALTIVEC_BUILTIN_VMULOUH:
15122     case P8V_BUILTIN_VMULOUW:
15123       arg0 = gimple_call_arg (stmt, 0);
15124       arg1 = gimple_call_arg (stmt, 1);
15125       lhs = gimple_call_lhs (stmt);
15126       g = gimple_build_assign (lhs, VEC_WIDEN_MULT_ODD_EXPR, arg0, arg1);
15127       gimple_set_location (g, gimple_location (stmt));
15128       gsi_replace (gsi, g, true);
15129       return true;
15130     /* Flavors of vec_div (Integer).  */
15131     case VSX_BUILTIN_DIV_V2DI:
15132     case VSX_BUILTIN_UDIV_V2DI:
15133       arg0 = gimple_call_arg (stmt, 0);
15134       arg1 = gimple_call_arg (stmt, 1);
15135       lhs = gimple_call_lhs (stmt);
15136       g = gimple_build_assign (lhs, TRUNC_DIV_EXPR, arg0, arg1);
15137       gimple_set_location (g, gimple_location (stmt));
15138       gsi_replace (gsi, g, true);
15139       return true;
15140     /* Flavors of vec_div (Float).  */
15141     case VSX_BUILTIN_XVDIVSP:
15142     case VSX_BUILTIN_XVDIVDP:
15143       arg0 = gimple_call_arg (stmt, 0);
15144       arg1 = gimple_call_arg (stmt, 1);
15145       lhs = gimple_call_lhs (stmt);
15146       g = gimple_build_assign (lhs, RDIV_EXPR, arg0, arg1);
15147       gimple_set_location (g, gimple_location (stmt));
15148       gsi_replace (gsi, g, true);
15149       return true;
15150     /* Flavors of vec_and.  */
15151     case ALTIVEC_BUILTIN_VAND:
15152       arg0 = gimple_call_arg (stmt, 0);
15153       arg1 = gimple_call_arg (stmt, 1);
15154       lhs = gimple_call_lhs (stmt);
15155       g = gimple_build_assign (lhs, BIT_AND_EXPR, arg0, arg1);
15156       gimple_set_location (g, gimple_location (stmt));
15157       gsi_replace (gsi, g, true);
15158       return true;
15159     /* Flavors of vec_andc.  */
15160     case ALTIVEC_BUILTIN_VANDC:
15161       arg0 = gimple_call_arg (stmt, 0);
15162       arg1 = gimple_call_arg (stmt, 1);
15163       lhs = gimple_call_lhs (stmt);
15164       temp = create_tmp_reg_or_ssa_name (TREE_TYPE (arg1));
15165       g = gimple_build_assign (temp, BIT_NOT_EXPR, arg1);
15166       gimple_set_location (g, gimple_location (stmt));
15167       gsi_insert_before (gsi, g, GSI_SAME_STMT);
15168       g = gimple_build_assign (lhs, BIT_AND_EXPR, arg0, temp);
15169       gimple_set_location (g, gimple_location (stmt));
15170       gsi_replace (gsi, g, true);
15171       return true;
15172     /* Flavors of vec_nand.  */
15173     case P8V_BUILTIN_VEC_NAND:
15174     case P8V_BUILTIN_NAND_V16QI:
15175     case P8V_BUILTIN_NAND_V8HI:
15176     case P8V_BUILTIN_NAND_V4SI:
15177     case P8V_BUILTIN_NAND_V4SF:
15178     case P8V_BUILTIN_NAND_V2DF:
15179     case P8V_BUILTIN_NAND_V2DI:
15180       arg0 = gimple_call_arg (stmt, 0);
15181       arg1 = gimple_call_arg (stmt, 1);
15182       lhs = gimple_call_lhs (stmt);
15183       temp = create_tmp_reg_or_ssa_name (TREE_TYPE (arg1));
15184       g = gimple_build_assign (temp, BIT_AND_EXPR, arg0, arg1);
15185       gimple_set_location (g, gimple_location (stmt));
15186       gsi_insert_before (gsi, g, GSI_SAME_STMT);
15187       g = gimple_build_assign (lhs, BIT_NOT_EXPR, temp);
15188       gimple_set_location (g, gimple_location (stmt));
15189       gsi_replace (gsi, g, true);
15190       return true;
15191     /* Flavors of vec_or.  */
15192     case ALTIVEC_BUILTIN_VOR:
15193       arg0 = gimple_call_arg (stmt, 0);
15194       arg1 = gimple_call_arg (stmt, 1);
15195       lhs = gimple_call_lhs (stmt);
15196       g = gimple_build_assign (lhs, BIT_IOR_EXPR, arg0, arg1);
15197       gimple_set_location (g, gimple_location (stmt));
15198       gsi_replace (gsi, g, true);
15199       return true;
15200     /* flavors of vec_orc.  */
15201     case P8V_BUILTIN_ORC_V16QI:
15202     case P8V_BUILTIN_ORC_V8HI:
15203     case P8V_BUILTIN_ORC_V4SI:
15204     case P8V_BUILTIN_ORC_V4SF:
15205     case P8V_BUILTIN_ORC_V2DF:
15206     case P8V_BUILTIN_ORC_V2DI:
15207       arg0 = gimple_call_arg (stmt, 0);
15208       arg1 = gimple_call_arg (stmt, 1);
15209       lhs = gimple_call_lhs (stmt);
15210       temp = create_tmp_reg_or_ssa_name (TREE_TYPE (arg1));
15211       g = gimple_build_assign (temp, BIT_NOT_EXPR, arg1);
15212       gimple_set_location (g, gimple_location (stmt));
15213       gsi_insert_before (gsi, g, GSI_SAME_STMT);
15214       g = gimple_build_assign (lhs, BIT_IOR_EXPR, arg0, temp);
15215       gimple_set_location (g, gimple_location (stmt));
15216       gsi_replace (gsi, g, true);
15217       return true;
15218     /* Flavors of vec_xor.  */
15219     case ALTIVEC_BUILTIN_VXOR:
15220       arg0 = gimple_call_arg (stmt, 0);
15221       arg1 = gimple_call_arg (stmt, 1);
15222       lhs = gimple_call_lhs (stmt);
15223       g = gimple_build_assign (lhs, BIT_XOR_EXPR, arg0, arg1);
15224       gimple_set_location (g, gimple_location (stmt));
15225       gsi_replace (gsi, g, true);
15226       return true;
15227     /* Flavors of vec_nor.  */
15228     case ALTIVEC_BUILTIN_VNOR:
15229       arg0 = gimple_call_arg (stmt, 0);
15230       arg1 = gimple_call_arg (stmt, 1);
15231       lhs = gimple_call_lhs (stmt);
15232       temp = create_tmp_reg_or_ssa_name (TREE_TYPE (arg1));
15233       g = gimple_build_assign (temp, BIT_IOR_EXPR, arg0, arg1);
15234       gimple_set_location (g, gimple_location (stmt));
15235       gsi_insert_before (gsi, g, GSI_SAME_STMT);
15236       g = gimple_build_assign (lhs, BIT_NOT_EXPR, temp);
15237       gimple_set_location (g, gimple_location (stmt));
15238       gsi_replace (gsi, g, true);
15239       return true;
15240     /* flavors of vec_abs.  */
15241     case ALTIVEC_BUILTIN_ABS_V16QI:
15242     case ALTIVEC_BUILTIN_ABS_V8HI:
15243     case ALTIVEC_BUILTIN_ABS_V4SI:
15244     case ALTIVEC_BUILTIN_ABS_V4SF:
15245     case P8V_BUILTIN_ABS_V2DI:
15246     case VSX_BUILTIN_XVABSDP:
15247       arg0 = gimple_call_arg (stmt, 0);
15248       if (INTEGRAL_TYPE_P (TREE_TYPE (TREE_TYPE (arg0)))
15249           && !TYPE_OVERFLOW_WRAPS (TREE_TYPE (TREE_TYPE (arg0))))
15250         return false;
15251       lhs = gimple_call_lhs (stmt);
15252       g = gimple_build_assign (lhs, ABS_EXPR, arg0);
15253       gimple_set_location (g, gimple_location (stmt));
15254       gsi_replace (gsi, g, true);
15255       return true;
15256     /* flavors of vec_min.  */
15257     case VSX_BUILTIN_XVMINDP:
15258     case P8V_BUILTIN_VMINSD:
15259     case P8V_BUILTIN_VMINUD:
15260     case ALTIVEC_BUILTIN_VMINSB:
15261     case ALTIVEC_BUILTIN_VMINSH:
15262     case ALTIVEC_BUILTIN_VMINSW:
15263     case ALTIVEC_BUILTIN_VMINUB:
15264     case ALTIVEC_BUILTIN_VMINUH:
15265     case ALTIVEC_BUILTIN_VMINUW:
15266     case ALTIVEC_BUILTIN_VMINFP:
15267       arg0 = gimple_call_arg (stmt, 0);
15268       arg1 = gimple_call_arg (stmt, 1);
15269       lhs = gimple_call_lhs (stmt);
15270       g = gimple_build_assign (lhs, MIN_EXPR, arg0, arg1);
15271       gimple_set_location (g, gimple_location (stmt));
15272       gsi_replace (gsi, g, true);
15273       return true;
15274     /* flavors of vec_max.  */
15275     case VSX_BUILTIN_XVMAXDP:
15276     case P8V_BUILTIN_VMAXSD:
15277     case P8V_BUILTIN_VMAXUD:
15278     case ALTIVEC_BUILTIN_VMAXSB:
15279     case ALTIVEC_BUILTIN_VMAXSH:
15280     case ALTIVEC_BUILTIN_VMAXSW:
15281     case ALTIVEC_BUILTIN_VMAXUB:
15282     case ALTIVEC_BUILTIN_VMAXUH:
15283     case ALTIVEC_BUILTIN_VMAXUW:
15284     case ALTIVEC_BUILTIN_VMAXFP:
15285       arg0 = gimple_call_arg (stmt, 0);
15286       arg1 = gimple_call_arg (stmt, 1);
15287       lhs = gimple_call_lhs (stmt);
15288       g = gimple_build_assign (lhs, MAX_EXPR, arg0, arg1);
15289       gimple_set_location (g, gimple_location (stmt));
15290       gsi_replace (gsi, g, true);
15291       return true;
15292     /* Flavors of vec_eqv.  */
15293     case P8V_BUILTIN_EQV_V16QI:
15294     case P8V_BUILTIN_EQV_V8HI:
15295     case P8V_BUILTIN_EQV_V4SI:
15296     case P8V_BUILTIN_EQV_V4SF:
15297     case P8V_BUILTIN_EQV_V2DF:
15298     case P8V_BUILTIN_EQV_V2DI:
15299       arg0 = gimple_call_arg (stmt, 0);
15300       arg1 = gimple_call_arg (stmt, 1);
15301       lhs = gimple_call_lhs (stmt);
15302       temp = create_tmp_reg_or_ssa_name (TREE_TYPE (arg1));
15303       g = gimple_build_assign (temp, BIT_XOR_EXPR, arg0, arg1);
15304       gimple_set_location (g, gimple_location (stmt));
15305       gsi_insert_before (gsi, g, GSI_SAME_STMT);
15306       g = gimple_build_assign (lhs, BIT_NOT_EXPR, temp);
15307       gimple_set_location (g, gimple_location (stmt));
15308       gsi_replace (gsi, g, true);
15309       return true;
15310     /* Flavors of vec_rotate_left.  */
15311     case ALTIVEC_BUILTIN_VRLB:
15312     case ALTIVEC_BUILTIN_VRLH:
15313     case ALTIVEC_BUILTIN_VRLW:
15314     case P8V_BUILTIN_VRLD:
15315       arg0 = gimple_call_arg (stmt, 0);
15316       arg1 = gimple_call_arg (stmt, 1);
15317       lhs = gimple_call_lhs (stmt);
15318       g = gimple_build_assign (lhs, LROTATE_EXPR, arg0, arg1);
15319       gimple_set_location (g, gimple_location (stmt));
15320       gsi_replace (gsi, g, true);
15321       return true;
15322   /* Flavors of vector shift right algebraic.
15323      vec_sra{b,h,w} -> vsra{b,h,w}.  */
15324     case ALTIVEC_BUILTIN_VSRAB:
15325     case ALTIVEC_BUILTIN_VSRAH:
15326     case ALTIVEC_BUILTIN_VSRAW:
15327     case P8V_BUILTIN_VSRAD:
15328       {
15329         arg0 = gimple_call_arg (stmt, 0);
15330         arg1 = gimple_call_arg (stmt, 1);
15331         lhs = gimple_call_lhs (stmt);
15332         tree arg1_type = TREE_TYPE (arg1);
15333         tree unsigned_arg1_type = unsigned_type_for (TREE_TYPE (arg1));
15334         tree unsigned_element_type = unsigned_type_for (TREE_TYPE (arg1_type));
15335         location_t loc = gimple_location (stmt);
15336         /* Force arg1 into the range valid matching the arg0 type.  */
15337         /* Build a vector consisting of the max valid bit-size values.  */
15338         int n_elts = VECTOR_CST_NELTS (arg1);
15339         tree element_size = build_int_cst (unsigned_element_type,
15340                                            128 / n_elts);
15341         tree_vector_builder elts (unsigned_arg1_type, n_elts, 1);
15342         for (int i = 0; i < n_elts; i++)
15343           elts.safe_push (element_size);
15344         tree modulo_tree = elts.build ();
15345         /* Modulo the provided shift value against that vector.  */
15346         gimple_seq stmts = NULL;
15347         tree unsigned_arg1 = gimple_build (&stmts, VIEW_CONVERT_EXPR,
15348                                            unsigned_arg1_type, arg1);
15349         tree new_arg1 = gimple_build (&stmts, loc, TRUNC_MOD_EXPR,
15350                                       unsigned_arg1_type, unsigned_arg1,
15351                                       modulo_tree);
15352         gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
15353         /* And finally, do the shift.  */
15354         g = gimple_build_assign (lhs, RSHIFT_EXPR, arg0, new_arg1);
15355         gimple_set_location (g, loc);
15356         gsi_replace (gsi, g, true);
15357         return true;
15358       }
15359    /* Flavors of vector shift left.
15360       builtin_altivec_vsl{b,h,w} -> vsl{b,h,w}.  */
15361     case ALTIVEC_BUILTIN_VSLB:
15362     case ALTIVEC_BUILTIN_VSLH:
15363     case ALTIVEC_BUILTIN_VSLW:
15364     case P8V_BUILTIN_VSLD:
15365       {
15366         location_t loc;
15367         gimple_seq stmts = NULL;
15368         arg0 = gimple_call_arg (stmt, 0);
15369         tree arg0_type = TREE_TYPE (arg0);
15370         if (INTEGRAL_TYPE_P (TREE_TYPE (arg0_type))
15371             && !TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg0_type)))
15372           return false;
15373         arg1 = gimple_call_arg (stmt, 1);
15374         tree arg1_type = TREE_TYPE (arg1);
15375         tree unsigned_arg1_type = unsigned_type_for (TREE_TYPE (arg1));
15376         tree unsigned_element_type = unsigned_type_for (TREE_TYPE (arg1_type));
15377         loc = gimple_location (stmt);
15378         lhs = gimple_call_lhs (stmt);
15379         /* Force arg1 into the range valid matching the arg0 type.  */
15380         /* Build a vector consisting of the max valid bit-size values.  */
15381         int n_elts = VECTOR_CST_NELTS (arg1);
15382         int tree_size_in_bits = TREE_INT_CST_LOW (size_in_bytes (arg1_type))
15383                                 * BITS_PER_UNIT;
15384         tree element_size = build_int_cst (unsigned_element_type,
15385                                            tree_size_in_bits / n_elts);
15386         tree_vector_builder elts (unsigned_type_for (arg1_type), n_elts, 1);
15387         for (int i = 0; i < n_elts; i++)
15388           elts.safe_push (element_size);
15389         tree modulo_tree = elts.build ();
15390         /* Modulo the provided shift value against that vector.  */
15391         tree unsigned_arg1 = gimple_build (&stmts, VIEW_CONVERT_EXPR,
15392                                            unsigned_arg1_type, arg1);
15393         tree new_arg1 = gimple_build (&stmts, loc, TRUNC_MOD_EXPR,
15394                                       unsigned_arg1_type, unsigned_arg1,
15395                                       modulo_tree);
15396         gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
15397         /* And finally, do the shift.  */
15398         g = gimple_build_assign (lhs, LSHIFT_EXPR, arg0, new_arg1);
15399         gimple_set_location (g, gimple_location (stmt));
15400         gsi_replace (gsi, g, true);
15401         return true;
15402       }
15403     /* Flavors of vector shift right.  */
15404     case ALTIVEC_BUILTIN_VSRB:
15405     case ALTIVEC_BUILTIN_VSRH:
15406     case ALTIVEC_BUILTIN_VSRW:
15407     case P8V_BUILTIN_VSRD:
15408       {
15409         arg0 = gimple_call_arg (stmt, 0);
15410         arg1 = gimple_call_arg (stmt, 1);
15411         lhs = gimple_call_lhs (stmt);
15412         tree arg1_type = TREE_TYPE (arg1);
15413         tree unsigned_arg1_type = unsigned_type_for (TREE_TYPE (arg1));
15414         tree unsigned_element_type = unsigned_type_for (TREE_TYPE (arg1_type));
15415         location_t loc = gimple_location (stmt);
15416         gimple_seq stmts = NULL;
15417         /* Convert arg0 to unsigned.  */
15418         tree arg0_unsigned
15419           = gimple_build (&stmts, VIEW_CONVERT_EXPR,
15420                           unsigned_type_for (TREE_TYPE (arg0)), arg0);
15421         /* Force arg1 into the range valid matching the arg0 type.  */
15422         /* Build a vector consisting of the max valid bit-size values.  */
15423         int n_elts = VECTOR_CST_NELTS (arg1);
15424         tree element_size = build_int_cst (unsigned_element_type,
15425                                            128 / n_elts);
15426         tree_vector_builder elts (unsigned_arg1_type, n_elts, 1);
15427         for (int i = 0; i < n_elts; i++)
15428           elts.safe_push (element_size);
15429         tree modulo_tree = elts.build ();
15430         /* Modulo the provided shift value against that vector.  */
15431         tree unsigned_arg1 = gimple_build (&stmts, VIEW_CONVERT_EXPR,
15432                                            unsigned_arg1_type, arg1);
15433         tree new_arg1 = gimple_build (&stmts, loc, TRUNC_MOD_EXPR,
15434                                       unsigned_arg1_type, unsigned_arg1,
15435                                       modulo_tree);
15436         /* Do the shift.  */
15437         tree res
15438           = gimple_build (&stmts, RSHIFT_EXPR,
15439                           TREE_TYPE (arg0_unsigned), arg0_unsigned, new_arg1);
15440         /* Convert result back to the lhs type.  */
15441         res = gimple_build (&stmts, VIEW_CONVERT_EXPR, TREE_TYPE (lhs), res);
15442         gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
15443         update_call_from_tree (gsi, res);
15444         return true;
15445       }
15446     /* Vector loads.  */
15447     case ALTIVEC_BUILTIN_LVX_V16QI:
15448     case ALTIVEC_BUILTIN_LVX_V8HI:
15449     case ALTIVEC_BUILTIN_LVX_V4SI:
15450     case ALTIVEC_BUILTIN_LVX_V4SF:
15451     case ALTIVEC_BUILTIN_LVX_V2DI:
15452     case ALTIVEC_BUILTIN_LVX_V2DF:
15453     case ALTIVEC_BUILTIN_LVX_V1TI:
15454       {
15455         arg0 = gimple_call_arg (stmt, 0);  // offset
15456         arg1 = gimple_call_arg (stmt, 1);  // address
15457         lhs = gimple_call_lhs (stmt);
15458         location_t loc = gimple_location (stmt);
15459         /* Since arg1 may be cast to a different type, just use ptr_type_node
15460            here instead of trying to enforce TBAA on pointer types.  */
15461         tree arg1_type = ptr_type_node;
15462         tree lhs_type = TREE_TYPE (lhs);
15463         /* POINTER_PLUS_EXPR wants the offset to be of type 'sizetype'.  Create
15464            the tree using the value from arg0.  The resulting type will match
15465            the type of arg1.  */
15466         gimple_seq stmts = NULL;
15467         tree temp_offset = gimple_convert (&stmts, loc, sizetype, arg0);
15468         tree temp_addr = gimple_build (&stmts, loc, POINTER_PLUS_EXPR,
15469                                        arg1_type, arg1, temp_offset);
15470         /* Mask off any lower bits from the address.  */
15471         tree aligned_addr = gimple_build (&stmts, loc, BIT_AND_EXPR,
15472                                           arg1_type, temp_addr,
15473                                           build_int_cst (arg1_type, -16));
15474         gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
15475         if (!is_gimple_mem_ref_addr (aligned_addr))
15476           {
15477             tree t = make_ssa_name (TREE_TYPE (aligned_addr));
15478             gimple *g = gimple_build_assign (t, aligned_addr);
15479             gsi_insert_before (gsi, g, GSI_SAME_STMT);
15480             aligned_addr = t;
15481           }
15482         /* Use the build2 helper to set up the mem_ref.  The MEM_REF could also
15483            take an offset, but since we've already incorporated the offset
15484            above, here we just pass in a zero.  */
15485         gimple *g
15486           = gimple_build_assign (lhs, build2 (MEM_REF, lhs_type, aligned_addr,
15487                                               build_int_cst (arg1_type, 0)));
15488         gimple_set_location (g, loc);
15489         gsi_replace (gsi, g, true);
15490         return true;
15491       }
15492     /* Vector stores.  */
15493     case ALTIVEC_BUILTIN_STVX_V16QI:
15494     case ALTIVEC_BUILTIN_STVX_V8HI:
15495     case ALTIVEC_BUILTIN_STVX_V4SI:
15496     case ALTIVEC_BUILTIN_STVX_V4SF:
15497     case ALTIVEC_BUILTIN_STVX_V2DI:
15498     case ALTIVEC_BUILTIN_STVX_V2DF:
15499       {
15500         arg0 = gimple_call_arg (stmt, 0); /* Value to be stored.  */
15501         arg1 = gimple_call_arg (stmt, 1); /* Offset.  */
15502         tree arg2 = gimple_call_arg (stmt, 2); /* Store-to address.  */
15503         location_t loc = gimple_location (stmt);
15504         tree arg0_type = TREE_TYPE (arg0);
15505         /* Use ptr_type_node (no TBAA) for the arg2_type.
15506            FIXME: (Richard)  "A proper fix would be to transition this type as
15507            seen from the frontend to GIMPLE, for example in a similar way we
15508            do for MEM_REFs by piggy-backing that on an extra argument, a
15509            constant zero pointer of the alias pointer type to use (which would
15510            also serve as a type indicator of the store itself).  I'd use a
15511            target specific internal function for this (not sure if we can have
15512            those target specific, but I guess if it's folded away then that's
15513            fine) and get away with the overload set."  */
15514         tree arg2_type = ptr_type_node;
15515         /* POINTER_PLUS_EXPR wants the offset to be of type 'sizetype'.  Create
15516            the tree using the value from arg0.  The resulting type will match
15517            the type of arg2.  */
15518         gimple_seq stmts = NULL;
15519         tree temp_offset = gimple_convert (&stmts, loc, sizetype, arg1);
15520         tree temp_addr = gimple_build (&stmts, loc, POINTER_PLUS_EXPR,
15521                                        arg2_type, arg2, temp_offset);
15522         /* Mask off any lower bits from the address.  */
15523         tree aligned_addr = gimple_build (&stmts, loc, BIT_AND_EXPR,
15524                                           arg2_type, temp_addr,
15525                                           build_int_cst (arg2_type, -16));
15526         gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
15527         if (!is_gimple_mem_ref_addr (aligned_addr))
15528           {
15529             tree t = make_ssa_name (TREE_TYPE (aligned_addr));
15530             gimple *g = gimple_build_assign (t, aligned_addr);
15531             gsi_insert_before (gsi, g, GSI_SAME_STMT);
15532             aligned_addr = t;
15533           }
15534         /* The desired gimple result should be similar to:
15535            MEM[(__vector floatD.1407 *)_1] = vf1D.2697;  */
15536         gimple *g
15537           = gimple_build_assign (build2 (MEM_REF, arg0_type, aligned_addr,
15538                                          build_int_cst (arg2_type, 0)), arg0);
15539         gimple_set_location (g, loc);
15540         gsi_replace (gsi, g, true);
15541         return true;
15542       }
15543
15544     /* unaligned Vector loads.  */
15545     case VSX_BUILTIN_LXVW4X_V16QI:
15546     case VSX_BUILTIN_LXVW4X_V8HI:
15547     case VSX_BUILTIN_LXVW4X_V4SF:
15548     case VSX_BUILTIN_LXVW4X_V4SI:
15549     case VSX_BUILTIN_LXVD2X_V2DF:
15550     case VSX_BUILTIN_LXVD2X_V2DI:
15551       {
15552         arg0 = gimple_call_arg (stmt, 0);  // offset
15553         arg1 = gimple_call_arg (stmt, 1);  // address
15554         lhs = gimple_call_lhs (stmt);
15555         location_t loc = gimple_location (stmt);
15556         /* Since arg1 may be cast to a different type, just use ptr_type_node
15557            here instead of trying to enforce TBAA on pointer types.  */
15558         tree arg1_type = ptr_type_node;
15559         tree lhs_type = TREE_TYPE (lhs);
15560         /* In GIMPLE the type of the MEM_REF specifies the alignment.  The
15561           required alignment (power) is 4 bytes regardless of data type.  */
15562         tree align_ltype = build_aligned_type (lhs_type, 4);
15563         /* POINTER_PLUS_EXPR wants the offset to be of type 'sizetype'.  Create
15564            the tree using the value from arg0.  The resulting type will match
15565            the type of arg1.  */
15566         gimple_seq stmts = NULL;
15567         tree temp_offset = gimple_convert (&stmts, loc, sizetype, arg0);
15568         tree temp_addr = gimple_build (&stmts, loc, POINTER_PLUS_EXPR,
15569                                        arg1_type, arg1, temp_offset);
15570         gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
15571         if (!is_gimple_mem_ref_addr (temp_addr))
15572           {
15573             tree t = make_ssa_name (TREE_TYPE (temp_addr));
15574             gimple *g = gimple_build_assign (t, temp_addr);
15575             gsi_insert_before (gsi, g, GSI_SAME_STMT);
15576             temp_addr = t;
15577           }
15578         /* Use the build2 helper to set up the mem_ref.  The MEM_REF could also
15579            take an offset, but since we've already incorporated the offset
15580            above, here we just pass in a zero.  */
15581         gimple *g;
15582         g = gimple_build_assign (lhs, build2 (MEM_REF, align_ltype, temp_addr,
15583                                               build_int_cst (arg1_type, 0)));
15584         gimple_set_location (g, loc);
15585         gsi_replace (gsi, g, true);
15586         return true;
15587       }
15588
15589     /* unaligned Vector stores.  */
15590     case VSX_BUILTIN_STXVW4X_V16QI:
15591     case VSX_BUILTIN_STXVW4X_V8HI:
15592     case VSX_BUILTIN_STXVW4X_V4SF:
15593     case VSX_BUILTIN_STXVW4X_V4SI:
15594     case VSX_BUILTIN_STXVD2X_V2DF:
15595     case VSX_BUILTIN_STXVD2X_V2DI:
15596       {
15597         arg0 = gimple_call_arg (stmt, 0); /* Value to be stored.  */
15598         arg1 = gimple_call_arg (stmt, 1); /* Offset.  */
15599         tree arg2 = gimple_call_arg (stmt, 2); /* Store-to address.  */
15600         location_t loc = gimple_location (stmt);
15601         tree arg0_type = TREE_TYPE (arg0);
15602         /* Use ptr_type_node (no TBAA) for the arg2_type.  */
15603         tree arg2_type = ptr_type_node;
15604         /* In GIMPLE the type of the MEM_REF specifies the alignment.  The
15605            required alignment (power) is 4 bytes regardless of data type.  */
15606         tree align_stype = build_aligned_type (arg0_type, 4);
15607         /* POINTER_PLUS_EXPR wants the offset to be of type 'sizetype'.  Create
15608            the tree using the value from arg1.  */
15609         gimple_seq stmts = NULL;
15610         tree temp_offset = gimple_convert (&stmts, loc, sizetype, arg1);
15611         tree temp_addr = gimple_build (&stmts, loc, POINTER_PLUS_EXPR,
15612                                        arg2_type, arg2, temp_offset);
15613         gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
15614         if (!is_gimple_mem_ref_addr (temp_addr))
15615           {
15616             tree t = make_ssa_name (TREE_TYPE (temp_addr));
15617             gimple *g = gimple_build_assign (t, temp_addr);
15618             gsi_insert_before (gsi, g, GSI_SAME_STMT);
15619             temp_addr = t;
15620           }
15621         gimple *g;
15622         g = gimple_build_assign (build2 (MEM_REF, align_stype, temp_addr,
15623                                          build_int_cst (arg2_type, 0)), arg0);
15624         gimple_set_location (g, loc);
15625         gsi_replace (gsi, g, true);
15626         return true;
15627       }
15628
15629     /* Vector Fused multiply-add (fma).  */
15630     case ALTIVEC_BUILTIN_VMADDFP:
15631     case VSX_BUILTIN_XVMADDDP:
15632     case ALTIVEC_BUILTIN_VMLADDUHM:
15633       {
15634         arg0 = gimple_call_arg (stmt, 0);
15635         arg1 = gimple_call_arg (stmt, 1);
15636         tree arg2 = gimple_call_arg (stmt, 2);
15637         lhs = gimple_call_lhs (stmt);
15638         gcall *g = gimple_build_call_internal (IFN_FMA, 3, arg0, arg1, arg2);
15639         gimple_call_set_lhs (g, lhs);
15640         gimple_call_set_nothrow (g, true);
15641         gimple_set_location (g, gimple_location (stmt));
15642         gsi_replace (gsi, g, true);
15643         return true;
15644       }
15645
15646     /* Vector compares; EQ, NE, GE, GT, LE.  */
15647     case ALTIVEC_BUILTIN_VCMPEQUB:
15648     case ALTIVEC_BUILTIN_VCMPEQUH:
15649     case ALTIVEC_BUILTIN_VCMPEQUW:
15650     case P8V_BUILTIN_VCMPEQUD:
15651       fold_compare_helper (gsi, EQ_EXPR, stmt);
15652       return true;
15653
15654     case P9V_BUILTIN_CMPNEB:
15655     case P9V_BUILTIN_CMPNEH:
15656     case P9V_BUILTIN_CMPNEW:
15657       fold_compare_helper (gsi, NE_EXPR, stmt);
15658       return true;
15659
15660     case VSX_BUILTIN_CMPGE_16QI:
15661     case VSX_BUILTIN_CMPGE_U16QI:
15662     case VSX_BUILTIN_CMPGE_8HI:
15663     case VSX_BUILTIN_CMPGE_U8HI:
15664     case VSX_BUILTIN_CMPGE_4SI:
15665     case VSX_BUILTIN_CMPGE_U4SI:
15666     case VSX_BUILTIN_CMPGE_2DI:
15667     case VSX_BUILTIN_CMPGE_U2DI:
15668       fold_compare_helper (gsi, GE_EXPR, stmt);
15669       return true;
15670
15671     case ALTIVEC_BUILTIN_VCMPGTSB:
15672     case ALTIVEC_BUILTIN_VCMPGTUB:
15673     case ALTIVEC_BUILTIN_VCMPGTSH:
15674     case ALTIVEC_BUILTIN_VCMPGTUH:
15675     case ALTIVEC_BUILTIN_VCMPGTSW:
15676     case ALTIVEC_BUILTIN_VCMPGTUW:
15677     case P8V_BUILTIN_VCMPGTUD:
15678     case P8V_BUILTIN_VCMPGTSD:
15679       fold_compare_helper (gsi, GT_EXPR, stmt);
15680       return true;
15681
15682     case VSX_BUILTIN_CMPLE_16QI:
15683     case VSX_BUILTIN_CMPLE_U16QI:
15684     case VSX_BUILTIN_CMPLE_8HI:
15685     case VSX_BUILTIN_CMPLE_U8HI:
15686     case VSX_BUILTIN_CMPLE_4SI:
15687     case VSX_BUILTIN_CMPLE_U4SI:
15688     case VSX_BUILTIN_CMPLE_2DI:
15689     case VSX_BUILTIN_CMPLE_U2DI:
15690       fold_compare_helper (gsi, LE_EXPR, stmt);
15691       return true;
15692
15693     /* flavors of vec_splat_[us]{8,16,32}.  */
15694     case ALTIVEC_BUILTIN_VSPLTISB:
15695     case ALTIVEC_BUILTIN_VSPLTISH:
15696     case ALTIVEC_BUILTIN_VSPLTISW:
15697       {
15698         arg0 = gimple_call_arg (stmt, 0);
15699         lhs = gimple_call_lhs (stmt);
15700
15701         /* Only fold the vec_splat_*() if the lower bits of arg 0 is a
15702            5-bit signed constant in range -16 to +15.  */
15703         if (TREE_CODE (arg0) != INTEGER_CST
15704             || !IN_RANGE (TREE_INT_CST_LOW (arg0), -16, 15))
15705           return false;
15706         gimple_seq stmts = NULL;
15707         location_t loc = gimple_location (stmt);
15708         tree splat_value = gimple_convert (&stmts, loc,
15709                                            TREE_TYPE (TREE_TYPE (lhs)), arg0);
15710         gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
15711         tree splat_tree = build_vector_from_val (TREE_TYPE (lhs), splat_value);
15712         g = gimple_build_assign (lhs, splat_tree);
15713         gimple_set_location (g, gimple_location (stmt));
15714         gsi_replace (gsi, g, true);
15715         return true;
15716       }
15717
15718     /* Flavors of vec_splat.  */
15719     /* a = vec_splat (b, 0x3) becomes a = { b[3],b[3],b[3],...};  */
15720     case ALTIVEC_BUILTIN_VSPLTB:
15721     case ALTIVEC_BUILTIN_VSPLTH:
15722     case ALTIVEC_BUILTIN_VSPLTW:
15723     case VSX_BUILTIN_XXSPLTD_V2DI:
15724     case VSX_BUILTIN_XXSPLTD_V2DF:
15725       {
15726         arg0 = gimple_call_arg (stmt, 0); /* input vector.  */
15727         arg1 = gimple_call_arg (stmt, 1); /* index into arg0.  */
15728         /* Only fold the vec_splat_*() if arg1 is both a constant value and
15729            is a valid index into the arg0 vector.  */
15730         unsigned int n_elts = VECTOR_CST_NELTS (arg0);
15731         if (TREE_CODE (arg1) != INTEGER_CST
15732             || TREE_INT_CST_LOW (arg1) > (n_elts -1))
15733           return false;
15734         lhs = gimple_call_lhs (stmt);
15735         tree lhs_type = TREE_TYPE (lhs);
15736         tree arg0_type = TREE_TYPE (arg0);
15737         tree splat;
15738         if (TREE_CODE (arg0) == VECTOR_CST)
15739           splat = VECTOR_CST_ELT (arg0, TREE_INT_CST_LOW (arg1));
15740         else
15741           {
15742             /* Determine (in bits) the length and start location of the
15743                splat value for a call to the tree_vec_extract helper.  */
15744             int splat_elem_size = TREE_INT_CST_LOW (size_in_bytes (arg0_type))
15745                                   * BITS_PER_UNIT / n_elts;
15746             int splat_start_bit = TREE_INT_CST_LOW (arg1) * splat_elem_size;
15747             tree len = build_int_cst (bitsizetype, splat_elem_size);
15748             tree start = build_int_cst (bitsizetype, splat_start_bit);
15749             splat = tree_vec_extract (gsi, TREE_TYPE (lhs_type), arg0,
15750                                       len, start);
15751           }
15752         /* And finally, build the new vector.  */
15753         tree splat_tree = build_vector_from_val (lhs_type, splat);
15754         g = gimple_build_assign (lhs, splat_tree);
15755         gimple_set_location (g, gimple_location (stmt));
15756         gsi_replace (gsi, g, true);
15757         return true;
15758       }
15759
15760     /* vec_mergel (integrals).  */
15761     case ALTIVEC_BUILTIN_VMRGLH:
15762     case ALTIVEC_BUILTIN_VMRGLW:
15763     case VSX_BUILTIN_XXMRGLW_4SI:
15764     case ALTIVEC_BUILTIN_VMRGLB:
15765     case VSX_BUILTIN_VEC_MERGEL_V2DI:
15766     case VSX_BUILTIN_XXMRGLW_4SF:
15767     case VSX_BUILTIN_VEC_MERGEL_V2DF:
15768       fold_mergehl_helper (gsi, stmt, 1);
15769       return true;
15770     /* vec_mergeh (integrals).  */
15771     case ALTIVEC_BUILTIN_VMRGHH:
15772     case ALTIVEC_BUILTIN_VMRGHW:
15773     case VSX_BUILTIN_XXMRGHW_4SI:
15774     case ALTIVEC_BUILTIN_VMRGHB:
15775     case VSX_BUILTIN_VEC_MERGEH_V2DI:
15776     case VSX_BUILTIN_XXMRGHW_4SF:
15777     case VSX_BUILTIN_VEC_MERGEH_V2DF:
15778       fold_mergehl_helper (gsi, stmt, 0);
15779       return true;
15780
15781     /* Flavors of vec_mergee.  */
15782     case P8V_BUILTIN_VMRGEW_V4SI:
15783     case P8V_BUILTIN_VMRGEW_V2DI:
15784     case P8V_BUILTIN_VMRGEW_V4SF:
15785     case P8V_BUILTIN_VMRGEW_V2DF:
15786       fold_mergeeo_helper (gsi, stmt, 0);
15787       return true;
15788     /* Flavors of vec_mergeo.  */
15789     case P8V_BUILTIN_VMRGOW_V4SI:
15790     case P8V_BUILTIN_VMRGOW_V2DI:
15791     case P8V_BUILTIN_VMRGOW_V4SF:
15792     case P8V_BUILTIN_VMRGOW_V2DF:
15793       fold_mergeeo_helper (gsi, stmt, 1);
15794       return true;
15795
15796     /* d = vec_pack (a, b) */
15797     case P8V_BUILTIN_VPKUDUM:
15798     case ALTIVEC_BUILTIN_VPKUHUM:
15799     case ALTIVEC_BUILTIN_VPKUWUM:
15800       {
15801         arg0 = gimple_call_arg (stmt, 0);
15802         arg1 = gimple_call_arg (stmt, 1);
15803         lhs = gimple_call_lhs (stmt);
15804         gimple *g = gimple_build_assign (lhs, VEC_PACK_TRUNC_EXPR, arg0, arg1);
15805         gimple_set_location (g, gimple_location (stmt));
15806         gsi_replace (gsi, g, true);
15807         return true;
15808       }
15809
15810     /* d = vec_unpackh (a) */
15811     /* Note that the UNPACK_{HI,LO}_EXPR used in the gimple_build_assign call
15812        in this code is sensitive to endian-ness, and needs to be inverted to
15813        handle both LE and BE targets.  */
15814     case ALTIVEC_BUILTIN_VUPKHSB:
15815     case ALTIVEC_BUILTIN_VUPKHSH:
15816     case P8V_BUILTIN_VUPKHSW:
15817       {
15818         arg0 = gimple_call_arg (stmt, 0);
15819         lhs = gimple_call_lhs (stmt);
15820         if (BYTES_BIG_ENDIAN)
15821           g = gimple_build_assign (lhs, VEC_UNPACK_HI_EXPR, arg0);
15822         else
15823           g = gimple_build_assign (lhs, VEC_UNPACK_LO_EXPR, arg0);
15824         gimple_set_location (g, gimple_location (stmt));
15825         gsi_replace (gsi, g, true);
15826         return true;
15827       }
15828     /* d = vec_unpackl (a) */
15829     case ALTIVEC_BUILTIN_VUPKLSB:
15830     case ALTIVEC_BUILTIN_VUPKLSH:
15831     case P8V_BUILTIN_VUPKLSW:
15832       {
15833         arg0 = gimple_call_arg (stmt, 0);
15834         lhs = gimple_call_lhs (stmt);
15835         if (BYTES_BIG_ENDIAN)
15836           g = gimple_build_assign (lhs, VEC_UNPACK_LO_EXPR, arg0);
15837         else
15838           g = gimple_build_assign (lhs, VEC_UNPACK_HI_EXPR, arg0);
15839         gimple_set_location (g, gimple_location (stmt));
15840         gsi_replace (gsi, g, true);
15841         return true;
15842       }
15843     /* There is no gimple type corresponding with pixel, so just return.  */
15844     case ALTIVEC_BUILTIN_VUPKHPX:
15845     case ALTIVEC_BUILTIN_VUPKLPX:
15846       return false;
15847
15848     /* vec_perm.  */
15849     case ALTIVEC_BUILTIN_VPERM_16QI:
15850     case ALTIVEC_BUILTIN_VPERM_8HI:
15851     case ALTIVEC_BUILTIN_VPERM_4SI:
15852     case ALTIVEC_BUILTIN_VPERM_2DI:
15853     case ALTIVEC_BUILTIN_VPERM_4SF:
15854     case ALTIVEC_BUILTIN_VPERM_2DF:
15855       {
15856         arg0 = gimple_call_arg (stmt, 0);
15857         arg1 = gimple_call_arg (stmt, 1);
15858         tree permute = gimple_call_arg (stmt, 2);
15859         lhs = gimple_call_lhs (stmt);
15860         location_t loc = gimple_location (stmt);
15861         gimple_seq stmts = NULL;
15862         // convert arg0 and arg1 to match the type of the permute
15863         // for the VEC_PERM_EXPR operation.
15864         tree permute_type = (TREE_TYPE (permute));
15865         tree arg0_ptype = gimple_convert (&stmts, loc, permute_type, arg0);
15866         tree arg1_ptype = gimple_convert (&stmts, loc, permute_type, arg1);
15867         tree lhs_ptype = gimple_build (&stmts, loc, VEC_PERM_EXPR,
15868                                       permute_type, arg0_ptype, arg1_ptype,
15869                                       permute);
15870         // Convert the result back to the desired lhs type upon completion.
15871         tree temp = gimple_convert (&stmts, loc, TREE_TYPE (lhs), lhs_ptype);
15872         gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
15873         g = gimple_build_assign (lhs, temp);
15874         gimple_set_location (g, loc);
15875         gsi_replace (gsi, g, true);
15876         return true;
15877       }
15878
15879     default:
15880       if (TARGET_DEBUG_BUILTIN)
15881         fprintf (stderr, "gimple builtin intrinsic not matched:%d %s %s\n",
15882                  fn_code, fn_name1, fn_name2);
15883       break;
15884     }
15885
15886   return false;
15887 }
15888
15889 /* Expand an expression EXP that calls a built-in function,
15890    with result going to TARGET if that's convenient
15891    (and in mode MODE if that's convenient).
15892    SUBTARGET may be used as the target for computing one of EXP's operands.
15893    IGNORE is nonzero if the value is to be ignored.  */
15894
15895 static rtx
15896 rs6000_expand_builtin (tree exp, rtx target, rtx subtarget ATTRIBUTE_UNUSED,
15897                        machine_mode mode ATTRIBUTE_UNUSED,
15898                        int ignore ATTRIBUTE_UNUSED)
15899 {
15900   tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
15901   enum rs6000_builtins fcode
15902     = (enum rs6000_builtins)DECL_FUNCTION_CODE (fndecl);
15903   size_t uns_fcode = (size_t)fcode;
15904   const struct builtin_description *d;
15905   size_t i;
15906   rtx ret;
15907   bool success;
15908   HOST_WIDE_INT mask = rs6000_builtin_info[uns_fcode].mask;
15909   bool func_valid_p = ((rs6000_builtin_mask & mask) == mask);
15910   enum insn_code icode = rs6000_builtin_info[uns_fcode].icode;
15911
15912   /* We have two different modes (KFmode, TFmode) that are the IEEE 128-bit
15913      floating point type, depending on whether long double is the IBM extended
15914      double (KFmode) or long double is IEEE 128-bit (TFmode).  It is simpler if
15915      we only define one variant of the built-in function, and switch the code
15916      when defining it, rather than defining two built-ins and using the
15917      overload table in rs6000-c.c to switch between the two.  If we don't have
15918      the proper assembler, don't do this switch because CODE_FOR_*kf* and
15919      CODE_FOR_*tf* will be CODE_FOR_nothing.  */
15920   if (FLOAT128_IEEE_P (TFmode))
15921     switch (icode)
15922       {
15923       default:
15924         break;
15925
15926       case CODE_FOR_sqrtkf2_odd:        icode = CODE_FOR_sqrttf2_odd;   break;
15927       case CODE_FOR_trunckfdf2_odd:     icode = CODE_FOR_trunctfdf2_odd; break;
15928       case CODE_FOR_addkf3_odd:         icode = CODE_FOR_addtf3_odd;    break;
15929       case CODE_FOR_subkf3_odd:         icode = CODE_FOR_subtf3_odd;    break;
15930       case CODE_FOR_mulkf3_odd:         icode = CODE_FOR_multf3_odd;    break;
15931       case CODE_FOR_divkf3_odd:         icode = CODE_FOR_divtf3_odd;    break;
15932       case CODE_FOR_fmakf4_odd:         icode = CODE_FOR_fmatf4_odd;    break;
15933       case CODE_FOR_xsxexpqp_kf:        icode = CODE_FOR_xsxexpqp_tf;   break;
15934       case CODE_FOR_xsxsigqp_kf:        icode = CODE_FOR_xsxsigqp_tf;   break;
15935       case CODE_FOR_xststdcnegqp_kf:    icode = CODE_FOR_xststdcnegqp_tf; break;
15936       case CODE_FOR_xsiexpqp_kf:        icode = CODE_FOR_xsiexpqp_tf;   break;
15937       case CODE_FOR_xsiexpqpf_kf:       icode = CODE_FOR_xsiexpqpf_tf;  break;
15938       case CODE_FOR_xststdcqp_kf:       icode = CODE_FOR_xststdcqp_tf;  break;
15939       }
15940
15941   if (TARGET_DEBUG_BUILTIN)
15942     {
15943       const char *name1 = rs6000_builtin_info[uns_fcode].name;
15944       const char *name2 = (icode != CODE_FOR_nothing)
15945                            ? get_insn_name ((int) icode)
15946                            : "nothing";
15947       const char *name3;
15948
15949       switch (rs6000_builtin_info[uns_fcode].attr & RS6000_BTC_TYPE_MASK)
15950         {
15951         default:                   name3 = "unknown";   break;
15952         case RS6000_BTC_SPECIAL:   name3 = "special";   break;
15953         case RS6000_BTC_UNARY:     name3 = "unary";     break;
15954         case RS6000_BTC_BINARY:    name3 = "binary";    break;
15955         case RS6000_BTC_TERNARY:   name3 = "ternary";   break;
15956         case RS6000_BTC_PREDICATE: name3 = "predicate"; break;
15957         case RS6000_BTC_ABS:       name3 = "abs";       break;
15958         case RS6000_BTC_DST:       name3 = "dst";       break;
15959         }
15960
15961
15962       fprintf (stderr,
15963                "rs6000_expand_builtin, %s (%d), insn = %s (%d), type=%s%s\n",
15964                (name1) ? name1 : "---", fcode,
15965                (name2) ? name2 : "---", (int) icode,
15966                name3,
15967                func_valid_p ? "" : ", not valid");
15968     }        
15969
15970   if (!func_valid_p)
15971     {
15972       rs6000_invalid_builtin (fcode);
15973
15974       /* Given it is invalid, just generate a normal call.  */
15975       return expand_call (exp, target, ignore);
15976     }
15977
15978   switch (fcode)
15979     {
15980     case RS6000_BUILTIN_RECIP:
15981       return rs6000_expand_binop_builtin (CODE_FOR_recipdf3, exp, target);
15982
15983     case RS6000_BUILTIN_RECIPF:
15984       return rs6000_expand_binop_builtin (CODE_FOR_recipsf3, exp, target);
15985
15986     case RS6000_BUILTIN_RSQRTF:
15987       return rs6000_expand_unop_builtin (CODE_FOR_rsqrtsf2, exp, target);
15988
15989     case RS6000_BUILTIN_RSQRT:
15990       return rs6000_expand_unop_builtin (CODE_FOR_rsqrtdf2, exp, target);
15991
15992     case POWER7_BUILTIN_BPERMD:
15993       return rs6000_expand_binop_builtin (((TARGET_64BIT)
15994                                            ? CODE_FOR_bpermd_di
15995                                            : CODE_FOR_bpermd_si), exp, target);
15996
15997     case RS6000_BUILTIN_GET_TB:
15998       return rs6000_expand_zeroop_builtin (CODE_FOR_rs6000_get_timebase,
15999                                            target);
16000
16001     case RS6000_BUILTIN_MFTB:
16002       return rs6000_expand_zeroop_builtin (((TARGET_64BIT)
16003                                             ? CODE_FOR_rs6000_mftb_di
16004                                             : CODE_FOR_rs6000_mftb_si),
16005                                            target);
16006
16007     case RS6000_BUILTIN_MFFS:
16008       return rs6000_expand_zeroop_builtin (CODE_FOR_rs6000_mffs, target);
16009
16010     case RS6000_BUILTIN_MTFSB0:
16011       return rs6000_expand_mtfsb_builtin (CODE_FOR_rs6000_mtfsb0, exp);
16012
16013     case RS6000_BUILTIN_MTFSB1:
16014       return rs6000_expand_mtfsb_builtin (CODE_FOR_rs6000_mtfsb1, exp);
16015
16016     case RS6000_BUILTIN_SET_FPSCR_RN:
16017       return rs6000_expand_set_fpscr_rn_builtin (CODE_FOR_rs6000_set_fpscr_rn,
16018                                                  exp);
16019
16020     case RS6000_BUILTIN_SET_FPSCR_DRN:
16021       return
16022         rs6000_expand_set_fpscr_drn_builtin (CODE_FOR_rs6000_set_fpscr_drn,
16023                                              exp);
16024
16025     case RS6000_BUILTIN_MFFSL:
16026       return rs6000_expand_zeroop_builtin (CODE_FOR_rs6000_mffsl, target);
16027
16028     case RS6000_BUILTIN_MTFSF:
16029       return rs6000_expand_mtfsf_builtin (CODE_FOR_rs6000_mtfsf, exp);
16030
16031     case RS6000_BUILTIN_CPU_INIT:
16032     case RS6000_BUILTIN_CPU_IS:
16033     case RS6000_BUILTIN_CPU_SUPPORTS:
16034       return cpu_expand_builtin (fcode, exp, target);
16035
16036     case MISC_BUILTIN_SPEC_BARRIER:
16037       {
16038         emit_insn (gen_speculation_barrier ());
16039         return NULL_RTX;
16040       }
16041
16042     case ALTIVEC_BUILTIN_MASK_FOR_LOAD:
16043     case ALTIVEC_BUILTIN_MASK_FOR_STORE:
16044       {
16045         int icode2 = (BYTES_BIG_ENDIAN ? (int) CODE_FOR_altivec_lvsr_direct
16046                      : (int) CODE_FOR_altivec_lvsl_direct);
16047         machine_mode tmode = insn_data[icode2].operand[0].mode;
16048         machine_mode mode = insn_data[icode2].operand[1].mode;
16049         tree arg;
16050         rtx op, addr, pat;
16051
16052         gcc_assert (TARGET_ALTIVEC);
16053
16054         arg = CALL_EXPR_ARG (exp, 0);
16055         gcc_assert (POINTER_TYPE_P (TREE_TYPE (arg)));
16056         op = expand_expr (arg, NULL_RTX, Pmode, EXPAND_NORMAL);
16057         addr = memory_address (mode, op);
16058         if (fcode == ALTIVEC_BUILTIN_MASK_FOR_STORE)
16059           op = addr;
16060         else
16061           {
16062             /* For the load case need to negate the address.  */
16063             op = gen_reg_rtx (GET_MODE (addr));
16064             emit_insn (gen_rtx_SET (op, gen_rtx_NEG (GET_MODE (addr), addr)));
16065           }
16066         op = gen_rtx_MEM (mode, op);
16067
16068         if (target == 0
16069             || GET_MODE (target) != tmode
16070             || ! (*insn_data[icode2].operand[0].predicate) (target, tmode))
16071           target = gen_reg_rtx (tmode);
16072
16073         pat = GEN_FCN (icode2) (target, op);
16074         if (!pat)
16075           return 0;
16076         emit_insn (pat);
16077
16078         return target;
16079       }
16080
16081     case ALTIVEC_BUILTIN_VCFUX:
16082     case ALTIVEC_BUILTIN_VCFSX:
16083     case ALTIVEC_BUILTIN_VCTUXS:
16084     case ALTIVEC_BUILTIN_VCTSXS:
16085   /* FIXME: There's got to be a nicer way to handle this case than
16086      constructing a new CALL_EXPR.  */
16087       if (call_expr_nargs (exp) == 1)
16088         {
16089           exp = build_call_nary (TREE_TYPE (exp), CALL_EXPR_FN (exp),
16090                                  2, CALL_EXPR_ARG (exp, 0), integer_zero_node);
16091         }
16092       break;
16093
16094       /* For the pack and unpack int128 routines, fix up the builtin so it
16095          uses the correct IBM128 type.  */
16096     case MISC_BUILTIN_PACK_IF:
16097       if (TARGET_LONG_DOUBLE_128 && !TARGET_IEEEQUAD)
16098         {
16099           icode = CODE_FOR_packtf;
16100           fcode = MISC_BUILTIN_PACK_TF;
16101           uns_fcode = (size_t)fcode;
16102         }
16103       break;
16104
16105     case MISC_BUILTIN_UNPACK_IF:
16106       if (TARGET_LONG_DOUBLE_128 && !TARGET_IEEEQUAD)
16107         {
16108           icode = CODE_FOR_unpacktf;
16109           fcode = MISC_BUILTIN_UNPACK_TF;
16110           uns_fcode = (size_t)fcode;
16111         }
16112       break;
16113
16114     default:
16115       break;
16116     }
16117
16118   if (TARGET_ALTIVEC)
16119     {
16120       ret = altivec_expand_builtin (exp, target, &success);
16121
16122       if (success)
16123         return ret;
16124     }
16125   if (TARGET_HTM)
16126     {
16127       ret = htm_expand_builtin (exp, target, &success);
16128
16129       if (success)
16130         return ret;
16131     }  
16132
16133   unsigned attr = rs6000_builtin_info[uns_fcode].attr & RS6000_BTC_TYPE_MASK;
16134   /* RS6000_BTC_SPECIAL represents no-operand operators.  */
16135   gcc_assert (attr == RS6000_BTC_UNARY
16136               || attr == RS6000_BTC_BINARY
16137               || attr == RS6000_BTC_TERNARY
16138               || attr == RS6000_BTC_SPECIAL);
16139   
16140   /* Handle simple unary operations.  */
16141   d = bdesc_1arg;
16142   for (i = 0; i < ARRAY_SIZE (bdesc_1arg); i++, d++)
16143     if (d->code == fcode)
16144       return rs6000_expand_unop_builtin (icode, exp, target);
16145
16146   /* Handle simple binary operations.  */
16147   d = bdesc_2arg;
16148   for (i = 0; i < ARRAY_SIZE (bdesc_2arg); i++, d++)
16149     if (d->code == fcode)
16150       return rs6000_expand_binop_builtin (icode, exp, target);
16151
16152   /* Handle simple ternary operations.  */
16153   d = bdesc_3arg;
16154   for (i = 0; i < ARRAY_SIZE  (bdesc_3arg); i++, d++)
16155     if (d->code == fcode)
16156       return rs6000_expand_ternop_builtin (icode, exp, target);
16157
16158   /* Handle simple no-argument operations. */
16159   d = bdesc_0arg;
16160   for (i = 0; i < ARRAY_SIZE (bdesc_0arg); i++, d++)
16161     if (d->code == fcode)
16162       return rs6000_expand_zeroop_builtin (icode, target);
16163
16164   gcc_unreachable ();
16165 }
16166
16167 /* Create a builtin vector type with a name.  Taking care not to give
16168    the canonical type a name.  */
16169
16170 static tree
16171 rs6000_vector_type (const char *name, tree elt_type, unsigned num_elts)
16172 {
16173   tree result = build_vector_type (elt_type, num_elts);
16174
16175   /* Copy so we don't give the canonical type a name.  */
16176   result = build_variant_type_copy (result);
16177
16178   add_builtin_type (name, result);
16179
16180   return result;
16181 }
16182
16183 static void
16184 rs6000_init_builtins (void)
16185 {
16186   tree tdecl;
16187   tree ftype;
16188   machine_mode mode;
16189
16190   if (TARGET_DEBUG_BUILTIN)
16191     fprintf (stderr, "rs6000_init_builtins%s%s\n",
16192              (TARGET_ALTIVEC)      ? ", altivec" : "",
16193              (TARGET_VSX)          ? ", vsx"     : "");
16194
16195   V2DI_type_node = rs6000_vector_type (TARGET_POWERPC64 ? "__vector long"
16196                                        : "__vector long long",
16197                                        intDI_type_node, 2);
16198   V2DF_type_node = rs6000_vector_type ("__vector double", double_type_node, 2);
16199   V4SI_type_node = rs6000_vector_type ("__vector signed int",
16200                                        intSI_type_node, 4);
16201   V4SF_type_node = rs6000_vector_type ("__vector float", float_type_node, 4);
16202   V8HI_type_node = rs6000_vector_type ("__vector signed short",
16203                                        intHI_type_node, 8);
16204   V16QI_type_node = rs6000_vector_type ("__vector signed char",
16205                                         intQI_type_node, 16);
16206
16207   unsigned_V16QI_type_node = rs6000_vector_type ("__vector unsigned char",
16208                                         unsigned_intQI_type_node, 16);
16209   unsigned_V8HI_type_node = rs6000_vector_type ("__vector unsigned short",
16210                                        unsigned_intHI_type_node, 8);
16211   unsigned_V4SI_type_node = rs6000_vector_type ("__vector unsigned int",
16212                                        unsigned_intSI_type_node, 4);
16213   unsigned_V2DI_type_node = rs6000_vector_type (TARGET_POWERPC64
16214                                        ? "__vector unsigned long"
16215                                        : "__vector unsigned long long",
16216                                        unsigned_intDI_type_node, 2);
16217
16218   opaque_V4SI_type_node = build_opaque_vector_type (intSI_type_node, 4);
16219
16220   const_str_type_node
16221     = build_pointer_type (build_qualified_type (char_type_node,
16222                                                 TYPE_QUAL_CONST));
16223
16224   /* We use V1TI mode as a special container to hold __int128_t items that
16225      must live in VSX registers.  */
16226   if (intTI_type_node)
16227     {
16228       V1TI_type_node = rs6000_vector_type ("__vector __int128",
16229                                            intTI_type_node, 1);
16230       unsigned_V1TI_type_node
16231         = rs6000_vector_type ("__vector unsigned __int128",
16232                               unsigned_intTI_type_node, 1);
16233     }
16234
16235   /* The 'vector bool ...' types must be kept distinct from 'vector unsigned ...'
16236      types, especially in C++ land.  Similarly, 'vector pixel' is distinct from
16237      'vector unsigned short'.  */
16238
16239   bool_char_type_node = build_distinct_type_copy (unsigned_intQI_type_node);
16240   bool_short_type_node = build_distinct_type_copy (unsigned_intHI_type_node);
16241   bool_int_type_node = build_distinct_type_copy (unsigned_intSI_type_node);
16242   bool_long_long_type_node = build_distinct_type_copy (unsigned_intDI_type_node);
16243   pixel_type_node = build_distinct_type_copy (unsigned_intHI_type_node);
16244
16245   long_integer_type_internal_node = long_integer_type_node;
16246   long_unsigned_type_internal_node = long_unsigned_type_node;
16247   long_long_integer_type_internal_node = long_long_integer_type_node;
16248   long_long_unsigned_type_internal_node = long_long_unsigned_type_node;
16249   intQI_type_internal_node = intQI_type_node;
16250   uintQI_type_internal_node = unsigned_intQI_type_node;
16251   intHI_type_internal_node = intHI_type_node;
16252   uintHI_type_internal_node = unsigned_intHI_type_node;
16253   intSI_type_internal_node = intSI_type_node;
16254   uintSI_type_internal_node = unsigned_intSI_type_node;
16255   intDI_type_internal_node = intDI_type_node;
16256   uintDI_type_internal_node = unsigned_intDI_type_node;
16257   intTI_type_internal_node = intTI_type_node;
16258   uintTI_type_internal_node = unsigned_intTI_type_node;
16259   float_type_internal_node = float_type_node;
16260   double_type_internal_node = double_type_node;
16261   long_double_type_internal_node = long_double_type_node;
16262   dfloat64_type_internal_node = dfloat64_type_node;
16263   dfloat128_type_internal_node = dfloat128_type_node;
16264   void_type_internal_node = void_type_node;
16265
16266   /* 128-bit floating point support.  KFmode is IEEE 128-bit floating point.
16267      IFmode is the IBM extended 128-bit format that is a pair of doubles.
16268      TFmode will be either IEEE 128-bit floating point or the IBM double-double
16269      format that uses a pair of doubles, depending on the switches and
16270      defaults.
16271
16272      If we don't support for either 128-bit IBM double double or IEEE 128-bit
16273      floating point, we need make sure the type is non-zero or else self-test
16274      fails during bootstrap.
16275
16276      Always create __ibm128 as a separate type, even if the current long double
16277      format is IBM extended double.
16278
16279      For IEEE 128-bit floating point, always create the type __ieee128.  If the
16280      user used -mfloat128, rs6000-c.c will create a define from __float128 to
16281      __ieee128.  */
16282   if (TARGET_FLOAT128_TYPE)
16283     {
16284       if (!TARGET_IEEEQUAD && TARGET_LONG_DOUBLE_128)
16285         ibm128_float_type_node = long_double_type_node;
16286       else
16287         {
16288           ibm128_float_type_node = make_node (REAL_TYPE);
16289           TYPE_PRECISION (ibm128_float_type_node) = 128;
16290           SET_TYPE_MODE (ibm128_float_type_node, IFmode);
16291           layout_type (ibm128_float_type_node);
16292         }
16293
16294       lang_hooks.types.register_builtin_type (ibm128_float_type_node,
16295                                               "__ibm128");
16296
16297       if (TARGET_IEEEQUAD && TARGET_LONG_DOUBLE_128)
16298         ieee128_float_type_node = long_double_type_node;
16299       else
16300         ieee128_float_type_node = float128_type_node;
16301
16302       lang_hooks.types.register_builtin_type (ieee128_float_type_node,
16303                                               "__ieee128");
16304     }
16305
16306   else
16307     ieee128_float_type_node = ibm128_float_type_node = long_double_type_node;
16308
16309   /* Initialize the modes for builtin_function_type, mapping a machine mode to
16310      tree type node.  */
16311   builtin_mode_to_type[QImode][0] = integer_type_node;
16312   builtin_mode_to_type[HImode][0] = integer_type_node;
16313   builtin_mode_to_type[SImode][0] = intSI_type_node;
16314   builtin_mode_to_type[SImode][1] = unsigned_intSI_type_node;
16315   builtin_mode_to_type[DImode][0] = intDI_type_node;
16316   builtin_mode_to_type[DImode][1] = unsigned_intDI_type_node;
16317   builtin_mode_to_type[TImode][0] = intTI_type_node;
16318   builtin_mode_to_type[TImode][1] = unsigned_intTI_type_node;
16319   builtin_mode_to_type[SFmode][0] = float_type_node;
16320   builtin_mode_to_type[DFmode][0] = double_type_node;
16321   builtin_mode_to_type[IFmode][0] = ibm128_float_type_node;
16322   builtin_mode_to_type[KFmode][0] = ieee128_float_type_node;
16323   builtin_mode_to_type[TFmode][0] = long_double_type_node;
16324   builtin_mode_to_type[DDmode][0] = dfloat64_type_node;
16325   builtin_mode_to_type[TDmode][0] = dfloat128_type_node;
16326   builtin_mode_to_type[V1TImode][0] = V1TI_type_node;
16327   builtin_mode_to_type[V1TImode][1] = unsigned_V1TI_type_node;
16328   builtin_mode_to_type[V2DImode][0] = V2DI_type_node;
16329   builtin_mode_to_type[V2DImode][1] = unsigned_V2DI_type_node;
16330   builtin_mode_to_type[V2DFmode][0] = V2DF_type_node;
16331   builtin_mode_to_type[V4SImode][0] = V4SI_type_node;
16332   builtin_mode_to_type[V4SImode][1] = unsigned_V4SI_type_node;
16333   builtin_mode_to_type[V4SFmode][0] = V4SF_type_node;
16334   builtin_mode_to_type[V8HImode][0] = V8HI_type_node;
16335   builtin_mode_to_type[V8HImode][1] = unsigned_V8HI_type_node;
16336   builtin_mode_to_type[V16QImode][0] = V16QI_type_node;
16337   builtin_mode_to_type[V16QImode][1] = unsigned_V16QI_type_node;
16338
16339   tdecl = add_builtin_type ("__bool char", bool_char_type_node);
16340   TYPE_NAME (bool_char_type_node) = tdecl;
16341
16342   tdecl = add_builtin_type ("__bool short", bool_short_type_node);
16343   TYPE_NAME (bool_short_type_node) = tdecl;
16344
16345   tdecl = add_builtin_type ("__bool int", bool_int_type_node);
16346   TYPE_NAME (bool_int_type_node) = tdecl;
16347
16348   tdecl = add_builtin_type ("__pixel", pixel_type_node);
16349   TYPE_NAME (pixel_type_node) = tdecl;
16350
16351   bool_V16QI_type_node = rs6000_vector_type ("__vector __bool char",
16352                                              bool_char_type_node, 16);
16353   bool_V8HI_type_node = rs6000_vector_type ("__vector __bool short",
16354                                             bool_short_type_node, 8);
16355   bool_V4SI_type_node = rs6000_vector_type ("__vector __bool int",
16356                                             bool_int_type_node, 4);
16357   bool_V2DI_type_node = rs6000_vector_type (TARGET_POWERPC64
16358                                             ? "__vector __bool long"
16359                                             : "__vector __bool long long",
16360                                             bool_long_long_type_node, 2);
16361   pixel_V8HI_type_node = rs6000_vector_type ("__vector __pixel",
16362                                              pixel_type_node, 8);
16363
16364   /* Create Altivec and VSX builtins on machines with at least the
16365      general purpose extensions (970 and newer) to allow the use of
16366      the target attribute.  */
16367   if (TARGET_EXTRA_BUILTINS)
16368     altivec_init_builtins ();
16369   if (TARGET_HTM)
16370     htm_init_builtins ();
16371
16372   if (TARGET_EXTRA_BUILTINS)
16373     rs6000_common_init_builtins ();
16374
16375   ftype = builtin_function_type (DFmode, DFmode, DFmode, VOIDmode,
16376                                  RS6000_BUILTIN_RECIP, "__builtin_recipdiv");
16377   def_builtin ("__builtin_recipdiv", ftype, RS6000_BUILTIN_RECIP);
16378
16379   ftype = builtin_function_type (SFmode, SFmode, SFmode, VOIDmode,
16380                                  RS6000_BUILTIN_RECIPF, "__builtin_recipdivf");
16381   def_builtin ("__builtin_recipdivf", ftype, RS6000_BUILTIN_RECIPF);
16382
16383   ftype = builtin_function_type (DFmode, DFmode, VOIDmode, VOIDmode,
16384                                  RS6000_BUILTIN_RSQRT, "__builtin_rsqrt");
16385   def_builtin ("__builtin_rsqrt", ftype, RS6000_BUILTIN_RSQRT);
16386
16387   ftype = builtin_function_type (SFmode, SFmode, VOIDmode, VOIDmode,
16388                                  RS6000_BUILTIN_RSQRTF, "__builtin_rsqrtf");
16389   def_builtin ("__builtin_rsqrtf", ftype, RS6000_BUILTIN_RSQRTF);
16390
16391   mode = (TARGET_64BIT) ? DImode : SImode;
16392   ftype = builtin_function_type (mode, mode, mode, VOIDmode,
16393                                  POWER7_BUILTIN_BPERMD, "__builtin_bpermd");
16394   def_builtin ("__builtin_bpermd", ftype, POWER7_BUILTIN_BPERMD);
16395
16396   ftype = build_function_type_list (unsigned_intDI_type_node,
16397                                     NULL_TREE);
16398   def_builtin ("__builtin_ppc_get_timebase", ftype, RS6000_BUILTIN_GET_TB);
16399
16400   if (TARGET_64BIT)
16401     ftype = build_function_type_list (unsigned_intDI_type_node,
16402                                       NULL_TREE);
16403   else
16404     ftype = build_function_type_list (unsigned_intSI_type_node,
16405                                       NULL_TREE);
16406   def_builtin ("__builtin_ppc_mftb", ftype, RS6000_BUILTIN_MFTB);
16407
16408   ftype = build_function_type_list (double_type_node, NULL_TREE);
16409   def_builtin ("__builtin_mffs", ftype, RS6000_BUILTIN_MFFS);
16410
16411   ftype = build_function_type_list (double_type_node, NULL_TREE);
16412   def_builtin ("__builtin_mffsl", ftype, RS6000_BUILTIN_MFFSL);
16413
16414   ftype = build_function_type_list (void_type_node,
16415                                     intSI_type_node,
16416                                     NULL_TREE);
16417   def_builtin ("__builtin_mtfsb0", ftype, RS6000_BUILTIN_MTFSB0);
16418
16419   ftype = build_function_type_list (void_type_node,
16420                                     intSI_type_node,
16421                                     NULL_TREE);
16422   def_builtin ("__builtin_mtfsb1", ftype, RS6000_BUILTIN_MTFSB1);
16423
16424   ftype = build_function_type_list (void_type_node,
16425                                     intDI_type_node,
16426                                     NULL_TREE);
16427   def_builtin ("__builtin_set_fpscr_rn", ftype, RS6000_BUILTIN_SET_FPSCR_RN);
16428
16429   ftype = build_function_type_list (void_type_node,
16430                                     intDI_type_node,
16431                                     NULL_TREE);
16432   def_builtin ("__builtin_set_fpscr_drn", ftype, RS6000_BUILTIN_SET_FPSCR_DRN);
16433
16434   ftype = build_function_type_list (void_type_node,
16435                                     intSI_type_node, double_type_node,
16436                                     NULL_TREE);
16437   def_builtin ("__builtin_mtfsf", ftype, RS6000_BUILTIN_MTFSF);
16438
16439   ftype = build_function_type_list (void_type_node, NULL_TREE);
16440   def_builtin ("__builtin_cpu_init", ftype, RS6000_BUILTIN_CPU_INIT);
16441   def_builtin ("__builtin_ppc_speculation_barrier", ftype,
16442                MISC_BUILTIN_SPEC_BARRIER);
16443
16444   ftype = build_function_type_list (bool_int_type_node, const_ptr_type_node,
16445                                     NULL_TREE);
16446   def_builtin ("__builtin_cpu_is", ftype, RS6000_BUILTIN_CPU_IS);
16447   def_builtin ("__builtin_cpu_supports", ftype, RS6000_BUILTIN_CPU_SUPPORTS);
16448
16449   /* AIX libm provides clog as __clog.  */
16450   if (TARGET_XCOFF &&
16451       (tdecl = builtin_decl_explicit (BUILT_IN_CLOG)) != NULL_TREE)
16452     set_user_assembler_name (tdecl, "__clog");
16453
16454 #ifdef SUBTARGET_INIT_BUILTINS
16455   SUBTARGET_INIT_BUILTINS;
16456 #endif
16457 }
16458
16459 /* Returns the rs6000 builtin decl for CODE.  */
16460
16461 static tree
16462 rs6000_builtin_decl (unsigned code, bool initialize_p ATTRIBUTE_UNUSED)
16463 {
16464   HOST_WIDE_INT fnmask;
16465
16466   if (code >= RS6000_BUILTIN_COUNT)
16467     return error_mark_node;
16468
16469   fnmask = rs6000_builtin_info[code].mask;
16470   if ((fnmask & rs6000_builtin_mask) != fnmask)
16471     {
16472       rs6000_invalid_builtin ((enum rs6000_builtins)code);
16473       return error_mark_node;
16474     }
16475
16476   return rs6000_builtin_decls[code];
16477 }
16478
16479 static void
16480 altivec_init_builtins (void)
16481 {
16482   const struct builtin_description *d;
16483   size_t i;
16484   tree ftype;
16485   tree decl;
16486   HOST_WIDE_INT builtin_mask = rs6000_builtin_mask;
16487
16488   tree pvoid_type_node = build_pointer_type (void_type_node);
16489
16490   tree pcvoid_type_node
16491     = build_pointer_type (build_qualified_type (void_type_node,
16492                                                 TYPE_QUAL_CONST));
16493
16494   tree int_ftype_opaque
16495     = build_function_type_list (integer_type_node,
16496                                 opaque_V4SI_type_node, NULL_TREE);
16497   tree opaque_ftype_opaque
16498     = build_function_type_list (integer_type_node, NULL_TREE);
16499   tree opaque_ftype_opaque_int
16500     = build_function_type_list (opaque_V4SI_type_node,
16501                                 opaque_V4SI_type_node, integer_type_node, NULL_TREE);
16502   tree opaque_ftype_opaque_opaque_int
16503     = build_function_type_list (opaque_V4SI_type_node,
16504                                 opaque_V4SI_type_node, opaque_V4SI_type_node,
16505                                 integer_type_node, NULL_TREE);
16506   tree opaque_ftype_opaque_opaque_opaque
16507     = build_function_type_list (opaque_V4SI_type_node,
16508                                 opaque_V4SI_type_node, opaque_V4SI_type_node,
16509                                 opaque_V4SI_type_node, NULL_TREE);
16510   tree opaque_ftype_opaque_opaque
16511     = build_function_type_list (opaque_V4SI_type_node,
16512                                 opaque_V4SI_type_node, opaque_V4SI_type_node,
16513                                 NULL_TREE);
16514   tree int_ftype_int_opaque_opaque
16515     = build_function_type_list (integer_type_node,
16516                                 integer_type_node, opaque_V4SI_type_node,
16517                                 opaque_V4SI_type_node, NULL_TREE);
16518   tree int_ftype_int_v4si_v4si
16519     = build_function_type_list (integer_type_node,
16520                                 integer_type_node, V4SI_type_node,
16521                                 V4SI_type_node, NULL_TREE);
16522   tree int_ftype_int_v2di_v2di
16523     = build_function_type_list (integer_type_node,
16524                                 integer_type_node, V2DI_type_node,
16525                                 V2DI_type_node, NULL_TREE);
16526   tree void_ftype_v4si
16527     = build_function_type_list (void_type_node, V4SI_type_node, NULL_TREE);
16528   tree v8hi_ftype_void
16529     = build_function_type_list (V8HI_type_node, NULL_TREE);
16530   tree void_ftype_void
16531     = build_function_type_list (void_type_node, NULL_TREE);
16532   tree void_ftype_int
16533     = build_function_type_list (void_type_node, integer_type_node, NULL_TREE);
16534
16535   tree opaque_ftype_long_pcvoid
16536     = build_function_type_list (opaque_V4SI_type_node,
16537                                 long_integer_type_node, pcvoid_type_node,
16538                                 NULL_TREE);
16539   tree v16qi_ftype_long_pcvoid
16540     = build_function_type_list (V16QI_type_node,
16541                                 long_integer_type_node, pcvoid_type_node,
16542                                 NULL_TREE);
16543   tree v8hi_ftype_long_pcvoid
16544     = build_function_type_list (V8HI_type_node,
16545                                 long_integer_type_node, pcvoid_type_node,
16546                                 NULL_TREE);
16547   tree v4si_ftype_long_pcvoid
16548     = build_function_type_list (V4SI_type_node,
16549                                 long_integer_type_node, pcvoid_type_node,
16550                                 NULL_TREE);
16551   tree v4sf_ftype_long_pcvoid
16552     = build_function_type_list (V4SF_type_node,
16553                                 long_integer_type_node, pcvoid_type_node,
16554                                 NULL_TREE);
16555   tree v2df_ftype_long_pcvoid
16556     = build_function_type_list (V2DF_type_node,
16557                                 long_integer_type_node, pcvoid_type_node,
16558                                 NULL_TREE);
16559   tree v2di_ftype_long_pcvoid
16560     = build_function_type_list (V2DI_type_node,
16561                                 long_integer_type_node, pcvoid_type_node,
16562                                 NULL_TREE);
16563   tree v1ti_ftype_long_pcvoid
16564     = build_function_type_list (V1TI_type_node,
16565                                 long_integer_type_node, pcvoid_type_node,
16566                                 NULL_TREE);
16567
16568   tree void_ftype_opaque_long_pvoid
16569     = build_function_type_list (void_type_node,
16570                                 opaque_V4SI_type_node, long_integer_type_node,
16571                                 pvoid_type_node, NULL_TREE);
16572   tree void_ftype_v4si_long_pvoid
16573     = build_function_type_list (void_type_node,
16574                                 V4SI_type_node, long_integer_type_node,
16575                                 pvoid_type_node, NULL_TREE);
16576   tree void_ftype_v16qi_long_pvoid
16577     = build_function_type_list (void_type_node,
16578                                 V16QI_type_node, long_integer_type_node,
16579                                 pvoid_type_node, NULL_TREE);
16580
16581   tree void_ftype_v16qi_pvoid_long
16582     = build_function_type_list (void_type_node,
16583                                 V16QI_type_node, pvoid_type_node,
16584                                 long_integer_type_node, NULL_TREE);
16585
16586   tree void_ftype_v8hi_long_pvoid
16587     = build_function_type_list (void_type_node,
16588                                 V8HI_type_node, long_integer_type_node,
16589                                 pvoid_type_node, NULL_TREE);
16590   tree void_ftype_v4sf_long_pvoid
16591     = build_function_type_list (void_type_node,
16592                                 V4SF_type_node, long_integer_type_node,
16593                                 pvoid_type_node, NULL_TREE);
16594   tree void_ftype_v2df_long_pvoid
16595     = build_function_type_list (void_type_node,
16596                                 V2DF_type_node, long_integer_type_node,
16597                                 pvoid_type_node, NULL_TREE);
16598   tree void_ftype_v1ti_long_pvoid
16599     = build_function_type_list (void_type_node,
16600                                 V1TI_type_node, long_integer_type_node,
16601                                 pvoid_type_node, NULL_TREE);
16602   tree void_ftype_v2di_long_pvoid
16603     = build_function_type_list (void_type_node,
16604                                 V2DI_type_node, long_integer_type_node,
16605                                 pvoid_type_node, NULL_TREE);
16606   tree int_ftype_int_v8hi_v8hi
16607     = build_function_type_list (integer_type_node,
16608                                 integer_type_node, V8HI_type_node,
16609                                 V8HI_type_node, NULL_TREE);
16610   tree int_ftype_int_v16qi_v16qi
16611     = build_function_type_list (integer_type_node,
16612                                 integer_type_node, V16QI_type_node,
16613                                 V16QI_type_node, NULL_TREE);
16614   tree int_ftype_int_v4sf_v4sf
16615     = build_function_type_list (integer_type_node,
16616                                 integer_type_node, V4SF_type_node,
16617                                 V4SF_type_node, NULL_TREE);
16618   tree int_ftype_int_v2df_v2df
16619     = build_function_type_list (integer_type_node,
16620                                 integer_type_node, V2DF_type_node,
16621                                 V2DF_type_node, NULL_TREE);
16622   tree v2di_ftype_v2di
16623     = build_function_type_list (V2DI_type_node, V2DI_type_node, NULL_TREE);
16624   tree v4si_ftype_v4si
16625     = build_function_type_list (V4SI_type_node, V4SI_type_node, NULL_TREE);
16626   tree v8hi_ftype_v8hi
16627     = build_function_type_list (V8HI_type_node, V8HI_type_node, NULL_TREE);
16628   tree v16qi_ftype_v16qi
16629     = build_function_type_list (V16QI_type_node, V16QI_type_node, NULL_TREE);
16630   tree v4sf_ftype_v4sf
16631     = build_function_type_list (V4SF_type_node, V4SF_type_node, NULL_TREE);
16632   tree v2df_ftype_v2df
16633     = build_function_type_list (V2DF_type_node, V2DF_type_node, NULL_TREE);
16634   tree void_ftype_pcvoid_int_int
16635     = build_function_type_list (void_type_node,
16636                                 pcvoid_type_node, integer_type_node,
16637                                 integer_type_node, NULL_TREE);
16638
16639   def_builtin ("__builtin_altivec_mtvscr", void_ftype_v4si, ALTIVEC_BUILTIN_MTVSCR);
16640   def_builtin ("__builtin_altivec_mfvscr", v8hi_ftype_void, ALTIVEC_BUILTIN_MFVSCR);
16641   def_builtin ("__builtin_altivec_dssall", void_ftype_void, ALTIVEC_BUILTIN_DSSALL);
16642   def_builtin ("__builtin_altivec_dss", void_ftype_int, ALTIVEC_BUILTIN_DSS);
16643   def_builtin ("__builtin_altivec_lvsl", v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVSL);
16644   def_builtin ("__builtin_altivec_lvsr", v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVSR);
16645   def_builtin ("__builtin_altivec_lvebx", v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVEBX);
16646   def_builtin ("__builtin_altivec_lvehx", v8hi_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVEHX);
16647   def_builtin ("__builtin_altivec_lvewx", v4si_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVEWX);
16648   def_builtin ("__builtin_altivec_lvxl", v4si_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVXL);
16649   def_builtin ("__builtin_altivec_lvxl_v2df", v2df_ftype_long_pcvoid,
16650                ALTIVEC_BUILTIN_LVXL_V2DF);
16651   def_builtin ("__builtin_altivec_lvxl_v2di", v2di_ftype_long_pcvoid,
16652                ALTIVEC_BUILTIN_LVXL_V2DI);
16653   def_builtin ("__builtin_altivec_lvxl_v4sf", v4sf_ftype_long_pcvoid,
16654                ALTIVEC_BUILTIN_LVXL_V4SF);
16655   def_builtin ("__builtin_altivec_lvxl_v4si", v4si_ftype_long_pcvoid,
16656                ALTIVEC_BUILTIN_LVXL_V4SI);
16657   def_builtin ("__builtin_altivec_lvxl_v8hi", v8hi_ftype_long_pcvoid,
16658                ALTIVEC_BUILTIN_LVXL_V8HI);
16659   def_builtin ("__builtin_altivec_lvxl_v16qi", v16qi_ftype_long_pcvoid,
16660                ALTIVEC_BUILTIN_LVXL_V16QI);
16661   def_builtin ("__builtin_altivec_lvx", v4si_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVX);
16662   def_builtin ("__builtin_altivec_lvx_v1ti", v1ti_ftype_long_pcvoid,
16663                ALTIVEC_BUILTIN_LVX_V1TI);
16664   def_builtin ("__builtin_altivec_lvx_v2df", v2df_ftype_long_pcvoid,
16665                ALTIVEC_BUILTIN_LVX_V2DF);
16666   def_builtin ("__builtin_altivec_lvx_v2di", v2di_ftype_long_pcvoid,
16667                ALTIVEC_BUILTIN_LVX_V2DI);
16668   def_builtin ("__builtin_altivec_lvx_v4sf", v4sf_ftype_long_pcvoid,
16669                ALTIVEC_BUILTIN_LVX_V4SF);
16670   def_builtin ("__builtin_altivec_lvx_v4si", v4si_ftype_long_pcvoid,
16671                ALTIVEC_BUILTIN_LVX_V4SI);
16672   def_builtin ("__builtin_altivec_lvx_v8hi", v8hi_ftype_long_pcvoid,
16673                ALTIVEC_BUILTIN_LVX_V8HI);
16674   def_builtin ("__builtin_altivec_lvx_v16qi", v16qi_ftype_long_pcvoid,
16675                ALTIVEC_BUILTIN_LVX_V16QI);
16676   def_builtin ("__builtin_altivec_stvx", void_ftype_v4si_long_pvoid, ALTIVEC_BUILTIN_STVX);
16677   def_builtin ("__builtin_altivec_stvx_v2df", void_ftype_v2df_long_pvoid,
16678                ALTIVEC_BUILTIN_STVX_V2DF);
16679   def_builtin ("__builtin_altivec_stvx_v2di", void_ftype_v2di_long_pvoid,
16680                ALTIVEC_BUILTIN_STVX_V2DI);
16681   def_builtin ("__builtin_altivec_stvx_v4sf", void_ftype_v4sf_long_pvoid,
16682                ALTIVEC_BUILTIN_STVX_V4SF);
16683   def_builtin ("__builtin_altivec_stvx_v4si", void_ftype_v4si_long_pvoid,
16684                ALTIVEC_BUILTIN_STVX_V4SI);
16685   def_builtin ("__builtin_altivec_stvx_v8hi", void_ftype_v8hi_long_pvoid,
16686                ALTIVEC_BUILTIN_STVX_V8HI);
16687   def_builtin ("__builtin_altivec_stvx_v16qi", void_ftype_v16qi_long_pvoid,
16688                ALTIVEC_BUILTIN_STVX_V16QI);
16689   def_builtin ("__builtin_altivec_stvewx", void_ftype_v4si_long_pvoid, ALTIVEC_BUILTIN_STVEWX);
16690   def_builtin ("__builtin_altivec_stvxl", void_ftype_v4si_long_pvoid, ALTIVEC_BUILTIN_STVXL);
16691   def_builtin ("__builtin_altivec_stvxl_v2df", void_ftype_v2df_long_pvoid,
16692                ALTIVEC_BUILTIN_STVXL_V2DF);
16693   def_builtin ("__builtin_altivec_stvxl_v2di", void_ftype_v2di_long_pvoid,
16694                ALTIVEC_BUILTIN_STVXL_V2DI);
16695   def_builtin ("__builtin_altivec_stvxl_v4sf", void_ftype_v4sf_long_pvoid,
16696                ALTIVEC_BUILTIN_STVXL_V4SF);
16697   def_builtin ("__builtin_altivec_stvxl_v4si", void_ftype_v4si_long_pvoid,
16698                ALTIVEC_BUILTIN_STVXL_V4SI);
16699   def_builtin ("__builtin_altivec_stvxl_v8hi", void_ftype_v8hi_long_pvoid,
16700                ALTIVEC_BUILTIN_STVXL_V8HI);
16701   def_builtin ("__builtin_altivec_stvxl_v16qi", void_ftype_v16qi_long_pvoid,
16702                ALTIVEC_BUILTIN_STVXL_V16QI);
16703   def_builtin ("__builtin_altivec_stvebx", void_ftype_v16qi_long_pvoid, ALTIVEC_BUILTIN_STVEBX);
16704   def_builtin ("__builtin_altivec_stvehx", void_ftype_v8hi_long_pvoid, ALTIVEC_BUILTIN_STVEHX);
16705   def_builtin ("__builtin_vec_ld", opaque_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LD);
16706   def_builtin ("__builtin_vec_lde", opaque_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LDE);
16707   def_builtin ("__builtin_vec_ldl", opaque_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LDL);
16708   def_builtin ("__builtin_vec_lvsl", v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LVSL);
16709   def_builtin ("__builtin_vec_lvsr", v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LVSR);
16710   def_builtin ("__builtin_vec_lvebx", v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LVEBX);
16711   def_builtin ("__builtin_vec_lvehx", v8hi_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LVEHX);
16712   def_builtin ("__builtin_vec_lvewx", v4si_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LVEWX);
16713   def_builtin ("__builtin_vec_st", void_ftype_opaque_long_pvoid, ALTIVEC_BUILTIN_VEC_ST);
16714   def_builtin ("__builtin_vec_ste", void_ftype_opaque_long_pvoid, ALTIVEC_BUILTIN_VEC_STE);
16715   def_builtin ("__builtin_vec_stl", void_ftype_opaque_long_pvoid, ALTIVEC_BUILTIN_VEC_STL);
16716   def_builtin ("__builtin_vec_stvewx", void_ftype_opaque_long_pvoid, ALTIVEC_BUILTIN_VEC_STVEWX);
16717   def_builtin ("__builtin_vec_stvebx", void_ftype_opaque_long_pvoid, ALTIVEC_BUILTIN_VEC_STVEBX);
16718   def_builtin ("__builtin_vec_stvehx", void_ftype_opaque_long_pvoid, ALTIVEC_BUILTIN_VEC_STVEHX);
16719
16720   def_builtin ("__builtin_vsx_lxvd2x_v2df", v2df_ftype_long_pcvoid,
16721                VSX_BUILTIN_LXVD2X_V2DF);
16722   def_builtin ("__builtin_vsx_lxvd2x_v2di", v2di_ftype_long_pcvoid,
16723                VSX_BUILTIN_LXVD2X_V2DI);
16724   def_builtin ("__builtin_vsx_lxvw4x_v4sf", v4sf_ftype_long_pcvoid,
16725                VSX_BUILTIN_LXVW4X_V4SF);
16726   def_builtin ("__builtin_vsx_lxvw4x_v4si", v4si_ftype_long_pcvoid,
16727                VSX_BUILTIN_LXVW4X_V4SI);
16728   def_builtin ("__builtin_vsx_lxvw4x_v8hi", v8hi_ftype_long_pcvoid,
16729                VSX_BUILTIN_LXVW4X_V8HI);
16730   def_builtin ("__builtin_vsx_lxvw4x_v16qi", v16qi_ftype_long_pcvoid,
16731                VSX_BUILTIN_LXVW4X_V16QI);
16732   def_builtin ("__builtin_vsx_stxvd2x_v2df", void_ftype_v2df_long_pvoid,
16733                VSX_BUILTIN_STXVD2X_V2DF);
16734   def_builtin ("__builtin_vsx_stxvd2x_v2di", void_ftype_v2di_long_pvoid,
16735                VSX_BUILTIN_STXVD2X_V2DI);
16736   def_builtin ("__builtin_vsx_stxvw4x_v4sf", void_ftype_v4sf_long_pvoid,
16737                VSX_BUILTIN_STXVW4X_V4SF);
16738   def_builtin ("__builtin_vsx_stxvw4x_v4si", void_ftype_v4si_long_pvoid,
16739                VSX_BUILTIN_STXVW4X_V4SI);
16740   def_builtin ("__builtin_vsx_stxvw4x_v8hi", void_ftype_v8hi_long_pvoid,
16741                VSX_BUILTIN_STXVW4X_V8HI);
16742   def_builtin ("__builtin_vsx_stxvw4x_v16qi", void_ftype_v16qi_long_pvoid,
16743                VSX_BUILTIN_STXVW4X_V16QI);
16744
16745   def_builtin ("__builtin_vsx_ld_elemrev_v2df", v2df_ftype_long_pcvoid,
16746                VSX_BUILTIN_LD_ELEMREV_V2DF);
16747   def_builtin ("__builtin_vsx_ld_elemrev_v2di", v2di_ftype_long_pcvoid,
16748                VSX_BUILTIN_LD_ELEMREV_V2DI);
16749   def_builtin ("__builtin_vsx_ld_elemrev_v4sf", v4sf_ftype_long_pcvoid,
16750                VSX_BUILTIN_LD_ELEMREV_V4SF);
16751   def_builtin ("__builtin_vsx_ld_elemrev_v4si", v4si_ftype_long_pcvoid,
16752                VSX_BUILTIN_LD_ELEMREV_V4SI);
16753   def_builtin ("__builtin_vsx_ld_elemrev_v8hi", v8hi_ftype_long_pcvoid,
16754                VSX_BUILTIN_LD_ELEMREV_V8HI);
16755   def_builtin ("__builtin_vsx_ld_elemrev_v16qi", v16qi_ftype_long_pcvoid,
16756                VSX_BUILTIN_LD_ELEMREV_V16QI);
16757   def_builtin ("__builtin_vsx_st_elemrev_v2df", void_ftype_v2df_long_pvoid,
16758                VSX_BUILTIN_ST_ELEMREV_V2DF);
16759   def_builtin ("__builtin_vsx_st_elemrev_v1ti", void_ftype_v1ti_long_pvoid,
16760                VSX_BUILTIN_ST_ELEMREV_V1TI);
16761   def_builtin ("__builtin_vsx_st_elemrev_v2di", void_ftype_v2di_long_pvoid,
16762                VSX_BUILTIN_ST_ELEMREV_V2DI);
16763   def_builtin ("__builtin_vsx_st_elemrev_v4sf", void_ftype_v4sf_long_pvoid,
16764                VSX_BUILTIN_ST_ELEMREV_V4SF);
16765   def_builtin ("__builtin_vsx_st_elemrev_v4si", void_ftype_v4si_long_pvoid,
16766                VSX_BUILTIN_ST_ELEMREV_V4SI);
16767   def_builtin ("__builtin_vsx_st_elemrev_v8hi", void_ftype_v8hi_long_pvoid,
16768                VSX_BUILTIN_ST_ELEMREV_V8HI);
16769   def_builtin ("__builtin_vsx_st_elemrev_v16qi", void_ftype_v16qi_long_pvoid,
16770                VSX_BUILTIN_ST_ELEMREV_V16QI);
16771
16772   def_builtin ("__builtin_vec_vsx_ld", opaque_ftype_long_pcvoid,
16773                VSX_BUILTIN_VEC_LD);
16774   def_builtin ("__builtin_vec_vsx_st", void_ftype_opaque_long_pvoid,
16775                VSX_BUILTIN_VEC_ST);
16776   def_builtin ("__builtin_vec_xl", opaque_ftype_long_pcvoid,
16777                VSX_BUILTIN_VEC_XL);
16778   def_builtin ("__builtin_vec_xl_be", opaque_ftype_long_pcvoid,
16779                VSX_BUILTIN_VEC_XL_BE);
16780   def_builtin ("__builtin_vec_xst", void_ftype_opaque_long_pvoid,
16781                VSX_BUILTIN_VEC_XST);
16782   def_builtin ("__builtin_vec_xst_be", void_ftype_opaque_long_pvoid,
16783                VSX_BUILTIN_VEC_XST_BE);
16784
16785   def_builtin ("__builtin_vec_step", int_ftype_opaque, ALTIVEC_BUILTIN_VEC_STEP);
16786   def_builtin ("__builtin_vec_splats", opaque_ftype_opaque, ALTIVEC_BUILTIN_VEC_SPLATS);
16787   def_builtin ("__builtin_vec_promote", opaque_ftype_opaque, ALTIVEC_BUILTIN_VEC_PROMOTE);
16788
16789   def_builtin ("__builtin_vec_sld", opaque_ftype_opaque_opaque_int, ALTIVEC_BUILTIN_VEC_SLD);
16790   def_builtin ("__builtin_vec_splat", opaque_ftype_opaque_int, ALTIVEC_BUILTIN_VEC_SPLAT);
16791   def_builtin ("__builtin_vec_extract", opaque_ftype_opaque_int, ALTIVEC_BUILTIN_VEC_EXTRACT);
16792   def_builtin ("__builtin_vec_insert", opaque_ftype_opaque_opaque_int, ALTIVEC_BUILTIN_VEC_INSERT);
16793   def_builtin ("__builtin_vec_vspltw", opaque_ftype_opaque_int, ALTIVEC_BUILTIN_VEC_VSPLTW);
16794   def_builtin ("__builtin_vec_vsplth", opaque_ftype_opaque_int, ALTIVEC_BUILTIN_VEC_VSPLTH);
16795   def_builtin ("__builtin_vec_vspltb", opaque_ftype_opaque_int, ALTIVEC_BUILTIN_VEC_VSPLTB);
16796   def_builtin ("__builtin_vec_ctf", opaque_ftype_opaque_int, ALTIVEC_BUILTIN_VEC_CTF);
16797   def_builtin ("__builtin_vec_vcfsx", opaque_ftype_opaque_int, ALTIVEC_BUILTIN_VEC_VCFSX);
16798   def_builtin ("__builtin_vec_vcfux", opaque_ftype_opaque_int, ALTIVEC_BUILTIN_VEC_VCFUX);
16799   def_builtin ("__builtin_vec_cts", opaque_ftype_opaque_int, ALTIVEC_BUILTIN_VEC_CTS);
16800   def_builtin ("__builtin_vec_ctu", opaque_ftype_opaque_int, ALTIVEC_BUILTIN_VEC_CTU);
16801
16802   def_builtin ("__builtin_vec_adde", opaque_ftype_opaque_opaque_opaque,
16803                 ALTIVEC_BUILTIN_VEC_ADDE);
16804   def_builtin ("__builtin_vec_addec", opaque_ftype_opaque_opaque_opaque,
16805                 ALTIVEC_BUILTIN_VEC_ADDEC);
16806   def_builtin ("__builtin_vec_cmpne", opaque_ftype_opaque_opaque,
16807                 ALTIVEC_BUILTIN_VEC_CMPNE);
16808   def_builtin ("__builtin_vec_mul", opaque_ftype_opaque_opaque,
16809                 ALTIVEC_BUILTIN_VEC_MUL);
16810   def_builtin ("__builtin_vec_sube", opaque_ftype_opaque_opaque_opaque,
16811                 ALTIVEC_BUILTIN_VEC_SUBE);
16812   def_builtin ("__builtin_vec_subec", opaque_ftype_opaque_opaque_opaque,
16813                 ALTIVEC_BUILTIN_VEC_SUBEC);
16814
16815   /* Cell builtins.  */
16816   def_builtin ("__builtin_altivec_lvlx",  v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVLX);
16817   def_builtin ("__builtin_altivec_lvlxl", v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVLXL);
16818   def_builtin ("__builtin_altivec_lvrx",  v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVRX);
16819   def_builtin ("__builtin_altivec_lvrxl", v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_LVRXL);
16820
16821   def_builtin ("__builtin_vec_lvlx",  v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LVLX);
16822   def_builtin ("__builtin_vec_lvlxl", v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LVLXL);
16823   def_builtin ("__builtin_vec_lvrx",  v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LVRX);
16824   def_builtin ("__builtin_vec_lvrxl", v16qi_ftype_long_pcvoid, ALTIVEC_BUILTIN_VEC_LVRXL);
16825
16826   def_builtin ("__builtin_altivec_stvlx",  void_ftype_v16qi_long_pvoid, ALTIVEC_BUILTIN_STVLX);
16827   def_builtin ("__builtin_altivec_stvlxl", void_ftype_v16qi_long_pvoid, ALTIVEC_BUILTIN_STVLXL);
16828   def_builtin ("__builtin_altivec_stvrx",  void_ftype_v16qi_long_pvoid, ALTIVEC_BUILTIN_STVRX);
16829   def_builtin ("__builtin_altivec_stvrxl", void_ftype_v16qi_long_pvoid, ALTIVEC_BUILTIN_STVRXL);
16830
16831   def_builtin ("__builtin_vec_stvlx",  void_ftype_v16qi_long_pvoid, ALTIVEC_BUILTIN_VEC_STVLX);
16832   def_builtin ("__builtin_vec_stvlxl", void_ftype_v16qi_long_pvoid, ALTIVEC_BUILTIN_VEC_STVLXL);
16833   def_builtin ("__builtin_vec_stvrx",  void_ftype_v16qi_long_pvoid, ALTIVEC_BUILTIN_VEC_STVRX);
16834   def_builtin ("__builtin_vec_stvrxl", void_ftype_v16qi_long_pvoid, ALTIVEC_BUILTIN_VEC_STVRXL);
16835
16836   if (TARGET_P9_VECTOR)
16837     {
16838       def_builtin ("__builtin_altivec_stxvl", void_ftype_v16qi_pvoid_long,
16839                    P9V_BUILTIN_STXVL);
16840       def_builtin ("__builtin_xst_len_r", void_ftype_v16qi_pvoid_long,
16841                    P9V_BUILTIN_XST_LEN_R);
16842     }
16843
16844   /* Add the DST variants.  */
16845   d = bdesc_dst;
16846   for (i = 0; i < ARRAY_SIZE (bdesc_dst); i++, d++)
16847     {
16848       HOST_WIDE_INT mask = d->mask;
16849
16850       /* It is expected that these dst built-in functions may have
16851          d->icode equal to CODE_FOR_nothing.  */
16852       if ((mask & builtin_mask) != mask)
16853         {
16854           if (TARGET_DEBUG_BUILTIN)
16855             fprintf (stderr, "altivec_init_builtins, skip dst %s\n",
16856                      d->name);
16857           continue;
16858         }
16859       def_builtin (d->name, void_ftype_pcvoid_int_int, d->code);
16860     }
16861
16862   /* Initialize the predicates.  */
16863   d = bdesc_altivec_preds;
16864   for (i = 0; i < ARRAY_SIZE (bdesc_altivec_preds); i++, d++)
16865     {
16866       machine_mode mode1;
16867       tree type;
16868       HOST_WIDE_INT mask = d->mask;
16869
16870       if ((mask & builtin_mask) != mask)
16871         {
16872           if (TARGET_DEBUG_BUILTIN)
16873             fprintf (stderr, "altivec_init_builtins, skip predicate %s\n",
16874                      d->name);
16875           continue;
16876         }
16877
16878       if (rs6000_overloaded_builtin_p (d->code))
16879         mode1 = VOIDmode;
16880       else
16881         {
16882           /* Cannot define builtin if the instruction is disabled.  */
16883           gcc_assert (d->icode != CODE_FOR_nothing);
16884           mode1 = insn_data[d->icode].operand[1].mode;
16885         }
16886
16887       switch (mode1)
16888         {
16889         case E_VOIDmode:
16890           type = int_ftype_int_opaque_opaque;
16891           break;
16892         case E_V2DImode:
16893           type = int_ftype_int_v2di_v2di;
16894           break;
16895         case E_V4SImode:
16896           type = int_ftype_int_v4si_v4si;
16897           break;
16898         case E_V8HImode:
16899           type = int_ftype_int_v8hi_v8hi;
16900           break;
16901         case E_V16QImode:
16902           type = int_ftype_int_v16qi_v16qi;
16903           break;
16904         case E_V4SFmode:
16905           type = int_ftype_int_v4sf_v4sf;
16906           break;
16907         case E_V2DFmode:
16908           type = int_ftype_int_v2df_v2df;
16909           break;
16910         default:
16911           gcc_unreachable ();
16912         }
16913
16914       def_builtin (d->name, type, d->code);
16915     }
16916
16917   /* Initialize the abs* operators.  */
16918   d = bdesc_abs;
16919   for (i = 0; i < ARRAY_SIZE (bdesc_abs); i++, d++)
16920     {
16921       machine_mode mode0;
16922       tree type;
16923       HOST_WIDE_INT mask = d->mask;
16924
16925       if ((mask & builtin_mask) != mask)
16926         {
16927           if (TARGET_DEBUG_BUILTIN)
16928             fprintf (stderr, "altivec_init_builtins, skip abs %s\n",
16929                      d->name);
16930           continue;
16931         }
16932
16933       /* Cannot define builtin if the instruction is disabled.  */
16934       gcc_assert (d->icode != CODE_FOR_nothing);
16935       mode0 = insn_data[d->icode].operand[0].mode;
16936
16937       switch (mode0)
16938         {
16939         case E_V2DImode:
16940           type = v2di_ftype_v2di;
16941           break;
16942         case E_V4SImode:
16943           type = v4si_ftype_v4si;
16944           break;
16945         case E_V8HImode:
16946           type = v8hi_ftype_v8hi;
16947           break;
16948         case E_V16QImode:
16949           type = v16qi_ftype_v16qi;
16950           break;
16951         case E_V4SFmode:
16952           type = v4sf_ftype_v4sf;
16953           break;
16954         case E_V2DFmode:
16955           type = v2df_ftype_v2df;
16956           break;
16957         default:
16958           gcc_unreachable ();
16959         }
16960
16961       def_builtin (d->name, type, d->code);
16962     }
16963
16964   /* Initialize target builtin that implements
16965      targetm.vectorize.builtin_mask_for_load.  */
16966
16967   decl = add_builtin_function ("__builtin_altivec_mask_for_load",
16968                                v16qi_ftype_long_pcvoid,
16969                                ALTIVEC_BUILTIN_MASK_FOR_LOAD,
16970                                BUILT_IN_MD, NULL, NULL_TREE);
16971   TREE_READONLY (decl) = 1;
16972   /* Record the decl. Will be used by rs6000_builtin_mask_for_load.  */
16973   altivec_builtin_mask_for_load = decl;
16974
16975   /* Access to the vec_init patterns.  */
16976   ftype = build_function_type_list (V4SI_type_node, integer_type_node,
16977                                     integer_type_node, integer_type_node,
16978                                     integer_type_node, NULL_TREE);
16979   def_builtin ("__builtin_vec_init_v4si", ftype, ALTIVEC_BUILTIN_VEC_INIT_V4SI);
16980
16981   ftype = build_function_type_list (V8HI_type_node, short_integer_type_node,
16982                                     short_integer_type_node,
16983                                     short_integer_type_node,
16984                                     short_integer_type_node,
16985                                     short_integer_type_node,
16986                                     short_integer_type_node,
16987                                     short_integer_type_node,
16988                                     short_integer_type_node, NULL_TREE);
16989   def_builtin ("__builtin_vec_init_v8hi", ftype, ALTIVEC_BUILTIN_VEC_INIT_V8HI);
16990
16991   ftype = build_function_type_list (V16QI_type_node, char_type_node,
16992                                     char_type_node, char_type_node,
16993                                     char_type_node, char_type_node,
16994                                     char_type_node, char_type_node,
16995                                     char_type_node, char_type_node,
16996                                     char_type_node, char_type_node,
16997                                     char_type_node, char_type_node,
16998                                     char_type_node, char_type_node,
16999                                     char_type_node, NULL_TREE);
17000   def_builtin ("__builtin_vec_init_v16qi", ftype,
17001                ALTIVEC_BUILTIN_VEC_INIT_V16QI);
17002
17003   ftype = build_function_type_list (V4SF_type_node, float_type_node,
17004                                     float_type_node, float_type_node,
17005                                     float_type_node, NULL_TREE);
17006   def_builtin ("__builtin_vec_init_v4sf", ftype, ALTIVEC_BUILTIN_VEC_INIT_V4SF);
17007
17008   /* VSX builtins.  */
17009   ftype = build_function_type_list (V2DF_type_node, double_type_node,
17010                                     double_type_node, NULL_TREE);
17011   def_builtin ("__builtin_vec_init_v2df", ftype, VSX_BUILTIN_VEC_INIT_V2DF);
17012
17013   ftype = build_function_type_list (V2DI_type_node, intDI_type_node,
17014                                     intDI_type_node, NULL_TREE);
17015   def_builtin ("__builtin_vec_init_v2di", ftype, VSX_BUILTIN_VEC_INIT_V2DI);
17016
17017   /* Access to the vec_set patterns.  */
17018   ftype = build_function_type_list (V4SI_type_node, V4SI_type_node,
17019                                     intSI_type_node,
17020                                     integer_type_node, NULL_TREE);
17021   def_builtin ("__builtin_vec_set_v4si", ftype, ALTIVEC_BUILTIN_VEC_SET_V4SI);
17022
17023   ftype = build_function_type_list (V8HI_type_node, V8HI_type_node,
17024                                     intHI_type_node,
17025                                     integer_type_node, NULL_TREE);
17026   def_builtin ("__builtin_vec_set_v8hi", ftype, ALTIVEC_BUILTIN_VEC_SET_V8HI);
17027
17028   ftype = build_function_type_list (V16QI_type_node, V16QI_type_node,
17029                                     intQI_type_node,
17030                                     integer_type_node, NULL_TREE);
17031   def_builtin ("__builtin_vec_set_v16qi", ftype, ALTIVEC_BUILTIN_VEC_SET_V16QI);
17032
17033   ftype = build_function_type_list (V4SF_type_node, V4SF_type_node,
17034                                     float_type_node,
17035                                     integer_type_node, NULL_TREE);
17036   def_builtin ("__builtin_vec_set_v4sf", ftype, ALTIVEC_BUILTIN_VEC_SET_V4SF);
17037
17038   ftype = build_function_type_list (V2DF_type_node, V2DF_type_node,
17039                                     double_type_node,
17040                                     integer_type_node, NULL_TREE);
17041   def_builtin ("__builtin_vec_set_v2df", ftype, VSX_BUILTIN_VEC_SET_V2DF);
17042
17043   ftype = build_function_type_list (V2DI_type_node, V2DI_type_node,
17044                                     intDI_type_node,
17045                                     integer_type_node, NULL_TREE);
17046   def_builtin ("__builtin_vec_set_v2di", ftype, VSX_BUILTIN_VEC_SET_V2DI);
17047
17048   /* Access to the vec_extract patterns.  */
17049   ftype = build_function_type_list (intSI_type_node, V4SI_type_node,
17050                                     integer_type_node, NULL_TREE);
17051   def_builtin ("__builtin_vec_ext_v4si", ftype, ALTIVEC_BUILTIN_VEC_EXT_V4SI);
17052
17053   ftype = build_function_type_list (intHI_type_node, V8HI_type_node,
17054                                     integer_type_node, NULL_TREE);
17055   def_builtin ("__builtin_vec_ext_v8hi", ftype, ALTIVEC_BUILTIN_VEC_EXT_V8HI);
17056
17057   ftype = build_function_type_list (intQI_type_node, V16QI_type_node,
17058                                     integer_type_node, NULL_TREE);
17059   def_builtin ("__builtin_vec_ext_v16qi", ftype, ALTIVEC_BUILTIN_VEC_EXT_V16QI);
17060
17061   ftype = build_function_type_list (float_type_node, V4SF_type_node,
17062                                     integer_type_node, NULL_TREE);
17063   def_builtin ("__builtin_vec_ext_v4sf", ftype, ALTIVEC_BUILTIN_VEC_EXT_V4SF);
17064
17065   ftype = build_function_type_list (double_type_node, V2DF_type_node,
17066                                     integer_type_node, NULL_TREE);
17067   def_builtin ("__builtin_vec_ext_v2df", ftype, VSX_BUILTIN_VEC_EXT_V2DF);
17068
17069   ftype = build_function_type_list (intDI_type_node, V2DI_type_node,
17070                                     integer_type_node, NULL_TREE);
17071   def_builtin ("__builtin_vec_ext_v2di", ftype, VSX_BUILTIN_VEC_EXT_V2DI);
17072
17073
17074   if (V1TI_type_node)
17075     {
17076       tree v1ti_ftype_long_pcvoid
17077         = build_function_type_list (V1TI_type_node,
17078                                     long_integer_type_node, pcvoid_type_node,
17079                                     NULL_TREE);
17080       tree void_ftype_v1ti_long_pvoid
17081         = build_function_type_list (void_type_node,
17082                                     V1TI_type_node, long_integer_type_node,
17083                                     pvoid_type_node, NULL_TREE);
17084       def_builtin ("__builtin_vsx_ld_elemrev_v1ti", v1ti_ftype_long_pcvoid,
17085                    VSX_BUILTIN_LD_ELEMREV_V1TI);
17086       def_builtin ("__builtin_vsx_lxvd2x_v1ti", v1ti_ftype_long_pcvoid,
17087                    VSX_BUILTIN_LXVD2X_V1TI);
17088       def_builtin ("__builtin_vsx_stxvd2x_v1ti", void_ftype_v1ti_long_pvoid,
17089                    VSX_BUILTIN_STXVD2X_V1TI);
17090       ftype = build_function_type_list (V1TI_type_node, intTI_type_node,
17091                                         NULL_TREE, NULL_TREE);
17092       def_builtin ("__builtin_vec_init_v1ti", ftype, VSX_BUILTIN_VEC_INIT_V1TI);
17093       ftype = build_function_type_list (V1TI_type_node, V1TI_type_node,
17094                                         intTI_type_node,
17095                                         integer_type_node, NULL_TREE);
17096       def_builtin ("__builtin_vec_set_v1ti", ftype, VSX_BUILTIN_VEC_SET_V1TI);
17097       ftype = build_function_type_list (intTI_type_node, V1TI_type_node,
17098                                         integer_type_node, NULL_TREE);
17099       def_builtin ("__builtin_vec_ext_v1ti", ftype, VSX_BUILTIN_VEC_EXT_V1TI);
17100     }
17101
17102 }
17103
17104 static void
17105 htm_init_builtins (void)
17106 {
17107   HOST_WIDE_INT builtin_mask = rs6000_builtin_mask;
17108   const struct builtin_description *d;
17109   size_t i;
17110
17111   d = bdesc_htm;
17112   for (i = 0; i < ARRAY_SIZE (bdesc_htm); i++, d++)
17113     {
17114       tree op[MAX_HTM_OPERANDS], type;
17115       HOST_WIDE_INT mask = d->mask;
17116       unsigned attr = rs6000_builtin_info[d->code].attr;
17117       bool void_func = (attr & RS6000_BTC_VOID);
17118       int attr_args = (attr & RS6000_BTC_TYPE_MASK);
17119       int nopnds = 0;
17120       tree gpr_type_node;
17121       tree rettype;
17122       tree argtype;
17123
17124       /* It is expected that these htm built-in functions may have
17125          d->icode equal to CODE_FOR_nothing.  */
17126
17127       if (TARGET_32BIT && TARGET_POWERPC64)
17128         gpr_type_node = long_long_unsigned_type_node;
17129       else
17130         gpr_type_node = long_unsigned_type_node;
17131
17132       if (attr & RS6000_BTC_SPR)
17133         {
17134           rettype = gpr_type_node;
17135           argtype = gpr_type_node;
17136         }
17137       else if (d->code == HTM_BUILTIN_TABORTDC
17138                || d->code == HTM_BUILTIN_TABORTDCI)
17139         {
17140           rettype = unsigned_type_node;
17141           argtype = gpr_type_node;
17142         }
17143       else
17144         {
17145           rettype = unsigned_type_node;
17146           argtype = unsigned_type_node;
17147         }
17148
17149       if ((mask & builtin_mask) != mask)
17150         {
17151           if (TARGET_DEBUG_BUILTIN)
17152             fprintf (stderr, "htm_builtin, skip binary %s\n", d->name);
17153           continue;
17154         }
17155
17156       if (d->name == 0)
17157         {
17158           if (TARGET_DEBUG_BUILTIN)
17159             fprintf (stderr, "htm_builtin, bdesc_htm[%ld] no name\n",
17160                      (long unsigned) i);
17161           continue;
17162         }
17163
17164       op[nopnds++] = (void_func) ? void_type_node : rettype;
17165
17166       if (attr_args == RS6000_BTC_UNARY)
17167         op[nopnds++] = argtype;
17168       else if (attr_args == RS6000_BTC_BINARY)
17169         {
17170           op[nopnds++] = argtype;
17171           op[nopnds++] = argtype;
17172         }
17173       else if (attr_args == RS6000_BTC_TERNARY)
17174         {
17175           op[nopnds++] = argtype;
17176           op[nopnds++] = argtype;
17177           op[nopnds++] = argtype;
17178         }
17179
17180       switch (nopnds)
17181         {
17182         case 1:
17183           type = build_function_type_list (op[0], NULL_TREE);
17184           break;
17185         case 2:
17186           type = build_function_type_list (op[0], op[1], NULL_TREE);
17187           break;
17188         case 3:
17189           type = build_function_type_list (op[0], op[1], op[2], NULL_TREE);
17190           break;
17191         case 4:
17192           type = build_function_type_list (op[0], op[1], op[2], op[3],
17193                                            NULL_TREE);
17194           break;
17195         default:
17196           gcc_unreachable ();
17197         }
17198
17199       def_builtin (d->name, type, d->code);
17200     }
17201 }
17202
17203 /* Hash function for builtin functions with up to 3 arguments and a return
17204    type.  */
17205 hashval_t
17206 builtin_hasher::hash (builtin_hash_struct *bh)
17207 {
17208   unsigned ret = 0;
17209   int i;
17210
17211   for (i = 0; i < 4; i++)
17212     {
17213       ret = (ret * (unsigned)MAX_MACHINE_MODE) + ((unsigned)bh->mode[i]);
17214       ret = (ret * 2) + bh->uns_p[i];
17215     }
17216
17217   return ret;
17218 }
17219
17220 /* Compare builtin hash entries H1 and H2 for equivalence.  */
17221 bool
17222 builtin_hasher::equal (builtin_hash_struct *p1, builtin_hash_struct *p2)
17223 {
17224   return ((p1->mode[0] == p2->mode[0])
17225           && (p1->mode[1] == p2->mode[1])
17226           && (p1->mode[2] == p2->mode[2])
17227           && (p1->mode[3] == p2->mode[3])
17228           && (p1->uns_p[0] == p2->uns_p[0])
17229           && (p1->uns_p[1] == p2->uns_p[1])
17230           && (p1->uns_p[2] == p2->uns_p[2])
17231           && (p1->uns_p[3] == p2->uns_p[3]));
17232 }
17233
17234 /* Map types for builtin functions with an explicit return type and up to 3
17235    arguments.  Functions with fewer than 3 arguments use VOIDmode as the type
17236    of the argument.  */
17237 static tree
17238 builtin_function_type (machine_mode mode_ret, machine_mode mode_arg0,
17239                        machine_mode mode_arg1, machine_mode mode_arg2,
17240                        enum rs6000_builtins builtin, const char *name)
17241 {
17242   struct builtin_hash_struct h;
17243   struct builtin_hash_struct *h2;
17244   int num_args = 3;
17245   int i;
17246   tree ret_type = NULL_TREE;
17247   tree arg_type[3] = { NULL_TREE, NULL_TREE, NULL_TREE };
17248
17249   /* Create builtin_hash_table.  */
17250   if (builtin_hash_table == NULL)
17251     builtin_hash_table = hash_table<builtin_hasher>::create_ggc (1500);
17252
17253   h.type = NULL_TREE;
17254   h.mode[0] = mode_ret;
17255   h.mode[1] = mode_arg0;
17256   h.mode[2] = mode_arg1;
17257   h.mode[3] = mode_arg2;
17258   h.uns_p[0] = 0;
17259   h.uns_p[1] = 0;
17260   h.uns_p[2] = 0;
17261   h.uns_p[3] = 0;
17262
17263   /* If the builtin is a type that produces unsigned results or takes unsigned
17264      arguments, and it is returned as a decl for the vectorizer (such as
17265      widening multiplies, permute), make sure the arguments and return value
17266      are type correct.  */
17267   switch (builtin)
17268     {
17269     /* unsigned 1 argument functions.  */
17270     case CRYPTO_BUILTIN_VSBOX:
17271     case CRYPTO_BUILTIN_VSBOX_BE:
17272     case P8V_BUILTIN_VGBBD:
17273     case MISC_BUILTIN_CDTBCD:
17274     case MISC_BUILTIN_CBCDTD:
17275       h.uns_p[0] = 1;
17276       h.uns_p[1] = 1;
17277       break;
17278
17279     /* unsigned 2 argument functions.  */
17280     case ALTIVEC_BUILTIN_VMULEUB:
17281     case ALTIVEC_BUILTIN_VMULEUH:
17282     case P8V_BUILTIN_VMULEUW:
17283     case ALTIVEC_BUILTIN_VMULOUB:
17284     case ALTIVEC_BUILTIN_VMULOUH:
17285     case P8V_BUILTIN_VMULOUW:
17286     case CRYPTO_BUILTIN_VCIPHER:
17287     case CRYPTO_BUILTIN_VCIPHER_BE:
17288     case CRYPTO_BUILTIN_VCIPHERLAST:
17289     case CRYPTO_BUILTIN_VCIPHERLAST_BE:
17290     case CRYPTO_BUILTIN_VNCIPHER:
17291     case CRYPTO_BUILTIN_VNCIPHER_BE:
17292     case CRYPTO_BUILTIN_VNCIPHERLAST:
17293     case CRYPTO_BUILTIN_VNCIPHERLAST_BE:
17294     case CRYPTO_BUILTIN_VPMSUMB:
17295     case CRYPTO_BUILTIN_VPMSUMH:
17296     case CRYPTO_BUILTIN_VPMSUMW:
17297     case CRYPTO_BUILTIN_VPMSUMD:
17298     case CRYPTO_BUILTIN_VPMSUM:
17299     case MISC_BUILTIN_ADDG6S:
17300     case MISC_BUILTIN_DIVWEU:
17301     case MISC_BUILTIN_DIVDEU:
17302     case VSX_BUILTIN_UDIV_V2DI:
17303     case ALTIVEC_BUILTIN_VMAXUB:
17304     case ALTIVEC_BUILTIN_VMINUB:
17305     case ALTIVEC_BUILTIN_VMAXUH:
17306     case ALTIVEC_BUILTIN_VMINUH:
17307     case ALTIVEC_BUILTIN_VMAXUW:
17308     case ALTIVEC_BUILTIN_VMINUW:
17309     case P8V_BUILTIN_VMAXUD:
17310     case P8V_BUILTIN_VMINUD:
17311       h.uns_p[0] = 1;
17312       h.uns_p[1] = 1;
17313       h.uns_p[2] = 1;
17314       break;
17315
17316     /* unsigned 3 argument functions.  */
17317     case ALTIVEC_BUILTIN_VPERM_16QI_UNS:
17318     case ALTIVEC_BUILTIN_VPERM_8HI_UNS:
17319     case ALTIVEC_BUILTIN_VPERM_4SI_UNS:
17320     case ALTIVEC_BUILTIN_VPERM_2DI_UNS:
17321     case ALTIVEC_BUILTIN_VSEL_16QI_UNS:
17322     case ALTIVEC_BUILTIN_VSEL_8HI_UNS:
17323     case ALTIVEC_BUILTIN_VSEL_4SI_UNS:
17324     case ALTIVEC_BUILTIN_VSEL_2DI_UNS:
17325     case VSX_BUILTIN_VPERM_16QI_UNS:
17326     case VSX_BUILTIN_VPERM_8HI_UNS:
17327     case VSX_BUILTIN_VPERM_4SI_UNS:
17328     case VSX_BUILTIN_VPERM_2DI_UNS:
17329     case VSX_BUILTIN_XXSEL_16QI_UNS:
17330     case VSX_BUILTIN_XXSEL_8HI_UNS:
17331     case VSX_BUILTIN_XXSEL_4SI_UNS:
17332     case VSX_BUILTIN_XXSEL_2DI_UNS:
17333     case CRYPTO_BUILTIN_VPERMXOR:
17334     case CRYPTO_BUILTIN_VPERMXOR_V2DI:
17335     case CRYPTO_BUILTIN_VPERMXOR_V4SI:
17336     case CRYPTO_BUILTIN_VPERMXOR_V8HI:
17337     case CRYPTO_BUILTIN_VPERMXOR_V16QI:
17338     case CRYPTO_BUILTIN_VSHASIGMAW:
17339     case CRYPTO_BUILTIN_VSHASIGMAD:
17340     case CRYPTO_BUILTIN_VSHASIGMA:
17341       h.uns_p[0] = 1;
17342       h.uns_p[1] = 1;
17343       h.uns_p[2] = 1;
17344       h.uns_p[3] = 1;
17345       break;
17346
17347     /* signed permute functions with unsigned char mask.  */
17348     case ALTIVEC_BUILTIN_VPERM_16QI:
17349     case ALTIVEC_BUILTIN_VPERM_8HI:
17350     case ALTIVEC_BUILTIN_VPERM_4SI:
17351     case ALTIVEC_BUILTIN_VPERM_4SF:
17352     case ALTIVEC_BUILTIN_VPERM_2DI:
17353     case ALTIVEC_BUILTIN_VPERM_2DF:
17354     case VSX_BUILTIN_VPERM_16QI:
17355     case VSX_BUILTIN_VPERM_8HI:
17356     case VSX_BUILTIN_VPERM_4SI:
17357     case VSX_BUILTIN_VPERM_4SF:
17358     case VSX_BUILTIN_VPERM_2DI:
17359     case VSX_BUILTIN_VPERM_2DF:
17360       h.uns_p[3] = 1;
17361       break;
17362
17363     /* unsigned args, signed return.  */
17364     case VSX_BUILTIN_XVCVUXDSP:
17365     case VSX_BUILTIN_XVCVUXDDP_UNS:
17366     case ALTIVEC_BUILTIN_UNSFLOAT_V4SI_V4SF:
17367       h.uns_p[1] = 1;
17368       break;
17369
17370     /* signed args, unsigned return.  */
17371     case VSX_BUILTIN_XVCVDPUXDS_UNS:
17372     case ALTIVEC_BUILTIN_FIXUNS_V4SF_V4SI:
17373     case MISC_BUILTIN_UNPACK_TD:
17374     case MISC_BUILTIN_UNPACK_V1TI:
17375       h.uns_p[0] = 1;
17376       break;
17377
17378     /* unsigned arguments, bool return (compares).  */
17379     case ALTIVEC_BUILTIN_VCMPEQUB:
17380     case ALTIVEC_BUILTIN_VCMPEQUH:
17381     case ALTIVEC_BUILTIN_VCMPEQUW:
17382     case P8V_BUILTIN_VCMPEQUD:
17383     case VSX_BUILTIN_CMPGE_U16QI:
17384     case VSX_BUILTIN_CMPGE_U8HI:
17385     case VSX_BUILTIN_CMPGE_U4SI:
17386     case VSX_BUILTIN_CMPGE_U2DI:
17387     case ALTIVEC_BUILTIN_VCMPGTUB:
17388     case ALTIVEC_BUILTIN_VCMPGTUH:
17389     case ALTIVEC_BUILTIN_VCMPGTUW:
17390     case P8V_BUILTIN_VCMPGTUD:
17391       h.uns_p[1] = 1;
17392       h.uns_p[2] = 1;
17393       break;
17394
17395     /* unsigned arguments for 128-bit pack instructions.  */
17396     case MISC_BUILTIN_PACK_TD:
17397     case MISC_BUILTIN_PACK_V1TI:
17398       h.uns_p[1] = 1;
17399       h.uns_p[2] = 1;
17400       break;
17401
17402     /* unsigned second arguments (vector shift right).  */
17403     case ALTIVEC_BUILTIN_VSRB:
17404     case ALTIVEC_BUILTIN_VSRH:
17405     case ALTIVEC_BUILTIN_VSRW:
17406     case P8V_BUILTIN_VSRD:
17407       h.uns_p[2] = 1;
17408       break;
17409
17410     default:
17411       break;
17412     }
17413
17414   /* Figure out how many args are present.  */
17415   while (num_args > 0 && h.mode[num_args] == VOIDmode)
17416     num_args--;
17417
17418   ret_type = builtin_mode_to_type[h.mode[0]][h.uns_p[0]];
17419   if (!ret_type && h.uns_p[0])
17420     ret_type = builtin_mode_to_type[h.mode[0]][0];
17421
17422   if (!ret_type)
17423     fatal_error (input_location,
17424                  "internal error: builtin function %qs had an unexpected "
17425                  "return type %qs", name, GET_MODE_NAME (h.mode[0]));
17426
17427   for (i = 0; i < (int) ARRAY_SIZE (arg_type); i++)
17428     arg_type[i] = NULL_TREE;
17429
17430   for (i = 0; i < num_args; i++)
17431     {
17432       int m = (int) h.mode[i+1];
17433       int uns_p = h.uns_p[i+1];
17434
17435       arg_type[i] = builtin_mode_to_type[m][uns_p];
17436       if (!arg_type[i] && uns_p)
17437         arg_type[i] = builtin_mode_to_type[m][0];
17438
17439       if (!arg_type[i])
17440         fatal_error (input_location,
17441                      "internal error: builtin function %qs, argument %d "
17442                      "had unexpected argument type %qs", name, i,
17443                      GET_MODE_NAME (m));
17444     }
17445
17446   builtin_hash_struct **found = builtin_hash_table->find_slot (&h, INSERT);
17447   if (*found == NULL)
17448     {
17449       h2 = ggc_alloc<builtin_hash_struct> ();
17450       *h2 = h;
17451       *found = h2;
17452
17453       h2->type = build_function_type_list (ret_type, arg_type[0], arg_type[1],
17454                                            arg_type[2], NULL_TREE);
17455     }
17456
17457   return (*found)->type;
17458 }
17459
17460 static void
17461 rs6000_common_init_builtins (void)
17462 {
17463   const struct builtin_description *d;
17464   size_t i;
17465
17466   tree opaque_ftype_opaque = NULL_TREE;
17467   tree opaque_ftype_opaque_opaque = NULL_TREE;
17468   tree opaque_ftype_opaque_opaque_opaque = NULL_TREE;
17469   HOST_WIDE_INT builtin_mask = rs6000_builtin_mask;
17470
17471   /* Create Altivec and VSX builtins on machines with at least the
17472      general purpose extensions (970 and newer) to allow the use of
17473      the target attribute.  */
17474
17475   if (TARGET_EXTRA_BUILTINS)
17476     builtin_mask |= RS6000_BTM_COMMON;
17477
17478   /* Add the ternary operators.  */
17479   d = bdesc_3arg;
17480   for (i = 0; i < ARRAY_SIZE (bdesc_3arg); i++, d++)
17481     {
17482       tree type;
17483       HOST_WIDE_INT mask = d->mask;
17484
17485       if ((mask & builtin_mask) != mask)
17486         {
17487           if (TARGET_DEBUG_BUILTIN)
17488             fprintf (stderr, "rs6000_builtin, skip ternary %s\n", d->name);
17489           continue;
17490         }
17491
17492       if (rs6000_overloaded_builtin_p (d->code))
17493         {
17494           if (! (type = opaque_ftype_opaque_opaque_opaque))
17495             type = opaque_ftype_opaque_opaque_opaque
17496               = build_function_type_list (opaque_V4SI_type_node,
17497                                           opaque_V4SI_type_node,
17498                                           opaque_V4SI_type_node,
17499                                           opaque_V4SI_type_node,
17500                                           NULL_TREE);
17501         }
17502       else
17503         {
17504           enum insn_code icode = d->icode;
17505           if (d->name == 0)
17506             {
17507               if (TARGET_DEBUG_BUILTIN)
17508                 fprintf (stderr, "rs6000_builtin, bdesc_3arg[%ld] no name\n",
17509                          (long unsigned)i);
17510
17511               continue;
17512             }
17513
17514           if (icode == CODE_FOR_nothing)
17515             {
17516               if (TARGET_DEBUG_BUILTIN)
17517                 fprintf (stderr, "rs6000_builtin, skip ternary %s (no code)\n",
17518                          d->name);
17519
17520               continue;
17521             }
17522
17523           type = builtin_function_type (insn_data[icode].operand[0].mode,
17524                                         insn_data[icode].operand[1].mode,
17525                                         insn_data[icode].operand[2].mode,
17526                                         insn_data[icode].operand[3].mode,
17527                                         d->code, d->name);
17528         }
17529
17530       def_builtin (d->name, type, d->code);
17531     }
17532
17533   /* Add the binary operators.  */
17534   d = bdesc_2arg;
17535   for (i = 0; i < ARRAY_SIZE (bdesc_2arg); i++, d++)
17536     {
17537       machine_mode mode0, mode1, mode2;
17538       tree type;
17539       HOST_WIDE_INT mask = d->mask;
17540
17541       if ((mask & builtin_mask) != mask)
17542         {
17543           if (TARGET_DEBUG_BUILTIN)
17544             fprintf (stderr, "rs6000_builtin, skip binary %s\n", d->name);
17545           continue;
17546         }
17547
17548       if (rs6000_overloaded_builtin_p (d->code))
17549         {
17550           if (! (type = opaque_ftype_opaque_opaque))
17551             type = opaque_ftype_opaque_opaque
17552               = build_function_type_list (opaque_V4SI_type_node,
17553                                           opaque_V4SI_type_node,
17554                                           opaque_V4SI_type_node,
17555                                           NULL_TREE);
17556         }
17557       else
17558         {
17559           enum insn_code icode = d->icode;
17560           if (d->name == 0)
17561             {
17562               if (TARGET_DEBUG_BUILTIN)
17563                 fprintf (stderr, "rs6000_builtin, bdesc_2arg[%ld] no name\n",
17564                          (long unsigned)i);
17565
17566               continue;
17567             }
17568
17569           if (icode == CODE_FOR_nothing)
17570             {
17571               if (TARGET_DEBUG_BUILTIN)
17572                 fprintf (stderr, "rs6000_builtin, skip binary %s (no code)\n",
17573                          d->name);
17574
17575               continue;
17576             }
17577
17578           mode0 = insn_data[icode].operand[0].mode;
17579           mode1 = insn_data[icode].operand[1].mode;
17580           mode2 = insn_data[icode].operand[2].mode;
17581
17582           type = builtin_function_type (mode0, mode1, mode2, VOIDmode,
17583                                         d->code, d->name);
17584         }
17585
17586       def_builtin (d->name, type, d->code);
17587     }
17588
17589   /* Add the simple unary operators.  */
17590   d = bdesc_1arg;
17591   for (i = 0; i < ARRAY_SIZE (bdesc_1arg); i++, d++)
17592     {
17593       machine_mode mode0, mode1;
17594       tree type;
17595       HOST_WIDE_INT mask = d->mask;
17596
17597       if ((mask & builtin_mask) != mask)
17598         {
17599           if (TARGET_DEBUG_BUILTIN)
17600             fprintf (stderr, "rs6000_builtin, skip unary %s\n", d->name);
17601           continue;
17602         }
17603
17604       if (rs6000_overloaded_builtin_p (d->code))
17605         {
17606           if (! (type = opaque_ftype_opaque))
17607             type = opaque_ftype_opaque
17608               = build_function_type_list (opaque_V4SI_type_node,
17609                                           opaque_V4SI_type_node,
17610                                           NULL_TREE);
17611         }
17612       else
17613         {
17614           enum insn_code icode = d->icode;
17615           if (d->name == 0)
17616             {
17617               if (TARGET_DEBUG_BUILTIN)
17618                 fprintf (stderr, "rs6000_builtin, bdesc_1arg[%ld] no name\n",
17619                          (long unsigned)i);
17620
17621               continue;
17622             }
17623
17624           if (icode == CODE_FOR_nothing)
17625             {
17626               if (TARGET_DEBUG_BUILTIN)
17627                 fprintf (stderr, "rs6000_builtin, skip unary %s (no code)\n",
17628                          d->name);
17629
17630               continue;
17631             }
17632
17633           mode0 = insn_data[icode].operand[0].mode;
17634           mode1 = insn_data[icode].operand[1].mode;
17635
17636           type = builtin_function_type (mode0, mode1, VOIDmode, VOIDmode,
17637                                         d->code, d->name);
17638         }
17639
17640       def_builtin (d->name, type, d->code);
17641     }
17642
17643   /* Add the simple no-argument operators.  */
17644   d = bdesc_0arg;
17645   for (i = 0; i < ARRAY_SIZE (bdesc_0arg); i++, d++)
17646     {
17647       machine_mode mode0;
17648       tree type;
17649       HOST_WIDE_INT mask = d->mask;
17650
17651       if ((mask & builtin_mask) != mask)
17652         {
17653           if (TARGET_DEBUG_BUILTIN)
17654             fprintf (stderr, "rs6000_builtin, skip no-argument %s\n", d->name);
17655           continue;
17656         }
17657       if (rs6000_overloaded_builtin_p (d->code))
17658         {
17659           if (!opaque_ftype_opaque)
17660             opaque_ftype_opaque
17661               = build_function_type_list (opaque_V4SI_type_node, NULL_TREE);
17662           type = opaque_ftype_opaque;
17663         }
17664       else
17665         {
17666           enum insn_code icode = d->icode;
17667           if (d->name == 0)
17668             {
17669               if (TARGET_DEBUG_BUILTIN)
17670                 fprintf (stderr, "rs6000_builtin, bdesc_0arg[%lu] no name\n",
17671                          (long unsigned) i);
17672               continue;
17673             }
17674           if (icode == CODE_FOR_nothing)
17675             {
17676               if (TARGET_DEBUG_BUILTIN)
17677                 fprintf (stderr,
17678                          "rs6000_builtin, skip no-argument %s (no code)\n",
17679                          d->name);
17680               continue;
17681             }
17682           mode0 = insn_data[icode].operand[0].mode;
17683           type = builtin_function_type (mode0, VOIDmode, VOIDmode, VOIDmode,
17684                                         d->code, d->name);
17685         }
17686       def_builtin (d->name, type, d->code);
17687     }
17688 }
17689
17690 /* Set up AIX/Darwin/64-bit Linux quad floating point routines.  */
17691 static void
17692 init_float128_ibm (machine_mode mode)
17693 {
17694   if (!TARGET_XL_COMPAT)
17695     {
17696       set_optab_libfunc (add_optab, mode, "__gcc_qadd");
17697       set_optab_libfunc (sub_optab, mode, "__gcc_qsub");
17698       set_optab_libfunc (smul_optab, mode, "__gcc_qmul");
17699       set_optab_libfunc (sdiv_optab, mode, "__gcc_qdiv");
17700
17701       if (!TARGET_HARD_FLOAT)
17702         {
17703           set_optab_libfunc (neg_optab, mode, "__gcc_qneg");
17704           set_optab_libfunc (eq_optab, mode, "__gcc_qeq");
17705           set_optab_libfunc (ne_optab, mode, "__gcc_qne");
17706           set_optab_libfunc (gt_optab, mode, "__gcc_qgt");
17707           set_optab_libfunc (ge_optab, mode, "__gcc_qge");
17708           set_optab_libfunc (lt_optab, mode, "__gcc_qlt");
17709           set_optab_libfunc (le_optab, mode, "__gcc_qle");
17710           set_optab_libfunc (unord_optab, mode, "__gcc_qunord");
17711
17712           set_conv_libfunc (sext_optab, mode, SFmode, "__gcc_stoq");
17713           set_conv_libfunc (sext_optab, mode, DFmode, "__gcc_dtoq");
17714           set_conv_libfunc (trunc_optab, SFmode, mode, "__gcc_qtos");
17715           set_conv_libfunc (trunc_optab, DFmode, mode, "__gcc_qtod");
17716           set_conv_libfunc (sfix_optab, SImode, mode, "__gcc_qtoi");
17717           set_conv_libfunc (ufix_optab, SImode, mode, "__gcc_qtou");
17718           set_conv_libfunc (sfloat_optab, mode, SImode, "__gcc_itoq");
17719           set_conv_libfunc (ufloat_optab, mode, SImode, "__gcc_utoq");
17720         }
17721     }
17722   else
17723     {
17724       set_optab_libfunc (add_optab, mode, "_xlqadd");
17725       set_optab_libfunc (sub_optab, mode, "_xlqsub");
17726       set_optab_libfunc (smul_optab, mode, "_xlqmul");
17727       set_optab_libfunc (sdiv_optab, mode, "_xlqdiv");
17728     }
17729
17730   /* Add various conversions for IFmode to use the traditional TFmode
17731      names.  */
17732   if (mode == IFmode)
17733     {
17734       set_conv_libfunc (sext_optab, mode, SDmode, "__dpd_extendsdtf");
17735       set_conv_libfunc (sext_optab, mode, DDmode, "__dpd_extendddtf");
17736       set_conv_libfunc (trunc_optab, mode, TDmode, "__dpd_trunctdtf");
17737       set_conv_libfunc (trunc_optab, SDmode, mode, "__dpd_trunctfsd");
17738       set_conv_libfunc (trunc_optab, DDmode, mode, "__dpd_trunctfdd");
17739       set_conv_libfunc (sext_optab, TDmode, mode, "__dpd_extendtftd");
17740
17741       if (TARGET_POWERPC64)
17742         {
17743           set_conv_libfunc (sfix_optab, TImode, mode, "__fixtfti");
17744           set_conv_libfunc (ufix_optab, TImode, mode, "__fixunstfti");
17745           set_conv_libfunc (sfloat_optab, mode, TImode, "__floattitf");
17746           set_conv_libfunc (ufloat_optab, mode, TImode, "__floatuntitf");
17747         }
17748     }
17749 }
17750
17751 /* Create a decl for either complex long double multiply or complex long double
17752    divide when long double is IEEE 128-bit floating point.  We can't use
17753    __multc3 and __divtc3 because the original long double using IBM extended
17754    double used those names.  The complex multiply/divide functions are encoded
17755    as builtin functions with a complex result and 4 scalar inputs.  */
17756
17757 static void
17758 create_complex_muldiv (const char *name, built_in_function fncode, tree fntype)
17759 {
17760   tree fndecl = add_builtin_function (name, fntype, fncode, BUILT_IN_NORMAL,
17761                                       name, NULL_TREE);
17762
17763   set_builtin_decl (fncode, fndecl, true);
17764
17765   if (TARGET_DEBUG_BUILTIN)
17766     fprintf (stderr, "create complex %s, fncode: %d\n", name, (int) fncode);
17767
17768   return;
17769 }
17770
17771 /* Set up IEEE 128-bit floating point routines.  Use different names if the
17772    arguments can be passed in a vector register.  The historical PowerPC
17773    implementation of IEEE 128-bit floating point used _q_<op> for the names, so
17774    continue to use that if we aren't using vector registers to pass IEEE
17775    128-bit floating point.  */
17776
17777 static void
17778 init_float128_ieee (machine_mode mode)
17779 {
17780   if (FLOAT128_VECTOR_P (mode))
17781     {
17782       static bool complex_muldiv_init_p = false;
17783
17784       /* Set up to call __mulkc3 and __divkc3 under -mabi=ieeelongdouble.  If
17785          we have clone or target attributes, this will be called a second
17786          time.  We want to create the built-in function only once.  */
17787      if (mode == TFmode && TARGET_IEEEQUAD && !complex_muldiv_init_p)
17788        {
17789          complex_muldiv_init_p = true;
17790          built_in_function fncode_mul =
17791            (built_in_function) (BUILT_IN_COMPLEX_MUL_MIN + TCmode
17792                                 - MIN_MODE_COMPLEX_FLOAT);
17793          built_in_function fncode_div =
17794            (built_in_function) (BUILT_IN_COMPLEX_DIV_MIN + TCmode
17795                                 - MIN_MODE_COMPLEX_FLOAT);
17796
17797          tree fntype = build_function_type_list (complex_long_double_type_node,
17798                                                  long_double_type_node,
17799                                                  long_double_type_node,
17800                                                  long_double_type_node,
17801                                                  long_double_type_node,
17802                                                  NULL_TREE);
17803
17804          create_complex_muldiv ("__mulkc3", fncode_mul, fntype);
17805          create_complex_muldiv ("__divkc3", fncode_div, fntype);
17806        }
17807
17808       set_optab_libfunc (add_optab, mode, "__addkf3");
17809       set_optab_libfunc (sub_optab, mode, "__subkf3");
17810       set_optab_libfunc (neg_optab, mode, "__negkf2");
17811       set_optab_libfunc (smul_optab, mode, "__mulkf3");
17812       set_optab_libfunc (sdiv_optab, mode, "__divkf3");
17813       set_optab_libfunc (sqrt_optab, mode, "__sqrtkf2");
17814       set_optab_libfunc (abs_optab, mode, "__abskf2");
17815       set_optab_libfunc (powi_optab, mode, "__powikf2");
17816
17817       set_optab_libfunc (eq_optab, mode, "__eqkf2");
17818       set_optab_libfunc (ne_optab, mode, "__nekf2");
17819       set_optab_libfunc (gt_optab, mode, "__gtkf2");
17820       set_optab_libfunc (ge_optab, mode, "__gekf2");
17821       set_optab_libfunc (lt_optab, mode, "__ltkf2");
17822       set_optab_libfunc (le_optab, mode, "__lekf2");
17823       set_optab_libfunc (unord_optab, mode, "__unordkf2");
17824
17825       set_conv_libfunc (sext_optab, mode, SFmode, "__extendsfkf2");
17826       set_conv_libfunc (sext_optab, mode, DFmode, "__extenddfkf2");
17827       set_conv_libfunc (trunc_optab, SFmode, mode, "__trunckfsf2");
17828       set_conv_libfunc (trunc_optab, DFmode, mode, "__trunckfdf2");
17829
17830       set_conv_libfunc (sext_optab, mode, IFmode, "__trunctfkf2");
17831       if (mode != TFmode && FLOAT128_IBM_P (TFmode))
17832         set_conv_libfunc (sext_optab, mode, TFmode, "__trunctfkf2");
17833
17834       set_conv_libfunc (trunc_optab, IFmode, mode, "__extendkftf2");
17835       if (mode != TFmode && FLOAT128_IBM_P (TFmode))
17836         set_conv_libfunc (trunc_optab, TFmode, mode, "__extendkftf2");
17837
17838       set_conv_libfunc (sext_optab, mode, SDmode, "__dpd_extendsdkf");
17839       set_conv_libfunc (sext_optab, mode, DDmode, "__dpd_extendddkf");
17840       set_conv_libfunc (trunc_optab, mode, TDmode, "__dpd_trunctdkf");
17841       set_conv_libfunc (trunc_optab, SDmode, mode, "__dpd_trunckfsd");
17842       set_conv_libfunc (trunc_optab, DDmode, mode, "__dpd_trunckfdd");
17843       set_conv_libfunc (sext_optab, TDmode, mode, "__dpd_extendkftd");
17844
17845       set_conv_libfunc (sfix_optab, SImode, mode, "__fixkfsi");
17846       set_conv_libfunc (ufix_optab, SImode, mode, "__fixunskfsi");
17847       set_conv_libfunc (sfix_optab, DImode, mode, "__fixkfdi");
17848       set_conv_libfunc (ufix_optab, DImode, mode, "__fixunskfdi");
17849
17850       set_conv_libfunc (sfloat_optab, mode, SImode, "__floatsikf");
17851       set_conv_libfunc (ufloat_optab, mode, SImode, "__floatunsikf");
17852       set_conv_libfunc (sfloat_optab, mode, DImode, "__floatdikf");
17853       set_conv_libfunc (ufloat_optab, mode, DImode, "__floatundikf");
17854
17855       if (TARGET_POWERPC64)
17856         {
17857           set_conv_libfunc (sfix_optab, TImode, mode, "__fixkfti");
17858           set_conv_libfunc (ufix_optab, TImode, mode, "__fixunskfti");
17859           set_conv_libfunc (sfloat_optab, mode, TImode, "__floattikf");
17860           set_conv_libfunc (ufloat_optab, mode, TImode, "__floatuntikf");
17861         }
17862     }
17863
17864   else
17865     {
17866       set_optab_libfunc (add_optab, mode, "_q_add");
17867       set_optab_libfunc (sub_optab, mode, "_q_sub");
17868       set_optab_libfunc (neg_optab, mode, "_q_neg");
17869       set_optab_libfunc (smul_optab, mode, "_q_mul");
17870       set_optab_libfunc (sdiv_optab, mode, "_q_div");
17871       if (TARGET_PPC_GPOPT)
17872         set_optab_libfunc (sqrt_optab, mode, "_q_sqrt");
17873
17874       set_optab_libfunc (eq_optab, mode, "_q_feq");
17875       set_optab_libfunc (ne_optab, mode, "_q_fne");
17876       set_optab_libfunc (gt_optab, mode, "_q_fgt");
17877       set_optab_libfunc (ge_optab, mode, "_q_fge");
17878       set_optab_libfunc (lt_optab, mode, "_q_flt");
17879       set_optab_libfunc (le_optab, mode, "_q_fle");
17880
17881       set_conv_libfunc (sext_optab, mode, SFmode, "_q_stoq");
17882       set_conv_libfunc (sext_optab, mode, DFmode, "_q_dtoq");
17883       set_conv_libfunc (trunc_optab, SFmode, mode, "_q_qtos");
17884       set_conv_libfunc (trunc_optab, DFmode, mode, "_q_qtod");
17885       set_conv_libfunc (sfix_optab, SImode, mode, "_q_qtoi");
17886       set_conv_libfunc (ufix_optab, SImode, mode, "_q_qtou");
17887       set_conv_libfunc (sfloat_optab, mode, SImode, "_q_itoq");
17888       set_conv_libfunc (ufloat_optab, mode, SImode, "_q_utoq");
17889     }
17890 }
17891
17892 static void
17893 rs6000_init_libfuncs (void)
17894 {
17895   /* __float128 support.  */
17896   if (TARGET_FLOAT128_TYPE)
17897     {
17898       init_float128_ibm (IFmode);
17899       init_float128_ieee (KFmode);
17900     }
17901
17902   /* AIX/Darwin/64-bit Linux quad floating point routines.  */
17903   if (TARGET_LONG_DOUBLE_128)
17904     {
17905       if (!TARGET_IEEEQUAD)
17906         init_float128_ibm (TFmode);
17907
17908       /* IEEE 128-bit including 32-bit SVR4 quad floating point routines.  */
17909       else
17910         init_float128_ieee (TFmode);
17911     }
17912 }
17913
17914 /* Emit a potentially record-form instruction, setting DST from SRC.
17915    If DOT is 0, that is all; otherwise, set CCREG to the result of the
17916    signed comparison of DST with zero.  If DOT is 1, the generated RTL
17917    doesn't care about the DST result; if DOT is 2, it does.  If CCREG
17918    is CR0 do a single dot insn (as a PARALLEL); otherwise, do a SET and
17919    a separate COMPARE.  */
17920
17921 void
17922 rs6000_emit_dot_insn (rtx dst, rtx src, int dot, rtx ccreg)
17923 {
17924   if (dot == 0)
17925     {
17926       emit_move_insn (dst, src);
17927       return;
17928     }
17929
17930   if (cc_reg_not_cr0_operand (ccreg, CCmode))
17931     {
17932       emit_move_insn (dst, src);
17933       emit_move_insn (ccreg, gen_rtx_COMPARE (CCmode, dst, const0_rtx));
17934       return;
17935     }
17936
17937   rtx ccset = gen_rtx_SET (ccreg, gen_rtx_COMPARE (CCmode, src, const0_rtx));
17938   if (dot == 1)
17939     {
17940       rtx clobber = gen_rtx_CLOBBER (VOIDmode, dst);
17941       emit_insn (gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, ccset, clobber)));
17942     }
17943   else
17944     {
17945       rtx set = gen_rtx_SET (dst, src);
17946       emit_insn (gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, ccset, set)));
17947     }
17948 }
17949
17950 \f
17951 /* A validation routine: say whether CODE, a condition code, and MODE
17952    match.  The other alternatives either don't make sense or should
17953    never be generated.  */
17954
17955 void
17956 validate_condition_mode (enum rtx_code code, machine_mode mode)
17957 {
17958   gcc_assert ((GET_RTX_CLASS (code) == RTX_COMPARE
17959                || GET_RTX_CLASS (code) == RTX_COMM_COMPARE)
17960               && GET_MODE_CLASS (mode) == MODE_CC);
17961
17962   /* These don't make sense.  */
17963   gcc_assert ((code != GT && code != LT && code != GE && code != LE)
17964               || mode != CCUNSmode);
17965
17966   gcc_assert ((code != GTU && code != LTU && code != GEU && code != LEU)
17967               || mode == CCUNSmode);
17968
17969   gcc_assert (mode == CCFPmode
17970               || (code != ORDERED && code != UNORDERED
17971                   && code != UNEQ && code != LTGT
17972                   && code != UNGT && code != UNLT
17973                   && code != UNGE && code != UNLE));
17974
17975   /* These should never be generated except for
17976      flag_finite_math_only.  */
17977   gcc_assert (mode != CCFPmode
17978               || flag_finite_math_only
17979               || (code != LE && code != GE
17980                   && code != UNEQ && code != LTGT
17981                   && code != UNGT && code != UNLT));
17982
17983   /* These are invalid; the information is not there.  */
17984   gcc_assert (mode != CCEQmode || code == EQ || code == NE);
17985 }
17986
17987 \f
17988 /* Return whether MASK (a CONST_INT) is a valid mask for any rlwinm,
17989    rldicl, rldicr, or rldic instruction in mode MODE.  If so, if E is
17990    not zero, store there the bit offset (counted from the right) where
17991    the single stretch of 1 bits begins; and similarly for B, the bit
17992    offset where it ends.  */
17993
17994 bool
17995 rs6000_is_valid_mask (rtx mask, int *b, int *e, machine_mode mode)
17996 {
17997   unsigned HOST_WIDE_INT val = INTVAL (mask);
17998   unsigned HOST_WIDE_INT bit;
17999   int nb, ne;
18000   int n = GET_MODE_PRECISION (mode);
18001
18002   if (mode != DImode && mode != SImode)
18003     return false;
18004
18005   if (INTVAL (mask) >= 0)
18006     {
18007       bit = val & -val;
18008       ne = exact_log2 (bit);
18009       nb = exact_log2 (val + bit);
18010     }
18011   else if (val + 1 == 0)
18012     {
18013       nb = n;
18014       ne = 0;
18015     }
18016   else if (val & 1)
18017     {
18018       val = ~val;
18019       bit = val & -val;
18020       nb = exact_log2 (bit);
18021       ne = exact_log2 (val + bit);
18022     }
18023   else
18024     {
18025       bit = val & -val;
18026       ne = exact_log2 (bit);
18027       if (val + bit == 0)
18028         nb = n;
18029       else
18030         nb = 0;
18031     }
18032
18033   nb--;
18034
18035   if (nb < 0 || ne < 0 || nb >= n || ne >= n)
18036     return false;
18037
18038   if (b)
18039     *b = nb;
18040   if (e)
18041     *e = ne;
18042
18043   return true;
18044 }
18045
18046 /* Return whether MASK (a CONST_INT) is a valid mask for any rlwinm, rldicl,
18047    or rldicr instruction, to implement an AND with it in mode MODE.  */
18048
18049 bool
18050 rs6000_is_valid_and_mask (rtx mask, machine_mode mode)
18051 {
18052   int nb, ne;
18053
18054   if (!rs6000_is_valid_mask (mask, &nb, &ne, mode))
18055     return false;
18056
18057   /* For DImode, we need a rldicl, rldicr, or a rlwinm with mask that
18058      does not wrap.  */
18059   if (mode == DImode)
18060     return (ne == 0 || nb == 63 || (nb < 32 && ne <= nb));
18061
18062   /* For SImode, rlwinm can do everything.  */
18063   if (mode == SImode)
18064     return (nb < 32 && ne < 32);
18065
18066   return false;
18067 }
18068
18069 /* Return the instruction template for an AND with mask in mode MODE, with
18070    operands OPERANDS.  If DOT is true, make it a record-form instruction.  */
18071
18072 const char *
18073 rs6000_insn_for_and_mask (machine_mode mode, rtx *operands, bool dot)
18074 {
18075   int nb, ne;
18076
18077   if (!rs6000_is_valid_mask (operands[2], &nb, &ne, mode))
18078     gcc_unreachable ();
18079
18080   if (mode == DImode && ne == 0)
18081     {
18082       operands[3] = GEN_INT (63 - nb);
18083       if (dot)
18084         return "rldicl. %0,%1,0,%3";
18085       return "rldicl %0,%1,0,%3";
18086     }
18087
18088   if (mode == DImode && nb == 63)
18089     {
18090       operands[3] = GEN_INT (63 - ne);
18091       if (dot)
18092         return "rldicr. %0,%1,0,%3";
18093       return "rldicr %0,%1,0,%3";
18094     }
18095
18096   if (nb < 32 && ne < 32)
18097     {
18098       operands[3] = GEN_INT (31 - nb);
18099       operands[4] = GEN_INT (31 - ne);
18100       if (dot)
18101         return "rlwinm. %0,%1,0,%3,%4";
18102       return "rlwinm %0,%1,0,%3,%4";
18103     }
18104
18105   gcc_unreachable ();
18106 }
18107
18108 /* Return whether MASK (a CONST_INT) is a valid mask for any rlw[i]nm,
18109    rld[i]cl, rld[i]cr, or rld[i]c instruction, to implement an AND with
18110    shift SHIFT (a ROTATE, ASHIFT, or LSHIFTRT) in mode MODE.  */
18111
18112 bool
18113 rs6000_is_valid_shift_mask (rtx mask, rtx shift, machine_mode mode)
18114 {
18115   int nb, ne;
18116
18117   if (!rs6000_is_valid_mask (mask, &nb, &ne, mode))
18118     return false;
18119
18120   int n = GET_MODE_PRECISION (mode);
18121   int sh = -1;
18122
18123   if (CONST_INT_P (XEXP (shift, 1)))
18124     {
18125       sh = INTVAL (XEXP (shift, 1));
18126       if (sh < 0 || sh >= n)
18127         return false;
18128     }
18129
18130   rtx_code code = GET_CODE (shift);
18131
18132   /* Convert any shift by 0 to a rotate, to simplify below code.  */
18133   if (sh == 0)
18134     code = ROTATE;
18135
18136   /* Convert rotate to simple shift if we can, to make analysis simpler.  */
18137   if (code == ROTATE && sh >= 0 && nb >= ne && ne >= sh)
18138     code = ASHIFT;
18139   if (code == ROTATE && sh >= 0 && nb >= ne && nb < sh)
18140     {
18141       code = LSHIFTRT;
18142       sh = n - sh;
18143     }
18144
18145   /* DImode rotates need rld*.  */
18146   if (mode == DImode && code == ROTATE)
18147     return (nb == 63 || ne == 0 || ne == sh);
18148
18149   /* SImode rotates need rlw*.  */
18150   if (mode == SImode && code == ROTATE)
18151     return (nb < 32 && ne < 32 && sh < 32);
18152
18153   /* Wrap-around masks are only okay for rotates.  */
18154   if (ne > nb)
18155     return false;
18156
18157   /* Variable shifts are only okay for rotates.  */
18158   if (sh < 0)
18159     return false;
18160
18161   /* Don't allow ASHIFT if the mask is wrong for that.  */
18162   if (code == ASHIFT && ne < sh)
18163     return false;
18164
18165   /* If we can do it with an rlw*, we can do it.  Don't allow LSHIFTRT
18166      if the mask is wrong for that.  */
18167   if (nb < 32 && ne < 32 && sh < 32
18168       && !(code == LSHIFTRT && nb >= 32 - sh))
18169     return true;
18170
18171   /* If we can do it with an rld*, we can do it.  Don't allow LSHIFTRT
18172      if the mask is wrong for that.  */
18173   if (code == LSHIFTRT)
18174     sh = 64 - sh;
18175   if (nb == 63 || ne == 0 || ne == sh)
18176     return !(code == LSHIFTRT && nb >= sh);
18177
18178   return false;
18179 }
18180
18181 /* Return the instruction template for a shift with mask in mode MODE, with
18182    operands OPERANDS.  If DOT is true, make it a record-form instruction.  */
18183
18184 const char *
18185 rs6000_insn_for_shift_mask (machine_mode mode, rtx *operands, bool dot)
18186 {
18187   int nb, ne;
18188
18189   if (!rs6000_is_valid_mask (operands[3], &nb, &ne, mode))
18190     gcc_unreachable ();
18191
18192   if (mode == DImode && ne == 0)
18193     {
18194       if (GET_CODE (operands[4]) == LSHIFTRT && INTVAL (operands[2]))
18195         operands[2] = GEN_INT (64 - INTVAL (operands[2]));
18196       operands[3] = GEN_INT (63 - nb);
18197       if (dot)
18198         return "rld%I2cl. %0,%1,%2,%3";
18199       return "rld%I2cl %0,%1,%2,%3";
18200     }
18201
18202   if (mode == DImode && nb == 63)
18203     {
18204       operands[3] = GEN_INT (63 - ne);
18205       if (dot)
18206         return "rld%I2cr. %0,%1,%2,%3";
18207       return "rld%I2cr %0,%1,%2,%3";
18208     }
18209
18210   if (mode == DImode
18211       && GET_CODE (operands[4]) != LSHIFTRT
18212       && CONST_INT_P (operands[2])
18213       && ne == INTVAL (operands[2]))
18214     {
18215       operands[3] = GEN_INT (63 - nb);
18216       if (dot)
18217         return "rld%I2c. %0,%1,%2,%3";
18218       return "rld%I2c %0,%1,%2,%3";
18219     }
18220
18221   if (nb < 32 && ne < 32)
18222     {
18223       if (GET_CODE (operands[4]) == LSHIFTRT && INTVAL (operands[2]))
18224         operands[2] = GEN_INT (32 - INTVAL (operands[2]));
18225       operands[3] = GEN_INT (31 - nb);
18226       operands[4] = GEN_INT (31 - ne);
18227       /* This insn can also be a 64-bit rotate with mask that really makes
18228          it just a shift right (with mask); the %h below are to adjust for
18229          that situation (shift count is >= 32 in that case).  */
18230       if (dot)
18231         return "rlw%I2nm. %0,%1,%h2,%3,%4";
18232       return "rlw%I2nm %0,%1,%h2,%3,%4";
18233     }
18234
18235   gcc_unreachable ();
18236 }
18237
18238 /* Return whether MASK (a CONST_INT) is a valid mask for any rlwimi or
18239    rldimi instruction, to implement an insert with shift SHIFT (a ROTATE,
18240    ASHIFT, or LSHIFTRT) in mode MODE.  */
18241
18242 bool
18243 rs6000_is_valid_insert_mask (rtx mask, rtx shift, machine_mode mode)
18244 {
18245   int nb, ne;
18246
18247   if (!rs6000_is_valid_mask (mask, &nb, &ne, mode))
18248     return false;
18249
18250   int n = GET_MODE_PRECISION (mode);
18251
18252   int sh = INTVAL (XEXP (shift, 1));
18253   if (sh < 0 || sh >= n)
18254     return false;
18255
18256   rtx_code code = GET_CODE (shift);
18257
18258   /* Convert any shift by 0 to a rotate, to simplify below code.  */
18259   if (sh == 0)
18260     code = ROTATE;
18261
18262   /* Convert rotate to simple shift if we can, to make analysis simpler.  */
18263   if (code == ROTATE && sh >= 0 && nb >= ne && ne >= sh)
18264     code = ASHIFT;
18265   if (code == ROTATE && sh >= 0 && nb >= ne && nb < sh)
18266     {
18267       code = LSHIFTRT;
18268       sh = n - sh;
18269     }
18270
18271   /* DImode rotates need rldimi.  */
18272   if (mode == DImode && code == ROTATE)
18273     return (ne == sh);
18274
18275   /* SImode rotates need rlwimi.  */
18276   if (mode == SImode && code == ROTATE)
18277     return (nb < 32 && ne < 32 && sh < 32);
18278
18279   /* Wrap-around masks are only okay for rotates.  */
18280   if (ne > nb)
18281     return false;
18282
18283   /* Don't allow ASHIFT if the mask is wrong for that.  */
18284   if (code == ASHIFT && ne < sh)
18285     return false;
18286
18287   /* If we can do it with an rlwimi, we can do it.  Don't allow LSHIFTRT
18288      if the mask is wrong for that.  */
18289   if (nb < 32 && ne < 32 && sh < 32
18290       && !(code == LSHIFTRT && nb >= 32 - sh))
18291     return true;
18292
18293   /* If we can do it with an rldimi, we can do it.  Don't allow LSHIFTRT
18294      if the mask is wrong for that.  */
18295   if (code == LSHIFTRT)
18296     sh = 64 - sh;
18297   if (ne == sh)
18298     return !(code == LSHIFTRT && nb >= sh);
18299
18300   return false;
18301 }
18302
18303 /* Return the instruction template for an insert with mask in mode MODE, with
18304    operands OPERANDS.  If DOT is true, make it a record-form instruction.  */
18305
18306 const char *
18307 rs6000_insn_for_insert_mask (machine_mode mode, rtx *operands, bool dot)
18308 {
18309   int nb, ne;
18310
18311   if (!rs6000_is_valid_mask (operands[3], &nb, &ne, mode))
18312     gcc_unreachable ();
18313
18314   /* Prefer rldimi because rlwimi is cracked.  */
18315   if (TARGET_POWERPC64
18316       && (!dot || mode == DImode)
18317       && GET_CODE (operands[4]) != LSHIFTRT
18318       && ne == INTVAL (operands[2]))
18319     {
18320       operands[3] = GEN_INT (63 - nb);
18321       if (dot)
18322         return "rldimi. %0,%1,%2,%3";
18323       return "rldimi %0,%1,%2,%3";
18324     }
18325
18326   if (nb < 32 && ne < 32)
18327     {
18328       if (GET_CODE (operands[4]) == LSHIFTRT && INTVAL (operands[2]))
18329         operands[2] = GEN_INT (32 - INTVAL (operands[2]));
18330       operands[3] = GEN_INT (31 - nb);
18331       operands[4] = GEN_INT (31 - ne);
18332       if (dot)
18333         return "rlwimi. %0,%1,%2,%3,%4";
18334       return "rlwimi %0,%1,%2,%3,%4";
18335     }
18336
18337   gcc_unreachable ();
18338 }
18339
18340 /* Return whether an AND with C (a CONST_INT) in mode MODE can be done
18341    using two machine instructions.  */
18342
18343 bool
18344 rs6000_is_valid_2insn_and (rtx c, machine_mode mode)
18345 {
18346   /* There are two kinds of AND we can handle with two insns:
18347      1) those we can do with two rl* insn;
18348      2) ori[s];xori[s].
18349
18350      We do not handle that last case yet.  */
18351
18352   /* If there is just one stretch of ones, we can do it.  */
18353   if (rs6000_is_valid_mask (c, NULL, NULL, mode))
18354     return true;
18355
18356   /* Otherwise, fill in the lowest "hole"; if we can do the result with
18357      one insn, we can do the whole thing with two.  */
18358   unsigned HOST_WIDE_INT val = INTVAL (c);
18359   unsigned HOST_WIDE_INT bit1 = val & -val;
18360   unsigned HOST_WIDE_INT bit2 = (val + bit1) & ~val;
18361   unsigned HOST_WIDE_INT val1 = (val + bit1) & val;
18362   unsigned HOST_WIDE_INT bit3 = val1 & -val1;
18363   return rs6000_is_valid_and_mask (GEN_INT (val + bit3 - bit2), mode);
18364 }
18365
18366 /* Emit the two insns to do an AND in mode MODE, with operands OPERANDS.
18367    If EXPAND is true, split rotate-and-mask instructions we generate to
18368    their constituent parts as well (this is used during expand); if DOT
18369    is 1, make the last insn a record-form instruction clobbering the
18370    destination GPR and setting the CC reg (from operands[3]); if 2, set
18371    that GPR as well as the CC reg.  */
18372
18373 void
18374 rs6000_emit_2insn_and (machine_mode mode, rtx *operands, bool expand, int dot)
18375 {
18376   gcc_assert (!(expand && dot));
18377
18378   unsigned HOST_WIDE_INT val = INTVAL (operands[2]);
18379
18380   /* If it is one stretch of ones, it is DImode; shift left, mask, then
18381      shift right.  This generates better code than doing the masks without
18382      shifts, or shifting first right and then left.  */
18383   int nb, ne;
18384   if (rs6000_is_valid_mask (operands[2], &nb, &ne, mode) && nb >= ne)
18385     {
18386       gcc_assert (mode == DImode);
18387
18388       int shift = 63 - nb;
18389       if (expand)
18390         {
18391           rtx tmp1 = gen_reg_rtx (DImode);
18392           rtx tmp2 = gen_reg_rtx (DImode);
18393           emit_insn (gen_ashldi3 (tmp1, operands[1], GEN_INT (shift)));
18394           emit_insn (gen_anddi3 (tmp2, tmp1, GEN_INT (val << shift)));
18395           emit_insn (gen_lshrdi3 (operands[0], tmp2, GEN_INT (shift)));
18396         }
18397       else
18398         {
18399           rtx tmp = gen_rtx_ASHIFT (mode, operands[1], GEN_INT (shift));
18400           tmp = gen_rtx_AND (mode, tmp, GEN_INT (val << shift));
18401           emit_move_insn (operands[0], tmp);
18402           tmp = gen_rtx_LSHIFTRT (mode, operands[0], GEN_INT (shift));
18403           rs6000_emit_dot_insn (operands[0], tmp, dot, dot ? operands[3] : 0);
18404         }
18405       return;
18406     }
18407
18408   /* Otherwise, make a mask2 that cuts out the lowest "hole", and a mask1
18409      that does the rest.  */
18410   unsigned HOST_WIDE_INT bit1 = val & -val;
18411   unsigned HOST_WIDE_INT bit2 = (val + bit1) & ~val;
18412   unsigned HOST_WIDE_INT val1 = (val + bit1) & val;
18413   unsigned HOST_WIDE_INT bit3 = val1 & -val1;
18414
18415   unsigned HOST_WIDE_INT mask1 = -bit3 + bit2 - 1;
18416   unsigned HOST_WIDE_INT mask2 = val + bit3 - bit2;
18417
18418   gcc_assert (rs6000_is_valid_and_mask (GEN_INT (mask2), mode));
18419
18420   /* Two "no-rotate"-and-mask instructions, for SImode.  */
18421   if (rs6000_is_valid_and_mask (GEN_INT (mask1), mode))
18422     {
18423       gcc_assert (mode == SImode);
18424
18425       rtx reg = expand ? gen_reg_rtx (mode) : operands[0];
18426       rtx tmp = gen_rtx_AND (mode, operands[1], GEN_INT (mask1));
18427       emit_move_insn (reg, tmp);
18428       tmp = gen_rtx_AND (mode, reg, GEN_INT (mask2));
18429       rs6000_emit_dot_insn (operands[0], tmp, dot, dot ? operands[3] : 0);
18430       return;
18431     }
18432
18433   gcc_assert (mode == DImode);
18434
18435   /* Two "no-rotate"-and-mask instructions, for DImode: both are rlwinm
18436      insns; we have to do the first in SImode, because it wraps.  */
18437   if (mask2 <= 0xffffffff
18438       && rs6000_is_valid_and_mask (GEN_INT (mask1), SImode))
18439     {
18440       rtx reg = expand ? gen_reg_rtx (mode) : operands[0];
18441       rtx tmp = gen_rtx_AND (SImode, gen_lowpart (SImode, operands[1]),
18442                              GEN_INT (mask1));
18443       rtx reg_low = gen_lowpart (SImode, reg);
18444       emit_move_insn (reg_low, tmp);
18445       tmp = gen_rtx_AND (mode, reg, GEN_INT (mask2));
18446       rs6000_emit_dot_insn (operands[0], tmp, dot, dot ? operands[3] : 0);
18447       return;
18448     }
18449
18450   /* Two rld* insns: rotate, clear the hole in the middle (which now is
18451      at the top end), rotate back and clear the other hole.  */
18452   int right = exact_log2 (bit3);
18453   int left = 64 - right;
18454
18455   /* Rotate the mask too.  */
18456   mask1 = (mask1 >> right) | ((bit2 - 1) << left);
18457
18458   if (expand)
18459     {
18460       rtx tmp1 = gen_reg_rtx (DImode);
18461       rtx tmp2 = gen_reg_rtx (DImode);
18462       rtx tmp3 = gen_reg_rtx (DImode);
18463       emit_insn (gen_rotldi3 (tmp1, operands[1], GEN_INT (left)));
18464       emit_insn (gen_anddi3 (tmp2, tmp1, GEN_INT (mask1)));
18465       emit_insn (gen_rotldi3 (tmp3, tmp2, GEN_INT (right)));
18466       emit_insn (gen_anddi3 (operands[0], tmp3, GEN_INT (mask2)));
18467     }
18468   else
18469     {
18470       rtx tmp = gen_rtx_ROTATE (mode, operands[1], GEN_INT (left));
18471       tmp = gen_rtx_AND (mode, tmp, GEN_INT (mask1));
18472       emit_move_insn (operands[0], tmp);
18473       tmp = gen_rtx_ROTATE (mode, operands[0], GEN_INT (right));
18474       tmp = gen_rtx_AND (mode, tmp, GEN_INT (mask2));
18475       rs6000_emit_dot_insn (operands[0], tmp, dot, dot ? operands[3] : 0);
18476     }
18477 }
18478 \f
18479 /* Return 1 if REGNO (reg1) == REGNO (reg2) - 1 making them candidates
18480    for lfq and stfq insns iff the registers are hard registers.   */
18481
18482 int
18483 registers_ok_for_quad_peep (rtx reg1, rtx reg2)
18484 {
18485   /* We might have been passed a SUBREG.  */
18486   if (!REG_P (reg1) || !REG_P (reg2))
18487     return 0;
18488
18489   /* We might have been passed non floating point registers.  */
18490   if (!FP_REGNO_P (REGNO (reg1))
18491       || !FP_REGNO_P (REGNO (reg2)))
18492     return 0;
18493
18494   return (REGNO (reg1) == REGNO (reg2) - 1);
18495 }
18496
18497 /* Return 1 if addr1 and addr2 are suitable for lfq or stfq insn.
18498    addr1 and addr2 must be in consecutive memory locations
18499    (addr2 == addr1 + 8).  */
18500
18501 int
18502 mems_ok_for_quad_peep (rtx mem1, rtx mem2)
18503 {
18504   rtx addr1, addr2;
18505   unsigned int reg1, reg2;
18506   int offset1, offset2;
18507
18508   /* The mems cannot be volatile.  */
18509   if (MEM_VOLATILE_P (mem1) || MEM_VOLATILE_P (mem2))
18510     return 0;
18511
18512   addr1 = XEXP (mem1, 0);
18513   addr2 = XEXP (mem2, 0);
18514
18515   /* Extract an offset (if used) from the first addr.  */
18516   if (GET_CODE (addr1) == PLUS)
18517     {
18518       /* If not a REG, return zero.  */
18519       if (!REG_P (XEXP (addr1, 0)))
18520         return 0;
18521       else
18522         {
18523           reg1 = REGNO (XEXP (addr1, 0));
18524           /* The offset must be constant!  */
18525           if (!CONST_INT_P (XEXP (addr1, 1)))
18526             return 0;
18527           offset1 = INTVAL (XEXP (addr1, 1));
18528         }
18529     }
18530   else if (!REG_P (addr1))
18531     return 0;
18532   else
18533     {
18534       reg1 = REGNO (addr1);
18535       /* This was a simple (mem (reg)) expression.  Offset is 0.  */
18536       offset1 = 0;
18537     }
18538
18539   /* And now for the second addr.  */
18540   if (GET_CODE (addr2) == PLUS)
18541     {
18542       /* If not a REG, return zero.  */
18543       if (!REG_P (XEXP (addr2, 0)))
18544         return 0;
18545       else
18546         {
18547           reg2 = REGNO (XEXP (addr2, 0));
18548           /* The offset must be constant. */
18549           if (!CONST_INT_P (XEXP (addr2, 1)))
18550             return 0;
18551           offset2 = INTVAL (XEXP (addr2, 1));
18552         }
18553     }
18554   else if (!REG_P (addr2))
18555     return 0;
18556   else
18557     {
18558       reg2 = REGNO (addr2);
18559       /* This was a simple (mem (reg)) expression.  Offset is 0.  */
18560       offset2 = 0;
18561     }
18562
18563   /* Both of these must have the same base register.  */
18564   if (reg1 != reg2)
18565     return 0;
18566
18567   /* The offset for the second addr must be 8 more than the first addr.  */
18568   if (offset2 != offset1 + 8)
18569     return 0;
18570
18571   /* All the tests passed.  addr1 and addr2 are valid for lfq or stfq
18572      instructions.  */
18573   return 1;
18574 }
18575 \f
18576 /* Implement TARGET_SECONDARY_RELOAD_NEEDED_MODE.  For SDmode values we
18577    need to use DDmode, in all other cases we can use the same mode.  */
18578 static machine_mode
18579 rs6000_secondary_memory_needed_mode (machine_mode mode)
18580 {
18581   if (lra_in_progress && mode == SDmode)
18582     return DDmode;
18583   return mode;
18584 }
18585
18586 /* Classify a register type.  Because the FMRGOW/FMRGEW instructions only work
18587    on traditional floating point registers, and the VMRGOW/VMRGEW instructions
18588    only work on the traditional altivec registers, note if an altivec register
18589    was chosen.  */
18590
18591 static enum rs6000_reg_type
18592 register_to_reg_type (rtx reg, bool *is_altivec)
18593 {
18594   HOST_WIDE_INT regno;
18595   enum reg_class rclass;
18596
18597   if (SUBREG_P (reg))
18598     reg = SUBREG_REG (reg);
18599
18600   if (!REG_P (reg))
18601     return NO_REG_TYPE;
18602
18603   regno = REGNO (reg);
18604   if (!HARD_REGISTER_NUM_P (regno))
18605     {
18606       if (!lra_in_progress && !reload_completed)
18607         return PSEUDO_REG_TYPE;
18608
18609       regno = true_regnum (reg);
18610       if (regno < 0 || !HARD_REGISTER_NUM_P (regno))
18611         return PSEUDO_REG_TYPE;
18612     }
18613
18614   gcc_assert (regno >= 0);
18615
18616   if (is_altivec && ALTIVEC_REGNO_P (regno))
18617     *is_altivec = true;
18618
18619   rclass = rs6000_regno_regclass[regno];
18620   return reg_class_to_reg_type[(int)rclass];
18621 }
18622
18623 /* Helper function to return the cost of adding a TOC entry address.  */
18624
18625 static inline int
18626 rs6000_secondary_reload_toc_costs (addr_mask_type addr_mask)
18627 {
18628   int ret;
18629
18630   if (TARGET_CMODEL != CMODEL_SMALL)
18631     ret = ((addr_mask & RELOAD_REG_OFFSET) == 0) ? 1 : 2;
18632
18633   else
18634     ret = (TARGET_MINIMAL_TOC) ? 6 : 3;
18635
18636   return ret;
18637 }
18638
18639 /* Helper function for rs6000_secondary_reload to determine whether the memory
18640    address (ADDR) with a given register class (RCLASS) and machine mode (MODE)
18641    needs reloading.  Return negative if the memory is not handled by the memory
18642    helper functions and to try a different reload method, 0 if no additional
18643    instructions are need, and positive to give the extra cost for the
18644    memory.  */
18645
18646 static int
18647 rs6000_secondary_reload_memory (rtx addr,
18648                                 enum reg_class rclass,
18649                                 machine_mode mode)
18650 {
18651   int extra_cost = 0;
18652   rtx reg, and_arg, plus_arg0, plus_arg1;
18653   addr_mask_type addr_mask;
18654   const char *type = NULL;
18655   const char *fail_msg = NULL;
18656
18657   if (GPR_REG_CLASS_P (rclass))
18658     addr_mask = reg_addr[mode].addr_mask[RELOAD_REG_GPR];
18659
18660   else if (rclass == FLOAT_REGS)
18661     addr_mask = reg_addr[mode].addr_mask[RELOAD_REG_FPR];
18662
18663   else if (rclass == ALTIVEC_REGS)
18664     addr_mask = reg_addr[mode].addr_mask[RELOAD_REG_VMX];
18665
18666   /* For the combined VSX_REGS, turn off Altivec AND -16.  */
18667   else if (rclass == VSX_REGS)
18668     addr_mask = (reg_addr[mode].addr_mask[RELOAD_REG_VMX]
18669                  & ~RELOAD_REG_AND_M16);
18670
18671   /* If the register allocator hasn't made up its mind yet on the register
18672      class to use, settle on defaults to use.  */
18673   else if (rclass == NO_REGS)
18674     {
18675       addr_mask = (reg_addr[mode].addr_mask[RELOAD_REG_ANY]
18676                    & ~RELOAD_REG_AND_M16);
18677
18678       if ((addr_mask & RELOAD_REG_MULTIPLE) != 0)
18679         addr_mask &= ~(RELOAD_REG_INDEXED
18680                        | RELOAD_REG_PRE_INCDEC
18681                        | RELOAD_REG_PRE_MODIFY);
18682     }
18683
18684   else
18685     addr_mask = 0;
18686
18687   /* If the register isn't valid in this register class, just return now.  */
18688   if ((addr_mask & RELOAD_REG_VALID) == 0)
18689     {
18690       if (TARGET_DEBUG_ADDR)
18691         {
18692           fprintf (stderr,
18693                    "rs6000_secondary_reload_memory: mode = %s, class = %s, "
18694                    "not valid in class\n",
18695                    GET_MODE_NAME (mode), reg_class_names[rclass]);
18696           debug_rtx (addr);
18697         }
18698
18699       return -1;
18700     }
18701
18702   switch (GET_CODE (addr))
18703     {
18704       /* Does the register class supports auto update forms for this mode?  We
18705          don't need a scratch register, since the powerpc only supports
18706          PRE_INC, PRE_DEC, and PRE_MODIFY.  */
18707     case PRE_INC:
18708     case PRE_DEC:
18709       reg = XEXP (addr, 0);
18710       if (!base_reg_operand (addr, GET_MODE (reg)))
18711         {
18712           fail_msg = "no base register #1";
18713           extra_cost = -1;
18714         }
18715
18716       else if ((addr_mask & RELOAD_REG_PRE_INCDEC) == 0)
18717         {
18718           extra_cost = 1;
18719           type = "update";
18720         }
18721       break;
18722
18723     case PRE_MODIFY:
18724       reg = XEXP (addr, 0);
18725       plus_arg1 = XEXP (addr, 1);
18726       if (!base_reg_operand (reg, GET_MODE (reg))
18727           || GET_CODE (plus_arg1) != PLUS
18728           || !rtx_equal_p (reg, XEXP (plus_arg1, 0)))
18729         {
18730           fail_msg = "bad PRE_MODIFY";
18731           extra_cost = -1;
18732         }
18733
18734       else if ((addr_mask & RELOAD_REG_PRE_MODIFY) == 0)
18735         {
18736           extra_cost = 1;
18737           type = "update";
18738         }
18739       break;
18740
18741       /* Do we need to simulate AND -16 to clear the bottom address bits used
18742          in VMX load/stores?  Only allow the AND for vector sizes.  */
18743     case AND:
18744       and_arg = XEXP (addr, 0);
18745       if (GET_MODE_SIZE (mode) != 16
18746           || !CONST_INT_P (XEXP (addr, 1))
18747           || INTVAL (XEXP (addr, 1)) != -16)
18748         {
18749           fail_msg = "bad Altivec AND #1";
18750           extra_cost = -1;
18751         }
18752
18753       if (rclass != ALTIVEC_REGS)
18754         {
18755           if (legitimate_indirect_address_p (and_arg, false))
18756             extra_cost = 1;
18757
18758           else if (legitimate_indexed_address_p (and_arg, false))
18759             extra_cost = 2;
18760
18761           else
18762             {
18763               fail_msg = "bad Altivec AND #2";
18764               extra_cost = -1;
18765             }
18766
18767           type = "and";
18768         }
18769       break;
18770
18771       /* If this is an indirect address, make sure it is a base register.  */
18772     case REG:
18773     case SUBREG:
18774       if (!legitimate_indirect_address_p (addr, false))
18775         {
18776           extra_cost = 1;
18777           type = "move";
18778         }
18779       break;
18780
18781       /* If this is an indexed address, make sure the register class can handle
18782          indexed addresses for this mode.  */
18783     case PLUS:
18784       plus_arg0 = XEXP (addr, 0);
18785       plus_arg1 = XEXP (addr, 1);
18786
18787       /* (plus (plus (reg) (constant)) (constant)) is generated during
18788          push_reload processing, so handle it now.  */
18789       if (GET_CODE (plus_arg0) == PLUS && CONST_INT_P (plus_arg1))
18790         {
18791           if ((addr_mask & RELOAD_REG_OFFSET) == 0)
18792             {
18793               extra_cost = 1;
18794               type = "offset";
18795             }
18796         }
18797
18798       /* (plus (plus (reg) (constant)) (reg)) is also generated during
18799          push_reload processing, so handle it now.  */
18800       else if (GET_CODE (plus_arg0) == PLUS && REG_P (plus_arg1))
18801         {
18802           if ((addr_mask & RELOAD_REG_INDEXED) == 0)
18803             {
18804               extra_cost = 1;
18805               type = "indexed #2";
18806             }
18807         }
18808
18809       else if (!base_reg_operand (plus_arg0, GET_MODE (plus_arg0)))
18810         {
18811           fail_msg = "no base register #2";
18812           extra_cost = -1;
18813         }
18814
18815       else if (int_reg_operand (plus_arg1, GET_MODE (plus_arg1)))
18816         {
18817           if ((addr_mask & RELOAD_REG_INDEXED) == 0
18818               || !legitimate_indexed_address_p (addr, false))
18819             {
18820               extra_cost = 1;
18821               type = "indexed";
18822             }
18823         }
18824
18825       else if ((addr_mask & RELOAD_REG_QUAD_OFFSET) != 0
18826                && CONST_INT_P (plus_arg1))
18827         {
18828           if (!quad_address_offset_p (INTVAL (plus_arg1)))
18829             {
18830               extra_cost = 1;
18831               type = "vector d-form offset";
18832             }
18833         }
18834
18835       /* Make sure the register class can handle offset addresses.  */
18836       else if (rs6000_legitimate_offset_address_p (mode, addr, false, true))
18837         {
18838           if ((addr_mask & RELOAD_REG_OFFSET) == 0)
18839             {
18840               extra_cost = 1;
18841               type = "offset #2";
18842             }
18843         }
18844
18845       else
18846         {
18847           fail_msg = "bad PLUS";
18848           extra_cost = -1;
18849         }
18850
18851       break;
18852
18853     case LO_SUM:
18854       /* Quad offsets are restricted and can't handle normal addresses.  */
18855       if ((addr_mask & RELOAD_REG_QUAD_OFFSET) != 0)
18856         {
18857           extra_cost = -1;
18858           type = "vector d-form lo_sum";
18859         }
18860
18861       else if (!legitimate_lo_sum_address_p (mode, addr, false))
18862         {
18863           fail_msg = "bad LO_SUM";
18864           extra_cost = -1;
18865         }
18866
18867       if ((addr_mask & RELOAD_REG_OFFSET) == 0)
18868         {
18869           extra_cost = 1;
18870           type = "lo_sum";
18871         }
18872       break;
18873
18874       /* Static addresses need to create a TOC entry.  */
18875     case CONST:
18876     case SYMBOL_REF:
18877     case LABEL_REF:
18878       if ((addr_mask & RELOAD_REG_QUAD_OFFSET) != 0)
18879         {
18880           extra_cost = -1;
18881           type = "vector d-form lo_sum #2";
18882         }
18883
18884       else
18885         {
18886           type = "address";
18887           extra_cost = rs6000_secondary_reload_toc_costs (addr_mask);
18888         }
18889       break;
18890
18891       /* TOC references look like offsetable memory.  */
18892     case UNSPEC:
18893       if (TARGET_CMODEL == CMODEL_SMALL || XINT (addr, 1) != UNSPEC_TOCREL)
18894         {
18895           fail_msg = "bad UNSPEC";
18896           extra_cost = -1;
18897         }
18898
18899       else if ((addr_mask & RELOAD_REG_QUAD_OFFSET) != 0)
18900         {
18901           extra_cost = -1;
18902           type = "vector d-form lo_sum #3";
18903         }
18904
18905       else if ((addr_mask & RELOAD_REG_OFFSET) == 0)
18906         {
18907           extra_cost = 1;
18908           type = "toc reference";
18909         }
18910       break;
18911
18912     default:
18913         {
18914           fail_msg = "bad address";
18915           extra_cost = -1;
18916         }
18917     }
18918
18919   if (TARGET_DEBUG_ADDR /* && extra_cost != 0 */)
18920     {
18921       if (extra_cost < 0)
18922         fprintf (stderr,
18923                  "rs6000_secondary_reload_memory error: mode = %s, "
18924                  "class = %s, addr_mask = '%s', %s\n",
18925                  GET_MODE_NAME (mode),
18926                  reg_class_names[rclass],
18927                  rs6000_debug_addr_mask (addr_mask, false),
18928                  (fail_msg != NULL) ? fail_msg : "<bad address>");
18929
18930       else
18931         fprintf (stderr,
18932                  "rs6000_secondary_reload_memory: mode = %s, class = %s, "
18933                  "addr_mask = '%s', extra cost = %d, %s\n",
18934                  GET_MODE_NAME (mode),
18935                  reg_class_names[rclass],
18936                  rs6000_debug_addr_mask (addr_mask, false),
18937                  extra_cost,
18938                  (type) ? type : "<none>");
18939
18940       debug_rtx (addr);
18941     }
18942
18943   return extra_cost;
18944 }
18945
18946 /* Helper function for rs6000_secondary_reload to return true if a move to a
18947    different register classe is really a simple move.  */
18948
18949 static bool
18950 rs6000_secondary_reload_simple_move (enum rs6000_reg_type to_type,
18951                                      enum rs6000_reg_type from_type,
18952                                      machine_mode mode)
18953 {
18954   int size = GET_MODE_SIZE (mode);
18955
18956   /* Add support for various direct moves available.  In this function, we only
18957      look at cases where we don't need any extra registers, and one or more
18958      simple move insns are issued.  Originally small integers are not allowed
18959      in FPR/VSX registers.  Single precision binary floating is not a simple
18960      move because we need to convert to the single precision memory layout.
18961      The 4-byte SDmode can be moved.  TDmode values are disallowed since they
18962      need special direct move handling, which we do not support yet.  */
18963   if (TARGET_DIRECT_MOVE
18964       && ((to_type == GPR_REG_TYPE && from_type == VSX_REG_TYPE)
18965           || (to_type == VSX_REG_TYPE && from_type == GPR_REG_TYPE)))
18966     {
18967       if (TARGET_POWERPC64)
18968         {
18969           /* ISA 2.07: MTVSRD or MVFVSRD.  */
18970           if (size == 8)
18971             return true;
18972
18973           /* ISA 3.0: MTVSRDD or MFVSRD + MFVSRLD.  */
18974           if (size == 16 && TARGET_P9_VECTOR && mode != TDmode)
18975             return true;
18976         }
18977
18978       /* ISA 2.07: MTVSRWZ or  MFVSRWZ.  */
18979       if (TARGET_P8_VECTOR)
18980         {
18981           if (mode == SImode)
18982             return true;
18983
18984           if (TARGET_P9_VECTOR && (mode == HImode || mode == QImode))
18985             return true;
18986         }
18987
18988       /* ISA 2.07: MTVSRWZ or  MFVSRWZ.  */
18989       if (mode == SDmode)
18990         return true;
18991     }
18992
18993   /* Move to/from SPR.  */
18994   else if ((size == 4 || (TARGET_POWERPC64 && size == 8))
18995            && ((to_type == GPR_REG_TYPE && from_type == SPR_REG_TYPE)
18996                || (to_type == SPR_REG_TYPE && from_type == GPR_REG_TYPE)))
18997     return true;
18998
18999   return false;
19000 }
19001
19002 /* Direct move helper function for rs6000_secondary_reload, handle all of the
19003    special direct moves that involve allocating an extra register, return the
19004    insn code of the helper function if there is such a function or
19005    CODE_FOR_nothing if not.  */
19006
19007 static bool
19008 rs6000_secondary_reload_direct_move (enum rs6000_reg_type to_type,
19009                                      enum rs6000_reg_type from_type,
19010                                      machine_mode mode,
19011                                      secondary_reload_info *sri,
19012                                      bool altivec_p)
19013 {
19014   bool ret = false;
19015   enum insn_code icode = CODE_FOR_nothing;
19016   int cost = 0;
19017   int size = GET_MODE_SIZE (mode);
19018
19019   if (TARGET_POWERPC64 && size == 16)
19020     {
19021       /* Handle moving 128-bit values from GPRs to VSX point registers on
19022          ISA 2.07 (power8, power9) when running in 64-bit mode using
19023          XXPERMDI to glue the two 64-bit values back together.  */
19024       if (to_type == VSX_REG_TYPE && from_type == GPR_REG_TYPE)
19025         {
19026           cost = 3;                     /* 2 mtvsrd's, 1 xxpermdi.  */
19027           icode = reg_addr[mode].reload_vsx_gpr;
19028         }
19029
19030       /* Handle moving 128-bit values from VSX point registers to GPRs on
19031          ISA 2.07 when running in 64-bit mode using XXPERMDI to get access to the
19032          bottom 64-bit value.  */
19033       else if (to_type == GPR_REG_TYPE && from_type == VSX_REG_TYPE)
19034         {
19035           cost = 3;                     /* 2 mfvsrd's, 1 xxpermdi.  */
19036           icode = reg_addr[mode].reload_gpr_vsx;
19037         }
19038     }
19039
19040   else if (TARGET_POWERPC64 && mode == SFmode)
19041     {
19042       if (to_type == GPR_REG_TYPE && from_type == VSX_REG_TYPE)
19043         {
19044           cost = 3;                     /* xscvdpspn, mfvsrd, and.  */
19045           icode = reg_addr[mode].reload_gpr_vsx;
19046         }
19047
19048       else if (to_type == VSX_REG_TYPE && from_type == GPR_REG_TYPE)
19049         {
19050           cost = 2;                     /* mtvsrz, xscvspdpn.  */
19051           icode = reg_addr[mode].reload_vsx_gpr;
19052         }
19053     }
19054
19055   else if (!TARGET_POWERPC64 && size == 8)
19056     {
19057       /* Handle moving 64-bit values from GPRs to floating point registers on
19058          ISA 2.07 when running in 32-bit mode using FMRGOW to glue the two
19059          32-bit values back together.  Altivec register classes must be handled
19060          specially since a different instruction is used, and the secondary
19061          reload support requires a single instruction class in the scratch
19062          register constraint.  However, right now TFmode is not allowed in
19063          Altivec registers, so the pattern will never match.  */
19064       if (to_type == VSX_REG_TYPE && from_type == GPR_REG_TYPE && !altivec_p)
19065         {
19066           cost = 3;                     /* 2 mtvsrwz's, 1 fmrgow.  */
19067           icode = reg_addr[mode].reload_fpr_gpr;
19068         }
19069     }
19070
19071   if (icode != CODE_FOR_nothing)
19072     {
19073       ret = true;
19074       if (sri)
19075         {
19076           sri->icode = icode;
19077           sri->extra_cost = cost;
19078         }
19079     }
19080
19081   return ret;
19082 }
19083
19084 /* Return whether a move between two register classes can be done either
19085    directly (simple move) or via a pattern that uses a single extra temporary
19086    (using ISA 2.07's direct move in this case.  */
19087
19088 static bool
19089 rs6000_secondary_reload_move (enum rs6000_reg_type to_type,
19090                               enum rs6000_reg_type from_type,
19091                               machine_mode mode,
19092                               secondary_reload_info *sri,
19093                               bool altivec_p)
19094 {
19095   /* Fall back to load/store reloads if either type is not a register.  */
19096   if (to_type == NO_REG_TYPE || from_type == NO_REG_TYPE)
19097     return false;
19098
19099   /* If we haven't allocated registers yet, assume the move can be done for the
19100      standard register types.  */
19101   if ((to_type == PSEUDO_REG_TYPE && from_type == PSEUDO_REG_TYPE)
19102       || (to_type == PSEUDO_REG_TYPE && IS_STD_REG_TYPE (from_type))
19103       || (from_type == PSEUDO_REG_TYPE && IS_STD_REG_TYPE (to_type)))
19104     return true;
19105
19106   /* Moves to the same set of registers is a simple move for non-specialized
19107      registers.  */
19108   if (to_type == from_type && IS_STD_REG_TYPE (to_type))
19109     return true;
19110
19111   /* Check whether a simple move can be done directly.  */
19112   if (rs6000_secondary_reload_simple_move (to_type, from_type, mode))
19113     {
19114       if (sri)
19115         {
19116           sri->icode = CODE_FOR_nothing;
19117           sri->extra_cost = 0;
19118         }
19119       return true;
19120     }
19121
19122   /* Now check if we can do it in a few steps.  */
19123   return rs6000_secondary_reload_direct_move (to_type, from_type, mode, sri,
19124                                               altivec_p);
19125 }
19126
19127 /* Inform reload about cases where moving X with a mode MODE to a register in
19128    RCLASS requires an extra scratch or immediate register.  Return the class
19129    needed for the immediate register.
19130
19131    For VSX and Altivec, we may need a register to convert sp+offset into
19132    reg+sp.
19133
19134    For misaligned 64-bit gpr loads and stores we need a register to
19135    convert an offset address to indirect.  */
19136
19137 static reg_class_t
19138 rs6000_secondary_reload (bool in_p,
19139                          rtx x,
19140                          reg_class_t rclass_i,
19141                          machine_mode mode,
19142                          secondary_reload_info *sri)
19143 {
19144   enum reg_class rclass = (enum reg_class) rclass_i;
19145   reg_class_t ret = ALL_REGS;
19146   enum insn_code icode;
19147   bool default_p = false;
19148   bool done_p = false;
19149
19150   /* Allow subreg of memory before/during reload.  */
19151   bool memory_p = (MEM_P (x)
19152                    || (!reload_completed && SUBREG_P (x)
19153                        && MEM_P (SUBREG_REG (x))));
19154
19155   sri->icode = CODE_FOR_nothing;
19156   sri->t_icode = CODE_FOR_nothing;
19157   sri->extra_cost = 0;
19158   icode = ((in_p)
19159            ? reg_addr[mode].reload_load
19160            : reg_addr[mode].reload_store);
19161
19162   if (REG_P (x) || register_operand (x, mode))
19163     {
19164       enum rs6000_reg_type to_type = reg_class_to_reg_type[(int)rclass];
19165       bool altivec_p = (rclass == ALTIVEC_REGS);
19166       enum rs6000_reg_type from_type = register_to_reg_type (x, &altivec_p);
19167
19168       if (!in_p)
19169         std::swap (to_type, from_type);
19170
19171       /* Can we do a direct move of some sort?  */
19172       if (rs6000_secondary_reload_move (to_type, from_type, mode, sri,
19173                                         altivec_p))
19174         {
19175           icode = (enum insn_code)sri->icode;
19176           default_p = false;
19177           done_p = true;
19178           ret = NO_REGS;
19179         }
19180     }
19181
19182   /* Make sure 0.0 is not reloaded or forced into memory.  */
19183   if (x == CONST0_RTX (mode) && VSX_REG_CLASS_P (rclass))
19184     {
19185       ret = NO_REGS;
19186       default_p = false;
19187       done_p = true;
19188     }
19189
19190   /* If this is a scalar floating point value and we want to load it into the
19191      traditional Altivec registers, do it via a move via a traditional floating
19192      point register, unless we have D-form addressing.  Also make sure that
19193      non-zero constants use a FPR.  */
19194   if (!done_p && reg_addr[mode].scalar_in_vmx_p
19195       && !mode_supports_vmx_dform (mode)
19196       && (rclass == VSX_REGS || rclass == ALTIVEC_REGS)
19197       && (memory_p || CONST_DOUBLE_P (x)))
19198     {
19199       ret = FLOAT_REGS;
19200       default_p = false;
19201       done_p = true;
19202     }
19203
19204   /* Handle reload of load/stores if we have reload helper functions.  */
19205   if (!done_p && icode != CODE_FOR_nothing && memory_p)
19206     {
19207       int extra_cost = rs6000_secondary_reload_memory (XEXP (x, 0), rclass,
19208                                                        mode);
19209
19210       if (extra_cost >= 0)
19211         {
19212           done_p = true;
19213           ret = NO_REGS;
19214           if (extra_cost > 0)
19215             {
19216               sri->extra_cost = extra_cost;
19217               sri->icode = icode;
19218             }
19219         }
19220     }
19221
19222   /* Handle unaligned loads and stores of integer registers.  */
19223   if (!done_p && TARGET_POWERPC64
19224       && reg_class_to_reg_type[(int)rclass] == GPR_REG_TYPE
19225       && memory_p
19226       && GET_MODE_SIZE (GET_MODE (x)) >= UNITS_PER_WORD)
19227     {
19228       rtx addr = XEXP (x, 0);
19229       rtx off = address_offset (addr);
19230
19231       if (off != NULL_RTX)
19232         {
19233           unsigned int extra = GET_MODE_SIZE (GET_MODE (x)) - UNITS_PER_WORD;
19234           unsigned HOST_WIDE_INT offset = INTVAL (off);
19235
19236           /* We need a secondary reload when our legitimate_address_p
19237              says the address is good (as otherwise the entire address
19238              will be reloaded), and the offset is not a multiple of
19239              four or we have an address wrap.  Address wrap will only
19240              occur for LO_SUMs since legitimate_offset_address_p
19241              rejects addresses for 16-byte mems that will wrap.  */
19242           if (GET_CODE (addr) == LO_SUM
19243               ? (1 /* legitimate_address_p allows any offset for lo_sum */
19244                  && ((offset & 3) != 0
19245                      || ((offset & 0xffff) ^ 0x8000) >= 0x10000 - extra))
19246               : (offset + 0x8000 < 0x10000 - extra /* legitimate_address_p */
19247                  && (offset & 3) != 0))
19248             {
19249               /* -m32 -mpowerpc64 needs to use a 32-bit scratch register.  */
19250               if (in_p)
19251                 sri->icode = ((TARGET_32BIT) ? CODE_FOR_reload_si_load
19252                               : CODE_FOR_reload_di_load);
19253               else
19254                 sri->icode = ((TARGET_32BIT) ? CODE_FOR_reload_si_store
19255                               : CODE_FOR_reload_di_store);
19256               sri->extra_cost = 2;
19257               ret = NO_REGS;
19258               done_p = true;
19259             }
19260           else
19261             default_p = true;
19262         }
19263       else
19264         default_p = true;
19265     }
19266
19267   if (!done_p && !TARGET_POWERPC64
19268       && reg_class_to_reg_type[(int)rclass] == GPR_REG_TYPE
19269       && memory_p
19270       && GET_MODE_SIZE (GET_MODE (x)) > UNITS_PER_WORD)
19271     {
19272       rtx addr = XEXP (x, 0);
19273       rtx off = address_offset (addr);
19274
19275       if (off != NULL_RTX)
19276         {
19277           unsigned int extra = GET_MODE_SIZE (GET_MODE (x)) - UNITS_PER_WORD;
19278           unsigned HOST_WIDE_INT offset = INTVAL (off);
19279
19280           /* We need a secondary reload when our legitimate_address_p
19281              says the address is good (as otherwise the entire address
19282              will be reloaded), and we have a wrap.
19283
19284              legitimate_lo_sum_address_p allows LO_SUM addresses to
19285              have any offset so test for wrap in the low 16 bits.
19286
19287              legitimate_offset_address_p checks for the range
19288              [-0x8000,0x7fff] for mode size of 8 and [-0x8000,0x7ff7]
19289              for mode size of 16.  We wrap at [0x7ffc,0x7fff] and
19290              [0x7ff4,0x7fff] respectively, so test for the
19291              intersection of these ranges, [0x7ffc,0x7fff] and
19292              [0x7ff4,0x7ff7] respectively.
19293
19294              Note that the address we see here may have been
19295              manipulated by legitimize_reload_address.  */
19296           if (GET_CODE (addr) == LO_SUM
19297               ? ((offset & 0xffff) ^ 0x8000) >= 0x10000 - extra
19298               : offset - (0x8000 - extra) < UNITS_PER_WORD)
19299             {
19300               if (in_p)
19301                 sri->icode = CODE_FOR_reload_si_load;
19302               else
19303                 sri->icode = CODE_FOR_reload_si_store;
19304               sri->extra_cost = 2;
19305               ret = NO_REGS;
19306               done_p = true;
19307             }
19308           else
19309             default_p = true;
19310         }
19311       else
19312         default_p = true;
19313     }
19314
19315   if (!done_p)
19316     default_p = true;
19317
19318   if (default_p)
19319     ret = default_secondary_reload (in_p, x, rclass, mode, sri);
19320
19321   gcc_assert (ret != ALL_REGS);
19322
19323   if (TARGET_DEBUG_ADDR)
19324     {
19325       fprintf (stderr,
19326                "\nrs6000_secondary_reload, return %s, in_p = %s, rclass = %s, "
19327                "mode = %s",
19328                reg_class_names[ret],
19329                in_p ? "true" : "false",
19330                reg_class_names[rclass],
19331                GET_MODE_NAME (mode));
19332
19333       if (reload_completed)
19334         fputs (", after reload", stderr);
19335
19336       if (!done_p)
19337         fputs (", done_p not set", stderr);
19338
19339       if (default_p)
19340         fputs (", default secondary reload", stderr);
19341
19342       if (sri->icode != CODE_FOR_nothing)
19343         fprintf (stderr, ", reload func = %s, extra cost = %d",
19344                  insn_data[sri->icode].name, sri->extra_cost);
19345
19346       else if (sri->extra_cost > 0)
19347         fprintf (stderr, ", extra cost = %d", sri->extra_cost);
19348
19349       fputs ("\n", stderr);
19350       debug_rtx (x);
19351     }
19352
19353   return ret;
19354 }
19355
19356 /* Better tracing for rs6000_secondary_reload_inner.  */
19357
19358 static void
19359 rs6000_secondary_reload_trace (int line, rtx reg, rtx mem, rtx scratch,
19360                                bool store_p)
19361 {
19362   rtx set, clobber;
19363
19364   gcc_assert (reg != NULL_RTX && mem != NULL_RTX && scratch != NULL_RTX);
19365
19366   fprintf (stderr, "rs6000_secondary_reload_inner:%d, type = %s\n", line,
19367            store_p ? "store" : "load");
19368
19369   if (store_p)
19370     set = gen_rtx_SET (mem, reg);
19371   else
19372     set = gen_rtx_SET (reg, mem);
19373
19374   clobber = gen_rtx_CLOBBER (VOIDmode, scratch);
19375   debug_rtx (gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, set, clobber)));
19376 }
19377
19378 static void rs6000_secondary_reload_fail (int, rtx, rtx, rtx, bool)
19379   ATTRIBUTE_NORETURN;
19380
19381 static void
19382 rs6000_secondary_reload_fail (int line, rtx reg, rtx mem, rtx scratch,
19383                               bool store_p)
19384 {
19385   rs6000_secondary_reload_trace (line, reg, mem, scratch, store_p);
19386   gcc_unreachable ();
19387 }
19388
19389 /* Fixup reload addresses for values in GPR, FPR, and VMX registers that have
19390    reload helper functions.  These were identified in
19391    rs6000_secondary_reload_memory, and if reload decided to use the secondary
19392    reload, it calls the insns:
19393         reload_<RELOAD:mode>_<P:mptrsize>_store
19394         reload_<RELOAD:mode>_<P:mptrsize>_load
19395
19396    which in turn calls this function, to do whatever is necessary to create
19397    valid addresses.  */
19398
19399 void
19400 rs6000_secondary_reload_inner (rtx reg, rtx mem, rtx scratch, bool store_p)
19401 {
19402   int regno = true_regnum (reg);
19403   machine_mode mode = GET_MODE (reg);
19404   addr_mask_type addr_mask;
19405   rtx addr;
19406   rtx new_addr;
19407   rtx op_reg, op0, op1;
19408   rtx and_op;
19409   rtx cc_clobber;
19410   rtvec rv;
19411
19412   if (regno < 0 || !HARD_REGISTER_NUM_P (regno) || !MEM_P (mem)
19413       || !base_reg_operand (scratch, GET_MODE (scratch)))
19414     rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
19415
19416   if (IN_RANGE (regno, FIRST_GPR_REGNO, LAST_GPR_REGNO))
19417     addr_mask = reg_addr[mode].addr_mask[RELOAD_REG_GPR];
19418
19419   else if (IN_RANGE (regno, FIRST_FPR_REGNO, LAST_FPR_REGNO))
19420     addr_mask = reg_addr[mode].addr_mask[RELOAD_REG_FPR];
19421
19422   else if (IN_RANGE (regno, FIRST_ALTIVEC_REGNO, LAST_ALTIVEC_REGNO))
19423     addr_mask = reg_addr[mode].addr_mask[RELOAD_REG_VMX];
19424
19425   else
19426     rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
19427
19428   /* Make sure the mode is valid in this register class.  */
19429   if ((addr_mask & RELOAD_REG_VALID) == 0)
19430     rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
19431
19432   if (TARGET_DEBUG_ADDR)
19433     rs6000_secondary_reload_trace (__LINE__, reg, mem, scratch, store_p);
19434
19435   new_addr = addr = XEXP (mem, 0);
19436   switch (GET_CODE (addr))
19437     {
19438       /* Does the register class support auto update forms for this mode?  If
19439          not, do the update now.  We don't need a scratch register, since the
19440          powerpc only supports PRE_INC, PRE_DEC, and PRE_MODIFY.  */
19441     case PRE_INC:
19442     case PRE_DEC:
19443       op_reg = XEXP (addr, 0);
19444       if (!base_reg_operand (op_reg, Pmode))
19445         rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
19446
19447       if ((addr_mask & RELOAD_REG_PRE_INCDEC) == 0)
19448         {
19449           int delta = GET_MODE_SIZE (mode);
19450           if (GET_CODE (addr) == PRE_DEC)
19451             delta = -delta;
19452           emit_insn (gen_add2_insn (op_reg, GEN_INT (delta)));
19453           new_addr = op_reg;
19454         }
19455       break;
19456
19457     case PRE_MODIFY:
19458       op0 = XEXP (addr, 0);
19459       op1 = XEXP (addr, 1);
19460       if (!base_reg_operand (op0, Pmode)
19461           || GET_CODE (op1) != PLUS
19462           || !rtx_equal_p (op0, XEXP (op1, 0)))
19463         rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
19464
19465       if ((addr_mask & RELOAD_REG_PRE_MODIFY) == 0)
19466         {
19467           emit_insn (gen_rtx_SET (op0, op1));
19468           new_addr = reg;
19469         }
19470       break;
19471
19472       /* Do we need to simulate AND -16 to clear the bottom address bits used
19473          in VMX load/stores?  */
19474     case AND:
19475       op0 = XEXP (addr, 0);
19476       op1 = XEXP (addr, 1);
19477       if ((addr_mask & RELOAD_REG_AND_M16) == 0)
19478         {
19479           if (REG_P (op0) || SUBREG_P (op0))
19480             op_reg = op0;
19481
19482           else if (GET_CODE (op1) == PLUS)
19483             {
19484               emit_insn (gen_rtx_SET (scratch, op1));
19485               op_reg = scratch;
19486             }
19487
19488           else
19489             rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
19490
19491           and_op = gen_rtx_AND (GET_MODE (scratch), op_reg, op1);
19492           cc_clobber = gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (CCmode));
19493           rv = gen_rtvec (2, gen_rtx_SET (scratch, and_op), cc_clobber);
19494           emit_insn (gen_rtx_PARALLEL (VOIDmode, rv));
19495           new_addr = scratch;
19496         }
19497       break;
19498
19499       /* If this is an indirect address, make sure it is a base register.  */
19500     case REG:
19501     case SUBREG:
19502       if (!base_reg_operand (addr, GET_MODE (addr)))
19503         {
19504           emit_insn (gen_rtx_SET (scratch, addr));
19505           new_addr = scratch;
19506         }
19507       break;
19508
19509       /* If this is an indexed address, make sure the register class can handle
19510          indexed addresses for this mode.  */
19511     case PLUS:
19512       op0 = XEXP (addr, 0);
19513       op1 = XEXP (addr, 1);
19514       if (!base_reg_operand (op0, Pmode))
19515         rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
19516
19517       else if (int_reg_operand (op1, Pmode))
19518         {
19519           if ((addr_mask & RELOAD_REG_INDEXED) == 0)
19520             {
19521               emit_insn (gen_rtx_SET (scratch, addr));
19522               new_addr = scratch;
19523             }
19524         }
19525
19526       else if (mode_supports_dq_form (mode) && CONST_INT_P (op1))
19527         {
19528           if (((addr_mask & RELOAD_REG_QUAD_OFFSET) == 0)
19529               || !quad_address_p (addr, mode, false))
19530             {
19531               emit_insn (gen_rtx_SET (scratch, addr));
19532               new_addr = scratch;
19533             }
19534         }
19535
19536       /* Make sure the register class can handle offset addresses.  */
19537       else if (rs6000_legitimate_offset_address_p (mode, addr, false, true))
19538         {
19539           if ((addr_mask & RELOAD_REG_OFFSET) == 0)
19540             {
19541               emit_insn (gen_rtx_SET (scratch, addr));
19542               new_addr = scratch;
19543             }
19544         }
19545
19546       else
19547         rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
19548
19549       break;
19550
19551     case LO_SUM:
19552       op0 = XEXP (addr, 0);
19553       op1 = XEXP (addr, 1);
19554       if (!base_reg_operand (op0, Pmode))
19555         rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
19556
19557       else if (int_reg_operand (op1, Pmode))
19558         {
19559           if ((addr_mask & RELOAD_REG_INDEXED) == 0)
19560             {
19561               emit_insn (gen_rtx_SET (scratch, addr));
19562               new_addr = scratch;
19563             }
19564         }
19565
19566       /* Quad offsets are restricted and can't handle normal addresses.  */
19567       else if (mode_supports_dq_form (mode))
19568         {
19569           emit_insn (gen_rtx_SET (scratch, addr));
19570           new_addr = scratch;
19571         }
19572
19573       /* Make sure the register class can handle offset addresses.  */
19574       else if (legitimate_lo_sum_address_p (mode, addr, false))
19575         {
19576           if ((addr_mask & RELOAD_REG_OFFSET) == 0)
19577             {
19578               emit_insn (gen_rtx_SET (scratch, addr));
19579               new_addr = scratch;
19580             }
19581         }
19582
19583       else
19584         rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
19585
19586       break;
19587
19588     case SYMBOL_REF:
19589     case CONST:
19590     case LABEL_REF:
19591       rs6000_emit_move (scratch, addr, Pmode);
19592       new_addr = scratch;
19593       break;
19594
19595     default:
19596       rs6000_secondary_reload_fail (__LINE__, reg, mem, scratch, store_p);
19597     }
19598
19599   /* Adjust the address if it changed.  */
19600   if (addr != new_addr)
19601     {
19602       mem = replace_equiv_address_nv (mem, new_addr);
19603       if (TARGET_DEBUG_ADDR)
19604         fprintf (stderr, "\nrs6000_secondary_reload_inner, mem adjusted.\n");
19605     }
19606
19607   /* Now create the move.  */
19608   if (store_p)
19609     emit_insn (gen_rtx_SET (mem, reg));
19610   else
19611     emit_insn (gen_rtx_SET (reg, mem));
19612
19613   return;
19614 }
19615
19616 /* Convert reloads involving 64-bit gprs and misaligned offset
19617    addressing, or multiple 32-bit gprs and offsets that are too large,
19618    to use indirect addressing.  */
19619
19620 void
19621 rs6000_secondary_reload_gpr (rtx reg, rtx mem, rtx scratch, bool store_p)
19622 {
19623   int regno = true_regnum (reg);
19624   enum reg_class rclass;
19625   rtx addr;
19626   rtx scratch_or_premodify = scratch;
19627
19628   if (TARGET_DEBUG_ADDR)
19629     {
19630       fprintf (stderr, "\nrs6000_secondary_reload_gpr, type = %s\n",
19631                store_p ? "store" : "load");
19632       fprintf (stderr, "reg:\n");
19633       debug_rtx (reg);
19634       fprintf (stderr, "mem:\n");
19635       debug_rtx (mem);
19636       fprintf (stderr, "scratch:\n");
19637       debug_rtx (scratch);
19638     }
19639
19640   gcc_assert (regno >= 0 && HARD_REGISTER_NUM_P (regno));
19641   gcc_assert (MEM_P (mem));
19642   rclass = REGNO_REG_CLASS (regno);
19643   gcc_assert (rclass == GENERAL_REGS || rclass == BASE_REGS);
19644   addr = XEXP (mem, 0);
19645
19646   if (GET_CODE (addr) == PRE_MODIFY)
19647     {
19648       gcc_assert (REG_P (XEXP (addr, 0))
19649                   && GET_CODE (XEXP (addr, 1)) == PLUS
19650                   && XEXP (XEXP (addr, 1), 0) == XEXP (addr, 0));
19651       scratch_or_premodify = XEXP (addr, 0);
19652       addr = XEXP (addr, 1);
19653     }
19654   gcc_assert (GET_CODE (addr) == PLUS || GET_CODE (addr) == LO_SUM);
19655
19656   rs6000_emit_move (scratch_or_premodify, addr, Pmode);
19657
19658   mem = replace_equiv_address_nv (mem, scratch_or_premodify);
19659
19660   /* Now create the move.  */
19661   if (store_p)
19662     emit_insn (gen_rtx_SET (mem, reg));
19663   else
19664     emit_insn (gen_rtx_SET (reg, mem));
19665
19666   return;
19667 }
19668
19669 /* Given an rtx X being reloaded into a reg required to be
19670    in class CLASS, return the class of reg to actually use.
19671    In general this is just CLASS; but on some machines
19672    in some cases it is preferable to use a more restrictive class.
19673
19674    On the RS/6000, we have to return NO_REGS when we want to reload a
19675    floating-point CONST_DOUBLE to force it to be copied to memory.
19676
19677    We also don't want to reload integer values into floating-point
19678    registers if we can at all help it.  In fact, this can
19679    cause reload to die, if it tries to generate a reload of CTR
19680    into a FP register and discovers it doesn't have the memory location
19681    required.
19682
19683    ??? Would it be a good idea to have reload do the converse, that is
19684    try to reload floating modes into FP registers if possible?
19685  */
19686
19687 static enum reg_class
19688 rs6000_preferred_reload_class (rtx x, enum reg_class rclass)
19689 {
19690   machine_mode mode = GET_MODE (x);
19691   bool is_constant = CONSTANT_P (x);
19692
19693   /* If a mode can't go in FPR/ALTIVEC/VSX registers, don't return a preferred
19694      reload class for it.  */
19695   if ((rclass == ALTIVEC_REGS || rclass == VSX_REGS)
19696       && (reg_addr[mode].addr_mask[RELOAD_REG_VMX] & RELOAD_REG_VALID) == 0)
19697     return NO_REGS;
19698
19699   if ((rclass == FLOAT_REGS || rclass == VSX_REGS)
19700       && (reg_addr[mode].addr_mask[RELOAD_REG_FPR] & RELOAD_REG_VALID) == 0)
19701     return NO_REGS;
19702
19703   /* For VSX, see if we should prefer FLOAT_REGS or ALTIVEC_REGS.  Do not allow
19704      the reloading of address expressions using PLUS into floating point
19705      registers.  */
19706   if (TARGET_VSX && VSX_REG_CLASS_P (rclass) && GET_CODE (x) != PLUS)
19707     {
19708       if (is_constant)
19709         {
19710           /* Zero is always allowed in all VSX registers.  */
19711           if (x == CONST0_RTX (mode))
19712             return rclass;
19713
19714           /* If this is a vector constant that can be formed with a few Altivec
19715              instructions, we want altivec registers.  */
19716           if (GET_CODE (x) == CONST_VECTOR && easy_vector_constant (x, mode))
19717             return ALTIVEC_REGS;
19718
19719           /* If this is an integer constant that can easily be loaded into
19720              vector registers, allow it.  */
19721           if (CONST_INT_P (x))
19722             {
19723               HOST_WIDE_INT value = INTVAL (x);
19724
19725               /* ISA 2.07 can generate -1 in all registers with XXLORC.  ISA
19726                  2.06 can generate it in the Altivec registers with
19727                  VSPLTI<x>.  */
19728               if (value == -1)
19729                 {
19730                   if (TARGET_P8_VECTOR)
19731                     return rclass;
19732                   else if (rclass == ALTIVEC_REGS || rclass == VSX_REGS)
19733                     return ALTIVEC_REGS;
19734                   else
19735                     return NO_REGS;
19736                 }
19737
19738               /* ISA 3.0 can load -128..127 using the XXSPLTIB instruction and
19739                  a sign extend in the Altivec registers.  */
19740               if (IN_RANGE (value, -128, 127) && TARGET_P9_VECTOR
19741                   && (rclass == ALTIVEC_REGS || rclass == VSX_REGS))
19742                 return ALTIVEC_REGS;
19743             }
19744
19745           /* Force constant to memory.  */
19746           return NO_REGS;
19747         }
19748
19749       /* D-form addressing can easily reload the value.  */
19750       if (mode_supports_vmx_dform (mode)
19751           || mode_supports_dq_form (mode))
19752         return rclass;
19753
19754       /* If this is a scalar floating point value and we don't have D-form
19755          addressing, prefer the traditional floating point registers so that we
19756          can use D-form (register+offset) addressing.  */
19757       if (rclass == VSX_REGS
19758           && (mode == SFmode || GET_MODE_SIZE (mode) == 8))
19759         return FLOAT_REGS;
19760
19761       /* Prefer the Altivec registers if Altivec is handling the vector
19762          operations (i.e. V16QI, V8HI, and V4SI), or if we prefer Altivec
19763          loads.  */
19764       if (VECTOR_UNIT_ALTIVEC_P (mode) || VECTOR_MEM_ALTIVEC_P (mode)
19765           || mode == V1TImode)
19766         return ALTIVEC_REGS;
19767
19768       return rclass;
19769     }
19770
19771   if (is_constant || GET_CODE (x) == PLUS)
19772     {
19773       if (reg_class_subset_p (GENERAL_REGS, rclass))
19774         return GENERAL_REGS;
19775       if (reg_class_subset_p (BASE_REGS, rclass))
19776         return BASE_REGS;
19777       return NO_REGS;
19778     }
19779
19780   if (GET_MODE_CLASS (mode) == MODE_INT && rclass == GEN_OR_FLOAT_REGS)
19781     return GENERAL_REGS;
19782
19783   return rclass;
19784 }
19785
19786 /* Debug version of rs6000_preferred_reload_class.  */
19787 static enum reg_class
19788 rs6000_debug_preferred_reload_class (rtx x, enum reg_class rclass)
19789 {
19790   enum reg_class ret = rs6000_preferred_reload_class (x, rclass);
19791
19792   fprintf (stderr,
19793            "\nrs6000_preferred_reload_class, return %s, rclass = %s, "
19794            "mode = %s, x:\n",
19795            reg_class_names[ret], reg_class_names[rclass],
19796            GET_MODE_NAME (GET_MODE (x)));
19797   debug_rtx (x);
19798
19799   return ret;
19800 }
19801
19802 /* If we are copying between FP or AltiVec registers and anything else, we need
19803    a memory location.  The exception is when we are targeting ppc64 and the
19804    move to/from fpr to gpr instructions are available.  Also, under VSX, you
19805    can copy vector registers from the FP register set to the Altivec register
19806    set and vice versa.  */
19807
19808 static bool
19809 rs6000_secondary_memory_needed (machine_mode mode,
19810                                 reg_class_t from_class,
19811                                 reg_class_t to_class)
19812 {
19813   enum rs6000_reg_type from_type, to_type;
19814   bool altivec_p = ((from_class == ALTIVEC_REGS)
19815                     || (to_class == ALTIVEC_REGS));
19816
19817   /* If a simple/direct move is available, we don't need secondary memory  */
19818   from_type = reg_class_to_reg_type[(int)from_class];
19819   to_type = reg_class_to_reg_type[(int)to_class];
19820
19821   if (rs6000_secondary_reload_move (to_type, from_type, mode,
19822                                     (secondary_reload_info *)0, altivec_p))
19823     return false;
19824
19825   /* If we have a floating point or vector register class, we need to use
19826      memory to transfer the data.  */
19827   if (IS_FP_VECT_REG_TYPE (from_type) || IS_FP_VECT_REG_TYPE (to_type))
19828     return true;
19829
19830   return false;
19831 }
19832
19833 /* Debug version of rs6000_secondary_memory_needed.  */
19834 static bool
19835 rs6000_debug_secondary_memory_needed (machine_mode mode,
19836                                       reg_class_t from_class,
19837                                       reg_class_t to_class)
19838 {
19839   bool ret = rs6000_secondary_memory_needed (mode, from_class, to_class);
19840
19841   fprintf (stderr,
19842            "rs6000_secondary_memory_needed, return: %s, from_class = %s, "
19843            "to_class = %s, mode = %s\n",
19844            ret ? "true" : "false",
19845            reg_class_names[from_class],
19846            reg_class_names[to_class],
19847            GET_MODE_NAME (mode));
19848
19849   return ret;
19850 }
19851
19852 /* Return the register class of a scratch register needed to copy IN into
19853    or out of a register in RCLASS in MODE.  If it can be done directly,
19854    NO_REGS is returned.  */
19855
19856 static enum reg_class
19857 rs6000_secondary_reload_class (enum reg_class rclass, machine_mode mode,
19858                                rtx in)
19859 {
19860   int regno;
19861
19862   if (TARGET_ELF || (DEFAULT_ABI == ABI_DARWIN
19863 #if TARGET_MACHO
19864                      && MACHOPIC_INDIRECT
19865 #endif
19866                      ))
19867     {
19868       /* We cannot copy a symbolic operand directly into anything
19869          other than BASE_REGS for TARGET_ELF.  So indicate that a
19870          register from BASE_REGS is needed as an intermediate
19871          register.
19872
19873          On Darwin, pic addresses require a load from memory, which
19874          needs a base register.  */
19875       if (rclass != BASE_REGS
19876           && (SYMBOL_REF_P (in)
19877               || GET_CODE (in) == HIGH
19878               || GET_CODE (in) == LABEL_REF
19879               || GET_CODE (in) == CONST))
19880         return BASE_REGS;
19881     }
19882
19883   if (REG_P (in))
19884     {
19885       regno = REGNO (in);
19886       if (!HARD_REGISTER_NUM_P (regno))
19887         {
19888           regno = true_regnum (in);
19889           if (!HARD_REGISTER_NUM_P (regno))
19890             regno = -1;
19891         }
19892     }
19893   else if (SUBREG_P (in))
19894     {
19895       regno = true_regnum (in);
19896       if (!HARD_REGISTER_NUM_P (regno))
19897         regno = -1;
19898     }
19899   else
19900     regno = -1;
19901
19902   /* If we have VSX register moves, prefer moving scalar values between
19903      Altivec registers and GPR by going via an FPR (and then via memory)
19904      instead of reloading the secondary memory address for Altivec moves.  */
19905   if (TARGET_VSX
19906       && GET_MODE_SIZE (mode) < 16
19907       && !mode_supports_vmx_dform (mode)
19908       && (((rclass == GENERAL_REGS || rclass == BASE_REGS)
19909            && (regno >= 0 && ALTIVEC_REGNO_P (regno)))
19910           || ((rclass == VSX_REGS || rclass == ALTIVEC_REGS)
19911               && (regno >= 0 && INT_REGNO_P (regno)))))
19912     return FLOAT_REGS;
19913
19914   /* We can place anything into GENERAL_REGS and can put GENERAL_REGS
19915      into anything.  */
19916   if (rclass == GENERAL_REGS || rclass == BASE_REGS
19917       || (regno >= 0 && INT_REGNO_P (regno)))
19918     return NO_REGS;
19919
19920   /* Constants, memory, and VSX registers can go into VSX registers (both the
19921      traditional floating point and the altivec registers).  */
19922   if (rclass == VSX_REGS
19923       && (regno == -1 || VSX_REGNO_P (regno)))
19924     return NO_REGS;
19925
19926   /* Constants, memory, and FP registers can go into FP registers.  */
19927   if ((regno == -1 || FP_REGNO_P (regno))
19928       && (rclass == FLOAT_REGS || rclass == GEN_OR_FLOAT_REGS))
19929     return (mode != SDmode || lra_in_progress) ? NO_REGS : GENERAL_REGS;
19930
19931   /* Memory, and AltiVec registers can go into AltiVec registers.  */
19932   if ((regno == -1 || ALTIVEC_REGNO_P (regno))
19933       && rclass == ALTIVEC_REGS)
19934     return NO_REGS;
19935
19936   /* We can copy among the CR registers.  */
19937   if ((rclass == CR_REGS || rclass == CR0_REGS)
19938       && regno >= 0 && CR_REGNO_P (regno))
19939     return NO_REGS;
19940
19941   /* Otherwise, we need GENERAL_REGS.  */
19942   return GENERAL_REGS;
19943 }
19944
19945 /* Debug version of rs6000_secondary_reload_class.  */
19946 static enum reg_class
19947 rs6000_debug_secondary_reload_class (enum reg_class rclass,
19948                                      machine_mode mode, rtx in)
19949 {
19950   enum reg_class ret = rs6000_secondary_reload_class (rclass, mode, in);
19951   fprintf (stderr,
19952            "\nrs6000_secondary_reload_class, return %s, rclass = %s, "
19953            "mode = %s, input rtx:\n",
19954            reg_class_names[ret], reg_class_names[rclass],
19955            GET_MODE_NAME (mode));
19956   debug_rtx (in);
19957
19958   return ret;
19959 }
19960
19961 /* Implement TARGET_CAN_CHANGE_MODE_CLASS.  */
19962
19963 static bool
19964 rs6000_can_change_mode_class (machine_mode from,
19965                               machine_mode to,
19966                               reg_class_t rclass)
19967 {
19968   unsigned from_size = GET_MODE_SIZE (from);
19969   unsigned to_size = GET_MODE_SIZE (to);
19970
19971   if (from_size != to_size)
19972     {
19973       enum reg_class xclass = (TARGET_VSX) ? VSX_REGS : FLOAT_REGS;
19974
19975       if (reg_classes_intersect_p (xclass, rclass))
19976         {
19977           unsigned to_nregs = hard_regno_nregs (FIRST_FPR_REGNO, to);
19978           unsigned from_nregs = hard_regno_nregs (FIRST_FPR_REGNO, from);
19979           bool to_float128_vector_p = FLOAT128_VECTOR_P (to);
19980           bool from_float128_vector_p = FLOAT128_VECTOR_P (from);
19981
19982           /* Don't allow 64-bit types to overlap with 128-bit types that take a
19983              single register under VSX because the scalar part of the register
19984              is in the upper 64-bits, and not the lower 64-bits.  Types like
19985              TFmode/TDmode that take 2 scalar register can overlap.  128-bit
19986              IEEE floating point can't overlap, and neither can small
19987              values.  */
19988
19989           if (to_float128_vector_p && from_float128_vector_p)
19990             return true;
19991
19992           else if (to_float128_vector_p || from_float128_vector_p)
19993             return false;
19994
19995           /* TDmode in floating-mode registers must always go into a register
19996              pair with the most significant word in the even-numbered register
19997              to match ISA requirements.  In little-endian mode, this does not
19998              match subreg numbering, so we cannot allow subregs.  */
19999           if (!BYTES_BIG_ENDIAN && (to == TDmode || from == TDmode))
20000             return false;
20001
20002           if (from_size < 8 || to_size < 8)
20003             return false;
20004
20005           if (from_size == 8 && (8 * to_nregs) != to_size)
20006             return false;
20007
20008           if (to_size == 8 && (8 * from_nregs) != from_size)
20009             return false;
20010
20011           return true;
20012         }
20013       else
20014         return true;
20015     }
20016
20017   /* Since the VSX register set includes traditional floating point registers
20018      and altivec registers, just check for the size being different instead of
20019      trying to check whether the modes are vector modes.  Otherwise it won't
20020      allow say DF and DI to change classes.  For types like TFmode and TDmode
20021      that take 2 64-bit registers, rather than a single 128-bit register, don't
20022      allow subregs of those types to other 128 bit types.  */
20023   if (TARGET_VSX && VSX_REG_CLASS_P (rclass))
20024     {
20025       unsigned num_regs = (from_size + 15) / 16;
20026       if (hard_regno_nregs (FIRST_FPR_REGNO, to) > num_regs
20027           || hard_regno_nregs (FIRST_FPR_REGNO, from) > num_regs)
20028         return false;
20029
20030       return (from_size == 8 || from_size == 16);
20031     }
20032
20033   if (TARGET_ALTIVEC && rclass == ALTIVEC_REGS
20034       && (ALTIVEC_VECTOR_MODE (from) + ALTIVEC_VECTOR_MODE (to)) == 1)
20035     return false;
20036
20037   return true;
20038 }
20039
20040 /* Debug version of rs6000_can_change_mode_class.  */
20041 static bool
20042 rs6000_debug_can_change_mode_class (machine_mode from,
20043                                     machine_mode to,
20044                                     reg_class_t rclass)
20045 {
20046   bool ret = rs6000_can_change_mode_class (from, to, rclass);
20047
20048   fprintf (stderr,
20049            "rs6000_can_change_mode_class, return %s, from = %s, "
20050            "to = %s, rclass = %s\n",
20051            ret ? "true" : "false",
20052            GET_MODE_NAME (from), GET_MODE_NAME (to),
20053            reg_class_names[rclass]);
20054
20055   return ret;
20056 }
20057 \f
20058 /* Return a string to do a move operation of 128 bits of data.  */
20059
20060 const char *
20061 rs6000_output_move_128bit (rtx operands[])
20062 {
20063   rtx dest = operands[0];
20064   rtx src = operands[1];
20065   machine_mode mode = GET_MODE (dest);
20066   int dest_regno;
20067   int src_regno;
20068   bool dest_gpr_p, dest_fp_p, dest_vmx_p, dest_vsx_p;
20069   bool src_gpr_p, src_fp_p, src_vmx_p, src_vsx_p;
20070
20071   if (REG_P (dest))
20072     {
20073       dest_regno = REGNO (dest);
20074       dest_gpr_p = INT_REGNO_P (dest_regno);
20075       dest_fp_p = FP_REGNO_P (dest_regno);
20076       dest_vmx_p = ALTIVEC_REGNO_P (dest_regno);
20077       dest_vsx_p = dest_fp_p | dest_vmx_p;
20078     }
20079   else
20080     {
20081       dest_regno = -1;
20082       dest_gpr_p = dest_fp_p = dest_vmx_p = dest_vsx_p = false;
20083     }
20084
20085   if (REG_P (src))
20086     {
20087       src_regno = REGNO (src);
20088       src_gpr_p = INT_REGNO_P (src_regno);
20089       src_fp_p = FP_REGNO_P (src_regno);
20090       src_vmx_p = ALTIVEC_REGNO_P (src_regno);
20091       src_vsx_p = src_fp_p | src_vmx_p;
20092     }
20093   else
20094     {
20095       src_regno = -1;
20096       src_gpr_p = src_fp_p = src_vmx_p = src_vsx_p = false;
20097     }
20098
20099   /* Register moves.  */
20100   if (dest_regno >= 0 && src_regno >= 0)
20101     {
20102       if (dest_gpr_p)
20103         {
20104           if (src_gpr_p)
20105             return "#";
20106
20107           if (TARGET_DIRECT_MOVE_128 && src_vsx_p)
20108             return (WORDS_BIG_ENDIAN
20109                     ? "mfvsrd %0,%x1\n\tmfvsrld %L0,%x1"
20110                     : "mfvsrd %L0,%x1\n\tmfvsrld %0,%x1");
20111
20112           else if (TARGET_VSX && TARGET_DIRECT_MOVE && src_vsx_p)
20113             return "#";
20114         }
20115
20116       else if (TARGET_VSX && dest_vsx_p)
20117         {
20118           if (src_vsx_p)
20119             return "xxlor %x0,%x1,%x1";
20120
20121           else if (TARGET_DIRECT_MOVE_128 && src_gpr_p)
20122             return (WORDS_BIG_ENDIAN
20123                     ? "mtvsrdd %x0,%1,%L1"
20124                     : "mtvsrdd %x0,%L1,%1");
20125
20126           else if (TARGET_DIRECT_MOVE && src_gpr_p)
20127             return "#";
20128         }
20129
20130       else if (TARGET_ALTIVEC && dest_vmx_p && src_vmx_p)
20131         return "vor %0,%1,%1";
20132
20133       else if (dest_fp_p && src_fp_p)
20134         return "#";
20135     }
20136
20137   /* Loads.  */
20138   else if (dest_regno >= 0 && MEM_P (src))
20139     {
20140       if (dest_gpr_p)
20141         {
20142           if (TARGET_QUAD_MEMORY && quad_load_store_p (dest, src))
20143             return "lq %0,%1";
20144           else
20145             return "#";
20146         }
20147
20148       else if (TARGET_ALTIVEC && dest_vmx_p
20149                && altivec_indexed_or_indirect_operand (src, mode))
20150         return "lvx %0,%y1";
20151
20152       else if (TARGET_VSX && dest_vsx_p)
20153         {
20154           if (mode_supports_dq_form (mode)
20155               && quad_address_p (XEXP (src, 0), mode, true))
20156             return "lxv %x0,%1";
20157
20158           else if (TARGET_P9_VECTOR)
20159             return "lxvx %x0,%y1";
20160
20161           else if (mode == V16QImode || mode == V8HImode || mode == V4SImode)
20162             return "lxvw4x %x0,%y1";
20163
20164           else
20165             return "lxvd2x %x0,%y1";
20166         }
20167
20168       else if (TARGET_ALTIVEC && dest_vmx_p)
20169         return "lvx %0,%y1";
20170
20171       else if (dest_fp_p)
20172         return "#";
20173     }
20174
20175   /* Stores.  */
20176   else if (src_regno >= 0 && MEM_P (dest))
20177     {
20178       if (src_gpr_p)
20179         {
20180           if (TARGET_QUAD_MEMORY && quad_load_store_p (dest, src))
20181             return "stq %1,%0";
20182           else
20183             return "#";
20184         }
20185
20186       else if (TARGET_ALTIVEC && src_vmx_p
20187                && altivec_indexed_or_indirect_operand (dest, mode))
20188         return "stvx %1,%y0";
20189
20190       else if (TARGET_VSX && src_vsx_p)
20191         {
20192           if (mode_supports_dq_form (mode)
20193               && quad_address_p (XEXP (dest, 0), mode, true))
20194             return "stxv %x1,%0";
20195
20196           else if (TARGET_P9_VECTOR)
20197             return "stxvx %x1,%y0";
20198
20199           else if (mode == V16QImode || mode == V8HImode || mode == V4SImode)
20200             return "stxvw4x %x1,%y0";
20201
20202           else
20203             return "stxvd2x %x1,%y0";
20204         }
20205
20206       else if (TARGET_ALTIVEC && src_vmx_p)
20207         return "stvx %1,%y0";
20208
20209       else if (src_fp_p)
20210         return "#";
20211     }
20212
20213   /* Constants.  */
20214   else if (dest_regno >= 0
20215            && (CONST_INT_P (src)
20216                || CONST_WIDE_INT_P (src)
20217                || CONST_DOUBLE_P (src)
20218                || GET_CODE (src) == CONST_VECTOR))
20219     {
20220       if (dest_gpr_p)
20221         return "#";
20222
20223       else if ((dest_vmx_p && TARGET_ALTIVEC)
20224                || (dest_vsx_p && TARGET_VSX))
20225         return output_vec_const_move (operands);
20226     }
20227
20228   fatal_insn ("Bad 128-bit move", gen_rtx_SET (dest, src));
20229 }
20230
20231 /* Validate a 128-bit move.  */
20232 bool
20233 rs6000_move_128bit_ok_p (rtx operands[])
20234 {
20235   machine_mode mode = GET_MODE (operands[0]);
20236   return (gpc_reg_operand (operands[0], mode)
20237           || gpc_reg_operand (operands[1], mode));
20238 }
20239
20240 /* Return true if a 128-bit move needs to be split.  */
20241 bool
20242 rs6000_split_128bit_ok_p (rtx operands[])
20243 {
20244   if (!reload_completed)
20245     return false;
20246
20247   if (!gpr_or_gpr_p (operands[0], operands[1]))
20248     return false;
20249
20250   if (quad_load_store_p (operands[0], operands[1]))
20251     return false;
20252
20253   return true;
20254 }
20255
20256 \f
20257 /* Given a comparison operation, return the bit number in CCR to test.  We
20258    know this is a valid comparison.
20259
20260    SCC_P is 1 if this is for an scc.  That means that %D will have been
20261    used instead of %C, so the bits will be in different places.
20262
20263    Return -1 if OP isn't a valid comparison for some reason.  */
20264
20265 int
20266 ccr_bit (rtx op, int scc_p)
20267 {
20268   enum rtx_code code = GET_CODE (op);
20269   machine_mode cc_mode;
20270   int cc_regnum;
20271   int base_bit;
20272   rtx reg;
20273
20274   if (!COMPARISON_P (op))
20275     return -1;
20276
20277   reg = XEXP (op, 0);
20278
20279   if (!REG_P (reg) || !CR_REGNO_P (REGNO (reg)))
20280     return -1;
20281
20282   cc_mode = GET_MODE (reg);
20283   cc_regnum = REGNO (reg);
20284   base_bit = 4 * (cc_regnum - CR0_REGNO);
20285
20286   validate_condition_mode (code, cc_mode);
20287
20288   /* When generating a sCOND operation, only positive conditions are
20289      allowed.  */
20290   if (scc_p)
20291     switch (code)
20292       {
20293       case EQ:
20294       case GT:
20295       case LT:
20296       case UNORDERED:
20297       case GTU:
20298       case LTU:
20299         break;
20300       default:
20301         return -1;
20302       }
20303
20304   switch (code)
20305     {
20306     case NE:
20307       return scc_p ? base_bit + 3 : base_bit + 2;
20308     case EQ:
20309       return base_bit + 2;
20310     case GT:  case GTU:  case UNLE:
20311       return base_bit + 1;
20312     case LT:  case LTU:  case UNGE:
20313       return base_bit;
20314     case ORDERED:  case UNORDERED:
20315       return base_bit + 3;
20316
20317     case GE:  case GEU:
20318       /* If scc, we will have done a cror to put the bit in the
20319          unordered position.  So test that bit.  For integer, this is ! LT
20320          unless this is an scc insn.  */
20321       return scc_p ? base_bit + 3 : base_bit;
20322
20323     case LE:  case LEU:
20324       return scc_p ? base_bit + 3 : base_bit + 1;
20325
20326     default:
20327       return -1;
20328     }
20329 }
20330 \f
20331 /* Return the GOT register.  */
20332
20333 rtx
20334 rs6000_got_register (rtx value ATTRIBUTE_UNUSED)
20335 {
20336   /* The second flow pass currently (June 1999) can't update
20337      regs_ever_live without disturbing other parts of the compiler, so
20338      update it here to make the prolog/epilogue code happy.  */
20339   if (!can_create_pseudo_p ()
20340       && !df_regs_ever_live_p (RS6000_PIC_OFFSET_TABLE_REGNUM))
20341     df_set_regs_ever_live (RS6000_PIC_OFFSET_TABLE_REGNUM, true);
20342
20343   crtl->uses_pic_offset_table = 1;
20344
20345   return pic_offset_table_rtx;
20346 }
20347 \f
20348 #define INT_P(X) (CONST_INT_P (X) && GET_MODE (X) == VOIDmode)
20349
20350 /* Write out a function code label.  */
20351
20352 void
20353 rs6000_output_function_entry (FILE *file, const char *fname)
20354 {
20355   if (fname[0] != '.')
20356     {
20357       switch (DEFAULT_ABI)
20358         {
20359         default:
20360           gcc_unreachable ();
20361
20362         case ABI_AIX:
20363           if (DOT_SYMBOLS)
20364             putc ('.', file);
20365           else
20366             ASM_OUTPUT_INTERNAL_LABEL_PREFIX (file, "L.");
20367           break;
20368
20369         case ABI_ELFv2:
20370         case ABI_V4:
20371         case ABI_DARWIN:
20372           break;
20373         }
20374     }
20375
20376   RS6000_OUTPUT_BASENAME (file, fname);
20377 }
20378
20379 /* Print an operand.  Recognize special options, documented below.  */
20380
20381 #if TARGET_ELF
20382 /* Access to .sdata2 through r2 (see -msdata=eabi in invoke.texi) is
20383    only introduced by the linker, when applying the sda21
20384    relocation.  */
20385 #define SMALL_DATA_RELOC ((rs6000_sdata == SDATA_EABI) ? "sda21" : "sdarel")
20386 #define SMALL_DATA_REG ((rs6000_sdata == SDATA_EABI) ? 0 : 13)
20387 #else
20388 #define SMALL_DATA_RELOC "sda21"
20389 #define SMALL_DATA_REG 0
20390 #endif
20391
20392 void
20393 print_operand (FILE *file, rtx x, int code)
20394 {
20395   int i;
20396   unsigned HOST_WIDE_INT uval;
20397
20398   switch (code)
20399     {
20400       /* %a is output_address.  */
20401
20402       /* %c is output_addr_const if a CONSTANT_ADDRESS_P, otherwise
20403          output_operand.  */
20404
20405     case 'D':
20406       /* Like 'J' but get to the GT bit only.  */
20407       if (!REG_P (x) || !CR_REGNO_P (REGNO (x)))
20408         {
20409           output_operand_lossage ("invalid %%D value");
20410           return;
20411         }
20412
20413       /* Bit 1 is GT bit.  */
20414       i = 4 * (REGNO (x) - CR0_REGNO) + 1;
20415
20416       /* Add one for shift count in rlinm for scc.  */
20417       fprintf (file, "%d", i + 1);
20418       return;
20419
20420     case 'e':
20421       /* If the low 16 bits are 0, but some other bit is set, write 's'.  */
20422       if (! INT_P (x))
20423         {
20424           output_operand_lossage ("invalid %%e value");
20425           return;
20426         }
20427
20428       uval = INTVAL (x);
20429       if ((uval & 0xffff) == 0 && uval != 0)
20430         putc ('s', file);
20431       return;
20432
20433     case 'E':
20434       /* X is a CR register.  Print the number of the EQ bit of the CR */
20435       if (!REG_P (x) || !CR_REGNO_P (REGNO (x)))
20436         output_operand_lossage ("invalid %%E value");
20437       else
20438         fprintf (file, "%d", 4 * (REGNO (x) - CR0_REGNO) + 2);
20439       return;
20440
20441     case 'f':
20442       /* X is a CR register.  Print the shift count needed to move it
20443          to the high-order four bits.  */
20444       if (!REG_P (x) || !CR_REGNO_P (REGNO (x)))
20445         output_operand_lossage ("invalid %%f value");
20446       else
20447         fprintf (file, "%d", 4 * (REGNO (x) - CR0_REGNO));
20448       return;
20449
20450     case 'F':
20451       /* Similar, but print the count for the rotate in the opposite
20452          direction.  */
20453       if (!REG_P (x) || !CR_REGNO_P (REGNO (x)))
20454         output_operand_lossage ("invalid %%F value");
20455       else
20456         fprintf (file, "%d", 32 - 4 * (REGNO (x) - CR0_REGNO));
20457       return;
20458
20459     case 'G':
20460       /* X is a constant integer.  If it is negative, print "m",
20461          otherwise print "z".  This is to make an aze or ame insn.  */
20462       if (!CONST_INT_P (x))
20463         output_operand_lossage ("invalid %%G value");
20464       else if (INTVAL (x) >= 0)
20465         putc ('z', file);
20466       else
20467         putc ('m', file);
20468       return;
20469
20470     case 'h':
20471       /* If constant, output low-order five bits.  Otherwise, write
20472          normally.  */
20473       if (INT_P (x))
20474         fprintf (file, HOST_WIDE_INT_PRINT_DEC, INTVAL (x) & 31);
20475       else
20476         print_operand (file, x, 0);
20477       return;
20478
20479     case 'H':
20480       /* If constant, output low-order six bits.  Otherwise, write
20481          normally.  */
20482       if (INT_P (x))
20483         fprintf (file, HOST_WIDE_INT_PRINT_DEC, INTVAL (x) & 63);
20484       else
20485         print_operand (file, x, 0);
20486       return;
20487
20488     case 'I':
20489       /* Print `i' if this is a constant, else nothing.  */
20490       if (INT_P (x))
20491         putc ('i', file);
20492       return;
20493
20494     case 'j':
20495       /* Write the bit number in CCR for jump.  */
20496       i = ccr_bit (x, 0);
20497       if (i == -1)
20498         output_operand_lossage ("invalid %%j code");
20499       else
20500         fprintf (file, "%d", i);
20501       return;
20502
20503     case 'J':
20504       /* Similar, but add one for shift count in rlinm for scc and pass
20505          scc flag to `ccr_bit'.  */
20506       i = ccr_bit (x, 1);
20507       if (i == -1)
20508         output_operand_lossage ("invalid %%J code");
20509       else
20510         /* If we want bit 31, write a shift count of zero, not 32.  */
20511         fprintf (file, "%d", i == 31 ? 0 : i + 1);
20512       return;
20513
20514     case 'k':
20515       /* X must be a constant.  Write the 1's complement of the
20516          constant.  */
20517       if (! INT_P (x))
20518         output_operand_lossage ("invalid %%k value");
20519       else
20520         fprintf (file, HOST_WIDE_INT_PRINT_DEC, ~ INTVAL (x));
20521       return;
20522
20523     case 'K':
20524       /* X must be a symbolic constant on ELF.  Write an
20525          expression suitable for an 'addi' that adds in the low 16
20526          bits of the MEM.  */
20527       if (GET_CODE (x) == CONST)
20528         {
20529           if (GET_CODE (XEXP (x, 0)) != PLUS
20530               || (!SYMBOL_REF_P (XEXP (XEXP (x, 0), 0))
20531                   && GET_CODE (XEXP (XEXP (x, 0), 0)) != LABEL_REF)
20532               || !CONST_INT_P (XEXP (XEXP (x, 0), 1)))
20533             output_operand_lossage ("invalid %%K value");
20534         }
20535       print_operand_address (file, x);
20536       fputs ("@l", file);
20537       return;
20538
20539       /* %l is output_asm_label.  */
20540
20541     case 'L':
20542       /* Write second word of DImode or DFmode reference.  Works on register
20543          or non-indexed memory only.  */
20544       if (REG_P (x))
20545         fputs (reg_names[REGNO (x) + 1], file);
20546       else if (MEM_P (x))
20547         {
20548           machine_mode mode = GET_MODE (x);
20549           /* Handle possible auto-increment.  Since it is pre-increment and
20550              we have already done it, we can just use an offset of word.  */
20551           if (GET_CODE (XEXP (x, 0)) == PRE_INC
20552               || GET_CODE (XEXP (x, 0)) == PRE_DEC)
20553             output_address (mode, plus_constant (Pmode, XEXP (XEXP (x, 0), 0),
20554                                                  UNITS_PER_WORD));
20555           else if (GET_CODE (XEXP (x, 0)) == PRE_MODIFY)
20556             output_address (mode, plus_constant (Pmode, XEXP (XEXP (x, 0), 0),
20557                                                  UNITS_PER_WORD));
20558           else
20559             output_address (mode, XEXP (adjust_address_nv (x, SImode,
20560                                                            UNITS_PER_WORD),
20561                                   0));
20562
20563           if (small_data_operand (x, GET_MODE (x)))
20564             fprintf (file, "@%s(%s)", SMALL_DATA_RELOC,
20565                      reg_names[SMALL_DATA_REG]);
20566         }
20567       return;
20568
20569     case 'N': /* Unused */
20570       /* Write the number of elements in the vector times 4.  */
20571       if (GET_CODE (x) != PARALLEL)
20572         output_operand_lossage ("invalid %%N value");
20573       else
20574         fprintf (file, "%d", XVECLEN (x, 0) * 4);
20575       return;
20576
20577     case 'O': /* Unused */
20578       /* Similar, but subtract 1 first.  */
20579       if (GET_CODE (x) != PARALLEL)
20580         output_operand_lossage ("invalid %%O value");
20581       else
20582         fprintf (file, "%d", (XVECLEN (x, 0) - 1) * 4);
20583       return;
20584
20585     case 'p':
20586       /* X is a CONST_INT that is a power of two.  Output the logarithm.  */
20587       if (! INT_P (x)
20588           || INTVAL (x) < 0
20589           || (i = exact_log2 (INTVAL (x))) < 0)
20590         output_operand_lossage ("invalid %%p value");
20591       else
20592         fprintf (file, "%d", i);
20593       return;
20594
20595     case 'P':
20596       /* The operand must be an indirect memory reference.  The result
20597          is the register name.  */
20598       if (!MEM_P (x) || !REG_P (XEXP (x, 0))
20599           || REGNO (XEXP (x, 0)) >= 32)
20600         output_operand_lossage ("invalid %%P value");
20601       else
20602         fputs (reg_names[REGNO (XEXP (x, 0))], file);
20603       return;
20604
20605     case 'q':
20606       /* This outputs the logical code corresponding to a boolean
20607          expression.  The expression may have one or both operands
20608          negated (if one, only the first one).  For condition register
20609          logical operations, it will also treat the negated
20610          CR codes as NOTs, but not handle NOTs of them.  */
20611       {
20612         const char *const *t = 0;
20613         const char *s;
20614         enum rtx_code code = GET_CODE (x);
20615         static const char * const tbl[3][3] = {
20616           { "and", "andc", "nor" },
20617           { "or", "orc", "nand" },
20618           { "xor", "eqv", "xor" } };
20619
20620         if (code == AND)
20621           t = tbl[0];
20622         else if (code == IOR)
20623           t = tbl[1];
20624         else if (code == XOR)
20625           t = tbl[2];
20626         else
20627           output_operand_lossage ("invalid %%q value");
20628
20629         if (GET_CODE (XEXP (x, 0)) != NOT)
20630           s = t[0];
20631         else
20632           {
20633             if (GET_CODE (XEXP (x, 1)) == NOT)
20634               s = t[2];
20635             else
20636               s = t[1];
20637           }
20638
20639         fputs (s, file);
20640       }
20641       return;
20642
20643     case 'Q':
20644       if (! TARGET_MFCRF)
20645         return;
20646       fputc (',', file);
20647       /* FALLTHRU */
20648
20649     case 'R':
20650       /* X is a CR register.  Print the mask for `mtcrf'.  */
20651       if (!REG_P (x) || !CR_REGNO_P (REGNO (x)))
20652         output_operand_lossage ("invalid %%R value");
20653       else
20654         fprintf (file, "%d", 128 >> (REGNO (x) - CR0_REGNO));
20655       return;
20656
20657     case 's':
20658       /* Low 5 bits of 32 - value */
20659       if (! INT_P (x))
20660         output_operand_lossage ("invalid %%s value");
20661       else
20662         fprintf (file, HOST_WIDE_INT_PRINT_DEC, (32 - INTVAL (x)) & 31);
20663       return;
20664
20665     case 't':
20666       /* Like 'J' but get to the OVERFLOW/UNORDERED bit.  */
20667       if (!REG_P (x) || !CR_REGNO_P (REGNO (x)))
20668         {
20669           output_operand_lossage ("invalid %%t value");
20670           return;
20671         }
20672
20673       /* Bit 3 is OV bit.  */
20674       i = 4 * (REGNO (x) - CR0_REGNO) + 3;
20675
20676       /* If we want bit 31, write a shift count of zero, not 32.  */
20677       fprintf (file, "%d", i == 31 ? 0 : i + 1);
20678       return;
20679
20680     case 'T':
20681       /* Print the symbolic name of a branch target register.  */
20682       if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_PLTSEQ)
20683         x = XVECEXP (x, 0, 0);
20684       if (!REG_P (x) || (REGNO (x) != LR_REGNO
20685                          && REGNO (x) != CTR_REGNO))
20686         output_operand_lossage ("invalid %%T value");
20687       else if (REGNO (x) == LR_REGNO)
20688         fputs ("lr", file);
20689       else
20690         fputs ("ctr", file);
20691       return;
20692
20693     case 'u':
20694       /* High-order or low-order 16 bits of constant, whichever is non-zero,
20695          for use in unsigned operand.  */
20696       if (! INT_P (x))
20697         {
20698           output_operand_lossage ("invalid %%u value");
20699           return;
20700         }
20701
20702       uval = INTVAL (x);
20703       if ((uval & 0xffff) == 0)
20704         uval >>= 16;
20705
20706       fprintf (file, HOST_WIDE_INT_PRINT_HEX, uval & 0xffff);
20707       return;
20708
20709     case 'v':
20710       /* High-order 16 bits of constant for use in signed operand.  */
20711       if (! INT_P (x))
20712         output_operand_lossage ("invalid %%v value");
20713       else
20714         fprintf (file, HOST_WIDE_INT_PRINT_HEX,
20715                  (INTVAL (x) >> 16) & 0xffff);
20716       return;
20717
20718     case 'U':
20719       /* Print `u' if this has an auto-increment or auto-decrement.  */
20720       if (MEM_P (x)
20721           && (GET_CODE (XEXP (x, 0)) == PRE_INC
20722               || GET_CODE (XEXP (x, 0)) == PRE_DEC
20723               || GET_CODE (XEXP (x, 0)) == PRE_MODIFY))
20724         putc ('u', file);
20725       return;
20726
20727     case 'V':
20728       /* Print the trap code for this operand.  */
20729       switch (GET_CODE (x))
20730         {
20731         case EQ:
20732           fputs ("eq", file);   /* 4 */
20733           break;
20734         case NE:
20735           fputs ("ne", file);   /* 24 */
20736           break;
20737         case LT:
20738           fputs ("lt", file);   /* 16 */
20739           break;
20740         case LE:
20741           fputs ("le", file);   /* 20 */
20742           break;
20743         case GT:
20744           fputs ("gt", file);   /* 8 */
20745           break;
20746         case GE:
20747           fputs ("ge", file);   /* 12 */
20748           break;
20749         case LTU:
20750           fputs ("llt", file);  /* 2 */
20751           break;
20752         case LEU:
20753           fputs ("lle", file);  /* 6 */
20754           break;
20755         case GTU:
20756           fputs ("lgt", file);  /* 1 */
20757           break;
20758         case GEU:
20759           fputs ("lge", file);  /* 5 */
20760           break;
20761         default:
20762           output_operand_lossage ("invalid %%V value");
20763         }
20764       break;
20765
20766     case 'w':
20767       /* If constant, low-order 16 bits of constant, signed.  Otherwise, write
20768          normally.  */
20769       if (INT_P (x))
20770         fprintf (file, HOST_WIDE_INT_PRINT_DEC,
20771                  ((INTVAL (x) & 0xffff) ^ 0x8000) - 0x8000);
20772       else
20773         print_operand (file, x, 0);
20774       return;
20775
20776     case 'x':
20777       /* X is a FPR or Altivec register used in a VSX context.  */
20778       if (!REG_P (x) || !VSX_REGNO_P (REGNO (x)))
20779         output_operand_lossage ("invalid %%x value");
20780       else
20781         {
20782           int reg = REGNO (x);
20783           int vsx_reg = (FP_REGNO_P (reg)
20784                          ? reg - 32
20785                          : reg - FIRST_ALTIVEC_REGNO + 32);
20786
20787 #ifdef TARGET_REGNAMES      
20788           if (TARGET_REGNAMES)
20789             fprintf (file, "%%vs%d", vsx_reg);
20790           else
20791 #endif
20792             fprintf (file, "%d", vsx_reg);
20793         }
20794       return;
20795
20796     case 'X':
20797       if (MEM_P (x)
20798           && (legitimate_indexed_address_p (XEXP (x, 0), 0)
20799               || (GET_CODE (XEXP (x, 0)) == PRE_MODIFY
20800                   && legitimate_indexed_address_p (XEXP (XEXP (x, 0), 1), 0))))
20801         putc ('x', file);
20802       return;
20803
20804     case 'Y':
20805       /* Like 'L', for third word of TImode/PTImode  */
20806       if (REG_P (x))
20807         fputs (reg_names[REGNO (x) + 2], file);
20808       else if (MEM_P (x))
20809         {
20810           machine_mode mode = GET_MODE (x);
20811           if (GET_CODE (XEXP (x, 0)) == PRE_INC
20812               || GET_CODE (XEXP (x, 0)) == PRE_DEC)
20813             output_address (mode, plus_constant (Pmode,
20814                                                  XEXP (XEXP (x, 0), 0), 8));
20815           else if (GET_CODE (XEXP (x, 0)) == PRE_MODIFY)
20816             output_address (mode, plus_constant (Pmode,
20817                                                  XEXP (XEXP (x, 0), 0), 8));
20818           else
20819             output_address (mode, XEXP (adjust_address_nv (x, SImode, 8), 0));
20820           if (small_data_operand (x, GET_MODE (x)))
20821             fprintf (file, "@%s(%s)", SMALL_DATA_RELOC,
20822                      reg_names[SMALL_DATA_REG]);
20823         }
20824       return;
20825
20826     case 'z':
20827       if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_PLTSEQ)
20828         x = XVECEXP (x, 0, 1);
20829       /* X is a SYMBOL_REF.  Write out the name preceded by a
20830          period and without any trailing data in brackets.  Used for function
20831          names.  If we are configured for System V (or the embedded ABI) on
20832          the PowerPC, do not emit the period, since those systems do not use
20833          TOCs and the like.  */
20834       if (!SYMBOL_REF_P (x))
20835         {
20836           output_operand_lossage ("invalid %%z value");
20837           return;
20838         }
20839
20840       /* For macho, check to see if we need a stub.  */
20841       if (TARGET_MACHO)
20842         {
20843           const char *name = XSTR (x, 0);
20844 #if TARGET_MACHO
20845           if (darwin_picsymbol_stubs
20846               && MACHOPIC_INDIRECT
20847               && machopic_classify_symbol (x) == MACHOPIC_UNDEFINED_FUNCTION)
20848             name = machopic_indirection_name (x, /*stub_p=*/true);
20849 #endif
20850           assemble_name (file, name);
20851         }
20852       else if (!DOT_SYMBOLS)
20853         assemble_name (file, XSTR (x, 0));
20854       else
20855         rs6000_output_function_entry (file, XSTR (x, 0));
20856       return;
20857
20858     case 'Z':
20859       /* Like 'L', for last word of TImode/PTImode.  */
20860       if (REG_P (x))
20861         fputs (reg_names[REGNO (x) + 3], file);
20862       else if (MEM_P (x))
20863         {
20864           machine_mode mode = GET_MODE (x);
20865           if (GET_CODE (XEXP (x, 0)) == PRE_INC
20866               || GET_CODE (XEXP (x, 0)) == PRE_DEC)
20867             output_address (mode, plus_constant (Pmode,
20868                                                  XEXP (XEXP (x, 0), 0), 12));
20869           else if (GET_CODE (XEXP (x, 0)) == PRE_MODIFY)
20870             output_address (mode, plus_constant (Pmode,
20871                                                  XEXP (XEXP (x, 0), 0), 12));
20872           else
20873             output_address (mode, XEXP (adjust_address_nv (x, SImode, 12), 0));
20874           if (small_data_operand (x, GET_MODE (x)))
20875             fprintf (file, "@%s(%s)", SMALL_DATA_RELOC,
20876                      reg_names[SMALL_DATA_REG]);
20877         }
20878       return;
20879
20880       /* Print AltiVec memory operand.  */
20881     case 'y':
20882       {
20883         rtx tmp;
20884
20885         gcc_assert (MEM_P (x));
20886
20887         tmp = XEXP (x, 0);
20888
20889         if (VECTOR_MEM_ALTIVEC_OR_VSX_P (GET_MODE (x))
20890             && GET_CODE (tmp) == AND
20891             && CONST_INT_P (XEXP (tmp, 1))
20892             && INTVAL (XEXP (tmp, 1)) == -16)
20893           tmp = XEXP (tmp, 0);
20894         else if (VECTOR_MEM_VSX_P (GET_MODE (x))
20895                  && GET_CODE (tmp) == PRE_MODIFY)
20896           tmp = XEXP (tmp, 1);
20897         if (REG_P (tmp))
20898           fprintf (file, "0,%s", reg_names[REGNO (tmp)]);
20899         else
20900           {
20901             if (GET_CODE (tmp) != PLUS
20902                 || !REG_P (XEXP (tmp, 0))
20903                 || !REG_P (XEXP (tmp, 1)))
20904               {
20905                 output_operand_lossage ("invalid %%y value, try using the 'Z' constraint");
20906                 break;
20907               }
20908
20909             if (REGNO (XEXP (tmp, 0)) == 0)
20910               fprintf (file, "%s,%s", reg_names[ REGNO (XEXP (tmp, 1)) ],
20911                        reg_names[ REGNO (XEXP (tmp, 0)) ]);
20912             else
20913               fprintf (file, "%s,%s", reg_names[ REGNO (XEXP (tmp, 0)) ],
20914                        reg_names[ REGNO (XEXP (tmp, 1)) ]);
20915           }
20916         break;
20917       }
20918
20919     case 0:
20920       if (REG_P (x))
20921         fprintf (file, "%s", reg_names[REGNO (x)]);
20922       else if (MEM_P (x))
20923         {
20924           /* We need to handle PRE_INC and PRE_DEC here, since we need to
20925              know the width from the mode.  */
20926           if (GET_CODE (XEXP (x, 0)) == PRE_INC)
20927             fprintf (file, "%d(%s)", GET_MODE_SIZE (GET_MODE (x)),
20928                      reg_names[REGNO (XEXP (XEXP (x, 0), 0))]);
20929           else if (GET_CODE (XEXP (x, 0)) == PRE_DEC)
20930             fprintf (file, "%d(%s)", - GET_MODE_SIZE (GET_MODE (x)),
20931                      reg_names[REGNO (XEXP (XEXP (x, 0), 0))]);
20932           else if (GET_CODE (XEXP (x, 0)) == PRE_MODIFY)
20933             output_address (GET_MODE (x), XEXP (XEXP (x, 0), 1));
20934           else
20935             output_address (GET_MODE (x), XEXP (x, 0));
20936         }
20937       else if (toc_relative_expr_p (x, false,
20938                                     &tocrel_base_oac, &tocrel_offset_oac))
20939         /* This hack along with a corresponding hack in
20940            rs6000_output_addr_const_extra arranges to output addends
20941            where the assembler expects to find them.  eg.
20942            (plus (unspec [(symbol_ref ("x")) (reg 2)] tocrel) 4)
20943            without this hack would be output as "x@toc+4".  We
20944            want "x+4@toc".  */
20945         output_addr_const (file, CONST_CAST_RTX (tocrel_base_oac));
20946       else if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_TLSGD)
20947         output_addr_const (file, XVECEXP (x, 0, 0));
20948       else if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_PLTSEQ)
20949         output_addr_const (file, XVECEXP (x, 0, 1));
20950       else
20951         output_addr_const (file, x);
20952       return;
20953
20954     case '&':
20955       if (const char *name = get_some_local_dynamic_name ())
20956         assemble_name (file, name);
20957       else
20958         output_operand_lossage ("'%%&' used without any "
20959                                 "local dynamic TLS references");
20960       return;
20961
20962     default:
20963       output_operand_lossage ("invalid %%xn code");
20964     }
20965 }
20966 \f
20967 /* Print the address of an operand.  */
20968
20969 void
20970 print_operand_address (FILE *file, rtx x)
20971 {
20972   if (REG_P (x))
20973     fprintf (file, "0(%s)", reg_names[ REGNO (x) ]);
20974
20975   /* Is it a pc-relative address?  */
20976   else if (pcrel_address (x, Pmode))
20977     {
20978       HOST_WIDE_INT offset;
20979
20980       if (GET_CODE (x) == CONST)
20981         x = XEXP (x, 0);
20982
20983       if (GET_CODE (x) == PLUS)
20984         {
20985           offset = INTVAL (XEXP (x, 1));
20986           x = XEXP (x, 0);
20987         }
20988       else
20989         offset = 0;
20990
20991       output_addr_const (file, x);
20992
20993       if (offset)
20994         fprintf (file, "%+" PRId64, offset);
20995
20996       fputs ("@pcrel", file);
20997     }
20998   else if (SYMBOL_REF_P (x) || GET_CODE (x) == CONST
20999            || GET_CODE (x) == LABEL_REF)
21000     {
21001       output_addr_const (file, x);
21002       if (small_data_operand (x, GET_MODE (x)))
21003         fprintf (file, "@%s(%s)", SMALL_DATA_RELOC,
21004                  reg_names[SMALL_DATA_REG]);
21005       else
21006         gcc_assert (!TARGET_TOC);
21007     }
21008   else if (GET_CODE (x) == PLUS && REG_P (XEXP (x, 0))
21009            && REG_P (XEXP (x, 1)))
21010     {
21011       if (REGNO (XEXP (x, 0)) == 0)
21012         fprintf (file, "%s,%s", reg_names[ REGNO (XEXP (x, 1)) ],
21013                  reg_names[ REGNO (XEXP (x, 0)) ]);
21014       else
21015         fprintf (file, "%s,%s", reg_names[ REGNO (XEXP (x, 0)) ],
21016                  reg_names[ REGNO (XEXP (x, 1)) ]);
21017     }
21018   else if (GET_CODE (x) == PLUS && REG_P (XEXP (x, 0))
21019            && CONST_INT_P (XEXP (x, 1)))
21020     fprintf (file, HOST_WIDE_INT_PRINT_DEC "(%s)",
21021              INTVAL (XEXP (x, 1)), reg_names[ REGNO (XEXP (x, 0)) ]);
21022 #if TARGET_MACHO
21023   else if (GET_CODE (x) == LO_SUM && REG_P (XEXP (x, 0))
21024            && CONSTANT_P (XEXP (x, 1)))
21025     {
21026       fprintf (file, "lo16(");
21027       output_addr_const (file, XEXP (x, 1));
21028       fprintf (file, ")(%s)", reg_names[ REGNO (XEXP (x, 0)) ]);
21029     }
21030 #endif
21031 #if TARGET_ELF
21032   else if (GET_CODE (x) == LO_SUM && REG_P (XEXP (x, 0))
21033            && CONSTANT_P (XEXP (x, 1)))
21034     {
21035       output_addr_const (file, XEXP (x, 1));
21036       fprintf (file, "@l(%s)", reg_names[ REGNO (XEXP (x, 0)) ]);
21037     }
21038 #endif
21039   else if (toc_relative_expr_p (x, false, &tocrel_base_oac, &tocrel_offset_oac))
21040     {
21041       /* This hack along with a corresponding hack in
21042          rs6000_output_addr_const_extra arranges to output addends
21043          where the assembler expects to find them.  eg.
21044          (lo_sum (reg 9)
21045          .       (plus (unspec [(symbol_ref ("x")) (reg 2)] tocrel) 8))
21046          without this hack would be output as "x@toc+8@l(9)".  We
21047          want "x+8@toc@l(9)".  */
21048       output_addr_const (file, CONST_CAST_RTX (tocrel_base_oac));
21049       if (GET_CODE (x) == LO_SUM)
21050         fprintf (file, "@l(%s)", reg_names[REGNO (XEXP (x, 0))]);
21051       else
21052         fprintf (file, "(%s)", reg_names[REGNO (XVECEXP (tocrel_base_oac, 0, 1))]);
21053     }
21054   else
21055     output_addr_const (file, x);
21056 }
21057 \f
21058 /* Implement TARGET_ASM_OUTPUT_ADDR_CONST_EXTRA.  */
21059
21060 static bool
21061 rs6000_output_addr_const_extra (FILE *file, rtx x)
21062 {
21063   if (GET_CODE (x) == UNSPEC)
21064     switch (XINT (x, 1))
21065       {
21066       case UNSPEC_TOCREL:
21067         gcc_checking_assert (SYMBOL_REF_P (XVECEXP (x, 0, 0))
21068                              && REG_P (XVECEXP (x, 0, 1))
21069                              && REGNO (XVECEXP (x, 0, 1)) == TOC_REGISTER);
21070         output_addr_const (file, XVECEXP (x, 0, 0));
21071         if (x == tocrel_base_oac && tocrel_offset_oac != const0_rtx)
21072           {
21073             if (INTVAL (tocrel_offset_oac) >= 0)
21074               fprintf (file, "+");
21075             output_addr_const (file, CONST_CAST_RTX (tocrel_offset_oac));
21076           }
21077         if (!TARGET_AIX || (TARGET_ELF && TARGET_MINIMAL_TOC))
21078           {
21079             putc ('-', file);
21080             assemble_name (file, toc_label_name);
21081             need_toc_init = 1;
21082           }
21083         else if (TARGET_ELF)
21084           fputs ("@toc", file);
21085         return true;
21086
21087 #if TARGET_MACHO
21088       case UNSPEC_MACHOPIC_OFFSET:
21089         output_addr_const (file, XVECEXP (x, 0, 0));
21090         putc ('-', file);
21091         machopic_output_function_base_name (file);
21092         return true;
21093 #endif
21094       }
21095   return false;
21096 }
21097 \f
21098 /* Target hook for assembling integer objects.  The PowerPC version has
21099    to handle fixup entries for relocatable code if RELOCATABLE_NEEDS_FIXUP
21100    is defined.  It also needs to handle DI-mode objects on 64-bit
21101    targets.  */
21102
21103 static bool
21104 rs6000_assemble_integer (rtx x, unsigned int size, int aligned_p)
21105 {
21106 #ifdef RELOCATABLE_NEEDS_FIXUP
21107   /* Special handling for SI values.  */
21108   if (RELOCATABLE_NEEDS_FIXUP && size == 4 && aligned_p)
21109     {
21110       static int recurse = 0;
21111
21112       /* For -mrelocatable, we mark all addresses that need to be fixed up in
21113          the .fixup section.  Since the TOC section is already relocated, we
21114          don't need to mark it here.  We used to skip the text section, but it
21115          should never be valid for relocated addresses to be placed in the text
21116          section.  */
21117       if (DEFAULT_ABI == ABI_V4
21118           && (TARGET_RELOCATABLE || flag_pic > 1)
21119           && in_section != toc_section
21120           && !recurse
21121           && !CONST_SCALAR_INT_P (x)
21122           && CONSTANT_P (x))
21123         {
21124           char buf[256];
21125
21126           recurse = 1;
21127           ASM_GENERATE_INTERNAL_LABEL (buf, "LCP", fixuplabelno);
21128           fixuplabelno++;
21129           ASM_OUTPUT_LABEL (asm_out_file, buf);
21130           fprintf (asm_out_file, "\t.long\t(");
21131           output_addr_const (asm_out_file, x);
21132           fprintf (asm_out_file, ")@fixup\n");
21133           fprintf (asm_out_file, "\t.section\t\".fixup\",\"aw\"\n");
21134           ASM_OUTPUT_ALIGN (asm_out_file, 2);
21135           fprintf (asm_out_file, "\t.long\t");
21136           assemble_name (asm_out_file, buf);
21137           fprintf (asm_out_file, "\n\t.previous\n");
21138           recurse = 0;
21139           return true;
21140         }
21141       /* Remove initial .'s to turn a -mcall-aixdesc function
21142          address into the address of the descriptor, not the function
21143          itself.  */
21144       else if (SYMBOL_REF_P (x)
21145                && XSTR (x, 0)[0] == '.'
21146                && DEFAULT_ABI == ABI_AIX)
21147         {
21148           const char *name = XSTR (x, 0);
21149           while (*name == '.')
21150             name++;
21151
21152           fprintf (asm_out_file, "\t.long\t%s\n", name);
21153           return true;
21154         }
21155     }
21156 #endif /* RELOCATABLE_NEEDS_FIXUP */
21157   return default_assemble_integer (x, size, aligned_p);
21158 }
21159
21160 /* Return a template string for assembly to emit when making an
21161    external call.  FUNOP is the call mem argument operand number.  */
21162
21163 static const char *
21164 rs6000_call_template_1 (rtx *operands, unsigned int funop, bool sibcall)
21165 {
21166   /* -Wformat-overflow workaround, without which gcc thinks that %u
21167       might produce 10 digits.  */
21168   gcc_assert (funop <= MAX_RECOG_OPERANDS);
21169
21170   char arg[12];
21171   arg[0] = 0;
21172   if (TARGET_TLS_MARKERS && GET_CODE (operands[funop + 1]) == UNSPEC)
21173     {
21174       if (XINT (operands[funop + 1], 1) == UNSPEC_TLSGD)
21175         sprintf (arg, "(%%%u@tlsgd)", funop + 1);
21176       else if (XINT (operands[funop + 1], 1) == UNSPEC_TLSLD)
21177         sprintf (arg, "(%%&@tlsld)");
21178       else
21179         gcc_unreachable ();
21180     }
21181
21182   /* The magic 32768 offset here corresponds to the offset of
21183      r30 in .got2, as given by LCTOC1.  See sysv4.h:toc_section.  */
21184   char z[11];
21185   sprintf (z, "%%z%u%s", funop,
21186            (DEFAULT_ABI == ABI_V4 && TARGET_SECURE_PLT && flag_pic == 2
21187             ? "+32768" : ""));
21188
21189   static char str[32];  /* 1 spare */
21190   if (rs6000_pcrel_p (cfun))
21191     sprintf (str, "b%s %s@notoc%s", sibcall ? "" : "l", z, arg);
21192   else if (DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
21193     sprintf (str, "b%s %s%s%s", sibcall ? "" : "l", z, arg,
21194              sibcall ? "" : "\n\tnop");
21195   else if (DEFAULT_ABI == ABI_V4)
21196     sprintf (str, "b%s %s%s%s", sibcall ? "" : "l", z, arg,
21197              flag_pic ? "@plt" : "");
21198 #if TARGET_MACHO
21199   /* If/when we remove the mlongcall opt, we can share the AIX/ELGv2 case. */
21200    else if (DEFAULT_ABI == ABI_DARWIN)
21201     {
21202       /* The cookie is in operand func+2.  */
21203       gcc_checking_assert (GET_CODE (operands[funop + 2]) == CONST_INT);
21204       int cookie = INTVAL (operands[funop + 2]);
21205       if (cookie & CALL_LONG)
21206         {
21207           tree funname = get_identifier (XSTR (operands[funop], 0));
21208           tree labelname = get_prev_label (funname);
21209           gcc_checking_assert (labelname && !sibcall);
21210
21211           /* "jbsr foo, L42" is Mach-O for "Link as 'bl foo' if a 'bl'
21212              instruction will reach 'foo', otherwise link as 'bl L42'".
21213              "L42" should be a 'branch island', that will do a far jump to
21214              'foo'.  Branch islands are generated in
21215              macho_branch_islands().  */
21216           sprintf (str, "jbsr %%z%u,%.10s", funop,
21217                    IDENTIFIER_POINTER (labelname));
21218         }
21219       else
21220         /* Same as AIX or ELFv2, except to keep backwards compat, no nop
21221            after the call.  */
21222         sprintf (str, "b%s %s%s", sibcall ? "" : "l", z, arg);
21223     }
21224 #endif
21225   else
21226     gcc_unreachable ();
21227   return str;
21228 }
21229
21230 const char *
21231 rs6000_call_template (rtx *operands, unsigned int funop)
21232 {
21233   return rs6000_call_template_1 (operands, funop, false);
21234 }
21235
21236 const char *
21237 rs6000_sibcall_template (rtx *operands, unsigned int funop)
21238 {
21239   return rs6000_call_template_1 (operands, funop, true);
21240 }
21241
21242 /* As above, for indirect calls.  */
21243
21244 static const char *
21245 rs6000_indirect_call_template_1 (rtx *operands, unsigned int funop,
21246                                  bool sibcall)
21247 {
21248   /* -Wformat-overflow workaround, without which gcc thinks that %u
21249      might produce 10 digits.  Note that -Wformat-overflow will not
21250      currently warn here for str[], so do not rely on a warning to
21251      ensure str[] is correctly sized.  */
21252   gcc_assert (funop <= MAX_RECOG_OPERANDS);
21253
21254   /* Currently, funop is either 0 or 1.  The maximum string is always
21255      a !speculate 64-bit __tls_get_addr call.
21256
21257      ABI_ELFv2, pcrel:
21258      . 27       .reloc .,R_PPC64_TLSGD,%2\n\t
21259      . 35       .reloc .,R_PPC64_PLTSEQ_NOTOC,%z1\n\t
21260      .  9       crset 2\n\t
21261      . 27       .reloc .,R_PPC64_TLSGD,%2\n\t
21262      . 36       .reloc .,R_PPC64_PLTCALL_NOTOC,%z1\n\t
21263      .  8       beq%T1l-
21264      .---
21265      .142
21266
21267      ABI_AIX:
21268      .  9       ld 2,%3\n\t
21269      . 27       .reloc .,R_PPC64_TLSGD,%2\n\t
21270      . 29       .reloc .,R_PPC64_PLTSEQ,%z1\n\t
21271      .  9       crset 2\n\t
21272      . 27       .reloc .,R_PPC64_TLSGD,%2\n\t
21273      . 30       .reloc .,R_PPC64_PLTCALL,%z1\n\t
21274      . 10       beq%T1l-\n\t
21275      . 10       ld 2,%4(1)
21276      .---
21277      .151
21278
21279      ABI_ELFv2:
21280      . 27       .reloc .,R_PPC64_TLSGD,%2\n\t
21281      . 29       .reloc .,R_PPC64_PLTSEQ,%z1\n\t
21282      .  9       crset 2\n\t
21283      . 27       .reloc .,R_PPC64_TLSGD,%2\n\t
21284      . 30       .reloc .,R_PPC64_PLTCALL,%z1\n\t
21285      . 10       beq%T1l-\n\t
21286      . 10       ld 2,%3(1)
21287      .---
21288      .142
21289
21290      ABI_V4:
21291      . 27       .reloc .,R_PPC64_TLSGD,%2\n\t
21292      . 35       .reloc .,R_PPC64_PLTSEQ,%z1+32768\n\t
21293      .  9       crset 2\n\t
21294      . 27       .reloc .,R_PPC64_TLSGD,%2\n\t
21295      . 36       .reloc .,R_PPC64_PLTCALL,%z1+32768\n\t
21296      .  8       beq%T1l-
21297      .---
21298      .141  */
21299   static char str[160];  /* 8 spare */
21300   char *s = str;
21301   const char *ptrload = TARGET_64BIT ? "d" : "wz";
21302
21303   if (DEFAULT_ABI == ABI_AIX)
21304     s += sprintf (s,
21305                   "l%s 2,%%%u\n\t",
21306                   ptrload, funop + 2);
21307
21308   /* We don't need the extra code to stop indirect call speculation if
21309      calling via LR.  */
21310   bool speculate = (TARGET_MACHO
21311                     || rs6000_speculate_indirect_jumps
21312                     || (REG_P (operands[funop])
21313                         && REGNO (operands[funop]) == LR_REGNO));
21314
21315   if (TARGET_PLTSEQ && GET_CODE (operands[funop]) == UNSPEC)
21316     {
21317       const char *rel64 = TARGET_64BIT ? "64" : "";
21318       char tls[29];
21319       tls[0] = 0;
21320       if (TARGET_TLS_MARKERS && GET_CODE (operands[funop + 1]) == UNSPEC)
21321         {
21322           if (XINT (operands[funop + 1], 1) == UNSPEC_TLSGD)
21323             sprintf (tls, ".reloc .,R_PPC%s_TLSGD,%%%u\n\t",
21324                      rel64, funop + 1);
21325           else if (XINT (operands[funop + 1], 1) == UNSPEC_TLSLD)
21326             sprintf (tls, ".reloc .,R_PPC%s_TLSLD,%%&\n\t",
21327                      rel64);
21328           else
21329             gcc_unreachable ();
21330         }
21331
21332       const char *notoc = rs6000_pcrel_p (cfun) ? "_NOTOC" : "";
21333       const char *addend = (DEFAULT_ABI == ABI_V4 && TARGET_SECURE_PLT
21334                             && flag_pic == 2 ? "+32768" : "");
21335       if (!speculate)
21336         {
21337           s += sprintf (s,
21338                         "%s.reloc .,R_PPC%s_PLTSEQ%s,%%z%u%s\n\t",
21339                         tls, rel64, notoc, funop, addend);
21340           s += sprintf (s, "crset 2\n\t");
21341         }
21342       s += sprintf (s,
21343                     "%s.reloc .,R_PPC%s_PLTCALL%s,%%z%u%s\n\t",
21344                     tls, rel64, notoc, funop, addend);
21345     }
21346   else if (!speculate)
21347     s += sprintf (s, "crset 2\n\t");
21348
21349   if (rs6000_pcrel_p (cfun))
21350     {
21351       if (speculate)
21352         sprintf (s, "b%%T%ul", funop);
21353       else
21354         sprintf (s, "beq%%T%ul-", funop);
21355     }
21356   else if (DEFAULT_ABI == ABI_AIX)
21357     {
21358       if (speculate)
21359         sprintf (s,
21360                  "b%%T%ul\n\t"
21361                  "l%s 2,%%%u(1)",
21362                  funop, ptrload, funop + 3);
21363       else
21364         sprintf (s,
21365                  "beq%%T%ul-\n\t"
21366                  "l%s 2,%%%u(1)",
21367                  funop, ptrload, funop + 3);
21368     }
21369   else if (DEFAULT_ABI == ABI_ELFv2)
21370     {
21371       if (speculate)
21372         sprintf (s,
21373                  "b%%T%ul\n\t"
21374                  "l%s 2,%%%u(1)",
21375                  funop, ptrload, funop + 2);
21376       else
21377         sprintf (s,
21378                  "beq%%T%ul-\n\t"
21379                  "l%s 2,%%%u(1)",
21380                  funop, ptrload, funop + 2);
21381     }
21382   else
21383     {
21384       if (speculate)
21385         sprintf (s,
21386                  "b%%T%u%s",
21387                  funop, sibcall ? "" : "l");
21388       else
21389         sprintf (s,
21390                  "beq%%T%u%s-%s",
21391                  funop, sibcall ? "" : "l", sibcall ? "\n\tb $" : "");
21392     }
21393   return str;
21394 }
21395
21396 const char *
21397 rs6000_indirect_call_template (rtx *operands, unsigned int funop)
21398 {
21399   return rs6000_indirect_call_template_1 (operands, funop, false);
21400 }
21401
21402 const char *
21403 rs6000_indirect_sibcall_template (rtx *operands, unsigned int funop)
21404 {
21405   return rs6000_indirect_call_template_1 (operands, funop, true);
21406 }
21407
21408 #if HAVE_AS_PLTSEQ
21409 /* Output indirect call insns.  WHICH identifies the type of sequence.  */
21410 const char *
21411 rs6000_pltseq_template (rtx *operands, int which)
21412 {
21413   const char *rel64 = TARGET_64BIT ? "64" : "";
21414   char tls[30];
21415   tls[0] = 0;
21416   if (TARGET_TLS_MARKERS && GET_CODE (operands[3]) == UNSPEC)
21417     {
21418       char off = which == RS6000_PLTSEQ_PLT_PCREL34 ? '8' : '4';
21419       if (XINT (operands[3], 1) == UNSPEC_TLSGD)
21420         sprintf (tls, ".reloc .-%c,R_PPC%s_TLSGD,%%3\n\t",
21421                  off, rel64);
21422       else if (XINT (operands[3], 1) == UNSPEC_TLSLD)
21423         sprintf (tls, ".reloc .-%c,R_PPC%s_TLSLD,%%&\n\t",
21424                  off, rel64);
21425       else
21426         gcc_unreachable ();
21427     }
21428
21429   gcc_assert (DEFAULT_ABI == ABI_ELFv2 || DEFAULT_ABI == ABI_V4);
21430   static char str[96];  /* 10 spare */
21431   char off = WORDS_BIG_ENDIAN ? '2' : '4';
21432   const char *addend = (DEFAULT_ABI == ABI_V4 && TARGET_SECURE_PLT
21433                         && flag_pic == 2 ? "+32768" : "");
21434   switch (which)
21435     {
21436     case RS6000_PLTSEQ_TOCSAVE:
21437       sprintf (str,
21438                "st%s\n\t"
21439                "%s.reloc .-4,R_PPC%s_PLTSEQ,%%z2",
21440                TARGET_64BIT ? "d 2,24(1)" : "w 2,12(1)",
21441                tls, rel64);
21442       break;
21443     case RS6000_PLTSEQ_PLT16_HA:
21444       if (DEFAULT_ABI == ABI_V4 && !flag_pic)
21445         sprintf (str,
21446                  "lis %%0,0\n\t"
21447                  "%s.reloc .-%c,R_PPC%s_PLT16_HA,%%z2",
21448                  tls, off, rel64);
21449       else
21450         sprintf (str,
21451                  "addis %%0,%%1,0\n\t"
21452                  "%s.reloc .-%c,R_PPC%s_PLT16_HA,%%z2%s",
21453                  tls, off, rel64, addend);
21454       break;
21455     case RS6000_PLTSEQ_PLT16_LO:
21456       sprintf (str,
21457                "l%s %%0,0(%%1)\n\t"
21458                "%s.reloc .-%c,R_PPC%s_PLT16_LO%s,%%z2%s",
21459                TARGET_64BIT ? "d" : "wz",
21460                tls, off, rel64, TARGET_64BIT ? "_DS" : "", addend);
21461       break;
21462     case RS6000_PLTSEQ_MTCTR:
21463       sprintf (str,
21464                "mtctr %%1\n\t"
21465                "%s.reloc .-4,R_PPC%s_PLTSEQ,%%z2%s",
21466                tls, rel64, addend);
21467       break;
21468     case RS6000_PLTSEQ_PLT_PCREL34:
21469       sprintf (str,
21470                "pl%s %%0,0(0),1\n\t"
21471                "%s.reloc .-8,R_PPC%s_PLT_PCREL34_NOTOC,%%z2",
21472                TARGET_64BIT ? "d" : "wz",
21473                tls, rel64);
21474       break;
21475     default:
21476       gcc_unreachable ();
21477     }
21478   return str;
21479 }
21480 #endif
21481
21482 /* Helper function to return whether a MODE can do prefixed loads/stores.
21483    VOIDmode is used when we are loading the pc-relative address into a base
21484    register, but we are not using it as part of a memory operation.  As modes
21485    add support for prefixed memory, they will be added here.  */
21486
21487 static bool
21488 mode_supports_prefixed_address_p (machine_mode mode)
21489 {
21490   return mode == VOIDmode;
21491 }
21492
21493 /* Function to return true if ADDR is a valid prefixed memory address that uses
21494    mode MODE.  */
21495
21496 bool
21497 rs6000_prefixed_address (rtx addr, machine_mode mode)
21498 {
21499   if (!TARGET_PREFIXED_ADDR || !mode_supports_prefixed_address_p (mode))
21500     return false;
21501
21502   /* Check for PC-relative addresses.  */
21503   if (pcrel_address (addr, Pmode))
21504     return true;
21505
21506   /* Check for prefixed memory addresses that have a large numeric offset,
21507      or an offset that can't be used for a DS/DQ-form memory operation.  */
21508   if (GET_CODE (addr) == PLUS)
21509     {
21510       rtx op0 = XEXP (addr, 0);
21511       rtx op1 = XEXP (addr, 1);
21512
21513       if (!base_reg_operand (op0, Pmode) || !CONST_INT_P (op1))
21514         return false;
21515
21516       HOST_WIDE_INT value = INTVAL (op1);
21517       if (!SIGNED_34BIT_OFFSET_P (value))
21518         return false;
21519
21520       /* Offset larger than 16-bits?  */
21521       if (!SIGNED_16BIT_OFFSET_P (value))
21522         return true;
21523
21524       /* DQ instruction (bottom 4 bits must be 0) for vectors.  */
21525       HOST_WIDE_INT mask;
21526       if (GET_MODE_SIZE (mode) >= 16)
21527         mask = 15;
21528
21529       /* DS instruction (bottom 2 bits must be 0).  For 32-bit integers, we
21530          need to use DS instructions if we are sign-extending the value with
21531          LWA.  For 32-bit floating point, we need DS instructions to load and
21532          store values to the traditional Altivec registers.  */
21533       else if (GET_MODE_SIZE (mode) >= 4)
21534         mask = 3;
21535
21536       /* QImode/HImode has no restrictions.  */
21537       else
21538         return true;
21539
21540       /* Return true if we must use a prefixed instruction.  */
21541       return (value & mask) != 0;
21542     }
21543
21544   return false;
21545 }
21546 \f
21547 #if defined (HAVE_GAS_HIDDEN) && !TARGET_MACHO
21548 /* Emit an assembler directive to set symbol visibility for DECL to
21549    VISIBILITY_TYPE.  */
21550
21551 static void
21552 rs6000_assemble_visibility (tree decl, int vis)
21553 {
21554   if (TARGET_XCOFF)
21555     return;
21556
21557   /* Functions need to have their entry point symbol visibility set as
21558      well as their descriptor symbol visibility.  */
21559   if (DEFAULT_ABI == ABI_AIX
21560       && DOT_SYMBOLS
21561       && TREE_CODE (decl) == FUNCTION_DECL)
21562     {
21563       static const char * const visibility_types[] = {
21564         NULL, "protected", "hidden", "internal"
21565       };
21566
21567       const char *name, *type;
21568
21569       name = ((* targetm.strip_name_encoding)
21570               (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl))));
21571       type = visibility_types[vis];
21572
21573       fprintf (asm_out_file, "\t.%s\t%s\n", type, name);
21574       fprintf (asm_out_file, "\t.%s\t.%s\n", type, name);
21575     }
21576   else
21577     default_assemble_visibility (decl, vis);
21578 }
21579 #endif
21580 \f
21581 enum rtx_code
21582 rs6000_reverse_condition (machine_mode mode, enum rtx_code code)
21583 {
21584   /* Reversal of FP compares takes care -- an ordered compare
21585      becomes an unordered compare and vice versa.  */
21586   if (mode == CCFPmode
21587       && (!flag_finite_math_only
21588           || code == UNLT || code == UNLE || code == UNGT || code == UNGE
21589           || code == UNEQ || code == LTGT))
21590     return reverse_condition_maybe_unordered (code);
21591   else
21592     return reverse_condition (code);
21593 }
21594
21595 /* Generate a compare for CODE.  Return a brand-new rtx that
21596    represents the result of the compare.  */
21597
21598 static rtx
21599 rs6000_generate_compare (rtx cmp, machine_mode mode)
21600 {
21601   machine_mode comp_mode;
21602   rtx compare_result;
21603   enum rtx_code code = GET_CODE (cmp);
21604   rtx op0 = XEXP (cmp, 0);
21605   rtx op1 = XEXP (cmp, 1);
21606
21607   if (!TARGET_FLOAT128_HW && FLOAT128_VECTOR_P (mode))
21608     comp_mode = CCmode;
21609   else if (FLOAT_MODE_P (mode))
21610     comp_mode = CCFPmode;
21611   else if (code == GTU || code == LTU
21612            || code == GEU || code == LEU)
21613     comp_mode = CCUNSmode;
21614   else if ((code == EQ || code == NE)
21615            && unsigned_reg_p (op0)
21616            && (unsigned_reg_p (op1)
21617                || (CONST_INT_P (op1) && INTVAL (op1) != 0)))
21618     /* These are unsigned values, perhaps there will be a later
21619        ordering compare that can be shared with this one.  */
21620     comp_mode = CCUNSmode;
21621   else
21622     comp_mode = CCmode;
21623
21624   /* If we have an unsigned compare, make sure we don't have a signed value as
21625      an immediate.  */
21626   if (comp_mode == CCUNSmode && CONST_INT_P (op1)
21627       && INTVAL (op1) < 0)
21628     {
21629       op0 = copy_rtx_if_shared (op0);
21630       op1 = force_reg (GET_MODE (op0), op1);
21631       cmp = gen_rtx_fmt_ee (code, GET_MODE (cmp), op0, op1);
21632     }
21633
21634   /* First, the compare.  */
21635   compare_result = gen_reg_rtx (comp_mode);
21636
21637   /* IEEE 128-bit support in VSX registers when we do not have hardware
21638      support.  */
21639   if (!TARGET_FLOAT128_HW && FLOAT128_VECTOR_P (mode))
21640     {
21641       rtx libfunc = NULL_RTX;
21642       bool check_nan = false;
21643       rtx dest;
21644
21645       switch (code)
21646         {
21647         case EQ:
21648         case NE:
21649           libfunc = optab_libfunc (eq_optab, mode);
21650           break;
21651
21652         case GT:
21653         case GE:
21654           libfunc = optab_libfunc (ge_optab, mode);
21655           break;
21656
21657         case LT:
21658         case LE:
21659           libfunc = optab_libfunc (le_optab, mode);
21660           break;
21661
21662         case UNORDERED:
21663         case ORDERED:
21664           libfunc = optab_libfunc (unord_optab, mode);
21665           code = (code == UNORDERED) ? NE : EQ;
21666           break;
21667
21668         case UNGE:
21669         case UNGT:
21670           check_nan = true;
21671           libfunc = optab_libfunc (ge_optab, mode);
21672           code = (code == UNGE) ? GE : GT;
21673           break;
21674
21675         case UNLE:
21676         case UNLT:
21677           check_nan = true;
21678           libfunc = optab_libfunc (le_optab, mode);
21679           code = (code == UNLE) ? LE : LT;
21680           break;
21681
21682         case UNEQ:
21683         case LTGT:
21684           check_nan = true;
21685           libfunc = optab_libfunc (eq_optab, mode);
21686           code = (code = UNEQ) ? EQ : NE;
21687           break;
21688
21689         default:
21690           gcc_unreachable ();
21691         }
21692
21693       gcc_assert (libfunc);
21694
21695       if (!check_nan)
21696         dest = emit_library_call_value (libfunc, NULL_RTX, LCT_CONST,
21697                                         SImode, op0, mode, op1, mode);
21698
21699       /* The library signals an exception for signalling NaNs, so we need to
21700          handle isgreater, etc. by first checking isordered.  */
21701       else
21702         {
21703           rtx ne_rtx, normal_dest, unord_dest;
21704           rtx unord_func = optab_libfunc (unord_optab, mode);
21705           rtx join_label = gen_label_rtx ();
21706           rtx join_ref = gen_rtx_LABEL_REF (VOIDmode, join_label);
21707           rtx unord_cmp = gen_reg_rtx (comp_mode);
21708
21709
21710           /* Test for either value being a NaN.  */
21711           gcc_assert (unord_func);
21712           unord_dest = emit_library_call_value (unord_func, NULL_RTX, LCT_CONST,
21713                                                 SImode, op0, mode, op1, mode);
21714
21715           /* Set value (0) if either value is a NaN, and jump to the join
21716              label.  */
21717           dest = gen_reg_rtx (SImode);
21718           emit_move_insn (dest, const1_rtx);
21719           emit_insn (gen_rtx_SET (unord_cmp,
21720                                   gen_rtx_COMPARE (comp_mode, unord_dest,
21721                                                    const0_rtx)));
21722
21723           ne_rtx = gen_rtx_NE (comp_mode, unord_cmp, const0_rtx);
21724           emit_jump_insn (gen_rtx_SET (pc_rtx,
21725                                        gen_rtx_IF_THEN_ELSE (VOIDmode, ne_rtx,
21726                                                              join_ref,
21727                                                              pc_rtx)));
21728
21729           /* Do the normal comparison, knowing that the values are not
21730              NaNs.  */
21731           normal_dest = emit_library_call_value (libfunc, NULL_RTX, LCT_CONST,
21732                                                  SImode, op0, mode, op1, mode);
21733
21734           emit_insn (gen_cstoresi4 (dest,
21735                                     gen_rtx_fmt_ee (code, SImode, normal_dest,
21736                                                     const0_rtx),
21737                                     normal_dest, const0_rtx));
21738
21739           /* Join NaN and non-Nan paths.  Compare dest against 0.  */
21740           emit_label (join_label);
21741           code = NE;
21742         }
21743
21744       emit_insn (gen_rtx_SET (compare_result,
21745                               gen_rtx_COMPARE (comp_mode, dest, const0_rtx)));
21746     }
21747
21748   else
21749     {
21750       /* Generate XLC-compatible TFmode compare as PARALLEL with extra
21751          CLOBBERs to match cmptf_internal2 pattern.  */
21752       if (comp_mode == CCFPmode && TARGET_XL_COMPAT
21753           && FLOAT128_IBM_P (GET_MODE (op0))
21754           && TARGET_HARD_FLOAT)
21755         emit_insn (gen_rtx_PARALLEL (VOIDmode,
21756           gen_rtvec (10,
21757                      gen_rtx_SET (compare_result,
21758                                   gen_rtx_COMPARE (comp_mode, op0, op1)),
21759                      gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (DFmode)),
21760                      gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (DFmode)),
21761                      gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (DFmode)),
21762                      gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (DFmode)),
21763                      gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (DFmode)),
21764                      gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (DFmode)),
21765                      gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (DFmode)),
21766                      gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (DFmode)),
21767                      gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (Pmode)))));
21768       else if (GET_CODE (op1) == UNSPEC
21769                && XINT (op1, 1) == UNSPEC_SP_TEST)
21770         {
21771           rtx op1b = XVECEXP (op1, 0, 0);
21772           comp_mode = CCEQmode;
21773           compare_result = gen_reg_rtx (CCEQmode);
21774           if (TARGET_64BIT)
21775             emit_insn (gen_stack_protect_testdi (compare_result, op0, op1b));
21776           else
21777             emit_insn (gen_stack_protect_testsi (compare_result, op0, op1b));
21778         }
21779       else
21780         emit_insn (gen_rtx_SET (compare_result,
21781                                 gen_rtx_COMPARE (comp_mode, op0, op1)));
21782     }
21783
21784   /* Some kinds of FP comparisons need an OR operation;
21785      under flag_finite_math_only we don't bother.  */
21786   if (FLOAT_MODE_P (mode)
21787       && (!FLOAT128_IEEE_P (mode) || TARGET_FLOAT128_HW)
21788       && !flag_finite_math_only
21789       && (code == LE || code == GE
21790           || code == UNEQ || code == LTGT
21791           || code == UNGT || code == UNLT))
21792     {
21793       enum rtx_code or1, or2;
21794       rtx or1_rtx, or2_rtx, compare2_rtx;
21795       rtx or_result = gen_reg_rtx (CCEQmode);
21796
21797       switch (code)
21798         {
21799         case LE: or1 = LT;  or2 = EQ;  break;
21800         case GE: or1 = GT;  or2 = EQ;  break;
21801         case UNEQ: or1 = UNORDERED;  or2 = EQ;  break;
21802         case LTGT: or1 = LT;  or2 = GT;  break;
21803         case UNGT: or1 = UNORDERED;  or2 = GT;  break;
21804         case UNLT: or1 = UNORDERED;  or2 = LT;  break;
21805         default:  gcc_unreachable ();
21806         }
21807       validate_condition_mode (or1, comp_mode);
21808       validate_condition_mode (or2, comp_mode);
21809       or1_rtx = gen_rtx_fmt_ee (or1, SImode, compare_result, const0_rtx);
21810       or2_rtx = gen_rtx_fmt_ee (or2, SImode, compare_result, const0_rtx);
21811       compare2_rtx = gen_rtx_COMPARE (CCEQmode,
21812                                       gen_rtx_IOR (SImode, or1_rtx, or2_rtx),
21813                                       const_true_rtx);
21814       emit_insn (gen_rtx_SET (or_result, compare2_rtx));
21815
21816       compare_result = or_result;
21817       code = EQ;
21818     }
21819
21820   validate_condition_mode (code, GET_MODE (compare_result));
21821
21822   return gen_rtx_fmt_ee (code, VOIDmode, compare_result, const0_rtx);
21823 }
21824
21825 \f
21826 /* Return the diagnostic message string if the binary operation OP is
21827    not permitted on TYPE1 and TYPE2, NULL otherwise.  */
21828
21829 static const char*
21830 rs6000_invalid_binary_op (int op ATTRIBUTE_UNUSED,
21831                           const_tree type1,
21832                           const_tree type2)
21833 {
21834   machine_mode mode1 = TYPE_MODE (type1);
21835   machine_mode mode2 = TYPE_MODE (type2);
21836
21837   /* For complex modes, use the inner type.  */
21838   if (COMPLEX_MODE_P (mode1))
21839     mode1 = GET_MODE_INNER (mode1);
21840
21841   if (COMPLEX_MODE_P (mode2))
21842     mode2 = GET_MODE_INNER (mode2);
21843
21844   /* Don't allow IEEE 754R 128-bit binary floating point and IBM extended
21845      double to intermix unless -mfloat128-convert.  */
21846   if (mode1 == mode2)
21847     return NULL;
21848
21849   if (!TARGET_FLOAT128_CVT)
21850     {
21851       if ((mode1 == KFmode && mode2 == IFmode)
21852           || (mode1 == IFmode && mode2 == KFmode))
21853         return N_("__float128 and __ibm128 cannot be used in the same "
21854                   "expression");
21855
21856       if (TARGET_IEEEQUAD
21857           && ((mode1 == IFmode && mode2 == TFmode)
21858               || (mode1 == TFmode && mode2 == IFmode)))
21859         return N_("__ibm128 and long double cannot be used in the same "
21860                   "expression");
21861
21862       if (!TARGET_IEEEQUAD
21863           && ((mode1 == KFmode && mode2 == TFmode)
21864               || (mode1 == TFmode && mode2 == KFmode)))
21865         return N_("__float128 and long double cannot be used in the same "
21866                   "expression");
21867     }
21868
21869   return NULL;
21870 }
21871
21872 \f
21873 /* Expand floating point conversion to/from __float128 and __ibm128.  */
21874
21875 void
21876 rs6000_expand_float128_convert (rtx dest, rtx src, bool unsigned_p)
21877 {
21878   machine_mode dest_mode = GET_MODE (dest);
21879   machine_mode src_mode = GET_MODE (src);
21880   convert_optab cvt = unknown_optab;
21881   bool do_move = false;
21882   rtx libfunc = NULL_RTX;
21883   rtx dest2;
21884   typedef rtx (*rtx_2func_t) (rtx, rtx);
21885   rtx_2func_t hw_convert = (rtx_2func_t)0;
21886   size_t kf_or_tf;
21887
21888   struct hw_conv_t {
21889     rtx_2func_t from_df;
21890     rtx_2func_t from_sf;
21891     rtx_2func_t from_si_sign;
21892     rtx_2func_t from_si_uns;
21893     rtx_2func_t from_di_sign;
21894     rtx_2func_t from_di_uns;
21895     rtx_2func_t to_df;
21896     rtx_2func_t to_sf;
21897     rtx_2func_t to_si_sign;
21898     rtx_2func_t to_si_uns;
21899     rtx_2func_t to_di_sign;
21900     rtx_2func_t to_di_uns;
21901   } hw_conversions[2] = {
21902     /* convertions to/from KFmode */
21903     {
21904       gen_extenddfkf2_hw,               /* KFmode <- DFmode.  */
21905       gen_extendsfkf2_hw,               /* KFmode <- SFmode.  */
21906       gen_float_kfsi2_hw,               /* KFmode <- SImode (signed).  */
21907       gen_floatuns_kfsi2_hw,            /* KFmode <- SImode (unsigned).  */
21908       gen_float_kfdi2_hw,               /* KFmode <- DImode (signed).  */
21909       gen_floatuns_kfdi2_hw,            /* KFmode <- DImode (unsigned).  */
21910       gen_trunckfdf2_hw,                /* DFmode <- KFmode.  */
21911       gen_trunckfsf2_hw,                /* SFmode <- KFmode.  */
21912       gen_fix_kfsi2_hw,                 /* SImode <- KFmode (signed).  */
21913       gen_fixuns_kfsi2_hw,              /* SImode <- KFmode (unsigned).  */
21914       gen_fix_kfdi2_hw,                 /* DImode <- KFmode (signed).  */
21915       gen_fixuns_kfdi2_hw,              /* DImode <- KFmode (unsigned).  */
21916     },
21917
21918     /* convertions to/from TFmode */
21919     {
21920       gen_extenddftf2_hw,               /* TFmode <- DFmode.  */
21921       gen_extendsftf2_hw,               /* TFmode <- SFmode.  */
21922       gen_float_tfsi2_hw,               /* TFmode <- SImode (signed).  */
21923       gen_floatuns_tfsi2_hw,            /* TFmode <- SImode (unsigned).  */
21924       gen_float_tfdi2_hw,               /* TFmode <- DImode (signed).  */
21925       gen_floatuns_tfdi2_hw,            /* TFmode <- DImode (unsigned).  */
21926       gen_trunctfdf2_hw,                /* DFmode <- TFmode.  */
21927       gen_trunctfsf2_hw,                /* SFmode <- TFmode.  */
21928       gen_fix_tfsi2_hw,                 /* SImode <- TFmode (signed).  */
21929       gen_fixuns_tfsi2_hw,              /* SImode <- TFmode (unsigned).  */
21930       gen_fix_tfdi2_hw,                 /* DImode <- TFmode (signed).  */
21931       gen_fixuns_tfdi2_hw,              /* DImode <- TFmode (unsigned).  */
21932     },
21933   };
21934
21935   if (dest_mode == src_mode)
21936     gcc_unreachable ();
21937
21938   /* Eliminate memory operations.  */
21939   if (MEM_P (src))
21940     src = force_reg (src_mode, src);
21941
21942   if (MEM_P (dest))
21943     {
21944       rtx tmp = gen_reg_rtx (dest_mode);
21945       rs6000_expand_float128_convert (tmp, src, unsigned_p);
21946       rs6000_emit_move (dest, tmp, dest_mode);
21947       return;
21948     }
21949
21950   /* Convert to IEEE 128-bit floating point.  */
21951   if (FLOAT128_IEEE_P (dest_mode))
21952     {
21953       if (dest_mode == KFmode)
21954         kf_or_tf = 0;
21955       else if (dest_mode == TFmode)
21956         kf_or_tf = 1;
21957       else
21958         gcc_unreachable ();
21959
21960       switch (src_mode)
21961         {
21962         case E_DFmode:
21963           cvt = sext_optab;
21964           hw_convert = hw_conversions[kf_or_tf].from_df;
21965           break;
21966
21967         case E_SFmode:
21968           cvt = sext_optab;
21969           hw_convert = hw_conversions[kf_or_tf].from_sf;
21970           break;
21971
21972         case E_KFmode:
21973         case E_IFmode:
21974         case E_TFmode:
21975           if (FLOAT128_IBM_P (src_mode))
21976             cvt = sext_optab;
21977           else
21978             do_move = true;
21979           break;
21980
21981         case E_SImode:
21982           if (unsigned_p)
21983             {
21984               cvt = ufloat_optab;
21985               hw_convert = hw_conversions[kf_or_tf].from_si_uns;
21986             }
21987           else
21988             {
21989               cvt = sfloat_optab;
21990               hw_convert = hw_conversions[kf_or_tf].from_si_sign;
21991             }
21992           break;
21993
21994         case E_DImode:
21995           if (unsigned_p)
21996             {
21997               cvt = ufloat_optab;
21998               hw_convert = hw_conversions[kf_or_tf].from_di_uns;
21999             }
22000           else
22001             {
22002               cvt = sfloat_optab;
22003               hw_convert = hw_conversions[kf_or_tf].from_di_sign;
22004             }
22005           break;
22006
22007         default:
22008           gcc_unreachable ();
22009         }
22010     }
22011
22012   /* Convert from IEEE 128-bit floating point.  */
22013   else if (FLOAT128_IEEE_P (src_mode))
22014     {
22015       if (src_mode == KFmode)
22016         kf_or_tf = 0;
22017       else if (src_mode == TFmode)
22018         kf_or_tf = 1;
22019       else
22020         gcc_unreachable ();
22021
22022       switch (dest_mode)
22023         {
22024         case E_DFmode:
22025           cvt = trunc_optab;
22026           hw_convert = hw_conversions[kf_or_tf].to_df;
22027           break;
22028
22029         case E_SFmode:
22030           cvt = trunc_optab;
22031           hw_convert = hw_conversions[kf_or_tf].to_sf;
22032           break;
22033
22034         case E_KFmode:
22035         case E_IFmode:
22036         case E_TFmode:
22037           if (FLOAT128_IBM_P (dest_mode))
22038             cvt = trunc_optab;
22039           else
22040             do_move = true;
22041           break;
22042
22043         case E_SImode:
22044           if (unsigned_p)
22045             {
22046               cvt = ufix_optab;
22047               hw_convert = hw_conversions[kf_or_tf].to_si_uns;
22048             }
22049           else
22050             {
22051               cvt = sfix_optab;
22052               hw_convert = hw_conversions[kf_or_tf].to_si_sign;
22053             }
22054           break;
22055
22056         case E_DImode:
22057           if (unsigned_p)
22058             {
22059               cvt = ufix_optab;
22060               hw_convert = hw_conversions[kf_or_tf].to_di_uns;
22061             }
22062           else
22063             {
22064               cvt = sfix_optab;
22065               hw_convert = hw_conversions[kf_or_tf].to_di_sign;
22066             }
22067           break;
22068
22069         default:
22070           gcc_unreachable ();
22071         }
22072     }
22073
22074   /* Both IBM format.  */
22075   else if (FLOAT128_IBM_P (dest_mode) && FLOAT128_IBM_P (src_mode))
22076     do_move = true;
22077
22078   else
22079     gcc_unreachable ();
22080
22081   /* Handle conversion between TFmode/KFmode/IFmode.  */
22082   if (do_move)
22083     emit_insn (gen_rtx_SET (dest, gen_rtx_FLOAT_EXTEND (dest_mode, src)));
22084
22085   /* Handle conversion if we have hardware support.  */
22086   else if (TARGET_FLOAT128_HW && hw_convert)
22087     emit_insn ((hw_convert) (dest, src));
22088
22089   /* Call an external function to do the conversion.  */
22090   else if (cvt != unknown_optab)
22091     {
22092       libfunc = convert_optab_libfunc (cvt, dest_mode, src_mode);
22093       gcc_assert (libfunc != NULL_RTX);
22094
22095       dest2 = emit_library_call_value (libfunc, dest, LCT_CONST, dest_mode,
22096                                        src, src_mode);
22097
22098       gcc_assert (dest2 != NULL_RTX);
22099       if (!rtx_equal_p (dest, dest2))
22100         emit_move_insn (dest, dest2);
22101     }
22102
22103   else
22104     gcc_unreachable ();
22105
22106   return;
22107 }
22108
22109 \f
22110 /* Emit RTL that sets a register to zero if OP1 and OP2 are equal.  SCRATCH
22111    can be used as that dest register.  Return the dest register.  */
22112
22113 rtx
22114 rs6000_emit_eqne (machine_mode mode, rtx op1, rtx op2, rtx scratch)
22115 {
22116   if (op2 == const0_rtx)
22117     return op1;
22118
22119   if (GET_CODE (scratch) == SCRATCH)
22120     scratch = gen_reg_rtx (mode);
22121
22122   if (logical_operand (op2, mode))
22123     emit_insn (gen_rtx_SET (scratch, gen_rtx_XOR (mode, op1, op2)));
22124   else
22125     emit_insn (gen_rtx_SET (scratch,
22126                             gen_rtx_PLUS (mode, op1, negate_rtx (mode, op2))));
22127
22128   return scratch;
22129 }
22130
22131 void
22132 rs6000_emit_sCOND (machine_mode mode, rtx operands[])
22133 {
22134   rtx condition_rtx;
22135   machine_mode op_mode;
22136   enum rtx_code cond_code;
22137   rtx result = operands[0];
22138
22139   condition_rtx = rs6000_generate_compare (operands[1], mode);
22140   cond_code = GET_CODE (condition_rtx);
22141
22142   if (cond_code == NE
22143       || cond_code == GE || cond_code == LE
22144       || cond_code == GEU || cond_code == LEU
22145       || cond_code == ORDERED || cond_code == UNGE || cond_code == UNLE)
22146     {
22147       rtx not_result = gen_reg_rtx (CCEQmode);
22148       rtx not_op, rev_cond_rtx;
22149       machine_mode cc_mode;
22150
22151       cc_mode = GET_MODE (XEXP (condition_rtx, 0));
22152
22153       rev_cond_rtx = gen_rtx_fmt_ee (rs6000_reverse_condition (cc_mode, cond_code),
22154                                      SImode, XEXP (condition_rtx, 0), const0_rtx);
22155       not_op = gen_rtx_COMPARE (CCEQmode, rev_cond_rtx, const0_rtx);
22156       emit_insn (gen_rtx_SET (not_result, not_op));
22157       condition_rtx = gen_rtx_EQ (VOIDmode, not_result, const0_rtx);
22158     }
22159
22160   op_mode = GET_MODE (XEXP (operands[1], 0));
22161   if (op_mode == VOIDmode)
22162     op_mode = GET_MODE (XEXP (operands[1], 1));
22163
22164   if (TARGET_POWERPC64 && (op_mode == DImode || FLOAT_MODE_P (mode)))
22165     {
22166       PUT_MODE (condition_rtx, DImode);
22167       convert_move (result, condition_rtx, 0);
22168     }
22169   else
22170     {
22171       PUT_MODE (condition_rtx, SImode);
22172       emit_insn (gen_rtx_SET (result, condition_rtx));
22173     }
22174 }
22175
22176 /* Emit a branch of kind CODE to location LOC.  */
22177
22178 void
22179 rs6000_emit_cbranch (machine_mode mode, rtx operands[])
22180 {
22181   rtx condition_rtx, loc_ref;
22182
22183   condition_rtx = rs6000_generate_compare (operands[0], mode);
22184   loc_ref = gen_rtx_LABEL_REF (VOIDmode, operands[3]);
22185   emit_jump_insn (gen_rtx_SET (pc_rtx,
22186                                gen_rtx_IF_THEN_ELSE (VOIDmode, condition_rtx,
22187                                                      loc_ref, pc_rtx)));
22188 }
22189
22190 /* Return the string to output a conditional branch to LABEL, which is
22191    the operand template of the label, or NULL if the branch is really a
22192    conditional return.
22193
22194    OP is the conditional expression.  XEXP (OP, 0) is assumed to be a
22195    condition code register and its mode specifies what kind of
22196    comparison we made.
22197
22198    REVERSED is nonzero if we should reverse the sense of the comparison.
22199
22200    INSN is the insn.  */
22201
22202 char *
22203 output_cbranch (rtx op, const char *label, int reversed, rtx_insn *insn)
22204 {
22205   static char string[64];
22206   enum rtx_code code = GET_CODE (op);
22207   rtx cc_reg = XEXP (op, 0);
22208   machine_mode mode = GET_MODE (cc_reg);
22209   int cc_regno = REGNO (cc_reg) - CR0_REGNO;
22210   int need_longbranch = label != NULL && get_attr_length (insn) == 8;
22211   int really_reversed = reversed ^ need_longbranch;
22212   char *s = string;
22213   const char *ccode;
22214   const char *pred;
22215   rtx note;
22216
22217   validate_condition_mode (code, mode);
22218
22219   /* Work out which way this really branches.  We could use
22220      reverse_condition_maybe_unordered here always but this
22221      makes the resulting assembler clearer.  */
22222   if (really_reversed)
22223     {
22224       /* Reversal of FP compares takes care -- an ordered compare
22225          becomes an unordered compare and vice versa.  */
22226       if (mode == CCFPmode)
22227         code = reverse_condition_maybe_unordered (code);
22228       else
22229         code = reverse_condition (code);
22230     }
22231
22232   switch (code)
22233     {
22234       /* Not all of these are actually distinct opcodes, but
22235          we distinguish them for clarity of the resulting assembler.  */
22236     case NE: case LTGT:
22237       ccode = "ne"; break;
22238     case EQ: case UNEQ:
22239       ccode = "eq"; break;
22240     case GE: case GEU:
22241       ccode = "ge"; break;
22242     case GT: case GTU: case UNGT:
22243       ccode = "gt"; break;
22244     case LE: case LEU:
22245       ccode = "le"; break;
22246     case LT: case LTU: case UNLT:
22247       ccode = "lt"; break;
22248     case UNORDERED: ccode = "un"; break;
22249     case ORDERED: ccode = "nu"; break;
22250     case UNGE: ccode = "nl"; break;
22251     case UNLE: ccode = "ng"; break;
22252     default:
22253       gcc_unreachable ();
22254     }
22255
22256   /* Maybe we have a guess as to how likely the branch is.  */
22257   pred = "";
22258   note = find_reg_note (insn, REG_BR_PROB, NULL_RTX);
22259   if (note != NULL_RTX)
22260     {
22261       /* PROB is the difference from 50%.  */
22262       int prob = profile_probability::from_reg_br_prob_note (XINT (note, 0))
22263                    .to_reg_br_prob_base () - REG_BR_PROB_BASE / 2;
22264
22265       /* Only hint for highly probable/improbable branches on newer cpus when
22266          we have real profile data, as static prediction overrides processor
22267          dynamic prediction.  For older cpus we may as well always hint, but
22268          assume not taken for branches that are very close to 50% as a
22269          mispredicted taken branch is more expensive than a
22270          mispredicted not-taken branch.  */
22271       if (rs6000_always_hint
22272           || (abs (prob) > REG_BR_PROB_BASE / 100 * 48
22273               && (profile_status_for_fn (cfun) != PROFILE_GUESSED)
22274               && br_prob_note_reliable_p (note)))
22275         {
22276           if (abs (prob) > REG_BR_PROB_BASE / 20
22277               && ((prob > 0) ^ need_longbranch))
22278             pred = "+";
22279           else
22280             pred = "-";
22281         }
22282     }
22283
22284   if (label == NULL)
22285     s += sprintf (s, "b%slr%s ", ccode, pred);
22286   else
22287     s += sprintf (s, "b%s%s ", ccode, pred);
22288
22289   /* We need to escape any '%' characters in the reg_names string.
22290      Assume they'd only be the first character....  */
22291   if (reg_names[cc_regno + CR0_REGNO][0] == '%')
22292     *s++ = '%';
22293   s += sprintf (s, "%s", reg_names[cc_regno + CR0_REGNO]);
22294
22295   if (label != NULL)
22296     {
22297       /* If the branch distance was too far, we may have to use an
22298          unconditional branch to go the distance.  */
22299       if (need_longbranch)
22300         s += sprintf (s, ",$+8\n\tb %s", label);
22301       else
22302         s += sprintf (s, ",%s", label);
22303     }
22304
22305   return string;
22306 }
22307
22308 /* Return insn for VSX or Altivec comparisons.  */
22309
22310 static rtx
22311 rs6000_emit_vector_compare_inner (enum rtx_code code, rtx op0, rtx op1)
22312 {
22313   rtx mask;
22314   machine_mode mode = GET_MODE (op0);
22315
22316   switch (code)
22317     {
22318     default:
22319       break;
22320
22321     case GE:
22322       if (GET_MODE_CLASS (mode) == MODE_VECTOR_INT)
22323         return NULL_RTX;
22324       /* FALLTHRU */
22325
22326     case EQ:
22327     case GT:
22328     case GTU:
22329     case ORDERED:
22330     case UNORDERED:
22331     case UNEQ:
22332     case LTGT:
22333       mask = gen_reg_rtx (mode);
22334       emit_insn (gen_rtx_SET (mask, gen_rtx_fmt_ee (code, mode, op0, op1)));
22335       return mask;
22336     }
22337
22338   return NULL_RTX;
22339 }
22340
22341 /* Emit vector compare for operands OP0 and OP1 using code RCODE.
22342    DMODE is expected destination mode. This is a recursive function.  */
22343
22344 static rtx
22345 rs6000_emit_vector_compare (enum rtx_code rcode,
22346                             rtx op0, rtx op1,
22347                             machine_mode dmode)
22348 {
22349   rtx mask;
22350   bool swap_operands = false;
22351   bool try_again = false;
22352
22353   gcc_assert (VECTOR_UNIT_ALTIVEC_OR_VSX_P (dmode));
22354   gcc_assert (GET_MODE (op0) == GET_MODE (op1));
22355
22356   /* See if the comparison works as is.  */
22357   mask = rs6000_emit_vector_compare_inner (rcode, op0, op1);
22358   if (mask)
22359     return mask;
22360
22361   switch (rcode)
22362     {
22363     case LT:
22364       rcode = GT;
22365       swap_operands = true;
22366       try_again = true;
22367       break;
22368     case LTU:
22369       rcode = GTU;
22370       swap_operands = true;
22371       try_again = true;
22372       break;
22373     case NE:
22374     case UNLE:
22375     case UNLT:
22376     case UNGE:
22377     case UNGT:
22378       /* Invert condition and try again.
22379          e.g., A != B becomes ~(A==B).  */
22380       {
22381         enum rtx_code rev_code;
22382         enum insn_code nor_code;
22383         rtx mask2;
22384
22385         rev_code = reverse_condition_maybe_unordered (rcode);
22386         if (rev_code == UNKNOWN)
22387           return NULL_RTX;
22388
22389         nor_code = optab_handler (one_cmpl_optab, dmode);
22390         if (nor_code == CODE_FOR_nothing)
22391           return NULL_RTX;
22392
22393         mask2 = rs6000_emit_vector_compare (rev_code, op0, op1, dmode);
22394         if (!mask2)
22395           return NULL_RTX;
22396
22397         mask = gen_reg_rtx (dmode);
22398         emit_insn (GEN_FCN (nor_code) (mask, mask2));
22399         return mask;
22400       }
22401       break;
22402     case GE:
22403     case GEU:
22404     case LE:
22405     case LEU:
22406       /* Try GT/GTU/LT/LTU OR EQ */
22407       {
22408         rtx c_rtx, eq_rtx;
22409         enum insn_code ior_code;
22410         enum rtx_code new_code;
22411
22412         switch (rcode)
22413           {
22414           case  GE:
22415             new_code = GT;
22416             break;
22417
22418           case GEU:
22419             new_code = GTU;
22420             break;
22421
22422           case LE:
22423             new_code = LT;
22424             break;
22425
22426           case LEU:
22427             new_code = LTU;
22428             break;
22429
22430           default:
22431             gcc_unreachable ();
22432           }
22433
22434         ior_code = optab_handler (ior_optab, dmode);
22435         if (ior_code == CODE_FOR_nothing)
22436           return NULL_RTX;
22437
22438         c_rtx = rs6000_emit_vector_compare (new_code, op0, op1, dmode);
22439         if (!c_rtx)
22440           return NULL_RTX;
22441
22442         eq_rtx = rs6000_emit_vector_compare (EQ, op0, op1, dmode);
22443         if (!eq_rtx)
22444           return NULL_RTX;
22445
22446         mask = gen_reg_rtx (dmode);
22447         emit_insn (GEN_FCN (ior_code) (mask, c_rtx, eq_rtx));
22448         return mask;
22449       }
22450       break;
22451     default:
22452       return NULL_RTX;
22453     }
22454
22455   if (try_again)
22456     {
22457       if (swap_operands)
22458         std::swap (op0, op1);
22459
22460       mask = rs6000_emit_vector_compare_inner (rcode, op0, op1);
22461       if (mask)
22462         return mask;
22463     }
22464
22465   /* You only get two chances.  */
22466   return NULL_RTX;
22467 }
22468
22469 /* Emit vector conditional expression.  DEST is destination. OP_TRUE and
22470    OP_FALSE are two VEC_COND_EXPR operands.  CC_OP0 and CC_OP1 are the two
22471    operands for the relation operation COND.  */
22472
22473 int
22474 rs6000_emit_vector_cond_expr (rtx dest, rtx op_true, rtx op_false,
22475                               rtx cond, rtx cc_op0, rtx cc_op1)
22476 {
22477   machine_mode dest_mode = GET_MODE (dest);
22478   machine_mode mask_mode = GET_MODE (cc_op0);
22479   enum rtx_code rcode = GET_CODE (cond);
22480   machine_mode cc_mode = CCmode;
22481   rtx mask;
22482   rtx cond2;
22483   bool invert_move = false;
22484
22485   if (VECTOR_UNIT_NONE_P (dest_mode))
22486     return 0;
22487
22488   gcc_assert (GET_MODE_SIZE (dest_mode) == GET_MODE_SIZE (mask_mode)
22489               && GET_MODE_NUNITS (dest_mode) == GET_MODE_NUNITS (mask_mode));
22490
22491   switch (rcode)
22492     {
22493       /* Swap operands if we can, and fall back to doing the operation as
22494          specified, and doing a NOR to invert the test.  */
22495     case NE:
22496     case UNLE:
22497     case UNLT:
22498     case UNGE:
22499     case UNGT:
22500       /* Invert condition and try again.
22501          e.g., A  = (B != C) ? D : E becomes A = (B == C) ? E : D.  */
22502       invert_move = true;
22503       rcode = reverse_condition_maybe_unordered (rcode);
22504       if (rcode == UNKNOWN)
22505         return 0;
22506       break;
22507
22508     case GE:
22509     case LE:
22510       if (GET_MODE_CLASS (mask_mode) == MODE_VECTOR_INT)
22511         {
22512           /* Invert condition to avoid compound test.  */
22513           invert_move = true;
22514           rcode = reverse_condition (rcode);
22515         }
22516       break;
22517
22518     case GTU:
22519     case GEU:
22520     case LTU:
22521     case LEU:
22522       /* Mark unsigned tests with CCUNSmode.  */
22523       cc_mode = CCUNSmode;
22524
22525       /* Invert condition to avoid compound test if necessary.  */
22526       if (rcode == GEU || rcode == LEU)
22527         {
22528           invert_move = true;
22529           rcode = reverse_condition (rcode);
22530         }
22531       break;
22532
22533     default:
22534       break;
22535     }
22536
22537   /* Get the vector mask for the given relational operations.  */
22538   mask = rs6000_emit_vector_compare (rcode, cc_op0, cc_op1, mask_mode);
22539
22540   if (!mask)
22541     return 0;
22542
22543   if (invert_move)
22544     std::swap (op_true, op_false);
22545
22546   /* Optimize vec1 == vec2, to know the mask generates -1/0.  */
22547   if (GET_MODE_CLASS (dest_mode) == MODE_VECTOR_INT
22548       && (GET_CODE (op_true) == CONST_VECTOR
22549           || GET_CODE (op_false) == CONST_VECTOR))
22550     {
22551       rtx constant_0 = CONST0_RTX (dest_mode);
22552       rtx constant_m1 = CONSTM1_RTX (dest_mode);
22553
22554       if (op_true == constant_m1 && op_false == constant_0)
22555         {
22556           emit_move_insn (dest, mask);
22557           return 1;
22558         }
22559
22560       else if (op_true == constant_0 && op_false == constant_m1)
22561         {
22562           emit_insn (gen_rtx_SET (dest, gen_rtx_NOT (dest_mode, mask)));
22563           return 1;
22564         }
22565
22566       /* If we can't use the vector comparison directly, perhaps we can use
22567          the mask for the true or false fields, instead of loading up a
22568          constant.  */
22569       if (op_true == constant_m1)
22570         op_true = mask;
22571
22572       if (op_false == constant_0)
22573         op_false = mask;
22574     }
22575
22576   if (!REG_P (op_true) && !SUBREG_P (op_true))
22577     op_true = force_reg (dest_mode, op_true);
22578
22579   if (!REG_P (op_false) && !SUBREG_P (op_false))
22580     op_false = force_reg (dest_mode, op_false);
22581
22582   cond2 = gen_rtx_fmt_ee (NE, cc_mode, gen_lowpart (dest_mode, mask),
22583                           CONST0_RTX (dest_mode));
22584   emit_insn (gen_rtx_SET (dest,
22585                           gen_rtx_IF_THEN_ELSE (dest_mode,
22586                                                 cond2,
22587                                                 op_true,
22588                                                 op_false)));
22589   return 1;
22590 }
22591
22592 /* ISA 3.0 (power9) minmax subcase to emit a XSMAXCDP or XSMINCDP instruction
22593    for SF/DF scalars.  Move TRUE_COND to DEST if OP of the operands of the last
22594    comparison is nonzero/true, FALSE_COND if it is zero/false.  Return 0 if the
22595    hardware has no such operation.  */
22596
22597 static int
22598 rs6000_emit_p9_fp_minmax (rtx dest, rtx op, rtx true_cond, rtx false_cond)
22599 {
22600   enum rtx_code code = GET_CODE (op);
22601   rtx op0 = XEXP (op, 0);
22602   rtx op1 = XEXP (op, 1);
22603   machine_mode compare_mode = GET_MODE (op0);
22604   machine_mode result_mode = GET_MODE (dest);
22605   bool max_p = false;
22606
22607   if (result_mode != compare_mode)
22608     return 0;
22609
22610   if (code == GE || code == GT)
22611     max_p = true;
22612   else if (code == LE || code == LT)
22613     max_p = false;
22614   else
22615     return 0;
22616
22617   if (rtx_equal_p (op0, true_cond) && rtx_equal_p (op1, false_cond))
22618     ;
22619
22620   else if (rtx_equal_p (op1, true_cond) && rtx_equal_p (op0, false_cond))
22621     max_p = !max_p;
22622
22623   else
22624     return 0;
22625
22626   rs6000_emit_minmax (dest, max_p ? SMAX : SMIN, op0, op1);
22627   return 1;
22628 }
22629
22630 /* ISA 3.0 (power9) conditional move subcase to emit XSCMP{EQ,GE,GT,NE}DP and
22631    XXSEL instructions for SF/DF scalars.  Move TRUE_COND to DEST if OP of the
22632    operands of the last comparison is nonzero/true, FALSE_COND if it is
22633    zero/false.  Return 0 if the hardware has no such operation.  */
22634
22635 static int
22636 rs6000_emit_p9_fp_cmove (rtx dest, rtx op, rtx true_cond, rtx false_cond)
22637 {
22638   enum rtx_code code = GET_CODE (op);
22639   rtx op0 = XEXP (op, 0);
22640   rtx op1 = XEXP (op, 1);
22641   machine_mode result_mode = GET_MODE (dest);
22642   rtx compare_rtx;
22643   rtx cmove_rtx;
22644   rtx clobber_rtx;
22645
22646   if (!can_create_pseudo_p ())
22647     return 0;
22648
22649   switch (code)
22650     {
22651     case EQ:
22652     case GE:
22653     case GT:
22654       break;
22655
22656     case NE:
22657     case LT:
22658     case LE:
22659       code = swap_condition (code);
22660       std::swap (op0, op1);
22661       break;
22662
22663     default:
22664       return 0;
22665     }
22666
22667   /* Generate:  [(parallel [(set (dest)
22668                                  (if_then_else (op (cmp1) (cmp2))
22669                                                (true)
22670                                                (false)))
22671                             (clobber (scratch))])].  */
22672
22673   compare_rtx = gen_rtx_fmt_ee (code, CCFPmode, op0, op1);
22674   cmove_rtx = gen_rtx_SET (dest,
22675                            gen_rtx_IF_THEN_ELSE (result_mode,
22676                                                  compare_rtx,
22677                                                  true_cond,
22678                                                  false_cond));
22679
22680   clobber_rtx = gen_rtx_CLOBBER (VOIDmode, gen_rtx_SCRATCH (V2DImode));
22681   emit_insn (gen_rtx_PARALLEL (VOIDmode,
22682                                gen_rtvec (2, cmove_rtx, clobber_rtx)));
22683
22684   return 1;
22685 }
22686
22687 /* Emit a conditional move: move TRUE_COND to DEST if OP of the
22688    operands of the last comparison is nonzero/true, FALSE_COND if it
22689    is zero/false.  Return 0 if the hardware has no such operation.  */
22690
22691 int
22692 rs6000_emit_cmove (rtx dest, rtx op, rtx true_cond, rtx false_cond)
22693 {
22694   enum rtx_code code = GET_CODE (op);
22695   rtx op0 = XEXP (op, 0);
22696   rtx op1 = XEXP (op, 1);
22697   machine_mode compare_mode = GET_MODE (op0);
22698   machine_mode result_mode = GET_MODE (dest);
22699   rtx temp;
22700   bool is_against_zero;
22701
22702   /* These modes should always match.  */
22703   if (GET_MODE (op1) != compare_mode
22704       /* In the isel case however, we can use a compare immediate, so
22705          op1 may be a small constant.  */
22706       && (!TARGET_ISEL || !short_cint_operand (op1, VOIDmode)))
22707     return 0;
22708   if (GET_MODE (true_cond) != result_mode)
22709     return 0;
22710   if (GET_MODE (false_cond) != result_mode)
22711     return 0;
22712
22713   /* See if we can use the ISA 3.0 (power9) min/max/compare functions.  */
22714   if (TARGET_P9_MINMAX
22715       && (compare_mode == SFmode || compare_mode == DFmode)
22716       && (result_mode == SFmode || result_mode == DFmode))
22717     {
22718       if (rs6000_emit_p9_fp_minmax (dest, op, true_cond, false_cond))
22719         return 1;
22720
22721       if (rs6000_emit_p9_fp_cmove (dest, op, true_cond, false_cond))
22722         return 1;
22723     }
22724
22725   /* Don't allow using floating point comparisons for integer results for
22726      now.  */
22727   if (FLOAT_MODE_P (compare_mode) && !FLOAT_MODE_P (result_mode))
22728     return 0;
22729
22730   /* First, work out if the hardware can do this at all, or
22731      if it's too slow....  */
22732   if (!FLOAT_MODE_P (compare_mode))
22733     {
22734       if (TARGET_ISEL)
22735         return rs6000_emit_int_cmove (dest, op, true_cond, false_cond);
22736       return 0;
22737     }
22738
22739   is_against_zero = op1 == CONST0_RTX (compare_mode);
22740
22741   /* A floating-point subtract might overflow, underflow, or produce
22742      an inexact result, thus changing the floating-point flags, so it
22743      can't be generated if we care about that.  It's safe if one side
22744      of the construct is zero, since then no subtract will be
22745      generated.  */
22746   if (SCALAR_FLOAT_MODE_P (compare_mode)
22747       && flag_trapping_math && ! is_against_zero)
22748     return 0;
22749
22750   /* Eliminate half of the comparisons by switching operands, this
22751      makes the remaining code simpler.  */
22752   if (code == UNLT || code == UNGT || code == UNORDERED || code == NE
22753       || code == LTGT || code == LT || code == UNLE)
22754     {
22755       code = reverse_condition_maybe_unordered (code);
22756       temp = true_cond;
22757       true_cond = false_cond;
22758       false_cond = temp;
22759     }
22760
22761   /* UNEQ and LTGT take four instructions for a comparison with zero,
22762      it'll probably be faster to use a branch here too.  */
22763   if (code == UNEQ && HONOR_NANS (compare_mode))
22764     return 0;
22765
22766   /* We're going to try to implement comparisons by performing
22767      a subtract, then comparing against zero.  Unfortunately,
22768      Inf - Inf is NaN which is not zero, and so if we don't
22769      know that the operand is finite and the comparison
22770      would treat EQ different to UNORDERED, we can't do it.  */
22771   if (HONOR_INFINITIES (compare_mode)
22772       && code != GT && code != UNGE
22773       && (!CONST_DOUBLE_P (op1)
22774           || real_isinf (CONST_DOUBLE_REAL_VALUE (op1)))
22775       /* Constructs of the form (a OP b ? a : b) are safe.  */
22776       && ((! rtx_equal_p (op0, false_cond) && ! rtx_equal_p (op1, false_cond))
22777           || (! rtx_equal_p (op0, true_cond)
22778               && ! rtx_equal_p (op1, true_cond))))
22779     return 0;
22780
22781   /* At this point we know we can use fsel.  */
22782
22783   /* Reduce the comparison to a comparison against zero.  */
22784   if (! is_against_zero)
22785     {
22786       temp = gen_reg_rtx (compare_mode);
22787       emit_insn (gen_rtx_SET (temp, gen_rtx_MINUS (compare_mode, op0, op1)));
22788       op0 = temp;
22789       op1 = CONST0_RTX (compare_mode);
22790     }
22791
22792   /* If we don't care about NaNs we can reduce some of the comparisons
22793      down to faster ones.  */
22794   if (! HONOR_NANS (compare_mode))
22795     switch (code)
22796       {
22797       case GT:
22798         code = LE;
22799         temp = true_cond;
22800         true_cond = false_cond;
22801         false_cond = temp;
22802         break;
22803       case UNGE:
22804         code = GE;
22805         break;
22806       case UNEQ:
22807         code = EQ;
22808         break;
22809       default:
22810         break;
22811       }
22812
22813   /* Now, reduce everything down to a GE.  */
22814   switch (code)
22815     {
22816     case GE:
22817       break;
22818
22819     case LE:
22820       temp = gen_reg_rtx (compare_mode);
22821       emit_insn (gen_rtx_SET (temp, gen_rtx_NEG (compare_mode, op0)));
22822       op0 = temp;
22823       break;
22824
22825     case ORDERED:
22826       temp = gen_reg_rtx (compare_mode);
22827       emit_insn (gen_rtx_SET (temp, gen_rtx_ABS (compare_mode, op0)));
22828       op0 = temp;
22829       break;
22830
22831     case EQ:
22832       temp = gen_reg_rtx (compare_mode);
22833       emit_insn (gen_rtx_SET (temp,
22834                               gen_rtx_NEG (compare_mode,
22835                                            gen_rtx_ABS (compare_mode, op0))));
22836       op0 = temp;
22837       break;
22838
22839     case UNGE:
22840       /* a UNGE 0 <-> (a GE 0 || -a UNLT 0) */
22841       temp = gen_reg_rtx (result_mode);
22842       emit_insn (gen_rtx_SET (temp,
22843                               gen_rtx_IF_THEN_ELSE (result_mode,
22844                                                     gen_rtx_GE (VOIDmode,
22845                                                                 op0, op1),
22846                                                     true_cond, false_cond)));
22847       false_cond = true_cond;
22848       true_cond = temp;
22849
22850       temp = gen_reg_rtx (compare_mode);
22851       emit_insn (gen_rtx_SET (temp, gen_rtx_NEG (compare_mode, op0)));
22852       op0 = temp;
22853       break;
22854
22855     case GT:
22856       /* a GT 0 <-> (a GE 0 && -a UNLT 0) */
22857       temp = gen_reg_rtx (result_mode);
22858       emit_insn (gen_rtx_SET (temp,
22859                               gen_rtx_IF_THEN_ELSE (result_mode,
22860                                                     gen_rtx_GE (VOIDmode,
22861                                                                 op0, op1),
22862                                                     true_cond, false_cond)));
22863       true_cond = false_cond;
22864       false_cond = temp;
22865
22866       temp = gen_reg_rtx (compare_mode);
22867       emit_insn (gen_rtx_SET (temp, gen_rtx_NEG (compare_mode, op0)));
22868       op0 = temp;
22869       break;
22870
22871     default:
22872       gcc_unreachable ();
22873     }
22874
22875   emit_insn (gen_rtx_SET (dest,
22876                           gen_rtx_IF_THEN_ELSE (result_mode,
22877                                                 gen_rtx_GE (VOIDmode,
22878                                                             op0, op1),
22879                                                 true_cond, false_cond)));
22880   return 1;
22881 }
22882
22883 /* Same as above, but for ints (isel).  */
22884
22885 int
22886 rs6000_emit_int_cmove (rtx dest, rtx op, rtx true_cond, rtx false_cond)
22887 {
22888   rtx condition_rtx, cr;
22889   machine_mode mode = GET_MODE (dest);
22890   enum rtx_code cond_code;
22891   rtx (*isel_func) (rtx, rtx, rtx, rtx, rtx);
22892   bool signedp;
22893
22894   if (mode != SImode && (!TARGET_POWERPC64 || mode != DImode))
22895     return 0;
22896
22897   /* We still have to do the compare, because isel doesn't do a
22898      compare, it just looks at the CRx bits set by a previous compare
22899      instruction.  */
22900   condition_rtx = rs6000_generate_compare (op, mode);
22901   cond_code = GET_CODE (condition_rtx);
22902   cr = XEXP (condition_rtx, 0);
22903   signedp = GET_MODE (cr) == CCmode;
22904
22905   isel_func = (mode == SImode
22906                ? (signedp ? gen_isel_signed_si : gen_isel_unsigned_si)
22907                : (signedp ? gen_isel_signed_di : gen_isel_unsigned_di));
22908
22909   switch (cond_code)
22910     {
22911     case LT: case GT: case LTU: case GTU: case EQ:
22912       /* isel handles these directly.  */
22913       break;
22914
22915     default:
22916       /* We need to swap the sense of the comparison.  */
22917       {
22918         std::swap (false_cond, true_cond);
22919         PUT_CODE (condition_rtx, reverse_condition (cond_code));
22920       }
22921       break;
22922     }
22923
22924   false_cond = force_reg (mode, false_cond);
22925   if (true_cond != const0_rtx)
22926     true_cond = force_reg (mode, true_cond);
22927
22928   emit_insn (isel_func (dest, condition_rtx, true_cond, false_cond, cr));
22929
22930   return 1;
22931 }
22932
22933 void
22934 rs6000_emit_minmax (rtx dest, enum rtx_code code, rtx op0, rtx op1)
22935 {
22936   machine_mode mode = GET_MODE (op0);
22937   enum rtx_code c;
22938   rtx target;
22939
22940   /* VSX/altivec have direct min/max insns.  */
22941   if ((code == SMAX || code == SMIN)
22942       && (VECTOR_UNIT_ALTIVEC_OR_VSX_P (mode)
22943           || (mode == SFmode && VECTOR_UNIT_VSX_P (DFmode))))
22944     {
22945       emit_insn (gen_rtx_SET (dest, gen_rtx_fmt_ee (code, mode, op0, op1)));
22946       return;
22947     }
22948
22949   if (code == SMAX || code == SMIN)
22950     c = GE;
22951   else
22952     c = GEU;
22953
22954   if (code == SMAX || code == UMAX)
22955     target = emit_conditional_move (dest, c, op0, op1, mode,
22956                                     op0, op1, mode, 0);
22957   else
22958     target = emit_conditional_move (dest, c, op0, op1, mode,
22959                                     op1, op0, mode, 0);
22960   gcc_assert (target);
22961   if (target != dest)
22962     emit_move_insn (dest, target);
22963 }
22964
22965 /* A subroutine of the atomic operation splitters.  Jump to LABEL if
22966    COND is true.  Mark the jump as unlikely to be taken.  */
22967
22968 static void
22969 emit_unlikely_jump (rtx cond, rtx label)
22970 {
22971   rtx x = gen_rtx_IF_THEN_ELSE (VOIDmode, cond, label, pc_rtx);
22972   rtx_insn *insn = emit_jump_insn (gen_rtx_SET (pc_rtx, x));
22973   add_reg_br_prob_note (insn, profile_probability::very_unlikely ());
22974 }
22975
22976 /* A subroutine of the atomic operation splitters.  Emit a load-locked
22977    instruction in MODE.  For QI/HImode, possibly use a pattern than includes
22978    the zero_extend operation.  */
22979
22980 static void
22981 emit_load_locked (machine_mode mode, rtx reg, rtx mem)
22982 {
22983   rtx (*fn) (rtx, rtx) = NULL;
22984
22985   switch (mode)
22986     {
22987     case E_QImode:
22988       fn = gen_load_lockedqi;
22989       break;
22990     case E_HImode:
22991       fn = gen_load_lockedhi;
22992       break;
22993     case E_SImode:
22994       if (GET_MODE (mem) == QImode)
22995         fn = gen_load_lockedqi_si;
22996       else if (GET_MODE (mem) == HImode)
22997         fn = gen_load_lockedhi_si;
22998       else
22999         fn = gen_load_lockedsi;
23000       break;
23001     case E_DImode:
23002       fn = gen_load_lockeddi;
23003       break;
23004     case E_TImode:
23005       fn = gen_load_lockedti;
23006       break;
23007     default:
23008       gcc_unreachable ();
23009     }
23010   emit_insn (fn (reg, mem));
23011 }
23012
23013 /* A subroutine of the atomic operation splitters.  Emit a store-conditional
23014    instruction in MODE.  */
23015
23016 static void
23017 emit_store_conditional (machine_mode mode, rtx res, rtx mem, rtx val)
23018 {
23019   rtx (*fn) (rtx, rtx, rtx) = NULL;
23020
23021   switch (mode)
23022     {
23023     case E_QImode:
23024       fn = gen_store_conditionalqi;
23025       break;
23026     case E_HImode:
23027       fn = gen_store_conditionalhi;
23028       break;
23029     case E_SImode:
23030       fn = gen_store_conditionalsi;
23031       break;
23032     case E_DImode:
23033       fn = gen_store_conditionaldi;
23034       break;
23035     case E_TImode:
23036       fn = gen_store_conditionalti;
23037       break;
23038     default:
23039       gcc_unreachable ();
23040     }
23041
23042   /* Emit sync before stwcx. to address PPC405 Erratum.  */
23043   if (PPC405_ERRATUM77)
23044     emit_insn (gen_hwsync ());
23045
23046   emit_insn (fn (res, mem, val));
23047 }
23048
23049 /* Expand barriers before and after a load_locked/store_cond sequence.  */
23050
23051 static rtx
23052 rs6000_pre_atomic_barrier (rtx mem, enum memmodel model)
23053 {
23054   rtx addr = XEXP (mem, 0);
23055
23056   if (!legitimate_indirect_address_p (addr, reload_completed)
23057       && !legitimate_indexed_address_p (addr, reload_completed))
23058     {
23059       addr = force_reg (Pmode, addr);
23060       mem = replace_equiv_address_nv (mem, addr);
23061     }
23062
23063   switch (model)
23064     {
23065     case MEMMODEL_RELAXED:
23066     case MEMMODEL_CONSUME:
23067     case MEMMODEL_ACQUIRE:
23068       break;
23069     case MEMMODEL_RELEASE:
23070     case MEMMODEL_ACQ_REL:
23071       emit_insn (gen_lwsync ());
23072       break;
23073     case MEMMODEL_SEQ_CST:
23074       emit_insn (gen_hwsync ());
23075       break;
23076     default:
23077       gcc_unreachable ();
23078     }
23079   return mem;
23080 }
23081
23082 static void
23083 rs6000_post_atomic_barrier (enum memmodel model)
23084 {
23085   switch (model)
23086     {
23087     case MEMMODEL_RELAXED:
23088     case MEMMODEL_CONSUME:
23089     case MEMMODEL_RELEASE:
23090       break;
23091     case MEMMODEL_ACQUIRE:
23092     case MEMMODEL_ACQ_REL:
23093     case MEMMODEL_SEQ_CST:
23094       emit_insn (gen_isync ());
23095       break;
23096     default:
23097       gcc_unreachable ();
23098     }
23099 }
23100
23101 /* A subroutine of the various atomic expanders.  For sub-word operations,
23102    we must adjust things to operate on SImode.  Given the original MEM,
23103    return a new aligned memory.  Also build and return the quantities by
23104    which to shift and mask.  */
23105
23106 static rtx
23107 rs6000_adjust_atomic_subword (rtx orig_mem, rtx *pshift, rtx *pmask)
23108 {
23109   rtx addr, align, shift, mask, mem;
23110   HOST_WIDE_INT shift_mask;
23111   machine_mode mode = GET_MODE (orig_mem);
23112
23113   /* For smaller modes, we have to implement this via SImode.  */
23114   shift_mask = (mode == QImode ? 0x18 : 0x10);
23115
23116   addr = XEXP (orig_mem, 0);
23117   addr = force_reg (GET_MODE (addr), addr);
23118
23119   /* Aligned memory containing subword.  Generate a new memory.  We
23120      do not want any of the existing MEM_ATTR data, as we're now
23121      accessing memory outside the original object.  */
23122   align = expand_simple_binop (Pmode, AND, addr, GEN_INT (-4),
23123                                NULL_RTX, 1, OPTAB_LIB_WIDEN);
23124   mem = gen_rtx_MEM (SImode, align);
23125   MEM_VOLATILE_P (mem) = MEM_VOLATILE_P (orig_mem);
23126   if (MEM_ALIAS_SET (orig_mem) == ALIAS_SET_MEMORY_BARRIER)
23127     set_mem_alias_set (mem, ALIAS_SET_MEMORY_BARRIER);
23128
23129   /* Shift amount for subword relative to aligned word.  */
23130   shift = gen_reg_rtx (SImode);
23131   addr = gen_lowpart (SImode, addr);
23132   rtx tmp = gen_reg_rtx (SImode);
23133   emit_insn (gen_ashlsi3 (tmp, addr, GEN_INT (3)));
23134   emit_insn (gen_andsi3 (shift, tmp, GEN_INT (shift_mask)));
23135   if (BYTES_BIG_ENDIAN)
23136     shift = expand_simple_binop (SImode, XOR, shift, GEN_INT (shift_mask),
23137                                  shift, 1, OPTAB_LIB_WIDEN);
23138   *pshift = shift;
23139
23140   /* Mask for insertion.  */
23141   mask = expand_simple_binop (SImode, ASHIFT, GEN_INT (GET_MODE_MASK (mode)),
23142                               shift, NULL_RTX, 1, OPTAB_LIB_WIDEN);
23143   *pmask = mask;
23144
23145   return mem;
23146 }
23147
23148 /* A subroutine of the various atomic expanders.  For sub-word operands,
23149    combine OLDVAL and NEWVAL via MASK.  Returns a new pseduo.  */
23150
23151 static rtx
23152 rs6000_mask_atomic_subword (rtx oldval, rtx newval, rtx mask)
23153 {
23154   rtx x;
23155
23156   x = gen_reg_rtx (SImode);
23157   emit_insn (gen_rtx_SET (x, gen_rtx_AND (SImode,
23158                                           gen_rtx_NOT (SImode, mask),
23159                                           oldval)));
23160
23161   x = expand_simple_binop (SImode, IOR, newval, x, x, 1, OPTAB_LIB_WIDEN);
23162
23163   return x;
23164 }
23165
23166 /* A subroutine of the various atomic expanders.  For sub-word operands,
23167    extract WIDE to NARROW via SHIFT.  */
23168
23169 static void
23170 rs6000_finish_atomic_subword (rtx narrow, rtx wide, rtx shift)
23171 {
23172   wide = expand_simple_binop (SImode, LSHIFTRT, wide, shift,
23173                               wide, 1, OPTAB_LIB_WIDEN);
23174   emit_move_insn (narrow, gen_lowpart (GET_MODE (narrow), wide));
23175 }
23176
23177 /* Expand an atomic compare and swap operation.  */
23178
23179 void
23180 rs6000_expand_atomic_compare_and_swap (rtx operands[])
23181 {
23182   rtx boolval, retval, mem, oldval, newval, cond;
23183   rtx label1, label2, x, mask, shift;
23184   machine_mode mode, orig_mode;
23185   enum memmodel mod_s, mod_f;
23186   bool is_weak;
23187
23188   boolval = operands[0];
23189   retval = operands[1];
23190   mem = operands[2];
23191   oldval = operands[3];
23192   newval = operands[4];
23193   is_weak = (INTVAL (operands[5]) != 0);
23194   mod_s = memmodel_base (INTVAL (operands[6]));
23195   mod_f = memmodel_base (INTVAL (operands[7]));
23196   orig_mode = mode = GET_MODE (mem);
23197
23198   mask = shift = NULL_RTX;
23199   if (mode == QImode || mode == HImode)
23200     {
23201       /* Before power8, we didn't have access to lbarx/lharx, so generate a
23202          lwarx and shift/mask operations.  With power8, we need to do the
23203          comparison in SImode, but the store is still done in QI/HImode.  */
23204       oldval = convert_modes (SImode, mode, oldval, 1);
23205
23206       if (!TARGET_SYNC_HI_QI)
23207         {
23208           mem = rs6000_adjust_atomic_subword (mem, &shift, &mask);
23209
23210           /* Shift and mask OLDVAL into position with the word.  */
23211           oldval = expand_simple_binop (SImode, ASHIFT, oldval, shift,
23212                                         NULL_RTX, 1, OPTAB_LIB_WIDEN);
23213
23214           /* Shift and mask NEWVAL into position within the word.  */
23215           newval = convert_modes (SImode, mode, newval, 1);
23216           newval = expand_simple_binop (SImode, ASHIFT, newval, shift,
23217                                         NULL_RTX, 1, OPTAB_LIB_WIDEN);
23218         }
23219
23220       /* Prepare to adjust the return value.  */
23221       retval = gen_reg_rtx (SImode);
23222       mode = SImode;
23223     }
23224   else if (reg_overlap_mentioned_p (retval, oldval))
23225     oldval = copy_to_reg (oldval);
23226
23227   if (mode != TImode && !reg_or_short_operand (oldval, mode))
23228     oldval = copy_to_mode_reg (mode, oldval);
23229
23230   if (reg_overlap_mentioned_p (retval, newval))
23231     newval = copy_to_reg (newval);
23232
23233   mem = rs6000_pre_atomic_barrier (mem, mod_s);
23234
23235   label1 = NULL_RTX;
23236   if (!is_weak)
23237     {
23238       label1 = gen_rtx_LABEL_REF (VOIDmode, gen_label_rtx ());
23239       emit_label (XEXP (label1, 0));
23240     }
23241   label2 = gen_rtx_LABEL_REF (VOIDmode, gen_label_rtx ());
23242
23243   emit_load_locked (mode, retval, mem);
23244
23245   x = retval;
23246   if (mask)
23247     x = expand_simple_binop (SImode, AND, retval, mask,
23248                              NULL_RTX, 1, OPTAB_LIB_WIDEN);
23249
23250   cond = gen_reg_rtx (CCmode);
23251   /* If we have TImode, synthesize a comparison.  */
23252   if (mode != TImode)
23253     x = gen_rtx_COMPARE (CCmode, x, oldval);
23254   else
23255     {
23256       rtx xor1_result = gen_reg_rtx (DImode);
23257       rtx xor2_result = gen_reg_rtx (DImode);
23258       rtx or_result = gen_reg_rtx (DImode);
23259       rtx new_word0 = simplify_gen_subreg (DImode, x, TImode, 0);
23260       rtx new_word1 = simplify_gen_subreg (DImode, x, TImode, 8);
23261       rtx old_word0 = simplify_gen_subreg (DImode, oldval, TImode, 0);
23262       rtx old_word1 = simplify_gen_subreg (DImode, oldval, TImode, 8);
23263
23264       emit_insn (gen_xordi3 (xor1_result, new_word0, old_word0));
23265       emit_insn (gen_xordi3 (xor2_result, new_word1, old_word1));
23266       emit_insn (gen_iordi3 (or_result, xor1_result, xor2_result));
23267       x = gen_rtx_COMPARE (CCmode, or_result, const0_rtx);
23268     }
23269
23270   emit_insn (gen_rtx_SET (cond, x));
23271
23272   x = gen_rtx_NE (VOIDmode, cond, const0_rtx);
23273   emit_unlikely_jump (x, label2);
23274
23275   x = newval;
23276   if (mask)
23277     x = rs6000_mask_atomic_subword (retval, newval, mask);
23278
23279   emit_store_conditional (orig_mode, cond, mem, x);
23280
23281   if (!is_weak)
23282     {
23283       x = gen_rtx_NE (VOIDmode, cond, const0_rtx);
23284       emit_unlikely_jump (x, label1);
23285     }
23286
23287   if (!is_mm_relaxed (mod_f))
23288     emit_label (XEXP (label2, 0));
23289
23290   rs6000_post_atomic_barrier (mod_s);
23291
23292   if (is_mm_relaxed (mod_f))
23293     emit_label (XEXP (label2, 0));
23294
23295   if (shift)
23296     rs6000_finish_atomic_subword (operands[1], retval, shift);
23297   else if (mode != GET_MODE (operands[1]))
23298     convert_move (operands[1], retval, 1);
23299
23300   /* In all cases, CR0 contains EQ on success, and NE on failure.  */
23301   x = gen_rtx_EQ (SImode, cond, const0_rtx);
23302   emit_insn (gen_rtx_SET (boolval, x));
23303 }
23304
23305 /* Expand an atomic exchange operation.  */
23306
23307 void
23308 rs6000_expand_atomic_exchange (rtx operands[])
23309 {
23310   rtx retval, mem, val, cond;
23311   machine_mode mode;
23312   enum memmodel model;
23313   rtx label, x, mask, shift;
23314
23315   retval = operands[0];
23316   mem = operands[1];
23317   val = operands[2];
23318   model = memmodel_base (INTVAL (operands[3]));
23319   mode = GET_MODE (mem);
23320
23321   mask = shift = NULL_RTX;
23322   if (!TARGET_SYNC_HI_QI && (mode == QImode || mode == HImode))
23323     {
23324       mem = rs6000_adjust_atomic_subword (mem, &shift, &mask);
23325
23326       /* Shift and mask VAL into position with the word.  */
23327       val = convert_modes (SImode, mode, val, 1);
23328       val = expand_simple_binop (SImode, ASHIFT, val, shift,
23329                                  NULL_RTX, 1, OPTAB_LIB_WIDEN);
23330
23331       /* Prepare to adjust the return value.  */
23332       retval = gen_reg_rtx (SImode);
23333       mode = SImode;
23334     }
23335
23336   mem = rs6000_pre_atomic_barrier (mem, model);
23337
23338   label = gen_rtx_LABEL_REF (VOIDmode, gen_label_rtx ());
23339   emit_label (XEXP (label, 0));
23340
23341   emit_load_locked (mode, retval, mem);
23342
23343   x = val;
23344   if (mask)
23345     x = rs6000_mask_atomic_subword (retval, val, mask);
23346
23347   cond = gen_reg_rtx (CCmode);
23348   emit_store_conditional (mode, cond, mem, x);
23349
23350   x = gen_rtx_NE (VOIDmode, cond, const0_rtx);
23351   emit_unlikely_jump (x, label);
23352
23353   rs6000_post_atomic_barrier (model);
23354
23355   if (shift)
23356     rs6000_finish_atomic_subword (operands[0], retval, shift);
23357 }
23358
23359 /* Expand an atomic fetch-and-operate pattern.  CODE is the binary operation
23360    to perform.  MEM is the memory on which to operate.  VAL is the second
23361    operand of the binary operator.  BEFORE and AFTER are optional locations to
23362    return the value of MEM either before of after the operation.  MODEL_RTX
23363    is a CONST_INT containing the memory model to use.  */
23364
23365 void
23366 rs6000_expand_atomic_op (enum rtx_code code, rtx mem, rtx val,
23367                          rtx orig_before, rtx orig_after, rtx model_rtx)
23368 {
23369   enum memmodel model = memmodel_base (INTVAL (model_rtx));
23370   machine_mode mode = GET_MODE (mem);
23371   machine_mode store_mode = mode;
23372   rtx label, x, cond, mask, shift;
23373   rtx before = orig_before, after = orig_after;
23374
23375   mask = shift = NULL_RTX;
23376   /* On power8, we want to use SImode for the operation.  On previous systems,
23377      use the operation in a subword and shift/mask to get the proper byte or
23378      halfword.  */
23379   if (mode == QImode || mode == HImode)
23380     {
23381       if (TARGET_SYNC_HI_QI)
23382         {
23383           val = convert_modes (SImode, mode, val, 1);
23384
23385           /* Prepare to adjust the return value.  */
23386           before = gen_reg_rtx (SImode);
23387           if (after)
23388             after = gen_reg_rtx (SImode);
23389           mode = SImode;
23390         }
23391       else
23392         {
23393           mem = rs6000_adjust_atomic_subword (mem, &shift, &mask);
23394
23395           /* Shift and mask VAL into position with the word.  */
23396           val = convert_modes (SImode, mode, val, 1);
23397           val = expand_simple_binop (SImode, ASHIFT, val, shift,
23398                                      NULL_RTX, 1, OPTAB_LIB_WIDEN);
23399
23400           switch (code)
23401             {
23402             case IOR:
23403             case XOR:
23404               /* We've already zero-extended VAL.  That is sufficient to
23405                  make certain that it does not affect other bits.  */
23406               mask = NULL;
23407               break;
23408
23409             case AND:
23410               /* If we make certain that all of the other bits in VAL are
23411                  set, that will be sufficient to not affect other bits.  */
23412               x = gen_rtx_NOT (SImode, mask);
23413               x = gen_rtx_IOR (SImode, x, val);
23414               emit_insn (gen_rtx_SET (val, x));
23415               mask = NULL;
23416               break;
23417
23418             case NOT:
23419             case PLUS:
23420             case MINUS:
23421               /* These will all affect bits outside the field and need
23422                  adjustment via MASK within the loop.  */
23423               break;
23424
23425             default:
23426               gcc_unreachable ();
23427             }
23428
23429           /* Prepare to adjust the return value.  */
23430           before = gen_reg_rtx (SImode);
23431           if (after)
23432             after = gen_reg_rtx (SImode);
23433           store_mode = mode = SImode;
23434         }
23435     }
23436
23437   mem = rs6000_pre_atomic_barrier (mem, model);
23438
23439   label = gen_label_rtx ();
23440   emit_label (label);
23441   label = gen_rtx_LABEL_REF (VOIDmode, label);
23442
23443   if (before == NULL_RTX)
23444     before = gen_reg_rtx (mode);
23445
23446   emit_load_locked (mode, before, mem);
23447
23448   if (code == NOT)
23449     {
23450       x = expand_simple_binop (mode, AND, before, val,
23451                                NULL_RTX, 1, OPTAB_LIB_WIDEN);
23452       after = expand_simple_unop (mode, NOT, x, after, 1);
23453     }
23454   else
23455     {
23456       after = expand_simple_binop (mode, code, before, val,
23457                                    after, 1, OPTAB_LIB_WIDEN);
23458     }
23459
23460   x = after;
23461   if (mask)
23462     {
23463       x = expand_simple_binop (SImode, AND, after, mask,
23464                                NULL_RTX, 1, OPTAB_LIB_WIDEN);
23465       x = rs6000_mask_atomic_subword (before, x, mask);
23466     }
23467   else if (store_mode != mode)
23468     x = convert_modes (store_mode, mode, x, 1);
23469
23470   cond = gen_reg_rtx (CCmode);
23471   emit_store_conditional (store_mode, cond, mem, x);
23472
23473   x = gen_rtx_NE (VOIDmode, cond, const0_rtx);
23474   emit_unlikely_jump (x, label);
23475
23476   rs6000_post_atomic_barrier (model);
23477
23478   if (shift)
23479     {
23480       /* QImode/HImode on machines without lbarx/lharx where we do a lwarx and
23481          then do the calcuations in a SImode register.  */
23482       if (orig_before)
23483         rs6000_finish_atomic_subword (orig_before, before, shift);
23484       if (orig_after)
23485         rs6000_finish_atomic_subword (orig_after, after, shift);
23486     }
23487   else if (store_mode != mode)
23488     {
23489       /* QImode/HImode on machines with lbarx/lharx where we do the native
23490          operation and then do the calcuations in a SImode register.  */
23491       if (orig_before)
23492         convert_move (orig_before, before, 1);
23493       if (orig_after)
23494         convert_move (orig_after, after, 1);
23495     }
23496   else if (orig_after && after != orig_after)
23497     emit_move_insn (orig_after, after);
23498 }
23499
23500 /* Emit instructions to move SRC to DST.  Called by splitters for
23501    multi-register moves.  It will emit at most one instruction for
23502    each register that is accessed; that is, it won't emit li/lis pairs
23503    (or equivalent for 64-bit code).  One of SRC or DST must be a hard
23504    register.  */
23505
23506 void
23507 rs6000_split_multireg_move (rtx dst, rtx src)
23508 {
23509   /* The register number of the first register being moved.  */
23510   int reg;
23511   /* The mode that is to be moved.  */
23512   machine_mode mode;
23513   /* The mode that the move is being done in, and its size.  */
23514   machine_mode reg_mode;
23515   int reg_mode_size;
23516   /* The number of registers that will be moved.  */
23517   int nregs;
23518
23519   reg = REG_P (dst) ? REGNO (dst) : REGNO (src);
23520   mode = GET_MODE (dst);
23521   nregs = hard_regno_nregs (reg, mode);
23522   if (FP_REGNO_P (reg))
23523     reg_mode = DECIMAL_FLOAT_MODE_P (mode) ? DDmode :
23524         (TARGET_HARD_FLOAT ? DFmode : SFmode);
23525   else if (ALTIVEC_REGNO_P (reg))
23526     reg_mode = V16QImode;
23527   else
23528     reg_mode = word_mode;
23529   reg_mode_size = GET_MODE_SIZE (reg_mode);
23530
23531   gcc_assert (reg_mode_size * nregs == GET_MODE_SIZE (mode));
23532
23533   /* TDmode residing in FP registers is special, since the ISA requires that
23534      the lower-numbered word of a register pair is always the most significant
23535      word, even in little-endian mode.  This does not match the usual subreg
23536      semantics, so we cannnot use simplify_gen_subreg in those cases.  Access
23537      the appropriate constituent registers "by hand" in little-endian mode.
23538
23539      Note we do not need to check for destructive overlap here since TDmode
23540      can only reside in even/odd register pairs.  */
23541   if (FP_REGNO_P (reg) && DECIMAL_FLOAT_MODE_P (mode) && !BYTES_BIG_ENDIAN)
23542     {
23543       rtx p_src, p_dst;
23544       int i;
23545
23546       for (i = 0; i < nregs; i++)
23547         {
23548           if (REG_P (src) && FP_REGNO_P (REGNO (src)))
23549             p_src = gen_rtx_REG (reg_mode, REGNO (src) + nregs - 1 - i);
23550           else
23551             p_src = simplify_gen_subreg (reg_mode, src, mode,
23552                                          i * reg_mode_size);
23553
23554           if (REG_P (dst) && FP_REGNO_P (REGNO (dst)))
23555             p_dst = gen_rtx_REG (reg_mode, REGNO (dst) + nregs - 1 - i);
23556           else
23557             p_dst = simplify_gen_subreg (reg_mode, dst, mode,
23558                                          i * reg_mode_size);
23559
23560           emit_insn (gen_rtx_SET (p_dst, p_src));
23561         }
23562
23563       return;
23564     }
23565
23566   if (REG_P (src) && REG_P (dst) && (REGNO (src) < REGNO (dst)))
23567     {
23568       /* Move register range backwards, if we might have destructive
23569          overlap.  */
23570       int i;
23571       for (i = nregs - 1; i >= 0; i--)
23572         emit_insn (gen_rtx_SET (simplify_gen_subreg (reg_mode, dst, mode,
23573                                                      i * reg_mode_size),
23574                                 simplify_gen_subreg (reg_mode, src, mode,
23575                                                      i * reg_mode_size)));
23576     }
23577   else
23578     {
23579       int i;
23580       int j = -1;
23581       bool used_update = false;
23582       rtx restore_basereg = NULL_RTX;
23583
23584       if (MEM_P (src) && INT_REGNO_P (reg))
23585         {
23586           rtx breg;
23587
23588           if (GET_CODE (XEXP (src, 0)) == PRE_INC
23589               || GET_CODE (XEXP (src, 0)) == PRE_DEC)
23590             {
23591               rtx delta_rtx;
23592               breg = XEXP (XEXP (src, 0), 0);
23593               delta_rtx = (GET_CODE (XEXP (src, 0)) == PRE_INC
23594                            ? GEN_INT (GET_MODE_SIZE (GET_MODE (src)))
23595                            : GEN_INT (-GET_MODE_SIZE (GET_MODE (src))));
23596               emit_insn (gen_add3_insn (breg, breg, delta_rtx));
23597               src = replace_equiv_address (src, breg);
23598             }
23599           else if (! rs6000_offsettable_memref_p (src, reg_mode, true))
23600             {
23601               if (GET_CODE (XEXP (src, 0)) == PRE_MODIFY)
23602                 {
23603                   rtx basereg = XEXP (XEXP (src, 0), 0);
23604                   if (TARGET_UPDATE)
23605                     {
23606                       rtx ndst = simplify_gen_subreg (reg_mode, dst, mode, 0);
23607                       emit_insn (gen_rtx_SET (ndst,
23608                                               gen_rtx_MEM (reg_mode,
23609                                                            XEXP (src, 0))));
23610                       used_update = true;
23611                     }
23612                   else
23613                     emit_insn (gen_rtx_SET (basereg,
23614                                             XEXP (XEXP (src, 0), 1)));
23615                   src = replace_equiv_address (src, basereg);
23616                 }
23617               else
23618                 {
23619                   rtx basereg = gen_rtx_REG (Pmode, reg);
23620                   emit_insn (gen_rtx_SET (basereg, XEXP (src, 0)));
23621                   src = replace_equiv_address (src, basereg);
23622                 }
23623             }
23624
23625           breg = XEXP (src, 0);
23626           if (GET_CODE (breg) == PLUS || GET_CODE (breg) == LO_SUM)
23627             breg = XEXP (breg, 0);
23628
23629           /* If the base register we are using to address memory is
23630              also a destination reg, then change that register last.  */
23631           if (REG_P (breg)
23632               && REGNO (breg) >= REGNO (dst)
23633               && REGNO (breg) < REGNO (dst) + nregs)
23634             j = REGNO (breg) - REGNO (dst);
23635         }
23636       else if (MEM_P (dst) && INT_REGNO_P (reg))
23637         {
23638           rtx breg;
23639
23640           if (GET_CODE (XEXP (dst, 0)) == PRE_INC
23641               || GET_CODE (XEXP (dst, 0)) == PRE_DEC)
23642             {
23643               rtx delta_rtx;
23644               breg = XEXP (XEXP (dst, 0), 0);
23645               delta_rtx = (GET_CODE (XEXP (dst, 0)) == PRE_INC
23646                            ? GEN_INT (GET_MODE_SIZE (GET_MODE (dst)))
23647                            : GEN_INT (-GET_MODE_SIZE (GET_MODE (dst))));
23648
23649               /* We have to update the breg before doing the store.
23650                  Use store with update, if available.  */
23651
23652               if (TARGET_UPDATE)
23653                 {
23654                   rtx nsrc = simplify_gen_subreg (reg_mode, src, mode, 0);
23655                   emit_insn (TARGET_32BIT
23656                              ? (TARGET_POWERPC64
23657                                 ? gen_movdi_si_update (breg, breg, delta_rtx, nsrc)
23658                                 : gen_movsi_si_update (breg, breg, delta_rtx, nsrc))
23659                              : gen_movdi_di_update (breg, breg, delta_rtx, nsrc));
23660                   used_update = true;
23661                 }
23662               else
23663                 emit_insn (gen_add3_insn (breg, breg, delta_rtx));
23664               dst = replace_equiv_address (dst, breg);
23665             }
23666           else if (!rs6000_offsettable_memref_p (dst, reg_mode, true)
23667                    && GET_CODE (XEXP (dst, 0)) != LO_SUM)
23668             {
23669               if (GET_CODE (XEXP (dst, 0)) == PRE_MODIFY)
23670                 {
23671                   rtx basereg = XEXP (XEXP (dst, 0), 0);
23672                   if (TARGET_UPDATE)
23673                     {
23674                       rtx nsrc = simplify_gen_subreg (reg_mode, src, mode, 0);
23675                       emit_insn (gen_rtx_SET (gen_rtx_MEM (reg_mode,
23676                                                            XEXP (dst, 0)),
23677                                               nsrc));
23678                       used_update = true;
23679                     }
23680                   else
23681                     emit_insn (gen_rtx_SET (basereg,
23682                                             XEXP (XEXP (dst, 0), 1)));
23683                   dst = replace_equiv_address (dst, basereg);
23684                 }
23685               else
23686                 {
23687                   rtx basereg = XEXP (XEXP (dst, 0), 0);
23688                   rtx offsetreg = XEXP (XEXP (dst, 0), 1);
23689                   gcc_assert (GET_CODE (XEXP (dst, 0)) == PLUS
23690                               && REG_P (basereg)
23691                               && REG_P (offsetreg)
23692                               && REGNO (basereg) != REGNO (offsetreg));
23693                   if (REGNO (basereg) == 0)
23694                     {
23695                       rtx tmp = offsetreg;
23696                       offsetreg = basereg;
23697                       basereg = tmp;
23698                     }
23699                   emit_insn (gen_add3_insn (basereg, basereg, offsetreg));
23700                   restore_basereg = gen_sub3_insn (basereg, basereg, offsetreg);
23701                   dst = replace_equiv_address (dst, basereg);
23702                 }
23703             }
23704           else if (GET_CODE (XEXP (dst, 0)) != LO_SUM)
23705             gcc_assert (rs6000_offsettable_memref_p (dst, reg_mode, true));
23706         }
23707
23708       for (i = 0; i < nregs; i++)
23709         {
23710           /* Calculate index to next subword.  */
23711           ++j;
23712           if (j == nregs)
23713             j = 0;
23714
23715           /* If compiler already emitted move of first word by
23716              store with update, no need to do anything.  */
23717           if (j == 0 && used_update)
23718             continue;
23719
23720           emit_insn (gen_rtx_SET (simplify_gen_subreg (reg_mode, dst, mode,
23721                                                        j * reg_mode_size),
23722                                   simplify_gen_subreg (reg_mode, src, mode,
23723                                                        j * reg_mode_size)));
23724         }
23725       if (restore_basereg != NULL_RTX)
23726         emit_insn (restore_basereg);
23727     }
23728 }
23729
23730 static GTY(()) alias_set_type set = -1;
23731
23732 alias_set_type
23733 get_TOC_alias_set (void)
23734 {
23735   if (set == -1)
23736     set = new_alias_set ();
23737   return set;
23738 }
23739
23740 /* Return the internal arg pointer used for function incoming
23741    arguments.  When -fsplit-stack, the arg pointer is r12 so we need
23742    to copy it to a pseudo in order for it to be preserved over calls
23743    and suchlike.  We'd really like to use a pseudo here for the
23744    internal arg pointer but data-flow analysis is not prepared to
23745    accept pseudos as live at the beginning of a function.  */
23746
23747 static rtx
23748 rs6000_internal_arg_pointer (void)
23749 {
23750   if (flag_split_stack
23751      && (lookup_attribute ("no_split_stack", DECL_ATTRIBUTES (cfun->decl))
23752          == NULL))
23753
23754     {
23755       if (cfun->machine->split_stack_arg_pointer == NULL_RTX)
23756         {
23757           rtx pat;
23758
23759           cfun->machine->split_stack_arg_pointer = gen_reg_rtx (Pmode);
23760           REG_POINTER (cfun->machine->split_stack_arg_pointer) = 1;
23761
23762           /* Put the pseudo initialization right after the note at the
23763              beginning of the function.  */
23764           pat = gen_rtx_SET (cfun->machine->split_stack_arg_pointer,
23765                              gen_rtx_REG (Pmode, 12));
23766           push_topmost_sequence ();
23767           emit_insn_after (pat, get_insns ());
23768           pop_topmost_sequence ();
23769         }
23770       rtx ret = plus_constant (Pmode, cfun->machine->split_stack_arg_pointer,
23771                                FIRST_PARM_OFFSET (current_function_decl));
23772       return copy_to_reg (ret);
23773     }
23774   return virtual_incoming_args_rtx;
23775 }
23776
23777 /* We may have to tell the dataflow pass that the split stack prologue
23778    is initializing a register.  */
23779
23780 static void
23781 rs6000_live_on_entry (bitmap regs)
23782 {
23783   if (flag_split_stack)
23784     bitmap_set_bit (regs, 12);
23785 }
23786
23787 \f
23788 /* A C compound statement that outputs the assembler code for a thunk
23789    function, used to implement C++ virtual function calls with
23790    multiple inheritance.  The thunk acts as a wrapper around a virtual
23791    function, adjusting the implicit object parameter before handing
23792    control off to the real function.
23793
23794    First, emit code to add the integer DELTA to the location that
23795    contains the incoming first argument.  Assume that this argument
23796    contains a pointer, and is the one used to pass the `this' pointer
23797    in C++.  This is the incoming argument *before* the function
23798    prologue, e.g. `%o0' on a sparc.  The addition must preserve the
23799    values of all other incoming arguments.
23800
23801    After the addition, emit code to jump to FUNCTION, which is a
23802    `FUNCTION_DECL'.  This is a direct pure jump, not a call, and does
23803    not touch the return address.  Hence returning from FUNCTION will
23804    return to whoever called the current `thunk'.
23805
23806    The effect must be as if FUNCTION had been called directly with the
23807    adjusted first argument.  This macro is responsible for emitting
23808    all of the code for a thunk function; output_function_prologue()
23809    and output_function_epilogue() are not invoked.
23810
23811    The THUNK_FNDECL is redundant.  (DELTA and FUNCTION have already
23812    been extracted from it.)  It might possibly be useful on some
23813    targets, but probably not.
23814
23815    If you do not define this macro, the target-independent code in the
23816    C++ frontend will generate a less efficient heavyweight thunk that
23817    calls FUNCTION instead of jumping to it.  The generic approach does
23818    not support varargs.  */
23819
23820 static void
23821 rs6000_output_mi_thunk (FILE *file, tree thunk_fndecl ATTRIBUTE_UNUSED,
23822                         HOST_WIDE_INT delta, HOST_WIDE_INT vcall_offset,
23823                         tree function)
23824 {
23825   const char *fnname = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (thunk_fndecl));
23826   rtx this_rtx, funexp;
23827   rtx_insn *insn;
23828
23829   reload_completed = 1;
23830   epilogue_completed = 1;
23831
23832   /* Mark the end of the (empty) prologue.  */
23833   emit_note (NOTE_INSN_PROLOGUE_END);
23834
23835   /* Find the "this" pointer.  If the function returns a structure,
23836      the structure return pointer is in r3.  */
23837   if (aggregate_value_p (TREE_TYPE (TREE_TYPE (function)), function))
23838     this_rtx = gen_rtx_REG (Pmode, 4);
23839   else
23840     this_rtx = gen_rtx_REG (Pmode, 3);
23841
23842   /* Apply the constant offset, if required.  */
23843   if (delta)
23844     emit_insn (gen_add3_insn (this_rtx, this_rtx, GEN_INT (delta)));
23845
23846   /* Apply the offset from the vtable, if required.  */
23847   if (vcall_offset)
23848     {
23849       rtx vcall_offset_rtx = GEN_INT (vcall_offset);
23850       rtx tmp = gen_rtx_REG (Pmode, 12);
23851
23852       emit_move_insn (tmp, gen_rtx_MEM (Pmode, this_rtx));
23853       if (((unsigned HOST_WIDE_INT) vcall_offset) + 0x8000 >= 0x10000)
23854         {
23855           emit_insn (gen_add3_insn (tmp, tmp, vcall_offset_rtx));
23856           emit_move_insn (tmp, gen_rtx_MEM (Pmode, tmp));
23857         }
23858       else
23859         {
23860           rtx loc = gen_rtx_PLUS (Pmode, tmp, vcall_offset_rtx);
23861
23862           emit_move_insn (tmp, gen_rtx_MEM (Pmode, loc));
23863         }
23864       emit_insn (gen_add3_insn (this_rtx, this_rtx, tmp));
23865     }
23866
23867   /* Generate a tail call to the target function.  */
23868   if (!TREE_USED (function))
23869     {
23870       assemble_external (function);
23871       TREE_USED (function) = 1;
23872     }
23873   funexp = XEXP (DECL_RTL (function), 0);
23874   funexp = gen_rtx_MEM (FUNCTION_MODE, funexp);
23875
23876 #if TARGET_MACHO
23877   if (MACHOPIC_INDIRECT)
23878     funexp = machopic_indirect_call_target (funexp);
23879 #endif
23880
23881   /* gen_sibcall expects reload to convert scratch pseudo to LR so we must
23882      generate sibcall RTL explicitly.  */
23883   insn = emit_call_insn (
23884            gen_rtx_PARALLEL (VOIDmode,
23885              gen_rtvec (3,
23886                         gen_rtx_CALL (VOIDmode,
23887                                       funexp, const0_rtx),
23888                         gen_rtx_USE (VOIDmode, const0_rtx),
23889                         simple_return_rtx)));
23890   SIBLING_CALL_P (insn) = 1;
23891   emit_barrier ();
23892
23893   /* Run just enough of rest_of_compilation to get the insns emitted.
23894      There's not really enough bulk here to make other passes such as
23895      instruction scheduling worth while.  */
23896   insn = get_insns ();
23897   shorten_branches (insn);
23898   assemble_start_function (thunk_fndecl, fnname);
23899   final_start_function (insn, file, 1);
23900   final (insn, file, 1);
23901   final_end_function ();
23902   assemble_end_function (thunk_fndecl, fnname);
23903
23904   reload_completed = 0;
23905   epilogue_completed = 0;
23906 }
23907 \f
23908 /* A quick summary of the various types of 'constant-pool tables'
23909    under PowerPC:
23910
23911    Target       Flags           Name            One table per
23912    AIX          (none)          AIX TOC         object file
23913    AIX          -mfull-toc      AIX TOC         object file
23914    AIX          -mminimal-toc   AIX minimal TOC translation unit
23915    SVR4/EABI    (none)          SVR4 SDATA      object file
23916    SVR4/EABI    -fpic           SVR4 pic        object file
23917    SVR4/EABI    -fPIC           SVR4 PIC        translation unit
23918    SVR4/EABI    -mrelocatable   EABI TOC        function
23919    SVR4/EABI    -maix           AIX TOC         object file
23920    SVR4/EABI    -maix -mminimal-toc
23921                                 AIX minimal TOC translation unit
23922
23923    Name                 Reg.    Set by  entries       contains:
23924                                         made by  addrs? fp?     sum?
23925
23926    AIX TOC              2       crt0    as       Y      option  option
23927    AIX minimal TOC      30      prolog  gcc      Y      Y       option
23928    SVR4 SDATA           13      crt0    gcc      N      Y       N
23929    SVR4 pic             30      prolog  ld       Y      not yet N
23930    SVR4 PIC             30      prolog  gcc      Y      option  option
23931    EABI TOC             30      prolog  gcc      Y      option  option
23932
23933 */
23934
23935 /* Hash functions for the hash table.  */
23936
23937 static unsigned
23938 rs6000_hash_constant (rtx k)
23939 {
23940   enum rtx_code code = GET_CODE (k);
23941   machine_mode mode = GET_MODE (k);
23942   unsigned result = (code << 3) ^ mode;
23943   const char *format;
23944   int flen, fidx;
23945
23946   format = GET_RTX_FORMAT (code);
23947   flen = strlen (format);
23948   fidx = 0;
23949
23950   switch (code)
23951     {
23952     case LABEL_REF:
23953       return result * 1231 + (unsigned) INSN_UID (XEXP (k, 0));
23954
23955     case CONST_WIDE_INT:
23956       {
23957         int i;
23958         flen = CONST_WIDE_INT_NUNITS (k);
23959         for (i = 0; i < flen; i++)
23960           result = result * 613 + CONST_WIDE_INT_ELT (k, i);
23961         return result;
23962       }
23963
23964     case CONST_DOUBLE:
23965       return real_hash (CONST_DOUBLE_REAL_VALUE (k)) * result;
23966
23967     case CODE_LABEL:
23968       fidx = 3;
23969       break;
23970
23971     default:
23972       break;
23973     }
23974
23975   for (; fidx < flen; fidx++)
23976     switch (format[fidx])
23977       {
23978       case 's':
23979         {
23980           unsigned i, len;
23981           const char *str = XSTR (k, fidx);
23982           len = strlen (str);
23983           result = result * 613 + len;
23984           for (i = 0; i < len; i++)
23985             result = result * 613 + (unsigned) str[i];
23986           break;
23987         }
23988       case 'u':
23989       case 'e':
23990         result = result * 1231 + rs6000_hash_constant (XEXP (k, fidx));
23991         break;
23992       case 'i':
23993       case 'n':
23994         result = result * 613 + (unsigned) XINT (k, fidx);
23995         break;
23996       case 'w':
23997         if (sizeof (unsigned) >= sizeof (HOST_WIDE_INT))
23998           result = result * 613 + (unsigned) XWINT (k, fidx);
23999         else
24000           {
24001             size_t i;
24002             for (i = 0; i < sizeof (HOST_WIDE_INT) / sizeof (unsigned); i++)
24003               result = result * 613 + (unsigned) (XWINT (k, fidx)
24004                                                   >> CHAR_BIT * i);
24005           }
24006         break;
24007       case '0':
24008         break;
24009       default:
24010         gcc_unreachable ();
24011       }
24012
24013   return result;
24014 }
24015
24016 hashval_t
24017 toc_hasher::hash (toc_hash_struct *thc)
24018 {
24019   return rs6000_hash_constant (thc->key) ^ thc->key_mode;
24020 }
24021
24022 /* Compare H1 and H2 for equivalence.  */
24023
24024 bool
24025 toc_hasher::equal (toc_hash_struct *h1, toc_hash_struct *h2)
24026 {
24027   rtx r1 = h1->key;
24028   rtx r2 = h2->key;
24029
24030   if (h1->key_mode != h2->key_mode)
24031     return 0;
24032
24033   return rtx_equal_p (r1, r2);
24034 }
24035
24036 /* These are the names given by the C++ front-end to vtables, and
24037    vtable-like objects.  Ideally, this logic should not be here;
24038    instead, there should be some programmatic way of inquiring as
24039    to whether or not an object is a vtable.  */
24040
24041 #define VTABLE_NAME_P(NAME)                             \
24042   (strncmp ("_vt.", name, strlen ("_vt.")) == 0         \
24043   || strncmp ("_ZTV", name, strlen ("_ZTV")) == 0       \
24044   || strncmp ("_ZTT", name, strlen ("_ZTT")) == 0       \
24045   || strncmp ("_ZTI", name, strlen ("_ZTI")) == 0       \
24046   || strncmp ("_ZTC", name, strlen ("_ZTC")) == 0)
24047
24048 #ifdef NO_DOLLAR_IN_LABEL
24049 /* Return a GGC-allocated character string translating dollar signs in
24050    input NAME to underscores.  Used by XCOFF ASM_OUTPUT_LABELREF.  */
24051
24052 const char *
24053 rs6000_xcoff_strip_dollar (const char *name)
24054 {
24055   char *strip, *p;
24056   const char *q;
24057   size_t len;
24058
24059   q = (const char *) strchr (name, '$');
24060
24061   if (q == 0 || q == name)
24062     return name;
24063
24064   len = strlen (name);
24065   strip = XALLOCAVEC (char, len + 1);
24066   strcpy (strip, name);
24067   p = strip + (q - name);
24068   while (p)
24069     {
24070       *p = '_';
24071       p = strchr (p + 1, '$');
24072     }
24073
24074   return ggc_alloc_string (strip, len);
24075 }
24076 #endif
24077
24078 void
24079 rs6000_output_symbol_ref (FILE *file, rtx x)
24080 {
24081   const char *name = XSTR (x, 0);
24082
24083   /* Currently C++ toc references to vtables can be emitted before it
24084      is decided whether the vtable is public or private.  If this is
24085      the case, then the linker will eventually complain that there is
24086      a reference to an unknown section.  Thus, for vtables only,
24087      we emit the TOC reference to reference the identifier and not the
24088      symbol.  */
24089   if (VTABLE_NAME_P (name))
24090     {
24091       RS6000_OUTPUT_BASENAME (file, name);
24092     }
24093   else
24094     assemble_name (file, name);
24095 }
24096
24097 /* Output a TOC entry.  We derive the entry name from what is being
24098    written.  */
24099
24100 void
24101 output_toc (FILE *file, rtx x, int labelno, machine_mode mode)
24102 {
24103   char buf[256];
24104   const char *name = buf;
24105   rtx base = x;
24106   HOST_WIDE_INT offset = 0;
24107
24108   gcc_assert (!TARGET_NO_TOC);
24109
24110   /* When the linker won't eliminate them, don't output duplicate
24111      TOC entries (this happens on AIX if there is any kind of TOC,
24112      and on SVR4 under -fPIC or -mrelocatable).  Don't do this for
24113      CODE_LABELs.  */
24114   if (TARGET_TOC && GET_CODE (x) != LABEL_REF)
24115     {
24116       struct toc_hash_struct *h;
24117
24118       /* Create toc_hash_table.  This can't be done at TARGET_OPTION_OVERRIDE
24119          time because GGC is not initialized at that point.  */
24120       if (toc_hash_table == NULL)
24121         toc_hash_table = hash_table<toc_hasher>::create_ggc (1021);
24122
24123       h = ggc_alloc<toc_hash_struct> ();
24124       h->key = x;
24125       h->key_mode = mode;
24126       h->labelno = labelno;
24127
24128       toc_hash_struct **found = toc_hash_table->find_slot (h, INSERT);
24129       if (*found == NULL)
24130         *found = h;
24131       else  /* This is indeed a duplicate.
24132                Set this label equal to that label.  */
24133         {
24134           fputs ("\t.set ", file);
24135           ASM_OUTPUT_INTERNAL_LABEL_PREFIX (file, "LC");
24136           fprintf (file, "%d,", labelno);
24137           ASM_OUTPUT_INTERNAL_LABEL_PREFIX (file, "LC");
24138           fprintf (file, "%d\n", ((*found)->labelno));
24139
24140 #ifdef HAVE_AS_TLS
24141           if (TARGET_XCOFF && SYMBOL_REF_P (x)
24142               && (SYMBOL_REF_TLS_MODEL (x) == TLS_MODEL_GLOBAL_DYNAMIC
24143                   || SYMBOL_REF_TLS_MODEL (x) == TLS_MODEL_LOCAL_DYNAMIC))
24144             {
24145               fputs ("\t.set ", file);
24146               ASM_OUTPUT_INTERNAL_LABEL_PREFIX (file, "LCM");
24147               fprintf (file, "%d,", labelno);
24148               ASM_OUTPUT_INTERNAL_LABEL_PREFIX (file, "LCM");
24149               fprintf (file, "%d\n", ((*found)->labelno));
24150             }
24151 #endif
24152           return;
24153         }
24154     }
24155
24156   /* If we're going to put a double constant in the TOC, make sure it's
24157      aligned properly when strict alignment is on.  */
24158   if ((CONST_DOUBLE_P (x) || CONST_WIDE_INT_P (x))
24159       && STRICT_ALIGNMENT
24160       && GET_MODE_BITSIZE (mode) >= 64
24161       && ! (TARGET_NO_FP_IN_TOC && ! TARGET_MINIMAL_TOC)) {
24162     ASM_OUTPUT_ALIGN (file, 3);
24163   }
24164
24165   (*targetm.asm_out.internal_label) (file, "LC", labelno);
24166
24167   /* Handle FP constants specially.  Note that if we have a minimal
24168      TOC, things we put here aren't actually in the TOC, so we can allow
24169      FP constants.  */
24170   if (CONST_DOUBLE_P (x)
24171       && (GET_MODE (x) == TFmode || GET_MODE (x) == TDmode
24172           || GET_MODE (x) == IFmode || GET_MODE (x) == KFmode))
24173     {
24174       long k[4];
24175
24176       if (DECIMAL_FLOAT_MODE_P (GET_MODE (x)))
24177         REAL_VALUE_TO_TARGET_DECIMAL128 (*CONST_DOUBLE_REAL_VALUE (x), k);
24178       else
24179         REAL_VALUE_TO_TARGET_LONG_DOUBLE (*CONST_DOUBLE_REAL_VALUE (x), k);
24180
24181       if (TARGET_64BIT)
24182         {
24183           if (TARGET_ELF || TARGET_MINIMAL_TOC)
24184             fputs (DOUBLE_INT_ASM_OP, file);
24185           else
24186             fprintf (file, "\t.tc FT_%lx_%lx_%lx_%lx[TC],",
24187                      k[0] & 0xffffffff, k[1] & 0xffffffff,
24188                      k[2] & 0xffffffff, k[3] & 0xffffffff);
24189           fprintf (file, "0x%lx%08lx,0x%lx%08lx\n",
24190                    k[WORDS_BIG_ENDIAN ? 0 : 1] & 0xffffffff,
24191                    k[WORDS_BIG_ENDIAN ? 1 : 0] & 0xffffffff,
24192                    k[WORDS_BIG_ENDIAN ? 2 : 3] & 0xffffffff,
24193                    k[WORDS_BIG_ENDIAN ? 3 : 2] & 0xffffffff);
24194           return;
24195         }
24196       else
24197         {
24198           if (TARGET_ELF || TARGET_MINIMAL_TOC)
24199             fputs ("\t.long ", file);
24200           else
24201             fprintf (file, "\t.tc FT_%lx_%lx_%lx_%lx[TC],",
24202                      k[0] & 0xffffffff, k[1] & 0xffffffff,
24203                      k[2] & 0xffffffff, k[3] & 0xffffffff);
24204           fprintf (file, "0x%lx,0x%lx,0x%lx,0x%lx\n",
24205                    k[0] & 0xffffffff, k[1] & 0xffffffff,
24206                    k[2] & 0xffffffff, k[3] & 0xffffffff);
24207           return;
24208         }
24209     }
24210   else if (CONST_DOUBLE_P (x)
24211            && (GET_MODE (x) == DFmode || GET_MODE (x) == DDmode))
24212     {
24213       long k[2];
24214
24215       if (DECIMAL_FLOAT_MODE_P (GET_MODE (x)))
24216         REAL_VALUE_TO_TARGET_DECIMAL64 (*CONST_DOUBLE_REAL_VALUE (x), k);
24217       else
24218         REAL_VALUE_TO_TARGET_DOUBLE (*CONST_DOUBLE_REAL_VALUE (x), k);
24219
24220       if (TARGET_64BIT)
24221         {
24222           if (TARGET_ELF || TARGET_MINIMAL_TOC)
24223             fputs (DOUBLE_INT_ASM_OP, file);
24224           else
24225             fprintf (file, "\t.tc FD_%lx_%lx[TC],",
24226                      k[0] & 0xffffffff, k[1] & 0xffffffff);
24227           fprintf (file, "0x%lx%08lx\n",
24228                    k[WORDS_BIG_ENDIAN ? 0 : 1] & 0xffffffff,
24229                    k[WORDS_BIG_ENDIAN ? 1 : 0] & 0xffffffff);
24230           return;
24231         }
24232       else
24233         {
24234           if (TARGET_ELF || TARGET_MINIMAL_TOC)
24235             fputs ("\t.long ", file);
24236           else
24237             fprintf (file, "\t.tc FD_%lx_%lx[TC],",
24238                      k[0] & 0xffffffff, k[1] & 0xffffffff);
24239           fprintf (file, "0x%lx,0x%lx\n",
24240                    k[0] & 0xffffffff, k[1] & 0xffffffff);
24241           return;
24242         }
24243     }
24244   else if (CONST_DOUBLE_P (x)
24245            && (GET_MODE (x) == SFmode || GET_MODE (x) == SDmode))
24246     {
24247       long l;
24248
24249       if (DECIMAL_FLOAT_MODE_P (GET_MODE (x)))
24250         REAL_VALUE_TO_TARGET_DECIMAL32 (*CONST_DOUBLE_REAL_VALUE (x), l);
24251       else
24252         REAL_VALUE_TO_TARGET_SINGLE (*CONST_DOUBLE_REAL_VALUE (x), l);
24253
24254       if (TARGET_64BIT)
24255         {
24256           if (TARGET_ELF || TARGET_MINIMAL_TOC)
24257             fputs (DOUBLE_INT_ASM_OP, file);
24258           else
24259             fprintf (file, "\t.tc FS_%lx[TC],", l & 0xffffffff);
24260           if (WORDS_BIG_ENDIAN)
24261             fprintf (file, "0x%lx00000000\n", l & 0xffffffff);
24262           else
24263             fprintf (file, "0x%lx\n", l & 0xffffffff);
24264           return;
24265         }
24266       else
24267         {
24268           if (TARGET_ELF || TARGET_MINIMAL_TOC)
24269             fputs ("\t.long ", file);
24270           else
24271             fprintf (file, "\t.tc FS_%lx[TC],", l & 0xffffffff);
24272           fprintf (file, "0x%lx\n", l & 0xffffffff);
24273           return;
24274         }
24275     }
24276   else if (GET_MODE (x) == VOIDmode && CONST_INT_P (x))
24277     {
24278       unsigned HOST_WIDE_INT low;
24279       HOST_WIDE_INT high;
24280
24281       low = INTVAL (x) & 0xffffffff;
24282       high = (HOST_WIDE_INT) INTVAL (x) >> 32;
24283
24284       /* TOC entries are always Pmode-sized, so when big-endian
24285          smaller integer constants in the TOC need to be padded.
24286          (This is still a win over putting the constants in
24287          a separate constant pool, because then we'd have
24288          to have both a TOC entry _and_ the actual constant.)
24289
24290          For a 32-bit target, CONST_INT values are loaded and shifted
24291          entirely within `low' and can be stored in one TOC entry.  */
24292
24293       /* It would be easy to make this work, but it doesn't now.  */
24294       gcc_assert (!TARGET_64BIT || POINTER_SIZE >= GET_MODE_BITSIZE (mode));
24295
24296       if (WORDS_BIG_ENDIAN && POINTER_SIZE > GET_MODE_BITSIZE (mode))
24297         {
24298           low |= high << 32;
24299           low <<= POINTER_SIZE - GET_MODE_BITSIZE (mode);
24300           high = (HOST_WIDE_INT) low >> 32;
24301           low &= 0xffffffff;
24302         }
24303
24304       if (TARGET_64BIT)
24305         {
24306           if (TARGET_ELF || TARGET_MINIMAL_TOC)
24307             fputs (DOUBLE_INT_ASM_OP, file);
24308           else
24309             fprintf (file, "\t.tc ID_%lx_%lx[TC],",
24310                      (long) high & 0xffffffff, (long) low & 0xffffffff);
24311           fprintf (file, "0x%lx%08lx\n",
24312                    (long) high & 0xffffffff, (long) low & 0xffffffff);
24313           return;
24314         }
24315       else
24316         {
24317           if (POINTER_SIZE < GET_MODE_BITSIZE (mode))
24318             {
24319               if (TARGET_ELF || TARGET_MINIMAL_TOC)
24320                 fputs ("\t.long ", file);
24321               else
24322                 fprintf (file, "\t.tc ID_%lx_%lx[TC],",
24323                          (long) high & 0xffffffff, (long) low & 0xffffffff);
24324               fprintf (file, "0x%lx,0x%lx\n",
24325                        (long) high & 0xffffffff, (long) low & 0xffffffff);
24326             }
24327           else
24328             {
24329               if (TARGET_ELF || TARGET_MINIMAL_TOC)
24330                 fputs ("\t.long ", file);
24331               else
24332                 fprintf (file, "\t.tc IS_%lx[TC],", (long) low & 0xffffffff);
24333               fprintf (file, "0x%lx\n", (long) low & 0xffffffff);
24334             }
24335           return;
24336         }
24337     }
24338
24339   if (GET_CODE (x) == CONST)
24340     {
24341       gcc_assert (GET_CODE (XEXP (x, 0)) == PLUS
24342                   && CONST_INT_P (XEXP (XEXP (x, 0), 1)));
24343
24344       base = XEXP (XEXP (x, 0), 0);
24345       offset = INTVAL (XEXP (XEXP (x, 0), 1));
24346     }
24347
24348   switch (GET_CODE (base))
24349     {
24350     case SYMBOL_REF:
24351       name = XSTR (base, 0);
24352       break;
24353
24354     case LABEL_REF:
24355       ASM_GENERATE_INTERNAL_LABEL (buf, "L",
24356                                    CODE_LABEL_NUMBER (XEXP (base, 0)));
24357       break;
24358
24359     case CODE_LABEL:
24360       ASM_GENERATE_INTERNAL_LABEL (buf, "L", CODE_LABEL_NUMBER (base));
24361       break;
24362
24363     default:
24364       gcc_unreachable ();
24365     }
24366
24367   if (TARGET_ELF || TARGET_MINIMAL_TOC)
24368     fputs (TARGET_32BIT ? "\t.long " : DOUBLE_INT_ASM_OP, file);
24369   else
24370     {
24371       fputs ("\t.tc ", file);
24372       RS6000_OUTPUT_BASENAME (file, name);
24373
24374       if (offset < 0)
24375         fprintf (file, ".N" HOST_WIDE_INT_PRINT_UNSIGNED, - offset);
24376       else if (offset)
24377         fprintf (file, ".P" HOST_WIDE_INT_PRINT_UNSIGNED, offset);
24378
24379       /* Mark large TOC symbols on AIX with [TE] so they are mapped
24380          after other TOC symbols, reducing overflow of small TOC access
24381          to [TC] symbols.  */
24382       fputs (TARGET_XCOFF && TARGET_CMODEL != CMODEL_SMALL
24383              ? "[TE]," : "[TC],", file);
24384     }
24385
24386   /* Currently C++ toc references to vtables can be emitted before it
24387      is decided whether the vtable is public or private.  If this is
24388      the case, then the linker will eventually complain that there is
24389      a TOC reference to an unknown section.  Thus, for vtables only,
24390      we emit the TOC reference to reference the symbol and not the
24391      section.  */
24392   if (VTABLE_NAME_P (name))
24393     {
24394       RS6000_OUTPUT_BASENAME (file, name);
24395       if (offset < 0)
24396         fprintf (file, HOST_WIDE_INT_PRINT_DEC, offset);
24397       else if (offset > 0)
24398         fprintf (file, "+" HOST_WIDE_INT_PRINT_DEC, offset);
24399     }
24400   else
24401     output_addr_const (file, x);
24402
24403 #if HAVE_AS_TLS
24404   if (TARGET_XCOFF && SYMBOL_REF_P (base))
24405     {
24406       switch (SYMBOL_REF_TLS_MODEL (base))
24407         {
24408         case 0:
24409           break;
24410         case TLS_MODEL_LOCAL_EXEC:
24411           fputs ("@le", file);
24412           break;
24413         case TLS_MODEL_INITIAL_EXEC:
24414           fputs ("@ie", file);
24415           break;
24416         /* Use global-dynamic for local-dynamic.  */
24417         case TLS_MODEL_GLOBAL_DYNAMIC:
24418         case TLS_MODEL_LOCAL_DYNAMIC:
24419           putc ('\n', file);
24420           (*targetm.asm_out.internal_label) (file, "LCM", labelno);
24421           fputs ("\t.tc .", file);
24422           RS6000_OUTPUT_BASENAME (file, name);
24423           fputs ("[TC],", file);
24424           output_addr_const (file, x);
24425           fputs ("@m", file);
24426           break;
24427         default:
24428           gcc_unreachable ();
24429         }
24430     }
24431 #endif
24432
24433   putc ('\n', file);
24434 }
24435 \f
24436 /* Output an assembler pseudo-op to write an ASCII string of N characters
24437    starting at P to FILE.
24438
24439    On the RS/6000, we have to do this using the .byte operation and
24440    write out special characters outside the quoted string.
24441    Also, the assembler is broken; very long strings are truncated,
24442    so we must artificially break them up early.  */
24443
24444 void
24445 output_ascii (FILE *file, const char *p, int n)
24446 {
24447   char c;
24448   int i, count_string;
24449   const char *for_string = "\t.byte \"";
24450   const char *for_decimal = "\t.byte ";
24451   const char *to_close = NULL;
24452
24453   count_string = 0;
24454   for (i = 0; i < n; i++)
24455     {
24456       c = *p++;
24457       if (c >= ' ' && c < 0177)
24458         {
24459           if (for_string)
24460             fputs (for_string, file);
24461           putc (c, file);
24462
24463           /* Write two quotes to get one.  */
24464           if (c == '"')
24465             {
24466               putc (c, file);
24467               ++count_string;
24468             }
24469
24470           for_string = NULL;
24471           for_decimal = "\"\n\t.byte ";
24472           to_close = "\"\n";
24473           ++count_string;
24474
24475           if (count_string >= 512)
24476             {
24477               fputs (to_close, file);
24478
24479               for_string = "\t.byte \"";
24480               for_decimal = "\t.byte ";
24481               to_close = NULL;
24482               count_string = 0;
24483             }
24484         }
24485       else
24486         {
24487           if (for_decimal)
24488             fputs (for_decimal, file);
24489           fprintf (file, "%d", c);
24490
24491           for_string = "\n\t.byte \"";
24492           for_decimal = ", ";
24493           to_close = "\n";
24494           count_string = 0;
24495         }
24496     }
24497
24498   /* Now close the string if we have written one.  Then end the line.  */
24499   if (to_close)
24500     fputs (to_close, file);
24501 }
24502 \f
24503 /* Generate a unique section name for FILENAME for a section type
24504    represented by SECTION_DESC.  Output goes into BUF.
24505
24506    SECTION_DESC can be any string, as long as it is different for each
24507    possible section type.
24508
24509    We name the section in the same manner as xlc.  The name begins with an
24510    underscore followed by the filename (after stripping any leading directory
24511    names) with the last period replaced by the string SECTION_DESC.  If
24512    FILENAME does not contain a period, SECTION_DESC is appended to the end of
24513    the name.  */
24514
24515 void
24516 rs6000_gen_section_name (char **buf, const char *filename,
24517                          const char *section_desc)
24518 {
24519   const char *q, *after_last_slash, *last_period = 0;
24520   char *p;
24521   int len;
24522
24523   after_last_slash = filename;
24524   for (q = filename; *q; q++)
24525     {
24526       if (*q == '/')
24527         after_last_slash = q + 1;
24528       else if (*q == '.')
24529         last_period = q;
24530     }
24531
24532   len = strlen (after_last_slash) + strlen (section_desc) + 2;
24533   *buf = (char *) xmalloc (len);
24534
24535   p = *buf;
24536   *p++ = '_';
24537
24538   for (q = after_last_slash; *q; q++)
24539     {
24540       if (q == last_period)
24541         {
24542           strcpy (p, section_desc);
24543           p += strlen (section_desc);
24544           break;
24545         }
24546
24547       else if (ISALNUM (*q))
24548         *p++ = *q;
24549     }
24550
24551   if (last_period == 0)
24552     strcpy (p, section_desc);
24553   else
24554     *p = '\0';
24555 }
24556 \f
24557 /* Emit profile function.  */
24558
24559 void
24560 output_profile_hook (int labelno ATTRIBUTE_UNUSED)
24561 {
24562   /* Non-standard profiling for kernels, which just saves LR then calls
24563      _mcount without worrying about arg saves.  The idea is to change
24564      the function prologue as little as possible as it isn't easy to
24565      account for arg save/restore code added just for _mcount.  */
24566   if (TARGET_PROFILE_KERNEL)
24567     return;
24568
24569   if (DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
24570     {
24571 #ifndef NO_PROFILE_COUNTERS
24572 # define NO_PROFILE_COUNTERS 0
24573 #endif
24574       if (NO_PROFILE_COUNTERS)
24575         emit_library_call (init_one_libfunc (RS6000_MCOUNT),
24576                            LCT_NORMAL, VOIDmode);
24577       else
24578         {
24579           char buf[30];
24580           const char *label_name;
24581           rtx fun;
24582
24583           ASM_GENERATE_INTERNAL_LABEL (buf, "LP", labelno);
24584           label_name = ggc_strdup ((*targetm.strip_name_encoding) (buf));
24585           fun = gen_rtx_SYMBOL_REF (Pmode, label_name);
24586
24587           emit_library_call (init_one_libfunc (RS6000_MCOUNT),
24588                              LCT_NORMAL, VOIDmode, fun, Pmode);
24589         }
24590     }
24591   else if (DEFAULT_ABI == ABI_DARWIN)
24592     {
24593       const char *mcount_name = RS6000_MCOUNT;
24594       int caller_addr_regno = LR_REGNO;
24595
24596       /* Be conservative and always set this, at least for now.  */
24597       crtl->uses_pic_offset_table = 1;
24598
24599 #if TARGET_MACHO
24600       /* For PIC code, set up a stub and collect the caller's address
24601          from r0, which is where the prologue puts it.  */
24602       if (MACHOPIC_INDIRECT
24603           && crtl->uses_pic_offset_table)
24604         caller_addr_regno = 0;
24605 #endif
24606       emit_library_call (gen_rtx_SYMBOL_REF (Pmode, mcount_name),
24607                          LCT_NORMAL, VOIDmode,
24608                          gen_rtx_REG (Pmode, caller_addr_regno), Pmode);
24609     }
24610 }
24611
24612 /* Write function profiler code.  */
24613
24614 void
24615 output_function_profiler (FILE *file, int labelno)
24616 {
24617   char buf[100];
24618
24619   switch (DEFAULT_ABI)
24620     {
24621     default:
24622       gcc_unreachable ();
24623
24624     case ABI_V4:
24625       if (!TARGET_32BIT)
24626         {
24627           warning (0, "no profiling of 64-bit code for this ABI");
24628           return;
24629         }
24630       ASM_GENERATE_INTERNAL_LABEL (buf, "LP", labelno);
24631       fprintf (file, "\tmflr %s\n", reg_names[0]);
24632       if (NO_PROFILE_COUNTERS)
24633         {
24634           asm_fprintf (file, "\tstw %s,4(%s)\n",
24635                        reg_names[0], reg_names[1]);
24636         }
24637       else if (TARGET_SECURE_PLT && flag_pic)
24638         {
24639           if (TARGET_LINK_STACK)
24640             {
24641               char name[32];
24642               get_ppc476_thunk_name (name);
24643               asm_fprintf (file, "\tbl %s\n", name);
24644             }
24645           else
24646             asm_fprintf (file, "\tbcl 20,31,1f\n1:\n");
24647           asm_fprintf (file, "\tstw %s,4(%s)\n",
24648                        reg_names[0], reg_names[1]);
24649           asm_fprintf (file, "\tmflr %s\n", reg_names[12]);
24650           asm_fprintf (file, "\taddis %s,%s,",
24651                        reg_names[12], reg_names[12]);
24652           assemble_name (file, buf);
24653           asm_fprintf (file, "-1b@ha\n\tla %s,", reg_names[0]);
24654           assemble_name (file, buf);
24655           asm_fprintf (file, "-1b@l(%s)\n", reg_names[12]);
24656         }
24657       else if (flag_pic == 1)
24658         {
24659           fputs ("\tbl _GLOBAL_OFFSET_TABLE_@local-4\n", file);
24660           asm_fprintf (file, "\tstw %s,4(%s)\n",
24661                        reg_names[0], reg_names[1]);
24662           asm_fprintf (file, "\tmflr %s\n", reg_names[12]);
24663           asm_fprintf (file, "\tlwz %s,", reg_names[0]);
24664           assemble_name (file, buf);
24665           asm_fprintf (file, "@got(%s)\n", reg_names[12]);
24666         }
24667       else if (flag_pic > 1)
24668         {
24669           asm_fprintf (file, "\tstw %s,4(%s)\n",
24670                        reg_names[0], reg_names[1]);
24671           /* Now, we need to get the address of the label.  */
24672           if (TARGET_LINK_STACK)
24673             {
24674               char name[32];
24675               get_ppc476_thunk_name (name);
24676               asm_fprintf (file, "\tbl %s\n\tb 1f\n\t.long ", name);
24677               assemble_name (file, buf);
24678               fputs ("-.\n1:", file);
24679               asm_fprintf (file, "\tmflr %s\n", reg_names[11]);
24680               asm_fprintf (file, "\taddi %s,%s,4\n",
24681                            reg_names[11], reg_names[11]);
24682             }
24683           else
24684             {
24685               fputs ("\tbcl 20,31,1f\n\t.long ", file);
24686               assemble_name (file, buf);
24687               fputs ("-.\n1:", file);
24688               asm_fprintf (file, "\tmflr %s\n", reg_names[11]);
24689             }
24690           asm_fprintf (file, "\tlwz %s,0(%s)\n",
24691                        reg_names[0], reg_names[11]);
24692           asm_fprintf (file, "\tadd %s,%s,%s\n",
24693                        reg_names[0], reg_names[0], reg_names[11]);
24694         }
24695       else
24696         {
24697           asm_fprintf (file, "\tlis %s,", reg_names[12]);
24698           assemble_name (file, buf);
24699           fputs ("@ha\n", file);
24700           asm_fprintf (file, "\tstw %s,4(%s)\n",
24701                        reg_names[0], reg_names[1]);
24702           asm_fprintf (file, "\tla %s,", reg_names[0]);
24703           assemble_name (file, buf);
24704           asm_fprintf (file, "@l(%s)\n", reg_names[12]);
24705         }
24706
24707       /* ABI_V4 saves the static chain reg with ASM_OUTPUT_REG_PUSH.  */
24708       fprintf (file, "\tbl %s%s\n",
24709                RS6000_MCOUNT, flag_pic ? "@plt" : "");
24710       break;
24711
24712     case ABI_AIX:
24713     case ABI_ELFv2:
24714     case ABI_DARWIN:
24715       /* Don't do anything, done in output_profile_hook ().  */
24716       break;
24717     }
24718 }
24719
24720 \f
24721
24722 /* The following variable value is the last issued insn.  */
24723
24724 static rtx_insn *last_scheduled_insn;
24725
24726 /* The following variable helps to balance issuing of load and
24727    store instructions */
24728
24729 static int load_store_pendulum;
24730
24731 /* The following variable helps pair divide insns during scheduling.  */
24732 static int divide_cnt;
24733 /* The following variable helps pair and alternate vector and vector load
24734    insns during scheduling.  */
24735 static int vec_pairing;
24736
24737
24738 /* Power4 load update and store update instructions are cracked into a
24739    load or store and an integer insn which are executed in the same cycle.
24740    Branches have their own dispatch slot which does not count against the
24741    GCC issue rate, but it changes the program flow so there are no other
24742    instructions to issue in this cycle.  */
24743
24744 static int
24745 rs6000_variable_issue_1 (rtx_insn *insn, int more)
24746 {
24747   last_scheduled_insn = insn;
24748   if (GET_CODE (PATTERN (insn)) == USE
24749       || GET_CODE (PATTERN (insn)) == CLOBBER)
24750     {
24751       cached_can_issue_more = more;
24752       return cached_can_issue_more;
24753     }
24754
24755   if (insn_terminates_group_p (insn, current_group))
24756     {
24757       cached_can_issue_more = 0;
24758       return cached_can_issue_more;
24759     }
24760
24761   /* If no reservation, but reach here */
24762   if (recog_memoized (insn) < 0)
24763     return more;
24764
24765   if (rs6000_sched_groups)
24766     {
24767       if (is_microcoded_insn (insn))
24768         cached_can_issue_more = 0;
24769       else if (is_cracked_insn (insn))
24770         cached_can_issue_more = more > 2 ? more - 2 : 0;
24771       else
24772         cached_can_issue_more = more - 1;
24773
24774       return cached_can_issue_more;
24775     }
24776
24777   if (rs6000_tune == PROCESSOR_CELL && is_nonpipeline_insn (insn))
24778     return 0;
24779
24780   cached_can_issue_more = more - 1;
24781   return cached_can_issue_more;
24782 }
24783
24784 static int
24785 rs6000_variable_issue (FILE *stream, int verbose, rtx_insn *insn, int more)
24786 {
24787   int r = rs6000_variable_issue_1 (insn, more);
24788   if (verbose)
24789     fprintf (stream, "// rs6000_variable_issue (more = %d) = %d\n", more, r);
24790   return r;
24791 }
24792
24793 /* Adjust the cost of a scheduling dependency.  Return the new cost of
24794    a dependency LINK or INSN on DEP_INSN.  COST is the current cost.  */
24795
24796 static int
24797 rs6000_adjust_cost (rtx_insn *insn, int dep_type, rtx_insn *dep_insn, int cost,
24798                     unsigned int)
24799 {
24800   enum attr_type attr_type;
24801
24802   if (recog_memoized (insn) < 0 || recog_memoized (dep_insn) < 0)
24803     return cost;
24804
24805   switch (dep_type)
24806     {
24807     case REG_DEP_TRUE:
24808       {
24809         /* Data dependency; DEP_INSN writes a register that INSN reads
24810            some cycles later.  */
24811
24812         /* Separate a load from a narrower, dependent store.  */
24813         if ((rs6000_sched_groups || rs6000_tune == PROCESSOR_POWER9
24814              || rs6000_tune == PROCESSOR_FUTURE)
24815             && GET_CODE (PATTERN (insn)) == SET
24816             && GET_CODE (PATTERN (dep_insn)) == SET
24817             && MEM_P (XEXP (PATTERN (insn), 1))
24818             && MEM_P (XEXP (PATTERN (dep_insn), 0))
24819             && (GET_MODE_SIZE (GET_MODE (XEXP (PATTERN (insn), 1)))
24820                 > GET_MODE_SIZE (GET_MODE (XEXP (PATTERN (dep_insn), 0)))))
24821           return cost + 14;
24822
24823         attr_type = get_attr_type (insn);
24824
24825         switch (attr_type)
24826           {
24827           case TYPE_JMPREG:
24828             /* Tell the first scheduling pass about the latency between
24829                a mtctr and bctr (and mtlr and br/blr).  The first
24830                scheduling pass will not know about this latency since
24831                the mtctr instruction, which has the latency associated
24832                to it, will be generated by reload.  */
24833             return 4;
24834           case TYPE_BRANCH:
24835             /* Leave some extra cycles between a compare and its
24836                dependent branch, to inhibit expensive mispredicts.  */
24837             if ((rs6000_tune == PROCESSOR_PPC603
24838                  || rs6000_tune == PROCESSOR_PPC604
24839                  || rs6000_tune == PROCESSOR_PPC604e
24840                  || rs6000_tune == PROCESSOR_PPC620
24841                  || rs6000_tune == PROCESSOR_PPC630
24842                  || rs6000_tune == PROCESSOR_PPC750
24843                  || rs6000_tune == PROCESSOR_PPC7400
24844                  || rs6000_tune == PROCESSOR_PPC7450
24845                  || rs6000_tune == PROCESSOR_PPCE5500
24846                  || rs6000_tune == PROCESSOR_PPCE6500
24847                  || rs6000_tune == PROCESSOR_POWER4
24848                  || rs6000_tune == PROCESSOR_POWER5
24849                  || rs6000_tune == PROCESSOR_POWER7
24850                  || rs6000_tune == PROCESSOR_POWER8
24851                  || rs6000_tune == PROCESSOR_POWER9
24852                  || rs6000_tune == PROCESSOR_FUTURE
24853                  || rs6000_tune == PROCESSOR_CELL)
24854                 && recog_memoized (dep_insn)
24855                 && (INSN_CODE (dep_insn) >= 0))
24856
24857               switch (get_attr_type (dep_insn))
24858                 {
24859                 case TYPE_CMP:
24860                 case TYPE_FPCOMPARE:
24861                 case TYPE_CR_LOGICAL:
24862                   return cost + 2;
24863                 case TYPE_EXTS:
24864                 case TYPE_MUL:
24865                   if (get_attr_dot (dep_insn) == DOT_YES)
24866                     return cost + 2;
24867                   else
24868                     break;
24869                 case TYPE_SHIFT:
24870                   if (get_attr_dot (dep_insn) == DOT_YES
24871                       && get_attr_var_shift (dep_insn) == VAR_SHIFT_NO)
24872                     return cost + 2;
24873                   else
24874                     break;
24875                 default:
24876                   break;
24877                 }
24878             break;
24879
24880           case TYPE_STORE:
24881           case TYPE_FPSTORE:
24882             if ((rs6000_tune == PROCESSOR_POWER6)
24883                 && recog_memoized (dep_insn)
24884                 && (INSN_CODE (dep_insn) >= 0))
24885               {
24886
24887                 if (GET_CODE (PATTERN (insn)) != SET)
24888                   /* If this happens, we have to extend this to schedule
24889                      optimally.  Return default for now.  */
24890                   return cost;
24891
24892                 /* Adjust the cost for the case where the value written
24893                    by a fixed point operation is used as the address
24894                    gen value on a store. */
24895                 switch (get_attr_type (dep_insn))
24896                   {
24897                   case TYPE_LOAD:
24898                   case TYPE_CNTLZ:
24899                     {
24900                       if (! rs6000_store_data_bypass_p (dep_insn, insn))
24901                         return get_attr_sign_extend (dep_insn)
24902                                == SIGN_EXTEND_YES ? 6 : 4;
24903                       break;
24904                     }
24905                   case TYPE_SHIFT:
24906                     {
24907                       if (! rs6000_store_data_bypass_p (dep_insn, insn))
24908                         return get_attr_var_shift (dep_insn) == VAR_SHIFT_YES ?
24909                                6 : 3;
24910                       break;
24911                     }
24912                   case TYPE_INTEGER:
24913                   case TYPE_ADD:
24914                   case TYPE_LOGICAL:
24915                   case TYPE_EXTS:
24916                   case TYPE_INSERT:
24917                     {
24918                       if (! rs6000_store_data_bypass_p (dep_insn, insn))
24919                         return 3;
24920                       break;
24921                     }
24922                   case TYPE_STORE:
24923                   case TYPE_FPLOAD:
24924                   case TYPE_FPSTORE:
24925                     {
24926                       if (get_attr_update (dep_insn) == UPDATE_YES
24927                           && ! rs6000_store_data_bypass_p (dep_insn, insn))
24928                         return 3;
24929                       break;
24930                     }
24931                   case TYPE_MUL:
24932                     {
24933                       if (! rs6000_store_data_bypass_p (dep_insn, insn))
24934                         return 17;
24935                       break;
24936                     }
24937                   case TYPE_DIV:
24938                     {
24939                       if (! rs6000_store_data_bypass_p (dep_insn, insn))
24940                         return get_attr_size (dep_insn) == SIZE_32 ? 45 : 57;
24941                       break;
24942                     }
24943                   default:
24944                     break;
24945                   }
24946               }
24947             break;
24948
24949           case TYPE_LOAD:
24950             if ((rs6000_tune == PROCESSOR_POWER6)
24951                 && recog_memoized (dep_insn)
24952                 && (INSN_CODE (dep_insn) >= 0))
24953               {
24954
24955                 /* Adjust the cost for the case where the value written
24956                    by a fixed point instruction is used within the address
24957                    gen portion of a subsequent load(u)(x) */
24958                 switch (get_attr_type (dep_insn))
24959                   {
24960                   case TYPE_LOAD:
24961                   case TYPE_CNTLZ:
24962                     {
24963                       if (set_to_load_agen (dep_insn, insn))
24964                         return get_attr_sign_extend (dep_insn)
24965                                == SIGN_EXTEND_YES ? 6 : 4;
24966                       break;
24967                     }
24968                   case TYPE_SHIFT:
24969                     {
24970                       if (set_to_load_agen (dep_insn, insn))
24971                         return get_attr_var_shift (dep_insn) == VAR_SHIFT_YES ?
24972                                6 : 3;
24973                       break;
24974                     }
24975                   case TYPE_INTEGER:
24976                   case TYPE_ADD:
24977                   case TYPE_LOGICAL:
24978                   case TYPE_EXTS:
24979                   case TYPE_INSERT:
24980                     {
24981                       if (set_to_load_agen (dep_insn, insn))
24982                         return 3;
24983                       break;
24984                     }
24985                   case TYPE_STORE:
24986                   case TYPE_FPLOAD:
24987                   case TYPE_FPSTORE:
24988                     {
24989                       if (get_attr_update (dep_insn) == UPDATE_YES
24990                           && set_to_load_agen (dep_insn, insn))
24991                         return 3;
24992                       break;
24993                     }
24994                   case TYPE_MUL:
24995                     {
24996                       if (set_to_load_agen (dep_insn, insn))
24997                         return 17;
24998                       break;
24999                     }
25000                   case TYPE_DIV:
25001                     {
25002                       if (set_to_load_agen (dep_insn, insn))
25003                         return get_attr_size (dep_insn) == SIZE_32 ? 45 : 57;
25004                       break;
25005                     }
25006                   default:
25007                     break;
25008                   }
25009               }
25010             break;
25011
25012           case TYPE_FPLOAD:
25013             if ((rs6000_tune == PROCESSOR_POWER6)
25014                 && get_attr_update (insn) == UPDATE_NO
25015                 && recog_memoized (dep_insn)
25016                 && (INSN_CODE (dep_insn) >= 0)
25017                 && (get_attr_type (dep_insn) == TYPE_MFFGPR))
25018               return 2;
25019
25020           default:
25021             break;
25022           }
25023
25024         /* Fall out to return default cost.  */
25025       }
25026       break;
25027
25028     case REG_DEP_OUTPUT:
25029       /* Output dependency; DEP_INSN writes a register that INSN writes some
25030          cycles later.  */
25031       if ((rs6000_tune == PROCESSOR_POWER6)
25032           && recog_memoized (dep_insn)
25033           && (INSN_CODE (dep_insn) >= 0))
25034         {
25035           attr_type = get_attr_type (insn);
25036
25037           switch (attr_type)
25038             {
25039             case TYPE_FP:
25040             case TYPE_FPSIMPLE:
25041               if (get_attr_type (dep_insn) == TYPE_FP
25042                   || get_attr_type (dep_insn) == TYPE_FPSIMPLE)
25043                 return 1;
25044               break;
25045             case TYPE_FPLOAD:
25046               if (get_attr_update (insn) == UPDATE_NO
25047                   && get_attr_type (dep_insn) == TYPE_MFFGPR)
25048                 return 2;
25049               break;
25050             default:
25051               break;
25052             }
25053         }
25054       /* Fall through, no cost for output dependency.  */
25055       /* FALLTHRU */
25056
25057     case REG_DEP_ANTI:
25058       /* Anti dependency; DEP_INSN reads a register that INSN writes some
25059          cycles later.  */
25060       return 0;
25061
25062     default:
25063       gcc_unreachable ();
25064     }
25065
25066   return cost;
25067 }
25068
25069 /* Debug version of rs6000_adjust_cost.  */
25070
25071 static int
25072 rs6000_debug_adjust_cost (rtx_insn *insn, int dep_type, rtx_insn *dep_insn,
25073                           int cost, unsigned int dw)
25074 {
25075   int ret = rs6000_adjust_cost (insn, dep_type, dep_insn, cost, dw);
25076
25077   if (ret != cost)
25078     {
25079       const char *dep;
25080
25081       switch (dep_type)
25082         {
25083         default:             dep = "unknown depencency"; break;
25084         case REG_DEP_TRUE:   dep = "data dependency";    break;
25085         case REG_DEP_OUTPUT: dep = "output dependency";  break;
25086         case REG_DEP_ANTI:   dep = "anti depencency";    break;
25087         }
25088
25089       fprintf (stderr,
25090                "\nrs6000_adjust_cost, final cost = %d, orig cost = %d, "
25091                "%s, insn:\n", ret, cost, dep);
25092
25093       debug_rtx (insn);
25094     }
25095
25096   return ret;
25097 }
25098
25099 /* The function returns a true if INSN is microcoded.
25100    Return false otherwise.  */
25101
25102 static bool
25103 is_microcoded_insn (rtx_insn *insn)
25104 {
25105   if (!insn || !NONDEBUG_INSN_P (insn)
25106       || GET_CODE (PATTERN (insn)) == USE
25107       || GET_CODE (PATTERN (insn)) == CLOBBER)
25108     return false;
25109
25110   if (rs6000_tune == PROCESSOR_CELL)
25111     return get_attr_cell_micro (insn) == CELL_MICRO_ALWAYS;
25112
25113   if (rs6000_sched_groups
25114       && (rs6000_tune == PROCESSOR_POWER4 || rs6000_tune == PROCESSOR_POWER5))
25115     {
25116       enum attr_type type = get_attr_type (insn);
25117       if ((type == TYPE_LOAD
25118            && get_attr_update (insn) == UPDATE_YES
25119            && get_attr_sign_extend (insn) == SIGN_EXTEND_YES)
25120           || ((type == TYPE_LOAD || type == TYPE_STORE)
25121               && get_attr_update (insn) == UPDATE_YES
25122               && get_attr_indexed (insn) == INDEXED_YES)
25123           || type == TYPE_MFCR)
25124         return true;
25125     }
25126
25127   return false;
25128 }
25129
25130 /* The function returns true if INSN is cracked into 2 instructions
25131    by the processor (and therefore occupies 2 issue slots).  */
25132
25133 static bool
25134 is_cracked_insn (rtx_insn *insn)
25135 {
25136   if (!insn || !NONDEBUG_INSN_P (insn)
25137       || GET_CODE (PATTERN (insn)) == USE
25138       || GET_CODE (PATTERN (insn)) == CLOBBER)
25139     return false;
25140
25141   if (rs6000_sched_groups
25142       && (rs6000_tune == PROCESSOR_POWER4 || rs6000_tune == PROCESSOR_POWER5))
25143     {
25144       enum attr_type type = get_attr_type (insn);
25145       if ((type == TYPE_LOAD
25146            && get_attr_sign_extend (insn) == SIGN_EXTEND_YES
25147            && get_attr_update (insn) == UPDATE_NO)
25148           || (type == TYPE_LOAD
25149               && get_attr_sign_extend (insn) == SIGN_EXTEND_NO
25150               && get_attr_update (insn) == UPDATE_YES
25151               && get_attr_indexed (insn) == INDEXED_NO)
25152           || (type == TYPE_STORE
25153               && get_attr_update (insn) == UPDATE_YES
25154               && get_attr_indexed (insn) == INDEXED_NO)
25155           || ((type == TYPE_FPLOAD || type == TYPE_FPSTORE)
25156               && get_attr_update (insn) == UPDATE_YES)
25157           || (type == TYPE_CR_LOGICAL
25158               && get_attr_cr_logical_3op (insn) == CR_LOGICAL_3OP_YES)
25159           || (type == TYPE_EXTS
25160               && get_attr_dot (insn) == DOT_YES)
25161           || (type == TYPE_SHIFT
25162               && get_attr_dot (insn) == DOT_YES
25163               && get_attr_var_shift (insn) == VAR_SHIFT_NO)
25164           || (type == TYPE_MUL
25165               && get_attr_dot (insn) == DOT_YES)
25166           || type == TYPE_DIV
25167           || (type == TYPE_INSERT
25168               && get_attr_size (insn) == SIZE_32))
25169         return true;
25170     }
25171
25172   return false;
25173 }
25174
25175 /* The function returns true if INSN can be issued only from
25176    the branch slot.  */
25177
25178 static bool
25179 is_branch_slot_insn (rtx_insn *insn)
25180 {
25181   if (!insn || !NONDEBUG_INSN_P (insn)
25182       || GET_CODE (PATTERN (insn)) == USE
25183       || GET_CODE (PATTERN (insn)) == CLOBBER)
25184     return false;
25185
25186   if (rs6000_sched_groups)
25187     {
25188       enum attr_type type = get_attr_type (insn);
25189       if (type == TYPE_BRANCH || type == TYPE_JMPREG)
25190         return true;
25191       return false;
25192     }
25193
25194   return false;
25195 }
25196
25197 /* The function returns true if out_inst sets a value that is
25198    used in the address generation computation of in_insn */
25199 static bool
25200 set_to_load_agen (rtx_insn *out_insn, rtx_insn *in_insn)
25201 {
25202   rtx out_set, in_set;
25203
25204   /* For performance reasons, only handle the simple case where
25205      both loads are a single_set. */
25206   out_set = single_set (out_insn);
25207   if (out_set)
25208     {
25209       in_set = single_set (in_insn);
25210       if (in_set)
25211         return reg_mentioned_p (SET_DEST (out_set), SET_SRC (in_set));
25212     }
25213
25214   return false;
25215 }
25216
25217 /* Try to determine base/offset/size parts of the given MEM.
25218    Return true if successful, false if all the values couldn't
25219    be determined.
25220
25221    This function only looks for REG or REG+CONST address forms.
25222    REG+REG address form will return false. */
25223
25224 static bool
25225 get_memref_parts (rtx mem, rtx *base, HOST_WIDE_INT *offset,
25226                   HOST_WIDE_INT *size)
25227 {
25228   rtx addr_rtx;
25229   if MEM_SIZE_KNOWN_P (mem)
25230     *size = MEM_SIZE (mem);
25231   else
25232     return false;
25233
25234   addr_rtx = (XEXP (mem, 0));
25235   if (GET_CODE (addr_rtx) == PRE_MODIFY)
25236     addr_rtx = XEXP (addr_rtx, 1);
25237
25238   *offset = 0;
25239   while (GET_CODE (addr_rtx) == PLUS
25240          && CONST_INT_P (XEXP (addr_rtx, 1)))
25241     {
25242       *offset += INTVAL (XEXP (addr_rtx, 1));
25243       addr_rtx = XEXP (addr_rtx, 0);
25244     }
25245   if (!REG_P (addr_rtx))
25246     return false;
25247
25248   *base = addr_rtx;
25249   return true;
25250 }
25251
25252 /* The function returns true if the target storage location of
25253    mem1 is adjacent to the target storage location of mem2 */
25254 /* Return 1 if memory locations are adjacent.  */
25255
25256 static bool
25257 adjacent_mem_locations (rtx mem1, rtx mem2)
25258 {
25259   rtx reg1, reg2;
25260   HOST_WIDE_INT off1, size1, off2, size2;
25261
25262   if (get_memref_parts (mem1, &reg1, &off1, &size1)
25263       && get_memref_parts (mem2, &reg2, &off2, &size2))
25264     return ((REGNO (reg1) == REGNO (reg2))
25265             && ((off1 + size1 == off2)
25266                 || (off2 + size2 == off1)));
25267
25268   return false;
25269 }
25270
25271 /* This function returns true if it can be determined that the two MEM
25272    locations overlap by at least 1 byte based on base reg/offset/size. */
25273
25274 static bool
25275 mem_locations_overlap (rtx mem1, rtx mem2)
25276 {
25277   rtx reg1, reg2;
25278   HOST_WIDE_INT off1, size1, off2, size2;
25279
25280   if (get_memref_parts (mem1, &reg1, &off1, &size1)
25281       && get_memref_parts (mem2, &reg2, &off2, &size2))
25282     return ((REGNO (reg1) == REGNO (reg2))
25283             && (((off1 <= off2) && (off1 + size1 > off2))
25284                 || ((off2 <= off1) && (off2 + size2 > off1))));
25285
25286   return false;
25287 }
25288
25289 /* A C statement (sans semicolon) to update the integer scheduling
25290    priority INSN_PRIORITY (INSN). Increase the priority to execute the
25291    INSN earlier, reduce the priority to execute INSN later.  Do not
25292    define this macro if you do not need to adjust the scheduling
25293    priorities of insns.  */
25294
25295 static int
25296 rs6000_adjust_priority (rtx_insn *insn ATTRIBUTE_UNUSED, int priority)
25297 {
25298   rtx load_mem, str_mem;
25299   /* On machines (like the 750) which have asymmetric integer units,
25300      where one integer unit can do multiply and divides and the other
25301      can't, reduce the priority of multiply/divide so it is scheduled
25302      before other integer operations.  */
25303
25304 #if 0
25305   if (! INSN_P (insn))
25306     return priority;
25307
25308   if (GET_CODE (PATTERN (insn)) == USE)
25309     return priority;
25310
25311   switch (rs6000_tune) {
25312   case PROCESSOR_PPC750:
25313     switch (get_attr_type (insn))
25314       {
25315       default:
25316         break;
25317
25318       case TYPE_MUL:
25319       case TYPE_DIV:
25320         fprintf (stderr, "priority was %#x (%d) before adjustment\n",
25321                  priority, priority);
25322         if (priority >= 0 && priority < 0x01000000)
25323           priority >>= 3;
25324         break;
25325       }
25326   }
25327 #endif
25328
25329   if (insn_must_be_first_in_group (insn)
25330       && reload_completed
25331       && current_sched_info->sched_max_insns_priority
25332       && rs6000_sched_restricted_insns_priority)
25333     {
25334
25335       /* Prioritize insns that can be dispatched only in the first
25336          dispatch slot.  */
25337       if (rs6000_sched_restricted_insns_priority == 1)
25338         /* Attach highest priority to insn. This means that in
25339            haifa-sched.c:ready_sort(), dispatch-slot restriction considerations
25340            precede 'priority' (critical path) considerations.  */
25341         return current_sched_info->sched_max_insns_priority;
25342       else if (rs6000_sched_restricted_insns_priority == 2)
25343         /* Increase priority of insn by a minimal amount. This means that in
25344            haifa-sched.c:ready_sort(), only 'priority' (critical path)
25345            considerations precede dispatch-slot restriction considerations.  */
25346         return (priority + 1);
25347     }
25348
25349   if (rs6000_tune == PROCESSOR_POWER6
25350       && ((load_store_pendulum == -2 && is_load_insn (insn, &load_mem))
25351           || (load_store_pendulum == 2 && is_store_insn (insn, &str_mem))))
25352     /* Attach highest priority to insn if the scheduler has just issued two
25353        stores and this instruction is a load, or two loads and this instruction
25354        is a store. Power6 wants loads and stores scheduled alternately
25355        when possible */
25356     return current_sched_info->sched_max_insns_priority;
25357
25358   return priority;
25359 }
25360
25361 /* Return true if the instruction is nonpipelined on the Cell. */
25362 static bool
25363 is_nonpipeline_insn (rtx_insn *insn)
25364 {
25365   enum attr_type type;
25366   if (!insn || !NONDEBUG_INSN_P (insn)
25367       || GET_CODE (PATTERN (insn)) == USE
25368       || GET_CODE (PATTERN (insn)) == CLOBBER)
25369     return false;
25370
25371   type = get_attr_type (insn);
25372   if (type == TYPE_MUL
25373       || type == TYPE_DIV
25374       || type == TYPE_SDIV
25375       || type == TYPE_DDIV
25376       || type == TYPE_SSQRT
25377       || type == TYPE_DSQRT
25378       || type == TYPE_MFCR
25379       || type == TYPE_MFCRF
25380       || type == TYPE_MFJMPR)
25381     {
25382       return true;
25383     }
25384   return false;
25385 }
25386
25387
25388 /* Return how many instructions the machine can issue per cycle.  */
25389
25390 static int
25391 rs6000_issue_rate (void)
25392 {
25393   /* Unless scheduling for register pressure, use issue rate of 1 for
25394      first scheduling pass to decrease degradation.  */
25395   if (!reload_completed && !flag_sched_pressure)
25396     return 1;
25397
25398   switch (rs6000_tune) {
25399   case PROCESSOR_RS64A:
25400   case PROCESSOR_PPC601: /* ? */
25401   case PROCESSOR_PPC7450:
25402     return 3;
25403   case PROCESSOR_PPC440:
25404   case PROCESSOR_PPC603:
25405   case PROCESSOR_PPC750:
25406   case PROCESSOR_PPC7400:
25407   case PROCESSOR_PPC8540:
25408   case PROCESSOR_PPC8548:
25409   case PROCESSOR_CELL:
25410   case PROCESSOR_PPCE300C2:
25411   case PROCESSOR_PPCE300C3:
25412   case PROCESSOR_PPCE500MC:
25413   case PROCESSOR_PPCE500MC64:
25414   case PROCESSOR_PPCE5500:
25415   case PROCESSOR_PPCE6500:
25416   case PROCESSOR_TITAN:
25417     return 2;
25418   case PROCESSOR_PPC476:
25419   case PROCESSOR_PPC604:
25420   case PROCESSOR_PPC604e:
25421   case PROCESSOR_PPC620:
25422   case PROCESSOR_PPC630:
25423     return 4;
25424   case PROCESSOR_POWER4:
25425   case PROCESSOR_POWER5:
25426   case PROCESSOR_POWER6:
25427   case PROCESSOR_POWER7:
25428     return 5;
25429   case PROCESSOR_POWER8:
25430     return 7;
25431   case PROCESSOR_POWER9:
25432   case PROCESSOR_FUTURE:
25433     return 6;
25434   default:
25435     return 1;
25436   }
25437 }
25438
25439 /* Return how many instructions to look ahead for better insn
25440    scheduling.  */
25441
25442 static int
25443 rs6000_use_sched_lookahead (void)
25444 {
25445   switch (rs6000_tune)
25446     {
25447     case PROCESSOR_PPC8540:
25448     case PROCESSOR_PPC8548:
25449       return 4;
25450
25451     case PROCESSOR_CELL:
25452       return (reload_completed ? 8 : 0);
25453
25454     default:
25455       return 0;
25456     }
25457 }
25458
25459 /* We are choosing insn from the ready queue.  Return zero if INSN can be
25460    chosen.  */
25461 static int
25462 rs6000_use_sched_lookahead_guard (rtx_insn *insn, int ready_index)
25463 {
25464   if (ready_index == 0)
25465     return 0;
25466
25467   if (rs6000_tune != PROCESSOR_CELL)
25468     return 0;
25469
25470   gcc_assert (insn != NULL_RTX && INSN_P (insn));
25471
25472   if (!reload_completed
25473       || is_nonpipeline_insn (insn)
25474       || is_microcoded_insn (insn))
25475     return 1;
25476
25477   return 0;
25478 }
25479
25480 /* Determine if PAT refers to memory. If so, set MEM_REF to the MEM rtx
25481    and return true.  */
25482
25483 static bool
25484 find_mem_ref (rtx pat, rtx *mem_ref)
25485 {
25486   const char * fmt;
25487   int i, j;
25488
25489   /* stack_tie does not produce any real memory traffic.  */
25490   if (tie_operand (pat, VOIDmode))
25491     return false;
25492
25493   if (MEM_P (pat))
25494     {
25495       *mem_ref = pat;
25496       return true;
25497     }
25498
25499   /* Recursively process the pattern.  */
25500   fmt = GET_RTX_FORMAT (GET_CODE (pat));
25501
25502   for (i = GET_RTX_LENGTH (GET_CODE (pat)) - 1; i >= 0; i--)
25503     {
25504       if (fmt[i] == 'e')
25505         {
25506           if (find_mem_ref (XEXP (pat, i), mem_ref))
25507             return true;
25508         }
25509       else if (fmt[i] == 'E')
25510         for (j = XVECLEN (pat, i) - 1; j >= 0; j--)
25511           {
25512             if (find_mem_ref (XVECEXP (pat, i, j), mem_ref))
25513               return true;
25514           }
25515     }
25516
25517   return false;
25518 }
25519
25520 /* Determine if PAT is a PATTERN of a load insn.  */
25521
25522 static bool
25523 is_load_insn1 (rtx pat, rtx *load_mem)
25524 {
25525   if (!pat || pat == NULL_RTX)
25526     return false;
25527
25528   if (GET_CODE (pat) == SET)
25529     return find_mem_ref (SET_SRC (pat), load_mem);
25530
25531   if (GET_CODE (pat) == PARALLEL)
25532     {
25533       int i;
25534
25535       for (i = 0; i < XVECLEN (pat, 0); i++)
25536         if (is_load_insn1 (XVECEXP (pat, 0, i), load_mem))
25537           return true;
25538     }
25539
25540   return false;
25541 }
25542
25543 /* Determine if INSN loads from memory.  */
25544
25545 static bool
25546 is_load_insn (rtx insn, rtx *load_mem)
25547 {
25548   if (!insn || !INSN_P (insn))
25549     return false;
25550
25551   if (CALL_P (insn))
25552     return false;
25553
25554   return is_load_insn1 (PATTERN (insn), load_mem);
25555 }
25556
25557 /* Determine if PAT is a PATTERN of a store insn.  */
25558
25559 static bool
25560 is_store_insn1 (rtx pat, rtx *str_mem)
25561 {
25562   if (!pat || pat == NULL_RTX)
25563     return false;
25564
25565   if (GET_CODE (pat) == SET)
25566     return find_mem_ref (SET_DEST (pat), str_mem);
25567
25568   if (GET_CODE (pat) == PARALLEL)
25569     {
25570       int i;
25571
25572       for (i = 0; i < XVECLEN (pat, 0); i++)
25573         if (is_store_insn1 (XVECEXP (pat, 0, i), str_mem))
25574           return true;
25575     }
25576
25577   return false;
25578 }
25579
25580 /* Determine if INSN stores to memory.  */
25581
25582 static bool
25583 is_store_insn (rtx insn, rtx *str_mem)
25584 {
25585   if (!insn || !INSN_P (insn))
25586     return false;
25587
25588   return is_store_insn1 (PATTERN (insn), str_mem);
25589 }
25590
25591 /* Return whether TYPE is a Power9 pairable vector instruction type.  */
25592
25593 static bool
25594 is_power9_pairable_vec_type (enum attr_type type)
25595 {
25596   switch (type)
25597     {
25598       case TYPE_VECSIMPLE:
25599       case TYPE_VECCOMPLEX:
25600       case TYPE_VECDIV:
25601       case TYPE_VECCMP:
25602       case TYPE_VECPERM:
25603       case TYPE_VECFLOAT:
25604       case TYPE_VECFDIV:
25605       case TYPE_VECDOUBLE:
25606         return true;
25607       default:
25608         break;
25609     }
25610   return false;
25611 }
25612
25613 /* Returns whether the dependence between INSN and NEXT is considered
25614    costly by the given target.  */
25615
25616 static bool
25617 rs6000_is_costly_dependence (dep_t dep, int cost, int distance)
25618 {
25619   rtx insn;
25620   rtx next;
25621   rtx load_mem, str_mem;
25622
25623   /* If the flag is not enabled - no dependence is considered costly;
25624      allow all dependent insns in the same group.
25625      This is the most aggressive option.  */
25626   if (rs6000_sched_costly_dep == no_dep_costly)
25627     return false;
25628
25629   /* If the flag is set to 1 - a dependence is always considered costly;
25630      do not allow dependent instructions in the same group.
25631      This is the most conservative option.  */
25632   if (rs6000_sched_costly_dep == all_deps_costly)
25633     return true;
25634
25635   insn = DEP_PRO (dep);
25636   next = DEP_CON (dep);
25637
25638   if (rs6000_sched_costly_dep == store_to_load_dep_costly
25639       && is_load_insn (next, &load_mem)
25640       && is_store_insn (insn, &str_mem))
25641     /* Prevent load after store in the same group.  */
25642     return true;
25643
25644   if (rs6000_sched_costly_dep == true_store_to_load_dep_costly
25645       && is_load_insn (next, &load_mem)
25646       && is_store_insn (insn, &str_mem)
25647       && DEP_TYPE (dep) == REG_DEP_TRUE
25648       && mem_locations_overlap(str_mem, load_mem))
25649      /* Prevent load after store in the same group if it is a true
25650         dependence.  */
25651      return true;
25652
25653   /* The flag is set to X; dependences with latency >= X are considered costly,
25654      and will not be scheduled in the same group.  */
25655   if (rs6000_sched_costly_dep <= max_dep_latency
25656       && ((cost - distance) >= (int)rs6000_sched_costly_dep))
25657     return true;
25658
25659   return false;
25660 }
25661
25662 /* Return the next insn after INSN that is found before TAIL is reached,
25663    skipping any "non-active" insns - insns that will not actually occupy
25664    an issue slot.  Return NULL_RTX if such an insn is not found.  */
25665
25666 static rtx_insn *
25667 get_next_active_insn (rtx_insn *insn, rtx_insn *tail)
25668 {
25669   if (insn == NULL_RTX || insn == tail)
25670     return NULL;
25671
25672   while (1)
25673     {
25674       insn = NEXT_INSN (insn);
25675       if (insn == NULL_RTX || insn == tail)
25676         return NULL;
25677
25678       if (CALL_P (insn)
25679           || JUMP_P (insn) || JUMP_TABLE_DATA_P (insn)
25680           || (NONJUMP_INSN_P (insn)
25681               && GET_CODE (PATTERN (insn)) != USE
25682               && GET_CODE (PATTERN (insn)) != CLOBBER
25683               && INSN_CODE (insn) != CODE_FOR_stack_tie))
25684         break;
25685     }
25686   return insn;
25687 }
25688
25689 /* Do Power9 specific sched_reorder2 reordering of ready list.  */
25690
25691 static int
25692 power9_sched_reorder2 (rtx_insn **ready, int lastpos)
25693 {
25694   int pos;
25695   int i;
25696   rtx_insn *tmp;
25697   enum attr_type type, type2;
25698
25699   type = get_attr_type (last_scheduled_insn);
25700
25701   /* Try to issue fixed point divides back-to-back in pairs so they will be
25702      routed to separate execution units and execute in parallel.  */
25703   if (type == TYPE_DIV && divide_cnt == 0)
25704     {
25705       /* First divide has been scheduled.  */
25706       divide_cnt = 1;
25707
25708       /* Scan the ready list looking for another divide, if found move it
25709          to the end of the list so it is chosen next.  */
25710       pos = lastpos;
25711       while (pos >= 0)
25712         {
25713           if (recog_memoized (ready[pos]) >= 0
25714               && get_attr_type (ready[pos]) == TYPE_DIV)
25715             {
25716               tmp = ready[pos];
25717               for (i = pos; i < lastpos; i++)
25718                 ready[i] = ready[i + 1];
25719               ready[lastpos] = tmp;
25720               break;
25721             }
25722           pos--;
25723         }
25724     }
25725   else
25726     {
25727       /* Last insn was the 2nd divide or not a divide, reset the counter.  */
25728       divide_cnt = 0;
25729
25730       /* The best dispatch throughput for vector and vector load insns can be
25731          achieved by interleaving a vector and vector load such that they'll
25732          dispatch to the same superslice. If this pairing cannot be achieved
25733          then it is best to pair vector insns together and vector load insns
25734          together.
25735
25736          To aid in this pairing, vec_pairing maintains the current state with
25737          the following values:
25738
25739              0  : Initial state, no vecload/vector pairing has been started.
25740
25741              1  : A vecload or vector insn has been issued and a candidate for
25742                   pairing has been found and moved to the end of the ready
25743                   list.  */
25744       if (type == TYPE_VECLOAD)
25745         {
25746           /* Issued a vecload.  */
25747           if (vec_pairing == 0)
25748             {
25749               int vecload_pos = -1;
25750               /* We issued a single vecload, look for a vector insn to pair it
25751                  with.  If one isn't found, try to pair another vecload.  */
25752               pos = lastpos;
25753               while (pos >= 0)
25754                 {
25755                   if (recog_memoized (ready[pos]) >= 0)
25756                     {
25757                       type2 = get_attr_type (ready[pos]);
25758                       if (is_power9_pairable_vec_type (type2))
25759                         {
25760                           /* Found a vector insn to pair with, move it to the
25761                              end of the ready list so it is scheduled next.  */
25762                           tmp = ready[pos];
25763                           for (i = pos; i < lastpos; i++)
25764                             ready[i] = ready[i + 1];
25765                           ready[lastpos] = tmp;
25766                           vec_pairing = 1;
25767                           return cached_can_issue_more;
25768                         }
25769                       else if (type2 == TYPE_VECLOAD && vecload_pos == -1)
25770                         /* Remember position of first vecload seen.  */
25771                         vecload_pos = pos;
25772                     }
25773                   pos--;
25774                 }
25775               if (vecload_pos >= 0)
25776                 {
25777                   /* Didn't find a vector to pair with but did find a vecload,
25778                      move it to the end of the ready list.  */
25779                   tmp = ready[vecload_pos];
25780                   for (i = vecload_pos; i < lastpos; i++)
25781                     ready[i] = ready[i + 1];
25782                   ready[lastpos] = tmp;
25783                   vec_pairing = 1;
25784                   return cached_can_issue_more;
25785                 }
25786             }
25787         }
25788       else if (is_power9_pairable_vec_type (type))
25789         {
25790           /* Issued a vector operation.  */
25791           if (vec_pairing == 0)
25792             {
25793               int vec_pos = -1;
25794               /* We issued a single vector insn, look for a vecload to pair it
25795                  with.  If one isn't found, try to pair another vector.  */
25796               pos = lastpos;
25797               while (pos >= 0)
25798                 {
25799                   if (recog_memoized (ready[pos]) >= 0)
25800                     {
25801                       type2 = get_attr_type (ready[pos]);
25802                       if (type2 == TYPE_VECLOAD)
25803                         {
25804                           /* Found a vecload insn to pair with, move it to the
25805                              end of the ready list so it is scheduled next.  */
25806                           tmp = ready[pos];
25807                           for (i = pos; i < lastpos; i++)
25808                             ready[i] = ready[i + 1];
25809                           ready[lastpos] = tmp;
25810                           vec_pairing = 1;
25811                           return cached_can_issue_more;
25812                         }
25813                       else if (is_power9_pairable_vec_type (type2)
25814                                && vec_pos == -1)
25815                         /* Remember position of first vector insn seen.  */
25816                         vec_pos = pos;
25817                     }
25818                   pos--;
25819                 }
25820               if (vec_pos >= 0)
25821                 {
25822                   /* Didn't find a vecload to pair with but did find a vector
25823                      insn, move it to the end of the ready list.  */
25824                   tmp = ready[vec_pos];
25825                   for (i = vec_pos; i < lastpos; i++)
25826                     ready[i] = ready[i + 1];
25827                   ready[lastpos] = tmp;
25828                   vec_pairing = 1;
25829                   return cached_can_issue_more;
25830                 }
25831             }
25832         }
25833
25834       /* We've either finished a vec/vecload pair, couldn't find an insn to
25835          continue the current pair, or the last insn had nothing to do with
25836          with pairing.  In any case, reset the state.  */
25837       vec_pairing = 0;
25838     }
25839
25840   return cached_can_issue_more;
25841 }
25842
25843 /* We are about to begin issuing insns for this clock cycle. */
25844
25845 static int
25846 rs6000_sched_reorder (FILE *dump ATTRIBUTE_UNUSED, int sched_verbose,
25847                         rtx_insn **ready ATTRIBUTE_UNUSED,
25848                         int *pn_ready ATTRIBUTE_UNUSED,
25849                         int clock_var ATTRIBUTE_UNUSED)
25850 {
25851   int n_ready = *pn_ready;
25852
25853   if (sched_verbose)
25854     fprintf (dump, "// rs6000_sched_reorder :\n");
25855
25856   /* Reorder the ready list, if the second to last ready insn
25857      is a nonepipeline insn.  */
25858   if (rs6000_tune == PROCESSOR_CELL && n_ready > 1)
25859   {
25860     if (is_nonpipeline_insn (ready[n_ready - 1])
25861         && (recog_memoized (ready[n_ready - 2]) > 0))
25862       /* Simply swap first two insns.  */
25863       std::swap (ready[n_ready - 1], ready[n_ready - 2]);
25864   }
25865
25866   if (rs6000_tune == PROCESSOR_POWER6)
25867     load_store_pendulum = 0;
25868
25869   return rs6000_issue_rate ();
25870 }
25871
25872 /* Like rs6000_sched_reorder, but called after issuing each insn.  */
25873
25874 static int
25875 rs6000_sched_reorder2 (FILE *dump, int sched_verbose, rtx_insn **ready,
25876                          int *pn_ready, int clock_var ATTRIBUTE_UNUSED)
25877 {
25878   if (sched_verbose)
25879     fprintf (dump, "// rs6000_sched_reorder2 :\n");
25880
25881   /* For Power6, we need to handle some special cases to try and keep the
25882      store queue from overflowing and triggering expensive flushes.
25883
25884      This code monitors how load and store instructions are being issued
25885      and skews the ready list one way or the other to increase the likelihood
25886      that a desired instruction is issued at the proper time.
25887
25888      A couple of things are done.  First, we maintain a "load_store_pendulum"
25889      to track the current state of load/store issue.
25890
25891        - If the pendulum is at zero, then no loads or stores have been
25892          issued in the current cycle so we do nothing.
25893
25894        - If the pendulum is 1, then a single load has been issued in this
25895          cycle and we attempt to locate another load in the ready list to
25896          issue with it.
25897
25898        - If the pendulum is -2, then two stores have already been
25899          issued in this cycle, so we increase the priority of the first load
25900          in the ready list to increase it's likelihood of being chosen first
25901          in the next cycle.
25902
25903        - If the pendulum is -1, then a single store has been issued in this
25904          cycle and we attempt to locate another store in the ready list to
25905          issue with it, preferring a store to an adjacent memory location to
25906          facilitate store pairing in the store queue.
25907
25908        - If the pendulum is 2, then two loads have already been
25909          issued in this cycle, so we increase the priority of the first store
25910          in the ready list to increase it's likelihood of being chosen first
25911          in the next cycle.
25912
25913        - If the pendulum < -2 or > 2, then do nothing.
25914
25915        Note: This code covers the most common scenarios.  There exist non
25916              load/store instructions which make use of the LSU and which
25917              would need to be accounted for to strictly model the behavior
25918              of the machine.  Those instructions are currently unaccounted
25919              for to help minimize compile time overhead of this code.
25920    */
25921   if (rs6000_tune == PROCESSOR_POWER6 && last_scheduled_insn)
25922     {
25923       int pos;
25924       int i;
25925       rtx_insn *tmp;
25926       rtx load_mem, str_mem;
25927
25928       if (is_store_insn (last_scheduled_insn, &str_mem))
25929         /* Issuing a store, swing the load_store_pendulum to the left */
25930         load_store_pendulum--;
25931       else if (is_load_insn (last_scheduled_insn, &load_mem))
25932         /* Issuing a load, swing the load_store_pendulum to the right */
25933         load_store_pendulum++;
25934       else
25935         return cached_can_issue_more;
25936
25937       /* If the pendulum is balanced, or there is only one instruction on
25938          the ready list, then all is well, so return. */
25939       if ((load_store_pendulum == 0) || (*pn_ready <= 1))
25940         return cached_can_issue_more;
25941
25942       if (load_store_pendulum == 1)
25943         {
25944           /* A load has been issued in this cycle.  Scan the ready list
25945              for another load to issue with it */
25946           pos = *pn_ready-1;
25947
25948           while (pos >= 0)
25949             {
25950               if (is_load_insn (ready[pos], &load_mem))
25951                 {
25952                   /* Found a load.  Move it to the head of the ready list,
25953                      and adjust it's priority so that it is more likely to
25954                      stay there */
25955                   tmp = ready[pos];
25956                   for (i=pos; i<*pn_ready-1; i++)
25957                     ready[i] = ready[i + 1];
25958                   ready[*pn_ready-1] = tmp;
25959
25960                   if (!sel_sched_p () && INSN_PRIORITY_KNOWN (tmp))
25961                     INSN_PRIORITY (tmp)++;
25962                   break;
25963                 }
25964               pos--;
25965             }
25966         }
25967       else if (load_store_pendulum == -2)
25968         {
25969           /* Two stores have been issued in this cycle.  Increase the
25970              priority of the first load in the ready list to favor it for
25971              issuing in the next cycle. */
25972           pos = *pn_ready-1;
25973
25974           while (pos >= 0)
25975             {
25976               if (is_load_insn (ready[pos], &load_mem)
25977                   && !sel_sched_p ()
25978                   && INSN_PRIORITY_KNOWN (ready[pos]))
25979                 {
25980                   INSN_PRIORITY (ready[pos])++;
25981
25982                   /* Adjust the pendulum to account for the fact that a load
25983                      was found and increased in priority.  This is to prevent
25984                      increasing the priority of multiple loads */
25985                   load_store_pendulum--;
25986
25987                   break;
25988                 }
25989               pos--;
25990             }
25991         }
25992       else if (load_store_pendulum == -1)
25993         {
25994           /* A store has been issued in this cycle.  Scan the ready list for
25995              another store to issue with it, preferring a store to an adjacent
25996              memory location */
25997           int first_store_pos = -1;
25998
25999           pos = *pn_ready-1;
26000
26001           while (pos >= 0)
26002             {
26003               if (is_store_insn (ready[pos], &str_mem))
26004                 {
26005                   rtx str_mem2;
26006                   /* Maintain the index of the first store found on the
26007                      list */
26008                   if (first_store_pos == -1)
26009                     first_store_pos = pos;
26010
26011                   if (is_store_insn (last_scheduled_insn, &str_mem2)
26012                       && adjacent_mem_locations (str_mem, str_mem2))
26013                     {
26014                       /* Found an adjacent store.  Move it to the head of the
26015                          ready list, and adjust it's priority so that it is
26016                          more likely to stay there */
26017                       tmp = ready[pos];
26018                       for (i=pos; i<*pn_ready-1; i++)
26019                         ready[i] = ready[i + 1];
26020                       ready[*pn_ready-1] = tmp;
26021
26022                       if (!sel_sched_p () && INSN_PRIORITY_KNOWN (tmp))
26023                         INSN_PRIORITY (tmp)++;
26024
26025                       first_store_pos = -1;
26026
26027                       break;
26028                     };
26029                 }
26030               pos--;
26031             }
26032
26033           if (first_store_pos >= 0)
26034             {
26035               /* An adjacent store wasn't found, but a non-adjacent store was,
26036                  so move the non-adjacent store to the front of the ready
26037                  list, and adjust its priority so that it is more likely to
26038                  stay there. */
26039               tmp = ready[first_store_pos];
26040               for (i=first_store_pos; i<*pn_ready-1; i++)
26041                 ready[i] = ready[i + 1];
26042               ready[*pn_ready-1] = tmp;
26043               if (!sel_sched_p () && INSN_PRIORITY_KNOWN (tmp))
26044                 INSN_PRIORITY (tmp)++;
26045             }
26046         }
26047       else if (load_store_pendulum == 2)
26048        {
26049            /* Two loads have been issued in this cycle.  Increase the priority
26050               of the first store in the ready list to favor it for issuing in
26051               the next cycle. */
26052           pos = *pn_ready-1;
26053
26054           while (pos >= 0)
26055             {
26056               if (is_store_insn (ready[pos], &str_mem)
26057                   && !sel_sched_p ()
26058                   && INSN_PRIORITY_KNOWN (ready[pos]))
26059                 {
26060                   INSN_PRIORITY (ready[pos])++;
26061
26062                   /* Adjust the pendulum to account for the fact that a store
26063                      was found and increased in priority.  This is to prevent
26064                      increasing the priority of multiple stores */
26065                   load_store_pendulum++;
26066
26067                   break;
26068                 }
26069               pos--;
26070             }
26071         }
26072     }
26073
26074   /* Do Power9 dependent reordering if necessary.  */
26075   if (rs6000_tune == PROCESSOR_POWER9 && last_scheduled_insn
26076       && recog_memoized (last_scheduled_insn) >= 0)
26077     return power9_sched_reorder2 (ready, *pn_ready - 1);
26078
26079   return cached_can_issue_more;
26080 }
26081
26082 /* Return whether the presence of INSN causes a dispatch group termination
26083    of group WHICH_GROUP.
26084
26085    If WHICH_GROUP == current_group, this function will return true if INSN
26086    causes the termination of the current group (i.e, the dispatch group to
26087    which INSN belongs). This means that INSN will be the last insn in the
26088    group it belongs to.
26089
26090    If WHICH_GROUP == previous_group, this function will return true if INSN
26091    causes the termination of the previous group (i.e, the dispatch group that
26092    precedes the group to which INSN belongs).  This means that INSN will be
26093    the first insn in the group it belongs to).  */
26094
26095 static bool
26096 insn_terminates_group_p (rtx_insn *insn, enum group_termination which_group)
26097 {
26098   bool first, last;
26099
26100   if (! insn)
26101     return false;
26102
26103   first = insn_must_be_first_in_group (insn);
26104   last = insn_must_be_last_in_group (insn);
26105
26106   if (first && last)
26107     return true;
26108
26109   if (which_group == current_group)
26110     return last;
26111   else if (which_group == previous_group)
26112     return first;
26113
26114   return false;
26115 }
26116
26117
26118 static bool
26119 insn_must_be_first_in_group (rtx_insn *insn)
26120 {
26121   enum attr_type type;
26122
26123   if (!insn
26124       || NOTE_P (insn)
26125       || DEBUG_INSN_P (insn)
26126       || GET_CODE (PATTERN (insn)) == USE
26127       || GET_CODE (PATTERN (insn)) == CLOBBER)
26128     return false;
26129
26130   switch (rs6000_tune)
26131     {
26132     case PROCESSOR_POWER5:
26133       if (is_cracked_insn (insn))
26134         return true;
26135       /* FALLTHRU */
26136     case PROCESSOR_POWER4:
26137       if (is_microcoded_insn (insn))
26138         return true;
26139
26140       if (!rs6000_sched_groups)
26141         return false;
26142
26143       type = get_attr_type (insn);
26144
26145       switch (type)
26146         {
26147         case TYPE_MFCR:
26148         case TYPE_MFCRF:
26149         case TYPE_MTCR:
26150         case TYPE_CR_LOGICAL:
26151         case TYPE_MTJMPR:
26152         case TYPE_MFJMPR:
26153         case TYPE_DIV:
26154         case TYPE_LOAD_L:
26155         case TYPE_STORE_C:
26156         case TYPE_ISYNC:
26157         case TYPE_SYNC:
26158           return true;
26159         default:
26160           break;
26161         }
26162       break;
26163     case PROCESSOR_POWER6:
26164       type = get_attr_type (insn);
26165
26166       switch (type)
26167         {
26168         case TYPE_EXTS:
26169         case TYPE_CNTLZ:
26170         case TYPE_TRAP:
26171         case TYPE_MUL:
26172         case TYPE_INSERT:
26173         case TYPE_FPCOMPARE:
26174         case TYPE_MFCR:
26175         case TYPE_MTCR:
26176         case TYPE_MFJMPR:
26177         case TYPE_MTJMPR:
26178         case TYPE_ISYNC:
26179         case TYPE_SYNC:
26180         case TYPE_LOAD_L:
26181         case TYPE_STORE_C:
26182           return true;
26183         case TYPE_SHIFT:
26184           if (get_attr_dot (insn) == DOT_NO
26185               || get_attr_var_shift (insn) == VAR_SHIFT_NO)
26186             return true;
26187           else
26188             break;
26189         case TYPE_DIV:
26190           if (get_attr_size (insn) == SIZE_32)
26191             return true;
26192           else
26193             break;
26194         case TYPE_LOAD:
26195         case TYPE_STORE:
26196         case TYPE_FPLOAD:
26197         case TYPE_FPSTORE:
26198           if (get_attr_update (insn) == UPDATE_YES)
26199             return true;
26200           else
26201             break;
26202         default:
26203           break;
26204         }
26205       break;
26206     case PROCESSOR_POWER7:
26207       type = get_attr_type (insn);
26208
26209       switch (type)
26210         {
26211         case TYPE_CR_LOGICAL:
26212         case TYPE_MFCR:
26213         case TYPE_MFCRF:
26214         case TYPE_MTCR:
26215         case TYPE_DIV:
26216         case TYPE_ISYNC:
26217         case TYPE_LOAD_L:
26218         case TYPE_STORE_C:
26219         case TYPE_MFJMPR:
26220         case TYPE_MTJMPR:
26221           return true;
26222         case TYPE_MUL:
26223         case TYPE_SHIFT:
26224         case TYPE_EXTS:
26225           if (get_attr_dot (insn) == DOT_YES)
26226             return true;
26227           else
26228             break;
26229         case TYPE_LOAD:
26230           if (get_attr_sign_extend (insn) == SIGN_EXTEND_YES
26231               || get_attr_update (insn) == UPDATE_YES)
26232             return true;
26233           else
26234             break;
26235         case TYPE_STORE:
26236         case TYPE_FPLOAD:
26237         case TYPE_FPSTORE:
26238           if (get_attr_update (insn) == UPDATE_YES)
26239             return true;
26240           else
26241             break;
26242         default:
26243           break;
26244         }
26245       break;
26246     case PROCESSOR_POWER8:
26247       type = get_attr_type (insn);
26248
26249       switch (type)
26250         {
26251         case TYPE_CR_LOGICAL:
26252         case TYPE_MFCR:
26253         case TYPE_MFCRF:
26254         case TYPE_MTCR:
26255         case TYPE_SYNC:
26256         case TYPE_ISYNC:
26257         case TYPE_LOAD_L:
26258         case TYPE_STORE_C:
26259         case TYPE_VECSTORE:
26260         case TYPE_MFJMPR:
26261         case TYPE_MTJMPR:
26262           return true;
26263         case TYPE_SHIFT:
26264         case TYPE_EXTS:
26265         case TYPE_MUL:
26266           if (get_attr_dot (insn) == DOT_YES)
26267             return true;
26268           else
26269             break;
26270         case TYPE_LOAD:
26271           if (get_attr_sign_extend (insn) == SIGN_EXTEND_YES
26272               || get_attr_update (insn) == UPDATE_YES)
26273             return true;
26274           else
26275             break;
26276         case TYPE_STORE:
26277           if (get_attr_update (insn) == UPDATE_YES
26278               && get_attr_indexed (insn) == INDEXED_YES)
26279             return true;
26280           else
26281             break;
26282         default:
26283           break;
26284         }
26285       break;
26286     default:
26287       break;
26288     }
26289
26290   return false;
26291 }
26292
26293 static bool
26294 insn_must_be_last_in_group (rtx_insn *insn)
26295 {
26296   enum attr_type type;
26297
26298   if (!insn
26299       || NOTE_P (insn)
26300       || DEBUG_INSN_P (insn)
26301       || GET_CODE (PATTERN (insn)) == USE
26302       || GET_CODE (PATTERN (insn)) == CLOBBER)
26303     return false;
26304
26305   switch (rs6000_tune) {
26306   case PROCESSOR_POWER4:
26307   case PROCESSOR_POWER5:
26308     if (is_microcoded_insn (insn))
26309       return true;
26310
26311     if (is_branch_slot_insn (insn))
26312       return true;
26313
26314     break;
26315   case PROCESSOR_POWER6:
26316     type = get_attr_type (insn);
26317
26318     switch (type)
26319       {
26320       case TYPE_EXTS:
26321       case TYPE_CNTLZ:
26322       case TYPE_TRAP:
26323       case TYPE_MUL:
26324       case TYPE_FPCOMPARE:
26325       case TYPE_MFCR:
26326       case TYPE_MTCR:
26327       case TYPE_MFJMPR:
26328       case TYPE_MTJMPR:
26329       case TYPE_ISYNC:
26330       case TYPE_SYNC:
26331       case TYPE_LOAD_L:
26332       case TYPE_STORE_C:
26333         return true;
26334       case TYPE_SHIFT:
26335         if (get_attr_dot (insn) == DOT_NO
26336             || get_attr_var_shift (insn) == VAR_SHIFT_NO)
26337           return true;
26338         else
26339           break;
26340       case TYPE_DIV:
26341         if (get_attr_size (insn) == SIZE_32)
26342           return true;
26343         else
26344           break;
26345       default:
26346         break;
26347     }
26348     break;
26349   case PROCESSOR_POWER7:
26350     type = get_attr_type (insn);
26351
26352     switch (type)
26353       {
26354       case TYPE_ISYNC:
26355       case TYPE_SYNC:
26356       case TYPE_LOAD_L:
26357       case TYPE_STORE_C:
26358         return true;
26359       case TYPE_LOAD:
26360         if (get_attr_sign_extend (insn) == SIGN_EXTEND_YES
26361             && get_attr_update (insn) == UPDATE_YES)
26362           return true;
26363         else
26364           break;
26365       case TYPE_STORE:
26366         if (get_attr_update (insn) == UPDATE_YES
26367             && get_attr_indexed (insn) == INDEXED_YES)
26368           return true;
26369         else
26370           break;
26371       default:
26372         break;
26373     }
26374     break;
26375   case PROCESSOR_POWER8:
26376     type = get_attr_type (insn);
26377
26378     switch (type)
26379       {
26380       case TYPE_MFCR:
26381       case TYPE_MTCR:
26382       case TYPE_ISYNC:
26383       case TYPE_SYNC:
26384       case TYPE_LOAD_L:
26385       case TYPE_STORE_C:
26386         return true;
26387       case TYPE_LOAD:
26388         if (get_attr_sign_extend (insn) == SIGN_EXTEND_YES
26389             && get_attr_update (insn) == UPDATE_YES)
26390           return true;
26391         else
26392           break;
26393       case TYPE_STORE:
26394         if (get_attr_update (insn) == UPDATE_YES
26395             && get_attr_indexed (insn) == INDEXED_YES)
26396           return true;
26397         else
26398           break;
26399       default:
26400         break;
26401     }
26402     break;
26403   default:
26404     break;
26405   }
26406
26407   return false;
26408 }
26409
26410 /* Return true if it is recommended to keep NEXT_INSN "far" (in a separate
26411    dispatch group) from the insns in GROUP_INSNS.  Return false otherwise.  */
26412
26413 static bool
26414 is_costly_group (rtx *group_insns, rtx next_insn)
26415 {
26416   int i;
26417   int issue_rate = rs6000_issue_rate ();
26418
26419   for (i = 0; i < issue_rate; i++)
26420     {
26421       sd_iterator_def sd_it;
26422       dep_t dep;
26423       rtx insn = group_insns[i];
26424
26425       if (!insn)
26426         continue;
26427
26428       FOR_EACH_DEP (insn, SD_LIST_RES_FORW, sd_it, dep)
26429         {
26430           rtx next = DEP_CON (dep);
26431
26432           if (next == next_insn
26433               && rs6000_is_costly_dependence (dep, dep_cost (dep), 0))
26434             return true;
26435         }
26436     }
26437
26438   return false;
26439 }
26440
26441 /* Utility of the function redefine_groups.
26442    Check if it is too costly to schedule NEXT_INSN together with GROUP_INSNS
26443    in the same dispatch group.  If so, insert nops before NEXT_INSN, in order
26444    to keep it "far" (in a separate group) from GROUP_INSNS, following
26445    one of the following schemes, depending on the value of the flag
26446    -minsert_sched_nops = X:
26447    (1) X == sched_finish_regroup_exact: insert exactly as many nops as needed
26448        in order to force NEXT_INSN into a separate group.
26449    (2) X < sched_finish_regroup_exact: insert exactly X nops.
26450    GROUP_END, CAN_ISSUE_MORE and GROUP_COUNT record the state after nop
26451    insertion (has a group just ended, how many vacant issue slots remain in the
26452    last group, and how many dispatch groups were encountered so far).  */
26453
26454 static int
26455 force_new_group (int sched_verbose, FILE *dump, rtx *group_insns,
26456                  rtx_insn *next_insn, bool *group_end, int can_issue_more,
26457                  int *group_count)
26458 {
26459   rtx nop;
26460   bool force;
26461   int issue_rate = rs6000_issue_rate ();
26462   bool end = *group_end;
26463   int i;
26464
26465   if (next_insn == NULL_RTX || DEBUG_INSN_P (next_insn))
26466     return can_issue_more;
26467
26468   if (rs6000_sched_insert_nops > sched_finish_regroup_exact)
26469     return can_issue_more;
26470
26471   force = is_costly_group (group_insns, next_insn);
26472   if (!force)
26473     return can_issue_more;
26474
26475   if (sched_verbose > 6)
26476     fprintf (dump,"force: group count = %d, can_issue_more = %d\n",
26477              *group_count ,can_issue_more);
26478
26479   if (rs6000_sched_insert_nops == sched_finish_regroup_exact)
26480     {
26481       if (*group_end)
26482         can_issue_more = 0;
26483
26484       /* Since only a branch can be issued in the last issue_slot, it is
26485          sufficient to insert 'can_issue_more - 1' nops if next_insn is not
26486          a branch. If next_insn is a branch, we insert 'can_issue_more' nops;
26487          in this case the last nop will start a new group and the branch
26488          will be forced to the new group.  */
26489       if (can_issue_more && !is_branch_slot_insn (next_insn))
26490         can_issue_more--;
26491
26492       /* Do we have a special group ending nop? */
26493       if (rs6000_tune == PROCESSOR_POWER6 || rs6000_tune == PROCESSOR_POWER7
26494           || rs6000_tune == PROCESSOR_POWER8)
26495         {
26496           nop = gen_group_ending_nop ();
26497           emit_insn_before (nop, next_insn);
26498           can_issue_more = 0;
26499         }
26500       else
26501         while (can_issue_more > 0)
26502           {
26503             nop = gen_nop ();
26504             emit_insn_before (nop, next_insn);
26505             can_issue_more--;
26506           }
26507
26508       *group_end = true;
26509       return 0;
26510     }
26511
26512   if (rs6000_sched_insert_nops < sched_finish_regroup_exact)
26513     {
26514       int n_nops = rs6000_sched_insert_nops;
26515
26516       /* Nops can't be issued from the branch slot, so the effective
26517          issue_rate for nops is 'issue_rate - 1'.  */
26518       if (can_issue_more == 0)
26519         can_issue_more = issue_rate;
26520       can_issue_more--;
26521       if (can_issue_more == 0)
26522         {
26523           can_issue_more = issue_rate - 1;
26524           (*group_count)++;
26525           end = true;
26526           for (i = 0; i < issue_rate; i++)
26527             {
26528               group_insns[i] = 0;
26529             }
26530         }
26531
26532       while (n_nops > 0)
26533         {
26534           nop = gen_nop ();
26535           emit_insn_before (nop, next_insn);
26536           if (can_issue_more == issue_rate - 1) /* new group begins */
26537             end = false;
26538           can_issue_more--;
26539           if (can_issue_more == 0)
26540             {
26541               can_issue_more = issue_rate - 1;
26542               (*group_count)++;
26543               end = true;
26544               for (i = 0; i < issue_rate; i++)
26545                 {
26546                   group_insns[i] = 0;
26547                 }
26548             }
26549           n_nops--;
26550         }
26551
26552       /* Scale back relative to 'issue_rate' (instead of 'issue_rate - 1').  */
26553       can_issue_more++;
26554
26555       /* Is next_insn going to start a new group?  */
26556       *group_end
26557         = (end
26558            || (can_issue_more == 1 && !is_branch_slot_insn (next_insn))
26559            || (can_issue_more <= 2 && is_cracked_insn (next_insn))
26560            || (can_issue_more < issue_rate &&
26561                insn_terminates_group_p (next_insn, previous_group)));
26562       if (*group_end && end)
26563         (*group_count)--;
26564
26565       if (sched_verbose > 6)
26566         fprintf (dump, "done force: group count = %d, can_issue_more = %d\n",
26567                  *group_count, can_issue_more);
26568       return can_issue_more;
26569     }
26570
26571   return can_issue_more;
26572 }
26573
26574 /* This function tries to synch the dispatch groups that the compiler "sees"
26575    with the dispatch groups that the processor dispatcher is expected to
26576    form in practice.  It tries to achieve this synchronization by forcing the
26577    estimated processor grouping on the compiler (as opposed to the function
26578    'pad_goups' which tries to force the scheduler's grouping on the processor).
26579
26580    The function scans the insn sequence between PREV_HEAD_INSN and TAIL and
26581    examines the (estimated) dispatch groups that will be formed by the processor
26582    dispatcher.  It marks these group boundaries to reflect the estimated
26583    processor grouping, overriding the grouping that the scheduler had marked.
26584    Depending on the value of the flag '-minsert-sched-nops' this function can
26585    force certain insns into separate groups or force a certain distance between
26586    them by inserting nops, for example, if there exists a "costly dependence"
26587    between the insns.
26588
26589    The function estimates the group boundaries that the processor will form as
26590    follows:  It keeps track of how many vacant issue slots are available after
26591    each insn.  A subsequent insn will start a new group if one of the following
26592    4 cases applies:
26593    - no more vacant issue slots remain in the current dispatch group.
26594    - only the last issue slot, which is the branch slot, is vacant, but the next
26595      insn is not a branch.
26596    - only the last 2 or less issue slots, including the branch slot, are vacant,
26597      which means that a cracked insn (which occupies two issue slots) can't be
26598      issued in this group.
26599    - less than 'issue_rate' slots are vacant, and the next insn always needs to
26600      start a new group.  */
26601
26602 static int
26603 redefine_groups (FILE *dump, int sched_verbose, rtx_insn *prev_head_insn,
26604                  rtx_insn *tail)
26605 {
26606   rtx_insn *insn, *next_insn;
26607   int issue_rate;
26608   int can_issue_more;
26609   int slot, i;
26610   bool group_end;
26611   int group_count = 0;
26612   rtx *group_insns;
26613
26614   /* Initialize.  */
26615   issue_rate = rs6000_issue_rate ();
26616   group_insns = XALLOCAVEC (rtx, issue_rate);
26617   for (i = 0; i < issue_rate; i++)
26618     {
26619       group_insns[i] = 0;
26620     }
26621   can_issue_more = issue_rate;
26622   slot = 0;
26623   insn = get_next_active_insn (prev_head_insn, tail);
26624   group_end = false;
26625
26626   while (insn != NULL_RTX)
26627     {
26628       slot = (issue_rate - can_issue_more);
26629       group_insns[slot] = insn;
26630       can_issue_more =
26631         rs6000_variable_issue (dump, sched_verbose, insn, can_issue_more);
26632       if (insn_terminates_group_p (insn, current_group))
26633         can_issue_more = 0;
26634
26635       next_insn = get_next_active_insn (insn, tail);
26636       if (next_insn == NULL_RTX)
26637         return group_count + 1;
26638
26639       /* Is next_insn going to start a new group?  */
26640       group_end
26641         = (can_issue_more == 0
26642            || (can_issue_more == 1 && !is_branch_slot_insn (next_insn))
26643            || (can_issue_more <= 2 && is_cracked_insn (next_insn))
26644            || (can_issue_more < issue_rate &&
26645                insn_terminates_group_p (next_insn, previous_group)));
26646
26647       can_issue_more = force_new_group (sched_verbose, dump, group_insns,
26648                                         next_insn, &group_end, can_issue_more,
26649                                         &group_count);
26650
26651       if (group_end)
26652         {
26653           group_count++;
26654           can_issue_more = 0;
26655           for (i = 0; i < issue_rate; i++)
26656             {
26657               group_insns[i] = 0;
26658             }
26659         }
26660
26661       if (GET_MODE (next_insn) == TImode && can_issue_more)
26662         PUT_MODE (next_insn, VOIDmode);
26663       else if (!can_issue_more && GET_MODE (next_insn) != TImode)
26664         PUT_MODE (next_insn, TImode);
26665
26666       insn = next_insn;
26667       if (can_issue_more == 0)
26668         can_issue_more = issue_rate;
26669     } /* while */
26670
26671   return group_count;
26672 }
26673
26674 /* Scan the insn sequence between PREV_HEAD_INSN and TAIL and examine the
26675    dispatch group boundaries that the scheduler had marked.  Pad with nops
26676    any dispatch groups which have vacant issue slots, in order to force the
26677    scheduler's grouping on the processor dispatcher.  The function
26678    returns the number of dispatch groups found.  */
26679
26680 static int
26681 pad_groups (FILE *dump, int sched_verbose, rtx_insn *prev_head_insn,
26682             rtx_insn *tail)
26683 {
26684   rtx_insn *insn, *next_insn;
26685   rtx nop;
26686   int issue_rate;
26687   int can_issue_more;
26688   int group_end;
26689   int group_count = 0;
26690
26691   /* Initialize issue_rate.  */
26692   issue_rate = rs6000_issue_rate ();
26693   can_issue_more = issue_rate;
26694
26695   insn = get_next_active_insn (prev_head_insn, tail);
26696   next_insn = get_next_active_insn (insn, tail);
26697
26698   while (insn != NULL_RTX)
26699     {
26700       can_issue_more =
26701         rs6000_variable_issue (dump, sched_verbose, insn, can_issue_more);
26702
26703       group_end = (next_insn == NULL_RTX || GET_MODE (next_insn) == TImode);
26704
26705       if (next_insn == NULL_RTX)
26706         break;
26707
26708       if (group_end)
26709         {
26710           /* If the scheduler had marked group termination at this location
26711              (between insn and next_insn), and neither insn nor next_insn will
26712              force group termination, pad the group with nops to force group
26713              termination.  */
26714           if (can_issue_more
26715               && (rs6000_sched_insert_nops == sched_finish_pad_groups)
26716               && !insn_terminates_group_p (insn, current_group)
26717               && !insn_terminates_group_p (next_insn, previous_group))
26718             {
26719               if (!is_branch_slot_insn (next_insn))
26720                 can_issue_more--;
26721
26722               while (can_issue_more)
26723                 {
26724                   nop = gen_nop ();
26725                   emit_insn_before (nop, next_insn);
26726                   can_issue_more--;
26727                 }
26728             }
26729
26730           can_issue_more = issue_rate;
26731           group_count++;
26732         }
26733
26734       insn = next_insn;
26735       next_insn = get_next_active_insn (insn, tail);
26736     }
26737
26738   return group_count;
26739 }
26740
26741 /* We're beginning a new block.  Initialize data structures as necessary.  */
26742
26743 static void
26744 rs6000_sched_init (FILE *dump ATTRIBUTE_UNUSED,
26745                      int sched_verbose ATTRIBUTE_UNUSED,
26746                      int max_ready ATTRIBUTE_UNUSED)
26747 {
26748   last_scheduled_insn = NULL;
26749   load_store_pendulum = 0;
26750   divide_cnt = 0;
26751   vec_pairing = 0;
26752 }
26753
26754 /* The following function is called at the end of scheduling BB.
26755    After reload, it inserts nops at insn group bundling.  */
26756
26757 static void
26758 rs6000_sched_finish (FILE *dump, int sched_verbose)
26759 {
26760   int n_groups;
26761
26762   if (sched_verbose)
26763     fprintf (dump, "=== Finishing schedule.\n");
26764
26765   if (reload_completed && rs6000_sched_groups)
26766     {
26767       /* Do not run sched_finish hook when selective scheduling enabled.  */
26768       if (sel_sched_p ())
26769         return;
26770
26771       if (rs6000_sched_insert_nops == sched_finish_none)
26772         return;
26773
26774       if (rs6000_sched_insert_nops == sched_finish_pad_groups)
26775         n_groups = pad_groups (dump, sched_verbose,
26776                                current_sched_info->prev_head,
26777                                current_sched_info->next_tail);
26778       else
26779         n_groups = redefine_groups (dump, sched_verbose,
26780                                     current_sched_info->prev_head,
26781                                     current_sched_info->next_tail);
26782
26783       if (sched_verbose >= 6)
26784         {
26785           fprintf (dump, "ngroups = %d\n", n_groups);
26786           print_rtl (dump, current_sched_info->prev_head);
26787           fprintf (dump, "Done finish_sched\n");
26788         }
26789     }
26790 }
26791
26792 struct rs6000_sched_context
26793 {
26794   short cached_can_issue_more;
26795   rtx_insn *last_scheduled_insn;
26796   int load_store_pendulum;
26797   int divide_cnt;
26798   int vec_pairing;
26799 };
26800
26801 typedef struct rs6000_sched_context rs6000_sched_context_def;
26802 typedef rs6000_sched_context_def *rs6000_sched_context_t;
26803
26804 /* Allocate store for new scheduling context.  */
26805 static void *
26806 rs6000_alloc_sched_context (void)
26807 {
26808   return xmalloc (sizeof (rs6000_sched_context_def));
26809 }
26810
26811 /* If CLEAN_P is true then initializes _SC with clean data,
26812    and from the global context otherwise.  */
26813 static void
26814 rs6000_init_sched_context (void *_sc, bool clean_p)
26815 {
26816   rs6000_sched_context_t sc = (rs6000_sched_context_t) _sc;
26817
26818   if (clean_p)
26819     {
26820       sc->cached_can_issue_more = 0;
26821       sc->last_scheduled_insn = NULL;
26822       sc->load_store_pendulum = 0;
26823       sc->divide_cnt = 0;
26824       sc->vec_pairing = 0;
26825     }
26826   else
26827     {
26828       sc->cached_can_issue_more = cached_can_issue_more;
26829       sc->last_scheduled_insn = last_scheduled_insn;
26830       sc->load_store_pendulum = load_store_pendulum;
26831       sc->divide_cnt = divide_cnt;
26832       sc->vec_pairing = vec_pairing;
26833     }
26834 }
26835
26836 /* Sets the global scheduling context to the one pointed to by _SC.  */
26837 static void
26838 rs6000_set_sched_context (void *_sc)
26839 {
26840   rs6000_sched_context_t sc = (rs6000_sched_context_t) _sc;
26841
26842   gcc_assert (sc != NULL);
26843
26844   cached_can_issue_more = sc->cached_can_issue_more;
26845   last_scheduled_insn = sc->last_scheduled_insn;
26846   load_store_pendulum = sc->load_store_pendulum;
26847   divide_cnt = sc->divide_cnt;
26848   vec_pairing = sc->vec_pairing;
26849 }
26850
26851 /* Free _SC.  */
26852 static void
26853 rs6000_free_sched_context (void *_sc)
26854 {
26855   gcc_assert (_sc != NULL);
26856
26857   free (_sc);
26858 }
26859
26860 static bool
26861 rs6000_sched_can_speculate_insn (rtx_insn *insn)
26862 {
26863   switch (get_attr_type (insn))
26864     {
26865     case TYPE_DIV:
26866     case TYPE_SDIV:
26867     case TYPE_DDIV:
26868     case TYPE_VECDIV:
26869     case TYPE_SSQRT:
26870     case TYPE_DSQRT:
26871       return false;
26872
26873     default:
26874       return true;
26875   }
26876 }
26877 \f
26878 /* Length in units of the trampoline for entering a nested function.  */
26879
26880 int
26881 rs6000_trampoline_size (void)
26882 {
26883   int ret = 0;
26884
26885   switch (DEFAULT_ABI)
26886     {
26887     default:
26888       gcc_unreachable ();
26889
26890     case ABI_AIX:
26891       ret = (TARGET_32BIT) ? 12 : 24;
26892       break;
26893
26894     case ABI_ELFv2:
26895       gcc_assert (!TARGET_32BIT);
26896       ret = 32;
26897       break;
26898
26899     case ABI_DARWIN:
26900     case ABI_V4:
26901       ret = (TARGET_32BIT) ? 40 : 48;
26902       break;
26903     }
26904
26905   return ret;
26906 }
26907
26908 /* Emit RTL insns to initialize the variable parts of a trampoline.
26909    FNADDR is an RTX for the address of the function's pure code.
26910    CXT is an RTX for the static chain value for the function.  */
26911
26912 static void
26913 rs6000_trampoline_init (rtx m_tramp, tree fndecl, rtx cxt)
26914 {
26915   int regsize = (TARGET_32BIT) ? 4 : 8;
26916   rtx fnaddr = XEXP (DECL_RTL (fndecl), 0);
26917   rtx ctx_reg = force_reg (Pmode, cxt);
26918   rtx addr = force_reg (Pmode, XEXP (m_tramp, 0));
26919
26920   switch (DEFAULT_ABI)
26921     {
26922     default:
26923       gcc_unreachable ();
26924
26925     /* Under AIX, just build the 3 word function descriptor */
26926     case ABI_AIX:
26927       {
26928         rtx fnmem, fn_reg, toc_reg;
26929
26930         if (!TARGET_POINTERS_TO_NESTED_FUNCTIONS)
26931           error ("you cannot take the address of a nested function if you use "
26932                  "the %qs option", "-mno-pointers-to-nested-functions");
26933
26934         fnmem = gen_const_mem (Pmode, force_reg (Pmode, fnaddr));
26935         fn_reg = gen_reg_rtx (Pmode);
26936         toc_reg = gen_reg_rtx (Pmode);
26937
26938   /* Macro to shorten the code expansions below.  */
26939 # define MEM_PLUS(MEM, OFFSET) adjust_address (MEM, Pmode, OFFSET)
26940
26941         m_tramp = replace_equiv_address (m_tramp, addr);
26942
26943         emit_move_insn (fn_reg, MEM_PLUS (fnmem, 0));
26944         emit_move_insn (toc_reg, MEM_PLUS (fnmem, regsize));
26945         emit_move_insn (MEM_PLUS (m_tramp, 0), fn_reg);
26946         emit_move_insn (MEM_PLUS (m_tramp, regsize), toc_reg);
26947         emit_move_insn (MEM_PLUS (m_tramp, 2*regsize), ctx_reg);
26948
26949 # undef MEM_PLUS
26950       }
26951       break;
26952
26953     /* Under V.4/eabi/darwin, __trampoline_setup does the real work.  */
26954     case ABI_ELFv2:
26955     case ABI_DARWIN:
26956     case ABI_V4:
26957       emit_library_call (gen_rtx_SYMBOL_REF (Pmode, "__trampoline_setup"),
26958                          LCT_NORMAL, VOIDmode,
26959                          addr, Pmode,
26960                          GEN_INT (rs6000_trampoline_size ()), SImode,
26961                          fnaddr, Pmode,
26962                          ctx_reg, Pmode);
26963       break;
26964     }
26965 }
26966
26967 \f
26968 /* Returns TRUE iff the target attribute indicated by ATTR_ID takes a plain
26969    identifier as an argument, so the front end shouldn't look it up.  */
26970
26971 static bool
26972 rs6000_attribute_takes_identifier_p (const_tree attr_id)
26973 {
26974   return is_attribute_p ("altivec", attr_id);
26975 }
26976
26977 /* Handle the "altivec" attribute.  The attribute may have
26978    arguments as follows:
26979
26980         __attribute__((altivec(vector__)))
26981         __attribute__((altivec(pixel__)))       (always followed by 'unsigned short')
26982         __attribute__((altivec(bool__)))        (always followed by 'unsigned')
26983
26984   and may appear more than once (e.g., 'vector bool char') in a
26985   given declaration.  */
26986
26987 static tree
26988 rs6000_handle_altivec_attribute (tree *node,
26989                                  tree name ATTRIBUTE_UNUSED,
26990                                  tree args,
26991                                  int flags ATTRIBUTE_UNUSED,
26992                                  bool *no_add_attrs)
26993 {
26994   tree type = *node, result = NULL_TREE;
26995   machine_mode mode;
26996   int unsigned_p;
26997   char altivec_type
26998     = ((args && TREE_CODE (args) == TREE_LIST && TREE_VALUE (args)
26999         && TREE_CODE (TREE_VALUE (args)) == IDENTIFIER_NODE)
27000        ? *IDENTIFIER_POINTER (TREE_VALUE (args))
27001        : '?');
27002
27003   while (POINTER_TYPE_P (type)
27004          || TREE_CODE (type) == FUNCTION_TYPE
27005          || TREE_CODE (type) == METHOD_TYPE
27006          || TREE_CODE (type) == ARRAY_TYPE)
27007     type = TREE_TYPE (type);
27008
27009   mode = TYPE_MODE (type);
27010
27011   /* Check for invalid AltiVec type qualifiers.  */
27012   if (type == long_double_type_node)
27013     error ("use of %<long double%> in AltiVec types is invalid");
27014   else if (type == boolean_type_node)
27015     error ("use of boolean types in AltiVec types is invalid");
27016   else if (TREE_CODE (type) == COMPLEX_TYPE)
27017     error ("use of %<complex%> in AltiVec types is invalid");
27018   else if (DECIMAL_FLOAT_MODE_P (mode))
27019     error ("use of decimal floating point types in AltiVec types is invalid");
27020   else if (!TARGET_VSX)
27021     {
27022       if (type == long_unsigned_type_node || type == long_integer_type_node)
27023         {
27024           if (TARGET_64BIT)
27025             error ("use of %<long%> in AltiVec types is invalid for "
27026                    "64-bit code without %qs", "-mvsx");
27027           else if (rs6000_warn_altivec_long)
27028             warning (0, "use of %<long%> in AltiVec types is deprecated; "
27029                      "use %<int%>");
27030         }
27031       else if (type == long_long_unsigned_type_node
27032                || type == long_long_integer_type_node)
27033         error ("use of %<long long%> in AltiVec types is invalid without %qs",
27034                "-mvsx");
27035       else if (type == double_type_node)
27036         error ("use of %<double%> in AltiVec types is invalid without %qs",
27037                "-mvsx");
27038     }
27039
27040   switch (altivec_type)
27041     {
27042     case 'v':
27043       unsigned_p = TYPE_UNSIGNED (type);
27044       switch (mode)
27045         {
27046         case E_TImode:
27047           result = (unsigned_p ? unsigned_V1TI_type_node : V1TI_type_node);
27048           break;
27049         case E_DImode:
27050           result = (unsigned_p ? unsigned_V2DI_type_node : V2DI_type_node);
27051           break;
27052         case E_SImode:
27053           result = (unsigned_p ? unsigned_V4SI_type_node : V4SI_type_node);
27054           break;
27055         case E_HImode:
27056           result = (unsigned_p ? unsigned_V8HI_type_node : V8HI_type_node);
27057           break;
27058         case E_QImode:
27059           result = (unsigned_p ? unsigned_V16QI_type_node : V16QI_type_node);
27060           break;
27061         case E_SFmode: result = V4SF_type_node; break;
27062         case E_DFmode: result = V2DF_type_node; break;
27063           /* If the user says 'vector int bool', we may be handed the 'bool'
27064              attribute _before_ the 'vector' attribute, and so select the
27065              proper type in the 'b' case below.  */
27066         case E_V4SImode: case E_V8HImode: case E_V16QImode: case E_V4SFmode:
27067         case E_V2DImode: case E_V2DFmode:
27068           result = type;
27069         default: break;
27070         }
27071       break;
27072     case 'b':
27073       switch (mode)
27074         {
27075         case E_DImode: case E_V2DImode: result = bool_V2DI_type_node; break;
27076         case E_SImode: case E_V4SImode: result = bool_V4SI_type_node; break;
27077         case E_HImode: case E_V8HImode: result = bool_V8HI_type_node; break;
27078         case E_QImode: case E_V16QImode: result = bool_V16QI_type_node;
27079         default: break;
27080         }
27081       break;
27082     case 'p':
27083       switch (mode)
27084         {
27085         case E_V8HImode: result = pixel_V8HI_type_node;
27086         default: break;
27087         }
27088     default: break;
27089     }
27090
27091   /* Propagate qualifiers attached to the element type
27092      onto the vector type.  */
27093   if (result && result != type && TYPE_QUALS (type))
27094     result = build_qualified_type (result, TYPE_QUALS (type));
27095
27096   *no_add_attrs = true;  /* No need to hang on to the attribute.  */
27097
27098   if (result)
27099     *node = lang_hooks.types.reconstruct_complex_type (*node, result);
27100
27101   return NULL_TREE;
27102 }
27103
27104 /* AltiVec defines five built-in scalar types that serve as vector
27105    elements; we must teach the compiler how to mangle them.  The 128-bit
27106    floating point mangling is target-specific as well.  */
27107
27108 static const char *
27109 rs6000_mangle_type (const_tree type)
27110 {
27111   type = TYPE_MAIN_VARIANT (type);
27112
27113   if (TREE_CODE (type) != VOID_TYPE && TREE_CODE (type) != BOOLEAN_TYPE
27114       && TREE_CODE (type) != INTEGER_TYPE && TREE_CODE (type) != REAL_TYPE)
27115     return NULL;
27116
27117   if (type == bool_char_type_node) return "U6__boolc";
27118   if (type == bool_short_type_node) return "U6__bools";
27119   if (type == pixel_type_node) return "u7__pixel";
27120   if (type == bool_int_type_node) return "U6__booli";
27121   if (type == bool_long_long_type_node) return "U6__boolx";
27122
27123   if (SCALAR_FLOAT_TYPE_P (type) && FLOAT128_IBM_P (TYPE_MODE (type)))
27124     return "g";
27125   if (SCALAR_FLOAT_TYPE_P (type) && FLOAT128_IEEE_P (TYPE_MODE (type)))
27126     return ieee128_mangling_gcc_8_1 ? "U10__float128" : "u9__ieee128";
27127
27128   /* For all other types, use the default mangling.  */
27129   return NULL;
27130 }
27131
27132 /* Handle a "longcall" or "shortcall" attribute; arguments as in
27133    struct attribute_spec.handler.  */
27134
27135 static tree
27136 rs6000_handle_longcall_attribute (tree *node, tree name,
27137                                   tree args ATTRIBUTE_UNUSED,
27138                                   int flags ATTRIBUTE_UNUSED,
27139                                   bool *no_add_attrs)
27140 {
27141   if (TREE_CODE (*node) != FUNCTION_TYPE
27142       && TREE_CODE (*node) != FIELD_DECL
27143       && TREE_CODE (*node) != TYPE_DECL)
27144     {
27145       warning (OPT_Wattributes, "%qE attribute only applies to functions",
27146                name);
27147       *no_add_attrs = true;
27148     }
27149
27150   return NULL_TREE;
27151 }
27152
27153 /* Set longcall attributes on all functions declared when
27154    rs6000_default_long_calls is true.  */
27155 static void
27156 rs6000_set_default_type_attributes (tree type)
27157 {
27158   if (rs6000_default_long_calls
27159       && (TREE_CODE (type) == FUNCTION_TYPE
27160           || TREE_CODE (type) == METHOD_TYPE))
27161     TYPE_ATTRIBUTES (type) = tree_cons (get_identifier ("longcall"),
27162                                         NULL_TREE,
27163                                         TYPE_ATTRIBUTES (type));
27164
27165 #if TARGET_MACHO
27166   darwin_set_default_type_attributes (type);
27167 #endif
27168 }
27169
27170 /* Return a reference suitable for calling a function with the
27171    longcall attribute.  */
27172
27173 static rtx
27174 rs6000_longcall_ref (rtx call_ref, rtx arg)
27175 {
27176   /* System V adds '.' to the internal name, so skip them.  */
27177   const char *call_name = XSTR (call_ref, 0);
27178   if (*call_name == '.')
27179     {
27180       while (*call_name == '.')
27181         call_name++;
27182
27183       tree node = get_identifier (call_name);
27184       call_ref = gen_rtx_SYMBOL_REF (VOIDmode, IDENTIFIER_POINTER (node));
27185     }
27186
27187   if (TARGET_PLTSEQ)
27188     {
27189       rtx base = const0_rtx;
27190       int regno = 12;
27191       if (rs6000_pcrel_p (cfun))
27192         {
27193           rtx reg = gen_rtx_REG (Pmode, regno);
27194           rtx u = gen_rtx_UNSPEC (Pmode, gen_rtvec (3, base, call_ref, arg),
27195                                   UNSPEC_PLT_PCREL);
27196           emit_insn (gen_rtx_SET (reg, u));
27197           return reg;
27198         }
27199
27200       if (DEFAULT_ABI == ABI_ELFv2)
27201         base = gen_rtx_REG (Pmode, TOC_REGISTER);
27202       else
27203         {
27204           if (flag_pic)
27205             base = gen_rtx_REG (Pmode, RS6000_PIC_OFFSET_TABLE_REGNUM);
27206           regno = 11;
27207         }
27208       /* Reg must match that used by linker PLT stubs.  For ELFv2, r12
27209          may be used by a function global entry point.  For SysV4, r11
27210          is used by __glink_PLTresolve lazy resolver entry.  */
27211       rtx reg = gen_rtx_REG (Pmode, regno);
27212       rtx hi = gen_rtx_UNSPEC (Pmode, gen_rtvec (3, base, call_ref, arg),
27213                                UNSPEC_PLT16_HA);
27214       rtx lo = gen_rtx_UNSPEC (Pmode, gen_rtvec (3, reg, call_ref, arg),
27215                                UNSPEC_PLT16_LO);
27216       emit_insn (gen_rtx_SET (reg, hi));
27217       emit_insn (gen_rtx_SET (reg, lo));
27218       return reg;
27219     }
27220
27221   return force_reg (Pmode, call_ref);
27222 }
27223 \f
27224 #ifndef TARGET_USE_MS_BITFIELD_LAYOUT
27225 #define TARGET_USE_MS_BITFIELD_LAYOUT 0
27226 #endif
27227
27228 /* Handle a "ms_struct" or "gcc_struct" attribute; arguments as in
27229    struct attribute_spec.handler.  */
27230 static tree
27231 rs6000_handle_struct_attribute (tree *node, tree name,
27232                                 tree args ATTRIBUTE_UNUSED,
27233                                 int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
27234 {
27235   tree *type = NULL;
27236   if (DECL_P (*node))
27237     {
27238       if (TREE_CODE (*node) == TYPE_DECL)
27239         type = &TREE_TYPE (*node);
27240     }
27241   else
27242     type = node;
27243
27244   if (!(type && (TREE_CODE (*type) == RECORD_TYPE
27245                  || TREE_CODE (*type) == UNION_TYPE)))
27246     {
27247       warning (OPT_Wattributes, "%qE attribute ignored", name);
27248       *no_add_attrs = true;
27249     }
27250
27251   else if ((is_attribute_p ("ms_struct", name)
27252             && lookup_attribute ("gcc_struct", TYPE_ATTRIBUTES (*type)))
27253            || ((is_attribute_p ("gcc_struct", name)
27254                 && lookup_attribute ("ms_struct", TYPE_ATTRIBUTES (*type)))))
27255     {
27256       warning (OPT_Wattributes, "%qE incompatible attribute ignored",
27257                name);
27258       *no_add_attrs = true;
27259     }
27260
27261   return NULL_TREE;
27262 }
27263
27264 static bool
27265 rs6000_ms_bitfield_layout_p (const_tree record_type)
27266 {
27267   return (TARGET_USE_MS_BITFIELD_LAYOUT &&
27268           !lookup_attribute ("gcc_struct", TYPE_ATTRIBUTES (record_type)))
27269     || lookup_attribute ("ms_struct", TYPE_ATTRIBUTES (record_type));
27270 }
27271 \f
27272 #ifdef USING_ELFOS_H
27273
27274 /* A get_unnamed_section callback, used for switching to toc_section.  */
27275
27276 static void
27277 rs6000_elf_output_toc_section_asm_op (const void *data ATTRIBUTE_UNUSED)
27278 {
27279   if ((DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
27280       && TARGET_MINIMAL_TOC)
27281     {
27282       if (!toc_initialized)
27283         {
27284           fprintf (asm_out_file, "%s\n", TOC_SECTION_ASM_OP);
27285           ASM_OUTPUT_ALIGN (asm_out_file, TARGET_64BIT ? 3 : 2);
27286           (*targetm.asm_out.internal_label) (asm_out_file, "LCTOC", 0);
27287           fprintf (asm_out_file, "\t.tc ");
27288           ASM_OUTPUT_INTERNAL_LABEL_PREFIX (asm_out_file, "LCTOC1[TC],");
27289           ASM_OUTPUT_INTERNAL_LABEL_PREFIX (asm_out_file, "LCTOC1");
27290           fprintf (asm_out_file, "\n");
27291
27292           fprintf (asm_out_file, "%s\n", MINIMAL_TOC_SECTION_ASM_OP);
27293           ASM_OUTPUT_ALIGN (asm_out_file, TARGET_64BIT ? 3 : 2);
27294           ASM_OUTPUT_INTERNAL_LABEL_PREFIX (asm_out_file, "LCTOC1");
27295           fprintf (asm_out_file, " = .+32768\n");
27296           toc_initialized = 1;
27297         }
27298       else
27299         fprintf (asm_out_file, "%s\n", MINIMAL_TOC_SECTION_ASM_OP);
27300     }
27301   else if (DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
27302     {
27303       fprintf (asm_out_file, "%s\n", TOC_SECTION_ASM_OP);
27304       if (!toc_initialized)
27305         {
27306           ASM_OUTPUT_ALIGN (asm_out_file, TARGET_64BIT ? 3 : 2);
27307           toc_initialized = 1;
27308         }
27309     }
27310   else
27311     {
27312       fprintf (asm_out_file, "%s\n", MINIMAL_TOC_SECTION_ASM_OP);
27313       if (!toc_initialized)
27314         {
27315           ASM_OUTPUT_ALIGN (asm_out_file, TARGET_64BIT ? 3 : 2);
27316           ASM_OUTPUT_INTERNAL_LABEL_PREFIX (asm_out_file, "LCTOC1");
27317           fprintf (asm_out_file, " = .+32768\n");
27318           toc_initialized = 1;
27319         }
27320     }
27321 }
27322
27323 /* Implement TARGET_ASM_INIT_SECTIONS.  */
27324
27325 static void
27326 rs6000_elf_asm_init_sections (void)
27327 {
27328   toc_section
27329     = get_unnamed_section (0, rs6000_elf_output_toc_section_asm_op, NULL);
27330
27331   sdata2_section
27332     = get_unnamed_section (SECTION_WRITE, output_section_asm_op,
27333                            SDATA2_SECTION_ASM_OP);
27334 }
27335
27336 /* Implement TARGET_SELECT_RTX_SECTION.  */
27337
27338 static section *
27339 rs6000_elf_select_rtx_section (machine_mode mode, rtx x,
27340                                unsigned HOST_WIDE_INT align)
27341 {
27342   if (ASM_OUTPUT_SPECIAL_POOL_ENTRY_P (x, mode))
27343     return toc_section;
27344   else
27345     return default_elf_select_rtx_section (mode, x, align);
27346 }
27347 \f
27348 /* For a SYMBOL_REF, set generic flags and then perform some
27349    target-specific processing.
27350
27351    When the AIX ABI is requested on a non-AIX system, replace the
27352    function name with the real name (with a leading .) rather than the
27353    function descriptor name.  This saves a lot of overriding code to
27354    read the prefixes.  */
27355
27356 static void rs6000_elf_encode_section_info (tree, rtx, int) ATTRIBUTE_UNUSED;
27357 static void
27358 rs6000_elf_encode_section_info (tree decl, rtx rtl, int first)
27359 {
27360   default_encode_section_info (decl, rtl, first);
27361
27362   if (first
27363       && TREE_CODE (decl) == FUNCTION_DECL
27364       && !TARGET_AIX
27365       && DEFAULT_ABI == ABI_AIX)
27366     {
27367       rtx sym_ref = XEXP (rtl, 0);
27368       size_t len = strlen (XSTR (sym_ref, 0));
27369       char *str = XALLOCAVEC (char, len + 2);
27370       str[0] = '.';
27371       memcpy (str + 1, XSTR (sym_ref, 0), len + 1);
27372       XSTR (sym_ref, 0) = ggc_alloc_string (str, len + 1);
27373     }
27374 }
27375
27376 static inline bool
27377 compare_section_name (const char *section, const char *templ)
27378 {
27379   int len;
27380
27381   len = strlen (templ);
27382   return (strncmp (section, templ, len) == 0
27383           && (section[len] == 0 || section[len] == '.'));
27384 }
27385
27386 bool
27387 rs6000_elf_in_small_data_p (const_tree decl)
27388 {
27389   if (rs6000_sdata == SDATA_NONE)
27390     return false;
27391
27392   /* We want to merge strings, so we never consider them small data.  */
27393   if (TREE_CODE (decl) == STRING_CST)
27394     return false;
27395
27396   /* Functions are never in the small data area.  */
27397   if (TREE_CODE (decl) == FUNCTION_DECL)
27398     return false;
27399
27400   if (TREE_CODE (decl) == VAR_DECL && DECL_SECTION_NAME (decl))
27401     {
27402       const char *section = DECL_SECTION_NAME (decl);
27403       if (compare_section_name (section, ".sdata")
27404           || compare_section_name (section, ".sdata2")
27405           || compare_section_name (section, ".gnu.linkonce.s")
27406           || compare_section_name (section, ".sbss")
27407           || compare_section_name (section, ".sbss2")
27408           || compare_section_name (section, ".gnu.linkonce.sb")
27409           || strcmp (section, ".PPC.EMB.sdata0") == 0
27410           || strcmp (section, ".PPC.EMB.sbss0") == 0)
27411         return true;
27412     }
27413   else
27414     {
27415       /* If we are told not to put readonly data in sdata, then don't.  */
27416       if (TREE_READONLY (decl) && rs6000_sdata != SDATA_EABI
27417           && !rs6000_readonly_in_sdata)
27418         return false;
27419
27420       HOST_WIDE_INT size = int_size_in_bytes (TREE_TYPE (decl));
27421
27422       if (size > 0
27423           && size <= g_switch_value
27424           /* If it's not public, and we're not going to reference it there,
27425              there's no need to put it in the small data section.  */
27426           && (rs6000_sdata != SDATA_DATA || TREE_PUBLIC (decl)))
27427         return true;
27428     }
27429
27430   return false;
27431 }
27432
27433 #endif /* USING_ELFOS_H */
27434 \f
27435 /* Implement TARGET_USE_BLOCKS_FOR_CONSTANT_P.  */
27436
27437 static bool
27438 rs6000_use_blocks_for_constant_p (machine_mode mode, const_rtx x)
27439 {
27440   return !ASM_OUTPUT_SPECIAL_POOL_ENTRY_P (x, mode);
27441 }
27442
27443 /* Do not place thread-local symbols refs in the object blocks.  */
27444
27445 static bool
27446 rs6000_use_blocks_for_decl_p (const_tree decl)
27447 {
27448   return !DECL_THREAD_LOCAL_P (decl);
27449 }
27450 \f
27451 /* Return a REG that occurs in ADDR with coefficient 1.
27452    ADDR can be effectively incremented by incrementing REG.
27453
27454    r0 is special and we must not select it as an address
27455    register by this routine since our caller will try to
27456    increment the returned register via an "la" instruction.  */
27457
27458 rtx
27459 find_addr_reg (rtx addr)
27460 {
27461   while (GET_CODE (addr) == PLUS)
27462     {
27463       if (REG_P (XEXP (addr, 0))
27464           && REGNO (XEXP (addr, 0)) != 0)
27465         addr = XEXP (addr, 0);
27466       else if (REG_P (XEXP (addr, 1))
27467                && REGNO (XEXP (addr, 1)) != 0)
27468         addr = XEXP (addr, 1);
27469       else if (CONSTANT_P (XEXP (addr, 0)))
27470         addr = XEXP (addr, 1);
27471       else if (CONSTANT_P (XEXP (addr, 1)))
27472         addr = XEXP (addr, 0);
27473       else
27474         gcc_unreachable ();
27475     }
27476   gcc_assert (REG_P (addr) && REGNO (addr) != 0);
27477   return addr;
27478 }
27479
27480 void
27481 rs6000_fatal_bad_address (rtx op)
27482 {
27483   fatal_insn ("bad address", op);
27484 }
27485
27486 #if TARGET_MACHO
27487
27488 vec<branch_island, va_gc> *branch_islands;
27489
27490 /* Remember to generate a branch island for far calls to the given
27491    function.  */
27492
27493 static void
27494 add_compiler_branch_island (tree label_name, tree function_name,
27495                             int line_number)
27496 {
27497   branch_island bi = {function_name, label_name, line_number};
27498   vec_safe_push (branch_islands, bi);
27499 }
27500
27501 /* NO_PREVIOUS_DEF checks in the link list whether the function name is
27502    already there or not.  */
27503
27504 static int
27505 no_previous_def (tree function_name)
27506 {
27507   branch_island *bi;
27508   unsigned ix;
27509
27510   FOR_EACH_VEC_SAFE_ELT (branch_islands, ix, bi)
27511     if (function_name == bi->function_name)
27512       return 0;
27513   return 1;
27514 }
27515
27516 /* GET_PREV_LABEL gets the label name from the previous definition of
27517    the function.  */
27518
27519 static tree
27520 get_prev_label (tree function_name)
27521 {
27522   branch_island *bi;
27523   unsigned ix;
27524
27525   FOR_EACH_VEC_SAFE_ELT (branch_islands, ix, bi)
27526     if (function_name == bi->function_name)
27527       return bi->label_name;
27528   return NULL_TREE;
27529 }
27530
27531 /* Generate PIC and indirect symbol stubs.  */
27532
27533 void
27534 machopic_output_stub (FILE *file, const char *symb, const char *stub)
27535 {
27536   unsigned int length;
27537   char *symbol_name, *lazy_ptr_name;
27538   char *local_label_0;
27539   static unsigned label = 0;
27540
27541   /* Lose our funky encoding stuff so it doesn't contaminate the stub.  */
27542   symb = (*targetm.strip_name_encoding) (symb);
27543
27544
27545   length = strlen (symb);
27546   symbol_name = XALLOCAVEC (char, length + 32);
27547   GEN_SYMBOL_NAME_FOR_SYMBOL (symbol_name, symb, length);
27548
27549   lazy_ptr_name = XALLOCAVEC (char, length + 32);
27550   GEN_LAZY_PTR_NAME_FOR_SYMBOL (lazy_ptr_name, symb, length);
27551
27552   if (flag_pic == 2)
27553     switch_to_section (darwin_sections[machopic_picsymbol_stub1_section]);
27554   else
27555     switch_to_section (darwin_sections[machopic_symbol_stub1_section]);
27556
27557   if (flag_pic == 2)
27558     {
27559       fprintf (file, "\t.align 5\n");
27560
27561       fprintf (file, "%s:\n", stub);
27562       fprintf (file, "\t.indirect_symbol %s\n", symbol_name);
27563
27564       label++;
27565       local_label_0 = XALLOCAVEC (char, 16);
27566       sprintf (local_label_0, "L%u$spb", label);
27567
27568       fprintf (file, "\tmflr r0\n");
27569       if (TARGET_LINK_STACK)
27570         {
27571           char name[32];
27572           get_ppc476_thunk_name (name);
27573           fprintf (file, "\tbl %s\n", name);
27574           fprintf (file, "%s:\n\tmflr r11\n", local_label_0);
27575         }
27576       else
27577         {
27578           fprintf (file, "\tbcl 20,31,%s\n", local_label_0);
27579           fprintf (file, "%s:\n\tmflr r11\n", local_label_0);
27580         }
27581       fprintf (file, "\taddis r11,r11,ha16(%s-%s)\n",
27582                lazy_ptr_name, local_label_0);
27583       fprintf (file, "\tmtlr r0\n");
27584       fprintf (file, "\t%s r12,lo16(%s-%s)(r11)\n",
27585                (TARGET_64BIT ? "ldu" : "lwzu"),
27586                lazy_ptr_name, local_label_0);
27587       fprintf (file, "\tmtctr r12\n");
27588       fprintf (file, "\tbctr\n");
27589     }
27590   else
27591     {
27592       fprintf (file, "\t.align 4\n");
27593
27594       fprintf (file, "%s:\n", stub);
27595       fprintf (file, "\t.indirect_symbol %s\n", symbol_name);
27596
27597       fprintf (file, "\tlis r11,ha16(%s)\n", lazy_ptr_name);
27598       fprintf (file, "\t%s r12,lo16(%s)(r11)\n",
27599                (TARGET_64BIT ? "ldu" : "lwzu"),
27600                lazy_ptr_name);
27601       fprintf (file, "\tmtctr r12\n");
27602       fprintf (file, "\tbctr\n");
27603     }
27604
27605   switch_to_section (darwin_sections[machopic_lazy_symbol_ptr_section]);
27606   fprintf (file, "%s:\n", lazy_ptr_name);
27607   fprintf (file, "\t.indirect_symbol %s\n", symbol_name);
27608   fprintf (file, "%sdyld_stub_binding_helper\n",
27609            (TARGET_64BIT ? DOUBLE_INT_ASM_OP : "\t.long\t"));
27610 }
27611
27612 /* Legitimize PIC addresses.  If the address is already
27613    position-independent, we return ORIG.  Newly generated
27614    position-independent addresses go into a reg.  This is REG if non
27615    zero, otherwise we allocate register(s) as necessary.  */
27616
27617 #define SMALL_INT(X) ((UINTVAL (X) + 0x8000) < 0x10000)
27618
27619 rtx
27620 rs6000_machopic_legitimize_pic_address (rtx orig, machine_mode mode,
27621                                         rtx reg)
27622 {
27623   rtx base, offset;
27624
27625   if (reg == NULL && !reload_completed)
27626     reg = gen_reg_rtx (Pmode);
27627
27628   if (GET_CODE (orig) == CONST)
27629     {
27630       rtx reg_temp;
27631
27632       if (GET_CODE (XEXP (orig, 0)) == PLUS
27633           && XEXP (XEXP (orig, 0), 0) == pic_offset_table_rtx)
27634         return orig;
27635
27636       gcc_assert (GET_CODE (XEXP (orig, 0)) == PLUS);
27637
27638       /* Use a different reg for the intermediate value, as
27639          it will be marked UNCHANGING.  */
27640       reg_temp = !can_create_pseudo_p () ? reg : gen_reg_rtx (Pmode);
27641       base = rs6000_machopic_legitimize_pic_address (XEXP (XEXP (orig, 0), 0),
27642                                                      Pmode, reg_temp);
27643       offset =
27644         rs6000_machopic_legitimize_pic_address (XEXP (XEXP (orig, 0), 1),
27645                                                 Pmode, reg);
27646
27647       if (CONST_INT_P (offset))
27648         {
27649           if (SMALL_INT (offset))
27650             return plus_constant (Pmode, base, INTVAL (offset));
27651           else if (!reload_completed)
27652             offset = force_reg (Pmode, offset);
27653           else
27654             {
27655               rtx mem = force_const_mem (Pmode, orig);
27656               return machopic_legitimize_pic_address (mem, Pmode, reg);
27657             }
27658         }
27659       return gen_rtx_PLUS (Pmode, base, offset);
27660     }
27661
27662   /* Fall back on generic machopic code.  */
27663   return machopic_legitimize_pic_address (orig, mode, reg);
27664 }
27665
27666 /* Output a .machine directive for the Darwin assembler, and call
27667    the generic start_file routine.  */
27668
27669 static void
27670 rs6000_darwin_file_start (void)
27671 {
27672   static const struct
27673   {
27674     const char *arg;
27675     const char *name;
27676     HOST_WIDE_INT if_set;
27677   } mapping[] = {
27678     { "ppc64", "ppc64", MASK_64BIT },
27679     { "970", "ppc970", MASK_PPC_GPOPT | MASK_MFCRF | MASK_POWERPC64 },
27680     { "power4", "ppc970", 0 },
27681     { "G5", "ppc970", 0 },
27682     { "7450", "ppc7450", 0 },
27683     { "7400", "ppc7400", MASK_ALTIVEC },
27684     { "G4", "ppc7400", 0 },
27685     { "750", "ppc750", 0 },
27686     { "740", "ppc750", 0 },
27687     { "G3", "ppc750", 0 },
27688     { "604e", "ppc604e", 0 },
27689     { "604", "ppc604", 0 },
27690     { "603e", "ppc603", 0 },
27691     { "603", "ppc603", 0 },
27692     { "601", "ppc601", 0 },
27693     { NULL, "ppc", 0 } };
27694   const char *cpu_id = "";
27695   size_t i;
27696
27697   rs6000_file_start ();
27698   darwin_file_start ();
27699
27700   /* Determine the argument to -mcpu=.  Default to G3 if not specified.  */
27701   
27702   if (rs6000_default_cpu != 0 && rs6000_default_cpu[0] != '\0')
27703     cpu_id = rs6000_default_cpu;
27704
27705   if (global_options_set.x_rs6000_cpu_index)
27706     cpu_id = processor_target_table[rs6000_cpu_index].name;
27707
27708   /* Look through the mapping array.  Pick the first name that either
27709      matches the argument, has a bit set in IF_SET that is also set
27710      in the target flags, or has a NULL name.  */
27711
27712   i = 0;
27713   while (mapping[i].arg != NULL
27714          && strcmp (mapping[i].arg, cpu_id) != 0
27715          && (mapping[i].if_set & rs6000_isa_flags) == 0)
27716     i++;
27717
27718   fprintf (asm_out_file, "\t.machine %s\n", mapping[i].name);
27719 }
27720
27721 #endif /* TARGET_MACHO */
27722
27723 #if TARGET_ELF
27724 static int
27725 rs6000_elf_reloc_rw_mask (void)
27726 {
27727   if (flag_pic)
27728     return 3;
27729   else if (DEFAULT_ABI == ABI_AIX || DEFAULT_ABI == ABI_ELFv2)
27730     return 2;
27731   else
27732     return 0;
27733 }
27734
27735 /* Record an element in the table of global constructors.  SYMBOL is
27736    a SYMBOL_REF of the function to be called; PRIORITY is a number
27737    between 0 and MAX_INIT_PRIORITY.
27738
27739    This differs from default_named_section_asm_out_constructor in
27740    that we have special handling for -mrelocatable.  */
27741
27742 static void rs6000_elf_asm_out_constructor (rtx, int) ATTRIBUTE_UNUSED;
27743 static void
27744 rs6000_elf_asm_out_constructor (rtx symbol, int priority)
27745 {
27746   const char *section = ".ctors";
27747   char buf[18];
27748
27749   if (priority != DEFAULT_INIT_PRIORITY)
27750     {
27751       sprintf (buf, ".ctors.%.5u",
27752                /* Invert the numbering so the linker puts us in the proper
27753                   order; constructors are run from right to left, and the
27754                   linker sorts in increasing order.  */
27755                MAX_INIT_PRIORITY - priority);
27756       section = buf;
27757     }
27758
27759   switch_to_section (get_section (section, SECTION_WRITE, NULL));
27760   assemble_align (POINTER_SIZE);
27761
27762   if (DEFAULT_ABI == ABI_V4
27763       && (TARGET_RELOCATABLE || flag_pic > 1))
27764     {
27765       fputs ("\t.long (", asm_out_file);
27766       output_addr_const (asm_out_file, symbol);
27767       fputs (")@fixup\n", asm_out_file);
27768     }
27769   else
27770     assemble_integer (symbol, POINTER_SIZE / BITS_PER_UNIT, POINTER_SIZE, 1);
27771 }
27772
27773 static void rs6000_elf_asm_out_destructor (rtx, int) ATTRIBUTE_UNUSED;
27774 static void
27775 rs6000_elf_asm_out_destructor (rtx symbol, int priority)
27776 {
27777   const char *section = ".dtors";
27778   char buf[18];
27779
27780   if (priority != DEFAULT_INIT_PRIORITY)
27781     {
27782       sprintf (buf, ".dtors.%.5u",
27783                /* Invert the numbering so the linker puts us in the proper
27784                   order; constructors are run from right to left, and the
27785                   linker sorts in increasing order.  */
27786                MAX_INIT_PRIORITY - priority);
27787       section = buf;
27788     }
27789
27790   switch_to_section (get_section (section, SECTION_WRITE, NULL));
27791   assemble_align (POINTER_SIZE);
27792
27793   if (DEFAULT_ABI == ABI_V4
27794       && (TARGET_RELOCATABLE || flag_pic > 1))
27795     {
27796       fputs ("\t.long (", asm_out_file);
27797       output_addr_const (asm_out_file, symbol);
27798       fputs (")@fixup\n", asm_out_file);
27799     }
27800   else
27801     assemble_integer (symbol, POINTER_SIZE / BITS_PER_UNIT, POINTER_SIZE, 1);
27802 }
27803
27804 void
27805 rs6000_elf_declare_function_name (FILE *file, const char *name, tree decl)
27806 {
27807   if (TARGET_64BIT && DEFAULT_ABI != ABI_ELFv2)
27808     {
27809       fputs ("\t.section\t\".opd\",\"aw\"\n\t.align 3\n", file);
27810       ASM_OUTPUT_LABEL (file, name);
27811       fputs (DOUBLE_INT_ASM_OP, file);
27812       rs6000_output_function_entry (file, name);
27813       fputs (",.TOC.@tocbase,0\n\t.previous\n", file);
27814       if (DOT_SYMBOLS)
27815         {
27816           fputs ("\t.size\t", file);
27817           assemble_name (file, name);
27818           fputs (",24\n\t.type\t.", file);
27819           assemble_name (file, name);
27820           fputs (",@function\n", file);
27821           if (TREE_PUBLIC (decl) && ! DECL_WEAK (decl))
27822             {
27823               fputs ("\t.globl\t.", file);
27824               assemble_name (file, name);
27825               putc ('\n', file);
27826             }
27827         }
27828       else
27829         ASM_OUTPUT_TYPE_DIRECTIVE (file, name, "function");
27830       ASM_DECLARE_RESULT (file, DECL_RESULT (decl));
27831       rs6000_output_function_entry (file, name);
27832       fputs (":\n", file);
27833       return;
27834     }
27835
27836   int uses_toc;
27837   if (DEFAULT_ABI == ABI_V4
27838       && (TARGET_RELOCATABLE || flag_pic > 1)
27839       && !TARGET_SECURE_PLT
27840       && (!constant_pool_empty_p () || crtl->profile)
27841       && (uses_toc = uses_TOC ()))
27842     {
27843       char buf[256];
27844
27845       if (uses_toc == 2)
27846         switch_to_other_text_partition ();
27847       (*targetm.asm_out.internal_label) (file, "LCL", rs6000_pic_labelno);
27848
27849       fprintf (file, "\t.long ");
27850       assemble_name (file, toc_label_name);
27851       need_toc_init = 1;
27852       putc ('-', file);
27853       ASM_GENERATE_INTERNAL_LABEL (buf, "LCF", rs6000_pic_labelno);
27854       assemble_name (file, buf);
27855       putc ('\n', file);
27856       if (uses_toc == 2)
27857         switch_to_other_text_partition ();
27858     }
27859
27860   ASM_OUTPUT_TYPE_DIRECTIVE (file, name, "function");
27861   ASM_DECLARE_RESULT (file, DECL_RESULT (decl));
27862
27863   if (TARGET_CMODEL == CMODEL_LARGE
27864       && rs6000_global_entry_point_prologue_needed_p ())
27865     {
27866       char buf[256];
27867
27868       (*targetm.asm_out.internal_label) (file, "LCL", rs6000_pic_labelno);
27869
27870       fprintf (file, "\t.quad .TOC.-");
27871       ASM_GENERATE_INTERNAL_LABEL (buf, "LCF", rs6000_pic_labelno);
27872       assemble_name (file, buf);
27873       putc ('\n', file);
27874     }
27875
27876   if (DEFAULT_ABI == ABI_AIX)
27877     {
27878       const char *desc_name, *orig_name;
27879
27880       orig_name = (*targetm.strip_name_encoding) (name);
27881       desc_name = orig_name;
27882       while (*desc_name == '.')
27883         desc_name++;
27884
27885       if (TREE_PUBLIC (decl))
27886         fprintf (file, "\t.globl %s\n", desc_name);
27887
27888       fprintf (file, "%s\n", MINIMAL_TOC_SECTION_ASM_OP);
27889       fprintf (file, "%s:\n", desc_name);
27890       fprintf (file, "\t.long %s\n", orig_name);
27891       fputs ("\t.long _GLOBAL_OFFSET_TABLE_\n", file);
27892       fputs ("\t.long 0\n", file);
27893       fprintf (file, "\t.previous\n");
27894     }
27895   ASM_OUTPUT_LABEL (file, name);
27896 }
27897
27898 static void rs6000_elf_file_end (void) ATTRIBUTE_UNUSED;
27899 static void
27900 rs6000_elf_file_end (void)
27901 {
27902 #ifdef HAVE_AS_GNU_ATTRIBUTE
27903   /* ??? The value emitted depends on options active at file end.
27904      Assume anyone using #pragma or attributes that might change
27905      options knows what they are doing.  */
27906   if ((TARGET_64BIT || DEFAULT_ABI == ABI_V4)
27907       && rs6000_passes_float)
27908     {
27909       int fp;
27910
27911       if (TARGET_HARD_FLOAT)
27912         fp = 1;
27913       else
27914         fp = 2;
27915       if (rs6000_passes_long_double)
27916         {
27917           if (!TARGET_LONG_DOUBLE_128)
27918             fp |= 2 * 4;
27919           else if (TARGET_IEEEQUAD)
27920             fp |= 3 * 4;
27921           else
27922             fp |= 1 * 4;
27923         }
27924       fprintf (asm_out_file, "\t.gnu_attribute 4, %d\n", fp);
27925     }
27926   if (TARGET_32BIT && DEFAULT_ABI == ABI_V4)
27927     {
27928       if (rs6000_passes_vector)
27929         fprintf (asm_out_file, "\t.gnu_attribute 8, %d\n",
27930                  (TARGET_ALTIVEC_ABI ? 2 : 1));
27931       if (rs6000_returns_struct)
27932         fprintf (asm_out_file, "\t.gnu_attribute 12, %d\n",
27933                  aix_struct_return ? 2 : 1);
27934     }
27935 #endif
27936 #if defined (POWERPC_LINUX) || defined (POWERPC_FREEBSD)
27937   if (TARGET_32BIT || DEFAULT_ABI == ABI_ELFv2)
27938     file_end_indicate_exec_stack ();
27939 #endif
27940
27941   if (flag_split_stack)
27942     file_end_indicate_split_stack ();
27943
27944   if (cpu_builtin_p)
27945     {
27946       /* We have expanded a CPU builtin, so we need to emit a reference to
27947          the special symbol that LIBC uses to declare it supports the
27948          AT_PLATFORM and AT_HWCAP/AT_HWCAP2 in the TCB feature.  */
27949       switch_to_section (data_section);
27950       fprintf (asm_out_file, "\t.align %u\n", TARGET_32BIT ? 2 : 3);
27951       fprintf (asm_out_file, "\t%s %s\n",
27952                TARGET_32BIT ? ".long" : ".quad", tcb_verification_symbol);
27953     }
27954 }
27955 #endif
27956
27957 #if TARGET_XCOFF
27958
27959 #ifndef HAVE_XCOFF_DWARF_EXTRAS
27960 #define HAVE_XCOFF_DWARF_EXTRAS 0
27961 #endif
27962
27963 static enum unwind_info_type
27964 rs6000_xcoff_debug_unwind_info (void)
27965 {
27966   return UI_NONE;
27967 }
27968
27969 static void
27970 rs6000_xcoff_asm_output_anchor (rtx symbol)
27971 {
27972   char buffer[100];
27973
27974   sprintf (buffer, "$ + " HOST_WIDE_INT_PRINT_DEC,
27975            SYMBOL_REF_BLOCK_OFFSET (symbol));
27976   fprintf (asm_out_file, "%s", SET_ASM_OP);
27977   RS6000_OUTPUT_BASENAME (asm_out_file, XSTR (symbol, 0));
27978   fprintf (asm_out_file, ",");
27979   RS6000_OUTPUT_BASENAME (asm_out_file, buffer);
27980   fprintf (asm_out_file, "\n");
27981 }
27982
27983 static void
27984 rs6000_xcoff_asm_globalize_label (FILE *stream, const char *name)
27985 {
27986   fputs (GLOBAL_ASM_OP, stream);
27987   RS6000_OUTPUT_BASENAME (stream, name);
27988   putc ('\n', stream);
27989 }
27990
27991 /* A get_unnamed_decl callback, used for read-only sections.  PTR
27992    points to the section string variable.  */
27993
27994 static void
27995 rs6000_xcoff_output_readonly_section_asm_op (const void *directive)
27996 {
27997   fprintf (asm_out_file, "\t.csect %s[RO],%s\n",
27998            *(const char *const *) directive,
27999            XCOFF_CSECT_DEFAULT_ALIGNMENT_STR);
28000 }
28001
28002 /* Likewise for read-write sections.  */
28003
28004 static void
28005 rs6000_xcoff_output_readwrite_section_asm_op (const void *directive)
28006 {
28007   fprintf (asm_out_file, "\t.csect %s[RW],%s\n",
28008            *(const char *const *) directive,
28009            XCOFF_CSECT_DEFAULT_ALIGNMENT_STR);
28010 }
28011
28012 static void
28013 rs6000_xcoff_output_tls_section_asm_op (const void *directive)
28014 {
28015   fprintf (asm_out_file, "\t.csect %s[TL],%s\n",
28016            *(const char *const *) directive,
28017            XCOFF_CSECT_DEFAULT_ALIGNMENT_STR);
28018 }
28019
28020 /* A get_unnamed_section callback, used for switching to toc_section.  */
28021
28022 static void
28023 rs6000_xcoff_output_toc_section_asm_op (const void *data ATTRIBUTE_UNUSED)
28024 {
28025   if (TARGET_MINIMAL_TOC)
28026     {
28027       /* toc_section is always selected at least once from
28028          rs6000_xcoff_file_start, so this is guaranteed to
28029          always be defined once and only once in each file.  */
28030       if (!toc_initialized)
28031         {
28032           fputs ("\t.toc\nLCTOC..1:\n", asm_out_file);
28033           fputs ("\t.tc toc_table[TC],toc_table[RW]\n", asm_out_file);
28034           toc_initialized = 1;
28035         }
28036       fprintf (asm_out_file, "\t.csect toc_table[RW]%s\n",
28037                (TARGET_32BIT ? "" : ",3"));
28038     }
28039   else
28040     fputs ("\t.toc\n", asm_out_file);
28041 }
28042
28043 /* Implement TARGET_ASM_INIT_SECTIONS.  */
28044
28045 static void
28046 rs6000_xcoff_asm_init_sections (void)
28047 {
28048   read_only_data_section
28049     = get_unnamed_section (0, rs6000_xcoff_output_readonly_section_asm_op,
28050                            &xcoff_read_only_section_name);
28051
28052   private_data_section
28053     = get_unnamed_section (SECTION_WRITE,
28054                            rs6000_xcoff_output_readwrite_section_asm_op,
28055                            &xcoff_private_data_section_name);
28056
28057   read_only_private_data_section
28058     = get_unnamed_section (0, rs6000_xcoff_output_readonly_section_asm_op,
28059                            &xcoff_private_rodata_section_name);
28060
28061   tls_data_section
28062     = get_unnamed_section (SECTION_TLS,
28063                            rs6000_xcoff_output_tls_section_asm_op,
28064                            &xcoff_tls_data_section_name);
28065
28066   tls_private_data_section
28067     = get_unnamed_section (SECTION_TLS,
28068                            rs6000_xcoff_output_tls_section_asm_op,
28069                            &xcoff_private_data_section_name);
28070
28071   toc_section
28072     = get_unnamed_section (0, rs6000_xcoff_output_toc_section_asm_op, NULL);
28073
28074   readonly_data_section = read_only_data_section;
28075 }
28076
28077 static int
28078 rs6000_xcoff_reloc_rw_mask (void)
28079 {
28080   return 3;
28081 }
28082
28083 static void
28084 rs6000_xcoff_asm_named_section (const char *name, unsigned int flags,
28085                                 tree decl ATTRIBUTE_UNUSED)
28086 {
28087   int smclass;
28088   static const char * const suffix[5] = { "PR", "RO", "RW", "TL", "XO" };
28089
28090   if (flags & SECTION_EXCLUDE)
28091     smclass = 4;
28092   else if (flags & SECTION_DEBUG)
28093     {
28094       fprintf (asm_out_file, "\t.dwsect %s\n", name);
28095       return;
28096     }
28097   else if (flags & SECTION_CODE)
28098     smclass = 0;
28099   else if (flags & SECTION_TLS)
28100     smclass = 3;
28101   else if (flags & SECTION_WRITE)
28102     smclass = 2;
28103   else
28104     smclass = 1;
28105
28106   fprintf (asm_out_file, "\t.csect %s%s[%s],%u\n",
28107            (flags & SECTION_CODE) ? "." : "",
28108            name, suffix[smclass], flags & SECTION_ENTSIZE);
28109 }
28110
28111 #define IN_NAMED_SECTION(DECL) \
28112   ((TREE_CODE (DECL) == FUNCTION_DECL || TREE_CODE (DECL) == VAR_DECL) \
28113    && DECL_SECTION_NAME (DECL) != NULL)
28114
28115 static section *
28116 rs6000_xcoff_select_section (tree decl, int reloc,
28117                              unsigned HOST_WIDE_INT align)
28118 {
28119   /* Place variables with alignment stricter than BIGGEST_ALIGNMENT into
28120      named section.  */
28121   if (align > BIGGEST_ALIGNMENT)
28122     {
28123       resolve_unique_section (decl, reloc, true);
28124       if (IN_NAMED_SECTION (decl))
28125         return get_named_section (decl, NULL, reloc);
28126     }
28127
28128   if (decl_readonly_section (decl, reloc))
28129     {
28130       if (TREE_PUBLIC (decl))
28131         return read_only_data_section;
28132       else
28133         return read_only_private_data_section;
28134     }
28135   else
28136     {
28137 #if HAVE_AS_TLS
28138       if (TREE_CODE (decl) == VAR_DECL && DECL_THREAD_LOCAL_P (decl))
28139         {
28140           if (TREE_PUBLIC (decl))
28141             return tls_data_section;
28142           else if (bss_initializer_p (decl))
28143             {
28144               /* Convert to COMMON to emit in BSS.  */
28145               DECL_COMMON (decl) = 1;
28146               return tls_comm_section;
28147             }
28148           else
28149             return tls_private_data_section;
28150         }
28151       else
28152 #endif
28153         if (TREE_PUBLIC (decl))
28154         return data_section;
28155       else
28156         return private_data_section;
28157     }
28158 }
28159
28160 static void
28161 rs6000_xcoff_unique_section (tree decl, int reloc ATTRIBUTE_UNUSED)
28162 {
28163   const char *name;
28164
28165   /* Use select_section for private data and uninitialized data with
28166      alignment <= BIGGEST_ALIGNMENT.  */
28167   if (!TREE_PUBLIC (decl)
28168       || DECL_COMMON (decl)
28169       || (DECL_INITIAL (decl) == NULL_TREE
28170           && DECL_ALIGN (decl) <= BIGGEST_ALIGNMENT)
28171       || DECL_INITIAL (decl) == error_mark_node
28172       || (flag_zero_initialized_in_bss
28173           && initializer_zerop (DECL_INITIAL (decl))))
28174     return;
28175
28176   name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl));
28177   name = (*targetm.strip_name_encoding) (name);
28178   set_decl_section_name (decl, name);
28179 }
28180
28181 /* Select section for constant in constant pool.
28182
28183    On RS/6000, all constants are in the private read-only data area.
28184    However, if this is being placed in the TOC it must be output as a
28185    toc entry.  */
28186
28187 static section *
28188 rs6000_xcoff_select_rtx_section (machine_mode mode, rtx x,
28189                                  unsigned HOST_WIDE_INT align ATTRIBUTE_UNUSED)
28190 {
28191   if (ASM_OUTPUT_SPECIAL_POOL_ENTRY_P (x, mode))
28192     return toc_section;
28193   else
28194     return read_only_private_data_section;
28195 }
28196
28197 /* Remove any trailing [DS] or the like from the symbol name.  */
28198
28199 static const char *
28200 rs6000_xcoff_strip_name_encoding (const char *name)
28201 {
28202   size_t len;
28203   if (*name == '*')
28204     name++;
28205   len = strlen (name);
28206   if (name[len - 1] == ']')
28207     return ggc_alloc_string (name, len - 4);
28208   else
28209     return name;
28210 }
28211
28212 /* Section attributes.  AIX is always PIC.  */
28213
28214 static unsigned int
28215 rs6000_xcoff_section_type_flags (tree decl, const char *name, int reloc)
28216 {
28217   unsigned int align;
28218   unsigned int flags = default_section_type_flags (decl, name, reloc);
28219
28220   /* Align to at least UNIT size.  */
28221   if ((flags & SECTION_CODE) != 0 || !decl || !DECL_P (decl))
28222     align = MIN_UNITS_PER_WORD;
28223   else
28224     /* Increase alignment of large objects if not already stricter.  */
28225     align = MAX ((DECL_ALIGN (decl) / BITS_PER_UNIT),
28226                  int_size_in_bytes (TREE_TYPE (decl)) > MIN_UNITS_PER_WORD
28227                  ? UNITS_PER_FP_WORD : MIN_UNITS_PER_WORD);
28228
28229   return flags | (exact_log2 (align) & SECTION_ENTSIZE);
28230 }
28231
28232 /* Output at beginning of assembler file.
28233
28234    Initialize the section names for the RS/6000 at this point.
28235
28236    Specify filename, including full path, to assembler.
28237
28238    We want to go into the TOC section so at least one .toc will be emitted.
28239    Also, in order to output proper .bs/.es pairs, we need at least one static
28240    [RW] section emitted.
28241
28242    Finally, declare mcount when profiling to make the assembler happy.  */
28243
28244 static void
28245 rs6000_xcoff_file_start (void)
28246 {
28247   rs6000_gen_section_name (&xcoff_bss_section_name,
28248                            main_input_filename, ".bss_");
28249   rs6000_gen_section_name (&xcoff_private_data_section_name,
28250                            main_input_filename, ".rw_");
28251   rs6000_gen_section_name (&xcoff_private_rodata_section_name,
28252                            main_input_filename, ".rop_");
28253   rs6000_gen_section_name (&xcoff_read_only_section_name,
28254                            main_input_filename, ".ro_");
28255   rs6000_gen_section_name (&xcoff_tls_data_section_name,
28256                            main_input_filename, ".tls_");
28257   rs6000_gen_section_name (&xcoff_tbss_section_name,
28258                            main_input_filename, ".tbss_[UL]");
28259
28260   fputs ("\t.file\t", asm_out_file);
28261   output_quoted_string (asm_out_file, main_input_filename);
28262   fputc ('\n', asm_out_file);
28263   if (write_symbols != NO_DEBUG)
28264     switch_to_section (private_data_section);
28265   switch_to_section (toc_section);
28266   switch_to_section (text_section);
28267   if (profile_flag)
28268     fprintf (asm_out_file, "\t.extern %s\n", RS6000_MCOUNT);
28269   rs6000_file_start ();
28270 }
28271
28272 /* Output at end of assembler file.
28273    On the RS/6000, referencing data should automatically pull in text.  */
28274
28275 static void
28276 rs6000_xcoff_file_end (void)
28277 {
28278   switch_to_section (text_section);
28279   fputs ("_section_.text:\n", asm_out_file);
28280   switch_to_section (data_section);
28281   fputs (TARGET_32BIT
28282          ? "\t.long _section_.text\n" : "\t.llong _section_.text\n",
28283          asm_out_file);
28284 }
28285
28286 struct declare_alias_data
28287 {
28288   FILE *file;
28289   bool function_descriptor;
28290 };
28291
28292 /* Declare alias N.  A helper function for for_node_and_aliases.  */
28293
28294 static bool
28295 rs6000_declare_alias (struct symtab_node *n, void *d)
28296 {
28297   struct declare_alias_data *data = (struct declare_alias_data *)d;
28298   /* Main symbol is output specially, because varasm machinery does part of
28299      the job for us - we do not need to declare .globl/lglobs and such.  */
28300   if (!n->alias || n->weakref)
28301     return false;
28302
28303   if (lookup_attribute ("ifunc", DECL_ATTRIBUTES (n->decl)))
28304     return false;
28305
28306   /* Prevent assemble_alias from trying to use .set pseudo operation
28307      that does not behave as expected by the middle-end.  */
28308   TREE_ASM_WRITTEN (n->decl) = true;
28309
28310   const char *name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (n->decl));
28311   char *buffer = (char *) alloca (strlen (name) + 2);
28312   char *p;
28313   int dollar_inside = 0;
28314
28315   strcpy (buffer, name);
28316   p = strchr (buffer, '$');
28317   while (p) {
28318     *p = '_';
28319     dollar_inside++;
28320     p = strchr (p + 1, '$');
28321   }
28322   if (TREE_PUBLIC (n->decl))
28323     {
28324       if (!RS6000_WEAK || !DECL_WEAK (n->decl))
28325         {
28326           if (dollar_inside) {
28327               if (data->function_descriptor)
28328                 fprintf(data->file, "\t.rename .%s,\".%s\"\n", buffer, name);
28329               fprintf(data->file, "\t.rename %s,\"%s\"\n", buffer, name);
28330             }
28331           if (data->function_descriptor)
28332             {
28333               fputs ("\t.globl .", data->file);
28334               RS6000_OUTPUT_BASENAME (data->file, buffer);
28335               putc ('\n', data->file);
28336             }
28337           fputs ("\t.globl ", data->file);
28338           RS6000_OUTPUT_BASENAME (data->file, buffer);
28339           putc ('\n', data->file);
28340         }
28341 #ifdef ASM_WEAKEN_DECL
28342       else if (DECL_WEAK (n->decl) && !data->function_descriptor)
28343         ASM_WEAKEN_DECL (data->file, n->decl, name, NULL);
28344 #endif
28345     }
28346   else
28347     {
28348       if (dollar_inside)
28349         {
28350           if (data->function_descriptor)
28351             fprintf(data->file, "\t.rename .%s,\".%s\"\n", buffer, name);
28352           fprintf(data->file, "\t.rename %s,\"%s\"\n", buffer, name);
28353         }
28354       if (data->function_descriptor)
28355         {
28356           fputs ("\t.lglobl .", data->file);
28357           RS6000_OUTPUT_BASENAME (data->file, buffer);
28358           putc ('\n', data->file);
28359         }
28360       fputs ("\t.lglobl ", data->file);
28361       RS6000_OUTPUT_BASENAME (data->file, buffer);
28362       putc ('\n', data->file);
28363     }
28364   if (data->function_descriptor)
28365     fputs (".", data->file);
28366   RS6000_OUTPUT_BASENAME (data->file, buffer);
28367   fputs (":\n", data->file);
28368   return false;
28369 }
28370
28371
28372 #ifdef HAVE_GAS_HIDDEN
28373 /* Helper function to calculate visibility of a DECL
28374    and return the value as a const string.  */
28375
28376 static const char *
28377 rs6000_xcoff_visibility (tree decl)
28378 {
28379   static const char * const visibility_types[] = {
28380     "", ",protected", ",hidden", ",internal"
28381   };
28382
28383   enum symbol_visibility vis = DECL_VISIBILITY (decl);
28384   return visibility_types[vis];
28385 }
28386 #endif
28387
28388
28389 /* This macro produces the initial definition of a function name.
28390    On the RS/6000, we need to place an extra '.' in the function name and
28391    output the function descriptor.
28392    Dollar signs are converted to underscores.
28393
28394    The csect for the function will have already been created when
28395    text_section was selected.  We do have to go back to that csect, however.
28396
28397    The third and fourth parameters to the .function pseudo-op (16 and 044)
28398    are placeholders which no longer have any use.
28399
28400    Because AIX assembler's .set command has unexpected semantics, we output
28401    all aliases as alternative labels in front of the definition.  */
28402
28403 void
28404 rs6000_xcoff_declare_function_name (FILE *file, const char *name, tree decl)
28405 {
28406   char *buffer = (char *) alloca (strlen (name) + 1);
28407   char *p;
28408   int dollar_inside = 0;
28409   struct declare_alias_data data = {file, false};
28410
28411   strcpy (buffer, name);
28412   p = strchr (buffer, '$');
28413   while (p) {
28414     *p = '_';
28415     dollar_inside++;
28416     p = strchr (p + 1, '$');
28417   }
28418   if (TREE_PUBLIC (decl))
28419     {
28420       if (!RS6000_WEAK || !DECL_WEAK (decl))
28421         {
28422           if (dollar_inside) {
28423               fprintf(file, "\t.rename .%s,\".%s\"\n", buffer, name);
28424               fprintf(file, "\t.rename %s,\"%s\"\n", buffer, name);
28425             }
28426           fputs ("\t.globl .", file);
28427           RS6000_OUTPUT_BASENAME (file, buffer);
28428 #ifdef HAVE_GAS_HIDDEN
28429           fputs (rs6000_xcoff_visibility (decl), file);
28430 #endif
28431           putc ('\n', file);
28432         }
28433     }
28434   else
28435     {
28436       if (dollar_inside) {
28437           fprintf(file, "\t.rename .%s,\".%s\"\n", buffer, name);
28438           fprintf(file, "\t.rename %s,\"%s\"\n", buffer, name);
28439         }
28440       fputs ("\t.lglobl .", file);
28441       RS6000_OUTPUT_BASENAME (file, buffer);
28442       putc ('\n', file);
28443     }
28444   fputs ("\t.csect ", file);
28445   RS6000_OUTPUT_BASENAME (file, buffer);
28446   fputs (TARGET_32BIT ? "[DS]\n" : "[DS],3\n", file);
28447   RS6000_OUTPUT_BASENAME (file, buffer);
28448   fputs (":\n", file);
28449   symtab_node::get (decl)->call_for_symbol_and_aliases (rs6000_declare_alias,
28450                                                         &data, true);
28451   fputs (TARGET_32BIT ? "\t.long ." : "\t.llong .", file);
28452   RS6000_OUTPUT_BASENAME (file, buffer);
28453   fputs (", TOC[tc0], 0\n", file);
28454   in_section = NULL;
28455   switch_to_section (function_section (decl));
28456   putc ('.', file);
28457   RS6000_OUTPUT_BASENAME (file, buffer);
28458   fputs (":\n", file);
28459   data.function_descriptor = true;
28460   symtab_node::get (decl)->call_for_symbol_and_aliases (rs6000_declare_alias,
28461                                                         &data, true);
28462   if (!DECL_IGNORED_P (decl))
28463     {
28464       if (write_symbols == DBX_DEBUG || write_symbols == XCOFF_DEBUG)
28465         xcoffout_declare_function (file, decl, buffer);
28466       else if (write_symbols == DWARF2_DEBUG)
28467         {
28468           name = (*targetm.strip_name_encoding) (name);
28469           fprintf (file, "\t.function .%s,.%s,2,0\n", name, name);
28470         }
28471     }
28472   return;
28473 }
28474
28475
28476 /* Output assembly language to globalize a symbol from a DECL,
28477    possibly with visibility.  */
28478
28479 void
28480 rs6000_xcoff_asm_globalize_decl_name (FILE *stream, tree decl)
28481 {
28482   const char *name = XSTR (XEXP (DECL_RTL (decl), 0), 0);
28483   fputs (GLOBAL_ASM_OP, stream);
28484   RS6000_OUTPUT_BASENAME (stream, name);
28485 #ifdef HAVE_GAS_HIDDEN
28486   fputs (rs6000_xcoff_visibility (decl), stream);
28487 #endif
28488   putc ('\n', stream);
28489 }
28490
28491 /* Output assembly language to define a symbol as COMMON from a DECL,
28492    possibly with visibility.  */
28493
28494 void
28495 rs6000_xcoff_asm_output_aligned_decl_common (FILE *stream,
28496                                              tree decl ATTRIBUTE_UNUSED,
28497                                              const char *name,
28498                                              unsigned HOST_WIDE_INT size,
28499                                              unsigned HOST_WIDE_INT align)
28500 {
28501   unsigned HOST_WIDE_INT align2 = 2;
28502
28503   if (align > 32)
28504     align2 = floor_log2 (align / BITS_PER_UNIT);
28505   else if (size > 4)
28506     align2 = 3;
28507
28508   fputs (COMMON_ASM_OP, stream);
28509   RS6000_OUTPUT_BASENAME (stream, name);
28510
28511   fprintf (stream,
28512            "," HOST_WIDE_INT_PRINT_UNSIGNED "," HOST_WIDE_INT_PRINT_UNSIGNED,
28513            size, align2);
28514
28515 #ifdef HAVE_GAS_HIDDEN
28516   if (decl != NULL)
28517     fputs (rs6000_xcoff_visibility (decl), stream);
28518 #endif
28519   putc ('\n', stream);
28520 }
28521
28522 /* This macro produces the initial definition of a object (variable) name.
28523    Because AIX assembler's .set command has unexpected semantics, we output
28524    all aliases as alternative labels in front of the definition.  */
28525
28526 void
28527 rs6000_xcoff_declare_object_name (FILE *file, const char *name, tree decl)
28528 {
28529   struct declare_alias_data data = {file, false};
28530   RS6000_OUTPUT_BASENAME (file, name);
28531   fputs (":\n", file);
28532   symtab_node::get_create (decl)->call_for_symbol_and_aliases (rs6000_declare_alias,
28533                                                                &data, true);
28534 }
28535
28536 /* Overide the default 'SYMBOL-.' syntax with AIX compatible 'SYMBOL-$'. */
28537
28538 void
28539 rs6000_asm_output_dwarf_pcrel (FILE *file, int size, const char *label)
28540 {
28541   fputs (integer_asm_op (size, FALSE), file);
28542   assemble_name (file, label);
28543   fputs ("-$", file);
28544 }
28545
28546 /* Output a symbol offset relative to the dbase for the current object.
28547    We use __gcc_unwind_dbase as an arbitrary base for dbase and assume
28548    signed offsets.
28549
28550    __gcc_unwind_dbase is embedded in all executables/libraries through
28551    libgcc/config/rs6000/crtdbase.S.  */
28552
28553 void
28554 rs6000_asm_output_dwarf_datarel (FILE *file, int size, const char *label)
28555 {
28556   fputs (integer_asm_op (size, FALSE), file);
28557   assemble_name (file, label);
28558   fputs("-__gcc_unwind_dbase", file);
28559 }
28560
28561 #ifdef HAVE_AS_TLS
28562 static void
28563 rs6000_xcoff_encode_section_info (tree decl, rtx rtl, int first)
28564 {
28565   rtx symbol;
28566   int flags;
28567   const char *symname;
28568
28569   default_encode_section_info (decl, rtl, first);
28570
28571   /* Careful not to prod global register variables.  */
28572   if (!MEM_P (rtl))
28573     return;
28574   symbol = XEXP (rtl, 0);
28575   if (!SYMBOL_REF_P (symbol))
28576     return;
28577
28578   flags = SYMBOL_REF_FLAGS (symbol);
28579
28580   if (TREE_CODE (decl) == VAR_DECL && DECL_THREAD_LOCAL_P (decl))
28581     flags &= ~SYMBOL_FLAG_HAS_BLOCK_INFO;
28582
28583   SYMBOL_REF_FLAGS (symbol) = flags;
28584
28585   /* Append mapping class to extern decls.  */
28586   symname = XSTR (symbol, 0);
28587   if (decl /* sync condition with assemble_external () */
28588       && DECL_P (decl) && DECL_EXTERNAL (decl) && TREE_PUBLIC (decl)
28589       && ((TREE_CODE (decl) == VAR_DECL && !DECL_THREAD_LOCAL_P (decl))
28590           || TREE_CODE (decl) == FUNCTION_DECL)
28591       && symname[strlen (symname) - 1] != ']')
28592     {
28593       char *newname = (char *) alloca (strlen (symname) + 5);
28594       strcpy (newname, symname);
28595       strcat (newname, (TREE_CODE (decl) == FUNCTION_DECL
28596                         ? "[DS]" : "[UA]"));
28597       XSTR (symbol, 0) = ggc_strdup (newname);
28598     }
28599 }
28600 #endif /* HAVE_AS_TLS */
28601 #endif /* TARGET_XCOFF */
28602
28603 void
28604 rs6000_asm_weaken_decl (FILE *stream, tree decl,
28605                         const char *name, const char *val)
28606 {
28607   fputs ("\t.weak\t", stream);
28608   RS6000_OUTPUT_BASENAME (stream, name);
28609   if (decl && TREE_CODE (decl) == FUNCTION_DECL
28610       && DEFAULT_ABI == ABI_AIX && DOT_SYMBOLS)
28611     {
28612       if (TARGET_XCOFF)                                         
28613         fputs ("[DS]", stream);
28614 #if TARGET_XCOFF && HAVE_GAS_HIDDEN
28615       if (TARGET_XCOFF)
28616         fputs (rs6000_xcoff_visibility (decl), stream);
28617 #endif
28618       fputs ("\n\t.weak\t.", stream);
28619       RS6000_OUTPUT_BASENAME (stream, name);
28620     }
28621 #if TARGET_XCOFF && HAVE_GAS_HIDDEN
28622   if (TARGET_XCOFF)
28623     fputs (rs6000_xcoff_visibility (decl), stream);
28624 #endif
28625   fputc ('\n', stream);
28626   if (val)
28627     {
28628 #ifdef ASM_OUTPUT_DEF
28629       ASM_OUTPUT_DEF (stream, name, val);
28630 #endif
28631       if (decl && TREE_CODE (decl) == FUNCTION_DECL
28632           && DEFAULT_ABI == ABI_AIX && DOT_SYMBOLS)
28633         {
28634           fputs ("\t.set\t.", stream);
28635           RS6000_OUTPUT_BASENAME (stream, name);
28636           fputs (",.", stream);
28637           RS6000_OUTPUT_BASENAME (stream, val);
28638           fputc ('\n', stream);
28639         }
28640     }
28641 }
28642
28643
28644 /* Return true if INSN should not be copied.  */
28645
28646 static bool
28647 rs6000_cannot_copy_insn_p (rtx_insn *insn)
28648 {
28649   return recog_memoized (insn) >= 0
28650          && get_attr_cannot_copy (insn);
28651 }
28652
28653 /* Compute a (partial) cost for rtx X.  Return true if the complete
28654    cost has been computed, and false if subexpressions should be
28655    scanned.  In either case, *TOTAL contains the cost result.  */
28656
28657 static bool
28658 rs6000_rtx_costs (rtx x, machine_mode mode, int outer_code,
28659                   int opno ATTRIBUTE_UNUSED, int *total, bool speed)
28660 {
28661   int code = GET_CODE (x);
28662
28663   switch (code)
28664     {
28665       /* On the RS/6000, if it is valid in the insn, it is free.  */
28666     case CONST_INT:
28667       if (((outer_code == SET
28668             || outer_code == PLUS
28669             || outer_code == MINUS)
28670            && (satisfies_constraint_I (x)
28671                || satisfies_constraint_L (x)))
28672           || (outer_code == AND
28673               && (satisfies_constraint_K (x)
28674                   || (mode == SImode
28675                       ? satisfies_constraint_L (x)
28676                       : satisfies_constraint_J (x))))
28677           || ((outer_code == IOR || outer_code == XOR)
28678               && (satisfies_constraint_K (x)
28679                   || (mode == SImode
28680                       ? satisfies_constraint_L (x)
28681                       : satisfies_constraint_J (x))))
28682           || outer_code == ASHIFT
28683           || outer_code == ASHIFTRT
28684           || outer_code == LSHIFTRT
28685           || outer_code == ROTATE
28686           || outer_code == ROTATERT
28687           || outer_code == ZERO_EXTRACT
28688           || (outer_code == MULT
28689               && satisfies_constraint_I (x))
28690           || ((outer_code == DIV || outer_code == UDIV
28691                || outer_code == MOD || outer_code == UMOD)
28692               && exact_log2 (INTVAL (x)) >= 0)
28693           || (outer_code == COMPARE
28694               && (satisfies_constraint_I (x)
28695                   || satisfies_constraint_K (x)))
28696           || ((outer_code == EQ || outer_code == NE)
28697               && (satisfies_constraint_I (x)
28698                   || satisfies_constraint_K (x)
28699                   || (mode == SImode
28700                       ? satisfies_constraint_L (x)
28701                       : satisfies_constraint_J (x))))
28702           || (outer_code == GTU
28703               && satisfies_constraint_I (x))
28704           || (outer_code == LTU
28705               && satisfies_constraint_P (x)))
28706         {
28707           *total = 0;
28708           return true;
28709         }
28710       else if ((outer_code == PLUS
28711                 && reg_or_add_cint_operand (x, VOIDmode))
28712                || (outer_code == MINUS
28713                    && reg_or_sub_cint_operand (x, VOIDmode))
28714                || ((outer_code == SET
28715                     || outer_code == IOR
28716                     || outer_code == XOR)
28717                    && (INTVAL (x)
28718                        & ~ (unsigned HOST_WIDE_INT) 0xffffffff) == 0))
28719         {
28720           *total = COSTS_N_INSNS (1);
28721           return true;
28722         }
28723       /* FALLTHRU */
28724
28725     case CONST_DOUBLE:
28726     case CONST_WIDE_INT:
28727     case CONST:
28728     case HIGH:
28729     case SYMBOL_REF:
28730       *total = !speed ? COSTS_N_INSNS (1) + 1 : COSTS_N_INSNS (2);
28731       return true;
28732
28733     case MEM:
28734       /* When optimizing for size, MEM should be slightly more expensive
28735          than generating address, e.g., (plus (reg) (const)).
28736          L1 cache latency is about two instructions.  */
28737       *total = !speed ? COSTS_N_INSNS (1) + 1 : COSTS_N_INSNS (2);
28738       if (rs6000_slow_unaligned_access (mode, MEM_ALIGN (x)))
28739         *total += COSTS_N_INSNS (100);
28740       return true;
28741
28742     case LABEL_REF:
28743       *total = 0;
28744       return true;
28745
28746     case PLUS:
28747     case MINUS:
28748       if (FLOAT_MODE_P (mode))
28749         *total = rs6000_cost->fp;
28750       else
28751         *total = COSTS_N_INSNS (1);
28752       return false;
28753
28754     case MULT:
28755       if (CONST_INT_P (XEXP (x, 1))
28756           && satisfies_constraint_I (XEXP (x, 1)))
28757         {
28758           if (INTVAL (XEXP (x, 1)) >= -256
28759               && INTVAL (XEXP (x, 1)) <= 255)
28760             *total = rs6000_cost->mulsi_const9;
28761           else
28762             *total = rs6000_cost->mulsi_const;
28763         }
28764       else if (mode == SFmode)
28765         *total = rs6000_cost->fp;
28766       else if (FLOAT_MODE_P (mode))
28767         *total = rs6000_cost->dmul;
28768       else if (mode == DImode)
28769         *total = rs6000_cost->muldi;
28770       else
28771         *total = rs6000_cost->mulsi;
28772       return false;
28773
28774     case FMA:
28775       if (mode == SFmode)
28776         *total = rs6000_cost->fp;
28777       else
28778         *total = rs6000_cost->dmul;
28779       break;
28780
28781     case DIV:
28782     case MOD:
28783       if (FLOAT_MODE_P (mode))
28784         {
28785           *total = mode == DFmode ? rs6000_cost->ddiv
28786                                   : rs6000_cost->sdiv;
28787           return false;
28788         }
28789       /* FALLTHRU */
28790
28791     case UDIV:
28792     case UMOD:
28793       if (CONST_INT_P (XEXP (x, 1))
28794           && exact_log2 (INTVAL (XEXP (x, 1))) >= 0)
28795         {
28796           if (code == DIV || code == MOD)
28797             /* Shift, addze */
28798             *total = COSTS_N_INSNS (2);
28799           else
28800             /* Shift */
28801             *total = COSTS_N_INSNS (1);
28802         }
28803       else
28804         {
28805           if (GET_MODE (XEXP (x, 1)) == DImode)
28806             *total = rs6000_cost->divdi;
28807           else
28808             *total = rs6000_cost->divsi;
28809         }
28810       /* Add in shift and subtract for MOD unless we have a mod instruction. */
28811       if (!TARGET_MODULO && (code == MOD || code == UMOD))
28812         *total += COSTS_N_INSNS (2);
28813       return false;
28814
28815     case CTZ:
28816       *total = COSTS_N_INSNS (TARGET_CTZ ? 1 : 4);
28817       return false;
28818
28819     case FFS:
28820       *total = COSTS_N_INSNS (4);
28821       return false;
28822
28823     case POPCOUNT:
28824       *total = COSTS_N_INSNS (TARGET_POPCNTD ? 1 : 6);
28825       return false;
28826
28827     case PARITY:
28828       *total = COSTS_N_INSNS (TARGET_CMPB ? 2 : 6);
28829       return false;
28830
28831     case NOT:
28832       if (outer_code == AND || outer_code == IOR || outer_code == XOR)
28833         *total = 0;
28834       else
28835         *total = COSTS_N_INSNS (1);
28836       return false;
28837
28838     case AND:
28839       if (CONST_INT_P (XEXP (x, 1)))
28840         {
28841           rtx left = XEXP (x, 0);
28842           rtx_code left_code = GET_CODE (left);
28843
28844           /* rotate-and-mask: 1 insn.  */
28845           if ((left_code == ROTATE
28846                || left_code == ASHIFT
28847                || left_code == LSHIFTRT)
28848               && rs6000_is_valid_shift_mask (XEXP (x, 1), left, mode))
28849             {
28850               *total = rtx_cost (XEXP (left, 0), mode, left_code, 0, speed);
28851               if (!CONST_INT_P (XEXP (left, 1)))
28852                 *total += rtx_cost (XEXP (left, 1), SImode, left_code, 1, speed);
28853               *total += COSTS_N_INSNS (1);
28854               return true;
28855             }
28856
28857           /* rotate-and-mask (no rotate), andi., andis.: 1 insn.  */
28858           HOST_WIDE_INT val = INTVAL (XEXP (x, 1));
28859           if (rs6000_is_valid_and_mask (XEXP (x, 1), mode)
28860               || (val & 0xffff) == val
28861               || (val & 0xffff0000) == val
28862               || ((val & 0xffff) == 0 && mode == SImode))
28863             {
28864               *total = rtx_cost (left, mode, AND, 0, speed);
28865               *total += COSTS_N_INSNS (1);
28866               return true;
28867             }
28868
28869           /* 2 insns.  */
28870           if (rs6000_is_valid_2insn_and (XEXP (x, 1), mode))
28871             {
28872               *total = rtx_cost (left, mode, AND, 0, speed);
28873               *total += COSTS_N_INSNS (2);
28874               return true;
28875             }
28876         }
28877
28878       *total = COSTS_N_INSNS (1);
28879       return false;
28880
28881     case IOR:
28882       /* FIXME */
28883       *total = COSTS_N_INSNS (1);
28884       return true;
28885
28886     case CLZ:
28887     case XOR:
28888     case ZERO_EXTRACT:
28889       *total = COSTS_N_INSNS (1);
28890       return false;
28891
28892     case ASHIFT:
28893       /* The EXTSWSLI instruction is a combined instruction.  Don't count both
28894          the sign extend and shift separately within the insn.  */
28895       if (TARGET_EXTSWSLI && mode == DImode
28896           && GET_CODE (XEXP (x, 0)) == SIGN_EXTEND
28897           && GET_MODE (XEXP (XEXP (x, 0), 0)) == SImode)
28898         {
28899           *total = 0;
28900           return false;
28901         }
28902       /* fall through */
28903           
28904     case ASHIFTRT:
28905     case LSHIFTRT:
28906     case ROTATE:
28907     case ROTATERT:
28908       /* Handle mul_highpart.  */
28909       if (outer_code == TRUNCATE
28910           && GET_CODE (XEXP (x, 0)) == MULT)
28911         {
28912           if (mode == DImode)
28913             *total = rs6000_cost->muldi;
28914           else
28915             *total = rs6000_cost->mulsi;
28916           return true;
28917         }
28918       else if (outer_code == AND)
28919         *total = 0;
28920       else
28921         *total = COSTS_N_INSNS (1);
28922       return false;
28923
28924     case SIGN_EXTEND:
28925     case ZERO_EXTEND:
28926       if (MEM_P (XEXP (x, 0)))
28927         *total = 0;
28928       else
28929         *total = COSTS_N_INSNS (1);
28930       return false;
28931
28932     case COMPARE:
28933     case NEG:
28934     case ABS:
28935       if (!FLOAT_MODE_P (mode))
28936         {
28937           *total = COSTS_N_INSNS (1);
28938           return false;
28939         }
28940       /* FALLTHRU */
28941
28942     case FLOAT:
28943     case UNSIGNED_FLOAT:
28944     case FIX:
28945     case UNSIGNED_FIX:
28946     case FLOAT_TRUNCATE:
28947       *total = rs6000_cost->fp;
28948       return false;
28949
28950     case FLOAT_EXTEND:
28951       if (mode == DFmode)
28952         *total = rs6000_cost->sfdf_convert;
28953       else
28954         *total = rs6000_cost->fp;
28955       return false;
28956
28957     case UNSPEC:
28958       switch (XINT (x, 1))
28959         {
28960         case UNSPEC_FRSP:
28961           *total = rs6000_cost->fp;
28962           return true;
28963
28964         default:
28965           break;
28966         }
28967       break;
28968
28969     case CALL:
28970     case IF_THEN_ELSE:
28971       if (!speed)
28972         {
28973           *total = COSTS_N_INSNS (1);
28974           return true;
28975         }
28976       else if (FLOAT_MODE_P (mode) && TARGET_PPC_GFXOPT && TARGET_HARD_FLOAT)
28977         {
28978           *total = rs6000_cost->fp;
28979           return false;
28980         }
28981       break;
28982
28983     case NE:
28984     case EQ:
28985     case GTU:
28986     case LTU:
28987       /* Carry bit requires mode == Pmode.
28988          NEG or PLUS already counted so only add one.  */
28989       if (mode == Pmode
28990           && (outer_code == NEG || outer_code == PLUS))
28991         {
28992           *total = COSTS_N_INSNS (1);
28993           return true;
28994         }
28995       /* FALLTHRU */
28996
28997     case GT:
28998     case LT:
28999     case UNORDERED:
29000       if (outer_code == SET)
29001         {
29002           if (XEXP (x, 1) == const0_rtx)
29003             {
29004               *total = COSTS_N_INSNS (2);
29005               return true;
29006             }
29007           else
29008             {
29009               *total = COSTS_N_INSNS (3);
29010               return false;
29011             }
29012         }
29013       /* CC COMPARE.  */
29014       if (outer_code == COMPARE)
29015         {
29016           *total = 0;
29017           return true;
29018         }
29019       break;
29020
29021     default:
29022       break;
29023     }
29024
29025   return false;
29026 }
29027
29028 /* Debug form of r6000_rtx_costs that is selected if -mdebug=cost.  */
29029
29030 static bool
29031 rs6000_debug_rtx_costs (rtx x, machine_mode mode, int outer_code,
29032                         int opno, int *total, bool speed)
29033 {
29034   bool ret = rs6000_rtx_costs (x, mode, outer_code, opno, total, speed);
29035
29036   fprintf (stderr,
29037            "\nrs6000_rtx_costs, return = %s, mode = %s, outer_code = %s, "
29038            "opno = %d, total = %d, speed = %s, x:\n",
29039            ret ? "complete" : "scan inner",
29040            GET_MODE_NAME (mode),
29041            GET_RTX_NAME (outer_code),
29042            opno,
29043            *total,
29044            speed ? "true" : "false");
29045
29046   debug_rtx (x);
29047
29048   return ret;
29049 }
29050
29051 static int
29052 rs6000_insn_cost (rtx_insn *insn, bool speed)
29053 {
29054   if (recog_memoized (insn) < 0)
29055     return 0;
29056
29057   if (!speed)
29058     return get_attr_length (insn);
29059
29060   int cost = get_attr_cost (insn);
29061   if (cost > 0)
29062     return cost;
29063
29064   int n = get_attr_length (insn) / 4;
29065   enum attr_type type = get_attr_type (insn);
29066
29067   switch (type)
29068     {
29069     case TYPE_LOAD:
29070     case TYPE_FPLOAD:
29071     case TYPE_VECLOAD:
29072       cost = COSTS_N_INSNS (n + 1);
29073       break;
29074
29075     case TYPE_MUL:
29076       switch (get_attr_size (insn))
29077         {
29078         case SIZE_8:
29079           cost = COSTS_N_INSNS (n - 1) + rs6000_cost->mulsi_const9;
29080           break;
29081         case SIZE_16:
29082           cost = COSTS_N_INSNS (n - 1) + rs6000_cost->mulsi_const;
29083           break;
29084         case SIZE_32:
29085           cost = COSTS_N_INSNS (n - 1) + rs6000_cost->mulsi;
29086           break;
29087         case SIZE_64:
29088           cost = COSTS_N_INSNS (n - 1) + rs6000_cost->muldi;
29089           break;
29090         default:
29091           gcc_unreachable ();
29092         }
29093       break;
29094     case TYPE_DIV:
29095       switch (get_attr_size (insn))
29096         {
29097         case SIZE_32:
29098           cost = COSTS_N_INSNS (n - 1) + rs6000_cost->divsi;
29099           break;
29100         case SIZE_64:
29101           cost = COSTS_N_INSNS (n - 1) + rs6000_cost->divdi;
29102           break;
29103         default:
29104           gcc_unreachable ();
29105         }
29106       break;
29107
29108     case TYPE_FP:
29109       cost = n * rs6000_cost->fp;
29110       break;
29111     case TYPE_DMUL:
29112       cost = n * rs6000_cost->dmul;
29113       break;
29114     case TYPE_SDIV:
29115       cost = n * rs6000_cost->sdiv;
29116       break;
29117     case TYPE_DDIV:
29118       cost = n * rs6000_cost->ddiv;
29119       break;
29120
29121     case TYPE_SYNC:
29122     case TYPE_LOAD_L:
29123     case TYPE_MFCR:
29124     case TYPE_MFCRF:
29125       cost = COSTS_N_INSNS (n + 2);
29126       break;
29127
29128     default:
29129       cost = COSTS_N_INSNS (n);
29130     }
29131
29132   return cost;
29133 }
29134
29135 /* Debug form of ADDRESS_COST that is selected if -mdebug=cost.  */
29136
29137 static int
29138 rs6000_debug_address_cost (rtx x, machine_mode mode,
29139                            addr_space_t as, bool speed)
29140 {
29141   int ret = TARGET_ADDRESS_COST (x, mode, as, speed);
29142
29143   fprintf (stderr, "\nrs6000_address_cost, return = %d, speed = %s, x:\n",
29144            ret, speed ? "true" : "false");
29145   debug_rtx (x);
29146
29147   return ret;
29148 }
29149
29150
29151 /* A C expression returning the cost of moving data from a register of class
29152    CLASS1 to one of CLASS2.  */
29153
29154 static int
29155 rs6000_register_move_cost (machine_mode mode,
29156                            reg_class_t from, reg_class_t to)
29157 {
29158   int ret;
29159   reg_class_t rclass;
29160
29161   if (TARGET_DEBUG_COST)
29162     dbg_cost_ctrl++;
29163
29164   /* If we have VSX, we can easily move between FPR or Altivec registers,
29165      otherwise we can only easily move within classes.
29166      Do this first so we give best-case answers for union classes
29167      containing both gprs and vsx regs.  */
29168   HARD_REG_SET to_vsx, from_vsx;
29169   COPY_HARD_REG_SET (to_vsx, reg_class_contents[to]);
29170   AND_HARD_REG_SET (to_vsx, reg_class_contents[VSX_REGS]);
29171   COPY_HARD_REG_SET (from_vsx, reg_class_contents[from]);
29172   AND_HARD_REG_SET (from_vsx, reg_class_contents[VSX_REGS]);
29173   if (!hard_reg_set_empty_p (to_vsx)
29174       && !hard_reg_set_empty_p (from_vsx)
29175       && (TARGET_VSX
29176           || hard_reg_set_intersect_p (to_vsx, from_vsx)))
29177     {
29178       int reg = FIRST_FPR_REGNO;
29179       if (TARGET_VSX
29180           || (TEST_HARD_REG_BIT (to_vsx, FIRST_ALTIVEC_REGNO)
29181               && TEST_HARD_REG_BIT (from_vsx, FIRST_ALTIVEC_REGNO)))
29182         reg = FIRST_ALTIVEC_REGNO;
29183       ret = 2 * hard_regno_nregs (reg, mode);
29184     }
29185
29186   /*  Moves from/to GENERAL_REGS.  */
29187   else if ((rclass = from, reg_classes_intersect_p (to, GENERAL_REGS))
29188            || (rclass = to, reg_classes_intersect_p (from, GENERAL_REGS)))
29189     {
29190       if (rclass == FLOAT_REGS || rclass == ALTIVEC_REGS || rclass == VSX_REGS)
29191         {
29192           if (TARGET_DIRECT_MOVE)
29193             {
29194               /* Keep the cost for direct moves above that for within
29195                  a register class even if the actual processor cost is
29196                  comparable.  We do this because a direct move insn
29197                  can't be a nop, whereas with ideal register
29198                  allocation a move within the same class might turn
29199                  out to be a nop.  */
29200               if (rs6000_tune == PROCESSOR_POWER9
29201                   || rs6000_tune == PROCESSOR_FUTURE)
29202                 ret = 3 * hard_regno_nregs (FIRST_GPR_REGNO, mode);
29203               else
29204                 ret = 4 * hard_regno_nregs (FIRST_GPR_REGNO, mode);
29205               /* SFmode requires a conversion when moving between gprs
29206                  and vsx.  */
29207               if (mode == SFmode)
29208                 ret += 2;
29209             }
29210           else
29211             ret = (rs6000_memory_move_cost (mode, rclass, false)
29212                    + rs6000_memory_move_cost (mode, GENERAL_REGS, false));
29213         }
29214
29215       /* It's more expensive to move CR_REGS than CR0_REGS because of the
29216          shift.  */
29217       else if (rclass == CR_REGS)
29218         ret = 4;
29219
29220       /* For those processors that have slow LR/CTR moves, make them more
29221          expensive than memory in order to bias spills to memory .*/
29222       else if ((rs6000_tune == PROCESSOR_POWER6
29223                 || rs6000_tune == PROCESSOR_POWER7
29224                 || rs6000_tune == PROCESSOR_POWER8
29225                 || rs6000_tune == PROCESSOR_POWER9)
29226                && reg_class_subset_p (rclass, SPECIAL_REGS))
29227         ret = 6 * hard_regno_nregs (FIRST_GPR_REGNO, mode);
29228
29229       else
29230         /* A move will cost one instruction per GPR moved.  */
29231         ret = 2 * hard_regno_nregs (FIRST_GPR_REGNO, mode);
29232     }
29233
29234   /* Everything else has to go through GENERAL_REGS.  */
29235   else
29236     ret = (rs6000_register_move_cost (mode, GENERAL_REGS, to)
29237            + rs6000_register_move_cost (mode, from, GENERAL_REGS));
29238
29239   if (TARGET_DEBUG_COST)
29240     {
29241       if (dbg_cost_ctrl == 1)
29242         fprintf (stderr,
29243                  "rs6000_register_move_cost: ret=%d, mode=%s, from=%s, to=%s\n",
29244                  ret, GET_MODE_NAME (mode), reg_class_names[from],
29245                  reg_class_names[to]);
29246       dbg_cost_ctrl--;
29247     }
29248
29249   return ret;
29250 }
29251
29252 /* A C expressions returning the cost of moving data of MODE from a register to
29253    or from memory.  */
29254
29255 static int
29256 rs6000_memory_move_cost (machine_mode mode, reg_class_t rclass,
29257                          bool in ATTRIBUTE_UNUSED)
29258 {
29259   int ret;
29260
29261   if (TARGET_DEBUG_COST)
29262     dbg_cost_ctrl++;
29263
29264   if (reg_classes_intersect_p (rclass, GENERAL_REGS))
29265     ret = 4 * hard_regno_nregs (0, mode);
29266   else if ((reg_classes_intersect_p (rclass, FLOAT_REGS)
29267             || reg_classes_intersect_p (rclass, VSX_REGS)))
29268     ret = 4 * hard_regno_nregs (32, mode);
29269   else if (reg_classes_intersect_p (rclass, ALTIVEC_REGS))
29270     ret = 4 * hard_regno_nregs (FIRST_ALTIVEC_REGNO, mode);
29271   else
29272     ret = 4 + rs6000_register_move_cost (mode, rclass, GENERAL_REGS);
29273
29274   if (TARGET_DEBUG_COST)
29275     {
29276       if (dbg_cost_ctrl == 1)
29277         fprintf (stderr,
29278                  "rs6000_memory_move_cost: ret=%d, mode=%s, rclass=%s, in=%d\n",
29279                  ret, GET_MODE_NAME (mode), reg_class_names[rclass], in);
29280       dbg_cost_ctrl--;
29281     }
29282
29283   return ret;
29284 }
29285
29286 /* Implement TARGET_IRA_CHANGE_PSEUDO_ALLOCNO_CLASS.
29287
29288    The register allocator chooses GEN_OR_VSX_REGS for the allocno
29289    class if GENERAL_REGS and VSX_REGS cost is lower than the memory
29290    cost.  This happens a lot when TARGET_DIRECT_MOVE makes the register
29291    move cost between GENERAL_REGS and VSX_REGS low.
29292
29293    It might seem reasonable to use a union class.  After all, if usage
29294    of vsr is low and gpr high, it might make sense to spill gpr to vsr
29295    rather than memory.  However, in cases where register pressure of
29296    both is high, like the cactus_adm spec test, allowing
29297    GEN_OR_VSX_REGS as the allocno class results in bad decisions in
29298    the first scheduling pass.  This is partly due to an allocno of
29299    GEN_OR_VSX_REGS wrongly contributing to the GENERAL_REGS pressure
29300    class, which gives too high a pressure for GENERAL_REGS and too low
29301    for VSX_REGS.  So, force a choice of the subclass here.
29302
29303    The best class is also the union if GENERAL_REGS and VSX_REGS have
29304    the same cost.  In that case we do use GEN_OR_VSX_REGS as the
29305    allocno class, since trying to narrow down the class by regno mode
29306    is prone to error.  For example, SImode is allowed in VSX regs and
29307    in some cases (eg. gcc.target/powerpc/p9-xxbr-3.c do_bswap32_vect)
29308    it would be wrong to choose an allocno of GENERAL_REGS based on
29309    SImode.  */
29310
29311 static reg_class_t
29312 rs6000_ira_change_pseudo_allocno_class (int regno ATTRIBUTE_UNUSED,
29313                                         reg_class_t allocno_class,
29314                                         reg_class_t best_class)
29315 {
29316   switch (allocno_class)
29317     {
29318     case GEN_OR_VSX_REGS:
29319       /* best_class must be a subset of allocno_class.  */
29320       gcc_checking_assert (best_class == GEN_OR_VSX_REGS
29321                            || best_class == GEN_OR_FLOAT_REGS
29322                            || best_class == VSX_REGS
29323                            || best_class == ALTIVEC_REGS
29324                            || best_class == FLOAT_REGS
29325                            || best_class == GENERAL_REGS
29326                            || best_class == BASE_REGS);
29327       /* Use best_class but choose wider classes when copying from the
29328          wider class to best_class is cheap.  This mimics IRA choice
29329          of allocno class.  */
29330       if (best_class == BASE_REGS)
29331         return GENERAL_REGS;
29332       if (TARGET_VSX
29333           && (best_class == FLOAT_REGS || best_class == ALTIVEC_REGS))
29334         return VSX_REGS;
29335       return best_class;
29336
29337     default:
29338       break;
29339     }
29340
29341   return allocno_class;
29342 }
29343
29344 /* Returns a code for a target-specific builtin that implements
29345    reciprocal of the function, or NULL_TREE if not available.  */
29346
29347 static tree
29348 rs6000_builtin_reciprocal (tree fndecl)
29349 {
29350   switch (DECL_FUNCTION_CODE (fndecl))
29351     {
29352     case VSX_BUILTIN_XVSQRTDP:
29353       if (!RS6000_RECIP_AUTO_RSQRTE_P (V2DFmode))
29354         return NULL_TREE;
29355
29356       return rs6000_builtin_decls[VSX_BUILTIN_RSQRT_2DF];
29357
29358     case VSX_BUILTIN_XVSQRTSP:
29359       if (!RS6000_RECIP_AUTO_RSQRTE_P (V4SFmode))
29360         return NULL_TREE;
29361
29362       return rs6000_builtin_decls[VSX_BUILTIN_RSQRT_4SF];
29363
29364     default:
29365       return NULL_TREE;
29366     }
29367 }
29368
29369 /* Load up a constant.  If the mode is a vector mode, splat the value across
29370    all of the vector elements.  */
29371
29372 static rtx
29373 rs6000_load_constant_and_splat (machine_mode mode, REAL_VALUE_TYPE dconst)
29374 {
29375   rtx reg;
29376
29377   if (mode == SFmode || mode == DFmode)
29378     {
29379       rtx d = const_double_from_real_value (dconst, mode);
29380       reg = force_reg (mode, d);
29381     }
29382   else if (mode == V4SFmode)
29383     {
29384       rtx d = const_double_from_real_value (dconst, SFmode);
29385       rtvec v = gen_rtvec (4, d, d, d, d);
29386       reg = gen_reg_rtx (mode);
29387       rs6000_expand_vector_init (reg, gen_rtx_PARALLEL (mode, v));
29388     }
29389   else if (mode == V2DFmode)
29390     {
29391       rtx d = const_double_from_real_value (dconst, DFmode);
29392       rtvec v = gen_rtvec (2, d, d);
29393       reg = gen_reg_rtx (mode);
29394       rs6000_expand_vector_init (reg, gen_rtx_PARALLEL (mode, v));
29395     }
29396   else
29397     gcc_unreachable ();
29398
29399   return reg;
29400 }
29401
29402 /* Generate an FMA instruction.  */
29403
29404 static void
29405 rs6000_emit_madd (rtx target, rtx m1, rtx m2, rtx a)
29406 {
29407   machine_mode mode = GET_MODE (target);
29408   rtx dst;
29409
29410   dst = expand_ternary_op (mode, fma_optab, m1, m2, a, target, 0);
29411   gcc_assert (dst != NULL);
29412
29413   if (dst != target)
29414     emit_move_insn (target, dst);
29415 }
29416
29417 /* Generate a FNMSUB instruction: dst = -fma(m1, m2, -a).  */
29418
29419 static void
29420 rs6000_emit_nmsub (rtx dst, rtx m1, rtx m2, rtx a)
29421 {
29422   machine_mode mode = GET_MODE (dst);
29423   rtx r;
29424
29425   /* This is a tad more complicated, since the fnma_optab is for
29426      a different expression: fma(-m1, m2, a), which is the same
29427      thing except in the case of signed zeros.
29428
29429      Fortunately we know that if FMA is supported that FNMSUB is
29430      also supported in the ISA.  Just expand it directly.  */
29431
29432   gcc_assert (optab_handler (fma_optab, mode) != CODE_FOR_nothing);
29433
29434   r = gen_rtx_NEG (mode, a);
29435   r = gen_rtx_FMA (mode, m1, m2, r);
29436   r = gen_rtx_NEG (mode, r);
29437   emit_insn (gen_rtx_SET (dst, r));
29438 }
29439
29440 /* Newton-Raphson approximation of floating point divide DST = N/D.  If NOTE_P,
29441    add a reg_note saying that this was a division.  Support both scalar and
29442    vector divide.  Assumes no trapping math and finite arguments.  */
29443
29444 void
29445 rs6000_emit_swdiv (rtx dst, rtx n, rtx d, bool note_p)
29446 {
29447   machine_mode mode = GET_MODE (dst);
29448   rtx one, x0, e0, x1, xprev, eprev, xnext, enext, u, v;
29449   int i;
29450
29451   /* Low precision estimates guarantee 5 bits of accuracy.  High
29452      precision estimates guarantee 14 bits of accuracy.  SFmode
29453      requires 23 bits of accuracy.  DFmode requires 52 bits of
29454      accuracy.  Each pass at least doubles the accuracy, leading
29455      to the following.  */
29456   int passes = (TARGET_RECIP_PRECISION) ? 1 : 3;
29457   if (mode == DFmode || mode == V2DFmode)
29458     passes++;
29459
29460   enum insn_code code = optab_handler (smul_optab, mode);
29461   insn_gen_fn gen_mul = GEN_FCN (code);
29462
29463   gcc_assert (code != CODE_FOR_nothing);
29464
29465   one = rs6000_load_constant_and_splat (mode, dconst1);
29466
29467   /* x0 = 1./d estimate */
29468   x0 = gen_reg_rtx (mode);
29469   emit_insn (gen_rtx_SET (x0, gen_rtx_UNSPEC (mode, gen_rtvec (1, d),
29470                                               UNSPEC_FRES)));
29471
29472   /* Each iteration but the last calculates x_(i+1) = x_i * (2 - d * x_i).  */
29473   if (passes > 1) {
29474
29475     /* e0 = 1. - d * x0  */
29476     e0 = gen_reg_rtx (mode);
29477     rs6000_emit_nmsub (e0, d, x0, one);
29478
29479     /* x1 = x0 + e0 * x0  */
29480     x1 = gen_reg_rtx (mode);
29481     rs6000_emit_madd (x1, e0, x0, x0);
29482
29483     for (i = 0, xprev = x1, eprev = e0; i < passes - 2;
29484          ++i, xprev = xnext, eprev = enext) {
29485       
29486       /* enext = eprev * eprev  */
29487       enext = gen_reg_rtx (mode);
29488       emit_insn (gen_mul (enext, eprev, eprev));
29489
29490       /* xnext = xprev + enext * xprev  */
29491       xnext = gen_reg_rtx (mode);
29492       rs6000_emit_madd (xnext, enext, xprev, xprev);
29493     }
29494
29495   } else
29496     xprev = x0;
29497
29498   /* The last iteration calculates x_(i+1) = n * x_i * (2 - d * x_i).  */
29499
29500   /* u = n * xprev  */
29501   u = gen_reg_rtx (mode);
29502   emit_insn (gen_mul (u, n, xprev));
29503
29504   /* v = n - (d * u)  */
29505   v = gen_reg_rtx (mode);
29506   rs6000_emit_nmsub (v, d, u, n);
29507
29508   /* dst = (v * xprev) + u  */
29509   rs6000_emit_madd (dst, v, xprev, u);
29510
29511   if (note_p)
29512     add_reg_note (get_last_insn (), REG_EQUAL, gen_rtx_DIV (mode, n, d));
29513 }
29514
29515 /* Goldschmidt's Algorithm for single/double-precision floating point
29516    sqrt and rsqrt.  Assumes no trapping math and finite arguments.  */
29517
29518 void
29519 rs6000_emit_swsqrt (rtx dst, rtx src, bool recip)
29520 {
29521   machine_mode mode = GET_MODE (src);
29522   rtx e = gen_reg_rtx (mode);
29523   rtx g = gen_reg_rtx (mode);
29524   rtx h = gen_reg_rtx (mode);
29525
29526   /* Low precision estimates guarantee 5 bits of accuracy.  High
29527      precision estimates guarantee 14 bits of accuracy.  SFmode
29528      requires 23 bits of accuracy.  DFmode requires 52 bits of
29529      accuracy.  Each pass at least doubles the accuracy, leading
29530      to the following.  */
29531   int passes = (TARGET_RECIP_PRECISION) ? 1 : 3;
29532   if (mode == DFmode || mode == V2DFmode)
29533     passes++;
29534
29535   int i;
29536   rtx mhalf;
29537   enum insn_code code = optab_handler (smul_optab, mode);
29538   insn_gen_fn gen_mul = GEN_FCN (code);
29539
29540   gcc_assert (code != CODE_FOR_nothing);
29541
29542   mhalf = rs6000_load_constant_and_splat (mode, dconsthalf);
29543
29544   /* e = rsqrt estimate */
29545   emit_insn (gen_rtx_SET (e, gen_rtx_UNSPEC (mode, gen_rtvec (1, src),
29546                                              UNSPEC_RSQRT)));
29547
29548   /* If (src == 0.0) filter infinity to prevent NaN for sqrt(0.0).  */
29549   if (!recip)
29550     {
29551       rtx zero = force_reg (mode, CONST0_RTX (mode));
29552
29553       if (mode == SFmode)
29554         {
29555           rtx target = emit_conditional_move (e, GT, src, zero, mode,
29556                                               e, zero, mode, 0);
29557           if (target != e)
29558             emit_move_insn (e, target);
29559         }
29560       else
29561         {
29562           rtx cond = gen_rtx_GT (VOIDmode, e, zero);
29563           rs6000_emit_vector_cond_expr (e, e, zero, cond, src, zero);
29564         }
29565     }
29566
29567   /* g = sqrt estimate.  */
29568   emit_insn (gen_mul (g, e, src));
29569   /* h = 1/(2*sqrt) estimate.  */
29570   emit_insn (gen_mul (h, e, mhalf));
29571
29572   if (recip)
29573     {
29574       if (passes == 1)
29575         {
29576           rtx t = gen_reg_rtx (mode);
29577           rs6000_emit_nmsub (t, g, h, mhalf);
29578           /* Apply correction directly to 1/rsqrt estimate.  */
29579           rs6000_emit_madd (dst, e, t, e);
29580         }
29581       else
29582         {
29583           for (i = 0; i < passes; i++)
29584             {
29585               rtx t1 = gen_reg_rtx (mode);
29586               rtx g1 = gen_reg_rtx (mode);
29587               rtx h1 = gen_reg_rtx (mode);
29588
29589               rs6000_emit_nmsub (t1, g, h, mhalf);
29590               rs6000_emit_madd (g1, g, t1, g);
29591               rs6000_emit_madd (h1, h, t1, h);
29592
29593               g = g1;
29594               h = h1;
29595             }
29596           /* Multiply by 2 for 1/rsqrt.  */
29597           emit_insn (gen_add3_insn (dst, h, h));
29598         }
29599     }
29600   else
29601     {
29602       rtx t = gen_reg_rtx (mode);
29603       rs6000_emit_nmsub (t, g, h, mhalf);
29604       rs6000_emit_madd (dst, g, t, g);
29605     }
29606
29607   return;
29608 }
29609
29610 /* Emit popcount intrinsic on TARGET_POPCNTB (Power5) and TARGET_POPCNTD
29611    (Power7) targets.  DST is the target, and SRC is the argument operand.  */
29612
29613 void
29614 rs6000_emit_popcount (rtx dst, rtx src)
29615 {
29616   machine_mode mode = GET_MODE (dst);
29617   rtx tmp1, tmp2;
29618
29619   /* Use the PPC ISA 2.06 popcnt{w,d} instruction if we can.  */
29620   if (TARGET_POPCNTD)
29621     {
29622       if (mode == SImode)
29623         emit_insn (gen_popcntdsi2 (dst, src));
29624       else
29625         emit_insn (gen_popcntddi2 (dst, src));
29626       return;
29627     }
29628
29629   tmp1 = gen_reg_rtx (mode);
29630
29631   if (mode == SImode)
29632     {
29633       emit_insn (gen_popcntbsi2 (tmp1, src));
29634       tmp2 = expand_mult (SImode, tmp1, GEN_INT (0x01010101),
29635                            NULL_RTX, 0);
29636       tmp2 = force_reg (SImode, tmp2);
29637       emit_insn (gen_lshrsi3 (dst, tmp2, GEN_INT (24)));
29638     }
29639   else
29640     {
29641       emit_insn (gen_popcntbdi2 (tmp1, src));
29642       tmp2 = expand_mult (DImode, tmp1,
29643                           GEN_INT ((HOST_WIDE_INT)
29644                                    0x01010101 << 32 | 0x01010101),
29645                           NULL_RTX, 0);
29646       tmp2 = force_reg (DImode, tmp2);
29647       emit_insn (gen_lshrdi3 (dst, tmp2, GEN_INT (56)));
29648     }
29649 }
29650
29651
29652 /* Emit parity intrinsic on TARGET_POPCNTB targets.  DST is the
29653    target, and SRC is the argument operand.  */
29654
29655 void
29656 rs6000_emit_parity (rtx dst, rtx src)
29657 {
29658   machine_mode mode = GET_MODE (dst);
29659   rtx tmp;
29660
29661   tmp = gen_reg_rtx (mode);
29662
29663   /* Use the PPC ISA 2.05 prtyw/prtyd instruction if we can.  */
29664   if (TARGET_CMPB)
29665     {
29666       if (mode == SImode)
29667         {
29668           emit_insn (gen_popcntbsi2 (tmp, src));
29669           emit_insn (gen_paritysi2_cmpb (dst, tmp));
29670         }
29671       else
29672         {
29673           emit_insn (gen_popcntbdi2 (tmp, src));
29674           emit_insn (gen_paritydi2_cmpb (dst, tmp));
29675         }
29676       return;
29677     }
29678
29679   if (mode == SImode)
29680     {
29681       /* Is mult+shift >= shift+xor+shift+xor?  */
29682       if (rs6000_cost->mulsi_const >= COSTS_N_INSNS (3))
29683         {
29684           rtx tmp1, tmp2, tmp3, tmp4;
29685
29686           tmp1 = gen_reg_rtx (SImode);
29687           emit_insn (gen_popcntbsi2 (tmp1, src));
29688
29689           tmp2 = gen_reg_rtx (SImode);
29690           emit_insn (gen_lshrsi3 (tmp2, tmp1, GEN_INT (16)));
29691           tmp3 = gen_reg_rtx (SImode);
29692           emit_insn (gen_xorsi3 (tmp3, tmp1, tmp2));
29693
29694           tmp4 = gen_reg_rtx (SImode);
29695           emit_insn (gen_lshrsi3 (tmp4, tmp3, GEN_INT (8)));
29696           emit_insn (gen_xorsi3 (tmp, tmp3, tmp4));
29697         }
29698       else
29699         rs6000_emit_popcount (tmp, src);
29700       emit_insn (gen_andsi3 (dst, tmp, const1_rtx));
29701     }
29702   else
29703     {
29704       /* Is mult+shift >= shift+xor+shift+xor+shift+xor?  */
29705       if (rs6000_cost->muldi >= COSTS_N_INSNS (5))
29706         {
29707           rtx tmp1, tmp2, tmp3, tmp4, tmp5, tmp6;
29708
29709           tmp1 = gen_reg_rtx (DImode);
29710           emit_insn (gen_popcntbdi2 (tmp1, src));
29711
29712           tmp2 = gen_reg_rtx (DImode);
29713           emit_insn (gen_lshrdi3 (tmp2, tmp1, GEN_INT (32)));
29714           tmp3 = gen_reg_rtx (DImode);
29715           emit_insn (gen_xordi3 (tmp3, tmp1, tmp2));
29716
29717           tmp4 = gen_reg_rtx (DImode);
29718           emit_insn (gen_lshrdi3 (tmp4, tmp3, GEN_INT (16)));
29719           tmp5 = gen_reg_rtx (DImode);
29720           emit_insn (gen_xordi3 (tmp5, tmp3, tmp4));
29721
29722           tmp6 = gen_reg_rtx (DImode);
29723           emit_insn (gen_lshrdi3 (tmp6, tmp5, GEN_INT (8)));
29724           emit_insn (gen_xordi3 (tmp, tmp5, tmp6));
29725         }
29726       else
29727         rs6000_emit_popcount (tmp, src);
29728       emit_insn (gen_anddi3 (dst, tmp, const1_rtx));
29729     }
29730 }
29731
29732 /* Expand an Altivec constant permutation for little endian mode.
29733    OP0 and OP1 are the input vectors and TARGET is the output vector.
29734    SEL specifies the constant permutation vector.
29735
29736    There are two issues: First, the two input operands must be
29737    swapped so that together they form a double-wide array in LE
29738    order.  Second, the vperm instruction has surprising behavior
29739    in LE mode:  it interprets the elements of the source vectors
29740    in BE mode ("left to right") and interprets the elements of
29741    the destination vector in LE mode ("right to left").  To
29742    correct for this, we must subtract each element of the permute
29743    control vector from 31.
29744
29745    For example, suppose we want to concatenate vr10 = {0, 1, 2, 3}
29746    with vr11 = {4, 5, 6, 7} and extract {0, 2, 4, 6} using a vperm.
29747    We place {0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27} in vr12 to
29748    serve as the permute control vector.  Then, in BE mode,
29749
29750      vperm 9,10,11,12
29751
29752    places the desired result in vr9.  However, in LE mode the 
29753    vector contents will be
29754
29755      vr10 = 00000003 00000002 00000001 00000000
29756      vr11 = 00000007 00000006 00000005 00000004
29757
29758    The result of the vperm using the same permute control vector is
29759
29760      vr9  = 05000000 07000000 01000000 03000000
29761
29762    That is, the leftmost 4 bytes of vr10 are interpreted as the
29763    source for the rightmost 4 bytes of vr9, and so on.
29764
29765    If we change the permute control vector to
29766
29767      vr12 = {31,20,29,28,23,22,21,20,15,14,13,12,7,6,5,4}
29768
29769    and issue
29770
29771      vperm 9,11,10,12
29772
29773    we get the desired
29774
29775    vr9  = 00000006 00000004 00000002 00000000.  */
29776
29777 static void
29778 altivec_expand_vec_perm_const_le (rtx target, rtx op0, rtx op1,
29779                                   const vec_perm_indices &sel)
29780 {
29781   unsigned int i;
29782   rtx perm[16];
29783   rtx constv, unspec;
29784
29785   /* Unpack and adjust the constant selector.  */
29786   for (i = 0; i < 16; ++i)
29787     {
29788       unsigned int elt = 31 - (sel[i] & 31);
29789       perm[i] = GEN_INT (elt);
29790     }
29791
29792   /* Expand to a permute, swapping the inputs and using the
29793      adjusted selector.  */
29794   if (!REG_P (op0))
29795     op0 = force_reg (V16QImode, op0);
29796   if (!REG_P (op1))
29797     op1 = force_reg (V16QImode, op1);
29798
29799   constv = gen_rtx_CONST_VECTOR (V16QImode, gen_rtvec_v (16, perm));
29800   constv = force_reg (V16QImode, constv);
29801   unspec = gen_rtx_UNSPEC (V16QImode, gen_rtvec (3, op1, op0, constv),
29802                            UNSPEC_VPERM);
29803   if (!REG_P (target))
29804     {
29805       rtx tmp = gen_reg_rtx (V16QImode);
29806       emit_move_insn (tmp, unspec);
29807       unspec = tmp;
29808     }
29809
29810   emit_move_insn (target, unspec);
29811 }
29812
29813 /* Similarly to altivec_expand_vec_perm_const_le, we must adjust the
29814    permute control vector.  But here it's not a constant, so we must
29815    generate a vector NAND or NOR to do the adjustment.  */
29816
29817 void
29818 altivec_expand_vec_perm_le (rtx operands[4])
29819 {
29820   rtx notx, iorx, unspec;
29821   rtx target = operands[0];
29822   rtx op0 = operands[1];
29823   rtx op1 = operands[2];
29824   rtx sel = operands[3];
29825   rtx tmp = target;
29826   rtx norreg = gen_reg_rtx (V16QImode);
29827   machine_mode mode = GET_MODE (target);
29828
29829   /* Get everything in regs so the pattern matches.  */
29830   if (!REG_P (op0))
29831     op0 = force_reg (mode, op0);
29832   if (!REG_P (op1))
29833     op1 = force_reg (mode, op1);
29834   if (!REG_P (sel))
29835     sel = force_reg (V16QImode, sel);
29836   if (!REG_P (target))
29837     tmp = gen_reg_rtx (mode);
29838
29839   if (TARGET_P9_VECTOR)
29840     {
29841       unspec = gen_rtx_UNSPEC (mode, gen_rtvec (3, op1, op0, sel),
29842                                UNSPEC_VPERMR);
29843     }
29844   else
29845     {
29846       /* Invert the selector with a VNAND if available, else a VNOR.
29847          The VNAND is preferred for future fusion opportunities.  */
29848       notx = gen_rtx_NOT (V16QImode, sel);
29849       iorx = (TARGET_P8_VECTOR
29850               ? gen_rtx_IOR (V16QImode, notx, notx)
29851               : gen_rtx_AND (V16QImode, notx, notx));
29852       emit_insn (gen_rtx_SET (norreg, iorx));
29853
29854       /* Permute with operands reversed and adjusted selector.  */
29855       unspec = gen_rtx_UNSPEC (mode, gen_rtvec (3, op1, op0, norreg),
29856                                UNSPEC_VPERM);
29857     }
29858
29859   /* Copy into target, possibly by way of a register.  */
29860   if (!REG_P (target))
29861     {
29862       emit_move_insn (tmp, unspec);
29863       unspec = tmp;
29864     }
29865
29866   emit_move_insn (target, unspec);
29867 }
29868
29869 /* Expand an Altivec constant permutation.  Return true if we match
29870    an efficient implementation; false to fall back to VPERM.
29871
29872    OP0 and OP1 are the input vectors and TARGET is the output vector.
29873    SEL specifies the constant permutation vector.  */
29874
29875 static bool
29876 altivec_expand_vec_perm_const (rtx target, rtx op0, rtx op1,
29877                                const vec_perm_indices &sel)
29878 {
29879   struct altivec_perm_insn {
29880     HOST_WIDE_INT mask;
29881     enum insn_code impl;
29882     unsigned char perm[16];
29883   };
29884   static const struct altivec_perm_insn patterns[] = {
29885     { OPTION_MASK_ALTIVEC, CODE_FOR_altivec_vpkuhum_direct,
29886       {  1,  3,  5,  7,  9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
29887     { OPTION_MASK_ALTIVEC, CODE_FOR_altivec_vpkuwum_direct,
29888       {  2,  3,  6,  7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
29889     { OPTION_MASK_ALTIVEC, 
29890       (BYTES_BIG_ENDIAN ? CODE_FOR_altivec_vmrghb_direct
29891        : CODE_FOR_altivec_vmrglb_direct),
29892       {  0, 16,  1, 17,  2, 18,  3, 19,  4, 20,  5, 21,  6, 22,  7, 23 } },
29893     { OPTION_MASK_ALTIVEC,
29894       (BYTES_BIG_ENDIAN ? CODE_FOR_altivec_vmrghh_direct
29895        : CODE_FOR_altivec_vmrglh_direct),
29896       {  0,  1, 16, 17,  2,  3, 18, 19,  4,  5, 20, 21,  6,  7, 22, 23 } },
29897     { OPTION_MASK_ALTIVEC,
29898       (BYTES_BIG_ENDIAN ? CODE_FOR_altivec_vmrghw_direct
29899        : CODE_FOR_altivec_vmrglw_direct),
29900       {  0,  1,  2,  3, 16, 17, 18, 19,  4,  5,  6,  7, 20, 21, 22, 23 } },
29901     { OPTION_MASK_ALTIVEC,
29902       (BYTES_BIG_ENDIAN ? CODE_FOR_altivec_vmrglb_direct
29903        : CODE_FOR_altivec_vmrghb_direct),
29904       {  8, 24,  9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
29905     { OPTION_MASK_ALTIVEC,
29906       (BYTES_BIG_ENDIAN ? CODE_FOR_altivec_vmrglh_direct
29907        : CODE_FOR_altivec_vmrghh_direct),
29908       {  8,  9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
29909     { OPTION_MASK_ALTIVEC,
29910       (BYTES_BIG_ENDIAN ? CODE_FOR_altivec_vmrglw_direct
29911        : CODE_FOR_altivec_vmrghw_direct),
29912       {  8,  9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
29913     { OPTION_MASK_P8_VECTOR,
29914       (BYTES_BIG_ENDIAN ? CODE_FOR_p8_vmrgew_v4sf_direct
29915        : CODE_FOR_p8_vmrgow_v4sf_direct),
29916       {  0,  1,  2,  3, 16, 17, 18, 19,  8,  9, 10, 11, 24, 25, 26, 27 } },
29917     { OPTION_MASK_P8_VECTOR,
29918       (BYTES_BIG_ENDIAN ? CODE_FOR_p8_vmrgow_v4sf_direct
29919        : CODE_FOR_p8_vmrgew_v4sf_direct),
29920       {  4,  5,  6,  7, 20, 21, 22, 23, 12, 13, 14, 15, 28, 29, 30, 31 } }
29921   };
29922
29923   unsigned int i, j, elt, which;
29924   unsigned char perm[16];
29925   rtx x;
29926   bool one_vec;
29927
29928   /* Unpack the constant selector.  */
29929   for (i = which = 0; i < 16; ++i)
29930     {
29931       elt = sel[i] & 31;
29932       which |= (elt < 16 ? 1 : 2);
29933       perm[i] = elt;
29934     }
29935
29936   /* Simplify the constant selector based on operands.  */
29937   switch (which)
29938     {
29939     default:
29940       gcc_unreachable ();
29941
29942     case 3:
29943       one_vec = false;
29944       if (!rtx_equal_p (op0, op1))
29945         break;
29946       /* FALLTHRU */
29947
29948     case 2:
29949       for (i = 0; i < 16; ++i)
29950         perm[i] &= 15;
29951       op0 = op1;
29952       one_vec = true;
29953       break;
29954
29955     case 1:
29956       op1 = op0;
29957       one_vec = true;
29958       break;
29959     }
29960  
29961   /* Look for splat patterns.  */
29962   if (one_vec)
29963     {
29964       elt = perm[0];
29965
29966       for (i = 0; i < 16; ++i)
29967         if (perm[i] != elt)
29968           break;
29969       if (i == 16)
29970         {
29971           if (!BYTES_BIG_ENDIAN)
29972             elt = 15 - elt;
29973           emit_insn (gen_altivec_vspltb_direct (target, op0, GEN_INT (elt)));
29974           return true;
29975         }
29976
29977       if (elt % 2 == 0)
29978         {
29979           for (i = 0; i < 16; i += 2)
29980             if (perm[i] != elt || perm[i + 1] != elt + 1)
29981               break;
29982           if (i == 16)
29983             {
29984               int field = BYTES_BIG_ENDIAN ? elt / 2 : 7 - elt / 2;
29985               x = gen_reg_rtx (V8HImode);
29986               emit_insn (gen_altivec_vsplth_direct (x, gen_lowpart (V8HImode, op0),
29987                                                     GEN_INT (field)));
29988               emit_move_insn (target, gen_lowpart (V16QImode, x));
29989               return true;
29990             }
29991         }
29992
29993       if (elt % 4 == 0)
29994         {
29995           for (i = 0; i < 16; i += 4)
29996             if (perm[i] != elt
29997                 || perm[i + 1] != elt + 1
29998                 || perm[i + 2] != elt + 2
29999                 || perm[i + 3] != elt + 3)
30000               break;
30001           if (i == 16)
30002             {
30003               int field = BYTES_BIG_ENDIAN ? elt / 4 : 3 - elt / 4;
30004               x = gen_reg_rtx (V4SImode);
30005               emit_insn (gen_altivec_vspltw_direct (x, gen_lowpart (V4SImode, op0),
30006                                                     GEN_INT (field)));
30007               emit_move_insn (target, gen_lowpart (V16QImode, x));
30008               return true;
30009             }
30010         }
30011     }
30012
30013   /* Look for merge and pack patterns.  */
30014   for (j = 0; j < ARRAY_SIZE (patterns); ++j)
30015     {
30016       bool swapped;
30017
30018       if ((patterns[j].mask & rs6000_isa_flags) == 0)
30019         continue;
30020
30021       elt = patterns[j].perm[0];
30022       if (perm[0] == elt)
30023         swapped = false;
30024       else if (perm[0] == elt + 16)
30025         swapped = true;
30026       else
30027         continue;
30028       for (i = 1; i < 16; ++i)
30029         {
30030           elt = patterns[j].perm[i];
30031           if (swapped)
30032             elt = (elt >= 16 ? elt - 16 : elt + 16);
30033           else if (one_vec && elt >= 16)
30034             elt -= 16;
30035           if (perm[i] != elt)
30036             break;
30037         }
30038       if (i == 16)
30039         {
30040           enum insn_code icode = patterns[j].impl;
30041           machine_mode omode = insn_data[icode].operand[0].mode;
30042           machine_mode imode = insn_data[icode].operand[1].mode;
30043
30044           /* For little-endian, don't use vpkuwum and vpkuhum if the
30045              underlying vector type is not V4SI and V8HI, respectively.
30046              For example, using vpkuwum with a V8HI picks up the even
30047              halfwords (BE numbering) when the even halfwords (LE
30048              numbering) are what we need.  */
30049           if (!BYTES_BIG_ENDIAN
30050               && icode == CODE_FOR_altivec_vpkuwum_direct
30051               && ((REG_P (op0)
30052                    && GET_MODE (op0) != V4SImode)
30053                   || (SUBREG_P (op0)
30054                       && GET_MODE (XEXP (op0, 0)) != V4SImode)))
30055             continue;
30056           if (!BYTES_BIG_ENDIAN
30057               && icode == CODE_FOR_altivec_vpkuhum_direct
30058               && ((REG_P (op0)
30059                    && GET_MODE (op0) != V8HImode)
30060                   || (SUBREG_P (op0)
30061                       && GET_MODE (XEXP (op0, 0)) != V8HImode)))
30062             continue;
30063
30064           /* For little-endian, the two input operands must be swapped
30065              (or swapped back) to ensure proper right-to-left numbering
30066              from 0 to 2N-1.  */
30067           if (swapped ^ !BYTES_BIG_ENDIAN)
30068             std::swap (op0, op1);
30069           if (imode != V16QImode)
30070             {
30071               op0 = gen_lowpart (imode, op0);
30072               op1 = gen_lowpart (imode, op1);
30073             }
30074           if (omode == V16QImode)
30075             x = target;
30076           else
30077             x = gen_reg_rtx (omode);
30078           emit_insn (GEN_FCN (icode) (x, op0, op1));
30079           if (omode != V16QImode)
30080             emit_move_insn (target, gen_lowpart (V16QImode, x));
30081           return true;
30082         }
30083     }
30084
30085   if (!BYTES_BIG_ENDIAN)
30086     {
30087       altivec_expand_vec_perm_const_le (target, op0, op1, sel);
30088       return true;
30089     }
30090
30091   return false;
30092 }
30093
30094 /* Expand a VSX Permute Doubleword constant permutation.
30095    Return true if we match an efficient implementation.  */
30096
30097 static bool
30098 rs6000_expand_vec_perm_const_1 (rtx target, rtx op0, rtx op1,
30099                                 unsigned char perm0, unsigned char perm1)
30100 {
30101   rtx x;
30102
30103   /* If both selectors come from the same operand, fold to single op.  */
30104   if ((perm0 & 2) == (perm1 & 2))
30105     {
30106       if (perm0 & 2)
30107         op0 = op1;
30108       else
30109         op1 = op0;
30110     }
30111   /* If both operands are equal, fold to simpler permutation.  */
30112   if (rtx_equal_p (op0, op1))
30113     {
30114       perm0 = perm0 & 1;
30115       perm1 = (perm1 & 1) + 2;
30116     }
30117   /* If the first selector comes from the second operand, swap.  */
30118   else if (perm0 & 2)
30119     {
30120       if (perm1 & 2)
30121         return false;
30122       perm0 -= 2;
30123       perm1 += 2;
30124       std::swap (op0, op1);
30125     }
30126   /* If the second selector does not come from the second operand, fail.  */
30127   else if ((perm1 & 2) == 0)
30128     return false;
30129
30130   /* Success! */
30131   if (target != NULL)
30132     {
30133       machine_mode vmode, dmode;
30134       rtvec v;
30135
30136       vmode = GET_MODE (target);
30137       gcc_assert (GET_MODE_NUNITS (vmode) == 2);
30138       dmode = mode_for_vector (GET_MODE_INNER (vmode), 4).require ();
30139       x = gen_rtx_VEC_CONCAT (dmode, op0, op1);
30140       v = gen_rtvec (2, GEN_INT (perm0), GEN_INT (perm1));
30141       x = gen_rtx_VEC_SELECT (vmode, x, gen_rtx_PARALLEL (VOIDmode, v));
30142       emit_insn (gen_rtx_SET (target, x));
30143     }
30144   return true;
30145 }
30146
30147 /* Implement TARGET_VECTORIZE_VEC_PERM_CONST.  */
30148
30149 static bool
30150 rs6000_vectorize_vec_perm_const (machine_mode vmode, rtx target, rtx op0,
30151                                  rtx op1, const vec_perm_indices &sel)
30152 {
30153   bool testing_p = !target;
30154
30155   /* AltiVec (and thus VSX) can handle arbitrary permutations.  */
30156   if (TARGET_ALTIVEC && testing_p)
30157     return true;
30158
30159   /* Check for ps_merge* or xxpermdi insns.  */
30160   if ((vmode == V2DFmode || vmode == V2DImode) && VECTOR_MEM_VSX_P (vmode))
30161     {
30162       if (testing_p)
30163         {
30164           op0 = gen_raw_REG (vmode, LAST_VIRTUAL_REGISTER + 1);
30165           op1 = gen_raw_REG (vmode, LAST_VIRTUAL_REGISTER + 2);
30166         }
30167       if (rs6000_expand_vec_perm_const_1 (target, op0, op1, sel[0], sel[1]))
30168         return true;
30169     }
30170
30171   if (TARGET_ALTIVEC)
30172     {
30173       /* Force the target-independent code to lower to V16QImode.  */
30174       if (vmode != V16QImode)
30175         return false;
30176       if (altivec_expand_vec_perm_const (target, op0, op1, sel))
30177         return true;
30178     }
30179
30180   return false;
30181 }
30182
30183 /* A subroutine for rs6000_expand_extract_even & rs6000_expand_interleave.
30184    OP0 and OP1 are the input vectors and TARGET is the output vector.
30185    PERM specifies the constant permutation vector.  */
30186
30187 static void
30188 rs6000_do_expand_vec_perm (rtx target, rtx op0, rtx op1,
30189                            machine_mode vmode, const vec_perm_builder &perm)
30190 {
30191   rtx x = expand_vec_perm_const (vmode, op0, op1, perm, BLKmode, target);
30192   if (x != target)
30193     emit_move_insn (target, x);
30194 }
30195
30196 /* Expand an extract even operation.  */
30197
30198 void
30199 rs6000_expand_extract_even (rtx target, rtx op0, rtx op1)
30200 {
30201   machine_mode vmode = GET_MODE (target);
30202   unsigned i, nelt = GET_MODE_NUNITS (vmode);
30203   vec_perm_builder perm (nelt, nelt, 1);
30204
30205   for (i = 0; i < nelt; i++)
30206     perm.quick_push (i * 2);
30207
30208   rs6000_do_expand_vec_perm (target, op0, op1, vmode, perm);
30209 }
30210
30211 /* Expand a vector interleave operation.  */
30212
30213 void
30214 rs6000_expand_interleave (rtx target, rtx op0, rtx op1, bool highp)
30215 {
30216   machine_mode vmode = GET_MODE (target);
30217   unsigned i, high, nelt = GET_MODE_NUNITS (vmode);
30218   vec_perm_builder perm (nelt, nelt, 1);
30219
30220   high = (highp ? 0 : nelt / 2);
30221   for (i = 0; i < nelt / 2; i++)
30222     {
30223       perm.quick_push (i + high);
30224       perm.quick_push (i + nelt + high);
30225     }
30226
30227   rs6000_do_expand_vec_perm (target, op0, op1, vmode, perm);
30228 }
30229
30230 /* Scale a V2DF vector SRC by two to the SCALE and place in TGT.  */
30231 void
30232 rs6000_scale_v2df (rtx tgt, rtx src, int scale)
30233 {
30234   HOST_WIDE_INT hwi_scale (scale);
30235   REAL_VALUE_TYPE r_pow;
30236   rtvec v = rtvec_alloc (2);
30237   rtx elt;
30238   rtx scale_vec = gen_reg_rtx (V2DFmode);
30239   (void)real_powi (&r_pow, DFmode, &dconst2, hwi_scale);
30240   elt = const_double_from_real_value (r_pow, DFmode);
30241   RTVEC_ELT (v, 0) = elt;
30242   RTVEC_ELT (v, 1) = elt;
30243   rs6000_expand_vector_init (scale_vec, gen_rtx_PARALLEL (V2DFmode, v));
30244   emit_insn (gen_mulv2df3 (tgt, src, scale_vec));
30245 }
30246
30247 /* Return an RTX representing where to find the function value of a
30248    function returning MODE.  */
30249 static rtx
30250 rs6000_complex_function_value (machine_mode mode)
30251 {
30252   unsigned int regno;
30253   rtx r1, r2;
30254   machine_mode inner = GET_MODE_INNER (mode);
30255   unsigned int inner_bytes = GET_MODE_UNIT_SIZE (mode);
30256
30257   if (TARGET_FLOAT128_TYPE
30258       && (mode == KCmode
30259           || (mode == TCmode && TARGET_IEEEQUAD)))
30260     regno = ALTIVEC_ARG_RETURN;
30261
30262   else if (FLOAT_MODE_P (mode) && TARGET_HARD_FLOAT)
30263     regno = FP_ARG_RETURN;
30264
30265   else
30266     {
30267       regno = GP_ARG_RETURN;
30268
30269       /* 32-bit is OK since it'll go in r3/r4.  */
30270       if (TARGET_32BIT && inner_bytes >= 4)
30271         return gen_rtx_REG (mode, regno);
30272     }
30273
30274   if (inner_bytes >= 8)
30275     return gen_rtx_REG (mode, regno);
30276
30277   r1 = gen_rtx_EXPR_LIST (inner, gen_rtx_REG (inner, regno),
30278                           const0_rtx);
30279   r2 = gen_rtx_EXPR_LIST (inner, gen_rtx_REG (inner, regno + 1),
30280                           GEN_INT (inner_bytes));
30281   return gen_rtx_PARALLEL (mode, gen_rtvec (2, r1, r2));
30282 }
30283
30284 /* Return an rtx describing a return value of MODE as a PARALLEL
30285    in N_ELTS registers, each of mode ELT_MODE, starting at REGNO,
30286    stride REG_STRIDE.  */
30287
30288 static rtx
30289 rs6000_parallel_return (machine_mode mode,
30290                         int n_elts, machine_mode elt_mode,
30291                         unsigned int regno, unsigned int reg_stride)
30292 {
30293   rtx par = gen_rtx_PARALLEL (mode, rtvec_alloc (n_elts));
30294
30295   int i;
30296   for (i = 0; i < n_elts; i++)
30297     {
30298       rtx r = gen_rtx_REG (elt_mode, regno);
30299       rtx off = GEN_INT (i * GET_MODE_SIZE (elt_mode));
30300       XVECEXP (par, 0, i) = gen_rtx_EXPR_LIST (VOIDmode, r, off);
30301       regno += reg_stride;
30302     }
30303
30304   return par;
30305 }
30306
30307 /* Target hook for TARGET_FUNCTION_VALUE.
30308
30309    An integer value is in r3 and a floating-point value is in fp1,
30310    unless -msoft-float.  */
30311
30312 static rtx
30313 rs6000_function_value (const_tree valtype,
30314                        const_tree fn_decl_or_type ATTRIBUTE_UNUSED,
30315                        bool outgoing ATTRIBUTE_UNUSED)
30316 {
30317   machine_mode mode;
30318   unsigned int regno;
30319   machine_mode elt_mode;
30320   int n_elts;
30321
30322   /* Special handling for structs in darwin64.  */
30323   if (TARGET_MACHO 
30324       && rs6000_darwin64_struct_check_p (TYPE_MODE (valtype), valtype))
30325     {
30326       CUMULATIVE_ARGS valcum;
30327       rtx valret;
30328
30329       valcum.words = 0;
30330       valcum.fregno = FP_ARG_MIN_REG;
30331       valcum.vregno = ALTIVEC_ARG_MIN_REG;
30332       /* Do a trial code generation as if this were going to be passed as
30333          an argument; if any part goes in memory, we return NULL.  */
30334       valret = rs6000_darwin64_record_arg (&valcum, valtype, true, /* retval= */ true);
30335       if (valret)
30336         return valret;
30337       /* Otherwise fall through to standard ABI rules.  */
30338     }
30339
30340   mode = TYPE_MODE (valtype);
30341
30342   /* The ELFv2 ABI returns homogeneous VFP aggregates in registers.  */
30343   if (rs6000_discover_homogeneous_aggregate (mode, valtype, &elt_mode, &n_elts))
30344     {
30345       int first_reg, n_regs;
30346
30347       if (SCALAR_FLOAT_MODE_NOT_VECTOR_P (elt_mode))
30348         {
30349           /* _Decimal128 must use even/odd register pairs.  */
30350           first_reg = (elt_mode == TDmode) ? FP_ARG_RETURN + 1 : FP_ARG_RETURN;
30351           n_regs = (GET_MODE_SIZE (elt_mode) + 7) >> 3;
30352         }
30353       else
30354         {
30355           first_reg = ALTIVEC_ARG_RETURN;
30356           n_regs = 1;
30357         }
30358
30359       return rs6000_parallel_return (mode, n_elts, elt_mode, first_reg, n_regs);
30360     }
30361
30362   /* Some return value types need be split in -mpowerpc64, 32bit ABI.  */
30363   if (TARGET_32BIT && TARGET_POWERPC64)
30364     switch (mode)
30365       {
30366       default:
30367         break;
30368       case E_DImode:
30369       case E_SCmode:
30370       case E_DCmode:
30371       case E_TCmode:
30372         int count = GET_MODE_SIZE (mode) / 4;
30373         return rs6000_parallel_return (mode, count, SImode, GP_ARG_RETURN, 1);
30374       }
30375
30376   if ((INTEGRAL_TYPE_P (valtype)
30377        && GET_MODE_BITSIZE (mode) < (TARGET_32BIT ? 32 : 64))
30378       || POINTER_TYPE_P (valtype))
30379     mode = TARGET_32BIT ? SImode : DImode;
30380
30381   if (DECIMAL_FLOAT_MODE_P (mode) && TARGET_HARD_FLOAT)
30382     /* _Decimal128 must use an even/odd register pair.  */
30383     regno = (mode == TDmode) ? FP_ARG_RETURN + 1 : FP_ARG_RETURN;
30384   else if (SCALAR_FLOAT_TYPE_P (valtype) && TARGET_HARD_FLOAT
30385            && !FLOAT128_VECTOR_P (mode))
30386     regno = FP_ARG_RETURN;
30387   else if (TREE_CODE (valtype) == COMPLEX_TYPE
30388            && targetm.calls.split_complex_arg)
30389     return rs6000_complex_function_value (mode);
30390   /* VSX is a superset of Altivec and adds V2DImode/V2DFmode.  Since the same
30391      return register is used in both cases, and we won't see V2DImode/V2DFmode
30392      for pure altivec, combine the two cases.  */
30393   else if ((TREE_CODE (valtype) == VECTOR_TYPE || FLOAT128_VECTOR_P (mode))
30394            && TARGET_ALTIVEC && TARGET_ALTIVEC_ABI
30395            && ALTIVEC_OR_VSX_VECTOR_MODE (mode))
30396     regno = ALTIVEC_ARG_RETURN;
30397   else
30398     regno = GP_ARG_RETURN;
30399
30400   return gen_rtx_REG (mode, regno);
30401 }
30402
30403 /* Define how to find the value returned by a library function
30404    assuming the value has mode MODE.  */
30405 rtx
30406 rs6000_libcall_value (machine_mode mode)
30407 {
30408   unsigned int regno;
30409
30410   /* Long long return value need be split in -mpowerpc64, 32bit ABI.  */
30411   if (TARGET_32BIT && TARGET_POWERPC64 && mode == DImode)
30412     return rs6000_parallel_return (mode, 2, SImode, GP_ARG_RETURN, 1);
30413
30414   if (DECIMAL_FLOAT_MODE_P (mode) && TARGET_HARD_FLOAT)
30415     /* _Decimal128 must use an even/odd register pair.  */
30416     regno = (mode == TDmode) ? FP_ARG_RETURN + 1 : FP_ARG_RETURN;
30417   else if (SCALAR_FLOAT_MODE_NOT_VECTOR_P (mode) && TARGET_HARD_FLOAT)
30418     regno = FP_ARG_RETURN;
30419   /* VSX is a superset of Altivec and adds V2DImode/V2DFmode.  Since the same
30420      return register is used in both cases, and we won't see V2DImode/V2DFmode
30421      for pure altivec, combine the two cases.  */
30422   else if (ALTIVEC_OR_VSX_VECTOR_MODE (mode)
30423            && TARGET_ALTIVEC && TARGET_ALTIVEC_ABI)
30424     regno = ALTIVEC_ARG_RETURN;
30425   else if (COMPLEX_MODE_P (mode) && targetm.calls.split_complex_arg)
30426     return rs6000_complex_function_value (mode);
30427   else
30428     regno = GP_ARG_RETURN;
30429
30430   return gen_rtx_REG (mode, regno);
30431 }
30432
30433 /* Compute register pressure classes.  We implement the target hook to avoid
30434    IRA picking something like GEN_OR_FLOAT_REGS as a pressure class, which can
30435    lead to incorrect estimates of number of available registers and therefor
30436    increased register pressure/spill.   */
30437 static int
30438 rs6000_compute_pressure_classes (enum reg_class *pressure_classes)
30439 {
30440   int n;
30441
30442   n = 0;
30443   pressure_classes[n++] = GENERAL_REGS;
30444   if (TARGET_VSX)
30445     pressure_classes[n++] = VSX_REGS;
30446   else
30447     {
30448       if (TARGET_ALTIVEC)
30449         pressure_classes[n++] = ALTIVEC_REGS;
30450       if (TARGET_HARD_FLOAT)
30451         pressure_classes[n++] = FLOAT_REGS;
30452     }
30453   pressure_classes[n++] = CR_REGS;
30454   pressure_classes[n++] = SPECIAL_REGS;
30455
30456   return n;
30457 }
30458
30459 /* Given FROM and TO register numbers, say whether this elimination is allowed.
30460    Frame pointer elimination is automatically handled.
30461
30462    For the RS/6000, if frame pointer elimination is being done, we would like
30463    to convert ap into fp, not sp.
30464
30465    We need r30 if -mminimal-toc was specified, and there are constant pool
30466    references.  */
30467
30468 static bool
30469 rs6000_can_eliminate (const int from, const int to)
30470 {
30471   return (from == ARG_POINTER_REGNUM && to == STACK_POINTER_REGNUM
30472           ? ! frame_pointer_needed
30473           : from == RS6000_PIC_OFFSET_TABLE_REGNUM
30474             ? ! TARGET_MINIMAL_TOC || TARGET_NO_TOC
30475                 || constant_pool_empty_p ()
30476             : true);
30477 }
30478
30479 /* Define the offset between two registers, FROM to be eliminated and its
30480    replacement TO, at the start of a routine.  */
30481 HOST_WIDE_INT
30482 rs6000_initial_elimination_offset (int from, int to)
30483 {
30484   rs6000_stack_t *info = rs6000_stack_info ();
30485   HOST_WIDE_INT offset;
30486
30487   if (from == HARD_FRAME_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
30488     offset = info->push_p ? 0 : -info->total_size;
30489   else if (from == FRAME_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
30490     {
30491       offset = info->push_p ? 0 : -info->total_size;
30492       if (FRAME_GROWS_DOWNWARD)
30493         offset += info->fixed_size + info->vars_size + info->parm_size;
30494     }
30495   else if (from == FRAME_POINTER_REGNUM && to == HARD_FRAME_POINTER_REGNUM)
30496     offset = FRAME_GROWS_DOWNWARD
30497              ? info->fixed_size + info->vars_size + info->parm_size
30498              : 0;
30499   else if (from == ARG_POINTER_REGNUM && to == HARD_FRAME_POINTER_REGNUM)
30500     offset = info->total_size;
30501   else if (from == ARG_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
30502     offset = info->push_p ? info->total_size : 0;
30503   else if (from == RS6000_PIC_OFFSET_TABLE_REGNUM)
30504     offset = 0;
30505   else
30506     gcc_unreachable ();
30507
30508   return offset;
30509 }
30510
30511 /* Fill in sizes of registers used by unwinder.  */
30512
30513 static void
30514 rs6000_init_dwarf_reg_sizes_extra (tree address)
30515 {
30516   if (TARGET_MACHO && ! TARGET_ALTIVEC)
30517     {
30518       int i;
30519       machine_mode mode = TYPE_MODE (char_type_node);
30520       rtx addr = expand_expr (address, NULL_RTX, VOIDmode, EXPAND_NORMAL);
30521       rtx mem = gen_rtx_MEM (BLKmode, addr);
30522       rtx value = gen_int_mode (16, mode);
30523
30524       /* On Darwin, libgcc may be built to run on both G3 and G4/5.
30525          The unwinder still needs to know the size of Altivec registers.  */
30526
30527       for (i = FIRST_ALTIVEC_REGNO; i < LAST_ALTIVEC_REGNO+1; i++)
30528         {
30529           int column = DWARF_REG_TO_UNWIND_COLUMN
30530                 (DWARF2_FRAME_REG_OUT (DWARF_FRAME_REGNUM (i), true));
30531           HOST_WIDE_INT offset = column * GET_MODE_SIZE (mode);
30532
30533           emit_move_insn (adjust_address (mem, mode, offset), value);
30534         }
30535     }
30536 }
30537
30538 /* Map internal gcc register numbers to debug format register numbers.
30539    FORMAT specifies the type of debug register number to use:
30540      0 -- debug information, except for frame-related sections
30541      1 -- DWARF .debug_frame section
30542      2 -- DWARF .eh_frame section  */
30543
30544 unsigned int
30545 rs6000_dbx_register_number (unsigned int regno, unsigned int format)
30546 {
30547   /* On some platforms, we use the standard DWARF register
30548      numbering for .debug_info and .debug_frame.  */
30549   if ((format == 0 && write_symbols == DWARF2_DEBUG) || format == 1)
30550     {
30551 #ifdef RS6000_USE_DWARF_NUMBERING
30552       if (regno <= 31)
30553         return regno;
30554       if (FP_REGNO_P (regno))
30555         return regno - FIRST_FPR_REGNO + 32;
30556       if (ALTIVEC_REGNO_P (regno))
30557         return regno - FIRST_ALTIVEC_REGNO + 1124;
30558       if (regno == LR_REGNO)
30559         return 108;
30560       if (regno == CTR_REGNO)
30561         return 109;
30562       if (regno == CA_REGNO)
30563         return 101;  /* XER */
30564       /* Special handling for CR for .debug_frame: rs6000_emit_prologue has
30565          translated any combination of CR2, CR3, CR4 saves to a save of CR2.
30566          The actual code emitted saves the whole of CR, so we map CR2_REGNO
30567          to the DWARF reg for CR.  */
30568       if (format == 1 && regno == CR2_REGNO)
30569         return 64;
30570       if (CR_REGNO_P (regno))
30571         return regno - CR0_REGNO + 86;
30572       if (regno == VRSAVE_REGNO)
30573         return 356;
30574       if (regno == VSCR_REGNO)
30575         return 67;
30576
30577       /* These do not make much sense.  */
30578       if (regno == FRAME_POINTER_REGNUM)
30579         return 111;
30580       if (regno == ARG_POINTER_REGNUM)
30581         return 67;
30582       if (regno == 64)
30583         return 100;
30584
30585       gcc_unreachable ();
30586 #endif
30587     }
30588
30589   /* We use the GCC 7 (and before) internal number for non-DWARF debug
30590      information, and also for .eh_frame.  */
30591   /* Translate the regnos to their numbers in GCC 7 (and before).  */
30592   if (regno <= 31)
30593     return regno;
30594   if (FP_REGNO_P (regno))
30595     return regno - FIRST_FPR_REGNO + 32;
30596   if (ALTIVEC_REGNO_P (regno))
30597     return regno - FIRST_ALTIVEC_REGNO + 77;
30598   if (regno == LR_REGNO)
30599     return 65;
30600   if (regno == CTR_REGNO)
30601     return 66;
30602   if (regno == CA_REGNO)
30603     return 76;  /* XER */
30604   if (CR_REGNO_P (regno))
30605     return regno - CR0_REGNO + 68;
30606   if (regno == VRSAVE_REGNO)
30607     return 109;
30608   if (regno == VSCR_REGNO)
30609     return 110;
30610
30611   if (regno == FRAME_POINTER_REGNUM)
30612     return 111;
30613   if (regno == ARG_POINTER_REGNUM)
30614     return 67;
30615   if (regno == 64)
30616     return 64;
30617
30618   gcc_unreachable ();
30619 }
30620
30621 /* target hook eh_return_filter_mode */
30622 static scalar_int_mode
30623 rs6000_eh_return_filter_mode (void)
30624 {
30625   return TARGET_32BIT ? SImode : word_mode;
30626 }
30627
30628 /* Target hook for translate_mode_attribute.  */
30629 static machine_mode
30630 rs6000_translate_mode_attribute (machine_mode mode)
30631 {
30632   if ((FLOAT128_IEEE_P (mode)
30633        && ieee128_float_type_node == long_double_type_node)
30634       || (FLOAT128_IBM_P (mode)
30635           && ibm128_float_type_node == long_double_type_node))
30636     return COMPLEX_MODE_P (mode) ? E_TCmode : E_TFmode;
30637   return mode;
30638 }
30639
30640 /* Target hook for scalar_mode_supported_p.  */
30641 static bool
30642 rs6000_scalar_mode_supported_p (scalar_mode mode)
30643 {
30644   /* -m32 does not support TImode.  This is the default, from
30645      default_scalar_mode_supported_p.  For -m32 -mpowerpc64 we want the
30646      same ABI as for -m32.  But default_scalar_mode_supported_p allows
30647      integer modes of precision 2 * BITS_PER_WORD, which matches TImode
30648      for -mpowerpc64.  */
30649   if (TARGET_32BIT && mode == TImode)
30650     return false;
30651
30652   if (DECIMAL_FLOAT_MODE_P (mode))
30653     return default_decimal_float_supported_p ();
30654   else if (TARGET_FLOAT128_TYPE && (mode == KFmode || mode == IFmode))
30655     return true;
30656   else
30657     return default_scalar_mode_supported_p (mode);
30658 }
30659
30660 /* Target hook for vector_mode_supported_p.  */
30661 static bool
30662 rs6000_vector_mode_supported_p (machine_mode mode)
30663 {
30664   /* There is no vector form for IEEE 128-bit.  If we return true for IEEE
30665      128-bit, the compiler might try to widen IEEE 128-bit to IBM
30666      double-double.  */
30667   if (VECTOR_MEM_ALTIVEC_OR_VSX_P (mode) && !FLOAT128_IEEE_P (mode))
30668     return true;
30669
30670   else
30671     return false;
30672 }
30673
30674 /* Target hook for floatn_mode.  */
30675 static opt_scalar_float_mode
30676 rs6000_floatn_mode (int n, bool extended)
30677 {
30678   if (extended)
30679     {
30680       switch (n)
30681         {
30682         case 32:
30683           return DFmode;
30684
30685         case 64:
30686           if (TARGET_FLOAT128_TYPE)
30687             return (FLOAT128_IEEE_P (TFmode)) ? TFmode : KFmode;
30688           else
30689             return opt_scalar_float_mode ();
30690
30691         case 128:
30692           return opt_scalar_float_mode ();
30693
30694         default:
30695           /* Those are the only valid _FloatNx types.  */
30696           gcc_unreachable ();
30697         }
30698     }
30699   else
30700     {
30701       switch (n)
30702         {
30703         case 32:
30704           return SFmode;
30705
30706         case 64:
30707           return DFmode;
30708
30709         case 128:
30710           if (TARGET_FLOAT128_TYPE)
30711             return (FLOAT128_IEEE_P (TFmode)) ? TFmode : KFmode;
30712           else
30713             return opt_scalar_float_mode ();
30714
30715         default:
30716           return opt_scalar_float_mode ();
30717         }
30718     }
30719
30720 }
30721
30722 /* Target hook for c_mode_for_suffix.  */
30723 static machine_mode
30724 rs6000_c_mode_for_suffix (char suffix)
30725 {
30726   if (TARGET_FLOAT128_TYPE)
30727     {
30728       if (suffix == 'q' || suffix == 'Q')
30729         return (FLOAT128_IEEE_P (TFmode)) ? TFmode : KFmode;
30730
30731       /* At the moment, we are not defining a suffix for IBM extended double.
30732          If/when the default for -mabi=ieeelongdouble is changed, and we want
30733          to support __ibm128 constants in legacy library code, we may need to
30734          re-evalaute this decision.  Currently, c-lex.c only supports 'w' and
30735          'q' as machine dependent suffixes.  The x86_64 port uses 'w' for
30736          __float80 constants.  */
30737     }
30738
30739   return VOIDmode;
30740 }
30741
30742 /* Target hook for invalid_arg_for_unprototyped_fn. */
30743 static const char *
30744 invalid_arg_for_unprototyped_fn (const_tree typelist, const_tree funcdecl, const_tree val)
30745 {
30746   return (!rs6000_darwin64_abi
30747           && typelist == 0
30748           && TREE_CODE (TREE_TYPE (val)) == VECTOR_TYPE
30749           && (funcdecl == NULL_TREE
30750               || (TREE_CODE (funcdecl) == FUNCTION_DECL
30751                   && DECL_BUILT_IN_CLASS (funcdecl) != BUILT_IN_MD)))
30752           ? N_("AltiVec argument passed to unprototyped function")
30753           : NULL;
30754 }
30755
30756 /* For TARGET_SECURE_PLT 32-bit PIC code we can save PIC register
30757    setup by using __stack_chk_fail_local hidden function instead of
30758    calling __stack_chk_fail directly.  Otherwise it is better to call
30759    __stack_chk_fail directly.  */
30760
30761 static tree ATTRIBUTE_UNUSED
30762 rs6000_stack_protect_fail (void)
30763 {
30764   return (DEFAULT_ABI == ABI_V4 && TARGET_SECURE_PLT && flag_pic)
30765          ? default_hidden_stack_protect_fail ()
30766          : default_external_stack_protect_fail ();
30767 }
30768
30769 /* Implement the TARGET_ASAN_SHADOW_OFFSET hook.  */
30770
30771 #if TARGET_ELF
30772 static unsigned HOST_WIDE_INT
30773 rs6000_asan_shadow_offset (void)
30774 {
30775   return (unsigned HOST_WIDE_INT) 1 << (TARGET_64BIT ? 41 : 29);
30776 }
30777 #endif
30778 \f
30779 /* Mask options that we want to support inside of attribute((target)) and
30780    #pragma GCC target operations.  Note, we do not include things like
30781    64/32-bit, endianness, hard/soft floating point, etc. that would have
30782    different calling sequences.  */
30783
30784 struct rs6000_opt_mask {
30785   const char *name;             /* option name */
30786   HOST_WIDE_INT mask;           /* mask to set */
30787   bool invert;                  /* invert sense of mask */
30788   bool valid_target;            /* option is a target option */
30789 };
30790
30791 static struct rs6000_opt_mask const rs6000_opt_masks[] =
30792 {
30793   { "altivec",                  OPTION_MASK_ALTIVEC,            false, true  },
30794   { "cmpb",                     OPTION_MASK_CMPB,               false, true  },
30795   { "crypto",                   OPTION_MASK_CRYPTO,             false, true  },
30796   { "direct-move",              OPTION_MASK_DIRECT_MOVE,        false, true  },
30797   { "dlmzb",                    OPTION_MASK_DLMZB,              false, true  },
30798   { "efficient-unaligned-vsx",  OPTION_MASK_EFFICIENT_UNALIGNED_VSX,
30799                                                                 false, true  },
30800   { "float128",                 OPTION_MASK_FLOAT128_KEYWORD,   false, true  },
30801   { "float128-hardware",        OPTION_MASK_FLOAT128_HW,        false, true  },
30802   { "fprnd",                    OPTION_MASK_FPRND,              false, true  },
30803   { "future",                   OPTION_MASK_FUTURE,             false, true  },
30804   { "hard-dfp",                 OPTION_MASK_DFP,                false, true  },
30805   { "htm",                      OPTION_MASK_HTM,                false, true  },
30806   { "isel",                     OPTION_MASK_ISEL,               false, true  },
30807   { "mfcrf",                    OPTION_MASK_MFCRF,              false, true  },
30808   { "mfpgpr",                   0,                              false, true  },
30809   { "modulo",                   OPTION_MASK_MODULO,             false, true  },
30810   { "mulhw",                    OPTION_MASK_MULHW,              false, true  },
30811   { "multiple",                 OPTION_MASK_MULTIPLE,           false, true  },
30812   { "pcrel",                    OPTION_MASK_PCREL,              false, true  },
30813   { "popcntb",                  OPTION_MASK_POPCNTB,            false, true  },
30814   { "popcntd",                  OPTION_MASK_POPCNTD,            false, true  },
30815   { "power8-fusion",            OPTION_MASK_P8_FUSION,          false, true  },
30816   { "power8-fusion-sign",       OPTION_MASK_P8_FUSION_SIGN,     false, true  },
30817   { "power8-vector",            OPTION_MASK_P8_VECTOR,          false, true  },
30818   { "power9-minmax",            OPTION_MASK_P9_MINMAX,          false, true  },
30819   { "power9-misc",              OPTION_MASK_P9_MISC,            false, true  },
30820   { "power9-vector",            OPTION_MASK_P9_VECTOR,          false, true  },
30821   { "powerpc-gfxopt",           OPTION_MASK_PPC_GFXOPT,         false, true  },
30822   { "powerpc-gpopt",            OPTION_MASK_PPC_GPOPT,          false, true  },
30823   { "prefixed-addr",            OPTION_MASK_PREFIXED_ADDR,      false, true  },
30824   { "quad-memory",              OPTION_MASK_QUAD_MEMORY,        false, true  },
30825   { "quad-memory-atomic",       OPTION_MASK_QUAD_MEMORY_ATOMIC, false, true  },
30826   { "recip-precision",          OPTION_MASK_RECIP_PRECISION,    false, true  },
30827   { "save-toc-indirect",        OPTION_MASK_SAVE_TOC_INDIRECT,  false, true  },
30828   { "string",                   0,                              false, true  },
30829   { "update",                   OPTION_MASK_NO_UPDATE,          true , true  },
30830   { "vsx",                      OPTION_MASK_VSX,                false, true  },
30831 #ifdef OPTION_MASK_64BIT
30832 #if TARGET_AIX_OS
30833   { "aix64",                    OPTION_MASK_64BIT,              false, false },
30834   { "aix32",                    OPTION_MASK_64BIT,              true,  false },
30835 #else
30836   { "64",                       OPTION_MASK_64BIT,              false, false },
30837   { "32",                       OPTION_MASK_64BIT,              true,  false },
30838 #endif
30839 #endif
30840 #ifdef OPTION_MASK_EABI
30841   { "eabi",                     OPTION_MASK_EABI,               false, false },
30842 #endif
30843 #ifdef OPTION_MASK_LITTLE_ENDIAN
30844   { "little",                   OPTION_MASK_LITTLE_ENDIAN,      false, false },
30845   { "big",                      OPTION_MASK_LITTLE_ENDIAN,      true,  false },
30846 #endif
30847 #ifdef OPTION_MASK_RELOCATABLE
30848   { "relocatable",              OPTION_MASK_RELOCATABLE,        false, false },
30849 #endif
30850 #ifdef OPTION_MASK_STRICT_ALIGN
30851   { "strict-align",             OPTION_MASK_STRICT_ALIGN,       false, false },
30852 #endif
30853   { "soft-float",               OPTION_MASK_SOFT_FLOAT,         false, false },
30854   { "string",                   0,                              false, false },
30855 };
30856
30857 /* Builtin mask mapping for printing the flags.  */
30858 static struct rs6000_opt_mask const rs6000_builtin_mask_names[] =
30859 {
30860   { "altivec",           RS6000_BTM_ALTIVEC,    false, false },
30861   { "vsx",               RS6000_BTM_VSX,        false, false },
30862   { "fre",               RS6000_BTM_FRE,        false, false },
30863   { "fres",              RS6000_BTM_FRES,       false, false },
30864   { "frsqrte",           RS6000_BTM_FRSQRTE,    false, false },
30865   { "frsqrtes",          RS6000_BTM_FRSQRTES,   false, false },
30866   { "popcntd",           RS6000_BTM_POPCNTD,    false, false },
30867   { "cell",              RS6000_BTM_CELL,       false, false },
30868   { "power8-vector",     RS6000_BTM_P8_VECTOR,  false, false },
30869   { "power9-vector",     RS6000_BTM_P9_VECTOR,  false, false },
30870   { "power9-misc",       RS6000_BTM_P9_MISC,    false, false },
30871   { "crypto",            RS6000_BTM_CRYPTO,     false, false },
30872   { "htm",               RS6000_BTM_HTM,        false, false },
30873   { "hard-dfp",          RS6000_BTM_DFP,        false, false },
30874   { "hard-float",        RS6000_BTM_HARD_FLOAT, false, false },
30875   { "long-double-128",   RS6000_BTM_LDBL128,    false, false },
30876   { "powerpc64",         RS6000_BTM_POWERPC64,  false, false },
30877   { "float128",          RS6000_BTM_FLOAT128,   false, false },
30878   { "float128-hw",       RS6000_BTM_FLOAT128_HW,false, false },
30879 };
30880
30881 /* Option variables that we want to support inside attribute((target)) and
30882    #pragma GCC target operations.  */
30883
30884 struct rs6000_opt_var {
30885   const char *name;             /* option name */
30886   size_t global_offset;         /* offset of the option in global_options.  */
30887   size_t target_offset;         /* offset of the option in target options.  */
30888 };
30889
30890 static struct rs6000_opt_var const rs6000_opt_vars[] =
30891 {
30892   { "friz",
30893     offsetof (struct gcc_options, x_TARGET_FRIZ),
30894     offsetof (struct cl_target_option, x_TARGET_FRIZ), },
30895   { "avoid-indexed-addresses",
30896     offsetof (struct gcc_options, x_TARGET_AVOID_XFORM),
30897     offsetof (struct cl_target_option, x_TARGET_AVOID_XFORM) },
30898   { "longcall",
30899     offsetof (struct gcc_options, x_rs6000_default_long_calls),
30900     offsetof (struct cl_target_option, x_rs6000_default_long_calls), },
30901   { "optimize-swaps",
30902     offsetof (struct gcc_options, x_rs6000_optimize_swaps),
30903     offsetof (struct cl_target_option, x_rs6000_optimize_swaps), },
30904   { "allow-movmisalign",
30905     offsetof (struct gcc_options, x_TARGET_ALLOW_MOVMISALIGN),
30906     offsetof (struct cl_target_option, x_TARGET_ALLOW_MOVMISALIGN), },
30907   { "sched-groups",
30908     offsetof (struct gcc_options, x_TARGET_SCHED_GROUPS),
30909     offsetof (struct cl_target_option, x_TARGET_SCHED_GROUPS), },
30910   { "always-hint",
30911     offsetof (struct gcc_options, x_TARGET_ALWAYS_HINT),
30912     offsetof (struct cl_target_option, x_TARGET_ALWAYS_HINT), },
30913   { "align-branch-targets",
30914     offsetof (struct gcc_options, x_TARGET_ALIGN_BRANCH_TARGETS),
30915     offsetof (struct cl_target_option, x_TARGET_ALIGN_BRANCH_TARGETS), },
30916   { "tls-markers",
30917     offsetof (struct gcc_options, x_tls_markers),
30918     offsetof (struct cl_target_option, x_tls_markers), },
30919   { "sched-prolog",
30920     offsetof (struct gcc_options, x_TARGET_SCHED_PROLOG),
30921     offsetof (struct cl_target_option, x_TARGET_SCHED_PROLOG), },
30922   { "sched-epilog",
30923     offsetof (struct gcc_options, x_TARGET_SCHED_PROLOG),
30924     offsetof (struct cl_target_option, x_TARGET_SCHED_PROLOG), },
30925   { "speculate-indirect-jumps",
30926     offsetof (struct gcc_options, x_rs6000_speculate_indirect_jumps),
30927     offsetof (struct cl_target_option, x_rs6000_speculate_indirect_jumps), },
30928 };
30929
30930 /* Inner function to handle attribute((target("..."))) and #pragma GCC target
30931    parsing.  Return true if there were no errors.  */
30932
30933 static bool
30934 rs6000_inner_target_options (tree args, bool attr_p)
30935 {
30936   bool ret = true;
30937
30938   if (args == NULL_TREE)
30939     ;
30940
30941   else if (TREE_CODE (args) == STRING_CST)
30942     {
30943       char *p = ASTRDUP (TREE_STRING_POINTER (args));
30944       char *q;
30945
30946       while ((q = strtok (p, ",")) != NULL)
30947         {
30948           bool error_p = false;
30949           bool not_valid_p = false;
30950           const char *cpu_opt = NULL;
30951
30952           p = NULL;
30953           if (strncmp (q, "cpu=", 4) == 0)
30954             {
30955               int cpu_index = rs6000_cpu_name_lookup (q+4);
30956               if (cpu_index >= 0)
30957                 rs6000_cpu_index = cpu_index;
30958               else
30959                 {
30960                   error_p = true;
30961                   cpu_opt = q+4;
30962                 }
30963             }
30964           else if (strncmp (q, "tune=", 5) == 0)
30965             {
30966               int tune_index = rs6000_cpu_name_lookup (q+5);
30967               if (tune_index >= 0)
30968                 rs6000_tune_index = tune_index;
30969               else
30970                 {
30971                   error_p = true;
30972                   cpu_opt = q+5;
30973                 }
30974             }
30975           else
30976             {
30977               size_t i;
30978               bool invert = false;
30979               char *r = q;
30980
30981               error_p = true;
30982               if (strncmp (r, "no-", 3) == 0)
30983                 {
30984                   invert = true;
30985                   r += 3;
30986                 }
30987
30988               for (i = 0; i < ARRAY_SIZE (rs6000_opt_masks); i++)
30989                 if (strcmp (r, rs6000_opt_masks[i].name) == 0)
30990                   {
30991                     HOST_WIDE_INT mask = rs6000_opt_masks[i].mask;
30992
30993                     if (!rs6000_opt_masks[i].valid_target)
30994                       not_valid_p = true;
30995                     else
30996                       {
30997                         error_p = false;
30998                         rs6000_isa_flags_explicit |= mask;
30999
31000                         /* VSX needs altivec, so -mvsx automagically sets
31001                            altivec and disables -mavoid-indexed-addresses.  */
31002                         if (!invert)
31003                           {
31004                             if (mask == OPTION_MASK_VSX)
31005                               {
31006                                 mask |= OPTION_MASK_ALTIVEC;
31007                                 TARGET_AVOID_XFORM = 0;
31008                               }
31009                           }
31010
31011                         if (rs6000_opt_masks[i].invert)
31012                           invert = !invert;
31013
31014                         if (invert)
31015                           rs6000_isa_flags &= ~mask;
31016                         else
31017                           rs6000_isa_flags |= mask;
31018                       }
31019                     break;
31020                   }
31021
31022               if (error_p && !not_valid_p)
31023                 {
31024                   for (i = 0; i < ARRAY_SIZE (rs6000_opt_vars); i++)
31025                     if (strcmp (r, rs6000_opt_vars[i].name) == 0)
31026                       {
31027                         size_t j = rs6000_opt_vars[i].global_offset;
31028                         *((int *) ((char *)&global_options + j)) = !invert;
31029                         error_p = false;
31030                         not_valid_p = false;
31031                         break;
31032                       }
31033                 }
31034             }
31035
31036           if (error_p)
31037             {
31038               const char *eprefix, *esuffix;
31039
31040               ret = false;
31041               if (attr_p)
31042                 {
31043                   eprefix = "__attribute__((__target__(";
31044                   esuffix = ")))";
31045                 }
31046               else
31047                 {
31048                   eprefix = "#pragma GCC target ";
31049                   esuffix = "";
31050                 }
31051
31052               if (cpu_opt)
31053                 error ("invalid cpu %qs for %s%qs%s", cpu_opt, eprefix,
31054                        q, esuffix);
31055               else if (not_valid_p)
31056                 error ("%s%qs%s is not allowed", eprefix, q, esuffix);
31057               else
31058                 error ("%s%qs%s is invalid", eprefix, q, esuffix);
31059             }
31060         }
31061     }
31062
31063   else if (TREE_CODE (args) == TREE_LIST)
31064     {
31065       do
31066         {
31067           tree value = TREE_VALUE (args);
31068           if (value)
31069             {
31070               bool ret2 = rs6000_inner_target_options (value, attr_p);
31071               if (!ret2)
31072                 ret = false;
31073             }
31074           args = TREE_CHAIN (args);
31075         }
31076       while (args != NULL_TREE);
31077     }
31078
31079   else
31080     {
31081       error ("attribute %<target%> argument not a string");
31082       return false;
31083     }
31084
31085   return ret;
31086 }
31087
31088 /* Print out the target options as a list for -mdebug=target.  */
31089
31090 static void
31091 rs6000_debug_target_options (tree args, const char *prefix)
31092 {
31093   if (args == NULL_TREE)
31094     fprintf (stderr, "%s<NULL>", prefix);
31095
31096   else if (TREE_CODE (args) == STRING_CST)
31097     {
31098       char *p = ASTRDUP (TREE_STRING_POINTER (args));
31099       char *q;
31100
31101       while ((q = strtok (p, ",")) != NULL)
31102         {
31103           p = NULL;
31104           fprintf (stderr, "%s\"%s\"", prefix, q);
31105           prefix = ", ";
31106         }
31107     }
31108
31109   else if (TREE_CODE (args) == TREE_LIST)
31110     {
31111       do
31112         {
31113           tree value = TREE_VALUE (args);
31114           if (value)
31115             {
31116               rs6000_debug_target_options (value, prefix);
31117               prefix = ", ";
31118             }
31119           args = TREE_CHAIN (args);
31120         }
31121       while (args != NULL_TREE);
31122     }
31123
31124   else
31125     gcc_unreachable ();
31126
31127   return;
31128 }
31129
31130 \f
31131 /* Hook to validate attribute((target("..."))).  */
31132
31133 static bool
31134 rs6000_valid_attribute_p (tree fndecl,
31135                           tree ARG_UNUSED (name),
31136                           tree args,
31137                           int flags)
31138 {
31139   struct cl_target_option cur_target;
31140   bool ret;
31141   tree old_optimize;
31142   tree new_target, new_optimize;
31143   tree func_optimize;
31144
31145   gcc_assert ((fndecl != NULL_TREE) && (args != NULL_TREE));
31146
31147   if (TARGET_DEBUG_TARGET)
31148     {
31149       tree tname = DECL_NAME (fndecl);
31150       fprintf (stderr, "\n==================== rs6000_valid_attribute_p:\n");
31151       if (tname)
31152         fprintf (stderr, "function: %.*s\n",
31153                  (int) IDENTIFIER_LENGTH (tname),
31154                  IDENTIFIER_POINTER (tname));
31155       else
31156         fprintf (stderr, "function: unknown\n");
31157   
31158       fprintf (stderr, "args:");
31159       rs6000_debug_target_options (args, " ");
31160       fprintf (stderr, "\n");
31161
31162       if (flags)
31163         fprintf (stderr, "flags: 0x%x\n", flags);
31164
31165       fprintf (stderr, "--------------------\n");
31166     }
31167
31168   /* attribute((target("default"))) does nothing, beyond
31169      affecting multi-versioning.  */
31170   if (TREE_VALUE (args)
31171       && TREE_CODE (TREE_VALUE (args)) == STRING_CST
31172       && TREE_CHAIN (args) == NULL_TREE
31173       && strcmp (TREE_STRING_POINTER (TREE_VALUE (args)), "default") == 0)
31174     return true;
31175
31176   old_optimize = build_optimization_node (&global_options);
31177   func_optimize = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (fndecl);
31178
31179   /* If the function changed the optimization levels as well as setting target
31180      options, start with the optimizations specified.  */
31181   if (func_optimize && func_optimize != old_optimize)
31182     cl_optimization_restore (&global_options,
31183                              TREE_OPTIMIZATION (func_optimize));
31184
31185   /* The target attributes may also change some optimization flags, so update
31186      the optimization options if necessary.  */
31187   cl_target_option_save (&cur_target, &global_options);
31188   rs6000_cpu_index = rs6000_tune_index = -1;
31189   ret = rs6000_inner_target_options (args, true);
31190
31191   /* Set up any additional state.  */
31192   if (ret)
31193     {
31194       ret = rs6000_option_override_internal (false);
31195       new_target = build_target_option_node (&global_options);
31196     }
31197   else
31198     new_target = NULL;
31199
31200   new_optimize = build_optimization_node (&global_options);
31201
31202   if (!new_target)
31203     ret = false;
31204
31205   else if (fndecl)
31206     {
31207       DECL_FUNCTION_SPECIFIC_TARGET (fndecl) = new_target;
31208
31209       if (old_optimize != new_optimize)
31210         DECL_FUNCTION_SPECIFIC_OPTIMIZATION (fndecl) = new_optimize;
31211     }
31212
31213   cl_target_option_restore (&global_options, &cur_target);
31214
31215   if (old_optimize != new_optimize)
31216     cl_optimization_restore (&global_options,
31217                              TREE_OPTIMIZATION (old_optimize));
31218
31219   return ret;
31220 }
31221
31222 \f
31223 /* Hook to validate the current #pragma GCC target and set the state, and
31224    update the macros based on what was changed.  If ARGS is NULL, then
31225    POP_TARGET is used to reset the options.  */
31226
31227 bool
31228 rs6000_pragma_target_parse (tree args, tree pop_target)
31229 {
31230   tree prev_tree = build_target_option_node (&global_options);
31231   tree cur_tree;
31232   struct cl_target_option *prev_opt, *cur_opt;
31233   HOST_WIDE_INT prev_flags, cur_flags, diff_flags;
31234   HOST_WIDE_INT prev_bumask, cur_bumask, diff_bumask;
31235
31236   if (TARGET_DEBUG_TARGET)
31237     {
31238       fprintf (stderr, "\n==================== rs6000_pragma_target_parse\n");
31239       fprintf (stderr, "args:");
31240       rs6000_debug_target_options (args, " ");
31241       fprintf (stderr, "\n");
31242
31243       if (pop_target)
31244         {
31245           fprintf (stderr, "pop_target:\n");
31246           debug_tree (pop_target);
31247         }
31248       else
31249         fprintf (stderr, "pop_target: <NULL>\n");
31250
31251       fprintf (stderr, "--------------------\n");
31252     }
31253
31254   if (! args)
31255     {
31256       cur_tree = ((pop_target)
31257                   ? pop_target
31258                   : target_option_default_node);
31259       cl_target_option_restore (&global_options,
31260                                 TREE_TARGET_OPTION (cur_tree));
31261     }
31262   else
31263     {
31264       rs6000_cpu_index = rs6000_tune_index = -1;
31265       if (!rs6000_inner_target_options (args, false)
31266           || !rs6000_option_override_internal (false)
31267           || (cur_tree = build_target_option_node (&global_options))
31268              == NULL_TREE)
31269         {
31270           if (TARGET_DEBUG_BUILTIN || TARGET_DEBUG_TARGET)
31271             fprintf (stderr, "invalid pragma\n");
31272
31273           return false;
31274         }
31275     }
31276
31277   target_option_current_node = cur_tree;
31278   rs6000_activate_target_options (target_option_current_node);
31279
31280   /* If we have the preprocessor linked in (i.e. C or C++ languages), possibly
31281      change the macros that are defined.  */
31282   if (rs6000_target_modify_macros_ptr)
31283     {
31284       prev_opt    = TREE_TARGET_OPTION (prev_tree);
31285       prev_bumask = prev_opt->x_rs6000_builtin_mask;
31286       prev_flags  = prev_opt->x_rs6000_isa_flags;
31287
31288       cur_opt     = TREE_TARGET_OPTION (cur_tree);
31289       cur_flags   = cur_opt->x_rs6000_isa_flags;
31290       cur_bumask  = cur_opt->x_rs6000_builtin_mask;
31291
31292       diff_bumask = (prev_bumask ^ cur_bumask);
31293       diff_flags  = (prev_flags ^ cur_flags);
31294
31295       if ((diff_flags != 0) || (diff_bumask != 0))
31296         {
31297           /* Delete old macros.  */
31298           rs6000_target_modify_macros_ptr (false,
31299                                            prev_flags & diff_flags,
31300                                            prev_bumask & diff_bumask);
31301
31302           /* Define new macros.  */
31303           rs6000_target_modify_macros_ptr (true,
31304                                            cur_flags & diff_flags,
31305                                            cur_bumask & diff_bumask);
31306         }
31307     }
31308
31309   return true;
31310 }
31311
31312 \f
31313 /* Remember the last target of rs6000_set_current_function.  */
31314 static GTY(()) tree rs6000_previous_fndecl;
31315
31316 /* Restore target's globals from NEW_TREE and invalidate the
31317    rs6000_previous_fndecl cache.  */
31318
31319 void
31320 rs6000_activate_target_options (tree new_tree)
31321 {
31322   cl_target_option_restore (&global_options, TREE_TARGET_OPTION (new_tree));
31323   if (TREE_TARGET_GLOBALS (new_tree))
31324     restore_target_globals (TREE_TARGET_GLOBALS (new_tree));
31325   else if (new_tree == target_option_default_node)
31326     restore_target_globals (&default_target_globals);
31327   else
31328     TREE_TARGET_GLOBALS (new_tree) = save_target_globals_default_opts ();
31329   rs6000_previous_fndecl = NULL_TREE;
31330 }
31331
31332 /* Establish appropriate back-end context for processing the function
31333    FNDECL.  The argument might be NULL to indicate processing at top
31334    level, outside of any function scope.  */
31335 static void
31336 rs6000_set_current_function (tree fndecl)
31337 {
31338   if (TARGET_DEBUG_TARGET)
31339     {
31340       fprintf (stderr, "\n==================== rs6000_set_current_function");
31341
31342       if (fndecl)
31343         fprintf (stderr, ", fndecl %s (%p)",
31344                  (DECL_NAME (fndecl)
31345                   ? IDENTIFIER_POINTER (DECL_NAME (fndecl))
31346                   : "<unknown>"), (void *)fndecl);
31347
31348       if (rs6000_previous_fndecl)
31349         fprintf (stderr, ", prev_fndecl (%p)", (void *)rs6000_previous_fndecl);
31350
31351       fprintf (stderr, "\n");
31352     }
31353
31354   /* Only change the context if the function changes.  This hook is called
31355      several times in the course of compiling a function, and we don't want to
31356      slow things down too much or call target_reinit when it isn't safe.  */
31357   if (fndecl == rs6000_previous_fndecl)
31358     return;
31359
31360   tree old_tree;
31361   if (rs6000_previous_fndecl == NULL_TREE)
31362     old_tree = target_option_current_node;
31363   else if (DECL_FUNCTION_SPECIFIC_TARGET (rs6000_previous_fndecl))
31364     old_tree = DECL_FUNCTION_SPECIFIC_TARGET (rs6000_previous_fndecl);
31365   else
31366     old_tree = target_option_default_node;
31367
31368   tree new_tree;
31369   if (fndecl == NULL_TREE)
31370     {
31371       if (old_tree != target_option_current_node)
31372         new_tree = target_option_current_node;
31373       else
31374         new_tree = NULL_TREE;
31375     }
31376   else
31377     {
31378       new_tree = DECL_FUNCTION_SPECIFIC_TARGET (fndecl);
31379       if (new_tree == NULL_TREE)
31380         new_tree = target_option_default_node;
31381     }
31382
31383   if (TARGET_DEBUG_TARGET)
31384     {
31385       if (new_tree)
31386         {
31387           fprintf (stderr, "\nnew fndecl target specific options:\n");
31388           debug_tree (new_tree);
31389         }
31390
31391       if (old_tree)
31392         {
31393           fprintf (stderr, "\nold fndecl target specific options:\n");
31394           debug_tree (old_tree);
31395         }
31396
31397       if (old_tree != NULL_TREE || new_tree != NULL_TREE)
31398         fprintf (stderr, "--------------------\n");
31399     }
31400
31401   if (new_tree && old_tree != new_tree)
31402     rs6000_activate_target_options (new_tree);
31403
31404   if (fndecl)
31405     rs6000_previous_fndecl = fndecl;
31406 }
31407
31408 \f
31409 /* Save the current options */
31410
31411 static void
31412 rs6000_function_specific_save (struct cl_target_option *ptr,
31413                                struct gcc_options *opts)
31414 {
31415   ptr->x_rs6000_isa_flags = opts->x_rs6000_isa_flags;
31416   ptr->x_rs6000_isa_flags_explicit = opts->x_rs6000_isa_flags_explicit;
31417 }
31418
31419 /* Restore the current options */
31420
31421 static void
31422 rs6000_function_specific_restore (struct gcc_options *opts,
31423                                   struct cl_target_option *ptr)
31424                                   
31425 {
31426   opts->x_rs6000_isa_flags = ptr->x_rs6000_isa_flags;
31427   opts->x_rs6000_isa_flags_explicit = ptr->x_rs6000_isa_flags_explicit;
31428   (void) rs6000_option_override_internal (false);
31429 }
31430
31431 /* Print the current options */
31432
31433 static void
31434 rs6000_function_specific_print (FILE *file, int indent,
31435                                 struct cl_target_option *ptr)
31436 {
31437   rs6000_print_isa_options (file, indent, "Isa options set",
31438                             ptr->x_rs6000_isa_flags);
31439
31440   rs6000_print_isa_options (file, indent, "Isa options explicit",
31441                             ptr->x_rs6000_isa_flags_explicit);
31442 }
31443
31444 /* Helper function to print the current isa or misc options on a line.  */
31445
31446 static void
31447 rs6000_print_options_internal (FILE *file,
31448                                int indent,
31449                                const char *string,
31450                                HOST_WIDE_INT flags,
31451                                const char *prefix,
31452                                const struct rs6000_opt_mask *opts,
31453                                size_t num_elements)
31454 {
31455   size_t i;
31456   size_t start_column = 0;
31457   size_t cur_column;
31458   size_t max_column = 120;
31459   size_t prefix_len = strlen (prefix);
31460   size_t comma_len = 0;
31461   const char *comma = "";
31462
31463   if (indent)
31464     start_column += fprintf (file, "%*s", indent, "");
31465
31466   if (!flags)
31467     {
31468       fprintf (stderr, DEBUG_FMT_S, string, "<none>");
31469       return;
31470     }
31471
31472   start_column += fprintf (stderr, DEBUG_FMT_WX, string, flags);
31473
31474   /* Print the various mask options.  */
31475   cur_column = start_column;
31476   for (i = 0; i < num_elements; i++)
31477     {
31478       bool invert = opts[i].invert;
31479       const char *name = opts[i].name;
31480       const char *no_str = "";
31481       HOST_WIDE_INT mask = opts[i].mask;
31482       size_t len = comma_len + prefix_len + strlen (name);
31483
31484       if (!invert)
31485         {
31486           if ((flags & mask) == 0)
31487             {
31488               no_str = "no-";
31489               len += sizeof ("no-") - 1;
31490             }
31491
31492           flags &= ~mask;
31493         }
31494
31495       else
31496         {
31497           if ((flags & mask) != 0)
31498             {
31499               no_str = "no-";
31500               len += sizeof ("no-") - 1;
31501             }
31502
31503           flags |= mask;
31504         }
31505
31506       cur_column += len;
31507       if (cur_column > max_column)
31508         {
31509           fprintf (stderr, ", \\\n%*s", (int)start_column, "");
31510           cur_column = start_column + len;
31511           comma = "";
31512         }
31513
31514       fprintf (file, "%s%s%s%s", comma, prefix, no_str, name);
31515       comma = ", ";
31516       comma_len = sizeof (", ") - 1;
31517     }
31518
31519   fputs ("\n", file);
31520 }
31521
31522 /* Helper function to print the current isa options on a line.  */
31523
31524 static void
31525 rs6000_print_isa_options (FILE *file, int indent, const char *string,
31526                           HOST_WIDE_INT flags)
31527 {
31528   rs6000_print_options_internal (file, indent, string, flags, "-m",
31529                                  &rs6000_opt_masks[0],
31530                                  ARRAY_SIZE (rs6000_opt_masks));
31531 }
31532
31533 static void
31534 rs6000_print_builtin_options (FILE *file, int indent, const char *string,
31535                               HOST_WIDE_INT flags)
31536 {
31537   rs6000_print_options_internal (file, indent, string, flags, "",
31538                                  &rs6000_builtin_mask_names[0],
31539                                  ARRAY_SIZE (rs6000_builtin_mask_names));
31540 }
31541
31542 /* If the user used -mno-vsx, we need turn off all of the implicit ISA 2.06,
31543    2.07, and 3.0 options that relate to the vector unit (-mdirect-move,
31544    -mupper-regs-df, etc.).
31545
31546    If the user used -mno-power8-vector, we need to turn off all of the implicit
31547    ISA 2.07 and 3.0 options that relate to the vector unit.
31548
31549    If the user used -mno-power9-vector, we need to turn off all of the implicit
31550    ISA 3.0 options that relate to the vector unit.
31551
31552    This function does not handle explicit options such as the user specifying
31553    -mdirect-move.  These are handled in rs6000_option_override_internal, and
31554    the appropriate error is given if needed.
31555
31556    We return a mask of all of the implicit options that should not be enabled
31557    by default.  */
31558
31559 static HOST_WIDE_INT
31560 rs6000_disable_incompatible_switches (void)
31561 {
31562   HOST_WIDE_INT ignore_masks = rs6000_isa_flags_explicit;
31563   size_t i, j;
31564
31565   static const struct {
31566     const HOST_WIDE_INT no_flag;        /* flag explicitly turned off.  */
31567     const HOST_WIDE_INT dep_flags;      /* flags that depend on this option.  */
31568     const char *const name;             /* name of the switch.  */
31569   } flags[] = {
31570     { OPTION_MASK_FUTURE,       OTHER_FUTURE_MASKS,     "future"        },
31571     { OPTION_MASK_P9_VECTOR,    OTHER_P9_VECTOR_MASKS,  "power9-vector" },
31572     { OPTION_MASK_P8_VECTOR,    OTHER_P8_VECTOR_MASKS,  "power8-vector" },
31573     { OPTION_MASK_VSX,          OTHER_VSX_VECTOR_MASKS, "vsx"           },
31574   };
31575
31576   for (i = 0; i < ARRAY_SIZE (flags); i++)
31577     {
31578       HOST_WIDE_INT no_flag = flags[i].no_flag;
31579
31580       if ((rs6000_isa_flags & no_flag) == 0
31581           && (rs6000_isa_flags_explicit & no_flag) != 0)
31582         {
31583           HOST_WIDE_INT dep_flags = flags[i].dep_flags;
31584           HOST_WIDE_INT set_flags = (rs6000_isa_flags_explicit
31585                                      & rs6000_isa_flags
31586                                      & dep_flags);
31587
31588           if (set_flags)
31589             {
31590               for (j = 0; j < ARRAY_SIZE (rs6000_opt_masks); j++)
31591                 if ((set_flags & rs6000_opt_masks[j].mask) != 0)
31592                   {
31593                     set_flags &= ~rs6000_opt_masks[j].mask;
31594                     error ("%<-mno-%s%> turns off %<-m%s%>",
31595                            flags[i].name,
31596                            rs6000_opt_masks[j].name);
31597                   }
31598
31599               gcc_assert (!set_flags);
31600             }
31601
31602           rs6000_isa_flags &= ~dep_flags;
31603           ignore_masks |= no_flag | dep_flags;
31604         }
31605     }
31606
31607   return ignore_masks;
31608 }
31609
31610 \f
31611 /* Helper function for printing the function name when debugging.  */
31612
31613 static const char *
31614 get_decl_name (tree fn)
31615 {
31616   tree name;
31617
31618   if (!fn)
31619     return "<null>";
31620
31621   name = DECL_NAME (fn);
31622   if (!name)
31623     return "<no-name>";
31624
31625   return IDENTIFIER_POINTER (name);
31626 }
31627
31628 /* Return the clone id of the target we are compiling code for in a target
31629    clone.  The clone id is ordered from 0 (default) to CLONE_MAX-1 and gives
31630    the priority list for the target clones (ordered from lowest to
31631    highest).  */
31632
31633 static int
31634 rs6000_clone_priority (tree fndecl)
31635 {
31636   tree fn_opts = DECL_FUNCTION_SPECIFIC_TARGET (fndecl);
31637   HOST_WIDE_INT isa_masks;
31638   int ret = CLONE_DEFAULT;
31639   tree attrs = lookup_attribute ("target", DECL_ATTRIBUTES (fndecl));
31640   const char *attrs_str = NULL;
31641
31642   attrs = TREE_VALUE (TREE_VALUE (attrs));
31643   attrs_str = TREE_STRING_POINTER (attrs);
31644
31645   /* Return priority zero for default function.  Return the ISA needed for the
31646      function if it is not the default.  */
31647   if (strcmp (attrs_str, "default") != 0)
31648     {
31649       if (fn_opts == NULL_TREE)
31650         fn_opts = target_option_default_node;
31651
31652       if (!fn_opts || !TREE_TARGET_OPTION (fn_opts))
31653         isa_masks = rs6000_isa_flags;
31654       else
31655         isa_masks = TREE_TARGET_OPTION (fn_opts)->x_rs6000_isa_flags;
31656
31657       for (ret = CLONE_MAX - 1; ret != 0; ret--)
31658         if ((rs6000_clone_map[ret].isa_mask & isa_masks) != 0)
31659           break;
31660     }
31661
31662   if (TARGET_DEBUG_TARGET)
31663     fprintf (stderr, "rs6000_get_function_version_priority (%s) => %d\n",
31664              get_decl_name (fndecl), ret);
31665
31666   return ret;
31667 }
31668
31669 /* This compares the priority of target features in function DECL1 and DECL2.
31670    It returns positive value if DECL1 is higher priority, negative value if
31671    DECL2 is higher priority and 0 if they are the same.  Note, priorities are
31672    ordered from lowest (CLONE_DEFAULT) to highest (currently CLONE_ISA_3_0).  */
31673
31674 static int
31675 rs6000_compare_version_priority (tree decl1, tree decl2)
31676 {
31677   int priority1 = rs6000_clone_priority (decl1);
31678   int priority2 = rs6000_clone_priority (decl2);
31679   int ret = priority1 - priority2;
31680
31681   if (TARGET_DEBUG_TARGET)
31682     fprintf (stderr, "rs6000_compare_version_priority (%s, %s) => %d\n",
31683              get_decl_name (decl1), get_decl_name (decl2), ret);
31684
31685   return ret;
31686 }
31687
31688 /* Make a dispatcher declaration for the multi-versioned function DECL.
31689    Calls to DECL function will be replaced with calls to the dispatcher
31690    by the front-end.  Returns the decl of the dispatcher function.  */
31691
31692 static tree
31693 rs6000_get_function_versions_dispatcher (void *decl)
31694 {
31695   tree fn = (tree) decl;
31696   struct cgraph_node *node = NULL;
31697   struct cgraph_node *default_node = NULL;
31698   struct cgraph_function_version_info *node_v = NULL;
31699   struct cgraph_function_version_info *first_v = NULL;
31700
31701   tree dispatch_decl = NULL;
31702
31703   struct cgraph_function_version_info *default_version_info = NULL;
31704   gcc_assert (fn != NULL && DECL_FUNCTION_VERSIONED (fn));
31705
31706   if (TARGET_DEBUG_TARGET)
31707     fprintf (stderr, "rs6000_get_function_versions_dispatcher (%s)\n",
31708              get_decl_name (fn));
31709
31710   node = cgraph_node::get (fn);
31711   gcc_assert (node != NULL);
31712
31713   node_v = node->function_version ();
31714   gcc_assert (node_v != NULL);
31715
31716   if (node_v->dispatcher_resolver != NULL)
31717     return node_v->dispatcher_resolver;
31718
31719   /* Find the default version and make it the first node.  */
31720   first_v = node_v;
31721   /* Go to the beginning of the chain.  */
31722   while (first_v->prev != NULL)
31723     first_v = first_v->prev;
31724
31725   default_version_info = first_v;
31726   while (default_version_info != NULL)
31727     {
31728       const tree decl2 = default_version_info->this_node->decl;
31729       if (is_function_default_version (decl2))
31730         break;
31731       default_version_info = default_version_info->next;
31732     }
31733
31734   /* If there is no default node, just return NULL.  */
31735   if (default_version_info == NULL)
31736     return NULL;
31737
31738   /* Make default info the first node.  */
31739   if (first_v != default_version_info)
31740     {
31741       default_version_info->prev->next = default_version_info->next;
31742       if (default_version_info->next)
31743         default_version_info->next->prev = default_version_info->prev;
31744       first_v->prev = default_version_info;
31745       default_version_info->next = first_v;
31746       default_version_info->prev = NULL;
31747     }
31748
31749   default_node = default_version_info->this_node;
31750
31751 #ifndef TARGET_LIBC_PROVIDES_HWCAP_IN_TCB
31752   error_at (DECL_SOURCE_LOCATION (default_node->decl),
31753             "%<target_clones%> attribute needs GLIBC (2.23 and newer) that "
31754             "exports hardware capability bits");
31755 #else
31756
31757   if (targetm.has_ifunc_p ())
31758     {
31759       struct cgraph_function_version_info *it_v = NULL;
31760       struct cgraph_node *dispatcher_node = NULL;
31761       struct cgraph_function_version_info *dispatcher_version_info = NULL;
31762
31763       /* Right now, the dispatching is done via ifunc.  */
31764       dispatch_decl = make_dispatcher_decl (default_node->decl);
31765
31766       dispatcher_node = cgraph_node::get_create (dispatch_decl);
31767       gcc_assert (dispatcher_node != NULL);
31768       dispatcher_node->dispatcher_function = 1;
31769       dispatcher_version_info
31770         = dispatcher_node->insert_new_function_version ();
31771       dispatcher_version_info->next = default_version_info;
31772       dispatcher_node->definition = 1;
31773
31774       /* Set the dispatcher for all the versions.  */
31775       it_v = default_version_info;
31776       while (it_v != NULL)
31777         {
31778           it_v->dispatcher_resolver = dispatch_decl;
31779           it_v = it_v->next;
31780         }
31781     }
31782   else
31783     {
31784       error_at (DECL_SOURCE_LOCATION (default_node->decl),
31785                 "multiversioning needs ifunc which is not supported "
31786                 "on this target");
31787     }
31788 #endif
31789
31790   return dispatch_decl;
31791 }
31792
31793 /* Make the resolver function decl to dispatch the versions of a multi-
31794    versioned function, DEFAULT_DECL.  Create an empty basic block in the
31795    resolver and store the pointer in EMPTY_BB.  Return the decl of the resolver
31796    function.  */
31797
31798 static tree
31799 make_resolver_func (const tree default_decl,
31800                     const tree dispatch_decl,
31801                     basic_block *empty_bb)
31802 {
31803   /* Make the resolver function static.  The resolver function returns
31804      void *.  */
31805   tree decl_name = clone_function_name (default_decl, "resolver");
31806   const char *resolver_name = IDENTIFIER_POINTER (decl_name);
31807   tree type = build_function_type_list (ptr_type_node, NULL_TREE);
31808   tree decl = build_fn_decl (resolver_name, type);
31809   SET_DECL_ASSEMBLER_NAME (decl, decl_name);
31810
31811   DECL_NAME (decl) = decl_name;
31812   TREE_USED (decl) = 1;
31813   DECL_ARTIFICIAL (decl) = 1;
31814   DECL_IGNORED_P (decl) = 0;
31815   TREE_PUBLIC (decl) = 0;
31816   DECL_UNINLINABLE (decl) = 1;
31817
31818   /* Resolver is not external, body is generated.  */
31819   DECL_EXTERNAL (decl) = 0;
31820   DECL_EXTERNAL (dispatch_decl) = 0;
31821
31822   DECL_CONTEXT (decl) = NULL_TREE;
31823   DECL_INITIAL (decl) = make_node (BLOCK);
31824   DECL_STATIC_CONSTRUCTOR (decl) = 0;
31825
31826   /* Build result decl and add to function_decl.  */
31827   tree t = build_decl (UNKNOWN_LOCATION, RESULT_DECL, NULL_TREE, ptr_type_node);
31828   DECL_CONTEXT (t) = decl;
31829   DECL_ARTIFICIAL (t) = 1;
31830   DECL_IGNORED_P (t) = 1;
31831   DECL_RESULT (decl) = t;
31832
31833   gimplify_function_tree (decl);
31834   push_cfun (DECL_STRUCT_FUNCTION (decl));
31835   *empty_bb = init_lowered_empty_function (decl, false,
31836                                            profile_count::uninitialized ());
31837
31838   cgraph_node::add_new_function (decl, true);
31839   symtab->call_cgraph_insertion_hooks (cgraph_node::get_create (decl));
31840
31841   pop_cfun ();
31842
31843   /* Mark dispatch_decl as "ifunc" with resolver as resolver_name.  */
31844   DECL_ATTRIBUTES (dispatch_decl)
31845     = make_attribute ("ifunc", resolver_name, DECL_ATTRIBUTES (dispatch_decl));
31846
31847   cgraph_node::create_same_body_alias (dispatch_decl, decl);
31848
31849   return decl;
31850 }
31851
31852 /* This adds a condition to the basic_block NEW_BB in function FUNCTION_DECL to
31853    return a pointer to VERSION_DECL if we are running on a machine that
31854    supports the index CLONE_ISA hardware architecture bits.  This function will
31855    be called during version dispatch to decide which function version to
31856    execute.  It returns the basic block at the end, to which more conditions
31857    can be added.  */
31858
31859 static basic_block
31860 add_condition_to_bb (tree function_decl, tree version_decl,
31861                      int clone_isa, basic_block new_bb)
31862 {
31863   push_cfun (DECL_STRUCT_FUNCTION (function_decl));
31864
31865   gcc_assert (new_bb != NULL);
31866   gimple_seq gseq = bb_seq (new_bb);
31867
31868
31869   tree convert_expr = build1 (CONVERT_EXPR, ptr_type_node,
31870                               build_fold_addr_expr (version_decl));
31871   tree result_var = create_tmp_var (ptr_type_node);
31872   gimple *convert_stmt = gimple_build_assign (result_var, convert_expr);
31873   gimple *return_stmt = gimple_build_return (result_var);
31874
31875   if (clone_isa == CLONE_DEFAULT)
31876     {
31877       gimple_seq_add_stmt (&gseq, convert_stmt);
31878       gimple_seq_add_stmt (&gseq, return_stmt);
31879       set_bb_seq (new_bb, gseq);
31880       gimple_set_bb (convert_stmt, new_bb);
31881       gimple_set_bb (return_stmt, new_bb);
31882       pop_cfun ();
31883       return new_bb;
31884     }
31885
31886   tree bool_zero = build_int_cst (bool_int_type_node, 0);
31887   tree cond_var = create_tmp_var (bool_int_type_node);
31888   tree predicate_decl = rs6000_builtin_decls [(int) RS6000_BUILTIN_CPU_SUPPORTS];
31889   const char *arg_str = rs6000_clone_map[clone_isa].name;
31890   tree predicate_arg = build_string_literal (strlen (arg_str) + 1, arg_str);
31891   gimple *call_cond_stmt = gimple_build_call (predicate_decl, 1, predicate_arg);
31892   gimple_call_set_lhs (call_cond_stmt, cond_var);
31893
31894   gimple_set_block (call_cond_stmt, DECL_INITIAL (function_decl));
31895   gimple_set_bb (call_cond_stmt, new_bb);
31896   gimple_seq_add_stmt (&gseq, call_cond_stmt);
31897
31898   gimple *if_else_stmt = gimple_build_cond (NE_EXPR, cond_var, bool_zero,
31899                                             NULL_TREE, NULL_TREE);
31900   gimple_set_block (if_else_stmt, DECL_INITIAL (function_decl));
31901   gimple_set_bb (if_else_stmt, new_bb);
31902   gimple_seq_add_stmt (&gseq, if_else_stmt);
31903
31904   gimple_seq_add_stmt (&gseq, convert_stmt);
31905   gimple_seq_add_stmt (&gseq, return_stmt);
31906   set_bb_seq (new_bb, gseq);
31907
31908   basic_block bb1 = new_bb;
31909   edge e12 = split_block (bb1, if_else_stmt);
31910   basic_block bb2 = e12->dest;
31911   e12->flags &= ~EDGE_FALLTHRU;
31912   e12->flags |= EDGE_TRUE_VALUE;
31913
31914   edge e23 = split_block (bb2, return_stmt);
31915   gimple_set_bb (convert_stmt, bb2);
31916   gimple_set_bb (return_stmt, bb2);
31917
31918   basic_block bb3 = e23->dest;
31919   make_edge (bb1, bb3, EDGE_FALSE_VALUE);
31920
31921   remove_edge (e23);
31922   make_edge (bb2, EXIT_BLOCK_PTR_FOR_FN (cfun), 0);
31923
31924   pop_cfun ();
31925   return bb3;
31926 }
31927
31928 /* This function generates the dispatch function for multi-versioned functions.
31929    DISPATCH_DECL is the function which will contain the dispatch logic.
31930    FNDECLS are the function choices for dispatch, and is a tree chain.
31931    EMPTY_BB is the basic block pointer in DISPATCH_DECL in which the dispatch
31932    code is generated.  */
31933
31934 static int
31935 dispatch_function_versions (tree dispatch_decl,
31936                             void *fndecls_p,
31937                             basic_block *empty_bb)
31938 {
31939   int ix;
31940   tree ele;
31941   vec<tree> *fndecls;
31942   tree clones[CLONE_MAX];
31943
31944   if (TARGET_DEBUG_TARGET)
31945     fputs ("dispatch_function_versions, top\n", stderr);
31946
31947   gcc_assert (dispatch_decl != NULL
31948               && fndecls_p != NULL
31949               && empty_bb != NULL);
31950
31951   /* fndecls_p is actually a vector.  */
31952   fndecls = static_cast<vec<tree> *> (fndecls_p);
31953
31954   /* At least one more version other than the default.  */
31955   gcc_assert (fndecls->length () >= 2);
31956
31957   /* The first version in the vector is the default decl.  */
31958   memset ((void *) clones, '\0', sizeof (clones));
31959   clones[CLONE_DEFAULT] = (*fndecls)[0];
31960
31961   /* On the PowerPC, we do not need to call __builtin_cpu_init, which is a NOP
31962      on the PowerPC (on the x86_64, it is not a NOP).  The builtin function
31963      __builtin_cpu_support ensures that the TOC fields are setup by requiring a
31964      recent glibc.  If we ever need to call __builtin_cpu_init, we would need
31965      to insert the code here to do the call.  */
31966
31967   for (ix = 1; fndecls->iterate (ix, &ele); ++ix)
31968     {
31969       int priority = rs6000_clone_priority (ele);
31970       if (!clones[priority])
31971         clones[priority] = ele;
31972     }
31973
31974   for (ix = CLONE_MAX - 1; ix >= 0; ix--)
31975     if (clones[ix])
31976       {
31977         if (TARGET_DEBUG_TARGET)
31978           fprintf (stderr, "dispatch_function_versions, clone %d, %s\n",
31979                    ix, get_decl_name (clones[ix]));
31980
31981         *empty_bb = add_condition_to_bb (dispatch_decl, clones[ix], ix,
31982                                          *empty_bb);
31983       }
31984
31985   return 0;
31986 }
31987
31988 /* Generate the dispatching code body to dispatch multi-versioned function
31989    DECL.  The target hook is called to process the "target" attributes and
31990    provide the code to dispatch the right function at run-time.  NODE points
31991    to the dispatcher decl whose body will be created.  */
31992
31993 static tree
31994 rs6000_generate_version_dispatcher_body (void *node_p)
31995 {
31996   tree resolver;
31997   basic_block empty_bb;
31998   struct cgraph_node *node = (cgraph_node *) node_p;
31999   struct cgraph_function_version_info *ninfo = node->function_version ();
32000
32001   if (ninfo->dispatcher_resolver)
32002     return ninfo->dispatcher_resolver;
32003
32004   /* node is going to be an alias, so remove the finalized bit.  */
32005   node->definition = false;
32006
32007   /* The first version in the chain corresponds to the default version.  */
32008   ninfo->dispatcher_resolver = resolver
32009     = make_resolver_func (ninfo->next->this_node->decl, node->decl, &empty_bb);
32010
32011   if (TARGET_DEBUG_TARGET)
32012     fprintf (stderr, "rs6000_get_function_versions_dispatcher, %s\n",
32013              get_decl_name (resolver));
32014
32015   push_cfun (DECL_STRUCT_FUNCTION (resolver));
32016   auto_vec<tree, 2> fn_ver_vec;
32017
32018   for (struct cgraph_function_version_info *vinfo = ninfo->next;
32019        vinfo;
32020        vinfo = vinfo->next)
32021     {
32022       struct cgraph_node *version = vinfo->this_node;
32023       /* Check for virtual functions here again, as by this time it should
32024          have been determined if this function needs a vtable index or
32025          not.  This happens for methods in derived classes that override
32026          virtual methods in base classes but are not explicitly marked as
32027          virtual.  */
32028       if (DECL_VINDEX (version->decl))
32029         sorry ("Virtual function multiversioning not supported");
32030
32031       fn_ver_vec.safe_push (version->decl);
32032     }
32033
32034   dispatch_function_versions (resolver, &fn_ver_vec, &empty_bb);
32035   cgraph_edge::rebuild_edges ();
32036   pop_cfun ();
32037   return resolver;
32038 }
32039
32040 \f
32041 /* Hook to determine if one function can safely inline another.  */
32042
32043 static bool
32044 rs6000_can_inline_p (tree caller, tree callee)
32045 {
32046   bool ret = false;
32047   tree caller_tree = DECL_FUNCTION_SPECIFIC_TARGET (caller);
32048   tree callee_tree = DECL_FUNCTION_SPECIFIC_TARGET (callee);
32049
32050   /* If callee has no option attributes, then it is ok to inline.  */
32051   if (!callee_tree)
32052     ret = true;
32053
32054   /* If caller has no option attributes, but callee does then it is not ok to
32055      inline.  */
32056   else if (!caller_tree)
32057     ret = false;
32058
32059   else
32060     {
32061       struct cl_target_option *caller_opts = TREE_TARGET_OPTION (caller_tree);
32062       struct cl_target_option *callee_opts = TREE_TARGET_OPTION (callee_tree);
32063
32064       /* Callee's options should a subset of the caller's, i.e. a vsx function
32065          can inline an altivec function but a non-vsx function can't inline a
32066          vsx function.  */
32067       if ((caller_opts->x_rs6000_isa_flags & callee_opts->x_rs6000_isa_flags)
32068           == callee_opts->x_rs6000_isa_flags)
32069         ret = true;
32070     }
32071
32072   if (TARGET_DEBUG_TARGET)
32073     fprintf (stderr, "rs6000_can_inline_p:, caller %s, callee %s, %s inline\n",
32074              get_decl_name (caller), get_decl_name (callee),
32075              (ret ? "can" : "cannot"));
32076
32077   return ret;
32078 }
32079 \f
32080 /* Allocate a stack temp and fixup the address so it meets the particular
32081    memory requirements (either offetable or REG+REG addressing).  */
32082
32083 rtx
32084 rs6000_allocate_stack_temp (machine_mode mode,
32085                             bool offsettable_p,
32086                             bool reg_reg_p)
32087 {
32088   rtx stack = assign_stack_temp (mode, GET_MODE_SIZE (mode));
32089   rtx addr = XEXP (stack, 0);
32090   int strict_p = reload_completed;
32091
32092   if (!legitimate_indirect_address_p (addr, strict_p))
32093     {
32094       if (offsettable_p
32095           && !rs6000_legitimate_offset_address_p (mode, addr, strict_p, true))
32096         stack = replace_equiv_address (stack, copy_addr_to_reg (addr));
32097
32098       else if (reg_reg_p && !legitimate_indexed_address_p (addr, strict_p))
32099         stack = replace_equiv_address (stack, copy_addr_to_reg (addr));
32100     }
32101
32102   return stack;
32103 }
32104
32105 /* Given a memory reference, if it is not a reg or reg+reg addressing,
32106    convert to such a form to deal with memory reference instructions
32107    like STFIWX and LDBRX that only take reg+reg addressing.  */
32108
32109 rtx
32110 rs6000_force_indexed_or_indirect_mem (rtx x)
32111 {
32112   machine_mode mode = GET_MODE (x);
32113
32114   gcc_assert (MEM_P (x));
32115   if (can_create_pseudo_p () && !indexed_or_indirect_operand (x, mode))
32116     {
32117       rtx addr = XEXP (x, 0);
32118       if (GET_CODE (addr) == PRE_INC || GET_CODE (addr) == PRE_DEC)
32119         {
32120           rtx reg = XEXP (addr, 0);
32121           HOST_WIDE_INT size = GET_MODE_SIZE (GET_MODE (x));
32122           rtx size_rtx = GEN_INT ((GET_CODE (addr) == PRE_DEC) ? -size : size);
32123           gcc_assert (REG_P (reg));
32124           emit_insn (gen_add3_insn (reg, reg, size_rtx));
32125           addr = reg;
32126         }
32127       else if (GET_CODE (addr) == PRE_MODIFY)
32128         {
32129           rtx reg = XEXP (addr, 0);
32130           rtx expr = XEXP (addr, 1);
32131           gcc_assert (REG_P (reg));
32132           gcc_assert (GET_CODE (expr) == PLUS);
32133           emit_insn (gen_add3_insn (reg, XEXP (expr, 0), XEXP (expr, 1)));
32134           addr = reg;
32135         }
32136
32137       if (GET_CODE (addr) == PLUS)
32138         {
32139           rtx op0 = XEXP (addr, 0);
32140           rtx op1 = XEXP (addr, 1);
32141           op0 = force_reg (Pmode, op0);
32142           op1 = force_reg (Pmode, op1);
32143           x = replace_equiv_address (x, gen_rtx_PLUS (Pmode, op0, op1));
32144         }
32145       else
32146         x = replace_equiv_address (x, force_reg (Pmode, addr));
32147     }
32148
32149   return x;
32150 }
32151
32152 /* Implement TARGET_LEGITIMATE_CONSTANT_P.
32153
32154    On the RS/6000, all integer constants are acceptable, most won't be valid
32155    for particular insns, though.  Only easy FP constants are acceptable.  */
32156
32157 static bool
32158 rs6000_legitimate_constant_p (machine_mode mode, rtx x)
32159 {
32160   if (TARGET_ELF && tls_referenced_p (x))
32161     return false;
32162
32163   if (CONST_DOUBLE_P (x))
32164     return easy_fp_constant (x, mode);
32165
32166   if (GET_CODE (x) == CONST_VECTOR)
32167     return easy_vector_constant (x, mode);
32168
32169   return true;
32170 }
32171
32172 \f
32173 /* Return TRUE iff the sequence ending in LAST sets the static chain.  */
32174
32175 static bool
32176 chain_already_loaded (rtx_insn *last)
32177 {
32178   for (; last != NULL; last = PREV_INSN (last))
32179     {
32180       if (NONJUMP_INSN_P (last))
32181         {
32182           rtx patt = PATTERN (last);
32183
32184           if (GET_CODE (patt) == SET)
32185             {
32186               rtx lhs = XEXP (patt, 0);
32187
32188               if (REG_P (lhs) && REGNO (lhs) == STATIC_CHAIN_REGNUM)
32189                 return true;
32190             }
32191         }
32192     }
32193   return false;
32194 }
32195
32196 /* Expand code to perform a call under the AIX or ELFv2 ABI.  */
32197
32198 void
32199 rs6000_call_aix (rtx value, rtx func_desc, rtx tlsarg, rtx cookie)
32200 {
32201   rtx func = func_desc;
32202   rtx toc_reg = gen_rtx_REG (Pmode, TOC_REGNUM);
32203   rtx toc_load = NULL_RTX;
32204   rtx toc_restore = NULL_RTX;
32205   rtx func_addr;
32206   rtx abi_reg = NULL_RTX;
32207   rtx call[4];
32208   int n_call;
32209   rtx insn;
32210   bool is_pltseq_longcall;
32211
32212   if (global_tlsarg)
32213     tlsarg = global_tlsarg;
32214
32215   /* Handle longcall attributes.  */
32216   is_pltseq_longcall = false;
32217   if ((INTVAL (cookie) & CALL_LONG) != 0
32218       && GET_CODE (func_desc) == SYMBOL_REF)
32219     {
32220       func = rs6000_longcall_ref (func_desc, tlsarg);
32221       if (TARGET_PLTSEQ)
32222         is_pltseq_longcall = true;
32223     }
32224
32225   /* Handle indirect calls.  */
32226   if (!SYMBOL_REF_P (func)
32227       || (DEFAULT_ABI == ABI_AIX && !SYMBOL_REF_FUNCTION_P (func)))
32228     {
32229       if (!rs6000_pcrel_p (cfun))
32230         {
32231           /* Save the TOC into its reserved slot before the call,
32232              and prepare to restore it after the call.  */
32233           rtx stack_toc_offset = GEN_INT (RS6000_TOC_SAVE_SLOT);
32234           rtx stack_toc_unspec = gen_rtx_UNSPEC (Pmode,
32235                                                  gen_rtvec (1, stack_toc_offset),
32236                                                  UNSPEC_TOCSLOT);
32237           toc_restore = gen_rtx_SET (toc_reg, stack_toc_unspec);
32238
32239           /* Can we optimize saving the TOC in the prologue or
32240              do we need to do it at every call?  */
32241           if (TARGET_SAVE_TOC_INDIRECT && !cfun->calls_alloca)
32242             cfun->machine->save_toc_in_prologue = true;
32243           else
32244             {
32245               rtx stack_ptr = gen_rtx_REG (Pmode, STACK_POINTER_REGNUM);
32246               rtx stack_toc_mem = gen_frame_mem (Pmode,
32247                                                  gen_rtx_PLUS (Pmode, stack_ptr,
32248                                                                stack_toc_offset));
32249               MEM_VOLATILE_P (stack_toc_mem) = 1;
32250               if (is_pltseq_longcall)
32251                 {
32252                   rtvec v = gen_rtvec (3, toc_reg, func_desc, tlsarg);
32253                   rtx mark_toc_reg = gen_rtx_UNSPEC (Pmode, v, UNSPEC_PLTSEQ);
32254                   emit_insn (gen_rtx_SET (stack_toc_mem, mark_toc_reg));
32255                 }
32256               else
32257                 emit_move_insn (stack_toc_mem, toc_reg);
32258             }
32259         }
32260
32261       if (DEFAULT_ABI == ABI_ELFv2)
32262         {
32263           /* A function pointer in the ELFv2 ABI is just a plain address, but
32264              the ABI requires it to be loaded into r12 before the call.  */
32265           func_addr = gen_rtx_REG (Pmode, 12);
32266           if (!rtx_equal_p (func_addr, func))
32267             emit_move_insn (func_addr, func);
32268           abi_reg = func_addr;
32269           /* Indirect calls via CTR are strongly preferred over indirect
32270              calls via LR, so move the address there.  Needed to mark
32271              this insn for linker plt sequence editing too.  */
32272           func_addr = gen_rtx_REG (Pmode, CTR_REGNO);
32273           if (is_pltseq_longcall)
32274             {
32275               rtvec v = gen_rtvec (3, abi_reg, func_desc, tlsarg);
32276               rtx mark_func = gen_rtx_UNSPEC (Pmode, v, UNSPEC_PLTSEQ);
32277               emit_insn (gen_rtx_SET (func_addr, mark_func));
32278               v = gen_rtvec (2, func_addr, func_desc);
32279               func_addr = gen_rtx_UNSPEC (Pmode, v, UNSPEC_PLTSEQ);
32280             }
32281           else
32282             emit_move_insn (func_addr, abi_reg);
32283         }
32284       else
32285         {
32286           /* A function pointer under AIX is a pointer to a data area whose
32287              first word contains the actual address of the function, whose
32288              second word contains a pointer to its TOC, and whose third word
32289              contains a value to place in the static chain register (r11).
32290              Note that if we load the static chain, our "trampoline" need
32291              not have any executable code.  */
32292
32293           /* Load up address of the actual function.  */
32294           func = force_reg (Pmode, func);
32295           func_addr = gen_reg_rtx (Pmode);
32296           emit_move_insn (func_addr, gen_rtx_MEM (Pmode, func));
32297
32298           /* Indirect calls via CTR are strongly preferred over indirect
32299              calls via LR, so move the address there.  */
32300           rtx ctr_reg = gen_rtx_REG (Pmode, CTR_REGNO);
32301           emit_move_insn (ctr_reg, func_addr);
32302           func_addr = ctr_reg;
32303
32304           /* Prepare to load the TOC of the called function.  Note that the
32305              TOC load must happen immediately before the actual call so
32306              that unwinding the TOC registers works correctly.  See the
32307              comment in frob_update_context.  */
32308           rtx func_toc_offset = GEN_INT (GET_MODE_SIZE (Pmode));
32309           rtx func_toc_mem = gen_rtx_MEM (Pmode,
32310                                           gen_rtx_PLUS (Pmode, func,
32311                                                         func_toc_offset));
32312           toc_load = gen_rtx_USE (VOIDmode, func_toc_mem);
32313
32314           /* If we have a static chain, load it up.  But, if the call was
32315              originally direct, the 3rd word has not been written since no
32316              trampoline has been built, so we ought not to load it, lest we
32317              override a static chain value.  */
32318           if (!(GET_CODE (func_desc) == SYMBOL_REF
32319                 && SYMBOL_REF_FUNCTION_P (func_desc))
32320               && TARGET_POINTERS_TO_NESTED_FUNCTIONS
32321               && !chain_already_loaded (get_current_sequence ()->next->last))
32322             {
32323               rtx sc_reg = gen_rtx_REG (Pmode, STATIC_CHAIN_REGNUM);
32324               rtx func_sc_offset = GEN_INT (2 * GET_MODE_SIZE (Pmode));
32325               rtx func_sc_mem = gen_rtx_MEM (Pmode,
32326                                              gen_rtx_PLUS (Pmode, func,
32327                                                            func_sc_offset));
32328               emit_move_insn (sc_reg, func_sc_mem);
32329               abi_reg = sc_reg;
32330             }
32331         }
32332     }
32333   else
32334     {
32335       /* No TOC register needed for calls from PC-relative callers.  */
32336       if (!rs6000_pcrel_p (cfun))
32337         /* Direct calls use the TOC: for local calls, the callee will
32338            assume the TOC register is set; for non-local calls, the
32339            PLT stub needs the TOC register.  */
32340         abi_reg = toc_reg;
32341       func_addr = func;
32342     }
32343
32344   /* Create the call.  */
32345   call[0] = gen_rtx_CALL (VOIDmode, gen_rtx_MEM (SImode, func_addr), tlsarg);
32346   if (value != NULL_RTX)
32347     call[0] = gen_rtx_SET (value, call[0]);
32348   n_call = 1;
32349
32350   if (toc_load)
32351     call[n_call++] = toc_load;
32352   if (toc_restore)
32353     call[n_call++] = toc_restore;
32354
32355   call[n_call++] = gen_hard_reg_clobber (Pmode, LR_REGNO);
32356
32357   insn = gen_rtx_PARALLEL (VOIDmode, gen_rtvec_v (n_call, call));
32358   insn = emit_call_insn (insn);
32359
32360   /* Mention all registers defined by the ABI to hold information
32361      as uses in CALL_INSN_FUNCTION_USAGE.  */
32362   if (abi_reg)
32363     use_reg (&CALL_INSN_FUNCTION_USAGE (insn), abi_reg);
32364 }
32365
32366 /* Expand code to perform a sibling call under the AIX or ELFv2 ABI.  */
32367
32368 void
32369 rs6000_sibcall_aix (rtx value, rtx func_desc, rtx tlsarg, rtx cookie)
32370 {
32371   rtx call[2];
32372   rtx insn;
32373
32374   gcc_assert (INTVAL (cookie) == 0);
32375
32376   if (global_tlsarg)
32377     tlsarg = global_tlsarg;
32378
32379   /* Create the call.  */
32380   call[0] = gen_rtx_CALL (VOIDmode, gen_rtx_MEM (SImode, func_desc), tlsarg);
32381   if (value != NULL_RTX)
32382     call[0] = gen_rtx_SET (value, call[0]);
32383
32384   call[1] = simple_return_rtx;
32385
32386   insn = gen_rtx_PARALLEL (VOIDmode, gen_rtvec_v (2, call));
32387   insn = emit_call_insn (insn);
32388
32389   /* Note use of the TOC register.  */
32390   if (!rs6000_pcrel_p (cfun))
32391     use_reg (&CALL_INSN_FUNCTION_USAGE (insn),
32392              gen_rtx_REG (Pmode, TOC_REGNUM));
32393 }
32394
32395 /* Expand code to perform a call under the SYSV4 ABI.  */
32396
32397 void
32398 rs6000_call_sysv (rtx value, rtx func_desc, rtx tlsarg, rtx cookie)
32399 {
32400   rtx func = func_desc;
32401   rtx func_addr;
32402   rtx call[4];
32403   rtx insn;
32404   rtx abi_reg = NULL_RTX;
32405   int n;
32406
32407   if (global_tlsarg)
32408     tlsarg = global_tlsarg;
32409
32410   /* Handle longcall attributes.  */
32411   if ((INTVAL (cookie) & CALL_LONG) != 0
32412       && GET_CODE (func_desc) == SYMBOL_REF)
32413     {
32414       func = rs6000_longcall_ref (func_desc, tlsarg);
32415       /* If the longcall was implemented as an inline PLT call using
32416          PLT unspecs then func will be REG:r11.  If not, func will be
32417          a pseudo reg.  The inline PLT call sequence supports lazy
32418          linking (and longcalls to functions in dlopen'd libraries).
32419          The other style of longcalls don't.  The lazy linking entry
32420          to the dynamic symbol resolver requires r11 be the function
32421          address (as it is for linker generated PLT stubs).  Ensure
32422          r11 stays valid to the bctrl by marking r11 used by the call.  */
32423       if (TARGET_PLTSEQ)
32424         abi_reg = func;
32425     }
32426
32427   /* Handle indirect calls.  */
32428   if (GET_CODE (func) != SYMBOL_REF)
32429     {
32430       func = force_reg (Pmode, func);
32431
32432       /* Indirect calls via CTR are strongly preferred over indirect
32433          calls via LR, so move the address there.  That can't be left
32434          to reload because we want to mark every instruction in an
32435          inline PLT call sequence with a reloc, enabling the linker to
32436          edit the sequence back to a direct call when that makes sense.  */
32437       func_addr = gen_rtx_REG (Pmode, CTR_REGNO);
32438       if (abi_reg)
32439         {
32440           rtvec v = gen_rtvec (3, func, func_desc, tlsarg);
32441           rtx mark_func = gen_rtx_UNSPEC (Pmode, v, UNSPEC_PLTSEQ);
32442           emit_insn (gen_rtx_SET (func_addr, mark_func));
32443           v = gen_rtvec (2, func_addr, func_desc);
32444           func_addr = gen_rtx_UNSPEC (Pmode, v, UNSPEC_PLTSEQ);
32445         }
32446       else
32447         emit_move_insn (func_addr, func);
32448     }
32449   else
32450     func_addr = func;
32451
32452   /* Create the call.  */
32453   call[0] = gen_rtx_CALL (VOIDmode, gen_rtx_MEM (SImode, func_addr), tlsarg);
32454   if (value != NULL_RTX)
32455     call[0] = gen_rtx_SET (value, call[0]);
32456
32457   call[1] = gen_rtx_USE (VOIDmode, cookie);
32458   n = 2;
32459   if (TARGET_SECURE_PLT
32460       && flag_pic
32461       && GET_CODE (func_addr) == SYMBOL_REF
32462       && !SYMBOL_REF_LOCAL_P (func_addr))
32463     call[n++] = gen_rtx_USE (VOIDmode, pic_offset_table_rtx);
32464
32465   call[n++] = gen_hard_reg_clobber (Pmode, LR_REGNO);
32466
32467   insn = gen_rtx_PARALLEL (VOIDmode, gen_rtvec_v (n, call));
32468   insn = emit_call_insn (insn);
32469   if (abi_reg)
32470     use_reg (&CALL_INSN_FUNCTION_USAGE (insn), abi_reg);
32471 }
32472
32473 /* Expand code to perform a sibling call under the SysV4 ABI.  */
32474
32475 void
32476 rs6000_sibcall_sysv (rtx value, rtx func_desc, rtx tlsarg, rtx cookie)
32477 {
32478   rtx func = func_desc;
32479   rtx func_addr;
32480   rtx call[3];
32481   rtx insn;
32482   rtx abi_reg = NULL_RTX;
32483
32484   if (global_tlsarg)
32485     tlsarg = global_tlsarg;
32486
32487   /* Handle longcall attributes.  */
32488   if ((INTVAL (cookie) & CALL_LONG) != 0
32489       && GET_CODE (func_desc) == SYMBOL_REF)
32490     {
32491       func = rs6000_longcall_ref (func_desc, tlsarg);
32492       /* If the longcall was implemented as an inline PLT call using
32493          PLT unspecs then func will be REG:r11.  If not, func will be
32494          a pseudo reg.  The inline PLT call sequence supports lazy
32495          linking (and longcalls to functions in dlopen'd libraries).
32496          The other style of longcalls don't.  The lazy linking entry
32497          to the dynamic symbol resolver requires r11 be the function
32498          address (as it is for linker generated PLT stubs).  Ensure
32499          r11 stays valid to the bctr by marking r11 used by the call.  */
32500       if (TARGET_PLTSEQ)
32501         abi_reg = func;
32502     }
32503
32504   /* Handle indirect calls.  */
32505   if (GET_CODE (func) != SYMBOL_REF)
32506     {
32507       func = force_reg (Pmode, func);
32508
32509       /* Indirect sibcalls must go via CTR.  That can't be left to
32510          reload because we want to mark every instruction in an inline
32511          PLT call sequence with a reloc, enabling the linker to edit
32512          the sequence back to a direct call when that makes sense.  */
32513       func_addr = gen_rtx_REG (Pmode, CTR_REGNO);
32514       if (abi_reg)
32515         {
32516           rtvec v = gen_rtvec (3, func, func_desc, tlsarg);
32517           rtx mark_func = gen_rtx_UNSPEC (Pmode, v, UNSPEC_PLTSEQ);
32518           emit_insn (gen_rtx_SET (func_addr, mark_func));
32519           v = gen_rtvec (2, func_addr, func_desc);
32520           func_addr = gen_rtx_UNSPEC (Pmode, v, UNSPEC_PLTSEQ);
32521         }
32522       else
32523         emit_move_insn (func_addr, func);
32524     }
32525   else
32526     func_addr = func;
32527
32528   /* Create the call.  */
32529   call[0] = gen_rtx_CALL (VOIDmode, gen_rtx_MEM (SImode, func_addr), tlsarg);
32530   if (value != NULL_RTX)
32531     call[0] = gen_rtx_SET (value, call[0]);
32532
32533   call[1] = gen_rtx_USE (VOIDmode, cookie);
32534   call[2] = simple_return_rtx;
32535
32536   insn = gen_rtx_PARALLEL (VOIDmode, gen_rtvec_v (3, call));
32537   insn = emit_call_insn (insn);
32538   if (abi_reg)
32539     use_reg (&CALL_INSN_FUNCTION_USAGE (insn), abi_reg);
32540 }
32541
32542 #if TARGET_MACHO
32543
32544 /* Expand code to perform a call under the Darwin ABI.
32545    Modulo handling of mlongcall, this is much the same as sysv.
32546    if/when the longcall optimisation is removed, we could drop this
32547    code and use the sysv case (taking care to avoid the tls stuff).
32548
32549    We can use this for sibcalls too, if needed.  */
32550
32551 void
32552 rs6000_call_darwin_1 (rtx value, rtx func_desc, rtx tlsarg,
32553                       rtx cookie, bool sibcall)
32554 {
32555   rtx func = func_desc;
32556   rtx func_addr;
32557   rtx call[3];
32558   rtx insn;
32559   int cookie_val = INTVAL (cookie);
32560   bool make_island = false;
32561
32562   /* Handle longcall attributes, there are two cases for Darwin:
32563      1) Newer linkers are capable of synthesising any branch islands needed.
32564      2) We need a helper branch island synthesised by the compiler.
32565      The second case has mostly been retired and we don't use it for m64.
32566      In fact, it's is an optimisation, we could just indirect as sysv does..
32567      ... however, backwards compatibility for now.
32568      If we're going to use this, then we need to keep the CALL_LONG bit set,
32569      so that we can pick up the special insn form later.  */
32570   if ((cookie_val & CALL_LONG) != 0
32571       && GET_CODE (func_desc) == SYMBOL_REF)
32572     {
32573       /* FIXME: the longcall opt should not hang off picsymbol stubs.  */
32574       if (darwin_picsymbol_stubs && TARGET_32BIT)
32575         make_island = true; /* Do nothing yet, retain the CALL_LONG flag.  */
32576       else
32577         {
32578           /* The linker is capable of doing this, but the user explicitly
32579              asked for -mlongcall, so we'll do the 'normal' version.  */
32580           func = rs6000_longcall_ref (func_desc, NULL_RTX);
32581           cookie_val &= ~CALL_LONG; /* Handled, zap it.  */
32582         }
32583     }
32584
32585   /* Handle indirect calls.  */
32586   if (GET_CODE (func) != SYMBOL_REF)
32587     {
32588       func = force_reg (Pmode, func);
32589
32590       /* Indirect calls via CTR are strongly preferred over indirect
32591          calls via LR, and are required for indirect sibcalls, so move
32592          the address there.   */
32593       func_addr = gen_rtx_REG (Pmode, CTR_REGNO);
32594       emit_move_insn (func_addr, func);
32595     }
32596   else
32597     func_addr = func;
32598
32599   /* Create the call.  */
32600   call[0] = gen_rtx_CALL (VOIDmode, gen_rtx_MEM (SImode, func_addr), tlsarg);
32601   if (value != NULL_RTX)
32602     call[0] = gen_rtx_SET (value, call[0]);
32603
32604   call[1] = gen_rtx_USE (VOIDmode, GEN_INT (cookie_val));
32605
32606   if (sibcall)
32607     call[2] = simple_return_rtx;
32608   else
32609     call[2] = gen_hard_reg_clobber (Pmode, LR_REGNO);
32610
32611   insn = gen_rtx_PARALLEL (VOIDmode, gen_rtvec_v (3, call));
32612   insn = emit_call_insn (insn);
32613   /* Now we have the debug info in the insn, we can set up the branch island
32614      if we're using one.  */
32615   if (make_island)
32616     {
32617       tree funname = get_identifier (XSTR (func_desc, 0));
32618
32619       if (no_previous_def (funname))
32620         {
32621           rtx label_rtx = gen_label_rtx ();
32622           char *label_buf, temp_buf[256];
32623           ASM_GENERATE_INTERNAL_LABEL (temp_buf, "L",
32624                                        CODE_LABEL_NUMBER (label_rtx));
32625           label_buf = temp_buf[0] == '*' ? temp_buf + 1 : temp_buf;
32626           tree labelname = get_identifier (label_buf);
32627           add_compiler_branch_island (labelname, funname,
32628                                      insn_line ((const rtx_insn*)insn));
32629         }
32630      }
32631 }
32632 #endif
32633
32634 void
32635 rs6000_call_darwin (rtx value ATTRIBUTE_UNUSED, rtx func_desc ATTRIBUTE_UNUSED,
32636                     rtx tlsarg ATTRIBUTE_UNUSED, rtx cookie ATTRIBUTE_UNUSED)
32637 {
32638 #if TARGET_MACHO
32639   rs6000_call_darwin_1 (value, func_desc, tlsarg, cookie, false);
32640 #else
32641   gcc_unreachable();
32642 #endif
32643 }
32644
32645
32646 void
32647 rs6000_sibcall_darwin (rtx value ATTRIBUTE_UNUSED, rtx func_desc ATTRIBUTE_UNUSED,
32648                        rtx tlsarg ATTRIBUTE_UNUSED, rtx cookie ATTRIBUTE_UNUSED)
32649 {
32650 #if TARGET_MACHO
32651   rs6000_call_darwin_1 (value, func_desc, tlsarg, cookie, true);
32652 #else
32653   gcc_unreachable();
32654 #endif
32655 }
32656
32657 /* Return whether we should generate PC-relative code for FNDECL.  */
32658 bool
32659 rs6000_fndecl_pcrel_p (const_tree fndecl)
32660 {
32661   if (DEFAULT_ABI != ABI_ELFv2)
32662     return false;
32663
32664   struct cl_target_option *opts = target_opts_for_fn (fndecl);
32665
32666   return ((opts->x_rs6000_isa_flags & OPTION_MASK_PCREL) != 0
32667           && TARGET_CMODEL == CMODEL_MEDIUM);
32668 }
32669
32670 /* Return whether we should generate PC-relative code for *FN.  */
32671 bool
32672 rs6000_pcrel_p (struct function *fn)
32673 {
32674   if (DEFAULT_ABI != ABI_ELFv2)
32675     return false;
32676
32677   /* Optimize usual case.  */
32678   if (fn == cfun)
32679     return ((rs6000_isa_flags & OPTION_MASK_PCREL) != 0
32680             && TARGET_CMODEL == CMODEL_MEDIUM);
32681
32682   return rs6000_fndecl_pcrel_p (fn->decl);
32683 }
32684
32685 #ifdef HAVE_GAS_HIDDEN
32686 # define USE_HIDDEN_LINKONCE 1
32687 #else
32688 # define USE_HIDDEN_LINKONCE 0
32689 #endif
32690
32691 /* Fills in the label name that should be used for a 476 link stack thunk.  */
32692
32693 void
32694 get_ppc476_thunk_name (char name[32])
32695 {
32696   gcc_assert (TARGET_LINK_STACK);
32697
32698   if (USE_HIDDEN_LINKONCE)
32699     sprintf (name, "__ppc476.get_thunk");
32700   else
32701     ASM_GENERATE_INTERNAL_LABEL (name, "LPPC476_", 0);
32702 }
32703
32704 /* This function emits the simple thunk routine that is used to preserve
32705    the link stack on the 476 cpu.  */
32706
32707 static void rs6000_code_end (void) ATTRIBUTE_UNUSED;
32708 static void
32709 rs6000_code_end (void)
32710 {
32711   char name[32];
32712   tree decl;
32713
32714   if (!TARGET_LINK_STACK)
32715     return;
32716
32717   get_ppc476_thunk_name (name);
32718
32719   decl = build_decl (BUILTINS_LOCATION, FUNCTION_DECL, get_identifier (name),
32720                      build_function_type_list (void_type_node, NULL_TREE));
32721   DECL_RESULT (decl) = build_decl (BUILTINS_LOCATION, RESULT_DECL,
32722                                    NULL_TREE, void_type_node);
32723   TREE_PUBLIC (decl) = 1;
32724   TREE_STATIC (decl) = 1;
32725
32726 #if RS6000_WEAK
32727   if (USE_HIDDEN_LINKONCE && !TARGET_XCOFF)
32728     {
32729       cgraph_node::create (decl)->set_comdat_group (DECL_ASSEMBLER_NAME (decl));
32730       targetm.asm_out.unique_section (decl, 0);
32731       switch_to_section (get_named_section (decl, NULL, 0));
32732       DECL_WEAK (decl) = 1;
32733       ASM_WEAKEN_DECL (asm_out_file, decl, name, 0);
32734       targetm.asm_out.globalize_label (asm_out_file, name);
32735       targetm.asm_out.assemble_visibility (decl, VISIBILITY_HIDDEN);
32736       ASM_DECLARE_FUNCTION_NAME (asm_out_file, name, decl);
32737     }
32738   else
32739 #endif
32740     {
32741       switch_to_section (text_section);
32742       ASM_OUTPUT_LABEL (asm_out_file, name);
32743     }
32744
32745   DECL_INITIAL (decl) = make_node (BLOCK);
32746   current_function_decl = decl;
32747   allocate_struct_function (decl, false);
32748   init_function_start (decl);
32749   first_function_block_is_cold = false;
32750   /* Make sure unwind info is emitted for the thunk if needed.  */
32751   final_start_function (emit_barrier (), asm_out_file, 1);
32752
32753   fputs ("\tblr\n", asm_out_file);
32754
32755   final_end_function ();
32756   init_insn_lengths ();
32757   free_after_compilation (cfun);
32758   set_cfun (NULL);
32759   current_function_decl = NULL;
32760 }
32761
32762 /* Add r30 to hard reg set if the prologue sets it up and it is not
32763    pic_offset_table_rtx.  */
32764
32765 static void
32766 rs6000_set_up_by_prologue (struct hard_reg_set_container *set)
32767 {
32768   if (!TARGET_SINGLE_PIC_BASE
32769       && TARGET_TOC
32770       && TARGET_MINIMAL_TOC
32771       && !constant_pool_empty_p ())
32772     add_to_hard_reg_set (&set->set, Pmode, RS6000_PIC_OFFSET_TABLE_REGNUM);
32773   if (cfun->machine->split_stack_argp_used)
32774     add_to_hard_reg_set (&set->set, Pmode, 12);
32775
32776   /* Make sure the hard reg set doesn't include r2, which was possibly added
32777      via PIC_OFFSET_TABLE_REGNUM.  */
32778   if (TARGET_TOC)
32779     remove_from_hard_reg_set (&set->set, Pmode, TOC_REGNUM);
32780 }
32781
32782 \f
32783 /* Helper function for rs6000_split_logical to emit a logical instruction after
32784    spliting the operation to single GPR registers.
32785
32786    DEST is the destination register.
32787    OP1 and OP2 are the input source registers.
32788    CODE is the base operation (AND, IOR, XOR, NOT).
32789    MODE is the machine mode.
32790    If COMPLEMENT_FINAL_P is true, wrap the whole operation with NOT.
32791    If COMPLEMENT_OP1_P is true, wrap operand1 with NOT.
32792    If COMPLEMENT_OP2_P is true, wrap operand2 with NOT.  */
32793
32794 static void
32795 rs6000_split_logical_inner (rtx dest,
32796                             rtx op1,
32797                             rtx op2,
32798                             enum rtx_code code,
32799                             machine_mode mode,
32800                             bool complement_final_p,
32801                             bool complement_op1_p,
32802                             bool complement_op2_p)
32803 {
32804   rtx bool_rtx;
32805
32806   /* Optimize AND of 0/0xffffffff and IOR/XOR of 0.  */
32807   if (op2 && CONST_INT_P (op2)
32808       && (mode == SImode || (mode == DImode && TARGET_POWERPC64))
32809       && !complement_final_p && !complement_op1_p && !complement_op2_p)
32810     {
32811       HOST_WIDE_INT mask = GET_MODE_MASK (mode);
32812       HOST_WIDE_INT value = INTVAL (op2) & mask;
32813
32814       /* Optimize AND of 0 to just set 0.  Optimize AND of -1 to be a move.  */
32815       if (code == AND)
32816         {
32817           if (value == 0)
32818             {
32819               emit_insn (gen_rtx_SET (dest, const0_rtx));
32820               return;
32821             }
32822
32823           else if (value == mask)
32824             {
32825               if (!rtx_equal_p (dest, op1))
32826                 emit_insn (gen_rtx_SET (dest, op1));
32827               return;
32828             }
32829         }
32830
32831       /* Optimize IOR/XOR of 0 to be a simple move.  Split large operations
32832          into separate ORI/ORIS or XORI/XORIS instrucitons.  */
32833       else if (code == IOR || code == XOR)
32834         {
32835           if (value == 0)
32836             {
32837               if (!rtx_equal_p (dest, op1))
32838                 emit_insn (gen_rtx_SET (dest, op1));
32839               return;
32840             }
32841         }
32842     }
32843
32844   if (code == AND && mode == SImode
32845       && !complement_final_p && !complement_op1_p && !complement_op2_p)
32846     {
32847       emit_insn (gen_andsi3 (dest, op1, op2));
32848       return;
32849     }
32850
32851   if (complement_op1_p)
32852     op1 = gen_rtx_NOT (mode, op1);
32853
32854   if (complement_op2_p)
32855     op2 = gen_rtx_NOT (mode, op2);
32856
32857   /* For canonical RTL, if only one arm is inverted it is the first.  */
32858   if (!complement_op1_p && complement_op2_p)
32859     std::swap (op1, op2);
32860
32861   bool_rtx = ((code == NOT)
32862               ? gen_rtx_NOT (mode, op1)
32863               : gen_rtx_fmt_ee (code, mode, op1, op2));
32864
32865   if (complement_final_p)
32866     bool_rtx = gen_rtx_NOT (mode, bool_rtx);
32867
32868   emit_insn (gen_rtx_SET (dest, bool_rtx));
32869 }
32870
32871 /* Split a DImode AND/IOR/XOR with a constant on a 32-bit system.  These
32872    operations are split immediately during RTL generation to allow for more
32873    optimizations of the AND/IOR/XOR.
32874
32875    OPERANDS is an array containing the destination and two input operands.
32876    CODE is the base operation (AND, IOR, XOR, NOT).
32877    MODE is the machine mode.
32878    If COMPLEMENT_FINAL_P is true, wrap the whole operation with NOT.
32879    If COMPLEMENT_OP1_P is true, wrap operand1 with NOT.
32880    If COMPLEMENT_OP2_P is true, wrap operand2 with NOT.
32881    CLOBBER_REG is either NULL or a scratch register of type CC to allow
32882    formation of the AND instructions.  */
32883
32884 static void
32885 rs6000_split_logical_di (rtx operands[3],
32886                          enum rtx_code code,
32887                          bool complement_final_p,
32888                          bool complement_op1_p,
32889                          bool complement_op2_p)
32890 {
32891   const HOST_WIDE_INT lower_32bits = HOST_WIDE_INT_C(0xffffffff);
32892   const HOST_WIDE_INT upper_32bits = ~ lower_32bits;
32893   const HOST_WIDE_INT sign_bit = HOST_WIDE_INT_C(0x80000000);
32894   enum hi_lo { hi = 0, lo = 1 };
32895   rtx op0_hi_lo[2], op1_hi_lo[2], op2_hi_lo[2];
32896   size_t i;
32897
32898   op0_hi_lo[hi] = gen_highpart (SImode, operands[0]);
32899   op1_hi_lo[hi] = gen_highpart (SImode, operands[1]);
32900   op0_hi_lo[lo] = gen_lowpart (SImode, operands[0]);
32901   op1_hi_lo[lo] = gen_lowpart (SImode, operands[1]);
32902
32903   if (code == NOT)
32904     op2_hi_lo[hi] = op2_hi_lo[lo] = NULL_RTX;
32905   else
32906     {
32907       if (!CONST_INT_P (operands[2]))
32908         {
32909           op2_hi_lo[hi] = gen_highpart_mode (SImode, DImode, operands[2]);
32910           op2_hi_lo[lo] = gen_lowpart (SImode, operands[2]);
32911         }
32912       else
32913         {
32914           HOST_WIDE_INT value = INTVAL (operands[2]);
32915           HOST_WIDE_INT value_hi_lo[2];
32916
32917           gcc_assert (!complement_final_p);
32918           gcc_assert (!complement_op1_p);
32919           gcc_assert (!complement_op2_p);
32920
32921           value_hi_lo[hi] = value >> 32;
32922           value_hi_lo[lo] = value & lower_32bits;
32923
32924           for (i = 0; i < 2; i++)
32925             {
32926               HOST_WIDE_INT sub_value = value_hi_lo[i];
32927
32928               if (sub_value & sign_bit)
32929                 sub_value |= upper_32bits;
32930
32931               op2_hi_lo[i] = GEN_INT (sub_value);
32932
32933               /* If this is an AND instruction, check to see if we need to load
32934                  the value in a register.  */
32935               if (code == AND && sub_value != -1 && sub_value != 0
32936                   && !and_operand (op2_hi_lo[i], SImode))
32937                 op2_hi_lo[i] = force_reg (SImode, op2_hi_lo[i]);
32938             }
32939         }
32940     }
32941
32942   for (i = 0; i < 2; i++)
32943     {
32944       /* Split large IOR/XOR operations.  */
32945       if ((code == IOR || code == XOR)
32946           && CONST_INT_P (op2_hi_lo[i])
32947           && !complement_final_p
32948           && !complement_op1_p
32949           && !complement_op2_p
32950           && !logical_const_operand (op2_hi_lo[i], SImode))
32951         {
32952           HOST_WIDE_INT value = INTVAL (op2_hi_lo[i]);
32953           HOST_WIDE_INT hi_16bits = value & HOST_WIDE_INT_C(0xffff0000);
32954           HOST_WIDE_INT lo_16bits = value & HOST_WIDE_INT_C(0x0000ffff);
32955           rtx tmp = gen_reg_rtx (SImode);
32956
32957           /* Make sure the constant is sign extended.  */
32958           if ((hi_16bits & sign_bit) != 0)
32959             hi_16bits |= upper_32bits;
32960
32961           rs6000_split_logical_inner (tmp, op1_hi_lo[i], GEN_INT (hi_16bits),
32962                                       code, SImode, false, false, false);
32963
32964           rs6000_split_logical_inner (op0_hi_lo[i], tmp, GEN_INT (lo_16bits),
32965                                       code, SImode, false, false, false);
32966         }
32967       else
32968         rs6000_split_logical_inner (op0_hi_lo[i], op1_hi_lo[i], op2_hi_lo[i],
32969                                     code, SImode, complement_final_p,
32970                                     complement_op1_p, complement_op2_p);
32971     }
32972
32973   return;
32974 }
32975
32976 /* Split the insns that make up boolean operations operating on multiple GPR
32977    registers.  The boolean MD patterns ensure that the inputs either are
32978    exactly the same as the output registers, or there is no overlap.
32979
32980    OPERANDS is an array containing the destination and two input operands.
32981    CODE is the base operation (AND, IOR, XOR, NOT).
32982    If COMPLEMENT_FINAL_P is true, wrap the whole operation with NOT.
32983    If COMPLEMENT_OP1_P is true, wrap operand1 with NOT.
32984    If COMPLEMENT_OP2_P is true, wrap operand2 with NOT.  */
32985
32986 void
32987 rs6000_split_logical (rtx operands[3],
32988                       enum rtx_code code,
32989                       bool complement_final_p,
32990                       bool complement_op1_p,
32991                       bool complement_op2_p)
32992 {
32993   machine_mode mode = GET_MODE (operands[0]);
32994   machine_mode sub_mode;
32995   rtx op0, op1, op2;
32996   int sub_size, regno0, regno1, nregs, i;
32997
32998   /* If this is DImode, use the specialized version that can run before
32999      register allocation.  */
33000   if (mode == DImode && !TARGET_POWERPC64)
33001     {
33002       rs6000_split_logical_di (operands, code, complement_final_p,
33003                                complement_op1_p, complement_op2_p);
33004       return;
33005     }
33006
33007   op0 = operands[0];
33008   op1 = operands[1];
33009   op2 = (code == NOT) ? NULL_RTX : operands[2];
33010   sub_mode = (TARGET_POWERPC64) ? DImode : SImode;
33011   sub_size = GET_MODE_SIZE (sub_mode);
33012   regno0 = REGNO (op0);
33013   regno1 = REGNO (op1);
33014
33015   gcc_assert (reload_completed);
33016   gcc_assert (IN_RANGE (regno0, FIRST_GPR_REGNO, LAST_GPR_REGNO));
33017   gcc_assert (IN_RANGE (regno1, FIRST_GPR_REGNO, LAST_GPR_REGNO));
33018
33019   nregs = rs6000_hard_regno_nregs[(int)mode][regno0];
33020   gcc_assert (nregs > 1);
33021
33022   if (op2 && REG_P (op2))
33023     gcc_assert (IN_RANGE (REGNO (op2), FIRST_GPR_REGNO, LAST_GPR_REGNO));
33024
33025   for (i = 0; i < nregs; i++)
33026     {
33027       int offset = i * sub_size;
33028       rtx sub_op0 = simplify_subreg (sub_mode, op0, mode, offset);
33029       rtx sub_op1 = simplify_subreg (sub_mode, op1, mode, offset);
33030       rtx sub_op2 = ((code == NOT)
33031                      ? NULL_RTX
33032                      : simplify_subreg (sub_mode, op2, mode, offset));
33033
33034       rs6000_split_logical_inner (sub_op0, sub_op1, sub_op2, code, sub_mode,
33035                                   complement_final_p, complement_op1_p,
33036                                   complement_op2_p);
33037     }
33038
33039   return;
33040 }
33041
33042 \f
33043 /* Return true if the peephole2 can combine a load involving a combination of
33044    an addis instruction and a load with an offset that can be fused together on
33045    a power8.  */
33046
33047 bool
33048 fusion_gpr_load_p (rtx addis_reg,       /* register set via addis.  */
33049                    rtx addis_value,     /* addis value.  */
33050                    rtx target,          /* target register that is loaded.  */
33051                    rtx mem)             /* bottom part of the memory addr.  */
33052 {
33053   rtx addr;
33054   rtx base_reg;
33055
33056   /* Validate arguments.  */
33057   if (!base_reg_operand (addis_reg, GET_MODE (addis_reg)))
33058     return false;
33059
33060   if (!base_reg_operand (target, GET_MODE (target)))
33061     return false;
33062
33063   if (!fusion_gpr_addis (addis_value, GET_MODE (addis_value)))
33064     return false;
33065
33066   /* Allow sign/zero extension.  */
33067   if (GET_CODE (mem) == ZERO_EXTEND
33068       || (GET_CODE (mem) == SIGN_EXTEND && TARGET_P8_FUSION_SIGN))
33069     mem = XEXP (mem, 0);
33070
33071   if (!MEM_P (mem))
33072     return false;
33073
33074   if (!fusion_gpr_mem_load (mem, GET_MODE (mem)))
33075     return false;
33076
33077   addr = XEXP (mem, 0);                 /* either PLUS or LO_SUM.  */
33078   if (GET_CODE (addr) != PLUS && GET_CODE (addr) != LO_SUM)
33079     return false;
33080
33081   /* Validate that the register used to load the high value is either the
33082      register being loaded, or we can safely replace its use.
33083
33084      This function is only called from the peephole2 pass and we assume that
33085      there are 2 instructions in the peephole (addis and load), so we want to
33086      check if the target register was not used in the memory address and the
33087      register to hold the addis result is dead after the peephole.  */
33088   if (REGNO (addis_reg) != REGNO (target))
33089     {
33090       if (reg_mentioned_p (target, mem))
33091         return false;
33092
33093       if (!peep2_reg_dead_p (2, addis_reg))
33094         return false;
33095
33096       /* If the target register being loaded is the stack pointer, we must
33097          avoid loading any other value into it, even temporarily.  */
33098       if (REG_P (target) && REGNO (target) == STACK_POINTER_REGNUM)
33099         return false;
33100     }
33101
33102   base_reg = XEXP (addr, 0);
33103   return REGNO (addis_reg) == REGNO (base_reg);
33104 }
33105
33106 /* During the peephole2 pass, adjust and expand the insns for a load fusion
33107    sequence.  We adjust the addis register to use the target register.  If the
33108    load sign extends, we adjust the code to do the zero extending load, and an
33109    explicit sign extension later since the fusion only covers zero extending
33110    loads.
33111
33112    The operands are:
33113         operands[0]     register set with addis (to be replaced with target)
33114         operands[1]     value set via addis
33115         operands[2]     target register being loaded
33116         operands[3]     D-form memory reference using operands[0].  */
33117
33118 void
33119 expand_fusion_gpr_load (rtx *operands)
33120 {
33121   rtx addis_value = operands[1];
33122   rtx target = operands[2];
33123   rtx orig_mem = operands[3];
33124   rtx  new_addr, new_mem, orig_addr, offset;
33125   enum rtx_code plus_or_lo_sum;
33126   machine_mode target_mode = GET_MODE (target);
33127   machine_mode extend_mode = target_mode;
33128   machine_mode ptr_mode = Pmode;
33129   enum rtx_code extend = UNKNOWN;
33130
33131   if (GET_CODE (orig_mem) == ZERO_EXTEND
33132       || (TARGET_P8_FUSION_SIGN && GET_CODE (orig_mem) == SIGN_EXTEND))
33133     {
33134       extend = GET_CODE (orig_mem);
33135       orig_mem = XEXP (orig_mem, 0);
33136       target_mode = GET_MODE (orig_mem);
33137     }
33138
33139   gcc_assert (MEM_P (orig_mem));
33140
33141   orig_addr = XEXP (orig_mem, 0);
33142   plus_or_lo_sum = GET_CODE (orig_addr);
33143   gcc_assert (plus_or_lo_sum == PLUS || plus_or_lo_sum == LO_SUM);
33144
33145   offset = XEXP (orig_addr, 1);
33146   new_addr = gen_rtx_fmt_ee (plus_or_lo_sum, ptr_mode, addis_value, offset);
33147   new_mem = replace_equiv_address_nv (orig_mem, new_addr, false);
33148
33149   if (extend != UNKNOWN)
33150     new_mem = gen_rtx_fmt_e (ZERO_EXTEND, extend_mode, new_mem);
33151
33152   new_mem = gen_rtx_UNSPEC (extend_mode, gen_rtvec (1, new_mem),
33153                             UNSPEC_FUSION_GPR);
33154   emit_insn (gen_rtx_SET (target, new_mem));
33155
33156   if (extend == SIGN_EXTEND)
33157     {
33158       int sub_off = ((BYTES_BIG_ENDIAN)
33159                      ? GET_MODE_SIZE (extend_mode) - GET_MODE_SIZE (target_mode)
33160                      : 0);
33161       rtx sign_reg
33162         = simplify_subreg (target_mode, target, extend_mode, sub_off);
33163
33164       emit_insn (gen_rtx_SET (target,
33165                               gen_rtx_SIGN_EXTEND (extend_mode, sign_reg)));
33166     }
33167
33168   return;
33169 }
33170
33171 /* Emit the addis instruction that will be part of a fused instruction
33172    sequence.  */
33173
33174 void
33175 emit_fusion_addis (rtx target, rtx addis_value)
33176 {
33177   rtx fuse_ops[10];
33178   const char *addis_str = NULL;
33179
33180   /* Emit the addis instruction.  */
33181   fuse_ops[0] = target;
33182   if (satisfies_constraint_L (addis_value))
33183     {
33184       fuse_ops[1] = addis_value;
33185       addis_str = "lis %0,%v1";
33186     }
33187
33188   else if (GET_CODE (addis_value) == PLUS)
33189     {
33190       rtx op0 = XEXP (addis_value, 0);
33191       rtx op1 = XEXP (addis_value, 1);
33192
33193       if (REG_P (op0) && CONST_INT_P (op1)
33194           && satisfies_constraint_L (op1))
33195         {
33196           fuse_ops[1] = op0;
33197           fuse_ops[2] = op1;
33198           addis_str = "addis %0,%1,%v2";
33199         }
33200     }
33201
33202   else if (GET_CODE (addis_value) == HIGH)
33203     {
33204       rtx value = XEXP (addis_value, 0);
33205       if (GET_CODE (value) == UNSPEC && XINT (value, 1) == UNSPEC_TOCREL)
33206         {
33207           fuse_ops[1] = XVECEXP (value, 0, 0);          /* symbol ref.  */
33208           fuse_ops[2] = XVECEXP (value, 0, 1);          /* TOC register.  */
33209           if (TARGET_ELF)
33210             addis_str = "addis %0,%2,%1@toc@ha";
33211
33212           else if (TARGET_XCOFF)
33213             addis_str = "addis %0,%1@u(%2)";
33214
33215           else
33216             gcc_unreachable ();
33217         }
33218
33219       else if (GET_CODE (value) == PLUS)
33220         {
33221           rtx op0 = XEXP (value, 0);
33222           rtx op1 = XEXP (value, 1);
33223
33224           if (GET_CODE (op0) == UNSPEC
33225               && XINT (op0, 1) == UNSPEC_TOCREL
33226               && CONST_INT_P (op1))
33227             {
33228               fuse_ops[1] = XVECEXP (op0, 0, 0);        /* symbol ref.  */
33229               fuse_ops[2] = XVECEXP (op0, 0, 1);        /* TOC register.  */
33230               fuse_ops[3] = op1;
33231               if (TARGET_ELF)
33232                 addis_str = "addis %0,%2,%1+%3@toc@ha";
33233
33234               else if (TARGET_XCOFF)
33235                 addis_str = "addis %0,%1+%3@u(%2)";
33236
33237               else
33238                 gcc_unreachable ();
33239             }
33240         }
33241
33242       else if (satisfies_constraint_L (value))
33243         {
33244           fuse_ops[1] = value;
33245           addis_str = "lis %0,%v1";
33246         }
33247
33248       else if (TARGET_ELF && !TARGET_POWERPC64 && CONSTANT_P (value))
33249         {
33250           fuse_ops[1] = value;
33251           addis_str = "lis %0,%1@ha";
33252         }
33253     }
33254
33255   if (!addis_str)
33256     fatal_insn ("Could not generate addis value for fusion", addis_value);
33257
33258   output_asm_insn (addis_str, fuse_ops);
33259 }
33260
33261 /* Emit a D-form load or store instruction that is the second instruction
33262    of a fusion sequence.  */
33263
33264 static void
33265 emit_fusion_load (rtx load_reg, rtx addis_reg, rtx offset, const char *insn_str)
33266 {
33267   rtx fuse_ops[10];
33268   char insn_template[80];
33269
33270   fuse_ops[0] = load_reg;
33271   fuse_ops[1] = addis_reg;
33272
33273   if (CONST_INT_P (offset) && satisfies_constraint_I (offset))
33274     {
33275       sprintf (insn_template, "%s %%0,%%2(%%1)", insn_str);
33276       fuse_ops[2] = offset;
33277       output_asm_insn (insn_template, fuse_ops);
33278     }
33279
33280   else if (GET_CODE (offset) == UNSPEC
33281            && XINT (offset, 1) == UNSPEC_TOCREL)
33282     {
33283       if (TARGET_ELF)
33284         sprintf (insn_template, "%s %%0,%%2@toc@l(%%1)", insn_str);
33285
33286       else if (TARGET_XCOFF)
33287         sprintf (insn_template, "%s %%0,%%2@l(%%1)", insn_str);
33288
33289       else
33290         gcc_unreachable ();
33291
33292       fuse_ops[2] = XVECEXP (offset, 0, 0);
33293       output_asm_insn (insn_template, fuse_ops);
33294     }
33295
33296   else if (GET_CODE (offset) == PLUS
33297            && GET_CODE (XEXP (offset, 0)) == UNSPEC
33298            && XINT (XEXP (offset, 0), 1) == UNSPEC_TOCREL
33299            && CONST_INT_P (XEXP (offset, 1)))
33300     {
33301       rtx tocrel_unspec = XEXP (offset, 0);
33302       if (TARGET_ELF)
33303         sprintf (insn_template, "%s %%0,%%2+%%3@toc@l(%%1)", insn_str);
33304
33305       else if (TARGET_XCOFF)
33306         sprintf (insn_template, "%s %%0,%%2+%%3@l(%%1)", insn_str);
33307
33308       else
33309         gcc_unreachable ();
33310
33311       fuse_ops[2] = XVECEXP (tocrel_unspec, 0, 0);
33312       fuse_ops[3] = XEXP (offset, 1);
33313       output_asm_insn (insn_template, fuse_ops);
33314     }
33315
33316   else if (TARGET_ELF && !TARGET_POWERPC64 && CONSTANT_P (offset))
33317     {
33318       sprintf (insn_template, "%s %%0,%%2@l(%%1)", insn_str);
33319
33320       fuse_ops[2] = offset;
33321       output_asm_insn (insn_template, fuse_ops);
33322     }
33323
33324   else
33325     fatal_insn ("Unable to generate load/store offset for fusion", offset);
33326
33327   return;
33328 }
33329
33330 /* Given an address, convert it into the addis and load offset parts.  Addresses
33331    created during the peephole2 process look like:
33332         (lo_sum (high (unspec [(sym)] UNSPEC_TOCREL))
33333                 (unspec [(...)] UNSPEC_TOCREL))  */
33334
33335 static void
33336 fusion_split_address (rtx addr, rtx *p_hi, rtx *p_lo)
33337 {
33338   rtx hi, lo;
33339
33340   if (GET_CODE (addr) == PLUS || GET_CODE (addr) == LO_SUM)
33341     {
33342       hi = XEXP (addr, 0);
33343       lo = XEXP (addr, 1);
33344     }
33345   else
33346     gcc_unreachable ();
33347
33348   *p_hi = hi;
33349   *p_lo = lo;
33350 }
33351
33352 /* Return a string to fuse an addis instruction with a gpr load to the same
33353    register that we loaded up the addis instruction.  The address that is used
33354    is the logical address that was formed during peephole2:
33355         (lo_sum (high) (low-part))
33356
33357    The code is complicated, so we call output_asm_insn directly, and just
33358    return "".  */
33359
33360 const char *
33361 emit_fusion_gpr_load (rtx target, rtx mem)
33362 {
33363   rtx addis_value;
33364   rtx addr;
33365   rtx load_offset;
33366   const char *load_str = NULL;
33367   machine_mode mode;
33368
33369   if (GET_CODE (mem) == ZERO_EXTEND)
33370     mem = XEXP (mem, 0);
33371
33372   gcc_assert (REG_P (target) && MEM_P (mem));
33373
33374   addr = XEXP (mem, 0);
33375   fusion_split_address (addr, &addis_value, &load_offset);
33376
33377   /* Now emit the load instruction to the same register.  */
33378   mode = GET_MODE (mem);
33379   switch (mode)
33380     {
33381     case E_QImode:
33382       load_str = "lbz";
33383       break;
33384
33385     case E_HImode:
33386       load_str = "lhz";
33387       break;
33388
33389     case E_SImode:
33390     case E_SFmode:
33391       load_str = "lwz";
33392       break;
33393
33394     case E_DImode:
33395     case E_DFmode:
33396       gcc_assert (TARGET_POWERPC64);
33397       load_str = "ld";
33398       break;
33399
33400     default:
33401       fatal_insn ("Bad GPR fusion", gen_rtx_SET (target, mem));
33402     }
33403
33404   /* Emit the addis instruction.  */
33405   emit_fusion_addis (target, addis_value);
33406
33407   /* Emit the D-form load instruction.  */
33408   emit_fusion_load (target, target, load_offset, load_str);
33409
33410   return "";
33411 }
33412 \f
33413
33414 #ifdef RS6000_GLIBC_ATOMIC_FENV
33415 /* Function declarations for rs6000_atomic_assign_expand_fenv.  */
33416 static tree atomic_hold_decl, atomic_clear_decl, atomic_update_decl;
33417 #endif
33418
33419 /* Implement TARGET_ATOMIC_ASSIGN_EXPAND_FENV hook.  */
33420
33421 static void
33422 rs6000_atomic_assign_expand_fenv (tree *hold, tree *clear, tree *update)
33423 {
33424   if (!TARGET_HARD_FLOAT)
33425     {
33426 #ifdef RS6000_GLIBC_ATOMIC_FENV
33427       if (atomic_hold_decl == NULL_TREE)
33428         {
33429           atomic_hold_decl
33430             = build_decl (BUILTINS_LOCATION, FUNCTION_DECL,
33431                           get_identifier ("__atomic_feholdexcept"),
33432                           build_function_type_list (void_type_node,
33433                                                     double_ptr_type_node,
33434                                                     NULL_TREE));
33435           TREE_PUBLIC (atomic_hold_decl) = 1;
33436           DECL_EXTERNAL (atomic_hold_decl) = 1;
33437         }
33438
33439       if (atomic_clear_decl == NULL_TREE)
33440         {
33441           atomic_clear_decl
33442             = build_decl (BUILTINS_LOCATION, FUNCTION_DECL,
33443                           get_identifier ("__atomic_feclearexcept"),
33444                           build_function_type_list (void_type_node,
33445                                                     NULL_TREE));
33446           TREE_PUBLIC (atomic_clear_decl) = 1;
33447           DECL_EXTERNAL (atomic_clear_decl) = 1;
33448         }
33449
33450       tree const_double = build_qualified_type (double_type_node,
33451                                                 TYPE_QUAL_CONST);
33452       tree const_double_ptr = build_pointer_type (const_double);
33453       if (atomic_update_decl == NULL_TREE)
33454         {
33455           atomic_update_decl
33456             = build_decl (BUILTINS_LOCATION, FUNCTION_DECL,
33457                           get_identifier ("__atomic_feupdateenv"),
33458                           build_function_type_list (void_type_node,
33459                                                     const_double_ptr,
33460                                                     NULL_TREE));
33461           TREE_PUBLIC (atomic_update_decl) = 1;
33462           DECL_EXTERNAL (atomic_update_decl) = 1;
33463         }
33464
33465       tree fenv_var = create_tmp_var_raw (double_type_node);
33466       TREE_ADDRESSABLE (fenv_var) = 1;
33467       tree fenv_addr = build1 (ADDR_EXPR, double_ptr_type_node, fenv_var);
33468
33469       *hold = build_call_expr (atomic_hold_decl, 1, fenv_addr);
33470       *clear = build_call_expr (atomic_clear_decl, 0);
33471       *update = build_call_expr (atomic_update_decl, 1,
33472                                  fold_convert (const_double_ptr, fenv_addr));
33473 #endif
33474       return;
33475     }
33476
33477   tree mffs = rs6000_builtin_decls[RS6000_BUILTIN_MFFS];
33478   tree mtfsf = rs6000_builtin_decls[RS6000_BUILTIN_MTFSF];
33479   tree call_mffs = build_call_expr (mffs, 0);
33480
33481   /* Generates the equivalent of feholdexcept (&fenv_var)
33482
33483      *fenv_var = __builtin_mffs ();
33484      double fenv_hold;
33485      *(uint64_t*)&fenv_hold = *(uint64_t*)fenv_var & 0xffffffff00000007LL;
33486      __builtin_mtfsf (0xff, fenv_hold);  */
33487
33488   /* Mask to clear everything except for the rounding modes and non-IEEE
33489      arithmetic flag.  */
33490   const unsigned HOST_WIDE_INT hold_exception_mask =
33491     HOST_WIDE_INT_C (0xffffffff00000007);
33492
33493   tree fenv_var = create_tmp_var_raw (double_type_node);
33494
33495   tree hold_mffs = build2 (MODIFY_EXPR, void_type_node, fenv_var, call_mffs);
33496
33497   tree fenv_llu = build1 (VIEW_CONVERT_EXPR, uint64_type_node, fenv_var);
33498   tree fenv_llu_and = build2 (BIT_AND_EXPR, uint64_type_node, fenv_llu,
33499                               build_int_cst (uint64_type_node,
33500                                              hold_exception_mask));
33501
33502   tree fenv_hold_mtfsf = build1 (VIEW_CONVERT_EXPR, double_type_node,
33503                                  fenv_llu_and);
33504
33505   tree hold_mtfsf = build_call_expr (mtfsf, 2,
33506                                      build_int_cst (unsigned_type_node, 0xff),
33507                                      fenv_hold_mtfsf);
33508
33509   *hold = build2 (COMPOUND_EXPR, void_type_node, hold_mffs, hold_mtfsf);
33510
33511   /* Generates the equivalent of feclearexcept (FE_ALL_EXCEPT):
33512
33513      double fenv_clear = __builtin_mffs ();
33514      *(uint64_t)&fenv_clear &= 0xffffffff00000000LL;
33515      __builtin_mtfsf (0xff, fenv_clear);  */
33516
33517   /* Mask to clear everything except for the rounding modes and non-IEEE
33518      arithmetic flag.  */
33519   const unsigned HOST_WIDE_INT clear_exception_mask =
33520     HOST_WIDE_INT_C (0xffffffff00000000);
33521
33522   tree fenv_clear = create_tmp_var_raw (double_type_node);
33523
33524   tree clear_mffs = build2 (MODIFY_EXPR, void_type_node, fenv_clear, call_mffs);
33525
33526   tree fenv_clean_llu = build1 (VIEW_CONVERT_EXPR, uint64_type_node, fenv_clear);
33527   tree fenv_clear_llu_and = build2 (BIT_AND_EXPR, uint64_type_node,
33528                                     fenv_clean_llu,
33529                                     build_int_cst (uint64_type_node,
33530                                                    clear_exception_mask));
33531
33532   tree fenv_clear_mtfsf = build1 (VIEW_CONVERT_EXPR, double_type_node,
33533                                   fenv_clear_llu_and);
33534
33535   tree clear_mtfsf = build_call_expr (mtfsf, 2,
33536                                       build_int_cst (unsigned_type_node, 0xff),
33537                                       fenv_clear_mtfsf);
33538
33539   *clear = build2 (COMPOUND_EXPR, void_type_node, clear_mffs, clear_mtfsf);
33540
33541   /* Generates the equivalent of feupdateenv (&fenv_var)
33542
33543      double old_fenv = __builtin_mffs ();
33544      double fenv_update;
33545      *(uint64_t*)&fenv_update = (*(uint64_t*)&old & 0xffffffff1fffff00LL) |
33546                                 (*(uint64_t*)fenv_var 0x1ff80fff);
33547      __builtin_mtfsf (0xff, fenv_update);  */
33548
33549   const unsigned HOST_WIDE_INT update_exception_mask =
33550     HOST_WIDE_INT_C (0xffffffff1fffff00);
33551   const unsigned HOST_WIDE_INT new_exception_mask =
33552     HOST_WIDE_INT_C (0x1ff80fff);
33553
33554   tree old_fenv = create_tmp_var_raw (double_type_node);
33555   tree update_mffs = build2 (MODIFY_EXPR, void_type_node, old_fenv, call_mffs);
33556
33557   tree old_llu = build1 (VIEW_CONVERT_EXPR, uint64_type_node, old_fenv);
33558   tree old_llu_and = build2 (BIT_AND_EXPR, uint64_type_node, old_llu,
33559                              build_int_cst (uint64_type_node,
33560                                             update_exception_mask));
33561
33562   tree new_llu_and = build2 (BIT_AND_EXPR, uint64_type_node, fenv_llu,
33563                              build_int_cst (uint64_type_node,
33564                                             new_exception_mask));
33565
33566   tree new_llu_mask = build2 (BIT_IOR_EXPR, uint64_type_node,
33567                               old_llu_and, new_llu_and);
33568
33569   tree fenv_update_mtfsf = build1 (VIEW_CONVERT_EXPR, double_type_node,
33570                                    new_llu_mask);
33571
33572   tree update_mtfsf = build_call_expr (mtfsf, 2,
33573                                        build_int_cst (unsigned_type_node, 0xff),
33574                                        fenv_update_mtfsf);
33575
33576   *update = build2 (COMPOUND_EXPR, void_type_node, update_mffs, update_mtfsf);
33577 }
33578
33579 void
33580 rs6000_generate_float2_double_code (rtx dst, rtx src1, rtx src2)
33581 {
33582   rtx rtx_tmp0, rtx_tmp1, rtx_tmp2, rtx_tmp3;
33583
33584   rtx_tmp0 = gen_reg_rtx (V2DFmode);
33585   rtx_tmp1 = gen_reg_rtx (V2DFmode);
33586
33587   /* The destination of the vmrgew instruction layout is:
33588      rtx_tmp2[0] rtx_tmp3[0] rtx_tmp2[1] rtx_tmp3[0].
33589      Setup rtx_tmp0 and rtx_tmp1 to ensure the order of the elements after the
33590      vmrgew instruction will be correct.  */
33591   if (BYTES_BIG_ENDIAN)
33592     {
33593        emit_insn (gen_vsx_xxpermdi_v2df_be (rtx_tmp0, src1, src2,
33594                                             GEN_INT (0)));
33595        emit_insn (gen_vsx_xxpermdi_v2df_be (rtx_tmp1, src1, src2,
33596                                             GEN_INT (3)));
33597     }
33598   else
33599     {
33600        emit_insn (gen_vsx_xxpermdi_v2df (rtx_tmp0, src1, src2, GEN_INT (3)));
33601        emit_insn (gen_vsx_xxpermdi_v2df (rtx_tmp1, src1, src2, GEN_INT (0)));
33602     }
33603
33604   rtx_tmp2 = gen_reg_rtx (V4SFmode);
33605   rtx_tmp3 = gen_reg_rtx (V4SFmode);
33606
33607   emit_insn (gen_vsx_xvcdpsp (rtx_tmp2, rtx_tmp0));
33608   emit_insn (gen_vsx_xvcdpsp (rtx_tmp3, rtx_tmp1));
33609
33610   if (BYTES_BIG_ENDIAN)
33611     emit_insn (gen_p8_vmrgew_v4sf (dst, rtx_tmp2, rtx_tmp3));
33612   else
33613     emit_insn (gen_p8_vmrgew_v4sf (dst, rtx_tmp3, rtx_tmp2));
33614 }
33615
33616 void
33617 rs6000_generate_float2_code (bool signed_convert, rtx dst, rtx src1, rtx src2)
33618 {
33619   rtx rtx_tmp0, rtx_tmp1, rtx_tmp2, rtx_tmp3;
33620
33621   rtx_tmp0 = gen_reg_rtx (V2DImode);
33622   rtx_tmp1 = gen_reg_rtx (V2DImode);
33623
33624   /* The destination of the vmrgew instruction layout is:
33625      rtx_tmp2[0] rtx_tmp3[0] rtx_tmp2[1] rtx_tmp3[0].
33626      Setup rtx_tmp0 and rtx_tmp1 to ensure the order of the elements after the
33627      vmrgew instruction will be correct.  */
33628   if (BYTES_BIG_ENDIAN)
33629     {
33630       emit_insn (gen_vsx_xxpermdi_v2di_be (rtx_tmp0, src1, src2, GEN_INT (0)));
33631       emit_insn (gen_vsx_xxpermdi_v2di_be (rtx_tmp1, src1, src2, GEN_INT (3)));
33632     }
33633   else
33634     {
33635       emit_insn (gen_vsx_xxpermdi_v2di (rtx_tmp0, src1, src2, GEN_INT (3)));
33636       emit_insn (gen_vsx_xxpermdi_v2di (rtx_tmp1, src1, src2, GEN_INT (0)));
33637     }
33638
33639   rtx_tmp2 = gen_reg_rtx (V4SFmode);
33640   rtx_tmp3 = gen_reg_rtx (V4SFmode);
33641
33642   if (signed_convert)
33643     {
33644       emit_insn (gen_vsx_xvcvsxdsp (rtx_tmp2, rtx_tmp0));
33645       emit_insn (gen_vsx_xvcvsxdsp (rtx_tmp3, rtx_tmp1));
33646     }
33647   else
33648     {
33649        emit_insn (gen_vsx_xvcvuxdsp (rtx_tmp2, rtx_tmp0));
33650        emit_insn (gen_vsx_xvcvuxdsp (rtx_tmp3, rtx_tmp1));
33651     }
33652
33653   if (BYTES_BIG_ENDIAN)
33654     emit_insn (gen_p8_vmrgew_v4sf (dst, rtx_tmp2, rtx_tmp3));
33655   else
33656     emit_insn (gen_p8_vmrgew_v4sf (dst, rtx_tmp3, rtx_tmp2));
33657 }
33658
33659 void
33660 rs6000_generate_vsigned2_code (bool signed_convert, rtx dst, rtx src1,
33661                                rtx src2)
33662 {
33663   rtx rtx_tmp0, rtx_tmp1, rtx_tmp2, rtx_tmp3;
33664
33665   rtx_tmp0 = gen_reg_rtx (V2DFmode);
33666   rtx_tmp1 = gen_reg_rtx (V2DFmode);
33667
33668   emit_insn (gen_vsx_xxpermdi_v2df (rtx_tmp0, src1, src2, GEN_INT (0)));
33669   emit_insn (gen_vsx_xxpermdi_v2df (rtx_tmp1, src1, src2, GEN_INT (3)));
33670
33671   rtx_tmp2 = gen_reg_rtx (V4SImode);
33672   rtx_tmp3 = gen_reg_rtx (V4SImode);
33673
33674   if (signed_convert)
33675     {
33676       emit_insn (gen_vsx_xvcvdpsxws (rtx_tmp2, rtx_tmp0));
33677       emit_insn (gen_vsx_xvcvdpsxws (rtx_tmp3, rtx_tmp1));
33678     }
33679   else
33680     {
33681       emit_insn (gen_vsx_xvcvdpuxws (rtx_tmp2, rtx_tmp0));
33682       emit_insn (gen_vsx_xvcvdpuxws (rtx_tmp3, rtx_tmp1));
33683     }
33684
33685   emit_insn (gen_p8_vmrgew_v4si (dst, rtx_tmp2, rtx_tmp3));
33686 }
33687
33688 /* Implement the TARGET_OPTAB_SUPPORTED_P hook.  */
33689
33690 static bool
33691 rs6000_optab_supported_p (int op, machine_mode mode1, machine_mode,
33692                           optimization_type opt_type)
33693 {
33694   switch (op)
33695     {
33696     case rsqrt_optab:
33697       return (opt_type == OPTIMIZE_FOR_SPEED
33698               && RS6000_RECIP_AUTO_RSQRTE_P (mode1));
33699
33700     default:
33701       return true;
33702     }
33703 }
33704
33705 /* Implement TARGET_CONSTANT_ALIGNMENT.  */
33706
33707 static HOST_WIDE_INT
33708 rs6000_constant_alignment (const_tree exp, HOST_WIDE_INT align)
33709 {
33710   if (TREE_CODE (exp) == STRING_CST
33711       && (STRICT_ALIGNMENT || !optimize_size))
33712     return MAX (align, BITS_PER_WORD);
33713   return align;
33714 }
33715
33716 /* Implement TARGET_STARTING_FRAME_OFFSET.  */
33717
33718 static HOST_WIDE_INT
33719 rs6000_starting_frame_offset (void)
33720 {
33721   if (FRAME_GROWS_DOWNWARD)
33722     return 0;
33723   return RS6000_STARTING_FRAME_OFFSET;
33724 }
33725 \f
33726
33727 /* Create an alias for a mangled name where we have changed the mangling (in
33728    GCC 8.1, we used U10__float128, and now we use u9__ieee128).  This is called
33729    via the target hook TARGET_ASM_GLOBALIZE_DECL_NAME.  */
33730
33731 #if TARGET_ELF && RS6000_WEAK
33732 static void
33733 rs6000_globalize_decl_name (FILE * stream, tree decl)
33734 {
33735   const char *name = XSTR (XEXP (DECL_RTL (decl), 0), 0);
33736
33737   targetm.asm_out.globalize_label (stream, name);
33738
33739   if (rs6000_passes_ieee128 && name[0] == '_' && name[1] == 'Z')
33740     {
33741       tree save_asm_name = DECL_ASSEMBLER_NAME (decl);
33742       const char *old_name;
33743
33744       ieee128_mangling_gcc_8_1 = true;
33745       lang_hooks.set_decl_assembler_name (decl);
33746       old_name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl));
33747       SET_DECL_ASSEMBLER_NAME (decl, save_asm_name);
33748       ieee128_mangling_gcc_8_1 = false;
33749
33750       if (strcmp (name, old_name) != 0)
33751         {
33752           fprintf (stream, "\t.weak %s\n", old_name);
33753           fprintf (stream, "\t.set %s,%s\n", old_name, name);
33754         }
33755     }
33756 }
33757 #endif
33758
33759 \f
33760 /* On 64-bit Linux and Freebsd systems, possibly switch the long double library
33761    function names from <foo>l to <foo>f128 if the default long double type is
33762    IEEE 128-bit.  Typically, with the C and C++ languages, the standard math.h
33763    include file switches the names on systems that support long double as IEEE
33764    128-bit, but that doesn't work if the user uses __builtin_<foo>l directly.
33765    In the future, glibc will export names like __ieee128_sinf128 and we can
33766    switch to using those instead of using sinf128, which pollutes the user's
33767    namespace.
33768
33769    This will switch the names for Fortran math functions as well (which doesn't
33770    use math.h).  However, Fortran needs other changes to the compiler and
33771    library before you can switch the real*16 type at compile time.
33772
33773    We use the TARGET_MANGLE_DECL_ASSEMBLER_NAME hook to change this name.  We
33774    only do this if the default is that long double is IBM extended double, and
33775    the user asked for IEEE 128-bit.  */
33776
33777 static tree
33778 rs6000_mangle_decl_assembler_name (tree decl, tree id)
33779 {
33780   if (!TARGET_IEEEQUAD_DEFAULT && TARGET_IEEEQUAD && TARGET_LONG_DOUBLE_128
33781       && TREE_CODE (decl) == FUNCTION_DECL && DECL_IS_BUILTIN (decl) )
33782     {
33783       size_t len = IDENTIFIER_LENGTH (id);
33784       const char *name = IDENTIFIER_POINTER (id);
33785
33786       if (name[len - 1] == 'l')
33787         {
33788           bool uses_ieee128_p = false;
33789           tree type = TREE_TYPE (decl);
33790           machine_mode ret_mode = TYPE_MODE (type);
33791
33792           /* See if the function returns a IEEE 128-bit floating point type or
33793              complex type.  */
33794           if (ret_mode == TFmode || ret_mode == TCmode)
33795             uses_ieee128_p = true;
33796           else
33797             {
33798               function_args_iterator args_iter;
33799               tree arg;
33800
33801               /* See if the function passes a IEEE 128-bit floating point type
33802                  or complex type.  */
33803               FOREACH_FUNCTION_ARGS (type, arg, args_iter)
33804                 {
33805                   machine_mode arg_mode = TYPE_MODE (arg);
33806                   if (arg_mode == TFmode || arg_mode == TCmode)
33807                     {
33808                       uses_ieee128_p = true;
33809                       break;
33810                     }
33811                 }
33812             }
33813
33814           /* If we passed or returned an IEEE 128-bit floating point type,
33815              change the name.  */
33816           if (uses_ieee128_p)
33817             {
33818               char *name2 = (char *) alloca (len + 4);
33819               memcpy (name2, name, len - 1);
33820               strcpy (name2 + len - 1, "f128");
33821               id = get_identifier (name2);
33822             }
33823         }
33824     }
33825
33826   return id;
33827 }
33828
33829 /* Predict whether the given loop in gimple will be transformed in the RTL
33830    doloop_optimize pass.  */
33831
33832 static bool
33833 rs6000_predict_doloop_p (struct loop *loop)
33834 {
33835   gcc_assert (loop);
33836
33837   /* On rs6000, targetm.can_use_doloop_p is actually
33838      can_use_doloop_if_innermost.  Just ensure the loop is innermost.  */
33839   if (loop->inner != NULL)
33840     {
33841       if (dump_file && (dump_flags & TDF_DETAILS))
33842         fprintf (dump_file, "Predict doloop failure due to"
33843                             " loop nesting.\n");
33844       return false;
33845     }
33846
33847   return true;
33848 }
33849
33850 struct gcc_target targetm = TARGET_INITIALIZER;
33851
33852 #include "gt-rs6000.h"