Debian Codegraph @

gcc/config/aarch64/aarch64.cc

raw
1 /* Machine description for AArch64 architecture.
2 Copyright (C) 2009-2025 Free Software Foundation, Inc.
3 Contributed by ARM Ltd.
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 by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public 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 #define INCLUDE_STRING
24 #define INCLUDE_ALGORITHM
25 #define INCLUDE_VECTOR
26 #include "config.h"
27 #include "system.h"
28 #include "coretypes.h"
29 #include "backend.h"
30 #include "target.h"
31 #include "rtl.h"
32 #include "tree.h"
33 #include "memmodel.h"
34 #include "gimple.h"
35 #include "cfghooks.h"
36 #include "cfgloop.h"
37 #include "df.h"
38 #include "tm_p.h"
39 #include "stringpool.h"
40 #include "attribs.h"
41 #include "optabs.h"
42 #include "regs.h"
43 #include "emit-rtl.h"
44 #include "recog.h"
45 #include "cgraph.h"
46 #include "diagnostic.h"
47 #include "insn-attr.h"
48 #include "alias.h"
49 #include "fold-const.h"
50 #include "stor-layout.h"
51 #include "calls.h"
52 #include "varasm.h"
53 #include "output.h"
54 #include "flags.h"
55 #include "explow.h"
56 #include "expr.h"
57 #include "reload.h"
58 #include "langhooks.h"
59 #include "opts.h"
60 #include "gimplify.h"
61 #include "dwarf2.h"
62 #include "dwarf2out.h"
63 #include "gimple-iterator.h"
64 #include "tree-vectorizer.h"
65 #include "aarch64-cost-tables.h"
66 #include "dumpfile.h"
67 #include "builtins.h"
68 #include "rtl-iter.h"
69 #include "tm-constrs.h"
70 #include "sched-int.h"
71 #include "target-globals.h"
72 #include "common/common-target.h"
73 #include "cfgrtl.h"
74 #include "selftest.h"
75 #include "selftest-rtl.h"
76 #include "rtx-vector-builder.h"
77 #include "intl.h"
78 #include "expmed.h"
79 #include "function-abi.h"
80 #include "gimple-pretty-print.h"
81 #include "tree-ssa-loop-niter.h"
82 #include "fractional-cost.h"
83 #include "rtlanal.h"
84 #include "tree-dfa.h"
85 #include "asan.h"
86 #include "aarch64-feature-deps.h"
87 #include "config/arm/aarch-common.h"
88 #include "config/arm/aarch-common-protos.h"
89 #include "common/config/aarch64/cpuinfo.h"
90 #include "ssa.h"
91 #include "except.h"
92 #include "tree-pass.h"
93 #include "cfgbuild.h"
94 #include "symbol-summary.h"
95 #include "sreal.h"
96 #include "ipa-cp.h"
97 #include "ipa-prop.h"
98 #include "ipa-fnsummary.h"
99 #include "hash-map.h"
100 #include "ifcvt.h"
101
102 /* This file should be included last. */
103 #include "target-def.h"
104
105 /* Defined for convenience. */
106 #define POINTER_BYTES (POINTER_SIZE / BITS_PER_UNIT)
107
108 /* Maximum bytes set for an inline memset expansion. With -Os use 3 STP
109 and 1 MOVI/DUP (same size as a call). */
110 #define MAX_SET_SIZE(speed) (speed ? 256 : 96)
111
112 /* Flags that describe how a function shares certain architectural state
113 with its callers.
114
115 - AARCH64_STATE_SHARED indicates that the function does share the state
116 with callers.
117
118 - AARCH64_STATE_IN indicates that the function reads (or might read) the
119 incoming state. The converse is that the function ignores the incoming
120 state.
121
122 - AARCH64_STATE_OUT indicates that the function returns new state.
123 The converse is that the state on return is the same as it was on entry.
124
125 A function that partially modifies the state treats it as both IN
126 and OUT (because the value on return depends to some extent on the
127 value on input). */
128 constexpr auto AARCH64_STATE_SHARED = 1U << 0;
129 constexpr auto AARCH64_STATE_IN = 1U << 1;
130 constexpr auto AARCH64_STATE_OUT = 1U << 2;
131
132 /* Enum to distinguish which type of check is to be done in
133 aarch64_simd_valid_imm. */
134 enum simd_immediate_check {
135 AARCH64_CHECK_MOV,
136 AARCH64_CHECK_ORR,
137 AARCH64_CHECK_AND,
138 AARCH64_CHECK_XOR
139 };
140
141 /* Information about a legitimate vector immediate operand. */
142 struct simd_immediate_info
143 {
144 enum insn_type { MOV, MVN, INDEX, PTRUE, SVE_MOV };
145 enum modifier_type { LSL, MSL };
146
147 simd_immediate_info () {}
148 simd_immediate_info (scalar_float_mode, rtx);
149 simd_immediate_info (scalar_int_mode, unsigned HOST_WIDE_INT,
150 insn_type = MOV, modifier_type = LSL,
151 unsigned int = 0);
152 simd_immediate_info (scalar_mode, rtx, rtx);
153 simd_immediate_info (scalar_int_mode, aarch64_svpattern);
154
155 /* The mode of the elements. */
156 scalar_mode elt_mode;
157
158 /* The instruction to use to move the immediate into a vector. */
159 insn_type insn;
160
161 union
162 {
163 /* For MOV and MVN. */
164 struct
165 {
166 /* The value of each element. */
167 rtx value;
168
169 /* The kind of shift modifier to use, and the number of bits to shift.
170 This is (LSL, 0) if no shift is needed. */
171 modifier_type modifier;
172 unsigned int shift;
173 } mov;
174
175 /* For INDEX. */
176 struct
177 {
178 /* The value of the first element and the step to be added for each
179 subsequent element. */
180 rtx base, step;
181 } index;
182
183 /* For PTRUE. */
184 aarch64_svpattern pattern;
185 } u;
186 };
187
188 /* Construct a floating-point immediate in which each element has mode
189 ELT_MODE_IN and value VALUE_IN. */
190 inline simd_immediate_info
191 ::simd_immediate_info (scalar_float_mode elt_mode_in, rtx value_in)
192 : elt_mode (elt_mode_in), insn (MOV)
193 {
194 u.mov.value = value_in;
195 u.mov.modifier = LSL;
196 u.mov.shift = 0;
197 }
198
199 /* Construct an integer immediate in which each element has mode ELT_MODE_IN
200 and value VALUE_IN. The other parameters are as for the structure
201 fields. */
202 inline simd_immediate_info
203 ::simd_immediate_info (scalar_int_mode elt_mode_in,
204 unsigned HOST_WIDE_INT value_in,
205 insn_type insn_in, modifier_type modifier_in,
206 unsigned int shift_in)
207 : elt_mode (elt_mode_in), insn (insn_in)
208 {
209 u.mov.value = gen_int_mode (value_in, elt_mode_in);
210 u.mov.modifier = modifier_in;
211 u.mov.shift = shift_in;
212 }
213
214 /* Construct an integer immediate in which each element has mode ELT_MODE_IN
215 and where element I is equal to BASE_IN + I * STEP_IN. */
216 inline simd_immediate_info
217 ::simd_immediate_info (scalar_mode elt_mode_in, rtx base_in, rtx step_in)
218 : elt_mode (elt_mode_in), insn (INDEX)
219 {
220 u.index.base = base_in;
221 u.index.step = step_in;
222 }
223
224 /* Construct a predicate that controls elements of mode ELT_MODE_IN
225 and has PTRUE pattern PATTERN_IN. */
226 inline simd_immediate_info
227 ::simd_immediate_info (scalar_int_mode elt_mode_in,
228 aarch64_svpattern pattern_in)
229 : elt_mode (elt_mode_in), insn (PTRUE)
230 {
231 u.pattern = pattern_in;
232 }
233
234 namespace {
235
236 /* Describes types that map to Pure Scalable Types (PSTs) in the AAPCS64. */
237 class pure_scalable_type_info
238 {
239 public:
240 /* Represents the result of analyzing a type. All values are nonzero,
241 in the possibly forlorn hope that accidental conversions to bool
242 trigger a warning. */
243 enum analysis_result
244 {
245 /* The type does not have an ABI identity; i.e. it doesn't contain
246 at least one object whose type is a Fundamental Data Type. */
247 NO_ABI_IDENTITY = 1,
248
249 /* The type is definitely a Pure Scalable Type. */
250 IS_PST,
251
252 /* The type is definitely not a Pure Scalable Type. */
253 ISNT_PST,
254
255 /* It doesn't matter for PCS purposes whether the type is a Pure
256 Scalable Type or not, since the type will be handled the same
257 way regardless.
258
259 Specifically, this means that if the type is a Pure Scalable Type,
260 there aren't enough argument registers to hold it, and so it will
261 need to be passed or returned in memory. If the type isn't a
262 Pure Scalable Type, it's too big to be passed or returned in core
263 or SIMD&FP registers, and so again will need to go in memory. */
264 DOESNT_MATTER
265 };
266
267 /* Aggregates of 17 bytes or more are normally passed and returned
268 in memory, so aggregates of that size can safely be analyzed as
269 DOESNT_MATTER. We need to be able to collect enough pieces to
270 represent a PST that is smaller than that. Since predicates are
271 2 bytes in size for -msve-vector-bits=128, that means we need to be
272 able to store at least 8 pieces.
273
274 We also need to be able to store enough pieces to represent
275 a single vector in each vector argument register and a single
276 predicate in each predicate argument register. This means that
277 we need at least 12 pieces. */
278 static const unsigned int MAX_PIECES = NUM_FP_ARG_REGS + NUM_PR_ARG_REGS;
279 static_assert (MAX_PIECES >= 8, "Need to store at least 8 predicates");
280
281 /* Describes one piece of a PST. Each piece is one of:
282
283 - a single Scalable Vector Type (SVT)
284 - a single Scalable Predicate Type (SPT)
285 - a PST containing 2, 3 or 4 SVTs, with no padding
286
287 It either represents a single built-in type or a PST formed from
288 multiple homogeneous built-in types. */
289 struct piece
290 {
291 rtx get_rtx (unsigned int, unsigned int) const;
292
293 /* The number of vector and predicate registers that the piece
294 occupies. One of the two is always zero. */
295 unsigned int num_zr;
296 unsigned int num_pr;
297
298 /* The mode of the registers described above. */
299 machine_mode mode;
300
301 /* If this piece is formed from multiple homogeneous built-in types,
302 this is the mode of the built-in types, otherwise it is MODE. */
303 machine_mode orig_mode;
304
305 /* The offset in bytes of the piece from the start of the type. */
306 poly_uint64 offset;
307 };
308
309 /* Divides types analyzed as IS_PST into individual pieces. The pieces
310 are in memory order. */
311 auto_vec<piece, MAX_PIECES> pieces;
312
313 unsigned int num_zr () const;
314 unsigned int num_pr () const;
315
316 rtx get_rtx (machine_mode mode, unsigned int, unsigned int) const;
317
318 analysis_result analyze (const_tree);
319 bool analyze_registers (const_tree);
320
321 private:
322 analysis_result analyze_array (const_tree);
323 analysis_result analyze_record (const_tree);
324 void add_piece (const piece &);
325 };
326 }
327
328 /* The current code model. */
329 enum aarch64_code_model aarch64_cmodel;
330
331 enum aarch64_tp_reg aarch64_tpidr_register;
332
333 /* The number of 64-bit elements in an SVE vector. */
334 poly_uint16 aarch64_sve_vg;
335
336 #ifdef HAVE_AS_TLS
337 #undef TARGET_HAVE_TLS
338 #define TARGET_HAVE_TLS 1
339 #endif
340
341 static bool aarch64_composite_type_p (const_tree, machine_mode);
342 static bool aarch64_return_in_memory_1 (const_tree);
343 static bool aarch64_vfp_is_call_or_return_candidate (machine_mode,
344 const_tree,
345 machine_mode *, int *,
346 bool *, bool);
347 static void aarch64_elf_asm_constructor (rtx, int) ATTRIBUTE_UNUSED;
348 static void aarch64_elf_asm_destructor (rtx, int) ATTRIBUTE_UNUSED;
349 static void aarch64_override_options_after_change (void);
350 static bool aarch64_vector_mode_supported_p (machine_mode);
351 static int aarch64_address_cost (rtx, machine_mode, addr_space_t, bool);
352 static bool aarch64_builtin_support_vector_misalignment (machine_mode mode,
353 const_tree type,
354 int misalignment,
355 bool is_packed);
356 static machine_mode aarch64_simd_container_mode (scalar_mode, poly_int64);
357 static bool aarch64_print_address_internal (FILE*, machine_mode, rtx,
358 aarch64_addr_query_type);
359
360 /* The processor for which instructions should be scheduled. */
361 enum aarch64_cpu aarch64_tune = AARCH64_CPU_cortexa53;
362
363 /* Global flag for PC relative loads. */
364 bool aarch64_pcrelative_literal_loads;
365
366 /* Global flag for whether frame pointer is enabled. */
367 bool aarch64_use_frame_pointer;
368
369 /* Support for command line parsing of boolean flags in the tuning
370 structures. */
371 struct aarch64_flag_desc
372 {
373 const char* name;
374 unsigned int flag;
375 };
376
377 #define AARCH64_FUSION_PAIR(name, internal_name) \
378 { name, AARCH64_FUSE_##internal_name },
379 static const struct aarch64_flag_desc aarch64_fusible_pairs[] =
380 {
381 { "none", AARCH64_FUSE_NOTHING },
382 #include "aarch64-fusion-pairs.def"
383 { "all", AARCH64_FUSE_ALL },
384 { NULL, AARCH64_FUSE_NOTHING }
385 };
386
387 #define AARCH64_EXTRA_TUNING_OPTION(name, internal_name) \
388 { name, AARCH64_EXTRA_TUNE_##internal_name },
389 static const struct aarch64_flag_desc aarch64_tuning_flags[] =
390 {
391 { "none", AARCH64_EXTRA_TUNE_NONE },
392 #include "aarch64-tuning-flags.def"
393 { "all", AARCH64_EXTRA_TUNE_ALL },
394 { NULL, AARCH64_EXTRA_TUNE_NONE }
395 };
396
397 /* Tuning parameters. */
398 #include "tuning_models/generic.h"
399 #include "tuning_models/generic_armv8_a.h"
400 #include "tuning_models/generic_armv9_a.h"
401 #include "tuning_models/cortexa35.h"
402 #include "tuning_models/cortexa53.h"
403 #include "tuning_models/cortexa57.h"
404 #include "tuning_models/cortexa72.h"
405 #include "tuning_models/cortexa73.h"
406 #include "tuning_models/cortexx925.h"
407 #include "tuning_models/exynosm1.h"
408 #include "tuning_models/thunderxt88.h"
409 #include "tuning_models/thunderx.h"
410 #include "tuning_models/tsv110.h"
411 #include "tuning_models/hip12.h"
412 #include "tuning_models/xgene1.h"
413 #include "tuning_models/emag.h"
414 #include "tuning_models/qdf24xx.h"
415 #include "tuning_models/saphira.h"
416 #include "tuning_models/thunderx2t99.h"
417 #include "tuning_models/thunderx3t110.h"
418 #include "tuning_models/neoversen1.h"
419 #include "tuning_models/ampere1.h"
420 #include "tuning_models/ampere1a.h"
421 #include "tuning_models/ampere1b.h"
422 #include "tuning_models/neoversev1.h"
423 #include "tuning_models/neoverse512tvb.h"
424 #include "tuning_models/neoversen2.h"
425 #include "tuning_models/neoversen3.h"
426 #include "tuning_models/neoversev2.h"
427 #include "tuning_models/neoversev3.h"
428 #include "tuning_models/neoversev3ae.h"
429 #include "tuning_models/olympus.h"
430 #include "tuning_models/a64fx.h"
431 #include "tuning_models/fujitsu_monaka.h"
432
433 /* Support for fine-grained override of the tuning structures. */
434 struct aarch64_tuning_override_function
435 {
436 const char* name;
437 void (*parse_override)(const char*, struct tune_params*);
438 };
439
440 static void aarch64_parse_fuse_string (const char*, struct tune_params*);
441 static void aarch64_parse_tune_string (const char*, struct tune_params*);
442 static void aarch64_parse_sve_width_string (const char*, struct tune_params*);
443
444 static const struct aarch64_tuning_override_function
445 aarch64_tuning_override_functions[] =
446 {
447 { "fuse", aarch64_parse_fuse_string },
448 { "tune", aarch64_parse_tune_string },
449 { "sve_width", aarch64_parse_sve_width_string },
450 { NULL, NULL }
451 };
452
453 /* A processor implementing AArch64. */
454 struct processor
455 {
456 const char *name;
457 aarch64_cpu ident;
458 aarch64_cpu sched_core;
459 aarch64_arch arch;
460 aarch64_feature_flags flags;
461 const tune_params *tune;
462 };
463
464 /* Architectures implementing AArch64. */
465 static CONSTEXPR const processor all_architectures[] =
466 {
467 #define AARCH64_ARCH(NAME, CORE, ARCH_IDENT, D, E) \
468 {NAME, AARCH64_CPU_##CORE, AARCH64_CPU_##CORE, AARCH64_ARCH_##ARCH_IDENT, \
469 feature_deps::ARCH_IDENT ().enable, NULL},
470 #include "aarch64-arches.def"
471 {NULL, aarch64_no_cpu, aarch64_no_cpu, aarch64_no_arch, 0, NULL}
472 };
473
474 /* Processor cores implementing AArch64. */
475 static const struct processor all_cores[] =
476 {
477 #define AARCH64_CORE(NAME, IDENT, SCHED, ARCH, E, COSTS, G, H, I) \
478 {NAME, AARCH64_CPU_##IDENT, AARCH64_CPU_##SCHED, AARCH64_ARCH_##ARCH, \
479 feature_deps::cpu_##IDENT, &COSTS##_tunings},
480 #include "aarch64-cores.def"
481 {NULL, aarch64_no_cpu, aarch64_no_cpu, aarch64_no_arch, 0, NULL}
482 };
483 /* Internal representation of system registers. */
484 typedef struct {
485 const char *name;
486 /* Stringified sysreg encoding values, represented as
487 s<sn>_<op1>_c<cn>_c<cm>_<op2>. */
488 const char *encoding;
489 /* Flags affecting sysreg usage, such as read/write-only. */
490 unsigned properties;
491 /* Architectural features implied by sysreg. */
492 aarch64_feature_flags arch_reqs;
493 } sysreg_t;
494
495 /* An aarch64_feature_set initializer for a single feature,
496 AARCH64_FEATURE_<FEAT>. */
497 #define AARCH64_FEATURE(FEAT) AARCH64_FL_##FEAT
498
499 /* Used by AARCH64_FEATURES. */
500 #define AARCH64_OR_FEATURES_1(X, F1) \
501 AARCH64_FEATURE (F1)
502 #define AARCH64_OR_FEATURES_2(X, F1, F2) \
503 (AARCH64_FEATURE (F1) | AARCH64_OR_FEATURES_1 (X, F2))
504 #define AARCH64_OR_FEATURES_3(X, F1, ...) \
505 (AARCH64_FEATURE (F1) | AARCH64_OR_FEATURES_2 (X, __VA_ARGS__))
506
507 /* An aarch64_feature_set initializer for the N features listed in "...". */
508 #define AARCH64_FEATURES(N, ...) \
509 AARCH64_OR_FEATURES_##N (0, __VA_ARGS__)
510
511 #define AARCH64_NO_FEATURES 0
512
513 /* Flags associated with the properties of system registers. It mainly serves
514 to mark particular registers as read or write only. */
515 #define F_DEPRECATED (1 << 1)
516 #define F_REG_READ (1 << 2)
517 #define F_REG_WRITE (1 << 3)
518 #define F_ARCHEXT (1 << 4)
519 /* Flag indicating register name is alias for another system register. */
520 #define F_REG_ALIAS (1 << 5)
521 /* Flag indicatinig registers which may be implemented with 128-bits. */
522 #define F_REG_128 (1 << 6)
523
524 /* Database of system registers, their encodings and architectural
525 requirements. */
526 const sysreg_t aarch64_sysregs[] =
527 {
528 #define CPENC(SN, OP1, CN, CM, OP2) "s"#SN"_"#OP1"_c"#CN"_c"#CM"_"#OP2
529 #define SYSREG(NAME, ENC, FLAGS, ARCH) \
530 { NAME, ENC, FLAGS, ARCH },
531 #include "aarch64-sys-regs.def"
532 #undef CPENC
533 };
534
535 #undef AARCH64_NO_FEATURES
536
537 using sysreg_map_t = hash_map<nofree_string_hash, const sysreg_t *>;
538 static sysreg_map_t *sysreg_map = nullptr;
539
540 /* Map system register names to their hardware metadata: encoding,
541 feature flags and architectural feature requirements, all of which
542 are encoded in a sysreg_t struct. */
543 void
544 aarch64_register_sysreg (const char *name, const sysreg_t *metadata)
545 {
546 bool dup = sysreg_map->put (name, metadata);
547 gcc_checking_assert (!dup);
548 }
549
550 /* Lazily initialize hash table for system register validation,
551 checking the validity of supplied register name and returning
552 register's associated metadata. */
553 static void
554 aarch64_init_sysregs (void)
555 {
556 gcc_assert (!sysreg_map);
557 sysreg_map = new sysreg_map_t;
558
559
560 for (unsigned i = 0; i < ARRAY_SIZE (aarch64_sysregs); i++)
561 {
562 const sysreg_t *reg = aarch64_sysregs + i;
563 aarch64_register_sysreg (reg->name, reg);
564 }
565 }
566
567 /* No direct access to the sysreg hash-map should be made. Doing so
568 risks trying to acess an unitialized hash-map and dereferencing the
569 returned double pointer without due care risks dereferencing a
570 null-pointer. */
571 const sysreg_t *
572 aarch64_lookup_sysreg_map (const char *regname)
573 {
574 if (!sysreg_map)
575 aarch64_init_sysregs ();
576
577 const sysreg_t **sysreg_entry = sysreg_map->get (regname);
578 if (sysreg_entry != NULL)
579 return *sysreg_entry;
580 return NULL;
581 }
582
583 /* The current tuning set. */
584 struct tune_params aarch64_tune_params = generic_tunings;
585
586 /* If NAME is the name of an arm:: attribute that describes shared state,
587 return its associated AARCH64_STATE_* flags, otherwise return 0. */
588 static unsigned int
589 aarch64_attribute_shared_state_flags (const char *name)
590 {
591 if (strcmp (name, "in") == 0)
592 return AARCH64_STATE_SHARED | AARCH64_STATE_IN;
593 if (strcmp (name, "inout") == 0)
594 return AARCH64_STATE_SHARED | AARCH64_STATE_IN | AARCH64_STATE_OUT;
595 if (strcmp (name, "out") == 0)
596 return AARCH64_STATE_SHARED | AARCH64_STATE_OUT;
597 if (strcmp (name, "preserves") == 0)
598 return AARCH64_STATE_SHARED;
599 return 0;
600 }
601
602 /* See whether attribute list ATTRS has any sharing information
603 for state STATE_NAME. Return the associated state flags if so,
604 otherwise return 0. */
605 static unsigned int
606 aarch64_lookup_shared_state_flags (tree attrs, const char *state_name)
607 {
608 for (tree attr = attrs; attr; attr = TREE_CHAIN (attr))
609 {
610 if (!is_attribute_namespace_p ("arm", attr))
611 continue;
612
613 auto attr_name = IDENTIFIER_POINTER (get_attribute_name (attr));
614 auto flags = aarch64_attribute_shared_state_flags (attr_name);
615 if (!flags)
616 continue;
617
618 for (tree arg = TREE_VALUE (attr); arg; arg = TREE_CHAIN (arg))
619 {
620 tree value = TREE_VALUE (arg);
621 if (TREE_CODE (value) == STRING_CST
622 && strcmp (TREE_STRING_POINTER (value), state_name) == 0)
623 return flags;
624 }
625 }
626 return 0;
627 }
628
629 /* Return true if DECL creates a new scope for state STATE_STRING. */
630 static bool
631 aarch64_fndecl_has_new_state (const_tree decl, const char *state_name)
632 {
633 if (tree attr = lookup_attribute ("arm", "new", DECL_ATTRIBUTES (decl)))
634 for (tree arg = TREE_VALUE (attr); arg; arg = TREE_CHAIN (arg))
635 {
636 tree value = TREE_VALUE (arg);
637 if (TREE_CODE (value) == STRING_CST
638 && strcmp (TREE_STRING_POINTER (value), state_name) == 0)
639 return true;
640 }
641 return false;
642 }
643
644 /* Return true if attribute argument VALUE is a recognized state string,
645 otherwise report an error. NAME is the name of the attribute to which
646 VALUE is being passed. */
647 static bool
648 aarch64_check_state_string (tree name, tree value)
649 {
650 if (TREE_CODE (value) != STRING_CST)
651 {
652 error ("the arguments to %qE must be constant strings", name);
653 return false;
654 }
655
656 const char *state_name = TREE_STRING_POINTER (value);
657 if (strcmp (state_name, "za") != 0
658 && strcmp (state_name, "zt0") != 0)
659 {
660 error ("unrecognized state string %qs", state_name);
661 return false;
662 }
663
664 return true;
665 }
666
667 /* qsort callback to compare two STRING_CSTs. */
668 static int
669 cmp_string_csts (const void *a, const void *b)
670 {
671 return strcmp (TREE_STRING_POINTER (*(const_tree const *) a),
672 TREE_STRING_POINTER (*(const_tree const *) b));
673 }
674
675 /* Canonicalize a list of state strings. ARGS contains the arguments to
676 a new attribute while OLD_ATTR, if nonnull, contains a previous attribute
677 of the same type. If CAN_MERGE_IN_PLACE, it is safe to adjust OLD_ATTR's
678 arguments and drop the new attribute. Otherwise, the new attribute must
679 be kept and ARGS must include the information in OLD_ATTR.
680
681 In both cases, the new arguments must be a sorted list of state strings
682 with duplicates removed.
683
684 Return true if new attribute should be kept, false if it should be
685 dropped. */
686 static bool
687 aarch64_merge_string_arguments (tree args, tree old_attr,
688 bool can_merge_in_place)
689 {
690 /* Get a sorted list of all state strings (including duplicates). */
691 auto add_args = [](vec<tree> &strings, const_tree args)
692 {
693 for (const_tree arg = args; arg; arg = TREE_CHAIN (arg))
694 if (TREE_CODE (TREE_VALUE (arg)) == STRING_CST)
695 strings.safe_push (TREE_VALUE (arg));
696 };
697 auto_vec<tree, 16> strings;
698 add_args (strings, args);
699 if (old_attr)
700 add_args (strings, TREE_VALUE (old_attr));
701 strings.qsort (cmp_string_csts);
702
703 /* The list can be empty if there was no previous attribute and if all
704 the new arguments are erroneous. Drop the attribute in that case. */
705 if (strings.is_empty ())
706 return false;
707
708 /* Destructively modify one of the argument lists, removing duplicates
709 on the fly. */
710 bool use_old_attr = old_attr && can_merge_in_place;
711 tree *end = use_old_attr ? &TREE_VALUE (old_attr) : &args;
712 tree prev = NULL_TREE;
713 for (tree arg : strings)
714 {
715 if (prev && simple_cst_equal (arg, prev))
716 continue;
717 prev = arg;
718 if (!*end)
719 *end = tree_cons (NULL_TREE, arg, NULL_TREE);
720 else
721 TREE_VALUE (*end) = arg;
722 end = &TREE_CHAIN (*end);
723 }
724 *end = NULL_TREE;
725 return !use_old_attr;
726 }
727
728 /* Check whether an 'aarch64_vector_pcs' attribute is valid. */
729
730 static tree
731 handle_aarch64_vector_pcs_attribute (tree *node, tree name, tree,
732 int, bool *no_add_attrs)
733 {
734 /* Since we set fn_type_req to true, the caller should have checked
735 this for us. */
736 gcc_assert (FUNC_OR_METHOD_TYPE_P (*node));
737 switch ((arm_pcs) fntype_abi (*node).id ())
738 {
739 case ARM_PCS_AAPCS64:
740 case ARM_PCS_SIMD:
741 return NULL_TREE;
742
743 case ARM_PCS_SVE:
744 error ("the %qE attribute cannot be applied to an SVE function type",
745 name);
746 *no_add_attrs = true;
747 return NULL_TREE;
748
749 case ARM_PCS_TLSDESC:
750 case ARM_PCS_UNKNOWN:
751 break;
752 }
753 gcc_unreachable ();
754 }
755
756 /* Return true if arm::new(ARGS) is compatible with the type of decl DECL,
757 otherwise report an error. */
758 static bool
759 aarch64_check_arm_new_against_type (tree args, tree decl)
760 {
761 tree type_attrs = TYPE_ATTRIBUTES (TREE_TYPE (decl));
762 for (tree arg = args; arg; arg = TREE_CHAIN (arg))
763 {
764 tree value = TREE_VALUE (arg);
765 if (TREE_CODE (value) == STRING_CST)
766 {
767 const char *state_name = TREE_STRING_POINTER (value);
768 if (aarch64_lookup_shared_state_flags (type_attrs, state_name))
769 {
770 error_at (DECL_SOURCE_LOCATION (decl),
771 "cannot create a new %qs scope since %qs is shared"
772 " with callers", state_name, state_name);
773 return false;
774 }
775 }
776 }
777 return true;
778 }
779
780 /* Callback for arm::new attributes. */
781 static tree
782 handle_arm_new (tree *node, tree name, tree args, int, bool *no_add_attrs)
783 {
784 tree decl = *node;
785 if (TREE_CODE (decl) != FUNCTION_DECL)
786 {
787 error ("%qE attribute applies only to function definitions", name);
788 *no_add_attrs = true;
789 return NULL_TREE;
790 }
791 if (TREE_TYPE (decl) == error_mark_node)
792 {
793 *no_add_attrs = true;
794 return NULL_TREE;
795 }
796
797 for (tree arg = args; arg; arg = TREE_CHAIN (arg))
798 aarch64_check_state_string (name, TREE_VALUE (arg));
799
800 if (!aarch64_check_arm_new_against_type (args, decl))
801 {
802 *no_add_attrs = true;
803 return NULL_TREE;
804 }
805
806 /* If there is an old attribute, we should try to update it in-place,
807 so that there is only one (definitive) arm::new attribute on the decl. */
808 tree old_attr = lookup_attribute ("arm", "new", DECL_ATTRIBUTES (decl));
809 if (!aarch64_merge_string_arguments (args, old_attr, true))
810 *no_add_attrs = true;
811
812 return NULL_TREE;
813 }
814
815 /* Callback for arm::{in,out,inout,preserves} attributes. */
816 static tree
817 handle_arm_shared (tree *node, tree name, tree args,
818 int, bool *no_add_attrs)
819 {
820 tree type = *node;
821 tree old_attrs = TYPE_ATTRIBUTES (type);
822 auto flags = aarch64_attribute_shared_state_flags (IDENTIFIER_POINTER (name));
823 for (tree arg = args; arg; arg = TREE_CHAIN (arg))
824 {
825 tree value = TREE_VALUE (arg);
826 if (aarch64_check_state_string (name, value))
827 {
828 const char *state_name = TREE_STRING_POINTER (value);
829 auto old_flags = aarch64_lookup_shared_state_flags (old_attrs,
830 state_name);
831 if (old_flags && old_flags != flags)
832 {
833 error ("inconsistent attributes for state %qs", state_name);
834 *no_add_attrs = true;
835 return NULL_TREE;
836 }
837 }
838 }
839
840 /* We can't update an old attribute in-place, since types are shared.
841 Instead make sure that this new attribute contains all the
842 information, so that the old attribute becomes redundant. */
843 tree old_attr = lookup_attribute ("arm", IDENTIFIER_POINTER (name),
844 old_attrs);
845 if (!aarch64_merge_string_arguments (args, old_attr, false))
846 *no_add_attrs = true;
847
848 return NULL_TREE;
849 }
850
851 /* Mutually-exclusive function type attributes for controlling PSTATE.SM. */
852 static const struct attribute_spec::exclusions attr_streaming_exclusions[] =
853 {
854 /* Attribute name exclusion applies to:
855 function, type, variable */
856 { "streaming", false, true, false },
857 { "streaming_compatible", false, true, false },
858 { NULL, false, false, false }
859 };
860
861 /* Table of machine attributes. */
862 static const attribute_spec aarch64_gnu_attributes[] =
863 {
864 /* { name, min_len, max_len, decl_req, type_req, fn_type_req,
865 affects_type_identity, handler, exclude } */
866 { "aarch64_vector_pcs", 0, 0, false, true, true, true,
867 handle_aarch64_vector_pcs_attribute, NULL },
868 { "indirect_return", 0, 0, false, true, true, true, NULL, NULL },
869 { "arm_sve_vector_bits", 1, 1, false, true, false, true,
870 aarch64_sve::handle_arm_sve_vector_bits_attribute,
871 NULL },
872 { "Advanced SIMD type", 1, 1, false, true, false, true, NULL, NULL },
873 { "SVE type", 3, 3, false, true, false, true, NULL, NULL },
874 { "SVE sizeless type", 0, 0, false, true, false, true, NULL, NULL },
875 #if TARGET_DLLIMPORT_DECL_ATTRIBUTES
876 { "dllimport", 0, 0, false, false, false, false, handle_dll_attribute, NULL },
877 { "dllexport", 0, 0, false, false, false, false, handle_dll_attribute, NULL },
878 #endif
879 #ifdef SUBTARGET_ATTRIBUTE_TABLE
880 SUBTARGET_ATTRIBUTE_TABLE
881 #endif
882 };
883
884 static const scoped_attribute_specs aarch64_gnu_attribute_table =
885 {
886 "gnu", { aarch64_gnu_attributes }
887 };
888
889 static const attribute_spec aarch64_arm_attributes[] =
890 {
891 { "streaming", 0, 0, false, true, true, true,
892 NULL, attr_streaming_exclusions },
893 { "streaming_compatible", 0, 0, false, true, true, true,
894 NULL, attr_streaming_exclusions },
895 { "locally_streaming", 0, 0, true, false, false, false, NULL, NULL },
896 { "new", 1, -1, true, false, false, false,
897 handle_arm_new, NULL },
898 { "preserves", 1, -1, false, true, true, true,
899 handle_arm_shared, NULL },
900 { "in", 1, -1, false, true, true, true,
901 handle_arm_shared, NULL },
902 { "out", 1, -1, false, true, true, true,
903 handle_arm_shared, NULL },
904 { "inout", 1, -1, false, true, true, true,
905 handle_arm_shared, NULL }
906 };
907
908 static const scoped_attribute_specs aarch64_arm_attribute_table =
909 {
910 "arm", { aarch64_arm_attributes }
911 };
912
913 static const scoped_attribute_specs *const aarch64_attribute_table[] =
914 {
915 &aarch64_gnu_attribute_table,
916 &aarch64_arm_attribute_table
917 };
918
919 typedef enum aarch64_cond_code
920 {
921 AARCH64_EQ = 0, AARCH64_NE, AARCH64_CS, AARCH64_CC, AARCH64_MI, AARCH64_PL,
922 AARCH64_VS, AARCH64_VC, AARCH64_HI, AARCH64_LS, AARCH64_GE, AARCH64_LT,
923 AARCH64_GT, AARCH64_LE, AARCH64_AL, AARCH64_NV
924 }
925 aarch64_cc;
926
927 #define AARCH64_INVERSE_CONDITION_CODE(X) ((aarch64_cc) (((int) X) ^ 1))
928
929
930 /* The condition codes of the processor, and the inverse function. */
931 static const char * const aarch64_condition_codes[] =
932 {
933 "eq", "ne", "cs", "cc", "mi", "pl", "vs", "vc",
934 "hi", "ls", "ge", "lt", "gt", "le", "al", "nv"
935 };
936
937 /* The preferred condition codes for SVE conditions. */
938 static const char *const aarch64_sve_condition_codes[] =
939 {
940 "none", "any", "nlast", "last", "first", "nfrst", "vs", "vc",
941 "pmore", "plast", "tcont", "tstop", "gt", "le", "al", "nv"
942 };
943
944 /* Return the assembly token for svpattern value VALUE. */
945
946 static const char *
947 svpattern_token (enum aarch64_svpattern pattern)
948 {
949 switch (pattern)
950 {
951 #define CASE(UPPER, LOWER, VALUE) case AARCH64_SV_##UPPER: return #LOWER;
952 AARCH64_FOR_SVPATTERN (CASE)
953 #undef CASE
954 case AARCH64_NUM_SVPATTERNS:
955 break;
956 }
957 gcc_unreachable ();
958 }
959
960 /* Return the location of a piece that is known to be passed or returned
961 in registers. FIRST_ZR is the first unused vector argument register
962 and FIRST_PR is the first unused predicate argument register. */
963
964 rtx
965 pure_scalable_type_info::piece::get_rtx (unsigned int first_zr,
966 unsigned int first_pr) const
967 {
968 gcc_assert (VECTOR_MODE_P (mode)
969 && first_zr + num_zr <= V0_REGNUM + NUM_FP_ARG_REGS
970 && first_pr + num_pr <= P0_REGNUM + NUM_PR_ARG_REGS);
971
972 if (num_zr > 0 && num_pr == 0)
973 return gen_rtx_REG (mode, first_zr);
974
975 if (num_zr == 0 && num_pr > 0)
976 return gen_rtx_REG (mode, first_pr);
977
978 gcc_unreachable ();
979 }
980
981 /* Return the total number of vector registers required by the PST. */
982
983 unsigned int
984 pure_scalable_type_info::num_zr () const
985 {
986 unsigned int res = 0;
987 for (unsigned int i = 0; i < pieces.length (); ++i)
988 res += pieces[i].num_zr;
989 return res;
990 }
991
992 /* Return the total number of predicate registers required by the PST. */
993
994 unsigned int
995 pure_scalable_type_info::num_pr () const
996 {
997 unsigned int res = 0;
998 for (unsigned int i = 0; i < pieces.length (); ++i)
999 res += pieces[i].num_pr;
1000 return res;
1001 }
1002
1003 /* Return the location of a PST that is known to be passed or returned
1004 in registers. FIRST_ZR is the first unused vector argument register
1005 and FIRST_PR is the first unused predicate argument register. */
1006
1007 rtx
1008 pure_scalable_type_info::get_rtx (machine_mode mode,
1009 unsigned int first_zr,
1010 unsigned int first_pr) const
1011 {
1012 /* Try to return a single REG if possible. This leads to better
1013 code generation; it isn't required for correctness. */
1014 if (mode == pieces[0].mode)
1015 {
1016 gcc_assert (pieces.length () == 1);
1017 return pieces[0].get_rtx (first_zr, first_pr);
1018 }
1019
1020 /* Build up a PARALLEL that contains the individual pieces. */
1021 rtvec rtxes = rtvec_alloc (pieces.length ());
1022 for (unsigned int i = 0; i < pieces.length (); ++i)
1023 {
1024 rtx reg = pieces[i].get_rtx (first_zr, first_pr);
1025 rtx offset = gen_int_mode (pieces[i].offset, Pmode);
1026 RTVEC_ELT (rtxes, i) = gen_rtx_EXPR_LIST (VOIDmode, reg, offset);
1027 first_zr += pieces[i].num_zr;
1028 first_pr += pieces[i].num_pr;
1029 }
1030 return gen_rtx_PARALLEL (mode, rtxes);
1031 }
1032
1033 /* Analyze whether TYPE is a Pure Scalable Type according to the rules
1034 in the AAPCS64. */
1035
1036 pure_scalable_type_info::analysis_result
1037 pure_scalable_type_info::analyze (const_tree type)
1038 {
1039 /* Prevent accidental reuse. */
1040 gcc_assert (pieces.is_empty ());
1041
1042 /* No code will be generated for erroneous types, so we won't establish
1043 an ABI mapping. */
1044 if (type == error_mark_node)
1045 return NO_ABI_IDENTITY;
1046
1047 /* Zero-sized types disappear in the language->ABI mapping. */
1048 if (TYPE_SIZE (type) && integer_zerop (TYPE_SIZE (type)))
1049 return NO_ABI_IDENTITY;
1050
1051 /* Check for SVTs, SPTs, and built-in tuple types that map to PSTs. */
1052 piece p = {};
1053 if (aarch64_sve::builtin_type_p (type, &p.num_zr, &p.num_pr))
1054 {
1055 machine_mode mode = TYPE_MODE_RAW (type);
1056 gcc_assert (VECTOR_MODE_P (mode)
1057 && (!TARGET_SVE || aarch64_sve_mode_p (mode)));
1058
1059 p.mode = p.orig_mode = mode;
1060 add_piece (p);
1061 return IS_PST;
1062 }
1063
1064 /* Check for user-defined PSTs. */
1065 if (TREE_CODE (type) == ARRAY_TYPE)
1066 return analyze_array (type);
1067 if (TREE_CODE (type) == RECORD_TYPE)
1068 return analyze_record (type);
1069
1070 return ISNT_PST;
1071 }
1072
1073 /* Analyze a type that is known not to be passed or returned in memory.
1074 Return true if it has an ABI identity and is a Pure Scalable Type. */
1075
1076 bool
1077 pure_scalable_type_info::analyze_registers (const_tree type)
1078 {
1079 analysis_result result = analyze (type);
1080 gcc_assert (result != DOESNT_MATTER);
1081 return result == IS_PST;
1082 }
1083
1084 /* Subroutine of analyze for handling ARRAY_TYPEs. */
1085
1086 pure_scalable_type_info::analysis_result
1087 pure_scalable_type_info::analyze_array (const_tree type)
1088 {
1089 /* Analyze the element type. */
1090 pure_scalable_type_info element_info;
1091 analysis_result result = element_info.analyze (TREE_TYPE (type));
1092 if (result != IS_PST)
1093 return result;
1094
1095 /* An array of unknown, flexible or variable length will be passed and
1096 returned by reference whatever we do. */
1097 tree nelts_minus_one = array_type_nelts_minus_one (type);
1098 if (!tree_fits_uhwi_p (nelts_minus_one))
1099 return DOESNT_MATTER;
1100
1101 /* Likewise if the array is constant-sized but too big to be interesting.
1102 The double checks against MAX_PIECES are to protect against overflow. */
1103 unsigned HOST_WIDE_INT count = tree_to_uhwi (nelts_minus_one);
1104 if (count > MAX_PIECES)
1105 return DOESNT_MATTER;
1106 count += 1;
1107 if (count * element_info.pieces.length () > MAX_PIECES)
1108 return DOESNT_MATTER;
1109
1110 /* The above checks should have weeded out elements of unknown size. */
1111 poly_uint64 element_bytes;
1112 if (!poly_int_tree_p (TYPE_SIZE_UNIT (TREE_TYPE (type)), &element_bytes))
1113 gcc_unreachable ();
1114
1115 /* Build up the list of individual vectors and predicates. */
1116 gcc_assert (!element_info.pieces.is_empty ());
1117 for (unsigned int i = 0; i < count; ++i)
1118 for (unsigned int j = 0; j < element_info.pieces.length (); ++j)
1119 {
1120 piece p = element_info.pieces[j];
1121 p.offset += i * element_bytes;
1122 add_piece (p);
1123 }
1124 return IS_PST;
1125 }
1126
1127 /* Subroutine of analyze for handling RECORD_TYPEs. */
1128
1129 pure_scalable_type_info::analysis_result
1130 pure_scalable_type_info::analyze_record (const_tree type)
1131 {
1132 for (tree field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
1133 {
1134 if (TREE_CODE (field) != FIELD_DECL)
1135 continue;
1136
1137 /* Zero-sized fields disappear in the language->ABI mapping. */
1138 if (DECL_SIZE (field) && integer_zerop (DECL_SIZE (field)))
1139 continue;
1140
1141 /* All fields with an ABI identity must be PSTs for the record as
1142 a whole to be a PST. If any individual field is too big to be
1143 interesting then the record is too. */
1144 pure_scalable_type_info field_info;
1145 analysis_result subresult = field_info.analyze (TREE_TYPE (field));
1146 if (subresult == NO_ABI_IDENTITY)
1147 continue;
1148 if (subresult != IS_PST)
1149 return subresult;
1150
1151 /* Since all previous fields are PSTs, we ought to be able to track
1152 the field offset using poly_ints. */
1153 tree bitpos = bit_position (field);
1154 gcc_assert (poly_int_tree_p (bitpos));
1155
1156 /* For the same reason, it shouldn't be possible to create a PST field
1157 whose offset isn't byte-aligned. */
1158 poly_widest_int wide_bytepos = exact_div (wi::to_poly_widest (bitpos),
1159 BITS_PER_UNIT);
1160
1161 /* Punt if the record is too big to be interesting. */
1162 poly_uint64 bytepos;
1163 if (!wide_bytepos.to_uhwi (&bytepos)
1164 || pieces.length () + field_info.pieces.length () > MAX_PIECES)
1165 return DOESNT_MATTER;
1166
1167 /* Add the individual vectors and predicates in the field to the
1168 record's list. */
1169 gcc_assert (!field_info.pieces.is_empty ());
1170 for (unsigned int i = 0; i < field_info.pieces.length (); ++i)
1171 {
1172 piece p = field_info.pieces[i];
1173 p.offset += bytepos;
1174 add_piece (p);
1175 }
1176 }
1177 /* Empty structures disappear in the language->ABI mapping. */
1178 return pieces.is_empty () ? NO_ABI_IDENTITY : IS_PST;
1179 }
1180
1181 /* Add P to the list of pieces in the type. */
1182
1183 void
1184 pure_scalable_type_info::add_piece (const piece &p)
1185 {
1186 /* Try to fold the new piece into the previous one to form a
1187 single-mode PST. For example, if we see three consecutive vectors
1188 of the same mode, we can represent them using the corresponding
1189 3-tuple mode.
1190
1191 This is purely an optimization. */
1192 if (!pieces.is_empty ())
1193 {
1194 piece &prev = pieces.last ();
1195 gcc_assert (VECTOR_MODE_P (p.mode) && VECTOR_MODE_P (prev.mode));
1196 unsigned int nelems1, nelems2;
1197 if (prev.orig_mode == p.orig_mode
1198 && GET_MODE_CLASS (p.orig_mode) != MODE_VECTOR_BOOL
1199 && known_eq (prev.offset + GET_MODE_SIZE (prev.mode), p.offset)
1200 && constant_multiple_p (GET_MODE_NUNITS (prev.mode),
1201 GET_MODE_NUNITS (p.orig_mode), &nelems1)
1202 && constant_multiple_p (GET_MODE_NUNITS (p.mode),
1203 GET_MODE_NUNITS (p.orig_mode), &nelems2)
1204 && targetm.array_mode (p.orig_mode,
1205 nelems1 + nelems2).exists (&prev.mode))
1206 {
1207 prev.num_zr += p.num_zr;
1208 prev.num_pr += p.num_pr;
1209 return;
1210 }
1211 }
1212 pieces.quick_push (p);
1213 }
1214
1215 /* Return true if at least one possible value of type TYPE includes at
1216 least one object of Pure Scalable Type, in the sense of the AAPCS64.
1217
1218 This is a relatively expensive test for some types, so it should
1219 generally be made as late as possible. */
1220
1221 static bool
1222 aarch64_some_values_include_pst_objects_p (const_tree type)
1223 {
1224 if (TYPE_SIZE (type) && integer_zerop (TYPE_SIZE (type)))
1225 return false;
1226
1227 if (aarch64_sve::builtin_type_p (type))
1228 return true;
1229
1230 if (TREE_CODE (type) == ARRAY_TYPE || TREE_CODE (type) == COMPLEX_TYPE)
1231 return aarch64_some_values_include_pst_objects_p (TREE_TYPE (type));
1232
1233 if (RECORD_OR_UNION_TYPE_P (type))
1234 for (tree field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
1235 if (TREE_CODE (field) == FIELD_DECL
1236 && aarch64_some_values_include_pst_objects_p (TREE_TYPE (field)))
1237 return true;
1238
1239 return false;
1240 }
1241
1242 /* Return the descriptor of the SIMD ABI. */
1243
1244 static const predefined_function_abi &
1245 aarch64_simd_abi (void)
1246 {
1247 predefined_function_abi &simd_abi = function_abis[ARM_PCS_SIMD];
1248 if (!simd_abi.initialized_p ())
1249 {
1250 HARD_REG_SET full_reg_clobbers
1251 = default_function_abi.full_reg_clobbers ();
1252 for (int regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1253 if (FP_SIMD_SAVED_REGNUM_P (regno))
1254 CLEAR_HARD_REG_BIT (full_reg_clobbers, regno);
1255 simd_abi.initialize (ARM_PCS_SIMD, full_reg_clobbers);
1256 }
1257 return simd_abi;
1258 }
1259
1260 /* Return the descriptor of the SVE PCS. */
1261
1262 static const predefined_function_abi &
1263 aarch64_sve_abi (void)
1264 {
1265 predefined_function_abi &sve_abi = function_abis[ARM_PCS_SVE];
1266 if (!sve_abi.initialized_p ())
1267 {
1268 HARD_REG_SET full_reg_clobbers
1269 = default_function_abi.full_reg_clobbers ();
1270 for (int regno = V8_REGNUM; regno <= V23_REGNUM; ++regno)
1271 CLEAR_HARD_REG_BIT (full_reg_clobbers, regno);
1272 for (int regno = P4_REGNUM; regno <= P15_REGNUM; ++regno)
1273 CLEAR_HARD_REG_BIT (full_reg_clobbers, regno);
1274 sve_abi.initialize (ARM_PCS_SVE, full_reg_clobbers);
1275 }
1276 return sve_abi;
1277 }
1278
1279 /* If X is an UNSPEC_SALT_ADDR expression, return the address that it
1280 wraps, otherwise return X itself. */
1281
1282 static rtx
1283 strip_salt (rtx x)
1284 {
1285 rtx search = x;
1286 if (GET_CODE (search) == CONST)
1287 search = XEXP (search, 0);
1288 if (GET_CODE (search) == UNSPEC && XINT (search, 1) == UNSPEC_SALT_ADDR)
1289 x = XVECEXP (search, 0, 0);
1290 return x;
1291 }
1292
1293 /* Like strip_offset, but also strip any UNSPEC_SALT_ADDR from the
1294 expression. */
1295
1296 static rtx
1297 strip_offset_and_salt (rtx addr, poly_int64 *offset)
1298 {
1299 return strip_salt (strip_offset (addr, offset));
1300 }
1301
1302 /* Generate code to enable conditional branches in functions over 1 MiB. */
1303 const char *
1304 aarch64_gen_far_branch (rtx * operands, int pos_label, const char * dest,
1305 const char * branch_format)
1306 {
1307 rtx_code_label * tmp_label = gen_label_rtx ();
1308 char label_buf[256];
1309 char buffer[128];
1310 ASM_GENERATE_INTERNAL_LABEL (label_buf, dest,
1311 CODE_LABEL_NUMBER (tmp_label));
1312 const char *label_ptr = targetm.strip_name_encoding (label_buf);
1313 rtx dest_label = operands[pos_label];
1314 operands[pos_label] = tmp_label;
1315
1316 snprintf (buffer, sizeof (buffer), "%s%s", branch_format, label_ptr);
1317 output_asm_insn (buffer, operands);
1318
1319 snprintf (buffer, sizeof (buffer), "b\t%%l%d\n%s:", pos_label, label_ptr);
1320 operands[pos_label] = dest_label;
1321 output_asm_insn (buffer, operands);
1322 return "";
1323 }
1324
1325 void
1326 aarch64_err_no_fpadvsimd (machine_mode mode)
1327 {
1328 if (TARGET_GENERAL_REGS_ONLY)
1329 if (FLOAT_MODE_P (mode))
1330 error ("%qs is incompatible with the use of floating-point types",
1331 "-mgeneral-regs-only");
1332 else
1333 error ("%qs is incompatible with the use of vector types",
1334 "-mgeneral-regs-only");
1335 else
1336 if (FLOAT_MODE_P (mode))
1337 error ("%qs feature modifier is incompatible with the use of"
1338 " floating-point types", "+nofp");
1339 else
1340 error ("%qs feature modifier is incompatible with the use of"
1341 " vector types", "+nofp");
1342 }
1343
1344 /* Report when we try to do something that requires SVE when SVE is disabled.
1345 This is an error of last resort and isn't very high-quality. It usually
1346 involves attempts to measure the vector length in some way. */
1347 static void
1348 aarch64_report_sve_required (void)
1349 {
1350 static bool reported_p = false;
1351
1352 /* Avoid reporting a slew of messages for a single oversight. */
1353 if (reported_p)
1354 return;
1355
1356 error ("this operation requires the SVE ISA extension");
1357 inform (input_location, "you can enable SVE using the command-line"
1358 " option %<-march%>, or by using the %<target%>"
1359 " attribute or pragma");
1360 reported_p = true;
1361 }
1362
1363 /* Return true if REGNO is P0-P15 or one of the special FFR-related
1364 registers. */
1365 inline bool
1366 pr_or_ffr_regnum_p (unsigned int regno)
1367 {
1368 return PR_REGNUM_P (regno) || regno == FFR_REGNUM || regno == FFRT_REGNUM;
1369 }
1370
1371 /* Implement TARGET_IRA_CHANGE_PSEUDO_ALLOCNO_CLASS.
1372 The register allocator chooses POINTER_AND_FP_REGS if FP_REGS and
1373 GENERAL_REGS have the same cost - even if POINTER_AND_FP_REGS has a much
1374 higher cost. POINTER_AND_FP_REGS is also used if the cost of both FP_REGS
1375 and GENERAL_REGS is lower than the memory cost (in this case the best class
1376 is the lowest cost one). Using POINTER_AND_FP_REGS irrespectively of its
1377 cost results in bad allocations with many redundant int<->FP moves which
1378 are expensive on various cores.
1379 To avoid this we don't allow POINTER_AND_FP_REGS as the allocno class, but
1380 force a decision between FP_REGS and GENERAL_REGS. We use the allocno class
1381 if it isn't POINTER_AND_FP_REGS. Similarly, use the best class if it isn't
1382 POINTER_AND_FP_REGS. Otherwise set the allocno class depending on the mode.
1383 The result of this is that it is no longer inefficient to have a higher
1384 memory move cost than the register move cost.
1385 */
1386
1387 static reg_class_t
1388 aarch64_ira_change_pseudo_allocno_class (int regno, reg_class_t allocno_class,
1389 reg_class_t best_class)
1390 {
1391 machine_mode mode;
1392
1393 if (!reg_class_subset_p (GENERAL_REGS, allocno_class)
1394 || !reg_class_subset_p (FP_REGS, allocno_class))
1395 return allocno_class;
1396
1397 if (!reg_class_subset_p (GENERAL_REGS, best_class)
1398 || !reg_class_subset_p (FP_REGS, best_class))
1399 return best_class;
1400
1401 mode = PSEUDO_REGNO_MODE (regno);
1402 return FLOAT_MODE_P (mode) || VECTOR_MODE_P (mode) ? FP_REGS : GENERAL_REGS;
1403 }
1404
1405 static unsigned int
1406 aarch64_min_divisions_for_recip_mul (machine_mode mode)
1407 {
1408 if (GET_MODE_UNIT_SIZE (mode) == 4)
1409 return aarch64_tune_params.min_div_recip_mul_sf;
1410 return aarch64_tune_params.min_div_recip_mul_df;
1411 }
1412
1413 /* Return the reassociation width of treeop OPC with mode MODE. */
1414 static int
1415 aarch64_reassociation_width (unsigned opc, machine_mode mode)
1416 {
1417 if (VECTOR_MODE_P (mode))
1418 return aarch64_tune_params.vec_reassoc_width;
1419 if (INTEGRAL_MODE_P (mode))
1420 return aarch64_tune_params.int_reassoc_width;
1421 /* Reassociation reduces the number of FMAs which may result in worse
1422 performance. Use a per-CPU setting for FMA reassociation which allows
1423 narrow CPUs with few FP pipes to switch it off (value of 1), and wider
1424 CPUs with many FP pipes to enable reassociation.
1425 Since the reassociation pass doesn't understand FMA at all, assume
1426 that any FP addition might turn into FMA. */
1427 if (FLOAT_MODE_P (mode))
1428 return opc == PLUS_EXPR ? aarch64_tune_params.fma_reassoc_width
1429 : aarch64_tune_params.fp_reassoc_width;
1430 return 1;
1431 }
1432
1433 /* Provide a mapping from gcc register numbers to dwarf register numbers. */
1434 unsigned
1435 aarch64_debugger_regno (unsigned regno)
1436 {
1437 if (GP_REGNUM_P (regno))
1438 return AARCH64_DWARF_R0 + regno - R0_REGNUM;
1439 else if (regno == SP_REGNUM)
1440 return AARCH64_DWARF_SP;
1441 else if (FP_REGNUM_P (regno))
1442 return AARCH64_DWARF_V0 + regno - V0_REGNUM;
1443 else if (PR_REGNUM_P (regno))
1444 return AARCH64_DWARF_P0 + regno - P0_REGNUM;
1445 else if (regno == VG_REGNUM)
1446 return AARCH64_DWARF_VG;
1447
1448 /* Return values >= DWARF_FRAME_REGISTERS indicate that there is no
1449 equivalent DWARF register. */
1450 return DWARF_FRAME_REGISTERS;
1451 }
1452
1453 /* Implement TARGET_DWARF_FRAME_REG_MODE. */
1454 static machine_mode
1455 aarch64_dwarf_frame_reg_mode (int regno)
1456 {
1457 /* Predicate registers are call-clobbered in the EH ABI (which is
1458 ARM_PCS_AAPCS64), so they should not be described by CFI.
1459 Their size changes as VL changes, so any values computed by
1460 __builtin_init_dwarf_reg_size_table might not be valid for
1461 all frames. */
1462 if (PR_REGNUM_P (regno))
1463 return VOIDmode;
1464 return default_dwarf_frame_reg_mode (regno);
1465 }
1466
1467 /* Implement TARGET_OUTPUT_CFI_DIRECTIVE. */
1468 static bool
1469 aarch64_output_cfi_directive (FILE *f, dw_cfi_ref cfi)
1470 {
1471 bool found = false;
1472 if (cfi->dw_cfi_opc == DW_CFA_AARCH64_negate_ra_state)
1473 {
1474 fprintf (f, "\t.cfi_negate_ra_state\n");
1475 found = true;
1476 }
1477 return found;
1478 }
1479
1480 /* Implement TARGET_DW_CFI_OPRND1_DESC. */
1481 static bool
1482 aarch64_dw_cfi_oprnd1_desc (dwarf_call_frame_info cfi_opc,
1483 dw_cfi_oprnd_type &oprnd_type)
1484 {
1485 if (cfi_opc == DW_CFA_AARCH64_negate_ra_state)
1486 {
1487 oprnd_type = dw_cfi_oprnd_unused;
1488 return true;
1489 }
1490 return false;
1491 }
1492
1493 /* If X is a CONST_DOUBLE, return its bit representation as a constant
1494 integer, otherwise return X unmodified. */
1495 static rtx
1496 aarch64_bit_representation (rtx x)
1497 {
1498 if (CONST_DOUBLE_P (x))
1499 x = gen_lowpart (int_mode_for_mode (GET_MODE (x)).require (), x);
1500 return x;
1501 }
1502
1503 /* Return an estimate for the number of quadwords in an SVE vector. This is
1504 equivalent to the number of Advanced SIMD vectors in an SVE vector. */
1505 static unsigned int
1506 aarch64_estimated_sve_vq ()
1507 {
1508 return estimated_poly_value (BITS_PER_SVE_VECTOR) / 128;
1509 }
1510
1511 /* Return true if MODE is an SVE predicate mode. */
1512 static bool
1513 aarch64_sve_pred_mode_p (machine_mode mode)
1514 {
1515 return (TARGET_SVE
1516 && (mode == VNx16BImode
1517 || mode == VNx8BImode
1518 || mode == VNx4BImode
1519 || mode == VNx2BImode));
1520 }
1521
1522 /* Three mutually-exclusive flags describing a vector or predicate type. */
1523 const unsigned int VEC_ADVSIMD = 1;
1524 const unsigned int VEC_SVE_DATA = 2;
1525 const unsigned int VEC_SVE_PRED = 4;
1526 /* Indicates a structure of 2, 3 or 4 vectors or predicates. */
1527 const unsigned int VEC_STRUCT = 8;
1528 /* Can be used in combination with VEC_SVE_DATA to indicate that the
1529 vector has fewer significant bytes than a full SVE vector. */
1530 const unsigned int VEC_PARTIAL = 16;
1531 /* Useful combinations of the above. */
1532 const unsigned int VEC_ANY_SVE = VEC_SVE_DATA | VEC_SVE_PRED;
1533 const unsigned int VEC_ANY_DATA = VEC_ADVSIMD | VEC_SVE_DATA;
1534
1535 /* Return a set of flags describing the vector properties of mode MODE.
1536 If ANY_TARGET_P is false (the default), ignore modes that are not supported
1537 by the current target. Otherwise categorize the modes that can be used
1538 with the set of all targets supported by the port. */
1539
1540 static unsigned int
1541 aarch64_classify_vector_mode (machine_mode mode, bool any_target_p = false)
1542 {
1543 if (aarch64_sve_pred_mode_p (mode))
1544 return VEC_SVE_PRED;
1545
1546 /* Make the decision based on the mode's enum value rather than its
1547 properties, so that we keep the correct classification regardless
1548 of -msve-vector-bits. */
1549 switch (mode)
1550 {
1551 /* Partial SVE QI vectors. */
1552 case E_VNx2QImode:
1553 case E_VNx4QImode:
1554 case E_VNx8QImode:
1555 /* Partial SVE HI vectors. */
1556 case E_VNx2HImode:
1557 case E_VNx4HImode:
1558 /* Partial SVE SI vector. */
1559 case E_VNx2SImode:
1560 /* Partial SVE HF vectors. */
1561 case E_VNx2HFmode:
1562 case E_VNx4HFmode:
1563 /* Partial SVE BF vectors. */
1564 case E_VNx2BFmode:
1565 case E_VNx4BFmode:
1566 /* Partial SVE SF vector. */
1567 case E_VNx2SFmode:
1568 return (TARGET_SVE || any_target_p) ? VEC_SVE_DATA | VEC_PARTIAL : 0;
1569
1570 case E_VNx16QImode:
1571 case E_VNx8HImode:
1572 case E_VNx4SImode:
1573 case E_VNx2DImode:
1574 case E_VNx8BFmode:
1575 case E_VNx8HFmode:
1576 case E_VNx4SFmode:
1577 case E_VNx2DFmode:
1578 return (TARGET_SVE || any_target_p) ? VEC_SVE_DATA : 0;
1579
1580 /* x2 SVE vectors. */
1581 case E_VNx32QImode:
1582 case E_VNx16HImode:
1583 case E_VNx8SImode:
1584 case E_VNx4DImode:
1585 case E_VNx16BFmode:
1586 case E_VNx16HFmode:
1587 case E_VNx8SFmode:
1588 case E_VNx4DFmode:
1589 /* x3 SVE vectors. */
1590 case E_VNx48QImode:
1591 case E_VNx24HImode:
1592 case E_VNx12SImode:
1593 case E_VNx6DImode:
1594 case E_VNx24BFmode:
1595 case E_VNx24HFmode:
1596 case E_VNx12SFmode:
1597 case E_VNx6DFmode:
1598 /* x4 SVE vectors. */
1599 case E_VNx64QImode:
1600 case E_VNx32HImode:
1601 case E_VNx16SImode:
1602 case E_VNx8DImode:
1603 case E_VNx32BFmode:
1604 case E_VNx32HFmode:
1605 case E_VNx16SFmode:
1606 case E_VNx8DFmode:
1607 return (TARGET_SVE || any_target_p) ? VEC_SVE_DATA | VEC_STRUCT : 0;
1608
1609 case E_OImode:
1610 case E_CImode:
1611 case E_XImode:
1612 return (TARGET_FLOAT || any_target_p) ? VEC_ADVSIMD | VEC_STRUCT : 0;
1613
1614 /* Structures of 64-bit Advanced SIMD vectors. */
1615 case E_V2x8QImode:
1616 case E_V2x4HImode:
1617 case E_V2x2SImode:
1618 case E_V2x1DImode:
1619 case E_V2x4BFmode:
1620 case E_V2x4HFmode:
1621 case E_V2x2SFmode:
1622 case E_V2x1DFmode:
1623 case E_V3x8QImode:
1624 case E_V3x4HImode:
1625 case E_V3x2SImode:
1626 case E_V3x1DImode:
1627 case E_V3x4BFmode:
1628 case E_V3x4HFmode:
1629 case E_V3x2SFmode:
1630 case E_V3x1DFmode:
1631 case E_V4x8QImode:
1632 case E_V4x4HImode:
1633 case E_V4x2SImode:
1634 case E_V4x1DImode:
1635 case E_V4x4BFmode:
1636 case E_V4x4HFmode:
1637 case E_V4x2SFmode:
1638 case E_V4x1DFmode:
1639 return (TARGET_FLOAT || any_target_p)
1640 ? VEC_ADVSIMD | VEC_STRUCT | VEC_PARTIAL : 0;
1641
1642 /* Structures of 128-bit Advanced SIMD vectors. */
1643 case E_V2x16QImode:
1644 case E_V2x8HImode:
1645 case E_V2x4SImode:
1646 case E_V2x2DImode:
1647 case E_V2x8BFmode:
1648 case E_V2x8HFmode:
1649 case E_V2x4SFmode:
1650 case E_V2x2DFmode:
1651 case E_V3x16QImode:
1652 case E_V3x8HImode:
1653 case E_V3x4SImode:
1654 case E_V3x2DImode:
1655 case E_V3x8BFmode:
1656 case E_V3x8HFmode:
1657 case E_V3x4SFmode:
1658 case E_V3x2DFmode:
1659 case E_V4x16QImode:
1660 case E_V4x8HImode:
1661 case E_V4x4SImode:
1662 case E_V4x2DImode:
1663 case E_V4x8BFmode:
1664 case E_V4x8HFmode:
1665 case E_V4x4SFmode:
1666 case E_V4x2DFmode:
1667 return (TARGET_FLOAT || any_target_p) ? VEC_ADVSIMD | VEC_STRUCT : 0;
1668
1669 /* 64-bit Advanced SIMD vectors. */
1670 case E_V8QImode:
1671 case E_V4HImode:
1672 case E_V2SImode:
1673 case E_V1DImode:
1674 case E_V4HFmode:
1675 case E_V4BFmode:
1676 case E_V2SFmode:
1677 case E_V1DFmode:
1678 /* 128-bit Advanced SIMD vectors. */
1679 case E_V16QImode:
1680 case E_V8HImode:
1681 case E_V4SImode:
1682 case E_V2DImode:
1683 case E_V8HFmode:
1684 case E_V8BFmode:
1685 case E_V4SFmode:
1686 case E_V2DFmode:
1687 return (TARGET_FLOAT || any_target_p) ? VEC_ADVSIMD : 0;
1688
1689 case E_VNx32BImode:
1690 case E_VNx64BImode:
1691 return TARGET_SVE ? VEC_SVE_PRED | VEC_STRUCT : 0;
1692
1693 default:
1694 return 0;
1695 }
1696 }
1697
1698 /* Like aarch64_classify_vector_mode, but also include modes that are used
1699 for memory operands but not register operands. Such modes do not count
1700 as real vector modes; they are just an internal construct to make things
1701 easier to describe. */
1702 static unsigned int
1703 aarch64_classify_vector_memory_mode (machine_mode mode)
1704 {
1705 switch (mode)
1706 {
1707 case VNx1SImode:
1708 case VNx1DImode:
1709 return TARGET_SVE ? VEC_SVE_DATA | VEC_PARTIAL : 0;
1710
1711 case VNx1TImode:
1712 return TARGET_SVE ? VEC_SVE_DATA : 0;
1713
1714 case VNx2TImode:
1715 case VNx3TImode:
1716 case VNx4TImode:
1717 return TARGET_SVE ? VEC_SVE_DATA | VEC_STRUCT : 0;
1718
1719 default:
1720 return aarch64_classify_vector_mode (mode);
1721 }
1722 }
1723
1724 /* Return true if MODE is any of the Advanced SIMD structure modes. */
1725 bool
1726 aarch64_advsimd_struct_mode_p (machine_mode mode)
1727 {
1728 unsigned int vec_flags = aarch64_classify_vector_mode (mode);
1729 return (vec_flags & VEC_ADVSIMD) && (vec_flags & VEC_STRUCT);
1730 }
1731
1732 /* Return true if MODE is an Advanced SIMD D-register structure mode. */
1733 static bool
1734 aarch64_advsimd_partial_struct_mode_p (machine_mode mode)
1735 {
1736 return (aarch64_classify_vector_mode (mode)
1737 == (VEC_ADVSIMD | VEC_STRUCT | VEC_PARTIAL));
1738 }
1739
1740 /* Return true if MODE is an Advanced SIMD Q-register structure mode. */
1741 static bool
1742 aarch64_advsimd_full_struct_mode_p (machine_mode mode)
1743 {
1744 return (aarch64_classify_vector_mode (mode) == (VEC_ADVSIMD | VEC_STRUCT));
1745 }
1746
1747 /* Return true if MODE is any of the data vector modes, including
1748 structure modes. */
1749 static bool
1750 aarch64_vector_data_mode_p (machine_mode mode)
1751 {
1752 return aarch64_classify_vector_mode (mode) & VEC_ANY_DATA;
1753 }
1754
1755 /* Return true if MODE is any form of SVE mode, including predicates,
1756 vectors and structures. */
1757 bool
1758 aarch64_sve_mode_p (machine_mode mode)
1759 {
1760 return aarch64_classify_vector_mode (mode) & VEC_ANY_SVE;
1761 }
1762
1763 /* Return true if MODE is an SVE data vector mode; either a single vector
1764 or a structure of vectors. */
1765 static bool
1766 aarch64_sve_data_mode_p (machine_mode mode)
1767 {
1768 return aarch64_classify_vector_mode (mode) & VEC_SVE_DATA;
1769 }
1770
1771 /* Return the number of defined bytes in one constituent vector of
1772 SVE mode MODE, which has vector flags VEC_FLAGS. */
1773 static poly_int64
1774 aarch64_vl_bytes (machine_mode mode, unsigned int vec_flags)
1775 {
1776 if (vec_flags & VEC_PARTIAL)
1777 /* A single partial vector. */
1778 return GET_MODE_SIZE (mode);
1779
1780 if (vec_flags & VEC_SVE_DATA)
1781 /* A single vector or a tuple. */
1782 return BYTES_PER_SVE_VECTOR;
1783
1784 /* A single predicate. */
1785 gcc_assert (vec_flags & VEC_SVE_PRED);
1786 return BYTES_PER_SVE_PRED;
1787 }
1788
1789 /* If MODE holds an array of vectors, return the number of vectors
1790 in the array, otherwise return 1. */
1791
1792 static unsigned int
1793 aarch64_ldn_stn_vectors (machine_mode mode)
1794 {
1795 unsigned int vec_flags = aarch64_classify_vector_mode (mode);
1796 if (vec_flags == (VEC_ADVSIMD | VEC_PARTIAL | VEC_STRUCT))
1797 return exact_div (GET_MODE_SIZE (mode), 8).to_constant ();
1798 if (vec_flags == (VEC_ADVSIMD | VEC_STRUCT))
1799 return exact_div (GET_MODE_SIZE (mode), 16).to_constant ();
1800 if (vec_flags == (VEC_SVE_DATA | VEC_STRUCT))
1801 return exact_div (GET_MODE_SIZE (mode),
1802 BYTES_PER_SVE_VECTOR).to_constant ();
1803 return 1;
1804 }
1805
1806 /* Given an Advanced SIMD vector mode MODE and a tuple size NELEMS, return the
1807 corresponding vector structure mode. */
1808 opt_machine_mode
1809 aarch64_advsimd_vector_array_mode (machine_mode mode,
1810 unsigned HOST_WIDE_INT nelems)
1811 {
1812 unsigned int flags = VEC_ADVSIMD | VEC_STRUCT;
1813 if (known_eq (GET_MODE_SIZE (mode), 8))
1814 flags |= VEC_PARTIAL;
1815
1816 machine_mode struct_mode;
1817 FOR_EACH_MODE_IN_CLASS (struct_mode, GET_MODE_CLASS (mode))
1818 if (aarch64_classify_vector_mode (struct_mode) == flags
1819 && GET_MODE_INNER (struct_mode) == GET_MODE_INNER (mode)
1820 && known_eq (GET_MODE_NUNITS (struct_mode),
1821 GET_MODE_NUNITS (mode) * nelems))
1822 return struct_mode;
1823 return opt_machine_mode ();
1824 }
1825
1826 /* Return the SVE vector mode that has NUNITS elements of mode INNER_MODE. */
1827
1828 opt_machine_mode
1829 aarch64_sve_data_mode (scalar_mode inner_mode, poly_uint64 nunits)
1830 {
1831 enum mode_class mclass = (is_a <scalar_float_mode> (inner_mode)
1832 ? MODE_VECTOR_FLOAT : MODE_VECTOR_INT);
1833 machine_mode mode;
1834 FOR_EACH_MODE_IN_CLASS (mode, mclass)
1835 if (inner_mode == GET_MODE_INNER (mode)
1836 && known_eq (nunits, GET_MODE_NUNITS (mode))
1837 && aarch64_sve_data_mode_p (mode))
1838 return mode;
1839 return opt_machine_mode ();
1840 }
1841
1842 /* Implement target hook TARGET_ARRAY_MODE. */
1843 static opt_machine_mode
1844 aarch64_array_mode (machine_mode mode, unsigned HOST_WIDE_INT nelems)
1845 {
1846 if (TARGET_SVE && GET_MODE_CLASS (mode) == MODE_VECTOR_BOOL)
1847 {
1848 /* Use VNx32BI and VNx64BI for tuples of predicates, but explicitly
1849 reject giving a mode to other array sizes. Using integer modes
1850 requires a round trip through memory and generates terrible code. */
1851 if (nelems == 1)
1852 return mode;
1853 if (mode == VNx16BImode && nelems == 2)
1854 return VNx32BImode;
1855 if (mode == VNx16BImode && nelems == 4)
1856 return VNx64BImode;
1857 return BLKmode;
1858 }
1859
1860 auto flags = aarch64_classify_vector_mode (mode);
1861 if (flags == VEC_SVE_DATA && IN_RANGE (nelems, 2, 4))
1862 return aarch64_sve_data_mode (GET_MODE_INNER (mode),
1863 GET_MODE_NUNITS (mode) * nelems);
1864
1865 if (flags == VEC_ADVSIMD && IN_RANGE (nelems, 2, 4))
1866 return aarch64_advsimd_vector_array_mode (mode, nelems);
1867
1868 return opt_machine_mode ();
1869 }
1870
1871 /* Implement target hook TARGET_ARRAY_MODE_SUPPORTED_P. */
1872 static bool
1873 aarch64_array_mode_supported_p (machine_mode mode,
1874 unsigned HOST_WIDE_INT nelems)
1875 {
1876 if (TARGET_BASE_SIMD
1877 && (AARCH64_VALID_SIMD_QREG_MODE (mode)
1878 || AARCH64_VALID_SIMD_DREG_MODE (mode))
1879 && (nelems >= 2 && nelems <= 4))
1880 return true;
1881
1882 return false;
1883 }
1884
1885 /* MODE is some form of SVE vector mode. For data modes, return the number
1886 of vector register bits that each element of MODE occupies, such as 64
1887 for both VNx2DImode and VNx2SImode (where each 32-bit value is stored
1888 in a 64-bit container). For predicate modes, return the number of
1889 data bits controlled by each significant predicate bit. */
1890
1891 static unsigned int
1892 aarch64_sve_container_bits (machine_mode mode)
1893 {
1894 unsigned int vec_flags = aarch64_classify_vector_mode (mode);
1895 poly_uint64 vector_bits = (vec_flags & (VEC_PARTIAL | VEC_SVE_PRED)
1896 ? BITS_PER_SVE_VECTOR
1897 : GET_MODE_BITSIZE (mode));
1898 return vector_element_size (vector_bits, GET_MODE_NUNITS (mode));
1899 }
1900
1901 /* Return the SVE predicate mode to use for elements that have
1902 ELEM_NBYTES bytes, if such a mode exists. */
1903
1904 opt_machine_mode
1905 aarch64_sve_pred_mode (unsigned int elem_nbytes)
1906 {
1907 if (TARGET_SVE)
1908 {
1909 if (elem_nbytes == 1)
1910 return VNx16BImode;
1911 if (elem_nbytes == 2)
1912 return VNx8BImode;
1913 if (elem_nbytes == 4)
1914 return VNx4BImode;
1915 if (elem_nbytes == 8)
1916 return VNx2BImode;
1917 }
1918 return opt_machine_mode ();
1919 }
1920
1921 /* Return the SVE predicate mode that should be used to control
1922 SVE mode MODE. */
1923
1924 machine_mode
1925 aarch64_sve_pred_mode (machine_mode mode)
1926 {
1927 unsigned int bits = aarch64_sve_container_bits (mode);
1928 return aarch64_sve_pred_mode (bits / BITS_PER_UNIT).require ();
1929 }
1930
1931 /* Implement TARGET_VECTORIZE_GET_MASK_MODE. */
1932
1933 static opt_machine_mode
1934 aarch64_get_mask_mode (machine_mode mode)
1935 {
1936 unsigned int vec_flags = aarch64_classify_vector_mode (mode);
1937 if (vec_flags & VEC_SVE_DATA)
1938 return aarch64_sve_pred_mode (mode);
1939
1940 return default_get_mask_mode (mode);
1941 }
1942
1943 /* Return the integer element mode associated with SVE mode MODE. */
1944
1945 static scalar_int_mode
1946 aarch64_sve_element_int_mode (machine_mode mode)
1947 {
1948 poly_uint64 vector_bits = (GET_MODE_CLASS (mode) == MODE_VECTOR_BOOL
1949 ? BITS_PER_SVE_VECTOR
1950 : GET_MODE_BITSIZE (mode));
1951 unsigned int elt_bits = vector_element_size (vector_bits,
1952 GET_MODE_NUNITS (mode));
1953 return int_mode_for_size (elt_bits, 0).require ();
1954 }
1955
1956 /* Return an integer element mode that contains exactly
1957 aarch64_sve_container_bits (MODE) bits. This is wider than
1958 aarch64_sve_element_int_mode if MODE is a partial vector,
1959 otherwise it's the same. */
1960
1961 static scalar_int_mode
1962 aarch64_sve_container_int_mode (machine_mode mode)
1963 {
1964 return int_mode_for_size (aarch64_sve_container_bits (mode), 0).require ();
1965 }
1966
1967 /* Return the integer vector mode associated with SVE mode MODE.
1968 Unlike related_int_vector_mode, this can handle the case in which
1969 MODE is a predicate (and thus has a different total size). */
1970
1971 machine_mode
1972 aarch64_sve_int_mode (machine_mode mode)
1973 {
1974 scalar_int_mode int_mode = aarch64_sve_element_int_mode (mode);
1975 return aarch64_sve_data_mode (int_mode, GET_MODE_NUNITS (mode)).require ();
1976 }
1977
1978 /* Look for a vector mode with the same classification as VEC_MODE,
1979 but with each group of FACTOR elements coalesced into a single element.
1980 In other words, look for a mode in which the elements are FACTOR times
1981 larger and in which the number of elements is FACTOR times smaller.
1982
1983 Return the mode found, if one exists. */
1984
1985 static opt_machine_mode
1986 aarch64_coalesce_units (machine_mode vec_mode, unsigned int factor)
1987 {
1988 auto elt_bits = vector_element_size (GET_MODE_BITSIZE (vec_mode),
1989 GET_MODE_NUNITS (vec_mode));
1990 auto vec_flags = aarch64_classify_vector_mode (vec_mode);
1991 if (vec_flags & VEC_SVE_PRED)
1992 {
1993 if (known_eq (GET_MODE_SIZE (vec_mode), BYTES_PER_SVE_PRED))
1994 return aarch64_sve_pred_mode (elt_bits * factor);
1995 return {};
1996 }
1997
1998 scalar_mode new_elt_mode;
1999 if (!int_mode_for_size (elt_bits * factor, false).exists (&new_elt_mode))
2000 return {};
2001
2002 if (vec_flags == VEC_ADVSIMD)
2003 {
2004 auto mode = aarch64_simd_container_mode (new_elt_mode,
2005 GET_MODE_BITSIZE (vec_mode));
2006 if (mode != word_mode)
2007 return mode;
2008 }
2009 else if (vec_flags & VEC_SVE_DATA)
2010 {
2011 poly_uint64 new_nunits;
2012 if (multiple_p (GET_MODE_NUNITS (vec_mode), factor, &new_nunits))
2013 return aarch64_sve_data_mode (new_elt_mode, new_nunits);
2014 }
2015 return {};
2016 }
2017
2018 /* Implement TARGET_VECTORIZE_RELATED_MODE. */
2019
2020 static opt_machine_mode
2021 aarch64_vectorize_related_mode (machine_mode vector_mode,
2022 scalar_mode element_mode,
2023 poly_uint64 nunits)
2024 {
2025 unsigned int vec_flags = aarch64_classify_vector_mode (vector_mode);
2026
2027 /* If we're operating on SVE vectors, try to return an SVE mode. */
2028 poly_uint64 sve_nunits;
2029 if ((vec_flags & VEC_SVE_DATA)
2030 && multiple_p (BYTES_PER_SVE_VECTOR,
2031 GET_MODE_SIZE (element_mode), &sve_nunits))
2032 {
2033 machine_mode sve_mode;
2034 if (maybe_ne (nunits, 0U))
2035 {
2036 /* Try to find a full or partial SVE mode with exactly
2037 NUNITS units. */
2038 if (multiple_p (sve_nunits, nunits)
2039 && aarch64_sve_data_mode (element_mode,
2040 nunits).exists (&sve_mode))
2041 return sve_mode;
2042 }
2043 else
2044 {
2045 /* Take the preferred number of units from the number of bytes
2046 that fit in VECTOR_MODE. We always start by "autodetecting"
2047 a full vector mode with preferred_simd_mode, so vectors
2048 chosen here will also be full vector modes. Then
2049 autovectorize_vector_modes tries smaller starting modes
2050 and thus smaller preferred numbers of units. */
2051 sve_nunits = ordered_min (sve_nunits, GET_MODE_SIZE (vector_mode));
2052 if (aarch64_sve_data_mode (element_mode,
2053 sve_nunits).exists (&sve_mode))
2054 return sve_mode;
2055 }
2056 }
2057
2058 /* Prefer to use 1 128-bit vector instead of 2 64-bit vectors. */
2059 if (TARGET_SIMD
2060 && (vec_flags & VEC_ADVSIMD)
2061 && known_eq (nunits, 0U)
2062 && known_eq (GET_MODE_BITSIZE (vector_mode), 64U)
2063 && maybe_ge (GET_MODE_BITSIZE (element_mode)
2064 * GET_MODE_NUNITS (vector_mode), 128U))
2065 {
2066 machine_mode res = aarch64_simd_container_mode (element_mode, 128);
2067 if (VECTOR_MODE_P (res))
2068 return res;
2069 }
2070
2071 return default_vectorize_related_mode (vector_mode, element_mode, nunits);
2072 }
2073
2074 /* Implement TARGET_VECTORIZE_PREFERRED_DIV_AS_SHIFTS_OVER_MULT. */
2075
2076 static bool
2077 aarch64_vectorize_preferred_div_as_shifts_over_mult (const_tree type)
2078 {
2079 machine_mode mode = TYPE_MODE (type);
2080 unsigned int vec_flags = aarch64_classify_vector_mode (mode);
2081 bool sve_p = (vec_flags & VEC_ANY_SVE);
2082 bool simd_p = (vec_flags & VEC_ADVSIMD);
2083
2084 return (sve_p && TARGET_SVE2) || (simd_p && TARGET_SIMD);
2085 }
2086
2087 /* Implement TARGET_PREFERRED_ELSE_VALUE. For binary operations,
2088 prefer to use the first arithmetic operand as the else value if
2089 the else value doesn't matter, since that exactly matches the SVE
2090 destructive merging form. For ternary operations we could either
2091 pick the first operand and use FMAD-like instructions or the last
2092 operand and use FMLA-like instructions; the latter seems more
2093 natural. */
2094
2095 static tree
2096 aarch64_preferred_else_value (unsigned, tree, unsigned int nops, tree *ops)
2097 {
2098 return nops == 3 ? ops[2] : ops[0];
2099 }
2100
2101 /* Implement TARGET_MAX_NOCE_IFCVT_SEQ_COST. If an explicit max was set then
2102 honor it, otherwise apply a tuning specific scale to branch costs. */
2103
2104 static unsigned int
2105 aarch64_max_noce_ifcvt_seq_cost (edge e)
2106 {
2107 bool predictable_p = predictable_edge_p (e);
2108 if (predictable_p)
2109 {
2110 if (OPTION_SET_P (param_max_rtl_if_conversion_predictable_cost))
2111 return param_max_rtl_if_conversion_predictable_cost;
2112 }
2113 else
2114 {
2115 if (OPTION_SET_P (param_max_rtl_if_conversion_unpredictable_cost))
2116 return param_max_rtl_if_conversion_unpredictable_cost;
2117 }
2118
2119 /* For modern machines with long speculative execution chains and modern
2120 branch prediction the penalty of the branch misprediction needs to weighed
2121 against the cost of executing the instructions unconditionally. RISC cores
2122 tend to not have that deep pipelines and so the cost of mispredictions can
2123 be reasonably cheap. */
2124
2125 bool speed_p = optimize_function_for_speed_p (cfun);
2126 return BRANCH_COST (speed_p, predictable_p)
2127 * aarch64_tune_params.branch_costs->br_mispredict_factor;
2128 }
2129
2130 /* Return true if SEQ is a good candidate as a replacement for the
2131 if-convertible sequence described in IF_INFO. AArch64 has a range of
2132 branchless statements and not all of them are potentially problematic. For
2133 instance a cset is usually beneficial whereas a csel is more complicated. */
2134
2135 static bool
2136 aarch64_noce_conversion_profitable_p (rtx_insn *seq,
2137 struct noce_if_info *if_info)
2138 {
2139 /* If not in a loop, just accept all if-conversion as the branch predictor
2140 won't have anything to train on. So assume sequences are essentially
2141 unpredictable. ce1 is in CFG mode still while ce2 is outside. For ce2
2142 accept limited if-conversion based on the shape of the instruction. */
2143 if (current_loops
2144 && (!if_info->test_bb->loop_father
2145 || !if_info->test_bb->loop_father->header
2146 || bb_loop_depth (if_info->test_bb->loop_father->header) == 0))
2147 return true;
2148
2149 /* For now we only care about csel speciifcally. */
2150 bool is_csel_p = true;
2151
2152 if (if_info->then_simple
2153 && if_info->a != NULL_RTX
2154 && !REG_P (if_info->a)
2155 && !SUBREG_P (if_info->a))
2156 is_csel_p = false;
2157
2158 if (if_info->else_simple
2159 && if_info->b != NULL_RTX
2160 && !REG_P (if_info->b)
2161 && !SUBREG_P (if_info->b))
2162 is_csel_p = false;
2163
2164 for (rtx_insn *insn = seq; is_csel_p && insn; insn = NEXT_INSN (insn))
2165 {
2166 rtx set = single_set (insn);
2167 if (!set)
2168 continue;
2169
2170 rtx src = SET_SRC (set);
2171 rtx dst = SET_DEST (set);
2172 machine_mode mode = GET_MODE (src);
2173 if (GET_MODE_CLASS (mode) != MODE_INT)
2174 continue;
2175
2176 switch (GET_CODE (src))
2177 {
2178 case PLUS:
2179 case MINUS:
2180 {
2181 /* Likely a CINC. */
2182 if (REG_P (dst)
2183 && (REG_P (XEXP (src, 0)) || SUBREG_P (XEXP (src, 0)))
2184 && (XEXP (src, 1) == CONST1_RTX (mode)
2185 || XEXP (src, 1) == CONSTM1_RTX (mode)))
2186 is_csel_p = false;
2187 break;
2188 }
2189 default:
2190 break;
2191 }
2192 }
2193
2194 /* For now accept every variant but csel unconditionally because CSEL usually
2195 means you have to wait for two values to be computed. */
2196 if (!is_csel_p)
2197 return true;
2198
2199 /* TODO: Add detecting of csel, cinc, cset etc and take profiling in
2200 consideration. For now this basic costing is enough to cover
2201 most cases. */
2202 if (if_info->speed_p)
2203 {
2204 unsigned cost = seq_cost (seq, true);
2205 return cost <= if_info->max_seq_cost;
2206 }
2207
2208 return default_noce_conversion_profitable_p (seq, if_info);
2209 }
2210
2211 /* Implement TARGET_HARD_REGNO_NREGS. */
2212
2213 static unsigned int
2214 aarch64_hard_regno_nregs (unsigned regno, machine_mode mode)
2215 {
2216 /* ??? Logically we should only need to provide a value when
2217 HARD_REGNO_MODE_OK says that the combination is valid,
2218 but at the moment we need to handle all modes. Just ignore
2219 any runtime parts for registers that can't store them. */
2220 HOST_WIDE_INT lowest_size = constant_lower_bound (GET_MODE_SIZE (mode));
2221 switch (aarch64_regno_regclass (regno))
2222 {
2223 case FP_REGS:
2224 case FP_LO_REGS:
2225 case FP_LO8_REGS:
2226 {
2227 unsigned int vec_flags = aarch64_classify_vector_mode (mode);
2228 if (vec_flags & VEC_SVE_DATA)
2229 return exact_div (GET_MODE_SIZE (mode),
2230 aarch64_vl_bytes (mode, vec_flags)).to_constant ();
2231 if (vec_flags == (VEC_ADVSIMD | VEC_STRUCT | VEC_PARTIAL))
2232 return GET_MODE_SIZE (mode).to_constant () / 8;
2233 return CEIL (lowest_size, UNITS_PER_VREG);
2234 }
2235
2236 case PR_REGS:
2237 case PR_LO_REGS:
2238 case PR_HI_REGS:
2239 return mode == VNx64BImode ? 4 : mode == VNx32BImode ? 2 : 1;
2240
2241 case MOVEABLE_SYSREGS:
2242 case FFR_REGS:
2243 case PR_AND_FFR_REGS:
2244 case FAKE_REGS:
2245 return 1;
2246
2247 default:
2248 return CEIL (lowest_size, UNITS_PER_WORD);
2249 }
2250 gcc_unreachable ();
2251 }
2252
2253 /* Implement TARGET_HARD_REGNO_MODE_OK. */
2254
2255 static bool
2256 aarch64_hard_regno_mode_ok (unsigned regno, machine_mode mode)
2257 {
2258 if (mode == V8DImode)
2259 return IN_RANGE (regno, R0_REGNUM, R23_REGNUM)
2260 && multiple_p (regno - R0_REGNUM, 2);
2261
2262 if (GET_MODE_CLASS (mode) == MODE_CC)
2263 return regno == CC_REGNUM;
2264
2265 if (regno == VG_REGNUM)
2266 /* This must have the same size as _Unwind_Word. */
2267 return mode == DImode;
2268
2269 if (regno == FPM_REGNUM)
2270 return mode == QImode || mode == HImode || mode == SImode || mode == DImode;
2271
2272 unsigned int vec_flags = aarch64_classify_vector_mode (mode);
2273 if (vec_flags == VEC_SVE_PRED)
2274 return pr_or_ffr_regnum_p (regno);
2275
2276 if (vec_flags == (VEC_SVE_PRED | VEC_STRUCT))
2277 return PR_REGNUM_P (regno);
2278
2279 if (pr_or_ffr_regnum_p (regno))
2280 return false;
2281
2282 /* These registers are abstract; their modes don't matter. */
2283 if (FAKE_REGNUM_P (regno))
2284 return true;
2285
2286 if (regno == SP_REGNUM)
2287 /* The purpose of comparing with ptr_mode is to support the
2288 global register variable associated with the stack pointer
2289 register via the syntax of asm ("wsp") in ILP32. */
2290 return mode == Pmode || mode == ptr_mode;
2291
2292 if (regno == FRAME_POINTER_REGNUM || regno == ARG_POINTER_REGNUM)
2293 return mode == Pmode;
2294
2295 if (GP_REGNUM_P (regno))
2296 {
2297 if (vec_flags & (VEC_ANY_SVE | VEC_STRUCT))
2298 return false;
2299 if (known_le (GET_MODE_SIZE (mode), 8))
2300 return true;
2301 if (known_le (GET_MODE_SIZE (mode), 16))
2302 return (regno & 1) == 0;
2303 }
2304 else if (FP_REGNUM_P (regno))
2305 {
2306 if (vec_flags & VEC_STRUCT)
2307 return end_hard_regno (mode, regno) - 1 <= V31_REGNUM;
2308 else
2309 return !VECTOR_MODE_P (mode) || vec_flags != 0;
2310 }
2311
2312 return false;
2313 }
2314
2315 /* Return true if a function with type FNTYPE returns its value in
2316 SVE vector or predicate registers. */
2317
2318 static bool
2319 aarch64_returns_value_in_sve_regs_p (const_tree fntype)
2320 {
2321 tree return_type = TREE_TYPE (fntype);
2322
2323 pure_scalable_type_info pst_info;
2324 switch (pst_info.analyze (return_type))
2325 {
2326 case pure_scalable_type_info::IS_PST:
2327 return (pst_info.num_zr () <= NUM_FP_ARG_REGS
2328 && pst_info.num_pr () <= NUM_PR_ARG_REGS);
2329
2330 case pure_scalable_type_info::DOESNT_MATTER:
2331 gcc_assert (aarch64_return_in_memory_1 (return_type));
2332 return false;
2333
2334 case pure_scalable_type_info::NO_ABI_IDENTITY:
2335 case pure_scalable_type_info::ISNT_PST:
2336 return false;
2337 }
2338 gcc_unreachable ();
2339 }
2340
2341 /* Return true if a function with type FNTYPE takes arguments in
2342 SVE vector or predicate registers. */
2343
2344 static bool
2345 aarch64_takes_arguments_in_sve_regs_p (const_tree fntype)
2346 {
2347 CUMULATIVE_ARGS args_so_far_v;
2348 aarch64_init_cumulative_args (&args_so_far_v, NULL_TREE, NULL_RTX,
2349 NULL_TREE, 0, true);
2350 cumulative_args_t args_so_far = pack_cumulative_args (&args_so_far_v);
2351
2352 for (tree chain = TYPE_ARG_TYPES (fntype);
2353 chain && chain != void_list_node;
2354 chain = TREE_CHAIN (chain))
2355 {
2356 tree arg_type = TREE_VALUE (chain);
2357 if (arg_type == error_mark_node)
2358 return false;
2359
2360 function_arg_info arg (arg_type, /*named=*/true);
2361 apply_pass_by_reference_rules (&args_so_far_v, arg);
2362 pure_scalable_type_info pst_info;
2363 if (pst_info.analyze_registers (arg.type))
2364 {
2365 unsigned int end_zr = args_so_far_v.aapcs_nvrn + pst_info.num_zr ();
2366 unsigned int end_pr = args_so_far_v.aapcs_nprn + pst_info.num_pr ();
2367 gcc_assert (end_zr <= NUM_FP_ARG_REGS && end_pr <= NUM_PR_ARG_REGS);
2368 return true;
2369 }
2370
2371 targetm.calls.function_arg_advance (args_so_far, arg);
2372 }
2373 return false;
2374 }
2375
2376 /* Implement TARGET_FNTYPE_ABI. */
2377
2378 static const predefined_function_abi &
2379 aarch64_fntype_abi (const_tree fntype)
2380 {
2381 if (lookup_attribute ("aarch64_vector_pcs", TYPE_ATTRIBUTES (fntype)))
2382 return aarch64_simd_abi ();
2383
2384 if (aarch64_returns_value_in_sve_regs_p (fntype)
2385 || aarch64_takes_arguments_in_sve_regs_p (fntype))
2386 return aarch64_sve_abi ();
2387
2388 return default_function_abi;
2389 }
2390
2391 /* Return the state of PSTATE.SM on entry to functions of type FNTYPE. */
2392
2393 static aarch64_isa_mode
2394 aarch64_fntype_pstate_sm (const_tree fntype)
2395 {
2396 if (lookup_attribute ("arm", "streaming", TYPE_ATTRIBUTES (fntype)))
2397 return AARCH64_ISA_MODE_SM_ON;
2398
2399 if (lookup_attribute ("arm", "streaming_compatible",
2400 TYPE_ATTRIBUTES (fntype)))
2401 return 0;
2402
2403 return AARCH64_ISA_MODE_SM_OFF;
2404 }
2405
2406 /* Return state flags that describe whether and how functions of type
2407 FNTYPE share state STATE_NAME with their callers. */
2408
2409 static unsigned int
2410 aarch64_fntype_shared_flags (const_tree fntype, const char *state_name)
2411 {
2412 return aarch64_lookup_shared_state_flags (TYPE_ATTRIBUTES (fntype),
2413 state_name);
2414 }
2415
2416 /* Return the state of PSTATE.ZA on entry to functions of type FNTYPE. */
2417
2418 static aarch64_isa_mode
2419 aarch64_fntype_pstate_za (const_tree fntype)
2420 {
2421 if (aarch64_fntype_shared_flags (fntype, "za")
2422 || aarch64_fntype_shared_flags (fntype, "zt0"))
2423 return AARCH64_ISA_MODE_ZA_ON;
2424
2425 return 0;
2426 }
2427
2428 /* Return the ISA mode on entry to functions of type FNTYPE. */
2429
2430 static aarch64_isa_mode
2431 aarch64_fntype_isa_mode (const_tree fntype)
2432 {
2433 return (aarch64_fntype_pstate_sm (fntype)
2434 | aarch64_fntype_pstate_za (fntype));
2435 }
2436
2437 /* Return true if FNDECL uses streaming mode internally, as an
2438 implementation choice. */
2439
2440 static bool
2441 aarch64_fndecl_is_locally_streaming (const_tree fndecl)
2442 {
2443 return lookup_attribute ("arm", "locally_streaming",
2444 DECL_ATTRIBUTES (fndecl));
2445 }
2446
2447 /* Return the state of PSTATE.SM when compiling the body of
2448 function FNDECL. This might be different from the state of
2449 PSTATE.SM on entry. */
2450
2451 static aarch64_isa_mode
2452 aarch64_fndecl_pstate_sm (const_tree fndecl)
2453 {
2454 if (aarch64_fndecl_is_locally_streaming (fndecl))
2455 return AARCH64_ISA_MODE_SM_ON;
2456
2457 return aarch64_fntype_pstate_sm (TREE_TYPE (fndecl));
2458 }
2459
2460 /* Return true if function FNDECL has state STATE_NAME, either by creating
2461 new state itself or by sharing state with callers. */
2462
2463 static bool
2464 aarch64_fndecl_has_state (tree fndecl, const char *state_name)
2465 {
2466 return (aarch64_fndecl_has_new_state (fndecl, state_name)
2467 || aarch64_fntype_shared_flags (TREE_TYPE (fndecl),
2468 state_name) != 0);
2469 }
2470
2471 /* Return the state of PSTATE.ZA when compiling the body of function FNDECL.
2472 This might be different from the state of PSTATE.ZA on entry. */
2473
2474 static aarch64_isa_mode
2475 aarch64_fndecl_pstate_za (const_tree fndecl)
2476 {
2477 if (aarch64_fndecl_has_new_state (fndecl, "za")
2478 || aarch64_fndecl_has_new_state (fndecl, "zt0"))
2479 return AARCH64_ISA_MODE_ZA_ON;
2480
2481 return aarch64_fntype_pstate_za (TREE_TYPE (fndecl));
2482 }
2483
2484 /* Return the ISA mode that should be used to compile the body of
2485 function FNDECL. */
2486
2487 static aarch64_isa_mode
2488 aarch64_fndecl_isa_mode (const_tree fndecl)
2489 {
2490 return (aarch64_fndecl_pstate_sm (fndecl)
2491 | aarch64_fndecl_pstate_za (fndecl));
2492 }
2493
2494 /* Return the state of PSTATE.SM on entry to the current function.
2495 This might be different from the state of PSTATE.SM in the function
2496 body. */
2497
2498 static aarch64_isa_mode
2499 aarch64_cfun_incoming_pstate_sm ()
2500 {
2501 return aarch64_fntype_pstate_sm (TREE_TYPE (cfun->decl));
2502 }
2503
2504 /* Return the state of PSTATE.ZA on entry to the current function.
2505 This might be different from the state of PSTATE.ZA in the function
2506 body. */
2507
2508 static aarch64_isa_mode
2509 aarch64_cfun_incoming_pstate_za ()
2510 {
2511 return aarch64_fntype_pstate_za (TREE_TYPE (cfun->decl));
2512 }
2513
2514 /* Return state flags that describe whether and how the current function shares
2515 state STATE_NAME with callers. */
2516
2517 static unsigned int
2518 aarch64_cfun_shared_flags (const char *state_name)
2519 {
2520 return aarch64_fntype_shared_flags (TREE_TYPE (cfun->decl), state_name);
2521 }
2522
2523 /* Return true if the current function creates new state of type STATE_NAME
2524 (as opposed to sharing the state with its callers or ignoring the state
2525 altogether). */
2526
2527 static bool
2528 aarch64_cfun_has_new_state (const char *state_name)
2529 {
2530 return aarch64_fndecl_has_new_state (cfun->decl, state_name);
2531 }
2532
2533 /* Return true if PSTATE.SM is 1 in the body of the current function,
2534 but is not guaranteed to be 1 on entry. */
2535
2536 static bool
2537 aarch64_cfun_enables_pstate_sm ()
2538 {
2539 return (aarch64_fndecl_is_locally_streaming (cfun->decl)
2540 && aarch64_cfun_incoming_pstate_sm () != AARCH64_ISA_MODE_SM_ON);
2541 }
2542
2543 /* Return true if the current function has state STATE_NAME, either by
2544 creating new state itself or by sharing state with callers. */
2545
2546 static bool
2547 aarch64_cfun_has_state (const char *state_name)
2548 {
2549 return aarch64_fndecl_has_state (cfun->decl, state_name);
2550 }
2551
2552 /* Return true if a call from the current function to a function with
2553 ISA mode CALLEE_MODE would involve a change to PSTATE.SM around
2554 the BL instruction. */
2555
2556 static bool
2557 aarch64_call_switches_pstate_sm (aarch64_isa_mode callee_mode)
2558 {
2559 return (bool) (callee_mode & ~AARCH64_ISA_MODE & AARCH64_ISA_MODE_SM_STATE);
2560 }
2561
2562 /* Implement TARGET_COMPATIBLE_VECTOR_TYPES_P. */
2563
2564 static bool
2565 aarch64_compatible_vector_types_p (const_tree type1, const_tree type2)
2566 {
2567 return (aarch64_sve::builtin_type_p (type1)
2568 == aarch64_sve::builtin_type_p (type2));
2569 }
2570
2571 /* Return true if we should emit CFI for register REGNO. */
2572
2573 static bool
2574 aarch64_emit_cfi_for_reg_p (unsigned int regno)
2575 {
2576 return (GP_REGNUM_P (regno)
2577 || !default_function_abi.clobbers_full_reg_p (regno));
2578 }
2579
2580 /* Return the mode we should use to save and restore register REGNO. */
2581
2582 static machine_mode
2583 aarch64_reg_save_mode (unsigned int regno)
2584 {
2585 if (GP_REGNUM_P (regno) || regno == VG_REGNUM)
2586 return DImode;
2587
2588 if (FP_REGNUM_P (regno))
2589 switch (crtl->abi->id ())
2590 {
2591 case ARM_PCS_AAPCS64:
2592 /* Only the low 64 bits are saved by the base PCS. */
2593 return DFmode;
2594
2595 case ARM_PCS_SIMD:
2596 /* The vector PCS saves the low 128 bits (which is the full
2597 register on non-SVE targets). */
2598 return V16QImode;
2599
2600 case ARM_PCS_SVE:
2601 /* Use vectors of DImode for registers that need frame
2602 information, so that the first 64 bytes of the save slot
2603 are always the equivalent of what storing D<n> would give. */
2604 if (aarch64_emit_cfi_for_reg_p (regno))
2605 return VNx2DImode;
2606
2607 /* Use vectors of bytes otherwise, so that the layout is
2608 endian-agnostic, and so that we can use LDR and STR for
2609 big-endian targets. */
2610 return VNx16QImode;
2611
2612 case ARM_PCS_TLSDESC:
2613 case ARM_PCS_UNKNOWN:
2614 break;
2615 }
2616
2617 if (PR_REGNUM_P (regno))
2618 /* Save the full predicate register. */
2619 return VNx16BImode;
2620
2621 gcc_unreachable ();
2622 }
2623
2624 /* Return the CONST_INT that should be placed in an UNSPEC_CALLEE_ABI rtx.
2625 This value encodes the following information:
2626 - the ISA mode on entry to a callee (ISA_MODE)
2627 - the ABI of the callee (PCS_VARIANT)
2628 - whether the callee has an indirect_return
2629 attribute (INDIRECT_RETURN). */
2630
2631 rtx
2632 aarch64_gen_callee_cookie (aarch64_isa_mode isa_mode, arm_pcs pcs_variant,
2633 bool indirect_return)
2634 {
2635 unsigned int im = (unsigned int) isa_mode;
2636 unsigned int ir = (indirect_return ? 1 : 0) << AARCH64_NUM_ISA_MODES;
2637 unsigned int pv = (unsigned int) pcs_variant
2638 << (AARCH64_NUM_ABI_ATTRIBUTES + AARCH64_NUM_ISA_MODES);
2639 return gen_int_mode (im | ir | pv, DImode);
2640 }
2641
2642 /* COOKIE is a CONST_INT from an UNSPEC_CALLEE_ABI rtx. Return the
2643 callee's ABI. */
2644
2645 static const predefined_function_abi &
2646 aarch64_callee_abi (rtx cookie)
2647 {
2648 return function_abis[UINTVAL (cookie)
2649 >> (AARCH64_NUM_ABI_ATTRIBUTES + AARCH64_NUM_ISA_MODES)];
2650 }
2651
2652 /* COOKIE is a CONST_INT from an UNSPEC_CALLEE_ABI rtx. Return the
2653 required ISA mode on entry to the callee, which is also the ISA
2654 mode on return from the callee. */
2655
2656 static aarch64_isa_mode
2657 aarch64_callee_isa_mode (rtx cookie)
2658 {
2659 return UINTVAL (cookie) & ((1 << AARCH64_NUM_ISA_MODES) - 1);
2660 }
2661
2662 /* COOKIE is a CONST_INT from an UNSPEC_CALLEE_ABI rtx. Return
2663 whether function was marked with an indirect_return attribute. */
2664
2665 static bool
2666 aarch64_callee_indirect_return (rtx cookie)
2667 {
2668 return ((UINTVAL (cookie) >> AARCH64_NUM_ISA_MODES) & 1) == 1;
2669 }
2670
2671 /* INSN is a call instruction. Return the CONST_INT stored in its
2672 UNSPEC_CALLEE_ABI rtx. */
2673
2674 static rtx
2675 aarch64_insn_callee_cookie (const rtx_insn *insn)
2676 {
2677 rtx pat = PATTERN (insn);
2678 gcc_assert (GET_CODE (pat) == PARALLEL);
2679 rtx unspec = XVECEXP (pat, 0, 1);
2680 gcc_assert (GET_CODE (unspec) == UNSPEC
2681 && XINT (unspec, 1) == UNSPEC_CALLEE_ABI);
2682 return XVECEXP (unspec, 0, 0);
2683 }
2684
2685 /* INSN is a call instruction. Return true if the callee has an
2686 indirect_return attribute. */
2687
2688 bool
2689 aarch_fun_is_indirect_return (rtx_insn *insn)
2690 {
2691 rtx cookie = aarch64_insn_callee_cookie (insn);
2692 return aarch64_callee_indirect_return (cookie);
2693 }
2694
2695 /* Implement TARGET_INSN_CALLEE_ABI. */
2696
2697 const predefined_function_abi &
2698 aarch64_insn_callee_abi (const rtx_insn *insn)
2699 {
2700 return aarch64_callee_abi (aarch64_insn_callee_cookie (insn));
2701 }
2702
2703 /* INSN is a call instruction. Return the required ISA mode on entry to
2704 the callee, which is also the ISA mode on return from the callee. */
2705
2706 static aarch64_isa_mode
2707 aarch64_insn_callee_isa_mode (const rtx_insn *insn)
2708 {
2709 return aarch64_callee_isa_mode (aarch64_insn_callee_cookie (insn));
2710 }
2711
2712 /* Implement TARGET_HARD_REGNO_CALL_PART_CLOBBERED. The callee only saves
2713 the lower 64 bits of a 128-bit register. Tell the compiler the callee
2714 clobbers the top 64 bits when restoring the bottom 64 bits. */
2715
2716 static bool
2717 aarch64_hard_regno_call_part_clobbered (unsigned int abi_id,
2718 unsigned int regno,
2719 machine_mode mode)
2720 {
2721 if (FP_REGNUM_P (regno) && abi_id != ARM_PCS_SVE)
2722 {
2723 poly_int64 per_register_size;
2724 if (aarch64_sve_mode_p (mode))
2725 /* SVE instructions operate on the full SVE register, even for
2726 partial modes like VNx2SF whose GET_MODE_SIZE is only 8 bytes
2727 under -msve-vector-bits=128. The elements of such partial
2728 modes are strided across the register and can lie outside the
2729 callee-preserved low 64 bits. Compare against the full SVE
2730 vector size so that V8-V15 are correctly recognised as
2731 partially clobbered for any SVE mode under AAPCS64/AAPCS_SIMD. */
2732 per_register_size = BYTES_PER_SVE_VECTOR;
2733 else
2734 {
2735 per_register_size = GET_MODE_SIZE (mode);
2736 unsigned int nregs = hard_regno_nregs (regno, mode);
2737 if (nregs > 1)
2738 per_register_size = exact_div (per_register_size, nregs);
2739 }
2740 if (abi_id == ARM_PCS_SIMD || abi_id == ARM_PCS_TLSDESC)
2741 return maybe_gt (per_register_size, 16);
2742 return maybe_gt (per_register_size, 8);
2743 }
2744 return false;
2745 }
2746
2747 /* Implement REGMODE_NATURAL_SIZE. */
2748 poly_uint64
2749 aarch64_regmode_natural_size (machine_mode mode)
2750 {
2751 /* The natural size for SVE data modes is one SVE data vector,
2752 and similarly for predicates. We can't independently modify
2753 anything smaller than that. */
2754 /* ??? For now, only do this for variable-width SVE registers.
2755 Doing it for constant-sized registers breaks lower-subreg.cc. */
2756 /* ??? And once that's fixed, we should probably have similar
2757 code for Advanced SIMD. */
2758 if (!aarch64_sve_vg.is_constant ())
2759 {
2760 /* REGMODE_NATURAL_SIZE influences general subreg validity rules,
2761 so we need to handle memory-only modes as well. */
2762 unsigned int vec_flags = aarch64_classify_vector_memory_mode (mode);
2763 if (vec_flags & VEC_SVE_PRED)
2764 return BYTES_PER_SVE_PRED;
2765 if (vec_flags & VEC_SVE_DATA)
2766 return BYTES_PER_SVE_VECTOR;
2767 }
2768 return UNITS_PER_WORD;
2769 }
2770
2771 /* Implement HARD_REGNO_CALLER_SAVE_MODE. */
2772 machine_mode
2773 aarch64_hard_regno_caller_save_mode (unsigned regno, unsigned,
2774 machine_mode mode)
2775 {
2776 /* The predicate mode determines which bits are significant and
2777 which are "don't care". Decreasing the number of lanes would
2778 lose data while increasing the number of lanes would make bits
2779 unnecessarily significant. */
2780 if (PR_REGNUM_P (regno))
2781 return mode;
2782 if (known_lt (GET_MODE_SIZE (mode), 4)
2783 && REG_CAN_CHANGE_MODE_P (regno, mode, SImode)
2784 && REG_CAN_CHANGE_MODE_P (regno, SImode, mode))
2785 return SImode;
2786 return mode;
2787 }
2788
2789 /* Return true if I's bits are consecutive ones from the MSB. */
2790 bool
2791 aarch64_high_bits_all_ones_p (HOST_WIDE_INT i)
2792 {
2793 return exact_log2 (-i) != HOST_WIDE_INT_M1;
2794 }
2795
2796 /* Implement TARGET_CONSTANT_ALIGNMENT. Make strings word-aligned so
2797 that strcpy from constants will be faster. */
2798
2799 static HOST_WIDE_INT
2800 aarch64_constant_alignment (const_tree exp, HOST_WIDE_INT align)
2801 {
2802 if (TREE_CODE (exp) == STRING_CST && !optimize_size)
2803 return MAX (align, BITS_PER_WORD);
2804 return align;
2805 }
2806
2807 /* Align definitions of arrays, unions and structures so that
2808 initializations and copies can be made more efficient. This is not
2809 ABI-changing, so it only affects places where we can see the
2810 definition. Increasing the alignment tends to introduce padding,
2811 so don't do this when optimizing for size/conserving stack space. */
2812
2813 unsigned
2814 aarch64_data_alignment (const_tree type, unsigned align)
2815 {
2816 if (optimize_size)
2817 return align;
2818
2819 if (AGGREGATE_TYPE_P (type))
2820 {
2821 unsigned HOST_WIDE_INT size = 0;
2822
2823 if (TYPE_SIZE (type) && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST
2824 && tree_fits_uhwi_p (TYPE_SIZE (type)))
2825 size = tree_to_uhwi (TYPE_SIZE (type));
2826
2827 /* Align small structs/arrays to 32 bits, or 64 bits if larger. */
2828 if (align < 32 && size <= 32)
2829 align = 32;
2830 else if (align < 64)
2831 align = 64;
2832 }
2833
2834 return align;
2835 }
2836
2837 unsigned
2838 aarch64_stack_alignment (const_tree type, unsigned align)
2839 {
2840 if (flag_conserve_stack)
2841 return align;
2842
2843 if (AGGREGATE_TYPE_P (type))
2844 {
2845 unsigned HOST_WIDE_INT size = 0;
2846
2847 if (TYPE_SIZE (type) && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST
2848 && tree_fits_uhwi_p (TYPE_SIZE (type)))
2849 size = tree_to_uhwi (TYPE_SIZE (type));
2850
2851 /* Align small structs/arrays to 32 bits, or 64 bits if larger. */
2852 if (align < 32 && size <= 32)
2853 align = 32;
2854 else if (align < 64)
2855 align = 64;
2856 }
2857
2858 return align;
2859 }
2860
2861 /* Return true if calls to DECL should be treated as
2862 long-calls (ie called via a register). */
2863 static bool
2864 aarch64_decl_is_long_call_p (const_tree decl ATTRIBUTE_UNUSED)
2865 {
2866 return false;
2867 }
2868
2869 /* Return true if calls to symbol-ref SYM should be treated as
2870 long-calls (ie called via a register). */
2871 bool
2872 aarch64_is_long_call_p (rtx sym)
2873 {
2874 return aarch64_decl_is_long_call_p (SYMBOL_REF_DECL (sym));
2875 }
2876
2877 /* Return true if calls to symbol-ref SYM should not go through
2878 plt stubs. */
2879
2880 bool
2881 aarch64_is_noplt_call_p (rtx sym)
2882 {
2883 const_tree decl = SYMBOL_REF_DECL (sym);
2884
2885 if (flag_pic
2886 && decl
2887 && (!flag_plt
2888 || lookup_attribute ("noplt", DECL_ATTRIBUTES (decl)))
2889 && !targetm.binds_local_p (decl))
2890 return true;
2891
2892 return false;
2893 }
2894
2895 /* Emit an insn that's a simple single-set. Both the operands must be
2896 known to be valid. */
2897 inline static rtx_insn *
2898 emit_set_insn (rtx x, rtx y)
2899 {
2900 return emit_insn (gen_rtx_SET (x, y));
2901 }
2902
2903 /* X and Y are two things to compare using CODE. Emit the compare insn and
2904 return the rtx for register 0 in the proper mode. */
2905 rtx
2906 aarch64_gen_compare_reg (RTX_CODE code, rtx x, rtx y)
2907 {
2908 machine_mode cmp_mode = GET_MODE (x);
2909 machine_mode cc_mode;
2910 rtx cc_reg;
2911
2912 if (cmp_mode == TImode)
2913 {
2914 gcc_assert (code == NE);
2915
2916 cc_mode = CCmode;
2917 cc_reg = gen_rtx_REG (cc_mode, CC_REGNUM);
2918
2919 rtx x_lo = operand_subword (x, 0, 0, TImode);
2920 rtx y_lo = operand_subword (y, 0, 0, TImode);
2921 emit_set_insn (cc_reg, gen_rtx_COMPARE (cc_mode, x_lo, y_lo));
2922
2923 rtx x_hi = operand_subword (x, 1, 0, TImode);
2924 rtx y_hi = operand_subword (y, 1, 0, TImode);
2925 emit_insn (gen_ccmpccdi (cc_reg, cc_reg, x_hi, y_hi,
2926 gen_rtx_EQ (cc_mode, cc_reg, const0_rtx),
2927 GEN_INT (AARCH64_EQ)));
2928 }
2929 else
2930 {
2931 cc_mode = SELECT_CC_MODE (code, x, y);
2932 cc_reg = gen_rtx_REG (cc_mode, CC_REGNUM);
2933 emit_set_insn (cc_reg, gen_rtx_COMPARE (cc_mode, x, y));
2934 }
2935 return cc_reg;
2936 }
2937
2938 /* Similarly, but maybe zero-extend Y if Y_MODE < SImode. */
2939
2940 static rtx
2941 aarch64_gen_compare_reg_maybe_ze (RTX_CODE code, rtx x, rtx y,
2942 machine_mode y_mode)
2943 {
2944 if (y_mode == E_QImode || y_mode == E_HImode)
2945 {
2946 if (CONST_INT_P (y))
2947 {
2948 y = GEN_INT (INTVAL (y) & GET_MODE_MASK (y_mode));
2949 y_mode = SImode;
2950 }
2951 else
2952 {
2953 rtx t, cc_reg;
2954 machine_mode cc_mode;
2955
2956 t = gen_rtx_ZERO_EXTEND (SImode, y);
2957 t = gen_rtx_COMPARE (CC_SWPmode, t, x);
2958 cc_mode = CC_SWPmode;
2959 cc_reg = gen_rtx_REG (cc_mode, CC_REGNUM);
2960 emit_set_insn (cc_reg, t);
2961 return cc_reg;
2962 }
2963 }
2964
2965 if (!aarch64_plus_operand (y, y_mode))
2966 y = force_reg (y_mode, y);
2967
2968 return aarch64_gen_compare_reg (code, x, y);
2969 }
2970
2971 /* Generate conditional branch to LABEL, comparing X to 0 using CODE.
2972 Return the jump instruction. */
2973
2974 static rtx
2975 aarch64_gen_compare_zero_and_branch (rtx_code code, rtx x,
2976 rtx_code_label *label)
2977 {
2978 if (aarch64_track_speculation)
2979 {
2980 /* Emit an explicit compare instruction, so that we can correctly
2981 track the condition codes. */
2982 rtx cc_reg = aarch64_gen_compare_reg (code, x, const0_rtx);
2983 x = gen_rtx_fmt_ee (code, GET_MODE (cc_reg), cc_reg, const0_rtx);
2984 }
2985 else
2986 x = gen_rtx_fmt_ee (code, VOIDmode, x, const0_rtx);
2987
2988 x = gen_rtx_IF_THEN_ELSE (VOIDmode, x,
2989 gen_rtx_LABEL_REF (Pmode, label), pc_rtx);
2990 return gen_rtx_SET (pc_rtx, x);
2991 }
2992
2993 /* Return an rtx that branches to LABEL based on the value of bit BITNUM of X.
2994 If CODE is NE, it branches to LABEL when the bit is set; if CODE is EQ,
2995 it branches to LABEL when the bit is clear. */
2996
2997 static rtx
2998 aarch64_gen_test_and_branch (rtx_code code, rtx x, int bitnum,
2999 rtx_code_label *label)
3000 {
3001 auto mode = GET_MODE (x);
3002 if (aarch64_track_speculation)
3003 {
3004 auto mask = gen_int_mode (HOST_WIDE_INT_1U << bitnum, mode);
3005 emit_insn (gen_aarch64_and3nr_compare0 (mode, x, mask));
3006 rtx cc_reg = gen_rtx_REG (CC_NZVmode, CC_REGNUM);
3007 rtx x = gen_rtx_fmt_ee (code, CC_NZVmode, cc_reg, const0_rtx);
3008 return gen_condjump (x, cc_reg, label);
3009 }
3010 return gen_aarch64_tb (code, mode, mode,
3011 x, gen_int_mode (bitnum, mode), label);
3012 }
3013
3014 /* Consider the operation:
3015
3016 OPERANDS[0] = CODE (OPERANDS[1], OPERANDS[2]) + OPERANDS[3]
3017
3018 where:
3019
3020 - CODE is [SU]MAX or [SU]MIN
3021 - OPERANDS[2] and OPERANDS[3] are constant integers
3022 - OPERANDS[3] is a positive or negative shifted 12-bit immediate
3023 - all operands have mode MODE
3024
3025 Decide whether it is possible to implement the operation using:
3026
3027 SUBS <tmp>, OPERANDS[1], -OPERANDS[3]
3028 or
3029 ADDS <tmp>, OPERANDS[1], OPERANDS[3]
3030
3031 followed by:
3032
3033 <insn> OPERANDS[0], <tmp>, [wx]zr, <cond>
3034
3035 where <insn> is one of CSEL, CSINV or CSINC. Return true if so.
3036 If GENERATE_P is true, also update OPERANDS as follows:
3037
3038 OPERANDS[4] = -OPERANDS[3]
3039 OPERANDS[5] = the rtl condition representing <cond>
3040 OPERANDS[6] = <tmp>
3041 OPERANDS[7] = 0 for CSEL, -1 for CSINV or 1 for CSINC. */
3042 bool
3043 aarch64_maxmin_plus_const (rtx_code code, rtx *operands, bool generate_p)
3044 {
3045 signop sgn = (code == UMAX || code == UMIN ? UNSIGNED : SIGNED);
3046 rtx dst = operands[0];
3047 rtx maxmin_op = operands[2];
3048 rtx add_op = operands[3];
3049 machine_mode mode = GET_MODE (dst);
3050
3051 /* max (x, y) - z == (x >= y + 1 ? x : y) - z
3052 == (x >= y ? x : y) - z
3053 == (x > y ? x : y) - z
3054 == (x > y - 1 ? x : y) - z
3055
3056 min (x, y) - z == (x <= y - 1 ? x : y) - z
3057 == (x <= y ? x : y) - z
3058 == (x < y ? x : y) - z
3059 == (x < y + 1 ? x : y) - z
3060
3061 Check whether z is in { y - 1, y, y + 1 } and pick the form(s) for
3062 which x is compared with z. Set DIFF to y - z. Thus the supported
3063 combinations are as follows, with DIFF being the value after the ":":
3064
3065 max (x, y) - z == x >= y + 1 ? x - (y + 1) : -1 [z == y + 1]
3066 == x >= y ? x - y : 0 [z == y]
3067 == x > y ? x - y : 0 [z == y]
3068 == x > y - 1 ? x - (y - 1) : 1 [z == y - 1]
3069
3070 min (x, y) - z == x <= y - 1 ? x - (y - 1) : 1 [z == y - 1]
3071 == x <= y ? x - y : 0 [z == y]
3072 == x < y ? x - y : 0 [z == y]
3073 == x < y + 1 ? x - (y + 1) : -1 [z == y + 1]. */
3074 auto maxmin_val = rtx_mode_t (maxmin_op, mode);
3075 auto add_val = rtx_mode_t (add_op, mode);
3076 auto sub_val = wi::neg (add_val);
3077 auto diff = wi::sub (maxmin_val, sub_val);
3078 if (!(diff == 0
3079 || (diff == 1 && wi::gt_p (maxmin_val, sub_val, sgn))
3080 || (diff == -1 && wi::lt_p (maxmin_val, sub_val, sgn))))
3081 return false;
3082
3083 if (!generate_p)
3084 return true;
3085
3086 rtx_code cmp;
3087 switch (code)
3088 {
3089 case SMAX:
3090 cmp = diff == 1 ? GT : GE;
3091 break;
3092 case UMAX:
3093 cmp = diff == 1 ? GTU : GEU;
3094 break;
3095 case SMIN:
3096 cmp = diff == -1 ? LT : LE;
3097 break;
3098 case UMIN:
3099 cmp = diff == -1 ? LTU : LEU;
3100 break;
3101 default:
3102 gcc_unreachable ();
3103 }
3104 rtx cc = gen_rtx_REG (CCmode, CC_REGNUM);
3105
3106 operands[4] = immed_wide_int_const (sub_val, mode);
3107 operands[5] = gen_rtx_fmt_ee (cmp, VOIDmode, cc, const0_rtx);
3108 if (can_create_pseudo_p ())
3109 operands[6] = gen_reg_rtx (mode);
3110 else
3111 operands[6] = dst;
3112 operands[7] = immed_wide_int_const (diff, mode);
3113
3114 return true;
3115 }
3116
3117
3118 /* Build the SYMBOL_REF for __tls_get_addr. */
3119
3120 static GTY(()) rtx tls_get_addr_libfunc;
3121
3122 rtx
3123 aarch64_tls_get_addr (void)
3124 {
3125 if (!tls_get_addr_libfunc)
3126 tls_get_addr_libfunc = init_one_libfunc ("__tls_get_addr");
3127 return tls_get_addr_libfunc;
3128 }
3129
3130 /* Return the TLS model to use for ADDR. */
3131
3132 static enum tls_model
3133 tls_symbolic_operand_type (rtx addr)
3134 {
3135 enum tls_model tls_kind = TLS_MODEL_NONE;
3136 poly_int64 offset;
3137 addr = strip_offset_and_salt (addr, &offset);
3138 if (SYMBOL_REF_P (addr))
3139 tls_kind = SYMBOL_REF_TLS_MODEL (addr);
3140
3141 return tls_kind;
3142 }
3143
3144 /* We'll allow lo_sum's in addresses in our legitimate addresses
3145 so that combine would take care of combining addresses where
3146 necessary, but for generation purposes, we'll generate the address
3147 as :
3148 RTL Absolute
3149 tmp = hi (symbol_ref); adrp x1, foo
3150 dest = lo_sum (tmp, symbol_ref); add dest, x1, :lo_12:foo
3151 nop
3152
3153 PIC TLS
3154 adrp x1, :got:foo adrp tmp, :tlsgd:foo
3155 ldr x1, [:got_lo12:foo] add dest, tmp, :tlsgd_lo12:foo
3156 bl __tls_get_addr
3157 nop
3158
3159 Load TLS symbol, depending on TLS mechanism and TLS access model.
3160
3161 Global Dynamic - Traditional TLS:
3162 adrp tmp, :tlsgd:imm
3163 add dest, tmp, #:tlsgd_lo12:imm
3164 bl __tls_get_addr
3165
3166 Global Dynamic - TLS Descriptors:
3167 adrp dest, :tlsdesc:imm
3168 ldr tmp, [dest, #:tlsdesc_lo12:imm]
3169 add dest, dest, #:tlsdesc_lo12:imm
3170 blr tmp
3171 mrs tp, tpidr_el0
3172 add dest, dest, tp
3173
3174 Initial Exec:
3175 mrs tp, tpidr_el0
3176 adrp tmp, :gottprel:imm
3177 ldr dest, [tmp, #:gottprel_lo12:imm]
3178 add dest, dest, tp
3179
3180 Local Exec:
3181 mrs tp, tpidr_el0
3182 add t0, tp, #:tprel_hi12:imm, lsl #12
3183 add t0, t0, #:tprel_lo12_nc:imm
3184 */
3185
3186 static void
3187 aarch64_load_symref_appropriately (rtx dest, rtx imm,
3188 enum aarch64_symbol_type type)
3189 {
3190 #if TARGET_PECOFF
3191 rtx tmp = legitimize_pe_coff_symbol (imm, true);
3192 if (tmp)
3193 {
3194 emit_insn (gen_rtx_SET (dest, tmp));
3195 return;
3196 }
3197 #endif
3198
3199 switch (type)
3200 {
3201 case SYMBOL_SMALL_ABSOLUTE:
3202 {
3203 /* In ILP32, the mode of dest can be either SImode or DImode. */
3204 rtx tmp_reg = dest;
3205 machine_mode mode = GET_MODE (dest);
3206
3207 gcc_assert (mode == Pmode || mode == ptr_mode);
3208
3209 if (can_create_pseudo_p ())
3210 tmp_reg = gen_reg_rtx (mode);
3211
3212 HOST_WIDE_INT mid_const = 0;
3213 if (TARGET_PECOFF)
3214 {
3215 poly_int64 offset;
3216 strip_offset (imm, &offset);
3217
3218 HOST_WIDE_INT const_offset;
3219 if (offset.is_constant (&const_offset))
3220 /* Written this way for the sake of negative offsets. */
3221 mid_const = const_offset / (1 << 20) * (1 << 20);
3222 }
3223 imm = plus_constant (mode, imm, -mid_const);
3224
3225 emit_move_insn (tmp_reg, gen_rtx_HIGH (mode, copy_rtx (imm)));
3226 if (mid_const)
3227 emit_set_insn (tmp_reg, plus_constant (mode, tmp_reg, mid_const));
3228 emit_insn (gen_add_losym (dest, tmp_reg, imm));
3229 return;
3230 }
3231
3232 case SYMBOL_TINY_ABSOLUTE:
3233 emit_insn (gen_rtx_SET (dest, imm));
3234 return;
3235
3236 case SYMBOL_SMALL_GOT_28K:
3237 {
3238 machine_mode mode = GET_MODE (dest);
3239 rtx gp_rtx = pic_offset_table_rtx;
3240 rtx insn;
3241 rtx mem;
3242
3243 /* NOTE: pic_offset_table_rtx can be NULL_RTX, because we can reach
3244 here before rtl expand. Tree IVOPT will generate rtl pattern to
3245 decide rtx costs, in which case pic_offset_table_rtx is not
3246 initialized. For that case no need to generate the first adrp
3247 instruction as the final cost for global variable access is
3248 one instruction. */
3249 if (gp_rtx != NULL)
3250 {
3251 /* -fpic for -mcmodel=small allow 32K GOT table size (but we are
3252 using the page base as GOT base, the first page may be wasted,
3253 in the worst scenario, there is only 28K space for GOT).
3254
3255 The generate instruction sequence for accessing global variable
3256 is:
3257
3258 ldr reg, [pic_offset_table_rtx, #:gotpage_lo15:sym]
3259
3260 Only one instruction needed. But we must initialize
3261 pic_offset_table_rtx properly. We generate initialize insn for
3262 every global access, and allow CSE to remove all redundant.
3263
3264 The final instruction sequences will look like the following
3265 for multiply global variables access.
3266
3267 adrp pic_offset_table_rtx, _GLOBAL_OFFSET_TABLE_
3268
3269 ldr reg, [pic_offset_table_rtx, #:gotpage_lo15:sym1]
3270 ldr reg, [pic_offset_table_rtx, #:gotpage_lo15:sym2]
3271 ldr reg, [pic_offset_table_rtx, #:gotpage_lo15:sym3]
3272 ... */
3273
3274 rtx s = gen_rtx_SYMBOL_REF (Pmode, "_GLOBAL_OFFSET_TABLE_");
3275 crtl->uses_pic_offset_table = 1;
3276 emit_move_insn (gp_rtx, gen_rtx_HIGH (Pmode, s));
3277
3278 if (mode != GET_MODE (gp_rtx))
3279 gp_rtx = gen_lowpart (mode, gp_rtx);
3280
3281 }
3282
3283 if (mode == ptr_mode)
3284 {
3285 if (mode == DImode)
3286 insn = gen_ldr_got_small_28k_di (dest, gp_rtx, imm);
3287 else
3288 insn = gen_ldr_got_small_28k_si (dest, gp_rtx, imm);
3289
3290 mem = XVECEXP (SET_SRC (insn), 0, 0);
3291 }
3292 else
3293 {
3294 gcc_assert (mode == Pmode);
3295
3296 insn = gen_ldr_got_small_28k_sidi (dest, gp_rtx, imm);
3297 mem = XVECEXP (XEXP (SET_SRC (insn), 0), 0, 0);
3298 }
3299
3300 /* The operand is expected to be MEM. Whenever the related insn
3301 pattern changed, above code which calculate mem should be
3302 updated. */
3303 gcc_assert (MEM_P (mem));
3304 MEM_READONLY_P (mem) = 1;
3305 MEM_NOTRAP_P (mem) = 1;
3306 emit_insn (insn);
3307 return;
3308 }
3309
3310 case SYMBOL_SMALL_GOT_4G:
3311 emit_insn (gen_rtx_SET (dest, imm));
3312 return;
3313
3314 case SYMBOL_SMALL_TLSGD:
3315 {
3316 rtx_insn *insns;
3317 /* The return type of __tls_get_addr is the C pointer type
3318 so use ptr_mode. */
3319 rtx result = gen_rtx_REG (ptr_mode, R0_REGNUM);
3320 rtx tmp_reg = dest;
3321
3322 if (GET_MODE (dest) != ptr_mode)
3323 tmp_reg = can_create_pseudo_p () ? gen_reg_rtx (ptr_mode) : result;
3324
3325 start_sequence ();
3326 if (ptr_mode == SImode)
3327 aarch64_emit_call_insn (gen_tlsgd_small_si (result, imm));
3328 else
3329 aarch64_emit_call_insn (gen_tlsgd_small_di (result, imm));
3330 insns = get_insns ();
3331 end_sequence ();
3332
3333 RTL_CONST_CALL_P (insns) = 1;
3334 emit_libcall_block (insns, tmp_reg, result, imm);
3335 /* Convert back to the mode of the dest adding a zero_extend
3336 from SImode (ptr_mode) to DImode (Pmode). */
3337 if (dest != tmp_reg)
3338 convert_move (dest, tmp_reg, true);
3339 return;
3340 }
3341
3342 case SYMBOL_SMALL_TLSDESC:
3343 {
3344 machine_mode mode = GET_MODE (dest);
3345 rtx x0 = gen_rtx_REG (mode, R0_REGNUM);
3346 rtx tp;
3347
3348 gcc_assert (mode == Pmode || mode == ptr_mode);
3349
3350 /* In ILP32, the got entry is always of SImode size. Unlike
3351 small GOT, the dest is fixed at reg 0. */
3352 if (TARGET_ILP32)
3353 emit_insn (gen_tlsdesc_small_si (imm));
3354 else
3355 emit_insn (gen_tlsdesc_small_di (imm));
3356 tp = aarch64_load_tp (NULL);
3357
3358 if (mode != Pmode)
3359 tp = gen_lowpart (mode, tp);
3360
3361 emit_insn (gen_rtx_SET (dest, gen_rtx_PLUS (mode, tp, x0)));
3362 if (REG_P (dest))
3363 set_unique_reg_note (get_last_insn (), REG_EQUIV, imm);
3364 return;
3365 }
3366
3367 case SYMBOL_SMALL_TLSIE:
3368 {
3369 /* In ILP32, the mode of dest can be either SImode or DImode,
3370 while the got entry is always of SImode size. The mode of
3371 dest depends on how dest is used: if dest is assigned to a
3372 pointer (e.g. in the memory), it has SImode; it may have
3373 DImode if dest is dereferenced to access the memeory.
3374 This is why we have to handle three different tlsie_small
3375 patterns here (two patterns for ILP32). */
3376 machine_mode mode = GET_MODE (dest);
3377 rtx tmp_reg = gen_reg_rtx (mode);
3378 rtx tp = aarch64_load_tp (NULL);
3379
3380 if (mode == ptr_mode)
3381 {
3382 if (mode == DImode)
3383 emit_insn (gen_tlsie_small_di (tmp_reg, imm));
3384 else
3385 {
3386 emit_insn (gen_tlsie_small_si (tmp_reg, imm));
3387 tp = gen_lowpart (mode, tp);
3388 }
3389 }
3390 else
3391 {
3392 gcc_assert (mode == Pmode);
3393 emit_insn (gen_tlsie_small_sidi (tmp_reg, imm));
3394 }
3395
3396 emit_insn (gen_rtx_SET (dest, gen_rtx_PLUS (mode, tp, tmp_reg)));
3397 if (REG_P (dest))
3398 set_unique_reg_note (get_last_insn (), REG_EQUIV, imm);
3399 return;
3400 }
3401
3402 case SYMBOL_TLSLE12:
3403 case SYMBOL_TLSLE24:
3404 case SYMBOL_TLSLE32:
3405 case SYMBOL_TLSLE48:
3406 {
3407 machine_mode mode = GET_MODE (dest);
3408 rtx tp = aarch64_load_tp (NULL);
3409
3410 if (mode != Pmode)
3411 tp = gen_lowpart (mode, tp);
3412
3413 switch (type)
3414 {
3415 case SYMBOL_TLSLE12:
3416 emit_insn ((mode == DImode ? gen_tlsle12_di : gen_tlsle12_si)
3417 (dest, tp, imm));
3418 break;
3419 case SYMBOL_TLSLE24:
3420 emit_insn ((mode == DImode ? gen_tlsle24_di : gen_tlsle24_si)
3421 (dest, tp, imm));
3422 break;
3423 case SYMBOL_TLSLE32:
3424 emit_insn ((mode == DImode ? gen_tlsle32_di : gen_tlsle32_si)
3425 (dest, imm));
3426 emit_insn ((mode == DImode ? gen_adddi3 : gen_addsi3)
3427 (dest, dest, tp));
3428 break;
3429 case SYMBOL_TLSLE48:
3430 emit_insn ((mode == DImode ? gen_tlsle48_di : gen_tlsle48_si)
3431 (dest, imm));
3432 emit_insn ((mode == DImode ? gen_adddi3 : gen_addsi3)
3433 (dest, dest, tp));
3434 break;
3435 default:
3436 gcc_unreachable ();
3437 }
3438
3439 if (REG_P (dest))
3440 set_unique_reg_note (get_last_insn (), REG_EQUIV, imm);
3441 return;
3442 }
3443
3444 case SYMBOL_TINY_GOT:
3445 {
3446 rtx insn;
3447 machine_mode mode = GET_MODE (dest);
3448
3449 if (mode == ptr_mode)
3450 insn = gen_ldr_got_tiny (mode, dest, imm);
3451 else
3452 {
3453 gcc_assert (mode == Pmode);
3454 insn = gen_ldr_got_tiny_sidi (dest, imm);
3455 }
3456
3457 emit_insn (insn);
3458 return;
3459 }
3460
3461 case SYMBOL_TINY_TLSIE:
3462 {
3463 machine_mode mode = GET_MODE (dest);
3464 rtx tp = aarch64_load_tp (NULL);
3465
3466 if (mode == ptr_mode)
3467 {
3468 if (mode == DImode)
3469 emit_insn (gen_tlsie_tiny_di (dest, imm, tp));
3470 else
3471 {
3472 tp = gen_lowpart (mode, tp);
3473 emit_insn (gen_tlsie_tiny_si (dest, imm, tp));
3474 }
3475 }
3476 else
3477 {
3478 gcc_assert (mode == Pmode);
3479 emit_insn (gen_tlsie_tiny_sidi (dest, imm, tp));
3480 }
3481
3482 if (REG_P (dest))
3483 set_unique_reg_note (get_last_insn (), REG_EQUIV, imm);
3484 return;
3485 }
3486
3487 default:
3488 gcc_unreachable ();
3489 }
3490 }
3491
3492 /* Emit a move from SRC to DEST. Assume that the move expanders can
3493 handle all moves if !can_create_pseudo_p (). The distinction is
3494 important because, unlike emit_move_insn, the move expanders know
3495 how to force Pmode objects into the constant pool even when the
3496 constant pool address is not itself legitimate. */
3497 static rtx
3498 aarch64_emit_move (rtx dest, rtx src)
3499 {
3500 return (can_create_pseudo_p ()
3501 ? emit_move_insn (dest, src)
3502 : emit_move_insn_1 (dest, src));
3503 }
3504
3505 /* Apply UNOPTAB to OP and store the result in DEST. */
3506
3507 static void
3508 aarch64_emit_unop (rtx dest, optab unoptab, rtx op)
3509 {
3510 rtx tmp = expand_unop (GET_MODE (dest), unoptab, op, dest, 0);
3511 if (dest != tmp)
3512 emit_move_insn (dest, tmp);
3513 }
3514
3515 /* Apply BINOPTAB to OP0 and OP1 and store the result in DEST. */
3516
3517 static void
3518 aarch64_emit_binop (rtx dest, optab binoptab, rtx op0, rtx op1)
3519 {
3520 rtx tmp = expand_binop (GET_MODE (dest), binoptab, op0, op1, dest, 0,
3521 OPTAB_DIRECT);
3522 if (dest != tmp)
3523 emit_move_insn (dest, tmp);
3524 }
3525
3526 /* Split a move from SRC to DST into multiple moves of mode SINGLE_MODE. */
3527
3528 void
3529 aarch64_split_move (rtx dst, rtx src, machine_mode single_mode)
3530 {
3531 machine_mode mode = GET_MODE (dst);
3532 auto npieces = exact_div (GET_MODE_SIZE (mode),
3533 GET_MODE_SIZE (single_mode)).to_constant ();
3534 auto_vec<rtx, 4> dst_pieces, src_pieces;
3535
3536 /* There should be at least one piece. */
3537 gcc_assert (npieces > 0);
3538
3539 for (unsigned int i = 0; i < npieces; ++i)
3540 {
3541 auto off = i * GET_MODE_SIZE (single_mode);
3542 dst_pieces.safe_push (simplify_gen_subreg (single_mode, dst, mode, off));
3543 src_pieces.safe_push (simplify_gen_subreg (single_mode, src, mode, off));
3544 }
3545
3546 /* At most one pairing may overlap. */
3547 if (reg_overlap_mentioned_p (dst_pieces[0], src))
3548 for (unsigned int i = npieces; i-- > 0;)
3549 aarch64_emit_move (dst_pieces[i], src_pieces[i]);
3550 else
3551 for (unsigned int i = 0; i < npieces; ++i)
3552 aarch64_emit_move (dst_pieces[i], src_pieces[i]);
3553 }
3554
3555 /* Split a 128-bit move operation into two 64-bit move operations,
3556 taking care to handle partial overlap of register to register
3557 copies. Special cases are needed when moving between GP regs and
3558 FP regs. SRC can be a register, constant or memory; DST a register
3559 or memory. If either operand is memory it must not have any side
3560 effects. */
3561 void
3562 aarch64_split_128bit_move (rtx dst, rtx src)
3563 {
3564 machine_mode mode = GET_MODE (dst);
3565
3566 gcc_assert (mode == TImode || mode == TFmode || mode == TDmode);
3567 gcc_assert (!(side_effects_p (src) || side_effects_p (dst)));
3568 gcc_assert (mode == GET_MODE (src) || GET_MODE (src) == VOIDmode);
3569
3570 if (REG_P (dst) && REG_P (src))
3571 {
3572 int src_regno = REGNO (src);
3573 int dst_regno = REGNO (dst);
3574
3575 /* Handle FP <-> GP regs. */
3576 if (FP_REGNUM_P (dst_regno) && GP_REGNUM_P (src_regno))
3577 {
3578 rtx src_lo = gen_lowpart (word_mode, src);
3579 rtx src_hi = gen_highpart (word_mode, src);
3580
3581 emit_insn (gen_aarch64_movlow_di (mode, dst, src_lo));
3582 emit_insn (gen_aarch64_movhigh_di (mode, dst, src_hi));
3583 return;
3584 }
3585 else if (GP_REGNUM_P (dst_regno) && FP_REGNUM_P (src_regno))
3586 {
3587 rtx dst_lo = gen_lowpart (word_mode, dst);
3588 rtx dst_hi = gen_highpart (word_mode, dst);
3589
3590 emit_insn (gen_aarch64_movdi_low (mode, dst_lo, src));
3591 emit_insn (gen_aarch64_movdi_high (mode, dst_hi, src));
3592 return;
3593 }
3594 }
3595
3596 aarch64_split_move (dst, src, word_mode);
3597 }
3598
3599 /* Return true if we should split a move from 128-bit value SRC
3600 to 128-bit register DEST. */
3601
3602 bool
3603 aarch64_split_128bit_move_p (rtx dst, rtx src)
3604 {
3605 if (FP_REGNUM_P (REGNO (dst)))
3606 return REG_P (src) && !FP_REGNUM_P (REGNO (src));
3607 /* All moves to GPRs need to be split. */
3608 return true;
3609 }
3610
3611 /* Split a complex SIMD move. */
3612
3613 void
3614 aarch64_split_simd_move (rtx dst, rtx src)
3615 {
3616 machine_mode src_mode = GET_MODE (src);
3617 machine_mode dst_mode = GET_MODE (dst);
3618
3619 gcc_assert (VECTOR_MODE_P (dst_mode));
3620
3621 if (REG_P (dst) && REG_P (src))
3622 {
3623 gcc_assert (VECTOR_MODE_P (src_mode));
3624 emit_insn (gen_aarch64_split_simd_mov (src_mode, dst, src));
3625 }
3626 }
3627
3628 /* Return a register that contains SVE value X reinterpreted as SVE mode MODE.
3629 The semantics of those of svreinterpret rather than those of subregs;
3630 see the comment at the head of aarch64-sve.md for details about the
3631 difference. */
3632
3633 rtx
3634 aarch64_sve_reinterpret (machine_mode mode, rtx x)
3635 {
3636 if (GET_MODE (x) == mode)
3637 return x;
3638
3639 /* can_change_mode_class must only return true if subregs and svreinterprets
3640 have the same semantics. */
3641 if (targetm.can_change_mode_class (GET_MODE (x), mode, FP_REGS))
3642 return force_lowpart_subreg (mode, x, GET_MODE (x));
3643
3644 rtx res = gen_reg_rtx (mode);
3645 x = force_reg (GET_MODE (x), x);
3646 emit_insn (gen_aarch64_sve_reinterpret (mode, res, x));
3647 return res;
3648 }
3649
3650 bool
3651 aarch64_zero_extend_const_eq (machine_mode xmode, rtx x,
3652 machine_mode ymode, rtx y)
3653 {
3654 rtx r = simplify_const_unary_operation (ZERO_EXTEND, xmode, y, ymode);
3655 gcc_assert (r != NULL);
3656 return rtx_equal_p (x, r);
3657 }
3658
3659 /* Return TARGET if it is nonnull and a register of mode MODE.
3660 Otherwise, return a fresh register of mode MODE if we can,
3661 or TARGET reinterpreted as MODE if we can't. */
3662
3663 static rtx
3664 aarch64_target_reg (rtx target, machine_mode mode)
3665 {
3666 if (target && REG_P (target) && GET_MODE (target) == mode)
3667 return target;
3668 if (!can_create_pseudo_p ())
3669 {
3670 gcc_assert (target);
3671 return gen_lowpart (mode, target);
3672 }
3673 return gen_reg_rtx (mode);
3674 }
3675
3676 /* Return a register that contains the constant in BUILDER, given that
3677 the constant is a legitimate move operand. Use TARGET as the register
3678 if it is nonnull and convenient. */
3679
3680 static rtx
3681 aarch64_emit_set_immediate (rtx target, rtx_vector_builder &builder)
3682 {
3683 rtx src = builder.build ();
3684 target = aarch64_target_reg (target, GET_MODE (src));
3685 emit_insn (gen_rtx_SET (target, src));
3686 return target;
3687 }
3688
3689 static rtx
3690 aarch64_force_temporary (machine_mode mode, rtx x, rtx value)
3691 {
3692 if (can_create_pseudo_p ())
3693 return force_reg (mode, value);
3694 else
3695 {
3696 gcc_assert (x);
3697 aarch64_emit_move (x, value);
3698 return x;
3699 }
3700 }
3701
3702 /* Return true if predicate value X is a constant in which every element
3703 is a CONST_INT. When returning true, describe X in BUILDER as a VNx16BI
3704 value, i.e. as a predicate in which all bits are significant. */
3705
3706 static bool
3707 aarch64_get_sve_pred_bits (rtx_vector_builder &builder, rtx x)
3708 {
3709 if (!CONST_VECTOR_P (x))
3710 return false;
3711
3712 unsigned int factor = vector_element_size (GET_MODE_NUNITS (VNx16BImode),
3713 GET_MODE_NUNITS (GET_MODE (x)));
3714 unsigned int npatterns = CONST_VECTOR_NPATTERNS (x) * factor;
3715 unsigned int nelts_per_pattern = CONST_VECTOR_NELTS_PER_PATTERN (x);
3716 builder.new_vector (VNx16BImode, npatterns, nelts_per_pattern);
3717
3718 unsigned int nelts = const_vector_encoded_nelts (x);
3719 for (unsigned int i = 0; i < nelts; ++i)
3720 {
3721 rtx elt = CONST_VECTOR_ENCODED_ELT (x, i);
3722 if (!CONST_INT_P (elt))
3723 return false;
3724
3725 builder.quick_push (elt);
3726 for (unsigned int j = 1; j < factor; ++j)
3727 builder.quick_push (const0_rtx);
3728 }
3729 builder.finalize ();
3730 return true;
3731 }
3732
3733 /* BUILDER contains a predicate constant of mode VNx16BI. Return the
3734 widest predicate element size it can have (that is, the largest size
3735 for which each element would still be 0 or 1). */
3736
3737 unsigned int
3738 aarch64_widest_sve_pred_elt_size (rtx_vector_builder &builder)
3739 {
3740 /* Start with the most optimistic assumption: that we only need
3741 one bit per pattern. This is what we will use if only the first
3742 bit in each pattern is ever set. */
3743 unsigned int mask = GET_MODE_SIZE (DImode);
3744 mask |= builder.npatterns ();
3745
3746 /* Look for set bits. */
3747 unsigned int nelts = builder.encoded_nelts ();
3748 for (unsigned int i = 1; i < nelts; ++i)
3749 if (INTVAL (builder.elt (i)) != 0)
3750 {
3751 if (i & 1)
3752 return 1;
3753 mask |= i;
3754 }
3755 return mask & -mask;
3756 }
3757
3758 /* If VNx16BImode rtx X is a canonical PTRUE for a predicate mode,
3759 return that predicate mode, otherwise return opt_machine_mode (). */
3760
3761 opt_machine_mode
3762 aarch64_ptrue_all_mode (rtx x)
3763 {
3764 gcc_assert (GET_MODE (x) == VNx16BImode);
3765 if (!CONST_VECTOR_P (x)
3766 || !CONST_VECTOR_DUPLICATE_P (x)
3767 || !CONST_INT_P (CONST_VECTOR_ENCODED_ELT (x, 0))
3768 || INTVAL (CONST_VECTOR_ENCODED_ELT (x, 0)) == 0)
3769 return opt_machine_mode ();
3770
3771 unsigned int nelts = const_vector_encoded_nelts (x);
3772 for (unsigned int i = 1; i < nelts; ++i)
3773 if (CONST_VECTOR_ENCODED_ELT (x, i) != const0_rtx)
3774 return opt_machine_mode ();
3775
3776 return aarch64_sve_pred_mode (nelts);
3777 }
3778
3779 /* BUILDER is a predicate constant of mode VNx16BI. Consider the value
3780 that the constant would have with predicate element size ELT_SIZE
3781 (ignoring the upper bits in each element) and return:
3782
3783 * -1 if all bits are set
3784 * N if the predicate has N leading set bits followed by all clear bits
3785 * 0 if the predicate does not have any of these forms. */
3786
3787 int
3788 aarch64_partial_ptrue_length (rtx_vector_builder &builder,
3789 unsigned int elt_size)
3790 {
3791 /* If nelts_per_pattern is 3, we have set bits followed by clear bits
3792 followed by set bits. */
3793 if (builder.nelts_per_pattern () == 3)
3794 return 0;
3795
3796 /* Skip over leading set bits. */
3797 unsigned int nelts = builder.encoded_nelts ();
3798 unsigned int i = 0;
3799 for (; i < nelts; i += elt_size)
3800 if (INTVAL (builder.elt (i)) == 0)
3801 break;
3802 unsigned int vl = i / elt_size;
3803
3804 /* Check for the all-true case. */
3805 if (i == nelts)
3806 return -1;
3807
3808 /* If nelts_per_pattern is 1, then either VL is zero, or we have a
3809 repeating pattern of set bits followed by clear bits. */
3810 if (builder.nelts_per_pattern () != 2)
3811 return 0;
3812
3813 /* We have a "foreground" value and a duplicated "background" value.
3814 If the background might repeat and the last set bit belongs to it,
3815 we might have set bits followed by clear bits followed by set bits. */
3816 if (i > builder.npatterns () && maybe_ne (nelts, builder.full_nelts ()))
3817 return 0;
3818
3819 /* Make sure that the rest are all clear. */
3820 for (; i < nelts; i += elt_size)
3821 if (INTVAL (builder.elt (i)) != 0)
3822 return 0;
3823
3824 return vl;
3825 }
3826
3827 /* See if there is an svpattern that encodes an SVE predicate of mode
3828 PRED_MODE in which the first VL bits are set and the rest are clear.
3829 Return the pattern if so, otherwise return AARCH64_NUM_SVPATTERNS.
3830 A VL of -1 indicates an all-true vector. */
3831
3832 aarch64_svpattern
3833 aarch64_svpattern_for_vl (machine_mode pred_mode, int vl)
3834 {
3835 if (vl < 0)
3836 return AARCH64_SV_ALL;
3837
3838 if (maybe_gt (vl, GET_MODE_NUNITS (pred_mode)))
3839 return AARCH64_NUM_SVPATTERNS;
3840
3841 if (vl >= 1 && vl <= 8)
3842 return aarch64_svpattern (AARCH64_SV_VL1 + (vl - 1));
3843
3844 if (vl >= 16 && vl <= 256 && pow2p_hwi (vl))
3845 return aarch64_svpattern (AARCH64_SV_VL16 + (exact_log2 (vl) - 4));
3846
3847 int max_vl;
3848 if (GET_MODE_NUNITS (pred_mode).is_constant (&max_vl))
3849 {
3850 if (vl == (max_vl / 3) * 3)
3851 return AARCH64_SV_MUL3;
3852 /* These would only trigger for non-power-of-2 lengths. */
3853 if (vl == (max_vl & -4))
3854 return AARCH64_SV_MUL4;
3855 if (vl == (1 << floor_log2 (max_vl)))
3856 return AARCH64_SV_POW2;
3857 if (vl == max_vl)
3858 return AARCH64_SV_ALL;
3859 }
3860 return AARCH64_NUM_SVPATTERNS;
3861 }
3862
3863 /* Return a VNx16BImode constant in which every sequence of ELT_SIZE
3864 bits has the lowest bit set and the upper bits clear. This is the
3865 VNx16BImode equivalent of a PTRUE for controlling elements of
3866 ELT_SIZE bytes. However, because the constant is VNx16BImode,
3867 all bits are significant, even the upper zeros. */
3868
3869 rtx
3870 aarch64_ptrue_all (unsigned int elt_size)
3871 {
3872 rtx_vector_builder builder (VNx16BImode, elt_size, 1);
3873 builder.quick_push (const1_rtx);
3874 for (unsigned int i = 1; i < elt_size; ++i)
3875 builder.quick_push (const0_rtx);
3876 return builder.build ();
3877 }
3878
3879 /* Return an all-true predicate register of mode MODE. */
3880
3881 rtx
3882 aarch64_ptrue_reg (machine_mode mode)
3883 {
3884 gcc_assert (aarch64_sve_pred_mode_p (mode));
3885 rtx reg = force_reg (VNx16BImode, CONSTM1_RTX (VNx16BImode));
3886 return gen_lowpart (mode, reg);
3887 }
3888
3889 /* Return an all-true (restricted to the leading VL bits) predicate register of
3890 mode MODE. */
3891
3892 rtx
3893 aarch64_ptrue_reg (machine_mode mode, unsigned int vl)
3894 {
3895 gcc_assert (aarch64_sve_pred_mode_p (mode));
3896
3897 rtx_vector_builder builder (VNx16BImode, vl, 2);
3898
3899 for (unsigned i = 0; i < vl; i++)
3900 builder.quick_push (CONST1_RTX (BImode));
3901
3902 for (unsigned i = 0; i < vl; i++)
3903 builder.quick_push (CONST0_RTX (BImode));
3904
3905 rtx const_vec = builder.build ();
3906 rtx reg = force_reg (VNx16BImode, const_vec);
3907 return gen_lowpart (mode, reg);
3908 }
3909
3910 /* Return a register of mode PRED_MODE for controlling data of mode DATA_MODE.
3911
3912 DATA_MODE can be a scalar, an Advanced SIMD vector, or an SVE vector.
3913 If it's an N-byte scalar or an Advanced SIMD vector, the first N bits
3914 of the predicate will be active and the rest will be inactive.
3915 If DATA_MODE is an SVE mode, every bit of the predicate will be active. */
3916 rtx
3917 aarch64_ptrue_reg (machine_mode pred_mode, machine_mode data_mode)
3918 {
3919 if (aarch64_sve_mode_p (data_mode))
3920 return aarch64_ptrue_reg (pred_mode);
3921
3922 auto size = GET_MODE_SIZE (data_mode).to_constant ();
3923 return aarch64_ptrue_reg (pred_mode, size);
3924 }
3925
3926 /* Return an all-false predicate register of mode MODE. */
3927
3928 rtx
3929 aarch64_pfalse_reg (machine_mode mode)
3930 {
3931 gcc_assert (aarch64_sve_pred_mode_p (mode));
3932 rtx reg = force_reg (VNx16BImode, CONST0_RTX (VNx16BImode));
3933 return gen_lowpart (mode, reg);
3934 }
3935
3936 /* PRED1[0] is a PTEST predicate and PRED1[1] is an aarch64_sve_ptrue_flag
3937 for it. PRED2[0] is the predicate for the instruction whose result
3938 is tested by the PTEST and PRED2[1] is again an aarch64_sve_ptrue_flag
3939 for it. Return true if we can prove that the two predicates are
3940 equivalent for PTEST purposes; that is, if we can replace PRED2[0]
3941 with PRED1[0] without changing behavior. */
3942
3943 bool
3944 aarch64_sve_same_pred_for_ptest_p (rtx *pred1, rtx *pred2)
3945 {
3946 machine_mode mode = GET_MODE (pred1[0]);
3947 gcc_assert (aarch64_sve_pred_mode_p (mode)
3948 && mode == GET_MODE (pred2[0])
3949 && aarch64_sve_ptrue_flag (pred1[1], SImode)
3950 && aarch64_sve_ptrue_flag (pred2[1], SImode));
3951
3952 bool ptrue1_p = (pred1[0] == CONSTM1_RTX (mode)
3953 || INTVAL (pred1[1]) == SVE_KNOWN_PTRUE);
3954 bool ptrue2_p = (pred2[0] == CONSTM1_RTX (mode)
3955 || INTVAL (pred2[1]) == SVE_KNOWN_PTRUE);
3956 return (ptrue1_p && ptrue2_p) || rtx_equal_p (pred1[0], pred2[0]);
3957 }
3958
3959 /* Emit a comparison CMP between OP0 and OP1, both of which have mode
3960 DATA_MODE, and return the result in a predicate of mode PRED_MODE.
3961 Use TARGET as the target register if nonnull and convenient. */
3962
3963 static rtx
3964 aarch64_sve_emit_int_cmp (rtx target, machine_mode pred_mode, rtx_code cmp,
3965 machine_mode data_mode, rtx op1, rtx op2)
3966 {
3967 insn_code icode = code_for_aarch64_pred_cmp (cmp, data_mode);
3968 expand_operand ops[5];
3969 create_output_operand (&ops[0], target, pred_mode);
3970 create_input_operand (&ops[1], CONSTM1_RTX (pred_mode), pred_mode);
3971 create_integer_operand (&ops[2], SVE_KNOWN_PTRUE);
3972 create_input_operand (&ops[3], op1, data_mode);
3973 create_input_operand (&ops[4], op2, data_mode);
3974 expand_insn (icode, 5, ops);
3975 return ops[0].value;
3976 }
3977
3978 /* Use a comparison to convert integer vector SRC into MODE, which is
3979 the corresponding SVE predicate mode. Use TARGET for the result
3980 if it's nonnull and convenient. */
3981
3982 rtx
3983 aarch64_convert_sve_data_to_pred (rtx target, machine_mode mode, rtx src)
3984 {
3985 machine_mode src_mode = GET_MODE (src);
3986 return aarch64_sve_emit_int_cmp (target, mode, NE, src_mode,
3987 src, CONST0_RTX (src_mode));
3988 }
3989
3990 /* Return the assembly token for svprfop value PRFOP. */
3991
3992 static const char *
3993 svprfop_token (enum aarch64_svprfop prfop)
3994 {
3995 switch (prfop)
3996 {
3997 #define CASE(UPPER, LOWER, VALUE) case AARCH64_SV_##UPPER: return #LOWER;
3998 AARCH64_FOR_SVPRFOP (CASE)
3999 #undef CASE
4000 case AARCH64_NUM_SVPRFOPS:
4001 break;
4002 }
4003 gcc_unreachable ();
4004 }
4005
4006 /* Return the assembly string for an SVE prefetch operation with
4007 mnemonic MNEMONIC, given that PRFOP_RTX is the prefetch operation
4008 and that SUFFIX is the format for the remaining operands. */
4009
4010 char *
4011 aarch64_output_sve_prefetch (const char *mnemonic, rtx prfop_rtx,
4012 const char *suffix)
4013 {
4014 static char buffer[128];
4015 aarch64_svprfop prfop = (aarch64_svprfop) INTVAL (prfop_rtx);
4016 unsigned int written = snprintf (buffer, sizeof (buffer), "%s\t%s, %s",
4017 mnemonic, svprfop_token (prfop), suffix);
4018 gcc_assert (written < sizeof (buffer));
4019 return buffer;
4020 }
4021
4022 /* Check whether we can calculate the number of elements in PATTERN
4023 at compile time, given that there are NELTS_PER_VQ elements per
4024 128-bit block. Return the value if so, otherwise return -1. */
4025
4026 HOST_WIDE_INT
4027 aarch64_fold_sve_cnt_pat (aarch64_svpattern pattern, unsigned int nelts_per_vq)
4028 {
4029 unsigned int vl, const_vg;
4030 if (pattern >= AARCH64_SV_VL1 && pattern <= AARCH64_SV_VL8)
4031 vl = 1 + (pattern - AARCH64_SV_VL1);
4032 else if (pattern >= AARCH64_SV_VL16 && pattern <= AARCH64_SV_VL256)
4033 vl = 16 << (pattern - AARCH64_SV_VL16);
4034 else if (aarch64_sve_vg.is_constant (&const_vg))
4035 {
4036 /* There are two vector granules per quadword. */
4037 unsigned int nelts = (const_vg / 2) * nelts_per_vq;
4038 switch (pattern)
4039 {
4040 case AARCH64_SV_POW2: return 1 << floor_log2 (nelts);
4041 case AARCH64_SV_MUL4: return nelts & -4;
4042 case AARCH64_SV_MUL3: return (nelts / 3) * 3;
4043 case AARCH64_SV_ALL: return nelts;
4044 default: gcc_unreachable ();
4045 }
4046 }
4047 else
4048 return -1;
4049
4050 /* There are two vector granules per quadword. */
4051 poly_uint64 nelts_all = exact_div (aarch64_sve_vg, 2) * nelts_per_vq;
4052 if (known_le (vl, nelts_all))
4053 return vl;
4054
4055 /* Requesting more elements than are available results in a PFALSE. */
4056 if (known_gt (vl, nelts_all))
4057 return 0;
4058
4059 return -1;
4060 }
4061
4062 /* Return true if a single CNT[BHWD] instruction can multiply FACTOR
4063 by the number of 128-bit quadwords in an SVE vector. */
4064
4065 static bool
4066 aarch64_sve_cnt_factor_p (HOST_WIDE_INT factor)
4067 {
4068 /* The coefficient must be [1, 16] * {2, 4, 8, 16}. */
4069 return (IN_RANGE (factor, 2, 16 * 16)
4070 && (factor & 1) == 0
4071 && factor <= 16 * (factor & -factor));
4072 }
4073
4074 /* Return true if we can move VALUE into a register using a single
4075 CNT[BHWD] instruction. */
4076
4077 static bool
4078 aarch64_sve_cnt_immediate_p (poly_int64 value)
4079 {
4080 HOST_WIDE_INT factor = value.coeffs[0];
4081 return value.coeffs[1] == factor && aarch64_sve_cnt_factor_p (factor);
4082 }
4083
4084 /* Likewise for rtx X. */
4085
4086 bool
4087 aarch64_sve_cnt_immediate_p (rtx x)
4088 {
4089 poly_int64 value;
4090 return poly_int_rtx_p (x, &value) && aarch64_sve_cnt_immediate_p (value);
4091 }
4092
4093 /* Return the asm string for an instruction with a CNT-like vector size
4094 operand (a vector pattern followed by a multiplier in the range [1, 16]).
4095 PREFIX is the mnemonic without the size suffix and OPERANDS is the
4096 first part of the operands template (the part that comes before the
4097 vector size itself). PATTERN is the pattern to use. FACTOR is the
4098 number of quadwords. NELTS_PER_VQ, if nonzero, is the number of elements
4099 in each quadword. If it is zero, we can use any element size. */
4100
4101 static char *
4102 aarch64_output_sve_cnt_immediate (const char *prefix, const char *operands,
4103 aarch64_svpattern pattern,
4104 unsigned int factor,
4105 unsigned int nelts_per_vq)
4106 {
4107 static char buffer[sizeof ("sqincd\t%x0, %w0, vl256, mul #16")];
4108
4109 if (nelts_per_vq == 0)
4110 /* There is some overlap in the ranges of the four CNT instructions.
4111 Here we always use the smallest possible element size, so that the
4112 multiplier is 1 whereever possible. */
4113 nelts_per_vq = factor & -factor;
4114 int shift = std::min (exact_log2 (nelts_per_vq), 4);
4115 gcc_assert (IN_RANGE (shift, 1, 4));
4116 char suffix = "dwhb"[shift - 1];
4117
4118 factor >>= shift;
4119 unsigned int written;
4120 if (pattern == AARCH64_SV_ALL && factor == 1)
4121 written = snprintf (buffer, sizeof (buffer), "%s%c\t%s",
4122 prefix, suffix, operands);
4123 else if (factor == 1)
4124 written = snprintf (buffer, sizeof (buffer), "%s%c\t%s, %s",
4125 prefix, suffix, operands, svpattern_token (pattern));
4126 else
4127 written = snprintf (buffer, sizeof (buffer), "%s%c\t%s, %s, mul #%d",
4128 prefix, suffix, operands, svpattern_token (pattern),
4129 factor);
4130 gcc_assert (written < sizeof (buffer));
4131 return buffer;
4132 }
4133
4134 /* Return the asm string for an instruction with a CNT-like vector size
4135 operand (a vector pattern followed by a multiplier in the range [1, 16]).
4136 PREFIX is the mnemonic without the size suffix and OPERANDS is the
4137 first part of the operands template (the part that comes before the
4138 vector size itself). X is the value of the vector size operand,
4139 as a polynomial integer rtx; we need to convert this into an "all"
4140 pattern with a multiplier. */
4141
4142 char *
4143 aarch64_output_sve_cnt_immediate (const char *prefix, const char *operands,
4144 rtx x)
4145 {
4146 poly_int64 value = rtx_to_poly_int64 (x);
4147 gcc_assert (aarch64_sve_cnt_immediate_p (value));
4148 return aarch64_output_sve_cnt_immediate (prefix, operands, AARCH64_SV_ALL,
4149 value.coeffs[1], 0);
4150 }
4151
4152 /* Return the asm string for an instruction with a CNT-like vector size
4153 operand (a vector pattern followed by a multiplier in the range [1, 16]).
4154 PREFIX is the mnemonic without the size suffix and OPERANDS is the
4155 first part of the operands template (the part that comes before the
4156 vector size itself). CNT_PAT[0..2] are the operands of the
4157 UNSPEC_SVE_CNT_PAT; see aarch64_sve_cnt_pat for details. */
4158
4159 char *
4160 aarch64_output_sve_cnt_pat_immediate (const char *prefix,
4161 const char *operands, rtx *cnt_pat)
4162 {
4163 aarch64_svpattern pattern = (aarch64_svpattern) INTVAL (cnt_pat[0]);
4164 unsigned int nelts_per_vq = INTVAL (cnt_pat[1]);
4165 unsigned int factor = INTVAL (cnt_pat[2]) * nelts_per_vq;
4166 return aarch64_output_sve_cnt_immediate (prefix, operands, pattern,
4167 factor, nelts_per_vq);
4168 }
4169
4170 /* Return true if we can add X using a single SVE INC or DEC instruction. */
4171
4172 bool
4173 aarch64_sve_scalar_inc_dec_immediate_p (rtx x)
4174 {
4175 poly_int64 value;
4176 return (poly_int_rtx_p (x, &value)
4177 && (aarch64_sve_cnt_immediate_p (value)
4178 || aarch64_sve_cnt_immediate_p (-value)));
4179 }
4180
4181 /* Return the asm string for adding SVE INC/DEC immediate OFFSET to
4182 operand 0. */
4183
4184 char *
4185 aarch64_output_sve_scalar_inc_dec (rtx offset)
4186 {
4187 poly_int64 offset_value = rtx_to_poly_int64 (offset);
4188 gcc_assert (offset_value.coeffs[0] == offset_value.coeffs[1]);
4189 if (offset_value.coeffs[1] > 0)
4190 return aarch64_output_sve_cnt_immediate ("inc", "%x0", AARCH64_SV_ALL,
4191 offset_value.coeffs[1], 0);
4192 else
4193 return aarch64_output_sve_cnt_immediate ("dec", "%x0", AARCH64_SV_ALL,
4194 -offset_value.coeffs[1], 0);
4195 }
4196
4197 /* Return true if a single RDVL instruction can multiply FACTOR by the
4198 number of 128-bit quadwords in an SVE vector. This is also the
4199 range of ADDVL. */
4200
4201 static bool
4202 aarch64_sve_rdvl_addvl_factor_p (HOST_WIDE_INT factor)
4203 {
4204 return (multiple_p (factor, 16)
4205 && IN_RANGE (factor, -32 * 16, 31 * 16));
4206 }
4207
4208 /* Return true if ADDPL can be used to add FACTOR multiplied by the number
4209 of quadwords in an SVE vector. */
4210
4211 static bool
4212 aarch64_sve_addpl_factor_p (HOST_WIDE_INT factor)
4213 {
4214 return (multiple_p (factor, 2)
4215 && IN_RANGE (factor, -32 * 2, 31 * 2));
4216 }
4217
4218 /* Return true if we can move VALUE into a register using a single
4219 RDVL instruction. */
4220
4221 static bool
4222 aarch64_sve_rdvl_immediate_p (poly_int64 value)
4223 {
4224 HOST_WIDE_INT factor = value.coeffs[0];
4225 return value.coeffs[1] == factor && aarch64_sve_rdvl_addvl_factor_p (factor);
4226 }
4227
4228 /* Likewise for rtx X. */
4229
4230 bool
4231 aarch64_sve_rdvl_immediate_p (rtx x)
4232 {
4233 poly_int64 value;
4234 return poly_int_rtx_p (x, &value) && aarch64_sve_rdvl_immediate_p (value);
4235 }
4236
4237 /* Return the asm string for moving RDVL immediate OFFSET into register
4238 operand 0. */
4239
4240 char *
4241 aarch64_output_sve_rdvl (rtx offset)
4242 {
4243 static char buffer[sizeof ("rdvl\t%x0, #-") + 3 * sizeof (int)];
4244 poly_int64 offset_value = rtx_to_poly_int64 (offset);
4245 gcc_assert (aarch64_sve_rdvl_immediate_p (offset_value));
4246
4247 int factor = offset_value.coeffs[1];
4248 snprintf (buffer, sizeof (buffer), "rdvl\t%%x0, #%d", factor / 16);
4249 return buffer;
4250 }
4251
4252 /* Return true if we can add VALUE to a register using a single ADDVL
4253 or ADDPL instruction. */
4254
4255 static bool
4256 aarch64_sve_addvl_addpl_immediate_p (poly_int64 value)
4257 {
4258 HOST_WIDE_INT factor = value.coeffs[0];
4259 if (factor == 0 || value.coeffs[1] != factor)
4260 return false;
4261 return (aarch64_sve_rdvl_addvl_factor_p (factor)
4262 || aarch64_sve_addpl_factor_p (factor));
4263 }
4264
4265 /* Likewise for rtx X. */
4266
4267 bool
4268 aarch64_sve_addvl_addpl_immediate_p (rtx x)
4269 {
4270 poly_int64 value;
4271 return (poly_int_rtx_p (x, &value)
4272 && aarch64_sve_addvl_addpl_immediate_p (value));
4273 }
4274
4275 /* Return the asm string for adding ADDVL or ADDPL immediate OFFSET
4276 to operand 1 and storing the result in operand 0. */
4277
4278 char *
4279 aarch64_output_sve_addvl_addpl (rtx offset)
4280 {
4281 static char buffer[sizeof ("addpl\t%x0, %x1, #-") + 3 * sizeof (int)];
4282 poly_int64 offset_value = rtx_to_poly_int64 (offset);
4283 gcc_assert (aarch64_sve_addvl_addpl_immediate_p (offset_value));
4284
4285 int factor = offset_value.coeffs[1];
4286 if ((factor & 15) == 0)
4287 snprintf (buffer, sizeof (buffer), "addvl\t%%x0, %%x1, #%d", factor / 16);
4288 else
4289 snprintf (buffer, sizeof (buffer), "addpl\t%%x0, %%x1, #%d", factor / 2);
4290 return buffer;
4291 }
4292
4293 /* Return true if X is a valid immediate for an SVE vector INC or DEC
4294 instruction. If it is, store the number of elements in each vector
4295 quadword in *NELTS_PER_VQ_OUT (if nonnull) and store the multiplication
4296 factor in *FACTOR_OUT (if nonnull). */
4297
4298 bool
4299 aarch64_sve_vector_inc_dec_immediate_p (rtx x, int *factor_out,
4300 unsigned int *nelts_per_vq_out)
4301 {
4302 rtx elt;
4303 poly_int64 value;
4304
4305 if (!const_vec_duplicate_p (x, &elt)
4306 || !poly_int_rtx_p (elt, &value))
4307 return false;
4308
4309 unsigned int nelts_per_vq = 128 / GET_MODE_UNIT_BITSIZE (GET_MODE (x));
4310 if (nelts_per_vq != 8 && nelts_per_vq != 4 && nelts_per_vq != 2)
4311 /* There's no vector INCB. */
4312 return false;
4313
4314 HOST_WIDE_INT factor = value.coeffs[0];
4315 if (value.coeffs[1] != factor)
4316 return false;
4317
4318 /* The coefficient must be [1, 16] * NELTS_PER_VQ. */
4319 if ((factor % nelts_per_vq) != 0
4320 || !IN_RANGE (abs (factor), nelts_per_vq, 16 * nelts_per_vq))
4321 return false;
4322
4323 if (factor_out)
4324 *factor_out = factor;
4325 if (nelts_per_vq_out)
4326 *nelts_per_vq_out = nelts_per_vq;
4327 return true;
4328 }
4329
4330 /* Return true if X is a valid immediate for an SVE vector INC or DEC
4331 instruction. */
4332
4333 bool
4334 aarch64_sve_vector_inc_dec_immediate_p (rtx x)
4335 {
4336 return aarch64_sve_vector_inc_dec_immediate_p (x, NULL, NULL);
4337 }
4338
4339 /* Return the asm template for an SVE vector INC or DEC instruction.
4340 OPERANDS gives the operands before the vector count and X is the
4341 value of the vector count operand itself. */
4342
4343 char *
4344 aarch64_output_sve_vector_inc_dec (const char *operands, rtx x)
4345 {
4346 int factor;
4347 unsigned int nelts_per_vq;
4348 if (!aarch64_sve_vector_inc_dec_immediate_p (x, &factor, &nelts_per_vq))
4349 gcc_unreachable ();
4350 if (factor < 0)
4351 return aarch64_output_sve_cnt_immediate ("dec", operands, AARCH64_SV_ALL,
4352 -factor, nelts_per_vq);
4353 else
4354 return aarch64_output_sve_cnt_immediate ("inc", operands, AARCH64_SV_ALL,
4355 factor, nelts_per_vq);
4356 }
4357
4358 /* Return a constant that represents FACTOR multiplied by the
4359 number of 128-bit quadwords in an SME vector. ISA_MODE is the
4360 ISA mode in which the calculation is being performed. */
4361
4362 rtx
4363 aarch64_sme_vq_immediate (machine_mode mode, HOST_WIDE_INT factor,
4364 aarch64_isa_mode isa_mode)
4365 {
4366 gcc_assert (aarch64_sve_rdvl_addvl_factor_p (factor));
4367 if (isa_mode & AARCH64_ISA_MODE_SM_ON)
4368 /* We're in streaming mode, so we can use normal poly-int values. */
4369 return gen_int_mode ({ factor, factor }, mode);
4370
4371 rtvec vec = gen_rtvec (1, gen_int_mode (factor, SImode));
4372 rtx unspec = gen_rtx_UNSPEC (mode, vec, UNSPEC_SME_VQ);
4373 return gen_rtx_CONST (mode, unspec);
4374 }
4375
4376 /* Return true if X is a constant that represents some number X
4377 multiplied by the number of quadwords in an SME vector. Store this X
4378 in *FACTOR if so. */
4379
4380 static bool
4381 aarch64_sme_vq_unspec_p (const_rtx x, HOST_WIDE_INT *factor)
4382 {
4383 if (!TARGET_SME || GET_CODE (x) != CONST)
4384 return false;
4385
4386 x = XEXP (x, 0);
4387 if (GET_CODE (x) != UNSPEC
4388 || XINT (x, 1) != UNSPEC_SME_VQ
4389 || XVECLEN (x, 0) != 1)
4390 return false;
4391
4392 x = XVECEXP (x, 0, 0);
4393 if (!CONST_INT_P (x))
4394 return false;
4395
4396 *factor = INTVAL (x);
4397 return true;
4398 }
4399
4400 /* Return true if X is a constant that represents some number Y
4401 multiplied by the number of quadwords in an SME vector, and if
4402 that Y is in the range of RDSVL. */
4403
4404 bool
4405 aarch64_rdsvl_immediate_p (const_rtx x)
4406 {
4407 HOST_WIDE_INT factor;
4408 return (aarch64_sme_vq_unspec_p (x, &factor)
4409 && aarch64_sve_rdvl_addvl_factor_p (factor));
4410 }
4411
4412 /* Return the asm string for an RDSVL instruction that calculates X,
4413 which is a constant that satisfies aarch64_rdsvl_immediate_p. */
4414
4415 char *
4416 aarch64_output_rdsvl (const_rtx x)
4417 {
4418 gcc_assert (aarch64_rdsvl_immediate_p (x));
4419 static char buffer[sizeof ("rdsvl\t%x0, #-") + 3 * sizeof (int)];
4420 x = XVECEXP (XEXP (x, 0), 0, 0);
4421 snprintf (buffer, sizeof (buffer), "rdsvl\t%%x0, #%d",
4422 (int) INTVAL (x) / 16);
4423 return buffer;
4424 }
4425
4426 /* Return true if X is a constant that can be added using ADDSVL or ADDSPL. */
4427
4428 bool
4429 aarch64_addsvl_addspl_immediate_p (const_rtx x)
4430 {
4431 HOST_WIDE_INT factor;
4432 return (aarch64_sme_vq_unspec_p (x, &factor)
4433 && (aarch64_sve_rdvl_addvl_factor_p (factor)
4434 || aarch64_sve_addpl_factor_p (factor)));
4435 }
4436
4437 /* X is a constant that satisfies aarch64_addsvl_addspl_immediate_p.
4438 Return the asm string for the associated instruction. */
4439
4440 char *
4441 aarch64_output_addsvl_addspl (rtx x)
4442 {
4443 static char buffer[sizeof ("addspl\t%x0, %x1, #-") + 3 * sizeof (int)];
4444 HOST_WIDE_INT factor;
4445 if (!aarch64_sme_vq_unspec_p (x, &factor))
4446 gcc_unreachable ();
4447 if (aarch64_sve_rdvl_addvl_factor_p (factor))
4448 snprintf (buffer, sizeof (buffer), "addsvl\t%%x0, %%x1, #%d",
4449 (int) factor / 16);
4450 else if (aarch64_sve_addpl_factor_p (factor))
4451 snprintf (buffer, sizeof (buffer), "addspl\t%%x0, %%x1, #%d",
4452 (int) factor / 2);
4453 else
4454 gcc_unreachable ();
4455 return buffer;
4456 }
4457
4458 /* Multipliers for repeating bitmasks of width 32, 16, 8, 4, and 2. */
4459
4460 static const unsigned HOST_WIDE_INT bitmask_imm_mul[] =
4461 {
4462 0x0000000100000001ull,
4463 0x0001000100010001ull,
4464 0x0101010101010101ull,
4465 0x1111111111111111ull,
4466 0x5555555555555555ull,
4467 };
4468
4469
4470
4471 /* Return true if 64-bit VAL is a valid bitmask immediate. */
4472 static bool
4473 aarch64_bitmask_imm (unsigned HOST_WIDE_INT val)
4474 {
4475 unsigned HOST_WIDE_INT tmp, mask, first_one, next_one;
4476 int bits;
4477
4478 /* Check for a single sequence of one bits and return quickly if so.
4479 The special cases of all ones and all zeroes returns false. */
4480 tmp = val + (val & -val);
4481
4482 if (tmp == (tmp & -tmp))
4483 return (val + 1) > 1;
4484
4485 /* Invert if the immediate doesn't start with a zero bit - this means we
4486 only need to search for sequences of one bits. */
4487 if (val & 1)
4488 val = ~val;
4489
4490 /* Find the first set bit and set tmp to val with the first sequence of one
4491 bits removed. Return success if there is a single sequence of ones. */
4492 first_one = val & -val;
4493 tmp = val & (val + first_one);
4494
4495 if (tmp == 0)
4496 return true;
4497
4498 /* Find the next set bit and compute the difference in bit position. */
4499 next_one = tmp & -tmp;
4500 bits = clz_hwi (first_one) - clz_hwi (next_one);
4501 mask = val ^ tmp;
4502
4503 /* Check the bit position difference is a power of 2, and that the first
4504 sequence of one bits fits within 'bits' bits. */
4505 if ((mask >> bits) != 0 || bits != (bits & -bits))
4506 return false;
4507
4508 /* Check the sequence of one bits is repeated 64/bits times. */
4509 return val == mask * bitmask_imm_mul[__builtin_clz (bits) - 26];
4510 }
4511
4512
4513 /* Return true if VAL is a valid bitmask immediate for MODE. */
4514 bool
4515 aarch64_bitmask_imm (unsigned HOST_WIDE_INT val, machine_mode mode)
4516 {
4517 if (mode == DImode)
4518 return aarch64_bitmask_imm (val);
4519
4520 if (mode == SImode)
4521 return aarch64_bitmask_imm ((val & 0xffffffff) | (val << 32));
4522
4523 /* Replicate small immediates to fit 64 bits. */
4524 int size = GET_MODE_UNIT_PRECISION (mode);
4525 val &= (HOST_WIDE_INT_1U << size) - 1;
4526 val *= bitmask_imm_mul[__builtin_clz (size) - 26];
4527
4528 return aarch64_bitmask_imm (val);
4529 }
4530
4531
4532 /* Return true if the immediate VAL can be a bitfield immediate
4533 by changing the given MASK bits in VAL to zeroes, ones or bits
4534 from the other half of VAL. Return the new immediate in VAL2. */
4535 static inline bool
4536 aarch64_check_bitmask (unsigned HOST_WIDE_INT val,
4537 unsigned HOST_WIDE_INT &val2,
4538 unsigned HOST_WIDE_INT mask)
4539 {
4540 val2 = val & ~mask;
4541 if (val2 != val && aarch64_bitmask_imm (val2))
4542 return true;
4543 val2 = val | mask;
4544 if (val2 != val && aarch64_bitmask_imm (val2))
4545 return true;
4546 val = val & ~mask;
4547 val2 = val | (((val >> 32) | (val << 32)) & mask);
4548 if (val2 != val && aarch64_bitmask_imm (val2))
4549 return true;
4550 val2 = val | (((val >> 16) | (val << 48)) & mask);
4551 if (val2 != val && aarch64_bitmask_imm (val2))
4552 return true;
4553 return false;
4554 }
4555
4556
4557 /* Return true if VAL is a valid MOVZ immediate. */
4558 static inline bool
4559 aarch64_is_movz (unsigned HOST_WIDE_INT val)
4560 {
4561 return (val >> (ctz_hwi (val) & 48)) < 65536;
4562 }
4563
4564
4565 /* Return true if immediate VAL can be created by a 64-bit MOVI/MOVN/MOVZ. */
4566 bool
4567 aarch64_is_mov_xn_imm (unsigned HOST_WIDE_INT val)
4568 {
4569 return aarch64_is_movz (val) || aarch64_is_movz (~val)
4570 || aarch64_bitmask_imm (val);
4571 }
4572
4573
4574 /* Return true if VAL is an immediate that can be created by a single
4575 MOV instruction. */
4576 bool
4577 aarch64_move_imm (unsigned HOST_WIDE_INT val, machine_mode mode)
4578 {
4579 gcc_assert (mode == SImode || mode == DImode);
4580
4581 if (val < 65536)
4582 return true;
4583
4584 unsigned HOST_WIDE_INT mask =
4585 (val >> 32) == 0 || mode == SImode ? 0xffffffff : HOST_WIDE_INT_M1U;
4586
4587 if (aarch64_is_movz (val & mask) || aarch64_is_movz (~val & mask))
4588 return true;
4589
4590 val = (val & mask) | ((val << 32) & ~mask);
4591 return aarch64_bitmask_imm (val);
4592 }
4593
4594
4595 static int
4596 aarch64_internal_mov_immediate (rtx dest, rtx imm, bool generate,
4597 machine_mode mode)
4598 {
4599 int i;
4600 unsigned HOST_WIDE_INT val, val2, val3, mask;
4601 int one_match, zero_match;
4602 int num_insns;
4603
4604 gcc_assert (mode == SImode || mode == DImode);
4605
4606 val = INTVAL (imm);
4607
4608 if (aarch64_move_imm (val, mode))
4609 {
4610 if (generate)
4611 emit_insn (gen_rtx_SET (dest, imm));
4612 return 1;
4613 }
4614
4615 if ((val >> 32) == 0 || mode == SImode)
4616 {
4617 if (generate)
4618 {
4619 emit_insn (gen_rtx_SET (dest, GEN_INT (val & 0xffff)));
4620 if (mode == SImode)
4621 emit_insn (gen_insv_immsi (dest, GEN_INT (16),
4622 GEN_INT ((val >> 16) & 0xffff)));
4623 else
4624 emit_insn (gen_insv_immdi (dest, GEN_INT (16),
4625 GEN_INT ((val >> 16) & 0xffff)));
4626 }
4627 return 2;
4628 }
4629
4630 /* Remaining cases are all for DImode. */
4631
4632 mask = 0xffff;
4633 zero_match = ((val & mask) == 0) + ((val & (mask << 16)) == 0) +
4634 ((val & (mask << 32)) == 0) + ((val & (mask << 48)) == 0);
4635 one_match = ((~val & mask) == 0) + ((~val & (mask << 16)) == 0) +
4636 ((~val & (mask << 32)) == 0) + ((~val & (mask << 48)) == 0);
4637
4638 /* Try a bitmask immediate and a movk to generate the immediate
4639 in 2 instructions. */
4640
4641 if (zero_match < 2 && one_match < 2)
4642 {
4643 for (i = 0; i < 64; i += 16)
4644 {
4645 if (aarch64_check_bitmask (val, val2, mask << i))
4646 break;
4647
4648 val2 = val & ~(mask << i);
4649 if ((val2 >> 32) == 0 && aarch64_move_imm (val2, DImode))
4650 break;
4651 }
4652
4653 if (i != 64)
4654 {
4655 if (generate)
4656 {
4657 emit_insn (gen_rtx_SET (dest, GEN_INT (val2)));
4658 emit_insn (gen_insv_immdi (dest, GEN_INT (i),
4659 GEN_INT ((val >> i) & 0xffff)));
4660 }
4661 return 2;
4662 }
4663
4664 /* Try 2 bitmask immediates which are xor'd together. */
4665 for (i = 0; i < 64; i += 16)
4666 {
4667 val2 = (val >> i) & mask;
4668 val2 |= val2 << 16;
4669 val2 |= val2 << 32;
4670 if (aarch64_bitmask_imm (val2) && aarch64_bitmask_imm (val ^ val2))
4671 break;
4672 }
4673
4674 if (i != 64)
4675 {
4676 if (generate)
4677 {
4678 emit_insn (gen_rtx_SET (dest, GEN_INT (val2)));
4679 emit_insn (gen_xordi3 (dest, dest, GEN_INT (val ^ val2)));
4680 }
4681 return 2;
4682 }
4683 }
4684
4685 /* Try a bitmask plus 2 movk to generate the immediate in 3 instructions. */
4686 if (zero_match + one_match == 0)
4687 {
4688 for (i = 0; i < 48; i += 16)
4689 for (int j = i + 16; j < 64; j += 16)
4690 if (aarch64_check_bitmask (val, val2, (mask << i) | (mask << j)))
4691 {
4692 if (generate)
4693 {
4694 emit_insn (gen_rtx_SET (dest, GEN_INT (val2)));
4695 emit_insn (gen_insv_immdi (dest, GEN_INT (i),
4696 GEN_INT ((val >> i) & 0xffff)));
4697 emit_insn (gen_insv_immdi (dest, GEN_INT (j),
4698 GEN_INT ((val >> j) & 0xffff)));
4699 }
4700 return 3;
4701 }
4702
4703 /* Try shifting and inserting the bottom 32-bits into the top bits. */
4704 val2 = val & 0xffffffff;
4705 val3 = 0xffffffff;
4706 val3 = val2 | (val3 << 32);
4707 for (i = 17; i < 48; i++)
4708 if ((val2 | (val2 << i)) == val)
4709 {
4710 if (generate)
4711 {
4712 emit_insn (gen_rtx_SET (dest, GEN_INT (val2 & 0xffff)));
4713 emit_insn (gen_insv_immdi (dest, GEN_INT (16),
4714 GEN_INT (val2 >> 16)));
4715 emit_insn (gen_ior_ashldi3 (dest, dest, GEN_INT (i), dest));
4716 }
4717 return 3;
4718 }
4719 else if ((val3 & ~(val3 << i)) == val)
4720 {
4721 if (generate)
4722 {
4723 emit_insn (gen_rtx_SET (dest, GEN_INT (val3 | 0xffff0000)));
4724 emit_insn (gen_insv_immdi (dest, GEN_INT (16),
4725 GEN_INT (val2 >> 16)));
4726 emit_insn (gen_and_one_cmpl_ashldi3 (dest, dest, GEN_INT (i),
4727 dest));
4728 }
4729 return 3;
4730 }
4731 }
4732
4733 /* Generate 2-4 instructions, skipping 16 bits of all zeroes or ones which
4734 are emitted by the initial mov. If one_match > zero_match, skip set bits,
4735 otherwise skip zero bits. */
4736
4737 num_insns = 1;
4738 mask = 0xffff;
4739 val2 = one_match > zero_match ? ~val : val;
4740 i = (val2 & mask) != 0 ? 0 : (val2 & (mask << 16)) != 0 ? 16 : 32;
4741
4742 if (generate)
4743 emit_insn (gen_rtx_SET (dest, GEN_INT (one_match > zero_match
4744 ? (val | ~(mask << i))
4745 : (val & (mask << i)))));
4746 for (i += 16; i < 64; i += 16)
4747 {
4748 if ((val2 & (mask << i)) == 0)
4749 continue;
4750 if (generate)
4751 emit_insn (gen_insv_immdi (dest, GEN_INT (i),
4752 GEN_INT ((val >> i) & 0xffff)));
4753 num_insns ++;
4754 }
4755
4756 return num_insns;
4757 }
4758
4759 /* Return whether imm is a 128-bit immediate which is simple enough to
4760 expand inline. */
4761 bool
4762 aarch64_mov128_immediate (rtx imm)
4763 {
4764 if (CONST_INT_P (imm))
4765 return true;
4766
4767 gcc_assert (CONST_WIDE_INT_NUNITS (imm) == 2);
4768
4769 rtx lo = GEN_INT (CONST_WIDE_INT_ELT (imm, 0));
4770 rtx hi = GEN_INT (CONST_WIDE_INT_ELT (imm, 1));
4771
4772 return aarch64_internal_mov_immediate (NULL_RTX, lo, false, DImode)
4773 + aarch64_internal_mov_immediate (NULL_RTX, hi, false, DImode) <= 4;
4774 }
4775
4776
4777 /* Return true if val can be encoded as a 12-bit unsigned immediate with
4778 a left shift of 0 or 12 bits. */
4779 bool
4780 aarch64_uimm12_shift (unsigned HOST_WIDE_INT val)
4781 {
4782 return val < 4096 || (val & 0xfff000) == val;
4783 }
4784
4785 /* Returns the nearest value to VAL that will fit as a 12-bit unsigned immediate
4786 that can be created with a left shift of 0 or 12. */
4787 static HOST_WIDE_INT
4788 aarch64_clamp_to_uimm12_shift (unsigned HOST_WIDE_INT val)
4789 {
4790 /* Check to see if the value fits in 24 bits, as that is the maximum we can
4791 handle correctly. */
4792 gcc_assert (val < 0x1000000);
4793
4794 if (val < 4096)
4795 return val;
4796
4797 return val & 0xfff000;
4798 }
4799
4800
4801 /* Test whether:
4802
4803 X = (X & AND_VAL) | IOR_VAL;
4804
4805 can be implemented using:
4806
4807 MOVK X, #(IOR_VAL >> shift), LSL #shift
4808
4809 Return the shift if so, otherwise return -1. */
4810 int
4811 aarch64_movk_shift (const wide_int_ref &and_val,
4812 const wide_int_ref &ior_val)
4813 {
4814 unsigned int precision = and_val.get_precision ();
4815 unsigned HOST_WIDE_INT mask = 0xffff;
4816 for (unsigned int shift = 0; shift < precision; shift += 16)
4817 {
4818 if (and_val == ~mask && (ior_val & mask) == ior_val)
4819 return shift;
4820 mask <<= 16;
4821 }
4822 return -1;
4823 }
4824
4825 /* Create mask of ones, covering the lowest to highest bits set in VAL_IN.
4826 Assumed precondition: VAL_IN Is not zero. */
4827
4828 unsigned HOST_WIDE_INT
4829 aarch64_and_split_imm1 (HOST_WIDE_INT val_in)
4830 {
4831 int lowest_bit_set = ctz_hwi (val_in);
4832 int highest_bit_set = floor_log2 (val_in);
4833 gcc_assert (val_in != 0);
4834
4835 return ((HOST_WIDE_INT_UC (2) << highest_bit_set) -
4836 (HOST_WIDE_INT_1U << lowest_bit_set));
4837 }
4838
4839 /* Create constant where bits outside of lowest bit set to highest bit set
4840 are set to 1. */
4841
4842 unsigned HOST_WIDE_INT
4843 aarch64_and_split_imm2 (HOST_WIDE_INT val_in)
4844 {
4845 return val_in | ~aarch64_and_split_imm1 (val_in);
4846 }
4847
4848 /* Return true if VAL_IN is a valid 'and' bitmask immediate. */
4849
4850 bool
4851 aarch64_and_bitmask_imm (unsigned HOST_WIDE_INT val_in, machine_mode mode)
4852 {
4853 scalar_int_mode int_mode;
4854 if (!is_a <scalar_int_mode> (mode, &int_mode))
4855 return false;
4856
4857 if (aarch64_bitmask_imm (val_in, int_mode))
4858 return false;
4859
4860 if (aarch64_move_imm (val_in, int_mode))
4861 return false;
4862
4863 unsigned HOST_WIDE_INT imm2 = aarch64_and_split_imm2 (val_in);
4864
4865 return aarch64_bitmask_imm (imm2, int_mode);
4866 }
4867
4868 /* Return the number of temporary registers that aarch64_add_offset_1
4869 would need to add OFFSET to a register. */
4870
4871 static unsigned int
4872 aarch64_add_offset_1_temporaries (HOST_WIDE_INT offset)
4873 {
4874 return absu_hwi (offset) < 0x1000000 ? 0 : 1;
4875 }
4876
4877 /* A subroutine of aarch64_add_offset. Set DEST to SRC + OFFSET for
4878 a non-polynomial OFFSET. MODE is the mode of the addition.
4879 FRAME_RELATED_P is true if the RTX_FRAME_RELATED flag should
4880 be set and CFA adjustments added to the generated instructions.
4881
4882 TEMP1, if nonnull, is a register of mode MODE that can be used as a
4883 temporary if register allocation is already complete. This temporary
4884 register may overlap DEST but must not overlap SRC. If TEMP1 is known
4885 to hold abs (OFFSET), EMIT_MOVE_IMM can be set to false to avoid emitting
4886 the immediate again.
4887
4888 Since this function may be used to adjust the stack pointer, we must
4889 ensure that it cannot cause transient stack deallocation (for example
4890 by first incrementing SP and then decrementing when adjusting by a
4891 large immediate). */
4892
4893 static void
4894 aarch64_add_offset_1 (scalar_int_mode mode, rtx dest,
4895 rtx src, HOST_WIDE_INT offset, rtx temp1,
4896 bool frame_related_p, bool emit_move_imm)
4897 {
4898 gcc_assert (emit_move_imm || temp1 != NULL_RTX);
4899 gcc_assert (temp1 == NULL_RTX || !reg_overlap_mentioned_p (temp1, src));
4900
4901 unsigned HOST_WIDE_INT moffset = absu_hwi (offset);
4902 rtx_insn *insn;
4903
4904 if (!moffset)
4905 {
4906 if (!rtx_equal_p (dest, src))
4907 {
4908 insn = emit_insn (gen_rtx_SET (dest, src));
4909 RTX_FRAME_RELATED_P (insn) = frame_related_p;
4910 }
4911 return;
4912 }
4913
4914 /* Single instruction adjustment. */
4915 if (aarch64_uimm12_shift (moffset))
4916 {
4917 insn = emit_insn (gen_add3_insn (dest, src, GEN_INT (offset)));
4918 RTX_FRAME_RELATED_P (insn) = frame_related_p;
4919 return;
4920 }
4921
4922 /* Emit 2 additions/subtractions if the adjustment is less than 24 bits
4923 and either:
4924
4925 a) the offset cannot be loaded by a 16-bit move or
4926 b) there is no spare register into which we can move it. */
4927 if (moffset < 0x1000000
4928 && ((!temp1 && !can_create_pseudo_p ())
4929 || !aarch64_move_imm (moffset, mode)))
4930 {
4931 HOST_WIDE_INT low_off = moffset & 0xfff;
4932
4933 low_off = offset < 0 ? -low_off : low_off;
4934 insn = emit_insn (gen_add3_insn (dest, src, GEN_INT (low_off)));
4935 RTX_FRAME_RELATED_P (insn) = frame_related_p;
4936 insn = emit_insn (gen_add2_insn (dest, GEN_INT (offset - low_off)));
4937 RTX_FRAME_RELATED_P (insn) = frame_related_p;
4938 return;
4939 }
4940
4941 /* Emit a move immediate if required and an addition/subtraction. */
4942 if (emit_move_imm)
4943 {
4944 gcc_assert (temp1 != NULL_RTX || can_create_pseudo_p ());
4945 temp1 = aarch64_force_temporary (mode, temp1,
4946 gen_int_mode (moffset, mode));
4947 }
4948 insn = emit_insn (offset < 0
4949 ? gen_sub3_insn (dest, src, temp1)
4950 : gen_add3_insn (dest, src, temp1));
4951 if (frame_related_p)
4952 {
4953 RTX_FRAME_RELATED_P (insn) = frame_related_p;
4954 rtx adj = plus_constant (mode, src, offset);
4955 add_reg_note (insn, REG_CFA_ADJUST_CFA, gen_rtx_SET (dest, adj));
4956 }
4957 }
4958
4959 /* Return the number of temporary registers that aarch64_add_offset
4960 would need to move OFFSET into a register or add OFFSET to a register;
4961 ADD_P is true if we want the latter rather than the former. */
4962
4963 static unsigned int
4964 aarch64_offset_temporaries (bool add_p, poly_int64 offset)
4965 {
4966 /* This follows the same structure as aarch64_add_offset. */
4967 if (add_p && aarch64_sve_addvl_addpl_immediate_p (offset))
4968 return 0;
4969
4970 unsigned int count = 0;
4971 HOST_WIDE_INT factor = offset.coeffs[1];
4972 HOST_WIDE_INT constant = offset.coeffs[0] - factor;
4973 poly_int64 poly_offset (factor, factor);
4974 if (add_p && aarch64_sve_addvl_addpl_immediate_p (poly_offset))
4975 /* Need one register for the ADDVL/ADDPL result. */
4976 count += 1;
4977 else if (factor != 0)
4978 {
4979 factor /= (HOST_WIDE_INT) least_bit_hwi (factor);
4980 if (!IN_RANGE (factor, -32, 31))
4981 /* Need one register for the CNT or RDVL result and one for the
4982 multiplication factor. If necessary, the second temporary
4983 can be reused for the constant part of the offset. */
4984 return 2;
4985 /* Need one register for the CNT or RDVL result (which might then
4986 be shifted). */
4987 count += 1;
4988 }
4989 return count + aarch64_add_offset_1_temporaries (constant);
4990 }
4991
4992 /* If X can be represented as a poly_int64, return the number
4993 of temporaries that are required to add it to a register.
4994 Return -1 otherwise. */
4995
4996 int
4997 aarch64_add_offset_temporaries (rtx x)
4998 {
4999 poly_int64 offset;
5000 if (!poly_int_rtx_p (x, &offset))
5001 return -1;
5002 return aarch64_offset_temporaries (true, offset);
5003 }
5004
5005 /* Set DEST to SRC + OFFSET. MODE is the mode of the addition.
5006 FRAME_RELATED_P is true if the RTX_FRAME_RELATED flag should
5007 be set and CFA adjustments added to the generated instructions.
5008
5009 TEMP1, if nonnull, is a register of mode MODE that can be used as a
5010 temporary if register allocation is already complete. This temporary
5011 register may overlap DEST if !FRAME_RELATED_P but must not overlap SRC.
5012 If TEMP1 is known to hold abs (OFFSET), EMIT_MOVE_IMM can be set to
5013 false to avoid emitting the immediate again.
5014
5015 TEMP2, if nonnull, is a second temporary register that doesn't
5016 overlap either DEST or REG.
5017
5018 FORCE_ISA_MODE is AARCH64_ISA_MODE_SM_ON if any variable component of OFFSET
5019 is measured relative to the SME vector length instead of the current
5020 prevailing vector length. It is 0 otherwise.
5021
5022 Since this function may be used to adjust the stack pointer, we must
5023 ensure that it cannot cause transient stack deallocation (for example
5024 by first incrementing SP and then decrementing when adjusting by a
5025 large immediate). */
5026
5027 static void
5028 aarch64_add_offset (scalar_int_mode mode, rtx dest, rtx src,
5029 poly_int64 offset, rtx temp1, rtx temp2,
5030 aarch64_isa_mode force_isa_mode,
5031 bool frame_related_p, bool emit_move_imm = true)
5032 {
5033 gcc_assert (emit_move_imm || temp1 != NULL_RTX);
5034 gcc_assert (temp1 == NULL_RTX || !reg_overlap_mentioned_p (temp1, src));
5035 gcc_assert (temp1 == NULL_RTX
5036 || !frame_related_p
5037 || !reg_overlap_mentioned_p (temp1, dest));
5038 gcc_assert (temp2 == NULL_RTX || !reg_overlap_mentioned_p (dest, temp2));
5039
5040 /* Try using ADDVL or ADDPL to add the whole value. */
5041 if (src != const0_rtx && aarch64_sve_addvl_addpl_immediate_p (offset))
5042 {
5043 gcc_assert (offset.coeffs[0] == offset.coeffs[1]);
5044 rtx offset_rtx;
5045 if (force_isa_mode == 0)
5046 offset_rtx = gen_int_mode (offset, mode);
5047 else
5048 offset_rtx = aarch64_sme_vq_immediate (mode, offset.coeffs[0], 0);
5049 rtx_insn *insn = emit_insn (gen_add3_insn (dest, src, offset_rtx));
5050 RTX_FRAME_RELATED_P (insn) = frame_related_p;
5051 if (frame_related_p && (force_isa_mode & AARCH64_ISA_MODE_SM_ON))
5052 add_reg_note (insn, REG_CFA_ADJUST_CFA,
5053 gen_rtx_SET (dest, plus_constant (Pmode, src,
5054 offset)));
5055 return;
5056 }
5057
5058 /* Coefficient 1 is multiplied by the number of 128-bit blocks in an
5059 SVE vector register, over and above the minimum size of 128 bits.
5060 This is equivalent to half the value returned by CNTD with a
5061 vector shape of ALL. */
5062 HOST_WIDE_INT factor = offset.coeffs[1];
5063 HOST_WIDE_INT constant = offset.coeffs[0] - factor;
5064
5065 /* Try using ADDVL or ADDPL to add the VG-based part. */
5066 poly_int64 poly_offset (factor, factor);
5067 if (src != const0_rtx
5068 && aarch64_sve_addvl_addpl_immediate_p (poly_offset))
5069 {
5070 rtx offset_rtx;
5071 if (force_isa_mode == 0)
5072 offset_rtx = gen_int_mode (poly_offset, mode);
5073 else
5074 offset_rtx = aarch64_sme_vq_immediate (mode, factor, 0);
5075 if (frame_related_p)
5076 {
5077 rtx_insn *insn = emit_insn (gen_add3_insn (dest, src, offset_rtx));
5078 RTX_FRAME_RELATED_P (insn) = true;
5079 if (force_isa_mode & AARCH64_ISA_MODE_SM_ON)
5080 add_reg_note (insn, REG_CFA_ADJUST_CFA,
5081 gen_rtx_SET (dest, plus_constant (Pmode, src,
5082 poly_offset)));
5083 src = dest;
5084 }
5085 else
5086 {
5087 rtx addr = gen_rtx_PLUS (mode, src, offset_rtx);
5088 src = aarch64_force_temporary (mode, temp1, addr);
5089 temp1 = temp2;
5090 temp2 = NULL_RTX;
5091 }
5092 }
5093 /* Otherwise use a CNT-based sequence. */
5094 else if (factor != 0)
5095 {
5096 /* Calculate CNTB * FACTOR / 16 as CNTB * REL_FACTOR * 2**SHIFT,
5097 with negative shifts indicating a shift right. */
5098 HOST_WIDE_INT low_bit = least_bit_hwi (factor);
5099 HOST_WIDE_INT rel_factor = factor / low_bit;
5100 int shift = exact_log2 (low_bit) - 4;
5101 gcc_assert (shift >= -4 && (rel_factor & 1) != 0);
5102
5103 /* Set CODE, VAL and SHIFT so that [+-] VAL * 2**SHIFT is
5104 equal to CNTB * FACTOR / 16, with CODE being the [+-].
5105
5106 We can avoid a multiplication if REL_FACTOR is in the range
5107 of RDVL, although there are then various optimizations that
5108 we can try on top. */
5109 rtx_code code = PLUS;
5110 rtx val;
5111 if (IN_RANGE (rel_factor, -32, 31))
5112 {
5113 if (force_isa_mode & AARCH64_ISA_MODE_SM_ON)
5114 {
5115 /* Try to use an unshifted RDSVL, otherwise fall back on
5116 a shifted RDSVL #1. */
5117 if (aarch64_sve_rdvl_addvl_factor_p (factor))
5118 shift = 0;
5119 else
5120 factor = rel_factor * 16;
5121 val = aarch64_sme_vq_immediate (mode, factor, 0);
5122 }
5123 /* Try to use an unshifted CNT[BHWD] or RDVL. */
5124 else if (aarch64_sve_cnt_factor_p (factor)
5125 || aarch64_sve_rdvl_addvl_factor_p (factor))
5126 {
5127 val = gen_int_mode (poly_int64 (factor, factor), mode);
5128 shift = 0;
5129 }
5130 /* Try to subtract an unshifted CNT[BHWD]. */
5131 else if (aarch64_sve_cnt_factor_p (-factor))
5132 {
5133 code = MINUS;
5134 val = gen_int_mode (poly_int64 (-factor, -factor), mode);
5135 shift = 0;
5136 }
5137 /* If subtraction is free, prefer to load a positive constant.
5138 In the best case this will fit a shifted CNTB. */
5139 else if (src != const0_rtx && rel_factor < 0)
5140 {
5141 code = MINUS;
5142 val = gen_int_mode (-rel_factor * BYTES_PER_SVE_VECTOR, mode);
5143 }
5144 /* Otherwise use a shifted RDVL or CNT[BHWD]. */
5145 else
5146 val = gen_int_mode (rel_factor * BYTES_PER_SVE_VECTOR, mode);
5147 }
5148 else
5149 {
5150 /* If we can calculate CNTB << SHIFT directly, prefer to do that,
5151 since it should increase the chances of being able to use
5152 a shift and add sequence for the multiplication.
5153 If CNTB << SHIFT is out of range, stick with the current
5154 shift factor. */
5155 if (force_isa_mode == 0
5156 && IN_RANGE (low_bit, 2, 16 * 16))
5157 {
5158 val = gen_int_mode (poly_int64 (low_bit, low_bit), mode);
5159 shift = 0;
5160 }
5161 else if ((force_isa_mode & AARCH64_ISA_MODE_SM_ON)
5162 && aarch64_sve_rdvl_addvl_factor_p (low_bit))
5163 {
5164 val = aarch64_sme_vq_immediate (mode, low_bit, 0);
5165 shift = 0;
5166 }
5167 else
5168 val = gen_int_mode (BYTES_PER_SVE_VECTOR, mode);
5169
5170 val = aarch64_force_temporary (mode, temp1, val);
5171
5172 /* Prefer to multiply by a positive factor and subtract rather
5173 than multiply by a negative factor and add, since positive
5174 values are usually easier to move. */
5175 if (rel_factor < 0 && src != const0_rtx)
5176 {
5177 rel_factor = -rel_factor;
5178 code = MINUS;
5179 }
5180
5181 if (can_create_pseudo_p ())
5182 {
5183 rtx coeff1 = gen_int_mode (rel_factor, mode);
5184 val = expand_mult (mode, val, coeff1, NULL_RTX, true, true);
5185 }
5186 else
5187 {
5188 rtx coeff1 = gen_int_mode (rel_factor, mode);
5189 coeff1 = aarch64_force_temporary (mode, temp2, coeff1);
5190 val = gen_rtx_MULT (mode, val, coeff1);
5191 }
5192 }
5193
5194 /* Multiply by 2 ** SHIFT. */
5195 if (shift > 0)
5196 {
5197 val = aarch64_force_temporary (mode, temp1, val);
5198 val = gen_rtx_ASHIFT (mode, val, GEN_INT (shift));
5199 }
5200 else if (shift < 0)
5201 {
5202 val = aarch64_force_temporary (mode, temp1, val);
5203 val = gen_rtx_ASHIFTRT (mode, val, GEN_INT (-shift));
5204 }
5205
5206 /* Add the result to SRC or subtract the result from SRC. */
5207 if (src != const0_rtx)
5208 {
5209 val = aarch64_force_temporary (mode, temp1, val);
5210 val = gen_rtx_fmt_ee (code, mode, src, val);
5211 }
5212 else if (code == MINUS)
5213 {
5214 val = aarch64_force_temporary (mode, temp1, val);
5215 val = gen_rtx_NEG (mode, val);
5216 }
5217
5218 if (constant == 0 || frame_related_p)
5219 {
5220 rtx_insn *insn = emit_insn (gen_rtx_SET (dest, val));
5221 if (frame_related_p)
5222 {
5223 RTX_FRAME_RELATED_P (insn) = true;
5224 add_reg_note (insn, REG_CFA_ADJUST_CFA,
5225 gen_rtx_SET (dest, plus_constant (Pmode, src,
5226 poly_offset)));
5227 }
5228 src = dest;
5229 if (constant == 0)
5230 return;
5231 }
5232 else
5233 {
5234 src = aarch64_force_temporary (mode, temp1, val);
5235 temp1 = temp2;
5236 temp2 = NULL_RTX;
5237 }
5238
5239 emit_move_imm = true;
5240 }
5241
5242 aarch64_add_offset_1 (mode, dest, src, constant, temp1,
5243 frame_related_p, emit_move_imm);
5244 }
5245
5246 /* Like aarch64_add_offset, but the offset is given as an rtx rather
5247 than a poly_int64. */
5248
5249 void
5250 aarch64_split_add_offset (scalar_int_mode mode, rtx dest, rtx src,
5251 rtx offset_rtx, rtx temp1, rtx temp2)
5252 {
5253 aarch64_add_offset (mode, dest, src, rtx_to_poly_int64 (offset_rtx),
5254 temp1, temp2, 0, false);
5255 }
5256
5257 /* Add DELTA to the stack pointer, marking the instructions frame-related.
5258 TEMP1 is available as a temporary if nonnull. FORCE_ISA_MODE is as
5259 for aarch64_add_offset. EMIT_MOVE_IMM is false if TEMP1 already
5260 contains abs (DELTA). */
5261
5262 static inline void
5263 aarch64_add_sp (rtx temp1, rtx temp2, poly_int64 delta,
5264 aarch64_isa_mode force_isa_mode, bool emit_move_imm)
5265 {
5266 aarch64_add_offset (Pmode, stack_pointer_rtx, stack_pointer_rtx, delta,
5267 temp1, temp2, force_isa_mode, true, emit_move_imm);
5268 }
5269
5270 /* Subtract DELTA from the stack pointer, marking the instructions
5271 frame-related if FRAME_RELATED_P. FORCE_ISA_MODE is as for
5272 aarch64_add_offset. TEMP1 is available as a temporary if nonnull. */
5273
5274 static inline void
5275 aarch64_sub_sp (rtx temp1, rtx temp2, poly_int64 delta,
5276 aarch64_isa_mode force_isa_mode,
5277 bool frame_related_p, bool emit_move_imm = true)
5278 {
5279 aarch64_add_offset (Pmode, stack_pointer_rtx, stack_pointer_rtx, -delta,
5280 temp1, temp2, force_isa_mode, frame_related_p,
5281 emit_move_imm);
5282 }
5283
5284 /* A streaming-compatible function needs to switch temporarily to the known
5285 PSTATE.SM mode described by LOCAL_MODE. The low bit of OLD_SVCR contains
5286 the runtime state of PSTATE.SM in the streaming-compatible code, before
5287 the start of the switch to LOCAL_MODE.
5288
5289 Emit instructions to branch around the mode switch if PSTATE.SM already
5290 matches LOCAL_MODE. Return the label that the branch jumps to. */
5291
5292 static rtx_insn *
5293 aarch64_guard_switch_pstate_sm (rtx old_svcr, aarch64_isa_mode local_mode)
5294 {
5295 local_mode &= AARCH64_ISA_MODE_SM_STATE;
5296 gcc_assert (local_mode != 0);
5297 auto already_ok_cond = (local_mode & AARCH64_ISA_MODE_SM_ON ? NE : EQ);
5298 auto *label = gen_label_rtx ();
5299 auto branch = aarch64_gen_test_and_branch (already_ok_cond, old_svcr, 0,
5300 label);
5301 auto *jump = emit_jump_insn (branch);
5302 JUMP_LABEL (jump) = label;
5303 return label;
5304 }
5305
5306 /* Emit code to switch from the PSTATE.SM state in OLD_MODE to the PSTATE.SM
5307 state in NEW_MODE. This is known to involve either an SMSTART SM or
5308 an SMSTOP SM. */
5309
5310 static void
5311 aarch64_switch_pstate_sm (aarch64_isa_mode old_mode, aarch64_isa_mode new_mode)
5312 {
5313 old_mode &= AARCH64_ISA_MODE_SM_STATE;
5314 new_mode &= AARCH64_ISA_MODE_SM_STATE;
5315 gcc_assert (old_mode != new_mode);
5316
5317 if ((new_mode & AARCH64_ISA_MODE_SM_ON)
5318 || (!new_mode && (old_mode & AARCH64_ISA_MODE_SM_OFF)))
5319 emit_insn (gen_aarch64_smstart_sm ());
5320 else
5321 emit_insn (gen_aarch64_smstop_sm ());
5322 }
5323
5324 /* As a side-effect, SMSTART SM and SMSTOP SM clobber the contents of all
5325 FP and predicate registers. This class emits code to preserve any
5326 necessary registers around the mode switch.
5327
5328 The class uses four approaches to saving and restoring contents, enumerated
5329 by group_type:
5330
5331 - GPR: save and restore the contents of FP registers using GPRs.
5332 This is used if the FP register contains no more than 64 significant
5333 bits. The registers used are FIRST_GPR onwards.
5334
5335 - MEM_128: save and restore 128-bit SIMD registers using memory.
5336
5337 - MEM_SVE_PRED: save and restore full SVE predicate registers using memory.
5338
5339 - MEM_SVE_DATA: save and restore full SVE vector registers using memory.
5340
5341 The save slots within each memory group are consecutive, with the
5342 MEM_SVE_PRED slots occupying a region below the MEM_SVE_DATA slots.
5343
5344 There will only be two mode switches for each use of SME, so they should
5345 not be particularly performance-sensitive. It's also rare for SIMD, SVE
5346 or predicate registers to be live across mode switches. We therefore
5347 don't preallocate the save slots but instead allocate them locally on
5348 demand. This makes the code emitted by the class self-contained. */
5349
5350 class aarch64_sme_mode_switch_regs
5351 {
5352 public:
5353 static const unsigned int FIRST_GPR = R10_REGNUM;
5354
5355 void add_reg (machine_mode, unsigned int);
5356 void add_call_args (rtx_call_insn *);
5357 void add_call_result (rtx_call_insn *);
5358 void add_call_preserved_reg (unsigned int);
5359 void add_call_preserved_regs (bitmap);
5360
5361 void emit_prologue ();
5362 void emit_epilogue ();
5363
5364 /* The number of GPRs needed to save FP registers, starting from
5365 FIRST_GPR. */
5366 unsigned int num_gprs () { return m_group_count[GPR]; }
5367
5368 private:
5369 enum sequence { PROLOGUE, EPILOGUE };
5370 enum group_type { GPR, MEM_128, MEM_SVE_PRED, MEM_SVE_DATA, NUM_GROUPS };
5371
5372 /* Information about the save location for one FP, SIMD, SVE data, or
5373 SVE predicate register. */
5374 struct save_location {
5375 /* The register to be saved. */
5376 rtx reg;
5377
5378 /* Which group the save location belongs to. */
5379 group_type group;
5380
5381 /* A zero-based index of the register within the group. */
5382 unsigned int index;
5383 };
5384
5385 unsigned int sve_data_headroom ();
5386 rtx get_slot_mem (machine_mode, poly_int64);
5387 void emit_stack_adjust (sequence, poly_int64);
5388 void emit_mem_move (sequence, const save_location &, poly_int64);
5389
5390 void emit_gpr_moves (sequence);
5391 void emit_mem_128_moves (sequence);
5392 void emit_sve_sp_adjust (sequence);
5393 void emit_sve_pred_moves (sequence);
5394 void emit_sve_data_moves (sequence);
5395
5396 /* All save locations, in no particular order. */
5397 auto_vec<save_location, 12> m_save_locations;
5398
5399 /* The number of registers in each group. */
5400 unsigned int m_group_count[NUM_GROUPS] = {};
5401 };
5402
5403 /* Record that (reg:MODE REGNO) needs to be preserved around the mode
5404 switch. */
5405
5406 void
5407 aarch64_sme_mode_switch_regs::add_reg (machine_mode mode, unsigned int regno)
5408 {
5409 if (!FP_REGNUM_P (regno) && !PR_REGNUM_P (regno))
5410 return;
5411
5412 unsigned int end_regno = end_hard_regno (mode, regno);
5413 unsigned int vec_flags = aarch64_classify_vector_mode (mode);
5414 gcc_assert ((vec_flags & VEC_STRUCT) || end_regno == regno + 1);
5415 for (; regno < end_regno; regno++)
5416 {
5417 /* Force the mode of SVE saves and restores even for single registers.
5418 This is necessary because big-endian targets only allow LDR Z and
5419 STR Z to be used with byte modes. */
5420 machine_mode submode = mode;
5421 if (vec_flags & VEC_SVE_PRED)
5422 submode = VNx16BImode;
5423 else if (vec_flags & VEC_SVE_DATA)
5424 submode = SVE_BYTE_MODE;
5425 else if (vec_flags & VEC_STRUCT)
5426 {
5427 if (vec_flags & VEC_PARTIAL)
5428 submode = V8QImode;
5429 else
5430 submode = V16QImode;
5431 }
5432 save_location loc;
5433 loc.reg = gen_rtx_REG (submode, regno);
5434 if (vec_flags & VEC_SVE_PRED)
5435 {
5436 gcc_assert (PR_REGNUM_P (regno));
5437 loc.group = MEM_SVE_PRED;
5438 }
5439 else
5440 {
5441 gcc_assert (FP_REGNUM_P (regno));
5442 if (known_le (GET_MODE_SIZE (submode), 8))
5443 loc.group = GPR;
5444 else if (known_eq (GET_MODE_SIZE (submode), 16))
5445 loc.group = MEM_128;
5446 else
5447 loc.group = MEM_SVE_DATA;
5448 }
5449 loc.index = m_group_count[loc.group]++;
5450 m_save_locations.quick_push (loc);
5451 }
5452 }
5453
5454 /* Record that the arguments to CALL_INSN need to be preserved around
5455 the mode switch. */
5456
5457 void
5458 aarch64_sme_mode_switch_regs::add_call_args (rtx_call_insn *call_insn)
5459 {
5460 for (rtx node = CALL_INSN_FUNCTION_USAGE (call_insn);
5461 node; node = XEXP (node, 1))
5462 {
5463 rtx item = XEXP (node, 0);
5464 if (GET_CODE (item) != USE)
5465 continue;
5466 item = XEXP (item, 0);
5467 if (!REG_P (item))
5468 continue;
5469 add_reg (GET_MODE (item), REGNO (item));
5470 }
5471 }
5472
5473 /* Record that the return value from CALL_INSN (if any) needs to be
5474 preserved around the mode switch. */
5475
5476 void
5477 aarch64_sme_mode_switch_regs::add_call_result (rtx_call_insn *call_insn)
5478 {
5479 rtx pat = PATTERN (call_insn);
5480 gcc_assert (GET_CODE (pat) == PARALLEL);
5481 pat = XVECEXP (pat, 0, 0);
5482 if (GET_CODE (pat) == CALL)
5483 return;
5484 rtx dest = SET_DEST (pat);
5485 if (GET_CODE (dest) == PARALLEL)
5486 for (int i = 0; i < XVECLEN (dest, 0); ++i)
5487 {
5488 rtx x = XVECEXP (dest, 0, i);
5489 gcc_assert (GET_CODE (x) == EXPR_LIST);
5490 rtx reg = XEXP (x, 0);
5491 add_reg (GET_MODE (reg), REGNO (reg));
5492 }
5493 else
5494 add_reg (GET_MODE (dest), REGNO (dest));
5495 }
5496
5497 /* REGNO is a register that is call-preserved under the current function's ABI.
5498 Record that it must be preserved around the mode switch. */
5499
5500 void
5501 aarch64_sme_mode_switch_regs::add_call_preserved_reg (unsigned int regno)
5502 {
5503 if (FP_REGNUM_P (regno))
5504 switch (crtl->abi->id ())
5505 {
5506 case ARM_PCS_SVE:
5507 add_reg (VNx16QImode, regno);
5508 break;
5509 case ARM_PCS_SIMD:
5510 add_reg (V16QImode, regno);
5511 break;
5512 case ARM_PCS_AAPCS64:
5513 add_reg (DImode, regno);
5514 break;
5515 default:
5516 gcc_unreachable ();
5517 }
5518 else if (PR_REGNUM_P (regno))
5519 add_reg (VNx16BImode, regno);
5520 }
5521
5522 /* The hard registers in REGS are call-preserved under the current function's
5523 ABI. Record that they must be preserved around the mode switch. */
5524
5525 void
5526 aarch64_sme_mode_switch_regs::add_call_preserved_regs (bitmap regs)
5527 {
5528 bitmap_iterator bi;
5529 unsigned int regno;
5530 EXECUTE_IF_SET_IN_BITMAP (regs, 0, regno, bi)
5531 if (HARD_REGISTER_NUM_P (regno))
5532 add_call_preserved_reg (regno);
5533 else
5534 break;
5535 }
5536
5537 /* Emit code to save registers before the mode switch. */
5538
5539 void
5540 aarch64_sme_mode_switch_regs::emit_prologue ()
5541 {
5542 emit_sve_sp_adjust (PROLOGUE);
5543 emit_sve_pred_moves (PROLOGUE);
5544 emit_sve_data_moves (PROLOGUE);
5545 emit_mem_128_moves (PROLOGUE);
5546 emit_gpr_moves (PROLOGUE);
5547 }
5548
5549 /* Emit code to restore registers after the mode switch. */
5550
5551 void
5552 aarch64_sme_mode_switch_regs::emit_epilogue ()
5553 {
5554 emit_gpr_moves (EPILOGUE);
5555 emit_mem_128_moves (EPILOGUE);
5556 emit_sve_pred_moves (EPILOGUE);
5557 emit_sve_data_moves (EPILOGUE);
5558 emit_sve_sp_adjust (EPILOGUE);
5559 }
5560
5561 /* The SVE predicate registers are stored below the SVE data registers,
5562 with the predicate save area being padded to a data-register-sized
5563 boundary. Return the size of this padded area as a whole number
5564 of data register slots. */
5565
5566 unsigned int
5567 aarch64_sme_mode_switch_regs::sve_data_headroom ()
5568 {
5569 return CEIL (m_group_count[MEM_SVE_PRED], 8);
5570 }
5571
5572 /* Return a memory reference of mode MODE to OFFSET bytes from the
5573 stack pointer. */
5574
5575 rtx
5576 aarch64_sme_mode_switch_regs::get_slot_mem (machine_mode mode,
5577 poly_int64 offset)
5578 {
5579 rtx addr = plus_constant (Pmode, stack_pointer_rtx, offset);
5580 return gen_rtx_MEM (mode, addr);
5581 }
5582
5583 /* Allocate or deallocate SIZE bytes of stack space: SEQ decides which. */
5584
5585 void
5586 aarch64_sme_mode_switch_regs::emit_stack_adjust (sequence seq,
5587 poly_int64 size)
5588 {
5589 if (seq == PROLOGUE)
5590 size = -size;
5591 emit_insn (gen_rtx_SET (stack_pointer_rtx,
5592 plus_constant (Pmode, stack_pointer_rtx, size)));
5593 }
5594
5595 /* Save or restore the register in LOC, whose slot is OFFSET bytes from
5596 the stack pointer. SEQ chooses between saving and restoring. */
5597
5598 void
5599 aarch64_sme_mode_switch_regs::emit_mem_move (sequence seq,
5600 const save_location &loc,
5601 poly_int64 offset)
5602 {
5603 rtx mem = get_slot_mem (GET_MODE (loc.reg), offset);
5604 if (seq == PROLOGUE)
5605 emit_move_insn (mem, loc.reg);
5606 else
5607 emit_move_insn (loc.reg, mem);
5608 }
5609
5610 /* Emit instructions to save or restore the GPR group. SEQ chooses between
5611 saving and restoring. */
5612
5613 void
5614 aarch64_sme_mode_switch_regs::emit_gpr_moves (sequence seq)
5615 {
5616 for (auto &loc : m_save_locations)
5617 if (loc.group == GPR)
5618 {
5619 gcc_assert (loc.index < 8);
5620 rtx gpr = gen_rtx_REG (GET_MODE (loc.reg), FIRST_GPR + loc.index);
5621 if (seq == PROLOGUE)
5622 emit_move_insn (gpr, loc.reg);
5623 else
5624 emit_move_insn (loc.reg, gpr);
5625 }
5626 }
5627
5628 /* Emit instructions to save or restore the MEM_128 group. SEQ chooses
5629 between saving and restoring. */
5630
5631 void
5632 aarch64_sme_mode_switch_regs::emit_mem_128_moves (sequence seq)
5633 {
5634 HOST_WIDE_INT count = m_group_count[MEM_128];
5635 if (count == 0)
5636 return;
5637
5638 auto sp = stack_pointer_rtx;
5639 auto sp_adjust = (seq == PROLOGUE ? -count : count) * 16;
5640
5641 /* Pick a common mode that supports LDR & STR with pre/post-modification
5642 and LDP & STP with pre/post-modification. */
5643 auto mode = TFmode;
5644
5645 /* An instruction pattern that should be emitted at the end. */
5646 rtx last_pat = NULL_RTX;
5647
5648 /* A previous MEM_128 location that hasn't been handled yet. */
5649 save_location *prev_loc = nullptr;
5650
5651 /* Look for LDP/STPs and record any leftover LDR/STR in PREV_LOC. */
5652 for (auto &loc : m_save_locations)
5653 if (loc.group == MEM_128)
5654 {
5655 if (!prev_loc)
5656 {
5657 prev_loc = &loc;
5658 continue;
5659 }
5660 gcc_assert (loc.index == prev_loc->index + 1);
5661
5662 /* The offset of the base of the save area from the current
5663 stack pointer. */
5664 HOST_WIDE_INT bias = 0;
5665 if (prev_loc->index == 0 && seq == PROLOGUE)
5666 bias = sp_adjust;
5667
5668 /* Get the two sets in the LDP/STP. */
5669 rtx ops[] = {
5670 gen_rtx_REG (mode, REGNO (prev_loc->reg)),
5671 get_slot_mem (mode, prev_loc->index * 16 + bias),
5672 gen_rtx_REG (mode, REGNO (loc.reg)),
5673 get_slot_mem (mode, loc.index * 16 + bias)
5674 };
5675 unsigned int lhs = (seq == PROLOGUE);
5676 rtx set1 = gen_rtx_SET (ops[lhs], ops[1 - lhs]);
5677 rtx set2 = gen_rtx_SET (ops[lhs + 2], ops[3 - lhs]);
5678
5679 /* Combine the sets with any stack allocation/deallocation. */
5680 rtx pat;
5681 if (prev_loc->index == 0)
5682 {
5683 rtx plus_sp = plus_constant (Pmode, sp, sp_adjust);
5684 rtvec vec = gen_rtvec (3, gen_rtx_SET (sp, plus_sp), set1, set2);
5685 pat = gen_rtx_PARALLEL (VOIDmode, vec);
5686 }
5687 else if (seq == PROLOGUE)
5688 pat = aarch64_gen_store_pair (ops[1], ops[0], ops[2]);
5689 else
5690 pat = aarch64_gen_load_pair (ops[0], ops[2], ops[1]);
5691
5692 /* Queue a deallocation to the end, otherwise emit the
5693 instruction now. */
5694 if (seq == EPILOGUE && prev_loc->index == 0)
5695 last_pat = pat;
5696 else
5697 emit_insn (pat);
5698 prev_loc = nullptr;
5699 }
5700
5701 /* Handle any leftover LDR/STR. */
5702 if (prev_loc)
5703 {
5704 rtx reg = gen_rtx_REG (mode, REGNO (prev_loc->reg));
5705 rtx addr;
5706 if (prev_loc->index != 0)
5707 addr = plus_constant (Pmode, sp, prev_loc->index * 16);
5708 else if (seq == PROLOGUE)
5709 {
5710 rtx allocate = plus_constant (Pmode, sp, -count * 16);
5711 addr = gen_rtx_PRE_MODIFY (Pmode, sp, allocate);
5712 }
5713 else
5714 {
5715 rtx deallocate = plus_constant (Pmode, sp, count * 16);
5716 addr = gen_rtx_POST_MODIFY (Pmode, sp, deallocate);
5717 }
5718 rtx mem = gen_rtx_MEM (mode, addr);
5719 if (seq == PROLOGUE)
5720 emit_move_insn (mem, reg);
5721 else
5722 emit_move_insn (reg, mem);
5723 }
5724
5725 if (last_pat)
5726 emit_insn (last_pat);
5727 }
5728
5729 /* Allocate or deallocate the stack space needed by the SVE groups.
5730 SEQ chooses between allocating and deallocating. */
5731
5732 void
5733 aarch64_sme_mode_switch_regs::emit_sve_sp_adjust (sequence seq)
5734 {
5735 if (unsigned int count = m_group_count[MEM_SVE_DATA] + sve_data_headroom ())
5736 emit_stack_adjust (seq, count * BYTES_PER_SVE_VECTOR);
5737 }
5738
5739 /* Save or restore the MEM_SVE_DATA group. SEQ chooses between saving
5740 and restoring. */
5741
5742 void
5743 aarch64_sme_mode_switch_regs::emit_sve_data_moves (sequence seq)
5744 {
5745 for (auto &loc : m_save_locations)
5746 if (loc.group == MEM_SVE_DATA)
5747 {
5748 auto index = loc.index + sve_data_headroom ();
5749 emit_mem_move (seq, loc, index * BYTES_PER_SVE_VECTOR);
5750 }
5751 }
5752
5753 /* Save or restore the MEM_SVE_PRED group. SEQ chooses between saving
5754 and restoring. */
5755
5756 void
5757 aarch64_sme_mode_switch_regs::emit_sve_pred_moves (sequence seq)
5758 {
5759 for (auto &loc : m_save_locations)
5760 if (loc.group == MEM_SVE_PRED)
5761 emit_mem_move (seq, loc, loc.index * BYTES_PER_SVE_PRED);
5762 }
5763
5764 /* Set DEST to (vec_series BASE STEP). */
5765
5766 static void
5767 aarch64_expand_vec_series (rtx dest, rtx base, rtx step)
5768 {
5769 machine_mode mode = GET_MODE (dest);
5770 scalar_mode inner = GET_MODE_INNER (mode);
5771
5772 /* Each operand can be a register or an immediate in the range [-16, 15]. */
5773 if (!aarch64_sve_index_immediate_p (base))
5774 base = force_reg (inner, base);
5775 if (!aarch64_sve_index_immediate_p (step))
5776 step = force_reg (inner, step);
5777
5778 emit_set_insn (dest, gen_rtx_VEC_SERIES (mode, base, step));
5779 }
5780
5781 /* Duplicate 128-bit Advanced SIMD vector SRC so that it fills an SVE
5782 register of mode MODE. Use TARGET for the result if it's nonnull
5783 and convenient.
5784
5785 The two vector modes must have the same element mode. The behavior
5786 is to duplicate architectural lane N of SRC into architectural lanes
5787 N + I * STEP of the result. On big-endian targets, architectural
5788 lane 0 of an Advanced SIMD vector is the last element of the vector
5789 in memory layout, so for big-endian targets this operation has the
5790 effect of reversing SRC before duplicating it. Callers need to
5791 account for this. */
5792
5793 rtx
5794 aarch64_expand_sve_dupq (rtx target, machine_mode mode, rtx src)
5795 {
5796 machine_mode src_mode = GET_MODE (src);
5797 gcc_assert (GET_MODE_INNER (mode) == GET_MODE_INNER (src_mode));
5798 insn_code icode = (BYTES_BIG_ENDIAN
5799 ? code_for_aarch64_vec_duplicate_vq_be (mode)
5800 : code_for_aarch64_vec_duplicate_vq_le (mode));
5801
5802 unsigned int i = 0;
5803 expand_operand ops[3];
5804 create_output_operand (&ops[i++], target, mode);
5805 create_output_operand (&ops[i++], src, src_mode);
5806 if (BYTES_BIG_ENDIAN)
5807 {
5808 /* Create a PARALLEL describing the reversal of SRC. */
5809 unsigned int nelts_per_vq = 128 / GET_MODE_UNIT_BITSIZE (mode);
5810 rtx sel = aarch64_gen_stepped_int_parallel (nelts_per_vq,
5811 nelts_per_vq - 1, -1);
5812 create_fixed_operand (&ops[i++], sel);
5813 }
5814 expand_insn (icode, i, ops);
5815 return ops[0].value;
5816 }
5817
5818 /* Try to force 128-bit vector value SRC into memory and use LD1RQ to fetch
5819 the memory image into DEST. Return true on success. */
5820
5821 static bool
5822 aarch64_expand_sve_ld1rq (rtx dest, rtx src)
5823 {
5824 src = force_const_mem (GET_MODE (src), src);
5825 if (!src)
5826 return false;
5827
5828 /* Make sure that the address is legitimate. */
5829 if (!aarch64_sve_ld1rq_operand_p (src))
5830 {
5831 rtx addr = force_reg (Pmode, XEXP (src, 0));
5832 src = replace_equiv_address (src, addr);
5833 }
5834
5835 machine_mode mode = GET_MODE (dest);
5836 machine_mode pred_mode = aarch64_sve_pred_mode (mode);
5837 rtx ptrue = aarch64_ptrue_reg (pred_mode);
5838 emit_insn (gen_aarch64_sve_ld1rq (mode, dest, src, ptrue));
5839 return true;
5840 }
5841
5842 /* SRC is an SVE CONST_VECTOR that contains N "foreground" values followed
5843 by N "background" values. Try to move it into TARGET using:
5844
5845 PTRUE PRED.<T>, VL<N>
5846 MOV TRUE.<T>, #<foreground>
5847 MOV FALSE.<T>, #<background>
5848 SEL TARGET.<T>, PRED.<T>, TRUE.<T>, FALSE.<T>
5849
5850 The PTRUE is always a single instruction but the MOVs might need a
5851 longer sequence. If the background value is zero (as it often is),
5852 the sequence can sometimes collapse to a PTRUE followed by a
5853 zero-predicated move.
5854
5855 Return the target on success, otherwise return null. */
5856
5857 static rtx
5858 aarch64_expand_sve_const_vector_sel (rtx target, rtx src)
5859 {
5860 gcc_assert (CONST_VECTOR_NELTS_PER_PATTERN (src) == 2);
5861
5862 /* Make sure that the PTRUE is valid. */
5863 machine_mode mode = GET_MODE (src);
5864 machine_mode pred_mode = aarch64_sve_pred_mode (mode);
5865 unsigned int npatterns = CONST_VECTOR_NPATTERNS (src);
5866 if (aarch64_svpattern_for_vl (pred_mode, npatterns)
5867 == AARCH64_NUM_SVPATTERNS)
5868 return NULL_RTX;
5869
5870 rtx_vector_builder pred_builder (pred_mode, npatterns, 2);
5871 rtx_vector_builder true_builder (mode, npatterns, 1);
5872 rtx_vector_builder false_builder (mode, npatterns, 1);
5873 for (unsigned int i = 0; i < npatterns; ++i)
5874 {
5875 true_builder.quick_push (CONST_VECTOR_ENCODED_ELT (src, i));
5876 pred_builder.quick_push (CONST1_RTX (BImode));
5877 }
5878 for (unsigned int i = 0; i < npatterns; ++i)
5879 {
5880 false_builder.quick_push (CONST_VECTOR_ENCODED_ELT (src, i + npatterns));
5881 pred_builder.quick_push (CONST0_RTX (BImode));
5882 }
5883 expand_operand ops[4];
5884 create_output_operand (&ops[0], target, mode);
5885 create_input_operand (&ops[1], true_builder.build (), mode);
5886 create_input_operand (&ops[2], false_builder.build (), mode);
5887 create_input_operand (&ops[3], pred_builder.build (), pred_mode);
5888 expand_insn (code_for_vcond_mask (mode, mode), 4, ops);
5889 return target;
5890 }
5891
5892 /* Return a register containing CONST_VECTOR SRC, given that SRC has an
5893 SVE data mode and isn't a legitimate constant. Use TARGET for the
5894 result if convenient.
5895
5896 The returned register can have whatever mode seems most natural
5897 given the contents of SRC. */
5898
5899 static rtx
5900 aarch64_expand_sve_const_vector (rtx target, rtx src)
5901 {
5902 machine_mode mode = GET_MODE (src);
5903 unsigned int npatterns = CONST_VECTOR_NPATTERNS (src);
5904 unsigned int nelts_per_pattern = CONST_VECTOR_NELTS_PER_PATTERN (src);
5905 scalar_mode elt_mode = GET_MODE_INNER (mode);
5906 unsigned int elt_bits = GET_MODE_BITSIZE (elt_mode);
5907 unsigned int container_bits = aarch64_sve_container_bits (mode);
5908 unsigned int encoded_bits = npatterns * nelts_per_pattern * container_bits;
5909
5910 if (nelts_per_pattern == 1
5911 && encoded_bits <= 128
5912 && container_bits != elt_bits)
5913 {
5914 /* We have a partial vector mode and a constant whose full-vector
5915 equivalent would occupy a repeating 128-bit sequence. Build that
5916 full-vector equivalent instead, so that we have the option of
5917 using LD1RQ and Advanced SIMD operations. */
5918 unsigned int repeat = container_bits / elt_bits;
5919 machine_mode full_mode = aarch64_full_sve_mode (elt_mode).require ();
5920 rtx_vector_builder builder (full_mode, npatterns * repeat, 1);
5921 for (unsigned int i = 0; i < npatterns; ++i)
5922 for (unsigned int j = 0; j < repeat; ++j)
5923 builder.quick_push (CONST_VECTOR_ENCODED_ELT (src, i));
5924 target = aarch64_target_reg (target, full_mode);
5925 return aarch64_expand_sve_const_vector (target, builder.build ());
5926 }
5927
5928 if (nelts_per_pattern == 1 && encoded_bits == 128)
5929 {
5930 /* The constant is a duplicated quadword but can't be narrowed
5931 beyond a quadword. Get the memory image of the first quadword
5932 as a 128-bit vector and try using LD1RQ to load it from memory.
5933
5934 The effect for both endiannesses is to load memory lane N into
5935 architectural lanes N + I * STEP of the result. On big-endian
5936 targets, the layout of the 128-bit vector in an Advanced SIMD
5937 register would be different from its layout in an SVE register,
5938 but this 128-bit vector is a memory value only. */
5939 machine_mode vq_mode = aarch64_v128_mode (elt_mode).require ();
5940 rtx vq_value = simplify_gen_subreg (vq_mode, src, mode, 0);
5941 if (vq_value && aarch64_expand_sve_ld1rq (target, vq_value))
5942 return target;
5943 }
5944
5945 if (nelts_per_pattern == 1 && encoded_bits < 128)
5946 {
5947 /* The vector is a repeating sequence of 64 bits or fewer.
5948 See if we can load them using an Advanced SIMD move and then
5949 duplicate it to fill a vector. This is better than using a GPR
5950 move because it keeps everything in the same register file. */
5951 machine_mode vq_mode = aarch64_v128_mode (elt_mode).require ();
5952 rtx_vector_builder builder (vq_mode, npatterns, 1);
5953 for (unsigned int i = 0; i < npatterns; ++i)
5954 {
5955 /* We want memory lane N to go into architectural lane N,
5956 so reverse for big-endian targets. The DUP .Q pattern
5957 has a compensating reverse built-in. */
5958 unsigned int srci = BYTES_BIG_ENDIAN ? npatterns - i - 1 : i;
5959 builder.quick_push (CONST_VECTOR_ENCODED_ELT (src, srci));
5960 }
5961 rtx vq_src = builder.build ();
5962 if (aarch64_simd_valid_mov_imm (vq_src))
5963 {
5964 vq_src = force_reg (vq_mode, vq_src);
5965 return aarch64_expand_sve_dupq (target, mode, vq_src);
5966 }
5967
5968 /* Get an integer representation of the repeating part of Advanced
5969 SIMD vector VQ_SRC. This preserves the endianness of VQ_SRC,
5970 which for big-endian targets is lane-swapped wrt a normal
5971 Advanced SIMD vector. This means that for both endiannesses,
5972 memory lane N of SVE vector SRC corresponds to architectural
5973 lane N of a register holding VQ_SRC. This in turn means that
5974 memory lane 0 of SVE vector SRC is in the lsb of VQ_SRC (viewed
5975 as a single 128-bit value) and thus that memory lane 0 of SRC is
5976 in the lsb of the integer. Duplicating the integer therefore
5977 ensures that memory lane N of SRC goes into architectural lane
5978 N + I * INDEX of the SVE register. */
5979 scalar_mode int_mode = int_mode_for_size (encoded_bits, 0).require ();
5980 rtx elt_value = simplify_gen_subreg (int_mode, vq_src, vq_mode, 0);
5981 if (elt_value)
5982 {
5983 /* Pretend that we had a vector of INT_MODE to start with. */
5984 elt_mode = int_mode;
5985 mode = aarch64_full_sve_mode (int_mode).require ();
5986
5987 /* If the integer can be moved into a general register by a
5988 single instruction, do that and duplicate the result. */
5989 if (CONST_INT_P (elt_value)
5990 && aarch64_move_imm (INTVAL (elt_value),
5991 encoded_bits <= 32 ? SImode : DImode))
5992 {
5993 elt_value = force_reg (elt_mode, elt_value);
5994 return expand_vector_broadcast (mode, elt_value);
5995 }
5996 }
5997 else if (npatterns == 1)
5998 /* We're duplicating a single value, but can't do better than
5999 force it to memory and load from there. This handles things
6000 like symbolic constants. */
6001 elt_value = CONST_VECTOR_ENCODED_ELT (src, 0);
6002
6003 if (elt_value)
6004 {
6005 /* Load the element from memory if we can, otherwise move it into
6006 a register and use a DUP. */
6007 rtx op = force_const_mem (elt_mode, elt_value);
6008 if (!op)
6009 op = force_reg (elt_mode, elt_value);
6010 return expand_vector_broadcast (mode, op);
6011 }
6012 }
6013
6014 /* Try using INDEX. */
6015 rtx base, step;
6016 if (const_vec_series_p (src, &base, &step))
6017 {
6018 aarch64_expand_vec_series (target, base, step);
6019 return target;
6020 }
6021
6022 /* From here on, it's better to force the whole constant to memory
6023 if we can. */
6024 if (GET_MODE_NUNITS (mode).is_constant ())
6025 return NULL_RTX;
6026
6027 if (nelts_per_pattern == 2)
6028 if (rtx res = aarch64_expand_sve_const_vector_sel (target, src))
6029 return res;
6030
6031 /* Expand each pattern individually. */
6032 gcc_assert (npatterns > 1);
6033 rtx_vector_builder builder;
6034 auto_vec<rtx, 16> vectors (npatterns);
6035 for (unsigned int i = 0; i < npatterns; ++i)
6036 {
6037 builder.new_vector (mode, 1, nelts_per_pattern);
6038 for (unsigned int j = 0; j < nelts_per_pattern; ++j)
6039 builder.quick_push (CONST_VECTOR_ELT (src, i + j * npatterns));
6040 vectors.quick_push (force_reg (mode, builder.build ()));
6041 }
6042
6043 /* Use permutes to interleave the separate vectors. */
6044 while (npatterns > 1)
6045 {
6046 npatterns /= 2;
6047 for (unsigned int i = 0; i < npatterns; ++i)
6048 {
6049 rtx tmp = (npatterns == 1 ? target : gen_reg_rtx (mode));
6050 rtvec v = gen_rtvec (2, vectors[i], vectors[i + npatterns]);
6051 emit_set_insn (tmp, gen_rtx_UNSPEC (mode, v, UNSPEC_ZIP1));
6052 vectors[i] = tmp;
6053 }
6054 }
6055 gcc_assert (vectors[0] == target);
6056 return target;
6057 }
6058
6059 /* Use WHILE to set a predicate register of mode MODE in which the first
6060 VL bits are set and the rest are clear. Use TARGET for the register
6061 if it's nonnull and convenient. */
6062
6063 static rtx
6064 aarch64_sve_move_pred_via_while (rtx target, machine_mode mode,
6065 unsigned int vl)
6066 {
6067 rtx limit = force_reg (DImode, gen_int_mode (vl, DImode));
6068 target = aarch64_target_reg (target, mode);
6069 emit_insn (gen_while (UNSPEC_WHILELO, DImode, mode,
6070 target, const0_rtx, limit));
6071 return gen_lowpart (VNx16BImode, target);
6072 }
6073
6074 static rtx
6075 aarch64_expand_sve_const_pred_1 (rtx, rtx_vector_builder &, bool);
6076
6077 /* BUILDER is a constant predicate in which the index of every set bit
6078 is a multiple of ELT_SIZE (which is <= 8). Try to load the constant
6079 by inverting every element at a multiple of ELT_SIZE and EORing the
6080 result with an ELT_SIZE PTRUE.
6081
6082 Return a register that contains the constant on success, otherwise
6083 return null. Use TARGET as the register if it is nonnull and
6084 convenient. */
6085
6086 static rtx
6087 aarch64_expand_sve_const_pred_eor (rtx target, rtx_vector_builder &builder,
6088 unsigned int elt_size)
6089 {
6090 /* Invert every element at a multiple of ELT_SIZE, keeping the
6091 other bits zero. */
6092 rtx_vector_builder inv_builder (VNx16BImode, builder.npatterns (),
6093 builder.nelts_per_pattern ());
6094 for (unsigned int i = 0; i < builder.encoded_nelts (); ++i)
6095 if ((i & (elt_size - 1)) == 0 && INTVAL (builder.elt (i)) == 0)
6096 inv_builder.quick_push (const1_rtx);
6097 else
6098 inv_builder.quick_push (const0_rtx);
6099 inv_builder.finalize ();
6100
6101 /* See if we can load the constant cheaply. */
6102 rtx inv = aarch64_expand_sve_const_pred_1 (NULL_RTX, inv_builder, false);
6103 if (!inv)
6104 return NULL_RTX;
6105
6106 /* EOR the result with an ELT_SIZE PTRUE. */
6107 rtx mask = aarch64_ptrue_all (elt_size);
6108 mask = force_reg (VNx16BImode, mask);
6109 inv = gen_lowpart (VNx16BImode, inv);
6110 target = aarch64_target_reg (target, VNx16BImode);
6111 emit_insn (gen_aarch64_pred_z (XOR, VNx16BImode, target, mask, inv, mask));
6112 return target;
6113 }
6114
6115 /* BUILDER is a constant predicate in which the index of every set bit
6116 is a multiple of ELT_SIZE (which is <= 8). Try to load the constant
6117 using a TRN1 of size PERMUTE_SIZE, which is >= ELT_SIZE. Return the
6118 register on success, otherwise return null. Use TARGET as the register
6119 if nonnull and convenient. */
6120
6121 static rtx
6122 aarch64_expand_sve_const_pred_trn (rtx target, rtx_vector_builder &builder,
6123 unsigned int elt_size,
6124 unsigned int permute_size)
6125 {
6126 /* We're going to split the constant into two new constants A and B,
6127 with element I of BUILDER going into A if (I & PERMUTE_SIZE) == 0
6128 and into B otherwise. E.g. for PERMUTE_SIZE == 4 && ELT_SIZE == 1:
6129
6130 A: { 0, 1, 2, 3, _, _, _, _, 8, 9, 10, 11, _, _, _, _ }
6131 B: { 4, 5, 6, 7, _, _, _, _, 12, 13, 14, 15, _, _, _, _ }
6132
6133 where _ indicates elements that will be discarded by the permute.
6134
6135 First calculate the ELT_SIZEs for A and B. */
6136 unsigned int a_elt_size = GET_MODE_SIZE (DImode);
6137 unsigned int b_elt_size = GET_MODE_SIZE (DImode);
6138 for (unsigned int i = 0; i < builder.encoded_nelts (); i += elt_size)
6139 if (INTVAL (builder.elt (i)) != 0)
6140 {
6141 if (i & permute_size)
6142 b_elt_size |= i - permute_size;
6143 else
6144 a_elt_size |= i;
6145 }
6146 a_elt_size &= -a_elt_size;
6147 b_elt_size &= -b_elt_size;
6148
6149 /* Now construct the vectors themselves. */
6150 rtx_vector_builder a_builder (VNx16BImode, builder.npatterns (),
6151 builder.nelts_per_pattern ());
6152 rtx_vector_builder b_builder (VNx16BImode, builder.npatterns (),
6153 builder.nelts_per_pattern ());
6154 unsigned int nelts = builder.encoded_nelts ();
6155 for (unsigned int i = 0; i < nelts; ++i)
6156 if (i & (elt_size - 1))
6157 {
6158 a_builder.quick_push (const0_rtx);
6159 b_builder.quick_push (const0_rtx);
6160 }
6161 else if ((i & permute_size) == 0)
6162 {
6163 /* The A and B elements are significant. */
6164 a_builder.quick_push (builder.elt (i));
6165 b_builder.quick_push (builder.elt (i + permute_size));
6166 }
6167 else
6168 {
6169 /* The A and B elements are going to be discarded, so pick whatever
6170 is likely to give a nice constant. We are targeting element
6171 sizes A_ELT_SIZE and B_ELT_SIZE for A and B respectively,
6172 with the aim of each being a sequence of ones followed by
6173 a sequence of zeros. So:
6174
6175 * if X_ELT_SIZE <= PERMUTE_SIZE, the best approach is to
6176 duplicate the last X_ELT_SIZE element, to extend the
6177 current sequence of ones or zeros.
6178
6179 * if X_ELT_SIZE > PERMUTE_SIZE, the best approach is to add a
6180 zero, so that the constant really does have X_ELT_SIZE and
6181 not a smaller size. */
6182 if (a_elt_size > permute_size)
6183 a_builder.quick_push (const0_rtx);
6184 else
6185 a_builder.quick_push (a_builder.elt (i - a_elt_size));
6186 if (b_elt_size > permute_size)
6187 b_builder.quick_push (const0_rtx);
6188 else
6189 b_builder.quick_push (b_builder.elt (i - b_elt_size));
6190 }
6191 a_builder.finalize ();
6192 b_builder.finalize ();
6193
6194 /* Try loading A into a register. */
6195 rtx_insn *last = get_last_insn ();
6196 rtx a = aarch64_expand_sve_const_pred_1 (NULL_RTX, a_builder, false);
6197 if (!a)
6198 return NULL_RTX;
6199
6200 /* Try loading B into a register. */
6201 rtx b = a;
6202 if (a_builder != b_builder)
6203 {
6204 b = aarch64_expand_sve_const_pred_1 (NULL_RTX, b_builder, false);
6205 if (!b)
6206 {
6207 delete_insns_since (last);
6208 return NULL_RTX;
6209 }
6210 }
6211
6212 /* Emit the TRN1 itself. We emit a TRN that operates on VNx16BI
6213 operands but permutes them as though they had mode MODE. */
6214 machine_mode mode = aarch64_sve_pred_mode (permute_size).require ();
6215 target = aarch64_target_reg (target, GET_MODE (a));
6216 emit_insn (gen_aarch64_sve_acle (UNSPEC_TRN1, mode, target, a, b));
6217 return target;
6218 }
6219
6220 /* Subroutine of aarch64_expand_sve_const_pred. Try to load the VNx16BI
6221 constant in BUILDER into an SVE predicate register. Return the register
6222 on success, otherwise return null. Use TARGET for the register if
6223 nonnull and convenient.
6224
6225 ALLOW_RECURSE_P is true if we can use methods that would call this
6226 function recursively. */
6227
6228 static rtx
6229 aarch64_expand_sve_const_pred_1 (rtx target, rtx_vector_builder &builder,
6230 bool allow_recurse_p)
6231 {
6232 if (builder.encoded_nelts () == 1)
6233 /* A PFALSE or a PTRUE .B ALL. */
6234 return aarch64_emit_set_immediate (target, builder);
6235
6236 unsigned int elt_size = aarch64_widest_sve_pred_elt_size (builder);
6237 if (int vl = aarch64_partial_ptrue_length (builder, elt_size))
6238 {
6239 /* If we can load the constant using PTRUE, use it as-is. */
6240 machine_mode mode = aarch64_sve_pred_mode (elt_size).require ();
6241 if (aarch64_svpattern_for_vl (mode, vl) != AARCH64_NUM_SVPATTERNS)
6242 return aarch64_emit_set_immediate (target, builder);
6243
6244 /* Otherwise use WHILE to set the first VL bits. */
6245 return aarch64_sve_move_pred_via_while (target, mode, vl);
6246 }
6247
6248 if (!allow_recurse_p)
6249 return NULL_RTX;
6250
6251 /* Try inverting the vector in element size ELT_SIZE and then EORing
6252 the result with an ELT_SIZE PTRUE. */
6253 if (INTVAL (builder.elt (0)) == 0)
6254 if (rtx res = aarch64_expand_sve_const_pred_eor (target, builder,
6255 elt_size))
6256 return res;
6257
6258 /* Try using TRN1 to permute two simpler constants. */
6259 for (unsigned int i = elt_size; i <= 8; i *= 2)
6260 if (rtx res = aarch64_expand_sve_const_pred_trn (target, builder,
6261 elt_size, i))
6262 return res;
6263
6264 return NULL_RTX;
6265 }
6266
6267 /* Return an SVE predicate register that contains the VNx16BImode
6268 constant in BUILDER, without going through the move expanders.
6269
6270 The returned register can have whatever mode seems most natural
6271 given the contents of BUILDER. Use TARGET for the result if
6272 convenient. */
6273
6274 static rtx
6275 aarch64_expand_sve_const_pred (rtx target, rtx_vector_builder &builder)
6276 {
6277 /* Try loading the constant using pure predicate operations. */
6278 if (rtx res = aarch64_expand_sve_const_pred_1 (target, builder, true))
6279 return res;
6280
6281 /* Try forcing the constant to memory. */
6282 if (builder.full_nelts ().is_constant ())
6283 if (rtx mem = force_const_mem (VNx16BImode, builder.build ()))
6284 {
6285 target = aarch64_target_reg (target, VNx16BImode);
6286 emit_move_insn (target, mem);
6287 return target;
6288 }
6289
6290 /* The last resort is to load the constant as an integer and then
6291 compare it against zero. Use -1 for set bits in order to increase
6292 the changes of using SVE DUPM or an Advanced SIMD byte mask. */
6293 rtx_vector_builder int_builder (VNx16QImode, builder.npatterns (),
6294 builder.nelts_per_pattern ());
6295 for (unsigned int i = 0; i < builder.encoded_nelts (); ++i)
6296 int_builder.quick_push (INTVAL (builder.elt (i))
6297 ? constm1_rtx : const0_rtx);
6298 return aarch64_convert_sve_data_to_pred (target, VNx16BImode,
6299 int_builder.build ());
6300 }
6301
6302 /* Set DEST to immediate IMM. */
6303
6304 void
6305 aarch64_expand_mov_immediate (rtx dest, rtx imm)
6306 {
6307 machine_mode mode = GET_MODE (dest);
6308
6309 /* Check on what type of symbol it is. */
6310 scalar_int_mode int_mode;
6311 if ((SYMBOL_REF_P (imm)
6312 || LABEL_REF_P (imm)
6313 || GET_CODE (imm) == CONST
6314 || GET_CODE (imm) == CONST_POLY_INT)
6315 && is_a <scalar_int_mode> (mode, &int_mode))
6316 {
6317 rtx mem;
6318 poly_int64 offset;
6319 HOST_WIDE_INT const_offset;
6320 enum aarch64_symbol_type sty;
6321
6322 /* If we have (const (plus symbol offset)), separate out the offset
6323 before we start classifying the symbol. */
6324 rtx base = strip_offset (imm, &offset);
6325
6326 /* We must always add an offset involving VL separately, rather than
6327 folding it into the relocation. */
6328 if (!offset.is_constant (&const_offset))
6329 {
6330 if (!TARGET_SVE)
6331 {
6332 aarch64_report_sve_required ();
6333 return;
6334 }
6335 if (base == const0_rtx
6336 && (aarch64_sve_cnt_immediate_p (offset)
6337 || aarch64_sve_rdvl_immediate_p (offset)))
6338 emit_insn (gen_rtx_SET (dest, imm));
6339 else
6340 {
6341 /* Do arithmetic on 32-bit values if the result is smaller
6342 than that. */
6343 if (partial_subreg_p (int_mode, SImode))
6344 {
6345 /* It is invalid to do symbol calculations in modes
6346 narrower than SImode. */
6347 gcc_assert (base == const0_rtx);
6348 dest = gen_lowpart (SImode, dest);
6349 int_mode = SImode;
6350 }
6351 if (base != const0_rtx)
6352 {
6353 base = aarch64_force_temporary (int_mode, dest, base);
6354 aarch64_add_offset (int_mode, dest, base, offset,
6355 NULL_RTX, NULL_RTX, 0, false);
6356 }
6357 else
6358 aarch64_add_offset (int_mode, dest, base, offset,
6359 dest, NULL_RTX, 0, false);
6360 }
6361 return;
6362 }
6363
6364 if (aarch64_rdsvl_immediate_p (base))
6365 {
6366 /* We could handle non-constant offsets if they are ever
6367 generated. */
6368 gcc_assert (const_offset == 0);
6369 emit_insn (gen_rtx_SET (dest, imm));
6370 return;
6371 }
6372
6373 sty = aarch64_classify_symbol (base, const_offset);
6374 switch (sty)
6375 {
6376 case SYMBOL_FORCE_TO_MEM:
6377 if (int_mode != ptr_mode)
6378 imm = convert_memory_address (ptr_mode, imm);
6379
6380 if (const_offset != 0
6381 && targetm.cannot_force_const_mem (ptr_mode, imm))
6382 {
6383 gcc_assert (can_create_pseudo_p ());
6384 base = aarch64_force_temporary (int_mode, dest, base);
6385 aarch64_add_offset (int_mode, dest, base, const_offset,
6386 NULL_RTX, NULL_RTX, 0, false);
6387 return;
6388 }
6389
6390 mem = force_const_mem (ptr_mode, imm);
6391 gcc_assert (mem);
6392
6393 /* If we aren't generating PC relative literals, then
6394 we need to expand the literal pool access carefully.
6395 This is something that needs to be done in a number
6396 of places, so could well live as a separate function. */
6397 if (!aarch64_pcrelative_literal_loads)
6398 {
6399 gcc_assert (can_create_pseudo_p ());
6400 base = gen_reg_rtx (ptr_mode);
6401 aarch64_expand_mov_immediate (base, XEXP (mem, 0));
6402 if (ptr_mode != Pmode)
6403 base = convert_memory_address (Pmode, base);
6404 mem = gen_rtx_MEM (ptr_mode, base);
6405 }
6406
6407 if (int_mode != ptr_mode)
6408 mem = gen_rtx_ZERO_EXTEND (int_mode, mem);
6409
6410 emit_insn (gen_rtx_SET (dest, mem));
6411
6412 return;
6413
6414 case SYMBOL_SMALL_TLSGD:
6415 case SYMBOL_SMALL_TLSDESC:
6416 case SYMBOL_SMALL_TLSIE:
6417 case SYMBOL_SMALL_GOT_28K:
6418 case SYMBOL_SMALL_GOT_4G:
6419 case SYMBOL_TINY_GOT:
6420 case SYMBOL_TINY_TLSIE:
6421 if (const_offset != 0)
6422 {
6423 gcc_assert(can_create_pseudo_p ());
6424 base = aarch64_force_temporary (int_mode, dest, base);
6425 aarch64_add_offset (int_mode, dest, base, const_offset,
6426 NULL_RTX, NULL_RTX, 0, false);
6427 return;
6428 }
6429 /* FALLTHRU */
6430
6431 case SYMBOL_SMALL_ABSOLUTE:
6432 case SYMBOL_TINY_ABSOLUTE:
6433 case SYMBOL_TLSLE12:
6434 case SYMBOL_TLSLE24:
6435 case SYMBOL_TLSLE32:
6436 case SYMBOL_TLSLE48:
6437 aarch64_load_symref_appropriately (dest, imm, sty);
6438 return;
6439
6440 default:
6441 gcc_unreachable ();
6442 }
6443 }
6444
6445 if (!CONST_INT_P (imm))
6446 {
6447 if (aarch64_sve_pred_mode_p (mode))
6448 {
6449 /* Only the low bit of each .H, .S and .D element is defined,
6450 so we can set the upper bits to whatever we like. If the
6451 predicate is all-true in MODE, prefer to set all the undefined
6452 bits as well, so that we can share a single .B predicate for
6453 all modes. */
6454 if (imm == CONSTM1_RTX (mode))
6455 imm = CONSTM1_RTX (VNx16BImode);
6456
6457 /* All methods for constructing predicate modes wider than VNx16BI
6458 will set the upper bits of each element to zero. Expose this
6459 by moving such constants as a VNx16BI, so that all bits are
6460 significant and so that constants for different modes can be
6461 shared. The wider constant will still be available as a
6462 REG_EQUAL note. */
6463 rtx_vector_builder builder;
6464 if (aarch64_get_sve_pred_bits (builder, imm))
6465 {
6466 rtx res = aarch64_expand_sve_const_pred (dest, builder);
6467 if (dest != res)
6468 emit_move_insn (dest, gen_lowpart (mode, res));
6469 return;
6470 }
6471 }
6472
6473 if (GET_CODE (imm) == HIGH || aarch64_simd_valid_mov_imm (imm))
6474 {
6475 emit_insn (gen_rtx_SET (dest, imm));
6476 return;
6477 }
6478
6479 if (CONST_VECTOR_P (imm) && aarch64_sve_data_mode_p (mode))
6480 if (rtx res = aarch64_expand_sve_const_vector (dest, imm))
6481 {
6482 if (dest != res)
6483 emit_insn (gen_aarch64_sve_reinterpret (mode, dest, res));
6484 return;
6485 }
6486
6487 rtx mem = force_const_mem (mode, imm);
6488 gcc_assert (mem);
6489 emit_move_insn (dest, mem);
6490 return;
6491 }
6492
6493 aarch64_internal_mov_immediate (dest, imm, true, mode);
6494 }
6495
6496 /* Return the MEM rtx that provides the canary value that should be used
6497 for stack-smashing protection. MODE is the mode of the memory.
6498 For SSP_GLOBAL, DECL_RTL is the MEM rtx for the canary variable
6499 (__stack_chk_guard), otherwise it has no useful value. SALT_TYPE
6500 indicates whether the caller is performing a SET or a TEST operation. */
6501
6502 rtx
6503 aarch64_stack_protect_canary_mem (machine_mode mode, rtx decl_rtl,
6504 aarch64_salt_type salt_type)
6505 {
6506 rtx addr;
6507 if (aarch64_stack_protector_guard == SSP_GLOBAL)
6508 {
6509 gcc_assert (MEM_P (decl_rtl));
6510 addr = XEXP (decl_rtl, 0);
6511 poly_int64 offset;
6512 rtx base = strip_offset_and_salt (addr, &offset);
6513 if (!SYMBOL_REF_P (base))
6514 return decl_rtl;
6515
6516 rtvec v = gen_rtvec (2, base, GEN_INT (salt_type));
6517 addr = gen_rtx_UNSPEC (Pmode, v, UNSPEC_SALT_ADDR);
6518 addr = gen_rtx_CONST (Pmode, addr);
6519 addr = plus_constant (Pmode, addr, offset);
6520 }
6521 else
6522 {
6523 /* Calculate the address from the system register. */
6524 rtx salt = GEN_INT (salt_type);
6525 addr = gen_reg_rtx (mode);
6526 if (mode == DImode)
6527 emit_insn (gen_reg_stack_protect_address_di (addr, salt));
6528 else
6529 {
6530 emit_insn (gen_reg_stack_protect_address_si (addr, salt));
6531 addr = convert_memory_address (Pmode, addr);
6532 }
6533 addr = plus_constant (Pmode, addr, aarch64_stack_protector_guard_offset);
6534 }
6535 return gen_rtx_MEM (mode, force_reg (Pmode, addr));
6536 }
6537
6538 /* Emit an SVE predicated move from SRC to DEST. PRED is a predicate
6539 that is known to contain PTRUE. */
6540
6541 void
6542 aarch64_emit_sve_pred_move (rtx dest, rtx pred, rtx src)
6543 {
6544 expand_operand ops[3];
6545 machine_mode mode = GET_MODE (dest);
6546 create_output_operand (&ops[0], dest, mode);
6547 create_input_operand (&ops[1], pred, GET_MODE(pred));
6548 create_input_operand (&ops[2], src, mode);
6549 temporary_volatile_ok v (true);
6550 expand_insn (code_for_aarch64_pred_mov (mode), 3, ops);
6551 }
6552
6553 /* Expand a pre-RA SVE data move from SRC to DEST in which at least one
6554 operand is in memory. In this case we need to use the predicated LD1
6555 and ST1 instead of LDR and STR, both for correctness on big-endian
6556 targets and because LD1 and ST1 support a wider range of addressing modes.
6557 PRED_MODE is the mode of the predicate.
6558
6559 See the comment at the head of aarch64-sve.md for details about the
6560 big-endian handling. */
6561
6562 void
6563 aarch64_expand_sve_mem_move (rtx dest, rtx src, machine_mode pred_mode)
6564 {
6565 machine_mode mode = GET_MODE (dest);
6566 rtx ptrue = aarch64_ptrue_reg (pred_mode);
6567 if (!register_operand (src, mode)
6568 && !register_operand (dest, mode))
6569 {
6570 rtx tmp = gen_reg_rtx (mode);
6571 if (MEM_P (src))
6572 aarch64_emit_sve_pred_move (tmp, ptrue, src);
6573 else
6574 emit_move_insn (tmp, src);
6575 src = tmp;
6576 }
6577 aarch64_emit_sve_pred_move (dest, ptrue, src);
6578 }
6579
6580 /* Called only on big-endian targets. See whether an SVE vector move
6581 from SRC to DEST is effectively a REV[BHW] instruction, because at
6582 least one operand is a subreg of an SVE vector that has wider or
6583 narrower elements. Return true and emit the instruction if so.
6584
6585 For example:
6586
6587 (set (reg:VNx8HI R1) (subreg:VNx8HI (reg:VNx16QI R2) 0))
6588
6589 represents a VIEW_CONVERT between the following vectors, viewed
6590 in memory order:
6591
6592 R2: { [0].high, [0].low, [1].high, [1].low, ... }
6593 R1: { [0], [1], [2], [3], ... }
6594
6595 The high part of lane X in R2 should therefore correspond to lane X*2
6596 of R1, but the register representations are:
6597
6598 msb lsb
6599 R2: ...... [1].high [1].low [0].high [0].low
6600 R1: ...... [3] [2] [1] [0]
6601
6602 where the low part of lane X in R2 corresponds to lane X*2 in R1.
6603 We therefore need a reverse operation to swap the high and low values
6604 around.
6605
6606 This is purely an optimization. Without it we would spill the
6607 subreg operand to the stack in one mode and reload it in the
6608 other mode, which has the same effect as the REV. */
6609
6610 bool
6611 aarch64_maybe_expand_sve_subreg_move (rtx dest, rtx src)
6612 {
6613 gcc_assert (BYTES_BIG_ENDIAN);
6614
6615 /* Do not try to optimize subregs that LRA has created for matched
6616 reloads. These subregs only exist as a temporary measure to make
6617 the RTL well-formed, but they are exempt from the usual
6618 TARGET_CAN_CHANGE_MODE_CLASS rules.
6619
6620 For example, if we have:
6621
6622 (set (reg:VNx8HI R1) (foo:VNx8HI (reg:VNx4SI R2)))
6623
6624 and the constraints require R1 and R2 to be in the same register,
6625 LRA may need to create RTL such as:
6626
6627 (set (subreg:VNx4SI (reg:VNx8HI TMP) 0) (reg:VNx4SI R2))
6628 (set (reg:VNx8HI TMP) (foo:VNx8HI (subreg:VNx4SI (reg:VNx8HI TMP) 0)))
6629 (set (reg:VNx8HI R1) (reg:VNx8HI TMP))
6630
6631 which forces both the input and output of the original instruction
6632 to use the same hard register. But for this to work, the normal
6633 rules have to be suppressed on the subreg input, otherwise LRA
6634 would need to reload that input too, meaning that the process
6635 would never terminate. To compensate for this, the normal rules
6636 are also suppressed for the subreg output of the first move.
6637 Ignoring the special case and handling the first move normally
6638 would therefore generate wrong code: we would reverse the elements
6639 for the first subreg but not reverse them back for the second subreg. */
6640 if (SUBREG_P (dest) && !LRA_SUBREG_P (dest))
6641 dest = SUBREG_REG (dest);
6642 if (SUBREG_P (src) && !LRA_SUBREG_P (src))
6643 src = SUBREG_REG (src);
6644
6645 /* The optimization handles two single SVE REGs with different element
6646 sizes. */
6647 if (!REG_P (dest)
6648 || !REG_P (src)
6649 || aarch64_classify_vector_mode (GET_MODE (dest)) != VEC_SVE_DATA
6650 || aarch64_classify_vector_mode (GET_MODE (src)) != VEC_SVE_DATA
6651 || (GET_MODE_UNIT_SIZE (GET_MODE (dest))
6652 == GET_MODE_UNIT_SIZE (GET_MODE (src))))
6653 return false;
6654
6655 /* Generate *aarch64_sve_mov<mode>_subreg_be. */
6656 rtx ptrue = aarch64_ptrue_reg (VNx16BImode);
6657 rtx unspec = gen_rtx_UNSPEC (GET_MODE (dest), gen_rtvec (2, ptrue, src),
6658 UNSPEC_REV_SUBREG);
6659 emit_insn (gen_rtx_SET (dest, unspec));
6660 return true;
6661 }
6662
6663 /* Return a copy of X with mode MODE, without changing its other
6664 attributes. Unlike gen_lowpart, this doesn't care whether the
6665 mode change is valid. */
6666
6667 rtx
6668 aarch64_replace_reg_mode (rtx x, machine_mode mode)
6669 {
6670 if (GET_MODE (x) == mode)
6671 return x;
6672
6673 x = shallow_copy_rtx (x);
6674 set_mode_and_regno (x, mode, REGNO (x));
6675 return x;
6676 }
6677
6678 /* Return the SVE REV[BHW] unspec for reversing quantites of mode MODE
6679 stored in wider integer containers. */
6680
6681 static unsigned int
6682 aarch64_sve_rev_unspec (machine_mode mode)
6683 {
6684 switch (GET_MODE_UNIT_SIZE (mode))
6685 {
6686 case 1: return UNSPEC_REVB;
6687 case 2: return UNSPEC_REVH;
6688 case 4: return UNSPEC_REVW;
6689 }
6690 gcc_unreachable ();
6691 }
6692
6693 /* Split a *aarch64_sve_mov<mode>_subreg_be pattern with the given
6694 operands. */
6695
6696 void
6697 aarch64_split_sve_subreg_move (rtx dest, rtx ptrue, rtx src)
6698 {
6699 /* Decide which REV operation we need. The mode with wider elements
6700 determines the mode of the operands and the mode with the narrower
6701 elements determines the reverse width. */
6702 machine_mode mode_with_wider_elts = aarch64_sve_int_mode (GET_MODE (dest));
6703 machine_mode mode_with_narrower_elts = aarch64_sve_int_mode (GET_MODE (src));
6704 if (GET_MODE_UNIT_SIZE (mode_with_wider_elts)
6705 < GET_MODE_UNIT_SIZE (mode_with_narrower_elts))
6706 std::swap (mode_with_wider_elts, mode_with_narrower_elts);
6707
6708 unsigned int unspec = aarch64_sve_rev_unspec (mode_with_narrower_elts);
6709 machine_mode pred_mode = aarch64_sve_pred_mode (mode_with_wider_elts);
6710
6711 /* Get the operands in the appropriate modes and emit the instruction. */
6712 ptrue = gen_lowpart (pred_mode, ptrue);
6713 dest = aarch64_replace_reg_mode (dest, mode_with_wider_elts);
6714 src = aarch64_replace_reg_mode (src, mode_with_wider_elts);
6715 emit_insn (gen_aarch64_pred (unspec, mode_with_wider_elts,
6716 dest, ptrue, src));
6717 }
6718
6719 static bool
6720 aarch64_function_ok_for_sibcall (tree, tree exp)
6721 {
6722 auto from_abi = crtl->abi->id ();
6723 auto to_abi = expr_callee_abi (exp).id ();
6724
6725 /* ARM_PCS_SVE preserves strictly more than ARM_PCS_SIMD, which in
6726 turn preserves strictly more than the base PCS. The callee must
6727 preserve everything that the caller is required to preserve. */
6728 if (from_abi != to_abi && to_abi == ARM_PCS_SVE)
6729 to_abi = ARM_PCS_SIMD;
6730 if (from_abi != to_abi && to_abi == ARM_PCS_SIMD)
6731 to_abi = ARM_PCS_AAPCS64;
6732 if (from_abi != to_abi)
6733 return false;
6734
6735 tree fntype = TREE_TYPE (TREE_TYPE (CALL_EXPR_FN (exp)));
6736 if (aarch64_fntype_pstate_sm (fntype) & ~aarch64_cfun_incoming_pstate_sm ())
6737 return false;
6738 for (auto state : { "za", "zt0" })
6739 if (bool (aarch64_cfun_shared_flags (state))
6740 != bool (aarch64_fntype_shared_flags (fntype, state)))
6741 return false;
6742
6743 /* BTI J is needed where indirect_return functions may return
6744 if bti is enabled there. */
6745 if (lookup_attribute ("indirect_return", TYPE_ATTRIBUTES (fntype))
6746 && !lookup_attribute ("indirect_return",
6747 TYPE_ATTRIBUTES (TREE_TYPE (cfun->decl))))
6748 return false;
6749
6750 return true;
6751 }
6752
6753 /* Subroutine of aarch64_pass_by_reference for arguments that are not
6754 passed in SVE registers. */
6755
6756 static bool
6757 aarch64_pass_by_reference_1 (CUMULATIVE_ARGS *pcum,
6758 const function_arg_info &arg)
6759 {
6760 HOST_WIDE_INT size;
6761 machine_mode dummymode;
6762 int nregs;
6763
6764 /* GET_MODE_SIZE (BLKmode) is useless since it is 0. */
6765 if (arg.mode == BLKmode && arg.type)
6766 size = int_size_in_bytes (arg.type);
6767 else
6768 /* No frontends can create types with variable-sized modes, so we
6769 shouldn't be asked to pass or return them. */
6770 size = GET_MODE_SIZE (arg.mode).to_constant ();
6771
6772 /* Aggregates are passed by reference based on their size. */
6773 if (arg.aggregate_type_p ())
6774 size = int_size_in_bytes (arg.type);
6775
6776 /* Variable sized arguments are always returned by reference. */
6777 if (size < 0)
6778 return true;
6779
6780 /* Can this be a candidate to be passed in fp/simd register(s)? */
6781 if (aarch64_vfp_is_call_or_return_candidate (arg.mode, arg.type,
6782 &dummymode, &nregs, NULL,
6783 !pcum || pcum->silent_p))
6784 return false;
6785
6786 /* Arguments which are variable sized or larger than 2 registers are
6787 passed by reference unless they are a homogenous floating point
6788 aggregate. */
6789 return size > 2 * UNITS_PER_WORD;
6790 }
6791
6792 /* Implement TARGET_PASS_BY_REFERENCE. */
6793
6794 static bool
6795 aarch64_pass_by_reference (cumulative_args_t pcum_v,
6796 const function_arg_info &arg)
6797 {
6798 CUMULATIVE_ARGS *pcum = get_cumulative_args (pcum_v);
6799
6800 if (!arg.type)
6801 return aarch64_pass_by_reference_1 (pcum, arg);
6802
6803 pure_scalable_type_info pst_info;
6804 switch (pst_info.analyze (arg.type))
6805 {
6806 case pure_scalable_type_info::IS_PST:
6807 if (pcum && !pcum->silent_p && !TARGET_SVE)
6808 /* We can't gracefully recover at this point, so make this a
6809 fatal error. */
6810 fatal_error (input_location, "arguments of type %qT require"
6811 " the SVE ISA extension", arg.type);
6812
6813 /* Variadic SVE types are passed by reference. Normal non-variadic
6814 arguments are too if we've run out of registers. */
6815 return (!arg.named
6816 || pcum->aapcs_nvrn + pst_info.num_zr () > NUM_FP_ARG_REGS
6817 || pcum->aapcs_nprn + pst_info.num_pr () > NUM_PR_ARG_REGS);
6818
6819 case pure_scalable_type_info::DOESNT_MATTER:
6820 gcc_assert (aarch64_pass_by_reference_1 (pcum, arg));
6821 return true;
6822
6823 case pure_scalable_type_info::NO_ABI_IDENTITY:
6824 case pure_scalable_type_info::ISNT_PST:
6825 return aarch64_pass_by_reference_1 (pcum, arg);
6826 }
6827 gcc_unreachable ();
6828 }
6829
6830 /* Return TRUE if VALTYPE is padded to its least significant bits. */
6831 static bool
6832 aarch64_return_in_msb (const_tree valtype)
6833 {
6834 machine_mode dummy_mode;
6835 int dummy_int;
6836
6837 /* Never happens in little-endian mode. */
6838 if (!BYTES_BIG_ENDIAN)
6839 return false;
6840
6841 /* Only composite types smaller than or equal to 16 bytes can
6842 be potentially returned in registers. */
6843 if (!aarch64_composite_type_p (valtype, TYPE_MODE (valtype))
6844 || int_size_in_bytes (valtype) <= 0
6845 || int_size_in_bytes (valtype) > 16)
6846 return false;
6847
6848 /* But not a composite that is an HFA (Homogeneous Floating-point Aggregate)
6849 or an HVA (Homogeneous Short-Vector Aggregate); such a special composite
6850 is always passed/returned in the least significant bits of fp/simd
6851 register(s). */
6852 if (aarch64_vfp_is_call_or_return_candidate (TYPE_MODE (valtype), valtype,
6853 &dummy_mode, &dummy_int, NULL,
6854 false))
6855 return false;
6856
6857 /* Likewise pure scalable types for SVE vector and predicate registers. */
6858 pure_scalable_type_info pst_info;
6859 if (pst_info.analyze_registers (valtype))
6860 return false;
6861
6862 return true;
6863 }
6864
6865 /* Implement TARGET_FUNCTION_VALUE.
6866 Define how to find the value returned by a function. */
6867
6868 static rtx
6869 aarch64_function_value (const_tree type, const_tree func,
6870 bool outgoing ATTRIBUTE_UNUSED)
6871 {
6872 machine_mode mode;
6873 int unsignedp;
6874
6875 mode = TYPE_MODE (type);
6876 if (INTEGRAL_TYPE_P (type))
6877 mode = promote_function_mode (type, mode, &unsignedp, func, 1);
6878
6879 pure_scalable_type_info pst_info;
6880 if (type && pst_info.analyze_registers (type))
6881 return pst_info.get_rtx (mode, V0_REGNUM, P0_REGNUM);
6882
6883 /* Generic vectors that map to full SVE modes with -msve-vector-bits=N
6884 are returned in memory, not by value. */
6885 unsigned int vec_flags = aarch64_classify_vector_mode (mode);
6886 bool sve_p = (vec_flags & VEC_ANY_SVE);
6887
6888 if (aarch64_return_in_msb (type))
6889 {
6890 HOST_WIDE_INT size = int_size_in_bytes (type);
6891
6892 if (size % UNITS_PER_WORD != 0)
6893 {
6894 size += UNITS_PER_WORD - size % UNITS_PER_WORD;
6895 mode = int_mode_for_size (size * BITS_PER_UNIT, 0).require ();
6896 }
6897 }
6898
6899 int count;
6900 machine_mode ag_mode;
6901 if (aarch64_vfp_is_call_or_return_candidate (mode, type, &ag_mode, &count,
6902 NULL, false))
6903 {
6904 gcc_assert (!sve_p);
6905 if (!aarch64_composite_type_p (type, mode))
6906 {
6907 gcc_assert (count == 1 && mode == ag_mode);
6908 return gen_rtx_REG (mode, V0_REGNUM);
6909 }
6910 else if (aarch64_advsimd_full_struct_mode_p (mode)
6911 && known_eq (GET_MODE_SIZE (ag_mode), 16))
6912 return gen_rtx_REG (mode, V0_REGNUM);
6913 else if (aarch64_advsimd_partial_struct_mode_p (mode)
6914 && known_eq (GET_MODE_SIZE (ag_mode), 8))
6915 return gen_rtx_REG (mode, V0_REGNUM);
6916 else
6917 {
6918 int i;
6919 rtx par;
6920
6921 par = gen_rtx_PARALLEL (mode, rtvec_alloc (count));
6922 for (i = 0; i < count; i++)
6923 {
6924 rtx tmp = gen_rtx_REG (ag_mode, V0_REGNUM + i);
6925 rtx offset = gen_int_mode (i * GET_MODE_SIZE (ag_mode), Pmode);
6926 tmp = gen_rtx_EXPR_LIST (VOIDmode, tmp, offset);
6927 XVECEXP (par, 0, i) = tmp;
6928 }
6929 return par;
6930 }
6931 }
6932 else
6933 {
6934 if (sve_p)
6935 {
6936 /* Vector types can acquire a partial SVE mode using things like
6937 __attribute__((vector_size(N))), and this is potentially useful.
6938 However, the choice of mode doesn't affect the type's ABI
6939 identity, so we should treat the types as though they had
6940 the associated integer mode, just like they did before SVE
6941 was introduced.
6942
6943 We know that the vector must be 128 bits or smaller,
6944 otherwise we'd have returned it in memory instead. */
6945 gcc_assert (type
6946 && (aarch64_some_values_include_pst_objects_p (type)
6947 || (vec_flags & VEC_PARTIAL)));
6948
6949 scalar_int_mode int_mode = int_mode_for_mode (mode).require ();
6950 rtx reg = gen_rtx_REG (int_mode, R0_REGNUM);
6951 rtx pair = gen_rtx_EXPR_LIST (VOIDmode, reg, const0_rtx);
6952 return gen_rtx_PARALLEL (mode, gen_rtvec (1, pair));
6953 }
6954 return gen_rtx_REG (mode, R0_REGNUM);
6955 }
6956 }
6957
6958 /* Implements TARGET_FUNCTION_VALUE_REGNO_P.
6959 Return true if REGNO is the number of a hard register in which the values
6960 of called function may come back. */
6961
6962 static bool
6963 aarch64_function_value_regno_p (const unsigned int regno)
6964 {
6965 /* Maximum of 16 bytes can be returned in the general registers. Examples
6966 of 16-byte return values are: 128-bit integers and 16-byte small
6967 structures (excluding homogeneous floating-point aggregates). */
6968 if (regno == R0_REGNUM || regno == R1_REGNUM)
6969 return true;
6970
6971 /* Up to four fp/simd registers can return a function value, e.g. a
6972 homogeneous floating-point aggregate having four members. */
6973 if (regno >= V0_REGNUM && regno < V0_REGNUM + HA_MAX_NUM_FLDS)
6974 return TARGET_FLOAT;
6975
6976 if (regno >= P0_REGNUM && regno < P0_REGNUM + HA_MAX_NUM_FLDS)
6977 return TARGET_SVE;
6978
6979 return false;
6980 }
6981
6982 /* Subroutine for aarch64_return_in_memory for types that are not returned
6983 in SVE registers. */
6984
6985 static bool
6986 aarch64_return_in_memory_1 (const_tree type)
6987 {
6988 HOST_WIDE_INT size;
6989 machine_mode ag_mode;
6990 int count;
6991
6992 if (!AGGREGATE_TYPE_P (type)
6993 && TREE_CODE (type) != BITINT_TYPE
6994 && TREE_CODE (type) != COMPLEX_TYPE
6995 && TREE_CODE (type) != VECTOR_TYPE)
6996 /* Simple scalar types always returned in registers. */
6997 return false;
6998
6999 if (aarch64_vfp_is_call_or_return_candidate (TYPE_MODE (type), type,
7000 &ag_mode, &count, NULL, false))
7001 return false;
7002
7003 /* Types larger than 2 registers returned in memory. */
7004 size = int_size_in_bytes (type);
7005 return (size < 0 || size > 2 * UNITS_PER_WORD);
7006 }
7007
7008 /* Implement TARGET_RETURN_IN_MEMORY.
7009
7010 If the type T of the result of a function is such that
7011 void func (T arg)
7012 would require that arg be passed as a value in a register (or set of
7013 registers) according to the parameter passing rules, then the result
7014 is returned in the same registers as would be used for such an
7015 argument. */
7016
7017 static bool
7018 aarch64_return_in_memory (const_tree type, const_tree fndecl ATTRIBUTE_UNUSED)
7019 {
7020 pure_scalable_type_info pst_info;
7021 switch (pst_info.analyze (type))
7022 {
7023 case pure_scalable_type_info::IS_PST:
7024 return (pst_info.num_zr () > NUM_FP_ARG_REGS
7025 || pst_info.num_pr () > NUM_PR_ARG_REGS);
7026
7027 case pure_scalable_type_info::DOESNT_MATTER:
7028 gcc_assert (aarch64_return_in_memory_1 (type));
7029 return true;
7030
7031 case pure_scalable_type_info::NO_ABI_IDENTITY:
7032 case pure_scalable_type_info::ISNT_PST:
7033 return aarch64_return_in_memory_1 (type);
7034 }
7035 gcc_unreachable ();
7036 }
7037
7038 static bool
7039 aarch64_vfp_is_call_candidate (cumulative_args_t pcum_v, machine_mode mode,
7040 const_tree type, int *nregs)
7041 {
7042 CUMULATIVE_ARGS *pcum = get_cumulative_args (pcum_v);
7043 return aarch64_vfp_is_call_or_return_candidate (mode, type,
7044 &pcum->aapcs_vfp_rmode,
7045 nregs, NULL, pcum->silent_p);
7046 }
7047
7048 /* Given MODE and TYPE of a function argument, return the alignment in
7049 bits. The idea is to suppress any stronger alignment requested by
7050 the user and opt for the natural alignment (specified in AAPCS64 \S
7051 4.1). ABI_BREAK_GCC_9 is set to the old alignment if the alignment
7052 was incorrectly calculated in versions of GCC prior to GCC 9.
7053 ABI_BREAK_GCC_13 is set to the old alignment if it was incorrectly
7054 calculated in versions between GCC 9 and GCC 13. If the alignment
7055 might have changed between GCC 13 and GCC 14, ABI_BREAK_GCC_14
7056 is the old GCC 13 alignment, otherwise it is zero.
7057
7058 This is a helper function for local use only. */
7059
7060 static unsigned int
7061 aarch64_function_arg_alignment (machine_mode mode, const_tree type,
7062 unsigned int *abi_break_gcc_9,
7063 unsigned int *abi_break_gcc_13,
7064 unsigned int *abi_break_gcc_14)
7065 {
7066 *abi_break_gcc_9 = 0;
7067 *abi_break_gcc_13 = 0;
7068 *abi_break_gcc_14 = 0;
7069 if (!type)
7070 return GET_MODE_ALIGNMENT (mode);
7071
7072 if (integer_zerop (TYPE_SIZE (type)))
7073 return 0;
7074
7075 gcc_assert (TYPE_MODE (type) == mode);
7076
7077 if (!AGGREGATE_TYPE_P (type))
7078 {
7079 /* The ABI alignment is the natural alignment of the type, without
7080 any attributes applied. Normally this is the alignment of the
7081 TYPE_MAIN_VARIANT, but not always; see PR108910 for a counterexample.
7082 For now we just handle the known exceptions explicitly. */
7083 type = TYPE_MAIN_VARIANT (type);
7084 if (POINTER_TYPE_P (type))
7085 {
7086 gcc_assert (known_eq (POINTER_SIZE, GET_MODE_BITSIZE (mode)));
7087 return POINTER_SIZE;
7088 }
7089 if (TREE_CODE (type) == ENUMERAL_TYPE && TREE_TYPE (type))
7090 {
7091 *abi_break_gcc_14 = TYPE_ALIGN (type);
7092 type = TYPE_MAIN_VARIANT (TREE_TYPE (type));
7093 }
7094 gcc_assert (!TYPE_USER_ALIGN (type));
7095 return TYPE_ALIGN (type);
7096 }
7097
7098 if (TREE_CODE (type) == ARRAY_TYPE)
7099 return TYPE_ALIGN (TREE_TYPE (type));
7100
7101 unsigned int alignment = 0;
7102 unsigned int bitfield_alignment_with_packed = 0;
7103 unsigned int bitfield_alignment = 0;
7104 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
7105 if (TREE_CODE (field) == FIELD_DECL)
7106 {
7107 /* Note that we explicitly consider zero-sized fields here,
7108 even though they don't map to AAPCS64 machine types.
7109 For example, in:
7110
7111 struct __attribute__((aligned(8))) empty {};
7112
7113 struct s {
7114 [[no_unique_address]] empty e;
7115 int x;
7116 };
7117
7118 "s" contains only one Fundamental Data Type (the int field)
7119 but gains 8-byte alignment and size thanks to "e". */
7120 alignment = std::max (alignment, DECL_ALIGN (field));
7121 if (DECL_BIT_FIELD_TYPE (field))
7122 {
7123 /* Take the bit-field type's alignment into account only
7124 if the user didn't reduce this field's alignment with
7125 the packed attribute. */
7126 if (!DECL_PACKED (field))
7127 bitfield_alignment
7128 = std::max (bitfield_alignment,
7129 TYPE_ALIGN (DECL_BIT_FIELD_TYPE (field)));
7130
7131 /* Compute the alignment even if the bit-field is
7132 packed, so that we can emit a warning in case the
7133 alignment changed between GCC versions. */
7134 bitfield_alignment_with_packed
7135 = std::max (bitfield_alignment_with_packed,
7136 TYPE_ALIGN (DECL_BIT_FIELD_TYPE (field)));
7137 }
7138 }
7139
7140 /* Emit a warning if the alignment is different when taking the
7141 'packed' attribute into account. */
7142 if (bitfield_alignment != bitfield_alignment_with_packed
7143 && bitfield_alignment_with_packed > alignment)
7144 *abi_break_gcc_13 = bitfield_alignment_with_packed;
7145
7146 if (bitfield_alignment > alignment)
7147 {
7148 *abi_break_gcc_9 = alignment;
7149 return bitfield_alignment;
7150 }
7151
7152 return alignment;
7153 }
7154
7155 /* Return true if TYPE describes a _BitInt(N) or an angreggate that uses the
7156 _BitInt(N) type. These include ARRAY_TYPE's with an element that is a
7157 _BitInt(N) or an aggregate that uses it, and a RECORD_TYPE or a UNION_TYPE
7158 with a field member that is a _BitInt(N) or an aggregate that uses it.
7159 Return false otherwise. */
7160
7161 static bool
7162 bitint_or_aggr_of_bitint_p (tree type)
7163 {
7164 if (!type)
7165 return false;
7166
7167 if (TREE_CODE (type) == BITINT_TYPE)
7168 return true;
7169
7170 /* If ARRAY_TYPE, check it's element type. */
7171 if (TREE_CODE (type) == ARRAY_TYPE)
7172 return bitint_or_aggr_of_bitint_p (TREE_TYPE (type));
7173
7174 /* If RECORD_TYPE or UNION_TYPE, check the fields' types. */
7175 if (RECORD_OR_UNION_TYPE_P (type))
7176 for (tree field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
7177 {
7178 if (TREE_CODE (field) != FIELD_DECL)
7179 continue;
7180 if (bitint_or_aggr_of_bitint_p (TREE_TYPE (field)))
7181 return true;
7182 }
7183 return false;
7184 }
7185
7186 /* Layout a function argument according to the AAPCS64 rules. The rule
7187 numbers refer to the rule numbers in the AAPCS64. ORIG_MODE is the
7188 mode that was originally given to us by the target hook, whereas the
7189 mode in ARG might be the result of replacing partial SVE modes with
7190 the equivalent integer mode. */
7191
7192 static void
7193 aarch64_layout_arg (cumulative_args_t pcum_v, const function_arg_info &arg)
7194 {
7195 CUMULATIVE_ARGS *pcum = get_cumulative_args (pcum_v);
7196 tree type = arg.type;
7197 machine_mode mode = arg.mode;
7198 int ncrn, nvrn, nregs;
7199 bool allocate_ncrn, allocate_nvrn;
7200 HOST_WIDE_INT size;
7201 unsigned int abi_break_gcc_9;
7202 unsigned int abi_break_gcc_13;
7203 unsigned int abi_break_gcc_14;
7204
7205 /* We need to do this once per argument. */
7206 if (pcum->aapcs_arg_processed)
7207 return;
7208
7209 bool warn_pcs_change
7210 = (warn_psabi
7211 && !pcum->silent_p
7212 && (currently_expanding_function_start
7213 || currently_expanding_gimple_stmt));
7214
7215 /* HFAs and HVAs can have an alignment greater than 16 bytes. For example:
7216
7217 typedef struct foo {
7218 __Int8x16_t foo[2] __attribute__((aligned(32)));
7219 } foo;
7220
7221 is still a HVA despite its larger-than-normal alignment.
7222 However, such over-aligned HFAs and HVAs are guaranteed to have
7223 no padding.
7224
7225 If we exclude HFAs and HVAs from the discussion below, then there
7226 are several things to note:
7227
7228 - Both the C and AAPCS64 interpretations of a type's alignment should
7229 give a value that is no greater than the type's size.
7230
7231 - Types bigger than 16 bytes are passed indirectly.
7232
7233 - If an argument of type T is passed indirectly, TYPE and MODE describe
7234 a pointer to T rather than T iself.
7235
7236 It follows that the AAPCS64 alignment of TYPE must be no greater
7237 than 16 bytes.
7238
7239 Versions prior to GCC 9.1 ignored a bitfield's underlying type
7240 and so could calculate an alignment that was too small. If this
7241 happened for TYPE then ABI_BREAK_GCC_9 is this older, too-small alignment.
7242
7243 Although GCC 9.1 fixed that bug, it introduced a different one:
7244 it would consider the alignment of a bitfield's underlying type even
7245 if the field was packed (which should have the effect of overriding
7246 the alignment of the underlying type). This was fixed in GCC 13.1.
7247
7248 As a result of this bug, GCC 9 to GCC 12 could calculate an alignment
7249 that was too big. If this happened for TYPE, ABI_BREAK_GCC_13 is
7250 this older, too-big alignment.
7251
7252 Also, the fact that GCC 9 to GCC 12 considered irrelevant
7253 alignments meant they could calculate type alignments that were
7254 bigger than the type's size, contrary to the assumption above.
7255 The handling of register arguments was nevertheless (and justifiably)
7256 written to follow the assumption that the alignment can never be
7257 greater than the size. The same was not true for stack arguments;
7258 their alignment was instead handled by MIN bounds in
7259 aarch64_function_arg_boundary.
7260
7261 The net effect is that, if GCC 9 to GCC 12 incorrectly calculated
7262 an alignment of more than 16 bytes for TYPE then:
7263
7264 - If the argument was passed in registers, these GCC versions
7265 would treat the alignment as though it was *less than* 16 bytes.
7266
7267 - If the argument was passed on the stack, these GCC versions
7268 would treat the alignment as though it was *equal to* 16 bytes.
7269
7270 Both behaviors were wrong, but in different cases. */
7271
7272 pcum->aapcs_arg_processed = true;
7273
7274 pure_scalable_type_info pst_info;
7275 if (type && pst_info.analyze_registers (type))
7276 {
7277 /* aarch64_function_arg_alignment has never had an effect on
7278 this case. */
7279
7280 /* The PCS says that it is invalid to pass an SVE value to an
7281 unprototyped function. There is no ABI-defined location we
7282 can return in this case, so we have no real choice but to raise
7283 an error immediately, even though this is only a query function. */
7284 if (arg.named && pcum->pcs_variant != ARM_PCS_SVE)
7285 {
7286 gcc_assert (!pcum->silent_p);
7287 error ("SVE type %qT cannot be passed to an unprototyped function",
7288 arg.type);
7289 /* Avoid repeating the message, and avoid tripping the assert
7290 below. */
7291 pcum->pcs_variant = ARM_PCS_SVE;
7292 }
7293
7294 /* We would have converted the argument into pass-by-reference
7295 form if it didn't fit in registers. */
7296 pcum->aapcs_nextnvrn = pcum->aapcs_nvrn + pst_info.num_zr ();
7297 pcum->aapcs_nextnprn = pcum->aapcs_nprn + pst_info.num_pr ();
7298 gcc_assert (arg.named
7299 && pcum->pcs_variant == ARM_PCS_SVE
7300 && pcum->aapcs_nextnvrn <= NUM_FP_ARG_REGS
7301 && pcum->aapcs_nextnprn <= NUM_PR_ARG_REGS);
7302 pcum->aapcs_reg = pst_info.get_rtx (mode, V0_REGNUM + pcum->aapcs_nvrn,
7303 P0_REGNUM + pcum->aapcs_nprn);
7304 return;
7305 }
7306
7307 /* Generic vectors that map to full SVE modes with -msve-vector-bits=N
7308 are passed by reference, not by value. */
7309 unsigned int vec_flags = aarch64_classify_vector_mode (mode);
7310 bool sve_p = (vec_flags & VEC_ANY_SVE);
7311 if (sve_p)
7312 /* Vector types can acquire a partial SVE mode using things like
7313 __attribute__((vector_size(N))), and this is potentially useful.
7314 However, the choice of mode doesn't affect the type's ABI
7315 identity, so we should treat the types as though they had
7316 the associated integer mode, just like they did before SVE
7317 was introduced.
7318
7319 We know that the vector must be 128 bits or smaller,
7320 otherwise we'd have passed it in memory instead. */
7321 gcc_assert (type
7322 && (aarch64_some_values_include_pst_objects_p (type)
7323 || (vec_flags & VEC_PARTIAL)));
7324
7325 /* Size in bytes, rounded to the nearest multiple of 8 bytes. */
7326 if (type)
7327 size = int_size_in_bytes (type);
7328 else
7329 /* No frontends can create types with variable-sized modes, so we
7330 shouldn't be asked to pass or return them. */
7331 size = GET_MODE_SIZE (mode).to_constant ();
7332 size = ROUND_UP (size, UNITS_PER_WORD);
7333
7334 allocate_ncrn = (type) ? !(FLOAT_TYPE_P (type)) : !FLOAT_MODE_P (mode);
7335 allocate_nvrn = aarch64_vfp_is_call_candidate (pcum_v,
7336 mode,
7337 type,
7338 &nregs);
7339 gcc_assert (!sve_p || !allocate_nvrn);
7340
7341 unsigned int alignment
7342 = aarch64_function_arg_alignment (mode, type, &abi_break_gcc_9,
7343 &abi_break_gcc_13, &abi_break_gcc_14);
7344
7345 gcc_assert ((allocate_nvrn || alignment <= 16 * BITS_PER_UNIT)
7346 && (!alignment || abi_break_gcc_9 < alignment)
7347 && (!abi_break_gcc_13 || alignment < abi_break_gcc_13));
7348
7349 /* _BitInt(N) was only added in GCC 14. */
7350 bool warn_pcs_change_le_gcc14
7351 = warn_pcs_change && !bitint_or_aggr_of_bitint_p (type);
7352
7353 /* allocate_ncrn may be false-positive, but allocate_nvrn is quite reliable.
7354 The following code thus handles passing by SIMD/FP registers first. */
7355
7356 nvrn = pcum->aapcs_nvrn;
7357
7358 /* C1 - C5 for floating point, homogenous floating point aggregates (HFA)
7359 and homogenous short-vector aggregates (HVA). */
7360 if (allocate_nvrn)
7361 {
7362 /* aarch64_function_arg_alignment has never had an effect on
7363 this case. */
7364 if (!pcum->silent_p && !TARGET_FLOAT)
7365 aarch64_err_no_fpadvsimd (mode);
7366
7367 if (nvrn + nregs <= NUM_FP_ARG_REGS)
7368 {
7369 pcum->aapcs_nextnvrn = nvrn + nregs;
7370 if (!aarch64_composite_type_p (type, mode))
7371 {
7372 gcc_assert (nregs == 1);
7373 pcum->aapcs_reg = gen_rtx_REG (mode, V0_REGNUM + nvrn);
7374 }
7375 else if (aarch64_advsimd_full_struct_mode_p (mode)
7376 && known_eq (GET_MODE_SIZE (pcum->aapcs_vfp_rmode), 16))
7377 pcum->aapcs_reg = gen_rtx_REG (mode, V0_REGNUM + nvrn);
7378 else if (aarch64_advsimd_partial_struct_mode_p (mode)
7379 && known_eq (GET_MODE_SIZE (pcum->aapcs_vfp_rmode), 8))
7380 pcum->aapcs_reg = gen_rtx_REG (mode, V0_REGNUM + nvrn);
7381 else
7382 {
7383 rtx par;
7384 int i;
7385 par = gen_rtx_PARALLEL (mode, rtvec_alloc (nregs));
7386 for (i = 0; i < nregs; i++)
7387 {
7388 rtx tmp = gen_rtx_REG (pcum->aapcs_vfp_rmode,
7389 V0_REGNUM + nvrn + i);
7390 rtx offset = gen_int_mode
7391 (i * GET_MODE_SIZE (pcum->aapcs_vfp_rmode), Pmode);
7392 tmp = gen_rtx_EXPR_LIST (VOIDmode, tmp, offset);
7393 XVECEXP (par, 0, i) = tmp;
7394 }
7395 pcum->aapcs_reg = par;
7396 }
7397 return;
7398 }
7399 else
7400 {
7401 /* C.3 NSRN is set to 8. */
7402 pcum->aapcs_nextnvrn = NUM_FP_ARG_REGS;
7403 goto on_stack;
7404 }
7405 }
7406
7407 ncrn = pcum->aapcs_ncrn;
7408 nregs = size / UNITS_PER_WORD;
7409
7410 /* C6 - C9. though the sign and zero extension semantics are
7411 handled elsewhere. This is the case where the argument fits
7412 entirely general registers. */
7413 if (allocate_ncrn && (ncrn + nregs <= NUM_ARG_REGS))
7414 {
7415 gcc_assert (nregs == 0 || nregs == 1 || nregs == 2);
7416
7417 /* C.8 if the argument has an alignment of 16 then the NGRN is
7418 rounded up to the next even number. */
7419 if (nregs == 2
7420 && ncrn % 2)
7421 {
7422 /* Emit a warning if the alignment changed when taking the
7423 'packed' attribute into account. */
7424 if (warn_pcs_change_le_gcc14
7425 && abi_break_gcc_13
7426 && ((abi_break_gcc_13 == 16 * BITS_PER_UNIT)
7427 != (alignment == 16 * BITS_PER_UNIT)))
7428 inform (input_location, "parameter passing for argument of type "
7429 "%qT changed in GCC 13.1", type);
7430
7431 if (warn_pcs_change_le_gcc14
7432 && abi_break_gcc_14
7433 && ((abi_break_gcc_14 == 16 * BITS_PER_UNIT)
7434 != (alignment == 16 * BITS_PER_UNIT)))
7435 inform (input_location, "parameter passing for argument of type "
7436 "%qT changed in GCC 14.1", type);
7437
7438 /* The == 16 * BITS_PER_UNIT instead of >= 16 * BITS_PER_UNIT
7439 comparison is there because for > 16 * BITS_PER_UNIT
7440 alignment nregs should be > 2 and therefore it should be
7441 passed by reference rather than value. */
7442 if (alignment == 16 * BITS_PER_UNIT)
7443 {
7444 if (warn_pcs_change_le_gcc14
7445 && abi_break_gcc_9)
7446 inform (input_location, "parameter passing for argument of type "
7447 "%qT changed in GCC 9.1", type);
7448 ++ncrn;
7449 gcc_assert (ncrn + nregs <= NUM_ARG_REGS);
7450 }
7451 }
7452
7453 /* If an argument with an SVE mode needs to be shifted up to the
7454 high part of the register, treat it as though it had an integer mode.
7455 Using the normal (parallel [...]) would suppress the shifting. */
7456 if (sve_p
7457 && BYTES_BIG_ENDIAN
7458 && maybe_ne (GET_MODE_SIZE (mode), nregs * UNITS_PER_WORD)
7459 && aarch64_pad_reg_upward (mode, type, false))
7460 {
7461 mode = int_mode_for_mode (mode).require ();
7462 sve_p = false;
7463 }
7464
7465 /* NREGS can be 0 when e.g. an empty structure is to be passed.
7466 A reg is still generated for it, but the caller should be smart
7467 enough not to use it. */
7468 if (nregs == 0
7469 || (nregs == 1 && !sve_p)
7470 || GET_MODE_CLASS (mode) == MODE_INT)
7471 pcum->aapcs_reg = gen_rtx_REG (mode, R0_REGNUM + ncrn);
7472 else
7473 {
7474 rtx par;
7475 int i;
7476
7477 par = gen_rtx_PARALLEL (mode, rtvec_alloc (nregs));
7478 for (i = 0; i < nregs; i++)
7479 {
7480 scalar_int_mode reg_mode = word_mode;
7481 if (nregs == 1)
7482 reg_mode = int_mode_for_mode (mode).require ();
7483 rtx tmp = gen_rtx_REG (reg_mode, R0_REGNUM + ncrn + i);
7484 tmp = gen_rtx_EXPR_LIST (VOIDmode, tmp,
7485 GEN_INT (i * UNITS_PER_WORD));
7486 XVECEXP (par, 0, i) = tmp;
7487 }
7488 pcum->aapcs_reg = par;
7489 }
7490
7491 pcum->aapcs_nextncrn = ncrn + nregs;
7492 return;
7493 }
7494
7495 /* C.11 */
7496 pcum->aapcs_nextncrn = NUM_ARG_REGS;
7497
7498 /* The argument is passed on stack; record the needed number of words for
7499 this argument and align the total size if necessary. */
7500 on_stack:
7501 pcum->aapcs_stack_words = size / UNITS_PER_WORD;
7502
7503 if (warn_pcs_change_le_gcc14
7504 && abi_break_gcc_13
7505 && ((abi_break_gcc_13 >= 16 * BITS_PER_UNIT)
7506 != (alignment >= 16 * BITS_PER_UNIT)))
7507 inform (input_location, "parameter passing for argument of type "
7508 "%qT changed in GCC 13.1", type);
7509
7510 if (warn_pcs_change_le_gcc14
7511 && abi_break_gcc_14
7512 && ((abi_break_gcc_14 >= 16 * BITS_PER_UNIT)
7513 != (alignment >= 16 * BITS_PER_UNIT)))
7514 inform (input_location, "parameter passing for argument of type "
7515 "%qT changed in GCC 14.1", type);
7516
7517 if (alignment == 16 * BITS_PER_UNIT)
7518 {
7519 int new_size = ROUND_UP (pcum->aapcs_stack_size, 16 / UNITS_PER_WORD);
7520 if (pcum->aapcs_stack_size != new_size)
7521 {
7522 if (warn_pcs_change_le_gcc14
7523 && abi_break_gcc_9)
7524 inform (input_location, "parameter passing for argument of type "
7525 "%qT changed in GCC 9.1", type);
7526 pcum->aapcs_stack_size = new_size;
7527 }
7528 }
7529 return;
7530 }
7531
7532 /* Add the current argument register to the set of those that need
7533 to be saved and restored around a change to PSTATE.SM. */
7534
7535 static void
7536 aarch64_record_sme_mode_switch_args (CUMULATIVE_ARGS *pcum)
7537 {
7538 subrtx_var_iterator::array_type array;
7539 FOR_EACH_SUBRTX_VAR (iter, array, pcum->aapcs_reg, NONCONST)
7540 {
7541 rtx x = *iter;
7542 if (REG_P (x) && (FP_REGNUM_P (REGNO (x)) || PR_REGNUM_P (REGNO (x))))
7543 {
7544 unsigned int i = pcum->num_sme_mode_switch_args++;
7545 gcc_assert (i < ARRAY_SIZE (pcum->sme_mode_switch_args));
7546 pcum->sme_mode_switch_args[i] = x;
7547 }
7548 }
7549 }
7550
7551 /* Return a parallel that contains all the registers that need to be
7552 saved around a change to PSTATE.SM. Return const0_rtx if there is
7553 no such mode switch, or if no registers need to be saved. */
7554
7555 static rtx
7556 aarch64_finish_sme_mode_switch_args (CUMULATIVE_ARGS *pcum)
7557 {
7558 if (!pcum->num_sme_mode_switch_args)
7559 return const0_rtx;
7560
7561 auto argvec = gen_rtvec_v (pcum->num_sme_mode_switch_args,
7562 pcum->sme_mode_switch_args);
7563 return gen_rtx_PARALLEL (VOIDmode, argvec);
7564 }
7565
7566 /* Implement TARGET_FUNCTION_ARG. */
7567
7568 static rtx
7569 aarch64_function_arg (cumulative_args_t pcum_v, const function_arg_info &arg)
7570 {
7571 CUMULATIVE_ARGS *pcum = get_cumulative_args (pcum_v);
7572 gcc_assert (pcum->pcs_variant == ARM_PCS_AAPCS64
7573 || pcum->pcs_variant == ARM_PCS_SIMD
7574 || pcum->pcs_variant == ARM_PCS_SVE);
7575
7576 if (arg.end_marker_p ())
7577 {
7578 rtx abi_cookie = aarch64_gen_callee_cookie (pcum->isa_mode,
7579 pcum->pcs_variant,
7580 pcum->indirect_return);
7581 rtx sme_mode_switch_args = aarch64_finish_sme_mode_switch_args (pcum);
7582 rtx shared_za_flags = gen_int_mode (pcum->shared_za_flags, SImode);
7583 rtx shared_zt0_flags = gen_int_mode (pcum->shared_zt0_flags, SImode);
7584 return gen_rtx_PARALLEL (VOIDmode, gen_rtvec (4, abi_cookie,
7585 sme_mode_switch_args,
7586 shared_za_flags,
7587 shared_zt0_flags));
7588 }
7589
7590 aarch64_layout_arg (pcum_v, arg);
7591 return pcum->aapcs_reg;
7592 }
7593
7594 void
7595 aarch64_init_cumulative_args (CUMULATIVE_ARGS *pcum,
7596 const_tree fntype,
7597 rtx libname ATTRIBUTE_UNUSED,
7598 const_tree fndecl,
7599 unsigned n_named ATTRIBUTE_UNUSED,
7600 bool silent_p)
7601 {
7602 pcum->aapcs_ncrn = 0;
7603 pcum->aapcs_nvrn = 0;
7604 pcum->aapcs_nprn = 0;
7605 pcum->aapcs_nextncrn = 0;
7606 pcum->aapcs_nextnvrn = 0;
7607 pcum->aapcs_nextnprn = 0;
7608 if (fntype)
7609 {
7610 pcum->pcs_variant = (arm_pcs) fntype_abi (fntype).id ();
7611 pcum->isa_mode = aarch64_fntype_isa_mode (fntype);
7612 pcum->indirect_return = lookup_attribute ("indirect_return",
7613 TYPE_ATTRIBUTES (fntype));
7614 }
7615 else
7616 {
7617 pcum->pcs_variant = ARM_PCS_AAPCS64;
7618 pcum->isa_mode = AARCH64_DEFAULT_ISA_MODE;
7619 pcum->indirect_return = false;
7620 }
7621 pcum->aapcs_reg = NULL_RTX;
7622 pcum->aapcs_arg_processed = false;
7623 pcum->aapcs_stack_words = 0;
7624 pcum->aapcs_stack_size = 0;
7625 pcum->silent_p = silent_p;
7626 pcum->shared_za_flags
7627 = (fntype ? aarch64_fntype_shared_flags (fntype, "za") : 0U);
7628 pcum->shared_zt0_flags
7629 = (fntype ? aarch64_fntype_shared_flags (fntype, "zt0") : 0U);
7630 pcum->num_sme_mode_switch_args = 0;
7631
7632 if (!silent_p
7633 && !TARGET_FLOAT
7634 && fntype && fntype != error_mark_node)
7635 {
7636 const_tree type = TREE_TYPE (fntype);
7637 machine_mode mode ATTRIBUTE_UNUSED; /* To pass pointer as argument. */
7638 int nregs ATTRIBUTE_UNUSED; /* Likewise. */
7639 if (aarch64_vfp_is_call_or_return_candidate (TYPE_MODE (type), type,
7640 &mode, &nregs, NULL, false))
7641 aarch64_err_no_fpadvsimd (TYPE_MODE (type));
7642 }
7643
7644 if (!silent_p
7645 && !TARGET_SVE
7646 && pcum->pcs_variant == ARM_PCS_SVE)
7647 {
7648 /* We can't gracefully recover at this point, so make this a
7649 fatal error. */
7650 if (fndecl)
7651 fatal_error (input_location, "%qE requires the SVE ISA extension",
7652 fndecl);
7653 else
7654 fatal_error (input_location, "calls to functions of type %qT require"
7655 " the SVE ISA extension", fntype);
7656 }
7657 }
7658
7659 static void
7660 aarch64_function_arg_advance (cumulative_args_t pcum_v,
7661 const function_arg_info &arg)
7662 {
7663 CUMULATIVE_ARGS *pcum = get_cumulative_args (pcum_v);
7664 if (pcum->pcs_variant == ARM_PCS_AAPCS64
7665 || pcum->pcs_variant == ARM_PCS_SIMD
7666 || pcum->pcs_variant == ARM_PCS_SVE)
7667 {
7668 aarch64_layout_arg (pcum_v, arg);
7669 gcc_assert ((pcum->aapcs_reg != NULL_RTX)
7670 != (pcum->aapcs_stack_words != 0));
7671 if (pcum->aapcs_reg
7672 && aarch64_call_switches_pstate_sm (pcum->isa_mode))
7673 aarch64_record_sme_mode_switch_args (pcum);
7674
7675 pcum->aapcs_arg_processed = false;
7676 pcum->aapcs_ncrn = pcum->aapcs_nextncrn;
7677 pcum->aapcs_nvrn = pcum->aapcs_nextnvrn;
7678 pcum->aapcs_nprn = pcum->aapcs_nextnprn;
7679 pcum->aapcs_stack_size += pcum->aapcs_stack_words;
7680 pcum->aapcs_stack_words = 0;
7681 pcum->aapcs_reg = NULL_RTX;
7682 }
7683 }
7684
7685 bool
7686 aarch64_function_arg_regno_p (unsigned regno)
7687 {
7688 return ((GP_REGNUM_P (regno) && regno < R0_REGNUM + NUM_ARG_REGS)
7689 || (FP_REGNUM_P (regno) && regno < V0_REGNUM + NUM_FP_ARG_REGS)
7690 || (PR_REGNUM_P (regno) && regno < P0_REGNUM + NUM_PR_ARG_REGS));
7691 }
7692
7693 /* Implement FUNCTION_ARG_BOUNDARY. Every parameter gets at least
7694 PARM_BOUNDARY bits of alignment, but will be given anything up
7695 to STACK_BOUNDARY bits if the type requires it. This makes sure
7696 that both before and after the layout of each argument, the Next
7697 Stacked Argument Address (NSAA) will have a minimum alignment of
7698 8 bytes. */
7699
7700 static unsigned int
7701 aarch64_function_arg_boundary (machine_mode mode, const_tree type)
7702 {
7703 unsigned int abi_break_gcc_9;
7704 unsigned int abi_break_gcc_13;
7705 unsigned int abi_break_gcc_14;
7706 unsigned int alignment = aarch64_function_arg_alignment (mode, type,
7707 &abi_break_gcc_9,
7708 &abi_break_gcc_13,
7709 &abi_break_gcc_14);
7710 /* We rely on aarch64_layout_arg and aarch64_gimplify_va_arg_expr
7711 to emit warnings about ABI incompatibility. */
7712 alignment = MIN (MAX (alignment, PARM_BOUNDARY), STACK_BOUNDARY);
7713 return alignment;
7714 }
7715
7716 /* Implement TARGET_GET_RAW_RESULT_MODE and TARGET_GET_RAW_ARG_MODE. */
7717
7718 static fixed_size_mode
7719 aarch64_get_reg_raw_mode (int regno)
7720 {
7721 /* Don't use any non GP registers for __builtin_apply and
7722 __builtin_return if general registers only mode is requested. */
7723 if (TARGET_GENERAL_REGS_ONLY && !GP_REGNUM_P (regno))
7724 return as_a <fixed_size_mode> (VOIDmode);
7725 if (TARGET_SVE && FP_REGNUM_P (regno))
7726 /* Don't use the SVE part of the register for __builtin_apply and
7727 __builtin_return. The SVE registers aren't used by the normal PCS,
7728 so using them there would be a waste of time. The PCS extensions
7729 for SVE types are fundamentally incompatible with the
7730 __builtin_return/__builtin_apply interface. */
7731 return as_a <fixed_size_mode> (V16QImode);
7732 if (PR_REGNUM_P (regno))
7733 /* For SVE PR regs, indicate that they should be ignored for
7734 __builtin_apply/__builtin_return. */
7735 return as_a <fixed_size_mode> (VOIDmode);
7736 return default_get_reg_raw_mode (regno);
7737 }
7738
7739 /* Implement TARGET_FUNCTION_ARG_PADDING.
7740
7741 Small aggregate types are placed in the lowest memory address.
7742
7743 The related parameter passing rules are B.4, C.3, C.5 and C.14. */
7744
7745 static pad_direction
7746 aarch64_function_arg_padding (machine_mode mode, const_tree type)
7747 {
7748 /* On little-endian targets, the least significant byte of every stack
7749 argument is passed at the lowest byte address of the stack slot. */
7750 if (!BYTES_BIG_ENDIAN)
7751 return PAD_UPWARD;
7752
7753 /* Otherwise, integral, floating-point and pointer types are padded downward:
7754 the least significant byte of a stack argument is passed at the highest
7755 byte address of the stack slot. */
7756 if (type
7757 ? (INTEGRAL_TYPE_P (type) || SCALAR_FLOAT_TYPE_P (type)
7758 || POINTER_TYPE_P (type))
7759 : (SCALAR_INT_MODE_P (mode) || SCALAR_FLOAT_MODE_P (mode)))
7760 return PAD_DOWNWARD;
7761
7762 /* Everything else padded upward, i.e. data in first byte of stack slot. */
7763 return PAD_UPWARD;
7764 }
7765
7766 /* Similarly, for use by BLOCK_REG_PADDING (MODE, TYPE, FIRST).
7767
7768 It specifies padding for the last (may also be the only)
7769 element of a block move between registers and memory. If
7770 assuming the block is in the memory, padding upward means that
7771 the last element is padded after its highest significant byte,
7772 while in downward padding, the last element is padded at the
7773 its least significant byte side.
7774
7775 Small aggregates and small complex types are always padded
7776 upwards.
7777
7778 We don't need to worry about homogeneous floating-point or
7779 short-vector aggregates; their move is not affected by the
7780 padding direction determined here. Regardless of endianness,
7781 each element of such an aggregate is put in the least
7782 significant bits of a fp/simd register.
7783
7784 Return !BYTES_BIG_ENDIAN if the least significant byte of the
7785 register has useful data, and return the opposite if the most
7786 significant byte does. */
7787
7788 bool
7789 aarch64_pad_reg_upward (machine_mode mode, const_tree type,
7790 bool first ATTRIBUTE_UNUSED)
7791 {
7792
7793 /* Aside from pure scalable types, small composite types are always
7794 padded upward. */
7795 if (BYTES_BIG_ENDIAN && aarch64_composite_type_p (type, mode))
7796 {
7797 HOST_WIDE_INT size;
7798 if (type)
7799 size = int_size_in_bytes (type);
7800 else
7801 /* No frontends can create types with variable-sized modes, so we
7802 shouldn't be asked to pass or return them. */
7803 size = GET_MODE_SIZE (mode).to_constant ();
7804 if (size < 2 * UNITS_PER_WORD)
7805 {
7806 pure_scalable_type_info pst_info;
7807 if (pst_info.analyze_registers (type))
7808 return false;
7809 return true;
7810 }
7811 }
7812
7813 /* Otherwise, use the default padding. */
7814 return !BYTES_BIG_ENDIAN;
7815 }
7816
7817 static scalar_int_mode
7818 aarch64_libgcc_cmp_return_mode (void)
7819 {
7820 return SImode;
7821 }
7822
7823 #define PROBE_INTERVAL (1 << STACK_CHECK_PROBE_INTERVAL_EXP)
7824
7825 /* We use the 12-bit shifted immediate arithmetic instructions so values
7826 must be multiple of (1 << 12), i.e. 4096. */
7827 #define ARITH_FACTOR 4096
7828
7829 #if (PROBE_INTERVAL % ARITH_FACTOR) != 0
7830 #error Cannot use simple address calculation for stack probing
7831 #endif
7832
7833 /* Emit code to probe a range of stack addresses from FIRST to FIRST+POLY_SIZE,
7834 inclusive. These are offsets from the current stack pointer. */
7835
7836 static void
7837 aarch64_emit_probe_stack_range (HOST_WIDE_INT first, poly_int64 poly_size)
7838 {
7839 HOST_WIDE_INT size;
7840 if (!poly_size.is_constant (&size))
7841 {
7842 sorry ("stack probes for SVE frames");
7843 return;
7844 }
7845
7846 rtx reg1 = gen_rtx_REG (Pmode, PROBE_STACK_FIRST_REGNUM);
7847
7848 /* See the same assertion on PROBE_INTERVAL above. */
7849 gcc_assert ((first % ARITH_FACTOR) == 0);
7850
7851 /* See if we have a constant small number of probes to generate. If so,
7852 that's the easy case. */
7853 if (size <= PROBE_INTERVAL)
7854 {
7855 const HOST_WIDE_INT base = ROUND_UP (size, ARITH_FACTOR);
7856
7857 emit_set_insn (reg1,
7858 plus_constant (Pmode,
7859 stack_pointer_rtx, -(first + base)));
7860 emit_stack_probe (plus_constant (Pmode, reg1, base - size));
7861 }
7862
7863 /* The run-time loop is made up of 8 insns in the generic case while the
7864 compile-time loop is made up of 4+2*(n-2) insns for n # of intervals. */
7865 else if (size <= 4 * PROBE_INTERVAL)
7866 {
7867 HOST_WIDE_INT i, rem;
7868
7869 emit_set_insn (reg1,
7870 plus_constant (Pmode,
7871 stack_pointer_rtx,
7872 -(first + PROBE_INTERVAL)));
7873 emit_stack_probe (reg1);
7874
7875 /* Probe at FIRST + N * PROBE_INTERVAL for values of N from 2 until
7876 it exceeds SIZE. If only two probes are needed, this will not
7877 generate any code. Then probe at FIRST + SIZE. */
7878 for (i = 2 * PROBE_INTERVAL; i < size; i += PROBE_INTERVAL)
7879 {
7880 emit_set_insn (reg1,
7881 plus_constant (Pmode, reg1, -PROBE_INTERVAL));
7882 emit_stack_probe (reg1);
7883 }
7884
7885 rem = size - (i - PROBE_INTERVAL);
7886 if (rem > 256)
7887 {
7888 const HOST_WIDE_INT base = ROUND_UP (rem, ARITH_FACTOR);
7889
7890 emit_set_insn (reg1, plus_constant (Pmode, reg1, -base));
7891 emit_stack_probe (plus_constant (Pmode, reg1, base - rem));
7892 }
7893 else
7894 emit_stack_probe (plus_constant (Pmode, reg1, -rem));
7895 }
7896
7897 /* Otherwise, do the same as above, but in a loop. Note that we must be
7898 extra careful with variables wrapping around because we might be at
7899 the very top (or the very bottom) of the address space and we have
7900 to be able to handle this case properly; in particular, we use an
7901 equality test for the loop condition. */
7902 else
7903 {
7904 rtx reg2 = gen_rtx_REG (Pmode, PROBE_STACK_SECOND_REGNUM);
7905
7906 /* Step 1: round SIZE to the previous multiple of the interval. */
7907
7908 HOST_WIDE_INT rounded_size = size & -PROBE_INTERVAL;
7909
7910
7911 /* Step 2: compute initial and final value of the loop counter. */
7912
7913 /* TEST_ADDR = SP + FIRST. */
7914 emit_set_insn (reg1,
7915 plus_constant (Pmode, stack_pointer_rtx, -first));
7916
7917 /* LAST_ADDR = SP + FIRST + ROUNDED_SIZE. */
7918 HOST_WIDE_INT adjustment = - (first + rounded_size);
7919 if (! aarch64_uimm12_shift (adjustment))
7920 {
7921 aarch64_internal_mov_immediate (reg2, GEN_INT (adjustment),
7922 true, Pmode);
7923 emit_set_insn (reg2, gen_rtx_PLUS (Pmode, stack_pointer_rtx, reg2));
7924 }
7925 else
7926 emit_set_insn (reg2,
7927 plus_constant (Pmode, stack_pointer_rtx, adjustment));
7928
7929 /* Step 3: the loop
7930
7931 do
7932 {
7933 TEST_ADDR = TEST_ADDR + PROBE_INTERVAL
7934 probe at TEST_ADDR
7935 }
7936 while (TEST_ADDR != LAST_ADDR)
7937
7938 probes at FIRST + N * PROBE_INTERVAL for values of N from 1
7939 until it is equal to ROUNDED_SIZE. */
7940
7941 emit_insn (gen_probe_stack_range (reg1, reg1, reg2));
7942
7943
7944 /* Step 4: probe at FIRST + SIZE if we cannot assert at compile-time
7945 that SIZE is equal to ROUNDED_SIZE. */
7946
7947 if (size != rounded_size)
7948 {
7949 HOST_WIDE_INT rem = size - rounded_size;
7950
7951 if (rem > 256)
7952 {
7953 const HOST_WIDE_INT base = ROUND_UP (rem, ARITH_FACTOR);
7954
7955 emit_set_insn (reg2, plus_constant (Pmode, reg2, -base));
7956 emit_stack_probe (plus_constant (Pmode, reg2, base - rem));
7957 }
7958 else
7959 emit_stack_probe (plus_constant (Pmode, reg2, -rem));
7960 }
7961 }
7962
7963 /* Make sure nothing is scheduled before we are done. */
7964 emit_insn (gen_blockage ());
7965 }
7966
7967 /* Probe a range of stack addresses from REG1 to REG2 inclusive. These are
7968 absolute addresses. */
7969
7970 const char *
7971 aarch64_output_probe_stack_range (rtx reg1, rtx reg2)
7972 {
7973 static int labelno = 0;
7974 char loop_lab[32];
7975 rtx xops[2];
7976
7977 ASM_GENERATE_INTERNAL_LABEL (loop_lab, "LPSRL", labelno++);
7978
7979 /* Loop. */
7980 ASM_OUTPUT_INTERNAL_LABEL (asm_out_file, loop_lab);
7981
7982 HOST_WIDE_INT stack_clash_probe_interval
7983 = 1 << param_stack_clash_protection_guard_size;
7984
7985 /* TEST_ADDR = TEST_ADDR + PROBE_INTERVAL. */
7986 xops[0] = reg1;
7987 HOST_WIDE_INT interval;
7988 if (flag_stack_clash_protection)
7989 interval = stack_clash_probe_interval;
7990 else
7991 interval = PROBE_INTERVAL;
7992
7993 gcc_assert (aarch64_uimm12_shift (interval));
7994 xops[1] = GEN_INT (interval);
7995
7996 output_asm_insn ("sub\t%0, %0, %1", xops);
7997
7998 /* If doing stack clash protection then we probe up by the ABI specified
7999 amount. We do this because we're dropping full pages at a time in the
8000 loop. But if we're doing non-stack clash probing, probe at SP 0. */
8001 if (flag_stack_clash_protection)
8002 xops[1] = GEN_INT (STACK_CLASH_CALLER_GUARD);
8003 else
8004 xops[1] = CONST0_RTX (GET_MODE (xops[1]));
8005
8006 /* Probe at TEST_ADDR. If we're inside the loop it is always safe to probe
8007 by this amount for each iteration. */
8008 output_asm_insn ("str\txzr, [%0, %1]", xops);
8009
8010 /* Test if TEST_ADDR == LAST_ADDR. */
8011 xops[1] = reg2;
8012 output_asm_insn ("cmp\t%0, %1", xops);
8013
8014 /* Branch. */
8015 fputs ("\tb.ne\t", asm_out_file);
8016 assemble_name_raw (asm_out_file, loop_lab);
8017 fputc ('\n', asm_out_file);
8018
8019 return "";
8020 }
8021
8022 /* Emit the probe loop for doing stack clash probes and stack adjustments for
8023 SVE. This emits probes from BASE to BASE - ADJUSTMENT based on a guard size
8024 of GUARD_SIZE. When a probe is emitted it is done at most
8025 MIN_PROBE_THRESHOLD bytes from the current BASE at an interval of
8026 at most MIN_PROBE_THRESHOLD. By the end of this function
8027 BASE = BASE - ADJUSTMENT. */
8028
8029 const char *
8030 aarch64_output_probe_sve_stack_clash (rtx base, rtx adjustment,
8031 rtx min_probe_threshold, rtx guard_size)
8032 {
8033 /* This function is not allowed to use any instruction generation function
8034 like gen_ and friends. If you do you'll likely ICE during CFG validation,
8035 so instead emit the code you want using output_asm_insn. */
8036 gcc_assert (flag_stack_clash_protection);
8037 gcc_assert (CONST_INT_P (min_probe_threshold) && CONST_INT_P (guard_size));
8038 gcc_assert (INTVAL (guard_size) > INTVAL (min_probe_threshold));
8039
8040 /* The minimum required allocation before the residual requires probing. */
8041 HOST_WIDE_INT residual_probe_guard = INTVAL (min_probe_threshold);
8042
8043 /* Clamp the value down to the nearest value that can be used with a cmp. */
8044 residual_probe_guard = aarch64_clamp_to_uimm12_shift (residual_probe_guard);
8045 rtx probe_offset_value_rtx = gen_int_mode (residual_probe_guard, Pmode);
8046
8047 gcc_assert (INTVAL (min_probe_threshold) >= residual_probe_guard);
8048 gcc_assert (aarch64_uimm12_shift (residual_probe_guard));
8049
8050 static int labelno = 0;
8051 char loop_start_lab[32];
8052 char loop_end_lab[32];
8053 rtx xops[2];
8054
8055 ASM_GENERATE_INTERNAL_LABEL (loop_start_lab, "SVLPSPL", labelno);
8056 ASM_GENERATE_INTERNAL_LABEL (loop_end_lab, "SVLPEND", labelno++);
8057
8058 /* Emit loop start label. */
8059 ASM_OUTPUT_INTERNAL_LABEL (asm_out_file, loop_start_lab);
8060
8061 /* ADJUSTMENT < RESIDUAL_PROBE_GUARD. */
8062 xops[0] = adjustment;
8063 xops[1] = probe_offset_value_rtx;
8064 output_asm_insn ("cmp\t%0, %1", xops);
8065
8066 /* Branch to end if not enough adjustment to probe. */
8067 fputs ("\tb.lt\t", asm_out_file);
8068 assemble_name_raw (asm_out_file, loop_end_lab);
8069 fputc ('\n', asm_out_file);
8070
8071 /* BASE = BASE - RESIDUAL_PROBE_GUARD. */
8072 xops[0] = base;
8073 xops[1] = probe_offset_value_rtx;
8074 output_asm_insn ("sub\t%0, %0, %1", xops);
8075
8076 /* Probe at BASE. */
8077 xops[1] = const0_rtx;
8078 output_asm_insn ("str\txzr, [%0, %1]", xops);
8079
8080 /* ADJUSTMENT = ADJUSTMENT - RESIDUAL_PROBE_GUARD. */
8081 xops[0] = adjustment;
8082 xops[1] = probe_offset_value_rtx;
8083 output_asm_insn ("sub\t%0, %0, %1", xops);
8084
8085 /* Branch to start if still more bytes to allocate. */
8086 fputs ("\tb\t", asm_out_file);
8087 assemble_name_raw (asm_out_file, loop_start_lab);
8088 fputc ('\n', asm_out_file);
8089
8090 /* No probe leave. */
8091 ASM_OUTPUT_INTERNAL_LABEL (asm_out_file, loop_end_lab);
8092
8093 /* BASE = BASE - ADJUSTMENT. */
8094 xops[0] = base;
8095 xops[1] = adjustment;
8096 output_asm_insn ("sub\t%0, %0, %1", xops);
8097 return "";
8098 }
8099
8100 /* Determine whether a frame chain needs to be generated. */
8101 static bool
8102 aarch64_needs_frame_chain (void)
8103 {
8104 if (frame_pointer_needed)
8105 return true;
8106
8107 /* A leaf function cannot have calls or write LR. */
8108 bool is_leaf = crtl->is_leaf && !df_regs_ever_live_p (LR_REGNUM);
8109
8110 /* Don't use a frame chain in leaf functions if leaf frame pointers
8111 are disabled. */
8112 if (flag_omit_leaf_frame_pointer && is_leaf)
8113 return false;
8114
8115 return aarch64_use_frame_pointer;
8116 }
8117
8118 /* Return true if the current function should save registers above
8119 the locals area, rather than below it. */
8120
8121 static bool
8122 aarch64_save_regs_above_locals_p ()
8123 {
8124 /* When using stack smash protection, make sure that the canary slot
8125 comes between the locals and the saved registers. Otherwise,
8126 it would be possible for a carefully sized smash attack to change
8127 the saved registers (particularly LR and FP) without reaching the
8128 canary. */
8129 return crtl->stack_protect_guard;
8130 }
8131
8132 /* Return true if the current function needs to record the incoming
8133 value of PSTATE.SM. */
8134 static bool
8135 aarch64_need_old_pstate_sm ()
8136 {
8137 /* Exit early if the incoming value of PSTATE.SM is known at
8138 compile time. */
8139 if (aarch64_cfun_incoming_pstate_sm () != 0)
8140 return false;
8141
8142 if (aarch64_cfun_enables_pstate_sm ())
8143 return true;
8144
8145 /* Non-local goto receivers are entered with PSTATE.SM equal to 0,
8146 but the function needs to return with PSTATE.SM unchanged. */
8147 if (nonlocal_goto_handler_labels)
8148 return true;
8149
8150 /* Likewise for exception handlers. */
8151 eh_landing_pad lp;
8152 for (unsigned int i = 1; vec_safe_iterate (cfun->eh->lp_array, i, &lp); ++i)
8153 if (lp && lp->post_landing_pad)
8154 return true;
8155
8156 /* Non-local gotos need to set PSTATE.SM to zero. It's possible to call
8157 streaming-compatible functions without SME being available, so PSTATE.SM
8158 should only be changed if it is currently set to one. */
8159 if (crtl->has_nonlocal_goto)
8160 return true;
8161
8162 if (cfun->machine->call_switches_pstate_sm)
8163 for (auto insn = get_insns (); insn; insn = NEXT_INSN (insn))
8164 if (auto *call = dyn_cast<rtx_call_insn *> (insn))
8165 if (!SIBLING_CALL_P (call))
8166 {
8167 /* Return true if there is a call to a non-streaming-compatible
8168 function. */
8169 auto callee_isa_mode = aarch64_insn_callee_isa_mode (call);
8170 if (aarch64_call_switches_pstate_sm (callee_isa_mode))
8171 return true;
8172 }
8173 return false;
8174 }
8175
8176 /* Mark the registers that need to be saved by the callee and calculate
8177 the size of the callee-saved registers area and frame record (both FP
8178 and LR may be omitted). */
8179 static void
8180 aarch64_layout_frame (void)
8181 {
8182 unsigned regno, last_fp_reg = INVALID_REGNUM;
8183 machine_mode vector_save_mode = aarch64_reg_save_mode (V8_REGNUM);
8184 poly_int64 vector_save_size = GET_MODE_SIZE (vector_save_mode);
8185 bool frame_related_fp_reg_p = false;
8186 aarch64_frame &frame = cfun->machine->frame;
8187 poly_int64 top_of_locals = -1;
8188 bool enables_pstate_sm = aarch64_cfun_enables_pstate_sm ();
8189
8190 vec_safe_truncate (frame.saved_gprs, 0);
8191 vec_safe_truncate (frame.saved_fprs, 0);
8192 vec_safe_truncate (frame.saved_prs, 0);
8193
8194 frame.emit_frame_chain = aarch64_needs_frame_chain ();
8195
8196 /* Adjust the outgoing arguments size if required. Keep it in sync with what
8197 the mid-end is doing. */
8198 crtl->outgoing_args_size = STACK_DYNAMIC_OFFSET (cfun);
8199
8200 #define SLOT_NOT_REQUIRED (-2)
8201 #define SLOT_REQUIRED (-1)
8202
8203 frame.wb_push_candidate1 = INVALID_REGNUM;
8204 frame.wb_push_candidate2 = INVALID_REGNUM;
8205 frame.spare_pred_reg = INVALID_REGNUM;
8206
8207 /* First mark all the registers that really need to be saved... */
8208 for (regno = 0; regno <= LAST_SAVED_REGNUM; regno++)
8209 frame.reg_offset[regno] = SLOT_NOT_REQUIRED;
8210 frame.old_svcr_offset = SLOT_NOT_REQUIRED;
8211
8212 /* ... that includes the eh data registers (if needed)... */
8213 if (crtl->calls_eh_return)
8214 for (regno = 0; EH_RETURN_DATA_REGNO (regno) != INVALID_REGNUM; regno++)
8215 frame.reg_offset[EH_RETURN_DATA_REGNO (regno)] = SLOT_REQUIRED;
8216
8217 /* ... and any callee saved register that dataflow says is live. */
8218 for (regno = R0_REGNUM; regno <= R30_REGNUM; regno++)
8219 if (df_regs_ever_live_p (regno)
8220 && !fixed_regs[regno]
8221 && (regno == R30_REGNUM
8222 || !crtl->abi->clobbers_full_reg_p (regno)))
8223 frame.reg_offset[regno] = SLOT_REQUIRED;
8224
8225 for (regno = V0_REGNUM; regno <= V31_REGNUM; regno++)
8226 if ((enables_pstate_sm || df_regs_ever_live_p (regno))
8227 && !fixed_regs[regno]
8228 && !crtl->abi->clobbers_full_reg_p (regno))
8229 {
8230 frame.reg_offset[regno] = SLOT_REQUIRED;
8231 last_fp_reg = regno;
8232 if (aarch64_emit_cfi_for_reg_p (regno))
8233 frame_related_fp_reg_p = true;
8234 }
8235
8236 /* Big-endian SVE frames need a spare predicate register in order
8237 to save Z8-Z15. Decide which register they should use. Prefer
8238 an unused argument register if possible, so that we don't force P4
8239 to be saved unnecessarily. */
8240 if (frame_related_fp_reg_p
8241 && crtl->abi->id () == ARM_PCS_SVE
8242 && BYTES_BIG_ENDIAN)
8243 {
8244 bitmap live1 = df_get_live_out (ENTRY_BLOCK_PTR_FOR_FN (cfun));
8245 bitmap live2 = df_get_live_in (EXIT_BLOCK_PTR_FOR_FN (cfun));
8246 for (regno = P0_REGNUM; regno <= P7_REGNUM; regno++)
8247 if (!bitmap_bit_p (live1, regno) && !bitmap_bit_p (live2, regno))
8248 break;
8249 gcc_assert (regno <= P7_REGNUM);
8250 frame.spare_pred_reg = regno;
8251 df_set_regs_ever_live (regno, true);
8252 }
8253
8254 for (regno = P0_REGNUM; regno <= P15_REGNUM; regno++)
8255 if ((enables_pstate_sm || df_regs_ever_live_p (regno))
8256 && !fixed_regs[regno]
8257 && !crtl->abi->clobbers_full_reg_p (regno))
8258 frame.reg_offset[regno] = SLOT_REQUIRED;
8259
8260 bool regs_at_top_p = aarch64_save_regs_above_locals_p ();
8261
8262 poly_int64 offset = crtl->outgoing_args_size;
8263 gcc_assert (multiple_p (offset, STACK_BOUNDARY / BITS_PER_UNIT));
8264 if (regs_at_top_p)
8265 {
8266 offset += get_frame_size ();
8267 offset = aligned_upper_bound (offset, STACK_BOUNDARY / BITS_PER_UNIT);
8268 top_of_locals = offset;
8269 }
8270 frame.bytes_below_saved_regs = offset;
8271 frame.sve_save_and_probe = INVALID_REGNUM;
8272
8273 /* Now assign stack slots for the registers. Start with the predicate
8274 registers, since predicate LDR and STR have a relatively small
8275 offset range. These saves happen below the hard frame pointer. */
8276 for (regno = P0_REGNUM; regno <= P15_REGNUM; regno++)
8277 if (known_eq (frame.reg_offset[regno], SLOT_REQUIRED))
8278 {
8279 vec_safe_push (frame.saved_prs, regno);
8280 if (frame.sve_save_and_probe == INVALID_REGNUM)
8281 frame.sve_save_and_probe = regno;
8282 frame.reg_offset[regno] = offset;
8283 offset += BYTES_PER_SVE_PRED;
8284 }
8285
8286 poly_int64 saved_prs_size = offset - frame.bytes_below_saved_regs;
8287 if (maybe_ne (saved_prs_size, 0))
8288 {
8289 /* If we have any vector registers to save above the predicate registers,
8290 the offset of the vector register save slots need to be a multiple
8291 of the vector size. This lets us use the immediate forms of LDR/STR
8292 (or LD1/ST1 for big-endian).
8293
8294 A vector register is 8 times the size of a predicate register,
8295 and we need to save a maximum of 12 predicate registers, so the
8296 first vector register will be at either #1, MUL VL or #2, MUL VL.
8297
8298 If we don't have any vector registers to save, and we know how
8299 big the predicate save area is, we can just round it up to the
8300 next 16-byte boundary. */
8301 if (last_fp_reg == INVALID_REGNUM && offset.is_constant ())
8302 offset = aligned_upper_bound (offset, STACK_BOUNDARY / BITS_PER_UNIT);
8303 else
8304 {
8305 if (known_le (saved_prs_size, vector_save_size))
8306 offset = frame.bytes_below_saved_regs + vector_save_size;
8307 else if (known_le (saved_prs_size, vector_save_size * 2))
8308 offset = frame.bytes_below_saved_regs + vector_save_size * 2;
8309 else
8310 gcc_unreachable ();
8311 }
8312 }
8313
8314 /* If we need to save any SVE vector registers, add them next. */
8315 if (last_fp_reg != INVALID_REGNUM && crtl->abi->id () == ARM_PCS_SVE)
8316 for (regno = V0_REGNUM; regno <= V31_REGNUM; regno++)
8317 if (known_eq (frame.reg_offset[regno], SLOT_REQUIRED))
8318 {
8319 vec_safe_push (frame.saved_fprs, regno);
8320 if (frame.sve_save_and_probe == INVALID_REGNUM)
8321 frame.sve_save_and_probe = regno;
8322 frame.reg_offset[regno] = offset;
8323 offset += vector_save_size;
8324 }
8325
8326 /* OFFSET is now the offset of the hard frame pointer from the bottom
8327 of the callee save area. */
8328 auto below_hard_fp_saved_regs_size = offset - frame.bytes_below_saved_regs;
8329 bool saves_below_hard_fp_p = maybe_ne (below_hard_fp_saved_regs_size, 0);
8330 gcc_assert (!saves_below_hard_fp_p
8331 || (frame.sve_save_and_probe != INVALID_REGNUM
8332 && known_eq (frame.reg_offset[frame.sve_save_and_probe],
8333 frame.bytes_below_saved_regs)));
8334
8335 frame.bytes_below_hard_fp = offset;
8336 frame.hard_fp_save_and_probe = INVALID_REGNUM;
8337
8338 auto allocate_gpr_slot = [&](unsigned int regno)
8339 {
8340 vec_safe_push (frame.saved_gprs, regno);
8341 frame.reg_offset[regno] = offset;
8342 offset += UNITS_PER_WORD;
8343 };
8344
8345 if (frame.emit_frame_chain)
8346 {
8347 /* FP and LR are placed in the linkage record. */
8348 allocate_gpr_slot (R29_REGNUM);
8349 allocate_gpr_slot (R30_REGNUM);
8350 }
8351 else if ((flag_stack_clash_protection || !frame.is_scs_enabled)
8352 && known_eq (frame.reg_offset[R30_REGNUM], SLOT_REQUIRED))
8353 /* Put the LR save slot first, since it makes a good choice of probe
8354 for stack clash purposes. The idea is that the link register usually
8355 has to be saved before a call anyway, and so we lose little by
8356 stopping it from being individually shrink-wrapped. */
8357 allocate_gpr_slot (R30_REGNUM);
8358
8359 for (regno = R0_REGNUM; regno <= R30_REGNUM; regno++)
8360 if (known_eq (frame.reg_offset[regno], SLOT_REQUIRED))
8361 allocate_gpr_slot (regno);
8362
8363 if (aarch64_need_old_pstate_sm ())
8364 {
8365 frame.old_svcr_offset = offset;
8366 offset += UNITS_PER_WORD;
8367 }
8368
8369 /* If the current function changes the SVE vector length, ensure that the
8370 old value of the DWARF VG register is saved and available in the CFI,
8371 so that outer frames with VL-sized offsets can be processed correctly. */
8372 if (cfun->machine->call_switches_pstate_sm
8373 || aarch64_cfun_enables_pstate_sm ())
8374 {
8375 frame.reg_offset[VG_REGNUM] = offset;
8376 offset += UNITS_PER_WORD;
8377 }
8378
8379 poly_int64 max_int_offset = offset;
8380 offset = aligned_upper_bound (offset, STACK_BOUNDARY / BITS_PER_UNIT);
8381 bool has_align_gap = maybe_ne (offset, max_int_offset);
8382
8383 for (regno = V0_REGNUM; regno <= V31_REGNUM; regno++)
8384 if (known_eq (frame.reg_offset[regno], SLOT_REQUIRED))
8385 {
8386 vec_safe_push (frame.saved_fprs, regno);
8387 /* If there is an alignment gap between integer and fp callee-saves,
8388 allocate the last fp register to it if possible. */
8389 if (regno == last_fp_reg
8390 && has_align_gap
8391 && known_eq (vector_save_size, 8)
8392 && multiple_p (offset, 16))
8393 {
8394 frame.reg_offset[regno] = max_int_offset;
8395 break;
8396 }
8397
8398 frame.reg_offset[regno] = offset;
8399 offset += vector_save_size;
8400 }
8401
8402 offset = aligned_upper_bound (offset, STACK_BOUNDARY / BITS_PER_UNIT);
8403 auto saved_regs_size = offset - frame.bytes_below_saved_regs;
8404
8405 array_slice<unsigned int> push_regs = (!vec_safe_is_empty (frame.saved_gprs)
8406 ? frame.saved_gprs
8407 : frame.saved_fprs);
8408 if (!push_regs.empty ()
8409 && known_eq (frame.reg_offset[push_regs[0]], frame.bytes_below_hard_fp))
8410 {
8411 frame.hard_fp_save_and_probe = push_regs[0];
8412 frame.wb_push_candidate1 = push_regs[0];
8413 if (push_regs.size () > 1)
8414 frame.wb_push_candidate2 = push_regs[1];
8415 }
8416
8417 /* With stack-clash, a register must be saved in non-leaf functions.
8418 The saving of the bottommost register counts as an implicit probe,
8419 which allows us to maintain the invariant described in the comment
8420 at expand_prologue. */
8421 gcc_assert (crtl->is_leaf || maybe_ne (saved_regs_size, 0));
8422
8423 if (!regs_at_top_p)
8424 {
8425 offset += get_frame_size ();
8426 offset = aligned_upper_bound (offset, STACK_BOUNDARY / BITS_PER_UNIT);
8427 top_of_locals = offset;
8428 }
8429 offset += frame.saved_varargs_size;
8430 gcc_assert (multiple_p (offset, STACK_BOUNDARY / BITS_PER_UNIT));
8431 frame.frame_size = offset;
8432
8433 frame.bytes_above_hard_fp = frame.frame_size - frame.bytes_below_hard_fp;
8434 gcc_assert (known_ge (top_of_locals, 0));
8435 frame.bytes_above_locals = frame.frame_size - top_of_locals;
8436
8437 frame.initial_adjust = 0;
8438 frame.final_adjust = 0;
8439 frame.callee_adjust = 0;
8440 frame.sve_callee_adjust = 0;
8441
8442 frame.wb_pop_candidate1 = frame.wb_push_candidate1;
8443 frame.wb_pop_candidate2 = frame.wb_push_candidate2;
8444
8445 /* Shadow call stack only deals with functions where the LR is pushed
8446 onto the stack and without specifying the "no_sanitize" attribute
8447 with the argument "shadow-call-stack". */
8448 frame.is_scs_enabled
8449 = (!crtl->calls_eh_return
8450 && sanitize_flags_p (SANITIZE_SHADOW_CALL_STACK)
8451 && known_ge (frame.reg_offset[LR_REGNUM], 0));
8452
8453 /* When shadow call stack is enabled, the scs_pop in the epilogue will
8454 restore x30, and we don't need to pop x30 again in the traditional
8455 way. Pop candidates record the registers that need to be popped
8456 eventually. */
8457 if (frame.is_scs_enabled)
8458 {
8459 if (frame.wb_pop_candidate2 == R30_REGNUM)
8460 frame.wb_pop_candidate2 = INVALID_REGNUM;
8461 else if (frame.wb_pop_candidate1 == R30_REGNUM)
8462 frame.wb_pop_candidate1 = INVALID_REGNUM;
8463 }
8464
8465 /* If candidate2 is INVALID_REGNUM, we need to adjust max_push_offset to
8466 256 to ensure that the offset meets the requirements of emit_move_insn.
8467 Similarly, if candidate1 is INVALID_REGNUM, we need to set
8468 max_push_offset to 0, because no registers are popped at this time,
8469 so callee_adjust cannot be adjusted. */
8470 HOST_WIDE_INT max_push_offset = 0;
8471 if (frame.wb_pop_candidate1 != INVALID_REGNUM)
8472 {
8473 if (frame.wb_pop_candidate2 != INVALID_REGNUM)
8474 max_push_offset = 512;
8475 else
8476 max_push_offset = 256;
8477 }
8478
8479 HOST_WIDE_INT const_size, const_below_saved_regs, const_above_fp;
8480 HOST_WIDE_INT const_saved_regs_size;
8481 if (known_eq (saved_regs_size, 0))
8482 frame.initial_adjust = frame.frame_size;
8483 else if (frame.frame_size.is_constant (&const_size)
8484 && const_size < max_push_offset
8485 && known_eq (frame.bytes_above_hard_fp, const_size))
8486 {
8487 /* Simple, small frame with no data below the saved registers.
8488
8489 stp reg1, reg2, [sp, -frame_size]!
8490 stp reg3, reg4, [sp, 16] */
8491 frame.callee_adjust = const_size;
8492 }
8493 else if (frame.bytes_below_saved_regs.is_constant (&const_below_saved_regs)
8494 && saved_regs_size.is_constant (&const_saved_regs_size)
8495 && const_below_saved_regs + const_saved_regs_size < 512
8496 /* We could handle this case even with data below the saved
8497 registers, provided that that data left us with valid offsets
8498 for all predicate and vector save slots. It's such a rare
8499 case that it hardly seems worth the effort though. */
8500 && (!saves_below_hard_fp_p || const_below_saved_regs == 0)
8501 && !(cfun->calls_alloca
8502 && frame.bytes_above_hard_fp.is_constant (&const_above_fp)
8503 && const_above_fp < max_push_offset))
8504 {
8505 /* Frame with small area below the saved registers:
8506
8507 sub sp, sp, frame_size
8508 stp reg1, reg2, [sp, bytes_below_saved_regs]
8509 stp reg3, reg4, [sp, bytes_below_saved_regs + 16] */
8510 frame.initial_adjust = frame.frame_size;
8511 }
8512 else if (saves_below_hard_fp_p
8513 && known_eq (saved_regs_size, below_hard_fp_saved_regs_size))
8514 {
8515 /* Frame in which all saves are SVE saves:
8516
8517 sub sp, sp, frame_size - bytes_below_saved_regs
8518 save SVE registers relative to SP
8519 sub sp, sp, bytes_below_saved_regs */
8520 frame.initial_adjust = frame.frame_size - frame.bytes_below_saved_regs;
8521 frame.final_adjust = frame.bytes_below_saved_regs;
8522 }
8523 else if (frame.wb_push_candidate1 != INVALID_REGNUM
8524 && frame.bytes_above_hard_fp.is_constant (&const_above_fp)
8525 && const_above_fp < max_push_offset)
8526 {
8527 /* Frame with large area below the saved registers, or with SVE saves,
8528 but with a small area above:
8529
8530 stp reg1, reg2, [sp, -hard_fp_offset]!
8531 stp reg3, reg4, [sp, 16]
8532 [sub sp, sp, below_hard_fp_saved_regs_size]
8533 [save SVE registers relative to SP]
8534 sub sp, sp, bytes_below_saved_regs */
8535 frame.callee_adjust = const_above_fp;
8536 frame.sve_callee_adjust = below_hard_fp_saved_regs_size;
8537 frame.final_adjust = frame.bytes_below_saved_regs;
8538 }
8539 else
8540 {
8541 /* General case:
8542
8543 sub sp, sp, hard_fp_offset
8544 stp x29, x30, [sp, 0]
8545 add x29, sp, 0
8546 stp reg3, reg4, [sp, 16]
8547 [sub sp, sp, below_hard_fp_saved_regs_size]
8548 [save SVE registers relative to SP]
8549 sub sp, sp, bytes_below_saved_regs */
8550 frame.initial_adjust = frame.bytes_above_hard_fp;
8551 frame.sve_callee_adjust = below_hard_fp_saved_regs_size;
8552 frame.final_adjust = frame.bytes_below_saved_regs;
8553 }
8554
8555 /* The frame is allocated in pieces, with each non-final piece
8556 including a register save at offset 0 that acts as a probe for
8557 the following piece. In addition, the save of the bottommost register
8558 acts as a probe for callees and allocas. Roll back any probes that
8559 aren't needed.
8560
8561 A probe isn't needed if it is associated with the final allocation
8562 (including callees and allocas) that happens before the epilogue is
8563 executed. */
8564 if (crtl->is_leaf
8565 && !cfun->calls_alloca
8566 && known_eq (frame.final_adjust, 0))
8567 {
8568 if (maybe_ne (frame.sve_callee_adjust, 0))
8569 frame.sve_save_and_probe = INVALID_REGNUM;
8570 else
8571 frame.hard_fp_save_and_probe = INVALID_REGNUM;
8572 }
8573
8574 /* Make sure the individual adjustments add up to the full frame size. */
8575 gcc_assert (known_eq (frame.initial_adjust
8576 + frame.callee_adjust
8577 + frame.sve_callee_adjust
8578 + frame.final_adjust, frame.frame_size));
8579
8580 if (frame.callee_adjust == 0)
8581 {
8582 /* We've decided not to do a "real" push and pop. However,
8583 setting up the frame chain is treated as being essentially
8584 a multi-instruction push. */
8585 frame.wb_pop_candidate1 = frame.wb_pop_candidate2 = INVALID_REGNUM;
8586 if (!frame.emit_frame_chain)
8587 frame.wb_push_candidate1 = frame.wb_push_candidate2 = INVALID_REGNUM;
8588 }
8589
8590 frame.laid_out = true;
8591 }
8592
8593 /* Return true if the register REGNO is saved on entry to
8594 the current function. */
8595
8596 static bool
8597 aarch64_register_saved_on_entry (int regno)
8598 {
8599 return known_ge (cfun->machine->frame.reg_offset[regno], 0);
8600 }
8601
8602 /* Push the register number REGNO of mode MODE to the stack with write-back
8603 adjusting the stack by ADJUSTMENT. */
8604
8605 static void
8606 aarch64_pushwb_single_reg (machine_mode mode, unsigned regno,
8607 HOST_WIDE_INT adjustment)
8608 {
8609 rtx base_rtx = stack_pointer_rtx;
8610 rtx insn, reg, mem;
8611
8612 reg = gen_rtx_REG (mode, regno);
8613 mem = gen_rtx_PRE_MODIFY (Pmode, base_rtx,
8614 plus_constant (Pmode, base_rtx, -adjustment));
8615 mem = gen_frame_mem (mode, mem);
8616
8617 insn = emit_move_insn (mem, reg);
8618 RTX_FRAME_RELATED_P (insn) = 1;
8619 }
8620
8621 /* Generate and return an instruction to store the pair of registers
8622 REG and REG2 of mode MODE to location BASE with write-back adjusting
8623 the stack location BASE by ADJUSTMENT. */
8624
8625 static rtx
8626 aarch64_gen_storewb_pair (machine_mode mode, rtx base, rtx reg, rtx reg2,
8627 HOST_WIDE_INT adjustment)
8628 {
8629 rtx new_base = plus_constant (Pmode, base, -adjustment);
8630 rtx mem = gen_frame_mem (mode, new_base);
8631 rtx mem2 = adjust_address_nv (mem, mode, GET_MODE_SIZE (mode));
8632
8633 return gen_rtx_PARALLEL (VOIDmode,
8634 gen_rtvec (3,
8635 gen_rtx_SET (base, new_base),
8636 gen_rtx_SET (mem, reg),
8637 gen_rtx_SET (mem2, reg2)));
8638 }
8639
8640 /* Push registers numbered REGNO1 and REGNO2 to the stack, adjusting the
8641 stack pointer by ADJUSTMENT. */
8642
8643 static void
8644 aarch64_push_regs (unsigned regno1, unsigned regno2, HOST_WIDE_INT adjustment)
8645 {
8646 rtx_insn *insn;
8647 machine_mode mode = aarch64_reg_save_mode (regno1);
8648
8649 if (regno2 == INVALID_REGNUM)
8650 return aarch64_pushwb_single_reg (mode, regno1, adjustment);
8651
8652 rtx reg1 = gen_rtx_REG (mode, regno1);
8653 rtx reg2 = gen_rtx_REG (mode, regno2);
8654
8655 insn = emit_insn (aarch64_gen_storewb_pair (mode, stack_pointer_rtx, reg1,
8656 reg2, adjustment));
8657 RTX_FRAME_RELATED_P (XVECEXP (PATTERN (insn), 0, 2)) = 1;
8658 RTX_FRAME_RELATED_P (XVECEXP (PATTERN (insn), 0, 1)) = 1;
8659 RTX_FRAME_RELATED_P (insn) = 1;
8660 }
8661
8662 /* Load the pair of register REG, REG2 of mode MODE from stack location BASE,
8663 adjusting it by ADJUSTMENT afterwards. */
8664
8665 static rtx
8666 aarch64_gen_loadwb_pair (machine_mode mode, rtx base, rtx reg, rtx reg2,
8667 HOST_WIDE_INT adjustment)
8668 {
8669 rtx mem = gen_frame_mem (mode, base);
8670 rtx mem2 = adjust_address_nv (mem, mode, GET_MODE_SIZE (mode));
8671 rtx new_base = plus_constant (Pmode, base, adjustment);
8672
8673 return gen_rtx_PARALLEL (VOIDmode,
8674 gen_rtvec (3,
8675 gen_rtx_SET (base, new_base),
8676 gen_rtx_SET (reg, mem),
8677 gen_rtx_SET (reg2, mem2)));
8678 }
8679
8680 /* Pop the two registers numbered REGNO1, REGNO2 from the stack, adjusting it
8681 afterwards by ADJUSTMENT and writing the appropriate REG_CFA_RESTORE notes
8682 into CFI_OPS. */
8683
8684 static void
8685 aarch64_pop_regs (unsigned regno1, unsigned regno2, HOST_WIDE_INT adjustment,
8686 rtx *cfi_ops)
8687 {
8688 machine_mode mode = aarch64_reg_save_mode (regno1);
8689 rtx reg1 = gen_rtx_REG (mode, regno1);
8690
8691 *cfi_ops = alloc_reg_note (REG_CFA_RESTORE, reg1, *cfi_ops);
8692
8693 if (regno2 == INVALID_REGNUM)
8694 {
8695 rtx mem = plus_constant (Pmode, stack_pointer_rtx, adjustment);
8696 mem = gen_rtx_POST_MODIFY (Pmode, stack_pointer_rtx, mem);
8697 emit_move_insn (reg1, gen_frame_mem (mode, mem));
8698 }
8699 else
8700 {
8701 rtx reg2 = gen_rtx_REG (mode, regno2);
8702 *cfi_ops = alloc_reg_note (REG_CFA_RESTORE, reg2, *cfi_ops);
8703 emit_insn (aarch64_gen_loadwb_pair (mode, stack_pointer_rtx, reg1,
8704 reg2, adjustment));
8705 }
8706 }
8707
8708 /* Given an ldp/stp register operand mode MODE, return a suitable mode to use
8709 for a mem rtx representing the entire pair. */
8710
8711 static machine_mode
8712 aarch64_pair_mode_for_mode (machine_mode mode)
8713 {
8714 if (known_eq (GET_MODE_SIZE (mode), 4))
8715 return V2x4QImode;
8716 else if (known_eq (GET_MODE_SIZE (mode), 8))
8717 return V2x8QImode;
8718 else if (known_eq (GET_MODE_SIZE (mode), 16))
8719 return V2x16QImode;
8720 else
8721 gcc_unreachable ();
8722 }
8723
8724 /* Given a base mem MEM with mode and address suitable for a single ldp/stp
8725 operand, return an rtx like MEM which instead represents the entire pair. */
8726
8727 static rtx
8728 aarch64_pair_mem_from_base (rtx mem)
8729 {
8730 auto pair_mode = aarch64_pair_mode_for_mode (GET_MODE (mem));
8731 mem = adjust_bitfield_address_nv (mem, pair_mode, 0);
8732 gcc_assert (aarch64_mem_pair_lanes_operand (mem, pair_mode));
8733 return mem;
8734 }
8735
8736 /* Generate and return a store pair instruction to store REG1 and REG2
8737 into memory starting at BASE_MEM. All three rtxes should have modes of the
8738 same size. */
8739
8740 rtx
8741 aarch64_gen_store_pair (rtx base_mem, rtx reg1, rtx reg2)
8742 {
8743 rtx pair_mem = aarch64_pair_mem_from_base (base_mem);
8744
8745 return gen_rtx_SET (pair_mem,
8746 gen_rtx_UNSPEC (GET_MODE (pair_mem),
8747 gen_rtvec (2, reg1, reg2),
8748 UNSPEC_STP));
8749 }
8750
8751 /* Generate and return a load pair instruction to load a pair of
8752 registers starting at BASE_MEM into REG1 and REG2. If CODE is
8753 UNKNOWN, all three rtxes should have modes of the same size.
8754 Otherwise, CODE is {SIGN,ZERO}_EXTEND, base_mem should be in SImode,
8755 and REG{1,2} should be in DImode. */
8756
8757 rtx
8758 aarch64_gen_load_pair (rtx reg1, rtx reg2, rtx base_mem, enum rtx_code code)
8759 {
8760 rtx pair_mem = aarch64_pair_mem_from_base (base_mem);
8761
8762 const bool any_extend_p = (code == ZERO_EXTEND || code == SIGN_EXTEND);
8763 if (any_extend_p)
8764 gcc_checking_assert (GET_MODE (base_mem) == SImode
8765 && GET_MODE (reg1) == DImode
8766 && GET_MODE (reg2) == DImode);
8767 else
8768 gcc_assert (code == UNKNOWN);
8769
8770 rtx unspecs[2] = {
8771 gen_rtx_UNSPEC (any_extend_p ? SImode : GET_MODE (reg1),
8772 gen_rtvec (1, pair_mem),
8773 UNSPEC_LDP_FST),
8774 gen_rtx_UNSPEC (any_extend_p ? SImode : GET_MODE (reg2),
8775 gen_rtvec (1, copy_rtx (pair_mem)),
8776 UNSPEC_LDP_SND)
8777 };
8778
8779 if (any_extend_p)
8780 for (int i = 0; i < 2; i++)
8781 unspecs[i] = gen_rtx_fmt_e (code, DImode, unspecs[i]);
8782
8783 return gen_rtx_PARALLEL (VOIDmode,
8784 gen_rtvec (2,
8785 gen_rtx_SET (reg1, unspecs[0]),
8786 gen_rtx_SET (reg2, unspecs[1])));
8787 }
8788
8789 /* Return TRUE if return address signing should be enabled for the current
8790 function, otherwise return FALSE. */
8791
8792 bool
8793 aarch64_return_address_signing_enabled (void)
8794 {
8795 /* This function should only be called after frame laid out. */
8796 gcc_assert (cfun->machine->frame.laid_out);
8797
8798 /* If signing scope is AARCH_FUNCTION_NON_LEAF, we only sign a leaf function
8799 if its LR is pushed onto stack. */
8800 return (aarch_ra_sign_scope == AARCH_FUNCTION_ALL
8801 || (aarch_ra_sign_scope == AARCH_FUNCTION_NON_LEAF
8802 && known_ge (cfun->machine->frame.reg_offset[LR_REGNUM], 0)));
8803 }
8804
8805 /* Only used by the arm backend. */
8806 void aarch_bti_arch_check (void)
8807 {}
8808
8809 /* Return TRUE if Branch Target Identification Mechanism is enabled. */
8810 bool
8811 aarch_bti_enabled (void)
8812 {
8813 return (aarch_enable_bti == 1);
8814 }
8815
8816 /* Check if INSN is a BTI J insn. */
8817 bool
8818 aarch_bti_j_insn_p (rtx_insn *insn)
8819 {
8820 if (!insn || !INSN_P (insn))
8821 return false;
8822
8823 rtx pat = PATTERN (insn);
8824 return GET_CODE (pat) == UNSPEC_VOLATILE && XINT (pat, 1) == UNSPECV_BTI_J;
8825 }
8826
8827 /* Return TRUE if Guarded Control Stack is enabled. */
8828 bool
8829 aarch64_gcs_enabled (void)
8830 {
8831 return (aarch64_enable_gcs == 1);
8832 }
8833
8834 /* Check if X (or any sub-rtx of X) is a PACIASP/PACIBSP instruction. */
8835 bool
8836 aarch_pac_insn_p (rtx x)
8837 {
8838 if (!INSN_P (x))
8839 return false;
8840
8841 subrtx_var_iterator::array_type array;
8842 FOR_EACH_SUBRTX_VAR (iter, array, PATTERN (x), ALL)
8843 {
8844 rtx sub = *iter;
8845 if (sub && GET_CODE (sub) == UNSPEC)
8846 {
8847 int unspec_val = XINT (sub, 1);
8848 switch (unspec_val)
8849 {
8850 case UNSPEC_PACIASP:
8851 case UNSPEC_PACIBSP:
8852 return true;
8853
8854 default:
8855 return false;
8856 }
8857 iter.skip_subrtxes ();
8858 }
8859 }
8860 return false;
8861 }
8862
8863 rtx aarch_gen_bti_c (void)
8864 {
8865 return gen_bti_c ();
8866 }
8867
8868 rtx aarch_gen_bti_j (void)
8869 {
8870 return gen_bti_j ();
8871 }
8872
8873 /* The caller is going to use ST1D or LD1D to save or restore an SVE
8874 register in mode MODE at BASE_RTX + OFFSET, where OFFSET is in
8875 the range [1, 16] * GET_MODE_SIZE (MODE). Prepare for this by:
8876
8877 (1) updating BASE_RTX + OFFSET so that it is a legitimate ST1D
8878 or LD1D address
8879
8880 (2) setting PRED to a valid predicate register for the ST1D or LD1D,
8881 if the variable isn't already nonnull
8882
8883 (1) is needed when OFFSET is in the range [8, 16] * GET_MODE_SIZE (MODE).
8884 Handle this case using a temporary base register that is suitable for
8885 all offsets in that range. Use ANCHOR_REG as this base register if it
8886 is nonnull, otherwise create a new register and store it in ANCHOR_REG. */
8887
8888 static inline void
8889 aarch64_adjust_sve_callee_save_base (machine_mode mode, rtx &base_rtx,
8890 rtx &anchor_reg, poly_int64 &offset,
8891 rtx &ptrue)
8892 {
8893 if (maybe_ge (offset, 8 * GET_MODE_SIZE (mode)))
8894 {
8895 /* This is the maximum valid offset of the anchor from the base.
8896 Lower values would be valid too. */
8897 poly_int64 anchor_offset = 16 * GET_MODE_SIZE (mode);
8898 if (!anchor_reg)
8899 {
8900 anchor_reg = gen_rtx_REG (Pmode, STACK_CLASH_SVE_CFA_REGNUM);
8901 emit_insn (gen_add3_insn (anchor_reg, base_rtx,
8902 gen_int_mode (anchor_offset, Pmode)));
8903 }
8904 base_rtx = anchor_reg;
8905 offset -= anchor_offset;
8906 }
8907 if (!ptrue)
8908 {
8909 int pred_reg = cfun->machine->frame.spare_pred_reg;
8910 emit_move_insn (gen_rtx_REG (VNx16BImode, pred_reg),
8911 CONSTM1_RTX (VNx16BImode));
8912 ptrue = gen_rtx_REG (VNx2BImode, pred_reg);
8913 }
8914 }
8915
8916 /* Add a REG_CFA_EXPRESSION note to INSN to say that register REG
8917 is saved at BASE + OFFSET. */
8918
8919 static void
8920 aarch64_add_cfa_expression (rtx_insn *insn, rtx reg,
8921 rtx base, poly_int64 offset)
8922 {
8923 rtx mem = gen_frame_mem (GET_MODE (reg),
8924 plus_constant (Pmode, base, offset));
8925 add_reg_note (insn, REG_CFA_EXPRESSION, gen_rtx_SET (mem, reg));
8926 }
8927
8928 /* Emit code to save the callee-saved registers in REGS. Skip any
8929 write-back candidates if SKIP_WB is true, otherwise consider only
8930 write-back candidates.
8931
8932 The stack pointer is currently BYTES_BELOW_SP bytes above the bottom
8933 of the static frame. HARD_FP_VALID_P is true if the hard frame pointer
8934 has been set up. */
8935
8936 static void
8937 aarch64_save_callee_saves (poly_int64 bytes_below_sp,
8938 array_slice<unsigned int> regs, bool skip_wb,
8939 bool hard_fp_valid_p)
8940 {
8941 aarch64_frame &frame = cfun->machine->frame;
8942 rtx_insn *insn;
8943 rtx anchor_reg = NULL_RTX, ptrue = NULL_RTX;
8944
8945 auto skip_save_p = [&](unsigned int regno)
8946 {
8947 if (cfun->machine->reg_is_wrapped_separately[regno])
8948 return true;
8949
8950 if (skip_wb == (regno == frame.wb_push_candidate1
8951 || regno == frame.wb_push_candidate2))
8952 return true;
8953
8954 return false;
8955 };
8956
8957 for (unsigned int i = 0; i < regs.size (); ++i)
8958 {
8959 unsigned int regno = regs[i];
8960 poly_int64 offset;
8961 bool frame_related_p = aarch64_emit_cfi_for_reg_p (regno);
8962
8963 if (skip_save_p (regno))
8964 continue;
8965
8966 machine_mode mode = aarch64_reg_save_mode (regno);
8967 rtx reg = gen_rtx_REG (mode, regno);
8968 rtx move_src = reg;
8969 offset = frame.reg_offset[regno] - bytes_below_sp;
8970 if (regno == VG_REGNUM)
8971 {
8972 move_src = gen_rtx_REG (DImode, IP0_REGNUM);
8973 emit_move_insn (move_src, gen_int_mode (aarch64_sve_vg, DImode));
8974 }
8975 rtx base_rtx = stack_pointer_rtx;
8976 poly_int64 sp_offset = offset;
8977
8978 HOST_WIDE_INT const_offset;
8979 if (mode == VNx2DImode && BYTES_BIG_ENDIAN)
8980 aarch64_adjust_sve_callee_save_base (mode, base_rtx, anchor_reg,
8981 offset, ptrue);
8982 else if (GP_REGNUM_P (REGNO (reg))
8983 && (!offset.is_constant (&const_offset) || const_offset >= 512))
8984 {
8985 poly_int64 fp_offset = frame.bytes_below_hard_fp - bytes_below_sp;
8986 if (hard_fp_valid_p)
8987 base_rtx = hard_frame_pointer_rtx;
8988 else
8989 {
8990 if (!anchor_reg)
8991 {
8992 anchor_reg = gen_rtx_REG (Pmode, STACK_CLASH_SVE_CFA_REGNUM);
8993 emit_insn (gen_add3_insn (anchor_reg, base_rtx,
8994 gen_int_mode (fp_offset, Pmode)));
8995 }
8996 base_rtx = anchor_reg;
8997 }
8998 offset -= fp_offset;
8999 }
9000 rtx mem = gen_frame_mem (mode, plus_constant (Pmode, base_rtx, offset));
9001 rtx cfi_mem = gen_frame_mem (mode, plus_constant (Pmode,
9002 stack_pointer_rtx,
9003 sp_offset));
9004 rtx cfi_set = gen_rtx_SET (cfi_mem, reg);
9005 bool need_cfi_note_p = (base_rtx != stack_pointer_rtx);
9006
9007 unsigned int regno2;
9008 if (!aarch64_sve_mode_p (mode)
9009 && reg == move_src
9010 && i + 1 < regs.size ()
9011 && (regno2 = regs[i + 1], !skip_save_p (regno2))
9012 && known_eq (GET_MODE_SIZE (mode),
9013 frame.reg_offset[regno2] - frame.reg_offset[regno]))
9014 {
9015 rtx reg2 = gen_rtx_REG (mode, regno2);
9016
9017 offset += GET_MODE_SIZE (mode);
9018 insn = emit_insn (aarch64_gen_store_pair (mem, reg, reg2));
9019
9020 rtx cfi_mem2
9021 = gen_frame_mem (mode,
9022 plus_constant (Pmode,
9023 stack_pointer_rtx,
9024 sp_offset + GET_MODE_SIZE (mode)));
9025 rtx cfi_set2 = gen_rtx_SET (cfi_mem2, reg2);
9026
9027 /* The first part of a frame-related parallel insn is always
9028 assumed to be relevant to the frame calculations;
9029 subsequent parts, are only frame-related if
9030 explicitly marked. */
9031 if (aarch64_emit_cfi_for_reg_p (regno2))
9032 RTX_FRAME_RELATED_P (cfi_set2) = 1;
9033
9034 /* Add a REG_FRAME_RELATED_EXPR note since the unspec
9035 representation of stp cannot be understood directly by
9036 dwarf2cfi. */
9037 rtx par = gen_rtx_PARALLEL (VOIDmode,
9038 gen_rtvec (2, cfi_set, cfi_set2));
9039 add_reg_note (insn, REG_FRAME_RELATED_EXPR, par);
9040
9041 regno = regno2;
9042 ++i;
9043 }
9044 else
9045 {
9046 if (mode == VNx2DImode && BYTES_BIG_ENDIAN)
9047 {
9048 insn = emit_insn (gen_aarch64_pred_mov (mode, mem,
9049 ptrue, move_src));
9050 need_cfi_note_p = true;
9051 }
9052 else if (aarch64_sve_mode_p (mode))
9053 insn = emit_insn (gen_rtx_SET (mem, move_src));
9054 else
9055 insn = emit_move_insn (mem, move_src);
9056
9057 if (frame_related_p && (need_cfi_note_p || move_src != reg))
9058 add_reg_note (insn, REG_FRAME_RELATED_EXPR, cfi_set);
9059 }
9060
9061 RTX_FRAME_RELATED_P (insn) = frame_related_p;
9062
9063 /* Emit a fake instruction to indicate that the VG save slot has
9064 been initialized. */
9065 if (regno == VG_REGNUM)
9066 emit_insn (gen_aarch64_old_vg_saved (move_src, mem));
9067 }
9068 }
9069
9070 /* Emit code to restore the callee registers in REGS, ignoring pop candidates
9071 and any other registers that are handled separately. Write the appropriate
9072 REG_CFA_RESTORE notes into CFI_OPS.
9073
9074 The stack pointer is currently BYTES_BELOW_SP bytes above the bottom
9075 of the static frame. */
9076
9077 static void
9078 aarch64_restore_callee_saves (poly_int64 bytes_below_sp,
9079 array_slice<unsigned int> regs, rtx *cfi_ops)
9080 {
9081 aarch64_frame &frame = cfun->machine->frame;
9082 poly_int64 offset;
9083 rtx anchor_reg = NULL_RTX, ptrue = NULL_RTX;
9084
9085 auto skip_restore_p = [&](unsigned int regno)
9086 {
9087 if (cfun->machine->reg_is_wrapped_separately[regno])
9088 return true;
9089
9090 if (regno == frame.wb_pop_candidate1
9091 || regno == frame.wb_pop_candidate2)
9092 return true;
9093
9094 /* The shadow call stack code restores LR separately. */
9095 if (frame.is_scs_enabled && regno == LR_REGNUM)
9096 return true;
9097
9098 return false;
9099 };
9100
9101 for (unsigned int i = 0; i < regs.size (); ++i)
9102 {
9103 unsigned int regno = regs[i];
9104 bool frame_related_p = aarch64_emit_cfi_for_reg_p (regno);
9105 if (skip_restore_p (regno))
9106 continue;
9107
9108 machine_mode mode = aarch64_reg_save_mode (regno);
9109 rtx reg = gen_rtx_REG (mode, regno);
9110 offset = frame.reg_offset[regno] - bytes_below_sp;
9111 rtx base_rtx = stack_pointer_rtx;
9112 if (mode == VNx2DImode && BYTES_BIG_ENDIAN)
9113 aarch64_adjust_sve_callee_save_base (mode, base_rtx, anchor_reg,
9114 offset, ptrue);
9115 rtx mem = gen_frame_mem (mode, plus_constant (Pmode, base_rtx, offset));
9116
9117 unsigned int regno2;
9118 if (!aarch64_sve_mode_p (mode)
9119 && i + 1 < regs.size ()
9120 && (regno2 = regs[i + 1], !skip_restore_p (regno2))
9121 && known_eq (GET_MODE_SIZE (mode),
9122 frame.reg_offset[regno2] - frame.reg_offset[regno]))
9123 {
9124 rtx reg2 = gen_rtx_REG (mode, regno2);
9125
9126 offset += GET_MODE_SIZE (mode);
9127 emit_insn (aarch64_gen_load_pair (reg, reg2, mem));
9128
9129 *cfi_ops = alloc_reg_note (REG_CFA_RESTORE, reg2, *cfi_ops);
9130 regno = regno2;
9131 ++i;
9132 }
9133 else if (mode == VNx2DImode && BYTES_BIG_ENDIAN)
9134 emit_insn (gen_aarch64_pred_mov (mode, reg, ptrue, mem));
9135 else if (aarch64_sve_mode_p (mode))
9136 emit_insn (gen_rtx_SET (reg, mem));
9137 else
9138 emit_move_insn (reg, mem);
9139 if (frame_related_p)
9140 *cfi_ops = alloc_reg_note (REG_CFA_RESTORE, reg, *cfi_ops);
9141 }
9142 }
9143
9144 /* Return true if OFFSET is a signed 4-bit value multiplied by the size
9145 of MODE. */
9146
9147 static inline bool
9148 offset_4bit_signed_scaled_p (machine_mode mode, poly_int64 offset)
9149 {
9150 HOST_WIDE_INT multiple;
9151 return (constant_multiple_p (offset, GET_MODE_SIZE (mode), &multiple)
9152 && IN_RANGE (multiple, -8, 7));
9153 }
9154
9155 /* Return true if OFFSET is a signed 6-bit value multiplied by the size
9156 of MODE. */
9157
9158 static inline bool
9159 offset_6bit_signed_scaled_p (machine_mode mode, poly_int64 offset)
9160 {
9161 HOST_WIDE_INT multiple;
9162 return (constant_multiple_p (offset, GET_MODE_SIZE (mode), &multiple)
9163 && IN_RANGE (multiple, -32, 31));
9164 }
9165
9166 /* Return true if OFFSET is an unsigned 6-bit value multiplied by the size
9167 of MODE. */
9168
9169 static inline bool
9170 offset_6bit_unsigned_scaled_p (machine_mode mode, poly_int64 offset)
9171 {
9172 HOST_WIDE_INT multiple;
9173 return (constant_multiple_p (offset, GET_MODE_SIZE (mode), &multiple)
9174 && IN_RANGE (multiple, 0, 63));
9175 }
9176
9177 /* Return true if OFFSET is a signed 7-bit value multiplied by the size
9178 of MODE. */
9179
9180 bool
9181 aarch64_offset_7bit_signed_scaled_p (machine_mode mode, poly_int64 offset)
9182 {
9183 HOST_WIDE_INT multiple;
9184 return (constant_multiple_p (offset, GET_MODE_SIZE (mode), &multiple)
9185 && IN_RANGE (multiple, -64, 63));
9186 }
9187
9188 /* Return true if OFFSET is a signed 9-bit value. */
9189
9190 bool
9191 aarch64_offset_9bit_signed_unscaled_p (machine_mode mode ATTRIBUTE_UNUSED,
9192 poly_int64 offset)
9193 {
9194 HOST_WIDE_INT const_offset;
9195 return (offset.is_constant (&const_offset)
9196 && IN_RANGE (const_offset, -256, 255));
9197 }
9198
9199 /* Return true if OFFSET is a signed 9-bit value multiplied by the size
9200 of MODE. */
9201
9202 static inline bool
9203 offset_9bit_signed_scaled_p (machine_mode mode, poly_int64 offset)
9204 {
9205 HOST_WIDE_INT multiple;
9206 return (constant_multiple_p (offset, GET_MODE_SIZE (mode), &multiple)
9207 && IN_RANGE (multiple, -256, 255));
9208 }
9209
9210 /* Return true if OFFSET is an unsigned 12-bit value multiplied by the size
9211 of MODE. */
9212
9213 static inline bool
9214 offset_12bit_unsigned_scaled_p (machine_mode mode, poly_int64 offset)
9215 {
9216 HOST_WIDE_INT multiple;
9217 return (constant_multiple_p (offset, GET_MODE_SIZE (mode), &multiple)
9218 && IN_RANGE (multiple, 0, 4095));
9219 }
9220
9221 /* Implement TARGET_SHRINK_WRAP_GET_SEPARATE_COMPONENTS. */
9222
9223 static sbitmap
9224 aarch64_get_separate_components (void)
9225 {
9226 aarch64_frame &frame = cfun->machine->frame;
9227 sbitmap components = sbitmap_alloc (LAST_SAVED_REGNUM + 1);
9228 bitmap_clear (components);
9229
9230 /* The registers we need saved to the frame. */
9231 bool enables_pstate_sm = aarch64_cfun_enables_pstate_sm ();
9232 for (unsigned regno = 0; regno <= LAST_SAVED_REGNUM; regno++)
9233 if (aarch64_register_saved_on_entry (regno))
9234 {
9235 /* Disallow shrink wrapping for registers that will be clobbered
9236 by an SMSTART SM in the prologue. */
9237 if (enables_pstate_sm
9238 && (FP_REGNUM_P (regno) || PR_REGNUM_P (regno)))
9239 continue;
9240
9241 /* Punt on saves and restores that use ST1D and LD1D. We could
9242 try to be smarter, but it would involve making sure that the
9243 spare predicate register itself is safe to use at the save
9244 and restore points. Also, when a frame pointer is being used,
9245 the slots are often out of reach of ST1D and LD1D anyway. */
9246 machine_mode mode = aarch64_reg_save_mode (regno);
9247 if (mode == VNx2DImode && BYTES_BIG_ENDIAN)
9248 continue;
9249
9250 poly_int64 offset = frame.reg_offset[regno];
9251
9252 /* Get the offset relative to the register we'll use. */
9253 if (frame_pointer_needed)
9254 offset -= frame.bytes_below_hard_fp;
9255
9256 /* Check that we can access the stack slot of the register with one
9257 direct load with no adjustments needed. */
9258 if (aarch64_sve_mode_p (mode)
9259 ? offset_9bit_signed_scaled_p (mode, offset)
9260 : offset_12bit_unsigned_scaled_p (mode, offset))
9261 bitmap_set_bit (components, regno);
9262 }
9263
9264 /* Don't mess with the hard frame pointer. */
9265 if (frame_pointer_needed)
9266 bitmap_clear_bit (components, HARD_FRAME_POINTER_REGNUM);
9267
9268 /* If the spare predicate register used by big-endian SVE code
9269 is call-preserved, it must be saved in the main prologue
9270 before any saves that use it. */
9271 if (frame.spare_pred_reg != INVALID_REGNUM)
9272 bitmap_clear_bit (components, frame.spare_pred_reg);
9273
9274 unsigned reg1 = frame.wb_push_candidate1;
9275 unsigned reg2 = frame.wb_push_candidate2;
9276 /* If registers have been chosen to be stored/restored with
9277 writeback don't interfere with them to avoid having to output explicit
9278 stack adjustment instructions. */
9279 if (reg2 != INVALID_REGNUM)
9280 bitmap_clear_bit (components, reg2);
9281 if (reg1 != INVALID_REGNUM)
9282 bitmap_clear_bit (components, reg1);
9283
9284 bitmap_clear_bit (components, LR_REGNUM);
9285 bitmap_clear_bit (components, SP_REGNUM);
9286 if (flag_stack_clash_protection)
9287 {
9288 if (frame.sve_save_and_probe != INVALID_REGNUM)
9289 bitmap_clear_bit (components, frame.sve_save_and_probe);
9290 if (frame.hard_fp_save_and_probe != INVALID_REGNUM)
9291 bitmap_clear_bit (components, frame.hard_fp_save_and_probe);
9292 }
9293
9294 /* The VG save sequence needs a temporary GPR. Punt for now on trying
9295 to find one. */
9296 bitmap_clear_bit (components, VG_REGNUM);
9297
9298 return components;
9299 }
9300
9301 /* Implement TARGET_SHRINK_WRAP_COMPONENTS_FOR_BB. */
9302
9303 static sbitmap
9304 aarch64_components_for_bb (basic_block bb)
9305 {
9306 bitmap in = DF_LIVE_IN (bb);
9307 bitmap gen = &DF_LIVE_BB_INFO (bb)->gen;
9308 bitmap kill = &DF_LIVE_BB_INFO (bb)->kill;
9309
9310 sbitmap components = sbitmap_alloc (LAST_SAVED_REGNUM + 1);
9311 bitmap_clear (components);
9312
9313 /* Clobbered registers don't generate values in any meaningful sense,
9314 since nothing after the clobber can rely on their value. And we can't
9315 say that partially-clobbered registers are unconditionally killed,
9316 because whether they're killed or not depends on the mode of the
9317 value they're holding. Thus partially call-clobbered registers
9318 appear in neither the kill set nor the gen set.
9319
9320 Check manually for any calls that clobber more of a register than the
9321 current function can. */
9322 function_abi_aggregator callee_abis;
9323 rtx_insn *insn;
9324 FOR_BB_INSNS (bb, insn)
9325 if (CALL_P (insn))
9326 callee_abis.note_callee_abi (insn_callee_abi (insn));
9327 HARD_REG_SET extra_caller_saves = callee_abis.caller_save_regs (*crtl->abi);
9328
9329 /* GPRs are used in a bb if they are in the IN, GEN, or KILL sets. */
9330 for (unsigned regno = 0; regno <= LAST_SAVED_REGNUM; regno++)
9331 if (!fixed_regs[regno]
9332 && !crtl->abi->clobbers_full_reg_p (regno)
9333 && (TEST_HARD_REG_BIT (extra_caller_saves, regno)
9334 || bitmap_bit_p (in, regno)
9335 || bitmap_bit_p (gen, regno)
9336 || bitmap_bit_p (kill, regno)))
9337 {
9338 bitmap_set_bit (components, regno);
9339
9340 /* If there is a callee-save at an adjacent offset, add it too
9341 to increase the use of LDP/STP. */
9342 poly_int64 offset = cfun->machine->frame.reg_offset[regno];
9343 unsigned regno2 = multiple_p (offset, 16) ? regno + 1 : regno - 1;
9344
9345 if (regno2 <= LAST_SAVED_REGNUM)
9346 {
9347 poly_int64 offset2 = cfun->machine->frame.reg_offset[regno2];
9348 if (regno < regno2
9349 ? known_eq (offset + 8, offset2)
9350 : multiple_p (offset2, 16) && known_eq (offset2 + 8, offset))
9351 bitmap_set_bit (components, regno2);
9352 }
9353 }
9354
9355 return components;
9356 }
9357
9358 /* Implement TARGET_SHRINK_WRAP_DISQUALIFY_COMPONENTS.
9359 Nothing to do for aarch64. */
9360
9361 static void
9362 aarch64_disqualify_components (sbitmap, edge, sbitmap, bool)
9363 {
9364 }
9365
9366 /* Return the next set bit in BMP from START onwards. Return the total number
9367 of bits in BMP if no set bit is found at or after START. */
9368
9369 static unsigned int
9370 aarch64_get_next_set_bit (sbitmap bmp, unsigned int start)
9371 {
9372 unsigned int nbits = SBITMAP_SIZE (bmp);
9373 if (start == nbits)
9374 return start;
9375
9376 gcc_assert (start < nbits);
9377 for (unsigned int i = start; i < nbits; i++)
9378 if (bitmap_bit_p (bmp, i))
9379 return i;
9380
9381 return nbits;
9382 }
9383
9384 /* Do the work for aarch64_emit_prologue_components and
9385 aarch64_emit_epilogue_components. COMPONENTS is the bitmap of registers
9386 to save/restore, PROLOGUE_P indicates whether to emit the prologue sequence
9387 for these components or the epilogue sequence. That is, it determines
9388 whether we should emit stores or loads and what kind of CFA notes to attach
9389 to the insns. Otherwise the logic for the two sequences is very
9390 similar. */
9391
9392 static void
9393 aarch64_process_components (sbitmap components, bool prologue_p)
9394 {
9395 aarch64_frame &frame = cfun->machine->frame;
9396 rtx ptr_reg = gen_rtx_REG (Pmode, frame_pointer_needed
9397 ? HARD_FRAME_POINTER_REGNUM
9398 : STACK_POINTER_REGNUM);
9399
9400 unsigned last_regno = SBITMAP_SIZE (components);
9401 unsigned regno = aarch64_get_next_set_bit (components, R0_REGNUM);
9402 rtx_insn *insn = NULL;
9403
9404 while (regno != last_regno)
9405 {
9406 bool frame_related_p = aarch64_emit_cfi_for_reg_p (regno);
9407 machine_mode mode = aarch64_reg_save_mode (regno);
9408
9409 rtx reg = gen_rtx_REG (mode, regno);
9410 poly_int64 offset = frame.reg_offset[regno];
9411 if (frame_pointer_needed)
9412 offset -= frame.bytes_below_hard_fp;
9413
9414 rtx addr = plus_constant (Pmode, ptr_reg, offset);
9415 rtx mem = gen_frame_mem (mode, addr);
9416
9417 rtx set = prologue_p ? gen_rtx_SET (mem, reg) : gen_rtx_SET (reg, mem);
9418 unsigned regno2 = aarch64_get_next_set_bit (components, regno + 1);
9419 /* No more registers to handle after REGNO.
9420 Emit a single save/restore and exit. */
9421 if (regno2 == last_regno)
9422 {
9423 insn = emit_insn (set);
9424 if (frame_related_p)
9425 {
9426 RTX_FRAME_RELATED_P (insn) = 1;
9427 if (prologue_p)
9428 add_reg_note (insn, REG_CFA_OFFSET, copy_rtx (set));
9429 else
9430 add_reg_note (insn, REG_CFA_RESTORE, reg);
9431 }
9432 break;
9433 }
9434
9435 poly_int64 offset2 = frame.reg_offset[regno2];
9436 /* The next register is not of the same class or its offset is not
9437 mergeable with the current one into a pair. */
9438 if (aarch64_sve_mode_p (mode)
9439 || !satisfies_constraint_Ump (mem)
9440 || GP_REGNUM_P (regno) != GP_REGNUM_P (regno2)
9441 || (crtl->abi->id () == ARM_PCS_SIMD && FP_REGNUM_P (regno))
9442 || maybe_ne ((offset2 - frame.reg_offset[regno]),
9443 GET_MODE_SIZE (mode)))
9444 {
9445 insn = emit_insn (set);
9446 if (frame_related_p)
9447 {
9448 RTX_FRAME_RELATED_P (insn) = 1;
9449 if (prologue_p)
9450 add_reg_note (insn, REG_CFA_OFFSET, copy_rtx (set));
9451 else
9452 add_reg_note (insn, REG_CFA_RESTORE, reg);
9453 }
9454
9455 regno = regno2;
9456 continue;
9457 }
9458
9459 bool frame_related2_p = aarch64_emit_cfi_for_reg_p (regno2);
9460
9461 /* REGNO2 can be saved/restored in a pair with REGNO. */
9462 rtx reg2 = gen_rtx_REG (mode, regno2);
9463 if (frame_pointer_needed)
9464 offset2 -= frame.bytes_below_hard_fp;
9465 rtx addr2 = plus_constant (Pmode, ptr_reg, offset2);
9466 rtx mem2 = gen_frame_mem (mode, addr2);
9467 rtx set2 = prologue_p ? gen_rtx_SET (mem2, reg2)
9468 : gen_rtx_SET (reg2, mem2);
9469
9470 if (prologue_p)
9471 insn = emit_insn (aarch64_gen_store_pair (mem, reg, reg2));
9472 else
9473 insn = emit_insn (aarch64_gen_load_pair (reg, reg2, mem));
9474
9475 if (frame_related_p || frame_related2_p)
9476 {
9477 RTX_FRAME_RELATED_P (insn) = 1;
9478 if (prologue_p)
9479 {
9480 if (frame_related_p)
9481 add_reg_note (insn, REG_CFA_OFFSET, set);
9482 if (frame_related2_p)
9483 add_reg_note (insn, REG_CFA_OFFSET, set2);
9484 }
9485 else
9486 {
9487 if (frame_related_p)
9488 add_reg_note (insn, REG_CFA_RESTORE, reg);
9489 if (frame_related2_p)
9490 add_reg_note (insn, REG_CFA_RESTORE, reg2);
9491 }
9492 }
9493
9494 regno = aarch64_get_next_set_bit (components, regno2 + 1);
9495 }
9496 }
9497
9498 /* Implement TARGET_SHRINK_WRAP_EMIT_PROLOGUE_COMPONENTS. */
9499
9500 static void
9501 aarch64_emit_prologue_components (sbitmap components)
9502 {
9503 aarch64_process_components (components, true);
9504 }
9505
9506 /* Implement TARGET_SHRINK_WRAP_EMIT_EPILOGUE_COMPONENTS. */
9507
9508 static void
9509 aarch64_emit_epilogue_components (sbitmap components)
9510 {
9511 aarch64_process_components (components, false);
9512 }
9513
9514 /* Implement TARGET_SHRINK_WRAP_SET_HANDLED_COMPONENTS. */
9515
9516 static void
9517 aarch64_set_handled_components (sbitmap components)
9518 {
9519 for (unsigned regno = 0; regno <= LAST_SAVED_REGNUM; regno++)
9520 if (bitmap_bit_p (components, regno))
9521 cfun->machine->reg_is_wrapped_separately[regno] = true;
9522 }
9523
9524 /* On AArch64 we have an ABI defined safe buffer. This constant is used to
9525 determining the probe offset for alloca. */
9526
9527 static HOST_WIDE_INT
9528 aarch64_stack_clash_protection_alloca_probe_range (void)
9529 {
9530 return STACK_CLASH_CALLER_GUARD;
9531 }
9532
9533 /* Emit a stack tie that acts as a scheduling barrier for all previous and
9534 subsequent memory accesses and that requires the stack pointer and REG
9535 to have their current values. REG can be stack_pointer_rtx if no
9536 other register's value needs to be fixed. */
9537
9538 static void
9539 aarch64_emit_stack_tie (rtx reg)
9540 {
9541 emit_insn (gen_stack_tie (reg, gen_int_mode (REGNO (reg), DImode)));
9542 }
9543
9544 /* Allocate POLY_SIZE bytes of stack space using TEMP1 and TEMP2 as scratch
9545 registers, given that the stack pointer is currently BYTES_BELOW_SP bytes
9546 above the bottom of the static frame.
9547
9548 If POLY_SIZE is not large enough to require a probe this function will only
9549 adjust the stack. When allocating the stack space FRAME_RELATED_P is then
9550 used to indicate if the allocation is frame related. FINAL_ADJUSTMENT_P
9551 indicates whether we are allocating the area below the saved registers.
9552 If we are then we ensure that any allocation larger than the ABI defined
9553 buffer needs a probe so that the invariant of having a 1KB buffer is
9554 maintained.
9555
9556 We emit barriers after each stack adjustment to prevent optimizations from
9557 breaking the invariant that we never drop the stack more than a page. This
9558 invariant is needed to make it easier to correctly handle asynchronous
9559 events, e.g. if we were to allow the stack to be dropped by more than a page
9560 and then have multiple probes up and we take a signal somewhere in between
9561 then the signal handler doesn't know the state of the stack and can make no
9562 assumptions about which pages have been probed.
9563
9564 FORCE_ISA_MODE is AARCH64_ISA_MODE_SM_ON if any variable component of
9565 POLY_SIZE is measured relative to the SME vector length instead of the
9566 current prevailing vector length. It is 0 otherwise. */
9567
9568 static void
9569 aarch64_allocate_and_probe_stack_space (rtx temp1, rtx temp2,
9570 poly_int64 poly_size,
9571 poly_int64 bytes_below_sp,
9572 aarch64_isa_mode force_isa_mode,
9573 bool frame_related_p,
9574 bool final_adjustment_p)
9575 {
9576 aarch64_frame &frame = cfun->machine->frame;
9577 HOST_WIDE_INT guard_size
9578 = 1 << param_stack_clash_protection_guard_size;
9579 HOST_WIDE_INT guard_used_by_caller = STACK_CLASH_CALLER_GUARD;
9580 HOST_WIDE_INT byte_sp_alignment = STACK_BOUNDARY / BITS_PER_UNIT;
9581 gcc_assert (multiple_p (poly_size, byte_sp_alignment));
9582 HOST_WIDE_INT min_probe_threshold
9583 = (final_adjustment_p
9584 ? guard_used_by_caller + byte_sp_alignment
9585 : guard_size - guard_used_by_caller);
9586 poly_int64 frame_size = frame.frame_size;
9587
9588 /* We should always have a positive probe threshold. */
9589 gcc_assert (min_probe_threshold > 0);
9590
9591 if (flag_stack_clash_protection && !final_adjustment_p)
9592 {
9593 poly_int64 initial_adjust = frame.initial_adjust;
9594 poly_int64 sve_callee_adjust = frame.sve_callee_adjust;
9595 poly_int64 final_adjust = frame.final_adjust;
9596
9597 if (known_eq (frame_size, 0))
9598 {
9599 dump_stack_clash_frame_info (NO_PROBE_NO_FRAME, false);
9600 }
9601 else if (known_lt (initial_adjust + sve_callee_adjust,
9602 guard_size - guard_used_by_caller)
9603 && known_lt (final_adjust, guard_used_by_caller))
9604 {
9605 dump_stack_clash_frame_info (NO_PROBE_SMALL_FRAME, true);
9606 }
9607 }
9608
9609 /* If SIZE is not large enough to require probing, just adjust the stack and
9610 exit. */
9611 if (known_lt (poly_size, min_probe_threshold)
9612 || !flag_stack_clash_protection)
9613 {
9614 aarch64_sub_sp (temp1, temp2, poly_size, force_isa_mode,
9615 frame_related_p);
9616 return;
9617 }
9618
9619 HOST_WIDE_INT size;
9620 /* Handle the SVE non-constant case first. */
9621 if (!poly_size.is_constant (&size))
9622 {
9623 if (dump_file)
9624 {
9625 fprintf (dump_file, "Stack clash SVE prologue: ");
9626 print_dec (poly_size, dump_file);
9627 fprintf (dump_file, " bytes, dynamic probing will be required.\n");
9628 }
9629
9630 /* First calculate the amount of bytes we're actually spilling. */
9631 aarch64_add_offset (Pmode, temp1, CONST0_RTX (Pmode),
9632 poly_size, temp1, temp2, force_isa_mode,
9633 false, true);
9634
9635 auto initial_cfa_offset = frame.frame_size - bytes_below_sp;
9636 auto final_cfa_offset = initial_cfa_offset + poly_size;
9637 if (frame_related_p)
9638 {
9639 /* This is done to provide unwinding information for the stack
9640 adjustments we're about to do, however to prevent the optimizers
9641 from removing the R11 move and leaving the CFA note (which would be
9642 very wrong) we tie the old and new stack pointer together.
9643 The tie will expand to nothing but the optimizers will not touch
9644 the instruction. */
9645 rtx stack_ptr_copy = gen_rtx_REG (Pmode, STACK_CLASH_SVE_CFA_REGNUM);
9646 auto *insn = emit_move_insn (stack_ptr_copy, stack_pointer_rtx);
9647 aarch64_emit_stack_tie (stack_ptr_copy);
9648
9649 /* We want the CFA independent of the stack pointer for the
9650 duration of the loop. */
9651 add_reg_note (insn, REG_CFA_DEF_CFA,
9652 plus_constant (Pmode, stack_ptr_copy,
9653 initial_cfa_offset));
9654 RTX_FRAME_RELATED_P (insn) = 1;
9655 }
9656
9657 rtx probe_const = gen_int_mode (min_probe_threshold, Pmode);
9658 rtx guard_const = gen_int_mode (guard_size, Pmode);
9659
9660 auto *insn
9661 = emit_insn (gen_probe_sve_stack_clash (Pmode, stack_pointer_rtx,
9662 stack_pointer_rtx, temp1,
9663 probe_const, guard_const));
9664
9665 /* Now reset the CFA register if needed. */
9666 if (frame_related_p)
9667 {
9668 add_reg_note (insn, REG_CFA_DEF_CFA,
9669 plus_constant (Pmode, stack_pointer_rtx,
9670 final_cfa_offset));
9671 RTX_FRAME_RELATED_P (insn) = 1;
9672 }
9673
9674 return;
9675 }
9676
9677 if (dump_file)
9678 fprintf (dump_file,
9679 "Stack clash AArch64 prologue: " HOST_WIDE_INT_PRINT_DEC
9680 " bytes, probing will be required.\n", size);
9681
9682 /* Round size to the nearest multiple of guard_size, and calculate the
9683 residual as the difference between the original size and the rounded
9684 size. */
9685 HOST_WIDE_INT rounded_size = ROUND_DOWN (size, guard_size);
9686 HOST_WIDE_INT residual = size - rounded_size;
9687
9688 /* We can handle a small number of allocations/probes inline. Otherwise
9689 punt to a loop. */
9690 if (rounded_size <= STACK_CLASH_MAX_UNROLL_PAGES * guard_size)
9691 {
9692 for (HOST_WIDE_INT i = 0; i < rounded_size; i += guard_size)
9693 {
9694 aarch64_sub_sp (NULL, temp2, guard_size, force_isa_mode, true);
9695 emit_stack_probe (plus_constant (Pmode, stack_pointer_rtx,
9696 guard_used_by_caller));
9697 emit_insn (gen_blockage ());
9698 }
9699 dump_stack_clash_frame_info (PROBE_INLINE, size != rounded_size);
9700 }
9701 else
9702 {
9703 /* Compute the ending address. */
9704 aarch64_add_offset (Pmode, temp1, stack_pointer_rtx, -rounded_size,
9705 temp1, NULL, force_isa_mode, false, true);
9706 rtx_insn *insn = get_last_insn ();
9707
9708 /* For the initial allocation, we don't have a frame pointer
9709 set up, so we always need CFI notes. If we're doing the
9710 final allocation, then we may have a frame pointer, in which
9711 case it is the CFA, otherwise we need CFI notes.
9712
9713 We can determine which allocation we are doing by looking at
9714 the value of FRAME_RELATED_P since the final allocations are not
9715 frame related. */
9716 auto cfa_offset = frame.frame_size - (bytes_below_sp - rounded_size);
9717 if (frame_related_p)
9718 {
9719 /* We want the CFA independent of the stack pointer for the
9720 duration of the loop. */
9721 add_reg_note (insn, REG_CFA_DEF_CFA,
9722 plus_constant (Pmode, temp1, cfa_offset));
9723 RTX_FRAME_RELATED_P (insn) = 1;
9724 }
9725
9726 /* This allocates and probes the stack. Note that this re-uses some of
9727 the existing Ada stack protection code. However we are guaranteed not
9728 to enter the non loop or residual branches of that code.
9729
9730 The non-loop part won't be entered because if our allocation amount
9731 doesn't require a loop, the case above would handle it.
9732
9733 The residual amount won't be entered because TEMP1 is a mutliple of
9734 the allocation size. The residual will always be 0. As such, the only
9735 part we are actually using from that code is the loop setup. The
9736 actual probing is done in aarch64_output_probe_stack_range. */
9737 insn = emit_insn (gen_probe_stack_range (stack_pointer_rtx,
9738 stack_pointer_rtx, temp1));
9739
9740 /* Now reset the CFA register if needed. */
9741 if (frame_related_p)
9742 {
9743 add_reg_note (insn, REG_CFA_DEF_CFA,
9744 plus_constant (Pmode, stack_pointer_rtx, cfa_offset));
9745 RTX_FRAME_RELATED_P (insn) = 1;
9746 }
9747
9748 emit_insn (gen_blockage ());
9749 dump_stack_clash_frame_info (PROBE_LOOP, size != rounded_size);
9750 }
9751
9752 /* Handle any residuals. Residuals of at least MIN_PROBE_THRESHOLD have to
9753 be probed. This maintains the requirement that each page is probed at
9754 least once. For initial probing we probe only if the allocation is
9755 more than GUARD_SIZE - buffer, and below the saved registers we probe
9756 if the amount is larger than buffer. GUARD_SIZE - buffer + buffer ==
9757 GUARD_SIZE. This works that for any allocation that is large enough to
9758 trigger a probe here, we'll have at least one, and if they're not large
9759 enough for this code to emit anything for them, The page would have been
9760 probed by the saving of FP/LR either by this function or any callees. If
9761 we don't have any callees then we won't have more stack adjustments and so
9762 are still safe. */
9763 if (residual)
9764 {
9765 gcc_assert (guard_used_by_caller + byte_sp_alignment <= size);
9766
9767 /* If we're doing final adjustments, and we've done any full page
9768 allocations then any residual needs to be probed. */
9769 if (final_adjustment_p && rounded_size != 0)
9770 min_probe_threshold = 0;
9771
9772 aarch64_sub_sp (temp1, temp2, residual, force_isa_mode, frame_related_p);
9773 if (residual >= min_probe_threshold)
9774 {
9775 if (dump_file)
9776 fprintf (dump_file,
9777 "Stack clash AArch64 prologue residuals: "
9778 HOST_WIDE_INT_PRINT_DEC " bytes, probing will be required."
9779 "\n", residual);
9780
9781 emit_stack_probe (plus_constant (Pmode, stack_pointer_rtx,
9782 guard_used_by_caller));
9783 emit_insn (gen_blockage ());
9784 }
9785 }
9786 }
9787
9788 /* Implement TARGET_EXTRA_LIVE_ON_ENTRY. */
9789
9790 void
9791 aarch64_extra_live_on_entry (bitmap regs)
9792 {
9793 if (TARGET_ZA)
9794 {
9795 bitmap_set_bit (regs, LOWERING_REGNUM);
9796 bitmap_set_bit (regs, SME_STATE_REGNUM);
9797 bitmap_set_bit (regs, TPIDR2_SETUP_REGNUM);
9798 bitmap_set_bit (regs, ZA_FREE_REGNUM);
9799 bitmap_set_bit (regs, ZA_SAVED_REGNUM);
9800
9801 /* The only time ZA can't have live contents on entry is when
9802 the function explicitly treats it as a pure output. */
9803 auto za_flags = aarch64_cfun_shared_flags ("za");
9804 if (za_flags != (AARCH64_STATE_SHARED | AARCH64_STATE_OUT))
9805 bitmap_set_bit (regs, ZA_REGNUM);
9806
9807 /* Since ZT0 is call-clobbered, it is only live on input if
9808 it is explicitly shared, and is not a pure output. */
9809 auto zt0_flags = aarch64_cfun_shared_flags ("zt0");
9810 if (zt0_flags != 0
9811 && zt0_flags != (AARCH64_STATE_SHARED | AARCH64_STATE_OUT))
9812 bitmap_set_bit (regs, ZT0_REGNUM);
9813 }
9814 }
9815
9816 /* Return 1 if the register is used by the epilogue. We need to say the
9817 return register is used, but only after epilogue generation is complete.
9818 Note that in the case of sibcalls, the values "used by the epilogue" are
9819 considered live at the start of the called function. */
9820
9821 int
9822 aarch64_epilogue_uses (int regno)
9823 {
9824 if (epilogue_completed)
9825 {
9826 if (regno == LR_REGNUM)
9827 return 1;
9828 }
9829 if (regno == LOWERING_REGNUM && TARGET_ZA)
9830 return 1;
9831 if (regno == SME_STATE_REGNUM && TARGET_ZA)
9832 return 1;
9833 if (regno == TPIDR2_SETUP_REGNUM && TARGET_ZA)
9834 return 1;
9835 /* If the function shares SME state with its caller, ensure that that
9836 data is not in the lazy save buffer on exit. */
9837 if (regno == ZA_SAVED_REGNUM && aarch64_cfun_incoming_pstate_za () != 0)
9838 return 1;
9839 if (regno == ZA_REGNUM && aarch64_cfun_shared_flags ("za") != 0)
9840 return 1;
9841 if (regno == ZT0_REGNUM && aarch64_cfun_shared_flags ("zt0") != 0)
9842 return 1;
9843 return 0;
9844 }
9845
9846 /* Implement TARGET_USE_LATE_PROLOGUE_EPILOGUE. */
9847
9848 static bool
9849 aarch64_use_late_prologue_epilogue ()
9850 {
9851 return aarch64_cfun_enables_pstate_sm ();
9852 }
9853
9854 /* The current function's frame has a save slot for the incoming state
9855 of SVCR. Return a legitimate memory for the slot, based on the hard
9856 frame pointer. */
9857
9858 static rtx
9859 aarch64_old_svcr_mem ()
9860 {
9861 gcc_assert (frame_pointer_needed
9862 && known_ge (cfun->machine->frame.old_svcr_offset, 0));
9863 rtx base = hard_frame_pointer_rtx;
9864 poly_int64 offset = (0
9865 /* hard fp -> bottom of frame. */
9866 - cfun->machine->frame.bytes_below_hard_fp
9867 /* bottom of frame -> save slot. */
9868 + cfun->machine->frame.old_svcr_offset);
9869 return gen_frame_mem (DImode, plus_constant (Pmode, base, offset));
9870 }
9871
9872 /* The current function's frame has a save slot for the incoming state
9873 of SVCR. Load the slot into register REGNO and return the register. */
9874
9875 static rtx
9876 aarch64_read_old_svcr (unsigned int regno)
9877 {
9878 rtx svcr = gen_rtx_REG (DImode, regno);
9879 emit_move_insn (svcr, aarch64_old_svcr_mem ());
9880 return svcr;
9881 }
9882
9883 /* Like the rtx version of aarch64_guard_switch_pstate_sm, but first
9884 load the incoming value of SVCR from its save slot into temporary
9885 register REGNO. */
9886
9887 static rtx_insn *
9888 aarch64_guard_switch_pstate_sm (unsigned int regno,
9889 aarch64_isa_mode local_mode)
9890 {
9891 rtx old_svcr = aarch64_read_old_svcr (regno);
9892 return aarch64_guard_switch_pstate_sm (old_svcr, local_mode);
9893 }
9894
9895 /* AArch64 stack frames generated by this compiler look like:
9896
9897 +-------------------------------+
9898 | |
9899 | incoming stack arguments |
9900 | |
9901 +-------------------------------+
9902 | | <-- incoming stack pointer (aligned)
9903 | callee-allocated save area |
9904 | for register varargs |
9905 | |
9906 +-------------------------------+
9907 | local variables (1) | <-- frame_pointer_rtx
9908 | |
9909 +-------------------------------+
9910 | padding (1) |
9911 +-------------------------------+
9912 | callee-saved registers |
9913 +-------------------------------+
9914 | LR' |
9915 +-------------------------------+
9916 | FP' |
9917 +-------------------------------+ <-- hard_frame_pointer_rtx (aligned)
9918 | SVE vector registers |
9919 +-------------------------------+
9920 | SVE predicate registers |
9921 +-------------------------------+
9922 | local variables (2) |
9923 +-------------------------------+
9924 | padding (2) |
9925 +-------------------------------+
9926 | dynamic allocation |
9927 +-------------------------------+
9928 | padding |
9929 +-------------------------------+
9930 | outgoing stack arguments | <-- arg_pointer
9931 | |
9932 +-------------------------------+
9933 | | <-- stack_pointer_rtx (aligned)
9934
9935 The regions marked (1) and (2) are mutually exclusive. (2) is used
9936 when aarch64_save_regs_above_locals_p is true.
9937
9938 Dynamic stack allocations via alloca() decrease stack_pointer_rtx
9939 but leave frame_pointer_rtx and hard_frame_pointer_rtx
9940 unchanged.
9941
9942 By default for stack-clash we assume the guard is at least 64KB, but this
9943 value is configurable to either 4KB or 64KB. We also force the guard size to
9944 be the same as the probing interval and both values are kept in sync.
9945
9946 With those assumptions the callee can allocate up to 63KB (or 3KB depending
9947 on the guard size) of stack space without probing.
9948
9949 When probing is needed, we emit a probe at the start of the prologue
9950 and every PARAM_STACK_CLASH_PROTECTION_GUARD_SIZE bytes thereafter.
9951
9952 We can also use register saves as probes. These are stored in
9953 sve_save_and_probe and hard_fp_save_and_probe.
9954
9955 For outgoing arguments we probe if the size is larger than 1KB, such that
9956 the ABI specified buffer is maintained for the next callee.
9957
9958 The following registers are reserved during frame layout and should not be
9959 used for any other purpose:
9960
9961 - r11: Used by stack clash protection when SVE is enabled, and also
9962 as an anchor register when saving and restoring registers
9963 - r12(EP0) and r13(EP1): Used as temporaries for stack adjustment.
9964 - r14 and r15: Used for speculation tracking.
9965 - r16(IP0), r17(IP1): Used by indirect tailcalls.
9966 - r30(LR), r29(FP): Used by standard frame layout.
9967
9968 These registers must be avoided in frame layout related code unless the
9969 explicit intention is to interact with one of the features listed above. */
9970
9971 /* Generate the prologue instructions for entry into a function.
9972 Establish the stack frame by decreasing the stack pointer with a
9973 properly calculated size and, if necessary, create a frame record
9974 filled with the values of LR and previous frame pointer. The
9975 current FP is also set up if it is in use. */
9976
9977 void
9978 aarch64_expand_prologue (void)
9979 {
9980 aarch64_frame &frame = cfun->machine->frame;
9981 poly_int64 frame_size = frame.frame_size;
9982 poly_int64 initial_adjust = frame.initial_adjust;
9983 HOST_WIDE_INT callee_adjust = frame.callee_adjust;
9984 poly_int64 final_adjust = frame.final_adjust;
9985 poly_int64 sve_callee_adjust = frame.sve_callee_adjust;
9986 unsigned reg1 = frame.wb_push_candidate1;
9987 unsigned reg2 = frame.wb_push_candidate2;
9988 bool emit_frame_chain = frame.emit_frame_chain;
9989 rtx_insn *insn;
9990 aarch64_isa_mode force_isa_mode = 0;
9991 if (aarch64_cfun_enables_pstate_sm ())
9992 force_isa_mode = AARCH64_ISA_MODE_SM_ON;
9993
9994 if (flag_stack_clash_protection
9995 && known_eq (callee_adjust, 0)
9996 && known_lt (frame.reg_offset[VG_REGNUM], 0))
9997 {
9998 /* Fold the SVE allocation into the initial allocation.
9999 We don't do this in aarch64_layout_arg to avoid pessimizing
10000 the epilogue code. */
10001 initial_adjust += sve_callee_adjust;
10002 sve_callee_adjust = 0;
10003 }
10004
10005 /* Sign return address for functions. */
10006 if (aarch64_return_address_signing_enabled ())
10007 {
10008 switch (aarch64_ra_sign_key)
10009 {
10010 case AARCH64_KEY_A:
10011 insn = emit_insn (gen_paciasp ());
10012 break;
10013 case AARCH64_KEY_B:
10014 insn = emit_insn (gen_pacibsp ());
10015 break;
10016 default:
10017 gcc_unreachable ();
10018 }
10019 add_reg_note (insn, REG_CFA_NEGATE_RA_STATE, const0_rtx);
10020 RTX_FRAME_RELATED_P (insn) = 1;
10021 }
10022
10023 /* Push return address to shadow call stack. */
10024 if (frame.is_scs_enabled)
10025 emit_insn (gen_scs_push ());
10026
10027 if (flag_stack_usage_info)
10028 current_function_static_stack_size = constant_lower_bound (frame_size);
10029
10030 if (flag_stack_check == STATIC_BUILTIN_STACK_CHECK)
10031 {
10032 if (crtl->is_leaf && !cfun->calls_alloca)
10033 {
10034 if (maybe_gt (frame_size, PROBE_INTERVAL)
10035 && maybe_gt (frame_size, get_stack_check_protect ()))
10036 aarch64_emit_probe_stack_range (get_stack_check_protect (),
10037 (frame_size
10038 - get_stack_check_protect ()));
10039 }
10040 else if (maybe_gt (frame_size, 0))
10041 aarch64_emit_probe_stack_range (get_stack_check_protect (), frame_size);
10042 }
10043
10044 rtx tmp0_rtx = gen_rtx_REG (Pmode, EP0_REGNUM);
10045 rtx tmp1_rtx = gen_rtx_REG (Pmode, EP1_REGNUM);
10046
10047 /* In theory we should never have both an initial adjustment
10048 and a callee save adjustment. Verify that is the case since the
10049 code below does not handle it for -fstack-clash-protection. */
10050 gcc_assert (known_eq (initial_adjust, 0) || callee_adjust == 0);
10051
10052 /* The offset of the current SP from the bottom of the static frame. */
10053 poly_int64 bytes_below_sp = frame_size;
10054
10055 /* Will only probe if the initial adjustment is larger than the guard
10056 less the amount of the guard reserved for use by the caller's
10057 outgoing args. */
10058 aarch64_allocate_and_probe_stack_space (tmp0_rtx, tmp1_rtx, initial_adjust,
10059 bytes_below_sp, force_isa_mode,
10060 true, false);
10061 bytes_below_sp -= initial_adjust;
10062
10063 if (callee_adjust != 0)
10064 {
10065 aarch64_push_regs (reg1, reg2, callee_adjust);
10066 bytes_below_sp -= callee_adjust;
10067 }
10068
10069 if (emit_frame_chain)
10070 {
10071 /* The offset of the frame chain record (if any) from the current SP. */
10072 poly_int64 chain_offset = (initial_adjust + callee_adjust
10073 - frame.bytes_above_hard_fp);
10074 gcc_assert (known_ge (chain_offset, 0));
10075
10076 gcc_assert (reg1 == R29_REGNUM && reg2 == R30_REGNUM);
10077 if (callee_adjust == 0)
10078 aarch64_save_callee_saves (bytes_below_sp, frame.saved_gprs,
10079 false, false);
10080 else
10081 gcc_assert (known_eq (chain_offset, 0));
10082 aarch64_add_offset (Pmode, hard_frame_pointer_rtx,
10083 stack_pointer_rtx, chain_offset,
10084 tmp1_rtx, tmp0_rtx, force_isa_mode,
10085 frame_pointer_needed);
10086 if (frame_pointer_needed && !frame_size.is_constant ())
10087 {
10088 /* Variable-sized frames need to describe the save slot
10089 address using DW_CFA_expression rather than DW_CFA_offset.
10090 This means that, without taking further action, the
10091 locations of the registers that we've already saved would
10092 remain based on the stack pointer even after we redefine
10093 the CFA based on the frame pointer. We therefore need new
10094 DW_CFA_expressions to re-express the save slots with addresses
10095 based on the frame pointer. */
10096 rtx_insn *insn = get_last_insn ();
10097 gcc_assert (RTX_FRAME_RELATED_P (insn));
10098
10099 /* Add an explicit CFA definition if this was previously
10100 implicit. */
10101 if (!find_reg_note (insn, REG_CFA_ADJUST_CFA, NULL_RTX))
10102 {
10103 rtx src = plus_constant (Pmode, stack_pointer_rtx, chain_offset);
10104 add_reg_note (insn, REG_CFA_ADJUST_CFA,
10105 gen_rtx_SET (hard_frame_pointer_rtx, src));
10106 }
10107
10108 /* Change the save slot expressions for the registers that
10109 we've already saved. */
10110 aarch64_add_cfa_expression (insn, regno_reg_rtx[reg2],
10111 hard_frame_pointer_rtx, UNITS_PER_WORD);
10112 aarch64_add_cfa_expression (insn, regno_reg_rtx[reg1],
10113 hard_frame_pointer_rtx, 0);
10114 }
10115 aarch64_emit_stack_tie (hard_frame_pointer_rtx);
10116 }
10117
10118 aarch64_save_callee_saves (bytes_below_sp, frame.saved_gprs, true,
10119 emit_frame_chain);
10120 if (maybe_ge (frame.reg_offset[VG_REGNUM], 0))
10121 {
10122 unsigned int saved_regs[] = { VG_REGNUM };
10123 aarch64_save_callee_saves (bytes_below_sp, saved_regs, true,
10124 emit_frame_chain);
10125 }
10126 if (maybe_ne (sve_callee_adjust, 0))
10127 {
10128 gcc_assert (!flag_stack_clash_protection
10129 || known_eq (initial_adjust, 0)
10130 /* The VG save isn't shrink-wrapped and so serves as
10131 a probe of the initial allocation. */
10132 || known_eq (frame.reg_offset[VG_REGNUM], bytes_below_sp));
10133 aarch64_allocate_and_probe_stack_space (tmp1_rtx, tmp0_rtx,
10134 sve_callee_adjust,
10135 bytes_below_sp, force_isa_mode,
10136 !frame_pointer_needed, false);
10137 bytes_below_sp -= sve_callee_adjust;
10138 }
10139 aarch64_save_callee_saves (bytes_below_sp, frame.saved_prs, true,
10140 emit_frame_chain);
10141 aarch64_save_callee_saves (bytes_below_sp, frame.saved_fprs, true,
10142 emit_frame_chain);
10143
10144 /* We may need to probe the final adjustment if it is larger than the guard
10145 that is assumed by the called. */
10146 aarch64_allocate_and_probe_stack_space (tmp1_rtx, tmp0_rtx, final_adjust,
10147 bytes_below_sp, force_isa_mode,
10148 !frame_pointer_needed, true);
10149 bytes_below_sp -= final_adjust;
10150 gcc_assert (known_eq (bytes_below_sp, 0));
10151 if (emit_frame_chain && maybe_ne (final_adjust, 0))
10152 aarch64_emit_stack_tie (hard_frame_pointer_rtx);
10153
10154 /* Save the incoming value of PSTATE.SM, if required. Code further
10155 down does this for locally-streaming functions. */
10156 if (known_ge (frame.old_svcr_offset, 0)
10157 && !aarch64_cfun_enables_pstate_sm ())
10158 {
10159 rtx mem = aarch64_old_svcr_mem ();
10160 MEM_VOLATILE_P (mem) = 1;
10161 if (TARGET_SME)
10162 {
10163 rtx reg = gen_rtx_REG (DImode, IP0_REGNUM);
10164 emit_insn (gen_aarch64_read_svcr (reg));
10165 emit_move_insn (mem, reg);
10166 }
10167 else
10168 {
10169 rtx old_r0 = NULL_RTX, old_r1 = NULL_RTX;
10170 auto &args = crtl->args.info;
10171 if (args.aapcs_ncrn > 0)
10172 {
10173 old_r0 = gen_rtx_REG (DImode, PROBE_STACK_FIRST_REGNUM);
10174 emit_move_insn (old_r0, gen_rtx_REG (DImode, R0_REGNUM));
10175 }
10176 if (args.aapcs_ncrn > 1)
10177 {
10178 old_r1 = gen_rtx_REG (DImode, PROBE_STACK_SECOND_REGNUM);
10179 emit_move_insn (old_r1, gen_rtx_REG (DImode, R1_REGNUM));
10180 }
10181 emit_insn (gen_aarch64_get_sme_state ());
10182 emit_move_insn (mem, gen_rtx_REG (DImode, R0_REGNUM));
10183 if (old_r0)
10184 emit_move_insn (gen_rtx_REG (DImode, R0_REGNUM), old_r0);
10185 if (old_r1)
10186 emit_move_insn (gen_rtx_REG (DImode, R1_REGNUM), old_r1);
10187 }
10188 }
10189
10190 /* Enable PSTATE.SM, if required. */
10191 if (aarch64_cfun_enables_pstate_sm ())
10192 {
10193 rtx_insn *guard_label = nullptr;
10194 if (known_ge (cfun->machine->frame.old_svcr_offset, 0))
10195 {
10196 /* The current function is streaming-compatible. Save the
10197 original state of PSTATE.SM. */
10198 rtx svcr = gen_rtx_REG (DImode, IP0_REGNUM);
10199 emit_insn (gen_aarch64_read_svcr (svcr));
10200 emit_move_insn (aarch64_old_svcr_mem (), svcr);
10201 guard_label = aarch64_guard_switch_pstate_sm (svcr,
10202 AARCH64_ISA_MODE);
10203 }
10204 aarch64_sme_mode_switch_regs args_switch;
10205 auto &args = crtl->args.info;
10206 for (unsigned int i = 0; i < args.num_sme_mode_switch_args; ++i)
10207 {
10208 rtx x = args.sme_mode_switch_args[i];
10209 args_switch.add_reg (GET_MODE (x), REGNO (x));
10210 }
10211 args_switch.emit_prologue ();
10212 emit_insn (gen_aarch64_smstart_sm ());
10213 args_switch.emit_epilogue ();
10214 if (guard_label)
10215 emit_label (guard_label);
10216 }
10217 }
10218
10219 /* Return TRUE if we can use a simple_return insn.
10220
10221 This function checks whether the callee saved stack is empty, which
10222 means no restore actions are need. The pro_and_epilogue will use
10223 this to check whether shrink-wrapping opt is feasible. */
10224
10225 bool
10226 aarch64_use_return_insn_p (void)
10227 {
10228 if (!reload_completed)
10229 return false;
10230
10231 if (crtl->profile)
10232 return false;
10233
10234 return known_eq (cfun->machine->frame.frame_size, 0);
10235 }
10236
10237 /* Return false for locally streaming functions in order to avoid
10238 shrink-wrapping them. Shrink-wrapping is unsafe when the function prologue
10239 and epilogue contain streaming state change, because these implicitly change
10240 the meaning of poly_int values. */
10241
10242 bool
10243 aarch64_use_simple_return_insn_p (void)
10244 {
10245 if (aarch64_cfun_enables_pstate_sm ())
10246 return false;
10247
10248 return true;
10249 }
10250
10251 /* Generate the epilogue instructions for returning from a function.
10252 This is almost exactly the reverse of the prolog sequence, except
10253 that we need to insert barriers to avoid scheduling loads that read
10254 from a deallocated stack, and we optimize the unwind records by
10255 emitting them all together if possible. */
10256 void
10257 aarch64_expand_epilogue (rtx_call_insn *sibcall)
10258 {
10259 aarch64_frame &frame = cfun->machine->frame;
10260 poly_int64 initial_adjust = frame.initial_adjust;
10261 HOST_WIDE_INT callee_adjust = frame.callee_adjust;
10262 poly_int64 final_adjust = frame.final_adjust;
10263 poly_int64 sve_callee_adjust = frame.sve_callee_adjust;
10264 poly_int64 bytes_below_hard_fp = frame.bytes_below_hard_fp;
10265 unsigned reg1 = frame.wb_pop_candidate1;
10266 unsigned reg2 = frame.wb_pop_candidate2;
10267 rtx cfi_ops = NULL;
10268 rtx_insn *insn;
10269 /* A stack clash protection prologue may not have left EP0_REGNUM or
10270 EP1_REGNUM in a usable state. The same is true for allocations
10271 with an SVE component, since we then need both temporary registers
10272 for each allocation. For stack clash we are in a usable state if
10273 the adjustment is less than GUARD_SIZE - GUARD_USED_BY_CALLER. */
10274 HOST_WIDE_INT guard_size
10275 = 1 << param_stack_clash_protection_guard_size;
10276 HOST_WIDE_INT guard_used_by_caller = STACK_CLASH_CALLER_GUARD;
10277 aarch64_isa_mode force_isa_mode = 0;
10278 if (aarch64_cfun_enables_pstate_sm ())
10279 force_isa_mode = AARCH64_ISA_MODE_SM_ON;
10280
10281 /* We can re-use the registers when:
10282
10283 (a) the deallocation amount is the same as the corresponding
10284 allocation amount (which is false if we combine the initial
10285 and SVE callee save allocations in the prologue); and
10286
10287 (b) the allocation amount doesn't need a probe (which is false
10288 if the amount is guard_size - guard_used_by_caller or greater).
10289
10290 In such situations the register should remain live with the correct
10291 value. */
10292 bool can_inherit_p = (initial_adjust.is_constant ()
10293 && final_adjust.is_constant ()
10294 && (!flag_stack_clash_protection
10295 || (known_lt (initial_adjust,
10296 guard_size - guard_used_by_caller)
10297 && known_eq (sve_callee_adjust, 0))));
10298
10299 /* We need to add memory barrier to prevent read from deallocated stack. */
10300 bool need_barrier_p
10301 = maybe_ne (get_frame_size ()
10302 + frame.saved_varargs_size, 0);
10303
10304 /* Reset PSTATE.SM, if required. */
10305 if (aarch64_cfun_enables_pstate_sm ())
10306 {
10307 rtx_insn *guard_label = nullptr;
10308 if (known_ge (cfun->machine->frame.old_svcr_offset, 0))
10309 guard_label = aarch64_guard_switch_pstate_sm (IP0_REGNUM,
10310 AARCH64_ISA_MODE);
10311 aarch64_sme_mode_switch_regs return_switch;
10312 if (sibcall)
10313 return_switch.add_call_args (sibcall);
10314 else if (crtl->return_rtx && REG_P (crtl->return_rtx))
10315 return_switch.add_reg (GET_MODE (crtl->return_rtx),
10316 REGNO (crtl->return_rtx));
10317 return_switch.emit_prologue ();
10318 emit_insn (gen_aarch64_smstop_sm ());
10319 return_switch.emit_epilogue ();
10320 if (guard_label)
10321 emit_label (guard_label);
10322 }
10323
10324 /* Emit a barrier to prevent loads from a deallocated stack. */
10325 if (maybe_gt (final_adjust, crtl->outgoing_args_size)
10326 || cfun->calls_alloca
10327 || crtl->calls_eh_return)
10328 {
10329 aarch64_emit_stack_tie (stack_pointer_rtx);
10330 need_barrier_p = false;
10331 }
10332
10333 /* Restore the stack pointer from the frame pointer if it may not
10334 be the same as the stack pointer. */
10335 rtx tmp0_rtx = gen_rtx_REG (Pmode, EP0_REGNUM);
10336 rtx tmp1_rtx = gen_rtx_REG (Pmode, EP1_REGNUM);
10337 if (frame_pointer_needed
10338 && (maybe_ne (final_adjust, 0) || cfun->calls_alloca))
10339 /* If writeback is used when restoring callee-saves, the CFA
10340 is restored on the instruction doing the writeback. */
10341 aarch64_add_offset (Pmode, stack_pointer_rtx,
10342 hard_frame_pointer_rtx,
10343 -bytes_below_hard_fp + final_adjust,
10344 tmp1_rtx, tmp0_rtx, force_isa_mode,
10345 callee_adjust == 0);
10346 else
10347 /* The case where we need to re-use the register here is very rare, so
10348 avoid the complicated condition and just always emit a move if the
10349 immediate doesn't fit. */
10350 aarch64_add_sp (tmp1_rtx, tmp0_rtx, final_adjust, force_isa_mode, true);
10351
10352 /* Restore the vector registers before the predicate registers,
10353 so that we can use P4 as a temporary for big-endian SVE frames. */
10354 aarch64_restore_callee_saves (final_adjust, frame.saved_fprs, &cfi_ops);
10355 aarch64_restore_callee_saves (final_adjust, frame.saved_prs, &cfi_ops);
10356 if (maybe_ne (sve_callee_adjust, 0))
10357 aarch64_add_sp (NULL_RTX, NULL_RTX, sve_callee_adjust,
10358 force_isa_mode, true);
10359
10360 /* When shadow call stack is enabled, the scs_pop in the epilogue will
10361 restore x30, we don't need to restore x30 again in the traditional
10362 way. */
10363 aarch64_restore_callee_saves (final_adjust + sve_callee_adjust,
10364 frame.saved_gprs, &cfi_ops);
10365
10366 if (need_barrier_p)
10367 aarch64_emit_stack_tie (stack_pointer_rtx);
10368
10369 if (callee_adjust != 0)
10370 aarch64_pop_regs (reg1, reg2, callee_adjust, &cfi_ops);
10371
10372 /* If we have no register restore information, the CFA must have been
10373 defined in terms of the stack pointer since the end of the prologue. */
10374 gcc_assert (cfi_ops || !frame_pointer_needed);
10375
10376 if (cfi_ops && (callee_adjust != 0 || maybe_gt (initial_adjust, 65536)))
10377 {
10378 /* Emit delayed restores and set the CFA to be SP + initial_adjust. */
10379 insn = get_last_insn ();
10380 rtx new_cfa = plus_constant (Pmode, stack_pointer_rtx, initial_adjust);
10381 REG_NOTES (insn) = alloc_reg_note (REG_CFA_DEF_CFA, new_cfa, cfi_ops);
10382 RTX_FRAME_RELATED_P (insn) = 1;
10383 cfi_ops = NULL;
10384 }
10385
10386 /* Liveness of EP0_REGNUM can not be trusted across function calls either, so
10387 add restriction on emit_move optimization to leaf functions. */
10388 aarch64_add_sp (tmp0_rtx, tmp1_rtx, initial_adjust, force_isa_mode,
10389 (!can_inherit_p || !crtl->is_leaf
10390 || df_regs_ever_live_p (EP0_REGNUM)));
10391
10392 if (cfi_ops)
10393 {
10394 /* Emit delayed restores and reset the CFA to be SP. */
10395 insn = get_last_insn ();
10396 cfi_ops = alloc_reg_note (REG_CFA_DEF_CFA, stack_pointer_rtx, cfi_ops);
10397 REG_NOTES (insn) = cfi_ops;
10398 RTX_FRAME_RELATED_P (insn) = 1;
10399 }
10400
10401 /* Pop return address from shadow call stack. */
10402 if (frame.is_scs_enabled)
10403 {
10404 machine_mode mode = aarch64_reg_save_mode (R30_REGNUM);
10405 rtx reg = gen_rtx_REG (mode, R30_REGNUM);
10406
10407 insn = emit_insn (gen_scs_pop ());
10408 add_reg_note (insn, REG_CFA_RESTORE, reg);
10409 RTX_FRAME_RELATED_P (insn) = 1;
10410 }
10411
10412 /* Stack adjustment for exception handler. */
10413 if (crtl->calls_eh_return && !sibcall)
10414 {
10415 /* If the EH_RETURN_TAKEN_RTX flag is set then we need
10416 to unwind the stack and jump to the handler, otherwise
10417 skip this eh_return logic and continue with normal
10418 return after the label. We have already reset the CFA
10419 to be SP; letting the CFA move during this adjustment
10420 is just as correct as retaining the CFA from the body
10421 of the function. Therefore, do nothing special. */
10422 rtx_code_label *label = gen_label_rtx ();
10423 rtx x = aarch64_gen_compare_zero_and_branch (EQ, EH_RETURN_TAKEN_RTX,
10424 label);
10425 rtx jump = emit_jump_insn (x);
10426 JUMP_LABEL (jump) = label;
10427 LABEL_NUSES (label)++;
10428 emit_insn (gen_add2_insn (stack_pointer_rtx,
10429 EH_RETURN_STACKADJ_RTX));
10430 emit_jump_insn (gen_indirect_jump (EH_RETURN_HANDLER_RTX));
10431 emit_barrier ();
10432 emit_label (label);
10433 }
10434
10435 /* We prefer to emit the combined return/authenticate instruction RETAA,
10436 however there are three cases in which we must instead emit an explicit
10437 authentication instruction.
10438
10439 1) Sibcalls don't return in a normal way, so if we're about to call one
10440 we must authenticate.
10441
10442 2) The RETAA instruction is not available without FEAT_PAuth, so if we
10443 are generating code for !TARGET_PAUTH we can't use it and must
10444 explicitly authenticate.
10445 */
10446 if (aarch64_return_address_signing_enabled ()
10447 && (sibcall || !TARGET_PAUTH))
10448 {
10449 switch (aarch64_ra_sign_key)
10450 {
10451 case AARCH64_KEY_A:
10452 insn = emit_insn (gen_autiasp ());
10453 break;
10454 case AARCH64_KEY_B:
10455 insn = emit_insn (gen_autibsp ());
10456 break;
10457 default:
10458 gcc_unreachable ();
10459 }
10460 add_reg_note (insn, REG_CFA_NEGATE_RA_STATE, const0_rtx);
10461 RTX_FRAME_RELATED_P (insn) = 1;
10462 }
10463
10464 emit_use (gen_rtx_REG (DImode, LR_REGNUM));
10465 if (!sibcall)
10466 emit_jump_insn (ret_rtx);
10467 }
10468
10469 /* Output code to add DELTA to the first argument, and then jump
10470 to FUNCTION. Used for C++ multiple inheritance. */
10471 static void
10472 aarch64_output_mi_thunk (FILE *file, tree thunk ATTRIBUTE_UNUSED,
10473 HOST_WIDE_INT delta,
10474 HOST_WIDE_INT vcall_offset,
10475 tree function)
10476 {
10477 /* The this pointer is always in x0. Note that this differs from
10478 Arm where the this pointer maybe bumped to r1 if r0 is required
10479 to return a pointer to an aggregate. On AArch64 a result value
10480 pointer will be in x8. */
10481 int this_regno = R0_REGNUM;
10482 rtx this_rtx, temp0, temp1, addr, funexp;
10483 rtx_insn *insn;
10484 const char *fnname = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (thunk));
10485
10486 if (aarch_bti_enabled ())
10487 emit_insn (gen_bti_c());
10488
10489 reload_completed = 1;
10490 emit_note (NOTE_INSN_PROLOGUE_END);
10491
10492 this_rtx = gen_rtx_REG (Pmode, this_regno);
10493 temp0 = gen_rtx_REG (Pmode, EP0_REGNUM);
10494 temp1 = gen_rtx_REG (Pmode, EP1_REGNUM);
10495
10496 if (vcall_offset == 0)
10497 aarch64_add_offset (Pmode, this_rtx, this_rtx, delta, temp1, temp0,
10498 0, false);
10499 else
10500 {
10501 gcc_assert ((vcall_offset & (POINTER_BYTES - 1)) == 0);
10502
10503 addr = this_rtx;
10504 if (delta != 0)
10505 {
10506 if (delta >= -256 && delta < 256)
10507 addr = gen_rtx_PRE_MODIFY (Pmode, this_rtx,
10508 plus_constant (Pmode, this_rtx, delta));
10509 else
10510 aarch64_add_offset (Pmode, this_rtx, this_rtx, delta,
10511 temp1, temp0, 0, false);
10512 }
10513
10514 if (Pmode == ptr_mode)
10515 aarch64_emit_move (temp0, gen_rtx_MEM (ptr_mode, addr));
10516 else
10517 aarch64_emit_move (temp0,
10518 gen_rtx_ZERO_EXTEND (Pmode,
10519 gen_rtx_MEM (ptr_mode, addr)));
10520
10521 if (vcall_offset >= -256 && vcall_offset < 4096 * POINTER_BYTES)
10522 addr = plus_constant (Pmode, temp0, vcall_offset);
10523 else
10524 {
10525 aarch64_internal_mov_immediate (temp1, GEN_INT (vcall_offset), true,
10526 Pmode);
10527 addr = gen_rtx_PLUS (Pmode, temp0, temp1);
10528 }
10529
10530 if (Pmode == ptr_mode)
10531 aarch64_emit_move (temp1, gen_rtx_MEM (ptr_mode,addr));
10532 else
10533 aarch64_emit_move (temp1,
10534 gen_rtx_SIGN_EXTEND (Pmode,
10535 gen_rtx_MEM (ptr_mode, addr)));
10536
10537 emit_insn (gen_add2_insn (this_rtx, temp1));
10538 }
10539
10540 /* Generate a tail call to the target function. */
10541 if (!TREE_USED (function))
10542 {
10543 assemble_external (function);
10544 TREE_USED (function) = 1;
10545 }
10546 funexp = XEXP (DECL_RTL (function), 0);
10547 funexp = gen_rtx_MEM (FUNCTION_MODE, funexp);
10548 auto isa_mode = aarch64_fntype_isa_mode (TREE_TYPE (function));
10549 auto pcs_variant = arm_pcs (fndecl_abi (function).id ());
10550 bool ir = lookup_attribute ("indirect_return",
10551 TYPE_ATTRIBUTES (TREE_TYPE (function)));
10552 rtx callee_abi = aarch64_gen_callee_cookie (isa_mode, pcs_variant, ir);
10553 insn = emit_call_insn (gen_sibcall (funexp, const0_rtx, callee_abi));
10554 SIBLING_CALL_P (insn) = 1;
10555
10556 insn = get_insns ();
10557 shorten_branches (insn);
10558
10559 assemble_start_function (thunk, fnname);
10560 final_start_function (insn, file, 1);
10561 final (insn, file, 1);
10562 final_end_function ();
10563 assemble_end_function (thunk, fnname);
10564
10565 /* Stop pretending to be a post-reload pass. */
10566 reload_completed = 0;
10567 }
10568
10569 static bool
10570 aarch64_tls_referenced_p (rtx x)
10571 {
10572 if (!TARGET_HAVE_TLS)
10573 return false;
10574 subrtx_iterator::array_type array;
10575 FOR_EACH_SUBRTX (iter, array, x, ALL)
10576 {
10577 const_rtx x = *iter;
10578 if (SYMBOL_REF_P (x) && SYMBOL_REF_TLS_MODEL (x) != 0)
10579 return true;
10580 /* Don't recurse into UNSPEC_TLS looking for TLS symbols; these are
10581 TLS offsets, not real symbol references. */
10582 if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_TLS)
10583 iter.skip_subrtxes ();
10584 }
10585 return false;
10586 }
10587
10588
10589 static bool
10590 aarch64_cannot_force_const_mem (machine_mode mode ATTRIBUTE_UNUSED, rtx x)
10591 {
10592 if (GET_CODE (x) == HIGH)
10593 return true;
10594
10595 /* There's no way to calculate VL-based values using relocations. */
10596 subrtx_iterator::array_type array;
10597 HOST_WIDE_INT factor;
10598 FOR_EACH_SUBRTX (iter, array, x, ALL)
10599 if (GET_CODE (*iter) == CONST_POLY_INT
10600 || aarch64_sme_vq_unspec_p (x, &factor))
10601 return true;
10602
10603 poly_int64 offset;
10604 rtx base = strip_offset_and_salt (x, &offset);
10605 if (SYMBOL_REF_P (base) || LABEL_REF_P (base))
10606 {
10607 /* We checked for POLY_INT_CST offsets above. */
10608 if (aarch64_classify_symbol (base, offset.to_constant ())
10609 != SYMBOL_FORCE_TO_MEM)
10610 return true;
10611 else
10612 /* Avoid generating a 64-bit relocation in ILP32; leave
10613 to aarch64_expand_mov_immediate to handle it properly. */
10614 return mode != ptr_mode;
10615 }
10616
10617 return aarch64_tls_referenced_p (x);
10618 }
10619
10620 /* Implement TARGET_CASE_VALUES_THRESHOLD.
10621 The expansion for a table switch is quite expensive due to the number
10622 of instructions, the table lookup and hard to predict indirect jump.
10623 When optimizing for speed, and -O3 enabled, use the per-core tuning if
10624 set, otherwise use tables for >= 11 cases as a tradeoff between size and
10625 performance. When optimizing for size, use 8 for smallest codesize. */
10626
10627 static unsigned int
10628 aarch64_case_values_threshold (void)
10629 {
10630 /* Use the specified limit for the number of cases before using jump
10631 tables at higher optimization levels. */
10632 if (optimize > 2
10633 && aarch64_tune_params.max_case_values != 0)
10634 return aarch64_tune_params.max_case_values;
10635 else
10636 return optimize_size ? 8 : 11;
10637 }
10638
10639 /* Return true if register REGNO is a valid index register.
10640 STRICT_P is true if REG_OK_STRICT is in effect. */
10641
10642 bool
10643 aarch64_regno_ok_for_index_p (int regno, bool strict_p)
10644 {
10645 if (!HARD_REGISTER_NUM_P (regno))
10646 {
10647 if (!strict_p)
10648 return true;
10649
10650 if (!reg_renumber)
10651 return false;
10652
10653 regno = reg_renumber[regno];
10654 }
10655 return GP_REGNUM_P (regno);
10656 }
10657
10658 /* Return true if register REGNO is a valid base register for mode MODE.
10659 STRICT_P is true if REG_OK_STRICT is in effect. */
10660
10661 bool
10662 aarch64_regno_ok_for_base_p (int regno, bool strict_p)
10663 {
10664 if (!HARD_REGISTER_NUM_P (regno))
10665 {
10666 if (!strict_p)
10667 return true;
10668
10669 if (!reg_renumber)
10670 return false;
10671
10672 regno = reg_renumber[regno];
10673 }
10674
10675 /* The fake registers will be eliminated to either the stack or
10676 hard frame pointer, both of which are usually valid base registers.
10677 Reload deals with the cases where the eliminated form isn't valid. */
10678 return (GP_REGNUM_P (regno)
10679 || regno == SP_REGNUM
10680 || regno == FRAME_POINTER_REGNUM
10681 || regno == ARG_POINTER_REGNUM);
10682 }
10683
10684 /* Return true if X is a valid base register for mode MODE.
10685 STRICT_P is true if REG_OK_STRICT is in effect. */
10686
10687 static bool
10688 aarch64_base_register_rtx_p (rtx x, bool strict_p)
10689 {
10690 if (!strict_p
10691 && SUBREG_P (x)
10692 && contains_reg_of_mode[GENERAL_REGS][GET_MODE (SUBREG_REG (x))])
10693 x = SUBREG_REG (x);
10694
10695 return (REG_P (x) && aarch64_regno_ok_for_base_p (REGNO (x), strict_p));
10696 }
10697
10698 /* Return true if address offset is a valid index. If it is, fill in INFO
10699 appropriately. STRICT_P is true if REG_OK_STRICT is in effect. */
10700
10701 static bool
10702 aarch64_classify_index (struct aarch64_address_info *info, rtx x,
10703 machine_mode mode, bool strict_p)
10704 {
10705 enum aarch64_address_type type;
10706 rtx index;
10707 int shift;
10708
10709 /* (reg:P) */
10710 if ((REG_P (x) || SUBREG_P (x))
10711 && GET_MODE (x) == Pmode)
10712 {
10713 type = ADDRESS_REG_REG;
10714 index = x;
10715 shift = 0;
10716 }
10717 /* (sign_extend:DI (reg:SI)) */
10718 else if ((GET_CODE (x) == SIGN_EXTEND
10719 || GET_CODE (x) == ZERO_EXTEND)
10720 && GET_MODE (x) == DImode
10721 && GET_MODE (XEXP (x, 0)) == SImode)
10722 {
10723 type = (GET_CODE (x) == SIGN_EXTEND)
10724 ? ADDRESS_REG_SXTW : ADDRESS_REG_UXTW;
10725 index = XEXP (x, 0);
10726 shift = 0;
10727 }
10728 /* (mult:DI (sign_extend:DI (reg:SI)) (const_int scale)) */
10729 else if (GET_CODE (x) == MULT
10730 && (GET_CODE (XEXP (x, 0)) == SIGN_EXTEND
10731 || GET_CODE (XEXP (x, 0)) == ZERO_EXTEND)
10732 && GET_MODE (XEXP (x, 0)) == DImode
10733 && GET_MODE (XEXP (XEXP (x, 0), 0)) == SImode
10734 && CONST_INT_P (XEXP (x, 1)))
10735 {
10736 type = (GET_CODE (XEXP (x, 0)) == SIGN_EXTEND)
10737 ? ADDRESS_REG_SXTW : ADDRESS_REG_UXTW;
10738 index = XEXP (XEXP (x, 0), 0);
10739 shift = exact_log2 (INTVAL (XEXP (x, 1)));
10740 }
10741 /* (ashift:DI (sign_extend:DI (reg:SI)) (const_int shift)) */
10742 else if (GET_CODE (x) == ASHIFT
10743 && (GET_CODE (XEXP (x, 0)) == SIGN_EXTEND
10744 || GET_CODE (XEXP (x, 0)) == ZERO_EXTEND)
10745 && GET_MODE (XEXP (x, 0)) == DImode
10746 && GET_MODE (XEXP (XEXP (x, 0), 0)) == SImode
10747 && CONST_INT_P (XEXP (x, 1)))
10748 {
10749 type = (GET_CODE (XEXP (x, 0)) == SIGN_EXTEND)
10750 ? ADDRESS_REG_SXTW : ADDRESS_REG_UXTW;
10751 index = XEXP (XEXP (x, 0), 0);
10752 shift = INTVAL (XEXP (x, 1));
10753 }
10754 /* (and:DI (mult:DI (reg:DI) (const_int scale))
10755 (const_int 0xffffffff<<shift)) */
10756 else if (GET_CODE (x) == AND
10757 && GET_MODE (x) == DImode
10758 && GET_CODE (XEXP (x, 0)) == MULT
10759 && GET_MODE (XEXP (XEXP (x, 0), 0)) == DImode
10760 && CONST_INT_P (XEXP (XEXP (x, 0), 1))
10761 && CONST_INT_P (XEXP (x, 1)))
10762 {
10763 type = ADDRESS_REG_UXTW;
10764 index = XEXP (XEXP (x, 0), 0);
10765 shift = exact_log2 (INTVAL (XEXP (XEXP (x, 0), 1)));
10766 /* Avoid undefined code dealing with shift being -1. */
10767 if (shift != -1
10768 && INTVAL (XEXP (x, 1)) != (HOST_WIDE_INT)0xffffffff << shift)
10769 shift = -1;
10770 }
10771 /* (and:DI (ashift:DI (reg:DI) (const_int shift))
10772 (const_int 0xffffffff<<shift)) */
10773 else if (GET_CODE (x) == AND
10774 && GET_MODE (x) == DImode
10775 && GET_CODE (XEXP (x, 0)) == ASHIFT
10776 && GET_MODE (XEXP (XEXP (x, 0), 0)) == DImode
10777 && CONST_INT_P (XEXP (XEXP (x, 0), 1))
10778 && CONST_INT_P (XEXP (x, 1)))
10779 {
10780 type = ADDRESS_REG_UXTW;
10781 index = XEXP (XEXP (x, 0), 0);
10782 shift = INTVAL (XEXP (XEXP (x, 0), 1));
10783 if (INTVAL (XEXP (x, 1)) != (HOST_WIDE_INT)0xffffffff << shift)
10784 shift = -1;
10785 }
10786 /* (mult:P (reg:P) (const_int scale)) */
10787 else if (GET_CODE (x) == MULT
10788 && GET_MODE (x) == Pmode
10789 && GET_MODE (XEXP (x, 0)) == Pmode
10790 && CONST_INT_P (XEXP (x, 1)))
10791 {
10792 type = ADDRESS_REG_REG;
10793 index = XEXP (x, 0);
10794 shift = exact_log2 (INTVAL (XEXP (x, 1)));
10795 }
10796 /* (ashift:P (reg:P) (const_int shift)) */
10797 else if (GET_CODE (x) == ASHIFT
10798 && GET_MODE (x) == Pmode
10799 && GET_MODE (XEXP (x, 0)) == Pmode
10800 && CONST_INT_P (XEXP (x, 1)))
10801 {
10802 type = ADDRESS_REG_REG;
10803 index = XEXP (x, 0);
10804 shift = INTVAL (XEXP (x, 1));
10805 }
10806 else
10807 return false;
10808
10809 if (!strict_p
10810 && SUBREG_P (index)
10811 && contains_reg_of_mode[GENERAL_REGS][GET_MODE (SUBREG_REG (index))])
10812 index = SUBREG_REG (index);
10813
10814 auto vec_flags = aarch64_classify_vector_memory_mode (mode);
10815 if (vec_flags & VEC_SVE_DATA)
10816 {
10817 if (type != ADDRESS_REG_REG
10818 || (1 << shift) != GET_MODE_UNIT_SIZE (mode))
10819 return false;
10820 }
10821 else
10822 {
10823 if (shift != 0
10824 && !(IN_RANGE (shift, 1, 3)
10825 && known_eq (1 << shift, GET_MODE_SIZE (mode))))
10826 return false;
10827 }
10828
10829 if (REG_P (index)
10830 && aarch64_regno_ok_for_index_p (REGNO (index), strict_p))
10831 {
10832 info->type = type;
10833 info->offset = index;
10834 info->shift = shift;
10835 return true;
10836 }
10837
10838 return false;
10839 }
10840
10841 /* Return true if MODE is one of the modes for which we
10842 support LDP/STP operations. */
10843
10844 static bool
10845 aarch64_mode_valid_for_sched_fusion_p (machine_mode mode)
10846 {
10847 return mode == SImode || mode == DImode
10848 || mode == SFmode || mode == DFmode
10849 || mode == SDmode || mode == DDmode
10850 || (aarch64_vector_mode_supported_p (mode)
10851 && (known_eq (GET_MODE_SIZE (mode), 8)
10852 || known_eq (GET_MODE_SIZE (mode), 16)));
10853 }
10854
10855 /* Return true if REGNO is a virtual pointer register, or an eliminable
10856 "soft" frame register. Like REGNO_PTR_FRAME_P except that we don't
10857 include stack_pointer or hard_frame_pointer. */
10858 static bool
10859 virt_or_elim_regno_p (unsigned regno)
10860 {
10861 return ((regno >= FIRST_VIRTUAL_REGISTER
10862 && regno <= LAST_VIRTUAL_POINTER_REGISTER)
10863 || regno == FRAME_POINTER_REGNUM
10864 || regno == ARG_POINTER_REGNUM);
10865 }
10866
10867 /* Return true if X is a valid address of type TYPE for machine mode MODE.
10868 If it is, fill in INFO appropriately. STRICT_P is true if
10869 REG_OK_STRICT is in effect. */
10870
10871 bool
10872 aarch64_classify_address (struct aarch64_address_info *info,
10873 rtx x, machine_mode mode, bool strict_p,
10874 aarch64_addr_query_type type)
10875 {
10876 enum rtx_code code = GET_CODE (x);
10877 rtx op0, op1;
10878 poly_int64 offset;
10879
10880 HOST_WIDE_INT const_size;
10881
10882 /* Whether a vector mode is partial doesn't affect address legitimacy.
10883 Partial vectors like VNx8QImode allow the same indexed addressing
10884 mode and MUL VL addressing mode as full vectors like VNx16QImode;
10885 in both cases, MUL VL counts multiples of GET_MODE_SIZE. */
10886 unsigned int vec_flags = aarch64_classify_vector_memory_mode (mode);
10887 vec_flags &= ~VEC_PARTIAL;
10888
10889 /* We use load/store pair for all large int mode load/stores.
10890 TI/TF/TDmode may also use a load/store pair. */
10891 bool advsimd_struct_p = (vec_flags == (VEC_ADVSIMD | VEC_STRUCT));
10892 bool load_store_pair_p = (type == ADDR_QUERY_LDP_STP
10893 || type == ADDR_QUERY_LDP_STP_N
10894 || mode == TImode
10895 || mode == TFmode
10896 || mode == TDmode
10897 || advsimd_struct_p);
10898 /* If we are dealing with ADDR_QUERY_LDP_STP_N that means the incoming mode
10899 corresponds to the actual size of the memory being loaded/stored and the
10900 mode of the corresponding addressing mode is half of that. */
10901 if (type == ADDR_QUERY_LDP_STP_N)
10902 {
10903 if (known_eq (GET_MODE_SIZE (mode), 32))
10904 mode = V16QImode;
10905 else if (known_eq (GET_MODE_SIZE (mode), 16))
10906 mode = DFmode;
10907 else if (known_eq (GET_MODE_SIZE (mode), 8))
10908 mode = SFmode;
10909 else
10910 return false;
10911
10912 /* This isn't really an Advanced SIMD struct mode, but a mode
10913 used to represent the complete mem in a load/store pair. */
10914 advsimd_struct_p = false;
10915 }
10916
10917 bool allow_reg_index_p = (!load_store_pair_p
10918 && ((vec_flags == 0
10919 && known_lt (GET_MODE_SIZE (mode), 16))
10920 || vec_flags == VEC_ADVSIMD
10921 || vec_flags & VEC_SVE_DATA));
10922
10923 /* For SVE, only accept [Rn], [Rn, #offset, MUL VL] and [Rn, Rm, LSL #shift].
10924 The latter is not valid for SVE predicates, and that's rejected through
10925 allow_reg_index_p above. */
10926 if ((vec_flags & (VEC_SVE_DATA | VEC_SVE_PRED)) != 0
10927 && (code != REG && code != PLUS))
10928 return false;
10929
10930 gcc_checking_assert (GET_MODE (x) == VOIDmode
10931 || SCALAR_INT_MODE_P (GET_MODE (x)));
10932
10933 switch (code)
10934 {
10935 case REG:
10936 case SUBREG:
10937 info->type = ADDRESS_REG_IMM;
10938 info->base = x;
10939 info->offset = const0_rtx;
10940 info->const_offset = 0;
10941 return aarch64_base_register_rtx_p (x, strict_p);
10942
10943 case PLUS:
10944 op0 = XEXP (x, 0);
10945 op1 = XEXP (x, 1);
10946
10947 if (! strict_p
10948 && REG_P (op0)
10949 && virt_or_elim_regno_p (REGNO (op0))
10950 && poly_int_rtx_p (op1, &offset))
10951 {
10952 info->type = ADDRESS_REG_IMM;
10953 info->base = op0;
10954 info->offset = op1;
10955 info->const_offset = offset;
10956
10957 return true;
10958 }
10959
10960 if (maybe_ne (GET_MODE_SIZE (mode), 0)
10961 && aarch64_base_register_rtx_p (op0, strict_p)
10962 && poly_int_rtx_p (op1, &offset))
10963 {
10964 info->type = ADDRESS_REG_IMM;
10965 info->base = op0;
10966 info->offset = op1;
10967 info->const_offset = offset;
10968
10969 /* TImode, TFmode and TDmode values are allowed in both pairs of X
10970 registers and individual Q registers. The available
10971 address modes are:
10972 X,X: 7-bit signed scaled offset
10973 Q: 9-bit signed offset
10974 We conservatively require an offset representable in either mode.
10975 When performing the check for pairs of X registers i.e. LDP/STP
10976 pass down DImode since that is the natural size of the LDP/STP
10977 instruction memory accesses. */
10978 if (mode == TImode || mode == TFmode || mode == TDmode)
10979 return (aarch64_offset_7bit_signed_scaled_p (DImode, offset)
10980 && (aarch64_offset_9bit_signed_unscaled_p (mode, offset)
10981 || offset_12bit_unsigned_scaled_p (mode, offset)));
10982
10983 if (mode == V8DImode)
10984 return (aarch64_offset_7bit_signed_scaled_p (DImode, offset)
10985 && aarch64_offset_7bit_signed_scaled_p (DImode, offset + 48));
10986
10987 /* A 7bit offset check because OImode will emit a ldp/stp
10988 instruction (only !TARGET_SIMD or big endian will get here).
10989 For ldp/stp instructions, the offset is scaled for the size of a
10990 single element of the pair. */
10991 if (aarch64_advsimd_partial_struct_mode_p (mode)
10992 && known_eq (GET_MODE_SIZE (mode), 16))
10993 return aarch64_offset_7bit_signed_scaled_p (DImode, offset);
10994 if (aarch64_advsimd_full_struct_mode_p (mode)
10995 && known_eq (GET_MODE_SIZE (mode), 32))
10996 return aarch64_offset_7bit_signed_scaled_p (TImode, offset);
10997
10998 /* Three 9/12 bit offsets checks because CImode will emit three
10999 ldr/str instructions (only !TARGET_SIMD or big endian will
11000 get here). */
11001 if (aarch64_advsimd_partial_struct_mode_p (mode)
11002 && known_eq (GET_MODE_SIZE (mode), 24))
11003 return (aarch64_offset_7bit_signed_scaled_p (DImode, offset)
11004 && (aarch64_offset_9bit_signed_unscaled_p (DImode,
11005 offset + 16)
11006 || offset_12bit_unsigned_scaled_p (DImode,
11007 offset + 16)));
11008 if (aarch64_advsimd_full_struct_mode_p (mode)
11009 && known_eq (GET_MODE_SIZE (mode), 48))
11010 return (aarch64_offset_7bit_signed_scaled_p (TImode, offset)
11011 && (aarch64_offset_9bit_signed_unscaled_p (TImode,
11012 offset + 32)
11013 || offset_12bit_unsigned_scaled_p (TImode,
11014 offset + 32)));
11015
11016 /* Two 7bit offsets checks because XImode will emit two ldp/stp
11017 instructions (only big endian will get here). */
11018 if (aarch64_advsimd_partial_struct_mode_p (mode)
11019 && known_eq (GET_MODE_SIZE (mode), 32))
11020 return (aarch64_offset_7bit_signed_scaled_p (DImode, offset)
11021 && aarch64_offset_7bit_signed_scaled_p (DImode,
11022 offset + 16));
11023 if (aarch64_advsimd_full_struct_mode_p (mode)
11024 && known_eq (GET_MODE_SIZE (mode), 64))
11025 return (aarch64_offset_7bit_signed_scaled_p (TImode, offset)
11026 && aarch64_offset_7bit_signed_scaled_p (TImode,
11027 offset + 32));
11028
11029 /* Make "m" use the LD1 offset range for SVE data modes, so
11030 that pre-RTL optimizers like ivopts will work to that
11031 instead of the wider LDR/STR range. */
11032 if (vec_flags == VEC_SVE_DATA)
11033 return (type == ADDR_QUERY_M
11034 ? offset_4bit_signed_scaled_p (mode, offset)
11035 : offset_9bit_signed_scaled_p (mode, offset));
11036
11037 if (vec_flags == (VEC_SVE_DATA | VEC_STRUCT))
11038 {
11039 poly_int64 end_offset = (offset
11040 + GET_MODE_SIZE (mode)
11041 - BYTES_PER_SVE_VECTOR);
11042 return (type == ADDR_QUERY_M
11043 ? offset_4bit_signed_scaled_p (mode, offset)
11044 : (offset_9bit_signed_scaled_p (SVE_BYTE_MODE, offset)
11045 && offset_9bit_signed_scaled_p (SVE_BYTE_MODE,
11046 end_offset)));
11047 }
11048
11049 if (vec_flags == VEC_SVE_PRED)
11050 return offset_9bit_signed_scaled_p (mode, offset);
11051
11052 if (vec_flags == (VEC_SVE_PRED | VEC_STRUCT))
11053 {
11054 poly_int64 end_offset = (offset
11055 + GET_MODE_SIZE (mode)
11056 - BYTES_PER_SVE_PRED);
11057 return (offset_9bit_signed_scaled_p (VNx16BImode, end_offset)
11058 && offset_9bit_signed_scaled_p (VNx16BImode, offset));
11059 }
11060
11061 if (load_store_pair_p)
11062 return ((known_eq (GET_MODE_SIZE (mode), 4)
11063 || known_eq (GET_MODE_SIZE (mode), 8)
11064 || known_eq (GET_MODE_SIZE (mode), 16))
11065 && aarch64_offset_7bit_signed_scaled_p (mode, offset));
11066 else
11067 return (aarch64_offset_9bit_signed_unscaled_p (mode, offset)
11068 || offset_12bit_unsigned_scaled_p (mode, offset));
11069 }
11070
11071 if (allow_reg_index_p)
11072 {
11073 /* Look for base + (scaled/extended) index register. */
11074 if (aarch64_base_register_rtx_p (op0, strict_p)
11075 && aarch64_classify_index (info, op1, mode, strict_p))
11076 {
11077 info->base = op0;
11078 return true;
11079 }
11080 if (aarch64_base_register_rtx_p (op1, strict_p)
11081 && aarch64_classify_index (info, op0, mode, strict_p))
11082 {
11083 info->base = op1;
11084 return true;
11085 }
11086 }
11087
11088 return false;
11089
11090 case POST_INC:
11091 case POST_DEC:
11092 case PRE_INC:
11093 case PRE_DEC:
11094 info->type = ADDRESS_REG_WB;
11095 info->base = XEXP (x, 0);
11096 info->offset = NULL_RTX;
11097 return aarch64_base_register_rtx_p (info->base, strict_p);
11098
11099 case POST_MODIFY:
11100 case PRE_MODIFY:
11101 info->type = ADDRESS_REG_WB;
11102 info->base = XEXP (x, 0);
11103 if (GET_CODE (XEXP (x, 1)) == PLUS
11104 && poly_int_rtx_p (XEXP (XEXP (x, 1), 1), &offset)
11105 && rtx_equal_p (XEXP (XEXP (x, 1), 0), info->base)
11106 && aarch64_base_register_rtx_p (info->base, strict_p))
11107 {
11108 info->offset = XEXP (XEXP (x, 1), 1);
11109 info->const_offset = offset;
11110
11111 /* TImode, TFmode and TDmode values are allowed in both pairs of X
11112 registers and individual Q registers. The available
11113 address modes are:
11114 X,X: 7-bit signed scaled offset
11115 Q: 9-bit signed offset
11116 We conservatively require an offset representable in either mode.
11117 */
11118 if (mode == TImode || mode == TFmode || mode == TDmode)
11119 return (aarch64_offset_7bit_signed_scaled_p (mode, offset)
11120 && aarch64_offset_9bit_signed_unscaled_p (mode, offset));
11121
11122 if (load_store_pair_p)
11123 return ((known_eq (GET_MODE_SIZE (mode), 4)
11124 || known_eq (GET_MODE_SIZE (mode), 8)
11125 || known_eq (GET_MODE_SIZE (mode), 16))
11126 && aarch64_offset_7bit_signed_scaled_p (mode, offset));
11127 else
11128 return aarch64_offset_9bit_signed_unscaled_p (mode, offset);
11129 }
11130 return false;
11131
11132 case CONST:
11133 case SYMBOL_REF:
11134 case LABEL_REF:
11135 /* load literal: pc-relative constant pool entry. Only supported
11136 for SI mode or larger. */
11137 info->type = ADDRESS_SYMBOLIC;
11138
11139 if (!load_store_pair_p
11140 && GET_MODE_SIZE (mode).is_constant (&const_size)
11141 && const_size >= 4)
11142 {
11143 poly_int64 offset;
11144 rtx sym = strip_offset_and_salt (x, &offset);
11145 return ((LABEL_REF_P (sym)
11146 || (SYMBOL_REF_P (sym)
11147 && CONSTANT_POOL_ADDRESS_P (sym)
11148 && aarch64_pcrelative_literal_loads)));
11149 }
11150 return false;
11151
11152 case LO_SUM:
11153 info->type = ADDRESS_LO_SUM;
11154 info->base = XEXP (x, 0);
11155 info->offset = XEXP (x, 1);
11156 if (allow_reg_index_p
11157 && aarch64_base_register_rtx_p (info->base, strict_p))
11158 {
11159 poly_int64 offset;
11160 HOST_WIDE_INT const_offset;
11161 rtx sym = strip_offset_and_salt (info->offset, &offset);
11162 if (SYMBOL_REF_P (sym)
11163 && offset.is_constant (&const_offset)
11164 && (aarch64_classify_symbol (sym, const_offset)
11165 == SYMBOL_SMALL_ABSOLUTE))
11166 {
11167 /* The symbol and offset must be aligned to the access size. */
11168 unsigned int align;
11169
11170 if (CONSTANT_POOL_ADDRESS_P (sym))
11171 align = GET_MODE_ALIGNMENT (get_pool_mode (sym));
11172 else if (TREE_CONSTANT_POOL_ADDRESS_P (sym))
11173 {
11174 tree exp = SYMBOL_REF_DECL (sym);
11175 align = TYPE_ALIGN (TREE_TYPE (exp));
11176 align = aarch64_constant_alignment (exp, align);
11177 }
11178 else if (SYMBOL_REF_DECL (sym))
11179 align = DECL_ALIGN (SYMBOL_REF_DECL (sym));
11180 else if (SYMBOL_REF_HAS_BLOCK_INFO_P (sym)
11181 && SYMBOL_REF_BLOCK (sym) != NULL)
11182 align = SYMBOL_REF_BLOCK (sym)->alignment;
11183 else
11184 align = BITS_PER_UNIT;
11185
11186 poly_int64 ref_size = GET_MODE_SIZE (mode);
11187 if (known_eq (ref_size, 0))
11188 ref_size = GET_MODE_SIZE (DImode);
11189
11190 return (multiple_p (const_offset, ref_size)
11191 && multiple_p (align / BITS_PER_UNIT, ref_size));
11192 }
11193 }
11194 return false;
11195
11196 default:
11197 return false;
11198 }
11199 }
11200
11201 /* Return true if the address X is valid for a PRFM instruction.
11202 STRICT_P is true if we should do strict checking with
11203 aarch64_classify_address. */
11204
11205 bool
11206 aarch64_address_valid_for_prefetch_p (rtx x, bool strict_p)
11207 {
11208 struct aarch64_address_info addr;
11209
11210 /* PRFM accepts the same addresses as DImode... */
11211 bool res = aarch64_classify_address (&addr, x, DImode, strict_p);
11212 if (!res)
11213 return false;
11214
11215 /* ... except writeback forms. */
11216 return addr.type != ADDRESS_REG_WB;
11217 }
11218
11219 bool
11220 aarch64_symbolic_address_p (rtx x)
11221 {
11222 poly_int64 offset;
11223 x = strip_offset_and_salt (x, &offset);
11224 return SYMBOL_REF_P (x) || LABEL_REF_P (x);
11225 }
11226
11227 /* Classify the base of symbolic expression X. */
11228
11229 enum aarch64_symbol_type
11230 aarch64_classify_symbolic_expression (rtx x)
11231 {
11232 rtx offset;
11233
11234 split_const (x, &x, &offset);
11235 return aarch64_classify_symbol (x, INTVAL (offset));
11236 }
11237
11238
11239 /* Return TRUE if X is a legitimate address for accessing memory in
11240 mode MODE. */
11241 static bool
11242 aarch64_legitimate_address_hook_p (machine_mode mode, rtx x, bool strict_p,
11243 code_helper = ERROR_MARK)
11244 {
11245 struct aarch64_address_info addr;
11246
11247 return aarch64_classify_address (&addr, x, mode, strict_p);
11248 }
11249
11250 /* Return TRUE if X is a legitimate address of type TYPE for accessing
11251 memory in mode MODE. STRICT_P is true if REG_OK_STRICT is in effect. */
11252 bool
11253 aarch64_legitimate_address_p (machine_mode mode, rtx x, bool strict_p,
11254 aarch64_addr_query_type type)
11255 {
11256 struct aarch64_address_info addr;
11257
11258 return aarch64_classify_address (&addr, x, mode, strict_p, type);
11259 }
11260
11261 /* Implement TARGET_LEGITIMIZE_ADDRESS_DISPLACEMENT. */
11262
11263 static bool
11264 aarch64_legitimize_address_displacement (rtx *offset1, rtx *offset2,
11265 poly_int64 orig_offset,
11266 machine_mode mode)
11267 {
11268 HOST_WIDE_INT size;
11269 if (GET_MODE_SIZE (mode).is_constant (&size))
11270 {
11271 HOST_WIDE_INT const_offset, second_offset;
11272
11273 /* A general SVE offset is A * VQ + B. Remove the A component from
11274 coefficient 0 in order to get the constant B. */
11275 const_offset = orig_offset.coeffs[0] - orig_offset.coeffs[1];
11276
11277 /* Split an out-of-range address displacement into a base and
11278 offset. Use 4KB range for 1- and 2-byte accesses and a 16KB
11279 range otherwise to increase opportunities for sharing the base
11280 address of different sizes. Unaligned accesses use the signed
11281 9-bit range, TImode/TFmode/TDmode use the intersection of signed
11282 scaled 7-bit and signed 9-bit offset. */
11283 if (mode == TImode || mode == TFmode || mode == TDmode)
11284 second_offset = ((const_offset + 0x100) & 0x1f8) - 0x100;
11285 else if ((const_offset & (size - 1)) != 0)
11286 second_offset = ((const_offset + 0x100) & 0x1ff) - 0x100;
11287 else
11288 second_offset = const_offset & (size < 4 ? 0xfff : 0x3ffc);
11289
11290 if (second_offset == 0 || known_eq (orig_offset, second_offset))
11291 return false;
11292
11293 /* Split the offset into second_offset and the rest. */
11294 *offset1 = gen_int_mode (orig_offset - second_offset, Pmode);
11295 *offset2 = gen_int_mode (second_offset, Pmode);
11296 return true;
11297 }
11298 else
11299 {
11300 /* Get the mode we should use as the basis of the range. For structure
11301 modes this is the mode of one vector. */
11302 unsigned int vec_flags = aarch64_classify_vector_mode (mode);
11303 machine_mode step_mode
11304 = (vec_flags & VEC_STRUCT) != 0 ? SVE_BYTE_MODE : mode;
11305
11306 /* Get the "mul vl" multiplier we'd like to use. */
11307 HOST_WIDE_INT factor = GET_MODE_SIZE (step_mode).coeffs[1];
11308 HOST_WIDE_INT vnum = orig_offset.coeffs[1] / factor;
11309 if (vec_flags & VEC_SVE_DATA)
11310 /* LDR supports a 9-bit range, but the move patterns for
11311 structure modes require all vectors to be in range of the
11312 same base. The simplest way of accomodating that while still
11313 promoting reuse of anchor points between different modes is
11314 to use an 8-bit range unconditionally. */
11315 vnum = ((vnum + 128) & 255) - 128;
11316 else
11317 /* Predicates are only handled singly, so we might as well use
11318 the full range. */
11319 vnum = ((vnum + 256) & 511) - 256;
11320 if (vnum == 0)
11321 return false;
11322
11323 /* Convert the "mul vl" multiplier into a byte offset. */
11324 poly_int64 second_offset = GET_MODE_SIZE (step_mode) * vnum;
11325 if (known_eq (second_offset, orig_offset))
11326 return false;
11327
11328 /* Split the offset into second_offset and the rest. */
11329 *offset1 = gen_int_mode (orig_offset - second_offset, Pmode);
11330 *offset2 = gen_int_mode (second_offset, Pmode);
11331 return true;
11332 }
11333 }
11334
11335 /* Return the binary representation of floating point constant VALUE in INTVAL.
11336 If the value cannot be converted, return false without setting INTVAL.
11337 The conversion is done in the given MODE. */
11338 bool
11339 aarch64_reinterpret_float_as_int (rtx value, unsigned HOST_WIDE_INT *intval)
11340 {
11341
11342 /* We make a general exception for 0. */
11343 if (aarch64_float_const_zero_rtx_p (value))
11344 {
11345 *intval = 0;
11346 return true;
11347 }
11348
11349 scalar_float_mode mode;
11350 if (!CONST_DOUBLE_P (value)
11351 || !is_a <scalar_float_mode> (GET_MODE (value), &mode)
11352 || GET_MODE_BITSIZE (mode) > HOST_BITS_PER_WIDE_INT
11353 /* Only support up to DF mode. */
11354 || GET_MODE_BITSIZE (mode) > GET_MODE_BITSIZE (DFmode))
11355 return false;
11356
11357 unsigned HOST_WIDE_INT ival = 0;
11358
11359 long res[2];
11360 real_to_target (res,
11361 CONST_DOUBLE_REAL_VALUE (value),
11362 REAL_MODE_FORMAT (mode));
11363
11364 if (mode == DFmode || mode == DDmode)
11365 {
11366 int order = BYTES_BIG_ENDIAN ? 1 : 0;
11367 ival = zext_hwi (res[order], 32);
11368 ival |= (zext_hwi (res[1 - order], 32) << 32);
11369 }
11370 else
11371 ival = zext_hwi (res[0], 32);
11372
11373 *intval = ival;
11374 return true;
11375 }
11376
11377 /* Return TRUE if rtx X is an immediate constant that can be moved using a
11378 single MOV(+MOVK) followed by an FMOV. */
11379 bool
11380 aarch64_float_const_rtx_p (rtx x)
11381 {
11382 machine_mode mode = GET_MODE (x);
11383 if (mode == VOIDmode)
11384 return false;
11385
11386 /* Determine whether it's cheaper to write float constants as
11387 mov/movk pairs over ldr/adrp pairs. */
11388 unsigned HOST_WIDE_INT ival;
11389
11390 if (CONST_DOUBLE_P (x)
11391 && SCALAR_FLOAT_MODE_P (mode)
11392 && aarch64_reinterpret_float_as_int (x, &ival))
11393 {
11394 machine_mode imode = known_eq (GET_MODE_SIZE (mode), 8) ? DImode : SImode;
11395 int num_instr = aarch64_internal_mov_immediate
11396 (NULL_RTX, gen_int_mode (ival, imode), false, imode);
11397 return num_instr < 3;
11398 }
11399
11400 return false;
11401 }
11402
11403 /* Return TRUE if rtx X is immediate constant 0.0 (but not in Decimal
11404 Floating Point). */
11405 bool
11406 aarch64_float_const_zero_rtx_p (rtx x)
11407 {
11408 /* 0.0 in Decimal Floating Point cannot be represented by #0 or
11409 zr as our callers expect, so no need to check the actual
11410 value if X is of Decimal Floating Point type. */
11411 if (GET_MODE_CLASS (GET_MODE (x)) == MODE_DECIMAL_FLOAT)
11412 return false;
11413
11414 if (REAL_VALUE_MINUS_ZERO (*CONST_DOUBLE_REAL_VALUE (x)))
11415 return !HONOR_SIGNED_ZEROS (GET_MODE (x));
11416 return real_equal (CONST_DOUBLE_REAL_VALUE (x), &dconst0);
11417 }
11418
11419 /* Return true if X is any kind of constant zero rtx. */
11420
11421 bool
11422 aarch64_const_zero_rtx_p (rtx x)
11423 {
11424 return (x == CONST0_RTX (GET_MODE (x))
11425 || (CONST_DOUBLE_P (x) && aarch64_float_const_zero_rtx_p (x)));
11426 }
11427
11428 /* Return TRUE if rtx X is immediate constant that fits in a single
11429 MOVI immediate operation. */
11430 bool
11431 aarch64_can_const_movi_rtx_p (rtx x, machine_mode mode)
11432 {
11433 if (!TARGET_SIMD)
11434 return false;
11435
11436 machine_mode vmode;
11437 scalar_int_mode imode;
11438 unsigned HOST_WIDE_INT ival;
11439
11440 if (CONST_DOUBLE_P (x)
11441 && SCALAR_FLOAT_MODE_P (mode))
11442 {
11443 if (!aarch64_reinterpret_float_as_int (x, &ival))
11444 return false;
11445
11446 /* We make a general exception for 0. */
11447 if (aarch64_float_const_zero_rtx_p (x))
11448 return true;
11449
11450 imode = int_mode_for_mode (mode).require ();
11451 }
11452 else if (CONST_INT_P (x)
11453 && is_a <scalar_int_mode> (mode, &imode))
11454 ival = INTVAL (x);
11455 else
11456 return false;
11457
11458 /* use a 64 bit mode for everything except for DI/DF/DD mode, where we use
11459 a 128 bit vector mode. */
11460 int width = GET_MODE_BITSIZE (imode) == 64 ? 128 : 64;
11461
11462 vmode = aarch64_simd_container_mode (imode, width);
11463 rtx v_op = aarch64_simd_gen_const_vector_dup (vmode, ival);
11464
11465 return aarch64_simd_valid_mov_imm (v_op);
11466 }
11467
11468 /* Return TRUE if DST and SRC with mode MODE is a valid fp move. */
11469 bool
11470 aarch64_valid_fp_move (rtx dst, rtx src, machine_mode mode)
11471 {
11472 if (!TARGET_FLOAT)
11473 return false;
11474
11475 if (aarch64_reg_or_fp_zero (src, mode))
11476 return true;
11477
11478 if (!register_operand (dst, mode))
11479 return false;
11480
11481 if (MEM_P (src))
11482 return true;
11483
11484 if (aarch64_can_const_movi_rtx_p (src, mode)
11485 || aarch64_float_const_representable_p (src)
11486 || aarch64_float_const_zero_rtx_p (src))
11487 return true;
11488
11489 /* Block FP immediates which are split during expand. */
11490 if (aarch64_float_const_rtx_p (src))
11491 return false;
11492
11493 return can_create_pseudo_p ();
11494 }
11495
11496 /* Return the fixed registers used for condition codes. */
11497
11498 static bool
11499 aarch64_fixed_condition_code_regs (unsigned int *p1, unsigned int *p2)
11500 {
11501 *p1 = CC_REGNUM;
11502 *p2 = INVALID_REGNUM;
11503 return true;
11504 }
11505
11506 /* Return a fresh memory reference to the current function's TPIDR2 block,
11507 creating a block if necessary. */
11508
11509 static rtx
11510 aarch64_get_tpidr2_block ()
11511 {
11512 if (!cfun->machine->tpidr2_block)
11513 /* The TPIDR2 block is 16 bytes in size and must be aligned to a 128-bit
11514 boundary. */
11515 cfun->machine->tpidr2_block = assign_stack_local (V16QImode, 16, 128);
11516 return copy_rtx (cfun->machine->tpidr2_block);
11517 }
11518
11519 /* Return a fresh register that points to the current function's
11520 TPIDR2 block, creating a block if necessary. */
11521
11522 static rtx
11523 aarch64_get_tpidr2_ptr ()
11524 {
11525 rtx block = aarch64_get_tpidr2_block ();
11526 return force_reg (Pmode, XEXP (block, 0));
11527 }
11528
11529 /* Emit instructions to allocate a ZA lazy save buffer and initialize the
11530 current function's TPIDR2 block. */
11531
11532 static void
11533 aarch64_init_tpidr2_block ()
11534 {
11535 rtx block = aarch64_get_tpidr2_block ();
11536
11537 /* The ZA save buffer is SVL.B*SVL.B bytes in size. */
11538 rtx svl_bytes = aarch64_sme_vq_immediate (Pmode, 16, AARCH64_ISA_MODE);
11539 rtx svl_bytes_reg = force_reg (DImode, svl_bytes);
11540 rtx za_size = expand_simple_binop (Pmode, MULT, svl_bytes_reg,
11541 svl_bytes_reg, NULL, 0, OPTAB_LIB_WIDEN);
11542 rtx za_save_buffer = allocate_dynamic_stack_space (za_size, 128,
11543 BITS_PER_UNIT, -1, true);
11544 za_save_buffer = force_reg (Pmode, za_save_buffer);
11545 cfun->machine->za_save_buffer = za_save_buffer;
11546
11547 /* The first word of the block points to the save buffer and the second
11548 word is the number of ZA slices to save. */
11549 rtx block_0 = adjust_address (block, DImode, 0);
11550 emit_insn (aarch64_gen_store_pair (block_0, za_save_buffer, svl_bytes_reg));
11551
11552 if (!memory_operand (block, V16QImode))
11553 block = replace_equiv_address (block, force_reg (Pmode, XEXP (block, 0)));
11554 emit_insn (gen_aarch64_setup_local_tpidr2 (block));
11555 }
11556
11557 /* Restore the contents of ZA from the lazy save buffer, given that
11558 register TPIDR2_BLOCK points to the current function's TPIDR2 block.
11559 PSTATE.ZA is known to be 0 and TPIDR2_EL0 is known to be null. */
11560
11561 void
11562 aarch64_restore_za (rtx tpidr2_block)
11563 {
11564 emit_insn (gen_aarch64_smstart_za ());
11565 if (REGNO (tpidr2_block) != R0_REGNUM)
11566 emit_move_insn (gen_rtx_REG (Pmode, R0_REGNUM), tpidr2_block);
11567 emit_insn (gen_aarch64_tpidr2_restore ());
11568 }
11569
11570 /* Return the ZT0 save buffer, creating one if necessary. */
11571
11572 static rtx
11573 aarch64_get_zt0_save_buffer ()
11574 {
11575 if (!cfun->machine->zt0_save_buffer)
11576 cfun->machine->zt0_save_buffer = assign_stack_local (V8DImode, 64, 128);
11577 return cfun->machine->zt0_save_buffer;
11578 }
11579
11580 /* Save ZT0 to the current function's save buffer. */
11581
11582 static void
11583 aarch64_save_zt0 ()
11584 {
11585 rtx mem = aarch64_get_zt0_save_buffer ();
11586 mem = replace_equiv_address (mem, force_reg (Pmode, XEXP (mem, 0)));
11587 emit_insn (gen_aarch64_sme_str_zt0 (mem));
11588 }
11589
11590 /* Restore ZT0 from the current function's save buffer. FROM_LAZY_SAVE_P
11591 is true if the load is happening after a call to a private-ZA function,
11592 false if it can be treated as a normal load. */
11593
11594 static void
11595 aarch64_restore_zt0 (bool from_lazy_save_p)
11596 {
11597 rtx mem = aarch64_get_zt0_save_buffer ();
11598 mem = replace_equiv_address (mem, force_reg (Pmode, XEXP (mem, 0)));
11599 emit_insn (from_lazy_save_p
11600 ? gen_aarch64_restore_zt0 (mem)
11601 : gen_aarch64_sme_ldr_zt0 (mem));
11602 }
11603
11604 /* Implement TARGET_START_CALL_ARGS. */
11605
11606 static void
11607 aarch64_start_call_args (cumulative_args_t ca_v)
11608 {
11609 CUMULATIVE_ARGS *ca = get_cumulative_args (ca_v);
11610
11611 if (!TARGET_SME && (ca->isa_mode & AARCH64_ISA_MODE_SM_ON))
11612 {
11613 error ("calling a streaming function requires the ISA extension %qs",
11614 "sme");
11615 inform (input_location, "you can enable %qs using the command-line"
11616 " option %<-march%>, or by using the %<target%>"
11617 " attribute or pragma", "sme");
11618 }
11619
11620 if ((ca->shared_za_flags & (AARCH64_STATE_IN | AARCH64_STATE_OUT))
11621 && !aarch64_cfun_has_state ("za"))
11622 error ("call to a function that shares %qs state from a function"
11623 " that has no %qs state", "za", "za");
11624 else if ((ca->shared_zt0_flags & (AARCH64_STATE_IN | AARCH64_STATE_OUT))
11625 && !aarch64_cfun_has_state ("zt0"))
11626 error ("call to a function that shares %qs state from a function"
11627 " that has no %qs state", "zt0", "zt0");
11628 else if (!TARGET_ZA && (ca->isa_mode & AARCH64_ISA_MODE_ZA_ON))
11629 error ("call to a function that shares SME state from a function"
11630 " that has no SME state");
11631
11632 /* If this is a call to a private ZA function, emit a marker to
11633 indicate where any necessary set-up code could be inserted.
11634 The code itself is inserted by the mode-switching pass. */
11635 if (TARGET_ZA && !(ca->isa_mode & AARCH64_ISA_MODE_ZA_ON))
11636 emit_insn (gen_aarch64_start_private_za_call ());
11637
11638 /* If this is a call to a shared-ZA function that doesn't share ZT0,
11639 save and restore ZT0 around the call. */
11640 if (aarch64_cfun_has_state ("zt0")
11641 && (ca->isa_mode & AARCH64_ISA_MODE_ZA_ON)
11642 && ca->shared_zt0_flags == 0)
11643 aarch64_save_zt0 ();
11644 }
11645
11646 /* This function is used by the call expanders of the machine description.
11647 RESULT is the register in which the result is returned. It's NULL for
11648 "call" and "sibcall".
11649 MEM is the location of the function call.
11650 COOKIE is either:
11651 - a const_int that gives the argument to the call's UNSPEC_CALLEE_ABI.
11652 - a PARALLEL that contains such a const_int as its first element.
11653 The second element is a PARALLEL that lists all the argument
11654 registers that need to be saved and restored around a change
11655 in PSTATE.SM, or const0_rtx if no such switch is needed.
11656 The third and fourth elements are const_ints that contain the
11657 sharing flags for ZA and ZT0 respectively.
11658 SIBCALL indicates whether this function call is normal call or sibling call.
11659 It will generate different pattern accordingly. */
11660
11661 void
11662 aarch64_expand_call (rtx result, rtx mem, rtx cookie, bool sibcall)
11663 {
11664 rtx call, callee, tmp;
11665 rtvec vec;
11666 machine_mode mode;
11667
11668 rtx callee_abi = cookie;
11669 rtx sme_mode_switch_args = const0_rtx;
11670 unsigned int shared_za_flags = 0;
11671 unsigned int shared_zt0_flags = 0;
11672 if (GET_CODE (cookie) == PARALLEL)
11673 {
11674 callee_abi = XVECEXP (cookie, 0, 0);
11675 sme_mode_switch_args = XVECEXP (cookie, 0, 1);
11676 shared_za_flags = INTVAL (XVECEXP (cookie, 0, 2));
11677 shared_zt0_flags = INTVAL (XVECEXP (cookie, 0, 3));
11678 }
11679
11680 gcc_assert (CONST_INT_P (callee_abi));
11681 auto callee_isa_mode = aarch64_callee_isa_mode (callee_abi);
11682
11683 if (aarch64_cfun_has_state ("za")
11684 && (callee_isa_mode & AARCH64_ISA_MODE_ZA_ON)
11685 && !shared_za_flags)
11686 {
11687 sorry ("call to a function that shares state other than %qs"
11688 " from a function that has %qs state", "za", "za");
11689 inform (input_location, "use %<__arm_preserves(\"za\")%> if the"
11690 " callee preserves ZA");
11691 }
11692
11693 gcc_assert (MEM_P (mem));
11694 callee = XEXP (mem, 0);
11695
11696 #if TARGET_PECOFF
11697 tmp = legitimize_pe_coff_symbol (callee, false);
11698 if (tmp)
11699 callee = tmp;
11700 #endif
11701
11702 mode = GET_MODE (callee);
11703 gcc_assert (mode == Pmode);
11704
11705 /* Decide if we should generate indirect calls by loading the
11706 address of the callee into a register before performing
11707 the branch-and-link. */
11708 if (SYMBOL_REF_P (callee)
11709 ? (aarch64_is_long_call_p (callee)
11710 || aarch64_is_noplt_call_p (callee))
11711 : !REG_P (callee))
11712 XEXP (mem, 0) = force_reg (mode, callee);
11713
11714 /* Accumulate the return values, including state that is shared via
11715 attributes. */
11716 auto_vec<rtx, 8> return_values;
11717 if (result)
11718 {
11719 if (GET_CODE (result) == PARALLEL)
11720 for (int i = 0; i < XVECLEN (result, 0); ++i)
11721 return_values.safe_push (XVECEXP (result, 0, i));
11722 else
11723 return_values.safe_push (result);
11724 }
11725 unsigned int orig_num_return_values = return_values.length ();
11726 if (shared_za_flags & AARCH64_STATE_OUT)
11727 return_values.safe_push (gen_rtx_REG (VNx16BImode, ZA_REGNUM));
11728 /* When calling private-ZA functions from functions with ZA state,
11729 we want to know whether the call committed a lazy save. */
11730 if (TARGET_ZA && !shared_za_flags)
11731 return_values.safe_push (gen_rtx_REG (VNx16BImode, ZA_SAVED_REGNUM));
11732 if (shared_zt0_flags & AARCH64_STATE_OUT)
11733 return_values.safe_push (gen_rtx_REG (V8DImode, ZT0_REGNUM));
11734
11735 /* Create the new return value, if necessary. */
11736 if (orig_num_return_values != return_values.length ())
11737 {
11738 if (return_values.length () == 1)
11739 result = return_values[0];
11740 else
11741 {
11742 for (rtx &x : return_values)
11743 if (GET_CODE (x) != EXPR_LIST)
11744 x = gen_rtx_EXPR_LIST (VOIDmode, x, const0_rtx);
11745 rtvec v = gen_rtvec_v (return_values.length (),
11746 return_values.address ());
11747 result = gen_rtx_PARALLEL (VOIDmode, v);
11748 }
11749 }
11750
11751 call = gen_rtx_CALL (VOIDmode, mem, const0_rtx);
11752
11753 if (result != NULL_RTX)
11754 call = gen_rtx_SET (result, call);
11755
11756 if (sibcall)
11757 tmp = ret_rtx;
11758 else
11759 tmp = gen_rtx_CLOBBER (VOIDmode, gen_rtx_REG (Pmode, LR_REGNUM));
11760
11761 callee_abi = gen_rtx_UNSPEC (DImode, gen_rtvec (1, callee_abi),
11762 UNSPEC_CALLEE_ABI);
11763
11764 vec = gen_rtvec (3, call, callee_abi, tmp);
11765 call = gen_rtx_PARALLEL (VOIDmode, vec);
11766
11767 auto call_insn = aarch64_emit_call_insn (call);
11768
11769 /* Check whether the call requires a change to PSTATE.SM. We can't
11770 emit the instructions to change PSTATE.SM yet, since they involve
11771 a change in vector length and a change in instruction set, which
11772 cannot be represented in RTL.
11773
11774 For now, just record which registers will be clobbered and used
11775 by the changes to PSTATE.SM. */
11776 if (!sibcall && aarch64_call_switches_pstate_sm (callee_isa_mode))
11777 {
11778 aarch64_sme_mode_switch_regs args_switch;
11779 if (sme_mode_switch_args != const0_rtx)
11780 {
11781 unsigned int num_args = XVECLEN (sme_mode_switch_args, 0);
11782 for (unsigned int i = 0; i < num_args; ++i)
11783 {
11784 rtx x = XVECEXP (sme_mode_switch_args, 0, i);
11785 args_switch.add_reg (GET_MODE (x), REGNO (x));
11786 }
11787 }
11788
11789 aarch64_sme_mode_switch_regs result_switch;
11790 if (result)
11791 result_switch.add_call_result (call_insn);
11792
11793 unsigned int num_gprs = MAX (args_switch.num_gprs (),
11794 result_switch.num_gprs ());
11795 for (unsigned int i = 0; i < num_gprs; ++i)
11796 clobber_reg (&CALL_INSN_FUNCTION_USAGE (call_insn),
11797 gen_rtx_REG (DImode, args_switch.FIRST_GPR + i));
11798
11799 for (int regno = V0_REGNUM; regno < V0_REGNUM + 32; regno += 4)
11800 clobber_reg (&CALL_INSN_FUNCTION_USAGE (call_insn),
11801 gen_rtx_REG (V4x16QImode, regno));
11802
11803 for (int regno = P0_REGNUM; regno < P0_REGNUM + 16; regno += 1)
11804 clobber_reg (&CALL_INSN_FUNCTION_USAGE (call_insn),
11805 gen_rtx_REG (VNx16BImode, regno));
11806
11807 /* Ensure that the VG save slot has been initialized. Also emit
11808 an instruction to model the effect of the temporary clobber
11809 of VG, so that the prologue/epilogue pass sees the need to
11810 save the old value. */
11811 use_reg (&CALL_INSN_FUNCTION_USAGE (call_insn),
11812 gen_rtx_REG (DImode, VG_REGNUM));
11813 emit_insn_before (gen_aarch64_update_vg (), call_insn);
11814
11815 cfun->machine->call_switches_pstate_sm = true;
11816 }
11817
11818 /* Add any ZA-related information.
11819
11820 ZA_REGNUM represents the current function's ZA state, rather than
11821 the contents of the ZA register itself. We ensure that the function's
11822 ZA state is preserved by private-ZA call sequences, so the call itself
11823 does not use or clobber ZA_REGNUM. The same thing applies to
11824 ZT0_REGNUM. */
11825 if (TARGET_ZA)
11826 {
11827 /* The callee requires ZA to be active if the callee is shared-ZA,
11828 otherwise it requires ZA to be dormant or off. The state of ZA is
11829 captured by a combination of SME_STATE_REGNUM, TPIDR2_SETUP_REGNUM,
11830 and ZA_SAVED_REGNUM. */
11831 use_reg (&CALL_INSN_FUNCTION_USAGE (call_insn),
11832 gen_rtx_REG (DImode, SME_STATE_REGNUM));
11833 use_reg (&CALL_INSN_FUNCTION_USAGE (call_insn),
11834 gen_rtx_REG (DImode, TPIDR2_SETUP_REGNUM));
11835 use_reg (&CALL_INSN_FUNCTION_USAGE (call_insn),
11836 gen_rtx_REG (VNx16BImode, ZA_SAVED_REGNUM));
11837
11838 /* Keep the aarch64_start/end_private_za_call markers live. */
11839 if (!(callee_isa_mode & AARCH64_ISA_MODE_ZA_ON))
11840 use_reg (&CALL_INSN_FUNCTION_USAGE (call_insn),
11841 gen_rtx_REG (VNx16BImode, LOWERING_REGNUM));
11842
11843 /* If the callee is a shared-ZA function, record whether it uses the
11844 current value of ZA and ZT0. */
11845 if (shared_za_flags & AARCH64_STATE_IN)
11846 use_reg (&CALL_INSN_FUNCTION_USAGE (call_insn),
11847 gen_rtx_REG (VNx16BImode, ZA_REGNUM));
11848
11849 if (shared_zt0_flags & AARCH64_STATE_IN)
11850 use_reg (&CALL_INSN_FUNCTION_USAGE (call_insn),
11851 gen_rtx_REG (V8DImode, ZT0_REGNUM));
11852 }
11853 }
11854
11855 /* Implement TARGET_END_CALL_ARGS. */
11856
11857 static void
11858 aarch64_end_call_args (cumulative_args_t ca_v)
11859 {
11860 CUMULATIVE_ARGS *ca = get_cumulative_args (ca_v);
11861
11862 /* If this is a call to a private ZA function, emit a marker to
11863 indicate where any necessary restoration code could be inserted.
11864 The code itself is inserted by the mode-switching pass. */
11865 if (TARGET_ZA && !(ca->isa_mode & AARCH64_ISA_MODE_ZA_ON))
11866 emit_insn (gen_aarch64_end_private_za_call ());
11867
11868 /* If this is a call to a shared-ZA function that doesn't share ZT0,
11869 save and restore ZT0 around the call. */
11870 if (aarch64_cfun_has_state ("zt0")
11871 && (ca->isa_mode & AARCH64_ISA_MODE_ZA_ON)
11872 && ca->shared_zt0_flags == 0)
11873 aarch64_restore_zt0 (false);
11874 }
11875
11876 /* Emit call insn with PAT and do aarch64-specific handling. */
11877
11878 rtx_call_insn *
11879 aarch64_emit_call_insn (rtx pat)
11880 {
11881 auto insn = emit_call_insn (pat);
11882
11883 rtx *fusage = &CALL_INSN_FUNCTION_USAGE (insn);
11884 clobber_reg (fusage, gen_rtx_REG (word_mode, IP0_REGNUM));
11885 clobber_reg (fusage, gen_rtx_REG (word_mode, IP1_REGNUM));
11886 return as_a<rtx_call_insn *> (insn);
11887 }
11888
11889 machine_mode
11890 aarch64_select_cc_mode (RTX_CODE code, rtx x, rtx y)
11891 {
11892 machine_mode mode_x = GET_MODE (x);
11893 rtx_code code_x = GET_CODE (x);
11894
11895 /* All floating point compares return CCFP if it is an equality
11896 comparison, and CCFPE otherwise. */
11897 if (GET_MODE_CLASS (mode_x) == MODE_FLOAT)
11898 {
11899 switch (code)
11900 {
11901 case EQ:
11902 case NE:
11903 case UNORDERED:
11904 case ORDERED:
11905 case UNLT:
11906 case UNLE:
11907 case UNGT:
11908 case UNGE:
11909 case UNEQ:
11910 return CCFPmode;
11911
11912 case LT:
11913 case LE:
11914 case GT:
11915 case GE:
11916 case LTGT:
11917 return CCFPEmode;
11918
11919 default:
11920 gcc_unreachable ();
11921 }
11922 }
11923
11924 /* Equality comparisons of short modes against zero can be performed
11925 using the TST instruction with the appropriate bitmask. */
11926 if (y == const0_rtx && (REG_P (x) || SUBREG_P (x))
11927 && (code == EQ || code == NE)
11928 && (mode_x == HImode || mode_x == QImode))
11929 return CC_Zmode;
11930
11931 /* Similarly, comparisons of zero_extends from shorter modes can
11932 be performed using an ANDS with an immediate mask. */
11933 if (y == const0_rtx && code_x == ZERO_EXTEND
11934 && (mode_x == SImode || mode_x == DImode)
11935 && (GET_MODE (XEXP (x, 0)) == HImode || GET_MODE (XEXP (x, 0)) == QImode)
11936 && (code == EQ || code == NE))
11937 return CC_Zmode;
11938
11939 /* Zero extracts support equality comparisons. */
11940 if ((mode_x == SImode || mode_x == DImode)
11941 && y == const0_rtx
11942 && (code_x == ZERO_EXTRACT && CONST_INT_P (XEXP (x, 1))
11943 && CONST_INT_P (XEXP (x, 2)))
11944 && (code == EQ || code == NE))
11945 return CC_Zmode;
11946
11947 /* ANDS/BICS/TST support equality and all signed comparisons. */
11948 if ((mode_x == SImode || mode_x == DImode)
11949 && y == const0_rtx
11950 && (code_x == AND)
11951 && (code == EQ || code == NE || code == LT || code == GE
11952 || code == GT || code == LE))
11953 return CC_NZVmode;
11954
11955 /* ADDS/SUBS correctly set N and Z flags. */
11956 if ((mode_x == SImode || mode_x == DImode)
11957 && y == const0_rtx
11958 && (code == EQ || code == NE || code == LT || code == GE)
11959 && (code_x == PLUS || code_x == MINUS || code_x == NEG))
11960 return CC_NZmode;
11961
11962 /* A compare with a shifted operand. Because of canonicalization,
11963 the comparison will have to be swapped when we emit the assembly
11964 code. */
11965 if ((mode_x == SImode || mode_x == DImode)
11966 && (REG_P (y) || SUBREG_P (y) || y == const0_rtx)
11967 && (code_x == ASHIFT || code_x == ASHIFTRT
11968 || code_x == LSHIFTRT
11969 || code_x == ZERO_EXTEND || code_x == SIGN_EXTEND))
11970 return CC_SWPmode;
11971
11972 /* Similarly for a negated operand, but we can only do this for
11973 equalities. */
11974 if ((mode_x == SImode || mode_x == DImode)
11975 && (REG_P (y) || SUBREG_P (y))
11976 && (code == EQ || code == NE)
11977 && code_x == NEG)
11978 return CC_Zmode;
11979
11980 /* A test for unsigned overflow from an addition. */
11981 if ((mode_x == DImode || mode_x == TImode)
11982 && (code == LTU || code == GEU)
11983 && code_x == PLUS
11984 && rtx_equal_p (XEXP (x, 0), y))
11985 return CC_Cmode;
11986
11987 /* A test for unsigned overflow from an add with carry. */
11988 if ((mode_x == DImode || mode_x == TImode)
11989 && (code == LTU || code == GEU)
11990 && code_x == PLUS
11991 && CONST_SCALAR_INT_P (y)
11992 && (rtx_mode_t (y, mode_x)
11993 == (wi::shwi (1, mode_x)
11994 << (GET_MODE_BITSIZE (mode_x).to_constant () / 2))))
11995 return CC_ADCmode;
11996
11997 /* A test for signed overflow. */
11998 if ((mode_x == DImode || mode_x == TImode)
11999 && code == NE
12000 && code_x == PLUS
12001 && GET_CODE (y) == SIGN_EXTEND)
12002 return CC_Vmode;
12003
12004 /* For everything else, return CCmode. */
12005 return CCmode;
12006 }
12007
12008 static int
12009 aarch64_get_condition_code_1 (machine_mode, enum rtx_code);
12010
12011 int
12012 aarch64_get_condition_code (rtx x)
12013 {
12014 machine_mode mode = GET_MODE (XEXP (x, 0));
12015 enum rtx_code comp_code = GET_CODE (x);
12016
12017 if (GET_MODE_CLASS (mode) != MODE_CC)
12018 mode = SELECT_CC_MODE (comp_code, XEXP (x, 0), XEXP (x, 1));
12019 return aarch64_get_condition_code_1 (mode, comp_code);
12020 }
12021
12022 static int
12023 aarch64_get_condition_code_1 (machine_mode mode, enum rtx_code comp_code)
12024 {
12025 switch (mode)
12026 {
12027 case E_CCFPmode:
12028 case E_CCFPEmode:
12029 switch (comp_code)
12030 {
12031 case GE: return AARCH64_GE;
12032 case GT: return AARCH64_GT;
12033 case LE: return AARCH64_LS;
12034 case LT: return AARCH64_MI;
12035 case NE: return AARCH64_NE;
12036 case EQ: return AARCH64_EQ;
12037 case ORDERED: return AARCH64_VC;
12038 case UNORDERED: return AARCH64_VS;
12039 case UNLT: return AARCH64_LT;
12040 case UNLE: return AARCH64_LE;
12041 case UNGT: return AARCH64_HI;
12042 case UNGE: return AARCH64_PL;
12043 default: return -1;
12044 }
12045 break;
12046
12047 case E_CCmode:
12048 switch (comp_code)
12049 {
12050 case NE: return AARCH64_NE;
12051 case EQ: return AARCH64_EQ;
12052 case GE: return AARCH64_GE;
12053 case GT: return AARCH64_GT;
12054 case LE: return AARCH64_LE;
12055 case LT: return AARCH64_LT;
12056 case GEU: return AARCH64_CS;
12057 case GTU: return AARCH64_HI;
12058 case LEU: return AARCH64_LS;
12059 case LTU: return AARCH64_CC;
12060 default: return -1;
12061 }
12062 break;
12063
12064 case E_CC_SWPmode:
12065 switch (comp_code)
12066 {
12067 case NE: return AARCH64_NE;
12068 case EQ: return AARCH64_EQ;
12069 case GE: return AARCH64_LE;
12070 case GT: return AARCH64_LT;
12071 case LE: return AARCH64_GE;
12072 case LT: return AARCH64_GT;
12073 case GEU: return AARCH64_LS;
12074 case GTU: return AARCH64_CC;
12075 case LEU: return AARCH64_CS;
12076 case LTU: return AARCH64_HI;
12077 default: return -1;
12078 }
12079 break;
12080
12081 case E_CC_NZCmode:
12082 switch (comp_code)
12083 {
12084 case NE: return AARCH64_NE; /* = any */
12085 case EQ: return AARCH64_EQ; /* = none */
12086 case GE: return AARCH64_PL; /* = nfrst */
12087 case LT: return AARCH64_MI; /* = first */
12088 case GEU: return AARCH64_CS; /* = nlast */
12089 case GTU: return AARCH64_HI; /* = pmore */
12090 case LEU: return AARCH64_LS; /* = plast */
12091 case LTU: return AARCH64_CC; /* = last */
12092 default: return -1;
12093 }
12094 break;
12095
12096 case E_CC_NZVmode:
12097 switch (comp_code)
12098 {
12099 case NE: return AARCH64_NE;
12100 case EQ: return AARCH64_EQ;
12101 case GE: return AARCH64_PL;
12102 case LT: return AARCH64_MI;
12103 case GT: return AARCH64_GT;
12104 case LE: return AARCH64_LE;
12105 default: return -1;
12106 }
12107 break;
12108
12109 case E_CC_NZmode:
12110 switch (comp_code)
12111 {
12112 case NE: return AARCH64_NE;
12113 case EQ: return AARCH64_EQ;
12114 case GE: return AARCH64_PL;
12115 case LT: return AARCH64_MI;
12116 default: return -1;
12117 }
12118 break;
12119
12120 case E_CC_Zmode:
12121 switch (comp_code)
12122 {
12123 case NE: return AARCH64_NE;
12124 case EQ: return AARCH64_EQ;
12125 default: return -1;
12126 }
12127 break;
12128
12129 case E_CC_Cmode:
12130 switch (comp_code)
12131 {
12132 case LTU: return AARCH64_CS;
12133 case GEU: return AARCH64_CC;
12134 default: return -1;
12135 }
12136 break;
12137
12138 case E_CC_ADCmode:
12139 switch (comp_code)
12140 {
12141 case GEU: return AARCH64_CS;
12142 case LTU: return AARCH64_CC;
12143 default: return -1;
12144 }
12145 break;
12146
12147 case E_CC_Vmode:
12148 switch (comp_code)
12149 {
12150 case NE: return AARCH64_VS;
12151 case EQ: return AARCH64_VC;
12152 default: return -1;
12153 }
12154 break;
12155
12156 default:
12157 return -1;
12158 }
12159
12160 return -1;
12161 }
12162
12163 /* Return true if X is a CONST_INT, CONST_WIDE_INT or a constant vector
12164 duplicate of such constants. If so, store in RET_WI the wide_int
12165 representation of the constant paired with the inner mode of the vector mode
12166 or MODE for scalar X constants. If MODE is not provided then TImode is
12167 used. */
12168
12169 static bool
12170 aarch64_extract_vec_duplicate_wide_int (rtx x, wide_int *ret_wi,
12171 scalar_mode mode = TImode)
12172 {
12173 rtx elt = unwrap_const_vec_duplicate (x);
12174 if (!CONST_SCALAR_INT_P (elt))
12175 return false;
12176 scalar_mode smode
12177 = CONST_SCALAR_INT_P (x) ? mode : GET_MODE_INNER (GET_MODE (x));
12178 *ret_wi = rtx_mode_t (elt, smode);
12179 return true;
12180 }
12181
12182 /* Return true if X is a scalar or a constant vector of integer
12183 immediates that represent the rounding constant used in the fixed-point
12184 arithmetic instructions.
12185 The accepted form of the constant is (1 << (C - 1)) where C is in the range
12186 [1, MODE_WIDTH/2]. */
12187
12188 bool
12189 aarch64_rnd_imm_p (rtx x)
12190 {
12191 wide_int rnd_cst;
12192 if (!aarch64_extract_vec_duplicate_wide_int (x, &rnd_cst))
12193 return false;
12194 int log2 = wi::exact_log2 (rnd_cst);
12195 if (log2 < 0)
12196 return false;
12197 return IN_RANGE (log2, 0, rnd_cst.get_precision () / 2 - 1);
12198 }
12199
12200 /* Return true if RND is a constant vector of integer rounding constants
12201 corresponding to a constant vector of shifts, SHIFT.
12202 The relationship should be RND == (1 << (SHIFT - 1)). */
12203
12204 bool
12205 aarch64_const_vec_rnd_cst_p (rtx rnd, rtx shift)
12206 {
12207 wide_int rnd_cst, shft_cst;
12208 if (!aarch64_extract_vec_duplicate_wide_int (rnd, &rnd_cst)
12209 || !aarch64_extract_vec_duplicate_wide_int (shift, &shft_cst))
12210 return false;
12211
12212 return rnd_cst == (wi::shwi (1, rnd_cst.get_precision ()) << (shft_cst - 1));
12213 }
12214
12215 bool
12216 aarch64_const_vec_all_same_in_range_p (rtx x,
12217 HOST_WIDE_INT minval,
12218 HOST_WIDE_INT maxval)
12219 {
12220 rtx elt;
12221 return (const_vec_duplicate_p (x, &elt)
12222 && CONST_INT_P (elt)
12223 && IN_RANGE (INTVAL (elt), minval, maxval));
12224 }
12225
12226 /* Some constants can't be made using normal mov instructions in Advanced SIMD
12227 but we can still create them in various ways. If the constant in VAL can be
12228 created using alternate methods then if possible then return true and
12229 additionally set TARGET to the rtx for the sequence if TARGET is not NULL.
12230 Otherwise return false if sequence is not possible. */
12231
12232 bool
12233 aarch64_maybe_generate_simd_constant (rtx target, rtx val, machine_mode mode)
12234 {
12235 wide_int wval;
12236 auto smode = GET_MODE_INNER (mode);
12237 if (!aarch64_extract_vec_duplicate_wide_int (val, &wval, smode))
12238 return false;
12239
12240 /* For Advanced SIMD we can create an integer with only the top bit set
12241 using fneg (0.0f). */
12242 if (TARGET_SIMD
12243 && !TARGET_SVE
12244 && smode == DImode
12245 && wi::only_sign_bit_p (wval))
12246 {
12247 if (!target)
12248 return true;
12249
12250 /* Use the same base type as aarch64_gen_shareable_zero. */
12251 rtx zero = CONST0_RTX (V4SImode);
12252 emit_move_insn (lowpart_subreg (V4SImode, target, mode), zero);
12253 rtx neg = lowpart_subreg (V2DImode, target, mode);
12254 emit_insn (gen_aarch64_fnegv2di2 (neg, copy_rtx (neg)));
12255 return true;
12256 }
12257
12258 return false;
12259 }
12260
12261 /* Check if the value in VAL with mode MODE can be created using special
12262 instruction sequences. */
12263
12264 bool aarch64_simd_special_constant_p (rtx val, machine_mode mode)
12265 {
12266 return aarch64_maybe_generate_simd_constant (NULL_RTX, val, mode);
12267 }
12268
12269 bool
12270 aarch64_const_vec_all_same_int_p (rtx x, HOST_WIDE_INT val)
12271 {
12272 return aarch64_const_vec_all_same_in_range_p (x, val, val);
12273 }
12274
12275 /* Return true if VEC is a constant in which every element is in the range
12276 [MINVAL, MAXVAL]. The elements do not need to have the same value. */
12277
12278 static bool
12279 aarch64_const_vec_all_in_range_p (rtx vec,
12280 HOST_WIDE_INT minval,
12281 HOST_WIDE_INT maxval)
12282 {
12283 if (!CONST_VECTOR_P (vec)
12284 || GET_MODE_CLASS (GET_MODE (vec)) != MODE_VECTOR_INT)
12285 return false;
12286
12287 int nunits;
12288 if (!CONST_VECTOR_STEPPED_P (vec))
12289 nunits = const_vector_encoded_nelts (vec);
12290 else if (!CONST_VECTOR_NUNITS (vec).is_constant (&nunits))
12291 return false;
12292
12293 for (int i = 0; i < nunits; i++)
12294 {
12295 rtx vec_elem = CONST_VECTOR_ELT (vec, i);
12296 if (!CONST_INT_P (vec_elem)
12297 || !IN_RANGE (INTVAL (vec_elem), minval, maxval))
12298 return false;
12299 }
12300 return true;
12301 }
12302
12303 /* N Z C V. */
12304 #define AARCH64_CC_V 1
12305 #define AARCH64_CC_C (1 << 1)
12306 #define AARCH64_CC_Z (1 << 2)
12307 #define AARCH64_CC_N (1 << 3)
12308
12309 /* N Z C V flags for ccmp. Indexed by AARCH64_COND_CODE. */
12310 static const int aarch64_nzcv_codes[] =
12311 {
12312 0, /* EQ, Z == 1. */
12313 AARCH64_CC_Z, /* NE, Z == 0. */
12314 0, /* CS, C == 1. */
12315 AARCH64_CC_C, /* CC, C == 0. */
12316 0, /* MI, N == 1. */
12317 AARCH64_CC_N, /* PL, N == 0. */
12318 0, /* VS, V == 1. */
12319 AARCH64_CC_V, /* VC, V == 0. */
12320 0, /* HI, C ==1 && Z == 0. */
12321 AARCH64_CC_C, /* LS, !(C == 1 && Z == 0). */
12322 AARCH64_CC_V, /* GE, N == V. */
12323 0, /* LT, N != V. */
12324 AARCH64_CC_Z, /* GT, Z == 0 && N == V. */
12325 0, /* LE, !(Z == 0 && N == V). */
12326 0, /* AL, Any. */
12327 0 /* NV, Any. */
12328 };
12329
12330 /* Print floating-point vector immediate operand X to F, negating it
12331 first if NEGATE is true. Return true on success, false if it isn't
12332 a constant we can handle. */
12333
12334 static bool
12335 aarch64_print_vector_float_operand (FILE *f, rtx x, bool negate)
12336 {
12337 rtx elt;
12338
12339 if (!const_vec_duplicate_p (x, &elt))
12340 return false;
12341
12342 REAL_VALUE_TYPE r = *CONST_DOUBLE_REAL_VALUE (elt);
12343 if (negate)
12344 r = real_value_negate (&r);
12345
12346 /* Handle the SVE single-bit immediates specially, since they have a
12347 fixed form in the assembly syntax. */
12348 if (real_equal (&r, &dconst0))
12349 asm_fprintf (f, "0.0");
12350 else if (real_equal (&r, &dconst2))
12351 asm_fprintf (f, "2.0");
12352 else if (real_equal (&r, &dconst1))
12353 asm_fprintf (f, "1.0");
12354 else if (real_equal (&r, &dconsthalf))
12355 asm_fprintf (f, "0.5");
12356 else
12357 {
12358 const int buf_size = 20;
12359 char float_buf[buf_size] = {'\0'};
12360 real_to_decimal_for_mode (float_buf, &r, buf_size, buf_size,
12361 1, GET_MODE (elt));
12362 asm_fprintf (f, "%s", float_buf);
12363 }
12364
12365 return true;
12366 }
12367
12368 /* Return the equivalent letter for size. */
12369 static char
12370 sizetochar (int size)
12371 {
12372 switch (size)
12373 {
12374 case 64: return 'd';
12375 case 32: return 's';
12376 case 16: return 'h';
12377 case 8: return 'b';
12378 default: gcc_unreachable ();
12379 }
12380 }
12381
12382 /* Print operand X to file F in a target specific manner according to CODE.
12383 The acceptable formatting commands given by CODE are:
12384 'c': An integer or symbol address without a preceding #
12385 sign.
12386 'C': Take the duplicated element in a vector constant
12387 and print it in hex.
12388 'D': Take the duplicated element in a vector constant
12389 and print it as an unsigned integer, in decimal.
12390 'e': Print the sign/zero-extend size as a character 8->b,
12391 16->h, 32->w. Can also be used for masks:
12392 0xff->b, 0xffff->h, 0xffffffff->w.
12393 'I': If the operand is a duplicated vector constant,
12394 replace it with the duplicated scalar. If the
12395 operand is then a floating-point constant, replace
12396 it with the integer bit representation. Print the
12397 transformed constant as a signed decimal number.
12398 'p': Prints N such that 2^N == X (X must be power of 2 and
12399 const int).
12400 'P': Print the number of non-zero bits in X (a const_int).
12401 'H': Print the higher numbered register of a pair (TImode)
12402 of regs.
12403 'm': Print a condition (eq, ne, etc).
12404 'M': Same as 'm', but invert condition.
12405 'N': Take the duplicated element in a vector constant
12406 and print the negative of it in decimal.
12407 'b/h/s/d/q': Print a scalar FP/SIMD register name.
12408 'Z': Same for SVE registers. ('z' was already taken.)
12409 Note that it is not necessary to use %Z for operands
12410 that have SVE modes. The convention is to use %Z
12411 only for non-SVE (or potentially non-SVE) modes.
12412 'S/T/U/V': Print a FP/SIMD register name for a register list.
12413 The register printed is the FP/SIMD register name
12414 of X + 0/1/2/3 for S/T/U/V.
12415 'R': Print a scalar Integer/FP/SIMD register name + 1.
12416 'X': Print bottom 16 bits of integer constant in hex.
12417 'w/x': Print a general register name or the zero register
12418 (32-bit or 64-bit).
12419 '0': Print a normal operand, if it's a general register,
12420 then we assume DImode.
12421 'k': Print NZCV for conditional compare instructions.
12422 'K': Print a predicate register as pn<N> rather than p<N>
12423 'A': Output address constant representing the first
12424 argument of X, specifying a relocation offset
12425 if appropriate.
12426 'L': Output constant address specified by X
12427 with a relocation offset if appropriate.
12428 'G': Prints address of X, specifying a PC relative
12429 relocation mode if appropriate.
12430 'y': Output address of LDP or STP - this is used for
12431 some LDP/STPs which don't use a PARALLEL in their
12432 pattern (so the mode needs to be adjusted).
12433 'z': Output address of a typical LDP or STP. */
12434
12435 static void
12436 aarch64_print_operand (FILE *f, rtx x, int code)
12437 {
12438 rtx elt;
12439 switch (code)
12440 {
12441 case 'c':
12442 if (CONST_INT_P (x))
12443 fprintf (f, HOST_WIDE_INT_PRINT_DEC, INTVAL (x));
12444 else
12445 {
12446 poly_int64 offset;
12447 rtx base = strip_offset_and_salt (x, &offset);
12448 if (SYMBOL_REF_P (base))
12449 output_addr_const (f, x);
12450 else
12451 output_operand_lossage ("unsupported operand for code '%c'", code);
12452 }
12453 break;
12454
12455 case 'e':
12456 {
12457 x = unwrap_const_vec_duplicate (x);
12458 if (!CONST_INT_P (x))
12459 {
12460 output_operand_lossage ("invalid operand for '%%%c'", code);
12461 return;
12462 }
12463
12464 HOST_WIDE_INT val = INTVAL (x);
12465 if ((val & ~7) == 8 || val == 0xff)
12466 fputc ('b', f);
12467 else if ((val & ~7) == 16 || val == 0xffff)
12468 fputc ('h', f);
12469 else if ((val & ~7) == 32 || val == 0xffffffff)
12470 fputc ('w', f);
12471 else
12472 {
12473 output_operand_lossage ("invalid operand for '%%%c'", code);
12474 return;
12475 }
12476 }
12477 break;
12478
12479 case 'p':
12480 {
12481 int n;
12482
12483 if (!CONST_INT_P (x) || (n = exact_log2 (INTVAL (x))) < 0)
12484 {
12485 output_operand_lossage ("invalid operand for '%%%c'", code);
12486 return;
12487 }
12488
12489 asm_fprintf (f, "%d", n);
12490 }
12491 break;
12492
12493 case 'P':
12494 if (!CONST_INT_P (x))
12495 {
12496 output_operand_lossage ("invalid operand for '%%%c'", code);
12497 return;
12498 }
12499
12500 asm_fprintf (f, "%u", popcount_hwi (INTVAL (x)));
12501 break;
12502
12503 case 'H':
12504 if (x == const0_rtx)
12505 {
12506 asm_fprintf (f, "xzr");
12507 break;
12508 }
12509
12510 if (!REG_P (x) || !GP_REGNUM_P (REGNO (x) + 1))
12511 {
12512 output_operand_lossage ("invalid operand for '%%%c'", code);
12513 return;
12514 }
12515
12516 asm_fprintf (f, "%s", reg_names [REGNO (x) + 1]);
12517 break;
12518
12519 case 'I':
12520 {
12521 x = aarch64_bit_representation (unwrap_const_vec_duplicate (x));
12522 if (CONST_INT_P (x))
12523 asm_fprintf (f, "%wd", INTVAL (x));
12524 else
12525 {
12526 output_operand_lossage ("invalid operand for '%%%c'", code);
12527 return;
12528 }
12529 break;
12530 }
12531
12532 case 'M':
12533 case 'm':
12534 {
12535 int cond_code;
12536 /* CONST_TRUE_RTX means al/nv (al is the default, don't print it). */
12537 if (x == const_true_rtx)
12538 {
12539 if (code == 'M')
12540 fputs ("nv", f);
12541 return;
12542 }
12543
12544 if (!COMPARISON_P (x))
12545 {
12546 output_operand_lossage ("invalid operand for '%%%c'", code);
12547 return;
12548 }
12549
12550 cond_code = aarch64_get_condition_code (x);
12551 gcc_assert (cond_code >= 0);
12552 if (code == 'M')
12553 cond_code = AARCH64_INVERSE_CONDITION_CODE (cond_code);
12554 if (GET_MODE (XEXP (x, 0)) == CC_NZCmode)
12555 fputs (aarch64_sve_condition_codes[cond_code], f);
12556 else
12557 fputs (aarch64_condition_codes[cond_code], f);
12558 }
12559 break;
12560
12561 case 'N':
12562 if (!const_vec_duplicate_p (x, &elt))
12563 {
12564 output_operand_lossage ("invalid vector constant");
12565 return;
12566 }
12567
12568 if (GET_MODE_CLASS (GET_MODE (x)) == MODE_VECTOR_INT)
12569 asm_fprintf (f, "%wd", (HOST_WIDE_INT) -UINTVAL (elt));
12570 else if (GET_MODE_CLASS (GET_MODE (x)) == MODE_VECTOR_FLOAT
12571 && aarch64_print_vector_float_operand (f, x, true))
12572 ;
12573 else
12574 {
12575 output_operand_lossage ("invalid vector constant");
12576 return;
12577 }
12578 break;
12579
12580 case 'b':
12581 case 'h':
12582 case 's':
12583 case 'd':
12584 case 'q':
12585 case 'Z':
12586 code = TOLOWER (code);
12587 if (!REG_P (x) || !FP_REGNUM_P (REGNO (x)))
12588 {
12589 output_operand_lossage ("incompatible floating point / vector register operand for '%%%c'", code);
12590 return;
12591 }
12592 asm_fprintf (f, "%c%d", code, REGNO (x) - V0_REGNUM);
12593 break;
12594
12595 case 'S':
12596 case 'T':
12597 case 'U':
12598 case 'V':
12599 if (!REG_P (x) || (!FP_REGNUM_P (REGNO (x)) && !PR_REGNUM_P (REGNO (x))))
12600 {
12601 output_operand_lossage ("incompatible operand for '%%%c'", code);
12602 return;
12603 }
12604 if (PR_REGNUM_P (REGNO (x)))
12605 asm_fprintf (f, "p%d", REGNO (x) - P0_REGNUM + (code - 'S'));
12606 else
12607 asm_fprintf (f, "%c%d",
12608 aarch64_sve_data_mode_p (GET_MODE (x)) ? 'z' : 'v',
12609 REGNO (x) - V0_REGNUM + (code - 'S'));
12610 break;
12611
12612 case 'R':
12613 if (REG_P (x) && FP_REGNUM_P (REGNO (x))
12614 && (aarch64_advsimd_partial_struct_mode_p (GET_MODE (x))))
12615 asm_fprintf (f, "d%d", REGNO (x) - V0_REGNUM + 1);
12616 else if (REG_P (x) && FP_REGNUM_P (REGNO (x)))
12617 asm_fprintf (f, "q%d", REGNO (x) - V0_REGNUM + 1);
12618 else if (REG_P (x) && GP_REGNUM_P (REGNO (x)))
12619 asm_fprintf (f, "x%d", REGNO (x) - R0_REGNUM + 1);
12620 else
12621 output_operand_lossage ("incompatible register operand for '%%%c'",
12622 code);
12623 break;
12624
12625 case 'X':
12626 if (!CONST_INT_P (x))
12627 {
12628 output_operand_lossage ("invalid operand for '%%%c'", code);
12629 return;
12630 }
12631 asm_fprintf (f, "0x%wx", UINTVAL (x) & 0xffff);
12632 break;
12633
12634 case 'C':
12635 {
12636 /* Print a replicated constant in hex. */
12637 if (!const_vec_duplicate_p (x, &elt) || !CONST_INT_P (elt))
12638 {
12639 output_operand_lossage ("invalid operand for '%%%c'", code);
12640 return;
12641 }
12642 scalar_mode inner_mode = GET_MODE_INNER (GET_MODE (x));
12643 asm_fprintf (f, "0x%wx", UINTVAL (elt) & GET_MODE_MASK (inner_mode));
12644 }
12645 break;
12646
12647 case 'D':
12648 {
12649 /* Print a replicated constant in decimal, treating it as
12650 unsigned. */
12651 if (!const_vec_duplicate_p (x, &elt) || !CONST_INT_P (elt))
12652 {
12653 output_operand_lossage ("invalid operand for '%%%c'", code);
12654 return;
12655 }
12656 scalar_mode inner_mode = GET_MODE_INNER (GET_MODE (x));
12657 asm_fprintf (f, "%wd", UINTVAL (elt) & GET_MODE_MASK (inner_mode));
12658 }
12659 break;
12660
12661 case 'w':
12662 case 'x':
12663 if (aarch64_const_zero_rtx_p (x))
12664 {
12665 asm_fprintf (f, "%czr", code);
12666 break;
12667 }
12668
12669 if (REG_P (x) && GP_REGNUM_P (REGNO (x)))
12670 {
12671 asm_fprintf (f, "%c%d", code, REGNO (x) - R0_REGNUM);
12672 break;
12673 }
12674
12675 if (REG_P (x) && REGNO (x) == SP_REGNUM)
12676 {
12677 asm_fprintf (f, "%ssp", code == 'w' ? "w" : "");
12678 break;
12679 }
12680
12681 /* Fall through */
12682
12683 case 0:
12684 if (x == NULL)
12685 {
12686 output_operand_lossage ("missing operand");
12687 return;
12688 }
12689
12690 switch (GET_CODE (x))
12691 {
12692 case CONST_STRING:
12693 {
12694 asm_fprintf (f, "%s", XSTR (x, 0));
12695 break;
12696 }
12697 case REG:
12698 if (aarch64_sve_data_mode_p (GET_MODE (x)))
12699 {
12700 if (REG_NREGS (x) == 1)
12701 asm_fprintf (f, "z%d", REGNO (x) - V0_REGNUM);
12702 else
12703 {
12704 char suffix
12705 = sizetochar (GET_MODE_UNIT_BITSIZE (GET_MODE (x)));
12706 asm_fprintf (f, "{z%d.%c - z%d.%c}",
12707 REGNO (x) - V0_REGNUM, suffix,
12708 END_REGNO (x) - V0_REGNUM - 1, suffix);
12709 }
12710 }
12711 else
12712 asm_fprintf (f, "%s", reg_names [REGNO (x)]);
12713 break;
12714
12715 case MEM:
12716 output_address (GET_MODE (x), XEXP (x, 0));
12717 break;
12718
12719 case LABEL_REF:
12720 case SYMBOL_REF:
12721 output_addr_const (asm_out_file, x);
12722 break;
12723
12724 case CONST_INT:
12725 asm_fprintf (f, "%wd", INTVAL (x));
12726 break;
12727
12728 case CONST:
12729 if (!VECTOR_MODE_P (GET_MODE (x)))
12730 {
12731 output_addr_const (asm_out_file, x);
12732 break;
12733 }
12734 /* fall through */
12735
12736 case CONST_VECTOR:
12737 if (!const_vec_duplicate_p (x, &elt))
12738 {
12739 output_operand_lossage ("invalid vector constant");
12740 return;
12741 }
12742
12743 if (GET_MODE_CLASS (GET_MODE (x)) == MODE_VECTOR_INT)
12744 asm_fprintf (f, "%wd", INTVAL (elt));
12745 else if (GET_MODE_CLASS (GET_MODE (x)) == MODE_VECTOR_FLOAT
12746 && aarch64_print_vector_float_operand (f, x, false))
12747 ;
12748 else
12749 {
12750 output_operand_lossage ("invalid vector constant");
12751 return;
12752 }
12753 break;
12754
12755 case CONST_DOUBLE:
12756 /* Since we define TARGET_SUPPORTS_WIDE_INT we shouldn't ever
12757 be getting CONST_DOUBLEs holding integers. */
12758 gcc_assert (GET_MODE (x) != VOIDmode);
12759 if (aarch64_float_const_zero_rtx_p (x))
12760 {
12761 fputc ('0', f);
12762 break;
12763 }
12764 else if (aarch64_float_const_representable_p (x))
12765 {
12766 #define buf_size 20
12767 char float_buf[buf_size] = {'\0'};
12768 real_to_decimal_for_mode (float_buf,
12769 CONST_DOUBLE_REAL_VALUE (x),
12770 buf_size, buf_size,
12771 1, GET_MODE (x));
12772 asm_fprintf (asm_out_file, "%s", float_buf);
12773 break;
12774 #undef buf_size
12775 }
12776 output_operand_lossage ("invalid constant");
12777 return;
12778 default:
12779 output_operand_lossage ("invalid operand");
12780 return;
12781 }
12782 break;
12783
12784 case 'A':
12785 if (GET_CODE (x) == HIGH)
12786 x = XEXP (x, 0);
12787
12788 switch (aarch64_classify_symbolic_expression (x))
12789 {
12790 case SYMBOL_SMALL_GOT_4G:
12791 asm_fprintf (asm_out_file, ":got:");
12792 break;
12793
12794 case SYMBOL_SMALL_TLSGD:
12795 asm_fprintf (asm_out_file, ":tlsgd:");
12796 break;
12797
12798 case SYMBOL_SMALL_TLSDESC:
12799 asm_fprintf (asm_out_file, ":tlsdesc:");
12800 break;
12801
12802 case SYMBOL_SMALL_TLSIE:
12803 asm_fprintf (asm_out_file, ":gottprel:");
12804 break;
12805
12806 case SYMBOL_TLSLE24:
12807 asm_fprintf (asm_out_file, ":tprel:");
12808 break;
12809
12810 case SYMBOL_TINY_GOT:
12811 gcc_unreachable ();
12812 break;
12813
12814 default:
12815 break;
12816 }
12817 output_addr_const (asm_out_file, x);
12818 break;
12819
12820 case 'L':
12821 switch (aarch64_classify_symbolic_expression (x))
12822 {
12823 case SYMBOL_SMALL_GOT_4G:
12824 asm_fprintf (asm_out_file, ":got_lo12:");
12825 break;
12826
12827 case SYMBOL_SMALL_TLSGD:
12828 asm_fprintf (asm_out_file, ":tlsgd_lo12:");
12829 break;
12830
12831 case SYMBOL_SMALL_TLSDESC:
12832 asm_fprintf (asm_out_file, ":tlsdesc_lo12:");
12833 break;
12834
12835 case SYMBOL_SMALL_TLSIE:
12836 asm_fprintf (asm_out_file, ":gottprel_lo12:");
12837 break;
12838
12839 case SYMBOL_TLSLE12:
12840 asm_fprintf (asm_out_file, ":tprel_lo12:");
12841 break;
12842
12843 case SYMBOL_TLSLE24:
12844 asm_fprintf (asm_out_file, ":tprel_lo12_nc:");
12845 break;
12846
12847 case SYMBOL_TINY_GOT:
12848 asm_fprintf (asm_out_file, ":got:");
12849 break;
12850
12851 case SYMBOL_TINY_TLSIE:
12852 asm_fprintf (asm_out_file, ":gottprel:");
12853 break;
12854
12855 default:
12856 break;
12857 }
12858 output_addr_const (asm_out_file, x);
12859 break;
12860
12861 case 'G':
12862 switch (aarch64_classify_symbolic_expression (x))
12863 {
12864 case SYMBOL_TLSLE24:
12865 asm_fprintf (asm_out_file, ":tprel_hi12:");
12866 break;
12867 default:
12868 break;
12869 }
12870 output_addr_const (asm_out_file, x);
12871 break;
12872
12873 case 'k':
12874 {
12875 HOST_WIDE_INT cond_code;
12876
12877 if (!CONST_INT_P (x))
12878 {
12879 output_operand_lossage ("invalid operand for '%%%c'", code);
12880 return;
12881 }
12882
12883 cond_code = INTVAL (x);
12884 gcc_assert (cond_code >= 0 && cond_code <= AARCH64_NV);
12885 asm_fprintf (f, "%d", aarch64_nzcv_codes[cond_code]);
12886 }
12887 break;
12888
12889 case 'K':
12890 if (!REG_P (x) || !PR_REGNUM_P (REGNO (x)))
12891 {
12892 output_operand_lossage ("invalid operand for '%%%c'", code);
12893 return;
12894 }
12895 asm_fprintf (f, "pn%d", REGNO (x) - P0_REGNUM);
12896 break;
12897
12898 case 'y':
12899 case 'z':
12900 {
12901 machine_mode mode = GET_MODE (x);
12902
12903 if (!MEM_P (x)
12904 || (code == 'y'
12905 && maybe_ne (GET_MODE_SIZE (mode), 8)
12906 && maybe_ne (GET_MODE_SIZE (mode), 16)
12907 && maybe_ne (GET_MODE_SIZE (mode), 32)))
12908 {
12909 output_operand_lossage ("invalid operand for '%%%c'", code);
12910 return;
12911 }
12912
12913 if (!aarch64_print_address_internal (f, mode, XEXP (x, 0),
12914 code == 'y'
12915 ? ADDR_QUERY_LDP_STP_N
12916 : ADDR_QUERY_LDP_STP))
12917 output_operand_lossage ("invalid operand prefix '%%%c'", code);
12918 }
12919 break;
12920
12921 default:
12922 output_operand_lossage ("invalid operand prefix '%%%c'", code);
12923 return;
12924 }
12925 }
12926
12927 /* Print address 'x' of a memory access with mode 'mode'.
12928 'op' is the context required by aarch64_classify_address. It can either be
12929 MEM for a normal memory access or PARALLEL for LDP/STP. */
12930 static bool
12931 aarch64_print_address_internal (FILE *f, machine_mode mode, rtx x,
12932 aarch64_addr_query_type type)
12933 {
12934 struct aarch64_address_info addr;
12935 unsigned int size, vec_flags;
12936
12937 /* Check all addresses are Pmode - including ILP32. */
12938 if (GET_MODE (x) != Pmode
12939 && (!CONST_INT_P (x)
12940 || trunc_int_for_mode (INTVAL (x), Pmode) != INTVAL (x)))
12941 {
12942 output_operand_lossage ("invalid address mode");
12943 return false;
12944 }
12945
12946 const bool load_store_pair_p = (type == ADDR_QUERY_LDP_STP
12947 || type == ADDR_QUERY_LDP_STP_N);
12948
12949 if (aarch64_classify_address (&addr, x, mode, true, type))
12950 switch (addr.type)
12951 {
12952 case ADDRESS_REG_IMM:
12953 if (known_eq (addr.const_offset, 0))
12954 {
12955 asm_fprintf (f, "[%s]", reg_names[REGNO (addr.base)]);
12956 return true;
12957 }
12958
12959 vec_flags = aarch64_classify_vector_memory_mode (mode);
12960 if ((vec_flags & VEC_ANY_SVE) && !load_store_pair_p)
12961 {
12962 HOST_WIDE_INT vnum
12963 = exact_div (addr.const_offset,
12964 aarch64_vl_bytes (mode, vec_flags)).to_constant ();
12965 asm_fprintf (f, "[%s, #%wd, mul vl]",
12966 reg_names[REGNO (addr.base)], vnum);
12967 return true;
12968 }
12969
12970 if (!CONST_INT_P (addr.offset))
12971 return false;
12972
12973 asm_fprintf (f, "[%s, %wd]", reg_names[REGNO (addr.base)],
12974 INTVAL (addr.offset));
12975 return true;
12976
12977 case ADDRESS_REG_REG:
12978 if (addr.shift == 0)
12979 asm_fprintf (f, "[%s, %s]", reg_names [REGNO (addr.base)],
12980 reg_names [REGNO (addr.offset)]);
12981 else
12982 asm_fprintf (f, "[%s, %s, lsl %u]", reg_names [REGNO (addr.base)],
12983 reg_names [REGNO (addr.offset)], addr.shift);
12984 return true;
12985
12986 case ADDRESS_REG_UXTW:
12987 if (addr.shift == 0)
12988 asm_fprintf (f, "[%s, w%d, uxtw]", reg_names [REGNO (addr.base)],
12989 REGNO (addr.offset) - R0_REGNUM);
12990 else
12991 asm_fprintf (f, "[%s, w%d, uxtw %u]", reg_names [REGNO (addr.base)],
12992 REGNO (addr.offset) - R0_REGNUM, addr.shift);
12993 return true;
12994
12995 case ADDRESS_REG_SXTW:
12996 if (addr.shift == 0)
12997 asm_fprintf (f, "[%s, w%d, sxtw]", reg_names [REGNO (addr.base)],
12998 REGNO (addr.offset) - R0_REGNUM);
12999 else
13000 asm_fprintf (f, "[%s, w%d, sxtw %u]", reg_names [REGNO (addr.base)],
13001 REGNO (addr.offset) - R0_REGNUM, addr.shift);
13002 return true;
13003
13004 case ADDRESS_REG_WB:
13005 /* Writeback is only supported for fixed-width modes. */
13006 size = GET_MODE_SIZE (mode).to_constant ();
13007 switch (GET_CODE (x))
13008 {
13009 case PRE_INC:
13010 asm_fprintf (f, "[%s, %d]!", reg_names [REGNO (addr.base)], size);
13011 return true;
13012 case POST_INC:
13013 asm_fprintf (f, "[%s], %d", reg_names [REGNO (addr.base)], size);
13014 return true;
13015 case PRE_DEC:
13016 asm_fprintf (f, "[%s, -%d]!", reg_names [REGNO (addr.base)], size);
13017 return true;
13018 case POST_DEC:
13019 asm_fprintf (f, "[%s], -%d", reg_names [REGNO (addr.base)], size);
13020 return true;
13021 case PRE_MODIFY:
13022 asm_fprintf (f, "[%s, %wd]!", reg_names[REGNO (addr.base)],
13023 INTVAL (addr.offset));
13024 return true;
13025 case POST_MODIFY:
13026 asm_fprintf (f, "[%s], %wd", reg_names[REGNO (addr.base)],
13027 INTVAL (addr.offset));
13028 return true;
13029 default:
13030 break;
13031 }
13032 break;
13033
13034 case ADDRESS_LO_SUM:
13035 asm_fprintf (f, "[%s, #:lo12:", reg_names [REGNO (addr.base)]);
13036 output_addr_const (f, addr.offset);
13037 asm_fprintf (f, "]");
13038 return true;
13039
13040 case ADDRESS_SYMBOLIC:
13041 output_addr_const (f, x);
13042 return true;
13043 }
13044
13045 return false;
13046 }
13047
13048 /* Print address 'x' of a memory access with mode 'mode'. */
13049 static void
13050 aarch64_print_operand_address (FILE *f, machine_mode mode, rtx x)
13051 {
13052 if (!aarch64_print_address_internal (f, mode, x, ADDR_QUERY_ANY))
13053 output_addr_const (f, x);
13054 }
13055
13056 /* Implement TARGET_ASM_OUTPUT_ADDR_CONST_EXTRA. */
13057
13058 static bool
13059 aarch64_output_addr_const_extra (FILE *file, rtx x)
13060 {
13061 if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_SALT_ADDR)
13062 {
13063 output_addr_const (file, XVECEXP (x, 0, 0));
13064 return true;
13065 }
13066 return false;
13067 }
13068
13069 bool
13070 aarch64_label_mentioned_p (rtx x)
13071 {
13072 const char *fmt;
13073 int i;
13074
13075 if (LABEL_REF_P (x))
13076 return true;
13077
13078 /* UNSPEC_TLS entries for a symbol include a LABEL_REF for the
13079 referencing instruction, but they are constant offsets, not
13080 symbols. */
13081 if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_TLS)
13082 return false;
13083
13084 fmt = GET_RTX_FORMAT (GET_CODE (x));
13085 for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
13086 {
13087 if (fmt[i] == 'E')
13088 {
13089 int j;
13090
13091 for (j = XVECLEN (x, i) - 1; j >= 0; j--)
13092 if (aarch64_label_mentioned_p (XVECEXP (x, i, j)))
13093 return 1;
13094 }
13095 else if (fmt[i] == 'e' && aarch64_label_mentioned_p (XEXP (x, i)))
13096 return 1;
13097 }
13098
13099 return 0;
13100 }
13101
13102 /* Implement REGNO_REG_CLASS. */
13103
13104 enum reg_class
13105 aarch64_regno_regclass (unsigned regno)
13106 {
13107 if (W8_W11_REGNUM_P (regno))
13108 return W8_W11_REGS;
13109
13110 if (W12_W15_REGNUM_P (regno))
13111 return W12_W15_REGS;
13112
13113 if (STUB_REGNUM_P (regno))
13114 return STUB_REGS;
13115
13116 if (GP_REGNUM_P (regno))
13117 return GENERAL_REGS;
13118
13119 if (regno == SP_REGNUM)
13120 return STACK_REG;
13121
13122 if (regno == FRAME_POINTER_REGNUM
13123 || regno == ARG_POINTER_REGNUM)
13124 return POINTER_REGS;
13125
13126 if (FP_REGNUM_P (regno))
13127 return (FP_LO8_REGNUM_P (regno) ? FP_LO8_REGS
13128 : FP_LO_REGNUM_P (regno) ? FP_LO_REGS : FP_REGS);
13129
13130 if (PR_REGNUM_P (regno))
13131 return PR_LO_REGNUM_P (regno) ? PR_LO_REGS : PR_HI_REGS;
13132
13133 if (regno == FPM_REGNUM)
13134 return MOVEABLE_SYSREGS;
13135
13136 if (regno == FFR_REGNUM || regno == FFRT_REGNUM)
13137 return FFR_REGS;
13138
13139 if (FAKE_REGNUM_P (regno))
13140 return FAKE_REGS;
13141
13142 return NO_REGS;
13143 }
13144
13145 /* OFFSET is an address offset for mode MODE, which has SIZE bytes.
13146 If OFFSET is out of range, return an offset of an anchor point
13147 that is in range. Return 0 otherwise. */
13148
13149 static HOST_WIDE_INT
13150 aarch64_anchor_offset (HOST_WIDE_INT offset, HOST_WIDE_INT size,
13151 machine_mode mode)
13152 {
13153 /* Does it look like we'll need a 16-byte load/store-pair operation? */
13154 if (size > 16)
13155 return (offset + 0x400) & ~0x7f0;
13156
13157 /* For offsets that aren't a multiple of the access size, the limit is
13158 -256...255. */
13159 if (offset & (size - 1))
13160 {
13161 /* BLKmode typically uses LDP of X-registers. */
13162 if (mode == BLKmode)
13163 return (offset + 512) & ~0x3ff;
13164 return (offset + 0x100) & ~0x1ff;
13165 }
13166
13167 /* Small negative offsets are supported. */
13168 if (IN_RANGE (offset, -256, 0))
13169 return 0;
13170
13171 if (mode == TImode || mode == TFmode || mode == TDmode)
13172 return (offset + 0x100) & ~0x1ff;
13173
13174 /* Use 12-bit offset by access size. */
13175 return offset & (~0xfff * size);
13176 }
13177
13178 static rtx
13179 aarch64_legitimize_address (rtx x, rtx /* orig_x */, machine_mode mode)
13180 {
13181 #if TARGET_PECOFF
13182 rtx tmp = legitimize_pe_coff_symbol (x, true);
13183 if (tmp)
13184 return tmp;
13185 #endif
13186
13187 /* Try to split X+CONST into Y=X+(CONST & ~mask), Y+(CONST&mask),
13188 where mask is selected by alignment and size of the offset.
13189 We try to pick as large a range for the offset as possible to
13190 maximize the chance of a CSE. However, for aligned addresses
13191 we limit the range to 4k so that structures with different sized
13192 elements are likely to use the same base. We need to be careful
13193 not to split a CONST for some forms of address expression, otherwise
13194 it will generate sub-optimal code. */
13195
13196 /* First split X + CONST (base, offset) into (base + X) + offset. */
13197 if (GET_CODE (x) == PLUS && GET_CODE (XEXP (x, 1)) == CONST)
13198 {
13199 poly_int64 offset;
13200 rtx base = strip_offset (XEXP (x, 1), &offset);
13201
13202 base = expand_binop (Pmode, add_optab, base, XEXP (x, 0),
13203 NULL_RTX, true, OPTAB_DIRECT);
13204 x = plus_constant (Pmode, base, offset);
13205 }
13206
13207 if (GET_CODE (x) == PLUS && CONST_INT_P (XEXP (x, 1)))
13208 {
13209 rtx base = XEXP (x, 0);
13210 rtx offset_rtx = XEXP (x, 1);
13211 HOST_WIDE_INT offset = INTVAL (offset_rtx);
13212
13213 if (GET_CODE (base) == PLUS)
13214 {
13215 rtx op0 = XEXP (base, 0);
13216 rtx op1 = XEXP (base, 1);
13217
13218 /* Force any scaling into a temp for CSE. */
13219 op0 = force_reg (Pmode, op0);
13220 op1 = force_reg (Pmode, op1);
13221
13222 /* Let the pointer register be in op0. */
13223 if (REG_POINTER (op1))
13224 std::swap (op0, op1);
13225
13226 /* If the pointer is virtual or frame related, then we know that
13227 virtual register instantiation or register elimination is going
13228 to apply a second constant. We want the two constants folded
13229 together easily. Therefore, emit as (OP0 + CONST) + OP1. */
13230 if (virt_or_elim_regno_p (REGNO (op0)))
13231 {
13232 base = expand_binop (Pmode, add_optab, op0, offset_rtx,
13233 NULL_RTX, true, OPTAB_DIRECT);
13234 return gen_rtx_PLUS (Pmode, base, op1);
13235 }
13236
13237 /* Otherwise, in order to encourage CSE (and thence loop strength
13238 reduce) scaled addresses, emit as (OP0 + OP1) + CONST. */
13239 base = expand_binop (Pmode, add_optab, op0, op1,
13240 NULL_RTX, true, OPTAB_DIRECT);
13241 x = gen_rtx_PLUS (Pmode, base, offset_rtx);
13242 }
13243
13244 HOST_WIDE_INT size;
13245 if (GET_MODE_SIZE (mode).is_constant (&size))
13246 {
13247 HOST_WIDE_INT base_offset = aarch64_anchor_offset (offset, size,
13248 mode);
13249 if (base_offset != 0)
13250 {
13251 base = plus_constant (Pmode, base, base_offset);
13252 base = force_operand (base, NULL_RTX);
13253 return plus_constant (Pmode, base, offset - base_offset);
13254 }
13255 }
13256 }
13257
13258 return x;
13259 }
13260
13261 static reg_class_t
13262 aarch64_secondary_reload (bool in_p ATTRIBUTE_UNUSED, rtx x,
13263 reg_class_t rclass,
13264 machine_mode mode,
13265 secondary_reload_info *sri)
13266 {
13267 /* Use aarch64_sve_reload_mem for SVE memory reloads that cannot use
13268 LDR and STR. See the comment at the head of aarch64-sve.md for
13269 more details about the big-endian handling. */
13270 unsigned int vec_flags = aarch64_classify_vector_mode (mode);
13271 if (reg_class_subset_p (rclass, FP_REGS)
13272 && !((REG_P (x) && HARD_REGISTER_P (x))
13273 || aarch64_simd_valid_mov_imm (x))
13274 && mode != VNx16QImode
13275 && (vec_flags & VEC_SVE_DATA)
13276 && ((vec_flags & VEC_PARTIAL) || BYTES_BIG_ENDIAN))
13277 {
13278 sri->icode = CODE_FOR_aarch64_sve_reload_mem;
13279 return NO_REGS;
13280 }
13281
13282 /* If we have to disable direct literal pool loads and stores because the
13283 function is too big, then we need a scratch register. */
13284 if (MEM_P (x) && SYMBOL_REF_P (x) && CONSTANT_POOL_ADDRESS_P (x)
13285 && (SCALAR_FLOAT_MODE_P (GET_MODE (x))
13286 || targetm.vector_mode_supported_p (GET_MODE (x)))
13287 && !aarch64_pcrelative_literal_loads)
13288 {
13289 sri->icode = code_for_aarch64_reload_movcp (mode, DImode);
13290 return NO_REGS;
13291 }
13292
13293 /* Without the TARGET_SIMD or TARGET_SVE instructions we cannot move a
13294 Q register to a Q register directly. We need a scratch. */
13295 if (REG_P (x)
13296 && (mode == TFmode
13297 || mode == TImode
13298 || mode == TDmode
13299 || (vec_flags == VEC_ADVSIMD && known_eq (GET_MODE_SIZE (mode), 16)))
13300 && mode == GET_MODE (x)
13301 && !TARGET_SIMD
13302 && FP_REGNUM_P (REGNO (x))
13303 && reg_class_subset_p (rclass, FP_REGS))
13304 {
13305 sri->icode = code_for_aarch64_reload_mov (mode);
13306 return NO_REGS;
13307 }
13308
13309 /* A TFmode, TImode or TDmode memory access should be handled via an FP_REGS
13310 because AArch64 has richer addressing modes for LDR/STR instructions
13311 than LDP/STP instructions. */
13312 if (TARGET_FLOAT && rclass == GENERAL_REGS
13313 && known_eq (GET_MODE_SIZE (mode), 16) && MEM_P (x))
13314 return FP_REGS;
13315
13316 if (rclass == FP_REGS
13317 && (mode == TImode || mode == TFmode || mode == TDmode)
13318 && CONSTANT_P(x))
13319 return GENERAL_REGS;
13320
13321 return NO_REGS;
13322 }
13323
13324 /* Implement TARGET_SECONDARY_MEMORY_NEEDED. */
13325
13326 static bool
13327 aarch64_secondary_memory_needed (machine_mode mode, reg_class_t class1,
13328 reg_class_t class2)
13329 {
13330 if (!TARGET_SIMD
13331 && reg_classes_intersect_p (class1, FP_REGS)
13332 && reg_classes_intersect_p (class2, FP_REGS))
13333 {
13334 /* We can't do a 128-bit FPR-to-FPR move without TARGET_SIMD,
13335 so we can't easily split a move involving tuples of 128-bit
13336 vectors. Force the copy through memory instead.
13337
13338 (Tuples of 64-bit vectors are fine.) */
13339 unsigned int vec_flags = aarch64_classify_vector_mode (mode);
13340 if (vec_flags == (VEC_ADVSIMD | VEC_STRUCT))
13341 return true;
13342 }
13343 return false;
13344 }
13345
13346 /* Implement TARGET_FRAME_POINTER_REQUIRED. */
13347
13348 static bool
13349 aarch64_frame_pointer_required ()
13350 {
13351 /* If the function needs to record the incoming value of PSTATE.SM,
13352 make sure that the slot is accessible from the frame pointer. */
13353 return aarch64_need_old_pstate_sm ();
13354 }
13355
13356 static bool
13357 aarch64_can_eliminate (const int from ATTRIBUTE_UNUSED, const int to)
13358 {
13359 gcc_assert (from == ARG_POINTER_REGNUM || from == FRAME_POINTER_REGNUM);
13360
13361 /* If we need a frame pointer, ARG_POINTER_REGNUM and FRAME_POINTER_REGNUM
13362 can only eliminate to HARD_FRAME_POINTER_REGNUM. */
13363 if (frame_pointer_needed)
13364 return to == HARD_FRAME_POINTER_REGNUM;
13365 return true;
13366 }
13367
13368 poly_int64
13369 aarch64_initial_elimination_offset (unsigned from, unsigned to)
13370 {
13371 aarch64_frame &frame = cfun->machine->frame;
13372
13373 if (to == HARD_FRAME_POINTER_REGNUM)
13374 {
13375 if (from == ARG_POINTER_REGNUM)
13376 return frame.bytes_above_hard_fp;
13377
13378 if (from == FRAME_POINTER_REGNUM)
13379 return frame.bytes_above_hard_fp - frame.bytes_above_locals;
13380 }
13381
13382 if (to == STACK_POINTER_REGNUM)
13383 {
13384 if (from == FRAME_POINTER_REGNUM)
13385 return frame.frame_size - frame.bytes_above_locals;
13386 }
13387
13388 return frame.frame_size;
13389 }
13390
13391
13392 /* Get return address without mangling. */
13393
13394 rtx
13395 aarch64_return_addr_rtx (void)
13396 {
13397 rtx val = get_hard_reg_initial_val (Pmode, LR_REGNUM);
13398 /* Note: aarch64_return_address_signing_enabled only
13399 works after cfun->machine->frame.laid_out is set,
13400 so here we don't know if the return address will
13401 be signed or not. */
13402 rtx lr = gen_rtx_REG (Pmode, LR_REGNUM);
13403 emit_move_insn (lr, val);
13404 emit_insn (GEN_FCN (CODE_FOR_xpaclri) ());
13405 return lr;
13406 }
13407
13408
13409 /* Implement RETURN_ADDR_RTX. We do not support moving back to a
13410 previous frame. */
13411
13412 rtx
13413 aarch64_return_addr (int count, rtx frame ATTRIBUTE_UNUSED)
13414 {
13415 if (count != 0)
13416 return const0_rtx;
13417 return aarch64_return_addr_rtx ();
13418 }
13419
13420 static void
13421 aarch64_asm_trampoline_template (FILE *f)
13422 {
13423 /* Even if the current function doesn't have branch protection, some
13424 later function might, so since this template is only generated once
13425 we have to add a BTI just in case. */
13426 asm_fprintf (f, "\thint\t34 // bti c\n");
13427
13428 if (TARGET_ILP32)
13429 {
13430 asm_fprintf (f, "\tldr\tw%d, .+20\n", IP1_REGNUM - R0_REGNUM);
13431 asm_fprintf (f, "\tldr\tw%d, .+20\n", STATIC_CHAIN_REGNUM - R0_REGNUM);
13432 }
13433 else
13434 {
13435 asm_fprintf (f, "\tldr\t%s, .+20\n", reg_names [IP1_REGNUM]);
13436 asm_fprintf (f, "\tldr\t%s, .+24\n", reg_names [STATIC_CHAIN_REGNUM]);
13437 }
13438 asm_fprintf (f, "\tbr\t%s\n", reg_names [IP1_REGNUM]);
13439
13440 /* We always emit a speculation barrier.
13441 This is because the same trampoline template is used for every nested
13442 function. Since nested functions are not particularly common or
13443 performant we don't worry too much about the extra instructions to copy
13444 around.
13445 This is not yet a problem, since we have not yet implemented function
13446 specific attributes to choose between hardening against straight line
13447 speculation or not, but such function specific attributes are likely to
13448 happen in the future. */
13449 asm_fprintf (f, "\tdsb\tsy\n\tisb\n");
13450
13451 assemble_aligned_integer (POINTER_BYTES, const0_rtx);
13452 assemble_aligned_integer (POINTER_BYTES, const0_rtx);
13453 }
13454
13455 static void
13456 aarch64_trampoline_init (rtx m_tramp, tree fndecl, rtx chain_value)
13457 {
13458 rtx fnaddr, mem, a_tramp;
13459 const int tramp_code_sz = 24;
13460
13461 /* Don't need to copy the trailing D-words, we fill those in below. */
13462 /* We create our own memory address in Pmode so that `emit_block_move` can
13463 use parts of the backend which expect Pmode addresses. */
13464 rtx temp = convert_memory_address (Pmode, XEXP (m_tramp, 0));
13465 emit_block_move (gen_rtx_MEM (BLKmode, temp),
13466 assemble_trampoline_template (),
13467 GEN_INT (tramp_code_sz), BLOCK_OP_NORMAL);
13468 mem = adjust_address (m_tramp, ptr_mode, tramp_code_sz);
13469 fnaddr = XEXP (DECL_RTL (fndecl), 0);
13470 if (GET_MODE (fnaddr) != ptr_mode)
13471 fnaddr = convert_memory_address (ptr_mode, fnaddr);
13472 emit_move_insn (mem, fnaddr);
13473
13474 mem = adjust_address (m_tramp, ptr_mode, tramp_code_sz + POINTER_BYTES);
13475 emit_move_insn (mem, chain_value);
13476
13477 /* XXX We should really define a "clear_cache" pattern and use
13478 gen_clear_cache(). */
13479 a_tramp = XEXP (m_tramp, 0);
13480 maybe_emit_call_builtin___clear_cache (a_tramp,
13481 plus_constant (ptr_mode,
13482 a_tramp,
13483 TRAMPOLINE_SIZE));
13484 }
13485
13486 static unsigned char
13487 aarch64_class_max_nregs (reg_class_t regclass, machine_mode mode)
13488 {
13489 /* ??? Logically we should only need to provide a value when
13490 HARD_REGNO_MODE_OK says that at least one register in REGCLASS
13491 can hold MODE, but at the moment we need to handle all modes.
13492 Just ignore any runtime parts for registers that can't store them. */
13493 HOST_WIDE_INT lowest_size = constant_lower_bound (GET_MODE_SIZE (mode));
13494 unsigned int nregs, vec_flags;
13495 switch (regclass)
13496 {
13497 case W8_W11_REGS:
13498 case W12_W15_REGS:
13499 case STUB_REGS:
13500 case TAILCALL_ADDR_REGS:
13501 case POINTER_REGS:
13502 case GENERAL_REGS:
13503 case ALL_REGS:
13504 case POINTER_AND_FP_REGS:
13505 case FP_REGS:
13506 case FP_LO_REGS:
13507 case FP_LO8_REGS:
13508 vec_flags = aarch64_classify_vector_mode (mode);
13509 if ((vec_flags & VEC_SVE_DATA)
13510 && constant_multiple_p (GET_MODE_SIZE (mode),
13511 aarch64_vl_bytes (mode, vec_flags), &nregs))
13512 return nregs;
13513 if (vec_flags == (VEC_ADVSIMD | VEC_STRUCT | VEC_PARTIAL))
13514 return GET_MODE_SIZE (mode).to_constant () / 8;
13515 return (vec_flags & VEC_ADVSIMD
13516 ? CEIL (lowest_size, UNITS_PER_VREG)
13517 : CEIL (lowest_size, UNITS_PER_WORD));
13518
13519 case PR_REGS:
13520 case PR_LO_REGS:
13521 case PR_HI_REGS:
13522 return mode == VNx64BImode ? 4 : mode == VNx32BImode ? 2 : 1;
13523
13524 case MOVEABLE_SYSREGS:
13525 case STACK_REG:
13526 case FFR_REGS:
13527 case PR_AND_FFR_REGS:
13528 case FAKE_REGS:
13529 return 1;
13530
13531 case NO_REGS:
13532 return 0;
13533
13534 default:
13535 break;
13536 }
13537 gcc_unreachable ();
13538 }
13539
13540 static reg_class_t
13541 aarch64_preferred_reload_class (rtx x, reg_class_t regclass)
13542 {
13543 if (regclass == POINTER_REGS)
13544 return GENERAL_REGS;
13545
13546 if (regclass == STACK_REG)
13547 {
13548 if (REG_P(x)
13549 && reg_class_subset_p (REGNO_REG_CLASS (REGNO (x)), POINTER_REGS))
13550 return regclass;
13551
13552 return NO_REGS;
13553 }
13554
13555 /* Register eliminiation can result in a request for
13556 SP+constant->FP_REGS. We cannot support such operations which
13557 use SP as source and an FP_REG as destination, so reject out
13558 right now. */
13559 if (! reg_class_subset_p (regclass, GENERAL_REGS) && GET_CODE (x) == PLUS)
13560 {
13561 rtx lhs = XEXP (x, 0);
13562
13563 /* Look through a possible SUBREG introduced by ILP32. */
13564 if (SUBREG_P (lhs))
13565 lhs = SUBREG_REG (lhs);
13566
13567 gcc_assert (REG_P (lhs));
13568 gcc_assert (reg_class_subset_p (REGNO_REG_CLASS (REGNO (lhs)),
13569 POINTER_REGS));
13570 return NO_REGS;
13571 }
13572
13573 return regclass;
13574 }
13575
13576 void
13577 aarch64_asm_output_labelref (FILE* f, const char *name)
13578 {
13579 asm_fprintf (f, "%U%s", name);
13580 }
13581
13582 static void
13583 aarch64_elf_asm_constructor (rtx symbol, int priority)
13584 {
13585 if (priority == DEFAULT_INIT_PRIORITY)
13586 default_ctor_section_asm_out_constructor (symbol, priority);
13587 else
13588 {
13589 section *s;
13590 /* While priority is known to be in range [0, 65535], so 18 bytes
13591 would be enough, the compiler might not know that. To avoid
13592 -Wformat-truncation false positive, use a larger size. */
13593 char buf[23];
13594 snprintf (buf, sizeof (buf), ".init_array.%.5u", priority);
13595 s = get_section (buf, SECTION_WRITE | SECTION_NOTYPE, NULL);
13596 switch_to_section (s);
13597 assemble_align (POINTER_SIZE);
13598 assemble_aligned_integer (POINTER_BYTES, symbol);
13599 }
13600 }
13601
13602 static void
13603 aarch64_elf_asm_destructor (rtx symbol, int priority)
13604 {
13605 if (priority == DEFAULT_INIT_PRIORITY)
13606 default_dtor_section_asm_out_destructor (symbol, priority);
13607 else
13608 {
13609 section *s;
13610 /* While priority is known to be in range [0, 65535], so 18 bytes
13611 would be enough, the compiler might not know that. To avoid
13612 -Wformat-truncation false positive, use a larger size. */
13613 char buf[23];
13614 snprintf (buf, sizeof (buf), ".fini_array.%.5u", priority);
13615 s = get_section (buf, SECTION_WRITE | SECTION_NOTYPE, NULL);
13616 switch_to_section (s);
13617 assemble_align (POINTER_SIZE);
13618 assemble_aligned_integer (POINTER_BYTES, symbol);
13619 }
13620 }
13621
13622 const char*
13623 aarch64_output_casesi (rtx *operands)
13624 {
13625 char buf[100];
13626 char label[100];
13627 rtx diff_vec = PATTERN (NEXT_INSN (as_a <rtx_insn *> (operands[2])));
13628 int index;
13629 static const char *const patterns[4][2] =
13630 {
13631 {
13632 "ldrb\t%w3, [%0,%w1,uxtw]",
13633 "add\t%3, %4, %w3, sxtb #2"
13634 },
13635 {
13636 "ldrh\t%w3, [%0,%w1,uxtw #1]",
13637 "add\t%3, %4, %w3, sxth #2"
13638 },
13639 {
13640 "ldr\t%w3, [%0,%w1,uxtw #2]",
13641 "add\t%3, %4, %w3, sxtw #2"
13642 },
13643 /* We assume that DImode is only generated when not optimizing and
13644 that we don't really need 64-bit address offsets. That would
13645 imply an object file with 8GB of code in a single function! */
13646 {
13647 "ldr\t%w3, [%0,%w1,uxtw #2]",
13648 "add\t%3, %4, %w3, sxtw #2"
13649 }
13650 };
13651
13652 gcc_assert (GET_CODE (diff_vec) == ADDR_DIFF_VEC);
13653
13654 scalar_int_mode mode = as_a <scalar_int_mode> (GET_MODE (diff_vec));
13655 index = exact_log2 (GET_MODE_SIZE (mode));
13656
13657 gcc_assert (index >= 0 && index <= 3);
13658
13659 /* Need to implement table size reduction, by chaning the code below. */
13660 output_asm_insn (patterns[index][0], operands);
13661 ASM_GENERATE_INTERNAL_LABEL (label, "Lrtx", CODE_LABEL_NUMBER (operands[2]));
13662 snprintf (buf, sizeof (buf),
13663 "adr\t%%4, %s", targetm.strip_name_encoding (label));
13664 output_asm_insn (buf, operands);
13665 output_asm_insn (patterns[index][1], operands);
13666 output_asm_insn ("br\t%3", operands);
13667 output_asm_insn (aarch64_sls_barrier (aarch64_harden_sls_retbr_p ()),
13668 operands);
13669 assemble_label (asm_out_file, label);
13670 return "";
13671 }
13672
13673 /* Return the asm string for an SME ZERO instruction whose 8-bit mask
13674 operand is MASK. */
13675 const char *
13676 aarch64_output_sme_zero_za (rtx mask)
13677 {
13678 auto mask_val = UINTVAL (mask);
13679 if (mask_val == 0)
13680 return "zero\t{}";
13681
13682 if (mask_val == 0xff)
13683 return "zero\t{ za }";
13684
13685 static constexpr struct { unsigned char mask; char letter; } tiles[] = {
13686 { 0xff, 'b' },
13687 { 0x55, 'h' },
13688 { 0x11, 's' },
13689 { 0x01, 'd' }
13690 };
13691 /* The last entry in the list has the form "za7.d }", but that's the
13692 same length as "za7.d, ". */
13693 static char buffer[sizeof("zero\t{ ") + sizeof ("za7.d, ") * 8 + 1];
13694 for (auto &tile : tiles)
13695 {
13696 unsigned int tile_mask = tile.mask;
13697 unsigned int tile_index = 0;
13698 unsigned int i = snprintf (buffer, sizeof (buffer), "zero\t");
13699 const char *prefix = "{ ";
13700 auto remaining_mask = mask_val;
13701 while (tile_mask < 0x100)
13702 {
13703 if ((remaining_mask & tile_mask) == tile_mask)
13704 {
13705 i += snprintf (buffer + i, sizeof (buffer) - i, "%sza%d.%c",
13706 prefix, tile_index, tile.letter);
13707 prefix = ", ";
13708 remaining_mask &= ~tile_mask;
13709 }
13710 tile_mask <<= 1;
13711 tile_index += 1;
13712 }
13713 if (remaining_mask == 0)
13714 {
13715 gcc_assert (i + 3 <= sizeof (buffer));
13716 snprintf (buffer + i, sizeof (buffer) - i, " }");
13717 return buffer;
13718 }
13719 }
13720 gcc_unreachable ();
13721 }
13722
13723 /* Return size in bits of an arithmetic operand which is shifted/scaled and
13724 masked such that it is suitable for a UXTB, UXTH, or UXTW extend
13725 operator. */
13726
13727 int
13728 aarch64_uxt_size (int shift, HOST_WIDE_INT mask)
13729 {
13730 if (shift >= 0 && shift <= 4)
13731 {
13732 int size;
13733 for (size = 8; size <= 32; size *= 2)
13734 {
13735 HOST_WIDE_INT bits = ((HOST_WIDE_INT)1U << size) - 1;
13736 if (mask == bits << shift)
13737 return size;
13738 }
13739 }
13740 return 0;
13741 }
13742
13743 /* Constant pools are per function only when PC relative
13744 literal loads are true or we are in the large memory
13745 model. */
13746
13747 static inline bool
13748 aarch64_can_use_per_function_literal_pools_p (void)
13749 {
13750 return (aarch64_pcrelative_literal_loads
13751 || aarch64_cmodel == AARCH64_CMODEL_LARGE);
13752 }
13753
13754 static bool
13755 aarch64_use_blocks_for_constant_p (machine_mode, const_rtx)
13756 {
13757 /* We can't use blocks for constants when we're using a per-function
13758 constant pool. */
13759 return !aarch64_can_use_per_function_literal_pools_p ();
13760 }
13761
13762 /* Select appropriate section for constants depending
13763 on where we place literal pools. */
13764
13765 static section *
13766 aarch64_select_rtx_section (machine_mode mode,
13767 rtx x,
13768 unsigned HOST_WIDE_INT align)
13769 {
13770 if (aarch64_can_use_per_function_literal_pools_p ())
13771 return function_section (current_function_decl);
13772
13773 return default_elf_select_rtx_section (mode, x, align);
13774 }
13775
13776 /* Implement ASM_OUTPUT_POOL_EPILOGUE. */
13777 void
13778 aarch64_asm_output_pool_epilogue (FILE *f, const char *, tree,
13779 HOST_WIDE_INT offset)
13780 {
13781 /* When using per-function literal pools, we must ensure that any code
13782 section is aligned to the minimal instruction length, lest we get
13783 errors from the assembler re "unaligned instructions". */
13784 if ((offset & 3) && aarch64_can_use_per_function_literal_pools_p ())
13785 ASM_OUTPUT_ALIGN (f, 2);
13786 }
13787
13788 /* Costs. */
13789
13790 /* Helper function for rtx cost calculation. Strip a shift expression
13791 from X. Returns the inner operand if successful, or the original
13792 expression on failure. */
13793 static rtx
13794 aarch64_strip_shift (rtx x)
13795 {
13796 rtx op = x;
13797
13798 /* We accept both ROTATERT and ROTATE: since the RHS must be a constant
13799 we can convert both to ROR during final output. */
13800 if ((GET_CODE (op) == ASHIFT
13801 || GET_CODE (op) == ASHIFTRT
13802 || GET_CODE (op) == LSHIFTRT
13803 || GET_CODE (op) == ROTATERT
13804 || GET_CODE (op) == ROTATE)
13805 && CONST_INT_P (XEXP (op, 1)))
13806 return XEXP (op, 0);
13807
13808 if (GET_CODE (op) == MULT
13809 && CONST_INT_P (XEXP (op, 1))
13810 && ((unsigned) exact_log2 (INTVAL (XEXP (op, 1)))) < 64)
13811 return XEXP (op, 0);
13812
13813 return x;
13814 }
13815
13816 /* Helper function for rtx cost calculation. Strip an extend
13817 expression from X. Returns the inner operand if successful, or the
13818 original expression on failure. We deal with a number of possible
13819 canonicalization variations here. If STRIP_SHIFT is true, then
13820 we can strip off a shift also. */
13821 static rtx
13822 aarch64_strip_extend (rtx x, bool strip_shift)
13823 {
13824 scalar_int_mode mode;
13825 rtx op = x;
13826
13827 if (!is_a <scalar_int_mode> (GET_MODE (op), &mode))
13828 return op;
13829
13830 if (GET_CODE (op) == AND
13831 && GET_CODE (XEXP (op, 0)) == MULT
13832 && CONST_INT_P (XEXP (XEXP (op, 0), 1))
13833 && CONST_INT_P (XEXP (op, 1))
13834 && aarch64_uxt_size (exact_log2 (INTVAL (XEXP (XEXP (op, 0), 1))),
13835 INTVAL (XEXP (op, 1))) != 0)
13836 return XEXP (XEXP (op, 0), 0);
13837
13838 /* Now handle extended register, as this may also have an optional
13839 left shift by 1..4. */
13840 if (strip_shift
13841 && GET_CODE (op) == ASHIFT
13842 && CONST_INT_P (XEXP (op, 1))
13843 && ((unsigned HOST_WIDE_INT) INTVAL (XEXP (op, 1))) <= 4)
13844 op = XEXP (op, 0);
13845
13846 if (GET_CODE (op) == ZERO_EXTEND
13847 || GET_CODE (op) == SIGN_EXTEND)
13848 op = XEXP (op, 0);
13849
13850 if (op != x)
13851 return op;
13852
13853 return x;
13854 }
13855
13856 /* Helper function for rtx cost calculation. Strip extension as well as any
13857 inner VEC_SELECT high-half from X. Returns the inner vector operand if
13858 successful, or the original expression on failure. */
13859 static rtx
13860 aarch64_strip_extend_vec_half (rtx x)
13861 {
13862 if (GET_CODE (x) == ZERO_EXTEND || GET_CODE (x) == SIGN_EXTEND)
13863 {
13864 x = XEXP (x, 0);
13865 if (GET_CODE (x) == VEC_SELECT
13866 && vec_series_highpart_p (GET_MODE (x), GET_MODE (XEXP (x, 0)),
13867 XEXP (x, 1)))
13868 x = XEXP (x, 0);
13869 }
13870 return x;
13871 }
13872
13873 /* Helper function for rtx cost calculation. Strip VEC_DUPLICATE as well as
13874 any subsequent extend and VEC_SELECT from X. Returns the inner scalar
13875 operand if successful, or the original expression on failure. */
13876 static rtx
13877 aarch64_strip_duplicate_vec_elt (rtx x)
13878 {
13879 if (GET_CODE (x) == VEC_DUPLICATE
13880 && is_a<scalar_mode> (GET_MODE (XEXP (x, 0))))
13881 {
13882 x = XEXP (x, 0);
13883 if (GET_CODE (x) == VEC_SELECT)
13884 x = XEXP (x, 0);
13885 else if ((GET_CODE (x) == ZERO_EXTEND || GET_CODE (x) == SIGN_EXTEND)
13886 && GET_CODE (XEXP (x, 0)) == VEC_SELECT)
13887 x = XEXP (XEXP (x, 0), 0);
13888 }
13889 return x;
13890 }
13891
13892 /* Return true iff CODE is a shift supported in combination
13893 with arithmetic instructions. */
13894
13895 static bool
13896 aarch64_shift_p (enum rtx_code code)
13897 {
13898 return code == ASHIFT || code == ASHIFTRT || code == LSHIFTRT;
13899 }
13900
13901
13902 /* Return true iff X is a cheap shift without a sign extend. */
13903
13904 static bool
13905 aarch64_cheap_mult_shift_p (rtx x)
13906 {
13907 rtx op0, op1;
13908
13909 op0 = XEXP (x, 0);
13910 op1 = XEXP (x, 1);
13911
13912 if (!(aarch64_tune_params.extra_tuning_flags
13913 & AARCH64_EXTRA_TUNE_CHEAP_SHIFT_EXTEND))
13914 return false;
13915
13916 if (GET_CODE (op0) == SIGN_EXTEND)
13917 return false;
13918
13919 if (GET_CODE (x) == ASHIFT && CONST_INT_P (op1)
13920 && UINTVAL (op1) <= 4)
13921 return true;
13922
13923 if (GET_CODE (x) != MULT || !CONST_INT_P (op1))
13924 return false;
13925
13926 HOST_WIDE_INT l2 = exact_log2 (INTVAL (op1));
13927
13928 if (l2 > 0 && l2 <= 4)
13929 return true;
13930
13931 return false;
13932 }
13933
13934 /* Helper function for rtx cost calculation. Calculate the cost of
13935 a MULT or ASHIFT, which may be part of a compound PLUS/MINUS rtx.
13936 Return the calculated cost of the expression, recursing manually in to
13937 operands where needed. */
13938
13939 static int
13940 aarch64_rtx_mult_cost (rtx x, enum rtx_code code, int outer, bool speed)
13941 {
13942 rtx op0, op1;
13943 const struct cpu_cost_table *extra_cost
13944 = aarch64_tune_params.insn_extra_cost;
13945 int cost = 0;
13946 bool compound_p = (outer == PLUS || outer == MINUS);
13947 machine_mode mode = GET_MODE (x);
13948
13949 gcc_checking_assert (code == MULT);
13950
13951 op0 = XEXP (x, 0);
13952 op1 = XEXP (x, 1);
13953
13954 if (VECTOR_MODE_P (mode))
13955 {
13956 unsigned int vec_flags = aarch64_classify_vector_mode (mode);
13957 if (TARGET_SIMD && (vec_flags & VEC_ADVSIMD))
13958 {
13959 /* The select-operand-high-half versions of the instruction have the
13960 same cost as the three vector version - don't add the costs of the
13961 extension or selection into the costs of the multiply. */
13962 op0 = aarch64_strip_extend_vec_half (op0);
13963 op1 = aarch64_strip_extend_vec_half (op1);
13964 /* The by-element versions of the instruction have the same costs as
13965 the normal 3-vector version. We make an assumption that the input
13966 to the VEC_DUPLICATE is already on the FP & SIMD side. This means
13967 costing of a MUL by element pre RA is a bit optimistic. */
13968 op0 = aarch64_strip_duplicate_vec_elt (op0);
13969 op1 = aarch64_strip_duplicate_vec_elt (op1);
13970 }
13971 cost += rtx_cost (op0, mode, MULT, 0, speed);
13972 cost += rtx_cost (op1, mode, MULT, 1, speed);
13973 if (speed)
13974 {
13975 if (GET_CODE (x) == MULT)
13976 cost += extra_cost->vect.mult;
13977 /* This is to catch the SSRA costing currently flowing here. */
13978 else
13979 cost += extra_cost->vect.alu;
13980 }
13981 return cost;
13982 }
13983
13984 /* Integer multiply/fma. */
13985 if (GET_MODE_CLASS (mode) == MODE_INT)
13986 {
13987 /* The multiply will be canonicalized as a shift, cost it as such. */
13988 if (aarch64_shift_p (GET_CODE (x))
13989 || (CONST_INT_P (op1)
13990 && exact_log2 (INTVAL (op1)) > 0))
13991 {
13992 bool is_extend = GET_CODE (op0) == ZERO_EXTEND
13993 || GET_CODE (op0) == SIGN_EXTEND;
13994 if (speed)
13995 {
13996 if (compound_p)
13997 {
13998 /* If the shift is considered cheap,
13999 then don't add any cost. */
14000 if (aarch64_cheap_mult_shift_p (x))
14001 ;
14002 else if (REG_P (op1))
14003 /* ARITH + shift-by-register. */
14004 cost += extra_cost->alu.arith_shift_reg;
14005 else if (is_extend)
14006 /* ARITH + extended register. We don't have a cost field
14007 for ARITH+EXTEND+SHIFT, so use extend_arith here. */
14008 cost += extra_cost->alu.extend_arith;
14009 else
14010 /* ARITH + shift-by-immediate. */
14011 cost += extra_cost->alu.arith_shift;
14012 }
14013 else
14014 /* LSL (immediate). */
14015 cost += extra_cost->alu.shift;
14016
14017 }
14018 /* Strip extends as we will have costed them in the case above. */
14019 if (is_extend)
14020 op0 = aarch64_strip_extend (op0, true);
14021
14022 cost += rtx_cost (op0, VOIDmode, code, 0, speed);
14023
14024 return cost;
14025 }
14026
14027 /* MNEG or [US]MNEGL. Extract the NEG operand and indicate that it's a
14028 compound and let the below cases handle it. After all, MNEG is a
14029 special-case alias of MSUB. */
14030 if (GET_CODE (op0) == NEG)
14031 {
14032 op0 = XEXP (op0, 0);
14033 compound_p = true;
14034 }
14035
14036 /* Integer multiplies or FMAs have zero/sign extending variants. */
14037 if ((GET_CODE (op0) == ZERO_EXTEND
14038 && GET_CODE (op1) == ZERO_EXTEND)
14039 || (GET_CODE (op0) == SIGN_EXTEND
14040 && GET_CODE (op1) == SIGN_EXTEND))
14041 {
14042 cost += rtx_cost (XEXP (op0, 0), VOIDmode, MULT, 0, speed);
14043 cost += rtx_cost (XEXP (op1, 0), VOIDmode, MULT, 1, speed);
14044
14045 if (speed)
14046 {
14047 if (compound_p)
14048 /* SMADDL/UMADDL/UMSUBL/SMSUBL. */
14049 cost += extra_cost->mult[0].extend_add;
14050 else
14051 /* MUL/SMULL/UMULL. */
14052 cost += extra_cost->mult[0].extend;
14053 }
14054
14055 return cost;
14056 }
14057
14058 /* This is either an integer multiply or a MADD. In both cases
14059 we want to recurse and cost the operands. */
14060 cost += rtx_cost (op0, mode, MULT, 0, speed);
14061 cost += rtx_cost (op1, mode, MULT, 1, speed);
14062
14063 if (speed)
14064 {
14065 if (compound_p)
14066 /* MADD/MSUB. */
14067 cost += extra_cost->mult[mode == DImode].add;
14068 else
14069 /* MUL. */
14070 cost += extra_cost->mult[mode == DImode].simple;
14071 }
14072
14073 return cost;
14074 }
14075 else
14076 {
14077 if (speed)
14078 {
14079 /* Floating-point FMA/FMUL can also support negations of the
14080 operands, unless the rounding mode is upward or downward in
14081 which case FNMUL is different than FMUL with operand negation. */
14082 bool neg0 = GET_CODE (op0) == NEG;
14083 bool neg1 = GET_CODE (op1) == NEG;
14084 if (compound_p || !flag_rounding_math || (neg0 && neg1))
14085 {
14086 if (neg0)
14087 op0 = XEXP (op0, 0);
14088 if (neg1)
14089 op1 = XEXP (op1, 0);
14090 }
14091
14092 if (compound_p)
14093 /* FMADD/FNMADD/FNMSUB/FMSUB. */
14094 cost += extra_cost->fp[mode == DFmode].fma;
14095 else
14096 /* FMUL/FNMUL. */
14097 cost += extra_cost->fp[mode == DFmode].mult;
14098 }
14099
14100 cost += rtx_cost (op0, mode, MULT, 0, speed);
14101 cost += rtx_cost (op1, mode, MULT, 1, speed);
14102 return cost;
14103 }
14104 }
14105
14106 static int
14107 aarch64_address_cost (rtx x,
14108 machine_mode mode,
14109 addr_space_t as ATTRIBUTE_UNUSED,
14110 bool speed)
14111 {
14112 enum rtx_code c = GET_CODE (x);
14113 const struct cpu_addrcost_table *addr_cost = aarch64_tune_params.addr_cost;
14114 struct aarch64_address_info info;
14115 int cost = 0;
14116 info.shift = 0;
14117
14118 if (!aarch64_classify_address (&info, x, mode, false))
14119 {
14120 if (GET_CODE (x) == CONST || SYMBOL_REF_P (x))
14121 {
14122 /* This is a CONST or SYMBOL ref which will be split
14123 in a different way depending on the code model in use.
14124 Cost it through the generic infrastructure. */
14125 int cost_symbol_ref = rtx_cost (x, Pmode, MEM, 1, speed);
14126 /* Divide through by the cost of one instruction to
14127 bring it to the same units as the address costs. */
14128 cost_symbol_ref /= COSTS_N_INSNS (1);
14129 /* The cost is then the cost of preparing the address,
14130 followed by an immediate (possibly 0) offset. */
14131 return cost_symbol_ref + addr_cost->imm_offset;
14132 }
14133 else
14134 {
14135 /* This is most likely a jump table from a case
14136 statement. */
14137 return addr_cost->register_offset;
14138 }
14139 }
14140
14141 switch (info.type)
14142 {
14143 case ADDRESS_LO_SUM:
14144 case ADDRESS_SYMBOLIC:
14145 case ADDRESS_REG_IMM:
14146 cost += addr_cost->imm_offset;
14147 break;
14148
14149 case ADDRESS_REG_WB:
14150 if (c == PRE_INC || c == PRE_DEC || c == PRE_MODIFY)
14151 cost += addr_cost->pre_modify;
14152 else if (c == POST_INC || c == POST_DEC || c == POST_MODIFY)
14153 {
14154 unsigned int nvectors = aarch64_ldn_stn_vectors (mode);
14155 if (nvectors == 3)
14156 cost += addr_cost->post_modify_ld3_st3;
14157 else if (nvectors == 4)
14158 cost += addr_cost->post_modify_ld4_st4;
14159 else
14160 cost += addr_cost->post_modify;
14161 }
14162 else
14163 gcc_unreachable ();
14164
14165 break;
14166
14167 case ADDRESS_REG_REG:
14168 cost += addr_cost->register_offset;
14169 break;
14170
14171 case ADDRESS_REG_SXTW:
14172 cost += addr_cost->register_sextend;
14173 break;
14174
14175 case ADDRESS_REG_UXTW:
14176 cost += addr_cost->register_zextend;
14177 break;
14178
14179 default:
14180 gcc_unreachable ();
14181 }
14182
14183
14184 if (info.shift > 0)
14185 {
14186 /* For the sake of calculating the cost of the shifted register
14187 component, we can treat same sized modes in the same way. */
14188 if (known_eq (GET_MODE_BITSIZE (mode), 16))
14189 cost += addr_cost->addr_scale_costs.hi;
14190 else if (known_eq (GET_MODE_BITSIZE (mode), 32))
14191 cost += addr_cost->addr_scale_costs.si;
14192 else if (known_eq (GET_MODE_BITSIZE (mode), 64))
14193 cost += addr_cost->addr_scale_costs.di;
14194 else
14195 /* We can't tell, or this is a 128-bit vector. */
14196 cost += addr_cost->addr_scale_costs.ti;
14197 }
14198
14199 return cost;
14200 }
14201
14202 /* Return the cost of a branch. If SPEED_P is true then the compiler is
14203 optimizing for speed. If PREDICTABLE_P is true then the branch is predicted
14204 to be taken. */
14205
14206 int
14207 aarch64_branch_cost (bool speed_p, bool predictable_p)
14208 {
14209 /* When optimizing for speed, use the cost of unpredictable branches. */
14210 const struct cpu_branch_cost *branch_costs =
14211 aarch64_tune_params.branch_costs;
14212
14213 if (!speed_p || predictable_p)
14214 return branch_costs->predictable;
14215 else
14216 return branch_costs->unpredictable;
14217 }
14218
14219 /* Return true if X is a zero or sign extract
14220 usable in an ADD or SUB (extended register) instruction. */
14221 static bool
14222 aarch64_rtx_arith_op_extract_p (rtx x)
14223 {
14224 /* The simple case <ARITH>, XD, XN, XM, [us]xt.
14225 No shift. */
14226 if (GET_CODE (x) == SIGN_EXTEND
14227 || GET_CODE (x) == ZERO_EXTEND)
14228 return REG_P (XEXP (x, 0));
14229
14230 return false;
14231 }
14232
14233 static bool
14234 aarch64_frint_unspec_p (unsigned int u)
14235 {
14236 switch (u)
14237 {
14238 case UNSPEC_FRINTZ:
14239 case UNSPEC_FRINTP:
14240 case UNSPEC_FRINTM:
14241 case UNSPEC_FRINTA:
14242 case UNSPEC_FRINTN:
14243 case UNSPEC_FRINTX:
14244 case UNSPEC_FRINTI:
14245 return true;
14246
14247 default:
14248 return false;
14249 }
14250 }
14251
14252 /* Return true iff X is an rtx that will match an extr instruction
14253 i.e. as described in the *extr<mode>5_insn family of patterns.
14254 OP0 and OP1 will be set to the operands of the shifts involved
14255 on success and will be NULL_RTX otherwise. */
14256
14257 static bool
14258 aarch64_extr_rtx_p (rtx x, rtx *res_op0, rtx *res_op1)
14259 {
14260 rtx op0, op1;
14261 scalar_int_mode mode;
14262 if (!is_a <scalar_int_mode> (GET_MODE (x), &mode))
14263 return false;
14264
14265 *res_op0 = NULL_RTX;
14266 *res_op1 = NULL_RTX;
14267
14268 if (GET_CODE (x) != IOR)
14269 return false;
14270
14271 op0 = XEXP (x, 0);
14272 op1 = XEXP (x, 1);
14273
14274 if ((GET_CODE (op0) == ASHIFT && GET_CODE (op1) == LSHIFTRT)
14275 || (GET_CODE (op1) == ASHIFT && GET_CODE (op0) == LSHIFTRT))
14276 {
14277 /* Canonicalise locally to ashift in op0, lshiftrt in op1. */
14278 if (GET_CODE (op1) == ASHIFT)
14279 std::swap (op0, op1);
14280
14281 if (!CONST_INT_P (XEXP (op0, 1)) || !CONST_INT_P (XEXP (op1, 1)))
14282 return false;
14283
14284 unsigned HOST_WIDE_INT shft_amnt_0 = UINTVAL (XEXP (op0, 1));
14285 unsigned HOST_WIDE_INT shft_amnt_1 = UINTVAL (XEXP (op1, 1));
14286
14287 if (shft_amnt_0 < GET_MODE_BITSIZE (mode)
14288 && shft_amnt_0 + shft_amnt_1 == GET_MODE_BITSIZE (mode))
14289 {
14290 *res_op0 = XEXP (op0, 0);
14291 *res_op1 = XEXP (op1, 0);
14292 return true;
14293 }
14294 }
14295
14296 return false;
14297 }
14298
14299 /* Calculate the cost of calculating (if_then_else (OP0) (OP1) (OP2)),
14300 storing it in *COST. Result is true if the total cost of the operation
14301 has now been calculated. */
14302 static bool
14303 aarch64_if_then_else_costs (rtx op0, rtx op1, rtx op2, int *cost, bool speed)
14304 {
14305 rtx inner;
14306 rtx comparator;
14307 enum rtx_code cmpcode;
14308 const struct cpu_cost_table *extra_cost
14309 = aarch64_tune_params.insn_extra_cost;
14310
14311 if (COMPARISON_P (op0))
14312 {
14313 inner = XEXP (op0, 0);
14314 comparator = XEXP (op0, 1);
14315 cmpcode = GET_CODE (op0);
14316 }
14317 else
14318 {
14319 inner = op0;
14320 comparator = const0_rtx;
14321 cmpcode = NE;
14322 }
14323
14324 if (GET_CODE (op1) == PC || GET_CODE (op2) == PC)
14325 {
14326 /* Conditional branch. */
14327 if (GET_MODE_CLASS (GET_MODE (inner)) == MODE_CC)
14328 return true;
14329 else
14330 {
14331 if (cmpcode == NE || cmpcode == EQ)
14332 {
14333 if (comparator == const0_rtx)
14334 {
14335 /* TBZ/TBNZ/CBZ/CBNZ. */
14336 if (GET_CODE (inner) == ZERO_EXTRACT)
14337 /* TBZ/TBNZ. */
14338 *cost += rtx_cost (XEXP (inner, 0), VOIDmode,
14339 ZERO_EXTRACT, 0, speed);
14340 else
14341 /* CBZ/CBNZ. */
14342 *cost += rtx_cost (inner, VOIDmode, cmpcode, 0, speed);
14343
14344 return true;
14345 }
14346 if (register_operand (inner, VOIDmode)
14347 && aarch64_imm24 (comparator, VOIDmode))
14348 {
14349 /* SUB and SUBS. */
14350 *cost += COSTS_N_INSNS (2);
14351 if (speed)
14352 *cost += extra_cost->alu.arith * 2;
14353 return true;
14354 }
14355 }
14356 else if (cmpcode == LT || cmpcode == GE)
14357 {
14358 /* TBZ/TBNZ. */
14359 if (comparator == const0_rtx)
14360 return true;
14361 }
14362 }
14363 }
14364 else if (GET_MODE_CLASS (GET_MODE (inner)) == MODE_CC)
14365 {
14366 /* CCMP. */
14367 if (GET_CODE (op1) == COMPARE)
14368 {
14369 /* Increase cost of CCMP reg, 0, imm, CC to prefer CMP reg, 0. */
14370 if (XEXP (op1, 1) == const0_rtx)
14371 *cost += 1;
14372 if (speed)
14373 {
14374 machine_mode mode = GET_MODE (XEXP (op1, 0));
14375
14376 if (GET_MODE_CLASS (mode) == MODE_INT)
14377 *cost += extra_cost->alu.arith;
14378 else
14379 *cost += extra_cost->fp[mode == DFmode].compare;
14380 }
14381 return true;
14382 }
14383
14384 /* It's a conditional operation based on the status flags,
14385 so it must be some flavor of CSEL. */
14386
14387 /* CSNEG, CSINV, and CSINC are handled for free as part of CSEL. */
14388 if (GET_CODE (op1) == NEG
14389 || GET_CODE (op1) == NOT
14390 || (GET_CODE (op1) == PLUS && XEXP (op1, 1) == const1_rtx))
14391 op1 = XEXP (op1, 0);
14392 else if (GET_CODE (op1) == ZERO_EXTEND && GET_CODE (op2) == ZERO_EXTEND)
14393 {
14394 /* CSEL with zero-extension (*cmovdi_insn_uxtw). */
14395 op1 = XEXP (op1, 0);
14396 op2 = XEXP (op2, 0);
14397 }
14398 else if (GET_CODE (op1) == ZERO_EXTEND && op2 == const0_rtx)
14399 {
14400 inner = XEXP (op1, 0);
14401 if (GET_CODE (inner) == NEG || GET_CODE (inner) == NOT)
14402 /* CSINV/NEG with zero extend + const 0 (*csinv3_uxtw_insn3). */
14403 op1 = XEXP (inner, 0);
14404 }
14405 else if (op1 == constm1_rtx || op1 == const1_rtx)
14406 {
14407 /* Use CSINV or CSINC. */
14408 *cost += rtx_cost (op2, VOIDmode, IF_THEN_ELSE, 2, speed);
14409 return true;
14410 }
14411 else if (op2 == constm1_rtx || op2 == const1_rtx)
14412 {
14413 /* Use CSINV or CSINC. */
14414 *cost += rtx_cost (op1, VOIDmode, IF_THEN_ELSE, 1, speed);
14415 return true;
14416 }
14417
14418 *cost += rtx_cost (op1, VOIDmode, IF_THEN_ELSE, 1, speed);
14419 *cost += rtx_cost (op2, VOIDmode, IF_THEN_ELSE, 2, speed);
14420 return true;
14421 }
14422
14423 /* We don't know what this is, cost all operands. */
14424 return false;
14425 }
14426
14427 /* Check whether X is a bitfield operation of the form shift + extend that
14428 maps down to a UBFIZ/SBFIZ/UBFX/SBFX instruction. If so, return the
14429 operand to which the bitfield operation is applied. Otherwise return
14430 NULL_RTX. */
14431
14432 static rtx
14433 aarch64_extend_bitfield_pattern_p (rtx x)
14434 {
14435 rtx_code outer_code = GET_CODE (x);
14436 machine_mode outer_mode = GET_MODE (x);
14437
14438 if (outer_code != ZERO_EXTEND && outer_code != SIGN_EXTEND
14439 && outer_mode != SImode && outer_mode != DImode)
14440 return NULL_RTX;
14441
14442 rtx inner = XEXP (x, 0);
14443 rtx_code inner_code = GET_CODE (inner);
14444 machine_mode inner_mode = GET_MODE (inner);
14445 rtx op = NULL_RTX;
14446
14447 switch (inner_code)
14448 {
14449 case ASHIFT:
14450 if (CONST_INT_P (XEXP (inner, 1))
14451 && (inner_mode == QImode || inner_mode == HImode))
14452 op = XEXP (inner, 0);
14453 break;
14454 case LSHIFTRT:
14455 if (outer_code == ZERO_EXTEND && CONST_INT_P (XEXP (inner, 1))
14456 && (inner_mode == QImode || inner_mode == HImode))
14457 op = XEXP (inner, 0);
14458 break;
14459 case ASHIFTRT:
14460 if (outer_code == SIGN_EXTEND && CONST_INT_P (XEXP (inner, 1))
14461 && (inner_mode == QImode || inner_mode == HImode))
14462 op = XEXP (inner, 0);
14463 break;
14464 default:
14465 break;
14466 }
14467
14468 return op;
14469 }
14470
14471 /* Return true if the mask and a shift amount from an RTX of the form
14472 (x << SHFT_AMNT) & MASK are valid to combine into a UBFIZ instruction of
14473 mode MODE. See the *andim_ashift<mode>_bfiz pattern. */
14474
14475 bool
14476 aarch64_mask_and_shift_for_ubfiz_p (scalar_int_mode mode, rtx mask,
14477 rtx shft_amnt)
14478 {
14479 return CONST_INT_P (mask) && CONST_INT_P (shft_amnt)
14480 && INTVAL (mask) > 0
14481 && UINTVAL (shft_amnt) < GET_MODE_BITSIZE (mode)
14482 && exact_log2 ((UINTVAL (mask) >> UINTVAL (shft_amnt)) + 1) >= 0
14483 && (UINTVAL (mask)
14484 & ((HOST_WIDE_INT_1U << UINTVAL (shft_amnt)) - 1)) == 0;
14485 }
14486
14487 /* Return true if the masks and a shift amount from an RTX of the form
14488 ((x & MASK1) | ((y << SHIFT_AMNT) & MASK2)) are valid to combine into
14489 a BFI instruction of mode MODE. See *arch64_bfi patterns. */
14490
14491 bool
14492 aarch64_masks_and_shift_for_bfi_p (scalar_int_mode mode,
14493 unsigned HOST_WIDE_INT mask1,
14494 unsigned HOST_WIDE_INT shft_amnt,
14495 unsigned HOST_WIDE_INT mask2)
14496 {
14497 unsigned HOST_WIDE_INT t;
14498
14499 /* Verify that there is no overlap in what bits are set in the two masks. */
14500 if (mask1 != ~mask2)
14501 return false;
14502
14503 /* Verify that mask2 is not all zeros or ones. */
14504 if (mask2 == 0 || mask2 == HOST_WIDE_INT_M1U)
14505 return false;
14506
14507 /* The shift amount should always be less than the mode size. */
14508 gcc_assert (shft_amnt < GET_MODE_BITSIZE (mode));
14509
14510 /* Verify that the mask being shifted is contiguous and would be in the
14511 least significant bits after shifting by shft_amnt. */
14512 t = mask2 + (HOST_WIDE_INT_1U << shft_amnt);
14513 return (t == (t & -t));
14514 }
14515
14516 /* Return true if X is an RTX representing an operation in the ABD family
14517 of instructions. */
14518
14519 static bool
14520 aarch64_abd_rtx_p (rtx x)
14521 {
14522 if (GET_CODE (x) != MINUS)
14523 return false;
14524 rtx max_arm = XEXP (x, 0);
14525 rtx min_arm = XEXP (x, 1);
14526 if (GET_CODE (max_arm) != SMAX && GET_CODE (max_arm) != UMAX)
14527 return false;
14528 bool signed_p = GET_CODE (max_arm) == SMAX;
14529 if (signed_p && GET_CODE (min_arm) != SMIN)
14530 return false;
14531 else if (!signed_p && GET_CODE (min_arm) != UMIN)
14532 return false;
14533
14534 rtx maxop0 = XEXP (max_arm, 0);
14535 rtx maxop1 = XEXP (max_arm, 1);
14536 rtx minop0 = XEXP (min_arm, 0);
14537 rtx minop1 = XEXP (min_arm, 1);
14538 return rtx_equal_p (maxop0, minop0) && rtx_equal_p (maxop1, minop1);
14539 }
14540
14541 /* Calculate the cost of calculating X, storing it in *COST. Result
14542 is true if the total cost of the operation has now been calculated. */
14543 static bool
14544 aarch64_rtx_costs (rtx x, machine_mode mode, int outer ATTRIBUTE_UNUSED,
14545 int param ATTRIBUTE_UNUSED, int *cost, bool speed)
14546 {
14547 rtx op0, op1, op2;
14548 const struct cpu_cost_table *extra_cost
14549 = aarch64_tune_params.insn_extra_cost;
14550 rtx_code code = GET_CODE (x);
14551 scalar_int_mode int_mode;
14552
14553 /* By default, assume that everything has equivalent cost to the
14554 cheapest instruction. Any additional costs are applied as a delta
14555 above this default. */
14556 *cost = COSTS_N_INSNS (1);
14557
14558 switch (code)
14559 {
14560 case SET:
14561 /* The cost depends entirely on the operands to SET. */
14562 *cost = 0;
14563 op0 = SET_DEST (x);
14564 op1 = SET_SRC (x);
14565
14566 switch (GET_CODE (op0))
14567 {
14568 case MEM:
14569 if (speed)
14570 {
14571 rtx address = XEXP (op0, 0);
14572 if (VECTOR_MODE_P (mode))
14573 *cost += extra_cost->ldst.storev;
14574 else if (GET_MODE_CLASS (mode) == MODE_INT)
14575 *cost += extra_cost->ldst.store;
14576 else if (mode == SFmode || mode == SDmode)
14577 *cost += extra_cost->ldst.storef;
14578 else if (mode == DFmode || mode == DDmode)
14579 *cost += extra_cost->ldst.stored;
14580
14581 *cost +=
14582 COSTS_N_INSNS (aarch64_address_cost (address, mode,
14583 0, speed));
14584 }
14585
14586 *cost += rtx_cost (op1, mode, SET, 1, speed);
14587 return true;
14588
14589 case SUBREG:
14590 if (! REG_P (SUBREG_REG (op0)))
14591 *cost += rtx_cost (SUBREG_REG (op0), VOIDmode, SET, 0, speed);
14592
14593 /* Fall through. */
14594 case REG:
14595 /* The cost is one per vector-register copied. */
14596 if (VECTOR_MODE_P (GET_MODE (op0)) && REG_P (op1))
14597 {
14598 int nregs = aarch64_hard_regno_nregs (V0_REGNUM, GET_MODE (op0));
14599 *cost = COSTS_N_INSNS (nregs);
14600 }
14601 /* const0_rtx is in general free, but we will use an
14602 instruction to set a register to 0. */
14603 else if (REG_P (op1) || op1 == const0_rtx)
14604 {
14605 /* The cost is 1 per register copied. */
14606 int nregs = aarch64_hard_regno_nregs (R0_REGNUM, GET_MODE (op0));
14607 *cost = COSTS_N_INSNS (nregs);
14608 }
14609 else
14610 /* Cost is just the cost of the RHS of the set. */
14611 *cost += rtx_cost (op1, mode, SET, 1, speed);
14612 return true;
14613
14614 case ZERO_EXTRACT:
14615 case SIGN_EXTRACT:
14616 /* Bit-field insertion. Strip any redundant widening of
14617 the RHS to meet the width of the target. */
14618 if (SUBREG_P (op1))
14619 op1 = SUBREG_REG (op1);
14620 if ((GET_CODE (op1) == ZERO_EXTEND
14621 || GET_CODE (op1) == SIGN_EXTEND)
14622 && CONST_INT_P (XEXP (op0, 1))
14623 && is_a <scalar_int_mode> (GET_MODE (XEXP (op1, 0)), &int_mode)
14624 && GET_MODE_BITSIZE (int_mode) >= INTVAL (XEXP (op0, 1)))
14625 op1 = XEXP (op1, 0);
14626
14627 if (CONST_INT_P (op1))
14628 {
14629 /* MOV immediate is assumed to always be cheap. */
14630 *cost = COSTS_N_INSNS (1);
14631 }
14632 else
14633 {
14634 /* BFM. */
14635 if (speed)
14636 *cost += extra_cost->alu.bfi;
14637 *cost += rtx_cost (op1, VOIDmode, code, 1, speed);
14638 }
14639
14640 return true;
14641
14642 default:
14643 /* We can't make sense of this, assume default cost. */
14644 *cost = COSTS_N_INSNS (1);
14645 return false;
14646 }
14647 return false;
14648
14649 case CONST_INT:
14650 /* If an instruction can incorporate a constant within the
14651 instruction, the instruction's expression avoids calling
14652 rtx_cost() on the constant. If rtx_cost() is called on a
14653 constant, then it is usually because the constant must be
14654 moved into a register by one or more instructions.
14655
14656 The exception is constant 0, which can be expressed
14657 as XZR/WZR and is therefore free. The exception to this is
14658 if we have (set (reg) (const0_rtx)) in which case we must cost
14659 the move. However, we can catch that when we cost the SET, so
14660 we don't need to consider that here. */
14661 if (x == const0_rtx)
14662 *cost = 0;
14663 else
14664 {
14665 /* To an approximation, building any other constant is
14666 proportionally expensive to the number of instructions
14667 required to build that constant. This is true whether we
14668 are compiling for SPEED or otherwise. */
14669 machine_mode imode = known_le (GET_MODE_SIZE (mode), 4)
14670 ? SImode : DImode;
14671 *cost = COSTS_N_INSNS (aarch64_internal_mov_immediate
14672 (NULL_RTX, x, false, imode));
14673 }
14674 return true;
14675
14676 case CONST_DOUBLE:
14677
14678 /* First determine number of instructions to do the move
14679 as an integer constant. */
14680 if (!aarch64_float_const_representable_p (x)
14681 && !aarch64_can_const_movi_rtx_p (x, mode)
14682 && aarch64_float_const_rtx_p (x))
14683 {
14684 unsigned HOST_WIDE_INT ival;
14685 bool succeed = aarch64_reinterpret_float_as_int (x, &ival);
14686 gcc_assert (succeed);
14687
14688 machine_mode imode = known_eq (GET_MODE_SIZE (mode), 8)
14689 ? DImode : SImode;
14690 int ncost = aarch64_internal_mov_immediate
14691 (NULL_RTX, gen_int_mode (ival, imode), false, imode);
14692 *cost += COSTS_N_INSNS (ncost);
14693 return true;
14694 }
14695
14696 if (speed)
14697 {
14698 /* mov[df,sf]_aarch64. */
14699 if (aarch64_float_const_representable_p (x))
14700 /* FMOV (scalar immediate). */
14701 *cost += extra_cost->fp[mode == DFmode || mode == DDmode].fpconst;
14702 else if (!aarch64_float_const_zero_rtx_p (x))
14703 {
14704 /* This will be a load from memory. */
14705 if (mode == DFmode || mode == DDmode)
14706 *cost += extra_cost->ldst.loadd;
14707 else
14708 *cost += extra_cost->ldst.loadf;
14709 }
14710 else
14711 /* Otherwise this is +0.0. We get this using MOVI d0, #0
14712 or MOV v0.s[0], wzr - neither of which are modeled by the
14713 cost tables. Just use the default cost. */
14714 {
14715 }
14716 }
14717
14718 return true;
14719
14720 case MEM:
14721 if (speed)
14722 {
14723 /* For loads we want the base cost of a load, plus an
14724 approximation for the additional cost of the addressing
14725 mode. */
14726 rtx address = XEXP (x, 0);
14727 if (VECTOR_MODE_P (mode))
14728 *cost += extra_cost->ldst.loadv;
14729 else if (GET_MODE_CLASS (mode) == MODE_INT)
14730 *cost += extra_cost->ldst.load;
14731 else if (mode == SFmode || mode == SDmode)
14732 *cost += extra_cost->ldst.loadf;
14733 else if (mode == DFmode || mode == DDmode)
14734 *cost += extra_cost->ldst.loadd;
14735
14736 *cost +=
14737 COSTS_N_INSNS (aarch64_address_cost (address, mode,
14738 0, speed));
14739 }
14740
14741 return true;
14742
14743 case NEG:
14744 op0 = XEXP (x, 0);
14745
14746 if (VECTOR_MODE_P (mode))
14747 {
14748 /* Many vector comparison operations are represented as NEG
14749 of a comparison. */
14750 if (COMPARISON_P (op0))
14751 {
14752 rtx op00 = XEXP (op0, 0);
14753 rtx op01 = XEXP (op0, 1);
14754 machine_mode inner_mode = GET_MODE (op00);
14755 /* FACGE/FACGT. */
14756 if (GET_MODE_CLASS (inner_mode) == MODE_VECTOR_FLOAT
14757 && GET_CODE (op00) == ABS
14758 && GET_CODE (op01) == ABS)
14759 {
14760 op00 = XEXP (op00, 0);
14761 op01 = XEXP (op01, 0);
14762 }
14763 *cost += rtx_cost (op00, inner_mode, GET_CODE (op0), 0, speed);
14764 *cost += rtx_cost (op01, inner_mode, GET_CODE (op0), 1, speed);
14765 if (speed)
14766 *cost += extra_cost->vect.alu;
14767 return true;
14768 }
14769 if (speed)
14770 {
14771 /* FNEG. */
14772 *cost += extra_cost->vect.alu;
14773 }
14774 return false;
14775 }
14776
14777 if (GET_MODE_CLASS (mode) == MODE_INT)
14778 {
14779 if (GET_RTX_CLASS (GET_CODE (op0)) == RTX_COMPARE
14780 || GET_RTX_CLASS (GET_CODE (op0)) == RTX_COMM_COMPARE)
14781 {
14782 /* CSETM. */
14783 *cost += rtx_cost (XEXP (op0, 0), VOIDmode, NEG, 0, speed);
14784 return true;
14785 }
14786
14787 /* Cost this as SUB wzr, X. */
14788 op0 = CONST0_RTX (mode);
14789 op1 = XEXP (x, 0);
14790 goto cost_minus;
14791 }
14792
14793 if (GET_MODE_CLASS (mode) == MODE_FLOAT)
14794 {
14795 /* Support (neg(fma...)) as a single instruction only if
14796 sign of zeros is unimportant. This matches the decision
14797 making in aarch64.md. */
14798 if (GET_CODE (op0) == FMA && !HONOR_SIGNED_ZEROS (GET_MODE (op0)))
14799 {
14800 /* FNMADD. */
14801 *cost = rtx_cost (op0, mode, NEG, 0, speed);
14802 return true;
14803 }
14804 if (GET_CODE (op0) == MULT)
14805 {
14806 /* FNMUL. */
14807 *cost = rtx_cost (op0, mode, NEG, 0, speed);
14808 return true;
14809 }
14810 if (speed)
14811 /* FNEG. */
14812 *cost += extra_cost->fp[mode == DFmode].neg;
14813 return false;
14814 }
14815
14816 return false;
14817
14818 case CLRSB:
14819 case CLZ:
14820 if (speed)
14821 {
14822 if (VECTOR_MODE_P (mode))
14823 *cost += extra_cost->vect.alu;
14824 else
14825 *cost += extra_cost->alu.clz;
14826 }
14827
14828 return false;
14829
14830 case CTZ:
14831 if (VECTOR_MODE_P (mode))
14832 {
14833 *cost = COSTS_N_INSNS (3);
14834 if (speed)
14835 *cost += extra_cost->vect.alu * 3;
14836 }
14837 else if (TARGET_CSSC)
14838 {
14839 *cost = COSTS_N_INSNS (1);
14840 if (speed)
14841 *cost += extra_cost->alu.clz;
14842 }
14843 else
14844 {
14845 *cost = COSTS_N_INSNS (2);
14846 if (speed)
14847 *cost += extra_cost->alu.clz + extra_cost->alu.rev;
14848 }
14849 return false;
14850
14851 case COMPARE:
14852 op0 = XEXP (x, 0);
14853 op1 = XEXP (x, 1);
14854
14855 if (op1 == const0_rtx
14856 && GET_CODE (op0) == AND)
14857 {
14858 x = op0;
14859 mode = GET_MODE (op0);
14860 goto cost_logic;
14861 }
14862
14863 if (GET_MODE_CLASS (GET_MODE (op0)) == MODE_INT)
14864 {
14865 /* TODO: A write to the CC flags possibly costs extra, this
14866 needs encoding in the cost tables. */
14867
14868 mode = GET_MODE (op0);
14869 /* ANDS. */
14870 if (GET_CODE (op0) == AND)
14871 {
14872 x = op0;
14873 goto cost_logic;
14874 }
14875
14876 if (GET_CODE (op0) == PLUS)
14877 {
14878 /* ADDS (and CMN alias). */
14879 x = op0;
14880 goto cost_plus;
14881 }
14882
14883 if (GET_CODE (op0) == MINUS)
14884 {
14885 /* SUBS. */
14886 x = op0;
14887 goto cost_minus;
14888 }
14889
14890 if (GET_CODE (op0) == ZERO_EXTRACT && op1 == const0_rtx
14891 && GET_MODE (x) == CC_NZmode && CONST_INT_P (XEXP (op0, 1))
14892 && CONST_INT_P (XEXP (op0, 2)))
14893 {
14894 /* COMPARE of ZERO_EXTRACT form of TST-immediate.
14895 Handle it here directly rather than going to cost_logic
14896 since we know the immediate generated for the TST is valid
14897 so we can avoid creating an intermediate rtx for it only
14898 for costing purposes. */
14899 if (speed)
14900 *cost += extra_cost->alu.logical;
14901
14902 *cost += rtx_cost (XEXP (op0, 0), GET_MODE (op0),
14903 ZERO_EXTRACT, 0, speed);
14904 return true;
14905 }
14906
14907 if (GET_CODE (op1) == NEG)
14908 {
14909 /* CMN. */
14910 if (speed)
14911 *cost += extra_cost->alu.arith;
14912
14913 *cost += rtx_cost (op0, mode, COMPARE, 0, speed);
14914 *cost += rtx_cost (XEXP (op1, 0), mode, NEG, 1, speed);
14915 return true;
14916 }
14917
14918 /* CMP.
14919
14920 Compare can freely swap the order of operands, and
14921 canonicalization puts the more complex operation first.
14922 But the integer MINUS logic expects the shift/extend
14923 operation in op1. */
14924 if (! (REG_P (op0)
14925 || (SUBREG_P (op0) && REG_P (SUBREG_REG (op0)))))
14926 {
14927 op0 = XEXP (x, 1);
14928 op1 = XEXP (x, 0);
14929 }
14930 goto cost_minus;
14931 }
14932
14933 if (GET_MODE_CLASS (GET_MODE (op0)) == MODE_FLOAT)
14934 {
14935 /* FCMP. */
14936 if (speed)
14937 *cost += extra_cost->fp[mode == DFmode].compare;
14938
14939 if (CONST_DOUBLE_P (op1) && aarch64_float_const_zero_rtx_p (op1))
14940 {
14941 *cost += rtx_cost (op0, VOIDmode, COMPARE, 0, speed);
14942 /* FCMP supports constant 0.0 for no extra cost. */
14943 return true;
14944 }
14945 return false;
14946 }
14947
14948 if (VECTOR_MODE_P (mode))
14949 {
14950 /* Vector compare. */
14951 if (speed)
14952 *cost += extra_cost->vect.alu;
14953
14954 if (aarch64_float_const_zero_rtx_p (op1))
14955 {
14956 /* Vector cm (eq|ge|gt|lt|le) supports constant 0.0 for no extra
14957 cost. */
14958 return true;
14959 }
14960 return false;
14961 }
14962 return false;
14963
14964 case MINUS:
14965 {
14966 op0 = XEXP (x, 0);
14967 op1 = XEXP (x, 1);
14968
14969 cost_minus:
14970 if (VECTOR_MODE_P (mode))
14971 {
14972 unsigned int vec_flags = aarch64_classify_vector_mode (mode);
14973 if (TARGET_SIMD && (vec_flags & VEC_ADVSIMD))
14974 {
14975 /* Recognise the SABD and UABD operation here.
14976 Recursion from the PLUS case will catch the accumulating
14977 forms. */
14978 if (aarch64_abd_rtx_p (x))
14979 {
14980 if (speed)
14981 *cost += extra_cost->vect.alu;
14982 return true;
14983 }
14984 /* SUBL2 and SUBW2.
14985 The select-operand-high-half versions of the sub instruction
14986 have the same cost as the regular three vector version -
14987 don't add the costs of the select into the costs of the sub.
14988 */
14989 op0 = aarch64_strip_extend_vec_half (op0);
14990 op1 = aarch64_strip_extend_vec_half (op1);
14991 }
14992 }
14993
14994 *cost += rtx_cost (op0, mode, MINUS, 0, speed);
14995
14996 /* Detect valid immediates. */
14997 if ((GET_MODE_CLASS (mode) == MODE_INT
14998 || (GET_MODE_CLASS (mode) == MODE_CC
14999 && GET_MODE_CLASS (GET_MODE (op0)) == MODE_INT))
15000 && CONST_INT_P (op1)
15001 && aarch64_uimm12_shift (INTVAL (op1)))
15002 {
15003 if (speed)
15004 /* SUB(S) (immediate). */
15005 *cost += extra_cost->alu.arith;
15006 return true;
15007 }
15008
15009 /* Look for SUB (extended register). */
15010 if (is_a <scalar_int_mode> (mode)
15011 && aarch64_rtx_arith_op_extract_p (op1))
15012 {
15013 if (speed)
15014 *cost += extra_cost->alu.extend_arith;
15015
15016 op1 = aarch64_strip_extend (op1, true);
15017 *cost += rtx_cost (op1, VOIDmode, GET_CODE (op1), 0, speed);
15018 return true;
15019 }
15020
15021 rtx new_op1 = aarch64_strip_extend (op1, false);
15022
15023 /* Cost this as an FMA-alike operation. */
15024 if ((GET_CODE (new_op1) == MULT
15025 || aarch64_shift_p (GET_CODE (new_op1)))
15026 && code != COMPARE)
15027 {
15028 *cost += aarch64_rtx_mult_cost (new_op1, MULT, code, speed);
15029 return true;
15030 }
15031
15032 *cost += rtx_cost (new_op1, VOIDmode, MINUS, 1, speed);
15033
15034 if (speed)
15035 {
15036 if (VECTOR_MODE_P (mode))
15037 {
15038 /* Vector SUB. */
15039 *cost += extra_cost->vect.alu;
15040 }
15041 else if (GET_MODE_CLASS (mode) == MODE_INT)
15042 {
15043 /* SUB(S). */
15044 *cost += extra_cost->alu.arith;
15045 }
15046 else if (GET_MODE_CLASS (mode) == MODE_FLOAT)
15047 {
15048 /* FSUB. */
15049 *cost += extra_cost->fp[mode == DFmode].addsub;
15050 }
15051 }
15052 return true;
15053 }
15054
15055 case PLUS:
15056 {
15057 rtx new_op0;
15058
15059 op0 = XEXP (x, 0);
15060 op1 = XEXP (x, 1);
15061
15062 cost_plus:
15063 if (VECTOR_MODE_P (mode))
15064 {
15065 /* ADDL2 and ADDW2. */
15066 unsigned int vec_flags = aarch64_classify_vector_mode (mode);
15067 if (TARGET_SIMD && (vec_flags & VEC_ADVSIMD))
15068 {
15069 /* The select-operand-high-half versions of the add instruction
15070 have the same cost as the regular three vector version -
15071 don't add the costs of the select into the costs of the add.
15072 */
15073 op0 = aarch64_strip_extend_vec_half (op0);
15074 op1 = aarch64_strip_extend_vec_half (op1);
15075 }
15076 }
15077
15078 if (GET_RTX_CLASS (GET_CODE (op0)) == RTX_COMPARE
15079 || GET_RTX_CLASS (GET_CODE (op0)) == RTX_COMM_COMPARE)
15080 {
15081 /* CSINC. */
15082 *cost += rtx_cost (XEXP (op0, 0), mode, PLUS, 0, speed);
15083 *cost += rtx_cost (op1, mode, PLUS, 1, speed);
15084 return true;
15085 }
15086
15087 if (GET_MODE_CLASS (mode) == MODE_INT
15088 && (aarch64_plus_immediate (op1, mode)
15089 || aarch64_sve_addvl_addpl_immediate (op1, mode)))
15090 {
15091 *cost += rtx_cost (op0, mode, PLUS, 0, speed);
15092
15093 if (speed)
15094 {
15095 /* ADD (immediate). */
15096 *cost += extra_cost->alu.arith;
15097
15098 /* Some tunings prefer to not use the VL-based scalar ops.
15099 Increase the cost of the poly immediate to prevent their
15100 formation. */
15101 if (GET_CODE (op1) == CONST_POLY_INT
15102 && (aarch64_tune_params.extra_tuning_flags
15103 & AARCH64_EXTRA_TUNE_CSE_SVE_VL_CONSTANTS))
15104 *cost += COSTS_N_INSNS (1);
15105 }
15106 return true;
15107 }
15108
15109 if (aarch64_pluslong_immediate (op1, mode))
15110 {
15111 /* 24-bit add in 2 instructions or 12-bit shifted add. */
15112 if ((INTVAL (op1) & 0xfff) != 0)
15113 *cost += COSTS_N_INSNS (1);
15114
15115 *cost += rtx_cost (op0, mode, PLUS, 0, speed);
15116 return true;
15117 }
15118
15119 *cost += rtx_cost (op1, mode, PLUS, 1, speed);
15120
15121 /* Look for ADD (extended register). */
15122 if (is_a <scalar_int_mode> (mode)
15123 && aarch64_rtx_arith_op_extract_p (op0))
15124 {
15125 if (speed)
15126 *cost += extra_cost->alu.extend_arith;
15127
15128 op0 = aarch64_strip_extend (op0, true);
15129 *cost += rtx_cost (op0, VOIDmode, GET_CODE (op0), 0, speed);
15130 return true;
15131 }
15132
15133 /* Strip any extend, leave shifts behind as we will
15134 cost them through mult_cost. */
15135 new_op0 = aarch64_strip_extend (op0, false);
15136
15137 if (GET_CODE (new_op0) == MULT
15138 || aarch64_shift_p (GET_CODE (new_op0)))
15139 {
15140 *cost += aarch64_rtx_mult_cost (new_op0, MULT, PLUS,
15141 speed);
15142 return true;
15143 }
15144
15145 *cost += rtx_cost (new_op0, VOIDmode, PLUS, 0, speed);
15146
15147 if (speed)
15148 {
15149 if (VECTOR_MODE_P (mode))
15150 {
15151 /* Vector ADD. */
15152 *cost += extra_cost->vect.alu;
15153 }
15154 else if (GET_MODE_CLASS (mode) == MODE_INT)
15155 {
15156 /* ADD. */
15157 *cost += extra_cost->alu.arith;
15158 }
15159 else if (GET_MODE_CLASS (mode) == MODE_FLOAT)
15160 {
15161 /* FADD. */
15162 *cost += extra_cost->fp[mode == DFmode].addsub;
15163 }
15164 }
15165 return true;
15166 }
15167
15168 case BITREVERSE:
15169 case BSWAP:
15170 *cost = COSTS_N_INSNS (1);
15171
15172 if (speed)
15173 {
15174 if (VECTOR_MODE_P (mode))
15175 *cost += extra_cost->vect.alu;
15176 else
15177 *cost += extra_cost->alu.rev;
15178 }
15179 return false;
15180
15181 case IOR:
15182 if (aarch_rev16_p (x))
15183 {
15184 *cost = COSTS_N_INSNS (1);
15185
15186 if (speed)
15187 {
15188 if (VECTOR_MODE_P (mode))
15189 *cost += extra_cost->vect.alu;
15190 else
15191 *cost += extra_cost->alu.rev;
15192 }
15193 return true;
15194 }
15195
15196 if (aarch64_extr_rtx_p (x, &op0, &op1))
15197 {
15198 *cost += rtx_cost (op0, mode, IOR, 0, speed);
15199 *cost += rtx_cost (op1, mode, IOR, 1, speed);
15200 if (speed)
15201 *cost += extra_cost->alu.shift;
15202
15203 return true;
15204 }
15205 /* Fall through. */
15206 case XOR:
15207 case AND:
15208 cost_logic:
15209 op0 = XEXP (x, 0);
15210 op1 = XEXP (x, 1);
15211
15212 if (VECTOR_MODE_P (mode))
15213 {
15214 if (speed)
15215 *cost += extra_cost->vect.alu;
15216 return true;
15217 }
15218
15219 if (code == AND
15220 && GET_CODE (op0) == MULT
15221 && CONST_INT_P (XEXP (op0, 1))
15222 && CONST_INT_P (op1)
15223 && aarch64_uxt_size (exact_log2 (INTVAL (XEXP (op0, 1))),
15224 INTVAL (op1)) != 0)
15225 {
15226 /* This is a UBFM/SBFM. */
15227 *cost += rtx_cost (XEXP (op0, 0), mode, ZERO_EXTRACT, 0, speed);
15228 if (speed)
15229 *cost += extra_cost->alu.bfx;
15230 return true;
15231 }
15232
15233 if (is_int_mode (mode, &int_mode))
15234 {
15235 if (CONST_INT_P (op1))
15236 {
15237 /* We have a mask + shift version of a UBFIZ
15238 i.e. the *andim_ashift<mode>_bfiz pattern. */
15239 if (GET_CODE (op0) == ASHIFT
15240 && aarch64_mask_and_shift_for_ubfiz_p (int_mode, op1,
15241 XEXP (op0, 1)))
15242 {
15243 *cost += rtx_cost (XEXP (op0, 0), int_mode, code, 0, speed);
15244 if (speed)
15245 *cost += extra_cost->alu.bfx;
15246
15247 return true;
15248 }
15249 else if (aarch64_bitmask_imm (INTVAL (op1), int_mode))
15250 {
15251 /* We possibly get the immediate for free, this is not
15252 modelled. */
15253 *cost += rtx_cost (op0, int_mode, code, 0, speed);
15254 if (speed)
15255 *cost += extra_cost->alu.logical;
15256
15257 return true;
15258 }
15259 }
15260 else
15261 {
15262 rtx new_op0 = op0;
15263
15264 /* Handle ORN, EON, or BIC. */
15265 if (GET_CODE (op0) == NOT)
15266 op0 = XEXP (op0, 0);
15267
15268 new_op0 = aarch64_strip_shift (op0);
15269
15270 /* If we had a shift on op0 then this is a logical-shift-
15271 by-register/immediate operation. Otherwise, this is just
15272 a logical operation. */
15273 if (speed)
15274 {
15275 if (new_op0 != op0)
15276 {
15277 /* Shift by immediate. */
15278 if (CONST_INT_P (XEXP (op0, 1)))
15279 *cost += extra_cost->alu.log_shift;
15280 else
15281 *cost += extra_cost->alu.log_shift_reg;
15282 }
15283 else
15284 *cost += extra_cost->alu.logical;
15285 }
15286
15287 /* In both cases we want to cost both operands. */
15288 *cost += rtx_cost (new_op0, int_mode, code, 0, speed);
15289 *cost += rtx_cost (op1, int_mode, code, 1, speed);
15290
15291 return true;
15292 }
15293 }
15294 return false;
15295
15296 case NOT:
15297 x = XEXP (x, 0);
15298 op0 = aarch64_strip_shift (x);
15299
15300 if (VECTOR_MODE_P (mode))
15301 {
15302 /* Vector NOT. */
15303 *cost += extra_cost->vect.alu;
15304 return false;
15305 }
15306
15307 /* MVN-shifted-reg. */
15308 if (op0 != x)
15309 {
15310 *cost += rtx_cost (op0, mode, code, 0, speed);
15311
15312 if (speed)
15313 *cost += extra_cost->alu.log_shift;
15314
15315 return true;
15316 }
15317 /* EON can have two forms: (xor (not a) b) but also (not (xor a b)).
15318 Handle the second form here taking care that 'a' in the above can
15319 be a shift. */
15320 else if (GET_CODE (op0) == XOR)
15321 {
15322 rtx newop0 = XEXP (op0, 0);
15323 rtx newop1 = XEXP (op0, 1);
15324 rtx op0_stripped = aarch64_strip_shift (newop0);
15325
15326 *cost += rtx_cost (newop1, mode, code, 1, speed);
15327 *cost += rtx_cost (op0_stripped, mode, XOR, 0, speed);
15328
15329 if (speed)
15330 {
15331 if (op0_stripped != newop0)
15332 *cost += extra_cost->alu.log_shift;
15333 else
15334 *cost += extra_cost->alu.logical;
15335 }
15336
15337 return true;
15338 }
15339 /* MVN. */
15340 if (speed)
15341 *cost += extra_cost->alu.logical;
15342
15343 return false;
15344
15345 case ZERO_EXTEND:
15346
15347 op0 = XEXP (x, 0);
15348 /* If a value is written in SI mode, then zero extended to DI
15349 mode, the operation will in general be free as a write to
15350 a 'w' register implicitly zeroes the upper bits of an 'x'
15351 register. However, if this is
15352
15353 (set (reg) (zero_extend (reg)))
15354
15355 we must cost the explicit register move. */
15356 if (mode == DImode
15357 && GET_MODE (op0) == SImode)
15358 {
15359 int op_cost = rtx_cost (op0, VOIDmode, ZERO_EXTEND, 0, speed);
15360
15361 /* If OP_COST is non-zero, then the cost of the zero extend
15362 is effectively the cost of the inner operation. Otherwise
15363 we have a MOV instruction and we take the cost from the MOV
15364 itself. This is true independently of whether we are
15365 optimizing for space or time. */
15366 if (op_cost)
15367 *cost = op_cost;
15368
15369 return true;
15370 }
15371 else if (MEM_P (op0))
15372 {
15373 /* All loads can zero extend to any size for free. */
15374 *cost = rtx_cost (op0, VOIDmode, ZERO_EXTEND, param, speed);
15375 return true;
15376 }
15377
15378 op0 = aarch64_extend_bitfield_pattern_p (x);
15379 if (op0)
15380 {
15381 *cost += rtx_cost (op0, mode, ZERO_EXTEND, 0, speed);
15382 if (speed)
15383 *cost += extra_cost->alu.bfx;
15384 return true;
15385 }
15386
15387 if (speed)
15388 {
15389 if (VECTOR_MODE_P (mode))
15390 {
15391 /* UMOV. */
15392 *cost += extra_cost->vect.alu;
15393 }
15394 else
15395 {
15396 /* We generate an AND instead of UXTB/UXTH. */
15397 *cost += extra_cost->alu.logical;
15398 }
15399 }
15400 return false;
15401
15402 case SIGN_EXTEND:
15403 if (MEM_P (XEXP (x, 0)))
15404 {
15405 /* LDRSH. */
15406 if (speed)
15407 {
15408 rtx address = XEXP (XEXP (x, 0), 0);
15409 *cost += extra_cost->ldst.load_sign_extend;
15410
15411 *cost +=
15412 COSTS_N_INSNS (aarch64_address_cost (address, mode,
15413 0, speed));
15414 }
15415 return true;
15416 }
15417
15418 op0 = aarch64_extend_bitfield_pattern_p (x);
15419 if (op0)
15420 {
15421 *cost += rtx_cost (op0, mode, SIGN_EXTEND, 0, speed);
15422 if (speed)
15423 *cost += extra_cost->alu.bfx;
15424 return true;
15425 }
15426
15427 if (speed)
15428 {
15429 if (VECTOR_MODE_P (mode))
15430 *cost += extra_cost->vect.alu;
15431 else
15432 *cost += extra_cost->alu.extend;
15433 }
15434 return false;
15435
15436 case ROTATE:
15437 case ROTATERT:
15438 case LSHIFTRT:
15439 case ASHIFTRT:
15440 case ASHIFT:
15441 op0 = XEXP (x, 0);
15442 op1 = XEXP (x, 1);
15443
15444 if (CONST_INT_P (op1))
15445 {
15446 if (speed)
15447 {
15448 if (VECTOR_MODE_P (mode))
15449 {
15450 /* Vector shift (immediate). */
15451 *cost += extra_cost->vect.alu;
15452 }
15453 else
15454 {
15455 /* LSL (immediate), ASR (immediate), UBMF, UBFIZ and friends.
15456 These are all aliases. */
15457 *cost += extra_cost->alu.shift;
15458 }
15459 }
15460
15461 /* We can incorporate zero/sign extend for free. */
15462 if (GET_CODE (op0) == ZERO_EXTEND
15463 || GET_CODE (op0) == SIGN_EXTEND)
15464 op0 = XEXP (op0, 0);
15465
15466 *cost += rtx_cost (op0, VOIDmode, ASHIFT, 0, speed);
15467 return true;
15468 }
15469 else
15470 {
15471 if (VECTOR_MODE_P (mode))
15472 {
15473 if (speed)
15474 /* Vector shift (register). */
15475 *cost += extra_cost->vect.alu;
15476 }
15477 else
15478 {
15479 if (speed)
15480 /* LSLV, ASRV. */
15481 *cost += extra_cost->alu.shift_reg;
15482
15483 /* The register shift amount may be in a shorter mode expressed
15484 as a lowpart SUBREG. For costing purposes just look inside. */
15485 if (SUBREG_P (op1) && subreg_lowpart_p (op1))
15486 op1 = SUBREG_REG (op1);
15487 if (GET_CODE (op1) == AND && REG_P (XEXP (op1, 0))
15488 && CONST_INT_P (XEXP (op1, 1))
15489 && known_eq (INTVAL (XEXP (op1, 1)),
15490 GET_MODE_BITSIZE (mode) - 1))
15491 {
15492 *cost += rtx_cost (op0, mode, code, 0, speed);
15493 /* We already demanded XEXP (op1, 0) to be REG_P, so
15494 don't recurse into it. */
15495 return true;
15496 }
15497 }
15498 return false; /* All arguments need to be in registers. */
15499 }
15500
15501 case SYMBOL_REF:
15502
15503 if (aarch64_cmodel == AARCH64_CMODEL_LARGE
15504 || aarch64_cmodel == AARCH64_CMODEL_SMALL_SPIC)
15505 {
15506 /* LDR. */
15507 if (speed)
15508 *cost += extra_cost->ldst.load;
15509 }
15510 else if (aarch64_cmodel == AARCH64_CMODEL_SMALL
15511 || aarch64_cmodel == AARCH64_CMODEL_SMALL_PIC)
15512 {
15513 /* ADRP, followed by ADD. */
15514 *cost += COSTS_N_INSNS (1);
15515 if (speed)
15516 *cost += 2 * extra_cost->alu.arith;
15517 }
15518 else if (aarch64_cmodel == AARCH64_CMODEL_TINY
15519 || aarch64_cmodel == AARCH64_CMODEL_TINY_PIC)
15520 {
15521 /* ADR. */
15522 if (speed)
15523 *cost += extra_cost->alu.arith;
15524 }
15525
15526 if (flag_pic)
15527 {
15528 /* One extra load instruction, after accessing the GOT. */
15529 *cost += COSTS_N_INSNS (1);
15530 if (speed)
15531 *cost += extra_cost->ldst.load;
15532 }
15533 return true;
15534
15535 case HIGH:
15536 case LO_SUM:
15537 /* ADRP/ADD (immediate). */
15538 if (speed)
15539 *cost += extra_cost->alu.arith;
15540 return true;
15541
15542 case ZERO_EXTRACT:
15543 case SIGN_EXTRACT:
15544 /* UBFX/SBFX. */
15545 if (speed)
15546 {
15547 if (VECTOR_MODE_P (mode))
15548 *cost += extra_cost->vect.alu;
15549 else
15550 *cost += extra_cost->alu.bfx;
15551 }
15552
15553 /* We can trust that the immediates used will be correct (there
15554 are no by-register forms), so we need only cost op0. */
15555 *cost += rtx_cost (XEXP (x, 0), VOIDmode, code, 0, speed);
15556 return true;
15557
15558 case MULT:
15559 *cost += aarch64_rtx_mult_cost (x, MULT, 0, speed);
15560 /* aarch64_rtx_mult_cost always handles recursion to its
15561 operands. */
15562 return true;
15563
15564 case MOD:
15565 /* We can expand signed mod by power of 2 using a NEGS, two parallel
15566 ANDs and a CSNEG. Assume here that CSNEG is the same as the cost of
15567 an unconditional negate. This case should only ever be reached through
15568 the set_smod_pow2_cheap check in expmed.cc. */
15569 if (CONST_INT_P (XEXP (x, 1))
15570 && exact_log2 (INTVAL (XEXP (x, 1))) > 0
15571 && (mode == SImode || mode == DImode))
15572 {
15573 /* We expand to 4 instructions. Reset the baseline. */
15574 *cost = COSTS_N_INSNS (4);
15575
15576 if (speed)
15577 *cost += 2 * extra_cost->alu.logical
15578 + 2 * extra_cost->alu.arith;
15579
15580 return true;
15581 }
15582
15583 /* Fall-through. */
15584 case UMOD:
15585 if (speed)
15586 {
15587 /* Slighly prefer UMOD over SMOD. */
15588 if (VECTOR_MODE_P (mode))
15589 *cost += extra_cost->vect.alu;
15590 else if (GET_MODE_CLASS (mode) == MODE_INT)
15591 *cost += (extra_cost->mult[mode == DImode].add
15592 + extra_cost->mult[mode == DImode].idiv
15593 + (code == MOD ? 1 : 0));
15594 }
15595 return false; /* All arguments need to be in registers. */
15596
15597 case DIV:
15598 case UDIV:
15599 case SQRT:
15600 if (speed)
15601 {
15602 if (VECTOR_MODE_P (mode))
15603 *cost += extra_cost->vect.alu;
15604 else if (GET_MODE_CLASS (mode) == MODE_INT)
15605 /* There is no integer SQRT, so only DIV and UDIV can get
15606 here. */
15607 *cost += (extra_cost->mult[mode == DImode].idiv
15608 /* Slighly prefer UDIV over SDIV. */
15609 + (code == DIV ? 1 : 0));
15610 else
15611 *cost += extra_cost->fp[mode == DFmode].div;
15612 }
15613 return false; /* All arguments need to be in registers. */
15614
15615 case IF_THEN_ELSE:
15616 return aarch64_if_then_else_costs (XEXP (x, 0), XEXP (x, 1),
15617 XEXP (x, 2), cost, speed);
15618
15619 case EQ:
15620 case NE:
15621 case GT:
15622 case GTU:
15623 case LT:
15624 case LTU:
15625 case GE:
15626 case GEU:
15627 case LE:
15628 case LEU:
15629
15630 return false; /* All arguments must be in registers. */
15631
15632 case FMA:
15633 op0 = XEXP (x, 0);
15634 op1 = XEXP (x, 1);
15635 op2 = XEXP (x, 2);
15636
15637 if (speed)
15638 {
15639 if (VECTOR_MODE_P (mode))
15640 *cost += extra_cost->vect.alu;
15641 else
15642 *cost += extra_cost->fp[mode == DFmode].fma;
15643 }
15644
15645 /* FMSUB, FNMADD, and FNMSUB are free. */
15646 if (GET_CODE (op0) == NEG)
15647 op0 = XEXP (op0, 0);
15648
15649 if (GET_CODE (op2) == NEG)
15650 op2 = XEXP (op2, 0);
15651
15652 /* aarch64_fnma4_elt_to_64v2df has the NEG as operand 1,
15653 and the by-element operand as operand 0. */
15654 if (GET_CODE (op1) == NEG)
15655 op1 = XEXP (op1, 0);
15656
15657 /* Catch vector-by-element operations. The by-element operand can
15658 either be (vec_duplicate (vec_select (x))) or just
15659 (vec_select (x)), depending on whether we are multiplying by
15660 a vector or a scalar.
15661
15662 Canonicalization is not very good in these cases, FMA4 will put the
15663 by-element operand as operand 0, FNMA4 will have it as operand 1. */
15664 if (GET_CODE (op0) == VEC_DUPLICATE)
15665 op0 = XEXP (op0, 0);
15666 else if (GET_CODE (op1) == VEC_DUPLICATE)
15667 op1 = XEXP (op1, 0);
15668
15669 if (GET_CODE (op0) == VEC_SELECT)
15670 op0 = XEXP (op0, 0);
15671 else if (GET_CODE (op1) == VEC_SELECT)
15672 op1 = XEXP (op1, 0);
15673
15674 /* If the remaining parameters are not registers,
15675 get the cost to put them into registers. */
15676 *cost += rtx_cost (op0, mode, FMA, 0, speed);
15677 *cost += rtx_cost (op1, mode, FMA, 1, speed);
15678 *cost += rtx_cost (op2, mode, FMA, 2, speed);
15679 return true;
15680
15681 case FLOAT:
15682 case UNSIGNED_FLOAT:
15683 if (speed)
15684 *cost += extra_cost->fp[mode == DFmode].fromint;
15685 return false;
15686
15687 case FLOAT_EXTEND:
15688 if (speed)
15689 {
15690 if (VECTOR_MODE_P (mode))
15691 {
15692 /*Vector truncate. */
15693 *cost += extra_cost->vect.alu;
15694 }
15695 else
15696 *cost += extra_cost->fp[mode == DFmode].widen;
15697 }
15698 return false;
15699
15700 case FLOAT_TRUNCATE:
15701 if (speed)
15702 {
15703 if (VECTOR_MODE_P (mode))
15704 {
15705 /*Vector conversion. */
15706 *cost += extra_cost->vect.alu;
15707 }
15708 else
15709 *cost += extra_cost->fp[mode == DFmode].narrow;
15710 }
15711 return false;
15712
15713 case FIX:
15714 case UNSIGNED_FIX:
15715 x = XEXP (x, 0);
15716 /* Strip the rounding part. They will all be implemented
15717 by the fcvt* family of instructions anyway. */
15718 if (GET_CODE (x) == UNSPEC)
15719 {
15720 unsigned int uns_code = XINT (x, 1);
15721
15722 if (uns_code == UNSPEC_FRINTA
15723 || uns_code == UNSPEC_FRINTM
15724 || uns_code == UNSPEC_FRINTN
15725 || uns_code == UNSPEC_FRINTP
15726 || uns_code == UNSPEC_FRINTZ)
15727 x = XVECEXP (x, 0, 0);
15728 }
15729
15730 if (speed)
15731 {
15732 if (VECTOR_MODE_P (mode))
15733 *cost += extra_cost->vect.alu;
15734 else
15735 *cost += extra_cost->fp[GET_MODE (x) == DFmode].toint;
15736 }
15737
15738 /* We can combine fmul by a power of 2 followed by a fcvt into a single
15739 fixed-point fcvt. */
15740 if (GET_CODE (x) == MULT
15741 && ((VECTOR_MODE_P (mode)
15742 && aarch64_vec_fpconst_pow_of_2 (XEXP (x, 1)) > 0)
15743 || aarch64_fpconst_pow_of_2 (XEXP (x, 1)) > 0))
15744 {
15745 *cost += rtx_cost (XEXP (x, 0), VOIDmode, code, 0, speed);
15746 return true;
15747 }
15748
15749 *cost += rtx_cost (x, VOIDmode, code, 0, speed);
15750 return true;
15751
15752 case ABS:
15753 if (VECTOR_MODE_P (mode))
15754 {
15755 /* ABS (vector). */
15756 if (speed)
15757 *cost += extra_cost->vect.alu;
15758 }
15759 else if (GET_MODE_CLASS (mode) == MODE_FLOAT)
15760 {
15761 op0 = XEXP (x, 0);
15762
15763 /* FABD, which is analogous to FADD. */
15764 if (GET_CODE (op0) == MINUS)
15765 {
15766 *cost += rtx_cost (XEXP (op0, 0), mode, MINUS, 0, speed);
15767 *cost += rtx_cost (XEXP (op0, 1), mode, MINUS, 1, speed);
15768 if (speed)
15769 *cost += extra_cost->fp[mode == DFmode].addsub;
15770
15771 return true;
15772 }
15773 /* Simple FABS is analogous to FNEG. */
15774 if (speed)
15775 *cost += extra_cost->fp[mode == DFmode].neg;
15776 }
15777 else
15778 {
15779 /* Integer ABS will either be split to
15780 two arithmetic instructions, or will be an ABS
15781 (scalar), which we don't model. */
15782 *cost = COSTS_N_INSNS (2);
15783 if (speed)
15784 *cost += 2 * extra_cost->alu.arith;
15785 }
15786 return false;
15787
15788 case SMAX:
15789 case SMIN:
15790 if (speed)
15791 {
15792 if (VECTOR_MODE_P (mode))
15793 *cost += extra_cost->vect.alu;
15794 else
15795 {
15796 /* FMAXNM/FMINNM/FMAX/FMIN.
15797 TODO: This may not be accurate for all implementations, but
15798 we do not model this in the cost tables. */
15799 *cost += extra_cost->fp[mode == DFmode].addsub;
15800 }
15801 }
15802 return false;
15803
15804 case UNSPEC:
15805 /* The floating point round to integer frint* instructions. */
15806 if (aarch64_frint_unspec_p (XINT (x, 1)))
15807 {
15808 if (speed)
15809 *cost += extra_cost->fp[mode == DFmode].roundint;
15810
15811 return false;
15812 }
15813 break;
15814
15815 case TRUNCATE:
15816
15817 /* Decompose <su>muldi3_highpart. */
15818 if (/* (truncate:DI */
15819 mode == DImode
15820 /* (lshiftrt:TI */
15821 && GET_MODE (XEXP (x, 0)) == TImode
15822 && GET_CODE (XEXP (x, 0)) == LSHIFTRT
15823 /* (mult:TI */
15824 && GET_CODE (XEXP (XEXP (x, 0), 0)) == MULT
15825 /* (ANY_EXTEND:TI (reg:DI))
15826 (ANY_EXTEND:TI (reg:DI))) */
15827 && ((GET_CODE (XEXP (XEXP (XEXP (x, 0), 0), 0)) == ZERO_EXTEND
15828 && GET_CODE (XEXP (XEXP (XEXP (x, 0), 0), 1)) == ZERO_EXTEND)
15829 || (GET_CODE (XEXP (XEXP (XEXP (x, 0), 0), 0)) == SIGN_EXTEND
15830 && GET_CODE (XEXP (XEXP (XEXP (x, 0), 0), 1)) == SIGN_EXTEND))
15831 && GET_MODE (XEXP (XEXP (XEXP (XEXP (x, 0), 0), 0), 0)) == DImode
15832 && GET_MODE (XEXP (XEXP (XEXP (XEXP (x, 0), 0), 1), 0)) == DImode
15833 /* (const_int 64) */
15834 && CONST_INT_P (XEXP (XEXP (x, 0), 1))
15835 && UINTVAL (XEXP (XEXP (x, 0), 1)) == 64)
15836 {
15837 /* UMULH/SMULH. */
15838 if (speed)
15839 *cost += extra_cost->mult[mode == DImode].extend;
15840 *cost += rtx_cost (XEXP (XEXP (XEXP (XEXP (x, 0), 0), 0), 0),
15841 mode, MULT, 0, speed);
15842 *cost += rtx_cost (XEXP (XEXP (XEXP (XEXP (x, 0), 0), 1), 0),
15843 mode, MULT, 1, speed);
15844 return true;
15845 }
15846 break;
15847 case CONST_VECTOR:
15848 {
15849 /* Load using MOVI/MVNI. */
15850 if (aarch64_simd_valid_mov_imm (x))
15851 *cost = extra_cost->vect.movi;
15852 else /* Load using constant pool. */
15853 *cost = extra_cost->ldst.load;
15854 break;
15855 }
15856 case VEC_CONCAT:
15857 /* depending on the operation, either DUP or INS.
15858 For now, keep default costing. */
15859 break;
15860 case VEC_DUPLICATE:
15861 /* Load using a DUP. */
15862 *cost = extra_cost->vect.dup;
15863 return false;
15864 case VEC_SELECT:
15865 {
15866 rtx op0 = XEXP (x, 0);
15867 *cost = rtx_cost (op0, GET_MODE (op0), VEC_SELECT, 0, speed);
15868
15869 /* cost subreg of 0 as free, otherwise as DUP */
15870 rtx op1 = XEXP (x, 1);
15871 if (vec_series_lowpart_p (mode, GET_MODE (op1), op1))
15872 ;
15873 else if (vec_series_highpart_p (mode, GET_MODE (op1), op1))
15874 *cost = extra_cost->vect.dup;
15875 else
15876 *cost = extra_cost->vect.extract;
15877 return true;
15878 }
15879 default:
15880 break;
15881 }
15882
15883 if (dump_file
15884 && flag_aarch64_verbose_cost)
15885 fprintf (dump_file,
15886 "\nFailed to cost RTX. Assuming default cost.\n");
15887
15888 return true;
15889 }
15890
15891 /* Wrapper around aarch64_rtx_costs, dumps the partial, or total cost
15892 calculated for X. This cost is stored in *COST. Returns true
15893 if the total cost of X was calculated. */
15894 static bool
15895 aarch64_rtx_costs_wrapper (rtx x, machine_mode mode, int outer,
15896 int param, int *cost, bool speed)
15897 {
15898 bool result = aarch64_rtx_costs (x, mode, outer, param, cost, speed);
15899
15900 if (dump_file
15901 && flag_aarch64_verbose_cost)
15902 {
15903 print_rtl_single (dump_file, x);
15904 fprintf (dump_file, "\n%s cost: %d (%s)\n",
15905 speed ? "Hot" : "Cold",
15906 *cost, result ? "final" : "partial");
15907 }
15908
15909 return result;
15910 }
15911
15912 static int
15913 aarch64_register_move_cost (machine_mode mode,
15914 reg_class_t from_i, reg_class_t to_i)
15915 {
15916 enum reg_class from = (enum reg_class) from_i;
15917 enum reg_class to = (enum reg_class) to_i;
15918 const struct cpu_regmove_cost *regmove_cost
15919 = aarch64_tune_params.regmove_cost;
15920
15921 /* Trest any subset of POINTER_REGS as though it were GENERAL_REGS. */
15922 if (reg_class_subset_p (to, POINTER_REGS))
15923 to = GENERAL_REGS;
15924
15925 if (reg_class_subset_p (from, POINTER_REGS))
15926 from = GENERAL_REGS;
15927
15928 /* Make RDFFR very expensive. In particular, if we know that the FFR
15929 contains a PTRUE (e.g. after a SETFFR), we must never use RDFFR
15930 as a way of obtaining a PTRUE. */
15931 if (GET_MODE_CLASS (mode) == MODE_VECTOR_BOOL
15932 && hard_reg_set_subset_p (reg_class_contents[from_i],
15933 reg_class_contents[FFR_REGS]))
15934 return 80;
15935
15936 /* Moves to/from sysregs are expensive, and must go via GPR. */
15937 if (from == MOVEABLE_SYSREGS)
15938 return 80 + aarch64_register_move_cost (mode, GENERAL_REGS, to);
15939 if (to == MOVEABLE_SYSREGS)
15940 return 80 + aarch64_register_move_cost (mode, from, GENERAL_REGS);
15941
15942 /* Moving between GPR and stack cost is the same as GP2GP. */
15943 if ((from == GENERAL_REGS && to == STACK_REG)
15944 || (to == GENERAL_REGS && from == STACK_REG))
15945 return regmove_cost->GP2GP;
15946
15947 /* To/From the stack register, we move via the gprs. */
15948 if (to == STACK_REG || from == STACK_REG)
15949 return aarch64_register_move_cost (mode, from, GENERAL_REGS)
15950 + aarch64_register_move_cost (mode, GENERAL_REGS, to);
15951
15952 unsigned int vec_flags = aarch64_classify_vector_mode (mode);
15953 if (vec_flags != (VEC_ADVSIMD | VEC_STRUCT | VEC_PARTIAL)
15954 && known_eq (GET_MODE_SIZE (mode), 16))
15955 {
15956 /* 128-bit operations on general registers require 2 instructions. */
15957 if (from == GENERAL_REGS && to == GENERAL_REGS)
15958 return regmove_cost->GP2GP * 2;
15959 else if (from == GENERAL_REGS)
15960 return regmove_cost->GP2FP * 2;
15961 else if (to == GENERAL_REGS)
15962 return regmove_cost->FP2GP * 2;
15963
15964 /* When AdvSIMD instructions are disabled it is not possible to move
15965 a 128-bit value directly between Q registers. This is handled in
15966 secondary reload. A general register is used as a scratch to move
15967 the upper DI value and the lower DI value is moved directly,
15968 hence the cost is the sum of three moves. */
15969 if (!TARGET_SIMD && !TARGET_SVE)
15970 return regmove_cost->GP2FP + regmove_cost->FP2GP + regmove_cost->FP2FP;
15971
15972 return regmove_cost->FP2FP;
15973 }
15974
15975 if (from == GENERAL_REGS && to == GENERAL_REGS)
15976 return regmove_cost->GP2GP;
15977 else if (from == GENERAL_REGS)
15978 return regmove_cost->GP2FP;
15979 else if (to == GENERAL_REGS)
15980 return regmove_cost->FP2GP;
15981
15982 if (!TARGET_SIMD && vec_flags == (VEC_ADVSIMD | VEC_STRUCT))
15983 {
15984 /* Needs a round-trip through memory, which can use LDP/STP for pairs.
15985 The cost must be greater than 2 units to indicate that direct
15986 moves aren't possible. */
15987 auto per_vector = (aarch64_tune_params.memmov_cost.load_fp
15988 + aarch64_tune_params.memmov_cost.store_fp);
15989 return MIN (CEIL (per_vector, 2), 4);
15990 }
15991
15992 return regmove_cost->FP2FP;
15993 }
15994
15995 /* Implements TARGET_MEMORY_MOVE_COST. */
15996 static int
15997 aarch64_memory_move_cost (machine_mode mode, reg_class_t rclass_i, bool in)
15998 {
15999 enum reg_class rclass = (enum reg_class) rclass_i;
16000 if (GET_MODE_CLASS (mode) == MODE_VECTOR_BOOL
16001 ? reg_classes_intersect_p (rclass, PR_REGS)
16002 : reg_class_subset_p (rclass, PR_REGS))
16003 return (in
16004 ? aarch64_tune_params.memmov_cost.load_pred
16005 : aarch64_tune_params.memmov_cost.store_pred);
16006
16007 if (VECTOR_MODE_P (mode) || FLOAT_MODE_P (mode)
16008 ? reg_classes_intersect_p (rclass, FP_REGS)
16009 : reg_class_subset_p (rclass, FP_REGS))
16010 return (in
16011 ? aarch64_tune_params.memmov_cost.load_fp
16012 : aarch64_tune_params.memmov_cost.store_fp);
16013
16014 /* If the move needs to go through GPRs, add the cost of doing that. */
16015 int base = 0;
16016 if (rclass_i == MOVEABLE_SYSREGS)
16017 base += (in
16018 ? aarch64_register_move_cost (DImode, GENERAL_REGS, rclass_i)
16019 : aarch64_register_move_cost (DImode, rclass_i, GENERAL_REGS));
16020
16021 return (in
16022 ? base + aarch64_tune_params.memmov_cost.load_int
16023 : base + aarch64_tune_params.memmov_cost.store_int);
16024 }
16025
16026 /* CALLEE_SAVED_REGS is the set of callee-saved registers that the
16027 RA has already decided to use. Return the total number of registers
16028 in class RCLASS that need to be saved and restored, including the
16029 frame link registers. */
16030 static int
16031 aarch64_count_saves (const HARD_REG_SET &callee_saved_regs, reg_class rclass)
16032 {
16033 auto saved_gprs = callee_saved_regs & reg_class_contents[rclass];
16034 auto nregs = hard_reg_set_popcount (saved_gprs);
16035
16036 if (TEST_HARD_REG_BIT (reg_class_contents[rclass], LR_REGNUM))
16037 {
16038 if (aarch64_needs_frame_chain ())
16039 nregs += 2;
16040 else if (!crtl->is_leaf || df_regs_ever_live_p (LR_REGNUM))
16041 nregs += 1;
16042 }
16043 return nregs;
16044 }
16045
16046 /* CALLEE_SAVED_REGS is the set of callee-saved registers that the
16047 RA has already decided to use. Return the total number of registers
16048 that need to be saved above the hard frame pointer, including the
16049 frame link registers. */
16050 static int
16051 aarch64_count_above_hard_fp_saves (const HARD_REG_SET &callee_saved_regs)
16052 {
16053 /* FP and Advanced SIMD registers are saved above the frame pointer
16054 but SVE registers are saved below it. */
16055 if (known_le (GET_MODE_SIZE (aarch64_reg_save_mode (V8_REGNUM)), 16U))
16056 return aarch64_count_saves (callee_saved_regs, POINTER_AND_FP_REGS);
16057 return aarch64_count_saves (callee_saved_regs, POINTER_REGS);
16058 }
16059
16060 /* Implement TARGET_CALLEE_SAVE_COST. */
16061 static int
16062 aarch64_callee_save_cost (spill_cost_type spill_type, unsigned int regno,
16063 machine_mode mode, unsigned int nregs, int mem_cost,
16064 const HARD_REG_SET &callee_saved_regs,
16065 bool existing_spill_p)
16066 {
16067 /* If we've already committed to saving an odd number of GPRs, assume that
16068 saving one more will involve turning an STR into an STP and an LDR
16069 into an LDP. This should still be more expensive than not spilling
16070 (meaning that the minimum cost is 1), but it should usually be cheaper
16071 than a separate store or load. */
16072 if (GP_REGNUM_P (regno)
16073 && nregs == 1
16074 && (aarch64_count_saves (callee_saved_regs, GENERAL_REGS) & 1))
16075 return 1;
16076
16077 /* Similarly for saving FP registers, if we only need to save the low
16078 64 bits. (We can also use STP/LDP instead of STR/LDR for Q registers,
16079 but that is less likely to be a saving.) */
16080 if (FP_REGNUM_P (regno)
16081 && nregs == 1
16082 && known_eq (GET_MODE_SIZE (aarch64_reg_save_mode (regno)), 8U)
16083 && (aarch64_count_saves (callee_saved_regs, FP_REGS) & 1))
16084 return 1;
16085
16086 /* If this would be the first register that we save, add the cost of
16087 allocating or deallocating the frame. For GPR, FPR, and Advanced SIMD
16088 saves, the allocation and deallocation can be folded into the save and
16089 restore. */
16090 if (!existing_spill_p
16091 && !GP_REGNUM_P (regno)
16092 && !(FP_REGNUM_P (regno)
16093 && known_le (GET_MODE_SIZE (aarch64_reg_save_mode (regno)), 16U)))
16094 return default_callee_save_cost (spill_type, regno, mode, nregs, mem_cost,
16095 callee_saved_regs, existing_spill_p);
16096
16097 return mem_cost;
16098 }
16099
16100 /* Implement TARGET_FRAME_ALLOCATION_COST. */
16101 static int
16102 aarch64_frame_allocation_cost (frame_cost_type,
16103 const HARD_REG_SET &callee_saved_regs)
16104 {
16105 /* The intention is to model the relative costs of different approaches
16106 to storing data on the stack, rather than to model the cost of saving
16107 data vs not saving it. This means that we should return 0 if:
16108
16109 - any frame is going to be allocated with:
16110
16111 stp x29, x30, [sp, #-...]!
16112
16113 to create a frame link.
16114
16115 - any frame is going to be allocated with:
16116
16117 str x30, [sp, #-...]!
16118
16119 to save the link register.
16120
16121 In both cases, the allocation and deallocation instructions are the
16122 same however we store data to the stack. (In the second case, the STR
16123 could be converted to an STP by saving an extra call-preserved register,
16124 but that is modeled by aarch64_callee_save_cost.)
16125
16126 In other cases, assume that a frame would need to be allocated with a
16127 separate subtraction and deallocated with a separate addition. Saves
16128 of call-clobbered registers can then reclaim this cost using a
16129 predecrement store and a postincrement load.
16130
16131 For simplicity, give this addition or subtraction the same cost as
16132 a GPR move. We could parameterize this if necessary. */
16133 if (aarch64_count_above_hard_fp_saves (callee_saved_regs) == 0)
16134 return aarch64_tune_params.regmove_cost->GP2GP;
16135 return 0;
16136 }
16137
16138 /* Implement TARGET_INSN_COST. We have the opportunity to do something
16139 much more productive here, such as using insn attributes to cost things.
16140 But we don't, not yet.
16141
16142 The main point of this current definition is to make calling insn_cost
16143 on one instruction equivalent to calling seq_cost on a sequence that
16144 contains only that instruction. The default definition would instead
16145 only look at SET_SRCs, ignoring SET_DESTs.
16146
16147 This ensures that, for example, storing a 128-bit zero vector is more
16148 expensive than storing a 128-bit vector register. A move of zero
16149 into a 128-bit vector register followed by multiple stores of that
16150 register is then cheaper than multiple stores of zero (which would
16151 use STP of XZR). This in turn allows STP Qs to be formed. */
16152 static int
16153 aarch64_insn_cost (rtx_insn *insn, bool speed)
16154 {
16155 if (rtx set = single_set (insn))
16156 return set_rtx_cost (set, speed);
16157
16158 /* If the instruction does multiple sets in parallel, use the cost
16159 of the most expensive set. This copes with instructions that set
16160 the flags to a useful value as a side effect. */
16161 rtx pat = PATTERN (insn);
16162 if (GET_CODE (pat) == PARALLEL)
16163 {
16164 int max_cost = 0;
16165 for (int i = 0; i < XVECLEN (pat, 0); ++i)
16166 {
16167 rtx x = XVECEXP (pat, 0, i);
16168 if (GET_CODE (x) == SET)
16169 max_cost = std::max (max_cost, set_rtx_cost (x, speed));
16170 }
16171 return max_cost;
16172 }
16173
16174 return pattern_cost (pat, speed);
16175 }
16176
16177 /* Implement TARGET_INIT_BUILTINS. */
16178 static void
16179 aarch64_init_builtins ()
16180 {
16181 aarch64_general_init_builtins ();
16182 aarch64_sve::init_builtins ();
16183 #ifdef SUBTARGET_INIT_BUILTINS
16184 SUBTARGET_INIT_BUILTINS;
16185 #endif
16186 }
16187
16188 /* Implement TARGET_FOLD_BUILTIN. */
16189 static tree
16190 aarch64_fold_builtin (tree fndecl, int nargs, tree *args, bool)
16191 {
16192 unsigned int code = DECL_MD_FUNCTION_CODE (fndecl);
16193 unsigned int subcode = code >> AARCH64_BUILTIN_SHIFT;
16194 tree type = TREE_TYPE (TREE_TYPE (fndecl));
16195 switch (code & AARCH64_BUILTIN_CLASS)
16196 {
16197 case AARCH64_BUILTIN_GENERAL:
16198 return aarch64_general_fold_builtin (subcode, type, nargs, args);
16199
16200 case AARCH64_BUILTIN_SVE:
16201 return NULL_TREE;
16202 }
16203 gcc_unreachable ();
16204 }
16205
16206 /* Implement TARGET_GIMPLE_FOLD_BUILTIN. */
16207 static bool
16208 aarch64_gimple_fold_builtin (gimple_stmt_iterator *gsi)
16209 {
16210 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
16211 tree fndecl = gimple_call_fndecl (stmt);
16212 unsigned int code = DECL_MD_FUNCTION_CODE (fndecl);
16213 unsigned int subcode = code >> AARCH64_BUILTIN_SHIFT;
16214 gimple *new_stmt = NULL;
16215 switch (code & AARCH64_BUILTIN_CLASS)
16216 {
16217 case AARCH64_BUILTIN_GENERAL:
16218 new_stmt = aarch64_general_gimple_fold_builtin (subcode, stmt, gsi);
16219 break;
16220
16221 case AARCH64_BUILTIN_SVE:
16222 new_stmt = aarch64_sve::gimple_fold_builtin (subcode, gsi, stmt);
16223 break;
16224 }
16225
16226 if (!new_stmt)
16227 return false;
16228
16229 gsi_replace (gsi, new_stmt, false);
16230 return true;
16231 }
16232
16233 /* Implement TARGET_EXPAND_BUILTIN. */
16234 static rtx
16235 aarch64_expand_builtin (tree exp, rtx target, rtx, machine_mode, int ignore)
16236 {
16237 tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
16238 unsigned int code = DECL_MD_FUNCTION_CODE (fndecl);
16239 unsigned int subcode = code >> AARCH64_BUILTIN_SHIFT;
16240 switch (code & AARCH64_BUILTIN_CLASS)
16241 {
16242 case AARCH64_BUILTIN_GENERAL:
16243 return aarch64_general_expand_builtin (subcode, exp, target, ignore);
16244
16245 case AARCH64_BUILTIN_SVE:
16246 return aarch64_sve::expand_builtin (subcode, exp, target);
16247 }
16248 gcc_unreachable ();
16249 }
16250
16251 /* Implement TARGET_BUILTIN_DECL. */
16252 static tree
16253 aarch64_builtin_decl (unsigned int code, bool initialize_p)
16254 {
16255 unsigned int subcode = code >> AARCH64_BUILTIN_SHIFT;
16256 switch (code & AARCH64_BUILTIN_CLASS)
16257 {
16258 case AARCH64_BUILTIN_GENERAL:
16259 return aarch64_general_builtin_decl (subcode, initialize_p);
16260
16261 case AARCH64_BUILTIN_SVE:
16262 return aarch64_sve::builtin_decl (subcode, initialize_p);
16263 }
16264 gcc_unreachable ();
16265 }
16266
16267 /* Return true if it is safe and beneficial to use the approximate rsqrt optabs
16268 to optimize 1.0/sqrt. */
16269
16270 static bool
16271 use_rsqrt_p (machine_mode mode)
16272 {
16273 return (!flag_trapping_math
16274 && flag_unsafe_math_optimizations
16275 && ((aarch64_tune_params.approx_modes->recip_sqrt
16276 & AARCH64_APPROX_MODE (mode))
16277 || flag_mrecip_low_precision_sqrt));
16278 }
16279
16280 /* Function to decide when to use the approximate reciprocal square root
16281 builtin. */
16282
16283 static tree
16284 aarch64_builtin_reciprocal (tree fndecl)
16285 {
16286 machine_mode mode = TYPE_MODE (TREE_TYPE (fndecl));
16287
16288 if (!use_rsqrt_p (mode))
16289 return NULL_TREE;
16290 unsigned int code = DECL_MD_FUNCTION_CODE (fndecl);
16291 unsigned int subcode = code >> AARCH64_BUILTIN_SHIFT;
16292 switch (code & AARCH64_BUILTIN_CLASS)
16293 {
16294 case AARCH64_BUILTIN_GENERAL:
16295 return aarch64_general_builtin_rsqrt (subcode);
16296
16297 case AARCH64_BUILTIN_SVE:
16298 return NULL_TREE;
16299 }
16300 gcc_unreachable ();
16301 }
16302
16303 /* Emit code to perform the floating-point operation:
16304
16305 DST = SRC1 * SRC2
16306
16307 where all three operands are already known to be registers.
16308 If the operation is an SVE one, PTRUE is a suitable all-true
16309 predicate. */
16310
16311 static void
16312 aarch64_emit_mult (rtx dst, rtx ptrue, rtx src1, rtx src2)
16313 {
16314 if (ptrue)
16315 emit_insn (gen_aarch64_pred (UNSPEC_COND_FMUL, GET_MODE (dst),
16316 dst, ptrue, src1, src2,
16317 gen_int_mode (SVE_RELAXED_GP, SImode)));
16318 else
16319 emit_set_insn (dst, gen_rtx_MULT (GET_MODE (dst), src1, src2));
16320 }
16321
16322 /* Emit instruction sequence to compute either the approximate square root
16323 or its approximate reciprocal, depending on the flag RECP, and return
16324 whether the sequence was emitted or not. */
16325
16326 bool
16327 aarch64_emit_approx_sqrt (rtx dst, rtx src, bool recp)
16328 {
16329 machine_mode mode = GET_MODE (dst);
16330
16331 if (GET_MODE_INNER (mode) == HFmode)
16332 {
16333 gcc_assert (!recp);
16334 return false;
16335 }
16336
16337 if (!recp)
16338 {
16339 if (!(flag_mlow_precision_sqrt
16340 || (aarch64_tune_params.approx_modes->sqrt
16341 & AARCH64_APPROX_MODE (mode))))
16342 return false;
16343
16344 if (!flag_finite_math_only
16345 || flag_trapping_math
16346 || !flag_unsafe_math_optimizations
16347 || optimize_function_for_size_p (cfun))
16348 return false;
16349 }
16350 else
16351 /* Caller assumes we cannot fail. */
16352 gcc_assert (use_rsqrt_p (mode));
16353
16354 rtx pg = NULL_RTX;
16355 if (aarch64_sve_mode_p (mode))
16356 pg = aarch64_ptrue_reg (aarch64_sve_pred_mode (mode));
16357 machine_mode mmsk = (VECTOR_MODE_P (mode)
16358 ? related_int_vector_mode (mode).require ()
16359 : int_mode_for_mode (mode).require ());
16360 rtx xmsk = NULL_RTX;
16361 if (!recp)
16362 {
16363 /* When calculating the approximate square root, compare the
16364 argument with 0.0 and create a mask. */
16365 rtx zero = CONST0_RTX (mode);
16366 if (pg)
16367 {
16368 xmsk = gen_reg_rtx (GET_MODE (pg));
16369 rtx hint = gen_int_mode (SVE_KNOWN_PTRUE, SImode);
16370 emit_insn (gen_aarch64_pred_fcm (UNSPEC_COND_FCMNE, mode,
16371 xmsk, pg, hint, src, zero));
16372 }
16373 else
16374 {
16375 xmsk = gen_reg_rtx (mmsk);
16376 emit_insn (gen_rtx_SET (xmsk,
16377 gen_rtx_NEG (mmsk,
16378 gen_rtx_EQ (mmsk, src, zero))));
16379 }
16380 }
16381
16382 /* Estimate the approximate reciprocal square root. */
16383 rtx xdst = gen_reg_rtx (mode);
16384 emit_insn (gen_aarch64_rsqrte (mode, xdst, src));
16385
16386 /* Iterate over the series twice for SF and thrice for DF. */
16387 int iterations = (GET_MODE_INNER (mode) == DFmode) ? 3 : 2;
16388
16389 /* Optionally iterate over the series once less for faster performance
16390 while sacrificing the accuracy. */
16391 if ((recp && flag_mrecip_low_precision_sqrt)
16392 || (!recp && flag_mlow_precision_sqrt))
16393 iterations--;
16394
16395 /* Iterate over the series to calculate the approximate reciprocal square
16396 root. */
16397 rtx x1 = gen_reg_rtx (mode);
16398 while (iterations--)
16399 {
16400 rtx x2 = gen_reg_rtx (mode);
16401 aarch64_emit_mult (x2, pg, xdst, xdst);
16402
16403 emit_insn (gen_aarch64_rsqrts (mode, x1, src, x2));
16404
16405 if (iterations > 0)
16406 aarch64_emit_mult (xdst, pg, xdst, x1);
16407 }
16408
16409 if (!recp)
16410 {
16411 if (pg)
16412 /* Multiply nonzero source values by the corresponding intermediate
16413 result elements, so that the final calculation is the approximate
16414 square root rather than its reciprocal. Select a zero result for
16415 zero source values, to avoid the Inf * 0 -> NaN that we'd get
16416 otherwise. */
16417 emit_insn (gen_cond (UNSPEC_COND_FMUL, mode,
16418 xdst, xmsk, xdst, src, CONST0_RTX (mode)));
16419 else
16420 {
16421 /* Qualify the approximate reciprocal square root when the
16422 argument is 0.0 by squashing the intermediary result to 0.0. */
16423 rtx xtmp = gen_reg_rtx (mmsk);
16424 emit_set_insn (xtmp, gen_rtx_AND (mmsk, gen_rtx_NOT (mmsk, xmsk),
16425 gen_rtx_SUBREG (mmsk, xdst, 0)));
16426 emit_move_insn (xdst, gen_rtx_SUBREG (mode, xtmp, 0));
16427
16428 /* Calculate the approximate square root. */
16429 aarch64_emit_mult (xdst, pg, xdst, src);
16430 }
16431 }
16432
16433 /* Finalize the approximation. */
16434 aarch64_emit_mult (dst, pg, xdst, x1);
16435
16436 return true;
16437 }
16438
16439 /* Emit the instruction sequence to compute the approximation for the division
16440 of NUM by DEN in QUO and return whether the sequence was emitted or not. */
16441
16442 bool
16443 aarch64_emit_approx_div (rtx quo, rtx num, rtx den)
16444 {
16445 machine_mode mode = GET_MODE (quo);
16446
16447 if (GET_MODE_INNER (mode) == HFmode)
16448 return false;
16449
16450 bool use_approx_division_p = (flag_mlow_precision_div
16451 || (aarch64_tune_params.approx_modes->division
16452 & AARCH64_APPROX_MODE (mode)));
16453
16454 if (!flag_finite_math_only
16455 || flag_trapping_math
16456 || !flag_unsafe_math_optimizations
16457 || optimize_function_for_size_p (cfun)
16458 || !use_approx_division_p)
16459 return false;
16460
16461 if (!TARGET_SIMD && VECTOR_MODE_P (mode))
16462 return false;
16463
16464 rtx pg = NULL_RTX;
16465 if (aarch64_sve_mode_p (mode))
16466 pg = aarch64_ptrue_reg (aarch64_sve_pred_mode (mode));
16467
16468 /* Estimate the approximate reciprocal. */
16469 rtx xrcp = gen_reg_rtx (mode);
16470 emit_insn (gen_aarch64_frecpe (mode, xrcp, den));
16471
16472 /* Iterate over the series twice for SF and thrice for DF. */
16473 int iterations = (GET_MODE_INNER (mode) == DFmode) ? 3 : 2;
16474
16475 /* Optionally iterate over the series less for faster performance,
16476 while sacrificing the accuracy. The default is 2 for DF and 1 for SF. */
16477 if (flag_mlow_precision_div)
16478 iterations = (GET_MODE_INNER (mode) == DFmode
16479 ? aarch64_double_recp_precision
16480 : aarch64_float_recp_precision);
16481
16482 /* Iterate over the series to calculate the approximate reciprocal. */
16483 rtx xtmp = gen_reg_rtx (mode);
16484 while (iterations--)
16485 {
16486 emit_insn (gen_aarch64_frecps (mode, xtmp, xrcp, den));
16487
16488 if (iterations > 0)
16489 aarch64_emit_mult (xrcp, pg, xrcp, xtmp);
16490 }
16491
16492 if (num != CONST1_RTX (mode))
16493 {
16494 /* As the approximate reciprocal of DEN is already calculated, only
16495 calculate the approximate division when NUM is not 1.0. */
16496 rtx xnum = force_reg (mode, num);
16497 aarch64_emit_mult (xrcp, pg, xrcp, xnum);
16498 }
16499
16500 /* Finalize the approximation. */
16501 aarch64_emit_mult (quo, pg, xrcp, xtmp);
16502 return true;
16503 }
16504
16505 /* Emit an optimized sequence to perform a vector rotate
16506 of REG by the vector constant amount AMNT_VEC and place the result
16507 in DST. Return true iff successful. */
16508
16509 bool
16510 aarch64_emit_opt_vec_rotate (rtx dst, rtx reg, rtx amnt_vec)
16511 {
16512 rtx amnt = unwrap_const_vec_duplicate (amnt_vec);
16513 gcc_assert (CONST_INT_P (amnt));
16514 HOST_WIDE_INT rotamnt = UINTVAL (amnt);
16515 machine_mode mode = GET_MODE (reg);
16516 /* Don't end up here after reload. */
16517 gcc_assert (can_create_pseudo_p ());
16518 /* Rotates by half the element width map down to REV* instructions and should
16519 always be preferred when possible. */
16520 if (rotamnt == GET_MODE_UNIT_BITSIZE (mode) / 2
16521 && expand_rotate_as_vec_perm (mode, dst, reg, amnt))
16522 return true;
16523 /* 64 and 128-bit vector modes can use the XAR instruction
16524 when available. */
16525 else if ((TARGET_SHA3 && mode == V2DImode)
16526 || (TARGET_SVE2
16527 && (known_eq (GET_MODE_SIZE (mode), 8)
16528 || known_eq (GET_MODE_SIZE (mode), 16))))
16529 {
16530 rtx zeroes = aarch64_gen_shareable_zero (mode);
16531 rtx xar_op
16532 = gen_rtx_ROTATE (mode, gen_rtx_XOR (mode, reg, zeroes),
16533 amnt_vec);
16534 emit_set_insn (dst, xar_op);
16535 return true;
16536 }
16537 /* If none of the above, try to expand rotates by any byte amount as
16538 permutes. */
16539 else if (expand_rotate_as_vec_perm (mode, dst, reg, amnt))
16540 return true;
16541 return false;
16542 }
16543
16544 /* Return the number of instructions that can be issued per cycle. */
16545 static int
16546 aarch64_sched_issue_rate (void)
16547 {
16548 return aarch64_tune_params.issue_rate;
16549 }
16550
16551 /* Implement TARGET_SCHED_VARIABLE_ISSUE. */
16552 static int
16553 aarch64_sched_variable_issue (FILE *, int, rtx_insn *insn, int more)
16554 {
16555 if (DEBUG_INSN_P (insn))
16556 return more;
16557
16558 rtx_code code = GET_CODE (PATTERN (insn));
16559 if (code == USE || code == CLOBBER)
16560 return more;
16561
16562 if (get_attr_type (insn) == TYPE_NO_INSN)
16563 return more;
16564
16565 return more - 1;
16566 }
16567
16568 static int
16569 aarch64_sched_first_cycle_multipass_dfa_lookahead (void)
16570 {
16571 int issue_rate = aarch64_sched_issue_rate ();
16572
16573 return issue_rate > 1 && !sched_fusion ? issue_rate : 0;
16574 }
16575
16576
16577 /* Implement TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD as
16578 autopref_multipass_dfa_lookahead_guard from haifa-sched.cc. It only
16579 has an effect if PARAM_SCHED_AUTOPREF_QUEUE_DEPTH > 0. */
16580
16581 static int
16582 aarch64_first_cycle_multipass_dfa_lookahead_guard (rtx_insn *insn,
16583 int ready_index)
16584 {
16585 return autopref_multipass_dfa_lookahead_guard (insn, ready_index);
16586 }
16587
16588
16589 /* Vectorizer cost model target hooks. */
16590
16591 /* If a vld1 from address ADDR should be recorded in vector_load_decls,
16592 return the decl that should be recorded. Return null otherwise. */
16593 tree
16594 aarch64_vector_load_decl (tree addr)
16595 {
16596 if (TREE_CODE (addr) != ADDR_EXPR)
16597 return NULL_TREE;
16598 tree base = get_base_address (TREE_OPERAND (addr, 0));
16599 if (TREE_CODE (base) != VAR_DECL)
16600 return NULL_TREE;
16601 return base;
16602 }
16603
16604 /* Return true if STMT_INFO accesses a decl that is known to be the
16605 argument to a vld1 in the same function. */
16606 static bool
16607 aarch64_accesses_vector_load_decl_p (stmt_vec_info stmt_info)
16608 {
16609 if (!cfun->machine->vector_load_decls)
16610 return false;
16611 auto dr = STMT_VINFO_DATA_REF (stmt_info);
16612 if (!dr)
16613 return false;
16614 tree decl = aarch64_vector_load_decl (DR_BASE_ADDRESS (dr));
16615 return decl && cfun->machine->vector_load_decls->contains (decl);
16616 }
16617
16618 /* Information about how the CPU would issue the scalar, Advanced SIMD
16619 or SVE version of a vector loop, using the scheme defined by the
16620 aarch64_base_vec_issue_info hierarchy of structures. */
16621 class aarch64_vec_op_count
16622 {
16623 public:
16624 aarch64_vec_op_count () = default;
16625 aarch64_vec_op_count (const aarch64_vec_issue_info *, unsigned int,
16626 unsigned int = 1);
16627
16628 unsigned int vec_flags () const { return m_vec_flags; }
16629 unsigned int vf_factor () const { return m_vf_factor; }
16630
16631 const aarch64_base_vec_issue_info *base_issue_info () const;
16632 const aarch64_simd_vec_issue_info *simd_issue_info () const;
16633 const aarch64_sve_vec_issue_info *sve_issue_info () const;
16634
16635 fractional_cost rename_cycles_per_iter () const;
16636 fractional_cost min_nonpred_cycles_per_iter () const;
16637 fractional_cost min_pred_cycles_per_iter () const;
16638 fractional_cost min_cycles_per_iter () const;
16639
16640 void dump () const;
16641
16642 /* The number of individual "general" operations. See the comments
16643 in aarch64_base_vec_issue_info for details. */
16644 unsigned int general_ops = 0;
16645
16646 /* The number of load and store operations, under the same scheme
16647 as above. */
16648 unsigned int loads = 0;
16649 unsigned int stores = 0;
16650
16651 /* The minimum number of cycles needed to execute all loop-carried
16652 operations, which in the vector code become associated with
16653 reductions. */
16654 unsigned int reduction_latency = 0;
16655
16656 /* The number of individual predicate operations. See the comments
16657 in aarch64_sve_vec_issue_info for details. */
16658 unsigned int pred_ops = 0;
16659
16660 private:
16661 /* The issue information for the core. */
16662 const aarch64_vec_issue_info *m_issue_info = nullptr;
16663
16664 /* - If M_VEC_FLAGS is zero then this structure describes scalar code
16665 - If M_VEC_FLAGS & VEC_ADVSIMD is nonzero then this structure describes
16666 Advanced SIMD code.
16667 - If M_VEC_FLAGS & VEC_ANY_SVE is nonzero then this structure describes
16668 SVE code. */
16669 unsigned int m_vec_flags = 0;
16670
16671 /* Assume that, when the code is executing on the core described
16672 by M_ISSUE_INFO, one iteration of the loop will handle M_VF_FACTOR
16673 times more data than the vectorizer anticipates.
16674
16675 This is only ever different from 1 for SVE. It allows us to consider
16676 what would happen on a 256-bit SVE target even when the -mtune
16677 parameters say that the “likely” SVE length is 128 bits. */
16678 unsigned int m_vf_factor = 1;
16679 };
16680
16681 aarch64_vec_op_count::
16682 aarch64_vec_op_count (const aarch64_vec_issue_info *issue_info,
16683 unsigned int vec_flags, unsigned int vf_factor)
16684 : m_issue_info (issue_info),
16685 m_vec_flags (vec_flags),
16686 m_vf_factor (vf_factor)
16687 {
16688 }
16689
16690 /* Return the base issue information (i.e. the parts that make sense
16691 for both scalar and vector code). Return null if we have no issue
16692 information. */
16693 const aarch64_base_vec_issue_info *
16694 aarch64_vec_op_count::base_issue_info () const
16695 {
16696 if (auto *ret = simd_issue_info ())
16697 return ret;
16698 return m_issue_info->scalar;
16699 }
16700
16701 /* If the structure describes vector code and we have associated issue
16702 information, return that issue information, otherwise return null. */
16703 const aarch64_simd_vec_issue_info *
16704 aarch64_vec_op_count::simd_issue_info () const
16705 {
16706 if (auto *ret = sve_issue_info ())
16707 return ret;
16708 if (m_vec_flags)
16709 return m_issue_info->advsimd;
16710 return nullptr;
16711 }
16712
16713 /* If the structure describes SVE code and we have associated issue
16714 information, return that issue information, otherwise return null. */
16715 const aarch64_sve_vec_issue_info *
16716 aarch64_vec_op_count::sve_issue_info () const
16717 {
16718 if (m_vec_flags & VEC_ANY_SVE)
16719 return m_issue_info->sve;
16720 return nullptr;
16721 }
16722
16723 /* Estimate the minimum number of cycles per iteration needed to rename
16724 the instructions.
16725
16726 ??? For now this is done inline rather than via cost tables, since it
16727 isn't clear how it should be parameterized for the general case. */
16728 fractional_cost
16729 aarch64_vec_op_count::rename_cycles_per_iter () const
16730 {
16731 if (sve_issue_info () == &neoverse512tvb_sve_issue_info
16732 || sve_issue_info () == &neoversen2_sve_issue_info
16733 || sve_issue_info () == &neoversev2_sve_issue_info)
16734 /* + 1 for an addition. We've already counted a general op for each
16735 store, so we don't need to account for stores separately. The branch
16736 reads no registers and so does not need to be counted either.
16737
16738 ??? This value is very much on the pessimistic side, but seems to work
16739 pretty well in practice. */
16740 return { general_ops + loads + pred_ops + 1, 5 };
16741
16742 return 0;
16743 }
16744
16745 /* Like min_cycles_per_iter, but excluding predicate operations. */
16746 fractional_cost
16747 aarch64_vec_op_count::min_nonpred_cycles_per_iter () const
16748 {
16749 auto *issue_info = base_issue_info ();
16750
16751 fractional_cost cycles = MAX (reduction_latency, 1);
16752 cycles = std::max (cycles, { stores, issue_info->stores_per_cycle });
16753 cycles = std::max (cycles, { loads + stores,
16754 issue_info->loads_stores_per_cycle });
16755 cycles = std::max (cycles, { general_ops,
16756 issue_info->general_ops_per_cycle });
16757 cycles = std::max (cycles, rename_cycles_per_iter ());
16758 return cycles;
16759 }
16760
16761 /* Like min_cycles_per_iter, but including only the predicate operations. */
16762 fractional_cost
16763 aarch64_vec_op_count::min_pred_cycles_per_iter () const
16764 {
16765 if (auto *issue_info = sve_issue_info ())
16766 return { pred_ops, issue_info->pred_ops_per_cycle };
16767 return 0;
16768 }
16769
16770 /* Estimate the minimum number of cycles needed to issue the operations.
16771 This is a very simplistic model! */
16772 fractional_cost
16773 aarch64_vec_op_count::min_cycles_per_iter () const
16774 {
16775 return std::max (min_nonpred_cycles_per_iter (),
16776 min_pred_cycles_per_iter ());
16777 }
16778
16779 /* Dump information about the structure. */
16780 void
16781 aarch64_vec_op_count::dump () const
16782 {
16783 dump_printf_loc (MSG_NOTE, vect_location,
16784 " load operations = %d\n", loads);
16785 dump_printf_loc (MSG_NOTE, vect_location,
16786 " store operations = %d\n", stores);
16787 dump_printf_loc (MSG_NOTE, vect_location,
16788 " general operations = %d\n", general_ops);
16789 if (sve_issue_info ())
16790 dump_printf_loc (MSG_NOTE, vect_location,
16791 " predicate operations = %d\n", pred_ops);
16792 dump_printf_loc (MSG_NOTE, vect_location,
16793 " reduction latency = %d\n", reduction_latency);
16794 if (auto rcpi = rename_cycles_per_iter ())
16795 dump_printf_loc (MSG_NOTE, vect_location,
16796 " estimated cycles per iteration to rename = %f\n",
16797 rcpi.as_double ());
16798 if (auto pred_cpi = min_pred_cycles_per_iter ())
16799 {
16800 dump_printf_loc (MSG_NOTE, vect_location,
16801 " estimated min cycles per iteration"
16802 " without predication = %f\n",
16803 min_nonpred_cycles_per_iter ().as_double ());
16804 dump_printf_loc (MSG_NOTE, vect_location,
16805 " estimated min cycles per iteration"
16806 " for predication = %f\n", pred_cpi.as_double ());
16807 }
16808 if (auto cpi = min_cycles_per_iter ())
16809 dump_printf_loc (MSG_NOTE, vect_location,
16810 " estimated min cycles per iteration = %f\n",
16811 cpi.as_double ());
16812 }
16813
16814 /* Information about vector code that we're in the process of costing. */
16815 class aarch64_vector_costs : public vector_costs
16816 {
16817 public:
16818 aarch64_vector_costs (vec_info *, bool);
16819
16820 unsigned int add_stmt_cost (int count, vect_cost_for_stmt kind,
16821 stmt_vec_info stmt_info, slp_tree, tree vectype,
16822 int misalign,
16823 vect_cost_model_location where) override;
16824 void finish_cost (const vector_costs *) override;
16825 bool better_main_loop_than_p (const vector_costs *other) const override;
16826
16827 private:
16828 void record_potential_advsimd_unrolling (loop_vec_info);
16829 void analyze_loop_vinfo (loop_vec_info);
16830 void count_ops (unsigned int, vect_cost_for_stmt, stmt_vec_info, slp_tree,
16831 aarch64_vec_op_count *);
16832 fractional_cost adjust_body_cost_sve (const aarch64_vec_op_count *,
16833 fractional_cost, unsigned int,
16834 unsigned int *, bool *);
16835 unsigned int adjust_body_cost (loop_vec_info, const aarch64_vector_costs *,
16836 unsigned int);
16837 bool prefer_unrolled_loop () const;
16838 unsigned int determine_suggested_unroll_factor ();
16839
16840 /* True if we have performed one-time initialization based on the
16841 vec_info. */
16842 bool m_analyzed_vinfo = false;
16843
16844 /* This loop uses an average operation that is not supported by SVE, but is
16845 supported by Advanced SIMD and SVE2. */
16846 bool m_has_avg = false;
16847
16848 /* Additional initialization costs for using gather or scatter operation in
16849 the current loop. */
16850 unsigned int m_sve_gather_scatter_init_cost = 0;
16851
16852 /* True if the vector body contains a store to a decl and if the
16853 function is known to have a vld1 from the same decl.
16854
16855 In the Advanced SIMD ACLE, the recommended endian-agnostic way of
16856 initializing a vector is:
16857
16858 float f[4] = { elts };
16859 float32x4_t x = vld1q_f32(f);
16860
16861 We should strongly prefer vectorization of the initialization of f,
16862 so that the store to f and the load back can be optimized away,
16863 leaving a vectorization of { elts }. */
16864 bool m_stores_to_vector_load_decl = false;
16865
16866 /* Non-zero if the last operation we costed is a vector promotion or demotion.
16867 In this case the value is the number of insns in the last operation.
16868
16869 On AArch64 vector promotion and demotions require us to first widen or
16870 narrow the input and only after that emit conversion instructions. For
16871 costing this means we need to emit the cost of the final conversions as
16872 well. */
16873 unsigned int m_num_last_promote_demote = 0;
16874
16875 /* - If M_VEC_FLAGS is zero then we're costing the original scalar code.
16876 - If M_VEC_FLAGS & VEC_ADVSIMD is nonzero then we're costing Advanced
16877 SIMD code.
16878 - If M_VEC_FLAGS & VEC_ANY_SVE is nonzero then we're costing SVE code. */
16879 unsigned int m_vec_flags = 0;
16880
16881 /* At the moment, we do not model LDP and STP in the vector and scalar costs.
16882 This means that code such as:
16883
16884 a[0] = x;
16885 a[1] = x;
16886
16887 will be costed as two scalar instructions and two vector instructions
16888 (a scalar_to_vec and an unaligned_store). For SLP, the vector form
16889 wins if the costs are equal, because of the fact that the vector costs
16890 include constant initializations whereas the scalar costs don't.
16891 We would therefore tend to vectorize the code above, even though
16892 the scalar version can use a single STP.
16893
16894 We should eventually fix this and model LDP and STP in the main costs;
16895 see the comment in aarch64_sve_adjust_stmt_cost for some of the problems.
16896 Until then, we look specifically for code that does nothing more than
16897 STP-like operations. We cost them on that basis in addition to the
16898 normal latency-based costs.
16899
16900 If the scalar or vector code could be a sequence of STPs +
16901 initialization, this variable counts the cost of the sequence,
16902 with 2 units per instruction. The variable is ~0U for other
16903 kinds of code. */
16904 unsigned int m_stp_sequence_cost = 0;
16905
16906 /* On some CPUs, SVE and Advanced SIMD provide the same theoretical vector
16907 throughput, such as 4x128 Advanced SIMD vs. 2x256 SVE. In those
16908 situations, we try to predict whether an Advanced SIMD implementation
16909 of the loop could be completely unrolled and become straight-line code.
16910 If so, it is generally better to use the Advanced SIMD version rather
16911 than length-agnostic SVE, since the SVE loop would execute an unknown
16912 number of times and so could not be completely unrolled in the same way.
16913
16914 If we're applying this heuristic, M_UNROLLED_ADVSIMD_NITERS is the
16915 number of Advanced SIMD loop iterations that would be unrolled and
16916 M_UNROLLED_ADVSIMD_STMTS estimates the total number of statements
16917 in the unrolled loop. Both values are zero if we're not applying
16918 the heuristic. */
16919 unsigned HOST_WIDE_INT m_unrolled_advsimd_niters = 0;
16920 unsigned HOST_WIDE_INT m_unrolled_advsimd_stmts = 0;
16921
16922 /* If we're vectorizing a loop that executes a constant number of times,
16923 this variable gives the number of times that the vector loop would
16924 iterate, otherwise it is zero. */
16925 uint64_t m_num_vector_iterations = 0;
16926
16927 /* Used only when vectorizing loops. Estimates the number and kind of
16928 operations that would be needed by one iteration of the scalar
16929 or vector loop. There is one entry for each tuning option of
16930 interest. */
16931 auto_vec<aarch64_vec_op_count, 2> m_ops;
16932 };
16933
16934 aarch64_vector_costs::aarch64_vector_costs (vec_info *vinfo,
16935 bool costing_for_scalar)
16936 : vector_costs (vinfo, costing_for_scalar),
16937 m_vec_flags (costing_for_scalar ? 0
16938 : aarch64_classify_vector_mode (vinfo->vector_mode))
16939 {
16940 if (auto *issue_info = aarch64_tune_params.vec_costs->issue_info)
16941 {
16942 m_ops.quick_push ({ issue_info, m_vec_flags });
16943 if (aarch64_tune_params.vec_costs == &neoverse512tvb_vector_cost)
16944 {
16945 unsigned int vf_factor = (m_vec_flags & VEC_ANY_SVE) ? 2 : 1;
16946 m_ops.quick_push ({ &neoversev1_vec_issue_info, m_vec_flags,
16947 vf_factor });
16948 }
16949 }
16950 }
16951
16952 /* Implement TARGET_VECTORIZE_CREATE_COSTS. */
16953 vector_costs *
16954 aarch64_vectorize_create_costs (vec_info *vinfo, bool costing_for_scalar)
16955 {
16956 return new aarch64_vector_costs (vinfo, costing_for_scalar);
16957 }
16958
16959 /* Return the appropriate SIMD costs for vectors of type VECTYPE. */
16960 static const simd_vec_cost *
16961 aarch64_simd_vec_costs (tree vectype)
16962 {
16963 const cpu_vector_cost *costs = aarch64_tune_params.vec_costs;
16964 if (vectype != NULL
16965 && aarch64_sve_mode_p (TYPE_MODE (vectype))
16966 && costs->sve != NULL)
16967 return costs->sve;
16968 return costs->advsimd;
16969 }
16970
16971 /* Return the appropriate SIMD costs for vectors with VEC_* flags FLAGS. */
16972 static const simd_vec_cost *
16973 aarch64_simd_vec_costs_for_flags (unsigned int flags)
16974 {
16975 const cpu_vector_cost *costs = aarch64_tune_params.vec_costs;
16976 if ((flags & VEC_ANY_SVE) && costs->sve)
16977 return costs->sve;
16978 return costs->advsimd;
16979 }
16980
16981 /* If STMT_INFO is a memory reference, return the scalar memory type,
16982 otherwise return null. */
16983 static tree
16984 aarch64_dr_type (stmt_vec_info stmt_info)
16985 {
16986 if (auto dr = STMT_VINFO_DATA_REF (stmt_info))
16987 return TREE_TYPE (DR_REF (dr));
16988 return NULL_TREE;
16989 }
16990
16991 /* Decide whether to use the unrolling heuristic described above
16992 m_unrolled_advsimd_niters, updating that field if so. LOOP_VINFO
16993 describes the loop that we're vectorizing. */
16994 void
16995 aarch64_vector_costs::
16996 record_potential_advsimd_unrolling (loop_vec_info loop_vinfo)
16997 {
16998 /* The heuristic only makes sense on targets that have the same
16999 vector throughput for SVE and Advanced SIMD. */
17000 if (!(aarch64_tune_params.extra_tuning_flags
17001 & AARCH64_EXTRA_TUNE_MATCHED_VECTOR_THROUGHPUT))
17002 return;
17003
17004 /* We only want to apply the heuristic if LOOP_VINFO is being
17005 vectorized for SVE. */
17006 if (!(m_vec_flags & VEC_ANY_SVE))
17007 return;
17008
17009 /* Check whether it is possible in principle to use Advanced SIMD
17010 instead. */
17011 if (aarch64_autovec_preference == AARCH64_AUTOVEC_SVE_ONLY)
17012 return;
17013
17014 /* We don't want to apply the heuristic to outer loops, since it's
17015 harder to track two levels of unrolling. */
17016 if (LOOP_VINFO_LOOP (loop_vinfo)->inner)
17017 return;
17018
17019 /* Only handle cases in which the number of Advanced SIMD iterations
17020 would be known at compile time but the number of SVE iterations
17021 would not. */
17022 if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
17023 || aarch64_sve_vg.is_constant ())
17024 return;
17025
17026 /* Guess how many times the Advanced SIMD loop would iterate and make
17027 sure that it is within the complete unrolling limit. Even if the
17028 number of iterations is small enough, the number of statements might
17029 not be, which is why we need to estimate the number of statements too. */
17030 unsigned int estimated_vq = aarch64_estimated_sve_vq ();
17031 unsigned int advsimd_vf = CEIL (vect_vf_for_cost (loop_vinfo), estimated_vq);
17032 unsigned HOST_WIDE_INT unrolled_advsimd_niters
17033 = LOOP_VINFO_INT_NITERS (loop_vinfo) / advsimd_vf;
17034 if (unrolled_advsimd_niters > (unsigned int) param_max_completely_peel_times)
17035 return;
17036
17037 /* Record that we're applying the heuristic and should try to estimate
17038 the number of statements in the Advanced SIMD loop. */
17039 m_unrolled_advsimd_niters = unrolled_advsimd_niters;
17040 }
17041
17042 /* Do one-time initialization of the aarch64_vector_costs given that we're
17043 costing the loop vectorization described by LOOP_VINFO. */
17044 void
17045 aarch64_vector_costs::analyze_loop_vinfo (loop_vec_info loop_vinfo)
17046 {
17047 /* Record the number of times that the vector loop would execute,
17048 if known. */
17049 class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
17050 auto scalar_niters = max_stmt_executions_int (loop);
17051 if (scalar_niters >= 0)
17052 {
17053 unsigned int vf = vect_vf_for_cost (loop_vinfo);
17054 if (LOOP_VINFO_MASKS (loop_vinfo).is_empty ())
17055 m_num_vector_iterations = scalar_niters / vf;
17056 else
17057 m_num_vector_iterations = CEIL (scalar_niters, vf);
17058 }
17059
17060 /* Detect whether we're vectorizing for SVE and should apply the unrolling
17061 heuristic described above m_unrolled_advsimd_niters. */
17062 record_potential_advsimd_unrolling (loop_vinfo);
17063 }
17064
17065 /* Implement targetm.vectorize.builtin_vectorization_cost. */
17066 static int
17067 aarch64_builtin_vectorization_cost (enum vect_cost_for_stmt type_of_cost,
17068 tree vectype,
17069 int misalign ATTRIBUTE_UNUSED)
17070 {
17071 unsigned elements;
17072 const cpu_vector_cost *costs = aarch64_tune_params.vec_costs;
17073 bool fp = false;
17074
17075 if (vectype != NULL)
17076 fp = FLOAT_TYPE_P (vectype);
17077
17078 const simd_vec_cost *simd_costs = aarch64_simd_vec_costs (vectype);
17079
17080 switch (type_of_cost)
17081 {
17082 case scalar_stmt:
17083 return fp ? costs->scalar_fp_stmt_cost : costs->scalar_int_stmt_cost;
17084
17085 case scalar_load:
17086 return costs->scalar_load_cost;
17087
17088 case scalar_store:
17089 return costs->scalar_store_cost;
17090
17091 case vector_stmt:
17092 return fp ? simd_costs->fp_stmt_cost
17093 : simd_costs->int_stmt_cost;
17094
17095 case vector_load:
17096 return simd_costs->align_load_cost;
17097
17098 case vector_store:
17099 return simd_costs->store_cost;
17100
17101 case vec_to_scalar:
17102 return simd_costs->vec_to_scalar_cost;
17103
17104 case scalar_to_vec:
17105 return simd_costs->scalar_to_vec_cost;
17106
17107 case unaligned_load:
17108 case vector_gather_load:
17109 return simd_costs->unalign_load_cost;
17110
17111 case unaligned_store:
17112 case vector_scatter_store:
17113 return simd_costs->unalign_store_cost;
17114
17115 case cond_branch_taken:
17116 return costs->cond_taken_branch_cost;
17117
17118 case cond_branch_not_taken:
17119 return costs->cond_not_taken_branch_cost;
17120
17121 case vec_perm:
17122 return simd_costs->permute_cost;
17123
17124 case vec_promote_demote:
17125 return fp ? simd_costs->fp_stmt_cost
17126 : simd_costs->int_stmt_cost;
17127
17128 case vec_construct:
17129 elements = estimated_poly_value (TYPE_VECTOR_SUBPARTS (vectype));
17130 return elements / 2 + 1;
17131
17132 default:
17133 gcc_unreachable ();
17134 }
17135 }
17136
17137 /* Return true if an access of kind KIND for STMT_INFO (or NODE if SLP)
17138 represents one vector of an LD[234] or ST[234] operation. Return the total
17139 number of vectors (2, 3 or 4) if so, otherwise return a value outside that
17140 range. */
17141 static int
17142 aarch64_ld234_st234_vectors (vect_cost_for_stmt kind, stmt_vec_info stmt_info,
17143 slp_tree node)
17144 {
17145 if ((kind == vector_load
17146 || kind == unaligned_load
17147 || kind == vector_store
17148 || kind == unaligned_store)
17149 && STMT_VINFO_DATA_REF (stmt_info))
17150 {
17151 stmt_info = DR_GROUP_FIRST_ELEMENT (stmt_info);
17152 if (stmt_info
17153 && vect_mem_access_type (stmt_info, node) == VMAT_LOAD_STORE_LANES)
17154 return DR_GROUP_SIZE (stmt_info);
17155 }
17156 return 0;
17157 }
17158
17159 /* Return true if creating multiple copies of STMT_INFO for Advanced SIMD
17160 vectors would produce a series of LDP or STP operations. KIND is the
17161 kind of statement that STMT_INFO represents. */
17162 static bool
17163 aarch64_advsimd_ldp_stp_p (enum vect_cost_for_stmt kind,
17164 stmt_vec_info stmt_info)
17165 {
17166 switch (kind)
17167 {
17168 case vector_load:
17169 case vector_store:
17170 case unaligned_load:
17171 case unaligned_store:
17172 break;
17173
17174 default:
17175 return false;
17176 }
17177
17178 return is_gimple_assign (stmt_info->stmt);
17179 }
17180
17181 /* Return true if STMT_INFO is the second part of a two-statement multiply-add
17182 or multiply-subtract sequence that might be suitable for fusing into a
17183 single instruction. If VEC_FLAGS is zero, analyze the operation as
17184 a scalar one, otherwise analyze it as an operation on vectors with those
17185 VEC_* flags. */
17186 static bool
17187 aarch64_multiply_add_p (vec_info *vinfo, stmt_vec_info stmt_info,
17188 unsigned int vec_flags)
17189 {
17190 gassign *assign = dyn_cast<gassign *> (stmt_info->stmt);
17191 if (!assign)
17192 return false;
17193 tree_code code = gimple_assign_rhs_code (assign);
17194 if (code != PLUS_EXPR && code != MINUS_EXPR)
17195 return false;
17196
17197 auto is_mul_result = [&](int i)
17198 {
17199 tree rhs = gimple_op (assign, i);
17200 /* ??? Should we try to check for a single use as well? */
17201 if (TREE_CODE (rhs) != SSA_NAME)
17202 return false;
17203
17204 stmt_vec_info def_stmt_info = vinfo->lookup_def (rhs);
17205 if (!def_stmt_info
17206 || STMT_VINFO_DEF_TYPE (def_stmt_info) != vect_internal_def)
17207 return false;
17208 gassign *rhs_assign = dyn_cast<gassign *> (def_stmt_info->stmt);
17209 if (!rhs_assign || gimple_assign_rhs_code (rhs_assign) != MULT_EXPR)
17210 return false;
17211
17212 if (vec_flags & VEC_ADVSIMD)
17213 {
17214 /* Scalar and SVE code can tie the result to any FMLA input (or none,
17215 although that requires a MOVPRFX for SVE). However, Advanced SIMD
17216 only supports MLA forms, so will require a move if the result
17217 cannot be tied to the accumulator. The most important case in
17218 which this is true is when the accumulator input is invariant. */
17219 rhs = gimple_op (assign, 3 - i);
17220 if (TREE_CODE (rhs) != SSA_NAME)
17221 return false;
17222 def_stmt_info = vinfo->lookup_def (rhs);
17223 if (!def_stmt_info
17224 || STMT_VINFO_DEF_TYPE (def_stmt_info) == vect_external_def
17225 || STMT_VINFO_DEF_TYPE (def_stmt_info) == vect_constant_def)
17226 return false;
17227 }
17228
17229 return true;
17230 };
17231
17232 if (code == MINUS_EXPR && (vec_flags & VEC_ADVSIMD))
17233 /* Advanced SIMD doesn't have FNMADD/FNMSUB/FNMLA/FNMLS, so the
17234 multiplication must be on the second operand (to form an FMLS).
17235 But if both operands are multiplications and the second operand
17236 is used more than once, we'll instead negate the second operand
17237 and use it as an accumulator for the first operand. */
17238 return (is_mul_result (2)
17239 && (has_single_use (gimple_assign_rhs2 (assign))
17240 || !is_mul_result (1)));
17241
17242 return is_mul_result (1) || is_mul_result (2);
17243 }
17244
17245 /* Return true if STMT_INFO is the second part of a two-statement boolean AND
17246 expression sequence that might be suitable for fusing into a
17247 single instruction. If VEC_FLAGS is zero, analyze the operation as
17248 a scalar one, otherwise analyze it as an operation on vectors with those
17249 VEC_* flags. */
17250
17251 static bool
17252 aarch64_bool_compound_p (vec_info *vinfo, stmt_vec_info stmt_info,
17253 unsigned int vec_flags)
17254 {
17255 gassign *assign = dyn_cast<gassign *> (stmt_info->stmt);
17256 if (!assign
17257 || gimple_assign_rhs_code (assign) != BIT_AND_EXPR
17258 || !STMT_VINFO_VECTYPE (stmt_info)
17259 || !VECTOR_BOOLEAN_TYPE_P (STMT_VINFO_VECTYPE (stmt_info)))
17260 return false;
17261
17262 for (int i = 1; i < 3; ++i)
17263 {
17264 tree rhs = gimple_op (assign, i);
17265
17266 if (TREE_CODE (rhs) != SSA_NAME)
17267 continue;
17268
17269 stmt_vec_info def_stmt_info = vinfo->lookup_def (rhs);
17270 if (!def_stmt_info
17271 || STMT_VINFO_DEF_TYPE (def_stmt_info) != vect_internal_def)
17272 continue;
17273
17274 gassign *rhs_assign = dyn_cast<gassign *> (def_stmt_info->stmt);
17275 if (!rhs_assign
17276 || TREE_CODE_CLASS (gimple_assign_rhs_code (rhs_assign))
17277 != tcc_comparison)
17278 continue;
17279
17280 if (vec_flags & VEC_ADVSIMD)
17281 return false;
17282
17283 return true;
17284 }
17285 return false;
17286 }
17287
17288 /* We are considering implementing STMT_INFO using SVE. If STMT_INFO is an
17289 in-loop reduction that SVE supports directly, return its latency in cycles,
17290 otherwise return zero. SVE_COSTS specifies the latencies of the relevant
17291 instructions. */
17292 static unsigned int
17293 aarch64_sve_in_loop_reduction_latency (vec_info *vinfo,
17294 stmt_vec_info stmt_info,
17295 const sve_vec_cost *sve_costs)
17296 {
17297 switch (vect_reduc_type (vinfo, stmt_info))
17298 {
17299 case EXTRACT_LAST_REDUCTION:
17300 return sve_costs->clast_cost;
17301
17302 case FOLD_LEFT_REDUCTION:
17303 switch (TYPE_MODE (TREE_TYPE (gimple_get_lhs (stmt_info->stmt))))
17304 {
17305 case E_HFmode:
17306 case E_BFmode:
17307 return sve_costs->fadda_f16_cost;
17308
17309 case E_SFmode:
17310 return sve_costs->fadda_f32_cost;
17311
17312 case E_DFmode:
17313 return sve_costs->fadda_f64_cost;
17314
17315 default:
17316 break;
17317 }
17318 break;
17319 }
17320
17321 return 0;
17322 }
17323
17324 /* STMT_INFO describes a loop-carried operation in the original scalar code
17325 that we are considering implementing as a reduction. Return one of the
17326 following values, depending on VEC_FLAGS:
17327
17328 - If VEC_FLAGS is zero, return the loop carry latency of the original
17329 scalar operation.
17330
17331 - If VEC_FLAGS & VEC_ADVSIMD, return the loop carry latency of the
17332 Advanced SIMD implementation.
17333
17334 - If VEC_FLAGS & VEC_ANY_SVE, return the loop carry latency of the
17335 SVE implementation. */
17336 static unsigned int
17337 aarch64_in_loop_reduction_latency (vec_info *vinfo, stmt_vec_info stmt_info,
17338 unsigned int vec_flags)
17339 {
17340 const cpu_vector_cost *vec_costs = aarch64_tune_params.vec_costs;
17341 const sve_vec_cost *sve_costs = nullptr;
17342 if (vec_flags & VEC_ANY_SVE)
17343 sve_costs = aarch64_tune_params.vec_costs->sve;
17344
17345 /* If the caller is asking for the SVE latency, check for forms of reduction
17346 that only SVE can handle directly. */
17347 if (sve_costs)
17348 {
17349 unsigned int latency
17350 = aarch64_sve_in_loop_reduction_latency (vinfo, stmt_info, sve_costs);
17351 if (latency)
17352 return latency;
17353 }
17354
17355 /* Handle scalar costs. */
17356 bool is_float = FLOAT_TYPE_P (TREE_TYPE (gimple_get_lhs (stmt_info->stmt)));
17357 if (vec_flags == 0)
17358 {
17359 if (is_float)
17360 return vec_costs->scalar_fp_stmt_cost;
17361 return vec_costs->scalar_int_stmt_cost;
17362 }
17363
17364 /* Otherwise, the loop body just contains normal integer or FP operations,
17365 with a vector reduction outside the loop. */
17366 const simd_vec_cost *simd_costs
17367 = aarch64_simd_vec_costs_for_flags (vec_flags);
17368 if (is_float)
17369 return simd_costs->fp_stmt_cost;
17370 return simd_costs->int_stmt_cost;
17371 }
17372
17373 /* STMT_COST is the cost calculated by aarch64_builtin_vectorization_cost
17374 for STMT_INFO, which has cost kind KIND. If this is a scalar operation,
17375 try to subdivide the target-independent categorization provided by KIND
17376 to get a more accurate cost. */
17377 static fractional_cost
17378 aarch64_detect_scalar_stmt_subtype (vec_info *vinfo, vect_cost_for_stmt kind,
17379 stmt_vec_info stmt_info,
17380 fractional_cost stmt_cost)
17381 {
17382 /* Detect an extension of a loaded value. In general, we'll be able to fuse
17383 the extension with the load. */
17384 if (kind == scalar_stmt && vect_is_extending_load (vinfo, stmt_info))
17385 return 0;
17386
17387 return stmt_cost;
17388 }
17389
17390 /* STMT_COST is the cost calculated by aarch64_builtin_vectorization_cost
17391 for the vectorized form of STMT_INFO possibly using SLP node NODE, which has
17392 cost kind KIND and which when vectorized would operate on vector type
17393 VECTYPE. Try to subdivide the target-independent categorization provided by
17394 KIND to get a more accurate cost. WHERE specifies where the cost associated
17395 with KIND occurs. */
17396 static fractional_cost
17397 aarch64_detect_vector_stmt_subtype (vec_info *vinfo, vect_cost_for_stmt kind,
17398 stmt_vec_info stmt_info, slp_tree node,
17399 tree vectype,
17400 enum vect_cost_model_location where,
17401 fractional_cost stmt_cost)
17402 {
17403 const simd_vec_cost *simd_costs = aarch64_simd_vec_costs (vectype);
17404 const sve_vec_cost *sve_costs = nullptr;
17405 if (aarch64_sve_mode_p (TYPE_MODE (vectype)))
17406 sve_costs = aarch64_tune_params.vec_costs->sve;
17407
17408 /* It's generally better to avoid costing inductions, since the induction
17409 will usually be hidden by other operations. This is particularly true
17410 for things like COND_REDUCTIONS. */
17411 if (is_a<gphi *> (stmt_info->stmt))
17412 return 0;
17413
17414 /* Detect cases in which vec_to_scalar is describing the extraction of a
17415 vector element in preparation for a scalar store. The store itself is
17416 costed separately. */
17417 if (vect_is_store_elt_extraction (kind, stmt_info))
17418 return simd_costs->store_elt_extra_cost;
17419
17420 /* Detect SVE gather loads, which are costed as a single scalar_load
17421 for each element. We therefore need to divide the full-instruction
17422 cost by the number of elements in the vector. */
17423 if (kind == scalar_load
17424 && sve_costs
17425 && vect_mem_access_type (stmt_info, node) == VMAT_GATHER_SCATTER)
17426 {
17427 unsigned int nunits = vect_nunits_for_cost (vectype);
17428 /* Test for VNx2 modes, which have 64-bit containers. */
17429 if (known_eq (GET_MODE_NUNITS (TYPE_MODE (vectype)), aarch64_sve_vg))
17430 return { sve_costs->gather_load_x64_cost, nunits };
17431 return { sve_costs->gather_load_x32_cost, nunits };
17432 }
17433
17434 /* Detect cases in which a scalar_store is really storing one element
17435 in a scatter operation. */
17436 if (kind == scalar_store
17437 && sve_costs
17438 && vect_mem_access_type (stmt_info, node) == VMAT_GATHER_SCATTER)
17439 return sve_costs->scatter_store_elt_cost;
17440
17441 /* Detect cases in which vec_to_scalar represents an in-loop reduction. */
17442 if (kind == vec_to_scalar
17443 && where == vect_body
17444 && sve_costs)
17445 {
17446 unsigned int latency
17447 = aarch64_sve_in_loop_reduction_latency (vinfo, stmt_info, sve_costs);
17448 if (latency)
17449 return latency;
17450 }
17451
17452 /* Detect cases in which vec_to_scalar represents a single reduction
17453 instruction like FADDP or MAXV. */
17454 if (kind == vec_to_scalar
17455 && where == vect_epilogue
17456 && vect_is_reduction (stmt_info))
17457 switch (GET_MODE_INNER (TYPE_MODE (vectype)))
17458 {
17459 case E_QImode:
17460 return simd_costs->reduc_i8_cost;
17461
17462 case E_HImode:
17463 return simd_costs->reduc_i16_cost;
17464
17465 case E_SImode:
17466 return simd_costs->reduc_i32_cost;
17467
17468 case E_DImode:
17469 return simd_costs->reduc_i64_cost;
17470
17471 case E_HFmode:
17472 case E_BFmode:
17473 return simd_costs->reduc_f16_cost;
17474
17475 case E_SFmode:
17476 return simd_costs->reduc_f32_cost;
17477
17478 case E_DFmode:
17479 return simd_costs->reduc_f64_cost;
17480
17481 default:
17482 break;
17483 }
17484
17485 /* Otherwise stick with the original categorization. */
17486 return stmt_cost;
17487 }
17488
17489 /* STMT_COST is the cost calculated by aarch64_builtin_vectorization_cost
17490 for STMT_INFO, which has cost kind KIND and which when vectorized would
17491 operate on vector type VECTYPE. Adjust the cost as necessary for SVE
17492 targets. */
17493 static fractional_cost
17494 aarch64_sve_adjust_stmt_cost (class vec_info *vinfo, vect_cost_for_stmt kind,
17495 stmt_vec_info stmt_info, tree vectype,
17496 fractional_cost stmt_cost)
17497 {
17498 /* Unlike vec_promote_demote, vector_stmt conversions do not change the
17499 vector register size or number of units. Integer promotions of this
17500 type therefore map to SXT[BHW] or UXT[BHW].
17501
17502 Most loads have extending forms that can do the sign or zero extension
17503 on the fly. Optimistically assume that a load followed by an extension
17504 will fold to this form during combine, and that the extension therefore
17505 comes for free. */
17506 if (kind == vector_stmt && vect_is_extending_load (vinfo, stmt_info))
17507 stmt_cost = 0;
17508
17509 /* For similar reasons, vector_stmt integer truncations are a no-op,
17510 because we can just ignore the unused upper bits of the source. */
17511 if (kind == vector_stmt && vect_is_integer_truncation (stmt_info))
17512 stmt_cost = 0;
17513
17514 /* Advanced SIMD can load and store pairs of registers using LDP and STP,
17515 but there are no equivalent instructions for SVE. This means that
17516 (all other things being equal) 128-bit SVE needs twice as many load
17517 and store instructions as Advanced SIMD in order to process vector pairs.
17518
17519 Also, scalar code can often use LDP and STP to access pairs of values,
17520 so it is too simplistic to say that one SVE load or store replaces
17521 VF scalar loads and stores.
17522
17523 Ideally we would account for this in the scalar and Advanced SIMD
17524 costs by making suitable load/store pairs as cheap as a single
17525 load/store. However, that would be a very invasive change and in
17526 practice it tends to stress other parts of the cost model too much.
17527 E.g. stores of scalar constants currently count just a store,
17528 whereas stores of vector constants count a store and a vec_init.
17529 This is an artificial distinction for AArch64, where stores of
17530 nonzero scalar constants need the same kind of register invariant
17531 as vector stores.
17532
17533 An alternative would be to double the cost of any SVE loads and stores
17534 that could be paired in Advanced SIMD (and possibly also paired in
17535 scalar code). But this tends to stress other parts of the cost model
17536 in the same way. It also means that we can fall back to Advanced SIMD
17537 even if full-loop predication would have been useful.
17538
17539 Here we go for a more conservative version: double the costs of SVE
17540 loads and stores if one iteration of the scalar loop processes enough
17541 elements for it to use a whole number of Advanced SIMD LDP or STP
17542 instructions. This makes it very likely that the VF would be 1 for
17543 Advanced SIMD, and so no epilogue should be needed. */
17544 if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
17545 {
17546 stmt_vec_info first = DR_GROUP_FIRST_ELEMENT (stmt_info);
17547 unsigned int count = DR_GROUP_SIZE (first) - DR_GROUP_GAP (first);
17548 unsigned int elt_bits = GET_MODE_UNIT_BITSIZE (TYPE_MODE (vectype));
17549 if (multiple_p (count * elt_bits, 256)
17550 && aarch64_advsimd_ldp_stp_p (kind, stmt_info))
17551 stmt_cost *= 2;
17552 }
17553
17554 return stmt_cost;
17555 }
17556
17557 /* STMT_COST is the cost calculated for STMT_INFO, which has cost kind KIND
17558 and which when vectorized would operate on vector type VECTYPE. Add the
17559 cost of any embedded operations. */
17560 static fractional_cost
17561 aarch64_adjust_stmt_cost (vec_info *vinfo, vect_cost_for_stmt kind,
17562 stmt_vec_info stmt_info, slp_tree node, tree vectype,
17563 unsigned vec_flags, fractional_cost stmt_cost)
17564 {
17565 if (vectype)
17566 {
17567 const simd_vec_cost *simd_costs = aarch64_simd_vec_costs (vectype);
17568
17569 /* Detect cases in which a vector load or store represents an
17570 LD[234] or ST[234] instruction. */
17571 switch (aarch64_ld234_st234_vectors (kind, stmt_info, node))
17572 {
17573 case 2:
17574 stmt_cost += simd_costs->ld2_st2_permute_cost;
17575 break;
17576
17577 case 3:
17578 stmt_cost += simd_costs->ld3_st3_permute_cost;
17579 break;
17580
17581 case 4:
17582 stmt_cost += simd_costs->ld4_st4_permute_cost;
17583 break;
17584 }
17585
17586 gassign *assign = dyn_cast<gassign *> (STMT_VINFO_STMT (stmt_info));
17587 if ((kind == scalar_stmt || kind == vector_stmt) && assign)
17588 {
17589 /* For MLA we need to reduce the cost since MLA is 1 instruction. */
17590 if (!vect_is_reduction (stmt_info)
17591 && aarch64_multiply_add_p (vinfo, stmt_info, vec_flags))
17592 return 0;
17593
17594 /* For vector boolean ANDs with a compare operand we just need
17595 one insn. */
17596 if (aarch64_bool_compound_p (vinfo, stmt_info, vec_flags))
17597 return 0;
17598 }
17599
17600 if (kind == vector_stmt || kind == vec_to_scalar)
17601 if (tree cmp_type = vect_embedded_comparison_type (stmt_info))
17602 {
17603 if (FLOAT_TYPE_P (cmp_type))
17604 stmt_cost += simd_costs->fp_stmt_cost;
17605 else
17606 stmt_cost += simd_costs->int_stmt_cost;
17607 }
17608 }
17609
17610 if (kind == scalar_stmt)
17611 if (tree cmp_type = vect_embedded_comparison_type (stmt_info))
17612 {
17613 if (FLOAT_TYPE_P (cmp_type))
17614 stmt_cost += aarch64_tune_params.vec_costs->scalar_fp_stmt_cost;
17615 else
17616 stmt_cost += aarch64_tune_params.vec_costs->scalar_int_stmt_cost;
17617 }
17618
17619 return stmt_cost;
17620 }
17621
17622 /* Return true if STMT_INFO is part of a reduction that has the form:
17623
17624 r = r op ...;
17625 r = r op ...;
17626
17627 with the single accumulator being read and written multiple times. */
17628 static bool
17629 aarch64_force_single_cycle (vec_info *vinfo, stmt_vec_info stmt_info)
17630 {
17631 if (!STMT_VINFO_REDUC_DEF (stmt_info))
17632 return false;
17633
17634 auto reduc_info = info_for_reduction (vinfo, stmt_info);
17635 return STMT_VINFO_FORCE_SINGLE_CYCLE (reduc_info);
17636 }
17637
17638 /* COUNT, KIND and STMT_INFO are the same as for vector_costs::add_stmt_cost
17639 and they describe an operation in the body of a vector loop. Record issue
17640 information relating to the vector operation in OPS. */
17641 void
17642 aarch64_vector_costs::count_ops (unsigned int count, vect_cost_for_stmt kind,
17643 stmt_vec_info stmt_info, slp_tree node,
17644 aarch64_vec_op_count *ops)
17645 {
17646 const aarch64_base_vec_issue_info *base_issue = ops->base_issue_info ();
17647 if (!base_issue)
17648 return;
17649 const aarch64_simd_vec_issue_info *simd_issue = ops->simd_issue_info ();
17650 const aarch64_sve_vec_issue_info *sve_issue = ops->sve_issue_info ();
17651
17652 /* Calculate the minimum cycles per iteration imposed by a reduction
17653 operation. */
17654 if (stmt_info
17655 && (kind == scalar_stmt || kind == vector_stmt || kind == vec_to_scalar)
17656 && vect_is_reduction (stmt_info))
17657 {
17658 unsigned int base
17659 = aarch64_in_loop_reduction_latency (m_vinfo, stmt_info, m_vec_flags);
17660 if (aarch64_force_single_cycle (m_vinfo, stmt_info))
17661 /* ??? Ideally we'd use a tree to reduce the copies down to 1 vector,
17662 and then accumulate that, but at the moment the loop-carried
17663 dependency includes all copies. */
17664 ops->reduction_latency = MAX (ops->reduction_latency, base * count);
17665 else
17666 ops->reduction_latency = MAX (ops->reduction_latency, base);
17667 }
17668
17669 if (stmt_info && (kind == scalar_stmt || kind == vector_stmt))
17670 {
17671 /* Assume that multiply-adds will become a single operation. */
17672 if (aarch64_multiply_add_p (m_vinfo, stmt_info, m_vec_flags))
17673 return;
17674
17675 /* Assume that bool AND with compare operands will become a single
17676 operation. */
17677 if (aarch64_bool_compound_p (m_vinfo, stmt_info, m_vec_flags))
17678 return;
17679 }
17680
17681 /* Detect the case where we are using an emulated gather/scatter. When a
17682 target does not support gathers and scatters directly the vectorizer
17683 emulates these by constructing an index vector and then issuing an
17684 extraction for every lane in the vector. If the index vector is loaded
17685 from memory, the vector load and extractions are subsequently lowered by
17686 veclower into a series of scalar index loads. After the final loads are
17687 done it issues a vec_construct to recreate the vector from the scalar. For
17688 costing when we see a vec_to_scalar on a stmt with VMAT_GATHER_SCATTER we
17689 are dealing with an emulated instruction and should adjust costing
17690 properly. */
17691 if (stmt_info
17692 && kind == vec_to_scalar
17693 && (m_vec_flags & VEC_ADVSIMD)
17694 && vect_mem_access_type (stmt_info, node) == VMAT_GATHER_SCATTER)
17695 {
17696 auto dr = STMT_VINFO_DATA_REF (stmt_info);
17697 tree dr_ref = DR_REF (dr);
17698 while (handled_component_p (dr_ref))
17699 {
17700 if (TREE_CODE (dr_ref) == ARRAY_REF)
17701 {
17702 tree offset = TREE_OPERAND (dr_ref, 1);
17703 if (SSA_VAR_P (offset))
17704 {
17705 if (gimple_vuse (SSA_NAME_DEF_STMT (offset)))
17706 {
17707 if (STMT_VINFO_TYPE (stmt_info) == load_vec_info_type)
17708 ops->loads += count - 1;
17709 else
17710 /* Stores want to count both the index to array and data to
17711 array using vec_to_scalar. However we have index stores
17712 in Adv.SIMD and so we only want to adjust the index
17713 loads. */
17714 ops->loads += count / 2;
17715 return;
17716 }
17717 break;
17718 }
17719 }
17720 dr_ref = TREE_OPERAND (dr_ref, 0);
17721 }
17722 }
17723
17724 /* Count the basic operation cost associated with KIND. */
17725 switch (kind)
17726 {
17727 case cond_branch_taken:
17728 case cond_branch_not_taken:
17729 case vector_gather_load:
17730 case vector_scatter_store:
17731 /* We currently don't expect these to be used in a loop body. */
17732 break;
17733
17734 case vec_perm:
17735 case vec_promote_demote:
17736 case vec_construct:
17737 case vec_to_scalar:
17738 case scalar_to_vec:
17739 case vector_stmt:
17740 case scalar_stmt:
17741 ops->general_ops += count;
17742 break;
17743
17744 case scalar_load:
17745 case vector_load:
17746 case unaligned_load:
17747 ops->loads += count;
17748 if (m_vec_flags
17749 || (stmt_info && FLOAT_TYPE_P (aarch64_dr_type (stmt_info))))
17750 ops->general_ops += base_issue->fp_simd_load_general_ops * count;
17751 break;
17752
17753 case vector_store:
17754 case unaligned_store:
17755 case scalar_store:
17756 ops->stores += count;
17757 if (m_vec_flags
17758 || (stmt_info && FLOAT_TYPE_P (aarch64_dr_type (stmt_info))))
17759 ops->general_ops += base_issue->fp_simd_store_general_ops * count;
17760 break;
17761 }
17762
17763 /* Add any embedded comparison operations. */
17764 if (stmt_info
17765 && (kind == scalar_stmt || kind == vector_stmt || kind == vec_to_scalar)
17766 && vect_embedded_comparison_type (stmt_info))
17767 ops->general_ops += count;
17768
17769 /* COND_REDUCTIONS need two sets of VEC_COND_EXPRs, whereas so far we
17770 have only accounted for one. */
17771 if (stmt_info
17772 && (kind == vector_stmt || kind == vec_to_scalar)
17773 && vect_reduc_type (m_vinfo, stmt_info) == COND_REDUCTION)
17774 ops->general_ops += count;
17775
17776 /* Count the predicate operations needed by an SVE comparison. */
17777 if (stmt_info
17778 && sve_issue
17779 && (kind == vector_stmt || kind == vec_to_scalar))
17780 if (tree type = vect_comparison_type (stmt_info))
17781 {
17782 unsigned int base = (FLOAT_TYPE_P (type)
17783 ? sve_issue->fp_cmp_pred_ops
17784 : sve_issue->int_cmp_pred_ops);
17785 ops->pred_ops += base * count;
17786 }
17787
17788 /* Add any extra overhead associated with LD[234] and ST[234] operations. */
17789 if (stmt_info && simd_issue)
17790 switch (aarch64_ld234_st234_vectors (kind, stmt_info, node))
17791 {
17792 case 2:
17793 ops->general_ops += simd_issue->ld2_st2_general_ops * count;
17794 break;
17795
17796 case 3:
17797 ops->general_ops += simd_issue->ld3_st3_general_ops * count;
17798 break;
17799
17800 case 4:
17801 ops->general_ops += simd_issue->ld4_st4_general_ops * count;
17802 break;
17803 }
17804
17805 /* Add any overhead associated with gather loads and scatter stores. */
17806 if (stmt_info
17807 && sve_issue
17808 && (kind == scalar_load || kind == scalar_store)
17809 && vect_mem_access_type (stmt_info, node) == VMAT_GATHER_SCATTER)
17810 {
17811 unsigned int pairs = CEIL (count, 2);
17812 ops->pred_ops += sve_issue->gather_scatter_pair_pred_ops * pairs;
17813 ops->general_ops += sve_issue->gather_scatter_pair_general_ops * pairs;
17814 }
17815 }
17816
17817 /* Return true if STMT_INFO contains a memory access and if the constant
17818 component of the memory address is aligned to SIZE bytes. */
17819 static bool
17820 aarch64_aligned_constant_offset_p (stmt_vec_info stmt_info,
17821 poly_uint64 size)
17822 {
17823 if (!STMT_VINFO_DATA_REF (stmt_info))
17824 return false;
17825
17826 if (auto first_stmt = DR_GROUP_FIRST_ELEMENT (stmt_info))
17827 stmt_info = first_stmt;
17828 tree constant_offset = DR_INIT (STMT_VINFO_DATA_REF (stmt_info));
17829 /* Needed for gathers & scatters, for example. */
17830 if (!constant_offset)
17831 return false;
17832
17833 return multiple_p (wi::to_poly_offset (constant_offset), size);
17834 }
17835
17836 /* Check if a scalar or vector stmt could be part of a region of code
17837 that does nothing more than store values to memory, in the scalar
17838 case using STP. Return the cost of the stmt if so, counting 2 for
17839 one instruction. Return ~0U otherwise.
17840
17841 The arguments are a subset of those passed to add_stmt_cost. */
17842 unsigned int
17843 aarch64_stp_sequence_cost (unsigned int count, vect_cost_for_stmt kind,
17844 stmt_vec_info stmt_info, tree vectype)
17845 {
17846 /* Code that stores vector constants uses a vector_load to create
17847 the constant. We don't apply the heuristic to that case for two
17848 main reasons:
17849
17850 - At the moment, STPs are only formed via peephole2, and the
17851 constant scalar moves would often come between STRs and so
17852 prevent STP formation.
17853
17854 - The scalar code also has to load the constant somehow, and that
17855 isn't costed. */
17856 switch (kind)
17857 {
17858 case scalar_to_vec:
17859 /* Count 2 insns for a GPR->SIMD dup and 1 insn for a FPR->SIMD dup. */
17860 return (FLOAT_TYPE_P (vectype) ? 2 : 4) * count;
17861
17862 case vec_construct:
17863 if (FLOAT_TYPE_P (vectype))
17864 /* Count 1 insn for the maximum number of FP->SIMD INS
17865 instructions. */
17866 return (vect_nunits_for_cost (vectype) - 1) * 2 * count;
17867
17868 /* Count 2 insns for a GPR->SIMD move and 2 insns for the
17869 maximum number of GPR->SIMD INS instructions. */
17870 return vect_nunits_for_cost (vectype) * 4 * count;
17871
17872 case vector_store:
17873 case unaligned_store:
17874 /* Count 1 insn per vector if we can't form STP Q pairs. */
17875 if (aarch64_sve_mode_p (TYPE_MODE (vectype)))
17876 return count * 2;
17877
17878 if (stmt_info)
17879 {
17880 /* Assume we won't be able to use STP if the constant offset
17881 component of the address is misaligned. ??? This could be
17882 removed if we formed STP pairs earlier, rather than relying
17883 on peephole2. */
17884 auto size = GET_MODE_SIZE (TYPE_MODE (vectype));
17885 if (!aarch64_aligned_constant_offset_p (stmt_info, size))
17886 return count * 2;
17887 }
17888 return CEIL (count, 2) * 2;
17889
17890 case scalar_store:
17891 if (stmt_info && STMT_VINFO_DATA_REF (stmt_info))
17892 {
17893 /* Check for a mode in which STP pairs can be formed. */
17894 auto size = GET_MODE_SIZE (TYPE_MODE (aarch64_dr_type (stmt_info)));
17895 if (maybe_ne (size, 4) && maybe_ne (size, 8))
17896 return ~0U;
17897
17898 /* Assume we won't be able to use STP if the constant offset
17899 component of the address is misaligned. ??? This could be
17900 removed if we formed STP pairs earlier, rather than relying
17901 on peephole2. */
17902 if (!aarch64_aligned_constant_offset_p (stmt_info, size))
17903 return ~0U;
17904 }
17905 return count;
17906
17907 default:
17908 return ~0U;
17909 }
17910 }
17911
17912 unsigned
17913 aarch64_vector_costs::add_stmt_cost (int count, vect_cost_for_stmt kind,
17914 stmt_vec_info stmt_info, slp_tree node,
17915 tree vectype, int misalign,
17916 vect_cost_model_location where)
17917 {
17918 fractional_cost stmt_cost
17919 = aarch64_builtin_vectorization_cost (kind, vectype, misalign);
17920
17921 bool in_inner_loop_p = (where == vect_body
17922 && stmt_info
17923 && stmt_in_inner_loop_p (m_vinfo, stmt_info));
17924
17925 /* Do one-time initialization based on the vinfo. */
17926 loop_vec_info loop_vinfo = dyn_cast<loop_vec_info> (m_vinfo);
17927 if (!m_analyzed_vinfo)
17928 {
17929 if (loop_vinfo)
17930 analyze_loop_vinfo (loop_vinfo);
17931
17932 m_analyzed_vinfo = true;
17933 }
17934
17935 /* Apply the heuristic described above m_stp_sequence_cost. */
17936 if (m_stp_sequence_cost != ~0U)
17937 {
17938 uint64_t cost = aarch64_stp_sequence_cost (count, kind,
17939 stmt_info, vectype);
17940 m_stp_sequence_cost = MIN (m_stp_sequence_cost + cost, ~0U);
17941 }
17942
17943 /* Try to get a more accurate cost by looking at STMT_INFO instead
17944 of just looking at KIND. */
17945 if (stmt_info)
17946 {
17947 /* If we scalarize a strided store, the vectorizer costs one
17948 vec_to_scalar for each element. However, we can store the first
17949 element using an FP store without a separate extract step. */
17950 if (vect_is_store_elt_extraction (kind, stmt_info))
17951 count -= 1;
17952
17953 stmt_cost = aarch64_detect_scalar_stmt_subtype (m_vinfo, kind,
17954 stmt_info, stmt_cost);
17955
17956 if (vectype && m_vec_flags)
17957 stmt_cost = aarch64_detect_vector_stmt_subtype (m_vinfo, kind,
17958 stmt_info, node,
17959 vectype, where,
17960 stmt_cost);
17961
17962 /* Check if we've seen an SVE gather/scatter operation and which size. */
17963 if (kind == scalar_load
17964 && aarch64_sve_mode_p (TYPE_MODE (vectype))
17965 && vect_mem_access_type (stmt_info, node) == VMAT_GATHER_SCATTER)
17966 {
17967 const sve_vec_cost *sve_costs = aarch64_tune_params.vec_costs->sve;
17968 if (sve_costs)
17969 {
17970 /* Test for VNx2 modes, which have 64-bit containers. */
17971 if (known_eq (GET_MODE_NUNITS (TYPE_MODE (vectype)),
17972 aarch64_sve_vg))
17973 m_sve_gather_scatter_init_cost
17974 += sve_costs->gather_load_x64_init_cost;
17975 else
17976 m_sve_gather_scatter_init_cost
17977 += sve_costs->gather_load_x32_init_cost;
17978 }
17979 }
17980 }
17981
17982 /* Do any SVE-specific adjustments to the cost. */
17983 if (stmt_info && vectype && aarch64_sve_mode_p (TYPE_MODE (vectype)))
17984 stmt_cost = aarch64_sve_adjust_stmt_cost (m_vinfo, kind, stmt_info,
17985 vectype, stmt_cost);
17986
17987 /* Vector promotion and demotion requires us to widen the operation first
17988 and only after that perform the conversion. Unfortunately the mid-end
17989 expects this to be doable as a single operation and doesn't pass on
17990 enough context here for us to tell which operation is happening. To
17991 account for this we count every promote-demote operation twice and if
17992 the previously costed operation was also a promote-demote we reduce
17993 the cost of the currently being costed operation to simulate the final
17994 conversion cost. Note that for SVE we can do better here if the converted
17995 value comes from a load since the widening load would consume the widening
17996 operations. However since we're in stage 3 we can't change the helper
17997 vect_is_extending_load and duplicating the code seems not useful. */
17998 gassign *assign = NULL;
17999 if (kind == vec_promote_demote
18000 && (assign = dyn_cast <gassign *> (STMT_VINFO_STMT (stmt_info)))
18001 && gimple_assign_rhs_code (assign) == FLOAT_EXPR)
18002 {
18003 auto new_count = count * 2 - m_num_last_promote_demote;
18004 m_num_last_promote_demote = count;
18005 count = new_count;
18006 }
18007 else
18008 m_num_last_promote_demote = 0;
18009
18010 if (stmt_info)
18011 {
18012 /* Account for any extra "embedded" costs that apply additively
18013 to the base cost calculated above. */
18014 stmt_cost = aarch64_adjust_stmt_cost (m_vinfo, kind, stmt_info, node,
18015 vectype, m_vec_flags, stmt_cost);
18016
18017 /* If we're applying the SVE vs. Advanced SIMD unrolling heuristic,
18018 estimate the number of statements in the unrolled Advanced SIMD
18019 loop. For simplicitly, we assume that one iteration of the
18020 Advanced SIMD loop would need the same number of statements
18021 as one iteration of the SVE loop. */
18022 if (where == vect_body && m_unrolled_advsimd_niters)
18023 m_unrolled_advsimd_stmts += count * m_unrolled_advsimd_niters;
18024
18025 /* Detect the use of an averaging operation. */
18026 gimple *stmt = stmt_info->stmt;
18027 if (is_gimple_call (stmt)
18028 && gimple_call_internal_p (stmt))
18029 {
18030 switch (gimple_call_internal_fn (stmt))
18031 {
18032 case IFN_AVG_FLOOR:
18033 case IFN_AVG_CEIL:
18034 m_has_avg = true;
18035 default:
18036 break;
18037 }
18038 }
18039 }
18040
18041 /* If we're recording a nonzero vector loop body cost for the
18042 innermost loop, also estimate the operations that would need
18043 to be issued by all relevant implementations of the loop. */
18044 if (loop_vinfo
18045 && (m_costing_for_scalar || where == vect_body)
18046 && (!LOOP_VINFO_LOOP (loop_vinfo)->inner || in_inner_loop_p)
18047 && stmt_cost != 0)
18048 for (auto &ops : m_ops)
18049 count_ops (count, kind, stmt_info, node, &ops);
18050
18051 /* If the statement stores to a decl that is known to be the argument
18052 to a vld1 in the same function, ignore the store for costing purposes.
18053 See the comment above m_stores_to_vector_load_decl for more details. */
18054 if (stmt_info
18055 && (kind == vector_store || kind == unaligned_store)
18056 && aarch64_accesses_vector_load_decl_p (stmt_info))
18057 {
18058 stmt_cost = 0;
18059 m_stores_to_vector_load_decl = true;
18060 }
18061
18062 return record_stmt_cost (stmt_info, where, (count * stmt_cost).ceil ());
18063 }
18064
18065 /* Return true if (a) we're applying the Advanced SIMD vs. SVE unrolling
18066 heuristic described above m_unrolled_advsimd_niters and (b) the heuristic
18067 says that we should prefer the Advanced SIMD loop. */
18068 bool
18069 aarch64_vector_costs::prefer_unrolled_loop () const
18070 {
18071 if (!m_unrolled_advsimd_stmts)
18072 return false;
18073
18074 if (dump_enabled_p ())
18075 dump_printf_loc (MSG_NOTE, vect_location, "Number of insns in"
18076 " unrolled Advanced SIMD loop = "
18077 HOST_WIDE_INT_PRINT_UNSIGNED "\n",
18078 m_unrolled_advsimd_stmts);
18079
18080 /* The balance here is tricky. On the one hand, we can't be sure whether
18081 the code is vectorizable with Advanced SIMD or not. However, even if
18082 it isn't vectorizable with Advanced SIMD, there's a possibility that
18083 the scalar code could also be unrolled. Some of the code might then
18084 benefit from SLP, or from using LDP and STP. We therefore apply
18085 the heuristic regardless of can_use_advsimd_p. */
18086 return (m_unrolled_advsimd_stmts
18087 && (m_unrolled_advsimd_stmts
18088 <= (unsigned int) param_max_completely_peeled_insns));
18089 }
18090
18091 /* Subroutine of adjust_body_cost for handling SVE. Use ISSUE_INFO to work out
18092 how fast the SVE code can be issued and compare it to the equivalent value
18093 for scalar code (SCALAR_CYCLES_PER_ITER). If COULD_USE_ADVSIMD is true,
18094 also compare it to the issue rate of Advanced SIMD code
18095 (ADVSIMD_CYCLES_PER_ITER).
18096
18097 ORIG_BODY_COST is the cost originally passed to adjust_body_cost and
18098 *BODY_COST is the current value of the adjusted cost. *SHOULD_DISPARAGE
18099 is true if we think the loop body is too expensive. */
18100
18101 fractional_cost
18102 aarch64_vector_costs::
18103 adjust_body_cost_sve (const aarch64_vec_op_count *ops,
18104 fractional_cost scalar_cycles_per_iter,
18105 unsigned int orig_body_cost, unsigned int *body_cost,
18106 bool *should_disparage)
18107 {
18108 if (dump_enabled_p ())
18109 ops->dump ();
18110
18111 fractional_cost sve_pred_cycles_per_iter = ops->min_pred_cycles_per_iter ();
18112 fractional_cost sve_cycles_per_iter = ops->min_cycles_per_iter ();
18113
18114 /* If the scalar version of the loop could issue at least as
18115 quickly as the predicate parts of the SVE loop, make the SVE loop
18116 prohibitively expensive. In this case vectorization is adding an
18117 overhead that the original scalar code didn't have.
18118
18119 This is mostly intended to detect cases in which WHILELOs dominate
18120 for very tight loops, which is something that normal latency-based
18121 costs would not model. Adding this kind of cliffedge would be
18122 too drastic for scalar_cycles_per_iter vs. sve_cycles_per_iter;
18123 code in the caller handles that case in a more conservative way. */
18124 fractional_cost sve_estimate = sve_pred_cycles_per_iter + 1;
18125 if (scalar_cycles_per_iter < sve_estimate)
18126 {
18127 unsigned int min_cost
18128 = orig_body_cost * estimated_poly_value (BYTES_PER_SVE_VECTOR);
18129 if (*body_cost < min_cost)
18130 {
18131 if (dump_enabled_p ())
18132 dump_printf_loc (MSG_NOTE, vect_location,
18133 "Increasing body cost to %d because the"
18134 " scalar code could issue within the limit"
18135 " imposed by predicate operations\n",
18136 min_cost);
18137 *body_cost = min_cost;
18138 *should_disparage = true;
18139 }
18140 }
18141
18142 return sve_cycles_per_iter;
18143 }
18144
18145 unsigned int
18146 aarch64_vector_costs::determine_suggested_unroll_factor ()
18147 {
18148 bool sve = m_vec_flags & VEC_ANY_SVE;
18149 /* If we are trying to unroll an Advanced SIMD main loop that contains
18150 an averaging operation that we do not support with SVE and we might use a
18151 predicated epilogue, we need to be conservative and block unrolling as
18152 this might lead to a less optimal loop for the first and only epilogue
18153 using the original loop's vectorization factor.
18154 TODO: Remove this constraint when we add support for multiple epilogue
18155 vectorization. */
18156 if (!sve && !TARGET_SVE2 && m_has_avg)
18157 return 1;
18158
18159 unsigned int max_unroll_factor = 1;
18160 for (auto vec_ops : m_ops)
18161 {
18162 aarch64_simd_vec_issue_info const *vec_issue
18163 = vec_ops.simd_issue_info ();
18164 if (!vec_issue)
18165 return 1;
18166 /* Limit unroll factor to a value adjustable by the user, the default
18167 value is 4. */
18168 unsigned int unroll_factor = aarch64_vect_unroll_limit;
18169 unsigned int factor
18170 = vec_ops.reduction_latency > 1 ? vec_ops.reduction_latency : 1;
18171 unsigned int temp;
18172
18173 /* Sanity check, this should never happen. */
18174 if ((vec_ops.stores + vec_ops.loads + vec_ops.general_ops) == 0)
18175 return 1;
18176
18177 /* Check stores. */
18178 if (vec_ops.stores > 0)
18179 {
18180 temp = CEIL (factor * vec_issue->stores_per_cycle,
18181 vec_ops.stores);
18182 unroll_factor = MIN (unroll_factor, temp);
18183 }
18184
18185 /* Check loads + stores. */
18186 if (vec_ops.loads > 0)
18187 {
18188 temp = CEIL (factor * vec_issue->loads_stores_per_cycle,
18189 vec_ops.loads + vec_ops.stores);
18190 unroll_factor = MIN (unroll_factor, temp);
18191 }
18192
18193 /* Check general ops. */
18194 if (vec_ops.general_ops > 0)
18195 {
18196 temp = CEIL (factor * vec_issue->general_ops_per_cycle,
18197 vec_ops.general_ops);
18198 unroll_factor = MIN (unroll_factor, temp);
18199 }
18200 max_unroll_factor = MAX (max_unroll_factor, unroll_factor);
18201 }
18202
18203 /* Make sure unroll factor is power of 2. */
18204 return 1 << ceil_log2 (max_unroll_factor);
18205 }
18206
18207 /* BODY_COST is the cost of a vector loop body. Adjust the cost as necessary
18208 and return the new cost. */
18209 unsigned int
18210 aarch64_vector_costs::
18211 adjust_body_cost (loop_vec_info loop_vinfo,
18212 const aarch64_vector_costs *scalar_costs,
18213 unsigned int body_cost)
18214 {
18215 if (scalar_costs->m_ops.is_empty () || m_ops.is_empty ())
18216 return body_cost;
18217
18218 const auto &scalar_ops = scalar_costs->m_ops[0];
18219 const auto &vector_ops = m_ops[0];
18220 unsigned int estimated_vf = vect_vf_for_cost (loop_vinfo);
18221 unsigned int orig_body_cost = body_cost;
18222 bool should_disparage = false;
18223
18224 if (dump_enabled_p ())
18225 dump_printf_loc (MSG_NOTE, vect_location,
18226 "Original vector body cost = %d\n", body_cost);
18227
18228 /* If we know we have a single partial vector iteration, cap the VF
18229 to the number of scalar iterations for costing purposes. */
18230 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
18231 {
18232 auto niters = LOOP_VINFO_INT_NITERS (loop_vinfo);
18233 if (niters < estimated_vf && dump_enabled_p ())
18234 dump_printf_loc (MSG_NOTE, vect_location,
18235 "Scalar loop iterates at most %wd times. Capping VF "
18236 " from %d to %wd\n", niters, estimated_vf, niters);
18237
18238 estimated_vf = MIN (estimated_vf, niters);
18239 }
18240
18241 fractional_cost scalar_cycles_per_iter
18242 = scalar_ops.min_cycles_per_iter () * estimated_vf;
18243
18244 fractional_cost vector_cycles_per_iter = vector_ops.min_cycles_per_iter ();
18245
18246 if (dump_enabled_p ())
18247 {
18248 if (IN_RANGE (m_num_vector_iterations, 0, 65536))
18249 dump_printf_loc (MSG_NOTE, vect_location,
18250 "Vector loop iterates at most %wd times\n",
18251 m_num_vector_iterations);
18252 dump_printf_loc (MSG_NOTE, vect_location, "Scalar issue estimate:\n");
18253 scalar_ops.dump ();
18254 dump_printf_loc (MSG_NOTE, vect_location,
18255 " estimated cycles per vector iteration"
18256 " (for VF %d) = %f\n",
18257 estimated_vf, scalar_cycles_per_iter.as_double ());
18258 }
18259
18260 if (vector_ops.sve_issue_info ())
18261 {
18262 if (dump_enabled_p ())
18263 dump_printf_loc (MSG_NOTE, vect_location, "SVE issue estimate:\n");
18264 vector_cycles_per_iter
18265 = adjust_body_cost_sve (&vector_ops, scalar_cycles_per_iter,
18266 orig_body_cost, &body_cost, &should_disparage);
18267
18268 if (aarch64_tune_params.vec_costs == &neoverse512tvb_vector_cost)
18269 {
18270 /* Also take Neoverse V1 tuning into account, doubling the
18271 scalar and Advanced SIMD estimates to account for the
18272 doubling in SVE vector length. */
18273 if (dump_enabled_p ())
18274 dump_printf_loc (MSG_NOTE, vect_location,
18275 "Neoverse V1 estimate:\n");
18276 auto vf_factor = m_ops[1].vf_factor ();
18277 adjust_body_cost_sve (&m_ops[1], scalar_cycles_per_iter * vf_factor,
18278 orig_body_cost, &body_cost, &should_disparage);
18279 }
18280 }
18281 else
18282 {
18283 if (dump_enabled_p ())
18284 {
18285 dump_printf_loc (MSG_NOTE, vect_location,
18286 "Vector issue estimate:\n");
18287 vector_ops.dump ();
18288 }
18289 }
18290
18291 /* Decide whether to stick to latency-based costs or whether to try to
18292 take issue rates into account. */
18293 unsigned int threshold = aarch64_loop_vect_issue_rate_niters;
18294 if (m_vec_flags & VEC_ANY_SVE)
18295 threshold = CEIL (threshold, aarch64_estimated_sve_vq ());
18296
18297 if (m_num_vector_iterations >= 1
18298 && m_num_vector_iterations < threshold)
18299 {
18300 if (dump_enabled_p ())
18301 dump_printf_loc (MSG_NOTE, vect_location,
18302 "Low iteration count, so using pure latency"
18303 " costs\n");
18304 }
18305 /* Increase the cost of the vector code if it looks like the scalar code
18306 could issue more quickly. These values are only rough estimates,
18307 so minor differences should only result in minor changes. */
18308 else if (scalar_cycles_per_iter < vector_cycles_per_iter)
18309 {
18310 body_cost = fractional_cost::scale (body_cost, vector_cycles_per_iter,
18311 scalar_cycles_per_iter);
18312 if (dump_enabled_p ())
18313 dump_printf_loc (MSG_NOTE, vect_location,
18314 "Increasing body cost to %d because scalar code"
18315 " would issue more quickly\n", body_cost);
18316 }
18317 /* In general, it's expected that the proposed vector code would be able
18318 to issue more quickly than the original scalar code. This should
18319 already be reflected to some extent in the latency-based costs.
18320
18321 However, the latency-based costs effectively assume that the scalar
18322 code and the vector code execute serially, which tends to underplay
18323 one important case: if the real (non-serialized) execution time of
18324 a scalar iteration is dominated by loop-carried dependencies,
18325 and if the vector code is able to reduce both the length of
18326 the loop-carried dependencies *and* the number of cycles needed
18327 to issue the code in general, we can be more confident that the
18328 vector code is an improvement, even if adding the other (non-loop-carried)
18329 latencies tends to hide this saving. We therefore reduce the cost of the
18330 vector loop body in proportion to the saving. */
18331 else if (scalar_ops.reduction_latency > vector_ops.reduction_latency
18332 && scalar_ops.reduction_latency == scalar_cycles_per_iter
18333 && scalar_cycles_per_iter > vector_cycles_per_iter
18334 && !should_disparage)
18335 {
18336 body_cost = fractional_cost::scale (body_cost, vector_cycles_per_iter,
18337 scalar_cycles_per_iter);
18338 if (dump_enabled_p ())
18339 dump_printf_loc (MSG_NOTE, vect_location,
18340 "Decreasing body cost to %d account for smaller"
18341 " reduction latency\n", body_cost);
18342 }
18343
18344 return body_cost;
18345 }
18346
18347 void
18348 aarch64_vector_costs::finish_cost (const vector_costs *uncast_scalar_costs)
18349 {
18350 /* Record the issue information for any SVE WHILE instructions that the
18351 loop needs. */
18352 loop_vec_info loop_vinfo = dyn_cast<loop_vec_info> (m_vinfo);
18353 if (!m_ops.is_empty ()
18354 && loop_vinfo
18355 && LOOP_VINFO_FULLY_MASKED_P (loop_vinfo))
18356 {
18357 unsigned int num_masks = 0;
18358 rgroup_controls *rgm;
18359 unsigned int num_vectors_m1;
18360 FOR_EACH_VEC_ELT (LOOP_VINFO_MASKS (loop_vinfo).rgc_vec,
18361 num_vectors_m1, rgm)
18362 if (rgm->type)
18363 num_masks += num_vectors_m1 + 1;
18364 for (auto &ops : m_ops)
18365 if (auto *issue = ops.sve_issue_info ())
18366 ops.pred_ops += num_masks * issue->while_pred_ops;
18367 }
18368
18369 auto *scalar_costs
18370 = static_cast<const aarch64_vector_costs *> (uncast_scalar_costs);
18371 if (loop_vinfo && m_vec_flags)
18372 {
18373 m_costs[vect_body] = adjust_body_cost (loop_vinfo, scalar_costs,
18374 m_costs[vect_body]);
18375 m_suggested_unroll_factor = determine_suggested_unroll_factor ();
18376
18377 /* For gather and scatters there's an additional overhead for the first
18378 iteration. For low count loops they're not beneficial so model the
18379 overhead as loop prologue costs. */
18380 m_costs[vect_prologue] += m_sve_gather_scatter_init_cost;
18381 }
18382
18383 /* Apply the heuristic described above m_stp_sequence_cost. Prefer
18384 the scalar code in the event of a tie, since there is more chance
18385 of scalar code being optimized with surrounding operations.
18386
18387 In addition, if the vector body is a simple store to a decl that
18388 is elsewhere loaded using vld1, strongly prefer the vector form,
18389 to the extent of giving the prologue a zero cost. See the comment
18390 above m_stores_to_vector_load_decl for details. */
18391 if (!loop_vinfo
18392 && scalar_costs
18393 && m_stp_sequence_cost != ~0U)
18394 {
18395 if (m_stores_to_vector_load_decl)
18396 m_costs[vect_prologue] = 0;
18397 else if (m_stp_sequence_cost >= scalar_costs->m_stp_sequence_cost)
18398 m_costs[vect_body] = 2 * scalar_costs->total_cost ();
18399 }
18400
18401 vector_costs::finish_cost (scalar_costs);
18402 }
18403
18404 bool
18405 aarch64_vector_costs::
18406 better_main_loop_than_p (const vector_costs *uncast_other) const
18407 {
18408 auto other = static_cast<const aarch64_vector_costs *> (uncast_other);
18409
18410 auto this_loop_vinfo = as_a<loop_vec_info> (this->m_vinfo);
18411 auto other_loop_vinfo = as_a<loop_vec_info> (other->m_vinfo);
18412
18413 if (dump_enabled_p ())
18414 dump_printf_loc (MSG_NOTE, vect_location,
18415 "Comparing two main loops (%s at VF %d vs %s at VF %d)\n",
18416 GET_MODE_NAME (this_loop_vinfo->vector_mode),
18417 vect_vf_for_cost (this_loop_vinfo),
18418 GET_MODE_NAME (other_loop_vinfo->vector_mode),
18419 vect_vf_for_cost (other_loop_vinfo));
18420
18421 /* Apply the unrolling heuristic described above
18422 m_unrolled_advsimd_niters. */
18423 if (bool (m_unrolled_advsimd_stmts)
18424 != bool (other->m_unrolled_advsimd_stmts))
18425 {
18426 bool this_prefer_unrolled = this->prefer_unrolled_loop ();
18427 bool other_prefer_unrolled = other->prefer_unrolled_loop ();
18428 if (this_prefer_unrolled != other_prefer_unrolled)
18429 {
18430 if (dump_enabled_p ())
18431 dump_printf_loc (MSG_NOTE, vect_location,
18432 "Preferring Advanced SIMD loop because"
18433 " it can be unrolled\n");
18434 return other_prefer_unrolled;
18435 }
18436 }
18437
18438 for (unsigned int i = 0; i < m_ops.length (); ++i)
18439 {
18440 if (dump_enabled_p ())
18441 {
18442 if (i)
18443 dump_printf_loc (MSG_NOTE, vect_location,
18444 "Reconsidering with subtuning %d\n", i);
18445 dump_printf_loc (MSG_NOTE, vect_location,
18446 "Issue info for %s loop:\n",
18447 GET_MODE_NAME (this_loop_vinfo->vector_mode));
18448 this->m_ops[i].dump ();
18449 dump_printf_loc (MSG_NOTE, vect_location,
18450 "Issue info for %s loop:\n",
18451 GET_MODE_NAME (other_loop_vinfo->vector_mode));
18452 other->m_ops[i].dump ();
18453 }
18454
18455 auto this_estimated_vf = (vect_vf_for_cost (this_loop_vinfo)
18456 * this->m_ops[i].vf_factor ());
18457 auto other_estimated_vf = (vect_vf_for_cost (other_loop_vinfo)
18458 * other->m_ops[i].vf_factor ());
18459
18460 /* If it appears that one loop could process the same amount of data
18461 in fewer cycles, prefer that loop over the other one. */
18462 fractional_cost this_cost
18463 = this->m_ops[i].min_cycles_per_iter () * other_estimated_vf;
18464 fractional_cost other_cost
18465 = other->m_ops[i].min_cycles_per_iter () * this_estimated_vf;
18466 if (dump_enabled_p ())
18467 {
18468 dump_printf_loc (MSG_NOTE, vect_location,
18469 "Weighted cycles per iteration of %s loop ~= %f\n",
18470 GET_MODE_NAME (this_loop_vinfo->vector_mode),
18471 this_cost.as_double ());
18472 dump_printf_loc (MSG_NOTE, vect_location,
18473 "Weighted cycles per iteration of %s loop ~= %f\n",
18474 GET_MODE_NAME (other_loop_vinfo->vector_mode),
18475 other_cost.as_double ());
18476 }
18477 if (this_cost != other_cost)
18478 {
18479 if (dump_enabled_p ())
18480 dump_printf_loc (MSG_NOTE, vect_location,
18481 "Preferring loop with lower cycles"
18482 " per iteration\n");
18483 return this_cost < other_cost;
18484 }
18485
18486 /* If the issue rate of SVE code is limited by predicate operations
18487 (i.e. if sve_pred_cycles_per_iter > sve_nonpred_cycles_per_iter),
18488 and if Advanced SIMD code could issue within the limit imposed
18489 by the predicate operations, the predicate operations are adding an
18490 overhead that the original code didn't have and so we should prefer
18491 the Advanced SIMD version. */
18492 auto better_pred_limit_p = [](const aarch64_vec_op_count &a,
18493 const aarch64_vec_op_count &b) -> bool
18494 {
18495 if (a.pred_ops == 0
18496 && (b.min_pred_cycles_per_iter ()
18497 > b.min_nonpred_cycles_per_iter ()))
18498 {
18499 if (dump_enabled_p ())
18500 dump_printf_loc (MSG_NOTE, vect_location,
18501 "Preferring Advanced SIMD loop since"
18502 " SVE loop is predicate-limited\n");
18503 return true;
18504 }
18505 return false;
18506 };
18507 if (better_pred_limit_p (this->m_ops[i], other->m_ops[i]))
18508 return true;
18509 if (better_pred_limit_p (other->m_ops[i], this->m_ops[i]))
18510 return false;
18511 }
18512
18513 return vector_costs::better_main_loop_than_p (other);
18514 }
18515
18516 static void initialize_aarch64_code_model (struct gcc_options *);
18517
18518 /* Parse TOKEN, which has length LENGTH to see if it is an option
18519 described in FLAG. If it is, return the index bit for that fusion type.
18520 If not, error (printing OPTION_NAME) and return zero. */
18521
18522 static unsigned int
18523 aarch64_parse_one_option_token (const char *token,
18524 size_t length,
18525 const struct aarch64_flag_desc *flag,
18526 const char *option_name)
18527 {
18528 for (; flag->name != NULL; flag++)
18529 {
18530 if (length == strlen (flag->name)
18531 && !strncmp (flag->name, token, length))
18532 return flag->flag;
18533 }
18534
18535 error ("unknown flag passed in %<-moverride=%s%> (%s)", option_name, token);
18536 return 0;
18537 }
18538
18539 /* Parse OPTION which is a comma-separated list of flags to enable.
18540 FLAGS gives the list of flags we understand, INITIAL_STATE gives any
18541 default state we inherit from the CPU tuning structures. OPTION_NAME
18542 gives the top-level option we are parsing in the -moverride string,
18543 for use in error messages. */
18544
18545 static unsigned int
18546 aarch64_parse_boolean_options (const char *option,
18547 const struct aarch64_flag_desc *flags,
18548 unsigned int initial_state,
18549 const char *option_name)
18550 {
18551 const char separator = '.';
18552 const char* specs = option;
18553 const char* ntoken = option;
18554 unsigned int found_flags = initial_state;
18555
18556 while ((ntoken = strchr (specs, separator)))
18557 {
18558 size_t token_length = ntoken - specs;
18559 unsigned token_ops = aarch64_parse_one_option_token (specs,
18560 token_length,
18561 flags,
18562 option_name);
18563 /* If we find "none" (or, for simplicity's sake, an error) anywhere
18564 in the token stream, reset the supported operations. So:
18565
18566 adrp+add.cmp+branch.none.adrp+add
18567
18568 would have the result of turning on only adrp+add fusion. */
18569 if (!token_ops)
18570 found_flags = 0;
18571
18572 found_flags |= token_ops;
18573 specs = ++ntoken;
18574 }
18575
18576 /* We ended with a comma, print something. */
18577 if (!(*specs))
18578 {
18579 error ("%qs string ill-formed", option_name);
18580 return 0;
18581 }
18582
18583 /* We still have one more token to parse. */
18584 size_t token_length = strlen (specs);
18585 unsigned token_ops = aarch64_parse_one_option_token (specs,
18586 token_length,
18587 flags,
18588 option_name);
18589 if (!token_ops)
18590 found_flags = 0;
18591
18592 found_flags |= token_ops;
18593 return found_flags;
18594 }
18595
18596 /* Support for overriding instruction fusion. */
18597
18598 static void
18599 aarch64_parse_fuse_string (const char *fuse_string,
18600 struct tune_params *tune)
18601 {
18602 tune->fusible_ops = aarch64_parse_boolean_options (fuse_string,
18603 aarch64_fusible_pairs,
18604 tune->fusible_ops,
18605 "fuse=");
18606 }
18607
18608 /* Support for overriding other tuning flags. */
18609
18610 static void
18611 aarch64_parse_tune_string (const char *tune_string,
18612 struct tune_params *tune)
18613 {
18614 tune->extra_tuning_flags
18615 = aarch64_parse_boolean_options (tune_string,
18616 aarch64_tuning_flags,
18617 tune->extra_tuning_flags,
18618 "tune=");
18619 }
18620
18621 /* Parse the sve_width tuning moverride string in TUNE_STRING.
18622 Accept the valid SVE vector widths allowed by
18623 aarch64_sve_vector_bits_enum and use it to override sve_width
18624 in TUNE. */
18625
18626 static void
18627 aarch64_parse_sve_width_string (const char *tune_string,
18628 struct tune_params *tune)
18629 {
18630 int width = -1;
18631
18632 int n = sscanf (tune_string, "%d", &width);
18633 if (n == EOF)
18634 {
18635 error ("invalid format for %<sve_width%>");
18636 return;
18637 }
18638 switch (width)
18639 {
18640 case SVE_128:
18641 case SVE_256:
18642 case SVE_512:
18643 case SVE_1024:
18644 case SVE_2048:
18645 break;
18646 default:
18647 error ("invalid %<sve_width%> value: %d", width);
18648 }
18649 tune->sve_width = (enum aarch64_sve_vector_bits_enum) width;
18650 }
18651
18652 /* Parse TOKEN, which has length LENGTH to see if it is a tuning option
18653 we understand. If it is, extract the option string and handoff to
18654 the appropriate function. */
18655
18656 void
18657 aarch64_parse_one_override_token (const char* token,
18658 size_t length,
18659 struct tune_params *tune)
18660 {
18661 const struct aarch64_tuning_override_function *fn
18662 = aarch64_tuning_override_functions;
18663
18664 const char *option_part = strchr (token, '=');
18665 if (!option_part)
18666 {
18667 error ("tuning string missing in option (%s)", token);
18668 return;
18669 }
18670
18671 /* Get the length of the option name. */
18672 length = option_part - token;
18673 /* Skip the '=' to get to the option string. */
18674 option_part++;
18675
18676 for (; fn->name != NULL; fn++)
18677 {
18678 if (!strncmp (fn->name, token, length))
18679 {
18680 fn->parse_override (option_part, tune);
18681 return;
18682 }
18683 }
18684
18685 error ("unknown tuning option (%s)",token);
18686 return;
18687 }
18688
18689 /* A checking mechanism for the implementation of the tls size. */
18690
18691 static void
18692 initialize_aarch64_tls_size (struct gcc_options *opts)
18693 {
18694 if (aarch64_tls_size == 0)
18695 aarch64_tls_size = 24;
18696
18697 switch (opts->x_aarch64_cmodel_var)
18698 {
18699 case AARCH64_CMODEL_TINY:
18700 /* Both the default and maximum TLS size allowed under tiny is 1M which
18701 needs two instructions to address, so we clamp the size to 24. */
18702 if (aarch64_tls_size > 24)
18703 aarch64_tls_size = 24;
18704 break;
18705 case AARCH64_CMODEL_SMALL:
18706 /* The maximum TLS size allowed under small is 4G. */
18707 if (aarch64_tls_size > 32)
18708 aarch64_tls_size = 32;
18709 break;
18710 case AARCH64_CMODEL_LARGE:
18711 /* The maximum TLS size allowed under large is 16E.
18712 FIXME: 16E should be 64bit, we only support 48bit offset now. */
18713 if (aarch64_tls_size > 48)
18714 aarch64_tls_size = 48;
18715 break;
18716 default:
18717 gcc_unreachable ();
18718 }
18719
18720 return;
18721 }
18722
18723 /* Return the CPU corresponding to the enum CPU. */
18724
18725 static const struct processor *
18726 aarch64_get_tune_cpu (enum aarch64_cpu cpu)
18727 {
18728 gcc_assert (cpu != aarch64_no_cpu);
18729
18730 return &all_cores[cpu];
18731 }
18732
18733 /* Return the architecture corresponding to the enum ARCH. */
18734
18735 static const struct processor *
18736 aarch64_get_arch (enum aarch64_arch arch)
18737 {
18738 gcc_assert (arch != aarch64_no_arch);
18739
18740 return &all_architectures[arch];
18741 }
18742
18743 /* Parse STRING looking for options in the format:
18744 string :: option:string
18745 option :: name=substring
18746 name :: {a-z}
18747 substring :: defined by option. */
18748
18749 static void
18750 aarch64_parse_override_string (const char* input_string,
18751 struct tune_params* tune)
18752 {
18753 const char separator = ':';
18754 size_t string_length = strlen (input_string) + 1;
18755 char *string_root = (char *) xmalloc (sizeof (*string_root) * string_length);
18756 char *string = string_root;
18757 strncpy (string, input_string, string_length);
18758 string[string_length - 1] = '\0';
18759
18760 char* ntoken = string;
18761
18762 while ((ntoken = strchr (string, separator)))
18763 {
18764 size_t token_length = ntoken - string;
18765 /* Make this substring look like a string. */
18766 *ntoken = '\0';
18767 aarch64_parse_one_override_token (string, token_length, tune);
18768 string = ++ntoken;
18769 }
18770
18771 /* One last option to parse. */
18772 aarch64_parse_one_override_token (string, strlen (string), tune);
18773 free (string_root);
18774 }
18775
18776 /* Adjust CURRENT_TUNE (a generic tuning struct) with settings that
18777 are best for a generic target with the currently-enabled architecture
18778 extensions. */
18779 static void
18780 aarch64_adjust_generic_arch_tuning (struct tune_params &current_tune)
18781 {
18782 /* Neoverse V1 is the only core that is known to benefit from
18783 AARCH64_EXTRA_TUNE_CSE_SVE_VL_CONSTANTS. There is therefore no
18784 point enabling it for SVE2 and above. */
18785 if (TARGET_SVE2)
18786 current_tune.extra_tuning_flags
18787 &= ~AARCH64_EXTRA_TUNE_CSE_SVE_VL_CONSTANTS;
18788 }
18789
18790 static void
18791 aarch64_override_options_after_change_1 (struct gcc_options *opts)
18792 {
18793 /* PR 70044: We have to be careful about being called multiple times for the
18794 same function. This means all changes should be repeatable. */
18795
18796 /* Set aarch64_use_frame_pointer based on -fno-omit-frame-pointer.
18797 Disable the frame pointer flag so the mid-end will not use a frame
18798 pointer in leaf functions in order to support -fomit-leaf-frame-pointer.
18799 Set x_flag_omit_frame_pointer to the special value 2 to differentiate
18800 between -fomit-frame-pointer (1) and -fno-omit-frame-pointer (2). */
18801 aarch64_use_frame_pointer = opts->x_flag_omit_frame_pointer != 1;
18802 if (opts->x_flag_omit_frame_pointer == 0)
18803 opts->x_flag_omit_frame_pointer = 2;
18804
18805 /* If not optimizing for size, set the default
18806 alignment to what the target wants. */
18807 if (!opts->x_optimize_size)
18808 {
18809 if (opts->x_flag_align_loops && !opts->x_str_align_loops)
18810 opts->x_str_align_loops = aarch64_tune_params.loop_align;
18811 if (opts->x_flag_align_jumps && !opts->x_str_align_jumps)
18812 opts->x_str_align_jumps = aarch64_tune_params.jump_align;
18813 if (opts->x_flag_align_functions && !opts->x_str_align_functions)
18814 opts->x_str_align_functions = aarch64_tune_params.function_align;
18815 }
18816
18817 /* We default to no pc-relative literal loads. */
18818
18819 aarch64_pcrelative_literal_loads = false;
18820
18821 /* If -mpc-relative-literal-loads is set on the command line, this
18822 implies that the user asked for PC relative literal loads. */
18823 if (opts->x_pcrelative_literal_loads == 1)
18824 aarch64_pcrelative_literal_loads = true;
18825
18826 /* In the tiny memory model it makes no sense to disallow PC relative
18827 literal pool loads. */
18828 if (aarch64_cmodel == AARCH64_CMODEL_TINY
18829 || aarch64_cmodel == AARCH64_CMODEL_TINY_PIC)
18830 aarch64_pcrelative_literal_loads = true;
18831
18832 /* When enabling the lower precision Newton series for the square root, also
18833 enable it for the reciprocal square root, since the latter is an
18834 intermediary step for the former. */
18835 if (flag_mlow_precision_sqrt)
18836 flag_mrecip_low_precision_sqrt = true;
18837 }
18838
18839 /* 'Unpack' up the internal tuning structs and update the options
18840 in OPTS. The caller must have set up selected_tune and selected_arch
18841 as all the other target-specific codegen decisions are
18842 derived from them. */
18843
18844 void
18845 aarch64_override_options_internal (struct gcc_options *opts)
18846 {
18847 const struct processor *tune = aarch64_get_tune_cpu (opts->x_selected_tune);
18848 aarch64_tune = tune->sched_core;
18849 /* Make a copy of the tuning parameters attached to the core, which
18850 we may later overwrite. */
18851 aarch64_tune_params = *(tune->tune);
18852 if (tune->tune == &generic_tunings)
18853 aarch64_adjust_generic_arch_tuning (aarch64_tune_params);
18854
18855 if (opts->x_aarch64_override_tune_string)
18856 aarch64_parse_override_string (opts->x_aarch64_override_tune_string,
18857 &aarch64_tune_params);
18858
18859 if (opts->x_aarch64_ldp_policy_param)
18860 aarch64_tune_params.ldp_policy_model = opts->x_aarch64_ldp_policy_param;
18861
18862 if (opts->x_aarch64_stp_policy_param)
18863 aarch64_tune_params.stp_policy_model = opts->x_aarch64_stp_policy_param;
18864
18865 /* This target defaults to strict volatile bitfields. */
18866 if (opts->x_flag_strict_volatile_bitfields < 0 && abi_version_at_least (2))
18867 opts->x_flag_strict_volatile_bitfields = 1;
18868
18869 if (aarch64_stack_protector_guard == SSP_GLOBAL
18870 && opts->x_aarch64_stack_protector_guard_offset_str)
18871 {
18872 error ("incompatible options %<-mstack-protector-guard=global%> and "
18873 "%<-mstack-protector-guard-offset=%s%>",
18874 aarch64_stack_protector_guard_offset_str);
18875 }
18876
18877 if (aarch64_stack_protector_guard == SSP_SYSREG
18878 && !(opts->x_aarch64_stack_protector_guard_offset_str
18879 && opts->x_aarch64_stack_protector_guard_reg_str))
18880 {
18881 error ("both %<-mstack-protector-guard-offset%> and "
18882 "%<-mstack-protector-guard-reg%> must be used "
18883 "with %<-mstack-protector-guard=sysreg%>");
18884 }
18885
18886 if (opts->x_aarch64_stack_protector_guard_reg_str)
18887 {
18888 if (strlen (opts->x_aarch64_stack_protector_guard_reg_str) > 100)
18889 error ("specify a system register with a small string length");
18890 }
18891
18892 if (opts->x_aarch64_stack_protector_guard_offset_str)
18893 {
18894 char *end;
18895 const char *str = aarch64_stack_protector_guard_offset_str;
18896 errno = 0;
18897 long offs = strtol (aarch64_stack_protector_guard_offset_str, &end, 0);
18898 if (!*str || *end || errno)
18899 error ("%qs is not a valid offset in %qs", str,
18900 "-mstack-protector-guard-offset=");
18901 aarch64_stack_protector_guard_offset = offs;
18902 }
18903
18904 if ((flag_sanitize & SANITIZE_SHADOW_CALL_STACK)
18905 && !fixed_regs[R18_REGNUM])
18906 error ("%<-fsanitize=shadow-call-stack%> requires %<-ffixed-x18%>");
18907
18908 aarch64_feature_flags isa_flags = aarch64_get_isa_flags (opts);
18909 if ((isa_flags & (AARCH64_FL_SM_ON | AARCH64_FL_ZA_ON))
18910 && !(isa_flags & AARCH64_FL_SME))
18911 {
18912 if (isa_flags & AARCH64_FL_SM_ON)
18913 error ("streaming functions require the ISA extension %qs", "sme");
18914 else
18915 error ("functions with SME state require the ISA extension %qs",
18916 "sme");
18917 inform (input_location, "you can enable %qs using the command-line"
18918 " option %<-march%>, or by using the %<target%>"
18919 " attribute or pragma", "sme");
18920 opts->x_target_flags &= ~MASK_GENERAL_REGS_ONLY;
18921 auto new_flags = (isa_flags
18922 | feature_deps::SME ().enable
18923 /* TODO: Remove once we support SME without SVE2. */
18924 | feature_deps::SVE2 ().enable);
18925 aarch64_set_asm_isa_flags (opts, new_flags);
18926 }
18927
18928 initialize_aarch64_code_model (opts);
18929 initialize_aarch64_tls_size (opts);
18930 aarch64_tpidr_register = opts->x_aarch64_tpidr_reg;
18931
18932 int queue_depth = 0;
18933 switch (aarch64_tune_params.autoprefetcher_model)
18934 {
18935 case tune_params::AUTOPREFETCHER_OFF:
18936 queue_depth = -1;
18937 break;
18938 case tune_params::AUTOPREFETCHER_WEAK:
18939 queue_depth = 0;
18940 break;
18941 case tune_params::AUTOPREFETCHER_STRONG:
18942 queue_depth = max_insn_queue_index + 1;
18943 break;
18944 default:
18945 gcc_unreachable ();
18946 }
18947
18948 /* We don't mind passing in global_options_set here as we don't use
18949 the *options_set structs anyway. */
18950 SET_OPTION_IF_UNSET (opts, &global_options_set,
18951 param_sched_autopref_queue_depth, queue_depth);
18952
18953 /* Set up parameters to be used in prefetching algorithm. Do not
18954 override the defaults unless we are tuning for a core we have
18955 researched values for. */
18956 if (aarch64_tune_params.prefetch->num_slots > 0)
18957 SET_OPTION_IF_UNSET (opts, &global_options_set,
18958 param_simultaneous_prefetches,
18959 aarch64_tune_params.prefetch->num_slots);
18960 if (aarch64_tune_params.prefetch->l1_cache_size >= 0)
18961 SET_OPTION_IF_UNSET (opts, &global_options_set,
18962 param_l1_cache_size,
18963 aarch64_tune_params.prefetch->l1_cache_size);
18964 if (aarch64_tune_params.prefetch->l1_cache_line_size >= 0)
18965 SET_OPTION_IF_UNSET (opts, &global_options_set,
18966 param_l1_cache_line_size,
18967 aarch64_tune_params.prefetch->l1_cache_line_size);
18968
18969 if (aarch64_tune_params.prefetch->l1_cache_line_size >= 0)
18970 {
18971 SET_OPTION_IF_UNSET (opts, &global_options_set,
18972 param_destruct_interfere_size,
18973 aarch64_tune_params.prefetch->l1_cache_line_size);
18974 SET_OPTION_IF_UNSET (opts, &global_options_set,
18975 param_construct_interfere_size,
18976 aarch64_tune_params.prefetch->l1_cache_line_size);
18977 }
18978 else
18979 {
18980 /* For a generic AArch64 target, cover the current range of cache line
18981 sizes. */
18982 SET_OPTION_IF_UNSET (opts, &global_options_set,
18983 param_destruct_interfere_size,
18984 256);
18985 SET_OPTION_IF_UNSET (opts, &global_options_set,
18986 param_construct_interfere_size,
18987 64);
18988 }
18989
18990 if (aarch64_tune_params.prefetch->l2_cache_size >= 0)
18991 SET_OPTION_IF_UNSET (opts, &global_options_set,
18992 param_l2_cache_size,
18993 aarch64_tune_params.prefetch->l2_cache_size);
18994 if (!aarch64_tune_params.prefetch->prefetch_dynamic_strides)
18995 SET_OPTION_IF_UNSET (opts, &global_options_set,
18996 param_prefetch_dynamic_strides, 0);
18997 if (aarch64_tune_params.prefetch->minimum_stride >= 0)
18998 SET_OPTION_IF_UNSET (opts, &global_options_set,
18999 param_prefetch_minimum_stride,
19000 aarch64_tune_params.prefetch->minimum_stride);
19001
19002 /* Use the alternative scheduling-pressure algorithm by default. */
19003 SET_OPTION_IF_UNSET (opts, &global_options_set,
19004 param_sched_pressure_algorithm,
19005 SCHED_PRESSURE_MODEL);
19006
19007 /* Validate the guard size. */
19008 int guard_size = param_stack_clash_protection_guard_size;
19009
19010 if (guard_size != 12 && guard_size != 16)
19011 error ("only values 12 (4 KB) and 16 (64 KB) are supported for guard "
19012 "size. Given value %d (%llu KB) is out of range",
19013 guard_size, (1ULL << guard_size) / 1024ULL);
19014
19015 /* Enforce that interval is the same size as size so the mid-end does the
19016 right thing. */
19017 SET_OPTION_IF_UNSET (opts, &global_options_set,
19018 param_stack_clash_protection_probe_interval,
19019 guard_size);
19020
19021 /* The maybe_set calls won't update the value if the user has explicitly set
19022 one. Which means we need to validate that probing interval and guard size
19023 are equal. */
19024 int probe_interval
19025 = param_stack_clash_protection_probe_interval;
19026 if (guard_size != probe_interval)
19027 error ("stack clash guard size %<%d%> must be equal to probing interval "
19028 "%<%d%>", guard_size, probe_interval);
19029
19030 /* Enable sw prefetching at specified optimization level for
19031 CPUS that have prefetch. Lower optimization level threshold by 1
19032 when profiling is enabled. */
19033 if (opts->x_flag_prefetch_loop_arrays < 0
19034 && !opts->x_optimize_size
19035 && aarch64_tune_params.prefetch->default_opt_level >= 0
19036 && opts->x_optimize >= aarch64_tune_params.prefetch->default_opt_level)
19037 opts->x_flag_prefetch_loop_arrays = 1;
19038
19039 /* Avoid loop-dependant FMA chains. */
19040 if (aarch64_tune_params.extra_tuning_flags
19041 & AARCH64_EXTRA_TUNE_AVOID_CROSS_LOOP_FMA)
19042 SET_OPTION_IF_UNSET (opts, &global_options_set, param_avoid_fma_max_bits,
19043 512);
19044
19045 /* Consider fully pipelined FMA in reassociation. */
19046 if (aarch64_tune_params.extra_tuning_flags
19047 & AARCH64_EXTRA_TUNE_FULLY_PIPELINED_FMA)
19048 SET_OPTION_IF_UNSET (opts, &global_options_set, param_fully_pipelined_fma,
19049 1);
19050
19051 /* TODO: SME codegen without SVE2 is not supported, once this support is added
19052 remove this 'sorry' and the implicit enablement of SVE2 in the checks for
19053 streaming mode above in this function. */
19054 if (TARGET_SME && !TARGET_SVE2)
19055 sorry ("no support for %qs without %qs", "sme", "sve2");
19056
19057 aarch64_override_options_after_change_1 (opts);
19058 }
19059
19060 /* Straight line speculation indicators. */
19061 enum aarch64_sls_hardening_type
19062 {
19063 SLS_NONE = 0,
19064 SLS_RETBR = 1,
19065 SLS_BLR = 2,
19066 SLS_ALL = 3,
19067 };
19068 static enum aarch64_sls_hardening_type aarch64_sls_hardening;
19069
19070 /* Return whether we should mitigatate Straight Line Speculation for the RET
19071 and BR instructions. */
19072 bool
19073 aarch64_harden_sls_retbr_p (void)
19074 {
19075 return aarch64_sls_hardening & SLS_RETBR;
19076 }
19077
19078 /* Return whether we should mitigatate Straight Line Speculation for the BLR
19079 instruction. */
19080 bool
19081 aarch64_harden_sls_blr_p (void)
19082 {
19083 return aarch64_sls_hardening & SLS_BLR;
19084 }
19085
19086 /* As of yet we only allow setting these options globally, in the future we may
19087 allow setting them per function. */
19088 static void
19089 aarch64_validate_sls_mitigation (const char *const_str)
19090 {
19091 char *token_save = NULL;
19092 char *str = NULL;
19093
19094 if (strcmp (const_str, "none") == 0)
19095 {
19096 aarch64_sls_hardening = SLS_NONE;
19097 return;
19098 }
19099 if (strcmp (const_str, "all") == 0)
19100 {
19101 aarch64_sls_hardening = SLS_ALL;
19102 return;
19103 }
19104
19105 char *str_root = xstrdup (const_str);
19106 str = strtok_r (str_root, ",", &token_save);
19107 if (!str)
19108 error ("invalid argument given to %<-mharden-sls=%>");
19109
19110 int temp = SLS_NONE;
19111 while (str)
19112 {
19113 if (strcmp (str, "blr") == 0)
19114 temp |= SLS_BLR;
19115 else if (strcmp (str, "retbr") == 0)
19116 temp |= SLS_RETBR;
19117 else if (strcmp (str, "none") == 0 || strcmp (str, "all") == 0)
19118 {
19119 error ("%qs must be by itself for %<-mharden-sls=%>", str);
19120 break;
19121 }
19122 else
19123 {
19124 error ("invalid argument %qs for %<-mharden-sls=%>", str);
19125 break;
19126 }
19127 str = strtok_r (NULL, ",", &token_save);
19128 }
19129 aarch64_sls_hardening = (aarch64_sls_hardening_type) temp;
19130 free (str_root);
19131 }
19132
19133 /* Return the VG value associated with -msve-vector-bits= value VALUE. */
19134
19135 static poly_uint16
19136 aarch64_convert_sve_vector_bits (aarch64_sve_vector_bits_enum value)
19137 {
19138 /* 128-bit SVE and Advanced SIMD modes use different register layouts
19139 on big-endian targets, so we would need to forbid subregs that convert
19140 from one to the other. By default a reinterpret sequence would then
19141 involve a store to memory in one mode and a load back in the other.
19142 Even if we optimize that sequence using reverse instructions,
19143 it would still be a significant potential overhead.
19144
19145 For now, it seems better to generate length-agnostic code for that
19146 case instead. */
19147 if (value == SVE_SCALABLE
19148 || (value == SVE_128 && BYTES_BIG_ENDIAN))
19149 return poly_uint16 (2, 2);
19150 else
19151 return (int) value / 64;
19152 }
19153
19154 /* Set the global aarch64_asm_isa_flags to FLAGS and update
19155 aarch64_isa_flags accordingly. */
19156
19157 void
19158 aarch64_set_asm_isa_flags (aarch64_feature_flags flags)
19159 {
19160 aarch64_set_asm_isa_flags (&global_options, flags);
19161 }
19162
19163 static void
19164 aarch64_handle_no_branch_protection (void)
19165 {
19166 aarch_ra_sign_scope = AARCH_FUNCTION_NONE;
19167 aarch_enable_bti = 0;
19168 aarch64_enable_gcs = 0;
19169 }
19170
19171 static void
19172 aarch64_handle_standard_branch_protection (void)
19173 {
19174 aarch_ra_sign_scope = AARCH_FUNCTION_NON_LEAF;
19175 aarch64_ra_sign_key = AARCH64_KEY_A;
19176 aarch_enable_bti = 1;
19177 aarch64_enable_gcs = 1;
19178 }
19179
19180 static void
19181 aarch64_handle_pac_ret_protection (void)
19182 {
19183 aarch_ra_sign_scope = AARCH_FUNCTION_NON_LEAF;
19184 aarch64_ra_sign_key = AARCH64_KEY_A;
19185 }
19186
19187 static void
19188 aarch64_handle_pac_ret_leaf (void)
19189 {
19190 aarch_ra_sign_scope = AARCH_FUNCTION_ALL;
19191 }
19192
19193 static void
19194 aarch64_handle_pac_ret_b_key (void)
19195 {
19196 aarch64_ra_sign_key = AARCH64_KEY_B;
19197 }
19198
19199 static void
19200 aarch64_handle_bti_protection (void)
19201 {
19202 aarch_enable_bti = 1;
19203 }
19204 static void
19205 aarch64_handle_gcs_protection (void)
19206 {
19207 aarch64_enable_gcs = 1;
19208 }
19209
19210 static const struct aarch_branch_protect_type aarch64_pac_ret_subtypes[] = {
19211 { "leaf", false, aarch64_handle_pac_ret_leaf, NULL, 0 },
19212 { "b-key", false, aarch64_handle_pac_ret_b_key, NULL, 0 },
19213 { NULL, false, NULL, NULL, 0 }
19214 };
19215
19216 static const struct aarch_branch_protect_type aarch64_branch_protect_types[] =
19217 {
19218 { "none", true, aarch64_handle_no_branch_protection, NULL, 0 },
19219 { "standard", true, aarch64_handle_standard_branch_protection, NULL, 0 },
19220 { "pac-ret", false, aarch64_handle_pac_ret_protection,
19221 aarch64_pac_ret_subtypes, ARRAY_SIZE (aarch64_pac_ret_subtypes) },
19222 { "bti", false, aarch64_handle_bti_protection, NULL, 0 },
19223 { "gcs", false, aarch64_handle_gcs_protection, NULL, 0 },
19224 { NULL, false, NULL, NULL, 0 }
19225 };
19226
19227 /* Implement TARGET_OPTION_OVERRIDE. This is called once in the beginning
19228 and is used to parse the -m{cpu,tune,arch} strings and setup the initial
19229 tuning structs. In particular it must set selected_tune and
19230 aarch64_asm_isa_flags that define the available ISA features and tuning
19231 decisions. It must also set selected_arch as this will be used to
19232 output the .arch asm tags for each function. */
19233
19234 static void
19235 aarch64_override_options (void)
19236 {
19237 aarch64_feature_flags cpu_isa = 0;
19238 aarch64_feature_flags arch_isa = 0;
19239 aarch64_set_asm_isa_flags (0);
19240
19241 aarch64_cpu cpu = aarch64_no_cpu;
19242 aarch64_arch arch = aarch64_no_arch;
19243 aarch64_cpu tune = aarch64_no_cpu;
19244
19245 if (aarch64_harden_sls_string)
19246 aarch64_validate_sls_mitigation (aarch64_harden_sls_string);
19247
19248 if (aarch64_branch_protection_string)
19249 aarch_validate_mbranch_protection (aarch64_branch_protect_types,
19250 aarch64_branch_protection_string,
19251 "-mbranch-protection=");
19252
19253 /* -mcpu=CPU is shorthand for -march=ARCH_FOR_CPU, -mtune=CPU.
19254 If either of -march or -mtune is given, they override their
19255 respective component of -mcpu. */
19256 if (aarch64_cpu_string)
19257 aarch64_validate_mcpu (aarch64_cpu_string, &cpu, &cpu_isa);
19258
19259 if (aarch64_arch_string)
19260 aarch64_validate_march (aarch64_arch_string, &arch, &arch_isa);
19261
19262 if (aarch64_tune_string)
19263 aarch64_validate_mtune (aarch64_tune_string, &tune);
19264
19265 #ifdef SUBTARGET_OVERRIDE_OPTIONS
19266 SUBTARGET_OVERRIDE_OPTIONS;
19267 #endif
19268
19269 if (cpu != aarch64_no_cpu && arch != aarch64_no_arch)
19270 {
19271 /* If both -mcpu and -march are specified, warn if they are not
19272 feature compatible. feature compatible means that the inclusion of the
19273 cpu features would end up disabling an achitecture feature. In
19274 otherwords the cpu features need to be a strict superset of the arch
19275 features and if so prefer the -march ISA flags. */
19276 if (~cpu_isa & arch_isa)
19277 {
19278 std::string ext_diff
19279 = aarch64_get_extension_string_for_isa_flags (arch_isa, cpu_isa);
19280 warning (0, "switch %<-mcpu=%s%> conflicts with %<-march=%s%> switch "
19281 "and resulted in options %qs being added",
19282 aarch64_cpu_string,
19283 aarch64_arch_string,
19284 ext_diff.c_str ());
19285 }
19286
19287 selected_arch = arch;
19288 aarch64_set_asm_isa_flags (arch_isa | AARCH64_FL_DEFAULT_ISA_MODE);
19289 }
19290 else if (cpu != aarch64_no_cpu)
19291 {
19292 selected_arch = aarch64_get_tune_cpu (cpu)->arch;
19293 aarch64_set_asm_isa_flags (cpu_isa | AARCH64_FL_DEFAULT_ISA_MODE);
19294 }
19295 else if (arch != aarch64_no_arch)
19296 {
19297 cpu = aarch64_get_arch (arch)->ident;
19298 selected_arch = arch;
19299 aarch64_set_asm_isa_flags (arch_isa | AARCH64_FL_DEFAULT_ISA_MODE);
19300 }
19301 else
19302 {
19303 /* No -mcpu or -march specified, so use the default CPU. */
19304 cpu = TARGET_CPU_DEFAULT;
19305 const processor *cpu_info = aarch64_get_tune_cpu (cpu);
19306 selected_arch = cpu_info->arch;
19307 aarch64_set_asm_isa_flags (cpu_info->flags
19308 | AARCH64_FL_DEFAULT_ISA_MODE);
19309 }
19310
19311 selected_tune = (tune != aarch64_no_cpu) ? tune : cpu;
19312
19313 if (aarch_enable_bti == 2)
19314 {
19315 #ifdef TARGET_ENABLE_BTI
19316 aarch_enable_bti = 1;
19317 #else
19318 aarch_enable_bti = 0;
19319 #endif
19320 }
19321
19322 if (aarch64_enable_gcs == 2)
19323 {
19324 #ifdef TARGET_ENABLE_GCS
19325 aarch64_enable_gcs = 1;
19326 #else
19327 aarch64_enable_gcs = 0;
19328 #endif
19329 }
19330
19331 /* Return address signing is currently not supported for ILP32 targets. For
19332 LP64 targets use the configured option in the absence of a command-line
19333 option for -mbranch-protection. */
19334 if (!TARGET_ILP32 && aarch64_branch_protection_string == NULL)
19335 {
19336 #ifdef TARGET_ENABLE_PAC_RET
19337 aarch_ra_sign_scope = AARCH_FUNCTION_NON_LEAF;
19338 #else
19339 aarch_ra_sign_scope = AARCH_FUNCTION_NONE;
19340 #endif
19341 }
19342
19343 #ifndef HAVE_AS_MABI_OPTION
19344 /* The compiler may have been configured with 2.23.* binutils, which does
19345 not have support for ILP32. */
19346 if (TARGET_ILP32)
19347 error ("assembler does not support %<-mabi=ilp32%>");
19348 #endif
19349 if (TARGET_ILP32)
19350 warning (OPT_Wdeprecated, "%<-mabi=ilp32%> is deprecated");
19351
19352 /* Convert -msve-vector-bits to a VG count. */
19353 aarch64_sve_vg = aarch64_convert_sve_vector_bits (aarch64_sve_vector_bits);
19354
19355 if (aarch_ra_sign_scope != AARCH_FUNCTION_NONE && TARGET_ILP32)
19356 sorry ("return address signing is only supported for %<-mabi=lp64%>");
19357
19358 /* The pass to insert speculation tracking runs before
19359 shrink-wrapping and the latter does not know how to update the
19360 tracking status. So disable it in this case. */
19361 if (aarch64_track_speculation)
19362 flag_shrink_wrap = 0;
19363
19364 aarch64_override_options_internal (&global_options);
19365
19366 /* Save these options as the default ones in case we push and pop them later
19367 while processing functions with potential target attributes. */
19368 target_option_default_node = target_option_current_node
19369 = build_target_option_node (&global_options, &global_options_set);
19370 }
19371
19372 /* Implement targetm.override_options_after_change. */
19373
19374 static void
19375 aarch64_override_options_after_change (void)
19376 {
19377 aarch64_override_options_after_change_1 (&global_options);
19378 }
19379
19380 /* Implement the TARGET_OFFLOAD_OPTIONS hook. */
19381 static char *
19382 aarch64_offload_options (void)
19383 {
19384 if (TARGET_ILP32)
19385 return xstrdup ("-foffload-abi=ilp32 -foffload-abi-host-opts=-mabi=ilp32");
19386 else
19387 return xstrdup ("-foffload-abi=lp64 -foffload-abi-host-opts=-mabi=lp64");
19388 }
19389
19390 static struct machine_function *
19391 aarch64_init_machine_status (void)
19392 {
19393 struct machine_function *machine;
19394 machine = ggc_cleared_alloc<machine_function> ();
19395 return machine;
19396 }
19397
19398 void
19399 aarch64_init_expanders (void)
19400 {
19401 init_machine_status = aarch64_init_machine_status;
19402 }
19403
19404 /* A checking mechanism for the implementation of the various code models. */
19405 static void
19406 initialize_aarch64_code_model (struct gcc_options *opts)
19407 {
19408 aarch64_cmodel = opts->x_aarch64_cmodel_var;
19409 switch (opts->x_aarch64_cmodel_var)
19410 {
19411 case AARCH64_CMODEL_TINY:
19412 if (opts->x_flag_pic)
19413 aarch64_cmodel = AARCH64_CMODEL_TINY_PIC;
19414 break;
19415 case AARCH64_CMODEL_SMALL:
19416 if (opts->x_flag_pic)
19417 {
19418 #ifdef HAVE_AS_SMALL_PIC_RELOCS
19419 aarch64_cmodel = (flag_pic == 2
19420 ? AARCH64_CMODEL_SMALL_PIC
19421 : AARCH64_CMODEL_SMALL_SPIC);
19422 #else
19423 aarch64_cmodel = AARCH64_CMODEL_SMALL_PIC;
19424 #endif
19425 }
19426 break;
19427 case AARCH64_CMODEL_LARGE:
19428 if (opts->x_flag_pic)
19429 sorry ("code model %qs with %<-f%s%>", "large",
19430 opts->x_flag_pic > 1 ? "PIC" : "pic");
19431 if (opts->x_aarch64_abi == AARCH64_ABI_ILP32)
19432 sorry ("code model %qs not supported in ilp32 mode", "large");
19433 break;
19434 case AARCH64_CMODEL_TINY_PIC:
19435 case AARCH64_CMODEL_SMALL_PIC:
19436 case AARCH64_CMODEL_SMALL_SPIC:
19437 gcc_unreachable ();
19438 }
19439 }
19440
19441 /* Implements TARGET_OPTION_RESTORE. Restore the backend codegen decisions
19442 using the information saved in PTR. */
19443
19444 static void
19445 aarch64_option_restore (struct gcc_options *opts,
19446 struct gcc_options * /* opts_set */,
19447 struct cl_target_option * /* ptr */)
19448 {
19449 aarch64_override_options_internal (opts);
19450 }
19451
19452 /* Implement TARGET_OPTION_PRINT. */
19453
19454 static void
19455 aarch64_option_print (FILE *file, int indent, struct cl_target_option *ptr)
19456 {
19457 const struct processor *cpu
19458 = aarch64_get_tune_cpu (ptr->x_selected_tune);
19459 const struct processor *arch = aarch64_get_arch (ptr->x_selected_arch);
19460 aarch64_feature_flags isa_flags = aarch64_get_asm_isa_flags(ptr);
19461 std::string extension
19462 = aarch64_get_extension_string_for_isa_flags (isa_flags, arch->flags);
19463
19464 fprintf (file, "%*sselected tune = %s\n", indent, "", cpu->name);
19465 fprintf (file, "%*sselected arch = %s%s\n", indent, "",
19466 arch->name, extension.c_str ());
19467 }
19468
19469 static GTY(()) tree aarch64_previous_fndecl;
19470
19471 void
19472 aarch64_reset_previous_fndecl (void)
19473 {
19474 aarch64_previous_fndecl = NULL;
19475 }
19476
19477 /* Restore or save the TREE_TARGET_GLOBALS from or to NEW_TREE.
19478 Used by aarch64_set_current_function and aarch64_pragma_target_parse to
19479 make sure optab availability predicates are recomputed when necessary. */
19480
19481 void
19482 aarch64_save_restore_target_globals (tree new_tree)
19483 {
19484 if (TREE_TARGET_GLOBALS (new_tree))
19485 restore_target_globals (TREE_TARGET_GLOBALS (new_tree));
19486 else if (new_tree == target_option_default_node)
19487 restore_target_globals (&default_target_globals);
19488 else
19489 TREE_TARGET_GLOBALS (new_tree) = save_target_globals_default_opts ();
19490 }
19491
19492 /* Return the target_option_node for FNDECL, or the current options
19493 if FNDECL is null. */
19494
19495 static tree
19496 aarch64_fndecl_options (tree fndecl)
19497 {
19498 if (!fndecl)
19499 return target_option_current_node;
19500
19501 if (tree options = DECL_FUNCTION_SPECIFIC_TARGET (fndecl))
19502 return options;
19503
19504 return target_option_default_node;
19505 }
19506
19507 /* Implement TARGET_SET_CURRENT_FUNCTION. Unpack the codegen decisions
19508 like tuning and ISA features from the DECL_FUNCTION_SPECIFIC_TARGET
19509 of the function, if such exists. This function may be called multiple
19510 times on a single function so use aarch64_previous_fndecl to avoid
19511 setting up identical state. */
19512
19513 static void
19514 aarch64_set_current_function (tree fndecl)
19515 {
19516 tree old_tree = aarch64_fndecl_options (aarch64_previous_fndecl);
19517 tree new_tree = aarch64_fndecl_options (fndecl);
19518
19519 auto new_isa_mode = (fndecl
19520 ? aarch64_fndecl_isa_mode (fndecl)
19521 : AARCH64_DEFAULT_ISA_MODE);
19522 auto isa_flags = aarch64_get_isa_flags (TREE_TARGET_OPTION (new_tree));
19523
19524 static bool reported_zt0_p;
19525 if (!reported_zt0_p
19526 && !(isa_flags & AARCH64_FL_SME2)
19527 && fndecl
19528 && aarch64_fndecl_has_state (fndecl, "zt0"))
19529 {
19530 error ("functions with %qs state require the ISA extension %qs",
19531 "zt0", "sme2");
19532 inform (input_location, "you can enable %qs using the command-line"
19533 " option %<-march%>, or by using the %<target%>"
19534 " attribute or pragma", "sme2");
19535 reported_zt0_p = true;
19536 }
19537
19538 /* If nothing to do, return. #pragma GCC reset or #pragma GCC pop to
19539 the default have been handled by aarch64_save_restore_target_globals from
19540 aarch64_pragma_target_parse. */
19541 if (old_tree == new_tree
19542 && (!fndecl || aarch64_previous_fndecl)
19543 && (isa_flags & AARCH64_FL_ISA_MODES).val[0] == new_isa_mode)
19544 {
19545 gcc_assert (AARCH64_ISA_MODE == new_isa_mode);
19546 return;
19547 }
19548
19549 aarch64_previous_fndecl = fndecl;
19550
19551 /* First set the target options. */
19552 cl_target_option_restore (&global_options, &global_options_set,
19553 TREE_TARGET_OPTION (new_tree));
19554
19555 /* The ISA mode can vary based on function type attributes and
19556 function declaration attributes. Make sure that the target
19557 options correctly reflect these attributes. */
19558 if ((isa_flags & AARCH64_FL_ISA_MODES).val[0] != new_isa_mode)
19559 {
19560 auto base_flags = (aarch64_asm_isa_flags & ~AARCH64_FL_ISA_MODES);
19561 aarch64_set_asm_isa_flags (base_flags
19562 | aarch64_feature_flags (new_isa_mode));
19563
19564 aarch64_override_options_internal (&global_options);
19565 new_tree = build_target_option_node (&global_options,
19566 &global_options_set);
19567 DECL_FUNCTION_SPECIFIC_TARGET (fndecl) = new_tree;
19568
19569 tree new_optimize = build_optimization_node (&global_options,
19570 &global_options_set);
19571 if (new_optimize != optimization_default_node)
19572 DECL_FUNCTION_SPECIFIC_OPTIMIZATION (fndecl) = new_optimize;
19573 }
19574
19575 aarch64_save_restore_target_globals (new_tree);
19576
19577 gcc_assert (AARCH64_ISA_MODE == new_isa_mode);
19578 }
19579
19580 /* Enum describing the various ways we can handle attributes.
19581 In many cases we can reuse the generic option handling machinery. */
19582
19583 enum aarch64_attr_opt_type
19584 {
19585 aarch64_attr_mask, /* Attribute should set a bit in target_flags. */
19586 aarch64_attr_bool, /* Attribute sets or unsets a boolean variable. */
19587 aarch64_attr_enum, /* Attribute sets an enum variable. */
19588 aarch64_attr_custom /* Attribute requires a custom handling function. */
19589 };
19590
19591 /* All the information needed to handle a target attribute.
19592 NAME is the name of the attribute.
19593 ATTR_TYPE specifies the type of behavior of the attribute as described
19594 in the definition of enum aarch64_attr_opt_type.
19595 ALLOW_NEG is true if the attribute supports a "no-" form.
19596 HANDLER is the function that takes the attribute string as an argument
19597 It is needed only when the ATTR_TYPE is aarch64_attr_custom.
19598 OPT_NUM is the enum specifying the option that the attribute modifies.
19599 This is needed for attributes that mirror the behavior of a command-line
19600 option, that is it has ATTR_TYPE aarch64_attr_mask, aarch64_attr_bool or
19601 aarch64_attr_enum. */
19602
19603 struct aarch64_attribute_info
19604 {
19605 const char *name;
19606 enum aarch64_attr_opt_type attr_type;
19607 bool allow_neg;
19608 bool (*handler) (const char *);
19609 enum opt_code opt_num;
19610 };
19611
19612 /* Handle the ARCH_STR argument to the arch= target attribute. */
19613
19614 static bool
19615 aarch64_handle_attr_arch (const char *str)
19616 {
19617 aarch64_arch tmp_arch = aarch64_no_arch;
19618 std::string invalid_extension;
19619 aarch64_feature_flags tmp_flags;
19620 enum aarch_parse_opt_result parse_res
19621 = aarch64_parse_arch (str, &tmp_arch, &tmp_flags, &invalid_extension);
19622
19623 if (parse_res == AARCH_PARSE_OK)
19624 {
19625 gcc_assert (tmp_arch != aarch64_no_arch);
19626 selected_arch = tmp_arch;
19627 aarch64_set_asm_isa_flags (tmp_flags | (aarch64_asm_isa_flags
19628 & AARCH64_FL_ISA_MODES));
19629 return true;
19630 }
19631
19632 switch (parse_res)
19633 {
19634 case AARCH_PARSE_MISSING_ARG:
19635 error ("missing name in %<target(\"arch=\")%> pragma or attribute");
19636 break;
19637 case AARCH_PARSE_INVALID_ARG:
19638 error ("invalid name %qs in %<target(\"arch=\")%> pragma or attribute", str);
19639 aarch64_print_hint_for_arch (str);
19640 break;
19641 case AARCH_PARSE_INVALID_FEATURE:
19642 error ("invalid feature modifier %s of value %qs in "
19643 "%<target()%> pragma or attribute", invalid_extension.c_str (), str);
19644 aarch64_print_hint_for_extensions (invalid_extension.c_str ());
19645 break;
19646 default:
19647 gcc_unreachable ();
19648 }
19649
19650 return false;
19651 }
19652
19653 /* Handle the argument CPU_STR to the cpu= target attribute. */
19654
19655 static bool
19656 aarch64_handle_attr_cpu (const char *str)
19657 {
19658 aarch64_cpu tmp_cpu = aarch64_no_cpu;
19659 std::string invalid_extension;
19660 aarch64_feature_flags tmp_flags;
19661 enum aarch_parse_opt_result parse_res
19662 = aarch64_parse_cpu (str, &tmp_cpu, &tmp_flags, &invalid_extension);
19663
19664 if (parse_res == AARCH_PARSE_OK)
19665 {
19666 gcc_assert (tmp_cpu != aarch64_no_cpu);
19667 selected_tune = tmp_cpu;
19668 selected_arch = aarch64_get_tune_cpu (tmp_cpu)->arch;
19669 aarch64_set_asm_isa_flags (tmp_flags | (aarch64_asm_isa_flags
19670 & AARCH64_FL_ISA_MODES));
19671 return true;
19672 }
19673
19674 switch (parse_res)
19675 {
19676 case AARCH_PARSE_MISSING_ARG:
19677 error ("missing name in %<target(\"cpu=\")%> pragma or attribute");
19678 break;
19679 case AARCH_PARSE_INVALID_ARG:
19680 error ("invalid name %qs in %<target(\"cpu=\")%> pragma or attribute", str);
19681 aarch64_print_hint_for_core (str);
19682 break;
19683 case AARCH_PARSE_INVALID_FEATURE:
19684 error ("invalid feature modifier %qs of value %qs in "
19685 "%<target()%> pragma or attribute", invalid_extension.c_str (), str);
19686 aarch64_print_hint_for_extensions (invalid_extension.c_str ());
19687 break;
19688 default:
19689 gcc_unreachable ();
19690 }
19691
19692 return false;
19693 }
19694
19695 /* Handle the argument STR to the branch-protection= attribute. */
19696
19697 static bool
19698 aarch64_handle_attr_branch_protection (const char* str)
19699 {
19700 return aarch_validate_mbranch_protection (aarch64_branch_protect_types, str,
19701 "target(\"branch-protection=\")");
19702 }
19703
19704 /* Handle the argument STR to the tune= target attribute. */
19705
19706 static bool
19707 aarch64_handle_attr_tune (const char *str)
19708 {
19709 aarch64_cpu tmp_tune = aarch64_no_cpu;
19710 enum aarch_parse_opt_result parse_res
19711 = aarch64_parse_tune (str, &tmp_tune);
19712
19713 if (parse_res == AARCH_PARSE_OK)
19714 {
19715 gcc_assert (tmp_tune != aarch64_no_cpu);
19716 selected_tune = tmp_tune;
19717 return true;
19718 }
19719
19720 switch (parse_res)
19721 {
19722 case AARCH_PARSE_INVALID_ARG:
19723 error ("invalid name %qs in %<target(\"tune=\")%> pragma or attribute", str);
19724 aarch64_print_hint_for_core (str);
19725 break;
19726 default:
19727 gcc_unreachable ();
19728 }
19729
19730 return false;
19731 }
19732
19733 /* Parse an architecture extensions target attribute string specified in STR.
19734 For example "+fp+nosimd". Show any errors if needed. Return TRUE
19735 if successful. Update aarch64_isa_flags to reflect the ISA features
19736 modified. */
19737
19738 static bool
19739 aarch64_handle_attr_isa_flags (char *str)
19740 {
19741 enum aarch_parse_opt_result parse_res;
19742 auto isa_flags = aarch64_asm_isa_flags;
19743
19744 /* We allow "+nothing" in the beginning to clear out all architectural
19745 features if the user wants to handpick specific features. */
19746 if (strncmp ("+nothing", str, 8) == 0)
19747 {
19748 isa_flags &= AARCH64_FL_ISA_MODES;
19749 str += 8;
19750 }
19751
19752 std::string invalid_extension;
19753 parse_res = aarch64_parse_extension (str, &isa_flags, &invalid_extension);
19754
19755 if (parse_res == AARCH_PARSE_OK)
19756 {
19757 aarch64_set_asm_isa_flags (isa_flags);
19758 return true;
19759 }
19760
19761 switch (parse_res)
19762 {
19763 case AARCH_PARSE_MISSING_ARG:
19764 error ("missing value in %<target()%> pragma or attribute");
19765 break;
19766
19767 case AARCH_PARSE_INVALID_FEATURE:
19768 error ("invalid feature modifier %qs of value %qs in "
19769 "%<target()%> pragma or attribute", invalid_extension.c_str (), str);
19770 break;
19771
19772 default:
19773 gcc_unreachable ();
19774 }
19775
19776 return false;
19777 }
19778
19779 /* The target attributes that we support. On top of these we also support just
19780 ISA extensions, like __attribute__ ((target ("+crc"))), but that case is
19781 handled explicitly in aarch64_process_one_target_attr. */
19782
19783 static const struct aarch64_attribute_info aarch64_attributes[] =
19784 {
19785 { "general-regs-only", aarch64_attr_mask, false, NULL,
19786 OPT_mgeneral_regs_only },
19787 { "fix-cortex-a53-835769", aarch64_attr_bool, true, NULL,
19788 OPT_mfix_cortex_a53_835769 },
19789 { "fix-cortex-a53-843419", aarch64_attr_bool, true, NULL,
19790 OPT_mfix_cortex_a53_843419 },
19791 { "cmodel", aarch64_attr_enum, false, NULL, OPT_mcmodel_ },
19792 { "strict-align", aarch64_attr_mask, true, NULL, OPT_mstrict_align },
19793 { "omit-leaf-frame-pointer", aarch64_attr_bool, true, NULL,
19794 OPT_momit_leaf_frame_pointer },
19795 { "tls-dialect", aarch64_attr_enum, false, NULL, OPT_mtls_dialect_ },
19796 { "arch", aarch64_attr_custom, false, aarch64_handle_attr_arch,
19797 OPT_march_ },
19798 { "cpu", aarch64_attr_custom, false, aarch64_handle_attr_cpu, OPT_mcpu_ },
19799 { "tune", aarch64_attr_custom, false, aarch64_handle_attr_tune,
19800 OPT_mtune_ },
19801 { "branch-protection", aarch64_attr_custom, false,
19802 aarch64_handle_attr_branch_protection, OPT_mbranch_protection_ },
19803 { "sign-return-address", aarch64_attr_enum, false, NULL,
19804 OPT_msign_return_address_ },
19805 { "outline-atomics", aarch64_attr_bool, true, NULL,
19806 OPT_moutline_atomics},
19807 { "simd-memops", aarch64_attr_bool, true, NULL,
19808 OPT_msimd_memops},
19809 { NULL, aarch64_attr_custom, false, NULL, OPT____ }
19810 };
19811
19812 /* Parse ARG_STR which contains the definition of one target attribute.
19813 Show appropriate errors if any or return true if the attribute is valid. */
19814
19815 static bool
19816 aarch64_process_one_target_attr (char *arg_str)
19817 {
19818 bool invert = false;
19819
19820 size_t len = strlen (arg_str);
19821
19822 if (len == 0)
19823 {
19824 error ("malformed %<target()%> pragma or attribute");
19825 return false;
19826 }
19827
19828 auto_vec<char, 32> buffer;
19829 buffer.safe_grow (len + 1);
19830 char *str_to_check = buffer.address ();
19831 memcpy (str_to_check, arg_str, len + 1);
19832
19833 /* We have something like __attribute__ ((target ("+fp+nosimd"))).
19834 It is easier to detect and handle it explicitly here rather than going
19835 through the machinery for the rest of the target attributes in this
19836 function. */
19837 if (*str_to_check == '+')
19838 return aarch64_handle_attr_isa_flags (str_to_check);
19839
19840 if (len > 3 && startswith (str_to_check, "no-"))
19841 {
19842 invert = true;
19843 str_to_check += 3;
19844 }
19845 char *arg = strchr (str_to_check, '=');
19846
19847 /* If we found opt=foo then terminate STR_TO_CHECK at the '='
19848 and point ARG to "foo". */
19849 if (arg)
19850 {
19851 *arg = '\0';
19852 arg++;
19853 }
19854 const struct aarch64_attribute_info *p_attr;
19855 bool found = false;
19856 for (p_attr = aarch64_attributes; p_attr->name; p_attr++)
19857 {
19858 /* If the names don't match up, or the user has given an argument
19859 to an attribute that doesn't accept one, or didn't give an argument
19860 to an attribute that expects one, fail to match. */
19861 if (strcmp (str_to_check, p_attr->name) != 0)
19862 continue;
19863
19864 found = true;
19865 bool attr_need_arg_p = p_attr->attr_type == aarch64_attr_custom
19866 || p_attr->attr_type == aarch64_attr_enum;
19867
19868 if (attr_need_arg_p ^ (arg != NULL))
19869 {
19870 error ("pragma or attribute %<target(\"%s\")%> does not accept an argument", str_to_check);
19871 return false;
19872 }
19873
19874 /* If the name matches but the attribute does not allow "no-" versions
19875 then we can't match. */
19876 if (invert && !p_attr->allow_neg)
19877 {
19878 error ("pragma or attribute %<target(\"%s\")%> does not allow a negated form", str_to_check);
19879 return false;
19880 }
19881
19882 switch (p_attr->attr_type)
19883 {
19884 /* Has a custom handler registered.
19885 For example, cpu=, arch=, tune=. */
19886 case aarch64_attr_custom:
19887 gcc_assert (p_attr->handler);
19888 if (!p_attr->handler (arg))
19889 return false;
19890 break;
19891
19892 /* Either set or unset a boolean option. */
19893 case aarch64_attr_bool:
19894 {
19895 struct cl_decoded_option decoded;
19896
19897 generate_option (p_attr->opt_num, NULL, !invert,
19898 CL_TARGET, &decoded);
19899 aarch64_handle_option (&global_options, &global_options_set,
19900 &decoded, input_location);
19901 break;
19902 }
19903 /* Set or unset a bit in the target_flags. aarch64_handle_option
19904 should know what mask to apply given the option number. */
19905 case aarch64_attr_mask:
19906 {
19907 struct cl_decoded_option decoded;
19908 /* We only need to specify the option number.
19909 aarch64_handle_option will know which mask to apply. */
19910 decoded.opt_index = p_attr->opt_num;
19911 decoded.value = !invert;
19912 aarch64_handle_option (&global_options, &global_options_set,
19913 &decoded, input_location);
19914 break;
19915 }
19916 /* Use the option setting machinery to set an option to an enum. */
19917 case aarch64_attr_enum:
19918 {
19919 gcc_assert (arg);
19920 bool valid;
19921 int value;
19922 valid = opt_enum_arg_to_value (p_attr->opt_num, arg,
19923 &value, CL_TARGET);
19924 if (valid)
19925 {
19926 set_option (&global_options, NULL, p_attr->opt_num, value,
19927 NULL, DK_UNSPECIFIED, input_location,
19928 global_dc);
19929 }
19930 else
19931 {
19932 error ("pragma or attribute %<target(\"%s=%s\")%> is not valid", str_to_check, arg);
19933 }
19934 break;
19935 }
19936 default:
19937 gcc_unreachable ();
19938 }
19939 }
19940
19941 /* If we reached here we either have found an attribute and validated
19942 it or didn't match any. If we matched an attribute but its arguments
19943 were malformed we will have returned false already. */
19944 return found;
19945 }
19946
19947 /* Count how many times the character C appears in
19948 NULL-terminated string STR. */
19949
19950 static unsigned int
19951 num_occurences_in_str (char c, char *str)
19952 {
19953 unsigned int res = 0;
19954 while (*str != '\0')
19955 {
19956 if (*str == c)
19957 res++;
19958
19959 str++;
19960 }
19961
19962 return res;
19963 }
19964
19965 /* Parse the tree in ARGS that contains the target attribute information
19966 and update the global target options space. */
19967
19968 bool
19969 aarch64_process_target_attr (tree args)
19970 {
19971 if (TREE_CODE (args) == TREE_LIST)
19972 {
19973 do
19974 {
19975 tree head = TREE_VALUE (args);
19976 if (head)
19977 {
19978 if (!aarch64_process_target_attr (head))
19979 return false;
19980 }
19981 args = TREE_CHAIN (args);
19982 } while (args);
19983
19984 return true;
19985 }
19986
19987 if (TREE_CODE (args) != STRING_CST)
19988 {
19989 error ("attribute %<target%> argument not a string");
19990 return false;
19991 }
19992
19993 size_t len = strlen (TREE_STRING_POINTER (args));
19994 auto_vec<char, 32> buffer;
19995 buffer.safe_grow (len + 1);
19996 char *str_to_check = buffer.address ();
19997 memcpy (str_to_check, TREE_STRING_POINTER (args), len + 1);
19998
19999 if (len == 0)
20000 {
20001 error ("malformed %<target()%> pragma or attribute");
20002 return false;
20003 }
20004
20005 /* Used to catch empty spaces between commas i.e.
20006 attribute ((target ("attr1,,attr2"))). */
20007 unsigned int num_commas = num_occurences_in_str (',', str_to_check);
20008
20009 /* Handle multiple target attributes separated by ','. */
20010 char *token = strtok_r (str_to_check, ",", &str_to_check);
20011
20012 unsigned int num_attrs = 0;
20013 while (token)
20014 {
20015 num_attrs++;
20016 if (!aarch64_process_one_target_attr (token))
20017 {
20018 /* Check if token is possibly an arch extension without
20019 leading '+'. */
20020 aarch64_feature_flags isa_temp = 0;
20021 auto with_plus = std::string ("+") + token;
20022 enum aarch_parse_opt_result ext_res
20023 = aarch64_parse_extension (with_plus.c_str (), &isa_temp, nullptr);
20024
20025 if (ext_res == AARCH_PARSE_OK)
20026 error ("arch extension %qs should be prefixed by %<+%>",
20027 token);
20028 else
20029 error ("pragma or attribute %<target(\"%s\")%> is not valid", token);
20030 return false;
20031 }
20032
20033 token = strtok_r (NULL, ",", &str_to_check);
20034 }
20035
20036 if (num_attrs != num_commas + 1)
20037 {
20038 error ("malformed %<target(\"%s\")%> pragma or attribute", TREE_STRING_POINTER (args));
20039 return false;
20040 }
20041
20042 return true;
20043 }
20044
20045 static bool aarch64_process_target_version_attr (tree args);
20046
20047 /* Implement TARGET_OPTION_VALID_ATTRIBUTE_P. This is used to
20048 process attribute ((target ("..."))). */
20049
20050 static bool
20051 aarch64_option_valid_attribute_p (tree fndecl, tree, tree args, int)
20052 {
20053 struct cl_target_option cur_target;
20054 bool ret;
20055 tree old_optimize;
20056 tree new_target, new_optimize;
20057 tree existing_target = DECL_FUNCTION_SPECIFIC_TARGET (fndecl);
20058
20059 /* If what we're processing is the current pragma string then the
20060 target option node is already stored in target_option_current_node
20061 by aarch64_pragma_target_parse in aarch64-c.cc. Use that to avoid
20062 having to re-parse the string. This is especially useful to keep
20063 arm_neon.h compile times down since that header contains a lot
20064 of intrinsics enclosed in pragmas. */
20065 if (!existing_target && args == current_target_pragma)
20066 {
20067 DECL_FUNCTION_SPECIFIC_TARGET (fndecl) = target_option_current_node;
20068 return true;
20069 }
20070 tree func_optimize = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (fndecl);
20071
20072 old_optimize
20073 = build_optimization_node (&global_options, &global_options_set);
20074 func_optimize = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (fndecl);
20075
20076 /* If the function changed the optimization levels as well as setting
20077 target options, start with the optimizations specified. */
20078 if (func_optimize && func_optimize != old_optimize)
20079 cl_optimization_restore (&global_options, &global_options_set,
20080 TREE_OPTIMIZATION (func_optimize));
20081
20082 /* Save the current target options to restore at the end. */
20083 cl_target_option_save (&cur_target, &global_options, &global_options_set);
20084
20085 /* If fndecl already has some target attributes applied to it, unpack
20086 them so that we add this attribute on top of them, rather than
20087 overwriting them. */
20088 if (existing_target)
20089 {
20090 struct cl_target_option *existing_options
20091 = TREE_TARGET_OPTION (existing_target);
20092
20093 if (existing_options)
20094 cl_target_option_restore (&global_options, &global_options_set,
20095 existing_options);
20096 }
20097 else
20098 cl_target_option_restore (&global_options, &global_options_set,
20099 TREE_TARGET_OPTION (target_option_current_node));
20100
20101 ret = aarch64_process_target_attr (args);
20102 if (ret)
20103 {
20104 tree version_attr = lookup_attribute ("target_version",
20105 DECL_ATTRIBUTES (fndecl));
20106 if (version_attr != NULL_TREE)
20107 {
20108 /* Reapply any target_version attribute after target attribute.
20109 This should be equivalent to applying the target_version once
20110 after processing all target attributes. */
20111 tree version_args = TREE_VALUE (version_attr);
20112 ret = aarch64_process_target_version_attr (version_args);
20113 }
20114 }
20115
20116 /* Set up any additional state. */
20117 if (ret)
20118 {
20119 aarch64_override_options_internal (&global_options);
20120 new_target = build_target_option_node (&global_options,
20121 &global_options_set);
20122 }
20123 else
20124 new_target = NULL;
20125
20126 new_optimize = build_optimization_node (&global_options,
20127 &global_options_set);
20128
20129 if (fndecl && ret)
20130 {
20131 DECL_FUNCTION_SPECIFIC_TARGET (fndecl) = new_target;
20132
20133 if (old_optimize != new_optimize)
20134 DECL_FUNCTION_SPECIFIC_OPTIMIZATION (fndecl) = new_optimize;
20135 }
20136
20137 cl_target_option_restore (&global_options, &global_options_set, &cur_target);
20138
20139 if (old_optimize != new_optimize)
20140 cl_optimization_restore (&global_options, &global_options_set,
20141 TREE_OPTIMIZATION (old_optimize));
20142 return ret;
20143 }
20144
20145 typedef unsigned long long aarch64_fmv_feature_mask;
20146
20147 typedef struct
20148 {
20149 const char *name;
20150 aarch64_fmv_feature_mask feature_mask;
20151 aarch64_feature_flags opt_flags;
20152 } aarch64_fmv_feature_datum;
20153
20154 #define AARCH64_FMV_FEATURE(NAME, FEAT_NAME, C) \
20155 {NAME, 1ULL << FEAT_##FEAT_NAME, ::feature_deps::fmv_deps_##FEAT_NAME},
20156
20157 /* The "rdma" alias uses a different FEAT_NAME to avoid a duplicate
20158 feature_deps name. */
20159 #define FEAT_RDMA FEAT_RDM
20160
20161 /* FMV features are listed in priority order, to make it easier to sort target
20162 strings. */
20163 static aarch64_fmv_feature_datum aarch64_fmv_feature_data[] = {
20164 #include "config/aarch64/aarch64-option-extensions.def"
20165 };
20166
20167 /* Parse a function multiversioning feature string STR, as found in a
20168 target_version or target_clones attribute.
20169
20170 If ISA_FLAGS is nonnull, then update it with the specified architecture
20171 features turned on. If FEATURE_MASK is nonnull, then assign to it a bitmask
20172 representing the set of features explicitly specified in the feature string.
20173 Return an aarch_parse_opt_result describing the result.
20174
20175 When the STR string contains an invalid or duplicate extension, a copy of
20176 the extension string is created and stored to INVALID_EXTENSION. */
20177
20178 static enum aarch_parse_opt_result
20179 aarch64_parse_fmv_features (const char *str, aarch64_feature_flags *isa_flags,
20180 aarch64_fmv_feature_mask *feature_mask,
20181 std::string *invalid_extension)
20182 {
20183 if (feature_mask)
20184 *feature_mask = 0ULL;
20185
20186 if (strcmp (str, "default") == 0)
20187 return AARCH_PARSE_OK;
20188
20189 while (str != NULL && *str != 0)
20190 {
20191 const char *ext;
20192 size_t len;
20193
20194 ext = strchr (str, '+');
20195
20196 if (ext != NULL)
20197 len = ext - str;
20198 else
20199 len = strlen (str);
20200
20201 if (len == 0)
20202 return AARCH_PARSE_MISSING_ARG;
20203
20204 int num_features = ARRAY_SIZE (aarch64_fmv_feature_data);
20205 int i;
20206 for (i = 0; i < num_features; i++)
20207 {
20208 if (strlen (aarch64_fmv_feature_data[i].name) == len
20209 && strncmp (aarch64_fmv_feature_data[i].name, str, len) == 0)
20210 {
20211 if (isa_flags)
20212 *isa_flags |= aarch64_fmv_feature_data[i].opt_flags;
20213 if (feature_mask)
20214 {
20215 auto old_feature_mask = *feature_mask;
20216 *feature_mask |= aarch64_fmv_feature_data[i].feature_mask;
20217 if (*feature_mask == old_feature_mask)
20218 {
20219 /* Duplicate feature. */
20220 if (invalid_extension)
20221 *invalid_extension = std::string (str, len);
20222 return AARCH_PARSE_DUPLICATE_FEATURE;
20223 }
20224 }
20225 break;
20226 }
20227 }
20228
20229 if (i == num_features)
20230 {
20231 /* Feature not found in list. */
20232 if (invalid_extension)
20233 *invalid_extension = std::string (str, len);
20234 return AARCH_PARSE_INVALID_FEATURE;
20235 }
20236
20237 str = ext;
20238 if (str)
20239 /* Skip over the next '+'. */
20240 str++;
20241 }
20242
20243 return AARCH_PARSE_OK;
20244 }
20245
20246 /* Parse the tree in ARGS that contains the target_version attribute
20247 information and update the global target options space. */
20248
20249 static bool
20250 aarch64_process_target_version_attr (tree args)
20251 {
20252 static bool issued_warning = false;
20253 if (!issued_warning)
20254 {
20255 warning (OPT_Wexperimental_fmv_target,
20256 "Function Multi Versioning support is experimental, and the "
20257 "behavior is likely to change");
20258 issued_warning = true;
20259 }
20260
20261 if (TREE_CODE (args) == TREE_LIST)
20262 {
20263 if (TREE_CHAIN (args))
20264 {
20265 error ("attribute %<target_version%> has multiple values");
20266 return false;
20267 }
20268 args = TREE_VALUE (args);
20269 }
20270
20271 if (!args || TREE_CODE (args) != STRING_CST)
20272 {
20273 error ("attribute %<target_version%> argument not a string");
20274 return false;
20275 }
20276
20277 const char *str = TREE_STRING_POINTER (args);
20278
20279 enum aarch_parse_opt_result parse_res;
20280 auto isa_flags = aarch64_asm_isa_flags;
20281
20282 std::string invalid_extension;
20283 parse_res = aarch64_parse_fmv_features (str, &isa_flags, NULL,
20284 &invalid_extension);
20285
20286 if (parse_res == AARCH_PARSE_OK)
20287 {
20288 aarch64_set_asm_isa_flags (isa_flags);
20289 return true;
20290 }
20291
20292 switch (parse_res)
20293 {
20294 case AARCH_PARSE_MISSING_ARG:
20295 error ("missing value in %<target_version%> attribute");
20296 break;
20297
20298 case AARCH_PARSE_INVALID_FEATURE:
20299 error ("invalid feature modifier %qs of value %qs in "
20300 "%<target_version%> attribute", invalid_extension.c_str (),
20301 str);
20302 break;
20303
20304 case AARCH_PARSE_DUPLICATE_FEATURE:
20305 error ("duplicate feature modifier %qs of value %qs in "
20306 "%<target_version%> attribute", invalid_extension.c_str (),
20307 str);
20308 break;
20309
20310 default:
20311 gcc_unreachable ();
20312 }
20313
20314 return false;
20315 }
20316
20317 /* Implement TARGET_OPTION_VALID_VERSION_ATTRIBUTE_P. This is used to
20318 process attribute ((target_version ("..."))). */
20319
20320 static bool
20321 aarch64_option_valid_version_attribute_p (tree fndecl, tree, tree args, int)
20322 {
20323 struct cl_target_option cur_target;
20324 bool ret;
20325 tree new_target;
20326 tree existing_target = DECL_FUNCTION_SPECIFIC_TARGET (fndecl);
20327
20328 /* Save the current target options to restore at the end. */
20329 cl_target_option_save (&cur_target, &global_options, &global_options_set);
20330
20331 /* If fndecl already has some target attributes applied to it, unpack
20332 them so that we add this attribute on top of them, rather than
20333 overwriting them. */
20334 if (existing_target)
20335 {
20336 struct cl_target_option *existing_options
20337 = TREE_TARGET_OPTION (existing_target);
20338
20339 if (existing_options)
20340 cl_target_option_restore (&global_options, &global_options_set,
20341 existing_options);
20342 }
20343 else
20344 cl_target_option_restore (&global_options, &global_options_set,
20345 TREE_TARGET_OPTION (target_option_current_node));
20346
20347 ret = aarch64_process_target_version_attr (args);
20348
20349 /* Set up any additional state. */
20350 if (ret)
20351 {
20352 aarch64_override_options_internal (&global_options);
20353 new_target = build_target_option_node (&global_options,
20354 &global_options_set);
20355 }
20356 else
20357 new_target = NULL;
20358
20359 if (fndecl && ret)
20360 DECL_FUNCTION_SPECIFIC_TARGET (fndecl) = new_target;
20361
20362 cl_target_option_restore (&global_options, &global_options_set, &cur_target);
20363
20364 return ret;
20365 }
20366
20367 /* This parses the attribute arguments to target_version in DECL and the
20368 feature mask required to select those targets. No adjustments are made to
20369 add or remove redundant feature requirements. */
20370
20371 static aarch64_fmv_feature_mask
20372 get_feature_mask_for_version (tree decl)
20373 {
20374 tree version_attr = lookup_attribute ("target_version",
20375 DECL_ATTRIBUTES (decl));
20376 if (version_attr == NULL)
20377 return 0;
20378
20379 const char *version_string = TREE_STRING_POINTER (TREE_VALUE (TREE_VALUE
20380 (version_attr)));
20381 enum aarch_parse_opt_result parse_res;
20382 aarch64_fmv_feature_mask feature_mask;
20383
20384 parse_res = aarch64_parse_fmv_features (version_string, NULL, &feature_mask,
20385 NULL);
20386
20387 /* We should have detected any errors before getting here. */
20388 gcc_assert (parse_res == AARCH_PARSE_OK);
20389
20390 return feature_mask;
20391 }
20392
20393 /* Compare priorities of two feature masks. Return:
20394 1: mask1 is higher priority
20395 -1: mask2 is higher priority
20396 0: masks are equal. */
20397
20398 static int
20399 compare_feature_masks (aarch64_fmv_feature_mask mask1,
20400 aarch64_fmv_feature_mask mask2)
20401 {
20402 int pop1 = popcount_hwi (mask1);
20403 int pop2 = popcount_hwi (mask2);
20404 if (pop1 > pop2)
20405 return 1;
20406 if (pop2 > pop1)
20407 return -1;
20408
20409 auto diff_mask = mask1 ^ mask2;
20410 if (diff_mask == 0ULL)
20411 return 0;
20412 int num_features = ARRAY_SIZE (aarch64_fmv_feature_data);
20413 for (int i = num_features - 1; i >= 0; i--)
20414 {
20415 auto bit_mask = aarch64_fmv_feature_data[i].feature_mask;
20416 if (diff_mask & bit_mask)
20417 return (mask1 & bit_mask) ? 1 : -1;
20418 }
20419 gcc_unreachable();
20420 }
20421
20422 /* Compare priorities of two version decls. */
20423
20424 int
20425 aarch64_compare_version_priority (tree decl1, tree decl2)
20426 {
20427 auto mask1 = get_feature_mask_for_version (decl1);
20428 auto mask2 = get_feature_mask_for_version (decl2);
20429
20430 return compare_feature_masks (mask1, mask2);
20431 }
20432
20433 /* Build the struct __ifunc_arg_t type:
20434
20435 struct __ifunc_arg_t
20436 {
20437 unsigned long _size; // Size of the struct, so it can grow.
20438 unsigned long _hwcap;
20439 unsigned long _hwcap2;
20440 }
20441 */
20442
20443 static tree
20444 build_ifunc_arg_type ()
20445 {
20446 tree ifunc_arg_type = lang_hooks.types.make_type (RECORD_TYPE);
20447 tree field1 = build_decl (UNKNOWN_LOCATION, FIELD_DECL,
20448 get_identifier ("_size"),
20449 long_unsigned_type_node);
20450 tree field2 = build_decl (UNKNOWN_LOCATION, FIELD_DECL,
20451 get_identifier ("_hwcap"),
20452 long_unsigned_type_node);
20453 tree field3 = build_decl (UNKNOWN_LOCATION, FIELD_DECL,
20454 get_identifier ("_hwcap2"),
20455 long_unsigned_type_node);
20456
20457 DECL_FIELD_CONTEXT (field1) = ifunc_arg_type;
20458 DECL_FIELD_CONTEXT (field2) = ifunc_arg_type;
20459 DECL_FIELD_CONTEXT (field3) = ifunc_arg_type;
20460
20461 TYPE_FIELDS (ifunc_arg_type) = field1;
20462 DECL_CHAIN (field1) = field2;
20463 DECL_CHAIN (field2) = field3;
20464
20465 layout_type (ifunc_arg_type);
20466
20467 tree const_type = build_qualified_type (ifunc_arg_type, TYPE_QUAL_CONST);
20468 tree pointer_type = build_pointer_type (const_type);
20469
20470 return pointer_type;
20471 }
20472
20473 /* Implement TARGET_MANGLE_DECL_ASSEMBLER_NAME, to add function multiversioning
20474 suffixes. */
20475
20476 tree
20477 aarch64_mangle_decl_assembler_name (tree decl, tree id)
20478 {
20479 /* For function version, add the target suffix to the assembler name. */
20480 if (TREE_CODE (decl) == FUNCTION_DECL
20481 && DECL_FUNCTION_VERSIONED (decl))
20482 {
20483 aarch64_fmv_feature_mask feature_mask = get_feature_mask_for_version (decl);
20484
20485 std::string name = IDENTIFIER_POINTER (id);
20486
20487 /* For the default version, append ".default". */
20488 if (feature_mask == 0ULL)
20489 {
20490 name += ".default";
20491 return get_identifier (name.c_str());
20492 }
20493
20494 name += "._";
20495
20496 int num_features = ARRAY_SIZE (aarch64_fmv_feature_data);
20497 for (int i = 0; i < num_features; i++)
20498 {
20499 if (feature_mask & aarch64_fmv_feature_data[i].feature_mask)
20500 {
20501 name += "M";
20502 name += aarch64_fmv_feature_data[i].name;
20503 }
20504 }
20505
20506 if (DECL_ASSEMBLER_NAME_SET_P (decl))
20507 SET_DECL_RTL (decl, NULL);
20508
20509 id = get_identifier (name.c_str());
20510 }
20511 return id;
20512 }
20513
20514 /* Return an identifier for the base assembler name of a versioned function.
20515 This is computed by taking the default version's assembler name, and
20516 stripping off the ".default" suffix if it's already been appended. */
20517
20518 static tree
20519 get_suffixed_assembler_name (tree default_decl, const char *suffix)
20520 {
20521 std::string name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (default_decl));
20522
20523 auto size = name.size ();
20524 if (size >= 8 && name.compare (size - 8, 8, ".default") == 0)
20525 name.resize (size - 8);
20526 name += suffix;
20527 return get_identifier (name.c_str());
20528 }
20529
20530 /* Make the resolver function decl to dispatch the versions of
20531 a multi-versioned function, DEFAULT_DECL. IFUNC_ALIAS_DECL is
20532 ifunc alias that will point to the created resolver. Create an
20533 empty basic block in the resolver and store the pointer in
20534 EMPTY_BB. Return the decl of the resolver function. */
20535
20536 static tree
20537 make_resolver_func (const tree default_decl,
20538 const tree ifunc_alias_decl,
20539 basic_block *empty_bb)
20540 {
20541 tree decl, type, t;
20542
20543 /* Create resolver function name based on default_decl. We need to remove an
20544 existing ".default" suffix if this has already been appended. */
20545 tree decl_name = get_suffixed_assembler_name (default_decl, ".resolver");
20546 const char *resolver_name = IDENTIFIER_POINTER (decl_name);
20547
20548 /* The resolver function should have signature
20549 (void *) resolver (uint64_t, const __ifunc_arg_t *) */
20550 type = build_function_type_list (ptr_type_node,
20551 uint64_type_node,
20552 build_ifunc_arg_type (),
20553 NULL_TREE);
20554
20555 decl = build_fn_decl (resolver_name, type);
20556 SET_DECL_ASSEMBLER_NAME (decl, decl_name);
20557
20558 DECL_NAME (decl) = decl_name;
20559 TREE_USED (decl) = 1;
20560 DECL_ARTIFICIAL (decl) = 1;
20561 DECL_IGNORED_P (decl) = 1;
20562 TREE_PUBLIC (decl) = 0;
20563 DECL_UNINLINABLE (decl) = 1;
20564
20565 /* Resolver is not external, body is generated. */
20566 DECL_EXTERNAL (decl) = 0;
20567 DECL_EXTERNAL (ifunc_alias_decl) = 0;
20568
20569 DECL_CONTEXT (decl) = NULL_TREE;
20570 DECL_INITIAL (decl) = make_node (BLOCK);
20571 DECL_STATIC_CONSTRUCTOR (decl) = 0;
20572
20573 if (DECL_COMDAT_GROUP (default_decl)
20574 || TREE_PUBLIC (default_decl))
20575 {
20576 /* In this case, each translation unit with a call to this
20577 versioned function will put out a resolver. Ensure it
20578 is comdat to keep just one copy. */
20579 DECL_COMDAT (decl) = 1;
20580 make_decl_one_only (decl, DECL_ASSEMBLER_NAME (decl));
20581 }
20582 else
20583 TREE_PUBLIC (ifunc_alias_decl) = 0;
20584
20585 /* Build result decl and add to function_decl. */
20586 t = build_decl (UNKNOWN_LOCATION, RESULT_DECL, NULL_TREE, ptr_type_node);
20587 DECL_CONTEXT (t) = decl;
20588 DECL_ARTIFICIAL (t) = 1;
20589 DECL_IGNORED_P (t) = 1;
20590 DECL_RESULT (decl) = t;
20591
20592 /* Build parameter decls and add to function_decl. */
20593 tree arg1 = build_decl (UNKNOWN_LOCATION, PARM_DECL,
20594 get_identifier ("hwcap"),
20595 uint64_type_node);
20596 tree arg2 = build_decl (UNKNOWN_LOCATION, PARM_DECL,
20597 get_identifier ("arg"),
20598 build_ifunc_arg_type());
20599 DECL_CONTEXT (arg1) = decl;
20600 DECL_CONTEXT (arg2) = decl;
20601 DECL_ARTIFICIAL (arg1) = 1;
20602 DECL_ARTIFICIAL (arg2) = 1;
20603 DECL_IGNORED_P (arg1) = 1;
20604 DECL_IGNORED_P (arg2) = 1;
20605 DECL_ARG_TYPE (arg1) = uint64_type_node;
20606 DECL_ARG_TYPE (arg2) = build_ifunc_arg_type ();
20607 DECL_ARGUMENTS (decl) = arg1;
20608 TREE_CHAIN (arg1) = arg2;
20609
20610 gimplify_function_tree (decl);
20611 push_cfun (DECL_STRUCT_FUNCTION (decl));
20612 *empty_bb = init_lowered_empty_function (decl, false,
20613 profile_count::uninitialized ());
20614
20615 cgraph_node::add_new_function (decl, true);
20616 symtab->call_cgraph_insertion_hooks (cgraph_node::get_create (decl));
20617
20618 pop_cfun ();
20619
20620 gcc_assert (ifunc_alias_decl != NULL);
20621 /* Mark ifunc_alias_decl as "ifunc" with resolver as resolver_name. */
20622 DECL_ATTRIBUTES (ifunc_alias_decl)
20623 = make_attribute ("ifunc", resolver_name,
20624 DECL_ATTRIBUTES (ifunc_alias_decl));
20625
20626 /* Create the alias for dispatch to resolver here. */
20627 cgraph_node::create_same_body_alias (ifunc_alias_decl, decl);
20628 return decl;
20629 }
20630
20631 /* This adds a condition to the basic_block NEW_BB in function FUNCTION_DECL
20632 to return a pointer to VERSION_DECL if all feature bits specified in
20633 FEATURE_MASK are not set in MASK_VAR. This function will be called during
20634 version dispatch to decide which function version to execute. It returns
20635 the basic block at the end, to which more conditions can be added. */
20636 static basic_block
20637 add_condition_to_bb (tree function_decl, tree version_decl,
20638 aarch64_fmv_feature_mask feature_mask,
20639 tree mask_var, basic_block new_bb)
20640 {
20641 gimple *return_stmt;
20642 tree convert_expr, result_var;
20643 gimple *convert_stmt;
20644 gimple *if_else_stmt;
20645
20646 basic_block bb1, bb2, bb3;
20647 edge e12, e23;
20648
20649 gimple_seq gseq;
20650
20651 push_cfun (DECL_STRUCT_FUNCTION (function_decl));
20652
20653 gcc_assert (new_bb != NULL);
20654 gseq = bb_seq (new_bb);
20655
20656 convert_expr = build1 (CONVERT_EXPR, ptr_type_node,
20657 build_fold_addr_expr (version_decl));
20658 result_var = create_tmp_var (ptr_type_node);
20659 convert_stmt = gimple_build_assign (result_var, convert_expr);
20660 return_stmt = gimple_build_return (result_var);
20661
20662 if (feature_mask == 0ULL)
20663 {
20664 /* Default version. */
20665 gimple_seq_add_stmt (&gseq, convert_stmt);
20666 gimple_seq_add_stmt (&gseq, return_stmt);
20667 set_bb_seq (new_bb, gseq);
20668 gimple_set_bb (convert_stmt, new_bb);
20669 gimple_set_bb (return_stmt, new_bb);
20670 pop_cfun ();
20671 return new_bb;
20672 }
20673
20674 tree and_expr_var = create_tmp_var (long_long_unsigned_type_node);
20675 tree and_expr = build2 (BIT_AND_EXPR,
20676 long_long_unsigned_type_node,
20677 mask_var,
20678 build_int_cst (long_long_unsigned_type_node,
20679 feature_mask));
20680 gimple *and_stmt = gimple_build_assign (and_expr_var, and_expr);
20681 gimple_set_block (and_stmt, DECL_INITIAL (function_decl));
20682 gimple_set_bb (and_stmt, new_bb);
20683 gimple_seq_add_stmt (&gseq, and_stmt);
20684
20685 tree zero_llu = build_int_cst (long_long_unsigned_type_node, 0);
20686 if_else_stmt = gimple_build_cond (EQ_EXPR, and_expr_var, zero_llu,
20687 NULL_TREE, NULL_TREE);
20688 gimple_set_block (if_else_stmt, DECL_INITIAL (function_decl));
20689 gimple_set_bb (if_else_stmt, new_bb);
20690 gimple_seq_add_stmt (&gseq, if_else_stmt);
20691
20692 gimple_seq_add_stmt (&gseq, convert_stmt);
20693 gimple_seq_add_stmt (&gseq, return_stmt);
20694 set_bb_seq (new_bb, gseq);
20695
20696 bb1 = new_bb;
20697 e12 = split_block (bb1, if_else_stmt);
20698 bb2 = e12->dest;
20699 e12->flags &= ~EDGE_FALLTHRU;
20700 e12->flags |= EDGE_TRUE_VALUE;
20701
20702 e23 = split_block (bb2, return_stmt);
20703
20704 gimple_set_bb (convert_stmt, bb2);
20705 gimple_set_bb (return_stmt, bb2);
20706
20707 bb3 = e23->dest;
20708 make_edge (bb1, bb3, EDGE_FALSE_VALUE);
20709
20710 remove_edge (e23);
20711 make_edge (bb2, EXIT_BLOCK_PTR_FOR_FN (cfun), 0);
20712
20713 pop_cfun ();
20714
20715 return bb3;
20716 }
20717
20718 /* This function generates the dispatch function for
20719 multi-versioned functions. DISPATCH_DECL is the function which will
20720 contain the dispatch logic. FNDECLS are the function choices for
20721 dispatch, and is a tree chain. EMPTY_BB is the basic block pointer
20722 in DISPATCH_DECL in which the dispatch code is generated. */
20723
20724 static int
20725 dispatch_function_versions (tree dispatch_decl,
20726 void *fndecls_p,
20727 basic_block *empty_bb)
20728 {
20729 gimple *ifunc_cpu_init_stmt;
20730 gimple_seq gseq;
20731 vec<tree> *fndecls;
20732
20733 gcc_assert (dispatch_decl != NULL
20734 && fndecls_p != NULL
20735 && empty_bb != NULL);
20736
20737 push_cfun (DECL_STRUCT_FUNCTION (dispatch_decl));
20738
20739 gseq = bb_seq (*empty_bb);
20740 /* Function version dispatch is via IFUNC. IFUNC resolvers fire before
20741 constructors, so explicity call __init_cpu_features_resolver here. */
20742 tree init_fn_type = build_function_type_list (void_type_node,
20743 long_unsigned_type_node,
20744 build_ifunc_arg_type(),
20745 NULL);
20746 tree init_fn_id = get_identifier ("__init_cpu_features_resolver");
20747 tree init_fn_decl = build_decl (UNKNOWN_LOCATION, FUNCTION_DECL,
20748 init_fn_id, init_fn_type);
20749 DECL_EXTERNAL (init_fn_decl) = 1;
20750 TREE_PUBLIC (init_fn_decl) = 1;
20751 DECL_VISIBILITY (init_fn_decl) = VISIBILITY_HIDDEN;
20752 DECL_VISIBILITY_SPECIFIED (init_fn_decl) = 1;
20753 tree arg1 = DECL_ARGUMENTS (dispatch_decl);
20754 tree arg2 = TREE_CHAIN (arg1);
20755 ifunc_cpu_init_stmt = gimple_build_call (init_fn_decl, 2, arg1, arg2);
20756 gimple_seq_add_stmt (&gseq, ifunc_cpu_init_stmt);
20757 gimple_set_bb (ifunc_cpu_init_stmt, *empty_bb);
20758
20759 /* Build the struct type for __aarch64_cpu_features. */
20760 tree global_type = lang_hooks.types.make_type (RECORD_TYPE);
20761 tree field1 = build_decl (UNKNOWN_LOCATION, FIELD_DECL,
20762 get_identifier ("features"),
20763 long_long_unsigned_type_node);
20764 DECL_FIELD_CONTEXT (field1) = global_type;
20765 TYPE_FIELDS (global_type) = field1;
20766 layout_type (global_type);
20767
20768 tree global_var = build_decl (UNKNOWN_LOCATION, VAR_DECL,
20769 get_identifier ("__aarch64_cpu_features"),
20770 global_type);
20771 DECL_EXTERNAL (global_var) = 1;
20772 TREE_PUBLIC (global_var) = 1;
20773 DECL_VISIBILITY (global_var) = VISIBILITY_HIDDEN;
20774 DECL_VISIBILITY_SPECIFIED (global_var) = 1;
20775 tree mask_var = create_tmp_var (long_long_unsigned_type_node);
20776
20777 tree component_expr = build3 (COMPONENT_REF, long_long_unsigned_type_node,
20778 global_var, field1, NULL_TREE);
20779 gimple *component_stmt = gimple_build_assign (mask_var, component_expr);
20780 gimple_set_block (component_stmt, DECL_INITIAL (dispatch_decl));
20781 gimple_set_bb (component_stmt, *empty_bb);
20782 gimple_seq_add_stmt (&gseq, component_stmt);
20783
20784 tree not_expr = build1 (BIT_NOT_EXPR, long_long_unsigned_type_node, mask_var);
20785 gimple *not_stmt = gimple_build_assign (mask_var, not_expr);
20786 gimple_set_block (not_stmt, DECL_INITIAL (dispatch_decl));
20787 gimple_set_bb (not_stmt, *empty_bb);
20788 gimple_seq_add_stmt (&gseq, not_stmt);
20789
20790 set_bb_seq (*empty_bb, gseq);
20791
20792 pop_cfun ();
20793
20794 /* fndecls_p is actually a vector. */
20795 fndecls = static_cast<vec<tree> *> (fndecls_p);
20796
20797 /* At least one more version other than the default. */
20798 unsigned int num_versions = fndecls->length ();
20799 gcc_assert (num_versions >= 2);
20800
20801 struct function_version_info
20802 {
20803 tree version_decl;
20804 aarch64_fmv_feature_mask feature_mask;
20805 } *function_versions;
20806
20807 function_versions = (struct function_version_info *)
20808 XNEWVEC (struct function_version_info, (num_versions));
20809
20810 unsigned int actual_versions = 0;
20811
20812 for (tree version_decl : *fndecls)
20813 {
20814 aarch64_fmv_feature_mask feature_mask;
20815 /* Get attribute string, parse it and find the right features. */
20816 feature_mask = get_feature_mask_for_version (version_decl);
20817 function_versions [actual_versions].version_decl = version_decl;
20818 function_versions [actual_versions].feature_mask = feature_mask;
20819 actual_versions++;
20820 }
20821
20822 auto compare_feature_version_info = [](const void *p1, const void *p2) {
20823 const function_version_info v1 = *(const function_version_info *)p1;
20824 const function_version_info v2 = *(const function_version_info *)p2;
20825 return - compare_feature_masks (v1.feature_mask, v2.feature_mask);
20826 };
20827
20828 /* Sort the versions according to descending order of dispatch priority. */
20829 qsort (function_versions, actual_versions,
20830 sizeof (struct function_version_info), compare_feature_version_info);
20831
20832 for (unsigned int i = 0; i < actual_versions; ++i)
20833 *empty_bb = add_condition_to_bb (dispatch_decl,
20834 function_versions[i].version_decl,
20835 function_versions[i].feature_mask,
20836 mask_var,
20837 *empty_bb);
20838
20839 free (function_versions);
20840 return 0;
20841 }
20842
20843 /* Implement TARGET_GENERATE_VERSION_DISPATCHER_BODY. */
20844
20845 tree
20846 aarch64_generate_version_dispatcher_body (void *node_p)
20847 {
20848 tree resolver_decl;
20849 basic_block empty_bb;
20850 tree default_ver_decl;
20851 struct cgraph_node *versn;
20852 struct cgraph_node *node;
20853
20854 struct cgraph_function_version_info *node_version_info = NULL;
20855 struct cgraph_function_version_info *versn_info = NULL;
20856
20857 node = (cgraph_node *)node_p;
20858
20859 node_version_info = node->function_version ();
20860 gcc_assert (node->dispatcher_function
20861 && node_version_info != NULL);
20862
20863 if (node_version_info->dispatcher_resolver)
20864 return node_version_info->dispatcher_resolver;
20865
20866 /* The first version in the chain corresponds to the default version. */
20867 default_ver_decl = node_version_info->next->this_node->decl;
20868
20869 /* node is going to be an alias, so remove the finalized bit. */
20870 node->definition = false;
20871
20872 resolver_decl = make_resolver_func (default_ver_decl,
20873 node->decl, &empty_bb);
20874
20875 node_version_info->dispatcher_resolver = resolver_decl;
20876
20877 push_cfun (DECL_STRUCT_FUNCTION (resolver_decl));
20878
20879 auto_vec<tree, 2> fn_ver_vec;
20880
20881 for (versn_info = node_version_info->next; versn_info;
20882 versn_info = versn_info->next)
20883 {
20884 versn = versn_info->this_node;
20885 /* Check for virtual functions here again, as by this time it should
20886 have been determined if this function needs a vtable index or
20887 not. This happens for methods in derived classes that override
20888 virtual methods in base classes but are not explicitly marked as
20889 virtual. */
20890 if (DECL_VINDEX (versn->decl))
20891 sorry ("virtual function multiversioning not supported");
20892
20893 fn_ver_vec.safe_push (versn->decl);
20894 }
20895
20896 dispatch_function_versions (resolver_decl, &fn_ver_vec, &empty_bb);
20897 cgraph_edge::rebuild_edges ();
20898 pop_cfun ();
20899
20900 /* Fix up symbol names. First we need to obtain the base name, which may
20901 have already been mangled. */
20902 tree base_name = get_suffixed_assembler_name (default_ver_decl, "");
20903
20904 /* We need to redo the version mangling on the non-default versions for the
20905 target_clones case. Redoing the mangling for the target_version case is
20906 redundant but does no harm. We need to skip the default version, because
20907 expand_clones will append ".default" later; fortunately that suffix is the
20908 one we want anyway. */
20909 for (versn_info = node_version_info->next->next; versn_info;
20910 versn_info = versn_info->next)
20911 {
20912 tree version_decl = versn_info->this_node->decl;
20913 tree name = aarch64_mangle_decl_assembler_name (version_decl,
20914 base_name);
20915 symtab->change_decl_assembler_name (version_decl, name);
20916 }
20917
20918 /* We also need to use the base name for the ifunc declaration. */
20919 symtab->change_decl_assembler_name (node->decl, base_name);
20920
20921 return resolver_decl;
20922 }
20923
20924 /* Make a dispatcher declaration for the multi-versioned function DECL.
20925 Calls to DECL function will be replaced with calls to the dispatcher
20926 by the front-end. Returns the decl of the dispatcher function. */
20927
20928 tree
20929 aarch64_get_function_versions_dispatcher (void *decl)
20930 {
20931 tree fn = (tree) decl;
20932 struct cgraph_node *node = NULL;
20933 struct cgraph_node *default_node = NULL;
20934 struct cgraph_function_version_info *node_v = NULL;
20935 struct cgraph_function_version_info *first_v = NULL;
20936
20937 tree dispatch_decl = NULL;
20938
20939 struct cgraph_function_version_info *default_version_info = NULL;
20940
20941 gcc_assert (fn != NULL && DECL_FUNCTION_VERSIONED (fn));
20942
20943 node = cgraph_node::get (fn);
20944 gcc_assert (node != NULL);
20945
20946 node_v = node->function_version ();
20947 gcc_assert (node_v != NULL);
20948
20949 if (node_v->dispatcher_resolver != NULL)
20950 return node_v->dispatcher_resolver;
20951
20952 /* Find the default version and make it the first node. */
20953 first_v = node_v;
20954 /* Go to the beginning of the chain. */
20955 while (first_v->prev != NULL)
20956 first_v = first_v->prev;
20957 default_version_info = first_v;
20958 while (default_version_info != NULL)
20959 {
20960 if (get_feature_mask_for_version
20961 (default_version_info->this_node->decl) == 0ULL)
20962 break;
20963 default_version_info = default_version_info->next;
20964 }
20965
20966 /* If there is no default node, just return NULL. */
20967 if (default_version_info == NULL)
20968 return NULL;
20969
20970 /* Make default info the first node. */
20971 if (first_v != default_version_info)
20972 {
20973 default_version_info->prev->next = default_version_info->next;
20974 if (default_version_info->next)
20975 default_version_info->next->prev = default_version_info->prev;
20976 first_v->prev = default_version_info;
20977 default_version_info->next = first_v;
20978 default_version_info->prev = NULL;
20979 }
20980
20981 default_node = default_version_info->this_node;
20982
20983 if (targetm.has_ifunc_p ())
20984 {
20985 struct cgraph_function_version_info *it_v = NULL;
20986 struct cgraph_node *dispatcher_node = NULL;
20987 struct cgraph_function_version_info *dispatcher_version_info = NULL;
20988
20989 /* Right now, the dispatching is done via ifunc. */
20990 dispatch_decl = make_dispatcher_decl (default_node->decl);
20991 TREE_NOTHROW (dispatch_decl) = TREE_NOTHROW (fn);
20992
20993 dispatcher_node = cgraph_node::get_create (dispatch_decl);
20994 gcc_assert (dispatcher_node != NULL);
20995 dispatcher_node->dispatcher_function = 1;
20996 dispatcher_version_info
20997 = dispatcher_node->insert_new_function_version ();
20998 dispatcher_version_info->next = default_version_info;
20999 dispatcher_node->definition = 1;
21000
21001 /* Set the dispatcher for all the versions. */
21002 it_v = default_version_info;
21003 while (it_v != NULL)
21004 {
21005 it_v->dispatcher_resolver = dispatch_decl;
21006 it_v = it_v->next;
21007 }
21008 }
21009 else
21010 {
21011 error_at (DECL_SOURCE_LOCATION (default_node->decl),
21012 "multiversioning needs %<ifunc%> which is not supported "
21013 "on this target");
21014 }
21015
21016 return dispatch_decl;
21017 }
21018
21019 /* This function returns true if FN1 and FN2 are versions of the same function,
21020 that is, the target_version attributes of the function decls are different.
21021 This assumes that FN1 and FN2 have the same signature. */
21022
21023 bool
21024 aarch64_common_function_versions (tree fn1, tree fn2)
21025 {
21026 if (TREE_CODE (fn1) != FUNCTION_DECL
21027 || TREE_CODE (fn2) != FUNCTION_DECL)
21028 return false;
21029
21030 return (aarch64_compare_version_priority (fn1, fn2) != 0);
21031 }
21032
21033 /* Implement TARGET_FUNCTION_ATTRIBUTE_INLINABLE_P. Use an opt-out
21034 rather than an opt-in list. */
21035
21036 static bool
21037 aarch64_function_attribute_inlinable_p (const_tree fndecl)
21038 {
21039 /* A function that has local SME state cannot be inlined into its caller,
21040 since we only support managing PSTATE.ZA switches at function scope. */
21041 return (!aarch64_fndecl_has_new_state (fndecl, "za")
21042 && !aarch64_fndecl_has_new_state (fndecl, "zt0"));
21043 }
21044
21045 /* Helper for aarch64_can_inline_p. In the case where CALLER and CALLEE are
21046 tri-bool options (yes, no, don't care) and the default value is
21047 DEF, determine whether to reject inlining. */
21048
21049 static bool
21050 aarch64_tribools_ok_for_inlining_p (int caller, int callee,
21051 int dont_care, int def)
21052 {
21053 /* If the callee doesn't care, always allow inlining. */
21054 if (callee == dont_care)
21055 return true;
21056
21057 /* If the caller doesn't care, always allow inlining. */
21058 if (caller == dont_care)
21059 return true;
21060
21061 /* Otherwise, allow inlining if either the callee and caller values
21062 agree, or if the callee is using the default value. */
21063 return (callee == caller || callee == def);
21064 }
21065
21066 /* Bit allocations for ipa_fn_summary::target_info. */
21067
21068 /* Set if the function contains a stmt that relies on the function's
21069 choice of PSTATE.SM setting (0 for non-streaming, 1 for streaming).
21070 Not meaningful for streaming-compatible functions. */
21071 constexpr auto AARCH64_IPA_SM_FIXED = 1U << 0;
21072
21073 /* Set if the function clobbers ZA and ZT0. Not meaningful for functions that
21074 have ZA state. */
21075 constexpr auto AARCH64_IPA_CLOBBERS_ZA = 1U << 1;
21076 constexpr auto AARCH64_IPA_CLOBBERS_ZT0 = 1U << 2;
21077
21078 /* Implement TARGET_NEED_IPA_FN_TARGET_INFO. */
21079
21080 static bool
21081 aarch64_need_ipa_fn_target_info (const_tree, unsigned int &)
21082 {
21083 /* We could in principle skip this for streaming-compatible functions
21084 that have ZA state, but that's a rare combination. */
21085 return true;
21086 }
21087
21088 /* Implement TARGET_UPDATE_IPA_FN_TARGET_INFO. */
21089
21090 static bool
21091 aarch64_update_ipa_fn_target_info (unsigned int &info, const gimple *stmt)
21092 {
21093 if (auto *ga = dyn_cast<const gasm *> (stmt))
21094 {
21095 /* We don't know what the asm does, so conservatively assume that
21096 it requires the function's current SM mode. */
21097 info |= AARCH64_IPA_SM_FIXED;
21098 for (unsigned int i = 0; i < gimple_asm_nclobbers (ga); ++i)
21099 {
21100 tree op = gimple_asm_clobber_op (ga, i);
21101 const char *clobber = TREE_STRING_POINTER (TREE_VALUE (op));
21102 if (strcmp (clobber, "za") == 0)
21103 info |= AARCH64_IPA_CLOBBERS_ZA;
21104 if (strcmp (clobber, "zt0") == 0)
21105 info |= AARCH64_IPA_CLOBBERS_ZT0;
21106 }
21107 }
21108 if (auto *call = dyn_cast<const gcall *> (stmt))
21109 {
21110 if (gimple_call_builtin_p (call, BUILT_IN_MD))
21111 {
21112 /* The attributes on AArch64 builtins are supposed to be accurate.
21113 If the function isn't marked streaming-compatible then it
21114 needs whichever SM mode it selects. */
21115 tree decl = gimple_call_fndecl (call);
21116 if (aarch64_fndecl_pstate_sm (decl) != 0)
21117 info |= AARCH64_IPA_SM_FIXED;
21118 }
21119 }
21120 return true;
21121 }
21122
21123 /* Implement TARGET_CAN_INLINE_P. Decide whether it is valid
21124 to inline CALLEE into CALLER based on target-specific info.
21125 Make sure that the caller and callee have compatible architectural
21126 features. Then go through the other possible target attributes
21127 and see if they can block inlining. Try not to reject always_inline
21128 callees unless they are incompatible architecturally. */
21129
21130 static bool
21131 aarch64_can_inline_p (tree caller, tree callee)
21132 {
21133 tree caller_tree = DECL_FUNCTION_SPECIFIC_TARGET (caller);
21134 tree callee_tree = DECL_FUNCTION_SPECIFIC_TARGET (callee);
21135
21136 struct cl_target_option *caller_opts
21137 = TREE_TARGET_OPTION (caller_tree ? caller_tree
21138 : target_option_default_node);
21139
21140 struct cl_target_option *callee_opts
21141 = TREE_TARGET_OPTION (callee_tree ? callee_tree
21142 : target_option_default_node);
21143
21144 /* Callee's ISA flags should be a subset of the caller's. */
21145 auto caller_asm_isa = (aarch64_get_asm_isa_flags (caller_opts)
21146 & ~AARCH64_FL_ISA_MODES);
21147 auto callee_asm_isa = (aarch64_get_asm_isa_flags (callee_opts)
21148 & ~AARCH64_FL_ISA_MODES);
21149 if (callee_asm_isa & ~caller_asm_isa)
21150 return false;
21151
21152 auto caller_isa = (aarch64_get_isa_flags (caller_opts)
21153 & ~AARCH64_FL_ISA_MODES);
21154 auto callee_isa = (aarch64_get_isa_flags (callee_opts)
21155 & ~AARCH64_FL_ISA_MODES);
21156 if (callee_isa & ~caller_isa)
21157 return false;
21158
21159 /* Return true if the callee might have target_info property PROPERTY.
21160 The answer must be true unless we have positive proof to the contrary. */
21161 auto callee_has_property = [&](unsigned int property)
21162 {
21163 if (ipa_fn_summaries)
21164 if (auto *summary = ipa_fn_summaries->get (cgraph_node::get (callee)))
21165 if (!(summary->target_info & property))
21166 return false;
21167 return true;
21168 };
21169
21170 /* Streaming-compatible code can be inlined into functions with any
21171 PSTATE.SM mode. Otherwise the caller and callee must agree on
21172 PSTATE.SM mode, unless we can prove that the callee is naturally
21173 streaming-compatible. */
21174 auto caller_sm = (aarch64_get_isa_flags (caller_opts) & AARCH64_FL_SM_STATE);
21175 auto callee_sm = (aarch64_get_isa_flags (callee_opts) & AARCH64_FL_SM_STATE);
21176 if (callee_sm
21177 && caller_sm != callee_sm
21178 && callee_has_property (AARCH64_IPA_SM_FIXED))
21179 return false;
21180
21181 /* aarch64_function_attribute_inlinable_p prevents new-ZA and new-ZT0
21182 functions from being inlined into others. We also need to prevent
21183 inlining of shared-ZA functions into functions without ZA state,
21184 since this is an error condition.
21185
21186 The only other problematic case for ZA is inlining a function that
21187 directly clobbers ZA or ZT0 into a function that has ZA or ZT0 state. */
21188 auto caller_za = (aarch64_get_isa_flags (caller_opts) & AARCH64_FL_ZA_ON);
21189 auto callee_za = (aarch64_get_isa_flags (callee_opts) & AARCH64_FL_ZA_ON);
21190 if (!caller_za && callee_za)
21191 return false;
21192 if (!callee_za
21193 && aarch64_fndecl_has_state (caller, "za")
21194 && callee_has_property (AARCH64_IPA_CLOBBERS_ZA))
21195 return false;
21196 if (!callee_za
21197 && aarch64_fndecl_has_state (caller, "zt0")
21198 && callee_has_property (AARCH64_IPA_CLOBBERS_ZT0))
21199 return false;
21200
21201 /* Allow non-strict aligned functions inlining into strict
21202 aligned ones. */
21203 if ((TARGET_STRICT_ALIGN_P (caller_opts->x_target_flags)
21204 != TARGET_STRICT_ALIGN_P (callee_opts->x_target_flags))
21205 && !(!TARGET_STRICT_ALIGN_P (callee_opts->x_target_flags)
21206 && TARGET_STRICT_ALIGN_P (caller_opts->x_target_flags)))
21207 return false;
21208
21209 bool always_inline = lookup_attribute ("always_inline",
21210 DECL_ATTRIBUTES (callee));
21211
21212 /* If the architectural features match up and the callee is always_inline
21213 then the other attributes don't matter. */
21214 if (always_inline)
21215 return true;
21216
21217 if (caller_opts->x_aarch64_cmodel_var
21218 != callee_opts->x_aarch64_cmodel_var)
21219 return false;
21220
21221 if (caller_opts->x_aarch64_tls_dialect
21222 != callee_opts->x_aarch64_tls_dialect)
21223 return false;
21224
21225 /* Honour explicit requests to workaround errata. */
21226 if (!aarch64_tribools_ok_for_inlining_p (
21227 caller_opts->x_aarch64_fix_a53_err835769,
21228 callee_opts->x_aarch64_fix_a53_err835769,
21229 2, TARGET_FIX_ERR_A53_835769_DEFAULT))
21230 return false;
21231
21232 if (!aarch64_tribools_ok_for_inlining_p (
21233 caller_opts->x_aarch64_fix_a53_err843419,
21234 callee_opts->x_aarch64_fix_a53_err843419,
21235 2, TARGET_FIX_ERR_A53_843419))
21236 return false;
21237
21238 /* If the user explicitly specified -momit-leaf-frame-pointer for the
21239 caller and calle and they don't match up, reject inlining. */
21240 if (!aarch64_tribools_ok_for_inlining_p (
21241 caller_opts->x_flag_omit_leaf_frame_pointer,
21242 callee_opts->x_flag_omit_leaf_frame_pointer,
21243 2, 1))
21244 return false;
21245
21246 /* If the callee has specific tuning overrides, respect them. */
21247 if (callee_opts->x_aarch64_override_tune_string != NULL
21248 && caller_opts->x_aarch64_override_tune_string == NULL)
21249 return false;
21250
21251 /* If the user specified tuning override strings for the
21252 caller and callee and they don't match up, reject inlining.
21253 We just do a string compare here, we don't analyze the meaning
21254 of the string, as it would be too costly for little gain. */
21255 if (callee_opts->x_aarch64_override_tune_string
21256 && caller_opts->x_aarch64_override_tune_string
21257 && (strcmp (callee_opts->x_aarch64_override_tune_string,
21258 caller_opts->x_aarch64_override_tune_string) != 0))
21259 return false;
21260
21261 return true;
21262 }
21263
21264 /* Return the ID of the TLDESC ABI, initializing the descriptor if hasn't
21265 been already. */
21266
21267 arm_pcs
21268 aarch64_tlsdesc_abi_id ()
21269 {
21270 predefined_function_abi &tlsdesc_abi = function_abis[ARM_PCS_TLSDESC];
21271 if (!tlsdesc_abi.initialized_p ())
21272 {
21273 HARD_REG_SET full_reg_clobbers;
21274 CLEAR_HARD_REG_SET (full_reg_clobbers);
21275 SET_HARD_REG_BIT (full_reg_clobbers, R0_REGNUM);
21276 SET_HARD_REG_BIT (full_reg_clobbers, CC_REGNUM);
21277 for (int regno = P0_REGNUM; regno <= P15_REGNUM; ++regno)
21278 SET_HARD_REG_BIT (full_reg_clobbers, regno);
21279 tlsdesc_abi.initialize (ARM_PCS_TLSDESC, full_reg_clobbers);
21280 }
21281 return ARM_PCS_TLSDESC;
21282 }
21283
21284 /* Return true if SYMBOL_REF X binds locally. */
21285
21286 static bool
21287 aarch64_symbol_binds_local_p (const_rtx x)
21288 {
21289 return (SYMBOL_REF_DECL (x)
21290 ? targetm.binds_local_p (SYMBOL_REF_DECL (x))
21291 : SYMBOL_REF_LOCAL_P (x));
21292 }
21293
21294 /* Return true if SYMBOL_REF X is thread local */
21295 static bool
21296 aarch64_tls_symbol_p (rtx x)
21297 {
21298 if (! TARGET_HAVE_TLS)
21299 return false;
21300
21301 x = strip_salt (x);
21302 if (!SYMBOL_REF_P (x))
21303 return false;
21304
21305 return SYMBOL_REF_TLS_MODEL (x) != 0;
21306 }
21307
21308 /* Classify a TLS symbol into one of the TLS kinds. */
21309 enum aarch64_symbol_type
21310 aarch64_classify_tls_symbol (rtx x)
21311 {
21312 enum tls_model tls_kind = tls_symbolic_operand_type (x);
21313
21314 switch (tls_kind)
21315 {
21316 case TLS_MODEL_GLOBAL_DYNAMIC:
21317 case TLS_MODEL_LOCAL_DYNAMIC:
21318 return TARGET_TLS_DESC ? SYMBOL_SMALL_TLSDESC : SYMBOL_SMALL_TLSGD;
21319
21320 case TLS_MODEL_INITIAL_EXEC:
21321 switch (aarch64_cmodel)
21322 {
21323 case AARCH64_CMODEL_TINY:
21324 case AARCH64_CMODEL_TINY_PIC:
21325 return SYMBOL_TINY_TLSIE;
21326 default:
21327 return SYMBOL_SMALL_TLSIE;
21328 }
21329
21330 case TLS_MODEL_LOCAL_EXEC:
21331 if (aarch64_tls_size == 12)
21332 return SYMBOL_TLSLE12;
21333 else if (aarch64_tls_size == 24)
21334 return SYMBOL_TLSLE24;
21335 else if (aarch64_tls_size == 32)
21336 return SYMBOL_TLSLE32;
21337 else if (aarch64_tls_size == 48)
21338 return SYMBOL_TLSLE48;
21339 else
21340 gcc_unreachable ();
21341
21342 case TLS_MODEL_EMULATED:
21343 case TLS_MODEL_NONE:
21344 return SYMBOL_FORCE_TO_MEM;
21345
21346 default:
21347 gcc_unreachable ();
21348 }
21349 }
21350
21351 /* Return the correct method for accessing X + OFFSET, where X is either
21352 a SYMBOL_REF or LABEL_REF. */
21353
21354 enum aarch64_symbol_type
21355 aarch64_classify_symbol (rtx x, HOST_WIDE_INT offset)
21356 {
21357 x = strip_salt (x);
21358
21359 if (LABEL_REF_P (x))
21360 {
21361 switch (aarch64_cmodel)
21362 {
21363 case AARCH64_CMODEL_LARGE:
21364 return SYMBOL_FORCE_TO_MEM;
21365
21366 case AARCH64_CMODEL_TINY_PIC:
21367 case AARCH64_CMODEL_TINY:
21368 return SYMBOL_TINY_ABSOLUTE;
21369
21370 case AARCH64_CMODEL_SMALL_SPIC:
21371 case AARCH64_CMODEL_SMALL_PIC:
21372 case AARCH64_CMODEL_SMALL:
21373 return SYMBOL_SMALL_ABSOLUTE;
21374
21375 default:
21376 gcc_unreachable ();
21377 }
21378 }
21379
21380 if (SYMBOL_REF_P (x))
21381 {
21382 if (aarch64_tls_symbol_p (x))
21383 return aarch64_classify_tls_symbol (x);
21384
21385 switch (aarch64_cmodel)
21386 {
21387 case AARCH64_CMODEL_TINY_PIC:
21388 case AARCH64_CMODEL_TINY:
21389 /* With -fPIC non-local symbols use the GOT. For orthogonality
21390 always use the GOT for extern weak symbols. */
21391 if (!TARGET_PECOFF
21392 && (flag_pic || SYMBOL_REF_WEAK (x))
21393 && !aarch64_symbol_binds_local_p (x))
21394 return SYMBOL_TINY_GOT;
21395
21396 /* When we retrieve symbol + offset address, we have to make sure
21397 the offset does not cause overflow of the final address. But
21398 we have no way of knowing the address of symbol at compile time
21399 so we can't accurately say if the distance between the PC and
21400 symbol + offset is outside the addressible range of +/-1MB in the
21401 TINY code model. So we limit the maximum offset to +/-64KB and
21402 assume the offset to the symbol is not larger than +/-(1MB - 64KB).
21403 If offset_within_block_p is true we allow larger offsets. */
21404 if (!(IN_RANGE (offset, -0x10000, 0x10000)
21405 || offset_within_block_p (x, offset)))
21406 return SYMBOL_FORCE_TO_MEM;
21407
21408 return SYMBOL_TINY_ABSOLUTE;
21409
21410
21411 case AARCH64_CMODEL_SMALL_SPIC:
21412 case AARCH64_CMODEL_SMALL_PIC:
21413 case AARCH64_CMODEL_SMALL:
21414 if (!TARGET_PECOFF
21415 && (flag_pic || SYMBOL_REF_WEAK (x))
21416 && !aarch64_symbol_binds_local_p (x))
21417 return aarch64_cmodel == AARCH64_CMODEL_SMALL_SPIC
21418 ? SYMBOL_SMALL_GOT_28K : SYMBOL_SMALL_GOT_4G;
21419
21420 /* Same reasoning as the tiny code model, but the offset cap here is
21421 1MB, allowing +/-3.9GB for the offset to the symbol. */
21422 if (!(IN_RANGE (offset, -0x100000, 0x100000)
21423 || offset_within_block_p (x, offset)))
21424 return SYMBOL_FORCE_TO_MEM;
21425
21426 return SYMBOL_SMALL_ABSOLUTE;
21427
21428 case AARCH64_CMODEL_LARGE:
21429 /* This is alright even in PIC code as the constant
21430 pool reference is always PC relative and within
21431 the same translation unit. */
21432 if (!aarch64_pcrelative_literal_loads && CONSTANT_POOL_ADDRESS_P (x))
21433 return SYMBOL_SMALL_ABSOLUTE;
21434 else
21435 return SYMBOL_FORCE_TO_MEM;
21436
21437 default:
21438 gcc_unreachable ();
21439 }
21440 }
21441
21442 /* By default push everything into the constant pool. */
21443 return SYMBOL_FORCE_TO_MEM;
21444 }
21445
21446 bool
21447 aarch64_constant_address_p (rtx x)
21448 {
21449 return (CONSTANT_P (x) && memory_address_p (DImode, x));
21450 }
21451
21452 bool
21453 aarch64_legitimate_pic_operand_p (rtx x)
21454 {
21455 poly_int64 offset;
21456 x = strip_offset_and_salt (x, &offset);
21457 if (SYMBOL_REF_P (x))
21458 return false;
21459
21460 return true;
21461 }
21462
21463 /* Implement TARGET_LEGITIMATE_CONSTANT_P hook. Return true for constants
21464 that should be rematerialized rather than spilled. */
21465
21466 static bool
21467 aarch64_legitimate_constant_p (machine_mode mode, rtx x)
21468 {
21469 /* Support CSE and rematerialization of common constants. */
21470 if (CONST_INT_P (x)
21471 || CONST_DOUBLE_P (x))
21472 return true;
21473
21474 /* Only accept variable-length vector constants if they can be
21475 handled directly.
21476
21477 ??? It would be possible (but complex) to handle rematerialization
21478 of other constants via secondary reloads. */
21479 if (!GET_MODE_SIZE (mode).is_constant ())
21480 return aarch64_simd_valid_mov_imm (x);
21481
21482 /* Otherwise, accept any CONST_VECTOR that, if all else fails, can at
21483 least be forced to memory and loaded from there. */
21484 if (CONST_VECTOR_P (x))
21485 return !targetm.cannot_force_const_mem (mode, x);
21486
21487 /* Do not allow vector struct mode constants for Advanced SIMD.
21488 We could support 0 and -1 easily, but they need support in
21489 aarch64-simd.md. */
21490 unsigned int vec_flags = aarch64_classify_vector_mode (mode);
21491 if (vec_flags == (VEC_ADVSIMD | VEC_STRUCT))
21492 return false;
21493
21494 if (GET_CODE (x) == HIGH)
21495 x = XEXP (x, 0);
21496
21497 /* Accept polynomial constants that can be calculated by using the
21498 destination of a move as the sole temporary. Constants that
21499 require a second temporary cannot be rematerialized (they can't be
21500 forced to memory and also aren't legitimate constants). */
21501 poly_int64 offset;
21502 if (poly_int_rtx_p (x, &offset))
21503 return aarch64_offset_temporaries (false, offset) <= 1;
21504
21505 /* If an offset is being added to something else, we need to allow the
21506 base to be moved into the destination register, meaning that there
21507 are no free temporaries for the offset. */
21508 x = strip_offset_and_salt (x, &offset);
21509 if (!offset.is_constant () && aarch64_offset_temporaries (true, offset) > 0)
21510 return false;
21511
21512 /* Do not allow const (plus (anchor_symbol, const_int)). */
21513 if (maybe_ne (offset, 0) && SYMBOL_REF_P (x) && SYMBOL_REF_ANCHOR_P (x))
21514 return false;
21515
21516 /* Treat symbols as constants. Avoid TLS symbols as they are complex,
21517 so spilling them is better than rematerialization. */
21518 if (SYMBOL_REF_P (x) && !SYMBOL_REF_TLS_MODEL (x))
21519 return true;
21520
21521 /* Label references are always constant. */
21522 if (LABEL_REF_P (x))
21523 return true;
21524
21525 return false;
21526 }
21527
21528 rtx
21529 aarch64_load_tp (rtx target)
21530 {
21531 if (!target
21532 || GET_MODE (target) != Pmode
21533 || !register_operand (target, Pmode))
21534 target = gen_reg_rtx (Pmode);
21535
21536 /* Can return in any reg. */
21537 emit_insn (gen_aarch64_load_tp_hard (target));
21538 return target;
21539 }
21540
21541 /* On AAPCS systems, this is the "struct __va_list". */
21542 static GTY(()) tree va_list_type;
21543
21544 /* Implement TARGET_BUILD_BUILTIN_VA_LIST.
21545 Return the type to use as __builtin_va_list.
21546
21547 AAPCS64 \S 7.1.4 requires that va_list be a typedef for a type defined as:
21548
21549 struct __va_list
21550 {
21551 void *__stack;
21552 void *__gr_top;
21553 void *__vr_top;
21554 int __gr_offs;
21555 int __vr_offs;
21556 }; */
21557
21558 static tree
21559 aarch64_build_builtin_va_list (void)
21560 {
21561 tree va_list_name;
21562 tree f_stack, f_grtop, f_vrtop, f_groff, f_vroff;
21563
21564 /* Create the type. */
21565 va_list_type = lang_hooks.types.make_type (RECORD_TYPE);
21566 /* Give it the required name. */
21567 va_list_name = build_decl (BUILTINS_LOCATION,
21568 TYPE_DECL,
21569 get_identifier ("__va_list"),
21570 va_list_type);
21571 DECL_ARTIFICIAL (va_list_name) = 1;
21572 TREE_PUBLIC (va_list_name) = 1;
21573 TYPE_NAME (va_list_type) = va_list_name;
21574 TYPE_STUB_DECL (va_list_type) = va_list_name;
21575
21576 /* Create the fields. */
21577 f_stack = build_decl (BUILTINS_LOCATION,
21578 FIELD_DECL, get_identifier ("__stack"),
21579 ptr_type_node);
21580 f_grtop = build_decl (BUILTINS_LOCATION,
21581 FIELD_DECL, get_identifier ("__gr_top"),
21582 ptr_type_node);
21583 f_vrtop = build_decl (BUILTINS_LOCATION,
21584 FIELD_DECL, get_identifier ("__vr_top"),
21585 ptr_type_node);
21586 f_groff = build_decl (BUILTINS_LOCATION,
21587 FIELD_DECL, get_identifier ("__gr_offs"),
21588 integer_type_node);
21589 f_vroff = build_decl (BUILTINS_LOCATION,
21590 FIELD_DECL, get_identifier ("__vr_offs"),
21591 integer_type_node);
21592
21593 /* Tell tree-stdarg pass about our internal offset fields.
21594 NOTE: va_list_gpr/fpr_counter_field are only used for tree comparision
21595 purpose to identify whether the code is updating va_list internal
21596 offset fields through irregular way. */
21597 va_list_gpr_counter_field = f_groff;
21598 va_list_fpr_counter_field = f_vroff;
21599
21600 DECL_ARTIFICIAL (f_stack) = 1;
21601 DECL_ARTIFICIAL (f_grtop) = 1;
21602 DECL_ARTIFICIAL (f_vrtop) = 1;
21603 DECL_ARTIFICIAL (f_groff) = 1;
21604 DECL_ARTIFICIAL (f_vroff) = 1;
21605
21606 DECL_FIELD_CONTEXT (f_stack) = va_list_type;
21607 DECL_FIELD_CONTEXT (f_grtop) = va_list_type;
21608 DECL_FIELD_CONTEXT (f_vrtop) = va_list_type;
21609 DECL_FIELD_CONTEXT (f_groff) = va_list_type;
21610 DECL_FIELD_CONTEXT (f_vroff) = va_list_type;
21611
21612 TYPE_FIELDS (va_list_type) = f_stack;
21613 DECL_CHAIN (f_stack) = f_grtop;
21614 DECL_CHAIN (f_grtop) = f_vrtop;
21615 DECL_CHAIN (f_vrtop) = f_groff;
21616 DECL_CHAIN (f_groff) = f_vroff;
21617
21618 /* Compute its layout. */
21619 layout_type (va_list_type);
21620
21621 return va_list_type;
21622 }
21623
21624 /* Implement TARGET_EXPAND_BUILTIN_VA_START. */
21625 static void
21626 aarch64_expand_builtin_va_start (tree valist, rtx nextarg ATTRIBUTE_UNUSED)
21627 {
21628 const CUMULATIVE_ARGS *cum;
21629 tree f_stack, f_grtop, f_vrtop, f_groff, f_vroff;
21630 tree stack, grtop, vrtop, groff, vroff;
21631 tree t;
21632 int gr_save_area_size = cfun->va_list_gpr_size;
21633 int vr_save_area_size = cfun->va_list_fpr_size;
21634 int vr_offset;
21635
21636 cum = &crtl->args.info;
21637 if (cfun->va_list_gpr_size)
21638 gr_save_area_size = MIN ((NUM_ARG_REGS - cum->aapcs_ncrn) * UNITS_PER_WORD,
21639 cfun->va_list_gpr_size);
21640 if (cfun->va_list_fpr_size)
21641 vr_save_area_size = MIN ((NUM_FP_ARG_REGS - cum->aapcs_nvrn)
21642 * UNITS_PER_VREG, cfun->va_list_fpr_size);
21643
21644 if (!TARGET_FLOAT)
21645 {
21646 gcc_assert (cum->aapcs_nvrn == 0);
21647 vr_save_area_size = 0;
21648 }
21649
21650 f_stack = TYPE_FIELDS (va_list_type_node);
21651 f_grtop = DECL_CHAIN (f_stack);
21652 f_vrtop = DECL_CHAIN (f_grtop);
21653 f_groff = DECL_CHAIN (f_vrtop);
21654 f_vroff = DECL_CHAIN (f_groff);
21655
21656 stack = build3 (COMPONENT_REF, TREE_TYPE (f_stack), valist, f_stack,
21657 NULL_TREE);
21658 grtop = build3 (COMPONENT_REF, TREE_TYPE (f_grtop), valist, f_grtop,
21659 NULL_TREE);
21660 vrtop = build3 (COMPONENT_REF, TREE_TYPE (f_vrtop), valist, f_vrtop,
21661 NULL_TREE);
21662 groff = build3 (COMPONENT_REF, TREE_TYPE (f_groff), valist, f_groff,
21663 NULL_TREE);
21664 vroff = build3 (COMPONENT_REF, TREE_TYPE (f_vroff), valist, f_vroff,
21665 NULL_TREE);
21666
21667 /* Emit code to initialize STACK, which points to the next varargs stack
21668 argument. CUM->AAPCS_STACK_SIZE gives the number of stack words used
21669 by named arguments. STACK is 8-byte aligned. */
21670 t = make_tree (TREE_TYPE (stack), virtual_incoming_args_rtx);
21671 if (cum->aapcs_stack_size > 0)
21672 t = fold_build_pointer_plus_hwi (t, cum->aapcs_stack_size * UNITS_PER_WORD);
21673 t = build2 (MODIFY_EXPR, TREE_TYPE (stack), stack, t);
21674 expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
21675
21676 /* Emit code to initialize GRTOP, the top of the GR save area.
21677 virtual_incoming_args_rtx should have been 16 byte aligned. */
21678 t = make_tree (TREE_TYPE (grtop), virtual_incoming_args_rtx);
21679 t = build2 (MODIFY_EXPR, TREE_TYPE (grtop), grtop, t);
21680 expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
21681
21682 /* Emit code to initialize VRTOP, the top of the VR save area.
21683 This address is gr_save_area_bytes below GRTOP, rounded
21684 down to the next 16-byte boundary. */
21685 t = make_tree (TREE_TYPE (vrtop), virtual_incoming_args_rtx);
21686 vr_offset = ROUND_UP (gr_save_area_size,
21687 STACK_BOUNDARY / BITS_PER_UNIT);
21688
21689 if (vr_offset)
21690 t = fold_build_pointer_plus_hwi (t, -vr_offset);
21691 t = build2 (MODIFY_EXPR, TREE_TYPE (vrtop), vrtop, t);
21692 expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
21693
21694 /* Emit code to initialize GROFF, the offset from GRTOP of the
21695 next GPR argument. */
21696 t = build2 (MODIFY_EXPR, TREE_TYPE (groff), groff,
21697 build_int_cst (TREE_TYPE (groff), -gr_save_area_size));
21698 expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
21699
21700 /* Likewise emit code to initialize VROFF, the offset from FTOP
21701 of the next VR argument. */
21702 t = build2 (MODIFY_EXPR, TREE_TYPE (vroff), vroff,
21703 build_int_cst (TREE_TYPE (vroff), -vr_save_area_size));
21704 expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
21705 }
21706
21707 /* Implement TARGET_GIMPLIFY_VA_ARG_EXPR. */
21708
21709 static tree
21710 aarch64_gimplify_va_arg_expr (tree valist, tree type, gimple_seq *pre_p,
21711 gimple_seq *post_p ATTRIBUTE_UNUSED)
21712 {
21713 tree addr;
21714 bool indirect_p;
21715 bool is_ha; /* is HFA or HVA. */
21716 bool dw_align; /* double-word align. */
21717 machine_mode ag_mode = VOIDmode;
21718 int nregs;
21719 machine_mode mode;
21720
21721 tree f_stack, f_grtop, f_vrtop, f_groff, f_vroff;
21722 tree stack, f_top, f_off, off, arg, roundup, on_stack;
21723 HOST_WIDE_INT size, rsize, adjust, align;
21724 tree t, u, cond1, cond2;
21725
21726 indirect_p = pass_va_arg_by_reference (type);
21727 if (indirect_p)
21728 type = build_pointer_type (type);
21729
21730 mode = TYPE_MODE (type);
21731
21732 f_stack = TYPE_FIELDS (va_list_type_node);
21733 f_grtop = DECL_CHAIN (f_stack);
21734 f_vrtop = DECL_CHAIN (f_grtop);
21735 f_groff = DECL_CHAIN (f_vrtop);
21736 f_vroff = DECL_CHAIN (f_groff);
21737
21738 stack = build3 (COMPONENT_REF, TREE_TYPE (f_stack), unshare_expr (valist),
21739 f_stack, NULL_TREE);
21740 size = int_size_in_bytes (type);
21741
21742 unsigned int abi_break_gcc_9;
21743 unsigned int abi_break_gcc_13;
21744 unsigned int abi_break_gcc_14;
21745 align
21746 = aarch64_function_arg_alignment (mode, type, &abi_break_gcc_9,
21747 &abi_break_gcc_13, &abi_break_gcc_14)
21748 / BITS_PER_UNIT;
21749
21750 dw_align = false;
21751 adjust = 0;
21752 if (aarch64_vfp_is_call_or_return_candidate (mode, type, &ag_mode, &nregs,
21753 &is_ha, false))
21754 {
21755 /* No frontends can create types with variable-sized modes, so we
21756 shouldn't be asked to pass or return them. */
21757 unsigned int ag_size = GET_MODE_SIZE (ag_mode).to_constant ();
21758
21759 /* TYPE passed in fp/simd registers. */
21760 if (!TARGET_FLOAT)
21761 aarch64_err_no_fpadvsimd (mode);
21762
21763 f_top = build3 (COMPONENT_REF, TREE_TYPE (f_vrtop),
21764 unshare_expr (valist), f_vrtop, NULL_TREE);
21765 f_off = build3 (COMPONENT_REF, TREE_TYPE (f_vroff),
21766 unshare_expr (valist), f_vroff, NULL_TREE);
21767
21768 rsize = nregs * UNITS_PER_VREG;
21769
21770 if (is_ha)
21771 {
21772 if (BYTES_BIG_ENDIAN && ag_size < UNITS_PER_VREG)
21773 adjust = UNITS_PER_VREG - ag_size;
21774 }
21775 else if (BLOCK_REG_PADDING (mode, type, 1) == PAD_DOWNWARD
21776 && size < UNITS_PER_VREG)
21777 {
21778 adjust = UNITS_PER_VREG - size;
21779 }
21780 }
21781 else
21782 {
21783 /* TYPE passed in general registers. */
21784 f_top = build3 (COMPONENT_REF, TREE_TYPE (f_grtop),
21785 unshare_expr (valist), f_grtop, NULL_TREE);
21786 f_off = build3 (COMPONENT_REF, TREE_TYPE (f_groff),
21787 unshare_expr (valist), f_groff, NULL_TREE);
21788 rsize = ROUND_UP (size, UNITS_PER_WORD);
21789 nregs = rsize / UNITS_PER_WORD;
21790
21791 if (align <= 8
21792 && abi_break_gcc_13
21793 && warn_psabi
21794 && !bitint_or_aggr_of_bitint_p (type))
21795 inform (input_location, "parameter passing for argument of type "
21796 "%qT changed in GCC 13.1", type);
21797
21798 if (warn_psabi
21799 && abi_break_gcc_14
21800 && (abi_break_gcc_14 > 8 * BITS_PER_UNIT) != (align > 8)
21801 && !bitint_or_aggr_of_bitint_p (type))
21802 inform (input_location, "parameter passing for argument of type "
21803 "%qT changed in GCC 14.1", type);
21804
21805 if (align > 8)
21806 {
21807 if (abi_break_gcc_9
21808 && warn_psabi
21809 && !bitint_or_aggr_of_bitint_p (type))
21810 inform (input_location, "parameter passing for argument of type "
21811 "%qT changed in GCC 9.1", type);
21812 dw_align = true;
21813 }
21814
21815 if (BLOCK_REG_PADDING (mode, type, 1) == PAD_DOWNWARD
21816 && size < UNITS_PER_WORD)
21817 {
21818 adjust = UNITS_PER_WORD - size;
21819 }
21820 }
21821
21822 /* Get a local temporary for the field value. */
21823 off = get_initialized_tmp_var (f_off, pre_p, NULL);
21824
21825 /* Emit code to branch if off >= 0. */
21826 t = build2 (GE_EXPR, boolean_type_node, off,
21827 build_int_cst (TREE_TYPE (off), 0));
21828 cond1 = build3 (COND_EXPR, ptr_type_node, t, NULL_TREE, NULL_TREE);
21829
21830 if (dw_align)
21831 {
21832 /* Emit: offs = (offs + 15) & -16. */
21833 t = build2 (PLUS_EXPR, TREE_TYPE (off), off,
21834 build_int_cst (TREE_TYPE (off), 15));
21835 t = build2 (BIT_AND_EXPR, TREE_TYPE (off), t,
21836 build_int_cst (TREE_TYPE (off), -16));
21837 roundup = build2 (MODIFY_EXPR, TREE_TYPE (off), off, t);
21838 }
21839 else
21840 roundup = NULL;
21841
21842 /* Update ap.__[g|v]r_offs */
21843 t = build2 (PLUS_EXPR, TREE_TYPE (off), off,
21844 build_int_cst (TREE_TYPE (off), rsize));
21845 t = build2 (MODIFY_EXPR, TREE_TYPE (f_off), unshare_expr (f_off), t);
21846
21847 /* String up. */
21848 if (roundup)
21849 t = build2 (COMPOUND_EXPR, TREE_TYPE (t), roundup, t);
21850
21851 /* [cond2] if (ap.__[g|v]r_offs > 0) */
21852 u = build2 (GT_EXPR, boolean_type_node, unshare_expr (f_off),
21853 build_int_cst (TREE_TYPE (f_off), 0));
21854 cond2 = build3 (COND_EXPR, ptr_type_node, u, NULL_TREE, NULL_TREE);
21855
21856 /* String up: make sure the assignment happens before the use. */
21857 t = build2 (COMPOUND_EXPR, TREE_TYPE (cond2), t, cond2);
21858 COND_EXPR_ELSE (cond1) = t;
21859
21860 /* Prepare the trees handling the argument that is passed on the stack;
21861 the top level node will store in ON_STACK. */
21862 arg = get_initialized_tmp_var (stack, pre_p, NULL);
21863 if (align > 8)
21864 {
21865 /* if (alignof(type) > 8) (arg = arg + 15) & -16; */
21866 t = fold_build_pointer_plus_hwi (arg, 15);
21867 t = build2 (BIT_AND_EXPR, TREE_TYPE (t), t,
21868 build_int_cst (TREE_TYPE (t), -16));
21869 roundup = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg, t);
21870 }
21871 else
21872 roundup = NULL;
21873 /* Advance ap.__stack */
21874 t = fold_build_pointer_plus_hwi (arg, size + 7);
21875 t = build2 (BIT_AND_EXPR, TREE_TYPE (t), t,
21876 build_int_cst (TREE_TYPE (t), -8));
21877 t = build2 (MODIFY_EXPR, TREE_TYPE (stack), unshare_expr (stack), t);
21878 /* String up roundup and advance. */
21879 if (roundup)
21880 t = build2 (COMPOUND_EXPR, TREE_TYPE (t), roundup, t);
21881 /* String up with arg */
21882 on_stack = build2 (COMPOUND_EXPR, TREE_TYPE (arg), t, arg);
21883 /* Big-endianness related address adjustment. */
21884 if (BLOCK_REG_PADDING (mode, type, 1) == PAD_DOWNWARD
21885 && size < UNITS_PER_WORD)
21886 {
21887 t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (arg), arg,
21888 size_int (UNITS_PER_WORD - size));
21889 on_stack = build2 (COMPOUND_EXPR, TREE_TYPE (arg), on_stack, t);
21890 }
21891
21892 COND_EXPR_THEN (cond1) = unshare_expr (on_stack);
21893 COND_EXPR_THEN (cond2) = unshare_expr (on_stack);
21894
21895 /* Adjustment to OFFSET in the case of BIG_ENDIAN. */
21896 t = off;
21897 if (adjust)
21898 t = build2 (PREINCREMENT_EXPR, TREE_TYPE (off), off,
21899 build_int_cst (TREE_TYPE (off), adjust));
21900
21901 t = fold_convert (sizetype, t);
21902 t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (f_top), f_top, t);
21903
21904 if (is_ha)
21905 {
21906 /* type ha; // treat as "struct {ftype field[n];}"
21907 ... [computing offs]
21908 for (i = 0; i <nregs; ++i, offs += 16)
21909 ha.field[i] = *((ftype *)(ap.__vr_top + offs));
21910 return ha; */
21911 int i;
21912 tree tmp_ha, field_t, field_ptr_t;
21913
21914 /* Declare a local variable. */
21915 tmp_ha = create_tmp_var_raw (type, "ha");
21916 gimple_add_tmp_var (tmp_ha);
21917
21918 /* Establish the base type. */
21919 switch (ag_mode)
21920 {
21921 case E_SFmode:
21922 field_t = float_type_node;
21923 field_ptr_t = float_ptr_type_node;
21924 break;
21925 case E_DFmode:
21926 field_t = double_type_node;
21927 field_ptr_t = double_ptr_type_node;
21928 break;
21929 case E_TFmode:
21930 field_t = long_double_type_node;
21931 field_ptr_t = long_double_ptr_type_node;
21932 break;
21933 case E_SDmode:
21934 field_t = dfloat32_type_node;
21935 field_ptr_t = build_pointer_type (dfloat32_type_node);
21936 break;
21937 case E_DDmode:
21938 field_t = dfloat64_type_node;
21939 field_ptr_t = build_pointer_type (dfloat64_type_node);
21940 break;
21941 case E_TDmode:
21942 field_t = dfloat128_type_node;
21943 field_ptr_t = build_pointer_type (dfloat128_type_node);
21944 break;
21945 case E_HFmode:
21946 field_t = aarch64_fp16_type_node;
21947 field_ptr_t = aarch64_fp16_ptr_type_node;
21948 break;
21949 case E_BFmode:
21950 field_t = bfloat16_type_node;
21951 field_ptr_t = aarch64_bf16_ptr_type_node;
21952 break;
21953 case E_V2SImode:
21954 case E_V4SImode:
21955 {
21956 tree innertype = make_signed_type (GET_MODE_PRECISION (SImode));
21957 field_t = build_vector_type_for_mode (innertype, ag_mode);
21958 field_ptr_t = build_pointer_type (field_t);
21959 }
21960 break;
21961 default:
21962 gcc_assert (0);
21963 }
21964
21965 /* *(field_ptr_t)&ha = *((field_ptr_t)vr_saved_area */
21966 TREE_ADDRESSABLE (tmp_ha) = 1;
21967 tmp_ha = build1 (ADDR_EXPR, field_ptr_t, tmp_ha);
21968 addr = t;
21969 t = fold_convert (field_ptr_t, addr);
21970 t = build2 (MODIFY_EXPR, field_t,
21971 build1 (INDIRECT_REF, field_t, tmp_ha),
21972 build1 (INDIRECT_REF, field_t, t));
21973
21974 /* ha.field[i] = *((field_ptr_t)vr_saved_area + i) */
21975 for (i = 1; i < nregs; ++i)
21976 {
21977 addr = fold_build_pointer_plus_hwi (addr, UNITS_PER_VREG);
21978 u = fold_convert (field_ptr_t, addr);
21979 u = build2 (MODIFY_EXPR, field_t,
21980 build2 (MEM_REF, field_t, tmp_ha,
21981 build_int_cst (field_ptr_t,
21982 (i *
21983 int_size_in_bytes (field_t)))),
21984 build1 (INDIRECT_REF, field_t, u));
21985 t = build2 (COMPOUND_EXPR, TREE_TYPE (t), t, u);
21986 }
21987
21988 u = fold_convert (TREE_TYPE (f_top), tmp_ha);
21989 t = build2 (COMPOUND_EXPR, TREE_TYPE (f_top), t, u);
21990 }
21991
21992 COND_EXPR_ELSE (cond2) = t;
21993 addr = fold_convert (build_pointer_type (type), cond1);
21994 addr = build_va_arg_indirect_ref (addr);
21995
21996 if (indirect_p)
21997 addr = build_va_arg_indirect_ref (addr);
21998
21999 return addr;
22000 }
22001
22002 /* Implement TARGET_SETUP_INCOMING_VARARGS. */
22003
22004 static void
22005 aarch64_setup_incoming_varargs (cumulative_args_t cum_v,
22006 const function_arg_info &arg,
22007 int *pretend_size ATTRIBUTE_UNUSED, int no_rtl)
22008 {
22009 CUMULATIVE_ARGS *cum = get_cumulative_args (cum_v);
22010 CUMULATIVE_ARGS local_cum;
22011 int gr_saved = cfun->va_list_gpr_size;
22012 int vr_saved = cfun->va_list_fpr_size;
22013
22014 /* The caller has advanced CUM up to, but not beyond, the last named
22015 argument. Advance a local copy of CUM past the last "real" named
22016 argument, to find out how many registers are left over. */
22017 local_cum = *cum;
22018 if (!TYPE_NO_NAMED_ARGS_STDARG_P (TREE_TYPE (current_function_decl)))
22019 aarch64_function_arg_advance (pack_cumulative_args(&local_cum), arg);
22020
22021 /* Found out how many registers we need to save.
22022 Honor tree-stdvar analysis results. */
22023 if (cfun->va_list_gpr_size)
22024 gr_saved = MIN (NUM_ARG_REGS - local_cum.aapcs_ncrn,
22025 cfun->va_list_gpr_size / UNITS_PER_WORD);
22026 if (cfun->va_list_fpr_size)
22027 vr_saved = MIN (NUM_FP_ARG_REGS - local_cum.aapcs_nvrn,
22028 cfun->va_list_fpr_size / UNITS_PER_VREG);
22029
22030 if (!TARGET_FLOAT)
22031 {
22032 gcc_assert (local_cum.aapcs_nvrn == 0);
22033 vr_saved = 0;
22034 }
22035
22036 if (!no_rtl)
22037 {
22038 if (gr_saved > 0)
22039 {
22040 rtx ptr, mem;
22041
22042 /* virtual_incoming_args_rtx should have been 16-byte aligned. */
22043 ptr = plus_constant (Pmode, virtual_incoming_args_rtx,
22044 - gr_saved * UNITS_PER_WORD);
22045 mem = gen_frame_mem (BLKmode, ptr);
22046 set_mem_alias_set (mem, get_varargs_alias_set ());
22047
22048 move_block_from_reg (local_cum.aapcs_ncrn + R0_REGNUM,
22049 mem, gr_saved);
22050 }
22051 if (vr_saved > 0)
22052 {
22053 /* We can't use move_block_from_reg, because it will use
22054 the wrong mode, storing D regs only. */
22055 machine_mode mode = TImode;
22056 int off, i, vr_start;
22057
22058 /* Set OFF to the offset from virtual_incoming_args_rtx of
22059 the first vector register. The VR save area lies below
22060 the GR one, and is aligned to 16 bytes. */
22061 off = -ROUND_UP (gr_saved * UNITS_PER_WORD,
22062 STACK_BOUNDARY / BITS_PER_UNIT);
22063 off -= vr_saved * UNITS_PER_VREG;
22064
22065 vr_start = V0_REGNUM + local_cum.aapcs_nvrn;
22066 for (i = 0; i < vr_saved; ++i)
22067 {
22068 rtx ptr, mem;
22069
22070 ptr = plus_constant (Pmode, virtual_incoming_args_rtx, off);
22071 mem = gen_frame_mem (mode, ptr);
22072 set_mem_alias_set (mem, get_varargs_alias_set ());
22073 aarch64_emit_move (mem, gen_rtx_REG (mode, vr_start + i));
22074 off += UNITS_PER_VREG;
22075 }
22076 }
22077 }
22078
22079 /* We don't save the size into *PRETEND_SIZE because we want to avoid
22080 any complication of having crtl->args.pretend_args_size changed. */
22081 cfun->machine->frame.saved_varargs_size
22082 = (ROUND_UP (gr_saved * UNITS_PER_WORD,
22083 STACK_BOUNDARY / BITS_PER_UNIT)
22084 + vr_saved * UNITS_PER_VREG);
22085 }
22086
22087 static void
22088 aarch64_conditional_register_usage (void)
22089 {
22090 int i;
22091 if (!TARGET_FLOAT)
22092 {
22093 for (i = V0_REGNUM; i <= V31_REGNUM; i++)
22094 {
22095 fixed_regs[i] = 1;
22096 call_used_regs[i] = 1;
22097 CLEAR_HARD_REG_BIT (operand_reg_set, i);
22098 }
22099 }
22100 if (!TARGET_SVE)
22101 for (i = P0_REGNUM; i <= P15_REGNUM; i++)
22102 {
22103 fixed_regs[i] = 1;
22104 call_used_regs[i] = 1;
22105 }
22106
22107 /* Only allow these registers to be accessed via special patterns. */
22108 CLEAR_HARD_REG_BIT (operand_reg_set, VG_REGNUM);
22109 CLEAR_HARD_REG_BIT (operand_reg_set, FFR_REGNUM);
22110 CLEAR_HARD_REG_BIT (operand_reg_set, FFRT_REGNUM);
22111 for (int i = FIRST_FAKE_REGNUM; i <= LAST_FAKE_REGNUM; ++i)
22112 CLEAR_HARD_REG_BIT (operand_reg_set, i);
22113
22114 /* When tracking speculation, we need a couple of call-clobbered registers
22115 to track the speculation state. It would be nice to just use
22116 IP0 and IP1, but currently there are numerous places that just
22117 assume these registers are free for other uses (eg pointer
22118 authentication). */
22119 if (aarch64_track_speculation)
22120 {
22121 fixed_regs[SPECULATION_TRACKER_REGNUM] = 1;
22122 call_used_regs[SPECULATION_TRACKER_REGNUM] = 1;
22123 fixed_regs[SPECULATION_SCRATCH_REGNUM] = 1;
22124 call_used_regs[SPECULATION_SCRATCH_REGNUM] = 1;
22125 }
22126 }
22127
22128 /* Implement TARGET_MEMBER_TYPE_FORCES_BLK. */
22129
22130 bool
22131 aarch64_member_type_forces_blk (const_tree field_or_array, machine_mode mode)
22132 {
22133 /* For records we're passed a FIELD_DECL, for arrays we're passed
22134 an ARRAY_TYPE. In both cases we're interested in the TREE_TYPE. */
22135 const_tree type = TREE_TYPE (field_or_array);
22136
22137 /* Assign BLKmode to anything that contains more than 2 SVE predicates.
22138 For structures, the "multiple" case is indicated by MODE being
22139 VOIDmode. */
22140 unsigned int num_zr, num_pr;
22141 if (aarch64_sve::builtin_type_p (type, &num_zr, &num_pr) && num_pr > 2)
22142 {
22143 if (TREE_CODE (field_or_array) == ARRAY_TYPE)
22144 return !simple_cst_equal (TYPE_SIZE (field_or_array),
22145 TYPE_SIZE (type));
22146 return mode == VOIDmode;
22147 }
22148
22149 return default_member_type_forces_blk (field_or_array, mode);
22150 }
22151
22152 /* Bitmasks that indicate whether earlier versions of GCC would have
22153 taken a different path through the ABI logic. This should result in
22154 a -Wpsabi warning if the earlier path led to a different ABI decision.
22155
22156 WARN_PSABI_EMPTY_CXX17_BASE
22157 Indicates that the type includes an artificial empty C++17 base field
22158 that, prior to GCC 10.1, would prevent the type from being treated as
22159 a HFA or HVA. See PR94383 for details.
22160
22161 WARN_PSABI_NO_UNIQUE_ADDRESS
22162 Indicates that the type includes an empty [[no_unique_address]] field
22163 that, prior to GCC 10.1, would prevent the type from being treated as
22164 a HFA or HVA. */
22165 const unsigned int WARN_PSABI_EMPTY_CXX17_BASE = 1U << 0;
22166 const unsigned int WARN_PSABI_NO_UNIQUE_ADDRESS = 1U << 1;
22167 const unsigned int WARN_PSABI_ZERO_WIDTH_BITFIELD = 1U << 2;
22168
22169 /* Walk down the type tree of TYPE counting consecutive base elements.
22170 If *MODEP is VOIDmode, then set it to the first valid floating point
22171 type. If a non-floating point type is found, or if a floating point
22172 type that doesn't match a non-VOIDmode *MODEP is found, then return -1,
22173 otherwise return the count in the sub-tree.
22174
22175 The WARN_PSABI_FLAGS argument allows the caller to check whether this
22176 function has changed its behavior relative to earlier versions of GCC.
22177 Normally the argument should be nonnull and point to a zero-initialized
22178 variable. The function then records whether the ABI decision might
22179 be affected by a known fix to the ABI logic, setting the associated
22180 WARN_PSABI_* bits if so.
22181
22182 When the argument is instead a null pointer, the function tries to
22183 simulate the behavior of GCC before all such ABI fixes were made.
22184 This is useful to check whether the function returns something
22185 different after the ABI fixes. */
22186 static int
22187 aapcs_vfp_sub_candidate (const_tree type, machine_mode *modep,
22188 unsigned int *warn_psabi_flags)
22189 {
22190 machine_mode mode;
22191 HOST_WIDE_INT size;
22192
22193 if (aarch64_sve::builtin_type_p (type))
22194 return -1;
22195
22196 switch (TREE_CODE (type))
22197 {
22198 case REAL_TYPE:
22199 mode = TYPE_MODE (type);
22200 if (mode != DFmode && mode != SFmode
22201 && mode != TFmode && mode != HFmode
22202 && mode != SDmode && mode != DDmode && mode != TDmode)
22203 return -1;
22204
22205 if (*modep == VOIDmode)
22206 *modep = mode;
22207
22208 if (*modep == mode)
22209 return 1;
22210
22211 break;
22212
22213 case COMPLEX_TYPE:
22214 mode = TYPE_MODE (TREE_TYPE (type));
22215 if (mode != DFmode && mode != SFmode
22216 && mode != TFmode && mode != HFmode)
22217 return -1;
22218
22219 if (*modep == VOIDmode)
22220 *modep = mode;
22221
22222 if (*modep == mode)
22223 return 2;
22224
22225 break;
22226
22227 case VECTOR_TYPE:
22228 /* Use V2SImode and V4SImode as representatives of all 64-bit
22229 and 128-bit vector types. */
22230 size = int_size_in_bytes (type);
22231 switch (size)
22232 {
22233 case 8:
22234 mode = V2SImode;
22235 break;
22236 case 16:
22237 mode = V4SImode;
22238 break;
22239 default:
22240 return -1;
22241 }
22242
22243 if (*modep == VOIDmode)
22244 *modep = mode;
22245
22246 /* Vector modes are considered to be opaque: two vectors are
22247 equivalent for the purposes of being homogeneous aggregates
22248 if they are the same size. */
22249 if (*modep == mode)
22250 return 1;
22251
22252 break;
22253
22254 case ARRAY_TYPE:
22255 {
22256 int count;
22257 tree index = TYPE_DOMAIN (type);
22258
22259 /* Can't handle incomplete types nor sizes that are not
22260 fixed. */
22261 if (!COMPLETE_TYPE_P (type)
22262 || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST)
22263 return -1;
22264
22265 count = aapcs_vfp_sub_candidate (TREE_TYPE (type), modep,
22266 warn_psabi_flags);
22267 if (count == -1
22268 || !index
22269 || !TYPE_MAX_VALUE (index)
22270 || !tree_fits_uhwi_p (TYPE_MAX_VALUE (index))
22271 || !TYPE_MIN_VALUE (index)
22272 || !tree_fits_uhwi_p (TYPE_MIN_VALUE (index))
22273 || count < 0)
22274 return -1;
22275
22276 count *= (1 + tree_to_uhwi (TYPE_MAX_VALUE (index))
22277 - tree_to_uhwi (TYPE_MIN_VALUE (index)));
22278
22279 /* There must be no padding. */
22280 if (maybe_ne (wi::to_poly_wide (TYPE_SIZE (type)),
22281 count * GET_MODE_BITSIZE (*modep)))
22282 return -1;
22283
22284 return count;
22285 }
22286
22287 case RECORD_TYPE:
22288 {
22289 int count = 0;
22290 int sub_count;
22291 tree field;
22292
22293 /* Can't handle incomplete types nor sizes that are not
22294 fixed. */
22295 if (!COMPLETE_TYPE_P (type)
22296 || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST)
22297 return -1;
22298
22299 for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
22300 {
22301 if (TREE_CODE (field) != FIELD_DECL)
22302 continue;
22303
22304 if (DECL_FIELD_ABI_IGNORED (field))
22305 {
22306 /* See whether this is something that earlier versions of
22307 GCC failed to ignore. */
22308 unsigned int flag;
22309 if (lookup_attribute ("no_unique_address",
22310 DECL_ATTRIBUTES (field)))
22311 flag = WARN_PSABI_NO_UNIQUE_ADDRESS;
22312 else if (cxx17_empty_base_field_p (field))
22313 flag = WARN_PSABI_EMPTY_CXX17_BASE;
22314 else
22315 /* No compatibility problem. */
22316 continue;
22317
22318 /* Simulate the old behavior when WARN_PSABI_FLAGS is null. */
22319 if (warn_psabi_flags)
22320 {
22321 *warn_psabi_flags |= flag;
22322 continue;
22323 }
22324 }
22325 /* A zero-width bitfield may affect layout in some
22326 circumstances, but adds no members. The determination
22327 of whether or not a type is an HFA is performed after
22328 layout is complete, so if the type still looks like an
22329 HFA afterwards, it is still classed as one. This is
22330 potentially an ABI break for the hard-float ABI. */
22331 else if (DECL_BIT_FIELD (field)
22332 && integer_zerop (DECL_SIZE (field)))
22333 {
22334 /* Prior to GCC-12 these fields were striped early,
22335 hiding them from the back-end entirely and
22336 resulting in the correct behaviour for argument
22337 passing. Simulate that old behaviour without
22338 generating a warning. */
22339 if (DECL_FIELD_CXX_ZERO_WIDTH_BIT_FIELD (field))
22340 continue;
22341 if (warn_psabi_flags)
22342 {
22343 *warn_psabi_flags |= WARN_PSABI_ZERO_WIDTH_BITFIELD;
22344 continue;
22345 }
22346 }
22347
22348 sub_count = aapcs_vfp_sub_candidate (TREE_TYPE (field), modep,
22349 warn_psabi_flags);
22350 if (sub_count < 0)
22351 return -1;
22352 count += sub_count;
22353 }
22354
22355 /* There must be no padding. */
22356 if (maybe_ne (wi::to_poly_wide (TYPE_SIZE (type)),
22357 count * GET_MODE_BITSIZE (*modep)))
22358 return -1;
22359
22360 return count;
22361 }
22362
22363 case UNION_TYPE:
22364 case QUAL_UNION_TYPE:
22365 {
22366 /* These aren't very interesting except in a degenerate case. */
22367 int count = 0;
22368 int sub_count;
22369 tree field;
22370
22371 /* Can't handle incomplete types nor sizes that are not
22372 fixed. */
22373 if (!COMPLETE_TYPE_P (type)
22374 || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST)
22375 return -1;
22376
22377 for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
22378 {
22379 if (TREE_CODE (field) != FIELD_DECL)
22380 continue;
22381
22382 sub_count = aapcs_vfp_sub_candidate (TREE_TYPE (field), modep,
22383 warn_psabi_flags);
22384 if (sub_count < 0)
22385 return -1;
22386 count = count > sub_count ? count : sub_count;
22387 }
22388
22389 /* There must be no padding. */
22390 if (maybe_ne (wi::to_poly_wide (TYPE_SIZE (type)),
22391 count * GET_MODE_BITSIZE (*modep)))
22392 return -1;
22393
22394 return count;
22395 }
22396
22397 default:
22398 break;
22399 }
22400
22401 return -1;
22402 }
22403
22404 /* Return TRUE if the type, as described by TYPE and MODE, is a short vector
22405 type as described in AAPCS64 \S 4.1.2.
22406
22407 See the comment above aarch64_composite_type_p for the notes on MODE. */
22408
22409 static bool
22410 aarch64_short_vector_p (const_tree type,
22411 machine_mode mode)
22412 {
22413 poly_int64 size = -1;
22414
22415 if (type && VECTOR_TYPE_P (type))
22416 {
22417 if (aarch64_sve::builtin_type_p (type))
22418 return false;
22419 size = int_size_in_bytes (type);
22420 }
22421 else if (GET_MODE_CLASS (mode) == MODE_VECTOR_INT
22422 || GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT)
22423 {
22424 /* The containing "else if" is too loose: it means that we look at TYPE
22425 if the type is a vector type (good), but that we otherwise ignore TYPE
22426 and look only at the mode. This is wrong because the type describes
22427 the language-level information whereas the mode is purely an internal
22428 GCC concept. We can therefore reach here for types that are not
22429 vectors in the AAPCS64 sense.
22430
22431 We can't "fix" that for the traditional Advanced SIMD vector modes
22432 without breaking backwards compatibility. However, there's no such
22433 baggage for the structure modes, which were introduced in GCC 12. */
22434 if (aarch64_advsimd_struct_mode_p (mode))
22435 return false;
22436
22437 /* For similar reasons, rely only on the type, not the mode, when
22438 processing SVE types. */
22439 if (type && aarch64_some_values_include_pst_objects_p (type))
22440 /* Leave later code to report an error if SVE is disabled. */
22441 gcc_assert (!TARGET_SVE || aarch64_sve_mode_p (mode));
22442 else
22443 size = GET_MODE_SIZE (mode);
22444 }
22445 if (known_eq (size, 8) || known_eq (size, 16))
22446 {
22447 /* 64-bit and 128-bit vectors should only acquire an SVE mode if
22448 they are being treated as scalable AAPCS64 types. */
22449 gcc_assert (!aarch64_sve_mode_p (mode)
22450 && !aarch64_advsimd_struct_mode_p (mode));
22451 return true;
22452 }
22453 return false;
22454 }
22455
22456 /* Return TRUE if the type, as described by TYPE and MODE, is a composite
22457 type as described in AAPCS64 \S 4.3. This includes aggregate, union and
22458 array types. The C99 floating-point complex types are also considered
22459 as composite types, according to AAPCS64 \S 7.1.1. The complex integer
22460 types, which are GCC extensions and out of the scope of AAPCS64, are
22461 treated as composite types here as well.
22462
22463 Note that MODE itself is not sufficient in determining whether a type
22464 is such a composite type or not. This is because
22465 stor-layout.cc:compute_record_mode may have already changed the MODE
22466 (BLKmode) of a RECORD_TYPE TYPE to some other mode. For example, a
22467 structure with only one field may have its MODE set to the mode of the
22468 field. Also an integer mode whose size matches the size of the
22469 RECORD_TYPE type may be used to substitute the original mode
22470 (i.e. BLKmode) in certain circumstances. In other words, MODE cannot be
22471 solely relied on. */
22472
22473 static bool
22474 aarch64_composite_type_p (const_tree type,
22475 machine_mode mode)
22476 {
22477 if (aarch64_short_vector_p (type, mode))
22478 return false;
22479
22480 if (type && (AGGREGATE_TYPE_P (type) || TREE_CODE (type) == COMPLEX_TYPE))
22481 return true;
22482
22483 if (type
22484 && TREE_CODE (type) == BITINT_TYPE
22485 && int_size_in_bytes (type) > 16)
22486 return true;
22487
22488 if (mode == BLKmode
22489 || GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT
22490 || GET_MODE_CLASS (mode) == MODE_COMPLEX_INT)
22491 return true;
22492
22493 return false;
22494 }
22495
22496 /* Return TRUE if an argument, whose type is described by TYPE and MODE,
22497 shall be passed or returned in simd/fp register(s) (providing these
22498 parameter passing registers are available).
22499
22500 Upon successful return, *COUNT returns the number of needed registers,
22501 *BASE_MODE returns the mode of the individual register and when IS_HA
22502 is not NULL, *IS_HA indicates whether or not the argument is a homogeneous
22503 floating-point aggregate or a homogeneous short-vector aggregate.
22504
22505 SILENT_P is true if the function should refrain from reporting any
22506 diagnostics. This should only be used if the caller is certain that
22507 any ABI decisions would eventually come through this function with
22508 SILENT_P set to false. */
22509
22510 static bool
22511 aarch64_vfp_is_call_or_return_candidate (machine_mode mode,
22512 const_tree type,
22513 machine_mode *base_mode,
22514 int *count,
22515 bool *is_ha,
22516 bool silent_p)
22517 {
22518 if (is_ha != NULL) *is_ha = false;
22519
22520 machine_mode new_mode = VOIDmode;
22521 bool composite_p = aarch64_composite_type_p (type, mode);
22522
22523 if ((!composite_p
22524 && (GET_MODE_CLASS (mode) == MODE_FLOAT
22525 || GET_MODE_CLASS (mode) == MODE_DECIMAL_FLOAT
22526 || (type && TYPE_MAIN_VARIANT (type) == aarch64_mfp8_type_node)))
22527 || aarch64_short_vector_p (type, mode))
22528 {
22529 *count = 1;
22530 new_mode = mode;
22531 }
22532 else if (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
22533 {
22534 if (is_ha != NULL) *is_ha = true;
22535 *count = 2;
22536 new_mode = GET_MODE_INNER (mode);
22537 }
22538 else if (type && composite_p)
22539 {
22540 unsigned int warn_psabi_flags = 0;
22541 int ag_count = aapcs_vfp_sub_candidate (type, &new_mode,
22542 &warn_psabi_flags);
22543 if (ag_count > 0 && ag_count <= HA_MAX_NUM_FLDS)
22544 {
22545 static unsigned last_reported_type_uid;
22546 unsigned uid = TYPE_UID (TYPE_MAIN_VARIANT (type));
22547 int alt;
22548 if (!silent_p
22549 && warn_psabi
22550 && warn_psabi_flags
22551 && uid != last_reported_type_uid
22552 && ((alt = aapcs_vfp_sub_candidate (type, &new_mode, NULL))
22553 != ag_count))
22554 {
22555 const char *url10
22556 = CHANGES_ROOT_URL "gcc-10/changes.html#empty_base";
22557 const char *url12
22558 = CHANGES_ROOT_URL "gcc-12/changes.html#zero_width_bitfields";
22559 gcc_assert (alt == -1);
22560 last_reported_type_uid = uid;
22561 /* Use TYPE_MAIN_VARIANT to strip any redundant const
22562 qualification. */
22563 if (warn_psabi_flags & WARN_PSABI_NO_UNIQUE_ADDRESS)
22564 inform (input_location, "parameter passing for argument of "
22565 "type %qT with %<[[no_unique_address]]%> members "
22566 "changed %{in GCC 10.1%}",
22567 TYPE_MAIN_VARIANT (type), url10);
22568 else if (warn_psabi_flags & WARN_PSABI_EMPTY_CXX17_BASE)
22569 inform (input_location, "parameter passing for argument of "
22570 "type %qT when C++17 is enabled changed to match "
22571 "C++14 %{in GCC 10.1%}",
22572 TYPE_MAIN_VARIANT (type), url10);
22573 else if (warn_psabi_flags & WARN_PSABI_ZERO_WIDTH_BITFIELD)
22574 inform (input_location, "parameter passing for argument of "
22575 "type %qT changed %{in GCC 12.1%}",
22576 TYPE_MAIN_VARIANT (type), url12);
22577 }
22578
22579 if (is_ha != NULL) *is_ha = true;
22580 *count = ag_count;
22581 }
22582 else
22583 return false;
22584 }
22585 else
22586 return false;
22587
22588 gcc_assert (!aarch64_sve_mode_p (new_mode));
22589 *base_mode = new_mode;
22590 return true;
22591 }
22592
22593 /* Implement TARGET_STRUCT_VALUE_RTX. */
22594
22595 static rtx
22596 aarch64_struct_value_rtx (tree fndecl ATTRIBUTE_UNUSED,
22597 int incoming ATTRIBUTE_UNUSED)
22598 {
22599 return gen_rtx_REG (Pmode, AARCH64_STRUCT_VALUE_REGNUM);
22600 }
22601
22602 /* Implements target hook vector_mode_supported_p. */
22603 static bool
22604 aarch64_vector_mode_supported_p (machine_mode mode)
22605 {
22606 unsigned int vec_flags = aarch64_classify_vector_mode (mode);
22607 return vec_flags != 0 && (vec_flags & VEC_STRUCT) == 0;
22608 }
22609
22610 /* Implements target hook vector_mode_supported_any_target_p. */
22611 static bool
22612 aarch64_vector_mode_supported_any_target_p (machine_mode mode)
22613 {
22614 unsigned int vec_flags = aarch64_classify_vector_mode (mode, true);
22615 return vec_flags != 0 && (vec_flags & VEC_STRUCT) == 0;
22616 }
22617
22618 /* Return the full-width SVE vector mode for element mode MODE, if one
22619 exists. */
22620 opt_machine_mode
22621 aarch64_full_sve_mode (scalar_mode mode)
22622 {
22623 switch (mode)
22624 {
22625 case E_DFmode:
22626 return VNx2DFmode;
22627 case E_SFmode:
22628 return VNx4SFmode;
22629 case E_HFmode:
22630 return VNx8HFmode;
22631 case E_BFmode:
22632 return VNx8BFmode;
22633 case E_DImode:
22634 return VNx2DImode;
22635 case E_SImode:
22636 return VNx4SImode;
22637 case E_HImode:
22638 return VNx8HImode;
22639 case E_QImode:
22640 return VNx16QImode;
22641 default:
22642 return opt_machine_mode ();
22643 }
22644 }
22645
22646 /* Return the 64-bit Advanced SIMD vector mode for element mode MODE,
22647 if it exists. */
22648 opt_machine_mode
22649 aarch64_v64_mode (scalar_mode mode)
22650 {
22651 switch (mode)
22652 {
22653 case E_SFmode:
22654 return V2SFmode;
22655 case E_HFmode:
22656 return V4HFmode;
22657 case E_BFmode:
22658 return V4BFmode;
22659 case E_SImode:
22660 return V2SImode;
22661 case E_HImode:
22662 return V4HImode;
22663 case E_QImode:
22664 return V8QImode;
22665 default:
22666 return {};
22667 }
22668 }
22669
22670 /* Return the 128-bit Advanced SIMD vector mode for element mode MODE,
22671 if it exists. */
22672 opt_machine_mode
22673 aarch64_v128_mode (scalar_mode mode)
22674 {
22675 switch (mode)
22676 {
22677 case E_DFmode:
22678 return V2DFmode;
22679 case E_SFmode:
22680 return V4SFmode;
22681 case E_HFmode:
22682 return V8HFmode;
22683 case E_BFmode:
22684 return V8BFmode;
22685 case E_SImode:
22686 return V4SImode;
22687 case E_HImode:
22688 return V8HImode;
22689 case E_QImode:
22690 return V16QImode;
22691 case E_DImode:
22692 return V2DImode;
22693 default:
22694 return opt_machine_mode ();
22695 }
22696 }
22697
22698 /* Return appropriate SIMD container
22699 for MODE within a vector of WIDTH bits. */
22700 static machine_mode
22701 aarch64_simd_container_mode (scalar_mode mode, poly_int64 width)
22702 {
22703 if (TARGET_SVE
22704 && maybe_ne (width, 128)
22705 && known_eq (width, BITS_PER_SVE_VECTOR))
22706 return aarch64_full_sve_mode (mode).else_mode (word_mode);
22707
22708 gcc_assert (known_eq (width, 64) || known_eq (width, 128));
22709 if (TARGET_BASE_SIMD)
22710 {
22711 if (known_eq (width, 128))
22712 return aarch64_v128_mode (mode).else_mode (word_mode);
22713 else
22714 return aarch64_v64_mode (mode).else_mode (word_mode);
22715 }
22716 return word_mode;
22717 }
22718
22719 /* Compare an SVE mode SVE_M and an Advanced SIMD mode ASIMD_M
22720 and return whether the SVE mode should be preferred over the
22721 Advanced SIMD one in aarch64_autovectorize_vector_modes. */
22722 static bool
22723 aarch64_cmp_autovec_modes (machine_mode sve_m, machine_mode asimd_m)
22724 {
22725 /* Take into account the aarch64-autovec-preference param if non-zero. */
22726 bool only_asimd_p = aarch64_autovec_preference == AARCH64_AUTOVEC_ASIMD_ONLY;
22727 bool only_sve_p = aarch64_autovec_preference == AARCH64_AUTOVEC_SVE_ONLY;
22728
22729 if (only_asimd_p)
22730 return false;
22731 if (only_sve_p)
22732 return true;
22733
22734 /* The preference in case of a tie in costs. */
22735 bool prefer_asimd = aarch64_autovec_preference == AARCH64_AUTOVEC_PREFER_ASIMD;
22736 bool prefer_sve = aarch64_autovec_preference == AARCH64_AUTOVEC_PREFER_SVE;
22737
22738 poly_int64 nunits_sve = GET_MODE_NUNITS (sve_m);
22739 poly_int64 nunits_asimd = GET_MODE_NUNITS (asimd_m);
22740 /* If the CPU information does not have an SVE width registered use the
22741 generic poly_int comparison that prefers SVE. If a preference is
22742 explicitly requested avoid this path. */
22743 if (aarch64_tune_params.sve_width == SVE_SCALABLE
22744 && !prefer_asimd
22745 && !prefer_sve)
22746 return maybe_gt (nunits_sve, nunits_asimd);
22747
22748 /* Otherwise estimate the runtime width of the modes involved. */
22749 HOST_WIDE_INT est_sve = estimated_poly_value (nunits_sve);
22750 HOST_WIDE_INT est_asimd = estimated_poly_value (nunits_asimd);
22751
22752 /* Preferring SVE means picking it first unless the Advanced SIMD mode
22753 is clearly wider. */
22754 if (prefer_sve)
22755 return est_sve >= est_asimd;
22756 /* Conversely, preferring Advanced SIMD means picking SVE only if SVE
22757 is clearly wider. */
22758 if (prefer_asimd)
22759 return est_sve > est_asimd;
22760
22761 /* In the default case prefer Advanced SIMD over SVE in case of a tie. */
22762 return est_sve > est_asimd;
22763 }
22764
22765 /* Return 128-bit container as the preferred SIMD mode for MODE. */
22766 static machine_mode
22767 aarch64_preferred_simd_mode (scalar_mode mode)
22768 {
22769 /* Take into account explicit auto-vectorization ISA preferences through
22770 aarch64_cmp_autovec_modes. */
22771 if (TARGET_SVE && aarch64_cmp_autovec_modes (VNx16QImode, V16QImode))
22772 return aarch64_full_sve_mode (mode).else_mode (word_mode);
22773 if (TARGET_SIMD)
22774 return aarch64_v128_mode (mode).else_mode (word_mode);
22775 return word_mode;
22776 }
22777
22778 /* Return a list of possible vector sizes for the vectorizer
22779 to iterate over. */
22780 static unsigned int
22781 aarch64_autovectorize_vector_modes (vector_modes *modes, bool)
22782 {
22783 static const machine_mode sve_modes[] = {
22784 /* Try using full vectors for all element types. */
22785 VNx16QImode,
22786
22787 /* Try using 16-bit containers for 8-bit elements and full vectors
22788 for wider elements. */
22789 VNx8QImode,
22790
22791 /* Try using 32-bit containers for 8-bit and 16-bit elements and
22792 full vectors for wider elements. */
22793 VNx4QImode,
22794
22795 /* Try using 64-bit containers for all element types. */
22796 VNx2QImode
22797 };
22798
22799 static const machine_mode advsimd_modes[] = {
22800 /* Try using 128-bit vectors for all element types. */
22801 V16QImode,
22802
22803 /* Try using 64-bit vectors for 8-bit elements and 128-bit vectors
22804 for wider elements. */
22805 V8QImode,
22806
22807 /* Try using 64-bit vectors for 16-bit elements and 128-bit vectors
22808 for wider elements.
22809
22810 TODO: We could support a limited form of V4QImode too, so that
22811 we use 32-bit vectors for 8-bit elements. */
22812 V4HImode,
22813
22814 /* Try using 64-bit vectors for 32-bit elements and 128-bit vectors
22815 for 64-bit elements.
22816
22817 TODO: We could similarly support limited forms of V2QImode and V2HImode
22818 for this case. */
22819 V2SImode
22820 };
22821
22822 /* Try using N-byte SVE modes only after trying N-byte Advanced SIMD mode.
22823 This is because:
22824
22825 - If we can't use N-byte Advanced SIMD vectors then the placement
22826 doesn't matter; we'll just continue as though the Advanced SIMD
22827 entry didn't exist.
22828
22829 - If an SVE main loop with N bytes ends up being cheaper than an
22830 Advanced SIMD main loop with N bytes then by default we'll replace
22831 the Advanced SIMD version with the SVE one.
22832
22833 - If an Advanced SIMD main loop with N bytes ends up being cheaper
22834 than an SVE main loop with N bytes then by default we'll try to
22835 use the SVE loop to vectorize the epilogue instead. */
22836
22837 bool only_asimd_p = aarch64_autovec_preference == AARCH64_AUTOVEC_ASIMD_ONLY;
22838 bool only_sve_p = aarch64_autovec_preference == AARCH64_AUTOVEC_SVE_ONLY;
22839
22840 unsigned int sve_i = (TARGET_SVE && !only_asimd_p) ? 0 : ARRAY_SIZE (sve_modes);
22841 unsigned int advsimd_i = 0;
22842
22843 while (!only_sve_p && advsimd_i < ARRAY_SIZE (advsimd_modes))
22844 {
22845 if (sve_i < ARRAY_SIZE (sve_modes)
22846 && aarch64_cmp_autovec_modes (sve_modes[sve_i],
22847 advsimd_modes[advsimd_i]))
22848 modes->safe_push (sve_modes[sve_i++]);
22849 else
22850 modes->safe_push (advsimd_modes[advsimd_i++]);
22851 }
22852 while (sve_i < ARRAY_SIZE (sve_modes))
22853 modes->safe_push (sve_modes[sve_i++]);
22854
22855 unsigned int flags = 0;
22856 if (aarch64_vect_compare_costs)
22857 flags |= VECT_COMPARE_COSTS;
22858 return flags;
22859 }
22860
22861 /* Implement TARGET_MANGLE_TYPE. */
22862
22863 static const char *
22864 aarch64_mangle_type (const_tree type)
22865 {
22866 /* The AArch64 ABI documents say that "__va_list" has to be
22867 mangled as if it is in the "std" namespace. */
22868 if (lang_hooks.types_compatible_p (CONST_CAST_TREE (type), va_list_type))
22869 return "St9__va_list";
22870
22871 /* Half-precision floating point types. */
22872 if (SCALAR_FLOAT_TYPE_P (type) && TYPE_PRECISION (type) == 16)
22873 {
22874 if (TYPE_MAIN_VARIANT (type) == float16_type_node)
22875 return NULL;
22876 if (TYPE_MODE (type) == BFmode)
22877 return "u6__bf16";
22878 else
22879 return "Dh";
22880 }
22881
22882 /* Modal 8 bit floating point types. */
22883 if (TYPE_MAIN_VARIANT (type) == aarch64_mfp8_type_node)
22884 return "u6__mfp8";
22885
22886 /* Mangle AArch64-specific internal types. TYPE_NAME is non-NULL_TREE for
22887 builtin types. */
22888 if (TYPE_NAME (type) != NULL)
22889 {
22890 const char *res;
22891 if ((res = aarch64_general_mangle_builtin_type (type))
22892 || (res = aarch64_sve::mangle_builtin_type (type)))
22893 return res;
22894 }
22895
22896 /* Use the default mangling. */
22897 return NULL;
22898 }
22899
22900 /* Implement TARGET_INVALID_CONVERSION. */
22901
22902 static const char *
22903 aarch64_invalid_conversion (const_tree fromtype, const_tree totype)
22904 {
22905 /* Do not allow conversions to/from FP8. But do allow conversions between
22906 volatile and const variants of __mfp8. */
22907 bool fromtype_is_fp8
22908 = (TYPE_MAIN_VARIANT (fromtype) == aarch64_mfp8_type_node);
22909 bool totype_is_fp8 = (TYPE_MAIN_VARIANT (totype) == aarch64_mfp8_type_node);
22910
22911 if (fromtype_is_fp8 && totype_is_fp8)
22912 return NULL;
22913
22914 if (fromtype_is_fp8)
22915 return N_ ("invalid conversion from type %<mfloat8_t%>");
22916 if (totype_is_fp8)
22917 return N_ ("invalid conversion to type %<mfloat8_t%>");
22918
22919 /* Conversion allowed. */
22920 return NULL;
22921 }
22922
22923 /* Implement TARGET_VERIFY_TYPE_CONTEXT. */
22924
22925 static bool
22926 aarch64_verify_type_context (location_t loc, type_context_kind context,
22927 const_tree type, bool silent_p)
22928 {
22929 return aarch64_sve::verify_type_context (loc, context, type, silent_p);
22930 }
22931
22932 /* Find the first rtx_insn before insn that will generate an assembly
22933 instruction. */
22934
22935 static rtx_insn *
22936 aarch64_prev_real_insn (rtx_insn *insn)
22937 {
22938 if (!insn)
22939 return NULL;
22940
22941 do
22942 {
22943 insn = prev_real_insn (insn);
22944 }
22945 while (insn && recog_memoized (insn) < 0);
22946
22947 return insn;
22948 }
22949
22950 static bool
22951 is_madd_op (enum attr_type t1)
22952 {
22953 unsigned int i;
22954 /* A number of these may be AArch32 only. */
22955 enum attr_type mlatypes[] = {
22956 TYPE_MLA, TYPE_MLAS, TYPE_SMLAD, TYPE_SMLADX, TYPE_SMLAL, TYPE_SMLALD,
22957 TYPE_SMLALS, TYPE_SMLALXY, TYPE_SMLAWX, TYPE_SMLAWY, TYPE_SMLAXY,
22958 TYPE_SMMLA, TYPE_UMLAL, TYPE_UMLALS,TYPE_SMLSD, TYPE_SMLSDX, TYPE_SMLSLD
22959 };
22960
22961 for (i = 0; i < ARRAY_SIZE (mlatypes); i++)
22962 {
22963 if (t1 == mlatypes[i])
22964 return true;
22965 }
22966
22967 return false;
22968 }
22969
22970 /* Check if there is a register dependency between a load and the insn
22971 for which we hold recog_data. */
22972
22973 static bool
22974 dep_between_memop_and_curr (rtx memop)
22975 {
22976 rtx load_reg;
22977 int opno;
22978
22979 gcc_assert (GET_CODE (memop) == SET);
22980
22981 if (!REG_P (SET_DEST (memop)))
22982 return false;
22983
22984 load_reg = SET_DEST (memop);
22985 for (opno = 1; opno < recog_data.n_operands; opno++)
22986 {
22987 rtx operand = recog_data.operand[opno];
22988 if (REG_P (operand)
22989 && reg_overlap_mentioned_p (load_reg, operand))
22990 return true;
22991
22992 }
22993 return false;
22994 }
22995
22996
22997 /* When working around the Cortex-A53 erratum 835769,
22998 given rtx_insn INSN, return true if it is a 64-bit multiply-accumulate
22999 instruction and has a preceding memory instruction such that a NOP
23000 should be inserted between them. */
23001
23002 bool
23003 aarch64_madd_needs_nop (rtx_insn* insn)
23004 {
23005 enum attr_type attr_type;
23006 rtx_insn *prev;
23007 rtx body;
23008
23009 if (!TARGET_FIX_ERR_A53_835769)
23010 return false;
23011
23012 if (!INSN_P (insn) || recog_memoized (insn) < 0)
23013 return false;
23014
23015 attr_type = get_attr_type (insn);
23016 if (!is_madd_op (attr_type))
23017 return false;
23018
23019 prev = aarch64_prev_real_insn (insn);
23020 /* aarch64_prev_real_insn can call recog_memoized on insns other than INSN.
23021 Restore recog state to INSN to avoid state corruption. */
23022 extract_constrain_insn_cached (insn);
23023
23024 if (!prev || !contains_mem_rtx_p (PATTERN (prev)))
23025 return false;
23026
23027 body = single_set (prev);
23028
23029 /* If the previous insn is a memory op and there is no dependency between
23030 it and the DImode madd, emit a NOP between them. If body is NULL then we
23031 have a complex memory operation, probably a load/store pair.
23032 Be conservative for now and emit a NOP. */
23033 if (GET_MODE (recog_data.operand[0]) == DImode
23034 && (!body || !dep_between_memop_and_curr (body)))
23035 return true;
23036
23037 return false;
23038
23039 }
23040
23041
23042 /* Implement FINAL_PRESCAN_INSN. */
23043
23044 void
23045 aarch64_final_prescan_insn (rtx_insn *insn)
23046 {
23047 if (aarch64_madd_needs_nop (insn))
23048 fprintf (asm_out_file, "\tnop // between mem op and mult-accumulate\n");
23049 }
23050
23051
23052 /* Return true if BASE_OR_STEP is a valid immediate operand for an SVE INDEX
23053 instruction. */
23054
23055 bool
23056 aarch64_sve_index_immediate_p (rtx base_or_step)
23057 {
23058 return (CONST_INT_P (base_or_step)
23059 && IN_RANGE (INTVAL (base_or_step), -16, 15));
23060 }
23061
23062 /* Return true if SERIES is a constant vector that can be loaded using
23063 an immediate SVE INDEX, considering both SVE and Advanced SIMD modes.
23064 When returning true, store the base in *BASE_OUT and the step
23065 in *STEP_OUT. */
23066
23067 static bool
23068 aarch64_sve_index_series_p (rtx series, rtx *base_out, rtx *step_out)
23069 {
23070 rtx base, step;
23071 if (!const_vec_series_p (series, &base, &step)
23072 || !CONST_INT_P (base)
23073 || !CONST_INT_P (step))
23074 return false;
23075
23076 auto mode = GET_MODE (series);
23077 auto elt_mode = as_a<scalar_int_mode> (GET_MODE_INNER (mode));
23078 unsigned int vec_flags = aarch64_classify_vector_mode (mode);
23079 if (BYTES_BIG_ENDIAN && (vec_flags & VEC_ADVSIMD))
23080 {
23081 /* On big-endian targets, architectural lane 0 holds the last element
23082 for Advanced SIMD and the first element for SVE; see the comment at
23083 the head of aarch64-sve.md for details. This means that, from an SVE
23084 point of view, an Advanced SIMD series goes from the last element to
23085 the first. */
23086 auto i = GET_MODE_NUNITS (mode).to_constant () - 1;
23087 base = gen_int_mode (UINTVAL (base) + i * UINTVAL (step), elt_mode);
23088 step = gen_int_mode (-UINTVAL (step), elt_mode);
23089 }
23090
23091 if (!aarch64_sve_index_immediate_p (base)
23092 || !aarch64_sve_index_immediate_p (step))
23093 return false;
23094
23095 /* If the mode spans multiple registers, check that each subseries is
23096 in range. */
23097 unsigned int nvectors = aarch64_ldn_stn_vectors (mode);
23098 if (nvectors != 1)
23099 {
23100 unsigned int nunits;
23101 if (!GET_MODE_NUNITS (mode).is_constant (&nunits))
23102 return false;
23103 nunits /= nvectors;
23104 for (unsigned int i = 1; i < nvectors; ++i)
23105 if (!IN_RANGE (INTVAL (base) + i * nunits * INTVAL (step), -16, 15))
23106 return false;
23107 }
23108
23109 *base_out = base;
23110 *step_out = step;
23111 return true;
23112 }
23113
23114 /* Return true if X is a valid immediate for the SVE ADD and SUB instructions
23115 when applied to mode MODE. Negate X first if NEGATE_P is true. */
23116
23117 bool
23118 aarch64_sve_arith_immediate_p (machine_mode mode, rtx x, bool negate_p)
23119 {
23120 rtx elt = unwrap_const_vec_duplicate (x);
23121 if (!CONST_INT_P (elt))
23122 return false;
23123
23124 HOST_WIDE_INT val = INTVAL (elt);
23125 if (negate_p)
23126 val = -val;
23127 val &= GET_MODE_MASK (GET_MODE_INNER (mode));
23128
23129 if (val & 0xff)
23130 return IN_RANGE (val, 0, 0xff);
23131 return IN_RANGE (val, 0, 0xff00);
23132 }
23133
23134 /* Return true if X is a valid immediate for the SVE SQADD and SQSUB
23135 instructions when applied to mode MODE. Negate X first if NEGATE_P
23136 is true. */
23137
23138 bool
23139 aarch64_sve_sqadd_sqsub_immediate_p (machine_mode mode, rtx x, bool negate_p)
23140 {
23141 if (!aarch64_sve_arith_immediate_p (mode, x, negate_p))
23142 return false;
23143
23144 /* After the optional negation, the immediate must be nonnegative.
23145 E.g. a saturating add of -127 must be done via SQSUB Zn.B, Zn.B, #127
23146 instead of SQADD Zn.B, Zn.B, #129. */
23147 rtx elt = unwrap_const_vec_duplicate (x);
23148 return negate_p == (INTVAL (elt) < 0);
23149 }
23150
23151 /* Return true if X is a valid immediate operand for an SVE logical
23152 instruction such as AND. */
23153
23154 bool
23155 aarch64_sve_bitmask_immediate_p (rtx x)
23156 {
23157 rtx elt;
23158
23159 return (const_vec_duplicate_p (x, &elt)
23160 && CONST_INT_P (elt)
23161 && aarch64_bitmask_imm (INTVAL (elt),
23162 GET_MODE_INNER (GET_MODE (x))));
23163 }
23164
23165 /* Return true if X is a valid immediate for the SVE DUP and CPY
23166 instructions. */
23167
23168 bool
23169 aarch64_sve_dup_immediate_p (rtx x)
23170 {
23171 x = aarch64_bit_representation (unwrap_const_vec_duplicate (x));
23172 if (!CONST_INT_P (x))
23173 return false;
23174
23175 HOST_WIDE_INT val = INTVAL (x);
23176 if (val & 0xff)
23177 return IN_RANGE (val, -0x80, 0x7f);
23178 return IN_RANGE (val, -0x8000, 0x7f00);
23179 }
23180
23181 /* Return true if X is a valid immediate operand for an SVE CMP instruction.
23182 SIGNED_P says whether the operand is signed rather than unsigned. */
23183
23184 bool
23185 aarch64_sve_cmp_immediate_p (rtx x, bool signed_p)
23186 {
23187 x = unwrap_const_vec_duplicate (x);
23188 return (CONST_INT_P (x)
23189 && (signed_p
23190 ? IN_RANGE (INTVAL (x), -16, 15)
23191 : IN_RANGE (INTVAL (x), 0, 127)));
23192 }
23193
23194 /* Return true if X is a valid immediate operand for an SVE FADD or FSUB
23195 instruction. Negate X first if NEGATE_P is true. */
23196
23197 bool
23198 aarch64_sve_float_arith_immediate_p (rtx x, bool negate_p)
23199 {
23200 rtx elt;
23201 REAL_VALUE_TYPE r;
23202
23203 if (GET_MODE_INNER (GET_MODE (x)) == BFmode
23204 || !const_vec_duplicate_p (x, &elt)
23205 || !CONST_DOUBLE_P (elt))
23206 return false;
23207
23208 r = *CONST_DOUBLE_REAL_VALUE (elt);
23209
23210 if (negate_p)
23211 r = real_value_negate (&r);
23212
23213 if (real_equal (&r, &dconst1))
23214 return true;
23215 if (real_equal (&r, &dconsthalf))
23216 return true;
23217 return false;
23218 }
23219
23220 /* Return true if X is a valid immediate operand for an SVE FMUL
23221 instruction. */
23222
23223 bool
23224 aarch64_sve_float_mul_immediate_p (rtx x)
23225 {
23226 rtx elt;
23227
23228 return (GET_MODE_INNER (GET_MODE (x)) != BFmode
23229 && const_vec_duplicate_p (x, &elt)
23230 && CONST_DOUBLE_P (elt)
23231 && (real_equal (CONST_DOUBLE_REAL_VALUE (elt), &dconsthalf)
23232 || real_equal (CONST_DOUBLE_REAL_VALUE (elt), &dconst2)));
23233 }
23234
23235 /* Return true if replicating VAL32 is a valid 2-byte or 4-byte immediate
23236 for the Advanced SIMD operation described by WHICH and INSN. If INFO
23237 is nonnull, use it to describe valid immediates. */
23238 static bool
23239 aarch64_advsimd_valid_immediate_hs (unsigned int val32,
23240 simd_immediate_info *info,
23241 enum simd_immediate_check which,
23242 simd_immediate_info::insn_type insn)
23243 {
23244 /* Try a 4-byte immediate with LSL. */
23245 for (unsigned int shift = 0; shift < 32; shift += 8)
23246 if ((val32 & (0xff << shift)) == val32)
23247 {
23248 if (info)
23249 *info = simd_immediate_info (SImode, val32 >> shift, insn,
23250 simd_immediate_info::LSL, shift);
23251 return true;
23252 }
23253
23254 /* Try a 2-byte immediate with LSL. */
23255 unsigned int imm16 = val32 & 0xffff;
23256 if (imm16 == (val32 >> 16))
23257 for (unsigned int shift = 0; shift < 16; shift += 8)
23258 if ((imm16 & (0xff << shift)) == imm16)
23259 {
23260 if (info)
23261 *info = simd_immediate_info (HImode, imm16 >> shift, insn,
23262 simd_immediate_info::LSL, shift);
23263 return true;
23264 }
23265
23266 /* Try a 4-byte immediate with MSL, except for cases that MVN
23267 can handle. */
23268 if (which == AARCH64_CHECK_MOV)
23269 for (unsigned int shift = 8; shift < 24; shift += 8)
23270 {
23271 unsigned int low = (1 << shift) - 1;
23272 if (((val32 & (0xff << shift)) | low) == val32)
23273 {
23274 if (info)
23275 *info = simd_immediate_info (SImode, val32 >> shift, insn,
23276 simd_immediate_info::MSL, shift);
23277 return true;
23278 }
23279 }
23280
23281 return false;
23282 }
23283
23284 /* Return true if replicating VAL64 with mode MODE is a valid immediate for the
23285 Advanced SIMD operation described by WHICH. If INFO is nonnull,
23286 use it to describe valid immediates. */
23287 static bool
23288 aarch64_advsimd_valid_immediate (unsigned HOST_WIDE_INT val64,
23289 scalar_int_mode mode,
23290 simd_immediate_info *info,
23291 enum simd_immediate_check which)
23292 {
23293 unsigned int val32 = val64 & 0xffffffff;
23294 unsigned int val8 = val64 & 0xff;
23295
23296 if (mode != DImode)
23297 {
23298 if ((which == AARCH64_CHECK_MOV || which == AARCH64_CHECK_ORR)
23299 && aarch64_advsimd_valid_immediate_hs (val32, info, which,
23300 simd_immediate_info::MOV))
23301 return true;
23302
23303 if ((which == AARCH64_CHECK_MOV || which == AARCH64_CHECK_AND)
23304 && aarch64_advsimd_valid_immediate_hs (~val32, info, which,
23305 simd_immediate_info::MVN))
23306 return true;
23307
23308 /* Try using a replicated byte. */
23309 if (which == AARCH64_CHECK_MOV && mode == QImode)
23310 {
23311 if (info)
23312 *info = simd_immediate_info (QImode, val8);
23313 return true;
23314 }
23315 }
23316
23317 /* Try using a bit-to-bytemask. */
23318 if (which == AARCH64_CHECK_MOV)
23319 {
23320 unsigned int i;
23321 for (i = 0; i < 64; i += 8)
23322 {
23323 unsigned char byte = (val64 >> i) & 0xff;
23324 if (byte != 0 && byte != 0xff)
23325 break;
23326 }
23327 if (i == 64)
23328 {
23329 if (info)
23330 *info = simd_immediate_info (DImode, val64);
23331 return true;
23332 }
23333 }
23334 return false;
23335 }
23336
23337 /* Return true if replicating IVAL with MODE gives a valid immediate for an SVE
23338 MOV instruction. If INFO is nonnull, use it to describe valid
23339 immediates. */
23340
23341 static bool
23342 aarch64_sve_valid_immediate (unsigned HOST_WIDE_INT ival, scalar_int_mode mode,
23343 simd_immediate_info *info,
23344 enum simd_immediate_check which)
23345 {
23346 HOST_WIDE_INT val = trunc_int_for_mode (ival, mode);
23347
23348 if (which == AARCH64_CHECK_MOV)
23349 {
23350 if (IN_RANGE (val, -0x80, 0x7f))
23351 {
23352 /* DUP with no shift. */
23353 if (info)
23354 *info = simd_immediate_info (mode, val,
23355 simd_immediate_info::SVE_MOV);
23356 return true;
23357 }
23358 if ((val & 0xff) == 0 && IN_RANGE (val, -0x8000, 0x7f00))
23359 {
23360 /* DUP with LSL #8. */
23361 if (info)
23362 *info = simd_immediate_info (mode, val,
23363 simd_immediate_info::SVE_MOV);
23364 return true;
23365 }
23366 }
23367 if (aarch64_bitmask_imm (ival, mode))
23368 {
23369 /* DUPM. */
23370 if (info)
23371 *info = simd_immediate_info (mode, val, simd_immediate_info::SVE_MOV);
23372 return true;
23373 }
23374 return false;
23375 }
23376
23377 /* Return true if X is an UNSPEC_PTRUE constant of the form:
23378
23379 (const (unspec [PATTERN ZERO] UNSPEC_PTRUE))
23380
23381 where PATTERN is the svpattern as a CONST_INT and where ZERO
23382 is a zero constant of the required PTRUE mode (which can have
23383 fewer elements than X's mode, if zero bits are significant).
23384
23385 If so, and if INFO is nonnull, describe the immediate in INFO. */
23386 bool
23387 aarch64_sve_ptrue_svpattern_p (rtx x, struct simd_immediate_info *info)
23388 {
23389 if (GET_CODE (x) != CONST)
23390 return false;
23391
23392 x = XEXP (x, 0);
23393 if (GET_CODE (x) != UNSPEC || XINT (x, 1) != UNSPEC_PTRUE)
23394 return false;
23395
23396 if (info)
23397 {
23398 aarch64_svpattern pattern
23399 = (aarch64_svpattern) INTVAL (XVECEXP (x, 0, 0));
23400 machine_mode pred_mode = GET_MODE (XVECEXP (x, 0, 1));
23401 scalar_int_mode int_mode = aarch64_sve_element_int_mode (pred_mode);
23402 *info = simd_immediate_info (int_mode, pattern);
23403 }
23404 return true;
23405 }
23406
23407 /* Return true if X is a valid SVE predicate. If INFO is nonnull, use
23408 it to describe valid immediates. */
23409
23410 static bool
23411 aarch64_sve_pred_valid_immediate (rtx x, simd_immediate_info *info)
23412 {
23413 if (aarch64_sve_ptrue_svpattern_p (x, info))
23414 return true;
23415
23416 if (x == CONST0_RTX (GET_MODE (x)))
23417 {
23418 if (info)
23419 *info = simd_immediate_info (DImode, 0);
23420 return true;
23421 }
23422
23423 /* Analyze the value as a VNx16BImode. This should be relatively
23424 efficient, since rtx_vector_builder has enough built-in capacity
23425 to store all VLA predicate constants without needing the heap. */
23426 rtx_vector_builder builder;
23427 if (!aarch64_get_sve_pred_bits (builder, x))
23428 return false;
23429
23430 unsigned int elt_size = aarch64_widest_sve_pred_elt_size (builder);
23431 if (int vl = aarch64_partial_ptrue_length (builder, elt_size))
23432 {
23433 machine_mode mode = aarch64_sve_pred_mode (elt_size).require ();
23434 aarch64_svpattern pattern = aarch64_svpattern_for_vl (mode, vl);
23435 if (pattern != AARCH64_NUM_SVPATTERNS)
23436 {
23437 if (info)
23438 {
23439 scalar_int_mode int_mode = aarch64_sve_element_int_mode (mode);
23440 *info = simd_immediate_info (int_mode, pattern);
23441 }
23442 return true;
23443 }
23444 }
23445 return false;
23446 }
23447
23448 /* We can only represent floating point constants which will fit in
23449 "quarter-precision" values. These values are characterised by
23450 a sign bit, a 4-bit mantissa and a 3-bit exponent. And are given
23451 by:
23452
23453 (-1)^s * (n/16) * 2^r
23454
23455 Where:
23456 's' is the sign bit.
23457 'n' is an integer in the range 16 <= n <= 31.
23458 'r' is an integer in the range -3 <= r <= 4.
23459
23460 Return true iff R represents a vale encodable into an AArch64 floating point
23461 move instruction as an immediate. Othewise false. */
23462
23463 static bool
23464 aarch64_real_float_const_representable_p (REAL_VALUE_TYPE r)
23465 {
23466 /* This represents our current view of how many bits
23467 make up the mantissa. */
23468 int point_pos = 2 * HOST_BITS_PER_WIDE_INT - 1;
23469 int exponent;
23470 unsigned HOST_WIDE_INT mantissa, mask;
23471 REAL_VALUE_TYPE m;
23472 bool fail = false;
23473
23474 /* We cannot represent infinities, NaNs or +/-zero. We won't
23475 know if we have +zero until we analyse the mantissa, but we
23476 can reject the other invalid values. */
23477 if (REAL_VALUE_ISINF (r) || REAL_VALUE_ISNAN (r)
23478 || REAL_VALUE_MINUS_ZERO (r))
23479 return false;
23480
23481 /* Extract exponent. */
23482 r = real_value_abs (&r);
23483 exponent = REAL_EXP (&r);
23484
23485 /* For the mantissa, we expand into two HOST_WIDE_INTS, apart from the
23486 highest (sign) bit, with a fixed binary point at bit point_pos.
23487 m1 holds the low part of the mantissa, m2 the high part.
23488 WARNING: If we ever have a representation using more than 2 * H_W_I - 1
23489 bits for the mantissa, this can fail (low bits will be lost). */
23490 real_ldexp (&m, &r, point_pos - exponent);
23491 wide_int w = real_to_integer (&m, &fail, HOST_BITS_PER_WIDE_INT * 2);
23492
23493 /* If the low part of the mantissa has bits set we cannot represent
23494 the value. */
23495 if (fail || w.ulow () != 0)
23496 return false;
23497
23498 /* We have rejected the lower HOST_WIDE_INT, so update our
23499 understanding of how many bits lie in the mantissa and
23500 look only at the high HOST_WIDE_INT. */
23501 mantissa = w.elt (1);
23502 point_pos -= HOST_BITS_PER_WIDE_INT;
23503
23504 /* We can only represent values with a mantissa of the form 1.xxxx. */
23505 mask = ((unsigned HOST_WIDE_INT)1 << (point_pos - 5)) - 1;
23506 if ((mantissa & mask) != 0)
23507 return false;
23508
23509 /* Having filtered unrepresentable values, we may now remove all
23510 but the highest 5 bits. */
23511 mantissa >>= point_pos - 5;
23512
23513 /* We cannot represent the value 0.0, so reject it. This is handled
23514 elsewhere. */
23515 if (mantissa == 0)
23516 return false;
23517
23518 /* Then, as bit 4 is always set, we can mask it off, leaving
23519 the mantissa in the range [0, 15]. */
23520 mantissa &= ~(1 << 4);
23521 gcc_assert (mantissa <= 15);
23522
23523 /* GCC internally does not use IEEE754-like encoding (where normalized
23524 significands are in the range [1, 2). GCC uses [0.5, 1) (see real.cc).
23525 Our mantissa values are shifted 4 places to the left relative to
23526 normalized IEEE754 so we must modify the exponent returned by REAL_EXP
23527 by 5 places to correct for GCC's representation. */
23528 exponent = 5 - exponent;
23529
23530 return (exponent >= 0 && exponent <= 7);
23531 }
23532
23533 /* Return true if OP is a valid SIMD immediate for the operation
23534 described by WHICH. If INFO is nonnull, use it to describe valid
23535 immediates. */
23536 static bool
23537 aarch64_simd_valid_imm (rtx op, simd_immediate_info *info,
23538 enum simd_immediate_check which)
23539 {
23540 machine_mode mode = GET_MODE (op);
23541 unsigned int vec_flags = aarch64_classify_vector_mode (mode);
23542 if (vec_flags == 0 || vec_flags == (VEC_ADVSIMD | VEC_STRUCT))
23543 return false;
23544
23545 if ((vec_flags & VEC_ADVSIMD) && !TARGET_SIMD)
23546 return false;
23547
23548 if (vec_flags == (VEC_SVE_PRED | VEC_STRUCT))
23549 return op == CONST0_RTX (mode) || op == CONSTM1_RTX (mode);
23550
23551 if (vec_flags & VEC_SVE_PRED)
23552 return aarch64_sve_pred_valid_immediate (op, info);
23553
23554 scalar_mode elt_mode = GET_MODE_INNER (mode);
23555 rtx base, step;
23556 unsigned int n_elts;
23557 if (CONST_VECTOR_P (op)
23558 && CONST_VECTOR_DUPLICATE_P (op))
23559 n_elts = CONST_VECTOR_NPATTERNS (op);
23560 else if (which == AARCH64_CHECK_MOV
23561 && TARGET_SVE
23562 && aarch64_sve_index_series_p (op, &base, &step))
23563 {
23564 if (info)
23565 {
23566 /* Get the corresponding container mode. E.g. an INDEX on V2SI
23567 should yield two integer values per 128-bit block, meaning
23568 that we need to treat it in the same way as V2DI and then
23569 ignore the upper 32 bits of each element. */
23570 elt_mode = aarch64_sve_container_int_mode (mode);
23571 *info = simd_immediate_info (elt_mode, base, step);
23572 }
23573 return true;
23574 }
23575 else if (CONST_VECTOR_P (op)
23576 && CONST_VECTOR_NUNITS (op).is_constant (&n_elts))
23577 /* N_ELTS set above. */;
23578 else
23579 return false;
23580
23581 /* If all elements in an SVE vector have the same value, we have a free
23582 choice between using the element mode and using the container mode.
23583 Using the element mode means that unused parts of the vector are
23584 duplicates of the used elements, while using the container mode means
23585 that the unused parts are an extension of the used elements. Using the
23586 element mode is better for (say) VNx4HI 0x101, since 0x01010101 is valid
23587 for its container mode VNx4SI while 0x00000101 isn't.
23588
23589 If not all elements in an SVE vector have the same value, we need the
23590 transition from one element to the next to occur at container boundaries.
23591 E.g. a fixed-length VNx4HI containing { 1, 2, 3, 4 } should be treated
23592 in the same way as a VNx4SI containing { 1, 2, 3, 4 }. */
23593 scalar_int_mode elt_int_mode;
23594 if ((vec_flags & VEC_SVE_DATA) && n_elts > 1)
23595 elt_int_mode = aarch64_sve_container_int_mode (mode);
23596 else
23597 elt_int_mode = int_mode_for_mode (elt_mode).require ();
23598
23599 unsigned int elt_size = GET_MODE_SIZE (elt_int_mode);
23600 if (elt_size > 8)
23601 return false;
23602
23603 /* Expand the vector constant out into a byte vector, with the least
23604 significant byte of the register first. */
23605 auto_vec<unsigned char, 16> bytes;
23606 bytes.reserve (n_elts * elt_size);
23607 for (unsigned int i = 0; i < n_elts; i++)
23608 {
23609 /* The vector is provided in gcc endian-neutral fashion.
23610 For aarch64_be Advanced SIMD, it must be laid out in the vector
23611 register in reverse order. */
23612 bool swap_p = ((vec_flags & VEC_ADVSIMD) != 0 && BYTES_BIG_ENDIAN);
23613 rtx elt = CONST_VECTOR_ELT (op, swap_p ? (n_elts - 1 - i) : i);
23614
23615 if (elt_mode != elt_int_mode)
23616 elt = gen_lowpart (elt_int_mode, elt);
23617
23618 if (!CONST_INT_P (elt))
23619 return false;
23620
23621 unsigned HOST_WIDE_INT elt_val = INTVAL (elt);
23622 for (unsigned int byte = 0; byte < elt_size; byte++)
23623 {
23624 bytes.quick_push (elt_val & 0xff);
23625 elt_val >>= BITS_PER_UNIT;
23626 }
23627 }
23628
23629 /* The immediate must repeat every eight bytes. */
23630 unsigned int nbytes = bytes.length ();
23631 for (unsigned i = 8; i < nbytes; ++i)
23632 if (bytes[i] != bytes[i - 8])
23633 return false;
23634
23635 /* Get the repeating 8-byte value as an integer. No endian correction
23636 is needed here because bytes is already in lsb-first order. */
23637 unsigned HOST_WIDE_INT val64 = 0;
23638 for (unsigned int i = 0; i < 8; i++)
23639 val64 |= ((unsigned HOST_WIDE_INT) bytes[i % nbytes]
23640 << (i * BITS_PER_UNIT));
23641
23642 /* Try encoding the integer immediate as a floating point value if it's an
23643 exact value. */
23644 scalar_float_mode fmode = DFmode;
23645 scalar_int_mode imode = DImode;
23646 unsigned HOST_WIDE_INT ival = val64;
23647 unsigned int val32 = val64 & 0xffffffff;
23648 if (val32 == (val64 >> 32))
23649 {
23650 fmode = SFmode;
23651 imode = SImode;
23652 ival = val32;
23653 unsigned int val16 = val32 & 0xffff;
23654 if (val16 == (val32 >> 16))
23655 {
23656 fmode = HFmode;
23657 imode = HImode;
23658 ival = val16;
23659 unsigned int val8 = val16 & 0xff;
23660 if (val8 == (val16 >> 8))
23661 {
23662 imode = QImode;
23663 ival = val8;
23664 }
23665 }
23666 }
23667
23668 if (which == AARCH64_CHECK_MOV
23669 && imode != QImode
23670 && (imode != HImode || TARGET_FP_F16INST))
23671 {
23672 long int as_long_ints[2];
23673 as_long_ints[0] = ival & 0xFFFFFFFF;
23674 as_long_ints[1] = (ival >> 32) & 0xFFFFFFFF;
23675 if (imode == DImode && FLOAT_WORDS_BIG_ENDIAN)
23676 std::swap (as_long_ints[0], as_long_ints[1]);
23677
23678 REAL_VALUE_TYPE r;
23679 real_from_target (&r, as_long_ints, fmode);
23680 if (aarch64_real_float_const_representable_p (r))
23681 {
23682 if (info)
23683 {
23684 rtx float_val = const_double_from_real_value (r, fmode);
23685 *info = simd_immediate_info (fmode, float_val);
23686 }
23687 return true;
23688 }
23689 }
23690
23691 if (vec_flags & VEC_SVE_DATA)
23692 return aarch64_sve_valid_immediate (ival, imode, info, which);
23693
23694 if (aarch64_advsimd_valid_immediate (val64, imode, info, which))
23695 return true;
23696
23697 if (TARGET_SVE)
23698 return aarch64_sve_valid_immediate (ival, imode, info, which);
23699 return false;
23700 }
23701
23702 /* Return true if OP is a valid SIMD move immediate for SVE or AdvSIMD. */
23703 bool
23704 aarch64_simd_valid_mov_imm (rtx op)
23705 {
23706 return aarch64_simd_valid_imm (op, NULL, AARCH64_CHECK_MOV);
23707 }
23708
23709 /* Return true if OP is a valid SIMD orr immediate for SVE or AdvSIMD. */
23710 bool
23711 aarch64_simd_valid_orr_imm (rtx op)
23712 {
23713 return aarch64_simd_valid_imm (op, NULL, AARCH64_CHECK_ORR);
23714 }
23715
23716 /* Return true if OP is a valid SIMD and immediate for SVE or AdvSIMD. */
23717 bool
23718 aarch64_simd_valid_and_imm (rtx op)
23719 {
23720 return aarch64_simd_valid_imm (op, NULL, AARCH64_CHECK_AND);
23721 }
23722
23723 /* Return true if OP is a valid SIMD xor immediate for SVE. */
23724 bool
23725 aarch64_simd_valid_xor_imm (rtx op)
23726 {
23727 return aarch64_simd_valid_imm (op, NULL, AARCH64_CHECK_XOR);
23728 }
23729
23730 /* Check whether X is a VEC_SERIES-like constant that starts at 0 and
23731 has a step in the range of INDEX. Return the index expression if so,
23732 otherwise return null. */
23733 rtx
23734 aarch64_check_zero_based_sve_index_immediate (rtx x)
23735 {
23736 rtx base, step;
23737 if (const_vec_series_p (x, &base, &step)
23738 && base == const0_rtx
23739 && aarch64_sve_index_immediate_p (step))
23740 return step;
23741 return NULL_RTX;
23742 }
23743
23744 /* Check of immediate shift constants are within range. */
23745 bool
23746 aarch64_simd_shift_imm_p (rtx x, machine_mode mode, bool left)
23747 {
23748 x = unwrap_const_vec_duplicate (x);
23749 if (!CONST_INT_P (x))
23750 return false;
23751 int bit_width = GET_MODE_UNIT_SIZE (mode) * BITS_PER_UNIT;
23752 if (left)
23753 return IN_RANGE (INTVAL (x), 0, bit_width - 1);
23754 else
23755 return IN_RANGE (INTVAL (x), 1, bit_width);
23756 }
23757
23758 /* Return the bitmask CONST_INT to select the bits required by a zero extract
23759 operation of width WIDTH at bit position POS. */
23760
23761 rtx
23762 aarch64_mask_from_zextract_ops (rtx width, rtx pos)
23763 {
23764 gcc_assert (CONST_INT_P (width));
23765 gcc_assert (CONST_INT_P (pos));
23766
23767 unsigned HOST_WIDE_INT mask
23768 = ((unsigned HOST_WIDE_INT) 1 << UINTVAL (width)) - 1;
23769 return GEN_INT (mask << UINTVAL (pos));
23770 }
23771
23772 bool
23773 aarch64_mov_operand_p (rtx x, machine_mode mode)
23774 {
23775 if (GET_CODE (x) == HIGH
23776 && aarch64_valid_symref (XEXP (x, 0), GET_MODE (XEXP (x, 0))))
23777 return true;
23778
23779 if (CONST_INT_P (x))
23780 return true;
23781
23782 if (VECTOR_MODE_P (GET_MODE (x)))
23783 {
23784 /* Require predicate constants to be VNx16BI before RA, so that we
23785 force everything to have a canonical form. */
23786 if (!lra_in_progress
23787 && !reload_completed
23788 && aarch64_sve_pred_mode_p (GET_MODE (x))
23789 && known_eq (GET_MODE_SIZE (GET_MODE (x)), BYTES_PER_SVE_PRED)
23790 && GET_MODE (x) != VNx16BImode)
23791 return false;
23792
23793 return aarch64_simd_valid_mov_imm (x);
23794 }
23795
23796 /* Remove UNSPEC_SALT_ADDR before checking symbol reference. */
23797 x = strip_salt (x);
23798
23799 /* GOT accesses are valid moves. */
23800 if (SYMBOL_REF_P (x)
23801 && aarch64_classify_symbolic_expression (x) == SYMBOL_SMALL_GOT_4G)
23802 return true;
23803
23804 if (SYMBOL_REF_P (x) && mode == DImode && CONSTANT_ADDRESS_P (x))
23805 return true;
23806
23807 if (TARGET_SVE
23808 && (aarch64_sve_cnt_immediate_p (x)
23809 || aarch64_sve_rdvl_immediate_p (x)))
23810 return true;
23811
23812 if (aarch64_rdsvl_immediate_p (x))
23813 return true;
23814
23815 return aarch64_classify_symbolic_expression (x)
23816 == SYMBOL_TINY_ABSOLUTE;
23817 }
23818
23819 /* Return a function-invariant register that contains VALUE. *CACHED_INSN
23820 caches instructions that set up such registers, so that they can be
23821 reused by future calls. */
23822
23823 static rtx
23824 aarch64_get_shareable_reg (rtx_insn **cached_insn, rtx value)
23825 {
23826 rtx_insn *insn = *cached_insn;
23827 if (insn && INSN_P (insn) && !insn->deleted ())
23828 {
23829 rtx pat = PATTERN (insn);
23830 if (GET_CODE (pat) == SET)
23831 {
23832 rtx dest = SET_DEST (pat);
23833 if (REG_P (dest)
23834 && !HARD_REGISTER_P (dest)
23835 && rtx_equal_p (SET_SRC (pat), value))
23836 return dest;
23837 }
23838 }
23839 rtx reg = gen_reg_rtx (GET_MODE (value));
23840 *cached_insn = emit_insn_before (gen_rtx_SET (reg, value),
23841 function_beg_insn);
23842 return reg;
23843 }
23844
23845 /* Create a 0 constant that is based on V4SI to allow CSE to optimally share
23846 the constant creation. */
23847
23848 rtx
23849 aarch64_gen_shareable_zero (machine_mode mode)
23850 {
23851 rtx reg = aarch64_get_shareable_reg (&cfun->machine->advsimd_zero_insn,
23852 CONST0_RTX (V4SImode));
23853 return lowpart_subreg (mode, reg, GET_MODE (reg));
23854 }
23855
23856 /* INSN is some form of extension or shift that can be split into a
23857 permutation involving a shared zero. Return true if we should
23858 perform such a split.
23859
23860 ??? For now, make sure that the split instruction executes more
23861 frequently than the zero that feeds it. In future it would be good
23862 to split without that restriction and instead recombine shared zeros
23863 if they turn out not to be worthwhile. This would allow splits in
23864 single-block functions and would also cope more naturally with
23865 rematerialization. The downside of not doing this is that we lose the
23866 optimizations for vector epilogues as well. */
23867
23868 bool
23869 aarch64_split_simd_shift_p (rtx_insn *insn)
23870 {
23871 return (can_create_pseudo_p ()
23872 && optimize_bb_for_speed_p (BLOCK_FOR_INSN (insn))
23873 && (ENTRY_BLOCK_PTR_FOR_FN (cfun)->count
23874 < BLOCK_FOR_INSN (insn)->count));
23875 }
23876
23877 /* Return a const_int vector of VAL. */
23878 rtx
23879 aarch64_simd_gen_const_vector_dup (machine_mode mode, HOST_WIDE_INT val)
23880 {
23881 rtx c = gen_int_mode (val, GET_MODE_INNER (mode));
23882 return gen_const_vec_duplicate (mode, c);
23883 }
23884
23885 /* Check OP is a legal scalar immediate for the MOVI instruction. */
23886
23887 bool
23888 aarch64_simd_scalar_immediate_valid_for_move (rtx op, scalar_int_mode mode)
23889 {
23890 machine_mode vmode;
23891
23892 vmode = aarch64_simd_container_mode (mode, 64);
23893 rtx op_v = aarch64_simd_gen_const_vector_dup (vmode, INTVAL (op));
23894 return aarch64_simd_valid_mov_imm (op_v);
23895 }
23896
23897 /* Construct and return a PARALLEL RTX vector with elements numbering the
23898 lanes of either the high (HIGH == TRUE) or low (HIGH == FALSE) half of
23899 the vector - from the perspective of the architecture. This does not
23900 line up with GCC's perspective on lane numbers, so we end up with
23901 different masks depending on our target endian-ness. The diagram
23902 below may help. We must draw the distinction when building masks
23903 which select one half of the vector. An instruction selecting
23904 architectural low-lanes for a big-endian target, must be described using
23905 a mask selecting GCC high-lanes.
23906
23907 Big-Endian Little-Endian
23908
23909 GCC 0 1 2 3 3 2 1 0
23910 | x | x | x | x | | x | x | x | x |
23911 Architecture 3 2 1 0 3 2 1 0
23912
23913 Low Mask: { 2, 3 } { 0, 1 }
23914 High Mask: { 0, 1 } { 2, 3 }
23915
23916 MODE Is the mode of the vector and NUNITS is the number of units in it. */
23917
23918 rtx
23919 aarch64_simd_vect_par_cnst_half (machine_mode mode, int nunits, bool high)
23920 {
23921 rtvec v = rtvec_alloc (nunits / 2);
23922 int high_base = nunits / 2;
23923 int low_base = 0;
23924 int base;
23925 rtx t1;
23926 int i;
23927
23928 if (BYTES_BIG_ENDIAN)
23929 base = high ? low_base : high_base;
23930 else
23931 base = high ? high_base : low_base;
23932
23933 for (i = 0; i < nunits / 2; i++)
23934 RTVEC_ELT (v, i) = GEN_INT (base + i);
23935
23936 t1 = gen_rtx_PARALLEL (mode, v);
23937 return t1;
23938 }
23939
23940 /* Check OP for validity as a PARALLEL RTX vector with elements
23941 numbering the lanes of either the high (HIGH == TRUE) or low lanes,
23942 from the perspective of the architecture. See the diagram above
23943 aarch64_simd_vect_par_cnst_half for more details. */
23944
23945 bool
23946 aarch64_simd_check_vect_par_cnst_half (rtx op, machine_mode mode,
23947 bool high)
23948 {
23949 int nelts;
23950 if (!VECTOR_MODE_P (mode) || !GET_MODE_NUNITS (mode).is_constant (&nelts))
23951 return false;
23952
23953 rtx ideal = aarch64_simd_vect_par_cnst_half (mode, nelts, high);
23954 HOST_WIDE_INT count_op = XVECLEN (op, 0);
23955 HOST_WIDE_INT count_ideal = XVECLEN (ideal, 0);
23956 int i = 0;
23957
23958 if (count_op != count_ideal)
23959 return false;
23960
23961 for (i = 0; i < count_ideal; i++)
23962 {
23963 rtx elt_op = XVECEXP (op, 0, i);
23964 rtx elt_ideal = XVECEXP (ideal, 0, i);
23965
23966 if (!CONST_INT_P (elt_op)
23967 || INTVAL (elt_ideal) != INTVAL (elt_op))
23968 return false;
23969 }
23970 return true;
23971 }
23972
23973 /* Return a PARALLEL containing NELTS elements, with element I equal
23974 to BASE + I * STEP. */
23975
23976 rtx
23977 aarch64_gen_stepped_int_parallel (unsigned int nelts, int base, int step)
23978 {
23979 rtvec vec = rtvec_alloc (nelts);
23980 for (unsigned int i = 0; i < nelts; ++i)
23981 RTVEC_ELT (vec, i) = gen_int_mode (base + i * step, DImode);
23982 return gen_rtx_PARALLEL (VOIDmode, vec);
23983 }
23984
23985 /* Return true if OP is a PARALLEL of CONST_INTs that form a linear
23986 series with step STEP. */
23987
23988 bool
23989 aarch64_stepped_int_parallel_p (rtx op, int step)
23990 {
23991 if (GET_CODE (op) != PARALLEL || !CONST_INT_P (XVECEXP (op, 0, 0)))
23992 return false;
23993
23994 unsigned HOST_WIDE_INT base = UINTVAL (XVECEXP (op, 0, 0));
23995 for (int i = 1; i < XVECLEN (op, 0); ++i)
23996 if (!CONST_INT_P (XVECEXP (op, 0, i))
23997 || UINTVAL (XVECEXP (op, 0, i)) != base + i * step)
23998 return false;
23999
24000 return true;
24001 }
24002
24003 /* Return true if OPERANDS[0] to OPERANDS[NUM_OPERANDS - 1] form a
24004 sequence of strided registers, with the stride being equal STRIDE.
24005 The operands are already known to be FPRs. */
24006 bool
24007 aarch64_strided_registers_p (rtx *operands, unsigned int num_operands,
24008 unsigned int stride)
24009 {
24010 for (unsigned int i = 1; i < num_operands; ++i)
24011 if (REGNO (operands[i]) != REGNO (operands[0]) + i * stride)
24012 return false;
24013 return true;
24014 }
24015
24016 /* Bounds-check lanes. Ensure OPERAND lies between LOW (inclusive) and
24017 HIGH (exclusive). */
24018 void
24019 aarch64_simd_lane_bounds (rtx operand, HOST_WIDE_INT low, HOST_WIDE_INT high,
24020 const_tree exp)
24021 {
24022 HOST_WIDE_INT lane;
24023 gcc_assert (CONST_INT_P (operand));
24024 lane = INTVAL (operand);
24025
24026 if (lane < low || lane >= high)
24027 {
24028 if (exp)
24029 error_at (EXPR_LOCATION (exp), "lane %wd out of range %wd - %wd",
24030 lane, low, high - 1);
24031 else
24032 error ("lane %wd out of range %wd - %wd", lane, low, high - 1);
24033 }
24034 }
24035
24036 /* Peform endian correction on lane number N, which indexes a vector
24037 of mode MODE, and return the result as an SImode rtx. */
24038
24039 rtx
24040 aarch64_endian_lane_rtx (machine_mode mode, unsigned int n)
24041 {
24042 return gen_int_mode (ENDIAN_LANE_N (GET_MODE_NUNITS (mode), n), SImode);
24043 }
24044
24045 /* Return TRUE if OP is a valid vector addressing mode. */
24046
24047 bool
24048 aarch64_simd_mem_operand_p (rtx op)
24049 {
24050 return (MEM_P (op)
24051 && (GET_CODE (XEXP (op, 0)) == POST_INC || REG_P (XEXP (op, 0)))
24052 && memory_operand (op, VOIDmode));
24053 }
24054
24055 /* Return true if OP is a valid MEM operand for an SVE LD1R instruction. */
24056
24057 bool
24058 aarch64_sve_ld1r_operand_p (rtx op)
24059 {
24060 struct aarch64_address_info addr;
24061 scalar_mode mode;
24062
24063 return (MEM_P (op)
24064 && is_a <scalar_mode> (GET_MODE (op), &mode)
24065 && aarch64_classify_address (&addr, XEXP (op, 0), mode, false)
24066 && addr.type == ADDRESS_REG_IMM
24067 && offset_6bit_unsigned_scaled_p (mode, addr.const_offset));
24068 }
24069
24070 /* Return true if OP is a valid MEM operand for an SVE LD1R{Q,O} instruction
24071 where the size of the read data is specified by `mode` and the size of the
24072 vector elements are specified by `elem_mode`. */
24073 bool
24074 aarch64_sve_ld1rq_ld1ro_operand_p (rtx op, machine_mode mode,
24075 scalar_mode elem_mode)
24076 {
24077 struct aarch64_address_info addr;
24078 if (!MEM_P (op)
24079 || !aarch64_classify_address (&addr, XEXP (op, 0), elem_mode, false))
24080 return false;
24081
24082 if (addr.type == ADDRESS_REG_IMM)
24083 return offset_4bit_signed_scaled_p (mode, addr.const_offset);
24084
24085 if (addr.type == ADDRESS_REG_REG)
24086 return (1U << addr.shift) == GET_MODE_SIZE (elem_mode);
24087
24088 return false;
24089 }
24090
24091 /* Return true if OP is a valid MEM operand for an SVE LD1RQ instruction. */
24092 bool
24093 aarch64_sve_ld1rq_operand_p (rtx op)
24094 {
24095 return aarch64_sve_ld1rq_ld1ro_operand_p (op, TImode,
24096 GET_MODE_INNER (GET_MODE (op)));
24097 }
24098
24099 /* Return true if OP is a valid MEM operand for an SVE LD1RO instruction for
24100 accessing a vector where the element size is specified by `elem_mode`. */
24101 bool
24102 aarch64_sve_ld1ro_operand_p (rtx op, scalar_mode elem_mode)
24103 {
24104 return aarch64_sve_ld1rq_ld1ro_operand_p (op, OImode, elem_mode);
24105 }
24106
24107 /* Return true if OP is a valid MEM operand for an SVE LDFF1 instruction. */
24108 bool
24109 aarch64_sve_ldff1_operand_p (rtx op)
24110 {
24111 if (!MEM_P (op))
24112 return false;
24113
24114 struct aarch64_address_info addr;
24115 if (!aarch64_classify_address (&addr, XEXP (op, 0), GET_MODE (op), false))
24116 return false;
24117
24118 if (addr.type == ADDRESS_REG_IMM)
24119 return known_eq (addr.const_offset, 0);
24120
24121 return addr.type == ADDRESS_REG_REG;
24122 }
24123
24124 /* Return true if OP is a valid MEM operand for an SVE LDNF1 instruction. */
24125 bool
24126 aarch64_sve_ldnf1_operand_p (rtx op)
24127 {
24128 struct aarch64_address_info addr;
24129
24130 return (MEM_P (op)
24131 && aarch64_classify_address (&addr, XEXP (op, 0),
24132 GET_MODE (op), false)
24133 && addr.type == ADDRESS_REG_IMM);
24134 }
24135
24136 /* Return true if OP is a valid MEM operand for an SVE LDR instruction.
24137 The conditions for STR are the same. */
24138 bool
24139 aarch64_sve_ldr_operand_p (rtx op)
24140 {
24141 struct aarch64_address_info addr;
24142
24143 return (MEM_P (op)
24144 && aarch64_classify_address (&addr, XEXP (op, 0), GET_MODE (op),
24145 false, ADDR_QUERY_ANY)
24146 && addr.type == ADDRESS_REG_IMM);
24147 }
24148
24149 /* Return true if OP is a valid address for an SVE PRF[BHWD] instruction,
24150 addressing memory of mode MODE. */
24151 bool
24152 aarch64_sve_prefetch_operand_p (rtx op, machine_mode mode)
24153 {
24154 struct aarch64_address_info addr;
24155 if (!aarch64_classify_address (&addr, op, mode, false, ADDR_QUERY_ANY))
24156 return false;
24157
24158 if (addr.type == ADDRESS_REG_IMM)
24159 return offset_6bit_signed_scaled_p (mode, addr.const_offset);
24160
24161 return addr.type == ADDRESS_REG_REG;
24162 }
24163
24164 /* Return true if OP is a valid MEM operand for an SVE_STRUCT mode.
24165 We need to be able to access the individual pieces, so the range
24166 is different from LD[234] and ST[234]. */
24167 bool
24168 aarch64_sve_struct_memory_operand_p (rtx op)
24169 {
24170 if (!MEM_P (op))
24171 return false;
24172
24173 machine_mode mode = GET_MODE (op);
24174 struct aarch64_address_info addr;
24175 if (!aarch64_classify_address (&addr, XEXP (op, 0), SVE_BYTE_MODE, false,
24176 ADDR_QUERY_ANY)
24177 || addr.type != ADDRESS_REG_IMM)
24178 return false;
24179
24180 poly_int64 first = addr.const_offset;
24181 poly_int64 last = first + GET_MODE_SIZE (mode) - BYTES_PER_SVE_VECTOR;
24182 return (offset_4bit_signed_scaled_p (SVE_BYTE_MODE, first)
24183 && offset_4bit_signed_scaled_p (SVE_BYTE_MODE, last));
24184 }
24185
24186 /* Return true if OFFSET is a constant integer and if VNUM is
24187 OFFSET * the number of bytes in an SVE vector. This is the requirement
24188 that exists in SME LDR and STR instructions, where the VL offset must
24189 equal the ZA slice offset. */
24190 bool
24191 aarch64_sme_ldr_vnum_offset_p (rtx offset, rtx vnum)
24192 {
24193 if (!CONST_INT_P (offset) || !IN_RANGE (INTVAL (offset), 0, 15))
24194 return false;
24195
24196 if (TARGET_STREAMING)
24197 {
24198 poly_int64 const_vnum;
24199 return (poly_int_rtx_p (vnum, &const_vnum)
24200 && known_eq (const_vnum,
24201 INTVAL (offset) * BYTES_PER_SVE_VECTOR));
24202 }
24203 else
24204 {
24205 HOST_WIDE_INT factor;
24206 return (aarch64_sme_vq_unspec_p (vnum, &factor)
24207 && factor == INTVAL (offset) * 16);
24208 }
24209 }
24210
24211 /* Emit a register copy from operand to operand, taking care not to
24212 early-clobber source registers in the process.
24213
24214 COUNT is the number of components into which the copy needs to be
24215 decomposed. */
24216 void
24217 aarch64_simd_emit_reg_reg_move (rtx *operands, machine_mode mode,
24218 unsigned int count)
24219 {
24220 unsigned int i;
24221 int rdest = REGNO (operands[0]);
24222 int rsrc = REGNO (operands[1]);
24223
24224 if (!reg_overlap_mentioned_p (operands[0], operands[1])
24225 || rdest < rsrc)
24226 for (i = 0; i < count; i++)
24227 emit_move_insn (gen_rtx_REG (mode, rdest + i),
24228 gen_rtx_REG (mode, rsrc + i));
24229 else
24230 for (i = 0; i < count; i++)
24231 emit_move_insn (gen_rtx_REG (mode, rdest + count - i - 1),
24232 gen_rtx_REG (mode, rsrc + count - i - 1));
24233 }
24234
24235 /* Compute and return the length of aarch64_simd_reglist<mode>, where <mode> is
24236 one of VSTRUCT modes: OI, CI, or XI. */
24237 int
24238 aarch64_simd_attr_length_rglist (machine_mode mode)
24239 {
24240 /* This is only used (and only meaningful) for Advanced SIMD, not SVE. */
24241 return (GET_MODE_SIZE (mode).to_constant () / UNITS_PER_VREG) * 4;
24242 }
24243
24244 /* Implement target hook TARGET_VECTOR_ALIGNMENT. The AAPCS64 sets the maximum
24245 alignment of a vector to 128 bits. SVE predicates have an alignment of
24246 16 bits. */
24247 static HOST_WIDE_INT
24248 aarch64_simd_vector_alignment (const_tree type)
24249 {
24250 /* ??? Checking the mode isn't ideal, but VECTOR_BOOLEAN_TYPE_P can
24251 be set for non-predicate vectors of booleans. Modes are the most
24252 direct way we have of identifying real SVE predicate types. */
24253 if (GET_MODE_CLASS (TYPE_MODE (type)) == MODE_VECTOR_BOOL)
24254 return 16;
24255 widest_int min_size
24256 = constant_lower_bound (wi::to_poly_widest (TYPE_SIZE (type)));
24257 return wi::umin (min_size, 128).to_uhwi ();
24258 }
24259
24260 /* Implement target hook TARGET_VECTORIZE_PREFERRED_VECTOR_ALIGNMENT. */
24261 static poly_uint64
24262 aarch64_vectorize_preferred_vector_alignment (const_tree type)
24263 {
24264 if (aarch64_sve_data_mode_p (TYPE_MODE (type)))
24265 {
24266 /* If the length of the vector is a fixed power of 2, try to align
24267 to that length, otherwise don't try to align at all. */
24268 HOST_WIDE_INT result;
24269 if (!GET_MODE_BITSIZE (TYPE_MODE (type)).is_constant (&result)
24270 || !pow2p_hwi (result))
24271 result = TYPE_ALIGN (TREE_TYPE (type));
24272 return result;
24273 }
24274 return TYPE_ALIGN (type);
24275 }
24276
24277 /* Implement target hook TARGET_VECTORIZE_VECTOR_ALIGNMENT_REACHABLE. */
24278 static bool
24279 aarch64_simd_vector_alignment_reachable (const_tree type, bool is_packed)
24280 {
24281 if (is_packed)
24282 return false;
24283
24284 /* For fixed-length vectors, check that the vectorizer will aim for
24285 full-vector alignment. This isn't true for generic GCC vectors
24286 that are wider than the ABI maximum of 128 bits. */
24287 poly_uint64 preferred_alignment =
24288 aarch64_vectorize_preferred_vector_alignment (type);
24289 if (TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST
24290 && maybe_ne (wi::to_widest (TYPE_SIZE (type)),
24291 preferred_alignment))
24292 return false;
24293
24294 /* Vectors whose size is <= BIGGEST_ALIGNMENT are naturally aligned. */
24295 return true;
24296 }
24297
24298 /* Return true if the vector misalignment factor is supported by the
24299 target. */
24300 static bool
24301 aarch64_builtin_support_vector_misalignment (machine_mode mode,
24302 const_tree type, int misalignment,
24303 bool is_packed)
24304 {
24305 if (TARGET_SIMD && STRICT_ALIGNMENT)
24306 {
24307 /* Return if movmisalign pattern is not supported for this mode. */
24308 if (optab_handler (movmisalign_optab, mode) == CODE_FOR_nothing)
24309 return false;
24310
24311 /* Misalignment factor is unknown at compile time. */
24312 if (misalignment == -1)
24313 return false;
24314 }
24315 return default_builtin_support_vector_misalignment (mode, type, misalignment,
24316 is_packed);
24317 }
24318
24319 /* If VALS is a vector constant that can be loaded into a register
24320 using DUP, generate instructions to do so and return an RTX to
24321 assign to the register. Otherwise return NULL_RTX. */
24322 static rtx
24323 aarch64_simd_dup_constant (rtx vals)
24324 {
24325 machine_mode mode = GET_MODE (vals);
24326 machine_mode inner_mode = GET_MODE_INNER (mode);
24327 rtx x;
24328
24329 if (!const_vec_duplicate_p (vals, &x))
24330 return NULL_RTX;
24331
24332 /* We can load this constant by using DUP and a constant in a
24333 single ARM register. This will be cheaper than a vector
24334 load. */
24335 x = force_reg (inner_mode, x);
24336 return gen_vec_duplicate (mode, x);
24337 }
24338
24339
24340 /* Generate code to load VALS, which is a PARALLEL containing only
24341 constants (for vec_init) or CONST_VECTOR, efficiently into a
24342 register. Returns an RTX to copy into the register, or NULL_RTX
24343 for a PARALLEL that cannot be converted into a CONST_VECTOR. */
24344 static rtx
24345 aarch64_simd_make_constant (rtx vals)
24346 {
24347 machine_mode mode = GET_MODE (vals);
24348 rtx const_dup;
24349 rtx const_vec = NULL_RTX;
24350 int n_const = 0;
24351 int i;
24352
24353 if (CONST_VECTOR_P (vals))
24354 const_vec = vals;
24355 else if (GET_CODE (vals) == PARALLEL)
24356 {
24357 /* A CONST_VECTOR must contain only CONST_INTs and
24358 CONST_DOUBLEs, but CONSTANT_P allows more (e.g. SYMBOL_REF).
24359 Only store valid constants in a CONST_VECTOR. */
24360 int n_elts = XVECLEN (vals, 0);
24361 for (i = 0; i < n_elts; ++i)
24362 {
24363 rtx x = XVECEXP (vals, 0, i);
24364 if (CONST_INT_P (x) || CONST_DOUBLE_P (x))
24365 n_const++;
24366 }
24367 if (n_const == n_elts)
24368 const_vec = gen_rtx_CONST_VECTOR (mode, XVEC (vals, 0));
24369 }
24370 else
24371 gcc_unreachable ();
24372
24373 if (const_vec != NULL_RTX
24374 && aarch64_simd_valid_mov_imm (const_vec))
24375 /* Load using MOVI/MVNI. */
24376 return const_vec;
24377 else if ((const_dup = aarch64_simd_dup_constant (vals)) != NULL_RTX)
24378 /* Loaded using DUP. */
24379 return const_dup;
24380 else if (const_vec != NULL_RTX)
24381 /* Load from constant pool. We cannot take advantage of single-cycle
24382 LD1 because we need a PC-relative addressing mode. */
24383 return const_vec;
24384 else
24385 /* A PARALLEL containing something not valid inside CONST_VECTOR.
24386 We cannot construct an initializer. */
24387 return NULL_RTX;
24388 }
24389
24390 /* VALS is a PARALLEL rtx that contains element values for a vector of
24391 mode MODE. Return a constant that contains all the CONST_INT and
24392 CONST_DOUBLE elements of VALS, using any convenient values for the
24393 other elements. */
24394
24395 static rtx
24396 aarch64_choose_vector_init_constant (machine_mode mode, rtx vals)
24397 {
24398 unsigned int n_elts = XVECLEN (vals, 0);
24399
24400 /* We really don't care what goes into the parts we will overwrite, but we're
24401 more likely to be able to load the constant efficiently if it has fewer,
24402 larger, repeating parts (see aarch64_simd_valid_imm). */
24403 rtvec copy = shallow_copy_rtvec (XVEC (vals, 0));
24404 for (unsigned int i = 0; i < n_elts; ++i)
24405 {
24406 rtx x = RTVEC_ELT (copy, i);
24407 if (CONST_INT_P (x) || CONST_DOUBLE_P (x))
24408 continue;
24409 /* This is effectively a bit-reversed increment, e.g.: 8, 4, 12,
24410 2, 10, 6, 12, ... for n_elts == 16. The early break makes the
24411 outer "i" loop O(n_elts * log(n_elts)). */
24412 unsigned int j = 0;
24413 for (;;)
24414 {
24415 for (unsigned int bit = n_elts / 2; bit > 0; bit /= 2)
24416 {
24417 j ^= bit;
24418 if (j & bit)
24419 break;
24420 }
24421 rtx test = XVECEXP (vals, 0, i ^ j);
24422 if (CONST_INT_P (test) || CONST_DOUBLE_P (test))
24423 {
24424 RTVEC_ELT (copy, i) = test;
24425 break;
24426 }
24427 gcc_assert (j != 0);
24428 }
24429 }
24430
24431 rtx c = gen_rtx_CONST_VECTOR (mode, copy);
24432 if (aarch64_simd_valid_mov_imm (c))
24433 return c;
24434
24435 /* Try generating a stepped sequence. */
24436 if (GET_MODE_CLASS (mode) == MODE_VECTOR_INT)
24437 for (unsigned int i = 0; i < n_elts; ++i)
24438 if (CONST_INT_P (XVECEXP (vals, 0, i)))
24439 {
24440 auto base = UINTVAL (XVECEXP (vals, 0, i));
24441 for (unsigned int j = i + 1; j < n_elts; ++j)
24442 if (CONST_INT_P (XVECEXP (vals, 0, j)))
24443 {
24444 /* It doesn't matter whether this division is exact.
24445 All that matters is whether the constant we produce
24446 is valid. */
24447 HOST_WIDE_INT diff = UINTVAL (XVECEXP (vals, 0, j)) - base;
24448 unsigned HOST_WIDE_INT step = diff / int (j - i);
24449 rtx_vector_builder builder (mode, n_elts, 1);
24450 for (unsigned int k = 0; k < n_elts; ++k)
24451 {
24452 rtx x = XVECEXP (vals, 0, k);
24453 if (!CONST_INT_P (x))
24454 x = gen_int_mode (int (k - i) * step + base,
24455 GET_MODE_INNER (mode));
24456 builder.quick_push (x);
24457 }
24458 rtx step_c = builder.build ();
24459 if (aarch64_simd_valid_mov_imm (step_c))
24460 return step_c;
24461 break;
24462 }
24463 break;
24464 }
24465
24466 return c;
24467 }
24468
24469 /* A subroutine of aarch64_expand_vector_init, with the same interface.
24470 The caller has already tried a divide-and-conquer approach, so do
24471 not consider that case here. */
24472
24473 void
24474 aarch64_expand_vector_init_fallback (rtx target, rtx vals)
24475 {
24476 machine_mode mode = GET_MODE (target);
24477 scalar_mode inner_mode = GET_MODE_INNER (mode);
24478 /* The number of vector elements. */
24479 int n_elts = XVECLEN (vals, 0);
24480 /* The number of vector elements which are not constant. */
24481 int n_var = 0;
24482 /* The first element of vals. */
24483 rtx v0 = XVECEXP (vals, 0, 0);
24484 bool all_same = true;
24485
24486 /* This is a special vec_init<M><N> where N is not an element mode but a
24487 vector mode with half the elements of M. We expect to find two entries
24488 of mode N in VALS and we must put their concatentation into TARGET. */
24489 if (XVECLEN (vals, 0) == 2 && VECTOR_MODE_P (GET_MODE (XVECEXP (vals, 0, 0))))
24490 {
24491 machine_mode narrow_mode = GET_MODE (XVECEXP (vals, 0, 0));
24492 gcc_assert (GET_MODE_INNER (narrow_mode) == inner_mode
24493 && known_eq (GET_MODE_SIZE (mode),
24494 2 * GET_MODE_SIZE (narrow_mode)));
24495 emit_insn (gen_aarch64_vec_concat (narrow_mode, target,
24496 XVECEXP (vals, 0, 0),
24497 XVECEXP (vals, 0, 1)));
24498 return;
24499 }
24500
24501 /* Count the number of variable elements to initialise. */
24502 for (int i = 0; i < n_elts; ++i)
24503 {
24504 rtx x = XVECEXP (vals, 0, i);
24505 if (!(CONST_INT_P (x) || CONST_DOUBLE_P (x)))
24506 ++n_var;
24507
24508 all_same &= rtx_equal_p (x, v0);
24509 }
24510
24511 /* No variable elements, hand off to aarch64_simd_make_constant which knows
24512 how best to handle this. */
24513 if (n_var == 0)
24514 {
24515 rtx constant = aarch64_simd_make_constant (vals);
24516 if (constant != NULL_RTX)
24517 {
24518 emit_move_insn (target, constant);
24519 return;
24520 }
24521 }
24522
24523 /* Splat a single non-constant element if we can. */
24524 if (all_same)
24525 {
24526 rtx x = force_reg (inner_mode, v0);
24527 aarch64_emit_move (target, gen_vec_duplicate (mode, x));
24528 return;
24529 }
24530
24531 enum insn_code icode = optab_handler (vec_set_optab, mode);
24532 gcc_assert (icode != CODE_FOR_nothing);
24533
24534 /* If there are only variable elements, try to optimize
24535 the insertion using dup for the most common element
24536 followed by insertions. */
24537
24538 /* The algorithm will fill matches[*][0] with the earliest matching element,
24539 and matches[X][1] with the count of duplicate elements (if X is the
24540 earliest element which has duplicates). */
24541
24542 if (n_var >= n_elts - 1 && n_elts <= 16)
24543 {
24544 int matches[16][2] = {0};
24545 for (int i = 0; i < n_elts; i++)
24546 {
24547 for (int j = 0; j <= i; j++)
24548 {
24549 if (rtx_equal_p (XVECEXP (vals, 0, i), XVECEXP (vals, 0, j)))
24550 {
24551 matches[i][0] = j;
24552 matches[j][1]++;
24553 break;
24554 }
24555 }
24556 }
24557 int maxelement = 0;
24558 int maxv = 0;
24559 rtx const_elem = NULL_RTX;
24560 int const_elem_pos = 0;
24561
24562 for (int i = 0; i < n_elts; i++)
24563 {
24564 if (matches[i][1] > maxv)
24565 {
24566 maxelement = i;
24567 maxv = matches[i][1];
24568 }
24569 if (CONST_INT_P (XVECEXP (vals, 0, i))
24570 || CONST_DOUBLE_P (XVECEXP (vals, 0, i)))
24571 {
24572 const_elem_pos = i;
24573 const_elem = XVECEXP (vals, 0, i);
24574 }
24575 }
24576
24577 /* Create a duplicate of the most common element, unless all elements
24578 are equally useless to us, in which case just immediately set the
24579 vector register using the first element. */
24580
24581 if (maxv == 1)
24582 {
24583 /* For vectors of two 64-bit elements, we can do even better. */
24584 if (n_elts == 2
24585 && (inner_mode == E_DImode
24586 || inner_mode == E_DFmode))
24587
24588 {
24589 rtx x0 = XVECEXP (vals, 0, 0);
24590 rtx x1 = XVECEXP (vals, 0, 1);
24591 /* Combine can pick up this case, but handling it directly
24592 here leaves clearer RTL.
24593
24594 This is load_pair_lanes<mode>, and also gives us a clean-up
24595 for store_pair_lanes<mode>. */
24596 if (memory_operand (x0, inner_mode)
24597 && memory_operand (x1, inner_mode)
24598 && aarch64_mergeable_load_pair_p (mode, x0, x1))
24599 {
24600 rtx t;
24601 if (inner_mode == DFmode)
24602 t = gen_load_pair_lanesdf (target, x0, x1);
24603 else
24604 t = gen_load_pair_lanesdi (target, x0, x1);
24605 emit_insn (t);
24606 return;
24607 }
24608 }
24609 /* The subreg-move sequence below will move into lane zero of the
24610 vector register. For big-endian we want that position to hold
24611 the last element of VALS. */
24612 maxelement = BYTES_BIG_ENDIAN ? n_elts - 1 : 0;
24613
24614 /* If we have a single constant element, use that for duplicating
24615 instead. */
24616 if (const_elem)
24617 {
24618 maxelement = const_elem_pos;
24619 aarch64_emit_move (target, gen_vec_duplicate (mode, const_elem));
24620 }
24621 else
24622 {
24623 rtx x = force_reg (inner_mode, XVECEXP (vals, 0, maxelement));
24624 aarch64_emit_move (target, lowpart_subreg (mode, x, inner_mode));
24625 }
24626 }
24627 else
24628 {
24629 rtx x = force_reg (inner_mode, XVECEXP (vals, 0, maxelement));
24630 aarch64_emit_move (target, gen_vec_duplicate (mode, x));
24631 }
24632
24633 /* Insert the rest. */
24634 for (int i = 0; i < n_elts; i++)
24635 {
24636 rtx x = XVECEXP (vals, 0, i);
24637 if (matches[i][0] == maxelement)
24638 continue;
24639 x = force_reg (inner_mode, x);
24640 emit_insn (GEN_FCN (icode) (target, x, GEN_INT (i)));
24641 }
24642 return;
24643 }
24644
24645 /* Initialise a vector which is part-variable. We want to first try
24646 to build those lanes which are constant in the most efficient way we
24647 can. */
24648 if (n_var != n_elts)
24649 {
24650 /* Load the constant part of the vector. */
24651 rtx constant = aarch64_choose_vector_init_constant (mode, vals);
24652 emit_move_insn (target, constant);
24653 }
24654
24655 /* Insert the variable lanes directly. */
24656 for (int i = 0; i < n_elts; i++)
24657 {
24658 rtx x = XVECEXP (vals, 0, i);
24659 if (CONST_INT_P (x) || CONST_DOUBLE_P (x))
24660 continue;
24661 x = force_reg (inner_mode, x);
24662 emit_insn (GEN_FCN (icode) (target, x, GEN_INT (i)));
24663 }
24664 }
24665
24666 /* Return even or odd half of VALS depending on EVEN_P. */
24667
24668 static rtx
24669 aarch64_unzip_vector_init (machine_mode mode, rtx vals, bool even_p)
24670 {
24671 int n = XVECLEN (vals, 0);
24672 machine_mode new_mode
24673 = aarch64_simd_container_mode (GET_MODE_INNER (mode),
24674 GET_MODE_BITSIZE (mode).to_constant () / 2);
24675 rtvec vec = rtvec_alloc (n / 2);
24676 for (int i = 0; i < n / 2; i++)
24677 RTVEC_ELT (vec, i) = (even_p) ? XVECEXP (vals, 0, 2 * i)
24678 : XVECEXP (vals, 0, 2 * i + 1);
24679 return gen_rtx_PARALLEL (new_mode, vec);
24680 }
24681
24682 /* Return true if SET is a scalar move. */
24683
24684 static bool
24685 scalar_move_insn_p (rtx set)
24686 {
24687 rtx src = SET_SRC (set);
24688 rtx dest = SET_DEST (set);
24689 return (is_a<scalar_mode> (GET_MODE (dest))
24690 && aarch64_mov_operand (src, GET_MODE (dest)));
24691 }
24692
24693 /* Similar to seq_cost, but ignore cost for scalar moves. */
24694
24695 static unsigned
24696 seq_cost_ignoring_scalar_moves (const rtx_insn *seq, bool speed)
24697 {
24698 unsigned cost = 0;
24699
24700 for (; seq; seq = NEXT_INSN (seq))
24701 if (NONDEBUG_INSN_P (seq))
24702 {
24703 if (rtx set = single_set (seq))
24704 {
24705 if (!scalar_move_insn_p (set))
24706 cost += set_rtx_cost (set, speed);
24707 }
24708 else
24709 {
24710 int this_cost = insn_cost (CONST_CAST_RTX_INSN (seq), speed);
24711 if (this_cost > 0)
24712 cost += this_cost;
24713 else
24714 cost++;
24715 }
24716 }
24717
24718 return cost;
24719 }
24720
24721 /* Expand a vector initialization sequence, such that TARGET is
24722 initialized to contain VALS. */
24723
24724 void
24725 aarch64_expand_vector_init (rtx target, rtx vals)
24726 {
24727 /* Try decomposing the initializer into even and odd halves and
24728 then ZIP them together. Use the resulting sequence if it is
24729 strictly cheaper than loading VALS directly.
24730
24731 Prefer the fallback sequence in the event of a tie, since it
24732 will tend to use fewer registers. */
24733
24734 machine_mode mode = GET_MODE (target);
24735 int n_elts = XVECLEN (vals, 0);
24736
24737 if (n_elts < 4
24738 || maybe_ne (GET_MODE_BITSIZE (mode), 128))
24739 {
24740 aarch64_expand_vector_init_fallback (target, vals);
24741 return;
24742 }
24743
24744 start_sequence ();
24745 rtx halves[2];
24746 unsigned costs[2];
24747 for (int i = 0; i < 2; i++)
24748 {
24749 start_sequence ();
24750 rtx new_vals = aarch64_unzip_vector_init (mode, vals, i == 0);
24751 rtx tmp_reg = gen_reg_rtx (GET_MODE (new_vals));
24752 aarch64_expand_vector_init (tmp_reg, new_vals);
24753 halves[i] = gen_rtx_SUBREG (mode, tmp_reg, 0);
24754 rtx_insn *rec_seq = get_insns ();
24755 end_sequence ();
24756 costs[i] = seq_cost_ignoring_scalar_moves (rec_seq, !optimize_size);
24757 emit_insn (rec_seq);
24758 }
24759
24760 /* The two halves should (by induction) be individually endian-correct.
24761 However, in the memory layout provided by VALS, the nth element of
24762 HALVES[0] comes immediately before the nth element HALVES[1].
24763 This means that, on big-endian targets, the nth element of HALVES[0]
24764 is more significant than the nth element HALVES[1]. */
24765 if (BYTES_BIG_ENDIAN)
24766 std::swap (halves[0], halves[1]);
24767 rtvec v = gen_rtvec (2, halves[0], halves[1]);
24768 rtx_insn *zip1_insn
24769 = emit_set_insn (target, gen_rtx_UNSPEC (mode, v, UNSPEC_ZIP1));
24770 unsigned seq_total_cost
24771 = (!optimize_size) ? std::max (costs[0], costs[1]) : costs[0] + costs[1];
24772 seq_total_cost += insn_cost (zip1_insn, !optimize_size);
24773
24774 rtx_insn *seq = get_insns ();
24775 end_sequence ();
24776
24777 start_sequence ();
24778 aarch64_expand_vector_init_fallback (target, vals);
24779 rtx_insn *fallback_seq = get_insns ();
24780 unsigned fallback_seq_cost
24781 = seq_cost_ignoring_scalar_moves (fallback_seq, !optimize_size);
24782 end_sequence ();
24783
24784 emit_insn (seq_total_cost < fallback_seq_cost ? seq : fallback_seq);
24785 }
24786
24787 /* Emit RTL corresponding to:
24788 insr TARGET, ELEM. */
24789
24790 static void
24791 emit_insr (rtx target, rtx elem)
24792 {
24793 machine_mode mode = GET_MODE (target);
24794 scalar_mode elem_mode = GET_MODE_INNER (mode);
24795 elem = force_reg (elem_mode, elem);
24796
24797 insn_code icode = optab_handler (vec_shl_insert_optab, mode);
24798 gcc_assert (icode != CODE_FOR_nothing);
24799 emit_insn (GEN_FCN (icode) (target, target, elem));
24800 }
24801
24802 /* Subroutine of aarch64_sve_expand_vector_init for handling
24803 trailing constants.
24804 This function works as follows:
24805 (a) Create a new vector consisting of trailing constants.
24806 (b) Initialize TARGET with the constant vector using emit_move_insn.
24807 (c) Insert remaining elements in TARGET using insr.
24808 NELTS is the total number of elements in original vector while
24809 while NELTS_REQD is the number of elements that are actually
24810 significant.
24811
24812 ??? The heuristic used is to do above only if number of constants
24813 is at least half the total number of elements. May need fine tuning. */
24814
24815 static bool
24816 aarch64_sve_expand_vector_init_handle_trailing_constants
24817 (rtx target, const rtx_vector_builder &builder, int nelts, int nelts_reqd)
24818 {
24819 machine_mode mode = GET_MODE (target);
24820 scalar_mode elem_mode = GET_MODE_INNER (mode);
24821 int n_trailing_constants = 0;
24822
24823 for (int i = nelts_reqd - 1;
24824 i >= 0 && valid_for_const_vector_p (elem_mode, builder.elt (i));
24825 i--)
24826 n_trailing_constants++;
24827
24828 if (n_trailing_constants >= nelts_reqd / 2)
24829 {
24830 /* Try to use the natural pattern of BUILDER to extend the trailing
24831 constant elements to a full vector. Replace any variables in the
24832 extra elements with zeros.
24833
24834 ??? It would be better if the builders supported "don't care"
24835 elements, with the builder filling in whichever elements
24836 give the most compact encoding. */
24837 rtx_vector_builder v (mode, nelts, 1);
24838 for (int i = 0; i < nelts; i++)
24839 {
24840 rtx x = builder.elt (i + nelts_reqd - n_trailing_constants);
24841 if (!valid_for_const_vector_p (elem_mode, x))
24842 x = CONST0_RTX (elem_mode);
24843 v.quick_push (x);
24844 }
24845 rtx const_vec = v.build ();
24846 emit_move_insn (target, const_vec);
24847
24848 for (int i = nelts_reqd - n_trailing_constants - 1; i >= 0; i--)
24849 emit_insr (target, builder.elt (i));
24850
24851 return true;
24852 }
24853
24854 return false;
24855 }
24856
24857 /* Subroutine of aarch64_sve_expand_vector_init.
24858 Works as follows:
24859 (a) Initialize TARGET by broadcasting element NELTS_REQD - 1 of BUILDER.
24860 (b) Skip trailing elements from BUILDER, which are the same as
24861 element NELTS_REQD - 1.
24862 (c) Insert earlier elements in reverse order in TARGET using insr. */
24863
24864 static void
24865 aarch64_sve_expand_vector_init_insert_elems (rtx target,
24866 const rtx_vector_builder &builder,
24867 int nelts_reqd)
24868 {
24869 machine_mode mode = GET_MODE (target);
24870 scalar_mode elem_mode = GET_MODE_INNER (mode);
24871
24872 struct expand_operand ops[2];
24873 enum insn_code icode = optab_handler (vec_duplicate_optab, mode);
24874 gcc_assert (icode != CODE_FOR_nothing);
24875
24876 create_output_operand (&ops[0], target, mode);
24877 create_input_operand (&ops[1], builder.elt (nelts_reqd - 1), elem_mode);
24878 expand_insn (icode, 2, ops);
24879
24880 int ndups = builder.count_dups (nelts_reqd - 1, -1, -1);
24881 for (int i = nelts_reqd - ndups - 1; i >= 0; i--)
24882 emit_insr (target, builder.elt (i));
24883 }
24884
24885 /* Subroutine of aarch64_sve_expand_vector_init to handle case
24886 when all trailing elements of builder are same.
24887 This works as follows:
24888 (a) Use expand_insn interface to broadcast last vector element in TARGET.
24889 (b) Insert remaining elements in TARGET using insr.
24890
24891 ??? The heuristic used is to do above if number of same trailing elements
24892 is at least 3/4 of total number of elements, loosely based on
24893 heuristic from mostly_zeros_p. May need fine-tuning. */
24894
24895 static bool
24896 aarch64_sve_expand_vector_init_handle_trailing_same_elem
24897 (rtx target, const rtx_vector_builder &builder, int nelts_reqd)
24898 {
24899 int ndups = builder.count_dups (nelts_reqd - 1, -1, -1);
24900 if (ndups >= (3 * nelts_reqd) / 4)
24901 {
24902 aarch64_sve_expand_vector_init_insert_elems (target, builder,
24903 nelts_reqd - ndups + 1);
24904 return true;
24905 }
24906
24907 return false;
24908 }
24909
24910 /* Initialize register TARGET from BUILDER. NELTS is the constant number
24911 of elements in BUILDER.
24912
24913 The function tries to initialize TARGET from BUILDER if it fits one
24914 of the special cases outlined below.
24915
24916 Failing that, the function divides BUILDER into two sub-vectors:
24917 v_even = even elements of BUILDER;
24918 v_odd = odd elements of BUILDER;
24919
24920 and recursively calls itself with v_even and v_odd.
24921
24922 if (recursive call succeeded for v_even or v_odd)
24923 TARGET = zip (v_even, v_odd)
24924
24925 The function returns true if it managed to build TARGET from BUILDER
24926 with one of the special cases, false otherwise.
24927
24928 Example: {a, 1, b, 2, c, 3, d, 4}
24929
24930 The vector gets divided into:
24931 v_even = {a, b, c, d}
24932 v_odd = {1, 2, 3, 4}
24933
24934 aarch64_sve_expand_vector_init(v_odd) hits case 1 and
24935 initialize tmp2 from constant vector v_odd using emit_move_insn.
24936
24937 aarch64_sve_expand_vector_init(v_even) fails since v_even contains
24938 4 elements, so we construct tmp1 from v_even using insr:
24939 tmp1 = dup(d)
24940 insr tmp1, c
24941 insr tmp1, b
24942 insr tmp1, a
24943
24944 And finally:
24945 TARGET = zip (tmp1, tmp2)
24946 which sets TARGET to {a, 1, b, 2, c, 3, d, 4}. */
24947
24948 static bool
24949 aarch64_sve_expand_vector_init (rtx target, const rtx_vector_builder &builder,
24950 int nelts, int nelts_reqd)
24951 {
24952 machine_mode mode = GET_MODE (target);
24953
24954 /* Case 1: Vector contains trailing constants. */
24955
24956 if (aarch64_sve_expand_vector_init_handle_trailing_constants
24957 (target, builder, nelts, nelts_reqd))
24958 return true;
24959
24960 /* Case 2: Vector contains leading constants. */
24961
24962 rtx_vector_builder rev_builder (mode, nelts_reqd, 1);
24963 for (int i = 0; i < nelts_reqd; i++)
24964 rev_builder.quick_push (builder.elt (nelts_reqd - i - 1));
24965 rev_builder.finalize ();
24966
24967 if (aarch64_sve_expand_vector_init_handle_trailing_constants
24968 (target, rev_builder, nelts, nelts_reqd))
24969 {
24970 emit_insn (gen_aarch64_sve_rev (mode, target, target));
24971 return true;
24972 }
24973
24974 /* Case 3: Vector contains trailing same element. */
24975
24976 if (aarch64_sve_expand_vector_init_handle_trailing_same_elem
24977 (target, builder, nelts_reqd))
24978 return true;
24979
24980 /* Case 4: Vector contains leading same element. */
24981
24982 if (aarch64_sve_expand_vector_init_handle_trailing_same_elem
24983 (target, rev_builder, nelts_reqd) && nelts_reqd == nelts)
24984 {
24985 emit_insn (gen_aarch64_sve_rev (mode, target, target));
24986 return true;
24987 }
24988
24989 /* Avoid recursing below 4-elements.
24990 ??? The threshold 4 may need fine-tuning. */
24991
24992 if (nelts_reqd <= 4)
24993 return false;
24994
24995 rtx_vector_builder v_even (mode, nelts, 1);
24996 rtx_vector_builder v_odd (mode, nelts, 1);
24997
24998 for (int i = 0; i < nelts * 2; i += 2)
24999 {
25000 v_even.quick_push (builder.elt (i));
25001 v_odd.quick_push (builder.elt (i + 1));
25002 }
25003
25004 v_even.finalize ();
25005 v_odd.finalize ();
25006
25007 rtx tmp1 = gen_reg_rtx (mode);
25008 bool did_even_p = aarch64_sve_expand_vector_init (tmp1, v_even,
25009 nelts, nelts_reqd / 2);
25010
25011 rtx tmp2 = gen_reg_rtx (mode);
25012 bool did_odd_p = aarch64_sve_expand_vector_init (tmp2, v_odd,
25013 nelts, nelts_reqd / 2);
25014
25015 if (!did_even_p && !did_odd_p)
25016 return false;
25017
25018 /* Initialize v_even and v_odd using INSR if it didn't match any of the
25019 special cases and zip v_even, v_odd. */
25020
25021 if (!did_even_p)
25022 aarch64_sve_expand_vector_init_insert_elems (tmp1, v_even, nelts_reqd / 2);
25023
25024 if (!did_odd_p)
25025 aarch64_sve_expand_vector_init_insert_elems (tmp2, v_odd, nelts_reqd / 2);
25026
25027 rtvec v = gen_rtvec (2, tmp1, tmp2);
25028 emit_set_insn (target, gen_rtx_UNSPEC (mode, v, UNSPEC_ZIP1));
25029 return true;
25030 }
25031
25032 /* Initialize register TARGET from the elements in PARALLEL rtx VALS. */
25033
25034 void
25035 aarch64_sve_expand_vector_init (rtx target, rtx vals)
25036 {
25037 machine_mode mode = GET_MODE (target);
25038 int nelts = XVECLEN (vals, 0);
25039
25040 rtx_vector_builder v (mode, nelts, 1);
25041 for (int i = 0; i < nelts; i++)
25042 v.quick_push (XVECEXP (vals, 0, i));
25043 v.finalize ();
25044
25045 /* If neither sub-vectors of v could be initialized specially,
25046 then use INSR to insert all elements from v into TARGET.
25047 ??? This might not be optimal for vectors with large
25048 initializers like 16-element or above.
25049 For nelts < 4, it probably isn't useful to handle specially. */
25050
25051 if (nelts < 4
25052 || !aarch64_sve_expand_vector_init (target, v, nelts, nelts))
25053 aarch64_sve_expand_vector_init_insert_elems (target, v, nelts);
25054 }
25055
25056 /* Initialize register TARGET from the two vector subelements in PARALLEL
25057 rtx VALS. */
25058
25059 void
25060 aarch64_sve_expand_vector_init_subvector (rtx target, rtx vals)
25061 {
25062 machine_mode mode = GET_MODE (target);
25063 int nelts = XVECLEN (vals, 0);
25064
25065 gcc_assert (nelts % 2 == 0);
25066
25067 /* We have to be concatting vector. */
25068 machine_mode elem_mode = GET_MODE (XVECEXP (vals, 0, 0));
25069 gcc_assert (VECTOR_MODE_P (elem_mode));
25070
25071 auto_vec<rtx> worklist;
25072 machine_mode wider_mode = elem_mode;
25073
25074 for (int i = 0; i < nelts; i++)
25075 worklist.safe_push (force_reg (elem_mode, XVECEXP (vals, 0, i)));
25076
25077 /* Keep widening pairwise to have maximum throughput. */
25078 while (nelts >= 2)
25079 {
25080 wider_mode
25081 = related_vector_mode (wider_mode, GET_MODE_INNER (wider_mode),
25082 GET_MODE_NUNITS (wider_mode) * 2).require ();
25083
25084 for (int i = 0; i < nelts; i += 2)
25085 {
25086 rtx arg0 = worklist[i];
25087 rtx arg1 = worklist[i+1];
25088 gcc_assert (GET_MODE (arg0) == GET_MODE (arg1));
25089
25090 rtx tmp = gen_reg_rtx (wider_mode);
25091 emit_insn (gen_aarch64_pack_partial (wider_mode, tmp, arg0, arg1));
25092 worklist[i / 2] = tmp;
25093 }
25094
25095 nelts /= 2;
25096 }
25097
25098 gcc_assert (wider_mode == mode);
25099 emit_move_insn (target, worklist[0]);
25100
25101 return;
25102 }
25103
25104 /* Check whether VALUE is a vector constant in which every element
25105 is either a power of 2 or a negated power of 2. If so, return
25106 a constant vector of log2s, and flip CODE between PLUS and MINUS
25107 if VALUE contains negated powers of 2. Return NULL_RTX otherwise. */
25108
25109 static rtx
25110 aarch64_convert_mult_to_shift (rtx value, rtx_code &code)
25111 {
25112 if (!CONST_VECTOR_P (value))
25113 return NULL_RTX;
25114
25115 rtx_vector_builder builder;
25116 if (!builder.new_unary_operation (GET_MODE (value), value, false))
25117 return NULL_RTX;
25118
25119 scalar_mode int_mode = GET_MODE_INNER (GET_MODE (value));
25120 /* 1 if the result of the multiplication must be negated,
25121 0 if it mustn't, or -1 if we don't yet care. */
25122 int negate = -1;
25123 unsigned int encoded_nelts = const_vector_encoded_nelts (value);
25124 for (unsigned int i = 0; i < encoded_nelts; ++i)
25125 {
25126 rtx elt = CONST_VECTOR_ENCODED_ELT (value, i);
25127 if (!CONST_SCALAR_INT_P (elt))
25128 return NULL_RTX;
25129 rtx_mode_t val (elt, int_mode);
25130 wide_int pow2 = wi::neg (val);
25131 if (val != pow2)
25132 {
25133 /* It matters whether we negate or not. Make that choice,
25134 and make sure that it's consistent with previous elements. */
25135 if (negate == !wi::neg_p (val))
25136 return NULL_RTX;
25137 negate = wi::neg_p (val);
25138 if (!negate)
25139 pow2 = val;
25140 }
25141 /* POW2 is now the value that we want to be a power of 2. */
25142 int shift = wi::exact_log2 (pow2);
25143 if (shift < 0)
25144 return NULL_RTX;
25145 builder.quick_push (gen_int_mode (shift, int_mode));
25146 }
25147 if (negate == -1)
25148 /* PLUS and MINUS are equivalent; canonicalize on PLUS. */
25149 code = PLUS;
25150 else if (negate == 1)
25151 code = code == PLUS ? MINUS : PLUS;
25152 return builder.build ();
25153 }
25154
25155 /* Prepare for an integer SVE multiply-add or multiply-subtract pattern;
25156 CODE is PLUS for the former and MINUS for the latter. OPERANDS is the
25157 operands array, in the same order as for fma_optab. Return true if
25158 the function emitted all the necessary instructions, false if the caller
25159 should generate the pattern normally with the new OPERANDS array. */
25160
25161 bool
25162 aarch64_prepare_sve_int_fma (rtx *operands, rtx_code code)
25163 {
25164 machine_mode mode = GET_MODE (operands[0]);
25165 if (rtx shifts = aarch64_convert_mult_to_shift (operands[2], code))
25166 {
25167 rtx product = expand_binop (mode, vashl_optab, operands[1], shifts,
25168 NULL_RTX, true, OPTAB_DIRECT);
25169 force_expand_binop (mode, code == PLUS ? add_optab : sub_optab,
25170 operands[3], product, operands[0], true,
25171 OPTAB_DIRECT);
25172 return true;
25173 }
25174 operands[2] = force_reg (mode, operands[2]);
25175 return false;
25176 }
25177
25178 /* Likewise, but for a conditional pattern. */
25179
25180 bool
25181 aarch64_prepare_sve_cond_int_fma (rtx *operands, rtx_code code)
25182 {
25183 machine_mode mode = GET_MODE (operands[0]);
25184 if (rtx shifts = aarch64_convert_mult_to_shift (operands[3], code))
25185 {
25186 rtx product = expand_binop (mode, vashl_optab, operands[2], shifts,
25187 NULL_RTX, true, OPTAB_DIRECT);
25188 emit_insn (gen_cond (code, mode, operands[0], operands[1],
25189 operands[4], product, operands[5]));
25190 return true;
25191 }
25192 operands[3] = force_reg (mode, operands[3]);
25193 return false;
25194 }
25195
25196 static unsigned HOST_WIDE_INT
25197 aarch64_shift_truncation_mask (machine_mode mode)
25198 {
25199 if (!SHIFT_COUNT_TRUNCATED || aarch64_vector_data_mode_p (mode))
25200 return 0;
25201 return GET_MODE_UNIT_BITSIZE (mode) - 1;
25202 }
25203
25204 /* Select a format to encode pointers in exception handling data. */
25205 int
25206 aarch64_asm_preferred_eh_data_format (int code ATTRIBUTE_UNUSED, int global)
25207 {
25208 int type;
25209 switch (aarch64_cmodel)
25210 {
25211 case AARCH64_CMODEL_TINY:
25212 case AARCH64_CMODEL_TINY_PIC:
25213 case AARCH64_CMODEL_SMALL:
25214 case AARCH64_CMODEL_SMALL_PIC:
25215 case AARCH64_CMODEL_SMALL_SPIC:
25216 /* text+got+data < 4Gb. 4-byte signed relocs are sufficient
25217 for everything. */
25218 type = DW_EH_PE_sdata4;
25219 break;
25220 default:
25221 /* No assumptions here. 8-byte relocs required. */
25222 type = DW_EH_PE_sdata8;
25223 break;
25224 }
25225 return (global ? DW_EH_PE_indirect : 0) | DW_EH_PE_pcrel | type;
25226 }
25227
25228 /* Return true if function declaration FNDECL needs to be marked as
25229 having a variant PCS. */
25230
25231 static bool
25232 aarch64_is_variant_pcs (tree fndecl)
25233 {
25234 /* Check for ABIs that preserve more registers than usual. */
25235 arm_pcs pcs = (arm_pcs) fndecl_abi (fndecl).id ();
25236 if (pcs == ARM_PCS_SIMD || pcs == ARM_PCS_SVE)
25237 return true;
25238
25239 /* Check for ABIs that allow PSTATE.SM to be 1 on entry. */
25240 tree fntype = TREE_TYPE (fndecl);
25241 if (aarch64_fntype_pstate_sm (fntype) != AARCH64_ISA_MODE_SM_OFF)
25242 return true;
25243
25244 /* Check for ABIs that require PSTATE.ZA to be 1 on entry, either because
25245 of ZA or ZT0. */
25246 if (aarch64_fntype_pstate_za (fntype) != 0)
25247 return true;
25248
25249 return false;
25250 }
25251
25252 /* Output .variant_pcs for aarch64_vector_pcs function symbols. */
25253
25254 static void
25255 aarch64_asm_output_variant_pcs (FILE *stream, const tree decl, const char* name)
25256 {
25257 if (TREE_CODE (decl) == FUNCTION_DECL
25258 && aarch64_is_variant_pcs (decl))
25259 {
25260 fprintf (stream, "\t.variant_pcs\t");
25261 assemble_name (stream, name);
25262 fprintf (stream, "\n");
25263 }
25264 }
25265
25266 /* The last .arch and .tune assembly strings that we printed. */
25267 static std::string aarch64_last_printed_arch_string;
25268 static std::string aarch64_last_printed_tune_string;
25269
25270 /* Implement ASM_DECLARE_FUNCTION_NAME. Output the ISA features used
25271 by the function fndecl. */
25272
25273 void
25274 aarch64_declare_function_name (FILE *stream, const char* name,
25275 tree fndecl)
25276 {
25277 tree target_parts = DECL_FUNCTION_SPECIFIC_TARGET (fndecl);
25278
25279 struct cl_target_option *targ_options;
25280 if (target_parts)
25281 targ_options = TREE_TARGET_OPTION (target_parts);
25282 else
25283 targ_options = TREE_TARGET_OPTION (target_option_current_node);
25284 gcc_assert (targ_options);
25285
25286 auto isa_flags = aarch64_get_asm_isa_flags (targ_options);
25287 aarch64_arch arch = targ_options->x_selected_arch;
25288 std::string to_print
25289 = aarch64_get_arch_string_for_assembler (arch, isa_flags);
25290 /* Only update the assembler .arch string if it is distinct from the last
25291 such string we printed. */
25292 if (to_print != aarch64_last_printed_arch_string)
25293 {
25294 asm_fprintf (asm_out_file, "\t.arch %s\n", to_print.c_str ());
25295 aarch64_last_printed_arch_string = to_print;
25296 }
25297
25298 /* Print the cpu name we're tuning for in the comments, might be
25299 useful to readers of the generated asm. Do it only when it changes
25300 from function to function and verbose assembly is requested. */
25301 const struct processor *this_tune
25302 = aarch64_get_tune_cpu (targ_options->x_selected_tune);
25303
25304 if (flag_debug_asm && aarch64_last_printed_tune_string != this_tune->name)
25305 {
25306 asm_fprintf (asm_out_file, "\t" ASM_COMMENT_START ".tune %s\n",
25307 this_tune->name);
25308 aarch64_last_printed_tune_string = this_tune->name;
25309 }
25310
25311 aarch64_asm_output_variant_pcs (stream, fndecl, name);
25312
25313 /* Don't forget the type directive for ELF. */
25314 ASM_OUTPUT_TYPE_DIRECTIVE (stream, name, "function");
25315 ASM_OUTPUT_FUNCTION_LABEL (stream, name, fndecl);
25316
25317 cfun->machine->label_is_assembled = true;
25318 }
25319
25320 /* Implement PRINT_PATCHABLE_FUNCTION_ENTRY. */
25321
25322 void
25323 aarch64_print_patchable_function_entry (FILE *file,
25324 unsigned HOST_WIDE_INT patch_area_size,
25325 bool record_p)
25326 {
25327 if (!cfun->machine->label_is_assembled)
25328 {
25329 /* Emit the patching area before the entry label, if any. */
25330 default_print_patchable_function_entry (file, patch_area_size,
25331 record_p);
25332 return;
25333 }
25334
25335 rtx pa = gen_patchable_area (GEN_INT (patch_area_size),
25336 GEN_INT (record_p));
25337 basic_block bb = ENTRY_BLOCK_PTR_FOR_FN (cfun)->next_bb;
25338
25339 if (!aarch_bti_enabled ()
25340 || cgraph_node::get (cfun->decl)->only_called_directly_p ())
25341 {
25342 /* Emit the patchable_area at the beginning of the function. */
25343 rtx_insn *insn = emit_insn_before (pa, BB_HEAD (bb));
25344 INSN_ADDRESSES_NEW (insn, -1);
25345 return;
25346 }
25347
25348 rtx_insn *insn = next_real_nondebug_insn (get_insns ());
25349 if (!insn
25350 || !INSN_P (insn)
25351 || GET_CODE (PATTERN (insn)) != UNSPEC_VOLATILE
25352 || XINT (PATTERN (insn), 1) != UNSPECV_BTI_C)
25353 {
25354 /* Emit a BTI_C. */
25355 insn = emit_insn_before (gen_bti_c (), BB_HEAD (bb));
25356 }
25357
25358 /* Emit the patchable_area after BTI_C. */
25359 insn = emit_insn_after (pa, insn);
25360 INSN_ADDRESSES_NEW (insn, -1);
25361 }
25362
25363 /* Output patchable area. */
25364
25365 void
25366 aarch64_output_patchable_area (unsigned int patch_area_size, bool record_p)
25367 {
25368 default_print_patchable_function_entry (asm_out_file, patch_area_size,
25369 record_p);
25370 }
25371
25372 /* Implement ASM_OUTPUT_DEF_FROM_DECLS. Output .variant_pcs for aliases. */
25373
25374 void
25375 aarch64_asm_output_alias (FILE *stream, const tree decl, const tree target)
25376 {
25377 const char *name = XSTR (XEXP (DECL_RTL (decl), 0), 0);
25378 const char *value = IDENTIFIER_POINTER (target);
25379 aarch64_asm_output_variant_pcs (stream, decl, name);
25380 ASM_OUTPUT_DEF (stream, name, value);
25381 }
25382
25383 /* Implement ASM_OUTPUT_EXTERNAL. Output .variant_pcs for undefined
25384 function symbol references. */
25385
25386 void
25387 aarch64_asm_output_external (FILE *stream, tree decl, const char* name)
25388 {
25389 default_elf_asm_output_external (stream, decl, name);
25390 aarch64_asm_output_variant_pcs (stream, decl, name);
25391 }
25392
25393 /* Triggered after a .cfi_startproc directive is emitted into the assembly file.
25394 Used to output the .cfi_b_key_frame directive when signing the current
25395 function with the B key. */
25396
25397 void
25398 aarch64_post_cfi_startproc (FILE *f, tree ignored ATTRIBUTE_UNUSED)
25399 {
25400 if (cfun->machine->frame.laid_out && aarch64_return_address_signing_enabled ()
25401 && aarch64_ra_sign_key == AARCH64_KEY_B)
25402 asm_fprintf (f, "\t.cfi_b_key_frame\n");
25403 }
25404
25405 /* Implements TARGET_ASM_FILE_START. Output the assembly header. */
25406
25407 static void
25408 aarch64_start_file (void)
25409 {
25410 struct cl_target_option *default_options
25411 = TREE_TARGET_OPTION (target_option_default_node);
25412
25413 aarch64_arch default_arch = default_options->x_selected_arch;
25414 auto default_isa_flags = aarch64_get_asm_isa_flags (default_options);
25415 std::string arch_string
25416 = aarch64_get_arch_string_for_assembler (default_arch, default_isa_flags);
25417 aarch64_last_printed_arch_string = arch_string;
25418 aarch64_last_printed_tune_string = "";
25419 asm_fprintf (asm_out_file, "\t.arch %s\n",
25420 arch_string.c_str ());
25421
25422 default_file_start ();
25423 }
25424
25425 /* Emit load exclusive. */
25426
25427 static void
25428 aarch64_emit_load_exclusive (machine_mode mode, rtx rval,
25429 rtx mem, rtx model_rtx)
25430 {
25431 if (mode == TImode)
25432 emit_insn (gen_aarch64_load_exclusive_pair (gen_lowpart (DImode, rval),
25433 gen_highpart (DImode, rval),
25434 mem, model_rtx));
25435 else
25436 emit_insn (gen_aarch64_load_exclusive (mode, rval, mem, model_rtx));
25437 }
25438
25439 /* Emit store exclusive. */
25440
25441 static void
25442 aarch64_emit_store_exclusive (machine_mode mode, rtx bval,
25443 rtx mem, rtx rval, rtx model_rtx)
25444 {
25445 if (mode == TImode)
25446 emit_insn (gen_aarch64_store_exclusive_pair
25447 (bval, mem, operand_subword (rval, 0, 0, TImode),
25448 operand_subword (rval, 1, 0, TImode), model_rtx));
25449 else
25450 emit_insn (gen_aarch64_store_exclusive (mode, bval, mem, rval, model_rtx));
25451 }
25452
25453 /* Mark the previous jump instruction as unlikely. */
25454
25455 static void
25456 aarch64_emit_unlikely_jump (rtx insn)
25457 {
25458 rtx_insn *jump = emit_jump_insn (insn);
25459 add_reg_br_prob_note (jump, profile_probability::very_unlikely ());
25460 }
25461
25462 /* We store the names of the various atomic helpers in a 5x5 array.
25463 Return the libcall function given MODE, MODEL and NAMES. */
25464
25465 rtx
25466 aarch64_atomic_ool_func(machine_mode mode, rtx model_rtx,
25467 const atomic_ool_names *names)
25468 {
25469 memmodel model = memmodel_from_int (INTVAL (model_rtx));
25470 int mode_idx, model_idx;
25471
25472 switch (mode)
25473 {
25474 case E_QImode:
25475 mode_idx = 0;
25476 break;
25477 case E_HImode:
25478 mode_idx = 1;
25479 break;
25480 case E_SImode:
25481 mode_idx = 2;
25482 break;
25483 case E_DImode:
25484 mode_idx = 3;
25485 break;
25486 case E_TImode:
25487 mode_idx = 4;
25488 break;
25489 default:
25490 gcc_unreachable ();
25491 }
25492
25493 switch (model)
25494 {
25495 case MEMMODEL_RELAXED:
25496 model_idx = 0;
25497 break;
25498 case MEMMODEL_CONSUME:
25499 case MEMMODEL_ACQUIRE:
25500 model_idx = 1;
25501 break;
25502 case MEMMODEL_RELEASE:
25503 model_idx = 2;
25504 break;
25505 case MEMMODEL_ACQ_REL:
25506 case MEMMODEL_SEQ_CST:
25507 model_idx = 3;
25508 break;
25509 case MEMMODEL_SYNC_ACQUIRE:
25510 case MEMMODEL_SYNC_RELEASE:
25511 case MEMMODEL_SYNC_SEQ_CST:
25512 model_idx = 4;
25513 break;
25514 default:
25515 gcc_unreachable ();
25516 }
25517
25518 return init_one_libfunc_visibility (names->str[mode_idx][model_idx],
25519 VISIBILITY_HIDDEN);
25520 }
25521
25522 #define DEF0(B, N) \
25523 { "__aarch64_" #B #N "_relax", \
25524 "__aarch64_" #B #N "_acq", \
25525 "__aarch64_" #B #N "_rel", \
25526 "__aarch64_" #B #N "_acq_rel", \
25527 "__aarch64_" #B #N "_sync" }
25528
25529 #define DEF4(B) DEF0(B, 1), DEF0(B, 2), DEF0(B, 4), DEF0(B, 8), \
25530 { NULL, NULL, NULL, NULL }
25531 #define DEF5(B) DEF0(B, 1), DEF0(B, 2), DEF0(B, 4), DEF0(B, 8), DEF0(B, 16)
25532
25533 static const atomic_ool_names aarch64_ool_cas_names = { { DEF5(cas) } };
25534 const atomic_ool_names aarch64_ool_swp_names = { { DEF4(swp) } };
25535 const atomic_ool_names aarch64_ool_ldadd_names = { { DEF4(ldadd) } };
25536 const atomic_ool_names aarch64_ool_ldset_names = { { DEF4(ldset) } };
25537 const atomic_ool_names aarch64_ool_ldclr_names = { { DEF4(ldclr) } };
25538 const atomic_ool_names aarch64_ool_ldeor_names = { { DEF4(ldeor) } };
25539
25540 #undef DEF0
25541 #undef DEF4
25542 #undef DEF5
25543
25544 /* Expand a compare and swap pattern. */
25545
25546 void
25547 aarch64_expand_compare_and_swap (rtx operands[])
25548 {
25549 rtx bval, rval, mem, oldval, newval, is_weak, mod_s, mod_f, x, cc_reg;
25550 machine_mode mode, r_mode;
25551
25552 bval = operands[0];
25553 rval = operands[1];
25554 mem = operands[2];
25555 oldval = operands[3];
25556 newval = operands[4];
25557 is_weak = operands[5];
25558 mod_s = operands[6];
25559 mod_f = operands[7];
25560 mode = GET_MODE (mem);
25561
25562 /* Normally the succ memory model must be stronger than fail, but in the
25563 unlikely event of fail being ACQUIRE and succ being RELEASE we need to
25564 promote succ to ACQ_REL so that we don't lose the acquire semantics. */
25565 if (is_mm_acquire (memmodel_from_int (INTVAL (mod_f)))
25566 && is_mm_release (memmodel_from_int (INTVAL (mod_s))))
25567 mod_s = GEN_INT (MEMMODEL_ACQ_REL);
25568
25569 r_mode = mode;
25570 if (mode == QImode || mode == HImode)
25571 {
25572 r_mode = SImode;
25573 rval = gen_reg_rtx (r_mode);
25574 }
25575
25576 if (TARGET_LSE)
25577 {
25578 /* The CAS insn requires oldval and rval overlap, but we need to
25579 have a copy of oldval saved across the operation to tell if
25580 the operation is successful. */
25581 if (reg_overlap_mentioned_p (rval, oldval))
25582 rval = copy_to_mode_reg (r_mode, oldval);
25583 else
25584 emit_move_insn (rval, gen_lowpart (r_mode, oldval));
25585 if (mode == TImode)
25586 newval = force_reg (mode, newval);
25587
25588 emit_insn (gen_aarch64_compare_and_swap_lse (mode, rval, mem,
25589 newval, mod_s));
25590 cc_reg = aarch64_gen_compare_reg_maybe_ze (NE, rval, oldval, mode);
25591 }
25592 else if (TARGET_OUTLINE_ATOMICS)
25593 {
25594 /* Oldval must satisfy compare afterward. */
25595 if (!aarch64_plus_operand (oldval, mode))
25596 oldval = force_reg (mode, oldval);
25597 rtx func = aarch64_atomic_ool_func (mode, mod_s, &aarch64_ool_cas_names);
25598 rval = emit_library_call_value (func, NULL_RTX, LCT_NORMAL, r_mode,
25599 oldval, mode, newval, mode,
25600 XEXP (mem, 0), Pmode);
25601 cc_reg = aarch64_gen_compare_reg_maybe_ze (NE, rval, oldval, mode);
25602 }
25603 else
25604 {
25605 /* The oldval predicate varies by mode. Test it and force to reg. */
25606 insn_code code = code_for_aarch64_compare_and_swap (mode);
25607 if (!insn_data[code].operand[2].predicate (oldval, mode))
25608 oldval = force_reg (mode, oldval);
25609
25610 emit_insn (GEN_FCN (code) (rval, mem, oldval, newval,
25611 is_weak, mod_s, mod_f));
25612 cc_reg = gen_rtx_REG (CCmode, CC_REGNUM);
25613 }
25614
25615 if (r_mode != mode)
25616 rval = gen_lowpart (mode, rval);
25617 emit_move_insn (operands[1], rval);
25618
25619 x = gen_rtx_EQ (SImode, cc_reg, const0_rtx);
25620 emit_insn (gen_rtx_SET (bval, x));
25621 }
25622
25623 /* Emit a barrier, that is appropriate for memory model MODEL, at the end of a
25624 sequence implementing an atomic operation. */
25625
25626 static void
25627 aarch64_emit_post_barrier (enum memmodel model)
25628 {
25629 const enum memmodel base_model = memmodel_base (model);
25630
25631 if (is_mm_sync (model)
25632 && (base_model == MEMMODEL_ACQUIRE
25633 || base_model == MEMMODEL_ACQ_REL
25634 || base_model == MEMMODEL_SEQ_CST))
25635 {
25636 emit_insn (gen_mem_thread_fence (GEN_INT (MEMMODEL_SEQ_CST)));
25637 }
25638 }
25639
25640 /* Split a compare and swap pattern. */
25641
25642 void
25643 aarch64_split_compare_and_swap (rtx operands[])
25644 {
25645 /* Split after prolog/epilog to avoid interactions with shrinkwrapping. */
25646 gcc_assert (epilogue_completed);
25647
25648 rtx rval, mem, oldval, newval, scratch, x, model_rtx;
25649 machine_mode mode;
25650 bool is_weak;
25651 rtx_code_label *label1, *label2;
25652 enum memmodel model;
25653
25654 rval = operands[0];
25655 mem = operands[1];
25656 oldval = operands[2];
25657 newval = operands[3];
25658 model_rtx = operands[5];
25659 scratch = operands[7];
25660 mode = GET_MODE (mem);
25661 model = memmodel_from_int (INTVAL (model_rtx));
25662 is_weak = operands[4] != const0_rtx && mode != TImode;
25663
25664 /* When OLDVAL is zero and we want the strong version we can emit a tighter
25665 loop:
25666 .label1:
25667 LD[A]XR rval, [mem]
25668 CBNZ rval, .label2
25669 ST[L]XR scratch, newval, [mem]
25670 CBNZ scratch, .label1
25671 .label2:
25672 CMP rval, 0. */
25673 bool strong_zero_p = (!is_weak && !aarch64_track_speculation &&
25674 oldval == const0_rtx && mode != TImode);
25675
25676 label1 = NULL;
25677 if (!is_weak)
25678 {
25679 label1 = gen_label_rtx ();
25680 emit_label (label1);
25681 }
25682 label2 = gen_label_rtx ();
25683
25684 /* The initial load can be relaxed for a __sync operation since a final
25685 barrier will be emitted to stop code hoisting. */
25686 if (is_mm_sync (model))
25687 aarch64_emit_load_exclusive (mode, rval, mem, GEN_INT (MEMMODEL_RELAXED));
25688 else
25689 aarch64_emit_load_exclusive (mode, rval, mem, model_rtx);
25690
25691 if (strong_zero_p)
25692 x = gen_rtx_NE (VOIDmode, rval, const0_rtx);
25693 else
25694 {
25695 rtx cc_reg = aarch64_gen_compare_reg_maybe_ze (NE, rval, oldval, mode);
25696 x = gen_rtx_NE (VOIDmode, cc_reg, const0_rtx);
25697 }
25698 x = gen_rtx_IF_THEN_ELSE (VOIDmode, x,
25699 gen_rtx_LABEL_REF (Pmode, label2), pc_rtx);
25700 aarch64_emit_unlikely_jump (gen_rtx_SET (pc_rtx, x));
25701
25702 aarch64_emit_store_exclusive (mode, scratch, mem, newval, model_rtx);
25703
25704 if (!is_weak)
25705 {
25706 x = aarch64_gen_compare_zero_and_branch (NE, scratch, label1);
25707 aarch64_emit_unlikely_jump (x);
25708 }
25709 else
25710 aarch64_gen_compare_reg (NE, scratch, const0_rtx);
25711
25712 /* 128-bit LDAXP is not atomic unless STLXP succeeds. So for a mismatch,
25713 store the returned value and loop if the STLXP fails. */
25714 if (mode == TImode)
25715 {
25716 rtx_code_label *label3 = gen_label_rtx ();
25717 emit_jump_insn (gen_rtx_SET (pc_rtx, gen_rtx_LABEL_REF (Pmode, label3)));
25718 emit_barrier ();
25719
25720 emit_label (label2);
25721 aarch64_emit_store_exclusive (mode, scratch, mem, rval, model_rtx);
25722
25723 x = aarch64_gen_compare_zero_and_branch (NE, scratch, label1);
25724 aarch64_emit_unlikely_jump (x);
25725
25726 label2 = label3;
25727 }
25728
25729 emit_label (label2);
25730
25731 /* If we used a CBNZ in the exchange loop emit an explicit compare with RVAL
25732 to set the condition flags. If this is not used it will be removed by
25733 later passes. */
25734 if (strong_zero_p)
25735 aarch64_gen_compare_reg (NE, rval, const0_rtx);
25736
25737 /* Emit any final barrier needed for a __sync operation. */
25738 if (is_mm_sync (model))
25739 aarch64_emit_post_barrier (model);
25740 }
25741
25742 /* Split an atomic operation. */
25743
25744 void
25745 aarch64_split_atomic_op (enum rtx_code code, rtx old_out, rtx new_out, rtx mem,
25746 rtx value, rtx model_rtx, rtx cond)
25747 {
25748 /* Split after prolog/epilog to avoid interactions with shrinkwrapping. */
25749 gcc_assert (epilogue_completed);
25750
25751 machine_mode mode = GET_MODE (mem);
25752 machine_mode wmode = (mode == DImode ? DImode : SImode);
25753 const enum memmodel model = memmodel_from_int (INTVAL (model_rtx));
25754 const bool is_sync = is_mm_sync (model);
25755 rtx_code_label *label;
25756 rtx x;
25757
25758 /* Split the atomic operation into a sequence. */
25759 label = gen_label_rtx ();
25760 emit_label (label);
25761
25762 if (new_out)
25763 new_out = gen_lowpart (wmode, new_out);
25764 if (old_out)
25765 old_out = gen_lowpart (wmode, old_out);
25766 else
25767 old_out = new_out;
25768 value = simplify_gen_subreg (wmode, value, mode, 0);
25769
25770 /* The initial load can be relaxed for a __sync operation since a final
25771 barrier will be emitted to stop code hoisting. */
25772 if (is_sync)
25773 aarch64_emit_load_exclusive (mode, old_out, mem,
25774 GEN_INT (MEMMODEL_RELAXED));
25775 else
25776 aarch64_emit_load_exclusive (mode, old_out, mem, model_rtx);
25777
25778 switch (code)
25779 {
25780 case SET:
25781 new_out = value;
25782 break;
25783
25784 case NOT:
25785 x = gen_rtx_AND (wmode, old_out, value);
25786 emit_insn (gen_rtx_SET (new_out, x));
25787 x = gen_rtx_NOT (wmode, new_out);
25788 emit_insn (gen_rtx_SET (new_out, x));
25789 break;
25790
25791 case MINUS:
25792 if (CONST_INT_P (value))
25793 {
25794 value = GEN_INT (-UINTVAL (value));
25795 code = PLUS;
25796 }
25797 /* Fall through. */
25798
25799 default:
25800 x = gen_rtx_fmt_ee (code, wmode, old_out, value);
25801 emit_insn (gen_rtx_SET (new_out, x));
25802 break;
25803 }
25804
25805 aarch64_emit_store_exclusive (mode, cond, mem,
25806 gen_lowpart (mode, new_out), model_rtx);
25807
25808 x = aarch64_gen_compare_zero_and_branch (NE, cond, label);
25809 aarch64_emit_unlikely_jump (x);
25810
25811 /* Emit any final barrier needed for a __sync operation. */
25812 if (is_sync)
25813 aarch64_emit_post_barrier (model);
25814 }
25815
25816 static void
25817 aarch64_init_libfuncs (void)
25818 {
25819 /* Half-precision float operations. The compiler handles all operations
25820 with NULL libfuncs by converting to SFmode. */
25821
25822 /* Conversions. */
25823 set_conv_libfunc (trunc_optab, HFmode, SFmode, "__gnu_f2h_ieee");
25824 set_conv_libfunc (sext_optab, SFmode, HFmode, "__gnu_h2f_ieee");
25825
25826 /* Arithmetic. */
25827 set_optab_libfunc (add_optab, HFmode, NULL);
25828 set_optab_libfunc (sdiv_optab, HFmode, NULL);
25829 set_optab_libfunc (smul_optab, HFmode, NULL);
25830 set_optab_libfunc (neg_optab, HFmode, NULL);
25831 set_optab_libfunc (sub_optab, HFmode, NULL);
25832
25833 /* Comparisons. */
25834 set_optab_libfunc (eq_optab, HFmode, NULL);
25835 set_optab_libfunc (ne_optab, HFmode, NULL);
25836 set_optab_libfunc (lt_optab, HFmode, NULL);
25837 set_optab_libfunc (le_optab, HFmode, NULL);
25838 set_optab_libfunc (ge_optab, HFmode, NULL);
25839 set_optab_libfunc (gt_optab, HFmode, NULL);
25840 set_optab_libfunc (unord_optab, HFmode, NULL);
25841 }
25842
25843 /* Target hook for c_mode_for_suffix. */
25844 static machine_mode
25845 aarch64_c_mode_for_suffix (char suffix)
25846 {
25847 if (suffix == 'q')
25848 return TFmode;
25849
25850 return VOIDmode;
25851 }
25852
25853 /* Return true iff X with mode MODE can be represented by a quarter-precision
25854 floating point immediate operand X. Note, we cannot represent 0.0. */
25855
25856 bool
25857 aarch64_float_const_representable_p (rtx x)
25858 {
25859 x = unwrap_const_vec_duplicate (x);
25860 machine_mode mode = GET_MODE (x);
25861
25862 if (DECIMAL_FLOAT_MODE_P (mode))
25863 return false;
25864
25865 if (!CONST_DOUBLE_P (x))
25866 return false;
25867
25868 if ((mode == HFmode && !TARGET_FP_F16INST)
25869 || mode == BFmode)
25870 return false;
25871
25872 REAL_VALUE_TYPE r = *CONST_DOUBLE_REAL_VALUE (x);
25873
25874 return aarch64_real_float_const_representable_p (r);
25875 }
25876
25877 /* Returns the string with the instruction for the SIMD immediate
25878 * CONST_VECTOR of MODE and WIDTH. WHICH selects a move, and(bic) or orr. */
25879 char*
25880 aarch64_output_simd_imm (rtx const_vector, unsigned width,
25881 enum simd_immediate_check which)
25882 {
25883 bool is_valid;
25884 static char templ[40];
25885 const char *mnemonic;
25886 const char *shift_op;
25887 unsigned int lane_count = 0;
25888 char element_char;
25889
25890 struct simd_immediate_info info;
25891
25892 is_valid = aarch64_simd_valid_imm (const_vector, &info, which);
25893 gcc_assert (is_valid);
25894
25895 element_char = sizetochar (GET_MODE_BITSIZE (info.elt_mode));
25896 lane_count = width / GET_MODE_BITSIZE (info.elt_mode);
25897
25898 if (GET_MODE_CLASS (info.elt_mode) == MODE_FLOAT)
25899 {
25900 gcc_assert (info.insn == simd_immediate_info::MOV
25901 && info.u.mov.shift == 0);
25902 /* For FP zero change it to a CONST_INT 0 and use the integer SIMD
25903 move immediate path. */
25904 if (aarch64_float_const_zero_rtx_p (info.u.mov.value))
25905 info.u.mov.value = GEN_INT (0);
25906 else
25907 {
25908 const unsigned int buf_size = 20;
25909 char float_buf[buf_size] = {'\0'};
25910 real_to_decimal_for_mode (float_buf,
25911 CONST_DOUBLE_REAL_VALUE (info.u.mov.value),
25912 buf_size, buf_size, 1, info.elt_mode);
25913
25914 if (lane_count == 1)
25915 snprintf (templ, sizeof (templ), "fmov\t%%d0, %s", float_buf);
25916 else
25917 snprintf (templ, sizeof (templ), "fmov\t%%0.%d%c, %s",
25918 lane_count, element_char, float_buf);
25919 return templ;
25920 }
25921 }
25922
25923 gcc_assert (CONST_INT_P (info.u.mov.value));
25924
25925 if (which == AARCH64_CHECK_MOV)
25926 {
25927 if (info.insn == simd_immediate_info::INDEX)
25928 {
25929 gcc_assert (TARGET_SVE);
25930 snprintf (templ, sizeof (templ), "index\t%%Z0.%c, #"
25931 HOST_WIDE_INT_PRINT_DEC ", #" HOST_WIDE_INT_PRINT_DEC,
25932 element_char, INTVAL (info.u.index.base),
25933 INTVAL (info.u.index.step));
25934 return templ;
25935 }
25936
25937 if (info.insn == simd_immediate_info::SVE_MOV)
25938 {
25939 gcc_assert (TARGET_SVE);
25940 snprintf (templ, sizeof (templ), "mov\t%%Z0.%c, #" HOST_WIDE_INT_PRINT_DEC,
25941 element_char, INTVAL (info.u.mov.value));
25942 return templ;
25943 }
25944
25945 mnemonic = info.insn == simd_immediate_info::MVN ? "mvni" : "movi";
25946 shift_op = (info.u.mov.modifier == simd_immediate_info::MSL
25947 ? "msl" : "lsl");
25948 if (lane_count == 1)
25949 snprintf (templ, sizeof (templ), "%s\t%%d0, " HOST_WIDE_INT_PRINT_HEX,
25950 mnemonic, UINTVAL (info.u.mov.value));
25951 else if (info.u.mov.shift)
25952 snprintf (templ, sizeof (templ), "%s\t%%0.%d%c, "
25953 HOST_WIDE_INT_PRINT_HEX ", %s %d", mnemonic, lane_count,
25954 element_char, UINTVAL (info.u.mov.value), shift_op,
25955 info.u.mov.shift);
25956 else
25957 snprintf (templ, sizeof (templ), "%s\t%%0.%d%c, "
25958 HOST_WIDE_INT_PRINT_HEX, mnemonic, lane_count,
25959 element_char, UINTVAL (info.u.mov.value));
25960 }
25961 else
25962 {
25963 /* AARCH64_CHECK_ORR, AARCH64_CHECK_AND or AARCH64_CHECK_XOR. */
25964 mnemonic = "orr";
25965 if (which == AARCH64_CHECK_AND)
25966 mnemonic = info.insn == simd_immediate_info::MVN ? "bic" : "and";
25967 else if (which == AARCH64_CHECK_XOR)
25968 mnemonic = "eor";
25969
25970 if (info.insn == simd_immediate_info::SVE_MOV)
25971 {
25972 gcc_assert (TARGET_SVE);
25973 snprintf (templ, sizeof (templ), "%s\t%%Z0.%c, %%Z0.%c, "
25974 HOST_WIDE_INT_PRINT_DEC, mnemonic, element_char,
25975 element_char, INTVAL (info.u.mov.value));
25976 }
25977 else if (info.u.mov.shift)
25978 snprintf (templ, sizeof (templ), "%s\t%%0.%d%c, #"
25979 HOST_WIDE_INT_PRINT_DEC ", %s #%d", mnemonic, lane_count,
25980 element_char, UINTVAL (info.u.mov.value), "lsl",
25981 info.u.mov.shift);
25982 else
25983 snprintf (templ, sizeof (templ), "%s\t%%0.%d%c, #"
25984 HOST_WIDE_INT_PRINT_DEC, mnemonic, lane_count,
25985 element_char, UINTVAL (info.u.mov.value));
25986 }
25987 return templ;
25988 }
25989
25990 /* Returns the string with the ORR instruction for the SIMD immediate
25991 CONST_VECTOR of WIDTH bits. */
25992 char*
25993 aarch64_output_simd_orr_imm (rtx const_vector, unsigned width)
25994 {
25995 return aarch64_output_simd_imm (const_vector, width, AARCH64_CHECK_ORR);
25996 }
25997
25998 /* Returns the string with the AND/BIC instruction for the SIMD immediate
25999 CONST_VECTOR of WIDTH bits. */
26000 char*
26001 aarch64_output_simd_and_imm (rtx const_vector, unsigned width)
26002 {
26003 return aarch64_output_simd_imm (const_vector, width, AARCH64_CHECK_AND);
26004 }
26005
26006 /* Returns the string with the EOR instruction for the SIMD immediate
26007 CONST_VECTOR of WIDTH bits. */
26008 char*
26009 aarch64_output_simd_xor_imm (rtx const_vector, unsigned width)
26010 {
26011 return aarch64_output_simd_imm (const_vector, width, AARCH64_CHECK_XOR);
26012 }
26013
26014 /* Returns the string with the MOV instruction for the SIMD immediate
26015 CONST_VECTOR of WIDTH bits. */
26016 char*
26017 aarch64_output_simd_mov_imm (rtx const_vector, unsigned width)
26018 {
26019 return aarch64_output_simd_imm (const_vector, width, AARCH64_CHECK_MOV);
26020 }
26021
26022 char*
26023 aarch64_output_scalar_simd_mov_immediate (rtx immediate, scalar_int_mode mode)
26024 {
26025
26026 /* If a floating point number was passed and we desire to use it in an
26027 integer mode do the conversion to integer. */
26028 if (CONST_DOUBLE_P (immediate) && GET_MODE_CLASS (mode) == MODE_INT)
26029 {
26030 unsigned HOST_WIDE_INT ival;
26031 if (!aarch64_reinterpret_float_as_int (immediate, &ival))
26032 gcc_unreachable ();
26033 immediate = gen_int_mode (ival, mode);
26034 }
26035
26036 machine_mode vmode;
26037 /* use a 64 bit mode for everything except for DI/DF/DD mode, where we use
26038 a 128 bit vector mode. */
26039 int width = GET_MODE_BITSIZE (mode) == 64 ? 128 : 64;
26040
26041 vmode = aarch64_simd_container_mode (mode, width);
26042 rtx v_op = aarch64_simd_gen_const_vector_dup (vmode, INTVAL (immediate));
26043 return aarch64_output_simd_mov_imm (v_op, width);
26044 }
26045
26046 /* Return the output string to use for moving immediate CONST_VECTOR
26047 into an SVE register. */
26048
26049 char *
26050 aarch64_output_sve_mov_immediate (rtx const_vector)
26051 {
26052 static char templ[40];
26053 struct simd_immediate_info info;
26054 char element_char;
26055 bool is_valid;
26056
26057 is_valid = aarch64_simd_valid_imm (const_vector, &info, AARCH64_CHECK_MOV);
26058 gcc_assert (is_valid);
26059
26060 element_char = sizetochar (GET_MODE_BITSIZE (info.elt_mode));
26061
26062 machine_mode vec_mode = GET_MODE (const_vector);
26063 if (aarch64_sve_pred_mode_p (vec_mode))
26064 {
26065 static char buf[sizeof ("ptrue\t%0.N, vlNNNNN")];
26066 if (info.insn == simd_immediate_info::MOV)
26067 {
26068 gcc_assert (info.u.mov.value == const0_rtx);
26069 snprintf (buf, sizeof (buf), "pfalse\t%%0.b");
26070 }
26071 else
26072 {
26073 gcc_assert (info.insn == simd_immediate_info::PTRUE);
26074 unsigned int total_bytes;
26075 if (info.u.pattern == AARCH64_SV_ALL
26076 && BYTES_PER_SVE_VECTOR.is_constant (&total_bytes))
26077 snprintf (buf, sizeof (buf), "ptrue\t%%0.%c, vl%d", element_char,
26078 total_bytes / GET_MODE_SIZE (info.elt_mode));
26079 else
26080 snprintf (buf, sizeof (buf), "ptrue\t%%0.%c, %s", element_char,
26081 svpattern_token (info.u.pattern));
26082 }
26083 return buf;
26084 }
26085
26086 if (info.insn == simd_immediate_info::INDEX)
26087 {
26088 snprintf (templ, sizeof (templ), "index\t%%0.%c, #"
26089 HOST_WIDE_INT_PRINT_DEC ", #" HOST_WIDE_INT_PRINT_DEC,
26090 element_char, INTVAL (info.u.index.base),
26091 INTVAL (info.u.index.step));
26092 return templ;
26093 }
26094
26095 if (GET_MODE_CLASS (info.elt_mode) == MODE_FLOAT)
26096 {
26097 if (aarch64_float_const_zero_rtx_p (info.u.mov.value))
26098 info.u.mov.value = GEN_INT (0);
26099 else
26100 {
26101 const int buf_size = 20;
26102 char float_buf[buf_size] = {};
26103 real_to_decimal_for_mode (float_buf,
26104 CONST_DOUBLE_REAL_VALUE (info.u.mov.value),
26105 buf_size, buf_size, 1, info.elt_mode);
26106
26107 snprintf (templ, sizeof (templ), "fmov\t%%0.%c, #%s",
26108 element_char, float_buf);
26109 return templ;
26110 }
26111 }
26112
26113 if (info.u.mov.value == const0_rtx && TARGET_NON_STREAMING)
26114 snprintf (templ, sizeof (templ), "movi\t%%d0, #0");
26115 else
26116 snprintf (templ, sizeof (templ), "mov\t%%0.%c, #" HOST_WIDE_INT_PRINT_DEC,
26117 element_char, INTVAL (info.u.mov.value));
26118 return templ;
26119 }
26120
26121 /* Return the asm template for a PTRUES. CONST_UNSPEC is the
26122 aarch64_sve_ptrue_svpattern_immediate that describes the predicate
26123 pattern. */
26124
26125 char *
26126 aarch64_output_sve_ptrues (rtx const_unspec)
26127 {
26128 static char templ[40];
26129 struct simd_immediate_info info;
26130 bool is_valid;
26131
26132 is_valid = aarch64_simd_valid_imm (const_unspec, &info, AARCH64_CHECK_MOV);
26133 gcc_assert (is_valid && info.insn == simd_immediate_info::PTRUE);
26134
26135 char element_char = sizetochar (GET_MODE_BITSIZE (info.elt_mode));
26136 snprintf (templ, sizeof (templ), "ptrues\t%%0.%c, %s", element_char,
26137 svpattern_token (info.u.pattern));
26138 return templ;
26139 }
26140
26141 /* Split operands into moves from op[1] + op[2] into op[0]. */
26142
26143 void
26144 aarch64_split_combinev16qi (rtx operands[3])
26145 {
26146 machine_mode halfmode = GET_MODE (operands[1]);
26147
26148 gcc_assert (halfmode == V16QImode);
26149
26150 rtx destlo = simplify_gen_subreg (halfmode, operands[0],
26151 GET_MODE (operands[0]), 0);
26152 rtx desthi = simplify_gen_subreg (halfmode, operands[0],
26153 GET_MODE (operands[0]),
26154 GET_MODE_SIZE (halfmode));
26155
26156 bool skiplo = rtx_equal_p (destlo, operands[1]);
26157 bool skiphi = rtx_equal_p (desthi, operands[2]);
26158
26159 if (skiplo && skiphi)
26160 {
26161 /* No-op move. Can't split to nothing; emit something. */
26162 emit_note (NOTE_INSN_DELETED);
26163 return;
26164 }
26165
26166 /* Special case of reversed high/low parts. */
26167 if (reg_overlap_mentioned_p (operands[2], destlo)
26168 && reg_overlap_mentioned_p (operands[1], desthi))
26169 {
26170 emit_insn (gen_xorv16qi3 (operands[1], operands[1], operands[2]));
26171 emit_insn (gen_xorv16qi3 (operands[2], operands[1], operands[2]));
26172 emit_insn (gen_xorv16qi3 (operands[1], operands[1], operands[2]));
26173 }
26174 else if (!reg_overlap_mentioned_p (operands[2], destlo))
26175 {
26176 /* Try to avoid unnecessary moves if part of the result
26177 is in the right place already. */
26178 if (!skiplo)
26179 emit_move_insn (destlo, operands[1]);
26180 if (!skiphi)
26181 emit_move_insn (desthi, operands[2]);
26182 }
26183 else
26184 {
26185 if (!skiphi)
26186 emit_move_insn (desthi, operands[2]);
26187 if (!skiplo)
26188 emit_move_insn (destlo, operands[1]);
26189 }
26190 }
26191
26192 /* vec_perm support. */
26193
26194 struct expand_vec_perm_d
26195 {
26196 rtx target, op0, op1;
26197 vec_perm_indices perm;
26198 machine_mode vmode;
26199 machine_mode op_mode;
26200 unsigned int vec_flags;
26201 unsigned int op_vec_flags;
26202 bool one_vector_p;
26203 bool zero_op0_p, zero_op1_p;
26204 bool testing_p;
26205 };
26206
26207 static bool aarch64_expand_vec_perm_const_1 (struct expand_vec_perm_d *d);
26208
26209 /* Generate a variable permutation. */
26210
26211 static void
26212 aarch64_expand_vec_perm_1 (rtx target, rtx op0, rtx op1, rtx sel)
26213 {
26214 machine_mode vmode = GET_MODE (target);
26215 bool one_vector_p = rtx_equal_p (op0, op1);
26216
26217 gcc_checking_assert (vmode == V8QImode || vmode == V16QImode);
26218 gcc_checking_assert (GET_MODE (op0) == vmode);
26219 gcc_checking_assert (GET_MODE (op1) == vmode);
26220 gcc_checking_assert (GET_MODE (sel) == vmode);
26221 gcc_checking_assert (TARGET_SIMD);
26222
26223 if (one_vector_p)
26224 {
26225 if (vmode == V8QImode)
26226 {
26227 /* Expand the argument to a V16QI mode by duplicating it. */
26228 rtx pair = gen_reg_rtx (V16QImode);
26229 emit_insn (gen_aarch64_combinev8qi (pair, op0, op0));
26230 emit_insn (gen_aarch64_qtbl1v8qi (target, pair, sel));
26231 }
26232 else
26233 {
26234 emit_insn (gen_aarch64_qtbl1v16qi (target, op0, sel));
26235 }
26236 }
26237 else
26238 {
26239 rtx pair;
26240
26241 if (vmode == V8QImode)
26242 {
26243 pair = gen_reg_rtx (V16QImode);
26244 emit_insn (gen_aarch64_combinev8qi (pair, op0, op1));
26245 emit_insn (gen_aarch64_qtbl1v8qi (target, pair, sel));
26246 }
26247 else
26248 {
26249 pair = gen_reg_rtx (V2x16QImode);
26250 emit_insn (gen_aarch64_combinev16qi (pair, op0, op1));
26251 emit_insn (gen_aarch64_qtbl2v16qi (target, pair, sel));
26252 }
26253 }
26254 }
26255
26256 /* Expand a vec_perm with the operands given by TARGET, OP0, OP1 and SEL.
26257 NELT is the number of elements in the vector. */
26258
26259 void
26260 aarch64_expand_vec_perm (rtx target, rtx op0, rtx op1, rtx sel,
26261 unsigned int nelt)
26262 {
26263 machine_mode vmode = GET_MODE (target);
26264 bool one_vector_p = rtx_equal_p (op0, op1);
26265 rtx mask;
26266
26267 /* The TBL instruction does not use a modulo index, so we must take care
26268 of that ourselves. */
26269 mask = aarch64_simd_gen_const_vector_dup (vmode,
26270 one_vector_p ? nelt - 1 : 2 * nelt - 1);
26271 sel = expand_simple_binop (vmode, AND, sel, mask, NULL, 0, OPTAB_LIB_WIDEN);
26272
26273 /* For big-endian, we also need to reverse the index within the vector
26274 (but not which vector). */
26275 if (BYTES_BIG_ENDIAN)
26276 {
26277 /* If one_vector_p, mask is a vector of (nelt - 1)'s already. */
26278 if (!one_vector_p)
26279 mask = aarch64_simd_gen_const_vector_dup (vmode, nelt - 1);
26280 sel = expand_simple_binop (vmode, XOR, sel, mask,
26281 NULL, 0, OPTAB_LIB_WIDEN);
26282 }
26283 aarch64_expand_vec_perm_1 (target, op0, op1, sel);
26284 }
26285
26286 /* Generate (set TARGET (unspec [OP0 OP1] CODE)). */
26287
26288 static void
26289 emit_unspec2 (rtx target, int code, rtx op0, rtx op1)
26290 {
26291 emit_insn (gen_rtx_SET (target,
26292 gen_rtx_UNSPEC (GET_MODE (target),
26293 gen_rtvec (2, op0, op1), code)));
26294 }
26295
26296 /* Expand an SVE vec_perm with the given operands. */
26297
26298 void
26299 aarch64_expand_sve_vec_perm (rtx target, rtx op0, rtx op1, rtx sel)
26300 {
26301 machine_mode data_mode = GET_MODE (target);
26302 machine_mode sel_mode = GET_MODE (sel);
26303 /* Enforced by the pattern condition. */
26304 int nunits = GET_MODE_NUNITS (sel_mode).to_constant ();
26305
26306 /* Note: vec_perm indices are supposed to wrap when they go beyond the
26307 size of the two value vectors, i.e. the upper bits of the indices
26308 are effectively ignored. SVE TBL instead produces 0 for any
26309 out-of-range indices, so we need to modulo all the vec_perm indices
26310 to ensure they are all in range. */
26311 rtx sel_reg = force_reg (sel_mode, sel);
26312
26313 /* Check if the sel only references the first values vector. */
26314 if (CONST_VECTOR_P (sel)
26315 && aarch64_const_vec_all_in_range_p (sel, 0, nunits - 1))
26316 {
26317 emit_unspec2 (target, UNSPEC_TBL, op0, sel_reg);
26318 return;
26319 }
26320
26321 /* Check if the two values vectors are the same. */
26322 if (rtx_equal_p (op0, op1))
26323 {
26324 rtx max_sel = aarch64_simd_gen_const_vector_dup (sel_mode, nunits - 1);
26325 rtx sel_mod = expand_simple_binop (sel_mode, AND, sel_reg, max_sel,
26326 NULL, 0, OPTAB_DIRECT);
26327 emit_unspec2 (target, UNSPEC_TBL, op0, sel_mod);
26328 return;
26329 }
26330
26331 /* Run TBL on for each value vector and combine the results. */
26332
26333 rtx res0 = gen_reg_rtx (data_mode);
26334 rtx res1 = gen_reg_rtx (data_mode);
26335 rtx neg_num_elems = aarch64_simd_gen_const_vector_dup (sel_mode, -nunits);
26336 if (!CONST_VECTOR_P (sel)
26337 || !aarch64_const_vec_all_in_range_p (sel, 0, 2 * nunits - 1))
26338 {
26339 rtx max_sel = aarch64_simd_gen_const_vector_dup (sel_mode,
26340 2 * nunits - 1);
26341 sel_reg = expand_simple_binop (sel_mode, AND, sel_reg, max_sel,
26342 NULL, 0, OPTAB_DIRECT);
26343 }
26344 emit_unspec2 (res0, UNSPEC_TBL, op0, sel_reg);
26345 rtx sel_sub = expand_simple_binop (sel_mode, PLUS, sel_reg, neg_num_elems,
26346 NULL, 0, OPTAB_DIRECT);
26347 emit_unspec2 (res1, UNSPEC_TBL, op1, sel_sub);
26348 if (GET_MODE_CLASS (data_mode) == MODE_VECTOR_INT)
26349 emit_insn (gen_rtx_SET (target, gen_rtx_IOR (data_mode, res0, res1)));
26350 else
26351 emit_unspec2 (target, UNSPEC_IORF, res0, res1);
26352 }
26353
26354 /* Recognize patterns suitable for the TRN instructions. */
26355 static bool
26356 aarch64_evpc_trn (struct expand_vec_perm_d *d)
26357 {
26358 HOST_WIDE_INT odd;
26359 poly_uint64 nelt = d->perm.length ();
26360 rtx out, in0, in1;
26361 machine_mode vmode = d->vmode;
26362
26363 if (GET_MODE_UNIT_SIZE (vmode) > 8)
26364 return false;
26365
26366 /* Note that these are little-endian tests.
26367 We correct for big-endian later. */
26368 if (!d->perm[0].is_constant (&odd)
26369 || (odd != 0 && odd != 1)
26370 || !d->perm.series_p (0, 2, odd, 2)
26371 || !d->perm.series_p (1, 2, nelt + odd, 2))
26372 return false;
26373
26374 /* Success! */
26375 if (d->testing_p)
26376 return true;
26377
26378 in0 = d->op0;
26379 in1 = d->op1;
26380 /* We don't need a big-endian lane correction for SVE; see the comment
26381 at the head of aarch64-sve.md for details. */
26382 if (BYTES_BIG_ENDIAN && d->vec_flags == VEC_ADVSIMD)
26383 {
26384 std::swap (in0, in1);
26385 odd = !odd;
26386 }
26387 out = d->target;
26388
26389 emit_set_insn (out, gen_rtx_UNSPEC (vmode, gen_rtvec (2, in0, in1),
26390 odd ? UNSPEC_TRN2 : UNSPEC_TRN1));
26391 return true;
26392 }
26393
26394 /* Try to re-encode the PERM constant so it combines odd and even elements.
26395 This rewrites constants such as {0, 1, 4, 5}/V4SF to {0, 2}/V2DI.
26396 We retry with this new constant with the full suite of patterns. */
26397 static bool
26398 aarch64_evpc_reencode (struct expand_vec_perm_d *d)
26399 {
26400 expand_vec_perm_d newd;
26401
26402 /* The subregs that we'd create are not supported for big-endian SVE;
26403 see aarch64_modes_compatible_p for details. */
26404 if (BYTES_BIG_ENDIAN && (d->vec_flags & VEC_ANY_SVE))
26405 return false;
26406
26407 /* Get the new mode. Always twice the size of the inner
26408 and half the elements. */
26409 machine_mode new_mode;
26410 if (!aarch64_coalesce_units (d->vmode, 2).exists (&new_mode))
26411 return false;
26412
26413 vec_perm_indices newpermindices;
26414 if (!newpermindices.new_shrunk_vector (d->perm, 2))
26415 return false;
26416
26417 newd.vmode = new_mode;
26418 newd.vec_flags = d->vec_flags;
26419 newd.op_mode = newd.vmode;
26420 newd.op_vec_flags = newd.vec_flags;
26421 newd.target = d->target ? gen_lowpart (new_mode, d->target) : NULL;
26422 newd.op0 = d->op0 ? gen_lowpart (new_mode, d->op0) : NULL;
26423 newd.op1 = d->op1 ? gen_lowpart (new_mode, d->op1) : NULL;
26424 newd.testing_p = d->testing_p;
26425 newd.one_vector_p = d->one_vector_p;
26426
26427 newd.perm.new_vector (newpermindices.encoding (), newd.one_vector_p ? 1 : 2,
26428 newpermindices.nelts_per_input ());
26429 return aarch64_expand_vec_perm_const_1 (&newd);
26430 }
26431
26432 /* Recognize patterns suitable for the UZP instructions. */
26433 static bool
26434 aarch64_evpc_uzp (struct expand_vec_perm_d *d)
26435 {
26436 HOST_WIDE_INT odd;
26437 rtx out, in0, in1;
26438 machine_mode vmode = d->vmode;
26439
26440 if (GET_MODE_UNIT_SIZE (vmode) > 8)
26441 return false;
26442
26443 /* Note that these are little-endian tests.
26444 We correct for big-endian later. */
26445 if (!d->perm[0].is_constant (&odd)
26446 || (odd != 0 && odd != 1)
26447 || !d->perm.series_p (0, 1, odd, 2))
26448 return false;
26449
26450 /* Success! */
26451 if (d->testing_p)
26452 return true;
26453
26454 in0 = d->op0;
26455 in1 = d->op1;
26456 /* We don't need a big-endian lane correction for SVE; see the comment
26457 at the head of aarch64-sve.md for details. */
26458 if (BYTES_BIG_ENDIAN && d->vec_flags == VEC_ADVSIMD)
26459 {
26460 std::swap (in0, in1);
26461 odd = !odd;
26462 }
26463 out = d->target;
26464
26465 emit_set_insn (out, gen_rtx_UNSPEC (vmode, gen_rtvec (2, in0, in1),
26466 odd ? UNSPEC_UZP2 : UNSPEC_UZP1));
26467 return true;
26468 }
26469
26470 /* Recognize patterns suitable for the ZIP instructions. */
26471 static bool
26472 aarch64_evpc_zip (struct expand_vec_perm_d *d)
26473 {
26474 unsigned int high;
26475 poly_uint64 nelt = d->perm.length ();
26476 rtx out, in0, in1;
26477 machine_mode vmode = d->vmode;
26478
26479 if (GET_MODE_UNIT_SIZE (vmode) > 8)
26480 return false;
26481
26482 /* Note that these are little-endian tests.
26483 We correct for big-endian later. */
26484 poly_uint64 first = d->perm[0];
26485 if ((maybe_ne (first, 0U) && maybe_ne (first * 2, nelt))
26486 || !d->perm.series_p (0, 2, first, 1)
26487 || !d->perm.series_p (1, 2, first + nelt, 1))
26488 return false;
26489 high = maybe_ne (first, 0U);
26490
26491 /* Success! */
26492 if (d->testing_p)
26493 return true;
26494
26495 in0 = d->op0;
26496 in1 = d->op1;
26497 /* We don't need a big-endian lane correction for SVE; see the comment
26498 at the head of aarch64-sve.md for details. */
26499 if (BYTES_BIG_ENDIAN && d->vec_flags == VEC_ADVSIMD)
26500 {
26501 std::swap (in0, in1);
26502 high = !high;
26503 }
26504 out = d->target;
26505
26506 emit_set_insn (out, gen_rtx_UNSPEC (vmode, gen_rtvec (2, in0, in1),
26507 high ? UNSPEC_ZIP2 : UNSPEC_ZIP1));
26508 return true;
26509 }
26510
26511 /* Recognize patterns for the EXT insn. */
26512
26513 static bool
26514 aarch64_evpc_ext (struct expand_vec_perm_d *d)
26515 {
26516 HOST_WIDE_INT location;
26517 rtx offset;
26518
26519 /* The first element always refers to the first vector.
26520 Check if the extracted indices are increasing by one. */
26521 if ((d->vec_flags & VEC_SVE_PRED)
26522 || !d->perm[0].is_constant (&location)
26523 || !d->perm.series_p (0, 1, location, 1))
26524 return false;
26525
26526 /* Success! */
26527 if (d->testing_p)
26528 return true;
26529
26530 /* The case where (location == 0) is a no-op for both big- and little-endian,
26531 and is removed by the mid-end at optimization levels -O1 and higher.
26532
26533 We don't need a big-endian lane correction for SVE; see the comment
26534 at the head of aarch64-sve.md for details. */
26535 if (BYTES_BIG_ENDIAN && location != 0 && d->vec_flags == VEC_ADVSIMD)
26536 {
26537 /* After setup, we want the high elements of the first vector (stored
26538 at the LSB end of the register), and the low elements of the second
26539 vector (stored at the MSB end of the register). So swap. */
26540 std::swap (d->op0, d->op1);
26541 /* location != 0 (above), so safe to assume (nelt - location) < nelt.
26542 to_constant () is safe since this is restricted to Advanced SIMD
26543 vectors. */
26544 location = d->perm.length ().to_constant () - location;
26545 }
26546
26547 offset = GEN_INT (location);
26548 emit_set_insn (d->target,
26549 gen_rtx_UNSPEC (d->vmode,
26550 gen_rtvec (3, d->op0, d->op1, offset),
26551 UNSPEC_EXT));
26552 return true;
26553 }
26554
26555 /* Recognize patterns for the REV{64,32,16} insns, which reverse elements
26556 within each 64-bit, 32-bit or 16-bit granule. */
26557
26558 static bool
26559 aarch64_evpc_rev_local (struct expand_vec_perm_d *d)
26560 {
26561 HOST_WIDE_INT diff;
26562 unsigned int i, size, unspec;
26563 machine_mode pred_mode;
26564
26565 if ((d->vec_flags & VEC_SVE_PRED)
26566 || !d->one_vector_p
26567 || !d->perm[0].is_constant (&diff)
26568 || !diff)
26569 return false;
26570
26571 if (d->vec_flags & VEC_SVE_DATA)
26572 size = (diff + 1) * aarch64_sve_container_bits (d->vmode);
26573 else
26574 size = (diff + 1) * GET_MODE_UNIT_BITSIZE (d->vmode);
26575 if (size == 64)
26576 {
26577 unspec = UNSPEC_REV64;
26578 pred_mode = VNx2BImode;
26579 }
26580 else if (size == 32)
26581 {
26582 unspec = UNSPEC_REV32;
26583 pred_mode = VNx4BImode;
26584 }
26585 else if (size == 16)
26586 {
26587 unspec = UNSPEC_REV16;
26588 pred_mode = VNx8BImode;
26589 }
26590 else
26591 return false;
26592
26593 unsigned int step = diff + 1;
26594 for (i = 0; i < step; ++i)
26595 if (!d->perm.series_p (i, step, diff - i, step))
26596 return false;
26597
26598 /* Success! */
26599 if (d->testing_p)
26600 return true;
26601
26602 if (d->vec_flags & VEC_SVE_DATA)
26603 {
26604 rtx pred = aarch64_ptrue_reg (pred_mode);
26605 emit_insn (gen_aarch64_sve_revbhw (d->vmode, pred_mode,
26606 d->target, pred, d->op0));
26607 return true;
26608 }
26609 rtx src = gen_rtx_UNSPEC (d->vmode, gen_rtvec (1, d->op0), unspec);
26610 emit_set_insn (d->target, src);
26611 return true;
26612 }
26613
26614 /* Recognize patterns for the REV insn, which reverses elements within
26615 a full vector. */
26616
26617 static bool
26618 aarch64_evpc_rev_global (struct expand_vec_perm_d *d)
26619 {
26620 poly_uint64 nelt = d->perm.length ();
26621
26622 if (!d->one_vector_p || d->vec_flags == VEC_ADVSIMD)
26623 return false;
26624
26625 if (!d->perm.series_p (0, 1, nelt - 1, -1))
26626 return false;
26627
26628 /* Success! */
26629 if (d->testing_p)
26630 return true;
26631
26632 rtx src = gen_rtx_UNSPEC (d->vmode, gen_rtvec (1, d->op0), UNSPEC_REV);
26633 emit_set_insn (d->target, src);
26634 return true;
26635 }
26636
26637 static bool
26638 aarch64_evpc_dup (struct expand_vec_perm_d *d)
26639 {
26640 rtx out = d->target;
26641 rtx in0;
26642 HOST_WIDE_INT elt;
26643 machine_mode vmode = d->vmode;
26644 rtx lane;
26645
26646 if ((d->vec_flags & VEC_SVE_PRED)
26647 || d->perm.encoding ().encoded_nelts () != 1
26648 || !d->perm[0].is_constant (&elt))
26649 return false;
26650
26651 if ((d->vec_flags & VEC_SVE_DATA)
26652 && elt * (aarch64_sve_container_bits (vmode) / 8) >= 64)
26653 return false;
26654
26655 /* Success! */
26656 if (d->testing_p)
26657 return true;
26658
26659 /* The generic preparation in aarch64_expand_vec_perm_const_1
26660 swaps the operand order and the permute indices if it finds
26661 d->perm[0] to be in the second operand. Thus, we can always
26662 use d->op0 and need not do any extra arithmetic to get the
26663 correct lane number. */
26664 in0 = d->op0;
26665 lane = GEN_INT (elt); /* The pattern corrects for big-endian. */
26666
26667 rtx parallel = gen_rtx_PARALLEL (VOIDmode, gen_rtvec (1, lane));
26668 rtx select = gen_rtx_VEC_SELECT (GET_MODE_INNER (vmode), in0, parallel);
26669 emit_set_insn (out, gen_rtx_VEC_DUPLICATE (vmode, select));
26670 return true;
26671 }
26672
26673 /* Recognize things that can be done using the SVE2p1 Hybrid-VLA
26674 permutations, which apply Advanced-SIMD-style permutations to each
26675 individual 128-bit block. */
26676
26677 static bool
26678 aarch64_evpc_hvla (struct expand_vec_perm_d *d)
26679 {
26680 machine_mode vmode = d->vmode;
26681 if (!TARGET_SVE2p1
26682 || !TARGET_NON_STREAMING
26683 || d->vec_flags != VEC_SVE_DATA
26684 || GET_MODE_UNIT_BITSIZE (vmode) > 64)
26685 return false;
26686
26687 /* Set SUBELTS to the number of elements in an Advanced SIMD vector
26688 and make sure that adding SUBELTS to each block of SUBELTS indices
26689 gives the next block of SUBELTS indices. That is, it must be possible
26690 to interpret the index vector as SUBELTS interleaved linear series in
26691 which each series has step SUBELTS. */
26692 unsigned int subelts = 128U / GET_MODE_UNIT_BITSIZE (vmode);
26693 unsigned int pairs = subelts / 2;
26694 for (unsigned int i = 0; i < subelts; ++i)
26695 if (!d->perm.series_p (i, subelts, d->perm[i], subelts))
26696 return false;
26697
26698 /* Used once we have verified that we can use UNSPEC to do the operation. */
26699 auto use_binary = [&](int unspec) -> bool
26700 {
26701 if (!d->testing_p)
26702 {
26703 rtvec vec = gen_rtvec (2, d->op0, d->op1);
26704 emit_set_insn (d->target, gen_rtx_UNSPEC (vmode, vec, unspec));
26705 }
26706 return true;
26707 };
26708
26709 /* Now check whether the first SUBELTS elements match a supported
26710 Advanced-SIMD-style operation. */
26711 poly_int64 first = d->perm[0];
26712 poly_int64 nelt = d->perm.length ();
26713 auto try_zip = [&]() -> bool
26714 {
26715 if (maybe_ne (first, 0) && maybe_ne (first, pairs))
26716 return false;
26717 for (unsigned int i = 0; i < pairs; ++i)
26718 if (maybe_ne (d->perm[i * 2], first + i)
26719 || maybe_ne (d->perm[i * 2 + 1], first + nelt + i))
26720 return false;
26721 return use_binary (maybe_ne (first, 0) ? UNSPEC_ZIPQ2 : UNSPEC_ZIPQ1);
26722 };
26723 auto try_uzp = [&]() -> bool
26724 {
26725 if (maybe_ne (first, 0) && maybe_ne (first, 1))
26726 return false;
26727 for (unsigned int i = 0; i < pairs; ++i)
26728 if (maybe_ne (d->perm[i], first + i * 2)
26729 || maybe_ne (d->perm[i + pairs], first + nelt + i * 2))
26730 return false;
26731 return use_binary (maybe_ne (first, 0) ? UNSPEC_UZPQ2 : UNSPEC_UZPQ1);
26732 };
26733 auto try_extq = [&]() -> bool
26734 {
26735 HOST_WIDE_INT start;
26736 if (!first.is_constant (&start) || !IN_RANGE (start, 0, subelts - 1))
26737 return false;
26738 for (unsigned int i = 0; i < subelts; ++i)
26739 {
26740 poly_int64 next = (start + i >= subelts
26741 ? start + i - subelts + nelt
26742 : start + i);
26743 if (maybe_ne (d->perm[i], next))
26744 return false;
26745 }
26746 if (!d->testing_p)
26747 {
26748 rtx op2 = gen_int_mode (start, SImode);
26749 emit_insn (gen_aarch64_sve_extq (vmode, d->target,
26750 d->op0, d->op1, op2));
26751 }
26752 return true;
26753 };
26754 auto try_dupq = [&]() -> bool
26755 {
26756 HOST_WIDE_INT start;
26757 if (!first.is_constant (&start) || !IN_RANGE (start, 0, subelts - 1))
26758 return false;
26759 for (unsigned int i = 0; i < subelts; ++i)
26760 if (maybe_ne (d->perm[i], start))
26761 return false;
26762 if (!d->testing_p)
26763 {
26764 rtx op1 = gen_int_mode (start, SImode);
26765 emit_insn (gen_aarch64_sve_dupq (vmode, d->target, d->op0, op1));
26766 }
26767 return true;
26768 };
26769
26770 return try_zip () || try_uzp () || try_extq () || try_dupq ();
26771 }
26772
26773 static bool
26774 aarch64_evpc_tbl (struct expand_vec_perm_d *d)
26775 {
26776 rtx rperm[MAX_COMPILE_TIME_VEC_BYTES], sel;
26777 machine_mode vmode = d->vmode;
26778
26779 /* Make sure that the indices are constant. */
26780 unsigned int encoded_nelts = d->perm.encoding ().encoded_nelts ();
26781 for (unsigned int i = 0; i < encoded_nelts; ++i)
26782 if (!d->perm[i].is_constant ())
26783 return false;
26784
26785 if (d->testing_p)
26786 return true;
26787
26788 /* Generic code will try constant permutation twice. Once with the
26789 original mode and again with the elements lowered to QImode.
26790 So wait and don't do the selector expansion ourselves. */
26791 if (vmode != V8QImode && vmode != V16QImode)
26792 return false;
26793
26794 /* to_constant is safe since this routine is specific to Advanced SIMD
26795 vectors. */
26796 unsigned int nelt = d->perm.length ().to_constant ();
26797
26798 /* If one register is the constant vector of 0 then we only need
26799 a one reg TBL and we map any accesses to the vector of 0 to -1. We can't
26800 do this earlier since vec_perm_indices clamps elements to within range so
26801 we can only do it during codegen. */
26802 if (d->zero_op0_p)
26803 d->op0 = d->op1;
26804 else if (d->zero_op1_p)
26805 d->op1 = d->op0;
26806
26807 for (unsigned int i = 0; i < nelt; ++i)
26808 {
26809 auto val = d->perm[i].to_constant ();
26810
26811 /* If we're selecting from a 0 vector, we can just use an out of range
26812 index instead. */
26813 if ((d->zero_op0_p && val < nelt) || (d->zero_op1_p && val >= nelt))
26814 rperm[i] = constm1_rtx;
26815 else
26816 {
26817 /* If we are remapping a zero register as the first parameter we need
26818 to adjust the indices of the non-zero register. */
26819 if (d->zero_op0_p)
26820 val = val % nelt;
26821
26822 /* If big-endian and two vectors we end up with a weird mixed-endian
26823 mode on NEON. Reverse the index within each word but not the word
26824 itself. to_constant is safe because we checked is_constant
26825 above. */
26826 rperm[i] = GEN_INT (BYTES_BIG_ENDIAN ? val ^ (nelt - 1) : val);
26827 }
26828 }
26829
26830 sel = gen_rtx_CONST_VECTOR (vmode, gen_rtvec_v (nelt, rperm));
26831 sel = force_reg (vmode, sel);
26832
26833 aarch64_expand_vec_perm_1 (d->target, d->op0, d->op1, sel);
26834 return true;
26835 }
26836
26837 /* Try to implement D using an SVE TBL instruction. */
26838
26839 static bool
26840 aarch64_evpc_sve_tbl (struct expand_vec_perm_d *d)
26841 {
26842 if (!d->one_vector_p)
26843 {
26844 /* aarch64_expand_sve_vec_perm does not yet handle variable-length
26845 vectors. */
26846 if (!d->perm.length ().is_constant ())
26847 return false;
26848
26849 /* This permutation reduces to the vec_perm optab if the elements are
26850 large enough to hold all selector indices. Do not handle that case
26851 here, since the general TBL+SUB+TBL+ORR sequence is too expensive to
26852 be considered a "native" constant permutation.
26853
26854 Not doing this would undermine code that queries can_vec_perm_const_p
26855 with allow_variable_p set to false. See PR121027. */
26856 if (selector_fits_mode_p (d->vmode, d->perm))
26857 return false;
26858 }
26859
26860 if (d->testing_p)
26861 return true;
26862
26863 machine_mode sel_mode = related_int_vector_mode (d->vmode).require ();
26864 rtx sel = vec_perm_indices_to_rtx (sel_mode, d->perm);
26865 if (d->one_vector_p)
26866 emit_unspec2 (d->target, UNSPEC_TBL, d->op0, force_reg (sel_mode, sel));
26867 else
26868 aarch64_expand_sve_vec_perm (d->target, d->op0, d->op1, sel);
26869 return true;
26870 }
26871
26872 /* Try to implement D using SVE dup instruction. */
26873
26874 static bool
26875 aarch64_evpc_sve_dup (struct expand_vec_perm_d *d)
26876 {
26877 if (BYTES_BIG_ENDIAN
26878 || !d->one_vector_p
26879 || d->vec_flags != VEC_SVE_DATA
26880 || d->op_vec_flags != VEC_ADVSIMD
26881 || d->perm.encoding ().nelts_per_pattern () != 1
26882 || !known_eq (d->perm.encoding ().npatterns (),
26883 GET_MODE_NUNITS (d->op_mode))
26884 || !known_eq (GET_MODE_BITSIZE (d->op_mode), 128))
26885 return false;
26886
26887 int npatterns = d->perm.encoding ().npatterns ();
26888 for (int i = 0; i < npatterns; i++)
26889 if (!known_eq (d->perm[i], i))
26890 return false;
26891
26892 if (d->testing_p)
26893 return true;
26894
26895 aarch64_expand_sve_dupq (d->target, GET_MODE (d->target), d->op0);
26896 return true;
26897 }
26898
26899 /* Try to implement D using SVE SEL instruction. */
26900
26901 static bool
26902 aarch64_evpc_sel (struct expand_vec_perm_d *d)
26903 {
26904 machine_mode vmode = d->vmode;
26905 int unit_size = GET_MODE_UNIT_SIZE (vmode);
26906
26907 if (d->vec_flags != VEC_SVE_DATA
26908 || unit_size > 8)
26909 return false;
26910
26911 int n_patterns = d->perm.encoding ().npatterns ();
26912 poly_int64 vec_len = d->perm.length ();
26913
26914 for (int i = 0; i < n_patterns; ++i)
26915 if (!known_eq (d->perm[i], i)
26916 && !known_eq (d->perm[i], vec_len + i))
26917 return false;
26918
26919 for (int i = n_patterns; i < n_patterns * 2; i++)
26920 if (!d->perm.series_p (i, n_patterns, i, n_patterns)
26921 && !d->perm.series_p (i, n_patterns, vec_len + i, n_patterns))
26922 return false;
26923
26924 if (d->testing_p)
26925 return true;
26926
26927 machine_mode pred_mode = aarch64_sve_pred_mode (vmode);
26928
26929 /* Build a predicate that is true when op0 elements should be used. */
26930 rtx_vector_builder builder (pred_mode, n_patterns, 2);
26931 for (int i = 0; i < n_patterns * 2; i++)
26932 {
26933 rtx elem = known_eq (d->perm[i], i) ? CONST1_RTX (BImode)
26934 : CONST0_RTX (BImode);
26935 builder.quick_push (elem);
26936 }
26937
26938 rtx const_vec = builder.build ();
26939 rtx pred = force_reg (pred_mode, const_vec);
26940 /* TARGET = PRED ? OP0 : OP1. */
26941 emit_insn (gen_vcond_mask (vmode, vmode, d->target, d->op0, d->op1, pred));
26942 return true;
26943 }
26944
26945 /* Recognize patterns suitable for the INS instructions. */
26946 static bool
26947 aarch64_evpc_ins (struct expand_vec_perm_d *d)
26948 {
26949 machine_mode mode = d->vmode;
26950 unsigned HOST_WIDE_INT nelt;
26951
26952 if (d->vec_flags != VEC_ADVSIMD)
26953 return false;
26954
26955 /* to_constant is safe since this routine is specific to Advanced SIMD
26956 vectors. */
26957 nelt = d->perm.length ().to_constant ();
26958 rtx insv = d->op0;
26959
26960 HOST_WIDE_INT idx = -1;
26961
26962 for (unsigned HOST_WIDE_INT i = 0; i < nelt; i++)
26963 {
26964 HOST_WIDE_INT elt;
26965 if (!d->perm[i].is_constant (&elt))
26966 return false;
26967 if (elt == (HOST_WIDE_INT) i)
26968 continue;
26969 if (idx != -1)
26970 {
26971 idx = -1;
26972 break;
26973 }
26974 idx = i;
26975 }
26976
26977 if (idx == -1)
26978 {
26979 insv = d->op1;
26980 for (unsigned HOST_WIDE_INT i = 0; i < nelt; i++)
26981 {
26982 if (d->perm[i].to_constant () == (HOST_WIDE_INT) (i + nelt))
26983 continue;
26984 if (idx != -1)
26985 return false;
26986 idx = i;
26987 }
26988
26989 if (idx == -1)
26990 return false;
26991 }
26992
26993 if (d->testing_p)
26994 return true;
26995
26996 gcc_assert (idx != -1);
26997
26998 unsigned extractindex = d->perm[idx].to_constant ();
26999 rtx extractv = d->op0;
27000 if (extractindex >= nelt)
27001 {
27002 extractv = d->op1;
27003 extractindex -= nelt;
27004 }
27005 gcc_assert (extractindex < nelt);
27006
27007 insn_code icode = code_for_aarch64_simd_vec_copy_lane (mode);
27008 expand_operand ops[5];
27009 create_output_operand (&ops[0], d->target, mode);
27010 create_input_operand (&ops[1], insv, mode);
27011 create_integer_operand (&ops[2], 1 << idx);
27012 create_input_operand (&ops[3], extractv, mode);
27013 create_integer_operand (&ops[4], extractindex);
27014 expand_insn (icode, 5, ops);
27015
27016 return true;
27017 }
27018
27019 static bool
27020 aarch64_expand_vec_perm_const_1 (struct expand_vec_perm_d *d)
27021 {
27022 gcc_assert (d->op_mode != E_VOIDmode);
27023
27024 /* The pattern matching functions above are written to look for a small
27025 number to begin the sequence (0, 1, N/2). If we begin with an index
27026 from the second operand, we can swap the operands. */
27027 poly_int64 nelt = d->perm.length ();
27028 if (known_ge (d->perm[0], nelt))
27029 {
27030 d->perm.rotate_inputs (1);
27031 std::swap (d->op0, d->op1);
27032 }
27033
27034 if (((d->vec_flags == VEC_ADVSIMD && TARGET_SIMD)
27035 || d->vec_flags == VEC_SVE_DATA
27036 || d->vec_flags == (VEC_SVE_DATA | VEC_PARTIAL)
27037 || d->vec_flags == VEC_SVE_PRED)
27038 && known_gt (nelt, 1))
27039 {
27040 if (d->vmode == d->op_mode)
27041 {
27042 if (aarch64_evpc_rev_local (d))
27043 return true;
27044 else if (aarch64_evpc_rev_global (d))
27045 return true;
27046 else if (aarch64_evpc_ext (d))
27047 return true;
27048 else if (aarch64_evpc_dup (d))
27049 return true;
27050 else if (aarch64_evpc_zip (d))
27051 return true;
27052 else if (aarch64_evpc_uzp (d))
27053 return true;
27054 else if (aarch64_evpc_trn (d))
27055 return true;
27056 else if (aarch64_evpc_sel (d))
27057 return true;
27058 else if (aarch64_evpc_ins (d))
27059 return true;
27060 else if (aarch64_evpc_hvla (d))
27061 return true;
27062 else if (aarch64_evpc_reencode (d))
27063 return true;
27064
27065 if (d->vec_flags == VEC_SVE_DATA)
27066 return aarch64_evpc_sve_tbl (d);
27067 else if (d->vec_flags == VEC_ADVSIMD)
27068 return aarch64_evpc_tbl (d);
27069 }
27070 else
27071 {
27072 if (aarch64_evpc_sve_dup (d))
27073 return true;
27074 }
27075 }
27076 return false;
27077 }
27078
27079 /* Implement TARGET_VECTORIZE_VEC_PERM_CONST. */
27080
27081 static bool
27082 aarch64_vectorize_vec_perm_const (machine_mode vmode, machine_mode op_mode,
27083 rtx target, rtx op0, rtx op1,
27084 const vec_perm_indices &sel)
27085 {
27086 struct expand_vec_perm_d d;
27087
27088 /* Check whether the mask can be applied to a single vector. */
27089 if (sel.ninputs () == 1
27090 || (op0 && rtx_equal_p (op0, op1)))
27091 d.one_vector_p = true;
27092 else if (sel.all_from_input_p (0))
27093 {
27094 d.one_vector_p = true;
27095 op1 = op0;
27096 }
27097 else if (sel.all_from_input_p (1))
27098 {
27099 d.one_vector_p = true;
27100 op0 = op1;
27101 }
27102 else
27103 d.one_vector_p = false;
27104
27105 d.zero_op0_p = op0 == CONST0_RTX (op_mode);
27106 d.zero_op1_p = op1 == CONST0_RTX (op_mode);
27107 d.perm.new_vector (sel.encoding (), d.one_vector_p ? 1 : 2,
27108 sel.nelts_per_input ());
27109 d.vmode = vmode;
27110 d.vec_flags = aarch64_classify_vector_mode (d.vmode);
27111 d.op_mode = op_mode;
27112 d.op_vec_flags = aarch64_classify_vector_mode (d.op_mode);
27113 d.target = target;
27114 d.op0 = op0 ? force_reg (op_mode, op0) : NULL_RTX;
27115 if (op0 && d.one_vector_p)
27116 d.op1 = copy_rtx (d.op0);
27117 else
27118 d.op1 = op1 ? force_reg (op_mode, op1) : NULL_RTX;
27119 d.testing_p = !target;
27120
27121 if (!d.testing_p)
27122 return aarch64_expand_vec_perm_const_1 (&d);
27123
27124 rtx_insn *last = get_last_insn ();
27125 bool ret = aarch64_expand_vec_perm_const_1 (&d);
27126 gcc_assert (last == get_last_insn ());
27127
27128 return ret;
27129 }
27130 /* Generate a byte permute mask for a register of mode MODE,
27131 which has NUNITS units. */
27132
27133 rtx
27134 aarch64_reverse_mask (machine_mode mode, unsigned int nunits)
27135 {
27136 /* We have to reverse each vector because we dont have
27137 a permuted load that can reverse-load according to ABI rules. */
27138 rtx mask;
27139 rtvec v = rtvec_alloc (16);
27140 unsigned int i, j;
27141 unsigned int usize = GET_MODE_UNIT_SIZE (mode);
27142
27143 gcc_assert (BYTES_BIG_ENDIAN);
27144 gcc_assert (AARCH64_VALID_SIMD_QREG_MODE (mode));
27145
27146 for (i = 0; i < nunits; i++)
27147 for (j = 0; j < usize; j++)
27148 RTVEC_ELT (v, i * usize + j) = GEN_INT ((i + 1) * usize - 1 - j);
27149 mask = gen_rtx_CONST_VECTOR (V16QImode, v);
27150 return force_reg (V16QImode, mask);
27151 }
27152
27153 /* Expand an SVE integer comparison using the SVE equivalent of:
27154
27155 (set TARGET (CODE OP0 OP1)). */
27156
27157 void
27158 aarch64_expand_sve_vec_cmp_int (rtx target, rtx_code code, rtx op0, rtx op1)
27159 {
27160 machine_mode pred_mode = GET_MODE (target);
27161 machine_mode data_mode = GET_MODE (op0);
27162 rtx res = aarch64_sve_emit_int_cmp (target, pred_mode, code, data_mode,
27163 op0, op1);
27164 if (!rtx_equal_p (target, res))
27165 emit_move_insn (target, res);
27166 }
27167
27168 /* Return the UNSPEC_COND_* code for comparison CODE. */
27169
27170 static unsigned int
27171 aarch64_unspec_cond_code (rtx_code code)
27172 {
27173 switch (code)
27174 {
27175 case NE:
27176 return UNSPEC_COND_FCMNE;
27177 case EQ:
27178 return UNSPEC_COND_FCMEQ;
27179 case LT:
27180 return UNSPEC_COND_FCMLT;
27181 case GT:
27182 return UNSPEC_COND_FCMGT;
27183 case LE:
27184 return UNSPEC_COND_FCMLE;
27185 case GE:
27186 return UNSPEC_COND_FCMGE;
27187 case UNORDERED:
27188 return UNSPEC_COND_FCMUO;
27189 default:
27190 gcc_unreachable ();
27191 }
27192 }
27193
27194 /* Emit:
27195
27196 (set TARGET (unspec [PRED KNOWN_PTRUE_P OP0 OP1] UNSPEC_COND_<X>))
27197
27198 where <X> is the operation associated with comparison CODE.
27199 KNOWN_PTRUE_P is true if PRED is known to be a PTRUE. */
27200
27201 static void
27202 aarch64_emit_sve_fp_cond (rtx target, rtx_code code, rtx pred,
27203 bool known_ptrue_p, rtx op0, rtx op1)
27204 {
27205 rtx flag = gen_int_mode (known_ptrue_p, SImode);
27206 rtx unspec = gen_rtx_UNSPEC (GET_MODE (pred),
27207 gen_rtvec (4, pred, flag, op0, op1),
27208 aarch64_unspec_cond_code (code));
27209 emit_set_insn (target, unspec);
27210 }
27211
27212 /* Emit the SVE equivalent of:
27213
27214 (set TMP1 (unspec [PRED KNOWN_PTRUE_P OP0 OP1] UNSPEC_COND_<X1>))
27215 (set TMP2 (unspec [PRED KNOWN_PTRUE_P OP0 OP1] UNSPEC_COND_<X2>))
27216 (set TARGET (ior:PRED_MODE TMP1 TMP2))
27217
27218 where <Xi> is the operation associated with comparison CODEi.
27219 KNOWN_PTRUE_P is true if PRED is known to be a PTRUE. */
27220
27221 static void
27222 aarch64_emit_sve_or_fp_conds (rtx target, rtx_code code1, rtx_code code2,
27223 rtx pred, bool known_ptrue_p, rtx op0, rtx op1)
27224 {
27225 machine_mode pred_mode = GET_MODE (pred);
27226 rtx tmp1 = gen_reg_rtx (pred_mode);
27227 aarch64_emit_sve_fp_cond (tmp1, code1, pred, known_ptrue_p, op0, op1);
27228 rtx tmp2 = gen_reg_rtx (pred_mode);
27229 aarch64_emit_sve_fp_cond (tmp2, code2, pred, known_ptrue_p, op0, op1);
27230 aarch64_emit_binop (target, ior_optab, tmp1, tmp2);
27231 }
27232
27233 /* Emit the SVE equivalent of:
27234
27235 (set TMP (unspec [PRED KNOWN_PTRUE_P OP0 OP1] UNSPEC_COND_<X>))
27236 (set TARGET (not TMP))
27237
27238 where <X> is the operation associated with comparison CODE.
27239 KNOWN_PTRUE_P is true if PRED is known to be a PTRUE. */
27240
27241 static void
27242 aarch64_emit_sve_invert_fp_cond (rtx target, rtx_code code, rtx pred,
27243 bool known_ptrue_p, rtx op0, rtx op1)
27244 {
27245 machine_mode pred_mode = GET_MODE (pred);
27246 rtx tmp = gen_reg_rtx (pred_mode);
27247 aarch64_emit_sve_fp_cond (tmp, code, pred, known_ptrue_p, op0, op1);
27248 aarch64_emit_unop (target, one_cmpl_optab, tmp);
27249 }
27250
27251 /* Expand an SVE floating-point comparison using the SVE equivalent of:
27252
27253 (set TARGET (CODE OP0 OP1)). */
27254
27255 void
27256 aarch64_expand_sve_vec_cmp_float (rtx target, rtx_code code, rtx op0, rtx op1)
27257 {
27258 machine_mode pred_mode = GET_MODE (target);
27259 machine_mode data_mode = GET_MODE (op0);
27260
27261 rtx ptrue = aarch64_ptrue_reg (pred_mode);
27262 switch (code)
27263 {
27264 case UNORDERED:
27265 /* UNORDERED has no immediate form. */
27266 op1 = force_reg (data_mode, op1);
27267 /* fall through */
27268 case LT:
27269 case LE:
27270 case GT:
27271 case GE:
27272 case EQ:
27273 case NE:
27274 /* There is native support for the comparison. */
27275 aarch64_emit_sve_fp_cond (target, code, ptrue, true, op0, op1);
27276 return;
27277
27278 case LTGT:
27279 /* This is a trapping operation (LT or GT). */
27280 aarch64_emit_sve_or_fp_conds (target, LT, GT, ptrue, true, op0, op1);
27281 return;
27282
27283 case UNEQ:
27284 if (!flag_trapping_math)
27285 {
27286 /* This would trap for signaling NaNs. */
27287 op1 = force_reg (data_mode, op1);
27288 aarch64_emit_sve_or_fp_conds (target, UNORDERED, EQ,
27289 ptrue, true, op0, op1);
27290 return;
27291 }
27292 /* fall through */
27293 case UNLT:
27294 case UNLE:
27295 case UNGT:
27296 case UNGE:
27297 if (flag_trapping_math)
27298 {
27299 /* Work out which elements are ordered. */
27300 rtx ordered = gen_reg_rtx (pred_mode);
27301 op1 = force_reg (data_mode, op1);
27302 aarch64_emit_sve_invert_fp_cond (ordered, UNORDERED,
27303 ptrue, true, op0, op1);
27304
27305 /* Test the opposite condition for the ordered elements,
27306 then invert the result. */
27307 if (code == UNEQ)
27308 code = NE;
27309 else
27310 code = reverse_condition_maybe_unordered (code);
27311 aarch64_emit_sve_invert_fp_cond (target, code,
27312 ordered, false, op0, op1);
27313 return;
27314 }
27315 break;
27316
27317 case ORDERED:
27318 /* ORDERED has no immediate form. */
27319 op1 = force_reg (data_mode, op1);
27320 break;
27321
27322 default:
27323 gcc_unreachable ();
27324 }
27325
27326 /* There is native support for the inverse comparison. */
27327 code = reverse_condition_maybe_unordered (code);
27328 aarch64_emit_sve_invert_fp_cond (target, code, ptrue, true, op0, op1);
27329 }
27330
27331 /* Return true if:
27332
27333 (a) MODE1 and MODE2 use the same layout for bytes that are common
27334 to both modes;
27335
27336 (b) subregs involving the two modes behave as the target-independent
27337 subreg rules require; and
27338
27339 (c) there is at least one register that can hold both modes.
27340
27341 Return false otherwise. */
27342
27343 static bool
27344 aarch64_modes_compatible_p (machine_mode mode1, machine_mode mode2)
27345 {
27346 unsigned int flags1 = aarch64_classify_vector_mode (mode1);
27347 unsigned int flags2 = aarch64_classify_vector_mode (mode2);
27348
27349 bool sve1_p = (flags1 & VEC_ANY_SVE);
27350 bool sve2_p = (flags2 & VEC_ANY_SVE);
27351
27352 bool partial_sve1_p = sve1_p && (flags1 & VEC_PARTIAL);
27353 bool partial_sve2_p = sve2_p && (flags2 & VEC_PARTIAL);
27354
27355 bool pred1_p = (flags1 & VEC_SVE_PRED);
27356 bool pred2_p = (flags2 & VEC_SVE_PRED);
27357
27358 bool partial_advsimd_struct1_p = (flags1 == (VEC_ADVSIMD | VEC_STRUCT
27359 | VEC_PARTIAL));
27360 bool partial_advsimd_struct2_p = (flags2 == (VEC_ADVSIMD | VEC_STRUCT
27361 | VEC_PARTIAL));
27362
27363 /* Don't allow changes between predicate modes and other modes.
27364 Only predicate registers can hold predicate modes and only
27365 non-predicate registers can hold non-predicate modes, so any
27366 attempt to mix them would require a round trip through memory. */
27367 if (pred1_p != pred2_p)
27368 return false;
27369
27370 /* The contents of partial SVE modes are distributed evenly across
27371 the register, whereas GCC expects them to be clustered together.
27372 We therefore need to be careful about mode changes involving them. */
27373 if (partial_sve1_p && partial_sve2_p)
27374 {
27375 /* Reject changes between partial SVE modes that have different
27376 patterns of significant and insignificant bits. */
27377 if ((aarch64_sve_container_bits (mode1)
27378 != aarch64_sve_container_bits (mode2))
27379 || GET_MODE_UNIT_SIZE (mode1) != GET_MODE_UNIT_SIZE (mode2))
27380 return false;
27381 }
27382 else if (partial_sve1_p)
27383 {
27384 /* The first lane of MODE1 is where GCC expects it, but anything
27385 bigger than that is not. */
27386 if (maybe_gt (GET_MODE_SIZE (mode2), GET_MODE_UNIT_SIZE (mode1)))
27387 return false;
27388 }
27389 else if (partial_sve2_p)
27390 {
27391 /* Similarly in reverse. */
27392 if (maybe_gt (GET_MODE_SIZE (mode1), GET_MODE_UNIT_SIZE (mode2)))
27393 return false;
27394 }
27395
27396 /* Don't allow changes between partial Advanced SIMD structure modes
27397 and other modes that are bigger than 8 bytes. E.g. V16QI and V2x8QI
27398 are the same size, but the former occupies one Q register while the
27399 latter occupies two D registers. */
27400 if (partial_advsimd_struct1_p != partial_advsimd_struct2_p
27401 && maybe_gt (GET_MODE_SIZE (mode1), 8)
27402 && maybe_gt (GET_MODE_SIZE (mode2), 8))
27403 return false;
27404
27405 if (maybe_ne (BITS_PER_SVE_VECTOR, 128u))
27406 {
27407 /* Don't allow changes between SVE modes and other modes that might
27408 be bigger than 128 bits. In particular, OImode, CImode and XImode
27409 divide into 128-bit quantities while SVE modes divide into
27410 BITS_PER_SVE_VECTOR quantities. */
27411 if (sve1_p && !sve2_p && maybe_gt (GET_MODE_BITSIZE (mode2), 128))
27412 return false;
27413 if (sve2_p && !sve1_p && maybe_gt (GET_MODE_BITSIZE (mode1), 128))
27414 return false;
27415 }
27416
27417 if (BYTES_BIG_ENDIAN)
27418 {
27419 /* Don't allow changes between SVE data modes and non-SVE modes.
27420 See the comment at the head of aarch64-sve.md for details. */
27421 if (sve1_p != sve2_p)
27422 return false;
27423
27424 /* Don't allow changes in element size: lane 0 of the new vector
27425 would not then be lane 0 of the old vector. See the comment
27426 above aarch64_maybe_expand_sve_subreg_move for a more detailed
27427 description.
27428
27429 In the worst case, this forces a register to be spilled in
27430 one mode and reloaded in the other, which handles the
27431 endianness correctly. */
27432 if (sve1_p && GET_MODE_UNIT_SIZE (mode1) != GET_MODE_UNIT_SIZE (mode2))
27433 return false;
27434 }
27435 return true;
27436 }
27437
27438 /* Implement TARGET_MODES_TIEABLE_P. In principle we should always defer
27439 to aarch64_modes_compatible_p. However due to issues with register
27440 allocation it is preferable to avoid tieing integer scalar and FP
27441 scalar modes. Executing integer operations in general registers is
27442 better than treating them as scalar vector operations. This reduces
27443 latency and avoids redundant int<->FP moves. So tie modes if they
27444 are either the same class, or one of them is a vector mode. */
27445
27446 static bool
27447 aarch64_modes_tieable_p (machine_mode mode1, machine_mode mode2)
27448 {
27449 if (aarch64_modes_compatible_p (mode1, mode2))
27450 {
27451 if (GET_MODE_CLASS (mode1) == GET_MODE_CLASS (mode2))
27452 return true;
27453 if (VECTOR_MODE_P (mode1) || VECTOR_MODE_P (mode2))
27454 return true;
27455 }
27456 return false;
27457 }
27458
27459 /* Return a new RTX holding the result of moving POINTER forward by
27460 AMOUNT bytes. */
27461
27462 static rtx
27463 aarch64_move_pointer (rtx pointer, poly_int64 amount)
27464 {
27465 rtx next = plus_constant (Pmode, XEXP (pointer, 0), amount);
27466
27467 return adjust_automodify_address (pointer, GET_MODE (pointer),
27468 next, amount);
27469 }
27470
27471 /* Expand a cpymem/movmem using the MOPS extension. OPERANDS are taken
27472 from the cpymem/movmem pattern. IS_MEMMOVE is true if this is a memmove
27473 rather than memcpy. Return true iff we succeeded. */
27474 bool
27475 aarch64_expand_cpymem_mops (rtx *operands, bool is_memmove)
27476 {
27477 if (!TARGET_MOPS)
27478 return false;
27479
27480 /* All three registers are changed by the instruction, so each one
27481 must be a fresh pseudo. */
27482 rtx dst_addr = copy_to_mode_reg (Pmode, XEXP (operands[0], 0));
27483 rtx src_addr = copy_to_mode_reg (Pmode, XEXP (operands[1], 0));
27484 rtx dst_mem = replace_equiv_address (operands[0], dst_addr);
27485 rtx src_mem = replace_equiv_address (operands[1], src_addr);
27486 rtx sz_reg = copy_to_mode_reg (DImode, operands[2]);
27487 if (is_memmove)
27488 emit_insn (gen_aarch64_movmemdi (dst_mem, src_mem, sz_reg));
27489 else
27490 emit_insn (gen_aarch64_cpymemdi (dst_mem, src_mem, sz_reg));
27491 return true;
27492 }
27493
27494 /* Expand cpymem/movmem, as if from a __builtin_memcpy/memmove.
27495 OPERANDS are taken from the cpymem/movmem pattern. IS_MEMMOVE is true
27496 if this is a memmove rather than memcpy. Return true if we succeed,
27497 otherwise return false, indicating that a libcall should be emitted. */
27498 bool
27499 aarch64_expand_cpymem (rtx *operands, bool is_memmove)
27500 {
27501 int mode_bytes;
27502 rtx dst = operands[0];
27503 rtx src = operands[1];
27504 unsigned align = UINTVAL (operands[3]);
27505 rtx base;
27506 machine_mode mode = BLKmode, next_mode;
27507
27508 /* Variable-sized or strict-align copies may use the MOPS expansion. */
27509 if (!CONST_INT_P (operands[2]) || (STRICT_ALIGNMENT && align < 16))
27510 return aarch64_expand_cpymem_mops (operands, is_memmove);
27511
27512 unsigned HOST_WIDE_INT size = UINTVAL (operands[2]);
27513
27514 /* Set inline limits for memmove/memcpy. MOPS has a separate threshold. */
27515 unsigned max_copy_size = TARGET_SIMD ? 256 : 128;
27516 unsigned mops_threshold = is_memmove ? aarch64_mops_memmove_size_threshold
27517 : aarch64_mops_memcpy_size_threshold;
27518
27519 /* Reduce the maximum size with -Os. */
27520 if (optimize_function_for_size_p (cfun))
27521 max_copy_size /= 4;
27522
27523 /* Large copies use MOPS when available or a library call. */
27524 if (size > max_copy_size || (TARGET_MOPS && size > mops_threshold))
27525 return aarch64_expand_cpymem_mops (operands, is_memmove);
27526
27527 /* Default to 32-byte LDP/STP on large copies, however small copies or
27528 no SIMD support fall back to 16-byte chunks.
27529 ??? Although it would be possible to use LDP/STP Qn in streaming mode
27530 (so using TARGET_BASE_SIMD instead of TARGET_SIMD), it isn't clear
27531 whether that would improve performance. */
27532 bool use_qregs = size > 24 && TARGET_SIMD_MEMOPS;
27533
27534 base = copy_to_mode_reg (Pmode, XEXP (dst, 0));
27535 dst = adjust_automodify_address (dst, VOIDmode, base, 0);
27536
27537 base = copy_to_mode_reg (Pmode, XEXP (src, 0));
27538 src = adjust_automodify_address (src, VOIDmode, base, 0);
27539
27540 auto_vec<std::pair<rtx, rtx>, 16> ops;
27541 int offset = 0;
27542
27543 while (size > 0)
27544 {
27545 /* Find the largest mode in which to do the copy in without over reading
27546 or writing. */
27547 opt_scalar_int_mode mode_iter;
27548 FOR_EACH_MODE_IN_CLASS (mode_iter, MODE_INT)
27549 if (GET_MODE_SIZE (mode_iter.require ()) <= MIN (size, 16))
27550 mode = mode_iter.require ();
27551
27552 gcc_assert (mode != BLKmode);
27553
27554 mode_bytes = GET_MODE_SIZE (mode).to_constant ();
27555
27556 /* Prefer Q-register accesses. */
27557 if (mode_bytes == 16 && use_qregs)
27558 mode = V4SImode;
27559
27560 rtx reg = gen_reg_rtx (mode);
27561 rtx load = gen_move_insn (reg, adjust_address (src, mode, offset));
27562 rtx store = gen_move_insn (adjust_address (dst, mode, offset), reg);
27563 ops.safe_push ({ load, store });
27564 size -= mode_bytes;
27565 offset += mode_bytes;
27566
27567 /* Emit trailing copies using overlapping unaligned accesses
27568 (when !STRICT_ALIGNMENT) - this is smaller and faster. */
27569 if (size > 0 && size < 16 && !STRICT_ALIGNMENT)
27570 {
27571 next_mode = smallest_mode_for_size
27572 (size * BITS_PER_UNIT, MODE_INT).require ();
27573 int n_bytes = GET_MODE_SIZE (next_mode).to_constant ();
27574 gcc_assert (n_bytes <= mode_bytes);
27575 offset -= n_bytes - size;
27576 size = n_bytes;
27577 }
27578 }
27579
27580 /* Memcpy interleaves loads with stores, memmove emits all loads first. */
27581 int nops = ops.length();
27582 int inc = is_memmove || nops <= 8 ? nops : 6;
27583
27584 for (int i = 0; i < nops; i += inc)
27585 {
27586 int m = MIN (nops, i + inc);
27587 /* Emit loads. */
27588 for (int j = i; j < m; j++)
27589 emit_insn (ops[j].first);
27590 /* Emit stores. */
27591 for (int j = i; j < m; j++)
27592 emit_insn (ops[j].second);
27593 }
27594 return true;
27595 }
27596
27597 /* Expand a setmem using the MOPS instructions. OPERANDS are the same
27598 as for the setmem pattern. Return true iff we succeed. */
27599 static bool
27600 aarch64_expand_setmem_mops (rtx *operands)
27601 {
27602 if (!TARGET_MOPS)
27603 return false;
27604
27605 /* The first two registers are changed by the instruction, so both
27606 of them must be a fresh pseudo. */
27607 rtx dst_addr = copy_to_mode_reg (Pmode, XEXP (operands[0], 0));
27608 rtx dst_mem = replace_equiv_address (operands[0], dst_addr);
27609 rtx sz_reg = copy_to_mode_reg (DImode, operands[1]);
27610 rtx val = operands[2];
27611 if (val != CONST0_RTX (QImode))
27612 val = force_reg (QImode, val);
27613 emit_insn (gen_aarch64_setmemdi (dst_mem, val, sz_reg));
27614 return true;
27615 }
27616
27617 /* Expand setmem, as if from a __builtin_memset. Return true if
27618 we succeed, otherwise return false. */
27619
27620 bool
27621 aarch64_expand_setmem (rtx *operands)
27622 {
27623 int mode_bytes;
27624 unsigned HOST_WIDE_INT len;
27625 rtx dst = operands[0];
27626 rtx val = operands[2], src;
27627 unsigned align = UINTVAL (operands[3]);
27628 rtx base;
27629 machine_mode mode = BLKmode, next_mode;
27630
27631 /* Variable-sized or strict-align memset may use the MOPS expansion. */
27632 if (!CONST_INT_P (operands[1]) || !TARGET_SIMD_MEMOPS
27633 || (STRICT_ALIGNMENT && align < 16))
27634 return aarch64_expand_setmem_mops (operands);
27635
27636 /* Set inline limits for memset. MOPS has a separate threshold. */
27637 unsigned max_set_size = MAX_SET_SIZE (optimize_function_for_speed_p (cfun));
27638 unsigned mops_threshold = aarch64_mops_memset_size_threshold;
27639
27640 len = UINTVAL (operands[1]);
27641
27642 /* Large memset uses MOPS when available or a library call. */
27643 if (len > max_set_size || (TARGET_MOPS && len > mops_threshold))
27644 return aarch64_expand_setmem_mops (operands);
27645
27646 base = copy_to_mode_reg (Pmode, XEXP (dst, 0));
27647 dst = adjust_automodify_address (dst, VOIDmode, base, 0);
27648
27649 /* Prepare the val using a DUP/MOVI v0.16B, val. */
27650 val = expand_vector_broadcast (V16QImode, val);
27651 val = force_reg (V16QImode, val);
27652
27653 int offset = 0;
27654 while (len > 0)
27655 {
27656 /* Find the largest mode in which to do the copy without
27657 over writing. */
27658 opt_scalar_int_mode mode_iter;
27659 FOR_EACH_MODE_IN_CLASS (mode_iter, MODE_INT)
27660 if (GET_MODE_SIZE (mode_iter.require ()) <= MIN (len, 16))
27661 mode = mode_iter.require ();
27662
27663 gcc_assert (mode != BLKmode);
27664
27665 mode_bytes = GET_MODE_SIZE (mode).to_constant ();
27666
27667 src = val;
27668
27669 /* Prefer Q-register accesses. */
27670 if (mode_bytes == 16)
27671 mode = V16QImode;
27672 else
27673 src = lowpart_subreg (mode, src, GET_MODE (val));
27674
27675 emit_move_insn (adjust_address (dst, mode, offset), src);
27676 len -= mode_bytes;
27677 offset += mode_bytes;
27678
27679 /* Emit trailing writes using overlapping unaligned accesses
27680 (when !STRICT_ALIGNMENT) - this is smaller and faster. */
27681 if (len > 0 && len < 16 && !STRICT_ALIGNMENT)
27682 {
27683 next_mode = smallest_mode_for_size
27684 (len * BITS_PER_UNIT, MODE_INT).require ();
27685 int n_bytes = GET_MODE_SIZE (next_mode).to_constant ();
27686 gcc_assert (n_bytes <= mode_bytes);
27687 offset -= n_bytes - len;
27688 len = n_bytes;
27689 }
27690 }
27691
27692 return true;
27693 }
27694
27695
27696 /* Split a DImode store of a CONST_INT SRC to MEM DST as two
27697 SImode stores. Handle the case when the constant has identical
27698 bottom and top halves. This is beneficial when the two stores can be
27699 merged into an STP and we avoid synthesising potentially expensive
27700 immediates twice. Return true if such a split is possible. */
27701
27702 bool
27703 aarch64_split_dimode_const_store (rtx dst, rtx src)
27704 {
27705 rtx lo = gen_lowpart (SImode, src);
27706 rtx hi = gen_highpart_mode (SImode, DImode, src);
27707
27708 if (!rtx_equal_p (lo, hi))
27709 return false;
27710
27711 unsigned int orig_cost
27712 = aarch64_internal_mov_immediate (NULL_RTX, src, false, DImode);
27713 unsigned int lo_cost
27714 = aarch64_internal_mov_immediate (NULL_RTX, lo, false, SImode);
27715
27716 /* We want to transform:
27717 MOV x1, 49370
27718 MOVK x1, 0x140, lsl 16
27719 MOVK x1, 0xc0da, lsl 32
27720 MOVK x1, 0x140, lsl 48
27721 STR x1, [x0]
27722 into:
27723 MOV w1, 49370
27724 MOVK w1, 0x140, lsl 16
27725 STP w1, w1, [x0]
27726 So we want to perform this when we save at least one instruction. */
27727 if (orig_cost <= lo_cost)
27728 return false;
27729
27730 rtx mem_lo = adjust_address (dst, SImode, 0);
27731 if (!aarch64_mem_pair_operand (mem_lo, SImode))
27732 return false;
27733
27734 rtx tmp_reg = gen_reg_rtx (SImode);
27735 aarch64_expand_mov_immediate (tmp_reg, lo);
27736 rtx mem_hi = aarch64_move_pointer (mem_lo, GET_MODE_SIZE (SImode));
27737 /* Don't emit an explicit store pair as this may not be always profitable.
27738 Let the sched-fusion logic decide whether to merge them. */
27739 emit_move_insn (mem_lo, tmp_reg);
27740 emit_move_insn (mem_hi, tmp_reg);
27741
27742 return true;
27743 }
27744
27745 /* Generate RTL for a conditional branch with rtx comparison CODE in
27746 mode CC_MODE. The destination of the unlikely conditional branch
27747 is LABEL_REF. */
27748
27749 void
27750 aarch64_gen_unlikely_cbranch (enum rtx_code code, machine_mode cc_mode,
27751 rtx label_ref)
27752 {
27753 rtx x;
27754 x = gen_rtx_fmt_ee (code, VOIDmode,
27755 gen_rtx_REG (cc_mode, CC_REGNUM),
27756 const0_rtx);
27757
27758 x = gen_rtx_IF_THEN_ELSE (VOIDmode, x,
27759 gen_rtx_LABEL_REF (VOIDmode, label_ref),
27760 pc_rtx);
27761 aarch64_emit_unlikely_jump (gen_rtx_SET (pc_rtx, x));
27762 }
27763
27764 /* Generate DImode scratch registers for 128-bit (TImode) addition.
27765
27766 OP1 represents the TImode destination operand 1
27767 OP2 represents the TImode destination operand 2
27768 LOW_DEST represents the low half (DImode) of TImode operand 0
27769 LOW_IN1 represents the low half (DImode) of TImode operand 1
27770 LOW_IN2 represents the low half (DImode) of TImode operand 2
27771 HIGH_DEST represents the high half (DImode) of TImode operand 0
27772 HIGH_IN1 represents the high half (DImode) of TImode operand 1
27773 HIGH_IN2 represents the high half (DImode) of TImode operand 2. */
27774
27775 void
27776 aarch64_addti_scratch_regs (rtx op1, rtx op2, rtx *low_dest,
27777 rtx *low_in1, rtx *low_in2,
27778 rtx *high_dest, rtx *high_in1,
27779 rtx *high_in2)
27780 {
27781 *low_dest = gen_reg_rtx (DImode);
27782 *low_in1 = force_lowpart_subreg (DImode, op1, TImode);
27783 *low_in2 = force_lowpart_subreg (DImode, op2, TImode);
27784 *high_dest = gen_reg_rtx (DImode);
27785 *high_in1 = force_highpart_subreg (DImode, op1, TImode);
27786 *high_in2 = force_highpart_subreg (DImode, op2, TImode);
27787 }
27788
27789 /* Generate DImode scratch registers for 128-bit (TImode) subtraction.
27790
27791 OP1 represents the TImode destination operand 1
27792 OP2 represents the TImode destination operand 2
27793 LOW_DEST represents the low half (DImode) of TImode operand 0
27794 LOW_IN1 represents the low half (DImode) of TImode operand 1
27795 LOW_IN2 represents the low half (DImode) of TImode operand 2
27796 HIGH_DEST represents the high half (DImode) of TImode operand 0
27797 HIGH_IN1 represents the high half (DImode) of TImode operand 1
27798 HIGH_IN2 represents the high half (DImode) of TImode operand 2. */
27799
27800
27801 void
27802 aarch64_subvti_scratch_regs (rtx op1, rtx op2, rtx *low_dest,
27803 rtx *low_in1, rtx *low_in2,
27804 rtx *high_dest, rtx *high_in1,
27805 rtx *high_in2)
27806 {
27807 *low_dest = gen_reg_rtx (DImode);
27808 *low_in1 = force_lowpart_subreg (DImode, op1, TImode);
27809 *low_in2 = force_lowpart_subreg (DImode, op2, TImode);
27810 *high_dest = gen_reg_rtx (DImode);
27811
27812 *high_in1 = force_highpart_subreg (DImode, op1, TImode);
27813 *high_in2 = force_highpart_subreg (DImode, op2, TImode);
27814 }
27815
27816 /* Generate RTL for 128-bit (TImode) subtraction with overflow.
27817
27818 OP0 represents the TImode destination operand 0
27819 LOW_DEST represents the low half (DImode) of TImode operand 0
27820 LOW_IN1 represents the low half (DImode) of TImode operand 1
27821 LOW_IN2 represents the low half (DImode) of TImode operand 2
27822 HIGH_DEST represents the high half (DImode) of TImode operand 0
27823 HIGH_IN1 represents the high half (DImode) of TImode operand 1
27824 HIGH_IN2 represents the high half (DImode) of TImode operand 2
27825 UNSIGNED_P is true if the operation is being performed on unsigned
27826 values. */
27827 void
27828 aarch64_expand_subvti (rtx op0, rtx low_dest, rtx low_in1,
27829 rtx low_in2, rtx high_dest, rtx high_in1,
27830 rtx high_in2, bool unsigned_p)
27831 {
27832 if (low_in2 == const0_rtx)
27833 {
27834 low_dest = low_in1;
27835 high_in2 = force_reg (DImode, high_in2);
27836 if (unsigned_p)
27837 emit_insn (gen_subdi3_compare1 (high_dest, high_in1, high_in2));
27838 else
27839 emit_insn (gen_subvdi_insn (high_dest, high_in1, high_in2));
27840 }
27841 else
27842 {
27843 if (aarch64_plus_immediate (low_in2, DImode))
27844 emit_insn (gen_subdi3_compare1_imm (low_dest, low_in1, low_in2,
27845 GEN_INT (-UINTVAL (low_in2))));
27846 else
27847 {
27848 low_in2 = force_reg (DImode, low_in2);
27849 emit_insn (gen_subdi3_compare1 (low_dest, low_in1, low_in2));
27850 }
27851 high_in2 = force_reg (DImode, high_in2);
27852
27853 if (unsigned_p)
27854 emit_insn (gen_usubdi3_carryinC (high_dest, high_in1, high_in2));
27855 else
27856 emit_insn (gen_subdi3_carryinV (high_dest, high_in1, high_in2));
27857 }
27858
27859 emit_move_insn (gen_lowpart (DImode, op0), low_dest);
27860 emit_move_insn (gen_highpart (DImode, op0), high_dest);
27861
27862 }
27863
27864 /* Implement the TARGET_ASAN_SHADOW_OFFSET hook. */
27865
27866 static unsigned HOST_WIDE_INT
27867 aarch64_asan_shadow_offset (void)
27868 {
27869 if (TARGET_ILP32)
27870 return (HOST_WIDE_INT_1 << 29);
27871 else
27872 return (HOST_WIDE_INT_1 << 36);
27873 }
27874
27875 static rtx
27876 aarch64_gen_ccmp_first (rtx_insn **prep_seq, rtx_insn **gen_seq,
27877 rtx_code code, tree treeop0, tree treeop1)
27878 {
27879 machine_mode op_mode, cmp_mode, cc_mode = CCmode;
27880 rtx op0, op1;
27881 int unsignedp = TYPE_UNSIGNED (TREE_TYPE (treeop0));
27882 insn_code icode;
27883 struct expand_operand ops[4];
27884
27885 start_sequence ();
27886 expand_operands (treeop0, treeop1, NULL_RTX, &op0, &op1, EXPAND_NORMAL);
27887
27888 op_mode = GET_MODE (op0);
27889 if (op_mode == VOIDmode)
27890 op_mode = GET_MODE (op1);
27891
27892 if (CONST_SCALAR_INT_P (op1))
27893 canonicalize_comparison (op_mode, &code, &op1);
27894
27895 switch (op_mode)
27896 {
27897 case E_QImode:
27898 case E_HImode:
27899 case E_SImode:
27900 cmp_mode = SImode;
27901 icode = CODE_FOR_cmpsi;
27902 break;
27903
27904 case E_DImode:
27905 cmp_mode = DImode;
27906 icode = CODE_FOR_cmpdi;
27907 break;
27908
27909 case E_SFmode:
27910 cmp_mode = SFmode;
27911 cc_mode = aarch64_select_cc_mode (code, op0, op1);
27912 icode = cc_mode == CCFPEmode ? CODE_FOR_fcmpesf : CODE_FOR_fcmpsf;
27913 break;
27914
27915 case E_DFmode:
27916 cmp_mode = DFmode;
27917 cc_mode = aarch64_select_cc_mode (code, op0, op1);
27918 icode = cc_mode == CCFPEmode ? CODE_FOR_fcmpedf : CODE_FOR_fcmpdf;
27919 break;
27920
27921 default:
27922 end_sequence ();
27923 return NULL_RTX;
27924 }
27925
27926 op0 = prepare_operand (icode, op0, 0, op_mode, cmp_mode, unsignedp);
27927 op1 = prepare_operand (icode, op1, 1, op_mode, cmp_mode, unsignedp);
27928 if (!op0 || !op1)
27929 {
27930 end_sequence ();
27931 return NULL_RTX;
27932 }
27933 *prep_seq = get_insns ();
27934 end_sequence ();
27935
27936 create_fixed_operand (&ops[0], op0);
27937 create_fixed_operand (&ops[1], op1);
27938
27939 start_sequence ();
27940 if (!maybe_expand_insn (icode, 2, ops))
27941 {
27942 end_sequence ();
27943 return NULL_RTX;
27944 }
27945 *gen_seq = get_insns ();
27946 end_sequence ();
27947
27948 return gen_rtx_fmt_ee (code, cc_mode,
27949 gen_rtx_REG (cc_mode, CC_REGNUM), const0_rtx);
27950 }
27951
27952 static rtx
27953 aarch64_gen_ccmp_next (rtx_insn **prep_seq, rtx_insn **gen_seq, rtx prev,
27954 rtx_code cmp_code, tree treeop0, tree treeop1,
27955 rtx_code bit_code)
27956 {
27957 rtx op0, op1, target;
27958 machine_mode op_mode, cmp_mode, cc_mode = CCmode;
27959 int unsignedp = TYPE_UNSIGNED (TREE_TYPE (treeop0));
27960 insn_code icode;
27961 struct expand_operand ops[6];
27962 int aarch64_cond;
27963
27964 push_to_sequence (*prep_seq);
27965 expand_operands (treeop0, treeop1, NULL_RTX, &op0, &op1, EXPAND_NORMAL);
27966
27967 op_mode = GET_MODE (op0);
27968 if (op_mode == VOIDmode)
27969 op_mode = GET_MODE (op1);
27970
27971 if (CONST_SCALAR_INT_P (op1))
27972 canonicalize_comparison (op_mode, &cmp_code, &op1);
27973
27974 switch (op_mode)
27975 {
27976 case E_QImode:
27977 case E_HImode:
27978 case E_SImode:
27979 cmp_mode = SImode;
27980 break;
27981
27982 case E_DImode:
27983 cmp_mode = DImode;
27984 break;
27985
27986 case E_SFmode:
27987 cmp_mode = SFmode;
27988 cc_mode = aarch64_select_cc_mode (cmp_code, op0, op1);
27989 break;
27990
27991 case E_DFmode:
27992 cmp_mode = DFmode;
27993 cc_mode = aarch64_select_cc_mode (cmp_code, op0, op1);
27994 break;
27995
27996 default:
27997 end_sequence ();
27998 return NULL_RTX;
27999 }
28000
28001 icode = code_for_ccmp (cc_mode, cmp_mode);
28002
28003 op0 = prepare_operand (icode, op0, 2, op_mode, cmp_mode, unsignedp);
28004 op1 = prepare_operand (icode, op1, 3, op_mode, cmp_mode, unsignedp);
28005 if (!op0 || !op1)
28006 {
28007 end_sequence ();
28008 return NULL_RTX;
28009 }
28010 *prep_seq = get_insns ();
28011 end_sequence ();
28012
28013 target = gen_rtx_REG (cc_mode, CC_REGNUM);
28014 aarch64_cond = aarch64_get_condition_code_1 (cc_mode, cmp_code);
28015
28016 if (bit_code != AND)
28017 {
28018 /* Treat the ccmp patterns as canonical and use them where possible,
28019 but fall back to ccmp_rev patterns if there's no other option. */
28020 rtx_code prev_code = GET_CODE (prev);
28021 machine_mode prev_mode = GET_MODE (XEXP (prev, 0));
28022 if ((prev_mode == CCFPmode || prev_mode == CCFPEmode)
28023 && !(prev_code == EQ
28024 || prev_code == NE
28025 || prev_code == ORDERED
28026 || prev_code == UNORDERED))
28027 icode = code_for_ccmp_rev (cc_mode, cmp_mode);
28028 else
28029 {
28030 rtx_code code = reverse_condition (prev_code);
28031 prev = gen_rtx_fmt_ee (code, VOIDmode, XEXP (prev, 0), const0_rtx);
28032 }
28033 aarch64_cond = AARCH64_INVERSE_CONDITION_CODE (aarch64_cond);
28034 }
28035
28036 create_fixed_operand (&ops[0], XEXP (prev, 0));
28037 create_fixed_operand (&ops[1], target);
28038 create_fixed_operand (&ops[2], op0);
28039 create_fixed_operand (&ops[3], op1);
28040 create_fixed_operand (&ops[4], prev);
28041 create_fixed_operand (&ops[5], GEN_INT (aarch64_cond));
28042
28043 push_to_sequence (*gen_seq);
28044 if (!maybe_expand_insn (icode, 6, ops))
28045 {
28046 end_sequence ();
28047 return NULL_RTX;
28048 }
28049
28050 *gen_seq = get_insns ();
28051 end_sequence ();
28052
28053 return gen_rtx_fmt_ee (cmp_code, VOIDmode, target, const0_rtx);
28054 }
28055
28056 #undef TARGET_GEN_CCMP_FIRST
28057 #define TARGET_GEN_CCMP_FIRST aarch64_gen_ccmp_first
28058
28059 #undef TARGET_GEN_CCMP_NEXT
28060 #define TARGET_GEN_CCMP_NEXT aarch64_gen_ccmp_next
28061
28062 /* Implement TARGET_SCHED_MACRO_FUSION_P. Return true if target supports
28063 instruction fusion of some sort. */
28064
28065 static bool
28066 aarch64_macro_fusion_p (void)
28067 {
28068 return aarch64_tune_params.fusible_ops != AARCH64_FUSE_NOTHING;
28069 }
28070
28071
28072 /* Implement TARGET_SCHED_MACRO_FUSION_PAIR_P. Return true if PREV and CURR
28073 should be kept together during scheduling. */
28074
28075 static bool
28076 aarch_macro_fusion_pair_p (rtx_insn *prev, rtx_insn *curr)
28077 {
28078 rtx set_dest;
28079 rtx prev_set = single_set (prev);
28080 rtx curr_set = single_set (curr);
28081 /* prev and curr are simple SET insns i.e. no flag setting or branching. */
28082 bool simple_sets_p = prev_set && curr_set && !any_condjump_p (curr);
28083
28084 if (!aarch64_macro_fusion_p ())
28085 return false;
28086
28087 if (simple_sets_p && aarch64_fusion_enabled_p (AARCH64_FUSE_MOV_MOVK))
28088 {
28089 /* We are trying to match:
28090 prev (mov) == (set (reg r0) (const_int imm16))
28091 curr (movk) == (set (zero_extract (reg r0)
28092 (const_int 16)
28093 (const_int 16))
28094 (const_int imm16_1)) */
28095
28096 set_dest = SET_DEST (curr_set);
28097
28098 if (GET_CODE (set_dest) == ZERO_EXTRACT
28099 && CONST_INT_P (SET_SRC (curr_set))
28100 && CONST_INT_P (SET_SRC (prev_set))
28101 && CONST_INT_P (XEXP (set_dest, 2))
28102 && INTVAL (XEXP (set_dest, 2)) == 16
28103 && REG_P (XEXP (set_dest, 0))
28104 && REG_P (SET_DEST (prev_set))
28105 && REGNO (XEXP (set_dest, 0)) == REGNO (SET_DEST (prev_set)))
28106 {
28107 return true;
28108 }
28109 }
28110
28111 if (simple_sets_p && aarch64_fusion_enabled_p (AARCH64_FUSE_ADRP_ADD))
28112 {
28113
28114 /* We're trying to match:
28115 prev (adrp) == (set (reg r1)
28116 (high (symbol_ref ("SYM"))))
28117 curr (add) == (set (reg r0)
28118 (lo_sum (reg r1)
28119 (symbol_ref ("SYM"))))
28120 Note that r0 need not necessarily be the same as r1, especially
28121 during pre-regalloc scheduling. */
28122
28123 if (satisfies_constraint_Ush (SET_SRC (prev_set))
28124 && REG_P (SET_DEST (prev_set)) && REG_P (SET_DEST (curr_set)))
28125 {
28126 if (GET_CODE (SET_SRC (curr_set)) == LO_SUM
28127 && REG_P (XEXP (SET_SRC (curr_set), 0))
28128 && REGNO (XEXP (SET_SRC (curr_set), 0))
28129 == REGNO (SET_DEST (prev_set))
28130 && rtx_equal_p (XEXP (SET_SRC (prev_set), 0),
28131 XEXP (SET_SRC (curr_set), 1)))
28132 return true;
28133 }
28134 }
28135
28136 if (simple_sets_p && aarch64_fusion_enabled_p (AARCH64_FUSE_MOVK_MOVK))
28137 {
28138
28139 /* We're trying to match:
28140 prev (movk) == (set (zero_extract (reg r0)
28141 (const_int 16)
28142 (const_int 32))
28143 (const_int imm16_1))
28144 curr (movk) == (set (zero_extract (reg r0)
28145 (const_int 16)
28146 (const_int 48))
28147 (const_int imm16_2)) */
28148
28149 if (GET_CODE (SET_DEST (prev_set)) == ZERO_EXTRACT
28150 && GET_CODE (SET_DEST (curr_set)) == ZERO_EXTRACT
28151 && REG_P (XEXP (SET_DEST (prev_set), 0))
28152 && REG_P (XEXP (SET_DEST (curr_set), 0))
28153 && REGNO (XEXP (SET_DEST (prev_set), 0))
28154 == REGNO (XEXP (SET_DEST (curr_set), 0))
28155 && CONST_INT_P (XEXP (SET_DEST (prev_set), 2))
28156 && CONST_INT_P (XEXP (SET_DEST (curr_set), 2))
28157 && INTVAL (XEXP (SET_DEST (prev_set), 2)) == 32
28158 && INTVAL (XEXP (SET_DEST (curr_set), 2)) == 48
28159 && CONST_INT_P (SET_SRC (prev_set))
28160 && CONST_INT_P (SET_SRC (curr_set)))
28161 return true;
28162
28163 }
28164 if (simple_sets_p && aarch64_fusion_enabled_p (AARCH64_FUSE_ADRP_LDR))
28165 {
28166 /* We're trying to match:
28167 prev (adrp) == (set (reg r0)
28168 (high (symbol_ref ("SYM"))))
28169 curr (ldr) == (set (reg r1)
28170 (mem (lo_sum (reg r0)
28171 (symbol_ref ("SYM")))))
28172 or
28173 curr (ldr) == (set (reg r1)
28174 (zero_extend (mem
28175 (lo_sum (reg r0)
28176 (symbol_ref ("SYM")))))) */
28177 if (satisfies_constraint_Ush (SET_SRC (prev_set))
28178 && REG_P (SET_DEST (prev_set)) && REG_P (SET_DEST (curr_set)))
28179 {
28180 rtx curr_src = SET_SRC (curr_set);
28181
28182 if (GET_CODE (curr_src) == ZERO_EXTEND)
28183 curr_src = XEXP (curr_src, 0);
28184
28185 if (MEM_P (curr_src) && GET_CODE (XEXP (curr_src, 0)) == LO_SUM
28186 && REG_P (XEXP (XEXP (curr_src, 0), 0))
28187 && REGNO (XEXP (XEXP (curr_src, 0), 0))
28188 == REGNO (SET_DEST (prev_set))
28189 && rtx_equal_p (XEXP (XEXP (curr_src, 0), 1),
28190 XEXP (SET_SRC (prev_set), 0)))
28191 return true;
28192 }
28193 }
28194
28195 /* Fuse compare (CMP/CMN/TST/BICS) and conditional branch. */
28196 if (aarch64_fusion_enabled_p (AARCH64_FUSE_CMP_BRANCH)
28197 && prev_set && curr_set && any_condjump_p (curr)
28198 && GET_CODE (SET_SRC (prev_set)) == COMPARE
28199 && SCALAR_INT_MODE_P (GET_MODE (XEXP (SET_SRC (prev_set), 0)))
28200 && reg_referenced_p (SET_DEST (prev_set), PATTERN (curr)))
28201 return true;
28202
28203 /* Fuse CMP and CSEL/CSET. */
28204 if (prev_set && curr_set
28205 && GET_CODE (SET_SRC (prev_set)) == COMPARE
28206 && SCALAR_INT_MODE_P (GET_MODE (XEXP (SET_SRC (prev_set), 0)))
28207 && reg_referenced_p (SET_DEST (prev_set), PATTERN (curr)))
28208 {
28209 enum attr_type prev_type = get_attr_type (prev);
28210 if ((prev_type == TYPE_ALUS_SREG || prev_type == TYPE_ALUS_IMM)
28211 && ((aarch64_fusion_enabled_p (AARCH64_FUSE_CMP_CSEL)
28212 && GET_CODE (SET_SRC (curr_set)) == IF_THEN_ELSE
28213 && aarch64_reg_or_zero (XEXP (SET_SRC (curr_set), 1), VOIDmode)
28214 && aarch64_reg_or_zero (XEXP (SET_SRC (curr_set), 2), VOIDmode)
28215 && SCALAR_INT_MODE_P (GET_MODE (XEXP (SET_SRC (curr_set), 1))))
28216 || (aarch64_fusion_enabled_p (AARCH64_FUSE_CMP_CSET)
28217 && GET_RTX_CLASS (GET_CODE (SET_SRC (curr_set)))
28218 == RTX_COMPARE
28219 && REG_P (SET_DEST (curr_set)))))
28220 return true;
28221 }
28222
28223 /* Fuse flag-setting ALU instructions and conditional branch. */
28224 if (aarch64_fusion_enabled_p (AARCH64_FUSE_ALU_BRANCH)
28225 && any_condjump_p (curr))
28226 {
28227 unsigned int condreg1, condreg2;
28228 rtx cc_reg_1;
28229 aarch64_fixed_condition_code_regs (&condreg1, &condreg2);
28230 cc_reg_1 = gen_rtx_REG (CCmode, condreg1);
28231
28232 if (reg_referenced_p (cc_reg_1, PATTERN (curr))
28233 && prev
28234 && modified_in_p (cc_reg_1, prev))
28235 {
28236 enum attr_type prev_type = get_attr_type (prev);
28237
28238 /* FIXME: this misses some which is considered simple arthematic
28239 instructions for ThunderX. Simple shifts are missed here. */
28240 if (prev_type == TYPE_ALUS_SREG
28241 || prev_type == TYPE_ALUS_IMM
28242 || prev_type == TYPE_LOGICS_REG
28243 || prev_type == TYPE_LOGICS_IMM)
28244 return true;
28245 }
28246 }
28247
28248 /* Fuse ALU instructions and CBZ/CBNZ. */
28249 if (prev_set
28250 && curr_set
28251 && aarch64_fusion_enabled_p (AARCH64_FUSE_ALU_CBZ)
28252 && any_condjump_p (curr))
28253 {
28254 /* We're trying to match:
28255 prev (alu_insn) == (set (r0) plus ((r0) (r1/imm)))
28256 curr (cbz) == (set (pc) (if_then_else (eq/ne) (r0)
28257 (const_int 0))
28258 (label_ref ("SYM"))
28259 (pc)) */
28260 if (SET_DEST (curr_set) == (pc_rtx)
28261 && GET_CODE (SET_SRC (curr_set)) == IF_THEN_ELSE
28262 && REG_P (XEXP (XEXP (SET_SRC (curr_set), 0), 0))
28263 && REG_P (SET_DEST (prev_set))
28264 && REGNO (SET_DEST (prev_set))
28265 == REGNO (XEXP (XEXP (SET_SRC (curr_set), 0), 0)))
28266 {
28267 /* Fuse ALU operations followed by conditional branch instruction. */
28268 switch (get_attr_type (prev))
28269 {
28270 case TYPE_ALU_IMM:
28271 case TYPE_ALU_SREG:
28272 case TYPE_ADC_REG:
28273 case TYPE_ADC_IMM:
28274 case TYPE_ADCS_REG:
28275 case TYPE_ADCS_IMM:
28276 case TYPE_LOGIC_REG:
28277 case TYPE_LOGIC_IMM:
28278 case TYPE_CSEL:
28279 case TYPE_ADR:
28280 case TYPE_MOV_IMM:
28281 case TYPE_SHIFT_REG:
28282 case TYPE_SHIFT_IMM:
28283 case TYPE_BFM:
28284 case TYPE_RBIT:
28285 case TYPE_REV:
28286 case TYPE_EXTEND:
28287 return true;
28288
28289 default:;
28290 }
28291 }
28292 }
28293
28294 /* Fuse A+B+1 and A-B-1 */
28295 if (simple_sets_p
28296 && aarch64_fusion_enabled_p (AARCH64_FUSE_ADDSUB_2REG_CONST1))
28297 {
28298 /* We're trying to match:
28299 prev == (set (r0) (plus (r0) (r1)))
28300 curr == (set (r0) (plus (r0) (const_int 1)))
28301 or:
28302 prev == (set (r0) (minus (r0) (r1)))
28303 curr == (set (r0) (plus (r0) (const_int -1))) */
28304
28305 rtx prev_src = SET_SRC (prev_set);
28306 rtx curr_src = SET_SRC (curr_set);
28307
28308 int polarity = 1;
28309 if (GET_CODE (prev_src) == MINUS)
28310 polarity = -1;
28311
28312 if (GET_CODE (curr_src) == PLUS
28313 && (GET_CODE (prev_src) == PLUS || GET_CODE (prev_src) == MINUS)
28314 && CONST_INT_P (XEXP (curr_src, 1))
28315 && INTVAL (XEXP (curr_src, 1)) == polarity
28316 && REG_P (XEXP (curr_src, 0))
28317 && REG_P (SET_DEST (prev_set))
28318 && REGNO (SET_DEST (prev_set)) == REGNO (XEXP (curr_src, 0)))
28319 return true;
28320 }
28321
28322 return false;
28323 }
28324
28325 /* Return true iff the instruction fusion described by OP is enabled. */
28326
28327 bool
28328 aarch64_fusion_enabled_p (enum aarch64_fusion_pairs op)
28329 {
28330 return (aarch64_tune_params.fusible_ops & op) != 0;
28331 }
28332
28333 /* If MEM is in the form of [base+offset], extract the two parts
28334 of address and set to BASE and OFFSET, otherwise return false
28335 after clearing BASE and OFFSET. */
28336
28337 bool
28338 extract_base_offset_in_addr (rtx mem, rtx *base, rtx *offset)
28339 {
28340 rtx addr;
28341
28342 gcc_assert (MEM_P (mem));
28343
28344 addr = XEXP (mem, 0);
28345
28346 if (REG_P (addr))
28347 {
28348 *base = addr;
28349 *offset = const0_rtx;
28350 return true;
28351 }
28352
28353 if (GET_CODE (addr) == PLUS
28354 && REG_P (XEXP (addr, 0)) && CONST_INT_P (XEXP (addr, 1)))
28355 {
28356 *base = XEXP (addr, 0);
28357 *offset = XEXP (addr, 1);
28358 return true;
28359 }
28360
28361 *base = NULL_RTX;
28362 *offset = NULL_RTX;
28363
28364 return false;
28365 }
28366
28367 /* Types for scheduling fusion. */
28368 enum sched_fusion_type
28369 {
28370 SCHED_FUSION_NONE = 0,
28371 SCHED_FUSION_LD_SIGN_EXTEND,
28372 SCHED_FUSION_LD_ZERO_EXTEND,
28373 SCHED_FUSION_LD,
28374 SCHED_FUSION_ST,
28375 SCHED_FUSION_NUM
28376 };
28377
28378 /* If INSN is a load or store of address in the form of [base+offset],
28379 extract the two parts and set to BASE and OFFSET. Return scheduling
28380 fusion type this INSN is. */
28381
28382 static enum sched_fusion_type
28383 fusion_load_store (rtx_insn *insn, rtx *base, rtx *offset)
28384 {
28385 rtx x, dest, src;
28386 enum sched_fusion_type fusion = SCHED_FUSION_LD;
28387
28388 gcc_assert (INSN_P (insn));
28389 x = PATTERN (insn);
28390 if (GET_CODE (x) != SET)
28391 return SCHED_FUSION_NONE;
28392
28393 src = SET_SRC (x);
28394 dest = SET_DEST (x);
28395
28396 machine_mode dest_mode = GET_MODE (dest);
28397
28398 if (!aarch64_mode_valid_for_sched_fusion_p (dest_mode))
28399 return SCHED_FUSION_NONE;
28400
28401 if (GET_CODE (src) == SIGN_EXTEND)
28402 {
28403 fusion = SCHED_FUSION_LD_SIGN_EXTEND;
28404 src = XEXP (src, 0);
28405 if (!MEM_P (src) || GET_MODE (src) != SImode)
28406 return SCHED_FUSION_NONE;
28407 }
28408 else if (GET_CODE (src) == ZERO_EXTEND)
28409 {
28410 fusion = SCHED_FUSION_LD_ZERO_EXTEND;
28411 src = XEXP (src, 0);
28412 if (!MEM_P (src) || GET_MODE (src) != SImode)
28413 return SCHED_FUSION_NONE;
28414 }
28415
28416 if (MEM_P (src) && REG_P (dest))
28417 extract_base_offset_in_addr (src, base, offset);
28418 else if (MEM_P (dest) && (REG_P (src) || src == const0_rtx))
28419 {
28420 fusion = SCHED_FUSION_ST;
28421 extract_base_offset_in_addr (dest, base, offset);
28422 }
28423 else
28424 return SCHED_FUSION_NONE;
28425
28426 if (*base == NULL_RTX || *offset == NULL_RTX)
28427 fusion = SCHED_FUSION_NONE;
28428
28429 return fusion;
28430 }
28431
28432 /* Implement the TARGET_SCHED_FUSION_PRIORITY hook.
28433
28434 Currently we only support to fuse ldr or str instructions, so FUSION_PRI
28435 and PRI are only calculated for these instructions. For other instruction,
28436 FUSION_PRI and PRI are simply set to MAX_PRI - 1. In the future, other
28437 type instruction fusion can be added by returning different priorities.
28438
28439 It's important that irrelevant instructions get the largest FUSION_PRI. */
28440
28441 static void
28442 aarch64_sched_fusion_priority (rtx_insn *insn, int max_pri,
28443 int *fusion_pri, int *pri)
28444 {
28445 int tmp, off_val;
28446 rtx base, offset;
28447 enum sched_fusion_type fusion;
28448
28449 gcc_assert (INSN_P (insn));
28450
28451 tmp = max_pri - 1;
28452 fusion = fusion_load_store (insn, &base, &offset);
28453 if (fusion == SCHED_FUSION_NONE)
28454 {
28455 *pri = tmp;
28456 *fusion_pri = tmp;
28457 return;
28458 }
28459
28460 /* Set FUSION_PRI according to fusion type and base register. */
28461 *fusion_pri = tmp - fusion * FIRST_PSEUDO_REGISTER - REGNO (base);
28462
28463 /* Calculate PRI. */
28464 tmp /= 2;
28465
28466 /* INSN with smaller offset goes first. */
28467 off_val = (int)(INTVAL (offset));
28468 if (off_val >= 0)
28469 tmp -= (off_val & 0xfffff);
28470 else
28471 tmp += ((- off_val) & 0xfffff);
28472
28473 *pri = tmp;
28474 return;
28475 }
28476
28477 /* Implement the TARGET_SCHED_ADJUST_PRIORITY hook.
28478 Adjust priority of sha1h instructions so they are scheduled before
28479 other SHA1 instructions. */
28480
28481 static int
28482 aarch64_sched_adjust_priority (rtx_insn *insn, int priority)
28483 {
28484 rtx x = PATTERN (insn);
28485
28486 if (GET_CODE (x) == SET)
28487 {
28488 x = SET_SRC (x);
28489
28490 if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_SHA1H)
28491 return priority + 10;
28492 }
28493
28494 return priority;
28495 }
28496
28497 /* If REVERSED is null, return true if memory reference *MEM2 comes
28498 immediately after memory reference *MEM1. Do not change the references
28499 in this case.
28500
28501 Otherwise, check if *MEM1 and *MEM2 are consecutive memory references and,
28502 if they are, try to make them use constant offsets from the same base
28503 register. Return true on success. When returning true, set *REVERSED
28504 to true if *MEM1 comes after *MEM2, false if *MEM1 comes before *MEM2. */
28505 static bool
28506 aarch64_check_consecutive_mems (rtx *mem1, rtx *mem2, bool *reversed)
28507 {
28508 if (reversed)
28509 *reversed = false;
28510
28511 if (GET_RTX_CLASS (GET_CODE (XEXP (*mem1, 0))) == RTX_AUTOINC
28512 || GET_RTX_CLASS (GET_CODE (XEXP (*mem2, 0))) == RTX_AUTOINC)
28513 return false;
28514
28515 if (!MEM_SIZE_KNOWN_P (*mem1) || !MEM_SIZE_KNOWN_P (*mem2))
28516 return false;
28517
28518 auto size1 = MEM_SIZE (*mem1);
28519 auto size2 = MEM_SIZE (*mem2);
28520
28521 rtx base1, base2, offset1, offset2;
28522 extract_base_offset_in_addr (*mem1, &base1, &offset1);
28523 extract_base_offset_in_addr (*mem2, &base2, &offset2);
28524
28525 /* Make sure at least one memory is in base+offset form. */
28526 if (!(base1 && offset1) && !(base2 && offset2))
28527 return false;
28528
28529 /* If both mems already use the same base register, just check the
28530 offsets. */
28531 if (base1 && base2 && rtx_equal_p (base1, base2))
28532 {
28533 if (!offset1 || !offset2)
28534 return false;
28535
28536 if (known_eq (UINTVAL (offset1) + size1, UINTVAL (offset2)))
28537 return true;
28538
28539 if (known_eq (UINTVAL (offset2) + size2, UINTVAL (offset1)) && reversed)
28540 {
28541 *reversed = true;
28542 return true;
28543 }
28544
28545 return false;
28546 }
28547
28548 /* Otherwise, check whether the MEM_EXPRs and MEM_OFFSETs together
28549 guarantee that the values are consecutive. */
28550 if (MEM_EXPR (*mem1)
28551 && MEM_EXPR (*mem2)
28552 && MEM_OFFSET_KNOWN_P (*mem1)
28553 && MEM_OFFSET_KNOWN_P (*mem2))
28554 {
28555 poly_int64 expr_offset1;
28556 poly_int64 expr_offset2;
28557 tree expr_base1 = get_addr_base_and_unit_offset (MEM_EXPR (*mem1),
28558 &expr_offset1);
28559 tree expr_base2 = get_addr_base_and_unit_offset (MEM_EXPR (*mem2),
28560 &expr_offset2);
28561 if (!expr_base1
28562 || !expr_base2
28563 || !DECL_P (expr_base1)
28564 || !operand_equal_p (expr_base1, expr_base2, OEP_ADDRESS_OF))
28565 return false;
28566
28567 expr_offset1 += MEM_OFFSET (*mem1);
28568 expr_offset2 += MEM_OFFSET (*mem2);
28569
28570 if (known_eq (expr_offset1 + size1, expr_offset2))
28571 ;
28572 else if (known_eq (expr_offset2 + size2, expr_offset1) && reversed)
28573 *reversed = true;
28574 else
28575 return false;
28576
28577 if (reversed)
28578 {
28579 if (base2)
28580 {
28581 rtx addr1 = plus_constant (Pmode, XEXP (*mem2, 0),
28582 expr_offset1 - expr_offset2);
28583 *mem1 = replace_equiv_address_nv (*mem1, addr1);
28584 }
28585 else
28586 {
28587 rtx addr2 = plus_constant (Pmode, XEXP (*mem1, 0),
28588 expr_offset2 - expr_offset1);
28589 *mem2 = replace_equiv_address_nv (*mem2, addr2);
28590 }
28591 }
28592 return true;
28593 }
28594
28595 return false;
28596 }
28597
28598 /* Test if MODE is suitable for a single transfer register in an ldp or stp
28599 instruction. */
28600
28601 bool
28602 aarch64_ldpstp_operand_mode_p (machine_mode mode)
28603 {
28604 if (!targetm.hard_regno_mode_ok (V0_REGNUM, mode)
28605 || hard_regno_nregs (V0_REGNUM, mode) > 1)
28606 return false;
28607
28608 const auto size = GET_MODE_SIZE (mode);
28609 return known_eq (size, 4) || known_eq (size, 8) || known_eq (size, 16);
28610 }
28611
28612 /* Return true if MEM1 and MEM2 can be combined into a single access
28613 of mode MODE, with the combined access having the same address as MEM1. */
28614
28615 bool
28616 aarch64_mergeable_load_pair_p (machine_mode mode, rtx mem1, rtx mem2)
28617 {
28618 if (STRICT_ALIGNMENT && MEM_ALIGN (mem1) < GET_MODE_ALIGNMENT (mode))
28619 return false;
28620 return aarch64_check_consecutive_mems (&mem1, &mem2, nullptr);
28621 }
28622
28623 /* Return true if MEM agrees with the ldp-stp policy model.
28624 Otherwise, false. */
28625
28626 bool
28627 aarch64_mem_ok_with_ldpstp_policy_model (rtx mem, bool load, machine_mode mode)
28628 {
28629 auto policy = (load
28630 ? aarch64_tune_params.ldp_policy_model
28631 : aarch64_tune_params.stp_policy_model);
28632
28633 /* If we have AARCH64_LDP_STP_POLICY_NEVER, reject the load pair. */
28634 if (policy == AARCH64_LDP_STP_POLICY_NEVER)
28635 return false;
28636
28637 /* If we have AARCH64_LDP_STP_POLICY_ALIGNED,
28638 do not emit the load pair unless the alignment is checked to be
28639 at least double the alignment of the type. */
28640 if (policy == AARCH64_LDP_STP_POLICY_ALIGNED
28641 && !optimize_function_for_size_p (cfun)
28642 && MEM_ALIGN (mem) < 2 * GET_MODE_ALIGNMENT (mode))
28643 return false;
28644
28645 return true;
28646 }
28647
28648 /* Given OPERANDS of consecutive load/store, check if we can merge
28649 them into ldp/stp. LOAD is true if they are load instructions. */
28650
28651 bool
28652 aarch64_operands_ok_for_ldpstp (rtx *operands, bool load)
28653 {
28654 enum reg_class rclass_1, rclass_2;
28655 rtx mem_1, mem_2, reg_1, reg_2;
28656
28657 if (load)
28658 {
28659 mem_1 = operands[1];
28660 mem_2 = operands[3];
28661 reg_1 = operands[0];
28662 reg_2 = operands[2];
28663 gcc_assert (REG_P (reg_1) && REG_P (reg_2));
28664 if (REGNO (reg_1) == REGNO (reg_2))
28665 return false;
28666 if (reg_overlap_mentioned_p (reg_1, mem_2))
28667 return false;
28668 }
28669 else
28670 {
28671 mem_1 = operands[0];
28672 mem_2 = operands[2];
28673 reg_1 = operands[1];
28674 reg_2 = operands[3];
28675 }
28676
28677 /* The mems cannot be volatile. */
28678 if (MEM_VOLATILE_P (mem_1) || MEM_VOLATILE_P (mem_2))
28679 return false;
28680
28681 /* Check if the addresses are in the form of [base+offset]. */
28682 bool reversed = false;
28683 if (!aarch64_check_consecutive_mems (&mem_1, &mem_2, &reversed))
28684 return false;
28685
28686 /* The operands must be of the same size. */
28687 gcc_assert (known_eq (GET_MODE_SIZE (GET_MODE (mem_1)),
28688 GET_MODE_SIZE (GET_MODE (mem_2))));
28689
28690 /* The lower memory access must be a mem-pair operand. */
28691 rtx lower_mem = reversed ? mem_2 : mem_1;
28692 machine_mode lower_mem_mode = GET_MODE (lower_mem);
28693 if (!aarch64_mem_pair_operand (lower_mem, lower_mem_mode))
28694 return false;
28695
28696 /* Check if lower_mem is ok with the ldp-stp policy model. */
28697 if (!aarch64_mem_ok_with_ldpstp_policy_model (lower_mem, load,
28698 lower_mem_mode))
28699 return false;
28700
28701 if (REG_P (reg_1) && FP_REGNUM_P (REGNO (reg_1)))
28702 rclass_1 = FP_REGS;
28703 else
28704 rclass_1 = GENERAL_REGS;
28705
28706 if (REG_P (reg_2) && FP_REGNUM_P (REGNO (reg_2)))
28707 rclass_2 = FP_REGS;
28708 else
28709 rclass_2 = GENERAL_REGS;
28710
28711 /* Check if the registers are of same class. */
28712 if (rclass_1 != rclass_2)
28713 return false;
28714
28715 return true;
28716 }
28717
28718 /* Given OPERANDS of consecutive load/store that can be merged,
28719 swap them if they are not in ascending order. */
28720 void
28721 aarch64_swap_ldrstr_operands (rtx* operands, bool load)
28722 {
28723 int mem_op = load ? 1 : 0;
28724 bool reversed = false;
28725 if (!aarch64_check_consecutive_mems (operands + mem_op,
28726 operands + mem_op + 2, &reversed))
28727 gcc_unreachable ();
28728
28729 if (reversed)
28730 {
28731 /* Irrespective of whether this is a load or a store,
28732 we do the same swap. */
28733 std::swap (operands[0], operands[2]);
28734 std::swap (operands[1], operands[3]);
28735 }
28736 }
28737
28738 /* Helper function used for generation of load/store pair instructions, called
28739 from peepholes in aarch64-ldpstp.md. OPERANDS is an array of
28740 operands as matched by the peepholes in that file. LOAD_P is true if we're
28741 generating a load pair, otherwise we're generating a store pair. CODE is
28742 either {ZERO,SIGN}_EXTEND for extending loads or UNKNOWN if we're generating a
28743 standard load/store pair. */
28744
28745 void
28746 aarch64_finish_ldpstp_peephole (rtx *operands, bool load_p, enum rtx_code code)
28747 {
28748 aarch64_swap_ldrstr_operands (operands, load_p);
28749
28750 if (load_p)
28751 emit_insn (aarch64_gen_load_pair (operands[0], operands[2],
28752 operands[1], code));
28753 else
28754 {
28755 gcc_assert (code == UNKNOWN);
28756 emit_insn (aarch64_gen_store_pair (operands[0], operands[1],
28757 operands[3]));
28758 }
28759 }
28760
28761 /* Taking X and Y to be HOST_WIDE_INT pointers, return the result of a
28762 comparison between the two. */
28763 int
28764 aarch64_host_wide_int_compare (const void *x, const void *y)
28765 {
28766 return wi::cmps (* ((const HOST_WIDE_INT *) x),
28767 * ((const HOST_WIDE_INT *) y));
28768 }
28769
28770 /* Taking X and Y to be pairs of RTX, one pointing to a MEM rtx and the
28771 other pointing to a REG rtx containing an offset, compare the offsets
28772 of the two pairs.
28773
28774 Return:
28775
28776 1 iff offset (X) > offset (Y)
28777 0 iff offset (X) == offset (Y)
28778 -1 iff offset (X) < offset (Y) */
28779 int
28780 aarch64_ldrstr_offset_compare (const void *x, const void *y)
28781 {
28782 const rtx * operands_1 = (const rtx *) x;
28783 const rtx * operands_2 = (const rtx *) y;
28784 rtx mem_1, mem_2, base, offset_1, offset_2;
28785
28786 if (MEM_P (operands_1[0]))
28787 mem_1 = operands_1[0];
28788 else
28789 mem_1 = operands_1[1];
28790
28791 if (MEM_P (operands_2[0]))
28792 mem_2 = operands_2[0];
28793 else
28794 mem_2 = operands_2[1];
28795
28796 /* Extract the offsets. */
28797 extract_base_offset_in_addr (mem_1, &base, &offset_1);
28798 extract_base_offset_in_addr (mem_2, &base, &offset_2);
28799
28800 gcc_assert (offset_1 != NULL_RTX && offset_2 != NULL_RTX);
28801
28802 return wi::cmps (INTVAL (offset_1), INTVAL (offset_2));
28803 }
28804
28805 /* Given OPERANDS of consecutive load/store, check if we can merge
28806 them into ldp/stp by adjusting the offset. LOAD is true if they
28807 are load instructions. MODE is the mode of memory operands.
28808
28809 Given below consecutive stores:
28810
28811 str w1, [xb, 0x100]
28812 str w1, [xb, 0x104]
28813 str w1, [xb, 0x108]
28814 str w1, [xb, 0x10c]
28815
28816 Though the offsets are out of the range supported by stp, we can
28817 still pair them after adjusting the offset, like:
28818
28819 add scratch, xb, 0x100
28820 stp w1, w1, [scratch]
28821 stp w1, w1, [scratch, 0x8]
28822
28823 The peephole patterns detecting this opportunity should guarantee
28824 the scratch register is avaliable. */
28825
28826 bool
28827 aarch64_operands_adjust_ok_for_ldpstp (rtx *operands, bool load,
28828 machine_mode mode)
28829 {
28830 const int num_insns = 4;
28831 enum reg_class rclass;
28832 HOST_WIDE_INT offvals[num_insns], msize;
28833 rtx mem[num_insns], reg[num_insns], base[num_insns], offset[num_insns];
28834
28835 if (load)
28836 {
28837 for (int i = 0; i < num_insns; i++)
28838 {
28839 reg[i] = operands[2 * i];
28840 mem[i] = operands[2 * i + 1];
28841
28842 gcc_assert (REG_P (reg[i]));
28843 }
28844
28845 /* Do not attempt to merge the loads if the loads clobber each other. */
28846 for (int i = 0; i < 8; i += 2)
28847 for (int j = i + 2; j < 8; j += 2)
28848 if (reg_overlap_mentioned_p (operands[i], operands[j]))
28849 return false;
28850 }
28851 else
28852 for (int i = 0; i < num_insns; i++)
28853 {
28854 mem[i] = operands[2 * i];
28855 reg[i] = operands[2 * i + 1];
28856 }
28857
28858 /* Skip if memory operand is by itself valid for ldp/stp. */
28859 if (!MEM_P (mem[0]) || aarch64_mem_pair_operand (mem[0], mode))
28860 return false;
28861
28862 for (int i = 0; i < num_insns; i++)
28863 {
28864 /* The mems cannot be volatile. */
28865 if (MEM_VOLATILE_P (mem[i]))
28866 return false;
28867
28868 /* Check if the addresses are in the form of [base+offset]. */
28869 extract_base_offset_in_addr (mem[i], base + i, offset + i);
28870 if (base[i] == NULL_RTX || offset[i] == NULL_RTX)
28871 return false;
28872 }
28873
28874 /* Check if the registers are of same class. */
28875 rclass = REG_P (reg[0]) && FP_REGNUM_P (REGNO (reg[0]))
28876 ? FP_REGS : GENERAL_REGS;
28877
28878 for (int i = 1; i < num_insns; i++)
28879 if (REG_P (reg[i]) && FP_REGNUM_P (REGNO (reg[i])))
28880 {
28881 if (rclass != FP_REGS)
28882 return false;
28883 }
28884 else
28885 {
28886 if (rclass != GENERAL_REGS)
28887 return false;
28888 }
28889
28890 /* Only the last register in the order in which they occur
28891 may be clobbered by the load. */
28892 if (rclass == GENERAL_REGS && load)
28893 for (int i = 0; i < num_insns - 1; i++)
28894 if (reg_mentioned_p (reg[i], mem[i]))
28895 return false;
28896
28897 /* Check if the bases are same. */
28898 for (int i = 0; i < num_insns - 1; i++)
28899 if (!rtx_equal_p (base[i], base[i + 1]))
28900 return false;
28901
28902 for (int i = 0; i < num_insns; i++)
28903 offvals[i] = INTVAL (offset[i]);
28904
28905 msize = GET_MODE_SIZE (mode).to_constant ();
28906
28907 /* Check if the offsets can be put in the right order to do a ldp/stp. */
28908 qsort (offvals, num_insns, sizeof (HOST_WIDE_INT),
28909 aarch64_host_wide_int_compare);
28910
28911 if (!(offvals[1] == offvals[0] + msize
28912 && offvals[3] == offvals[2] + msize))
28913 return false;
28914
28915 /* Check that offsets are within range of each other. The ldp/stp
28916 instructions have 7 bit immediate offsets, so use 0x80. */
28917 if (offvals[2] - offvals[0] >= msize * 0x80)
28918 return false;
28919
28920 /* The offsets must be aligned with respect to each other. */
28921 if (offvals[0] % msize != offvals[2] % msize)
28922 return false;
28923
28924 /* Check if mem[0] is ok with the ldp-stp policy model. */
28925 if (!aarch64_mem_ok_with_ldpstp_policy_model (mem[0], load, mode))
28926 return false;
28927
28928 return true;
28929 }
28930
28931 /* Given OPERANDS of consecutive load/store, this function pairs them
28932 into LDP/STP after adjusting the offset. It depends on the fact
28933 that the operands can be sorted so the offsets are correct for STP.
28934 MODE is the mode of memory operands. CODE is the rtl operator
28935 which should be applied to all memory operands, it's SIGN_EXTEND,
28936 ZERO_EXTEND or UNKNOWN. */
28937
28938 bool
28939 aarch64_gen_adjusted_ldpstp (rtx *operands, bool load,
28940 machine_mode mode, RTX_CODE code)
28941 {
28942 rtx base, offset_1, offset_2;
28943 rtx mem_1, mem_2;
28944 rtx temp_operands[8];
28945 HOST_WIDE_INT off_val_1, off_val_2, base_off, new_off_1, new_off_2,
28946 stp_off_upper_limit, stp_off_lower_limit, msize;
28947
28948 /* We make changes on a copy as we may still bail out. */
28949 for (int i = 0; i < 8; i ++)
28950 temp_operands[i] = operands[i];
28951
28952 /* Sort the operands. Note for cases as below:
28953 [base + 0x310] = A
28954 [base + 0x320] = B
28955 [base + 0x330] = C
28956 [base + 0x320] = D
28957 We need stable sorting otherwise wrong data may be store to offset 0x320.
28958 Also note the dead store in above case should be optimized away, but no
28959 guarantees here. */
28960 gcc_stablesort(temp_operands, 4, 2 * sizeof (rtx *),
28961 aarch64_ldrstr_offset_compare);
28962
28963 /* Copy the memory operands so that if we have to bail for some
28964 reason the original addresses are unchanged. */
28965 if (load)
28966 {
28967 mem_1 = copy_rtx (temp_operands[1]);
28968 mem_2 = copy_rtx (temp_operands[5]);
28969 }
28970 else
28971 {
28972 mem_1 = copy_rtx (temp_operands[0]);
28973 mem_2 = copy_rtx (temp_operands[4]);
28974 gcc_assert (code == UNKNOWN);
28975 }
28976
28977 extract_base_offset_in_addr (mem_1, &base, &offset_1);
28978 extract_base_offset_in_addr (mem_2, &base, &offset_2);
28979 gcc_assert (base != NULL_RTX && offset_1 != NULL_RTX
28980 && offset_2 != NULL_RTX);
28981
28982 /* Adjust offset so it can fit in LDP/STP instruction. */
28983 msize = GET_MODE_SIZE (mode).to_constant();
28984 stp_off_upper_limit = msize * (0x40 - 1);
28985 stp_off_lower_limit = - msize * 0x40;
28986
28987 off_val_1 = INTVAL (offset_1);
28988 off_val_2 = INTVAL (offset_2);
28989
28990 /* The base offset is optimally half way between the two STP/LDP offsets. */
28991 if (msize <= 4)
28992 base_off = (off_val_1 + off_val_2) / 2;
28993 else
28994 /* However, due to issues with negative LDP/STP offset generation for
28995 larger modes, for DF, DD, DI and vector modes. we must not use negative
28996 addresses smaller than 9 signed unadjusted bits can store. This
28997 provides the most range in this case. */
28998 base_off = off_val_1;
28999
29000 /* Adjust the base so that it is aligned with the addresses but still
29001 optimal. */
29002 if (base_off % msize != off_val_1 % msize)
29003 /* Fix the offset, bearing in mind we want to make it bigger not
29004 smaller. */
29005 base_off += (((base_off % msize) - (off_val_1 % msize)) + msize) % msize;
29006 else if (msize <= 4)
29007 /* The negative range of LDP/STP is one larger than the positive range. */
29008 base_off += msize;
29009
29010 /* Check if base offset is too big or too small. We can attempt to resolve
29011 this issue by setting it to the maximum value and seeing if the offsets
29012 still fit. */
29013 if (base_off >= 0x1000)
29014 {
29015 base_off = 0x1000 - 1;
29016 /* We must still make sure that the base offset is aligned with respect
29017 to the address. But it may not be made any bigger. */
29018 base_off -= (((base_off % msize) - (off_val_1 % msize)) + msize) % msize;
29019 }
29020
29021 /* Likewise for the case where the base is too small. */
29022 if (base_off <= -0x1000)
29023 {
29024 base_off = -0x1000 + 1;
29025 base_off += (((base_off % msize) - (off_val_1 % msize)) + msize) % msize;
29026 }
29027
29028 /* Offset of the first STP/LDP. */
29029 new_off_1 = off_val_1 - base_off;
29030
29031 /* Offset of the second STP/LDP. */
29032 new_off_2 = off_val_2 - base_off;
29033
29034 /* The offsets must be within the range of the LDP/STP instructions. */
29035 if (new_off_1 > stp_off_upper_limit || new_off_1 < stp_off_lower_limit
29036 || new_off_2 > stp_off_upper_limit || new_off_2 < stp_off_lower_limit)
29037 return false;
29038
29039 replace_equiv_address_nv (mem_1, plus_constant (Pmode, operands[8],
29040 new_off_1), true);
29041 replace_equiv_address_nv (mem_2, plus_constant (Pmode, operands[8],
29042 new_off_2), true);
29043
29044 if (!aarch64_mem_pair_operand (mem_1, mode)
29045 || !aarch64_mem_pair_operand (mem_2, mode))
29046 return false;
29047
29048 if (load)
29049 {
29050 operands[0] = temp_operands[0];
29051 operands[1] = mem_1;
29052 operands[2] = temp_operands[2];
29053 operands[4] = temp_operands[4];
29054 operands[5] = mem_2;
29055 operands[6] = temp_operands[6];
29056 }
29057 else
29058 {
29059 operands[0] = mem_1;
29060 operands[1] = temp_operands[1];
29061 operands[3] = temp_operands[3];
29062 operands[4] = mem_2;
29063 operands[5] = temp_operands[5];
29064 operands[7] = temp_operands[7];
29065 }
29066
29067 /* Emit adjusting instruction. */
29068 emit_insn (gen_rtx_SET (operands[8], plus_constant (DImode, base, base_off)));
29069 /* Emit ldp/stp instructions. */
29070 if (load)
29071 {
29072 emit_insn (aarch64_gen_load_pair (operands[0], operands[2],
29073 operands[1], code));
29074 emit_insn (aarch64_gen_load_pair (operands[4], operands[6],
29075 operands[5], code));
29076 }
29077 else
29078 {
29079 emit_insn (aarch64_gen_store_pair (operands[0], operands[1],
29080 operands[3]));
29081 emit_insn (aarch64_gen_store_pair (operands[4], operands[5],
29082 operands[7]));
29083 }
29084 return true;
29085 }
29086
29087 /* Implement TARGET_VECTORIZE_CONDITIONAL_OPERATION_IS_EXPENSIVE. Assume that
29088 predicated operations when available are beneficial. */
29089
29090 static bool
29091 aarch64_conditional_operation_is_expensive (unsigned)
29092 {
29093 return false;
29094 }
29095
29096 /* Implement TARGET_VECTORIZE_EMPTY_MASK_IS_EXPENSIVE. Assume for now that
29097 it isn't worth branching around empty masked ops (including masked
29098 stores). */
29099
29100 static bool
29101 aarch64_empty_mask_is_expensive (unsigned)
29102 {
29103 return false;
29104 }
29105
29106 /* Return 1 if pseudo register should be created and used to hold
29107 GOT address for PIC code. */
29108
29109 bool
29110 aarch64_use_pseudo_pic_reg (void)
29111 {
29112 return aarch64_cmodel == AARCH64_CMODEL_SMALL_SPIC;
29113 }
29114
29115 /* Implement TARGET_UNSPEC_MAY_TRAP_P. */
29116
29117 static int
29118 aarch64_unspec_may_trap_p (const_rtx x, unsigned flags)
29119 {
29120 switch (XINT (x, 1))
29121 {
29122 case UNSPEC_GOTSMALLPIC:
29123 case UNSPEC_GOTSMALLPIC28K:
29124 case UNSPEC_GOTTINYPIC:
29125 return 0;
29126 default:
29127 break;
29128 }
29129
29130 return default_unspec_may_trap_p (x, flags);
29131 }
29132
29133
29134 /* If X is a positive CONST_DOUBLE with a value that is a power of 2
29135 return the log2 of that value. Otherwise return -1. */
29136
29137 int
29138 aarch64_fpconst_pow_of_2 (rtx x)
29139 {
29140 const REAL_VALUE_TYPE *r;
29141
29142 if (!CONST_DOUBLE_P (x))
29143 return -1;
29144
29145 r = CONST_DOUBLE_REAL_VALUE (x);
29146
29147 if (REAL_VALUE_NEGATIVE (*r)
29148 || REAL_VALUE_ISNAN (*r)
29149 || REAL_VALUE_ISINF (*r)
29150 || !real_isinteger (r, DFmode))
29151 return -1;
29152
29153 return exact_log2 (real_to_integer (r));
29154 }
29155
29156 /* If X is a positive CONST_DOUBLE with a value that is the reciprocal of a
29157 power of 2 (i.e 1/2^n) return the number of float bits. e.g. for x==(1/2^n)
29158 return n. Otherwise return -1. */
29159
29160 int
29161 aarch64_fpconst_pow2_recip (rtx x)
29162 {
29163 REAL_VALUE_TYPE r0;
29164
29165 if (!CONST_DOUBLE_P (x))
29166 return -1;
29167
29168 r0 = *CONST_DOUBLE_REAL_VALUE (x);
29169 if (exact_real_inverse (DFmode, &r0)
29170 && !REAL_VALUE_NEGATIVE (r0))
29171 {
29172 int ret = exact_log2 (real_to_integer (&r0));
29173 if (ret >= 1 && ret <= 32)
29174 return ret;
29175 }
29176 return -1;
29177 }
29178
29179 /* If X is a vector of equal CONST_DOUBLE values and that value is
29180 Y, return the aarch64_fpconst_pow_of_2 of Y. Otherwise return -1. */
29181
29182 int
29183 aarch64_vec_fpconst_pow_of_2 (rtx x)
29184 {
29185 int nelts;
29186 if (!CONST_VECTOR_P (x)
29187 || !CONST_VECTOR_NUNITS (x).is_constant (&nelts))
29188 return -1;
29189
29190 if (GET_MODE_CLASS (GET_MODE (x)) != MODE_VECTOR_FLOAT)
29191 return -1;
29192
29193 int firstval = aarch64_fpconst_pow_of_2 (CONST_VECTOR_ELT (x, 0));
29194 if (firstval <= 0)
29195 return -1;
29196
29197 for (int i = 1; i < nelts; i++)
29198 if (aarch64_fpconst_pow_of_2 (CONST_VECTOR_ELT (x, i)) != firstval)
29199 return -1;
29200
29201 return firstval;
29202 }
29203
29204 /* Implement TARGET_PROMOTED_TYPE to promote 16-bit floating point types
29205 to float.
29206
29207 __fp16 always promotes through this hook.
29208 _Float16 may promote if TARGET_FLT_EVAL_METHOD is 16, but we do that
29209 through the generic excess precision logic rather than here. */
29210
29211 static tree
29212 aarch64_promoted_type (const_tree t)
29213 {
29214 if (SCALAR_FLOAT_TYPE_P (t)
29215 && TYPE_MAIN_VARIANT (t) == aarch64_fp16_type_node)
29216 return float_type_node;
29217
29218 return NULL_TREE;
29219 }
29220
29221 /* Implement the TARGET_OPTAB_SUPPORTED_P hook. */
29222
29223 static bool
29224 aarch64_optab_supported_p (int op, machine_mode mode1, machine_mode,
29225 optimization_type opt_type)
29226 {
29227 switch (op)
29228 {
29229 case rsqrt_optab:
29230 return opt_type == OPTIMIZE_FOR_SPEED && use_rsqrt_p (mode1);
29231
29232 default:
29233 return true;
29234 }
29235 }
29236
29237 /* Implement the TARGET_DWARF_POLY_INDETERMINATE_VALUE hook. */
29238
29239 static unsigned int
29240 aarch64_dwarf_poly_indeterminate_value (unsigned int i, unsigned int *factor,
29241 int *offset)
29242 {
29243 /* Polynomial invariant 1 == (VG / 2) - 1. */
29244 gcc_assert (i == 1);
29245 *factor = 2;
29246 *offset = 1;
29247 return AARCH64_DWARF_VG;
29248 }
29249
29250 /* Implement TARGET_LIBGCC_FLOATING_POINT_MODE_SUPPORTED_P - return TRUE
29251 if MODE is [BH]Fmode, and punt to the generic implementation otherwise. */
29252
29253 static bool
29254 aarch64_libgcc_floating_mode_supported_p (scalar_float_mode mode)
29255 {
29256 return ((mode == HFmode || mode == BFmode)
29257 ? true
29258 : default_libgcc_floating_mode_supported_p (mode));
29259 }
29260
29261 /* Implement TARGET_SCALAR_MODE_SUPPORTED_P - return TRUE
29262 if MODE is [BH]Fmode, and punt to the generic implementation otherwise. */
29263
29264 static bool
29265 aarch64_scalar_mode_supported_p (scalar_mode mode)
29266 {
29267 if (DECIMAL_FLOAT_MODE_P (mode))
29268 return default_decimal_float_supported_p ();
29269
29270 return ((mode == HFmode || mode == BFmode)
29271 ? true
29272 : default_scalar_mode_supported_p (mode));
29273 }
29274
29275 /* Set the value of FLT_EVAL_METHOD.
29276 ISO/IEC TS 18661-3 defines two values that we'd like to make use of:
29277
29278 0: evaluate all operations and constants, whose semantic type has at
29279 most the range and precision of type float, to the range and
29280 precision of float; evaluate all other operations and constants to
29281 the range and precision of the semantic type;
29282
29283 N, where _FloatN is a supported interchange floating type
29284 evaluate all operations and constants, whose semantic type has at
29285 most the range and precision of _FloatN type, to the range and
29286 precision of the _FloatN type; evaluate all other operations and
29287 constants to the range and precision of the semantic type;
29288
29289 If we have the ARMv8.2-A extensions then we support _Float16 in native
29290 precision, so we should set this to 16. Otherwise, we support the type,
29291 but want to evaluate expressions in float precision, so set this to
29292 0. */
29293
29294 static enum flt_eval_method
29295 aarch64_excess_precision (enum excess_precision_type type)
29296 {
29297 switch (type)
29298 {
29299 case EXCESS_PRECISION_TYPE_FAST:
29300 case EXCESS_PRECISION_TYPE_STANDARD:
29301 /* We can calculate either in 16-bit range and precision or
29302 32-bit range and precision. Make that decision based on whether
29303 we have native support for the ARMv8.2-A 16-bit floating-point
29304 instructions or not. */
29305 return (TARGET_FP_F16INST
29306 ? FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16
29307 : FLT_EVAL_METHOD_PROMOTE_TO_FLOAT);
29308 case EXCESS_PRECISION_TYPE_IMPLICIT:
29309 case EXCESS_PRECISION_TYPE_FLOAT16:
29310 return FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16;
29311 default:
29312 gcc_unreachable ();
29313 }
29314 return FLT_EVAL_METHOD_UNPREDICTABLE;
29315 }
29316
29317 /* Implement TARGET_C_BITINT_TYPE_INFO.
29318 Return true if _BitInt(N) is supported and fill its details into *INFO. */
29319 bool
29320 aarch64_bitint_type_info (int n, struct bitint_info *info)
29321 {
29322 if (TARGET_BIG_END)
29323 return false;
29324
29325 if (n <= 8)
29326 info->limb_mode = QImode;
29327 else if (n <= 16)
29328 info->limb_mode = HImode;
29329 else if (n <= 32)
29330 info->limb_mode = SImode;
29331 else if (n <= 64)
29332 info->limb_mode = DImode;
29333 else if (n <= 128)
29334 info->limb_mode = TImode;
29335 else
29336 /* The AAPCS for AArch64 defines _BitInt(N > 128) as an array with
29337 type {signed,unsigned} __int128[M] where M*128 >= N. However, to be
29338 able to use libgcc's implementation to support large _BitInt's we need
29339 to use a LIMB_MODE that is no larger than 'long long'. This is why we
29340 use DImode for our internal LIMB_MODE and we define the ABI_LIMB_MODE to
29341 be TImode to ensure we are ABI compliant. */
29342 info->limb_mode = DImode;
29343
29344 if (n > 128)
29345 info->abi_limb_mode = TImode;
29346 else
29347 info->abi_limb_mode = info->limb_mode;
29348 info->big_endian = TARGET_BIG_END;
29349 info->extended = false;
29350 return true;
29351 }
29352
29353 /* Implement TARGET_C_MODE_FOR_FLOATING_TYPE. Return TFmode for
29354 TI_LONG_DOUBLE_TYPE which is for long double type, go with the default
29355 one for the others. */
29356
29357 static machine_mode
29358 aarch64_c_mode_for_floating_type (enum tree_index ti)
29359 {
29360 if (ti == TI_LONG_DOUBLE_TYPE)
29361 return TFmode;
29362 return default_mode_for_floating_type (ti);
29363 }
29364
29365 /* Implement TARGET_SCHED_CAN_SPECULATE_INSN. Return true if INSN can be
29366 scheduled for speculative execution. Reject the long-running division
29367 and square-root instructions. */
29368
29369 static bool
29370 aarch64_sched_can_speculate_insn (rtx_insn *insn)
29371 {
29372 switch (get_attr_type (insn))
29373 {
29374 case TYPE_SDIV:
29375 case TYPE_UDIV:
29376 case TYPE_FDIVS:
29377 case TYPE_FDIVD:
29378 case TYPE_FSQRTS:
29379 case TYPE_FSQRTD:
29380 case TYPE_NEON_FP_SQRT_S:
29381 case TYPE_NEON_FP_SQRT_D:
29382 case TYPE_NEON_FP_SQRT_S_Q:
29383 case TYPE_NEON_FP_SQRT_D_Q:
29384 case TYPE_NEON_FP_DIV_S:
29385 case TYPE_NEON_FP_DIV_D:
29386 case TYPE_NEON_FP_DIV_S_Q:
29387 case TYPE_NEON_FP_DIV_D_Q:
29388 return false;
29389 default:
29390 return true;
29391 }
29392 }
29393
29394 /* Implement TARGET_COMPUTE_PRESSURE_CLASSES. */
29395
29396 static int
29397 aarch64_compute_pressure_classes (reg_class *classes)
29398 {
29399 int i = 0;
29400 classes[i++] = GENERAL_REGS;
29401 classes[i++] = FP_REGS;
29402 /* PR_REGS isn't a useful pressure class because many predicate pseudo
29403 registers need to go in PR_LO_REGS at some point during their
29404 lifetime. Splitting it into two halves has the effect of making
29405 all predicates count against PR_LO_REGS, so that we try whenever
29406 possible to restrict the number of live predicates to 8. This
29407 greatly reduces the amount of spilling in certain loops. */
29408 classes[i++] = PR_LO_REGS;
29409 classes[i++] = PR_HI_REGS;
29410 return i;
29411 }
29412
29413 /* Implement TARGET_CAN_CHANGE_MODE_CLASS. */
29414
29415 static bool
29416 aarch64_can_change_mode_class (machine_mode from,
29417 machine_mode to, reg_class_t)
29418 {
29419 return aarch64_modes_compatible_p (from, to);
29420 }
29421
29422 /* Implement TARGET_EARLY_REMAT_MODES. */
29423
29424 static void
29425 aarch64_select_early_remat_modes (sbitmap modes)
29426 {
29427 /* SVE values are not normally live across a call, so it should be
29428 worth doing early rematerialization even in VL-specific mode. */
29429 for (int i = 0; i < NUM_MACHINE_MODES; ++i)
29430 if (aarch64_sve_mode_p ((machine_mode) i))
29431 bitmap_set_bit (modes, i);
29432 }
29433
29434 /* Override the default target speculation_safe_value. */
29435 static rtx
29436 aarch64_speculation_safe_value (machine_mode mode,
29437 rtx result, rtx val, rtx failval)
29438 {
29439 /* Maybe we should warn if falling back to hard barriers. They are
29440 likely to be noticably more expensive than the alternative below. */
29441 if (!aarch64_track_speculation)
29442 return default_speculation_safe_value (mode, result, val, failval);
29443
29444 if (!REG_P (val))
29445 val = copy_to_mode_reg (mode, val);
29446
29447 if (!aarch64_reg_or_zero (failval, mode))
29448 failval = copy_to_mode_reg (mode, failval);
29449
29450 emit_insn (gen_despeculate_copy (mode, result, val, failval));
29451 return result;
29452 }
29453
29454 /* Implement TARGET_ESTIMATED_POLY_VALUE.
29455 Look into the tuning structure for an estimate.
29456 KIND specifies the type of requested estimate: min, max or likely.
29457 For cores with a known SVE width all three estimates are the same.
29458 For generic SVE tuning we want to distinguish the maximum estimate from
29459 the minimum and likely ones.
29460 The likely estimate is the same as the minimum in that case to give a
29461 conservative behavior of auto-vectorizing with SVE when it is a win
29462 even for 128-bit SVE.
29463 When SVE width information is available VAL.coeffs[1] is multiplied by
29464 the number of VQ chunks over the initial Advanced SIMD 128 bits. */
29465
29466 static HOST_WIDE_INT
29467 aarch64_estimated_poly_value (poly_int64 val,
29468 poly_value_estimate_kind kind
29469 = POLY_VALUE_LIKELY)
29470 {
29471 unsigned int width_source = aarch64_tune_params.sve_width;
29472
29473 /* If there is no core-specific information then the minimum and likely
29474 values are based on 128-bit vectors and the maximum is based on
29475 the architectural maximum of 2048 bits. */
29476 if (width_source == SVE_SCALABLE)
29477 switch (kind)
29478 {
29479 case POLY_VALUE_MIN:
29480 case POLY_VALUE_LIKELY:
29481 return val.coeffs[0];
29482 case POLY_VALUE_MAX:
29483 return val.coeffs[0] + val.coeffs[1] * 15;
29484 }
29485
29486 /* Allow sve_width to be a bitmask of different VL, treating the lowest
29487 as likely. This could be made more general if future -mtune options
29488 need it to be. */
29489 if (kind == POLY_VALUE_MAX)
29490 width_source = 1 << floor_log2 (width_source);
29491 else
29492 width_source = least_bit_hwi (width_source);
29493
29494 /* If the core provides width information, use that. */
29495 HOST_WIDE_INT over_128 = width_source - 128;
29496 return val.coeffs[0] + val.coeffs[1] * over_128 / 128;
29497 }
29498
29499
29500 /* Return true for types that could be supported as SIMD return or
29501 argument types. */
29502
29503 static bool
29504 supported_simd_type (tree t)
29505 {
29506 if (SCALAR_FLOAT_TYPE_P (t) || INTEGRAL_TYPE_P (t) || POINTER_TYPE_P (t))
29507 {
29508 HOST_WIDE_INT s = tree_to_shwi (TYPE_SIZE_UNIT (t));
29509 return s == 1 || s == 2 || s == 4 || s == 8;
29510 }
29511 return false;
29512 }
29513
29514 /* Determine the lane size for the clone argument/return type. This follows
29515 the LS(P) rule in the VFABIA64. */
29516
29517 static unsigned
29518 lane_size (cgraph_simd_clone_arg_type clone_arg_type, tree type)
29519 {
29520 gcc_assert (clone_arg_type != SIMD_CLONE_ARG_TYPE_MASK);
29521
29522 /* For non map-to-vector types that are pointers we use the element type it
29523 points to. */
29524 if (POINTER_TYPE_P (type))
29525 switch (clone_arg_type)
29526 {
29527 default:
29528 break;
29529 case SIMD_CLONE_ARG_TYPE_UNIFORM:
29530 case SIMD_CLONE_ARG_TYPE_LINEAR_CONSTANT_STEP:
29531 case SIMD_CLONE_ARG_TYPE_LINEAR_VARIABLE_STEP:
29532 type = TREE_TYPE (type);
29533 break;
29534 }
29535
29536 /* For types (or pointers of non map-to-vector types point to) that are
29537 integers or floating point, we use their size if they are 1, 2, 4 or 8.
29538 */
29539 if (INTEGRAL_TYPE_P (type)
29540 || SCALAR_FLOAT_TYPE_P (type))
29541 switch (TYPE_PRECISION (type) / BITS_PER_UNIT)
29542 {
29543 default:
29544 break;
29545 case 1:
29546 case 2:
29547 case 4:
29548 case 8:
29549 return TYPE_PRECISION (type);
29550 }
29551 /* For any other we use the size of uintptr_t. For map-to-vector types that
29552 are pointers, using the size of uintptr_t is the same as using the size of
29553 their type, seeing all pointers are the same size as uintptr_t. */
29554 return POINTER_SIZE;
29555 }
29556
29557
29558 /* Implement TARGET_SIMD_CLONE_COMPUTE_VECSIZE_AND_SIMDLEN. */
29559
29560 static int
29561 aarch64_simd_clone_compute_vecsize_and_simdlen (struct cgraph_node *node,
29562 struct cgraph_simd_clone *clonei,
29563 tree base_type ATTRIBUTE_UNUSED,
29564 int num, bool explicit_p)
29565 {
29566 tree t, ret_type;
29567 unsigned int nds_elt_bits, wds_elt_bits;
29568 unsigned HOST_WIDE_INT const_simdlen;
29569
29570 if (!TARGET_SIMD)
29571 return 0;
29572
29573 /* For now, SVE simdclones won't produce illegal simdlen, So only check
29574 const simdlens here. */
29575 if (maybe_ne (clonei->simdlen, 0U)
29576 && clonei->simdlen.is_constant (&const_simdlen)
29577 && (const_simdlen < 2
29578 || const_simdlen > 1024
29579 || (const_simdlen & (const_simdlen - 1)) != 0))
29580 {
29581 if (explicit_p)
29582 warning_at (DECL_SOURCE_LOCATION (node->decl), 0,
29583 "unsupported simdlen %wd", const_simdlen);
29584 return 0;
29585 }
29586
29587 ret_type = TREE_TYPE (TREE_TYPE (node->decl));
29588 /* According to AArch64's Vector ABI the type that determines the simdlen is
29589 the narrowest of types, so we ignore base_type for AArch64. */
29590 if (TREE_CODE (ret_type) != VOID_TYPE
29591 && !supported_simd_type (ret_type))
29592 {
29593 if (!explicit_p)
29594 ;
29595 else if (COMPLEX_FLOAT_TYPE_P (ret_type))
29596 warning_at (DECL_SOURCE_LOCATION (node->decl), 0,
29597 "GCC does not currently support return type %qT "
29598 "for simd", ret_type);
29599 else
29600 warning_at (DECL_SOURCE_LOCATION (node->decl), 0,
29601 "unsupported return type %qT for simd",
29602 ret_type);
29603 return 0;
29604 }
29605
29606 auto_vec<std::pair <tree, unsigned int>> vec_elts (clonei->nargs + 1);
29607
29608 /* We are looking for the NDS type here according to the VFABIA64. */
29609 if (TREE_CODE (ret_type) != VOID_TYPE)
29610 {
29611 nds_elt_bits = lane_size (SIMD_CLONE_ARG_TYPE_VECTOR, ret_type);
29612 wds_elt_bits = nds_elt_bits;
29613 vec_elts.safe_push (std::make_pair (ret_type, nds_elt_bits));
29614 }
29615 else
29616 {
29617 nds_elt_bits = POINTER_SIZE;
29618 wds_elt_bits = 0;
29619 }
29620
29621 int i;
29622 tree type_arg_types = TYPE_ARG_TYPES (TREE_TYPE (node->decl));
29623 bool decl_arg_p = (node->definition || type_arg_types == NULL_TREE);
29624 for (t = (decl_arg_p ? DECL_ARGUMENTS (node->decl) : type_arg_types), i = 0;
29625 t && t != void_list_node; t = TREE_CHAIN (t), i++)
29626 {
29627 tree type = decl_arg_p ? TREE_TYPE (t) : TREE_VALUE (t);
29628 if (clonei->args[i].arg_type != SIMD_CLONE_ARG_TYPE_UNIFORM
29629 && !supported_simd_type (type))
29630 {
29631 if (!explicit_p)
29632 ;
29633 else if (COMPLEX_FLOAT_TYPE_P (type))
29634 warning_at (DECL_SOURCE_LOCATION (node->decl), 0,
29635 "GCC does not currently support argument type %qT "
29636 "for simd", type);
29637 else
29638 warning_at (DECL_SOURCE_LOCATION (node->decl), 0,
29639 "unsupported argument type %qT for simd",
29640 type);
29641 return 0;
29642 }
29643 unsigned lane_bits = lane_size (clonei->args[i].arg_type, type);
29644 if (clonei->args[i].arg_type == SIMD_CLONE_ARG_TYPE_VECTOR)
29645 vec_elts.safe_push (std::make_pair (type, lane_bits));
29646 if (nds_elt_bits > lane_bits)
29647 nds_elt_bits = lane_bits;
29648 if (wds_elt_bits < lane_bits)
29649 wds_elt_bits = lane_bits;
29650 }
29651
29652 /* If we could not determine the WDS type from available parameters/return,
29653 then fallback to using uintptr_t. */
29654 if (wds_elt_bits == 0)
29655 wds_elt_bits = POINTER_SIZE;
29656
29657 clonei->mask_mode = VOIDmode;
29658 poly_uint64 simdlen;
29659 typedef struct
29660 {
29661 poly_uint64 len;
29662 char mangle;
29663 } aarch64_clone_info;
29664 auto_vec<aarch64_clone_info, 3> clones;
29665
29666 /* Keep track of the possible simdlens the clones of this function can have,
29667 and check them later to see if we support them. */
29668 if (known_eq (clonei->simdlen, 0U))
29669 {
29670 simdlen = exact_div (poly_uint64 (64), nds_elt_bits);
29671 if (maybe_ne (simdlen, 1U))
29672 clones.safe_push ({simdlen, 'n'});
29673 clones.safe_push ({simdlen * 2, 'n'});
29674 /* Only create an SVE simd clone if we aren't dealing with an unprototyped
29675 function.
29676 We have also disabled support for creating SVE simdclones for functions
29677 with function bodies and any simdclones when -msve-vector-bits is used.
29678 TODO: add support for these. */
29679 if (prototype_p (TREE_TYPE (node->decl))
29680 && !node->definition
29681 && !aarch64_sve_vg.is_constant ())
29682 clones.safe_push ({exact_div (BITS_PER_SVE_VECTOR, wds_elt_bits), 's'});
29683 }
29684 else
29685 clones.safe_push ({clonei->simdlen, 'n'});
29686
29687 clonei->vecsize_int = 0;
29688 clonei->vecsize_float = 0;
29689
29690 /* We currently do not support generating simdclones where vector arguments
29691 do not fit into a single vector register, i.e. vector types that are more
29692 than 128-bits large. This is because of how we currently represent such
29693 types in ACLE, where we use a struct to allow us to pass them as arguments
29694 and return.
29695 Hence why we have to check whether the simdlens available for this
29696 simdclone would cause a vector type to be larger than 128-bits, and reject
29697 such a clone. */
29698 unsigned j = 0;
29699 while (j < clones.length ())
29700 {
29701 bool remove_simdlen = false;
29702 for (auto elt : vec_elts)
29703 if (clones[j].mangle == 'n'
29704 && known_gt (clones[j].len * elt.second, 128U))
29705 {
29706 /* Don't issue a warning for every simdclone when there is no
29707 specific simdlen clause. */
29708 if (explicit_p && maybe_ne (clonei->simdlen, 0U))
29709 warning_at (DECL_SOURCE_LOCATION (node->decl), 0,
29710 "GCC does not currently support simdlen %wd for "
29711 "type %qT",
29712 constant_lower_bound (clones[j].len), elt.first);
29713 remove_simdlen = true;
29714 break;
29715 }
29716 if (remove_simdlen)
29717 clones.ordered_remove (j);
29718 else
29719 j++;
29720 }
29721
29722 int count = clones.length ();
29723 if (count == 0)
29724 {
29725 if (explicit_p && known_eq (clonei->simdlen, 0U))
29726 {
29727 /* Warn the user if we can't generate any simdclone. */
29728 simdlen = exact_div (poly_uint64 (64), nds_elt_bits);
29729 warning_at (DECL_SOURCE_LOCATION (node->decl), 0,
29730 "GCC does not currently support a simdclone with simdlens"
29731 " %wd and %wd for these types.",
29732 constant_lower_bound (simdlen),
29733 constant_lower_bound (simdlen*2));
29734 }
29735 return 0;
29736 }
29737
29738 gcc_assert (num < count);
29739 clonei->simdlen = clones[num].len;
29740 clonei->vecsize_mangle = clones[num].mangle;
29741 /* SVE simdclones always have a Mask, so set inbranch to 1. */
29742 if (clonei->vecsize_mangle == 's')
29743 clonei->inbranch = 1;
29744 return count;
29745 }
29746
29747 /* Helper function to adjust an SVE vector type of an SVE simd clone. Returns
29748 an SVE vector type based on the element type of the vector TYPE, with SIMDLEN
29749 number of elements. If IS_MASK, returns an SVE mask type appropriate for use
29750 with the SVE type it would otherwise return. */
29751
29752 static tree
29753 simd_clone_adjust_sve_vector_type (tree type, bool is_mask, poly_uint64 simdlen)
29754 {
29755 unsigned int num_zr = 0;
29756 unsigned int num_pr = 0;
29757 machine_mode vector_mode;
29758 type = TREE_TYPE (type);
29759 scalar_mode scalar_m = SCALAR_TYPE_MODE (type);
29760 vector_mode = aarch64_sve_data_mode (scalar_m, simdlen).require ();
29761 type = build_vector_type_for_mode (type, vector_mode);
29762 if (is_mask)
29763 {
29764 type = truth_type_for (type);
29765 num_pr = 1;
29766 }
29767 else
29768 num_zr = 1;
29769
29770 /* We create new types here with the SVE type attribute instead of using ACLE
29771 types as we need to support unpacked vectors which aren't available as
29772 ACLE SVE types. */
29773
29774 /* ??? This creates anonymous "SVE type" attributes for all types,
29775 even those that correspond to <arm_sve.h> types. This affects type
29776 compatibility in C/C++, but not in gimple. (Gimple type equivalence
29777 is instead decided by TARGET_COMPATIBLE_VECTOR_TYPES_P.)
29778
29779 Thus a C/C++ definition of the implementation function will have a
29780 different function type from the declaration that this code creates.
29781 However, it doesn't seem worth trying to fix that until we have a
29782 way of handling implementations that operate on unpacked types. */
29783 type = build_distinct_type_copy (type);
29784 aarch64_sve::add_sve_type_attribute (type, num_zr, num_pr, NULL, NULL);
29785 return type;
29786 }
29787
29788 /* Implement TARGET_SIMD_CLONE_ADJUST. */
29789 static void
29790 aarch64_simd_clone_adjust (struct cgraph_node *node)
29791 {
29792 tree t = TREE_TYPE (node->decl);
29793
29794 if (node->simdclone->vecsize_mangle == 's')
29795 {
29796 /* This is additive and has no effect if SVE, or a superset thereof, is
29797 already enabled. */
29798 tree target = build_string (strlen ("+sve") + 1, "+sve");
29799 if (!aarch64_option_valid_attribute_p (node->decl, NULL_TREE, target, 0))
29800 gcc_unreachable ();
29801 push_function_decl (node->decl);
29802 }
29803 else
29804 {
29805 /* Add aarch64_vector_pcs target attribute to SIMD clones so they
29806 use the correct ABI. */
29807 TYPE_ATTRIBUTES (t) = make_attribute ("aarch64_vector_pcs", "default",
29808 TYPE_ATTRIBUTES (t));
29809 }
29810
29811 cgraph_simd_clone *sc = node->simdclone;
29812
29813 for (unsigned i = 0; i < sc->nargs; ++i)
29814 {
29815 bool is_mask = false;
29816 tree type;
29817 switch (sc->args[i].arg_type)
29818 {
29819 case SIMD_CLONE_ARG_TYPE_MASK:
29820 is_mask = true;
29821 gcc_fallthrough ();
29822 case SIMD_CLONE_ARG_TYPE_VECTOR:
29823 case SIMD_CLONE_ARG_TYPE_LINEAR_VAL_CONSTANT_STEP:
29824 case SIMD_CLONE_ARG_TYPE_LINEAR_VAL_VARIABLE_STEP:
29825 type = sc->args[i].vector_type;
29826 gcc_assert (VECTOR_TYPE_P (type));
29827 if (node->simdclone->vecsize_mangle == 's')
29828 type = simd_clone_adjust_sve_vector_type (type, is_mask,
29829 sc->simdlen);
29830 sc->args[i].vector_type = type;
29831 break;
29832 default:
29833 continue;
29834 }
29835 }
29836 if (node->simdclone->vecsize_mangle == 's')
29837 {
29838 tree ret_type = TREE_TYPE (t);
29839 if (VECTOR_TYPE_P (ret_type))
29840 TREE_TYPE (t)
29841 = simd_clone_adjust_sve_vector_type (ret_type, false,
29842 node->simdclone->simdlen);
29843 pop_function_decl ();
29844 }
29845 }
29846
29847 /* Implement TARGET_SIMD_CLONE_USABLE. */
29848
29849 static int
29850 aarch64_simd_clone_usable (struct cgraph_node *node, machine_mode vector_mode)
29851 {
29852 switch (node->simdclone->vecsize_mangle)
29853 {
29854 case 'n':
29855 if (!TARGET_SIMD || aarch64_sve_mode_p (vector_mode))
29856 return -1;
29857 return 0;
29858 case 's':
29859 if (!TARGET_SVE
29860 || !aarch64_sve_mode_p (vector_mode))
29861 return -1;
29862 return 0;
29863 default:
29864 gcc_unreachable ();
29865 }
29866 }
29867
29868 /* Implement TARGET_COMP_TYPE_ATTRIBUTES */
29869
29870 static int
29871 aarch64_comp_type_attributes (const_tree type1, const_tree type2)
29872 {
29873 auto check_attr = [&](const char *ns, const char *name) {
29874 tree attr1 = lookup_attribute (ns, name, TYPE_ATTRIBUTES (type1));
29875 tree attr2 = lookup_attribute (ns, name, TYPE_ATTRIBUTES (type2));
29876 if (!attr1 && !attr2)
29877 return true;
29878
29879 return attr1 && attr2 && attribute_value_equal (attr1, attr2);
29880 };
29881
29882 if (!check_attr ("gnu", "aarch64_vector_pcs"))
29883 return 0;
29884 if (!check_attr ("gnu", "indirect_return"))
29885 return 0;
29886 if (!check_attr ("gnu", "Advanced SIMD type"))
29887 return 0;
29888 if (!check_attr ("gnu", "SVE type"))
29889 return 0;
29890 if (!check_attr ("gnu", "SVE sizeless type"))
29891 return 0;
29892 if (!check_attr ("arm", "streaming"))
29893 return 0;
29894 if (!check_attr ("arm", "streaming_compatible"))
29895 return 0;
29896 if (aarch64_lookup_shared_state_flags (TYPE_ATTRIBUTES (type1), "za")
29897 != aarch64_lookup_shared_state_flags (TYPE_ATTRIBUTES (type2), "za"))
29898 return 0;
29899 if (aarch64_lookup_shared_state_flags (TYPE_ATTRIBUTES (type1), "zt0")
29900 != aarch64_lookup_shared_state_flags (TYPE_ATTRIBUTES (type2), "zt0"))
29901 return 0;
29902 return 1;
29903 }
29904
29905 /* Implement TARGET_MERGE_DECL_ATTRIBUTES. */
29906
29907 static tree
29908 aarch64_merge_decl_attributes (tree olddecl, tree newdecl)
29909 {
29910 tree old_attrs = DECL_ATTRIBUTES (olddecl);
29911 tree old_new = lookup_attribute ("arm", "new", old_attrs);
29912
29913 tree new_attrs = DECL_ATTRIBUTES (newdecl);
29914 tree new_new = lookup_attribute ("arm", "new", new_attrs);
29915
29916 if (DECL_INITIAL (olddecl) && new_new)
29917 {
29918 error ("cannot apply attribute %qs to %q+D after the function"
29919 " has been defined", "new", newdecl);
29920 inform (DECL_SOURCE_LOCATION (olddecl), "%q+D defined here",
29921 newdecl);
29922 }
29923 else
29924 {
29925 if (old_new && new_new)
29926 {
29927 old_attrs = remove_attribute ("arm", "new", old_attrs);
29928 TREE_VALUE (new_new) = chainon (TREE_VALUE (new_new),
29929 TREE_VALUE (old_new));
29930 }
29931 if (new_new)
29932 aarch64_check_arm_new_against_type (TREE_VALUE (new_new), newdecl);
29933 }
29934
29935 return merge_attributes (old_attrs, new_attrs);
29936 }
29937
29938 /* Implement TARGET_GET_MULTILIB_ABI_NAME */
29939
29940 static const char *
29941 aarch64_get_multilib_abi_name (void)
29942 {
29943 if (TARGET_BIG_END)
29944 return TARGET_ILP32 ? "aarch64_be_ilp32" : "aarch64_be";
29945 return TARGET_ILP32 ? "aarch64_ilp32" : "aarch64";
29946 }
29947
29948 /* Implement TARGET_STACK_PROTECT_GUARD. In case of a
29949 global variable based guard use the default else
29950 return a null tree. */
29951 static tree
29952 aarch64_stack_protect_guard (void)
29953 {
29954 if (aarch64_stack_protector_guard == SSP_GLOBAL)
29955 return default_stack_protect_guard ();
29956
29957 return NULL_TREE;
29958 }
29959
29960 /* Implement TARGET_INVALID_UNARY_OP. */
29961
29962 static const char *
29963 aarch64_invalid_unary_op (int op, const_tree type)
29964 {
29965 /* Reject all single-operand operations on __mfp8 except for &. */
29966 if (TYPE_MAIN_VARIANT (type) == aarch64_mfp8_type_node && op != ADDR_EXPR)
29967 return N_ ("operation not permitted on type %<mfloat8_t%>");
29968
29969 /* Operation allowed. */
29970 return NULL;
29971 }
29972
29973 /* Implement TARGET_INVALID_BINARY_OP. */
29974
29975 static const char *
29976 aarch64_invalid_binary_op (int op ATTRIBUTE_UNUSED, const_tree type1,
29977 const_tree type2)
29978 {
29979 if (VECTOR_TYPE_P (type1)
29980 && VECTOR_TYPE_P (type2)
29981 && !TYPE_INDIVISIBLE_P (type1)
29982 && !TYPE_INDIVISIBLE_P (type2)
29983 && (aarch64_sve::builtin_type_p (type1)
29984 != aarch64_sve::builtin_type_p (type2)))
29985 return N_("cannot combine GNU and SVE vectors in a binary operation");
29986
29987 /* Reject all 2-operand operations on __mfp8. */
29988 if (TYPE_MAIN_VARIANT (type1) == aarch64_mfp8_type_node
29989 || TYPE_MAIN_VARIANT (type2) == aarch64_mfp8_type_node)
29990 return N_ ("operation not permitted on type %<mfloat8_t%>");
29991
29992 /* Operation allowed. */
29993 return NULL;
29994 }
29995
29996 /* Implement TARGET_MEMTAG_CAN_TAG_ADDRESSES. Here we tell the rest of the
29997 compiler that we automatically ignore the top byte of our pointers, which
29998 allows using -fsanitize=hwaddress. */
29999 bool
30000 aarch64_can_tag_addresses ()
30001 {
30002 return !TARGET_ILP32;
30003 }
30004
30005 /* Implement TARGET_ASM_FILE_END for AArch64. This adds the AArch64 GNU NOTE
30006 section at the end if needed. */
30007 #define GNU_PROPERTY_AARCH64_FEATURE_1_AND 0xc0000000
30008 #define GNU_PROPERTY_AARCH64_FEATURE_1_BTI (1U << 0)
30009 #define GNU_PROPERTY_AARCH64_FEATURE_1_PAC (1U << 1)
30010 #define GNU_PROPERTY_AARCH64_FEATURE_1_GCS (1U << 2)
30011 void
30012 aarch64_file_end_indicate_exec_stack ()
30013 {
30014 file_end_indicate_exec_stack ();
30015
30016 unsigned feature_1_and = 0;
30017 if (aarch_bti_enabled ())
30018 feature_1_and |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;
30019
30020 if (aarch_ra_sign_scope != AARCH_FUNCTION_NONE)
30021 feature_1_and |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;
30022
30023 if (aarch64_gcs_enabled ())
30024 feature_1_and |= GNU_PROPERTY_AARCH64_FEATURE_1_GCS;
30025
30026 if (feature_1_and)
30027 {
30028 /* Generate .note.gnu.property section. */
30029 switch_to_section (get_section (".note.gnu.property",
30030 SECTION_NOTYPE, NULL));
30031
30032 /* PT_NOTE header: namesz, descsz, type.
30033 namesz = 4 ("GNU\0")
30034 descsz = 16 (Size of the program property array)
30035 [(12 + padding) * Number of array elements]
30036 type = 5 (NT_GNU_PROPERTY_TYPE_0). */
30037 assemble_align (POINTER_SIZE);
30038 assemble_integer (GEN_INT (4), 4, 32, 1);
30039 assemble_integer (GEN_INT (ROUND_UP (12, POINTER_BYTES)), 4, 32, 1);
30040 assemble_integer (GEN_INT (5), 4, 32, 1);
30041
30042 /* PT_NOTE name. */
30043 assemble_string ("GNU", 4);
30044
30045 /* PT_NOTE contents for NT_GNU_PROPERTY_TYPE_0:
30046 type = GNU_PROPERTY_AARCH64_FEATURE_1_AND
30047 datasz = 4
30048 data = feature_1_and. */
30049 assemble_integer (GEN_INT (GNU_PROPERTY_AARCH64_FEATURE_1_AND), 4, 32, 1);
30050 assemble_integer (GEN_INT (4), 4, 32, 1);
30051 assemble_integer (GEN_INT (feature_1_and), 4, 32, 1);
30052
30053 /* Pad the size of the note to the required alignment. */
30054 assemble_align (POINTER_SIZE);
30055 }
30056 }
30057 #undef GNU_PROPERTY_AARCH64_FEATURE_1_GCS
30058 #undef GNU_PROPERTY_AARCH64_FEATURE_1_PAC
30059 #undef GNU_PROPERTY_AARCH64_FEATURE_1_BTI
30060 #undef GNU_PROPERTY_AARCH64_FEATURE_1_AND
30061
30062 /* Helper function for straight line speculation.
30063 Return what barrier should be emitted for straight line speculation
30064 mitigation.
30065 When not mitigating against straight line speculation this function returns
30066 an empty string.
30067 When mitigating against straight line speculation, use:
30068 * SB when the v8.5-A SB extension is enabled.
30069 * DSB+ISB otherwise. */
30070 const char *
30071 aarch64_sls_barrier (int mitigation_required)
30072 {
30073 return mitigation_required
30074 ? (TARGET_SB ? "sb" : "dsb\tsy\n\tisb")
30075 : "";
30076 }
30077
30078 static GTY (()) tree aarch64_sls_shared_thunks[30];
30079 static GTY (()) bool aarch64_sls_shared_thunks_needed = false;
30080 const char *indirect_symbol_names[30] = {
30081 "__call_indirect_x0",
30082 "__call_indirect_x1",
30083 "__call_indirect_x2",
30084 "__call_indirect_x3",
30085 "__call_indirect_x4",
30086 "__call_indirect_x5",
30087 "__call_indirect_x6",
30088 "__call_indirect_x7",
30089 "__call_indirect_x8",
30090 "__call_indirect_x9",
30091 "__call_indirect_x10",
30092 "__call_indirect_x11",
30093 "__call_indirect_x12",
30094 "__call_indirect_x13",
30095 "__call_indirect_x14",
30096 "__call_indirect_x15",
30097 "", /* "__call_indirect_x16", */
30098 "", /* "__call_indirect_x17", */
30099 "__call_indirect_x18",
30100 "__call_indirect_x19",
30101 "__call_indirect_x20",
30102 "__call_indirect_x21",
30103 "__call_indirect_x22",
30104 "__call_indirect_x23",
30105 "__call_indirect_x24",
30106 "__call_indirect_x25",
30107 "__call_indirect_x26",
30108 "__call_indirect_x27",
30109 "__call_indirect_x28",
30110 "__call_indirect_x29",
30111 };
30112
30113 /* Function to create a BLR thunk. This thunk is used to mitigate straight
30114 line speculation. Instead of a simple BLR that can be speculated past,
30115 we emit a BL to this thunk, and this thunk contains a BR to the relevant
30116 register. These thunks have the relevant speculation barries put after
30117 their indirect branch so that speculation is blocked.
30118
30119 We use such a thunk so the speculation barriers are kept off the
30120 architecturally executed path in order to reduce the performance overhead.
30121
30122 When optimizing for size we use stubs shared by the linked object.
30123 When optimizing for performance we emit stubs for each function in the hope
30124 that the branch predictor can better train on jumps specific for a given
30125 function. */
30126 rtx
30127 aarch64_sls_create_blr_label (int regnum)
30128 {
30129 gcc_assert (STUB_REGNUM_P (regnum));
30130 if (optimize_function_for_size_p (cfun))
30131 {
30132 /* For the thunks shared between different functions in this compilation
30133 unit we use a named symbol -- this is just for users to more easily
30134 understand the generated assembly. */
30135 aarch64_sls_shared_thunks_needed = true;
30136 const char *thunk_name = indirect_symbol_names[regnum];
30137 if (aarch64_sls_shared_thunks[regnum] == NULL)
30138 {
30139 /* Build a decl representing this function stub and record it for
30140 later. We build a decl here so we can use the GCC machinery for
30141 handling sections automatically (through `get_named_section` and
30142 `make_decl_one_only`). That saves us a lot of trouble handling
30143 the specifics of different output file formats. */
30144 tree decl = build_decl (BUILTINS_LOCATION, FUNCTION_DECL,
30145 get_identifier (thunk_name),
30146 build_function_type_list (void_type_node,
30147 NULL_TREE));
30148 DECL_RESULT (decl) = build_decl (BUILTINS_LOCATION, RESULT_DECL,
30149 NULL_TREE, void_type_node);
30150 TREE_PUBLIC (decl) = 1;
30151 TREE_STATIC (decl) = 1;
30152 DECL_IGNORED_P (decl) = 1;
30153 DECL_ARTIFICIAL (decl) = 1;
30154 make_decl_one_only (decl, DECL_ASSEMBLER_NAME (decl));
30155 resolve_unique_section (decl, 0, false);
30156 aarch64_sls_shared_thunks[regnum] = decl;
30157 }
30158
30159 return gen_rtx_SYMBOL_REF (Pmode, thunk_name);
30160 }
30161
30162 if (cfun->machine->call_via[regnum] == NULL)
30163 cfun->machine->call_via[regnum]
30164 = gen_rtx_LABEL_REF (Pmode, gen_label_rtx ());
30165 return cfun->machine->call_via[regnum];
30166 }
30167
30168 /* Helper function for aarch64_sls_emit_blr_function_thunks and
30169 aarch64_sls_emit_shared_blr_thunks below. */
30170 static void
30171 aarch64_sls_emit_function_stub (FILE *out_file, int regnum)
30172 {
30173 /* Save in x16 and branch to that function so this transformation does
30174 not prevent jumping to `BTI c` instructions. */
30175 asm_fprintf (out_file, "\tmov\tx16, x%d\n", regnum);
30176 asm_fprintf (out_file, "\tbr\tx16\n");
30177 }
30178
30179 /* Emit all BLR stubs for this particular function.
30180 Here we emit all the BLR stubs needed for the current function. Since we
30181 emit these stubs in a consecutive block we know there will be no speculation
30182 gadgets between each stub, and hence we only emit a speculation barrier at
30183 the end of the stub sequences.
30184
30185 This is called in the TARGET_ASM_FUNCTION_EPILOGUE hook. */
30186 void
30187 aarch64_sls_emit_blr_function_thunks (FILE *out_file)
30188 {
30189 if (! aarch64_harden_sls_blr_p ())
30190 return;
30191
30192 bool any_functions_emitted = false;
30193 /* We must save and restore the current function section since this assembly
30194 is emitted at the end of the function. This means it can be emitted *just
30195 after* the cold section of a function. That cold part would be emitted in
30196 a different section. That switch would trigger a `.cfi_endproc` directive
30197 to be emitted in the original section and a `.cfi_startproc` directive to
30198 be emitted in the new section. Switching to the original section without
30199 restoring would mean that the `.cfi_endproc` emitted as a function ends
30200 would happen in a different section -- leaving an unmatched
30201 `.cfi_startproc` in the cold text section and an unmatched `.cfi_endproc`
30202 in the standard text section. */
30203 section *save_text_section = in_section;
30204 switch_to_section (function_section (current_function_decl));
30205 for (int regnum = 0; regnum < 30; ++regnum)
30206 {
30207 rtx specu_label = cfun->machine->call_via[regnum];
30208 if (specu_label == NULL)
30209 continue;
30210
30211 targetm.asm_out.print_operand (out_file, specu_label, 0);
30212 asm_fprintf (out_file, ":\n");
30213 aarch64_sls_emit_function_stub (out_file, regnum);
30214 any_functions_emitted = true;
30215 }
30216 if (any_functions_emitted)
30217 /* Can use the SB if needs be here, since this stub will only be used
30218 by the current function, and hence for the current target. */
30219 asm_fprintf (out_file, "\t%s\n", aarch64_sls_barrier (true));
30220 switch_to_section (save_text_section);
30221 }
30222
30223 /* Emit shared BLR stubs for the current compilation unit.
30224 Over the course of compiling this unit we may have converted some BLR
30225 instructions to a BL to a shared stub function. This is where we emit those
30226 stub functions.
30227 This function is for the stubs shared between different functions in this
30228 compilation unit. We share when optimizing for size instead of speed.
30229
30230 This function is called through the TARGET_ASM_FILE_END hook. */
30231 void
30232 aarch64_sls_emit_shared_blr_thunks (FILE *out_file)
30233 {
30234 if (! aarch64_sls_shared_thunks_needed)
30235 return;
30236
30237 for (int regnum = 0; regnum < 30; ++regnum)
30238 {
30239 tree decl = aarch64_sls_shared_thunks[regnum];
30240 if (!decl)
30241 continue;
30242
30243 const char *name = indirect_symbol_names[regnum];
30244 switch_to_section (get_named_section (decl, NULL, 0));
30245 ASM_OUTPUT_ALIGN (out_file, 2);
30246 targetm.asm_out.globalize_label (out_file, name);
30247 /* Only emits if the compiler is configured for an assembler that can
30248 handle visibility directives. */
30249 targetm.asm_out.assemble_visibility (decl, VISIBILITY_HIDDEN);
30250 ASM_OUTPUT_TYPE_DIRECTIVE (out_file, name, "function");
30251 ASM_OUTPUT_LABEL (out_file, name);
30252 aarch64_sls_emit_function_stub (out_file, regnum);
30253 /* Use the most conservative target to ensure it can always be used by any
30254 function in the translation unit. */
30255 asm_fprintf (out_file, "\tdsb\tsy\n\tisb\n");
30256 ASM_DECLARE_FUNCTION_SIZE (out_file, name, decl);
30257 }
30258 }
30259
30260 /* Implement TARGET_ASM_FILE_END. */
30261 void
30262 aarch64_asm_file_end ()
30263 {
30264 aarch64_sls_emit_shared_blr_thunks (asm_out_file);
30265 /* Since this function will be called for the ASM_FILE_END hook, we ensure
30266 that what would be called otherwise (e.g. `file_end_indicate_exec_stack`
30267 for FreeBSD) still gets called. */
30268 #ifdef TARGET_ASM_FILE_END
30269 TARGET_ASM_FILE_END ();
30270 #endif
30271 }
30272
30273 const char *
30274 aarch64_indirect_call_asm (rtx addr)
30275 {
30276 gcc_assert (REG_P (addr));
30277 if (aarch64_harden_sls_blr_p ())
30278 {
30279 rtx stub_label = aarch64_sls_create_blr_label (REGNO (addr));
30280 output_asm_insn ("bl\t%0", &stub_label);
30281 }
30282 else
30283 output_asm_insn ("blr\t%0", &addr);
30284 return "";
30285 }
30286
30287 /* Emit the assembly instruction to load the thread pointer into DEST.
30288 Select between different tpidr_elN registers depending on -mtp= setting. */
30289
30290 const char *
30291 aarch64_output_load_tp (rtx dest)
30292 {
30293 const char *tpidrs[] = {"tpidr_el0", "tpidr_el1", "tpidr_el2",
30294 "tpidr_el3", "tpidrro_el0"};
30295 char buffer[64];
30296 snprintf (buffer, sizeof (buffer), "mrs\t%%0, %s",
30297 tpidrs[aarch64_tpidr_register]);
30298 output_asm_insn (buffer, &dest);
30299 return "";
30300 }
30301
30302 /* Set up the value of REG_ALLOC_ORDER from scratch.
30303
30304 It was previously good practice to put call-clobbered registers ahead
30305 of call-preserved registers, but that isn't necessary these days.
30306 IRA's model of register save/restore costs is much more sophisticated
30307 than the model that a simple ordering could provide. We leave
30308 HONOR_REG_ALLOC_ORDER undefined so that we can get the full benefit
30309 of IRA's model.
30310
30311 However, it is still useful to list registers that are members of
30312 multiple classes after registers that are members of fewer classes.
30313 For example, we have:
30314
30315 - FP_LO8_REGS: v0-v7
30316 - FP_LO_REGS: v0-v15
30317 - FP_REGS: v0-v31
30318
30319 If, as a tie-breaker, we allocate FP_REGS in the order v0-v31,
30320 we run the risk of starving other (lower-priority) pseudos that
30321 require FP_LO8_REGS or FP_LO_REGS. Allocating FP_LO_REGS in the
30322 order v0-v15 could similarly starve pseudos that require FP_LO8_REGS.
30323 Allocating downwards rather than upwards avoids this problem, at least
30324 in code that has reasonable register pressure.
30325
30326 The situation for predicate registers is similar. */
30327
30328 void
30329 aarch64_adjust_reg_alloc_order ()
30330 {
30331 for (int i = 0; i < FIRST_PSEUDO_REGISTER; ++i)
30332 if (IN_RANGE (i, V0_REGNUM, V31_REGNUM))
30333 reg_alloc_order[i] = V31_REGNUM - (i - V0_REGNUM);
30334 else if (IN_RANGE (i, P0_REGNUM, P15_REGNUM))
30335 reg_alloc_order[i] = P15_REGNUM - (i - P0_REGNUM);
30336 else
30337 reg_alloc_order[i] = i;
30338 }
30339
30340 /* Return true if the PARALLEL PAR can be used in a VEC_SELECT expression
30341 of vector mode MODE to select half the elements of that vector.
30342 Allow any combination of indices except duplicates (or out of range of
30343 the mode units). */
30344
30345 bool
30346 aarch64_parallel_select_half_p (machine_mode mode, rtx par)
30347 {
30348 int nunits = XVECLEN (par, 0);
30349 if (!known_eq (GET_MODE_NUNITS (mode), nunits * 2))
30350 return false;
30351 int mode_nunits = nunits * 2;
30352 /* Put all the elements of PAR into a hash_set and use its
30353 uniqueness guarantees to check that we don't try to insert the same
30354 element twice. */
30355 hash_set<rtx> parset;
30356 for (int i = 0; i < nunits; ++i)
30357 {
30358 rtx elt = XVECEXP (par, 0, i);
30359 if (!CONST_INT_P (elt)
30360 || !IN_RANGE (INTVAL (elt), 0, mode_nunits - 1)
30361 || parset.add (elt))
30362 return false;
30363 }
30364 return true;
30365 }
30366
30367 /* Return true if PAR1 and PAR2, two PARALLEL rtxes of CONST_INT values,
30368 contain any common elements. */
30369
30370 bool
30371 aarch64_pars_overlap_p (rtx par1, rtx par2)
30372 {
30373 int len1 = XVECLEN (par1, 0);
30374 int len2 = XVECLEN (par2, 0);
30375 hash_set<rtx> parset;
30376 for (int i = 0; i < len1; ++i)
30377 parset.add (XVECEXP (par1, 0, i));
30378 for (int i = 0; i < len2; ++i)
30379 if (parset.contains (XVECEXP (par2, 0, i)))
30380 return true;
30381 return false;
30382 }
30383
30384 /* Implement OPTIMIZE_MODE_SWITCHING. */
30385
30386 bool
30387 aarch64_optimize_mode_switching (aarch64_mode_entity entity)
30388 {
30389 bool have_sme_state = (aarch64_cfun_incoming_pstate_za () != 0
30390 || (aarch64_cfun_has_new_state ("za")
30391 && df_regs_ever_live_p (ZA_REGNUM))
30392 || (aarch64_cfun_has_new_state ("zt0")
30393 && df_regs_ever_live_p (ZT0_REGNUM)));
30394
30395 if (have_sme_state && nonlocal_goto_handler_labels)
30396 {
30397 static bool reported;
30398 if (!reported)
30399 {
30400 sorry ("non-local gotos in functions with SME state");
30401 reported = true;
30402 }
30403 }
30404
30405 switch (entity)
30406 {
30407 case aarch64_mode_entity::HAVE_ZA_SAVE_BUFFER:
30408 case aarch64_mode_entity::LOCAL_SME_STATE:
30409 return have_sme_state && !nonlocal_goto_handler_labels;
30410 }
30411 gcc_unreachable ();
30412 }
30413
30414 /* Implement TARGET_MODE_EMIT for ZA_SAVE_BUFFER. */
30415
30416 static void
30417 aarch64_mode_emit_za_save_buffer (aarch64_tristate_mode mode,
30418 aarch64_tristate_mode prev_mode)
30419 {
30420 if (mode == aarch64_tristate_mode::YES)
30421 {
30422 gcc_assert (prev_mode == aarch64_tristate_mode::NO);
30423 aarch64_init_tpidr2_block ();
30424 }
30425 else
30426 gcc_unreachable ();
30427 }
30428
30429 /* Implement TARGET_MODE_EMIT for LOCAL_SME_STATE. */
30430
30431 static void
30432 aarch64_mode_emit_local_sme_state (aarch64_local_sme_state mode,
30433 aarch64_local_sme_state prev_mode)
30434 {
30435 /* Back-propagation should ensure that we're always starting from
30436 a known mode. */
30437 gcc_assert (prev_mode != aarch64_local_sme_state::ANY);
30438
30439 if (prev_mode == aarch64_local_sme_state::INACTIVE_CALLER)
30440 {
30441 /* Commit any uncommitted lazy save. This leaves ZA either active
30442 and zero (lazy save case) or off (normal case).
30443
30444 The sequence is:
30445
30446 mrs <temp>, tpidr2_el0
30447 cbz <temp>, no_save
30448 bl __arm_tpidr2_save
30449 msr tpidr2_el0, xzr
30450 zero { za } // Only if ZA is live
30451 zero { zt0 } // Only if ZT0 is live
30452 no_save: */
30453 auto tmp_reg = gen_reg_rtx (DImode);
30454 emit_insn (gen_aarch64_read_tpidr2 (tmp_reg));
30455 auto label = gen_label_rtx ();
30456 rtx branch = aarch64_gen_compare_zero_and_branch (EQ, tmp_reg, label);
30457 auto jump = emit_jump_insn (branch);
30458 JUMP_LABEL (jump) = label;
30459 emit_insn (gen_aarch64_tpidr2_save ());
30460 emit_insn (gen_aarch64_clear_tpidr2 ());
30461 if (mode == aarch64_local_sme_state::ACTIVE_LIVE
30462 || mode == aarch64_local_sme_state::ACTIVE_DEAD)
30463 {
30464 if (aarch64_cfun_has_state ("za"))
30465 emit_insn (gen_aarch64_initial_zero_za ());
30466 if (aarch64_cfun_has_state ("zt0"))
30467 emit_insn (gen_aarch64_sme_zero_zt0 ());
30468 }
30469 emit_label (label);
30470 }
30471
30472 if (mode == aarch64_local_sme_state::ACTIVE_LIVE
30473 || mode == aarch64_local_sme_state::ACTIVE_DEAD)
30474 {
30475 if (prev_mode == aarch64_local_sme_state::INACTIVE_LOCAL)
30476 {
30477 /* Make ZA active after being inactive.
30478
30479 First handle the case in which the lazy save we set up was
30480 committed by a callee. If the function's source-level ZA state
30481 is live then we must conditionally restore it from the lazy
30482 save buffer. Otherwise we can just force PSTATE.ZA to 1. */
30483 if (mode == aarch64_local_sme_state::ACTIVE_LIVE)
30484 emit_insn (gen_aarch64_restore_za (aarch64_get_tpidr2_ptr ()));
30485 else
30486 emit_insn (gen_aarch64_smstart_za ());
30487
30488 /* Now handle the case in which the lazy save was not committed.
30489 In that case, ZA still contains the current function's ZA state,
30490 and we just need to cancel the lazy save. */
30491 emit_insn (gen_aarch64_clear_tpidr2 ());
30492
30493 /* Restore the ZT0 state, if we have some. */
30494 if (aarch64_cfun_has_state ("zt0"))
30495 aarch64_restore_zt0 (true);
30496
30497 return;
30498 }
30499
30500 if (prev_mode == aarch64_local_sme_state::SAVED_LOCAL)
30501 {
30502 /* Retrieve the current function's ZA state from the lazy save
30503 buffer. */
30504 aarch64_restore_za (aarch64_get_tpidr2_ptr ());
30505
30506 /* Restore the ZT0 state, if we have some. */
30507 if (aarch64_cfun_has_state ("zt0"))
30508 aarch64_restore_zt0 (true);
30509 return;
30510 }
30511
30512 if (prev_mode == aarch64_local_sme_state::INACTIVE_CALLER
30513 || prev_mode == aarch64_local_sme_state::OFF)
30514 {
30515 /* INACTIVE_CALLER means that we are enabling ZA for the first
30516 time in this function. The code above means that ZA is either
30517 active and zero (if we committed a lazy save) or off. Handle
30518 the latter case by forcing ZA on.
30519
30520 OFF means that PSTATE.ZA is guaranteed to be 0. We just need
30521 to force it to 1.
30522
30523 Both cases leave ZA zeroed. */
30524 emit_insn (gen_aarch64_smstart_za ());
30525
30526 /* Restore the ZT0 state, if we have some. */
30527 if (prev_mode == aarch64_local_sme_state::OFF
30528 && aarch64_cfun_has_state ("zt0"))
30529 aarch64_restore_zt0 (true);
30530 return;
30531 }
30532
30533 if (prev_mode == aarch64_local_sme_state::ACTIVE_DEAD
30534 || prev_mode == aarch64_local_sme_state::ACTIVE_LIVE)
30535 /* A simple change in liveness, such as in a CFG structure where
30536 ZA is only conditionally defined. No code is needed. */
30537 return;
30538
30539 gcc_unreachable ();
30540 }
30541
30542 if (mode == aarch64_local_sme_state::INACTIVE_LOCAL)
30543 {
30544 if (prev_mode == aarch64_local_sme_state::ACTIVE_LIVE
30545 || prev_mode == aarch64_local_sme_state::ACTIVE_DEAD
30546 || prev_mode == aarch64_local_sme_state::INACTIVE_CALLER)
30547 {
30548 /* Save the ZT0 state, if we have some. */
30549 if (aarch64_cfun_has_state ("zt0"))
30550 aarch64_save_zt0 ();
30551
30552 /* A transition from ACTIVE_LIVE to INACTIVE_LOCAL is the usual
30553 case of setting up a lazy save buffer before a call.
30554 A transition from INACTIVE_CALLER is similar, except that
30555 the contents of ZA are known to be zero.
30556
30557 A transition from ACTIVE_DEAD means that ZA is live at the
30558 point of the transition, but is dead on at least one incoming
30559 edge. (That is, ZA is only conditionally initialized.)
30560 For efficiency, we want to set up a lazy save even for
30561 dead contents, since forcing ZA off would make later code
30562 restore ZA from the lazy save buffer. */
30563 emit_insn (gen_aarch64_write_tpidr2 (aarch64_get_tpidr2_ptr ()));
30564 return;
30565 }
30566
30567 if (prev_mode == aarch64_local_sme_state::SAVED_LOCAL
30568 || prev_mode == aarch64_local_sme_state::OFF)
30569 /* We're simply discarding the information about which inactive
30570 state applies. */
30571 return;
30572
30573 gcc_unreachable ();
30574 }
30575
30576 if (mode == aarch64_local_sme_state::INACTIVE_CALLER
30577 || mode == aarch64_local_sme_state::OFF)
30578 {
30579 /* Save the ZT0 state, if we have some. */
30580 if ((prev_mode == aarch64_local_sme_state::ACTIVE_LIVE
30581 || prev_mode == aarch64_local_sme_state::ACTIVE_DEAD)
30582 && mode == aarch64_local_sme_state::OFF
30583 && aarch64_cfun_has_state ("zt0"))
30584 aarch64_save_zt0 ();
30585
30586 /* The transition to INACTIVE_CALLER is used before returning from
30587 new("za") functions. Any state in ZA belongs to the current
30588 function rather than a caller, but that state is no longer
30589 needed. Clear any pending lazy save and turn ZA off.
30590
30591 The transition to OFF is used before calling a private-ZA function.
30592 We committed any incoming lazy save above, so at this point any
30593 contents in ZA belong to the current function. */
30594 if (prev_mode == aarch64_local_sme_state::INACTIVE_LOCAL)
30595 emit_insn (gen_aarch64_clear_tpidr2 ());
30596
30597 if (prev_mode != aarch64_local_sme_state::OFF
30598 && prev_mode != aarch64_local_sme_state::SAVED_LOCAL)
30599 emit_insn (gen_aarch64_smstop_za ());
30600
30601 return;
30602 }
30603
30604 if (mode == aarch64_local_sme_state::SAVED_LOCAL)
30605 {
30606 /* This is a transition to an exception handler. */
30607 gcc_assert (prev_mode == aarch64_local_sme_state::OFF
30608 || prev_mode == aarch64_local_sme_state::INACTIVE_LOCAL);
30609 return;
30610 }
30611
30612 gcc_unreachable ();
30613 }
30614
30615 /* Implement TARGET_MODE_EMIT. */
30616
30617 static void
30618 aarch64_mode_emit (int entity, int mode, int prev_mode, HARD_REG_SET live)
30619 {
30620 if (mode == prev_mode)
30621 return;
30622
30623 start_sequence ();
30624 switch (aarch64_mode_entity (entity))
30625 {
30626 case aarch64_mode_entity::HAVE_ZA_SAVE_BUFFER:
30627 aarch64_mode_emit_za_save_buffer (aarch64_tristate_mode (mode),
30628 aarch64_tristate_mode (prev_mode));
30629 break;
30630
30631 case aarch64_mode_entity::LOCAL_SME_STATE:
30632 aarch64_mode_emit_local_sme_state (aarch64_local_sme_state (mode),
30633 aarch64_local_sme_state (prev_mode));
30634 break;
30635 }
30636 rtx_insn *seq = get_insns ();
30637 end_sequence ();
30638
30639 /* Get the set of clobbered registers that are currently live. */
30640 HARD_REG_SET clobbers = {};
30641 for (rtx_insn *insn = seq; insn; insn = NEXT_INSN (insn))
30642 {
30643 if (!NONDEBUG_INSN_P (insn))
30644 continue;
30645 vec_rtx_properties properties;
30646 properties.add_insn (insn, false);
30647 for (rtx_obj_reference ref : properties.refs ())
30648 if (ref.is_write () && HARD_REGISTER_NUM_P (ref.regno))
30649 SET_HARD_REG_BIT (clobbers, ref.regno);
30650 }
30651 clobbers &= live;
30652
30653 /* Emit instructions to save clobbered registers to pseudos. Queue
30654 instructions to restore the registers afterwards.
30655
30656 This should only needed in rare situations. */
30657 auto_vec<rtx, 33> after;
30658 for (unsigned int regno = R0_REGNUM; regno < R30_REGNUM; ++regno)
30659 if (TEST_HARD_REG_BIT (clobbers, regno))
30660 {
30661 rtx hard_reg = gen_rtx_REG (DImode, regno);
30662 rtx pseudo_reg = gen_reg_rtx (DImode);
30663 emit_move_insn (pseudo_reg, hard_reg);
30664 after.quick_push (gen_move_insn (hard_reg, pseudo_reg));
30665 }
30666 if (TEST_HARD_REG_BIT (clobbers, CC_REGNUM))
30667 {
30668 rtx pseudo_reg = gen_reg_rtx (DImode);
30669 emit_insn (gen_aarch64_save_nzcv (pseudo_reg));
30670 after.quick_push (gen_aarch64_restore_nzcv (pseudo_reg));
30671 }
30672
30673 /* Emit the transition instructions themselves. */
30674 emit_insn (seq);
30675
30676 /* Restore the clobbered registers. */
30677 for (auto *insn : after)
30678 emit_insn (insn);
30679 }
30680
30681 /* Return true if INSN references the SME state represented by hard register
30682 REGNO. */
30683
30684 static bool
30685 aarch64_insn_references_sme_state_p (rtx_insn *insn, unsigned int regno)
30686 {
30687 df_ref ref;
30688 FOR_EACH_INSN_DEF (ref, insn)
30689 if (!DF_REF_FLAGS_IS_SET (ref, DF_REF_MUST_CLOBBER)
30690 && DF_REF_REGNO (ref) == regno)
30691 return true;
30692 FOR_EACH_INSN_USE (ref, insn)
30693 if (DF_REF_REGNO (ref) == regno)
30694 return true;
30695 return false;
30696 }
30697
30698 /* Implement TARGET_MODE_NEEDED for LOCAL_SME_STATE. */
30699
30700 static aarch64_local_sme_state
30701 aarch64_mode_needed_local_sme_state (rtx_insn *insn, HARD_REG_SET live)
30702 {
30703 if (!CALL_P (insn)
30704 && find_reg_note (insn, REG_EH_REGION, NULL_RTX))
30705 {
30706 static bool reported;
30707 if (!reported)
30708 {
30709 sorry ("catching non-call exceptions in functions with SME state");
30710 reported = true;
30711 }
30712 /* Aim for graceful error recovery by picking the value that is
30713 least likely to generate an ICE. */
30714 return aarch64_local_sme_state::INACTIVE_LOCAL;
30715 }
30716
30717 /* A non-local goto is equivalent to a return. We disallow non-local
30718 receivers in functions with SME state, so we know that the target
30719 expects ZA to be dormant or off. */
30720 if (JUMP_P (insn)
30721 && find_reg_note (insn, REG_NON_LOCAL_GOTO, NULL_RTX))
30722 return aarch64_local_sme_state::INACTIVE_CALLER;
30723
30724 /* start_private_za_call and end_private_za_call bracket a sequence
30725 that calls a private-ZA function. Force ZA to be turned off if the
30726 function doesn't have any live ZA state, otherwise require ZA to be
30727 inactive. */
30728 auto icode = recog_memoized (insn);
30729 if (icode == CODE_FOR_aarch64_start_private_za_call
30730 || icode == CODE_FOR_aarch64_end_private_za_call)
30731 return (TEST_HARD_REG_BIT (live, ZA_REGNUM)
30732 ? aarch64_local_sme_state::INACTIVE_LOCAL
30733 : aarch64_local_sme_state::OFF);
30734
30735 /* Force ZA to contain the current function's ZA state if INSN wants
30736 to access it. Do the same for accesses to ZT0, since ZA and ZT0
30737 are both controlled by PSTATE.ZA. */
30738 if (aarch64_insn_references_sme_state_p (insn, ZA_REGNUM)
30739 || aarch64_insn_references_sme_state_p (insn, ZT0_REGNUM))
30740 return (TEST_HARD_REG_BIT (live, ZA_REGNUM)
30741 ? aarch64_local_sme_state::ACTIVE_LIVE
30742 : aarch64_local_sme_state::ACTIVE_DEAD);
30743
30744 return aarch64_local_sme_state::ANY;
30745 }
30746
30747 /* Implement TARGET_MODE_NEEDED for ZA_SAVE_BUFFER. */
30748
30749 static aarch64_tristate_mode
30750 aarch64_mode_needed_za_save_buffer (rtx_insn *insn, HARD_REG_SET live)
30751 {
30752 /* We need to set up a lazy save buffer no later than the first
30753 transition to INACTIVE_LOCAL (which involves setting up a lazy save). */
30754 if (aarch64_mode_needed_local_sme_state (insn, live)
30755 == aarch64_local_sme_state::INACTIVE_LOCAL)
30756 return aarch64_tristate_mode::YES;
30757
30758 /* Also make sure that the lazy save buffer is set up before the first
30759 insn that throws internally. The exception handler will sometimes
30760 load from it. */
30761 if (find_reg_note (insn, REG_EH_REGION, NULL_RTX))
30762 return aarch64_tristate_mode::YES;
30763
30764 return aarch64_tristate_mode::MAYBE;
30765 }
30766
30767 /* Implement TARGET_MODE_NEEDED. */
30768
30769 static int
30770 aarch64_mode_needed (int entity, rtx_insn *insn, HARD_REG_SET live)
30771 {
30772 switch (aarch64_mode_entity (entity))
30773 {
30774 case aarch64_mode_entity::HAVE_ZA_SAVE_BUFFER:
30775 return int (aarch64_mode_needed_za_save_buffer (insn, live));
30776
30777 case aarch64_mode_entity::LOCAL_SME_STATE:
30778 return int (aarch64_mode_needed_local_sme_state (insn, live));
30779 }
30780 gcc_unreachable ();
30781 }
30782
30783 /* Implement TARGET_MODE_AFTER for LOCAL_SME_STATE. */
30784
30785 static aarch64_local_sme_state
30786 aarch64_mode_after_local_sme_state (aarch64_local_sme_state mode,
30787 HARD_REG_SET live)
30788 {
30789 /* Note places where ZA dies, so that we can try to avoid saving and
30790 restoring state that isn't needed. */
30791 if (mode == aarch64_local_sme_state::ACTIVE_LIVE
30792 && !TEST_HARD_REG_BIT (live, ZA_REGNUM))
30793 return aarch64_local_sme_state::ACTIVE_DEAD;
30794
30795 /* Note where ZA is born, e.g. when moving past an __arm_out("za")
30796 function. */
30797 if (mode == aarch64_local_sme_state::ACTIVE_DEAD
30798 && TEST_HARD_REG_BIT (live, ZA_REGNUM))
30799 return aarch64_local_sme_state::ACTIVE_LIVE;
30800
30801 return mode;
30802 }
30803
30804 /* Implement TARGET_MODE_AFTER. */
30805
30806 static int
30807 aarch64_mode_after (int entity, int mode, rtx_insn *, HARD_REG_SET live)
30808 {
30809 switch (aarch64_mode_entity (entity))
30810 {
30811 case aarch64_mode_entity::HAVE_ZA_SAVE_BUFFER:
30812 return mode;
30813
30814 case aarch64_mode_entity::LOCAL_SME_STATE:
30815 return int (aarch64_mode_after_local_sme_state
30816 (aarch64_local_sme_state (mode), live));
30817 }
30818 gcc_unreachable ();
30819 }
30820
30821 /* Implement TARGET_MODE_CONFLUENCE for LOCAL_SME_STATE. */
30822
30823 static aarch64_local_sme_state
30824 aarch64_local_sme_confluence (aarch64_local_sme_state mode1,
30825 aarch64_local_sme_state mode2)
30826 {
30827 /* Perform a symmetrical check for two values. */
30828 auto is_pair = [&](aarch64_local_sme_state val1,
30829 aarch64_local_sme_state val2)
30830 {
30831 return ((mode1 == val1 && mode2 == val2)
30832 || (mode1 == val2 && mode2 == val1));
30833 };
30834
30835 /* INACTIVE_CALLER means ZA is off or it has dormant contents belonging
30836 to a caller. OFF is one of the options. */
30837 if (is_pair (aarch64_local_sme_state::INACTIVE_CALLER,
30838 aarch64_local_sme_state::OFF))
30839 return aarch64_local_sme_state::INACTIVE_CALLER;
30840
30841 /* Similarly for dormant contents belonging to the current function. */
30842 if (is_pair (aarch64_local_sme_state::INACTIVE_LOCAL,
30843 aarch64_local_sme_state::OFF))
30844 return aarch64_local_sme_state::INACTIVE_LOCAL;
30845
30846 /* Treat a conditionally-initialized value as a fully-initialized value. */
30847 if (is_pair (aarch64_local_sme_state::ACTIVE_LIVE,
30848 aarch64_local_sme_state::ACTIVE_DEAD))
30849 return aarch64_local_sme_state::ACTIVE_LIVE;
30850
30851 return aarch64_local_sme_state::ANY;
30852 }
30853
30854 /* Implement TARGET_MODE_CONFLUENCE. */
30855
30856 static int
30857 aarch64_mode_confluence (int entity, int mode1, int mode2)
30858 {
30859 gcc_assert (mode1 != mode2);
30860 switch (aarch64_mode_entity (entity))
30861 {
30862 case aarch64_mode_entity::HAVE_ZA_SAVE_BUFFER:
30863 return int (aarch64_tristate_mode::MAYBE);
30864
30865 case aarch64_mode_entity::LOCAL_SME_STATE:
30866 return int (aarch64_local_sme_confluence
30867 (aarch64_local_sme_state (mode1),
30868 aarch64_local_sme_state (mode2)));
30869 }
30870 gcc_unreachable ();
30871 }
30872
30873 /* Implement TARGET_MODE_BACKPROP for an entity that either stays
30874 NO throughput, or makes one transition from NO to YES. */
30875
30876 static aarch64_tristate_mode
30877 aarch64_one_shot_backprop (aarch64_tristate_mode mode1,
30878 aarch64_tristate_mode mode2)
30879 {
30880 /* Keep bringing the transition forward until it starts from NO. */
30881 if (mode1 == aarch64_tristate_mode::MAYBE
30882 && mode2 == aarch64_tristate_mode::YES)
30883 return mode2;
30884
30885 return aarch64_tristate_mode::MAYBE;
30886 }
30887
30888 /* Implement TARGET_MODE_BACKPROP for LOCAL_SME_STATE. */
30889
30890 static aarch64_local_sme_state
30891 aarch64_local_sme_backprop (aarch64_local_sme_state mode1,
30892 aarch64_local_sme_state mode2)
30893 {
30894 /* We always need to know what the current state is when transitioning
30895 to a new state. Force any location with indeterminate starting state
30896 to be active. */
30897 if (mode1 == aarch64_local_sme_state::ANY)
30898 switch (mode2)
30899 {
30900 case aarch64_local_sme_state::INACTIVE_CALLER:
30901 case aarch64_local_sme_state::OFF:
30902 case aarch64_local_sme_state::ACTIVE_DEAD:
30903 /* The current function's ZA state is not live. */
30904 return aarch64_local_sme_state::ACTIVE_DEAD;
30905
30906 case aarch64_local_sme_state::INACTIVE_LOCAL:
30907 case aarch64_local_sme_state::ACTIVE_LIVE:
30908 /* The current function's ZA state is live. */
30909 return aarch64_local_sme_state::ACTIVE_LIVE;
30910
30911 case aarch64_local_sme_state::SAVED_LOCAL:
30912 /* This is a transition to an exception handler. Since we don't
30913 support non-call exceptions for SME functions, the source of
30914 the transition must be known. We'll assert later if that's
30915 not the case. */
30916 return aarch64_local_sme_state::ANY;
30917
30918 case aarch64_local_sme_state::ANY:
30919 return aarch64_local_sme_state::ANY;
30920 }
30921
30922 return aarch64_local_sme_state::ANY;
30923 }
30924
30925 /* Implement TARGET_MODE_BACKPROP. */
30926
30927 static int
30928 aarch64_mode_backprop (int entity, int mode1, int mode2)
30929 {
30930 switch (aarch64_mode_entity (entity))
30931 {
30932 case aarch64_mode_entity::HAVE_ZA_SAVE_BUFFER:
30933 return int (aarch64_one_shot_backprop (aarch64_tristate_mode (mode1),
30934 aarch64_tristate_mode (mode2)));
30935
30936 case aarch64_mode_entity::LOCAL_SME_STATE:
30937 return int (aarch64_local_sme_backprop
30938 (aarch64_local_sme_state (mode1),
30939 aarch64_local_sme_state (mode2)));
30940 }
30941 gcc_unreachable ();
30942 }
30943
30944 /* Implement TARGET_MODE_ENTRY. */
30945
30946 static int
30947 aarch64_mode_entry (int entity)
30948 {
30949 switch (aarch64_mode_entity (entity))
30950 {
30951 case aarch64_mode_entity::HAVE_ZA_SAVE_BUFFER:
30952 return int (aarch64_tristate_mode::NO);
30953
30954 case aarch64_mode_entity::LOCAL_SME_STATE:
30955 return int (aarch64_cfun_shared_flags ("za") != 0
30956 ? aarch64_local_sme_state::ACTIVE_LIVE
30957 : aarch64_cfun_incoming_pstate_za () != 0
30958 ? aarch64_local_sme_state::ACTIVE_DEAD
30959 : aarch64_local_sme_state::INACTIVE_CALLER);
30960 }
30961 gcc_unreachable ();
30962 }
30963
30964 /* Implement TARGET_MODE_EXIT. */
30965
30966 static int
30967 aarch64_mode_exit (int entity)
30968 {
30969 switch (aarch64_mode_entity (entity))
30970 {
30971 case aarch64_mode_entity::HAVE_ZA_SAVE_BUFFER:
30972 return int (aarch64_tristate_mode::MAYBE);
30973
30974 case aarch64_mode_entity::LOCAL_SME_STATE:
30975 return int (aarch64_cfun_shared_flags ("za") != 0
30976 ? aarch64_local_sme_state::ACTIVE_LIVE
30977 : aarch64_cfun_incoming_pstate_za () != 0
30978 ? aarch64_local_sme_state::ACTIVE_DEAD
30979 : aarch64_local_sme_state::INACTIVE_CALLER);
30980 }
30981 gcc_unreachable ();
30982 }
30983
30984 /* Implement TARGET_MODE_EH_HANDLER. */
30985
30986 static int
30987 aarch64_mode_eh_handler (int entity)
30988 {
30989 switch (aarch64_mode_entity (entity))
30990 {
30991 case aarch64_mode_entity::HAVE_ZA_SAVE_BUFFER:
30992 /* Require a lazy save buffer to be allocated before the first
30993 insn that can throw. */
30994 return int (aarch64_tristate_mode::YES);
30995
30996 case aarch64_mode_entity::LOCAL_SME_STATE:
30997 return int (aarch64_local_sme_state::SAVED_LOCAL);
30998 }
30999 gcc_unreachable ();
31000 }
31001
31002 /* Implement TARGET_MODE_PRIORITY. */
31003
31004 static int
31005 aarch64_mode_priority (int, int n)
31006 {
31007 return n;
31008 }
31009
31010 /* Implement TARGET_MD_ASM_ADJUST. */
31011
31012 static rtx_insn *
31013 aarch64_md_asm_adjust (vec<rtx> &outputs, vec<rtx> &inputs,
31014 vec<machine_mode> &input_modes,
31015 vec<const char *> &constraints,
31016 vec<rtx> &uses, vec<rtx> &clobbers,
31017 HARD_REG_SET &clobbered_regs, location_t loc)
31018 {
31019 rtx_insn *seq = arm_md_asm_adjust (outputs, inputs, input_modes, constraints,
31020 uses, clobbers, clobbered_regs, loc);
31021
31022 /* "za" in the clobber list of a function with ZA state is defined to
31023 mean that the asm can read from and write to ZA. We can model the
31024 read using a USE, but unfortunately, it's not possible to model the
31025 write directly. Use a separate insn to model the effect.
31026
31027 We must ensure that ZA is active on entry, which is enforced by using
31028 SME_STATE_REGNUM. The asm must ensure that ZA is active on return.
31029
31030 The same thing applies to ZT0. */
31031 if (TARGET_ZA)
31032 for (unsigned int i = clobbers.length (); i-- > 0; )
31033 {
31034 rtx x = clobbers[i];
31035 if (REG_P (x)
31036 && (REGNO (x) == ZA_REGNUM || REGNO (x) == ZT0_REGNUM))
31037 {
31038 auto id = cfun->machine->next_asm_update_za_id++;
31039
31040 start_sequence ();
31041 if (seq)
31042 emit_insn (seq);
31043 rtx id_rtx = gen_int_mode (id, SImode);
31044 emit_insn (REGNO (x) == ZA_REGNUM
31045 ? gen_aarch64_asm_update_za (id_rtx)
31046 : gen_aarch64_asm_update_zt0 (id_rtx));
31047 seq = get_insns ();
31048 end_sequence ();
31049
31050 auto mode = REGNO (x) == ZA_REGNUM ? VNx16QImode : V8DImode;
31051 uses.safe_push (gen_rtx_REG (mode, REGNO (x)));
31052 uses.safe_push (gen_rtx_REG (DImode, SME_STATE_REGNUM));
31053
31054 clobbers.ordered_remove (i);
31055 CLEAR_HARD_REG_BIT (clobbered_regs, REGNO (x));
31056 }
31057 }
31058 return seq;
31059 }
31060
31061 /* BB is the target of an exception or nonlocal goto edge, which means
31062 that PSTATE.SM is known to be 0 on entry. Put it into the state that
31063 the current function requires. */
31064
31065 static bool
31066 aarch64_switch_pstate_sm_for_landing_pad (basic_block bb)
31067 {
31068 if (TARGET_NON_STREAMING)
31069 return false;
31070
31071 start_sequence ();
31072 rtx_insn *guard_label = nullptr;
31073 if (TARGET_STREAMING_COMPATIBLE)
31074 guard_label = aarch64_guard_switch_pstate_sm (IP0_REGNUM,
31075 AARCH64_ISA_MODE_SM_OFF);
31076 aarch64_sme_mode_switch_regs args_switch;
31077 args_switch.add_call_preserved_regs (df_get_live_in (bb));
31078 args_switch.emit_prologue ();
31079 aarch64_switch_pstate_sm (AARCH64_ISA_MODE_SM_OFF, AARCH64_ISA_MODE_SM_ON);
31080 args_switch.emit_epilogue ();
31081 if (guard_label)
31082 emit_label (guard_label);
31083 auto seq = get_insns ();
31084 end_sequence ();
31085
31086 emit_insn_after (seq, bb_note (bb));
31087 return true;
31088 }
31089
31090 /* JUMP is a nonlocal goto. Its target requires PSTATE.SM to be 0 on entry,
31091 so arrange to make it so. */
31092
31093 static bool
31094 aarch64_switch_pstate_sm_for_jump (rtx_insn *jump)
31095 {
31096 if (TARGET_NON_STREAMING)
31097 return false;
31098
31099 start_sequence ();
31100 rtx_insn *guard_label = nullptr;
31101 if (TARGET_STREAMING_COMPATIBLE)
31102 guard_label = aarch64_guard_switch_pstate_sm (IP0_REGNUM,
31103 AARCH64_ISA_MODE_SM_OFF);
31104 aarch64_switch_pstate_sm (AARCH64_ISA_MODE_SM_ON, AARCH64_ISA_MODE_SM_OFF);
31105 if (guard_label)
31106 emit_label (guard_label);
31107 auto seq = get_insns ();
31108 end_sequence ();
31109
31110 emit_insn_before (seq, jump);
31111 return true;
31112 }
31113
31114 /* If CALL involves a change in PSTATE.SM, emit the instructions needed
31115 to switch to the new mode and the instructions needed to restore the
31116 original mode. Return true if something changed. */
31117 static bool
31118 aarch64_switch_pstate_sm_for_call (rtx_call_insn *call)
31119 {
31120 /* Mode switches for sibling calls are handled via the epilogue. */
31121 if (SIBLING_CALL_P (call))
31122 return false;
31123
31124 auto callee_isa_mode = aarch64_insn_callee_isa_mode (call);
31125 if (!aarch64_call_switches_pstate_sm (callee_isa_mode))
31126 return false;
31127
31128 /* Switch mode before the call, preserving any argument registers
31129 across the switch. */
31130 start_sequence ();
31131 rtx_insn *args_guard_label = nullptr;
31132 if (TARGET_STREAMING_COMPATIBLE)
31133 args_guard_label = aarch64_guard_switch_pstate_sm (IP0_REGNUM,
31134 callee_isa_mode);
31135 aarch64_sme_mode_switch_regs args_switch;
31136 args_switch.add_call_args (call);
31137 args_switch.emit_prologue ();
31138 aarch64_switch_pstate_sm (AARCH64_ISA_MODE, callee_isa_mode);
31139 args_switch.emit_epilogue ();
31140 if (args_guard_label)
31141 emit_label (args_guard_label);
31142 auto args_seq = get_insns ();
31143 end_sequence ();
31144 emit_insn_before (args_seq, call);
31145
31146 if (find_reg_note (call, REG_NORETURN, NULL_RTX))
31147 return true;
31148
31149 /* Switch mode after the call, preserving any return registers across
31150 the switch. */
31151 start_sequence ();
31152 rtx_insn *return_guard_label = nullptr;
31153 if (TARGET_STREAMING_COMPATIBLE)
31154 return_guard_label = aarch64_guard_switch_pstate_sm (IP0_REGNUM,
31155 callee_isa_mode);
31156 aarch64_sme_mode_switch_regs return_switch;
31157 return_switch.add_call_result (call);
31158 return_switch.emit_prologue ();
31159 aarch64_switch_pstate_sm (callee_isa_mode, AARCH64_ISA_MODE);
31160 return_switch.emit_epilogue ();
31161 if (return_guard_label)
31162 emit_label (return_guard_label);
31163 auto result_seq = get_insns ();
31164 end_sequence ();
31165 emit_insn_after (result_seq, call);
31166 return true;
31167 }
31168
31169 namespace {
31170
31171 const pass_data pass_data_switch_pstate_sm =
31172 {
31173 RTL_PASS, // type
31174 "smstarts", // name
31175 OPTGROUP_NONE, // optinfo_flags
31176 TV_NONE, // tv_id
31177 0, // properties_required
31178 0, // properties_provided
31179 0, // properties_destroyed
31180 0, // todo_flags_start
31181 TODO_df_finish, // todo_flags_finish
31182 };
31183
31184 class pass_switch_pstate_sm : public rtl_opt_pass
31185 {
31186 public:
31187 pass_switch_pstate_sm (gcc::context *ctxt)
31188 : rtl_opt_pass (pass_data_switch_pstate_sm, ctxt)
31189 {}
31190
31191 // opt_pass methods:
31192 bool gate (function *) override final;
31193 unsigned int execute (function *) override final;
31194 };
31195
31196 bool
31197 pass_switch_pstate_sm::gate (function *fn)
31198 {
31199 return (aarch64_fndecl_pstate_sm (fn->decl) != AARCH64_ISA_MODE_SM_OFF
31200 || cfun->machine->call_switches_pstate_sm);
31201 }
31202
31203 /* Emit any instructions needed to switch PSTATE.SM. */
31204 unsigned int
31205 pass_switch_pstate_sm::execute (function *fn)
31206 {
31207 basic_block bb;
31208
31209 auto_sbitmap blocks (last_basic_block_for_fn (cfun));
31210 bitmap_clear (blocks);
31211 FOR_EACH_BB_FN (bb, fn)
31212 {
31213 if (has_abnormal_call_or_eh_pred_edge_p (bb)
31214 && aarch64_switch_pstate_sm_for_landing_pad (bb))
31215 bitmap_set_bit (blocks, bb->index);
31216
31217 if (cfun->machine->call_switches_pstate_sm)
31218 {
31219 rtx_insn *insn;
31220 FOR_BB_INSNS (bb, insn)
31221 if (auto *call = dyn_cast<rtx_call_insn *> (insn))
31222 if (aarch64_switch_pstate_sm_for_call (call))
31223 bitmap_set_bit (blocks, bb->index);
31224 }
31225
31226 auto end = BB_END (bb);
31227 if (JUMP_P (end)
31228 && find_reg_note (end, REG_NON_LOCAL_GOTO, NULL_RTX)
31229 && aarch64_switch_pstate_sm_for_jump (end))
31230 bitmap_set_bit (blocks, bb->index);
31231 }
31232 find_many_sub_basic_blocks (blocks);
31233 clear_aux_for_blocks ();
31234 return 0;
31235 }
31236
31237 }
31238
31239 rtl_opt_pass *
31240 make_pass_switch_pstate_sm (gcc::context *ctxt)
31241 {
31242 return new pass_switch_pstate_sm (ctxt);
31243 }
31244
31245 /* Parse an implementation-defined system register name of
31246 the form S[0-3]_[0-7]_C[0-15]_C[0-15]_[0-7].
31247 Return true if name matched against above pattern, false
31248 otherwise. */
31249 bool
31250 aarch64_is_implem_def_reg (const char *regname)
31251 {
31252 unsigned pos = 0;
31253 unsigned name_len = strlen (regname);
31254 if (name_len < 12 || name_len > 14)
31255 return false;
31256
31257 auto cterm_valid_p = [&]()
31258 {
31259 bool leading_zero_p = false;
31260 unsigned i = 0;
31261 char n[3] = {0};
31262
31263 if (regname[pos] != 'c')
31264 return false;
31265 pos++;
31266 while (regname[pos] != '_')
31267 {
31268 if (leading_zero_p)
31269 return false;
31270 if (i == 0 && regname[pos] == '0')
31271 leading_zero_p = true;
31272 if (i > 2)
31273 return false;
31274 if (!ISDIGIT (regname[pos]))
31275 return false;
31276 n[i++] = regname[pos++];
31277 }
31278 if (atoi (n) > 15)
31279 return false;
31280 return true;
31281 };
31282
31283 if (regname[pos] != 's')
31284 return false;
31285 pos++;
31286 if (regname[pos] < '0' || regname[pos] > '3')
31287 return false;
31288 pos++;
31289 if (regname[pos++] != '_')
31290 return false;
31291 if (regname[pos] < '0' || regname[pos] > '7')
31292 return false;
31293 pos++;
31294 if (regname[pos++] != '_')
31295 return false;
31296 if (!cterm_valid_p ())
31297 return false;
31298 if (regname[pos++] != '_')
31299 return false;
31300 if (!cterm_valid_p ())
31301 return false;
31302 if (regname[pos++] != '_')
31303 return false;
31304 if (regname[pos] < '0' || regname[pos] > '7')
31305 return false;
31306 return true;
31307 }
31308
31309 /* Return true if REGNAME matches either a known permitted system
31310 register name, or a generic sysreg specification. For use in
31311 back-end predicate `aarch64_sysreg_string'. */
31312 bool
31313 aarch64_valid_sysreg_name_p (const char *regname)
31314 {
31315 const sysreg_t *sysreg = aarch64_lookup_sysreg_map (regname);
31316 if (sysreg == NULL)
31317 return aarch64_is_implem_def_reg (regname);
31318 return true;
31319 }
31320
31321 /* Return the generic sysreg specification for a valid system register
31322 name, otherwise NULL. WRITE_P is true iff the register is being
31323 written to. IS128OP indicates the requested system register should
31324 be checked for a 128-bit implementation. */
31325 const char *
31326 aarch64_retrieve_sysreg (const char *regname, bool write_p, bool is128op)
31327 {
31328 const sysreg_t *sysreg = aarch64_lookup_sysreg_map (regname);
31329 if (sysreg == NULL)
31330 {
31331 if (aarch64_is_implem_def_reg (regname))
31332 return regname;
31333 else
31334 return NULL;
31335 }
31336 if (is128op && !(sysreg->properties & F_REG_128))
31337 return NULL;
31338 if ((write_p && (sysreg->properties & F_REG_READ))
31339 || (!write_p && (sysreg->properties & F_REG_WRITE)))
31340 return NULL;
31341 return sysreg->encoding;
31342 }
31343
31344 /* Report that LOCATION has a call to FNDECL in which argument ARGNO
31345 was not an integer constant expression. ARGNO counts from zero. */
31346 void
31347 aarch64::report_non_ice (location_t location, tree fndecl, unsigned int argno)
31348 {
31349 error_at (location, "argument %d of %qE must be an integer constant"
31350 " expression", argno + 1, fndecl);
31351 }
31352
31353 /* Report that LOCATION has a call to FNDECL in which argument ARGNO has
31354 the value ACTUAL, whereas the function requires a value in the range
31355 [MIN, MAX]. ARGNO counts from zero. */
31356 void
31357 aarch64::report_out_of_range (location_t location, tree fndecl,
31358 unsigned int argno, HOST_WIDE_INT actual,
31359 HOST_WIDE_INT min, HOST_WIDE_INT max)
31360 {
31361 if (min == max)
31362 error_at (location, "passing %wd to argument %d of %qE, which expects"
31363 " the value %wd", actual, argno + 1, fndecl, min);
31364 else
31365 error_at (location, "passing %wd to argument %d of %qE, which expects"
31366 " a value in the range [%wd, %wd]", actual, argno + 1, fndecl,
31367 min, max);
31368 }
31369
31370 /* Report that LOCATION has a call to FNDECL in which argument ARGNO has
31371 the value ACTUAL, whereas the function requires either VALUE0 or
31372 VALUE1. ARGNO counts from zero. */
31373 void
31374 aarch64::report_neither_nor (location_t location, tree fndecl,
31375 unsigned int argno, HOST_WIDE_INT actual,
31376 HOST_WIDE_INT value0, HOST_WIDE_INT value1)
31377 {
31378 error_at (location, "passing %wd to argument %d of %qE, which expects"
31379 " either %wd or %wd", actual, argno + 1, fndecl, value0, value1);
31380 }
31381
31382 /* Report that LOCATION has a call to FNDECL in which argument ARGNO has
31383 the value ACTUAL, whereas the function requires one of VALUE0..3.
31384 ARGNO counts from zero. */
31385 void
31386 aarch64::report_not_one_of (location_t location, tree fndecl,
31387 unsigned int argno, HOST_WIDE_INT actual,
31388 HOST_WIDE_INT value0, HOST_WIDE_INT value1,
31389 HOST_WIDE_INT value2,
31390 HOST_WIDE_INT value3)
31391 {
31392 error_at (location, "passing %wd to argument %d of %qE, which expects"
31393 " %wd, %wd, %wd or %wd", actual, argno + 1, fndecl, value0, value1,
31394 value2, value3);
31395 }
31396
31397 /* Report that LOCATION has a call to FNDECL in which argument ARGNO has
31398 the value ACTUAL, whereas the function requires a valid value of
31399 enum type ENUMTYPE. ARGNO counts from zero. */
31400 void
31401 aarch64::report_not_enum (location_t location, tree fndecl, unsigned int argno,
31402 HOST_WIDE_INT actual, tree enumtype)
31403 {
31404 error_at (location, "passing %wd to argument %d of %qE, which expects"
31405 " a valid %qT value", actual, argno + 1, fndecl, enumtype);
31406 }
31407
31408 /* Generate assembly to calculate CRC
31409 using carry-less multiplication instruction.
31410 OPERANDS[1] is input CRC,
31411 OPERANDS[2] is data (message),
31412 OPERANDS[3] is the polynomial without the leading 1. */
31413
31414 void
31415 aarch64_expand_crc_using_pmull (scalar_mode crc_mode,
31416 scalar_mode data_mode,
31417 rtx *operands)
31418 {
31419 /* Check and keep arguments. */
31420 gcc_assert (!CONST_INT_P (operands[0]));
31421 gcc_assert (CONST_INT_P (operands[3]));
31422 rtx crc = operands[1];
31423 rtx data = operands[2];
31424 rtx polynomial = operands[3];
31425
31426 unsigned HOST_WIDE_INT crc_size = GET_MODE_BITSIZE (crc_mode);
31427 unsigned HOST_WIDE_INT data_size = GET_MODE_BITSIZE (data_mode);
31428 gcc_assert (crc_size <= 32);
31429 gcc_assert (data_size <= crc_size);
31430
31431 /* Calculate the quotient. */
31432 unsigned HOST_WIDE_INT
31433 q = gf2n_poly_long_div_quotient (UINTVAL (polynomial), crc_size);
31434 /* CRC calculation's main part. */
31435 if (crc_size > data_size)
31436 crc = expand_shift (RSHIFT_EXPR, DImode, crc, crc_size - data_size,
31437 NULL_RTX, 1);
31438
31439 rtx t0 = force_reg (DImode, gen_int_mode (q, DImode));
31440 polynomial = simplify_gen_unary (ZERO_EXTEND, DImode, polynomial,
31441 GET_MODE (polynomial));
31442 rtx t1 = force_reg (DImode, polynomial);
31443
31444 rtx a0 = expand_binop (DImode, xor_optab, crc, data, NULL_RTX, 1,
31445 OPTAB_WIDEN);
31446
31447 rtx pmull_res = gen_reg_rtx (TImode);
31448 emit_insn (gen_aarch64_crypto_pmulldi (pmull_res, a0, t0));
31449 a0 = gen_lowpart (DImode, pmull_res);
31450
31451 a0 = expand_shift (RSHIFT_EXPR, DImode, a0, crc_size, NULL_RTX, 1);
31452
31453 emit_insn (gen_aarch64_crypto_pmulldi (pmull_res, a0, t1));
31454 a0 = gen_lowpart (DImode, pmull_res);
31455
31456 if (crc_size > data_size)
31457 {
31458 rtx crc_part = expand_shift (LSHIFT_EXPR, DImode, operands[1], data_size,
31459 NULL_RTX, 0);
31460 a0 = expand_binop (DImode, xor_optab, a0, crc_part, NULL_RTX, 1,
31461 OPTAB_DIRECT);
31462 }
31463
31464 aarch64_emit_move (operands[0], gen_lowpart (crc_mode, a0));
31465 }
31466
31467 /* Generate assembly to calculate reversed CRC
31468 using carry-less multiplication instruction.
31469 OPERANDS[1] is input CRC,
31470 OPERANDS[2] is data,
31471 OPERANDS[3] is the polynomial without the leading 1. */
31472
31473 void
31474 aarch64_expand_reversed_crc_using_pmull (scalar_mode crc_mode,
31475 scalar_mode data_mode,
31476 rtx *operands)
31477 {
31478 /* Check and keep arguments. */
31479 gcc_assert (!CONST_INT_P (operands[0]));
31480 gcc_assert (CONST_INT_P (operands[3]));
31481 rtx crc = operands[1];
31482 rtx data = operands[2];
31483 rtx polynomial = operands[3];
31484
31485 unsigned HOST_WIDE_INT crc_size = GET_MODE_BITSIZE (crc_mode);
31486 unsigned HOST_WIDE_INT data_size = GET_MODE_BITSIZE (data_mode);
31487 gcc_assert (crc_size <= 32);
31488 gcc_assert (data_size <= crc_size);
31489
31490 /* Calculate the quotient. */
31491 unsigned HOST_WIDE_INT
31492 q = gf2n_poly_long_div_quotient (UINTVAL (polynomial), crc_size);
31493 /* Reflect the calculated quotient. */
31494 q = reflect_hwi (q, crc_size + 1);
31495 rtx t0 = force_reg (DImode, gen_int_mode (q, DImode));
31496
31497 /* Reflect the polynomial. */
31498 unsigned HOST_WIDE_INT ref_polynomial = reflect_hwi (UINTVAL (polynomial),
31499 crc_size);
31500 /* An unshifted multiplier would require the final result to be extracted
31501 using a shift right by DATA_SIZE - 1 bits. Shift the multiplier left
31502 so that the shift right can be by CRC_SIZE bits instead. */
31503 ref_polynomial <<= crc_size - data_size + 1;
31504 rtx t1 = force_reg (DImode, gen_int_mode (ref_polynomial, DImode));
31505
31506 /* CRC calculation's main part. */
31507 rtx a0 = expand_binop (DImode, xor_optab, crc, data, NULL_RTX, 1,
31508 OPTAB_WIDEN);
31509
31510 /* Perform carry-less multiplication and get low part. */
31511 rtx pmull_res = gen_reg_rtx (TImode);
31512 emit_insn (gen_aarch64_crypto_pmulldi (pmull_res, a0, t0));
31513 a0 = gen_lowpart (DImode, pmull_res);
31514
31515 a0 = expand_binop (DImode, and_optab, a0,
31516 gen_int_mode (GET_MODE_MASK (data_mode), DImode),
31517 NULL_RTX, 1, OPTAB_WIDEN);
31518
31519 /* Perform carry-less multiplication. */
31520 emit_insn (gen_aarch64_crypto_pmulldi (pmull_res, a0, t1));
31521
31522 /* Perform a shift right by CRC_SIZE as an extraction of lane 1. */
31523 machine_mode crc_vmode = aarch64_v128_mode (crc_mode).require ();
31524 a0 = (crc_size > data_size ? gen_reg_rtx (crc_mode) : operands[0]);
31525 emit_insn (gen_aarch64_get_lane (crc_vmode, a0,
31526 gen_lowpart (crc_vmode, pmull_res),
31527 aarch64_endian_lane_rtx (crc_vmode, 1)));
31528
31529 if (crc_size > data_size)
31530 {
31531 rtx crc_part = expand_shift (RSHIFT_EXPR, crc_mode, crc, data_size,
31532 NULL_RTX, 1);
31533 a0 = expand_binop (crc_mode, xor_optab, a0, crc_part, operands[0], 1,
31534 OPTAB_WIDEN);
31535 aarch64_emit_move (operands[0], a0);
31536 }
31537 }
31538
31539 /* Target-specific selftests. */
31540
31541 #if CHECKING_P
31542
31543 namespace selftest {
31544
31545 /* Selftest for the RTL loader.
31546 Verify that the RTL loader copes with a dump from
31547 print_rtx_function. This is essentially just a test that class
31548 function_reader can handle a real dump, but it also verifies
31549 that lookup_reg_by_dump_name correctly handles hard regs.
31550 The presence of hard reg names in the dump means that the test is
31551 target-specific, hence it is in this file. */
31552
31553 static void
31554 aarch64_test_loading_full_dump ()
31555 {
31556 rtl_dump_test t (SELFTEST_LOCATION, locate_file ("aarch64/times-two.rtl"));
31557
31558 ASSERT_STREQ ("times_two", IDENTIFIER_POINTER (DECL_NAME (cfun->decl)));
31559
31560 rtx_insn *insn_1 = get_insn_by_uid (1);
31561 ASSERT_EQ (NOTE, GET_CODE (insn_1));
31562
31563 rtx_insn *insn_15 = get_insn_by_uid (15);
31564 ASSERT_EQ (INSN, GET_CODE (insn_15));
31565 ASSERT_EQ (USE, GET_CODE (PATTERN (insn_15)));
31566
31567 /* Verify crtl->return_rtx. */
31568 ASSERT_EQ (REG, GET_CODE (crtl->return_rtx));
31569 ASSERT_EQ (0, REGNO (crtl->return_rtx));
31570 ASSERT_EQ (SImode, GET_MODE (crtl->return_rtx));
31571 }
31572
31573 /* Test the fractional_cost class. */
31574
31575 static void
31576 aarch64_test_fractional_cost ()
31577 {
31578 using cf = fractional_cost;
31579
31580 ASSERT_EQ (cf (0, 20), 0);
31581
31582 ASSERT_EQ (cf (4, 2), 2);
31583 ASSERT_EQ (3, cf (9, 3));
31584
31585 ASSERT_NE (cf (5, 2), 2);
31586 ASSERT_NE (3, cf (8, 3));
31587
31588 ASSERT_EQ (cf (7, 11) + cf (15, 11), 2);
31589 ASSERT_EQ (cf (2, 3) + cf (3, 5), cf (19, 15));
31590 ASSERT_EQ (cf (2, 3) + cf (1, 6) + cf (1, 6), 1);
31591
31592 ASSERT_EQ (cf (14, 15) - cf (4, 15), cf (2, 3));
31593 ASSERT_EQ (cf (1, 4) - cf (1, 2), 0);
31594 ASSERT_EQ (cf (3, 5) - cf (1, 10), cf (1, 2));
31595 ASSERT_EQ (cf (11, 3) - 3, cf (2, 3));
31596 ASSERT_EQ (3 - cf (7, 3), cf (2, 3));
31597 ASSERT_EQ (3 - cf (10, 3), 0);
31598
31599 ASSERT_EQ (cf (2, 3) * 5, cf (10, 3));
31600 ASSERT_EQ (14 * cf (11, 21), cf (22, 3));
31601
31602 ASSERT_TRUE (cf (4, 15) <= cf (5, 15));
31603 ASSERT_TRUE (cf (5, 15) <= cf (5, 15));
31604 ASSERT_FALSE (cf (6, 15) <= cf (5, 15));
31605 ASSERT_TRUE (cf (1, 3) <= cf (2, 5));
31606 ASSERT_TRUE (cf (1, 12) <= cf (1, 6));
31607 ASSERT_TRUE (cf (5, 3) <= cf (5, 3));
31608 ASSERT_TRUE (cf (239, 240) <= 1);
31609 ASSERT_TRUE (cf (240, 240) <= 1);
31610 ASSERT_FALSE (cf (241, 240) <= 1);
31611 ASSERT_FALSE (2 <= cf (207, 104));
31612 ASSERT_TRUE (2 <= cf (208, 104));
31613 ASSERT_TRUE (2 <= cf (209, 104));
31614
31615 ASSERT_TRUE (cf (4, 15) < cf (5, 15));
31616 ASSERT_FALSE (cf (5, 15) < cf (5, 15));
31617 ASSERT_FALSE (cf (6, 15) < cf (5, 15));
31618 ASSERT_TRUE (cf (1, 3) < cf (2, 5));
31619 ASSERT_TRUE (cf (1, 12) < cf (1, 6));
31620 ASSERT_FALSE (cf (5, 3) < cf (5, 3));
31621 ASSERT_TRUE (cf (239, 240) < 1);
31622 ASSERT_FALSE (cf (240, 240) < 1);
31623 ASSERT_FALSE (cf (241, 240) < 1);
31624 ASSERT_FALSE (2 < cf (207, 104));
31625 ASSERT_FALSE (2 < cf (208, 104));
31626 ASSERT_TRUE (2 < cf (209, 104));
31627
31628 ASSERT_FALSE (cf (4, 15) >= cf (5, 15));
31629 ASSERT_TRUE (cf (5, 15) >= cf (5, 15));
31630 ASSERT_TRUE (cf (6, 15) >= cf (5, 15));
31631 ASSERT_FALSE (cf (1, 3) >= cf (2, 5));
31632 ASSERT_FALSE (cf (1, 12) >= cf (1, 6));
31633 ASSERT_TRUE (cf (5, 3) >= cf (5, 3));
31634 ASSERT_FALSE (cf (239, 240) >= 1);
31635 ASSERT_TRUE (cf (240, 240) >= 1);
31636 ASSERT_TRUE (cf (241, 240) >= 1);
31637 ASSERT_TRUE (2 >= cf (207, 104));
31638 ASSERT_TRUE (2 >= cf (208, 104));
31639 ASSERT_FALSE (2 >= cf (209, 104));
31640
31641 ASSERT_FALSE (cf (4, 15) > cf (5, 15));
31642 ASSERT_FALSE (cf (5, 15) > cf (5, 15));
31643 ASSERT_TRUE (cf (6, 15) > cf (5, 15));
31644 ASSERT_FALSE (cf (1, 3) > cf (2, 5));
31645 ASSERT_FALSE (cf (1, 12) > cf (1, 6));
31646 ASSERT_FALSE (cf (5, 3) > cf (5, 3));
31647 ASSERT_FALSE (cf (239, 240) > 1);
31648 ASSERT_FALSE (cf (240, 240) > 1);
31649 ASSERT_TRUE (cf (241, 240) > 1);
31650 ASSERT_TRUE (2 > cf (207, 104));
31651 ASSERT_FALSE (2 > cf (208, 104));
31652 ASSERT_FALSE (2 > cf (209, 104));
31653
31654 ASSERT_EQ (cf (1, 2).ceil (), 1);
31655 ASSERT_EQ (cf (11, 7).ceil (), 2);
31656 ASSERT_EQ (cf (20, 1).ceil (), 20);
31657 ASSERT_EQ ((cf (0xfffffffd) + 1).ceil (), 0xfffffffe);
31658 ASSERT_EQ ((cf (0xfffffffd) + 2).ceil (), 0xffffffff);
31659 ASSERT_EQ ((cf (0xfffffffd) + 3).ceil (), 0xffffffff);
31660 ASSERT_EQ ((cf (0x7fffffff) * 2).ceil (), 0xfffffffe);
31661 ASSERT_EQ ((cf (0x80000000) * 2).ceil (), 0xffffffff);
31662
31663 ASSERT_EQ (cf (1, 2).as_double (), 0.5);
31664 }
31665
31666 /* Calculate whether our system register data, as imported from
31667 `aarch64-sys-reg.def' has any duplicate entries. */
31668 static void
31669 aarch64_test_sysreg_encoding_clashes (void)
31670 {
31671 using dup_instances_t = hash_map<nofree_string_hash,
31672 std::vector<const sysreg_t*>>;
31673
31674 dup_instances_t duplicate_instances;
31675
31676 /* Every time an encoding is established to come up more than once
31677 we add it to a "clash-analysis queue", which is then used to extract
31678 necessary information from our hash map when establishing whether
31679 repeated encodings are valid. */
31680
31681 /* 1) Collect recurrence information. */
31682 for (unsigned i = 0; i < ARRAY_SIZE (aarch64_sysregs); i++)
31683 {
31684 const sysreg_t *reg = aarch64_sysregs + i;
31685
31686 std::vector<const sysreg_t*> *tmp
31687 = &duplicate_instances.get_or_insert (reg->encoding);
31688
31689 tmp->push_back (reg);
31690 }
31691
31692 /* 2) Carry out analysis on collected data. */
31693 for (auto instance : duplicate_instances)
31694 {
31695 unsigned nrep = instance.second.size ();
31696 if (nrep > 1)
31697 for (unsigned i = 0; i < nrep; i++)
31698 for (unsigned j = i + 1; j < nrep; j++)
31699 {
31700 const sysreg_t *a = instance.second[i];
31701 const sysreg_t *b = instance.second[j];
31702 ASSERT_TRUE ((a->properties != b->properties)
31703 || (a->arch_reqs != b->arch_reqs));
31704 }
31705 }
31706 }
31707
31708 /* Test SVE arithmetic folding. */
31709
31710 static void
31711 aarch64_test_sve_folding ()
31712 {
31713 tree res = fold_unary (BIT_NOT_EXPR, ssizetype,
31714 ssize_int (poly_int64 (1, 1)));
31715 ASSERT_TRUE (operand_equal_p (res, ssize_int (poly_int64 (-2, -1))));
31716 }
31717
31718 /* Run all target-specific selftests. */
31719
31720 static void
31721 aarch64_run_selftests (void)
31722 {
31723 aarch64_test_loading_full_dump ();
31724 aarch64_test_fractional_cost ();
31725 aarch64_test_sysreg_encoding_clashes ();
31726 aarch64_test_sve_folding ();
31727 }
31728
31729 } // namespace selftest
31730
31731 #endif /* #if CHECKING_P */
31732
31733 #undef TARGET_STACK_PROTECT_GUARD
31734 #define TARGET_STACK_PROTECT_GUARD aarch64_stack_protect_guard
31735
31736 #undef TARGET_ADDRESS_COST
31737 #define TARGET_ADDRESS_COST aarch64_address_cost
31738
31739 /* This hook will determines whether unnamed bitfields affect the alignment
31740 of the containing structure. The hook returns true if the structure
31741 should inherit the alignment requirements of an unnamed bitfield's
31742 type. */
31743 #undef TARGET_ALIGN_ANON_BITFIELD
31744 #define TARGET_ALIGN_ANON_BITFIELD hook_bool_void_true
31745
31746 #undef TARGET_ASM_ALIGNED_DI_OP
31747 #define TARGET_ASM_ALIGNED_DI_OP "\t.xword\t"
31748
31749 #undef TARGET_ASM_ALIGNED_HI_OP
31750 #define TARGET_ASM_ALIGNED_HI_OP "\t.hword\t"
31751
31752 #undef TARGET_ASM_ALIGNED_SI_OP
31753 #define TARGET_ASM_ALIGNED_SI_OP "\t.word\t"
31754
31755 #if TARGET_PECOFF
31756 #undef TARGET_ASM_UNALIGNED_HI_OP
31757 #define TARGET_ASM_UNALIGNED_HI_OP TARGET_ASM_ALIGNED_HI_OP
31758 #undef TARGET_ASM_UNALIGNED_SI_OP
31759 #define TARGET_ASM_UNALIGNED_SI_OP TARGET_ASM_ALIGNED_SI_OP
31760 #undef TARGET_ASM_UNALIGNED_DI_OP
31761 #define TARGET_ASM_UNALIGNED_DI_OP TARGET_ASM_ALIGNED_DI_OP
31762 #endif
31763
31764 #undef TARGET_ASM_CAN_OUTPUT_MI_THUNK
31765 #define TARGET_ASM_CAN_OUTPUT_MI_THUNK \
31766 hook_bool_const_tree_hwi_hwi_const_tree_true
31767
31768 #undef TARGET_ASM_FILE_START
31769 #define TARGET_ASM_FILE_START aarch64_start_file
31770
31771 #undef TARGET_ASM_OUTPUT_MI_THUNK
31772 #define TARGET_ASM_OUTPUT_MI_THUNK aarch64_output_mi_thunk
31773
31774 #undef TARGET_ASM_SELECT_RTX_SECTION
31775 #define TARGET_ASM_SELECT_RTX_SECTION aarch64_select_rtx_section
31776
31777 #undef TARGET_ASM_TRAMPOLINE_TEMPLATE
31778 #define TARGET_ASM_TRAMPOLINE_TEMPLATE aarch64_asm_trampoline_template
31779
31780 #undef TARGET_ASM_PRINT_PATCHABLE_FUNCTION_ENTRY
31781 #define TARGET_ASM_PRINT_PATCHABLE_FUNCTION_ENTRY aarch64_print_patchable_function_entry
31782
31783 #undef TARGET_BUILD_BUILTIN_VA_LIST
31784 #define TARGET_BUILD_BUILTIN_VA_LIST aarch64_build_builtin_va_list
31785
31786 #undef TARGET_CALLEE_COPIES
31787 #define TARGET_CALLEE_COPIES hook_bool_CUMULATIVE_ARGS_arg_info_false
31788
31789 #undef TARGET_FRAME_POINTER_REQUIRED
31790 #define TARGET_FRAME_POINTER_REQUIRED aarch64_frame_pointer_required
31791
31792 #undef TARGET_CAN_ELIMINATE
31793 #define TARGET_CAN_ELIMINATE aarch64_can_eliminate
31794
31795 #undef TARGET_FUNCTION_ATTRIBUTE_INLINABLE_P
31796 #define TARGET_FUNCTION_ATTRIBUTE_INLINABLE_P \
31797 aarch64_function_attribute_inlinable_p
31798
31799 #undef TARGET_NEED_IPA_FN_TARGET_INFO
31800 #define TARGET_NEED_IPA_FN_TARGET_INFO aarch64_need_ipa_fn_target_info
31801
31802 #undef TARGET_UPDATE_IPA_FN_TARGET_INFO
31803 #define TARGET_UPDATE_IPA_FN_TARGET_INFO aarch64_update_ipa_fn_target_info
31804
31805 #undef TARGET_CAN_INLINE_P
31806 #define TARGET_CAN_INLINE_P aarch64_can_inline_p
31807
31808 #undef TARGET_CANNOT_FORCE_CONST_MEM
31809 #define TARGET_CANNOT_FORCE_CONST_MEM aarch64_cannot_force_const_mem
31810
31811 #undef TARGET_CASE_VALUES_THRESHOLD
31812 #define TARGET_CASE_VALUES_THRESHOLD aarch64_case_values_threshold
31813
31814 #undef TARGET_CONDITIONAL_REGISTER_USAGE
31815 #define TARGET_CONDITIONAL_REGISTER_USAGE aarch64_conditional_register_usage
31816
31817 #undef TARGET_MEMBER_TYPE_FORCES_BLK
31818 #define TARGET_MEMBER_TYPE_FORCES_BLK aarch64_member_type_forces_blk
31819
31820 /* Only the least significant bit is used for initialization guard
31821 variables. */
31822 #undef TARGET_CXX_GUARD_MASK_BIT
31823 #define TARGET_CXX_GUARD_MASK_BIT hook_bool_void_true
31824
31825 #undef TARGET_C_MODE_FOR_SUFFIX
31826 #define TARGET_C_MODE_FOR_SUFFIX aarch64_c_mode_for_suffix
31827
31828 #ifdef TARGET_BIG_ENDIAN_DEFAULT
31829 #undef TARGET_DEFAULT_TARGET_FLAGS
31830 #define TARGET_DEFAULT_TARGET_FLAGS (MASK_BIG_END)
31831 #endif
31832
31833 #undef TARGET_CLASS_MAX_NREGS
31834 #define TARGET_CLASS_MAX_NREGS aarch64_class_max_nregs
31835
31836 #undef TARGET_BUILTIN_DECL
31837 #define TARGET_BUILTIN_DECL aarch64_builtin_decl
31838
31839 #undef TARGET_BUILTIN_RECIPROCAL
31840 #define TARGET_BUILTIN_RECIPROCAL aarch64_builtin_reciprocal
31841
31842 #undef TARGET_C_EXCESS_PRECISION
31843 #define TARGET_C_EXCESS_PRECISION aarch64_excess_precision
31844
31845 #undef TARGET_C_BITINT_TYPE_INFO
31846 #define TARGET_C_BITINT_TYPE_INFO aarch64_bitint_type_info
31847
31848 #undef TARGET_C_MODE_FOR_FLOATING_TYPE
31849 #define TARGET_C_MODE_FOR_FLOATING_TYPE aarch64_c_mode_for_floating_type
31850
31851 #undef TARGET_EXPAND_BUILTIN
31852 #define TARGET_EXPAND_BUILTIN aarch64_expand_builtin
31853
31854 #undef TARGET_EXPAND_BUILTIN_VA_START
31855 #define TARGET_EXPAND_BUILTIN_VA_START aarch64_expand_builtin_va_start
31856
31857 #undef TARGET_FOLD_BUILTIN
31858 #define TARGET_FOLD_BUILTIN aarch64_fold_builtin
31859
31860 #undef TARGET_FUNCTION_ARG
31861 #define TARGET_FUNCTION_ARG aarch64_function_arg
31862
31863 #undef TARGET_FUNCTION_ARG_ADVANCE
31864 #define TARGET_FUNCTION_ARG_ADVANCE aarch64_function_arg_advance
31865
31866 #undef TARGET_FUNCTION_ARG_BOUNDARY
31867 #define TARGET_FUNCTION_ARG_BOUNDARY aarch64_function_arg_boundary
31868
31869 #undef TARGET_FUNCTION_ARG_PADDING
31870 #define TARGET_FUNCTION_ARG_PADDING aarch64_function_arg_padding
31871
31872 #undef TARGET_GET_RAW_RESULT_MODE
31873 #define TARGET_GET_RAW_RESULT_MODE aarch64_get_reg_raw_mode
31874 #undef TARGET_GET_RAW_ARG_MODE
31875 #define TARGET_GET_RAW_ARG_MODE aarch64_get_reg_raw_mode
31876
31877 #undef TARGET_FUNCTION_OK_FOR_SIBCALL
31878 #define TARGET_FUNCTION_OK_FOR_SIBCALL aarch64_function_ok_for_sibcall
31879
31880 #undef TARGET_FUNCTION_VALUE
31881 #define TARGET_FUNCTION_VALUE aarch64_function_value
31882
31883 #undef TARGET_FUNCTION_VALUE_REGNO_P
31884 #define TARGET_FUNCTION_VALUE_REGNO_P aarch64_function_value_regno_p
31885
31886 #undef TARGET_START_CALL_ARGS
31887 #define TARGET_START_CALL_ARGS aarch64_start_call_args
31888
31889 #undef TARGET_END_CALL_ARGS
31890 #define TARGET_END_CALL_ARGS aarch64_end_call_args
31891
31892 #undef TARGET_GIMPLE_FOLD_BUILTIN
31893 #define TARGET_GIMPLE_FOLD_BUILTIN aarch64_gimple_fold_builtin
31894
31895 #undef TARGET_GIMPLIFY_VA_ARG_EXPR
31896 #define TARGET_GIMPLIFY_VA_ARG_EXPR aarch64_gimplify_va_arg_expr
31897
31898 #undef TARGET_INIT_BUILTINS
31899 #define TARGET_INIT_BUILTINS aarch64_init_builtins
31900
31901 #undef TARGET_IRA_CHANGE_PSEUDO_ALLOCNO_CLASS
31902 #define TARGET_IRA_CHANGE_PSEUDO_ALLOCNO_CLASS \
31903 aarch64_ira_change_pseudo_allocno_class
31904
31905 #undef TARGET_LEGITIMATE_ADDRESS_P
31906 #define TARGET_LEGITIMATE_ADDRESS_P aarch64_legitimate_address_hook_p
31907
31908 #undef TARGET_LEGITIMATE_CONSTANT_P
31909 #define TARGET_LEGITIMATE_CONSTANT_P aarch64_legitimate_constant_p
31910
31911 #undef TARGET_LEGITIMIZE_ADDRESS_DISPLACEMENT
31912 #define TARGET_LEGITIMIZE_ADDRESS_DISPLACEMENT \
31913 aarch64_legitimize_address_displacement
31914
31915 #undef TARGET_LIBGCC_CMP_RETURN_MODE
31916 #define TARGET_LIBGCC_CMP_RETURN_MODE aarch64_libgcc_cmp_return_mode
31917
31918 #undef TARGET_LIBGCC_FLOATING_MODE_SUPPORTED_P
31919 #define TARGET_LIBGCC_FLOATING_MODE_SUPPORTED_P \
31920 aarch64_libgcc_floating_mode_supported_p
31921
31922 #undef TARGET_MANGLE_TYPE
31923 #define TARGET_MANGLE_TYPE aarch64_mangle_type
31924
31925 #undef TARGET_INVALID_CONVERSION
31926 #define TARGET_INVALID_CONVERSION aarch64_invalid_conversion
31927
31928 #undef TARGET_INVALID_UNARY_OP
31929 #define TARGET_INVALID_UNARY_OP aarch64_invalid_unary_op
31930
31931 #undef TARGET_INVALID_BINARY_OP
31932 #define TARGET_INVALID_BINARY_OP aarch64_invalid_binary_op
31933
31934 #undef TARGET_VERIFY_TYPE_CONTEXT
31935 #define TARGET_VERIFY_TYPE_CONTEXT aarch64_verify_type_context
31936
31937 #undef TARGET_MEMORY_MOVE_COST
31938 #define TARGET_MEMORY_MOVE_COST aarch64_memory_move_cost
31939
31940 #undef TARGET_CALLEE_SAVE_COST
31941 #define TARGET_CALLEE_SAVE_COST aarch64_callee_save_cost
31942
31943 #undef TARGET_FRAME_ALLOCATION_COST
31944 #define TARGET_FRAME_ALLOCATION_COST aarch64_frame_allocation_cost
31945
31946 #undef TARGET_MIN_DIVISIONS_FOR_RECIP_MUL
31947 #define TARGET_MIN_DIVISIONS_FOR_RECIP_MUL aarch64_min_divisions_for_recip_mul
31948
31949 #undef TARGET_MUST_PASS_IN_STACK
31950 #define TARGET_MUST_PASS_IN_STACK must_pass_in_stack_var_size
31951
31952 /* This target hook should return true if accesses to volatile bitfields
31953 should use the narrowest mode possible. It should return false if these
31954 accesses should use the bitfield container type. */
31955 #undef TARGET_NARROW_VOLATILE_BITFIELD
31956 #define TARGET_NARROW_VOLATILE_BITFIELD hook_bool_void_false
31957
31958 #undef TARGET_OPTION_OVERRIDE
31959 #define TARGET_OPTION_OVERRIDE aarch64_override_options
31960
31961 #undef TARGET_OVERRIDE_OPTIONS_AFTER_CHANGE
31962 #define TARGET_OVERRIDE_OPTIONS_AFTER_CHANGE \
31963 aarch64_override_options_after_change
31964
31965 #undef TARGET_OFFLOAD_OPTIONS
31966 #define TARGET_OFFLOAD_OPTIONS aarch64_offload_options
31967
31968 #undef TARGET_OPTION_RESTORE
31969 #define TARGET_OPTION_RESTORE aarch64_option_restore
31970
31971 #undef TARGET_OPTION_PRINT
31972 #define TARGET_OPTION_PRINT aarch64_option_print
31973
31974 #undef TARGET_OPTION_VALID_ATTRIBUTE_P
31975 #define TARGET_OPTION_VALID_ATTRIBUTE_P aarch64_option_valid_attribute_p
31976
31977 #undef TARGET_OPTION_VALID_VERSION_ATTRIBUTE_P
31978 #define TARGET_OPTION_VALID_VERSION_ATTRIBUTE_P \
31979 aarch64_option_valid_version_attribute_p
31980
31981 #undef TARGET_SET_CURRENT_FUNCTION
31982 #define TARGET_SET_CURRENT_FUNCTION aarch64_set_current_function
31983
31984 #undef TARGET_PASS_BY_REFERENCE
31985 #define TARGET_PASS_BY_REFERENCE aarch64_pass_by_reference
31986
31987 #undef TARGET_PREFERRED_RELOAD_CLASS
31988 #define TARGET_PREFERRED_RELOAD_CLASS aarch64_preferred_reload_class
31989
31990 #undef TARGET_SCHED_REASSOCIATION_WIDTH
31991 #define TARGET_SCHED_REASSOCIATION_WIDTH aarch64_reassociation_width
31992
31993 #undef TARGET_DWARF_FRAME_REG_MODE
31994 #define TARGET_DWARF_FRAME_REG_MODE aarch64_dwarf_frame_reg_mode
31995
31996 #undef TARGET_OUTPUT_CFI_DIRECTIVE
31997 #define TARGET_OUTPUT_CFI_DIRECTIVE aarch64_output_cfi_directive
31998
31999 #undef TARGET_DW_CFI_OPRND1_DESC
32000 #define TARGET_DW_CFI_OPRND1_DESC aarch64_dw_cfi_oprnd1_desc
32001
32002 #undef TARGET_PROMOTED_TYPE
32003 #define TARGET_PROMOTED_TYPE aarch64_promoted_type
32004
32005 #undef TARGET_SECONDARY_RELOAD
32006 #define TARGET_SECONDARY_RELOAD aarch64_secondary_reload
32007
32008 #undef TARGET_SECONDARY_MEMORY_NEEDED
32009 #define TARGET_SECONDARY_MEMORY_NEEDED aarch64_secondary_memory_needed
32010
32011 #undef TARGET_SHIFT_TRUNCATION_MASK
32012 #define TARGET_SHIFT_TRUNCATION_MASK aarch64_shift_truncation_mask
32013
32014 #undef TARGET_SETUP_INCOMING_VARARGS
32015 #define TARGET_SETUP_INCOMING_VARARGS aarch64_setup_incoming_varargs
32016
32017 #undef TARGET_STRUCT_VALUE_RTX
32018 #define TARGET_STRUCT_VALUE_RTX aarch64_struct_value_rtx
32019
32020 #undef TARGET_REGISTER_MOVE_COST
32021 #define TARGET_REGISTER_MOVE_COST aarch64_register_move_cost
32022
32023 #undef TARGET_RETURN_IN_MEMORY
32024 #define TARGET_RETURN_IN_MEMORY aarch64_return_in_memory
32025
32026 #undef TARGET_RETURN_IN_MSB
32027 #define TARGET_RETURN_IN_MSB aarch64_return_in_msb
32028
32029 #undef TARGET_RTX_COSTS
32030 #define TARGET_RTX_COSTS aarch64_rtx_costs_wrapper
32031
32032 #undef TARGET_INSN_COST
32033 #define TARGET_INSN_COST aarch64_insn_cost
32034
32035 #undef TARGET_SCALAR_MODE_SUPPORTED_P
32036 #define TARGET_SCALAR_MODE_SUPPORTED_P aarch64_scalar_mode_supported_p
32037
32038 #undef TARGET_SCHED_ISSUE_RATE
32039 #define TARGET_SCHED_ISSUE_RATE aarch64_sched_issue_rate
32040
32041 #undef TARGET_SCHED_VARIABLE_ISSUE
32042 #define TARGET_SCHED_VARIABLE_ISSUE aarch64_sched_variable_issue
32043
32044 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD
32045 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD \
32046 aarch64_sched_first_cycle_multipass_dfa_lookahead
32047
32048 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD
32049 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD \
32050 aarch64_first_cycle_multipass_dfa_lookahead_guard
32051
32052 #undef TARGET_SHRINK_WRAP_GET_SEPARATE_COMPONENTS
32053 #define TARGET_SHRINK_WRAP_GET_SEPARATE_COMPONENTS \
32054 aarch64_get_separate_components
32055
32056 #undef TARGET_SHRINK_WRAP_COMPONENTS_FOR_BB
32057 #define TARGET_SHRINK_WRAP_COMPONENTS_FOR_BB \
32058 aarch64_components_for_bb
32059
32060 #undef TARGET_SHRINK_WRAP_DISQUALIFY_COMPONENTS
32061 #define TARGET_SHRINK_WRAP_DISQUALIFY_COMPONENTS \
32062 aarch64_disqualify_components
32063
32064 #undef TARGET_SHRINK_WRAP_EMIT_PROLOGUE_COMPONENTS
32065 #define TARGET_SHRINK_WRAP_EMIT_PROLOGUE_COMPONENTS \
32066 aarch64_emit_prologue_components
32067
32068 #undef TARGET_SHRINK_WRAP_EMIT_EPILOGUE_COMPONENTS
32069 #define TARGET_SHRINK_WRAP_EMIT_EPILOGUE_COMPONENTS \
32070 aarch64_emit_epilogue_components
32071
32072 #undef TARGET_SHRINK_WRAP_SET_HANDLED_COMPONENTS
32073 #define TARGET_SHRINK_WRAP_SET_HANDLED_COMPONENTS \
32074 aarch64_set_handled_components
32075
32076 #undef TARGET_TRAMPOLINE_INIT
32077 #define TARGET_TRAMPOLINE_INIT aarch64_trampoline_init
32078
32079 #undef TARGET_USE_BLOCKS_FOR_CONSTANT_P
32080 #define TARGET_USE_BLOCKS_FOR_CONSTANT_P aarch64_use_blocks_for_constant_p
32081
32082 #undef TARGET_VECTOR_MODE_SUPPORTED_P
32083 #define TARGET_VECTOR_MODE_SUPPORTED_P aarch64_vector_mode_supported_p
32084
32085 #undef TARGET_VECTOR_MODE_SUPPORTED_ANY_TARGET_P
32086 #define TARGET_VECTOR_MODE_SUPPORTED_ANY_TARGET_P aarch64_vector_mode_supported_any_target_p
32087
32088 #undef TARGET_COMPATIBLE_VECTOR_TYPES_P
32089 #define TARGET_COMPATIBLE_VECTOR_TYPES_P aarch64_compatible_vector_types_p
32090
32091 #undef TARGET_VECTORIZE_SUPPORT_VECTOR_MISALIGNMENT
32092 #define TARGET_VECTORIZE_SUPPORT_VECTOR_MISALIGNMENT \
32093 aarch64_builtin_support_vector_misalignment
32094
32095 #undef TARGET_ARRAY_MODE
32096 #define TARGET_ARRAY_MODE aarch64_array_mode
32097
32098 #undef TARGET_ARRAY_MODE_SUPPORTED_P
32099 #define TARGET_ARRAY_MODE_SUPPORTED_P aarch64_array_mode_supported_p
32100
32101 #undef TARGET_VECTORIZE_CREATE_COSTS
32102 #define TARGET_VECTORIZE_CREATE_COSTS aarch64_vectorize_create_costs
32103
32104 #undef TARGET_VECTORIZE_BUILTIN_VECTORIZATION_COST
32105 #define TARGET_VECTORIZE_BUILTIN_VECTORIZATION_COST \
32106 aarch64_builtin_vectorization_cost
32107
32108 #undef TARGET_VECTORIZE_PREFERRED_SIMD_MODE
32109 #define TARGET_VECTORIZE_PREFERRED_SIMD_MODE aarch64_preferred_simd_mode
32110
32111 #undef TARGET_VECTORIZE_BUILTINS
32112 #define TARGET_VECTORIZE_BUILTINS
32113
32114 #undef TARGET_VECTORIZE_AUTOVECTORIZE_VECTOR_MODES
32115 #define TARGET_VECTORIZE_AUTOVECTORIZE_VECTOR_MODES \
32116 aarch64_autovectorize_vector_modes
32117
32118 #undef TARGET_ATOMIC_ASSIGN_EXPAND_FENV
32119 #define TARGET_ATOMIC_ASSIGN_EXPAND_FENV \
32120 aarch64_atomic_assign_expand_fenv
32121
32122 /* If-conversion costs. */
32123 #undef TARGET_MAX_NOCE_IFCVT_SEQ_COST
32124 #define TARGET_MAX_NOCE_IFCVT_SEQ_COST aarch64_max_noce_ifcvt_seq_cost
32125
32126 #undef TARGET_NOCE_CONVERSION_PROFITABLE_P
32127 #define TARGET_NOCE_CONVERSION_PROFITABLE_P aarch64_noce_conversion_profitable_p
32128
32129 /* Section anchor support. */
32130
32131 #undef TARGET_MIN_ANCHOR_OFFSET
32132 #define TARGET_MIN_ANCHOR_OFFSET -256
32133
32134 /* Limit the maximum anchor offset to 4k-1, since that's the limit for a
32135 byte offset; we can do much more for larger data types, but have no way
32136 to determine the size of the access. We assume accesses are aligned. */
32137 #undef TARGET_MAX_ANCHOR_OFFSET
32138 #define TARGET_MAX_ANCHOR_OFFSET 4095
32139
32140 #undef TARGET_VECTORIZE_PREFERRED_DIV_AS_SHIFTS_OVER_MULT
32141 #define TARGET_VECTORIZE_PREFERRED_DIV_AS_SHIFTS_OVER_MULT \
32142 aarch64_vectorize_preferred_div_as_shifts_over_mult
32143
32144 #undef TARGET_VECTOR_ALIGNMENT
32145 #define TARGET_VECTOR_ALIGNMENT aarch64_simd_vector_alignment
32146
32147 #undef TARGET_VECTORIZE_PREFERRED_VECTOR_ALIGNMENT
32148 #define TARGET_VECTORIZE_PREFERRED_VECTOR_ALIGNMENT \
32149 aarch64_vectorize_preferred_vector_alignment
32150 #undef TARGET_VECTORIZE_VECTOR_ALIGNMENT_REACHABLE
32151 #define TARGET_VECTORIZE_VECTOR_ALIGNMENT_REACHABLE \
32152 aarch64_simd_vector_alignment_reachable
32153
32154 /* vec_perm support. */
32155
32156 #undef TARGET_VECTORIZE_VEC_PERM_CONST
32157 #define TARGET_VECTORIZE_VEC_PERM_CONST \
32158 aarch64_vectorize_vec_perm_const
32159
32160 #undef TARGET_VECTORIZE_RELATED_MODE
32161 #define TARGET_VECTORIZE_RELATED_MODE aarch64_vectorize_related_mode
32162 #undef TARGET_VECTORIZE_GET_MASK_MODE
32163 #define TARGET_VECTORIZE_GET_MASK_MODE aarch64_get_mask_mode
32164 #undef TARGET_VECTORIZE_CONDITIONAL_OPERATION_IS_EXPENSIVE
32165 #define TARGET_VECTORIZE_CONDITIONAL_OPERATION_IS_EXPENSIVE \
32166 aarch64_conditional_operation_is_expensive
32167 #undef TARGET_VECTORIZE_EMPTY_MASK_IS_EXPENSIVE
32168 #define TARGET_VECTORIZE_EMPTY_MASK_IS_EXPENSIVE \
32169 aarch64_empty_mask_is_expensive
32170 #undef TARGET_PREFERRED_ELSE_VALUE
32171 #define TARGET_PREFERRED_ELSE_VALUE \
32172 aarch64_preferred_else_value
32173
32174 #undef TARGET_INIT_LIBFUNCS
32175 #define TARGET_INIT_LIBFUNCS aarch64_init_libfuncs
32176
32177 #undef TARGET_FIXED_CONDITION_CODE_REGS
32178 #define TARGET_FIXED_CONDITION_CODE_REGS aarch64_fixed_condition_code_regs
32179
32180 #undef TARGET_FLAGS_REGNUM
32181 #define TARGET_FLAGS_REGNUM CC_REGNUM
32182
32183 #undef TARGET_CALL_FUSAGE_CONTAINS_NON_CALLEE_CLOBBERS
32184 #define TARGET_CALL_FUSAGE_CONTAINS_NON_CALLEE_CLOBBERS true
32185
32186 #undef TARGET_ASAN_SHADOW_OFFSET
32187 #define TARGET_ASAN_SHADOW_OFFSET aarch64_asan_shadow_offset
32188
32189 #undef TARGET_LEGITIMIZE_ADDRESS
32190 #define TARGET_LEGITIMIZE_ADDRESS aarch64_legitimize_address
32191
32192 #undef TARGET_SCHED_CAN_SPECULATE_INSN
32193 #define TARGET_SCHED_CAN_SPECULATE_INSN aarch64_sched_can_speculate_insn
32194
32195 #undef TARGET_CAN_USE_DOLOOP_P
32196 #define TARGET_CAN_USE_DOLOOP_P can_use_doloop_if_innermost
32197
32198 #undef TARGET_SCHED_ADJUST_PRIORITY
32199 #define TARGET_SCHED_ADJUST_PRIORITY aarch64_sched_adjust_priority
32200
32201 #undef TARGET_SCHED_MACRO_FUSION_P
32202 #define TARGET_SCHED_MACRO_FUSION_P aarch64_macro_fusion_p
32203
32204 #undef TARGET_SCHED_MACRO_FUSION_PAIR_P
32205 #define TARGET_SCHED_MACRO_FUSION_PAIR_P aarch_macro_fusion_pair_p
32206
32207 #undef TARGET_SCHED_FUSION_PRIORITY
32208 #define TARGET_SCHED_FUSION_PRIORITY aarch64_sched_fusion_priority
32209
32210 #undef TARGET_UNSPEC_MAY_TRAP_P
32211 #define TARGET_UNSPEC_MAY_TRAP_P aarch64_unspec_may_trap_p
32212
32213 #undef TARGET_USE_PSEUDO_PIC_REG
32214 #define TARGET_USE_PSEUDO_PIC_REG aarch64_use_pseudo_pic_reg
32215
32216 #undef TARGET_PRINT_OPERAND
32217 #define TARGET_PRINT_OPERAND aarch64_print_operand
32218
32219 #undef TARGET_PRINT_OPERAND_ADDRESS
32220 #define TARGET_PRINT_OPERAND_ADDRESS aarch64_print_operand_address
32221
32222 #undef TARGET_ASM_OUTPUT_ADDR_CONST_EXTRA
32223 #define TARGET_ASM_OUTPUT_ADDR_CONST_EXTRA aarch64_output_addr_const_extra
32224
32225 #undef TARGET_OPTAB_SUPPORTED_P
32226 #define TARGET_OPTAB_SUPPORTED_P aarch64_optab_supported_p
32227
32228 #undef TARGET_OMIT_STRUCT_RETURN_REG
32229 #define TARGET_OMIT_STRUCT_RETURN_REG true
32230
32231 #undef TARGET_DWARF_POLY_INDETERMINATE_VALUE
32232 #define TARGET_DWARF_POLY_INDETERMINATE_VALUE \
32233 aarch64_dwarf_poly_indeterminate_value
32234
32235 /* The architecture reserves bits 0 and 1 so use bit 2 for descriptors. */
32236 #undef TARGET_CUSTOM_FUNCTION_DESCRIPTORS
32237 #define TARGET_CUSTOM_FUNCTION_DESCRIPTORS 4
32238
32239 #undef TARGET_HARD_REGNO_NREGS
32240 #define TARGET_HARD_REGNO_NREGS aarch64_hard_regno_nregs
32241 #undef TARGET_HARD_REGNO_MODE_OK
32242 #define TARGET_HARD_REGNO_MODE_OK aarch64_hard_regno_mode_ok
32243
32244 #undef TARGET_MODES_TIEABLE_P
32245 #define TARGET_MODES_TIEABLE_P aarch64_modes_tieable_p
32246
32247 #undef TARGET_HARD_REGNO_CALL_PART_CLOBBERED
32248 #define TARGET_HARD_REGNO_CALL_PART_CLOBBERED \
32249 aarch64_hard_regno_call_part_clobbered
32250
32251 #undef TARGET_INSN_CALLEE_ABI
32252 #define TARGET_INSN_CALLEE_ABI aarch64_insn_callee_abi
32253
32254 #undef TARGET_CONSTANT_ALIGNMENT
32255 #define TARGET_CONSTANT_ALIGNMENT aarch64_constant_alignment
32256
32257 #undef TARGET_STACK_CLASH_PROTECTION_ALLOCA_PROBE_RANGE
32258 #define TARGET_STACK_CLASH_PROTECTION_ALLOCA_PROBE_RANGE \
32259 aarch64_stack_clash_protection_alloca_probe_range
32260
32261 #undef TARGET_COMPUTE_PRESSURE_CLASSES
32262 #define TARGET_COMPUTE_PRESSURE_CLASSES aarch64_compute_pressure_classes
32263
32264 #undef TARGET_CAN_CHANGE_MODE_CLASS
32265 #define TARGET_CAN_CHANGE_MODE_CLASS aarch64_can_change_mode_class
32266
32267 #undef TARGET_SELECT_EARLY_REMAT_MODES
32268 #define TARGET_SELECT_EARLY_REMAT_MODES aarch64_select_early_remat_modes
32269
32270 #undef TARGET_SPECULATION_SAFE_VALUE
32271 #define TARGET_SPECULATION_SAFE_VALUE aarch64_speculation_safe_value
32272
32273 #undef TARGET_ESTIMATED_POLY_VALUE
32274 #define TARGET_ESTIMATED_POLY_VALUE aarch64_estimated_poly_value
32275
32276 #undef TARGET_ATTRIBUTE_TABLE
32277 #define TARGET_ATTRIBUTE_TABLE aarch64_attribute_table
32278
32279 #undef TARGET_SIMD_CLONE_COMPUTE_VECSIZE_AND_SIMDLEN
32280 #define TARGET_SIMD_CLONE_COMPUTE_VECSIZE_AND_SIMDLEN \
32281 aarch64_simd_clone_compute_vecsize_and_simdlen
32282
32283 #undef TARGET_SIMD_CLONE_ADJUST
32284 #define TARGET_SIMD_CLONE_ADJUST aarch64_simd_clone_adjust
32285
32286 #undef TARGET_SIMD_CLONE_USABLE
32287 #define TARGET_SIMD_CLONE_USABLE aarch64_simd_clone_usable
32288
32289 #undef TARGET_COMP_TYPE_ATTRIBUTES
32290 #define TARGET_COMP_TYPE_ATTRIBUTES aarch64_comp_type_attributes
32291
32292 #undef TARGET_MERGE_DECL_ATTRIBUTES
32293 #define TARGET_MERGE_DECL_ATTRIBUTES aarch64_merge_decl_attributes
32294
32295 #undef TARGET_GET_MULTILIB_ABI_NAME
32296 #define TARGET_GET_MULTILIB_ABI_NAME aarch64_get_multilib_abi_name
32297
32298 #undef TARGET_FNTYPE_ABI
32299 #define TARGET_FNTYPE_ABI aarch64_fntype_abi
32300
32301 #undef TARGET_MEMTAG_CAN_TAG_ADDRESSES
32302 #define TARGET_MEMTAG_CAN_TAG_ADDRESSES aarch64_can_tag_addresses
32303
32304 #if CHECKING_P
32305 #undef TARGET_RUN_TARGET_SELFTESTS
32306 #define TARGET_RUN_TARGET_SELFTESTS selftest::aarch64_run_selftests
32307 #endif /* #if CHECKING_P */
32308
32309 #undef TARGET_ASM_POST_CFI_STARTPROC
32310 #define TARGET_ASM_POST_CFI_STARTPROC aarch64_post_cfi_startproc
32311
32312 #undef TARGET_STRICT_ARGUMENT_NAMING
32313 #define TARGET_STRICT_ARGUMENT_NAMING hook_bool_CUMULATIVE_ARGS_true
32314
32315 #undef TARGET_MODE_EMIT
32316 #define TARGET_MODE_EMIT aarch64_mode_emit
32317
32318 #undef TARGET_MODE_NEEDED
32319 #define TARGET_MODE_NEEDED aarch64_mode_needed
32320
32321 #undef TARGET_MODE_AFTER
32322 #define TARGET_MODE_AFTER aarch64_mode_after
32323
32324 #undef TARGET_MODE_CONFLUENCE
32325 #define TARGET_MODE_CONFLUENCE aarch64_mode_confluence
32326
32327 #undef TARGET_MODE_BACKPROP
32328 #define TARGET_MODE_BACKPROP aarch64_mode_backprop
32329
32330 #undef TARGET_MODE_ENTRY
32331 #define TARGET_MODE_ENTRY aarch64_mode_entry
32332
32333 #undef TARGET_MODE_EXIT
32334 #define TARGET_MODE_EXIT aarch64_mode_exit
32335
32336 #undef TARGET_MODE_EH_HANDLER
32337 #define TARGET_MODE_EH_HANDLER aarch64_mode_eh_handler
32338
32339 #undef TARGET_MODE_PRIORITY
32340 #define TARGET_MODE_PRIORITY aarch64_mode_priority
32341
32342 #undef TARGET_MD_ASM_ADJUST
32343 #define TARGET_MD_ASM_ADJUST aarch64_md_asm_adjust
32344
32345 #undef TARGET_ASM_FILE_END
32346 #define TARGET_ASM_FILE_END aarch64_asm_file_end
32347
32348 #undef TARGET_ASM_FUNCTION_EPILOGUE
32349 #define TARGET_ASM_FUNCTION_EPILOGUE aarch64_sls_emit_blr_function_thunks
32350
32351 #undef TARGET_HAVE_SHADOW_CALL_STACK
32352 #define TARGET_HAVE_SHADOW_CALL_STACK true
32353
32354 #undef TARGET_CONST_ANCHOR
32355 #define TARGET_CONST_ANCHOR 0x1000000
32356
32357 #undef TARGET_EXTRA_LIVE_ON_ENTRY
32358 #define TARGET_EXTRA_LIVE_ON_ENTRY aarch64_extra_live_on_entry
32359
32360 #undef TARGET_USE_LATE_PROLOGUE_EPILOGUE
32361 #define TARGET_USE_LATE_PROLOGUE_EPILOGUE aarch64_use_late_prologue_epilogue
32362
32363 #undef TARGET_EMIT_EPILOGUE_FOR_SIBCALL
32364 #define TARGET_EMIT_EPILOGUE_FOR_SIBCALL aarch64_expand_epilogue
32365
32366 #undef TARGET_OPTION_FUNCTION_VERSIONS
32367 #define TARGET_OPTION_FUNCTION_VERSIONS aarch64_common_function_versions
32368
32369 #undef TARGET_COMPARE_VERSION_PRIORITY
32370 #define TARGET_COMPARE_VERSION_PRIORITY aarch64_compare_version_priority
32371
32372 #undef TARGET_GENERATE_VERSION_DISPATCHER_BODY
32373 #define TARGET_GENERATE_VERSION_DISPATCHER_BODY \
32374 aarch64_generate_version_dispatcher_body
32375
32376 #undef TARGET_GET_FUNCTION_VERSIONS_DISPATCHER
32377 #define TARGET_GET_FUNCTION_VERSIONS_DISPATCHER \
32378 aarch64_get_function_versions_dispatcher
32379
32380 #undef TARGET_MANGLE_DECL_ASSEMBLER_NAME
32381 #define TARGET_MANGLE_DECL_ASSEMBLER_NAME aarch64_mangle_decl_assembler_name
32382
32383 #undef TARGET_DOCUMENTATION_NAME
32384 #define TARGET_DOCUMENTATION_NAME "AArch64"
32385
32386 struct gcc_target targetm = TARGET_INITIALIZER;
32387
32388 #include "gt-aarch64.h"