LLVM 20.0.0git
RISCVISelLowering.cpp
Go to the documentation of this file.
1//===-- RISCVISelLowering.cpp - RISC-V DAG Lowering Implementation -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the interfaces that RISC-V uses to lower LLVM code into a
10// selection DAG.
11//
12//===----------------------------------------------------------------------===//
13
14#include "RISCVISelLowering.h"
16#include "RISCV.h"
18#include "RISCVRegisterInfo.h"
19#include "RISCVSubtarget.h"
20#include "RISCVTargetMachine.h"
21#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/Statistic.h"
36#include "llvm/IR/IRBuilder.h"
38#include "llvm/IR/IntrinsicsRISCV.h"
41#include "llvm/Support/Debug.h"
47#include <optional>
48
49using namespace llvm;
50
51#define DEBUG_TYPE "riscv-lower"
52
53STATISTIC(NumTailCalls, "Number of tail calls");
54
56 DEBUG_TYPE "-ext-max-web-size", cl::Hidden,
57 cl::desc("Give the maximum size (in number of nodes) of the web of "
58 "instructions that we will consider for VW expansion"),
59 cl::init(18));
60
61static cl::opt<bool>
62 AllowSplatInVW_W(DEBUG_TYPE "-form-vw-w-with-splat", cl::Hidden,
63 cl::desc("Allow the formation of VW_W operations (e.g., "
64 "VWADD_W) with splat constants"),
65 cl::init(false));
66
68 DEBUG_TYPE "-fp-repeated-divisors", cl::Hidden,
69 cl::desc("Set the minimum number of repetitions of a divisor to allow "
70 "transformation to multiplications by the reciprocal"),
71 cl::init(2));
72
73static cl::opt<int>
75 cl::desc("Give the maximum number of instructions that we will "
76 "use for creating a floating-point immediate value"),
77 cl::init(2));
78
80 const RISCVSubtarget &STI)
81 : TargetLowering(TM), Subtarget(STI) {
82
83 RISCVABI::ABI ABI = Subtarget.getTargetABI();
84 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
85
86 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
87 !Subtarget.hasStdExtF()) {
88 errs() << "Hard-float 'f' ABI can't be used for a target that "
89 "doesn't support the F instruction set extension (ignoring "
90 "target-abi)\n";
92 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
93 !Subtarget.hasStdExtD()) {
94 errs() << "Hard-float 'd' ABI can't be used for a target that "
95 "doesn't support the D instruction set extension (ignoring "
96 "target-abi)\n";
98 }
99
100 switch (ABI) {
101 default:
102 report_fatal_error("Don't know how to lower this ABI");
111 break;
112 }
113
114 MVT XLenVT = Subtarget.getXLenVT();
115
116 // Set up the register classes.
117 addRegisterClass(XLenVT, &RISCV::GPRRegClass);
118
119 if (Subtarget.hasStdExtZfhmin())
120 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
121 if (Subtarget.hasStdExtZfbfmin())
122 addRegisterClass(MVT::bf16, &RISCV::FPR16RegClass);
123 if (Subtarget.hasStdExtF())
124 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
125 if (Subtarget.hasStdExtD())
126 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
127 if (Subtarget.hasStdExtZhinxmin())
128 addRegisterClass(MVT::f16, &RISCV::GPRF16RegClass);
129 if (Subtarget.hasStdExtZfinx())
130 addRegisterClass(MVT::f32, &RISCV::GPRF32RegClass);
131 if (Subtarget.hasStdExtZdinx()) {
132 if (Subtarget.is64Bit())
133 addRegisterClass(MVT::f64, &RISCV::GPRRegClass);
134 else
135 addRegisterClass(MVT::f64, &RISCV::GPRPairRegClass);
136 }
137
138 static const MVT::SimpleValueType BoolVecVTs[] = {
139 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1,
140 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
141 static const MVT::SimpleValueType IntVecVTs[] = {
142 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8,
143 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16,
144 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
145 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
146 MVT::nxv4i64, MVT::nxv8i64};
147 static const MVT::SimpleValueType F16VecVTs[] = {
148 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16,
149 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
150 static const MVT::SimpleValueType BF16VecVTs[] = {
151 MVT::nxv1bf16, MVT::nxv2bf16, MVT::nxv4bf16,
152 MVT::nxv8bf16, MVT::nxv16bf16, MVT::nxv32bf16};
153 static const MVT::SimpleValueType F32VecVTs[] = {
154 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
155 static const MVT::SimpleValueType F64VecVTs[] = {
156 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
157
158 if (Subtarget.hasVInstructions()) {
159 auto addRegClassForRVV = [this](MVT VT) {
160 // Disable the smallest fractional LMUL types if ELEN is less than
161 // RVVBitsPerBlock.
162 unsigned MinElts = RISCV::RVVBitsPerBlock / Subtarget.getELen();
163 if (VT.getVectorMinNumElements() < MinElts)
164 return;
165
166 unsigned Size = VT.getSizeInBits().getKnownMinValue();
167 const TargetRegisterClass *RC;
169 RC = &RISCV::VRRegClass;
170 else if (Size == 2 * RISCV::RVVBitsPerBlock)
171 RC = &RISCV::VRM2RegClass;
172 else if (Size == 4 * RISCV::RVVBitsPerBlock)
173 RC = &RISCV::VRM4RegClass;
174 else if (Size == 8 * RISCV::RVVBitsPerBlock)
175 RC = &RISCV::VRM8RegClass;
176 else
177 llvm_unreachable("Unexpected size");
178
179 addRegisterClass(VT, RC);
180 };
181
182 for (MVT VT : BoolVecVTs)
183 addRegClassForRVV(VT);
184 for (MVT VT : IntVecVTs) {
185 if (VT.getVectorElementType() == MVT::i64 &&
186 !Subtarget.hasVInstructionsI64())
187 continue;
188 addRegClassForRVV(VT);
189 }
190
191 if (Subtarget.hasVInstructionsF16Minimal())
192 for (MVT VT : F16VecVTs)
193 addRegClassForRVV(VT);
194
195 if (Subtarget.hasVInstructionsBF16Minimal())
196 for (MVT VT : BF16VecVTs)
197 addRegClassForRVV(VT);
198
199 if (Subtarget.hasVInstructionsF32())
200 for (MVT VT : F32VecVTs)
201 addRegClassForRVV(VT);
202
203 if (Subtarget.hasVInstructionsF64())
204 for (MVT VT : F64VecVTs)
205 addRegClassForRVV(VT);
206
207 if (Subtarget.useRVVForFixedLengthVectors()) {
208 auto addRegClassForFixedVectors = [this](MVT VT) {
209 MVT ContainerVT = getContainerForFixedLengthVector(VT);
210 unsigned RCID = getRegClassIDForVecVT(ContainerVT);
211 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
212 addRegisterClass(VT, TRI.getRegClass(RCID));
213 };
215 if (useRVVForFixedLengthVectorVT(VT))
216 addRegClassForFixedVectors(VT);
217
219 if (useRVVForFixedLengthVectorVT(VT))
220 addRegClassForFixedVectors(VT);
221 }
222 }
223
224 // Compute derived properties from the register classes.
226
228
230 MVT::i1, Promote);
231 // DAGCombiner can call isLoadExtLegal for types that aren't legal.
233 MVT::i1, Promote);
234
235 // TODO: add all necessary setOperationAction calls.
237
242
247 if (!(Subtarget.hasVendorXCValu() && !Subtarget.is64Bit())) {
250 }
251
253
256
258
260
261 if (!Subtarget.hasStdExtZbb() && !Subtarget.hasVendorXTHeadBb() &&
262 !(Subtarget.hasVendorXCValu() && !Subtarget.is64Bit()))
263 setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand);
264
265 if (Subtarget.is64Bit()) {
267
270 MVT::i32, Custom);
272 if (!Subtarget.hasStdExtZbb())
275 Custom);
277 }
278 if (!Subtarget.hasStdExtZmmul()) {
280 } else if (Subtarget.is64Bit()) {
283 } else {
285 }
286
287 if (!Subtarget.hasStdExtM()) {
289 Expand);
290 } else if (Subtarget.is64Bit()) {
292 {MVT::i8, MVT::i16, MVT::i32}, Custom);
293 }
294
297 Expand);
298
300 Custom);
301
302 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) {
303 if (Subtarget.is64Bit())
305 } else if (Subtarget.hasVendorXTHeadBb()) {
306 if (Subtarget.is64Bit())
309 } else if (Subtarget.hasVendorXCVbitmanip() && !Subtarget.is64Bit()) {
311 } else {
313 }
314
315 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
316 // pattern match it directly in isel.
318 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb() ||
319 Subtarget.hasVendorXTHeadBb())
320 ? Legal
321 : Expand);
322
323 if (Subtarget.hasVendorXCVbitmanip() && !Subtarget.is64Bit()) {
325 } else {
326 // Zbkb can use rev8+brev8 to implement bitreverse.
328 Subtarget.hasStdExtZbkb() ? Custom : Expand);
329 }
330
331 if (Subtarget.hasStdExtZbb() ||
332 (Subtarget.hasVendorXCValu() && !Subtarget.is64Bit())) {
334 Legal);
335 }
336
337 if (Subtarget.hasStdExtZbb() ||
338 (Subtarget.hasVendorXCVbitmanip() && !Subtarget.is64Bit())) {
339 if (Subtarget.is64Bit())
341 } else {
343 }
344
345 if (Subtarget.hasStdExtZbb() || Subtarget.hasVendorXTHeadBb() ||
346 (Subtarget.hasVendorXCVbitmanip() && !Subtarget.is64Bit())) {
347 // We need the custom lowering to make sure that the resulting sequence
348 // for the 32bit case is efficient on 64bit targets.
349 if (Subtarget.is64Bit())
351 } else {
353 }
354
355 if (Subtarget.hasVendorXCValu() && !Subtarget.is64Bit()) {
357 } else if (Subtarget.hasShortForwardBranchOpt()) {
358 // We can use PseudoCCSUB to implement ABS.
360 } else if (Subtarget.is64Bit()) {
362 }
363
364 if (!Subtarget.hasVendorXTHeadCondMov())
366
367 static const unsigned FPLegalNodeTypes[] = {
375
376 static const ISD::CondCode FPCCToExpand[] = {
380
381 static const unsigned FPOpToExpand[] = {
383 ISD::FREM};
384
385 static const unsigned FPRndMode[] = {
388
389 if (Subtarget.hasStdExtZfhminOrZhinxmin())
391
392 static const unsigned ZfhminZfbfminPromoteOps[] = {
407
408 if (Subtarget.hasStdExtZfbfmin()) {
417 setOperationAction(ZfhminZfbfminPromoteOps, MVT::bf16, Promote);
419 // FIXME: Need to promote bf16 FCOPYSIGN to f32, but the
420 // DAGCombiner::visitFP_ROUND probably needs improvements first.
422 }
423
424 if (Subtarget.hasStdExtZfhminOrZhinxmin()) {
425 if (Subtarget.hasStdExtZfhOrZhinx()) {
426 setOperationAction(FPLegalNodeTypes, MVT::f16, Legal);
427 setOperationAction(FPRndMode, MVT::f16,
428 Subtarget.hasStdExtZfa() ? Legal : Custom);
431 } else {
432 setOperationAction(ZfhminZfbfminPromoteOps, MVT::f16, Promote);
435 MVT::f16, Legal);
436 // FIXME: Need to promote f16 FCOPYSIGN to f32, but the
437 // DAGCombiner::visitFP_ROUND probably needs improvements first.
439 }
440
443 setCondCodeAction(FPCCToExpand, MVT::f16, Expand);
446
448 Subtarget.hasStdExtZfa() ? Legal : Promote);
453 MVT::f16, Promote);
454
455 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
456 // complete support for all operations in LegalizeDAG.
461 MVT::f16, Promote);
462
463 // We need to custom promote this.
464 if (Subtarget.is64Bit())
466
468 Subtarget.hasStdExtZfa() ? Legal : Custom);
469 }
470
471 if (Subtarget.hasStdExtFOrZfinx()) {
472 setOperationAction(FPLegalNodeTypes, MVT::f32, Legal);
473 setOperationAction(FPRndMode, MVT::f32,
474 Subtarget.hasStdExtZfa() ? Legal : Custom);
475 setCondCodeAction(FPCCToExpand, MVT::f32, Expand);
479 setOperationAction(FPOpToExpand, MVT::f32, Expand);
480 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
481 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
482 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::bf16, Expand);
483 setTruncStoreAction(MVT::f32, MVT::bf16, Expand);
487 Subtarget.isSoftFPABI() ? LibCall : Custom);
490
491 if (Subtarget.hasStdExtZfa()) {
494 } else {
496 }
497 }
498
499 if (Subtarget.hasStdExtFOrZfinx() && Subtarget.is64Bit())
501
502 if (Subtarget.hasStdExtDOrZdinx()) {
503 setOperationAction(FPLegalNodeTypes, MVT::f64, Legal);
504
505 if (!Subtarget.is64Bit())
507
508 if (Subtarget.hasStdExtZfa()) {
509 setOperationAction(FPRndMode, MVT::f64, Legal);
512 } else {
513 if (Subtarget.is64Bit())
514 setOperationAction(FPRndMode, MVT::f64, Custom);
515
517 }
518
521 setCondCodeAction(FPCCToExpand, MVT::f64, Expand);
525 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
526 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
527 setOperationAction(FPOpToExpand, MVT::f64, Expand);
528 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
529 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
530 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::bf16, Expand);
531 setTruncStoreAction(MVT::f64, MVT::bf16, Expand);
535 Subtarget.isSoftFPABI() ? LibCall : Custom);
538 }
539
540 if (Subtarget.is64Bit()) {
543 MVT::i32, Custom);
545 }
546
547 if (Subtarget.hasStdExtFOrZfinx()) {
549 Custom);
550
553 XLenVT, Legal);
554
557 }
558
561 XLenVT, Custom);
562
564
565 if (Subtarget.is64Bit())
567
568 // TODO: On M-mode only targets, the cycle[h]/time[h] CSR may not be present.
569 // Unfortunately this can't be determined just from the ISA naming string.
571 Subtarget.is64Bit() ? Legal : Custom);
573 Subtarget.is64Bit() ? Legal : Custom);
574
577 if (Subtarget.is64Bit())
579
580 if (Subtarget.hasStdExtZicbop()) {
582 }
583
584 if (Subtarget.hasStdExtA()) {
586 if (Subtarget.hasStdExtZabha() && Subtarget.hasStdExtZacas())
588 else
590 } else if (Subtarget.hasForcedAtomics()) {
592 } else {
594 }
595
597
599
600 if (getTargetMachine().getTargetTriple().isOSLinux()) {
601 // Custom lowering of llvm.clear_cache.
603 }
604
605 if (Subtarget.hasVInstructions()) {
607
609
610 // RVV intrinsics may have illegal operands.
611 // We also need to custom legalize vmv.x.s.
614 {MVT::i8, MVT::i16}, Custom);
615 if (Subtarget.is64Bit())
617 MVT::i32, Custom);
618 else
620 MVT::i64, Custom);
621
623 MVT::Other, Custom);
624
625 static const unsigned IntegerVPOps[] = {
626 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL,
627 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM,
628 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR,
629 ISD::VP_XOR, ISD::VP_SRA, ISD::VP_SRL,
630 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND,
631 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX,
632 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
633 ISD::VP_MERGE, ISD::VP_SELECT, ISD::VP_FP_TO_SINT,
634 ISD::VP_FP_TO_UINT, ISD::VP_SETCC, ISD::VP_SIGN_EXTEND,
635 ISD::VP_ZERO_EXTEND, ISD::VP_TRUNCATE, ISD::VP_SMIN,
636 ISD::VP_SMAX, ISD::VP_UMIN, ISD::VP_UMAX,
637 ISD::VP_ABS, ISD::EXPERIMENTAL_VP_REVERSE, ISD::EXPERIMENTAL_VP_SPLICE,
638 ISD::VP_SADDSAT, ISD::VP_UADDSAT, ISD::VP_SSUBSAT,
639 ISD::VP_USUBSAT, ISD::VP_CTTZ_ELTS, ISD::VP_CTTZ_ELTS_ZERO_UNDEF,
640 ISD::EXPERIMENTAL_VP_SPLAT};
641
642 static const unsigned FloatingPointVPOps[] = {
643 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL,
644 ISD::VP_FDIV, ISD::VP_FNEG, ISD::VP_FABS,
645 ISD::VP_FMA, ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
646 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_MERGE,
647 ISD::VP_SELECT, ISD::VP_SINT_TO_FP, ISD::VP_UINT_TO_FP,
648 ISD::VP_SETCC, ISD::VP_FP_ROUND, ISD::VP_FP_EXTEND,
649 ISD::VP_SQRT, ISD::VP_FMINNUM, ISD::VP_FMAXNUM,
650 ISD::VP_FCEIL, ISD::VP_FFLOOR, ISD::VP_FROUND,
651 ISD::VP_FROUNDEVEN, ISD::VP_FCOPYSIGN, ISD::VP_FROUNDTOZERO,
652 ISD::VP_FRINT, ISD::VP_FNEARBYINT, ISD::VP_IS_FPCLASS,
653 ISD::VP_FMINIMUM, ISD::VP_FMAXIMUM, ISD::VP_LRINT,
654 ISD::VP_LLRINT, ISD::EXPERIMENTAL_VP_REVERSE,
655 ISD::EXPERIMENTAL_VP_SPLICE, ISD::VP_REDUCE_FMINIMUM,
656 ISD::VP_REDUCE_FMAXIMUM, ISD::EXPERIMENTAL_VP_SPLAT};
657
658 static const unsigned IntegerVecReduceOps[] = {
662
663 static const unsigned FloatingPointVecReduceOps[] = {
666
667 if (!Subtarget.is64Bit()) {
668 // We must custom-lower certain vXi64 operations on RV32 due to the vector
669 // element type being illegal.
671 MVT::i64, Custom);
672
673 setOperationAction(IntegerVecReduceOps, MVT::i64, Custom);
674
675 setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND,
676 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR,
677 ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN,
678 ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN},
679 MVT::i64, Custom);
680 }
681
682 for (MVT VT : BoolVecVTs) {
683 if (!isTypeLegal(VT))
684 continue;
685
687
688 // Mask VTs are custom-expanded into a series of standard nodes
692 VT, Custom);
693
695 Custom);
696
699 {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT,
700 Expand);
701
702 setOperationAction({ISD::VP_CTTZ_ELTS, ISD::VP_CTTZ_ELTS_ZERO_UNDEF}, VT,
703 Custom);
704
705 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom);
706
709 Custom);
710
712 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
713 Custom);
714
715 // RVV has native int->float & float->int conversions where the
716 // element type sizes are within one power-of-two of each other. Any
717 // wider distances between type sizes have to be lowered as sequences
718 // which progressively narrow the gap in stages.
723 VT, Custom);
725 Custom);
726
727 // Expand all extending loads to types larger than this, and truncating
728 // stores from types larger than this.
730 setTruncStoreAction(VT, OtherVT, Expand);
732 OtherVT, Expand);
733 }
734
735 setOperationAction({ISD::VP_FP_TO_SINT, ISD::VP_FP_TO_UINT,
736 ISD::VP_TRUNCATE, ISD::VP_SETCC},
737 VT, Custom);
738
741
743
744 setOperationAction(ISD::EXPERIMENTAL_VP_SPLICE, VT, Custom);
745 setOperationAction(ISD::EXPERIMENTAL_VP_REVERSE, VT, Custom);
746
749 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount()));
750 }
751
752 for (MVT VT : IntVecVTs) {
753 if (!isTypeLegal(VT))
754 continue;
755
758
759 // Vectors implement MULHS/MULHU.
761
762 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
763 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV())
765
767 Legal);
768
770
771 // Custom-lower extensions and truncations from/to mask types.
773 VT, Custom);
774
775 // RVV has native int->float & float->int conversions where the
776 // element type sizes are within one power-of-two of each other. Any
777 // wider distances between type sizes have to be lowered as sequences
778 // which progressively narrow the gap in stages.
783 VT, Custom);
785 Custom);
789 VT, Legal);
790
791 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
792 // nodes which truncate by one power of two at a time.
795 Custom);
796
797 // Custom-lower insert/extract operations to simplify patterns.
799 Custom);
800
801 // Custom-lower reduction operations to set up the corresponding custom
802 // nodes' operands.
803 setOperationAction(IntegerVecReduceOps, VT, Custom);
804
805 setOperationAction(IntegerVPOps, VT, Custom);
806
808
810 VT, Custom);
811
813 {ISD::VP_LOAD, ISD::VP_STORE, ISD::EXPERIMENTAL_VP_STRIDED_LOAD,
814 ISD::EXPERIMENTAL_VP_STRIDED_STORE, ISD::VP_GATHER, ISD::VP_SCATTER},
815 VT, Custom);
816
819 VT, Custom);
820
823
825
827 setTruncStoreAction(VT, OtherVT, Expand);
829 OtherVT, Expand);
830 }
831
834
835 // Splice
837
838 if (Subtarget.hasStdExtZvkb()) {
840 setOperationAction(ISD::VP_BSWAP, VT, Custom);
841 } else {
842 setOperationAction({ISD::BSWAP, ISD::VP_BSWAP}, VT, Expand);
844 }
845
846 if (Subtarget.hasStdExtZvbb()) {
848 setOperationAction(ISD::VP_BITREVERSE, VT, Custom);
849 setOperationAction({ISD::VP_CTLZ, ISD::VP_CTLZ_ZERO_UNDEF, ISD::VP_CTTZ,
850 ISD::VP_CTTZ_ZERO_UNDEF, ISD::VP_CTPOP},
851 VT, Custom);
852 } else {
853 setOperationAction({ISD::BITREVERSE, ISD::VP_BITREVERSE}, VT, Expand);
855 setOperationAction({ISD::VP_CTLZ, ISD::VP_CTLZ_ZERO_UNDEF, ISD::VP_CTTZ,
856 ISD::VP_CTTZ_ZERO_UNDEF, ISD::VP_CTPOP},
857 VT, Expand);
858
859 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if element of VT in the
860 // range of f32.
861 EVT FloatVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
862 if (isTypeLegal(FloatVT)) {
864 ISD::CTTZ_ZERO_UNDEF, ISD::VP_CTLZ,
865 ISD::VP_CTLZ_ZERO_UNDEF, ISD::VP_CTTZ_ZERO_UNDEF},
866 VT, Custom);
867 }
868 }
869 }
870
871 // Expand various CCs to best match the RVV ISA, which natively supports UNE
872 // but no other unordered comparisons, and supports all ordered comparisons
873 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
874 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
875 // and we pattern-match those back to the "original", swapping operands once
876 // more. This way we catch both operations and both "vf" and "fv" forms with
877 // fewer patterns.
878 static const ISD::CondCode VFPCCToExpand[] = {
882 };
883
884 // TODO: support more ops.
885 static const unsigned ZvfhminPromoteOps[] = {
893
894 // TODO: support more vp ops.
895 static const unsigned ZvfhminPromoteVPOps[] = {
896 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL,
897 ISD::VP_FDIV, ISD::VP_FNEG, ISD::VP_FABS,
898 ISD::VP_FMA, ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
899 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_SQRT,
900 ISD::VP_FMINNUM, ISD::VP_FMAXNUM, ISD::VP_FCEIL,
901 ISD::VP_FFLOOR, ISD::VP_FROUND, ISD::VP_FROUNDEVEN,
902 ISD::VP_FCOPYSIGN, ISD::VP_FROUNDTOZERO, ISD::VP_FRINT,
903 ISD::VP_FNEARBYINT, ISD::VP_SETCC, ISD::VP_FMINIMUM,
904 ISD::VP_FMAXIMUM, ISD::VP_REDUCE_FMINIMUM, ISD::VP_REDUCE_FMAXIMUM};
905
906 // Sets common operation actions on RVV floating-point vector types.
907 const auto SetCommonVFPActions = [&](MVT VT) {
909 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
910 // sizes are within one power-of-two of each other. Therefore conversions
911 // between vXf16 and vXf64 must be lowered as sequences which convert via
912 // vXf32.
915 // Custom-lower insert/extract operations to simplify patterns.
917 Custom);
918 // Expand various condition codes (explained above).
919 setCondCodeAction(VFPCCToExpand, VT, Expand);
920
923
927 VT, Custom);
928
929 setOperationAction(FloatingPointVecReduceOps, VT, Custom);
930
931 // Expand FP operations that need libcalls.
943
945
947
949 VT, Custom);
950
952 {ISD::VP_LOAD, ISD::VP_STORE, ISD::EXPERIMENTAL_VP_STRIDED_LOAD,
953 ISD::EXPERIMENTAL_VP_STRIDED_STORE, ISD::VP_GATHER, ISD::VP_SCATTER},
954 VT, Custom);
955
958
961 VT, Custom);
962
965
967
968 setOperationAction(FloatingPointVPOps, VT, Custom);
969
971 Custom);
974 VT, Legal);
979 VT, Custom);
980 };
981
982 // Sets common extload/truncstore actions on RVV floating-point vector
983 // types.
984 const auto SetCommonVFPExtLoadTruncStoreActions =
985 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
986 for (auto SmallVT : SmallerVTs) {
987 setTruncStoreAction(VT, SmallVT, Expand);
988 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
989 }
990 };
991
992 if (Subtarget.hasVInstructionsF16()) {
993 for (MVT VT : F16VecVTs) {
994 if (!isTypeLegal(VT))
995 continue;
996 SetCommonVFPActions(VT);
997 }
998 } else if (Subtarget.hasVInstructionsF16Minimal()) {
999 for (MVT VT : F16VecVTs) {
1000 if (!isTypeLegal(VT))
1001 continue;
1004 Custom);
1005 setOperationAction({ISD::VP_FP_ROUND, ISD::VP_FP_EXTEND}, VT, Custom);
1006 setOperationAction({ISD::VP_MERGE, ISD::VP_SELECT, ISD::SELECT}, VT,
1007 Custom);
1010 ISD::VP_SINT_TO_FP, ISD::VP_UINT_TO_FP},
1011 VT, Custom);
1014 VT, Custom);
1015 if (Subtarget.hasStdExtZfhmin())
1017 // load/store
1019
1020 // Custom split nxv32f16 since nxv32f32 if not legal.
1021 if (VT == MVT::nxv32f16) {
1022 setOperationAction(ZvfhminPromoteOps, VT, Custom);
1023 setOperationAction(ZvfhminPromoteVPOps, VT, Custom);
1024 continue;
1025 }
1026 // Add more promote ops.
1027 MVT F32VecVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
1028 setOperationPromotedToType(ZvfhminPromoteOps, VT, F32VecVT);
1029 setOperationPromotedToType(ZvfhminPromoteVPOps, VT, F32VecVT);
1030 }
1031 }
1032
1033 // TODO: Could we merge some code with zvfhmin?
1034 if (Subtarget.hasVInstructionsBF16Minimal()) {
1035 for (MVT VT : BF16VecVTs) {
1036 if (!isTypeLegal(VT))
1037 continue;
1039 setOperationAction({ISD::VP_FP_ROUND, ISD::VP_FP_EXTEND}, VT, Custom);
1041 Custom);
1044 VT, Custom);
1046 if (Subtarget.hasStdExtZfbfmin())
1048 setOperationAction({ISD::VP_MERGE, ISD::VP_SELECT, ISD::SELECT}, VT,
1049 Custom);
1051 // TODO: Promote to fp32.
1052 }
1053 }
1054
1055 if (Subtarget.hasVInstructionsF32()) {
1056 for (MVT VT : F32VecVTs) {
1057 if (!isTypeLegal(VT))
1058 continue;
1059 SetCommonVFPActions(VT);
1060 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
1061 }
1062 }
1063
1064 if (Subtarget.hasVInstructionsF64()) {
1065 for (MVT VT : F64VecVTs) {
1066 if (!isTypeLegal(VT))
1067 continue;
1068 SetCommonVFPActions(VT);
1069 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
1070 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
1071 }
1072 }
1073
1074 if (Subtarget.useRVVForFixedLengthVectors()) {
1076 if (!useRVVForFixedLengthVectorVT(VT))
1077 continue;
1078
1079 // By default everything must be expanded.
1080 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
1083 setTruncStoreAction(VT, OtherVT, Expand);
1085 OtherVT, Expand);
1086 }
1087
1088 // Custom lower fixed vector undefs to scalable vector undefs to avoid
1089 // expansion to a build_vector of 0s.
1091
1092 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
1094 Custom);
1095
1098 Custom);
1099
1101 VT, Custom);
1102
1104
1106
1108
1110
1113 Custom);
1114
1116
1119 Custom);
1120
1122 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
1123 Custom);
1124
1126 {
1135 },
1136 VT, Custom);
1138 Custom);
1139
1141
1142 // Operations below are different for between masks and other vectors.
1143 if (VT.getVectorElementType() == MVT::i1) {
1144 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND,
1145 ISD::OR, ISD::XOR},
1146 VT, Custom);
1147
1148 setOperationAction({ISD::VP_FP_TO_SINT, ISD::VP_FP_TO_UINT,
1149 ISD::VP_SETCC, ISD::VP_TRUNCATE},
1150 VT, Custom);
1151
1152 setOperationAction(ISD::EXPERIMENTAL_VP_SPLICE, VT, Custom);
1153 setOperationAction(ISD::EXPERIMENTAL_VP_REVERSE, VT, Custom);
1154 continue;
1155 }
1156
1157 // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to
1158 // it before type legalization for i64 vectors on RV32. It will then be
1159 // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle.
1160 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
1161 // improvements first.
1162 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
1165 }
1166
1169
1170 setOperationAction({ISD::VP_LOAD, ISD::VP_STORE,
1171 ISD::EXPERIMENTAL_VP_STRIDED_LOAD,
1172 ISD::EXPERIMENTAL_VP_STRIDED_STORE, ISD::VP_GATHER,
1173 ISD::VP_SCATTER},
1174 VT, Custom);
1175
1179 VT, Custom);
1180
1183
1185
1186 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
1187 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV())
1189
1193 VT, Custom);
1194
1196
1199
1200 // Custom-lower reduction operations to set up the corresponding custom
1201 // nodes' operands.
1205 VT, Custom);
1206
1207 setOperationAction(IntegerVPOps, VT, Custom);
1208
1209 if (Subtarget.hasStdExtZvkb())
1211
1212 if (Subtarget.hasStdExtZvbb()) {
1215 VT, Custom);
1216 } else {
1217 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if element of VT in the
1218 // range of f32.
1219 EVT FloatVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
1220 if (isTypeLegal(FloatVT))
1223 Custom);
1224 }
1225 }
1226
1228 // There are no extending loads or truncating stores.
1229 for (MVT InnerVT : MVT::fp_fixedlen_vector_valuetypes()) {
1230 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
1231 setTruncStoreAction(VT, InnerVT, Expand);
1232 }
1233
1234 if (!useRVVForFixedLengthVectorVT(VT))
1235 continue;
1236
1237 // By default everything must be expanded.
1238 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
1240
1241 // Custom lower fixed vector undefs to scalable vector undefs to avoid
1242 // expansion to a build_vector of 0s.
1244
1247 VT, Custom);
1248
1249 // FIXME: mload, mstore, mgather, mscatter, vp_load/store,
1250 // vp_stride_load/store, vp_gather/scatter can be hoisted to here.
1252
1255 Custom);
1256
1257 if (VT.getVectorElementType() == MVT::f16 &&
1258 !Subtarget.hasVInstructionsF16()) {
1259 setOperationAction({ISD::VP_FP_ROUND, ISD::VP_FP_EXTEND}, VT, Custom);
1261 {ISD::VP_MERGE, ISD::VP_SELECT, ISD::VSELECT, ISD::SELECT}, VT,
1262 Custom);
1264 ISD::VP_SINT_TO_FP, ISD::VP_UINT_TO_FP},
1265 VT, Custom);
1267 if (Subtarget.hasStdExtZfhmin()) {
1268 // FIXME: We should prefer BUILD_VECTOR over SPLAT_VECTOR.
1270 } else {
1271 // We need to custom legalize f16 build vectors if Zfhmin isn't
1272 // available.
1274 }
1275 MVT F32VecVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
1276 // Don't promote f16 vector operations to f32 if f32 vector type is
1277 // not legal.
1278 // TODO: could split the f16 vector into two vectors and do promotion.
1279 if (!isTypeLegal(F32VecVT))
1280 continue;
1281 setOperationPromotedToType(ZvfhminPromoteOps, VT, F32VecVT);
1282 setOperationPromotedToType(ZvfhminPromoteVPOps, VT, F32VecVT);
1283 continue;
1284 }
1285
1286 if (VT.getVectorElementType() == MVT::bf16) {
1287 setOperationAction({ISD::VP_FP_ROUND, ISD::VP_FP_EXTEND}, VT, Custom);
1288 // FIXME: We should prefer BUILD_VECTOR over SPLAT_VECTOR.
1291 {ISD::VP_MERGE, ISD::VP_SELECT, ISD::VSELECT, ISD::SELECT}, VT,
1292 Custom);
1293 // TODO: Promote to fp32.
1294 continue;
1295 }
1296
1299 VT, Custom);
1300
1303
1304 setOperationAction({ISD::VP_LOAD, ISD::VP_STORE,
1305 ISD::EXPERIMENTAL_VP_STRIDED_LOAD,
1306 ISD::EXPERIMENTAL_VP_STRIDED_STORE, ISD::VP_GATHER,
1307 ISD::VP_SCATTER},
1308 VT, Custom);
1309
1314 VT, Custom);
1315
1318 VT, Custom);
1319
1320 setCondCodeAction(VFPCCToExpand, VT, Expand);
1321
1324
1326
1327 setOperationAction(FloatingPointVecReduceOps, VT, Custom);
1328
1329 setOperationAction(FloatingPointVPOps, VT, Custom);
1330
1337 VT, Custom);
1338 }
1339
1340 // Custom-legalize bitcasts from fixed-length vectors to scalar types.
1341 setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64},
1342 Custom);
1343 if (Subtarget.hasStdExtZfhminOrZhinxmin())
1345 if (Subtarget.hasStdExtFOrZfinx())
1347 if (Subtarget.hasStdExtDOrZdinx())
1349 }
1350 }
1351
1352 if (Subtarget.hasStdExtA())
1354
1355 if (Subtarget.hasForcedAtomics()) {
1356 // Force __sync libcalls to be emitted for atomic rmw/cas operations.
1362 XLenVT, LibCall);
1363 }
1364
1365 if (Subtarget.hasVendorXTHeadMemIdx()) {
1366 for (unsigned im : {ISD::PRE_INC, ISD::POST_INC}) {
1367 setIndexedLoadAction(im, MVT::i8, Legal);
1368 setIndexedStoreAction(im, MVT::i8, Legal);
1369 setIndexedLoadAction(im, MVT::i16, Legal);
1370 setIndexedStoreAction(im, MVT::i16, Legal);
1371 setIndexedLoadAction(im, MVT::i32, Legal);
1372 setIndexedStoreAction(im, MVT::i32, Legal);
1373
1374 if (Subtarget.is64Bit()) {
1375 setIndexedLoadAction(im, MVT::i64, Legal);
1376 setIndexedStoreAction(im, MVT::i64, Legal);
1377 }
1378 }
1379 }
1380
1381 if (Subtarget.hasVendorXCVmem() && !Subtarget.is64Bit()) {
1385
1389 }
1390
1391 // Function alignments.
1392 const Align FunctionAlignment(Subtarget.hasStdExtCOrZca() ? 2 : 4);
1393 setMinFunctionAlignment(FunctionAlignment);
1394 // Set preferred alignments.
1397
1402
1403 if (Subtarget.hasStdExtFOrZfinx())
1405
1406 if (Subtarget.hasStdExtZbb())
1408
1409 if ((Subtarget.hasStdExtZbs() && Subtarget.is64Bit()) ||
1410 Subtarget.hasVInstructions())
1412
1413 if (Subtarget.hasStdExtZbkb())
1415 if (Subtarget.hasStdExtZfhminOrZhinxmin())
1417 if (Subtarget.hasStdExtFOrZfinx())
1420 if (Subtarget.hasVInstructions())
1422 ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL,
1425 ISD::EXPERIMENTAL_VP_REVERSE, ISD::MUL,
1428 if (Subtarget.hasVendorXTHeadMemPair())
1430 if (Subtarget.useRVVForFixedLengthVectors())
1432
1433 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
1434 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
1435
1436 // Disable strict node mutation.
1437 IsStrictFPEnabled = true;
1438 EnableExtLdPromotion = true;
1439
1440 // Let the subtarget decide if a predictable select is more expensive than the
1441 // corresponding branch. This information is used in CGP/SelectOpt to decide
1442 // when to convert selects into branches.
1443 PredictableSelectIsExpensive = Subtarget.predictableSelectIsExpensive();
1444}
1445
1447 LLVMContext &Context,
1448 EVT VT) const {
1449 if (!VT.isVector())
1450 return getPointerTy(DL);
1451 if (Subtarget.hasVInstructions() &&
1452 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1453 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1455}
1456
1457MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1458 return Subtarget.getXLenVT();
1459}
1460
1461// Return false if we can lower get_vector_length to a vsetvli intrinsic.
1462bool RISCVTargetLowering::shouldExpandGetVectorLength(EVT TripCountVT,
1463 unsigned VF,
1464 bool IsScalable) const {
1465 if (!Subtarget.hasVInstructions())
1466 return true;
1467
1468 if (!IsScalable)
1469 return true;
1470
1471 if (TripCountVT != MVT::i32 && TripCountVT != Subtarget.getXLenVT())
1472 return true;
1473
1474 // Don't allow VF=1 if those types are't legal.
1475 if (VF < RISCV::RVVBitsPerBlock / Subtarget.getELen())
1476 return true;
1477
1478 // VLEN=32 support is incomplete.
1479 if (Subtarget.getRealMinVLen() < RISCV::RVVBitsPerBlock)
1480 return true;
1481
1482 // The maximum VF is for the smallest element width with LMUL=8.
1483 // VF must be a power of 2.
1484 unsigned MaxVF = (RISCV::RVVBitsPerBlock / 8) * 8;
1485 return VF > MaxVF || !isPowerOf2_32(VF);
1486}
1487
1489 return !Subtarget.hasVInstructions() ||
1490 VT.getVectorElementType() != MVT::i1 || !isTypeLegal(VT);
1491}
1492
1494 const CallInst &I,
1495 MachineFunction &MF,
1496 unsigned Intrinsic) const {
1497 auto &DL = I.getDataLayout();
1498
1499 auto SetRVVLoadStoreInfo = [&](unsigned PtrOp, bool IsStore,
1500 bool IsUnitStrided, bool UsePtrVal = false) {
1502 // We can't use ptrVal if the intrinsic can access memory before the
1503 // pointer. This means we can't use it for strided or indexed intrinsics.
1504 if (UsePtrVal)
1505 Info.ptrVal = I.getArgOperand(PtrOp);
1506 else
1507 Info.fallbackAddressSpace =
1508 I.getArgOperand(PtrOp)->getType()->getPointerAddressSpace();
1509 Type *MemTy;
1510 if (IsStore) {
1511 // Store value is the first operand.
1512 MemTy = I.getArgOperand(0)->getType();
1513 } else {
1514 // Use return type. If it's segment load, return type is a struct.
1515 MemTy = I.getType();
1516 if (MemTy->isStructTy())
1517 MemTy = MemTy->getStructElementType(0);
1518 }
1519 if (!IsUnitStrided)
1520 MemTy = MemTy->getScalarType();
1521
1522 Info.memVT = getValueType(DL, MemTy);
1523 Info.align = Align(DL.getTypeSizeInBits(MemTy->getScalarType()) / 8);
1525 Info.flags |=
1527 return true;
1528 };
1529
1530 if (I.hasMetadata(LLVMContext::MD_nontemporal))
1532
1534 switch (Intrinsic) {
1535 default:
1536 return false;
1537 case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1538 case Intrinsic::riscv_masked_atomicrmw_add_i32:
1539 case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1540 case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1541 case Intrinsic::riscv_masked_atomicrmw_max_i32:
1542 case Intrinsic::riscv_masked_atomicrmw_min_i32:
1543 case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1544 case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1545 case Intrinsic::riscv_masked_cmpxchg_i32:
1547 Info.memVT = MVT::i32;
1548 Info.ptrVal = I.getArgOperand(0);
1549 Info.offset = 0;
1550 Info.align = Align(4);
1553 return true;
1554 case Intrinsic::riscv_seg2_load:
1555 case Intrinsic::riscv_seg3_load:
1556 case Intrinsic::riscv_seg4_load:
1557 case Intrinsic::riscv_seg5_load:
1558 case Intrinsic::riscv_seg6_load:
1559 case Intrinsic::riscv_seg7_load:
1560 case Intrinsic::riscv_seg8_load:
1561 return SetRVVLoadStoreInfo(/*PtrOp*/ 0, /*IsStore*/ false,
1562 /*IsUnitStrided*/ false, /*UsePtrVal*/ true);
1563 case Intrinsic::riscv_seg2_store:
1564 case Intrinsic::riscv_seg3_store:
1565 case Intrinsic::riscv_seg4_store:
1566 case Intrinsic::riscv_seg5_store:
1567 case Intrinsic::riscv_seg6_store:
1568 case Intrinsic::riscv_seg7_store:
1569 case Intrinsic::riscv_seg8_store:
1570 // Operands are (vec, ..., vec, ptr, vl)
1571 return SetRVVLoadStoreInfo(/*PtrOp*/ I.arg_size() - 2,
1572 /*IsStore*/ true,
1573 /*IsUnitStrided*/ false, /*UsePtrVal*/ true);
1574 case Intrinsic::riscv_vle:
1575 case Intrinsic::riscv_vle_mask:
1576 case Intrinsic::riscv_vleff:
1577 case Intrinsic::riscv_vleff_mask:
1578 return SetRVVLoadStoreInfo(/*PtrOp*/ 1,
1579 /*IsStore*/ false,
1580 /*IsUnitStrided*/ true,
1581 /*UsePtrVal*/ true);
1582 case Intrinsic::riscv_vse:
1583 case Intrinsic::riscv_vse_mask:
1584 return SetRVVLoadStoreInfo(/*PtrOp*/ 1,
1585 /*IsStore*/ true,
1586 /*IsUnitStrided*/ true,
1587 /*UsePtrVal*/ true);
1588 case Intrinsic::riscv_vlse:
1589 case Intrinsic::riscv_vlse_mask:
1590 case Intrinsic::riscv_vloxei:
1591 case Intrinsic::riscv_vloxei_mask:
1592 case Intrinsic::riscv_vluxei:
1593 case Intrinsic::riscv_vluxei_mask:
1594 return SetRVVLoadStoreInfo(/*PtrOp*/ 1,
1595 /*IsStore*/ false,
1596 /*IsUnitStrided*/ false);
1597 case Intrinsic::riscv_vsse:
1598 case Intrinsic::riscv_vsse_mask:
1599 case Intrinsic::riscv_vsoxei:
1600 case Intrinsic::riscv_vsoxei_mask:
1601 case Intrinsic::riscv_vsuxei:
1602 case Intrinsic::riscv_vsuxei_mask:
1603 return SetRVVLoadStoreInfo(/*PtrOp*/ 1,
1604 /*IsStore*/ true,
1605 /*IsUnitStrided*/ false);
1606 case Intrinsic::riscv_vlseg2:
1607 case Intrinsic::riscv_vlseg3:
1608 case Intrinsic::riscv_vlseg4:
1609 case Intrinsic::riscv_vlseg5:
1610 case Intrinsic::riscv_vlseg6:
1611 case Intrinsic::riscv_vlseg7:
1612 case Intrinsic::riscv_vlseg8:
1613 case Intrinsic::riscv_vlseg2ff:
1614 case Intrinsic::riscv_vlseg3ff:
1615 case Intrinsic::riscv_vlseg4ff:
1616 case Intrinsic::riscv_vlseg5ff:
1617 case Intrinsic::riscv_vlseg6ff:
1618 case Intrinsic::riscv_vlseg7ff:
1619 case Intrinsic::riscv_vlseg8ff:
1620 return SetRVVLoadStoreInfo(/*PtrOp*/ I.arg_size() - 2,
1621 /*IsStore*/ false,
1622 /*IsUnitStrided*/ false, /*UsePtrVal*/ true);
1623 case Intrinsic::riscv_vlseg2_mask:
1624 case Intrinsic::riscv_vlseg3_mask:
1625 case Intrinsic::riscv_vlseg4_mask:
1626 case Intrinsic::riscv_vlseg5_mask:
1627 case Intrinsic::riscv_vlseg6_mask:
1628 case Intrinsic::riscv_vlseg7_mask:
1629 case Intrinsic::riscv_vlseg8_mask:
1630 case Intrinsic::riscv_vlseg2ff_mask:
1631 case Intrinsic::riscv_vlseg3ff_mask:
1632 case Intrinsic::riscv_vlseg4ff_mask:
1633 case Intrinsic::riscv_vlseg5ff_mask:
1634 case Intrinsic::riscv_vlseg6ff_mask:
1635 case Intrinsic::riscv_vlseg7ff_mask:
1636 case Intrinsic::riscv_vlseg8ff_mask:
1637 return SetRVVLoadStoreInfo(/*PtrOp*/ I.arg_size() - 4,
1638 /*IsStore*/ false,
1639 /*IsUnitStrided*/ false, /*UsePtrVal*/ true);
1640 case Intrinsic::riscv_vlsseg2:
1641 case Intrinsic::riscv_vlsseg3:
1642 case Intrinsic::riscv_vlsseg4:
1643 case Intrinsic::riscv_vlsseg5:
1644 case Intrinsic::riscv_vlsseg6:
1645 case Intrinsic::riscv_vlsseg7:
1646 case Intrinsic::riscv_vlsseg8:
1647 case Intrinsic::riscv_vloxseg2:
1648 case Intrinsic::riscv_vloxseg3:
1649 case Intrinsic::riscv_vloxseg4:
1650 case Intrinsic::riscv_vloxseg5:
1651 case Intrinsic::riscv_vloxseg6:
1652 case Intrinsic::riscv_vloxseg7:
1653 case Intrinsic::riscv_vloxseg8:
1654 case Intrinsic::riscv_vluxseg2:
1655 case Intrinsic::riscv_vluxseg3:
1656 case Intrinsic::riscv_vluxseg4:
1657 case Intrinsic::riscv_vluxseg5:
1658 case Intrinsic::riscv_vluxseg6:
1659 case Intrinsic::riscv_vluxseg7:
1660 case Intrinsic::riscv_vluxseg8:
1661 return SetRVVLoadStoreInfo(/*PtrOp*/ I.arg_size() - 3,
1662 /*IsStore*/ false,
1663 /*IsUnitStrided*/ false);
1664 case Intrinsic::riscv_vlsseg2_mask:
1665 case Intrinsic::riscv_vlsseg3_mask:
1666 case Intrinsic::riscv_vlsseg4_mask:
1667 case Intrinsic::riscv_vlsseg5_mask:
1668 case Intrinsic::riscv_vlsseg6_mask:
1669 case Intrinsic::riscv_vlsseg7_mask:
1670 case Intrinsic::riscv_vlsseg8_mask:
1671 case Intrinsic::riscv_vloxseg2_mask:
1672 case Intrinsic::riscv_vloxseg3_mask:
1673 case Intrinsic::riscv_vloxseg4_mask:
1674 case Intrinsic::riscv_vloxseg5_mask:
1675 case Intrinsic::riscv_vloxseg6_mask:
1676 case Intrinsic::riscv_vloxseg7_mask:
1677 case Intrinsic::riscv_vloxseg8_mask:
1678 case Intrinsic::riscv_vluxseg2_mask:
1679 case Intrinsic::riscv_vluxseg3_mask:
1680 case Intrinsic::riscv_vluxseg4_mask:
1681 case Intrinsic::riscv_vluxseg5_mask:
1682 case Intrinsic::riscv_vluxseg6_mask:
1683 case Intrinsic::riscv_vluxseg7_mask:
1684 case Intrinsic::riscv_vluxseg8_mask:
1685 return SetRVVLoadStoreInfo(/*PtrOp*/ I.arg_size() - 5,
1686 /*IsStore*/ false,
1687 /*IsUnitStrided*/ false);
1688 case Intrinsic::riscv_vsseg2:
1689 case Intrinsic::riscv_vsseg3:
1690 case Intrinsic::riscv_vsseg4:
1691 case Intrinsic::riscv_vsseg5:
1692 case Intrinsic::riscv_vsseg6:
1693 case Intrinsic::riscv_vsseg7:
1694 case Intrinsic::riscv_vsseg8:
1695 return SetRVVLoadStoreInfo(/*PtrOp*/ I.arg_size() - 2,
1696 /*IsStore*/ true,
1697 /*IsUnitStrided*/ false);
1698 case Intrinsic::riscv_vsseg2_mask:
1699 case Intrinsic::riscv_vsseg3_mask:
1700 case Intrinsic::riscv_vsseg4_mask:
1701 case Intrinsic::riscv_vsseg5_mask:
1702 case Intrinsic::riscv_vsseg6_mask:
1703 case Intrinsic::riscv_vsseg7_mask:
1704 case Intrinsic::riscv_vsseg8_mask:
1705 return SetRVVLoadStoreInfo(/*PtrOp*/ I.arg_size() - 3,
1706 /*IsStore*/ true,
1707 /*IsUnitStrided*/ false);
1708 case Intrinsic::riscv_vssseg2:
1709 case Intrinsic::riscv_vssseg3:
1710 case Intrinsic::riscv_vssseg4:
1711 case Intrinsic::riscv_vssseg5:
1712 case Intrinsic::riscv_vssseg6:
1713 case Intrinsic::riscv_vssseg7:
1714 case Intrinsic::riscv_vssseg8:
1715 case Intrinsic::riscv_vsoxseg2:
1716 case Intrinsic::riscv_vsoxseg3:
1717 case Intrinsic::riscv_vsoxseg4:
1718 case Intrinsic::riscv_vsoxseg5:
1719 case Intrinsic::riscv_vsoxseg6:
1720 case Intrinsic::riscv_vsoxseg7:
1721 case Intrinsic::riscv_vsoxseg8:
1722 case Intrinsic::riscv_vsuxseg2:
1723 case Intrinsic::riscv_vsuxseg3:
1724 case Intrinsic::riscv_vsuxseg4:
1725 case Intrinsic::riscv_vsuxseg5:
1726 case Intrinsic::riscv_vsuxseg6:
1727 case Intrinsic::riscv_vsuxseg7:
1728 case Intrinsic::riscv_vsuxseg8:
1729 return SetRVVLoadStoreInfo(/*PtrOp*/ I.arg_size() - 3,
1730 /*IsStore*/ true,
1731 /*IsUnitStrided*/ false);
1732 case Intrinsic::riscv_vssseg2_mask:
1733 case Intrinsic::riscv_vssseg3_mask:
1734 case Intrinsic::riscv_vssseg4_mask:
1735 case Intrinsic::riscv_vssseg5_mask:
1736 case Intrinsic::riscv_vssseg6_mask:
1737 case Intrinsic::riscv_vssseg7_mask:
1738 case Intrinsic::riscv_vssseg8_mask:
1739 case Intrinsic::riscv_vsoxseg2_mask:
1740 case Intrinsic::riscv_vsoxseg3_mask:
1741 case Intrinsic::riscv_vsoxseg4_mask:
1742 case Intrinsic::riscv_vsoxseg5_mask:
1743 case Intrinsic::riscv_vsoxseg6_mask:
1744 case Intrinsic::riscv_vsoxseg7_mask:
1745 case Intrinsic::riscv_vsoxseg8_mask:
1746 case Intrinsic::riscv_vsuxseg2_mask:
1747 case Intrinsic::riscv_vsuxseg3_mask:
1748 case Intrinsic::riscv_vsuxseg4_mask:
1749 case Intrinsic::riscv_vsuxseg5_mask:
1750 case Intrinsic::riscv_vsuxseg6_mask:
1751 case Intrinsic::riscv_vsuxseg7_mask:
1752 case Intrinsic::riscv_vsuxseg8_mask:
1753 return SetRVVLoadStoreInfo(/*PtrOp*/ I.arg_size() - 4,
1754 /*IsStore*/ true,
1755 /*IsUnitStrided*/ false);
1756 }
1757}
1758
1760 const AddrMode &AM, Type *Ty,
1761 unsigned AS,
1762 Instruction *I) const {
1763 // No global is ever allowed as a base.
1764 if (AM.BaseGV)
1765 return false;
1766
1767 // None of our addressing modes allows a scalable offset
1768 if (AM.ScalableOffset)
1769 return false;
1770
1771 // RVV instructions only support register addressing.
1772 if (Subtarget.hasVInstructions() && isa<VectorType>(Ty))
1773 return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs;
1774
1775 // Require a 12-bit signed offset.
1776 if (!isInt<12>(AM.BaseOffs))
1777 return false;
1778
1779 switch (AM.Scale) {
1780 case 0: // "r+i" or just "i", depending on HasBaseReg.
1781 break;
1782 case 1:
1783 if (!AM.HasBaseReg) // allow "r+i".
1784 break;
1785 return false; // disallow "r+r" or "r+r+i".
1786 default:
1787 return false;
1788 }
1789
1790 return true;
1791}
1792
1794 return isInt<12>(Imm);
1795}
1796
1798 return isInt<12>(Imm);
1799}
1800
1801// On RV32, 64-bit integers are split into their high and low parts and held
1802// in two different registers, so the trunc is free since the low register can
1803// just be used.
1804// FIXME: Should we consider i64->i32 free on RV64 to match the EVT version of
1805// isTruncateFree?
1807 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1808 return false;
1809 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1810 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1811 return (SrcBits == 64 && DestBits == 32);
1812}
1813
1815 // We consider i64->i32 free on RV64 since we have good selection of W
1816 // instructions that make promoting operations back to i64 free in many cases.
1817 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
1818 !DstVT.isInteger())
1819 return false;
1820 unsigned SrcBits = SrcVT.getSizeInBits();
1821 unsigned DestBits = DstVT.getSizeInBits();
1822 return (SrcBits == 64 && DestBits == 32);
1823}
1824
1826 EVT SrcVT = Val.getValueType();
1827 // free truncate from vnsrl and vnsra
1828 if (Subtarget.hasVInstructions() &&
1829 (Val.getOpcode() == ISD::SRL || Val.getOpcode() == ISD::SRA) &&
1830 SrcVT.isVector() && VT2.isVector()) {
1831 unsigned SrcBits = SrcVT.getVectorElementType().getSizeInBits();
1832 unsigned DestBits = VT2.getVectorElementType().getSizeInBits();
1833 if (SrcBits == DestBits * 2) {
1834 return true;
1835 }
1836 }
1837 return TargetLowering::isTruncateFree(Val, VT2);
1838}
1839
1841 // Zexts are free if they can be combined with a load.
1842 // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1843 // poorly with type legalization of compares preferring sext.
1844 if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1845 EVT MemVT = LD->getMemoryVT();
1846 if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1847 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1848 LD->getExtensionType() == ISD::ZEXTLOAD))
1849 return true;
1850 }
1851
1852 return TargetLowering::isZExtFree(Val, VT2);
1853}
1854
1856 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1857}
1858
1860 return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32);
1861}
1862
1864 return Subtarget.hasStdExtZbb() ||
1865 (Subtarget.hasVendorXCVbitmanip() && !Subtarget.is64Bit());
1866}
1867
1869 return Subtarget.hasStdExtZbb() || Subtarget.hasVendorXTHeadBb() ||
1870 (Subtarget.hasVendorXCVbitmanip() && !Subtarget.is64Bit());
1871}
1872
1874 const Instruction &AndI) const {
1875 // We expect to be able to match a bit extraction instruction if the Zbs
1876 // extension is supported and the mask is a power of two. However, we
1877 // conservatively return false if the mask would fit in an ANDI instruction,
1878 // on the basis that it's possible the sinking+duplication of the AND in
1879 // CodeGenPrepare triggered by this hook wouldn't decrease the instruction
1880 // count and would increase code size (e.g. ANDI+BNEZ => BEXTI+BNEZ).
1881 if (!Subtarget.hasStdExtZbs() && !Subtarget.hasVendorXTHeadBs())
1882 return false;
1883 ConstantInt *Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
1884 if (!Mask)
1885 return false;
1886 return !Mask->getValue().isSignedIntN(12) && Mask->getValue().isPowerOf2();
1887}
1888
1890 EVT VT = Y.getValueType();
1891
1892 // FIXME: Support vectors once we have tests.
1893 if (VT.isVector())
1894 return false;
1895
1896 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) &&
1897 (!isa<ConstantSDNode>(Y) || cast<ConstantSDNode>(Y)->isOpaque());
1898}
1899
1901 // Zbs provides BEXT[_I], which can be used with SEQZ/SNEZ as a bit test.
1902 if (Subtarget.hasStdExtZbs())
1903 return X.getValueType().isScalarInteger();
1904 auto *C = dyn_cast<ConstantSDNode>(Y);
1905 // XTheadBs provides th.tst (similar to bexti), if Y is a constant
1906 if (Subtarget.hasVendorXTHeadBs())
1907 return C != nullptr;
1908 // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position.
1909 return C && C->getAPIntValue().ule(10);
1910}
1911
1913 EVT VT) const {
1914 // Only enable for rvv.
1915 if (!VT.isVector() || !Subtarget.hasVInstructions())
1916 return false;
1917
1918 if (VT.isFixedLengthVector() && !isTypeLegal(VT))
1919 return false;
1920
1921 return true;
1922}
1923
1925 Type *Ty) const {
1926 assert(Ty->isIntegerTy());
1927
1928 unsigned BitSize = Ty->getIntegerBitWidth();
1929 if (BitSize > Subtarget.getXLen())
1930 return false;
1931
1932 // Fast path, assume 32-bit immediates are cheap.
1933 int64_t Val = Imm.getSExtValue();
1934 if (isInt<32>(Val))
1935 return true;
1936
1937 // A constant pool entry may be more aligned thant he load we're trying to
1938 // replace. If we don't support unaligned scalar mem, prefer the constant
1939 // pool.
1940 // TODO: Can the caller pass down the alignment?
1941 if (!Subtarget.enableUnalignedScalarMem())
1942 return true;
1943
1944 // Prefer to keep the load if it would require many instructions.
1945 // This uses the same threshold we use for constant pools but doesn't
1946 // check useConstantPoolForLargeInts.
1947 // TODO: Should we keep the load only when we're definitely going to emit a
1948 // constant pool?
1949
1951 return Seq.size() <= Subtarget.getMaxBuildIntsCost();
1952}
1953
1957 unsigned OldShiftOpcode, unsigned NewShiftOpcode,
1958 SelectionDAG &DAG) const {
1959 // One interesting pattern that we'd want to form is 'bit extract':
1960 // ((1 >> Y) & 1) ==/!= 0
1961 // But we also need to be careful not to try to reverse that fold.
1962
1963 // Is this '((1 >> Y) & 1)'?
1964 if (XC && OldShiftOpcode == ISD::SRL && XC->isOne())
1965 return false; // Keep the 'bit extract' pattern.
1966
1967 // Will this be '((1 >> Y) & 1)' after the transform?
1968 if (NewShiftOpcode == ISD::SRL && CC->isOne())
1969 return true; // Do form the 'bit extract' pattern.
1970
1971 // If 'X' is a constant, and we transform, then we will immediately
1972 // try to undo the fold, thus causing endless combine loop.
1973 // So only do the transform if X is not a constant. This matches the default
1974 // implementation of this function.
1975 return !XC;
1976}
1977
1978bool RISCVTargetLowering::canSplatOperand(unsigned Opcode, int Operand) const {
1979 switch (Opcode) {
1980 case Instruction::Add:
1981 case Instruction::Sub:
1982 case Instruction::Mul:
1983 case Instruction::And:
1984 case Instruction::Or:
1985 case Instruction::Xor:
1986 case Instruction::FAdd:
1987 case Instruction::FSub:
1988 case Instruction::FMul:
1989 case Instruction::FDiv:
1990 case Instruction::ICmp:
1991 case Instruction::FCmp:
1992 return true;
1993 case Instruction::Shl:
1994 case Instruction::LShr:
1995 case Instruction::AShr:
1996 case Instruction::UDiv:
1997 case Instruction::SDiv:
1998 case Instruction::URem:
1999 case Instruction::SRem:
2000 case Instruction::Select:
2001 return Operand == 1;
2002 default:
2003 return false;
2004 }
2005}
2006
2007
2009 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
2010 return false;
2011
2012 if (canSplatOperand(I->getOpcode(), Operand))
2013 return true;
2014
2015 auto *II = dyn_cast<IntrinsicInst>(I);
2016 if (!II)
2017 return false;
2018
2019 switch (II->getIntrinsicID()) {
2020 case Intrinsic::fma:
2021 case Intrinsic::vp_fma:
2022 return Operand == 0 || Operand == 1;
2023 case Intrinsic::vp_shl:
2024 case Intrinsic::vp_lshr:
2025 case Intrinsic::vp_ashr:
2026 case Intrinsic::vp_udiv:
2027 case Intrinsic::vp_sdiv:
2028 case Intrinsic::vp_urem:
2029 case Intrinsic::vp_srem:
2030 case Intrinsic::ssub_sat:
2031 case Intrinsic::vp_ssub_sat:
2032 case Intrinsic::usub_sat:
2033 case Intrinsic::vp_usub_sat:
2034 return Operand == 1;
2035 // These intrinsics are commutative.
2036 case Intrinsic::vp_add:
2037 case Intrinsic::vp_mul:
2038 case Intrinsic::vp_and:
2039 case Intrinsic::vp_or:
2040 case Intrinsic::vp_xor:
2041 case Intrinsic::vp_fadd:
2042 case Intrinsic::vp_fmul:
2043 case Intrinsic::vp_icmp:
2044 case Intrinsic::vp_fcmp:
2045 case Intrinsic::smin:
2046 case Intrinsic::vp_smin:
2047 case Intrinsic::umin:
2048 case Intrinsic::vp_umin:
2049 case Intrinsic::smax:
2050 case Intrinsic::vp_smax:
2051 case Intrinsic::umax:
2052 case Intrinsic::vp_umax:
2053 case Intrinsic::sadd_sat:
2054 case Intrinsic::vp_sadd_sat:
2055 case Intrinsic::uadd_sat:
2056 case Intrinsic::vp_uadd_sat:
2057 // These intrinsics have 'vr' versions.
2058 case Intrinsic::vp_sub:
2059 case Intrinsic::vp_fsub:
2060 case Intrinsic::vp_fdiv:
2061 return Operand == 0 || Operand == 1;
2062 default:
2063 return false;
2064 }
2065}
2066
2067/// Check if sinking \p I's operands to I's basic block is profitable, because
2068/// the operands can be folded into a target instruction, e.g.
2069/// splats of scalars can fold into vector instructions.
2071 Instruction *I, SmallVectorImpl<Use *> &Ops) const {
2072 using namespace llvm::PatternMatch;
2073
2074 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
2075 return false;
2076
2077 // Don't sink splat operands if the target prefers it. Some targets requires
2078 // S2V transfer buffers and we can run out of them copying the same value
2079 // repeatedly.
2080 // FIXME: It could still be worth doing if it would improve vector register
2081 // pressure and prevent a vector spill.
2082 if (!Subtarget.sinkSplatOperands())
2083 return false;
2084
2085 for (auto OpIdx : enumerate(I->operands())) {
2086 if (!canSplatOperand(I, OpIdx.index()))
2087 continue;
2088
2089 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
2090 // Make sure we are not already sinking this operand
2091 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
2092 continue;
2093
2094 // We are looking for a splat that can be sunk.
2096 m_Undef(), m_ZeroMask())))
2097 continue;
2098
2099 // Don't sink i1 splats.
2100 if (cast<VectorType>(Op->getType())->getElementType()->isIntegerTy(1))
2101 continue;
2102
2103 // All uses of the shuffle should be sunk to avoid duplicating it across gpr
2104 // and vector registers
2105 for (Use &U : Op->uses()) {
2106 Instruction *Insn = cast<Instruction>(U.getUser());
2107 if (!canSplatOperand(Insn, U.getOperandNo()))
2108 return false;
2109 }
2110
2111 Ops.push_back(&Op->getOperandUse(0));
2112 Ops.push_back(&OpIdx.value());
2113 }
2114 return true;
2115}
2116
2118 unsigned Opc = VecOp.getOpcode();
2119
2120 // Assume target opcodes can't be scalarized.
2121 // TODO - do we have any exceptions?
2122 if (Opc >= ISD::BUILTIN_OP_END)
2123 return false;
2124
2125 // If the vector op is not supported, try to convert to scalar.
2126 EVT VecVT = VecOp.getValueType();
2127 if (!isOperationLegalOrCustomOrPromote(Opc, VecVT))
2128 return true;
2129
2130 // If the vector op is supported, but the scalar op is not, the transform may
2131 // not be worthwhile.
2132 // Permit a vector binary operation can be converted to scalar binary
2133 // operation which is custom lowered with illegal type.
2134 EVT ScalarVT = VecVT.getScalarType();
2135 return isOperationLegalOrCustomOrPromote(Opc, ScalarVT) ||
2136 isOperationCustom(Opc, ScalarVT);
2137}
2138
2140 const GlobalAddressSDNode *GA) const {
2141 // In order to maximise the opportunity for common subexpression elimination,
2142 // keep a separate ADD node for the global address offset instead of folding
2143 // it in the global address node. Later peephole optimisations may choose to
2144 // fold it back in when profitable.
2145 return false;
2146}
2147
2148// Return one of the followings:
2149// (1) `{0-31 value, false}` if FLI is available for Imm's type and FP value.
2150// (2) `{0-31 value, true}` if Imm is negative and FLI is available for its
2151// positive counterpart, which will be materialized from the first returned
2152// element. The second returned element indicated that there should be a FNEG
2153// followed.
2154// (3) `{-1, _}` if there is no way FLI can be used to materialize Imm.
2155std::pair<int, bool> RISCVTargetLowering::getLegalZfaFPImm(const APFloat &Imm,
2156 EVT VT) const {
2157 if (!Subtarget.hasStdExtZfa())
2158 return std::make_pair(-1, false);
2159
2160 bool IsSupportedVT = false;
2161 if (VT == MVT::f16) {
2162 IsSupportedVT = Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZvfh();
2163 } else if (VT == MVT::f32) {
2164 IsSupportedVT = true;
2165 } else if (VT == MVT::f64) {
2166 assert(Subtarget.hasStdExtD() && "Expect D extension");
2167 IsSupportedVT = true;
2168 }
2169
2170 if (!IsSupportedVT)
2171 return std::make_pair(-1, false);
2172
2174 if (Index < 0 && Imm.isNegative())
2175 // Try the combination of its positive counterpart + FNEG.
2176 return std::make_pair(RISCVLoadFPImm::getLoadFPImm(-Imm), true);
2177 else
2178 return std::make_pair(Index, false);
2179}
2180
2182 bool ForCodeSize) const {
2183 bool IsLegalVT = false;
2184 if (VT == MVT::f16)
2185 IsLegalVT = Subtarget.hasStdExtZfhminOrZhinxmin();
2186 else if (VT == MVT::f32)
2187 IsLegalVT = Subtarget.hasStdExtFOrZfinx();
2188 else if (VT == MVT::f64)
2189 IsLegalVT = Subtarget.hasStdExtDOrZdinx();
2190 else if (VT == MVT::bf16)
2191 IsLegalVT = Subtarget.hasStdExtZfbfmin();
2192
2193 if (!IsLegalVT)
2194 return false;
2195
2196 if (getLegalZfaFPImm(Imm, VT).first >= 0)
2197 return true;
2198
2199 // Cannot create a 64 bit floating-point immediate value for rv32.
2200 if (Subtarget.getXLen() < VT.getScalarSizeInBits()) {
2201 // td can handle +0.0 or -0.0 already.
2202 // -0.0 can be created by fmv + fneg.
2203 return Imm.isZero();
2204 }
2205
2206 // Special case: fmv + fneg
2207 if (Imm.isNegZero())
2208 return true;
2209
2210 // Building an integer and then converting requires a fmv at the end of
2211 // the integer sequence.
2212 const int Cost =
2213 1 + RISCVMatInt::getIntMatCost(Imm.bitcastToAPInt(), Subtarget.getXLen(),
2214 Subtarget);
2215 return Cost <= FPImmCost;
2216}
2217
2218// TODO: This is very conservative.
2220 unsigned Index) const {
2222 return false;
2223
2224 // Only support extracting a fixed from a fixed vector for now.
2225 if (ResVT.isScalableVector() || SrcVT.isScalableVector())
2226 return false;
2227
2228 EVT EltVT = ResVT.getVectorElementType();
2229 assert(EltVT == SrcVT.getVectorElementType() && "Should hold for node");
2230
2231 // The smallest type we can slide is i8.
2232 // TODO: We can extract index 0 from a mask vector without a slide.
2233 if (EltVT == MVT::i1)
2234 return false;
2235
2236 unsigned ResElts = ResVT.getVectorNumElements();
2237 unsigned SrcElts = SrcVT.getVectorNumElements();
2238
2239 unsigned MinVLen = Subtarget.getRealMinVLen();
2240 unsigned MinVLMAX = MinVLen / EltVT.getSizeInBits();
2241
2242 // If we're extracting only data from the first VLEN bits of the source
2243 // then we can always do this with an m1 vslidedown.vx. Restricting the
2244 // Index ensures we can use a vslidedown.vi.
2245 // TODO: We can generalize this when the exact VLEN is known.
2246 if (Index + ResElts <= MinVLMAX && Index < 31)
2247 return true;
2248
2249 // Convervatively only handle extracting half of a vector.
2250 // TODO: For sizes which aren't multiples of VLEN sizes, this may not be
2251 // a cheap extract. However, this case is important in practice for
2252 // shuffled extracts of longer vectors. How resolve?
2253 if ((ResElts * 2) != SrcElts)
2254 return false;
2255
2256 // Slide can support arbitrary index, but we only treat vslidedown.vi as
2257 // cheap.
2258 if (Index >= 32)
2259 return false;
2260
2261 // TODO: We can do arbitrary slidedowns, but for now only support extracting
2262 // the upper half of a vector until we have more test coverage.
2263 return Index == 0 || Index == ResElts;
2264}
2265
2268 EVT VT) const {
2269 // Use f32 to pass f16 if it is legal and Zfh/Zfhmin is not enabled.
2270 // We might still end up using a GPR but that will be decided based on ABI.
2271 if (VT == MVT::f16 && Subtarget.hasStdExtFOrZfinx() &&
2272 !Subtarget.hasStdExtZfhminOrZhinxmin())
2273 return MVT::f32;
2274
2276
2277 return PartVT;
2278}
2279
2282 EVT VT) const {
2283 // Use f32 to pass f16 if it is legal and Zfh/Zfhmin is not enabled.
2284 // We might still end up using a GPR but that will be decided based on ABI.
2285 if (VT == MVT::f16 && Subtarget.hasStdExtFOrZfinx() &&
2286 !Subtarget.hasStdExtZfhminOrZhinxmin())
2287 return 1;
2288
2290}
2291
2293 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
2294 unsigned &NumIntermediates, MVT &RegisterVT) const {
2296 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
2297
2298 return NumRegs;
2299}
2300
2301// Changes the condition code and swaps operands if necessary, so the SetCC
2302// operation matches one of the comparisons supported directly by branches
2303// in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
2304// with 1/-1.
2305static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
2306 ISD::CondCode &CC, SelectionDAG &DAG) {
2307 // If this is a single bit test that can't be handled by ANDI, shift the
2308 // bit to be tested to the MSB and perform a signed compare with 0.
2309 if (isIntEqualitySetCC(CC) && isNullConstant(RHS) &&
2310 LHS.getOpcode() == ISD::AND && LHS.hasOneUse() &&
2311 isa<ConstantSDNode>(LHS.getOperand(1))) {
2312 uint64_t Mask = LHS.getConstantOperandVal(1);
2313 if ((isPowerOf2_64(Mask) || isMask_64(Mask)) && !isInt<12>(Mask)) {
2314 unsigned ShAmt = 0;
2315 if (isPowerOf2_64(Mask)) {
2317 ShAmt = LHS.getValueSizeInBits() - 1 - Log2_64(Mask);
2318 } else {
2319 ShAmt = LHS.getValueSizeInBits() - llvm::bit_width(Mask);
2320 }
2321
2322 LHS = LHS.getOperand(0);
2323 if (ShAmt != 0)
2324 LHS = DAG.getNode(ISD::SHL, DL, LHS.getValueType(), LHS,
2325 DAG.getConstant(ShAmt, DL, LHS.getValueType()));
2326 return;
2327 }
2328 }
2329
2330 if (auto *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2331 int64_t C = RHSC->getSExtValue();
2332 switch (CC) {
2333 default: break;
2334 case ISD::SETGT:
2335 // Convert X > -1 to X >= 0.
2336 if (C == -1) {
2337 RHS = DAG.getConstant(0, DL, RHS.getValueType());
2338 CC = ISD::SETGE;
2339 return;
2340 }
2341 break;
2342 case ISD::SETLT:
2343 // Convert X < 1 to 0 >= X.
2344 if (C == 1) {
2345 RHS = LHS;
2346 LHS = DAG.getConstant(0, DL, RHS.getValueType());
2347 CC = ISD::SETGE;
2348 return;
2349 }
2350 break;
2351 }
2352 }
2353
2354 switch (CC) {
2355 default:
2356 break;
2357 case ISD::SETGT:
2358 case ISD::SETLE:
2359 case ISD::SETUGT:
2360 case ISD::SETULE:
2362 std::swap(LHS, RHS);
2363 break;
2364 }
2365}
2366
2368 assert(VT.isScalableVector() && "Expecting a scalable vector type");
2369 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
2370 if (VT.getVectorElementType() == MVT::i1)
2371 KnownSize *= 8;
2372
2373 switch (KnownSize) {
2374 default:
2375 llvm_unreachable("Invalid LMUL.");
2376 case 8:
2378 case 16:
2380 case 32:
2382 case 64:
2384 case 128:
2386 case 256:
2388 case 512:
2390 }
2391}
2392
2394 switch (LMul) {
2395 default:
2396 llvm_unreachable("Invalid LMUL.");
2401 return RISCV::VRRegClassID;
2403 return RISCV::VRM2RegClassID;
2405 return RISCV::VRM4RegClassID;
2407 return RISCV::VRM8RegClassID;
2408 }
2409}
2410
2412 RISCVII::VLMUL LMUL = getLMUL(VT);
2413 if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
2414 LMUL == RISCVII::VLMUL::LMUL_F4 ||
2415 LMUL == RISCVII::VLMUL::LMUL_F2 ||
2416 LMUL == RISCVII::VLMUL::LMUL_1) {
2417 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
2418 "Unexpected subreg numbering");
2419 return RISCV::sub_vrm1_0 + Index;
2420 }
2421 if (LMUL == RISCVII::VLMUL::LMUL_2) {
2422 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
2423 "Unexpected subreg numbering");
2424 return RISCV::sub_vrm2_0 + Index;
2425 }
2426 if (LMUL == RISCVII::VLMUL::LMUL_4) {
2427 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
2428 "Unexpected subreg numbering");
2429 return RISCV::sub_vrm4_0 + Index;
2430 }
2431 llvm_unreachable("Invalid vector type.");
2432}
2433
2435 if (VT.getVectorElementType() == MVT::i1)
2436 return RISCV::VRRegClassID;
2437 return getRegClassIDForLMUL(getLMUL(VT));
2438}
2439
2440// Attempt to decompose a subvector insert/extract between VecVT and
2441// SubVecVT via subregister indices. Returns the subregister index that
2442// can perform the subvector insert/extract with the given element index, as
2443// well as the index corresponding to any leftover subvectors that must be
2444// further inserted/extracted within the register class for SubVecVT.
2445std::pair<unsigned, unsigned>
2447 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
2448 const RISCVRegisterInfo *TRI) {
2449 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
2450 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
2451 RISCV::VRM2RegClassID > RISCV::VRRegClassID),
2452 "Register classes not ordered");
2453 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
2454 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
2455 // Try to compose a subregister index that takes us from the incoming
2456 // LMUL>1 register class down to the outgoing one. At each step we half
2457 // the LMUL:
2458 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
2459 // Note that this is not guaranteed to find a subregister index, such as
2460 // when we are extracting from one VR type to another.
2461 unsigned SubRegIdx = RISCV::NoSubRegister;
2462 for (const unsigned RCID :
2463 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
2464 if (VecRegClassID > RCID && SubRegClassID <= RCID) {
2465 VecVT = VecVT.getHalfNumVectorElementsVT();
2466 bool IsHi =
2467 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
2468 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
2469 getSubregIndexByMVT(VecVT, IsHi));
2470 if (IsHi)
2471 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
2472 }
2473 return {SubRegIdx, InsertExtractIdx};
2474}
2475
2476// Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
2477// stores for those types.
2478bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
2479 return !Subtarget.useRVVForFixedLengthVectors() ||
2480 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
2481}
2482
2484 if (!ScalarTy.isSimple())
2485 return false;
2486 switch (ScalarTy.getSimpleVT().SimpleTy) {
2487 case MVT::iPTR:
2488 return Subtarget.is64Bit() ? Subtarget.hasVInstructionsI64() : true;
2489 case MVT::i8:
2490 case MVT::i16:
2491 case MVT::i32:
2492 return true;
2493 case MVT::i64:
2494 return Subtarget.hasVInstructionsI64();
2495 case MVT::f16:
2496 return Subtarget.hasVInstructionsF16();
2497 case MVT::f32:
2498 return Subtarget.hasVInstructionsF32();
2499 case MVT::f64:
2500 return Subtarget.hasVInstructionsF64();
2501 default:
2502 return false;
2503 }
2504}
2505
2506
2507unsigned RISCVTargetLowering::combineRepeatedFPDivisors() const {
2508 return NumRepeatedDivisors;
2509}
2510
2512 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2513 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
2514 "Unexpected opcode");
2515 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
2516 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
2518 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
2519 if (!II)
2520 return SDValue();
2521 return Op.getOperand(II->VLOperand + 1 + HasChain);
2522}
2523
2525 const RISCVSubtarget &Subtarget) {
2526 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
2527 if (!Subtarget.useRVVForFixedLengthVectors())
2528 return false;
2529
2530 // We only support a set of vector types with a consistent maximum fixed size
2531 // across all supported vector element types to avoid legalization issues.
2532 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
2533 // fixed-length vector type we support is 1024 bytes.
2534 if (VT.getFixedSizeInBits() > 1024 * 8)
2535 return false;
2536
2537 unsigned MinVLen = Subtarget.getRealMinVLen();
2538
2539 MVT EltVT = VT.getVectorElementType();
2540
2541 // Don't use RVV for vectors we cannot scalarize if required.
2542 switch (EltVT.SimpleTy) {
2543 // i1 is supported but has different rules.
2544 default:
2545 return false;
2546 case MVT::i1:
2547 // Masks can only use a single register.
2548 if (VT.getVectorNumElements() > MinVLen)
2549 return false;
2550 MinVLen /= 8;
2551 break;
2552 case MVT::i8:
2553 case MVT::i16:
2554 case MVT::i32:
2555 break;
2556 case MVT::i64:
2557 if (!Subtarget.hasVInstructionsI64())
2558 return false;
2559 break;
2560 case MVT::f16:
2561 if (!Subtarget.hasVInstructionsF16Minimal())
2562 return false;
2563 break;
2564 case MVT::bf16:
2565 if (!Subtarget.hasVInstructionsBF16Minimal())
2566 return false;
2567 break;
2568 case MVT::f32:
2569 if (!Subtarget.hasVInstructionsF32())
2570 return false;
2571 break;
2572 case MVT::f64:
2573 if (!Subtarget.hasVInstructionsF64())
2574 return false;
2575 break;
2576 }
2577
2578 // Reject elements larger than ELEN.
2579 if (EltVT.getSizeInBits() > Subtarget.getELen())
2580 return false;
2581
2582 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
2583 // Don't use RVV for types that don't fit.
2584 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
2585 return false;
2586
2587 // TODO: Perhaps an artificial restriction, but worth having whilst getting
2588 // the base fixed length RVV support in place.
2589 if (!VT.isPow2VectorType())
2590 return false;
2591
2592 return true;
2593}
2594
2595bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
2596 return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
2597}
2598
2599// Return the largest legal scalable vector type that matches VT's element type.
2601 const RISCVSubtarget &Subtarget) {
2602 // This may be called before legal types are setup.
2603 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
2604 useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
2605 "Expected legal fixed length vector!");
2606
2607 unsigned MinVLen = Subtarget.getRealMinVLen();
2608 unsigned MaxELen = Subtarget.getELen();
2609
2610 MVT EltVT = VT.getVectorElementType();
2611 switch (EltVT.SimpleTy) {
2612 default:
2613 llvm_unreachable("unexpected element type for RVV container");
2614 case MVT::i1:
2615 case MVT::i8:
2616 case MVT::i16:
2617 case MVT::i32:
2618 case MVT::i64:
2619 case MVT::bf16:
2620 case MVT::f16:
2621 case MVT::f32:
2622 case MVT::f64: {
2623 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
2624 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
2625 // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
2626 unsigned NumElts =
2628 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
2629 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
2630 return MVT::getScalableVectorVT(EltVT, NumElts);
2631 }
2632 }
2633}
2634
2636 const RISCVSubtarget &Subtarget) {
2638 Subtarget);
2639}
2640
2642 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
2643}
2644
2645// Grow V to consume an entire RVV register.
2647 const RISCVSubtarget &Subtarget) {
2648 assert(VT.isScalableVector() &&
2649 "Expected to convert into a scalable vector!");
2650 assert(V.getValueType().isFixedLengthVector() &&
2651 "Expected a fixed length vector operand!");
2652 SDLoc DL(V);
2653 SDValue Zero = DAG.getVectorIdxConstant(0, DL);
2654 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
2655}
2656
2657// Shrink V so it's just big enough to maintain a VT's worth of data.
2659 const RISCVSubtarget &Subtarget) {
2661 "Expected to convert into a fixed length vector!");
2662 assert(V.getValueType().isScalableVector() &&
2663 "Expected a scalable vector operand!");
2664 SDLoc DL(V);
2665 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
2666 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
2667}
2668
2669/// Return the type of the mask type suitable for masking the provided
2670/// vector type. This is simply an i1 element type vector of the same
2671/// (possibly scalable) length.
2672static MVT getMaskTypeFor(MVT VecVT) {
2673 assert(VecVT.isVector());
2675 return MVT::getVectorVT(MVT::i1, EC);
2676}
2677
2678/// Creates an all ones mask suitable for masking a vector of type VecTy with
2679/// vector length VL. .
2680static SDValue getAllOnesMask(MVT VecVT, SDValue VL, const SDLoc &DL,
2681 SelectionDAG &DAG) {
2682 MVT MaskVT = getMaskTypeFor(VecVT);
2683 return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2684}
2685
2686static std::pair<SDValue, SDValue>
2688 const RISCVSubtarget &Subtarget) {
2689 assert(VecVT.isScalableVector() && "Expecting a scalable vector");
2690 SDValue VL = DAG.getRegister(RISCV::X0, Subtarget.getXLenVT());
2691 SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG);
2692 return {Mask, VL};
2693}
2694
2695static std::pair<SDValue, SDValue>
2696getDefaultVLOps(uint64_t NumElts, MVT ContainerVT, const SDLoc &DL,
2697 SelectionDAG &DAG, const RISCVSubtarget &Subtarget) {
2698 assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
2699 SDValue VL = DAG.getConstant(NumElts, DL, Subtarget.getXLenVT());
2700 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
2701 return {Mask, VL};
2702}
2703
2704// Gets the two common "VL" operands: an all-ones mask and the vector length.
2705// VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
2706// the vector type that the fixed-length vector is contained in. Otherwise if
2707// VecVT is scalable, then ContainerVT should be the same as VecVT.
2708static std::pair<SDValue, SDValue>
2709getDefaultVLOps(MVT VecVT, MVT ContainerVT, const SDLoc &DL, SelectionDAG &DAG,
2710 const RISCVSubtarget &Subtarget) {
2711 if (VecVT.isFixedLengthVector())
2712 return getDefaultVLOps(VecVT.getVectorNumElements(), ContainerVT, DL, DAG,
2713 Subtarget);
2714 assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
2715 return getDefaultScalableVLOps(ContainerVT, DL, DAG, Subtarget);
2716}
2717
2719 SelectionDAG &DAG) const {
2720 assert(VecVT.isScalableVector() && "Expected scalable vector");
2721 return DAG.getElementCount(DL, Subtarget.getXLenVT(),
2722 VecVT.getVectorElementCount());
2723}
2724
2725std::pair<unsigned, unsigned>
2727 const RISCVSubtarget &Subtarget) {
2728 assert(VecVT.isScalableVector() && "Expected scalable vector");
2729
2730 unsigned EltSize = VecVT.getScalarSizeInBits();
2731 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
2732
2733 unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
2734 unsigned MaxVLMAX =
2735 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
2736
2737 unsigned VectorBitsMin = Subtarget.getRealMinVLen();
2738 unsigned MinVLMAX =
2739 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize);
2740
2741 return std::make_pair(MinVLMAX, MaxVLMAX);
2742}
2743
2744// The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
2745// of either is (currently) supported. This can get us into an infinite loop
2746// where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
2747// as a ..., etc.
2748// Until either (or both) of these can reliably lower any node, reporting that
2749// we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
2750// the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
2751// which is not desirable.
2753 EVT VT, unsigned DefinedValues) const {
2754 return false;
2755}
2756
2758 // TODO: Here assume reciprocal throughput is 1 for LMUL_1, it is
2759 // implementation-defined.
2760 if (!VT.isVector())
2762 unsigned DLenFactor = Subtarget.getDLenFactor();
2763 unsigned Cost;
2764 if (VT.isScalableVector()) {
2765 unsigned LMul;
2766 bool Fractional;
2767 std::tie(LMul, Fractional) =
2769 if (Fractional)
2770 Cost = LMul <= DLenFactor ? (DLenFactor / LMul) : 1;
2771 else
2772 Cost = (LMul * DLenFactor);
2773 } else {
2774 Cost = divideCeil(VT.getSizeInBits(), Subtarget.getRealMinVLen() / DLenFactor);
2775 }
2776 return Cost;
2777}
2778
2779
2780/// Return the cost of a vrgather.vv instruction for the type VT. vrgather.vv
2781/// is generally quadratic in the number of vreg implied by LMUL. Note that
2782/// operand (index and possibly mask) are handled separately.
2784 return getLMULCost(VT) * getLMULCost(VT);
2785}
2786
2787/// Return the cost of a vrgather.vi (or vx) instruction for the type VT.
2788/// vrgather.vi/vx may be linear in the number of vregs implied by LMUL,
2789/// or may track the vrgather.vv cost. It is implementation-dependent.
2791 return getLMULCost(VT);
2792}
2793
2794/// Return the cost of a vslidedown.vx or vslideup.vx instruction
2795/// for the type VT. (This does not cover the vslide1up or vslide1down
2796/// variants.) Slides may be linear in the number of vregs implied by LMUL,
2797/// or may track the vrgather.vv cost. It is implementation-dependent.
2799 return getLMULCost(VT);
2800}
2801
2802/// Return the cost of a vslidedown.vi or vslideup.vi instruction
2803/// for the type VT. (This does not cover the vslide1up or vslide1down
2804/// variants.) Slides may be linear in the number of vregs implied by LMUL,
2805/// or may track the vrgather.vv cost. It is implementation-dependent.
2807 return getLMULCost(VT);
2808}
2809
2811 const RISCVSubtarget &Subtarget) {
2812 // RISC-V FP-to-int conversions saturate to the destination register size, but
2813 // don't produce 0 for nan. We can use a conversion instruction and fix the
2814 // nan case with a compare and a select.
2815 SDValue Src = Op.getOperand(0);
2816
2817 MVT DstVT = Op.getSimpleValueType();
2818 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2819
2820 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
2821
2822 if (!DstVT.isVector()) {
2823 // For bf16 or for f16 in absense of Zfh, promote to f32, then saturate
2824 // the result.
2825 if ((Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfhOrZhinx()) ||
2826 Src.getValueType() == MVT::bf16) {
2827 Src = DAG.getNode(ISD::FP_EXTEND, SDLoc(Op), MVT::f32, Src);
2828 }
2829
2830 unsigned Opc;
2831 if (SatVT == DstVT)
2832 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
2833 else if (DstVT == MVT::i64 && SatVT == MVT::i32)
2835 else
2836 return SDValue();
2837 // FIXME: Support other SatVTs by clamping before or after the conversion.
2838
2839 SDLoc DL(Op);
2840 SDValue FpToInt = DAG.getNode(
2841 Opc, DL, DstVT, Src,
2843
2844 if (Opc == RISCVISD::FCVT_WU_RV64)
2845 FpToInt = DAG.getZeroExtendInReg(FpToInt, DL, MVT::i32);
2846
2847 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
2848 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt,
2850 }
2851
2852 // Vectors.
2853
2854 MVT DstEltVT = DstVT.getVectorElementType();
2855 MVT SrcVT = Src.getSimpleValueType();
2856 MVT SrcEltVT = SrcVT.getVectorElementType();
2857 unsigned SrcEltSize = SrcEltVT.getSizeInBits();
2858 unsigned DstEltSize = DstEltVT.getSizeInBits();
2859
2860 // Only handle saturating to the destination type.
2861 if (SatVT != DstEltVT)
2862 return SDValue();
2863
2864 MVT DstContainerVT = DstVT;
2865 MVT SrcContainerVT = SrcVT;
2866 if (DstVT.isFixedLengthVector()) {
2867 DstContainerVT = getContainerForFixedLengthVector(DAG, DstVT, Subtarget);
2868 SrcContainerVT = getContainerForFixedLengthVector(DAG, SrcVT, Subtarget);
2869 assert(DstContainerVT.getVectorElementCount() ==
2870 SrcContainerVT.getVectorElementCount() &&
2871 "Expected same element count");
2872 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2873 }
2874
2875 SDLoc DL(Op);
2876
2877 auto [Mask, VL] = getDefaultVLOps(DstVT, DstContainerVT, DL, DAG, Subtarget);
2878
2879 SDValue IsNan = DAG.getNode(RISCVISD::SETCC_VL, DL, Mask.getValueType(),
2880 {Src, Src, DAG.getCondCode(ISD::SETNE),
2881 DAG.getUNDEF(Mask.getValueType()), Mask, VL});
2882
2883 // Need to widen by more than 1 step, promote the FP type, then do a widening
2884 // convert.
2885 if (DstEltSize > (2 * SrcEltSize)) {
2886 assert(SrcContainerVT.getVectorElementType() == MVT::f16 && "Unexpected VT!");
2887 MVT InterVT = SrcContainerVT.changeVectorElementType(MVT::f32);
2888 Src = DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterVT, Src, Mask, VL);
2889 }
2890
2891 MVT CvtContainerVT = DstContainerVT;
2892 MVT CvtEltVT = DstEltVT;
2893 if (SrcEltSize > (2 * DstEltSize)) {
2894 CvtEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
2895 CvtContainerVT = CvtContainerVT.changeVectorElementType(CvtEltVT);
2896 }
2897
2898 unsigned RVVOpc =
2900 SDValue Res = DAG.getNode(RVVOpc, DL, CvtContainerVT, Src, Mask, VL);
2901
2902 while (CvtContainerVT != DstContainerVT) {
2903 CvtEltVT = MVT::getIntegerVT(CvtEltVT.getSizeInBits() / 2);
2904 CvtContainerVT = CvtContainerVT.changeVectorElementType(CvtEltVT);
2905 // Rounding mode here is arbitrary since we aren't shifting out any bits.
2906 unsigned ClipOpc = IsSigned ? RISCVISD::TRUNCATE_VECTOR_VL_SSAT
2908 Res = DAG.getNode(ClipOpc, DL, CvtContainerVT, Res, Mask, VL);
2909 }
2910
2911 SDValue SplatZero = DAG.getNode(
2912 RISCVISD::VMV_V_X_VL, DL, DstContainerVT, DAG.getUNDEF(DstContainerVT),
2913 DAG.getConstant(0, DL, Subtarget.getXLenVT()), VL);
2914 Res = DAG.getNode(RISCVISD::VMERGE_VL, DL, DstContainerVT, IsNan, SplatZero,
2915 Res, DAG.getUNDEF(DstContainerVT), VL);
2916
2917 if (DstVT.isFixedLengthVector())
2918 Res = convertFromScalableVector(DstVT, Res, DAG, Subtarget);
2919
2920 return Res;
2921}
2922
2924 switch (Opc) {
2925 case ISD::FROUNDEVEN:
2927 case ISD::VP_FROUNDEVEN:
2928 return RISCVFPRndMode::RNE;
2929 case ISD::FTRUNC:
2930 case ISD::STRICT_FTRUNC:
2931 case ISD::VP_FROUNDTOZERO:
2932 return RISCVFPRndMode::RTZ;
2933 case ISD::FFLOOR:
2934 case ISD::STRICT_FFLOOR:
2935 case ISD::VP_FFLOOR:
2936 return RISCVFPRndMode::RDN;
2937 case ISD::FCEIL:
2938 case ISD::STRICT_FCEIL:
2939 case ISD::VP_FCEIL:
2940 return RISCVFPRndMode::RUP;
2941 case ISD::FROUND:
2942 case ISD::STRICT_FROUND:
2943 case ISD::VP_FROUND:
2944 return RISCVFPRndMode::RMM;
2945 case ISD::FRINT:
2946 return RISCVFPRndMode::DYN;
2947 }
2948
2950}
2951
2952// Expand vector FTRUNC, FCEIL, FFLOOR, FROUND, VP_FCEIL, VP_FFLOOR, VP_FROUND
2953// VP_FROUNDEVEN, VP_FROUNDTOZERO, VP_FRINT and VP_FNEARBYINT by converting to
2954// the integer domain and back. Taking care to avoid converting values that are
2955// nan or already correct.
2956static SDValue
2958 const RISCVSubtarget &Subtarget) {
2959 MVT VT = Op.getSimpleValueType();
2960 assert(VT.isVector() && "Unexpected type");
2961
2962 SDLoc DL(Op);
2963
2964 SDValue Src = Op.getOperand(0);
2965
2966 MVT ContainerVT = VT;
2967 if (VT.isFixedLengthVector()) {
2968 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2969 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
2970 }
2971
2972 SDValue Mask, VL;
2973 if (Op->isVPOpcode()) {
2974 Mask = Op.getOperand(1);
2975 if (VT.isFixedLengthVector())
2976 Mask = convertToScalableVector(getMaskTypeFor(ContainerVT), Mask, DAG,
2977 Subtarget);
2978 VL = Op.getOperand(2);
2979 } else {
2980 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2981 }
2982
2983 // Freeze the source since we are increasing the number of uses.
2984 Src = DAG.getFreeze(Src);
2985
2986 // We do the conversion on the absolute value and fix the sign at the end.
2987 SDValue Abs = DAG.getNode(RISCVISD::FABS_VL, DL, ContainerVT, Src, Mask, VL);
2988
2989 // Determine the largest integer that can be represented exactly. This and
2990 // values larger than it don't have any fractional bits so don't need to
2991 // be converted.
2992 const fltSemantics &FltSem = ContainerVT.getFltSemantics();
2993 unsigned Precision = APFloat::semanticsPrecision(FltSem);
2994 APFloat MaxVal = APFloat(FltSem);
2995 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
2996 /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
2997 SDValue MaxValNode =
2998 DAG.getConstantFP(MaxVal, DL, ContainerVT.getVectorElementType());
2999 SDValue MaxValSplat = DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, ContainerVT,
3000 DAG.getUNDEF(ContainerVT), MaxValNode, VL);
3001
3002 // If abs(Src) was larger than MaxVal or nan, keep it.
3003 MVT SetccVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3004 Mask =
3005 DAG.getNode(RISCVISD::SETCC_VL, DL, SetccVT,
3006 {Abs, MaxValSplat, DAG.getCondCode(ISD::SETOLT),
3007 Mask, Mask, VL});
3008
3009 // Truncate to integer and convert back to FP.
3010 MVT IntVT = ContainerVT.changeVectorElementTypeToInteger();
3011 MVT XLenVT = Subtarget.getXLenVT();
3012 SDValue Truncated;
3013
3014 switch (Op.getOpcode()) {
3015 default:
3016 llvm_unreachable("Unexpected opcode");
3017 case ISD::FCEIL:
3018 case ISD::VP_FCEIL:
3019 case ISD::FFLOOR:
3020 case ISD::VP_FFLOOR:
3021 case ISD::FROUND:
3022 case ISD::FROUNDEVEN:
3023 case ISD::VP_FROUND:
3024 case ISD::VP_FROUNDEVEN:
3025 case ISD::VP_FROUNDTOZERO: {
3028 Truncated = DAG.getNode(RISCVISD::VFCVT_RM_X_F_VL, DL, IntVT, Src, Mask,
3029 DAG.getTargetConstant(FRM, DL, XLenVT), VL);
3030 break;
3031 }
3032 case ISD::FTRUNC:
3033 Truncated = DAG.getNode(RISCVISD::VFCVT_RTZ_X_F_VL, DL, IntVT, Src,
3034 Mask, VL);
3035 break;
3036 case ISD::FRINT:
3037 case ISD::VP_FRINT:
3038 Truncated = DAG.getNode(RISCVISD::VFCVT_X_F_VL, DL, IntVT, Src, Mask, VL);
3039 break;
3040 case ISD::FNEARBYINT:
3041 case ISD::VP_FNEARBYINT:
3042 Truncated = DAG.getNode(RISCVISD::VFROUND_NOEXCEPT_VL, DL, ContainerVT, Src,
3043 Mask, VL);
3044 break;
3045 }
3046
3047 // VFROUND_NOEXCEPT_VL includes SINT_TO_FP_VL.
3048 if (Truncated.getOpcode() != RISCVISD::VFROUND_NOEXCEPT_VL)
3049 Truncated = DAG.getNode(RISCVISD::SINT_TO_FP_VL, DL, ContainerVT, Truncated,
3050 Mask, VL);
3051
3052 // Restore the original sign so that -0.0 is preserved.
3053 Truncated = DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Truncated,
3054 Src, Src, Mask, VL);
3055
3056 if (!VT.isFixedLengthVector())
3057 return Truncated;
3058
3059 return convertFromScalableVector(VT, Truncated, DAG, Subtarget);
3060}
3061
3062// Expand vector STRICT_FTRUNC, STRICT_FCEIL, STRICT_FFLOOR, STRICT_FROUND
3063// STRICT_FROUNDEVEN and STRICT_FNEARBYINT by converting sNan of the source to
3064// qNan and coverting the new source to integer and back to FP.
3065static SDValue
3067 const RISCVSubtarget &Subtarget) {
3068 SDLoc DL(Op);
3069 MVT VT = Op.getSimpleValueType();
3070 SDValue Chain = Op.getOperand(0);
3071 SDValue Src = Op.getOperand(1);
3072
3073 MVT ContainerVT = VT;
3074 if (VT.isFixedLengthVector()) {
3075 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
3076 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3077 }
3078
3079 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3080
3081 // Freeze the source since we are increasing the number of uses.
3082 Src = DAG.getFreeze(Src);
3083
3084 // Covert sNan to qNan by executing x + x for all unordered elemenet x in Src.
3085 MVT MaskVT = Mask.getSimpleValueType();
3087 DAG.getVTList(MaskVT, MVT::Other),
3088 {Chain, Src, Src, DAG.getCondCode(ISD::SETUNE),
3089 DAG.getUNDEF(MaskVT), Mask, VL});
3090 Chain = Unorder.getValue(1);
3092 DAG.getVTList(ContainerVT, MVT::Other),
3093 {Chain, Src, Src, Src, Unorder, VL});
3094 Chain = Src.getValue(1);
3095
3096 // We do the conversion on the absolute value and fix the sign at the end.
3097 SDValue Abs = DAG.getNode(RISCVISD::FABS_VL, DL, ContainerVT, Src, Mask, VL);
3098
3099 // Determine the largest integer that can be represented exactly. This and
3100 // values larger than it don't have any fractional bits so don't need to
3101 // be converted.
3102 const fltSemantics &FltSem = ContainerVT.getFltSemantics();
3103 unsigned Precision = APFloat::semanticsPrecision(FltSem);
3104 APFloat MaxVal = APFloat(FltSem);
3105 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
3106 /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
3107 SDValue MaxValNode =
3108 DAG.getConstantFP(MaxVal, DL, ContainerVT.getVectorElementType());
3109 SDValue MaxValSplat = DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, ContainerVT,
3110 DAG.getUNDEF(ContainerVT), MaxValNode, VL);
3111
3112 // If abs(Src) was larger than MaxVal or nan, keep it.
3113 Mask = DAG.getNode(
3114 RISCVISD::SETCC_VL, DL, MaskVT,
3115 {Abs, MaxValSplat, DAG.getCondCode(ISD::SETOLT), Mask, Mask, VL});
3116
3117 // Truncate to integer and convert back to FP.
3118 MVT IntVT = ContainerVT.changeVectorElementTypeToInteger();
3119 MVT XLenVT = Subtarget.getXLenVT();
3120 SDValue Truncated;
3121
3122 switch (Op.getOpcode()) {
3123 default:
3124 llvm_unreachable("Unexpected opcode");
3125 case ISD::STRICT_FCEIL:
3126 case ISD::STRICT_FFLOOR:
3127 case ISD::STRICT_FROUND:
3131 Truncated = DAG.getNode(
3132 RISCVISD::STRICT_VFCVT_RM_X_F_VL, DL, DAG.getVTList(IntVT, MVT::Other),
3133 {Chain, Src, Mask, DAG.getTargetConstant(FRM, DL, XLenVT), VL});
3134 break;
3135 }
3136 case ISD::STRICT_FTRUNC:
3137 Truncated =
3139 DAG.getVTList(IntVT, MVT::Other), Chain, Src, Mask, VL);
3140 break;
3143 DAG.getVTList(ContainerVT, MVT::Other), Chain, Src,
3144 Mask, VL);
3145 break;
3146 }
3147 Chain = Truncated.getValue(1);
3148
3149 // VFROUND_NOEXCEPT_VL includes SINT_TO_FP_VL.
3150 if (Op.getOpcode() != ISD::STRICT_FNEARBYINT) {
3151 Truncated = DAG.getNode(RISCVISD::STRICT_SINT_TO_FP_VL, DL,
3152 DAG.getVTList(ContainerVT, MVT::Other), Chain,
3153 Truncated, Mask, VL);
3154 Chain = Truncated.getValue(1);
3155 }
3156
3157 // Restore the original sign so that -0.0 is preserved.
3158 Truncated = DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Truncated,
3159 Src, Src, Mask, VL);
3160
3161 if (VT.isFixedLengthVector())
3162 Truncated = convertFromScalableVector(VT, Truncated, DAG, Subtarget);
3163 return DAG.getMergeValues({Truncated, Chain}, DL);
3164}
3165
3166static SDValue
3168 const RISCVSubtarget &Subtarget) {
3169 MVT VT = Op.getSimpleValueType();
3170 if (VT.isVector())
3171 return lowerVectorFTRUNC_FCEIL_FFLOOR_FROUND(Op, DAG, Subtarget);
3172
3173 if (DAG.shouldOptForSize())
3174 return SDValue();
3175
3176 SDLoc DL(Op);
3177 SDValue Src = Op.getOperand(0);
3178
3179 // Create an integer the size of the mantissa with the MSB set. This and all
3180 // values larger than it don't have any fractional bits so don't need to be
3181 // converted.
3182 const fltSemantics &FltSem = VT.getFltSemantics();
3183 unsigned Precision = APFloat::semanticsPrecision(FltSem);
3184 APFloat MaxVal = APFloat(FltSem);
3185 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
3186 /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
3187 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
3188
3190 return DAG.getNode(RISCVISD::FROUND, DL, VT, Src, MaxValNode,
3191 DAG.getTargetConstant(FRM, DL, Subtarget.getXLenVT()));
3192}
3193
3194// Expand vector LRINT and LLRINT by converting to the integer domain.
3196 const RISCVSubtarget &Subtarget) {
3197 MVT VT = Op.getSimpleValueType();
3198 assert(VT.isVector() && "Unexpected type");
3199
3200 SDLoc DL(Op);
3201 SDValue Src = Op.getOperand(0);
3202 MVT ContainerVT = VT;
3203
3204 if (VT.isFixedLengthVector()) {
3205 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
3206 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3207 }
3208
3209 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3210 SDValue Truncated =
3211 DAG.getNode(RISCVISD::VFCVT_X_F_VL, DL, ContainerVT, Src, Mask, VL);
3212
3213 if (!VT.isFixedLengthVector())
3214 return Truncated;
3215
3216 return convertFromScalableVector(VT, Truncated, DAG, Subtarget);
3217}
3218
3219static SDValue
3221 const SDLoc &DL, EVT VT, SDValue Passthru, SDValue Op,
3222 SDValue Offset, SDValue Mask, SDValue VL,
3224 if (Passthru.isUndef())
3226 SDValue PolicyOp = DAG.getTargetConstant(Policy, DL, Subtarget.getXLenVT());
3227 SDValue Ops[] = {Passthru, Op, Offset, Mask, VL, PolicyOp};
3228 return DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VT, Ops);
3229}
3230
3231static SDValue
3232getVSlideup(SelectionDAG &DAG, const RISCVSubtarget &Subtarget, const SDLoc &DL,
3233 EVT VT, SDValue Passthru, SDValue Op, SDValue Offset, SDValue Mask,
3234 SDValue VL,
3236 if (Passthru.isUndef())
3238 SDValue PolicyOp = DAG.getTargetConstant(Policy, DL, Subtarget.getXLenVT());
3239 SDValue Ops[] = {Passthru, Op, Offset, Mask, VL, PolicyOp};
3240 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VT, Ops);
3241}
3242
3243static MVT getLMUL1VT(MVT VT) {
3245 "Unexpected vector MVT");
3249}
3250
3254 int64_t Addend;
3255};
3256
3257static std::optional<APInt> getExactInteger(const APFloat &APF,
3259 // We will use a SINT_TO_FP to materialize this constant so we should use a
3260 // signed APSInt here.
3261 APSInt ValInt(BitWidth, /*IsUnsigned*/ false);
3262 // We use an arbitrary rounding mode here. If a floating-point is an exact
3263 // integer (e.g., 1.0), the rounding mode does not affect the output value. If
3264 // the rounding mode changes the output value, then it is not an exact
3265 // integer.
3267 bool IsExact;
3268 // If it is out of signed integer range, it will return an invalid operation.
3269 // If it is not an exact integer, IsExact is false.
3270 if ((APF.convertToInteger(ValInt, ArbitraryRM, &IsExact) ==
3272 !IsExact)
3273 return std::nullopt;
3274 return ValInt.extractBits(BitWidth, 0);
3275}
3276
3277// Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
3278// to the (non-zero) step S and start value X. This can be then lowered as the
3279// RVV sequence (VID * S) + X, for example.
3280// The step S is represented as an integer numerator divided by a positive
3281// denominator. Note that the implementation currently only identifies
3282// sequences in which either the numerator is +/- 1 or the denominator is 1. It
3283// cannot detect 2/3, for example.
3284// Note that this method will also match potentially unappealing index
3285// sequences, like <i32 0, i32 50939494>, however it is left to the caller to
3286// determine whether this is worth generating code for.
3287//
3288// EltSizeInBits is the size of the type that the sequence will be calculated
3289// in, i.e. SEW for build_vectors or XLEN for address calculations.
3290static std::optional<VIDSequence> isSimpleVIDSequence(SDValue Op,
3291 unsigned EltSizeInBits) {
3292 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
3293 if (!cast<BuildVectorSDNode>(Op)->isConstant())
3294 return std::nullopt;
3295 bool IsInteger = Op.getValueType().isInteger();
3296
3297 std::optional<unsigned> SeqStepDenom;
3298 std::optional<APInt> SeqStepNum;
3299 std::optional<APInt> SeqAddend;
3300 std::optional<std::pair<APInt, unsigned>> PrevElt;
3301 assert(EltSizeInBits >= Op.getValueType().getScalarSizeInBits());
3302
3303 // First extract the ops into a list of constant integer values. This may not
3304 // be possible for floats if they're not all representable as integers.
3306 const unsigned OpSize = Op.getScalarValueSizeInBits();
3307 for (auto [Idx, Elt] : enumerate(Op->op_values())) {
3308 if (Elt.isUndef()) {
3309 Elts[Idx] = std::nullopt;
3310 continue;
3311 }
3312 if (IsInteger) {
3313 Elts[Idx] = Elt->getAsAPIntVal().trunc(OpSize).zext(EltSizeInBits);
3314 } else {
3315 auto ExactInteger =
3316 getExactInteger(cast<ConstantFPSDNode>(Elt)->getValueAPF(), OpSize);
3317 if (!ExactInteger)
3318 return std::nullopt;
3319 Elts[Idx] = *ExactInteger;
3320 }
3321 }
3322
3323 for (auto [Idx, Elt] : enumerate(Elts)) {
3324 // Assume undef elements match the sequence; we just have to be careful
3325 // when interpolating across them.
3326 if (!Elt)
3327 continue;
3328
3329 if (PrevElt) {
3330 // Calculate the step since the last non-undef element, and ensure
3331 // it's consistent across the entire sequence.
3332 unsigned IdxDiff = Idx - PrevElt->second;
3333 APInt ValDiff = *Elt - PrevElt->first;
3334
3335 // A zero-value value difference means that we're somewhere in the middle
3336 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
3337 // step change before evaluating the sequence.
3338 if (ValDiff == 0)
3339 continue;
3340
3341 int64_t Remainder = ValDiff.srem(IdxDiff);
3342 // Normalize the step if it's greater than 1.
3343 if (Remainder != ValDiff.getSExtValue()) {
3344 // The difference must cleanly divide the element span.
3345 if (Remainder != 0)
3346 return std::nullopt;
3347 ValDiff = ValDiff.sdiv(IdxDiff);
3348 IdxDiff = 1;
3349 }
3350
3351 if (!SeqStepNum)
3352 SeqStepNum = ValDiff;
3353 else if (ValDiff != SeqStepNum)
3354 return std::nullopt;
3355
3356 if (!SeqStepDenom)
3357 SeqStepDenom = IdxDiff;
3358 else if (IdxDiff != *SeqStepDenom)
3359 return std::nullopt;
3360 }
3361
3362 // Record this non-undef element for later.
3363 if (!PrevElt || PrevElt->first != *Elt)
3364 PrevElt = std::make_pair(*Elt, Idx);
3365 }
3366
3367 // We need to have logged a step for this to count as a legal index sequence.
3368 if (!SeqStepNum || !SeqStepDenom)
3369 return std::nullopt;
3370
3371 // Loop back through the sequence and validate elements we might have skipped
3372 // while waiting for a valid step. While doing this, log any sequence addend.
3373 for (auto [Idx, Elt] : enumerate(Elts)) {
3374 if (!Elt)
3375 continue;
3376 APInt ExpectedVal =
3377 (APInt(EltSizeInBits, Idx) * *SeqStepNum).sdiv(*SeqStepDenom);
3378
3379 APInt Addend = *Elt - ExpectedVal;
3380 if (!SeqAddend)
3381 SeqAddend = Addend;
3382 else if (Addend != SeqAddend)
3383 return std::nullopt;
3384 }
3385
3386 assert(SeqAddend && "Must have an addend if we have a step");
3387
3388 return VIDSequence{SeqStepNum->getSExtValue(), *SeqStepDenom,
3389 SeqAddend->getSExtValue()};
3390}
3391
3392// Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
3393// and lower it as a VRGATHER_VX_VL from the source vector.
3394static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
3395 SelectionDAG &DAG,
3396 const RISCVSubtarget &Subtarget) {
3397 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
3398 return SDValue();
3399 SDValue Vec = SplatVal.getOperand(0);
3400 // Only perform this optimization on vectors of the same size for simplicity.
3401 // Don't perform this optimization for i1 vectors.
3402 // FIXME: Support i1 vectors, maybe by promoting to i8?
3403 if (Vec.getValueType() != VT || VT.getVectorElementType() == MVT::i1)
3404 return SDValue();
3405 SDValue Idx = SplatVal.getOperand(1);
3406 // The index must be a legal type.
3407 if (Idx.getValueType() != Subtarget.getXLenVT())
3408 return SDValue();
3409
3410 MVT ContainerVT = VT;
3411 if (VT.isFixedLengthVector()) {
3412 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
3413 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3414 }
3415
3416 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3417
3418 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
3419 Idx, DAG.getUNDEF(ContainerVT), Mask, VL);
3420
3421 if (!VT.isFixedLengthVector())
3422 return Gather;
3423
3424 return convertFromScalableVector(VT, Gather, DAG, Subtarget);
3425}
3426
3427
3428/// Try and optimize BUILD_VECTORs with "dominant values" - these are values
3429/// which constitute a large proportion of the elements. In such cases we can
3430/// splat a vector with the dominant element and make up the shortfall with
3431/// INSERT_VECTOR_ELTs. Returns SDValue if not profitable.
3432/// Note that this includes vectors of 2 elements by association. The
3433/// upper-most element is the "dominant" one, allowing us to use a splat to
3434/// "insert" the upper element, and an insert of the lower element at position
3435/// 0, which improves codegen.
3437 const RISCVSubtarget &Subtarget) {
3438 MVT VT = Op.getSimpleValueType();
3439 assert(VT.isFixedLengthVector() && "Unexpected vector!");
3440
3441 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
3442
3443 SDLoc DL(Op);
3444 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3445
3446 MVT XLenVT = Subtarget.getXLenVT();
3447 unsigned NumElts = Op.getNumOperands();
3448
3449 SDValue DominantValue;
3450 unsigned MostCommonCount = 0;
3451 DenseMap<SDValue, unsigned> ValueCounts;
3452 unsigned NumUndefElts =
3453 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
3454
3455 // Track the number of scalar loads we know we'd be inserting, estimated as
3456 // any non-zero floating-point constant. Other kinds of element are either
3457 // already in registers or are materialized on demand. The threshold at which
3458 // a vector load is more desirable than several scalar materializion and
3459 // vector-insertion instructions is not known.
3460 unsigned NumScalarLoads = 0;
3461
3462 for (SDValue V : Op->op_values()) {
3463 if (V.isUndef())
3464 continue;
3465
3466 ValueCounts.insert(std::make_pair(V, 0));
3467 unsigned &Count = ValueCounts[V];
3468 if (0 == Count)
3469 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
3470 NumScalarLoads += !CFP->isExactlyValue(+0.0);
3471
3472 // Is this value dominant? In case of a tie, prefer the highest element as
3473 // it's cheaper to insert near the beginning of a vector than it is at the
3474 // end.
3475 if (++Count >= MostCommonCount) {
3476 DominantValue = V;
3477 MostCommonCount = Count;
3478 }
3479 }
3480
3481 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
3482 unsigned NumDefElts = NumElts - NumUndefElts;
3483 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
3484
3485 // Don't perform this optimization when optimizing for size, since
3486 // materializing elements and inserting them tends to cause code bloat.
3487 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
3488 (NumElts != 2 || ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) &&
3489 ((MostCommonCount > DominantValueCountThreshold) ||
3490 (ValueCounts.size() <= Log2_32(NumDefElts)))) {
3491 // Start by splatting the most common element.
3492 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
3493
3494 DenseSet<SDValue> Processed{DominantValue};
3495
3496 // We can handle an insert into the last element (of a splat) via
3497 // v(f)slide1down. This is slightly better than the vslideup insert
3498 // lowering as it avoids the need for a vector group temporary. It
3499 // is also better than using vmerge.vx as it avoids the need to
3500 // materialize the mask in a vector register.
3501 if (SDValue LastOp = Op->getOperand(Op->getNumOperands() - 1);
3502 !LastOp.isUndef() && ValueCounts[LastOp] == 1 &&
3503 LastOp != DominantValue) {
3504 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3505 auto OpCode =
3507 if (!VT.isFloatingPoint())
3508 LastOp = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, LastOp);
3509 Vec = DAG.getNode(OpCode, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Vec,
3510 LastOp, Mask, VL);
3511 Vec = convertFromScalableVector(VT, Vec, DAG, Subtarget);
3512 Processed.insert(LastOp);
3513 }
3514
3515 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
3516 for (const auto &OpIdx : enumerate(Op->ops())) {
3517 const SDValue &V = OpIdx.value();
3518 if (V.isUndef() || !Processed.insert(V).second)
3519 continue;
3520 if (ValueCounts[V] == 1) {
3521 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
3522 DAG.getVectorIdxConstant(OpIdx.index(), DL));
3523 } else {
3524 // Blend in all instances of this value using a VSELECT, using a
3525 // mask where each bit signals whether that element is the one
3526 // we're after.
3528 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
3529 return DAG.getConstant(V == V1, DL, XLenVT);
3530 });
3531 Vec = DAG.getNode(ISD::VSELECT, DL, VT,
3532 DAG.getBuildVector(SelMaskTy, DL, Ops),
3533 DAG.getSplatBuildVector(VT, DL, V), Vec);
3534 }
3535 }
3536
3537 return Vec;
3538 }
3539
3540 return SDValue();
3541}
3542
3544 const RISCVSubtarget &Subtarget) {
3545 MVT VT = Op.getSimpleValueType();
3546 assert(VT.isFixedLengthVector() && "Unexpected vector!");
3547
3548 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
3549
3550 SDLoc DL(Op);
3551 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3552
3553 MVT XLenVT = Subtarget.getXLenVT();
3554 unsigned NumElts = Op.getNumOperands();
3555
3556 if (VT.getVectorElementType() == MVT::i1) {
3557 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
3558 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
3559 return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
3560 }
3561
3562 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
3563 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
3564 return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
3565 }
3566
3567 // Lower constant mask BUILD_VECTORs via an integer vector type, in
3568 // scalar integer chunks whose bit-width depends on the number of mask
3569 // bits and XLEN.
3570 // First, determine the most appropriate scalar integer type to use. This
3571 // is at most XLenVT, but may be shrunk to a smaller vector element type
3572 // according to the size of the final vector - use i8 chunks rather than
3573 // XLenVT if we're producing a v8i1. This results in more consistent
3574 // codegen across RV32 and RV64.
3575 unsigned NumViaIntegerBits = std::clamp(NumElts, 8u, Subtarget.getXLen());
3576 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELen());
3577 // If we have to use more than one INSERT_VECTOR_ELT then this
3578 // optimization is likely to increase code size; avoid peforming it in
3579 // such a case. We can use a load from a constant pool in this case.
3580 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
3581 return SDValue();
3582 // Now we can create our integer vector type. Note that it may be larger
3583 // than the resulting mask type: v4i1 would use v1i8 as its integer type.
3584 unsigned IntegerViaVecElts = divideCeil(NumElts, NumViaIntegerBits);
3585 MVT IntegerViaVecVT =
3586 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
3587 IntegerViaVecElts);
3588
3589 uint64_t Bits = 0;
3590 unsigned BitPos = 0, IntegerEltIdx = 0;
3591 SmallVector<SDValue, 8> Elts(IntegerViaVecElts);
3592
3593 for (unsigned I = 0; I < NumElts;) {
3594 SDValue V = Op.getOperand(I);
3595 bool BitValue = !V.isUndef() && V->getAsZExtVal();
3596 Bits |= ((uint64_t)BitValue << BitPos);
3597 ++BitPos;
3598 ++I;
3599
3600 // Once we accumulate enough bits to fill our scalar type or process the
3601 // last element, insert into our vector and clear our accumulated data.
3602 if (I % NumViaIntegerBits == 0 || I == NumElts) {
3603 if (NumViaIntegerBits <= 32)
3604 Bits = SignExtend64<32>(Bits);
3605 SDValue Elt = DAG.getSignedConstant(Bits, DL, XLenVT);
3606 Elts[IntegerEltIdx] = Elt;
3607 Bits = 0;
3608 BitPos = 0;
3609 IntegerEltIdx++;
3610 }
3611 }
3612
3613 SDValue Vec = DAG.getBuildVector(IntegerViaVecVT, DL, Elts);
3614
3615 if (NumElts < NumViaIntegerBits) {
3616 // If we're producing a smaller vector than our minimum legal integer
3617 // type, bitcast to the equivalent (known-legal) mask type, and extract
3618 // our final mask.
3619 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
3620 Vec = DAG.getBitcast(MVT::v8i1, Vec);
3621 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
3622 DAG.getConstant(0, DL, XLenVT));
3623 } else {
3624 // Else we must have produced an integer type with the same size as the
3625 // mask type; bitcast for the final result.
3626 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
3627 Vec = DAG.getBitcast(VT, Vec);
3628 }
3629
3630 return Vec;
3631 }
3632
3633 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
3634 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
3636 if (!VT.isFloatingPoint())
3637 Splat = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Splat);
3638 Splat =
3639 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
3640 return convertFromScalableVector(VT, Splat, DAG, Subtarget);
3641 }
3642
3643 // Try and match index sequences, which we can lower to the vid instruction
3644 // with optional modifications. An all-undef vector is matched by
3645 // getSplatValue, above.
3646 if (auto SimpleVID = isSimpleVIDSequence(Op, Op.getScalarValueSizeInBits())) {
3647 int64_t StepNumerator = SimpleVID->StepNumerator;
3648 unsigned StepDenominator = SimpleVID->StepDenominator;
3649 int64_t Addend = SimpleVID->Addend;
3650
3651 assert(StepNumerator != 0 && "Invalid step");
3652 bool Negate = false;
3653 int64_t SplatStepVal = StepNumerator;
3654 unsigned StepOpcode = ISD::MUL;
3655 // Exclude INT64_MIN to avoid passing it to std::abs. We won't optimize it
3656 // anyway as the shift of 63 won't fit in uimm5.
3657 if (StepNumerator != 1 && StepNumerator != INT64_MIN &&
3658 isPowerOf2_64(std::abs(StepNumerator))) {
3659 Negate = StepNumerator < 0;
3660 StepOpcode = ISD::SHL;
3661 SplatStepVal = Log2_64(std::abs(StepNumerator));
3662 }
3663
3664 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
3665 // threshold since it's the immediate value many RVV instructions accept.
3666 // There is no vmul.vi instruction so ensure multiply constant can fit in
3667 // a single addi instruction.
3668 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
3669 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
3670 isPowerOf2_32(StepDenominator) &&
3671 (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) {
3672 MVT VIDVT =
3674 MVT VIDContainerVT =
3675 getContainerForFixedLengthVector(DAG, VIDVT, Subtarget);
3676 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VIDContainerVT, Mask, VL);
3677 // Convert right out of the scalable type so we can use standard ISD
3678 // nodes for the rest of the computation. If we used scalable types with
3679 // these, we'd lose the fixed-length vector info and generate worse
3680 // vsetvli code.
3681 VID = convertFromScalableVector(VIDVT, VID, DAG, Subtarget);
3682 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
3683 (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
3684 SDValue SplatStep = DAG.getSignedConstant(SplatStepVal, DL, VIDVT);
3685 VID = DAG.getNode(StepOpcode, DL, VIDVT, VID, SplatStep);
3686 }
3687 if (StepDenominator != 1) {
3688 SDValue SplatStep =
3689 DAG.getConstant(Log2_64(StepDenominator), DL, VIDVT);
3690 VID = DAG.getNode(ISD::SRL, DL, VIDVT, VID, SplatStep);
3691 }
3692 if (Addend != 0 || Negate) {
3693 SDValue SplatAddend = DAG.getSignedConstant(Addend, DL, VIDVT);
3694 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VIDVT, SplatAddend,
3695 VID);
3696 }
3697 if (VT.isFloatingPoint()) {
3698 // TODO: Use vfwcvt to reduce register pressure.
3699 VID = DAG.getNode(ISD::SINT_TO_FP, DL, VT, VID);
3700 }
3701 return VID;
3702 }
3703 }
3704
3705 // For very small build_vectors, use a single scalar insert of a constant.
3706 // TODO: Base this on constant rematerialization cost, not size.
3707 const unsigned EltBitSize = VT.getScalarSizeInBits();
3708 if (VT.getSizeInBits() <= 32 &&
3710 MVT ViaIntVT = MVT::getIntegerVT(VT.getSizeInBits());
3711 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32) &&
3712 "Unexpected sequence type");
3713 // If we can use the original VL with the modified element type, this
3714 // means we only have a VTYPE toggle, not a VL toggle. TODO: Should this
3715 // be moved into InsertVSETVLI?
3716 unsigned ViaVecLen =
3717 (Subtarget.getRealMinVLen() >= VT.getSizeInBits() * NumElts) ? NumElts : 1;
3718 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, ViaVecLen);
3719
3720 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
3721 uint64_t SplatValue = 0;
3722 // Construct the amalgamated value at this larger vector type.
3723 for (const auto &OpIdx : enumerate(Op->op_values())) {
3724 const auto &SeqV = OpIdx.value();
3725 if (!SeqV.isUndef())
3726 SplatValue |=
3727 ((SeqV->getAsZExtVal() & EltMask) << (OpIdx.index() * EltBitSize));
3728 }
3729
3730 // On RV64, sign-extend from 32 to 64 bits where possible in order to
3731 // achieve better constant materializion.
3732 // On RV32, we need to sign-extend to use getSignedConstant.
3733 if (ViaIntVT == MVT::i32)
3734 SplatValue = SignExtend64<32>(SplatValue);
3735
3736 SDValue Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ViaVecVT,
3737 DAG.getUNDEF(ViaVecVT),
3738 DAG.getSignedConstant(SplatValue, DL, XLenVT),
3739 DAG.getVectorIdxConstant(0, DL));
3740 if (ViaVecLen != 1)
3742 MVT::getVectorVT(ViaIntVT, 1), Vec,
3743 DAG.getConstant(0, DL, XLenVT));
3744 return DAG.getBitcast(VT, Vec);
3745 }
3746
3747
3748 // Attempt to detect "hidden" splats, which only reveal themselves as splats
3749 // when re-interpreted as a vector with a larger element type. For example,
3750 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
3751 // could be instead splat as
3752 // v2i32 = build_vector i32 0x00010000, i32 0x00010000
3753 // TODO: This optimization could also work on non-constant splats, but it
3754 // would require bit-manipulation instructions to construct the splat value.
3755 SmallVector<SDValue> Sequence;
3756 const auto *BV = cast<BuildVectorSDNode>(Op);
3757 if (VT.isInteger() && EltBitSize < Subtarget.getELen() &&
3759 BV->getRepeatedSequence(Sequence) &&
3760 (Sequence.size() * EltBitSize) <= Subtarget.getELen()) {
3761 unsigned SeqLen = Sequence.size();
3762 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
3763 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
3764 ViaIntVT == MVT::i64) &&
3765 "Unexpected sequence type");
3766
3767 // If we can use the original VL with the modified element type, this
3768 // means we only have a VTYPE toggle, not a VL toggle. TODO: Should this
3769 // be moved into InsertVSETVLI?
3770 const unsigned RequiredVL = NumElts / SeqLen;
3771 const unsigned ViaVecLen =
3772 (Subtarget.getRealMinVLen() >= ViaIntVT.getSizeInBits() * NumElts) ?
3773 NumElts : RequiredVL;
3774 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, ViaVecLen);
3775
3776 unsigned EltIdx = 0;
3777 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
3778 uint64_t SplatValue = 0;
3779 // Construct the amalgamated value which can be splatted as this larger
3780 // vector type.
3781 for (const auto &SeqV : Sequence) {
3782 if (!SeqV.isUndef())
3783 SplatValue |=
3784 ((SeqV->getAsZExtVal() & EltMask) << (EltIdx * EltBitSize));
3785 EltIdx++;
3786 }
3787
3788 // On RV64, sign-extend from 32 to 64 bits where possible in order to
3789 // achieve better constant materializion.
3790 // On RV32, we need to sign-extend to use getSignedConstant.
3791 if (ViaIntVT == MVT::i32)
3792 SplatValue = SignExtend64<32>(SplatValue);
3793
3794 // Since we can't introduce illegal i64 types at this stage, we can only
3795 // perform an i64 splat on RV32 if it is its own sign-extended value. That
3796 // way we can use RVV instructions to splat.
3797 assert((ViaIntVT.bitsLE(XLenVT) ||
3798 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
3799 "Unexpected bitcast sequence");
3800 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
3801 SDValue ViaVL =
3802 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
3803 MVT ViaContainerVT =
3804 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
3805 SDValue Splat =
3806 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
3807 DAG.getUNDEF(ViaContainerVT),
3808 DAG.getSignedConstant(SplatValue, DL, XLenVT), ViaVL);
3809 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
3810 if (ViaVecLen != RequiredVL)
3812 MVT::getVectorVT(ViaIntVT, RequiredVL), Splat,
3813 DAG.getConstant(0, DL, XLenVT));
3814 return DAG.getBitcast(VT, Splat);
3815 }
3816 }
3817
3818 // If the number of signbits allows, see if we can lower as a <N x i8>.
3819 // Our main goal here is to reduce LMUL (and thus work) required to
3820 // build the constant, but we will also narrow if the resulting
3821 // narrow vector is known to materialize cheaply.
3822 // TODO: We really should be costing the smaller vector. There are
3823 // profitable cases this misses.
3824 if (EltBitSize > 8 && VT.isInteger() &&
3825 (NumElts <= 4 || VT.getSizeInBits() > Subtarget.getRealMinVLen()) &&
3826 DAG.ComputeMaxSignificantBits(Op) <= 8) {
3827 SDValue Source = DAG.getBuildVector(VT.changeVectorElementType(MVT::i8),
3828 DL, Op->ops());
3829 Source = convertToScalableVector(ContainerVT.changeVectorElementType(MVT::i8),
3830 Source, DAG, Subtarget);
3831 SDValue Res = DAG.getNode(RISCVISD::VSEXT_VL, DL, ContainerVT, Source, Mask, VL);
3832 return convertFromScalableVector(VT, Res, DAG, Subtarget);
3833 }
3834
3835 if (SDValue Res = lowerBuildVectorViaDominantValues(Op, DAG, Subtarget))
3836 return Res;
3837
3838 // For constant vectors, use generic constant pool lowering. Otherwise,
3839 // we'd have to materialize constants in GPRs just to move them into the
3840 // vector.
3841 return SDValue();
3842}
3843
3844static unsigned getPACKOpcode(unsigned DestBW,
3845 const RISCVSubtarget &Subtarget) {
3846 switch (DestBW) {
3847 default:
3848 llvm_unreachable("Unsupported pack size");
3849 case 16:
3850 return RISCV::PACKH;
3851 case 32:
3852 return Subtarget.is64Bit() ? RISCV::PACKW : RISCV::PACK;
3853 case 64:
3854 assert(Subtarget.is64Bit());
3855 return RISCV::PACK;
3856 }
3857}
3858
3859/// Double the element size of the build vector to reduce the number
3860/// of vslide1down in the build vector chain. In the worst case, this
3861/// trades three scalar operations for 1 vector operation. Scalar
3862/// operations are generally lower latency, and for out-of-order cores
3863/// we also benefit from additional parallelism.
3865 const RISCVSubtarget &Subtarget) {
3866 SDLoc DL(Op);
3867 MVT VT = Op.getSimpleValueType();
3868 assert(VT.isFixedLengthVector() && "Unexpected vector!");
3869 MVT ElemVT = VT.getVectorElementType();
3870 if (!ElemVT.isInteger())
3871 return SDValue();
3872
3873 // TODO: Relax these architectural restrictions, possibly with costing
3874 // of the actual instructions required.
3875 if (!Subtarget.hasStdExtZbb() || !Subtarget.hasStdExtZba())
3876 return SDValue();
3877
3878 unsigned NumElts = VT.getVectorNumElements();
3879 unsigned ElemSizeInBits = ElemVT.getSizeInBits();
3880 if (ElemSizeInBits >= std::min(Subtarget.getELen(), Subtarget.getXLen()) ||
3881 NumElts % 2 != 0)
3882 return SDValue();
3883
3884 // Produce [B,A] packed into a type twice as wide. Note that all
3885 // scalars are XLenVT, possibly masked (see below).
3886 MVT XLenVT = Subtarget.getXLenVT();
3887 SDValue Mask = DAG.getConstant(
3888 APInt::getLowBitsSet(XLenVT.getSizeInBits(), ElemSizeInBits), DL, XLenVT);
3889 auto pack = [&](SDValue A, SDValue B) {
3890 // Bias the scheduling of the inserted operations to near the
3891 // definition of the element - this tends to reduce register
3892 // pressure overall.
3893 SDLoc ElemDL(B);
3894 if (Subtarget.hasStdExtZbkb())
3895 // Note that we're relying on the high bits of the result being
3896 // don't care. For PACKW, the result is *sign* extended.
3897 return SDValue(
3898 DAG.getMachineNode(getPACKOpcode(ElemSizeInBits * 2, Subtarget),
3899 ElemDL, XLenVT, A, B),
3900 0);
3901
3902 A = DAG.getNode(ISD::AND, SDLoc(A), XLenVT, A, Mask);
3903 B = DAG.getNode(ISD::AND, SDLoc(B), XLenVT, B, Mask);
3904 SDValue ShtAmt = DAG.getConstant(ElemSizeInBits, ElemDL, XLenVT);
3905 SDNodeFlags Flags;
3906 Flags.setDisjoint(true);
3907 return DAG.getNode(ISD::OR, ElemDL, XLenVT, A,
3908 DAG.getNode(ISD::SHL, ElemDL, XLenVT, B, ShtAmt), Flags);
3909 };
3910
3911 SmallVector<SDValue> NewOperands;
3912 NewOperands.reserve(NumElts / 2);
3913 for (unsigned i = 0; i < VT.getVectorNumElements(); i += 2)
3914 NewOperands.push_back(pack(Op.getOperand(i), Op.getOperand(i + 1)));
3915 assert(NumElts == NewOperands.size() * 2);
3916 MVT WideVT = MVT::getIntegerVT(ElemSizeInBits * 2);
3917 MVT WideVecVT = MVT::getVectorVT(WideVT, NumElts / 2);
3918 return DAG.getNode(ISD::BITCAST, DL, VT,
3919 DAG.getBuildVector(WideVecVT, DL, NewOperands));
3920}
3921
3922// Convert to an vXf16 build_vector to vXi16 with bitcasts.
3924 MVT VT = Op.getSimpleValueType();
3925 MVT IVT = VT.changeVectorElementType(MVT::i16);
3927 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I)
3928 NewOps[I] = DAG.getBitcast(MVT::i16, Op.getOperand(I));
3929 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op), IVT, NewOps);
3930 return DAG.getBitcast(VT, Res);
3931}
3932
3934 const RISCVSubtarget &Subtarget) {
3935 MVT VT = Op.getSimpleValueType();
3936 assert(VT.isFixedLengthVector() && "Unexpected vector!");
3937
3938 // If we don't have scalar f16, we need to bitcast to an i16 vector.
3939 if (VT.getVectorElementType() == MVT::f16 &&
3940 !Subtarget.hasStdExtZfhmin())
3941 return lowerBUILD_VECTORvXf16(Op, DAG);
3942
3943 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
3945 return lowerBuildVectorOfConstants(Op, DAG, Subtarget);
3946
3947 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
3948
3949 SDLoc DL(Op);
3950 auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3951
3952 MVT XLenVT = Subtarget.getXLenVT();
3953
3954 if (VT.getVectorElementType() == MVT::i1) {
3955 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
3956 // vector type, we have a legal equivalently-sized i8 type, so we can use
3957 // that.
3958 MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
3959 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
3960
3961 SDValue WideVec;
3962 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
3963 // For a splat, perform a scalar truncate before creating the wider
3964 // vector.
3965 Splat = DAG.getNode(ISD::AND, DL, Splat.getValueType(), Splat,
3966 DAG.getConstant(1, DL, Splat.getValueType()));
3967 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
3968 } else {
3969 SmallVector<SDValue, 8> Ops(Op->op_values());
3970 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
3971 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
3972 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
3973 }
3974
3975 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
3976 }
3977
3978 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
3979 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
3980 return Gather;
3981 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
3983 if (!VT.isFloatingPoint())
3984 Splat = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Splat);
3985 Splat =
3986 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
3987 return convertFromScalableVector(VT, Splat, DAG, Subtarget);
3988 }
3989
3990 if (SDValue Res = lowerBuildVectorViaDominantValues(Op, DAG, Subtarget))
3991 return Res;
3992
3993 // If we're compiling for an exact VLEN value, we can split our work per
3994 // register in the register group.
3995 if (const auto VLen = Subtarget.getRealVLen();
3996 VLen && VT.getSizeInBits().getKnownMinValue() > *VLen) {
3997 MVT ElemVT = VT.getVectorElementType();
3998 unsigned ElemsPerVReg = *VLen / ElemVT.getFixedSizeInBits();
3999 EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
4000 MVT OneRegVT = MVT::getVectorVT(ElemVT, ElemsPerVReg);
4001 MVT M1VT = getContainerForFixedLengthVector(DAG, OneRegVT, Subtarget);
4002 assert(M1VT == getLMUL1VT(M1VT));
4003
4004 // The following semantically builds up a fixed length concat_vector
4005 // of the component build_vectors. We eagerly lower to scalable and
4006 // insert_subvector here to avoid DAG combining it back to a large
4007 // build_vector.
4008 SmallVector<SDValue> BuildVectorOps(Op->ops());
4009 unsigned NumOpElts = M1VT.getVectorMinNumElements();
4010 SDValue Vec = DAG.getUNDEF(ContainerVT);
4011 for (unsigned i = 0; i < VT.getVectorNumElements(); i += ElemsPerVReg) {
4012 auto OneVRegOfOps = ArrayRef(BuildVectorOps).slice(i, ElemsPerVReg);
4013 SDValue SubBV =
4014 DAG.getNode(ISD::BUILD_VECTOR, DL, OneRegVT, OneVRegOfOps);
4015 SubBV = convertToScalableVector(M1VT, SubBV, DAG, Subtarget);
4016 unsigned InsertIdx = (i / ElemsPerVReg) * NumOpElts;
4017 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, Vec, SubBV,
4018 DAG.getVectorIdxConstant(InsertIdx, DL));
4019 }
4020 return convertFromScalableVector(VT, Vec, DAG, Subtarget);
4021 }
4022
4023 // If we're about to resort to vslide1down (or stack usage), pack our
4024 // elements into the widest scalar type we can. This will force a VL/VTYPE
4025 // toggle, but reduces the critical path, the number of vslide1down ops
4026 // required, and possibly enables scalar folds of the values.
4027 if (SDValue Res = lowerBuildVectorViaPacking(Op, DAG, Subtarget))
4028 return Res;
4029
4030 // For m1 vectors, if we have non-undef values in both halves of our vector,
4031 // split the vector into low and high halves, build them separately, then
4032 // use a vselect to combine them. For long vectors, this cuts the critical
4033 // path of the vslide1down sequence in half, and gives us an opportunity
4034 // to special case each half independently. Note that we don't change the
4035 // length of the sub-vectors here, so if both fallback to the generic
4036 // vslide1down path, we should be able to fold the vselect into the final
4037 // vslidedown (for the undef tail) for the first half w/ masking.
4038 unsigned NumElts = VT.getVectorNumElements();
4039 unsigned NumUndefElts =
4040 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
4041 unsigned NumDefElts = NumElts - NumUndefElts;
4042 if (NumDefElts >= 8 && NumDefElts > NumElts / 2 &&
4043 ContainerVT.bitsLE(getLMUL1VT(ContainerVT))) {
4044 SmallVector<SDValue> SubVecAOps, SubVecBOps;
4045 SmallVector<SDValue> MaskVals;
4046 SDValue UndefElem = DAG.getUNDEF(Op->getOperand(0)->getValueType(0));
4047 SubVecAOps.reserve(NumElts);
4048 SubVecBOps.reserve(NumElts);
4049 for (unsigned i = 0; i < NumElts; i++) {
4050 SDValue Elem = Op->getOperand(i);
4051 if (i < NumElts / 2) {
4052 SubVecAOps.push_back(Elem);
4053 SubVecBOps.push_back(UndefElem);
4054 } else {
4055 SubVecAOps.push_back(UndefElem);
4056 SubVecBOps.push_back(Elem);
4057 }
4058 bool SelectMaskVal = (i < NumElts / 2);
4059 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
4060 }
4061 assert(SubVecAOps.size() == NumElts && SubVecBOps.size() == NumElts &&
4062 MaskVals.size() == NumElts);
4063
4064 SDValue SubVecA = DAG.getBuildVector(VT, DL, SubVecAOps);
4065 SDValue SubVecB = DAG.getBuildVector(VT, DL, SubVecBOps);
4066 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
4067 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
4068 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, SubVecA, SubVecB);
4069 }
4070
4071 // Cap the cost at a value linear to the number of elements in the vector.
4072 // The default lowering is to use the stack. The vector store + scalar loads
4073 // is linear in VL. However, at high lmuls vslide1down and vslidedown end up
4074 // being (at least) linear in LMUL. As a result, using the vslidedown
4075 // lowering for every element ends up being VL*LMUL..
4076 // TODO: Should we be directly costing the stack alternative? Doing so might
4077 // give us a more accurate upper bound.
4078 InstructionCost LinearBudget = VT.getVectorNumElements() * 2;
4079
4080 // TODO: unify with TTI getSlideCost.
4081 InstructionCost PerSlideCost = 1;
4082 switch (RISCVTargetLowering::getLMUL(ContainerVT)) {
4083 default: break;
4085 PerSlideCost = 2;
4086 break;
4088 PerSlideCost = 4;
4089 break;
4091 PerSlideCost = 8;
4092 break;
4093 }
4094
4095 // TODO: Should we be using the build instseq then cost + evaluate scheme
4096 // we use for integer constants here?
4097 unsigned UndefCount = 0;
4098 for (const SDValue &V : Op->ops()) {
4099 if (V.isUndef()) {
4100 UndefCount++;
4101 continue;
4102 }
4103 if (UndefCount) {
4104 LinearBudget -= PerSlideCost;
4105 UndefCount = 0;
4106 }
4107 LinearBudget -= PerSlideCost;
4108 }
4109 if (UndefCount) {
4110 LinearBudget -= PerSlideCost;
4111 }
4112
4113 if (LinearBudget < 0)
4114 return SDValue();
4115
4116 assert((!VT.isFloatingPoint() ||
4117 VT.getVectorElementType().getSizeInBits() <= Subtarget.getFLen()) &&
4118 "Illegal type which will result in reserved encoding");
4119
4120 const unsigned Policy = RISCVII::TAIL_AGNOSTIC | RISCVII::MASK_AGNOSTIC;
4121
4122 SDValue Vec;
4123 UndefCount = 0;
4124 for (SDValue V : Op->ops()) {
4125 if (V.isUndef()) {
4126 UndefCount++;
4127 continue;
4128 }
4129
4130 // Start our sequence with a TA splat in the hopes that hardware is able to
4131 // recognize there's no dependency on the prior value of our temporary
4132 // register.
4133 if (!Vec) {
4134 Vec = DAG.getSplatVector(VT, DL, V);
4135 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4136 UndefCount = 0;
4137 continue;
4138 }
4139
4140 if (UndefCount) {
4141 const SDValue Offset = DAG.getConstant(UndefCount, DL, Subtarget.getXLenVT());
4142 Vec = getVSlidedown(DAG, Subtarget, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
4143 Vec, Offset, Mask, VL, Policy);
4144 UndefCount = 0;
4145 }
4146 auto OpCode =
4148 if (!VT.isFloatingPoint())
4149 V = DAG.getNode(ISD::ANY_EXTEND, DL, Subtarget.getXLenVT(), V);
4150 Vec = DAG.getNode(OpCode, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Vec,
4151 V, Mask, VL);
4152 }
4153 if (UndefCount) {
4154 const SDValue Offset = DAG.getConstant(UndefCount, DL, Subtarget.getXLenVT());
4155 Vec = getVSlidedown(DAG, Subtarget, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
4156 Vec, Offset, Mask, VL, Policy);
4157 }
4158 return convertFromScalableVector(VT, Vec, DAG, Subtarget);
4159}
4160
4161static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
4163 SelectionDAG &DAG) {
4164 if (!Passthru)
4165 Passthru = DAG.getUNDEF(VT);
4166 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4167 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4168 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4169 // If Hi constant is all the same sign bit as Lo, lower this as a custom
4170 // node in order to try and match RVV vector/scalar instructions.
4171 if ((LoC >> 31) == HiC)
4172 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
4173
4174 // If vl is equal to VLMAX or fits in 4 bits and Hi constant is equal to Lo,
4175 // we could use vmv.v.x whose EEW = 32 to lower it. This allows us to use
4176 // vlmax vsetvli or vsetivli to change the VL.
4177 // FIXME: Support larger constants?
4178 // FIXME: Support non-constant VLs by saturating?
4179 if (LoC == HiC) {
4180 SDValue NewVL;
4181 if (isAllOnesConstant(VL) ||
4182 (isa<RegisterSDNode>(VL) &&
4183 cast<RegisterSDNode>(VL)->getReg() == RISCV::X0))
4184 NewVL = DAG.getRegister(RISCV::X0, MVT::i32);
4185 else if (isa<ConstantSDNode>(VL) && isUInt<4>(VL->getAsZExtVal()))
4186 NewVL = DAG.getNode(ISD::ADD, DL, VL.getValueType(), VL, VL);
4187
4188 if (NewVL) {
4189 MVT InterVT =
4190 MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4191 auto InterVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterVT,
4192 DAG.getUNDEF(InterVT), Lo, NewVL);
4193 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
4194 }
4195 }
4196 }
4197
4198 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4199 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4200 isa<ConstantSDNode>(Hi.getOperand(1)) &&
4201 Hi.getConstantOperandVal(1) == 31)
4202 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
4203
4204 // If the hi bits of the splat are undefined, then it's fine to just splat Lo
4205 // even if it might be sign extended.
4206 if (Hi.isUndef())
4207 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
4208
4209 // Fall back to a stack store and stride x0 vector load.