Debian Codegraph @

gcc/config/riscv/riscv-v.cc

raw
1 /* Subroutines used for code generation for RISC-V 'V' Extension for
2 GNU compiler.
3 Copyright (C) 2022-2025 Free Software Foundation, Inc.
4 Contributed by Juzhe Zhong ([email protected]), RiVAI Technologies Ltd.
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12
13 GCC is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
21
22 #define IN_TARGET_CODE 1
23
24 /* We have a maximum of 11 operands for RVV instruction patterns according to
25 the vector.md. */
26 #define RVV_INSN_OPERANDS_MAX 11
27
28 #include "config.h"
29 #include "system.h"
30 #include "coretypes.h"
31 #include "tm.h"
32 #include "backend.h"
33 #include "rtl.h"
34 #include "insn-config.h"
35 #include "insn-attr.h"
36 #include "recog.h"
37 #include "alias.h"
38 #include "tree.h"
39 #include "stringpool.h"
40 #include "attribs.h"
41 #include "explow.h"
42 #include "memmodel.h"
43 #include "emit-rtl.h"
44 #include "tm_p.h"
45 #include "target.h"
46 #include "targhooks.h"
47 #include "expr.h"
48 #include "optabs.h"
49 #include "tm-constrs.h"
50 #include "rtx-vector-builder.h"
51 #include "targhooks.h"
52 #include "predict.h"
53 #include "errors.h"
54 #include "riscv-v.h"
55
56 using namespace riscv_vector;
57
58 namespace riscv_vector {
59
60 /* Return true if NUNITS <=31 so that we can use immediate AVL in vsetivli. */
61 bool
62 imm_avl_p (machine_mode mode)
63 {
64 poly_uint64 nunits = GET_MODE_NUNITS (mode);
65
66 return nunits.is_constant ()
67 /* The vsetivli can only hold register 0~31. */
68 ? (IN_RANGE (nunits.to_constant (), 0, 31))
69 /* Only allowed in VLS-VLMAX mode. */
70 : false;
71 }
72
73 /* Return true if LEN is equal to NUNITS that out of the range [0, 31]. */
74 static bool
75 is_vlmax_len_p (machine_mode mode, rtx len)
76 {
77 poly_int64 value;
78 return poly_int_rtx_p (len, &value)
79 && known_eq (value, GET_MODE_NUNITS (mode));
80 }
81
82 /* Helper functions for insn_flags && insn_types */
83
84 /* Return true if caller need pass mask operand for insn pattern with
85 INSN_FLAGS. */
86
87 static bool
88 need_mask_operand_p (unsigned insn_flags)
89 {
90 return (insn_flags & HAS_MASK_P)
91 && !(insn_flags & (USE_ONE_TRUE_MASK_P | USE_ALL_TRUES_MASK_P));
92 }
93
94 template <int MAX_OPERANDS> class insn_expander
95 {
96 public:
97 insn_expander () = delete;
98
99 insn_expander (unsigned insn_flags, bool vlmax_p)
100 : m_insn_flags (insn_flags), m_opno (0), m_vlmax_p (vlmax_p),
101 m_vl_op (NULL_RTX)
102 {
103 check_insn_flags ();
104 }
105
106 void check_insn_flags () const
107 {
108 if (m_insn_flags & USE_ONE_TRUE_MASK_P)
109 /* USE_ONE_TRUE_MASK_P is dependent on HAS_MASK_P. */
110 gcc_assert ((m_insn_flags & HAS_MASK_P));
111
112 if (m_insn_flags & USE_ALL_TRUES_MASK_P)
113 /* USE_ALL_TRUES_MASK_P is dependent on HAS_MASK_P. */
114 gcc_assert ((m_insn_flags & HAS_MASK_P));
115
116 /* USE_ONE_TRUE_MASK_P and USE_ALL_TRUES_MASK_P are mutually exclusive. */
117 gcc_assert (!((m_insn_flags & USE_ONE_TRUE_MASK_P)
118 && (m_insn_flags & USE_ALL_TRUES_MASK_P)));
119
120 if (m_insn_flags & USE_VUNDEF_MERGE_P)
121 /* USE_VUNDEF_MERGE_P is dependent on HAS_MERGE_P. */
122 gcc_assert ((m_insn_flags & HAS_MERGE_P));
123
124 /* TU_POLICY_P and TDEFAULT_POLICY_P are mutually exclusive. */
125 gcc_assert (
126 !((m_insn_flags & TU_POLICY_P) && (m_insn_flags & TDEFAULT_POLICY_P)));
127
128 /* MU_POLICY_P and MDEFAULT_POLICY_P are mutually exclusive. */
129 gcc_assert (
130 !((m_insn_flags & MU_POLICY_P) && (m_insn_flags & MDEFAULT_POLICY_P)));
131
132 /* NULLARY_OP_P, UNARY_OP_P, BINARY_OP_P, TERNARY_OP_P are mutually
133 exclusive. */
134 gcc_assert (
135 !((m_insn_flags & NULLARY_OP_P)
136 && ((m_insn_flags & UNARY_OP_P) || (m_insn_flags & BINARY_OP_P)
137 || (m_insn_flags & TERNARY_OP_P))));
138 gcc_assert (
139 !((m_insn_flags & UNARY_OP_P)
140 && ((m_insn_flags & NULLARY_OP_P) || (m_insn_flags & BINARY_OP_P)
141 || (m_insn_flags & TERNARY_OP_P))));
142 gcc_assert (
143 !((m_insn_flags & BINARY_OP_P)
144 && ((m_insn_flags & NULLARY_OP_P) || (m_insn_flags & UNARY_OP_P)
145 || (m_insn_flags & TERNARY_OP_P))));
146 gcc_assert (
147 !((m_insn_flags & TERNARY_OP_P)
148 && ((m_insn_flags & NULLARY_OP_P) || (m_insn_flags & UNARY_OP_P)
149 || (m_insn_flags & BINARY_OP_P))));
150 }
151
152 void set_vl (rtx vl) { m_vl_op = vl; }
153
154 void add_output_operand (rtx x, machine_mode mode)
155 {
156 create_output_operand (&m_ops[m_opno++], x, mode);
157 gcc_assert (m_opno <= MAX_OPERANDS);
158 }
159 void add_input_operand (rtx x, machine_mode mode)
160 {
161 create_input_operand (&m_ops[m_opno++], x, mode);
162 gcc_assert (m_opno <= MAX_OPERANDS);
163 }
164 void add_all_one_mask_operand (machine_mode mask_mode)
165 {
166 add_input_operand (CONSTM1_RTX (mask_mode), mask_mode);
167 }
168 void add_first_one_true_mask_operand (machine_mode mask_mode)
169 {
170 add_input_operand (gen_scalar_move_mask (mask_mode), mask_mode);
171 }
172 void add_vundef_operand (machine_mode dest_mode)
173 {
174 add_input_operand (RVV_VUNDEF (dest_mode), dest_mode);
175 }
176 void add_policy_operand ()
177 {
178 if (m_insn_flags & TU_POLICY_P)
179 {
180 rtx tail_policy_rtx = gen_int_mode (TAIL_UNDISTURBED, Pmode);
181 add_input_operand (tail_policy_rtx, Pmode);
182 }
183 else if (m_insn_flags & TDEFAULT_POLICY_P)
184 {
185 rtx tail_policy_rtx = gen_int_mode (get_prefer_tail_policy (), Pmode);
186 add_input_operand (tail_policy_rtx, Pmode);
187 }
188
189 if (m_insn_flags & MU_POLICY_P)
190 {
191 rtx mask_policy_rtx = gen_int_mode (MASK_UNDISTURBED, Pmode);
192 add_input_operand (mask_policy_rtx, Pmode);
193 }
194 else if (m_insn_flags & MDEFAULT_POLICY_P)
195 {
196 rtx mask_policy_rtx = gen_int_mode (get_prefer_mask_policy (), Pmode);
197 add_input_operand (mask_policy_rtx, Pmode);
198 }
199 }
200 void add_avl_type_operand (avl_type type)
201 {
202 add_input_operand (gen_int_mode (type, Pmode), Pmode);
203 }
204
205 void
206 add_rounding_mode_operand (enum floating_point_rounding_mode rounding_mode)
207 {
208 rtx frm_rtx = gen_int_mode (rounding_mode, Pmode);
209 add_input_operand (frm_rtx, Pmode);
210 }
211
212 void
213 add_rounding_mode_operand (enum fixed_point_rounding_mode rounding_mode)
214 {
215 rtx frm_rtx = gen_int_mode (rounding_mode, Pmode);
216 add_input_operand (frm_rtx, Pmode);
217 }
218
219 /* Return the vtype mode based on insn_flags.
220 vtype mode mean the mode vsetvl insn set. */
221 machine_mode
222 get_vtype_mode (rtx *ops)
223 {
224 machine_mode vtype_mode;
225 if (m_insn_flags & VTYPE_MODE_FROM_OP1_P)
226 vtype_mode = GET_MODE (ops[1]);
227 else
228 vtype_mode = GET_MODE (ops[0]);
229 return vtype_mode;
230 }
231
232 void emit_insn (enum insn_code icode, rtx *ops)
233 {
234 int opno = 0;
235 int num_ops;
236 /* It's true if any operand is memory operand. */
237 bool any_mem_p = false;
238
239 machine_mode vtype_mode = get_vtype_mode (ops);
240 machine_mode mask_mode = get_mask_mode (vtype_mode);
241
242 /* Add dest operand. */
243 if (m_insn_flags & HAS_DEST_P)
244 {
245 rtx op = ops[opno++];
246 any_mem_p |= MEM_P (op);
247 add_output_operand (op, GET_MODE (op));
248 }
249
250 /* Add mask operand. */
251 if (m_insn_flags & USE_ONE_TRUE_MASK_P)
252 add_first_one_true_mask_operand (mask_mode);
253 else if (m_insn_flags & USE_ALL_TRUES_MASK_P)
254 add_all_one_mask_operand (mask_mode);
255 else if (m_insn_flags & HAS_MASK_P)
256 {
257 machine_mode mode = insn_data[(int) icode].operand[m_opno].mode;
258 gcc_assert (mode != VOIDmode);
259 add_input_operand (ops[opno++], mode);
260 }
261
262 /* Add merge operand. */
263 if (m_insn_flags & USE_VUNDEF_MERGE_P)
264 /* Same as dest operand. */
265 add_vundef_operand (GET_MODE (ops[0]));
266 else if (m_insn_flags & HAS_MERGE_P)
267 {
268 machine_mode mode = insn_data[(int) icode].operand[m_opno].mode;
269 gcc_assert (mode != VOIDmode);
270 add_input_operand (ops[opno++], mode);
271 }
272
273 if (m_insn_flags & NULLARY_OP_P)
274 num_ops = 0;
275 else if (m_insn_flags & UNARY_OP_P)
276 num_ops = 1;
277 else if (m_insn_flags & BINARY_OP_P)
278 num_ops = 2;
279 else if (m_insn_flags & TERNARY_OP_P)
280 num_ops = 3;
281 else
282 gcc_unreachable ();
283
284 /* Add the remain operands. */
285 for (; num_ops; num_ops--, opno++)
286 {
287 any_mem_p |= MEM_P (ops[opno]);
288 machine_mode mode = insn_data[(int) icode].operand[m_opno].mode;
289 /* 'create_input_operand doesn't allow VOIDmode.
290 According to vector.md, we may have some patterns that do not have
291 explicit machine mode specifying the operand. Such operands are
292 always Pmode. */
293 if (mode == VOIDmode)
294 mode = Pmode;
295
296 /* Early assertion ensures same mode since maybe_legitimize_operand
297 will check this. */
298 machine_mode required_mode = GET_MODE (ops[opno]);
299 if (required_mode != VOIDmode && required_mode != mode)
300 internal_error ("expected mode %s for operand %d of "
301 "insn %s but got mode %s.\n",
302 GET_MODE_NAME (mode),
303 opno,
304 insn_data[(int) icode].name,
305 GET_MODE_NAME (required_mode));
306
307 add_input_operand (ops[opno], mode);
308 }
309
310 /* Add vl operand. */
311 rtx len = m_vl_op;
312 bool vls_p = false;
313 if (m_vlmax_p)
314 {
315 if (riscv_v_ext_vls_mode_p (vtype_mode))
316 {
317 /* VLS modes always set VSETVL by
318 "vsetvl zero, rs1/imm". */
319 poly_uint64 nunits = GET_MODE_NUNITS (vtype_mode);
320 len = gen_int_mode (nunits, Pmode);
321 vls_p = true;
322 }
323 else if (can_create_pseudo_p ())
324 {
325 len = gen_reg_rtx (Pmode);
326 emit_vlmax_vsetvl (vtype_mode, len);
327 }
328 }
329
330 gcc_assert (len != NULL_RTX);
331 add_input_operand (len, Pmode);
332
333 /* Add tail and mask policy operands. */
334 add_policy_operand ();
335
336 /* Add avl_type operand. */
337 add_avl_type_operand (
338 vls_p ? avl_type::VLS
339 : (m_vlmax_p ? avl_type::VLMAX : avl_type::NONVLMAX));
340
341 /* Add rounding mode operand. */
342 if (m_insn_flags & FRM_DYN_P)
343 add_rounding_mode_operand (FRM_DYN);
344 else if (m_insn_flags & FRM_RUP_P)
345 add_rounding_mode_operand (FRM_RUP);
346 else if (m_insn_flags & FRM_RDN_P)
347 add_rounding_mode_operand (FRM_RDN);
348 else if (m_insn_flags & FRM_RMM_P)
349 add_rounding_mode_operand (FRM_RMM);
350 else if (m_insn_flags & FRM_RNE_P)
351 add_rounding_mode_operand (FRM_RNE);
352 else if (m_insn_flags & VXRM_RNU_P)
353 add_rounding_mode_operand (VXRM_RNU);
354 else if (m_insn_flags & VXRM_RDN_P)
355 add_rounding_mode_operand (VXRM_RDN);
356
357
358 if (insn_data[(int) icode].n_operands != m_opno)
359 internal_error ("invalid number of operands for insn %s, "
360 "expected %d but got %d.\n",
361 insn_data[(int) icode].name,
362 insn_data[(int) icode].n_operands, m_opno);
363
364 expand (icode, any_mem_p);
365 }
366
367 void expand (enum insn_code icode, bool temporary_volatile_p = false)
368 {
369 if (temporary_volatile_p)
370 {
371 temporary_volatile_ok v (true);
372 expand_insn (icode, m_opno, m_ops);
373 }
374 else
375 expand_insn (icode, m_opno, m_ops);
376 }
377
378 private:
379 unsigned m_insn_flags;
380 int m_opno;
381 bool m_vlmax_p;
382 rtx m_vl_op;
383 expand_operand m_ops[MAX_OPERANDS];
384 };
385
386 /* Emit an RVV insn with a vector length that equals the number of units of the
387 vector mode. For VLA modes this corresponds to VLMAX.
388
389 Unless the vector length can be encoded in the vsetivl[i] instruction this
390 function must only be used as long as we can create pseudo registers. This is
391 because it will set a pseudo register to VLMAX using vsetvl and use this as
392 definition for the vector length. */
393 void
394 emit_vlmax_insn (unsigned icode, unsigned insn_flags, rtx *ops)
395 {
396 insn_expander<RVV_INSN_OPERANDS_MAX> e (insn_flags, true);
397 gcc_assert (can_create_pseudo_p () || imm_avl_p (e.get_vtype_mode (ops)));
398
399 e.emit_insn ((enum insn_code) icode, ops);
400 }
401
402 /* Like emit_vlmax_insn but must only be used when we cannot create pseudo
403 registers anymore. This function, however, takes a predefined vector length
404 from the value in VL. */
405 void
406 emit_vlmax_insn_lra (unsigned icode, unsigned insn_flags, rtx *ops, rtx vl)
407 {
408 gcc_assert (!can_create_pseudo_p ());
409 machine_mode mode = GET_MODE (ops[0]);
410
411 if (imm_avl_p (mode))
412 {
413 /* Even though VL is a real hardreg already allocated since
414 it is post-RA now, we still gain benefits that we emit
415 vsetivli zero, imm instead of vsetvli VL, zero which is
416 we can be more flexible in post-RA instruction scheduling. */
417 insn_expander<RVV_INSN_OPERANDS_MAX> e (insn_flags, false);
418 e.set_vl (gen_int_mode (GET_MODE_NUNITS (mode), Pmode));
419 e.emit_insn ((enum insn_code) icode, ops);
420 }
421 else
422 {
423 insn_expander<RVV_INSN_OPERANDS_MAX> e (insn_flags, true);
424 e.set_vl (vl);
425 e.emit_insn ((enum insn_code) icode, ops);
426 }
427 }
428
429 /* Emit an RVV insn with a predefined vector length. Contrary to
430 emit_vlmax_insn the instruction's vector length is not deduced from its mode
431 but taken from the value in VL. */
432 void
433 emit_nonvlmax_insn (unsigned icode, unsigned insn_flags, rtx *ops, rtx vl)
434 {
435 insn_expander<RVV_INSN_OPERANDS_MAX> e (insn_flags, false);
436 e.set_vl (vl);
437 e.emit_insn ((enum insn_code) icode, ops);
438 }
439
440 /* Return true if the vector duplicated by a super element which is the fusion
441 of consecutive elements.
442
443 v = { a, b, a, b } super element = ab, v = { ab, ab } */
444 bool
445 rvv_builder::can_duplicate_repeating_sequence_p ()
446 {
447 poly_uint64 new_size = exact_div (full_nelts (), npatterns ());
448 unsigned int new_inner_size = m_inner_bits_size * npatterns ();
449 if (m_inner_mode == Pmode
450 || !int_mode_for_size (new_inner_size, 0).exists (&m_new_inner_mode)
451 || GET_MODE_SIZE (m_new_inner_mode) > UNITS_PER_WORD
452 || !get_vector_mode (m_new_inner_mode, new_size).exists (&m_new_mode))
453 return false;
454 return repeating_sequence_p (0, encoded_nelts (), npatterns ());
455 }
456
457 /* Return true if the vector is a simple sequence with one pattern and all
458 elements the same. */
459 bool
460 rvv_builder::is_repeating_sequence ()
461 {
462 if (npatterns () > 1)
463 return false;
464 return repeating_sequence_p (0, encoded_nelts (), 1);
465 }
466
467 /* Return true if it is a repeating sequence that using
468 merge approach has better codegen than using default
469 approach (slide1down).
470
471 Sequence A:
472 {a, b, a, b, a, b, a, b, a, b, a, b, a, b, a, b}
473
474 nelts = 16
475 npatterns = 2
476
477 for merging a we need mask 101010....
478 for merging b we need mask 010101....
479
480 Foreach element in the npattern, we need to build a mask in scalar register.
481 Mostly we need 3 instructions (aka COST = 3), which consists of 2 scalar
482 instructions and 1 scalar move to v0 register. Finally we need vector merge
483 to merge them.
484
485 lui a5, #imm
486 add a5, #imm
487 vmov.s.x v0, a5
488 vmerge.vxm v9, v9, a1, v0
489
490 So the overall (roughly) COST of Sequence A = (3 + 1) * npatterns = 8.
491 If we use slide1down, the COST = nelts = 16 > 8 (COST of merge).
492 So return true in this case as it is profitable.
493
494 Sequence B:
495 {a, b, c, d, e, f, g, h, a, b, c, d, e, f, g, h}
496
497 nelts = 16
498 npatterns = 8
499
500 COST of merge approach = (3 + 1) * npatterns = 24
501 COST of slide1down approach = nelts = 16
502 Return false in this case as it is NOT profitable in merge approach.
503 */
504 bool
505 rvv_builder::repeating_sequence_use_merge_profitable_p ()
506 {
507 if (inner_bytes_size () > UNITS_PER_WORD)
508 return false;
509
510 unsigned int nelts = full_nelts ().to_constant ();
511
512 if (!repeating_sequence_p (0, encoded_nelts (), npatterns ()))
513 return false;
514
515 unsigned int merge_cost = 1;
516 unsigned int build_merge_mask_cost = 3;
517 unsigned int slide1down_cost = nelts;
518
519 return (build_merge_mask_cost + merge_cost) * npatterns () < slide1down_cost;
520 }
521
522 /* Return true if it's worthwhile to use slideup combine 2 vectors. */
523 bool
524 rvv_builder::combine_sequence_use_slideup_profitable_p ()
525 {
526 int nelts = full_nelts ().to_constant ();
527 int leading_ndups = this->count_dups (0, nelts - 1, 1);
528 int trailing_ndups = this->count_dups (nelts - 1, -1, -1);
529
530 /* ??? Current heuristic we do is we do combine 2 vectors
531 by slideup when:
532 1. # of leading same elements is equal to # of trailing same elements.
533 2. Both of above are equal to nelts / 2.
534 Otherwise, it is not profitable. */
535 return leading_ndups == trailing_ndups && trailing_ndups == nelts / 2;
536 }
537
538 /* Return true if it's worthwhile to use merge combine vector with a scalar. */
539 bool
540 rvv_builder::combine_sequence_use_merge_profitable_p ()
541 {
542 int nelts = full_nelts ().to_constant ();
543 int leading_ndups = this->count_dups (0, nelts - 1, 1);
544 int trailing_ndups = this->count_dups (nelts - 1, -1, -1);
545 int nregs = riscv_get_v_regno_alignment (int_mode ());
546
547 if (leading_ndups + trailing_ndups != nelts)
548 return false;
549
550 /* Leading elements num > 255 which exceeds the maximum value
551 of QImode, we will need to use HImode. */
552 machine_mode mode;
553 if (leading_ndups > 255 || nregs > 2)
554 {
555 if (!get_vector_mode (HImode, nelts).exists (&mode))
556 return false;
557 /* We will need one more AVL/VL toggling vsetvl instruction. */
558 return leading_ndups > 4 && trailing_ndups > 4;
559 }
560
561 /* { a, a, a, b, b, ... , b } and { b, b, b, a, a, ... , a }
562 consume 3 slide instructions. */
563 return leading_ndups > 3 && trailing_ndups > 3;
564 }
565
566 /* Merge the repeating sequence into a single element and return the RTX. */
567 rtx
568 rvv_builder::get_merged_repeating_sequence ()
569 {
570 scalar_int_mode mode = Pmode;
571 rtx target = gen_reg_rtx (mode);
572 emit_move_insn (target, const0_rtx);
573 rtx imm = gen_int_mode ((1ULL << m_inner_bits_size) - 1, mode);
574 /* { a, b, a, b }: Generate duplicate element = b << bits | a. */
575 for (unsigned int i = 0; i < npatterns (); i++)
576 {
577 unsigned int loc = m_inner_bits_size * i;
578 rtx shift = gen_int_mode (loc, mode);
579 rtx ele = gen_lowpart (mode, elt (i));
580 rtx tmp = expand_simple_binop (mode, AND, ele, imm, NULL_RTX, false,
581 OPTAB_DIRECT);
582 rtx tmp2 = expand_simple_binop (mode, ASHIFT, tmp, shift, NULL_RTX, false,
583 OPTAB_DIRECT);
584 rtx tmp3 = expand_simple_binop (mode, IOR, tmp2, target, NULL_RTX, false,
585 OPTAB_DIRECT);
586 emit_move_insn (target, tmp3);
587 }
588 if (GET_MODE_SIZE (m_new_inner_mode) < UNITS_PER_WORD)
589 return gen_lowpart (m_new_inner_mode, target);
590 return target;
591 }
592
593 /* Get the mask for merge approach.
594
595 Consider such following case:
596 {a, b, a, b, a, b, a, b, a, b, a, b, a, b, a, b}
597 To merge "a", the mask should be 1010....
598 To merge "b", the mask should be 0101....
599 */
600 rtx
601 rvv_builder::get_merge_scalar_mask (unsigned int index_in_pattern,
602 machine_mode inner_mode) const
603 {
604 unsigned HOST_WIDE_INT mask = 0;
605 unsigned HOST_WIDE_INT base_mask = (1ULL << index_in_pattern);
606 /* Here we construct a mask pattern that will later be broadcast
607 to a vector register. The maximum broadcast size for vmv.v.x/vmv.s.x
608 is determined by the length of a vector element (ELEN) and not by
609 XLEN so make sure we do not exceed it. One example is -march=zve32*
610 which mandates ELEN == 32 but can be combined with -march=rv64
611 with XLEN == 64. */
612 unsigned int elen = TARGET_VECTOR_ELEN_64 ? 64 : 32;
613
614 gcc_assert (elen % npatterns () == 0);
615
616 int limit = elen / npatterns ();
617
618 for (int i = 0; i < limit; i++)
619 mask |= base_mask << (i * npatterns ());
620
621 return gen_int_mode (mask, inner_mode);
622 }
623
624 /* Return true if the variable-length vector is single step.
625 Single step means step all patterns in NPATTERNS are equal.
626 Consider this following case:
627
628 CASE 1: NPATTERNS = 2, NELTS_PER_PATTERN = 3.
629 { 0, 2, 2, 4, 4, 6, ... }
630 First pattern: step1 = 2 - 0 = 2
631 step2 = 4 - 2 = 2
632 Second pattern: step1 = 4 - 2 = 2
633 step2 = 6 - 4 = 2
634 Since all steps of NPATTERNS are equal step = 2.
635 Return true in this case.
636
637 CASE 2: NPATTERNS = 2, NELTS_PER_PATTERN = 3.
638 { 0, 1, 2, 4, 4, 7, ... }
639 First pattern: step1 = 2 - 0 = 2
640 step2 = 4 - 2 = 2
641 Second pattern: step1 = 4 - 1 = 3
642 step2 = 7 - 4 = 3
643 Since not all steps are equal, return false. */
644 bool
645 rvv_builder::single_step_npatterns_p () const
646 {
647 if (nelts_per_pattern () != 3)
648 return false;
649
650 poly_int64 step
651 = rtx_to_poly_int64 (elt (npatterns ())) - rtx_to_poly_int64 (elt (0));
652 for (unsigned int i = 0; i < npatterns (); i++)
653 {
654 poly_int64 ele0 = rtx_to_poly_int64 (elt (i));
655 poly_int64 ele1 = rtx_to_poly_int64 (elt (npatterns () + i));
656 poly_int64 ele2 = rtx_to_poly_int64 (elt (npatterns () * 2 + i));
657 poly_int64 diff1 = ele1 - ele0;
658 poly_int64 diff2 = ele2 - ele1;
659 if (maybe_ne (step, diff1) || maybe_ne (step, diff2))
660 return false;
661 }
662 return true;
663 }
664
665 /* Return true if the diff between const vector and vid sequence
666 is repeated. For example as below cases:
667 The diff means the const vector - vid.
668 CASE 1:
669 CONST VECTOR: {3, 2, 1, 0, 7, 6, 5, 4, ... }
670 VID : {0, 1, 2, 3, 4, 5, 6, 7, ... }
671 DIFF(MINUS) : {3, 1,-1,-3, 3, 1,-1,-3, ... }
672 The diff sequence {3, 1,-1,-3} is repeated in the npattern and
673 return TRUE for case 1.
674
675 CASE 2:
676 CONST VECTOR: {-4, 4,-3, 5,-2, 6,-1, 7, ...}
677 VID : { 0, 1, 2, 3, 4, 5, 6, 7, ... }
678 DIFF(MINUS) : {-4, 3,-5,-2,-6, 1,-7, 0, ... }
679 The diff sequence {-4, 3} is not repeated in the npattern and
680 return FALSE for case 2. */
681 bool
682 rvv_builder::npatterns_vid_diff_repeated_p () const
683 {
684 if (nelts_per_pattern () != 3)
685 return false;
686 else if (npatterns () == 0)
687 return false;
688
689 for (unsigned i = 0; i < npatterns (); i++)
690 {
691 poly_int64 diff_0 = rtx_to_poly_int64 (elt (i)) - i;
692 poly_int64 diff_1
693 = rtx_to_poly_int64 (elt (npatterns () + i)) - npatterns () - i;
694
695 if (maybe_ne (diff_0, diff_1))
696 return false;
697 }
698
699 return true;
700 }
701
702 /* Return true if the permutation consists of two
703 interleaved patterns with a constant step each.
704 TODO: We currently only support NPATTERNS = 2. */
705 bool
706 rvv_builder::interleaved_stepped_npatterns_p () const
707 {
708 if (npatterns () != 2 || nelts_per_pattern () != 3)
709 return false;
710 for (unsigned int i = 0; i < npatterns (); i++)
711 {
712 poly_int64 ele0 = rtx_to_poly_int64 (elt (i));
713 poly_int64 ele1 = rtx_to_poly_int64 (elt (npatterns () + i));
714 poly_int64 ele2 = rtx_to_poly_int64 (elt (npatterns () * 2 + i));
715 poly_int64 diff1 = ele1 - ele0;
716 poly_int64 diff2 = ele2 - ele1;
717 if (maybe_ne (diff1, diff2))
718 return false;
719 }
720 return true;
721 }
722
723 /* Return true if all elements of NPATTERNS are equal.
724
725 E.g. NPATTERNS = 4:
726 { 2, 2, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 16, 16, 16, 16, ... }
727 E.g. NPATTERNS = 8:
728 { 2, 2, 2, 2, 2, 2, 2, 2, 8, 8, 8, 8, 8, 8, 8, 8, ... }
729 We only check ele[0] ~ ele[NPATTERNS - 1] whether they are the same.
730 We don't need to check the elements[n] with n >= NPATTERNS since
731 they don't belong to the same pattern.
732 */
733 bool
734 rvv_builder::npatterns_all_equal_p () const
735 {
736 poly_int64 ele0 = rtx_to_poly_int64 (elt (0));
737 for (unsigned int i = 1; i < npatterns (); i++)
738 {
739 poly_int64 ele = rtx_to_poly_int64 (elt (i));
740 if (!known_eq (ele, ele0))
741 return false;
742 }
743 return true;
744 }
745
746 static unsigned
747 get_sew (machine_mode mode)
748 {
749 unsigned int sew = GET_MODE_CLASS (mode) == MODE_VECTOR_BOOL
750 ? 8
751 : GET_MODE_BITSIZE (GET_MODE_INNER (mode));
752 return sew;
753 }
754
755 /* Return true if X is a const_vector with all duplicate elements, which is in
756 the range between MINVAL and MAXVAL. */
757 bool
758 const_vec_all_same_in_range_p (rtx x, HOST_WIDE_INT minval,
759 HOST_WIDE_INT maxval)
760 {
761 rtx elt;
762 return (const_vec_duplicate_p (x, &elt) && CONST_INT_P (elt)
763 && IN_RANGE (INTVAL (elt), minval, maxval));
764 }
765
766 /* Return true if VEC is a constant in which every element is in the range
767 [MINVAL, MAXVAL]. The elements do not need to have the same value.
768
769 This function also exists in aarch64, we may unify it in middle-end in the
770 future. */
771
772 static bool
773 const_vec_all_in_range_p (rtx vec, poly_int64 minval, poly_int64 maxval)
774 {
775 if (!CONST_VECTOR_P (vec)
776 || GET_MODE_CLASS (GET_MODE (vec)) != MODE_VECTOR_INT)
777 return false;
778
779 int nunits;
780 if (!CONST_VECTOR_STEPPED_P (vec))
781 nunits = const_vector_encoded_nelts (vec);
782 else if (!CONST_VECTOR_NUNITS (vec).is_constant (&nunits))
783 return false;
784
785 for (int i = 0; i < nunits; i++)
786 {
787 rtx vec_elem = CONST_VECTOR_ELT (vec, i);
788 poly_int64 value;
789 if (!poly_int_rtx_p (vec_elem, &value)
790 || maybe_lt (value, minval)
791 || maybe_gt (value, maxval))
792 return false;
793 }
794 return true;
795 }
796
797 /* Returns true if the vector's elements are all duplicates in
798 range -16 ~ 15 integer or 0.0 floating-point. */
799
800 bool
801 valid_vec_immediate_p (rtx x)
802 {
803 return (satisfies_constraint_vi (x) || satisfies_constraint_Wc0 (x));
804 }
805
806 /* Return a const vector of VAL. The VAL can be either const_int or
807 const_poly_int. */
808
809 static rtx
810 gen_const_vector_dup (machine_mode mode, poly_int64 val)
811 {
812 scalar_mode smode = GET_MODE_INNER (mode);
813 rtx c = gen_int_mode (val, smode);
814 if (!val.is_constant () && GET_MODE_SIZE (smode) > GET_MODE_SIZE (Pmode))
815 {
816 /* When VAL is const_poly_int value, we need to explicitly broadcast
817 it into a vector using RVV broadcast instruction. */
818 return expand_vector_broadcast (mode, c);
819 }
820 return gen_const_vec_duplicate (mode, c);
821 }
822
823 /* Emit a vlmax vsetvl instruction. This should only be used when
824 optimization is disabled or after vsetvl insertion pass. */
825 void
826 emit_hard_vlmax_vsetvl (machine_mode vmode, rtx vl)
827 {
828 unsigned int sew = get_sew (vmode);
829 emit_insn (gen_vsetvl (Pmode, vl, RVV_VLMAX, gen_int_mode (sew, Pmode),
830 gen_int_mode (get_vlmul (vmode), Pmode), const0_rtx,
831 const0_rtx));
832 }
833
834 void
835 emit_vlmax_vsetvl (machine_mode vmode, rtx vl)
836 {
837 unsigned int sew = get_sew (vmode);
838 enum vlmul_type vlmul = get_vlmul (vmode);
839 unsigned int ratio = calculate_ratio (sew, vlmul);
840
841 if (!optimize)
842 emit_hard_vlmax_vsetvl (vmode, vl);
843 else
844 emit_insn (gen_vlmax_avl (Pmode, vl, gen_int_mode (ratio, Pmode)));
845 }
846
847 /* Calculate SEW/LMUL ratio. */
848 unsigned int
849 calculate_ratio (unsigned int sew, enum vlmul_type vlmul)
850 {
851 unsigned int ratio;
852 switch (vlmul)
853 {
854 case LMUL_1:
855 ratio = sew;
856 break;
857 case LMUL_2:
858 ratio = sew / 2;
859 break;
860 case LMUL_4:
861 ratio = sew / 4;
862 break;
863 case LMUL_8:
864 ratio = sew / 8;
865 break;
866 case LMUL_F8:
867 ratio = sew * 8;
868 break;
869 case LMUL_F4:
870 ratio = sew * 4;
871 break;
872 case LMUL_F2:
873 ratio = sew * 2;
874 break;
875 default:
876 gcc_unreachable ();
877 }
878 return ratio;
879 }
880
881 /* SCALABLE means that the vector-length is agnostic (run-time invariant and
882 compile-time unknown). ZVL means that the vector-length is specific
883 (compile-time known by march like zvl*b). Both SCALABLE and ZVL are doing
884 auto-vectorization using VLMAX vsetvl configuration. */
885 static bool
886 autovec_use_vlmax_p (void)
887 {
888 return rvv_vector_bits == RVV_VECTOR_BITS_SCALABLE
889 || rvv_vector_bits == RVV_VECTOR_BITS_ZVL;
890 }
891
892 /* This function emits VLMAX vrgather instruction. Emit vrgather.vx/vi when sel
893 is a const duplicate vector. Otherwise, emit vrgather.vv. */
894 static void
895 emit_vlmax_gather_insn (rtx target, rtx op, rtx sel)
896 {
897 rtx elt;
898 insn_code icode;
899 machine_mode data_mode = GET_MODE (target);
900 machine_mode sel_mode = GET_MODE (sel);
901 if (const_vec_duplicate_p (sel, &elt))
902 {
903 icode = code_for_pred_gather_scalar (data_mode);
904 sel = elt;
905 }
906 else if (maybe_ne (GET_MODE_SIZE (data_mode), GET_MODE_SIZE (sel_mode)))
907 icode = code_for_pred_gatherei16 (data_mode);
908 else
909 icode = code_for_pred_gather (data_mode);
910 rtx ops[] = {target, op, sel};
911 emit_vlmax_insn (icode, BINARY_OP, ops);
912 }
913
914 static void
915 emit_vlmax_masked_gather_mu_insn (rtx target, rtx op, rtx sel, rtx mask)
916 {
917 rtx elt;
918 insn_code icode;
919 machine_mode data_mode = GET_MODE (target);
920 machine_mode sel_mode = GET_MODE (sel);
921 if (const_vec_duplicate_p (sel, &elt))
922 {
923 icode = code_for_pred_gather_scalar (data_mode);
924 sel = elt;
925 }
926 else if (maybe_ne (GET_MODE_SIZE (data_mode), GET_MODE_SIZE (sel_mode)))
927 icode = code_for_pred_gatherei16 (data_mode);
928 else
929 icode = code_for_pred_gather (data_mode);
930 rtx ops[] = {target, mask, target, op, sel};
931 emit_vlmax_insn (icode, BINARY_OP_TAMU, ops);
932 }
933
934 /* According to RVV ISA spec (16.5.1. Synthesizing vdecompress):
935 https://github.com/riscv/riscv-v-spec/blob/master/v-spec.adoc
936
937 There is no inverse vdecompress provided, as this operation can be readily
938 synthesized using iota and a masked vrgather:
939
940 Desired functionality of 'vdecompress'
941 7 6 5 4 3 2 1 0 # vid
942
943 e d c b a # packed vector of 5 elements
944 1 0 0 1 1 1 0 1 # mask vector of 8 elements
945 p q r s t u v w # destination register before vdecompress
946
947 e q r d c b v a # result of vdecompress
948 # v0 holds mask
949 # v1 holds packed data
950 # v11 holds input expanded vector and result
951 viota.m v10, v0 # Calc iota from mask in v0
952 vrgather.vv v11, v1, v10, v0.t # Expand into destination
953 p q r s t u v w # v11 destination register
954 e d c b a # v1 source vector
955 1 0 0 1 1 1 0 1 # v0 mask vector
956
957 4 4 4 3 2 1 1 0 # v10 result of viota.m
958 e q r d c b v a # v11 destination after vrgather using viota.m under mask
959 */
960 static void
961 emit_vlmax_decompress_insn (rtx target, rtx op0, rtx op1, rtx mask)
962 {
963 machine_mode data_mode = GET_MODE (target);
964 machine_mode sel_mode = related_int_vector_mode (data_mode).require ();
965 if (GET_MODE_INNER (data_mode) == QImode)
966 sel_mode = get_vector_mode (HImode, GET_MODE_NUNITS (data_mode)).require ();
967
968 rtx sel = gen_reg_rtx (sel_mode);
969 rtx iota_ops[] = {sel, mask};
970 emit_vlmax_insn (code_for_pred_iota (sel_mode), UNARY_OP, iota_ops);
971 emit_vlmax_gather_insn (target, op0, sel);
972 emit_vlmax_masked_gather_mu_insn (target, op1, sel, mask);
973 }
974
975 /* Emit merge instruction. */
976
977 static machine_mode
978 get_repeating_sequence_dup_machine_mode (const rvv_builder &builder,
979 machine_mode mask_bit_mode)
980 {
981 unsigned mask_precision = GET_MODE_PRECISION (mask_bit_mode).to_constant ();
982 unsigned mask_scalar_size = mask_precision > builder.inner_bits_size ()
983 ? builder.inner_bits_size () : mask_precision;
984
985 scalar_mode inner_mode;
986 unsigned minimal_bits_size;
987
988 switch (mask_scalar_size)
989 {
990 case 8:
991 inner_mode = QImode;
992 minimal_bits_size = TARGET_MIN_VLEN / 8; /* AKA RVVMF8. */
993 break;
994 case 16:
995 inner_mode = HImode;
996 minimal_bits_size = TARGET_MIN_VLEN / 4; /* AKA RVVMF4. */
997 break;
998 case 32:
999 inner_mode = SImode;
1000 minimal_bits_size = TARGET_MIN_VLEN / 2; /* AKA RVVMF2. */
1001 break;
1002 case 64:
1003 inner_mode = DImode;
1004 minimal_bits_size = TARGET_MIN_VLEN / 1; /* AKA RVVM1. */
1005 break;
1006 default:
1007 gcc_unreachable ();
1008 break;
1009 }
1010
1011 gcc_assert (mask_precision % mask_scalar_size == 0);
1012
1013 uint64_t dup_nunit = mask_precision > mask_scalar_size
1014 ? mask_precision / mask_scalar_size : minimal_bits_size / mask_scalar_size;
1015
1016 return get_vector_mode (inner_mode, dup_nunit).require ();
1017 }
1018
1019 /* Expand series const vector. If VID is NULL_RTX, we use vid.v
1020 instructions to generate sequence for VID:
1021
1022 VID = { 0, 1, 2, 3, ... }
1023
1024 Otherwise, we use the VID argument directly. */
1025
1026 void
1027 expand_vec_series (rtx dest, rtx base, rtx step, rtx vid)
1028 {
1029 machine_mode mode = GET_MODE (dest);
1030 poly_int64 nunits_m1 = GET_MODE_NUNITS (mode) - 1;
1031 poly_int64 value;
1032 rtx result = register_operand (dest, mode) ? dest : gen_reg_rtx (mode);
1033
1034 /* VECT_IV = BASE + I * STEP. */
1035
1036 /* Step 1: Generate I = { 0, 1, 2, ... } by vid.v. */
1037 bool reverse_p = !vid && rtx_equal_p (step, constm1_rtx)
1038 && poly_int_rtx_p (base, &value)
1039 && known_eq (nunits_m1, value);
1040 if (!vid)
1041 {
1042 vid = gen_reg_rtx (mode);
1043 rtx op[] = {vid};
1044 emit_vlmax_insn (code_for_pred_series (mode), NULLARY_OP, op);
1045 }
1046
1047 rtx step_adj;
1048 if (reverse_p)
1049 {
1050 /* Special case:
1051 {nunits - 1, nunits - 2, ... , 0}.
1052 nunits can be either const_int or const_poly_int.
1053
1054 Code sequence:
1055 vid.v v
1056 vrsub nunits - 1, v. */
1057 rtx ops[]
1058 = {result, vid, gen_int_mode (nunits_m1, GET_MODE_INNER (mode))};
1059 insn_code icode = code_for_pred_sub_reverse_scalar (mode);
1060 emit_vlmax_insn (icode, BINARY_OP, ops);
1061 }
1062 else
1063 {
1064 /* Step 2: Generate I * STEP.
1065 - STEP is 1, we don't emit any instructions.
1066 - STEP is power of 2, we use vsll.vi/vsll.vx.
1067 - STEP is non-power of 2, we use vmul.vx. */
1068 if (rtx_equal_p (step, const1_rtx))
1069 step_adj = vid;
1070 else
1071 {
1072 step_adj = gen_reg_rtx (mode);
1073 if (CONST_INT_P (step) && pow2p_hwi (INTVAL (step)))
1074 {
1075 /* Emit logical left shift operation. */
1076 int shift = exact_log2 (INTVAL (step));
1077 rtx shift_amount = gen_int_mode (shift, Pmode);
1078 insn_code icode = code_for_pred_scalar (ASHIFT, mode);
1079 rtx ops[] = {step_adj, vid, shift_amount};
1080 emit_vlmax_insn (icode, BINARY_OP, ops);
1081 }
1082 else
1083 {
1084 insn_code icode = code_for_pred_scalar (MULT, mode);
1085 rtx ops[] = {step_adj, vid, step};
1086 emit_vlmax_insn (icode, BINARY_OP, ops);
1087 }
1088 }
1089
1090 /* Step 3: Generate BASE + I * STEP.
1091 - BASE is 0, use result of vid.
1092 - BASE is not 0, we use vadd.vx/vadd.vi. */
1093 if (rtx_equal_p (base, const0_rtx))
1094 emit_move_insn (result, step_adj);
1095 else
1096 {
1097 insn_code icode = code_for_pred_scalar (PLUS, mode);
1098 rtx ops[] = {result, step_adj, base};
1099 emit_vlmax_insn (icode, BINARY_OP, ops);
1100 }
1101 }
1102
1103 if (result != dest)
1104 emit_move_insn (dest, result);
1105 }
1106
1107 /* Subroutine of riscv_vector_expand_vector_init.
1108 Works as follows:
1109 (a) Initialize TARGET by broadcasting element NELTS_REQD - 1 of BUILDER.
1110 (b) Skip leading elements from BUILDER, which are the same as
1111 element NELTS_REQD - 1.
1112 (c) Insert earlier elements in reverse order in TARGET using vslide1down. */
1113
1114 static void
1115 expand_vector_init_insert_elems (rtx target, const rvv_builder &builder,
1116 int nelts_reqd)
1117 {
1118 machine_mode mode = GET_MODE (target);
1119 rtx dup = expand_vector_broadcast (mode, builder.elt (0));
1120 emit_move_insn (target, dup);
1121 int ndups = builder.count_dups (0, nelts_reqd - 1, 1);
1122 for (int i = ndups; i < nelts_reqd; i++)
1123 {
1124 unsigned int unspec
1125 = FLOAT_MODE_P (mode) ? UNSPEC_VFSLIDE1DOWN : UNSPEC_VSLIDE1DOWN;
1126 insn_code icode = code_for_pred_slide (unspec, mode);
1127 rtx ops[] = {target, target, builder.elt (i)};
1128 emit_vlmax_insn (icode, BINARY_OP, ops);
1129 }
1130 }
1131
1132 /* Subroutine of expand_vec_init to handle case
1133 when all trailing elements of builder are same.
1134 This works as follows:
1135 (a) Use expand_insn interface to broadcast last vector element in TARGET.
1136 (b) Insert remaining elements in TARGET using insr.
1137
1138 ??? The heuristic used is to do above if number of same trailing elements
1139 is greater than leading_ndups, loosely based on
1140 heuristic from mostly_zeros_p. May need fine-tuning. */
1141
1142 static bool
1143 expand_vector_init_trailing_same_elem (rtx target,
1144 const rtx_vector_builder &builder,
1145 int nelts_reqd)
1146 {
1147 int leading_ndups = builder.count_dups (0, nelts_reqd - 1, 1);
1148 int trailing_ndups = builder.count_dups (nelts_reqd - 1, -1, -1);
1149 machine_mode mode = GET_MODE (target);
1150
1151 if (trailing_ndups > leading_ndups)
1152 {
1153 rtx dup = expand_vector_broadcast (mode, builder.elt (nelts_reqd - 1));
1154 for (int i = nelts_reqd - trailing_ndups - 1; i >= 0; i--)
1155 {
1156 unsigned int unspec
1157 = FLOAT_MODE_P (mode) ? UNSPEC_VFSLIDE1UP : UNSPEC_VSLIDE1UP;
1158 insn_code icode = code_for_pred_slide (unspec, mode);
1159 rtx tmp = gen_reg_rtx (mode);
1160 rtx ops[] = {tmp, dup, builder.elt (i)};
1161 emit_vlmax_insn (icode, BINARY_OP, ops);
1162 /* slide1up need source and dest to be different REG. */
1163 dup = tmp;
1164 }
1165
1166 emit_move_insn (target, dup);
1167 return true;
1168 }
1169
1170 return false;
1171 }
1172
1173 static void
1174 expand_const_vector (rtx target, rtx src)
1175 {
1176 machine_mode mode = GET_MODE (target);
1177 rtx result = register_operand (target, mode) ? target : gen_reg_rtx (mode);
1178 rtx elt;
1179 if (const_vec_duplicate_p (src, &elt))
1180 {
1181 if (GET_MODE_CLASS (mode) == MODE_VECTOR_BOOL)
1182 {
1183 gcc_assert (rtx_equal_p (elt, const0_rtx)
1184 || rtx_equal_p (elt, const1_rtx));
1185 rtx ops[] = {result, src};
1186 emit_vlmax_insn (code_for_pred_mov (mode), UNARY_MASK_OP, ops);
1187 }
1188 /* Element in range -16 ~ 15 integer or 0.0 floating-point,
1189 we use vmv.v.i instruction. */
1190 else if (valid_vec_immediate_p (src))
1191 {
1192 rtx ops[] = {result, src};
1193 emit_vlmax_insn (code_for_pred_mov (mode), UNARY_OP, ops);
1194 }
1195 else
1196 {
1197 /* Emit vec_duplicate<mode> split pattern before RA so that
1198 we could have a better optimization opportunity in LICM
1199 which will hoist vmv.v.x outside the loop and in fwprop && combine
1200 which will transform 'vv' into 'vx' instruction.
1201
1202 The reason we don't emit vec_duplicate<mode> split pattern during
1203 RA since the split stage after RA is a too late stage to generate
1204 RVV instruction which need an additional register (We can't
1205 allocate a new register after RA) for VL operand of vsetvl
1206 instruction (vsetvl a5, zero). */
1207 if (lra_in_progress)
1208 {
1209 rtx ops[] = {result, elt};
1210 emit_vlmax_insn (code_for_pred_broadcast (mode), UNARY_OP, ops);
1211 }
1212 else
1213 {
1214 struct expand_operand ops[2];
1215 enum insn_code icode = optab_handler (vec_duplicate_optab, mode);
1216 gcc_assert (icode != CODE_FOR_nothing);
1217 create_output_operand (&ops[0], result, mode);
1218 create_input_operand (&ops[1], elt, GET_MODE_INNER (mode));
1219 expand_insn (icode, 2, ops);
1220 result = ops[0].value;
1221 }
1222 }
1223
1224 if (result != target)
1225 emit_move_insn (target, result);
1226 return;
1227 }
1228
1229 /* Support scalable const series vector. */
1230 rtx base, step;
1231 if (const_vec_series_p (src, &base, &step))
1232 {
1233 expand_vec_series (result, base, step);
1234
1235 if (result != target)
1236 emit_move_insn (target, result);
1237 return;
1238 }
1239
1240 /* Handle variable-length vector. */
1241 unsigned int nelts_per_pattern = CONST_VECTOR_NELTS_PER_PATTERN (src);
1242 unsigned int npatterns = CONST_VECTOR_NPATTERNS (src);
1243 rvv_builder builder (mode, npatterns, nelts_per_pattern);
1244 for (unsigned int i = 0; i < nelts_per_pattern; i++)
1245 {
1246 for (unsigned int j = 0; j < npatterns; j++)
1247 builder.quick_push (CONST_VECTOR_ELT (src, i * npatterns + j));
1248 }
1249 builder.finalize ();
1250
1251 if (CONST_VECTOR_DUPLICATE_P (src))
1252 {
1253 /* Handle the case with repeating sequence that NELTS_PER_PATTERN = 1
1254 E.g. NPATTERNS = 4, v = { 0, 2, 6, 7, ... }
1255 NPATTERNS = 8, v = { 0, 2, 6, 7, 19, 20, 8, 7 ... }
1256 The elements within NPATTERNS are not necessary regular. */
1257 if (builder.can_duplicate_repeating_sequence_p ())
1258 {
1259 /* We handle the case that we can find a vector container to hold
1260 element bitsize = NPATTERNS * ele_bitsize.
1261
1262 NPATTERNS = 8, element width = 8
1263 v = { 0, 1, 2, 3, 4, 5, 6, 7, ... }
1264 In this case, we can combine NPATTERNS element into a larger
1265 element. Use element width = 64 and broadcast a vector with
1266 all element equal to 0x0706050403020100. */
1267 rtx ele = builder.get_merged_repeating_sequence ();
1268 rtx dup;
1269 if (lra_in_progress)
1270 {
1271 dup = gen_reg_rtx (builder.new_mode ());
1272 rtx ops[] = {dup, ele};
1273 emit_vlmax_insn (code_for_pred_broadcast
1274 (builder.new_mode ()), UNARY_OP, ops);
1275 }
1276 else
1277 dup = expand_vector_broadcast (builder.new_mode (), ele);
1278 emit_move_insn (result, gen_lowpart (mode, dup));
1279 }
1280 else
1281 {
1282 /* We handle the case that we can't find a vector container to hold
1283 element bitsize = NPATTERNS * ele_bitsize.
1284
1285 NPATTERNS = 8, element width = 16
1286 v = { 0, 1, 2, 3, 4, 5, 6, 7, ... }
1287 Since NPATTERNS * element width = 128, we can't find a container
1288 to hold it.
1289
1290 In this case, we use NPATTERNS merge operations to generate such
1291 vector. */
1292 unsigned int nbits = npatterns - 1;
1293
1294 /* Generate vid = { 0, 1, 2, 3, 4, 5, 6, 7, ... }. */
1295 rtx vid = gen_reg_rtx (builder.int_mode ());
1296 rtx op[] = {vid};
1297 emit_vlmax_insn (code_for_pred_series (builder.int_mode ()),
1298 NULLARY_OP, op);
1299
1300 /* Generate vid_repeat = { 0, 1, ... nbits, ... } */
1301 rtx vid_repeat = gen_reg_rtx (builder.int_mode ());
1302 rtx and_ops[] = {vid_repeat, vid,
1303 gen_int_mode (nbits, builder.inner_int_mode ())};
1304 emit_vlmax_insn (code_for_pred_scalar (AND, builder.int_mode ()),
1305 BINARY_OP, and_ops);
1306
1307 rtx tmp1 = gen_reg_rtx (builder.mode ());
1308 rtx dup_ops[] = {tmp1, builder.elt (0)};
1309 emit_vlmax_insn (code_for_pred_broadcast (builder.mode ()), UNARY_OP,
1310 dup_ops);
1311 for (unsigned int i = 1; i < builder.npatterns (); i++)
1312 {
1313 /* Generate mask according to i. */
1314 rtx mask = gen_reg_rtx (builder.mask_mode ());
1315 rtx const_vec = gen_const_vector_dup (builder.int_mode (), i);
1316 expand_vec_cmp (mask, EQ, vid_repeat, const_vec);
1317
1318 /* Merge scalar to each i. */
1319 rtx tmp2 = gen_reg_rtx (builder.mode ());
1320 rtx merge_ops[] = {tmp2, tmp1, builder.elt (i), mask};
1321 insn_code icode = code_for_pred_merge_scalar (builder.mode ());
1322 emit_vlmax_insn (icode, MERGE_OP, merge_ops);
1323 tmp1 = tmp2;
1324 }
1325 emit_move_insn (result, tmp1);
1326 }
1327 }
1328 else if (CONST_VECTOR_STEPPED_P (src))
1329 {
1330 gcc_assert (GET_MODE_CLASS (mode) == MODE_VECTOR_INT);
1331 if (builder.single_step_npatterns_p ())
1332 {
1333 /* Describe the case by choosing NPATTERNS = 4 as an example. */
1334 insn_code icode;
1335
1336 /* Step 1: Generate vid = { 0, 1, 2, 3, 4, 5, 6, 7, ... }. */
1337 rtx vid = gen_reg_rtx (builder.mode ());
1338 rtx vid_ops[] = {vid};
1339 icode = code_for_pred_series (builder.mode ());
1340 emit_vlmax_insn (icode, NULLARY_OP, vid_ops);
1341
1342 if (builder.npatterns_all_equal_p ())
1343 {
1344 /* Generate the variable-length vector following this rule:
1345 { a, a, a + step, a + step, a + step * 2, a + step * 2, ...}
1346 E.g. { 0, 0, 8, 8, 16, 16, ... } */
1347
1348 /* We want to create a pattern where value[idx] = floor (idx /
1349 NPATTERNS). As NPATTERNS is always a power of two we can
1350 rewrite this as = idx & -NPATTERNS. */
1351 /* Step 2: VID AND -NPATTERNS:
1352 { 0&-4, 1&-4, 2&-4, 3 &-4, 4 &-4, 5 &-4, 6 &-4, 7 &-4, ... }
1353 */
1354 rtx imm
1355 = gen_int_mode (-builder.npatterns (), builder.inner_mode ());
1356 rtx tmp1 = gen_reg_rtx (builder.mode ());
1357 rtx and_ops[] = {tmp1, vid, imm};
1358 icode = code_for_pred_scalar (AND, builder.mode ());
1359 emit_vlmax_insn (icode, BINARY_OP, and_ops);
1360
1361 /* Step 3: Convert to step size 1. */
1362 rtx tmp2 = gen_reg_rtx (builder.mode ());
1363 /* log2 (npatterns) to get the shift amount to convert
1364 Eg. { 0, 0, 0, 0, 4, 4, ... }
1365 into { 0, 0, 0, 0, 1, 1, ... }. */
1366 HOST_WIDE_INT shift_amt = exact_log2 (builder.npatterns ()) ;
1367 rtx shift = gen_int_mode (shift_amt, builder.inner_mode ());
1368 rtx shift_ops[] = {tmp2, tmp1, shift};
1369 icode = code_for_pred_scalar (ASHIFTRT, builder.mode ());
1370 emit_vlmax_insn (icode, BINARY_OP, shift_ops);
1371
1372 /* Step 4: Multiply to step size n. */
1373 HOST_WIDE_INT step_size =
1374 INTVAL (builder.elt (builder.npatterns ()))
1375 - INTVAL (builder.elt (0));
1376 rtx tmp3 = gen_reg_rtx (builder.mode ());
1377 if (pow2p_hwi (step_size))
1378 {
1379 /* Power of 2 can be handled with a left shift. */
1380 HOST_WIDE_INT shift = exact_log2 (step_size);
1381 rtx shift_amount = gen_int_mode (shift, Pmode);
1382 insn_code icode = code_for_pred_scalar (ASHIFT, mode);
1383 rtx ops[] = {tmp3, tmp2, shift_amount};
1384 emit_vlmax_insn (icode, BINARY_OP, ops);
1385 }
1386 else
1387 {
1388 rtx mult_amt = gen_int_mode (step_size, builder.inner_mode ());
1389 insn_code icode = code_for_pred_scalar (MULT, builder.mode ());
1390 rtx ops[] = {tmp3, tmp2, mult_amt};
1391 emit_vlmax_insn (icode, BINARY_OP, ops);
1392 }
1393
1394 /* Step 5: Add starting value to all elements. */
1395 HOST_WIDE_INT init_val = INTVAL (builder.elt (0));
1396 if (init_val == 0)
1397 emit_move_insn (result, tmp3);
1398 else
1399 {
1400 rtx dup = gen_const_vector_dup (builder.mode (), init_val);
1401 rtx add_ops[] = {result, tmp3, dup};
1402 icode = code_for_pred (PLUS, builder.mode ());
1403 emit_vlmax_insn (icode, BINARY_OP, add_ops);
1404 }
1405 }
1406 else
1407 {
1408 /* Generate the variable-length vector following this rule:
1409 { a, b, a + step, b + step, a + step*2, b + step*2, ... } */
1410
1411 if (builder.npatterns_vid_diff_repeated_p ())
1412 {
1413 /* Case 1: For example as below:
1414 {3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8... }
1415 We have 3 - 0 = 3 equals 7 - 4 = 3, the sequence is
1416 repeated as below after minus vid.
1417 {3, 1, -1, -3, 3, 1, -1, -3...}
1418 Then we can simplify the diff code gen to at most
1419 npatterns(). */
1420 rvv_builder v (builder.mode (), builder.npatterns (), 1);
1421
1422 /* Step 1: Generate diff = TARGET - VID. */
1423 for (unsigned int i = 0; i < v.npatterns (); ++i)
1424 {
1425 poly_int64 diff = rtx_to_poly_int64 (builder.elt (i)) - i;
1426 v.quick_push (gen_int_mode (diff, v.inner_mode ()));
1427 }
1428
1429 /* Step 2: Generate result = VID + diff. */
1430 rtx vec = v.build ();
1431 rtx add_ops[] = {result, vid, vec};
1432 emit_vlmax_insn (code_for_pred (PLUS, builder.mode ()),
1433 BINARY_OP, add_ops);
1434 }
1435 else
1436 {
1437 /* Case 2: For example as below:
1438 { -4, 4, -4 + 1, 4 + 1, -4 + 2, 4 + 2, -4 + 3, 4 + 3, ... }
1439 */
1440 rvv_builder v (builder.mode (), builder.npatterns (), 1);
1441
1442 /* Step 1: Generate { a, b, a, b, ... } */
1443 for (unsigned int i = 0; i < v.npatterns (); ++i)
1444 v.quick_push (builder.elt (i));
1445 rtx new_base = v.build ();
1446
1447 /* Step 2: Generate tmp1 = VID >> LOG2 (NPATTERNS).  */
1448 rtx shift_count
1449 = gen_int_mode (exact_log2 (builder.npatterns ()),
1450 builder.inner_mode ());
1451 rtx tmp1 = gen_reg_rtx (builder.mode ());
1452 rtx shift_ops[] = {tmp1, vid, shift_count};
1453 emit_vlmax_insn (code_for_pred_scalar
1454 (LSHIFTRT, builder.mode ()), BINARY_OP,
1455 shift_ops);
1456
1457 /* Step 3: Generate tmp2 = tmp1 * step.  */
1458 rtx tmp2 = gen_reg_rtx (builder.mode ());
1459 rtx step
1460 = simplify_binary_operation (MINUS, builder.inner_mode (),
1461 builder.elt (v.npatterns()),
1462 builder.elt (0));
1463 expand_vec_series (tmp2, const0_rtx, step, tmp1);
1464
1465 /* Step 4: Generate result = tmp2 + new_base.  */
1466 rtx add_ops[] = {result, tmp2, new_base};
1467 emit_vlmax_insn (code_for_pred (PLUS, builder.mode ()),
1468 BINARY_OP, add_ops);
1469 }
1470 }
1471 }
1472 else if (builder.interleaved_stepped_npatterns_p ())
1473 {
1474 rtx base1 = builder.elt (0);
1475 rtx base2 = builder.elt (1);
1476 poly_int64 step1
1477 = rtx_to_poly_int64 (builder.elt (builder.npatterns ()))
1478 - rtx_to_poly_int64 (base1);
1479 poly_int64 step2
1480 = rtx_to_poly_int64 (builder.elt (builder.npatterns () + 1))
1481 - rtx_to_poly_int64 (base2);
1482
1483 rtx vid = gen_reg_rtx (mode);
1484 expand_vec_series (vid, const0_rtx, const1_rtx);
1485 /* Transform into { 0, 0, 1, 1, 2, 2, ... }. */
1486 rtx shifted_vid;
1487 if (lra_in_progress)
1488 {
1489 shifted_vid = gen_reg_rtx (mode);
1490 rtx shift = gen_int_mode (1, Xmode);
1491 rtx shift_ops[] = {shifted_vid, vid, shift};
1492 emit_vlmax_insn (code_for_pred_scalar
1493 (LSHIFTRT, mode), BINARY_OP,
1494 shift_ops);
1495 }
1496 else
1497 shifted_vid = expand_simple_binop (mode, LSHIFTRT, vid,
1498 const1_rtx, NULL_RTX,
1499 false, OPTAB_DIRECT);
1500 rtx tmp1 = gen_reg_rtx (mode);
1501 rtx tmp2 = gen_reg_rtx (mode);
1502 expand_vec_series (tmp1, base1,
1503 gen_int_mode (step1, builder.inner_mode ()),
1504 shifted_vid);
1505 expand_vec_series (tmp2, base2,
1506 gen_int_mode (step2, builder.inner_mode ()),
1507 shifted_vid);
1508
1509 /* Transform into { 0, 1, 0, 1, 0, 1, ... }. */
1510 rtx and_vid = gen_reg_rtx (mode);
1511 rtx and_ops[] = {and_vid, vid, const1_rtx};
1512 emit_vlmax_insn (code_for_pred_scalar (AND, mode), BINARY_OP,
1513 and_ops);
1514 rtx mask = gen_reg_rtx (builder.mask_mode ());
1515 expand_vec_cmp (mask, EQ, and_vid, CONST1_RTX (mode));
1516
1517 rtx ops[] = {result, tmp1, tmp2, mask};
1518 emit_vlmax_insn (code_for_pred_merge (mode), MERGE_OP, ops);
1519 }
1520 else
1521 /* TODO: We will enable more variable-length vector in the future. */
1522 gcc_unreachable ();
1523 }
1524 else
1525 gcc_unreachable ();
1526
1527 if (result != target)
1528 emit_move_insn (target, result);
1529 }
1530
1531 /* Get the frm mode with given CONST_INT rtx, the default mode is
1532 FRM_DYN. */
1533 enum floating_point_rounding_mode
1534 get_frm_mode (rtx operand)
1535 {
1536 gcc_assert (CONST_INT_P (operand));
1537
1538 switch (INTVAL (operand))
1539 {
1540 case FRM_RNE:
1541 return FRM_RNE;
1542 case FRM_RTZ:
1543 return FRM_RTZ;
1544 case FRM_RDN:
1545 return FRM_RDN;
1546 case FRM_RUP:
1547 return FRM_RUP;
1548 case FRM_RMM:
1549 return FRM_RMM;
1550 case FRM_DYN:
1551 return FRM_DYN;
1552 default:
1553 gcc_unreachable ();
1554 }
1555
1556 gcc_unreachable ();
1557 }
1558
1559 /* Expand a pre-RA RVV data move from SRC to DEST.
1560 It expands move for RVV fractional vector modes.
1561 Return true if the move as already been emitted. */
1562 bool
1563 legitimize_move (rtx dest, rtx *srcp)
1564 {
1565 rtx src = *srcp;
1566 machine_mode mode = GET_MODE (dest);
1567 if (CONST_VECTOR_P (src))
1568 {
1569 expand_const_vector (dest, src);
1570 return true;
1571 }
1572
1573 if (riscv_v_ext_vls_mode_p (mode))
1574 {
1575 if (GET_MODE_NUNITS (mode).to_constant () <= 31)
1576 {
1577 /* For NUNITS <= 31 VLS modes, we don't need extract
1578 scalar registers so we apply the naive (set (op0) (op1)) pattern. */
1579 if (can_create_pseudo_p ())
1580 {
1581 /* Need to force register if mem <- !reg. */
1582 if (MEM_P (dest) && !REG_P (src))
1583 *srcp = force_reg (mode, src);
1584
1585 return false;
1586 }
1587 }
1588 else if (GET_MODE_NUNITS (mode).to_constant () > 31 && lra_in_progress)
1589 {
1590 emit_insn (gen_mov_lra (mode, Pmode, dest, src));
1591 return true;
1592 }
1593 }
1594 else
1595 {
1596 /* In order to decrease the memory traffic, we don't use whole register
1597 * load/store for the LMUL less than 1 and mask mode, so those case will
1598 * require one extra general purpose register, but it's not allowed during
1599 * LRA process, so we have a special move pattern used for LRA, which will
1600 * defer the expansion after LRA. */
1601 if ((known_lt (GET_MODE_SIZE (mode), BYTES_PER_RISCV_VECTOR)
1602 || GET_MODE_CLASS (mode) == MODE_VECTOR_BOOL)
1603 && lra_in_progress)
1604 {
1605 emit_insn (gen_mov_lra (mode, Pmode, dest, src));
1606 return true;
1607 }
1608
1609 if (known_ge (GET_MODE_SIZE (mode), BYTES_PER_RISCV_VECTOR)
1610 && GET_MODE_CLASS (mode) != MODE_VECTOR_BOOL)
1611 {
1612 /* Need to force register if mem <- !reg. */
1613 if (MEM_P (dest) && !REG_P (src))
1614 *srcp = force_reg (mode, src);
1615
1616 return false;
1617 }
1618 }
1619
1620 if (register_operand (src, mode) && register_operand (dest, mode))
1621 {
1622 emit_insn (gen_rtx_SET (dest, src));
1623 return true;
1624 }
1625
1626 unsigned insn_flags
1627 = GET_MODE_CLASS (mode) == MODE_VECTOR_BOOL ? UNARY_MASK_OP : UNARY_OP;
1628 if (!register_operand (src, mode) && !register_operand (dest, mode))
1629 {
1630 rtx tmp = gen_reg_rtx (mode);
1631 if (MEM_P (src))
1632 {
1633 rtx ops[] = {tmp, src};
1634 emit_vlmax_insn (code_for_pred_mov (mode), insn_flags, ops);
1635 }
1636 else
1637 emit_move_insn (tmp, src);
1638 src = tmp;
1639 }
1640
1641 if (satisfies_constraint_vu (src))
1642 return false;
1643
1644 rtx ops[] = {dest, src};
1645 emit_vlmax_insn (code_for_pred_mov (mode), insn_flags, ops);
1646 return true;
1647 }
1648
1649 /* VTYPE information for machine_mode. */
1650 struct mode_vtype_group
1651 {
1652 enum vlmul_type vlmul[NUM_MACHINE_MODES];
1653 uint8_t ratio[NUM_MACHINE_MODES];
1654 machine_mode subpart_mode[NUM_MACHINE_MODES];
1655 uint8_t nf[NUM_MACHINE_MODES];
1656 mode_vtype_group ()
1657 {
1658 #define ENTRY(MODE, REQUIREMENT, VLMUL, RATIO) \
1659 vlmul[MODE##mode] = VLMUL; \
1660 ratio[MODE##mode] = RATIO;
1661 #define TUPLE_ENTRY(MODE, REQUIREMENT, SUBPART_MODE, NF, VLMUL, RATIO) \
1662 subpart_mode[MODE##mode] = SUBPART_MODE##mode; \
1663 nf[MODE##mode] = NF; \
1664 vlmul[MODE##mode] = VLMUL; \
1665 ratio[MODE##mode] = RATIO;
1666 #include "riscv-vector-switch.def"
1667 #undef ENTRY
1668 #undef TUPLE_ENTRY
1669 }
1670 };
1671
1672 static mode_vtype_group mode_vtype_infos;
1673
1674 /* Get vlmul field value by comparing LMUL with BYTES_PER_RISCV_VECTOR. */
1675 enum vlmul_type
1676 get_vlmul (machine_mode mode)
1677 {
1678 /* For VLS modes, the vlmul should be dynamically
1679 calculated since we need to adjust VLMUL according
1680 to TARGET_MIN_VLEN. */
1681 if (riscv_v_ext_vls_mode_p (mode))
1682 {
1683 int size = GET_MODE_BITSIZE (mode).to_constant ();
1684 int inner_size = GET_MODE_BITSIZE (GET_MODE_INNER (mode));
1685 if (size < TARGET_MIN_VLEN)
1686 {
1687 /* Follow rule LMUL >= SEW / ELEN. */
1688 int elen = TARGET_VECTOR_ELEN_64 ? 1 : 2;
1689 int factor = TARGET_MIN_VLEN / size;
1690 if (inner_size == 8)
1691 factor = MIN (factor, 8 / elen);
1692 else if (inner_size == 16)
1693 factor = MIN (factor, 4 / elen);
1694 else if (inner_size == 32)
1695 factor = MIN (factor, 2 / elen);
1696 else if (inner_size == 64)
1697 factor = MIN (factor, 1);
1698 else
1699 gcc_unreachable ();
1700
1701 switch (factor)
1702 {
1703 case 1:
1704 return LMUL_1;
1705 case 2:
1706 return LMUL_F2;
1707 case 4:
1708 return LMUL_F4;
1709 case 8:
1710 return LMUL_F8;
1711
1712 default:
1713 gcc_unreachable ();
1714 }
1715 }
1716 else
1717 {
1718 int factor = size / TARGET_MIN_VLEN;
1719 switch (factor)
1720 {
1721 case 1:
1722 return LMUL_1;
1723 case 2:
1724 return LMUL_2;
1725 case 4:
1726 return LMUL_4;
1727 case 8:
1728 return LMUL_8;
1729
1730 default:
1731 gcc_unreachable ();
1732 }
1733 }
1734 }
1735 return mode_vtype_infos.vlmul[mode];
1736 }
1737
1738 /* Return the VLMAX rtx of vector mode MODE. */
1739 rtx
1740 get_vlmax_rtx (machine_mode mode)
1741 {
1742 gcc_assert (riscv_v_ext_vector_mode_p (mode));
1743 return gen_int_mode (GET_MODE_NUNITS (mode), Pmode);
1744 }
1745
1746 /* Return the NF value of the corresponding mode. */
1747 unsigned int
1748 get_nf (machine_mode mode)
1749 {
1750 /* We don't allow non-tuple modes go through this function. */
1751 gcc_assert (riscv_v_ext_tuple_mode_p (mode));
1752 return mode_vtype_infos.nf[mode];
1753 }
1754
1755 /* Return the subpart mode of the tuple mode. For RVVM2x2SImode,
1756 the subpart mode is RVVM2SImode. This will help to build
1757 array/struct type in builtins. */
1758 machine_mode
1759 get_subpart_mode (machine_mode mode)
1760 {
1761 /* We don't allow non-tuple modes go through this function. */
1762 gcc_assert (riscv_v_ext_tuple_mode_p (mode));
1763 return mode_vtype_infos.subpart_mode[mode];
1764 }
1765
1766 /* Get ratio according to machine mode. */
1767 unsigned int
1768 get_ratio (machine_mode mode)
1769 {
1770 if (riscv_v_ext_vls_mode_p (mode))
1771 {
1772 unsigned int sew = get_sew (mode);
1773 vlmul_type vlmul = get_vlmul (mode);
1774 switch (vlmul)
1775 {
1776 case LMUL_1:
1777 return sew;
1778 case LMUL_2:
1779 return sew / 2;
1780 case LMUL_4:
1781 return sew / 4;
1782 case LMUL_8:
1783 return sew / 8;
1784 case LMUL_F8:
1785 return sew * 8;
1786 case LMUL_F4:
1787 return sew * 4;
1788 case LMUL_F2:
1789 return sew * 2;
1790
1791 default:
1792 gcc_unreachable ();
1793 }
1794 }
1795 return mode_vtype_infos.ratio[mode];
1796 }
1797
1798 /* Get ta according to operand[tail_op_idx]. */
1799 int
1800 get_ta (rtx ta)
1801 {
1802 if (INTVAL (ta) == TAIL_ANY)
1803 return INVALID_ATTRIBUTE;
1804 return INTVAL (ta);
1805 }
1806
1807 /* Get ma according to operand[mask_op_idx]. */
1808 int
1809 get_ma (rtx ma)
1810 {
1811 if (INTVAL (ma) == MASK_ANY)
1812 return INVALID_ATTRIBUTE;
1813 return INTVAL (ma);
1814 }
1815
1816 /* Get prefer tail policy. */
1817 enum tail_policy
1818 get_prefer_tail_policy ()
1819 {
1820 /* TODO: By default, we choose to use TAIL_ANY which allows
1821 compiler pick up either agnostic or undisturbed. Maybe we
1822 will have a compile option like -mprefer=agnostic to set
1823 this value???. */
1824 return TAIL_ANY;
1825 }
1826
1827 /* Get prefer mask policy. */
1828 enum mask_policy
1829 get_prefer_mask_policy ()
1830 {
1831 /* TODO: By default, we choose to use MASK_ANY which allows
1832 compiler pick up either agnostic or undisturbed. Maybe we
1833 will have a compile option like -mprefer=agnostic to set
1834 this value???. */
1835 return MASK_ANY;
1836 }
1837
1838 /* Get avl_type rtx. */
1839 rtx
1840 get_avl_type_rtx (enum avl_type type)
1841 {
1842 return gen_int_mode (type, Pmode);
1843 }
1844
1845 /* Return the appropriate mask mode for MODE. */
1846
1847 machine_mode
1848 get_mask_mode (machine_mode mode)
1849 {
1850 poly_int64 nunits = GET_MODE_NUNITS (mode);
1851 if (riscv_v_ext_tuple_mode_p (mode))
1852 {
1853 unsigned int nf = get_nf (mode);
1854 nunits = exact_div (nunits, nf);
1855 }
1856 return get_vector_mode (BImode, nunits).require ();
1857 }
1858
1859 /* Return the appropriate LMUL mode for MODE. */
1860
1861 opt_machine_mode
1862 get_lmul_mode (scalar_mode mode, int lmul)
1863 {
1864 poly_uint64 lmul_nunits;
1865 unsigned int bytes = GET_MODE_SIZE (mode);
1866 if (multiple_p (BYTES_PER_RISCV_VECTOR * lmul, bytes, &lmul_nunits))
1867 return get_vector_mode (mode, lmul_nunits);
1868 return E_VOIDmode;
1869 }
1870
1871 /* Return the appropriate LMUL1 mode for MODE.
1872 If VLS_P is specified, get a VLS mode that represents a full
1873 vector. */
1874
1875 opt_machine_mode
1876 get_m1_mode (machine_mode mode, bool vls_p)
1877 {
1878 scalar_mode smode = GET_MODE_INNER (mode);
1879 unsigned int bytes = GET_MODE_SIZE (smode);
1880 poly_uint64 bytes_vector = BYTES_PER_RISCV_VECTOR;
1881 if (vls_p)
1882 bytes_vector = constant_lower_bound (bytes_vector);
1883 poly_uint64 m1_nunits = exact_div (bytes_vector, bytes);
1884 return get_vector_mode (smode, m1_nunits);
1885 }
1886
1887 /* Return the RVV vector mode that has NUNITS elements of mode INNER_MODE.
1888 This function is not only used by builtins, but also will be used by
1889 auto-vectorization in the future. */
1890 opt_machine_mode
1891 get_vector_mode (scalar_mode inner_mode, poly_uint64 nunits)
1892 {
1893 enum mode_class mclass;
1894 if (inner_mode == E_BImode)
1895 mclass = MODE_VECTOR_BOOL;
1896 else if (FLOAT_MODE_P (inner_mode))
1897 mclass = MODE_VECTOR_FLOAT;
1898 else
1899 mclass = MODE_VECTOR_INT;
1900 machine_mode mode;
1901 FOR_EACH_MODE_IN_CLASS (mode, mclass)
1902 if (inner_mode == GET_MODE_INNER (mode)
1903 && known_eq (nunits, GET_MODE_NUNITS (mode))
1904 && (riscv_v_ext_vector_mode_p (mode)
1905 || riscv_v_ext_vls_mode_p (mode)))
1906 return mode;
1907 return opt_machine_mode ();
1908 }
1909
1910 /* Return the RVV tuple mode if we can find the legal tuple mode for the
1911 corresponding subpart mode and NF. */
1912 opt_machine_mode
1913 get_tuple_mode (machine_mode subpart_mode, unsigned int nf)
1914 {
1915 poly_uint64 nunits = GET_MODE_NUNITS (subpart_mode) * nf;
1916 scalar_mode inner_mode = GET_MODE_INNER (subpart_mode);
1917 enum mode_class mclass = GET_MODE_CLASS (subpart_mode);
1918 machine_mode mode;
1919 FOR_EACH_MODE_IN_CLASS (mode, mclass)
1920 if (inner_mode == GET_MODE_INNER (mode)
1921 && known_eq (nunits, GET_MODE_NUNITS (mode))
1922 && riscv_v_ext_tuple_mode_p (mode)
1923 && get_subpart_mode (mode) == subpart_mode)
1924 return mode;
1925 return opt_machine_mode ();
1926 }
1927
1928 bool
1929 simm5_p (rtx x)
1930 {
1931 if (!CONST_INT_P (x))
1932 return false;
1933 return IN_RANGE (INTVAL (x), -16, 15);
1934 }
1935
1936 bool
1937 neg_simm5_p (rtx x)
1938 {
1939 if (!CONST_INT_P (x))
1940 return false;
1941 return IN_RANGE (INTVAL (x), -15, 16);
1942 }
1943
1944 bool
1945 has_vi_variant_p (rtx_code code, rtx x)
1946 {
1947 switch (code)
1948 {
1949 case PLUS:
1950 case AND:
1951 case IOR:
1952 case XOR:
1953 case SS_PLUS:
1954 case US_PLUS:
1955 case EQ:
1956 case NE:
1957 case LE:
1958 case LEU:
1959 case GT:
1960 case GTU:
1961 return simm5_p (x);
1962
1963 case LT:
1964 case LTU:
1965 case GE:
1966 case GEU:
1967 case MINUS:
1968 case SS_MINUS:
1969 return neg_simm5_p (x);
1970
1971 default:
1972 return false;
1973 }
1974 }
1975
1976 bool
1977 sew64_scalar_helper (rtx *operands, rtx *scalar_op, rtx vl,
1978 machine_mode vector_mode, bool has_vi_variant_p,
1979 void (*emit_vector_func) (rtx *, rtx), enum avl_type type)
1980 {
1981 machine_mode scalar_mode = GET_MODE_INNER (vector_mode);
1982 if (has_vi_variant_p)
1983 {
1984 *scalar_op = force_reg (scalar_mode, *scalar_op);
1985 return false;
1986 }
1987
1988 if (TARGET_64BIT)
1989 {
1990 if (!rtx_equal_p (*scalar_op, const0_rtx))
1991 *scalar_op = force_reg (scalar_mode, *scalar_op);
1992 return false;
1993 }
1994
1995 if (immediate_operand (*scalar_op, Pmode))
1996 {
1997 if (!rtx_equal_p (*scalar_op, const0_rtx))
1998 *scalar_op = force_reg (Pmode, *scalar_op);
1999
2000 *scalar_op = gen_rtx_SIGN_EXTEND (scalar_mode, *scalar_op);
2001 return false;
2002 }
2003
2004 if (CONST_INT_P (*scalar_op))
2005 {
2006 if (maybe_gt (GET_MODE_SIZE (scalar_mode), GET_MODE_SIZE (Pmode)))
2007 *scalar_op = force_const_mem (scalar_mode, *scalar_op);
2008 else
2009 *scalar_op = force_reg (scalar_mode, *scalar_op);
2010 }
2011
2012 rtx tmp = gen_reg_rtx (vector_mode);
2013 rtx ops[] = {tmp, *scalar_op};
2014 if (type == VLMAX)
2015 emit_vlmax_insn (code_for_pred_broadcast (vector_mode), UNARY_OP, ops);
2016 else
2017 emit_nonvlmax_insn (code_for_pred_broadcast (vector_mode), UNARY_OP, ops,
2018 vl);
2019 emit_vector_func (operands, tmp);
2020
2021 return true;
2022 }
2023
2024 /* Get { ... ,0, 0, 0, ..., 0, 0, 0, 1 } mask. */
2025 rtx
2026 gen_scalar_move_mask (machine_mode mode)
2027 {
2028 rtx_vector_builder builder (mode, 1, 2);
2029 builder.quick_push (const1_rtx);
2030 builder.quick_push (const0_rtx);
2031 return builder.build ();
2032 }
2033
2034 static unsigned
2035 compute_vlmax (unsigned vector_bits, unsigned elt_size, unsigned min_size)
2036 {
2037 // Original equation:
2038 // VLMAX = (VectorBits / EltSize) * LMUL
2039 // where LMUL = MinSize / TARGET_MIN_VLEN
2040 // The following equations have been reordered to prevent loss of precision
2041 // when calculating fractional LMUL.
2042 return ((vector_bits / elt_size) * min_size) / TARGET_MIN_VLEN;
2043 }
2044
2045 static unsigned
2046 get_unknown_min_value (machine_mode mode)
2047 {
2048 enum vlmul_type vlmul = get_vlmul (mode);
2049 switch (vlmul)
2050 {
2051 case LMUL_1:
2052 return TARGET_MIN_VLEN;
2053 case LMUL_2:
2054 return TARGET_MIN_VLEN * 2;
2055 case LMUL_4:
2056 return TARGET_MIN_VLEN * 4;
2057 case LMUL_8:
2058 return TARGET_MIN_VLEN * 8;
2059 default:
2060 gcc_unreachable ();
2061 }
2062 }
2063
2064 static rtx
2065 force_vector_length_operand (rtx vl)
2066 {
2067 if (CONST_INT_P (vl) && !satisfies_constraint_vl (vl))
2068 return force_reg (Pmode, vl);
2069 return vl;
2070 }
2071
2072 rtx
2073 gen_no_side_effects_vsetvl_rtx (machine_mode vmode, rtx vl, rtx avl)
2074 {
2075 unsigned int sew = get_sew (vmode);
2076 rtx tail_policy = gen_int_mode (get_prefer_tail_policy (), Pmode);
2077 rtx mask_policy = gen_int_mode (get_prefer_mask_policy (), Pmode);
2078 return gen_vsetvl_no_side_effects (Pmode, vl, avl, gen_int_mode (sew, Pmode),
2079 gen_int_mode (get_vlmul (vmode), Pmode),
2080 tail_policy, mask_policy);
2081 }
2082
2083 /* GET VL * 2 rtx. */
2084 static rtx
2085 get_vl_x2_rtx (rtx avl, machine_mode mode, machine_mode demote_mode)
2086 {
2087 rtx i32vl = NULL_RTX;
2088 if (CONST_INT_P (avl))
2089 {
2090 unsigned elt_size = GET_MODE_BITSIZE (GET_MODE_INNER (mode));
2091 unsigned min_size = get_unknown_min_value (mode);
2092 unsigned vlen_max = RVV_65536;
2093 unsigned vlmax_max = compute_vlmax (vlen_max, elt_size, min_size);
2094 unsigned vlen_min = TARGET_MIN_VLEN;
2095 unsigned vlmax_min = compute_vlmax (vlen_min, elt_size, min_size);
2096
2097 unsigned HOST_WIDE_INT avl_int = INTVAL (avl);
2098 if (avl_int <= vlmax_min)
2099 i32vl = gen_int_mode (2 * avl_int, Pmode);
2100 else if (avl_int >= 2 * vlmax_max)
2101 {
2102 // Just set i32vl to VLMAX in this situation
2103 i32vl = gen_reg_rtx (Pmode);
2104 emit_insn (
2105 gen_no_side_effects_vsetvl_rtx (demote_mode, i32vl, RVV_VLMAX));
2106 }
2107 else
2108 {
2109 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl
2110 // is related to the hardware implementation.
2111 // So let the following code handle
2112 }
2113 }
2114 if (!i32vl)
2115 {
2116 // Using vsetvli instruction to get actually used length which related to
2117 // the hardware implementation
2118 rtx i64vl = gen_reg_rtx (Pmode);
2119 emit_insn (
2120 gen_no_side_effects_vsetvl_rtx (mode, i64vl, force_reg (Pmode, avl)));
2121 // scale 2 for 32-bit length
2122 i32vl = gen_reg_rtx (Pmode);
2123 emit_insn (
2124 gen_rtx_SET (i32vl, gen_rtx_ASHIFT (Pmode, i64vl, const1_rtx)));
2125 }
2126
2127 return force_vector_length_operand (i32vl);
2128 }
2129
2130 bool
2131 slide1_sew64_helper (int unspec, machine_mode mode, machine_mode demote_mode,
2132 machine_mode demote_mask_mode, rtx *ops)
2133 {
2134 rtx scalar_op = ops[4];
2135 rtx avl = ops[5];
2136 machine_mode scalar_mode = GET_MODE_INNER (mode);
2137 if (rtx_equal_p (scalar_op, const0_rtx))
2138 {
2139 ops[5] = force_vector_length_operand (ops[5]);
2140 return false;
2141 }
2142
2143 if (TARGET_64BIT)
2144 {
2145 ops[4] = force_reg (scalar_mode, scalar_op);
2146 ops[5] = force_vector_length_operand (ops[5]);
2147 return false;
2148 }
2149
2150 if (immediate_operand (scalar_op, Pmode))
2151 {
2152 ops[4] = gen_rtx_SIGN_EXTEND (scalar_mode, force_reg (Pmode, scalar_op));
2153 ops[5] = force_vector_length_operand (ops[5]);
2154 return false;
2155 }
2156
2157 if (CONST_INT_P (scalar_op))
2158 scalar_op = force_reg (scalar_mode, scalar_op);
2159
2160 rtx vl_x2 = get_vl_x2_rtx (avl, mode, demote_mode);
2161
2162 rtx demote_scalar_op1, demote_scalar_op2;
2163 if (unspec == UNSPEC_VSLIDE1UP)
2164 {
2165 demote_scalar_op1 = gen_highpart (Pmode, scalar_op);
2166 demote_scalar_op2 = gen_lowpart (Pmode, scalar_op);
2167 }
2168 else
2169 {
2170 demote_scalar_op1 = gen_lowpart (Pmode, scalar_op);
2171 demote_scalar_op2 = gen_highpart (Pmode, scalar_op);
2172 }
2173
2174 rtx temp = gen_reg_rtx (demote_mode);
2175 rtx ta = gen_int_mode (get_prefer_tail_policy (), Pmode);
2176 rtx ma = gen_int_mode (get_prefer_mask_policy (), Pmode);
2177 rtx merge = RVV_VUNDEF (demote_mode);
2178 /* Handle vslide1<ud>_tu. */
2179 if (register_operand (ops[2], mode)
2180 && rtx_equal_p (ops[1], CONSTM1_RTX (GET_MODE (ops[1]))))
2181 {
2182 merge = gen_lowpart (demote_mode, ops[2]);
2183 ta = ops[6];
2184 ma = ops[7];
2185 }
2186
2187 emit_insn (gen_pred_slide (unspec, demote_mode, temp,
2188 CONSTM1_RTX (demote_mask_mode), merge,
2189 gen_lowpart (demote_mode, ops[3]),
2190 demote_scalar_op1, vl_x2, ta, ma, ops[8]));
2191 emit_insn (gen_pred_slide (unspec, demote_mode,
2192 gen_lowpart (demote_mode, ops[0]),
2193 CONSTM1_RTX (demote_mask_mode), merge, temp,
2194 demote_scalar_op2, vl_x2, ta, ma, ops[8]));
2195
2196 if (!rtx_equal_p (ops[1], CONSTM1_RTX (GET_MODE (ops[1])))
2197 && !rtx_equal_p (ops[2], RVV_VUNDEF (GET_MODE (ops[2]))))
2198 emit_insn (gen_pred_merge (mode, ops[0], ops[2], ops[2], ops[0], ops[1],
2199 force_vector_length_operand (ops[5]), ops[6],
2200 ops[8]));
2201 return true;
2202 }
2203
2204 rtx
2205 gen_avl_for_scalar_move (rtx avl)
2206 {
2207 /* AVL for scalar move has different behavior between 0 and large than 0. */
2208 if (CONST_INT_P (avl))
2209 {
2210 /* So we could just set AVL to 1 for any constant other than 0. */
2211 if (rtx_equal_p (avl, const0_rtx))
2212 return const0_rtx;
2213 else
2214 return const1_rtx;
2215 }
2216 else
2217 {
2218 /* For non-constant value, we set any non zero value to 1 by
2219 `sgtu new_avl,input_avl,zero` + `vsetvli`. */
2220 rtx tmp = gen_reg_rtx (Pmode);
2221 emit_insn (
2222 gen_rtx_SET (tmp, gen_rtx_fmt_ee (GTU, Pmode, avl, const0_rtx)));
2223 return tmp;
2224 }
2225 }
2226
2227 /* Expand tuple modes data movement for. */
2228 void
2229 expand_tuple_move (rtx *ops)
2230 {
2231 unsigned int i;
2232 machine_mode tuple_mode = GET_MODE (ops[0]);
2233 machine_mode subpart_mode = get_subpart_mode (tuple_mode);
2234 poly_int64 subpart_size = GET_MODE_SIZE (subpart_mode);
2235 unsigned int nf = get_nf (tuple_mode);
2236 bool fractional_p = known_lt (subpart_size, BYTES_PER_RISCV_VECTOR);
2237
2238 if (REG_P (ops[0]) && CONST_VECTOR_P (ops[1]))
2239 {
2240 rtx val;
2241 gcc_assert (can_create_pseudo_p ()
2242 && const_vec_duplicate_p (ops[1], &val));
2243 for (i = 0; i < nf; ++i)
2244 {
2245 poly_int64 offset = i * subpart_size;
2246 rtx subreg
2247 = simplify_gen_subreg (subpart_mode, ops[0], tuple_mode, offset);
2248 rtx dup = gen_const_vec_duplicate (subpart_mode, val);
2249 emit_move_insn (subreg, dup);
2250 }
2251 }
2252 else if (REG_P (ops[0]) && REG_P (ops[1]))
2253 {
2254 for (i = 0; i < nf; ++i)
2255 {
2256 int index = i;
2257
2258 /* Take NF = 2 and LMUL = 1 for example:
2259
2260 - move v8 to v9:
2261 vmv1r v10,v9
2262 vmv1r v9,v8
2263
2264 - move v8 to v7:
2265 vmv1r v7,v8
2266 vmv1r v8,v9 */
2267 if (REGNO (ops[0]) > REGNO (ops[1]))
2268 index = nf - 1 - i;
2269 poly_int64 offset = index * subpart_size;
2270 rtx dst_subreg
2271 = simplify_gen_subreg (subpart_mode, ops[0], tuple_mode, offset);
2272 rtx src_subreg
2273 = simplify_gen_subreg (subpart_mode, ops[1], tuple_mode, offset);
2274 emit_insn (gen_rtx_SET (dst_subreg, src_subreg));
2275 }
2276 }
2277 else
2278 {
2279 /* Expand tuple memory data movement. */
2280 gcc_assert (MEM_P (ops[0]) || MEM_P (ops[1]));
2281 rtx offset = gen_int_mode (subpart_size, Pmode);
2282 if (!subpart_size.is_constant ())
2283 {
2284 emit_move_insn (ops[2], gen_int_mode (BYTES_PER_RISCV_VECTOR, Pmode));
2285 if (fractional_p)
2286 {
2287 unsigned int factor
2288 = exact_div (BYTES_PER_RISCV_VECTOR, subpart_size)
2289 .to_constant ();
2290 rtx pat
2291 = gen_rtx_ASHIFTRT (Pmode, ops[2],
2292 gen_int_mode (exact_log2 (factor), Pmode));
2293 emit_insn (gen_rtx_SET (ops[2], pat));
2294 }
2295
2296 if (known_gt (subpart_size, BYTES_PER_RISCV_VECTOR))
2297 {
2298 unsigned int factor
2299 = exact_div (subpart_size, BYTES_PER_RISCV_VECTOR)
2300 .to_constant ();
2301 rtx pat
2302 = gen_rtx_ASHIFT (Pmode, ops[2],
2303 gen_int_mode (exact_log2 (factor), Pmode));
2304 emit_insn (gen_rtx_SET (ops[2], pat));
2305 }
2306 offset = ops[2];
2307 }
2308
2309 /* Non-fractional LMUL has whole register moves that don't require a
2310 vsetvl for VLMAX. */
2311 if (fractional_p)
2312 emit_vlmax_vsetvl (subpart_mode, ops[4]);
2313 if (MEM_P (ops[1]))
2314 {
2315 /* Load operations. */
2316 emit_move_insn (ops[3], XEXP (ops[1], 0));
2317 for (i = 0; i < nf; i++)
2318 {
2319 rtx subreg = simplify_gen_subreg (subpart_mode, ops[0],
2320 tuple_mode, i * subpart_size);
2321 if (i != 0)
2322 {
2323 rtx new_addr = gen_rtx_PLUS (Pmode, ops[3], offset);
2324 emit_insn (gen_rtx_SET (ops[3], new_addr));
2325 }
2326 rtx mem = gen_rtx_MEM (subpart_mode, ops[3]);
2327
2328 if (fractional_p)
2329 {
2330 rtx operands[] = {subreg, mem};
2331 emit_vlmax_insn_lra (code_for_pred_mov (subpart_mode),
2332 UNARY_OP, operands, ops[4]);
2333 }
2334 else
2335 emit_move_insn (subreg, mem);
2336 }
2337 }
2338 else
2339 {
2340 /* Store operations. */
2341 emit_move_insn (ops[3], XEXP (ops[0], 0));
2342 for (i = 0; i < nf; i++)
2343 {
2344 rtx subreg = simplify_gen_subreg (subpart_mode, ops[1],
2345 tuple_mode, i * subpart_size);
2346 if (i != 0)
2347 {
2348 rtx new_addr = gen_rtx_PLUS (Pmode, ops[3], offset);
2349 emit_insn (gen_rtx_SET (ops[3], new_addr));
2350 }
2351 rtx mem = gen_rtx_MEM (subpart_mode, ops[3]);
2352
2353 if (fractional_p)
2354 {
2355 rtx operands[] = {mem, subreg};
2356 emit_vlmax_insn_lra (code_for_pred_mov (subpart_mode),
2357 UNARY_OP, operands, ops[4]);
2358 }
2359 else
2360 emit_move_insn (mem, subreg);
2361 }
2362 }
2363 }
2364 }
2365
2366 /* Return the vectorization machine mode for RVV according to LMUL. */
2367 machine_mode
2368 preferred_simd_mode (scalar_mode mode)
2369 {
2370 if (autovec_use_vlmax_p ())
2371 {
2372 /* We use LMUL = 1 as base bytesize which is BYTES_PER_RISCV_VECTOR and
2373 rvv_max_lmul as multiply factor to calculate the NUNITS to
2374 get the auto-vectorization mode. */
2375 poly_uint64 nunits;
2376 poly_uint64 vector_size = BYTES_PER_RISCV_VECTOR * TARGET_MAX_LMUL;
2377 poly_uint64 scalar_size = GET_MODE_SIZE (mode);
2378 /* Disable vectorization when we can't find a RVV mode for it.
2379 E.g. -march=rv64gc_zve32x doesn't have a vector mode to vectorize
2380 a double (DFmode) type. */
2381 if (!multiple_p (vector_size, scalar_size, &nunits))
2382 return word_mode;
2383 machine_mode rvv_mode;
2384 if (get_vector_mode (mode, nunits).exists (&rvv_mode))
2385 return rvv_mode;
2386 }
2387 return word_mode;
2388 }
2389
2390 /* Use merge approach to initialize the vector with repeating sequence.
2391 v = {a, b, a, b, a, b, a, b}.
2392
2393 v = broadcast (a).
2394 mask = 0b01010101....
2395 v = merge (v, b, mask)
2396 */
2397 static void
2398 expand_vector_init_merge_repeating_sequence (rtx target,
2399 const rvv_builder &builder)
2400 {
2401 /* We can't use BIT mode (BI) directly to generate mask = 0b01010...
2402 since we don't have such instruction in RVV.
2403 Instead, we should use INT mode (QI/HI/SI/DI) with integer move
2404 instruction to generate the mask data we want. */
2405 machine_mode mask_bit_mode = get_mask_mode (builder.mode ());
2406 machine_mode mask_int_mode
2407 = get_repeating_sequence_dup_machine_mode (builder, mask_bit_mode);
2408 uint64_t full_nelts = builder.full_nelts ().to_constant ();
2409
2410 /* Step 1: Broadcast the first pattern. */
2411 rtx ops[] = {target, force_reg (builder.inner_mode (), builder.elt (0))};
2412 emit_vlmax_insn (code_for_pred_broadcast (builder.mode ()),
2413 UNARY_OP, ops);
2414 /* Step 2: Merge the rest iteration of pattern. */
2415 for (unsigned int i = 1; i < builder.npatterns (); i++)
2416 {
2417 /* Step 2-1: Generate mask register v0 for each merge. */
2418 rtx merge_mask
2419 = builder.get_merge_scalar_mask (i, GET_MODE_INNER (mask_int_mode));
2420 rtx mask = gen_reg_rtx (mask_bit_mode);
2421 rtx dup = gen_reg_rtx (mask_int_mode);
2422
2423 if (full_nelts <= builder.inner_bits_size ()) /* vmv.s.x. */
2424 {
2425 rtx ops[] = {dup, merge_mask};
2426 emit_nonvlmax_insn (code_for_pred_broadcast (GET_MODE (dup)),
2427 SCALAR_MOVE_OP, ops, CONST1_RTX (Pmode));
2428 }
2429 else /* vmv.v.x. */
2430 {
2431 rtx ops[] = {dup,
2432 force_reg (GET_MODE_INNER (mask_int_mode), merge_mask)};
2433 rtx vl = gen_int_mode (CEIL (full_nelts, builder.inner_bits_size ()),
2434 Pmode);
2435 emit_nonvlmax_insn (code_for_pred_broadcast (mask_int_mode), UNARY_OP,
2436 ops, vl);
2437 }
2438
2439 emit_move_insn (mask, gen_lowpart (mask_bit_mode, dup));
2440
2441 /* Step 2-2: Merge pattern according to the mask. */
2442 rtx ops[] = {target, target, builder.elt (i), mask};
2443 emit_vlmax_insn (code_for_pred_merge_scalar (GET_MODE (target)),
2444 MERGE_OP, ops);
2445 }
2446 }
2447
2448 /* Use slideup approach to combine the vectors.
2449 v = {a, a, a, a, b, b, b, b}
2450
2451 First:
2452 v1 = {a, a, a, a, a, a, a, a}
2453 v2 = {b, b, b, b, b, b, b, b}
2454 v = slideup (v1, v2, nelt / 2)
2455 */
2456 static void
2457 expand_vector_init_slideup_combine_sequence (rtx target,
2458 const rvv_builder &builder)
2459 {
2460 machine_mode mode = GET_MODE (target);
2461 int nelts = builder.full_nelts ().to_constant ();
2462 rtx first_elt = builder.elt (0);
2463 rtx last_elt = builder.elt (nelts - 1);
2464 rtx low = expand_vector_broadcast (mode, first_elt);
2465 rtx high = expand_vector_broadcast (mode, last_elt);
2466 insn_code icode = code_for_pred_slide (UNSPEC_VSLIDEUP, mode);
2467 rtx ops[] = {target, low, high, gen_int_mode (nelts / 2, Pmode)};
2468 emit_vlmax_insn (icode, SLIDEUP_OP_MERGE, ops);
2469 }
2470
2471 /* Use merge approach to merge a scalar into a vector.
2472 v = {a, a, a, a, a, a, b, b}
2473
2474 v1 = {a, a, a, a, a, a, a, a}
2475 scalar = b
2476 mask = {0, 0, 0, 0, 0, 0, 1, 1}
2477 */
2478 static void
2479 expand_vector_init_merge_combine_sequence (rtx target,
2480 const rvv_builder &builder)
2481 {
2482 machine_mode mode = GET_MODE (target);
2483 machine_mode imode = builder.int_mode ();
2484 machine_mode mmode = builder.mask_mode ();
2485 int nelts = builder.full_nelts ().to_constant ();
2486 int leading_ndups = builder.count_dups (0, nelts - 1, 1);
2487 if ((leading_ndups > 255 && GET_MODE_INNER (imode) == QImode)
2488 || riscv_get_v_regno_alignment (imode) > 1)
2489 imode = get_vector_mode (HImode, nelts).require ();
2490
2491 /* Generate vid = { 0, 1, 2, ..., n }. */
2492 rtx vid = gen_reg_rtx (imode);
2493 expand_vec_series (vid, const0_rtx, const1_rtx);
2494
2495 /* Generate mask. */
2496 rtx mask = gen_reg_rtx (mmode);
2497 insn_code icode = code_for_pred_cmp_scalar (imode);
2498 rtx index = gen_int_mode (leading_ndups - 1, builder.inner_int_mode ());
2499 rtx dup_rtx = gen_rtx_VEC_DUPLICATE (imode, index);
2500 /* vmsgtu.vi/vmsgtu.vx. */
2501 rtx cmp = gen_rtx_fmt_ee (GTU, mmode, vid, dup_rtx);
2502 rtx sel = builder.elt (nelts - 1);
2503 rtx mask_ops[] = {mask, cmp, vid, index};
2504 emit_vlmax_insn (icode, COMPARE_OP, mask_ops);
2505
2506 /* Duplicate the first elements. */
2507 rtx dup = expand_vector_broadcast (mode, builder.elt (0));
2508 /* Merge scalar into vector according to mask. */
2509 rtx merge_ops[] = {target, dup, sel, mask};
2510 icode = code_for_pred_merge_scalar (mode);
2511 emit_vlmax_insn (icode, MERGE_OP, merge_ops);
2512 }
2513
2514 /* Initialize register TARGET from the elements in PARALLEL rtx VALS. */
2515
2516 void
2517 expand_vec_init (rtx target, rtx vals)
2518 {
2519 machine_mode mode = GET_MODE (target);
2520 int nelts = XVECLEN (vals, 0);
2521
2522 rvv_builder v (mode, nelts, 1);
2523 for (int i = 0; i < nelts; i++)
2524 v.quick_push (XVECEXP (vals, 0, i));
2525 v.finalize ();
2526
2527 /* If the sequence is v = { a, a, a, a } just broadcast an element. */
2528 if (v.is_repeating_sequence ())
2529 {
2530 machine_mode mode = GET_MODE (target);
2531 rtx dup = expand_vector_broadcast (mode, v.elt (0));
2532 emit_move_insn (target, dup);
2533 return;
2534 }
2535
2536 if (nelts > 3)
2537 {
2538 /* Case 1: Convert v = { a, b, a, b } into v = { ab, ab }. */
2539 if (v.can_duplicate_repeating_sequence_p ())
2540 {
2541 rtx ele = v.get_merged_repeating_sequence ();
2542 rtx dup = expand_vector_broadcast (v.new_mode (), ele);
2543 emit_move_insn (target, gen_lowpart (mode, dup));
2544 return;
2545 }
2546
2547 /* Case 2: Optimize repeating sequence cases that Case 1 can
2548 not handle and it is profitable. For example:
2549 ELEMENT BITSIZE = 64.
2550 v = {a, b, a, b, a, b, a, b, a, b, a, b, a, b, a, b}.
2551 We can't find a vector mode for "ab" which will be combined into
2552 128-bit element to duplicate. */
2553 if (v.repeating_sequence_use_merge_profitable_p ())
2554 {
2555 expand_vector_init_merge_repeating_sequence (target, v);
2556 return;
2557 }
2558
2559 /* Case 3: Optimize combine sequence.
2560 E.g. v = {a, a, a, a, a, a, a, a, b, b, b, b, b, b, b, b}.
2561 We can combine:
2562 v1 = {a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a}.
2563 and
2564 v2 = {b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b}.
2565 by slideup. */
2566 if (v.combine_sequence_use_slideup_profitable_p ())
2567 {
2568 expand_vector_init_slideup_combine_sequence (target, v);
2569 return;
2570 }
2571
2572 /* Case 4: Optimize combine sequence.
2573 E.g. v = {a, a, a, a, a, a, a, a, a, a, a, b, b, b, b, b}.
2574
2575 Generate vector:
2576 v = {a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a}.
2577
2578 Generate mask:
2579 mask = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1}.
2580
2581 Merge b into v by mask:
2582 v = {a, a, a, a, a, a, a, a, a, a, a, b, b, b, b, b}. */
2583 if (v.combine_sequence_use_merge_profitable_p ())
2584 {
2585 expand_vector_init_merge_combine_sequence (target, v);
2586 return;
2587 }
2588 }
2589
2590 /* Optimize trailing same elements sequence:
2591 v = {y, y2, y3, y4, y5, x, x, x, x, x, x, x, x, x, x, x}; */
2592 if (!expand_vector_init_trailing_same_elem (target, v, nelts))
2593 /* Handle common situation by vslide1down. This function can handle any
2594 situation of vec_init<mode>. Only the cases that are not optimized above
2595 will fall through here. */
2596 expand_vector_init_insert_elems (target, v, nelts);
2597 }
2598
2599 /* Get insn code for corresponding comparison. */
2600
2601 static insn_code
2602 get_cmp_insn_code (rtx_code code, machine_mode mode)
2603 {
2604 insn_code icode;
2605 switch (code)
2606 {
2607 case EQ:
2608 case NE:
2609 case LE:
2610 case LEU:
2611 case GT:
2612 case GTU:
2613 case LTGT:
2614 icode = code_for_pred_cmp (mode);
2615 break;
2616 case LT:
2617 case LTU:
2618 case GE:
2619 case GEU:
2620 if (FLOAT_MODE_P (mode))
2621 icode = code_for_pred_cmp (mode);
2622 else
2623 icode = code_for_pred_ltge (mode);
2624 break;
2625 default:
2626 gcc_unreachable ();
2627 }
2628 return icode;
2629 }
2630
2631 /* This hook gives the vectorizer more vector mode options. We want it to not
2632 only try modes with the maximum number of units a full vector can hold but
2633 for example also half the number of units for a smaller elements size.
2634 Such vectors can be promoted to a full vector of widened elements
2635 (still with the same number of elements, essentially vectorizing at a
2636 fixed number of units rather than a fixed number of bytes). */
2637 unsigned int
2638 autovectorize_vector_modes (vector_modes *modes, bool)
2639 {
2640 if (autovec_use_vlmax_p ())
2641 {
2642 poly_uint64 full_size = BYTES_PER_RISCV_VECTOR * TARGET_MAX_LMUL;
2643
2644 /* Start with a RVV<LMUL>QImode where LMUL is the number of units that
2645 fit a whole vector.
2646 Then try LMUL = nunits / 2, nunits / 4 and nunits / 8 which
2647 is guided by the extensions we have available (vf2, vf4 and vf8).
2648
2649 - full_size: Try using full vectors for all element types.
2650 - full_size / 2:
2651 Try using 16-bit containers for 8-bit elements and full vectors
2652 for wider elements.
2653 - full_size / 4:
2654 Try using 32-bit containers for 8-bit and 16-bit elements and
2655 full vectors for wider elements.
2656 - full_size / 8:
2657 Try using 64-bit containers for all element types. */
2658 static const int rvv_factors[] = {1, 2, 4, 8, 16, 32, 64};
2659 for (unsigned int i = 0; i < sizeof (rvv_factors) / sizeof (int); i++)
2660 {
2661 poly_uint64 units;
2662 machine_mode mode;
2663 if (can_div_trunc_p (full_size, rvv_factors[i], &units)
2664 && get_vector_mode (QImode, units).exists (&mode))
2665 modes->safe_push (mode);
2666 }
2667 }
2668 /* Push all VLSmodes according to TARGET_MIN_VLEN. */
2669 unsigned int i = 0;
2670 unsigned int base_size = TARGET_MIN_VLEN * TARGET_MAX_LMUL / 8;
2671 unsigned int size = base_size;
2672 machine_mode mode;
2673 while (size > 0 && get_vector_mode (QImode, size).exists (&mode))
2674 {
2675 if (vls_mode_valid_p (mode))
2676 modes->safe_push (mode);
2677
2678 i++;
2679 size = base_size / (1U << i);
2680 }
2681 /* Enable LOOP_VINFO comparison in COST model. */
2682 return VECT_COMPARE_COSTS;
2683 }
2684
2685 /* Return true if we can find the related MODE according to default LMUL. */
2686 static bool
2687 can_find_related_mode_p (machine_mode vector_mode, scalar_mode element_mode,
2688 poly_uint64 *nunits)
2689 {
2690 if (!autovec_use_vlmax_p ())
2691 return false;
2692 if (riscv_v_ext_vector_mode_p (vector_mode)
2693 && multiple_p (BYTES_PER_RISCV_VECTOR * TARGET_MAX_LMUL,
2694 GET_MODE_SIZE (element_mode), nunits))
2695 return true;
2696 if (riscv_v_ext_vls_mode_p (vector_mode)
2697 && multiple_p (TARGET_MIN_VLEN * TARGET_MAX_LMUL,
2698 GET_MODE_SIZE (element_mode), nunits))
2699 return true;
2700 return false;
2701 }
2702
2703 /* If the given VECTOR_MODE is an RVV mode, first get the largest number
2704 of units that fit into a full vector at the given ELEMENT_MODE.
2705 We will have the vectorizer call us with a successively decreasing
2706 number of units (as specified in autovectorize_vector_modes).
2707 The starting mode is always the one specified by preferred_simd_mode. */
2708 opt_machine_mode
2709 vectorize_related_mode (machine_mode vector_mode, scalar_mode element_mode,
2710 poly_uint64 nunits)
2711 {
2712 /* TODO: We will support RVV VLS auto-vectorization mode in the future. */
2713 poly_uint64 min_units;
2714 if (can_find_related_mode_p (vector_mode, element_mode, &min_units))
2715 {
2716 machine_mode rvv_mode;
2717 if (maybe_ne (nunits, 0U))
2718 {
2719 /* If we were given a number of units NUNITS, try to find an
2720 RVV vector mode of inner mode ELEMENT_MODE with the same
2721 number of units. */
2722 if (multiple_p (min_units, nunits)
2723 && get_vector_mode (element_mode, nunits).exists (&rvv_mode))
2724 return rvv_mode;
2725 }
2726 else
2727 {
2728 /* Look for a vector mode with the same number of units as the
2729 VECTOR_MODE we were given. We keep track of the minimum
2730 number of units so far which determines the smallest necessary
2731 but largest possible, suitable mode for vectorization. */
2732 min_units = ordered_min (min_units, GET_MODE_SIZE (vector_mode));
2733 if (get_vector_mode (element_mode, min_units).exists (&rvv_mode))
2734 return rvv_mode;
2735 }
2736 }
2737
2738 return default_vectorize_related_mode (vector_mode, element_mode, nunits);
2739 }
2740
2741 /* Expand an RVV comparison. */
2742
2743 void
2744 expand_vec_cmp (rtx target, rtx_code code, rtx op0, rtx op1, rtx mask,
2745 rtx maskoff)
2746 {
2747 machine_mode mask_mode = GET_MODE (target);
2748 machine_mode data_mode = GET_MODE (op0);
2749 insn_code icode = get_cmp_insn_code (code, data_mode);
2750
2751 if (code == LTGT)
2752 {
2753 rtx lt = gen_reg_rtx (mask_mode);
2754 rtx gt = gen_reg_rtx (mask_mode);
2755 expand_vec_cmp (lt, LT, op0, op1, mask, maskoff);
2756 expand_vec_cmp (gt, GT, op0, op1, mask, maskoff);
2757 icode = code_for_pred (IOR, mask_mode);
2758 rtx ops[] = {target, lt, gt};
2759 emit_vlmax_insn (icode, BINARY_MASK_OP, ops);
2760 return;
2761 }
2762
2763 rtx cmp = gen_rtx_fmt_ee (code, mask_mode, op0, op1);
2764 if (!mask && !maskoff)
2765 {
2766 rtx ops[] = {target, cmp, op0, op1};
2767 emit_vlmax_insn (icode, COMPARE_OP, ops);
2768 }
2769 else
2770 {
2771 rtx ops[] = {target, mask, maskoff, cmp, op0, op1};
2772 emit_vlmax_insn (icode, COMPARE_OP_MU, ops);
2773 }
2774 }
2775
2776 /* Expand an RVV floating-point comparison:
2777
2778 If CAN_INVERT_P is true, the caller can also handle inverted results;
2779 return true if the result is in fact inverted. */
2780
2781 bool
2782 expand_vec_cmp_float (rtx target, rtx_code code, rtx op0, rtx op1,
2783 bool can_invert_p)
2784 {
2785 machine_mode mask_mode = GET_MODE (target);
2786 machine_mode data_mode = GET_MODE (op0);
2787
2788 /* If can_invert_p = true:
2789 It suffices to implement a u>= b as !(a < b) but with the NaNs masked off:
2790
2791 vmfeq.vv v0, va, va
2792 vmfeq.vv v1, vb, vb
2793 vmand.mm v0, v0, v1
2794 vmflt.vv v0, va, vb, v0.t
2795 vmnot.m v0, v0
2796
2797 And, if !HONOR_SNANS, then you can remove the vmand.mm by masking the
2798 second vmfeq.vv:
2799
2800 vmfeq.vv v0, va, va
2801 vmfeq.vv v0, vb, vb, v0.t
2802 vmflt.vv v0, va, vb, v0.t
2803 vmnot.m v0, v0
2804
2805 If can_invert_p = false:
2806
2807 # Example of implementing isgreater()
2808 vmfeq.vv v0, va, va # Only set where A is not NaN.
2809 vmfeq.vv v1, vb, vb # Only set where B is not NaN.
2810 vmand.mm v0, v0, v1 # Only set where A and B are ordered,
2811 vmfgt.vv v0, va, vb, v0.t # so only set flags on ordered values.
2812 */
2813
2814 rtx eq0 = gen_reg_rtx (mask_mode);
2815 rtx eq1 = gen_reg_rtx (mask_mode);
2816 switch (code)
2817 {
2818 case EQ:
2819 case NE:
2820 case LT:
2821 case LE:
2822 case GT:
2823 case GE:
2824 case LTGT:
2825 /* There is native support for the comparison. */
2826 expand_vec_cmp (target, code, op0, op1);
2827 return false;
2828 case UNEQ:
2829 case ORDERED:
2830 case UNORDERED:
2831 case UNLT:
2832 case UNLE:
2833 case UNGT:
2834 case UNGE:
2835 /* vmfeq.vv v0, va, va */
2836 expand_vec_cmp (eq0, EQ, op0, op0);
2837 if (HONOR_SNANS (data_mode))
2838 {
2839 /*
2840 vmfeq.vv v1, vb, vb
2841 vmand.mm v0, v0, v1
2842 */
2843 expand_vec_cmp (eq1, EQ, op1, op1);
2844 insn_code icode = code_for_pred (AND, mask_mode);
2845 rtx ops[] = {eq0, eq0, eq1};
2846 emit_vlmax_insn (icode, BINARY_MASK_OP, ops);
2847 }
2848 else
2849 {
2850 /* vmfeq.vv v0, vb, vb, v0.t */
2851 expand_vec_cmp (eq0, EQ, op1, op1, eq0, eq0);
2852 }
2853 break;
2854 default:
2855 gcc_unreachable ();
2856 }
2857
2858 if (code == ORDERED)
2859 {
2860 emit_move_insn (target, eq0);
2861 return false;
2862 }
2863
2864 /* There is native support for the inverse comparison. */
2865 code = reverse_condition_maybe_unordered (code);
2866 if (code == ORDERED)
2867 emit_move_insn (target, eq0);
2868 else
2869 expand_vec_cmp (eq0, code, op0, op1, eq0, eq0);
2870
2871 if (can_invert_p)
2872 {
2873 emit_move_insn (target, eq0);
2874 return true;
2875 }
2876
2877 /* We use one_cmpl<mode>2 to make Combine PASS to combine mask instructions
2878 into: vmand.mm/vmnor.mm/vmnand.mm/vmxnor.mm. */
2879 emit_insn (gen_rtx_SET (target, gen_rtx_NOT (mask_mode, eq0)));
2880 return false;
2881 }
2882
2883 /* Modulo all SEL indices to ensure they are all in range if [0, MAX_SEL].
2884 MAX_SEL is nunits - 1 if rtx_equal_p (op0, op1). Otherwise, it is
2885 2 * nunits - 1. */
2886 static rtx
2887 modulo_sel_indices (rtx op0, rtx op1, rtx sel)
2888 {
2889 rtx sel_mod;
2890 machine_mode sel_mode = GET_MODE (sel);
2891 poly_uint64 nunits = GET_MODE_NUNITS (sel_mode);
2892 poly_uint64 max_sel = rtx_equal_p (op0, op1) ? nunits - 1 : 2 * nunits - 1;
2893 /* If SEL is variable-length CONST_VECTOR, we don't need to modulo it.
2894 Or if SEL is constant-length within [0, MAX_SEL], no need to modulo the
2895 indice. */
2896 if (CONST_VECTOR_P (sel)
2897 && (!nunits.is_constant () || const_vec_all_in_range_p (sel, 0, max_sel)))
2898 sel_mod = sel;
2899 else
2900 {
2901 rtx mod = gen_const_vector_dup (sel_mode, max_sel);
2902 sel_mod
2903 = expand_simple_binop (sel_mode, AND, sel, mod, NULL, 0, OPTAB_DIRECT);
2904 }
2905 return sel_mod;
2906 }
2907
2908 /* Implement vec_perm<mode>. */
2909
2910 void
2911 expand_vec_perm (rtx target, rtx op0, rtx op1, rtx sel)
2912 {
2913 machine_mode data_mode = GET_MODE (target);
2914 machine_mode sel_mode = GET_MODE (sel);
2915 poly_uint64 nunits = GET_MODE_NUNITS (sel_mode);
2916
2917 /* Check if the sel only references the first values vector. If each select
2918 index is in range of [0, nunits - 1]. A single vrgather instructions is
2919 enough. Since we will use vrgatherei16.vv for variable-length vector,
2920 it is never out of range and we don't need to modulo the index. */
2921 if (nunits.is_constant () && const_vec_all_in_range_p (sel, 0, nunits - 1))
2922 {
2923 emit_vlmax_gather_insn (target, op0, sel);
2924 return;
2925 }
2926
2927 /* Check if all the indices are same. */
2928 rtx elt;
2929 if (const_vec_duplicate_p (sel, &elt))
2930 {
2931 poly_uint64 value = rtx_to_poly_int64 (elt);
2932 rtx op = op0;
2933 if (maybe_gt (value, nunits - 1))
2934 {
2935 sel = gen_const_vector_dup (sel_mode, value - nunits);
2936 op = op1;
2937 }
2938 emit_vlmax_gather_insn (target, op, sel);
2939 }
2940
2941 /* Note: vec_perm indices are supposed to wrap when they go beyond the
2942 size of the two value vectors, i.e. the upper bits of the indices
2943 are effectively ignored. RVV vrgather instead produces 0 for any
2944 out-of-range indices, so we need to modulo all the vec_perm indices
2945 to ensure they are all in range of [0, nunits - 1] when op0 == op1
2946 or all in range of [0, 2 * nunits - 1] when op0 != op1. */
2947 rtx sel_mod = modulo_sel_indices (op0, op1, sel);
2948
2949 /* Check if the two values vectors are the same. */
2950 if (rtx_equal_p (op0, op1))
2951 {
2952 emit_vlmax_gather_insn (target, op0, sel_mod);
2953 return;
2954 }
2955
2956 /* This following sequence is handling the case that:
2957 __builtin_shufflevector (vec1, vec2, index...), the index can be any
2958 value in range of [0, 2 * nunits - 1]. */
2959 machine_mode mask_mode;
2960 mask_mode = get_mask_mode (data_mode);
2961 rtx mask = gen_reg_rtx (mask_mode);
2962 rtx max_sel = gen_const_vector_dup (sel_mode, nunits);
2963 bool overlap = reg_overlap_mentioned_p (target, op1);
2964 rtx tmp_target = overlap ? gen_reg_rtx (data_mode) : target;
2965
2966 /* Step 1: generate a mask that should select everything >= nunits into the
2967 * mask. */
2968 expand_vec_cmp (mask, GEU, sel_mod, max_sel);
2969
2970 /* Step2: gather every op0 values indexed by sel into TMP_TARGET,
2971 we don't need to care about the result of the element
2972 whose index >= nunits. */
2973 emit_vlmax_gather_insn (tmp_target, op0, sel_mod);
2974
2975 /* Step3: shift the range from (nunits, max_of_mode] to
2976 [0, max_of_mode - nunits]. */
2977 rtx tmp = gen_reg_rtx (sel_mode);
2978 rtx ops[] = {tmp, sel_mod, max_sel};
2979 emit_vlmax_insn (code_for_pred (MINUS, sel_mode), BINARY_OP, ops);
2980
2981 /* Step4: gather those into the previously masked-out elements
2982 of target. */
2983 emit_vlmax_masked_gather_mu_insn (tmp_target, op1, tmp, mask);
2984
2985 if (overlap)
2986 emit_move_insn (target, tmp_target);
2987 }
2988
2989 /* Implement TARGET_VECTORIZE_VEC_PERM_CONST for RVV. */
2990
2991 /* vec_perm support. */
2992
2993 struct expand_vec_perm_d
2994 {
2995 rtx target, op0, op1;
2996 vec_perm_indices perm;
2997 machine_mode vmode;
2998 machine_mode op_mode;
2999 bool one_vector_p;
3000 bool testing_p;
3001 };
3002
3003 /* Return the appropriate index mode for gather instructions. */
3004 opt_machine_mode
3005 get_gather_index_mode (struct expand_vec_perm_d *d)
3006 {
3007 machine_mode sel_mode = related_int_vector_mode (d->vmode).require ();
3008 poly_uint64 nunits = GET_MODE_NUNITS (d->vmode);
3009
3010 if (GET_MODE_INNER (d->vmode) == QImode)
3011 {
3012 if (nunits.is_constant ())
3013 {
3014 /* If indice is LMUL8 CONST_VECTOR and any element value
3015 exceed the range of 0 ~ 255, Forbid such permutation
3016 since we need vector HI mode to hold such indice and
3017 we don't have it. */
3018 if (!d->perm.all_in_range_p (0, 255)
3019 && !get_vector_mode (HImode, nunits).exists (&sel_mode))
3020 return opt_machine_mode ();
3021 }
3022 else
3023 {
3024 /* Permuting two SEW8 variable-length vectors need vrgatherei16.vv.
3025 Otherwise, it could overflow the index range. */
3026 if (!get_vector_mode (HImode, nunits).exists (&sel_mode))
3027 return opt_machine_mode ();
3028 }
3029 }
3030 else if (riscv_get_v_regno_alignment (sel_mode) > 1
3031 && GET_MODE_INNER (sel_mode) != HImode)
3032 sel_mode = get_vector_mode (HImode, nunits).require ();
3033 return sel_mode;
3034 }
3035
3036 /* Recognize the patterns that we can use merge operation to shuffle the
3037 vectors. The value of Each element (index i) in selector can only be
3038 either i or nunits + i. We will check the pattern is actually monotonic.
3039
3040 E.g.
3041 v = VEC_PERM_EXPR (v0, v1, selector),
3042 selector = { 0, nunits + 1, 2, nunits + 3, 4, nunits + 5, ... }
3043
3044 We can transform such pattern into:
3045
3046 v = vcond_mask (v0, v1, mask),
3047 mask = { 0, 1, 0, 1, 0, 1, ... }. */
3048
3049 static bool
3050 shuffle_merge_patterns (struct expand_vec_perm_d *d)
3051 {
3052 machine_mode vmode = d->vmode;
3053 machine_mode sel_mode = related_int_vector_mode (vmode).require ();
3054 int n_patterns = d->perm.encoding ().npatterns ();
3055 poly_int64 vec_len = d->perm.length ();
3056
3057 for (int i = 0; i < n_patterns; ++i)
3058 if (!known_eq (d->perm[i], i) && !known_eq (d->perm[i], vec_len + i))
3059 return false;
3060
3061 /* Check the pattern is monotonic here, otherwise, return false. */
3062 for (int i = n_patterns; i < n_patterns * 2; i++)
3063 if (!d->perm.series_p (i, n_patterns, i, n_patterns)
3064 && !d->perm.series_p (i, n_patterns, vec_len + i, n_patterns))
3065 return false;
3066
3067 /* We need to use precomputed mask for such situation and such mask
3068 can only be computed in compile-time known size modes. */
3069 bool indices_fit_selector_p
3070 = GET_MODE_BITSIZE (GET_MODE_INNER (vmode)) > 8 || known_lt (vec_len, 256);
3071 if (!indices_fit_selector_p && !vec_len.is_constant ())
3072 return false;
3073
3074 if (d->testing_p)
3075 return true;
3076
3077 machine_mode mask_mode = get_mask_mode (vmode);
3078 rtx mask = gen_reg_rtx (mask_mode);
3079
3080 if (indices_fit_selector_p && vec_len.is_constant ())
3081 {
3082 /* For a constant vector length we can generate the needed mask at
3083 compile time and load it as mask at runtime.
3084 This saves a compare at runtime. */
3085 rtx_vector_builder sel (mask_mode, d->perm.encoding ().npatterns (),
3086 d->perm.encoding ().nelts_per_pattern ());
3087 unsigned int encoded_nelts = sel.encoded_nelts ();
3088 for (unsigned int i = 0; i < encoded_nelts; i++)
3089 sel.quick_push (gen_int_mode (d->perm[i].to_constant ()
3090 < vec_len.to_constant (),
3091 GET_MODE_INNER (mask_mode)));
3092 mask = sel.build ();
3093 }
3094 else if (indices_fit_selector_p)
3095 {
3096 /* For a dynamic vector length < 256 we keep the permutation
3097 indices in the literal pool, load it at runtime and create the
3098 mask by selecting either OP0 or OP1 by
3099
3100 INDICES < NUNITS ? 1 : 0. */
3101 rtx sel = vec_perm_indices_to_rtx (sel_mode, d->perm);
3102 rtx x = gen_int_mode (vec_len, GET_MODE_INNER (sel_mode));
3103 insn_code icode = code_for_pred_cmp_scalar (sel_mode);
3104 rtx cmp = gen_rtx_fmt_ee (LTU, mask_mode, sel, x);
3105 rtx ops[] = {mask, cmp, sel, x};
3106 emit_vlmax_insn (icode, COMPARE_OP, ops);
3107 }
3108 else
3109 {
3110 /* For EEW8 and NUNITS may be larger than 255, we can't use vmsltu
3111 directly to generate the selector mask, instead, we can only use
3112 precomputed mask.
3113
3114 E.g. selector = <0, 257, 2, 259> for EEW8 vector with NUNITS = 256, we
3115 don't have a QImode scalar register to hold larger than 255.
3116 We also cannot hold that in a vector QImode register if LMUL = 8, and,
3117 since there is no larger HI mode vector we cannot create a larger
3118 selector.
3119
3120 As the mask is a simple {0, 1, ...} pattern and the length is known we
3121 can store it in a scalar register and broadcast it to a mask register.
3122 */
3123 gcc_assert (vec_len.is_constant ());
3124 int size = CEIL (GET_MODE_NUNITS (mask_mode).to_constant (), 8);
3125 machine_mode mode = get_vector_mode (QImode, size).require ();
3126 rtx tmp = gen_reg_rtx (mode);
3127 rvv_builder v (mode, 1, size);
3128 for (int i = 0; i < vec_len.to_constant () / 8; i++)
3129 {
3130 uint8_t value = 0;
3131 for (int j = 0; j < 8; j++)
3132 {
3133 int index = i * 8 + j;
3134 if (known_lt (d->perm[index], 256))
3135 value |= 1 << j;
3136 }
3137 v.quick_push (gen_int_mode (value, QImode));
3138 }
3139 emit_move_insn (tmp, v.build ());
3140 emit_move_insn (mask, gen_lowpart (mask_mode, tmp));
3141 }
3142
3143 /* TARGET = MASK ? OP0 : OP1. */
3144 /* swap op0 and op1 since the order is opposite to pred_merge. */
3145 rtx ops2[] = {d->target, d->op1, d->op0, mask};
3146 emit_vlmax_insn (code_for_pred_merge (vmode), MERGE_OP, ops2);
3147 return true;
3148 }
3149
3150 /* Recognize the consecutive index that we can use a single
3151 vrgather.v[x|i] to shuffle the vectors.
3152
3153 e.g. short[8] = VEC_PERM_EXPR <a, a, {0,1,0,1,0,1,0,1}>
3154 Use SEW = 32, index = 1 vrgather.vi to get the result. */
3155 static bool
3156 shuffle_consecutive_patterns (struct expand_vec_perm_d *d)
3157 {
3158 machine_mode vmode = d->vmode;
3159 scalar_mode smode = GET_MODE_INNER (vmode);
3160 poly_int64 vec_len = d->perm.length ();
3161 HOST_WIDE_INT elt;
3162
3163 if (!vec_len.is_constant () || !d->perm[0].is_constant (&elt))
3164 return false;
3165 int vlen = vec_len.to_constant ();
3166
3167 /* Compute the last element index of consecutive pattern from the leading
3168 consecutive elements. */
3169 int last_consecutive_idx = -1;
3170 int consecutive_num = -1;
3171 for (int i = 1; i < vlen; i++)
3172 {
3173 if (maybe_ne (d->perm[i], d->perm[i - 1] + 1))
3174 break;
3175 last_consecutive_idx = i;
3176 consecutive_num = last_consecutive_idx + 1;
3177 }
3178
3179 int new_vlen = vlen / consecutive_num;
3180 if (last_consecutive_idx < 0 || consecutive_num == vlen
3181 || !pow2p_hwi (consecutive_num) || !pow2p_hwi (new_vlen))
3182 return false;
3183 /* VEC_PERM <..., (index, index + 1, ... index + consecutive_num - 1)>.
3184 All elements of index, index + 1, ... index + consecutive_num - 1 should
3185 locate at the same vector. */
3186 if (maybe_ge (d->perm[0], vec_len)
3187 != maybe_ge (d->perm[last_consecutive_idx], vec_len))
3188 return false;
3189 /* If a vector has 8 elements. We allow optimizations on consecutive
3190 patterns e.g. <0, 1, 2, 3, 0, 1, 2, 3> or <4, 5, 6, 7, 4, 5, 6, 7>.
3191 Other patterns like <2, 3, 4, 5, 2, 3, 4, 5> are not feasible patterns
3192 to be optimized. */
3193 if (d->perm[0].to_constant () % consecutive_num != 0)
3194 return false;
3195 unsigned int container_bits = consecutive_num * GET_MODE_BITSIZE (smode);
3196 if (container_bits > 64)
3197 return false;
3198 else if (container_bits == 64)
3199 {
3200 if (!TARGET_VECTOR_ELEN_64)
3201 return false;
3202 else if (FLOAT_MODE_P (smode) && !TARGET_VECTOR_ELEN_FP_64)
3203 return false;
3204 }
3205
3206 /* Check the rest of elements are the same consecutive pattern. */
3207 for (int i = consecutive_num; i < vlen; i++)
3208 if (maybe_ne (d->perm[i], d->perm[i % consecutive_num]))
3209 return false;
3210
3211 if (FLOAT_MODE_P (smode))
3212 smode = float_mode_for_size (container_bits).require ();
3213 else
3214 smode = int_mode_for_size (container_bits, 0).require ();
3215 if (!get_vector_mode (smode, new_vlen).exists (&vmode))
3216 return false;
3217 machine_mode sel_mode = related_int_vector_mode (vmode).require ();
3218
3219 /* Success! */
3220 if (d->testing_p)
3221 return true;
3222
3223 int index = elt / consecutive_num;
3224 if (index >= new_vlen)
3225 index = index - new_vlen;
3226 rtx sel = gen_const_vector_dup (sel_mode, index);
3227 rtx op = elt >= vlen ? d->op0 : d->op1;
3228 emit_vlmax_gather_insn (gen_lowpart (vmode, d->target),
3229 gen_lowpart (vmode, op), sel);
3230 return true;
3231 }
3232
3233 /* Recognize the patterns that we can use compress operation to shuffle the
3234 vectors. The perm selector of compress pattern is divided into 2 part:
3235 The first part is the random index number < NUNITS.
3236 The second part is consecutive last N index number >= NUNITS.
3237
3238 E.g.
3239 v = VEC_PERM_EXPR (v0, v1, selector),
3240 selector = { 0, 2, 6, 7 }
3241
3242 We can transform such pattern into:
3243
3244 op1 = vcompress (op0, mask)
3245 mask = { 1, 0, 1, 0 }
3246 v = op1. */
3247
3248 static bool
3249 shuffle_compress_patterns (struct expand_vec_perm_d *d)
3250 {
3251 machine_mode vmode = d->vmode;
3252 poly_int64 vec_len = d->perm.length ();
3253
3254 if (!vec_len.is_constant ())
3255 return false;
3256
3257 int vlen = vec_len.to_constant ();
3258
3259 /* It's not worthwhile the compress pattern has elements < 4
3260 and we can't modulo indices for compress pattern. */
3261 if (known_ge (d->perm[vlen - 1], vlen * 2) || vlen < 4)
3262 return false;
3263
3264 /* Compress pattern doesn't work for one vector. */
3265 if (d->one_vector_p)
3266 return false;
3267
3268 /* Compress point is the point that all elements value with index i >=
3269 compress point of the selector are all consecutive series increasing and
3270 each selector value >= NUNITS. In this case, we could compress all elements
3271 of i < compress point into the op1. */
3272 int compress_point = -1;
3273 for (int i = 0; i < vlen; i++)
3274 {
3275 if (compress_point < 0 && known_ge (d->perm[i], vec_len))
3276 {
3277 compress_point = i;
3278 break;
3279 }
3280 }
3281
3282 /* We don't apply compress approach if we can't find the compress point. */
3283 if (compress_point < 0)
3284 return false;
3285
3286 /* We can only apply compress approach when all index values from 0 to
3287 compress point are increasing. */
3288 for (int i = 1; i < compress_point; i++)
3289 if (maybe_le (d->perm[i], d->perm[i - 1]))
3290 return false;
3291
3292 /* It must be series increasing from compress point. */
3293 for (int i = 1 + compress_point; i < vlen; i++)
3294 if (maybe_ne (d->perm[i], d->perm[i - 1] + 1))
3295 return false;
3296
3297 /* Success! */
3298 if (d->testing_p)
3299 return true;
3300
3301 /* Check whether we need to slideup op1 to apply compress approach.
3302
3303 E.g. For index = { 0, 2, 6, 7}, since d->perm[i - 1] = 7 which
3304 is 2 * NUNITS - 1, so we don't need to slide up.
3305
3306 For index = { 0, 2, 5, 6}, we need to slide op1 up before
3307 we apply compress approach. */
3308 bool need_slideup_p = maybe_ne (d->perm[vlen - 1], 2 * vec_len - 1)
3309 && !const_vec_duplicate_p (d->op1);
3310
3311 /* If we leave it directly be handled by general gather,
3312 the code sequence will be:
3313 VECTOR LOAD selector
3314 GEU mask, selector, NUNITS
3315 GATHER dest, op0, selector
3316 SUB selector, selector, NUNITS
3317 GATHER dest, op1, selector, mask
3318 Each ALU operation is considered as COST = 1 and VECTOR LOAD is considered
3319 as COST = 4. So, we consider the general gather handling COST = 9.
3320 TODO: This cost is not accurate, we can adjust it by tune info. */
3321 int general_cost = 9;
3322
3323 /* If we can use compress approach, the code sequence will be:
3324 MASK LOAD mask
3325 COMPRESS op1, op0, mask
3326 If it needs slide up, it will be:
3327 MASK LOAD mask
3328 SLIDEUP op1
3329 COMPRESS op1, op0, mask
3330 By default, mask load COST = 2.
3331 TODO: This cost is not accurate, we can adjust it by tune info. */
3332 int compress_cost = 4;
3333
3334 if (general_cost <= compress_cost)
3335 return false;
3336
3337 /* Build a mask that is true when selector element is true. */
3338 machine_mode mask_mode = get_mask_mode (vmode);
3339 rvv_builder builder (mask_mode, vlen, 1);
3340 for (int i = 0; i < vlen; i++)
3341 {
3342 bool is_compress_index = false;
3343 for (int j = 0; j < compress_point; j++)
3344 {
3345 if (known_eq (d->perm[j], i))
3346 {
3347 is_compress_index = true;
3348 break;
3349 }
3350 }
3351 if (is_compress_index)
3352 builder.quick_push (CONST1_RTX (BImode));
3353 else
3354 builder.quick_push (CONST0_RTX (BImode));
3355 }
3356 rtx mask = force_reg (mask_mode, builder.build ());
3357
3358 rtx merge = d->op1;
3359 if (need_slideup_p)
3360 {
3361 int slideup_cnt = vlen - (d->perm[vlen - 1].to_constant () % vlen) - 1;
3362 merge = gen_reg_rtx (vmode);
3363 rtx ops[] = {merge, d->op1, gen_int_mode (slideup_cnt, Pmode)};
3364 insn_code icode = code_for_pred_slide (UNSPEC_VSLIDEUP, vmode);
3365 emit_vlmax_insn (icode, BINARY_OP, ops);
3366 }
3367
3368 insn_code icode = code_for_pred_compress (vmode);
3369 rtx ops[] = {d->target, merge, d->op0, mask};
3370 emit_nonvlmax_insn (icode, COMPRESS_OP_MERGE, ops,
3371 gen_int_mode (vlen, Pmode));
3372 return true;
3373 }
3374
3375 /* Recognize patterns like [4 5 6 7 12 13 14 15] where either the lower
3376 or the higher parts of both vectors are combined into one. */
3377
3378 static bool
3379 shuffle_slide_patterns (struct expand_vec_perm_d *d)
3380 {
3381 machine_mode vmode = d->vmode;
3382 poly_int64 vec_len = d->perm.length ();
3383
3384 if (!vec_len.is_constant ())
3385 return false;
3386
3387 int vlen = vec_len.to_constant ();
3388 if (vlen < 4)
3389 return false;
3390
3391 if (d->one_vector_p)
3392 return false;
3393
3394 /* For a slideup OP0 can stay, for a slidedown OP1 can.
3395 The former requires that the first element of the permutation
3396 is the first element of OP0, the latter that the last permutation
3397 element is the last element of OP1. */
3398 bool slideup = false;
3399 bool slidedown = false;
3400
3401 /* For a slideup the permutation must start at OP0's first element. */
3402 if (known_eq (d->perm[0], 0))
3403 slideup = true;
3404
3405 /* For a slidedown the permutation must end at OP1's last element. */
3406 if (known_eq (d->perm[vlen - 1], 2 * vlen - 1))
3407 slidedown = true;
3408
3409 if (slideup && slidedown)
3410 return false;
3411
3412 if (!slideup && !slidedown)
3413 return false;
3414
3415 /* Check for a monotonic sequence with one pivot. */
3416 int pivot = -1;
3417 for (int i = 0; i < vlen; i++)
3418 {
3419 if (pivot == -1 && known_ge (d->perm[i], vec_len))
3420 pivot = i;
3421 if (i > 0 && i != pivot
3422 && maybe_ne (d->perm[i], d->perm[i - 1] + 1))
3423 return false;
3424 }
3425
3426 if (pivot == -1)
3427 return false;
3428
3429 /* For a slideup OP1's part (to be slid up) must be a low part,
3430 i.e. starting with its first element. */
3431 if (slideup && maybe_ne (d->perm[pivot], vlen))
3432 return false;
3433
3434 /* For a slidedown OP0's part (to be slid down) must be a high part,
3435 i.e. ending with its last element. */
3436 if (slidedown && maybe_ne (d->perm[pivot - 1], vlen - 1))
3437 return false;
3438
3439 /* Success! */
3440 if (d->testing_p)
3441 return true;
3442
3443 /* PIVOT is the start of the lower/higher part of OP1 or OP2.
3444 For a slideup it indicates how many elements of OP1 to
3445 skip/slide over. For a slidedown it indicates how long
3446 OP1's high part is, while VLEN - PIVOT is the amount to slide. */
3447 int slide_cnt = slideup ? pivot : vlen - pivot;
3448 insn_code icode;
3449 if (slideup)
3450 {
3451 /* No need for a vector length because we slide up until the
3452 end of OP1 anyway. */
3453 rtx ops[] = {d->target, d->op0, d->op1, gen_int_mode (slide_cnt, Pmode)};
3454 icode = code_for_pred_slide (UNSPEC_VSLIDEUP, vmode);
3455 emit_vlmax_insn (icode, SLIDEUP_OP_MERGE, ops);
3456 }
3457 else
3458 {
3459 /* Here we need a length because we slide to the beginning of OP1
3460 leaving the remaining elements undisturbed. */
3461 int len = pivot;
3462 rtx ops[] = {d->target, d->op1, d->op0,
3463 gen_int_mode (slide_cnt, Pmode)};
3464 icode = code_for_pred_slide (UNSPEC_VSLIDEDOWN, vmode);
3465 emit_nonvlmax_insn (icode, BINARY_OP_TUMA, ops,
3466 gen_int_mode (len, Pmode));
3467 }
3468
3469 return true;
3470 }
3471
3472 /* Recognize interleaving patterns like [0 4 1 5]. */
3473
3474 static bool
3475 shuffle_interleave_patterns (struct expand_vec_perm_d *d)
3476 {
3477 machine_mode vmode = d->vmode;
3478 machine_mode sel_mode = related_int_vector_mode (vmode).require ();
3479 poly_int64 vec_len = d->perm.length ();
3480 int n_patterns = d->perm.encoding ().npatterns ();
3481
3482 if (!vec_len.is_constant ())
3483 return false;
3484
3485 if (n_patterns != 2)
3486 return false;
3487
3488 unsigned vlen = vec_len.to_constant ();
3489
3490 if (vlen < 4 || vlen > 64)
3491 return false;
3492
3493 if (d->one_vector_p)
3494 return false;
3495
3496 bool low = true;
3497 if (d->perm.series_p (0, 2, 0, 1)
3498 && d->perm.series_p (1, 2, vlen, 1))
3499 low = true;
3500 else if (d->perm.series_p (0, 2, vlen / 2, 1)
3501 && d->perm.series_p (1, 2, vlen + vlen / 2, 1))
3502 low = false;
3503 else
3504 return false;
3505
3506 vec_perm_builder sel (vlen, 2, 1);
3507 sel.safe_grow (vlen);
3508 int cnt = 0;
3509 for (unsigned i = 0; i < vlen; i += 2)
3510 {
3511 sel[i] = cnt;
3512 sel[i + 1] = cnt + vlen / 2;
3513 cnt++;
3514 }
3515
3516 vec_perm_indices indices (sel, 2, vlen);
3517
3518 if (vlen != indices.length ().to_constant ())
3519 return false;
3520
3521 /* Success! */
3522 if (d->testing_p)
3523 return true;
3524
3525 int slide_cnt = vlen / 2;
3526 rtx tmp = gen_reg_rtx (vmode);
3527
3528 if (low)
3529 {
3530 /* No need for a vector length because we slide up until the
3531 end of OP1 anyway. */
3532 rtx ops[] = {tmp, d->op0, d->op1, gen_int_mode (slide_cnt, Pmode)};
3533 insn_code icode = code_for_pred_slide (UNSPEC_VSLIDEUP, vmode);
3534 emit_vlmax_insn (icode, SLIDEUP_OP_MERGE, ops);
3535 }
3536 else
3537 {
3538 rtx ops[] = {tmp, d->op1, d->op0, gen_int_mode (slide_cnt, Pmode)};
3539 insn_code icode = code_for_pred_slide (UNSPEC_VSLIDEDOWN, vmode);
3540 emit_nonvlmax_insn (icode, BINARY_OP_TUMA, ops,
3541 gen_int_mode (slide_cnt, Pmode));
3542 }
3543
3544 rtx sel_rtx = vec_perm_indices_to_rtx (sel_mode, indices);
3545 emit_vlmax_gather_insn (gen_lowpart (vmode, d->target), tmp, sel_rtx);
3546
3547 return true;
3548 }
3549
3550
3551 /* Recognize even/odd patterns like [0 2 4 6]. We use two compress
3552 and one slideup. */
3553
3554 static bool
3555 shuffle_even_odd_patterns (struct expand_vec_perm_d *d)
3556 {
3557 machine_mode vmode = d->vmode;
3558 poly_int64 vec_len = d->perm.length ();
3559 int n_patterns = d->perm.encoding ().npatterns ();
3560
3561 if (n_patterns != 1)
3562 return false;
3563
3564 if (!vec_len.is_constant ())
3565 return false;
3566
3567 int vlen = vec_len.to_constant ();
3568 if (vlen < 4 || vlen > 64)
3569 return false;
3570
3571 if (d->one_vector_p)
3572 return false;
3573
3574 bool even = true;
3575 if (!d->perm.series_p (0, 1, 0, 2))
3576 {
3577 even = false;
3578 if (!d->perm.series_p (0, 1, 1, 2))
3579 return false;
3580 }
3581
3582 /* Success! */
3583 if (d->testing_p)
3584 return true;
3585
3586 machine_mode mask_mode = get_mask_mode (vmode);
3587 rvv_builder builder (mask_mode, vlen, 1);
3588 int bit = even ? 0 : 1;
3589 for (int i = 0; i < vlen; i++)
3590 {
3591 bit ^= 1;
3592 if (bit)
3593 builder.quick_push (CONST1_RTX (BImode));
3594 else
3595 builder.quick_push (CONST0_RTX (BImode));
3596 }
3597 rtx mask = force_reg (mask_mode, builder.build ());
3598
3599 insn_code icode = code_for_pred_compress (vmode);
3600 rtx ops1[] = {d->target, d->op0, mask};
3601 emit_vlmax_insn (icode, COMPRESS_OP, ops1);
3602
3603 rtx tmp2 = gen_reg_rtx (vmode);
3604 rtx ops2[] = {tmp2, d->op1, mask};
3605 emit_vlmax_insn (icode, COMPRESS_OP, ops2);
3606
3607 rtx ops[] = {d->target, d->target, tmp2, gen_int_mode (vlen / 2, Pmode)};
3608 icode = code_for_pred_slide (UNSPEC_VSLIDEUP, vmode);
3609 emit_vlmax_insn (icode, SLIDEUP_OP_MERGE, ops);
3610
3611 return true;
3612 }
3613
3614 /* Recognize decompress patterns:
3615
3616 1. VEC_PERM_EXPR op0 and op1
3617 with isel = { 0, nunits, 1, nunits + 1, ... }.
3618 Decompress op0 and op1 vector with the mask = { 0, 1, 0, 1, ... }.
3619
3620 2. VEC_PERM_EXPR op0 and op1
3621 with isel = { 1/2 nunits, 3/2 nunits, 1/2 nunits+1, 3/2 nunits+1,... }.
3622 Slide down op0 and op1 with OFFSET = 1/2 nunits.
3623 Decompress op0 and op1 vector with the mask = { 0, 1, 0, 1, ... }.
3624 */
3625 static bool
3626 shuffle_decompress_patterns (struct expand_vec_perm_d *d)
3627 {
3628 poly_uint64 nelt = d->perm.length ();
3629 machine_mode mask_mode = get_mask_mode (d->vmode);
3630
3631 /* For constant size indices, we dont't need to handle it here.
3632 Just leave it to vec_perm<mode>. */
3633 if (d->perm.length ().is_constant ())
3634 return false;
3635
3636 poly_uint64 first = d->perm[0];
3637 if ((maybe_ne (first, 0U) && maybe_ne (first * 2, nelt))
3638 || !d->perm.series_p (0, 2, first, 1)
3639 || !d->perm.series_p (1, 2, first + nelt, 1))
3640 return false;
3641
3642 /* Permuting two SEW8 variable-length vectors need vrgatherei16.vv.
3643 Otherwise, it could overflow the index range. */
3644 machine_mode sel_mode = related_int_vector_mode (d->vmode).require ();
3645 if (GET_MODE_INNER (d->vmode) == QImode
3646 && !get_vector_mode (HImode, nelt).exists (&sel_mode))
3647 return false;
3648
3649 /* Success! */
3650 if (d->testing_p)
3651 return true;
3652
3653 rtx op0, op1;
3654 if (known_eq (first, 0U))
3655 {
3656 op0 = d->op0;
3657 op1 = d->op1;
3658 }
3659 else
3660 {
3661 op0 = gen_reg_rtx (d->vmode);
3662 op1 = gen_reg_rtx (d->vmode);
3663 insn_code icode = code_for_pred_slide (UNSPEC_VSLIDEDOWN, d->vmode);
3664 rtx ops0[] = {op0, d->op0, gen_int_mode (first, Pmode)};
3665 rtx ops1[] = {op1, d->op1, gen_int_mode (first, Pmode)};
3666 emit_vlmax_insn (icode, BINARY_OP, ops0);
3667 emit_vlmax_insn (icode, BINARY_OP, ops1);
3668 }
3669 /* Generate { 0, 1, .... } mask. */
3670 rtx vid = gen_reg_rtx (sel_mode);
3671 rtx vid_repeat = gen_reg_rtx (sel_mode);
3672 expand_vec_series (vid, const0_rtx, const1_rtx);
3673 rtx and_ops[] = {vid_repeat, vid, const1_rtx};
3674 emit_vlmax_insn (code_for_pred_scalar (AND, sel_mode), BINARY_OP, and_ops);
3675 rtx const_vec = gen_const_vector_dup (sel_mode, 1);
3676 rtx mask = gen_reg_rtx (mask_mode);
3677 expand_vec_cmp (mask, EQ, vid_repeat, const_vec);
3678 emit_vlmax_decompress_insn (d->target, op0, op1, mask);
3679 return true;
3680 }
3681
3682 static bool
3683 shuffle_bswap_pattern (struct expand_vec_perm_d *d)
3684 {
3685 HOST_WIDE_INT diff;
3686 unsigned i, size, step;
3687
3688 if (!d->one_vector_p || !d->perm[0].is_constant (&diff) || !diff)
3689 return false;
3690
3691 step = diff + 1;
3692 size = step * GET_MODE_UNIT_BITSIZE (d->vmode);
3693
3694 switch (size)
3695 {
3696 case 16:
3697 break;
3698 case 32:
3699 case 64:
3700 /* We will have VEC_PERM_EXPR after rtl expand when invoking
3701 __builtin_bswap. It will generate about 9 instructions in
3702 loop as below, no matter it is bswap16, bswap32 or bswap64.
3703 .L2:
3704 1 vle16.v v4,0(a0)
3705 2 vmv.v.x v2,a7
3706 3 vand.vv v2,v6,v2
3707 4 slli a2,a5,1
3708 5 vrgatherei16.vv v1,v4,v2
3709 6 sub a4,a4,a5
3710 7 vse16.v v1,0(a3)
3711 8 add a0,a0,a2
3712 9 add a3,a3,a2
3713 bne a4,zero,.L2
3714
3715 But for bswap16 we may have a even simple code gen, which
3716 has only 7 instructions in loop as below.
3717 .L5
3718 1 vle8.v v2,0(a5)
3719 2 addi a5,a5,32
3720 3 vsrl.vi v4,v2,8
3721 4 vsll.vi v2,v2,8
3722 5 vor.vv v4,v4,v2
3723 6 vse8.v v4,0(a4)
3724 7 addi a4,a4,32
3725 bne a5,a6,.L5
3726
3727 Unfortunately, the instructions in loop will grow to 13 and 24
3728 for bswap32 and bswap64. Thus, we will leverage vrgather (9 insn)
3729 for both the bswap64 and bswap32, but take shift and or (7 insn)
3730 for bswap16.
3731 */
3732 default:
3733 return false;
3734 }
3735
3736 for (i = 0; i < step; i++)
3737 if (!d->perm.series_p (i, step, diff - i, step))
3738 return false;
3739
3740 /* Disable when nunits < 4 since the later generic approach
3741 is more profitable on BSWAP. */
3742 if (!known_gt (GET_MODE_NUNITS (d->vmode), 2))
3743 return false;
3744
3745 if (d->testing_p)
3746 return true;
3747
3748 machine_mode vhi_mode;
3749 poly_uint64 vhi_nunits = exact_div (GET_MODE_NUNITS (d->vmode), 2);
3750
3751 if (!get_vector_mode (HImode, vhi_nunits).exists (&vhi_mode))
3752 return false;
3753
3754 /* Step-1: Move op0 to src with VHI mode. */
3755 rtx src = gen_reg_rtx (vhi_mode);
3756 emit_move_insn (src, gen_lowpart (vhi_mode, d->op0));
3757
3758 /* Step-2: Shift right 8 bits to dest. */
3759 rtx dest = expand_binop (vhi_mode, lshr_optab, src, gen_int_mode (8, Pmode),
3760 NULL_RTX, 0, OPTAB_DIRECT);
3761
3762 /* Step-3: Shift left 8 bits to src. */
3763 src = expand_binop (vhi_mode, ashl_optab, src, gen_int_mode (8, Pmode),
3764 NULL_RTX, 0, OPTAB_DIRECT);
3765
3766 /* Step-4: Logic Or dest and src to dest. */
3767 dest = expand_binop (vhi_mode, ior_optab, dest, src,
3768 NULL_RTX, 0, OPTAB_DIRECT);
3769
3770 /* Step-5: Move src to target with VQI mode. */
3771 emit_move_insn (d->target, gen_lowpart (d->vmode, dest));
3772
3773 return true;
3774 }
3775
3776 /* Recognize patterns like [3 4 5 6] where we combine the last element
3777 of the first vector and the first n - 1 elements of the second vector.
3778 This can be implemented by slides or by extracting and re-inserting
3779 (slide1up) the first vector's last element. */
3780
3781 static bool
3782 shuffle_off_by_one_patterns (struct expand_vec_perm_d *d)
3783 {
3784 poly_int64 nunits = GET_MODE_NUNITS (d->vmode);
3785
3786 /* Recognize { nunits - 1, nunits, nunits + 1, ... }. */
3787 if (!d->perm.series_p (0, 2, nunits - 1, 2)
3788 || !d->perm.series_p (1, 2, nunits, 2))
3789 return false;
3790
3791 /* Disable when nunits < 4 since the later generic approach
3792 is more profitable on indice = { nunits - 1, nunits }. */
3793 if (!known_gt (nunits, 2))
3794 return false;
3795
3796 /* Success! */
3797 if (d->testing_p)
3798 return true;
3799
3800 int scalar_cost = riscv_register_move_cost (d->vmode, V_REGS, GR_REGS)
3801 + riscv_register_move_cost (d->vmode, GR_REGS, V_REGS) + 2;
3802 int slide_cost = 2;
3803
3804 if (slide_cost < scalar_cost)
3805 {
3806 /* This variant should always be preferable because we just need two
3807 slides. The extract-variant also requires two slides but additionally
3808 pays the latency for register-file crossing. */
3809 rtx tmp = gen_reg_rtx (d->vmode);
3810 rtx ops[] = {tmp, d->op1, gen_int_mode (1, Pmode)};
3811 insn_code icode = code_for_pred_slide (UNSPEC_VSLIDEUP, d->vmode);
3812 emit_vlmax_insn (icode, BINARY_OP, ops);
3813
3814 rtx ops2[] = {d->target, tmp, d->op0, gen_int_mode (nunits - 1, Pmode)};
3815 icode = code_for_pred_slide (UNSPEC_VSLIDEDOWN, d->vmode);
3816 emit_nonvlmax_insn (icode, BINARY_OP_TUMA, ops2, gen_int_mode (1, Pmode));
3817 }
3818 else
3819 {
3820 /* Extract the last element of the first vector. */
3821 scalar_mode smode = GET_MODE_INNER (d->vmode);
3822 rtx tmp = gen_reg_rtx (smode);
3823 emit_vec_extract (tmp, d->op0, gen_int_mode (nunits - 1, Pmode));
3824
3825 /* Insert the scalar into element 0. */
3826 unsigned int unspec
3827 = FLOAT_MODE_P (d->vmode) ? UNSPEC_VFSLIDE1UP : UNSPEC_VSLIDE1UP;
3828 insn_code icode = code_for_pred_slide (unspec, d->vmode);
3829 rtx ops[] = {d->target, d->op1, tmp};
3830 emit_vlmax_insn (icode, BINARY_OP, ops);
3831 }
3832
3833 return true;
3834 }
3835
3836 /* This looks for a series pattern in the provided vector permute structure D.
3837 If successful it emits a series insn as well as a gather to implement it.
3838 Return true if successful, false otherwise. */
3839
3840 static bool
3841 shuffle_series_patterns (struct expand_vec_perm_d *d)
3842 {
3843 if (!d->one_vector_p || d->perm.encoding ().npatterns () != 1)
3844 return false;
3845
3846 poly_int64 el1 = d->perm[0];
3847 poly_int64 el2 = d->perm[1];
3848 poly_int64 el3 = d->perm[2];
3849
3850 poly_int64 step1 = el2 - el1;
3851 poly_int64 step2 = el3 - el2;
3852
3853 bool need_insert = false;
3854 bool have_series = false;
3855
3856 poly_int64 len = d->perm.length ();
3857 bool need_modulo = !len.is_constant ();
3858
3859 /* Check for a full series. */
3860 if (known_ne (step1, 0) && d->perm.series_p (0, 1, el1, step1))
3861 have_series = true;
3862
3863 /* Check for a series starting at the second element. */
3864 else if (known_ne (step2, 0) && d->perm.series_p (1, 1, el2, step2))
3865 {
3866 have_series = true;
3867 need_insert = true;
3868 }
3869
3870 /* A permute like {0, 3, 2, 1} is recognized as series because series_p also
3871 allows wrapping/modulo of the permute index. The step would be 3 and the
3872 indices are correct modulo 4. As noted in expand_vec_perm vrgather does
3873 not handle wrapping but rather zeros out-of-bounds indices.
3874 This means we would need to emit an explicit modulo operation here which
3875 does not seem worth it. We rather defer to the generic handling instead.
3876 Even in the non-wrapping case it is doubtful whether
3877 vid
3878 vmul
3879 vrgather
3880 is preferable over
3881 vle
3882 vrgather.
3883 If the permute mask can be reused there shouldn't be any difference and
3884 otherwise it becomes a question of load bandwidth. */
3885 if (have_series && len.is_constant ())
3886 {
3887 int64_t step = need_insert ? step2.to_constant () : step1.to_constant ();
3888 int prec = GET_MODE_PRECISION (GET_MODE_INNER (d->vmode));
3889 wide_int wlen = wide_int::from (len.to_constant (), prec * 2, SIGNED);
3890 wide_int wstep = wide_int::from (step, prec * 2, SIGNED);
3891 wide_int result = wi::mul (wlen, wstep);
3892 if (wi::gt_p (result, wlen, SIGNED))
3893 need_modulo = true;
3894 }
3895
3896 if (!have_series || (len.is_constant () && need_modulo))
3897 return false;
3898
3899 /* Disable shuffle if we can't find an appropriate integer index mode for
3900 gather. */
3901 machine_mode sel_mode;
3902 if (!get_gather_index_mode (d).exists (&sel_mode))
3903 return false;
3904
3905 /* Success! */
3906 if (d->testing_p)
3907 return true;
3908
3909 /* Create the series. */
3910 machine_mode eltmode = Pmode;
3911 rtx series = gen_reg_rtx (sel_mode);
3912 expand_vec_series (series, gen_int_mode (need_insert ? el2 : el1, eltmode),
3913 gen_int_mode (need_insert ? step2 : step1, eltmode));
3914
3915 if (need_modulo)
3916 {
3917 rtx mod = gen_const_vector_dup (sel_mode, len - 1);
3918 series = expand_simple_binop (sel_mode, AND, series, mod, NULL,
3919 0, OPTAB_DIRECT);
3920 }
3921
3922 /* Insert the remaining element if necessary. */
3923 if (need_insert)
3924 {
3925 insn_code icode = code_for_pred_slide (UNSPEC_VSLIDE1UP, sel_mode);
3926 rtx ops[]
3927 = {series, series, gen_int_mode (el1, GET_MODE_INNER (sel_mode))};
3928 emit_vlmax_insn (icode, BINARY_OP, ops);
3929 }
3930
3931 emit_vlmax_gather_insn (d->target, d->op0, series);
3932
3933 return true;
3934 }
3935
3936 /* Recognize the pattern that can be shuffled by generic approach. */
3937
3938 static bool
3939 shuffle_generic_patterns (struct expand_vec_perm_d *d)
3940 {
3941 machine_mode sel_mode;
3942
3943 /* We don't enable SLP for non-power of 2 NPATTERNS. */
3944 if (!pow2p_hwi (d->perm.encoding().npatterns ()))
3945 return false;
3946
3947 /* Disable shuffle if we can't find an appropriate integer index mode for
3948 gather. */
3949 if (!get_gather_index_mode (d).exists (&sel_mode))
3950 return false;
3951
3952 rtx sel = vec_perm_indices_to_rtx (sel_mode, d->perm);
3953 poly_uint64 nunits = GET_MODE_NUNITS (sel_mode);
3954 rtx elt;
3955
3956 bool is_simple = d->one_vector_p
3957 || const_vec_duplicate_p (sel, &elt)
3958 || (nunits.is_constant ()
3959 && const_vec_all_in_range_p (sel, 0, nunits - 1));
3960
3961 if (!is_simple && !riscv_two_source_permutes)
3962 return false;
3963
3964 /* Success! */
3965 if (d->testing_p)
3966 return true;
3967
3968 /* Some FIXED-VLMAX/VLS vector permutation situations call targethook
3969 instead of expand vec_perm<mode>, we handle it directly. */
3970 expand_vec_perm (d->target, d->op0, d->op1, sel);
3971 return true;
3972 }
3973
3974 /* This function recognizes and supports different permutation patterns
3975 and enable VLA SLP auto-vectorization. */
3976 static bool
3977 expand_vec_perm_const_1 (struct expand_vec_perm_d *d)
3978 {
3979 gcc_assert (d->op_mode != E_VOIDmode);
3980
3981 /* The pattern matching functions above are written to look for a small
3982 number to begin the sequence (0, 1, N/2). If we begin with an index
3983 from the second operand, we can swap the operands. */
3984 poly_int64 nelt = d->perm.length ();
3985 if (known_ge (d->perm[0], nelt))
3986 {
3987 d->perm.rotate_inputs (1);
3988 std::swap (d->op0, d->op1);
3989 }
3990
3991 if (known_gt (nelt, 1))
3992 {
3993 if (d->vmode == d->op_mode)
3994 {
3995 if (shuffle_merge_patterns (d))
3996 return true;
3997 if (shuffle_consecutive_patterns (d))
3998 return true;
3999 if (shuffle_slide_patterns (d))
4000 return true;
4001 if (shuffle_interleave_patterns (d))
4002 return true;
4003 if (shuffle_even_odd_patterns (d))
4004 return true;
4005 if (shuffle_compress_patterns (d))
4006 return true;
4007 if (shuffle_decompress_patterns (d))
4008 return true;
4009 if (shuffle_bswap_pattern (d))
4010 return true;
4011 if (shuffle_off_by_one_patterns (d))
4012 return true;
4013 if (shuffle_series_patterns (d))
4014 return true;
4015 if (shuffle_generic_patterns (d))
4016 return true;
4017 return false;
4018 }
4019 else
4020 return false;
4021 }
4022 return false;
4023 }
4024
4025 /* This function implements TARGET_VECTORIZE_VEC_PERM_CONST by using RVV
4026 * instructions. */
4027 bool
4028 expand_vec_perm_const (machine_mode vmode, machine_mode op_mode, rtx target,
4029 rtx op0, rtx op1, const vec_perm_indices &sel)
4030 {
4031 /* RVV doesn't have Mask type pack/unpack instructions and we don't use
4032 mask to do the iteration loop control. Just disable it directly. */
4033 if (GET_MODE_CLASS (vmode) == MODE_VECTOR_BOOL)
4034 return false;
4035
4036 struct expand_vec_perm_d d;
4037
4038 /* Check whether the mask can be applied to a single vector. */
4039 if (sel.ninputs () == 1 || (op0 && rtx_equal_p (op0, op1)))
4040 d.one_vector_p = true;
4041 else if (sel.all_from_input_p (0))
4042 {
4043 d.one_vector_p = true;
4044 op1 = op0;
4045 }
4046 else if (sel.all_from_input_p (1))
4047 {
4048 d.one_vector_p = true;
4049 op0 = op1;
4050 }
4051 else
4052 d.one_vector_p = false;
4053
4054 d.perm.new_vector (sel.encoding (), d.one_vector_p ? 1 : 2,
4055 sel.nelts_per_input ());
4056 d.vmode = vmode;
4057 d.op_mode = op_mode;
4058 d.target = target;
4059 d.op0 = op0;
4060 if (op0 == op1)
4061 d.op1 = d.op0;
4062 else
4063 d.op1 = op1;
4064 d.testing_p = !target;
4065
4066 if (!d.testing_p)
4067 return expand_vec_perm_const_1 (&d);
4068
4069 rtx_insn *last = get_last_insn ();
4070 bool ret = expand_vec_perm_const_1 (&d);
4071 gcc_assert (last == get_last_insn ());
4072
4073 return ret;
4074 }
4075
4076 /* Generate no side effects vsetvl to get the vector length. */
4077 void
4078 expand_select_vl (rtx *ops)
4079 {
4080 poly_int64 nunits = rtx_to_poly_int64 (ops[2]);
4081 if (CONST_INT_P (ops[1]) && known_le (INTVAL (ops[1]), nunits))
4082 {
4083 /* If length is known <= VF, we just use the length directly instead
4084 of using vsetvli.
4085
4086 E.g. _255 = .SELECT_VL (3, POLY_INT_CST [4, 4]);
4087 We move 3 into _255 instead of using explicit vsetvl. */
4088 emit_move_insn (ops[0], ops[1]);
4089 return;
4090 }
4091 /* We arbitrary picked QImode as inner scalar mode to get vector mode.
4092 since vsetvl only demand ratio. We let VSETVL PASS to optimize it. */
4093 scalar_int_mode mode = QImode;
4094 machine_mode rvv_mode = get_vector_mode (mode, nunits).require ();
4095 emit_insn (gen_no_side_effects_vsetvl_rtx (rvv_mode, ops[0], ops[1]));
4096 }
4097
4098 /* Return RVV_VUNDEF if the ELSE value is scratch rtx. */
4099 static rtx
4100 get_else_operand (rtx op)
4101 {
4102 return GET_CODE (op) == SCRATCH ? RVV_VUNDEF (GET_MODE (op)) : op;
4103 }
4104
4105 /* Expand MASK_LEN_{LOAD,STORE}. */
4106 void
4107 expand_load_store (rtx *ops, bool is_load)
4108 {
4109 int idx = 2;
4110 rtx mask = ops[idx++];
4111 /* A masked load has a merge/else operand. */
4112 if (is_load)
4113 get_else_operand (ops[idx++]);
4114 rtx len = ops[idx];
4115 machine_mode mode = GET_MODE (ops[0]);
4116
4117 if (is_vlmax_len_p (mode, len))
4118 {
4119 /* If the length operand is equal to VF, it is VLMAX load/store. */
4120 if (is_load)
4121 {
4122 rtx m_ops[] = {ops[0], mask, ops[1]};
4123 emit_vlmax_insn (code_for_pred_mov (mode), UNARY_OP_TAMA, m_ops);
4124 }
4125 else
4126 {
4127 len = gen_reg_rtx (Pmode);
4128 emit_vlmax_vsetvl (mode, len);
4129 emit_insn (gen_pred_store (mode, ops[0], mask, ops[1], len,
4130 get_avl_type_rtx (VLMAX)));
4131 }
4132 }
4133 else
4134 {
4135 if (!satisfies_constraint_vl (len))
4136 len = force_reg (Pmode, len);
4137 if (is_load)
4138 {
4139 rtx m_ops[] = {ops[0], mask, ops[1]};
4140 emit_nonvlmax_insn (code_for_pred_mov (mode), UNARY_OP_TAMA, m_ops,
4141 len);
4142 }
4143 else
4144 emit_insn (gen_pred_store (mode, ops[0], mask, ops[1], len,
4145 get_avl_type_rtx (NONVLMAX)));
4146 }
4147 }
4148
4149 /* Expand MASK_LEN_STRIDED_LOAD. */
4150 void
4151 expand_strided_load (machine_mode mode, rtx *ops)
4152 {
4153 rtx v_reg = ops[0];
4154 rtx base = ops[1];
4155 rtx stride = ops[2];
4156 rtx mask = ops[3];
4157 int idx = 4;
4158 get_else_operand (ops[idx++]);
4159 rtx len = ops[idx];
4160 poly_int64 len_val;
4161
4162 insn_code icode = code_for_pred_strided_load (mode);
4163 rtx emit_ops[] = {v_reg, mask, gen_rtx_MEM (mode, base), stride};
4164
4165 if (poly_int_rtx_p (len, &len_val)
4166 && known_eq (len_val, GET_MODE_NUNITS (mode)))
4167 emit_vlmax_insn (icode, BINARY_OP_TAMA, emit_ops);
4168 else
4169 {
4170 len = satisfies_constraint_vl (len) ? len : force_reg (Pmode, len);
4171 emit_nonvlmax_insn (icode, BINARY_OP_TAMA, emit_ops, len);
4172 }
4173 }
4174
4175 /* Expand MASK_LEN_STRIDED_STORE. */
4176 void
4177 expand_strided_store (machine_mode mode, rtx *ops)
4178 {
4179 rtx v_reg = ops[2];
4180 rtx base = ops[0];
4181 rtx stride = ops[1];
4182 rtx mask = ops[3];
4183 rtx len = ops[4];
4184 poly_int64 len_val;
4185 rtx vl_type;
4186
4187 if (poly_int_rtx_p (len, &len_val)
4188 && known_eq (len_val, GET_MODE_NUNITS (mode)))
4189 {
4190 len = gen_reg_rtx (Pmode);
4191 emit_vlmax_vsetvl (mode, len);
4192 vl_type = get_avl_type_rtx (VLMAX);
4193 }
4194 else
4195 {
4196 len = satisfies_constraint_vl (len) ? len : force_reg (Pmode, len);
4197 vl_type = get_avl_type_rtx (NONVLMAX);
4198 }
4199
4200 emit_insn (gen_pred_strided_store (mode, gen_rtx_MEM (mode, base),
4201 mask, stride, v_reg, len, vl_type));
4202 }
4203
4204 /* Return true if the operation is the floating-point operation need FRM. */
4205 static bool
4206 needs_fp_rounding (unsigned icode, machine_mode mode)
4207 {
4208 if (!FLOAT_MODE_P (mode))
4209 return false;
4210
4211 return icode != maybe_code_for_pred (SMIN, mode)
4212 && icode != maybe_code_for_pred (UNSPEC_VFMIN, mode)
4213 && icode != maybe_code_for_pred (SMAX, mode)
4214 && icode != maybe_code_for_pred (UNSPEC_VFMAX, mode)
4215 && icode != maybe_code_for_pred (NEG, mode)
4216 && icode != maybe_code_for_pred (ABS, mode)
4217 /* narrower-FP -> FP */
4218 && icode != maybe_code_for_pred_extend (mode)
4219 /* narrower-INT -> FP */
4220 && icode != maybe_code_for_pred_widen (FLOAT, mode)
4221 && icode != maybe_code_for_pred_widen (UNSIGNED_FLOAT, mode)
4222 /* vfsgnj */
4223 && icode != maybe_code_for_pred (UNSPEC_VCOPYSIGN, mode)
4224 && icode != maybe_code_for_pred_mov (mode);
4225 }
4226
4227 /* Subroutine to expand COND_LEN_* patterns. */
4228 static void
4229 expand_cond_len_op (unsigned icode, insn_flags op_type, rtx *ops, rtx len)
4230 {
4231 rtx dest = ops[0];
4232 rtx mask = ops[1];
4233 machine_mode mode = GET_MODE (dest);
4234 machine_mode mask_mode = GET_MODE (mask);
4235 bool is_dummy_mask = rtx_equal_p (mask, CONSTM1_RTX (mask_mode));
4236 bool is_vlmax_len = is_vlmax_len_p (mode, len);
4237
4238 unsigned insn_flags = HAS_DEST_P | HAS_MASK_P | HAS_MERGE_P | op_type;
4239 /* FIXME: We don't support simplification of COND_LEN_NEG (..., dummy len,
4240 dummy mask) into NEG_EXPR in GIMPLE FOLD yet. So, we do such
4241 simplification in RISC-V backend and may do that in middle-end in the
4242 future. */
4243 if (is_dummy_mask && is_vlmax_len)
4244 insn_flags |= TDEFAULT_POLICY_P | MDEFAULT_POLICY_P;
4245 else if (is_dummy_mask)
4246 insn_flags |= TU_POLICY_P | MDEFAULT_POLICY_P;
4247 else if (is_vlmax_len)
4248 insn_flags |= TDEFAULT_POLICY_P | MU_POLICY_P;
4249 else
4250 insn_flags |= TU_POLICY_P | MU_POLICY_P;
4251
4252 if (needs_fp_rounding (icode, mode))
4253 insn_flags |= FRM_DYN_P;
4254
4255 if (is_vlmax_len)
4256 emit_vlmax_insn (icode, insn_flags, ops);
4257 else
4258 emit_nonvlmax_insn (icode, insn_flags, ops, len);
4259 }
4260
4261 /* Expand unary ops COND_LEN_*. */
4262 void
4263 expand_cond_len_unop (unsigned icode, rtx *ops)
4264 {
4265 rtx dest = ops[0];
4266 rtx mask = ops[1];
4267 rtx src = ops[2];
4268 rtx merge = get_else_operand (ops[3]);
4269 rtx len = ops[4];
4270
4271 rtx cond_ops[] = {dest, mask, merge, src};
4272 expand_cond_len_op (icode, UNARY_OP_P, cond_ops, len);
4273 }
4274
4275 /* Expand unary ops COND_*. */
4276 void
4277 expand_cond_unop (unsigned icode, rtx *ops)
4278 {
4279 rtx dest = ops[0];
4280 rtx mask = ops[1];
4281 rtx src = ops[2];
4282 rtx merge = get_else_operand (ops[3]);
4283 rtx len = gen_int_mode (GET_MODE_NUNITS (GET_MODE (dest)), Pmode);
4284
4285 rtx cond_ops[] = {dest, mask, merge, src};
4286 expand_cond_len_op (icode, UNARY_OP_P, cond_ops, len);
4287 }
4288
4289 /* Expand binary ops COND_LEN_*. */
4290 void
4291 expand_cond_len_binop (unsigned icode, rtx *ops)
4292 {
4293 rtx dest = ops[0];
4294 rtx mask = ops[1];
4295 rtx src1 = ops[2];
4296 rtx src2 = ops[3];
4297 rtx merge = get_else_operand (ops[4]);
4298 rtx len = ops[5];
4299
4300 rtx cond_ops[] = {dest, mask, merge, src1, src2};
4301 expand_cond_len_op (icode, BINARY_OP_P, cond_ops, len);
4302 }
4303
4304 /* Expand binary ops COND_*. */
4305 void
4306 expand_cond_binop (unsigned icode, rtx *ops)
4307 {
4308 rtx dest = ops[0];
4309 rtx mask = ops[1];
4310 rtx src1 = ops[2];
4311 rtx src2 = ops[3];
4312 rtx merge = get_else_operand (ops[4]);
4313 rtx len = gen_int_mode (GET_MODE_NUNITS (GET_MODE (dest)), Pmode);
4314
4315 rtx cond_ops[] = {dest, mask, merge, src1, src2};
4316 expand_cond_len_op (icode, BINARY_OP_P, cond_ops, len);
4317 }
4318
4319 /* Prepare insn_code for gather_load/scatter_store according to
4320 the vector mode and index mode. */
4321 static insn_code
4322 prepare_gather_scatter (machine_mode vec_mode, machine_mode idx_mode,
4323 bool is_load)
4324 {
4325 if (!is_load)
4326 return code_for_pred_indexed_store (UNSPEC_UNORDERED, vec_mode, idx_mode);
4327 else
4328 {
4329 unsigned src_eew_bitsize = GET_MODE_BITSIZE (GET_MODE_INNER (idx_mode));
4330 unsigned dst_eew_bitsize = GET_MODE_BITSIZE (GET_MODE_INNER (vec_mode));
4331 if (dst_eew_bitsize == src_eew_bitsize)
4332 return code_for_pred_indexed_load_same_eew (UNSPEC_UNORDERED, vec_mode);
4333 else if (dst_eew_bitsize > src_eew_bitsize)
4334 {
4335 unsigned factor = dst_eew_bitsize / src_eew_bitsize;
4336 switch (factor)
4337 {
4338 case 2:
4339 return code_for_pred_indexed_load_x2_greater_eew (
4340 UNSPEC_UNORDERED, vec_mode);
4341 case 4:
4342 return code_for_pred_indexed_load_x4_greater_eew (
4343 UNSPEC_UNORDERED, vec_mode);
4344 case 8:
4345 return code_for_pred_indexed_load_x8_greater_eew (
4346 UNSPEC_UNORDERED, vec_mode);
4347 default:
4348 gcc_unreachable ();
4349 }
4350 }
4351 else
4352 {
4353 unsigned factor = src_eew_bitsize / dst_eew_bitsize;
4354 switch (factor)
4355 {
4356 case 2:
4357 return code_for_pred_indexed_load_x2_smaller_eew (
4358 UNSPEC_UNORDERED, vec_mode);
4359 case 4:
4360 return code_for_pred_indexed_load_x4_smaller_eew (
4361 UNSPEC_UNORDERED, vec_mode);
4362 case 8:
4363 return code_for_pred_indexed_load_x8_smaller_eew (
4364 UNSPEC_UNORDERED, vec_mode);
4365 default:
4366 gcc_unreachable ();
4367 }
4368 }
4369 }
4370 }
4371
4372 /* Expand LEN_MASK_{GATHER_LOAD,SCATTER_STORE}. */
4373 void
4374 expand_gather_scatter (rtx *ops, bool is_load)
4375 {
4376 rtx ptr, vec_offset, vec_reg;
4377 bool zero_extend_p;
4378 int shift;
4379 rtx mask = ops[5];
4380 rtx len = ops[6];
4381 if (is_load)
4382 len = ops[7];
4383 if (is_load)
4384 {
4385 vec_reg = ops[0];
4386 ptr = ops[1];
4387 vec_offset = ops[2];
4388 zero_extend_p = INTVAL (ops[3]);
4389 shift = exact_log2 (INTVAL (ops[4]));
4390 }
4391 else
4392 {
4393 vec_reg = ops[4];
4394 ptr = ops[0];
4395 vec_offset = ops[1];
4396 zero_extend_p = INTVAL (ops[2]);
4397 shift = exact_log2 (INTVAL (ops[3]));
4398 }
4399
4400 machine_mode vec_mode = GET_MODE (vec_reg);
4401 machine_mode idx_mode = GET_MODE (vec_offset);
4402 scalar_mode inner_idx_mode = GET_MODE_INNER (idx_mode);
4403 unsigned inner_offsize = GET_MODE_BITSIZE (inner_idx_mode);
4404 poly_int64 nunits = GET_MODE_NUNITS (vec_mode);
4405 bool is_vlmax = is_vlmax_len_p (vec_mode, len);
4406
4407 bool use_widening_shift = false;
4408
4409 /* Extend the offset element to address width. */
4410 if (inner_offsize < BITS_PER_WORD)
4411 {
4412 use_widening_shift = TARGET_ZVBB && zero_extend_p && shift == 1;
4413 /* 7.2. Vector Load/Store Addressing Modes.
4414 If the vector offset elements are narrower than XLEN, they are
4415 zero-extended to XLEN before adding to the ptr effective address. If
4416 the vector offset elements are wider than XLEN, the least-significant
4417 XLEN bits are used in the address calculation. An implementation must
4418 raise an illegal instruction exception if the EEW is not supported for
4419 offset elements.
4420
4421 RVV spec only refers to the shift == 0 case. */
4422 if (!zero_extend_p || shift)
4423 {
4424 if (zero_extend_p)
4425 inner_idx_mode
4426 = int_mode_for_size (inner_offsize * 2, 0).require ();
4427 else
4428 inner_idx_mode = int_mode_for_size (BITS_PER_WORD, 0).require ();
4429 machine_mode new_idx_mode
4430 = get_vector_mode (inner_idx_mode, nunits).require ();
4431 if (!use_widening_shift)
4432 {
4433 rtx tmp = gen_reg_rtx (new_idx_mode);
4434 emit_insn (gen_extend_insn (tmp, vec_offset, new_idx_mode, idx_mode,
4435 zero_extend_p ? true : false));
4436 vec_offset = tmp;
4437 }
4438 idx_mode = new_idx_mode;
4439 }
4440 }
4441
4442 if (shift)
4443 {
4444 rtx tmp;
4445 if (!use_widening_shift)
4446 tmp = expand_binop (idx_mode, ashl_optab, vec_offset,
4447 gen_int_mode (shift, Pmode), NULL_RTX, 0,
4448 OPTAB_DIRECT);
4449 else
4450 {
4451 tmp = gen_reg_rtx (idx_mode);
4452 insn_code icode = code_for_pred_vwsll_scalar (idx_mode);
4453 rtx ops[] = {tmp, vec_offset, const1_rtx};
4454 emit_vlmax_insn (icode, BINARY_OP, ops);
4455 }
4456
4457 vec_offset = tmp;
4458 }
4459
4460 insn_code icode = prepare_gather_scatter (vec_mode, idx_mode, is_load);
4461 if (is_vlmax)
4462 {
4463 if (is_load)
4464 {
4465 rtx load_ops[]
4466 = {vec_reg, mask, ptr, vec_offset};
4467 emit_vlmax_insn (icode, BINARY_OP_TAMA, load_ops);
4468 }
4469 else
4470 {
4471 rtx store_ops[] = {mask, ptr, vec_offset, vec_reg};
4472 emit_vlmax_insn (icode, SCATTER_OP_M, store_ops);
4473 }
4474 }
4475 else
4476 {
4477 if (is_load)
4478 {
4479 rtx load_ops[]
4480 = {vec_reg, mask, ptr, vec_offset};
4481 emit_nonvlmax_insn (icode, BINARY_OP_TAMA, load_ops, len);
4482 }
4483 else
4484 {
4485 rtx store_ops[] = {mask, ptr, vec_offset, vec_reg};
4486 emit_nonvlmax_insn (icode, SCATTER_OP_M, store_ops, len);
4487 }
4488 }
4489 }
4490
4491 /* Expand COND_LEN_*. */
4492 void
4493 expand_cond_len_ternop (unsigned icode, rtx *ops)
4494 {
4495 rtx dest = ops[0];
4496 rtx mask = ops[1];
4497 rtx src1 = ops[2];
4498 rtx src2 = ops[3];
4499 rtx src3 = ops[4];
4500 rtx merge = get_else_operand (ops[5]);
4501 rtx len = ops[6];
4502
4503 rtx cond_ops[] = {dest, mask, src1, src2, src3, merge};
4504 expand_cond_len_op (icode, TERNARY_OP_P, cond_ops, len);
4505 }
4506
4507 /* Expand COND_*. */
4508 void
4509 expand_cond_ternop (unsigned icode, rtx *ops)
4510 {
4511 rtx dest = ops[0];
4512 rtx mask = ops[1];
4513 rtx src1 = ops[2];
4514 rtx src2 = ops[3];
4515 rtx src3 = ops[4];
4516 rtx merge = get_else_operand (ops[5]);
4517 rtx len = gen_int_mode (GET_MODE_NUNITS (GET_MODE (dest)), Pmode);
4518
4519 rtx cond_ops[] = {dest, mask, src1, src2, src3, merge};
4520 expand_cond_len_op (icode, TERNARY_OP_P, cond_ops, len);
4521 }
4522
4523 /* Expand reduction operations.
4524 Case 1: ops = {scalar_dest, vector_src}
4525 Case 2: ops = {scalar_dest, vector_src, mask, vl}
4526 */
4527 void
4528 expand_reduction (unsigned unspec, unsigned unspec_for_vl0_safe,
4529 unsigned insn_flags, rtx *ops, rtx init)
4530 {
4531 rtx scalar_dest = ops[0];
4532 rtx vector_src = ops[1];
4533 machine_mode vmode = GET_MODE (vector_src);
4534 machine_mode vel_mode = GET_MODE (scalar_dest);
4535 machine_mode m1_mode = get_m1_mode (vel_mode).require ();
4536 rtx vl_op = NULL_RTX;
4537 bool need_vl0_safe = false;
4538 if (need_mask_operand_p (insn_flags))
4539 {
4540 vl_op = ops[3];
4541 need_vl0_safe = !CONST_INT_P (vl_op) && !CONST_POLY_INT_P (vl_op);
4542 }
4543
4544 rtx m1_tmp = gen_reg_rtx (m1_mode);
4545 rtx scalar_move_ops[] = {m1_tmp, init};
4546 insn_code icode = code_for_pred_broadcast (m1_mode);
4547 if (need_mask_operand_p (insn_flags))
4548 {
4549 if (need_vl0_safe)
4550 emit_nonvlmax_insn (icode, SCALAR_MOVE_OP, scalar_move_ops, const1_rtx);
4551 else
4552 emit_nonvlmax_insn (icode, SCALAR_MOVE_OP, scalar_move_ops, vl_op);
4553 }
4554 else
4555 emit_vlmax_insn (icode, SCALAR_MOVE_OP, scalar_move_ops);
4556
4557 rtx m1_tmp2 = gen_reg_rtx (m1_mode);
4558 rtx reduc_ops[] = {m1_tmp2, vector_src, m1_tmp};
4559
4560 if (need_vl0_safe)
4561 icode = code_for_pred (unspec_for_vl0_safe, vmode);
4562 else
4563 icode = code_for_pred (unspec, vmode);
4564
4565 if (need_mask_operand_p (insn_flags))
4566 {
4567 rtx mask_len_reduc_ops[] = {m1_tmp2, ops[2], vector_src, m1_tmp};
4568 emit_nonvlmax_insn (icode, insn_flags, mask_len_reduc_ops, vl_op);
4569 }
4570 else
4571 emit_vlmax_insn (icode, insn_flags, reduc_ops);
4572
4573 emit_insn (gen_pred_extract_first (m1_mode, scalar_dest, m1_tmp2));
4574 }
4575
4576 /* Prepare ops for ternary operations.
4577 It can be called before or after RA. */
4578 void
4579 prepare_ternary_operands (rtx *ops)
4580 {
4581 machine_mode mode = GET_MODE (ops[0]);
4582
4583 if (!rtx_equal_p (ops[5], RVV_VUNDEF (mode))
4584 && (VECTOR_MODE_P (GET_MODE (ops[2]))
4585 && !rtx_equal_p (ops[2], ops[5]))
4586 && !rtx_equal_p (ops[3], ops[5])
4587 && !rtx_equal_p (ops[4], ops[5]))
4588 {
4589 /* RA will fail to find vector REG and report ICE, so we pre-merge
4590 the ops for LMUL = 8. */
4591 if (satisfies_constraint_Wc1 (ops[1]))
4592 {
4593 emit_move_insn (ops[0], ops[5]);
4594 emit_insn (gen_pred_mov (mode, ops[0], ops[1], ops[0], ops[4], ops[6],
4595 ops[7], ops[8], ops[9]));
4596 }
4597 else
4598 emit_insn (gen_pred_merge (mode, ops[0], RVV_VUNDEF (mode), ops[5],
4599 ops[4], ops[1], ops[6], ops[7], ops[9]));
4600 ops[5] = ops[4] = ops[0];
4601 }
4602 else
4603 {
4604 /* Swap the multiplication ops if the fallback value is the
4605 second of the two. */
4606 if (rtx_equal_p (ops[3], ops[5]))
4607 std::swap (ops[2], ops[3]);
4608
4609 /* TODO: ??? Maybe we could support splitting FMA (a, 4, b)
4610 into PLUS (ASHIFT (a, 2), b) according to uarchs. */
4611 }
4612 gcc_assert (rtx_equal_p (ops[5], RVV_VUNDEF (mode))
4613 || rtx_equal_p (ops[5], ops[2]) || rtx_equal_p (ops[5], ops[4]));
4614 }
4615
4616 /* Expand VEC_MASK_LEN_{LOAD_LANES,STORE_LANES}. */
4617 void
4618 expand_lanes_load_store (rtx *ops, bool is_load)
4619 {
4620 rtx mask = ops[2];
4621 rtx len = ops[3];
4622 if (is_load)
4623 len = ops[4];
4624 rtx addr = is_load ? XEXP (ops[1], 0) : XEXP (ops[0], 0);
4625 rtx reg = is_load ? ops[0] : ops[1];
4626 machine_mode mode = GET_MODE (ops[0]);
4627
4628 if (is_vlmax_len_p (mode, len))
4629 {
4630 /* If the length operand is equal to VF, it is VLMAX load/store. */
4631 if (is_load)
4632 {
4633 rtx m_ops[] = {reg, mask, addr};
4634 emit_vlmax_insn (code_for_pred_unit_strided_load (mode), UNARY_OP_TAMA,
4635 m_ops);
4636 }
4637 else
4638 {
4639 len = gen_reg_rtx (Pmode);
4640 emit_vlmax_vsetvl (mode, len);
4641 emit_insn (gen_pred_unit_strided_store (mode, mask, addr, reg, len,
4642 get_avl_type_rtx (VLMAX)));
4643 }
4644 }
4645 else
4646 {
4647 if (!satisfies_constraint_vl (len))
4648 len = force_reg (Pmode, len);
4649 if (is_load)
4650 {
4651 rtx m_ops[] = {reg, mask, addr};
4652 emit_nonvlmax_insn (code_for_pred_unit_strided_load (mode),
4653 UNARY_OP_TAMA, m_ops, len);
4654 }
4655 else
4656 emit_insn (gen_pred_unit_strided_store (mode, mask, addr, reg, len,
4657 get_avl_type_rtx (NONVLMAX)));
4658 }
4659 }
4660
4661 /* Expand LEN_FOLD_EXTRACT_LAST. */
4662 void
4663 expand_fold_extract_last (rtx *ops)
4664 {
4665 rtx dst = ops[0];
4666 rtx default_value = ops[1];
4667 rtx mask = ops[2];
4668 rtx anchor = gen_reg_rtx (Pmode);
4669 rtx index = gen_reg_rtx (Pmode);
4670 rtx vect = ops[3];
4671 rtx else_label = gen_label_rtx ();
4672 rtx end_label = gen_label_rtx ();
4673 rtx len = ops[4];
4674 machine_mode mode = GET_MODE (vect);
4675 machine_mode mask_mode = GET_MODE (mask);
4676 rtx compress_vect = gen_reg_rtx (mode);
4677 rtx slide_vect = gen_reg_rtx (mode);
4678 insn_code icode;
4679
4680 if (is_vlmax_len_p (mode, len))
4681 len = NULL_RTX;
4682
4683 /* Calculate the number of 1-bit in mask. */
4684 rtx cpop_ops[] = {anchor, mask};
4685 if (len)
4686 emit_nonvlmax_insn (code_for_pred_popcount (mask_mode, Pmode), CPOP_OP,
4687 cpop_ops, len);
4688 else
4689 emit_vlmax_insn (code_for_pred_popcount (mask_mode, Pmode), CPOP_OP,
4690 cpop_ops);
4691
4692 riscv_expand_conditional_branch (else_label, EQ, anchor, const0_rtx);
4693 emit_insn (gen_rtx_SET (index, gen_rtx_PLUS (Pmode, anchor, constm1_rtx)));
4694 /* Compress the vector. */
4695 icode = code_for_pred_compress (mode);
4696 rtx compress_ops[] = {compress_vect, vect, mask};
4697 if (len)
4698 emit_nonvlmax_insn (icode, COMPRESS_OP, compress_ops, len);
4699 else
4700 emit_vlmax_insn (icode, COMPRESS_OP, compress_ops);
4701 /* Emit the slide down to index 0 in a new vector. */
4702 rtx slide_ops[] = {slide_vect, compress_vect, index};
4703 icode = code_for_pred_slide (UNSPEC_VSLIDEDOWN, mode);
4704 if (len)
4705 emit_nonvlmax_insn (icode, BINARY_OP, slide_ops, len);
4706 else
4707 emit_vlmax_insn (icode, BINARY_OP, slide_ops);
4708 /* Emit v(f)mv.[xf].s. */
4709 emit_insn (gen_pred_extract_first (mode, dst, slide_vect));
4710
4711 emit_jump_insn (gen_jump (end_label));
4712 emit_barrier ();
4713 emit_label (else_label);
4714 emit_move_insn (dst, default_value);
4715 emit_label (end_label);
4716 }
4717
4718 /* Return true if the LMUL of comparison less than or equal to one. */
4719 bool
4720 cmp_lmul_le_one (machine_mode mode)
4721 {
4722 if (riscv_v_ext_vector_mode_p (mode))
4723 return known_le (GET_MODE_SIZE (mode), BYTES_PER_RISCV_VECTOR);
4724 else if (riscv_v_ext_vls_mode_p (mode))
4725 return known_le (GET_MODE_BITSIZE (mode), TARGET_MIN_VLEN);
4726 return false;
4727 }
4728
4729 /* Return true if the LMUL of comparison greater than one. */
4730 bool
4731 cmp_lmul_gt_one (machine_mode mode)
4732 {
4733 if (riscv_v_ext_vector_mode_p (mode))
4734 return known_gt (GET_MODE_SIZE (mode), BYTES_PER_RISCV_VECTOR);
4735 else if (riscv_v_ext_vls_mode_p (mode))
4736 return known_gt (GET_MODE_BITSIZE (mode), TARGET_MIN_VLEN);
4737 return false;
4738 }
4739
4740 /* Return true if the VLS mode is legal. There are 2 cases here.
4741
4742 1. Enable VLS modes for VLA vectorization since fixed length VLMAX mode
4743 is the highest priority choice and should not conflict with VLS modes.
4744 2. Enable VLS modes for some cases in fixed-vlmax, aka the bitsize of the
4745 VLS mode are smaller than the minimal vla.
4746
4747 Take vlen = 2048 as example for case 2.
4748
4749 Note: Below table based on vlen = 2048.
4750 +----------------------------------------------------+----------------------+
4751 | VLS mode | VLA mode |
4752 +----------------------------------------------------+----------------------+
4753 | Name | Precision | Inner Precision | Enabled | Min mode | Min bits |
4754 +------------+-----------+-----------------+---------+-----------+----------+
4755 | V1BI | 1 | 1 | Yes | RVVMF64BI | 32 |
4756 | V2BI | 2 | 1 | Yes | RVVMF64BI | 32 |
4757 | V4BI | 4 | 1 | Yes | RVVMF64BI | 32 |
4758 | V8BI | 8 | 1 | Yes | RVVMF64BI | 32 |
4759 | V16BI | 16 | 1 | Yes | RVVMF64BI | 32 |
4760 | V32BI | 32 | 1 | NO | RVVMF64BI | 32 |
4761 | V64BI | 64 | 1 | NO | RVVMF64BI | 32 |
4762 | ... | ... | ... | ... | RVVMF64BI | 32 |
4763 | V4096BI | 4096 | 1 | NO | RVVMF64BI | 32 |
4764 +------------+-----------+-----------------+---------+-----------+----------+
4765 | V1QI | 8 | 8 | Yes | RVVMF8QI | 256 |
4766 | V2QI | 16 | 8 | Yes | RVVMF8QI | 256 |
4767 | V4QI | 32 | 8 | Yes | RVVMF8QI | 256 |
4768 | V8QI | 64 | 8 | Yes | RVVMF8QI | 256 |
4769 | V16QI | 128 | 8 | Yes | RVVMF8QI | 256 |
4770 | V32QI | 256 | 8 | NO | RVVMF8QI | 256 |
4771 | V64QI | 512 | 8 | NO | RVVMF8QI | 256 |
4772 | ... | ... | .. | ... | RVVMF8QI | 256 |
4773 | V4096QI | 32768 | 8 | NO | RVVMF8QI | 256 |
4774 +------------+-----------+-----------------+---------+-----------+----------+
4775 | V1HI | 16 | 16 | Yes | RVVMF4HI | 512 |
4776 | V2HI | 32 | 16 | Yes | RVVMF4HI | 512 |
4777 | V4HI | 64 | 16 | Yes | RVVMF4HI | 512 |
4778 | V8HI | 128 | 16 | Yes | RVVMF4HI | 512 |
4779 | V16HI | 256 | 16 | Yes | RVVMF4HI | 512 |
4780 | V32HI | 512 | 16 | NO | RVVMF4HI | 512 |
4781 | V64HI | 1024 | 16 | NO | RVVMF4HI | 512 |
4782 | ... | ... | .. | ... | RVVMF4HI | 512 |
4783 | V2048HI | 32768 | 16 | NO | RVVMF4HI | 512 |
4784 +------------+-----------+-----------------+---------+-----------+----------+
4785 | V1SI/SF | 32 | 32 | Yes | RVVMF2SI | 1024 |
4786 | V2SI/SF | 64 | 32 | Yes | RVVMF2SI | 1024 |
4787 | V4SI/SF | 128 | 32 | Yes | RVVMF2SI | 1024 |
4788 | V8SI/SF | 256 | 32 | Yes | RVVMF2SI | 1024 |
4789 | V16SI/SF | 512 | 32 | Yes | RVVMF2SI | 1024 |
4790 | V32SI/SF | 1024 | 32 | NO | RVVMF2SI | 1024 |
4791 | V64SI/SF | 2048 | 32 | NO | RVVMF2SI | 1024 |
4792 | ... | ... | .. | ... | RVVMF2SI | 1024 |
4793 | V1024SI/SF | 32768 | 32 | NO | RVVMF2SI | 1024 |
4794 +------------+-----------+-----------------+---------+-----------+----------+
4795 | V1DI/DF | 64 | 64 | Yes | RVVM1DI | 2048 |
4796 | V2DI/DF | 128 | 64 | Yes | RVVM1DI | 2048 |
4797 | V4DI/DF | 256 | 64 | Yes | RVVM1DI | 2048 |
4798 | V8DI/DF | 512 | 64 | Yes | RVVM1DI | 2048 |
4799 | V16DI/DF | 1024 | 64 | Yes | RVVM1DI | 2048 |
4800 | V32DI/DF | 2048 | 64 | NO | RVVM1DI | 2048 |
4801 | V64DI/DF | 4096 | 64 | NO | RVVM1DI | 2048 |
4802 | ... | ... | .. | ... | RVVM1DI | 2048 |
4803 | V512DI/DF | 32768 | 64 | NO | RVVM1DI | 2048 |
4804 +------------+-----------+-----------------+---------+-----------+----------+
4805
4806 Then we can have the condition for VLS mode in fixed-vlmax, aka:
4807 PRECISION (VLSmode) < VLEN / (64 / PRECISION(VLS_inner_mode)). */
4808 bool
4809 vls_mode_valid_p (machine_mode vls_mode)
4810 {
4811 if (!TARGET_VECTOR || TARGET_XTHEADVECTOR)
4812 return false;
4813
4814 if (rvv_vector_bits == RVV_VECTOR_BITS_SCALABLE)
4815 {
4816 if (GET_MODE_CLASS (vls_mode) != MODE_VECTOR_BOOL
4817 && !ordered_p (TARGET_MAX_LMUL * BITS_PER_RISCV_VECTOR,
4818 GET_MODE_PRECISION (vls_mode)))
4819 /* We enable VLS modes which are aligned with TARGET_MAX_LMUL and
4820 BITS_PER_RISCV_VECTOR.
4821
4822 e.g. When TARGET_MAX_LMUL = 1 and BITS_PER_RISCV_VECTOR = (128,128).
4823 We enable VLS modes have fixed size <= 128bit. Since ordered_p is
4824 false between VLA modes with size = (128, 128) bits and VLS mode
4825 with size = 128 bits, we will end up with multiple ICEs in
4826 middle-end generic codes. */
4827 return false;
4828 return true;
4829 }
4830
4831 if (rvv_vector_bits == RVV_VECTOR_BITS_ZVL)
4832 {
4833 machine_mode inner_mode = GET_MODE_INNER (vls_mode);
4834 int precision = GET_MODE_PRECISION (inner_mode).to_constant ();
4835 int min_vlmax_bitsize = TARGET_MIN_VLEN / (64 / precision);
4836
4837 return GET_MODE_PRECISION (vls_mode).to_constant () < min_vlmax_bitsize;
4838 }
4839
4840 return false;
4841 }
4842
4843 /* We don't have to convert the floating point to integer when the
4844 mantissa is zero. Thus, ther will be a limitation for both the
4845 single and double precision floating point. There will be no
4846 mantissa if the floating point is greater than the limit.
4847
4848 1. Half floating point.
4849 +-----------+---------------+
4850 | float | binary layout |
4851 +-----------+---------------+
4852 | 1023.5 | 0x63ff |
4853 +-----------+---------------+
4854 | 1024.0 | 0x6400 |
4855 +-----------+---------------+
4856 | 1025.0 | 0x6401 |
4857 +-----------+---------------+
4858 | ... | ... |
4859
4860 All half floating point will be unchanged for ceil if it is
4861 greater than and equal to 1024.
4862
4863 2. Single floating point.
4864 +-----------+---------------+
4865 | float | binary layout |
4866 +-----------+---------------+
4867 | 8388607.5 | 0x4affffff |
4868 +-----------+---------------+
4869 | 8388608.0 | 0x4b000000 |
4870 +-----------+---------------+
4871 | 8388609.0 | 0x4b000001 |
4872 +-----------+---------------+
4873 | ... | ... |
4874
4875 All single floating point will be unchanged for ceil if it is
4876 greater than and equal to 8388608.
4877
4878 3. Double floating point.
4879 +--------------------+--------------------+
4880 | float | binary layout |
4881 +--------------------+--------------------+
4882 | 4503599627370495.5 | 0X432fffffffffffff |
4883 +--------------------+--------------------+
4884 | 4503599627370496.0 | 0X4330000000000000 |
4885 +--------------------+--------------------+
4886 | 4503599627370497.0 | 0X4340000000000000 |
4887 +--------------------+--------------------+
4888 | ... | ... |
4889
4890 All double floating point will be unchanged for ceil if it is
4891 greater than and equal to 4503599627370496.
4892 */
4893 rtx
4894 get_fp_rounding_coefficient (machine_mode inner_mode)
4895 {
4896 REAL_VALUE_TYPE real;
4897
4898 if (inner_mode == E_HFmode)
4899 real_from_integer (&real, inner_mode, 1024, SIGNED);
4900 else if (inner_mode == E_SFmode)
4901 real_from_integer (&real, inner_mode, 8388608, SIGNED);
4902 else if (inner_mode == E_DFmode)
4903 real_from_integer (&real, inner_mode, 4503599627370496, SIGNED);
4904 else
4905 gcc_unreachable ();
4906
4907 return const_double_from_real_value (real, inner_mode);
4908 }
4909
4910 static rtx
4911 emit_vec_float_cmp_mask (rtx fp_vector, rtx_code code, rtx fp_scalar,
4912 machine_mode vec_fp_mode)
4913 {
4914 /* Step-1: Prepare the scalar float compare register. */
4915 rtx fp_reg = gen_reg_rtx (GET_MODE_INNER (vec_fp_mode));
4916 emit_insn (gen_move_insn (fp_reg, fp_scalar));
4917
4918 /* Step-2: Generate the mask. */
4919 machine_mode mask_mode = get_mask_mode (vec_fp_mode);
4920 rtx mask = gen_reg_rtx (mask_mode);
4921 rtx cmp = gen_rtx_fmt_ee (code, mask_mode, fp_vector, fp_reg);
4922 rtx cmp_ops[] = {mask, cmp, fp_vector, fp_reg};
4923 insn_code icode = code_for_pred_cmp_scalar (vec_fp_mode);
4924 emit_vlmax_insn (icode, COMPARE_OP, cmp_ops);
4925
4926 return mask;
4927 }
4928
4929 static void
4930 emit_vec_copysign (rtx op_dest, rtx op_src_0, rtx op_src_1,
4931 machine_mode vec_mode)
4932 {
4933 rtx sgnj_ops[] = {op_dest, op_src_0, op_src_1};
4934 insn_code icode = code_for_pred (UNSPEC_VCOPYSIGN, vec_mode);
4935
4936 emit_vlmax_insn (icode, BINARY_OP, sgnj_ops);
4937 }
4938
4939 static void
4940 emit_vec_abs (rtx op_dest, rtx op_src, machine_mode vec_mode)
4941 {
4942 rtx abs_ops[] = {op_dest, op_src};
4943 insn_code icode = code_for_pred (ABS, vec_mode);
4944
4945 emit_vlmax_insn (icode, UNARY_OP, abs_ops);
4946 }
4947
4948 static void
4949 emit_vec_cvt_x_f (rtx op_dest, rtx op_src, rtx mask,
4950 insn_type type, machine_mode vec_mode)
4951 {
4952 insn_code icode = code_for_pred_fcvt_x_f (UNSPEC_VFCVT, vec_mode);
4953
4954 if (type & USE_VUNDEF_MERGE_P)
4955 {
4956 rtx cvt_x_ops[] = {op_dest, mask, op_src};
4957 emit_vlmax_insn (icode, type, cvt_x_ops);
4958 }
4959 else
4960 {
4961 rtx cvt_x_ops[] = {op_dest, mask, op_dest, op_src};
4962 emit_vlmax_insn (icode, type, cvt_x_ops);
4963 }
4964 }
4965
4966 static void
4967 emit_vec_cvt_x_f (rtx op_dest, rtx op_src, insn_type type,
4968 machine_mode vec_mode)
4969 {
4970 rtx ops[] = {op_dest, op_src};
4971 insn_code icode = code_for_pred_fcvt_x_f (UNSPEC_VFCVT, vec_mode);
4972
4973 emit_vlmax_insn (icode, type, ops);
4974 }
4975
4976 static void
4977 emit_vec_narrow_cvt_x_f (rtx op_dest, rtx op_src, insn_type type,
4978 machine_mode vec_mode)
4979 {
4980 rtx ops[] = {op_dest, op_src};
4981 insn_code icode = code_for_pred_narrow_fcvt_x_f (UNSPEC_VFCVT, vec_mode);
4982
4983 emit_vlmax_insn (icode, type, ops);
4984 }
4985
4986 static void
4987 emit_vec_widen_cvt_x_f (rtx op_dest, rtx op_src, insn_type type,
4988 machine_mode vec_mode)
4989 {
4990 rtx ops[] = {op_dest, op_src};
4991 insn_code icode = code_for_pred_widen_fcvt_x_f (UNSPEC_VFCVT, vec_mode);
4992
4993 emit_vlmax_insn (icode, type, ops);
4994 }
4995
4996 static void
4997 emit_vec_widen_cvt_f_f (rtx op_dest, rtx op_src, insn_type type,
4998 machine_mode vec_mode)
4999 {
5000 rtx ops[] = {op_dest, op_src};
5001 insn_code icode = code_for_pred_extend (vec_mode);
5002
5003 emit_vlmax_insn (icode, type, ops);
5004 }
5005
5006 static void
5007 emit_vec_cvt_f_x (rtx op_dest, rtx op_src, rtx mask,
5008 insn_type type, machine_mode vec_mode)
5009 {
5010 rtx cvt_fp_ops[] = {op_dest, mask, op_dest, op_src};
5011 insn_code icode = code_for_pred (FLOAT, vec_mode);
5012
5013 emit_vlmax_insn (icode, type, cvt_fp_ops);
5014 }
5015
5016 static void
5017 emit_vec_cvt_x_f_rtz (rtx op_dest, rtx op_src, rtx mask,
5018 insn_type type, machine_mode vec_mode)
5019 {
5020 insn_code icode = code_for_pred (FIX, vec_mode);
5021
5022 if (type & USE_VUNDEF_MERGE_P)
5023 {
5024 rtx cvt_x_ops[] = {op_dest, mask, op_src};
5025 emit_vlmax_insn (icode, type, cvt_x_ops);
5026 }
5027 else
5028 {
5029 rtx cvt_x_ops[] = {op_dest, mask, op_dest, op_src};
5030 emit_vlmax_insn (icode, type, cvt_x_ops);
5031 }
5032 }
5033
5034 static void
5035 emit_vec_binary_alu (rtx op_dest, rtx op_1, rtx op_2, enum rtx_code rcode,
5036 machine_mode vec_mode)
5037 {
5038 rtx ops[] = {op_dest, op_1, op_2};
5039 insn_code icode = code_for_pred (rcode, vec_mode);
5040
5041 emit_vlmax_insn (icode, BINARY_OP, ops);
5042 }
5043
5044 void
5045 expand_vec_ceil (rtx op_0, rtx op_1, machine_mode vec_fp_mode,
5046 machine_mode vec_int_mode)
5047 {
5048 /* Step-1: Get the abs float value for mask generation. */
5049 emit_vec_abs (op_0, op_1, vec_fp_mode);
5050
5051 /* Step-2: Generate the mask on const fp. */
5052 rtx const_fp = get_fp_rounding_coefficient (GET_MODE_INNER (vec_fp_mode));
5053 rtx mask = emit_vec_float_cmp_mask (op_0, LT, const_fp, vec_fp_mode);
5054
5055 /* Step-3: Convert to integer on mask, with rounding up (aka ceil). */
5056 rtx tmp = gen_reg_rtx (vec_int_mode);
5057 emit_vec_cvt_x_f (tmp, op_1, mask, UNARY_OP_TAMA_FRM_RUP, vec_fp_mode);
5058
5059 /* Step-4: Convert to floating-point on mask for the final result.
5060 To avoid unnecessary frm register access, we use RUP here and it will
5061 never do the rounding up because the tmp rtx comes from the float
5062 to int conversion. */
5063 emit_vec_cvt_f_x (op_0, tmp, mask, UNARY_OP_TAMU_FRM_RUP, vec_fp_mode);
5064
5065 /* Step-5: Retrieve the sign bit for -0.0. */
5066 emit_vec_copysign (op_0, op_0, op_1, vec_fp_mode);
5067 }
5068
5069 void
5070 expand_vec_floor (rtx op_0, rtx op_1, machine_mode vec_fp_mode,
5071 machine_mode vec_int_mode)
5072 {
5073 /* Step-1: Get the abs float value for mask generation. */
5074 emit_vec_abs (op_0, op_1, vec_fp_mode);
5075
5076 /* Step-2: Generate the mask on const fp. */
5077 rtx const_fp = get_fp_rounding_coefficient (GET_MODE_INNER (vec_fp_mode));
5078 rtx mask = emit_vec_float_cmp_mask (op_0, LT, const_fp, vec_fp_mode);
5079
5080 /* Step-3: Convert to integer on mask, with rounding down (aka floor). */
5081 rtx tmp = gen_reg_rtx (vec_int_mode);
5082 emit_vec_cvt_x_f (tmp, op_1, mask, UNARY_OP_TAMA_FRM_RDN, vec_fp_mode);
5083
5084 /* Step-4: Convert to floating-point on mask for the floor result. */
5085 emit_vec_cvt_f_x (op_0, tmp, mask, UNARY_OP_TAMU_FRM_RDN, vec_fp_mode);
5086
5087 /* Step-5: Retrieve the sign bit for -0.0. */
5088 emit_vec_copysign (op_0, op_0, op_1, vec_fp_mode);
5089 }
5090
5091 void
5092 expand_vec_nearbyint (rtx op_0, rtx op_1, machine_mode vec_fp_mode,
5093 machine_mode vec_int_mode)
5094 {
5095 /* Step-1: Get the abs float value for mask generation. */
5096 emit_vec_abs (op_0, op_1, vec_fp_mode);
5097
5098 /* Step-2: Generate the mask on const fp. */
5099 rtx const_fp = get_fp_rounding_coefficient (GET_MODE_INNER (vec_fp_mode));
5100 rtx mask = emit_vec_float_cmp_mask (op_0, LT, const_fp, vec_fp_mode);
5101
5102 /* Step-3: Backup FP exception flags, nearbyint never raise exceptions. */
5103 rtx fflags = gen_reg_rtx (SImode);
5104 emit_insn (gen_riscv_frflags (fflags));
5105
5106 /* Step-4: Convert to integer on mask, with rounding down (aka nearbyint). */
5107 rtx tmp = gen_reg_rtx (vec_int_mode);
5108 emit_vec_cvt_x_f (tmp, op_1, mask, UNARY_OP_TAMA_FRM_DYN, vec_fp_mode);
5109
5110 /* Step-5: Convert to floating-point on mask for the nearbyint result. */
5111 emit_vec_cvt_f_x (op_0, tmp, mask, UNARY_OP_TAMU_FRM_DYN, vec_fp_mode);
5112
5113 /* Step-6: Restore FP exception flags. */
5114 emit_insn (gen_riscv_fsflags (fflags));
5115
5116 /* Step-7: Retrieve the sign bit for -0.0. */
5117 emit_vec_copysign (op_0, op_0, op_1, vec_fp_mode);
5118 }
5119
5120 void
5121 expand_vec_rint (rtx op_0, rtx op_1, machine_mode vec_fp_mode,
5122 machine_mode vec_int_mode)
5123 {
5124 /* Step-1: Get the abs float value for mask generation. */
5125 emit_vec_abs (op_0, op_1, vec_fp_mode);
5126
5127 /* Step-2: Generate the mask on const fp. */
5128 rtx const_fp = get_fp_rounding_coefficient (GET_MODE_INNER (vec_fp_mode));
5129 rtx mask = emit_vec_float_cmp_mask (op_0, LT, const_fp, vec_fp_mode);
5130
5131 /* Step-3: Convert to integer on mask, with dyn rounding (aka rint). */
5132 rtx tmp = gen_reg_rtx (vec_int_mode);
5133 emit_vec_cvt_x_f (tmp, op_1, mask, UNARY_OP_TAMA_FRM_DYN, vec_fp_mode);
5134
5135 /* Step-4: Convert to floating-point on mask for the rint result. */
5136 emit_vec_cvt_f_x (op_0, tmp, mask, UNARY_OP_TAMU_FRM_DYN, vec_fp_mode);
5137
5138 /* Step-5: Retrieve the sign bit for -0.0. */
5139 emit_vec_copysign (op_0, op_0, op_1, vec_fp_mode);
5140 }
5141
5142 void
5143 expand_vec_round (rtx op_0, rtx op_1, machine_mode vec_fp_mode,
5144 machine_mode vec_int_mode)
5145 {
5146 /* Step-1: Get the abs float value for mask generation. */
5147 emit_vec_abs (op_0, op_1, vec_fp_mode);
5148
5149 /* Step-2: Generate the mask on const fp. */
5150 rtx const_fp = get_fp_rounding_coefficient (GET_MODE_INNER (vec_fp_mode));
5151 rtx mask = emit_vec_float_cmp_mask (op_0, LT, const_fp, vec_fp_mode);
5152
5153 /* Step-3: Convert to integer on mask, rounding to nearest (aka round). */
5154 rtx tmp = gen_reg_rtx (vec_int_mode);
5155 emit_vec_cvt_x_f (tmp, op_1, mask, UNARY_OP_TAMA_FRM_RMM, vec_fp_mode);
5156
5157 /* Step-4: Convert to floating-point on mask for the round result. */
5158 emit_vec_cvt_f_x (op_0, tmp, mask, UNARY_OP_TAMU_FRM_RMM, vec_fp_mode);
5159
5160 /* Step-5: Retrieve the sign bit for -0.0. */
5161 emit_vec_copysign (op_0, op_0, op_1, vec_fp_mode);
5162 }
5163
5164 void
5165 expand_vec_trunc (rtx op_0, rtx op_1, machine_mode vec_fp_mode,
5166 machine_mode vec_int_mode)
5167 {
5168 /* Step-1: Get the abs float value for mask generation. */
5169 emit_vec_abs (op_0, op_1, vec_fp_mode);
5170
5171 /* Step-2: Generate the mask on const fp. */
5172 rtx const_fp = get_fp_rounding_coefficient (GET_MODE_INNER (vec_fp_mode));
5173 rtx mask = emit_vec_float_cmp_mask (op_0, LT, const_fp, vec_fp_mode);
5174
5175 /* Step-3: Convert to integer on mask, rounding to zero (aka truncate). */
5176 rtx tmp = gen_reg_rtx (vec_int_mode);
5177 emit_vec_cvt_x_f_rtz (tmp, op_1, mask, UNARY_OP_TAMA, vec_fp_mode);
5178
5179 /* Step-4: Convert to floating-point on mask for the rint result. */
5180 emit_vec_cvt_f_x (op_0, tmp, mask, UNARY_OP_TAMU_FRM_DYN, vec_fp_mode);
5181
5182 /* Step-5: Retrieve the sign bit for -0.0. */
5183 emit_vec_copysign (op_0, op_0, op_1, vec_fp_mode);
5184 }
5185
5186 void
5187 expand_vec_roundeven (rtx op_0, rtx op_1, machine_mode vec_fp_mode,
5188 machine_mode vec_int_mode)
5189 {
5190 /* Step-1: Get the abs float value for mask generation. */
5191 emit_vec_abs (op_0, op_1, vec_fp_mode);
5192
5193 /* Step-2: Generate the mask on const fp. */
5194 rtx const_fp = get_fp_rounding_coefficient (GET_MODE_INNER (vec_fp_mode));
5195 rtx mask = emit_vec_float_cmp_mask (op_0, LT, const_fp, vec_fp_mode);
5196
5197 /* Step-3: Convert to integer on mask, rounding to nearest, ties to even. */
5198 rtx tmp = gen_reg_rtx (vec_int_mode);
5199 emit_vec_cvt_x_f (tmp, op_1, mask, UNARY_OP_TAMA_FRM_RNE, vec_fp_mode);
5200
5201 /* Step-4: Convert to floating-point on mask for the rint result. */
5202 emit_vec_cvt_f_x (op_0, tmp, mask, UNARY_OP_TAMU_FRM_RNE, vec_fp_mode);
5203
5204 /* Step-5: Retrieve the sign bit for -0.0. */
5205 emit_vec_copysign (op_0, op_0, op_1, vec_fp_mode);
5206 }
5207
5208 /* Handling the rounding from floating-point to int/long/long long. */
5209 static void
5210 emit_vec_rounding_to_integer (rtx op_0, rtx op_1, insn_type type,
5211 machine_mode vec_fp_mode,
5212 machine_mode vec_int_mode,
5213 machine_mode vec_bridge_mode = E_VOIDmode)
5214 {
5215 poly_uint16 vec_fp_size = GET_MODE_SIZE (vec_fp_mode);
5216 poly_uint16 vec_int_size = GET_MODE_SIZE (vec_int_mode);
5217
5218 if (known_eq (vec_fp_size, vec_int_size)) /* SF => SI, DF => DI. */
5219 emit_vec_cvt_x_f (op_0, op_1, type, vec_fp_mode);
5220 else if (maybe_eq (vec_fp_size, vec_int_size * 2)) /* DF => SI. */
5221 emit_vec_narrow_cvt_x_f (op_0, op_1, type, vec_fp_mode);
5222 else if (maybe_eq (vec_fp_size * 2, vec_int_size)) /* SF => DI, HF => SI. */
5223 emit_vec_widen_cvt_x_f (op_0, op_1, type, vec_int_mode);
5224 else if (maybe_eq (vec_fp_size * 4, vec_int_size)) /* HF => DI. */
5225 {
5226 gcc_assert (vec_bridge_mode != E_VOIDmode);
5227
5228 rtx op_sf = gen_reg_rtx (vec_bridge_mode);
5229
5230 /* Step-1: HF => SF, no rounding here. */
5231 emit_vec_widen_cvt_f_f (op_sf, op_1, UNARY_OP, vec_bridge_mode);
5232 /* Step-2: SF => DI. */
5233 emit_vec_widen_cvt_x_f (op_0, op_sf, type, vec_int_mode);
5234 }
5235 else
5236 gcc_unreachable ();
5237 }
5238
5239 void
5240 expand_vec_lrint (rtx op_0, rtx op_1, machine_mode vec_fp_mode,
5241 machine_mode vec_int_mode, machine_mode vec_bridge_mode)
5242 {
5243 emit_vec_rounding_to_integer (op_0, op_1, UNARY_OP_FRM_DYN, vec_fp_mode,
5244 vec_int_mode, vec_bridge_mode);
5245 }
5246
5247 void
5248 expand_vec_lround (rtx op_0, rtx op_1, machine_mode vec_fp_mode,
5249 machine_mode vec_int_mode, machine_mode vec_bridge_mode)
5250 {
5251 emit_vec_rounding_to_integer (op_0, op_1, UNARY_OP_FRM_RMM, vec_fp_mode,
5252 vec_int_mode, vec_bridge_mode);
5253 }
5254
5255 void
5256 expand_vec_lceil (rtx op_0, rtx op_1, machine_mode vec_fp_mode,
5257 machine_mode vec_int_mode)
5258 {
5259 emit_vec_rounding_to_integer (op_0, op_1, UNARY_OP_FRM_RUP, vec_fp_mode,
5260 vec_int_mode);
5261 }
5262
5263 void
5264 expand_vec_lfloor (rtx op_0, rtx op_1, machine_mode vec_fp_mode,
5265 machine_mode vec_int_mode)
5266 {
5267 emit_vec_rounding_to_integer (op_0, op_1, UNARY_OP_FRM_RDN, vec_fp_mode,
5268 vec_int_mode);
5269 }
5270
5271 /* Expand the standard name usadd<mode>3 for vector mode, we can leverage
5272 the vector fixed point vector single-width saturating add directly. */
5273
5274 void
5275 expand_vec_usadd (rtx op_0, rtx op_1, rtx op_2, machine_mode vec_mode)
5276 {
5277 emit_vec_binary_alu (op_0, op_1, op_2, US_PLUS, vec_mode);
5278 }
5279
5280 /* Expand the standard name ssadd<mode>3 for vector mode, we can leverage
5281 the vector fixed point vector single-width saturating add directly. */
5282
5283 void
5284 expand_vec_ssadd (rtx op_0, rtx op_1, rtx op_2, machine_mode vec_mode)
5285 {
5286 emit_vec_binary_alu (op_0, op_1, op_2, SS_PLUS, vec_mode);
5287 }
5288
5289 /* Expand the standard name usadd<mode>3 for vector mode, we can leverage
5290 the vector fixed point vector single-width saturating add directly. */
5291
5292 void
5293 expand_vec_ussub (rtx op_0, rtx op_1, rtx op_2, machine_mode vec_mode)
5294 {
5295 emit_vec_binary_alu (op_0, op_1, op_2, US_MINUS, vec_mode);
5296 }
5297
5298 /* Expand the standard name ssadd<mode>3 for vector mode, we can leverage
5299 the vector fixed point vector single-width saturating add directly. */
5300
5301 void
5302 expand_vec_sssub (rtx op_0, rtx op_1, rtx op_2, machine_mode vec_mode)
5303 {
5304 emit_vec_binary_alu (op_0, op_1, op_2, SS_MINUS, vec_mode);
5305 }
5306
5307 /* Expand the standard name ustrunc<m><n>2 for double vector mode, like
5308 DI => SI. we can leverage the vector fixed point vector narrowing
5309 fixed-point clip directly. */
5310
5311 void
5312 expand_vec_double_ustrunc (rtx op_0, rtx op_1, machine_mode vec_mode)
5313 {
5314 insn_code icode;
5315 rtx zero = CONST0_RTX (Xmode);
5316 enum unspec unspec = UNSPEC_VNCLIPU;
5317 rtx ops[] = {op_0, op_1, zero};
5318
5319 icode = code_for_pred_narrow_clip_scalar (unspec, vec_mode);
5320 emit_vlmax_insn (icode, BINARY_OP_VXRM_RNU, ops);
5321 }
5322
5323 /* Expand the standard name sstrunc<m><n>2 for double vector mode, like
5324 DI => SI. we can leverage the vector fixed point vector narrowing
5325 fixed-point clip directly. */
5326
5327 void
5328 expand_vec_double_sstrunc (rtx op_0, rtx op_1, machine_mode vec_mode)
5329 {
5330 insn_code icode;
5331 rtx zero = CONST0_RTX (Xmode);
5332 enum unspec unspec = UNSPEC_VNCLIP;
5333 rtx ops[] = {op_0, op_1, zero};
5334
5335 icode = code_for_pred_narrow_clip_scalar (unspec, vec_mode);
5336 emit_vlmax_insn (icode, BINARY_OP_VXRM_RNU, ops);
5337 }
5338
5339 /* Expand the standard name ustrunc<m><n>2 for double vector mode, like
5340 DI => HI. we can leverage the vector fixed point vector narrowing
5341 fixed-point clip directly. */
5342
5343 void
5344 expand_vec_quad_ustrunc (rtx op_0, rtx op_1, machine_mode vec_mode,
5345 machine_mode double_mode)
5346 {
5347 rtx double_rtx = gen_reg_rtx (double_mode);
5348
5349 expand_vec_double_ustrunc (double_rtx, op_1, vec_mode);
5350 expand_vec_double_ustrunc (op_0, double_rtx, double_mode);
5351 }
5352
5353 /* Expand the standard name sstrunc<m><n>2 for quad vector mode, like
5354 DI => HI. we can leverage the vector fixed point vector narrowing
5355 fixed-point clip directly. */
5356
5357 void
5358 expand_vec_quad_sstrunc (rtx op_0, rtx op_1, machine_mode vec_mode,
5359 machine_mode double_mode)
5360 {
5361 rtx double_rtx = gen_reg_rtx (double_mode);
5362
5363 expand_vec_double_sstrunc (double_rtx, op_1, vec_mode);
5364 expand_vec_double_sstrunc (op_0, double_rtx, double_mode);
5365 }
5366
5367 /* Expand the standard name ustrunc<m><n>2 for double vector mode, like
5368 DI => QI. we can leverage the vector fixed point vector narrowing
5369 fixed-point clip directly. */
5370
5371 void
5372 expand_vec_oct_ustrunc (rtx op_0, rtx op_1, machine_mode vec_mode,
5373 machine_mode double_mode, machine_mode quad_mode)
5374 {
5375 rtx double_rtx = gen_reg_rtx (double_mode);
5376 rtx quad_rtx = gen_reg_rtx (quad_mode);
5377
5378 expand_vec_double_ustrunc (double_rtx, op_1, vec_mode);
5379 expand_vec_double_ustrunc (quad_rtx, double_rtx, double_mode);
5380 expand_vec_double_ustrunc (op_0, quad_rtx, quad_mode);
5381 }
5382
5383 /* Expand the standard name sstrunc<m><n>2 for oct vector mode, like
5384 DI => QI. we can leverage the vector fixed point vector narrowing
5385 fixed-point clip directly. */
5386
5387 void
5388 expand_vec_oct_sstrunc (rtx op_0, rtx op_1, machine_mode vec_mode,
5389 machine_mode double_mode, machine_mode quad_mode)
5390 {
5391 rtx double_rtx = gen_reg_rtx (double_mode);
5392 rtx quad_rtx = gen_reg_rtx (quad_mode);
5393
5394 expand_vec_double_sstrunc (double_rtx, op_1, vec_mode);
5395 expand_vec_double_sstrunc (quad_rtx, double_rtx, double_mode);
5396 expand_vec_double_sstrunc (op_0, quad_rtx, quad_mode);
5397 }
5398
5399 /* Vectorize popcount by the Wilkes-Wheeler-Gill algorithm that libgcc uses as
5400 well. */
5401 void
5402 expand_popcount (rtx *ops)
5403 {
5404 rtx dst = ops[0];
5405 rtx src = ops[1];
5406 machine_mode mode = GET_MODE (dst);
5407 scalar_mode imode = GET_MODE_INNER (mode);
5408 static const uint64_t m5 = 0x5555555555555555ULL;
5409 static const uint64_t m3 = 0x3333333333333333ULL;
5410 static const uint64_t mf = 0x0F0F0F0F0F0F0F0FULL;
5411 static const uint64_t m1 = 0x0101010101010101ULL;
5412
5413 rtx x1 = gen_reg_rtx (mode);
5414 rtx x2 = gen_reg_rtx (mode);
5415 rtx x3 = gen_reg_rtx (mode);
5416 rtx x4 = gen_reg_rtx (mode);
5417
5418 /* x1 = src - (src >> 1) & 0x555...); */
5419 rtx shift1 = expand_binop (mode, lshr_optab, src, GEN_INT (1), NULL, true,
5420 OPTAB_DIRECT);
5421
5422 rtx and1 = gen_reg_rtx (mode);
5423 rtx ops1[] = {and1, shift1, gen_int_mode (m5, imode)};
5424 emit_vlmax_insn (code_for_pred_scalar (AND, mode), riscv_vector::BINARY_OP,
5425 ops1);
5426
5427 x1 = expand_binop (mode, sub_optab, src, and1, NULL, true, OPTAB_DIRECT);
5428
5429 /* x2 = (x1 & 0x3333333333333333ULL) + ((x1 >> 2) & 0x3333333333333333ULL);
5430 */
5431 rtx and2 = gen_reg_rtx (mode);
5432 rtx ops2[] = {and2, x1, gen_int_mode (m3, imode)};
5433 emit_vlmax_insn (code_for_pred_scalar (AND, mode), riscv_vector::BINARY_OP,
5434 ops2);
5435
5436 rtx shift2 = expand_binop (mode, lshr_optab, x1, GEN_INT (2), NULL, true,
5437 OPTAB_DIRECT);
5438
5439 rtx and22 = gen_reg_rtx (mode);
5440 rtx ops22[] = {and22, shift2, gen_int_mode (m3, imode)};
5441 emit_vlmax_insn (code_for_pred_scalar (AND, mode), riscv_vector::BINARY_OP,
5442 ops22);
5443
5444 x2 = expand_binop (mode, add_optab, and2, and22, NULL, true, OPTAB_DIRECT);
5445
5446 /* x3 = (x2 + (x2 >> 4)) & 0x0f0f0f0f0f0f0f0fULL; */
5447 rtx shift3 = expand_binop (mode, lshr_optab, x2, GEN_INT (4), NULL, true,
5448 OPTAB_DIRECT);
5449
5450 rtx plus3
5451 = expand_binop (mode, add_optab, x2, shift3, NULL, true, OPTAB_DIRECT);
5452
5453 rtx ops3[] = {x3, plus3, gen_int_mode (mf, imode)};
5454 emit_vlmax_insn (code_for_pred_scalar (AND, mode), riscv_vector::BINARY_OP,
5455 ops3);
5456
5457 /* dest = (x3 * 0x0101010101010101ULL) >> 56; */
5458 rtx mul4 = gen_reg_rtx (mode);
5459 rtx ops4[] = {mul4, x3, gen_int_mode (m1, imode)};
5460 emit_vlmax_insn (code_for_pred_scalar (MULT, mode), riscv_vector::BINARY_OP,
5461 ops4);
5462
5463 x4 = expand_binop (mode, lshr_optab, mul4,
5464 GEN_INT (GET_MODE_BITSIZE (imode) - 8), NULL, true,
5465 OPTAB_DIRECT);
5466
5467 emit_move_insn (dst, x4);
5468 }
5469
5470 /* Return true if it is VLMAX AVL TYPE. */
5471 bool
5472 vlmax_avl_type_p (rtx_insn *rinsn)
5473 {
5474 extract_insn_cached (rinsn);
5475 int index = get_attr_avl_type_idx (rinsn);
5476 if (index == INVALID_ATTRIBUTE)
5477 return false;
5478
5479 gcc_assert (index < recog_data.n_operands);
5480
5481 rtx avl_type = recog_data.operand[index];
5482 return INTVAL (avl_type) == VLMAX;
5483 }
5484
5485 /* Return true if it is an RVV instruction depends on VL global
5486 status register. */
5487 bool
5488 has_vl_op (rtx_insn *rinsn)
5489 {
5490 return recog_memoized (rinsn) >= 0 && get_attr_has_vl_op (rinsn);
5491 }
5492
5493 /* Get default tail policy. */
5494 static bool
5495 get_default_ta ()
5496 {
5497 /* For the instruction that doesn't require TA, we still need a default value
5498 to emit vsetvl. We pick up the default value according to prefer policy. */
5499 return (bool) (get_prefer_tail_policy () & 0x1
5500 || (get_prefer_tail_policy () >> 1 & 0x1));
5501 }
5502
5503 /* Helper function to get TA operand. */
5504 bool
5505 tail_agnostic_p (rtx_insn *rinsn)
5506 {
5507 /* If it doesn't have TA, we return agnostic by default. */
5508 extract_insn_cached (rinsn);
5509 int ta = get_attr_ta (rinsn);
5510 return ta == INVALID_ATTRIBUTE ? get_default_ta () : IS_AGNOSTIC (ta);
5511 }
5512
5513 /* Change insn and Assert the change always happens. */
5514 void
5515 validate_change_or_fail (rtx object, rtx *loc, rtx new_rtx, bool in_group)
5516 {
5517 bool change_p = validate_change (object, loc, new_rtx, in_group);
5518 gcc_assert (change_p);
5519 }
5520
5521 /* Return true if it is NONVLMAX AVL TYPE. */
5522 bool
5523 nonvlmax_avl_type_p (rtx_insn *rinsn)
5524 {
5525 extract_insn_cached (rinsn);
5526 int index = get_attr_avl_type_idx (rinsn);
5527 if (index == INVALID_ATTRIBUTE)
5528 return false;
5529
5530 gcc_assert (index < recog_data.n_operands);
5531
5532 rtx avl_type = recog_data.operand[index];
5533 return INTVAL (avl_type) == NONVLMAX;
5534 }
5535
5536 /* Return true if RTX is RVV VLMAX AVL. */
5537 bool
5538 vlmax_avl_p (rtx x)
5539 {
5540 return x && rtx_equal_p (x, RVV_VLMAX);
5541 }
5542
5543 /* Helper function to get SEW operand. We always have SEW value for
5544 all RVV instructions that have VTYPE OP. */
5545 uint8_t
5546 get_sew (rtx_insn *rinsn)
5547 {
5548 return get_attr_sew (rinsn);
5549 }
5550
5551 /* Helper function to get VLMUL operand. We always have VLMUL value for
5552 all RVV instructions that have VTYPE OP. */
5553 enum vlmul_type
5554 get_vlmul (rtx_insn *rinsn)
5555 {
5556 return (enum vlmul_type) get_attr_vlmul (rinsn);
5557 }
5558
5559 /* Count the number of REGNO in RINSN. */
5560 int
5561 count_regno_occurrences (rtx_insn *rinsn, unsigned int regno)
5562 {
5563 int count = 0;
5564 extract_insn (rinsn);
5565 for (int i = 0; i < recog_data.n_operands; i++)
5566 if (refers_to_regno_p (regno, recog_data.operand[i]))
5567 count++;
5568 return count;
5569 }
5570
5571 /* Return true if the OP can be directly broadcasted. */
5572 bool
5573 can_be_broadcasted_p (rtx op)
5574 {
5575 machine_mode mode = GET_MODE (op);
5576 /* We don't allow RA (register allocation) reload generate
5577 (vec_duplicate:DI reg) in RV32 system wheras we allow
5578 (vec_duplicate:DI mem) in RV32 system. */
5579 if (!can_create_pseudo_p () && !FLOAT_MODE_P (mode)
5580 && maybe_gt (GET_MODE_SIZE (mode), GET_MODE_SIZE (Pmode))
5581 && !satisfies_constraint_Wdm (op))
5582 return false;
5583
5584 if (satisfies_constraint_K (op) || register_operand (op, mode)
5585 || satisfies_constraint_Wdm (op) || rtx_equal_p (op, CONST0_RTX (mode)))
5586 return true;
5587
5588 return can_create_pseudo_p () && nonmemory_operand (op, mode);
5589 }
5590
5591 void
5592 emit_vec_extract (rtx target, rtx src, rtx index)
5593 {
5594 machine_mode vmode = GET_MODE (src);
5595 machine_mode smode = GET_MODE (target);
5596 class expand_operand ops[3];
5597 enum insn_code icode
5598 = convert_optab_handler (vec_extract_optab, vmode, smode);
5599 gcc_assert (icode != CODE_FOR_nothing);
5600 create_output_operand (&ops[0], target, smode);
5601 ops[0].target = 1;
5602 create_input_operand (&ops[1], src, vmode);
5603
5604 poly_int64 val;
5605 if (poly_int_rtx_p (index, &val))
5606 create_integer_operand (&ops[2], val);
5607 else
5608 create_input_operand (&ops[2], index, Pmode);
5609
5610 expand_insn (icode, 3, ops);
5611 if (ops[0].value != target)
5612 emit_move_insn (target, ops[0].value);
5613 }
5614
5615 /* Return true if the offset mode is valid mode that we use for gather/scatter
5616 autovectorization. */
5617 bool
5618 gather_scatter_valid_offset_p (machine_mode mode)
5619 {
5620 /* If the element size of offset mode is already >= Pmode size,
5621 we don't need any extensions. */
5622 if (known_ge (GET_MODE_SIZE (GET_MODE_INNER (mode)), UNITS_PER_WORD))
5623 return true;
5624
5625 /* Since we are very likely extend the offset mode into vector Pmode,
5626 Disable gather/scatter autovectorization if we can't extend the offset
5627 mode into vector Pmode. */
5628 if (!get_vector_mode (Pmode, GET_MODE_NUNITS (mode)).exists ())
5629 return false;
5630 return true;
5631 }
5632
5633 /* Implement TARGET_ESTIMATED_POLY_VALUE.
5634 Look into the tuning structure for an estimate.
5635 KIND specifies the type of requested estimate: min, max or likely.
5636 For cores with a known VLA width all three estimates are the same.
5637 For generic VLA tuning we want to distinguish the maximum estimate from
5638 the minimum and likely ones.
5639 The likely estimate is the same as the minimum in that case to give a
5640 conservative behavior of auto-vectorizing with VLA when it is a win
5641 even for VLA vectorization.
5642 When VLA width information is available VAL.coeffs[1] is multiplied by
5643 the number of VLA chunks over the initial VLS bits. */
5644 HOST_WIDE_INT
5645 estimated_poly_value (poly_int64 val, unsigned int kind)
5646 {
5647 unsigned int width_source
5648 = BITS_PER_RISCV_VECTOR.is_constant ()
5649 ? (unsigned int) BITS_PER_RISCV_VECTOR.to_constant ()
5650 : (unsigned int) RVV_VECTOR_BITS_SCALABLE;
5651
5652 /* If there is no core-specific information then the minimum and likely
5653 values are based on TARGET_MIN_VLEN vectors and the maximum is based on
5654 the architectural maximum of 65536 bits. */
5655 unsigned int min_vlen_bytes = TARGET_MIN_VLEN / 8 - 1;
5656 if (width_source == RVV_VECTOR_BITS_SCALABLE)
5657 switch (kind)
5658 {
5659 case POLY_VALUE_MIN:
5660 case POLY_VALUE_LIKELY:
5661 return val.coeffs[0];
5662
5663 case POLY_VALUE_MAX:
5664 return val.coeffs[0] + val.coeffs[1] * min_vlen_bytes;
5665 }
5666
5667 /* Allow BITS_PER_RISCV_VECTOR to be a bitmask of different VL, treating the
5668 lowest as likely. This could be made more general if future -mtune
5669 options need it to be. */
5670 if (kind == POLY_VALUE_MAX)
5671 width_source = 1 << floor_log2 (width_source);
5672 else
5673 width_source = least_bit_hwi (width_source);
5674
5675 /* If the core provides width information, use that. */
5676 HOST_WIDE_INT over_min_vlen = width_source - TARGET_MIN_VLEN;
5677 return val.coeffs[0] + val.coeffs[1] * over_min_vlen / TARGET_MIN_VLEN;
5678 }
5679
5680 /* Return true it is whole register-register move. */
5681 bool
5682 whole_reg_to_reg_move_p (rtx *ops, machine_mode mode, int avl_type_index)
5683 {
5684 /* An operation is a whole-register move if either
5685 (1) Its vlmax operand equals VLMAX
5686 (2) Its vl operand equals the number of units of its mode. */
5687 if (register_operand (ops[0], mode)
5688 && register_operand (ops[3], mode)
5689 && satisfies_constraint_vu (ops[2])
5690 && satisfies_constraint_Wc1 (ops[1]))
5691 {
5692 if (INTVAL (ops[avl_type_index]) == VLMAX)
5693 return true;
5694 /* AVL propagation PASS will transform FIXED-VLMAX with NUNITS < 32
5695 into NON-VLMAX with LEN = NUNITS. */
5696 else if (CONST_INT_P (ops[4])
5697 && known_eq (INTVAL (ops[4]), GET_MODE_NUNITS (mode)))
5698 return true;
5699 }
5700 return false;
5701 }
5702
5703 /* Return true if we can transform vmv.v.x/vfmv.v.f to vmv.s.x/vfmv.s.f. */
5704 bool
5705 splat_to_scalar_move_p (rtx *ops)
5706 {
5707 return satisfies_constraint_Wc1 (ops[1])
5708 && satisfies_constraint_vu (ops[2])
5709 && !MEM_P (ops[3])
5710 && satisfies_constraint_k01 (ops[4])
5711 && INTVAL (ops[7]) == NONVLMAX
5712 && known_ge (GET_MODE_SIZE (Pmode), GET_MODE_SIZE (GET_MODE (ops[3])));
5713 }
5714
5715 } // namespace riscv_vector